diff --git "a/6355.jsonl" "b/6355.jsonl" new file mode 100644--- /dev/null +++ "b/6355.jsonl" @@ -0,0 +1,704 @@ +{"seq_id":"316772757","text":"# 3036 / calculate turn of each rings when first ring spin 1 cycle\ndef gcd(a, b):\n a, b = max(a, b), min(a, b)\n while True:\n a, b = b, a % b\n if b == 0:\n return a\n\n\nN = int(input())\nrings = list(map(int, input().split()))\nfor ring in rings[1:]:\n g = gcd(rings[0], ring)\n print(f'{rings[0] // g}/{ring // g}')\n","sub_path":"math/3036.py","file_name":"3036.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"354910288","text":"## 3. Populations and Samples ##\n\nquestion1 = 'population'\nquestion2 = 'population'\nquestion3 = 'sample'\nquestion4 = 'population'\nquestion5 = 'sample'\n\n## 4. Sampling Error ##\n\nimport pandas as pd\nwnba = pd.read_csv('wnba.csv')\nparameter = wnba['Games Played'].max()\nsample = wnba['Games Played'].sample(30, random_state = 1)\nstatistic = sample.max()\nsampling_error = parameter - statistic\n\n## 5. Simple Random Sampling ##\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nwnba = pd.read_csv('wnba.csv')\n\nsample = wnba.sample(100, random_state=1)\n\noutpls = []\n\nfor i in range(0,100):\n outpls.append(sample[\"PTS\"].sample(10, random_state=i).mean())\n\nplt.scatter(x=range(0,100),y=outpls)\nplt.axhline(wnba[\"PTS\"].mean())\n\n## 7. Stratified Sampling ##\n\nwnba[\"POINTS_PER_GAME\"] = wnba[\"PTS\"]/wnba[\"Games Played\"]\n\n# 5 Stratum\nwnba_F = wnba.loc[wnba[\"Pos\"]==\"F\"]\nwnba_GF = wnba.loc[wnba[\"Pos\"]==\"G/F\"]\nwnba_G = wnba.loc[wnba[\"Pos\"]==\"G\"]\nwnba_C = wnba.loc[wnba[\"Pos\"]==\"C\"]\nwnba_FC = wnba.loc[wnba[\"Pos\"]==\"F/C\"]\n\nstrata = [wnba_C,wnba_F,wnba_FC,wnba_GF,wnba_G]\n\nstrata_dict = {}\n\nfor stratum in strata:\n stratum_sample = stratum.sample(10, random_state=0)\n sample_mean = stratum_sample[\"POINTS_PER_GAME\"].mean()\n strata_dict[stratum[\"Pos\"].iloc[0]] = sample_mean\n\nposition_most_points = max(strata_dict, key=strata_dict.get)\n\n## 8. Proportional Stratified Sampling ##\n\nwnba_A = wnba.loc[wnba[\"Games Played\"]<=12]\nwnba_B = wnba.loc[(wnba[\"Games Played\"]>12) & (wnba[\"Games Played\"]<=22)]\nwnba_C = wnba.loc[wnba[\"Games Played\"]>22]\n\noutpls = []\n\nfor i in range(0,100):\n sample_a = wnba_A.sample(1,random_state=i)\n sample_b = wnba_B.sample(2,random_state=i)\n sample_c = wnba_C.sample(7,random_state=i)\n sample = pd.concat([sample_a,sample_b,sample_c])\n mean = sample[\"PTS\"].mean()\n outpls.append(mean)\n\nplt.scatter(x=range(0,100), y=outpls)\nplt.axhline(wnba[\"PTS\"].mean())\n \n\n## 10. Cluster Sampling ##\n\nteam_clusters = pd.Series(wnba[\"Team\"].unique()).sample(4, random_state=0)\nsampled_clusters = pd.DataFrame()\n\nfor team in team_clusters:\n sampled_clusters = pd.concat([sampled_clusters,wnba.loc[wnba[\"Team\"]==team]])\n\nsample_height_mean = sampled_clusters[\"Height\"].mean()\nsample_age_mean = sampled_clusters[\"Age\"].mean()\nsample_bmi_mean = sampled_clusters[\"BMI\"].mean()\nsample_points_mean = sampled_clusters[\"PTS\"].mean()\n\npop_height_mean = wnba[\"Height\"].mean()\npop_age_mean = wnba[\"Age\"].mean()\npop_bmi_mean = wnba[\"BMI\"].mean()\npop_points_mean = wnba[\"PTS\"].mean()\n\nsampling_error_height = pop_height_mean-sample_height_mean\nsampling_error_age = pop_age_mean-sample_age_mean\nsampling_error_BMI = pop_bmi_mean-sample_bmi_mean\nsampling_error_points = pop_points_mean-sample_points_mean\n","sub_path":"DataQuestArchive/statistics-fundamentals/Sampling-283.py","file_name":"Sampling-283.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"66792592","text":"from rohdeschwarz.instruments.vna.channel import Channel\n\ndef ports_used(self):\n result = []\n for t_name in self.traces:\n t = self._vna.trace(t_name)\n ports = t.test_ports()\n for i in ports:\n if not i in result:\n result.append(i)\n return sorted(result)\nChannel.ports_used = ports_used\n\nnothing = None\n","sub_path":"src/server/test_automation/commands/project/measurement/vna_patch.py","file_name":"vna_patch.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"386287169","text":"import pandas as pd\nimport copy\n\nfrom diagrams.base import *\n\nDATASET = DATASET_FOLDER + \"intersection-sizes-5-clique-snb-sf1.csv\"\n\ndata = pd.read_csv(DATASET, sep=\",\", comment=\"#\")\n\ndata[\"difference\"] = data[\"smallestIteratorBiggest\"] - data[\"total\"]\n\nprint(\"Total max: \", max(data[\"total\"]))\nprint(\"Smallest max: \", max(data[\"smallestIterator\"]))\nprint(\"Smallest with any (biggest) max: \", max(data[\"smallestIteratorBiggest\"]))\n\n\nproject = data[[\"total\"]]\na = project.plot.hist(histtype=\"stepfilled\", bins=list(range(0, 200, 1)), density=True, cumulative=True)\n\na.legend().remove()\nplt.xlabel(\"Size\")\n\nplt.tight_layout()\nplt.savefig(FIGURE_PATH + \"/intersections/total.png\")\nplt.show()\n\nproject = data[[\"smallestIterator\"]]\na = project.plot.hist(histtype=\"stepfilled\", bins=list(range(0, 200, 1)), density=True, cumulative=True)\n\na.legend().remove()\nplt.xlabel(\"Size\")\n\nplt.tight_layout()\nplt.savefig(FIGURE_PATH + \"/intersections/smallest.png\")\nplt.show()\n\n\nproject = data[[\"smallestIteratorBiggest\"]]\na = project.plot.hist(histtype=\"stepfilled\", bins=list(range(0, 200, 1)), density=True, cumulative=True)\n\na.legend().remove()\nplt.xlabel(\"Size\")\n\nplt.tight_layout()\nplt.savefig(FIGURE_PATH + \"/intersections/smallest-biggest.png\")\nplt.show()\n","sub_path":"diagrams/intersection-sizes.py","file_name":"intersection-sizes.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"35044615","text":"import numpy as np\r\nimport keras\r\nimport keras.backend as k\r\nfrom keras.layers import Conv2D,MaxPooling2D,SpatialDropout2D,Flatten,Dropout,Dense\r\nfrom keras.models import Sequential,load_model\r\nfrom keras.optimizers import adam\r\nfrom keras.preprocessing import image\r\nimport cv2\r\nimport datetime\r\nimport time\r\nimport cv2\r\nimport os\r\nimport smtplib\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.image import MIMEImage\r\nfrom email.mime.multipart import MIMEMultipart\r\nimport datetime\r\nimport smtplib\r\nimport time\r\n\r\n\r\nmymodel=load_model('mymodel.h5')\r\n\r\ncap=cv2.VideoCapture(0)\r\nface_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\r\n\r\nfrom_email_addr = 'USERNAME'\r\nfrom_email_password = \"Password\"\r\nto_email_addr = 'TO_MAIL'\r\n\r\nimg_counter = 0\r\n\r\n\r\nwhile cap.isOpened():\r\n _,img=cap.read()\r\n face=face_cascade.detectMultiScale(img,scaleFactor=1.1,minNeighbors=4)\r\n for(x,y,w,h) in face:\r\n face_img = img[y:y+h, x:x+w]\r\n cv2.imwrite('temp.jpg',face_img)\r\n test_image=image.load_img('temp.jpg',target_size=(150,150,3))\r\n test_image=image.img_to_array(test_image)\r\n test_image=np.expand_dims(test_image,axis=0)\r\n pred=mymodel.predict_classes(test_image)[0][0]\r\n if pred==1:\r\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,0,255),3)\r\n cv2.putText(img,'NO MASK',((x+w)//2,y+h+20),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),3)\r\n else:\r\n cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),3)\r\n cv2.putText(img,'MASK',((x+w)//2,y+h+20),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,0),3)\r\n datet=str(datetime.datetime.now())\r\n cv2.putText(img,datet,(400,450),cv2.FONT_HERSHEY_SIMPLEX,0.5,(255,255,255),1)\r\n\r\n if pred==1:\r\n time.sleep(3)\r\n img_name = \"opencv_frame_{}.png\".format(img_counter)\r\n cv2.imwrite(img_name, img)\r\n print(\"{} written!\".format(img_name))\r\n img_counter += 1\r\n\r\n # Message\r\n msg = MIMEMultipart()\r\n msg['Subject'] = 'No masks! This is automated email' + datetime.datetime.now().strftime('%Y-%m-%d%H:%M:%S')\r\n msg['From'] = from_email_addr\r\n msg['To'] = to_email_addr\r\n\r\n File = open(img_name, 'rb')\r\n img1 = MIMEImage(File.read())\r\n File.close()\r\n msg.attach(img1)\r\n print(\"attach successful\")\r\n\r\n # send Mail\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.starttls()\r\n server.login(from_email_addr, from_email_password)\r\n server.sendmail(from_email_addr, to_email_addr, msg.as_string())\r\n server.quit()\r\n print('Email sent')\r\n \r\n cv2.imshow('img',img)\r\n \r\n if cv2.waitKey(1)==ord('q'):\r\n break\r\n \r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","sub_path":"facemask.py","file_name":"facemask.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"391045860","text":"import socket\nimport time\nimport unittest\n\nfrom appium import webdriver\n\nAPPIUM_SERVER_HOST = '127.0.0.1'\nAPPIUM_SERVER_PORT = 4723\n\nclass SimpleAndroidUITests(unittest.TestCase):\n\n def setUp(self):\n desired_caps = {\n 'platformName': 'Android',\n 'deviceName': 'Android Emulator',\n 'automationName': 'UIAutomator2',\n 'app': '/root/tmp/sample_apk_debug.apk',\n 'browserName': 'android',\n 'remoteAppsCacheLimit': 0,\n 'appWaitDuration': 120000,\n 'adbExecTimeout': 300000,\n 'androidInstallTimeout': 300000,\n # UIAutomator2 Only\n 'uiautomator2ServerLaunchTimeout': 120000,\n 'uiautomator2ServerInstallTimeout': 300000,\n }\n self.driver = webdriver.Remote(\n 'http://{}:{}/wd/hub'.format(APPIUM_SERVER_HOST, APPIUM_SERVER_PORT),\n desired_caps)\n\n def tearDown(self):\n self.driver.quit()\n\n def test_calculation(self):\n text_fields = self.driver.find_elements_by_class_name('android.widget.EditText')\n text_fields[0].send_keys(4)\n text_fields[1].send_keys(6)\n\n btn_calculate = self.driver.find_element_by_class_name('android.widget.Button')\n btn_calculate.click()\n\n self.assertEqual('10', text_fields[2].text)\n\n\nif __name__ == '__main__':\n time.sleep(15)\n suite = unittest.TestLoader().loadTestsFromTestCase(SimpleAndroidUITests)\n unittest.TextTestRunner(verbosity=2).run(suite)\n","sub_path":"app_simple.py","file_name":"app_simple.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"115557985","text":"from django.shortcuts import render\nfrom quiz.models import Quiz\nfrom django.shortcuts import redirect\n\ndef start(request):\n context = {\n \"quizzes\": Quiz.objects.all(),\n }\n return render(request, \"quiz/start.html\", context)\n\ndef quiz(request, quiz_number):\n context = {\n \"quiz\": Quiz.objects.get(quiz_number=quiz_number),\n \"quiz_number\": quiz_number,\n }\n return render(request, \"quiz/quiz.html\", context)\n\ndef question(request, quiz_number, question_number):\n quiz = Quiz.objects.get(quiz_number=quiz_number)\n questions = quiz.questions.all()\n question = questions[int(question_number) - 1]\n islastpage = False,\n num_questions = quiz.questions.count()\n if int(question_number) == num_questions:\n islastpage = True\n context = {\n \"question_number\": question_number,\n \"question\": question.question,\n \"answer1\": question.answer1,\n \"answer2\": question.answer2,\n \"answer3\": question.answer3,\n \"answer4\": question.answer4,\n \"answer5\": question.answer5,\n \"answer6\": question.answer6,\n \"answer7\": question.answer7,\n \"answer8\": question.answer8,\n \"answer9\": question.answer9,\n \"answer10\": question.answer10,\n \"answer11\": question.answer11,\n \"answer12\": question.answer12,\n \"answer13\": question.answer13,\n \"answer14\": question.answer14,\n \"answer15\": question.answer15,\n \"answer16\": question.answer16,\n \"answer17\": question.answer17,\n \"answer18\": question.answer18,\n \"answer19\": question.answer19,\n \"answer20\": question.answer20,\n \"islastpage\": islastpage,\n \"quiz\": quiz,\n \"quiz_number\": quiz_number,\n \"islastpage\": islastpage,\n }\n return render(request, \"quiz/question.html\", context)\n\ndef answer(request, quiz_number, question_number):\n saved_answers = request.session.get(quiz_number, {})\n answer = int(request.POST[\"answer\"])\n saved_answers[question_number] = answer\n request.session[quiz_number] = saved_answers\n\n question_number = int(question_number)\n quiz = Quiz.objects.get(quiz_number=quiz_number)\n num_questions = quiz.questions.count()\n num_correct_answers = 0\n if num_questions <= question_number:\n return redirect(\"results_page\", quiz_number)\n else:\n return redirect(\"question_page\", quiz_number, question_number + 1)\n\ndef results(request, quiz_number):\n quiz = Quiz.objects.get(quiz_number=quiz_number)\n questions = quiz.questions.all()\n saved_answers = request.session.get(quiz_number, {})\n num_correct_answers = 0\n for question_number, answer in saved_answers.items():\n correct_answer = questions[int(question_number) - 1].correct\n if correct_answer == answer:\n num_correct_answers += 1\n context = {\n \"correct\": num_correct_answers,\n \"total\": questions.count(),\n }\n return render(request, \"quiz/results.html\", context)","sub_path":"quiz/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"516763585","text":"from django.conf.urls import patterns, include, url\nfrom views import *\n\nurlpatterns = patterns('',\n\n (r'^update_worker$',update_worker_view),\n (r'^update_wishes$',update_wishes_view),\n\n (r'^activity/schedule$',schedule_view),\n (r'^activity/notification$',notification_view),\n (r'^activity/care$',care_view),\n (r'^activity/prepare$',prepare_view),\n\n\t\n (r'^impression/footprints$',footprints_view),\n (r'^impression/milestones$',milestones_view),\n \n (r'^alumni/activity$',activity_view),\n\n (r'^blessing$',blessing_view),\n )\n\n","sub_path":"wuhan/myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"257310366","text":"def fevrier_bissextile (jour_test,mois_test,annee_test) :\r\n return (jour_test<30 and mois_test==2 and ((annee_test%4==0 and annee_test%100!=0) or (annee_test%100==0 and annee_test%400==0)))\r\n\r\nmois_A_31=[1,3,5,7,8,10,12]\r\nmois_A_30=[4,6,9,11]\r\n\r\njour=int(input(\"Entrer le numéro de jour : \"))\r\nmois=int(input(\"Entrer numéro de mois : \"))\r\nannee=int(input(\"Entrer le numéro d'année : \"))\r\n\r\nif jour<29 and mois==2 :\r\n date_valide=True\r\nelif fevrier_bissextile(jour,mois,annee) :\r\n date_valide=True\r\nelif jour<31 and (mois in mois_A_30) :\r\n date_valide=True\r\nelif jour<32 and (mois in mois_A_31) :\r\n date_valide=True\r\nelse :\r\n date_valide=False\r\n\r\nif len(str(jour))==1 :\r\n jour_str=str(\"0\"+str(jour))\r\nelse :\r\n jour_str=str(jour)\r\n\r\nif len(str(mois))==1 :\r\n mois_str=str(\"0\"+str(mois))\r\n\r\nif date_valide :\r\n print(\"La date est le : \"+jour_str+\"/\"+mois_str+\"/\"+str(annee))\r\nelse :\r\n print(\"La date est invalide\")\r\n","sub_path":"Python Project/TD/Archive/Gabin/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"254024494","text":"\"\"\"Changed video_url to youtube_video_id\n\nRevision ID: 0e1602048751\nRevises: 354b3be98017\nCreate Date: 2019-04-22 16:54:16.175631\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '0e1602048751'\ndown_revision = '354b3be98017'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('fight', sa.Column('youtube_video_id', sa.String(length=200), nullable=False))\n op.drop_column('fight', 'video_url')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('fight', sa.Column('video_url', sa.VARCHAR(length=200), autoincrement=False, nullable=False))\n op.drop_column('fight', 'youtube_video_id')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/0e1602048751_changed_video_url_to_youtube_video_id.py","file_name":"0e1602048751_changed_video_url_to_youtube_video_id.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"487154114","text":"# This file is part of afw.\n#\n# Developed for the LSST Data Management System.\n# This product includes software developed by the LSST Project\n# (https://www.lsst.org).\n# See the COPYRIGHT file at the top-level directory of this distribution\n# for details of code ownership.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\n__all__ = [\"makeCameraFromPath\", \"makeCameraFromCatalogs\",\n \"makeDetector\", \"copyDetector\"]\n\nimport os.path\nimport lsst.geom\nfrom lsst.afw.table import AmpInfoCatalog\nfrom .cameraGeomLib import FOCAL_PLANE, FIELD_ANGLE, PIXELS, TAN_PIXELS, ACTUAL_PIXELS, CameraSys, \\\n Detector, DetectorType, Orientation, TransformMap\nfrom .camera import Camera\nfrom .makePixelToTanPixel import makePixelToTanPixel\nfrom .pupil import PupilFactory\n\ncameraSysList = [FIELD_ANGLE, FOCAL_PLANE, PIXELS, TAN_PIXELS, ACTUAL_PIXELS]\ncameraSysMap = dict((sys.getSysName(), sys) for sys in cameraSysList)\n\n\ndef makeDetectorData(detectorConfig, ampInfoCatalog, focalPlaneToField):\n \"\"\"Build a dictionary of Detector constructor keyword arguments.\n\n The returned dictionary can be passed as keyword arguments to the Detector\n constructor, providing all required arguments. However, using these\n arguments directly constructs a Detector with knowledge of only the\n coordinate systems that are *directly* mapped to its own PIXELS coordinate\n system. To construct Detectors with a shared TransformMap for the full\n Camera, use makeCameraFromCatalogs or makeCameraFromPath instead of\n calling this function or makeDetector directly.\n\n Parameters\n ----------\n detectorConfig : `lsst.pex.config.Config`\n Configuration for this detector.\n ampInfoCatalog : `lsst.afw.table.AmpInfoCatalog`\n amplifier information for this detector\n focalPlaneToField : `lsst.afw.geom.TransformPoint2ToPoint2`\n FOCAL_PLANE to FIELD_ANGLE Transform\n\n Returns\n -------\n data : `dict`\n Contains the following keys: name, id, type, serial, bbox, orientation,\n pixelSize, transforms, ampInfoCatalog, and optionally crosstalk.\n The transforms key is a dictionary whose values are Transforms that map\n the Detector's PIXEL coordinate system to the CameraSys in the key.\n \"\"\"\n\n data = dict(\n name=detectorConfig.name,\n id=detectorConfig.id,\n type=DetectorType(detectorConfig.detectorType),\n physicalType=detectorConfig.physicalType,\n serial=detectorConfig.serial,\n ampInfoCatalog=ampInfoCatalog,\n orientation=makeOrientation(detectorConfig),\n pixelSize=lsst.geom.Extent2D(detectorConfig.pixelSize_x, detectorConfig.pixelSize_y),\n bbox=lsst.geom.Box2I(\n minimum=lsst.geom.Point2I(detectorConfig.bbox_x0, detectorConfig.bbox_y0),\n maximum=lsst.geom.Point2I(detectorConfig.bbox_x1, detectorConfig.bbox_y1),\n ),\n )\n\n transforms = makeTransformDict(detectorConfig.transformDict.transforms)\n transforms[FOCAL_PLANE] = data[\"orientation\"].makePixelFpTransform(data[\"pixelSize\"])\n\n tanPixSys = CameraSys(TAN_PIXELS, detectorConfig.name)\n transforms[tanPixSys] = makePixelToTanPixel(\n bbox=data[\"bbox\"],\n orientation=data[\"orientation\"],\n focalPlaneToField=focalPlaneToField,\n pixelSizeMm=data[\"pixelSize\"],\n )\n\n data[\"transforms\"] = transforms\n\n crosstalk = detectorConfig.getCrosstalk(len(ampInfoCatalog))\n if crosstalk is not None:\n data[\"crosstalk\"] = crosstalk\n\n return data\n\n\ndef makeDetector(detectorConfig, ampInfoCatalog, focalPlaneToField):\n \"\"\"Make a Detector instance from a detector config and amp info catalog\n\n Parameters\n ----------\n detectorConfig : `lsst.pex.config.Config`\n Configuration for this detector.\n ampInfoCatalog : `lsst.afw.table.AmpInfoCatalog`\n amplifier information for this detector\n focalPlaneToField : `lsst.afw.geom.TransformPoint2ToPoint2`\n FOCAL_PLANE to FIELD_ANGLE Transform\n\n Returns\n -------\n detector : `lsst.afw.cameraGeom.Detector`\n New Detector instance.\n \"\"\"\n data = makeDetectorData(detectorConfig, ampInfoCatalog, focalPlaneToField)\n return Detector(**data)\n\n\ndef copyDetector(detector, ampInfoCatalog=None):\n \"\"\"Return a copy of a Detector with possibly-updated amplifier information.\n\n No deep copies are made; the input transformDict is used unmodified\n\n Parameters\n ----------\n detector : `lsst.afw.cameraGeom.Detector`\n The Detector to clone\n ampInfoCatalog The ampInfoCatalog to use; default use original\n\n Returns\n -------\n detector : `lsst.afw.cameraGeom.Detector`\n New Detector instance.\n \"\"\"\n if ampInfoCatalog is None:\n ampInfoCatalog = detector.getAmpInfoCatalog()\n\n return Detector(detector.getName(), detector.getId(), detector.getType(),\n detector.getSerial(), detector.getBBox(),\n ampInfoCatalog, detector.getOrientation(), detector.getPixelSize(),\n detector.getTransformMap(), detector.getCrosstalk(), detector.getPhysicalType())\n\n\ndef makeOrientation(detectorConfig):\n \"\"\"Make an Orientation instance from a detector config\n\n Parameters\n ----------\n detectorConfig : `lsst.pex.config.Config`\n Configuration for this detector.\n\n Returns\n -------\n orientation : `lsst.afw.cameraGeom.Orientation`\n Location and rotation of the Detector.\n \"\"\"\n offset = lsst.geom.Point2D(detectorConfig.offset_x, detectorConfig.offset_y)\n refPos = lsst.geom.Point2D(detectorConfig.refpos_x, detectorConfig.refpos_y)\n yaw = lsst.geom.Angle(detectorConfig.yawDeg, lsst.geom.degrees)\n pitch = lsst.geom.Angle(detectorConfig.pitchDeg, lsst.geom.degrees)\n roll = lsst.geom.Angle(detectorConfig.rollDeg, lsst.geom.degrees)\n return Orientation(offset, refPos, yaw, pitch, roll)\n\n\ndef makeTransformDict(transformConfigDict):\n \"\"\"Make a dictionary of CameraSys: lsst.afw.geom.Transform from a config dict.\n\n Parameters\n ----------\n transformConfigDict : value obtained from a `lsst.pex.config.ConfigDictField`\n registry; keys are camera system names.\n\n Returns\n -------\n transforms : `dict`\n A dict of CameraSys or CameraSysPrefix: lsst.afw.geom.Transform\n \"\"\"\n resMap = dict()\n if transformConfigDict is not None:\n for key in transformConfigDict:\n transform = transformConfigDict[key].transform.apply()\n resMap[CameraSys(key)] = transform\n return resMap\n\n\ndef makeCameraFromPath(cameraConfig, ampInfoPath, shortNameFunc,\n pupilFactoryClass=PupilFactory):\n \"\"\"Make a Camera instance from a directory of ampInfo files\n\n The directory must contain one ampInfo fits file for each detector in cameraConfig.detectorList.\n The name of each ampInfo file must be shortNameFunc(fullDetectorName) + \".fits\".\n\n Parameters\n ----------\n cameraConfig : `CameraConfig`\n Config describing camera and its detectors.\n ampInfoPath : `str`\n Path to ampInfo data files.\n shortNameFunc : callable\n A function that converts a long detector name to a short one.\n pupilFactoryClass : `type`, optional\n Class to attach to camera; default is `lsst.afw.cameraGeom.PupilFactory`.\n\n Returns\n -------\n camera : `lsst.afw.cameraGeom.Camera`\n New Camera instance.\n \"\"\"\n ampInfoCatDict = dict()\n for detectorConfig in cameraConfig.detectorList.values():\n shortName = shortNameFunc(detectorConfig.name)\n ampCatPath = os.path.join(ampInfoPath, shortName + \".fits\")\n ampInfoCatalog = AmpInfoCatalog.readFits(ampCatPath)\n ampInfoCatDict[detectorConfig.name] = ampInfoCatalog\n\n return makeCameraFromCatalogs(cameraConfig, ampInfoCatDict, pupilFactoryClass)\n\n\ndef makeCameraFromCatalogs(cameraConfig, ampInfoCatDict,\n pupilFactoryClass=PupilFactory):\n \"\"\"Construct a Camera instance from a dictionary of detector name: AmpInfoCatalog\n\n Parameters\n ----------\n cameraConfig : `CameraConfig`\n Config describing camera and its detectors.\n ampInfoCatDict : `dict`\n A dictionary of detector name: AmpInfoCatalog\n pupilFactoryClass : `type`, optional\n Class to attach to camera; `lsst.default afw.cameraGeom.PupilFactory`.\n\n Returns\n -------\n camera : `lsst.afw.cameraGeom.Camera`\n New Camera instance.\n \"\"\"\n nativeSys = cameraSysMap[cameraConfig.transformDict.nativeSys]\n\n # nativeSys=FOCAL_PLANE seems to be assumed in various places in this file\n # (e.g. the definition of TAN_PIXELS), despite CameraConfig providing the\n # illusion that it's configurable.\n # Note that we can't actually get rid of the nativeSys config option\n # without breaking lots of on-disk camera configs.\n assert nativeSys == FOCAL_PLANE, \"Cameras with nativeSys != FOCAL_PLANE are not supported.\"\n\n transformDict = makeTransformDict(cameraConfig.transformDict.transforms)\n focalPlaneToField = transformDict[FIELD_ANGLE]\n transformMapBuilder = TransformMap.Builder(nativeSys)\n transformMapBuilder.connect(transformDict)\n\n # First pass: build a list of all Detector ctor kwargs, minus the\n # transformMap (which needs information from all Detectors).\n detectorData = []\n for detectorConfig in cameraConfig.detectorList.values():\n\n # Get kwargs that could be used to construct each Detector\n # if we didn't care about giving each of them access to\n # all of the transforms.\n thisDetectorData = makeDetectorData(\n detectorConfig=detectorConfig,\n ampInfoCatalog=ampInfoCatDict[detectorConfig.name],\n focalPlaneToField=focalPlaneToField,\n )\n\n # Pull the transforms dictionary out of the data dict; we'll replace\n # it with a TransformMap argument later.\n thisDetectorTransforms = thisDetectorData.pop(\"transforms\")\n\n # Save the rest of the Detector data dictionary for later\n detectorData.append(thisDetectorData)\n\n # For reasons I don't understand, some obs_ packages (e.g. HSC) set\n # nativeSys to None for their detectors (which doesn't seem to be\n # permitted by the config class!), but they really mean PIXELS. For\n # backwards compatibility we use that as the default...\n detectorNativeSysPrefix = cameraSysMap.get(detectorConfig.transformDict.nativeSys, PIXELS)\n\n # ...well, actually, it seems that we've always assumed down in C++\n # that the answer is always PIXELS without ever checking that it is.\n # So let's assert that it is, since there are hints all over this file\n # (e.g. the definition of TAN_PIXELS) that other parts of the codebase\n # have regularly made that assumption as well. Note that we can't\n # actually get rid of the nativeSys config option without breaking\n # lots of on-disk camera configs.\n assert detectorNativeSysPrefix == PIXELS, \"Detectors with nativeSys != PIXELS are not supported.\"\n detectorNativeSys = CameraSys(detectorNativeSysPrefix, detectorConfig.name)\n\n # Add this detector's transform dict to the shared TransformMapBuilder\n transformMapBuilder.connect(detectorNativeSys, thisDetectorTransforms)\n\n # Now that we've collected all of the Transforms, we can finally build the\n # (immutable) TransformMap.\n transformMap = transformMapBuilder.build()\n\n # Second pass through the detectorConfigs: actually make Detector instances\n detectorList = [Detector(transformMap=transformMap, **kw) for kw in detectorData]\n\n return Camera(cameraConfig.name, detectorList, transformMap, pupilFactoryClass)\n","sub_path":"python/lsst/afw/cameraGeom/cameraFactory.py","file_name":"cameraFactory.py","file_ext":"py","file_size_in_byte":12324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"71705170","text":"# https://v1.tf.wiki/zh/basic.html\nimport os\nimport sys\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport pandas as pd\nimport numpy as np\nimport tensorflow as tf\ntf.enable_eager_execution()\n\n##########################################################################################\n\nX = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\ny = tf.constant([[10.0], [20.0]])\n\nclass Linear(tf.keras.Model):\n def __init__(self):\n #super().__init__()\n super(Linear, self).__init__()\n self.dense = tf.keras.layers.Dense(units=1, kernel_initializer=tf.zeros_initializer(),\n bias_initializer=tf.zeros_initializer())\n\n def call(self, input):\n output = self.dense(input)\n return output\n\n# 以下代码结构与前节类似\nmodel = Linear()\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)\n#for i in range(100):\nfor i in range(1):\n with tf.GradientTape() as tape:\n y_pred = model(X) # 调用模型\n loss = tf.reduce_mean(tf.square(y_pred - y))\n grads = tape.gradient(loss, model.variables)\n print('model.variables is ', model.variables)\n optimizer.apply_gradients(grads_and_vars=zip(grads, model.variables))\n\nprint(model.variables)\n\n##########################################################################################################\n\nclass DataLoader():\n def __init__(self):\n mnist = tf.contrib.learn.datasets.load_dataset(\"mnist\")\n self.train_data = mnist.train.images # np.array [55000, 784]\n self.train_labels = np.asarray(mnist.train.labels, dtype=np.int32) # np.array [55000] of int32\n self.eval_data = mnist.test.images # np.array [10000, 784]\n self.eval_labels = np.asarray(mnist.test.labels, dtype=np.int32) # np.array [10000] of int32\n\n def get_batch(self, batch_size):\n index = np.random.randint(0, np.shape(self.train_data)[0], batch_size)\n return self.train_data[index, :], self.train_labels[index]\n\n##########################################################################################################\n\nprint('prog ends here!')\n\n","sub_path":"tensorflow_example_2.py","file_name":"tensorflow_example_2.py","file_ext":"py","file_size_in_byte":2173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"296093166","text":"#!/usr/bin/env python3\n\n\"\"\"The influence of windowing of log. bandlimited sweep signals when using a\n Kaiser Window by fixing beta (=2) and fade_out (=0).\n fstart = 100 Hz\n fstop = 5000 Hz\n\n\"\"\"\n\n\nimport sys\nsys.path.append('..')\n\nimport measurement_chain\nimport plotting\nimport calculation\nimport generation\nimport matplotlib.pyplot as plt\nimport windows\nfrom scipy.signal import lfilter\nimport numpy as np\n\n\n# Parameters of the measuring system\n\nfs = 44100\n\nfstart = 100\nfstop = 5000\nduration = 1\npad = 4\n\n# Generate excitation signal\n\nexcitation = generation.log_sweep(fstart, fstop, duration, fs)\nN = len(excitation)\n\n\n# Noise in measurement chain\n\nnoise_level_db = -30\nnoise = measurement_chain.additive_noise(noise_level_db)\n\n# FIR-Filter-System\n\ndirac_system = measurement_chain.convolution([1.0])\n\n# Combinate system elements\n\nsystem = measurement_chain.chained(dirac_system, noise)\n\n# Spectrum of dirac for reference\n\ndirac = np.zeros(pad * fs)\ndirac[0] = 1\ndirac_f = np.fft.rfft(dirac)\n\n# Lists\nbeta = 7\nfade_in_list = np.arange(0, 1001, 1)\nfade_out = 0\n\n\ndef get_results(fade_in):\n excitation_windowed = excitation * windows.window_kaiser(N,\n fade_in,\n fade_out,\n fs, beta)\n excitation_windowed_zeropadded = generation.zero_padding(\n excitation_windowed, pad, fs)\n excitation_zeropadded = generation.zero_padding(excitation, pad, fs)\n system_response = system(excitation_windowed_zeropadded)\n ir = calculation.deconv_process(excitation_zeropadded,\n system_response,\n fs)\n return ir\n\n\nwith open(\"log_sweep_kaiser_window_bandlimited_script5_1.txt\", \"w\") as f:\n for fade_in in fade_in_list:\n ir = get_results(fade_in)\n pnr = calculation.pnr_db(ir[0], ir[1:4 * fs])\n spectrum_distance = calculation.vector_distance(\n dirac_f, np.fft.rfft(ir[:pad * fs]))\n f.write(\n str(fade_in) + \" \" + str(pnr) +\n \" \" + str(spectrum_distance) + \" \\n\")\n","sub_path":"log_sweep_kaiser_window_bandlimited_script5/log_sweep_kaiser_window_bandlimited_script5_1.py","file_name":"log_sweep_kaiser_window_bandlimited_script5_1.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628965729","text":"import dash\nfrom dash.dependencies import Input, Output, State\nimport dash_html_components as html\nimport dash_core_components as dcc\nimport dash_bootstrap_components as dbc\nfrom dash.dependencies import Input, Output, State, MATCH, ALL\nimport random\nfrom glob import glob\nimport json\nimport argparse\n# from create_start_state import reset_json_file\nimport random\nimport sys\nfrom time import perf_counter\nfrom datetime import date\nimport os\nimport signal\n\n\n\n\n\n\n\n\n\n# paths_of_images = glob('static/pool_Set/*.jpg')\npaths_of_images = glob('static/Test_Set/*.png')\n\nclass_of_all_images = [-1] * len(paths_of_images) # stores the class annotations of all the images by initialising -1.s\n\n# =========CLI Parsing===============\narg_container = argparse.ArgumentParser(description='Specify the Operating System')\n\n# should be optional arguments container.add_arguments\narg_container.add_argument('--is_os_win', '-Is_Operating_System_Windows', type=int, required=True,\n help='Is your OS Windows? (--os True) else False')\n\narg_container.add_argument('--initials', \"-Annotator's_name_initials\", type=str, required=True,\n help='example: if your name is Prateek Pani, type \"--initials pp\"')\n\nargs = arg_container.parse_args()\n# ====================================\n\n\ntoday = date.today()\nday, month, year = date.today().day, date.today().month, date.today().year\nname_initials = args.initials\n\nif args.is_os_win == 0:\n path = './StatsIO/{}/{}_{}_{}/session_num.json'.format(name_initials, day, month, year)\n my_file = open(path, \"r\")\n session_dict = json.loads(my_file.read()) \n session_num = session_dict['session_num'] \n\nelse:\n path = '.\\\\StatsIO\\\\{}\\\\{}_{}_{}\\\\session_num.json'.format(name_initials, day, month, year)\n my_file = open(path, \"r\")\n session_dict = json.loads(my_file.read()) \n session_num = session_dict['session_num'] \n\n\nprint(\"\\nsession_num\\n\",session_num)\n\n\ndef modify_session_file_for_the_day(session_num):\n today = date.today()\n day, month, year = date.today().day, date.today().month, date.today().year\n name_initials = args.initials\n\n if args.is_os_win == 0:\n path = './StatsIO/{}/{}_{}_{}/session_num.json'.format(name_initials, day, month, year)\n fp = open(path, \"w\")\n session_num += 1\n d = {'session_num': session_num}\n fp.write(json.dumps(d))\n\n else:\n path = '.\\\\StatsIO\\\\{}\\\\{}_{}_{}\\\\session_num.json'.format(name_initials, day, month, year)\n fp = open(path, \"w\")\n session_num += 1\n d = {'session_num': session_num}\n fp.write(json.dumps(d))\n\n\n\n\n\n\n\n# ===========global variables==========================\nunseen_idx_set = set({})\nunseen_idx_set_start = set({})\nunseen_idx_list = []\ngl_state_18 = []\ngl_current_18 = []\nstate_18 = []\ncurrent_18 = []\nbatch_start_time = 0\nbatch_end_time = 0\nglob_idx = [i for i in range(len(paths_of_images))]\ntime_logs = []\nplot_grid_session_iter_num = 0\n\n\n# ===========global variables==========================\n\n\ndef calculate_ann_time(batch_start_time, save_to_disk=False):\n global time_logs\n global session_num\n\n batch_end_time = perf_counter()\n time_elapsed = batch_end_time - batch_start_time\n time_logs.append(time_elapsed)\n\n if save_to_disk == True:\n if args.is_os_win == 0:\n path = './StatsIO/{}/{}_{}_{}'.format(name_initials, day, month, year)\n file_name = f\"time_logs_{session_num}.json\"\n fp = open(os.path.join(path, file_name), 'w')\n d = {'time_logs': time_logs}\n fp.write(json.dumps(d))\n else:\n path = '.\\\\StatsIO\\\\{}\\\\{}_{}_{}'.format(name_initials, day, month, year)\n file_name = f\"time_logs_{session_num}.json\"\n fp = open(os.path.join(path, file_name), 'w')\n d = {'time_logs': time_logs}\n fp.write(json.dumps(d))\n\n\n return batch_end_time, time_elapsed\n\n\ndef check_point():\n '''function reads the last_checkpoint file and returns the current iter_no'''\n with open(f'last_checkpoint_{args.initials}.txt') as lc:\n iter_no = lc.read()\n lc.close()\n iter_no = int(iter_no)\n return iter_no\n\n\niter_no = check_point()\nsess_start_iter_no = iter_no\nprint('New Session Resuming from iteration: {}'.format(iter_no))\n\n# =============create folder for a particular session per person per day============================\nname_initials = args.initials # Use this to make folders\ntoday = date.today()\nday, month, year = date.today().day, date.today().month, date.today().year\n\ndef create_folder(today, name_initials):\n '''Should create a folder if not present and if present print'''\n day, month, year = today.day, today.month, today.year\n if args.is_os_win == 0:\n path = './StatsIO/{}/{}_{}_{}'.format(name_initials, day, month, year)\n else:\n path = '.\\\\StatsIO\\\\{}\\\\{}_{}_{}'.format(name_initials, day, month, year)\n # os.makedirs(path)\n try:\n os.makedirs(path)\n print(\"Directory created successfully\")\n except OSError as error:\n print(\"Directory already present\")\n\n\ncreate_folder(today, str(name_initials))\n\n\n# =============xxxx particular session xxxx============================\n# jpg\n\n# data retrieval for states\ndef read_json(today):\n global class_of_all_images\n global paths_of_images\n day, month, year = today.day, today.month, today.year\n\n pool_idx_list = list(range(len(paths_of_images)))\n gn_list, hk_list, gv_list = [], [], []\n hk_dict, gn_dict, gv_dict = {}, {}, {}\n hk_list = []\n hk_dict = {}\n\n hk_list = [idx for idx in range(len(paths_of_images))]\n\n\n if args.is_os_win == 0:\n with open(f\"StatsIO/{args.initials}/{day}_{month}_{year}/yest_inp_file.json\", 'r') as f: # change here only for the initials from folder @every start of session\n m = json.loads(f.read())\n if args.initials == 'hk':\n for le in hk_list:\n class_of_all_images[int(le)] = int(m[f'img_{le}.png'])\n elif args.initials == 'gv':\n for le in gv_list:\n class_of_all_images[int(le)] = int(m[f'img_{le}.png'])\n elif args.initials == 'gn':\n for le in gn_list:\n class_of_all_images[int(le)] = int(m[f'img_{le}.png'])\n else:\n raise KeyboardInterrupt\n\n\n else:\n with open(f\"StatsIO\\\\{args.initials}\\\\{day}_{month}_{year}\\\\yest_inp_file.json\", 'r') as f: # change here only for the initials from folder @every start of session\n m = json.loads(f.read())\n # print(m)\n if args.initials == 'hk':\n for le in hk_list:\n class_of_all_images[int(le)] = int(m[f'img_{le}.png'])\n elif args.initials == 'gv':\n for le in gv_list:\n class_of_all_images[int(le)] = int(m[f'img_{le}.png'])\n elif args.initials == 'gn':\n for le in gn_list:\n class_of_all_images[int(le)] = int(m[f'img_{le}.png'])\n else:\n raise KeyboardInterrupt\n\n\n\nread_json(today)\n\n\n# start of session reads from your_file.txt for unseen_idx_set\ndef start_new_session():\n global unseen_idx_set\n global paths_of_images\n global unseen_idx_list\n global unseen_idx_set_start\n global session_start_time\n global plot_grid_session_iter_num\n\n plot_grid_session_iter_num = 0\n\n my_file = open(f\"your_file_{args.initials}.txt\", \"r\")\n content = my_file.read()\n if len(list(content)) == 0:\n unseen_idx_set = set([i for i in range(len(paths_of_images))])\n unseen_idx_list = list(unseen_idx_set)\n else:\n ssi = list(content.split('\\n'))\n ssi = [int(le) for le in ssi if le != '']\n unseen_idx_set_start = set(ssi)\n unseen_idx_set = set(ssi)\n unseen_idx_list = list(unseen_idx_set)\n\n\nstart_new_session()\n\ndef save_functionality():\n '''On Clicking save save (1)recordings into mnist_data.json,\n (2)save unseen idx already calculated in its next call into your_file.txt'''\n\n global iter_no\n global class_of_all_images\n global unseen_idx_set\n global state_18\n global current_18\n global gl_state_18\n global gl_current_18\n\n current_18 = list(unseen_idx_set)[:18]\n\n m = {}\n\n # modify class_of_all_images before writing\n for i in range(len(gl_current_18)):\n class_of_all_images[gl_current_18[i]] = gl_state_18[i]\n\n # ======= saving everything in datastructures i.e MM i.e RAM for now as a session is to be treated as an atomic event =================\n req_dict = {f'img_{i}.png': class_of_all_images[i] for i in range(len(class_of_all_images))}\n\n unseen_idx_set = unseen_idx_set.difference(set(current_18))\n ssil = list(unseen_idx_set)\n\n print('\\nEOSAVE')\n # print(c1)\n return \"\"\n\n\n\n\n# ======================================================================= dash app ====================================\n# ========================================================================================================================================================================\n\n\n# ============ In card_body() we initialize the placeholder values from the previous_day json-file ================\ndef card_body(card_id):\n global current_18\n global state_18\n global paths_of_images\n global class_of_all_images\n\n for i in range(len(current_18)):\n if current_18[i] == card_id:\n break\n\n #============= CHANGES HERE CHANGES THE HEIGHT AND WIDTH OF INDIVIDUAL IMAGE EMBEDDED IN A CARD.================\n # className=f'img_{card_id}', \n # dbc.CardImg(id = f'cardimg_id_{card_id}', src=paths_of_images[card_id] , top=True, style={\"height\": \"125px\", \"width\": \"188px\"}, n_clicks=0),\n # make changes to CardImg here the img will sit.\n return [\n dbc.CardImg(src=paths_of_images[card_id] , top=True, style={\"height\": \"125px\", \"width\": \"188px\"}),\n dbc.CardBody([\n dcc.RadioItems(\n id={\n 'type': 'label-option',\n 'index': \"{}\".format(card_id) # global ids\n },\n options=[\n\n {'label': 'Normal', 'value': \"0\"},\n {'label': 'Poor Quality', 'value': \"1\"},\n {'label': 'Unsure', 'value': \"2\"},\n {'label': 'Hypo', 'value': \"3\"},\n {'label': 'Abnormal', 'value': \"4\"}\n\n ],\n value=str(state_18[i]),\n labelStyle={'display': 'inline-block', \"padding\": \"0px 1px 0px 1px\", \"margin\": \"1px\"},\n inputStyle={\"margin-right\": \"1px\"},\n className=\"\"\n )\n ], style={\"padding\": \"0.05rem\"})\n ]\n\n# make changes here to get reflected in each rectangle(card) as a whole\ndef card(card_id):\n global current_18\n title = \"title\"\n description = \"desc\"\n return dbc.Card(card_body(card_id), id = {\n 'type': 'card',\n 'index': \"{}\".format(card_id) # global ids\n },\n style={\"height\": \"200px\", \"width\": \"190px\"},\n )\n# children=html.Img(className='icon') \n# className=f'img_{card_id}'\n\n\napp = dash.Dash(\n __name__,\n assets_folder='./assets',\n external_stylesheets=[dbc.themes.BOOTSTRAP],\n meta_tags=[{'name': 'viewport', 'content': 'width=device-width, initial-scale=1'}],\n )\n\n\n # assets_folder='./assets'\n\n\n# change styling of buttons\napp.layout = html.Div(\n [\n html.Button(\"Start Annotation\", id=\"start-session\", n_clicks=0,\n style={'textAlign':'center','margin':'auto', 'backgroundColor': \"Green\", \"color\": \"green\", \"margin\": \"5px\", \"padding\": \"5px\", \"display\":'block'}),\n\n html.Button(\"Next\", id=\"next\", n_clicks=0,\n style={'textAlign':'center','margin':'auto', 'backgroundColor': \"blue\", \"color\": \"white\", \"margin\": \"5px\", \"padding\": \"5px\", \"display\":\"none\"}),\n\n html.Button(\"Stop Session\", value='Stop Session', n_clicks=0, id=\"stop-session\",\n style={'textAlign':'center','margin':'auto', 'backgroundColor': \"Tomato\", \"color\": \"white\", \"margin\": \"5px\", \"padding\": \"5px\", \"display\":\"none\"}),\n\n html.Div(id=\"card-deck\", \n\n style={\"margin\": \"1px\", \"padding\": \"1px\" , \"display\":\"block\"}),\n\n html.H3(id='button-clicks'),\n ], \n\n style={'text-align': \"center\", \"margin\": \"0.5em 0em\"}\n )\n\n\ndef gen_cards(current_18):\n global gl_state_18\n global gl_current_18\n\n gl_current_18 = current_18\n gl_state_18 = state_18\n\n\n return [\n dbc.Row([\n dbc.Col([card(i)]) for i in current_18[:6]]),\n dbc.Row([\n dbc.Col([card(i)]) for i in current_18[6:12]]),\n dbc.Row([\n dbc.Col([card(i)]) for i in current_18[12:18]]),\n ]\n\n\ndef predict_next_18_states(next_18):\n '''invoked from next i.e when \"next_btn\" is clicked and Uses ML to predict\n placeholders for next set of 18 points.....for now placeholders follow the following logic\n\n Here, I already have 18_predicted states predicted by model \"yesterday\" in yesterday_file. Just read the file and\n associate |yesterday_set|//3 inp-labels.json and assign to state_18'''\n global state_18\n global class_of_all_images\n\n state_18 = [class_of_all_images[int(le)] for le in next_18]\n return state_18\n\n\ndef most_confused_18():\n '''invoked from next ; calculates most confused 18 images based on HITL....\n for now random 18 from unseen_idx_set\n\n Here, I already have 18_predicted indices predicted by model \"yesterday\" in yesterday_file. Just read the file and\n associate |yesterday_set|//3 inp-labels.json and assign to next_18'''\n global unseen_idx_set\n global class_of_all_images\n\n # read file here now I have deterministically (|yesterday_set|//3) idxs Of the \"new_indices\" put batches of 18 here.\n next_18 = list(unseen_idx_set)[:18]\n\n return next_18\n\n\n\n\n# ============== Save Labels Uptil Now ==========================================\ndef save_labels_uptil_now(n_images):\n '''Only on clicking i.e n_clicks>=1 export button would work not from starting when the app runs'''\n global batch_start_time\n\n batch_start_time, time_elapsed = calculate_ann_time(batch_start_time, save_to_disk=True)\n\n global iter_no\n global class_of_all_images\n global unseen_idx_set\n global state_18\n global current_18\n global gl_state_18\n global gl_current_18\n global name_initials\n global today\n global unseen_idx_set_start\n global session_num\n \n\n day, month, year = today.day, today.month, today.year\n current_18 = list(unseen_idx_set)[:18]\n\n\n m = {}\n\n # modify class_of_all_images before writing\n for i in range(len(gl_current_18)):\n class_of_all_images[gl_current_18[i]] = gl_state_18[i]\n\n # ======= saving everything in datastructures i.e MM i.e RAM for now as a session is to be treated as an atomic event =================\n req_dict = {f'img_{i}.png': class_of_all_images[i] for i in range(len(class_of_all_images))}\n\n unseen_idx_set = unseen_idx_set.difference(set(current_18))\n ssil = list(unseen_idx_set)\n\n # =======================================================================================================================================\n\n # ================ saving everything in secondary memory (Disk) at StatsIO/{initials}/{day_month_year} ==========================================================================\n # create a dict1 and dump here. How to create idx from class_of_all_images and from index we know the img_name?\n\n # ======== save o/p files ===============================\n if args.is_os_win == 0:\n with open(file='./StatsIO/{}/{}_{}_{}/mnist_uptil_today_out_files.json'.format(name_initials, day, month, year), mode=\"w\") as f:\n f.write(json.dumps(req_dict))\n\n else:\n with open(file='.\\\\StatsIO\\\\{}\\\\{}_{}_{}/mnist_uptil_today_out_files.json'.format(name_initials, day, month, year), mode=\"w\") as f:\n f.write(json.dumps(req_dict))\n\n\n # save the idx_unseen uptil now\n with open(f'your_file_{args.initials}.txt', 'w') as f:\n for item in ssil:\n f.write(\"%s\\n\" % item)\n\n # save the last_checkpoint for this user so as to start from correct point the next time\n iter_no += 1\n file1 = open(f\"last_checkpoint_{args.initials}.txt\", \"w\")\n file1.write('{}'.format(str(iter_no)))\n file1.close()\n\n\n # create the idx-state file annotated_today\n my_file = open(f\"your_file_{args.initials}.txt\", \"r\")\n content = my_file.read()\n ssi = list(content.split('\\n'))\n ssi = [int(le) for le in ssi if le != '']\n unseen_idx_set_next = set(ssi)\n idx_set_annotated_today = unseen_idx_set_start.difference(unseen_idx_set_next)\n images_annotated_today_dict = {f'img_{int(idx)}.png': req_dict[f'img_{int(idx)}.png'] for idx in idx_set_annotated_today}\n if args.is_os_win == 0:\n with open(file='./StatsIO/{}/{}_{}_{}/images_annotated_today_{}.json'.format(name_initials, day, month, year, session_num),mode=\"w\") as f:\n f.write(json.dumps(images_annotated_today_dict))\n else:\n with open(file='.\\\\StatsIO\\\\{}\\\\{}_{}_{}/images_annotated_today_{}.json'.format(name_initials, day, month,year, session_num), mode=\"w\") as f:\n f.write(json.dumps(images_annotated_today_dict))\n\n\n\n print(f'\\n{(1 - (len(unseen_idx_set)/int(n_images))) *100:.1f}% of the images parsed\\n')\n print('\\nBatch of 90 images successfully saved to disk!!\\n')\n\n # Use the following in a button functionality based on the user input last part of the functionality\n # os.kill(os.getpid(), signal.SIGTERM)\n\n return \"\"\n\n# ============== End of Save Labels Uptil Now ==========================================\n\n\n\n\n\n# ============== Start Session ============================================\n@app.callback(\n [\n Output(component_id='start-session', component_property='style'),\n Output(component_id='next', component_property='style') ],\n # Output(component_id='export', component_property='style') ],\n Input(component_id=\"start-session\", component_property=\"n_clicks\"),\n prevent_initial_call = False\n)\ndef start_session(n_clicks):\n print('\\nInside START Session\\n')\n\n print('start',n_clicks)\n\n # {\"display\":'none'}\n if n_clicks == 0:\n return [{'textAlign':'center','margin':'auto', 'backgroundColor': \"green\", \"color\": \"white\", \"display\":'block'},\n {\"display\":'none'},\n ]\n\n # {\"display\":'none'}\n if n_clicks == 1:\n return [{\"display\":'none'},\n {'textAlign':'center','margin':'auto', 'backgroundColor': \"blue\", \"color\": \"white\", \"padding\": \"5px\", \"display\":'block'},\n ]\n \n\n # ============== End of Start Session ============================================\n\n\n\n# Output('next', 'style'),\n# Output('export', 'style')\n@app.callback(\n [\n Output('card-deck', 'children'),\n Output('card-deck', 'style'),\n # Output('next', 'style'),\n Output('stop-session', 'style')\n ],\n Input(\"next\", \"n_clicks\"),\n prevent_initial_call=True\n\n)\ndef next(n_clicks):\n '''calculates next set of 18 indices and assigns placeholders to these before loading\n invoke most_confused_18 and then predict_next_18_states'''\n global class_of_all_images\n global unseen_idx_set\n global current_18\n global state_18\n global iter_no\n global paths_of_images\n global batch_start_time\n global batch_end_time\n global plot_grid_session_iter_num\n\n print('\\nInside next\\n')\n print(f'n_clicks: {n_clicks}')\n\n\n if n_clicks % 6 == 0:\n # , {'display':'none'}, {'display':'none'},\n save_labels_uptil_now(len(paths_of_images))\n return [gen_cards(current_18), \n {'display':'none'}, \n # {'display':'none'}, \n {'textAlign':'center','margin':'auto', 'backgroundColor': \"Tomato\", \"color\": \"black\", \"padding\": \"5px\", \"display\":'block'}]\n\n else:\n plot_grid_session_iter_num += 1\n if plot_grid_session_iter_num >= 2:\n save_functionality()\n # Only save the logs in MM not to disk yet\n batch_start_time, time_elapsed = calculate_ann_time(batch_start_time, save_to_disk=True) #inside this fn def per_counter\n\n\n if int(iter_no) < ((1000 // 18) + 1):\n current_18 = most_confused_18() # next_24 will be current_24 for next iter\n state_18 = predict_next_18_states(current_18) # returned state list of these current_24 points\n\n # {'display':'none'}, {'display':'none'},\n return [gen_cards(current_18), \n {'display':'block'}, \n # {'display':'block'}, \n {'display':'none'}]\n\n\n\n\n@app.callback(\n Output(component_id='stop-session', component_property='className'),\n Input(component_id=\"stop-session\", component_property=\"n_clicks\"),\n prevent_initial_call = True\n)\ndef stop_session(n_clicks):\n '''Only on clicking i.e n_clicks>=1 export button would work not from starting when the app runs'''\n global session_num\n if n_clicks == 1:\n # modify session_file for the day\n modify_session_file_for_the_day(session_num)\n print('\\nSESSION ENDED SUCCESSFULLY!!\\n')\n os.kill(os.getpid(), signal.SIGTERM)\n return \"\"\n\n \n\n\n@app.callback(\n Output({'type': 'label-option', 'index': MATCH}, 'className'),\n Input({'type': 'label-option', 'index': MATCH}, 'value'),\n Input({'type': 'label-option', 'index': MATCH}, 'id')\n)\ndef button_click(value, id):\n '''What are the states of the radio buttons clicked?'''\n # I have the value of the recording here ,\n # Manipulate here and store in a datastructure and fire when save is clicked\n # print(f\"val: {value}, id: {id}\")\n\n global class_of_all_images\n global glob_idx\n global current_18\n global state_18\n class_of_all_images[int(id['index'])] = int(value)\n print(\"class of {} set to {}\".format(id['index'], value))\n for i in range(len(current_18)):\n if int(current_18[i]) == int(id['index']):\n break\n state_18[i] = int(value)\n return \"\"\n\n\nif __name__ == '__main__':\n port = random.randrange(2000, 7999)\n # during development\n # app.run_server(host='127.0.0.1', port=port, debug=True)\n\n\n # for testing\n app.run_server(host='127.0.0.1', port=port, debug=True)\n\n\n# , dev_tools_ui=False","sub_path":"at37.nosync/main_test_data.py","file_name":"main_test_data.py","file_ext":"py","file_size_in_byte":22444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"60733424","text":"import re\nimport sqlite3\nfrom itertools import chain\n\ndef start_menu():\n print()\n print(\"Welcome to the ATM Application.\")\n print(\"Please choose from the choices below.\")\n print()\n print(\"***********************************\")\n print(\"* \")\n print(\"* [1] Register New User \")\n print(\"* [2] Log in \")\n print(\"* [0] Exit the program \")\n print(\"* \")\n print(\"***********************************\")\n print()\n\ndef register_user():\n print()\n print(\"**********************************************\")\n print(\"* Registering a new user *\")\n print(\"**********************************************\")\n \n print()\n email = input(\"Enter your email (0 to exit): \")\n if email == '0':\n return\n while not (valid_email(email)):\n print()\n print(\"Email must be valid.\")\n print()\n email = input(\"Enter your email (0 to exit): \")\n if email == '0':\n return\n if user_available(email):\n print()\n print(\"Username is available.\")\n pin = get_pin()\n if (pin == 0):\n return\n print()\n insert_user_and_pin(email, pin)\n print(\"**********************************************\")\n print(\"* New Customer Added *\")\n print(\"**********************************************\")\n else:\n print()\n print(\"User already exists.\")\n print(\"Please choose a new username or log in.\")\n \ndef insert_user_and_pin(email, pin):\n db = sqlite3.connect('customer.db')\n cursor = db.cursor()\n cursor.execute(\"INSERT INTO customers (user_name, pin) VALUES (?, ?)\", (email.lower(), pin))\n db.commit()\n db.close()\n \ndef valid_email(email):\n regex = '^[A-Za-z0-9]+[\\._]?[A-Za-z0-9]+[@]\\w+[.]\\w{2,3}$'\n if re.search(regex,email):\n return True\n else:\n return False\n \ndef user_available(email):\n db = sqlite3.connect('customer.db')\n cursor = db.cursor()\n cursor.execute(\"SELECT count(*) FROM customers WHERE user_name =?\", (email.lower(),))\n data=cursor.fetchone()[0]\n if data==0:\n return True\n else:\n return False\n db.close()\n\ndef get_pin():\n while (True):\n print()\n pinString = input(\"Enter your 4-digit pin number (0 to exit): \")\n try:\n pin = int(pinString)\n if (pin == 0):\n break;\n if len(pinString) < 4 or len(pinString) > 4:\n print()\n print(\"Pin must contain four digits.\")\n elif len(pinString) == 4:\n break;\n except ValueError:\n print()\n print(\"Pin numbers can only contain digits.\")\n return pin\n \ndef log_in():\n print()\n print(\"**********************************************\")\n print(\"* Log in Screen *\")\n print(\"**********************************************\")\n print()\n email = None\n email = input(\"Enter your email (0 to exit): \")\n if (email == '0'):\n return\n while not (valid_email(email)):\n print()\n print(\"Email must be valid.\")\n print()\n email = input(\"Enter your email (0 to exit): \")\n if (email == '0'):\n return\n pin = get_pin()\n if (pin == 0):\n return\n while not (correct_pin(email, pin)):\n print()\n print(\"Pin does not match pin on file.\")\n print(\"Please try again.\")\n pin = get_pin()\n if (pin == 0):\n return\n print()\n get_acct_user_choice()\n return\n\ndef correct_pin(email, input_pin):\n db = sqlite3.connect('customer.db')\n cursor = db.cursor()\n result = cursor.execute(\"SELECT pin FROM customers WHERE user_name =?\", (email.lower(),))\n try:\n db_pin = next(result)\n if db_pin[0] == input_pin:\n db.close()\n return True\n else:\n db.close()\n return False\n except StopIteration as e:\n db.close()\n return False\n \ndef user_menu():\n print(\"**********************************************\")\n print(\"* Welcome to your account *\")\n print(\"**********************************************\")\n print()\n print(\"***************************************\")\n print(\"* \")\n print(\"* [1] Check Account Balance \")\n print(\"* [2] Withdrawal Money \")\n print(\"* [3] Transfer Money \")\n print(\"* [4] Make a Deposit \")\n print(\"* [0] Sign-out \")\n print(\"* \")\n print(\"***************************************\")\n print()\n \ndef get_acct_user_choice():\n option = None\n while option != 0:\n #try to convert user input to a number\n try:\n user_menu()\n option = int(input(\"Enter your option: \"))\n if option == 0:\n print()\n print(\"Returning to the main menu...\")\n return;\n elif option == 1:\n #todo check acct balance\n pass\n elif option == 2:\n #todo withdrawal money\n pass\n elif option == 3:\n #todo transfer funds\n pass\n elif option == 4:\n #todo deposit money\n pass\n else:\n print()\n print(\"Invalid option.\")\n #if user does not input a number, this error is thrown \n except ValueError:\n print()\n print(\"Input must be a number.\")\n\ndef get_init_user_choice():\n option = None\n while option != 0:\n #try to convert user input to a number\n try:\n start_menu()\n option = int(input(\"Enter your option: \"))\n if option == 0:\n print()\n print(\"Thanks for using this program! Goodbye!\")\n break;\n elif option == 1:\n register_user()\n elif option == 2:\n log_in()\n else:\n print()\n print(\"Invalid option.\")\n #if user does not input a number, this error is thrown \n except ValueError:\n print()\n print(\"Input must be a number.\")\n \ndef create_customers_table():\n db = sqlite3.connect('customer.db')\n cursor = db.cursor()\n cursor.execute(\"\"\"\n CREATE TABLE if not exists customers (\n id INTEGER PRIMARY KEY, user_name text, pin int\n )\n \"\"\")\n db.commit()\n \ndef main():\n create_customers_table()\n get_init_user_choice()\n\nif __name__ == \"__main__\": main()","sub_path":"atm-script.py","file_name":"atm-script.py","file_ext":"py","file_size_in_byte":7040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"138959898","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport sys\nimport codecs\nimport readchar\nimport simplejson as json\nfrom flask import Flask, render_template,request\n\nimport sugartensor as tf\nimport numpy as np\nfrom prepro import *\nfrom train import ModelGraph\n\napp = Flask(__name__)\n\n\n@app.route(\"/test\")\ndef output():\n return render_template(\"index.html\")\n\n\n@app.route('/output', methods=['GET'])\ndef worker():\n #print(request, file=sys.stderr)\n string = request.args.get('string').lower()\n work = request.args.get('work')\n words=string.split()\n #print(words, file=sys.stderr)\n n=len(words)\n\n latest_50_chars = string[-50:]\n para = \"E\"*(50 - len(latest_50_chars)) + latest_50_chars\n ctx = [char2idx[char] for char in para]\n\n logits = sess.run(g.logits, {g.x: np.expand_dims(ctx, 0)})\n preds = logits.argsort()[0][-3:]\n\n predword1, predword2, predword3 = [idx2word.get(pred) for pred in preds]\n\n return json.dumps([(predword1, ), (predword2, ), (predword3, )])\n\n \nif __name__==\"__main__\":\n g = ModelGraph(mode=\"test\")\n\n with tf.Session() as sess:\n tf.sg_init(sess)\n saver = tf.train.Saver()\n saver.restore(sess, tf.train.latest_checkpoint('asset/train'))\n print('Restored')\n\n char2idx, idx2char = load_char_vocab()\n word2idx, idx2word = load_word_vocab()\n\n previous = [0]*50 # a stack for previous words\n para = \"EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE\"\n ctx = [0]*50\n\n\n app.run(debug=True)\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"56714141","text":"#!/usr/bin/python3\n\n# Check metrics using trained weight files\nfrom keras.applications import InceptionV3, ResNet50, Xception\nfrom keras.models import Model\nfrom keras.layers import Flatten, Dense, Input, Dropout\nfrom keras.optimizers import Adam, RMSprop\nfrom six.moves import cPickle\nimport numpy as np\nimport keras\nimport os\n\n__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n# network and training\nEPOCHS = 30\nBATCH_SIZE = 35\nVERBOSE = 1\n\n# https://keras.io/optimizers\nOPTIMIZER = Adam()\n# OPTIMIZER = RMSprop()\n# OPTIMIZER = Adadelta(lr=1.0, rho=0.95, epsilon=None, decay=0.0)\n\n# Image processing layer\n# CNN = 'Xception'\n# CNN = \"IV3\"\nCNN = 'RN50'\n\n# Load data\nprint(\"...loading training data\")\nf = open((os.path.join(__location__, \"data.pkl\")), \"rb\")\nimg = cPickle.load(f)\nf.close()\n\nf = open((os.path.join(__location__, \"data_age.pkl\")), \"rb\")\nage = cPickle.load(f)\nf.close()\n\nf = open((os.path.join(__location__, \"data_gender.pkl\")), \"rb\")\ngender = cPickle.load(f)\nf.close()\n\nimg = np.asarray(img, dtype=np.float32)\nage = np.asarray(age)\ngender = np.asarray(gender)\n\n# this is to normalize x since RGB scale is [0,255]\nimg /= 255.\n\nimg_final = []\nage_final = []\ngdr_final = []\n\n# Shuffle images and split into train, validation and test sets\nrandom_no = np.random.choice(img.shape[0], size=img.shape[0], replace=False)\nfor i in random_no:\n img_final.append(img[i, :, :, :])\n age_final.append(age[i])\n gdr_final.append(gender[i])\n\nimg_final = np.asarray(img_final)\nage_final = np.asarray(age_final)\ngdr_final = np.asarray(gdr_final)\n\nprint(\"img_final shape:\" + str(img_final.shape))\nprint(\"age_final shape:\" + str(age_final.shape))\nprint(\"gdr_final shape:\" + str(gdr_final.shape))\n\n# First we need to create a model structure\n# input layer\nimage_input = Input(shape=img_final.shape[1:], name=\"image_input\")\n\nif CNN == \"IV3\":\n # Inception V3 layer with pre-trained weights from ImageNet\n # base_iv3_model = InceptionV3(include_top=False, weights=\"imagenet\")\n base_iv3_model = InceptionV3(weights=\"imagenet\")\n # Inception V3 output from input layer\n output_vgg16 = base_iv3_model(image_input)\n # flattening it #why?\n # flat_iv3 = Flatten()(output_vgg16)\nelif CNN == \"RN50\":\n # ResNet50 layer with pre-trained weights from ImageNet\n base_rn50_model = ResNet50(weights=\"imagenet\")\n # ResNet50 output from input layer\n output_rn50 = base_rn50_model(image_input)\nelif CNN == \"Xception\":\n # Xception layer with pre-trained weights from ImageNet\n base_xp_model = Xception(weights=\"imagenet\")\n # Xception output from input layer\n output_xp = base_xp_model(image_input)\n\n# Gender input layer\ngdr_input = Input(shape=(1,), name=\"gdr_input\")\n# Gender dense layer\ngdr_dense = Dense(32, activation=\"relu\")\n# Gender dense output\noutput_gdr_dense = gdr_dense(gdr_input)\n\nif CNN == \"IV3\":\n # Concatenating iv3 output with sex_dense output after going through shared layer\n x = keras.layers.concatenate([output_vgg16, output_gdr_dense])\nelif CNN == \"RN50\":\n # Concatenating ResNet50 output with gender_dense output after going through shared layer\n x = keras.layers.concatenate([output_rn50, output_gdr_dense])\nelif CNN == \"Xception\":\n # Concatenating Xception output with gender_dense output after going through shared layer\n x = keras.layers.concatenate([output_xp, output_gdr_dense])\n\n# We stack dense layers and dropout layers to avoid overfitting after that\nx = Dense(1000, activation=\"relu\")(x)\nx = Dropout(0)(x)\nx = Dense(1000, activation=\"relu\")(x)\nx = Dropout(0)(x)\n# x = Dense(240, activation=\"relu\")(x)\n# x = Dropout(0)(x)\n\n# and the final prediction layer as output (should be the main logistic regression layer)\n# predictions = Dense(1, activation='sigmoid', name='predictions')(x)\npredictions = Dense(1)(x)\n\n# Now that we have created a model structure we can define it\n# this defines the model with two inputs and one output\nmodel = Model(inputs=[image_input, gdr_input], outputs=predictions)\n\n# printing a model summary to check what we constructed\nprint(model.summary())\n\nmodel.compile(optimizer=OPTIMIZER, loss=\"mean_squared_error\", metrics=[\"MAE\", \"accuracy\"])\nmodel.load_weights(\"model.h5\")\n\nscore = model.evaluate(\n [img_final, gdr_final], age_final, batch_size=BATCH_SIZE, verbose=VERBOSE\n)\n\nprint(\"\\nTest loss:\", score[0])\nprint(\"Test MAE:\", score[1])\nprint(\"Test accuracy:\", score[2])\n","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":4411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"271591183","text":"import sys\n\nimport boto3\n\nimport aws_util\nimport notification_util\nimport settings\n\n\ndef main():\n # args\n config_filename = sys.argv[1] # 0 based\n settings.init(config_filename)\n\n sns = settings.aws_session.client('sns')\n \n\n # Send message to SQS queue\n response = sns.publish(\n TopicArn='arn:aws:sns:us-east-1:333408648190:home_security_event',\n\n Message='test #13 event: backdoor \\nhttps://photos.app.goo.gl/p8yPhr5m6v7H4Fr96',\n Subject='test_notification',\n MessageStructure='string'\n )\n\n print(f\"SNS Publish Response: {response['MessageId']}\")\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"test_notification.py","file_name":"test_notification.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"503327926","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 25 13:32:39 2017\n\n@author: p000495138\n\"\"\"\nimport pandas as pd\n\n# %%\n\"\"\"温度ログクラス\"\"\"\nclass FuserTmp():\n \n def __init__(self):\n None\n \n#%% 通常のログ\n def _read_fuser(self,data):\n data_list=[]\n for idx,line in enumerate(data):\n data_list.append(line.split()[0:16])\n return data_list\n \n#%% データフレームに変換 \n def toDataframe(self,data):\n \n self.datalist = self._read_fuser(data) \n \n column = [\"a\",\"FF\",\"state\",\"mode\",\"motor\",\n \"tar_cen\",\"tar_end\",\"tar_prs\",\n \"duty_cen\",\"duty_end\",\n \"tmp_cen\",\"tmp_end\",\"tmp_prs_cen\",\"tmp_prs_end\",\n \"p\",\"sec\"]\n self.datapd = pd.DataFrame(self.datalist,columns=column)\n self.datapd = self.datapd.dropna()#欠損値含む行を除去\n self.datapd = self.datapd.drop([\"a\",\"p\"],axis=1)\n self.datapd = self.datapd.astype(float)\n\n return self.datapd\n#%% \n\"\"\"半波ログクラス\"\"\"\nclass FuserWave(): \n def __init__(self): \n None\n \n#%% 通常のログ\n def _read_wave(self,data):\n data_list = []\n for idx,line in enumerate(data):\n #print(idx)\n duty = line.split()[2]\n preduty = line.split()[4]\n flow = line.split()[5].split(\":\")[1]\n time = line.split()[6].split(\":\")[1]\n data_list.append([duty,preduty,flow,time])\n return data_list\n \n#%% データフレームに変換 \n def toDataframe(self,data):\n self.data_list = self._read_wave(data) \n column = [\"duty\",\"preduty\",\"flow\",\"time_wave\"]\n self.datapd = pd.DataFrame(self.data_list,columns=column)\n self.datapd = self.datapd.dropna()#欠損値含む行を除去\n self.datapd = self.datapd.astype(float)\n return self.datapd","sub_path":"01_実験/d04_短制御周期Ves/PyParts/Log_Parts_Read_Fuser_Ves.py","file_name":"Log_Parts_Read_Fuser_Ves.py","file_ext":"py","file_size_in_byte":1922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"555112527","text":"# -*- coding:utf-8 -*-\n'''\n读完配置文件\n'''\nimport os\nimport configparser\n\nclass config:\n def __init__(self):\n # 项目路径\n self.rootDir = os.path.split(os.path.realpath(__file__))[0]\n # config.ini文件路径\n self.configFilePath = os.path.join(self.rootDir, 'config.ini') \n def get_config_values(self,section, option):\n \"\"\"\n 根据传入的section获取对应的value\n :param section: ini配置文件中用[]标识的内容\n :return:\n \"\"\"\n con = configparser.ConfigParser()\n con.read(self.configFilePath)\n # return config.items(section=section)\n return con.get(section=section, option=option)\n \n \nif __name__ == '__main__':\n cof = config()\n result = cof.get_config_values('GITHUB', 'AUTH_TOKEN')\n print(result)","sub_path":"server/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"292431766","text":"from PIL import Image\nimport numpy as np\nimport skimage.io as io\nimport tensorflow as tf\nimport cv2\nimport numpy as np\nimport os\nimport io\n#import Image\nfrom array import array\nfrom PIL import Image\nimport csv\n\nprefix = 'val'\nprefix = 'train'\n\ncount = 0\ncsvfile = open('tf_data_'+prefix+'.csv','w')\nwriter = csv.writer(csvfile, delimiter=';')\n\n#filename;class;xmin;ymin;xmax;ymax\nline = []\nline.append(\"filename\")\nline.append(\"class\")\nline.append(\"xmin\")\nline.append(\"ymin\")\nline.append(\"xmax\")\nline.append(\"ymax\")\nwriter.writerow(line)\n\n\nfor string_record in tf.python_io.tf_record_iterator(\"TF_RECORDS/tl_\"+prefix+\".record\"):\n #result = tf.train.Example.FromString(string_record)\n example = tf.train.Example()\n example.ParseFromString(string_record)\n \n height = (example.features.feature['image/height']\n .int64_list\n .value[0])\n print(height)\n \n width = (example.features.feature['image/width']\n .int64_list\n .value[0])\n print(width)\n\n label = (example.features.feature['image/object/class/label']\n .int64_list\n .value[0])\n print(\"label: \",label) \n\n\n filename = \"tl_\" + str(count) + \".jpeg\"\n count += 1\n\n img_string = (example.features.feature['image/encoded']\n .bytes_list\n .value[0])\n\n image = Image.open(io.BytesIO(img_string))\n (width2, height2) = image.size\n print(width2,height2,width,height)\n\n image.save('./val_tl_data/' + filename)\n\n xmin = (example.features.feature['image/object/bbox/xmin']\n .float_list\n .value[0])\n\n xmax = (example.features.feature['image/object/bbox/xmax']\n .float_list\n .value[0])\n \n ymin = (example.features.feature['image/object/bbox/ymin']\n .float_list\n .value[0])\n\n ymax = (example.features.feature['image/object/bbox/ymax']\n .float_list\n .value[0])\n line = []\n #csvstr = filename + \";\" + str(xmin)\n line.append(filename)\n line.append(\"traffic_light\")\n line.append(int(xmin*width))\n line.append(int(ymin*height))\n line.append(int(xmax*width))\n line.append(int(ymax*height))\n writer.writerow(line)\n #print(xmin,xmax,ymin,ymax)\n\n\nprint (count)\n","sub_path":"tl_training/data/extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":2582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"457485067","text":"# -*- coding: iso-8859-1 -*-\n#don't change this encoding, because other encodings could potentially cause problems with German Umlaute\n\nr'''\nadap_MAPDS - run script. \n\nInstructions:\n \n This script imports the main experiment class from \"MAPDS.py\" and runs the \n experiment using the specified parameters. It is supposed to be called \n from the command line. For this, either use the anaconda prompt or make\n sure that the right Python (including all necessary packages, which is why\n you should use conda environments in the first place.) is on your search\n path. \n \n There are two required arguments: \n subID as integer.\n emo as string: 'angry' or 'happy'\n\n python runMAPDS 4 -e happy (example for subID = 4)\n \n You either need to specify the absolute path like this:\n python C:\\Users\\neugebauer\\Documents\\Experiments\\adap_MAPDS\\expCode\\runMAPDS.py subID\n\n Or you go there first and then call it:\n cd C:\\Users\\neugebauer\\Documents\\Experiments\\adap_MAPDS\\expCode\n python runMAPDS.py subID\n\n You can run it without additional parameters, using the respective default.\n Defaults and options can be seen at the end of the script. Just search for\n \"optional arguments\". These are given using the correct indicators. E.g. \n if you want to run it in the first, not the second display, you can call it\n like this (assuming that you are in the correct directory):\n python runMAPDS.py subID -sn 0 (-sn is for \"screenNum\")\n\n@author Lukas Neugebauer\n'''\n\n######### IMPORT FROM MAIN SCRIPT ############################################\n\nfrom MAPDS import expQuad \n#also - import ArgumentParser\nfrom argparse import ArgumentParser\n\n\n######### DEFINE FUNCTION THAT WILL DO THE WORK FOR US #######################\n\ndef run_exp(args):\n \n #can't work without specifying a subID since putting in a default would overwrite anything.\n if args.subID is None:\n raise AttributeError('You didn\"t specify a subject ID and in order to avoid overwriting stuff this killed the programm.')\n #create instance of MAPDS using the arguments.\n exp = expQuad(**args.__dict__);\n #actually run the Trials, i.e. present stimuli, write responses to file and so on. No stopping criterion, no intermediary estimation of parameters.\n exp.runMe()\n\n\n######### RUN EVERYTHING FROM THE COMMAND LINE ###############################\n \nif __name__== \"__main__\":\n #handle arguments\n ##get parser object\n parser = ArgumentParser(description = 'Run a quadruplet task. Results are to be analyzed using MAPDS.')\n\n #add arguments\n #optional arguments\n parser.add_argument('subID', type = int, help = 'ID of subject. Is used for' \n + 'basically everything and required. You cannot run this'\n + 'script without specifying it.', default = None)\n parser.add_argument('-e','--emo',dest = 'emo', default = 'None',action = 'store')\n parser.add_argument('-s','--small',dest = 'winSize', default = \n 'big', action = 'store_const', const = 'small');\n parser.add_argument('-nt','--nTrials',dest = 'nTrials', type = int, default =\n 216, action = 'store', help = 'Number of trials for'\n + 'experiment. Defaults to 216')\n parser.add_argument('-sn','--screenNum', dest = 'screenNum', type = int, \n default = 1, action = 'store',help = 'Screen number,' \n + 'default is 1 , which is secondary display. Use 0 for'\n + 'primary display or see if you manage to use 2 for a'\n + 'tertiary display, if you have one. I didn''t check for that')\n parser.add_argument('-nit','--nIntroTrials',dest = 'nIntroTrials',type = int, \n default = 10, action = 'store', help = 'How many trials'\n + 'to run in the experiment.');\n parser.add_argument('-st','--stimlist',dest='stimlist',action = 'store',default = 'informed');\n args = parser.parse_args()\n\n #run the main function with them\n run_exp(args);\n","sub_path":"runMAPDS.py","file_name":"runMAPDS.py","file_ext":"py","file_size_in_byte":4150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"499982275","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 24 15:11:25 2018\n\n@author: lizheng\n\"\"\"\n\nfrom sklearn import metrics\nimport sys\n\nsys.path.append(\"D:\\PycharmProjects\\Tax\")\n\nimport spbm_model11 as sp\nimport pandas as pd\nimport numpy as np\nfrom sklearn.externals import joblib\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.linear_model import PassiveAggressiveClassifier\nimport datetime\n\n\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\n\nfrom scipy.sparse import csr_matrix\n\nfrom gensim.models import word2vec\nimport gensim\n\n\n\nimport json\nfrom urllib.parse import quote\nimport string\nimport requests\n# import time\n\n\ndef get_data(filename):\n csvfile = open(filename, 'rb')\n reader = pd.read_csv(csvfile)\n reader = reader.append(reader)\n #分割商品名称\n #reader = reader.drop_duplicates()\n\n reader['HWMC'] = sp.sjcl(list(reader['HWMC'].astype(str)))\n print(\"分词结束\", datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S'))\n\n\n\n # ##多线程分词\n # print(\"开始分词\", datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S'))\n # # keywordextraction,\n # from multiprocessing import Pool # 多线程处理机制,创建多个子进程\n # p = Pool(30)\n # reader['HWMC'] = p.map(sp.cut_jieba, list(reader['HWMC'].astype(str)))\n # p.close()\n # p.join()\n #\n # print(\"分词结束\", datetime.datetime.now().strftime('%Y.%m.%d-%H:%M:%S'))\n\n\n\n # # ###将分词结果保存为csv格式\n # df = pd.DataFrame({'HWMC':reader['HWMC']})\n #\n # #API匹配分词结果\n # dfNew = pd.DataFrame({'HWMC':reader['HWMC']})\n # valuearr = df.values\n # rowIndex = 0\n # i = 0\n # for sentenceindex in valuearr:\n # rowIndex += 1\n # for wordInSentence in sentenceindex:\n # arrWordToSimilar = wordInSentence.split(' ')\n # for wordToCheck in arrWordToSimilar:\n # # headers = {\n # # 'Connection': 'close',\n # # }\n # url = 'http://shuyantech.com/api/cndbpedia/ment2ent?q='+wordToCheck+'&apikey=cd9ad381122aeade145b3c55258d9be7'\n # # r = requests.get(quote(url, safe=string.printable), headers=headers)\n # r = requests.get(quote(url, safe=string.printable))\n # # r = requests.get(url, headers=headers)\n # i += 1\n # print(i)\n # str0 = json.loads(r.text)\n # rValue = str0['ret']\n # if len(rValue) > 0:\n # str1 = ''.join(rValue[0])\n # if str1.find('(') != -1:\n # str2 = str1.split('(')[1].split(')')[0]\n # strIndfNew = dfNew.values[rowIndex-1][0]\n # strIndfNew = strIndfNew + ' ' + str2\n # dfNew.values[rowIndex-1][0] = strIndfNew\n # df = dfNew\n # df.to_csv('fencijieguo1.5-3k.csv', index=False, index_label=False, encoding='utf-8-sig')\n # reader['HWMC'] = dfNew\n\n\n\n reader['HWMC'] = reader['HWMC'].apply(lambda x: np.NaN if str(x)=='' else x) #将空白替换为nan\n reader = reader[reader['HWMC'].notnull()]\n reader = shuffle(reader)\n reader.index = np.arange(len(reader))\n classes = reader.drop_duplicates('U_CODE')\n all_classes = np.asarray(classes['U_CODE'])\n X = np.array(reader['HWMC'])\n y = np.array(reader['U_CODE'])\n csvfile.close()\n return X, y, all_classes\n\n\n##转换为字典\ndef Dict(X):\n docs = X\n segments = []\n for i in range(len(X)):\n words = docs[i].split(' ')\n # words = np.array(words)\n for j in range(len(words)):\n fileContent = words[j]\n segments.append(fileContent)\n ##去重\n segments =list(set(segments))\n return segments\n\n\n##转换为list\ndef transfer(X):\n docs = X\n segments = []\n for i in range(len(X)):\n\n segments.append(docs[i])\n return segments\n\n##\n\n\n\ndef tfidf_compute(word, doc):\n\n docs = np.array(doc)\n words = np.array(word)\n\n\n # 词在文档中出现的个数\n cfs = []\n for e in docs:\n cf = [e.count(word) for word in words]\n cfs.append(cf)\n # print('==============================================')\n # print('cfs:\\n', np.array(cfs))\n\n\n # 词在文档中出现的频率\n tfs = []\n for e in cfs:\n tf = e/(np.sum(e))\n tfs.append(tf)\n # print('==============================================')\n # print('tfs:\\n', np.array(tfs))\n\n\n # 包含词的文档个数\n dfs = list(np.zeros(words.size, dtype=int))\n for i in range(words.size):\n for doc in docs:\n if doc.find(words[i]) != -1:\n dfs[i] += 1\n # print('==============================================')\n # print('df:\\n', np.array(dfs))\n\n\n # 计算每个词的idf(逆向文件频率inverse document frequency)\n # #log10(N/(1+DF))\n N = np.shape(docs)[0]\n # f(e) = np.log10(N*1.0/(1+e))\n idfs = [(np.log10(N*1.0/(1+e))) for e in dfs]\n\n # print('==============================================')\n # print('idfs:',np.array(idfs))\n\n\n # 计算tf-idf(term frequency - inverse document frequency)\n tfidfs = []\n for i in range(np.shape(docs)[0]):\n word_tfidf = np.multiply(tfs[i], idfs)\n tfidfs.append(word_tfidf)\n # print('==============================================')\n # print('tfidfs:\\n', np.array(tfidfs))\n\n\ndef sklearn_tfidf(docs):\n tag_list = docs\n\n vectorizer = CountVectorizer() # 将文本中的词语转换为词频矩阵\n\n X = vectorizer.fit_transform(tag_list) # 计算个词语出现的次数\n\n transformer = TfidfTransformer()\n\n tfidf = transformer.fit_transform(X) # 将词频矩阵X统计成TF-IDF值\n\n # print(tfidf)\n\n return tfidf\n\n\n\ndef sklearn_word2vec(docs):\n\n #加载数据\n sentences = docs\n\n #训练模型\n model = word2vec.Word2Vec(sentences, size=100, hs=1, min_count=1, window=3)\n\n return model\n # return csr_matrix(model)\n\n\n\ndef fit_form(model, data):\n\n martixs = model(data)\n\n print(martixs)\n\n return martixs\n\n # return csr_matrix(martixs)\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n MD = PassiveAggressiveClassifier(max_iter=1000, loss='squared_hinge', average=10, n_jobs=-1)\n X, y, all_classes = get_data('traindata1.5k.csv')\n\n\n # # word = dict(X)\n doc = transfer(X)\n print(doc)\n\n Dict = Dict(X)\n print(Dict)\n\n\n\n # # tfidf_compute(word, doc)\n #\n\n model = sklearn_word2vec(Dict)\n print(model['前'])\n\n\n #\n # model.save('/tmp')\n #\n # # model.save('/tmp/MyModel')\n # # model.save_word2vec_format('/tmp/MyModel.txt', binary=False)\n # # model = gensim.models.Word2Vec.load('/tmp/MyModel')\n #\n # model = gensim.models.Word2Vec.load('/tmp')\n\n\n\n # sss = StratifiedShuffleSplit(n_splits = 10,test_size = 0.2)#训练集额和测试集的比例随机选定,训练集和测试集的比例的和可以小于1,但是还要保证训练集中各类所占的比例是一样的\n # sss.get_n_splits(X, y)\n # i = 0\n # for train_index, test_index in sss.split(X, y):\n # print(\"{} time\".format(i))\n # X_train, X_test = X[train_index], X[test_index]\n # y_train, y_test = y[train_index], y[test_index]\n #\n #\n #\n #\n # # MD.partial_fit(sklearn_word2vec(transfer(X_train)), y_train, classes = all_classes)\n # # result = MD.predict(sklearn_word2vec(transfer(X_test)))\n #\n #\n #\n # MD.partial_fit(sp.get_hv(X_train), y_train, classes = all_classes)\n # result = MD.predict(sp.get_hv(X_test))\n #\n #\n #\n #\n #\n #\n # print(\"正确率: %.4g\" % metrics.accuracy_score(y_test, result), \"召回率: %.4g\" % metrics.recall_score(y_test, result, average='macro')\n # , \"F1: %.4g\" % metrics.f1_score(y_test, result, average='weighted'))\n # i += 1\n #\n # #joblib.dump(MD, \"D:\\\\PycharmProjects\\\\Tax\\\\321_2**15.pkl.gz\", compress=('gzip', 3))","sub_path":"BSE-ESTC/train_20180224.py","file_name":"train_20180224.py","file_ext":"py","file_size_in_byte":8052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"395189369","text":"\"\"\"\nThis module is used to fake the original hyperion functions and to store\ninterthread variables for led data and images\n\nCreated on 27.11.2014\nLast updated on 13.3.2016\n\n@author: Fabian Hertwig\n@author: Juha Rantanen\n\"\"\"\n\nimport imp\n\nledCount = 0\n\n# the data as set in the hypercon application\n# horizontal = 0\n# vertical = 0\n# first_led_offset = 0\n# clockwise_direction = False\n# corner_leds = False\nleds = None\nleds_top = None\nleds_right = None\nleds_bottom = None\nleds_left = None\nclockwise = False\n\n# the dictionary the hyperion effect will access\nargs = {}\n\n_ledData = None\n_imageData = None\n_imageWidth = 0\n_imageHeight = 0\n_abort = False\n\n\"\"\" helper functions \"\"\"\n\ndef init(_leds, _leds_top, _leds_right, _leds_bottom, _leds_left):\n \"\"\"\n Initialise the fake hyperion.\n \"\"\"\n global ledCount, leds, leds_top, leds_right, leds_bottom, leds_left\n global _ledData, _imageData, _imageWidth, _imageHeight\n\n ledCount = len(_leds)\n leds = _leds\n leds_top = _leds_top\n leds_right = _leds_right\n leds_bottom = _leds_bottom\n leds_left = _leds_left\n\n _imageWidth = len(leds_top) + 2\n _imageHeight = len(leds_left)\n _imageData = bytearray()\n\n for i in range(_imageWidth * _imageHeight * 3):\n _imageData.append(0)\n\n _ledData = bytearray()\n for x in range(ledCount * 3):\n _ledData.append(0)\n\n\ndef set_abort(abort_hyperion):\n global _abort\n _abort = abort_hyperion\n\n\ndef get_led_data():\n led_data_copy = bytearray()\n if _ledData:\n imp.acquire_lock()\n led_data_copy = bytearray(_ledData)\n imp.release_lock()\n return led_data_copy\n\ndef get_image_data():\n img_data_copy = bytearray()\n if _imageData:\n imp.acquire_lock()\n img_data_copy = bytearray(_imageData)\n imp.release_lock()\n return (_imageWidth, _imageHeight, img_data_copy)\n\ndef set_args(_args):\n global args\n args = _args\n\n\n\"\"\" fake hyperion functions \"\"\"\n\ndef abort():\n return _abort\n\ndef set_color_led_data(led_data):\n global _ledData\n imp.acquire_lock()\n _ledData = bytearray(led_data)\n imp.release_lock()\n\n\ndef set_color_rgb(red, green, blue):\n global _ledData\n imp.acquire_lock()\n for i in range(len(_ledData) / 3):\n _ledData[3*i] = red\n _ledData[3*i + 1] = green\n _ledData[3*i + 2] = blue\n imp.release_lock()\n\ndef setColor(*args):\n if len(args) == 1:\n set_color_led_data(args[0])\n elif len(args) == 3:\n set_color_rgb(args[0], args[1], args[2])\n else:\n raise TypeError('setColor takes 1 or 3 arguments')\n\ndef setImage(width, height, image_data):\n global _imageData\n imp.acquire_lock()\n _imageWidth = width\n _imageHeight = height\n _imageData = bytearray(image_data)\n imp.release_lock()\n","sub_path":"app/hyperion.py","file_name":"hyperion.py","file_ext":"py","file_size_in_byte":2769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"599067070","text":"from collections import defaultdict\n\n\n# Method 4 - Bottom-up DP, Space Optimized\nclass Solution:\n def longestCommonSubsequence(self, text1: str, text2: str) -> int:\n cache: defaultdict[int, int] = defaultdict(int)\n\n for char1 in text1:\n prev_cache = cache.copy()\n for index2, char2 in enumerate(text2, start=1):\n # Since we only access indices index1-1 and index2-1,\n # we can get away with storing just 1 row of old data.\n\n if char1 == char2:\n # NOTE: [index1 - 1] replaced with prev_cache\n cache[index2] = 1 + prev_cache[index2-1]\n else:\n cache[index2] = max(cache[index2-1], cache[index2])\n\n return cache[len(text2)]\n\n\ntests = [\n (\n (\"abcde\", \"ace\",),\n 3,\n ),\n (\n (\"abc\", \"abc\",),\n 3,\n ),\n (\n (\"abc\", \"def\",),\n 0,\n ),\n (\n (\"abcddrh\", \"abddghj\",),\n 5,\n ),\n (\n (\"opmtqvejqvudezchsloxizynabehqbyzknunobehkzqtkt\",\n \"srwbovohkvqhwrwvizebsrszcxepqrenilmvadqxuncpwhe\",),\n 14,\n ),\n]\n","sub_path":"longest_common_subsequence_optimized.py","file_name":"longest_common_subsequence_optimized.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"368229721","text":"#!/usr/bin/python3\n\n##\n# pysploit example exploit in Python 3\n##\n\nimport pysploit\nimport re\nimport struct\nimport time\n\nshellcode = b\"\"\"\\x48\\x31\\xf6\\x56\\x48\\xbf\\x2f\\x62\\x69\\x6e\\x2f\\\n\\x2f\\x73\\x68\\x57\\x54\\x5f\\x6a\\x3b\\x58\\x99\\x0f\\x05\"\"\"\n\n# Create context\nctx = pysploit.ctx()\nctx.spawn([\"../examples/vuln\"])\n\n# Read return address\nm = re.match(b\"Leak: (.+)$\", ctx.getline())\nretaddr = int(m.group(1), 16)\n\n# Prepare payload\npayload = shellcode + b\"A\" * (0x28 - len(shellcode))\npayload += struct.pack(\"hh lines:\n untagged:\n - D->Kpi\n - D->KK\n - D->pipi\n tagged, D*->D0pi with:\n - D->Kpi RS\n - D->Kpi WS\n - D->KK\n - D->pipi\n\n Usage:\n from StrippingSelections import StrippingD2hh\n confD2hh = StrippingD2hh.D2hhConf(\"D2hh\",StrippingD2hh.default_config)\n stream.appendLines( confD2hh.lines() )\n '''\n\n __configuration_keys__ = ('DaugPtMin',\n 'DaugPtMax',\n 'DaugPtLoose',\n 'DaugP',\n 'DaugPLoose',\n 'DaugIPChi2',\n 'DaugIPChi2Loose',\n 'DaugTrkChi2',\n 'DaugTrkChi2Loose',\n 'HighPIDK',\n 'LowPIDK',\n 'D0Pt',\n 'D0PtLoose',\n 'D0MassWindowCentre',\n 'D0MassWindowWidth',\n 'D0KPiMassWindowWidthLow',\n 'D0KPiMassWindowWidthHigh',\n 'D0PiPiMassWindowWidthLow',\n 'D0PiPiMassWindowWidthHigh',\n 'D0KKMassWindowWidthLow',\n 'D0KKMassWindowWidthHigh',\n 'D0P',\n 'D0VtxChi2Ndof',\n 'D0Tau',\n 'D0FDChi2',\n 'D0BPVDira',\n 'D0DOCA',\n 'Daug_TRCHI2DOF_MAX',\n 'Dstar_AMDiff_MAX',\n 'Dstar_VCHI2VDOF_MAX',\n 'Dstar_MDiff_MAX',\n 'UntaggedCFLinePrescale',\n 'UntaggedCFLinePostscale',\n 'UntaggedSCSLinePrescale',\n 'UntaggedSCSLinePostscale',\n 'TaggedRSLinePrescale',\n 'TaggedRSLinePostscale',\n 'TaggedWSLinePrescale',\n 'TaggedWSLinePostscale',\n 'TaggedSCSLinePrescale',\n 'TaggedSCSLinePostscale',\n 'TaggedRSSSLinePrescale',\n 'TaggedRSSSLinePostscale',\n 'TaggedSCSSSLinePrescale',\n 'TaggedSCSSSLinePostscale',\n 'UntaggedTISLinePrescale',\n 'UntaggedTISLinePostscale',\n 'UntaggedKpiOnly',\n 'RunSameSign',\n 'RunTISLines',\n 'RunDefault',\n 'UseTOSFilter',\n 'AddPartialD',\n 'Hlt1TOS',\n 'Hlt2TOSKPi',\n 'Hlt2TOSKK',\n 'Hlt2TOSPiPi'\n )\n\n def __init__(self, name, config) :\n\n LineBuilder.__init__(self, name, config)\n\n stdNoPIDsKaons = StdAllNoPIDsKaons\n stdNoPIDsPions = StdAllNoPIDsPions\n\n d2kpi_name = name+'PromptD2KPi'\n d0RS_name = name+'PromptD0RS'\n d0WS_name = name+'PromptD0WS'\n d2kk_name = name+'PromptD2KK'\n d2pipi_name = name+'PromptD2PiPi'\n dst2DPiPi_name = name+'PromptDst2D2PiPi'\n dst2DKK_name = name+'PromptDst2D2KK'\n dst2DRS_name = name+'PromptDst2D2RS'\n dst2DWS_name = name+'PromptDst2D2WS'\n dPartial_name = name+'PromptDPartial'\n dstarPartial_name = name+'PromptDstarPartial'\n pseudoPsi_name = name+'PromptD0D0FromDstarPartial'\n\n # D0 -> hh' selections\n\n self.selD2Kpi = makeD2hhAsymm(d2kpi_name, \n config,\n KPIDK_string = ' & (PIDK > %(HighPIDK)s)',\n PiPIDK_string = ' & (PIDK < %(LowPIDK)s)',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0KPiMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0KPiMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = '',\n DecayDescriptor = '[D0 -> K- pi+]cc',\n inputSel = [stdNoPIDsPions, stdNoPIDsKaons],\n useTOS = config['UseTOSFilter'],\n Hlt1TOS = config['Hlt1TOS'],\n Hlt2TOS = config['Hlt2TOSKPi']\n )\n\n self.selD0WS = makeD2hhAsymm(d0WS_name, \n config,\n KPIDK_string = ' & (PIDK > %(HighPIDK)s)',\n PiPIDK_string = ' & (PIDK < %(LowPIDK)s)',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0KPiMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0KPiMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = '',\n DecayDescriptor = '[D0 -> K+ pi-]cc',\n inputSel = [stdNoPIDsPions, stdNoPIDsKaons],\n useTOS = config['UseTOSFilter'],\n Hlt1TOS = config['Hlt1TOS'],\n Hlt2TOS = config['Hlt2TOSKPi']\n )\n\n self.selD0KKsgl = makeD2hhAsymm(d2kk_name+'_single', \n config,\n KPIDK_string = ' & (PIDK > %(LowPIDK)s)',\n PiPIDK_string = '',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0KKMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0KKMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = ' & (AHASCHILD( PIDK > %(HighPIDK)s ) )',\n DecayDescriptor = 'D0 -> K+ K-',\n inputSel = [stdNoPIDsKaons],\n useTOS = config['UseTOSFilter'],\n Hlt1TOS = config['Hlt1TOS'],\n Hlt2TOS = config['Hlt2TOSKK']\n )\n\n self.selD0PiPisgl = makeD2hhAsymm(d2pipi_name+'_single', \n config,\n KPIDK_string = '',\n PiPIDK_string = ' & (PIDK < %(LowPIDK)s)',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0PiPiMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0PiPiMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = '',\n DecayDescriptor = 'D0 -> pi+ pi-',\n inputSel = [stdNoPIDsPions], \n useTOS = config['UseTOSFilter'],\n Hlt1TOS = config['Hlt1TOS'],\n Hlt2TOS = config['Hlt2TOSPiPi']\n )\n\n self.selD0KK = makeD2hhAsymm(d2kk_name, \n config,\n KPIDK_string = ' & (PIDK > %(LowPIDK)s)',\n PiPIDK_string = '',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0KKMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0KKMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = ' & (AHASCHILD( PIDK > %(HighPIDK)s ) )',\n DecayDescriptor = '[D0 -> K+ K-]cc',\n inputSel = [stdNoPIDsKaons],\n useTOS = config['UseTOSFilter'],\n Hlt1TOS = config['Hlt1TOS'],\n Hlt2TOS = config['Hlt2TOSKK']\n )\n\n self.selD0PiPi = makeD2hhAsymm(d2pipi_name, \n config,\n KPIDK_string = '',\n PiPIDK_string = ' & (PIDK < %(LowPIDK)s)',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0PiPiMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0PiPiMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = '',\n DecayDescriptor = '[D0 -> pi+ pi-]cc',\n inputSel = [stdNoPIDsPions], \n useTOS = config['UseTOSFilter'],\n Hlt1TOS = config['Hlt1TOS'],\n Hlt2TOS = config['Hlt2TOSPiPi']\n )\n\n self.selD2KpiSS = makeD2hhAsymm(d2kpi_name+'SS', \n config,\n KPIDK_string = ' & (PIDK > %(HighPIDK)s)',\n PiPIDK_string = ' & (PIDK < %(LowPIDK)s)',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0KPiMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0KPiMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = '',\n DecayDescriptor = '[D0 -> K- pi-]cc',\n inputSel = [stdNoPIDsPions, stdNoPIDsKaons],\n useTOS = False,\n Hlt1TOS = config['Hlt1TOS'],\n Hlt2TOS = config['Hlt2TOSKPi']\n )\n\n self.selD0KKSS = makeD2hhAsymm(d2kk_name+'SS', \n config,\n KPIDK_string = ' & (PIDK > %(LowPIDK)s)',\n PiPIDK_string = '',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0KKMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0KKMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = ' & (AHASCHILD( PIDK > %(HighPIDK)s ) )',\n DecayDescriptor = '[D0 -> K- K-]cc',\n inputSel = [stdNoPIDsKaons],\n useTOS = False,\n Hlt1TOS = config['Hlt1TOS'],\n Hlt2TOS = config['Hlt2TOSKK']\n )\n\n self.selD0PiPiSS = makeD2hhAsymm(d2pipi_name+'SS', \n config,\n KPIDK_string = '',\n PiPIDK_string = ' & (PIDK < %(LowPIDK)s)',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0PiPiMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0PiPiMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = '',\n DecayDescriptor = '[D0 -> pi- pi-]cc',\n inputSel = [stdNoPIDsPions], \n useTOS = False,\n Hlt1TOS = config['Hlt1TOS'],\n Hlt2TOS = config['Hlt2TOSPiPi']\n )\n\n self.selD2KpiTIS = makeD2hhAsymm(d2kpi_name+'TIS', \n config,\n KPIDK_string = ' & (PIDK > %(HighPIDK)s)',\n PiPIDK_string = ' & (PIDK < %(LowPIDK)s)',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0KPiMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0KPiMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = '',\n DecayDescriptor = '[D0 -> K- pi+]cc',\n inputSel = [stdNoPIDsPions, stdNoPIDsKaons],\n useTOS = True,\n Hlt1TOS = { 'Hlt1Global%TIS' : 0 },\n Hlt2TOS = { 'Hlt2Global%TIS' : 0 }\n )\n\n self.selD0KKTIS = makeD2hhAsymm(d2kk_name+'TIS', \n config,\n KPIDK_string = ' & (PIDK > %(LowPIDK)s)',\n PiPIDK_string = '',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0KKMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0KKMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = ' & (AHASCHILD( PIDK > %(HighPIDK)s ) )',\n DecayDescriptor = 'D0 -> K+ K-',\n inputSel = [stdNoPIDsKaons],\n useTOS = True,\n Hlt1TOS = { 'Hlt1Global%TIS' : 0 },\n Hlt2TOS = { 'Hlt2Global%TIS' : 0 }\n )\n\n self.selD0PiPiTIS = makeD2hhAsymm(d2pipi_name+'TIS', \n config,\n KPIDK_string = '',\n PiPIDK_string = ' & (PIDK < %(LowPIDK)s)',\n Mass_low_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) > %(D0PiPiMassWindowWidthLow)s* MeV)',\n Mass_high_string = '& (DAMASS(%(D0MassWindowCentre)s* MeV) < %(D0PiPiMassWindowWidthHigh)s* MeV)',\n CombPIDK_string = '',\n DecayDescriptor = 'D0 -> pi+ pi-',\n inputSel = [stdNoPIDsPions], \n useTOS = True,\n Hlt1TOS = { 'Hlt1Global%TIS' : 0 },\n Hlt2TOS = { 'Hlt2Global%TIS' : 0 }\n )\n\n # Dstar -> D0 pi selections\n self.selDstRS = makeDstar2D0Pi( dst2DRS_name\n , config\n , '[D*(2010)+ -> D0 pi+]cc'\n , inputSel = [self.selD2Kpi, stdNoPIDsPions]\n )\n\n self.selDstWS = makeDstar2D0Pi( dst2DWS_name\n , config\n , '[D*(2010)+ -> D0 pi+]cc'\n , inputSel = [self.selD0WS, stdNoPIDsPions]\n )\n\n self.selDstKK = makeDstar2D0Pi( dst2DKK_name\n , config\n , '[D*(2010)+ -> D0 pi+]cc'\n , inputSel = [self.selD0KK, stdNoPIDsPions]\n )\n\n self.selDstPiPi = makeDstar2D0Pi( dst2DPiPi_name\n , config\n , '[D*(2010)+ -> D0 pi+]cc'\n , inputSel = [self.selD0PiPi, stdNoPIDsPions]\n )\n\n self.selDstRSSS = makeDstar2D0Pi( dst2DRS_name+'SS'\n , config\n , '[D*(2010)+ -> D0 pi+]cc'\n , inputSel = [self.selD2KpiSS, stdNoPIDsPions]\n )\n\n self.selDstKKSS = makeDstar2D0Pi( dst2DKK_name+'SS'\n , config\n , '[D*(2010)+ -> D0 pi+]cc'\n , inputSel = [self.selD0KKSS, stdNoPIDsPions]\n )\n\n self.selDstPiPiSS = makeDstar2D0Pi( dst2DPiPi_name+'SS'\n , config\n , '[D*(2010)+ -> D0 pi+]cc'\n , inputSel = [self.selD0PiPiSS, stdNoPIDsPions]\n )\n\n self.selDPartial = makeDPartial( dPartial_name\n , config\n , '[D- -> K- pi- pi+]cc'\n , inputSel = [stdNoPIDsPions, stdNoPIDsKaons]\n )\n\n self.selDstarPartial = makeDstarPartial( dstarPartial_name\n , config\n , '[D*(2010)+ -> D- pi+]cc'\n , inputSel = [self.selDPartial, stdNoPIDsPions]\n )\n\n self.selPseudoPsi = makePseudoPsi( pseudoPsi_name\n , config\n , '[psi(3770) -> D0 D*(2010)+]cc'\n , inputSel = [self.selD2Kpi, self.selDstarPartial]\n )\n # Untagged lines\n self.d2kpi_line = StrippingLine(d2kpi_name+\"Line\",\n prescale = config['UntaggedCFLinePrescale'],\n postscale = config['UntaggedCFLinePostscale'],\n selection = self.selD2Kpi\n )\n\n self.d2kk_line = StrippingLine(d2kk_name+\"Line\",\n prescale = config['UntaggedSCSLinePrescale'],\n postscale = config['UntaggedSCSLinePostscale'],\n selection = self.selD0KKsgl\n )\n\n self.d2pipi_line = StrippingLine(d2pipi_name+\"Line\",\n prescale = config['UntaggedSCSLinePrescale'],\n postscale = config['UntaggedSCSLinePostscale'],\n selection = self.selD0PiPisgl\n )\n\n # Untagged TIS lines\n self.d2kpiTIS_line = StrippingLine(d2kpi_name+\"TISLine\",\n prescale = config['UntaggedTISLinePrescale'],\n postscale = config['UntaggedTISLinePostscale'],\n selection = self.selD2KpiTIS\n )\n\n self.d2kkTIS_line = StrippingLine(d2kk_name+\"TISLine\",\n prescale = config['UntaggedTISLinePrescale'],\n postscale = config['UntaggedTISLinePostscale'],\n selection = self.selD0KKTIS\n )\n\n self.d2pipiTIS_line = StrippingLine(d2pipi_name+\"TISLine\",\n prescale = config['UntaggedTISLinePrescale'],\n postscale = config['UntaggedTISLinePostscale'],\n selection = self.selD0PiPiTIS\n )\n\n # Tagged lines\n self.dstRS_line = StrippingLine(dst2DRS_name+\"Line\",\n prescale = config['TaggedRSLinePrescale'],\n postscale = config['TaggedRSLinePostscale'],\n selection = self.selDstRS\n )\n\n self.dstWS_line = StrippingLine(dst2DWS_name+\"Line\",\n prescale = config['TaggedWSLinePrescale'],\n postscale = config['TaggedWSLinePostscale'],\n selection = self.selDstWS\n )\n\n self.dstKK_line = StrippingLine(dst2DKK_name+\"Line\",\n prescale = config['TaggedSCSLinePrescale'],\n postscale = config['TaggedSCSLinePostscale'],\n selection = self.selDstKK\n )\n\n self.dstPiPi_line = StrippingLine(dst2DPiPi_name+\"Line\",\n prescale = config['TaggedSCSLinePrescale'],\n postscale = config['TaggedSCSLinePostscale'],\n selection = self.selDstPiPi\n )\n\n # Tagged same sign lines\n self.dstRSSS_line = StrippingLine(dst2DRS_name+\"SSLine\",\n prescale = config['TaggedRSLinePrescale'],\n postscale = config['TaggedRSLinePostscale'],\n selection = self.selDstRSSS\n )\n\n self.dstKKSS_line = StrippingLine(dst2DKK_name+\"SSLine\",\n prescale = config['TaggedSCSLinePrescale'],\n postscale = config['TaggedSCSLinePostscale'],\n selection = self.selDstKKSS\n )\n\n self.dstPiPiSS_line = StrippingLine(dst2DPiPi_name+\"SSLine\",\n prescale = config['TaggedSCSLinePrescale'],\n postscale = config['TaggedSCSLinePostscale'],\n selection = self.selDstPiPiSS\n )\n\n # Pseudo Psi line\n if config['AddPartialD']:\n self.pseudoPsi_line = StrippingLine(pseudoPsi_name+\"Line\",\n prescale = 1.,\n postscale = 1.,\n selection = self.selPseudoPsi\n )\n\n # register lines\n if config['RunSameSign']:\n self.registerLine(self.dstRSSS_line)\n self.registerLine(self.dstKKSS_line)\n self.registerLine(self.dstPiPiSS_line)\n\n if config['RunTISLines']:\n self.registerLine(self.d2kpiTIS_line)\n self.registerLine(self.d2kkTIS_line)\n self.registerLine(self.d2pipiTIS_line)\n\n if config['RunDefault']:\n self.registerLine(self.d2kpi_line)\n if not config['UntaggedKpiOnly']:\n self.registerLine(self.d2kk_line)\n self.registerLine(self.d2pipi_line)\n\n self.registerLine(self.dstRS_line)\n self.registerLine(self.dstWS_line)\n self.registerLine(self.dstKK_line)\n self.registerLine(self.dstPiPi_line)\n if config['AddPartialD']:\n self.registerLine(self.pseudoPsi_line)\n\ndef makeD2hhAsymm(name,\n config,\n KPIDK_string,\n PiPIDK_string,\n Mass_low_string,\n Mass_high_string,\n CombPIDK_string,\n DecayDescriptor,\n inputSel,\n useTOS,\n Hlt1TOS,\n Hlt2TOS\n ) :\n \"\"\"\n Create and return a D0 -> hh' Selection object.\n Arguments:\n name : name of the Selection.\n config : dictionary of cut values.\n ..._string : cut implementation for PIDK cuts.\n DecayDescriptor: DecayDescriptor.\n inputSel : input selections\n \"\"\"\n\n def makeTISTOS( name, _input, _hlttos ) :\n from Configurables import TisTosParticleTagger\n _tisTosFilter = TisTosParticleTagger( name + \"Tagger\" )\n _tisTosFilter.TisTosSpecs = _hlttos\n return Selection( name\n , Algorithm = _tisTosFilter\n , RequiredSelections = [ _input ]\n ) \n\n _Kcuts1 = \"~ISMUON & (PT > %(DaugPtMin)s* MeV) & (MIPCHI2DV(PRIMARY) > %(DaugIPChi2)s)\" % locals()['config']\n _KcutsPIDK = KPIDK_string % locals()['config']\n _Kcuts2 = \" & (ISLONG) & (P > %(DaugP)s* MeV) & (TRCHI2DOF < %(DaugTrkChi2)s)\" % locals()['config']\n _Kcuts = _Kcuts1 + _KcutsPIDK + _Kcuts2\n _Picuts1 = \"~ISMUON & (PT > %(DaugPtMin)s* MeV) & (MIPCHI2DV(PRIMARY) > %(DaugIPChi2)s)\" % locals()['config']\n _PicutsPIDK = PiPIDK_string % locals()['config']\n _Picuts2 = \" & (ISLONG) & (P > %(DaugP)s* MeV) & (TRCHI2DOF < %(DaugTrkChi2)s)\" % locals()['config']\n _Picuts = _Picuts1 + _PicutsPIDK + _Picuts2\n _dauCuts = { 'K+': _Kcuts, 'pi+': _Picuts }\n\n _massLow = Mass_low_string % locals()['config']\n _massHigh = Mass_high_string % locals()['config']\n _combCuts1 = \"(APT > %(D0Pt)s* MeV)\" \\\n \"& (AHASCHILD( PT > %(DaugPtMax)s* MeV ) )\" \\\n \"& (ADOCA(1,2)< %(D0DOCA)s* mm)\" \\\n \"& (AP > %(D0P)s* MeV)\" % locals()['config']\n _combCutsPIDK = CombPIDK_string % locals()['config']\n _combCuts = _combCuts1 + _combCutsPIDK + _massLow + _massHigh\n\n _motherCuts = \"(VFASPF(VCHI2PDOF) < %(D0VtxChi2Ndof)s)\" \\\n \"& (BPVVDCHI2 > %(D0FDChi2)s)\" \\\n \"& (BPVLTIME() > %(D0Tau)s)\" \\\n \"& (BPVDIRA > %(D0BPVDira)s)\" % locals()['config']\n\n _D0 = CombineParticles( DecayDescriptor = DecayDescriptor,\n MotherCut = _motherCuts,\n CombinationCut = _combCuts,\n DaughtersCuts = _dauCuts)\n\n _sel = Selection ( name+'Sel',\n Algorithm = _D0,\n RequiredSelections = inputSel )\n\n if not useTOS:\n return _sel\n\n _selD2hhHlt1TOS = makeTISTOS( name + \"D2hhHlt1TOS\"\n , _sel\n , Hlt1TOS\n )\n _selD2hhHlt2TOS = makeTISTOS( name + \"D2hhHlt2TOS\"\n , _selD2hhHlt1TOS\n , Hlt2TOS\n )\n \n return _selD2hhHlt2TOS\n\ndef makeDstar2D0Pi( name\n , config\n , DecayDescriptor\n , inputSel\n ) :\n\n \"\"\"\n Create and return a D* -> D0 pi Selection object.\n Arguments:\n name : name of the Selection.\n config : dictionary of cut values.\n DecayDescriptor: DecayDescriptor.\n inputSel : input selections\n \"\"\"\n\n daugCuts = \"(TRCHI2DOF < %(Daug_TRCHI2DOF_MAX)s)\" % locals()['config']\n combCuts = \"((AM - AM1) < %(Dstar_AMDiff_MAX)s* MeV)\" % locals()['config']\n dstarCuts = \"(VFASPF(VCHI2/VDOF) < %(Dstar_VCHI2VDOF_MAX)s)\" \\\n \"& ((M - M1) < %(Dstar_MDiff_MAX)s* MeV)\" % locals()['config']\n\n _Dstar = CombineParticles( DecayDescriptor = DecayDescriptor\n , DaughtersCuts = { \"pi+\" : daugCuts }\n , CombinationCut = combCuts\n , MotherCut = dstarCuts\n )\n\n return Selection( name+'Sel',\n Algorithm = _Dstar,\n RequiredSelections = inputSel\n )\n\ndef makeDPartial( name\n , config\n , DecayDescriptor\n , inputSel\n ) :\n\n \"\"\"\n Create and return a D- -> K- pi- pi+ Selection object.\n Arguments:\n name : name of the Selection.\n config : dictionary of cut values.\n DecayDescriptor: DecayDescriptor.\n inputSel : input selections\n \"\"\"\n\n _Kcuts1 = \"~ISMUON & (PT > %(DaugPtLoose)s* MeV) & (MIPCHI2DV(PRIMARY) > %(DaugIPChi2Loose)s)\" % locals()['config']\n _KcutsPIDK = \" & (PIDK > %(HighPIDK)s)\" % locals()['config']\n _Kcuts2 = \" & (ISLONG) & (P > %(DaugPLoose)s* MeV) & (TRCHI2DOF < %(DaugTrkChi2Loose)s)\" % locals()['config']\n _Kcuts = _Kcuts1 + _KcutsPIDK + _Kcuts2\n _Picuts1 = \"~ISMUON & (PT > %(DaugPtMin)s* MeV) & (MIPCHI2DV(PRIMARY) > %(DaugIPChi2)s)\" % locals()['config']\n _PicutsPIDK = \" & (PIDK < %(LowPIDK)s)\" % locals()['config']\n _Picuts2 = \" & (ISLONG) & (P > %(DaugP)s* MeV) & (TRCHI2DOF < %(DaugTrkChi2)s)\" % locals()['config']\n _Picuts = _Picuts1 + _PicutsPIDK + _Picuts2\n _dauCuts = { 'K+': _Kcuts, 'pi+': _Picuts }\n #_Kcuts1 = \"~ISMUON & (PT > 500* MeV) & (MIPCHI2DV(PRIMARY) > 4)\"\n #_KcutsPIDK = \" & (PIDK > 5)\"\n #_Kcuts2 = \" & (ISLONG) & (P > 5000* MeV) & (TRCHI2DOF < 5)\"\n #_Kcuts = _Kcuts1 + _KcutsPIDK + _Kcuts2\n #_Picuts1 = \"~ISMUON & (PT > 500* MeV) & (MIPCHI2DV(PRIMARY) > 4)\"\n #_PicutsPIDK = \" & (PIDK < 0)\"\n #_Picuts2 = \" & (ISLONG) & (P > 5000* MeV) & (TRCHI2DOF < 5)\"\n #_Picuts = _Picuts1 + _PicutsPIDK + _Picuts2\n #_dauCuts = { 'K+': _Kcuts, 'pi+': _Picuts }\n\n _combCuts = \"(APT > %(D0PtLoose)s* MeV)\" \\\n \"& (AP > %(D0P)s* MeV)\" % locals()['config']\n\n _motherCuts = \"(VFASPF(VCHI2PDOF) < %(D0VtxChi2Ndof)s)\" \\\n \"& (BPVVDCHI2 > %(D0FDChi2)s)\" % locals()['config']\n\n\n _Dminus = CombineParticles( DecayDescriptor = DecayDescriptor\n , DaughtersCuts = _dauCuts\n , CombinationCut = _combCuts\n , MotherCut = _motherCuts\n )\n\n return Selection( name+'Sel',\n Algorithm = _Dminus,\n RequiredSelections = inputSel\n )\n\ndef makeDstarPartial( name\n , config\n , DecayDescriptor\n , inputSel\n ) :\n\n \"\"\"\n Create and return a D*+ -> D- pi+ Selection object.\n Arguments:\n name : name of the Selection.\n config : dictionary of cut values.\n DecayDescriptor: DecayDescriptor.\n inputSel : input selections\n \"\"\"\n\n daugCuts = \"(TRCHI2DOF < %(Daug_TRCHI2DOF_MAX)s)\" % locals()['config']\n combCuts = \"((AM - AM1) < %(Dstar_AMDiff_MAX)s* MeV)\" % locals()['config']\n dstarCuts = \"(VFASPF(VCHI2/VDOF) < %(Dstar_VCHI2VDOF_MAX)s)\" \\\n \"& ((M - M1) < %(Dstar_MDiff_MAX)s* MeV)\" % locals()['config']\n\n _Dstar = CombineParticles( DecayDescriptor = DecayDescriptor\n , DaughtersCuts = { \"pi+\" : daugCuts }\n , CombinationCut = combCuts\n , MotherCut = dstarCuts\n )\n\n return Selection( name+'Sel',\n Algorithm = _Dstar,\n RequiredSelections = inputSel\n )\n\ndef makePseudoPsi( name\n , config\n , DecayDescriptor\n , inputSel\n ) :\n\n \"\"\"\n Create and return a D* -> D0 pi Selection object.\n Arguments:\n name : name of the Selection.\n config : dictionary of cut values.\n DecayDescriptor: DecayDescriptor.\n inputSel : input selections\n \"\"\"\n\n _daugCuts = \"(PT> %(D0PtLoose)s*MeV)\" % locals()['config']\n _combCuts = \"(APT> %(D0PtLoose)s*MeV)\" % locals()['config']\n\n _Psi = CombineParticles( DecayDescriptor = DecayDescriptor\n , DaughtersCuts = { \"D0\": _daugCuts }\n , CombinationCut = _combCuts\n , MotherCut = \"(VFASPF(VCHI2PDOF) < 10000)\"\n )\n\n return Selection( name+'Sel',\n Algorithm = _Psi,\n RequiredSelections = inputSel\n )\n\n","sub_path":"DaVinciDev_v38r1p1/InstallArea/x86_64-slc6-gcc49-opt/python/StrippingArchive/Stripping23r1/StrippingCharm/StrippingD2hh.py","file_name":"StrippingD2hh.py","file_ext":"py","file_size_in_byte":36025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"48788166","text":"# basic imports\nfrom lingValUI import Ui_Dialog # make baby\nfrom PyQt5.QtCore import pyqtSlot\nfrom PyQt5.QtWidgets import QDialog, QApplication\nimport openpyxl\nimport docx\nfrom pathlib import Path\nimport re\nfrom PyQt5 import QtWidgets\nimport modules\n\n\nclass Dialog(QDialog, Ui_Dialog):\n \"\"\"\n Copy and paste from ORT to excel or vice versa\n \"\"\"\n def __init__(self, parent=None):\n super(Dialog, self).__init__(parent)\n self.setupUi(self)\n # self.pushButton.clicked.connect(self.buttonClicked) # alternative way to call your method\n #\n # def buttonClicked(self):\n # # write code\n\n @pyqtSlot() # decorator\n def on_pushButton_clicked(self):\n \"\"\"\n Write what this method does\n \"\"\"\n\n ft_file_path = Path(self.lineEditPath1.text())\n bt_file_path = Path(self.lineEditPath2.text())\n xls_file_path = Path(self.lineEditPath3.text())\n modules.removeCheckbox(xls_file_path)\n if self.checkBox.isChecked():\n hideTwoRows = True\n else:\n hideTwoRows = False\n front_user_column = int(self.excelSourceColumn.text())\n back_user_column = int(self.excelTargetColumn.text())\n for file in ft_file_path.iterdir():\n if file.suffix == \".docx\":\n front_doc, front_lp = modules.extractfileNameandFileLP(file)\n if front_lp == \"\":\n QtWidgets.QMessageBox.information(self, \"Error!\", \"Please make sure LP is present in the file name and in '-xx-XX' format \")\n exit()\n bt_file_name = modules.findBTmatch(front_doc, front_lp, bt_file_path)\n xls_file_name = modules.findXLSmatch(front_doc, front_lp, xls_file_path)\n if bt_file_name is None:\n QtWidgets.QMessageBox.information(self, \"Error!\", \"BT file match not found, skipping {0}\".format(file.name))\n continue\n if xls_file_name is None:\n print(front_doc)\n print(front_lp)\n QtWidgets.QMessageBox.information(self, \"Error!\", \"XLS match not found, skipping {0}\".format(file.name))\n continue\n front_doc = docx.Document(file)\n back_doc = docx.Document(bt_file_name)\n xls_file = openpyxl.load_workbook(xls_file_name)\n ft_ort_table = modules.extract_table_values(front_doc.tables[2])\n bt_ort_table = modules.extract_table_values(back_doc.tables[2])\n active_sheet = xls_file.active\n if hideTwoRows:\n active_sheet.row_dimensions[1].hidden = True\n active_sheet.row_dimensions[2].hidden = True\n xls_file.save(str(xls_file_name))\n if self.rbOption1.isChecked():\n modules.RecontoORT(front_doc.tables[2], back_doc.tables[2], xls_file, front_user_column, back_user_column)\n front_doc.save(str(file))\n back_doc.save(str(bt_file_name))\n if self.rbOption2.isChecked():\n modules.ORTtoRecon(ft_ort_table, bt_ort_table, active_sheet,front_user_column, back_user_column)\n xls_file.save(str(xls_file_name))\n elif file.suffix == \".doc\":\n QtWidgets.QMessageBox.information(self, \"Wrong file format\", \"{0} is a doc, please convert to docx\".format(file.name))\n continue\n QtWidgets.QMessageBox.information(self, \"Done!\", \"Macro finished\")\n\n\n\nif __name__ == \"__main__\":\n import sys\n application = QApplication(sys.argv)\n macro_dialog = Dialog() # create object of dialog, **use the name of your dialog**\n macro_dialog.show()\n sys.exit(application.exec_())\n\n\n\n","sub_path":"lingValMacro.py","file_name":"lingValMacro.py","file_ext":"py","file_size_in_byte":3806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"322961957","text":"from django.db import models\n\n# Create your models here.\nclass ControlWork(models.Model):\n question_count = models.IntegerField()\n\n\nclass Block(models.Model):\n name = models.CharField(max_length=200)\n control_work = models.ManyToManyField(ControlWork)\n\n\nclass Ticket(models.Model):\n control_work = models.ForeignKey(ControlWork, null=True)\n\n\nclass Question(models.Model):\n text = models.CharField(max_length=500)\n block = models.ForeignKey(Block, null=True)\n ticket = models.ManyToManyField(Ticket)\n\n\n\n\n","sub_path":"exam/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"58162924","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/solo/configurator/view.py\n# Compiled at: 2016-03-29 19:16:41\n# Size of source mod 2**32: 3021 bytes\nimport logging\nfrom typing import List\nfrom .config.routes import RouteItem\nfrom aiohttp.web import Request, Response, HTTPNotFound\nimport venusian\nlog = logging.getLogger(__name__)\n\nclass http_endpoint(object):\n venusian = venusian\n\n def __init__(self, **settings):\n self.__dict__.update(settings)\n\n def __call__(self, wrapped):\n settings = self.__dict__.copy()\n depth = settings.pop('_depth', 0)\n\n def callback(scanner, name, obj):\n scanner.config.add_view(view=obj, **settings)\n\n info = self.venusian.attach(wrapped, callback, category='solo', depth=depth + 1)\n if info.scope == 'class' and settings.get('attr') is None:\n settings['attr'] = wrapped.__name__\n return wrapped\n\n\nclass http_defaults(http_endpoint):\n __doc__ = ' This object is a copy of ``pyramid.view.view_defaults``.\\n\\n A class :term:`decorator` which, when applied to a class, will\\n provide defaults for all view configurations that use the class. This\\n decorator accepts all the arguments accepted by\\n :meth:`pyramid.view.view_config`, and each has the same meaning.\\n\\n See :ref:`view_defaults` for more information.\\n '\n\n def __call__(self, wrapped):\n wrapped.__view_defaults__ = self.__dict__.copy()\n return wrapped\n\n\nclass PredicatedHandler:\n __slots__ = [\n 'viewlist']\n\n def __init__(self, viewlist: List[RouteItem]):\n self.viewlist = viewlist\n\n def __call__(self, request: Request):\n \"\"\" Resolve predicates here.\n \"\"\"\n for route_item in self.viewlist:\n for predicate in route_item.predicates:\n if not predicate(None, request):\n log.debug('Predicate {} failed for {} {}'.format(predicate, request.method, request.path_qs))\n break\n else:\n log.debug('{} {} will be handled by {}'.format(request.method, request.path_qs, route_item.view))\n handler = route_item.view\n if route_item.attr:\n handler = getattr(handler(request), route_item.attr)\n response = await handler()\n else:\n response = await handler(request)\n if isinstance(response, Response):\n return response\n else:\n renderer = route_item.renderer\n return renderer(request, response)\n\n log.debug('All predicates have failed for {} {}'.format(request.method, request.path_qs))\n raise HTTPNotFound()","sub_path":"pycfiles/solo-0.0.1-py3.5/view.cpython-35.py","file_name":"view.cpython-35.py","file_ext":"py","file_size_in_byte":2867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"208928192","text":"import numpy as np\nimport sys\nimport matplotlib.pyplot as plot\nimport cilia.util\n\nif __name__ == '__main__':\n\t# Read name of ROI.\n\tif len(sys.argv) < 2 or len(sys.argv) > 4:\n\t\tquit('python view_roi.py [start pixel] [end pixel]')\n\troi = sys.argv[1]\n\n\t# Read the mat file.\n\tcurl = cilia.util.read_cilia_dict(roi, 'allRotData')\n\tdefo = cilia.util.read_cilia_dict(roi, 'allDefData')\n\n\t# Constrain the borders by 3 pixels each.\n\tcurl = curl[3:np.size(curl, axis = 0) - 4, 3:np.size(curl, axis = 1) - 4]\n\tdefo = defo[3:np.size(defo, axis = 0) - 4, 3:np.size(defo, axis = 1) - 4]\n\n\t# Perform filtering.\n\tcurl = curl[np.where(np.std(curl, axis = 1) > np.mean(np.std(curl, axis = 1)))[0], :]\n\tdefo = defo[np.where(np.std(defo, axis = 1) > np.mean(np.std(defo, axis = 1)))[0], :]\n\n\tif len(sys.argv) == 2:\n\t\tquit('Pixels: %s' % np.size(curl, axis = 0))\n\tstart = int(sys.argv[2])\n\tif len(sys.argv) == 3:\n\t\tend = start + 1\n\telse:\n\t\tend = int(sys.argv[3])\n\n\tplot.figure(0)\n\tplot.imshow(defo[start:end]) if end > start + 1 else plot.plot(defo[start])\n\tplot.title('Deformation')\n\n\tplot.figure(1)\n\tplot.imshow(curl[start:end]) if end > start + 1 else plot.plot(defo[start])\n\tplot.title('Curl')\n\t\n\tplot.show()\n","sub_path":"python/cilia/visualizations/view_pixels.py","file_name":"view_pixels.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"266455692","text":"# coding: utf-8\nfrom collections import OrderedDict\n\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.db.models import F, Q, Count\nfrom django.db.models.query import QuerySet\nfrom django.db.models.signals import post_save, pre_delete, m2m_changed\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils import timezone\nfrom django.utils.translation import ugettext as _\n\nfrom model_utils.managers import PassThroughManager\nfrom django_fsm import FSMField, transition\n\nfrom .exceptions import (\n ComponentAlreadyInstalled, ComponentNotInstalled, ComponentNotSupported,\n ComponentIsBroken, RackIsFilled, BasketIsFilled, BasketSlotIsBusy,\n ServerHasNoFreeSlotForComponent, RackUnitIsBusy)\nfrom .defaults import (\n PROPERTY_TEXT_FIELD, PROPERTY_SELECT_FIELD,\n PROPERTY_NUMBER_FIELD, PROPERTY_FIELD_CHOICES,\n ComponentState)\n\n\nclass CreatedModel(models.Model):\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n class Meta:\n abstract = True\n ordering = ['-updated_at']\n\n\n@python_2_unicode_compatible\nclass NamedModel(models.Model):\n name = models.CharField(\n max_length=255,\n verbose_name=_('Name'),\n blank=False,\n null=False)\n\n class Meta:\n abstract = True\n\n def __str__(self):\n return self.name\n\n def get_name(self):\n return self.name\n\n\nclass Node(CreatedModel, NamedModel):\n \"\"\"\n Узел (дата-центр)\n \"\"\"\n address = models.TextField(\n blank=True)\n servers_count = models.PositiveIntegerField(\n default=0,\n editable=False)\n\n class Meta:\n verbose_name = _('Node')\n verbose_name_plural = _('Nodes')\n\n @property\n def href(self):\n return reverse('api:node-detail', args=[self.pk])\n\n def get_server_list(self):\n return self.servers.all()\n\n\nclass Floor(CreatedModel, NamedModel):\n \"\"\"\n Этаж\n \"\"\"\n node = models.ForeignKey(Node)\n\n class Meta:\n verbose_name = _('Floor')\n verbose_name_plural = _('Floors')\n\n @property\n def href(self):\n return reverse('api:floor-detail', args=[self.pk])\n\n def get_node(self):\n return self.node\n\n def get_server_list(self):\n return self.servers.all()\n\n\nclass Room(CreatedModel, NamedModel):\n \"\"\"\n Помещение\n \"\"\"\n node = models.ForeignKey(Node, blank=True, null=True)\n floor = models.ForeignKey(Floor)\n\n class Meta:\n verbose_name = _('Room')\n verbose_name_plural = _('Rooms')\n\n @property\n def href(self):\n return reverse('api:room-detail', args=[self.pk])\n\n def save(self, *args, **kwargs):\n if self.floor:\n self.node = self.floor.get_node()\n\n return super(Room, self).save(*args, **kwargs)\n\n def get_node(self):\n return self.node\n\n def get_floor(self):\n return self.floor\n\n def get_server_list(self):\n return self.servers.all()\n\n\nclass Row(CreatedModel, NamedModel):\n \"\"\"\n Ряд\n \"\"\"\n node = models.ForeignKey(Node, blank=True, null=True)\n floor = models.ForeignKey(Floor, blank=True, null=True)\n room = models.ForeignKey(Room)\n\n class Meta:\n verbose_name = _('Row')\n verbose_name_plural = _('Rows')\n\n @property\n def href(self):\n return reverse('api:row-detail', args=[self.pk])\n\n def save(self, *args, **kwargs):\n if self.room:\n self.node = self.room.get_node()\n self.floor = self.room.get_floor()\n return super(Row, self).save(*args, **kwargs)\n\n def get_node(self):\n return self.node\n\n def get_floor(self):\n return self.floor\n\n def get_room(self):\n return self.room\n\n def get_server_list(self):\n return self.servers.all()\n\n\nclass RackQuerySet(QuerySet):\n\n def with_fullness(self, fullness=None, height=1):\n \"\"\"\n Valid values for 'fullness': all | empty | has_empty | filled | has_empty_height\n \"\"\"\n if not fullness or fullness == 'all':\n return self.all()\n\n elif fullness == 'empty':\n return self.filter(max_gap=F('total_units'))\n\n elif fullness == 'has_empty':\n return self.filter(max_gap__gt=0)\n\n elif fullness == 'has_empty_height':\n try:\n height = int(height) if height is not None else 1\n except ValueError:\n height = 1\n return self.filter(max_gap__gte=height)\n\n elif fullness == 'filled':\n return self.filter(max_gap=0)\n\n raise ValueError('Unsupported fullness value. Must be one of the following values: '\n 'all | empty | has_empty | filled | has_empty_height.')\n\n\nclass Rack(CreatedModel, NamedModel):\n \"\"\"\n Стойка\n \"\"\"\n node = models.ForeignKey(Node,\n blank=True, null=True)\n row = models.ForeignKey(Row)\n total_units = models.PositiveSmallIntegerField(\n verbose_name=_('total units'),\n default=1)\n max_gap = models.PositiveSmallIntegerField(\n verbose_name=_('max gap'),\n default=0)\n\n objects = PassThroughManager.for_queryset_class(RackQuerySet)()\n\n class Meta:\n verbose_name = _('Rack')\n verbose_name_plural = _('Racks')\n\n @property\n def href(self):\n return reverse('api:rack-detail', args=[self.pk])\n\n @property\n def floor(self):\n return self.get_floor()\n\n @property\n def room(self):\n return self.get_room()\n\n def save(self, *args, **kwargs):\n if not self.id:\n self.max_gap = self.total_units\n else:\n try:\n gaps = [g['height'] for g in self.find_gaps()]\n except:\n gaps = []\n self.max_gap = max(gaps) if len(gaps) else 0\n self.node = self.row.get_node()\n return super(Rack, self).save(*args, **kwargs)\n\n def get_node(self):\n return self.node\n\n def get_floor(self):\n return self.row.get_floor()\n\n def get_room(self):\n return self.row.get_room()\n\n def get_row(self):\n return self.row\n\n def get_server_list(self):\n return self.servers.all()\n\n def find_gaps(self):\n last_unit = None\n gaps = []\n for unit in self.units.all().order_by('position'):\n # if first server/basket in the rack\n if last_unit is None:\n if unit.position > 1:\n gaps.append({\n 'height': unit.position - 1,\n 'position': 1\n })\n # otherwise\n else:\n last_unit_ends = last_unit.position + last_unit.unit_takes - 1\n # there is a gap between last unit and current\n if (unit.position - last_unit_ends) > 1:\n gaps.append({\n 'height': unit.position - last_unit_ends - 1,\n 'position': last_unit_ends + 1\n })\n last_unit = unit\n\n # does last server/basket in the rack take all units till rack bottom (floor)\n # or there is a gap there?\n if last_unit and \\\n last_unit.position != self.total_units and \\\n (last_unit.position + last_unit.unit_takes - 1) < self.total_units:\n last_unit_ends = last_unit.position + last_unit.unit_takes - 1\n gaps.append({\n 'height': self.total_units - last_unit_ends,\n 'position': last_unit_ends + 1\n })\n\n # in this case rack is empty\n elif last_unit is None:\n gaps.append({\n 'height': self.total_units,\n 'position': 1\n })\n\n return gaps\n\n def find_position_of_height(self, height):\n for gap in self.find_gaps():\n if gap['height'] >= height:\n return gap['position']\n\n raise RackIsFilled\n\n def validate_position(self, position):\n if self.units.filter(position=position).exists():\n raise RackUnitIsBusy\n\n def mount(self, server=None, basket=None, position=None, height=None):\n if height is None:\n if server:\n height = server.get_height()\n elif basket:\n height = basket.get_height()\n else:\n raise ValueError('Specify of server/basket to mount it.')\n\n if position is None:\n position = self.find_position_of_height(height)\n\n self.validate_position(position)\n\n unit_kwargs = {\n 'rack': self,\n 'position': position,\n }\n if basket is not None:\n unit_kwargs['basket'] = basket\n unit_entity = basket\n elif server is not None:\n unit_kwargs['server'] = server\n unit_entity = server\n else:\n raise ValuerError('You cannot mount server and basket at the same time.')\n\n unit_entity.node = self.node\n unit_entity.rack = self\n unit_entity.save()\n\n return Unit.objects.get_or_create(**unit_kwargs)\n\n def unmount(self, server=None, basket=None):\n query = Q(rack=self)\n if basket is not None:\n query &= Q(basket=basket)\n unit_entity = basket\n elif server is not None:\n query &= Q(server=server)\n unit_entity = server\n else:\n raise ValuerError('You cannot unmount server and basket at the same time.')\n Unit.objects.filter(query).delete()\n unit_entity.node = None\n unit_entity.rack = None\n unit_entity.save()\n\n\nclass Unit(CreatedModel, models.Model):\n \"\"\"\n Описывает юнит\n \"\"\"\n rack = models.ForeignKey(\n Rack,\n related_name='units')\n position = models.PositiveSmallIntegerField(default=1)\n basket = models.ForeignKey(\n 'Basket',\n related_name='units',\n blank=True, null=True)\n server = models.ForeignKey(\n 'Server',\n related_name='units',\n blank=True, null=True)\n\n class Meta:\n verbose_name = _('Unit')\n verbose_name_plural = _('Units')\n\n @property\n def unit_takes(self):\n if self.basket:\n return self.basket.get_height()\n\n elif self.server:\n return self.server.get_height()\n\n raise AttributeError\n\n\nclass ComponentQuerySet(QuerySet):\n\n def of_kind(self, kind=None):\n if not kind:\n return self.all()\n\n query = Q(property__name='component.kind')\n try:\n query &= Q(id=int(kind))\n except ValueError:\n query &= Q(name=kind)\n\n try:\n po = PropertyOption.objects.get(query)\n except PropertyOption.DoesNotExist:\n return self.none()\n\n return self.filter(kind=po)\n\n def with_state(self, state=None):\n if not state or ComponentState.show_all(state):\n return self.all()\n\n if not ComponentState.is_valid(state):\n return self.none()\n\n return self.filter(state=state)\n\n\nclass Component(CreatedModel, NamedModel):\n manufacturer = models.CharField(max_length=200)\n model_name = models.CharField(max_length=200)\n serial_number = models.CharField(max_length=200)\n state = FSMField(\n default=ComponentState.FREE,\n verbose_name=_('Component State'),\n choices=ComponentState.CHOICES,\n protected=False)\n server = models.ForeignKey(\n 'Server',\n related_name='components',\n blank=True, null=True)\n kind = models.ForeignKey(\n 'PropertyOption',\n related_name='kind_opts',\n limit_choices_to={'property__name': 'component.kind'})\n\n objects = PassThroughManager.for_queryset_class(ComponentQuerySet)()\n\n class Meta:\n verbose_name = _('Component')\n verbose_name_plural = _('Components')\n\n @property\n def href(self):\n return reverse('api:component-detail', args=[self.pk])\n\n @transition(field=state, source=[ComponentState.FREE], target=ComponentState.INSTALLED)\n def install(self, server=None):\n \"\"\"\n Install component.\n \"\"\"\n self.server = server\n\n @transition(field=state, source=[ComponentState.INSTALLED], target=ComponentState.FREE)\n def uninstall(self):\n \"\"\"\n Uninstall component.\n \"\"\"\n self.server = None\n\n @transition(field=state, source='*', target=ComponentState.BROKEN)\n def broken(self):\n \"\"\"\n Component is broken.\n \"\"\"\n\n def get_properties(self):\n ret = []\n group = PropertyGroup.objects.get(name=self.kind.name)\n values = ComponentPropertyValue.objects.filter(component=self)\n values_bulk = dict([(v.property_id, v) for v in values])\n for prop in group.properties.all():\n ret.append({\n 'id': prop.pk,\n 'name': prop.name,\n 'title': prop.title,\n 'type': prop.type,\n 'property': prop,\n 'value': values_bulk.get(prop.pk, None),\n })\n return ret\n\n def is_installed(self):\n return self.state == ComponentState.INSTALLED\n\n def is_free(self):\n return self.state == ComponentState.FREE\n\n def is_broken(self):\n return self.state == ComponentState.BROKEN\n\n def is_uninstalled(self):\n return self.is_free() or self.is_broken()\n\n\nclass PropertyGroup(models.Model):\n \"\"\"\n Groups component properties together.\n Can belong to several servers components, servers components can\n have several groups.\n **Attributes:**\n name\n The name of the property group.\n servers components\n The assigned servers components of the property group.\n\n \"\"\"\n name = models.CharField(\n _(u\"Name\"),\n blank=True,\n max_length=50)\n components = models.ManyToManyField(\n Component,\n blank=True,\n verbose_name=_(u\"Servers Components\"),\n related_name=\"property_groups\")\n position = models.IntegerField(\n _(u\"Position\"),\n default=1000)\n\n class Meta:\n ordering = (\"position\", )\n\n def __str__(self):\n return self.name\n\n\nclass PropertyQuerySet(QuerySet):\n\n def of_kind(self, kind=None):\n if kind is None:\n return self.all()\n\n return self.filter(name__startswith='{}.'.format(kind))\n\n\nclass Property(models.Model):\n \"\"\"\n Represents a property of a server like cpu or hdd.\n A property has several ``PropertyOptions`` from which the user can choose\n (like 512mb, 1gb, 1tb).\n A property belongs to exactly one group xor server.\n \"\"\"\n name = models.CharField(\n _(u\"Name\"),\n max_length=100)\n title = models.CharField(\n _(u\"Title\"),\n max_length=100)\n groups = models.ManyToManyField(\n PropertyGroup,\n verbose_name=_(u\"Group\"),\n blank=True,\n through=\"GroupsPropertiesRelation\",\n related_name=\"properties\")\n components = models.ManyToManyField(\n Component,\n verbose_name=_(u\"Components\"),\n blank=True,\n through=\"ComponentsPropertiesRelation\",\n related_name=\"properties\")\n position = models.IntegerField(\n _(u\"Position\"),\n blank=True, null=True)\n unit = models.CharField(\n _(u\"Unit\"),\n blank=True,\n max_length=15)\n\n type = models.PositiveSmallIntegerField(\n _(u\"Type\"),\n choices=PROPERTY_FIELD_CHOICES,\n default=PROPERTY_TEXT_FIELD)\n\n required = models.BooleanField(_(u\"Required\"), default=False)\n\n\n objects = PassThroughManager.for_queryset_class(PropertyQuerySet)()\n\n class Meta:\n verbose_name_plural = _(u\"Properties\")\n ordering = [\"position\"]\n\n def __str__(self):\n return self.name\n\n @property\n def is_select_field(self):\n return self.type == PROPERTY_SELECT_FIELD\n\n @property\n def is_text_field(self):\n return self.type == PROPERTY_TEXT_FIELD\n\n @property\n def is_number_field(self):\n return self.type == PROPERTY_NUMBER_FIELD\n\n def is_valid_value(self, value):\n \"\"\"\n Returns True if given value is valid for this property.\n \"\"\"\n if self.is_number_field:\n try:\n float(value)\n except ValueError:\n return False\n return True\n\n\n@python_2_unicode_compatible\nclass GroupsPropertiesRelation(models.Model):\n \"\"\"\n Represents the m:n relationship between Groups and Properties.\n This is done via an explicit class to store the position of the property\n within the group.\n **Attributes:**\n group\n The property group the property belongs to.\n property\n The property of question of the relationship.\n position\n The position of the property within the group.\n \"\"\"\n group = models.ForeignKey(\n PropertyGroup,\n verbose_name=_(u\"Group\"),\n related_name=\"groupproperties\")\n property = models.ForeignKey(\n Property,\n verbose_name=_(u\"Property\"),\n related_name=\"groupproperties\")\n position = models.IntegerField(\n _(u\"Position\"),\n default=999)\n\n class Meta:\n ordering = (\"position\", )\n unique_together = (\"group\", \"property\")\n\n def __str__(self):\n return \"Group:{} -> Property:{}\".format(self.group.name, self.property.name)\n\n\nclass ComponentsPropertiesRelation(models.Model):\n \"\"\"\n Represents the m:n relationship between Servers components and Properties.\n This is done via an explicit class to store the position of the property\n within the server component.\n **Attributes:**\n server component\n The server component of the relationship.\n property\n The property of the relationship.\n position\n The position of the property within the server component.\n \"\"\"\n component = models.ForeignKey(\n Component,\n verbose_name=_(u\"Components\"),\n related_name=\"componentsproperties\")\n property = models.ForeignKey(\n Property,\n verbose_name=_(u\"Property\"))\n position = models.IntegerField(\n _(u\"Position\"),\n default=999)\n\n class Meta:\n ordering = (\"position\", )\n unique_together = (\"component\", \"property\")\n\n\n@python_2_unicode_compatible\nclass PropertyOption(models.Model):\n \"\"\"\n Represents a choosable option of a ``Property`` like red, green, blue.\n **Attributes:**\n property\n The property to which the option belongs\n name\n The name of the option\n position\n The position of the option within the property\n \"\"\"\n property = models.ForeignKey(\n Property,\n verbose_name=_(u\"Property\"),\n related_name=\"options\")\n name = models.CharField(\n _(u\"Name\"),\n max_length=100)\n position = models.IntegerField(\n _(u\"Position\"),\n default=99)\n\n\n class Meta:\n ordering = [\"position\"]\n verbose_name = _(u'Property Option')\n verbose_name_plural = _(u'Property Options')\n\n def __str__(self):\n return \"{} property:{}\".format(self.name, self.property)\n\n\n@python_2_unicode_compatible\nclass ComponentPropertyValue(models.Model):\n \"\"\"\n Stores the value resp. selected option of a server component/property combination.\n This is some kind of EAV.\n **Attributes:**\n server component\n The server component for which the value is stored.\n property\n The property for which the value is stored.\n property_group\n The property group for which the value is stored, if none then it's a local property\n value\n The value for the server component/property pair. Dependent of the property\n type the value is either a number, a text or an id of an option.\n \"\"\"\n component = models.ForeignKey(\n Component,\n verbose_name=_(u\"Component\"),\n related_name=\"property_values\")\n property = models.ForeignKey(\n Property,\n verbose_name=_(u\"Property\"),\n related_name=\"property_values\")\n property_group = models.ForeignKey(\n PropertyGroup,\n verbose_name=_(u\"Property group\"),\n blank=True, null=True,\n related_name=\"property_values\")\n value = models.CharField(\n _(u\"Value\"),\n blank=True,\n max_length=100)\n value_as_float = models.FloatField(\n _(u\"Value as float\"),\n blank=True, null=True)\n option = models.ForeignKey(\n PropertyOption,\n blank=True, null=True)\n\n\n class Meta:\n unique_together = (\"component\", \"property\", \"property_group\", \"value\")\n\n def __str__(self):\n property_group_name = self.property_group.name if self.property_group_id else ''\n return u\"{}/{}/{}: {}\".format(self.component.get_name(),\n property_group_name,\n self.property.name,\n self.value)\n\n def save(self, *args, **kwargs):\n if self.option:\n self.value = self.option.pk\n self.value_as_float = self.option.pk\n else:\n try:\n float(self.value)\n except ValueError:\n pass\n else:\n self.value_as_float = self.value\n\n super(ComponentPropertyValue, self).save(*args, **kwargs)\n\n def get_value(self):\n if self.property.is_select_field:\n return self.option\n elif self.property.is_number_field:\n return self.value_as_float\n else:\n return self.value\n\n\nclass ServerTemplate(CreatedModel, NamedModel):\n cpu_socket = models.ForeignKey(\n PropertyOption,\n related_name='cpu_socket_opts',\n limit_choices_to={'property__name': 'cpu.socket'})\n\n cpu_qty = models.PositiveSmallIntegerField(default=1)\n\n ram_standard = models.ForeignKey(\n PropertyOption,\n related_name='ram_standard_opts',\n limit_choices_to={'property__name': 'ram.standard'})\n\n ram_qty = models.PositiveSmallIntegerField(default=1)\n\n unit_takes = models.PositiveSmallIntegerField(\n verbose_name=_('height in units'),\n default=1)\n\n servers_uses = models.PositiveIntegerField(\n default=0,\n editable=False)\n\n\n class Meta:\n verbose_name = _('Server Template')\n verbose_name_plural = _('Server Templates')\n\n @property\n def href(self):\n return reverse('api:server-template-detail', args=[self.pk])\n\n def get_height(self):\n return self.unit_takes\n\n def get_server_list(self):\n return self.servers.all()\n\n def is_supported_cpu(self, component):\n return ComponentPropertyValue.objects\\\n .filter(\n component=component,\n property=self.cpu_socket.property,\n option=self.cpu_socket)\\\n .exists()\n\n def is_supported_ram(self, component):\n return ComponentPropertyValue.objects\\\n .filter(\n component=component,\n property=self.ram_standard.property,\n option=self.ram_standard)\\\n .exists()\n\n def is_supported_hdd(self, component):\n hdd_connection_type = set()\n hdd_form_factor = set()\n for hdd in self.hdds.all():\n hdd_connection_type.add(hdd.hdd_connection_type_id)\n hdd_form_factor.add(hdd.hdd_form_factor_id)\n\n # вначале оставим только компоненты с валидным connection_type\n valid_c_ids = ComponentPropertyValue.objects\\\n .values_list('component_id', flat=True)\\\n .filter(component=component,\n property__name='hdd.connection_type',\n option__in=hdd_connection_type)\n\n # теперь среди оставшихся компонентов ищем с валидным form_factor\n return ComponentPropertyValue.objects\\\n .filter(component__in=valid_c_ids,\n property__name='hdd.form_factor',\n option__in=hdd_form_factor)\\\n .exists()\n\n\nclass ServerTemplateHdd(models.Model):\n template = models.ForeignKey(\n ServerTemplate,\n related_name='hdds')\n hdd_qty = models.PositiveSmallIntegerField(default=1)\n hdd_form_factor = models.ForeignKey(\n PropertyOption,\n related_name='form_factor_opts',\n limit_choices_to={'property__name': 'hdd.form_factor'})\n hdd_connection_type = models.ForeignKey(\n PropertyOption,\n related_name='conn_type_opts',\n limit_choices_to={'property__name': 'hdd.connection_type'})\n\n\n class Meta:\n unique_together = ('template', 'hdd_form_factor', 'hdd_connection_type')\n\n\nclass ServerQuerySet(QuerySet):\n\n def uninstalled(self):\n return self.filter(basket__isnull=True, rack__isnull=True)\n\n\nclass Server(CreatedModel, NamedModel):\n node = models.ForeignKey(Node,\n related_name='servers',\n blank=True, null=True)\n floor = models.ForeignKey(Floor,\n related_name='servers',\n blank=True, null=True)\n room = models.ForeignKey(Room,\n related_name='servers',\n blank=True, null=True)\n row = models.ForeignKey(Row,\n related_name='servers',\n blank=True, null=True)\n rack = models.ForeignKey(Rack,\n related_name='servers',\n blank=True, null=True)\n basket = models.ForeignKey(\n 'Basket',\n related_name='servers',\n blank=True, null=True)\n template = models.ForeignKey(\n ServerTemplate,\n related_name='servers')\n\n objects = PassThroughManager.for_queryset_class(ServerQuerySet)()\n\n class Meta:\n verbose_name = _('Server')\n verbose_name_plural = _('Servers')\n\n @property\n def href(self):\n return reverse('api:server-detail', args=[self.pk])\n\n def save(self, *args, **kwargs):\n extra_args = ['node', 'floor', 'row', 'room']\n holder = None\n if self.rack:\n holder = self.rack\n elif self.basket:\n holder = self.basket\n\n if holder:\n for ea in extra_args:\n setattr(self, ea, getattr(holder, 'get_{}'.format(ea))())\n else:\n for ea in extra_args:\n setattr(self, ea, None)\n return super(Server, self).save(*args, **kwargs)\n\n def is_mounted(self):\n return self.basket or self.rack\n\n @property\n def slot_takes(self):\n \"\"\"\n На текущий момент поддерживаются только blade-сервера размером в 1 слот.\n\n TODO: возможно blade-сервера могут занимать несколько слотов в корзине.\n В тоже время корзина может представлять из себя двумерный массив:\n ___________________\n | 1 | 2 | 3 |\n -------------------\n | 4 | 5 | 6 |\n -------------------\n В этом случае нужно знать:\n - поддерживает ли корзина размещение blade-серверов в несколько слотов;\n - какие слоты возможно объединить: (1, 2) или (1, 4).\n\n \"\"\"\n return 1\n\n def get_node(self):\n return self.node\n\n def get_template(self):\n return self.template\n\n def get_rack(self):\n if self.rack:\n return self.rack\n\n if self.basket:\n return self.basket.rack\n return None\n\n def get_height(self):\n if self.basket:\n return self.basket.get_height()\n\n return self.template.get_height()\n\n def is_supported_component(self, component):\n tmpl = self.template\n c_kind = component.kind.name\n if c_kind == 'cpu':\n return tmpl.is_supported_cpu(component)\n elif c_kind == 'ram':\n return tmpl.is_supported_ram(component)\n elif c_kind == 'hdd':\n return tmpl.is_supported_hdd(component)\n elif c_kind == 'raid':\n return True\n elif c_kind == 'net':\n return True\n return False\n\n def has_free_slots_for_component(self, component):\n \"\"\"\n Проверяет есть ли свободное место в сервере для указанного компонента.\n\n Внимание! Прежде, чем вызывать этот метод, необходимо убедиться,\n что компонент совместим с сервером (например, с помощью\n Server.is_supported_component())\n \"\"\"\n tmpl = self.template\n c_kind = component.kind.name\n if c_kind in ('cpu', 'ram'):\n limit = getattr(tmpl, '{}_qty'.format(c_kind))\n cnt = self.components.filter(kind=component.kind).count()\n\n elif c_kind == 'hdd':\n hdd_connection_type = ComponentPropertyValue.objects\\\n .filter(component=component,\n property__name='hdd.connection_type')[0].option\n hdd_form_factor = ComponentPropertyValue.objects\\\n .filter(component=component,\n property__name='hdd.form_factor')[0].option\n limit = tmpl.hdds.filter(hdd_connection_type=hdd_connection_type,\n hdd_form_factor=hdd_form_factor)[0].hdd_qty\n # вначале оставим только компоненты с валидным connection_type\n all_server_components_ids = self.components.filter(kind=component.kind).values_list('id', flat=True)\n valid_c_ids = ComponentPropertyValue.objects\\\n .values_list('component_id', flat=True)\\\n .filter(component__in=all_server_components_ids,\n property__name='hdd.connection_type',\n option=hdd_connection_type)\n # теперь среди оставшихся компонентов ищем с валидным form_factor\n cnt = ComponentPropertyValue.objects\\\n .filter(component__in=valid_c_ids,\n property__name='hdd.form_factor',\n option=hdd_form_factor)\\\n .count()\n elif c_kind in ('net', 'raid'):\n return True\n else:\n raise NotImplementedError\n\n if cnt < limit:\n return True\n return False\n\n def install_component(self, component):\n if component.is_installed():\n raise ComponentAlreadyInstalled\n\n if component.is_broken():\n raise ComponentIsBroken\n\n if not self.is_supported_component(component):\n raise ComponentNotSupported\n\n # ensure there are empty slots left\n if not self.has_free_slots_for_component(component):\n raise ServerHasNoFreeSlotForComponent\n\n component.install(server=self)\n component.save()\n\n def uninstall_component(self, component):\n if component.is_free():\n raise ComponentNotInstalled\n\n component.uninstall()\n component.save()\n\n def install_components(self, components):\n ret = []\n for component in components:\n try:\n self.install_component(component)\n except Exception as exc:\n ret.append({'component': component, 'state': 'error', 'message': str(exc)})\n else:\n ret.append({'component': component, 'state': 'ok'})\n return ret\n\n def uninstall_components(self, components):\n map(self.uninstall_component, components)\n\n def get_installed_components(self):\n return self.components.filter(state=ComponentState.INSTALLED)\n\n def find_all_valid_components(self):\n return list(self.find_valid_cpu_components()) + \\\n list(self.find_valid_ram_components()) + \\\n list(self.find_valid_hdd_components()) + \\\n list(self.find_valid_net_components()) + \\\n list(self.find_valid_raid_components())\n\n def find_valid_cpu_components(self):\n query = Q(property__name='cpu.socket')\n query &= Q(option=self.template.cpu_socket)\n component_ids = ComponentPropertyValue.objects\\\n .values_list('component_id', flat=True)\\\n .filter(query)\n return Component.objects.filter(state=ComponentState.FREE, id__in=component_ids)\n\n def find_valid_hdd_components(self):\n hdd_connection_type = set()\n hdd_form_factor = set()\n for hdd in self.template.hdds.all():\n hdd_connection_type.add(hdd.hdd_connection_type_id)\n hdd_form_factor.add(hdd.hdd_form_factor_id)\n\n # вначале оставим только компоненты с валидным connection_type\n valid_c_ids = ComponentPropertyValue.objects\\\n .values_list('component_id', flat=True)\\\n .filter(property__name='hdd.connection_type',\n option__in=hdd_connection_type)\n\n # теперь среди оставшихся компонентов ищем с валидным form_factor\n component_ids = ComponentPropertyValue.objects\\\n .values_list('component_id', flat=True)\\\n .filter(component__in=valid_c_ids,\n property__name='hdd.form_factor',\n option__in=hdd_form_factor)\n return Component.objects.filter(state=ComponentState.FREE, id__in=component_ids)\n\n def find_valid_ram_components(self):\n query = Q(property__name='ram.standard')\n query &= Q(option=self.template.ram_standard)\n component_ids = ComponentPropertyValue.objects\\\n .values_list('component_id', flat=True)\\\n .filter(query)\n return Component.objects.filter(state=ComponentState.FREE, id__in=component_ids)\n\n def find_valid_raid_components(self):\n return Component.objects.filter(\n state=ComponentState.FREE,\n kind__name='raid')\n\n def find_valid_net_components(self):\n return Component.objects.filter(\n state=ComponentState.FREE,\n kind__name='net')\n\n\nclass BasketQuerySet(QuerySet):\n\n def uninstalled(self):\n return self.filter(rack__isnull=True)\n\n def with_empty_slots(self):\n return self.annotate(slots_taken=Count('slots'))\\\n .filter(slots_taken__lt=F('slot_qty'))\n\n\nclass Basket(CreatedModel, NamedModel):\n node = models.ForeignKey(Node,\n related_name='baskets',\n blank=True, null=True)\n rack = models.ForeignKey(Rack,\n related_name='baskets',\n blank=True, null=True)\n slot_qty = models.PositiveSmallIntegerField(\n verbose_name=_('Total slots Qty'),\n default=8)\n unit_takes = models.PositiveSmallIntegerField(\n verbose_name=_('height in units'),\n default=1)\n\n objects = PassThroughManager.for_queryset_class(BasketQuerySet)()\n\n class Meta:\n verbose_name = _('Basket')\n verbose_name_plural = _('Baskets')\n\n @property\n def href(self):\n return reverse('api:basket-detail', args=[self.pk])\n\n @property\n def floor(self):\n return self.get_floor()\n\n @property\n def room(self):\n return self.get_room()\n\n @property\n def row(self):\n return self.get_row()\n\n def save(self, *args, **kwargs):\n if self.rack:\n self.node = self.rack.get_node()\n else:\n self.node = None\n return super(Basket, self).save(*args, **kwargs)\n\n def has_free_slot(self):\n taken = self.slots.count()\n if taken < self.slot_qty:\n return True\n return False\n\n def get_node(self):\n return self.node\n\n def get_floor(self):\n return self.rack and self.rack.get_floor() or None\n\n def get_room(self):\n return self.rack and self.rack.get_room() or None\n\n def get_row(self):\n return self.rack and self.rack.get_row() or None\n\n def get_height(self):\n return self.unit_takes\n\n def get_position_in_rack(self):\n if self.rack:\n return self.units.all()[0].position\n return None\n\n def get_server_list(self):\n return self.servers.all()\n\n def validate_position(self, position):\n if self.slots.filter(position=position).exists():\n raise BasketSlotIsBusy\n\n def mount(self, server=None, position=None, slots_takes=None):\n if slots_takes is None:\n slots_takes = server.slot_takes\n\n if position is None:\n position = self.find_free_position(slots_takes)\n\n self.validate_position(position)\n\n server.basket = self\n server.node = self.node\n server.rack = self.rack\n server.save()\n\n slot_kwargs = {\n 'basket': self,\n 'position': position,\n 'server': server,\n }\n return BasketSlot.objects.get_or_create(**slot_kwargs)\n\n def unmount(self, server=None):\n server.node = None\n server.rack = None\n server.basket = None\n server.save()\n\n BasketSlot.objects\\\n .filter(basket=self, server=server)\\\n .delete()\n\n def find_gaps(self):\n last_slot = None\n gaps = []\n for slot in self.slots.all().order_by('position'):\n # if first server in the slot\n if last_slot is None:\n if slot.position > 1:\n gaps.append({\n 'slots': slot.position - 1,\n 'position': 1\n })\n # otherwise\n else:\n last_slot_ends = last_slot.position + last_slot.slot_takes - 1\n # there is a gap between last slot and current\n if (slot.position - last_slot_ends) > 1:\n gaps.append({\n 'slots': slot.position - last_slot_ends - 1,\n 'position': last_slot_ends + 1\n })\n last_slot = slot\n\n # does last server in the basket take all slots till basket bottom\n # or there is a gap there?\n if last_slot and \\\n last_slot.position != self.slot_qty and \\\n (last_slot.position + last_slot.slot_takes - 1) < self.slot_qty:\n last_slot_ends = last_slot.position + last_slot.slot_takes - 1\n gaps.append({\n 'slots': self.slot_qty - last_slot_ends,\n 'position': last_slot_ends + 1\n })\n\n # in this case basket is empty\n elif last_slot is None:\n gaps.append({\n 'slots': self.slot_qty,\n 'position': 1\n })\n\n return gaps\n\n def find_free_position(self, slots_takes=1):\n if slots_takes > 1:\n raise NotImplementedError\n\n gaps = self.find_gaps()\n if not len(gaps):\n raise BasketIsFilled\n\n return gaps[0]['position']\n\n\nclass BasketSlot(models.Model):\n \"\"\"\n Описывает слот (ячейку) в корзине\n \"\"\"\n basket = models.ForeignKey(Basket, related_name='slots')\n position = models.PositiveSmallIntegerField(default=1)\n server = models.ForeignKey(Server)\n\n class Meta:\n verbose_name = _('Basket slot')\n verbose_name_plural = _('Baskets slots')\n unique_together = ('basket', 'server')\n\n @property\n def slot_takes(self):\n return self.server.slot_takes\n\n\ndef unit_saved(sender, instance, **kwargs):\n rack = instance.rack\n gaps = [g['height'] for g in rack.find_gaps()]\n rack.max_gap = max(gaps) if len(gaps) else 0\n rack.save()\npost_save.connect(unit_saved, sender=Unit)\npre_delete.connect(unit_saved, sender=Unit)\n\n\ndef server_saved(sender, instance, **kwargs):\n node = instance.get_node()\n if node:\n node.servers_count = node.servers.count()\n node.save()\n\n template = instance.get_template()\n if template:\n template.servers_uses = template.servers.count()\n template.save()\npost_save.connect(server_saved, sender=Server)\npre_delete.connect(server_saved, sender=Server)\n","sub_path":"src/mbtest1/erp_test/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":40990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"577840764","text":"import tensorflow as tf\ntf.set_random_seed(777)\n\n\nx_data = [1,2,3]\ny_data = [1,2,3]\n\nw = tf.Variable(tf.random_normal([1]), name ='weight')\nb = tf.Variable(tf.random_normal([1]), name ='bias')\n\n\nx = tf.placeholder(dtype=tf.float32)\ny = tf.placeholder(dtype=tf.float32)\n\nhypothesis = x * w + b\ncost = tf.reduce_mean(tf.square(hypothesis - x))\n\nlearning_rate = 0.1\n# gradient = tf.reduce_mean((w * x - y) * x)\n# descent = w - learning_rate * gradient\n# update = w.assign(descent)\n\nupdate = tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\nfor step in range(30):\n _, _cost, _w = sess.run([update, cost, w], feed_dict={x:x_data, y:y_data})\n print('step:{} cost:{} w:{}'.format(step, _cost, _w))","sub_path":"day1/gradientDescentEx1.py","file_name":"gradientDescentEx1.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"466682968","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport datetime as dt\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import Normalizer\n#TRAIN\nrainfall = pd.read_csv('Digkilaan_interpol.csv')\nrainfall.columns = ['DATETIME','RAINFALL']\nrainfall['RAINFALL'] = rainfall['RAINFALL']\nrainfall['DATETIME'] = pd.to_datetime(rainfall['DATETIME'])\nrainfall['DATETIME'] = (rainfall['DATETIME'] - rainfall['DATETIME'].min()) / np.timedelta64(1,'D')\n\nrainfall.head()\nrainfall.info()\nrainfall.describe()\n\n\n\n#DROP EMPTY CELL\nrainfall['RAINFALL'].replace('', np.nan, inplace=True)\nrainfall.dropna(subset=['RAINFALL'], inplace=True)\nsns.pairplot(rainfall)\nsns.distplot(rainfall['RAINFALL'])\n\n\n\n\nX = rainfall[['DATETIME','RAINFALL']]\ny = rainfall['RAINFALL']\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, random_state=101)\n\nprint(X_test)\n\nlm = LinearRegression()\nlm.fit(X_train,y_train)\n\npredictions = lm.predict(X_test)\nprint(predictions)\n\nplt.scatter(y_test,predictions)\nplt.show()\n\n\n\n# #INPUT WATERLEVEL\nwaterlevel = pd.read_csv('Mandulog_interpol.csv')\nwaterlevel.columns = ['DATETIME','WATERLEVEL']\nwaterlevel['WATERLEVEL'].interpolate(method='linear', inplace=True)\nwaterlevel['DATETIME'] = pd.to_datetime(waterlevel['DATETIME'])\nwaterlevel['WATERLEVEL'] = waterlevel['WATERLEVEL']*1000\nwaterlevel.to_csv('Mandulog_imputed.csv')\n\n\n\n#INPUT RAINFALL\nrainfall = pd.read_csv('Digkilaan_interpol.csv')\nrainfall.columns = ['DATETIME','RAINFALL']\nrainfall['RAINFALL'].interpolate(method='linear', inplace=True)\nrainfall['DATETIME'] = pd.to_datetime(rainfall['DATETIME'])\nrainfall['RAINFALL'] = rainfall['RAINFALL']\nrainfall.to_csv('Digkilaan_imputed.csv')\n\n#MERGING\n\n\n# #separate array into input and output components\n# scaler = Normalizer().fit(merged_df)\n# normalizedX = scaler.transform(merged_df)\n\n\n\n# predictions = lm.predict(merged_df)\n# merged_df['PREDICTIONS'] = predictions\n# merged_df.to_csv('predicted.csv')\n","sub_path":"Scripts_Arch2_nfs/rainfall_training.py","file_name":"rainfall_training.py","file_ext":"py","file_size_in_byte":2059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"460890843","text":"import openpyxl\r\nimport re\r\nfrom nltk.corpus import stopwords\r\n\r\nEXCEL_IN = 'forum.no.tags.xlsx'\r\nEXCEL_OUT = 'forum.filtered.no.sent.length.xlsx'\r\n\r\n\r\ndef filter_words(text):\r\n if not text:\r\n return False\r\n match = re.split(r'\\s+', text)\r\n common = ['scary', 'me', 'sleep', 'my head', 'things', 'night', 'echoes', 'antipsychotic', 'whispering', 'alone', 'insane', 'dog bark', 'social', 'delusions', 'sad','television', 'TV', 'hallucinations', 'time', 'meds', 'symptoms', 'voices', 'medication', 'cognitive', 'running', 'thoughts', 'mg', 'scared', 'psychosis', 'headaches'] # should be lowercase\r\n is_common = False\r\n for word in match:\r\n if word in common:\r\n is_common = True\r\n break\r\n personal = ['i', 'my', \"i've\", \"i'm\", 'im', 'ive'] # should be lowercase\r\n return [match[0].lower() in personal, is_common]\r\n\r\n\r\ndef copy():\r\n for i in range(1, 10):\r\n v = posts.cell(sourceRow, i).value\r\n posts.cell(targetRow, i, v)\r\n posts.cell(sourceRow, i, '')\r\n\r\n\r\ndef copy_to(from_row, to_row, sheet_name):\r\n for i in range(1, 10):\r\n v = posts.cell(from_row, i).value\r\n xl[sheet_name].cell(to_row, i, v)\r\n\r\n\r\ndef clear(src):\r\n for i in range(1, 10):\r\n posts.cell(src, i, '')\r\n\r\n\r\nif __name__ == '__main__': # Script starts here\r\n xl = openpyxl.load_workbook(EXCEL_IN)\r\n posts = xl['Posts']\r\n targetRow = 2\r\n sourceRow = 3\r\n personalRow = 2\r\n commonRow = 2\r\n nonAndGenRow = 2\r\n bottomRow = len(posts['G']) + 1\r\n xl.create_sheet('Personal')\r\n copy_to(1, 1, 'Personal') # copy headers\r\n xl.create_sheet('Personal & Common')\r\n copy_to(1, 1, 'Personal & Common') # copy headers\r\n xl.create_sheet('Non and General')\r\n copy_to(1, 1, 'Non and General') # copy headers\r\n while sourceRow < bottomRow:\r\n text = posts.cell(sourceRow, 7).value # G column\r\n fw = filter_words(text)\r\n if fw:\r\n copy()\r\n if fw[0]:\r\n copy_to(targetRow, personalRow, 'Personal')\r\n personalRow += 1\r\n if fw[1]:\r\n copy_to(targetRow, commonRow, 'Personal & Common')\r\n commonRow += 1\r\n else:\r\n copy_to(targetRow, nonAndGenRow, 'Non and General')\r\n nonAndGenRow += 1\r\n else:\r\n copy_to(targetRow, nonAndGenRow, 'Non and General')\r\n nonAndGenRow += 1\r\n targetRow += 1\r\n else:\r\n if text:\r\n copy_to(sourceRow, nonAndGenRow, 'Non and General')\r\n nonAndGenRow += 1\r\n clear(sourceRow)\r\n print('\"{}\"'.format(text))\r\n sourceRow += 1\r\n xl.save(EXCEL_OUT)\r\n xl.close()\r\n","sub_path":"filter_stages/filter_posts_newsheet_keywords copy.py","file_name":"filter_posts_newsheet_keywords copy.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"238360421","text":"from sklearn.manifold import TSNE\nfrom sklearn.decomposition import PCA\nfrom matplotlib import pyplot as plt\nfrom sklearn.cluster import KMeans, AgglomerativeClustering\nfrom time import time\nfrom collections import Counter\n\nfrom hkp.Prediction.PredictionData import PredictionMatrix\nfrom hkp.Prediction.PredictionClustering import sort_cluster, plot_heatmap, analyze_cluster\nfrom hkp.Prediction.PredictionModel import analyze_prediction\nfrom hkp.orm import *\n\nfrom sqlalchemy import func\nfrom sqlalchemy import and_, or_\n\n\n# define parameters\nbuild_matrix = False # True if we build the matrix, False if we read the matrix from file\ntrainingset = 0 # numbers of training set\ntestset = 350000 # numbers of test set\nmatrix_type = 'tooth_planning' # prediction matrix (see Prediction.PredictionModel)\nfilename = 'data/predictionmatrix/pred_mat_' + matrix_type +'.pkl' # name of file contains prediction matrix\n\nheatmap = False # plot heatmap\nmapping = False # visualize in two dimensional plots by tsne or pca\n\nn_clusters = 15 # number of clusters\nrows = session.query(Lines.persid, func.count(Lines.persid).label('persid_count')).\\\n group_by(Lines.persid).subquery()\nrows_multiple = session.query(rows.c.persid).filter(rows.c.persid_count > 1).subquery()\nlines_gutstat = session.query(Lines.persid).filter(Lines.persid.in_(rows_multiple)).\\\n filter(Lines.gutstat != 0).subquery()\nlines_without_gutstat = session.query(Lines.fallnummer).filter(and_(Lines.persid.in_(lines_gutstat),\n Lines.gutstat == 0)).subquery()\nlines_gutachten = session.query(Lines.fallnummer).filter(Lines.gutstat == 0,\n Lines.planungsgutachten == True).subquery()\nquery = session.query(Lines).filter(~Lines.fallnummer.in_(lines_without_gutstat)).limit(testset)\n\npm = PredictionMatrix(query, testset=testset, result_type='complete',\n matrix_type=matrix_type, res_mat=True)\n# build matrix\nif build_matrix:\n start = time()\n pm = PredictionMatrix(query, testset=testset, result_type='complete',\n matrix_type=matrix_type, res_mat=True)\n print(\"Building matrix takes %.2f seconds\" % (time() - start))\n pm.store_prediction_matrix(filename)\nelse:\n pm = PredictionMatrix.load_prediction_matrix(filename)\n\n# Clustering\nclf = KMeans(n_clusters = n_clusters) # can substituted KMeans by, i.e., AgglomerativeClustering\n\n# Cluster index for each data\npred = clf.fit_predict(pm.x_test)\n\n# Analyze output (how many GUTSTAT in a cluster)\n# if analyze only for a certain cluster: add cluster_id = cluster index wanted to investigate\n# if print status, planning: add print_tooth_status = True\nresult_prediction = analyze_prediction(pm, pred)\nout_gutstat = analyze_cluster(result_prediction)\n\n# Plot Heatmap\nif heatmap:\n sorted_matrix, cluster_border = sort_cluster(pm, pred)\n plot_heatmap(sorted_matrix, cluster_border, pm.colnames)\n\n# Visualize with TSNE and/or PCA\nif mapping:\n x_tsne = TSNE().fit_transform(pm.x_test)\n x_pca = PCA().fit_transform(pm.x_test)\n\n plt.subplot(221)\n plt.scatter(x_tsne[:, 0], x_tsne[:, 1], c=pm.y_test)\n plt.subplot(222)\n plt.scatter(x_tsne[:, 0], x_tsne[:, 1], c=pred)\n plt.subplot(223)\n plt.scatter(x_pca[:, 0], x_pca[:, 1], c=pm.y_test)\n plt.subplot(224)\n plt.scatter(x_pca[:, 0], x_pca[:, 1], c=pred)\n plt.show()\n","sub_path":"run_clustering.py","file_name":"run_clustering.py","file_ext":"py","file_size_in_byte":3510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"291193529","text":"from flask_admin.contrib import sqla\nfrom secure_views import SecureModelView\n\n\nclass HazardLocationView(SecureModelView):\n\n can_create = True\n can_edit = True\n can_delete = True\n\n column_list = ('id', 'hazard_category', 'place_name', 'latitude',\n 'longitude')\n column_searchable_list = ['place_name', 'hazard_category']\n column_filters = column_list\n","sub_path":"code/classes/Kevin Pielacki/remote-server/views/hazard_location_view.py","file_name":"hazard_location_view.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"279157961","text":"#!/usr/bin/env python\n\"\"\"Re-segment raw read and re-label the data\"\"\"\n########################################################################\n# File: event_detection.py\n# executable: event_detection.py\n#\n# Author: Andrew Bailey\n# History: 10/6/17 Created\n########################################################################\n\n\nfrom __future__ import print_function\nimport sys\nimport os\nimport collections\nimport re\nimport numpy as np\nimport traceback\nfrom collections import defaultdict\nfrom timeit import default_timer as timer\nfrom signalalign.utils.pyporeParsers import SpeedyStatSplit\nfrom signalalign.fast5 import Fast5\nfrom signalalign.utils.filters import minknow_event_detect, scrappie_event_detect\nfrom py3helpers.utils import check_numpy_table, list_dir, TimeStamp, change_np_field_type, merge_dicts\nfrom py3helpers.seq_tools import create_fastq_line, check_fastq_line, ReverseComplement, pairwise_alignment_accuracy\n\nEVENT_DETECT_SPEEDY = \"speedy\"\nEVENT_DETECT_MINKNOW = \"minknow\"\nEVENT_DETECT_SCRAPPIE = \"scrappie\"\n\n\ndef create_speedy_event_table(signal, sampling_freq, start_time, min_width=5, max_width=80, min_gain_per_sample=0.008,\n window_width=800):\n \"\"\"Create new event table using SpeedyStatSplit Event detection\n\n :param signal: list or array of signal in pA for finding events\n :param sampling_freq: sampling frequency of ADC in Hz\n :param start_time: start time from fast5 file (time in seconds * sampling frequency)\n :param min_width: param for SpeedyStatSplit\n :param max_width: param for SpeedyStatSplit\n :param min_gain_per_sample: param for SpeedyStatSplit\n :param window_width: param for SpeedyStatSplit\n :return: Table of events without model state or move information\n \"\"\"\n assert np.sign(start_time) == 1, \"Start time has to be positive: {}\".format(start_time)\n assert type(signal[0]) is np.float64, \"Signal needs to be in pA. Not ADC counts\"\n\n # define speedy stat split\n parser = SpeedyStatSplit(min_width=min_width, max_width=max_width,\n min_gain_per_sample=min_gain_per_sample,\n window_width=window_width, sampling_freq=sampling_freq)\n # parse events\n events = parser.parse(np.asarray(signal, dtype=np.float64))\n num_events = len(events)\n # create empty event table\n event_table = get_empty_event_table(num_events)\n # set events into event table\n for i, event in enumerate(events):\n event_table['start'][i] = event.start / sampling_freq + (start_time / sampling_freq)\n event_table['raw_start'][i] = event.start\n event_table['length'][i] = event.duration / sampling_freq\n event_table['raw_length'][i] = event.duration\n event_table['mean'][i] = event.mean\n event_table['stdv'][i] = event.std\n\n return event_table\n\n\ndef create_minknow_event_table(signal, sampling_freq, start_time,\n window_lengths=(3, 6), thresholds=(1.4, 9.0), peak_height=0.2):\n \"\"\"Create new event table using minknow_event_detect event detection\n\n :param signal: list or array of signal in pA for finding events\n :param sampling_freq: sampling frequency of ADC in Hz\n :param start_time: start time from fast5 file (time in seconds * sampling frequency)\n :param window_lengths: t-test windows for minknow_event_detect\n :param thresholds: t-test thresholds for minknow_event_detect\n :param peak_height: peak height param for minknow_event_detect\n :return: Table of events without model state or move information\n \"\"\"\n assert np.sign(start_time) == 1, \"Start time has to be positive: {}\".format(start_time)\n assert type(signal[0]) is np.float64, \"Signal needs to be in pA. Not ADC counts\"\n events = minknow_event_detect(np.asarray(signal, dtype=float), sample_rate=sampling_freq,\n get_peaks=False, window_lengths=window_lengths,\n thresholds=thresholds, peak_height=peak_height)\n num_events = len(events)\n event_table = get_empty_event_table(num_events)\n for i, event in enumerate(events):\n event_table['start'][i] = event[\"start\"] + (start_time / sampling_freq)\n event_table['length'][i] = event[\"length\"]\n event_table['mean'][i] = event[\"mean\"]\n event_table['stdv'][i] = event[\"stdv\"]\n event_table['raw_start'][i] = np.round(event[\"start\"] * sampling_freq)\n event_table['raw_length'][i] = np.round(event[\"length\"] * sampling_freq)\n\n return event_table\n\n\ndef create_scrappie_event_table(fast5_location, sampling_freq):\n \"\"\"Create new event table using scrappie event detection via subprocess call to scrappie\n\n :param fast5_location: path to\n :param sampling_freq: sampling frequency of ADC in Hz\n :return: Table of events without model state or move information\n \"\"\"\n events = scrappie_event_detect(fast5_location)\n assert events is not None and len(events) > 0, \"Could not use scrappie to detect events in {}\".format(fast5_location)\n num_events = len(events)\n event_table = get_empty_event_table(num_events - 1)\n\n for i, event in enumerate(events):\n # drop last event (cannot compute length without \"next\" event)\n if i == num_events - 1: break\n\n event_table['start'][i] = event[\"start\"] / sampling_freq\n event_table['length'][i] = 0.0\n event_table['mean'][i] = event[\"mean\"]\n event_table['stdv'][i] = event[\"stdv\"]\n event_table['raw_start'][i] = np.round(event[\"start\"])\n event_table['raw_length'][i] = 0\n\n if i != 0:\n event_table['length'][i-1] = event_table['start'][i] - event_table['start'][i - 1]\n event_table['raw_length'][i-1] = event_table['raw_start'][i] - event_table['raw_start'][i - 1]\n\n return event_table\n\n\ndef get_empty_event_table(num_events):\n \"\"\"\n Gets default event table returned by create_XXX_event_table\n :param num_events: number of events to initialize\n :return: empty numpy array with appropriate columns\n \"\"\"\n return np.empty(num_events, dtype=[('start', float), ('length', float),\n ('mean', float), ('stdv', float),\n ('model_state', 'S5'), ('move', ' current_event_end:\n time[index] += current_event_end - old_event_start\n new_check_overlap = True\n break\n # check if entire old event is within the new event or not\n else:\n if old_event_start < current_event_start:\n time[index] += old_event_end - current_event_start\n else:\n time[index] += old_event_end - old_event_start\n # if old_event_end != current_event_end:\n old_indx += 1\n new_check_overlap = False\n num_loops += 1\n # break loop at end of old events\n if old_indx == num_old_events:\n break\n else:\n end_index = i\n num_kmers = len(kmers)\n # select index of best kmer to assign\n if num_kmers == 1:\n best_index = 0\n left_over = 0\n elif num_kmers > 1:\n # select on time in new event only\n best_index = time.index(max(time))\n # if there are several old events in a new event, track how many\n if new_check_overlap:\n left_over = sum(moves[best_index+1:-1])\n else:\n left_over = sum(moves[best_index+1:])\n else:\n # end of possible alignments\n end_index = i\n break\n # if previous old event overlapped into current new event\n # check if old event is going to be assigned twice\n if selected_overlap and best_index == 0 and check_overlap:\n if homopolymer:\n move = moves[best_index]\n else:\n move = 0\n elif selected_overlap and best_index != 0 and check_overlap:\n move = min(5, moves[best_index] + last_left_over)\n else:\n move = min(5, moves[best_index]+sum(moves[:best_index])+last_left_over)\n if most_moves < moves[best_index]+sum(moves[:best_index])+last_left_over:\n most_moves = moves[best_index]+sum(moves[:best_index])+last_left_over\n # print(kmers, moves, left_over, moves[best_index], sum(moves[:best_index]), last_left_over, move)\n # if new overlap\n if new_check_overlap:\n # new overlapped event will be tracked on next new_event so we drop a left_over count\n left_over = max(0, left_over-1)\n if most_moves < left_over-1:\n most_moves = left_over-1\n\n # check if we currently selected an overlapping old event\n if best_index == num_kmers-1:\n selected_overlap = True\n else:\n selected_overlap = False\n else:\n selected_overlap = False\n\n kmer = kmers[best_index]\n prob = probs[best_index]\n # assign event probs, move and model state\n event[\"p_model_state\"] = prob\n event[\"move\"] = move\n event[\"model_state\"] = kmer\n check_overlap = new_check_overlap\n last_left_over = left_over\n new_check_overlap = False\n homopolymer = False\n else:\n # skip event since the\n start_index = i + 1\n # print(most_moves)\n return new_events[start_index:end_index]\n\n\ndef check_event_table_time(event_table):\n \"\"\"Check if event table has correct math for start and length timing for each event\n\n :param event_table: event table with \"start\" and \"length\" columns\n \"\"\"\n check_numpy_table(event_table, req_fields=('start', 'length'))\n\n prev_end = event_table[0][\"start\"] + event_table[0][\"length\"]\n for event in event_table[1:]:\n if prev_end != event[\"start\"]:\n return False\n prev_end = event[\"start\"]+event[\"length\"]\n\n return True\n\n\ndef resegment_reads(fast5_path, params=None, speedy=False, overwrite=True, analysis_path=\"ReSegmentBasecall_000\"):\n \"\"\"Re-segment and create anchor alignment from previously base-called fast5 file\n :param fast5_path: path to fast5 file\n :param params: event detection parameters\n :param speedy: boolean option for speedyStatSplit or minknow\n :param overwrite: overwrite a previous event re-segmented event table\n :param analysis_path: name of key where events table will be placed (Analyses/'name'/Events)\n :return True when completed\n \"\"\"\n assert os.path.isfile(fast5_path), \"File does not exist: {}\".format(fast5_path)\n # create Fast5 object and sanity check\n f5fh = Fast5(fast5_path, read='r+')\n if not f5fh.has_basecall_data():\n f5fh.close()\n return None\n\n # gather previous event detection\n old_event_table = f5fh.get_basecall_data()\n\n read_id = bytes.decode(f5fh.raw_attributes['read_id'])\n sampling_freq = f5fh.sample_rate\n start_time = f5fh.raw_attributes['start_time']\n\n # get params\n if params is None: params = get_default_event_detection_params(\n EVENT_DETECT_SPEEDY if speedy else EVENT_DETECT_MINKNOW)\n\n # pick event detection algorithm\n signal = f5fh.get_read(raw=True, scale=True)\n if speedy:\n event_table = create_speedy_event_table(signal, sampling_freq, start_time, **params)\n params = merge_dicts([params, {\"event_detection\": \"speedy_stat_split\"}])\n else:\n event_table = create_minknow_event_table(signal, sampling_freq, start_time, **params)\n params = merge_dicts([params, {\"event_detection\": \"minknow_event_detect\"}])\n\n # metadata\n keys = [\"nanotensor version\", \"time_stamp\"]\n values = [\"0.2.0\", TimeStamp().posix_date()]\n attributes = merge_dicts([params, dict(zip(keys, values)), f5fh.raw_attributes])\n\n # do resegmentation\n if f5fh.is_read_rna():\n old_event_table = index_to_time(old_event_table, sampling_freq=sampling_freq, start_time=start_time)\n new_event_table = create_anchor_kmers(new_events=event_table, old_events=old_event_table)\n\n # get destination in fast5\n #todo find latest location? ie: save_event_table_and_fastq(..)\n destination = f5fh._join_path(f5fh.__base_analysis__, analysis_path)\n\n f5fh.set_event_table(destination, new_event_table, attributes, overwrite=overwrite)\n\n # gather new sequence\n sequence = sequence_from_events(new_event_table)\n if f5fh.is_read_rna():\n sequence = ReverseComplement().reverse(sequence)\n sequence = sequence.replace(\"T\", \"U\")\n quality_scores = '!'*len(sequence)\n fastq = create_fastq_line(read_id+\" :\", sequence, quality_scores)\n\n # set fastq\n f5fh.set_fastq(destination, fastq, overwrite=overwrite)\n return f5fh\n\n\ndef get_default_event_detection_params(event_detection_strategy):\n if event_detection_strategy == EVENT_DETECT_SPEEDY:\n return dict(min_width=5, max_width=80, min_gain_per_sample=0.008, window_width=800)\n elif event_detection_strategy == EVENT_DETECT_MINKNOW:\n return dict(window_lengths=(5, 10), thresholds=(2.0, 1.1), peak_height=1.2)\n elif event_detection_strategy == EVENT_DETECT_SCRAPPIE:\n return {}\n else:\n return None\n\n\ndef generate_events_and_alignment(fast5_path, nucleotide_sequence, nucleotide_qualities=None,\n event_detection_params=None, event_detection_strategy=None,\n save_to_fast5=True, overwrite=False,\n analysis_identifier=Fast5.__default_basecall_1d_analysis__, ):\n\n assert os.path.isfile(fast5_path), \"File does not exist: {}\".format(fast5_path)\n\n # create Fast5 object\n f5fh = Fast5(fast5_path, read='r+')\n read_id = bytes.decode(f5fh.raw_attributes['read_id'])\n sampling_freq = f5fh.sample_rate\n start_time = f5fh.raw_attributes['start_time']\n success = False\n\n # event detection prep\n if event_detection_strategy is None:\n event_detection_strategy = EVENT_DETECT_MINKNOW\n if event_detection_params is None:\n event_detection_params = get_default_event_detection_params(event_detection_strategy)\n\n # detect events\n if event_detection_strategy == EVENT_DETECT_SPEEDY:\n signal = f5fh.get_read(raw=True, scale=True)\n event_table = create_speedy_event_table(signal, sampling_freq, start_time, **event_detection_params)\n event_detection_params = merge_dicts([event_detection_params, {\"event_detection\": \"speedy_stat_split\"}])\n elif event_detection_strategy == EVENT_DETECT_MINKNOW:\n signal = f5fh.get_read(raw=True, scale=True)\n event_table = create_minknow_event_table(signal, sampling_freq, start_time, **event_detection_params)\n event_detection_params = merge_dicts([event_detection_params, {\"event_detection\": \"minknow_event_detect\"}])\n elif event_detection_strategy == EVENT_DETECT_SCRAPPIE:\n event_table = create_scrappie_event_table(fast5_path, sampling_freq)\n event_detection_params = merge_dicts([event_detection_params, {\"event_detection\": \"scrappie_event_detect\"}])\n else:\n raise Exception(\"PROGRAMMER ERROR: unknown resegment strat {}: expected {}\"\n .format(event_detection_strategy, [EVENT_DETECT_SPEEDY, EVENT_DETECT_MINKNOW, EVENT_DETECT_SCRAPPIE]))\n\n # gather attributes\n keys = [\"nanotensor version\", \"time_stamp\"]\n values = [\"0.2.0\", TimeStamp().posix_date()]\n attributes = merge_dicts([event_detection_params, dict(zip(keys, values)), f5fh.raw_attributes])\n\n # do the alignment\n # todo do_alignment(events, nucleotide_sequence)\n # success = evaluate_success()\n\n # save to fast5 (if appropriate)\n saved_location = None\n if save_to_fast5:\n fastq = create_fastq_line(read_id, nucleotide_sequence,\n \"*\" if nucleotide_qualities is None else nucleotide_qualities)\n saved_location = save_event_table_and_fastq(f5fh, event_table, fastq, attributes=attributes,\n overwrite=overwrite, analysis_identifier=analysis_identifier)\n\n # close\n f5fh.close()\n\n return success, event_table, saved_location\n\n\ndef save_event_table_and_fastq(f5fh, event_table, fastq_line, attributes=None, overwrite=False,\n analysis_identifier=Fast5.__default_basecall_1d_analysis__):\n # get destination root\n if overwrite:\n try:\n # get current identifier\n destination = f5fh.get_analysis_latest(analysis_identifier)\n f5fh.delete(destination, ignore=True)\n except IndexError:\n # doesn't exist, get initial location (ie Basecall_000)\n destination = f5fh.get_analysis_new(analysis_identifier)\n else:\n # get incremented directory for identifier\n destination = f5fh.get_analysis_new(analysis_identifier)\n\n # set event table (if present)\n if event_table is not None:\n f5fh.set_event_table(destination, event_table, attributes)\n\n # set nucleotide sequence (if present)\n if fastq_line is not None:\n f5fh.set_fastq(destination, fastq_line)\n\n return destination\n\n\ndef index_to_time(basecall_events, sampling_freq=0, start_time=0):\n \"\"\"Convert RNA basecall read start and length from indexes to time stamps\n\n :param basecall_events: basecall events from albacore/metricore basecalled event table\n :param sampling_freq: sampling frequency of experiment\n :param start_time: start time of experiment via fasta5 file\n \"\"\"\n check_numpy_table(basecall_events, req_fields=('start', 'length'))\n assert basecall_events[\"start\"].dtype is np.dtype('uint64'), \"Event start should be np.int32 type: {}\"\\\n .format(basecall_events[\"start\"].dtype)\n assert sampling_freq != 0, \"Must set sampling frequency\"\n assert start_time != 0, \"Must set start time\"\n\n event_table = change_np_field_type(basecall_events, 'start', float)\n event_table = change_np_field_type(event_table, 'length', float)\n event_table[\"start\"] = (event_table[\"start\"] / sampling_freq) + (start_time / sampling_freq)\n event_table[\"length\"] = event_table[\"length\"] / float(sampling_freq)\n return event_table\n\n\ndef time_to_index(event_table, sampling_freq=0, start_time=0):\n \"\"\"Convert start and lengths from time to raw signal indexes\n\n :param event_table: basecall events from albacore/metricore basecalled event table\n :param sampling_freq: sampling frequency of experiment\n :param start_time: start time of experiment via fasta5 file\n \"\"\"\n check_numpy_table(event_table, req_fields=('start', 'length'))\n assert event_table[\"start\"].dtype is not np.dtype('uint64'), \"Event start should not be np.int32 type: {}\" \\\n .format(event_table[\"start\"].dtype)\n assert sampling_freq != 0, \"Must set sampling frequency\"\n assert start_time != 0, \"Must set start time\"\n\n event_table[\"start\"] = np.round((event_table[\"start\"] - (start_time / float(sampling_freq))) * sampling_freq)\n event_table[\"length\"] = np.round(event_table[\"length\"] * sampling_freq)\n event_table = change_np_field_type(event_table, 'start', int)\n event_table = change_np_field_type(event_table, 'length', int)\n\n return event_table\n\n\ndef sequence_from_events(events):\n \"\"\"Get new read from event table with 'model_state' and 'move' fields\n\n :param events: event table with 'model_state' and 'move' fields\n\n \"\"\"\n check_numpy_table(events, req_fields=(\"model_state\", \"move\"))\n bases = []\n for i, event in enumerate(events):\n if i == 0:\n bases.extend([chr(x) for x in event['model_state']])\n\n else:\n if event['move'] > 0:\n bases.append(bytes.decode\n (event['model_state'][-event['move']:]))\n sequence = ''.join(bases)\n return sequence\n\n\ndef get_resegment_accuracy(fast5handle, section=\"template\"):\n \"\"\"Get accuracy comparison between original sequence and resegmented generated sequence\n\n :param fast5handle: Fast5 object with re-segemented read\n \"\"\"\n assert isinstance(fast5handle, Fast5), \"fast5handle needs to be a Fast5 instance\"\n # get fastqs\n resegment_fastq = fast5handle.get_fastq(analysis=\"ReSegmentBasecall\", section=section)\n original_fastq = fast5handle.get_fastq(analysis=\"Basecall_1D\", section=section)[:-1]\n # make sure the underlying assumption that we can split on newline is ok\n check_fastq_line(resegment_fastq)\n check_fastq_line(original_fastq)\n # get sequence\n resegment_seq = resegment_fastq.split('\\n')[1]\n original_seq = original_fastq.split('\\n')[1]\n return pairwise_alignment_accuracy(original_seq, resegment_seq, soft_clip=True)\n\n\ndef create_minknow_events_from_fast5(fast5_path, window_lengths=(3, 6), thresholds=(1.4, 9.0), peak_height=0.2):\n \"\"\"Create events with ('start', 'length', 'mean', 'stdv', 'model_state', 'move', 'p_model_state') fields from\n fast5 file. The 'model_state', 'move' and 'p_model_state' are all empty\n\n :param fast5_path: path to fast5 file\n :param window_lengths: Length 2 list of window lengths across\n raw data from which `t_stats` are derived\n :param thresholds: Length 2 list of thresholds on t-statistics\n :param peak_height: Absolute height a peak in signal must rise below\n previous and following minima to be considered relevant\n \"\"\"\n assert os.path.isfile(fast5_path), \"File does not exist: {}\".format(fast5_path)\n f5fh = Fast5(fast5_path, read='r+')\n signal = f5fh.get_read(raw=True, scale=True)\n # read_id = bytes.decode(f5fh.raw_attributes['read_id'])\n sampling_freq = f5fh.sample_rate\n start_time = f5fh.raw_attributes['start_time']\n #\n event_table = create_minknow_event_table(signal, sampling_freq, start_time, window_lengths=window_lengths,\n thresholds=thresholds, peak_height=peak_height)\n\n return event_table, f5fh\n\n\ndef main():\n \"\"\"Main docstring\"\"\"\n start = timer()\n\n dna_reads = \"/Users/andrewbailey/CLionProjects/nanopore-RNN/test_files/minion-reads/canonical/\"\n rna_reads = \"/Users/andrewbailey/CLionProjects/nanopore-RNN/test_files/minion-reads/rna_reads\"\n\n dna_minknow_params = dict(window_lengths=(5, 10), thresholds=(2.0, 1.1), peak_height=1.2)\n dna_speedy_params = dict(min_width=5, max_width=80, min_gain_per_sample=0.008, window_width=800)\n rna_minknow_params = dict(window_lengths=(5, 10), thresholds=(2.0, 1.1), peak_height=1.2)\n rna_speedy_params = dict(min_width=5, max_width=40, min_gain_per_sample=0.008, window_width=800)\n\n\n rna_minknow_params = dict(window_lengths=(5, 10), thresholds=(1.9, 1.0), peak_height=1.2)\n rna_speedy_params = dict(min_width=5, max_width=40, min_gain_per_sample=0.008, window_width=800)\n dna_minknow_params = dict(window_lengths=(5, 10), thresholds=(2.0, 1.1), peak_height=1.2)\n dna_speedy_params = dict(min_width=5, max_width=80, min_gain_per_sample=0.008, window_width=800)\n\n rna_files = list_dir(rna_reads, ext='fast5')\n dna_files = list_dir(dna_reads, ext='fast5')\n print(\"MAX RNA SKIPS: Speedy\")\n for fast5_path in rna_files:\n print(fast5_path)\n f5fh = resegment_reads(fast5_path, rna_speedy_params, speedy=True, overwrite=True)\n print(get_resegment_accuracy(f5fh))\n # f5fh = resegment_reads(fast5_path, rna_minknow_params, speedy=False, overwrite=True)\n # print(test_resegment_accuracy(f5fh))\n\n print(\"MAX RNA SKIPS: Minknow\")\n for fast5_path in rna_files:\n f5fh = resegment_reads(fast5_path, rna_minknow_params, speedy=False, overwrite=True)\n print(get_resegment_accuracy(f5fh))\n\n print(\"MAX DNA SKIPS: speedy\")\n for fast5_path in dna_files:\n print(fast5_path)\n f5fh = resegment_reads(fast5_path, dna_speedy_params, speedy=True, overwrite=True)\n print(get_resegment_accuracy(f5fh))\n print(\"MAX DNA SKIPS:Minknow\")\n for fast5_path in dna_files:\n f5fh = resegment_reads(fast5_path, dna_minknow_params, speedy=False, overwrite=True)\n print(get_resegment_accuracy(f5fh))\n\n # print(fast5_path)\n stop = timer()\n print(\"Running Time = {} seconds\".format(stop - start), file=sys.stderr)\n\n\nif __name__ == \"__main__\":\n main()\n\n raise SystemExit\n","sub_path":"src/signalalign/event_detection.py","file_name":"event_detection.py","file_ext":"py","file_size_in_byte":28950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"180381622","text":"from align_model import AlignModel\nfrom easy_srl_interface import easy_srl_interface\nfrom graph_utils import display_graph\nfrom states import Relation\nfrom syntax_parser import stanford_parser\nimport networkx as nx\n\n__author__ = 'minjoon'\n\n\nclass RelGenModel(object):\n def __init__(self):\n pass\n\n def get_relations(self, question, diagram_tree):\n raise Exception(\"Must be defined.\")\n\n @staticmethod\n def tokenize(string):\n return str(string).lower().split(\" \")\n\n\nclass DPRelGenModel(RelGenModel):\n def __init__(self, align_model, dep_parses=None):\n super(DPRelGenModel, self).__init__()\n assert isinstance(align_model, AlignModel)\n self.align_model = align_model\n self.dep_parses = dep_parses\n\n def get_relations(self, question, diagram_tree, problem_id=None):\n if self.dep_parses is not None and problem_id is not None and problem_id in self.dep_parses:\n dep_parse = self.dep_parses[problem_id]\n else:\n dep_parse = stanford_parser.get_best_syntax_parse(question)\n head = nx.topological_sort(dep_parse.directed)[0]\n predicate = [question[head]]\n arg0 = self.align_model.match(question, diagram_tree)\n arg1 = \"ANSWER\"\n return [[arg0, predicate, arg1]]\n\n def merge_choice(self, relation, choice, diagram_tree):\n arg1 = self.align_model.match(choice, diagram_tree)\n merged_relation = (relation[0], relation[1], arg1)\n return merged_relation\n\n","sub_path":"rel_gen_model.py","file_name":"rel_gen_model.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"194077313","text":"from socket import *\nfrom threading import Thread\nimport platform\nimport pickle\nimport json\nimport time\nfrom queue import PriorityQueue\n\n# config\nport = 8006\n\n# регистрация имени пользователя\n# name_in_chat = input('Введите ваше имя для входа в чат: ')\nname_in_chat = 'Виктор'\nusr_group = None\n\n\ndef send(socket, msg):\n socket.send(pickle.dumps(json.dumps(msg)))\n\n\ndef load_print(socket):\n data = json.loads(pickle.loads(socket.recv(2048)))\n # print('Сообщение от сервера: ', data)\n return data\n\n\ndef registration():\n # создание псевдоуникального токена\n sys_info = platform.uname()\n usr_data = {'system': f'{sys_info[0]}',\n 'node': f'{sys_info[1]}',\n 'release': f'{sys_info[2]}',\n 'version': f'{sys_info[3]}',\n 'machine': f'{sys_info[4]}',\n 'processor': f'{sys_info[5]}',\n 'name_in_chat': f'{name_in_chat}'\n }\n\n s = socket(AF_INET, SOCK_STREAM) # Создать сокет TCP\n s.connect(('localhost', port)) # Соединиться с сервером\n\n reg_msg = {\n 'action': 'registration',\n 'time': f'{time.time()}',\n 'user_name': f'{name_in_chat}',\n 'user': f'{usr_data}'\n }\n\n send(s, reg_msg)\n reg_data = load_print(s)\n for k, v in reg_data.items():\n if v.get('response') == 200:\n guid = k\n return s, guid, usr_data\n else:\n print('Ошибка регистарции')\n\n\ndef send_message(sock, guid, q, usr_data, group=None):\n def create_message(*args):\n send_message_msg = {\n 'action': 'send_message',\n 'time': f'{time.time()}',\n 'from_user_name': f'{name_in_chat}',\n 'from_guid': f'{guid}',\n 'to_user_name': f'{to_user_name}',\n 'to_guid': f'{to_guid}',\n 'message': f'{message}',\n }\n return send_message_msg\n\n if group is None:\n to_guid = int(input('Введите кому пишем: '))\n message = 'Личное:' + input('Введите ваше ссобщение: ')\n smsg = get_list(sock, guid, q, usr_data)\n to_user_name = smsg.get(f'{to_guid}').get('user_name')\n send(sock, create_message(to_user_name, to_guid, message))\n\n elif group != 'All' and group is not None:\n message = 'Групповое:' + input('Введите ваше ссобщение: ')\n smsg = get_list(sock, guid, q, usr_data)\n for to_guid, v in smsg.items():\n if str(v.get('group')) == usr_group:\n to_user_name = v.get('user_name')\n send(sock, create_message(to_user_name, to_guid, message))\n\n elif group == 'All':\n message = 'Публичное:' + input('Введите ваше ссобщение: ')\n smsg = get_list(sock, guid, q, usr_data)\n for to_guid, user_data in smsg.items():\n to_user_name = user_data.get('user_name')\n send(sock, create_message(to_user_name, to_guid, message))\n\n\ndef rec_message(sock, guid, q):\n while True:\n q.put(load_print(sock))\n req = q.queue[0].get('action')\n if req == 'rec_message':\n msg = q.get()\n if msg.get('response') == 200:\n pass\n elif 'response' not in msg:\n print(f'У Вас новое сообщение от {msg.get(\"from_user_name\")}:\\n'\n f'{msg.get(\"message\")}')\n resp_msg = {\n 'response': 200,\n 'action': 'send_message',\n 'time': f'{time.time()}',\n 'from_user_name': f'{name_in_chat}',\n 'from_guid': f'{guid}',\n 'to_user_name': f'{msg.get(\"from_user_name\")}',\n 'to_guid': f'{msg.get(\"from_guid\")}',\n 'alert': 'Сообщение доставлено'\n }\n send(sock, resp_msg)\n elif req == 'ping':\n q.get()\n resp_msg = {\n 'response': 200,\n 'action': 'ping',\n 'time': f'{time.time()}',\n 'guid': f'{guid}',\n 'alert': 'я тут'\n }\n send(sock, resp_msg)\n else:\n pass\n\n\ndef get_list(sock, guid, q, usr_data, group=None):\n get_list_msg = {\n 'action': 'get_user_list',\n 'time': f'{time.time()}',\n 'user_name': f'{name_in_chat}',\n 'group': group,\n 'user': f'{usr_data}',\n }\n send(sock, get_list_msg)\n msg = q.get()\n data = msg.get(f'{guid}').get('alert')\n print(data)\n return data\n\n\ndef leave(sock, guid, q, usr_data):\n leave_msg = {\n 'action': 'leave',\n 'time': f'{time.time()}',\n 'user': {\n 'user_name': f'{name_in_chat}',\n 'user': f'{usr_data}'\n }\n }\n send(sock, leave_msg)\n msg = q.get()\n data = msg.get(f'{guid}').get('alert')\n print(data)\n exit()\n\n\ndef show_group(sock, guid, q, usr_data):\n get_gr_list_msg = {\n 'action': 'show_group',\n 'time': f'{time.time()}',\n 'user_name': f'{name_in_chat}',\n 'user': f'{usr_data}'\n }\n send(sock, get_gr_list_msg)\n msg = q.get()\n data = msg.get(f'{guid}').get('alert')\n print(data)\n return data\n\n\ndef open_group(sock, guid, q, usr_data):\n global usr_group\n show_group(sock, guid, q, usr_data)\n group_id = int(input('Введите номер группы: '))\n open_msg = {\n 'action': 'open_group',\n 'time': f'{time.time()}',\n 'user_name': f'{name_in_chat}',\n 'group_id': group_id,\n 'user': f'{usr_data}'\n }\n send(sock, open_msg)\n msg = q.get()\n data = msg.get(f'{guid}')\n if data.get('response') == 200:\n usr_group = f'{group_id}'\n print(data.get('alert'))\n\n\ndef create_group(sock, guid, q, usr_data):\n global usr_group\n group_name = input('Введите название группы: ')\n create_group_msg = {\n 'action': 'create_group',\n 'time': f'{time.time()}',\n 'user_group': group_name,\n 'user_name': f'{name_in_chat}',\n 'user': f'{usr_data}'\n }\n send(sock, create_group_msg)\n msg = q.get()\n data = msg.get(f'{guid}')\n if data.get('response') == 200:\n groups = show_group(sock, guid, q, usr_data)\n for i, n in groups.items():\n if n == group_name:\n usr_group = i\n print(data.get('alert'))\n\n\ndef exit_of_group(sock, guid, q, usr_data):\n exit_of_group_msg = {\n 'action': 'exit_of_group',\n 'time': f'{time.time()}',\n 'user_name': f'{name_in_chat}',\n 'user': f'{usr_data}'\n }\n send(sock, exit_of_group_msg)\n msg = q.get()\n data = msg.get(f'{guid}').get('alert')\n print(data)\n\n\ndef menu(sock, guid, usr_data, q):\n continuer = ''\n while continuer.upper() != 'Q':\n try:\n print('Введите:\\n',\n '\"1\"- чтобы получить список пользователей в чате\\n',\n '\"2\" - чтобы написать сообщение пользователю\\n',\n '\"3\" - чтобы написать сообщение всем кто в онлайне\\n',\n '\"4\" - чтобы написать сообщение пользователям в группу\\n',\n '\"Q\" - чтобы покинуть чат\\n')\n continuer = input(': ')\n\n if continuer == '1':\n get_list(sock, guid, q, usr_data)\n elif continuer == '2':\n send_message(sock, guid, q, usr_data)\n elif continuer == '3':\n send_message(sock, guid, q, usr_data, 'All')\n elif continuer == '4':\n while continuer.upper() != 'Q' or 'B':\n print('Введите:\\n',\n '\"1\"- чтобы получить список групп\\n',\n '\"2\" - чтобы войти в группу\\n',\n '\"3\" - создать группу\\n',\n '\"4\" - чтобы выйти из группы\\n',\n '\"5\" - чтобы написать сообщение в группу\\n',\n '\"B\" - попасть в меню выше\\n',\n '\"Q\" - чтобы покинуть чат\\n')\n continuer = input(': ')\n if continuer == '1':\n show_group(sock, guid, q, usr_data)\n elif continuer == '2':\n open_group(sock, guid, q, usr_data)\n elif continuer == '3':\n create_group(sock, guid, q, usr_data)\n elif continuer == '4':\n exit_of_group(sock, guid, q, usr_data)\n elif continuer == '5':\n send_message(sock, guid, q, usr_data, usr_group)\n elif continuer == 'b' or continuer == 'B':\n break\n elif continuer == 'q' or continuer == 'Q':\n leave(sock, guid, q, usr_data)\n elif continuer == 'q' or continuer == 'Q':\n leave(sock, guid, q, usr_data)\n else:\n print('Вы ввели значение не из списка')\n except:\n pass\n\n\ndef main():\n input_queue = PriorityQueue()\n s, guid, usr_data = registration()\n t = Thread(target=rec_message, args=(s, guid, input_queue))\n t.daemon = True\n t.start()\n menu(s, guid, usr_data, input_queue)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"chat/Lesson8/client_2.py","file_name":"client_2.py","file_ext":"py","file_size_in_byte":9923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"189971415","text":"\"\"\"\n 内置可重写函数\n 练习:exercise01.py\n\"\"\"\n\nclass StudentModel:\n def __init__(self, name=\"\", age=0, score=0, id=0):\n self.name = name\n self.age = age\n self.score = score\n self.id = id\n\n # 对象 --> 字符串 (随意格式)\n def __str__(self):\n return \"我叫%s,编号是%d,年龄是%d,成绩是:%d\"%(self.name,self.id,self.age,self.score)\n\n # 对象 --> 字符串(解释器可识别,有格式)\n def __repr__(self):\n return \"StudentModel('%s',%d,%d,%d)\"%(self.name,self.age,self.score,self.id)\n\n\ns01 = StudentModel(\"无忌\",27,100,101)\nstr01 = str(s01)\nprint(str01)\nprint(s01)\n\nstr02 =repr(s01)\nprint(str02)\n\n# 根据字符串执行python代码\nre = eval(\"1+2*5\")\n# exec\nprint(re)\n\n# 克隆对象\n# repr 返回python格式的字符串\n# eval根据字符串执行代码\ns02 = eval(repr(s01))\ns02.name = \"老张\"\nprint(s01.name)\n\n\n\n\n\n\n\n\n\n","sub_path":"python_one_learn/day14/demo01.py","file_name":"demo01.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"68634180","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.11-intel/egg/esl/formatter.py\n# Compiled at: 2016-04-16 02:22:25\nfrom __future__ import absolute_import\nimport json, pygments.lexer, pygments.token, pygments.styles, pygments.lexers, pygments.style\nfrom pygments.formatters.terminal256 import Terminal256Formatter\nfrom pygments.lexers.special import TextLexer\nfrom pygments.util import ClassNotFound\nAVAILABLE_STYLES = set(pygments.styles.STYLE_MAP.keys())\nAVAILABLE_STYLES.add('solarized')\nDEFAULT_STYLE = 'solarized'\n\nclass ColorFormatter(object):\n \"\"\"\n Colorize using Pygments\n\n This processor that applies syntax highlighting to the headers,\n and also to the body if its content type is recognized.\n\n \"\"\"\n\n def __init__(self, explicit_json=False, color_scheme=DEFAULT_STYLE, **kwargs):\n super(ColorFormatter, self).__init__(**kwargs)\n self.explicit_json = explicit_json\n try:\n style_class = pygments.styles.get_style_by_name(color_scheme)\n except ClassNotFound:\n style_class = Solarized256Style\n\n self.formatter = Terminal256Formatter(style=style_class)\n\n def format_headers(self, headers):\n return pygments.highlight(headers, HTTPLexer(), self.formatter).strip()\n\n def format_body(self, body, mime):\n lexer = self.get_lexer(mime, body)\n if lexer:\n body = pygments.highlight(body, lexer, self.formatter)\n return body.strip()\n\n def get_lexer(self, mime, body):\n return get_lexer(mime=mime, explicit_json=self.explicit_json, body=body)\n\n\ndef get_lexer(mime, explicit_json=False, body=''):\n mime_types, lexer_names = [\n mime], []\n type_, subtype = mime.split('/', 1)\n if '+' not in subtype:\n lexer_names.append(subtype)\n else:\n subtype_name, subtype_suffix = subtype.split('+', 1)\n lexer_names.extend([subtype_name, subtype_suffix])\n mime_types.extend([\n '%s/%s' % (type_, subtype_name),\n '%s/%s' % (type_, subtype_suffix)])\n if 'json' in subtype:\n lexer_names.append('json')\n lexer = None\n for mime_type in mime_types:\n try:\n lexer = pygments.lexers.get_lexer_for_mimetype(mime_type)\n break\n except ClassNotFound:\n pass\n\n else:\n for name in lexer_names:\n try:\n lexer = pygments.lexers.get_lexer_by_name(name)\n except ClassNotFound:\n pass\n\n if explicit_json and body and (not lexer or isinstance(lexer, TextLexer)):\n try:\n json.loads(body)\n except ValueError:\n pass\n else:\n lexer = pygments.lexers.get_lexer_by_name('json')\n\n return lexer\n\n\nclass HTTPLexer(pygments.lexer.RegexLexer):\n \"\"\"Simplified HTTP lexer for Pygments.\n\n It only operates on headers and provides a stronger contrast between\n their names and values than the original one bundled with Pygments\n (:class:`pygments.lexers.text import HttpLexer`), especially when\n Solarized color scheme is used.\n\n \"\"\"\n name = 'HTTP'\n aliases = ['http']\n filenames = ['*.http']\n tokens = {'root': [\n (\n '([A-Z]+)( +)([^ ]+)( +)(HTTP)(/)(\\\\d+\\\\.\\\\d+)',\n pygments.lexer.bygroups(pygments.token.Name.Function, pygments.token.Text, pygments.token.Name.Namespace, pygments.token.Text, pygments.token.Keyword.Reserved, pygments.token.Operator, pygments.token.Number)),\n (\n '(HTTP)(/)(\\\\d+\\\\.\\\\d+)( +)(\\\\d{3})( +)(.+)',\n pygments.lexer.bygroups(pygments.token.Keyword.Reserved, pygments.token.Operator, pygments.token.Number, pygments.token.Text, pygments.token.Number, pygments.token.Text, pygments.token.Name.Exception)),\n (\n '(.*?)( *)(:)( *)(.+)',\n pygments.lexer.bygroups(pygments.token.Name.Attribute, pygments.token.Text, pygments.token.Operator, pygments.token.Text, pygments.token.String))]}\n\n\nclass Solarized256Style(pygments.style.Style):\n \"\"\"\n solarized256\n ------------\n\n A Pygments style inspired by Solarized's 256 color mode.\n\n :copyright: (c) 2011 by Hank Gay, (c) 2012 by John Mastro.\n :license: BSD, see LICENSE for more details.\n\n \"\"\"\n BASE03 = '#1c1c1c'\n BASE02 = '#262626'\n BASE01 = '#4e4e4e'\n BASE00 = '#585858'\n BASE0 = '#808080'\n BASE1 = '#8a8a8a'\n BASE2 = '#d7d7af'\n BASE3 = '#ffffd7'\n YELLOW = '#af8700'\n ORANGE = '#d75f00'\n RED = '#af0000'\n MAGENTA = '#af005f'\n VIOLET = '#5f5faf'\n BLUE = '#0087ff'\n CYAN = '#00afaf'\n GREEN = '#5f8700'\n background_color = BASE03\n styles = {pygments.token.Keyword: GREEN, \n pygments.token.Keyword.Constant: ORANGE, \n pygments.token.Keyword.Declaration: BLUE, \n pygments.token.Keyword.Namespace: ORANGE, \n pygments.token.Keyword.Reserved: BLUE, \n pygments.token.Keyword.Type: RED, \n pygments.token.Name.Attribute: BASE1, \n pygments.token.Name.Builtin: BLUE, \n pygments.token.Name.Builtin.Pseudo: BLUE, \n pygments.token.Name.Class: BLUE, \n pygments.token.Name.Constant: ORANGE, \n pygments.token.Name.Decorator: BLUE, \n pygments.token.Name.Entity: ORANGE, \n pygments.token.Name.Exception: YELLOW, \n pygments.token.Name.Function: BLUE, \n pygments.token.Name.Tag: BLUE, \n pygments.token.Name.Variable: BLUE, \n pygments.token.String: CYAN, \n pygments.token.String.Backtick: BASE01, \n pygments.token.String.Char: CYAN, \n pygments.token.String.Doc: CYAN, \n pygments.token.String.Escape: RED, \n pygments.token.String.Heredoc: CYAN, \n pygments.token.String.Regex: RED, \n pygments.token.Number: CYAN, \n pygments.token.Operator: BASE1, \n pygments.token.Operator.Word: GREEN, \n pygments.token.Comment: BASE01, \n pygments.token.Comment.Preproc: GREEN, \n pygments.token.Comment.Special: GREEN, \n pygments.token.Generic.Deleted: CYAN, \n pygments.token.Generic.Emph: 'italic', \n pygments.token.Generic.Error: RED, \n pygments.token.Generic.Heading: ORANGE, \n pygments.token.Generic.Inserted: GREEN, \n pygments.token.Generic.Strong: 'bold', \n pygments.token.Generic.Subheading: ORANGE, \n pygments.token.Token: BASE1, \n pygments.token.Token.Other: ORANGE}","sub_path":"pycfiles/esl-0.5.1-py2.7/formatter.py","file_name":"formatter.py","file_ext":"py","file_size_in_byte":6534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"303766021","text":"#coding: utf-8\nfrom functools import wraps\nimport inspect\nimport itertools\nfrom . import mommy\nfrom .timezone import tz_aware\nfrom .exceptions import RecipeNotFound, RecipeIteratorEmpty\n\nfrom six import string_types\nimport datetime\n\n\n# Python 2.6.x compatibility code\nitertools_count = itertools.count\ntry:\n itertools_count(0, 1)\nexcept TypeError:\n def count(start=0, step=1):\n n = start\n while True:\n yield n\n n += step\n itertools_count = count\n\nfinder = mommy.ModelFinder()\n\nclass Recipe(object):\n def __init__(self, model, **attrs):\n self.attr_mapping = attrs\n self.model = model\n # _iterator_backups will hold values of the form (backup_iterator, usable_iterator).\n self._iterator_backups = {}\n\n def _mapping(self, new_attrs):\n _save_related = new_attrs.get('_save_related', True)\n rel_fields_attrs = dict((k, v) for k, v in new_attrs.items() if '__' in k)\n new_attrs = dict((k, v) for k, v in new_attrs.items() if not '__' in k)\n mapping = self.attr_mapping.copy()\n for k, v in self.attr_mapping.items():\n # do not generate values if field value is provided\n if new_attrs.get(k):\n continue\n elif mommy.is_iterator(v):\n if isinstance(self.model, string_types):\n m = finder.get_model(self.model)\n else:\n m = self.model\n if m.objects.count() == 0 or k not in self._iterator_backups:\n self._iterator_backups[k] = itertools.tee(self._iterator_backups.get(k, [v])[0])\n mapping[k] = self._iterator_backups[k][1]\n elif isinstance(v, RecipeForeignKey):\n a={}\n for key, value in list(rel_fields_attrs.items()):\n if key.startswith('%s__' % k):\n a[key] = rel_fields_attrs.pop(key)\n recipe_attrs = mommy.filter_rel_attrs(k, **a)\n if _save_related:\n mapping[k] = v.recipe.make(**recipe_attrs)\n else:\n mapping[k] = v.recipe.prepare(**recipe_attrs)\n elif isinstance(v, related):\n mapping[k] = v.make()\n mapping.update(new_attrs)\n mapping.update(rel_fields_attrs)\n return mapping\n\n def make(self, **attrs):\n return mommy.make(self.model, **self._mapping(attrs))\n\n def prepare(self, **attrs):\n defaults = {'_save_related': False}\n defaults.update(attrs)\n return mommy.prepare(self.model, **self._mapping(defaults))\n\n def extend(self, **attrs):\n attr_mapping = self.attr_mapping.copy()\n attr_mapping.update(attrs)\n return Recipe(self.model, **attr_mapping)\n\n\nclass RecipeForeignKey(object):\n\n def __init__(self, recipe):\n if isinstance(recipe, Recipe):\n self.recipe = recipe\n elif isinstance(recipe, string_types):\n frame = inspect.stack()[2]\n caller_module = inspect.getmodule(frame[0])\n recipe = getattr(caller_module, recipe)\n if recipe:\n self.recipe = recipe\n else:\n raise RecipeNotFound\n else:\n raise TypeError('Not a recipe')\n\n\ndef foreign_key(recipe):\n \"\"\"\n Returns the callable, so that the associated model\n will not be created during the recipe definition.\n \"\"\"\n return RecipeForeignKey(recipe)\n\n\ndef _total_secs(td):\n \"\"\"\n python 2.6 compatible timedelta total seconds calculation\n backport from\n https://docs.python.org/2.7/library/datetime.html#datetime.timedelta.total_seconds\n \"\"\"\n if hasattr(td, 'total_seconds'):\n return td.total_seconds()\n else:\n #py26\n return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10.0**6\n\n\ndef seq(value, increment_by=1):\n if type(value) in [datetime.datetime, datetime.date, datetime.time]:\n if type(value) is datetime.date:\n date = datetime.datetime.combine(value, datetime.datetime.now().time())\n elif type(value) is datetime.time:\n date = datetime.datetime.combine(datetime.date.today(), value)\n else:\n date = value\n # convert to epoch time\n start = _total_secs((date - datetime.datetime(1970, 1, 1)))\n increment_by = _total_secs(increment_by)\n for n in itertools_count(increment_by, increment_by):\n series_date = tz_aware(datetime.datetime.utcfromtimestamp(start + n))\n if type(value) is datetime.time:\n yield series_date.time()\n elif type(value) is datetime.date:\n yield series_date.date()\n else:\n yield series_date\n else:\n for n in itertools_count(increment_by, increment_by):\n yield value + type(value)(n)\n\n\nclass related(object):\n def __init__(self, *args):\n self.related = []\n for recipe in args:\n if isinstance(recipe, Recipe):\n self.related.append(recipe)\n elif isinstance(recipe, string_types):\n frame = inspect.stack()[1]\n caller_module = inspect.getmodule(frame[0])\n recipe = getattr(caller_module, recipe)\n if recipe:\n self.related.append(recipe)\n else:\n raise RecipeNotFound\n else:\n raise TypeError('Not a recipe')\n\n def make(self):\n \"\"\"\n Persists objects to m2m relation\n \"\"\"\n return [m.make() for m in self.related]\n","sub_path":"myenv/lib/python3.5/site-packages/model_mommy/recipe.py","file_name":"recipe.py","file_ext":"py","file_size_in_byte":5649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"295483684","text":"\"\"\"Unit tests for Riemannian KMeans.\"\"\"\n\nimport geomstats.backend as gs\nimport geomstats.tests\nfrom geomstats.geometry import hypersphere\nfrom geomstats.geometry import spd_matrices\nfrom geomstats.learning.frechet_mean import FrechetMean\nfrom geomstats.learning.kmeans import RiemannianKMeans\n\n\nclass TestRiemannianKMeans(geomstats.tests.TestCase):\n _multiprocess_can_split_ = True\n\n @geomstats.tests.np_and_pytorch_only\n def test_hypersphere_kmeans_fit(self):\n gs.random.seed(55)\n\n manifold = hypersphere.Hypersphere(2)\n metric = hypersphere.HypersphereMetric(2)\n\n x = manifold.random_von_mises_fisher(kappa=100, n_samples=200)\n\n kmeans = RiemannianKMeans(metric, 1, tol=1e-3, lr=1.)\n kmeans.fit(x)\n center = kmeans.centroids\n\n mean = FrechetMean(metric=metric, lr=1.)\n mean.fit(x)\n\n result = metric.dist(center, mean.estimate_)\n expected = 0.\n self.assertAllClose(expected, result)\n\n @geomstats.tests.np_only\n def test_spd_kmeans_fit(self):\n gs.random.seed(0)\n dim = 3\n n_points = 2\n space = spd_matrices.SPDMatrices(dim)\n data = space.random_point(n_samples=n_points)\n metric = spd_matrices.SPDMetricAffine(dim)\n\n kmeans = RiemannianKMeans(\n metric, n_clusters=1, lr=1.)\n kmeans.fit(data)\n result = kmeans.centroids\n\n mean = FrechetMean(metric=metric, point_type='matrix', max_iter=100)\n mean.fit(data)\n expected = mean.estimate_\n self.assertAllClose(result, expected)\n\n @geomstats.tests.np_and_pytorch_only\n def test_hypersphere_kmeans_predict(self):\n gs.random.seed(1234)\n dim = 2\n\n manifold = hypersphere.Hypersphere(dim)\n metric = hypersphere.HypersphereMetric(dim)\n\n x = manifold.random_von_mises_fisher(kappa=100, n_samples=200)\n\n kmeans = RiemannianKMeans(metric, 5, tol=1e-5, lr=1.)\n kmeans.fit(x)\n result = kmeans.predict(x)\n\n centroids = kmeans.centroids\n expected = gs.array(\n [int(metric.closest_neighbor_index(x_i, centroids))\n for x_i in x])\n self.assertAllClose(expected, result)\n","sub_path":"tests/tests_geomstats/test_riemannian_kmeans.py","file_name":"test_riemannian_kmeans.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"436999762","text":"\"\"\"Both the operation interface and the task wrapper in this module.\"\"\"\n\nfrom queue import Queue\nfrom time import time\n\nimport sys\nimport thrush.engine.engine\n\nclass Task:\n \"\"\"The wrapper of a callback that will be called when the task is called.\n args:\n mailBox The FIFO queue that including the messages passing to the callback. \n For Function, the first value will be the argument of the callback; \n for generator, the first value will be the argument and the others will passed in turn as the yield value.\n barriers The List of barriers that will apply to the task.\n priority If a higher-priority task in the main queue, lower-priority tasks will not run.\n state A TaskState enum that descripbe the state of this task.\n startTime The time point this task last excuted. GuardWorker uses this field to check if a task is timeout.\n exception When a task is interrupted by a exception, the exception will be here. Note that a StopInteration will not be here ???? it's regarded as a normal action.\n timeout If this field is 0, no timeout check will applied. Unit is second.\n callback The function or generator that will be called when the task run.\n returnValue Return Value of callback. Note that for a generator, new yield value will cover the older one.\n followTask The task that will run after current task has closed or end by a exception. If current task has yield, follow task will not run.\n \"\"\"\n\n def __init__(self, callback, *args, priority = 8, timeout = 0, followTask = None):\n \"\"\"All unnamed arguments will be passed into mailBox as messages that will be passed to the callback.\n workAsGen If the callback will work as a generator.\"\"\"\n\n self._callback = None\n self._followTask = None\n \n self.mailBox = Queue()\n self.barriers = []\n self.priority = priority\n self.state = TaskState.Initialized\n self.startTime = 0\n self.exception = None\n self.timeout = timeout\n self.callback = callback\n self.returnValue = None\n self.followTask = None\n\n # When _typePending is True, Task doesn't know if the callback is a generator function.\n # After the first run of the callback, _typePending will be set to False: If return value is a generator, _workAsGenerator will be True and start the first generator right now; else, task will be close as the callback called.\n self._typePending = True\n self._workAsGenerator = False;\n\n # If some unnamed args are passed, put them into mailbox as default messages.\n for msg in args:\n self.mailBox.put(msg)\n\n @property\n def callback(self):\n return self._callback\n @callback.setter\n def setCallback(self, callback):\n \"\"\"\n The callback will be called when the task runs.\n Must be a function.\n \"\"\"\n if callback == None:\n return false\n\n if callable(callback):\n self._callback = callback\n else:\n raise ValueError(\"Callback of a task must be callable.\")\n\n @property\n def followTask(self):\n return self._followTask;\n\n @followTask.setter\n def setFollowTask(self, task):\n \"\"\"\n The follow task will be called after the task is closed.\n \"\"\"\n if task == None:\n return false\n\n if isinstance(task, Task):\n self._followTask = task\n else:\n raise ValueError(\"FollowTask must be a Task.\")\n\n @property\n def state(self):\n return self._state\n\n @state.setter\n def setState(self, value):\n self._state = value\n if self.state == TaskState.Closed or self.state == TaskState.Excepted:\n self.followTask.sendMessage(self)\n thrush.engine.engine.schedule(self.followTask)\n\n\n def checkBarriers(self):\n \"\"\"\n Check if all barriers are pasted.\n Only when checkBarriers returns a True, scheduler will run the task.\n \"\"\"\n for barrier in self.barriers:\n if barrier.pasted != True:\n return False\n\n return True\n\n def run(self):\n \"\"\"\n Run callback.\n \"\"\"\n # Prepare the argument of callback.\n # It's the to dequeue value of the mailbox queue.\n argument = None\n if self.mailBox.qsize() != 0:\n argument = self.mailBox.get_nowait()\n\n try:\n self.state = TaskState.Running\n \n if _workAsGenerator:\n if self._generatorFirstRun:\n self.returnValue = next(self._generator)\n self._generatorFirstRun = False\n else:\n self.returnValue = self._generator.Send(argument)\n else:\n callbackReturnValue = self.callback(argument)\n\n # If _typePending is True, it means that we haven't known if the callback is a generator function. Try to run the function and change the _typePending with the type check of callback's return value.\n if self._typePending == True:\n if isinstance(callbackReturnValue, generator):\n self._workAsGenerator = True\n self._generator = callbackReturnValue\n else:\n self._workAsGenerator = False\n self.returnValue = callbackReturnValue\n self.state = TaskState.Closed\n\n self._typePending = False\n\n # If it's a generator function's task, we have not run the generator for the first time yet.\n if self._workAsGenerator:\n run(self)\n else:\n self.returnValue = callbackReturnValue\n self.state = TaskState.Closed\n except StopIteration as exception:\n # For a StopIteration exception, check if the exception is raised in run() method.\n # If so, this exception is because generator yielded all its content as expection. The task will be closed.\n # Else, exception will wrapped into the exception field, and task will be set to Excepted to notice developer that the task has ended with a exception.\n exceptionInfo = sys.exc_info()\n frame = exc_info[2]\n if frame.tb_next == None:\n self.state = TaskState.Closed\n else:\n self.exception = exception\n self.state = TaskState.Excepted\n else:\n self.exception = exception\n self.state = TaskState.Excepted\n\n def sendMessage(self, message):\n \"\"\"\n Push a message to this task's mailbox.\n \"\"\"\n self.mailBox.put(message)\n\nclass TaskState:\n \"\"\"Enum different states of a task.\n Initialized A newly created task that has not been put into the main queue.\n Standby A task in the main queue.\n Running A task running.\n Closed A task that its callback has finaled, such as the function returned, the generator raise a StopIteration, or the function is interrupted by a exception.\n \"\"\"\n Initialized = \"initialized\"\n Standby = \"standby\"\n Running = \"running\"\n Closed = \"closed\"\n Excepted = \"excepted\"\n\n def __setattr__(self, name, value):\n members = vars(self)\n if members.get(name) != None:\n raise ValueError(\"Value of a enum should not be changed.\")","sub_path":"Thrush-Tasks/thrush/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":7658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"102595035","text":"import cv2\nfrom descriptors.gray_histogram import GrayHistogram\nfrom sklearn.cluster import KMeans\n\nclass ClusterImages:\n def __init__(self,images_paths):\n self.images_paths = images_paths\n def Cluster(self):\n\n desc = GrayHistogram([8])\n data = []\n\n for image_path in self.images_paths:\n image = cv2.imread(image_path)\n\n hist = desc.describe(image)\n data.append(hist)\n\n clt = KMeans(n_clusters=2)\n labels = clt.fit_predict(data)\n return labels\n","sub_path":"hsdetector/ClusterImages.py","file_name":"ClusterImages.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"107020624","text":"# 给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。\n#\n# 示例 1:\n# 输入: \"abcabcbb\"\n# 输出: 3\n# 解释: 因为无重复字符的最长子串是 \"abc\",所以其长度为 3。\n\n# 示例 2:\n# 输入: \"bbbbb\"\n# 输出: 1\n# 解释: 因为无重复字符的最长子串是 \"b\",所以其长度为 1。\n\n# 示例 3:\n# 输入: \"pwwkew\"\n# 输出: 3\n# 解释: 因为无重复字符的最长子串是 \"wke\",所以其长度为 3。(请注意,你的答案必须是 子串 的长度,\"pwke\" 是一个子序列,不是子串。)\n\n\nclass Solution:\n @staticmethod\n def length_of_longest_substring(s: str) -> int:\n # 如果字符串长度为0或空,则返回0\n if len(s) == 0 or s is None:\n return 0\n # 最长长度\n max_length = 0\n # 记录出现字符的字典\n appeared_map = {}\n # 滑块起始索引\n start = 0\n for end in range(len(s)):\n # 如果之前有重复的,且重复的在当前滑块内\n if s[end] in appeared_map.keys() and appeared_map[s[end]] >= start:\n # 若果之前有重复的,就将滑块起始位置滑至上一次出现的后一位\n start = appeared_map[s[end]] + 1\n # 将该重复字符的索引置为最新一次出现的位置\n appeared_map[s[end]] = end\n else:\n appeared_map[s[end]] = end\n if end - start + 1 > max_length:\n max_length = end - start + 1\n return max_length\n\n","sub_path":"longest_substring_without_repeating_characters.py","file_name":"longest_substring_without_repeating_characters.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"284176749","text":"import tensorflow as tf\nimport tensorflow.contrib.slim as slim\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport sys,os\nsys.path.append(os.path.realpath(\"..\"))\nsys.path.append(os.path.realpath(\"../Structs\"))\nsys.path.append(os.path.realpath(\"../DB\"))\nfrom CC_Agent import CC_Agent\nfrom Blackjack import Hand\nfrom NN_Move import NN_Move\nfrom Moves import Moves\nfrom Trainer import Init_Trainer\nfrom Trainer import Batch_Trainer\nfrom datetime import datetime\n\n\"\"\"\n - defines classes for both the primary netowrk and the target network\n - also defines the behaviour for the NN agent\n\"\"\"\n\n# class for the primary network\nclass Q_Net():\n def __init__(self, input_size, hidden_size, output_size, rnn_cell, myScope, training=True):\n self.init_feed_forward(input_size, hidden_size, output_size, myScope)\n self.rnn_processing(rnn_cell, hidden_size, myScope)\n self.split_streams(hidden_size, output_size)\n self.predict()\n self.gen_loss(output_size)\n self.train_update()\n\n if not training:\n self.disable_dropout()\n\n # dropout layers should be disabled when training is complete\n def disable_dropout(self):\n for dropout in self.dropout_layers:\n dropout.is_Training = False\n\n def rnn_processing(self, rnn_cell, hidden_size, myScope):\n # Take the output from the final fully connected layer and send it to a recurrent layer.\n # The input must be reshaped into [batch x trace x units] for rnn processing,\n # and then returned to [batch x units] when sent through the upper levles.\n self.trainLength = tf.placeholder(dtype=tf.int32)\n self.batch_size = tf.placeholder(dtype=tf.int32, shape=[])\n output_flat = tf.reshape(self.final_hidden, [self.batch_size, self.trainLength, hidden_size])\n self.state_in = rnn_cell.zero_state(self.batch_size, tf.float32)\n self.rnn, self.rnn_state = tf.nn.dynamic_rnn(\n inputs=output_flat, cell=rnn_cell, dtype=tf.float32, initial_state=self.state_in, scope=myScope + '_rnn')\n self.rnn = tf.reshape(self.rnn, shape=[-1, hidden_size])\n\n def init_feed_forward(self, inp_size, hidden_size, output_size, myScope):\n # Establish feed-forward part of the network\n self.input_layer = tf.placeholder(shape=[None, inp_size], dtype=tf.float32)\n\n hidden_layer1 = slim.fully_connected(self.input_layer, hidden_size,\n biases_initializer=None,\n activation_fn=tf.nn.relu,\n scope=(myScope+\"_hidden1\")) # Rectified linear activation func.\n\n dropout1 = slim.dropout(hidden_layer1, scope=myScope+\"_dropout1\")\n\n hidden_layer2 = slim.fully_connected(dropout1, hidden_size,\n biases_initializer=None,\n activation_fn=tf.nn.relu,\n scope=(myScope+\"_hidden2\"))\n\n dropout2 = slim.dropout(hidden_layer2, scope=myScope+\"_dropout2\")\n\n self.final_hidden = slim.fully_connected(dropout2, hidden_size,\n activation_fn=tf.nn.relu,\n biases_initializer=None,\n scope=(myScope+\"_final_hidden\")) # Softmax activation func. -> changed to relu, as no longer output\n\n self.dropout_layers = [dropout1, dropout2]\n\n #self.action = tf.argmax(self.output_layer, 1)\n\n def split_streams(self, hidden_size, output_size):\n # The output from the recurrent player is then split into separate Value and Advantage streams\n self.streamA, self.streamV = tf.split(self.rnn, 2, 1)\n self.AW = tf.Variable(tf.random_normal([hidden_size // 2, output_size]))\n self.VW = tf.Variable(tf.random_normal([hidden_size // 2, 1]))\n self.Advantage = tf.matmul(self.streamA, self.AW)\n self.Value = tf.matmul(self.streamV, self.VW)\n self.salience = tf.gradients(self.Advantage, self.input_layer)\n\n def predict(self):\n # Combine streams for final prediction value\n self.Qout = self.Value + tf.subtract(self.Advantage, tf.reduce_mean(self.Advantage, axis=1, keep_dims=True))\n self.predict = tf.argmax(self.Qout, 1)\n\n def gen_loss(self, output_size):\n # Loss calculated by taking the sum of squares difference between the target and prediction Q values.\n self.targetQ = tf.placeholder(shape=[None], dtype=tf.float32)\n self.actions = tf.placeholder(shape=[None], dtype=tf.int32)\n self.actions_onehot = tf.one_hot(self.actions, output_size, dtype=tf.float32)\n\n self.Q = tf.reduce_sum(tf.multiply(self.Qout, self.actions_onehot), axis=1)\n\n self.td_error = tf.square(self.targetQ - self.Q)\n\n # In order to only propogate accurate gradients through the network, we will mask the first\n # half of the losses for each trace as per Lample & Chatlot 2016\n self.maskA = tf.zeros([self.batch_size, self.trainLength // 2])\n self.maskB = tf.ones([self.batch_size, self.trainLength // 2])\n self.mask = tf.concat([self.maskA, self.maskB], 1)\n self.mask = tf.reshape(self.mask, [-1])\n self.loss = tf.reduce_mean(self.td_error * self.mask)\n\n # update the network by using Adam optimizer algorithm\n def train_update(self):\n self.trainer = tf.train.AdamOptimizer(learning_rate=0.0001)\n self.updateModel = self.trainer.minimize(self.loss)\n\n# target network is essentially the same as the primary network, but needs\n# a few extra behaviours defined to sync it back with the primary network when required\nclass Target_Net(Q_Net):\n def __init__(self, input_size, hidden_size, output_size, rnn_cell, myScope, training=True):\n super().__init__(input_size, hidden_size, output_size, rnn_cell, myScope, training)\n self.ops = None\n\n #These functions update the parameters of our target network with those of the primary network.\n def updateTargetGraph(self, tfVars, tau):\n total_vars = len(tfVars)\n op_holder = []\n for idx,var in enumerate(tfVars[0:total_vars//2]):\n op_holder.append(tfVars[idx+total_vars//2].assign((var.value()*tau) + ((1-tau)*tfVars[idx+total_vars//2].value())))\n self.ops = op_holder\n return op_holder\n\n def updateTarget(self, sess):\n op_holder = self.ops\n for op in op_holder:\n sess.run(op)\n total_vars = len(tf.trainable_variables())\n a = tf.trainable_variables()[0].eval(session=sess)\n b = tf.trainable_variables()[total_vars//2].eval(session=sess)\n if a.all() != b.all():\n print(\"Target Set Failed\")\n\n\n# Class for NN agent\nclass NN(CC_Agent):\n def __init__(self, setting=\"default\", hand=None, restore_type=\"default\", Training=True, auto_load=True):\n super().__init__(ID=\"nn\", extra_type=[\"nn\"])\n self.rnn_state = None\n self.sess = None\n\n self.parameters = self.set_parameters(setting=setting)\n self.train_params = self.set_training_params(setting=setting)\n\n if hand is None:\n self.Hand = Hand(self.ID)\n\n self.initalise_NN(Training)\n self.start_session()\n\n if auto_load:\n self.load_model(restore_type)\n\n # sets the bevhiour parameters of the nn\n def set_parameters(self, setting=\"default\"):\n if setting is \"default\":\n #Setting the training parameters\n nn_params = {\n \"gamma\": .99, # Discount factor on the target Q-values\n \"start_epsilon\" : 1, #Starting chance of random action\n \"epsilon\" : 1, # tracking value for epsilon - MAKE THIS AN ATTRIBUTE?\n \"end_epsilon\" : 0.001, #Final chance of random action\n \"path_default\" : \"./nn_data\", #The path to save our model to.\n \"hidden_size\" : 32, #The size of the final convolutional layer before splitting it into Advantage and Value streams.\n \"no_features\" : 6, # How many features to input into the network\n \"no_actions\" : 2, # No actions the network can take\n \"summaryLength\" : 100, #Number of epidoes to periodically save for analysis -- not applicable?\n \"annealing_steps\": 1000, # How many steps of training to reduce startE to endE.\n \"tau\" : 0.001,\n \"policy\" : \"e-greedy\",\n \"hand_val_norm_const\": 1 / 30, # value to normalise hand values by\n \"batch_size\": 8, # How many experience traces to use for each training step.\n \"trace_length\": 2, # How long each experience trace will be when training\n }\n\n start_epsilon = nn_params[\"start_epsilon\"]\n end_epsilon = nn_params[\"end_epsilon\"]\n annealing_steps = nn_params[\"annealing_steps\"]\n\n\n # Set the rate of random action decrease.\n nn_params[\"epsilon\"] = start_epsilon\n nn_params[\"epsilon_step\"] = (start_epsilon - end_epsilon) / annealing_steps\n\n return nn_params\n\n # sets parameters used in intial training\n def set_training_params(self, setting=\"default\"):\n if setting == \"default\":\n train_params = {\n \"batch_size\": 8, # How many experience traces to use for each training step.\n \"trace_length\": 2, # How long each experience trace will be when training\n \"update_freq\": 2, # How often to perform a training step.\n \"train_steps\": 20000, # How many episodes of game environment to train network with.\n \"explore_steps\": 1000, # how many steps for initial explore, before training\n \"save_model_frequency\": 50, # how often to save the model\n \"update_frequency\": 5, # how often to update the network weights\n \"test_steps\": 20000, # how many iterations to test\n \"hand_val_norm_const\": 1 / 30 # value to normalise hand values by\n }\n\n rewards = {\n \"winReward\": 3,\n \"lossCost\": -3,\n \"bustCost\": 0,\n \"hand_value_discount\": 1 / 2\n }\n return train_params\n\n\n # sets up both the primary and target rnn\n # initialises tf and sets the target net equal to primary net\n def initalise_NN(self, Training=True):\n no_features = self.parameters[\"no_features\"]\n hidden_size = self.parameters[\"hidden_size\"]\n no_actions = self.parameters[\"no_actions\"]\n tau = self.parameters[\"tau\"]\n\n tf.reset_default_graph()\n Primary_rnn_cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_size, state_is_tuple=True)\n Target_rnn_cell = tf.contrib.rnn.BasicLSTMCell(num_units=hidden_size, state_is_tuple=True)\n self.Primary_Network = Q_Net(no_features, hidden_size, no_actions, Primary_rnn_cell, 'main', Training)\n self.Target_Network = Target_Net(no_features, hidden_size, no_actions, Target_rnn_cell, 'target', Training)\n self.rnn_state = np.zeros([1, hidden_size]), np.zeros([1, hidden_size])\n\n self.init = tf.global_variables_initializer()\n trainables = tf.trainable_variables()\n self.targetOps = self.Target_Network.updateTargetGraph(trainables, tau)\n # saver is used for saving and restoring the nn model (the weights)\n self.saver = tf.train.Saver() # max_to_keep=5\n\n # resets the rnn_state\n def rnn_state_reset(self):\n hidden_size = self.parameters[\"hidden_size\"]\n self.rnn_state = np.zeros([1, hidden_size]), np.zeros([1, hidden_size])\n\n # gets the new rnn_state\n def rnn_state_update(self, game_state):\n self.rnn_state = self.sess.run(self.Primary_Network.rnn_state,\n feed_dict={\n self.Primary_Network.input_layer: [game_state],\n self.Primary_Network.trainLength: 1,\n self.Primary_Network.state_in: self.rnn_state,\n self.Primary_Network.batch_size: 1}\n )\n return self.rnn_state\n\n # start the session, run the assigned training type\n def init_training(self, type=\"group_all\"):\n # no context manager so that session does not have to be restarted every time a new move is needed\n trainer = Init_Trainer(self, training_params=self.train_params, training_type=type)\n self.start_session()\n self.sess.run(self.init)\n trainer.train(self.sess)\n self.stop_session()\n\n # runs trainer for new games NN has played in\n # does not update if there are not more than 50 games ot update from\n # ADD TO NEA WU\n def update_training(self):\n trainer = Batch_Trainer(self, training_params=self.train_params)\n no_games = trainer.get_num_games_to_train()\n if no_games >= 50:\n self.start_session()\n self.sess.run(self.init)\n\n trainer.train_new_games()\n print(\"success\")\n return no_games\n\n # Override from CC_Agent\n # exploring relates to the inital part of training when the agent is exploring the environment and takes random actions\n def get_move(self, all_players, exploring=False):\n game_state = self.get_state(all_players)\n chances = self.get_chances(game_state)\n\n # simple check so the neural network always takes the dominant strategy.\n if chances[\"bust\"] == 1:\n return Moves.STAND\n elif chances[\"bust\"] == 0:\n return Moves.HIT\n else:\n move_next = self.getNextAction(chances, game_state, exploring=exploring)\n return move_next\n\n # returns the next move of the agent\n # side effect => updated rnn cell state after every move\n def getNextAction(self, chances, game_state, exploring=False):\n # pass through NN model, and get the next move\n game_state = self.get_features(chances, game_state)\n move = NN_Move.choose_action(self.parameters, self.Primary_Network, game_state, self.rnn_state, self.sess,\n exploring=exploring)\n self.rnn_state_update(game_state)\n if move == True:\n move = Moves.HIT\n elif move == False:\n move = Moves.STAND\n return move\n\n # gets the features which wil be used as the parameter for the input layer of the nn\n # [normalise_agent_hand_val, normalised_best_val, chances] TODO update this so that it includes win margin\n def get_features(self, chances, game_state):\n hand_val_norm_const = self.parameters[\"hand_val_norm_const\"]\n features = []\n # append the hand values of agent hand and best player hand to the features array\n # should always be [agent_hand, best_player_hand]\n for hand in game_state:\n if isinstance(hand, int):\n hand_val = hand\n else:\n hand_val = hand.get_value()\n hand_val_normalised = hand_val * hand_val_norm_const\n features.append(hand_val_normalised)\n for key in sorted(chances):\n features.append(chances[key])\n return features\n\n # init the tf session - MUST BE CALLED BEFORE ANY TF ACTION OCCURS\n def start_session(self):\n self.sess = tf.Session()\n\n # stops the tf session - CALL WHEN TF WORK IS COMPLETED\n def stop_session(self):\n if self.sess is not None:\n self.sess.close()\n self.sess = None\n\n # checkpoints the current model for later use\n # model based-parameterisation\n # save a new model for a new paramaterisation\n def save_model(self):\n path = self.parameters[\"path_default\"]\n # Make a path for our model to be saved in.\n if not os.path.exists(path):\n os.makedirs(path)\n # eg. 28-02-2018,15-30-10\n model_version = datetime.now().strftime(\"%d-%m-%Y,%H-%M-%S\")\n model_type = \"/model-default-\"\n #(path + model_type + model_version + \".cptk\")\n self.saver.save(self.sess, \"nn_data/model.cptk\")\n\n # loads the last checkpointed model - session must have been started before model loading\n # TODO IMPLEMENT THE RESTORATION OF DIFFERENT FILES\n def load_model(self, restore_type=\"default\"):\n path = self.parameters[\"path_default\"]\n ckpt = tf.train.get_checkpoint_state(path) # gets the checkpoint from the last checkpoint file\n #self.saver.restore(self.sess, ckpt.model_checkpoint_path)\n self.saver.restore(self.sess, \"NN_AI/nn_data/model.cptk\") #NN_AI/nn_data/model.cptk\n print(\"model loaded successfully\")\n\n # updates the target and the primary network - should be called after game steps reaches its train frequency\n # exp buffer - experience_buffer class used to store game samples in training\n def update_networks(self, exp_buffer):\n batch_size = self.parameters[\"batch_size\"]\n hidden_size = self.parameters[\"hidden_size\"]\n trace_length = self.parameters[\"trace_length\"]\n y = self.parameters[\"gamma\"]\n\n self.Target_Network.updateTarget(self.sess)\n rnn_state_update = (np.zeros([batch_size, hidden_size]), np.zeros([batch_size, hidden_size])) # using intial rnn state for training\n trainBatch = exp_buffer.sample(batch_size, trace_length) # Get a random batch of experiences.\n\n # Below we perform the Double-DQN update to the target Q-values\n primary_out = self.sess.run(self.Primary_Network.predict, feed_dict={\n self.Primary_Network.input_layer: np.vstack(trainBatch[:, 3]),\n self.Primary_Network.trainLength: trace_length,\n self.Primary_Network.state_in: rnn_state_update,\n self.Primary_Network.batch_size: batch_size\n })\n\n target_out = self.sess.run(self.Target_Network.Qout, feed_dict={\n self.Target_Network.input_layer: np.vstack(trainBatch[:, 3]),\n self.Target_Network.trainLength: trace_length,\n self.Target_Network.state_in: rnn_state_update,\n self.Target_Network.batch_size: batch_size\n })\n\n end_multiplier = -(trainBatch[:, 4] - 1)\n doubleQ = target_out[range(batch_size * trace_length), primary_out]\n targetQ = trainBatch[:, 2] + (y * doubleQ * end_multiplier)\n # Update the network with our target values.\n self.sess.run(self.Primary_Network.updateModel,\n feed_dict={\n self.Primary_Network.input_layer: np.vstack(trainBatch[:, 0]),\n self.Primary_Network.targetQ: targetQ,\n self.Primary_Network.actions: trainBatch[:, 1],\n self.Primary_Network.trainLength: trace_length,\n self.Primary_Network.state_in: rnn_state_update,\n self.Primary_Network.batch_size: batch_size}\n )\n\n # at the end of each game each hand is passed and the card counter is decremented\n def update_end_game(self, new_cards):\n self.decrement_CC(new_cards)\n self.rnn_state_reset()\n\n # returns all the values and the names of the trainable variables loaded in the current tf graph\n def get_trainable_vars(self):\n if self.sess is None:\n self.start_session()\n trainables = tf.trainable_variables()\n names = [v.name for v in trainables]\n v = [self.sess.run(v) for v in trainables]\n\n toReturn = zip(names, v)\n\n self.stop_session()\n return toReturn\n\nif __name__ == \"__main__\":\n nn = NN()\n #nn.init_training()\n nn.start_session()\n nn.sess.run(nn.init)\n nn.update_training()\n nn.stop_session()\n","sub_path":"Code/NN_AI/NN.py","file_name":"NN.py","file_ext":"py","file_size_in_byte":19933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"451894873","text":"\n\n#calss header\nclass _BOLERO():\n\tdef __init__(self,): \n\t\tself.name = \"BOLERO\"\n\t\tself.definitions = [u\"a woman's short jacket that stops just above the waist and has no buttons\", u'a Spanish dance, or the music it is danced to: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_bolero.py","file_name":"_bolero.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"325872447","text":"import os\nfrom datetime import timedelta\n\nPROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))\n\nTIME_ZONE = 'America/New_York'\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\nUSE_TZ = True\nUSE_I18N = True\nUSE_L10N = True\n\nMEDIA_ROOT = ''\nMEDIA_URL = ''\nSTATIC_ROOT = os.path.abspath(os.path.join(PROJECT_ROOT, '..', 'static'))\nSTATIC_URL = '/static/'\nADMIN_MEDIA_PREFIX = '/static/admin/'\n\nSTATICFILES_DIRS = (\n # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n # Always use forward slashes, even on Windows.\n # Don't forget to use absolute paths, not relative paths.\n os.path.join(PROJECT_ROOT, 'static'),\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n)\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = 'thecleanest.urls'\n\nTEMPLATE_DIRS = (\n os.path.join(PROJECT_ROOT, 'templates'),\n)\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django_extensions',\n 'raven.contrib.django.raven_compat',\n 'south',\n 'postmark',\n 'tastypie',\n 'mathfilters',\n 'thecleanest.schedule',\n 'thecleanest.notifications',\n 'gunicorn',\n)\n\nEMAIL_BACKEND = \"postmark.backends.PostmarkBackend\"\nEMAIL_SENDER = \"Cleanosaurus Rex \"\nEMAIL_RECIPIENT = None\n\nAPI_LIMIT_PER_PAGE = 100\n\nNUDGE_GRACE_PERIOD = timedelta(minutes=30)\nSCHED_HORIZON = 31\nEXCUSED = [\n 'dheart@sunlightfoundation.com',\n 'cgates@sunlightfoundation.com',\n]\n","sub_path":"thecleanest/global_settings.py","file_name":"global_settings.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"292052284","text":"from PyQt5.QtWidgets import *\nfrom PyQt5.QtCore import Qt, QAbstractTableModel\nfrom PyQt5.QtGui import *\nimport sys\nimport json\nimport os\n\n\nclass TableModel(QAbstractTableModel):\n def __init__(self, data):\n super(TableModel, self).__init__()\n self.dataTable = data\n\n def data(self, index, role):\n if role == Qt.DisplayRole:\n return self.dataTable[index.row()][index.column()]\n\n def rowCount(self, index):\n return len(self.dataTable)\n\n def columnCount(self, index):\n return len(self.dataTable[0])\n\n\nclass myApp(QMainWindow):\n def __init__(self):\n super(myApp, self).__init__()\n self.open = open(\"json/data_contact.json\", \"r\")\n self.userContact = json.loads(self.open.read())\n self.mainUI()\n self.mainLayout()\n self.setCentralWidget(self.mainWidget)\n self.menuBars()\n self.setMenuBar(self.menu)\n self.setFixedSize(350, 300)\n self.toolBars()\n self.addToolBar(self.toolBar)\n\n def mainUI(self):\n self.firstTabs = firstTab()\n self.secondTabs = secondTab()\n self.thirdTabs = thirdTab()\n self.tabs = QTabWidget()\n self.tabs.addTab(self.firstTabs, \"Contact\")\n self.tabs.addTab(self.secondTabs, \"Favorite\")\n self.tabs.addTab(self.thirdTabs, \"Add Contact\")\n\n def toolBars(self):\n self.toolBar = QToolBar()\n button_tools = QAction(QIcon(\"icon/contact.png\"), \"Help\", self)\n self.toolBar2 = QToolBar()\n button_tools = QAction(QIcon(\"icon/contact.png\"), \"Help\", self)\n self.toolBar.addAction(button_tools)\n button_tools.triggered.connect(self.popupHelp)\n self.toolBar2.addAction(button_tools)\n button_tools.triggered.connect(self.popupHelp)\n\n def popupHelp(self):\n msg_pop = \"PyQT Contact Help Center!\"\n QMessageBox.information(self, \"Help Center\", msg_pop)\n\n def menuBars(self):\n self.menu = self.menuBar()\n test = self.menu.addMenu(\"File\")\n test2 = self.menu.addMenu(\"App\")\n test.addAction(\"Tentang Aplikasi\")\n test2.addAction(\"Contact Book List\")\n\n def mainLayout(self):\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.tabs)\n\n self.mainWidget = QWidget()\n self.mainWidget.setLayout(self.layout)\n\n\n# Show Data Contact\nclass firstTab(QWidget):\n def __init__(self):\n super(firstTab, self).__init__()\n self.dataFavorite = {}\n self.open = open(\"json/data_contact.json\", \"r\")\n self.userContact = json.loads(self.open.read())\n self.FavoriteTable()\n self.mainUI()\n self.setLayout(self.layout)\n\n def mainUI(self):\n self.btnAddFavorite = QPushButton(\"Add to Favorite\")\n self.btnAddFavorite.clicked.connect(self.addToFavorite)\n\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.tablePlaces)\n self.layout.addWidget(self.btnAddFavorite)\n\n # add favorite in list\n def addToFavorite(self):\n for i in self.userContact:\n if self.dataFavorite['nama'] == i['nama']:\n i['favorite'] = 1\n toJson = json.dumps(self.userContact, indent=4)\n fwrite = open('json/data_contact.json', 'w')\n fwrite.write(toJson)\n\n # fetch favorite in list\n def fetchFavorite(self, row, column):\n favoriteData = []\n rwf = row\n clf = column\n for x in range(len(self.head)):\n res = self.tablePlaces.item(int(rwf), int(x)).text()\n favoriteData.append(res)\n for i in self.userContact:\n if favoriteData[0] == i['nama']:\n self.dataFavorite.update(i)\n\n # Logic to Favorite Tabs\n def FavoriteTable(self):\n self.head = [\"name\", \"phone number\"]\n row = len(list(self.userContact))\n self.tablePlaces = QTableWidget()\n self.tablePlaces.setRowCount(row)\n self.tablePlaces.setColumnCount(len(self.head))\n for row in range(len(self.userContact)):\n for col in range(len(self.head)):\n if col == 0:\n self.tablePlaces.setItem(\n row, col, QTableWidgetItem(self.userContact[row][\"nama\"]))\n elif col == 1:\n self.tablePlaces.setItem(row, col, QTableWidgetItem(\n self.userContact[row][\"nomor_hp\"]))\n\n self.tablePlaces.setHorizontalHeaderLabels(self.head)\n\n self.tablePlaces.cellClicked.connect(self.fetchFavorite)\n\n\n# Add to Favorite Contact List\nclass secondTab(QWidget):\n def __init__(self):\n super(secondTab, self).__init__()\n self.open = open(\"json/data_contact.json\", \"r\")\n self.userContact = json.loads(self.open.read())\n self.dataFavorite = {}\n self.favoriteContact()\n self.mainUI()\n self.setLayout(self.layout)\n\n def mainUI(self):\n self.btnDeleteFavorite = QPushButton(\"Delete favorite Contact\")\n self.btnDeleteFavorite.clicked.connect(self.deleteFromfavorite)\n\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.tableFavs)\n self.layout.addWidget(self.btnDeleteFavorite)\n\n # get from mainUI\n def favoriteContact(self):\n self.head = [\"name\", \"phone number\"]\n self.contactFav = list(\n filter(lambda a: a[\"favorite\"] == 1, self.userContact))\n row = len(self.contactFav)\n self.tableFavs = QTableWidget()\n self.tableFavs.setRowCount(row)\n self.tableFavs.setColumnCount(len(self.head))\n for row in range(len(self.contactFav)):\n for col in range(len(self.head)):\n if col == 0:\n self.tableFavs.setItem(row, col, QTableWidgetItem(\n self.contactFav[row][\"nama\"]))\n elif col == 1:\n self.tableFavs.setItem(row, col, QTableWidgetItem(\n self.contactFav[row][\"nomor_hp\"]))\n\n self.tableFavs.setHorizontalHeaderLabels(self.head)\n self.tableFavs.cellClicked.connect(self.fetchFavorite)\n\n # fetch favorite in list\n def fetchFavorite(self, row, column):\n favoriteData = []\n rw = row\n cl = column\n for x in range(len(self.head)):\n res = self.tableFavs.item(int(rw), int(x)).text()\n favoriteData.append(res)\n for i in self.userContact:\n if favoriteData[0] == i['nama']:\n self.dataFavorite.update(i)\n\n # delete favorite if click nama in list\n def deleteFromfavorite(self):\n for i in self.userContact:\n if self.dataFavorite['nama'] == i['nama']:\n i['favorite'] = 0\n toJson = json.dumps(self.userContact, indent=4)\n fwrite = open('json/data_contact.json', 'w')\n fwrite.write(toJson)\n\n# Add New Contact to Contact List\n\n\nclass thirdTab(QWidget):\n def __init__(self):\n super(thirdTab, self).__init__()\n self.mainUI()\n self.setLayout(self.layout)\n self.open = open(\"json/data_contact.json\", \"r\")\n self.userContact = json.loads(self.open.read())\n\n # logic add\n def mainUI(self):\n self.lineEdit = QLineEdit()\n self.lineEdit.setPlaceholderText(\"Set Name\")\n self.lineEdit2 = QLineEdit()\n self.lineEdit2.setPlaceholderText(\"Set Phone Number\")\n self.buttonAdd = QPushButton(\"Add To Contact List\")\n self.buttonAdd.clicked.connect(self.addContact)\n self.lineEdit.returnPressed.connect(self.addContact)\n self.lineEdit2.returnPressed.connect(self.addContact)\n\n self.layout = QVBoxLayout()\n self.layout.addWidget(self.lineEdit)\n self.layout.addWidget(self.lineEdit2)\n self.layout.addWidget(self.buttonAdd)\n\n # get from MainUI\n\n def addContact(self):\n name = self.lineEdit.text()\n phone = self.lineEdit2.text()\n params = {\"nama\": name, \"nomor_hp\": phone, \"favorite\": 0}\n self.userContact.append(params)\n toJson = json.dumps(self.userContact, indent=4)\n fwrite = open('json/data_contact.json', 'w')\n fwrite.write(toJson)\n\n\ndef restart_program():\n \"\"\"Restarts the current program.\n Note: this function does not return. Any cleanup action (like\n saving data) must be done before calling this function.\"\"\"\n python = sys.executable\n os.execl(python, python, * sys.argv)\n\n\nif __name__ == \"__main__\":\n app = QApplication([])\n window = myApp()\n window.setWindowTitle(\"PyQt5 Contact\")\n window.show()\n sys.exit(app.exec_())\n","sub_path":"002/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"22749999","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: build/bdist.linux-x86_64/egg/protect/test/unit/test_snpeff.py\n# Compiled at: 2018-05-07 13:54:25\n__doc__ = '\\nAuthor : Arjun Arkal Rao\\nAffiliation : UCSC BME, UCSC Genomics Institute\\nFile : protect/test/test_snpeff.py\\n'\nfrom __future__ import print_function\nfrom protect.mutation_annotation.snpeff import run_snpeff\nfrom protect.pipeline.ProTECT import _parse_config_file\nfrom protect.test import ProtectTest\nfrom toil.job import Job\nimport os, subprocess\n\nclass TestSnpeff(ProtectTest):\n\n def setUp(self):\n super(TestSnpeff, self).setUp()\n test_dir = self._createTempDir()\n self.options = Job.Runner.getDefaultOptions(self._getTestJobStorePath())\n self.options.logLevel = 'INFO'\n self.options.workDir = test_dir\n self.options.clean = 'always'\n\n def test_snpeff(self):\n \"\"\"\n Test the functionality of run_transgene\n \"\"\"\n univ_options = self._getTestUnivOptions()\n univ_options['output_folder'] = '/mnt/ephemeral/done'\n config_file = os.path.join(self._projectRootPath(), 'src/protect/test/test_inputs/ci_parameters.yaml')\n test_src_folder = os.path.join(self._projectRootPath(), 'src', 'protect', 'test')\n a = Job.wrapJobFn(self._get_test_mutation_vcf)\n b = Job.wrapJobFn(self._get_all_tools, config_file).encapsulate()\n c = Job.wrapJobFn(self._get_tool, b.rv(), 'snpeff')\n d = Job.wrapJobFn(run_snpeff, a.rv(), univ_options, c.rv(), disk='100M', memory='100M', cores=1).encapsulate()\n a.addChild(b)\n b.addChild(c)\n a.addChild(d)\n c.addChild(d)\n Job.Runner.startToil(a, self.options)\n\n @staticmethod\n def _get_all_tools(job, config_file):\n sample_set, univ_options, tool_options = _parse_config_file(job, config_file, max_cores=None)\n return tool_options\n\n @staticmethod\n def _get_tool(job, all_tools, tool):\n return all_tools[tool]\n\n @staticmethod\n def _get_test_mutation_vcf(job):\n \"\"\"\n Get the test mutation vcf file and write to jobstore\n\n :return: FSID for the mutations vcf\n \"\"\"\n base_call = 's3am download s3://cgl-pipeline-inputs/protect/unit_results/mutations/merged/'\n filename = 'all_merged.vcf'\n call = (base_call + '%s ' % filename * 2).strip().split(' ')\n subprocess.check_call(call)\n return job.fileStore.writeGlobalFile(filename)\n\n\n_get_all_tools = TestSnpeff._get_all_tools\n_get_tool = TestSnpeff._get_tool\n_get_test_mutation_vcf = TestSnpeff._get_test_mutation_vcf","sub_path":"pycfiles/protected-0.0.1.tar/test_snpeff.py","file_name":"test_snpeff.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"590119950","text":"__author__ = 'kis2'\n\nimport sys\nimport os\nfrom PyQt4 import Qt, QtGui, QtCore\nimport image_converter\n\n\nclass MainMenu(QtGui.QWidget):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n\n\n\n self.setWindowTitle('Image Converter')\n\n vbox = QtGui.QVBoxLayout()\n vbox.addStretch(1)\n type_label = QtGui.QLabel('First field is used only for directory conversion')\n vbox.addWidget(type_label)\n\n self.input_format = QtGui.QLineEdit('input format')\n self.output_format = QtGui.QLineEdit('output format')\n\n text_hbox = QtGui.QHBoxLayout()\n text_hbox.addWidget(self.input_format)\n text_hbox.addWidget(self.output_format)\n vbox.addLayout(text_hbox)\n\n self.convert_folder_button = QtGui.QPushButton('Convert Folder')\n self.convert_folder_button.connect(self.convert_folder_button, QtCore.SIGNAL('clicked()'), self.convert_folder)\n vbox.addWidget(self.convert_folder_button)\n\n self.convert_file_button = QtGui.QPushButton('Convert File')\n self.convert_file_button.connect(self.convert_file_button, QtCore.SIGNAL('clicked()'), self.convert_file)\n vbox.addWidget(self.convert_file_button)\n\n self.setLayout(vbox)\n\n def get_directory(self, name):\n return str(QtGui.QFileDialog.getExistingDirectory(self, name))\n\n def get_file(self, mode):\n if mode == 'open':\n return str(QtGui.QFileDialog.getOpenFileName(self, 'Open File'))\n\n def convert_folder(self):\n directory_to_convert = self.get_directory('Directory To Convert')\n save_dir = self.get_directory('Saving Directory')\n input_format = self.input_format.text()\n output_format = self.output_format.text()\n files_to_convert = []\n for file in os.listdir(path=directory_to_convert):\n if file.endswith(input_format) or file.endswith(input_format.upper()):\n files_to_convert.append(os.path.join(directory_to_convert, file))\n print(files_to_convert)\n ConvertingBot = image_converter.ImageConverter(files_to_convert, output_format, save_dir)\n ConvertingBot.convert()\n\n def convert_file(self):\n opened_file = self.get_file('open')\n save_dir = self.get_directory('Saving Directory')\n print(opened_file)\n print(save_dir)\n output_format = self.output_format.text()\n files_to_convert = []\n files_to_convert.append(opened_file)\n ConvertingBot = image_converter.ImageConverter(files_to_convert, output_format, save_dir)\n ConvertingBot.convert()\n\n\n\napp = QtGui.QApplication(sys.argv)\nwindow = MainMenu()\nwindow.show()\nsys.exit(app.exec_())","sub_path":"image_converter_gui.py","file_name":"image_converter_gui.py","file_ext":"py","file_size_in_byte":2701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"122108863","text":"import mc, inspect\r\n\r\n''' --------------------------------------------------------------\r\nAndreas Pehrson, 20110422\r\n\r\n-- A simple logger facility for Boxee.\r\n\r\nHandles file logging and notification passing to Boxee.\r\n\r\nLevel description:\r\n TRACEIN | Only BoxeeLog:Debug, prepended with \"TRACEIN\". Not intended to be used directly. Use BPTraceEnter instead.\r\n TRACEOUT| Only BoxeeLog:Debug, prepended with \"TRACEOUT\". Not intended to be used directly. Use BPTraceExit instead.\r\n NOTICE | Only user notification.\r\n DEBUG | Only BoxeeLog:Debug, prepended with \"DEBUG\".\r\n INFO | UserNotification and BoxeeLog:Info, prepended with \"INFO\".\r\n WARNING | UserNotification and BoxeeLog:Info, prepended with \"WARNING\".\r\n ERROR | UserNotification and BoxeeLog:Error, prepended with \"ERROR\".\r\n FATAL | Immediate app termination and BoxeeLog:Error, prepended with \"FATAL\".\r\n\r\n\r\nNB: It seems that Boxee always log messages as DEBUG?\r\n Setting prepend on all log levels for now.\r\n -------------------------------------------------------------- '''\r\n\r\n# What to export, (what is imported when 'from logger import *')\r\n__all__ = [ \"Level\", \"Enable\", \"Disable\", \"EnablePlus\", \"DisableMinus\", \"IsEnabled\", \"BPLog\", \"BPTraceEnter\", \"BPTraceExit\" ]\r\n\r\nclass Level:\r\n '''A basic enum class of available log levels.'''\r\n TRACEIN,TRACEOUT,NOTICE,DEBUG,INFO,WARNING,ERROR,FATAL=range(1,9)\r\n\r\n# Storing of enabled log levels\r\nEnabled = { }\r\n# Initiate list\r\nfor i in range(1,9):\r\n Enabled[i] = False\r\n\r\ndef SetEnabled(lvl, b):\r\n '''Enable or disable the give level.'''\r\n if lvl == Level.TRACEIN:\r\n Enabled[Level.TRACEOUT] = b\r\n if lvl == Level.TRACEOUT:\r\n Enabled[Level.TRACEIN] = b\r\n Enabled[lvl] = b\r\n\r\ndef Enable(lvl):\r\n SetEnabled(lvl, True)\r\n\r\ndef Disable(lvl):\r\n SetEnabled(lvl, False)\r\n\r\ndef SetEnabledPlus(lvl, b):\r\n '''Enable the given level and all above, or\r\n Disable the given level and all below.\r\n '''\r\n if lvl == Level.TRACEOUT: #Either TRACEIN or TRACEOUT should work\r\n lvl = Level.TRACEIN\r\n if b:\r\n for i in range(lvl,9):\r\n Enable(i)\r\n else:\r\n for i in range(1,lvl+1):\r\n Disable(i)\r\n\r\ndef EnablePlus(lvl):\r\n SetEnabledPlus(lvl, True)\r\n\r\ndef DisableMinus(lvl):\r\n SetEnabledPlus(lvl, False)\r\n\r\ndef IsEnabled(lvl):\r\n if lvl in Enabled:\r\n return Enabled[lvl]\r\n return False\r\n\r\ndef BPLog(msg, lvl=Level.INFO):\r\n '''Actual logging occurs here, only on enabled levels.\r\n BPLog meaning BoxeePlayLogger.\r\n '''\r\n noteIcon = { Level.NOTICE : \"noteNotice.png\"\r\n #, Level.DEBUG : \"noteDebug.png\"\r\n , Level.INFO : \"noteInfo.png\"\r\n , Level.WARNING : \"noteWarn.png\"\r\n , Level.ERROR : \"noteError.png\"\r\n }\r\n logFunc = { Level.TRACEIN : mc.LogError#mc.LogDebug\r\n , Level.TRACEOUT: mc.LogError#mc.LogDebug\r\n , Level.DEBUG : mc.LogError#mc.LogDebug\r\n , Level.INFO : mc.LogError#mc.LogInfo\r\n , Level.WARNING : mc.LogError#mc.LogInfo\r\n , Level.ERROR : mc.LogError\r\n , Level.FATAL : mc.LogError\r\n }\r\n logPrepend = { Level.TRACEIN : \"TRACE, Entering scope of \"\r\n , Level.TRACEOUT: \"TRACE, Exiting scope of \"\r\n , Level.DEBUG : \"DEBUG, \"\r\n , Level.INFO : \"INFO, \"\r\n , Level.WARNING : \"WARNING, \"\r\n , Level.ERROR : \"ERROR, \"\r\n , Level.FATAL : \"FATAL, \"\r\n }\r\n\r\n if IsEnabled(lvl):\r\n\r\n# msg = \"Name:\" + __name__ + \",Module:\" + __module__ + \",File:\" + __file__ + \" :: \" + msg\r\n # Prepend log message if necessary\r\n if lvl in logPrepend:\r\n msg = logPrepend[lvl] + msg\r\n\r\n # Send notification to user\r\n if lvl in noteIcon:\r\n mc.ShowDialogNotification(msg, noteIcon[lvl])\r\n\r\n # Send message to log\r\n if lvl in logFunc:\r\n # Log message distinguisher for easy log file lookup\r\n msg = \"BPLog: \" + msg\r\n # Call Boxee log function\r\n logFunc[lvl](msg)\r\n\r\n # If FATAL, shut down app\r\n if lvl == Level.FATAL:\r\n #mc.GetApp().Close() #Boxee main app stupidly enough crashes on memviolation when executing this\r\n mc.ActivateWindow(10482) #Until better times..\r\n\r\n # Let's report any unknown log level\r\n if lvl not in noteIcon and lvl not in logFunc:\r\n BPLog(\"UNDEFINED LOG LEVEL: \" + str(lvl) +\r\n \", with message: \" + msg, Level.ERROR)\r\n\r\ndef BPTraceEnter(msg=\"\"):\r\n '''Sugar for BPLog with level TRACEIN.\r\n An optional message (no need for it to be a string)\r\n may be provided. For instance the arguments provided\r\n to the traced function.'''\r\n BPTrace(msg, Level.TRACEIN)\r\n\r\ndef BPTraceExit(msg=\"\"):\r\n '''Sugar for BPLog with level TRACEOUT.\r\n An optional message (no need for it to be a string)\r\n may be provided. For instance the arguments provided\r\n to the traced function.'''\r\n BPTrace(msg, Level.TRACEOUT)\r\n\r\ndef BPTrace(msg, level):\r\n '''BPTrace will inspect the call stack to see which\r\n function that called us and pass this on to the log.'''\r\n if IsEnabled(level):\r\n s = inspect.stack()\r\n if len(s) >= 2 and s[1][3].startswith('BPTrace'):\r\n depth = 2\r\n else:\r\n depth = 1\r\n called = len(s) >= depth + 2 #called at depth, caller at depth + 1\r\n\r\n f = s[depth]\r\n fFile = str(f[1]).rsplit('\\\\')[-1]\r\n fRow = str(f[2])\r\n fName = str(f[3])\r\n trace = \"%s at %s:%s\" % (fName, fFile, fRow)\r\n\r\n if called:\r\n caller = s[depth + 1]\r\n callFile = str(caller[1]).rsplit('\\\\')[-1]\r\n callRow = str(caller[2])\r\n callName = str(caller[3])\r\n trace += \" called from %s at %s:%s\" % (callName, callFile, callRow)\r\n BPLog(\"%s -> %s\" % (trace, msg), level)\r\n\r\n","sub_path":"tv.boxeeplay.svtplay3/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":6054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"561611728","text":"\n\nfrom xai.brain.wordbase.nouns._fund import _FUND\n\n#calss header\nclass _FUNDED(_FUND, ):\n\tdef __init__(self,): \n\t\t_FUND.__init__(self)\n\t\tself.name = \"FUNDED\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"fund\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_funded.py","file_name":"_funded.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"623541245","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\nimport sys\nimport scipy.stats\nimport numpy.random \n\n#file1 = str(sys.argv[1])\n#file2 = str(sys.argv[2])\n#xbins = int(sys.argv[3])\n#ybins = int(sys.argv[4])\n\nmatplotlib.pyplot.rcParams['agg.path.chunksize'] = 20000\n\n\n\ndef get_chi2(s1, s2, xbins, ybins):\n '''\n Input: s1 and s2 are L by 2 arrays with each row containing a pair of invariant \n masses for a decay into a three body system. \n xbins and ybins refer to the number of bins along each axis. \n Output: the chi-square test statistic for this particular sample. \n '''\n\n # designate sample1 as X and sample2 as Xbar\n # therefore alpha is N(s1)/N(s2)\n\n alpha = len(s1)/len(s2)\n\n Sarray = np.array([]).reshape(0,1)\n\n for i in range(xbins): \n\n s1xcut = [entry for entry in s1 if i*(1/xbins) <= entry[0] < (i+1)*(1/xbins)]\n s2xcut = [entry for entry in s2 if i*(1/xbins) <= entry[0] < (i+1)*(1/xbins)]\n \n for j in range(ybins): \n \n s1ycut = [entry for entry in s1xcut if j*(1/ybins) <= entry[1] < (j+1)*(1/ybins)]\n s2ycut = [entry for entry in s2xcut if j*(1/ybins) <= entry[1] < (j+1)*(1/ybins)]\n\n s1ycut = np.array(s1ycut)\n s2ycut = np.array(s2ycut)\n \n p = (len(s1ycut)-(alpha*len(s2ycut)))\n q = np.sqrt(len(s1ycut)+ (len(s2ycut)*alpha**2))\n \n if q != 0: \n\n #plt.scatter(s1ycut[:,0], s1ycut[:,1])\n #plt.show()\n\n S = p/q\n \n Sarray = np.append(Sarray, np.array(S).reshape(1,1), axis=0)\n \n S2 = np.square(Sarray)\n\n chi2 = np.sum(S2)\n\n #print('the Chi2 value is ' + str(chi2)) \n \n #p = scipy.stats.chi2.sf(chi2, xbins*ybins)\n\n #print('there are ' + str(xbins*ybins) + ' dof')\n\n #print('the p value (from scipy) is ' + str(p))\n \n return chi2\n\n\n\ndef permutation(file1, file2, xbins, ybins, iterations):\n '''\n Gets a distribution of chi-square values to mimic the null hypothesis. \n Input: two input files containing two different sets of samples, the number of\n bins along each axis, and the number of iterations - the number of data\n points you need in the final distribution. Could be costly to run. Need to optimize\n\n Output: list of chi-square values that mimic the null hypothesis, as well as \n the chi-square value that comes from the differentiated dataset. \n Consequently there is an estimate of the p-value.\n '''\n\n print('Doing permutations. Will do ' + str(iterations))\n print('Reading file ' + file1 + ' as file1 and file ' + file2 + ' as file2.')\n\n with open(file1) as file1:\n lines = file1.readlines()\n s1m12 = [line.split()[0] for line in lines]\n s1m13 = [line.split()[1] for line in lines]\n\n with open(file2) as file2:\n lines = file2.readlines()\n s2m12 = [line.split()[0] for line in lines]\n s2m13 = [line.split()[1] for line in lines]\n\n\n s1m12 = [float(i) for i in s1m12]\n s1m13 = [float(i) for i in s1m13]\n s1 = np.column_stack((s1m12, s1m13))\n\n s2m12 = [float(i) for i in s2m12]\n s2m13 = [float(i) for i in s2m13]\n s2 = np.column_stack((s2m12, s2m13))\n\n true_chi2 = get_chi2(s1,s2,xbins,ybins)\n print('The real chi2 value is ' + str(true_chi2))\n scipy_p = scipy.stats.chi2.sf(true_chi2, xbins*ybins)\n print('the p value as estimated by scipy.stats is ' + str(scipy_p))\n\n\n s12 = np.concatenate((s1, s2), axis=0)\n chi2_dist = []\n\n print('reached permutation loop')\n\n for i in range(iterations):\n\n if i % 20 == 0: \n print('reached ' + str(i) + ' events')\n\n np.random.shuffle(s12)\n\n s1 = s12[0:len(s1)]\n s2 = s12[len(s1):len(s12)]\n\n chi2 = get_chi2(s1, s2, xbins, ybins)\n\n chi2_dist.append(chi2)\n\n \n return chi2_dist, true_chi2\n\n\ndist = permutation('sample1.txt', 'sample2.txt', 3, 3, 10000)\n\ncounter = 0 \nfor i in dist[0]: \n if i > dist[1]: \n counter = counter+1\n \np_value = counter/10000\n\nprint('the p value from the permutation method is ' + str(p_value))\n\n\nplt.figure()\nplt.hist(dist[0], bins=50)\nplt.title(\"chi2 distribution\")\nplt.show()\n\n\n\n'''\np_array = []\nchi2_array = []\nr=20\n\nfor i in range(r): \n\n a, b = chi2_test('sample1.txt', 'sample2.txt', i, i)\n\n print('reached ' + str(i))\n\n p_array.append(b)\n chi2_array.append(a)\n\n\nplt.figure()\n\nplt.subplot(1,2,1)\nplt.plot(list(range(r)), p_array) \nplt.title(\"p value vs bins on each axis\")\n\nplt.subplot(1,2,2)\nplt.plot(list(range(r)), chi2_array)\nplt.title(\"chi2 statistic vs. bins on each axis\")\n\nplt.show()\n'''\n\n\n#data=[float(i) for i in data]\n#print(type(data[1][1]))\n#plot = plt.scatter(s1_m12, s1_m13, cmap=\"Purples\")\n#plt.pcolormesh(data)\n#plt.show()\n","sub_path":"runsA/chi2_tests/logs-run1/chi2simple_test_perm.py","file_name":"chi2simple_test_perm.py","file_ext":"py","file_size_in_byte":4798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"236116189","text":"import codecs\nimport csv\nimport os\n\ncsvfile = open('myEdgeList.csv')\nf = csv.reader(csvfile)\n\nlist_of_newcolumns = {}\n\nfor line in f:\n if line == \"\":\n break\n arr = line[0].split()\n cmp1 = arr[0]\n cmp2 = arr[1]\n list = []\n\n try:\n simcomp_out1 = open(cmp1 + \"_simcompOut.txt\", \"r\")\n except:\n print(\"ERROR: the compound: \" + cmp1 + \" doesn't have a simcompOut.txt file\")\n simcomp_out1 = None\n try:\n simcomp_out2 = open(cmp2 + \"_simcompOut.txt\", \"r\")\n except:\n print(\"ERROR: the compound: \" + cmp2 + \" doesn't have a simcompOut.txt file\")\n simcomp_out2 = None\n\n # first cmp\n if simcomp_out1 is not None:\n try:\n smilepe = simcomp_out1.readline().split()\n if \"1.0\" not in smilepe[1]:\n if float(smilepe[1]) >= 0.9:\n list.append(smilepe[0])\n else:\n list.append(\"\")\n print(\"Compound: \" + cmp1 + \" has kegg ID only with cutoff=\" + smilepe[1])\n else:\n list.append(smilepe[0])\n string1 = \"\"\n for line2 in simcomp_out1:\n string1 = string1 + (line2.split()[0]) + \";\"\n string1 = string1[:-1]\n list.append(string1)\n except:\n cutcom = \"curl -F smiles='\"\n htmlfile = codecs.open(cmp1 + '.html', \"r\", \"utf-8\")\n for line2 in htmlfile:\n if \"SMILES\" in line2:\n smiles = line2[line2.find(\"SMILES String:\") + 15:line2.find(\"

\")]\n break\n cutcom = cutcom + smiles\n cutcom = cutcom + \"' -F cutoff=0.60 -F limit=10 http://rest.genome.jp/simcomp/\"\n\n # listcum.append(cutcom)\n\n# result = subprocess.run(listcum, stdout=subprocess.PIPE)\n# output = result.stdout.decode('utf-8')\n output = os.popen(cutcom).read()\n\n if output:\n list.append(\"\")\n list.append(\"\")\n print(\"Compound: \" + cmp1 + \" has kegg ID only with cutoff=\" + output.split()[1])\n simcomp_out1.close()\n simcomp_out1 = open(cmp1 + \"_simcompOut.txt\", \"w\")\n simcomp_out1.write(output.split()[0] + \"\\t\" + output.split()[1])\n simcomp_out1.close()\n else:\n list.append(\"NA_eawagCMPid\")\n list.append(\"\")\n else:\n print(\"Some serious error: for compound: \" + cmp1 + \" missing the _simcompOut.txt file!\")\n list.append(\"\")\n list.append(\"\")\n\n # second cmp\n if simcomp_out2 is not None:\n try:\n smilepe = simcomp_out2.readline().split()\n if \"1.0\" not in smilepe[1]:\n if float(smilepe[1]) >= 0.9:\n list.append(smilepe[0])\n else:\n list.append(\"\")\n print(\"Compound: \" + cmp2 + \" has kegg ID only with cutoff=\" + smilepe[1])\n else:\n list.append(smilepe[0])\n string2 = \"\"\n for line2 in simcomp_out2:\n string2 = string2 + (line2.split()[0]) + \";\"\n string2 = string2[:-1]\n list.append(string2)\n except:\n cutcom1 = \"curl -F smiles='\"\n cutcom2 = \"' -F cutoff=0.60 -F limit=10 http://rest.genome.jp/simcomp/\"\n\n htmlfile = codecs.open(cmp2 + '.html', \"r\", \"utf-8\")\n for line2 in htmlfile:\n if \"SMILES\" in line2:\n smiles = line2[line2.find(\"SMILES String:\") + 15:line2.find(\"

\")]\n break\n\n command = cutcom1 + smiles + cutcom2\n output = os.popen(command).read()\n\n if output:\n list.append(\"\")\n list.append(\"\")\n print(\"Compound: \" + cmp2 + \" has kegg ID only with cutoff=\" + output.split()[1])\n simcomp_out2.close()\n simcomp_out2 = open(cmp2 + \"_simcompOut.txt\", \"w\")\n simcomp_out2.write(output.split()[0] + \"\\t\" + output.split()[1])\n simcomp_out2.close()\n else:\n list.append(\"NA_eawagCMPid\")\n list.append(\"\")\n else:\n print(\"Some serious error: for compound: \" + cmp2 + \" missing the _simcompOut.txt file!\")\n list.append(\"\")\n list.append(\"\")\n\n list_of_newcolumns[cmp1+cmp2] = list\n simcomp_out1.close()\n simcomp_out2.close()\ncsvfile.close()\n\nname = str(os.getcwd()).split('/')[-1].split('_')[0]\n\ndef testPropertyOfLine(list):\n assert len(list) >= 3\n assert \"r\" in list[0]\n assert \"c\" in list[1]\n assert \"c\" in list[2]\n\n if len(list) == 5:\n return list\n\n if len(list) == 4:\n if list[4][0] == \"e\":\n list.append(\"\")\n return list\n if type(list[4][0]) == int:\n print(\"Reaction: \" + list[0] + \" missing enzyme ID in: \" + name + \" file\")\n ec = list.pop()\n list.append(\"\")\n list.append(ec)\n return list\n if len(list) == 3:\n print(\"Reaction: \" + list[0] + \" missing enzyme ID in: \" + name + \" file\")\n list.append(\"\")\n list.append(\"\")\n return list\n\n\nfold = open(name, 'r')\n\nlist_newfile = []\nlist_header = [\"rxn\", \"eawagCMPid1\", \"eawagCMPid2\", \"eawagENZid\", \"expasyECnum\", \"keggCMP1BestHit\",\n \"keggCMP1alternatives\", \"keggCMP2BestHit\", \"keggCMP2alternatives\"]\nlist_newfile.append(list_header)\n\n# every line in abb file\nfor line in fold:\n list_for_newfile = line.split()\n try:\n list_for_newfile = testPropertyOfLine(list_for_newfile)\n id = str(list_for_newfile[1] + list_for_newfile[2])\n except:\n print(\"Some serious error in file: \" + name + \" missing compounds/reaction ID\")\n n = len(list_for_newfile)\n for i in range(5-n,5):\n list_for_newfile.append(\"\")\n\n\n for item in list_of_newcolumns[id]:\n list_for_newfile.append(item)\n list_newfile.append(list_for_newfile)\n\nif os.path.exists(name + \"_new.csv\"):\n os.remove(name + \"_new.csv\")\n\nwith open(name + '_new.csv', 'w') as f:\n wr = csv.writer(f,delimiter='\\t')\n wr.writerows(list_newfile)\n\nf.close()\nfold.close()\nprint('Successfuly added new kegg columns')\n\n","sub_path":"bigDatabaseEawag/script for bigDatabaseEawag/bigDatabase + data/mtm/addInfoSimcompWithHeader_v4.py","file_name":"addInfoSimcompWithHeader_v4.py","file_ext":"py","file_size_in_byte":6277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"116936895","text":"import os\nfrom nltk.corpus import stopwords\nfrom nltk.stem.wordnet import WordNetLemmatizer\nimport string\nimport nltk\nimport csv\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\nimport collections\nimport re\nstop = set(stopwords.words('english'))\n\nwith open(r\"C:\\Users\\hjn\\Desktop\\大创项目准备\\LDA\\stopwords\\ENstopwords-US.txt\", 'r', encoding='utf-8') as stopwordfile:\n for line in stopwordfile:\n\n stop.add(line.strip('\\n'))\nstop.add('mr')\nstop.add('hr')\n\nexclude = set(string.punctuation) # 标点符号\nlemma = WordNetLemmatizer() # 词干提取\n\n\ndef clean(doc):\n stop_free = \" \".join([i for i in doc.lower().split() if (i not in stop) & (i.isalpha())])\n punc_free = ''.join(ch for ch in stop_free if ch not in exclude)\n normalized = \" \".join(lemma.lemmatize(word) for word in punc_free.split())\n normalized_stop = \" \".join(word for word in normalized.split() if (word not in stop) & (word.isalpha()))\n return normalized_stop\n\n\nfiles_list = []\nd = []\nr = ''\nf = []\nfor root, dirs, files in os.walk(r\"C:\\Users\\hjn\\Desktop\\议会数据\\议会数据\\美国议会数据2019txt\"):\n r = root\n d = dirs\n f = files\nfor i in range(len(f)):\n files_list.append(os.path.join(root, f[i]))\n\n\n\ndoc_clean = []\nfrequency = []\ndoc_clean_huawei = []\nfrequency_huawei = []\ndoc_clean_ZTE = []\nfrequency_ZTE = []\ntop = []\ntop_huawei = []\ntop_zte = []\n\nfor i in range(5,6):\n f = open(files_list[i], 'r', encoding='utf-8')\n doc = f.read()\n f.close()\n words = re.split('.|;',doc)\n sentences = doc.split('.')\n mention_CN = []\n mention_huawei = []\n mention_zte = []\n for j in range(len(sentences)):\n if ('China' in sentences[j]) or ('Beijing' in sentences[j]) or ('Shanghai' in sentences[j]):\n if (j > 1)&((j+1)=len(sentences):\n l = j-1\n r = len(sentences)\n for t in range(l, r):\n if sentences[t] not in mention_CN:\n mention_CN.append(sentences[t])\n \n\n\n\n if ('Huawei' in words):\n if (j > 1)&((j+1)=len(sentences):\n l = j-1\n r = len(sentences)\n for t in range(l, r):\n if sentences[t] not in mention_huawei:\n mention_huawei.append(sentences[t])\n\n \n if ('ZTE' in words):\n if (j > 1)&((j+1)=len(sentences):\n l = j-1\n r = len(sentences)\n for t in range(l, r):\n if sentences[t] not in mention_zte:\n mention_zte.append(sentences[t])\n\n doc_clean.append(clean('.'.join(mention_CN)))\n fdist = nltk.FreqDist(clean('.'.join(mention_CN)).split())\n for key in fdist.keys():\n top.append(key)\n fdist = sorted(fdist.items(), key=lambda k: k[1])\n fdist.reverse()\n frequency.append(fdist[0:20])\n\n doc_clean_huawei.append(clean('.'.join(mention_huawei)))\n fdist = nltk.FreqDist(clean('.'.join(mention_huawei)).split())\n for key in fdist.keys():\n top_huawei.append(key)\n fdist = sorted(fdist.items(), key=lambda k: k[1])\n fdist.reverse()\n frequency_huawei.append(fdist[0:20])\n\n doc_clean_ZTE.append(clean('.'.join(mention_zte)))\n fdist = nltk.FreqDist(clean('.'.join(mention_zte)).split())\n for key in fdist.keys():\n top_zte.append(key)\n fdist = sorted(fdist.items(), key=lambda k: k[1])\n fdist.reverse()\n frequency_ZTE.append(fdist[0:20])\n\n if mention_zte!=[]:\n print('ZTE 已完成' + files_list[i])\n if mention_huawei!=[]:\n print('华为 已完成' + files_list[i])\n print('已完成' + files_list[i])\n\ndoc_clean = '.'.join(doc_clean)\nfdist = collections.Counter(top)\nwordcloud = WordCloud(background_color='white')\nwordcloud = wordcloud.fit_words(fdist)\nplt.imshow(wordcloud)\nplt.show()\nplt.savefig(r\"C:\\Users\\hjn\\Desktop\\大创项目准备\\US\\美国提及中国的词频云图_2019.png\")\n\nheader_a = ['frequency']\nwith open(r\"C:\\Users\\hjn\\Desktop\\大创项目准备\\US\\美国提及中国的词频_2019.csv\", \"w\", encoding='utf-8', newline='') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(header_a)\n csvwriter.writerows(zip(frequency))\ncsvfile.close()\n\n\ndoc_clean_huawei = '.'.join(doc_clean_huawei)\nfdist = collections.Counter(top_huawei)\nwordcloud = WordCloud(background_color='white')\nwordcloud = wordcloud.fit_words(fdist)\nplt.imshow(wordcloud)\nplt.show()\nplt.savefig(r\"C:\\Users\\hjn\\Desktop\\大创项目准备\\US\\美国提及华为的词频云图_2019.png\")\n\nheader_a = ['frequency']\nwith open(r\"C:\\Users\\hjn\\Desktop\\大创项目准备\\US\\美国提及华为的词频_2019.csv\", \"w\", encoding='utf-8', newline='') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(header_a)\n csvwriter.writerows(zip(frequency_huawei))\ncsvfile.close()\n\ndoc_clean_ZTE = '.'.join(doc_clean_ZTE)\nfdist = collections.Counter(top_zte)\nwordcloud = WordCloud(background_color='white')\nwordcloud = wordcloud.fit_words(fdist)\nplt.imshow(wordcloud)\nplt.show()\nplt.savefig(r\"C:\\Users\\hjn\\Desktop\\大创项目准备\\US\\美国提及ZTE的词频云图_2019.png\")\n\nheader_a = ['frequency']\nwith open(r\"C:\\Users\\hjn\\Desktop\\大创项目准备\\US\\美国提及ZTE的词频_2019.csv\", \"w\", encoding='utf-8', newline='') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(header_a)\n csvwriter.writerows(zip(frequency_ZTE))\ncsvfile.close()\n","sub_path":"US/mentionCN.py","file_name":"mentionCN.py","file_ext":"py","file_size_in_byte":6840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"20970131","text":"import sys\nfrom setuptools import setup\n\nentry_points = {\n 'console_scripts': [\n # knossos related\n 'cyclegan = cyclegan_tensorflow.main:main',\n ]\n}\ninstall_requires = []\nsetup(\n name='cyclegan_tensorflow',\n author='xhujoy',\n packages=['cyclegan_tensorflow'],\n entry_points=entry_points,\n include_package_data=True,\n version='1.0',\n description='',\n keywords=[],\n install_requires=install_requires,\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"406886656","text":"import json\nfrom gonzo.aws.route53 import Route53\nfrom gonzo.config import config_proxy as config\nfrom gonzo.helpers.document_loader import get_parsed_document\n\n\ndef get_current_cloud():\n backend = config.CLOUD['BACKEND']\n cloud_module = __import__(\n \"%s.cloud\" % backend, globals(), locals(), ['Cloud'])\n return cloud_module.Cloud()\n\n\ndef get_next_hostname(env_type):\n \"\"\" Calculate the next hostname for a given environment, server_type\n returns the full hostname, including the counter, e.g.\n production-ecommerce-web-013\n \"\"\"\n record_name = \"-\".join([\"_count\", env_type])\n next_count = 1\n r53 = Route53()\n try:\n count_value = r53.get_values_by_name(record_name)[0]\n next_count = int(count_value.replace('\\\"', '')) + 1\n r53.update_record(record_name, \"TXT\", \"%s\" % next_count)\n except: # TODO: specify\n r53.add_remove_record(record_name, \"TXT\", \"%s\" % next_count)\n name = \"%s-%03d\" % (env_type, next_count)\n return name\n\n\ndef launch_instance(env_type, size=None,\n user_data_uri=None, user_data_params=None,\n security_groups=None, extra_tags=None,\n image_name=None, owner=None):\n \"\"\" Launch instances\n\n Arguments:\n env_type (string): environment-server_type\n size (string): size of the instance to launch.\n user_data_uri (string): File path or URL for user data script.\n If None, Config value will be used.\n user_data_params (dict): Dictionary or parameters to supplement\n the defaults when generating user-data.\n security_groups (list): List of security groups to create (if\n necessary) and supplement the defaults.\n owner (string): username to set as owner\n \"\"\"\n\n cloud = get_current_cloud()\n environment, server_type = env_type.split(\"-\", 1)\n\n name = get_next_hostname(env_type)\n\n image_name = config.get_cloud_config_value('IMAGE_NAME',\n override=image_name)\n\n if size is None:\n sizes = config.SIZES\n default_size = sizes['default']\n size = sizes.get(server_type, default_size)\n\n zone = cloud.next_az(server_type)\n\n key_name = config.CLOUD['PUBLIC_KEY_NAME']\n\n tags = extra_tags or {}\n tags.update({\n 'environment': environment,\n 'server_type': server_type,\n })\n\n if owner:\n tags['owner'] = owner\n\n security_groups = add_default_security_groups(server_type, security_groups)\n for security_group in security_groups:\n create_if_not_exist_security_group(security_group)\n\n user_data = None\n user_data_uri = config.get_cloud_config_value('DEFAULT_USER_DATA',\n override=user_data_uri)\n if user_data_uri is not None:\n user_data = get_parsed_document(name, user_data_uri,\n 'USER_DATA_PARAMS', user_data_params)\n\n return cloud.launch_instance(\n name, image_name, size, zone, security_groups, key_name,\n user_data=user_data, tags=tags)\n\n\ndef add_default_security_groups(server_type, additional_security_groups=None):\n # Set defaults\n security_groups = [server_type, 'gonzo']\n\n # Add argument passed groups\n if additional_security_groups is not None:\n security_groups += additional_security_groups\n\n # Remove Duplicates\n security_groups = list(set(security_groups))\n\n return security_groups\n\n\ndef create_if_not_exist_security_group(group_name):\n cloud = get_current_cloud()\n if not cloud.security_group_exists(group_name):\n cloud.create_security_group(group_name)\n\n\ndef configure_instance(instance):\n instance.create_dns_entry()\n\n\ndef generate_stack_template(stack_type, stack_name,\n template_uri, template_params,\n owner=None):\n template_uri = config.get_namespaced_cloud_config_value(\n 'ORCHESTRATION_TEMPLATE_URIS', stack_type, override=template_uri)\n if template_uri is None:\n raise ValueError('A template must be specified by argument or '\n 'in config')\n\n template = get_parsed_document(stack_name, template_uri,\n 'ORCHESTRATION_TEMPLATE_PARAMS',\n template_params)\n\n # Parse as json for validation and for injecting gonzo defaults\n template_dict = json.loads(template)\n\n if owner:\n template_dict = insert_stack_owner_output(template_dict, owner)\n\n return json.dumps(template_dict)\n\n\ndef insert_stack_owner_output(template_dict, owner):\n \"\"\" Adds a stack output to a template with key \"owner\" \"\"\"\n template_outputs = template_dict.get('Outputs', {})\n template_outputs['owner'] = {\n 'Value': owner,\n 'Description': \"This stack's launcher (Managed by Gonzo)\"\n }\n template_dict.update({'Outputs': template_outputs})\n\n return template_dict\n\n\ndef launch_stack(stack_name, template_uri, template_params, owner=None):\n \"\"\" Launch stacks \"\"\"\n\n unique_stack_name = get_next_hostname(stack_name)\n\n template = generate_stack_template(stack_name, unique_stack_name,\n template_uri, template_params,\n owner)\n\n cloud = get_current_cloud()\n return cloud.launch_stack(unique_stack_name, template)\n\n\ndef terminate_stack(stack_name_or_id):\n cloud = get_current_cloud()\n return cloud.terminate_stack(stack_name_or_id)\n","sub_path":"gonzo/backends/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347764415","text":"import sys\ninput = sys.stdin.readline\n\nn = int(input())\n\nworld = [] \nfor i in range(n):\n world.append(list(map(int, input().split())))\n\nINF = 1e9\nmemo = {}\n\nfor i in range(n):\n for j in range(n):\n if world[i][j] == 0:\n world[i][j] = INF\n\ndef find_min(now, visited):\n if visited == (1 << n) - 1:\n return world[now][0]\n \n if (now, visited) in memo:\n return memo[(now, visited)]\n \n min_cost = INF\n \n for i in range(1,n):\n if not(visited & (1 << i)):\n cost = find_min(i, visited | (1 << i)) + world[now][i]\n min_cost = min(min_cost, cost)\n memo[(now, visited)] = min_cost\n return min_cost\n\nprint(find_min(0,1))\n","sub_path":"Bitmasking/BOJ2098외판원순회.py","file_name":"BOJ2098외판원순회.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"223451376","text":"import os\nimport json\nimport pycountry\nimport plotly.express as px\nimport pandas as pd\n\n# Current time for auditable data storing purposes\nfrom datetime import date, datetime\ntoday = date.today()\nnow = datetime.now()\ncurrent_time = now.strftime(\"%H:%M\")\ntimestamp = str(today) + ' ' + str(current_time)\n\n# Global variables\ndefault_input_path = 'Data/world_data_10-05-2020.json'\ndefault_input_props_path = 'Data/world_data_10-05-2020--list_country_properties.json'\ndefault_output_path = 'Results/countryProfiling/country_pandemic_risk ' + timestamp\n\nclass DataProcessor():\n def __init__(self, input_path=default_input_path, output_path=default_output_path, input_props_path=default_input_props_path):\n self.input_path = input_path\n self.output_path = output_path\n self.input_props_path = input_props_path\n self.data = {}\n self.props = {}\n self.risk_levels = {}\n self.risk_df = None\n\n def read(self):\n try:\n with open(self.input_path) as f:\n data = json.load(f)\n with open(self.input_props_path) as f_props:\n props = json.load(f_props)\n except:\n print('Error occured during Data Retrieval')\n data = {}\n props = {}\n self.data = data\n self.props = props\n\n def assess_risk(self):\n countries_data = self.data\n properties = self.props\n risk_levels = {}\n for country_name in countries_data:\n country_risk_level = 0\n country_data = countries_data[country_name]\n for prop_name in properties:\n if prop_name in country_data:\n prop_importance = properties[prop_name]\n country_prop_value = country_data[prop_name]\n if prop_importance:\n if country_prop_value:\n country_risk_level += prop_importance * country_prop_value\n else:\n print(country_name, '-', country_prop_value)\n else:\n print('MISSING', prop_name, 'for', country_name)\n break\n country_risk_level = round(country_risk_level)\n risk_levels[country_name] = country_risk_level\n # Sorting risk levels\n risk_levels = {k: v for k, v in sorted(risk_levels.items(), key=lambda item: item[1])}\n self.risk_levels = risk_levels\n\n def risk_to_df(self):\n risk_levels = self.risk_levels\n risk_levels_matrix = []\n for country_name in risk_levels:\n risk_levels_matrix.append([country_name.replace('_', ' '), risk_levels[country_name]])\n risk_df = pd.DataFrame.from_dict(risk_levels_matrix)\n risk_df.columns = ['Country', 'Pandemic-ready score']\n self.risk_df = risk_df\n\n def get_country_iso(self):\n risk_df = self.risk_df\n if risk_df.empty:\n print('Error - Make sure to generate a risk level dataframe first !')\n return -1\n list_countries = risk_df['Country'].unique().tolist()\n d_country_code = {}\n for country in list_countries:\n try:\n country_data = pycountry.countries.search_fuzzy(country)\n country_code = country_data[0].alpha_3\n d_country_code.update({country: country_code})\n except:\n print('could not add ISO 3 code for ->', country)\n # If could not find country, make ISO code ' '\n d_country_code.update({country: ' '})\n\n # Add a iso_alpha column to the dataframe\n for k, v in d_country_code.items():\n risk_df.loc[(risk_df.Country == k), 'iso_alpha'] = v\n\n self.risk_df = risk_df\n\n def plot_world_heat_map(self):\n risk_df = self.risk_df\n fig = px.choropleth(data_frame=risk_df,\n locations=\"iso_alpha\",\n color=\"Pandemic-ready score\", # value in column 'Confirmed' determines color\n hover_name=\"Country\",\n color_continuous_scale='RdYlGn') # color scale red, yellow green)\n\n fig.show()\n\n def export_data(self, output_format=\"csv\"):\n risk_df = self.risk_df\n if output_format == \"excel\":\n risk_df.to_excel(self.output_path + '.xlsx')\n else:\n risk_df.to_csv(self.output_path + '.csv', sep=';')\n\nif __name__ == \"__main__\":\n\n # Initializing class instance\n countries = DataProcessor()\n # Retrieving data\n countries.read()\n #print(countries.data)\n # Calculating risk factor for each country\n countries.assess_risk()\n print('Pandemic-ready scores by country : \\n', countries.risk_levels)\n # Generate the cuntry/risk dataframe\n countries.risk_to_df()\n # Associate to each country it's ISO code\n countries.get_country_iso()\n # Generate a World Map of COVID scores\n countries.plot_world_heat_map()\n # Export data as Excel and CSV files\n countries.export_data(output_format=\"csv\")\n countries.export_data(output_format=\"excel\")","sub_path":"countryProfiling.py","file_name":"countryProfiling.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"638767830","text":"# -*- coding: utf-8 -*-\n\nimport multiprocessing as mp\nimport pygame as pygame\nimport pandas as pd\nimport filterlib as flt\nimport blink as blk\n#from pyOpenBCI import OpenBCIGanglion\n\n\ndef blinks_detector(quit_program, blink_det, blinks_num, blink,):\n def detect_blinks(sample):\n if SYMULACJA_SYGNALU:\n smp_flted = sample\n else:\n smp = sample.channels_data[0]\n smp_flted = frt.filterIIR(smp, 0)\n #print(smp_flted)\n\n brt.blink_detect(smp_flted, -38000)\n if brt.new_blink:\n if brt.blinks_num == 1:\n #connected.set()\n print('CONNECTED. Speller starts detecting blinks.')\n else:\n blink_det.put(brt.blinks_num)\n blinks_num.value = brt.blinks_num\n blink.value = 1\n\n if quit_program.is_set():\n if not SYMULACJA_SYGNALU:\n print('Disconnect signal sent...')\n board.stop_stream()\n\n\n####################################################\n SYMULACJA_SYGNALU = True\n####################################################\n mac_adress = 'd2:b4:11:81:48:ad'\n####################################################\n\n clock = pygame.time.Clock()\n frt = flt.FltRealTime()\n brt = blk.BlinkRealTime()\n\n if SYMULACJA_SYGNALU:\n df = pd.read_csv('dane_do_symulacji/data.csv')\n for sample in df['signal']:\n if quit_program.is_set():\n break\n detect_blinks(sample)\n clock.tick(200)\n print('KONIEC SYGNAŁU')\n quit_program.set()\n else:\n board = OpenBCIGanglion(mac=mac_adress)\n board.start_stream(detect_blinks)\n\nif __name__ == \"__main__\":\n\n\n blink_det = mp.Queue()\n blink = mp.Value('i', 0)\n blinks_num = mp.Value('i', 0)\n #connected = mp.Event()\n quit_program = mp.Event()\n\n proc_blink_det = mp.Process(\n name='proc_',\n target=blinks_detector,\n args=(quit_program, blink_det, blinks_num, blink,)\n )\n\n # rozpoczęcie podprocesu\n proc_blink_det.start()\n print('subprocess started')\n\n ############################################\n # Poniżej należy dodać rozwinięcie programu\n ############################################\n\n\n\n import pygame\n import sys\n from pygame.locals import *\n import time\n import random\n\n pygame.init()\n\n ## czas co jaki odświeża się ekran\n FPS = 60\n fpsClock = pygame.time.Clock()\n\n ### ustawienia okna gry\n oknogry = pygame.display.set_mode((1500,800))\n\n pygame.display.set_caption('sprawdź co wiesz')\n\n GRAY = (255, 255, 255)\n\n ###### NIE ######\n NIE_SZER = 750 # szerokość\n NIE_WYS = 250 # wysokość\n RED = (255, 0, 0) # kolor wypełnienia\n NIE_POZ = (0, 550) # pozycja zapisana w tupli\n # utworzenie powierzchni NIE, wypełnienie jej kolorem\n NIE = pygame.Surface([NIE_SZER, NIE_WYS])\n NIE.fill(RED)\n\n ###### TAK ######\n TAK_SZER = 750 # szerokość\n TAK_WYS = 250 # wysokość\n GREEN = (154, 205, 50) # kolor wypełnienia\n TAK_POZ = (750, 550) # pozycja zapisana w tupli\n # utworzenie powierzchni TAK, wypełnienie jej kolorem\n TAK = pygame.Surface([TAK_SZER, TAK_WYS])\n TAK.fill(GREEN)\n\n #### PYTANIA ######\n\n # ustawienie prostokąta zawierającego nie\n NIE_prost = NIE.get_rect()\n NIE_prost.x = NIE_POZ[0]\n NIE_prost.y = NIE_POZ[1]\n\n # ustawienie prostokąta zawierającego TAK\n TAK_prost = TAK.get_rect()\n TAK_prost.x = TAK_POZ[0]\n TAK_prost.y = TAK_POZ[1]\n\n ## początkowe ustawienie mrówki i narysowanie jej\n mrowka_Img = pygame.image.load('mrowka.jpg')\n mrowka_x = 650\n mrowka_y = 340\n direction = 'left'\n\n ## wyświetlanie czasu po prawej stronie ekranu\n\n\n # komunikaty tekstowe ###################################################\n\n\n instrukcja = 'Kolor czerwony obrazuje odpowiedź \"nie\", kolor zielony \"tak\". Gdy mrówka znajdzie się po odpowiedniej stronie - mrugnij. Powodzenia!'\n instrukcja1 = 'Naciśnij tak by zacząć grę'\n pytanie1 = 'Królowa mrówek może przeżyć do 25 lat'\n ###Domyślnie odp tak\n pytanie2 = 'Mrówka pokazywana 50 ms pozostanie w pamięci ikonicznej dłużej niż mrówka eksponowana 100 ms'\n ###Odpowiedź tak\n pytanie3 = 'Istnieje około 1000 gatunków mrówek'\n ###Odpowiedź nie\n pytanie4 = 'Mrówka należy do rodziny pajęczaków'\n ###Odpowiedź nie\n pytanie5 = 'Zdanie: jeżeli mrówka jest owadem, to Ziemia jest płaska jest prawdziwe'\n ###Odpowiedź nie\n\n font = pygame.font.Font('freesansbold.ttf', 22)\n\n\n\n numer_pytania = 0\n\n def drukuj_instrukcja():\n tekst1 = font.render(instrukcja, True, (0, 0, 0))\n\n tekst_prost1 = tekst1.get_rect()\n tekst_prost1.center = (750, 25)\n oknogry.blit(tekst1, tekst_prost1)\n\n ### pętla główna programu##\n turn= 0\n pkt=0\n while True:\n oknogry.fill(GRAY)\n ## wyświetlanie instrukcji\n drukuj_instrukcja()\n\n\n\n ## ruch mrówki\n ###Odpwiedź nie === murwka_x <750\n ###Odpowiedźnie === mruwka_x>750\n\n\n #\n ####\n if blink.value == 1:\n print('BLINK!')\n past_dir = direction\n direction = 'null'\n\n\n if turn == 0:\n pyt= font.render('Naciśnij tak by zacząć grę', True, (0, 0, 0))\n oknogry.blit(pyt,(650,100))\n if direction == 'right':\n mrowka_x += 4\n if mrowka_x == 1250:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'left'\n\n elif direction == 'left':\n mrowka_x -= 4\n if mrowka_x == 50:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'right'\n elif direction == 'null':\n if mrowka_x<750 :\n\n direction = past_dir ### Przykład\n turn+=1\n blink.value = 0\n\n\n elif mrowka_x>750:\n\n direction = past_dir\n turn+=1\n blink.value = 0\n\n\n\n\n if turn==1:\n print('turn 1')\n pyt= font.render(pytanie1, True, (0, 0, 0))\n oknogry.blit(pyt,(550,100))\n score =font.render('Punkty:'+str(pkt),True,(0,0,0))\n oknogry.blit(score,(100,100)) ### Manipuluj X i Y aby ustawić napis\n if direction == 'right':\n mrowka_x += 4\n if mrowka_x == 1250:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'left'\n elif direction == 'left':\n mrowka_x -= 4\n if mrowka_x == 50:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'right'\n elif direction == 'null':\n if mrowka_x<750:\n pkt+=0\n turn+=1\n direction = past_dir\n blink.value = 0\n\n elif mrowka_x>750:\n pkt+=1\n turn+=1\n direction = past_dir\n blink.value = 0\n\n if turn ==2:\n print('turn 2')\n pyt= font.render(pytanie2, True, (0, 0, 0))\n oknogry.blit(pyt,(350,100))\n score =font.render('Punkty:'+str(pkt),True,(0,0,0))\n oknogry.blit(score,(100,100)) ### Manipuluj X i Y aby ustawić napis\n if direction == 'right':\n mrowka_x += 4\n if mrowka_x == 1250:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'left'\n elif direction == 'left':\n mrowka_x -= 4\n if mrowka_x == 50:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'right'\n elif direction == 'null':\n if mrowka_x<750:# and ruch == True:\n pkt+=0\n turn+=1\n direction = past_dir\n blink.value = 0\n if mrowka_x>750:# and ruch == True:\n pkt+=1\n turn+=1\n direction = past_dir\n blink.value = 0\n if turn == 3:\n print('turn 3')\n pyt= font.render(pytanie3, True, (0, 0, 0))\n oknogry.blit(pyt,(550,100))\n score =font.render('Punkty:'+str(pkt),True,(0,0,0))\n oknogry.blit(score,(100,100)) ### Manipuluj X i Y aby ustawić napis\n if direction == 'right':\n mrowka_x += 4\n if mrowka_x == 1250:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'left'\n elif direction == 'left':\n mrowka_x -= 4\n if mrowka_x == 50:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'right'\n elif direction == 'null':\n if mrowka_x<750 :#and ruch == True:\n pkt+=1\n turn+=1\n\n direction = past_dir\n blink.value = 0\n if mrowka_x>750:# and ruch == True:\n pkt+=0\n turn+=1\n direction = past_dir\n blink.value = 0\n if turn == 4:\n print('turn 4')\n\n pyt= font.render(pytanie4, True, (0, 0, 0))\n oknogry.blit(pyt,(550,100))\n score =font.render('Punkty:'+str(pkt),True,(0,0,0))\n oknogry.blit(score,(100,100)) ### Manipuluj X i Y aby ustawić napis\n if direction == 'right':\n mrowka_x += 4\n if mrowka_x == 1250:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'left'\n elif direction == 'left':\n mrowka_x -= 4\n if mrowka_x == 50:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'right'\n elif direction == 'null':\n if mrowka_x<750:# and ruch == True:\n pkt+=1\n turn+=1\n\n direction = past_dir\n blink.value = 0\n if mrowka_x>750:# and ruch == True:\n pkt+=1\n turn+=1\n direction = past_dir\n blink.value = 0\n if turn ==5:\n\n pyt= font.render(pytanie5, True, (0, 0, 0))\n oknogry.blit(pyt,(420,100))\n score =font.render('Punkty:'+str(pkt),True,(0,0,0))\n oknogry.blit(score,(100,100)) ### Manipuluj X i Y aby ustawić napis\n if direction == 'right':\n mrowka_x += 4\n if mrowka_x == 1250:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'left'\n elif direction == 'left':\n mrowka_x -= 4\n if mrowka_x == 50:\n mrowka_Img = pygame.transform.flip(mrowka_Img, True, False)\n direction = 'right'\n elif direction == 'null':\n if mrowka_x<750:# and ruch == True:\n pkt+=1\n turn+=1\n blink.value = 0\n if mrowka_x>750:# and ruch == True:\n pkt+=0\n turn+=1\n blink.value = 0\n if turn ==6:\n score = font.render ('Punkty:' +str(pkt),True,(0,0,0))\n oknogry.blit(score(100,100))\n\n\n\n\n\n\n\n\n\n\n #########################\n # #\n # #\n #########################\n oknogry.blit(mrowka_Img, (mrowka_x, mrowka_y))\n # narysuj NIE w oknie gry\n oknogry.blit(NIE, NIE_prost)\n # narysuj TAK w oknie gry\n oknogry.blit(TAK, TAK_prost)\n #####TUTAJ JEST MIEJSCE W KTÓRYM WYŚWIETLA SIĘ PYTANIE\n pygame.display.flip()\n\n ## zamykanie okna gry##\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == K_SPACE:\n past_dir = direction\n\n time.sleep(2)\n\n ## aktualizacja czasu i oknagry\n pygame.display.update()\n fpsClock.tick(FPS)\n","sub_path":"prezentacja/Templatka_projekt2/templatka.py","file_name":"templatka.py","file_ext":"py","file_size_in_byte":12743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"86170769","text":"#coding=utf-8\nfrom datetime import datetime\nimport time\nimport calendar\n\nclass datetimeutils(object):\n\n def __init__(self):\n print('初始化时间工具类')\n\n def get_current_time(self):\n return datetime.now().strftime('%Y-%m-%d')\n\n def get_current_time_new(self):\n return datetime.now().strftime('%Y%m%d')\n\n def get_current_datetime(self):\n return datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\n ###获取当前时间所在的季度.\n def get_current_month_quarter(self):\n Qnum = 0\n currentmonth = datetime.now().strftime('%Y-%m').split('-')[1]\n if currentmonth in ['01','02','03']:\n Qnum =1\n elif currentmonth in ['04','05','06']:\n Qnum =2\n elif currentmonth in ['07','08','09']:\n Qnum =3\n else:\n Qnum =4\n return Qnum\n\n def check_current_data_or_workday(self):\n date = datetime.now().isoweekday()\n if date in [1,2,3,4,5]:\n return True\n else: return False\n\nif __name__ == '__main__':\n print(datetimeutils().get_current_time_new())","sub_path":"finance_common_utils/common_utils/datetime_model/datetime_utils.py","file_name":"datetime_utils.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"410297624","text":"import pika\nimport json\n\n\"\"\"\nfrom channel import Channel\n\npika_channel = Channel(\n hostname=,\n port=,\n exchangename=,\n exchangetype=\n)\n\n-- To send to queue ------------\n\npika_channel.basic_publish(\n routing_key=, \n body_dict=\n)\n\n-------------------------------\n\n\n-- To consume -----------------\n\ndef callback(channel, method, properties, body):\n pass\n\npika_channel.set_consume_callback(queue=, callback=)\npika_channel.start_consuming()\n\n-------------------------------\n\n\"\"\"\nclass Channel:\n def __init__(self, hostname, port, exchangename, exchangetype):\n self.hostname = hostname\n self.port = port\n self.exchangename = exchangename\n self.exchangetype = exchangetype\n\n self.connection = pika.BlockingConnection(\n pika.ConnectionParameters(\n host=hostname, port=port,\n heartbeat=3600, blocked_connection_timeout=3600, # these parameters to prolong the expiration time (in seconds) of the connection\n )\n )\n self.channel = self.connection.channel()\n\n def set_consume_callback(self, queue, callback):\n self.callback = self.get_wrapped_callback(callback)\n self.channel.basic_consume(\n queue=queue, \n on_message_callback=self.callback, \n auto_ack=True\n )\n \n def start_consuming(self):\n return self.channel.start_consuming()\n\n def basic_publish(self, routing_key, body_dict):\n self.check_setup()\n self.channel.basic_publish(\n exchange=self.exchangename, \n routing_key=routing_key, \n body=json.dumps(body_dict), \n properties=pika.BasicProperties(delivery_mode = 2)\n ) \n \n def is_connection_open(self):\n try:\n self.connection.process_data_events()\n return True\n except pika.exceptions.AMQPError as e:\n print(\"AMQP Error:\", e)\n print(\"...creating a new connection.\")\n return False\n\n def check_setup(self):\n if not self.is_connection_open():\n self.connection = pika.BlockingConnection(pika.ConnectionParameters(host=self.hostname, port=self.port))\n if self.channel.is_closed:\n self.channel = self.connection.channel()\n self.channel.exchange_declare(exchange=self.exchangename, exchange_type=self.exchangetype)\n\n def get_wrapped_callback(self, callback):\n def wrapped_callback(*args, **kwargs):\n self.check_setup()\n return callback(*args, **kwargs)\n return wrapped_callback","sub_path":"backend/boilerplate-protected-endpoint/channel.py","file_name":"channel.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"45191002","text":"\n\n#\n# Copyright 2019 Xilinx Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport importlib.util\nimport os\nimport sys\nfrom typing import Any, NoReturn, Optional, Sequence, Tuple, Union\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport nndct_shared.utils as nndct_utils\nfrom nndct_shared.base import FrameworkType\nfrom nndct_shared.nndct_graph import Graph\nfrom nndct_shared.optimization import QuantOptimizer\nfrom pytorch_nndct.export import get_script_writer\nfrom nndct_shared.utils import NndctDebugLogger, NndctOption, NndctScreenLogger\nfrom pytorch_nndct.parse import TorchParser\nfrom pytorch_nndct.quantization import TORCHQuantizer\nfrom pytorch_nndct.utils import TorchSymbol\nfrom pytorch_nndct.nn.modules import reluk, channel_scale\nfrom nndct_shared.compile import DevGraphOptimizer\n\nfrom .ModuleHooker import ModuleHooker\n\n\ndef _reload_module(module_file_name: str, module_name: str) -> torch.nn.Module:\n\n py_module_name = \"_\".join([\"nndct\", module_name])\n spec = importlib.util.spec_from_file_location(py_module_name,\n module_file_name)\n py_module = importlib.util.module_from_spec(spec)\n sys.modules[py_module_name] = py_module\n spec.loader.exec_module(py_module)\n return py_module.__dict__[module_name]()\n\n\ndef recreate_nndct_module(graph: Graph, enable_quant: bool, export_file: str) -> torch.nn.Module:\n\n exporter = get_script_writer(enable_quant=enable_quant)\n exporter.write(graph, file_path=export_file)\n nndct_module = _reload_module(export_file, graph.name)\n return nndct_module\n\n\ndef parse_module(module: Union[torch.nn.Module, torch.jit.ScriptModule],\n input_args: Union[torch.Tensor, Sequence[Any]],\n enable_opt: bool = True,\n graph_name: Optional[str] = None) -> Graph:\n\n if NndctOption.nndct_equalization.value:\n if NndctOption.nndct_relu6_replace.value == 'reluk':\n replace_relu6_with_reluk(module)\n elif NndctOption.nndct_relu6_replace.value == 'relu':\n replace_relu6_with_relu(module)\n \n if NndctOption.nndct_wes.value:\n insert_scale_after_conv2d(module)\n \n parser = TorchParser()\n graph = parser(module._get_name() if graph_name is None else graph_name,\n module, input_args)\n if enable_opt:\n graph = quant_optimize(graph)\n \n if NndctOption.nndct_parse_debug.value >= 3:\n NndctDebugLogger.write(f\"nndct quant graph:\\n{graph}\")\n return graph\n\n\ndef quant_optimize(graph: Graph):\n def _execute_optimize(block):\n optimizer = QuantOptimizer()\n graph = optimizer(block)\n return graph\n \n for block in graph.block_subgraphs():\n quant_optimize(block)\n graph = _execute_optimize(graph)\n return graph\n \ndef register_output_hook(module: torch.nn.Module, record_once: bool = True) -> NoReturn:\n ModuleHooker.register_output_hook(module, record_once)\n\n\ndef disconnect_modeule_with_graph(module):\n ModuleHooker.detach_node_from_module(module)\n \n \ndef connect_module_with_graph(module: torch.nn.Module,\n graph: Graph,\n recover_param: bool = True,\n recover_state_dict_keys: bool = False) -> NoReturn:\n \"\"\"\n Hook graph info with modules\n Args:\n module (torch.nn.Module): rebuild module\n graph (Graph): nndct graph\n record_once (bool, optional): whether record output once or multiple times. Defaults to True.\n recover_param (bool, optional): recover parameters from graph to module. Defaults to True.\n recover_state_dict_keys (bool, optional): recover the state dict keys in rebuild module from graph. Defaults to False.\n \"\"\"\n\n # ModuleHooker.register_output_hook(module, record_once)\n\n ModuleHooker.hook_module_with_node(module, graph)\n \n # if bn is fused into conv, recover_state_dict_keys should be False\n if recover_state_dict_keys:\n ModuleHooker.register_state_dict_hook(module)\n \n if recover_param:\n ModuleHooker.update_parameters(module, graph, graph2module=True)\n\n\n# def connect_module_with_quantizer(module: torch.nn.Module,\n# quantizer: TORCHQuantizer) -> NoReturn:\n# ModuleHooker.hook_module_with_quantizer(module, quantizer)\n\n\ndef update_nndct_parameters(module: torch.nn.Module, graph: Graph) -> NoReturn:\n ModuleHooker.update_parameters(module, graph, graph2module=False)\n\n\ndef update_nndct_blob_data(module: torch.nn.Module,\n graph: Graph,\n time_step: Optional[int] = None) -> NoReturn:\n ModuleHooker.update_blobs_once(module, graph, time_step)\n\n\ndef set_outputs_recorder_status(module, turn_on) -> NoReturn:\n ModuleHooker.clear_record_outputs(module)\n ModuleHooker.turn_on_record_outputs(\n module) if turn_on else ModuleHooker.turn_off_record_outputs(module)\n\n\ndef prepare_quantizable_module(\n module: torch.nn.Module,\n input_args: Union[torch.Tensor, Sequence[Any]],\n export_folder: str,\n state_dict_file: Optional[str] = None,\n quant_mode: int = 1, \n device: torch.device = torch.device(\"cuda\")) -> Tuple[torch.nn.Module, Graph]:\n\n nndct_utils.create_work_dir(export_folder)\n\n if isinstance(state_dict_file, str):\n state_dict = torch.load(state_dict_file)\n module.load_state_dict(state_dict)\n\n export_file = os.path.join(export_folder,\n module._get_name() + TorchSymbol.SCRIPT_SUFFIX)\n \n # switch to specified device\n module, input_args = to_device(module, input_args, device)\n \n # parse origin module to graph\n NndctScreenLogger().info(f\"=>Parsing {module._get_name()}...\")\n graph = parse_module(module, input_args)\n NndctScreenLogger().info(f\"=>Quantizable module is generated.({export_file})\")\n # recreate quantizable module from graph\n quant_module = recreate_nndct_module(graph, True, export_file).to(device)\n quant_module.train(mode=module.training)\n # hook module with graph\n connect_module_with_graph(quant_module, graph)\n\n return quant_module, graph\n\n\ndef to_device(module: torch.nn.Module, \n input_args: Union[torch.Tensor, Sequence[Any]], \n device: torch.device) -> Tuple[torch.nn.Module, Union[torch.Tensor, Sequence[Any]]]:\n NndctScreenLogger().info(f\"=>Quant Module is in '{device.type}'.\")\n if input_args is not None:\n if isinstance(input_args, torch.Tensor):\n input_args = input_args.to(device)\n else:\n is_tuple = True if isinstance(input_args, tuple) else False\n input_args = list(input_args)\n for i in range(len(input_args)):\n if isinstance(input_args[i], torch.Tensor):\n input_args[i] = input_args[i].to(device)\n if is_tuple:\n input_args = tuple(input_args)\n \n module = module.to(device)\n return module, input_args\n\ndef replace_relu6_with_relu(module: torch.nn.Module):\n def _replace_func(op):\n for op_name, c_op in op.named_children():\n if isinstance(c_op, torch.nn.ReLU6):\n op._modules[op_name] = torch.nn.ReLU(c_op.inplace)\n if any([isinstance(submodule, torch.nn.ReLU6) for submodule in module.modules()]):\n module.apply(_replace_func)\n NndctScreenLogger().warning(f\"ReLU6 has been replaced by ReLU.\")\n \ndef replace_relu6_with_reluk(module: torch.nn.Module):\n def _replace_func(op):\n for op_name, c_op in op.named_children():\n if isinstance(c_op, torch.nn.ReLU6):\n #op._modules[op_name] = torch.nn.ReLU(c_op.inplace)\n op._modules[op_name] = reluk.ReLUk(channel_max=6.0)\n if any([isinstance(submodule, torch.nn.ReLU6) for submodule in module.modules()]):\n module.apply(_replace_func)\n NndctScreenLogger().warning(f\"ReLU6 has been replaced by ReLUK.\")\n \ndef insert_scale_after_conv2d(module: torch.nn.Module):\n def _insert_func(op):\n insert_name = None\n conv2d_cnt = 0 \n find_conv2d = False \n for op_name, c_op in op.named_children():\n if find_conv2d:\n conv2d_cnt = conv2d_cnt+1\n if isinstance(c_op, torch.nn.Conv2d) or isinstance(c_op, torch.nn.ConvTranspose2d):\n find_conv2d = True\n insert_name = op_name\n elif isinstance(c_op, torch.nn.BatchNorm2d) and (find_conv2d == True):\n insert_name = op_name\n \n if conv2d_cnt == 1:\n op._modules[insert_name] = torch.nn.Sequential(op._modules[insert_name], channel_scale.ChannelScale(channel_scale=1.0))\n find_conv2d = False\n conv2d_cnt = 0\n if find_conv2d:\n op._modules[insert_name] = torch.nn.Sequential(op._modules[insert_name], channel_scale.ChannelScale(channel_scale=1.0))\n \n if any([(isinstance(submodule, torch.nn.Conv2d) or isinstance(submodule, torch.nn.ConvTranspose2d)) for submodule in module.modules()]):\n module.apply(_insert_func)\n NndctScreenLogger().warning(f\"ChannelScale has been inserted after Conv2d.\")\n \ndef insert_scale_after_batchnorm2d(module: torch.nn.Module):\n def _insert_func(op):\n for op_name, c_op in op.named_children():\n if isinstance(c_op, torch.nn.BatchNorm2d):\n op._modules[op_name] = torch.nn.Sequential(op._modules[op_name], channel_scale.ChannelScale(channel_scale=1.0))\n if any([(isinstance(submodule, torch.nn.BatchNorm2d)) for submodule in module.modules()]):\n module.apply(_insert_func)\n NndctScreenLogger().warning(f\"ChannelScale has been inserted after batchnorm2d.\")\n\ndef get_deploy_graph_list(quant_model, nndct_graph):\n g_optmizer = DevGraphOptimizer(nndct_graph)\n g_optmizer.infer_tensor_layout()\n g_optmizer.strip_redundant_ops()\n \n # for node in g_optmizer._dev_graph.nodes:\n # print(f\"{node.name}, {node.op.type}, {node.out_tensors[0].layout}\")\n \n # sync model data with dev graph\n connect_module_with_graph(quant_model, g_optmizer.frozen_graph, recover_param=False)\n update_nndct_blob_data(quant_model, g_optmizer.frozen_graph)\n connect_module_with_graph(quant_model, nndct_graph, recover_param=False)\n \n g_optmizer.constant_folding()\n if NndctOption.nndct_parse_debug.value >= 3:\n NndctDebugLogger.write(f\"\\nfrozen dev graph:\\n{g_optmizer.frozen_graph}\")\n \n deploy_graphs = g_optmizer.partition_by_quant_part() \n \n return deploy_graphs\n","sub_path":"tools/Vitis-AI-Quantizer/vai_q_pytorch/pytorch_binding/pytorch_nndct/qproc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"517417349","text":"#!/usr/bin/env python3\n\"\"\"\n随机取10个数:\n\t数字取值范围[1,20]\n\t重复的数字及次数\n\t不重复的数字\n\"\"\"\nimport random\n\n\nnum = []\nrepeat = {}\nsingle = []\n\nfor _ in range(10):\n\tnum.append(random.randint(1, 20))\n\nfor value in num:\n\tif num.count(value) > 1:\n\t\trepeat[value] = num.count(value)\n\telse:\n\t\tsingle.append(value)\n\nprint(\"{}-->{}\".format(\"RepeatNum\", \"Count\"))\nfor repeatNum, count in repeat.items():\n\tprint(\"{:>4}:{:^4}\".format(repeatNum, count))\n\nprint(\"SingleNum:\")\nfor singleNum in single:\n\tprint(\"{:^2}\".format(singleNum), end=' ')\n\n","sub_path":"random-num.py","file_name":"random-num.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"490414370","text":"\nfrom duplocli.terraform.aws.common.tf_utils import TfUtils\nfrom duplocli.terraform.aws.schema.aws_tf_schema import AwsTfSchema\nimport os\nimport requests\nimport psutil\nfrom duplocli.terraform.aws.common.tf_file_utils import TfFileUtils\n\nclass AwsCreateTfstateStep1 :\n\n step = \"step1\"\n aws_tf_schema = {}\n mapping_aws_keys_to_tf_keys = []\n main_tf_json_dict = {\"resource\":{}}\n resources_dict = main_tf_json_dict[\"resource\"]\n tf_import_sh_list = []\n\n def __init__(self, params):\n self.params = params\n self.aws_az = params.aws_region\n self.utils = TfUtils(params, step=self.step)\n #file_utils for steps\n self.file_utils = TfFileUtils(params, step=self.step)\n self._load_schema()\n\n ############ execute_step public api ##########\n def execute_step(self, aws_obj_list=[]):\n self._aws_provider()\n self._empty_output()\n self._aws_resources(aws_obj_list)\n self._create_tf_state()\n return self.file_utils.tf_main_file()\n\n ############ download_key public api ##########\n def download_key(self, aws_obj_list=[] ):\n # download_aws_keys = self.params.download_aws_keys\n url = self.params.url\n tenant_id = self.params.tenant_id\n api_token = self.params.api_token\n if url is None or tenant_id is None or api_token is None :\n raise Exception(\"to download_keys - url, tenant_id, api_token are required.\")\n\n for aws_key_pair_instance in aws_obj_list:\n #aws_obj = {\"name\":name, \"key_name\":key_name, \"instanceId\":instanceId}\n key_name = aws_key_pair_instance['key_name']\n instanceId = aws_key_pair_instance['instanceId']\n endpoint = \"{0}/subscriptions/{1}/getKeyPair/{2}\".format(url\n , tenant_id\n , instanceId)\n headers = {\"Authorization\": \"Bearer {0}\".format( api_token )}\n response = requests.get(endpoint, headers=headers)\n self.file_utils.save_key_file(key_name, response.content )\n print(\"**** aws import step1 : save_key_file \", key_name, instanceId)\n return (self.file_utils.tf_main_file(), self.file_utils.tf_state_file(), self.file_utils.keys_folder())\n\n ############ aws tf resources ##########\n # aws_resources\n # [\n # {\n # \"tf_import_id\": \"duploservices-bigdata01\",\n # \"tf_resource_type\": \"aws_iam_role\",\n # \"tf_variable_id\": \"AROARKHYLTX2Z5RQWNRSM\"\n # },\n # ]\n def _aws_resources(self, aws_obj_list):\n for aws_obj in aws_obj_list:\n self._aws_resource(aws_obj)\n\n def _aws_resource(self, aws_obj):\n tf_resource_type=aws_obj['tf_resource_type']\n resource_obj = self._init_aws_resource(aws_obj)\n #hack: insert required fields: we are adding dummy data\n schema = self.aws_tf_schema.get_tf_resource(tf_resource_type)\n for required_name in schema.required:\n # keep an eye --- we are neglecting datas type !\n resource_obj[required_name] = \"aa\"\n return resource_obj\n\n def _init_aws_resource(self, aws_obj):\n tf_resource_type = aws_obj['tf_resource_type']\n tf_resource_var_name= aws_obj['tf_variable_id']\n tf_resource_type_sync_id = aws_obj['tf_import_id']\n ### create entry main.tf.json: resource \"TF_RESOURCE_TYPE\" \"TF_RESOURCE_VAR_NAME\"\n tf_resource_type_root = self._get_or_create_tf_resource_type_root(tf_resource_type)\n resource_obj = {}\n tf_resource_type_root[tf_resource_var_name] = resource_obj\n ### create entry run.sh: terraform import \"TF_RESOURCE_TYPE.TF_RESOURCE_VAR_NAME\" \"tf_resource_type_sync_id\"\n self.tf_import_sh_list.append(\n 'terraform import \"' + tf_resource_type + '.' + tf_resource_var_name + '\" \"' + tf_resource_type_sync_id + '\"')\n ### return: resource_obj\n return resource_obj\n\n def _get_or_create_tf_resource_type_root(self, tf_resource_type):\n #get parent for the resource\n if tf_resource_type not in self.resources_dict:\n self.resources_dict[tf_resource_type] = {}\n return self.resources_dict[tf_resource_type]\n\n def _load_schema(self):\n self.aws_tf_schema = AwsTfSchema(self.params, self.file_utils.aws_tf_schema_file())\n\n ############ aws_provider ##########\n def _aws_provider(self):\n tf_resource_type = \"provider\"\n tf_resource_var_name = \"aws\"\n resource_obj = self._base_provider(tf_resource_type, tf_resource_var_name)\n resource_obj[\"version\"] = \"~> 2.0\"\n resource_obj[\"region\"] = self.aws_az\n self.tf_import_sh_list.append('terraform init ')\n return resource_obj\n def _base_provider(self, tf_resource_type, tf_resource_var_name):\n resource_obj = {}\n resource_obj[tf_resource_var_name] = {}\n self.main_tf_json_dict[tf_resource_type] = resource_obj\n return resource_obj[tf_resource_var_name]\n\n ############ main.tf.json + script + generate state ##########\n def _empty_output(self):\n self.file_utils.empty_temp_folder()\n\n def _create_tf_state(self):\n # self._empty_output()\n ## save files\n self._plan()\n self.file_utils.save_main_file(self.main_tf_json_dict)\n self.file_utils.save_tf_import_script(self.tf_import_sh_list)\n self.file_utils.save_tf_run_script()\n ## execute script\n self.file_utils.create_state(self.file_utils.tf_run_script())\n self.rm_aws_security_group_rule_tf_bug()\n\n def _plan(self):\n ### create: terraform plan ...\n # bug in tf -> creates extra aws_security_group_rule... remove aws_security_group_rule first.\n # self.tf_import_sh_list.append(\n # 'terraform state list | grep aws_security_group_rule | xargs terraform state rm; terraform plan')\n\n self.tf_import_sh_list.append( \"terraform plan\")\n\n ############ main.tf.json + script + generate state ##########\n def rm_aws_security_group_rule_tf_bug(self):\n main_resources= self.main_tf_json_dict['resource']\n aws_security_group_rules=[]\n object_type_bug=\"aws_security_group_rule\" # #aws_security_group\n if object_type_bug in main_resources:\n aws_security_group_rules = list(main_resources[object_type_bug].keys())\n\n state_dict = self.file_utils.load_json_file( self.file_utils.tf_state_file())\n if \"resources\" in state_dict:\n resources = state_dict['resources']\n else:\n resources = state_dict['resource']\n\n resources_to_del = []\n for resource in resources: #list\n # print(resource)\n if object_type_bug == resource[\"type\"]:\n name = resource[\"name\"]\n if name not in aws_security_group_rules:\n # resources.remove(resource)\n resources_to_del.append(resource)\n else:\n print(\"name skip \", name)\n for resource in resources_to_del: # list\n resources.remove(resource)\n # save\n self.file_utils.save_state_file(state_dict)\n # print(state_dict)\n","sub_path":"duplocli/terraform/aws/step1/aws_create_tfstate_step1.py","file_name":"aws_create_tfstate_step1.py","file_ext":"py","file_size_in_byte":7256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"200011165","text":"import socket\nfrom multiprocessing import Process\n\nlisten_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nlisten_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n\n\naddress = ('127.0.0.1', 8080)\n\n\nlisten_sock.bind(address)\n\n\ndef handle(client_sock, client_addr):\n while 1:\n recv_dat = client_sock.recv(1024)\n if recv_dat:\n print('客户端{}发来消息{}'.format(client_addr, recv_dat.decode()))\n client_sock.send(recv_dat)\n else:\n print('{}关闭了客户端'.format(client_addr))\n client_sock.close()\n break\n\n\n\nlisten_sock.listen(128)\nwhile 1:\n client_sock, client_addr = listen_sock.accept()\n\n print('客户端{}已连接'.format(client_addr))\n process = Process(target=handle, args=(client_sock, client_addr))\n \n process.start()\n\n listen_sock.close()\n \n","sub_path":"就业/linux网络编程/10/tcp_process.py","file_name":"tcp_process.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"465780714","text":"# -*- coding: utf-8 -*-\nfrom dbhelper import DBHelper\nfrom flask import Flask, render_template,url_for, redirect\nfrom flask import request as flaskRequest\nimport requests, json, datetime, dateparser, string\n\napp = Flask(__name__)\nDB = DBHelper()\n\ncategories = ['Mugging', 'Break-in']\n\ndef format_date(userdate):\n\tdate = dateparser.parse(userdate)\n\ttry:\n\t\treturn datetime.datetime.strftime(date,\"%Y-%m-%d\")\n\texcept:\n\t\treturn None\n\ndef sanitize_string(userinput):\n\twhitelist = string.ascii_letters + string.digits + \" !?$.,;:-'()&\\\"\"\n\treturn ''.join(list(filter(lambda x: x in whitelist, userinput)))\n\n@app.route('/')\ndef index(error_message=None):\n\tcrimes = json.dumps(DB.get_all_crimes())\n\treturn render_template('index.html', crimes=crimes,\n\tcategories=categories, error_message=error_message)\n\n@app.route(\"/addcrime\", methods=['POST'])\ndef submitcrime():\n\tcategory = flaskRequest.form.get('category')\n\tif category not in categories:\n\t\treturn redirect(url_for('index'))\n\ttitle = flaskRequest.form.get('title')\n\tdate = format_date(flaskRequest.form.get('date'))\n\tif not date:\n\t\treturn index(\"Invalid date. Please use dd-mm-YYYY format\")\n\ttry:\n\t\tlatitude = float(flaskRequest.form.get('latitude'))\n\t\tlongitude = float(flaskRequest.form.get('longitude'))\n\texcept ValueError:\n\t\treturn index(\"Please place marker on the map\")\n\tdescription = sanitize_string(flaskRequest.form.get('description'))\n\ttry:\n\t\tDB.add_crime(category,title,date,latitude,longitude,description)\n\texcept Exception as e:\n\t\tprint(e)\n\tfinally:\n\t\treturn index()\n\nif __name__ == \"__main__\":\n\tapp.run(port=5000, debug=True)\n","sub_path":"crimemap.py","file_name":"crimemap.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"623170438","text":"#-*- codeing = utf-8 -*-\n#@time : 2021/6/7 0007 16:44\n#@author : HJK\n#@file : test3.py\n#@softwoare : PyCharm\n\n'''\n 购物商城:\n 需求:购物商城\n 1.商品\n 2.金钱\n 3.购物车\n\n 买东西需求:\n 看这个商品是不是存在\n 若存在,\n 您的余额是否够买这个东西\n 将自己的余额减去商品的价格\n 将这个商品添加购物车。\n 余额不够:提示您的余额,穷鬼!选其他商品!\n 若不存在:提示,您要的商品不存在。\n 是否是Q,q:\n 结算,打印购物小条。\n有十张优惠券,系统初始化就会随机抽取一张优惠券。最后计算的时候进行打折。\n1.进入商城时候,随机抽奖某个商品的优惠券。\n优惠券如下:\n\t\t10张辣条优惠券:满600减300\n\t\t20张Lenovo电脑优惠券:半折甩卖\n2.结算时,添加购物积分功能\n10元1个积分。\n'''\n\n# 准备必备商品\nimport random\nprices_list = [[\"联想电脑\",0.5],[\"Iphone 16x plus\",0.3],[\"PS5游戏机\",0.7],[\"老于妈\",0.1],[\"老于妈\",0.5]\n ,[\"卫龙辣条\",1],[\"HUA WEI watch\",0.8],[\"MAC PC\",0.5]]\n#随机生成一张优惠券\nrandom_num = random.randint(0,6)\nprint(random_num)\n#优惠的商品\nyouhui_goods = prices_list[random_num]\nshop=[\n [\"联想电脑\",6000],\n [\"Iphone 16x plus\",15000],\n [\"PS5游戏机\",3500],\n [\"老干妈\",7.5],\n [\"老于妈\",5.5],\n [\"卫龙辣条\",10],\n [\"HUA WEI watch\",1200],\n [\"MAC PC\",15000]\n]\n# 空的购物车\nmycart = []\nmoney = 0\nsale_money = 0\nall_apeed = 0\nman = 0\nwhile True:\n money = input(\"请输入你的余额:\")\n if money.isdigit():\n money = int(money)\n break\n else:\n print(\"输入有误,请重新输入\")\nnew_price = 0\nwhile True:\n for i,j in enumerate(shop):\n print(i,j)\n id = input(\"请输入要购买商品的编号:\")\n if id.isdigit():\n id = int(id)\n if id > len(shop)-1 or id < 0:\n print(\"输入的编号有误,请重新输入\")\n else:\n if youhui_goods[0] == shop[id][0]!= \"卫龙辣条\":\n new_price = shop[id][1] * youhui_goods[1]\n if money >= new_price:\n mycart.append(shop[id][0])\n money = money - new_price\n sale_money += new_price\n all_apeed+= new_price\n print(\"购买成功,余额还剩¥:\",money)\n else:\n print(\"余额只剩:\",money,\"请购买其他商品\")\n elif youhui_goods[0] == \"卫龙辣条\":\n if money >= shop[id][1]:\n mycart.append(shop[id][0])\n money = money - shop[id][1]\n print(\"满减前还剩\",money)\n sale_money += shop[id][1]\n all_apeed +=shop[id][1]\n print(\"满减前花了\",sale_money)\n if sale_money // 600 > 0:\n nums = sale_money//600\n money += 300*int(nums)\n print(\"满减后还剩\", money)\n all_apeed -= 300*int(nums)\n sale_money = 0\n print(\"满减后花了\", all_apeed)\n else:\n print(\"余额只剩:\",money,\"请购买其他商品\")\n else:\n if money >= shop[id][1]:\n mycart.append(shop[id][0])\n money = money - shop[id][1]\n all_apeed += shop[id][1]\n print(\"购买成功,余额还剩¥:\",money)\n else:\n print(\"余额只剩:\",money,\"请购买其他商品\")\n elif id == \"q\" or id == \"Q\":\n print(\"成功退出系统\")\n break\n else:\n print(\"输入的编号有误,请重新输入\")\nprint(\"-----------您购买的商品信息如下-----------\")\nzidian = {}\nfor i in range(len(mycart)):\n if mycart[i] not in zidian:\n zidian[mycart[i]] = 1\n else:\n zidian[mycart[i]] += 1\nprint(zidian)\nfor key,values in zidian.items():\n print(key,values)\nold_fen = 0\nnew_fen = all_apeed // 10\nprint(\"您的积分为%d\"%(old_fen+new_fen))","sub_path":"test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":4384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573467339","text":"import logging\nimport time\nfrom ._meta import ECS_VERSION\nfrom ._utils import merge_dicts, de_dot, json_dumps, TYPE_CHECKING\n\nif TYPE_CHECKING:\n from typing import Any, Dict\n\n\nclass StdlibFormatter(logging.Formatter):\n \"\"\"ECS Formatter for the standard library ``logging`` module\"\"\"\n\n WANTED_ATTRS = {\n \"levelname\": \"log.level\",\n \"funcName\": \"log.origin.function\",\n \"lineno\": \"log.origin.file.line\",\n \"filename\": \"log.origin.file.name\",\n \"message\": \"log.original\",\n \"name\": \"log.logger\",\n }\n LOGRECORD_DICT = {\n \"name\",\n \"msg\",\n \"args\",\n \"levelname\",\n \"levelno\",\n \"pathname\",\n \"filename\",\n \"module\",\n \"exc_info\",\n \"exc_text\",\n \"stack_info\",\n \"lineno\",\n \"funcName\",\n \"created\",\n \"msecs\",\n \"relativeCreated\",\n \"thread\",\n \"threadName\",\n \"processName\",\n \"process\",\n }\n converter = time.gmtime\n\n def __init__(self):\n # type: () -> None\n super(StdlibFormatter, self).__init__()\n\n def format(self, record):\n # type: (logging.LogRecord) -> str\n result = self.format_to_ecs(record)\n return json_dumps(result)\n\n def format_to_ecs(self, record):\n # type: (logging.LogRecord) -> Dict[str, Any]\n \"\"\"Function that can be overridden to add additional fields\n to the JSON before being dumped into a string.\n \"\"\"\n timestamp = \"%s.%03dZ\" % (\n self.formatTime(record, datefmt=\"%Y-%m-%dT%H:%M:%S\"),\n record.msecs,\n )\n result = {\"@timestamp\": timestamp, \"ecs\": {\"version\": ECS_VERSION}}\n available = record.__dict__\n\n # This is cleverness because 'message' is NOT a member\n # key of ``record.__dict__`` the ``getMessage()`` method\n # is effectively ``msg % args`` (actual keys) By manually\n # adding 'message' to ``available``, it simplifies the code\n available[\"message\"] = record.getMessage()\n\n for attribute in set(self.WANTED_ATTRS).intersection(available):\n ecs_attr = self.WANTED_ATTRS[attribute]\n value = getattr(record, attribute)\n if ecs_attr == \"log.level\" and isinstance(value, str):\n value = value.lower()\n merge_dicts(de_dot(ecs_attr, value), result)\n\n # Merge in any keys that were set within 'extra={...}'\n for key in set(available.keys()).difference(self.LOGRECORD_DICT):\n merge_dicts(de_dot(key, available[key]), result)\n\n # The following is mostly for the ecs format. You can't have 2x\n # 'message' keys in WANTED_ATTRS, so we set the value to\n # 'log.original' in ecs, and this code block guarantees it\n # still appears as 'message' too.\n result.setdefault(\"message\", available[\"message\"])\n return result\n","sub_path":"ecs_logging/_stdlib.py","file_name":"_stdlib.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"226255610","text":"import torch\n\n\ndef compute_offset_norm_loss(offset_preds, offset_gts, instance_labels, ignore_label=-100):\n\n pt_diff = offset_preds - offset_gts # (N, 3)\n pt_dist = torch.sum(torch.abs(pt_diff), dim=-1) # (N)\n valid = (instance_labels != ignore_label).float()\n offset_norm_loss = torch.sum(pt_dist * valid) / (torch.sum(valid) + 1e-6)\n\n return offset_norm_loss\n\n\ndef compute_offset_dir_loss(offset_preds, offset_gts, instance_labels, ignore_label=-100):\n\n gt_offsets_norm = torch.norm(offset_gts, p=2, dim=1) # (N), float\n gt_offsets_ = offset_gts / (gt_offsets_norm.unsqueeze(-1) + 1e-8)\n pt_offsets_norm = torch.norm(offset_preds, p=2, dim=1)\n pt_offsets_ = offset_preds / (pt_offsets_norm.unsqueeze(-1) + 1e-8)\n direction_diff = - (gt_offsets_ * pt_offsets_).sum(-1) # (N)\n valid = (instance_labels != ignore_label).float()\n offset_dir_loss = torch.sum(direction_diff * valid) / (torch.sum(valid) + 1e-6)\n\n return offset_dir_loss\n\n\n","sub_path":"model/loss_functions.py","file_name":"loss_functions.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"80787446","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSome variables for use in the analysis of the SOA experiment.\n\"\"\"\n\n# (x,y) resolution of the screen in pixels.\nscreenRes = (1920.,1080.)\n\n# Diagonal size of the screen in cm.\nscreenSize = 60.\n\n# Distance of eyes from the screen in cm.\nviewingDist = 70.\n\n# Thresholds for saccade detection in degrees of visual angle per second.\nlower = 30.\nupper = 200.\n\n# (x,y) positions of targets in pixels.\ntargets = {\n'Topleft':(673.,253.),\n'Topright':(1247.,253.),\n'Bottomleft':(673.,827.),\n'Bottomright':(1247.,827.)\n}\n\n","sub_path":"Scripts/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347186006","text":"import os\nimport pytest\nimport PyPWA.data.memory.kv\nimport numpy\n\nTEST_KV_DICT_FILE = os.path.join(os.path.dirname(__file__), \"test_docs/kv_test_data.txt\")\nTEST_KV_DICT_FILE_2 = os.path.join(os.path.dirname(__file__), \"test_docs/kv_test_data2.txt\")\n\nTEST_KV_FLOAT_FILE = os.path.join(os.path.dirname(__file__), \"test_docs/kv_test_float.txt\")\nTEST_KV_BOOL_FILE = os.path.join(os.path.dirname(__file__), \"test_docs/kv_test_bool.txt\")\n\n\ndef test_read_dict_of_arrays():\n kv_loader = PyPWA.data.memory.kv.DictOfArrays()\n\n data = kv_loader.parse(TEST_KV_DICT_FILE)\n\n numpy.testing.assert_approx_equal(data[\"ctAD\"][3], 0.915743, 5)\n numpy.testing.assert_approx_equal(data[\"QFactor\"][9], 0.762221, 5)\n assert len(list(data)) == 6\n\n\ndef test_dict_of_arrays_write_and_read():\n dictionary = {\"something\": numpy.random.rand(10), \"else\": numpy.random.rand(10)}\n\n kv_loader = PyPWA.data.memory.kv.DictOfArrays()\n\n kv_loader.write(TEST_KV_DICT_FILE_2, dictionary)\n\n loaded = kv_loader.parse(TEST_KV_DICT_FILE_2)\n\n numpy.testing.assert_array_almost_equal(dictionary[\"something\"], loaded[\"something\"])\n numpy.testing.assert_array_almost_equal(dictionary[\"else\"], loaded[\"else\"])\n os.remove(TEST_KV_DICT_FILE_2)\n\n\ndef test_list_of_floats():\n data = numpy.random.rand(50)\n kv_loader = PyPWA.data.memory.kv.ListOfFloats()\n kv_loader.write(TEST_KV_FLOAT_FILE, data)\n loaded = kv_loader.parse(TEST_KV_FLOAT_FILE)\n\n os.remove(TEST_KV_FLOAT_FILE)\n\n numpy.testing.assert_array_almost_equal(data, loaded)\n\n\ndef test_list_of_booleans():\n data = numpy.random.choice([True, False], 50)\n kv_loader = PyPWA.data.memory.kv.ListOfBooleans()\n kv_loader.write(TEST_KV_BOOL_FILE, data)\n loaded = kv_loader.parse(TEST_KV_BOOL_FILE)\n\n os.remove(TEST_KV_BOOL_FILE)\n\n numpy.testing.assert_array_almost_equal(loaded, data)\n\n\ndef test_abstract_methods():\n abstract = PyPWA.data.memory.kv.KvInterface()\n with pytest.raises(NotImplementedError):\n abstract.parse(TEST_KV_DICT_FILE)\n with pytest.raises(NotImplementedError):\n abstract.write(TEST_KV_DICT_FILE_2, {\"something\": 1})\n with pytest.raises(NotImplementedError):\n PyPWA.data.memory.kv.KvInterface.write(TEST_KV_DICT_FILE_2, {\"something\": 1})\n","sub_path":"tests/data/memory/test_kv.py","file_name":"test_kv.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"366058204","text":"\"\"\"\nThis module contains a particular implementation of the data analysis flow.\nThe analysisJob class runs a set of selection algorithms and then a set of\nanalysis algorithms for those events selected. \n\"\"\"\n\nfrom collections import Counter\n\nfrom Centella.AAlgo import AAlgo\n\nclass analysisJob(AAlgo):\n\n def __init__(self,param=False,level = 1,name='analysisJob',version=0,\n \n label=\"\",kargs={}):\n\n \"\"\"\n Basic data flow for analysis: run a collection of selection modules,\n and then a collection of analysis modules for those events selected.\n \"\"\"\n \n self.name = name\n \n AAlgo.__init__(self,param,level,self.name,0,label,kargs)\n \n self.selectors, self.analyzers = [],[]\n \n def initialize(self):\n \n \"\"\"\n Initialize selectors and analyzers. Pass centella services.\n \"\"\"\n \n self.m.log(1,'<<<--- Init method of analysisJob algorithm --->>>')\n \n self.nProcessed,self.nSelected = 0,0\n \n self.selCounter = Counter()\n\n modules = self.selectors + self.analyzers\n\n for mod in modules:\n \n if id(mod) in [id(m) for m in self.analyzers]: mt =\"Analyzer\"\n \n else: mt =\"Selector\" # not very elegant...\n \n self.m.log(1,'========= Initialize %s %s ======='%(mt,mod.label))\n\n mod.hman,mod.tman = self.hman,self.tman\n \n mod.logman, mod.docman = self.logman,self.docman \n \n mod.initialize()\n\n return\n\n def execute(self,event):\n\n \"\"\"\n Run selectors. Run analyzers if event is selected.\n \"\"\"\n \n self.nProcessed += 1\n\n for sel in self.selectors: \n \n #sel.n_evt=self.n_evt\n \n self.selCounter[sel.label+'_ana'] += 1\n\n if not sel.execute(event): return False\n \n self.selCounter[sel.label+'_sel'] += 1\n\n self.nSelected += 1\n\n for ana in self.analyzers:\n \n #sel.n_evt=self.n_evt\n\n ana.execute(event)\n\n return True\n\n def finalize(self):\n \n \"\"\"\n Finalize selectors and analyzers. Print counters.\n \"\"\"\n \n self.m.log(1,'<<<--- End method of analysisJob algorithm --->>>')\n \n self.m.log(1,'Number of events processed:',self.nProcessed)\n\n for sel in self.selectors: \n \n self.m.log(1,'========= Finalize Selector %s ======='%sel.label)\n \n self.m.log(1,'Number of events analyzed:',\n \n self.selCounter[sel.label+'_ana'])\n \n self.m.log(1,'Number of events selected:',\n \n self.selCounter[sel.label+'_sel'])\n \n sel.finalize()\n\n self.m.log(1,'====================================')\n\n self.m.log(1,'Final number of selected events:',self.nSelected)\n\n for ana in self.analyzers: \n \n self.m.log(1,'========= Finalize Analyzer %s ======='%ana.label)\n\n ana.finalize()\n\n return\n\n \n","sub_path":"Centella/analysisJob.py","file_name":"analysisJob.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"499899384","text":"\n\n\n\n\nimport math\ndef isPrime(x):\n for i in range (2, int(math.sqrt(x)) + 1):\n if x%i == 0:\n return False\n return True\ndef main():\n n = eval(input(\"Please enter a positive integer: \"))\n i = 2\n primes = 0\n twinprimes = 0\n lastprime = -1\n print(\"The first\", n, \"primes are:\")\n while (primes < n):\n if isPrime(i):\n print(i, \" \", end = '')\n if lastprime == i - 2:\n twinprimes = twinprimes + 1\n lastprime = i\n primes = primes + 1\n i = i + 1\n print()\n print(\"Amongst them there are\", twinprimes, \"twin primes.\")\nmain()","sub_path":"testFiles/primes/primes74.py","file_name":"primes74.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"514544545","text":"from tkinter import *\n\nlst=[]\n#Below should pack to class\nclass MyWindow:\n def __init__(self, wname=\"\"):\n self.root = Tk()\n self.root.title(wname)\n f1 = Frame(self.root, bg=\"grey\", borderwidth=6, relief=SUNKEN)\n f1.pack(side=LEFT, fill=\"y\")\n f2 = Frame(self.root, borderwidth=8, bg=\"grey\", relief=SUNKEN)\n f2.pack(side=TOP, fill=\"x\")\n self.text = Text(f1,font=(\"Purisa\",12))#height=6,width=70\n self.text.pack()\n l = Label(f2, text=\"Welcome to sublime text\", font=\"Helvetica 16 bold\", fg=\"red\", pady=22)\n l.pack()\n\n self.button=Button(self.root, text =\"Submit\", command=self.prn)\n self.button.pack()\n self.root.mainloop()\n\n def get_words_list(self, widget):\n \"\"\"Return list of words\"\"\"\n options=widget.get(1.0, END)# get lines into string\n #Remove spaces in list of lines\n return [i.strip() for i in options.splitlines()]\n\n def prn(self):\n \"\"\"Testing get_words_list\"\"\" \n lst.append(self.get_words_list(self.text))\n print (self.get_words_list(self.text))\n print(lst)\n\nif __name__ == \"__main__\":\n w = MyWindow(\"My window\")\n\n","sub_path":"Tkinter GUI/Taking array of input.py","file_name":"Taking array of input.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"497521491","text":"#rock paper scissors v3\n\nfrom random import randint\n\n# track the number of wins\nplayer_wins = 0\ncomputer_wins = 0\nwinning_score = 3 # adjust to the amount of wins you want before declaring the winner\n\nprint(\"WELCOME TO MY ROCK, PAPER AND SCISSORS GAME! HAVE FUN!!!\")\n\nwhile player_wins != winning_score and computer_wins != winning_score: \n print(f\"The score is: {player_wins} wins for the player. {computer_wins} wins for the computer.\") # prints the current score\n print(\"...rock...\")\n print(\"...paper...\")\n print(\"...scissors...\")\n player = input(\"Player, make your move: \").lower()\n rand_num = randint(0,2)\n if rand_num == 0:\n computer = \"rock\"\n elif rand_num == 1:\n computer = \"paper\"\n else:\n computer = \"scissors\"\n\n print(f\"Computer plays {computer}\" )\n\n if player == computer:\n print(\"It's a tie!\")\n elif player == \"rock\":\n if computer == \"scissors\":\n print(\"player wins!\")\n player_wins += 1 # adds a win to the player\n else:\n print(\"computer wins!\")\n computer_wins += 1 # adds a win to the computer\n elif player == \"paper\":\n if computer == \"rock\":\n print(\"player wins!\")\n player_wins += 1\n else:\n print(\"computer wins!\")\n computer_wins += 1\n elif player == \"scissors\":\n if computer == \"paper\":\n print(\"player wins!\")\n player_wins += 1\n else:\n print(\"computer wins!\")\n computer_wins += 1\n else:\n print(\"Please enter a valid move!\")\n\nif player_wins > computer_wins:\n print(f\"CONGRATS PLAYER, YOU WON!! {player_wins}-{computer_wins}\")\nelse:\n print(f\"COMPUTER KICKED YOUR BUTT {computer_wins}-{player_wins} ... BETTER LUCK NEXT TIME!\")","sub_path":"Projects/shifumi-Improved.py","file_name":"shifumi-Improved.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"457486758","text":"\"\"\"Tests that the brew function works\"\"\"\nimport pytest\nimport numpy as np\nimport mokapot\nfrom mokapot import LinearPsmDataset, PercolatorModel\n\nfrom ..fixtures import *\n\nnp.random.seed(42)\n\n\n@pytest.fixture\ndef svm():\n \"\"\"A simple Percolator model\"\"\"\n return PercolatorModel(train_fdr=0.05, max_iter=10)\n\n\ndef test_brew_simple(psms, svm):\n \"\"\"Test with mostly default parameters of brew\"\"\"\n results, models = mokapot.brew(psms, svm, test_fdr=0.05)\n assert isinstance(results, mokapot.confidence.LinearConfidence)\n assert len(models) == 3\n assert isinstance(models[0], PercolatorModel)\n\n\ndef test_brew_joint(psms, svm):\n \"\"\"Test that the multiple input PSM collections yield multiple out\"\"\"\n collections = [psms, psms, psms]\n results, models = mokapot.brew(collections, svm, test_fdr=0.05)\n assert len(results) == 3\n assert len(models) == 3\n\n\ndef test_brew_folds(psms, svm):\n \"\"\"Test that changing the number of folds works\"\"\"\n results, models = mokapot.brew(psms, svm, test_fdr=0.05, folds=4)\n assert isinstance(results, mokapot.confidence.LinearConfidence)\n assert len(models) == 4\n\n\ndef test_brew_test_fdr_error(psms, svm):\n \"\"\"Test that a sensible \"\"\"\n try:\n results, models = mokapot.brew(psms, svm)\n except RuntimeError as msg:\n if not str(msg).startswith(\"Failed to calibrate\"):\n raise\n\n\n# @pytest.mark.skip(reason=\"Not currently working, at least on MacOS.\")\ndef test_brew_multiprocess(psms, svm):\n \"\"\"Test that multiprocessing doesn't yield an error\"\"\"\n mokapot.brew(psms, svm, test_fdr=0.05, max_workers=3)\n","sub_path":"tests/unit_tests/test_brew.py","file_name":"test_brew.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"447584964","text":"class MathDojo:\n def __init__(self):\n self.result = 0\n def add(self, num, *nums):\n self.result += num\n for i in range(0, len(nums)):\n self.result += nums[i]\n # print(self.result)\n return self \n def subtract(self, num, *nums):\n self.result -= num\n for i in range(0, len(nums)):\n self.result -= nums[i]\n # print(self.result)\n return self\n# create an instance:\nmd = MathDojo()\n# to test:\nx = md.add(2).add(2,5,1).subtract(3,2).result\nprint(x)\t# should print 5\n# run each of the methods a few more times and check the result!\ntestadd = md.add(3).add(1,3,5).add(1,2,3,4,5,6).result\nprint(testadd)\ntestsubtract = md.subtract(30).subtract(1,3,5).subtract(1,2,3,4,5,6).result\nprint(testsubtract)","sub_path":"Python/OOP/mathdojo.py","file_name":"mathdojo.py","file_ext":"py","file_size_in_byte":728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"646253899","text":"import xlrd\ndata = xlrd.open_workbook('1.xlsx')\ntable = data.sheet_by_name('Sheet1')\nhang = table.nrows\nlie = table.ncols\n\ndef NIC(A):\n y = (-1/11)*A+(30/11)\n y = ('{:.2f}'.format(y))\n return y\ndef SJB1(B):\n y = (-1/390)*B+(730/390)\n y = ('{:.2f}'.format(y))\n return y\ndef fz(N):\n y = (-1/655)*N+(1130/655)\n y = ('{:.2f}'.format(y))\n return y\ndef my(Nm):\n y = (-1/28)*Nm+(40/28)\n y = ('{:.2f}'.format(y))\n return y\n############################################\ndef SJB11(B):\n y = (-1/390)*B+(730/390)\n y = ('{:.2f}'.format(y))\n return y\ndef fz1(N):\n y = (-1/1223)*N+(1480/1223)\n y = ('{:.2f}'.format(y))\n return y\ndef my1(Nm):\n y = (-1/28)*Nm+(40/28)\n y = ('{:.2f}'.format(y))\n return y\n########################################################3\nNIClist=[]#1\nSJB1list=[]\nfzilist=[]\nmyilist=[]\nsecond=[]#2\nSJB1list1=[]\nfzilist1=[]\nmyilist1=[]\nthird=[]#3\nfor i in range(0,hang):\n cel_B = table.cell(i,1).value\n NICi = NIC(cel_B)\n NIClist.append(eval(NICi))\n \n cel_C = table.cell(i,2).value\n SJBi = SJB1(cel_C)\n if eval(SJBi)>= 1:\n SJB1list.append(1)\n elif eval(SJBi) <= 0:\n SJB1list.append(0)\n else:\n SJB1list.append(eval(SJBi))\n\n cel_D = table.cell(i,3).value\n fzi = fz(cel_D)\n if eval(fzi)>= 1:\n fzilist.append(1)\n elif eval(SJBi) <= 0:\n fzilist.append(0)\n else:\n fzilist.append(eval(fzi))\n\n cel_E = table.cell(i,4).value\n myi = my(cel_E)\n if eval(myi)>= 1:\n myilist.append(1)\n elif eval(myi) <= 0:\n myilist.append(0)\n else:\n myilist.append(eval(myi))\n#########################################################\n cel_F = table.cell(i,5).value\n SJBi1 = SJB11(cel_F)\n if eval(SJBi1)>= 1:\n SJB1list1.append(1)\n elif eval(SJBi1) <= 0:\n SJB1list1.append(0)\n else:\n SJB1list1.append(eval(SJBi1))\n\n cel_G = table.cell(i,6).value\n fzi1 = fz1(cel_G)\n if eval(fzi1)>= 1:\n fzilist1.append(1)\n elif eval(fzi1) <= 0:\n fzilist1.append(0)\n else:\n fzilist1.append(eval(fzi1))\n\n cel_H = table.cell(i,7).value\n myi1 = my(cel_H)\n if eval(myi1)>= 1:\n myilist1.append(1)\n elif eval(myi1) <= 0:\n myilist1.append(0)\n else:\n myilist1.append(eval(myi1))\n#################################################################\n\nfor i in range(0,hang):\n secondi=min(SJB1list[i],fzilist[i],myilist[i])\n second.append(secondi)\n thirdi=min(SJB1list1[i],fzilist1[i],myilist1[i])\n third.append(thirdi)\n \n#########################################\nzhangjiao = []\nfor i in range(0,hang):\n cel_I = table.cell(i,8).value\n if cel_I == '':\n zhangjiao.append(0)\n else:\n \n if cel_I >= 19:\n zhangjiao.append(-2)\n elif cel_I < 19 :\n zhangjiao.append(0)\n#############################################\nganshe = []\nfor i in range(0,hang):\n cel_J = table.cell(i,9).value\n if cel_J == 'Y':\n ganshe.append(-2)\n else:\n ganshe.append(0)\n###############################################\nweiyi = []\nfor i in range(0,hang):\n cel_K = table.cell(i,10).value\n if cel_K == '':\n weiyi.append(0)\n else:\n \n if cel_K >= 20:\n weiyi.append(-4)\n elif cel_K < 20 :\n weiyi.append(0)\n##################################################\n\nsumend=[]\nfor i in range(0,hang):\n sum1=NIClist[i]+second[i]+third[i]+zhangjiao[i]+ganshe[i]+weiyi[i]\n if sum1 <0:\n sum1 = 0\n sum1 = ('{:.2f}'.format(sum1))\n sumend.append(sum1)\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\n\n\n \n \n","sub_path":"计算方法所有程序/第二次上机/第三题/第三题程序 (2).py","file_name":"第三题程序 (2).py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"486602325","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport threading\n\ndef run_method(arg1, arg2):\n print(\"Run...\")\n print(arg1)\n print(arg2)\n\nif __name__ == '__main__':\n t = threading.Thread(target=run_method, args=('argT1', 'argT2'))\n t.start()","sub_path":"python/demo/learning/python/common/ThreadDemo.py","file_name":"ThreadDemo.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"578853977","text":"#!/usr/bin/env python3\n\nfrom __future__ import annotations\nimport asyncio\nimport json\nimport sys\nimport enum\nimport random\n\n\nLEFT = b'Left\\n'\nRIGHT = b'Right\\n'\nFORWARD = b'Forward\\n'\n\n\nclass Direction(enum.Enum):\n \"\"\"A cardinal direction.\"\"\"\n\n NORTH = 0\n EAST = 1\n SOUTH = 2\n WEST = 3\n\n def right(self) -> Direction:\n \"\"\"Get the direction after turning right.\"\"\"\n return Direction((self.value + 1) % 4)\n\n def left(self) -> Direction:\n \"\"\"Get the direction after turning left.\"\"\"\n return Direction((self.value - 1) % 4)\n\n @classmethod\n def from_str(cls, s: str) -> cls:\n \"\"\"Create a direction from a string.\"\"\"\n if s == \"North\":\n return cls.NORTH\n if s == \"East\":\n return cls.EAST\n if s == \"South\":\n return cls.SOUTH\n if s == \"West\":\n return cls.WEST\n return None\n\n\nclass World:\n \"\"\"\n Wrap the world in a more easily-accessible manner.\n\n width: The width of the map\n height: The height of the map\n tiles: The (raw) list of tiles in the map, row-major.\n \"\"\"\n def __init__(self, data: dict):\n self.width: int = data[\"width\"]\n self.height: int = data[\"height\"]\n self.tiles: list = data[\"tiles\"]\n\n def get_tile(self, x: int, y: int) -> dict:\n \"\"\"Get the tile at the given position. Wraps around.\"\"\"\n x = x % self.width\n y = y % self.height\n index = x + self.width * y\n return self.tiles[index]\n\n def pos_in_dir(self, x: int, y: int, direction: Direction) -> (int, int):\n \"\"\"Find the position of the tile in the given direction.\"\"\"\n if direction == Direction.NORTH:\n y = y + 1\n elif direction == Direction.SOUTH:\n y = y - 1\n elif direction == Direction.EAST:\n x = x + 1\n elif direction == Direction.WEST:\n x = x - 1\n return (x % self.width, y % self.height)\n\n def tile_in_dir(self, x: int, y: int, direction: Direction) -> dict:\n \"\"\"Get the tile in the given direction from the point.\"\"\"\n return self.get_tile(*self.pos_in_dir(x, y, direction))\n\n def find_tile_pos(self, **kwargs) -> (int, int):\n \"\"\"\n Find the position of the first tile with the given qualifiers.\n\n Pass the qualifiers in as key-value pairs; for example, to find snake heads\n with my id call `world.find_tile_pos(type=\"SnakeHead\", id=my_id)`\n \"\"\"\n for x in range(self.width):\n for y in range(self.height):\n t = self.tiles[x + y * self.width]\n for key, value in kwargs.items():\n if t[key] != value:\n break\n else:\n return (x, y)\n return None\n\n\ndef safe_tile(tile) -> bool:\n \"\"\"Determines if the given tile is safe to move onto.\"\"\"\n if tile[\"type\"] == \"Blank\":\n return True\n if tile[\"type\"] == \"Doodah\":\n return True\n return False\n\n\ndef get_safe_tiles(x: int, y: int, direction: Direction, world: World) -> list:\n \"\"\"\n Get the list of safe tiles from this state.\n\n Returns pairs `(direction, choice)`.\n \"\"\"\n choices = []\n forward_tile = world.tile_in_dir(x, y, direction)\n left_tile = world.tile_in_dir(x, y, direction.left())\n right_tile = world.tile_in_dir(x, y, direction.right())\n if safe_tile(forward_tile):\n choices.append((direction, FORWARD))\n if safe_tile(left_tile):\n choices.append((direction.left(), LEFT))\n if safe_tile(right_tile):\n choices.append((direction.right(), RIGHT))\n return choices\n\ndef search_for_doodah(x: int, y: int, direction: Direction, world: World) -> bytes:\n \"\"\"Get a choice that will point to the doodah, if it exists.\"\"\"\n places_seen = [(x, y, direction)]\n to_go = []\n for next_dir, choice in get_safe_tiles(x, y, direction, world):\n next_x, next_y = world.pos_in_dir(x, y, next_dir)\n places_seen.append((next_x, next_y, next_dir))\n to_go.append((next_x, next_y, next_dir, choice))\n while len(to_go) > 0:\n x, y, direction, orig_choice = to_go.pop(0)\n tile = world.get_tile(x, y)\n if tile[\"type\"] == \"Doodah\":\n return orig_choice\n for next_dir, choice in get_safe_tiles(x, y, direction, world):\n next_x, next_y = world.pos_in_dir(x, y, next_dir)\n if (next_x, next_y, next_dir) not in places_seen:\n places_seen.append((next_x, next_y, next_dir))\n to_go.append((next_x, next_y, next_dir, orig_choice))\n return None\n\ndef decision(my_id: int, world: World) -> bytes:\n \"\"\"Pick a direction that won't kill us, if it exists\"\"\"\n # first we need to find ourselves\n pos = world.find_tile_pos(type=\"SnakeHead\", id=my_id)\n if not pos:\n print(\"Couldn't find snake head!\")\n sys.exit(1)\n x, y = pos\n direction = Direction.from_str(world.get_tile(x, y)[\"dir\"])\n\n # then we search for the doodah\n choice = search_for_doodah(x, y, direction, world)\n if choice:\n return choice\n else:\n # if there was no path, take a random safe choice if it exists\n choices = get_safe_tiles(x, y, direction, world)\n if len(choices) == 0:\n return FORWARD\n else:\n direction, choice = random.choice(choices)\n return choice\n\n\nasync def next_state(reader: asyncio.StreamReader) -> dict:\n \"\"\"Get the next line of data from the server.\"\"\"\n line = await reader.readline()\n return json.loads(line.decode(\"utf-8\"))\n\n\nasync def event_loop(my_id: int,\n reader: asyncio.StreamReader,\n writer: asyncio.StreamWriter):\n \"\"\"Run the decision loop.\"\"\"\n data = await next_state(reader)\n while data[\"state\"] == \"playing\":\n world = World(data[\"map\"])\n choice = decision(my_id, world)\n writer.write(choice)\n await writer.drain()\n data = await next_state(reader)\n print(\"Game finished! End state:\", data[\"state\"])\n\n\nasync def run_ai(host: str, port: int):\n \"\"\"Kick off the whole thing.\"\"\"\n print(\"Connecting...\")\n reader, writer = await asyncio.open_connection(host, port)\n writer.write(b'ai_search.py\\n')\n await writer.drain()\n\n print(\"Waiting for game to start...\")\n data = await next_state(reader)\n my_id = data[\"id\"]\n\n print(\"Game started! ID:\", my_id)\n await event_loop(my_id, reader, writer)\n\n\n# automatically restart the AI when its done\nwhile True:\n asyncio.run(run_ai('192.168.121.144', 3001))\n","sub_path":"client/ai_search.py","file_name":"ai_search.py","file_ext":"py","file_size_in_byte":6587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"470636327","text":"'''CSC108 Assignment 3: Social Networks'''\n\nfrom typing import List, Tuple, Dict, TextIO\n\n\ndef load_profiles(profiles_file: TextIO, person_to_friends: Dict[str, \\\n List[str]], person_to_networks: Dict[str, List[str]]) -> None:\n '''\n Update the person_to_friends dictionary and the person_to_networks\n dictionary to include data from profiles_file.\n Docstring examples not given since the result depends on input data.\n '''\n\n for line in profiles_file:\n if \",\" in line:\n key_name = get_name(line)\n\n if not key_name in person_to_friends:\n person_to_friends[key_name] = []\n if not key_name in person_to_networks:\n person_to_networks[key_name] = []\n\n line_len = len(line.strip())\n while line_len != 0:\n line = profiles_file.readline().strip()\n if \",\" in line:\n value_name = get_name(line)\n\n if not (value_name in person_to_friends[key_name]):\n person_to_friends[key_name].append(value_name)\n person_to_friends[key_name].sort()\n\n line_len = len(line.strip())\n if not \",\" in line and line_len != 0:\n if not (key_name) in person_to_networks[key_name]:\n person_to_networks[key_name].append(line)\n person_to_networks[key_name].sort()\n\n delete_empty_keys(person_to_friends, person_to_networks)\n\n\ndef get_name(line: str)-> str:\n '''\n Return a name (in the lastname-firstname form) based on the\n given a line.\n\n >>> get_name('Pritchett, Jay')\n 'Jay Pritchett'\n >>> get_name('Bale, Gareth\\n')\n 'Gareth Bale'\n >>> get_name('Ahmed, Mohammad')\n 'Mohammad Ahmed'\n >>> get_name('Dunphy, Luke\\n')\n 'Luke Dunphy'\n '''\n\n names = (line.split(\",\"))\n names[0], names[1] = names[1].strip(), names[0]\n name = str(names[0]) + \" \" + str(names[1])\n\n return name\n\n\ndef delete_empty_keys(person_to_friends: Dict[str, List[str]], \\\n person_to_networks: Dict[str, List[str]]) -> None:\n '''\n Update the person_to_friends dictionary and the\n person_to_networks dictionary by deleting all the\n empty keys (keys with no values).\n\n >>> person_to_friends = {'Jay Pritchett': ['Claire Dunphy',\\\n 'Gloria Pritchett', 'Manny Delgado'],\\\n 'Claire Dunphy': ['Jay Pritchett',\\\n 'Mitchell Pritchett', 'Phil Dunphy'],\\\n 'McDuck Scrooge': [], 'Manny Delgado':\\\n ['Gloria Pritchett', 'Jay Pritchett',\\\n 'Luke Dunphy'], 'Mitchell Pritchett':\\\n ['Cameron Tucker', 'Claire Dunphy', \\\n 'Luke Dunphy'], 'Alex Dunphy': \\\n ['Luke Dunphy'], 'Cameron Tucker':\\\n ['Gloria Pritchett', \\\n 'Mitchell Pritchett'], \\\n 'Haley Gwendolyn Dunphy': \\\n ['Dylan D-Money', 'Gilbert D-Cat'],\\\n 'Phil Dunphy': ['Claire Dunphy', \\\n 'Luke Dunphy'], 'Dylan D-Money': \\\n ['Chairman D-Cat', \\\n 'Haley Gwendolyn Dunphy'], \\\n 'Gloria Pritchett': ['Cameron Tucker',\\\n 'Jay Pritchett', 'Manny Delgado'], \\\n 'Luke Dunphy': ['Alex Dunphy', \\\n 'Manny Delgado', 'Mitchell Pritchett',\\\n 'Phil Dunphy']}\n >>> person_to_networks = {}\n >>> delete_empty_keys(person_to_friends, person_to_networks)\n >>> person_to_friends\n {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Mitchell Pritchett': ['Cameron Tucker',\\\n 'Claire Dunphy', 'Luke Dunphy'], 'Alex Dunphy': ['Luke Dunphy'],\\\n 'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],\\\n 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', \\\n 'Manny Delgado']}\n >>> person_to_networks\n {}\n >>> person_to_friends = {}\n >>> person_to_networks = {'Jay Pritchett': [], 'Claire Dunphy':\\\n ['Parent Teacher Association'], \\\n 'McDuck Scrooge': [], 'Manny Delgado':\\\n ['Chess Club'], 'Mitchell Pritchett': [],\\\n 'Alex Dunphy': [], 'Cameron Tucker': [],\\\n 'Haley Gwendolyn Dunphy': [], 'Phil Dunphy':\\\n [], 'Dylan D-Money': [], 'Gloria Pritchett':\\\n [], 'Luke Dunphy': []}\n >>> delete_empty_keys(person_to_friends, person_to_networks)\n >>> person_to_friends\n {}\n >>> person_to_networks\n {'Claire Dunphy': ['Parent Teacher Association'], \\\n 'Manny Delgado': ['Chess Club']}\n >>> person_to_friends = {'Karim Benzema': ['Claire Dunphy',\\\n 'Paul Pogba', 'Manny Delgado'],\\\n 'Gareth Bale': [], 'McDuck Scrooge': \\\n ['Moe Dunphy'], 'Manny Delgado':\\\n ['Mohmmad Ahmed'], 'Mitchell Pritchett':\\\n [], 'Alex Dunphy': [], 'Cameron Tucker':\\\n ['Omar Jay'], 'Haley Gwendolyn Dunphy': \\\n [], 'Phil Dunphy': [], 'Zlatan Ibrahimovic': \\\n [], 'Gloria Pritchett': [], \\\n 'Luke Dunphy': ['Lionel Messi']}\n >>> person_to_networks = {'Lionel Messi': [], 'Moe Dunphy': \\\n ['Parent Teacher Association'], \\\n 'McDuck Scrooge': [], 'Zlatan Ibrahimovic':\\\n ['Chess Club'], 'Mitchell Pritchett': \\\n ['Law Association'], 'Karim Benzema': \\\n ['Chess Club', 'Orchestra'], 'Cameron Tucker':\\\n ['Clown School', 'Wizard of Oz Fan Club'], \\\n 'Gareth Bale': [], 'Omar Jay': \\\n ['Real Estate Association'], 'Dylan D-Money':\\\n [], 'Mohmmad Ahmed': \\\n ['Parent Teacher Association'], 'Luke Dunphy': []}\n >>> delete_empty_keys(person_to_friends, person_to_networks)\n >>> person_to_friends\n {'Karim Benzema': ['Claire Dunphy', 'Paul Pogba', 'Manny Delgado'],\\\n 'McDuck Scrooge': ['Moe Dunphy'], 'Manny Delgado': ['Mohmmad Ahmed'],\\\n 'Cameron Tucker': ['Omar Jay'], 'Luke Dunphy': ['Lionel Messi']}\n >>> person_to_networks\n {'Moe Dunphy': ['Parent Teacher Association'], 'Zlatan Ibrahimovic':\\\n ['Chess Club'], 'Mitchell Pritchett': ['Law Association'], \\\n 'Karim Benzema': ['Chess Club', 'Orchestra'], 'Cameron Tucker':\\\n ['Clown School', 'Wizard of Oz Fan Club'], 'Omar Jay': \\\n ['Real Estate Association'], 'Mohmmad Ahmed': \\\n ['Parent Teacher Association']}\n '''\n\n friends_empty_dic = []\n netwroks_empty_dic = []\n\n for key in person_to_friends:\n key_len = len(person_to_friends[key])\n if key_len == 0:\n friends_empty_dic.append(key)\n\n for empty_key in friends_empty_dic:\n person_to_friends.pop(empty_key, None)\n\n for key in person_to_networks:\n key_len = len(person_to_networks[key])\n if key_len == 0:\n netwroks_empty_dic.append(key)\n\n for empty_key in netwroks_empty_dic:\n person_to_networks.pop(empty_key, None)\n\n\ndef get_average_friend_count(person_to_friends: Dict[str, List[str]]) -> float:\n '''\n Return the average number of friends that the keys (profiles) in the given\n person_to_friends dictionary have.\n\n >>> param = {'Jay Pritchett': ['Claire Dunphy', 'Manny Delgado'],\\\n 'Cameron Tucker': ['Claire Dunphy', 'Manny Delgado', \\\n 'Gloria Pritchett']}\n >>> get_average_friend_count(param)\n 2.5\n >>> param = {'Jay Pritchett': ['Luke Dunphy'], 'Luke Dunphy': \\\n ['Jay Pritchett']}\n >>> get_average_friend_count(param)\n 1.0\n >>> param = {'Claire Dunphy': ['Alex Dunphy', 'Manny Delgado', \\\n 'Mitchell Pritchett', 'Haley Gwendolyn Dunphy', \\\n 'Luke Dunphy', 'Gilbert D-Cat']}\n >>> get_average_friend_count(param)\n 6.0\n >>> param = {}\n >>> get_average_friend_count(param)\n 0.0\n >>> param = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett',\\\n 'Manny Delgado'], 'Claire Dunphy': ['Jay Pritchett', \\\n 'Mitchell Pritchett', 'Phil Dunphy'], 'Manny Delgado': \\\n ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], \\\n 'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy',\\\n 'Luke Dunphy'], 'Alex Dunphy': ['Luke Dunphy'], \\\n 'Cameron Tucker': ['Gloria Pritchett', \\\n 'Mitchell Pritchett'], 'Haley Gwendolyn Dunphy': \\\n ['Dylan D-Money', 'Gilbert D-Cat'],'Phil Dunphy': \\\n ['Claire Dunphy', 'Luke Dunphy'], 'Dylan D-Money': \\\n ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],\\\n 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett',\\\n 'Manny Delgado'], 'Luke Dunphy': ['Alex Dunphy',\\\n 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']}\n >>> get_average_friend_count(param)\n 2.5454545454545454\n '''\n\n num_of_profiles = 0\n num_of_friends = 0\n\n for key in person_to_friends:\n num_of_profiles += 1\n num_of_friends += len(person_to_friends[key])\n\n if num_of_profiles == 0:\n return 0.0\n\n else:\n avg_friends = (num_of_friends / num_of_profiles)\n return avg_friends\n\n\ndef get_families(person_to_friends: Dict[str, List[str]]) -> \\\n Dict[str, List[str]]:\n '''\n Return a dictionary in the form of lastnames to first names; where\n the keys are unique lastnames and the values are lists of all unique\n firstnames who share the same lastname with one another sorted\n alphabetically based on the give person_to_friends dictionary.\n The returned dictionary contains all the people in the\n person_to_friends dictionary as a key or in a value list.\n\n >>> param = {}\n >>> get_families(param)\n {}\n >>> param = {'Jay Pritchett': ['Claire Dunphy', 'Manny Delgado'],\\\n 'Alex Pritchett': ['Claire Dunphy', 'Manny Delgado']}\n >>> get_families(param)\n {'Pritchett': ['Alex', 'Jay'], 'Dunphy': ['Claire'], \\\n 'Delgado': ['Manny']}\n >>> param = {'Luke Dunphy': ['Haley Gwendolyn Dunphy'], \\\n 'Moe Dunphy': ['Luke Dunphy']}\n >>> get_families(param)\n {'Dunphy': ['Haley Gwendolyn', 'Luke', 'Moe']}\n >>> param = {'Jay Pritchett': ['Jay Pritchett'], \\\n 'Manny Delgado': ['Manny Delgado'], 'Claire Dunphy': \\\n ['Claire Dunphy']}\n >>> get_families(param)\n {'Pritchett': ['Jay'], 'Delgado': ['Manny'], 'Dunphy': ['Claire']}\n >>> param = {'Jay Pritchett': ['Claire Dunphy','Manny Delgado'], \\\n 'Cameron Tucker': ['Dylan D-Money', 'Gilbert D-Cat'], \\\n 'Cristiano Ronaldo': ['Lionel Messi', \\\n 'Zlatan Ibrahimovic', 'Diego Maradona'], 'Paul Pogba': \\\n ['David Beckham', 'Gareth Bale', 'Karim Benzema']}\n >>> get_families(param)\n {'Pritchett': ['Jay'], 'Dunphy': ['Claire'], 'Delgado': ['Manny'], \\\n 'Tucker': ['Cameron'], 'D-Money': ['Dylan'], 'D-Cat': ['Gilbert'], \\\n 'Ronaldo': ['Cristiano'], 'Messi': ['Lionel'], Ibrahimovic': ['Zlatan'], \\\n 'Maradona': ['Diego'], 'Pogba': ['Paul'], 'Beckham': ['David'], \\\n 'Bale': ['Gareth'], 'Benzema': ['Karim']}\n '''\n\n names_list = []\n\n for key in person_to_friends:\n for value in person_to_friends[key]:\n if not (key in names_list):\n names_list.append(key)\n if not (value in names_list):\n names_list.append(value)\n return get_families_helper_function(names_list)\n\n\ndef get_families_helper_function(names_list: Dict[str, List[str]]) -> \\\n Dict[str, List[str]]:\n '''\n Return a dictionary in the form of lastnames to first names by converting\n the list names_list into a dictionary where the keys are unique lastnames\n and the values are lists of all unique firstnames who share the same\n lastname with one another sorted alphabetically.\n\n >>> param = {}\n >>> get_families_helper_function(param)\n {}\n >>> param = ['Jay Pritchett', 'Claire Dunphy', 'Manny Delgado', \\\n 'Alex Pritchett']\n >>> get_families_helper_function(param)\n {'Pritchett': ['Alex', 'Jay'], 'Dunphy': ['Claire'], 'Delgado': ['Manny']}\n >>> param = ['Luke Dunphy', 'Haley Gwendolyn Dunphy', 'Moe Dunphy']\n >>> get_families_helper_function(param)\n {'Dunphy': ['Haley Gwendolyn', 'Luke', 'Moe']}\n >>> param = ['Jay Pritchett', 'Manny Delgado', 'Claire Dunphy']\n >>> get_families_helper_function(param)\n {'Pritchett': ['Jay'], 'Delgado': ['Manny'], 'Dunphy': ['Claire']}\n >>> param = ['Jay Pritchett', 'Claire Dunphy', 'Manny Delgado', \\\n 'Cameron Tucker', 'Dylan D-Money', 'Gilbert D-Cat', \\\n 'Cristiano Ronaldo', 'Lionel Messi', 'Zlatan Ibrahimovic', \\\n 'Diego Maradona', 'Paul Pogba', 'David Beckham', \\\n 'Gareth Bale', 'Karim Benzema']\n >>> get_families_helper_function(param)\n {'Pritchett': ['Jay'], 'Dunphy': ['Claire'], 'Delgado': ['Manny'], \\\n 'Tucker': ['Cameron'], 'D-Money': ['Dylan'], 'D-Cat': ['Gilbert'], \\\n 'Ronaldo': ['Cristiano'], 'Messi': ['Lionel'], Ibrahimovic': ['Zlatan'], \\\n 'Maradona': ['Diego'], 'Pogba': ['Paul'], 'Beckham': ['David'], \\\n 'Bale': ['Gareth'], 'Benzema': ['Karim']}\n '''\n\n families_dic = {}\n\n for name in names_list:\n space_index = name.rfind(\" \")\n last_name = name[space_index: len(name)].strip()\n\n for name in names_list:\n space_index = name.rfind(\" \")\n last_name = name[space_index: len(name)].strip()\n\n if not (last_name in list(families_dic)):\n families_dic[last_name] = []\n\n for key in families_dic:\n if last_name in key:\n families_dic[key].append(name[0:space_index].strip())\n families_dic[last_name].sort()\n\n return families_dic\n\n\ndef invert_network(person_to_networks: Dict[str, List[str]]) \\\n -> Dict[str, List[str]]:\n\n '''\n Return a dictionary in the form of network to people based on the\n given person_to_networks dictionary. The keys of the dictionary\n are unique network names and the values are alphabetically sorted\n lists of people who belong to the network in firstname-lastname format.\n\n >>> param = {}\n >>> invert_network(param)\n {}\n >>> param = {'Claire Dunphy': ['Parent Teacher Association'], \\\n 'Manny Delgado': ['Chess Club'], 'Mitchell Pritchett': \\\n ['Law Association'], 'Alex Dunphy': ['Chess Club', \\\n 'Orchestra'], 'Cameron Tucker': ['Clown School', \\\n 'Wizard of Oz Fan Club'], 'Phil Dunphy': \\\n ['Real Estate Association'], 'Gloria Pritchett': \\\n ['Parent Teacher Association']}\n >>> invert_network(param)\n {'Parent Teacher Association': ['Claire Dunphy', 'Gloria Pritchett'], \\\n 'Chess Club': ['Alex Dunphy', 'Manny Delgado'], 'Law Association': \\\n ['Mitchell Pritchett'], 'Orchestra': ['Alex Dunphy'], 'Clown School': \\\n ['Cameron Tucker'], 'Wizard of Oz Fan Club': ['Cameron Tucker'], \\\n 'Real Estate Association': ['Phil Dunphy']} \\\n >>> param = {'Manny Delgado': ['Chess Club'], 'Cameron Tucker': \\\n ['Clown School', 'Wizard of Oz Fan Club'], 'Gloria Pritchett':\\\n ['Parent Teacher Association'], 'moe ahmed': \\\n ['Parent Teacher Association', 'Law Association', 'Chess Club',\\\n 'Orchestra', 'Clown School', 'Wizard of Oz Fan Club', \\\n 'Real Estate Association']}\n >>> invert_network(param)\n {'Chess Club': ['Manny Delgado', 'moe ahmed'], 'Clown School': \\\n ['Cameron Tucker', 'moe ahmed'], 'Wizard of Oz Fan Club': \\\n ['Cameron Tucker', 'moe ahmed'], 'Parent Teacher Association': \\\n ['Gloria Pritchett', 'moe ahmed'], 'Law Association': ['moe ahmed'], \\\n 'Orchestra': ['moe ahmed'], 'Real Estate Association': ['moe ahmed']} \\\n >>> param = {'Manny Delgado': ['Chess Club'], 'Cameron Tucker': \\\n ['Clown School'], 'Gloria Pritchett': ['Parent Teacher Association']} \\\n >>> invert_network(param)\n {'Chess Club': ['Manny Delgado'], 'Clown School': ['Cameron Tucker'], \\\n 'Parent Teacher Association': ['Gloria Pritchett']}\n >>> param = {'Manny Delgado': ['Chess Club']}\n >>> invert_network(param)\n {'Chess Club': ['Manny Delgado']}\n '''\n\n network_names = []\n network_to_people = {}\n for key in person_to_networks:\n if not key in network_names:\n network_names.append(person_to_networks[key])\n\n for index in network_names:\n for network in index:\n if not network in network_to_people:\n network_to_people[network] = []\n\n for network in network_to_people:\n for key in person_to_networks:\n if network in person_to_networks[key]:\n network_to_people[network].append(key)\n network_to_people[network].sort()\n\n return network_to_people\n\n\ndef get_friends_of_friends(person_to_friends: Dict[str, List[str]], \\\n person: str) -> List[str]:\n '''\n Based on the given person_to_friends dictionary and the person\n (in the firstname-lastname form). Return a list (sorted in\n alphabetical order) of people's names in the form of firstname-lastname\n of people who are friends of the person's friends. The returned\n list will not contain the person and the friend of a friend\n will be listed in the returned list once for each mutual friend.\n\n >>> param = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Jay Pritchett', \\\n 'Mitchell Pritchett', 'Phil Dunphy'], 'Manny Delgado': \\\n ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], \\\n 'Alex Dunphy': ['Luke Dunphy'], 'Gloria Pritchett': \\\n ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado']}\n >>> get_friends_of_friends(param , 'Jay Pritchett')\n ['Cameron Tucker', 'Gloria Pritchett', 'Luke Dunphy', \\\n 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']\n >>> param = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Jay Pritchett', \\\n 'Mitchell Pritchett', 'Phil Dunphy', 'moe ah'],'Manny Delgado':\\\n ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy', 'moe ah'],\\\n 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', \\\n 'Manny Delgado', 'moe ah']}\n >>> get_friends_of_friends(param , 'Jay Pritchett')\n ['Cameron Tucker', 'Gloria Pritchett', 'Luke Dunphy', 'Manny Delgado', \\\n 'Mitchell Pritchett', 'Phil Dunphy', 'moe ah', 'moe ah', 'moe ah']\n >>> param = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Claire Dunphy', \\\n 'Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy', \\\n 'moe ah'],'Manny Delgado': ['Gloria Pritchett', \\\n 'Jay Pritchett', 'Luke Dunphy', 'moe ah'], 'Gloria Pritchett':\\\n ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado', 'moe ah']}\n >>> get_friends_of_friends(param, 'Claire Dunphy')\n ['Gloria Pritchett', 'Jay Pritchett', 'Manny Delgado', \\\n 'Mitchell Pritchett', 'Phil Dunphy', 'moe ah']\n >>> param = {'Claire Dunphy': ['Claire Dunphy', 'Jay Pritchett', \\\n 'Mitchell Pritchett', 'Phil Dunphy', 'moe ah']}\n >>> get_friends_of_friends(param, 'Claire Dunphy')\n ['Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy', 'moe ah']\n '''\n\n friends_of_friends = []\n friends_lst = []\n final_lst = []\n for key in person_to_friends:\n if key == person:\n for value in person_to_friends[key]:\n if not (person_to_friends[key] in friends_lst):\n friends_lst.append(value)\n\n for friend in friends_lst:\n for x in person_to_friends:\n if friend == x:\n for value in person_to_friends[x]:\n friends_of_friends.append(value)\n friends_of_friends.sort()\n\n for index in friends_of_friends:\n if index != person:\n final_lst.append(index)\n final_lst.sort()\n\n return final_lst\n\n\ndef same_lname_point_and_sorting(person: str, person_to_friends: Dict \\\n [str, List[str]], potential_friends: \\\n List[str], recommendation_dic: \\\n Dict[str, List[str]]) \\\n -> List[Tuple[str, int]]:\n '''\n Return a list of tuples of friend recommendations (sorted from\n highest to lowest score and alphabetically if the scores are\n equal) for the selected person based on the provided\n potential_friends list and the person_to_friends, person_to_networks,\n and the recommendation_dic dictionaries. The first element of the\n returned tuple is a potential friend's name (in the firstname-lastname\n form) and the second element is their score, a person is included\n in the list if and only if their score is greater than zero.\n\n >>> same_lname_point_and_sorting('Lionel Messi',{'Lionel Messi': \\\n ['Cristiano Ronaldo'], 'Robert Luis' : \\\n ['Cristiano Ronaldo']}, ['Robert Luis'], \\\n {'Robert Luis': [1]})\n [('Robert Luis', 1)]\n >>> same_lname_point_and_sorting('Robert Luis',{'Lionel Messi': \\\n ['Cristiano Ronaldo'], 'Robert Luis': \\\n ['Cristiano Ronaldo']}, ['Lionel Messi'],\\\n {'Lionel Messi': [1]})\n [('Lionel Messi', 1)]\n >>> x = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Mitchell Pritchett', \\\n 'Jay Pritchett', 'Phil Dunphy'], 'Manny Delgado': \\\n ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], \\\n 'Mitchell Pritchett': ['Cameron Tucker', 'Gloria Pritchett',\\\n 'Manny Delgado','Claire Dunphy', 'Luke Dunphy'], 'Alex Dunphy':\\\n ['Luke Dunphy'], 'Cameron Tucker': ['Gloria Pritchett', \\\n 'Mitchell Pritchett'], 'Haley Gwendolyn Dunphy': ['Dylan D-Money',\\\n 'Gilbert D-Cat'], 'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'],\\\n 'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'], \\\n 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', \\\n 'Manny Delgado'], 'Luke Dunphy': ['Manny Delgado','Phil Dunphy'], \\\n 'Mohammad Ahmed': ['Claire Dunphy']}\n >>> potential_friends = ['Alex Dunphy', 'Cameron Tucker', 'Chairman D-Cat',\\\n 'Dylan D-Money', 'Gilbert D-Cat', \\\n 'Haley Gwendolyn Dunphy', 'Luke Dunphy', \\\n 'Mitchell Pritchett', 'Mohammad Ahmed', \\\n 'Phil Dunphy']\n >>> recommendation_dic = {'Alex Dunphy': [1, 1], 'Cameron Tucker': [1, 1, 1], \\\n 'Chairman D-Cat': [], 'Dylan D-Money': [], 'Gilbert D-Cat': [], \\\n 'Haley Gwendolyn Dunphy': [], 'Luke Dunphy': [1], \\\n 'Mitchell Pritchett': [1, 1, 1], 'Mohammad Ahmed':\\\n [1], 'Phil Dunphy': [1, 1]}\n >>> same_lname_point_and_sorting('Jay Pritchett', x, potential_friends, \\\n recommendation_dic)\n [('Mitchell Pritchett', 4), ('Cameron Tucker', 3), ('Alex Dunphy', 2), \\\n ('Phil Dunphy', 2), ('Luke Dunphy', 1), ('Mohammad Ahmed', 1)]\n '''\n\n final = []\n pers_first_name = person[0:person.rfind(\" \")].strip()\n last_names = get_families(person_to_friends)\n for key in last_names:\n for potenial in potential_friends:\n space_index = potenial.rfind(\" \")\n first_name = potenial[0:space_index].strip()\n dic_len = len(recommendation_dic[potenial])\n if first_name in last_names[key] and pers_first_name \\\n in last_names[key] and dic_len != 0:\n recommendation_dic[potenial].append(1)\n for index in recommendation_dic:\n dic_len = len(recommendation_dic[index])\n if dic_len > 0:\n tup = (index, dic_len)\n final.append(tup)\n\n # This part of the code was taken from the course notes provided by professor\n # Samir Hamdi\n for tup_values in range(len(final)-1, 0, -1):\n for index in range(tup_values):\n if final[index][1] < final[index+1][1]:\n final[index], final[index+1] = final[index+1], final[index]\n return final\n\n\ndef mutual_friends_newtworks_points(person: str, person_to_friends: \\\n Dict[str, List[str]], person_to_networks: \\\n Dict[str, List[str]], potential_friends: \\\n List[str], recommendation_dic: Dict[str,\\\n List[str]])-> List[Tuple[str, int]]:\n '''\n Return the result of sendig the person, person_to_friends list,\n potential_friends list and the recommendation_dic dcitionary\n (after of adding a point to the potential friend's score in\n the dic dictionary if they have any mutual friends or if\n they belong to the same network network as the person\n based on the given person_to_friends and person_to_networks\n dictionaries) to the same_lname_point_and_sorting function.\n\n >>> x = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Mitchell Pritchett', \\\n 'Jay Pritchett', 'Phil Dunphy'], 'Manny Delgado': \\\n ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], \\\n 'Mitchell Pritchett': ['Cameron Tucker', 'Gloria Pritchett',\\\n 'Manny Delgado','Claire Dunphy', 'Luke Dunphy'], 'Alex Dunphy':\\\n ['Luke Dunphy'], 'Cameron Tucker': ['Gloria Pritchett', \\\n 'Mitchell Pritchett'], 'Haley Gwendolyn Dunphy': ['Dylan D-Money',\\\n 'Gilbert D-Cat'], 'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'],\\\n 'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'], \\\n 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', \\\n 'Manny Delgado'], 'Luke Dunphy': ['Manny Delgado','Phil Dunphy'], \\\n 'Mohammad Ahmed': ['Claire Dunphy']}\n >>> z = {'Claire Dunphy': ['Parent Teacher Association'], 'Manny Delgado':\\\n ['Chess Club'], 'Mitchell Pritchett': ['Law Association'], \\\n 'Alex Dunphy': ['Chess Club', 'Orchestra'], 'Cameron Tucker': \\\n ['Clown School', 'Wizard of Oz Fan Club'], 'Phil Dunphy': \\\n ['Real Estate Association'], 'Gloria Pritchett': \\\n ['Parent Teacher Association'], 'Jay Pritchett':\\\n ['Parent Teacher Association','Chess Club','Orchestra', \\\n 'Clown School', 'Wizard of Oz Fan Club','Real Estate Association']}\n >>> potential_friends = ['Alex Dunphy', 'Cameron Tucker', 'Chairman D-Cat',\\\n 'Dylan D-Money', 'Gilbert D-Cat', \\\n 'Gloria Pritchett', 'Haley Gwendolyn Dunphy', \\\n 'Luke Dunphy', 'Manny Delgado', 'Mohammad Ahmed']\n >>> recommendation_dic = {'Alex Dunphy': [], 'Cameron Tucker': [], \\\n 'Chairman D-Cat': [], 'Dylan D-Money': [], \\\n 'Gilbert D-Cat': [], 'Gloria Pritchett': [], \\\n 'Haley Gwendolyn Dunphy': [], 'Luke Dunphy': \\\n [], 'Manny Delgado': [], 'Mohammad Ahmed': []}\n >>> mutual_friends_newtworks_points('Claire Dunphy', x, z, \\\n potential_friends, recommendation_dic)\n [('Gloria Pritchett', 2), ('Luke Dunphy', 2), ('Cameron Tucker', 1), \\\n ('Manny Delgado', 1)]\n\n >>> x = {'Lionel Messi': ['Cristiano Ronaldo'], \\\n 'Robert Luis' : ['Cristiano Ronaldo']}\n >>> z = {}\n >>> potential_friends = ['Cristiano Ronaldo', 'Lionel Messi']\n >>> recommendation_dic = {'Cristiano Ronaldo': [], 'Lionel Messi': []}\n >>> mutual_friends_newtworks_points('Robert Luis', x, z, potential_friends,\\\n recommendation_dic)\n [('Lionel Messi', 1)]\n >>> x = {'George Messi': ['Cristiano Ronaldo', 'Mohammad Ali'], \\\n 'Robert Luis' : ['William Ronaldo', 'Mohammad Ali', \\\n 'Cristiano Ronaldo']}\n >>> z = {}\n >>> potential_friends = ['George Messi']\n >>> recommendation_dic = {'George Messi': []}\n >>> mutual_friends_newtworks_points('Robert Luis', x, z, potential_friends,\\\n recommendation_dic)\n [('George Messi', 2)]\n '''\n\n friends_lst = []\n\n for key in person_to_friends:\n if key == person:\n for value in person_to_friends[key]:\n if not (person_to_friends[key] in friends_lst):\n friends_lst.append(value)\n\n for key in person_to_friends:\n if key in potential_friends:\n for index in person_to_friends[key]:\n if index in friends_lst:\n recommendation_dic[key].append(1)\n\n network_to_ppl = invert_network(person_to_networks)\n\n for key in network_to_ppl:\n for potenial in potential_friends:\n if potenial in network_to_ppl[key]and person in network_to_ppl[key]:\n recommendation_dic[potenial].append(1)\n\n return same_lname_point_and_sorting(person, person_to_friends, \\\n potential_friends, recommendation_dic)\n\n\ndef get_potential_friends(person: str, person_to_friends: Dict[str, List[str]],\\\n person_to_networks: Dict[str, List[str]], friends_lst:\\\n List[str]) -> List[Tuple[str, int]]:\n '''\n Return the result of sending the person, person_to_friends\n and person_to_networks dictionaries and the friends_lst as well\n as creating and sending a dictionary with all the person's\n potential friends as keys based the friends_lst list (a list of all the\n person's friends in the firstname-lastname form) and the given\n person_to_friends dictionary, to the mutual_friends_newtworks_points\n function.\n\n >>> x = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Mitchell Pritchett', \\\n 'Jay Pritchett', 'Phil Dunphy'], 'Manny Delgado': \\\n ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], \\\n 'Mitchell Pritchett': ['Cameron Tucker', 'Gloria Pritchett', \\\n 'Manny Delgado','Claire Dunphy', 'Luke Dunphy'], 'Alex Dunphy': \\\n ['Luke Dunphy'], 'Cameron Tucker': ['Gloria Pritchett', \\\n 'Mitchell Pritchett'], 'Haley Gwendolyn Dunphy': ['Dylan D-Money',\\\n 'Gilbert D-Cat'], 'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'],\\\n 'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'], \\\n 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', \\\n 'Manny Delgado'], 'Luke Dunphy': ['Manny Delgado','Phil Dunphy'], \\\n 'Mohammad Ahmed': ['Claire Dunphy']}\n >>> z = {'Claire Dunphy': ['Parent Teacher Association'], 'Manny Delgado':\\\n ['Chess Club'], 'Mitchell Pritchett': ['Law Association'], \\\n 'Alex Dunphy': ['Chess Club', 'Orchestra'], 'Cameron Tucker': \\\n ['Clown School', 'Wizard of Oz Fan Club'], 'Phil Dunphy': \\\n ['Real Estate Association'], 'Gloria Pritchett': \\\n ['Parent Teacher Association'], 'Jay Pritchett': \\\n ['Parent Teacher Association','Chess Club','Orchestra', \\\n 'Clown School', 'Wizard of Oz Fan Club','Real Estate Association']}\n >>> get_potential_friends('Jay Pritchett', x, z, ['Claire Dunphy', \\\n 'Gloria Pritchett', 'Manny Delgado'])\n [('Mitchell Pritchett', 4), ('Cameron Tucker', 3), ('Alex Dunphy', 2), \\\n ('Phil Dunphy', 2), ('Luke Dunphy', 1), ('Mohammad Ahmed', 1)]\n >>> get_potential_friends('Lionel Messi', {'Lionel Messi': \\\n ['Cristiano Ronaldo'], 'Robert Messi' : \\\n ['Cristiano Ronaldo']}, {}, ['Cristiano Ronaldo'])\n [('Robert Messi', 2)]\n >>> get_potential_friends('Robert Luis', {'Lionel Messi': \\\n ['Cristiano Ronaldo'], 'Robert Luis' : \\\n ['Cristiano Ronaldo']}, {}, ['Cristiano Ronaldo'])\n [('Lionel Messi', 1)]\n '''\n\n recommendation_dic = {}\n potential_friends = []\n\n for name in person_to_friends:\n if not (name in friends_lst) and not (name in potential_friends)\\\n and name != person:\n potential_friends.append(name)\n potential_friends.sort()\n for value in person_to_friends[name]:\n if not (value in friends_lst) and not \\\n (value in potential_friends) and value != person:\n potential_friends.append(value)\n potential_friends.sort()\n\n for index in potential_friends:\n if not (index in recommendation_dic):\n recommendation_dic[index] = []\n\n return mutual_friends_newtworks_points(person, person_to_friends, \\\n person_to_networks, \\\n potential_friends, recommendation_dic)\n\n\ndef make_recommendations(person: str, person_to_friends: Dict[str, List[str]],\\\n person_to_networks: Dict[str, List[str]]) \\\n -> List[Tuple[str, int]]:\n '''\n Return a list of tuples of friend recommendations (sorted from highest\n to lowest score and alphabetically if the scores are equal) for the\n selected person based on the provided person_to_friends and\n person_to_networks dictionaries. The first element of the returned\n tuple is a potential friend's name (in the firstname-lastname form)\n and the second element is their score, a person is included in the\n list if and only if their score is greater than zero.\n\n >>> make_recommendations('Robert Ronald',{},{})\n []\n >>> x = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Jay Pritchett', \\\n 'Mitchell Pritchett', 'Phil Dunphy'], 'Manny Delgado': \\\n ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], \\\n 'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy', \\\n 'Luke Dunphy'], 'Alex Dunphy': ['Luke Dunphy'], 'Cameron Tucker': \\\n ['Gloria Pritchett', 'Mitchell Pritchett'], \\\n 'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'], \\\n 'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'], 'Dylan D-Money': \\\n ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'], 'Gloria Pritchett': \\\n ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado'], \\\n 'Luke Dunphy': ['Alex Dunphy', 'Manny Delgado', \\\n 'Mitchell Pritchett', 'Phil Dunphy']}\n >>> z = {'Claire Dunphy': ['Parent Teacher Association'], \\\n 'Manny Delgado': ['Chess Club'], 'Mitchell Pritchett': \\\n ['Law Association'], 'Alex Dunphy': ['Chess Club', 'Orchestra'], \\\n 'Cameron Tucker': ['Clown School', 'Wizard of Oz Fan Club'], \\\n 'Phil Dunphy': ['Real Estate Association'], 'Gloria Pritchett': \\\n ['Parent Teacher Association']}\n >>> make_recommendations('Claire Dunphy',x, z)\n [('Luke Dunphy', 3), ('Gloria Pritchett', 2), ('Cameron Tucker', 1), \\\n ('Manny Delgado', 1)]\n >>> make_recommendations('Lionel Messi',{'Lionel Messi': \\\n ['Cristiano Ronaldo'], 'Robert Messi': \\\n ['Cristiano Ronaldo']}, {})\n [('Robert Messi', 2)]\n >>> make_recommendations('Lionel Messi',{'Lionel Messi': \\\n ['Cristiano Ronaldo'], 'Robert Luis': \\\n ['Cristiano Ronaldo']}, {})\n [('Robert Luis', 1)]\n >>> x = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Claire Dunphy', \\\n 'Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy', \\\n 'moe ah'],'Manny Delgado': ['Gloria Pritchett', \\\n 'Jay Pritchett', 'Luke Dunphy', 'moe ah'], 'Gloria Pritchett': \\\n ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado', 'moe ah']}\n >>> z = {'Manny Delgado': ['Chess Club'], 'Cameron Tucker': \\\n ['Clown School', 'Wizard of Oz Fan Club'], 'Gloria Pritchett': \\\n ['Parent Teacher Association'], 'moe ahmed': \\\n ['Parent Teacher Association', 'Law Association', 'Chess Club', \\\n 'Orchestra', 'Clown School', 'Wizard of Oz Fan Club', \\\n 'Real Estate Association']}\n >>> make_recommendations('Manny Delgado', x, z)\n [('Claire Dunphy', 2)]\n >>> x = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Mitchell Pritchett', \\\n 'Jay Pritchett', 'Phil Dunphy'], 'Manny Delgado': \\\n ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'], \\\n 'Mitchell Pritchett': ['Cameron Tucker', 'Gloria Pritchett',\\\n 'Manny Delgado','Claire Dunphy', 'Luke Dunphy'], 'Alex Dunphy':\\\n ['Luke Dunphy'], 'Cameron Tucker': ['Gloria Pritchett', \\\n 'Mitchell Pritchett'], 'Haley Gwendolyn Dunphy': \\\n ['Dylan D-Money', 'Gilbert D-Cat'], 'Phil Dunphy': \\\n ['Claire Dunphy', 'Luke Dunphy'], 'Dylan D-Money': \\\n ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'], \\\n 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', \\\n 'Manny Delgado'], 'Luke Dunphy': ['Manny Delgado','Phil Dunphy'], \\\n 'Mohammad Ahmed': ['Claire Dunphy']}\n >>> z = {'Claire Dunphy': ['Parent Teacher Association'], 'Manny Delgado': \\\n ['Chess Club'], 'Mitchell Pritchett': ['Law Association'], \\\n 'Alex Dunphy': ['Chess Club', 'Orchestra'], 'Cameron Tucker': \\\n ['Clown School', 'Wizard of Oz Fan Club'], 'Phil Dunphy': \\\n ['Real Estate Association'], 'Gloria Pritchett': \\\n ['Parent Teacher Association'], 'Jay Pritchett':\\\n ['Parent Teacher Association','Chess Club','Orchestra', \\\n 'Clown School', 'Wizard of Oz Fan Club','Real Estate Association']}\n >>> make_recommendations('Jay Pritchett', x, z)\n [('Mitchell Pritchett', 4), ('Cameron Tucker', 3), ('Alex Dunphy', 2), \\\n ('Phil Dunphy', 2), ('Luke Dunphy', 1), ('Mohammad Ahmed', 1)]\n '''\n\n friends_lst = []\n\n for key in person_to_friends:\n if key == person:\n for value in person_to_friends[key]:\n if not (person_to_friends[key] in friends_lst):\n friends_lst.append(value)\n return get_potential_friends(person, person_to_friends,\\\n person_to_networks, friends_lst)\n\n\ndef is_network_connected(person_to_friends: Dict[str, List[str]]) -> bool:\n '''\n Return whether the social network based on the given\n person_to_friends dictionary is connected. A network\n is connected if and only if every key in the dictionary\n is linked, through a sequence of friends, to every\n other person in the dictionary.\n\n >>> param = {}\n >>> is_network_connected(param)\n True\n >>> param ={'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Jay Pritchett', \\\n 'Mitchell Pritchett', 'Phil Dunphy'], 'Manny Delgado':\\\n ['Gloria Pritchett', 'Jay Pritchett', 'Luke Dunphy'],\\\n 'Mitchell Pritchett': ['Cameron Tucker', 'Claire Dunphy',\\\n 'Luke Dunphy'], 'Alex Dunphy': ['Luke Dunphy'], \\\n 'Cameron Tucker': ['Gloria Pritchett', 'Mitchell Pritchett'],\\\n 'Haley Gwendolyn Dunphy': ['Dylan D-Money', 'Gilbert D-Cat'],\\\n 'Phil Dunphy': ['Claire Dunphy', 'Luke Dunphy'], \\\n 'Dylan D-Money': ['Chairman D-Cat', 'Haley Gwendolyn Dunphy'],\\\n 'Gloria Pritchett': ['Cameron Tucker', 'Jay Pritchett', \\\n 'Manny Delgado'], 'Luke Dunphy': ['Alex Dunphy', \\\n 'Manny Delgado', 'Mitchell Pritchett', 'Phil Dunphy']}\n >>> is_network_connected(param)\n False\n >>> param = {'Jay Pritchett': ['Claire Dunphy', 'Gloria Pritchett', \\\n 'Manny Delgado'], 'Claire Dunphy': ['Claire Dunphy', \\\n 'Jay Pritchett', 'Mitchell Pritchett', 'Phil Dunphy', \\\n 'moe ah'],'Manny Delgado': ['Gloria Pritchett', \\\n 'Jay Pritchett', 'Luke Dunphy', 'moe ah'], 'Gloria Pritchett': \\\n ['Cameron Tucker', 'Jay Pritchett', 'Manny Delgado', 'moe ah']}\n >>> is_network_connected(param)\n True\n >>> param = {'moe ahmed': ['Karim Benzema']}\n >>> is_network_connected(param)\n True\n >>> param = {'Lionel Messi': ['Cristiano Ronaldo'], 'Robert Luis': \\\n ['Cristiano Ronaldo']}\n >>> is_network_connected(param)\n False\n '''\n keys_lst = []\n connected_ppl_lst = []\n connected = True\n for key in person_to_friends:\n if not (person_to_friends in keys_lst):\n keys_lst.append(key)\n\n # If the key has on;y one key then the network is connected\n # return True\n if len(keys_lst) == 1:\n return True\n\n for key_name in keys_lst:\n for key in person_to_friends:\n if key_name == key:\n for value in person_to_friends[key]:\n if value in keys_lst and not (value in connected_ppl_lst):\n connected_ppl_lst.append(value)\n\n for name in connected_ppl_lst:\n for key1 in person_to_friends:\n if key1 == name:\n friends_of_friends_lst = get_friends_of_friends\\\n (person_to_friends, name)\n for index in friends_of_friends_lst:\n if index in keys_lst and not (index in \\\n connected_ppl_lst):\n connected_ppl_lst.append(index)\n\n for value1 in person_to_friends[key1]:\n friends_of_friends_lst = get_friends_of_friends\\\n (person_to_friends, value1)\n for index2 in friends_of_friends_lst:\n if index2 in keys_lst and not (index2 in \\\n connected_ppl_lst):\n connected_ppl_lst.append(index2)\n\n for name2 in connected_ppl_lst:\n friends_of_friends_lst = get_friends_of_friends \\\n (person_to_friends, name2)\n for index2 in friends_of_friends_lst:\n if name2 in keys_lst and not (name2 in \\\n connected_ppl_lst):\n connected_ppl_lst.append(name2)\n\n if len(connected_ppl_lst) != len(keys_lst):\n connected = False\n else:\n del connected_ppl_lst[:]\n\n return (connected)\n\n\n##if __name__ == '__main__':\n## # Do not move this code out of the __main__ block, and do not add any other\n## # testing code outside of the __main__ block.\n## import doctest\n## doctest.testmod()\n","sub_path":"network_functions.py","file_name":"network_functions.py","file_ext":"py","file_size_in_byte":44634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"117115527","text":"#assignment 1 question 2\n\nfrom a1_q1 import euclidian_distance ;\nimport tensorflow as tf;\n\n\n#given a dm with the distances with a set of all test and training points, return a responsibility matrix\n#of the k nearest neighbours\n\n#dm = pairwise distance matrix (n1xn2) of distances between all training points and all test points\n#n1 is the number of test points. n2 is the number of training points\n#k = number of nearest neighbours you want\n#return value = responsibility matrix\ndef responsibility(distanceMatrix, k):\n \n \n dm = tf.negative(distanceMatrix ); #flip all values to find closest neighbours\n \n #create a responsibility vector \n #we're going to flatten out the responsibility matrix so we can use scatter_update on it\n #we also have to flatten the indices of the k nearest neighbours (in indices)\n\n values, indices = tf.nn.top_k(dm, k);\n \n dmNumCol = dm.shape[1];\n indNumRow = indices.shape[0];\n \n #we need to add offsets to the indices to account for the rows\n #adding number of columns in dm * row number of index to each each\n offsets = tf.range(start = 0, limit = dmNumCol*indNumRow, delta = dmNumCol);\n offsets = tf.expand_dims(offsets, 0);\n offsets = tf.transpose(offsets); \n indices = indices + offsets;\n \n #flatten indices so i can scatter update\n flatIndices = tf.reshape(indices, [indices.shape[0]*indices.shape[1]]); \n \n #create responsibility values = 1/k\n resVal = tf.constant(1.0,tf.float32)/tf.constant(k,tf.float32);\n flatRes = tf.fill([flatIndices.shape[0]],resVal);\n \n size = dm.shape[0]*dm.shape[1];\n \n #create the zeros of the responsibility vector\n ref = tf.Variable(tf.zeros([size],tf.float32));\n \n with tf.Session() as session:\n session.run(tf.global_variables_initializer());#allows us to use tf.variable \n resVec = tf.scatter_update(ref,flatIndices, flatRes); \n \n #print(\"dimension matrix\");\n #print(session.run(dm));\n \n #print(\"indices\");\n #print(session.run(indices));\n \n #print(\"flat indices\");\n #print(session.run(flatIndices));\n #print(\"Responsibility Matrix\");\n resVec = tf.reshape(resVec, [dm.shape[0], dm.shape[1]]);\n print(session.run(resVec));\n return(resVec);\n###########################################################################\n\n\n#ASSUMING YOU ONLY SENT ROWS/COLUMNS THAT WERE VALID.\n#DON'T SEND EVERY TARGET VALUE IF YOU'RE TRYING TO GET THE PREDICTIONS FOR JUST TEST POINTS\n\n#targets = the target value of the test points. a qx1\n#responsibility matrix = rxq\n#q is the number of test points. r is the number of training points\n#result = returns the estimated y values given the responsibility matrix of a set of test points as a col vector\ndef calculate_predictions(targets, resMat):\n \n yhats = tf.multiply(resMat,targets);#multiplies close targets by 1/k and sets others to 0 \n yhats = tf.reduce_sum(yhats,1);#add the averaged values together\n yhats = tf.transpose(yhats);\n return(yhats);\n\n###########################################################################\n\n#predictions is a col vector\n#targets is a row vector\n#returns the mean squared error \ndef mse_loss(predictions,targets):\n\n x = tf.transpose(predictions);\n d = tf.transpose(targets);\n distance = euclidian_distance(x, z);#squared error\n mse = distance/2/x.shape[1];#mean squared error\n\nif __name__ == \"__main__\":\n \n test = [[0,0,0], [9,9,9]];\n training = [[0,0,0],[3,3,3], [2,2,2] ,[1,1,1],];\n \n #print(test);\n #print(dm);\n \n\n dm = euclidian_distance(test, training); \n result = responsibility(dm,2);\n \n # print(result);\n","sub_path":"A1/a1_q2.py","file_name":"a1_q2.py","file_ext":"py","file_size_in_byte":3710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"357576541","text":"n = int(input()) #도로 크기\nw = int(input()) #사건 수\ncop1 = [1,1] #경찰1 위치\ncop2 = [n,n] #경찰2 위치\nlocation = [list(map(int,input().split())) for _ in range(w)] #사건 위치\nwho = [] #사건 담당 경찰\nsum = 0 #총 거리\nfor i in range(3) : #총거리 최솟값, 사건 담당 경찰\n cop1_length = abs(cop1[0]-location[i][0]) + abs(cop1[1]-location[i][1])\n cop2_length = abs(cop2[0]-location[i][0]) + abs(cop2[1]-location[i][1])\n if cop1_length <= cop2_length :\n cop1 = location[i]\n who.append(1)\n sum += cop1_length\n else :\n cop2 = location[i]\n who.append(2)\n sum += cop2_length\nprint(sum)\nfor i in range(w) :\n print(who[i])\n\n","sub_path":"경찰차.py","file_name":"경찰차.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"23076175","text":"#!/usr/bin/python\n\nimport sys\nimport numpy as np\nimport healpy as hlp\nimport matplotlib.pyplot as plt\n\n#################################################################\ndir_path = sys.argv[1]\ninfile = dir_path + sys.argv[2] + '.fits'\nlmax = int(sys.argv[3])\nprint(infile)\n#dir_path = '/home/vasiliy/cmb_2/maps/'\n#infile = dir_path + 'COM_CMB_IQU-smica_2048_R3.00_full.fits'\n#lmax = 4096\noutfile_l = dir_path + 'l_healpix.txt'\noutfile_m = dir_path + 'm_healpix.txt'\noutfile_real = dir_path + 'real_healpix.txt'\noutfile_imag = dir_path + 'imag_healpix.txt'\n\nmapT = hlp.fitsfunc.read_map(infile, hdu=1)\n'''\n#hdu = fits.open(infile)\n#print(hdu[1].header)\n#print(hdu[2].header)\n#mapT = hdu[1].data['I_STOKES']\n'''\n\n#hlp.mollview(mapT)\n#plt.show()\n\n#mapQ = hdu[1].data['Q_STOKES']\n#mapU = hdu[1].data['U_STOKES']\n#cl, alm = hlp.sphtfunc.anafast((mapT, mapQ, mapU), lmax=4096, alm=True)\n#cl, alm = hlp.sphtfunc.anafast(mapT, lmax=4096, alm=True)\nalm = hlp.sphtfunc.map2alm(mapT, lmax=lmax)\nindex_l, index_m = hlp.sphtfunc.Alm.getlm(lmax=lmax)\n\n'''\nn = alm.shape[0]\nindex_l = np.zeros(n) \nindex_m = np.zeros(n) \nl = 1\nm = 0\nfor i in range(n):\n\tindex_l[i] = l\n\tindex_m[i] = m\n\tm += 1\n\tif (m > l):\n\t\tl += 1\n\t\tm = 0\n'''\n\nnp.savetxt(outfile_l, index_l, fmt='%d')\nnp.savetxt(outfile_m, index_m, fmt='%d')\nnp.savetxt(outfile_real, np.real(alm))\nnp.savetxt(outfile_imag, np.imag(alm))\n\n'''\nhlp.fitsfunc.write_alm(outfile, alm)\nfits.setval(outfile, 'TFORM1', value='1J', ext=1)\nfits.setval(outfile, 'TFORM2', value='1D', ext=1)\nfits.setval(outfile, 'TFORM3', value='1D', ext=1)\n'''\n\n'''\nindex = np.array([1, 3, 4, 7, 8, 9, 13, 14, 15, 16])\nalm = np.array([9.19155973e-14+0.00000000e+00j, -4.71149609e-14+0.00000000e+00j, -2.02682639e-15+6.71538359e-14j, \n1.070185681e-05+0.000000000e+00j, -2.699767492e-06+9.136712833e-06j, \n-1.231469287e-05+-1.504891316e-05j, -6.399447102e-06+0.000000000e+00j, -9.178583241e-06+8.081902934e-07j,\n2.144613609e-05+9.975963167e-07j, -2.91886571e-14+2.30288641e-14j])\n\nprint(n)\n\nt = fits.table_to_hdu(table.Table([index, np.real(alm), np.imag(alm)], dtype=('i4', 'f8', 'f8')))\nout_hdu1 = fits.PrimaryHDU()\nout_hdu2 = t\nout_fits = fits.HDUList([out_hdu1, out_hdu2]) \nhdr = out_fits[1].header\nout_fits.writeto(outfile, overwrite=True)\nfits.setval(outfile, 'TFORM1', value='1J', ext=1)\nfits.setval(outfile, 'TFORM2', value='1D', ext=1)\nfits.setval(outfile, 'TFORM3', value='1D', ext=1)\n'''\n'''\n#################################################################\ndl = np.zeros(cl.shape[0])\n#for l in range(cl.shape[0]):\n#\tdl[l] = cl[l]*l*(l+1)/2.0/np.pi\ncl[0] = 0.0\ncl[1] = 0.0\nplt.plot(cl)\nplt.xlabel('l')\nplt.ylabel('TT')\n#plt.show()\n'''\n","sub_path":"healp2glesp.py","file_name":"healp2glesp.py","file_ext":"py","file_size_in_byte":2649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"431113635","text":"class Solution:\n def rotate(self, nums: List[int], k: int) -> None:\n k = k % len(nums)\n # if k == 0:\n # return\n \"\"\"\n [1,2,3,4,5,6,7]\n [5,6,7,1,2,3,4]\n [7,6,5,4,3,2,1]\n [1,2,3,4,7,6,5]\n [5,3,2,1,4,6,7]\n 1234567\n 4321567\n 5321467\n 5621437\n 5671432\n 5671234\n 1 2 3 4 5 6\n \n \"\"\"\n def reverse(a, b):\n left = a\n right = b - 1\n while left < right:\n nums[left], nums[right] = nums[right], nums[left]\n left += 1\n right -= 1\n \n # move the last k elements to the first elems\n # but the order is reversed\n reverse(0, len(nums))\n reverse(0, k) # make sure the first half order is right\n reverse(k, len(nums)) # make sure the last half order is right\n \n \n \n \n","sub_path":"Arrays/189_Rotate_Array.py","file_name":"189_Rotate_Array.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"300602375","text":"import unittest\n\nfrom src.response import Response\n\n\nclass TestResponse(unittest.TestCase):\n def test_response(self):\n results = Response.handle(\"Foo\", 200)\n self.assertDictEqual(\n {\n \"statusCode\": \"200\",\n \"body\": '\"Foo\"',\n \"headers\": {\n \"Content-Type\": \"application/json\",\n \"Access-Control-Allow-Origin\": \"*\",\n },\n },\n results,\n )\n","sub_path":"tests/test_response.py","file_name":"test_response.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"137046992","text":"#!/usr/bin/env/python\n\ntry:\n import matplotlib.pyplot as plt\nexcept:\n raise\nimport networkx as nx\nimport json\n\nwith open('states_result.txt', 'r') as fr:\n data = json.load(fr)\n\nlabels = {}\nfor state in data:\n label = \"T\"+state+\": \"\n for element in data[state]:\n if len(data[state][element]) < 2:\n label = label + str(data[state][element][0])\n else:\n label = label + \"[0-1]\"\n labels[state] = label\n\nG=nx.cycle_graph(14)\n\nG= G.to_directed()\n\ngood_edges = []\nfor edge in G.edges():\n if (edge[0] < edge[1] and edge != (0,13) or edge==(13,0)):\n good_edges.append(edge)\n\nfor i in range(14):\n G.add_node(i, title= labels[str(i)])\n\npos=nx.spring_layout(G, iterations=200)\n\npos_labels = {}\nDELTA = 0.12\nfor position in pos:\n pos_labels[position] = []\n pos_labels[position].append(pos[position][0] + DELTA*(abs(pos[position][0])/pos[position][0]))\n pos_labels[position].append(pos[position][1] + DELTA*(abs(pos[position][1])/pos[position][1]))\n\nlabels=dict((n,d['title']) for n,d in G.nodes(data=True))\n\nnx.draw(G, pos=pos, node_size=500, node_color=range(14), cmap=plt.cm.Greens, with_labels=False, edgelist=good_edges)\nnx.draw_networkx_labels(G, pos_labels, labels)\n\nplt.savefig(\"test.png\")\n#plt.show()\n","sub_path":"plants/bottle-filling/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"54609697","text":"from datetime import date\r\n\r\nfrom django.db import models\r\nfrom django.contrib.auth import get_user_model\r\n\r\nUser = get_user_model()\r\n\r\n\r\nclass TodoList(models.Model):\r\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\r\n name = models.CharField(max_length=80)\r\n\r\n\r\n class Meta:\r\n ordering = ['name', 'id']\r\n \r\n \r\n def __str__(self):\r\n return \"[{}] {}\".format(self.owner, self.name)\r\n\r\n\r\n \r\nclass Todo(models.Model):\r\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\r\n todo_list = models.ForeignKey(TodoList, on_delete=models.CASCADE)\r\n description = models.CharField(max_length=200)\r\n due_date = models.DateField()\r\n time_due = models.TimeField()\r\n\r\n\r\n def linkify(self):\r\n s = self.description\r\n out = \"\"\r\n for w in s.split():\r\n if w.startswith(\"http\"):\r\n out += '{}'.format(w, w)\r\n else:\r\n out += w\r\n out += \" \"\r\n return out\r\n\r\n\r\n def days_from_today(self):\r\n delta = self.due_date - date.today()\r\n days = delta.days\r\n\r\n if days == 0:\r\n return \"today\"\r\n\r\n elif days < 0:\r\n return \"overdue\"\r\n\r\n elif days == 1:\r\n return \"tomorrow\"\r\n\r\n else:\r\n return \"in {} days\".format(days)\r\n\r\n\r\n class Meta:\r\n ordering = ['todo_list', 'due_date', 'time_due', 'id']\r\n\r\n\r\n def __str__(self):\r\n return \"[{}] {}: {} (due {} {})\".format(self.owner, self.todo_list.name, self.description, self.due_date, self.time_due)\r\n\r\n \r\n\r\nclass TodoRecord(models.Model):\r\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\r\n entry = models.CharField(max_length=255)\r\n todo_list_id = models.IntegerField(default=-1)\r\n created_datetime = models.DateTimeField(auto_now_add=True)\r\n\r\n\r\n class Meta:\r\n ordering = ['-created_datetime']\r\n\r\n\r\n def __str__(self):\r\n return \"[{}] {}\".format(self.created_datetime, self.entry)\r\n\r\n\r\n\r\nclass WeekdayTodo(models.Model):\r\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\r\n weekday = models.CharField(max_length=3) # calendar.day_abbr, 0=Mon\r\n name = models.CharField(max_length=200)\r\n\r\n\r\n def __str__(self):\r\n return \"[{}] {}: {}\".format(self.owner, self.weekday, self.name)\r\n\r\n\r\n\r\nclass DayOfMonthTodo(models.Model):\r\n owner = models.ForeignKey(User, on_delete=models.CASCADE)\r\n day = models.IntegerField()\r\n name = models.CharField(max_length=200)\r\n\r\n\r\n def __str__(self):\r\n return \"[{}] {}: {}\".format(self.owner, self.day, self.name)\r\n \r\n \r\n","sub_path":"todolists/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"577867401","text":"from odoo import api, fields, models\n\nclass product(models.Model):\n _inherit='product.product'\n \n is_promo_product=fields.Boolean(\"Is Promotion Product\")\n \n @api.multi\n def _get_promo_product_category(self):\n if self._context.get('default_type')=='service':\n category_id = self.env['ir.values'].sudo().get_default('sale.config.settings', 'promotion_product_category_id')\n if category_id:\n return self.env['product.category'].search([('id','=',category_id)])\n else:\n return self.env['product.template']._get_default_category_id()\n else:\n return self.env['product.template']._get_default_category_id()\n \n categ_id = fields.Many2one(\n 'product.category', 'Internal Category',\n change_default=True, default=_get_promo_product_category, domain=\"[('type','=','normal')]\",\n required=True, help=\"Select category for the current product\")","sub_path":"ERP_IN/addons/promotion_ept/models/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"218767270","text":"from __future__ import print_function\nfrom __future__ import unicode_literals\n\nfrom flask import Blueprint, jsonify\n\n\n# 创建一个单独的api , 蓝图\n\n\ndef get_api(config, tools, models):\n API_NAME = config.get('api_user', 'name')\n\n user_model = models['users']\n\n # controller\n ctrler = Blueprint(API_NAME, __name__)\n\n @ctrler.route('/weibo/user', methods=['GET'])\n def list_weibo_user():\n users = user_model.find()\n return jsonify({'data': list(users)})\n\n @ctrler.route('/weibo', methods=['GET'])\n def list_user_id():\n users = user_model.find_by_user_id(3952070245)\n\n # kafka 发送消息\n pub = tools['pubsub']['producer']\n\n # 返回数据 map()的返回值已经不再是list,而是iterators, 所以想要使用,只用将iterator 转换成list 即可,\n data = list(users)\n\n # 结果\n result = []\n for d in data:\n s = {\n 'name': d['name'],\n 'id': d['id'],\n 'weibos_count': d['weibos_count']\n }\n result.append(s)\n\n pub.publish(result)\n\n return jsonify({'data': 'ok', 'code': '0'})\n\n return {'prefix': '/' + API_NAME, 'ctrler': ctrler}\n","sub_path":"app/api/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"79801963","text":"'''\nThe analysis module\nHandles the analyses of the info and data space for experiment evaluation and design.\n'''\nfrom slm_lab.agent import AGENT_DATA_NAMES\nfrom slm_lab.env import ENV_DATA_NAMES\nfrom slm_lab.lib import logger, util, viz\nimport colorlover as cl\nimport numpy as np\nimport pandas as pd\nimport pydash as _\n\nDATA_AGG_FNS = {\n 't': 'sum',\n 'reward': 'sum',\n 'loss': 'mean',\n 'explore_var': 'mean',\n}\nFITNESS_STD = util.read('slm_lab/experiment/fitness_std.json')\nMA_WINDOW = 100\n\n\ndef get_session_data(session):\n '''Gather data from session: MDP, Agent, Env data, and form session_data.'''\n aeb_space = session.aeb_space\n data_names = AGENT_DATA_NAMES + ENV_DATA_NAMES\n agg_data_names = ['epi'] + list(DATA_AGG_FNS.keys())\n data_h_v_dict = {data_name: aeb_space.get_history_v(data_name)\n for data_name in data_names}\n session_df_data = {}\n session_data = {}\n for aeb in aeb_space.aeb_list:\n data_h_dict = {data_name: data_h_v[aeb]\n for data_name, data_h_v in data_h_v_dict.items()}\n reset_idx = np.isnan(data_h_dict['done'])\n nonreset_idx = ~reset_idx\n epi_h = reset_idx.astype(int).cumsum()\n t_h = np.ones(reset_idx.shape)\n data_h_dict['epi'] = epi_h\n data_h_dict['t'] = t_h\n df = pd.DataFrame({data_name: data_h_dict[data_name][nonreset_idx]\n for data_name in ['epi', 't'] + data_names})\n aeb_df = df[agg_data_names].groupby('epi').agg(DATA_AGG_FNS)\n aeb_df.reset_index(drop=False, inplace=True)\n # TODO save full data to db\n session_df_data[aeb] = df\n session_data[aeb] = aeb_df\n logger.debug(f'{session_data}')\n return session_data\n\n\ndef plot_session(session, session_data):\n '''Plot the session graph, 2 panes: reward, loss & explore_var. Each aeb_df gets its own color'''\n aeb_count = len(session_data)\n if aeb_count <= 8:\n palette = cl.scales[str(max(3, aeb_count))]['qual']['Set2']\n else:\n palette = util.interp(cl.scales['8']['qual']['Set2'], aeb_count)\n fig = viz.tools.make_subplots(rows=3, cols=1, shared_xaxes=True)\n for idx, (a, e, b) in enumerate(session_data):\n aeb_str = f'{a}{e}{b}'\n aeb_df = session_data[(a, e, b)]\n fig_1 = viz.plot_line(\n aeb_df, 'reward', 'epi', legend_name=aeb_str, draw=False, trace_kwargs={'legendgroup': aeb_str, 'line': {'color': palette[idx]}})\n fig.append_trace(fig_1.data[0], 1, 1)\n\n fig_2 = viz.plot_line(\n aeb_df, ['loss'], 'epi', y2_col=['explore_var'], trace_kwargs={'legendgroup': aeb_str, 'showlegend': False, 'line': {'color': palette[idx]}}, draw=False)\n fig.append_trace(fig_2.data[0], 2, 1)\n fig.append_trace(fig_2.data[1], 3, 1)\n\n fig.layout['xaxis1'].update(title='epi', zerolinewidth=1)\n fig.layout['yaxis1'].update(fig_1.layout['yaxis'])\n fig.layout['yaxis1'].update(domain=[0.55, 1])\n\n fig.layout['yaxis2'].update(fig_2.layout['yaxis'])\n fig.layout['yaxis2'].update(showgrid=False, domain=[0, 0.45])\n fig.layout['yaxis3'].update(fig_2.layout['yaxis2'])\n fig.layout['yaxis3'].update(overlaying='y2', anchor='x2')\n fig.layout.update(_.pick(fig_1.layout, ['legend']))\n fig.layout.update(_.pick(fig_2.layout, ['legend']))\n fig.layout.update(title=session.spec['name'], width=500, height=600)\n viz.plot(fig)\n return fig\n\n\ndef calc_session_fitness_df(session, session_data):\n '''Calculate the session fitness df'''\n session_fitness_data = {}\n for aeb in session_data:\n aeb_df = session_data[aeb]\n body = session.aeb_space.body_space.data[aeb]\n aeb_fitness_sr = calc_aeb_fitness_sr(aeb_df, body.env.name)\n aeb_fitness_df = pd.DataFrame([aeb_fitness_sr], index=[session.index])\n session_fitness_data[aeb] = aeb_fitness_df\n session_fitness_df = pd.concat(session_fitness_data, axis=1)\n mean_fitness_df = session_fitness_df.mean(\n axis=1, level=3) # mean across all bodies\n session_fitness = calc_fitness(mean_fitness_df)\n logger.info(f'Session mean fitness: {session_fitness}\\n{mean_fitness_df}')\n return session_fitness_df\n\n\ndef save_session_data(session_spec, session_df, session_fig):\n '''\n Save the session data: df, plot.\n session_df is multi-indexed with (a,e,b), 3 extra levels\n to read, use:\n session_df = util.read(filepath, header=[0, 1, 2, 3])\n session_data = util.session_df_to_data(session_df)\n '''\n # TODO generalize to use experiment timestamp, id, sesison coor in info space, to replace timestamp\n spec_name = session_spec['name']\n prepath = f'data/{spec_name}/{spec_name}_{util.get_timestamp()}'\n logger.info(f'Saving session data to {prepath}_*')\n util.write(session_df, f'{prepath}_session_df.csv')\n viz.save_image(session_fig, f'{prepath}_session_graph.png')\n\n\ndef analyze_session(session):\n '''Gather session data, plot, and return session df for high level agg.'''\n session_data = get_session_data(session)\n session_fig = plot_session(session, session_data)\n session_df = pd.concat(session_data, axis=1)\n session_fitness_df = calc_session_fitness_df(session, session_data)\n save_session_data(session.spec, session_df, session_fig)\n return session_df, session_fitness_df\n\n\ndef calc_trial_fitness_df(trial):\n '''Calculate the trial fitness df'''\n trial_fitness_data = {}\n all_session_fitness_df = pd.concat(\n list(trial.session_fitness_df_dict.values()))\n for aeb in util.get_df_aeb_list(all_session_fitness_df):\n aeb_df = all_session_fitness_df.loc[:, aeb]\n aeb_fitness_sr = aeb_df.mean()\n consistency = calc_consistency(aeb_df.values)\n aeb_fitness_sr = aeb_fitness_sr.append(\n pd.Series({'consistency': consistency}))\n aeb_fitness_df = pd.DataFrame([aeb_fitness_sr], index=[trial.index])\n trial_fitness_data[aeb] = aeb_fitness_df\n trial_fitness_df = pd.concat(trial_fitness_data, axis=1)\n mean_fitness_df = trial_fitness_df.mean(\n axis=1, level=3) # mean across all bodies\n trial_fitness_df = mean_fitness_df # agg for trial level\n trial_fitness = calc_fitness(mean_fitness_df)\n logger.info(f'Trial mean fitness: {trial_fitness}\\n{mean_fitness_df}')\n return trial_fitness_df\n\n\ndef save_trial_data(trial_spec, trial_df):\n spec_name = trial_spec['name']\n prepath = f'data/{spec_name}/{spec_name}_{util.get_timestamp()}'\n logger.info(f'Saving trial data to {prepath}_*')\n util.write(trial_spec, f'{prepath}_spec.json')\n # TODO trial data is composed of saved session data files\n # util.write(trial_df, f'{prepath}_trial_df.csv')\n\n\ndef analyze_trial(trial):\n '''Gather trial data, plot, and return trial df for high level agg.'''\n trial_df = pd.concat(trial.session_df_dict, axis=1)\n trial_fitness_df = calc_trial_fitness_df(trial)\n logger.debug(f'{trial_df}')\n save_trial_data(trial.spec, trial_df)\n return trial_df, trial_fitness_df\n\n\ndef analyze_experiment(experiment):\n '''Gather experiment data, plot, and return experiment df for high level agg.'''\n raise NotImplementedError()\n return experiment_df\n\n\n'''\nFitness analysis\n'''\n\n\ndef calc_strength(aeb_df, rand_epi_reward, std_epi_reward):\n '''\n Calculate the strength for each episode:\n strength_epi = (epi_reward - rand_epi_reward) / (std_epi_reward - rand_epi_reward)\n Propeties:\n - random agent has strength ~0, baseline agent has strength ~1.\n - if an agent achieve x2 rewards, the strength is ~x2, and so on.\n - strength of learning agent always tends toward positive regardless of the sign of rewards\n - scale of strength is always standard at 1 and its multiplies, regardless of the scale of actual rewards. Strength stays invariant even as reward gets rescaled.\n This allows for standard comparison between agents on the same problem using an intuitive measurement of strength. With proper scaling by a difficulty factor, we can compare across problems of different difficulties.\n '''\n return (aeb_df['reward'] - rand_epi_reward) / (std_epi_reward - rand_epi_reward)\n\n\ndef calc_stable_idx(aeb_df):\n '''Calculate the index (epi) when strength first becomes stable (using moving mean and working backward)'''\n # interpolate linearly by strength to account for failure to solve\n interp_strength = min(1, aeb_df['strength_ma'].max())\n std_strength_ra_idx = (aeb_df['strength_ma'] == interp_strength).idxmax()\n # index when it first achieved stable std_strength\n stable_idx = std_strength_ra_idx - (MA_WINDOW - 1)\n return stable_idx\n\n\ndef calc_std_strength_timestep(aeb_df):\n '''\n Calculate the timestep needed to achieve stable (within window) std_strength.\n For agent failing to achieve std_strength 1, use linear interpolation.\n '''\n # interpolate linearly by strength to account for failure to solve\n interp_strength = min(1, aeb_df['strength_ma'].max())\n stable_idx = calc_stable_idx(aeb_df)\n std_strength_timestep = aeb_df.loc[\n stable_idx, 'total_t'] / interp_strength\n return std_strength_timestep\n\n\ndef calc_speed(aeb_df, std_timestep):\n '''\n Calculate the speed (using absolute timesteps) to attain std_strength 1:\n speed = std_timestep / agent_timestep\n Propeties:\n - random agent has speed ~0, baseline agent has speed ~1\n - if an agent takes x2 timesteps to read std_strength, we can it is 2x slower.\n - speed of learning agent always tends toward positive regardless of the shape of rewards curve\n - scale of speed is always standard at 1 and its multiplies, regardless of absolute timestep.\n This allows an intuitive measurement of learning speed and the standard comparison between agents on the same problem. Absolute timestep also measures the bits of new information given to the agent, which is a more grounded metric. With proper scaling of timescale (or bits scale), we can compare across problems of different difficulties.\n '''\n agent_timestep = calc_std_strength_timestep(aeb_df)\n speed = std_timestep / agent_timestep\n return speed\n\n\ndef is_noisy_mono_inc(sr):\n '''Check if sr is monotonically increasing, within noise = 5% * std_strength = 0.05 * 1'''\n zero_noise = -0.05\n mono_inc_sr = np.diff(sr) >= zero_noise\n # restore sr to same length\n mono_inc_sr = np.insert(mono_inc_sr, 0, np.nan)\n return mono_inc_sr\n\n\ndef calc_stability(aeb_df):\n '''\n Calculate the stability at maintaining std_strength and higher:\n stability = ratio of times strength is monotonically increasing with 5% allowance for noise since becoming stable.\n Propeties:\n - considers once strength becomes stable (note, stable does not imply stability = 1)\n - allows for drop in strength of 5% of std_strength, which is invariant to the scale of rewards\n - if strength is monotonically increasing (with 5% noise), then it is stable\n - sharp gain in strength is considered stable\n - works even for partial solution (not attaining std_strength), due to how stable_idx is calculated\n '''\n stable_idx = calc_stable_idx(aeb_df)\n stable_df = aeb_df.loc[stable_idx:, 'strength_mono_inc']\n stability = stable_df.sum() / len(stable_df)\n return stability\n\n\ndef calc_consistency(fitness_vecs):\n '''\n Calculate the consistency of trial by the fitness_vectors of its sessions:\n consistency = ratio of non-outlier vectors\n Properties:\n - outliers are calculated using MAD modified z-score\n - if all the fitness vectors are zero, consistency = 0\n - works for all sorts of session fitness vectors, with the standard scale\n '''\n if ~np.any(fitness_vecs):\n # no consistency if vectors all 0\n consistency = 0\n else:\n is_outlier_arr = util.is_outlier(fitness_vecs)\n consistency = (~is_outlier_arr).sum() / len(is_outlier_arr)\n return consistency\n\n\ndef calc_fitness(fitness_vec):\n '''\n Takes a vector of qualifying standardized dimensions of fitness and compute the normalized length as fitness\n L2 norm because it diminishes lower values but amplifies higher values for comparison.\n '''\n if isinstance(fitness_vec, pd.Series):\n fitness_vec = fitness_vec.values\n elif isinstance(fitness_vec, pd.DataFrame):\n fitness_vec = fitness_vec.iloc[0].values\n std_fitness_vector = np.ones(len(fitness_vec))\n fitness = np.linalg.norm(fitness_vec) / np.linalg.norm(std_fitness_vector)\n return fitness\n\n\ndef calc_aeb_fitness_sr(aeb_df, env_name):\n '''Top level method to calculate fitness vector for AEB level data (strength, speed, stability)'''\n logger.info('Dev feature: fitness computation')\n no_fitness_sr = pd.Series({\n 'strength': 0, 'speed': 0, 'stability': 0})\n if len(aeb_df) < MA_WINDOW:\n logger.warn(\n f'Run more than {MA_WINDOW} episodes to compute proper fitness')\n return no_fitness_sr\n if env_name not in FITNESS_STD:\n logger.warn(\n f'The fitness standard for env {env_name} is not built yet. Contact author.')\n return no_fitness_sr\n std = FITNESS_STD.get(env_name)\n aeb_df['total_t'] = aeb_df['t'].cumsum()\n aeb_df['strength'] = calc_strength(\n aeb_df, std['rand_epi_reward'], std['std_epi_reward'])\n aeb_df['strength_ma'] = aeb_df['strength'].rolling(MA_WINDOW).mean()\n aeb_df['strength_mono_inc'] = is_noisy_mono_inc(\n aeb_df['strength']).astype(int)\n\n strength = aeb_df['strength_ma'].max()\n speed = calc_speed(aeb_df, std['std_timestep'])\n stability = calc_stability(aeb_df)\n aeb_fitness_sr = pd.Series({\n 'strength': strength, 'speed': speed, 'stability': stability})\n return aeb_fitness_sr\n","sub_path":"slm_lab/experiment/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":13739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"259957539","text":"#! /usr/bin/env python\n\n################################################################################\n#\n# Tectiform Open Source License (TOS)\n#\n# Copyright (c) 2015 Tectiform Inc.\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\nimport os\nimport shutil\nfrom .. Objects import Object\nfrom .. FileSystems import FileSystemBaseObject\nfrom .. FileSystems import FindFullDirectory\nfrom . BlockDevices import BlockDevice\nfrom . CharacterDevices import CharacterDevice\nfrom . Fifos import Fifo\nfrom . Files import File\nfrom . SymbolicLinks import SymbolicLink\nfrom . Sockets import Socket\nfrom types import *\n\n\nclass Directory(FileSystemBaseObject):\n\t\"\"\"The Directory class.\"\"\"\n\n\tdef __init__(self, name, **kwargs):\n\t\tdirname = str(name)\n\t\tif 'autofind' in kwargs:\n\t\t\tif kwargs['autofind']:\n\t\t\t\tdirname = FindFullDirectory(dirname)\n\t\tFileSystemBaseObject.__init__(self, dirname, **kwargs)\n\n\t# End __init__\n\n\n\t@property\n\tdef parent(self):\n\t\treturn Directory(self.path)\n\n\t# End parent\n\n\n\tdef __getObjectAccordingToClass(self,name,path):\n\t\te = FileSystemBaseObject(self.fullpath + os.sep + name)\n\t\tif e.directory:\n\t\t\tobj = Directory(self.fullpath + os.sep + name)\n\t\telif e.characterSpecialDevice:\n\t\t\tobj = CharacterDevice(self.fullpath + os.sep + name)\n\t\telif e.blockSpecialDevice:\n\t\t\tobj = BlockDevice(self.fullpath + os.sep + name)\n\t\telif e.symbolicLink:\n\t\t\tobj = SymbolicLink(self.fullpath + os.sep + name)\n\t\telif e.regular:\n\t\t\tobj = File(self.fullpath + os.sep + name)\n\t\telif e.fifo:\n\t\t\tobj = Fifo(self.fullpath + os.sep + name)\n\t\telif e.socket:\n\t\t\tobj = Socket(self.fullpath + os.sep + name)\n\t\telse:\n\t\t\tobj = e\n\t\treturn obj\n\n\t# End __getObjectAccordingToClass\n\n\n\n\t@property\n\tdef entries(self):\n\t\tentries = []\n\t\tnames = os.listdir(self.fullpath)\n\t\tfor name in names:\n\t\t\tentries.append(self.__getObjectAccordingToClass(name,self.fullpath))\n\n\t\treturn entries\n\t# End entries\n\n\n\t@property\n\tdef empty(self):\n\t\treturn len(self.entries) == 0\n\n\t# End empty\n\n\n\n\t@property\n\tdef files(self):\n\t\tfiles = []\n\t\ttry:\n\t\t\tentries = os.listdir(self.fullpath)\n\t\texcept OSError as e:\n\t\t\tif not Object.global_dry_run:\n\t\t\t\traise e\n\t\t\tentries = []\n\n\t\tfor entry in entries:\n\t\t\tobj = FileSystemBaseObject(self.fullpath + os.sep + entry)\n\t\t\tif not obj.directory and \\\n\t\t\t not obj.socket and \\\n\t\t\t not obj.symbolicLink and \\\n\t\t\t not obj.fifo:\n\t\t\t\tfiles.append(self.__getObjectAccordingToClass(entry,self.fullpath))\n\t\treturn files\n\t# End files\n\n\t@property\n\tdef directories(self):\n\t\tdirectories = []\n\t\ttry:\n\t\t\tentries = os.listdir(self.fullpath)\n\t\texcept OSError as e:\n\t\t\tif not Object.global_dry_run:\n\t\t\t\traise e\n\t\t\tentries = []\n\t\tfor entry in entries:\n\t\t\tobj = self.__getObjectAccordingToClass(entry,self.fullpath)\n\t\t\tif obj.directory:\n\t\t\t\tdirectories.append(obj)\n\t\treturn directories\n\t# End directories\n\n\t@property\n\tdef characters(self):\n\t\tspecials = []\n\t\ttry:\n\t\t\tentries = os.listdir(self.fullpath)\n\t\texcept OSError as e:\n\t\t\tif not Object.global_dry_run:\n\t\t\t\traise e\n\t\t\tentries = []\n\t\tfor entry in entries:\n\t\t\tobj = self.__getObjectAccordingToClass(entry,self.fullpath)\n\t\t\tif obj.characterSpecialDevice:\n\t\t\t\tspecials.append(obj)\n\t\treturn specials\n\t# End characters\n\n\t@property\n\tdef blocks(self):\n\t\tspecials = []\n\t\ttry:\n\t\t\tentries = os.listdir(self.fullpath)\n\t\texcept OSError as e:\n\t\t\tif not Object.global_dry_run:\n\t\t\t\traise e\n\t\t\tentries = []\n\t\tfor entry in entries:\n\t\t\tobj = self.__getObjectAccordingToClass(entry,self.fullpath)\n\t\t\tif obj.blockSpecialDevice:\n\t\t\t\tspecials.append(obj)\n\t\treturn specials\n\t# End blocks\n\n\t@property\n\tdef regulars(self):\n\t\tregs = []\n\t\ttry:\n\t\t\tentries = os.listdir(self.fullpath)\n\t\texcept OSError as e:\n\t\t\tif not Object.global_dry_run:\n\t\t\t\traise e\n\t\t\tentries = []\n\t\tfor entry in entries:\n\t\t\tobj = self.__getObjectAccordingToClass(entry,self.fullpath)\n\t\t\tif obj.regular:\n\t\t\t\tregs.append(obj)\n\t\treturn regs\n\t# End regulars\n\n\t@property\n\tdef fifos(self):\n\t\tspecials = []\n\t\ttry:\n\t\t\tentries = os.listdir(self.fullpath)\n\t\texcept OSError as e:\n\t\t\tif not Object.global_dry_run:\n\t\t\t\traise e\n\t\t\tentries = []\n\t\tfor entry in entries:\n\t\t\tobj = self.__getObjectAccordingToClass(entry,self.fullpath)\n\t\t\tif obj.fifo:\n\t\t\t\tspecials.append(obj)\n\t\treturn specials\n\t# End fifos\n\n\t@property\n\tdef links(self):\n\t\tspecials = []\n\t\ttry:\n\t\t\tentries = os.listdir(self.fullpath)\n\t\texcept OSError as e:\n\t\t\tif not Object.global_dry_run:\n\t\t\t\traise e\n\t\t\tentries = []\n\t\tfor entry in entries:\n\t\t\tobj = self.__getObjectAccordingToClass(entry,self.fullpath)\n\t\t\tif obj.symbolicLink:\n\t\t\t\tspecials.append(obj)\n\t\treturn specials\n\t# End links\n\n\t@property\n\tdef sockets(self):\n\t\tspecials = []\n\t\ttry:\n\t\t\tentries = os.listdir(self.fullpath)\n\t\texcept OSError as e:\n\t\t\tif not Object.global_dry_run:\n\t\t\t\traise e\n\t\t\tentries = []\n\t\tfor entry in entries:\n\t\t\tobj = self.__getObjectAccordingToClass(entry,self.fullpath)\n\t\t\tif obj.socket:\n\t\t\t\tspecials.append(obj)\n\t\treturn specials\n\t# End sockets\n\n\n\t@property\n\tdef all_directories(self):\n\t\tdirs = self.directories\n\t\tfor d in self.directories:\n\t\t\tdirs.extend(d.all_directories)\n\t\treturn dirs\n\t# End all_directories\n\n\n\t@property\n\tdef all_files(self):\n\t\tfiles = self.files\n\t\tdirs = self.directories\n\t\tfor d in dirs:\n\t\t\tfiles.extend(d.all_files)\n\t\treturn files\n\t# End all_files\n\n\t@property\n\tdef all_characters(self):\n\t\tfiles = self.characters\n\t\tdirs = self.directories\n\t\tfor d in dirs:\n\t\t\tfiles.extend(d.all_characters)\n\t\treturn files\n\t# End all_characters\n\n\t@property\n\tdef all_blocks(self):\n\t\tfiles = self.blocks\n\t\tdirs = self.directories\n\t\tfor d in dirs:\n\t\t\tfiles.extend(d.all_blocks)\n\t\treturn files\n\t# End all_blocks\n\n\t@property\n\tdef all_regulars(self):\n\t\tfiles = self.regulars\n\t\tdirs = self.directories\n\t\tfor d in dirs:\n\t\t\tfiles.extend(d.all_regulars)\n\t\treturn files\n\t# End all_regulars\n\n\t@property\n\tdef all_fifos(self):\n\t\tfiles = self.fifos\n\t\tdirs = self.directories\n\t\tfor d in dirs:\n\t\t\tfiles.extend(d.all_fifos)\n\t\treturn files\n\t# End all_fifos\n\n\t@property\n\tdef all_links(self):\n\t\tfiles = self.links\n\t\tdirs = self.directories\n\t\tfor d in dirs:\n\t\t\tfiles.extend(d.all_links)\n\t\treturn files\n\t# End all_links\n\n\t@property\n\tdef all_sockets(self):\n\t\tfiles = self.sockets\n\t\tdirs = self.directories\n\t\tfor d in dirs:\n\t\t\tfiles.extend(d.all_sockets)\n\t\treturn files\n\t# End all_sockets\n\n\t@property\n\tdef all_entries(self):\n\t\tentries = self.entries\n\t\tdirs = self.directories\n\t\tfor d in dirs:\n\t\t\tentries.append(d)\n\t\t\tentries.extend(d.all_entries)\n\t\treturn entries\n\t# End all_entries\n\n\n\t@property\n\tdef extensions(self):\n\t\tallEntries = self.all_entries\n\t\textensions = {}\n\t\tfor entry in allEntries:\n\t\t\tif entry.hasExtension:\n\t\t\t\tif not entry.extension in extensions:\n\t\t\t\t\textensions[entry.extension] = True\n\t\treturn extensions.keys()\n\n\t# End extensions\n\n\n\tdef create(self):\n\t\tif Object.log_object and Object.global_dry_run:\n\t\t\tObject.log_object.log(\"mkdir \" + self.fullpath)\n\t\tif not Object.global_dry_run:\n\t\t\tos.makedirs(self.fullpath)\n\n\t# End create\n\n\tdef remove(self):\n\t\tif os.path.exists(self.fullpath):\n\t\t\tshutil.rmtree(self.fullpath)\n\n\t# End remove\n\n\n\tdef removeContents(self):\n\t\tif os.path.exists(self.fullpath):\n\t\t\ttheStuff = self.entries\n\t\t\tfor theObject in theStuff:\n\t\t\t\ttheObject.remove()\n\t# End removeContents\n\n\n\tdef __getitem__(self,key):\n\t\tif type(key) != StringType and type(key) != UnicodeType:\n\t\t\traise KeyError(key)\n\t\tobj = FileSystemBaseObject(key)\n\t\tif not obj.exists:\n\t\t\traise KeyError(key)\n\n\t\treturn self.__getObjectAccordingToClass(obj.name, obj.path)\n\n\t# End __getitem__\n\n\n\tdef __contains__(self,obj):\n\t\treturn self.has_key(obj)\n\t# End __contains__\n\n\n\tdef has_key(self,key):\n\t\tif type(key) != StringType and type(key) != UnicodeType:\n\t\t\treturn False\n\n\t\tobj = FileSystemBaseObject(key)\n\t\tif not obj.exists:\n\t\t\treturn False\n\n\t\treturn True\n\n\t# End has_key\n\n\tdef keys(self):\n\t\treturn [ entry.fullpath for entry in self.entries ]\n\t# End keys\n\n\n\tdef hasChild(self,child):\n\t\tfor entry in self.entries:\n\t\t\tif child == entry.name:\n\t\t\t\treturn True\n\t\t\tif entry.directory:\n\t\t\t\tif entry.hasChild(child):\n\t\t\t\t\treturn True\n\t\treturn False\n\n\t# End hasChild\n\n\n\tdef getChildren(self,child):\n\t\tchildren = []\n\t\tfor entry in self.entries:\n\t\t\tif child == entry.name:\n\t\t\t\tchildren.append(entry)\n\t\t\tif entry.directory:\n\t\t\t\tchildren.extend(entry.getChildren(child))\n\t\treturn children\n\t# End getChildren\n\n\n\tdef make_current_directory(self):\n\t\tcurrent_directory = os.getcwd()\n\t\ttry:\n\t\t\tif Object.log_object and Object.global_dry_run:\n\t\t\t\tObject.log_object.log(\"cd \" + self.fullpath)\n\t\t\tos.chdir(self.fullpath)\n\t\texcept OSError as e:\n\t\t\tif not Object.global_dry_run:\n\t\t\t\traise e\n\t\treturn Directory(current_directory)\n\n\t# End make_current_directory\n\n\n# End Directory\n\n\n\ndef MakeDirectoryAndRemovePreviousContents(name,clearDirectory=True):\n\tif os.path.exists(name):\n\t\tif not clearDirectory:\n\t\t\tshutil.rmtree(name)\n\t\t\tif Object.log_object and Object.global_dry_run:\n\t\t\t\tObject.log_object.log(\"mkdir \" + name)\n\t\t\tos.mkdir(name)\n\telse:\n\t\tif Object.log_object and Object.global_dry_run:\n\t\t\tObject.log_object.log(\"mkdir \" + name)\n\t\tos.mkdir(name)\n\n# End MakeDirectoryAndRemovePreviousContents\n\n\ndef RemoveDirectory(name):\n\tif os.path.exists(name):\n\t\tshutil.rmtree(name)\n\n# End RemoveDirectory\n\n","sub_path":"FileSystems/Directories.py","file_name":"Directories.py","file_ext":"py","file_size_in_byte":10152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"126389937","text":"from bisect import bisect_left, bisect_right\n\ndef readinput():\n n,m=list(map(int,input().split()))\n a=list(map(int,input().split()))\n b=[]\n c=[]\n for _ in range(m):\n bb,cc=list(map(int,input().split()))\n b.append(bb)\n c.append(cc)\n return n,m,a,b,c\n\ndef main(n,m,a,b,c):\n a.sort()\n for i in range(m):\n #print(a)\n bi=b[i]\n ci=c[i]\n j=bisect_left(a,ci)-1\n if j<0:\n continue\n if j>bi-1:\n save=a[bi:j+1]\n l=j-bi+1\n r=j\n a[l:r+1]=[ci]*(r-l+1)\n a[0:l]=save\n else:\n l=0\n r=j\n a[l:r+1]=[ci]*(r-l+1)\n\n sum=0\n for i in range(n):\n sum+=a[i]\n \n return sum\n\ndef main2(n,m,a,b,c):\n all=[]\n for i in range(n):\n all.append((a[i],1))\n for i in range(m):\n all.append((c[i],b[i]))\n all.sort(reverse=True, key=lambda x:x[0])\n #print(all)\n count=n\n sum=0\n i=0\n while(count>0):\n ni=all[i][1]\n if ni<=count:\n sum+=all[i][0]*ni\n count-=ni\n else:\n sum+=all[i][0]*count\n count=0\n i+=1\n #print(sum,count)\n return sum\n\nif __name__=='__main__':\n n,m,a,b,c=readinput()\n ans=main2(n,m,a,b,c)\n print(ans)\n","sub_path":"Python_codes/p03038/s241408538.py","file_name":"s241408538.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"393586965","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Mar 21 00:21:19 2016\n\n@author: zz\n\"\"\"\n\nfrom RFCELM import RFCELM\nfrom util import *\n\ntrain_data, train_label, test_data, test_label = loadData(0.1)\nfeature_dim = train_data.shape[1]\nlabel_dim = train_label.shape[1]\n \ntrain_data = normalizeData(train_data)\ntest_data = normalizeData(test_data)\n\nrfcelm = RFCELM(28, 28, feature_dim*10, label_dim, 'lite', 'rf-c', train_data)\n\nrfcelm.trainModel(train_data, train_label)\n#rfcelm.save(r\"D:\\workspace\\Data\\ELM\\weights\\rfcelm\")\nrfcelm.testModel(test_data, test_label)","sub_path":"testRFCELM.py","file_name":"testRFCELM.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"327575582","text":"# -*- coding: utf-8 -*-\n\n\n\"\"\"\nUnittests for $ pyin\n\"\"\"\n\n\nimport json\nimport os\nimport subprocess\nimport sys\nimport textwrap\n\nimport pytest\n\nimport pyin.cli\n\n\ndef test_single_expr(runner, csv_with_header_content):\n result = runner.invoke(pyin.cli.main, [\n \"line.upper()\"\n ], input=csv_with_header_content)\n assert result.exit_code == 0\n assert result.output.strip() == csv_with_header_content.upper().strip()\n\n\ndef test_multiple_expr(runner, path_csv_with_header):\n expected = os.linesep.join((\n '\"FIELD1\",\"FIELD2\",\"FIELD3\"',\n '[\"l2f1,l2f2,l2f3\"]',\n '\"l3f1\",\"l3f2\",\"l3f3\"',\n '\"l4f1\",\"l4f2\",\"l4f3\"',\n 'END'))\n result = runner.invoke(pyin.cli.main, [\n '-i', path_csv_with_header,\n \"line.upper() if 'field' in line else line\",\n \"'l1' not in line\",\n \"line.replace('\\\"', '').split() if 'l2' in line else line\",\n \"'END' if 'l5' in line else line\"\n ])\n assert result.exit_code == 0\n assert result.output.strip() == expected.strip()\n\n\ndef test_with_generator(runner, csv_with_header_content):\n result = runner.invoke(pyin.cli.main, [\n \"(i for i in line)\"\n ], input=csv_with_header_content)\n assert result.exit_code == 0\n assert os.linesep.join(\n [json.dumps(list((i for i in line))) for line in csv_with_header_content.splitlines()])\n\n\ndef test_with_blank_lines(runner):\n result = runner.invoke(pyin.cli.main, [\n 'line'\n ], input=\"\")\n assert result.exit_code == 0\n assert result.output == ''\n\n\ndef test_block_mode(runner):\n text = json.dumps({k: None for k in range(10)}, indent=4)\n assert len(text.splitlines()) > 1\n\n result = runner.invoke(pyin.cli.main, [\n \"--block\",\n \"json.loads(line)\",\n \"{k: v for k, v in line.items() if int(k) in range(5)}\"\n ], input=text)\n assert result.exit_code == 0\n\n expected = '{\"3\": null, \"4\": null, \"0\": null, \"2\": null, \"1\": null}'\n assert json.loads(expected) == json.loads(result.output)\n\n\ndef test_unicode(runner):\n\n text = u\"\"\"Héllö\"\"\"\n result = runner.invoke(pyin.cli.main, [\n 'line.upper()'\n ], input=text)\n assert result.exit_code == 0\n assert result.output.strip() == text.strip().upper()\n\n\n@pytest.mark.parametrize(\"skip_lines\", [1, 3])\ndef test_skip_single_line(runner, skip_lines, csv_with_header_content):\n result = runner.invoke(pyin.cli.main, [\n '--skip', skip_lines,\n 'line'\n ], input=csv_with_header_content)\n assert result.exit_code == 0\n expected = os.linesep.join(csv_with_header_content.splitlines()[skip_lines:])\n assert result.output.strip() == expected.strip()\n\n\ndef test_skip_all_input(runner, csv_with_header_content):\n result = runner.invoke(pyin.cli.main, [\n '--skip', 100,\n 'line'\n ], input=csv_with_header_content)\n assert result.output != 0\n assert 'skipped' in result.output.lower()\n\n\ndef test_repr(runner):\n\n text = \"\"\"\n 2015-01-01\n 2015-01-02\n 2015-01-03\n \"\"\".strip()\n\n result = runner.invoke(pyin.cli.main, [\n \"line.strip()\",\n \"datetime.datetime.strptime(line, '%Y-%m-%d')\",\n \"isinstance(line, datetime.datetime)\"\n ], input=text)\n\n assert result.exit_code == 0\n assert result.output.strip() == textwrap.dedent(\"\"\"\n datetime.datetime(2015, 1, 1, 0, 0)\n datetime.datetime(2015, 1, 2, 0, 0)\n datetime.datetime(2015, 1, 3, 0, 0)\n \"\"\").strip()\n\n\ndef test_multi_infile(path_csv_with_header, runner):\n result = runner.invoke(pyin.cli.main, [\n '-i', path_csv_with_header,\n '-i', path_csv_with_header,\n 'line'\n ])\n assert result.exit_code == 0\n\n expected = ''\n for _ in range(2):\n with open(path_csv_with_header) as f:\n expected += f.read()\n\n assert result.output == expected\n\n\ndef test_catch_IOError(path_csv_with_header):\n\n \"\"\"Python produces an IOError if the input is stdin, and the output is\n stdout piped to another process that does not completely consume the input.\n \"\"\"\n\n result = subprocess.check_output(\n \"cat {} | pyin line | head -1\".format(path_csv_with_header), shell=True)\n assert result.decode().strip() == '\"field1\",\"field2\",\"field3\"'.strip()\n","sub_path":"tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":4220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"233535403","text":"import sys\n\nif ('HER/examples/run.py' not in sys.argv[0]) and ('HER/examples/visualize.py' not in sys.argv[0]):\n try:\n import matplotlib \n matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n import visualize \n except:\n print ('import failed')\n \nfrom Mask_RCNN.utils import Dataset\nimport numpy as np\n\nimport sys\nsys.path.append('Mask_RCNN')\n\nfrom time import time\nimport pickle\nimport os\n\nfrom scipy.misc import imread, imsave\n\n#things to check\n#1. need to preprocess/normalize image/mask input?\n\nNUMTHREADS=8\nDATADIR = 'ap-v3_data'\n\n#a hack to get around not being able to use tkinter \ndef make_save(name):\n plt.show = lambda: (plt.savefig(name, bbox_inches = 'tight', dpi = 300), plt.clf())\n \nclass Paths(object):\n def __init__(self, datadir):\n self.datadir = datadir\n if not os.path.exists(datadir):\n os.mkdir(datadir)\n \n self.maskdir = os.path.join(datadir, 'mask')\n if not os.path.exists(self.maskdir):\n os.mkdir(self.maskdir)\n\n self.imgdir = os.path.join(datadir, 'img')\n if not os.path.exists(self.imgdir):\n os.mkdir(self.imgdir)\n\n def mask_fn_for_id(self, i):\n return os.path.join(self.maskdir, '%d.npz' % i)\n\n def img_fn_for_id(self, i):\n return os.path.join(self.imgdir, '%d.png' % i)\n\n def save_img_to_id(self, i, img):\n pth = self.img_fn_for_id(i)\n imsave(pth, img)\n\n def load_img_from_id(self, i):\n pth = self.img_fn_for_id(i)\n return imread(pth)\n\n def save_mask_to_id(self, i, mask):\n pth = self.mask_fn_for_id(i)\n np.savez_compressed(pth, mask)\n \n def load_mask_from_id(self, i):\n pth = self.mask_fn_for_id(i)\n return np.load(pth)['arr_0']\n\nclass MujocoData(Dataset, Paths):\n\n def __init__(self, datadir='data'):\n Dataset.__init__(self)\n Paths.__init__(self, datadir)\n \n def load_mujoco(self, start_id = 0, end_id = 1000):\n self.add_class(\"mujoco\", 1, \"box\")\n\n for i in range(start_id, end_id):\n self.add_image(\"mujoco\", i, None)\n \n def load_image(self, i):\n return self.load_img_from_id(i)\n\n def load_mask(self, i):\n mask = self.load_mask_from_id(i)\n num_objs = mask.shape[-1]\n cls = cls = np.array([1]*num_objs).astype(np.int32)\n return mask, cls\n\nclass GenerateData(Paths):\n def __init__(self, renderer, datadir):\n self.renderer = renderer\n super().__init__(datadir)\n\n def generate(self, count=1000, tid = None):\n print ('tid is', tid)\n iterator = (range(count)\n if tid is None\n else range(tid, count, NUMTHREADS))\n \n for i in iterator:\n print(\"generating image %d\" %i)\n img, masks = self._generate()\n self.save_mask_to_id(i, masks)\n self.save_img_to_id(i, img)\n\n def _generate(self):\n self.renderer.reset()\n self.renderer.rand_state()\n\n img = self.renderer.render_rgb()\n box = self.renderer.render_box()\n box_modal = self.renderer.render_box(override_amodal = False)\n\n THRESHOLD = 50 #number of pixels visible\n exists_box = np.sum(box) > THRESHOLD\n\n #modality\n RATIO_THRESHOLD = 0.1\n exists_box = exists_box and (float(np.sum(box_modal)) / np.sum(box) > RATIO_THRESHOLD)\n\n cls = []\n masks = []\n if exists_box:\n masks.append(box)\n cls.append(1)\n else:\n print('warning: no box found')\n\n if exists_box:\n masks = np.stack(masks, axis = 2)\n else:\n h, w, _ = img.shape\n masks = np.zeros((h, w, 0)).astype(np.float32)\n\n #cls = np.array(cls).astype(np.int32)\n\n return img, masks#, cls\n\ndef visualize_data(data):\n image_ids = data.image_ids[:10]\n for image_id in image_ids:\n image = data.load_image(image_id)\n mask, class_ids = data.load_mask(image_id)\n #print(class_ids)\n\n make_save(\"debug/%s\" % image_id)\n visualize.display_top_masks(image, mask, class_ids, data.class_names, limit = 1)\n\ndef get_train_set():\n datadir=DATADIR\n data = MujocoData(datadir)\n data.load_mujoco(0, 8000)\n data.prepare()\n return data\n \ndef get_val_set():\n datadir=DATADIR\n data = MujocoData(datadir)\n data.load_mujoco(8000, 10000)\n #data.load_mujoco(0, 50)\n data.prepare()\n return data\n\ndef generate_wrapper(tid = None):\n import HER.envs\n import gym\n env = gym.make('active_pusher-v3')\n \n from renderer import Renderer\n renderer = Renderer(env)\n generator = GenerateData(renderer, datadir)\n generator.generate(count, tid)\n\nif __name__ == '__main__': \n\n do_generate = True\n do_vis = False\n count = 10000\n \n datadir=DATADIR\n \n if do_generate:\n if False:\n generate_wrapper()\n else:\n from multiprocessing import Process\n processes = []\n for j in range(NUMTHREADS):\n process = Process(target = lambda: generate_wrapper(j))\n process.start()\n processes.append(process)\n for process in processes:\n process.join()\n \n if do_vis:\n data = MujocoData(datadir)\n data.load_mujoco(0, count)\n data.prepare()\n\n visualize_data(data)\n","sub_path":"HER/rcnn/large_dataset.py","file_name":"large_dataset.py","file_ext":"py","file_size_in_byte":5478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"152426262","text":"from model.PDenseNet import PDenseNet18, PDenseNet34, PDenseNet50, PDenseNet101, PVGG\r\nfrom model.SANet import SANet\r\nfrom tool.config import opt\r\nfrom torch.utils.data import DataLoader, random_split\r\nfrom torchvision import transforms\r\nfrom tool.Loader import Loader, Normalize, ToTensor\r\nfrom Solver import Solver\r\n\r\n\r\ndef load_net(cuda=True):\r\n m_size = opt.m_size\r\n if m_size == '18':\r\n model = PDenseNet18()\r\n elif m_size == 34:\r\n model = PDenseNet34()\r\n elif m_size == 50:\r\n model = PDenseNet50()\r\n elif m_size == '101':\r\n model = PDenseNet101()\r\n elif m_size == 'PVGG':\r\n model = PVGG()\r\n else:\r\n print('模型错误')\r\n return -1\r\n if cuda:\r\n model.cuda()\r\n return model\r\n\r\n\r\ndef load_data():\r\n test_dataset = Loader(opt.test_iFname, opt.test_pFname,\r\n transform=transforms.Compose([\r\n Normalize(),\r\n ToTensor()])\r\n )\r\n testLoader = DataLoader(test_dataset, batch_size=1, shuffle=False)\r\n return testLoader\r\n\r\n\r\nif __name__ == '__main__':\r\n net = load_net()\r\n print('网络加载完成')\r\n loader = load_data()\r\n print('数据加载完成')\r\n solver = Solver(net, loader, model='test')\r\n solver.test()\r\n","sub_path":"ResNet-DC/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"328446380","text":"class Solution(object):\n def nthUglyNumber(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n if n <= 0:\n return -1\n i2 = i3 = i5 = 0\n k = [0] * n\n k[0] = 1\n for j in range(1, n):\n k[j] = min(k[i2] * 2, k[i3] * 3, k[i5] * 5)\n if k[j] == k[i2] * 2:\n i2 += 1\n if k[j] == k[i3] * 3:\n i3 += 1\n if k[j] == k[i5] * 5:\n i5 += 1\n # print(i2, i3, i5, k)\n return k[-1]\n\n\ntest = Solution()\nprint(test.nthUglyNumber(12))\n","sub_path":"python/264 Ugly Number II.py","file_name":"264 Ugly Number II.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"127228469","text":"\nimport fileinput\nimport numpy as np\nfrom scipy.spatial.distance import cityblock\n\n\ndef stdin2ndarray() :\n data = []\n for line in fileinput.input() :\n data.append(line.strip().split(\", \"))\n return np.array(data,dtype=int)\n\n\nif __name__ == \"__main__\":\n\n coordinates = stdin2ndarray()\n\n min_x = coordinates[:,0].min()\n min_y = coordinates[:,1].min()\n max_x = coordinates[:,0].max()\n max_y = coordinates[:,1].max()\n\n nwithin = 0\n for x in range(min_x, max_x+1):\n for y in range(min_y, max_y+1):\n d = np.array([cityblock([x, y], c) for c in coordinates])\n if d.sum() < 10000:\n nwithin += 1\n print(f\"Area {nwithin}\")\n","sub_path":"sgenheden-python/day6-part2.py","file_name":"day6-part2.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473278243","text":"# Pi Calculation using Gregory Series\n\ndef calculatePi(n):\n result = 0\n dividend = 1\n divisor = 1\n\n for i in range(n):\n result += dividend/divisor\n divisor += 2\n dividend = -dividend\n\n print(4*result)\n\n\ncalculatePi(6)\ncalculatePi(8)\n \n","sub_path":"HomeWork1/HW1.7.py","file_name":"HW1.7.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"303953336","text":"import numpy as np # knihovna NumPy\nimport sys # pro ukončení práce při chybném souboru\n\n\nclass Calculate:\n def __init__(self, molecules, periodic_table):\n self.molecules, self.output, atom_parameter, not_errors_molecules = molecules, [], {}, 0\n for molecule in self.molecules:\n try:\n \"\"\"příprava matic\"\"\"\n data_from_atoms, name, data_bond = [], molecule.name, []\n count = molecule.count_atoms\n degree_matrix = molecule.count_bond_matrix\n connectivity_matrix = molecule.bond_matrix\n identity_matrix = np.eye(count)\n \"\"\"výpočet S = D - A + I\"\"\"\n simplified_matrix = degree_matrix - connectivity_matrix + identity_matrix\n pt_electronegativity = np.zeros((count, 1))\n try:\n \"\"\"příprava vektoru s hodnotami elektronegativity z periodické tabulky \"\"\"\n for i, atom in enumerate(molecule.atoms):\n pt_electronegativity[i][0] = periodic_table[atom.element_symbol]\n data_from_atoms.append((atom.element_symbol, atom.bond))\n except IndexError:\n print(\"Can not calculate with \", name)\n continue\n not_errors_molecules += 1 # součet spočítaných molekul\n \"\"\"výpočet X = S^{-1} * X^{0}\"\"\"\n nk_electronegativity = np.linalg.solve(simplified_matrix, pt_electronegativity)\n \"\"\"výpočet X - X^{0}\"\"\"\n deviation_away_pt = nk_electronegativity-pt_electronegativity\n multiple = 1\n \"\"\"výpočet geometrického průměru\"\"\"\n for electroneg in pt_electronegativity:\n multiple = multiple * electroneg\n geometric_mean = multiple**(1/count)\n \"\"\"výpočet náboje\"\"\"\n charges = deviation_away_pt * (1/geometric_mean)\n self.output.append((name, count, data_from_atoms, charges))\n except KeyError:\n print(\"Something wrong with calculate\")\n sys.exit()\n print(\"Program calculated {} molecules.\".format(not_errors_molecules))\n\n def save_charges(self, file):\n data = self.output\n new_file = \"result/\" + file\n with open(new_file, \"w\") as f:\n for name, count, atoms, charges in data:\n print(\"{}\\n{}\".format(name, int(count)), file=f)\n for i, (atom, bond) in enumerate(atoms):\n print(\"{0:6d} {1:>2}{2} {3: f}\".format(i + 1, atom, bond, float(charges[i])), file=f)\n print(\"Now you can find charge for each element in file {}\".format(new_file))\n\n def give_result(self):\n return self.output\n","sub_path":"mgcm.py","file_name":"mgcm.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"368112215","text":"\"\"\"\nSetting common to reader and writer\n\"\"\"\n\nfrom datetime import timedelta\n\nPAYMENT_AMOUNT = 2 # in sats\n\nMAX_MEMO_SIZE = 600 # includes the length of the friendly prefix\nMAX_TITLE = 100\nMAX_CONTENT = MAX_MEMO_SIZE - MAX_TITLE # minus title, tags, etc...\n\nMAX_PAYREQ_SIZE = 2000 # pay_req includes memo and routing info\nFRIENDLY_PREFIX = \"ln.support\" # cannot have under-bars (_s)\n\nINVOICE_EXPIRY = 3600 # in seconds\nINVOICE_RETENTION = timedelta(weeks=1) # how long to keep invoice requests and invoices\n\n# Bounty\nAWARD_TIMEDELTA = timedelta(days=3)\nAWARD_TIMEDELTA = timedelta(seconds=30)\nCLAIM_TIMEDELTA = timedelta(days=7)\n","sub_path":"writer/project-basedir/biostar_writer/settings/base_common.py","file_name":"base_common.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"396808312","text":"import time\nfrom rllab.core.serializable import Serializable\nfrom numpy.linalg import norm\nfrom numpy import mean\nfrom numpy import std\nimport numpy as np\nimport csv, os\nimport scipy.misc as scm\n# import pickle\nimport tensorflow as tf\nfrom rllab.policies.uniform_control_policy import UniformControlPolicy\nfrom rllab.sampler.utils import rollout\nfrom railrl.policies.cmaes_icm import CMAESPolicy\n\nimport matplotlib.pyplot as plt\n\n\ndef save_data(file_name, ob, a, next_ob):\n\tfieldnames = [\"observation\", \"action\", \"next_observation\"]\n\tif not os.path.exists(file_name):\n\t\twith open(file_name, \"w+\") as f:\n\t\t\twriter = csv.DictWriter(f, fieldnames)\n\t\t\twriter.writeheader()\n\telse:\n\t\twith open(file_name, \"a+\") as f:\n\t\t\twriter = csv.DictWriter(f, fieldnames)\n\t\t\twriter.writerow({\n\t\t\t\t\"observation\": ob,\n\t\t\t\t\"action\": a,\n\t\t\t\t\"next_observation\": next_ob,\n\t\t\t})\n\n\ndef get_max_reward(env, policy, num_trajs=200):\n\tbest_reward = 0.0\n\tfor _ in range(num_trajs):\n\t\tinfo = rollout(env, policy)\n\t\tprint (\"Finished traj\", _)\n\t\tbest_reward = max(best_reward, np.sum(info['rewards']))\n\tprint (\"Max reward: \", best_reward)\n\ndef plot_action(env, policy, save_path, num_actions=1000):\n\tactions = np.zeros([num_actions, env.spec.action_space.flat_dim])\n\to = env.reset()\n\tfor i in range(num_actions):\n\t\ta, _ = policy.get_action(o)\n\t\tnext_o, r, d, env_info = env.step(a)\n\t\tactions[i, :] = a\n\t\tif d:\n\t\t\to = env.reset()\n\t\telse:\n\t\t\to = next_o\n\tnp.save(save_path, actions)\n\tprint (\"Saved action data\")\n\n\ndef test_state_hist(env):\n\tpolicy = UniformControlPolicy(env.spec)\n\t_states = []\n\to = env.reset()\n\ttry:\n\t\twhile True:\n\t\t\t_states.append(o)\n\t\t\ta, _ = policy.get_action(o)\n\t\t\tnext_o, r, d, env_info = env.step(a)\n\t\t\tif d:\n\t\t\t\to = env.reset()\n\t\t\telse:\n\t\t\t\to = next_o\n\texcept KeyboardInterrupt:\n\t\tstates = np.asarray(_states)\n\t\tsave_path = '/Users/dianchen/state.npy'\n\t\tnp.save(save_path, states)\n\t\t# pickle.dump(states, save_path)\n\t\tprint (\"State samples saved to {}\".format(save_path))\n\n\ndef test_icm_cmaes(encoder, inverse_model, forward_model, env, policy, sess):\n\tpolicy = CMAESPolicy(env.spec, encoder, inverse_model, forward_model, sess=sess)\n\to = env.reset()\n\twhile True:\n\t\ta, _ = policy.get_action([o], env=env)\n\t\tnext_o, r, d, env_info = env.step(a)\n\t\tif d:\n\t\t\to = env.reset()\n\t\telse:\n\t\t\to = next_o\n\t\tenv.render()\n\t\ttime.sleep(0.05)\n\n\ndef investigate_forward_loss(\n\t\t_encoder,\n\t\t_inverse_model,\n\t\t_forward_model,\n\t\tenv,\n\t\tpolicy,\n\t\tsess,\n\t\tnum_trajs=1,\n\t\tnum_top=10,\n\t\tdata_path='/tmp/data/',\n\t\tanimate=False\n\t):\n\t# Rebuild models\n\tact_space = env.action_space\n\tobs_space = env.observation_space\n\n\ts1_ph = tf.placeholder(tf.float32, [None] + list(obs_space.shape))\n\ts2_ph = tf.placeholder(tf.float32, [None] + list(obs_space.shape))\n\ta_ph = tf.placeholder(tf.float32, [None, act_space.flat_dim])\n\t\n\tencoder1 = _encoder.get_weight_tied_copy(observation_input=s1_ph)\n\tencoder2 = _encoder.get_weight_tied_copy(observation_input=s2_ph)\n\tinverse_model = _inverse_model.get_weight_tied_copy(feature_input1=encoder1.output, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfeature_input2=encoder2.output)\n\tforward_model = _forward_model.get_weight_tied_copy(feature_input=encoder1.output,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taction_input=a_ph)\n\n\tdef get_forward_loss(obs, next_obs, actions, normed=False):\n\t\tforward_loss = sess.run(\n\t\t\ttf.reduce_mean(tf.square(\n\t\t\t\tencoder2.output - forward_model.output\n\t\t\t), axis=1),\n\t\t\tfeed_dict={\n\t\t\t\ts1_ph: obs,\n\t\t\t\ts2_ph: next_obs,\n\t\t\t\ta_ph: actions\n\t\t\t}\n\t\t)\n\t\tif normed:\n\t\t\tnominator = sess.run(\n\t\t\t\ttf.reduce_mean(tf.square(\n\t\t\t\t\tencoder2.output - encoder1.output\n\t\t\t\t), axis=1),\n\t\t\t\tfeed_dict={\n\t\t\t\t\ts1_ph: obs,\n\t\t\t\t\ts2_ph: next_obs,\n\t\t\t\t\ta_ph: actions\n\t\t\t\t}\n\t\t\t)\n\t\t\treturn forward_loss / nominator\n\t\telse:\n\t\t\treturn forward_loss\n\n\t# Sample actions\n\tcon_obs = []\n\tcon_next_obs = []\n\tcon_actions = []\n\tnon_con_obs = []\n\tnon_con_next_obs = []\n\tnon_con_actions = []\n\tfor n in range(num_trajs):\n\t\tprint ('Start trajs %d' %n)\n\t\tob = env.reset()\n\t\tnext_ob = None\n\t\tfor t in range(env.wrapped_env._wrapped_env.env.spec.max_episode_steps):\n\t\t\taction, _ = policy.get_action(ob)\n\t\t\tnext_ob, reward, done, env_infos = env.step(action)\n\t\t\tif animate:\n\t\t\t\tenv.render()\n\t\t\tif env_infos['contact_reward']:\n\t\t\t\tcon_obs.append(ob)\n\t\t\t\tcon_next_obs.append(next_ob)\n\t\t\t\tcon_actions.append(action)\n\t\t\telse:\n\t\t\t\tnon_con_obs.append(ob)\n\t\t\t\tnon_con_next_obs.append(next_ob)\n\t\t\t\tnon_con_actions.append(action)\n\t\t\tif done:\n\t\t\t\tob = env.reset()\n\t\t\telse:\n\t\t\t\tob = next_ob\n\n\t# print (con_obs)\n\tcontacts_fw_losses = list(get_forward_loss(con_obs, con_next_obs, con_actions))\n\tnon_contacts_fw_losses = list(get_forward_loss(non_con_obs, non_con_next_obs, non_con_actions))\n\tfw_losses = contacts_fw_losses + non_contacts_fw_losses\n\tobs = con_obs + non_con_obs\n\tnext_obs = con_next_obs + non_con_next_obs\n\tnp_obs = np.array(obs)\n\tnp_next_obs = np.array(next_obs)\n\tindexes = np.array(fw_losses).argsort()[-num_top:][::-1]\n\ttop_obs = np_obs[indexes]\n\ttop_next_obs = np_next_obs[indexes]\n\n\tfor i, ob, next_ob in zip(range(num_top), top_obs, top_next_obs):\n\t\tenv.reset()\n\t\tqpos_idx = env.wrapped_env._wrapped_env.env.env.init_qpos.shape[0]\n\t\tenv.wrapped_env._wrapped_env.env.env.set_state(ob[:qpos_idx], ob[qpos_idx:])\n\t\timg_ob = env.wrapped_env._wrapped_env.env.env.render(mode='rgb_array')\n\t\tenv.wrapped_env._wrapped_env.env.env.set_state(next_ob[:qpos_idx], next_ob[qpos_idx:])\n\t\timg_next_ob = env.wrapped_env._wrapped_env.env.env.render(mode='rgb_array')\n\t\timg = np.concatenate([img_ob, img_next_ob], axis=1)\n\t\tscm.imsave(data_path+'ob_pair{}.png'.format(i), img)\n\t\tprint ('Saved data {}'.format(i))\n\n\n\tnp.save(data_path+'con_int_rew.npy', contacts_fw_losses)\n\tnp.save(data_path+'noncon_int_rew.npy', non_contacts_fw_losses)\n\tprint (\"Saved losses data\")\n\ndef plot_forward(_encoder, _inverse_model, _forward_model, env, policy, sess):\n\tfrom railrl.misc.pyhelper_fns.vis_utils import MyAnimationMulti\n\tvis_tool = MyAnimationMulti(None, numPlots = 2, isIm = [1,0])\n\t# Rebuild models\n\tact_space = env.action_space\n\tobs_space = env.observation_space\n\n\ts1_ph = tf.placeholder(tf.float32, [None] + list(obs_space.shape))\n\ts2_ph = tf.placeholder(tf.float32, [None] + list(obs_space.shape))\n\ta_ph = tf.placeholder(tf.float32, [None, act_space.flat_dim])\n\t\n\tencoder1 = _encoder.get_weight_tied_copy(observation_input=s1_ph)\n\tencoder2 = _encoder.get_weight_tied_copy(observation_input=s2_ph)\n\tinverse_model = _inverse_model.get_weight_tied_copy(feature_input1=encoder1.output, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfeature_input2=encoder2.output)\n\tforward_model = _forward_model.get_weight_tied_copy(feature_input=encoder1.output,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taction_input=a_ph)\n\n\tdef get_forward_loss(obs, next_obs, actions):\n\t\tforward_loss = sess.run(\n\t\t\ttf.reduce_mean(tf.square(\n\t\t\t\tencoder2.output - forward_model.output\n\t\t\t), axis=1),\n\t\t\tfeed_dict={\n\t\t\t\ts1_ph: obs,\n\t\t\t\ts2_ph: next_obs,\n\t\t\t\ta_ph: actions\n\t\t\t}\n\t\t)\n\t\treturn forward_loss\n\n\t# Call rllab rollout for parallel\n\twhile True:\n\t\tob = env.reset()\n\t\tnext_ob = None\n\t\tx = []\n\t\ty = []\n\t\tfor t in range(env.wrapped_env._wrapped_env.env.spec.max_episode_steps):\n\t\t\tprint(t)\n\t\t\taction, _ = policy.get_action(ob)\n\t\t\tnext_ob, reward, done, env_infos = env.step(action)\n\t\t\t# import pdb; pdb.set_trace()\n\t\t\timage = env._wrapped_env._wrapped_env.env.env.render(mode='rgb_array')\n\t\t\tforward_loss = get_forward_loss([ob], [next_ob], [action])\n\t\t\tif done:\n\t\t\t\tob = env.reset()\n\t\t\telse:\n\t\t\t\tob = next_ob\n\n\t\t\tx.append(t)\n\t\t\ty.append(forward_loss)\n\t\t\tvis_tool._display([image, y])\n\n\ndef get_time_to_first_contact(env, policy, is_random=False, num_trajs=100):\n\timport itertools\n\ttime_contact = []\n\tif is_random:\n\t\tfrom rllab.policies.uniform_control_policy import UniformControlPolicy\n\t\tpolicy = UniformControlPolicy(env.spec)\n\tprint (\"Using {}\".format(policy))\n\tfor traj_i in range(num_trajs):\n\t\tobs = env.reset()\n\t\tprint (\"Start traj {}\".format(traj_i))\n\t\tfor t in itertools.count():\n\t\t\taction, _ = policy.get_action(obs)\n\t\t\tobs, reward, done, env_info = env.step(action)\n\t\t\tif env_info['contact_reward'] > 0 or done:\n\t\t\t\ttime_contact.append(t)\n\t\t\t\tbreak\n\t# plt.hist(time_contact)\n\t# plt.title(\"Time to first contact over {} trajectories\".format(num_trajs))\n\t# plt.show()\n\tdata_path = input(\"Where do you want to save it? \\n\")\n\tnp.save(data_path, time_contact)\n\tprint (\"Data saved\")\n\tprint (\"Mean time to first contact: {}, median:{}, std:{} for {}, ({} trajectories)\".format(np.mean(time_contact), np.median(time_contact), np.std(time_contact), policy, num_trajs))\n\n\ndef episode_reward(env, policy, is_random=False):\n\timport itertools\n\tmean_reward = []\n\tif is_random:\n\t\tfrom rllab.policies.uniform_control_policy import UniformControlPolicy\n\t\tpolicy = UniformControlPolicy(env.spec)\n\tprint (\"Using {}\".format(policy))\n\tfor traj_i in range(num_trajs):\n\t\tobs = env.reset()\n\t\tprint (\"Start traj {}\".format(traj_i))\n\t\trewards\n\t\tfor t in itertools.count():\n\t\t\taction, _ = policy.get_action(obs)\n\t\t\tobs, reward, done, env_info = env.step(action)\n\t\t\tif done:\n\t\t\t\tbreak\n\tplt.his\n\tprint (\"Mean time to first contact: {} for {}, ({} trajectories)\".format(np.mean(time_contact), policy, num_trajs))\n\ndef investigate_inverse_loss(\n\t\t_encoder, \n\t\t_inverse_model, \n\t\t_forward_model, \n\t\tenv, \n\t\tpolicy, \n\t\tsess, \n\t\timg_path='/tmp/img', \n\t\tnum_trajs=100, \n\t\tnum_top=10,\n\t\tanimate=False\n\t):\n\t# Rebuild models\n\tact_space = env.action_space\n\tobs_space = env.observation_space\n\n\ts1_ph = tf.placeholder(tf.float32, [None] + list(obs_space.shape))\n\ts2_ph = tf.placeholder(tf.float32, [None] + list(obs_space.shape))\n\ta_ph = tf.placeholder(tf.float32, [None, act_space.flat_dim])\n\t\n\tencoder1 = _encoder.get_weight_tied_copy(observation_input=s1_ph)\n\tencoder2 = _encoder.get_weight_tied_copy(observation_input=s2_ph)\n\tinverse_model = _inverse_model.get_weight_tied_copy(feature_input1=encoder1.output, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfeature_input2=encoder2.output)\n\tforward_model = _forward_model.get_weight_tied_copy(feature_input=encoder1.output,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taction_input=a_ph)\n\tdef get_inverse_loss(obs, next_obs, actions):\n\t\treturn sess.run(\n\t\t\ttf.reduce_mean(\n\t\t\t\ttf.square(a_ph - inverse_model.output),\n\t\t\t\taxis=1\n\t\t\t), \n\t\t\tfeed_dict={\n\t\t\t\ts1_ph: obs,\n\t\t\t\ts2_ph: next_obs,\n\t\t\t\ta_ph: actions\n\t\t\t}\n\t\t)\n\n\t# Sample trajectories\n\tobs = []\n\tnext_obs = []\n\tactions = []\n\t# Call rllab rollout for parallel\n\tfor n in range(num_trajs):\n\t\tprint ('Start trajs %d' %n)\n\t\tob = env.reset()\n\t\tnext_ob = None\n\t\tfor t in range(env.wrapped_env._wrapped_env.env.spec.max_episode_steps):\n\t\t\taction, _ = policy.get_action(ob)\n\t\t\tnext_ob, reward, done, env_infos = env.step(action)\n\t\t\tif animate:\n\t\t\t\tenv.render()\n\t\t\tobs.append(ob)\n\t\t\tnext_obs.append(next_ob)\n\t\t\tactions.append(action)\n\t\t\tif done:\n\t\t\t\tob = env.reset()\n\t\t\telse:\n\t\t\t\tob = next_ob\n\n\tinverse_loss = get_inverse_loss(obs, next_obs, actions)\n\n\tnp_obs = np.array(obs)\n\tnp_next_obs = np.array(next_obs)\n\tnp_actions = np.array(actions)\n\tindexes = inverse_loss.argsort()[-num_top:][::-1]\n\ttop_obs = np_obs[indexes]\n\ttop_next_obs = np_next_obs[indexes]\n\ttop_actions = np_actions[indexes]\n\n\tfor i, ob, next_ob, a in zip(range(num_top), top_obs, top_next_obs, top_actions):\n\t\tenv.reset()\n\t\tenv.wrapped_env._wrapped_env.env.env.set_state(ob[:28], ob[28:])\n\t\timg_ob = env.wrapped_env._wrapped_env.env.env.render(mode='rgb_array')\n\t\tenv.wrapped_env._wrapped_env.env.env.set_state(next_ob[:28], next_ob[28:])\n\t\timg_next_ob = env.wrapped_env._wrapped_env.env.env.render(mode='rgb_array')\n\t\timg = np.concatenate([img_ob, img_next_ob], axis=1)\n\t\tscm.imsave(img_path+'ob_pair{}.png'.format(i), img)\n\t\tnp.save(img_path+'torc_{}.npy'.format(i), a)\n\t\tprint ('Saved data {}'.format(i))\n\n\n\ndef test_icm(_encoder, _inverse_model, _forward_model, env, policy, sess, animate=False):\n\t# Rebuild models\n\tact_space = env.action_space\n\tobs_space = env.observation_space\n\n\ts1_ph = tf.placeholder(tf.float32, [None] + list(obs_space.shape))\n\ts2_ph = tf.placeholder(tf.float32, [None] + list(obs_space.shape))\n\ta_ph = tf.placeholder(tf.float32, [None, act_space.flat_dim])\n\t\n\tencoder1 = _encoder.get_weight_tied_copy(observation_input=s1_ph)\n\tencoder2 = _encoder.get_weight_tied_copy(observation_input=s2_ph)\n\tinverse_model = _inverse_model.get_weight_tied_copy(feature_input1=encoder1.output, \n\t\t\t\t\t\t\t\t\t\t\t\t\t\tfeature_input2=encoder2.output)\n\tforward_model = _forward_model.get_weight_tied_copy(feature_input=encoder1.output,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\taction_input=a_ph)\n\n\tdef apply_action(env, a):\n\t\told_data = env.wrapped_env.env.env.data\n\t\told_qpos = old_data.qpos.flatten()\n\t\told_qvel = old_data.qvel.flatten()\n\t\tnext_o, r, d, env_info = env.step(a)\n\t\tenv.wrapped_env.env.env.set_state(old_qpos, old_qvel)\n\t\tenv.wrapped_env.env._elapsed_steps -= 1\n\t\treturn next_o\n\n\tdef get_forward_loss(ob, next_ob, a):\n\t\tforward_loss = tf.nn.l2_loss(encoder2.output - forward_model.output)\n\t\treturn sess.run(forward_loss, {\n\t\t\t\tencoder1.observation_input: [ob],\n\t\t\t\tencoder2.observation_input: [next_ob],\n\t\t\t\tforward_model.action_input: [a],\n\t\t\t})\n\n\tdef get_pred_f2(f1, a):\n\t\treturn sess.run(forward_model.output, { forward_model.feature_input: [f1],\n\t\t\t\t\t\t\t\t\t\t\t\tforward_model.action_input: [a] })\n\n\to = env.reset()\n\tf_difference = [] # Difference of f1 - f2\n\tpred_difference = [] # Difference of f2_pred - f2\n\ttry:\n\t\tprint (\"Press ctrl+c to exit\")\n\t\twhile True:\n\t\t\ta, _ = policy.get_action(o)\n\t\t\tf1 = _encoder.get_features(o)\n\t\t\t# f2_pred = get_pred_f2(f1, a)\n\t\t\tf2 = _encoder.get_features(apply_action(env, a))\n\t\t\t# f_difference.append(norm(f1 - f2)**2/2)\n\t\t\tpred_difference.append(get_forward_loss(o, apply_action(env, a), a))\n\t\t\tnext_o, r, d, env_info = env.step(a)\n\t\t\tif d:\n\t\t\t\to = env.reset()\n\t\t\telse:\n\t\t\t\to = next_o\n\t\t\tif animate:\n\t\t\t\tenv.render()\n\t\t\t\ttime.sleep(0.05)\n\n\texcept KeyboardInterrupt:\n\t\tprint (\"\\n----------\")\n\t\tprint (\"Collected {} samples\".format(len(f_difference)))\n\t\tprint (\"Mean of f1 - f2 difference: {}\".format(mean(f_difference)))\n\t\tprint (\"Std of f1 - f2 difference: {}\".format(std(f_difference)))\n\t\tprint (\"Mean of f2pred - f2 difference: {}\".format(mean(pred_difference)))\n\t\tprint (\"Std of f2pred - f2 difference: {}\".format(std(pred_difference)))\n\n\n\n","sub_path":"railrl/misc/.~c9_invoke_fZvbP.py","file_name":".~c9_invoke_fZvbP.py","file_ext":"py","file_size_in_byte":13961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"492503943","text":"import os\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nfrom src.utilities.memory_maker import MemoryMaker\n\n\nclass GenFiles:\n frame = 'frame_{}_{:07}.npy'\n numeric = 'numeric_{}_{:07}.npy'\n diff = 'diff_{}_{:07}.npy'\n\n steer_sampling = 'steer_sample_{}.npy'\n gear_sampling = 'gear_sample_{}.npy'\n\n\nclass Generator:\n def __init__(self, config, memory_tuple=None, base_path=None, eval_mode=False, batch_size=32, column_mode='all', test_size=0.2, index_override=None):\n # TODO the whole initialization is a bit of a mess now, should refactor\n if memory_tuple is not None:\n self.__memory = MemoryMaker(config, memory_tuple)\n self.memory_string = 'n{}_m{}'.format(*memory_tuple)\n else:\n self.__memory = MemoryMaker(config, (config.m_length, config.m_interval))\n self.memory_string = 'n{}_m{}'.format(config.m_length, config.m_interval)\n\n if base_path is not None:\n self.session_mode = False\n self.path = base_path + self.memory_string + '/'\n elif eval_mode:\n self.session_mode = True\n self.path = config.path_to_training + self.memory_string + '_val/'\n else:\n self.session_mode = True\n self.path = config.path_to_session_files\n\n self.batch_size = batch_size\n self.column_mode = column_mode\n\n if index_override is not None:\n indexes = index_override\n else:\n indexes = self.__apply_upsampling()\n self.train_indexes, self.test_indexes = train_test_split(indexes, test_size=test_size, shuffle=True)\n\n self.train_batch_count = len(self.train_indexes) // self.batch_size\n self.test_batch_count = len(self.test_indexes) // self.batch_size\n\n def __apply_upsampling(self):\n indexes = np.arange(self.__count_instances())\n if self.session_mode:\n # dont use any sampling, just use everything\n return indexes\n\n if self.column_mode == 'steer':\n sampling_multipliers = np.load(self.path + GenFiles.steer_sampling.format(self.memory_string), allow_pickle=True)\n assert indexes.shape[0] == sampling_multipliers.shape[0], 'Indexes and sampling shape mismatch!'\n elif self.column_mode == 'gear':\n sampling_multipliers = np.load(self.path + GenFiles.gear_sampling.format(self.memory_string), allow_pickle=True)\n assert indexes.shape[0] == sampling_multipliers.shape[0], 'Indexes and sampling shape mismatch!'\n elif self.column_mode == 'all':\n return indexes\n else:\n raise ValueError('Misconfigured generator column mode!')\n\n return np.repeat(indexes, sampling_multipliers)\n\n def __count_instances(self):\n return len([fn for fn in os.listdir(self.path) if fn.startswith('frame_')])\n\n def get_shapes(self):\n frame, numeric, diff = self.load_single_pair(0)\n\n if not hasattr(diff, '__len__'):\n return frame.shape, numeric.shape, 1\n\n return frame.shape, numeric.shape, diff.shape[0]\n\n def generate(self, data='train'):\n batch_count, indexes = self.__evaluate_indexes(data)\n\n while True:\n np.random.shuffle(indexes)\n\n for i in range(batch_count):\n batch_indexes = indexes[i * self.batch_size:(i + 1) * self.batch_size]\n x_frame, x_numeric, y = self.__load_batch(batch_indexes)\n\n yield x_frame, y\n\n def generate_with_numeric(self, data='train'):\n batch_count, indexes = self.__evaluate_indexes(data)\n\n while True:\n np.random.shuffle(indexes)\n\n for i in range(batch_count):\n batch_indexes = indexes[i * self.batch_size:(i + 1) * self.batch_size]\n x_frame, x_numeric, y = self.__load_batch(batch_indexes)\n\n yield (x_frame, x_numeric), y\n\n def __evaluate_indexes(self, data):\n if data == 'train':\n indexes = self.train_indexes\n batch_count = self.train_batch_count\n elif data == 'test':\n indexes = self.test_indexes\n batch_count = self.test_batch_count\n else:\n raise ValueError('Data type is not train or test!')\n return batch_count, indexes\n\n def generate_single_train(self, shuffle=True):\n batch_count, indexes = self.__evaluate_indexes('train')\n while True:\n if shuffle:\n np.random.shuffle(indexes)\n\n for index in indexes:\n x_frame, x_numeric, y = self.load_single_pair(index)\n yield x_frame, y\n\n def generate_single_train_with_numeric(self, shuffle=True):\n batch_count, indexes = self.__evaluate_indexes('train')\n while True:\n if shuffle:\n np.random.shuffle(indexes)\n\n for index in indexes:\n x_frame, x_numeric, y = self.load_single_pair(index)\n yield x_frame, x_numeric, y\n\n def generate_single_test(self, shuffle=True):\n batch_count, indexes = self.__evaluate_indexes('test')\n while True:\n if shuffle:\n np.random.shuffle(indexes)\n\n for index in indexes:\n x_frame, x_numeric, y = self.load_single_pair(index)\n yield x_frame, y\n\n def generate_single_test_with_numeric(self, shuffle=True):\n batch_count, indexes = self.__evaluate_indexes('test')\n while True:\n if shuffle:\n np.random.shuffle(indexes)\n\n for index in indexes:\n x_frame, x_numeric, y = self.load_single_pair(index)\n yield x_frame, x_numeric, y\n\n def __load_batch(self, batch_indexes):\n frames = []\n numerics = []\n diffs = []\n\n for i in batch_indexes:\n frame, numeric, diff = self.load_single_pair(i)\n\n frames.append(frame)\n numerics.append(numeric)\n diffs.append(diff)\n\n return np.array(frames), np.array(numerics), np.array(diffs)\n\n def load_single_pair(self, index):\n frame = np.load(self.path + GenFiles.frame.format(self.memory_string, index), allow_pickle=True)\n numeric = np.load(self.path + GenFiles.numeric.format(self.memory_string, index), allow_pickle=True)\n diff = np.load(self.path + GenFiles.diff.format(self.memory_string, index), allow_pickle=True)\n\n if self.column_mode == 'steer':\n # steering + throttle\n numeric = self.__memory.columns_from_memorized(numeric, columns=(1, 2,))\n # steering + throttle\n diff = diff[1:3]\n elif self.column_mode == 'throttle':\n pass\n elif self.column_mode == 'gear':\n # gear\n numeric = self.__memory.columns_from_memorized(numeric, columns=(0,))\n diff = diff[0]\n elif self.column_mode == 'all':\n numeric = self.__memory.columns_from_memorized(numeric, columns=(0, 1, 2,))\n diff = diff[0:3]\n else:\n raise ValueError('Misconfigured generator column mode!')\n\n return frame, numeric, diff\n","sub_path":"src/learning/training/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":7176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"162097813","text":"from django.conf.urls import url\nfrom .views import (\n StartLiveStreamView,\n GetTokenPublisherView,\n GetTokenSubscriberView,\n VoteView,\n StartArchiveView,\n EndEventView,\n SavedVideoView\n)\n\nurlpatterns = [\n url(r'^startlivestream/$', StartLiveStreamView.as_view(), name='session'),\n url(r'^gettokenpublisher/$',\n GetTokenPublisherView.as_view(),\n name='publisher'),\n url(r'^gettokensubscriber/$',\n GetTokenSubscriberView.as_view(),\n name='subscriber'),\n url(r'^vote/$', VoteView.as_view(), name='vote'),\n url(r'^startarchive/$', StartArchiveView.as_view(), name='startarchive'),\n url(r'^endevent/$', EndEventView.as_view(), name='endevent'),\n url(r'^savedvideo/$',\n SavedVideoView.as_view(),\n name='savedvideos'),\n]\n","sub_path":"channelshowdown/livestream/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"245616156","text":"from enum import Enum, auto\n\n\nclass YamlObject:\n \"\"\"\n Class which represents YamlObject with form of object, not normalized\n \"\"\"\n def __init__(self, data):\n self._data = data\n\n # def from_string(self, string):\n # \"\"\"Converts string to YamlObject\n # Gets: string\n # Returns: YamlObject\n # \"\"\"\n # return yaml_object\n\n def to_string(self, tabs=0):\n \"\"\"Converts YamlObject to string\n Gets: self\n Returns: string\n \"\"\"\n return self._data.to_string(tabs)\n\n def to_normal(self):\n \"\"\"Converts YamlObject to normal python object\n Gets: YamlObject\n Returns: normal value\n \"\"\"\n return self._data.normalized()\n\n def from_normal(normal):\n \"\"\"Converts normal python object to YamlObject\n Gets: normal value\n Returns: YamlObject\n \"\"\"\n return YamlObject(Data.from_normal(normal))\n\n\nclass Data:\n def __init__(self, data_type, data):\n self._data, self._data_type = data, data_type\n\n def get_name(self):\n return self._name\n\n def normalized(self):\n if self._data_type == DataType.NULL:\n return None\n elif self._data_type == DataType.BOOL:\n return bool(self._data)\n elif self._data_type == DataType.INT_8:\n return oct(self._data)\n elif self._data_type == DataType.INT_10:\n return int(self._data)\n elif self._data_type == DataType.INT_16:\n return int(self._data, 16)\n elif self._data_type == DataType.FLOAT:\n return float(self._data)\n elif self._data_type == DataType.STR:\n return str(self._data)\n elif self._data_type == DataType.SEQ:\n return [val.normalized() for val in self._data]\n elif self._data_type == DataType.MAP:\n return dict((key, val.normalized())\n for (key, val) in self._data.items())\n\n def from_normal(obj):\n data_type = DataType.to_type(obj)\n data = obj\n if data_type == DataType.SEQ:\n data = [Data.from_normal(val) for val in obj]\n elif data_type == DataType.MAP:\n data = dict((key, Data.from_normal(val))\n for (key, val) in obj.items())\n return Data(data_type, data)\n\n def to_string(self, tabs=0, pre_map=''):\n def pre(tabs):\n return \" \" * tabs\n\n if ((self._data_type == DataType.SEQ or\n self._data_type == DataType.MAP) and len(self._data) == 0):\n return \"[]\" if self._data_type == DataType.SEQ else \"{}\"\n elif self._data_type == DataType.SEQ:\n return '' if tabs == 0 else '\\n' + '\\n'.join(\n [\"{}- {}\".format(pre(tabs - 1),\n val.to_string(tabs))\n for val in self._data]) + '\\n'\n elif self._data_type == DataType.MAP:\n return '\\n{}'.format(pre(tabs)).join(\n [\"{}:{}\".format(key, val.to_string(tabs + 1, pre_map=' '))\n for (key, val) in self._data.items()])\n elif self._data_type == DataType.NULL:\n return pre_map + \"null\"\n elif self._data_type == DataType.STR:\n if len(self._data.split('\\n')) > 1:\n return \" |\\n\" + '\\n'.join(pre(tabs + 1) + val\n for val in self._data.split('\\n'))\n else:\n return pre_map + self._data\n elif self._data_type == DataType.INT_8:\n return pre_map + str(oct(self._data))\n elif self._data_type == DataType.INT_16:\n return pre_map + str(hex(self._data))\n else:\n return pre_map + str(self._data)\n\n\nclass DataType(Enum):\n NULL = auto()\n BOOL = auto()\n INT_10 = auto()\n INT_8 = auto()\n INT_16 = auto()\n FLOAT = auto()\n STR = auto()\n SEQ = auto()\n MAP = auto()\n\n def is_hex(s):\n try:\n int(s, 16)\n return True\n except ValueError:\n return False\n\n def to_type(value):\n data_type = DataType.NULL\n if isinstance(value, bool):\n data_type = DataType.BOOL\n elif isinstance(value, int):\n data_type = DataType.INT_10\n elif isinstance(value, float):\n data_type = DataType.FLOAT\n elif isinstance(value, str):\n data_type = DataType.STR\n elif isinstance(value, type([])):\n data_type = DataType.SEQ\n elif isinstance(value, type({})):\n data_type = DataType.MAP\n return data_type\n\n\nif __name__ == \"__main__\":\n print(\"<<<>>>\")\n a = {\"int\": 666,\n \"float\": 666.777,\n \"string\": \"String\",\n \"array\": [\"String\", 0o666, {\"1\": True, \"2\": [0x666, 0o777]}],\n \"empty seq\": [],\n \"empty map\": {}}\n print(\"<>\")\n print(a)\n yaml = YamlObject.from_normal(a)\n print(\"\\n<>\")\n print(yaml.to_string())\n print(\"\\n<>\")\n print(yaml.to_normal())\n print(\"\\n<<<>>>\")\n","sub_path":"lab-4/yaml_lib/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"61296851","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nScript Header\n\n$Id: cmCC26586_3pcc_BS_Device_management_26_SharedLineOrigination\n\nCopyright (c) 2014 Cisco Systems, Inc.\n\nName:\n cmCC26586_3pcc_BS_Device_management_26_SharedLineOrigination.py\n\nPurpose:\n This test case verifies the DUT is able to originate a call on\n a shared line. This test case applies only if the DUT supports\n BroadWorks Shared Call Appearance (SCA).\n\nAuthor:\n Yashashwini M B(ymuddena@cisco.com)\n\nReferences:\n US26586\n\nDescription:\n Originate a call from the DUT’s shared line to BroadWorks User E.\n Answer the call. Disconnect the call from the DUT.\n\nTest bed requirement:\n 1. 3 3pcc phones\n 2. 1 phone should register successfully with private line\n 3. Other 2 Phones should register successfully with shared line.\n\nTest Steps:\n 1. Originate a call from Phone 1 to Phone 3\n 2. Phone 3 answers the call\n 3. Phone 1 hangs up\nVerify the following:\n 1. The call is completed successfully.\n 2. Phone 1 primary line visual indicator shows the status of the shared\n line call.\n 3. Ensure that the DUT sends SUBSCRIBE for SCA on start-up\n\nKnown Bugs:\n\nEnd of Header\n\"\"\"\nimport tng\nimport logging\nfrom tng_sl.device.endpoint.synergylite.synergylite_3pcc_extended\\\n import wait_for_ccapi_call_states, wait_for_call_appearance_states\nfrom tng.frontend.timing import wait\nfrom tng_sl.contrib.mpp.phone_line_reg_helper import PhoneLineRegHelper\nfrom tng_sl.contrib.mpp.phone_line_reg_helper import PhoneConfigHelper\nfrom tng_sl.contrib.mpp.broadsoft_login_helper import BroadsoftLoginHelper\nfrom tng_sl.contrib.mpp.tshark_helper import TsharkHelper\nfrom tng_sl.contrib.setup_helper import SetupHelpersTestCase\n\nlog = logging.getLogger('SharedLineOrigination')\n\n\nclass SharedLineOrigination(SetupHelpersTestCase, tng.api.TestCase):\n\n helpers = (\n PhoneConfigHelper, BroadsoftLoginHelper, PhoneLineRegHelper,\n TsharkHelper)\n helper_num_devices = 3\n\n def setUp(self):\n log.info(\"Start of setUp method\")\n\n self.proxy = self.phone_data['proxy']\n self.serverproxy = self.toolkit.get_test_env_info(\n section='bsoft', parameter_name=\"as_ip_addr\")\n self.shared_userID = '{}{}'.format(self.user_id1, 'a')\n self.device_type = 'Cisco-Hybrid{}'.format(\n self.oPhone1.get_web_status('Product_Name')[2:])\n self.device_mac = self.oPhone1.ui.get_web_parameter_http(\n 'Status', 'MAC Address')\n self.default_profile, self.line_port, self.domain = (\n self.bsoft_web.get_default_profile_details(\n 'group admin', self.user_id1))\n self.profile_type1 = self.oPhone1.ui.get_web_parameter_http(\n 'Status', 'Product Name')\n\n self.profile_name = '{}{}'.format(self.profile_type1, self.user_id1)\n self.profile_type2 = 'Cisco-Hybrid-{}'.format(self.profile_type1[3:])\n\n log.info(\"Configure Shared line on Phone1\")\n self.shared_name = self.bsoft_web.configure_shared_line(\n shared_number=self.shared_userID, device_type=self.device_type,\n user_phone_num=self.user_id1)\n\n def delete_sharedline():\n log.info(\"Delete configured Shared line\")\n self.bsoft_web.delete_shared_line(\n user_phone_num=self.user_id1, shared_name=self.shared_name)\n\n self.addCleanup(delete_sharedline)\n\n # Create_Device_profile\n log.info(\"Creating device profile\")\n self.bsoft_web.grp_admin_create_device_identity_profile(\n self.profile_name, self.profile_type2, self.device_mac,\n account_type=\"group admin\", user_phone_num=self.user_id1,\n devicedomain=self.proxy, extension=False)\n wait(5, \" Wait for 5 sec\")\n set_profile_name = '{} (Group)'.format(self.profile_name)\n\n self.addCleanup(\n self.bsoft_web.delete_device_profile, self.profile_name)\n\n def broadsoft_cleanup():\n self.bsoft_web.grp_admin_set_device_identity_profile(\n self.default_profile, self.line_port, 'group admin',\n self.domain)\n\n self.addCleanup(broadsoft_cleanup)\n\n # Set the Device profile type\n log.info(\"Setting device profile\")\n self.bsoft_web.grp_admin_set_device_identity_profile(\n set_profile_name, self.user_id1, 'group admin', self.proxy)\n self.file_name = self.profile_type1[3:] + '.xml'\n\n xml_filename = self.bsoft_web.get_device_profile_rule(\n self.profile_name, self.file_name)\n self.profile_rule = '{}'.format(xml_filename)\n log.info(\"Provisioning profile rule\")\n self.oPhone1.ui.set_web_parameter_http(\n profile_rule=[\n 'Provisioning', 'Profile Rule', self.profile_rule])\n wait(10, \"Phone to be stable after resync\")\n\n log.info(\"End of setUp method\")\n\n def test_shared_line_origination(self):\n\n log.info(\"Start of test_shared_line_origination\")\n\n log.info('Start tshark on linux')\n filter_cmd = (\n 'port sip and (host {} or host {})'.format(\n self.oPhone1.ip, self.oPhone2.ip))\n log.info('Start tshark on linux with filter {}'.format(filter_cmd))\n capture_file = self.tshark.tshark_start(filter_cmd)\n\n log.info(\"Configure shared line on Phone1 and Phone2\")\n self.oPhone1.set_shared_extension()\n self.oPhone2.set_shared_extension()\n self.oPhone2.set_shared_line(self.shared_userID)\n wait(3, \"wait for 3 seconds\")\n\n self.tshark.tshark_stop()\n\n log.info(\n \"Phone1 dials Phone3 number: {}\".format(self.user_id3))\n self.oPhone1.ccapi.dial('null', self.user_id3, '', 1, 0, 1)\n wait_for_ccapi_call_states(\n self.devices, (\"PROCEEDING\", \"IDLE\", \"RINGING\"))\n wait_for_call_appearance_states(\n (self.oPhone1, self.oPhone2), (\"PROGRESSING\", \"PROGRESSING\"))\n\n log.info(\"Phone3 receives the call\")\n self.oPhone3.ccapi.accept(\"0000\")\n # check phones 1&3 are in connected\n wait_for_ccapi_call_states(\n self.devices, (\"CONNECTED\", \"IDLE\", \"CONNECTED\"))\n wait_for_call_appearance_states(\n (self.oPhone1, self.oPhone2), (\"ACTIVE\", \"ACTIVE\"))\n\n log.info(\"Check Phone1's SCA line lamp is STEADY RED\")\n self.verify_shared_lamp(\n phone=self.oPhone1, line='LINE1', ledColor='RED',\n ledCadence='STEADY')\n log.info(\"Check Phone2's SCA line lamp is BLINK_BLINK RED\")\n self.verify_shared_lamp(\n phone=self.oPhone2, line='LINE1', ledColor='RED',\n ledCadence='BLINK_BLINK')\n\n log.info(\"Phone1 hangs up call\")\n self.oPhone1.ccapi.hangUp('0000')\n wait_for_ccapi_call_states(\n (self.oPhone1, self.oPhone2, self.oPhone3),\n (\"IDLE\", \"IDLE\", \"IDLE\"))\n\n # Tshark analysis\n subscribe_cseq_1, subscribe_call_id_1 = (\n self.tshark.tshark_get_string_cseq_call_id(\n capture_file, src_ip=self.oPhone1.ip, dst_ip=self.serverproxy,\n search_string='call-info', method='SUBSCRIBE'))\n\n log.info(\"Phone 1(Primary line) sends a SUBSCRIBE for call info\")\n self.tshark.tshark_check_string_in_message(\n capture_file, method='SUBSCRIBE', search_string='call-info',\n src_ip=self.oPhone1.ip, dst_ip=self.serverproxy,\n cseq=subscribe_cseq_1, call_id=subscribe_call_id_1,\n header='event')\n\n log.info(\"Phone 2(Shared line) sends a SUBSCRIBE for call info\")\n subscribe_cseq_2, subscribe_call_id_2 = (\n self.tshark.tshark_get_string_cseq_call_id(\n capture_file, src_ip=self.oPhone2.ip, dst_ip=self.serverproxy,\n search_string='call-info', method='SUBSCRIBE'))\n\n self.tshark.tshark_check_string_in_message(\n capture_file, method='SUBSCRIBE', search_string='call-info',\n src_ip=self.oPhone2.ip, dst_ip=self.serverproxy,\n cseq=subscribe_cseq_2, call_id=subscribe_call_id_2,\n header='event')\n\n log.info(\"End of test_shared_line_origination\")\n\n def verify_shared_lamp(self, phone, line, ledColor, ledCadence):\n output = phone.ccapi.get_led_state(line)\n for ledColor_ledCadence in ledColor, ledCadence:\n self.assertIn(ledColor_ledCadence, str(output))\n log.info(\n \"The color of SCA {} for {} is {} and it is {}\".format(\n line, phone, ledColor, ledCadence))\n\n\n# this is called by 'tng run'\ndef main():\n tng.api.runner()\n\nif __name__ == '__main__':\n tng.run(main)\n","sub_path":"common/IOT/Broadsoft_DeviceManagement/cmCC26586_3pcc_BS_Device_management_28_SharedLineOrigination.py","file_name":"cmCC26586_3pcc_BS_Device_management_28_SharedLineOrigination.py","file_ext":"py","file_size_in_byte":8678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"471277757","text":"#################################\n'''\n ******* GETTING STARTED ********\n\nTask: Scrape the New York Times Opinion section on the home page\n\n0. Set up a cache\n1. Create a list called `master`\n2. For each article in the opinion section save the following in a list:\n 1. type string :: URL\n 2. type string :: Author(s)\n 3. type string :: Title\n3. For each list representing (2), append to the `master` list\n3. Print the following for each element in `master`:\n \"\"\" TITLE: {}\\nAUTHOR(S): {}\\n\"\"\".format(< put the title here>, ))\n'''\n#################################\n\nfrom bs4 import BeautifulSoup\nfrom alternate_advanced_caching import Cache\nimport requests\nfrom datetime import datetime\n\n##############\n# SETTING UP #\n##############\n\n\ndef create_id(site, topic):\n return \"{}_{}_{}.json\".format(site, topic, str(datetime.now()).replace(' ', ''))\n\ndef process(response):\n soup = BeautifulSoup(response, 'html.parser')\n opinion = soup.find('section', attrs={\"data-testid\":'block-Opinion'})\n articles = opinion.find_all('div', class_=\"css-z49qw6\")\n master = []\n print(response)\n for article in articles:\n link = article.find('a').get('href')\n author = article.find('a').find('div', class_=\"css-1j836f9\").find('div', class_=\"css-omcqsq\").text\n #author = article.find('div', class_=\"css-omcqsq\")).text\n title = article.find('a').find('h2').text\n master.append([title, author, link])\n\n for article in master:\n print(\"\"\" TITLE: {}\\nAUTHOR(S): {}\\n\"\"\".format(article[0], article[1]))\n\n###################\n# CONFIG #\n###################\ncache_file = \"nyt.json\"\nsite=\"nyt\"\ntopic=\"opinion\"\ncache = Cache(cache_file)\nbase = \"https://www.nytimes.com/?action=click&contentCollection=undefined®ion=TopBar&module=HomePage-Title&pgtype=sectionfront\"\n\n\n#######################\n# RUN PROGRAM #\n#######################\n\nUID = create_id(site, topic)\nresponse = cache.get(UID)\nif response == None:\n response = requests.get(base).text\n cache.set(UID, response, 1)\n\nprocess(response)\n","sub_path":"discussion program/warm_up.py","file_name":"warm_up.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"454925189","text":"#!/usr/bin/env python\n\nimport argparse\nimport httplib2\nimport oauth2client.client\nimport gdata.spreadsheet.service\nimport xml.etree.ElementTree\n\ndef get_access_token(tokenFile, refresh=False, verbose=0):\n with open(tokenFile, 'r') as f:\n credentials = oauth2client.client.Credentials.new_from_json(f.read())\n http = httplib2.Http()\n if refresh:\n if verbose > 0: print('refresh')\n credentials.refresh(http)\n else:\n if verbose > 0: print('authorize')\n credentials.authorize(http)\n return(credentials.access_token)\n\ndef enumerate_rows(spreadsheet_id, worksheet_id, verbose=0):\n cells_feed = gd_client.GetCellsFeed(spreadsheet_id, worksheet_id)\n print('number of cells found is {}'.format(len(cells_feed.entry)))\n current_row = cells_feed.entry[0].cell.row\n row_data = []\n for entry in cells_feed.entry:\n if current_row != entry.cell.row:\n print(unichr(0x00a6).join(row_data))\n current_row = entry.cell.row\n row_data = []\n row_data.append('R{}C{} {}'.format(entry.cell.row, entry.cell.col, entry.content.text))\n if verbose > 2:\n print(entry)\n if verbose > 1:\n for child in xml.etree.ElementTree.fromstring(entry.ToString()):\n print('tag:{} attrib:{} text:{}'.format(child.tag, child.attrib, child.text))\n print(child.tag)\n print(child.attrib)\n print(child.text)\n if verbose > 0: print('row:{} col:{} contents:{}'.format(entry.cell.row, entry.cell.col, entry.content.text))\n print(unichr(0x00a6).join(row_data))\n\ndef enumerate_worksheets(spreadsheet_id, show_rows, verbose=0):\n ws_feed = gd_client.GetWorksheetsFeed(spreadsheet_id)\n print('number of worksheets found is {}'.format(len(ws_feed.entry)))\n for entry in ws_feed.entry:\n worksheet_id = entry.id.text.rsplit('/',1)[1]\n print(' {} {} rows:{} columns:{}'.format(worksheet_id, entry.title.text, entry.row_count.text, entry.col_count.text))\n if show_rows:\n enumerate_rows(spreadsheet_id, worksheet_id, verbose=verbose)\n\ndef enumerate_documents(ss_feed, show_worksheets, show_rows, verbose=0):\n for entry in ss_feed.entry:\n spreadsheet_id = entry.id.text.rsplit('/',1)[1]\n if verbose > 0: print('{} {}'.format(spreadsheet_id, entry.title.text))\n if show_worksheets:\n enumerate_worksheets(spreadsheet_id, show_rows, verbose=verbose)\n\nif '__main__' == __name__:\n parser = argparse.ArgumentParser()\n parser.add_argument('-t', '--tokenFile', action='store', required=True, help='file containing OAuth token in JSON format')\n parser.add_argument('-n', '--name', action='store', required=True, help='name of the spreadsheet')\n parser.add_argument('-w', '--worksheets', action='store_true', help='set this to list out worksheets (tabs) in each spreadsheet')\n parser.add_argument('-r', '--rows', action='store_true', help='set this to list out rows in each spreadsheet')\n parser.add_argument('-v', '--verbose', action='count', help='be verbose')\n args = parser.parse_args()\n\n q = gdata.spreadsheet.service.DocumentQuery()\n q['title'] = args.name\n\n gd_client = gdata.spreadsheet.service.SpreadsheetsService()\n access_token = get_access_token(args.tokenFile, refresh=False, verbose=args.verbose)\n gd_client.additional_headers={'Authorization' : 'Bearer %s' % access_token}\n try:\n ss_feed = gd_client.GetSpreadsheetsFeed(query=q)\n except:\n access_token = get_access_token(args.tokenFile, refresh=True, verbose=args.verbose)\n gd_client.additional_headers={'Authorization' : 'Bearer %s' % access_token}\n ss_feed = gd_client.GetSpreadsheetsFeed(query=q)\n print('number of spreadsheets containing the name {} is {}'.format(args.name, len(ss_feed.entry)))\n enumerate_documents(ss_feed, args.worksheets, args.rows, verbose=args.verbose)\n","sub_path":"lsSpreadsheet.py","file_name":"lsSpreadsheet.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"105206606","text":"# -*- coding: utf-8 -*-\n# -----------------------------------------------------------------------------\n# arclytics_sim\n# mongo_service.py\n#\n# Attributions:\n# [1]\n# -----------------------------------------------------------------------------\n__author__ = ['Andrew Che <@codeninja55>']\n__credits__ = ['']\n__license__ = 'MIT'\n__version__ = '2.0.0'\n__status__ = 'development'\n__date__ = '2019.10.30'\n\"\"\"mongo_service.py: \n\nThis is a Service Access Layer where the application logic resides for \nmethods that access the data persistence layer for connecting to Mongo.\n\"\"\"\n\nfrom os import environ as env\n\nfrom arc_logging import AppLogger\nfrom sim_api.extensions import apm, Mongo\n\nlogger = AppLogger(__name__)\n\n\nclass MongoService(object):\n \"\"\"Service layer where the application logic resides.\"\"\"\n def __init__(self, client=Mongo()):\n \"\"\"\n Simply connects the service to the Mongo data access layer through an\n adapter.\n \"\"\"\n self.client = client\n self.db_name = env.get('MONGO_APP_DB')\n\n def find(\n self,\n query: dict = None,\n projections: dict = None,\n collection: str = '',\n sort: list = None,\n limit: int = 0\n ):\n \"\"\"Do a `collections.find()` query with projections. Additionally,\n we can also sort or limit the results returned.\n\n Usage:\n SearchService().find(\n # search for all documents\n query={},\n # return without _id field but with email\n projections={'_id': 0, 'email': 1},\n # sort ASCENDING on first_name field\n sort=[('first_name': 1)],\n # limit to only 10 returned results\n limit=10\n )\n\n Args:\n collection: the collection to run find() on.\n query: a dictionary of the query to be used.\n projections: a dictionary of the projections to be used.\n sort: a list of tuple pairs `(field, direction)` to sort results.\n limit: an int to limit the number of returned results.\n\n Returns:\n A list of the results which are Python dictionaries.\n \"\"\"\n if not sort:\n cursor = self.client.find(\n db_name=self.db_name,\n collection=collection,\n query=query,\n projections=projections,\n ).limit(limit)\n else:\n cursor = self.client.find(\n db_name=self.db_name,\n collection='users',\n query=query,\n projections=projections,\n ).sort(sort).limit(limit)\n\n return [obj for obj in cursor]\n\n def find_one(self, query: dict = None, projections: dict = None):\n \"\"\"Simple find one user based on a query and projection.\"\"\"\n return self.client.find_one(\n db_name=self.db_name,\n collection='users',\n query_selector=query,\n projections=projections\n )\n\n def find_slice(\n self,\n query: dict = None,\n projections: dict = None,\n collection: str = None,\n sort: list = None,\n limit: int = 0,\n skip: int = 0\n ):\n \"\"\"Do a `collections.find()` query with projections. Additionally we\n can do a slice on the results by providing the `skip` which will be\n the offset of the first returned result and a `limit` which is the\n end of the slice. We can also do a sort of the results but be away\n the sort always occurs first in the chained method returned.\n\n Args:\n collection: the collection to run find() on.\n query: a dictionary of the query to be used.\n projections: a dictionary of the projections to be used.\n sort: a list of tuple pairs `(field, direction)` to sort results.\n limit: an int to limit the number of returned results.\n skip: the offset of the result which is the number to start.\n\n Returns:\n A list of the results which are Python dictionaries.\n \"\"\"\n\n if not sort:\n cursor = self.client.find(\n db_name=self.db_name,\n collection=collection,\n query=query,\n projections=projections\n ).skip(skip).limit(limit)\n else:\n cursor = self.client.find(\n db_name=self.db_name,\n collection=collection,\n query=query,\n projections=projections,\n ).skip(skip).limit(limit).sort(sort)\n\n return list(cursor)\n\n def count(self, collection: str = None, skip: int = 0, limit: int = 0):\n \"\"\"Simply count the number of documents with a skip and limit query.\"\"\"\n return self.client.count(\n db_name=self.db_name,\n collection=collection,\n filter={}, # We always count ALL documents\n skip=skip,\n limit=limit\n )\n","sub_path":"services/simcct/sim_api/mongo_service.py","file_name":"mongo_service.py","file_ext":"py","file_size_in_byte":5014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"579435566","text":"#!/usr/bin/env python\n# -*- mode: python; coding: UTF-8; -*-\n\n\n\"\"\"Prepares a simple and secure Debian package archive.\"\"\"\n\n\nfrom __future__ import print_function\n\nimport os\nimport subprocess32\n\n\ndef _run_cmd(cmd, **kwargs):\n print('Run: \"{cmd_str}\"'.format(cmd_str=' '.join(cmd)))\n subprocess32.check_call(cmd, **kwargs)\n\n\ndef _main():\n \"\"\"Guide step by step through the creation of the package repository.\"\"\"\n\n # Verify we are at the right location.\n print('Verifying we are at the right location...')\n assert os.path.isdir('./gpgkeys')\n assert os.path.isdir('./yaobin')\n assert os.path.isfile('./build.py')\n print('Succeeded!')\n\n # Delete the package repository folder if it already exists.\n # We always want to start with a new one.\n print('Deleting the old package repository folder, if it exists...')\n _run_cmd(['rm', '-rf', 'pkg-repo'])\n print('Succeeded!')\n\n # Create the folder for the package repository.\n print('Creating the package repository folder...')\n _run_cmd(['mkdir', '-vp', os.path.join(os.getcwd(), 'pkg-repo')])\n print('Succeeded!')\n\n # Create the binary '.deb' package and move it to 'pkg-repo'.\n print('Creating the binary .deb package...')\n _run_cmd(['./build.py', '-n', 'yaobin', '-v', '1.0.0'])\n # _run_cmd(['mv', 'yaobin-wen_1.0.0_all.deb', 'pkg-repo'])\n print('Succeeded!')\n\n # Sign the package.\n print('Signing the binary .deb package...')\n _run_cmd([\n 'dpkg-sig',\n '-m', 'Yaobin Wen',\n # NOTE(ywen): The '--homedir ./gpgkeys' will properly quote the two\n # strings and pass them into '--gpg-options'. If you write\n # '\"--homedir ./gpgkeys\"', gpg complains\n # 'Invalid option \"--homedir ./gpgkeys\"'.\n # NOTE(ywen): By 03/30/2018, `dpkg-sig` has a bug of mismatching option\n # name. The option should be 'gpg-options', but the document says\n # 'gpgoptions'. See the bug report\n # https://bugs.launchpad.net/ubuntu/+source/dpkg-sig/+bug/1741254.\n '--gpg-options', '--homedir ./gpgkeys',\n '--sign', 'builder',\n 'yaobin-wen_1.0.0_all.deb',\n ])\n print('Succeeded!')\n\n # Create the 'conf' folder.\n print('Creating the \"conf\" folder...')\n _run_cmd(['mkdir', '-vp', os.path.join('.', 'pkg-repo', 'conf')])\n print('Succeeded!')\n\n # Create the 'distributions' file.\n print('Creating the \"distributions\" file...')\n with open(\n os.path.join('.', 'pkg-repo', 'conf', 'distributions'), 'w'\n ) as fdist:\n fdist.writelines([\n 'Origin: ', 'https://github.com/yaobinwen/robin_on_rails', '\\n',\n 'Label: ', 'Demo', '\\n',\n 'Codename: ', 'stretch', '\\n',\n 'Architectures: ', 'amd64', '\\n',\n 'Components: ', 'main', '\\n',\n 'Description: ',\n 'Demo to show how to prepare a secure package repository', '\\n',\n # NOTE(ywen): The key ID must match that of the public key in\n # './gpgkeys'.\n 'SignWith: ', '214BA15D', '\\n',\n ])\n print('Succeeded!')\n\n # Create the package repository.\n print('Creating the package repository...')\n _run_cmd(\n cmd=[\n 'reprepro',\n '--verbose',\n '--gnupghome', './gpgkeys',\n '--basedir', 'pkg-repo',\n 'includedeb', 'stretch', 'yaobin-wen_1.0.0_all.deb',\n ],\n # env={\n # 'GNUPGHOME': './gpgkeys',\n # }\n )\n print('Succeeded!')\n\n\nif __name__ == \"__main__\":\n _main()\n","sub_path":"Linux/packaging/prep-pkg-repo.py","file_name":"prep-pkg-repo.py","file_ext":"py","file_size_in_byte":3541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"239367457","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nfrom tkinter import *\nfrom tkinter.filedialog import askopenfilename\nfrom tkinter.filedialog import asksaveasfilename\nfrom tkinter.ttk import *\nimport sqlite3\n\n'''\n选择db,并且产生三个主要bat\n'''\ndef select_db_file():\n db_file = askopenfilename(title=\"请选择BaiduYunCacheFileV0.db文件\", filetypes=[('db', '*.db')])\n db.set(db_file)\n\n\ndef select_save_file():\n save_file = asksaveasfilename(filetypes=[('文件', '*.bat')])\n f.set(save_file + \".bat\")\n\n\ndef create_baiduyun_filelist():\n conn = sqlite3.connect(db.get())\n cursor = conn.cursor()\n cursor.execute(\"select * from cache_file\")\n sizeall = 0\n count = 0\n while True:\n value = cursor.fetchone()\n if not value:\n break\n path = value[2]\n name = value[3]\n size = value[4]\n md5 = value[5]\n if size!=0:\n # if path.startswith('/操作系统') or path.startswith('/PS') or path.startswith('/我的音乐/无损音乐')or path.startswith('/Android应用/Flyme4 通用免费主题')or path.startswith('/Windows游戏') or path.startswith('/Android应用/Flyme4 通用免费主题')or path.startswith('/Windows应用/Adobe 全套软件'):\n # continue\n # elif path.startswith('/动漫工坊/裏番组/合集/队列组'):\n sizeall = sizeall + size\n count = count + 1\n print(str(sizeall)+\" byte\")\n print(str(sizeall/ 1073741824)+\" GB\")\n print(str(count)+\"个文件\")\n\n\nroot = Tk()\nroot.title('百度云文件BaiduPCS-Go秒传批处理生成')\ndb_select = Button(root, text=' 选择DB文件 ', command=select_db_file)\ndb_select.grid(row=1, column=1, sticky=W, padx=(2, 0), pady=(2, 0))\ndb = StringVar()\ndb_path = Entry(root, width=80, textvariable=db)\ndb_path['state'] = 'readonly'\ndb_path.grid(row=1, column=2, padx=3, pady=3, sticky=W + E)\nsave_path = Button(root, text='选择保存地址', command=select_save_file)\nsave_path.grid(row=2, column=1, sticky=W, padx=(2, 0), pady=(2, 0))\nf = StringVar()\nfile_path = Entry(root, width=80, textvariable=f)\nfile_path['state'] = 'readonly'\nfile_path.grid(row=2, column=2, padx=3, pady=3, sticky=W + E)\ncreate_btn = Button(root, text='生成BaiduPCS-Go秒传批处理命令行', command=create_baiduyun_filelist)\ncreate_btn.grid(row=3, column=1, columnspan=2, pady=(0, 2))\nroot.columnconfigure(2, weight=1)\nroot.mainloop()\n","sub_path":"COMGUI/单文件大小统计.py","file_name":"单文件大小统计.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"464247601","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: HuRuiFeng\n@file: vm.py\n@time: 2020/8/19 21:28\n@project: wasm-python-book\n@desc:\n\"\"\"\nfrom ch10.binary.module import Module, ImportTagFunc, ImportTagTable, ImportTagMem, ImportTagGlobal, ExportTagFunc, \\\n ExportTagTable, ExportTagMem, ExportTagGlobal\nfrom ch10.binary.opcodes import Call\nfrom ch10.instance import module\nfrom ch10.interpreter.instructions import instr_table\nfrom ch10.interpreter.vm_func import new_internal_func, new_external_func\nfrom ch10.interpreter.vm_global import GlobalVar\nfrom ch10.interpreter.vm_memory import Memory\nfrom ch10.interpreter.vm_stack_control import ControlStack, ControlFrame\nfrom ch10.interpreter.vm_stack_operand import OperandStack\nfrom ch10.interpreter.vm_table import Table\n\n\nclass VM(OperandStack, ControlStack, module.Module):\n def __init__(self, module=None, memory=None):\n super(VM, self).__init__()\n if module is None:\n module = Module()\n self.module = module\n self.memory = memory\n # 用于存放模块实例的全局变量\n self.globals = []\n # 用于记录内/外部函数\n self.funcs = []\n self.table = None\n # 用来记录当前函数的第一个局部变量\n self.local_0_idx = None\n self.frames = []\n self.slots = []\n\n def link_imports(self, mm):\n for imp in self.module.import_sec:\n m = mm[imp.module]\n if m is None:\n raise Exception(\"module not found: \" + imp.module)\n else:\n self.link_import(m, imp)\n\n def link_import(self, m, imp):\n exported = m.get_member(imp.name)\n if exported is None:\n raise Exception(\"unknown import: %s.%s\" % (imp.module, imp.name))\n\n type_matched = False\n if isinstance(exported, module.Function):\n if imp.desc.tag == ImportTagFunc:\n exported_ft = self.module.type_sec[imp.desc.func_type]\n type_matched = is_func_type_match(exported_ft, exported.type)\n self.funcs.append(new_external_func(exported_ft, exported))\n elif isinstance(exported, module.Table):\n if imp.desc.tag == ImportTagTable:\n type_matched = is_limits_match(imp.desc.table.limits, exported.type.limits)\n self.table = exported\n elif isinstance(exported, module.Memory):\n if imp.desc.tag == ImportTagMem:\n type_matched = is_limits_match(imp.desc.mem, exported.type)\n self.memory = exported\n elif isinstance(exported, module.Global):\n if imp.desc.tag == ImportTagGlobal:\n type_matched = is_global_type_match(imp.desc.global_type, exported.type)\n self.globals.append(exported)\n\n if not type_matched:\n raise Exception(\"incompatible import type: %s.%s\" % (imp.module, imp.name))\n\n def init_mem(self):\n \"\"\"\n 内存初始化\n Wasm模块可以导入或者定义一块内存,还有一个数据段专门用来存放内存初始化数据\n \"\"\"\n # 如果模块定义了内存,就先创建内存实例并分配必要的内存页\n if len(self.module.mem_sec) > 0:\n self.memory = Memory(self.module.mem_sec[0])\n\n for data in self.module.data_sec:\n self.exec_const_expr(data.offset)\n\n # 指令执行完毕后,留在操作数栈顶的就是内存起始地址\n self.memory.write(self.pop_u64(), data.init)\n\n def init_globals(self):\n for global_var in self.module.global_sec:\n self.exec_const_expr(global_var.init)\n self.globals.append(GlobalVar(global_var.type, self.pop_u64()))\n\n def init_funcs(self):\n for i, ft_idx in enumerate(self.module.func_sec):\n ft = self.module.type_sec[ft_idx]\n code = self.module.code_sec[i]\n self.funcs.append(new_internal_func(self, ft, code))\n\n def init_table(self):\n if len(self.module.table_sec) > 0:\n self.table = Table(self.module.table_sec[0])\n for elem in self.module.elem_sec:\n for instr in elem.offset:\n self.exec_instr(instr)\n offset = self.pop_u32()\n for i, func_idx in enumerate(elem.init):\n self.table.set_elem(offset + i, self.funcs[func_idx])\n\n def exec_const_expr(self, expr):\n for instr in expr:\n self.exec_instr(instr)\n\n def exec_start_func(self):\n if self.module.start_sec is not None:\n idx = self.module.start_sec\n self.funcs[idx].call(None)\n\n def enter_block(self, opcode, bt, instrs):\n \"\"\"\n 进入函数(或控制块)时使用\n \"\"\"\n bp = self.stack_size - len(bt.param_types)\n cf = ControlFrame(opcode, bt, instrs, bp)\n self.push_control_frame(cf)\n if opcode == Call:\n self.local_0_idx = int(bp)\n\n def exit_block(self):\n cf = self.pop_control_frame()\n self.clear_block(cf)\n\n def clear_block(self, cf):\n results = self.pop_u64s(len(cf.bt.result_types))\n self.pop_u64s(self.stack_size - cf.bp)\n self.push_u64s(results)\n if cf.opcode == Call and self.control_depth > 0:\n last_call_frame, _ = self.top_call_frame()\n self.local_0_idx = int(last_call_frame.bp)\n\n def reset_block(self, cf):\n results = self.pop_u64s(len(cf.bt.param_types))\n self.pop_u64s(self.stack_size - cf.bp)\n self.push_u64s(results)\n\n def loop(self, verbose_flag=False):\n depth = self.control_depth\n while self.control_depth >= depth:\n cf = self.top_control_frame\n if cf.pc == len(cf.instrs):\n self.exit_block()\n else:\n instr = cf.instrs[cf.pc]\n if verbose_flag:\n print(\"PC={}, opcode={}, instrs={}, slots={}\".format(cf.pc, instr.opcode,\n instr_table[instr.opcode].__name__,\n self.slots))\n cf.pc += 1\n self.exec_instr(instr)\n\n def exec_instr(self, instr):\n \"\"\"指令分派逻辑:采用查表法\"\"\"\n instr_table[instr.opcode](self, instr.args)\n\n def get_member(self, name):\n for exp in self.module.export_sec:\n if exp.name == name:\n idx = exp.desc.idx\n tag = exp.desc.tag\n if tag == ExportTagFunc:\n return self.funcs[idx]\n elif tag == ExportTagTable:\n return self.table\n elif tag == ExportTagMem:\n return self.memory\n elif tag == ExportTagGlobal:\n return self.globals[idx]\n return None\n\n def invoke_func(self, name, args=None):\n if args is None:\n args = []\n m = self.get_member(name)\n if m is not None:\n return m.call(args)\n\n def get_global_val(self, name):\n m = self.get_member(name)\n if m is not None:\n return m.get(), None\n return None, \"global not found: \" + name\n\n def set_global_var(self, name, val):\n m = self.get_member(name)\n if m is not None:\n m.set(val)\n return None\n return \"global not found: \" + name\n\n\ndef new(m, mm):\n inst, error = None, None\n try:\n inst = new_vm(m, mm)\n except Exception as e:\n error = e\n return inst, error\n\n\ndef new_vm(m, mm):\n vm = VM(m)\n vm.link_imports(mm)\n vm.init_funcs()\n vm.init_table()\n vm.init_mem()\n vm.init_globals()\n vm.exec_start_func()\n return vm\n\n\ndef is_func_type_match(expected, actual) -> bool:\n return str(expected) == str(actual)\n\n\ndef is_global_type_match(expected, actual) -> bool:\n return actual.val_type == expected.val_type and actual.mut == expected.mut\n\n\ndef is_limits_match(expected, actual) -> bool:\n return actual.min >= expected.min and \\\n (expected.max == 0 or 0 < actual.max <= expected.max)\n","sub_path":"src/ch10/interpreter/vm.py","file_name":"vm.py","file_ext":"py","file_size_in_byte":8179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"594065481","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nfrom collections import OrderedDict\nimport numpy as np\nimport sys\nimport os\n\nfrom derivative import numerical_gradient as num_grad\nfrom layers import *\n\n## 多层神经网络\n## activation : 'relu' or 'sigmoid'\nclass MultiLayerNet:\n\tdef __init__(self, input_size, hidden_size_list, output_size, activation = 'relu', weight_init_std = 'relu', weight_decay_lambda = 0):\n\t\tself.input_size = input_size\n\t\tself.output_size = output_size\n\t\tself.hidden_size_list = hidden_size_list\n\t\tself.hidden_layer_num = len(hidden_size_list)\n\t\tself.weight_decay_lambda = weight_decay_lambda\n\t\t# 存储权重和偏置\n\t\tself.params = {}\n\t\t# 存储层 \n\t\tself.layers = OrderedDict()\n\t\t# 初始化权重\n\t\tself.__init_weight(weight_init_std)\n\t\t# 设置激活函数\n\t\tactivation_layer = {'sigmoid': Sigmoid, 'relu': Relu}\n\t\t# 创建多层神经网络 \n\t\tfor idx in range(1, self.hidden_layer_num+1):\n\t\t\tself.layers['Affine' + str(idx)] = Affine(self.params['W' + str(idx)], self.params['b' + str(idx)])\n\t\t\tself.layers['Activation_function' + str(idx)] = activation_layer[activation]()\n\t\t# 创建输出层\n\t\tidx = self.hidden_layer_num + 1\n\t\tself.layers['Affine' + str(idx)] = Affine(self.params['W' + str(idx)], self.params['b' + str(idx)])\n\t\t# 输出层的激活函数使用Softmax-With-Loss\n\t\tself.last_layer = SoftmaxWithLoss()\n\n\tdef __init_weight(self, weight_init_std):\n\t\tall_size_list = [self.input_size] + self.hidden_size_list + [self.output_size]\n\t\tfor idx in range(1, len(all_size_list)):\n\t\t\tscale = weight_init_std\n\t\t\t# Xavier初始值是以激活函数是线性函数为前提而推导出来的。因为sigmoid函数和tanh \n\t\t\t# 函数左右对称,且中央附近可以视作线性函数,所以适合使用`Xavier初始值`\n\t\t\t# 当激活函数使用ReLU时,一般推荐使用ReLU专用的初始值,也就是`He初始值`\n\t\t\tif str(weight_init_std).lower() in ('relu', 'he'):\n\t\t\t\tscale = np.sqrt(2.0 / all_size_list[idx - 1]) # ReLU权重初始值最优计算方法\n\t\t\telif str(weight_init_std).lower() in ('sigmoid', 'xavier'):\n\t\t\t\tscale = np.sqrt(1.0 / all_size_list[idx - 1]) # sigmoid权重初始值最优计算方法\n\t\t\t# 设定权重\n\t\t\tself.params['W' + str(idx)] = scale * np.random.randn(all_size_list[idx-1], all_size_list[idx])\n\t\t\tself.params['b' + str(idx)] = np.zeros(all_size_list[idx])\n\n\tdef predict(self, x):\n\t\tfor layer in self.layers.values():\n\t\t\tx = layer.forward(x)\n\t\treturn x\n\n\tdef loss(self, x, t):\n\t\ty = self.predict(x)\n\t\tweight_decay = 0\n\t\tfor idx in range(1, self.hidden_layer_num + 2):\n\t\t\tW = self.params['W' + str(idx)]\n\t\t\tweight_decay += 0.5 * self.weight_decay_lambda * np.sum(W ** 2)\n\t\treturn self.last_layer.forward(y, t) + weight_decay\n\n\tdef accuracy(self, x, t):\n\t\ty = self.predict(x)\n\t\ty = np.argmax(y, axis=1)\n\t\tif t.ndim != 1: \n\t\t\tt = np.argmax(t, axis=1)\n\t\taccuracy = np.sum(y == t) / float(x.shape[0])\n\t\treturn accuracy\n\n\tdef numerical_gradient(self, x, t):\n\t\tloss_W = lambda W: self.loss(x, t)\n\t\tgrads = {}\n\t\tfor idx in range(1, self.hidden_layer_num+2):\n\t\t\tgrads['W' + str(idx)] = num_grad(loss_W, self.params['W' + str(idx)])\n\t\t\tgrads['b' + str(idx)] = num_grad(loss_W, self.params['b' + str(idx)])\n\t\treturn grads\n\n\tdef gradient(self, x, t):\n\t\t# forward\n\t\tself.loss(x, t)\n\t\t# backward\n\t\tdout = 1\n\t\tdout = self.last_layer.backward(dout)\n\t\tlayers = list(self.layers.values())\n\t\tlayers.reverse()\n\t\tfor layer in layers:\n\t\t\tdout = layer.backward(dout)\n\t\t# 設定\n\t\tgrads = {}\n\t\tfor idx in range(1, self.hidden_layer_num+2):\n\t\t\tgrads['W' + str(idx)] = self.layers['Affine' + str(idx)].dW + self.weight_decay_lambda * self.layers['Affine' + str(idx)].W\n\t\t\tgrads['b' + str(idx)] = self.layers['Affine' + str(idx)].db\n\t\treturn grads\n\n\n## 测试多层神经网络\nif __name__== \"__main__\":\n\tmn = MultiLayerNet(input_size = 16, hidden_size_list = [10, 10, 10], output_size = 8)\n\tprint(mn.layers)\n\n\n","sub_path":"bin/knitter/multi_layer_net.py","file_name":"multi_layer_net.py","file_ext":"py","file_size_in_byte":3873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"390664277","text":"#!/usr/bin/env python\n# coding: utf-8\n\n###------NYC Events Historic : DATA CLEANING-----###\n\n#Import Packages\nimport pandas as pd\nfrom data_utility import readCsvFile\n\n## Read CSV\ngetEvents = readCsvFile('../Data/NYC_Permitted_Event_Information_Historical.csv')\n\n#Drop Columns\ngetRemEvents = getEvents.drop(['Event Street Side','Street Closure Type', 'Community Board'], axis=1)\n\n#Remove Nan Values from the dataset\ndropEvent1 = getRemEvents.dropna(subset=['Event ID', 'Event Name'],how = \"all\")\ndropEvent2 = dropEvent1.dropna(subset=['Start Date/Time', 'End Date/Time'],how = \"all\")\ndropEvent3 = dropEvent2.dropna(subset=['Event Borough'],how = \"all\")\ndropEvent4 = dropEvent3.dropna(subset=['Police Precinct'],how = \"all\")\n\n#Copy of Cleaned Dataset\neventDf = dropEvent4.copy()\n\ndef getCleanedEventsData():\n return eventDf\n\n\n","sub_path":"Python Notebook/Python files/NYC_GetCleaned_Events.py","file_name":"NYC_GetCleaned_Events.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"34057268","text":"'''\nCreated on Nov 30, 2015\n\n@author: rajeev.kumar\n\nDescription :Verify that for a Standard user, the Total services under Service Overview on the Dashboard gives the correct information.\nTest Flow :1)Login as a Admin & create/verify standard user\n 2)Login as a standard user & verify the Total services under Service Overview on the Dashboard\n'''\nfrom globalImports import *\n\n\ntc_id=utility.get_tc_data(__file__)\n\nclass Testcase(Manager.Manager): \n \"\"\"\n Standard user, the Total services under Service Overview on the Dashboard gives the correct information.\n \"\"\"\n \n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialization\n \"\"\"\n\n Manager.Manager.__init__(self, tc_id, *args, **kwargs)\n \n \n @BaseClass.TestBase.func_exec\n def test_functionality(self): \n \"\"\"\n This is the execution starting function\n \"\"\"\n self.browserObject = globalVars.browserObject\n \n #Check for current logged in user\n self.verifyCurrentUser(userRole='Standard', loginAsUser=True)\n \n #Verify Getting Started Page\n self.verifyLandingPageOptions(userRole='Standard')\n self.get_DashboardPage(\"Total Services\")\n \n #logout Standard user\n self.logout()\n ","sub_path":"GUI/gui-automation-ASMvNext84UI/tests/Testcase_NGI-TC-2604.py","file_name":"Testcase_NGI-TC-2604.py","file_ext":"py","file_size_in_byte":1304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"559254985","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\nclass Configuracion(models.Model):\n nombre = models.CharField(default='', max_length=20)\n lista_max_items = models.SmallIntegerField(default=5)\n lista_cycle_position = models.SmallIntegerField(default=4)\n porcent_plataforma = models.SmallIntegerField(default=20)\n porcent_patrocinador_directo = models.SmallIntegerField(default=20)\n porcent_segunda_generacion = models.SmallIntegerField(default=3)\n porcent_tercera_generacion = models.SmallIntegerField(default=7)\n porcent_posicion_cobro = models.SmallIntegerField(default=50)\n monto_minimo_retiro = models.DecimalField(max_digits=6, decimal_places=2, default=100)\n comision_retiro = models.DecimalField(max_digits=6, decimal_places=2, default=0)\n tope_cobros_nivel = models.SmallIntegerField(default=8)\n tope_cobros_clon = models.SmallIntegerField(default=16)\n\n def __str__(self):\n return \"Configuracion\" + str(self.nombre)\n\n class Meta: \n verbose_name_plural = 'Configuraciones'\n\nclass Cuenta(models.Model):\n jugador = models.ForeignKey('Jugador', on_delete=models.CASCADE)\n saldo_activacion = models.DecimalField(max_digits=10, decimal_places=2, default=0)\n saldo_disponible = models.DecimalField(max_digits=10, decimal_places=2, default=0)\n saldo_total = models.DecimalField(max_digits=10, decimal_places=2, default=0)\n beneficios_totales = models.DecimalField(max_digits=10, decimal_places=2, default=0)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return \"Cuenta \" + str(self.id) + \" \" + str(self.jugador)\n\n class Meta:\n verbose_name_plural = 'Cuentas'\n ordering = ['created']\n\nclass Movimiento(models.Model):\n TIPO_CHOICES = (\n ('E', 'ENTRADA'),\n ('S', 'SALIDA'),\n )\n\n CONCEPTO_CHOICES = (\n ('CP', 'COMISION PLATAFORMA'),\n ('C1', 'COMISION GENERACION 1'),\n ('C2', 'COMISION GENERACION 2'),\n ('C3', 'COMISION GENERACION 3'),\n ('CI', 'CICLAJE'),\n ('PN', 'PAGO POR NIVEL'),\n ('PA', 'PAGO AUTOMATICO POR NIVEL'),\n ('CS', 'CARGA DE SALDO'),\n ('RS', 'RETIRO DE SALDO'), \n ) \n\n BILLETERA_CHOICES = (\n ('E', 'CRIPTOMONEDA EXTERNA'), # BILLETERA EXTERNA CRIPTO\n ('D', 'DISPONIBLE'), # COMISIONES DIRECTAS\n ('A', 'ACTIVACION'), # TRANSFERENCIAS INTERNAS Y COMISIONES NO DIRECTAS\n\n ) \n cuenta = models.ForeignKey('Cuenta', on_delete=models.CASCADE)\n billetera = models.CharField(max_length=2, choices=BILLETERA_CHOICES,\n default='', blank=True, null=True)\n tipo = models.CharField(max_length=1, choices=TIPO_CHOICES,\n default='', blank=True, null=True)\n concepto = models.CharField(max_length=2, choices=CONCEPTO_CHOICES,\n default='', blank=True, null=True)\n descripcion = models.CharField(default='', max_length=250, blank=True, null=True)\n valor = models.DecimalField(max_digits=10, decimal_places=2, default=0)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return str(self.id)\n\n class Meta:\n verbose_name_plural = 'Movimientos'\n ordering = ['created']\n\nclass Lista(models.Model):\n ESTADO_CHOICES = (\n ('A', 'ABIERTA'),\n ('C', 'CERRADA'),\n ('B', 'BLOQUEADA')\n )\n alias = models.CharField(default='', max_length=20, blank=True, null=True)\n nivel = models.ForeignKey('Nivel', blank=True, null=True,\n on_delete=models.CASCADE)\n\n items = models.SmallIntegerField(default=0)\n jugador = models.ManyToManyField('Jugador', default='', blank=True,\n through='Juego',\n through_fields=('lista', 'jugador'))\n lista_padre = models.ForeignKey('self', on_delete=models.CASCADE,\n null=True,\n blank=True)\n estado = models.CharField(max_length=1, choices=ESTADO_CHOICES,\n default='A')\n pc = models.BooleanField(default=False)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return str(self.id)\n\n class Meta:\n verbose_name_plural = 'Listas'\n ordering = ['created']\n\n# item de lista\nclass Juego(models.Model):\n lista = models.ForeignKey(Lista, on_delete=models.CASCADE)\n jugador = models.ForeignKey('Jugador', on_delete=models.CASCADE)\n posicion = models.SmallIntegerField(default=-1)\n posicion_cerrado = models.IntegerField(default=-1)\n color_cerrado = models.CharField(max_length=10, default='red')\n cadena_ciclaje = models.TextField(default='', blank=True, null=True)\n\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return str(self.jugador) + ' jugando en lista ' + str(self.lista)\n\n class Meta:\n verbose_name_plural = 'Juegos'\n ordering = ['created']\n\n\nclass Jugador(models.Model):\n ESTADO_CHOICES = (\n ('R', 'REGISTRADO'),\n ('A', 'ACTIVO')\n )\n estado = models.CharField(max_length=1, choices=ESTADO_CHOICES,\n default='R')\n nuevo = models.BooleanField(default=True)\n usuario = models.OneToOneField(User,\n on_delete=models.CASCADE)\n promotor = models.ForeignKey('Jugador', blank=True, null=True,\n on_delete=models.CASCADE, related_name='jugador_promotor')\n nivel = models.ManyToManyField('Nivel', default='', blank=True,\n through='JugadorNivel',\n through_fields=('jugador', 'nivel'))\n whatsapp = models.CharField(max_length=10, blank=True, null=True)\n celular = models.CharField(max_length=10, blank=True, null=True)\n\n def __str__(self):\n return str(self.usuario)\n\n class Meta:\n verbose_name_plural = 'Jugadores'\n\n\nclass Nivel(models.Model):\n monto = models.DecimalField(max_digits=10, decimal_places=2, default=0)\n\n def __str__(self):\n return \"Nivel \" + str(self.id)\n\n class Meta:\n verbose_name_plural = 'Niveles'\n\n\nclass JugadorNivel(models.Model):\n ESTADO_CHOICES = (\n ('P', 'PENDIENTE DE ACTIVAR'),\n ('A', 'ACTIVO'),\n ('B', 'BLOQUEADO'),\n )\n\n jugador = models.ForeignKey('Jugador', on_delete=models.CASCADE)\n nivel = models.ForeignKey('Nivel', on_delete=models.CASCADE)\n patrocinador = models.ForeignKey('Jugador', blank=True, null=True,\n on_delete=models.CASCADE, related_name='patrocinador')\n estado = models.CharField(max_length=1, choices=ESTADO_CHOICES,\n default='P')\n \n n_referidos = models.PositiveIntegerField(default=0)\n n_referidos_activados = models.PositiveIntegerField(default=0)\n color = models.CharField(max_length=10, default='red')\n ciclo = models.BigIntegerField(default=0)\n cobros = models.BigIntegerField(default=0)\n bloqueo_x_cobros_nivel = models.BooleanField(default=False)\n bloqueo_y_cobros_clon = models.BooleanField(default=False)\n n_listas_cerradas = models.PositiveIntegerField(default=0)\n \n def __str__(self):\n return \"Jugador \" + str(self.jugador) + \" \" + str(self.nivel)\n\n class Meta:\n verbose_name_plural = 'Jugador Niveles'\n\nclass Clon(models.Model):\n ESTADO_CHOICES = (\n ('P', 'PENDIENTE ACTIVAR'),\n ('A', 'ACTIVO'),\n )\n TIPO_CHOICES = (\n ('R', 'POR REFERIDOS'),\n ('C', 'POR CICLOS'),\n )\n jugador = models.ForeignKey('jugador', blank=True, null=True,\n on_delete=models.CASCADE)\n estado = models.CharField(max_length=1, choices=ESTADO_CHOICES,\n default='P')\n tipo = models.CharField(max_length=1, choices=TIPO_CHOICES,\n default='R')\n nivel = models.ForeignKey('Nivel', on_delete=models.CASCADE, default=1)\n\n def __str__(self):\n return 'clon de ' + str(self.jugador)\n\n class Meta:\n verbose_name_plural = 'Clones'\n\nclass Cobrador(models.Model):\n jugador = models.ForeignKey('jugador', blank=True, null=True,\n on_delete=models.CASCADE)\n nivel = models.ForeignKey('Nivel', on_delete=models.CASCADE, default=1)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return str(self.jugador)\n\n class Meta:\n verbose_name_plural = 'Cobradores'\n ordering = ['-created']\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"152283477","text":"import os\nimport sys\nimport traceback\nfrom cli import CLI\n\nimport torneira\n\n\nclass Main(object):\n def __init__(self):\n self.cli = CLI()\n\n def start(self, options, args):\n # set path\n sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(options.settings_file)), \"..\"))\n sys.path.insert(0, os.path.dirname(os.path.abspath(options.settings_file)))\n\n # set setting\n exec(\"import %s as settings\" % os.path.splitext(os.path.basename(options.settings_file))[0])\n torneira.settings = settings \n\n from torneira.core.server import TorneiraServer\n server = TorneiraServer(\n pidfile=options.pidfile,\n port=options.port,\n media_dir=os.path.abspath(options.media_dir),\n xheaders=options.xheaders\n )\n\n if options.daemon:\n if args[0] == \"start\":\n server.start()\n\n elif args[0] == \"stop\":\n server.stop()\n\n elif args[0] == \"restart\":\n server.restart()\n else:\n server.run()\n\n def excecute(self):\n (options, args) = self.cli.parse()\n if args and args[0] in ('start', 'stop', 'restart'):\n try:\n self.start(options, args)\n except Exception:\n traceback.print_exc(file=sys.stderr)\n","sub_path":"torneira/runner/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"330455377","text":"from IPython.display import clear_output\nboard = None\nplayer = 1\ngame = 1\nxvalues = []\novalues = []\nmoves = 0\n\ndef startGame():\n global board\n global game\n global player\n global moves\n moves = 0\n game = 1\n player = 1\n board = [\"none\", [\"7\", \"8\", \"9\"], [\"4\", \"5\", \"6\"], [\"1\", \"2\", \"3\"]]\n displayBoard()\n print(\"^Position Example Board^\")\n board = [\"none\", [\" \", \" \", \" \"], [\" \", \" \", \" \"], [\" \", \" \", \" \"]]\n\ndef displayBoard():\n global board\n display = f\"\"\"\n * *\n {board[1][0]} * {board[1][1]} * {board[1][2]}\n * *\n * * * * * * * * * *\n * *\n {board[2][0]} * {board[2][1]} * {board[2][2]}\n * *\n * * * * * * * * * *\n * *\n {board[3][0]} * {board[3][1]} * {board[3][2]}\n * *\n \"\"\"\n print('\\n'*100)\n print(display)\n\ndef updateBoard(playerIn, xy, player):\n global board\n if player == 1: \n symbol = \"X\"\n xvalues.append(playerIn)\n else: \n symbol = \"O\"\n ovalues.append(playerIn)\n board[xy[0]][xy[1]] = symbol\n\ndef decode(position):\n if position < 4:\n return 3, position-1\n elif position < 7:\n return 2, position-4\n elif position < 10:\n return 1, position-7\n else:\n return 0,0\n\ndef getInput(player):\n global board\n global moves\n good = 0\n while good != 2:\n if good == 1:\n playerIn = int(input(f\"Player {player}, try again. \"))\n elif good == 0:\n playerIn = int(input(f\"Player {player}, make a move. \"))\n good = 1\n xy = decode(playerIn)\n if playerIn < 10 and board[xy[0]][xy[1]] != \"X\" and board[xy[0]][xy[1]] != \"O\":\n good = 2\n updateBoard(playerIn, xy, player)\n moves+=1\n return playerIn\n\ndef checkWin(player, lastPlay):\n global board\n for row in board[1:]:\n if(row[1] == row[2] == row[0] != \" \"):\n print(f'{player} wins with a row!')\n return True\n for y in range(0,3):\n if(board[1][y] == board[2][y] == board[3][y] != \" \"):\n print(f'{player} wins with a column!')\n return True\n if(board[3][0] == board[2][1] == board[1][2] != \" \") or (board[1][0] == board[2][1] == board[3][2] != \" \"):\n print(f'{player} wins with a diagonal!')\n return True\n return False\n\ndef checkPlayAgain():\n inn = input(\"Play again? (y/n) \")\n if inn == 'y':\n return True\n elif inn == 'n':\n return False\n\nstartGame()\n\nwhile game:\n lastPlay = getInput(player)\n displayBoard()\n win = checkWin(player, lastPlay)\n if win or moves == 9:\n if checkPlayAgain():\n startGame()\n else:\n game = 0\n else: \n if player == 1 : player = 2\n else: player = 1\nelse:\n print('Game Over')","sub_path":"Project1.py","file_name":"Project1.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"456338958","text":"import urllib\nfrom aupostcodes.models import AUPostCode\nfrom django.contrib.auth.models import User\n#from django.contrib.localflavor.au import forms\nfrom aupostcodes.fields import AUPostCodeField, AUPostCodeFormField\nfrom django.contrib.localflavor.au.forms import AUStateSelect, AUPhoneNumberField\nfrom django.db import models\n# Create your models here.\n#from django.contrib.auth.models import User\nfrom django.db.models.query_utils import Q\nfrom django.db.models.signals import post_save\nfrom django.contrib.auth.forms import UserCreationForm\n#from django.forms import ModelForm\nfrom django import forms\n#from registration import forms\nfrom django.forms.models import ModelForm\nfrom adv import settings\n\nSTATE_CHOICES = (\n ('VIC', 'VIC'),\n ('NSW', 'NSW'),\n ('SA', 'SA'),\n ('WA', 'WA'),\n ('QLD', 'QLD')\n)\n\n\nclass UserProfile(models.Model):\n # This field is required.\n user = models.OneToOneField(User)\n\n # Other fields here\n adv_user_name = models.CharField(max_length=255, blank=False, null=True)\n address = models.CharField(max_length=2000, blank=True, null=True)\n# address_2 = models.CharField(max_length=1500, blank=True, null=True)\n city = models.CharField(max_length=550, blank=True, null=True)\n mobile_phone = models.CharField(max_length=255, blank=True, null=True)\n home_phone = models.CharField(max_length=255, blank=True, null=True)\n latitude = models.CharField(max_length=255, blank=True, null=True)\n longitude = models.CharField(max_length=255, blank=True, null=True)\n state = models.CharField(max_length=3, blank=False, null=True)#choices=STATE_CHOICES)\n post_code = AUPostCodeField()#models.IntegerField(blank=False, null=True)\n prv_address = models.NullBooleanField()\n prv_city = models.NullBooleanField()\n prv_home_phone = models.NullBooleanField()\n prv_mobile_phone = models.NullBooleanField()\n prv_name = models.NullBooleanField()\n prv_post_code = models.NullBooleanField()\n prv_state = models.NullBooleanField()\n\n\n# def __str__(self):\n# return \"%s's profile\" % self.user\n\ndef create_user_profile(sender, instance, created, **kwargs):\n if created:\n UserProfile.objects.create(user=instance)\n#def save(self, commit=True):\n# user = super(Register, self).save(commit=False)\n## UserProfile.email = self.cleaned_data[\"email\"]\n# if commit:\n# User.save()\n# return User\npost_save.connect(create_user_profile, sender=User)\n\n\nclass Register(UserCreationForm):\n class Meta:\n model = User\n fields = (\"username\", \"email\", \"password1\", \"password2\")\n# fields = ( 'adv_user_name', 'address_1', 'address_2',)\n# widgets = {'adv_user_name': forms.TextInput(),'address_1': forms.TextInput(),'address_2': forms.TextInput(),}\n def save(self, commit=True):\n user = super(UserCreationForm, self).save(commit=False)\n user.email = self.cleaned_data[\"email\"]\n if commit:\n user.save()\n return user\n\nclass account(ModelForm):\n class Meta:\n model = UserProfile\n fields = ('adv_user_name', 'address', 'city', 'state', 'post_code', 'home_phone', 'mobile_phone')\n widgets = {'adv_user_name': forms.TextInput(), 'address': forms.TextInput(), 'city': forms.TextInput(), 'state': AUStateSelect(), 'home_phone': forms.TextInput(), 'mobile_phone': forms.TextInput(),}\n# def __init__(self, *args, **kwargs):\n# user = kwargs.pop('user')\n# super(account, self).__init__(*args, **kwargs)\n# self.adv_user_name = UserProfile.objects.filter(user=user)[0].adv_user_name\n# Save the profile form\n def save(self, commit=True):\n UserProfile = super(forms.ModelForm, self).save(commit=False)\n UserProfile.post_code = AUPostCode.objects.get(postcode=self.cleaned_data['post_code'])\n UserProfile.state = postcode=self.cleaned_data['state']\n if UserProfile.state != UserProfile.post_code.states[0]:\n UserProfile.state = UserProfile.post_code.states[0]\n UserProfile.city = postcode=self.cleaned_data['city']\n UserProfile.address = postcode=self.cleaned_data['address']\n location = \"%s, %s, %s, %s\" % (UserProfile.address, UserProfile.city, UserProfile.state, UserProfile.post_code)\n if not UserProfile.latitude or not UserProfile.longitude:\n latlng = self.geocode(location)\n latlng = latlng.split(',')\n UserProfile.latitude = latlng[0]\n UserProfile.longitude = latlng[1]\n UserProfile.adv_user_name = self.cleaned_data[\"adv_user_name\"]\n if commit:\n UserProfile.save()\n return UserProfile\n# Geocode the address on save\n def geocode(self, location):\n output = \"csv\"\n location = urllib.quote_plus(location)\n request = \"http://maps.google.com.au/maps/geo?q=%s&output=%s&key=%s\" % (location, output, settings.GOOGLE_API_KEY)\n data = urllib.urlopen(request).read()\n dlist = data.split(',')\n if dlist[0] == '200':\n return \"%s,%s\" % (dlist[2], dlist[3])\n else:\n return ','\n\n\n","sub_path":"ADVDirectory/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"90990809","text":"#!/usr/bin/env python3\n# PYTHON_PREAMBLE_START_STANDARD:{{{\n\n# Christopher David Cotton (c)\n# http://www.cdcotton.com\n\n# modules needed for preamble\nimport importlib\nimport os\nfrom pathlib import Path\nimport sys\n\n# Get full real filename\n__fullrealfile__ = os.path.abspath(__file__)\n\n# Function to get git directory containing this file\ndef getprojectdir(filename):\n curlevel = filename\n while curlevel is not '/':\n curlevel = os.path.dirname(curlevel)\n if os.path.exists(curlevel + '/.git/'):\n return(curlevel + '/')\n return(None)\n\n# Directory of project\n__projectdir__ = Path(getprojectdir(__fullrealfile__))\n\n# Function to call functions from files by their absolute path.\n# Imports modules if they've not already been imported\n# First argument is filename, second is function name, third is dictionary containing loaded modules.\nmodulesdict = {}\ndef importattr(modulefilename, func, modulesdict = modulesdict):\n # get modulefilename as string to prevent problems in <= python3.5 with pathlib -> os\n modulefilename = str(modulefilename)\n # if function in this file\n if modulefilename == __fullrealfile__:\n return(eval(func))\n else:\n # add file to moduledict if not there already\n if modulefilename not in modulesdict:\n # check filename exists\n if not os.path.isfile(modulefilename):\n raise Exception('Module not exists: ' + modulefilename + '. Function: ' + func + '. Filename called from: ' + __fullrealfile__ + '.')\n # add directory to path\n sys.path.append(os.path.dirname(modulefilename))\n # actually add module to moduledict\n modulesdict[modulefilename] = importlib.import_module(''.join(os.path.basename(modulefilename).split('.')[: -1]))\n\n # get the actual function from the file and return it\n return(getattr(modulesdict[modulefilename], func))\n\n# PYTHON_PREAMBLE_END:}}}\n\nimport random\nimport re\nimport string\nimport sys\n\ndef getalteredtext(mathtext, inputname, outputname, otherwords = [], nototherwords = []):\n \"\"\"\n Change all inputnames in this mathtext\n Need to check whether the inputname is part of a variable before replacing\n otherwords are terms like 'profits' which are a full word. I would not want to replace the letter r in this.\n \"\"\"\n\n # skip text stuff\n skiptext = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(30)]).replace(inputname, '')\n skiptextnum = 0\n addbacklaterlist = []\n\n labelpatterns = [re.compile(r'\\\\label{.*?}'), re.compile(r'\\\\begin{.*?}'), re.compile(r'\\\\end{.*?}')]\n\n for labelpattern in labelpatterns:\n matches = labelpattern.finditer(mathtext)\n for match in matches:\n mathtext = mathtext.replace(match.group(0), skiptext + '_b' + str(skiptextnum) + skiptext + '_f', 1)\n addbacklaterlist.append(match.group(0))\n skiptextnum = skiptextnum + 1\n\n # labelpattern = re.compile(r'\\\\label{.*?}')\n # matches = labelpattern.finditer(mathtext)\n # for match in matches:\n # mathtext = mathtext.replace(match.group(0), skiptext + '_b' + str(skiptextnum) + skiptext + '_f', 1)\n # addbacklaterlist.append(match.group(0))\n # skiptextnum = skiptextnum + 1\n #\n # labelpattern = re.compile(r'\\\\begin{.*?}')\n # matches = labelpattern.finditer(mathtext)\n # for match in matches:\n # mathtext = mathtext.replace(match.group(0), skiptext + '_b' + str(skiptextnum) + skiptext + '_f', 1)\n # addbacklaterlist.append(match.group(0))\n # skiptextnum = skiptextnum + 1\n \n\n # should add method for dealing with comments in formulae INCOMPLETE\n # mathtextlines = mathtext.split('\\n')\n # for line in mathtextlines:\n # for char in line:\n # if char == '\\\\':\n # escaped = True\n # else:\n # escaped = False\n\n wordcompile = re.compile(r'(? 0:\n newtext = ''\n for i in range(0, len(matches)):\n # add text in between i - 1 and i match\n if i == 0:\n newtext = newtext + text[0: matches[i].span()[0]]\n else:\n newtext = newtext + text[matches[i - 1].span()[1]: matches[i].span()[0]]\n # add replaced text for i match\n newtext = newtext + replacedtextlist[i]\n # add text after last match\n newtext = newtext + text[matches[-1].span()[1]: ]\n else:\n newtext = text\n\n return(newtext, otherwords, nototherwords)\n\n \ndef changename(text, inputname, outputname, otherwords = [], nototherwords = []):\n\n equationsregex = re.compile(r'(\\\\begin{equation\\*?})(.*?)(\\\\end{equation\\*?})', re.DOTALL)\n text, otherwords, nototherwords = replaceallmatches(equationsregex, text, inputname, outputname, otherwords = otherwords, nototherwords = nototherwords)\n\n inlineregex = re.compile(r'(?=0 and ctime - self.last_get_dialogs > self.get_dialogs_interval) or get_dialogs:\n self.used_get_dialogs = True\n self.last_get_dialogs = ctime\n res = []\n if self.whitelist:\n messages = self.api.messages.getDialogs(unread=(0 if self.whitelist_includeread else 1), count=20)\n self.whitelist_includeread = False\n else:\n messages = self.api.messages.getDialogs(unread=1, count=200)\n try:\n messages = messages['items'][::-1]\n except TypeError:\n logger.warning('Unable to fetch messages')\n return []\n for msg in sorted(messages, key=lambda m: m['message']['id']):\n cur = msg['message']\n if cur['out'] or cur['id'] in self.longpolled_messages:\n continue\n if self.last_message_id and cur['id'] > self.last_message_id:\n continue # wtf?\n cur['_method'] = 'getDialogs'\n res.append(cur)\n self.longpolled_messages.clear()\n else:\n self.used_get_dialogs = False\n res = []\n while not self.longpoll_queue.empty():\n res.append(self.longpoll_queue.get())\n res.sort(key=lambda x: x['id'])\n self.longpolled_messages.update(i['id'] for i in res)\n if res:\n self.last_message_id = max(self.last_message_id, res[-1]['id'])\n return res\n\n def _getLongpoll(self):\n arr = self.api.getLongpoll()\n if self.terminate_monitor:\n return []\n need_extra = []\n result = []\n for record in arr:\n if record['type'] == 'message_new': # new message\n msg = {}\n feed = record.get('object')\n msg['body'] = feed.get('text')\n msg['chat_id'] = feed.get('peer_id')\n if msg.get('chat_id') == None:\n msg['chat_id'] = feed.get('from_id')\n msg['payload'] = feed.get('payload')\n msg['user_id'] = feed.get('from_id')\n msg['id'] = feed.get('id')\n msg['attachments'] = feed.get('attachments')\n result.append(msg)\n return result\n","sub_path":"message_receiver.py","file_name":"message_receiver.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"256474127","text":"import pandas as pd\r\nimport matplotlib.pyplot as plt\r\n\r\ndef plot_result(train_loss, test_loss, acc, num_epochs):\r\n plt.rcParams['figure.figsize'] = [10,6]\r\n plt.rcParams.update({'font.size':14})\r\n result_df = pd.DataFrame({'iteration':range(1, num_epochs+1) ,'train_loss':train_loss, 'test_loss':test_loss, 'test_accuracy':acc})\r\n result_df.to_csv('result.csv', index = False)\r\n fig = plt.figure()\r\n plt.plot(train_loss, label = 'train_loss')\r\n plt.plot(test_loss, label = 'test_loss')\r\n plt.xlabel('iteration')\r\n plt.ylabel('loss')\r\n plt.ylim(bottom = 0)\r\n plt.title('Learning progression')\r\n plt.legend()\r\n fig.savefig('learning_progression.png')\r\n return\r\n","sub_path":"utils_thomas/plot_result.py","file_name":"plot_result.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"451507659","text":"#!/usr/bin/env python3\n\n\nfrom socket import gethostbyname\n\n# dict mapping as_num --> conpany name\nas_to_name = {}\n\n# dict mapping relevant part of ip bit representation ---> AS number\nip_to_as_dict = {}\n\nip_as_attachment = 'data-raw-table'\nas_info = 'data-used-autnums'\n\ndef map_as_to_company():\n file = open(as_info, 'r')\n for l in file:\n line = l.strip()\n q = line.find(' ')\n num, company_name = int(line[:q]), line[q+1:]\n as_to_name[num] = company_name\n\n\n\ndef map_ips_to_as():\n file = open(ip_as_attachment, 'r')\n for line in file:\n l= line.strip()\n l = l.split()\n if len(l)<2:\n continue\n\n ip, AS = l[0], int(l[1])\n q = ip.find('/')\n ip, relevant_bits = ip[:q], int(ip[q+1:])\n \n # convert ip to binary string representation \n l = ip.split('.')\n ip_bin = \"{:0>8b}{:0>8b}{:0>8b}{:0>8b}\".format(int(l[0]), int(l[1]), int(l[2]), int(l[3]))\n # dump irrelevant part\n ip_bin = ip_bin[:relevant_bits]\n\n ip_to_as_dict[ip_bin] = AS \n \n\n#\"{0:0>8b}\".format(255)\n# tries to find as owning given ip address\ndef find_as(ip):\n #convert to bit string\n l = ip.split('.')\n ip_bin = \"{:0>8b}{:0>8b}{:0>8b}{:0>8b}\".format(int(l[0]), int(l[1]), int(l[2]), int(l[3]))\n while ip_bin!='':\n #print ('looking for ip: ' + ip_bin)\n try:\n return ip_to_as_dict[ip_bin]\n except Exception:\n pass\n # try more general ip\n ip_bin = ip_bin[:-1]\n # haven't found matching in the dictionary\n return -1\n\n\n\nprint('Start with mapping AS nums to companies...')\nmap_as_to_company()\nprint('Done, now map ip to AS nums')\nmap_ips_to_as()\n\nprint('Everyting went well')\nprint('Is you wish to quit use CTRL+C\\n')\n\nwhile (True):\n print('Type ip adress to get AS it belongs to')\n # get ip, convert from url if necessary\n ip = gethostbyname(input())\n AS = find_as(ip)\n if AS==-1:\n print('Coudn\\'t find appropriate match')\n else:\n print('Ip: {} belongs to AS number {}, company owning this AS: {}\\n'.\\\n format(ip, AS, as_to_name[AS]))\n","sub_path":"as_info.py","file_name":"as_info.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"499975299","text":"# Copyright 2019 Amazon.com, Inc. or its affiliates. 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# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\nimport json\nimport string\nimport time\nfrom datetime import datetime\n\nimport pytest\nfrom assertpy import assert_that\nfrom pcluster_dcv_authenticator import (\n DCVAuthenticator,\n OneTimeTokenHandler,\n generate_random_token,\n generate_sha512_hash,\n)\n\nAUTH_MODULE_MOCK_PATH = \"pcluster_dcv_authenticator.\"\nAUTH_CLASS_MOCK_PATH = AUTH_MODULE_MOCK_PATH + \"DCVAuthenticator.\"\n\n\nclass TestOneTimeTokenHandler:\n \"\"\"Class to test the characteristics of the OneTimeTokenHandler class.\"\"\"\n\n @staticmethod\n def test_token_capacity():\n \"\"\"\n Test token capacity.\n\n Create a token handler with a defined size, add a number of items exceeding the internal capacity\n and verify the first one is not present.\n \"\"\"\n storage = OneTimeTokenHandler(3)\n storage.add_token(\"token1\", (\"some_value\", 1, 15.2, [\"a\", 2]))\n storage.add_token(\"token2\", (1, 2))\n storage.add_token(\"token3\", 5)\n storage.add_token(\"1\", 15)\n assert_that(storage.get_token_info(\"token1\")).is_none()\n\n @staticmethod\n def test_token_storage():\n \"\"\"Add tokens and their corresponding information in the storage and verify they are correctly stored.\"\"\"\n storage = OneTimeTokenHandler(3)\n storage.add_token(\"token1\", (\"some_value\", 1, 15.2, [\"a\", 2]))\n storage.add_token(\"token2\", (1, 2))\n storage.add_token(\"token3\", 5)\n assert_that(storage.get_token_info(\"token1\")).is_equal_to((\"some_value\", 1, 15.2, [\"a\", 2]))\n assert_that(storage.get_token_info(\"token2\")).is_equal_to((1, 2))\n assert_that(storage.get_token_info(\"token3\")).is_equal_to(5)\n\n @staticmethod\n def test_one_time_token():\n \"\"\"Add a token and verify it is correctly removed once used.\"\"\"\n storage = OneTimeTokenHandler(5)\n storage.add_token(1, \"some_value\")\n storage.get_token_info(1)\n assert_that(storage.get_token_info(1)).is_none()\n\n\ndef test_one_time_token_handler():\n TestOneTimeTokenHandler.test_token_capacity()\n TestOneTimeTokenHandler.test_token_storage()\n TestOneTimeTokenHandler.test_one_time_token()\n\n\ndef test_token_generator():\n # Verify token length and correctness\n assert_that(generate_random_token(256)).is_not_equal_to(generate_random_token(256))\n assert_that(len(generate_random_token(128))).is_equal_to(128)\n allowed_chars = \"\".join((string.ascii_letters, string.digits, \"_\", \"-\"))\n assert_that(allowed_chars).contains(*list(generate_random_token(256)))\n\n\ndef test_sha_generator():\n # Verify SHA512 generation and salt adding\n assert_that(len(generate_sha512_hash(\"hash\"))).is_equal_to(128)\n assert_that(generate_sha512_hash(\"hash\")).is_not_equal_to(generate_sha512_hash(\"hash\"))\n assert_that(generate_sha512_hash(\"hash1\", \"hash2\")).is_not_equal_to(generate_sha512_hash(\"hash1\", \"hash2\"))\n assert_that(generate_sha512_hash([1, 2, 4])).is_not_equal_to(generate_sha512_hash([1, 2, 4]))\n\n\n@pytest.mark.parametrize(\n \"user, command, session_id, result\",\n [\n (\"user1\", \"/usr/libexec/dcv/dcvagent\", \"mysession\", True),\n (\"user1\", \"/usr/libexec/dcv/dcvagent2\", \"mysession\", False),\n (\"wrong\", \"/usr/libexec/dcv/dcvagent\", \"mysession\", False),\n (\"user1\", \"/usr/libexec/dcv/dcvagent\", \"wrong\", False),\n (\"user1\", \"/usr/lib/x86_64-linux-gnu/dcv/dcvagent\", \"mysession\", True),\n (\"wrong\", \"/usr/lib/x86_64-linux-gnu/dcv/dcvagent\", \"mysession\", False),\n (\"user1\", \"/usr/lib/x86_64-linux-gnu/dcv/dcvagent\", \"wrong\", False),\n ],\n)\ndef test_is_process_valid(user, command, session_id, result):\n expected_session_id = \"mysession\"\n expected_user = \"user1\"\n\n ps_aux_output = (\n f\"{user} 63 0.0 0.0 4348844 3108 ?? Ss 23Jul19 2:32.46 {command} --mode full \"\n f\"--session-id {session_id}\"\n )\n\n assert_that(DCVAuthenticator.check_dcv_process(ps_aux_output, expected_user, expected_session_id)).is_equal_to(\n result\n )\n\n\ndef mock_generate_random_token(mocker, value):\n mocker.patch(AUTH_MODULE_MOCK_PATH + \"generate_random_token\", return_value=value)\n\n\ndef mock_verify_session_existence(mocker, exists):\n def _return_value(user, sessionid): # pylint: disable=W0613\n if not exists:\n raise DCVAuthenticator.IncorrectRequestError(\"The given session for the user does not exists\")\n\n mocker.patch(AUTH_CLASS_MOCK_PATH + \"_verify_session_existence\", side_effect=_return_value)\n\n\ndef mock_os(mocker, user, timestamp):\n class FileProperty:\n pass\n\n file_property = FileProperty\n file_property.st_uid = 1\n file_property.st_size = b\"800\"\n file_property.st_mtime = timestamp\n file_property.pw_name = user\n file_property.st_mode = 0\n\n mocker.patch(AUTH_MODULE_MOCK_PATH + \"os.stat\", return_value=file_property)\n mocker.patch(AUTH_MODULE_MOCK_PATH + \"os.remove\")\n mocker.patch(AUTH_MODULE_MOCK_PATH + \"getpwuid\", return_value=file_property)\n\n\n@pytest.mark.parametrize(\n \"parameters, keys, result\",\n [\n ({\"a\": \"5\", \"b\": \"2\"}, [\"authUser\", \"sessionID\"], DCVAuthenticator.IncorrectRequestError),\n ({\"authUser\": \"5\", \"b\": \"2\"}, [\"authUser\", \"sessionID\"], DCVAuthenticator.IncorrectRequestError),\n ({\"a\": \"5\", \"sessionID\": \"2\"}, [\"authUser\", \"sessionID\"], DCVAuthenticator.IncorrectRequestError),\n ({\"authUser\": \"user1\", \"sessionID\": \"1234\"}, [\"authUser\", \"sessionID\"], [\"user1\", \"1234\"]),\n ({\"requestToken\": \"token1\"}, [\"requestToken\"], [\"token1\"]),\n ],\n)\ndef test_get_request_token_parameter(parameters, keys, result):\n if isinstance(result, list):\n assert_that(DCVAuthenticator._extract_parameters_values(parameters, keys)).is_equal_to(result)\n else:\n with pytest.raises(result):\n DCVAuthenticator._extract_parameters_values(parameters, keys)\n\n\ndef test_get_request_token(mocker):\n \"\"\"Verify the first step of the authentication process, the retrieval of the Request Token.\"\"\"\n # A nosec comment is appended to the following line in order to disable the B105 check.\n # Since the request token is only being used for a unit test and not the actual auth service\n token_value = \"1234abcd_-\" # nosec B105\n user = \"centos\"\n session_id = \"mysession\"\n\n mock_verify_session_existence(mocker, exists=True)\n mock_generate_random_token(mocker, token_value)\n\n # all correct\n assert_that(DCVAuthenticator._get_request_token(user, session_id)).is_equal_to(\n json.dumps({\"requestToken\": token_value, \"accessFile\": generate_sha512_hash(token_value)})\n )\n assert_that(DCVAuthenticator.request_token_manager.get_token_info(token_value)[:-2]).is_equal_to((user, session_id))\n\n # session does not exists\n mock_verify_session_existence(mocker, exists=False)\n with pytest.raises(DCVAuthenticator.IncorrectRequestError):\n DCVAuthenticator._get_request_token(user, session_id)\n\n\n@pytest.mark.parametrize(\n \"user, session_id\",\n [\n (\"-1234abcd_-\", \"mysession\"),\n (\"a^mc\", \"mysession\"),\n (\"aAmc\", \"mysession\"),\n ('a\"mc', \"mysession\"),\n (\"a1234abcd_-\", \"^mysession\"),\n (\"a1234abcd_-\", \"mys+ession\"),\n (\"a1234abcd_-\", \"\".join((\"c\" for _ in range(129)))),\n (\"\".join((\"c\" for _ in range(33))), \"mysession\"),\n ],\n)\ndef test_get_request_token_regex(user, session_id):\n with pytest.raises(DCVAuthenticator.IncorrectRequestError):\n DCVAuthenticator._get_request_token(user, session_id)\n\n\n@pytest.mark.parametrize(\"token\", [\"assvbsd\", \"?\" + \"\".join((\"c\" for _ in range(255)))])\ndef test_get_session_token_regex(token):\n with pytest.raises(DCVAuthenticator.IncorrectRequestError):\n DCVAuthenticator._get_session_token(token)\n\n\ndef test_check_auth(mocker):\n \"\"\"\n Verify the DCVAuthenticator._check_auth method.\n\n The method verifies the token validity for the given DCV session id.\n \"\"\"\n token = generate_random_token(256)\n user = \"centos\"\n session_id = \"mysession\"\n mock_verify_session_existence(mocker, exists=True)\n\n # valid\n DCVAuthenticator.session_token_manager.add_token(\n token, DCVAuthenticator.SessionTokenInfo(user, session_id, datetime.utcnow())\n )\n assert_that(DCVAuthenticator._check_auth(session_id, token)).is_equal_to(user)\n\n # expired\n DCVAuthenticator.session_token_manager.add_token(\n token,\n DCVAuthenticator.SessionTokenInfo(user, session_id, datetime.utcnow() - DCVAuthenticator.session_token_ttl),\n )\n time.sleep(1)\n assert_that(DCVAuthenticator._check_auth(session_id, token)).is_none()\n\n # wrong session\n DCVAuthenticator.session_token_manager.add_token(\n token, DCVAuthenticator.SessionTokenInfo(user, session_id, datetime.utcnow())\n )\n assert_that(DCVAuthenticator._check_auth(\"mysession2\", token)).is_none()\n\n\ndef obtain_timestamp(date):\n return (date - datetime(1970, 1, 1)).total_seconds()\n\n\ndef test_get_session_token(mocker):\n \"\"\"Verify the second step of the authentication process, the retrieval of the Session Token.\"\"\"\n request_token = \"\".join(\"a\" for _ in range(256))\n user = \"centos\"\n session_id = \"mysession\"\n access_file = \"access_file\"\n mock_verify_session_existence(mocker, exists=True)\n\n # empty\n with pytest.raises(DCVAuthenticator.IncorrectRequestError):\n DCVAuthenticator._get_session_token(request_token)\n\n # expired\n DCVAuthenticator.request_token_manager.add_token(\n request_token,\n DCVAuthenticator.RequestTokenInfo(\n user, session_id, datetime.utcnow() - DCVAuthenticator.request_token_ttl, access_file\n ),\n )\n with pytest.raises(DCVAuthenticator.IncorrectRequestError):\n DCVAuthenticator._get_session_token(request_token)\n\n # file does not exist\n DCVAuthenticator.request_token_manager.add_token(\n request_token, DCVAuthenticator.RequestTokenInfo(user, session_id, datetime.utcnow(), access_file)\n )\n with pytest.raises(DCVAuthenticator.IncorrectRequestError):\n DCVAuthenticator._get_session_token(request_token)\n\n # user is different\n mock_os(mocker, \"centos2\", obtain_timestamp(datetime.utcnow()))\n DCVAuthenticator.request_token_manager.add_token(\n request_token, DCVAuthenticator.RequestTokenInfo(user, session_id, datetime.utcnow(), access_file)\n )\n with pytest.raises(DCVAuthenticator.IncorrectRequestError):\n DCVAuthenticator._get_session_token(request_token)\n\n # file is expired\n mock_os(mocker, user, obtain_timestamp(datetime.utcnow() - DCVAuthenticator.request_token_ttl))\n DCVAuthenticator.request_token_manager.add_token(\n request_token, DCVAuthenticator.RequestTokenInfo(user, session_id, datetime.utcnow(), access_file)\n )\n with pytest.raises(DCVAuthenticator.IncorrectRequestError):\n DCVAuthenticator._get_session_token(request_token)\n\n # working\n mock_os(mocker, user, obtain_timestamp(datetime.utcnow()))\n mock_verify_session_existence(mocker, exists=True)\n # A nosec comment is appended to the following line in order to disable the B105 check.\n # Since the session token is not a hardcoded password but merely used for unit testing\n session_token = \"1234\" # nosec B105\n mock_generate_random_token(mocker, session_token)\n DCVAuthenticator.request_token_manager.add_token(\n request_token, DCVAuthenticator.RequestTokenInfo(user, session_id, datetime.utcnow(), access_file)\n )\n assert_that(DCVAuthenticator._get_session_token(request_token)).is_equal_to(\n json.dumps({\"sessionToken\": session_token})\n )\n assert_that(DCVAuthenticator.session_token_manager.get_token_info(session_token)[:-1]).is_equal_to(\n (user, session_id)\n )\n","sub_path":"test/unit/dcv/test_dcv_authenticator.py","file_name":"test_dcv_authenticator.py","file_ext":"py","file_size_in_byte":12276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"148825709","text":"from dotenv import load_dotenv\nimport os\nimport re\n\n# APIs\nimport discord\nfrom discord import Emoji\nfrom discord.utils import get\n\n# parsers\nfrom paste_parser import PasteParser\nfrom media_info_parser import MediaInfoParser\nfrom codecs_parser import CodecsParser\nfrom checker import Checker\n\n# load environment variables\nload_dotenv()\n\n# environment variables\nIGNORE_AFTER_LINE = os.environ.get(\"IGNORE_AFTER_LINE\").strip()\nREVIEW_CHANNELS = [x.strip() for x in os.environ.get(\"REVIEW_CHANNELS\").split(',')]\nREVIEW_REPLY_CHANNELS = [x.strip() for x in os.environ.get(\"REVIEW_REPLY_CHANNELS\").split(',')]\nBOT_CHANNELS = [x.strip() for x in os.environ.get(\"BOT_CHANNELS\").split(',')]\nSOURCE = os.environ.get(\"SOURCE\").strip()\nRELEASE_GROUP = os.environ.get(\"RELEASE_GROUP\").strip()\nVERSION = os.environ.get(\"VERSION\").strip()\n\ndef print_help():\n return \"vdator \" + VERSION + \" help: \" \\\n \"I take a Pastebin link with BDInfo and MediaInfo dump.\" \\\n \" I ignore all input after the line `\" + IGNORE_AFTER_LINE + \"`.\" \\\n \" I add reactions in the following review channels: `\" + \", \".join(REVIEW_CHANNELS) + \"`,\" + \\\n \" I reply with full summary from review channels to: `\" + \", \".join(REVIEW_REPLY_CHANNELS) + \"`\" + \\\n \" and post full summaries in: `\" + \", \".join(BOT_CHANNELS) + \"`.\" \\\n \" Add a minus (-) sign in front of unused audio tracks in BDInfo.\" \\\n \" I check:```\" \\\n \"Video track names\\n\" \\\n \"Movie name format\\n\" \\\n \"Video and audio track names\\n\" \\\n \"DTS-HD MA 1.0/2.0 to FLAC, LPCM 1.0/2.0 to FLAC, LPCM > 2.0 to DTS-HD MA\\n\" \\\n \"Commentary to AC-3 @ 224 kbps\\n\" \\\n \"Text muxing mode\\n\" \\\n \"Commentary track people and spellcheck\\n\" \\\n \"Subtitle order\\n\" \\\n \"Chapter languages```\"\n\nasync def add_status_reactions(client, message, content):\n # ignore help\n if re.match(r'vdator (\\d+\\.)(\\d+\\.)(\\d+) help', content):\n return\n \n # add status reactions to message based on content\n if \"WARNING\" not in content and \"ERROR\" not in content:\n await client.add_reaction(message, '✅')\n else:\n if \"WARNING\" in content:\n await client.add_reaction(message, '⚠')\n if \"ERROR\" in content:\n await client.add_reaction(message, '❌')\n \nclient = discord.Client()\n\n@client.event\nasync def on_ready():\n print(\"I'm in\")\n print(client.user)\n\n@client.event\nasync def on_message(message):\n # only listens in bot and review channels\n if not (message.channel.name in BOT_CHANNELS or message.channel.name in REVIEW_CHANNELS):\n return\n \n # help command\n if message.content == \"!help\":\n reply = print_help()\n await client.send_message(message.channel, reply)\n return\n \n # self\n if message.author == client.user:\n # add status reactions to own messages\n await add_status_reactions(client, message, message.content)\n return\n\n if \"pastebin.com\" in message.content:\n # extract url from message\n url = re.search(\"(?Phttps?://[^\\s]+)\", message.content).group(\"url\")\n paste_parser = PasteParser()\n bdinfo, mediainfo = paste_parser.paste(url)\n reply = \"<\" + url + \">\" + \"\\n\"\n\n try:\n # parse mediainfo\n mediainfo_parser = MediaInfoParser()\n mediainfo = mediainfo_parser.parse(mediainfo)\n checker = Checker(bdinfo, mediainfo)\n \n # check metadata\n reply += checker.check_movie_name()\n codecs = CodecsParser()\n reply += checker.check_filename(codecs, SOURCE, RELEASE_GROUP)\n reply += checker.check_tracks_have_language()\n reply += checker.check_video_language_matches_first_audio_language()\n reply += checker.check_muxing_mode()\n reply += checker.check_mkvmerge()\n \n # check video\n reply += checker.check_video_track()\n \n # check audio\n reply += checker.print_audio_track_names()\n reply += checker.check_audio_track_conversions()\n \n # TMDB and IMDb People API\n reply += checker.check_people()\n reply += checker.spell_check_commentary()\n \n # check text\n reply += checker.print_text_tracks()\n reply += checker.text_order()\n \n # check chapters\n reply += checker.chapter_language()\n \n # report\n reply += checker.display_report()\n except:\n reply += \"\\n[ERROR] vdator failed to parse\\n\"\n \n # limit reply length\n reply = reply[:int(os.environ.get(\"DISCORD_MSG_CHAR_LIMIT\"))]\n \n if message.channel.name in BOT_CHANNELS:\n # reply in bot channel\n await client.send_message(message.channel, reply)\n elif message.channel.name in REVIEW_CHANNELS:\n # add reactions in review channel\n await add_status_reactions(client, message, reply)\n \n # and send reply to\n for ch in REVIEW_REPLY_CHANNELS:\n channel = get(message.server.channels, name=ch, type=discord.ChannelType.text)\n await client.send_message(channel, reply)\n \ntoken = os.environ.get(\"DISCORD_BOT_SECRET\")\nclient.run(token)\n","sub_path":"vdator/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"437051411","text":"import matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport random\r\nimport time\r\n\r\n\r\nclass AntColonyOptimisation:\r\n \"\"\" The Main Class \"\"\"\r\n\r\n def __init__(self, map_size=10, colony_size=20, start_point_x=0, start_point_y=0,\r\n alpha=2.0, beta=1, mode=1, evaporation_rate=0.2,\r\n iteration_amount=100, end_point_x=0, end_point_y=0, obstacle_amount=0,\r\n dynamic_obstacles=\"\"):\r\n self.start_point_x = start_point_x\r\n self.start_point_y = start_point_y\r\n self.end_point_x = end_point_x\r\n self.end_point_y = end_point_y\r\n self.map_size = map_size = map_size + 1\r\n self.grid_map = np.ndarray(shape=(map_size, map_size), dtype=object)\r\n self.colony_size = colony_size\r\n self.alpha = alpha\r\n self.beta = beta\r\n self.shortest_path = []\r\n self.evaporation_rate = evaporation_rate\r\n self.global_best = []\r\n self.mode = mode\r\n self.iteration_amount = iteration_amount\r\n self.ants = []\r\n self.obstacle_amount = obstacle_amount\r\n self.best_path_so_far = []\r\n self.dynamic_obstacle = dynamic_obstacles\r\n self.elitist_convergence_time = 0\r\n self.ant_system_convergence_time = 0\r\n self.as_average_iterations = 0\r\n self.eas_average_iterations = 0\r\n self.eas_length_list = []\r\n self.as_length_list = []\r\n\r\n def create_grid_map(self, map_size):\r\n \"\"\" Initialises The Grid Space Dependent On The Map Size \"\"\"\r\n for x in range(map_size):\r\n for y in range(map_size):\r\n self.grid_map[x, y] = Node(x, y)\r\n # self.grid_map[x, y].print_information()\r\n self.set_hive()\r\n self.set_goal()\r\n if self.obstacle_amount > 0:\r\n self.generate_random_obstacles()\r\n\r\n def obstacle_add_remove(self, x=3, y=3):\r\n \"\"\" The Method Used To Initialise The Obstacle Attribute Of A Node\"\"\"\r\n if self.grid_map[x, y].obstacle_present:\r\n self.grid_map[x, y].obstacle_present = False\r\n # print(\"Obstacle Has Been Added At \" + str(self.grid_map[x, y]) + \"!\")\r\n elif not self.grid_map[x, y].obstacle_present:\r\n self.grid_map[x, y].obstacle_present = True\r\n # print(\"Obstacle Has Been Added At \" + \"[\" + str(x) + \", \" + str(y) + \"]\" + \"!\")\r\n\r\n def display_grid(self, map_size):\r\n \"\"\" Initialises The Nodes Of The Grid Dependent On The Map Size \"\"\"\r\n for x in range(map_size):\r\n for y in range(map_size):\r\n if self.grid_map[x, y].hive:\r\n ax.scatter(x, y, c=\"#19FF30\", edgecolors=\"#000000\")\r\n continue\r\n if self.grid_map[x, y].goal:\r\n ax.scatter(x, y, c=\"#FF1018\", edgecolors=\"#000000\")\r\n continue\r\n if self.grid_map[x, y].obstacle_present:\r\n ax.scatter(x, y, c=\"#000000\", edgecolors=\"#FF1018\")\r\n continue\r\n else:\r\n cmap = plt.get_cmap('Blues')\r\n ax.scatter(x, y, color=cmap(self.grid_map[x, y].pheromone_amount))\r\n\r\n def display_pheromone_map(self):\r\n \"\"\" Method For Printing Out The Pheromone Levels In Command Line\"\"\"\r\n for x in range(aco.map_size):\r\n for y in range(aco.map_size):\r\n print(\" [\" + str(aco.grid_map[x, y].x) + \", \" + str(aco.grid_map[x, y].y) + \"] : \" +\r\n str(aco.grid_map[x, y].pheromone_amount))\r\n\r\n def set_hive(self):\r\n \"\"\" Sets the hive to user defined start point\"\"\"\r\n self.grid_map[self.start_point_x, self.start_point_y].hive = True\r\n\r\n def set_goal(self):\r\n \"\"\" Sets the goal to user defined end point\"\"\"\r\n self.grid_map[self.end_point_x, self.end_point_y].goal = True\r\n\r\n def ant_system(self):\r\n \"\"\" Method For Ant Colony System\"\"\"\r\n start_time = time.clock()\r\n for i in range(aco.iteration_amount):\r\n ants = [(Ant(aco.grid_map[aco.start_point_x, aco.start_point_y].x,\r\n aco.grid_map[aco.start_point_x, aco.start_point_y].y)) for i in range(aco.colony_size)]\r\n print(\"Iteration: \" + str(i))\r\n if i == (aco.iteration_amount // 2) and self.dynamic_obstacle.lower() == \"y\":\r\n aco.display_grid(aco.map_size)\r\n plt.savefig('as_pre_obstacle')\r\n self.generate_random_obstacles()\r\n for ant in ants:\r\n while not ant.tour_finished:\r\n if len(ant.route_taken) > 1000:\r\n print(\"Ant Timed Out\")\r\n # print(\"[\" + str(ant.current_node.x) + \", \" + str(ant.current_node.y) + \"]\")\r\n # print(\"Pheromone Is At: \" + str(aco.grid_map[ant.current_node.x,\r\n # ant.current_node.y].pheromone_amount))\r\n ant.tour_finished = True\r\n ant.found_solution = False\r\n ant.move_ant()\r\n for ant in ants:\r\n if ant.tour_finished and ant.found_solution:\r\n if len(aco.best_path_so_far) == 0:\r\n aco.best_path_so_far = ant.route_taken\r\n new_as_convergence_time = time.clock()\r\n self.as_average_iterations = i\r\n elif len(aco.best_path_so_far) > len(ant.route_taken):\r\n aco.best_path_so_far = ant.route_taken\r\n new_as_convergence_time = time.clock()\r\n self.as_average_iterations = i\r\n ant.ant_system_pheromone_update()\r\n aco.ant_system_global_pheromone_update()\r\n self.as_length_list.append(len(aco.best_path_so_far))\r\n self.ant_system_convergence_time = (new_as_convergence_time - start_time)\r\n\r\n def ant_system_global_pheromone_update(self):\r\n \"\"\" Method For Ant System Global Pheromone Update \"\"\"\r\n for x in range(aco.map_size):\r\n for y in range(aco.map_size):\r\n self.grid_map[x, y].pheromone_amount = (1.0 - aco.evaporation_rate) \\\r\n * self.grid_map[x, y].pheromone_amount\r\n\r\n def elitist_aco(self):\r\n \"\"\" Method For Elitist ACO\"\"\"\r\n start_time = time.clock()\r\n for i in range(aco.iteration_amount):\r\n ants = [(Ant(aco.grid_map[aco.start_point_x, aco.start_point_y].x, aco.grid_map[aco.start_point_x,\r\n aco.start_point_y].y)) for i\r\n in range(aco.colony_size)]\r\n print(\"Iteration: \" + str(i))\r\n if i == (aco.iteration_amount // 2) and self.dynamic_obstacle.lower() == \"y\":\r\n aco.display_grid(aco.map_size)\r\n plt.savefig('eas_pre_obstacles')\r\n self.generate_random_obstacles()\r\n for ant in ants:\r\n while not ant.tour_finished:\r\n if len(ant.route_taken) > (int(aco.map_size)**int(aco.map_size)):\r\n print(\"Ant Timed Out\")\r\n # print(\"[\" + str(ant.current_node.x) + \", \" + str(ant.current_node.y) + \"]\")\r\n # print(\"Pheromone Is At: \" + str(aco.grid_map[ant.current_node.x,\r\n # ant.current_node.y].pheromone_amount))\r\n ant.tour_finished = True\r\n ant.found_solution = False\r\n ant.move_ant()\r\n for ant in ants:\r\n if ant.tour_finished and ant.found_solution:\r\n if not aco.global_best:\r\n aco.global_best = ant.route_taken\r\n new_convergence_time = time.clock()\r\n self.eas_average_iterations = i\r\n elif len(aco.global_best) > len(ant.route_taken):\r\n aco.global_best = ant.route_taken\r\n new_convergence_time = time.clock()\r\n self.eas_average_iterations = i\r\n ant.elitist_aco_pheromone_update()\r\n aco.ant_system_global_pheromone_update()\r\n self.eas_length_list.append(len(aco.global_best))\r\n self.elitist_convergence_time = (new_convergence_time - start_time)\r\n def ant_colony_system(self):\r\n \"\"\" Ant Colony System\r\n Adds Local Pheromone Update\r\n Best Only Global Update \"\"\"\r\n\r\n for i in range(aco.iteration_amount):\r\n ants = [(Ant(aco.grid_map[1, 1].x, aco.grid_map[1, 1].y)) for i in range(aco.colony_size)]\r\n print(\"Iteration: \" + str(i))\r\n for ant in ants:\r\n while not ant.tour_finished:\r\n if len(ant.route_taken) > 1000:\r\n print(\"Ant Timed Out\")\r\n # print(\"[\" + str(ant.current_node.x) + \", \" + str(ant.current_node.y) + \"]\")\r\n # print(\"Pheromone Is At: \" + str(aco.grid_map[ant.current_node.x,\r\n # ant.current_node.y].pheromone_amount))\r\n ant.tour_finished = True\r\n ant.found_solution = False\r\n ant.move_ant()\r\n ant.acs_local_pheromone_update()\r\n if ant.tour_finished and ant.found_solution:\r\n ant.acs_offline_update()\r\n aco.ant_system_global_pheromone_update()\r\n\r\n def generate_random_obstacles(self):\r\n \"\"\" Generates Random Obstacles \"\"\"\r\n amount_of_obstacles_added = 0\r\n while amount_of_obstacles_added < aco.obstacle_amount:\r\n obstacle_x = random.randint(0, aco.map_size - 1)\r\n obstacle_y = random.randint(0, aco.map_size - 1)\r\n if not aco.grid_map[obstacle_x, obstacle_y].hive and not aco.grid_map[obstacle_x, obstacle_y].goal:\r\n aco.grid_map[obstacle_x, obstacle_y].obstacle_present = True\r\n amount_of_obstacles_added += 1\r\n\r\n def display_best_path(self):\r\n for node in aco.global_best:\r\n if not node.hive and not node.goal:\r\n ax.scatter(self.grid_map[node.x, node.y].x, self.grid_map[node.x, node.y].y,\r\n color='#e67e22', edgecolors=\"#000000\")\r\nclass Node:\r\n \"\"\" Class That Describes Each Node \"\"\"\r\n\r\n def __init__(self, x, y, pheromone_amount=0.1):\r\n self.x = x\r\n self.y = y\r\n self.pheromone_amount = pheromone_amount\r\n self.obstacle_present = False\r\n self.hive = False\r\n self.goal = False\r\n self.heuristic_value = 1\r\n\r\n def print_information(self):\r\n print(\"--- [\" + str(self.x) + \", \" + str(self.y) + \"] ---\")\r\n print(\"Node's Pheromone Strength Is: \" + str(self.pheromone_amount))\r\n print(\"Obstacle Presence: \" + str(self.obstacle_present))\r\n\r\n\r\nclass Ant:\r\n \"\"\" Class For The Ant Objects \"\"\"\r\n\r\n def __init__(self, x_value, y_value, ):\r\n self.x = x_value\r\n self.y = y_value\r\n self.route_taken = [aco.grid_map[self.x, self.y]]\r\n self.current_node = aco.grid_map[self.x, self.y]\r\n self.possible_nodes = []\r\n self.node_choice = Node\r\n self.tour_finished = False\r\n self.found_solution = False\r\n\r\n def move_ant(self):\r\n \"\"\" Function To Deal With Moving The Ant \"\"\"\r\n\r\n node_probability_total = 0.0\r\n self.get_possible_moves()\r\n\r\n # Code Adapted From Rochakgupta, 2018\r\n # Loops through all possible nodes that can be travelled to by the ant\r\n # node_probability_total stores the probability amount of each possible node selection and then\r\n # is used in conjunction with random_value to randomly decide which node to use\r\n if len(self.possible_nodes) > 0:\r\n for possible_node in self.possible_nodes:\r\n node_probability_total += pow(possible_node.pheromone_amount, aco.alpha) * \\\r\n pow(possible_node.heuristic_value, aco.beta)\r\n random_value = random.uniform(0.0, node_probability_total)\r\n\r\n probability = 0.0\r\n for possible_node in self.possible_nodes:\r\n probability += pow(possible_node.pheromone_amount, aco.alpha) * \\\r\n pow(possible_node.heuristic_value, aco.beta)\r\n if probability >= random_value:\r\n self.node_choice = possible_node\r\n self.possible_nodes.clear()\r\n break\r\n # End Of Adapted Code\r\n\r\n self.current_node = self.node_choice\r\n self.route_taken.append(self.current_node)\r\n self.x = self.current_node.x\r\n self.y = self.current_node.y\r\n if aco.mode == 1:\r\n if self.current_node.goal:\r\n self.tour_finished = True\r\n self.found_solution = True\r\n print(\"Ant Has Reached Goal In: \" + str(len(self.route_taken)))\r\n elif aco.mode == 2:\r\n if self.current_node.goal:\r\n self.tour_finished = True\r\n self.found_solution = True\r\n print(\"Ant Has Reached Goal In: \" + str(len(self.route_taken)))\r\n elif aco.mode == 3:\r\n if self.current_node.goal:\r\n self.tour_finished = True\r\n self.found_solution = True\r\n print(\"Ant Has Reached Goal In: \" + str(len(self.route_taken)))\r\n elif len(self.possible_nodes) <= 0:\r\n print(\"No Nodes Available\")\r\n self.tour_finished = True\r\n self.found_solution = False\r\n\r\n def ant_system_pheromone_update(self):\r\n \"\"\" Adds Pheromone Based On Ant System Update Algorithm \"\"\"\r\n # Local Update\r\n for node in self.route_taken:\r\n pheromone_to_add = (1 / len(self.route_taken))\r\n node.pheromone_amount += pheromone_to_add\r\n\r\n def elitist_aco_pheromone_update(self):\r\n \"\"\" Pheromone Update Using Elitist Ant Colony Optimisation \"\"\"\r\n for node in self.route_taken:\r\n pheromone_to_add = (1 / len(self.route_taken))\r\n node.pheromone_amount += pheromone_to_add\r\n for node in aco.global_best:\r\n pheromone_to_add = (1 / len(aco.global_best))\r\n node.pheromone_amount += pheromone_to_add\r\n\r\n def acs_local_pheromone_update(self):\r\n \"\"\" Local Pheromone Update For ACS \"\"\"\r\n pheromone_to_add = aco.evaporation_rate * aco.grid_map[self.x, self.y].pheromone_amount\r\n aco.grid_map[self.x, self.y].pheromone_amount = (1 / aco.evaporation_rate) * \\\r\n aco.grid_map[self.x, self.y].pheromone_amount + pheromone_to_add\r\n\r\n def acs_offline_update(self):\r\n \"\"\" Ant Colony System Offline Update \"\"\"\r\n for node in aco.global_best:\r\n pheromone_to_add = (1 / len(aco.global_best))\r\n node.pheromone_amount = (1 - aco.evaporation_rate) * aco.grid_map[self.x, self.y].pheromone_level + \\\r\n (aco.evaporation_rate * pheromone_to_add)\r\n\r\n def print_ant_information(self):\r\n \"\"\" Prints Out Ant Location On Map \"\"\"\r\n print(\"Ant Is At: [\" + str(self.x) + \", \" + str(self.y) + \"]\")\r\n\r\n def get_possible_moves(self):\r\n \"\"\" Collects Possible Nodes Ant Can Move To \"\"\"\r\n new_possible_nodes = []\r\n # Code Adapted From Justin Peel, 2018\r\n for x, y in [(self.x + i, self.y + j) for i in (-1, 0, 1) for j in (-1, 0, 1) if i != 0 or j != 0]:\r\n # End Of Adapted Code\r\n # Checks If The Move Is Outside Map Upper Boundaries\r\n if x >= aco.map_size or y >= aco.map_size:\r\n continue\r\n # Checks If The Node Is An Obstacle\r\n if not aco.grid_map[x, y].obstacle_present:\r\n # If The Node Is Also Not Outside Grid's Lower Boundary\r\n if x < 0 or y < 0:\r\n continue\r\n # Adds The Node To A List Of Possible Nodes\r\n self.possible_nodes.append(aco.grid_map[x, y])\r\n for possible_node in self.possible_nodes:\r\n if possible_node not in self.route_taken:\r\n new_possible_nodes.append(possible_node)\r\n self.possible_nodes = new_possible_nodes\r\n # print(\"--- Possible Nodes For [\" + str(self.x) + \", \" + str(self.y) + \"]\")\r\n # for possible_node in self.possible_nodes:\r\n # if possible_node not in self.route_taken:\r\n # print(\"[\" + str(possible_node.x) + \", \" + str(possible_node.y) + \"]\")\r\n\r\n\r\nfig, ax = plt.subplots()\r\nax.set_title('Ant Colony Optimisation')\r\n\r\nuser_map_size = int(input(\"Enter The Size Of The Map To Be Generated: \"))\r\nresponse = input(\"Do You Wish To Define Custom Start/Goal? (Y/N): \")\r\nif response.lower() == 'y':\r\n user_start_x = int(input(\"Enter Start X Position: \"))\r\n user_start_y = int(input(\"Enter Start Y Position: \"))\r\n user_end_x = int(input(\"Enter End X Position: \"))\r\n user_end_y = int(input(\"Enter End Y Position: \"))\r\n user_generate_obstacles = int(input(\"How Many Obstacles Do You Want Generated: \"))\r\n user_generate_dynamic_obstacles = str(input(\"Add Dynamic Obstacles? (Y/N): \"))\r\n user_ant_colony_size = int(input(\"Amount Of Ants To Spawn: \"))\r\n user_amount_of_iterations = int(input(\"Amount Of Iterations: \"))\r\n\r\n aco = AntColonyOptimisation(map_size=user_map_size, start_point_x=user_start_x, start_point_y=user_start_y,\r\n end_point_x=user_end_x, end_point_y=user_end_y, obstacle_amount=user_generate_obstacles,\r\n colony_size=user_ant_colony_size, iteration_amount=user_amount_of_iterations,\r\n dynamic_obstacles=user_generate_dynamic_obstacles)\r\n aco.create_grid_map(aco.map_size)\r\n print(\"\\n --- Ant System ---\\n\")\r\n aco.mode = 1\r\n print(\" --- Starting ---\")\r\n aco.ant_system()\r\n aco.display_pheromone_map()\r\n aco.display_grid(aco.map_size)\r\n plt.savefig('Ant_system')\r\n print(\"Shortest Path: \" + str(len(aco.best_path_so_far)))\r\n print(\"Time Taken: \" + str(aco.ant_system_convergence_time))\r\n print(\"Iteration Taken To Reach: \" + str(aco.as_average_iterations))\r\n aco = AntColonyOptimisation(map_size=user_map_size, start_point_x=user_start_x, start_point_y=user_start_y,\r\n end_point_x=user_end_x, end_point_y=user_end_y, obstacle_amount=user_generate_obstacles,\r\n colony_size=user_ant_colony_size, iteration_amount=user_amount_of_iterations,\r\n dynamic_obstacles=user_generate_dynamic_obstacles)\r\n aco.create_grid_map(aco.map_size)\r\n print(\"\\n --- Elite Ant System --- \\n\")\r\n aco.mode = 2\r\n print(\" --- Starting ---\")\r\n aco.elitist_aco()\r\n aco.display_pheromone_map()\r\n aco.display_grid(aco.map_size)\r\n aco.display_best_path()\r\n plt.savefig(\"Elitist_ant_system\")\r\n print(\"Shortest Path: \" + str(len(aco.global_best)))\r\n print(\"Time Taken: \" + str(aco.elitist_convergence_time))\r\n print(\"Iteration Taken To Reach: \" + str(aco.eas_average_iterations))\r\nif response.lower() == 'n':\r\n user_generate_obstacles = int(input(\"How Many Obstacles Do You Want Generated: \"))\r\n user_generate_dynamic_obstacles = str(input(\"Add Dynamic Obstacles? (Y/N): \"))\r\n user_ant_colony_size = int(input(\"Amount Of Ants To Spawn: \"))\r\n user_amount_of_iterations = int(input(\"Amount Of Iterations: \"))\r\n aco = AntColonyOptimisation(map_size=user_map_size, start_point_x=0, start_point_y=0, end_point_x=user_map_size - 1,\r\n end_point_y=user_map_size-1, obstacle_amount=user_generate_obstacles,\r\n colony_size=user_ant_colony_size, iteration_amount=user_amount_of_iterations,\r\n dynamic_obstacles=user_generate_dynamic_obstacles)\r\n aco.create_grid_map(aco.map_size)\r\n print(\"\\n --- Ant System ---\\n\")\r\n aco.mode = 1\r\n print(\" --- Starting ---\")\r\n aco.ant_system()\r\n aco.display_pheromone_map()\r\n aco.display_grid(aco.map_size)\r\n plt.savefig('Ant_system')\r\n print(\"Shortest Path: \" + str(len(aco.best_path_so_far)))\r\n print(\"Time Taken: \" + str(aco.ant_system_convergence_time))\r\n print(\"Iteration Taken To Reach: \" + str(aco.as_average_iterations))\r\n #for length in aco.as_length_list:\r\n # print(aco.as_length_list)\r\n\r\n aco = AntColonyOptimisation(map_size=user_map_size, start_point_x=0, start_point_y=0, end_point_x=user_map_size - 1,\r\n end_point_y=user_map_size-1, obstacle_amount=user_generate_obstacles,\r\n colony_size=user_ant_colony_size, iteration_amount=user_amount_of_iterations,\r\n dynamic_obstacles=user_generate_dynamic_obstacles)\r\n aco.create_grid_map(aco.map_size)\r\n print(\"\\n --- Elite Ant System --- \\n\")\r\n aco.mode = 2\r\n print(\" --- Starting ---\")\r\n aco.elitist_aco()\r\n aco.display_pheromone_map()\r\n aco.display_grid(aco.map_size)\r\n aco.display_best_path()\r\n plt.savefig(\"Elitist_ant_system\")\r\n print(\"Shortest Path: \" + str(len(aco.global_best)))\r\n print(\"Time Taken: \" + str(aco.elitist_convergence_time))\r\n print(\"Iteration Taken To Reach: \" + str(aco.eas_average_iterations))\r\n #for length in aco.eas_length_list:\r\n # print(aco.eas_length_list)\r\n\r\n\r\n#filename = 'ant_system_details'\r\n#with open(filename, 'w') as file_object\r\n # file_object.write()\r\n\r\n\r\n#print(\"\\n --- Ant Colony System ---\")\r\n\r\n# aco = AntColonyOptimisation()\r\n# aco.create_grid_map(aco.map_size)\r\n# aco.obstacle_add_remove(5, 6)\r\n# aco.obstacle_add_remove(3, 4)\r\n# aco.obstacle_add_remove(3, 5)\r\n# aco.obstacle_add_remove(3, 6)\r\n# aco.obstacle_add_remove(4, 3)\r\n# aco.obstacle_add_remove(5, 3)\r\n# aco.obstacle_add_remove(4, 6)\r\n# aco.obstacle_add_remove(5, 5)\r\n# aco.obstacle_add_remove(5, 4)\r\n# aco.obstacle_add_remove(3, 3)\r\n# aco.mode = 3\r\n\r\n# print(\" --- Starting ---\")\r\n# aco.ant_colony_system()\r\n# aco.display_pheromone_map()\r\n# aco.display_grid(aco.map_size)\r\n# plt.savefig(\"Ant Colony System\")\r\n\r\nplt.show()\r\n","sub_path":"AntColonyOptimisation.py","file_name":"AntColonyOptimisation.py","file_ext":"py","file_size_in_byte":22548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"203352464","text":"# encoding: utf-8\nfrom tornado.util import (unicode_type, ObjectDict)\nfrom tornado.escape import json_decode, json_encode\nfrom lib.core import config_settings, RestfulApiHandler\nimport logging, traceback\nimport sys\nimport os,time\nimport json\n\nclass ApiHandler(RestfulApiHandler):\n def request_dealer(self, *args, **kwargs):\n try:\n if len(args)==2:\n app, method = args\n else:\n pass\n # module = __import__('__api_'+app.lower())\n module = __import__(app)\n module = module.ApiProvider(self, self.settings)\n ret = module.executer(method)\n\n if self._status_code == 302 or self._finished:return\n\n cb = self.get_argument('callback','')\n if cb: self.write(cb + '(')\n self.write(ret)\n if cb: self.write(')')\n return\n except Exception as e:\n if self._status_code == 302:\n return\n e = '%s %s' % (e, traceback.format_exc())\n logging.error(e)\n # errorinfo = {}\n # errorinfo['fromip'] = self.request.remote_ip\n # errorinfo['errorinfo'] = e\n # errorinfo['fullurl'] = self.request.full_url()\n # errorinfo['debug'] = self.application.settings.get('debug')\n # errorinfo['codesource'] = 'API'\n # errorinfo['useragent'] = self.request.headers.get(\"User-Agent\", \"\")\n # errorinfo['refer'] = self.request.headers.get('Referer', '')\n # # errorinfo['mail_recv'] = 'developer@zhiguagua.com'\n # errorinfo['parambody'] = ''\n # if self.request.method == 'POST':\n # errorinfo['parambody'] = self.request.body\n # from Util4AI.NotifyDeveloper import NotifyDeveloper\n # NotifyDeveloper.send_error_msg(self.application.dc.redisDb, self.application.dc.mysqlDb_write, errorinfo)\n\n","sub_path":"lib/handlers/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"86694610","text":"from flask import Flask, render_template, request\nfrom chatterbot import ChatBot\nfrom chatterbot.trainers import ChatterBotCorpusTrainer\nfrom models import User\nPOSTGRES = {\n'user': 'root',\n'pw': 'root',\n'db': 'usuarios',\n'host': '127.0.0.1',\n'port': '5432',\n}\napp = Flask(__name__)\n \nenglish_bot = ChatBot(\"Chatterbot\", storage_adapter=\"chatterbot.storage.SQLStorageAdapter\")\ntrainer = ChatterBotCorpusTrainer(english_bot)\ntrainer.train(\"chatterbot.corpus.spanish\")\n\napp.config['SECRET_KEY'] = '7110c8ae51a4b5af97be6534caef90e4bb9bdcb3380af008f90b23a5d1616bf319bc298105da20fe'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://%(user)s:\\%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\nlogin_manager = LoginManager(app)\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n \n@app.route(\"/get\")\ndef get_bot_response():\n \n userText = request.args.get('msg')\n user = User(mensaje=userText)\n user.save()\n respuesta = User.get_by_mensaje(userText)\n return str(spanish_bot.get_response(userText))\n \n \nif __name__ == \"__main__\":\n app.run()\n","sub_path":"mainbot.py","file_name":"mainbot.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"222683519","text":"import unittest\nfrom rts.gen.gen import Gen\n\n\nclass GenTestCase(unittest.TestCase):\n \"\"\" Tests for `gen.py`.\"\"\"\n\n def test_produces_correct_num_task(self):\n gen_param = {\n 'num_task': 10,\n }\n g = Gen(**gen_param)\n ts = g.next_task_set()\n\n self.assertEqual(len(ts), 10)\n\n def test_correct_exec_time_range(self):\n gen_param = {\n 'num_task': 1,\n 'min_exec_time': 0,\n 'max_exec_time': 10,\n }\n g = Gen(**gen_param)\n ts = g.next_task_set()\n\n self.assertTrue(ts[0].exec_time <= 10)\n self.assertTrue(ts[0].exec_time >= 0)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/unit/gen/test_gen.py","file_name":"test_gen.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"249619832","text":"\nimport pandas as pd\nimport numpy as np\ncol_names = [\"ID\", \"label\"]\ncol_nameg = [\"label\"]\ndata1 = pd.read_csv(\"submission28.csv\", names=col_nameg)\ndata2 = pd.read_csv(\"submission711.csv\", names=col_names)\n# data2 = pd.read_csv(\"baidu_sub5(1)0.8979_xgb.csv\", names=col_names)\nnumber1=data1[[\"label\"]].as_matrix()\nnumber1=np.array(number1).reshape(len(number1))\n\nnumber2=data2[[\"label\"]].as_matrix()\nnumber2=np.array(number2).reshape(len(number2))\n\neq=0\nnoteq=0\nfor i in range(len(number1)):\n if number1[i] == number2[i]:\n eq=eq+1\n else:\n noteq=noteq+1\n\nprint(\"not equale:\"+str(noteq))","sub_path":"ML_learning/judege.py","file_name":"judege.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"631972222","text":"class Settings:\n \"\"\"\n 存储游戏《外星人入侵》中所有设置的类\n \"\"\"\n def __init__(self):\n \"\"\"\n 初始化游戏设置\n \"\"\"\n # 屏幕设置\n self.screen_width = 900\n self.screen_height = 600\n self.bg_color = (248, 248, 248)\n\n # 飞船移动速度\n self.ship_speed = 1.5\n\n # 子弹设置\n self.bullet_speed = 1.0\n self.bullet_width = 3\n self.bullet_height = 15\n self.bullet_color = (60, 60, 60)\n\n # 最大子弹数量\n self.bullets_allowed = 6\n \n # 外星人设置\n self.alien_speed = 1.0\n self.fleet_drop_speed = 10\n # fleet_direction为1表示向右移,为-1表示向左移\n self.fleet_direction = 1","sub_path":"pygame_alien_invasion/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"386880261","text":"from __future__ import absolute_import, division, print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom CNN_configuration import CNN2DConfiguration\n\ntf.logging.set_verbosity(tf.logging.INFO)\n\nconfig = CNN2DConfiguration()\n\n\n# Create Wrappers for reuse\n\ndef max_pool2d(features):\n k = config.pool_stride\n return tf.nn.max_pool(features, ksize=[1, k, k, 1], strides=[1, k, k, 1], padding='SAME')\n\n\ndef conv2d(features, w, b):\n\n x = tf.nn.conv2d(features, w, strides=[1, config.conv_stride, config.conv_stride, 1], padding='SAME')\n x = tf.nn.bias_add(x, b)\n return config.conv_activation(x)\n\n\ndef weight_variable(shape):\n return tf.Variable(tf.truncated_normal(shape, stddev=0.1))\n\n\ndef bias_variable(shape):\n return tf.Variable(tf.constant(0.1, shape=shape))\n\n\n# Create Model\ndef conv2_feature_net(features, weight, bias, dropout=config.drop_out,\n stft_freq_step=config.stft_freq_step, stft_time_step=config.stft_time_step):\n # Features dimension: [batch_size, input_size, num_channel]\n # reshape into [batch_size, stft_freq_step, stft_time_step, num_channel]\n features = tf.cast(features, tf.float32)\n features = tf.reshape(features, [-1, stft_freq_step, stft_time_step, config.num_channel])\n\n # Conv Layer 1\n with tf.name_scope('conv_1_layer'):\n conv1 = conv2d(features, weight['wc1'], bias['bc1'])\n # Max Pooling\n conv1 = max_pool2d(conv1)\n # batch normalization\n # norm1 = tf.layers.batch_normalization(conv1, axis=1)\n\n # Conv Layer 2\n with tf.name_scope('conv_2_layer'):\n conv2 = conv2d(conv1, weight['wc2'], bias['bc2'])\n # Max Pooling\n conv2 = max_pool2d(conv2)\n # batch normalization\n # norm2 = tf.layers.batch_normalization(conv2, axis=1)\n\n # Fully Connected Layer 1\n with tf.name_scope('fully_connected_layer_1'):\n fc1 = tf.reshape(conv2, [-1, weight['wd1'].get_shape().as_list()[0]])\n fc1 = tf.add(tf.matmul(fc1, weight['wd1']), bias['bd1'])\n fc1 = config.dense_activation(fc1)\n # Apply Dropout\n fc1 = tf.nn.dropout(fc1, dropout)\n\n # Output Layer\n # out = tf.add(tf.matmul(fc1, weight['out']), bias['out'])\n # return out\n return fc1\n\n\n# Construct RNN network\n# input: x: [batch_size, time_step, fc1+num_class], Note that the feature is concatenation of CNN output and\n# previous stage labels(one_hot encoded). For current stage, all zero is concatenated with CNN\n# output to fill up the place.\n# rnn_size: e.g. [32, 64, 128] defines 3 layer GRU net with 32, 64, 128 neurons in each layer respectively\n#\n# output:\n# pred: [batch_size, num_class], the prediction of sleep stage.\ndef rnn_net_concat(x, weights, biases, rnn_size=config.rnn_size):\n\n # Instantiate Basic RNN cells\n with tf.name_scope('LSTM_layers'):\n rnn_cells = tf.contrib.rnn.BasicLSTMCell(num_units=rnn_size)\n rnn_cells = tf.contrib.rnn.DropoutWrapper(rnn_cells, output_keep_prob=config.drop_out)\n outputs, _ = tf.contrib.rnn.static_rnn(rnn_cells, x, dtype=tf.float32)\n pred = tf.add(tf.matmul(outputs[-1], weights['rnn_out']), biases['rnn_out'])\n\n return pred\n\n\n# Define functions that initialize weights and biases\ndef get_config_weights_biases():\n\n # Calculate weight size for densely connected layers\n height = config.stft_freq_step\n width = config.stft_time_step\n height = np.ceil(height / config.pool_stride)\n width = np.ceil(width / config.pool_stride)\n height = np.ceil(height / config.pool_stride)\n width = np.ceil(width / config.pool_stride)\n flat = np.int32(height * width * config.conv_2_channel)\n\n # Store Layers weights and Biases\n weights = {\n 'wc1': weight_variable([config.kernel_size, config.kernel_size, config.num_channel, config.conv_1_channel]),\n\n 'wc2': weight_variable([config.kernel_size, config.kernel_size, config.conv_1_channel, config.conv_2_channel]),\n\n 'wd1': weight_variable(([flat, config.dense_1])),\n\n # densely connected layer 2\n # 'wd2': tf.Variable(tf.random_normal([config.dense_1, config.dense_2])),\n 'wd2': weight_variable([config.dense_1, config.dense_2]),\n\n # output layer\n # 'out': tf.Variable(tf.random_normal([config.dense_1, config.num_class]))\n 'out': weight_variable([config.dense_1, config.num_class]),\n\n # RNN output layer\n 'rnn_out': weight_variable([config.rnn_size, config.num_class])\n }\n\n biases = {\n 'bc1': bias_variable([config.conv_1_channel]),\n 'bc2': bias_variable([config.conv_2_channel]),\n 'bd1': bias_variable([config.dense_1]),\n 'bd2': bias_variable([config.dense_2]),\n 'out': bias_variable([config.num_class]),\n 'rnn_out': bias_variable([config.num_class])\n }\n\n return weights, biases\n","sub_path":"proj_7_CNN_LSTM_Sleep_Stage_classification/old/CNN2D_LSTM_net.py","file_name":"CNN2D_LSTM_net.py","file_ext":"py","file_size_in_byte":4900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"431546134","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Created by HazzaCheng on 2020-08-30\n\nimport unittest\n\nfrom src.sort.No179_Largest_Number import Solution\n\n\nclass MyTestCase(unittest.TestCase):\n def setUp(self) -> None:\n self.solution = Solution()\n\n def test1(self):\n nums = [10, 2]\n self.assertEqual('210', self.solution.largestNumber1(nums))\n\n nums = [3, 30, 34, 5, 9]\n self.assertEqual('9534330', self.solution.largestNumber1(nums))\n\n def test2(self):\n nums = [10, 2]\n self.assertEqual('210', self.solution.largestNumber2(nums))\n\n nums = [3, 30, 34, 5, 9]\n self.assertEqual('9534330', self.solution.largestNumber2(nums))\n\n def test3(self):\n nums = [10, 2]\n self.assertEqual('210', self.solution.largestNumber3(nums))\n\n nums = [3, 30, 34, 5, 9]\n self.assertEqual('9534330', self.solution.largestNumber3(nums))\n\n def test4(self):\n nums = [10, 2]\n self.assertEqual('210', self.solution.largestNumber4(nums))\n\n nums = [3, 30, 34, 5, 9]\n self.assertEqual('9534330', self.solution.largestNumber4(nums))\n\n def test5(self):\n nums = [10, 2]\n self.assertEqual('210', self.solution.largestNumber5(nums))\n\n nums = [3, 30, 34, 5, 9]\n self.assertEqual('9534330', self.solution.largestNumber5(nums))\n\n def test6(self):\n nums = [10, 2]\n self.assertEqual('210', self.solution.largestNumber6(nums))\n\n nums = [3, 30, 34, 5, 9]\n self.assertEqual('9534330', self.solution.largestNumber6(nums))\n\n\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"python/test/sort/test_no179.py","file_name":"test_no179.py","file_ext":"py","file_size_in_byte":1621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"27753263","text":"import copy\nimport numpy as np\nimport scipy.linalg\nimport scipy.sparse\nimport scipy.sparse.linalg\nimport matplotlib.pyplot as plt\n\n# Defining the Pauli matrices to be used in our calculation\nS0 = np.array([[1, 0], [0, 1]])\nSx = np.array([[0, 1], [1, 0]])\nSy = np.array([[0, -1j], [1j, 0]])\nSz = np.array([[1, 0], [0, -1]])\n\n# Some variables chosen initally for potential calculation\n# Note hbar will likely be taken to be 1. I am keeping it here should I ever need it.\ndt = 1\nhbar = 1.05 * np.power(10.0, -34)\n\n\ndef countBits(x):\n \"\"\"\n The function takes counts the number of 1's in the binary representation of a base 10 integer.\n\n :param x: Base 10 integer\n :return: The number of ones of the integer in binary representation\n \"\"\"\n # from https://stackoverflow.com/questions/10874012/how-does-this-bit-manipulation-work-in-java/10874449#10874449\n # Used because of the O(log(n)) complexity\n\n x = x - ((x >> 1) & 0x55555555)\n x = (x & 0x33333333) + ((x >> 2) & 0x33333333)\n x = (x + (x >> 4)) & 0x0F0F0F0F\n x = x + (x >> 8)\n x = x + (x >> 16)\n return x & 0x0000003F\n\n\ndef intToBinary(x, N):\n \"\"\"\n The function converts a base 10 integer into a binary number of a specified length (padding with 0s if needed)\n\n :param x: Base 10 integer to be converted to binary\n :param N: Length of binary string required\n :return: Binary number of specified length\n \"\"\"\n return (\"{0:0\" + str(N) + \"b}\").format(x)\n\n\ndef makeState(configuration):\n \"\"\"\n The function makeState takes argument configuration which specifies the state we want to initialise.\n\n :param configuration: np.array of length N with 1 meaning up and 0 meaning down, e.g. [1,0,0,1] means up-down-down-up\n :return: np.array of length 2**N, the state vector in full state space\n \"\"\"\n # Initialising the state vector, which will be represented in the full state space of the chain\n state = 1\n\n # Defining the states from which our specific state will be constructed from\n up = [1, 0]\n down = [0, 1]\n\n # The loop below constructs a vector of size 2^N through the Kronecker product\n i = 0\n while i < np.length(configuration):\n if configuration[i] == 0:\n state = scipy.kron(state, down)\n i += 1\n elif configuration[i] == 1:\n state = scipy.kron(state, up)\n i += 1\n else:\n return (\n \"The configuration has not been specified correctly, please read the\"\n \" docstring\"\n )\n\n return state\n\n\ndef groupSz(N):\n \"\"\"\n Creates a list of lists of states, in the full state space, grouped according to their total Sz spin\n\n :param N: Spin chain length as integer\n :return: List of lists of states with a given Sz for a chain of given length\n \"\"\"\n # Indexing from -N to N translated into what can be handled by an array\n SzList = [[] for i in range(N + 1)]\n\n # There is room for optimisation here, the loop adds O(2^N) complexity\n for state in range(2 ** N):\n # The below is only a proxy for spin, it just creates an ordering for the purposes of the code\n totalSpin = countBits(state)\n SzList[totalSpin].append([int(bit) for bit in (intToBinary(state, N))])\n\n return SzList\n\n\ndef makeHamiltonian(N, initialState, SzList):\n \"\"\"\n The function makeHamiltonian takes argument N, the length of our chain and constructs the XYZ Hamiltonian for\n a chain of that length, for a given initial state (to suppress unneeded data)\n\n\n :param N: integer length of the chain\n :param initialState: 2**N size vector specifying the initial state of the chain in the full space\n :return: 2**N x 2**N Hamiltonian of a chain of the specified length\n \"\"\"\n H = scipy.zeros([2 ** N, 2 ** N], dtype=float)\n\n totalSpin = countBits(initialState)\n basis = SzList[totalSpin]\n for state in basis:\n print(state)\n # We must loop over all nearest neighbour interactions to develop the Hamiltonian\n for interaction in range(N - 1):\n # Initialising the products which will be used to calculate the Hamiltonian matrix elements\n ProdX = 1\n ProdY = 1\n ProdZ = 1\n\n # The computation of the matrix elements is as follows:\n # (Almost) every interaction gains a contribution from a pair of spins, contributing an Sx, Sy and Sz term to H\n # There are N-1 interactions and for each one, we add a term which is a Kronecker product of Pauli matrices\n # if a spin participates in this interaction. Otherwise we take the Kronecker product with the identity to\n # ensure correct dimensionality of the matrix\n # It's clear we are looking at nearest neighbours below\n for site in range(N):\n if site == interaction or site == interaction + 1:\n ProdX = scipy.kron(ProdX, Sx)\n ProdY = scipy.kron(ProdY, Sy)\n ProdZ = scipy.kron(ProdZ, Sz)\n else:\n ProdX = scipy.kron(ProdX, S0)\n ProdY = scipy.kron(ProdY, S0)\n ProdZ = scipy.kron(ProdZ, S0)\n\n H += np.real(ProdX + ProdY + ProdZ)\n\n return H\n\n\ndef findTargetState(initialConfiguration):\n\n targetConfiguration = initialConfiguration.append(initialConfiguration[0])\n targetConfiguration.remove(initialConfiguration[0])\n targetState = makeState(targetConfiguration)\n\n return targetState\n\n\ndef fidelity(targetConfiguration, state):\n \"\"\"\n The function fidelity takes arguments initialState and state and calculates the fidelity between them.\n\n :param initialState: 2**N vector representing the initial state\n :param state: 2**N vector representing the state for which the calculation is conducted\n :return: float fidelity\n \"\"\"\n targetState = findTargetState(targetConfiguration)\n f = np.dot(targetState, state)\n return np.abs(f)\n\n\ndef makeHamiltonianJ(N, J):\n \"\"\"\n The function makeHamiltonian takes argument N, the length of our chain and constructs the XYZ Hamiltonian for\n a chain of that length. This particular function accomodates for non-uniform J coupling.\n\n :param N: integer length of the chain\n :param J: list of couplings of length N-1\n :return: 2**N x 2**N Hamiltonian of a chain of the specified length\n \"\"\"\n H = scipy.zeros([2 ** N, 2 ** N], dtype=float)\n\n # We must loop over all nearest neighbour interactions to develop the Hamiltonian\n for interaction in range(N - 1):\n # Initialising the products which will be used to calculate the Hamiltonian matrix elements\n ProdX = 1\n ProdY = 1\n ProdZ = 1\n\n Jtemp = J[interaction]\n\n # The computation of the matrix elements is as follows:\n # (Almost) every interaction gains a contribution from a pair of spins, contributing an Sx, Sy and Sz term to H\n # There are N-1 interactions and for each one, we add a term which is a Kronecker product of Pauli matrices\n # if a spin participates in this interaction. Otherwise we take the Kronecker product with the identity to\n # ensure correct dimensionality of the matrix\n # It's clear we are looking at nearest neighbours below\n for site in range(N):\n if site == interaction or site == interaction + 1:\n ProdX = scipy.kron(ProdX, Sx)\n ProdY = scipy.kron(ProdY, Sy)\n ProdZ = scipy.kron(ProdZ, Sz)\n else:\n ProdX = scipy.kron(ProdX, S0)\n ProdY = scipy.kron(ProdY, S0)\n ProdZ = scipy.kron(ProdZ, S0)\n\n H += np.real(Jtemp * (ProdX + ProdY + ProdZ))\n\n return H\n\n\ndef evolveState(state, hamiltonian, timestep):\n \"\"\"\n The function evolveState takes an input state, as generated by initialiseChain, a Hamiltonian as generated by\n makeHamiltonian and timestep (integer or float) and returns a final state after constructing a time evolution\n operator.\n\n :param state: np.array of length 2**N, the state vector in full state space\n :param hamiltonian: 2**N x 2**N Hamiltonian of a chain of the specified length\n :param timestep: integer/float\n :return: evolved state: np.array of length 2**N, again in the full state space\n \"\"\"\n evmat = scipy.linalg.expm(hamiltonian * -1j * timestep)\n newstate = evmat.dot(state)\n\n return newstate\n\n\n############# TESTING BELOW ############################################################################################\n\nconfig = [1, 0, 0]\ninitialState = makeState(config)\nH = makeHamiltonian(3)\n\nt = [i * dt for i in range(75)]\nS = [[] for i in range(len(initialState))]\nf = []\ncurrentState = initialState\ntargetState = findTargetState(config)\nfor i in range(len(initialState)):\n for j in range(75):\n currentState = evolveState(initialState, H, 0.05 * j * dt)\n S[i].append(np.abs(currentState[i]))\n f.append(fidelity(targetState, currentState))\n\nfor state in S:\n plt.plot(t, state, label=\"S\" + str(S.index(state)))\n\nplt.plot(t, f[:75], label=\"fidelity\")\nplt.legend()\nplt.show()\n","sub_path":"Old/Heisenberg_v2.py","file_name":"Heisenberg_v2.py","file_ext":"py","file_size_in_byte":9076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"256399512","text":"from Player_Menu.Character_Sheet_Menu import SQL_Lookup\nimport Connections\nfrom Quick_Python import run_query\n\n\ndef character_can_level_up(character_level: int, character_xp: int):\n query = \"select * \" \\\n \"from Info_XP \" \\\n \"where Level=?\"\n cursor = run_query(query, [character_level])\n xp_sheet = cursor.fetchone()\n if character_xp >= xp_sheet.XP:\n return True\n return False\n\n\ndef character_can_subclass(character_id: str, class_name: str):\n query = \"select a.Class,a.Level,B.Sub_Class_Level,A.Sub_Class \" \\\n \"from ( \" \\\n \"select Class,level, Sub_Class \" \\\n \"from Link_Character_Class \" \\\n \"where Character_ID = ? and Class = ? \" \\\n \") a \" \\\n \"left join ( \" \\\n \"select Class, Sub_Class_Level from Info_Classes \" \\\n \"where Class = ?\" \\\n \"group by Class, Sub_Class_Level) b \" \\\n \"on a.Class = b.Class\"\n cursor = run_query(query, [character_id, class_name, class_name])\n result = cursor.fetchone()\n if result.Sub_Class is None:\n if result.Level >= result.Sub_Class_Level:\n return True\n return False\n\n\ndef character_has_professions(character_id: str):\n query = \"select * \" \\\n \"from Link_Character_Skills \" \\\n \"where Character_ID = ?\"\n cursor = run_query(query, [character_id])\n result = cursor.fetchone()\n if result is None:\n return False\n return True\n\n\ndef character_has_class(character_id: str, class_name: str):\n query = \"select * \" \\\n \"from Link_Character_Class \" \\\n \"where Character_ID = ? AND Class = ?\"\n cursor = run_query(query, [character_id, class_name])\n result = cursor.fetchone()\n if result is None:\n return False\n return True\n\n\ndef class_is_spell_caster(character_id: str, class_name: str, class_level: int):\n if class_name == 'Rogue':\n if SQL_Lookup.character_class_subclass(character_id, class_name) == \"Arcane Trickster\":\n return True\n else:\n return False\n if class_name == 'Fighter':\n if SQL_Lookup.character_class_subclass(character_id, class_name) == \"Eldritch Knight\":\n return True\n else:\n return False\n\n query = \"select * \" \\\n \"from Info_Max_Spell_Level \" \\\n \"where Class = ?\"\n cursor = run_query(query, [class_name])\n result = cursor.fetchone()\n if result is None:\n return False\n if result[class_level] > 0:\n return True\n return False\n\n\ndef wizard_has_spells(character_id: str):\n query = \"select count(*) as Total \" \\\n \"from Main_Spell_Book A \" \\\n \"left join Link_Spell_book_Spells B \" \\\n \"on A.ID = B.Spell_Book_ID \" \\\n \"where Owner_ID = ?\"\n cursor = run_query(query, [character_id])\n result = cursor.fetchone()\n if result.Total > 0:\n return True\n return False\n\n\ndef class_learn_spells(class_name: str):\n query = \"select * \" \\\n \"from Info_Spells_Known \" \\\n \"where Class = ?\"\n cursor = run_query(query, [class_name])\n result = cursor.fetchone()\n if result is None:\n return False\n return True\n\n\ndef character_has_spells_by_class(character_id: str, class_name: str):\n sub_class = SQL_Lookup.character_class_subclass(character_id, class_name)\n query = \"select count(*) as Total \" \\\n \"from Link_Character_Spells A \" \\\n \"left Join Info_Spells B \" \\\n \"on A.Spell = B.Name \" \\\n \"where A.Character_ID = ? and (Origin = ? or Origin = ?)\" \\\n \n cursor = run_query(query, [character_id, class_name, sub_class])\n result = cursor.fetchone()\n if result.Total > 0:\n return True\n return False\n\n\ndef character_class_can_replace_spell(character_id: str, class_name: str):\n query = \"Select *\" \\\n \"From Link_Character_Class \" \\\n \"Where Character_ID = ? and Class = ?\"\n cursor = run_query(query, [character_id, class_name])\n result = cursor.fetchone()\n if result.Replace_Spell:\n return True\n return False\n\n\ndef class_can_replace_spell(class_name: str):\n query = \"Select *\" \\\n \"From Info_Spells_Known \" \\\n \"Where Class = ?\"\n cursor = run_query(query, [class_name])\n result = cursor.fetchone()\n if result is None:\n return False\n return True\n\n\ndef class_choice(character_id: str, class_name: str):\n query = \"Select * \" \\\n \"From Link_Character_Class \" \\\n \"Where Character_ID = ? and Class = ?\"\n cursor = run_query(query, [character_id, class_name])\n result = cursor.fetchone()\n if result.Class_Choice:\n return True\n return False\n","sub_path":"cogs/Player_Menu/Character_Sheet_Menu/SQL_Check.py","file_name":"SQL_Check.py","file_ext":"py","file_size_in_byte":4749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"391345694","text":"##\n## Imprima una tabla en formato CSV que contenga por registro,\n## la cantidad de elementos de las columnas 4 y 5\n## (filas en el archivo)\n##\n## E,3,5\n## A,3,4\n## B,4,4\n## ...\n## C,4,3\n## E,2,3\n## E,3,3\n##\nimport csv\nimport collections\nimport re\ndata = open('data.csv','r').readlines()\ndata = [row[0:-1] for row in data]\npatron = re.compile('\\t|\\s+')\ndatasub = [re.sub(patron,'~',x) for x in data]\ndatasplit = [re.split('~',x) for x in datasub]\ndatacol034 =[[x[0],(x[3].count(',')+1),(x[4].count(',')+1)]for x in datasplit]\nfor x in datacol034:\n print(x[0],x[1],x[2],sep=',')","sub_path":"q11.py","file_name":"q11.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"46585840","text":"# encoding=utf-8\nimport pymongo\nfrom items import InformationItem, TweetsItem, FollowsItem, FansItem\n\n\nclass MongoDBPipleline(object):\n def __init__(self):\n clinet = pymongo.MongoClient(\"localhost\", 27017)\n db = clinet[\"Sina\"]\n self.fan_list = db[\"fan_list\"]\n\n def process_item(self, item, spider):\n fans = [dict(_id=id, name=name, url=url) for id, name, url in item['fans']]\n self.fan_list.update(\n {'_id': item['_id'], 'name': item['name']},\n {'$addToSet':{'fans':{'$each': fans }}},\n upsert=True)\n return item\n","sub_path":"Sina_spider1/Sina_spider1/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"37156769","text":"from turtle import Turtle, Screen\nimport random\n\nis_race_on = False\nscreen = Screen()\nscreen.setup(width=500, height=400)\nuser_bet = screen.textinput(title=\"Make your bet\", prompt=\"Which turtle win the race? Enter a color\")\ncolor = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"violet\"]\ny = -100\nall_turtles = []\nfor i in range(0, 6):\n new_turtle = Turtle(\"turtle\")\n new_turtle.color(color[i])\n new_turtle.penup()\n y = y + 30\n new_turtle.goto(x=-230, y = y)\n all_turtles.append(new_turtle)\n\nif user_bet:\n is_race_on = True\n\nwhile is_race_on:\n for turtle in all_turtles:\n if turtle.xcor() > 230:\n is_race_on = False\n winning_color = turtle.pencolor()\n if winning_color == user_bet:\n print(f\"you won {winning_color}\")\n else:\n print(f\"you lost {winning_color}\")\n rand_distance = random.randint(0, 10)\n turtle.forward(rand_distance)\n\nscreen.exitonclick()\n\n\n","sub_path":"turtleRace/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"448974870","text":"\r\n#!/usr/bin/python\r\n# Adapted from http://kutuma.blogspot.com/2007/08/sending-emails-via-gmail-with-python.html\r\n\r\nimport getpass\r\nimport smtplib\r\nfrom email.mime.multipart import MIMEMultipart\r\nfrom email.mime.base import MIMEBase\r\nfrom email.mime.text import MIMEText\r\nfrom email import encoders\r\nimport os\r\nimport pandas\r\nimport time\r\n\r\ngmail_user = \"xjcarter@gmail.com\"\r\ngmail_pwd = \"Colo$$us001\" \r\n\r\ntest_html = \"\"\"\r\n\r\n\r\n\r\n\r\n

\r\n

Three Little Pigs

\r\n
\r\n
    \r\n
  1. One little piggy
  2. \r\n
  3. Twp little piggy
  4. \r\n
  5. Three little piggy\r\n
\r\n
\r\n
\r\n\r\n\r\n\"\"\"\r\n\r\ndef login(user):\r\n global gmail_user, gmail_pwd\r\n gmail_user = user\r\n gmail_pwd = getpass.getpass('Password for %s: ' % gmail_user)\r\n\r\ndef mail(to, subject, text=None, html=None, attach=None):\r\n msg = MIMEMultipart()\r\n msg['From'] = gmail_user\r\n msg['To'] = to\r\n msg['Subject'] = subject\r\n if text is not None:\r\n msg.attach(MIMEText(text))\r\n if html:\r\n msg.attach(MIMEText(html,\"html\"))\r\n if attach:\r\n part = MIMEBase('application', 'octet-stream')\r\n part.set_payload(open(attach, 'rb').read())\r\n encoders.encode_base64(part)\r\n part.add_header('Content-Disposition', 'attachment; filename=\"%s\"' % os.path.basename(attach))\r\n msg.attach(part)\r\n mailServer = smtplib.SMTP(\"smtp.gmail.com\", 587)\r\n mailServer.ehlo()\r\n mailServer.starttls()\r\n mailServer.ehlo()\r\n mailServer.login(gmail_user, gmail_pwd)\r\n mailServer.sendmail(gmail_user, to, msg.as_string())\r\n mailServer.close()\r\n \r\nif __name__ == '__main__':\r\n mail('xjcarter@gmail.com','Test',text=\"Hello J!\",html=test_html)\r\n\r\n","sub_path":"backup/mail_client.py","file_name":"mail_client.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"413003009","text":"5# Allow the user to enter an int number. Determine if the\r\n# number is prime or not. A number is prime if it is only\r\n# divisible exactly by 1 and itself, e.g. 3, 7, 11 and 17.\r\n# 2 is the only even prime number. 1 is not generally regarded\r\n# as prime. Display the answer “prime” or not prime as appropriate.\r\n\r\nx = int(input('Enter the number to test: '))\r\nisPrime = True # boolean data type - note capital T\r\n\r\ny = x - 1\r\nwhile y > 1:\r\n if x%y == 0:\r\n # x is divisible exactly by y ...\r\n isPrime = False\r\n break # exits the while loop\r\n else:\r\n y -= 1\r\n\r\nif isPrime == True:\r\n print('Number', x, 'is a prime number')\r\nelse:\r\n print('Number', x, 'is not a prime number')\r\n","sub_path":"Lab_1/LabExercises1/challenge2Solution.py","file_name":"challenge2Solution.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"586299795","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python2.7\n \n# Copyright 2009-2013 bjweeks, MZMcBride, svick, DixonD-git\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\nimport reports\n\n\nclass report(reports.report):\n def get_title(self):\n return u'Перенаправлення файлів, що не використовуються'\n\n def get_preamble_template(self):\n return u'Перенаправлення файлів, на які є щонайбільше одне посилання; дані станом на %s.'\n\n def get_table_columns(self):\n return [u'Сторінка', u'Використань файлу', u'Посилань на файл']\n\n def get_table_rows(self, conn):\n cursor = conn.cursor()\n cursor.execute('''\n /* unused_file_redirects.py SLOW_OK */\n SELECT\n page_namespace,\n CONVERT(page_title USING utf8),\n (SELECT COUNT(*)\n FROM imagelinks\n WHERE il_to = page_title) AS imagelinks,\n (SELECT COUNT(*)\n FROM pagelinks\n WHERE pl_title = page_title) AS links\n FROM page\n WHERE\n page_namespace = 6\n AND page_is_redirect = 1\n HAVING imagelinks + links <= 1;\n ''')\n\n for page_namespace, page_title, count1, count2 in cursor:\n page_title = u'[[%s]]' % self.make_page_title(page_namespace, page_title)\n yield [page_title, count1, count2]\n\n cursor.close()","sub_path":"reports/ukwiki/unused_file_redirects.py","file_name":"unused_file_redirects.py","file_ext":"py","file_size_in_byte":2117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"344840806","text":"#!/usr/bin/env python\n# vim: set fileencoding=utf-8 :\n\nfrom setuptools import setup, dist\ndist.Distribution(dict(setup_requires = ['bob.extension']))\n\n# load the requirements.txt for additional requirements\nfrom bob.extension.utils import load_requirements, find_packages\ninstall_requires = load_requirements()\n\nsetup(\n\n name = 'bob.hobpad2.chapter19',\n version = open(\"version.txt\").read().rstrip(),\n description = 'Software package to reproduce Evaluation Methodologies for Biometric Presentation Attack Detection chapter of Handbook of Biometric Anti-Spoofing: Presentation Attack Detection 2nd Edition',\n\n url = 'https://gitlab.idiap.ch/bob/bob.hobpad2.chapter19',\n license = 'GPLv3',\n author = 'Pavel Korshunov',\n author_email = 'pavel.korshunov@idiap.ch',\n keywords = 'bob',\n\n long_description = open('README.rst').read(),\n\n packages = find_packages('bob'),\n include_package_data = True,\n\n install_requires = install_requires,\n\n entry_points = {\n 'console_scripts': [\n 'plot_far_frr_pad.py = bob.hobpad2.chapter19.plot_far_frr_pad:main',\n 'plot_pad_results.py = bob.hobpad2.chapter19.plot_pad_results:main',\n ],\n },\n classifiers = [\n 'Framework :: Bob',\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)',\n 'Natural Language :: English',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Topic :: Scientific/Engineering :: Artificial Intelligence',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ],\n)\n","sub_path":"pypi_install_script/bob.hobpad2.chapter19-1.0.1/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"346506363","text":"import os\nimport os.path as osp\n\nimport torch\nimport torch.distributed as dist\n\nfrom ..fileio import io\nfrom ..utils.misc import get_dist_info\nfrom .base import BaseHook\nfrom .priority import Priority\nfrom .registry import HOOKS\n\n\n@HOOKS.register_module\nclass LogBufferHook(BaseHook):\n @property\n def priority(self):\n return Priority.LOW\n\n @staticmethod\n def sync(runner):\n rank, world_size = get_dist_info()\n\n if rank == 0:\n dist.barrier()\n for i in range(1, world_size):\n tmp_file = osp.join(runner.work_dir, f\"tmp_{i}.pkl\")\n tmp_results = io.load(tmp_file)\n n_history = tmp_results[\"n_history\"]\n value_history = tmp_results[\"value_history\"]\n for key in n_history:\n runner.log_buffer.value_history[key].extend(value_history[key])\n runner.log_buffer.n_history[key].extend(n_history[key])\n os.remove(tmp_file)\n else:\n tmp_file = osp.join(runner.work_dir, f\"tmp_{rank}.pkl\")\n io.dump(\n {\"value_history\": runner.log_buffer.value_history, \"n_history\": runner.log_buffer.n_history}, tmp_file\n )\n dist.barrier()\n dist.barrier()\n\n def before_epoch(self, runner):\n runner.log_buffer.clear()\n\n def after_iter(self, runner):\n runner.log_buffer.average()\n\n def after_epoch(self, runner):\n if dist.is_initialized():\n self.sync(runner)\n runner.log_buffer.average()\n if dist.is_initialized():\n for key, value in runner.log_buffer.output.items():\n value_tensor = torch.tensor(value, device=\"cuda\")\n dist.broadcast(value_tensor, 0)\n runner.log_buffer.output[key] = value_tensor.item()\n","sub_path":"ppln/hooks/log_buffer.py","file_name":"log_buffer.py","file_ext":"py","file_size_in_byte":1837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"329076503","text":"\"\"\"Start a local webserver to report the status of an arcyd instance.\"\"\"\n# =============================================================================\n# CONTENTS\n# -----------------------------------------------------------------------------\n# abdcmd_instaweb\n#\n# Public Functions:\n# getFromfilePrefixChars\n# setupParser\n# process\n#\n# -----------------------------------------------------------------------------\n# (this contents block is generated, edits will be lost)\n# =============================================================================\n\nfrom __future__ import absolute_import\n\nimport BaseHTTPServer\nimport os\n\nimport abdcmd_arcydstatushtml\nimport abdcmd_repostatushtml\n\n\ndef getFromfilePrefixChars():\n return None\n\n\ndef setupParser(parser):\n parser.add_argument(\n '--port',\n metavar=\"PORT\",\n type=int,\n default=8000,\n help=\"port to serve pages on\")\n\n parser.add_argument(\n '--report-file',\n metavar=\"REPORTFILE\",\n type=str,\n required=True,\n help=\"path to the arcyd report file to render\")\n\n parser.add_argument(\n '--repo-file-dir',\n metavar=\"REPOFILEDIR\",\n type=str,\n required=True,\n help=\"path to the repo files to render\")\n\n\nclass _NotFoundError(Exception):\n pass\n\n\nclass _RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):\n\n def __init__(self, instaweb_args, *args):\n self._instaweb_args = instaweb_args\n self.path = None # for pychecker\n self.wfile = None # for pychecker\n BaseHTTPServer.BaseHTTPRequestHandler.__init__(self, *args)\n\n def do_GET(self):\n\n try:\n content = self._get_content()\n except _NotFoundError:\n self.send_response(404)\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n self.wfile.write(\"

404

\")\n self.wfile.close()\n else:\n self.send_response(200)\n self.send_header(\"Content-type\", \"text/html\")\n self.end_headers()\n self.wfile.write(content)\n self.wfile.close()\n\n def _get_content(self):\n\n args = self._instaweb_args\n\n if self.path == '/':\n content = abdcmd_arcydstatushtml.render_content(\n args.report_file, '')\n elif self.path.lower().endswith('favicon.ico'):\n raise _NotFoundError('could not find favicon')\n else:\n relative_path = self.path.lstrip('/')\n dir_path = os.path.join(args.repo_file_dir, relative_path)\n\n # XXX: this is fragile, will go away once arcyd folder\n # layout is standardized\n repo_path = dir_path + '.try'\n branches_path = dir_path + '.ok'\n content = abdcmd_repostatushtml.render_content(\n repo_path, branches_path)\n\n return content\n\n\ndef _request_handler_factory(instaweb_args):\n\n def factory(*args):\n return _RequestHandler(instaweb_args, *args)\n\n return factory\n\n\ndef process(args):\n\n # start a webserver\n server_address = ('', args.port)\n factory = _request_handler_factory(args)\n httpd = BaseHTTPServer.HTTPServer(server_address, factory)\n httpd.serve_forever()\n\n\n# -----------------------------------------------------------------------------\n# Copyright (C) 2013-2014 Bloomberg Finance L.P.\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\n# deal in the Software without restriction, including without limitation the\n# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n# sell 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\n# all 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\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n# ------------------------------ END-OF-FILE ----------------------------------\n","sub_path":"py/abd/abdcmd_instaweb.py","file_name":"abdcmd_instaweb.py","file_ext":"py","file_size_in_byte":4559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"30820759","text":"import math\n\nimport pytest\n\nfrom wasm.tools.fixtures.numeric import (\n int_to_float,\n)\n\n\n@pytest.mark.parametrize(\n 'num_bits,value,expected',\n (\n # 32-bit\n (32, 0, 0.0),\n (32, 1, 1.401298464324817e-45),\n (32, 1120403456, 100.0),\n (32, 2**32 - 1, math.nan),\n (32, 1325400064, 2147483648), # float(2**31 - 1)\n # 64-bit\n (64, 0, 0.0),\n (64, 1, 5e-324),\n (64, 2**64 - 1, math.nan),\n (64, 4636737291354636288, 100.0),\n ),\n)\ndef test_int_to_float(num_bits, value, expected):\n actual = int_to_float(num_bits, value)\n assert isinstance(actual, float)\n\n if math.isnan(expected):\n assert math.isnan(actual)\n else:\n assert actual == expected\n\n\n@pytest.mark.parametrize(\n 'num_bits,value',\n (\n (32, -1),\n (32, 2**32),\n (64, -1),\n (64, 2**64),\n )\n)\ndef test_int_to_float_bounds(num_bits, value):\n with pytest.raises(OverflowError):\n int_to_float(num_bits, value)\n","sub_path":"tests/tools/test_int_to_float.py","file_name":"test_int_to_float.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"94136581","text":"import pandas as pd\nimport numpy as np\nfrom sklearn.neighbors import NearestNeighbors\nfrom tqdm import tqdm\nfrom pandas.api.types import CategoricalDtype\nimport sys\nimport os\n\nimport gc\ngc.enable()\n\nnp.random.seed(432) # Для повторяемости результатов\n\n\ndir_path = str(sys.argv[1]) # Путь к папке с исходными данными\nN_N = int(sys.argv[2]) # Количество ближайших соседей, учитывающихся при всех алгоритмах заполнения пропусков в данных\n\ntry:\n os.mkdir('Generated_Data')\nexcept:\n pass\n\nif __name__=='__main__':\n\n # Считываем исходные данные, в процессе первичного анализа было выявлено, что не все колонки в данных несут какой-либо смысл, поэтому считываем сразу только полезные\n\n user_region = pd.read_csv(dir_path + '/user_region.csv', usecols=['row', 'col'])\n user_age = pd.read_csv(dir_path + '/user_age.csv', usecols=['row'])\n item_subclass = pd.read_csv(dir_path + '/item_subclass.csv', usecols=['row', 'col'])\n item_price = pd.read_csv(dir_path + '/item_price.csv', usecols=['row', 'data'])\n item_asset = pd.read_csv(dir_path + '/item_asset.csv', usecols=['row', 'data'])\n interactions = pd.read_csv(dir_path+ '/interactions.csv')\n\n # Проверка на пустые значения\n\n assert user_region.isnull().values.any() == False\n assert user_age.isnull().values.any() == False\n assert item_subclass.isnull().values.any() == False\n assert item_price.isnull().values.any() == False\n assert item_asset.isnull().values.any() == False\n assert interactions.isnull().values.any() == False\n\n # Собираем датасет для продуктов\n\n item_subclass.rename(columns={'col':'product_category'}, inplace=True)\n item_subclass['product_category'] = item_subclass['product_category'].astype('category')\n\n item_price.rename(columns={'data':'price'}, inplace=True)\n\n item_asset.rename(columns={'data':'asset'}, inplace=True)\n\n prod_feats = item_subclass.merge(item_price, how='outer', on='row').merge(item_asset, how='outer', on='row')\n prod_feats.rename(columns={'row':'product_id'}, inplace=True)\n\n del [item_price, item_asset]\n gc.collect()\n\n # Заполняем пропуски в данных для продуктов на основе алгоритма ближайших соседей: ищем похожие продукты из той же категории с точки зрения ненулевых признаков, затем заполняем пропуски усреднением соответствующих значений признаков у соседей\n\n prod_feats_without_nan = prod_feats[(~prod_feats['price'].isna()) & (~prod_feats['asset'].isna())]\n \n print('Заполняем первичные пропуски для продуктов')\n\n for ind in tqdm(prod_feats[prod_feats['price'].isna()].index, position=0):\n categ = prod_feats.loc[ind, 'product_category']\n asset = prod_feats.loc[ind, 'asset']\n\n temp_df = prod_feats_without_nan[(prod_feats_without_nan['product_category'] == categ)]\n\n n_neighbors = min(N_N, temp_df.shape[0])\n\n nn = NearestNeighbors(n_neighbors)\n nn.fit(temp_df['asset'].values.reshape(-1,1))\n\n _, neighbors_inds = nn.kneighbors(np.reshape([asset], (1, 1)))\n\n prod_feats.loc[ind, 'price'] = temp_df.values[neighbors_inds, -2].mean()\n\n for ind in tqdm(prod_feats[prod_feats['asset'].isna()].index, position=0):\n categ = prod_feats.loc[ind, 'product_category']\n price = prod_feats.loc[ind, 'price']\n\n temp_df = prod_feats_without_nan[(prod_feats_without_nan['product_category'] == categ)]\n\n n_neighbors = min(N_N, temp_df.shape[0])\n\n nn = NearestNeighbors(n_neighbors)\n nn.fit(temp_df['price'].values.reshape(-1,1))\n\n _, neighbors_inds = nn.kneighbors(np.reshape([price], (1, 1)))\n\n prod_feats.loc[ind, 'asset'] = temp_df.values[neighbors_inds, -1].mean()\n\n # Собираем датасет для пользователей\n\n user_region.rename(columns={'col':'user_region'}, inplace=True)\n\n user_feats = user_age.merge(user_region, how='outer', on='row')\n user_feats.rename(columns={'row':'user_id'}, inplace=True)\n\n user_feats['user_region'].fillna(1, inplace=True) # Наивно относим всех пользователей с неизвестным регионом к новому региону с номером 1\n user_feats['user_region'] = user_feats['user_region'].astype('category')\n\n del [user_region, user_age]\n gc.collect()\n\n # Выделяем обучающие, валидационные и тестовые заказы в соотношении 70/15/15\n\n interactions.rename(columns={'row':'user_id', 'col':'product_id', 'data':'label'}, inplace=True)\n\n\n train_indexes = np.random.choice(interactions.index, int(len(interactions.index)*0.7), replace=False)\n val_train_indexes = list(filter(lambda x: x not in train_indexes, interactions.index))\n\n val_indexes = val_train_indexes[:int(len(val_train_indexes)*0.5)]\n test_indexes = val_train_indexes[int(len(val_train_indexes)*0.5):]\n\n interactions_train = interactions.loc[train_indexes].reset_index(drop=True)\n interactions_val = interactions.loc[val_indexes].reset_index(drop=True)\n interactions_test = interactions.loc[test_indexes].reset_index(drop=True)\n\n # Генерируем признаки на основе обучающей выборки\n\n user_prod_train = interactions_train.merge(user_feats, how='inner', on='user_id').merge(prod_feats, how='inner', on='product_id')\n\n # Признаки пользователя\n\n user_total_buy = user_prod_train.groupby('user_id')['user_id'].count().to_frame('user_total_buy') # Полное число покупок пользователя\n user_total_buy = user_total_buy.reset_index()\n\n user_dif_cat = user_prod_train.groupby('user_id')['product_category'].nunique().to_frame('user_dif_cat') # Число различных категорий, которые покупал пользователь\n user_dif_cat = user_dif_cat.reset_index()\n\n # Холодный старт для пользователей\n\n all_users = user_feats.merge(user_total_buy, how='outer', on='user_id').merge(user_dif_cat, how='outer', on='user_id')\n all_users_without_nan = all_users[(~all_users['user_total_buy'].isna()) & (~all_users['user_dif_cat'].isna())]\n\n # Заполняем пропуски для некоторых пользователей путем усреднения значений соответствующих признаков пользователей из того же региона\n \n print('Заполняем пропуски для пользователей')\n \n for ind in tqdm(all_users[all_users['user_total_buy'].isna()].index, position=0):\n region = all_users.loc[ind, 'user_region']\n\n temp_df = all_users_without_nan[(all_users_without_nan['user_region'] == region)]\n\n all_users.loc[ind, 'user_total_buy'] = int(temp_df.loc[:, 'user_total_buy'].mean())\n all_users.loc[ind, 'user_dif_cat'] = int(temp_df.loc[:, 'user_dif_cat'].mean())\n\n for ind in tqdm(all_users[all_users['user_dif_cat'].isna()].index, position=0):\n region = all_users.loc[ind, 'user_region']\n\n temp_df = all_users_without_nan[(all_users_without_nan['user_region'] == region)]\n\n all_users.loc[ind, 'user_dif_cat'] = int(temp_df.loc[:, 'user_dif_cat'].mean())\n\n all_users.drop_duplicates(subset=['user_id'], inplace=True)\n\n all_users.to_csv('Generated_Data/all_users.csv', index=False)\n\n # Признаки продукта\n\n product_total_buy = user_prod_train.groupby('product_id')['user_id'].count().to_frame('product_total_buy') # Полное число покупок продукта\n product_total_buy = product_total_buy.reset_index()\n\n prod_dif_region = user_prod_train.groupby('product_id')['user_region'].nunique().to_frame('prod_dif_region') # Число различных регионов, в которых покупали данный продукт\n prod_dif_region = prod_dif_region.reset_index()\n\n # Холодный старт для продуктов\n\n all_prods = prod_feats.merge(product_total_buy, how='outer', on='product_id').merge(prod_dif_region, how='outer', on='product_id')\n all_prod_without_nan = all_prods[(~all_prods['product_total_buy'].isna()) & (~all_prods['prod_dif_region'].isna())]\n\n # Заполняем пропуски для некоторых продуктов путем усреднения значений соответствующих признаков продуктов из той же категории\n \n print('Заполняем пропуски для сгенерированных признаков продуктов')\n \n for ind in tqdm(all_prods[all_prods['product_total_buy'].isna()].index, position=0):\n categ = all_prods.loc[ind, 'product_category']\n price, asset = all_prods.loc[ind, 'price'], all_prods.loc[ind, 'asset']\n\n temp_df = all_prod_without_nan[(all_prod_without_nan['product_category'] == categ)]\n if temp_df.shape[0] == 0:\n temp_df = all_prod_without_nan\n\n n_neighbors = min(N_N, temp_df.shape[0])\n\n nn = NearestNeighbors(n_neighbors)\n nn.fit(temp_df[['price', 'asset']].values)\n\n _, neighbors_inds = nn.kneighbors(np.reshape([price, asset], (1, 2)))\n\n all_prods.loc[ind, 'product_total_buy'] = int(temp_df.values[neighbors_inds, -2].mean())\n all_prods.loc[ind, 'prod_dif_region'] = int(temp_df.values[neighbors_inds, -1].mean())\n\n all_prods.drop_duplicates(subset=['product_id'], inplace=True)\n\n all_prods.to_csv('Generated_Data/all_prods.csv', index=False)\n\n # Соединяем все признаки с таблицей взаимодействия пользователей с продуктами\n\n user_prod_train = interactions_train.merge(all_users, how='inner', on='user_id').merge(all_prods, how='inner', on='product_id')\n \n print('Собираем датасеты для валидации и теста')\n\n val_arr = []\n for user_id, group_u in tqdm(interactions_val.groupby('user_id'), position=0):\n val_arr.append([user_id, group_u['product_id'].values])\n\n val_df = pd.DataFrame(val_arr, columns=['user_id', 'bought_products']).merge(all_users, how='inner', on='user_id')\n\n test_arr = []\n for user_id, group_u in tqdm(interactions_test.groupby('user_id'), position=0):\n test_arr.append([user_id, group_u['product_id'].values])\n\n test_df = pd.DataFrame(test_arr, columns=['user_id', 'bought_products']).merge(all_users, how='inner', on='user_id')\n\n val_df.to_csv('Generated_Data/val_df.csv', index=False)\n test_df.to_csv('Generated_Data/test_df.csv', index=False)\n\n del [user_feats, prod_feats, val_df, test_df]\n gc.collect()\n\n # Генерируем отрицательные классы: для каждого пользователя генерируем столько же отрицательных примеров, сколько у него положительных в обучающей выборке\n \n print('Генерируем отрицательные классы для обучающей выборки')\n\n negative_samples = []\n for user_id, group_u in tqdm(user_prod_train.groupby('user_id'), position=0):\n\n product_list = list(set(group_u['product_id']))\n\n target_products = list(set(user_prod_train[(user_prod_train['user_id'] != user_id) & (~user_prod_train['product_id'].isin(product_list))]['product_id']))\n\n num_to_extract = min(len(product_list), len(target_products))\n\n negative_products = np.random.choice(target_products, num_to_extract, replace=False)\n\n for product in negative_products:\n negative_samples.append([user_id, product])\n\n negative_user_prod_train = pd.DataFrame(negative_samples, columns=['user_id', 'product_id'])\n negative_user_prod_train['label'] = 0\n\n negative_user_prod_train = negative_user_prod_train.merge(all_users, how='inner', on='user_id').merge(all_prods, how='inner', on='product_id')\n\n df = pd.concat((user_prod_train, negative_user_prod_train), axis=0).sample(frac=1)\n\n df.to_csv('Generated_Data/train_dataset.csv', index=False)\n \n print('Предобработка завершена')\n","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":12774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"375735848","text":"import time\nfrom slackclient import SlackClient\nimport requests\nimport argparse\nimport config\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--message', default=\"hoge\", type=str, help='message')\n parser.add_argument('--app', default=\"hoge\", type=str, help='message')\n parser.add_argument('--endpoint', default=\"hoge\", type=str, help='message')\n parser.add_argument('--channel', default=\"hoge\", type=str, help='message')\n parser.add_argument('--token', default=\"hoge\", type=str, help='message')\n args = parser.parse_args()\n\n headers = {'Content-Type': 'application/json'}\n try:\n app = requests.get(\"{{}/app/{}\".format(config.DOCKER_REPOGITORY, args.app)).json()\n requests.put(\"{}endpoints/{}\".format(config.MARATHON_URL, args.endpoint), json={\"version\": app[\"version\"]}, headers=headers)\n except:\n app = {\"name\": \"\"}\n sc = SlackClient(args.token)\n sc.rtm_connect()\n sc.rtm_send_message(channel=args.channel, message=\"{} デプロイしましたです〜\".format(app[\"name\"]))\n","sub_path":"notice/notice_container_name_to_slack.py","file_name":"notice_container_name_to_slack.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"155777939","text":"# (C) Datadog, Inc. 2019\n# All rights reserved\n# Licensed under a 3-clause BSD style license (see LICENSE)\nimport os\n\nimport pytest\n\nfrom datadog_checks.base.utils.http import RequestsWrapper\nfrom datadog_checks.dev.ssh_tunnel import socks_proxy\nfrom datadog_checks.dev.terraform import terraform_run\nfrom datadog_checks.dev.utils import get_here\n\n\n@pytest.fixture(scope='session')\ndef dd_environment():\n with terraform_run(os.path.join(get_here(), 'terraform')) as outputs:\n ip = outputs['ip']['value']\n internal_ip = outputs['internal_ip']['value']\n private_key = outputs['ssh_private_key']['value']\n instance = {\n 'name': 'test',\n 'keystone_server_url': 'http://{}/identity/v3'.format(internal_ip),\n 'user': {'name': 'admin', 'password': 'labstack', 'domain': {'id': 'default'}},\n 'ssl_verify': False,\n }\n with socks_proxy(ip, 'ubuntu', private_key) as socks:\n socks_ip, socks_port = socks\n agent_config = {'proxy': {'http': 'socks5://{}:{}'.format(socks_ip, socks_port)}}\n yield instance, agent_config\n\n\n@pytest.fixture\ndef requests_wrapper():\n instance = {'timeout': 10, 'ssl_verify': False}\n yield RequestsWrapper(instance, {})\n","sub_path":"openstack_controller/tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"405808993","text":"import xadmin\nfrom .models import Article, Category, Tag\n# Register your models here.\n\n\nclass CategoryAdmin(object):\n list_display = ['name']\n search_fields = ['name']\n list_filter = ['name'] \n\nclass TagAdmin(object):\n list_display = ['name']\n search_fields = ['name']\n list_filter = ['name'] \n\nclass ArticleAdmin(object):\n list_display = ['title', 'created_time', 'category', 'tags', 'author']\n search_fields = ['title', 'category', 'tags', 'author']\n list_filter = ['title', 'category', 'tags', 'author'] \n\nxadmin.site.register(Category, CategoryAdmin)\nxadmin.site.register(Tag, TagAdmin)\nxadmin.site.register(Article, ArticleAdmin)","sub_path":"blog/adminx.py","file_name":"adminx.py","file_ext":"py","file_size_in_byte":661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"137464039","text":"import matplotlib\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport random\nimport math\nfrom matplotlib.animation import FuncAnimation\nfrom inspect import signature\nimport plotly.graph_objects as go\n\n\n\ndef example_2D(x,y):\n res = 0.2 + x**2 + y**2 - 0.1*math.cos(6.0*3.1415*x) - 0.1*math.cos(6.0*3.1415*y)\n return res\n\ndef example_3D(x,y,z):\n res = 4/3 * ((x^2 + y^2 -x*y)**(0.75)) + z\n return res\n\nclass objective_fun:\n def __init__(self, fun):\n self.fun = fun\n sig = signature(fun)\n self.n_args = len(sig.parameters)\n\n# o = objective_fun(example_2D)\n\n# o2 = objective_fun(example_3D)\n\nclass simulated_annealing(objective_fun):\n def __init__(self, fun, p_start, p_end, initial_try, n_cycles = 50, n_rounds = 50, lower_bound=-1.0, upper_bound=1.0):\n super().__init__(fun)\n self.lower_bound = lower_bound\n self.upper_bound = upper_bound\n self.t_start = -1.0/math.log(p_start)\n self.t_end = -1.0/math.log(p_end)\n # always assume you are an idiot\n if (len(initial_try) != self.n_args):\n print(\"Your initial try is wrong, you are a fool!\")\n return\n self.tries = [initial_try] # this is a list, we make it a list of lists\n self.n_cycles = n_cycles\n self.n_rounds = n_rounds\n self.cooling_rate = (self.t_end/self.t_start)**(1.0/(self.n_cycles -1.0))\n self.current_state = self.tries[0]\n self.global_state = self.current_state\n self.best_objective = self.fun(*self.current_state)\n self.DeltaE_avg = 0.0\n self.DeltaE = None\n self.results = [self.best_objective]\n self.history = [[*self.current_state, self.best_objective]]\n self.n_accepted = 1.0\n self.temperature = self.t_start\n self.accept = None\n self.round = 0\n self.cycle = 0\n\n def _generate_new_trial(self): # use _ for methods which wouldnt normally be accessed by user\n self.current_state = [x + random.random() - 0.5 for x in self.current_state]\n self.current_state = [max(min(x, self.upper_bound), self.lower_bound) for x in self.current_state]\n\n def _check_objective(self):\n # calculate local change in energy\n temp_objective = self.fun(*self.current_state)\n self.history.append([ *self.current_state , temp_objective])\n self.DeltaE = abs(temp_objective - self.best_objective)\n if (temp_objective > self.best_objective):\n if (self.cycle == 0 and self.round == 0):\n self.DeltaE_avg = self.DeltaE\n p_worse = math.exp(-self.DeltaE/(self.DeltaE_avg * self.temperature))\n self.accept = True if (random.random() < p_worse) else False\n else:\n self.accept = True\n\n def _update_state(self):\n if self.accept:\n self.global_state = self.current_state\n self.best_objective = self.fun(*self.global_state)\n self.n_accepted += 1\n self.DeltaE_avg = (self.DeltaE_avg * (self.n_accepted - 1.0) + self.DeltaE) / self.n_accepted\n\n def _record_and_update_temp(self):\n self.tries += [self.global_state]\n self.results += [ self.best_objective ]\n self.temperature = self.cooling_rate * self.temperature\n\n def optimize(self):\n for i in range(self.n_cycles):\n print('cycle: ' + str(i) + ' Temperature: ' + str(self.temperature))\n self.cycle = i\n for j in range(self.n_rounds):\n self.round = j\n self._generate_new_trial()\n self._check_objective()\n self._update_state()\n self._record_and_update_temp()\n # update to get the guy nice, get the actual best\n best_try = [*self.global_state, self.best_objective]\n return best_try\n\n# simanneal = simulated_annealing(example_2D, 0.01, 0.001, [1.0, 1.0], 50, 50)\n# best = simanneal.optimize()\n\n\nclass animation_sa:\n def __init__(self, sa: simulated_annealing, lower: float, upper: float, step: float):\n self.xy = [[t[0] for t in sa.tries]] + [[t[1] for t in sa.tries]]\n self.z = sa.results\n self.xyz = [*self.xy, self.z]\n self.history = [[h[i] for h in sa.history] for i in range(3)]\n if sa.n_args != 2:\n print(\"we cannot animate in {} dimensions!\".format(sa.n_args))\n return\n xi, yi = (np.arange(lower, upper, step) for i in range(2))\n self.mesh_x, self.mesh_y = np.meshgrid(xi, yi)\n self.mesh_fn = np.zeros(self.mesh_x.shape)\n for i in range(0, self.mesh_fn.shape[0]):\n for j in range(0, self.mesh_fn.shape[0]):\n self.mesh_fn[i,j] = sa.fun(self.mesh_x[i,j], self.mesh_y[i,j])\n\n def _animate_helper_2D(self, i):\n self.line.set_xdata(self.xy[0][:i])\n self.line.set_ydata(self.xy[1][:i])\n\n def animate_2D(self, title=\"Non-Convex Function\", anim_path=\"sa.mp4\"):\n fig, ax = plt.subplots()\n contours = plt.contour(self.mesh_x, self.mesh_y, self.mesh_fn)\n plt.clabel(contours, inline=1, fontsize=10)\n plt.title(title)\n plt.xlabel('x')\n plt.ylabel('y')\n self.line = ax.plot(self.xy[0][0], self.xy[1][0], 'r-o')[0]\n anim = FuncAnimation(\n fig, self._animate_helper_2D, interval=500, frames =len(self.xy[0])\n )\n plt.draw()\n anim.save(anim_path)\n plt.show()\n\n def view_3D(self, title=\"Non-Convex Function\"):\n surface = go.Surface(z=self.mesh_fn, x=self.mesh_x, y=self.mesh_y, opacity=0.5)\n trace = go.Scatter3d(\n x=self.xyz[0], y=self.xyz[1], z=self.xyz[2], marker = dict(\n size = 12,\n color = -np.arange(0, len(self.xyz[2])), # set color to an array/list of desired values\n colorscale='Bluered'), visible=True\n )\n fig = go.Figure(data = [ trace,surface ])\n fig.update_layout(title=title, autosize=False,\n width=1000, height=1000,\n margin=dict(l=65, r=50, b=65, t=90),\n showlegend=False)\n fig.show()\n\n def history_3D(self, title=\"Search History\"):\n surface = go.Surface(z=self.mesh_fn, x=self.mesh_x, y=self.mesh_y, opacity=0.5)\n trace = go.Scatter3d(\n x=self.history[0], y=self.history[1], z=self.history[2], mode='markers',marker = dict(\n size = 1,\n color = -np.arange(0, len(self.history[2])), # set color to an array/list of desired values\n colorscale='Bluered')\n )\n fig = go.Figure(data = [ trace,surface ])\n fig.update_layout(title=title, autosize=False,\n width=1000, height=1000,\n margin=dict(l=65, r=50, b=65, t=90),\n showlegend=False)\n fig.show()\n\n\n# viz = animation_sa(simanneal, -1.0, 1.0, 0.1)\n\ndef history_sa(sa: simulated_annealing, savepath: str='iterations.png'):\n fig = plt.figure()\n ax1 = fig.add_subplot(211)\n ax1.plot(sa.results, 'r.-')\n ax1.legend(['objective_fn'])\n ax2 = fig.add_subplot(212)\n for i in range(len(sa.tries[0])):\n ax2.plot([t[i] for t in sa.tries])\n ax2.legend([str(x) for x in signature(sa.fun).parameters.keys()])\n plt.savefig(savepath)\n plt.show()\n\n\n\n\n# viz.animate()\n","sub_path":"anneal_oop.py","file_name":"anneal_oop.py","file_ext":"py","file_size_in_byte":7307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"493474073","text":"import getopt, sys\nfrom itertools import islice,chain \n\n\nstarter='FastQPolish 1.4 Copyright (C) Sanli et al. (2012) \\nReleased under the GNU-GPL version 3 software license.'\nlicense= 'FastQPolish 1.4 Copyright (C) Sanli et al. (2012)\\nReleased under the GNU-GPL version 3 software license. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see .'\n\n\n\n\nclass Sequence():\n \"\"\"FastQ Sequence object.\"\"\"\n def __init__(self,seqID='',sequence='',spacer='+',quality=''):\n \"\"\"Constructor method of the Fastq Sequence object. \n \n Kwargs:\n\n * seqID (str): First line of a Fastq Sequence object representing the unique identifier\n * sequence (str): Second line of a Fastq Sequence object representing the DNA sequence\n * spacer (str): Third line of a Fastq Sequence object representing the spacer; by default a plus '+' sign. \n * quality (str): Fourth line of a Fastq Sequence object representing the Phred quality scores\n \n \"\"\"\n self.id=seqID # identifier\n self.sequence=sequence # sequence \n self.spacer=spacer # spacer \n self.quality=quality # quality \n\n\n def get_sequence(self):\n \"\"\"FastQ Sequence getter method \n \n Returns:\n\n * FastQ Sequence (str): Four attributes (lines) of a FastQ sequence object are concatenated and returned \n \n \"\"\"\n return self.id+'\\n'+self.sequence+'\\n'+self.spacer+'\\n'+self.quality+'\\n'\n\n\n def set_sequence(self,ID,sequence,quality,spacer='+'): \n \"\"\"Sequence setter method \"\"\" \n self.id=ID \n self.sequence=sequence\n self.quality=quality\n self.spacer=spacer \n\n def __str__(self):\n \"\"\" __str__ method overriding\n \n Returns:\n\n * fastq sequence (str): four lines of the fastq sequence concatenated \n\n \"\"\"\n return self.id+'\\n'+self.sequence+'\\n'+self.spacer+'\\n'+self.quality+'\\n'\n\n\n\n\nclass FastQParser():\n \"\"\"FastQParser object\"\"\"\n def __init__(self,handle):\n \"\"\"constructor method of the Fastq Parser object. \n \n Args:\n\n * handle (iterable): any iterable including fastq sequences: e.g an open fastq file object.\n \n \"\"\"\n\n self.handle=handle\n \n \n @property\n def fastq_sequences(self):\n \"\"\" Fastq Parser setter method. A generator method for Fastq Sequence iterators.\n \n \"\"\"\n while True: \n seqID=self.handle.next().rstrip()\n sequence=self.handle.next().rstrip()\n spacer=self.handle.next().rstrip()\n quality=self.handle.next().rstrip()\n yield Sequence(seqID,sequence=sequence,quality=quality,spacer=spacer) \n\n\n\n \n","sub_path":"build/lib/janitor/fastq_parser.py","file_name":"fastq_parser.py","file_ext":"py","file_size_in_byte":3290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"608933482","text":"from tkinter import *\nimport clipboard\n\nroot = Tk() # creating a blank window\nroot.geometry(\"1200x800+300+100\") # 1200x800 is main window size and 300+100 makes it open in middle of screen\ntitle_label = Label(root, text=\"Marking Comment Generator\", font=(\"Helvetica\", 25))\ntitle_label.place(x=425, y=10) # pack just puts the lab in where ever it can go\n\ntext_box_body = Text(root, height=15, width=125)\ntext_box_body.place(x=100, y=525)\n\nname = \"Jacob\"\n\n#\ndef good_job():\n text_box_body.insert(INSERT, \"Ka nui te pai! \" + name + \"\\n\")\n#\n#\n# def next_step():\n# text_box_body.insert(INSERT, \"your next step is to proof read your work \")\n#\n#\n# def did_well():\n# text_box_body.insert(INSERT, \"You have thought hard about your ideas \")\n\n\n# good_job_button = Button(root, text=\"Praise\", command=good_job)\n# good_job_button.place(x=50, y=50, )\n# good_job_button.config(height=5, width=15)\n#\n# did_well_button = Button(root, text=\"Did well\", command=did_well)\n# did_well_button.place(x=50, y=150, )\n# did_well_button.config(height=5, width=15)\n#\n# next_step_button = Button(root, text=\"constructive criticism\", command=next_step)\n# next_step_button.place(x=50, y=250, )\n# next_step_button.config(height=5, width=15)\n\nbuttons = {\n 'one': {'sticky': W + E + N + S, 'padx': 1, 'pady': 1},\n 'two': {'sticky': W + E + N + S, 'row': 0, 'column': 1, 'padx': 1, 'pady': 1},\n 'three': {'sticky': W + E + N + S, 'row': 0, 'column': 2, 'padx': 1, 'pady': 1}\n}\nprint(type(buttons))\nfor b in buttons:\n button = Button(root, text=b.title())\n button.grid(**buttons[b])\n\ndef Copy_input():\n text_box_string = text_box_body.get(\"1.0\", END) # copies the data in the textbox\n clipboard.copy(text_box_string) # adds the data in the text box to the pc clipboard\n\n\ncopy_text_button = Button(root, text=\"Copy Comment\", command=Copy_input, wraplength=80, justify=LEFT)\ncopy_text_button.place(x=1110, y=550)\ncopy_text_button.config(height=10, width=10)\n\n\ndef onClick(i):\n print(i)\n\ndict = {\"good job\": \"You've done a great job\",\n \"tau ke que\": \"testing file one\",\n \"gj\": \"testing file two\",\n \"nicu\":\"testing file three\"}\n\n\ndef start(i,xrow, ycolumn):\n button_identities = []\n yaxis = 50\n count = 0\n for x in range(ycolumn): # change 3 to a list\n\n print(\"here\")\n #print(yaxis)\n xaxis = 10\n for y in range(xrow):\n b = Button(root, height=5, width=13, command=lambda y=y: onClick(i))\n b.config(text=x)\n b.place(x=xaxis, y=yaxis)\n xaxis += 110\n button_identities.append(b)\n count += 1\n #print(count)\n\n\nstart(5,2,2)\n# start(160)\n# start(250)\n# start(340)\n# start(430)\nroot.mainloop()\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":2725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"119408816","text":"import asyncio\nimport subprocess\nfrom collections import Mapping, Sequence\n\nfrom ..core.formatter import FormattedEntity\nfrom .base import Worker\n\n\nclass Subprocess(FormattedEntity, Worker):\n \"\"\"\n config:\n cmd: str - shell command with mask python format\n list[str] - exec command with mask python format\n stdout: [none | PIPE | DEVNULL]\n stderr: [none | PIPE | DEVNULL]\n wait: bool - default True for wait shutdown process\n format: [json|str|bytes]\n \"\"\"\n\n async def init(self):\n if self.config.get('stdout'):\n self._stdout = getattr(subprocess, self.config.get('stdout'))\n elif 'stdout' in self.config:\n self._stdout = None\n else:\n self._stdout = subprocess.PIPE\n\n if self.config.get('stderr'):\n self._stderr = getattr(subprocess, self.config.get('stderr'))\n else:\n self._stderr = None\n self._wait = self.config.get('wait', True)\n await super().init()\n\n @property\n def process(self):\n if hasattr(self, '_process') and self._process is not None:\n return self._process\n\n def make_command(self, value):\n cmd = self.config.get('cmd')\n if value is None:\n return cmd,\n elif not cmd and isinstance(value, Sequence):\n return value\n elif not cmd and isinstance(value, str):\n return value,\n elif isinstance(cmd, list) and isinstance(value, str):\n return cmd + [value]\n elif isinstance(cmd, list) and isinstance(value, Sequence):\n result = list(cmd)\n result.extend(value)\n return result\n elif isinstance(cmd, list) and isinstance(value, Mapping):\n return [i.format_map(value) for i in cmd]\n elif isinstance(cmd, str) and isinstance(value, str):\n return self.config.cmd + ' ' + value,\n elif isinstance(cmd, str) and isinstance(value, Mapping):\n return self.config.cmd.format_map(value),\n elif isinstance(cmd, str) and isinstance(value, Sequence):\n return self.config.cmd.format(*value),\n else:\n raise ValueError(value)\n\n async def run_cmd(self, *args, **kwargs):\n if len(args) > 1:\n value = args\n elif args:\n value = args[0]\n elif kwargs:\n value = kwargs\n else:\n value = None\n cmd = self.make_command(value)\n self.logger.info(' '.join(cmd))\n if len(cmd) > 1:\n coro = asyncio.create_subprocess_exec\n else:\n coro = asyncio.create_subprocess_shell\n self._process = await coro(\n *cmd, stdout=self._stdout, stderr=self._stderr, loop=self.loop)\n if self._wait:\n await self._process.wait()\n if self._stdout:\n data = await self._process.stdout.read()\n return self.decode(data)\n\n run = run_cmd\n","sub_path":"aioworkers/worker/subprocess.py","file_name":"subprocess.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"152068689","text":"\"\"\" utility classes and functions to load yaml config files. \"\"\"\n\n\n\nimport os\nimport yaml\n\n\n\nclass LoaderMeta(type):\n\n def __new__(metacls, __name__, __bases__, __dict__):\n \"\"\"Add include constructer to class.\"\"\"\n\n # register the include constructor on the class\n cls = super().__new__(metacls, __name__, __bases__, __dict__)\n cls.add_constructor('!include', cls.construct_include)\n\n return cls\n\n\nclass Loader(yaml.Loader, metaclass=LoaderMeta):\n \"\"\"YAML Loader with `!include` constructor.\"\"\"\n\n def __init__(self, stream):\n \"\"\"Initialise Loader.\"\"\"\n\n try:\n self._root = os.path.split(stream.name)[0]\n except AttributeError:\n self._root = os.path.curdir\n\n super().__init__(stream)\n\n def construct_include(self, node):\n \"\"\"Include file referenced at node.\"\"\"\n\n filename = os.path.abspath(os.path.join(\n self._root, self.construct_scalar(node)\n ))\n extension = os.path.splitext(filename)[1].lstrip('.')\n\n with open(filename, 'r') as f:\n if extension in ('yaml', 'yml'):\n return yaml.load(f, Loader)\n else:\n return ''.join(f.readlines())\n\n\ndef parse(fn):\n \"\"\"Open fn and load yaml file, including the !include constructor.\"\"\"\n\n if fn:\n with open(fn, 'r') as ymlfile:\n config = yaml.load(ymlfile, Loader)\n return config\n else:\n raise Exception('no filename given')\n","sub_path":"trkpy/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"455570705","text":"import sys\n\nsys.argv = [\"main.py\", \"input.txt\"]\n\ndef main():\n test_cases = open(sys.argv[1], 'r')\n for test in test_cases:\n test = test.strip()\n data = test.split(\",\")\n total = 0\n child_count = 0\n data_nums = {\n \"Vampires\": 0,\n \"Zombies\": 0,\n \"Witches\": 0,\n \"Houses\": 0\n }\n\n for i in range(0, len(data)):\n data_split = data[i].split(\":\")\n data_nums[data_split[0].strip()] = int(data_split[1].strip())\n\n child_count = data_nums[\"Vampires\"] + data_nums[\"Zombies\"] + data_nums[\"Witches\"]\n total = (data_nums[\"Vampires\"] * 3) + (data_nums[\"Zombies\"] * 4) + (data_nums[\"Witches\"] * 5)\n\n print (total * data_nums[\"Houses\"]) / child_count\n\n test_cases.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"01-Easy/trick-or-treat/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"356759640","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 3 11:55:52 2019\n\n@author: Sven van Koutrik\n\"\"\"\nimport kartlapsim.utils.constants as constants\nimport numpy as np\nimport math\n\n\nclass Kart: \n \n def __init__(self, filenm):\n #meta\n self.m = 110\n self.vmax = 150\n self.hcg = 0.4\n self.l = 1.05\n self.wd = 0.4 \n self._rFinal = 71/10\n self.rTrans = np.array([1])\n self.T = 1 #m, track width\n self.frontbrakes = False\n \n #tyre\n self.mux = 1.72\n self.muy = 1.7\n self.betamax = 9 #deg, max beta for slip angle drag calc\n self.rw = 0.132 #m, wheel radius\n self.rwAyCoeff = 0.02 #rel change of rw with ay\n self.sxmax = 0.08 #long slip for max long force\n \n #resistance\n self.rho_air = 1.2\n self.cxa = 0.05\n self.croll = 0.02\n self.torqueCurveFile = filenm\n \n def ini(self):\n self.processTorqueCurve()\n self.calcAccLims()\n \n def processTorqueCurve(self):\n \n datarray = np.loadtxt(self.torqueCurveFile, delimiter=';', skiprows=1) \n \n nEng = datarray[:,0]*2*math.pi/60 #rad/s\n tEng = datarray[:,1]\n \n if len(self.rTrans)==1: #single gear\n self.nAxlePT = nEng/self.rFinal/self.rTrans\n self.TAxlePT = tEng*self.rFinal*self.rTrans\n else: #multiple gears\n self.nAxlePT = np.linspace(0,self.vmax/self.rw) #rad/s, axle speed range\n TAxleGear = []\n for i,r in enumerate(self.rTrans): #calc axle torque over speed range for each gear\n nEngPT = self.nAxlePT*self.rFinal*r\n TAxleGear.append( np.interp(nEngPT,nEng,tEng)*self.rFinal*r ) \n self.TAxlePT = np.amax( np.array(TAxleGear) ,axis=0)\n \n def calcAccLims(self):\n self.aymax = constants.g*self.muy\n self.fxmax = self.mux*((1-self.wd)*self.l*self.m*constants.g)/(self.l-self.mux*self.hcg)\n if self.frontbrakes:\n self.fxmin = -self.mux*self.m*constants.g\n else:\n self.fxmin = -self.mux*((1-self.wd)*self.l*self.m*constants.g)/(self.l+self.mux*self.hcg) \n\n","sub_path":"kartlapsim/kart.py","file_name":"kart.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"133243439","text":"\r\nimport os\r\ndebugging = False\r\n# if not debug mode then don't log to file or console\r\nif not debugging:\r\n os.environ['KIVY_NO_FILELOG'] = '1'\r\n os.environ['KIVY_NO_CONSOLELOG'] = '1'\r\n\r\nfrom kivy.logger import Logger\r\n\r\nimport kivy\r\nkivy.require('1.8.0')\r\n\r\nfrom kivy.app import App\r\nfrom kivy.config import Config\r\nfrom kivy.logger import Logger\r\nfrom kivy.metrics import dp, sp\r\n\r\nfrom dryfire.model.targetsModel import HipsAndHeadDryFireTargetModel\r\nfrom dryfire.view.appView import AppView\r\nfrom dryfire.model.persistentData import RangesModel, CalibrationsModel,\\\r\n BGFGsModel\r\n\r\nclass DryFireApp(App):\r\n \"\"\"\r\n this is the application class.\r\n the build method creates and returns an AppView object.\r\n that AppView object calls the other views.\r\n those views setup thier view models.\r\n \"\"\"\r\n icon = 'dryfire_64.png'\r\n\r\n\r\n def build(self):\r\n \"\"\"\r\n appdata is a dictionary of application wide data.\r\n App.get_running_app().appdata\r\n \"\"\"\r\n self.appdata = {}\r\n self.appdata['version'] = {'major': 5, 'minor': 0, 'bugfix': 2}\r\n # debug mode\r\n self.appdata['debug'] = debugging\r\n # target view model\r\n self.appdata['target_vm'] = None\r\n # ranges view model\r\n self.appdata['ranges_view'] = None\r\n # where the persistent data is stored\r\n self.appdata['user_data_dir'] = os.path.realpath(self.directory)\r\n # persistent data\r\n self.appdata['bgfgs'] = BGFGsModel(self.appdata['user_data_dir'])\r\n self.appdata['ranges'] = RangesModel(self.appdata['user_data_dir'])\r\n self.appdata['calibrations'] = CalibrationsModel(self.appdata['user_data_dir'])\r\n\r\n app_view = AppView(size_hint=(1.0, 1.0))\r\n self.appdata['app_view'] = app_view\r\n # self.appdata['app_view'] = TargetButtonSelect(size_hint=(1.0, 1.0))\r\n return self.appdata['app_view']\r\n\r\n def on_start(self):\r\n pass\r\n\r\n def on_pause(self):\r\n self.appdata ['app_view'].visible = False\r\n return True\r\n\r\n def on_resume(self):\r\n pass\r\n\r\n def on_stop(self):\r\n self.appdata ['target_vm'].visible = False\r\n\r\n# Config.set('graphics', 'fullscreen', 'auto')\r\napp = DryFireApp()\r\n# Logger.info('user data at :' + app.appdata['user_data_dir'])\r\napp.run()\r\n","sub_path":"windows/dryfire.py","file_name":"dryfire.py","file_ext":"py","file_size_in_byte":2323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"507076867","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom enum import Enum\nfrom azure.core import CaseInsensitiveEnumMeta\n\n\nclass CachingTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Specifies the caching requirements. :code:`
`:code:`
` Possible values are:\n :code:`
`:code:`
` **None** :code:`
`:code:`
` **ReadOnly**\n :code:`
`:code:`
` **ReadWrite** :code:`
`:code:`
` Default: **None for Standard\n storage. ReadOnly for Premium storage**.\n \"\"\"\n\n NONE = \"None\"\n READ_ONLY = \"ReadOnly\"\n READ_WRITE = \"ReadWrite\"\n\n\nclass DiskCreateOptionTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Specifies how the virtual machine should be created.:code:`
`:code:`
` Possible values\n are::code:`
`:code:`
` **Attach** \\u2013 This value is used when you are using a\n specialized disk to create the virtual machine.:code:`
`:code:`
` **FromImage** \\u2013\n This value is used when you are using an image to create the virtual machine. If you are using\n a platform image, you also use the imageReference element described above. If you are using a\n marketplace image, you also use the plan element previously described.\n \"\"\"\n\n FROM_IMAGE = \"FromImage\"\n EMPTY = \"Empty\"\n ATTACH = \"Attach\"\n\n\nclass IntervalInMins(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Interval value in minutes used to create LogAnalytics call rate logs.\"\"\"\n\n THREE_MINS = \"ThreeMins\"\n FIVE_MINS = \"FiveMins\"\n THIRTY_MINS = \"ThirtyMins\"\n SIXTY_MINS = \"SixtyMins\"\n\n\nclass IPVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Available from Api-Version 2017-03-30 onwards, it represents whether the specific\n ipconfiguration is IPv4 or IPv6. Default is taken as IPv4. Possible values are: 'IPv4' and\n 'IPv6'.\n \"\"\"\n\n I_PV4 = \"IPv4\"\n I_PV6 = \"IPv6\"\n\n\nclass MaintenanceOperationResultCodeTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"The Last Maintenance Operation Result Code.\"\"\"\n\n NONE = \"None\"\n RETRY_LATER = \"RetryLater\"\n MAINTENANCE_ABORTED = \"MaintenanceAborted\"\n MAINTENANCE_COMPLETED = \"MaintenanceCompleted\"\n\n\nclass OperatingSystemStateTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"The OS State.\"\"\"\n\n GENERALIZED = \"Generalized\"\n SPECIALIZED = \"Specialized\"\n\n\nclass OperatingSystemTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"The operating system of the osDiskImage.\"\"\"\n\n WINDOWS = \"Windows\"\n LINUX = \"Linux\"\n\n\nclass ProtocolTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Specifies the protocol of listener. :code:`
`:code:`
` Possible values are: :code:`
`\\\n **http** :code:`
`:code:`
` **https**.\n \"\"\"\n\n HTTP = \"Http\"\n HTTPS = \"Https\"\n\n\nclass ResourceIdentityType(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"The type of identity used for the virtual machine. The type 'SystemAssigned, UserAssigned'\n includes both an implicitly created identity and a set of user assigned identities. The type\n 'None' will remove any identities from the virtual machine.\n \"\"\"\n\n SYSTEM_ASSIGNED = \"SystemAssigned\"\n USER_ASSIGNED = \"UserAssigned\"\n SYSTEM_ASSIGNED_USER_ASSIGNED = \"SystemAssigned, UserAssigned\"\n NONE = \"None\"\n\n\nclass RollingUpgradeActionType(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"The last action performed on the rolling upgrade.\"\"\"\n\n START = \"Start\"\n CANCEL = \"Cancel\"\n\n\nclass RollingUpgradeStatusCode(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Code indicating the current status of the upgrade.\"\"\"\n\n ROLLING_FORWARD = \"RollingForward\"\n CANCELLED = \"Cancelled\"\n COMPLETED = \"Completed\"\n FAULTED = \"Faulted\"\n\n\nclass SettingNames(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Specifies the name of the setting to which the content applies. Possible values are:\n FirstLogonCommands and AutoLogon.\n \"\"\"\n\n AUTO_LOGON = \"AutoLogon\"\n FIRST_LOGON_COMMANDS = \"FirstLogonCommands\"\n\n\nclass StatusLevelTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"The level code.\"\"\"\n\n INFO = \"Info\"\n WARNING = \"Warning\"\n ERROR = \"Error\"\n\n\nclass StorageAccountTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Specifies the storage account type for the managed disk. Possible values are: Standard_LRS or\n Premium_LRS.\n \"\"\"\n\n STANDARD_LRS = \"Standard_LRS\"\n PREMIUM_LRS = \"Premium_LRS\"\n\n\nclass UpgradeMode(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Specifies the mode of an upgrade to virtual machines in the scale set.:code:`
`:code:`` Possible values are::code:`
`:code:`
` **Manual** - You control the application\n of updates to virtual machines in the scale set. You do this by using the manualUpgrade\n action.:code:`
`:code:`
` **Automatic** - All virtual machines in the scale set are\n automatically updated at the same time.\n \"\"\"\n\n AUTOMATIC = \"Automatic\"\n MANUAL = \"Manual\"\n ROLLING = \"Rolling\"\n\n\nclass UpgradeOperationInvoker(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Invoker of the Upgrade Operation.\"\"\"\n\n UNKNOWN = \"Unknown\"\n USER = \"User\"\n PLATFORM = \"Platform\"\n\n\nclass UpgradeState(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Code indicating the current status of the upgrade.\"\"\"\n\n ROLLING_FORWARD = \"RollingForward\"\n CANCELLED = \"Cancelled\"\n COMPLETED = \"Completed\"\n FAULTED = \"Faulted\"\n\n\nclass VirtualMachineEvictionPolicyTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Specifies the eviction policy for virtual machines in a low priority scale set.\n :code:`
`:code:`
`Minimum api-version: 2017-10-30-preview.\n \"\"\"\n\n DEALLOCATE = \"Deallocate\"\n DELETE = \"Delete\"\n\n\nclass VirtualMachinePriorityTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Specifies the priority for the virtual machines in the scale set.\n :code:`
`:code:`
`Minimum api-version: 2017-10-30-preview.\n \"\"\"\n\n REGULAR = \"Regular\"\n LOW = \"Low\"\n\n\nclass VirtualMachineScaleSetSkuScaleType(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"The scale type applicable to the sku.\"\"\"\n\n AUTOMATIC = \"Automatic\"\n NONE = \"None\"\n\n\nclass VirtualMachineSizeTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta):\n \"\"\"Specifies the size of the virtual machine. For more information about virtual machine sizes,\n see `Sizes for virtual machines\n `_.\n :code:`
`:code:`
` The available VM sizes depend on region and availability set. For a\n list of available sizes use these APIs: :code:`
`:code:`
` `List all available virtual\n machine sizes in an availability set\n `_\n :code:`
`:code:`
` `List all available virtual machine sizes in a region\n `_\n :code:`
`:code:`
` `List all available virtual machine sizes for resizing\n `_.\n \"\"\"\n\n BASIC_A0 = \"Basic_A0\"\n BASIC_A1 = \"Basic_A1\"\n BASIC_A2 = \"Basic_A2\"\n BASIC_A3 = \"Basic_A3\"\n BASIC_A4 = \"Basic_A4\"\n STANDARD_A0 = \"Standard_A0\"\n STANDARD_A1 = \"Standard_A1\"\n STANDARD_A2 = \"Standard_A2\"\n STANDARD_A3 = \"Standard_A3\"\n STANDARD_A4 = \"Standard_A4\"\n STANDARD_A5 = \"Standard_A5\"\n STANDARD_A6 = \"Standard_A6\"\n STANDARD_A7 = \"Standard_A7\"\n STANDARD_A8 = \"Standard_A8\"\n STANDARD_A9 = \"Standard_A9\"\n STANDARD_A10 = \"Standard_A10\"\n STANDARD_A11 = \"Standard_A11\"\n STANDARD_A1_V2 = \"Standard_A1_v2\"\n STANDARD_A2_V2 = \"Standard_A2_v2\"\n STANDARD_A4_V2 = \"Standard_A4_v2\"\n STANDARD_A8_V2 = \"Standard_A8_v2\"\n STANDARD_A2_M_V2 = \"Standard_A2m_v2\"\n STANDARD_A4_M_V2 = \"Standard_A4m_v2\"\n STANDARD_A8_M_V2 = \"Standard_A8m_v2\"\n STANDARD_B1_S = \"Standard_B1s\"\n STANDARD_B1_MS = \"Standard_B1ms\"\n STANDARD_B2_S = \"Standard_B2s\"\n STANDARD_B2_MS = \"Standard_B2ms\"\n STANDARD_B4_MS = \"Standard_B4ms\"\n STANDARD_B8_MS = \"Standard_B8ms\"\n STANDARD_D1 = \"Standard_D1\"\n STANDARD_D2 = \"Standard_D2\"\n STANDARD_D3 = \"Standard_D3\"\n STANDARD_D4 = \"Standard_D4\"\n STANDARD_D11 = \"Standard_D11\"\n STANDARD_D12 = \"Standard_D12\"\n STANDARD_D13 = \"Standard_D13\"\n STANDARD_D14 = \"Standard_D14\"\n STANDARD_D1_V2 = \"Standard_D1_v2\"\n STANDARD_D2_V2 = \"Standard_D2_v2\"\n STANDARD_D3_V2 = \"Standard_D3_v2\"\n STANDARD_D4_V2 = \"Standard_D4_v2\"\n STANDARD_D5_V2 = \"Standard_D5_v2\"\n STANDARD_D2_V3 = \"Standard_D2_v3\"\n STANDARD_D4_V3 = \"Standard_D4_v3\"\n STANDARD_D8_V3 = \"Standard_D8_v3\"\n STANDARD_D16_V3 = \"Standard_D16_v3\"\n STANDARD_D32_V3 = \"Standard_D32_v3\"\n STANDARD_D64_V3 = \"Standard_D64_v3\"\n STANDARD_D2_S_V3 = \"Standard_D2s_v3\"\n STANDARD_D4_S_V3 = \"Standard_D4s_v3\"\n STANDARD_D8_S_V3 = \"Standard_D8s_v3\"\n STANDARD_D16_S_V3 = \"Standard_D16s_v3\"\n STANDARD_D32_S_V3 = \"Standard_D32s_v3\"\n STANDARD_D64_S_V3 = \"Standard_D64s_v3\"\n STANDARD_D11_V2 = \"Standard_D11_v2\"\n STANDARD_D12_V2 = \"Standard_D12_v2\"\n STANDARD_D13_V2 = \"Standard_D13_v2\"\n STANDARD_D14_V2 = \"Standard_D14_v2\"\n STANDARD_D15_V2 = \"Standard_D15_v2\"\n STANDARD_DS1 = \"Standard_DS1\"\n STANDARD_DS2 = \"Standard_DS2\"\n STANDARD_DS3 = \"Standard_DS3\"\n STANDARD_DS4 = \"Standard_DS4\"\n STANDARD_DS11 = \"Standard_DS11\"\n STANDARD_DS12 = \"Standard_DS12\"\n STANDARD_DS13 = \"Standard_DS13\"\n STANDARD_DS14 = \"Standard_DS14\"\n STANDARD_DS1_V2 = \"Standard_DS1_v2\"\n STANDARD_DS2_V2 = \"Standard_DS2_v2\"\n STANDARD_DS3_V2 = \"Standard_DS3_v2\"\n STANDARD_DS4_V2 = \"Standard_DS4_v2\"\n STANDARD_DS5_V2 = \"Standard_DS5_v2\"\n STANDARD_DS11_V2 = \"Standard_DS11_v2\"\n STANDARD_DS12_V2 = \"Standard_DS12_v2\"\n STANDARD_DS13_V2 = \"Standard_DS13_v2\"\n STANDARD_DS14_V2 = \"Standard_DS14_v2\"\n STANDARD_DS15_V2 = \"Standard_DS15_v2\"\n STANDARD_DS13_4_V2 = \"Standard_DS13-4_v2\"\n STANDARD_DS13_2_V2 = \"Standard_DS13-2_v2\"\n STANDARD_DS14_8_V2 = \"Standard_DS14-8_v2\"\n STANDARD_DS14_4_V2 = \"Standard_DS14-4_v2\"\n STANDARD_E2_V3 = \"Standard_E2_v3\"\n STANDARD_E4_V3 = \"Standard_E4_v3\"\n STANDARD_E8_V3 = \"Standard_E8_v3\"\n STANDARD_E16_V3 = \"Standard_E16_v3\"\n STANDARD_E32_V3 = \"Standard_E32_v3\"\n STANDARD_E64_V3 = \"Standard_E64_v3\"\n STANDARD_E2_S_V3 = \"Standard_E2s_v3\"\n STANDARD_E4_S_V3 = \"Standard_E4s_v3\"\n STANDARD_E8_S_V3 = \"Standard_E8s_v3\"\n STANDARD_E16_S_V3 = \"Standard_E16s_v3\"\n STANDARD_E32_S_V3 = \"Standard_E32s_v3\"\n STANDARD_E64_S_V3 = \"Standard_E64s_v3\"\n STANDARD_E32_16_V3 = \"Standard_E32-16_v3\"\n STANDARD_E32_8_S_V3 = \"Standard_E32-8s_v3\"\n STANDARD_E64_32_S_V3 = \"Standard_E64-32s_v3\"\n STANDARD_E64_16_S_V3 = \"Standard_E64-16s_v3\"\n STANDARD_F1 = \"Standard_F1\"\n STANDARD_F2 = \"Standard_F2\"\n STANDARD_F4 = \"Standard_F4\"\n STANDARD_F8 = \"Standard_F8\"\n STANDARD_F16 = \"Standard_F16\"\n STANDARD_F1_S = \"Standard_F1s\"\n STANDARD_F2_S = \"Standard_F2s\"\n STANDARD_F4_S = \"Standard_F4s\"\n STANDARD_F8_S = \"Standard_F8s\"\n STANDARD_F16_S = \"Standard_F16s\"\n STANDARD_F2_S_V2 = \"Standard_F2s_v2\"\n STANDARD_F4_S_V2 = \"Standard_F4s_v2\"\n STANDARD_F8_S_V2 = \"Standard_F8s_v2\"\n STANDARD_F16_S_V2 = \"Standard_F16s_v2\"\n STANDARD_F32_S_V2 = \"Standard_F32s_v2\"\n STANDARD_F64_S_V2 = \"Standard_F64s_v2\"\n STANDARD_F72_S_V2 = \"Standard_F72s_v2\"\n STANDARD_G1 = \"Standard_G1\"\n STANDARD_G2 = \"Standard_G2\"\n STANDARD_G3 = \"Standard_G3\"\n STANDARD_G4 = \"Standard_G4\"\n STANDARD_G5 = \"Standard_G5\"\n STANDARD_GS1 = \"Standard_GS1\"\n STANDARD_GS2 = \"Standard_GS2\"\n STANDARD_GS3 = \"Standard_GS3\"\n STANDARD_GS4 = \"Standard_GS4\"\n STANDARD_GS5 = \"Standard_GS5\"\n STANDARD_GS4_8 = \"Standard_GS4-8\"\n STANDARD_GS4_4 = \"Standard_GS4-4\"\n STANDARD_GS5_16 = \"Standard_GS5-16\"\n STANDARD_GS5_8 = \"Standard_GS5-8\"\n STANDARD_H8 = \"Standard_H8\"\n STANDARD_H16 = \"Standard_H16\"\n STANDARD_H8_M = \"Standard_H8m\"\n STANDARD_H16_M = \"Standard_H16m\"\n STANDARD_H16_R = \"Standard_H16r\"\n STANDARD_H16_MR = \"Standard_H16mr\"\n STANDARD_L4_S = \"Standard_L4s\"\n STANDARD_L8_S = \"Standard_L8s\"\n STANDARD_L16_S = \"Standard_L16s\"\n STANDARD_L32_S = \"Standard_L32s\"\n STANDARD_M64_S = \"Standard_M64s\"\n STANDARD_M64_MS = \"Standard_M64ms\"\n STANDARD_M128_S = \"Standard_M128s\"\n STANDARD_M128_MS = \"Standard_M128ms\"\n STANDARD_M64_32_MS = \"Standard_M64-32ms\"\n STANDARD_M64_16_MS = \"Standard_M64-16ms\"\n STANDARD_M128_64_MS = \"Standard_M128-64ms\"\n STANDARD_M128_32_MS = \"Standard_M128-32ms\"\n STANDARD_NC6 = \"Standard_NC6\"\n STANDARD_NC12 = \"Standard_NC12\"\n STANDARD_NC24 = \"Standard_NC24\"\n STANDARD_NC24_R = \"Standard_NC24r\"\n STANDARD_NC6_S_V2 = \"Standard_NC6s_v2\"\n STANDARD_NC12_S_V2 = \"Standard_NC12s_v2\"\n STANDARD_NC24_S_V2 = \"Standard_NC24s_v2\"\n STANDARD_NC24_RS_V2 = \"Standard_NC24rs_v2\"\n STANDARD_NC6_S_V3 = \"Standard_NC6s_v3\"\n STANDARD_NC12_S_V3 = \"Standard_NC12s_v3\"\n STANDARD_NC24_S_V3 = \"Standard_NC24s_v3\"\n STANDARD_NC24_RS_V3 = \"Standard_NC24rs_v3\"\n STANDARD_ND6_S = \"Standard_ND6s\"\n STANDARD_ND12_S = \"Standard_ND12s\"\n STANDARD_ND24_S = \"Standard_ND24s\"\n STANDARD_ND24_RS = \"Standard_ND24rs\"\n STANDARD_NV6 = \"Standard_NV6\"\n STANDARD_NV12 = \"Standard_NV12\"\n STANDARD_NV24 = \"Standard_NV24\"\n","sub_path":"sdk/compute/azure-mgmt-compute/azure/mgmt/compute/v2017_12_01/models/_compute_management_client_enums.py","file_name":"_compute_management_client_enums.py","file_ext":"py","file_size_in_byte":13951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"341199851","text":"# -*- coding: utf-8 -*-\nfrom .strategy import Strategy\nfrom utils.url import get_url_site\n\nclass Forbid(Strategy):\n \"\"\"docstring for Forbid\"\"\"\n def run(self,data):\n for case in data:\n if case.close and case.result.get(\"conclusion\") in [\"noProblem\",\"robots\"]:\n continue\n # robots = case.get_data(\"robots\")\n # if not robots or robots.get('robots') != \"DISALLOW\":\n # return\n site = get_url_site(case.target)\n if \".wapka.me\" in site or \".wapka.mobi\" in site:\n case.set_result(\"conclusion\",\"Forbidden\")\n case.set_result(\"reason\",\"ip\")\n case.close = True\n continue\n forbid = case.get_data(\"forbid\")\n if not forbid:\n continue\n if \"forbidden\" in forbid and forbid[\"forbidden\"]:\n case.set_result(\"conclusion\",\"Forbidden\")\n case.set_result(\"reason\",forbid[\"forbidden\"])\n if \"out\" in forbid and forbid[\"out\"]:\n case.set_result(\"conclusion\",\"Forbidden_nm\")\n case.set_result(\"additional\",forbid[\"out\"])\n case.close = True\n return ","sub_path":"cover-monitor-framwork/strategy/forbid.py","file_name":"forbid.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"115247623","text":"from django.urls import path\n\nfrom grandchallenge.algorithms.views import (\n AlgorithmCreate,\n AlgorithmDetail,\n AlgorithmExecutionSessionCreate,\n AlgorithmExecutionSessionDetail,\n AlgorithmExperimentCreate,\n AlgorithmImageCreate,\n AlgorithmImageDetail,\n AlgorithmImageUpdate,\n AlgorithmList,\n AlgorithmPermissionRequestCreate,\n AlgorithmPermissionRequestList,\n AlgorithmPermissionRequestUpdate,\n AlgorithmUpdate,\n ComponentInterfaceList,\n EditorsUpdate,\n JobDetail,\n JobExperimentDetail,\n JobUpdate,\n JobViewersUpdate,\n JobsList,\n UsersUpdate,\n)\n\napp_name = \"algorithms\"\n\nurlpatterns = [\n path(\"\", AlgorithmList.as_view(), name=\"list\"),\n path(\"create/\", AlgorithmCreate.as_view(), name=\"create\"),\n path(\n \"interfaces/\",\n ComponentInterfaceList.as_view(),\n name=\"component-interface-list\",\n ),\n path(\"/\", AlgorithmDetail.as_view(), name=\"detail\"),\n path(\"/update/\", AlgorithmUpdate.as_view(), name=\"update\"),\n path(\n \"/images/create/\",\n AlgorithmImageCreate.as_view(),\n name=\"image-create\",\n ),\n path(\n \"/images//\",\n AlgorithmImageDetail.as_view(),\n name=\"image-detail\",\n ),\n path(\n \"/images//update/\",\n AlgorithmImageUpdate.as_view(),\n name=\"image-update\",\n ),\n path(\n \"/experiments/create/\",\n AlgorithmExecutionSessionCreate.as_view(),\n name=\"execution-session-create\",\n ),\n path(\n \"/experiments/create/flex/\",\n AlgorithmExperimentCreate.as_view(),\n name=\"execution-session-create-new\",\n ),\n path(\n \"/experiments//\",\n AlgorithmExecutionSessionDetail.as_view(),\n name=\"execution-session-detail\",\n ),\n path(\"/jobs/\", JobsList.as_view(), name=\"job-list\"),\n path(\"/jobs//\", JobDetail.as_view(), name=\"job-detail\",),\n path(\n \"/jobs//update/\",\n JobUpdate.as_view(),\n name=\"job-update\",\n ),\n path(\n \"/jobs//experiment/\",\n JobExperimentDetail.as_view(),\n name=\"job-experiment-detail\",\n ),\n path(\n \"/jobs//viewers/update/\",\n JobViewersUpdate.as_view(),\n name=\"job-viewers-update\",\n ),\n path(\n \"/editors/update/\",\n EditorsUpdate.as_view(),\n name=\"editors-update\",\n ),\n path(\"/users/update/\", UsersUpdate.as_view(), name=\"users-update\"),\n path(\n \"/permission-requests/\",\n AlgorithmPermissionRequestList.as_view(),\n name=\"permission-request-list\",\n ),\n path(\n \"/permission-requests/create/\",\n AlgorithmPermissionRequestCreate.as_view(),\n name=\"permission-request-create\",\n ),\n path(\n \"/permission-requests//update/\",\n AlgorithmPermissionRequestUpdate.as_view(),\n name=\"permission-request-update\",\n ),\n]\n","sub_path":"app/grandchallenge/algorithms/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"654358291","text":"import urllib.request, urllib.parse, urllib.error\n\nimport sqlite3\nimport re\n\n\nconn = sqlite3.connect('py4e.sqlite')\ncur = conn.cursor()\n\ncur.execute('DROP TABLE IF EXISTS Counts')\ncur.execute('''\nCREATE TABLE Counts (org TEXT, count INTEGER)''')\n\n###\nfh = open('mbox.txt')\n\nemail_dict = {}\nfor line in fh:\n if not line.startswith('From: '): continue\n pieces = line.split()\n email = pieces[1]\n domain = re.findall('@(\\S+)', email)[0]\n email_dict[domain] = email_dict.get(domain, 0) + 1\n\ninsert_list = []\nfor data in email_dict.items():\n email = data[0]\n count = data[1]\n insert_list.append('({}, {})'.format(repr(email), repr(count)))\n\nsql_str = 'INSERT INTO Counts (org, count) VALUES ' + ','.join(insert_list)\ncur.execute(sql_str)\nconn.commit()\n\n# https://www.sqlite.org/lang_select.html\n# sqlstr = 'SELECT email, count FROM Counts ORDER BY count DESC LIMIT 10'\n\n# cur.execute('SELECT email, count FROM Counts ORDER BY count DESC LIMIT 1')\n\n# for row in cur.execute(sqlstr):\n# print(str(row[0]), row[1])\n\ncur.close()","sub_path":"py4e/chapter15/chapter15-1.py","file_name":"chapter15-1.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"580976042","text":"import numpy as np\nfrom gen_var import * \nimport os\n\n\"\"\"This code will solve the Berger and Seltzer stopping power ode for singular time \nbut with an artbitrary pellet potential which linearly increases from the pellet to \nthe cloud edge.\n\nA potential field can be applied to account for additional electrostatic slowing of particles\nand changes in this potential to plot how the fraction of the initial distribution changes \nwith this pellet potential \"\"\" \n\nimport stopblock #function to bethe stop electrons\nimport MB_calc # function to determine EEDF\nimport pot_sum # function to add potentials from electrons and pellet at matching points\n\npot_test = 'false'\n\nparticle = 'electron' # clarifying particle type\n\nfrom electron import e_dist, ener_res, e_bar, KE_top, KE_bot, RME, M_fac #importing essential variables and functions\nimport electron as part\nimport bethe_analysis_functions as baf\n\n\"\"\"Delete all files in the sub directory\"\"\"\n\nmydir = './static_outputs_phi'\nfilelist = [ f for f in os.listdir(mydir) if f.endswith(\".npy\") ]\nfor f in filelist:\n os.remove(os.path.join(mydir, f))\n\ne_mid, e_bins, MB_norm = part.dist_calc(e_dist, ener_res, e_bar) #calculating mid-point energy of bins, bins etc\n\nener = np.arange(KE_bot, KE_top, ener_res) # establishing energy array\nMB = MB_calc.MB(ener, e_bar) \n\n#############################################\n\ni = t_static #index of time-array\n\n#############################################\n\nif (i > lt-1):\n print('Index for time array is too large. Select a time-index that \\\n fits within length of t array')\nelse:\n pass\n\nr = np.arange(0,rc[i] - rp[i], dr)\n\nlr = len(r)\n\"Now set up the potential field across the cloud\" \n\nflux_arr = []\nener_flux_arr = []\nlifetime_arr = []\n\nif (pot_test == 'true') :\n elec_pot = np.loadtxt(mydir+'/elec_pot_t_static.txt')\n r_elec = elec_pot[:,1]\n elec_pot = elec_pot[:,0]\nelse:\n pass\n\nfor p in range(0, lp):\n pot = np.linspace(pel_pot[p], cloud_pot, lr)\n if (pot_test =='true'):\n pot = pot_sum.pot_sum(elec_pot, pot, r_elec, r)\n else:\n pass\n pot /= RME*M_fac\n stopblock.stopblock_phi(e_mid, r,i, particle, pot)\n\n #Analysis codes \n\n term_en, ind = baf.stop_analysis_term_ener.term_energy(particle, r, i, le, mydir)\n stop_point = baf.stop_analysis_stop_point.stop_point(term_en,ind, particle, r,i,len(e_mid), mydir)\n \n \n \n \"Saving data for a singular Bethe calculation\"\n if (pot_test =='true'):\n np.savetxt(os.path.join(mydir, 'terminal_energy_pot_test_t'+str(i)+'pot'+str(pel_pot[p]) +'.txt'), term_en) \n np.savetxt(os.path.join(mydir, 'stop_point_pot_test_t' + str(i) +'pot'+str(pel_pot[p])+'.txt'), stop_point, fmt = ('%f'))\n else:\n np.savetxt(os.path.join(mydir, 'terminal_energy_t'+str(i)+'pot'+str(pel_pot[p]) +'.txt'), term_en) \n np.savetxt(os.path.join(mydir, 'stop_point_t' + str(i) +'pot'+str(pel_pot[p])+'.txt'), stop_point, fmt = ('%f'))\n faux_density,real_density = baf.stop_analysis_particle_density.particle_density(stop_point,i, len(e_mid), e_bins, particle,p)\n ret_flux_frac, ener_flux, lifetime = baf.stop_analysis_retarded_flux.retarded_flux(t_static,mydir, term_en)\n \n if (pot_test =='true'):\n np.savetxt(os.path.join(mydir, 'density_pot_test_t' +str(i) +'pot'+str(pel_pot[p])+'.txt'), faux_density)\n np.savetxt(os.path.join(mydir, 'real_density_pot_test_t'+str(i) +'pot'+str(pel_pot[p])+'.txt'), real_density)\n else:\n \n np.savetxt(os.path.join(mydir, 'density_t' +str(i) +'pot'+str(pel_pot[p])+'.txt'), faux_density)\n np.savetxt(os.path.join(mydir, 'real_density_t'+str(i) +'pot'+str(pel_pot[p])+'.txt'), real_density)\n np.append(flux_arr, (ret_flux_frac, pel_pot[p])) #Append potential dependant arrays with new quantities\n flux_arr.append((ret_flux_frac, pel_pot[p]))\n ener_flux_arr.append((ener_flux, pel_pot[p]))\n lifetime_arr.append((lifetime, pel_pot[p]))\n\"Saving compilation of Bethe calculations with varying potentials\"\nif (pot_test =='true'):\n np.savetxt(os.path.join(mydir, 'retarded_flux_pot_test_t'+str(i)+'.txt'), flux_arr)\n np.savetxt(os.path.join(mydir, 'retarded_ener_flux_pot_test'+str(i)+'.txt'), ener_flux_arr)\n np.savetxt(os.path.join(mydir, 'pellet_lifetime_retarding_potential_pot_test' + str(i)+'.txt'), lifetime_arr)\nelse:\n np.savetxt(os.path.join(mydir, 'retarded_flux_t'+str(i)+'.txt'), flux_arr)\n np.savetxt(os.path.join(mydir, 'retarded_ener_flux'+str(i)+'.txt'), ener_flux_arr)\n np.savetxt(os.path.join(mydir, 'pellet_lifetime_retarding_potential' + str(i)+'.txt'), lifetime_arr)\nprint('success')","sub_path":"bethe_static_cloud.py","file_name":"bethe_static_cloud.py","file_ext":"py","file_size_in_byte":4620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"349316307","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.6-intel/egg/aegis_model/util/aux_functions.py\n# Compiled at: 2020-01-27 21:51:56\n# Size of source mod 2**32: 1679 bytes\nimport datetime, math\nfrom requests import get\nfrom wows_stats.util.ansi_code import AnsiEscapeCode\n\ndef check_ip():\n \"\"\"\n Get external API from REST call\n :return: external ip address of current host\n \"\"\"\n try:\n ip = get('https://api.ipify.org').text\n print('External ip: {}{}{}'.format(AnsiEscapeCode.BLUE, ip, AnsiEscapeCode.ENDC))\n return ip\n except Exception:\n raise\n\n\ndef check_date():\n \"\"\"\n Get current date\n :return: current date in \"%Y-%m-%d\" format\n \"\"\"\n return datetime.datetime.now().date().strftime('%Y-%m-%d')\n\n\ndef max_hundred(x):\n return int(x / 100) * 100\n\n\ndef greatest_common_divisor(x, y):\n if x == 0 or y == 0:\n return 0\n else:\n if x == y:\n return x\n else:\n negate = False\n if not x > 0 > y:\n if x < 0 < y:\n negate = True\n else:\n x = abs(x)\n y = abs(y)\n if x > y:\n r = greatest_common_divisor(x - y, y)\n else:\n r = greatest_common_divisor(y - x, x)\n if negate:\n r = -r\n return r\n\n\ndef least_common_factor_with_limit(x, y, limit=1000):\n f = greatest_common_divisor(x, y)\n factor = 1\n for i in range(1, min(int(math.sqrt(f)), limit) + 1):\n if f % i == 0:\n factor = i\n\n return factor\n\n\ndef list_to_url_params(list):\n return ','.join(str(item) for item in list)\n\n\ndef generate_date_list_of_ten_days(date):\n date_format = '%Y-%m-%d'\n date_range = 10\n date_list = list()\n for day in range(date_range):\n date_list.append((date - datetime.timedelta(days=day)).strftime(format=date_format))\n\n return date_list\n\n\nif __name__ == '__main__':\n x = greatest_common_divisor(288, 108)\n print(x)","sub_path":"pycfiles/aegis_model-0.1-py3.6/aux_functions.cpython-36.py","file_name":"aux_functions.cpython-36.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"145010342","text":"from typing import List, Union\n\nfrom unimport.statement import Import, ImportFrom, Name\n\n__all__ = [\"NAMES\", \"IMPORTS\", \"UNUSED_IMPORTS\"]\n\n\nNAMES: List[Name] = [\n Name(lineno=3, name=\"TYPE_CHECKING\", is_all=False),\n Name(lineno=7, name=\"HistoryType\", is_all=False),\n Name(lineno=7, name=\"QWebHistory\", is_all=False),\n Name(lineno=7, name=\"List\", is_all=False),\n]\nIMPORTS: List[Union[Import, ImportFrom]] = [\n ImportFrom(\n lineno=1,\n column=1,\n name=\"TYPE_CHECKING\",\n package=\"typing\",\n star=False,\n suggestions=[],\n ),\n ImportFrom(\n lineno=1,\n column=2,\n name=\"List\",\n package=\"typing\",\n star=False,\n suggestions=[],\n ),\n ImportFrom(\n lineno=4,\n column=1,\n name=\"QWebHistory\",\n package=\"PyQt5.QtWebKit\",\n star=False,\n suggestions=[],\n ),\n]\nUNUSED_IMPORTS: List[Union[Import, ImportFrom]] = []\n","sub_path":"tests/cases/analyzer/type_variable/type_assing_list.py","file_name":"type_assing_list.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"56010144","text":"from matcher import Matcher\n\n\nclass OptimizerMatcher(Matcher):\n def __init__(self, projects, students, base_matcher):\n super().__init__(projects, students)\n self.base_matcher = base_matcher(projects, students)\n\n def create_match(self):\n self.base_matcher.create_match()\n self.matching = self.base_matcher.matching\n\n self.remove_small_projects()\n\n def remove_small_projects(self):\n small_project_found = True\n while small_project_found:\n small_project_found = False\n for project, members in self.matching.items():\n if len(members) < 3 and project != 'Kein Projekt':\n small_project_found = True\n self.empty_project(project, members)\n self.matching.pop(project)\n break\n\n def empty_project(self, project, members):\n for member in members:\n other_project_found = False\n for prio in member.prios:\n if prio != project and prio in self.matching:\n member.set_got_prio(prio)\n self.matching[prio].append(member)\n other_project_found = True\n break\n\n if not other_project_found:\n member.set_got_prio('Kein Projekt')\n if 'Kein Projekt' in self.matching:\n self.matching['Kein Projekt'].append(member)\n else:\n self.matching['Kein Projekt'] = [member]\n","sub_path":"src/matcher/Optimizer.py","file_name":"Optimizer.py","file_ext":"py","file_size_in_byte":1523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"419174646","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nPackage này dùng để mở rộng open edx app (dạng micro app)\n\"\"\"\n\n__apps__={}\n__register_apps__ = {}\n__controllers__ = []\n__pages__ = []\n__build_cached__ = None\n__controllert_url_build_cache__ = None\n\nfrom . controllers import Model\nfrom xdj import p2n3\nimport sys\n\ndef create(urls):\n \"\"\"\n Tạp app\n :param name:\n :param host_dir:\n :return:\n \"\"\"\n urlpatterns = ()\n global __build_cached__\n if __build_cached__ == None:\n __build_cached__ = {}\n\n from django.conf.urls import url\n import django\n replace_urls = []\n check_urls = []\n for item in __controllers__:\n\n if item.instance.replace_url:\n replace_urls.append(item.instance)\n if item.instance.check_url:\n check_urls.append(item.instance)\n\n if not p2n3.has_key(__apps__, item.instance.app_name):\n import os\n try:\n if item.instance.app_dir != None:\n server_static_path = os.sep.join([\n item.instance.app_dir,\"static\"\n ])\n urlpatterns += p2n3.create_static(item,server_static_path)\n\n except Exception as ex:\n raise ex\n __apps__.update({\n item.instance.app_name:item.instance.app_name\n })\n if not p2n3.has_key(__build_cached__, p2n3.get_function_code_path(item.instance.on_get)):\n url_pat = p2n3.get_url(item, item.instance.__view_exec__)\n if isinstance(url_pat,tuple):\n urlpatterns += p2n3.get_url(item, item.instance.__view_exec__)\n else:\n urlpatterns += (p2n3.get_url(item, item.instance.__view_exec__),)\n # if item.url == \"\":\n # urlpatterns += (\n # url(r\"^\"+item.instance.host_dir + \"$\", item.instance.__view_exec__),\n # url(r\"^\"+item.instance.host_dir + \"/$\", item.instance.__view_exec__)\n # )\n # else:\n # urlpatterns += (\n # url(r\"^\"+item.instance.host_dir +\"/\"+item.url+\"$\", item.instance.__view_exec__),\n # url(r\"^\"+item.instance.host_dir +\"/\"+item.url+\"/$\", item.instance.__view_exec__)\n # )\n for sub_page in item.instance.sub_pages:\n urlpatterns += p2n3.get_url(sub_page, sub_page.exec_request_get)\n # if item.url == \"\":\n # urlpatterns += (\n # url(r\"^\" + item.instance.host_dir+\"/\"+sub_page.url + \"$\", sub_page.exec_request_get),\n # url(r\"^\" + item.instance.host_dir +\"/\"+sub_page.url+ \"/$\", sub_page.exec_request_get)\n # )\n # else:\n # urlpatterns += (\n # url(r\"^\" + item.instance.host_dir + \"/\" + item.url+\"/\"+sub_page.url + \"$\", sub_page.exec_request_get),\n # url(r\"^\" + item.instance.host_dir + \"/\" + item.url+\"/\"+sub_page.url + \"/$\", sub_page.exec_request_get)\n # )\n __build_cached__.update({\n p2n3.get_function_code_path(item.instance.on_get): item.instance.on_get\n })\n # urlpatterns += (\n # url(r'config/self_paced', ConfigurationModelCurrentAPIView.as_view(model=SelfPacedConfiguration)),\n # url(r'config/programs', ConfigurationModelCurrentAPIView.as_view(model=ProgramsApiConfig)),\n # url(r'config/catalog', ConfigurationModelCurrentAPIView.as_view(model=CatalogIntegration)),\n # url(r'config/forums', ConfigurationModelCurrentAPIView.as_view(model=ForumsConfig)),\n # )\n if isinstance(urls,tuple):\n urls += urlpatterns\n for item in replace_urls:\n class cls_replacer():\n def __init__(self,obj):\n self.obj=obj\n def exec_url(self,request,*args,**kwargs):\n return self.obj.__view_exec__(request,*args,**kwargs)\n print (\"will replace with {0}\".format(item.replace_url))\n match_url = [x for x in urls if x.regex.pattern == item.replace_url]\n if match_url.__len__() == 0:\n print (\"{0} can not find replacer, will run under {1}\".format(item.replace_url,item.url))\n else:\n import inspect\n print (\"{0} can not find replacer, will run by controller {1} in {2}\".format(match_url[0].regex.pattern , item,inspect.getfile(item.__class__)))\n x= cls_replacer(item)\n match_url[0].callback = x.exec_url\n for item in check_urls:\n print (\"{0} will be check\".format(item.check_url))\n match_url = [x for x in urls if x.regex.pattern == item.check_url]\n if match_url.__len__() == 0:\n print (\"{0} can not find checker, will run under {1}\".format(item.check_url,item.url))\n else:\n import inspect\n print (\"{0} will be check by controller {1} in {2}\".format(match_url[0].regex.pattern , item,inspect.getfile(item.__class__)))\n class obj_check_url():\n def __init__(self,obj,origin_callback):\n self.obj = obj\n self.__origin_callback__ = origin_callback\n def check_request(self,request,*args,**kwargs):\n ret = self.obj.__view_exec__(request, *args, **kwargs)\n if ret:\n if issubclass(type(ret),Handler):\n _ret = ret.OnBeforeHandler(ret.model)\n if _ret==None:\n _ret = self.__origin_callback__(request,*args,**kwargs)\n ret.model.origin_result= _ret\n _ret = ret.OnAfterHandler(ret.model)\n if _ret == None:\n return ret.model.origin_result\n else:\n return _ret\n return ret\n else:\n return self.__origin_callback__(request, *args, **kwargs)\n\n x_obj = obj_check_url(item,match_url[0].callback)\n # item.__origin_callback__ = x_obj.check_request\n # def __check_request__(request,*args,**kwargs):\n # ret = item.__view_exec__(request,*args,**kwargs)\n # if ret:\n # return ret\n # else:\n # return item.__origin_callback__(request,*args,**kwargs)\n\n\n match_url[0].callback = x_obj.check_request\n\n\n\n if isinstance(urls, list):\n urls.extend(list(urlpatterns))\n\n # x = [x for x in urls if x._regex == r\"^static\\/(?P.*)$\"]\n # u = x[0]\n # print x[0].default_args[\"document_root\"]\n return urls\nfrom . controllers import BaseController,Controller\nfrom .page import Page\n\ndef register_INSTALLED_APPS(for_lms):\n from django.conf import settings\n # if settings.INSTALLED_APPS.count(\"xdj_models.models\") == 0:\n # settings.INSTALLED_APPS.append(\"xdj_models.models\")\n try:\n load_moddels()\n load_settings(for_lms)\n load_config()\n\n load_email_settings()\n load_feature_settings()\n load_elastic_search_config()\n settings.MIDDLEWARE_CLASSES.append(\"xdj.middle_ware.GlobalRequestMiddleware\")\n except Exception as ex:\n raise Exception(ex)\n\ndef load_apps(path_to_app_dir,urlpatterns=None,ignore_app_installed=False):\n if not ignore_app_installed:\n from django.conf import settings\n if settings.INSTALLED_APPS.count(\"xdj_models.models\") == 0:\n raise Exception(\"it look like you forgot call xdj.register_INSTALLED_APPS() at manage.py , cms/bitnami_wsgi.py or lms/bitnami_wsgi.py before startup.run()\\n\"\n \"How to use xdj?\\n\"\n \"At before startup.run() for dev mode or for deploy mode bottom of '{edx source}/apps/edx/edx-platform/lms/envs/bitnami.py' put follow code:\\n\"\n \"import sys\\n\"\n \"sys.path.append(path to parent of xdj package)\\n\"\n \"import xdj\"\n \"xdj.register_INSTALLED_APPS()\\n\"\n \"\")\n\n if urlpatterns==None:\n urlpatterns=()\n import os\n import sys\n import imp\n import xdj\n global __controllert_url_build_cache__\n if __controllert_url_build_cache__ == None:\n __controllert_url_build_cache__ = {}\n sys.path.append(path_to_app_dir)\n apply_settings()\n def get_all_sub_dir():\n if sys.version_info[0] == 2:\n lst=[x for x in os.walk(path_to_app_dir).next()[1] if x.find(\".\")==-1]\n return lst\n if sys.version_info[0] == 3:\n lst = [x for x in os.walk(path_to_app_dir).__next__()[1] if x.find(\".\") == -1]\n return lst\n lst_sub_dirs = get_all_sub_dir()\n for item in lst_sub_dirs:\n full_path_to_app = os.sep.join([path_to_app_dir,item])\n sys.path.append(full_path_to_app)\n controller_dir = os.sep.join([path_to_app_dir,item,\"controllers\"])\n if not hasattr(xdj, \"apps\"):\n setattr(xdj, \"apps\", imp.new_module(\"xdj.apps\"))\n if not hasattr(xdj.apps, item):\n setattr(xdj.apps, item, imp.new_module(\"xdj.apps.{0}\".format(item)))\n app_settings = None\n try:\n app_settings = imp.load_source(\"xdj.apps.{0}.settings\".format(item),os.sep.join([path_to_app_dir,item,\"settings.py\"]))\n except exceptions.IOError as ex:\n raise Exception(\"{0} was not found or error\".format(\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n ))\n except Exception as ex:\n raise ex\n if not hasattr(app_settings,\"app_name\"):\n raise Exception(\"'{0}' was not found in '{1}'\".format(\n \"app_name\",\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n ))\n if not hasattr(app_settings,\"on_authenticate\"):\n raise Exception(\"'{0}' was not found in '{1}'\".format(\n \"on_authenticate\",\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n ))\n if not callable(app_settings.on_authenticate):\n raise Exception(\"{0} in {1} must be a function with one param\".format(\n \"on_authenticate\",\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n ))\n if not hasattr(app_settings,\"host_dir\"):\n raise Exception(\"'{0}' was not found in '{1}'\".format(\n \"host_dir\",\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n ))\n if sys.version_info[0] == 2:\n if not type(app_settings.host_dir) in [str,unicode]:\n raise Exception(\n \"{0} in {3} mut be in {1}, not is {2}\".format(\n \"host_dir\",\n [str,unicode],\n app_settings.host_dir,\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n )\n )\n if sys.version_info[0] == 3:\n if not type(app_settings.host_dir) in [str]:\n raise Exception(\n \"{0} in {3} mut be in {1}, not is {2}\".format(\n \"host_dir\",\n [str],\n app_settings.host_dir,\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n )\n )\n if not hasattr(app_settings,\"on_get_language_resource_item\"):\n raise Exception(\"'{0}' was not found in '{1}'\".format(\n \"on_get_language_resource_item\",\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n ))\n if not callable(app_settings.on_get_language_resource_item):\n raise Exception(\"'{0}' in '{1}' must be a function like bellow\\n\"\n \"on_get_language_resource_item(language,appname,view,key,value)\".format(\n \"on_get_language_resource_item\",\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n ))\n if not hasattr(app_settings,\"rel_login_url\"):\n raise Exception(\"'{0}' was not found in '{1}'\".format(\n \"rel_login_url\",\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n ))\n import inspect\n if inspect.getargspec(app_settings.on_get_language_resource_item).args.__len__()<4:\n raise Exception(\"'{0}' in '{1}' must be a function like bellow\\n\"\n \"on_get_language_resource_item(language,appname,view,key,value)\".format(\n \"on_get_language_resource_item\",\n os.sep.join([path_to_app_dir, item, \"settings.py\"])\n ))\n\n _app=getattr(xdj.apps, item)\n if not hasattr(_app,\"settings\"):\n setattr(_app,\"settings\",app_settings)\n\n sys.path.append(controller_dir)\n files = os.listdir(controller_dir)\n for file in files:\n\n import inspect\n controller_file = os.sep.join([controller_dir,file])\n extension = os.path.splitext(controller_file)[1][1:]\n if (not p2n3.has_key(__controllert_url_build_cache__,controller_file)) and extension==\"py\":\n m = None\n try:\n m = imp.load_source(\"{0}.{1}\".format(item,file.split('.')[0]),controller_file)\n except SyntaxError as ex:\n raise ex\n except Exception as ex:\n from xdj.errors import LoadControllerError\n raise LoadControllerError(ex.message,file,ex.args)\n\n if __controllers__.__len__()>0:\n controller_instance=__controllers__[__controllers__.__len__()-1].instance\n class_file = inspect.getfile(controller_instance.__class__)\n extension_class = os.path.splitext(class_file)[1][1:]\n class_file = class_file[0:class_file.__len__() - extension_class.__len__()]\n controller_file_class = controller_file[0:controller_file.__len__() - extension.__len__()]\n if class_file == controller_file_class:\n __controllers__[__controllers__.__len__() - 1].app_dir = os.sep.join([path_to_app_dir,item])\n controller_instance.app_dir = os.sep.join([path_to_app_dir,item])\n controller_instance.host_dir = app_settings.host_dir\n controller_instance.app_name = app_settings.app_name\n controller_instance.on_authenticate = app_settings.on_authenticate\n controller_instance.rel_login_url = app_settings.rel_login_url\n controller_instance.settings = app_settings\n controller_instance.param_names = __controllers__[__controllers__.__len__()-1].params\n print (controller_instance.url)\n print (inspect.getfile(controller_instance.__class__))\n\n from . controllers import Res\n controller_instance.res = Res(app_settings.on_get_language_resource_item,controller_instance.app_name,controller_instance.template)\n else:\n print (\"uncontroller file {0}\".format(\n controller_file\n ))\n __controllert_url_build_cache__.update({\n controller_file:controller_instance\n })\n\n \"\"\"\n # self.controllerClass()\n if self.instance.app_name==None:\n raise Exception(\"{0} do not have 'app_name'\".format(self.controllerClass))\n if self.instance.app_dir==None:\n raise Exception(\"{0} do not have 'app_dir'\".format(self.controllerClass))\n \"\"\"\n # x=1\n\n return create(urlpatterns)\n\nclass dobject(object):\n def __init__(self,*args,**kwargs):\n def feed_data(data):\n if isinstance(data,dobject):\n data =data.__dict__\n for k,v in data.items():\n if isinstance(v,dict):\n self.__dict__.update({\n k:dobject(v)\n })\n elif isinstance(v,dobject):\n self.__dict__.update({\n k: v\n })\n\n elif isinstance(v,list):\n lst =[]\n for item in v:\n lst.append(dobject(item))\n self.__dict__.update({\n k:lst\n })\n else:\n self.__dict__.update({\n k:v\n })\n if args.__len__()==0:\n feed_data(kwargs)\n else:\n feed_data(args[0])\n\ndef apply_settings():\n \"\"\"\n https://openedx.atlassian.net/wiki/spaces/AC/pages/34734726/edX+Feature+Flags\n :return:\n \"\"\"\n from django.conf import settings\n setattr(settings,\"USE_DJANGO_PIPELINE\",True)\n \"\"\"\n http://django-pipeline.readthedocs.org/ – whatever version we specify in our requirements.txt\n \"\"\"\n setattr(settings,\"DISPLAY_DEBUG_INFO_TO_STAFF\",True)\n \"\"\"For large courses this slows down courseware access for staff.\"\"\"\n setattr(settings,\"MILESTONES_APP\",True)\n\ndef load_config():\n import json\n import os\n import sys\n filet_of_data_config = os.sep.join([os.path.dirname(__file__),\"config\",\"data.json\"])\n with open( filet_of_data_config,'r') as data_file:\n from django.conf import settings\n data = json.loads(data_file.read())\n settings.DATABASES['default']['ENGINE'] = data[\"sql\"][\"engine\"]\n settings.DATABASES['default']['NAME'] = data[\"sql\"][\"name\"]\n settings.DATABASES['default']['PORT'] = data[\"sql\"][\"port\"]\n settings.DATABASES['default']['HOST'] = data[\"sql\"][\"host\"]\n settings.DATABASES['default']['USER'] = data[\"sql\"][\"user\"]\n settings.DATABASES['default']['PASSWORD'] = data[\"sql\"][\"password\"]\n\n settings.DATABASES[\"read_replica\"]['ENGINE'] = data[\"sql\"][\"engine\"]\n settings.DATABASES[\"read_replica\"]['NAME'] = data[\"sql\"][\"name\"]\n settings.DATABASES[\"read_replica\"]['PORT'] = data[\"sql\"][\"port\"]\n settings.DATABASES[\"read_replica\"]['HOST'] = data[\"sql\"][\"host\"]\n settings.DATABASES[\"read_replica\"]['USER'] = data[\"sql\"][\"user\"]\n settings.DATABASES[\"read_replica\"]['PASSWORD'] = data[\"sql\"][\"password\"]\n\n settings.DATABASES['student_module_history']['ENGINE'] = data[\"sql\"][\"engine\"]\n settings.DATABASES['student_module_history']['NAME'] = data[\"sql\"][\"name\"]\n settings.DATABASES['student_module_history']['PORT'] = data[\"sql\"][\"port\"]\n settings.DATABASES['student_module_history']['HOST'] = data[\"sql\"][\"host\"]\n settings.DATABASES['student_module_history']['USER'] = data[\"sql\"][\"user\"]\n settings.DATABASES['student_module_history']['PASSWORD'] = data[\"sql\"][\"password\"]\n\n settings.CONTENTSTORE[\"DOC_STORE_CONFIG\"][\"db\"] = data[\"mongo\"][\"name\"]\n settings.CONTENTSTORE[\"DOC_STORE_CONFIG\"][\"host\"] = data[\"mongo\"][\"host\"]\n settings.CONTENTSTORE[\"DOC_STORE_CONFIG\"][\"user\"] = data[\"mongo\"][\"user\"]\n settings.CONTENTSTORE[\"DOC_STORE_CONFIG\"][\"password\"] = data[\"mongo\"][\"password\"]\n settings.CONTENTSTORE[\"DOC_STORE_CONFIG\"][\"port\"] = data[\"mongo\"][\"port\"]\n\n settings.CONTENTSTORE[\"OPTIONS\"][\"db\"] = data[\"mongo\"][\"name\"]\n settings.CONTENTSTORE[\"OPTIONS\"][\"host\"] = data[\"mongo\"][\"host\"]\n settings.CONTENTSTORE[\"OPTIONS\"][\"user\"] = data[\"mongo\"][\"user\"]\n settings.CONTENTSTORE[\"OPTIONS\"][\"password\"] = data[\"mongo\"][\"password\"]\n settings.CONTENTSTORE[\"OPTIONS\"][\"port\"] = data[\"mongo\"][\"port\"]\n\n settings.DOC_STORE_CONFIG[\"db\"] = data[\"mongo\"][\"name\"]\n settings.DOC_STORE_CONFIG[\"host\"] = data[\"mongo\"][\"host\"]\n settings.DOC_STORE_CONFIG[\"user\"] = data[\"mongo\"][\"user\"]\n settings.DOC_STORE_CONFIG[\"password\"] = data[\"mongo\"][\"password\"]\n settings.DOC_STORE_CONFIG[\"port\"] = data[\"mongo\"][\"port\"]\n\n settings.MODULESTORE[\"default\"][\"OPTIONS\"][\"stores\"][0][\"DOC_STORE_CONFIG\"][\"db\"] = data[\"mongo\"][\"name\"]\n settings.MODULESTORE[\"default\"][\"OPTIONS\"][\"stores\"][0][\"DOC_STORE_CONFIG\"][\"host\"] = data[\"mongo\"][\"host\"]\n settings.MODULESTORE[\"default\"][\"OPTIONS\"][\"stores\"][0][\"DOC_STORE_CONFIG\"][\"user\"] = data[\"mongo\"][\"user\"]\n settings.MODULESTORE[\"default\"][\"OPTIONS\"][\"stores\"][0][\"DOC_STORE_CONFIG\"][\"password\"] = data[\"mongo\"][\"password\"]\n settings.MODULESTORE[\"default\"][\"OPTIONS\"][\"stores\"][0][\"DOC_STORE_CONFIG\"][\"port\"] = data[\"mongo\"][\"port\"]\n\n settings.MODULESTORE[\"default\"][\"OPTIONS\"][\"stores\"][1][\"DOC_STORE_CONFIG\"][\"db\"] = data[\"mongo\"][\"name\"]\n settings.MODULESTORE[\"default\"][\"OPTIONS\"][\"stores\"][1][\"DOC_STORE_CONFIG\"][\"host\"] = data[\"mongo\"][\"host\"]\n settings.MODULESTORE[\"default\"][\"OPTIONS\"][\"stores\"][1][\"DOC_STORE_CONFIG\"][\"user\"] = data[\"mongo\"][\"user\"]\n settings.MODULESTORE[\"default\"][\"OPTIONS\"][\"stores\"][1][\"DOC_STORE_CONFIG\"][\"password\"] = data[\"mongo\"][\"password\"]\n settings.MODULESTORE[\"default\"][\"OPTIONS\"][\"stores\"][1][\"DOC_STORE_CONFIG\"][\"port\"] = data[\"mongo\"][\"port\"]\n\ndef load_settings(for_lms):\n from django.conf import settings\n import json\n import os\n import sys\n import logging\n logger = logging.getLogger(__name__)\n logger.info(\"load settings\")\n\n filet_of_settings_config = os.sep.join([os.path.dirname(__file__), \"config\", \"settings.json\"])\n with open(filet_of_settings_config, 'r') as data_file:\n\n data = json.loads(data_file.read())\n logger.info(data)\n for k,v in data.items():\n setattr(settings,k,v)\n if data.has_key(\"MAKO_TEMPLATE_DIRS_BASE\"):\n settings.TEMPLATES[0]['DIRS'] = data[\"MAKO_TEMPLATE_DIRS_BASE\"]\n settings.TEMPLATES[1]['DIRS'] = data[\"MAKO_TEMPLATE_DIRS_BASE\"]\n\n import path\n if data.has_key(\"STATIC_ROOT\"):\n settings.STATIC_ROOT = path.path(data[\"STATIC_ROOT\"])\n p = [x for x in settings.STATICFILES_DIRS if\n x.__str__()[x.__str__().__len__() - \"/lms/static\".__len__():] not in [\"/lms/static\", \"/cms/static\"]]\n # p.append(settings.STATIC_ROOT)\n settings.STATICFILES_DIRS = p\n if for_lms:\n if hasattr(settings,\"LMS_TEMPLATE\"):\n x = os.sep.join([settings.REPO_ROOT, \"lms\",\"templates\"])\n settings.MAKO_TEMPLATE_DIRS_BASE = [p for p in settings.MAKO_TEMPLATE_DIRS_BASE if p.__str__() != x]\n settings.MAKO_TEMPLATE_DIRS_BASE.append(settings.LMS_TEMPLATE)\n settings.DEFAULT_TEMPLATE_ENGINE_DIRS=settings.MAKO_TEMPLATE_DIRS_BASE\n settings.TEMPLATES[0]['DIRS'] = settings.MAKO_TEMPLATE_DIRS_BASE\n settings.TEMPLATES[1]['DIRS'] = settings.MAKO_TEMPLATE_DIRS_BASE\n else:\n if hasattr(settings,\"CMS_TEMPLATE\"):\n x = os.sep.join([settings.REPO_ROOT, \"cms\", \"templates\"])\n settings.MAKO_TEMPLATE_DIRS_BASE = [p for p in settings.MAKO_TEMPLATE_DIRS_BASE if p.__str__() != x]\n settings.MAKO_TEMPLATE_DIRS_BASE.append(settings.CMS_TEMPLATE)\n settings.DEFAULT_TEMPLATE_ENGINE_DIRS=settings.MAKO_TEMPLATE_DIRS_BASE\n settings.TEMPLATES[0]['DIRS'] = settings.MAKO_TEMPLATE_DIRS_BASE\n settings.TEMPLATES[1]['DIRS'] = settings.MAKO_TEMPLATE_DIRS_BASE\n settings.WEBPACK_LOADER[\"DEFAULT\"][\"STATS_FILE\"] = settings.WEBPACK_LOADER[\"DEFAULT\"][\"STATS_FILE\"].replace(\",/\",\n \"/\")\n\n\n\n return None\n\ndef load_email_settings():\n try:\n import json\n import os\n import sys\n filet_of_settings_config = os.sep.join([os.path.dirname(__file__), \"config\", \"email.json\"])\n with open(filet_of_settings_config, 'r') as data_file:\n from django.conf import settings\n data = json.loads(data_file.read())\n settings.EMAIL_HOST = data['host']\n settings.EMAIL_HOST_USER = data['user']\n settings.EMAIL_HOST_PASSWORD = data['password']\n settings.EMAIL_USE_TLS = data[\"tsl\"]\n settings.EMAIL_PORT = data[\"port\"]\n settings.EMAIL_FILE_PATH = data[\"path\"]\n settings.SERVER_EMAIL = data[\"email\"]\n settings.DEFAULT_FROM_EMAIL =data[\"email\"]\n settings.CONTACT_EMAIL = data[\"contact_email\"]\n settings.API_ACCESS_FROM_EMAIL = data[\"email\"]\n settings.API_ACCESS_MANAGER_EMAIL = data[\"email\"]\n settings.BUGS_EMAIL = data[\"email\"]\n settings.BULK_EMAIL_DEFAULT_FROM_EMAIL = data[\"email\"]\n settings.FEEDBACK_SUBMISSION_EMAIL =data[\"email\"]\n except Exception as ex:\n from xdj.errors import LoadConfigError\n raise LoadConfigError(filet_of_settings_config,ex.message,ex)\n\n\n\ndef load_forum_config():\n import json\n import os\n import sys\n filet_of_settings_config = os.sep.join([os.path.dirname(__file__), \"config\", \"forum.json\"])\n with open(filet_of_settings_config, 'r') as data_file:\n from django.conf import settings\n data = json.loads(data_file.read())\n \"\"\"\n \"COMMENTS_SERVICE_KEY\": \"9198a36ca5349defcc6ecc1d3235390bd47a\",\n \"COMMENTS_SERVICE_URL\": \"http://localhost:18080\"\n \"\"\"\n settings.COMMENTS_SERVICE_KEY = data['key']\n settings.COMMENTS_SERVICE_URL = data['url']\n\ndef load_feature_settings():\n import json\n import os\n import sys\n filet_of_settings_config = os.sep.join([os.path.dirname(__file__), \"config\", \"feature.json\"])\n with open(filet_of_settings_config, 'r') as data_file:\n from django.conf import settings\n data = json.loads(data_file.read())\n for k,v in data.items():\n settings.FEATURES.update({\n k:v\n })\n\ndef load_moddels():\n import json\n import os\n filet_of_settings_config = os.sep.join([os.path.dirname(__file__), \"config\", \"models.json\"])\n with open(filet_of_settings_config, 'r') as data_file:\n from django.conf import settings\n data = json.loads(data_file.read())\n for item in data:\n if settings.INSTALLED_APPS.count(item) ==0:\n settings.INSTALLED_APPS.append(item)\n\n\ndef load_elastic_search_config():\n import json\n import os\n import sys\n filet_of_settings_config = os.sep.join([os.path.dirname(__file__), \"config\", \"elastic_search.json\"])\n with open(filet_of_settings_config, 'r') as data_file:\n from django.conf import settings\n data = json.loads(data_file.read())\n settings.ELASTIC_SEARCH_CONFIG=data\n\ndef debugTemplate(x):\n from xdj.middle_ware import GlobalRequestMiddleware\n request = GlobalRequestMiddleware.get_current_request()\n pass\ndef apply_context(context):\n def res(key,value=None):\n if value == None:\n value = key\n\n\n return value\n # context._data.update({\"res\": res})\n # context.res = res\n context.res = res\n # context._data[\"res\"] = res\n # context[\"self\"].context._data[\"res\"] = res\n\n\nclass Handler(object):\n def from_json(self,txt):\n from xdj import JSON\n return JSON.from_json(txt)\n\n def __init__(self,model):\n self.model = model\n\n\ndef clear_language_cache():\n from xdj.controllers import clear_language_cache\n clear_language_cache()\n\n\ndef load_urls():\n from django.conf import settings\n import os\n settings.ROOT_URLCONF = ()\n apps_dirs = os.sep.join([os.path.dirname(os.path.dirname(__file__)),\"xdj_apps\"])\n ret_url = load_apps(apps_dirs,[],True)\n return ret_url\n\n\n\n\n\n\n","sub_path":"xdj/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":28150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"620041807","text":"import torch\nimport torchnet as tnt\nimport numpy as np\n\nfrom sklearn.metrics import confusion_matrix\nimport os\nimport json\nimport pickle as pkl\nimport argparse\nimport pprint\nfrom tqdm import tqdm\nfrom models.stclassifier import PseTae, PseLTae, PseGru, PseTempCNN, ClassifierOnly\nfrom learning.loader import get_test_loaders, get_embedding_loaders, classif_only_loader, get_multi_years_loaders\nfrom learning.output import prepare_output, checkpoint, save_pred, save_embedding, save_results, save_test_mode_results,\\\n overall_performance_by_year, overall_performance\nfrom dataset import PixelSetData, PixelSetData_preloaded, PixelSetData_classifier_only\n\nfrom learning.focal_loss import FocalLoss\nfrom learning.weight_init import weight_init\nfrom learning.metrics import mIou\n\n\n\ndef train_epoch(model, optimizer, criterion, data_loader, device, config):\n acc_meter = tnt.meter.ClassErrorMeter(accuracy=True)\n loss_meter = tnt.meter.AverageValueMeter()\n y_true = []\n y_pred = []\n\n for i, (data, y) in enumerate(data_loader):\n y_true.extend(list(map(int, y)))\n\n x = recursive_todevice(data, device)\n y = y.to(device)\n\n optimizer.zero_grad()\n\n out = model(x)\n loss = criterion(out, y.long())\n loss.backward()\n optimizer.step()\n\n pred = out.detach()\n y_p = pred.argmax(dim=1).cpu().numpy()\n y_pred.extend(list(y_p))\n acc_meter.add(pred, y)\n loss_meter.add(loss.item())\n\n if (i + 1) % config['display_step'] == 1:\n print('Step [{}/{}], Loss: {:.4f}, Acc : {:.2f}, IoU : {:.4f}'.format(i + 1, len(data_loader), loss_meter.value()[0],\n acc_meter.value()[0], mIou(y_true, y_pred, config['num_classes'])))\n\n epoch_metrics = {'train_loss': loss_meter.value()[0],\n 'train_accuracy': acc_meter.value()[0],\n 'train_IoU': mIou(y_true, y_pred, n_classes=config['num_classes'])}\n\n return epoch_metrics\n\n\ndef evaluation(model, criterion, loader, device, config, mode='val', fold=None):\n y_true = []\n y_pred = []\n\n acc_meter = tnt.meter.ClassErrorMeter(accuracy=True)\n loss_meter = tnt.meter.AverageValueMeter()\n pred = {}\n emb = {}\n for (data, y) in tqdm(loader):\n y_true.extend(list(map(int, y)))\n x = recursive_todevice(data, device)\n y = y.to(device)\n\n with torch.no_grad():\n if config['save_embedding'] and mode == 'test':\n prediction, embedding = model(x)\n for i, id in enumerate(data['pid']):\n save_embedding(embedding[i].tolist(), id, fold, config)\n else:\n prediction = model(x)\n\n if (config['save_pred']):\n for i, id in enumerate(data['pid']):\n exp_pred = torch.exp(prediction[i])\n pred[id] = torch.div(exp_pred, torch.sum(exp_pred)).tolist()\n\n loss = criterion(prediction, y)\n\n acc_meter.add(prediction, y)\n loss_meter.add(loss.item())\n y_p = prediction.argmax(dim=1).cpu().numpy()\n y_pred.extend(list(y_p))\n\n metrics = {'{}_accuracy'.format(mode): acc_meter.value()[0],\n '{}_loss'.format(mode): loss_meter.value()[0],\n '{}_IoU'.format(mode): mIou(y_true, y_pred, config['num_classes'])}\n\n if mode == 'val':\n return metrics\n\n if mode == 'test':\n if config['save_pred'] :\n save_pred(pred, fold, config)\n\n return metrics, confusion_matrix(y_true, y_pred, labels=list(range(config['num_classes'])))\n\n\n\ndef recursive_todevice(x, device):\n if type(x).__name__ == 'str':\n return x\n elif isinstance(x, torch.Tensor):\n return x.to(device)\n elif isinstance(x, dict):\n return {k: recursive_todevice(v, device) for k, v in x.items()}\n else:\n return [recursive_todevice(c, device) for c in x]\n\n\n\n\ndef model_definition(config, dt, test=False, year=None):\n if test:\n lms = config['sly'][config['year'][year]]\n else:\n lms = config['lms']\n\n if config['tae']:\n model_config = dict(input_dim=config['input_dim'], mlp1=config['mlp1'], pooling=config['pooling'],\n mlp2=config['mlp2'], n_head=config['n_head'], d_k=config['d_k'], mlp3=config['mlp3'],\n dropout=config['dropout'], T=config['T'], len_max_seq=lms,\n positions=dt.date_positions if config['positions'] == 'bespoke' else None,\n mlp4=config['mlp4'], d_model=config['d_model'], with_extra=False, extra_size=None,\n with_temp_feat=config['tempfeat'])\n if config['geomfeat']:\n model_config.update(with_extra=True, extra_size=4)\n\n\n model = PseTae(**model_config)\n\n elif config['gru']:\n model_config = dict(input_dim=config['input_dim'], mlp1=config['mlp1'], pooling=config['pooling'],\n mlp2=config['mlp2'], hidden_dim=config['hidden_dim'],\n positions=dt.date_positions if config['positions'] == 'bespoke' else None,\n mlp4=config['mlp4'], with_extra=False, extra_size=None,\n with_temp_feat=config['tempfeat'])\n if config['geomfeat']:\n model_config.update(with_extra=True, extra_size=4)\n\n model = PseGru(**model_config)\n\n elif config['tcnn']:\n model_config = dict(input_dim=config['input_dim'], mlp1=config['mlp1'], pooling=config['pooling'],\n mlp2=config['mlp2'], nker=config['nker'], mlp3=config['mlp3'],\n positions=dt.date_positions if config['positions'] == 'bespoke' else None,\n mlp4=config['mlp4'], with_extra=False, extra_size=None,\n with_temp_feat=config['tempfeat'])\n if config['geomfeat']:\n model_config.update(with_extra=True, extra_size=4)\n\n model = PseTempCNN(**model_config)\n elif config['classifier_only']:\n model_config = dict(mlp4=config['mlp4'])\n model = ClassifierOnly(**model_config)\n\n else:\n model_config = dict(input_dim=config['input_dim'], mlp1=config['mlp1'], pooling=config['pooling'],\n mlp2=config['mlp2'], n_head=config['n_head'], d_k=config['d_k'], mlp3=config['mlp3'],\n dropout=config['dropout'], T=config['T'], len_max_seq=lms,\n mlp4=config['mlp4'], d_model=config['d_model'], with_extra=False, extra_size=None,\n with_temp_feat=config['tempfeat'], return_embedding=config['save_embedding'])\n if config['geomfeat']:\n model_config.update(with_extra=True, extra_size=4)\n\n\n model = PseLTae(**model_config)\n return model, model_config\n\ndef test_model(model, loader, config, device, path ,fold):\n\n config['N_params'] = model.param_ratio()\n with open(os.path.join('conf.json'), 'w') as file:\n file.write(json.dumps(config, indent=4))\n model = model.to(device)\n model.apply(weight_init)\n criterion = FocalLoss(config['gamma'])\n new_state_dict = torch.load(os.path.join(path,'Fold_{}'.format(fold), 'model.pth.tar'))\n model_dict = {k: v for k, v in model.state_dict().items() if k != 'temporal_encoder.position_enc.weight'}\n model_dict_copy = {k: v for k, v in model.state_dict().items()}\n compatible_dict = {k: v for k, v in new_state_dict['state_dict'].items() if k in model_dict}\n model_dict_copy.update(compatible_dict)\n model.load_state_dict(model_dict_copy)\n model.eval()\n test_metrics, conf_mat = evaluation(model, criterion, loader, device=device, mode='test', config=config, fold=fold)\n \n print('Loss {:.4f}, Acc {:.2f}, IoU {:.4f}'.format(test_metrics['test_loss'], test_metrics['test_accuracy'],\n test_metrics['test_IoU']))\n return test_metrics, conf_mat, config\n\n\ndef main(config):\n np.random.seed(config['rdm_seed'])\n torch.manual_seed(config['rdm_seed'])\n prepare_output(config)\n\n mean_std = pkl.load(open(config['dataset_folder'] + '/normvals_tot.pkl', 'rb'))\n extra = 'geomfeat' if config['geomfeat'] else None\n extra_temp = 'tempfeat' if config['tempfeat'] else None\n\n # We only consider the subset of classes with more than 100 samples in the S2-Agri dataset\n # subset = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]\n subset = None\n if config['preload']:\n dt = []\n for year in config['year']:\n dt.append(PixelSetData_preloaded(config['dataset_folder'], labels='CODE9_' + year, npixel=config['npixel'],\n sub_classes=subset,\n norm=mean_std,\n extra_feature=extra))\n elif config['classifier_only']:\n dt = [[] for fold in range(config['kfold'])]\n for fold in range(0, config['kfold']):\n for year in config['year']:\n\n dt[fold].append(PixelSetData_classifier_only(config['dataset_folder'], labels='CODE9_' + year,\n sub_classes=subset, year=year, years_list=config['year'],\n num_classes=config['num_classes'], fold=fold,\n return_id=True))\n\n else:\n dt = []\n for year in config['year']:\n dt.append(PixelSetData(config['dataset_folder'], labels='CODE9_' + year, npixel=config['npixel'],\n sub_classes=subset, norm=mean_std,\n extra_feature=extra, extra_feature_temp=extra_temp, year=year,\n years_list=config['year'], num_classes=config['num_classes'], return_id=True))\n\n device = torch.device(config['device'])\n\n\n if config['tempfeat']:\n config['mlp4'][0] = config['mlp4'][0] + config['num_classes']\n\n if config['classifier_only']:\n for fold in range(0, config['kfold']):\n np.random.seed(config['rdm_seed'])\n torch.manual_seed(config['rdm_seed'])\n loader, dt[fold] = classif_only_loader(dt[fold], config['kfold'], fold, config)\n print('Starting Fold {}'.format(fold + 1))\n print('Train {}, Val {}, Test {}'.format(len(loader[0]), len(loader[1]), len(loader[2][0])))\n model, model_config = model_definition(config, dt)\n config['N_params'] = model.param_ratio()\n with open(os.path.join(config['res_dir'], 'conf.json'), 'w') as file:\n file.write(json.dumps(config, indent=4))\n\n model = model.to(device)\n model.apply(weight_init)\n optimizer = torch.optim.Adam(model.parameters())\n criterion = FocalLoss(config['gamma'])\n\n trainlog = {}\n\n best_mIoU = 0\n for epoch in range(1, config['epochs'] + 1):\n print('EPOCH {}/{}'.format(epoch, config['epochs']))\n\n model.train()\n train_metrics = train_epoch(model, optimizer, criterion, loader[0], device=device, config=config)\n print('Validation . . . ')\n model.eval()\n val_metrics = evaluation(model, criterion, loader[1], device=device, config=config, mode='val')\n\n print(\n 'Loss {:.4f}, Acc {:.2f}, IoU {:.4f}'.format(val_metrics['val_loss'], val_metrics['val_accuracy'],\n val_metrics['val_IoU']))\n trainlog[epoch] = {**train_metrics, **val_metrics}\n checkpoint(fold + 1, trainlog, config)\n\n if val_metrics['val_IoU'] >= best_mIoU:\n best_mIoU = val_metrics['val_IoU']\n torch.save({'epoch': epoch, 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict()},\n os.path.join(config['res_dir'], 'Fold_{}'.format(fold + 1), 'model.pth.tar'))\n\n print('Testing best epoch . . .')\n\n for year, i in enumerate(loader[2]):\n print(\"Année: {} \".format(config['year'][year]))\n\n model_test, model_test_config = model_definition(config, dt, test=True, year=year)\n path = config['res_dir']\n\n test_metrics, conf_mat, config = test_model(model_test, i, config, device, path, fold + 1)\n\n save_results(fold + 1, test_metrics, conf_mat, config, year)\n\n for year in config['year']:\n overall_performance_by_year(config, year)\n overall_performance(config)\n\n\n\n\n\n elif not config['test_mode']:\n\n loaders, dt = get_multi_years_loaders(dt, config['kfold'], config)\n for fold, (train_loader, val_loader, test_loader) in enumerate(loaders):\n print('Starting Fold {}'.format(fold + 1))\n print('Train {}, Val {}, Test {}'.format(len(train_loader), len(val_loader), len(test_loader[0])))\n model, model_config = model_definition(config, dt)\n config['N_params'] = model.param_ratio()\n with open(os.path.join(config['res_dir'], 'conf.json'), 'w') as file:\n file.write(json.dumps(config, indent=4))\n\n model = model.to(device)\n model.apply(weight_init)\n optimizer = torch.optim.Adam(model.parameters())\n criterion = FocalLoss(config['gamma'])\n\n trainlog = {}\n\n best_mIoU = 0\n for epoch in range(1, config['epochs'] + 1):\n print('EPOCH {}/{}'.format(epoch, config['epochs']))\n\n model.train()\n train_metrics = train_epoch(model, optimizer, criterion, train_loader, device=device, config=config)\n print('Validation . . . ')\n model.eval()\n val_metrics = evaluation(model, criterion, val_loader, device=device, config=config, mode='val')\n\n print(\n 'Loss {:.4f}, Acc {:.2f}, IoU {:.4f}'.format(val_metrics['val_loss'], val_metrics['val_accuracy'],\n val_metrics['val_IoU']))\n trainlog[epoch] = {**train_metrics, **val_metrics}\n checkpoint(fold + 1, trainlog, config)\n\n if val_metrics['val_IoU'] >= best_mIoU:\n best_mIoU = val_metrics['val_IoU']\n torch.save({'epoch': epoch, 'state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict()},\n os.path.join(config['res_dir'], 'Fold_{}'.format(fold + 1), 'model.pth.tar'))\n\n print('Testing best epoch . . .')\n\n for year, i in enumerate(test_loader):\n print(\"Année: {} \".format(config['year'][year]))\n\n model_test, model_test_config = model_definition(config, dt, test=True, year=year)\n path = config['res_dir']\n \n test_metrics, conf_mat, config = test_model(model_test, i, config, device, path, fold+1)\n\n save_results(fold + 1, test_metrics, conf_mat, config, year)\n\n # 1 fold (no cross validation)\n # break\n for year in config['year']:\n overall_performance_by_year(config, year)\n overall_performance(config)\n\n else:\n if config['save_embedding']:\n loaders = get_embedding_loaders(dt, config)\n for fold in range(config['kfold']):\n print(\"Fold: {} \".format(fold + 1))\n for year, loader in enumerate(loaders):\n print(\"Année: {} \".format(config['year'][year]))\n model, model_config = model_definition(config, dt, test=True, year=year)\n path = config['loaded_model']\n test_metrics, conf_mat, config = test_model(model, loader, config, device, path, fold+1)\n save_test_mode_results(test_metrics, conf_mat, config, config['year'][year], fold+1)\n\n else:\n loaders = get_test_loaders(dt, config['kfold'],config)\n for fold, loader_fold in enumerate(loaders):\n print(\"Fold: {} \".format(fold + 1))\n for year, loader in enumerate(loader_fold):\n print(\"Année: {} \".format(config['year'][year]))\n model, model_config = model_definition(config, dt, test=True, year=year)\n path = config['loaded_model']\n test_metrics, conf_mat, config = test_model(model, loader, config, device, path, fold+1)\n save_test_mode_results(test_metrics, conf_mat, config, config['year'][year], fold+1)\n for year in config['year']:\n overall_performance_by_year(config, year)\n overall_performance(config)\n\n\n\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n\n # Set-up parameters\n parser.add_argument('--dataset_folder', default='/home/FQuinton/Bureau/data_embedding2', type=str,\n help='Path to the folder where the results are saved.')\n parser.add_argument('--year', default=['2018','2019','2020'], type=str,\n help='The year of the data you want to use')\n parser.add_argument('--res_dir', default='./results/global_embedding', help='Path to the folder where the results should be stored')\n parser.add_argument('--num_workers', default=8, type=int, help='Number of data loading workers')\n parser.add_argument('--rdm_seed', default=1, type=int, help='Random seed')\n parser.add_argument('--device', default='cuda', type=str,\n help='Name of device to use for tensor computations (cuda/cpu)')\n parser.add_argument('--display_step', default=50, type=int,\n help='Interval in batches between display of training metrics')\n parser.add_argument('--preload', dest='preload', action='store_true',\n help='If specified, the whole dataset is loaded to RAM at initialization')\n parser.set_defaults(preload=False)\n\n #Parameters relatives to test\n parser.add_argument('--test_mode', default=False, type=bool,\n help='Load a pre-trained model and test on the whole data set')\n parser.add_argument('--loaded_model',\n default='/home/FQuinton/Bureau/lightweight-temporal-attention-pytorch/models_saved/global',\n type=str,\n help='Path to the pre-trained model')\n parser.add_argument('--save_pred', default=False, type=bool,\n help='Save predictions by parcel during test')\n parser.add_argument('--save_embedding', default=False, type=bool,\n help='Save embeddings by parcel during test')\n parser.add_argument('--save_emb_dir', default='/home/FQuinton/Bureau/test',\n help='Path to the folder where the results should be stored')\n\n # Training parameters\n parser.add_argument('--kfold', default=5, type=int, help='Number of folds for cross validation')\n parser.add_argument('--epochs', default=30, type=int, help='Number of epochs per fold')\n parser.add_argument('--batch_size', default=128, type=int, help='Batch size')\n parser.add_argument('--lr', default=0.001, type=float, help='Learning rate')\n parser.add_argument('--gamma', default=1, type=float, help='Gamma parameter of the focal loss')\n parser.add_argument('--npixel', default=64, type=int, help='Number of pixels to sample from the input images')\n\n # Architecture Hyperparameters\n ## PSE\n parser.add_argument('--input_dim', default=10, type=int, help='Number of channels of input images')\n parser.add_argument('--mlp1', default='[10,32,64]', type=str, help='Number of neurons in the layers of MLP1')\n parser.add_argument('--pooling', default='mean_std', type=str, help='Pixel-embeddings pooling strategy')\n parser.add_argument('--mlp2', default='[132,128]', type=str, help='Number of neurons in the layers of MLP2')\n parser.add_argument('--geomfeat', default=1, type=int,\n help='If 1 the precomputed geometrical features (f) are used in the PSE.')\n\n ## L-TAE\n parser.add_argument('--n_head', default=16, type=int, help='Number of attention heads')\n parser.add_argument('--d_k', default=8, type=int, help='Dimension of the key and query vectors')\n parser.add_argument('--mlp3', default='[256,128]', type=str, help='Number of neurons in the layers of MLP3')\n parser.add_argument('--T', default=1000, type=int, help='Maximum period for the positional encoding')\n parser.add_argument('--positions', default='bespoke', type=str,\n help='Positions to use for the positional encoding (bespoke / order)')\n parser.add_argument('--lms', default=36, type=int,\n help='Maximum sequence length for positional encoding (only necessary if positions == order)')\n parser.add_argument('--sly', default={'2018': 36, '2019': 27, '2020': 29},\n help='Sequence length by year for positional encoding (only necessary if positions == order)')\n parser.add_argument('--dropout', default=0.2, type=float, help='Dropout probability')\n parser.add_argument('--d_model', default=256, type=int,\n help=\"size of the embeddings (E), if input vectors are of a different size, a linear layer is used to project them to a d_model-dimensional space\"\n )\n\n\n\n ## Classifier\n parser.add_argument('--tempfeat', default=False, type=bool,\n help='If true the past years labels are used before classification PSE.')\n parser.add_argument('--num_classes', default=20, type=int, help='Number of classes')\n parser.add_argument('--mlp4', default='[256, 128, 64, 20]', type=str, help='Number of neurons in the layers of MLP4')\n\n ## Other methods (use one of the flags tae/gru/tcnn to train respectively a TAE, GRU or TempCNN instead of an L-TAE)\n ## see paper appendix for hyperparameters\n parser.add_argument('--tae', dest='tae', action='store_true',\n help=\"Temporal Attention Encoder for temporal encoding\")\n\n parser.add_argument('--gru', dest='gru', action='store_true', help=\"Gated Recurent Unit for temporal encoding\")\n parser.add_argument('--hidden_dim', default=156, type=int, help=\"Hidden state size\")\n\n parser.add_argument('--tcnn', dest='tcnn', action='store_true', help=\"Temporal Convolutions for temporal encoding\")\n parser.add_argument('--nker', default='[32,32,128]', type=str, help=\"Number of successive convolutional kernels \")\n parser.add_argument('--classifier_only', default=True, type=bool, help=\"Only train the classifier\")\n\n parser.set_defaults(gru=False, tcnn=False, tae=False)\n\n config = parser.parse_args()\n config = vars(config)\n for k, v in config.items():\n if 'mlp' in k or k == 'nker':\n v = v.replace('[', '')\n v = v.replace(']', '')\n config[k] = list(map(int, v.split(',')))\n\n pprint.pprint(config)\n main(config)\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":23453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"374678446","text":"#\n# @lc app=leetcode id=205 lang=python3\n#\n# [205] Isomorphic Strings\n#\n\n\n# @lc code=start\n\n\nclass Solution:\n def transformString(self, s: str) -> str:\n index_mapping = {}\n new_str = []\n\n for i, c in enumerate(s):\n if c not in index_mapping:\n index_mapping[c] = i\n new_str.append(str(index_mapping[c]))\n\n return \" \".join(new_str)\n\n def isIsomorphic(self, s: str, t: str) -> bool:\n return self.transformString(s) == self.transformString(t)\n # @lc code=end\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n testcases = [\n (\"egg\", \"add\", True),\n (\"bbbaaaba\", \"aaabbbba\", False)\n ]\n for i, (s, t, ans) in enumerate(testcases):\n\n print(\"Test case: \", i)\n print(\"answer: \", solution.isIsomorphic(s, t))\n print(\"expected: \", ans)\n print(\"===========================\")\n","sub_path":"leetcode/205.isomorphic-strings.py","file_name":"205.isomorphic-strings.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"324270541","text":"# -*- coding: utf-8 -*-\n\n__version__ = '0.1.3'\n\nimport functools\n\nimport six\nfrom six.moves import http_client as http\n\nimport flask\nfrom flask.views import http_method_funcs\n\nimport werkzeug\nfrom webargs import flaskparser\n\nfrom flask_apispec import utils\n\ndef identity(value):\n return value\n\ndef unpack(resp):\n resp = resp if isinstance(resp, tuple) else (resp, )\n return resp + (None, ) * (3 - len(resp))\n\nclass Wrapper(object):\n \"\"\"Apply annotations to a view function.\n\n :param func: View function to wrap\n :param instance: Optional instance or parent\n \"\"\"\n def __init__(self, func, instance=None):\n self.func = func\n self.instance = instance\n\n def __call__(self, *args, **kwargs):\n response = self.call_view(*args, **kwargs)\n if isinstance(response, werkzeug.Response):\n return response\n unpacked = unpack(response)\n status_code = unpacked[1] or http.OK\n return self.marshal_result(unpacked, status_code)\n\n def call_view(self, *args, **kwargs):\n config = flask.current_app.config\n parser = config.get('APISPEC_WEBARGS_PARSER', flaskparser.parser)\n annotation = utils.resolve_annotations(self.func, 'args', self.instance)\n if annotation.apply is not False:\n for option in annotation.options:\n schema = utils.resolve_instance(option['args'])\n parsed = parser.parse(schema, locations=option['kwargs']['locations'])\n kwargs.update(parsed)\n return self.func(*args, **kwargs)\n\n def marshal_result(self, unpacked, status_code):\n config = flask.current_app.config\n format_response = config.get('APISPEC_FORMAT_RESPONSE', flask.jsonify) or identity\n annotation = utils.resolve_annotations(self.func, 'schemas', self.instance)\n schemas = utils.merge_recursive(annotation.options)\n schema = schemas.get(status_code, schemas.get('default'))\n if schema and annotation.apply is not False:\n schema = utils.resolve_instance(schema['schema'])\n output = schema.dump(unpacked[0]).data\n else:\n output = unpacked[0]\n return format_output((format_response(output), ) + unpacked[1:])\n\ndef activate(func):\n if isinstance(func, type) or getattr(func, '__apispec__', {}).get('wrapped'):\n return func\n\n @functools.wraps(func)\n def wrapped(*args, **kwargs):\n instance = args[0] if func.__apispec__.get('ismethod') else None\n annotation = utils.resolve_annotations(func, 'wrapper', instance)\n wrapper_cls = utils.merge_recursive(annotation.options).get('wrapper', Wrapper)\n wrapper = wrapper_cls(func, instance)\n return wrapper(*args, **kwargs)\n\n wrapped.__apispec__['wrapped'] = True\n return wrapped\n\ndef format_output(values):\n while values[-1] is None:\n values = values[:-1]\n return values if len(values) > 1 else values[0]\n\ndef use_kwargs(args, locations=None, inherit=None, apply=None, **kwargs):\n \"\"\"Inject keyword arguments from the specified webargs arguments into the\n decorated view function.\n\n Usage:\n\n .. code-block:: python\n\n from webargs import Arg\n\n @use_kwargs({'name': Arg(str), 'category': Arg(str)})\n def get_pets(**kwargs):\n return Pet.query.filter_by(**kwargs).all()\n\n :param args: Mapping of argument names to `Arg` objects\n :param inherit: Inherit args from parent classes\n :param apply: Parse request with specified args\n \"\"\"\n kwargs.update({'locations': locations})\n def wrapper(func):\n options = {\n 'args': args,\n 'kwargs': kwargs,\n }\n annotate(func, 'args', [options], inherit=inherit, apply=apply)\n return activate(func)\n return wrapper\n\ndef marshal_with(schema, code='default', description='', inherit=None, apply=None):\n \"\"\"Marshal the return value of the decorated view function using the\n specified schema.\n\n Usage:\n\n .. code-block:: python\n\n class PetSchema(Schema):\n class Meta:\n fields = ('name', 'category')\n\n @marshal_with(PetSchema)\n def get_pet(pet_id):\n return Pet.query.filter(Pet.id == pet_id).one()\n\n :param schema: Marshmallow schema class or instance, or `None`\n :param code: Optional HTTP response code\n :param description: Optional response description\n :param inherit: Inherit schemas from parent classes\n :param apply: Marshal response with specified schema\n \"\"\"\n def wrapper(func):\n options = {\n code: {\n 'schema': schema or {},\n 'description': description,\n },\n }\n annotate(func, 'schemas', [options], inherit=inherit, apply=apply)\n return activate(func)\n return wrapper\n\ndef doc(inherit=None, **kwargs):\n \"\"\"Annotate the decorated view function or class with the specified Swagger\n attributes.\n\n Usage:\n\n .. code-block:: python\n\n @doc(tags=['pet'], description='a pet store')\n def get_pet(pet_id):\n return Pet.query.filter(Pet.id == pet_id).one()\n\n :param inherit: Inherit Swagger documentation from parent classes\n \"\"\"\n def wrapper(func):\n annotate(func, 'docs', [kwargs], inherit=inherit)\n return activate(func)\n return wrapper\n\ndef wrap_with(wrapper_cls):\n \"\"\"Use a custom `Wrapper` to apply annotations to the decorated function.\n\n :param wrapper_cls: Custom `Wrapper` subclass\n \"\"\"\n def wrapper(func):\n annotate(func, 'wrapper', [{'wrapper': wrapper_cls}])\n return activate(func)\n return wrapper\n\ndef annotate(func, key, options, **kwargs):\n annotation = utils.Annotation(options, **kwargs)\n func.__apispec__ = func.__dict__.get('__apispec__', {})\n func.__apispec__.setdefault(key, []).insert(0, annotation)\n\ndef inherit(child, parents):\n child.__apispec__ = child.__dict__.get('__apispec__', {})\n for key in ['args', 'schemas', 'docs']:\n child.__apispec__.setdefault(key, []).extend(\n annotation\n for parent in parents\n for annotation in getattr(parent, '__apispec__', {}).get(key, [])\n if annotation not in child.__apispec__[key]\n )\n\nclass ResourceMeta(type):\n\n def __new__(mcs, name, bases, attrs):\n klass = super(ResourceMeta, mcs).__new__(mcs, name, bases, attrs)\n mro = klass.mro()\n inherit(klass, mro[1:])\n methods = [\n each.lower() for each in\n getattr(klass, 'methods', None) or http_method_funcs\n ]\n for key, value in six.iteritems(attrs):\n if key.lower() in methods:\n parents = [\n getattr(parent, key) for parent in mro\n if hasattr(parent, key)\n ]\n inherit(value, parents)\n setattr(klass, key, activate(value))\n if not isinstance(value, staticmethod):\n value.__dict__.setdefault('__apispec__', {})\n value.__apispec__['ismethod'] = True\n return klass\n","sub_path":"flask_apispec/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"547993543","text":"import datetime\nimport os\n\nimport numpy as np\nfrom helper_classes import PL2VEC\nfrom helper_classes import Parser\nfrom helper_classes import DataAnalyser\nfrom helper_classes import Saver\nimport pandas as pd\nimport pickle\n\ndirectory = '/Users/demir/Desktop/Experiments/'\n#path = 'DBpedia'\npath = 'Bio2RDF'\n\nmax_iteration = 50\nbound_for_sentence = 4000\nM = 20\nK = 3\nNC = -2\nenergy_release_at_epoch = 0.1\nnum_sample_from_cluster = 5\n\nfolder_name = str(datetime.datetime.now())\nPATH = directory + folder_name # 'Spring'+str(folder_name)\nos.makedirs(PATH)\n\nparser = Parser()\nmodel = PL2VEC()\nanalyser = DataAnalyser()\n\nstats_corpus_info, vocab, kg_size, resources = parser.construct_comatrix_txt(path, bound_for_sentence, True)\n#stats_corpus_info, vocab, kg_size, resources = parser.process_knowledge_graph_to_construct_PPMI_co_matrix(path, bound_for_sentence)\n\npd.Series(vocab).to_csv(PATH + '/vocab.csv')\ndel vocab\n#pickle.dump(vocab, open(directory + \"vocab.p\", \"wb\"));del vocab\npickle.dump(stats_corpus_info, open(directory + \"stats_corpus_info.p\", \"wb\"))\npickle.dump(resources, open(directory + \"resources.p\", \"wb\"))\npickle.dump(kg_size, open(directory + \"kg_size.p\", \"wb\"))\n\n\nindex_resource = np.array(list(resources.values()), dtype=np.uint32)\ndel resources\n\ndef save_settings():\n print('num_of_interacting_entities:', K)\n print('energy_release_at_epoch:', energy_release_at_epoch)\n print('NC:', NC)\n print('Size of vocabulary :', len(stats_corpus_info))\n print('Num of RDFs :', kg_size)\n print('Num of unique entities :' + str(len(stats_corpus_info)))\n print('Num of interacting entities :' + str(K))\n print('Negative Constant :' + str(NC))\n print('energy_release_at_epoch :' + str(energy_release_at_epoch))\n print('Num of dimension in Embedding Space :' + str(M))\n print('Num of samples from each cluster :' + str(num_sample_from_cluster))\n\n Saver.settings.append('Num of RDFs :' + str(kg_size))\n Saver.settings.append('Negative Constant :' + str(NC))\n Saver.settings.append('energy_release_at_epoch :' + str(energy_release_at_epoch))\n Saver.settings.append('Num of dimension in Embedding Space :' + str(M))\n Saver.settings.append('Num of samples from each cluster :' + str(num_sample_from_cluster))\n Saver.settings.append('Num of unique entities :' + str(len(stats_corpus_info)))\n Saver.settings.append('Num of n-triples :' + str(kg_size))\n Saver.settings.append('Num of interacting entities :' + str(K))\n Saver.settings.append('Negative Constant :' + str(NC))\n Saver.settings.append('energy_release_at_epoch :' + str(energy_release_at_epoch))\n Saver.settings.append('Num of dimension in Embedding Space :' + str(M))\n Saver.settings.append('Num of samples from each cluster :' + str(num_sample_from_cluster))\n\n\nsave_settings()\n\nP, N = parser.retrieve_interactting_entities(stats_corpus_info, K)\nvocab_size=len(stats_corpus_info)\ndel stats_corpus_info\npickle.dump(N, open(PATH + \"/Negative_URIs.p\", \"wb\"))\npickle.dump(P, open(PATH + \"/Positive_URIs.p\", \"wb\"))\n\nassert len(P)==len(N)\n\n\nholder = model.combine_information(P, N)\ndel P\ndel N\n\n\nembeddings = model.randomly_initialize_embedding_space(vocab_size, M)\n\nlearned_embeddings = model.start(e=embeddings,\n max_iteration=max_iteration, energy_release_at_epoch=energy_release_at_epoch,\n holder=holder, negative_constant=NC)\ndel embeddings\ndel holder\n\nnp.savetxt(PATH + '/learned_embeddings.csv', learned_embeddings, delimiter=\",\")\nnp.savetxt(PATH + '/d_ratios.txt', np.array(model.ratio), delimiter=\",\")\n\ndict_of_cluster_with_original_term_names = analyser.pipeline_of_data_processing(index_resource,learned_embeddings, PATH)\ndel learned_embeddings\ndel index_resource\n\n\n# INSPECK\n#import pprint\n#pprint.pprint(locals())\n\nanalyser.pipeline_of_dl_learner(PATH, dict_of_cluster_with_original_term_names)\n\nSaver.settings.clear()\n\"\"\"\ndict_of_cluster_with_original_term_names, embeddings_of_resources, sampled_total_entities = analyser.pipeline_of_data_processing(\n indexes_of_subjects,\n learned_embeddings.values,\n vocabulary_of_entity_names,\n min_sample_DBSCAN,\n num_sample_from_cluster)\n\nanalyser.topN_cosine(sampled_total_entities, topN=5, times=5)\n\nSaver.settings.append('Num of generated clusters: ' + str(len(list(dict_of_cluster_with_original_term_names.keys()))))\npath = analyser.pipeline_of_dl_learner(directory, embeddings_of_resources, sampled_total_entities,\n dict_of_cluster_with_original_term_names,\n path)\n\nmodel.plot_distance_function(title=plot_name, K=num_of_interacting_entities, NC=NC, delta_e=energy_release_at_epoch,\n path=path)\n\npickle.dump(holder, open(path + \"/statistical_info.p\", \"wb\"))\npickle.dump(vocabulary_of_entity_names, open(path + \"/vocabs.p\", \"wb\"))\n\nSaver.settings.clear()\n\nprint('completed')\n\"\"\"\n","sub_path":"execute_PL2VEC.py","file_name":"execute_PL2VEC.py","file_ext":"py","file_size_in_byte":4939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"514704764","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n # ex: /\n url(r'^$', views.review_list, name='review_list'),\n # ex: /review/5/\n url(r'^review/(?P[0-9]+)/$', views.review_detail, name='review_detail'),\n # ex: /wine/\n url(r'^wine$', views.wine_list, name='wine_list'),\n\n url(r'^staff$', views.staff_list, name='staff_list'),\n url(r'^predictedList$', views.predicted_list, name='predicted_list'),\n url(r'^empReviewedList', views.reviewed_list, name='reviewed_list'),\n url(r'^staff/(?P[0-9]+)/$', views.staff_detail, name='staff_detail'),\n url(r'^staff/(?P[0-9]+)/add_emp_review/$', views.add_emp_review, name='add_emp_review'),\n url(r'^emprecommendation/$', views.emp_recommendation_list, name='emp_recommendation_list'),\n\n # ex: /wine/5/\n url(r'^wine/(?P[0-9]+)/$', views.wine_detail, name='wine_detail'),\n url(r'^wine/(?P[0-9]+)/add_review/$', views.add_review, name='add_review'),\n # ex: /review/user - get reviews for the logged user\n url(r'^review/user/(?P\\w+)/$', views.user_review_list, name='user_review_list'),\n # ex: /review/user - get reviews for the user passed in the url\n url(r'^review/user/$', views.user_review_list, name='user_review_list'),\n # ex: /recommendation - get wine recommendations for the logged user\n url(r'^recommendation/$', views.user_recommendation_list, name='user_recommendation_list'),\n]\n","sub_path":"hrms/reviews/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"198766115","text":"import os\nimport webapp2\nimport jinja2\nfrom app.models import Crane\n\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname('templates/')),\n extensions=['jinja2.ext.autoescape'],\n autoescape=True)\n\nJINJA_ENVIRONMENT.globals.update({\n 'cranes': Crane.objects.order_by('record_created')[:10],\n})\n\n\ndef reset_jinja_environment():\n JINJA_ENVIRONMENT.globals.update({\n 'cranes': Crane.objects.order_by('record_created')[:10],\n })\n\ndef render_response(template_name, **kwargs):\n return JINJA_ENVIRONMENT.get_template(template_name).render(**kwargs)\n","sub_path":"app/jinja_settings.py","file_name":"jinja_settings.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"190368675","text":"# 上面と前面の数字から、右側の面の数字を答えるプログラム\n\n# ダイスの面を定義するクラス\nclass Dice:\n def __init__(self):\n self.top = 1\n self.front = 2\n self.right = 3\n self.left = 4\n self.back = 5\n self.bottom = 6\n # 2->1->5->6\n def turnSouth(self):\n temp = self.top\n self.top = self.back\n self.back = self.bottom\n self.bottom = self.front\n self.front = temp\n return self\n # 4->1->3->6\n def turnEast(self):\n temp = self.top\n self.top = self.left\n self.left = self.bottom\n self.bottom = self.right\n self.right = temp\n return self\n # 3->1->4->6\n def turnWest(self):\n temp = self.top\n self.top = self.right\n self.right = self.bottom\n self.bottom = self.left\n self.left = temp\n return self\n # 5->1->2->6\n def turnNorth(self):\n temp = self.top\n self.top = self.front\n self.front = self.bottom\n self.bottom = self.back\n self.back = temp\n return self\n # 2->3->5->4\n def turnRight(self):\n temp = self.front\n self.front = self.right\n self.right = self.back\n self.back = self.left\n self.left = temp\n return self\n # 2->4->5->3\n def turnLeft(self):\n temp = self.front\n self.front = self.left\n self.left = self.back\n self.back = self.right\n self.right = temp\n return self\n\n# Diceの生成\nmyDice = Dice()\n# ダイス初期状態の入力\nmyDice.top, myDice.front, myDice.right, myDice.left, myDice.back, myDice.bottom = input().split()\n# 質問の数qを標準入力から取得\nq = int(input())\n# ループによる質問の読み込みと出力\n# 出力対象 右側面 ダイステーブル換算(3)\nfor i in range(0, q):\n # 質問の読み込み 上面(1) 前面(2) \n question = list(input())\n question = \"\".join(question).split()\n # 上面の割り出し 前後方向\n for j in range(0, 3):\n if question[0] == myDice.top:\n break\n myDice.turnNorth()\n # 上面の割り出し 左右方向\n for j in range(0, 3):\n if question[0] == myDice.top:\n break\n myDice.turnEast()\n # 正面の割り出し 上面を変えずに回転\n for j in range(0, 3):\n if question[1] == myDice.front:\n break\n myDice.turnRight()\n print(\"{0}\".format(myDice.right))\n","sub_path":"24DiceII.py","file_name":"24DiceII.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"168977027","text":"import sys\nsys.path.insert(0, '/Users/temi/cosmic-code/code/src')\nfrom order.domain.model import Asset, Portfolio, Holding\nfrom datetime import date, time\n\ndef create_asset():\n new_asset = Asset(ticker = \"abc\", name=\"abc\", qty = 10, price = 10.34)\n return new_asset\n\ndef test_asset_is_created():\n new_asset = Asset(ticker = \"abc\", name=\"abc\", qty = 10, price = 10.34)\n assert new_asset.name == \"abc\"\n assert new_asset.ticker == \"abc\"\n assert new_asset.qty == 10\n\ndef create_portfolio():\n all_holdings = list()\n new_asset = Asset(ticker = \"abc\", name=\"abc\", qty = 10, price = 10.34)\n new_asset_2 = Asset(ticker = \"abcb\", name=\"abcb\", qty = 50, price = 145.34)\n new_asset_3 = Asset(ticker = \"cde\", name=\"cde\", qty = 500, price = 56.34)\n all_holdings.append(Holding(new_asset).assetHoldings)\n all_holdings.append(Holding(new_asset_2).assetHoldings)\n all_holdings.append(Holding(new_asset_3).assetHoldings)\n return all_holdings\n\ndef test_portfolio_is_created():\n all_holdings = create_portfolio()\n new_portfolio = Portfolio(id = 100, holdings=all_holdings, date_created=date, date_updated=date)\n assert new_portfolio.holdings == all_holdings\n\ndef test_portfolio_total():\n all_holdings = create_portfolio()\n total = sum(item.qty * item.price for item in all_holdings)\n new_portfolio = Portfolio(id = 100, holdings=all_holdings, date_created=date, date_updated=date)\n assert new_portfolio.total == total\n\ndef test_asset_holding_is_valid():\n test_asset = create_asset()\n new_asset = Asset(ticker = \"abc\", name=\"abc\", qty = 20, price = 10.34)\n holding = Holding(test_asset)\n assert holding.isAssetValid() == True\n\n\ndef test_asset_holding_allocation():\n test_asset = create_asset()\n holding = Holding(test_asset)\n assert holding.assetHoldings == test_asset\n","sub_path":"tests/unit/test_order.py","file_name":"test_order.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"92068037","text":"\"\"\"The spatial grid\"\"\"\n# coding=utf-8\nimport numpy as np\nimport scipy.fftpack as fft\n\nfrom ..helper_functions import physics\nfrom ..algorithms import charge_deposition, FieldSolver, BoundaryCondition, current_deposition, field_interpolation\n\n\nclass Grid:\n \"\"\"\n Object representing the grid on which charges and fields are computed\n \"\"\"\n\n\n def __init__(self, T: float, L: float, NG: int, c: float = 1, epsilon_0: float = 1, bc=lambda *x: None,\n periodic=True):\n \"\"\"\n \n Parameters\n ----------\n T : float\n total runtime of the simulation\n L : float\n total length of simulation area\n NG : int\n number of grid cells\n c : float\n speed of light\n epsilon_0 : float\n electric permittivity of vacuum\n bc : function\n Function for providing values of the left boundary. To be refactored into taking the Laser object. # REFACTOR\n periodic: bool\n Defines whether the grid is to be treated as periodic or non-periodic.\n \"\"\"\n\n\n self.c = c\n self.epsilon_0 = epsilon_0\n self.particle_bc = lambda *x: None\n self.x, self.dx = np.linspace(0, L, NG, retstep=True, endpoint=False)\n self.x_interpolation = np.arange(NG+2)*self.dx - self.dx\n\n self.dt = self.dx / c\n self.T = T\n self.NT = physics.calculate_number_timesteps(T, self.dt)\n self.epsilon_0 = epsilon_0\n\n self.charge_density = np.zeros(NG + 1)\n self.current_density_x = np.zeros((NG + 3))\n self.current_density_yz = np.zeros((NG + 4, 2))\n self.electric_field = np.zeros((NG + 2, 3))\n self.magnetic_field = np.zeros((NG + 2, 3))\n\n self.L = L\n self.NG = NG\n\n self.bc_function = bc # REFACTOR boundary condition\n self.k = 2 * np.pi * fft.fftfreq(self.NG, self.dx)\n self.k[0] = 0.0001\n\n self.periodic = periodic\n if self.periodic:\n self.charge_gather_function = charge_deposition.periodic_density_deposition\n self.current_longitudinal_gather_function = current_deposition \\\n .periodic_longitudinal_current_deposition\n self.current_transversal_gather_function = current_deposition.periodic_transversal_current_deposition\n self.particle_bc = BoundaryCondition.return_particles_to_bounds\n self.interpolator = field_interpolation.PeriodicInterpolateField\n self.solver = FieldSolver.FourierSolver\n else:\n self.charge_gather_function = charge_deposition.aperiodic_density_deposition\n self.current_longitudinal_gather_function = current_deposition.aperiodic_longitudinal_current_deposition\n self.current_transversal_gather_function = current_deposition.aperiodic_transversal_current_deposition\n self.particle_bc = BoundaryCondition.kill_particles_outside_bounds\n self.interpolator = field_interpolation.AperiodicInterpolateField\n self.solver = FieldSolver.BunemanSolver\n\n\n self.list_species = []\n self.charge_density_history = np.zeros((self.NT, self.NG))\n self.current_density_history = np.zeros((self.NT, self.NG, 3))\n self.electric_field_history = np.zeros((self.NT, self.NG, 3))\n self.magnetic_field_history = np.zeros((self.NT, self.NG, 2))\n\n self.postprocessed = False\n\n def postprocess(self):\n if not self.postprocessed:\n print(\"Postprocessing grid.\")\n\n self.t = np.arange(self.NT) * self.dt\n\n # increase size of magnetic field history\n magnetic_field_history = np.zeros((self.NT, self.NG, 3), dtype=float)\n magnetic_field_history[:,:,1:] = self.magnetic_field_history\n self.magnetic_field_history = magnetic_field_history\n\n\n # calculate energy history\n self.longitudinal_energy_history = 0.5 * self.epsilon_0 * (self.electric_field_history[:,:,0] ** 2)\n perpendicular_electric_energy = 0.5 * self.epsilon_0 * (self.electric_field_history[:,:,1:] ** 2).sum(2) # over directions\n mu_zero_inv = 1/ (self.epsilon_0 * self.c**2)\n magnetic_energy = 0.5 * (self.magnetic_field_history **2).sum(2) * mu_zero_inv # over directions\n\n self.perpendicular_energy_history = perpendicular_electric_energy + magnetic_energy\n self.check_on_charge = np.gradient(self.electric_field_history[:, :, 0], self.dx, axis=1) * self.epsilon_0\n # fourier analysis\n from scipy import fftpack\n self.k_plot = fftpack.rfftfreq(int(self.NG), self.dx)[::2]\n self.longitudinal_energy_per_mode_history = np.abs(fftpack.rfft(self.longitudinal_energy_history))[:,::2]\n self.perpendicular_energy_per_mode_history = np.abs(fftpack.rfft(self.perpendicular_energy_history))[:,::2]\n\n self.longitudinal_energy_history = self.longitudinal_energy_history.sum(1)\n self.perpendicular_energy_history = self.perpendicular_energy_history.sum(1)\n self.grid_energy_history = self.perpendicular_energy_history + self.longitudinal_energy_history # over positions\n\n self.x_current = self.x + self.dx / 2\n self.postprocessed = True\n\n def apply_bc(self, i):\n # noinspection PyCallingNonCallable\n bc_value = self.bc_function(i * self.dt)\n if bc_value is not None:\n self.electric_field[0, 1] = bc_value\n self.magnetic_field[0, 2] = bc_value / self.c\n # TODO: add polarization\n # self.electric_field[0, 2] = bc_value\n # self.magnetic_field[0, 1] = bc_value / self.c\n\n def init_solver(self):\n return self.solver.init_solver(self)\n\n def solve(self):\n return self.solver.solve(self)\n\n def direct_energy_calculation(self):\n r\"\"\"\n Direct energy calculation as\n\n :math:`E = \\frac{\\epsilon_0}{2} \\sum_{i=0}^{NG} E^2 \\Delta x`\n\n :return float E: calculated energy\n \"\"\"\n return self.epsilon_0 * (self.electric_field ** 2).sum() * 0.5\n\n def gather_charge(self, list_species):\n # REFACTOR: move to Species\n self.charge_density[...] = 0.0\n for species in list_species:\n self.charge_density += species.gather_density() * species.eff_q\n # REFACTOR: optionally self.charge_density -= self.charge_density.mean() for periodic simulations\n\n def gather_current(self, list_species):\n # REFACTOR: move to Species\n self.current_density_x[...] = 0.0\n self.current_density_yz[...] = 0.0\n for species in list_species:\n self.current_longitudinal_gather_function(self.current_density_x, species.v[:, 0], species.x, self.dx, self.dt,\n species.eff_q)\n self.current_transversal_gather_function(self.current_density_yz, species.v, species.x, self.dx, self.dt,\n species.eff_q)\n\n def field_function(self, xp):\n result = self.interpolator(xp, np.hstack((self.electric_field, self.magnetic_field)), self.dx)\n return result[:, :3], result[:, 3:]\n\n def save_field_values(self, i):\n \"\"\"Update the i-th set of field values, without those gathered from interpolation (charge\\current)\"\"\"\n self.charge_density_history[i, :] = self.charge_density[:-1]\n self.current_density_history[i, :, 0] = self.current_density_x[1:-2]\n self.current_density_history[i, :, 1:] = self.current_density_yz[2:-2]\n self.electric_field_history[i] = self.electric_field[1:-1]\n self.magnetic_field_history[i] = self.magnetic_field[1:-1, 1:]\n\n def save_to_h5py(self, grid_data):\n \"\"\"\n Saves all grid data to h5py file\n grid_data: h5py group in premade hdf5 file\n \"\"\"\n h5py_dictionary = {'NGrid': self.NG,\n 'L': self.L,\n 'epsilon_0': self.epsilon_0,\n 'c': self.c,\n 'dt': self.dt,\n 'dx': self.dx,\n 'NT': self.NT,\n 'T': self.T,\n 'periodic': self.periodic\n }\n for key, value in h5py_dictionary.items():\n grid_data.attrs[key] = value\n h5py_dataset_dictionary = {'x':self.x,\n 'rho':self.charge_density_history,\n 'current':self.current_density_history,\n 'Efield':self.electric_field_history,\n 'Bfield':self.magnetic_field_history,\n }\n for key, value in h5py_dataset_dictionary.items():\n grid_data.create_dataset(name=key, dtype=float, data=value)\n\n # grid_data.create_dataset(name=\"energy per mode\", dtype=float,\n # data=self.energy_per_mode_history) # OPTIMIZE: do these in post production\n # grid_data.create_dataset(name=\"grid energy\", dtype=float, data=self.grid_energy_history)\n\n\ndef load_grid(grid_data, postprocess=False):\n \"\"\"\n Loads grid data and create a Grid object.\n\n Parameters\n ----------\n grid_data : h5py path\n Path to Grid data.\n postprocess: bool\n Whether to postprocess the grid after loading.\n Returns\n -------\n Grid\n the loaded grid.\n \"\"\"\n NG = grid_data.attrs['NGrid']\n L = grid_data.attrs['L']\n epsilon_0 = grid_data.attrs['epsilon_0']\n NT = grid_data['rho'].shape[0]\n c = grid_data.attrs['c']\n dx = grid_data.attrs['dx']\n dt = grid_data.attrs['dt']\n T = grid_data.attrs['T']\n periodic = grid_data.attrs['periodic']\n\n x = grid_data['x'][...]\n grid = Grid(T = T,\n L = L,\n NG = NG,\n c = c,\n epsilon_0 = epsilon_0,\n periodic = periodic\n )\n assert grid.dx == dx\n assert grid.dt == dt\n assert grid.NT == NT\n assert np.allclose(x, grid.x)\n grid.charge_density_history = grid_data['rho'][...]\n grid.current_density_history = grid_data['current'][...]\n grid.electric_field_history = grid_data['Efield'][...]\n grid.magnetic_field_history = grid_data['Bfield'][...]\n\n if postprocess:\n grid.postprocess()\n return grid","sub_path":"pythonpic/classes/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":10473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"605570063","text":"import os\nimport sys\nimport cv2\nimport math\n\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard, CSVLogger, LearningRateScheduler\nfrom argparse import ArgumentParser\nfrom keras.utils import to_categorical, Sequence\nfrom albumentations import *\nfrom model_lib import *\nfrom keras.optimizers import Adam\nfrom glob import glob\n\nfrom keras import backend as K\nimport tensorflow as tf\nimport numpy as np\nimport datetime as dt\n\n# control CUDA/tensorflow log level\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # or any {'0', '1', '2'}\n\n\ndef build_argparser():\n parser = ArgumentParser()\n parser.add_argument('-m', required=True, type=str)\n parser.add_argument('-pw', help='pretrained_weights path', type=str, default=None)\n parser.add_argument('-b', help='batch size', type=int, default=16)\n parser.add_argument('-e', help='epoch', type=int, default=30)\n parser.add_argument('-dst', help='Path to the models to save.', type=str, default='.')\n parser.add_argument('--train', '-t', help='folder of the training data', required=True, type=str)\n parser.add_argument('--validataion', '-v', help='folder of the validation data', type=str, default=None)\n parser.add_argument('--learning_rate', '-lr', help='init learning rate', type=float, default=1e-3)\n parser.add_argument('--epoch_drop', '-ed', help='epochs learning rate drop', type=int, default=10)\n parser.add_argument('--aug_prob', '-aug', type=float, default=0.5)\n parser.add_argument('--process_num', '-pn', type=int, default=1)\n parser.add_argument('-gpu', default='0', type=str)\n return parser\n\n\ndef strong_aug(height, width, p=.5):\n min_size = min(height, width)\n return Compose([\n Flip(),\n OneOf([\n Blur(blur_limit=5, p=1),\n CLAHE(clip_limit=3, tile_grid_size=(8, 8), p=1),\n RandomBrightnessContrast(brightness_limit=0.05, contrast_limit=0.05, p=1),\n HueSaturationValue(hue_shift_limit=5, sat_shift_limit=5, val_shift_limit=5, p=1),\n ], p=0.85),\n OneOf([\n RandomSizedCrop(height=height, width=width, min_max_height=(int(min_size * 0.9), int(min_size * 0.98)),\n p=1),\n ElasticTransform(alpha_affine=12, border_mode=0, p=1),\n GridDistortion(border_mode=0, distort_limit=0.2, p=1),\n ShiftScaleRotate(shift_limit=0.08, scale_limit=0.08, rotate_limit=5, border_mode=0, p=1),\n Rotate(limit=15, border_mode=0, p=1),\n ], p=0.85)\n ], p=p)\n\n\ndef lr_decay(epoch):\n \"\"\" Learning rate decay function\n\n Drop learning rate by [cfg.lr_sched_drop] every\n [cfg.epochs_drop] number of epochs\n\n Input\n epoch : Current epoch count\n Output\n lrate : New learning rate\n \"\"\"\n initial_lrate = lr\n drop_rate = 0.6\n epochs_until_drop = lr_epochs_drop\n lrate = initial_lrate * math.pow(drop_rate, math.floor((1 + epoch) / epochs_until_drop))\n return lrate\n\n\nclass DataGenerator(Sequence):\n \"\"\" Generates data for training and validation\n \"\"\"\n\n def __init__(self, img_names, labels, batch_size, n_classes, dim, preprocess_input,\n shuffle=True, aug=True, save_folder=None):\n \"\"\" Initialization\n img_names:full path of image\n labels:0 ~ n_classes-1\n dim:(width, heigth)\n \"\"\"\n self.img_names = img_names\n self.labels = labels\n self.batch_size = batch_size\n self.n_classes = n_classes\n self.dim = dim\n self.preprocess_input = preprocess_input\n self.shuffle = shuffle\n self.aug = aug\n self.save_folder = save_folder\n self.image_nums = len(self.img_names)\n self.all_index = np.arange(self.image_nums)\n\n self.on_epoch_end()\n\n def __len__(self):\n \"\"\" Returns number of batches in dataset\n \"\"\"\n return int(np.floor(self.image_nums / self.batch_size))\n\n def __getitem__(self, index):\n \"\"\" Returns one batch of data\n \"\"\"\n # Generate start and end indices of the batch\n idxmin = index * self.batch_size\n idxmax = min((index + 1) * self.batch_size, self.image_nums)\n temp_index = self.all_index[idxmin:idxmax]\n # Find IDs and labels for the selected indices\n img_names = [self.img_names[i] for i in temp_index]\n list_labels = [self.labels[i] for i in temp_index]\n # Generate data for selected IDs and labels\n x, y = self.__data_generation(img_names, list_labels)\n return x, y\n\n def on_epoch_end(self):\n \"\"\" Updates all_index after each epoch\n \"\"\"\n # Shuffle array of indices after each epoch end\n if self.shuffle:\n np.random.seed(42)\n np.random.shuffle(self.all_index)\n\n def __data_generation(self, img_names, list_labels):\n \"\"\" Generates data containing batch_size samples\n \"\"\"\n x_batch = []\n for image_name in img_names:\n image = cv2.imread(image_name)\n if image.shape[0] != self.dim[1] or image.shape[1] != self.dim[0]:\n image = cv2.resize(image, self.dim)\n if self.aug:\n data = {\"image\": image}\n augmented = global_aug(**data)\n image = augmented[\"image\"]\n if image.shape[0] != self.dim[1] or image.shape[1] != self.dim[0]:\n image = cv2.resize(image, self.dim)\n if self.save_folder:\n cv2.imwrite(os.path.join(self.save_folder, os.path.basename(image_name)), image)\n x_batch.append(image)\n x_array = self.preprocess_input(np.array(x_batch))\n y_array = to_categorical(np.array(list_labels), num_classes=self.n_classes)\n return x_array, y_array\n\n\ndef main():\n global lr\n global lr_epochs_drop\n global global_aug\n\n args = build_argparser().parse_args()\n train_path = os.path.abspath(args.train)\n # start_time = dt.datetime.now().strftime('%Y%m%d_%H%M')\n # dst_path = os.path.join(os.path.abspath(args.dst), start_time)\n dst_path = os.path.abspath(args.dst)\n model_name = args.m\n pre_weights = args.pw\n batch_size = args.b\n epochs = args.e\n gpu = args.gpu\n lr = args.learning_rate\n lr_epochs_drop = args.epoch_drop\n process_num = args.process_num\n log_dir = os.path.join(dst_path, 'train_log')\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n model_dir = os.path.join(dst_path, 'model')\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n\n # prepare data\n classes = sorted(os.listdir(train_path))\n num_classes = len(classes)\n class_ids = dict() # {'label1':0, ...}\n train_image_names = []\n train_image_indexs = []\n val_image_names = []\n val_image_indexs = []\n\n with open(os.path.join(dst_path, 'class.txt'), 'w') as f:\n for index, label in enumerate(classes):\n f.write(\"%s\\n\" % label)\n class_ids[label] = index\n\n for label in classes:\n tmp_names = glob(os.path.join(train_path, label, '*'))\n tmp_indexs = [class_ids[label]] * len(tmp_names)\n train_image_names.extend(tmp_names)\n train_image_indexs.extend(tmp_indexs)\n\n valid_flag = False\n if args.validataion is not None:\n validation_path = os.path.abspath(args.validataion)\n valid_flag = True\n for label in classes:\n tmp_names = glob(os.path.join(validation_path, label, '*'))\n tmp_indexs = [class_ids[label]] * len(tmp_names)\n val_image_names.extend(tmp_names)\n val_image_indexs.extend(tmp_indexs)\n\n save_name_loss = 'vloss{val_loss:.4f}.h5' if valid_flag else 'loss{loss:.4f}.h5'\n save_name = model_name + '_ep{epoch:02d}_' + save_name_loss\n full_save_name = os.path.join(model_dir, save_name)\n\n # keras config\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = gpu\n keras_config = tf.ConfigProto()\n keras_config.gpu_options.allow_growth = True # 不全部占满显存, 按需分配\n with tf.Session(config=keras_config) as sess:\n K.set_session(sess)\n if model_name == 'mobilenet':\n image_height = 224\n image_width = 224\n model, process_input = mobilenet(input_size=(image_height, image_width, 3),\n num_classes=num_classes)\n elif model_name == 'resnet50':\n image_height = 224\n image_width = 224\n model, process_input = resnet50(input_size=(image_height, image_width, 3),\n num_classes=num_classes)\n elif model_name == 'xception':\n image_height = 299\n image_width = 299\n model, process_input = xception(input_size=(image_height, image_width, 3),\n num_classes=num_classes)\n\n elif model_name == 'inception_resnetv2':\n image_height = 299\n image_width = 299\n model, process_input = inresv2(input_size=(image_height, image_width, 3),\n num_classes=num_classes)\n\n if pre_weights:\n model.load_weights(pre_weights)\n model.compile(optimizer=Adam(lr=lr), loss='categorical_crossentropy', metrics=['accuracy'])\n\n global_aug = strong_aug(image_height, image_width, args.aug_prob)\n\n # training\n callbacks_list = [\n LearningRateScheduler(lr_decay),\n EarlyStopping(monitor='val_loss' if valid_flag else 'loss', patience=20, verbose=0),\n TensorBoard(log_dir=log_dir),\n ModelCheckpoint(full_save_name, monitor='val_loss' if valid_flag else 'loss',\n verbose=0, save_best_only=True, save_weights_only=True),\n # CSVLogger(os.path.join(dst_path, \"%s_%s.csv\" % (model_name, start_time)))\n CSVLogger(os.path.join(dst_path, \"%s.csv\" % model_name))\n ]\n\n # Initialize train data generator\n training_generator = DataGenerator(img_names=train_image_names,\n labels=train_image_indexs,\n batch_size=batch_size,\n n_classes=num_classes,\n dim=(image_width, image_height),\n preprocess_input=process_input,\n shuffle=True,\n aug=True,\n save_folder=None)\n\n # Initialize validation generator\n if valid_flag:\n validation_generator = DataGenerator(img_names=val_image_names,\n labels=val_image_indexs,\n batch_size=batch_size,\n n_classes=num_classes,\n dim=(image_width, image_height),\n preprocess_input=process_input,\n shuffle=False,\n aug=False)\n\n model.fit_generator(generator=training_generator,\n epochs=epochs,\n callbacks=callbacks_list,\n validation_data=validation_generator if valid_flag else None,\n max_queue_size=20,\n workers=process_num,\n use_multiprocessing=True)\n # class_weight)\n\n # save last epoch weight\n save_name = model_name + '_ep_last.h5'\n full_save_name = os.path.join(model_dir, save_name)\n model.save_weights(full_save_name)\n\n K.clear_session()\n\n\nif __name__ == '__main__':\n sys.exit(main() or 0)\n","sub_path":"200726_sun_classification/train/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"158356888","text":"import asyncio\nfrom django import forms\nfrom datetime import datetime, timedelta\nimport requests\nimport urllib\nfrom weather.settings import WIND_SPEED_URL, TEMP_URL, MAX_CONCURRENT_WIND, MAX_CONCURRENT_TEMP\n\n\nclass DateForm(forms.Form):\n start = forms.DateTimeField(required=True, input_formats=[\"%Y-%m-%dT%H:%M:%S%z\"])\n end = forms.DateTimeField(required=True, input_formats=[\"%Y-%m-%dT%H:%M:%S%z\"])\n dtype = forms.CharField(required=True)\n api = forms.CharField(required=False)\n\n def clean(self):\n start = self.cleaned_data.get(\"start\")\n end = self.cleaned_data.get(\"end\")\n dtype = self.cleaned_data.get(\"dtype\")\n\n if not start or not end or not dtype:\n return\n\n max_date = datetime.now(start.tzinfo)\n min_date = datetime(1900, 1, 1, 0, 0, 0, tzinfo=start.tzinfo)\n\n if start > end:\n self.add_error('start', 'Start date should be prior end date')\n\n date_range_err = False\n if start > max_date or start < min_date:\n date_range_err = True\n self.add_error('start', \n forms.ValidationError(\n ('Invalid start date range for: %(date)s'),\n params={'date': start},\n )\n )\n if end > max_date or end < min_date:\n date_range_err = True\n self.add_error('end', \n forms.ValidationError(\n ('Invalid end date range for: %(date)s'),\n params={'date': end},\n )\n )\n\n if date_range_err:\n return\n\n # create async loop chunks\n loop = asyncio.get_event_loop()\n tasks = []\n if dtype in ['weather', 'wind']:\n tasks.append(self.__chunk_loop(start, end, loop, MAX_CONCURRENT_WIND, WIND_SPEED_URL))\n if dtype in ['weather', 'temperature']:\n tasks.append(self.__chunk_loop(start, end, loop, MAX_CONCURRENT_TEMP, TEMP_URL))\n\n if dtype == 'weather':\n w_res, t_res = loop.run_until_complete(asyncio.gather(*tasks))\n res = []\n # flatten t_res response (concurrent chunks)\n t_res = [c_list for sublist in t_res for c_list in sublist]\n # flatten w_res response and add temperature\n for k, chunk in enumerate(w_res):\n for j, w_data in enumerate(chunk):\n # if dict keys order not required replace append with mapping\n # res.append({**w_data, **t_res[k][j]})\n res.append({\n 'north': w_data['north'],\n 'west': w_data['west'],\n 'temp': t_res[k*j]['temp'],\n 'date': w_data['date'],\n })\n\n else:\n chunks = loop.run_until_complete(tasks[0])\n # flatten response (concurrent chunks)\n res = [c_list for sublist in chunks for c_list in sublist]\n\n self.data['response'] = res\n\n async def __chunk_loop(self, start, end, loop, chunk_size, url):\n tasks = []\n tasks_chunks = []\n for k, dt in self.__daterange(start, end):\n if k % chunk_size == 0 and k > 0:\n tasks_chunks.append(await asyncio.gather(*tasks))\n tasks = []\n tasks.append(\n loop.create_task(self.__get_data(url, dt))\n )\n tasks_chunks.append(await asyncio.gather(*tasks))\n return tasks_chunks\n\n async def __get_data(self, url, date):\n date_iso = urllib.parse.quote(date.isoformat())\n ws_url = \"%s?at=%s\" % (url, date_iso)\n r = requests.get(ws_url)\n \n if r.status_code != 200:\n self.add_error(\n 'api',\n forms.ValidationError(\n ('error response %(url)s: %(msg)s'),\n params = {'url': url + date_iso, 'msg': r.json()['message']}\n )\n )\n\n return r.json()\n\n def __daterange(self, date1, date2):\n for n in range(int((date2 - date1).days) + 1):\n yield n, date1 + timedelta(n)\n","sub_path":"weather/api/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"83776643","text":"# -*- coding: utf-8 -*-\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n\"\"\"Example DAG demonstrating the usage of the PythonOperator.\"\"\"\n\nimport time\nfrom pprint import pprint\nimport logging\n\nimport airflow\nfrom airflow.models import DAG\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.bash_operator import BashOperator\n\nargs = {\n 'owner': 'airflow',\n 'start_date': airflow.utils.dates.days_ago(1),\n}\n\ndag = DAG(\n dag_id='mysql2hive2',\n default_args=args,\n schedule_interval=\"0 * * * *\",\n)\n\n\n# [START howto_operator_python]\ndef print_context(ds, **kwargs):\n \"\"\"Print the Airflow context and ds variable from the context.\"\"\"\n pprint(kwargs)\n print(ds)\n return 'Whatever you return gets printed in the logs'\n\ndef dag_run(context, dag_run_obj):\n print(\"[dag_run] %s\"%dag_run_obj)\n return dag_run_obj\n\nrun_this = PythonOperator(\n task_id='print_the_context',\n provide_context=True,\n python_callable=print_context,\n dag=dag,\n)\n\ntrigger_hdfs = BashOperator(\n task_id='trigger_hdfs',\n bash_command=\"\"\"\n set -x\n\n if [[\"$(airflow trigger_dag -r trig__{{ execution_date }} -e {{ execution_date }} example_python_operator)\" != 0]]; then\n airflow clear -c -s {{ execution_date }} -e {{ execution_date }} example_python_operator\n fi\n \"\"\",\n dag=dag,\n)\n\nrun_this.set_downstream(trigger_hdfs)\n","sub_path":"dags/t3.py","file_name":"t3.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"25337325","text":"from keras import optimizers\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.layers import Activation, Dropout, Flatten, Dense\nfrom keras import backend as K\nfrom keras import optimizers\nfrom keras.applications import InceptionResNetV2\nfrom PIL import Image\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# dimensions of our images.\nimg_width, img_height = 48, 48\n\ntrain_data_dir = '../../fer2013_binary/training'\nvalidation_data_dir = '../../fer2013_binary/validation'\nnb_train_samples = 20000\nnb_validation_samples = 3000\nepochs = 100\nbatch_size = 32\n\nif K.image_data_format() == 'channels_first':\n input_shape = (3, img_width, img_height)\nelse:\n input_shape = (img_width, img_height, 3)\nvgg_conv = InceptionResNetV2(weights='imagenet',\n include_top=False,\n input_shape=(img_width, img_height, 3),\n classes = '1')\n\nmodel = Sequential()\nmodel.add(vgg_conv)\nmodel.add(Flatten())\nmodel.add(Dense(256))\nmodel.add(Activation('relu'))\n#model.add(Dropout(0.5))\nmodel.add(Dense(1))\nmodel.add(Activation('sigmoid')) #sigmoid instead of softmax because of two classes\n\n\n#make the outer layers available for fine tuning\nvgg_conv.trainable = True\nset_trainable = False\nfor layer in vgg_conv.layers:\n if layer.name == 'block5_conv1':\n set_trainable = True\n if set_trainable:\n layer.trainable = True\n else:\n layer.trainable = False\nvgg_conv.summary()\nmodel.summary()\noptimizers.Adam(lr=0.0001, beta_1=0.9, beta_2=0.999, epsilon=None, decay=0.0, amsgrad=False)\nmodel.compile(loss='binary_crossentropy',\t\t#does not suffer from slow convergence when using sigmoid\n optimizer=optimizers.RMSprop(lr=2e-5),\n metrics=['accuracy'])\n# this is the augmentation configuration we will use for training\ntrain_datagen = ImageDataGenerator(\n rescale=1. / 255)\n\n# this is the augmentation configuration we will use for testing:\n# only rescaling\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\n\ntrain_generator = train_datagen.flow_from_directory(\n train_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode='binary')\n\nvalidation_generator = test_datagen.flow_from_directory(\n validation_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode='binary')\n\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch=nb_train_samples // batch_size,\n epochs=epochs,\n validation_data=validation_generator,\n validation_steps=nb_validation_samples // batch_size)\nmodel.save_weights('pretrained_fine_tuned_model.h5')\n","sub_path":"transfer_learning/fine_tuning_transfer_learning_resnet_inception.py","file_name":"fine_tuning_transfer_learning_resnet_inception.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"464892100","text":"import logging as log\nimport pprint\nimport requests\n\nfrom syscore.talkwalker.urls import HOST\nfrom syscore.talkwalker.urls import SEARCH_RESULT_URL\n\n\ndef _to_paged_result(response, total_count, results_pulled_count):\n return {\n \"data\": [\n r[\"data\"]\n for r in response[\"result_content\"][\"data\"]\n ],\n \"result_number\": results_pulled_count,\n \"total_results\": total_count,\n }\n\n\ndef _do_search_request(s, url, params=None):\n res = s.get(\n url=url,\n params=params,\n )\n if res.status_code != 200:\n res.raise_for_status()\n data = res.json()\n if data[\"status_message\"] != \"OK\":\n log.error(\n \"search response status not OK: %s\",\n data[\"status_message\"]\n )\n raise requests.exceptions.RequestException\n return data\n\n\nasync def get_test_search_result(\n s: requests.Session,\n query: str\n):\n \"\"\"\n returns a generator for the entire result set,\n \"\"\"\n results_pulled_count = 0\n first_result = _do_search_request(\n s,\n url=SEARCH_RESULT_URL,\n params={\n \"access_token\": \"demo\",\n \"q\": query,\n }\n )\n results_pulled_count += len(\n first_result[\"result_content\"][\"data\"]\n )\n total_result_count = first_result[\"pagination\"][\"total\"]\n yield _to_paged_result(\n first_result,\n total_result_count,\n results_pulled_count\n )\n result = first_result\n while \"pagination\" in result \\\n and \"next\" in result[\"pagination\"]:\n next_url = result[\"pagination\"][\"next\"].split(\" \")[1]\n result = _do_search_request(\n s,\n url=f\"https://{HOST}{next_url}\"\n )\n results_pulled_count += len(\n result[\"result_content\"][\"data\"]\n )\n yield _to_paged_result(\n result,\n total_result_count,\n results_pulled_count\n )\n","sub_path":"corepy/syscore/syscore/talkwalker/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"575943523","text":"# -*- coding: utf-8 -*-\nimport os\nimport numpy as np\nimport gc\nimport multiprocessing\nimport pandas\nimport datetime\nimport sys\nfrom pandas.errors import EmptyDataError\n\nfrom functools import partial\n\n\n\ndef convert_content(content_string, x_dim, pad_before=True):\n\n int_list = list(map(np.uint8, str(content_string).encode('utf-8')))[:x_dim]\n if len(int_list) < x_dim:\n if pad_before:\n int_list = [np.uint8(0)] * (x_dim - len(int_list)) + int_list # Pad Before\n else:\n int_list = int_list + [np.uint8(0)] * (x_dim - len(int_list)) # Pad After\n\n return int_list\n\n\ndef convert_data(start_index, filename, npy_dir, batch_size, x_dim, pad_before=True, augmentation=1):\n\n try:\n dataframe = pandas.read_csv(filename,\n header=0,\n usecols=[\"src_content\", \"label\"],\n skiprows=list(range(1, start_index)),\n nrows=batch_size,\n engine='python')\n labels = dataframe[\"label\"].values.astype(np.uint8)\n except ValueError:\n dataframe = pandas.read_csv(filename,\n header=0,\n usecols=[\"src_content\"],\n skiprows=list(range(1, start_index)),\n nrows=batch_size,\n engine='python')\n labels = np.array([np.uint8(0)] * dataframe.shape[0])\n\n labels = labels.reshape((labels.shape[0], 1))\n src_content = list(convert_content(x, x_dim=x_dim, pad_before=pad_before)\n for x in dataframe[\"src_content\"].values)\n\n src_content_aug = src_content\n labels_aug = np.concatenate(tuple([labels] * augmentation))\n\n for i in range(1, augmentation):\n if pad_before:\n src_content_aug = src_content_aug + list(\n [np.uint8(0)]*i + content[:-i] for content in src_content\n )\n else:\n src_content_aug = src_content_aug + list(\n content[:-i] + [np.uint8(0)] * i for content in src_content\n )\n\n src_content_aug = np.array(src_content_aug)\n file_no = int(start_index / batch_size)\n if pad_before:\n pad_string = '_prepad'\n else:\n pad_string = '_postpad'\n\n basename = os.path.basename(filename)\n file_extension_index = basename.rfind('.')\n save_basename = basename[:file_extension_index] + pad_string + '_' + str(file_no) + '.npy'\n save_filename = os.path.join(npy_dir, save_basename)\n np.save(save_filename, np.concatenate((src_content_aug, labels_aug), axis=1))\n gc.collect()\n\n return\n\n\ndef convert_file_list(datafile_list, npy_dir, x_dim=1000, pad_before=True, augmentation=1):\n\n processors = int(multiprocessing.cpu_count() / 1.5)\n line_per_processor = int(1048576 / augmentation) # pow(2, 20)\n\n for filepath in datafile_list:\n if pad_before:\n pad_string = '_prepad'\n else:\n pad_string = '_postpad'\n\n filename = os.path.basename(filepath)\n file_extension_index = filename.rfind('.')\n npy_filename = filename[:file_extension_index] + pad_string + \"_0.npy\"\n\n if npy_filename in os.listdir(npy_dir): # Check already parsed npy existence\n continue\n\n try:\n df_temp = pandas.read_csv(filepath, header=0, engine='python')\n except EmptyDataError:\n continue\n\n row_count = df_temp.shape[0]\n del(df_temp)\n gc.collect()\n\n pool = multiprocessing.Pool(processes=processors)\n\n split_size = int(np.ceil(row_count / line_per_processor))\n index_list = list(range(0, split_size*line_per_processor, line_per_processor))\n\n pool.map(partial(convert_data,\n filename=filepath,\n npy_dir=npy_dir,\n batch_size=line_per_processor,\n x_dim=x_dim,\n pad_before=pad_before,\n augmentation=augmentation\n ),\n index_list)\n\n pool.close()\n pool.join()\n gc.collect()\n\n\nif __name__ == \"__main__\":\n\n yesterday = datetime.datetime.today() + datetime.timedelta(days=-1)\n day_before_yesterday = datetime.datetime.today() + datetime.timedelta(days=-2)\n yesterday_string = yesterday.strftime(\"%Y%m%d\")\n day_before_yesterday_string = day_before_yesterday.strftime(\"%Y%m%d\")\n data_dir = \"./data/\"\n npy_dir = \"./npy/\"\n\n payload_file_list = list(os.path.join(data_dir, f)\n for f in os.listdir(data_dir)\n if \"payload\" in f and day_before_yesterday_string in f)\n\n app_file_list = list(os.path.join(data_dir, f)\n for f in os.listdir(data_dir)\n if \"app\" in f and yesterday_string not in f)\n\n label_file_list = list(os.path.join(data_dir, f)\n for f in os.listdir(data_dir)\n if \"INV-APP\" in f and yesterday_string not in f)\n\n convert_file_list(payload_file_list, npy_dir, x_dim=1000, pad_before=True, augmentation=1)\n convert_file_list(app_file_list, npy_dir, x_dim=1000, pad_before=True, augmentation=20)\n convert_file_list(label_file_list, npy_dir, x_dim=1000, pad_before=True, augmentation=20)\n\n","sub_path":"inv_app/inv_app_crd_parse.py","file_name":"inv_app_crd_parse.py","file_ext":"py","file_size_in_byte":5459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"27684253","text":"\n\nimport datetime as dt\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport pandas as pd\nfrom xlrd import XLRDError\nimport strategies_backtester as sb\n\n\nclass IBS:\n # this is an attempt class... still work in progress\n def __init__(self, symbol, ibs_value, range_value):\n self._symbol = symbol\n self._ibs_value = ibs_value\n self._range_value = range_value\n\n def range_value(self):\n return self._range_value\n\n def ibs_value(self):\n return self._ibs_value\n\n def symbol(self):\n return self._symbol\n\n\ndef calculate_IBS(close, low, high):\n return (close - low)/(high - low)\n\n\ndef test_IBS_strategy(dataframes_dictionary, symbol_list, n_buy=1, n_sell=1, minutes_evening=1, minutes_morning=1,\n trigger_threshold=0.2, min_ibs_diff = 0.4, debug_print=False, \n lower_range=0.0050, upper_range=0.1):\n\n strategy_returns = pd.DataFrame()\n\n # make substitution of this with the function created in core.p\n dates_list = sb.dataframes_dictionary_common_dates(dataframes_dictionary, symbol_list)\n\n for date_index in range(len(dates_list)-1):\n ibs_dict = {}\n for symbol in symbol_list:\n symb_day_data = dataframes_dictionary[symbol][dataframes_dictionary[symbol].index.date == dates_list[date_index]]\n \n symb_close = symb_day_data.tail(minutes_evening).ix[0].LAST_PRICE\n symb_high = symb_day_data.head(-(minutes_evening - 1)).HIGH.max()\n symb_low = symb_day_data.head(-(minutes_evening - 1)).LOW.min()\n symb_range = symb_high/symb_low - 1\n ibs_dict[symbol] = (calculate_IBS(symb_close, symb_low, symb_high), symb_range)\n \n # filters ibs_dict keeping just those entries in the desired range\n ibs_dict = {k: v for k, v in ibs_dict.items() if ((abs(v[1]) > lower_range) and (abs(v[1]) < upper_range))}\n\n\n if len(ibs_dict) > (n_buy + n_sell - 1):\n # high_ibs and low_ibs should be changed to lists \n high_ibs_lst = []\n low_ibs_lst = []\n\n #buy symbols and ibs\n for _ in range(n_buy):\n # the ibs values are tuples of tuples (symbol, (ibs_value, symbol range)) obtained by dict.items()\n high_ibs = max(ibs_dict.items(), key=lambda x: x[1][0])\n high_ibs_lst.append(high_ibs)\n ibs_dict.pop(high_ibs[0])\n\n #sell symbols and ibs\n for _ in range(n_sell):\n low_ibs = min(ibs_dict.items(), key=lambda x: x[1][0])\n low_ibs_lst.append(low_ibs)\n ibs_dict.pop(low_ibs[0])\n\n highest_ibs = high_ibs_lst[0]\n lowest_ibs = low_ibs_lst[0]\n ibs_spread = highest_ibs[1][0] - lowest_ibs[1][0]\n range_high_ibs = highest_ibs[1][1]\n range_low_ibs = lowest_ibs[1][1]\n\n # printing lines for debugging\n if debug_print:\n print(\"date: \" + str(dates_list[date_index]))\n print(\"high_ibs: \" + str(highest_ibs))\n print(\"low_ibs: \" + str(lowest_ibs))\n\n # this check is done just on the FIRST element of the two lists high_ibs_lst and low_ibs_lst\n if ((lowest_ibs[1][0] <= trigger_threshold) or ((1 - highest_ibs[1][0]) <= trigger_threshold)) and (ibs_spread > min_ibs_diff): \n\n long_leg_returns_list = []\n short_leg_returns_lits = [] \n\n for ibs_tuple in low_ibs_lst:\n symb_to_buy_day = dataframes_dictionary[ibs_tuple[0]][dataframes_dictionary[ibs_tuple[0]].index.date == dates_list[date_index]] \n symb_to_buy_following_day = dataframes_dictionary[ibs_tuple[0]][dataframes_dictionary[ibs_tuple[0]].index.date == dates_list[date_index + 1]]\n long_leg = (symb_to_buy_following_day.head(minutes_morning).LAST_PRICE.mean() - symb_to_buy_day.tail(minutes_evening).LAST_PRICE.mean())/symb_to_buy_day.tail(minutes_evening).LAST_PRICE.mean()\n long_leg_returns_list.append(long_leg)\n\n for ibs_tuple in high_ibs_lst: \n symb_to_sell_day = dataframes_dictionary[ibs_tuple[0]][dataframes_dictionary[ibs_tuple[0]].index.date == dates_list[date_index]]\n symb_to_sell_following_day = dataframes_dictionary[ibs_tuple[0]][dataframes_dictionary[ibs_tuple[0]].index.date == dates_list[date_index + 1]]\n short_leg = -1 * ((symb_to_sell_following_day.head(minutes_morning).LAST_PRICE.mean() - symb_to_sell_day.tail(minutes_evening).LAST_PRICE.mean())/symb_to_sell_day.tail(minutes_evening).LAST_PRICE.mean())\n short_leg_returns_lits.append(short_leg)\n\n day_result = np.average(long_leg_returns_list) + np.average(short_leg_returns_lits)\n\n day_returns = pd.DataFrame(data={'returns': [day_result], 'highest_ibs': [str(highest_ibs)], 'lowest_ibs': [str(lowest_ibs)], 'ibs_spread': [ibs_spread], 'range_high_ibs' : range_high_ibs, 'range_low_ibs': range_low_ibs}, index=[dates_list[date_index + 1]])\n\n strategy_returns = strategy_returns.append(day_returns)\n\n #printing line for debugging\n if debug_print:\n print(str(lowest_ibs[1] <= trigger_threshold))\n print(str((1 - highest_ibs[1]) <= trigger_threshold))\n print(str((highest_ibs[1] - lowest_ibs[1]) > min_ibs_diff))\n print('return is ' + str(day_result))\n\n return dates_list, strategy_returns\n\n\n\n\n\n","sub_path":"strategies_backtester/ibs_tools.py","file_name":"ibs_tools.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"248371764","text":"# 使用gevent 完成协程多任务\n# pip install gevent\n# gevent 遇到延时操作 就切换\nimport gevent\nimport time\n\n\ndef test01(n):\n for i in range(n):\n print(gevent.getcurrent(), i)\n # time.sleep(1)\n # 遇到延时则切换线程\n gevent.sleep(1)\n\n\ndef test02(n):\n for i in range(n):\n print(gevent.getcurrent(), i)\n time.sleep(1)\n # 遇到延时则切换线程\n gevent.sleep(1)\n\n\ndef test03(n):\n for i in range(n):\n print(gevent.getcurrent(), i)\n time.sleep(1)\n # 遇到延时则切换线程\n gevent.sleep(1)\n\n\ng1 = gevent.spawn(test01, 5)\ng2 = gevent.spawn(test02, 5)\ng3 = gevent.spawn(test03, 5)\n# 耗时的时候 启动切换\n# g1.join()\n# g2.join()\n# g3.join()\n","sub_path":"mine_04_coroutine/mine_07_gevent.py","file_name":"mine_07_gevent.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"299679611","text":"from django.core.mail import EmailMessage\n\n\ndef send_email_notification(title, body, to, attachments=None):\n email = EmailMessage(title, body=body, to=to)\n email.content_subtype = 'html'\n if attachments:\n if isinstance(attachments, list):\n for m in attachments:\n email.attach(m['file_name'], m['file'], m['content_type'])\n else:\n email.attach(attachments['file_name'], attachments['file'], attachments['content_type'])\n email.send()\n\n","sub_path":"Main/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"151544379","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\nin_order_list = [\"D\", \"B\", \"E\", \"A\", \"F\", \"C\"]\npre_order_list = [\"A\", \"B\",\"D\", \"E\", \"C\", \"F\"]\n\ndef search_index(key, list):\n index = 0\n for i in list:\n if i == key:\n return index\n index = index + 1\n if index == len(list):\n print(\"Key not in the list.\")\n return\n\n\ndef construct_tree(in_order_list, pre_order_list):\n root = Node(pre_order_list.pop(0))\n temp = root\n lowest = in_order_list[0]\n\n # going to the extreme left of the tree till the lowest number\n for i in range(search_index(lowest, pre_order_list) + 1):\n temp.left = Node(pre_order_list.pop(0))\n temp = temp.left\n\n\n\n\n\n\n\n\n\n\nconstruct_tree(in_order_list, pre_order_list)\n\n","sub_path":"construct_tree.py","file_name":"construct_tree.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"579528535","text":"'''\nUsage:\n1) To Create\nmerkle_tree = MerkleTree(arity)\nmerkle_tree.createMerkleTree()\n2) To Verify\nverifyMerkleTree(merkle_tree.mrkl_root)\n\n\nEG)newMerkleTree = MerkleTree(2)\nnewMerkleTree.createMerkleTree([\"a\",\"b\",\"c\",\"d\",\"e\",\"f\"])\nprint(verifyMerkleTree(newMerkleTree.mrkl_root))\n'''\n\nfrom utils import getHashValue, verifyMerkleTree\nfrom typing import List\nfrom constants import hashSize\nfrom Transaction import Transaction,TransactionInput,TransactionOutput\nclass MerkleTreeNode:\n def __init__(self,value = \"\") -> None:\n self.hashValue: str = value\n self.nodeList = []\n\n def calculate(self, nodeList):\n self.nodeList = nodeList\n for i in nodeList:\n self.hashValue += i.hashValue\n self.hashValue = getHashValue(self.hashValue, hashSize)\n\n def __eq__(self, other) -> bool :\n if other is None:\n return False\n return self.hashValue == other.hashValue\n\nclass MerkleTree:\n def __init__(self, arity: int = 2) -> None:\n self.mrkl_root: MerkleTreeNode = MerkleTreeNode()\n self.fullTree: List[MerkleTreeNode] = []\n self.arity = arity\n\n def __eq__(self, other) -> bool:\n if other is None:\n return False\n return other.mrkl_root==self.mrkl_root\n\n def getTxnNodes(self, txnList: List[Transaction]) -> List[MerkleTreeNode] :\n txnNodes = []\n for i in txnList:\n txnNodes.append(MerkleTreeNode(i.hash))\n\n return txnNodes\n\n def get_new_level(self, txnNodes: List[MerkleTreeNode]) -> List[MerkleTreeNode]:\n index: int = 0\n newLevel: List[MerkleTreeNode] = []\n while index=len(txnNodes):\n break\n nodeList.append(txnNodes[index])\n index+=1\n newTempNode: MerkleTreeNode = MerkleTreeNode()\n newTempNode.calculate(nodeList)\n newLevel.append(newTempNode)\n\n return newLevel\n\n def createMerkleTree(self, txnList: List[Transaction]):\n txnNodes: List[MerkleTreeNode] = self.getTxnNodes(txnList)\n self.fullTree.extend(txnNodes)\n newLevel: List[MerkleTreeNode] = self.get_new_level(txnNodes)\n self.fullTree.extend(newLevel)\n while len(newLevel)>1:\n newLevel = self.get_new_level(newLevel)\n self.fullTree.extend(newLevel)\n\n self.mrkl_root = newLevel[0]\n\n\n# merkle_tree = MerkleTree(5)\n# # merkle_tree.createMerkleTree([\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\"])\n# print(verifyMerkleTree(merkle_tree.mrkl_root))\n","sub_path":"MerkleTree.py","file_name":"MerkleTree.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"279293445","text":"import pygame\nimport time\nfrom food import Food\nfrom gamestat import GameStat\nimport input\nfrom input import InputManager\nfrom snake import Snake\n\n# pygame.init()\n# games = GameStat(40, 30)\n\n# game_size = (20*games.boardWidth, 20*games.boardHeight)\n# game_display = pygame.display.set_mode(game_size)\n# backgound_img = pygame.image.load(\"black.jpg\")\n\n# red = pygame.Color(255, 0, 0)\n# gray = pygame.Color(196, 196, 196)\n# black = pygame.Color(0, 0, 0)\n# green = pygame.Color(0, 255, 0)\n# blue = pygame.Color(0, 0, 255)\n# white = pygame.Color(255, 255, 255)\n\npygame.init()\nloopbig = True\nwhile loopbig:\n \n games = GameStat(40, 30)\n\n game_size = (20*games.boardWidth, 20*games.boardHeight)\n game_display = pygame.display.set_mode(game_size)\n backgound_img = pygame.image.load(\"black.jpg\")\n\n red = pygame.Color(255, 0, 0)\n gray = pygame.Color(196, 196, 196)\n black = pygame.Color(0, 0, 0)\n green = pygame.Color(0, 255, 0)\n blue = pygame.Color(0, 0, 255)\n white = pygame.Color(255, 255, 255)\n\n level_choose = InputManager()\n font = pygame.font.SysFont(None, 48)\n img = font.render('Please select your level: (0 or 1)', True, blue)\n game_display.blit(img, (20, 20))\n loop = True\n\n font1 = pygame.font.SysFont('chalkduster.ttf', 72)\n img1 = font1.render('chalkduster.ttf', True, blue)\n while loop:\n game_display.blit(img, (20, 20))\n pygame.display.update()\n n = level_choose.getLevel()\n if n==-1:\n pygame.quit()\n if n in [0,1]:\n games.level = n\n loop = False\n \n snake_coords = [[6, 5], [5, 5]]\n my_snake = Snake(snake_coords, 1, 0.1)\n input_manager = InputManager()\n mfood = Food(7, 7)\n games.setUpObstacle()\n\n while games.end==False:\n score = font.render(str(games.score), True, white)\n games.animateObs(game_display)\n input_manager.getEvent()\n mfood.animate(game_display)\n my_snake.changedir(input_manager.move)\n my_snake.animate(game_display, red)\n my_snake.move(games)\n time.sleep(input_manager.speed)\n if my_snake.check_collide(mfood, games)==True:\n games.end=True\n pygame.display.flip()\n\n game_display.blit(backgound_img, (0,0))\n\n loop = True\n while loop:\n input_manager.getEvent()\n score = font.render(\"Your score: \"+str(games.score)+\", press esc to quit, space to restart\", True, white)\n game_display.blit(score, (20, 20))\n pygame.display.update()\n if input_manager.restart == 0:\n loopbig = False\n if input_manager.quit == 1:\n loop = False\n\n\n\n\n\n\n\n\n\n\n","sub_path":"gamen.py","file_name":"gamen.py","file_ext":"py","file_size_in_byte":2661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"626038699","text":"# Somewhat inspired by flameshot\n# TODO\n# - Allow selecting a point on the rectangle so you only move it\n# - Indicate the selection size as metadata on the overlay\n# - Allow setting a temporary screenshot naming scheme\n# - Add command to center the current selection\n# - Configure the screenshot flash color\n# - Possibly save clipped length and width when moving screen boundaries, so\n# when it moves back its going to the original size\n# - Sometimes compass doesn't work, sometimes arrows doesn't work\n# - Bounds checking still needs also check that the width or height does not\n# become negative\n# - Setting for if the crosshair grid is enabled by default\n# - Add numbers to the crosshair grid\n# - Figure out how to speed up closing the canvas, and taking screenshot\n# - Allows cycling windows?\n# - Allow flushing both caches\n# - Make current window selection seamless, it doesn't show the original\n# selection at first\n# - Make mouse snapping go to this center of the mouse?\n\nimport json\nimport pathlib\n\nfrom talon import (\n Context,\n Module,\n actions,\n canvas,\n ctrl,\n screen,\n ui,\n)\nfrom talon.skia import Paint, Rect\nfrom talon.types.point import Point2d\nfrom talon_init import TALON_HOME\n\nmod = Module()\nmod.tag(\n \"shotbox_showing\",\n desc=\"Tag indicates whether shotbox is showing\",\n)\nmod.tag(\"shotbox_enabled\", desc=\"Tag enables shotbox commands.\")\nmod.list(\"points_of_compass\", desc=\"Point of compass for shotbox\")\nmod.list(\"box_multipliers\", desc=\"Multipliers for growing/shrinking the box\")\nmod.list(\"box_dimensions\", desc=\"Box dimensions for multiplication\")\nmod.mode(\"shotbox\", desc=\"Indicate shotbox is active\")\n\nsetting_grow_size = mod.setting(\n \"shotbox_default_grow_size\",\n type=int,\n default=5,\n desc=\"The number of pixels to grow/shrink by default\",\n)\n\nsetting_undo_history_size = mod.setting(\n \"shotbox_undo_history_size\",\n type=int,\n default=100,\n desc=\"The number of box selections to record\",\n)\n\nsetting_screenshot_history_size = mod.setting(\n \"shotbox_screenshot_history_size\",\n type=int,\n default=100,\n desc=\"The number of screenshot selections to record\",\n)\n\nsetting_snap_to_mouse = mod.setting(\n \"shotbox_start_snapped_to_mouse\",\n type=int,\n default=1,\n desc=\"Whether the default selection on start snaps to mouse\",\n)\n\nsetting_default_x = mod.setting(\n \"shotbox_default_x\",\n type=int,\n default=500,\n desc=\"The default X coordinate\",\n)\n\nsetting_default_y = mod.setting(\n \"shotbox_default_y\",\n type=int,\n default=500,\n desc=\"The default Y coordinate\",\n)\n\nsetting_default_width = mod.setting(\n \"shotbox_default_width\",\n type=int,\n default=200,\n desc=\"The default box width\",\n)\n\nsetting_default_height = mod.setting(\n \"shotbox_default_height\",\n type=int,\n default=200,\n desc=\"The default box height\",\n)\n\nsetting_box_color = mod.setting(\n \"shotbox_box_color\",\n type=str,\n default=\"#FF00FF\",\n desc=\"The default box color\",\n)\n\n\nctx = Context()\n\nctx.matches = r\"\"\"\ntag: user.shotbox_enabled\n\"\"\"\n\ndirection_name_steps = [\n \"east\",\n \"south east\",\n \"south\",\n \"south west\",\n \"west\",\n \"north west\",\n \"north\",\n \"north east\",\n]\n\narrow_name_steps = [\"right\", \"down\", \"left\", \"up\"]\n\ndirection_vectors = [Point2d(0, 0) for _ in range(len(direction_name_steps))]\narrow_vectors = [Point2d(0, 0) for _ in range(len(arrow_name_steps))]\n\narrow_vectors[0] = direction_vectors[0] = Point2d(1, 0) # east\narrow_vectors[1] = direction_vectors[2] = Point2d(0, 1) # south\narrow_vectors[2] = direction_vectors[4] = Point2d(-1, 0) # west\narrow_vectors[3] = direction_vectors[6] = Point2d(0, -1) # north\n\n# This edits all single and double entries\nfor i in [1, 3, 5, 7]:\n direction_vectors[i] = (\n direction_vectors[(i - 1) % len(direction_vectors)]\n + direction_vectors[(i + 1) % len(direction_vectors)]\n ) / 2\n\nctx.lists[\"self.points_of_compass\"] = direction_name_steps\nctx.lists[\"self.box_multipliers\"] = [\"double\", \"triple\", \"half\"]\nctx.lists[\"self.box_dimensions\"] = [\"width\", \"length\", \"height\", \"all\"]\n\n\nclass ShotBox:\n def __init__(self, debug=False):\n self.debug = debug\n # XXX - Should this be configurable?\n self.screen_num = 1\n self.screen = None\n self.screen_rect = None\n self.img = None\n self.canvas = None\n self.active = False\n\n # XXX - we don't use the next three fields atm\n self.columns = 0\n self.rows = 0\n self.field_size = 32 # Breaks overlay into 32-pixel blocks\n\n # Theming\n self.overlay_transparency = 155 # Out of 255. +5 because we adjust by 50\n self.overlay_color = \"000000\"\n\n # Caching\n self.selection_history = []\n self.selection_history_idx = 0\n self.screenshot_history = []\n self.screenshot_history_idx = 0\n self.cycle_direction = 1\n self.cache_folder = pathlib.Path(TALON_HOME, \"cache/shotbox/\")\n self.selection_history_file = self.cache_folder / \"selection.json\"\n self.screenshot_history_file = self.cache_folder / \"screenshots.json\"\n self.init_cache()\n\n # Coordinates\n self.x = self.default_x = setting_default_x.get()\n self.y = self.default_y = setting_default_y.get()\n self.width = self.default_width = setting_default_width.get()\n self.height = self.default_height = setting_default_height.get()\n\n def init_cache(self):\n \"\"\"Make sure all cache files and folders exist\"\"\"\n self.cache_folder.mkdir(parents=True, exist_ok=True)\n # XXX - The two below could be copied into one function...\n self.selection_history_file.touch()\n with self.selection_history_file.open() as f:\n try:\n history = json.load(f)\n if len(history) > 0:\n self.selection_history_idx = len(history) - 1\n self.selection_history = history\n except Exception:\n pass\n #print(self.selection_history)\n\n self.screenshot_history_file.touch()\n with self.screenshot_history_file.open() as f:\n try:\n history = json.load(f)\n if len(history) > 0:\n self.screenshot_history_idx = len(history) - 1\n self.screenshot_history = history\n except Exception:\n pass\n #print(self.screenshot_history)\n\n def setup(self, *, rect: Rect = None, screen_num: int = None):\n \"\"\"Initial overlay setup to get screen dimensions, etc\"\"\"\n\n # each if block here might set the rect to None to indicate failure\n selected_screen = None\n if rect is not None:\n try:\n selected_screen = ui.screen_containing(*rect.center)\n except Exception:\n rect = None\n if rect is None and screen_num is not None:\n selected_screen = actions.user.screens_get_by_number(screen_num)\n rect = selected_screen.rect\n if rect is None:\n selected_screen = screen.main_screen()\n rect = selected_screen.rect\n\n self.screen_num = screen_num\n self.screen_rect = rect.copy()\n self.screen = selected_screen\n self.img = None\n if self.canvas is not None:\n self.canvas.close()\n self.canvas = canvas.Canvas.from_screen(selected_screen)\n if self.active:\n self.canvas.register(\"draw\", self.draw_box)\n self.canvas.freeze()\n\n self.columns = int(self.screen_rect.width // self.field_size)\n self.rows = int(self.screen_rect.height // self.field_size)\n\n self.max_x = self.screen_rect.width\n self.max_y = self.screen_rect.height\n self.max_width = self.screen_rect.width\n self.max_height = self.screen_rect.height\n\n def set_selection_rect(self, rect):\n \"\"\"Set the actual coordinates for the rect\"\"\"\n self.set_selection((rect.x, rect.y, rect.width, rect.height))\n\n def set_selection(self, pos):\n \"\"\"Set the actual coordinates for the current selection\"\"\"\n x, y, width, height = pos\n self.x = min(x, self.max_x)\n self.y = min(y, self.max_y)\n self.width = min(width, self.max_width - self.x)\n self.height = min(height, self.max_height - self.y)\n\n def show(self):\n \"\"\"Show the shotbox overlay\"\"\"\n if self.active:\n return\n self.set_selection(self.get_last_selection(direction=0))\n self.canvas.register(\"draw\", self.draw_box)\n self.canvas.freeze()\n self.active = True\n\n def close(self):\n \"\"\"Clear the shotbox overlay\"\"\"\n if not self.active:\n return\n self.canvas.unregister(\"draw\", self.draw_box)\n self.canvas.close()\n self.canvas = None\n self.img = None\n self.active = False\n\n def get_mouse_coordinates(self):\n \"\"\"Get mouse coordinates normalized to the current screen\"\"\"\n mouse_x, mouse_y = ctrl.mouse_pos()\n if mouse_x > self.screen_rect.width:\n mouse_x = mouse_x - self.screen_rect.width\n if mouse_y > self.screen_rect.height:\n mouse_y = mouse_y - self.screen_rect.height\n\n return (mouse_x, mouse_y)\n\n def snap_mouse(self):\n \"\"\"Snap the current selection to the last most cursor\"\"\"\n self.x, self.y = self.get_mouse_coordinates()\n self.commit()\n\n def record_selection(self, pos):\n \"\"\"Record the selection in the history\"\"\"\n # If we record a new selection after a redo, we trash all previous\n # redoable entries\n if (self.selection_history_idx) != len(self.selection_history):\n self.selection_history = self.selection_history[\n : self.selection_history_idx\n ]\n\n if len(self.selection_history) == setting_undo_history_size.get():\n self.selection_history = self.selection_history[1:]\n self.selection_history_idx -= 1\n\n self.selection_history.append(pos)\n self.selection_history_idx += 1\n\n # Commit to file\n with self.selection_history_file.open(\"w+\") as f:\n json.dump(self.selection_history, f)\n\n def default_selection(self):\n \"\"\"Return the ordinates for the default selection\"\"\"\n\n if setting_snap_to_mouse.get() == 1:\n x, y = self.get_mouse_coordinates()\n else:\n x = self.default_x\n y = self.default_y\n\n return (x, y, self.default_width, self.default_height)\n\n def get_last_selection(self, direction=1):\n \"\"\"Return a rectangle to highlight the last or default selection\"\"\"\n if len(self.selection_history) != 0:\n idx = self.selection_history_idx - direction\n if self.debug:\n print(f\"Calculated index: {idx}\")\n print(f\"History length: {len(self.selection_history)}\")\n if idx < 0:\n idx = 0\n elif idx == len(self.selection_history):\n idx = len(self.selection_history) - 1\n if direction == 1:\n x, y, width, height = self.selection_history[idx - 1]\n else:\n x, y, width, height = self.selection_history[idx]\n self.selection_history_idx = idx\n else:\n x, y, width, height = self.default_selection()\n\n return x, y, width, height\n\n def selected_rect(self):\n \"\"\"Return a rectangle of the current selection\"\"\"\n return Rect(self.x, self.y, self.width, self.height)\n\n # XXX - This will only work for duel monitors at the moment?\n def clip_rect(self, rect):\n \"\"\"Clip a rectangle to fit on the current canvas\"\"\"\n\n if rect.x >= self.screen_rect.x or rect.y < self.screen_rect.y:\n new_x = rect.x\n new_y = rect.y\n if rect.x >= self.screen_rect.x:\n new_x = rect.x - self.screen_rect.x\n if rect.y >= self.screen_rect.y:\n new_y = rect.y - self.screen_rect.y\n return Rect(new_x, new_y, rect.width, rect.height)\n else:\n return rect\n\n def unclipped_rect(self):\n \"\"\"Return a rectangle of the current selection without clipping\n to the screen\"\"\"\n return Rect(\n self.screen_rect.x + self.x,\n self.screen_rect.y + self.y,\n self.width,\n self.height,\n )\n\n def unclipped_selection(self):\n \"\"\"Return current selection ordinates without clipping to the screen\"\"\"\n return (\n self.screen_rect.x + self.x,\n self.screen_rect.y + self.y,\n self.width,\n self.height,\n )\n\n def draw_grid(self, canvas):\n \"\"\"Draw the grid over the non-selected portion\"\"\"\n\n # This was largely taken from mouse_guide.py\n SMALL_DIST = 5\n SMALL_LENGTH = 5\n SMALL_COLOR = setting_box_color.get()\n MID_DIST = 10\n MID_LENGTH = 10\n MID_COLOR = setting_box_color.get()\n LARGE_DIST = 50\n LARGE_LENGTH = 20\n LARGE_COLOR = setting_box_color.get()\n canvas.paint.antialias = False\n\n irange = lambda start, stop, step: range(int(start), int(stop), int(step))\n\n rect = self.selected_rect()\n cx, cy = rect.center\n margin = 200 # How many pixels around the box to paint\n\n for tick_dist, tick_length, color in (\n (SMALL_DIST, SMALL_LENGTH, SMALL_COLOR),\n (MID_DIST, MID_LENGTH, MID_COLOR),\n (LARGE_DIST, LARGE_LENGTH, LARGE_COLOR),\n ):\n\n half = tick_length // 2\n canvas.paint.color = color\n # top\n for y in irange(rect.top - margin - 1, rect.top - 1, tick_dist):\n canvas.draw_line(cx - half, y, cx + half, y)\n # bottom\n for y in irange(rect.bot + tick_dist, rect.bot + margin + 1, tick_dist):\n canvas.draw_line(cx - half, y, cx + half, y)\n # left\n for x in irange(rect.left - margin - 1, rect.left - 1, tick_dist):\n canvas.draw_line(x, cy - half, x, cy + half)\n # right\n for x in irange(rect.right + tick_dist, rect.right + margin + 1, tick_dist):\n canvas.draw_line(x, cy - half, x, cy + half)\n\n def draw_box(self, canvas):\n \"\"\"Draw an updated canvas\"\"\"\n paint = canvas.paint\n\n # for other-screen or individual-window grids\n # XXX - What is this? Clips the main rectangle boundaries?\n canvas.translate(self.screen_rect.x, self.screen_rect.y)\n canvas.clip_rect(\n Rect(\n -self.field_size * 2,\n -self.field_size * 2,\n self.screen_rect.width + self.field_size * 4,\n self.screen_rect.height + self.field_size * 4,\n )\n )\n # At any given time there are 4 darkened rectangles, and this\n # selection rectangle\n selection_rect = self.selected_rect()\n canvas.paint.color = self.overlay_color + hex_to_string(35)\n canvas.paint.style = Paint.Style.FILL\n\n # We need to be more careful if this selection dimensions are\n # already on zero?\n overlay_top_x = 0\n overlay_top_y = 0\n overlay_top_width = self.screen_rect.width\n overlay_top_height = selection_rect.y\n overlay_top_rect = Rect(\n overlay_top_x, overlay_top_y, overlay_top_width, overlay_top_height\n )\n if self.debug:\n print(\"Top:\")\n print(overlay_top_rect)\n\n overlay_left_x = 0\n overlay_left_y = selection_rect.y\n overlay_left_width = selection_rect.x\n overlay_left_height = selection_rect.height\n overlay_left_rect = Rect(\n overlay_left_x, overlay_left_y, overlay_left_width, overlay_left_height\n )\n if self.debug:\n print(\"Left:\")\n print(overlay_left_rect)\n\n overlay_right_x = selection_rect.x + selection_rect.width\n overlay_right_y = selection_rect.y\n overlay_right_width = self.screen_rect.width - overlay_right_x\n overlay_right_height = selection_rect.height\n overlay_right_rect = Rect(\n overlay_right_x, overlay_right_y, overlay_right_width, overlay_right_height\n )\n if self.debug:\n print(\"Right:\")\n print(overlay_right_rect)\n\n overlay_bottom_x = 0\n overlay_bottom_y = selection_rect.y + selection_rect.height\n overlay_bottom_width = self.screen_rect.width\n overlay_bottom_height = self.screen_rect.height - overlay_bottom_y\n overlay_bottom_rect = Rect(\n overlay_bottom_x,\n overlay_bottom_y,\n overlay_bottom_width,\n overlay_bottom_height,\n )\n if self.debug:\n print(\"Bottom:\")\n print(overlay_bottom_rect)\n\n canvas.paint.color = self.overlay_color + hex_to_string(\n self.overlay_transparency\n )\n canvas.paint.style = Paint.Style.FILL\n\n canvas.draw_rect(overlay_top_rect)\n canvas.draw_rect(overlay_bottom_rect)\n canvas.draw_rect(overlay_left_rect)\n canvas.draw_rect(overlay_right_rect)\n\n canvas.paint.style = Paint.Style.FILL\n canvas.paint.color = setting_box_color.get()\n margin = 0\n # XXX - Add the margins, and use leftmost = self.x + margin\n # See talon_hud\n canvas.draw_line(self.x, self.y, self.x + self.width, self.y)\n canvas.draw_line(self.x, self.y, self.x, self.y + self.height)\n canvas.draw_line(\n self.x + self.width, self.y, self.x + self.width, self.y + self.height\n )\n canvas.draw_line(\n self.x, self.y + self.height, self.x + self.width, self.y + self.height\n )\n\n # XXX - circle should be configurable\n # top circles\n canvas.draw_circle(self.x, self.y, 5, None)\n canvas.draw_circle(self.x + (self.width / 2), self.y, 5, None)\n canvas.draw_circle(self.x + self.width, self.y, 5, None)\n # side circles\n canvas.draw_circle(self.x, self.y + (self.height / 2), 5, None)\n canvas.draw_circle(self.x + self.width, self.y + (self.height / 2), 5, None)\n # bottom circles\n canvas.draw_circle(self.x, self.y + self.height, 5, None)\n canvas.draw_circle(self.x + (self.width / 2), self.y + self.height, 5, None)\n canvas.draw_circle(self.x + self.width, self.y + self.height, 5, None)\n\n self.draw_grid(canvas)\n\n def adjust(self, direction, size):\n \"\"\"Adjust the size of the overlay in direction specified.\n\n Note that the direction meaning is inverse during shrinkage, because if\n you say shrink up you don't actually want that top to shrink...\n \"\"\"\n\n # No explicit direction means adjust in all directions\n if direction == \"\":\n self.x = self.x - size\n self.y = self.y - size\n # *2 because the sizes will already be adjusted by the new x,y\n self.width = self.width + (size * 2)\n self.height = self.height + (size * 2)\n else:\n if direction.startswith(\"north\") or direction == \"up\":\n if size < 0:\n # Shrinking\n self.height = self.height + size\n else:\n # Growing\n self.y = self.y - size\n self.height = self.height + size\n if direction.startswith(\"south\") or direction == \"down\":\n if size < 0:\n # Shrinking\n self.y = self.y - size\n self.height = self.height + size\n else:\n # Growing\n self.height = self.height + size\n if \"east\" in direction or direction == \"right\":\n if size < 0:\n # Shrinking\n self.x = self.x - size\n self.width = self.width + size\n\n else:\n self.width = self.width + size\n if \"west\" in direction or direction == \"left\":\n if size < 0:\n # Shrinking\n\n self.width = self.width + size\n else:\n self.x = self.x - size\n self.width = self.width + size\n\n self.commit()\n\n def set_x(self, x):\n \"\"\"Set the x coordinate of the current selection\"\"\"\n self.x = x\n self.commit()\n\n def set_y(self, y):\n \"\"\"Set the y coordinate of the current selection\"\"\"\n self.y = y\n self.commit()\n\n def set_width(self, width):\n \"\"\"Set the width of the current selection\"\"\"\n self.width = width\n self.commit()\n\n def set_height(self, height):\n \"\"\"Set the height of the current selection\"\"\"\n self.height = height\n self.commit()\n\n def set_size(self, width, height):\n \"\"\"Set the width and height of the current selection\"\"\"\n self.width = width\n self.height = height\n self.commit()\n\n def move(self, direction, count):\n global direction_name_steps\n global direction_vectors\n global arrow_name_steps\n global arrow_vectors\n if direction in direction_name_steps:\n index = direction_name_steps.index(direction)\n point = direction_vectors[index]\n else:\n index = arrow_name_steps.index(direction)\n point = arrow_vectors[index]\n\n self.x = self.x + (point.x * count)\n self.y = self.y + (point.y * count)\n self.commit()\n\n def reset(self):\n \"\"\"Reset the selection to the default boundaries\"\"\"\n self.set_selection(self.default_selection())\n self.commit()\n\n def commit(self):\n \"\"\"Commit the coordinate adjustments\"\"\"\n # We do this to do a boundary sanitation pass\n self.set_selection((self.x, self.y, self.width, self.height))\n self.record_selection((self.x, self.y, self.width, self.height))\n self.canvas.freeze()\n\n def screenshot(self):\n \"\"\"Take a screenshot of the current selection\"\"\"\n\n if len(self.screenshot_history) == setting_screenshot_history_size.get():\n self.screenshot_history = self.screenshot_history[1:]\n\n # XXX - This should record this screen number and coordinates\n self.screenshot_history.append((self.x, self.y, self.width, self.height))\n self.screenshot_history_idx += 1\n with self.screenshot_history_file.open(\"w+\") as f:\n json.dump(self.screenshot_history, f)\n\n # XXX - if I don't just completely disable it, it seems to race with\n # this screenshot taking and sleeps are not super reliable (unless\n # their painfully long)\n self.disable()\n rect = self.unclipped_rect()\n actions.user.screenshot_rect(rect, screen_num=self.screen_num)\n self.screenshot_history_idx = -1\n\n def screenshot_next(self):\n \"\"\"Cycle to the next screenshot based off the previously used direction\"\"\"\n self.screenshot_cycle(self.cycle_direction)\n\n # XXX - it would be nice to show which screenshot in the text somewhere\n def screenshot_cycle(self, direction):\n \"\"\"Cycle to the next screenshot in the specified direction\"\"\"\n if len(self.screenshot_history) == 0:\n return\n self.cycle_direction = direction\n idx = self.screenshot_history_idx\n if idx == -1:\n idx = len(self.screenshot_history) - 1\n else:\n if direction > 0:\n idx -= 1\n elif direction < 0:\n idx += 1\n\n self.screenshot_select(idx)\n\n def screenshot_select(self, idx):\n self.screenshot_history_idx = idx\n self.set_selection(self.screenshot_history[self.screenshot_history_idx])\n self.commit()\n\n def undo(self):\n \"\"\"Undo the last selection modification\"\"\"\n if len(self.selection_history) == 0:\n return\n self.set_selection(self.get_last_selection(1))\n self.canvas.freeze()\n\n def redo(self):\n \"\"\"Redo the last selection modification\"\"\"\n if self.selection_history_idx == len(self.selection_history):\n return\n self.set_selection(self.get_last_selection(-1))\n self.canvas.freeze()\n\n def mouse_drag(self, modifiers=None):\n \"\"\"Drag the mouse across the current selection\"\"\"\n x, y, width, height = self.unclipped_selection()\n start_x = x\n start_y = y\n end_x = x + width\n end_y = y + height\n self.disable()\n\n ctrl.mouse_move(\n start_x,\n start_y,\n )\n\n ctrl.mouse_click(0, down=True)\n # Let the underlying application react\n actions.sleep(0.05)\n ctrl.mouse_move(\n end_x,\n end_y,\n )\n ctrl.mouse_click(0, up=True)\n\n def disable(self):\n \"\"\"Disable the shotbox overlay\"\"\"\n # XXX - I don't like that this access is context\n global ctx\n ctx.tags = []\n self.close()\n shotbox_mode_disable()\n\n\ndef hex_to_string(v: int) -> str:\n \"\"\"Convert hexadecimal integer to string-based transparency hex value\"\"\"\n return f\"{v:x}\"\n\n\nshotbox = ShotBox(debug=False)\n\n\ndef shotbox_mode_enable():\n \"\"\"Enable shotbox\"\"\"\n actions.mode.enable(\"user.shotbox\")\n actions.mode.disable(\"command\")\n\n\ndef shotbox_mode_disable():\n \"\"\"Disable shotbox\"\"\"\n actions.mode.disable(\"user.shotbox\")\n actions.mode.enable(\"command\")\n\n\n@mod.action_class\nclass ShotBoxActions:\n def shotbox_activate():\n \"\"\"Show the shotbox overlay on default screen\"\"\"\n if not shotbox.canvas:\n shotbox.setup()\n shotbox.show()\n ctx.tags = [\"user.shotbox_showing\"]\n shotbox_mode_enable()\n\n def shotbox_activate_win():\n \"\"\"Show the shotbox overlay on default screen, highlighting active window\"\"\"\n actions.user.shotbox_activate()\n win = ui.active_window()\n shotbox.set_selection(shotbox.clip_rect(win.rect))\n shotbox.commit()\n\n def selection_shotbox_screen(screen_num: int):\n \"\"\"Brings up overlay on the specified screen\"\"\"\n shotbox.setup(screen_num=screen_num)\n shotbox.show()\n ctx.tags = [\"user.shotbox_showing\"]\n shotbox_mode_enable()\n\n def shotbox_close():\n \"\"\"Close the active shotbox overlay\"\"\"\n if shotbox.active:\n ctx.tags = []\n shotbox.close()\n shotbox_mode_disable()\n\n def shotbox_snap_mouse():\n \"\"\"Snap the current selection to the mouse cursor\"\"\"\n shotbox.snap_mouse()\n\n def shotbox_grow(direction: str, size: int):\n \"\"\"Increase the size of the selection from all angles\"\"\"\n if size == -1:\n size = setting_grow_size.get()\n shotbox.adjust(direction, size)\n\n def shotbox_shrink(direction: str, size: int):\n \"\"\"Decrease the size of the selection from all angles\"\"\"\n if size == -1:\n size = setting_grow_size.get()\n shotbox.adjust(direction, -size)\n\n def shotbox_move(direction: str, count: int):\n \"\"\"Move the selection in some direction\"\"\"\n if count == -1:\n count = setting_grow_size.get()\n shotbox.move(direction, count)\n\n def shotbox_screenshot():\n \"\"\"Take a screenshot of the current selection\"\"\"\n shotbox.screenshot()\n\n def shotbox_set_x(x: int):\n \"\"\"Set the x coordinate of the current selection\"\"\"\n shotbox.set_x(x)\n\n def shotbox_set_y(y: int):\n \"\"\"Set the y coordinate of the current selection\"\"\"\n shotbox.set_y(y)\n\n def shotbox_set_width(width: int):\n \"\"\"Set the width of the current selection\"\"\"\n shotbox.set_width(width)\n\n def shotbox_set_height(height: int):\n \"\"\"Set the height of the current selection\"\"\"\n shotbox.set_height(height)\n\n def shotbox_set_size(width: int, height: int):\n \"\"\"Set the width and height of the current selection\"\"\"\n shotbox.set_size(width, height)\n\n def shotbox_reset():\n \"\"\"Reset the selection to the default\"\"\"\n shotbox.reset()\n\n def shotbox_grow_multiply(multiplier: str, direction: str):\n \"\"\"Adjust the box by a multiplayer\"\"\"\n multipliers = {\"double\": 2, \"triple\": 3, \"half\": 1.5}\n m = multipliers[multiplier]\n if direction == \"width\" or direction == \"length\":\n shotbox.set_width(shotbox.width * m)\n elif direction == \"height\":\n shotbox.set_height(shotbox.height * m)\n elif direction == \"all\":\n shotbox.set_width(shotbox.width * m)\n shotbox.set_height(shotbox.height * m)\n\n def shotbox_shrink_multiply(multiplier: str, direction: str):\n \"\"\"Adjust the box by a multiplayer\"\"\"\n multipliers = {\"double\": 0.5, \"triple\": 0.25, \"half\": 0.5}\n m = multipliers[multiplier]\n if direction == \"width\" or direction == \"length\":\n shotbox.set_width(shotbox.width * m)\n elif direction == \"height\":\n shotbox.set_height(shotbox.height * m)\n elif direction == \"all\":\n shotbox.set_width(shotbox.width * m)\n shotbox.set_height(shotbox.height * m)\n\n def shotbox_undo():\n \"\"\"Undo the last selection modification\"\"\"\n shotbox.undo()\n\n def shotbox_redo():\n \"\"\"Redo the last selection modification\"\"\"\n shotbox.redo()\n\n def shotbox_mouse_drag():\n \"\"\"Drag the mouse over the current selection box\"\"\"\n shotbox.mouse_drag()\n\n def shotbox_screenshot_cycle_next():\n \"\"\"Cycle to the next screenshot based off the previous direction\"\"\"\n shotbox.screenshot_next()\n\n def shotbox_screenshot_cycle_older():\n \"\"\"Cycle to the next oldest screenshot based off the previous direction\"\"\"\n shotbox.screenshot_cycle(-1)\n\n def shotbox_screenshot_cycle_newer():\n \"\"\"Cycle to the next newer screenshot based off the previous direction\"\"\"\n shotbox.screenshot_cycle(1)\n\n def shotbox_screenshot_cycle_first():\n \"\"\"Cycle to the first screenshot in the cache\"\"\"\n shotbox.screenshot_select(0)\n\n def shotbox_screenshot_cycle_last():\n \"\"\"Cycle to the last screenshot in the cache\"\"\"\n shotbox.screenshot_select(len(shotbox.screenshot_history) - 1)\n","sub_path":"plugin/shotbox/shotbox.py","file_name":"shotbox.py","file_ext":"py","file_size_in_byte":30497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"363578390","text":"import numpy as np\nimport cv2\nimport os\nimport json\n\nfrom util import (\n getRep,\n getPeople\n)\n\nfrom bottle import (\n get,\n post,\n request,\n response,\n default_app,\n BaseRequest\n )\n\nBaseRequest.MEMFILE_MAX = 1e8\n\n@get('/')\ndef default_get():\n return static_file(\"index.html\", \".\")\n\n@get('/')\ndef get_face(uid):\n f = glob.glob(\"/root/data/images/{}/*\".format(uid))\n return static_file(f[0], '/')\n\n@post('/')\ndef compare_image():\n if request.files.get('pic'):\n binary_data = request.files.get('pic').file.read()\n else:\n binary_data = request.body.read()\n\n img_array = np.asarray(bytearray(binary_data), dtype=np.uint8)\n image_data = cv2.imdecode(img_array, cv2.IMREAD_COLOR)\n response.content_type = 'application/json'\n if image_data is None:\n response.status = 200\n return {'error': 'Unable to decode posted image!'}\n try:\n people = getPeople(image_data)\n person = sorted(people, key=lambda p: p['face_size'])[-1]\n if person['confidence'] > 0.9:\n return json.dumps({\n 'name': person['uid'],\n 'message': 'welcome ' + person['uid']\n }, indent=4)\n else:\n return json.dumps({\n 'name': person['uid'],\n 'message': 'welcome ' + person['uid']\n }, indent=4)\n\n except Exception as e:\n response.status = 200\n return {'error': str(e)}\n\nport = int(os.environ.get('PORT', 8080))\n\nif __name__ == \"__main__\":\n run(host='0.0.0.0', port=port, debug=True, server='gunicorn', workers=4)\n\napp = default_app()\n","sub_path":"web_server.py","file_name":"web_server.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"75439929","text":"from bs4 import BeautifulSoup\nimport pandas as pd\n\nimport urllib2\nimport argparse\nimport os\nimport datetime\nimport sys\n\nparser = argparse.ArgumentParser(description='Dealership')\nparser.add_argument('--pages', action=\"store\", dest=\"pages\", default=1)\nparser.add_argument('--sort', action=\"store\", dest=\"sort\", default=None)\nargs = parser.parse_args()\n\ncars = []\n\n_image = []\n_price = []\n_model = []\n_type = []\n_year = []\n_mileage = []\n_gearbox = []\n_dealer = []\n_suburb = []\n\n\ndef getCarsOnPage(page):\n page = urllib2.urlopen('/cars-for-sale?pagenumber='+str(page)+'&sortorder=Newest')\n soup = BeautifulSoup(page, features=\"html.parser\")\n\n updateCarDetails(soup)\n\n\ndef updateCarDetails(warm_soup):\n\n for car in warm_soup.find_all('div', attrs={'class' : 'b-result-tile'}):\n cars.append(car)\n\n for car in cars:\n details = [x for x in car.stripped_strings]\n\n if len(details) >= 10:\n _image.append(car.a['href'])\n _price.append(details[0])\n _model.append(details[1])\n _type.append(details[2])\n _year.append(details[3])\n _mileage.append(details[4])\n _gearbox.append(details[5])\n _dealer.append(details[7])\n _suburb.append(details[8])\n\ndef Datetime():\n return str(datetime.datetime.now()).replace(':','').replace('-','').replace('.','').replace(' ','')\n\ndef progressBar(value, endvalue, bar_length=20):\n\n percent = float(value) / endvalue\n arrow = '-' * int(round(percent * bar_length)-1) + '>'\n spaces = ' ' * (bar_length - len(arrow))\n\n sys.stdout.write(\"\\rDownloading : [{0}] {1}%\".format(arrow + spaces, int(round(percent * 100))))\n sys.stdout.flush()\n\ndef main():\n \n pages = int(args.pages)\n\n for i in range(1,pages+1):\n getCarsOnPage(i)\n progressBar(i,pages)\n\n print('')\n\n table = pd.DataFrame(data={'Model' : _model, 'Price' : _price, 'Type' : _type, 'Year' : _year, 'Mileage' : _mileage, 'Gearbox' : _gearbox, 'Dealer' : _dealer, 'Suburb' : _suburb})\n table.drop_duplicates(inplace=True)\n\n if args.sort:\n table.sort_values(by=[args.sort], inplace=True)\n\n print(table)\n \n file = '\\\\cars_'+str(len(cars))+'_'+Datetime()+'.json'\n\n table.to_json(path_or_buf=os.getcwd()+file, orient='records',)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"CarDB_Data.py","file_name":"CarDB_Data.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"160976061","text":"import json\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument(\"file\", help=\"The name of the JSON file to read.\")\nargs = parser.parse_args()\n\nif (args.file):\n f = args.file\n print(\"Reading JSON: {} ...\".format(f))\n with open(f,encoding=\"utf8\") as json_data:\n \tdata = json.load(json_data)\n \t# number of images stored into the JSOn file\n total_images = data['count']\n print( \"{} total images in the file\".format(total_images))\n # array of images descriptions\n images = data['images']\n #for i in images:\n # print(\"Name: {}\".format(i['name']))\n","sub_path":"storage/backup-images/read-images.py","file_name":"read-images.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"516920745","text":"\n\nfrom the_tale.game.balance import constants as c\n\n\nclass PoliticPower(object):\n __slots__ = ('outer_power', 'inner_power', 'inner_circle', '_inner_positive_heroes', '_inner_negative_heroes')\n INNER_CIRCLE_SIZE = None\n POWER_REMOVE_BARRIER = 1\n\n def __init__(self, outer_power, inner_power, inner_circle):\n self.outer_power = outer_power\n self.inner_power = inner_power\n self.inner_circle = inner_circle\n\n self.reset_cache()\n\n\n @classmethod\n def create(cls):\n return cls(outer_power=0, inner_power=0, inner_circle={})\n\n def reset_cache(self):\n self._inner_positive_heroes = None\n self._inner_negative_heroes = None\n\n @property\n def inner_positive_heroes(self):\n if self._inner_positive_heroes is None:\n self.update_inner_heroes()\n\n return self._inner_positive_heroes\n\n @property\n def inner_negative_heroes(self):\n if self._inner_negative_heroes is None:\n self.update_inner_heroes()\n\n return self._inner_negative_heroes\n\n @property\n def positive_heroes_number(self):\n return len([power for power in self.inner_circle.values() if power > 0 ])\n\n @property\n def negative_heroes_number(self):\n return len([power for power in self.inner_circle.values() if power < 0 ])\n\n def serialize(self):\n return {'outer_power': self.outer_power,\n 'inner_power': self.inner_power,\n 'inner_circle': self.inner_circle}\n\n @classmethod\n def deserialize(cls, data):\n return cls(outer_power=data['outer_power'],\n inner_power=data['inner_power'],\n inner_circle={int(account_id): power for account_id, power in data['inner_circle'].items()})\n\n def ui_info(self, all_powers):\n return {'power': {'inner': {'value': self.inner_power,\n 'fraction': self.inner_power_fraction(all_powers)},\n 'outer': {'value': self.outer_power,\n 'fraction': self.outer_power_fraction(all_powers)},\n 'fraction': self.total_politic_power_fraction(all_powers)},\n 'heroes': {'positive': {hero_id: self.inner_circle[hero_id] for hero_id in self.inner_positive_heroes},\n 'negative': {hero_id: self.inner_circle[hero_id] for hero_id in self.inner_negative_heroes}}}\n\n def inner_accounts_ids(self):\n return self.inner_circle.keys()\n\n def inner_circle_rating(self):\n return sorted(self.inner_circle.items(), key=lambda x: abs(x[1]), reverse=True)\n\n def change_power(self, owner, hero_id, has_in_preferences, power):\n\n if (hero_id is None or\n not has_in_preferences):\n self.outer_power += power\n return\n\n self.reset_cache()\n\n self.inner_power += power\n self.inner_circle[hero_id] = self.inner_circle.get(hero_id, 0) + power\n\n owner.job.give_power(power)\n\n def job_effect_kwargs(self, owner):\n raise NotImplementedError()\n\n def sync_power(self):\n remove_candidates = set()\n\n for hero_id, power in self.inner_circle.items():\n new_power = power * c.PLACE_POWER_REDUCE_FRACTION\n self.inner_circle[hero_id] = new_power\n\n if abs(new_power) <= self.POWER_REMOVE_BARRIER:\n remove_candidates.add(hero_id)\n\n for hero_id in remove_candidates:\n del self.inner_circle[hero_id]\n\n self.inner_power *= c.PLACE_POWER_REDUCE_FRACTION\n self.outer_power *= c.PLACE_POWER_REDUCE_FRACTION\n\n self.reset_cache()\n\n def is_in_inner_circle(self, hero_id):\n\n if self._inner_positive_heroes is None:\n self.update_inner_heroes()\n\n return hero_id in self._inner_positive_heroes or hero_id in self._inner_negative_heroes\n\n # TODO: can be optimized by used memory\n def update_inner_heroes(self):\n positive_heroes = []\n negative_heroes = []\n\n for hero_id, power in self.inner_circle.items():\n if power > 0:\n positive_heroes.append((power, hero_id))\n else:\n negative_heroes.append((-power, hero_id))\n\n positive_heroes.sort()\n negative_heroes.sort()\n\n self._inner_positive_heroes = frozenset((hero_id for power, hero_id in positive_heroes[-self.INNER_CIRCLE_SIZE:]))\n self._inner_negative_heroes = frozenset((hero_id for power, hero_id in negative_heroes[-self.INNER_CIRCLE_SIZE:]))\n\n def inner_power_fraction(self, all_powers):\n # находим минимальное отрицательное влияние и компенсируем его при расчёте долей\n minimum_power = 0.0\n\n for obj in all_powers:\n minimum_power = min(minimum_power, obj.inner_power)\n\n total_power = 0.0\n\n for obj in all_powers:\n total_power += (obj.inner_power - minimum_power)\n\n return ((self.inner_power - minimum_power) / total_power) if total_power else 0\n\n def outer_power_fraction(self, all_powers):\n # находим минимальное отрицательное влияние и компенсируем его при расчёте долей\n minimum_power = 0.0\n\n for obj in all_powers:\n minimum_power = min(minimum_power, obj.outer_power)\n\n total_power = 0.0\n\n for obj in all_powers:\n total_power += (obj.outer_power - minimum_power)\n\n return ((self.outer_power - minimum_power) / total_power) if total_power else 0\n\n def total_politic_power_fraction(self, all_powers):\n return (self.inner_power_fraction(all_powers) + self.outer_power_fraction(all_powers)) / 2\n\n def __str__(self): return '{}, {}'.format(self.outer_power, self.inner_power)\n","sub_path":"src/the_tale/the_tale/game/politic_power.py","file_name":"politic_power.py","file_ext":"py","file_size_in_byte":5865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"26023746","text":"from pymongo_connect import connectToMongoDB\n\n[mydb,mycol] = connectToMongoDB()\n\n# 向集合中插入一条数据\n#mydict = {\"name\":\"npm\",\"url\":\"https://www.npm.org\"}\n#x = mycol.insert_one(mydict)\n# 返回插入的文档的id值\n#print(x.inserted_id)\n\n# 插入多条数据\nmylist = [\n {\"name\":\"taobao\",\"url\":\"https://www.taobao.com\"},\n {\"name\":\"facebook\",\"url\":\"https://www.facebook.com\"},\n {\"name\":\"github\",\"utl\":\"https://www.github.com\"}\n]\nx = mycol.insert_many(mylist)\n# 返回插入的文档的ids值\nprint(x.inserted_ids)\n","sub_path":"pymongo/pymongo_insert.py","file_name":"pymongo_insert.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"495339126","text":"#! python2\n# -*- coding: utf-8 -*-\n\"\"\"\nclass SVNRepo:\n @classmethod\n def isBadVersion(cls, id)\n # Run unit tests to check whether verison `id` is a bad version\n # return true if unit tests passed else false.\nYou can use SVNRepo.isBadVersion(10) to check whether version 10 is a\nbad version.\n\"\"\"\n\n\nclass Solution:\n \"\"\"\n @param: n: An integer\n @return: An integer which is the first bad version.\n \"\"\"\n def findFirstBadVersion(self, n):\n # write your code here\n if n is None:\n return -1\n if SVNRepo.isBadVersion(1) is True:\n return 1\n\n start, end = 1, n\n while start + 1 < end:\n mid = start + (end - start) / 2\n if SVNRepo.isBadVersion(mid) is False:\n start = mid\n else:\n end = mid\n\n return end\n\n\nif __name__ == \"__main__\":\n A=5\n print(Solution().findFirstBadVersion(A))\n","sub_path":"Python/Algorithms-in-Python/208_FindFirst.py","file_name":"208_FindFirst.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"23516174","text":"\n# coding: utf-8\n\n# In[213]:\n\n\n## PROGRAMA CREADO POR JUAN MOLINA\n## INTELIGENCIA ARTIFICIAL, 5TO SEMESTRE.\n\nfrom math import sqrt\n\n## VARIABLES GLOBALES INICIO ##\nlista = [17, 15, 23, 7, 9, 13]\nlongitudLista = len(lista)\nlistaOrdenada = sorted(lista)\nLongitudListaOrdenada = len(listaOrdenada)\n## VARIABLES GLOBALES FIN ##\n\n## FUNCION PROMEDIO\ndef _promedio():\n promedio = sum(lista) / longitudLista\n return promedio\n\n## FUNCION MODA\ndef _moda():\n moda = []\n seRepite = 0\n for i in lista:\n if lista.count(i) > seRepite:\n seRepite = lista.count(i)\n \n for i in lista:\n if lista.count(i) == seRepite and i not in moda:\n moda.append(i)\n \n if moda == lista:\n moda = 'Hay más de un dato que se repite.'\n return moda\n\n## FUNCION MEDIANA\ndef _mediana():\n if longitudLista % 2 == 0:\n mediana = (listaOrdenada[(LongitudListaOrdenada // 2) - 1] + listaOrdenada[LongitudListaOrdenada // 2]) // 2\n else:\n mediana = listaOrdenada[LongitudListaOrdenada // 2]\n return mediana\n\n## FUNCION VARIANZA\ndef _varianza():\n resta = []\n mediaMuestra = sum(lista) // longitudLista\n for i in lista:\n resta.append(pow((i - mediaMuestra), 2))\n sumaOperacion = sum(resta)\n varianza = sumaOperacion / (longitudLista - 1)\n return varianza\n\n## FUNCION DESVIACION ESTANDAR\ndef _desviacionEstandar():\n desviacionEstandar = sqrt(_varianza())\n return desviacionEstandar\n\nprint()\nprint(\"------------------------------------------------\")\nprint(\"Lista:\", lista)\nprint(\"Lista Ordenada:\", listaOrdenada)\nprint(\"------------------------------------------------\")\nprint(\"Total Datos:\", longitudLista)\nprint(\"Promedio:\", _promedio())\nprint(\"------------------------------------------------\")\nprint(\"Dato que más se repite (MODA):\", _moda())\nprint(\"------------------------------------------------\")\nprint(\"Dato central (MEDIANA):\", _mediana())\nprint(\"------------------------------------------------\")\nprint(\"Varianza:\", _varianza())\nprint(\"------------------------------------------------\")\nprint(\"Desviación Estandar:\", _desviacionEstandar())\nprint(\"------------------------------------------------\")\n\n","sub_path":"TALLER1/TALLER.py","file_name":"TALLER.py","file_ext":"py","file_size_in_byte":2207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"481616466","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n\n# Intercala_Arquivos.py\n# \n# Copyright 2015 Danilo de Oliveira \n# Versão para arquivos.\n# \nimport sys\n\ndef get_menor_elem(lstposicoes, MAT):\n\t\n\ttemp_list = []\n\t\n\tfor i in range(len(lstposicoes)):\n\t\tMAT[i].seek(lstposicoes[i])\n\t\ttemp_list.append(int(MAT[i].readline()))\n\t\n\tmenor = min(temp_list)\n\t\n\treturn menor,temp_list.index(menor)\n\n\ndef intercala(param_list_arquivos):\n\tMAT = []\n\n\tfor diretorio in param_list_arquivos:\n\t\tMAT.append(open(diretorio,'rt'))\n\n\n\tarqSaida = open('arq_intercalado.txt','wt')\n\n\tlstposicoes = [0] * len(MAT)\n\t\t\n\twhile len(MAT) != 0:\n\t\tm, indice = get_menor_elem(lstposicoes, MAT)\n\t\tarqSaida.write(str(m)+'\\n')\n\n\t\tlstposicoes[indice] = MAT[indice].tell()\n\n\t\tif MAT[indice].readline() == '':\n\t\t\tMAT[indice].close()\n\t\t\tdel MAT[indice]\n\t\t\tdel lstposicoes[indice]\n\n\tarqSaida.close()\n\n\treturn 0\n\n\n\ndef main():\n\t\n\t# OBS: Funciona via linha de comando. Considere cada arquivo cujo cada linha é um inteiro seguido de um \\n. Tem que estar em ordem crescente.\n\tintercala(sys.argv[1:])\n\t\n\t\n\treturn 0\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"Algoritmos/Ordena_Arquivo.py","file_name":"Ordena_Arquivo.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"513541853","text":"\n#-*- coding:utf-8 _*- \n\"\"\" \n@author:chengzhuo \n@file: json-text.py \n@time: 2017/10/29 \n\"\"\"\na=123\nimport json #不能写函数和类 要写函数和类用pickle\n\nb=json.dumps(a)\n\n\nprint(type(b))\nf=open('J_test.txt','w')\nf.write(b)\nf.close()","sub_path":"MODED/json_pickle_shelve.py","file_name":"json_pickle_shelve.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"368463049","text":"import inspect\n\nfrom . import htypes\n\n\nclass ViewCommand:\n\n kind = 'view'\n\n @classmethod\n def from_bound_method(cls, method):\n module_name = inspect.getmodule(method).this_module.name\n qual_name = method.__qualname__\n attr_name = method.__name__\n return cls(module_name, qual_name, attr_name, method)\n\n def __init__(self, module_name, qual_name, name, method):\n self._module_name = module_name\n self._qual_name = qual_name\n self.name = name\n self._method = method\n\n def __repr__(self):\n return f\"ViewCommand({self._module_name}.{self._qual_name})\"\n\n @property\n def dir(self):\n return [htypes.command.view_command_d(self._module_name, self._qual_name)]\n\n async def run(self):\n await self._method()\n\n\nclass ViewCommander:\n\n def __init__(self):\n self._command_list = []\n self._init_commands()\n\n def _init_commands(self):\n cls = type(self)\n for name in dir(self):\n if name.startswith('__'):\n continue\n if hasattr(cls, name) and type(getattr(cls, name)) is property:\n continue # Avoid to call properties as we are not yet fully constructed.\n attr = getattr(self, name)\n if getattr(attr, '__is_command__', False):\n self._command_list.append(ViewCommand.from_bound_method(attr))\n\n def get_command_list(self):\n return self._command_list\n","sub_path":"hyperapp/async/ui/view_command.dyn.py","file_name":"view_command.dyn.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"305841996","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 20 19:56:42 2021\n\n@author: AYSEL\n\"\"\"\n### 0-500 arasındaki asal sayıları prime_first ve \n### 500-1000 arasındaki asal sayıları prime_second fonksiyonu ile ekrana yazdırılması.\n\n\n# 0-500 arasında ki asal sayıları ekrana yazdıran fonksiyon.\ndef prime_first(number_1):\n print(f\"prime_fist fonksiyonu çalışıyor!! Sayı: {number_1}\")\n\n# 500-1000 arasında ki asal sayıları ekrana yazdıran fonksiyon.\ndef prime_second(number_2):\n print(f\"prime_second fonksiyonu çalışıyor!! Sayı: {number_2}\")\n\n# 0-1000 arasındaki asal sayıları bulan döngü\nfor i in range(0, 1000):\n if i > 1:\n for j in range(2, i):\n if (i % j) == 0:\n break\n else: \n if (i < 500):\n prime_first(i)\n if (i == 499):\n print(\"\\n\")\n \n elif (i >= 500):\n prime_second(i)\n","sub_path":"Homeworks/HW3.py","file_name":"HW3.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"534381461","text":"\"\"\"\n ----------------------------------------------------\n @Author: tsukasa\n @Affiliation: Waseda University\n @Email: rinsa@suou.waseda.jp\n @Date: 2019-05-17 14:55:08\n @Last Modified by: tsukasa\n @Last Modified time: 2019-05-17 15:32:13\n ----------------------------------------------------\n\n\"\"\"\n\nclass Progress:\n def __init__(self, n, N):\n self.n = n\n self.N = N\n\n def progress_bar(self):\n\n '''\n print current progress\n '''\n\n step = 2\n percent = float(self.n) / float(self.N) * 100\n\n ## convert percent to bar\n current = \"#\" * int(percent//step)\n remain = \" \" * int(100/step-int(percent//step))\n bar = \"|{}{}|\".format(current, remain)\n print(\"\\r{}:{:3.0f}[%]\".format(bar, percent), end=\"\", flush=True)","sub_path":"utils/progress.py","file_name":"progress.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"374059858","text":"#!/usr/bin/env python\n\n\nfrom pyzbar import pyzbar\nimport cv2\nimport roslib\nimport rospy\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\n \nclass qr_code_detector:\n def __init__(self):\n rospy.init_node('qr_code_detector') \n self.bridge = CvBridge()\n self.image_sub = rospy.Subscriber(\"/edrone/camera/image_raw\", Image, self.callback)\n self.object_pub = rospy.Publisher(\"object_detection\", String, queue_size=1)\n self.image_pub = rospy.Publisher(\"image_topic_2\", Image, queue_size=1)\n self.target=[0,1,2]\n\n\n def callback(self, data):\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n \n # find the barcodes in the frame and decode each of the barcodes\n barcodes = pyzbar.decode(cv_image)\n \n # loop through all the possible barcodes within images\n for barcode in barcodes:\n barcodeData = barcode.data.decode(\"utf-8\")\n self.image_pub.publish( self.bridge.cv2_to_imgmsg(cv_image, \"bgr8\"))\n self.object_pub.publish(barcodeData)\n\n\n\n # print(barcodeData)\n barcode_type = barcode.type\n print(barcode_type)\n\n \n\n dummy=[barcodeData]\n #print(dummy)\n #print(type(barcode_data))\n\n\n bubble_gum = dummy[0].split(',')\n unnaku_thevayana_value = map(float,bubble_gum)\n print(unnaku_thevayana_value)\n\n self.target[0]=unnaku_thevayana_value[0]\n self.target[1]=unnaku_thevayana_value[1]\n self.target[2]=unnaku_thevayana_value[2]\n\n \n if barcode_type== \"QRCODE\":\n print(self.target)\n\n\n\ndef main(): \n qrd = qr_code_detector()\n #rospy.init_node('qr_code_detector', anonymous=True)\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n cv2.destroyAllWindows()\n\n \nif __name__ == '__main__':\n main()","sub_path":"scripts/duo_thinker_qr.py","file_name":"duo_thinker_qr.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"175918897","text":"from turtle import *\r\nfrom random import random\r\nfrom freegames import line\r\n \r\ndef draw():\r\n \"Draw maze.\"\r\n color('black')\r\n width(5)\r\n\r\n for x in range(-200,200,40):\r\n for y in range(-200,200,40):\r\n if random() > 0.5:\r\n line(x,y, x + 40 ,y + 40)\r\n else:\r\n line(x,y+40, x+40 , y)\r\nupdate()\r\ndef tap():\r\n \"Draw line and dot fro screen tap\" \r\n if abs(x) > 198 or abs(y) > 198:\r\n up()\r\n else:\r\n down()\r\n\r\n width(20)\r\n color('red')\r\n goto(x, y)\r\n dot(4)\r\nsetup(420,420,370,0)\r\nhideturtle()\r\ntracer(False)\r\ndraw()\r\nonscreenclick(tap)\r\ndone()\r\n","sub_path":"amaze.py","file_name":"amaze.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"443257742","text":"#!/usr/bin/env python\n\nimport numpy as np, os\nfrom sim import run\n\ndef main():\n for sample in np.arange(-5,90.1,0.5):\n work = 'work_%s' % sample\n if os.path.exists(os.path.join(work, 'arcs-sim-wEidata.nxs')):\n print(\"skipping %s\" % sample)\n continue\n run(sample)\n return\n\nif __name__ == '__main__' : main()\n\n","sub_path":"share/DGS/generic/single-crystal/scattering/scripts/edison@nersc/scripts/sim-remainders.py","file_name":"sim-remainders.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"320623019","text":"import Project\nimport Input\n\nif __name__ == \"__main__\":\n response = \"\"\n queue = {}\n while True:\n print(f\"queue length is {len(queue)}\")\n response = input(\"please give project name or type start: \")\n if response == \"start\":\n break\n url = input(\"Please give youtube url: \")\n queue[response] = url\n\n for response in queue:\n Project.make_all(response, queue[response])\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"472518768","text":"# -*- coding: utf-8 -*-\n\n\"\"\"*************************************************************\n** @filepath : /var/projetos/nutbkup/app/model\n** @filename : usuario.py \n** @author : PJ Malva \n** @date : 2018-01-04 \n** @details : Manipulação de dados dos Usuarios\n*************************************************************\"\"\"\n\nimport hashlib\nfrom ..database.usuarios import Usuario as daoUsuario\n\nclass Usuario:\n def adicionar(self,nome,nick,senha,tipo):\n usuario = daoUsuario()\n usuario.nome_usu = nome\n usuario.usuario_usu = nick\n usuario.senha_usu = hashlib.md5(senha.encode()).hexdigest()\n usuario.ativo_usu = 'S'\n usuario.tipo_usu = tipo\n return usuario.salvar()\n\n def editar(self,id,nome,nick,senha,tipo):\n usuario = daoUsuario().query.get(id)\n usuario.nome_usu = nome\n usuario.usuario_usu = nick\n if senha != usuario.senha_usu:\n usuario.senha_usu = hashlib.md5(senha.encode()).hexdigest()\n usuario.tipo_usu = tipo\n return usuario.salvar()\n\n def carregarUsuarios(self, usuarios):\n allUsuarios = []\n for usuario in usuarios:\n allUsuarios.append({'id': usuario.id_usu, 'nome': usuario.nome_usu, \n 'nick': usuario.usuario_usu, 'senha': usuario.senha_usu, \n 'tipo': usuario.tipo_usu, 'email': usuario.email_usu})\n return allUsuarios\n\n def listarUsuarios(self):\n return self.carregarUsuarios(daoUsuario.listar()) \n\n def buscarUsuario(self, id=None, nick=None):\n if id is not None:\n usuarios = daoUsuario.buscar(id=id)\n else:\n usuarios = daoUsuario.buscar(usuario=nick)\n\n if len(usuarios) > 0:\n return self.carregarUsuarios(usuarios)\n else:\n return None\n\n def excluir(self, id):\n daoUsuario.cancelar(id)","sub_path":"web/app/model/usuario.py","file_name":"usuario.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"393770129","text":"import pytest\n\nfrom opentaxii.config import ServerConfig\nfrom opentaxii.middleware import create_app\nfrom opentaxii.server import TAXIIServer\nfrom opentaxii.utils import configure_logging\n\nfrom fixtures import DOMAIN\n\n\n@pytest.fixture(autouse=True, scope='session')\ndef setup_logging():\n configure_logging({'': 'debug'})\n\n\ndef get_config_for_tests(domain=DOMAIN, persistence_db=None, auth_db=None):\n\n config = ServerConfig()\n config.update({\n 'persistence_api': {\n 'class': 'opentaxii.persistence.sqldb.SQLDatabaseAPI',\n 'parameters': {\n 'db_connection': persistence_db or 'sqlite://',\n 'create_tables': True\n }\n },\n 'auth_api': {\n 'class': 'opentaxii.auth.sqldb.SQLDatabaseAPI',\n 'parameters': {\n 'db_connection': auth_db or 'sqlite://',\n 'create_tables': True,\n 'secret': 'dummy-secret-string-for-tests'\n }\n }\n })\n config['domain'] = domain\n return config\n\n\n@pytest.fixture()\ndef config(request):\n return get_config_for_tests()\n\n\n@pytest.fixture()\ndef server(config):\n return TAXIIServer(config)\n\n\n@pytest.fixture()\ndef client(server):\n app = create_app(server)\n app.config['TESTING'] = True\n return app.test_client()\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"17339406","text":"try:\n from urllib.parse import quote_plus\nexcept ImportError:\n from urllib import quote_plus\n\nimport processout\nimport json\n\nfrom processout.networking.request import Request\nfrom processout.networking.response import Response\n\n# The content of this file was automatically generated\n\nclass Webhook(object):\n def __init__(self, client, prefill = None):\n self._client = client\n\n self._id = None\n self._project = None\n self._project_id = None\n self._event = None\n self._event_id = None\n self._request_url = None\n self._request_method = None\n self._response_body = None\n self._response_code = None\n self._response_headers = None\n self._response_time_ms = None\n self._status = None\n self._created_at = None\n self._release_at = None\n if prefill != None:\n self.fill_with_data(prefill)\n\n \n @property\n def id(self):\n \"\"\"Get id\"\"\"\n return self._id\n\n @id.setter\n def id(self, val):\n \"\"\"Set id\n Keyword argument:\n val -- New id value\"\"\"\n self._id = val\n return self\n \n @property\n def project(self):\n \"\"\"Get project\"\"\"\n return self._project\n\n @project.setter\n def project(self, val):\n \"\"\"Set project\n Keyword argument:\n val -- New project value\"\"\"\n if val is None:\n self._project = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Project(self._client)\n obj.fill_with_data(val)\n self._project = obj\n else:\n self._project = val\n return self\n \n @property\n def project_id(self):\n \"\"\"Get project_id\"\"\"\n return self._project_id\n\n @project_id.setter\n def project_id(self, val):\n \"\"\"Set project_id\n Keyword argument:\n val -- New project_id value\"\"\"\n self._project_id = val\n return self\n \n @property\n def event(self):\n \"\"\"Get event\"\"\"\n return self._event\n\n @event.setter\n def event(self, val):\n \"\"\"Set event\n Keyword argument:\n val -- New event value\"\"\"\n if val is None:\n self._event = val\n return self\n\n if isinstance(val, dict):\n obj = processout.Event(self._client)\n obj.fill_with_data(val)\n self._event = obj\n else:\n self._event = val\n return self\n \n @property\n def event_id(self):\n \"\"\"Get event_id\"\"\"\n return self._event_id\n\n @event_id.setter\n def event_id(self, val):\n \"\"\"Set event_id\n Keyword argument:\n val -- New event_id value\"\"\"\n self._event_id = val\n return self\n \n @property\n def request_url(self):\n \"\"\"Get request_url\"\"\"\n return self._request_url\n\n @request_url.setter\n def request_url(self, val):\n \"\"\"Set request_url\n Keyword argument:\n val -- New request_url value\"\"\"\n self._request_url = val\n return self\n \n @property\n def request_method(self):\n \"\"\"Get request_method\"\"\"\n return self._request_method\n\n @request_method.setter\n def request_method(self, val):\n \"\"\"Set request_method\n Keyword argument:\n val -- New request_method value\"\"\"\n self._request_method = val\n return self\n \n @property\n def response_body(self):\n \"\"\"Get response_body\"\"\"\n return self._response_body\n\n @response_body.setter\n def response_body(self, val):\n \"\"\"Set response_body\n Keyword argument:\n val -- New response_body value\"\"\"\n self._response_body = val\n return self\n \n @property\n def response_code(self):\n \"\"\"Get response_code\"\"\"\n return self._response_code\n\n @response_code.setter\n def response_code(self, val):\n \"\"\"Set response_code\n Keyword argument:\n val -- New response_code value\"\"\"\n self._response_code = val\n return self\n \n @property\n def response_headers(self):\n \"\"\"Get response_headers\"\"\"\n return self._response_headers\n\n @response_headers.setter\n def response_headers(self, val):\n \"\"\"Set response_headers\n Keyword argument:\n val -- New response_headers value\"\"\"\n self._response_headers = val\n return self\n \n @property\n def response_time_ms(self):\n \"\"\"Get response_time_ms\"\"\"\n return self._response_time_ms\n\n @response_time_ms.setter\n def response_time_ms(self, val):\n \"\"\"Set response_time_ms\n Keyword argument:\n val -- New response_time_ms value\"\"\"\n self._response_time_ms = val\n return self\n \n @property\n def status(self):\n \"\"\"Get status\"\"\"\n return self._status\n\n @status.setter\n def status(self, val):\n \"\"\"Set status\n Keyword argument:\n val -- New status value\"\"\"\n self._status = val\n return self\n \n @property\n def created_at(self):\n \"\"\"Get created_at\"\"\"\n return self._created_at\n\n @created_at.setter\n def created_at(self, val):\n \"\"\"Set created_at\n Keyword argument:\n val -- New created_at value\"\"\"\n self._created_at = val\n return self\n \n @property\n def release_at(self):\n \"\"\"Get release_at\"\"\"\n return self._release_at\n\n @release_at.setter\n def release_at(self, val):\n \"\"\"Set release_at\n Keyword argument:\n val -- New release_at value\"\"\"\n self._release_at = val\n return self\n \n\n def fill_with_data(self, data):\n \"\"\"Fill the current object with the new values pulled from data\n Keyword argument:\n data -- The data from which to pull the new values\"\"\"\n if \"id\" in data.keys():\n self.id = data[\"id\"]\n if \"project\" in data.keys():\n self.project = data[\"project\"]\n if \"project_id\" in data.keys():\n self.project_id = data[\"project_id\"]\n if \"event\" in data.keys():\n self.event = data[\"event\"]\n if \"event_id\" in data.keys():\n self.event_id = data[\"event_id\"]\n if \"request_url\" in data.keys():\n self.request_url = data[\"request_url\"]\n if \"request_method\" in data.keys():\n self.request_method = data[\"request_method\"]\n if \"response_body\" in data.keys():\n self.response_body = data[\"response_body\"]\n if \"response_code\" in data.keys():\n self.response_code = data[\"response_code\"]\n if \"response_headers\" in data.keys():\n self.response_headers = data[\"response_headers\"]\n if \"response_time_ms\" in data.keys():\n self.response_time_ms = data[\"response_time_ms\"]\n if \"status\" in data.keys():\n self.status = data[\"status\"]\n if \"created_at\" in data.keys():\n self.created_at = data[\"created_at\"]\n if \"release_at\" in data.keys():\n self.release_at = data[\"release_at\"]\n \n return self\n\n def to_json(self):\n return {\n \"id\": self.id,\n \"project\": self.project,\n \"project_id\": self.project_id,\n \"event\": self.event,\n \"event_id\": self.event_id,\n \"request_url\": self.request_url,\n \"request_method\": self.request_method,\n \"response_body\": self.response_body,\n \"response_code\": self.response_code,\n \"response_headers\": self.response_headers,\n \"response_time_ms\": self.response_time_ms,\n \"status\": self.status,\n \"created_at\": self.created_at,\n \"release_at\": self.release_at,\n }\n\n \n","sub_path":"processout/webhook.py","file_name":"webhook.py","file_ext":"py","file_size_in_byte":7801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"213342946","text":"#!/usr/bin/env python3\n\"\"\"\nExample of how to draw a map from a shapefile (or part thereof)\n\"\"\"\n\nimport pandas as pd\nimport geopandas \nimport matplotlib.pyplot as plt\nimport contextily as ctx\nfrom shapely.geometry import Point\n\ndef add_basemap(ax, crs, url='http://a.tile.stamen.com/terrain/tileZ/tileX/tileY.png'):\n xmin, xmax, ymin, ymax = ax.axis()\n bb = geopandas.GeoSeries([Point(xmin, ymin), Point(xmax, ymax)])\n bb.crs = crs\n bb = bb.to_crs(epsg=4326)\n zoom = ctx.calculate_zoom(bb[0].x, bb[0].y, bb[1].x, bb[1].y)\n basemap, extent = ctx.bounds2img(xmin, ymin, xmax, ymax, zoom=zoom, url=url)\n ax.imshow(basemap, extent=extent, interpolation='bilinear')\n # restore original x/y limits\n ax.axis((xmin, xmax, ymin, ymax))\n\ndef main(lad_match):\n # 4326 is lat/lon\n # 3857 is mercator\n df = geopandas.read_file(\"../Mistral/data/Local_Authority_Districts_December_2016_Ultra_Generalised_Clipped_Boundaries_in_Great_Britain.shp\")\n print(df.columns.values)\n df = df[df.lad16cd.str.contains(lad_match)].to_crs(epsg=3857)\n\n df[\"unoblongity\"] = df.st_areasha / df.st_lengths ** 2\n\n if not len(df):\n print(\"No polygons found\")\n return\n\n\n ax = df.plot(figsize=(10, 10), alpha=0.5, column='unoblongity', cmap='Greens', edgecolor='k', ax=None)\n # url=\"https://a.basemaps.cartocdn.com/light_all/tileZ/tileX/tileY.png\" requires attribution: \"Map tiles by Carto, under CC BY 3.0. Data by OpenStreetMap, under ODbL.\"\n # url=\"https://a.tile.openstreetmap.org/tileZ/tileX/tileY.png\"\n add_basemap(ax, df.crs, url=\"https://tiles.wmflabs.org/bw-mapnik/tileZ/tileX/tileY.png\")\n plt.title(\"GB LADs\")\n plt.axis(\"off\")\n plt.show()\n\nif __name__ == \"__main__\":\n lad_match = \".*\" #\"E0|W0|S1\"\n main(lad_match)","sub_path":"tools/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"158178959","text":"############################################\n## written by Elise Hopman\n## at University of Wisconsin - Madison\n## spring/summer 2016\n############################################\n\n\"\"\"\nThis program runs an artificial language learning experiment\n\"\"\"\n\nimport sys\nfrom psychopy import visual, core, event\nimport numpy as num\nimport random\nfrom psychopy import gui, sound, microphone\nimport webbrowser\nimport wave\nimport time\n\n# functions for interaction with subject\ndef getsubjectnumber():\n myDlg = gui.Dlg(title=\"Subject\", pos=(200,400))\n myDlg.addText(' ')\n myDlg.addField('Subject number:',)\n myDlg.addText(' ')\n myDlg.show()\n if myDlg.OK:\n info = myDlg.data #this will be a list of data returned from each field added in order\n subnr = int(info[0])\n else: sys.exit() # if you press cancel the program will just stop. \n return subnr\ndef getconditionnumber():\n myDlg = gui.Dlg(title=\"Experimentinfo\", pos=(200,400))\n myDlg.addText(' ')\n myDlg.addField('Condition:',)\n myDlg.addText(' ')\n myDlg.show()\n if myDlg.OK:\n info = myDlg.data #this will be a list of data returned from each field added in order\n condnr = int(info[0])\n else: sys.exit() # if you press cancel the program will just stop. \n return condnr\ndef showmessage(window, whatyouwannasay):\n \"\"\" first makes the screen blank for half a second, then displays a message untill a key is pressed.\"\"\"\n blankscreen(window, .05) # THIS SHOULD BE 0.5 JUST HAVE IT LIKE THIS FOR TESTING ## CHANGE BACK\n message = visual.TextStim(window,pos = [0,0], text=whatyouwannasay, color = 'black')\n message.draw()\n window.flip()\n waitforkey()\ndef blankscreen(window, time):\n \"\"\" This function makes the screen blank for a specified time by drawing a white square as big as my laptop screen\"\"\"\n square = visual.GratingStim(window ,tex=\"none\",mask=\"none\",color=\"white\",size=[1440,900], pos = [0,0])\n square.draw()\n window.flip()\n core.wait(time)\ndef waitforkey():\n \"\"\" This function waits for a key\"\"\"\n # this function records time till keypress and when key is pressed returns the time.\n waitforkey = True\n timer = core.Clock()\n timer.reset()\n while waitforkey == True:\n if len(event.waitKeys())>0:\n return timer.getTime()\n waitforkey = False\ndef playsound(name):\n \"\"\" plays a sound and returns its duration \"\"\"\n sound_file = sound.Sound(name)\n dur = sound_file.getDuration()\n sound_file.play()\n return dur\n #core.wait(dur)\ndef showimage(window, time, picture,pl = '1', sizeofpic = 'no', issigns = False, feedback = 'none', mic = False, green = False):\n \"\"\" Shows an image in a certain position for a time, picture = path to pic (including .jpg or whatever)\"\"\"\n p1 = visual.ImageStim(window, image = picture, pos = [0,0])\n if pl == '2':\n p1 = visual.ImageStim(window, image = picture, pos = [-200,0])\n p2 = visual.ImageStim(window, image = picture, pos = [200,0])\n if sizeofpic != 'no':\n p2.setSize(sizeofpic)\n p2.draw()\n if sizeofpic != 'no':\n p1.setSize(sizeofpic)\n p1.draw()\n if issigns == True:\n issign = visual.ImageStim(window, image = \"pictures/is.png\", pos = [500,-400], size = [75,45])\n issign.draw()\n isnot = visual.ImageStim(window, image = \"pictures/isnot.png\", pos = [-500,-400], size = [90,75]) \n isnot.draw()\n if feedback == 'wrong':\n feedb = visual.ImageStim(window, image = \"pictures/rcross.png\", pos = [0,-400], size = [75,75])\n feedb.draw()\n elif feedback == 'right':\n feedb = visual.ImageStim(window, image = \"pictures/gcheck.png\", pos = [0,-400], size = [75,75])\n feedb.draw()\n if mic == True:\n mic = visual. ImageStim(window, image = \"pictures/mic.png\", pos = [0, -400], size = [64,64])\n mic.draw()\n if green == True:\n left = visual.Rect(win,lineColor=\"green\",fillColor=\"green\", pos = [-500, 0] ,size=[10,1610])\n left.draw()\n right = visual.Rect(win,lineColor=\"green\",fillColor=\"green\", pos = [500, 0] ,size=[10,1610])\n right.draw()\n up = visual.Rect(win,lineColor=\"green\",fillColor=\"green\", pos = [0, 400] ,size=[2010,10])\n up.draw()\n down = visual.Rect(win,lineColor=\"green\",fillColor=\"green\", pos = [0, -400] ,size=[2010,10])\n down.draw()\n window.flip()\n core.wait(time)\ndef forcedchoiceimage(window, time, picture1, picture2, pl = '1', vid = 'no', keys = 'no', si = [360,270]):\n \"\"\"shows 2 or 4 images for forced choice\"\"\"\n multiple = si\n if pl == '1':\n p1 = visual.ImageStim(window, image = picture1, pos = [-480,0], size = multiple)\n p2 = visual.ImageStim(window, image = picture2, pos = [480,0], size = multiple)\n elif pl == '2':\n p1 = visual.ImageStim(window, image = picture1, pos = [-650,0], size = multiple)\n p2 = visual.ImageStim(window, image = picture2, pos = [650,0], size = multiple) \n p3 = visual.ImageStim(window, image = picture1, pos = [-310,0], size = multiple)\n p4 = visual.ImageStim(window, image = picture2, pos = [310,0], size = multiple) \n p3.draw()\n p4.draw()\n elif pl == '3': # two pics on left one on right \n p1 = visual.ImageStim(window, image = picture1, pos = [-650,0], size = multiple)\n p2 = visual.ImageStim(window, image = picture2, pos = [480,0], size = multiple) \n p3 = visual.ImageStim(window, image = picture1, pos = [-310,0], size = multiple) \n p3.draw()\n elif pl == '4': # two pics on right one on left\n p1 = visual.ImageStim(window, image = picture1, pos = [-650,0], size = multiple)\n p2 = visual.ImageStim(window, image = picture2, pos = [650,0], size = multiple) \n p3 = visual.ImageStim(window, image = picture2, pos = [310,0], size = multiple) \n p3.draw()\n p1.draw()\n p2.draw()\n showkeys = 'no'\n if keys == 'yes':\n showkeys = 'yes'\n key1 = visual.TextStim(window, pos = [-480,-400], text='x', color = 'black')\n key1.draw()\n key2 = visual.TextStim(window, pos = [480, -400], text = 'm', color = 'black')\n key2.draw()\n window.flip()\n core.wait(time)\n if vid == 'yes':\n twomovies(window, picture1, picture2, keys = showkeys)\ndef showfixation(window,t, position):\n \"\"\" This function shows a fixation cross for a specified time t at a specified position in a specified window\"\"\"\n cross = visual.TextStim(window,pos = position, text='+', color = 'black', height = 80)\n cross.draw()\n window.flip()\n core.wait(t)\ndef passivetrial(window, picpath, soundpath, pl = '1', vid = 'no'):\n \"\"\" Shows an image and plays the sound that goes with it twice. \"\"\"\n # show all pics in the middle of the screen for now\n M = [0,0]\n single = [480, 360] # sizeofpic trying out\n if vid == 'yes':\n single = [900,675]\n # trial starts with a fixation cross for 500 ms\n showfixation(window, 0.5, M)\n # put the picture on the screen for 500 ms\n endpic = picpath\n showimage(window, .5, picpath, pl, sizeofpic = single, green = True)\n if vid == 'yes':\n endpic = movie(window, picpath, sizeofpic = single, green = True)\n # play the sound (while freezing the screen for as long as that takes)\n core.wait(playsound(soundpath))\n # show the picture for 1.5 s\n showimage(window, 1.5, endpic, pl, sizeofpic = single, green = True)\n # quick blank screen\n blankscreen(window, 0.5)\n # and then show the picture for 500 ms\n showimage(window, 0.5, picpath, pl, sizeofpic = single, green = True)\n if vid == 'yes':\n movie(window, picpath, sizeofpic = single, green = True)\n # play the sound (while freezing the screen for as long as that takes)\n core.wait(playsound(soundpath))\n # and then show the picture for 1.5 s\n showimage(window, 1, endpic, pl, sizeofpic = single, green = True) \ndef activecomptrial(window, picpath1, picpath2, soundpath, pl = '1', vid = 'no'):\n \"\"\"Shows an image and plays a sound and has the participant indicate whether these match and gives them feedback\"\"\"\n # show all pics in the middle of the screen for now\n M = [0,0]\n single = [480, 360]\n if vid == 'yes':\n single = [900,675]\n endpic = picpath1\n # trial starts with a fixation cross for 500 ms\n showfixation(window, 0.5, M)\n # put the picture on the screen for 500 ms\n showimage(window, .5, picpath1, pl, sizeofpic = single)\n if vid == 'yes':\n endpic = movie(window, picpath1, sizeofpic = single)\n # play the sound (while freezing the screen for as long as that takes)\n core.wait(playsound(soundpath))\n timer2 = core.MonotonicClock() # RT starts right as the sound is done till they hit the key\n # show the picture with check and crossmarks\n showimage(window, .01, endpic, pl, sizeofpic = single, issigns = True)\n response=event.waitKeys(keyList=['f','l'])[0]\n reaction = timer2.getTime()\n # right now it gives you feedback as to which one you chose, not as to whether that was the correct option. \n if response==\"f\":\n if picpath1 != picpath2:\n showimage(window, 1, endpic, pl, sizeofpic = single, feedback = 'right')\n blankscreen(window, .5)\n else:\n showimage(window, 1, endpic, pl, sizeofpic = single, feedback = 'wrong')\n elif response == \"l\":\n if picpath1 != picpath2:\n showimage(window, 1, endpic, pl, sizeofpic = single, feedback = 'wrong')\n blankscreen(window, .5)\n else:\n showimage(window, 1, endpic, pl, sizeofpic = single, feedback = 'right')\n # only if the picture changes because the 1st pic wasn't the correct one, there's a whitescreen in between\n showimage(window, .5, picpath2, pl, sizeofpic = single, green = True)\n endpic = picpath2\n if vid == 'yes':\n endpic = movie(window, picpath2, sizeofpic = single, green = True)\n core.wait(playsound(soundpath))\n showimage(window, 2, endpic, pl, sizeofpic = single, green = True) \n inf = [response, reaction]\n return inf\ndef activeprodtrial(window, picpath, soundpath, pl = '1', vid = 'no'):\n \"\"\"This function shows a picture, records with a mic, then plays the sound\"\"\"\n # show all pics in the middle of the screen for now\n M = [0,0]\n single = [480, 360]\n if vid == 'yes':\n single = [900,675]\n # trial starts with a fixation cross for 500 ms\n showfixation(window, 0.5, M)\n mic = microphone.AudioCapture()\n recname = 'data/s'+str(subjectnr) + '/recordings/recordingtrial'+ str(trialnr) + '.wav'\n mic.record(360, recname, block = False)\n reaction = 9990\n # put the picture on the screen for 500 ms\n timer2 = core.MonotonicClock() # so for these trials, RT includes .5 sec to see the pic + viddurations if applicable\n showimage(window, .5, picpath, pl, sizeofpic = single, mic = True)\n endpic = picpath\n event.clearEvents()\n if vid == 'yes':\n endpic = movie(window, picpath, sizeofpic = single, mic = True)\n while mic.recorder.running:\n if 'return' in event.getKeys():\n reaction = timer2.getTime()\n core.wait(1)\n mic.stop()\n showimage(window, .5, picpath, pl, sizeofpic = single, green = True)\n if vid == 'yes':\n movie(window, picpath, sizeofpic = single, green = True)\n core.wait(playsound(soundpath))\n showimage(window, 1, endpic, pl, sizeofpic = single, green = True)\n return reaction\ndef forcedchoicetesttrial(window, picpath1, picpath2, soundpath, pl = '1', vid = 'no'): \n \"\"\"Shows two pictures, plays a sound, has participant choose between the two pictures. \"\"\"\n M = [0,0]\n # trial starts with a fixation cross for 500 ms\n showfixation(window, 0.5, M)\n showkey = 'yes'\n siz = [360,270]\n if vid == 'yes':\n siz = [900,675]\n forcedchoiceimage(window, .5, picpath1, picpath2, pl, vid, keys = showkey, si = siz)\n # we time how long a trial takes them.\n timer2 = core.MonotonicClock()\n sound_file = sound.Sound(soundpath)\n dur = sound_file.getDuration()\n sound_file.play()\n response=event.waitKeys(keyList=['x','m'])[0]\n reaction = timer2.getTime()\n if reaction < dur:\n sound_file.stop()\n out = [response, reaction]\n return out\ndef errormonitoringtesttrial(window, soundpath):\n \"\"\"play a sound, have participant indicate right or wrong, record time\"\"\"\n # show all pics in the middle of the screen for now\n M = [0,0]\n # trial starts with a fixation cross for 500 ms\n showfixation(window, 0.5, M)\n showimage(window, .001, \"pictures/empty.png\", issigns = True)\n timer2 = core.MonotonicClock()\n sound_file = sound.Sound(soundpath)\n dur = sound_file.getDuration()\n sound_file.play()\n response=event.waitKeys(keyList=['f','l'])[0]\n reaction = timer2.getTime()\n if reaction < dur:\n sound_file.stop()\n out = [response, reaction]\n return out\ndef movie(window, name, sizeofpic = 'no', green = False, mic = False):\n \"\"\"plays a movie frame by frame\"\"\"\n lngth = len(name)\n nam = name[0:lngth-5]\n for i in range(10):\n j = i+1\n frame = nam + '%d.png' %j\n showimage(window, .025, frame, sizeofpic = sizeofpic, green = green, mic = mic)\n return frame\ndef twomovies(window, name1, name2, keys = 'no'):\n \"\"\"plays two movies side by side for a forced choice trial\"\"\"\n lngth1 = len(name1)\n shwk = 'no'\n if keys == 'yes':\n shwk = 'yes'\n nam1 = name1[0:lngth1-5]\n lngth2 = len(name2)\n nam2 = name2[0:lngth2-5] \n for i in range(10):\n j = i+1\n frame1 = nam1 + '%d.png' %j\n frame2 = nam2 + '%d.png' %j\n forcedchoiceimage(window, 0.025, frame1, frame2, keys = shwk, si = [900,675])\ndef activecompblock(trials, trlnr, ittype, pl = '1'):\n random.shuffle(trials)\n picknonmatch = range(len(trials))\n random.shuffle(picknonmatch) # random shuffle to pick which half of the trials get to be mismatch\n alts = genalt(trials)\n tcrct = 0\n for t in range(len(trials)):\n trial = trials[t]\n snd = trial[1]\n ckey = 'none'\n if trial[2]=='m': # if monster vocab trials\n if pl == '2':\n snd = trial[4] # plural sound\n if picknonmatch[t] < len(trials)/2:# match\n info = activecomptrial(win, trial[0],trial[0], snd, pl)\n key = info[0]\n if key == 'l':\n tcrct = tcrct + 1\n ckey = '1'\n elif key == 'f':\n ckey = '0'\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trlnr + \"AC\\t\" + ittype + \"\\t\"+ str(ckey) + \"\\t\" + key + \"\\tyesmatch\\t\" + str(info[1]) + \"\\t\" + snd + \"\\t\" + trial[0] + \"\\t\" + trial[0] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; \n else: # mismatch\n info = activecomptrial(win,alts[t][0], trial[0], snd, pl)\n key = info[0]\n if key == 'f':\n tcrct = tcrct + 1\n ckey = '1'\n elif key == 'l':\n ckey = '0' \n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trlnr + \"AC\\t\" + ittype + \"\\t\"+ str(ckey) + \"\\t\" + key + \"\\tmismatch\\t\" + str(info[1]) + \"\\t\" + snd + \"\\t\" + trial[0] + \"\\t\" + alts[t][0] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; \n trlnr = trlnr + 1\n activecompcorrect.append([tcrct, ittype])\n return trlnr\n# functions for generating the experiment\ndef getdurs(s):\n \"for a sound file 's' it gets you a list with the duration of the total file as well as each of the individual words that form the phrase (so that might be 0 for some parts of some phrases)\"\n for d in sounddurlist:\n if d[0] == s:\n return d\ndef getdur(s):\n sound_file = sound.Sound(s)\n dur = sound_file.getDuration()\n return dur\ndef genalt(lst):\n \"\"\"this function shuffles the lst so that no element stays in its old place\"\"\"\n gelukt = False\n while gelukt == False:\n new = list(lst)\n random.shuffle(new)\n cntr = 0\n for i in range(len(lst)):\n if new[i] == lst[i]:\n cntr = cntr + 1\n if cntr == 0:\n gelukt = True\n return new\ndef attachalt(lst, trials):\n \"\"\"attach an alternative pic from a different trial to each trial in 'trials' and output to 'list' these new trials\"\"\"\n talts = genalt(trials) # create derangement\n for t in range(len(trials)): # all of them will get an alternative assigned\n trl = list(trials[t])\n alt = talts[t][0] # grab foil the pic from the derangement selected trial\n trl.append(alt)\n lst.append(trl)\ndef assignlanguage(wlist):\n \"\"\"This function grabs a list, randomizes it and logs it\"\"\"\n random.shuffle(wlist[0])\n random.shuffle(wlist[1])\n f.write(\"\\n\\n\" + wlist[2])\n for i in range(len(wlist[0])):\n f.write('\\n%d\\t%d' %(wlist[0][i], wlist[1][i]))\ndef trialgenm(triallist, listofelements, sffxes, n = 0):\n \"\"\"generate a list of all monstr noun trials\"\"\" \n for j in range(len(listofelements[0])): # list of the visual monsters that is shuffled. \n vismon = listofelements[0][j]\n if vismon < 4:\n vissem = 1\n audsem = sffxes[1][0]\n elif vismon > 4:\n vissem = 2\n audsem = sffxes[1][1]\n audmon = listofelements[1][j]\n visual = \"pictures/PNG/1110007\" + str(vismon) + str(vissem) + '000.png'\n sound1 = \"sounds/combined/10100001\" + str(audsem) +\"1000\" + str(audmon) + str(audsem) +\"1000000.wav\" # sgl sound\n sound2 = \"sounds/combined/10100001\"+ str(audsem) + \"2000\" + str(audmon) + str(audsem)+ \"2000000.wav\" # pl sound\n triallist.append([visual, sound1, listofelements[3], listofelements[4], sound2, vissem])\ndef trialgenc(triallist, listofelements):\n \"\"\"generate a list of all color noun trials\"\"\" \n # random shuffle to get alternative\n for i in range(len(listofelements[0])): # go through all words of that type\n viscol = listofelements[0][i]\n audcol = listofelements[1][i]\n visual = \"pictures/PNG/100000\" + str(viscol) + \"00000.png\"\n sound = \"sounds/combined/0100000000\" + str(audcol) + \"00000000000.wav\"\n triallist.append([visual, sound, listofelements[3], listofelements[4]])\ndef trialgenp(triallist, listofelements):\n \"\"\"generate a list of all pattern noun trials\"\"\" \n # random shuffle to get alternative\n for i in range(len(listofelements[0])): # go through all words of that type\n vispat = listofelements[0][i]\n audpat = listofelements[1][i]\n visual = \"pictures/PNG/000100000\" + str(vispat) + \"00.png\"\n sound = \"sounds/combined/0001000000000000\" + str(audpat) + \"00000.wav\"\n triallist.append([visual, sound, listofelements[3], listofelements[4]])\ndef trialgenv(triallist, listofelements):\n \"\"\"generate a list of all verb noun trials\"\"\" \n # random shuffle to get alternative\n for i in range(len(listofelements[0])): # go through all words of that type\n visverb = listofelements[0][i]\n audverb = listofelements[1][i]\n visual = \"verbvocab/verb\" + str(visverb) + \"slide1.png\"\n sound = \"sounds/combined/000001000000000000\" + str(audverb) + \"000.wav\"\n triallist.append([visual, sound, listofelements[3], listofelements[4]])\ndef trialgenl(triallist, listofelements):\n \"\"\"generate a list of all landscape noun trials\"\"\" \n # random shuffle to get alternative\n for i in range(len(listofelements[0])): # go through all words of that type\n vislan = listofelements[0][i]\n audlan = listofelements[1][i]\n visual = \"pictures/PNG/00000100000\" + str(vislan) + \".png\"\n sound = \"sounds/combined/000000100000000000000\" + str(audlan) + \".wav\"\n triallist.append([visual, sound, listofelements[3], listofelements[4]])\ndef trialgenCM(tlist, clrs, mnstrs,sfxs):\n \"\"\"generate det col monster trials\"\"\"\n yellowdummy = list(range(6)) # shuffle to pick out which monsters are yellow in the first block\n pldummy = list(range(6)) # shuffle to pick out which monsters are plural in the first block\n random.shuffle(yellowdummy)\n random.shuffle(pldummy)\n for round in range(2):\n roundlist = []\n mdummy = list(range(6))\n monsterfoil = genalt(mnstrs[0])\n fdummy = list(range(6))\n random.shuffle(fdummy)\n for i in range(6): # through all monsters\n if round == 0: # which ones are sg/pl in the first round\n if pldummy[i] < 3:\n n = 1\n elif pldummy[i] > 2:\n n = 2\n if yellowdummy[i] < 3:\n cs = clrs[1][0]\n cp = clrs[0][0]\n cff = clrs[0][1]\n elif yellowdummy[i]>2:\n cs = clrs[1][1]\n cp = clrs[0][1]\n cff = clrs[0][0]\n elif round == 1: # and those are pl/sg in the second round\n if pldummy[i] < 3:\n n = 2\n elif pldummy[i] > 2:\n n = 1 \n if yellowdummy[i] >2:\n cs = clrs[1][0]\n cp = clrs[0][0]\n cff = clrs[0][1]\n elif yellowdummy[i]<3:\n cs = clrs[1][1]\n cp = clrs[0][1]\n cff = clrs[0][0]\n vismon = mnstrs[0][i]\n if vismon < 4:\n vissem = 1\n audsem = sfxs[1][0]\n elif vismon >3: \n vissem = 2\n audsem = sfxs[1][1]\n vismonf = monsterfoil[i] \n if vismonf < 4:\n vissemf = 1\n elif vismonf > 3:\n vissemf = 2\n audmon = mnstrs[1][i]\n sound = \"sounds/combined/11100001\" + str(audsem) + str(n) + str(cs) + str(audsem) + str(n) + str(audmon) + str(audsem) + str(n) + \"000000.wav\"\n pic = \"pictures/PNG/111000\" + str(cp) + str(vismon) + str(vissem) + \"000.png\"\n cf = cp\n if fdummy[i] == 1: # color foil\n cf = cff \n vismonf = vismon # set monster to be the old one\n vissemf = vissem\n elif fdummy[i] == 2: # both foil\n cf = cff\n elif fdummy[i] > 2:\n vismonf = vismon # set monster to be the old one\n vissemf = vissem\n fpic = \"pictures/PNG/111000\" + str(cf) + str(vismonf) + str(vissemf) + \"000.png\" # generate the foil pic, which is the same pic if fdummy was > 2\n roundlist.append([i, pic, vismon, cp, sound, audmon, cs, vissem, n , fpic])\n tlist.append(roundlist) \ndef trialgenNP(tlist, clrs, nmnstrs, smnstrs, nptrns, sptrns, sfx):\n \"\"\"generate 24 trials with full NPs\"\"\"\n pat = [[[3,1,2],[4,3,4]], [[1,2,1],[2,4,3]], [[2,4,1],[3,4,3]],[[2,1,2],[3,1,4]]] # patterns in each round, sorted by those for nice and scary groups\n random.shuffle(pat)\n random.shuffle(nmnstrs)\n random.shuffle(smnstrs)\n for r in range(4): # four rounds\n roundlist = []\n nicefoil = genalt(nmnstrs)\n scaryfoil = genalt(smnstrs)\n pldummy = list(range(6))\n random.shuffle(pldummy)\n colourdummy = list(range(6))\n random.shuffle(colourdummy)\n fdummy = list(range(6))\n random.shuffle(fdummy)\n for i in range(6): # six trials per round\n if i < 3:\n vissem = 1\n audsem = sfx[1][0]\n vismon = nmnstrs[i][0]\n audmon = nmnstrs[i][1]\n vismonf = nicefoil[i][0]\n whichpattern = pat[r][0][i]\n if whichpattern < 3: # a prob pattern\n h = whichpattern - 1\n u = 1 - h\n vispat = nptrns[h][0]\n vispatf = nptrns[u][0]\n audpat = nptrns[h][1]\n elif whichpattern > 2: # the improb pattern this round\n h = whichpattern - 3\n u = 1-h\n vispat = sptrns[h][0]\n vispatf = sptrns[u][0]\n audpat = sptrns[h][1]\n elif i > 2:\n j = i-3\n vissem = 2\n audsem = sfx[1][1]\n vismon = smnstrs[j][0]\n audmon = smnstrs[j][1]\n vismonf = scaryfoil[j][0]\n whichpattern = pat[r][1][j]\n if whichpattern > 2: # a prob pattern\n h = whichpattern - 3 # so h is 0 or 1\n u = 1 - h # so u is 1 or 0 (the other one that h)\n vispat = sptrns[h][0]\n vispatf = sptrns[u][0]\n audpat = sptrns[h][1]\n elif whichpattern < 3: # the improb pattern this round\n h = whichpattern - 1\n u = 1-h\n vispat = nptrns[h][0]\n vispatf = nptrns[u][0]\n audpat = nptrns[h][1]\n if pldummy[i] < 3:\n n = 1\n elif pldummy[i] > 2:\n n = 2\n if colourdummy[i] < 3: \n cp = clrs[0][0]\n cs = clrs[1][0]\n elif colourdummy[i]>2:\n cp = clrs[0][1]\n cs = clrs[1][1]\n sound = \"sounds/combined/11111001\" + str(audsem) + str(n) + str(cs) + str(audsem) + str(n) + str(audmon) + str(audsem) + str(n) + str(audpat) +\"10000.wav\"\n pic = \"pictures/PNG/111100\" + str(cp) + str(vismon) + str(vissem) + str(vispat) +\"00.png\"\n fcp = cp\n fmp = vismon\n fpat = vispat\n if fdummy[i] == 0:\n fcp = 3 - cp # so the other colour\n elif fdummy[i] == 1:\n fmp = vismonf\n elif fdummy[i] == 2:\n fpat = vispatf\n fpic = \"pictures/PNG/111100\" + str(fcp) + str(fmp) + str(vissem) + str(fpat) +\"00.png\"\n roundlist.append([pic, vismon, cp, vispat, sound, audmon, cs, vissem, n, fpic])\n tlist.append(roundlist) \ndef trialgenfull(clrs, nmnstrs, smnstrs, nptrns, sptrns, vrbs, plnts, sfx, exposure):\n \"\"\"generates a list of full sentence trials\"\"\"\n unroundlist = []\n activeroundlist = []\n passiveroundlist = []\n for item in exposure: # exposure is a list of 72 trials in groups of 6 that form a block. \n cgen = item[8]\n cp = clrs[0][cgen]\n cs = clrs[1][cgen]\n mgen = item[10]\n if item[9] == 'nice':\n vismon = nmnstrs[mgen][0]\n audmon = nmnstrs[mgen][1]\n vissem = 1\n audsem = sfx[1][0]\n elif item[9] == 'scary':\n vismon = smnstrs[mgen][0]\n audmon = smnstrs[mgen][1]\n vissem = 2\n audsem = sfx[1][1]\n pgen = item[12]\n if item[11] == 'nice':\n vispat = nptrns[pgen][0]\n audpat = nptrns[pgen][1]\n elif item[11] == 'scary':\n vispat = sptrns[pgen][0]\n audpat = sptrns[pgen][1]\n vgen = item[13]\n visverb = vrbs[0][vgen]\n audverb = vrbs[1][vgen]\n lgen = item[14]\n vislan = plnts[0][lgen]\n audlan = plnts[1][lgen]\n nr = item[15]\n pic = \"slides/v111111\"+str(cp) + str(vismon) + str(vissem) + str(vispat) + str(visverb) + str(vislan)+ 'n' + str(nr) + 'f1.png'\n sound = \"sounds/combined/11111111\" + str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + str(audpat)+ '1' + str(audverb) + str(audsem) + str(nr) + str(audlan) + \".wav\"\n unroundlist.append([pic, sound, cp, mgen, vissem, vispat, vgen, lgen, nr, vismon, visverb, vislan])\n tnr = 0\n planetlist = list(range(3))\n verblist = list(range(3))\n fdummy = list(range(6))\n for r in range(6):\n passiveblock = []\n for i in range(6):\n passivetrial = unroundlist[tnr]\n passiveblock.append([passivetrial[0], passivetrial[1]])\n tnr += 1\n passiveroundlist.append(passiveblock)\n for r in range(6):\n activeblock = []\n nmfoils = genalt(nmnstrs)\n smfoils = genalt(smnstrs)\n vfoils = genalt(verblist)\n lfoils = genalt(planetlist)\n random.shuffle(fdummy)\n for i in range(6):\n activetrial = unroundlist[tnr]\n cp = activetrial[2]\n cfc = 3-cp # 3 - colorpic is either 1 or 2 but the other one than the cp\n vissem = activetrial[4]\n mgen = activetrial[3]\n if vissem == 1: # vissem nice\n cmf = nmfoils[mgen][0] # mgen\n elif vissem == 2: # vissem scary\n cmf = smfoils[mgen][0] # mgen\n vispat = activetrial[5]\n if vispat < 3: #vispat nice pattern\n cpf = 3 - vispat # the other nice pattern\n elif vispat > 2: # vispat scary pattern\n cpf = 7 - vispat\n vgen = activetrial[6]\n lgen = activetrial[7]\n cvf = vrbs[0][vfoils[vgen]] # vgen picks out which vfoil it will be\n clf = plnts[0][lfoils[lgen]] # lgen picks out which foil it will be\n # so now i've generated a candidate foil for each aspect of each pic. now let's see who gets what foil\n fpic = activetrial[0]\n nr = activetrial[8]\n vismon = activetrial[9]\n visverb = activetrial[10]\n vislan = activetrial[11]\n if r % 3 == 0:\n if fdummy[i] == 0: # verbfoil\n fpic = \"slides/v111111\"+str(cp) + str(vismon) + str(vissem) + str(vispat) + str(cvf) + str(vislan) + 'n' + str(nr) + 'f1.png'\n elif fdummy[i] == 1: # planetfoil\n fpic = \"slides/v111111\"+str(cp) + str(vismon) + str(vissem) + str(vispat) + str(visverb) + str(clf) + 'n' + str(nr) + 'f1.png'\n elif r % 3 == 1:\n if fdummy[i] == 0: # planetfoil\n fpic = \"slides/v111111\"+str(cp) + str(vismon) + str(vissem) + str(vispat) + str(visverb) + str(clf) + 'n' + str(nr) + 'f1.png'\n elif fdummy[i] == 1: # patternfoil\n fpic = \"slides/v111111\"+str(cp) + str(vismon) + str(vissem) + str(cpf) + str(visverb) + str(vislan) + 'n' + str(nr) + 'f1.png'\n elif r % 3 == 2:\n if fdummy[i] == 0: # patternfoil\n fpic = \"slides/v111111\"+str(cp) + str(vismon) + str(vissem) + str(cpf) + str(visverb) + str(vislan) + 'n' + str(nr) + 'f1.png'\n elif fdummy[i] == 1: # verbfoil\n fpic = \"slides/v111111\"+str(cp) + str(vismon) + str(vissem) + str(vispat) + str(cvf) + str(vislan) + 'n' + str(nr) + 'f1.png'\n if r % 2 == 0:\n if fdummy[i] == 2: # monsterfoil\n fpic = \"slides/v111111\"+str(cp) + str(cmf) + str(vissem) + str(vispat) + str(visverb) + str(vislan) + 'n' + str(nr) + 'f1.png'\n elif r % 2 == 1:\n if fdummy[i] == 2: # colourfoil\n fpic = \"slides/v111111\"+str(cfc) + str(vismon) + str(vissem) + str(vispat) + str(visverb) + str(vislan) + 'n' + str(nr) + 'f1.png'\n activeblock.append([activetrial[0], activetrial[1], fpic])\n tnr += 1\n activeroundlist.append(activeblock)\n random.shuffle(activeroundlist)\n random.shuffle(passiveroundlist)\n return [passiveroundlist, activeroundlist]\ndef FCimprob(tlist, clrs, nmnstrs, smnstrs, nptrns,sptrns, sfxs):\n \"\"\"generates a list of NP trials with improbable monster-pattern combinations (and probable foil pics)\"\"\"\n improbclnr = [[[1,1],[2,2]],[[1,2],[2,1]], [[2,1],[1,2]],[[2,1],[1,2]],[[2,2],[1,1]],[[1,1],[2,2]]] # colour and number for the improbable noun phrases\n foilpat = [[0,1],[1,0],[0,1],[0,1],[1,0],[0,1]]\n random.shuffle(nmnstrs)\n random.shuffle(smnstrs)\n random.shuffle(nptrns)\n random.shuffle(sptrns)\n colourlist = list(range(2))\n random.shuffle(colourlist)\n nrdummy = ['1','2']\n random.shuffle(nrdummy)\n for m in range(6): # 6 monsters\n for p in range(2): # 2 patterns\n if m < 3:\n vismon = nmnstrs[m][0] # monster pic\n audmon = nmnstrs[m][1]\n vissem = 1\n vispat = sptrns[p][0]\n audpat = sptrns[p][1]\n vpf = foilpat[m][p] # 0 or 1\n vispatf = nptrns[vpf][0]\n audsem = sfxs[1][0]\n elif m > 2:\n n = m-3\n vissem = 2\n vismon = smnstrs[n][0]\n audmon = smnstrs[n][1]\n vispat = nptrns[p][0]\n audpat = nptrns[p][1]\n vpf = foilpat[m][p]\n vispatf = sptrns[vpf][0]\n audsem = sfxs[1][1]\n colp = improbclnr[m][p][0]-1 # 1 or 2 so 0 or 1\n cp = clrs[0][colp]\n cs = clrs[1][colp]\n nr = nrdummy[improbclnr[m][p][1]-1]\n pic = \"pictures/PNG/111100\" + str(cp) + str(vismon) + str(vissem) + str(vispat) + \"00.png\"\n fpic = \"pictures/PNG/111100\" + str(cp) + str(vismon) + str(vissem) + str(vispatf) + \"00.png\"\n sound = \"sounds/combined/11111001\" + str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + str(audpat) + '10000.wav' \n tlist.append([pic, sound, nr, fpic, 'FCimprbitem', 4])\ndef FCprob(tlist, clrs, nmnstrs, smnstrs, nptrns,sptrns, sfxs):\n \"\"\"generate a list of FC trials with probable NPs, with vocab, prob and number foils\"\"\"\n vocfoil = ['m', 'p', 'c','p','m','m','m','p','m','c','m','p']\n patfoil = [1,2,1,1,2,1,2,1,2,2,1,2]\n #smfoil = [4,5,3,5,6,1,6,1,2,4,2,3] old\n smfoil = [4,6,3,5,4,1,5,1,2,6,2,3]\n trtype = ['vocabitem', 'FCprobitems', 'FCnumbritem', 'FCsemanitem']\n # we're only using all four for the first 36 of these, the last 12 are for semantic trials but those changed to not have a pattern any longer. \n colnrmonpat = [[[1,1,1,1],[1,1,3,1],[1,1,6,2],[2,2,1,2],[2,2,3,2],[2,2,6,1],[1,2,2,1],[1,2,4,2],[1,2,5,2],[2,1,2,2],[2,1,4,1], [2,1,5,1]],[[1,2,1,1],[1,2,3,1],[1,2,6,2],[2,1,1,2],[2,1,3,2],[2,1,6,1],[1,1,2,1],[1,1,4,2],[1,1,5,2],[2,2,2,2],[2,2,4,1], [2,2,5,1]],[[2,1,1,1],[2,1,3,1],[2,1,6,2],[1,2,1,2],[1,2,3,2],[1,2,6,1],[2,2,2,1],[2,2,4,2],[2,2,5,2],[1,1,2,2],[1,1,4,1], [1,1,5,1]],[[2,2,1,1],[2,2,3,1],[2,2,6,2],[1,1,1,2],[1,1,3,2],[1,1,6,1],[2,1,2,1],[2,1,4,2],[2,1,5,2],[1,2,2,2],[1,2,4,1], [1,2,5,1]]]\n random.shuffle(nmnstrs)\n random.shuffle(smnstrs)\n random.shuffle(nptrns)\n random.shuffle(sptrns)\n colourlist = list(range(2))\n random.shuffle(colourlist)\n nrdummy = ['1','2']\n random.shuffle(nrdummy)\n scmfoil = genalt(smnstrs)\n nmfoil = genalt(nmnstrs)\n for a in range(4): # through all 4 types of testtrials\n for t in range(12): # through all 12 trials\n trialtype = trtype[a]\n inf = colnrmonpat[a][t]\n c = inf[0] # 1,2\n n = inf[1] # 1,2\n m = inf[2]-1 # 1-6 so 0-5\n p = inf[3]-1 # 1-2 so 0-1\n if m < 3:\n vismon = nmnstrs[m][0] # monster pic\n audmon = nmnstrs[m][1]\n vissem = 1\n vissemf = 2\n audsem = sfxs[1][0]\n vispat = nptrns[p][0]\n audpat = nptrns[p][1]\n q = 1-p # if p is 0 q is 1 and the other way around, just picks out the other pattern of the same type\n vvispatf = nptrns[q][0]\n r = patfoil[t]-1 # 0 or 1\n ipvispatf = sptrns[r][0]\n vvismonf = nmfoil[m][0] # foil if need be for vocab\n sf = smfoil[t]-4 # 1-6 except that for nm the smfoil would always be 4-6, or - 4 it would be 0-2\n svismonf = smnstrs[sf][0]\n elif m > 2:\n l = m-3\n vissem = 2\n vissemf = 1\n vismon = smnstrs[l][0]\n audmon = smnstrs[l][1]\n audsem = sfxs[1][1]\n vispat = sptrns[p][0]\n audpat = sptrns[p][1]\n q = 1-p\n vvispatf = sptrns[q][0]\n k = patfoil[t]-1\n ipvispatf = nptrns[k][0] ### smth wrong here\n vvismonf = scmfoil[l][0]\n sf = smfoil[t]-1\n svismonf = nmnstrs[sf][0]\n cp = clrs[0][c-1] # c is 1 or 2\n cf = 3-cp\n cs = clrs[1][c-1]\n nr = nrdummy[n-1]\n pic = \"pictures/PNG/111100\" + str(cp) + str(vismon) + str(vissem) + str(vispat) + \"00.png\"\n sound = \"sounds/combined/11111001\" + str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + str(audpat) + '10000.wav' \n if a == 0: # vocabitem\n if vocfoil[t] == 'm':\n fpic = \"pictures/PNG/111100\" + str(cp) + str(vvismonf) + str(vissem) + str(vispat) + \"00.png\"\n trialtype = 'FCvocabmons'\n critword = 3\n elif vocfoil[t] == 'p':\n fpic = \"pictures/PNG/111100\" + str(cp) + str(vismon) + str(vissem) + str(vvispatf) + \"00.png\"\n trialtype = 'FCvocabpatt'\n critword = 4\n elif vocfoil[t] == 'c':\n fpic = \"pictures/PNG/111100\" + str(cf) + str(vismon) + str(vissem) + str(vispat) + \"00.png\"\n trialtype = 'FCvocabcolr'\n critword = 2\n elif a == 1: # probable mon-pat item, so foil is improbable pattern\n fpic = \"pictures/PNG/111100\" + str(cp) + str(vismon) + str(vissem) + str(ipvispatf) + \"00.png\"\n critword = 4\n elif a == 2: # foil pic is the same, it's the nr that's diff\n fpic = \"pictures/PNG/111100\" + str(cp) + str(vismon) + str(vissem) + str(vispat) + \"00.png\"\n critword = 1\n elif a == 3:\n pic = \"pictures/PNG/111000\" + str(cp) + str(vismon) + str(vissem) + \"000.png\"\n fpic = \"pictures/PNG/111000\" + str(cp) + str(svismonf) + str(vissemf) + \"000.png\"\n sound = \"sounds/combined/11100001\" + str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + '000000.wav'\n critword = 1\n tlist.append([pic, sound, nr, fpic, trialtype, critword])\ndef FCvl(tlist, clrs, nmnstrs, smnstrs, nptrns, sptrns, vrbs, plnts, sfx, fcvllist):\n \"\"\"generates 6 fc test trials to test verb and landscape vocab\"\"\"\n planetlist = range(3)\n verblist = range(3)\n lfoils = genalt(planetlist)\n vfoils = genalt(verblist)\n for item in fcvllist: \n cgen = item[8]\n cp = clrs[0][cgen]\n cs = clrs[1][cgen]\n mgen = item[10]\n if item[9] == 'nice':\n vismon = nmnstrs[mgen][0]\n audmon = nmnstrs[mgen][1]\n vissem = 1\n audsem = sfx[1][0]\n elif item[9] == 'scary':\n vismon = smnstrs[mgen][0]\n audmon = smnstrs[mgen][1]\n vissem = 2\n audsem = sfx[1][1]\n pgen = item[12]\n if item[11] == 'nice':\n vispat = nptrns[pgen][0]\n audpat = nptrns[pgen][1]\n elif item[11] == 'scary':\n vispat = sptrns[pgen][0]\n audpat = sptrns[pgen][1]\n vgen = item[13]\n visverb = vrbs[0][vgen]\n audverb = vrbs[1][vgen]\n lgen = item[14]\n vislan = plnts[0][lgen]\n audlan = plnts[1][lgen]\n nr = item[15]\n cvf = vrbs[0][vfoils[vgen]] # vgen picks out which vfoil it will be\n clf = plnts[0][lfoils[lgen]] # lgen picks out which foil it will be\n pic = \"slides/v111111\"+str(cp) + str(vismon) + str(vissem) + str(vispat) + str(visverb) + str(vislan)+ 'n' + str(nr) + 'f1.png'\n sound = \"sounds/combined/11111111\" + str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + str(audpat) + '1' + str(audverb) + str(audsem) + str(nr) + str(audlan) + \".wav\"\n if item[7] == 'FCverb\\n':\n fpic = \"slides/v111111\"+str(cp) + str(vismon) + str(vissem) + str(vispat) + str(cvf) + str(vislan)+ 'n' + str(nr) + 'f1.png'\n critword = 6\n trialtype = 'FCvocabvvid'\n elif item[7] == 'FClandscape\\n':\n fpic = \"slides/v111111\"+str(cp) + str(vismon) + str(vissem) + str(vispat) + str(visverb) + str(clf)+ 'n' + str(nr) + 'f1.png'\n critword = 7\n trialtype = 'FCvocablvid'\n tlist.append([pic, sound, nr, fpic, trialtype, critword])\ndef EMgenerate(tlist, clrs, nmnstrs, smnstrs, nptrns, sptrns, vrbs, plnts, sfx, emlist):\n \"\"\"make error monitoring trials from input in emlist\"\"\"\n for item in emlist: \n cgen = item[8]\n cs = clrs[1][cgen]\n mgen = item[10]\n if item[9] == 'nice':\n audmon = nmnstrs[mgen][1]\n audsem = sfx[1][0]\n audsemf = sfx[1][1]\n elif item[9] == 'scary':\n audmon = smnstrs[mgen][1]\n audsem = sfx[1][1]\n audsemf = sfx[1][0]\n pgen = item[12]\n if item[11] == 'nice':\n audpat = nptrns[pgen][1]\n elif item[11] == 'scary':\n audpat = sptrns[pgen][1]\n vgen = item[13]\n audverb = vrbs[1][vgen]\n lgen = item[14]\n audlan = plnts[1][lgen]\n nr = item[15]\n sound = \"sounds/combined/11111111\" + str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + str(audpat) + '1' + str(audverb) + str(audsem) + str(nr) + str(audlan) + \".wav\"\n correcttrial = 1 # and set to 0 for incorrect ones.\n trialtype = item[7]\n trialtype = trialtype[:-1]\n if trialtype == 'EMimprob':\n trialtype = 'EMimpr'\n elif trialtype == 'EMswitch1':\n trialtype = 'EMsw1'\n elif trialtype == 'EMswitch2':\n trialtype = 'EMsw2'\n elif trialtype == 'EMswitch3':\n trialtype = 'EMsw3'\n elif trialtype == 'EMswitch4':\n trialtype = 'EMsw4'\n # this is all good for the correct trials (EMimprob, EMprob). For the other trials, generate the sound with the error\n # individual elements to the sentence\n det = \"sounds/t1w1s\" + str(audsem) + \"n\" +str(nr) +\".wav\"\n col = \"sounds/t2w\" + str(cs) + \"s\" + str(audsem) + \"n\" +str(nr) +\".wav\"\n mon = \"sounds/t3w\" + str(audmon) + \"s\" + str(audsem) + \"n\" +str(nr) +\".wav\"\n mar = \"sounds/combined/0001100000000000\" + str(audpat) + \"10000.wav\" # with ot\n mar1 = \"sounds/t4w\" + str(audpat) + \".wav\"\n ot = \"sounds/t5w1.wav\"\n ver = \"sounds/t6w\" + str(audverb) + \"s\" + str(audsem) + \"n\" + str(nr) + \".wav\"\n lan = \"sounds/t7w\" + str(audlan) + \".wav\"\n nrf = 3-nr # so the other number\n critword = 7\n if item[7][3] == 'a' or item[7][3] == 'n':\n correcttrial = 0\n if item[7] == 'EMnadj\\n':\n critword = 3\n mon = \"sounds/t3w\" + str(audmon) + \"s\" + str(audsem) + \"n\" +str(nrf) +\".wav\"\n name = \"nadj1111111\"+ str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nrf) + str(audpat) + str(audverb) + str(audsem) + str(nr) + str(audlan) + \".wav\"\n elif item[7] == 'EMsadj\\n':\n critword = 3\n mon = \"sounds/t3w\" + str(audmon) + \"s\" + str(audsemf) + \"n\" +str(nr) +\".wav\"\n name = \"sadj1111111\"+ str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsemf) + str(nr) + str(audpat) + str(audverb) + str(audsem) + str(nr) + str(audlan) + \".wav\" \n elif item[7] == 'EMnnadj\\n':\n critword = 6\n ver = \"sounds/t6w\" + str(audverb) + \"s\" + str(audsem) + \"n\" + str(nrf) + \".wav\"\n name = \"nnadj1111111\"+ str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + str(audpat) + str(audverb) + str(audsem) + str(nrf) + str(audlan) + \".wav\" \n elif item[7] == 'EMsnadj\\n':\n critword = 6\n ver = \"sounds/t6w\" + str(audverb) + \"s\" + str(audsemf) + \"n\" + str(nr) + \".wav\"\n name = \"snadj1111111\"+ str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + str(audpat) + str(audverb) + str(audsemf) + str(nr) + str(audlan) + \".wav\" \n sname = \"data/s\" + str(subjectnr) + \"/errortrials/\" + name\n sound6(det, col, mon, mar, ver, lan, sname) # generate the relevant soundfile\n sounddurlist.append([sname, getdur(sname), getdur(det), getdur(col), getdur(mon), getdur(mar1),getdur(ot), getdur(ver), getdur(lan)])\n sound = sname\n elif item[7][3] == 'w': # switch trials \n correcttrial = 0\n if item[7] == 'EMswitch1\\n': # 1324567 (switch monster and color) - adjacent, early, hard\n critword = 2\n name = \"data/s\" + str(subjectnr) + \"/errortrials/1switch1111111\"+ str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audpat) + str(audverb) + str(audsem) + str(nr) + str(audlan) + \".wav\" \n sound6(det,mon,col,mar,ver, lan, name)\n sounddurlist.append([name, getdur(name), getdur(det), getdur(mon), getdur(col), getdur(mar1), getdur(ot), getdur(ver), getdur(lan)])\n elif item[7] == 'EMswitch2\\n': # 1273456 (put planet between color and monster) - salient\n critword = 3\n name = \"data/s\" + str(subjectnr) + \"/errortrials/2switch1111111\"+ str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audlan) + str(audmon) + str(audsem) + str(nr) + str(audpat) + str(audverb) + str(audsem) + str(nr) + \".wav\" \n sound6(det,col,lan, mon, mar, ver, name)\n sounddurlist.append([name, getdur(name), getdur(det), getdur(col), getdur(lan), getdur(mon), getdur(mar1), getdur(ot), getdur(ver)])\n elif item[7] == 'EMswitch3\\n': # 1234657 (switch ot and verb) - late, hard\n critword = 5\n name = \"data/s\" + str(subjectnr) + \"/errortrials/3switch1111111\"+ str(audsem) + str(nr) + str(cs) + str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + str(audpat) + str(audverb) + str(audsem) + str(nr) + str(audlan) + \".wav\" \n sound7(det,col, mon, mar1, ver, ot, lan, name)\n sounddurlist.append([name, getdur(name), getdur(det), getdur(col), getdur(mon), getdur(mar1), getdur(ver), getdur(ot), getdur(lan)])\n elif item[7] == 'EMswitch4\\n': # 1345627 (color in between verb and planet) - salient\n critword = 2\n name = \"data/s\" + str(subjectnr) + \"/errortrials/4switch1111111\"+ str(audsem) + str(nr) + str(audmon) + str(audsem) + str(nr) + str(audpat) + str(audverb) + str(audsem) + str(nr)+ str(cs) + str(audsem) + str(nr) + str(audlan) + \".wav\" \n sound6(det, mon, mar, ver,col, lan, name)\n sounddurlist.append([name, getdur(name), getdur(det), getdur(mon), getdur(mar1), getdur(ot), getdur(ver), getdur(col), getdur(lan)]) \n sound = name\n tlist.append([sound, trialtype, correcttrial, critword])\n# functions to paste sounds together, only used in error monitoring to generate sentences with errors.\ndef soundrename(old, new):\n \"\"\"copy and rename a sound\"\"\"\n shutil.copy(old,new)\ndef soundcombine(sound1,sound2, newsound):\n \"\"\"grabs two sounds and pastes them together\"\"\"\n outfile = newsound\n infiles = [sound1,sound2]\n data= []\n for infile in infiles:\n w = wave.open(infile, 'rb')\n data.append( [w.getparams(), w.readframes(w.getnframes())] )\n w.close()\n output = wave.open(outfile, 'wb')\n output.setparams(data[0][0])\n output.writeframes(data[0][1])\n output.writeframes(data[1][1])\n output.close()\ndef soundtriplet(s1,s2,s3,s4):\n \"\"\"combine 3 sounds\"\"\"\n soundcombine(s1,s2,\"temp.wav\")\n soundcombine(\"temp.wav\", s3, s4)\ndef sound4(s1,s2,s3,s4,s5):\n \"\"\"combine 4 sounds\"\"\"\n soundtriplet(s1,s2,s3,\"t.wav\")\n soundcombine(\"t.wav\", s4, s5)\ndef sound5(s1,s2,s3,s4,s5,s6):\n \"\"\" combine 5 sounds\"\"\"\n soundtriplet(s1,s2,s3,\"t1.wav\")\n soundcombine(s4,s5, \"t2.wav\")\n soundcombine(\"t1.wav\", \"t2.wav\",s6)\ndef sound6(s1,s2,s3,s4,s5,s6,s7):\n \"\"\" combine 6 sounds\"\"\"\n soundtriplet(s1,s2,s3,\"tt1.wav\")\n soundtriplet(s4,s5,s6, \"tt2.wav\")\n soundcombine(\"tt1.wav\", \"tt2.wav\",s7)\ndef sound7(s1,s2,s3,s4,s5,s6,s7, s8):\n \"\"\"combine 7 sounds\"\"\"\n sound4(s1,s2,s3,s4, \"tt1.wav\")\n soundtriplet(s5,s6,s7, \"tt2.wav\")\n soundcombine(\"tt1.wav\", \"tt2.wav\",s8)\n\n# most instructions are in the folder 'instructions' for easy editing. # the if statement is just to be able to fold this away.\nread = True\nif read == True:\n g = open('instructions/activecompmessage1bcd.txt')\n activecompmessage1bcd = g.read()\n g.close()\n g = open('instructions/activecompmessage2.txt')\n activecompmessage2 = g.read()\n g.close()\n g = open('instructions/activecompmessage11.txt')\n activecompmessage11 = g.read()\n g.close()\n g = open('instructions/activeprodmessage.txt')\n activeprodmessage = g.read()\n g.close()\n g = open('instructions/activeprodmessage1.txt')\n activeprodmessage1 = g.read()\n g.close()\n g = open('instructions/activeprodmessage2.txt')\n activeprodmessage2 = g.read()\n g.close()\n g = open('instructions/combinedphrases.txt')\n combinedphrases = g.read()\n g.close()\n g = open('instructions/forcedchoicemessage.txt')\n forcedchoicemessage = g.read()\n g.close()\n g = open('instructions/openingmessagec.txt')\n openingmessagec = g.read()\n g.close()\n g = open('instructions/openingmessagep.txt')\n openingmessagep = g.read()\n g.close()\n g = open('instructions/overviewmessage.txt')\n overviewmessage = g.read()\n g.close()\n g = open('instructions/passivemessage.txt')\n passivemessage = g.read()\n g.close()\n g = open('instructions/passivemessage1.txt')\n passivemessage1 = g.read()\n g.close()\n g = open('instructions/passivemessage2.txt')\n passivemessage2 = g.read()\n g.close()\n g = open('instructions/vocabtestmessage1.txt')\n vocabtestmessage1 = g.read()\n g.close()\n g = open('instructions/endmessagec.txt')\n endmessagec = g.read()\n g.close()\n g = open('instructions/endmessagep.txt')\n endmessagep = g.read()\n g.close()\n\n # these instructions include unicode and are only available right here. \n activecompmessage = u\"ACTIVE LEARNING BLOCK\\n\\n\\n\\n\\n[during these trials, press '\\u2260' for mismatch and '=' for match]\\n\\n\\n\\n(press ENTER to start)\"\n activecompmessage1a = u\"Next, we'll do an active learning round. Active learning will help you remember the words better.\\n\\nIn active learning, you will see a picture and hear some speech. Your job is to decide whether the picture and the speech match or not. You will press the key marked '=' on the right hand side of the keyboard if you think that the picture and speech match. If you think that they don't match, you will press the key marked '\\u2260' on the left side of the keyboard. \"\n activecompmessage1 = activecompmessage1a + activecompmessage1bcd\n errormonitoringmessage = u\"Let's see how well you know the language! \\n\\nIn this final test, you'll hear a sentence and your job is to indicate with a buttonpress whether this could be a correct sentence in the novel language or whether there's a mistake in it. Do this AS FAST AS POSSIBLE. Once you know the answer, just press the button, even if the sentence is still unfolding.\\n\\nPress '\\u2260' for mistake and '=' for correct. In order to answer as fast as possible, keep your index fingers on the keys so that you can press a button as soon as you know the answer.\\n\\nSo note that you will only HEAR a sentence, you will not see a picture on the screen!\\n\\nThis is a long test, so there are some short breaks during the test. \\n\\n\\n\\n(press ENTER to continue)\\n.\"\n\n# first, get the subjectnr and conditionnr\nsubjectnr = getsubjectnumber()\n# get condition (1 is comp, 2 is prod)\nconditionnr = getconditionnumber()\n# Open a file for logging the experiment \nfilename = 'data/s' + str(subjectnr) + '/log' + str(subjectnr) + '.txt'\nf = open(filename, 'w') \nf.write(\"\\ncondition = %d\" %conditionnr)\n\n# this if statement is just to be able to fold all of the experiment generating away\nsetup = True\nif setup == True:\n # Assign word-object mappings for this person and log them\n colors = [[1,2],[1,2],\"colors\", 'c',2] # colors are 1-6, these are colors, wordtype 2, total of 6\n monsters = [[1,2,3,5,6,7],[1,2,3,4,5,6], \"monsters\", 'm',6]\n patterns = [[1,2,3,4],[1,2,3,4], \"patterns\", 'p',4]\n verbs = [[1,2,3],[1,2,3], \"verbs\",'v',3] \n landscapes = [[1,2,3],[1,2,3], \"landscapes\",'l',3] \n suffixes = [[1,2],[1,2], \"suffixes\", 's', 2]\n assignlanguage(colors)\n assignlanguage(monsters)\n assignlanguage(patterns)\n assignlanguage(verbs)\n assignlanguage(landscapes)\n assignlanguage(suffixes)\n\n nicemonsterlist = []\n scarymonsterlist = []\n for i in range(len(monsters[0])):\n vismon = monsters[0][i]\n audmon = monsters[1][i]\n if vismon < 4:\n nicemonsterlist.append([vismon, audmon])\n elif vismon > 4:\n scarymonsterlist.append([vismon, audmon])\n\n nicemonsterlistshuf = []\n scarymonsterlistshuf = []\n for i in range(len(monsters[0])):\n vismon = monsters[0][i]\n audmon = monsters[1][i]\n if vismon < 4:\n nicemonsterlistshuf.append([vismon, audmon])\n elif vismon > 4:\n scarymonsterlistshuf.append([vismon, audmon])\n\n nicepatternlist = []\n scarypatternlist = []\n for i in range(len(patterns[0])):\n vispat = patterns[0][i]\n audpat = patterns[1][i]\n if suffixes[0][0] == 1: # nice monsters get stripy patterns\n if vispat < 3:\n nicepatternlist.append([vispat, audpat])\n elif vispat > 2:\n scarypatternlist.append([vispat, audpat])\n elif suffixes[0][0] == 2: # nice monsters get dotty patterns\n if vispat < 3:\n scarypatternlist.append([vispat, audpat])\n elif vispat > 2:\n nicepatternlist.append([vispat, audpat])\n\n nicepatternlistshuf = []\n scarypatternlistshuf = []\n for i in range(len(patterns[0])):\n vispat = patterns[0][i]\n audpat = patterns[1][i]\n if suffixes[0][0] == 1: # nice monsters get stripy patterns\n if vispat < 3:\n nicepatternlistshuf.append([vispat, audpat])\n elif vispat > 2:\n scarypatternlistshuf.append([vispat, audpat])\n elif suffixes[0][0] == 2: # nice monsters get dotty patterns\n if vispat < 3:\n scarypatternlistshuf.append([vispat, audpat])\n elif vispat > 2:\n nicepatternlistshuf.append([vispat, audpat])\n\n file = open('sounds/listofsounddurations.txt', 'r')\n sounddurlist = []\n for line in file:\n trial = line.split(\"\\t\")\n sounddurlist.append(trial)\n\n for it in sounddurlist:\n it[8] = it[8][:-1]\n it[0] = \"sounds/\" + it[0]\n itsum = 0\n for i in range(1,9):\n it[i] = float(it[i])\n if i > 1:\n itsum += it[i]\n it.append(itsum)\n\n subjecttriallist = 'data/s' + str(subjectnr) + '/fulltriallist.txt'\n file = open(subjecttriallist, 'r')\n fullgeneratedlist = []\n for line in file:\n trial = line.split(\"\\t\")\n if trial[1] == 'c1':\n trial.append(0)\n elif trial[1] == 'c2':\n trial.append(1)\n if trial[2] == 'm1':\n trial.append('nice')\n trial.append(0)\n elif trial[2] == 'm2':\n trial.append('nice')\n trial.append(1)\n elif trial[2] == 'm3':\n trial.append('nice')\n trial.append(2)\n elif trial[2] == 'm4':\n trial.append('scary')\n trial.append(0)\n elif trial[2] == 'm5':\n trial.append('scary')\n trial.append(1)\n elif trial[2] == 'm6':\n trial.append('scary')\n trial.append(2)\n if trial[3] == 'p1':\n trial.append('nice')\n trial.append(0)\n elif trial[3] == 'p2':\n trial.append('nice')\n trial.append(1)\n elif trial[3] == 'p3':\n trial.append('scary')\n trial.append(0)\n elif trial[3] == 'p4':\n trial.append('scary')\n trial.append(1)\n if trial[4] == 'v1':\n trial.append(0)\n elif trial[4] == 'v2':\n trial.append(1)\n elif trial[4] == 'v3':\n trial.append(2)\n if trial[5] == 'l1':\n trial.append(0)\n elif trial[5] == 'l2':\n trial.append(1)\n elif trial[5] == 'l3':\n trial.append(2)\n if trial[6] == 'n1':\n trial.append(1)\n elif trial[6] == 'n2':\n trial.append(2)\n fullgeneratedlist.append(trial)\n fullgeneratedlist.pop(0)\n\n exposuregeneratedlist = [x for x in fullgeneratedlist if x[7] == 'exposure\\n']\n FCgeneratedlist = [x for x in fullgeneratedlist if x[7][0] == 'F']\n EMgeneratedlist = [x for x in fullgeneratedlist if x[7][1] == 'M']\n\n monster1 = []\n monster2 = []\n trialgenm(monster1, monsters, suffixes)\n trialgenm(monster2, monsters, suffixes) # create a copy that remains in order for forced choice vocab trials\n random.shuffle(monster1)\n\n color1 = []\n trialgenc(color1, colors)\n\n coloredmonstertrials = []\n trialgenCM(coloredmonstertrials, colors, monsters, suffixes)\n\n patterns1 = []\n trialgenp(patterns1, patterns)\n random.shuffle(patterns1)\n\n NPlist = []\n trialgenNP(NPlist, colors, nicemonsterlistshuf, scarymonsterlistshuf, nicepatternlistshuf, scarypatternlistshuf, suffixes)\n\n verbs1 = []\n trialgenv(verbs1, verbs)\n landscapes1 = []\n trialgenl(landscapes1, landscapes)\n\n vl = []\n attachalt(vl, verbs1)\n attachalt(vl, landscapes1)\n\n ftlist = trialgenfull(colors, nicemonsterlist, scarymonsterlist, nicepatternlist, scarypatternlist, verbs, landscapes, suffixes, exposuregeneratedlist)\n plist = ftlist[0]\n alist = ftlist[1]\n\n vocabtesttrials = []\n # pick half plural for the monster vocab trials\n mpldummy = list(range(6))\n random.shuffle(mpldummy)\n nmvocab = []\n smvocab = []\n for i in range(6):\n pic = monster2[i][0]\n if mpldummy[i] % 2 == 0: # if singular\n pl = '1'\n snd = monster2[i][1]\n elif mpldummy[i] % 2 == 1: # if plural\n pl = '2'\n snd = monster2[i][4] # plural sound\n if monster2[i][5] == 1: #vissem\n nmvocab.append([pic, snd, 'm', pl])\n elif monster2[i][5] == 2:\n smvocab.append([pic, snd, 'm', pl])\n attachalt(vocabtesttrials, nmvocab) # so that foils for nice monsters are nice monsters\n attachalt(vocabtesttrials, smvocab) # so that foils for scary monsters are scary monsters\n attachalt(vocabtesttrials, color1)\n attachalt(vocabtesttrials, patterns1)\n attachalt(vocabtesttrials, verbs1)\n attachalt(vocabtesttrials, landscapes1)\n random.shuffle(vocabtesttrials) \n\n FClist = []\n FCvl(FClist, colors, nicemonsterlist, scarymonsterlist, nicepatternlist, scarypatternlist, verbs, landscapes, suffixes, FCgeneratedlist)\n FCprob(FClist, colors, nicemonsterlistshuf, scarymonsterlistshuf, nicepatternlistshuf, scarypatternlistshuf, suffixes) # 48 probable monster-pattern combi trials with diff foils depending on what we're testing here\n FCimprob(FClist, colors, nicemonsterlistshuf, scarymonsterlistshuf, nicepatternlistshuf, scarypatternlistshuf, suffixes) # 12 improbable monster-pattern combi trials, foil is always other type of patterns\n random.shuffle(FClist) \n\n errorlist = []\n EMgenerate(errorlist, colors, nicemonsterlist, scarymonsterlist, nicepatternlist, scarypatternlist, verbs, landscapes, suffixes, EMgeneratedlist)\n\n random.shuffle(errorlist)\n\n for it in sounddurlist:\n itsum = 0\n for i in range(1,9):\n if i > 1:\n itsum += it[i]\n it.append(itsum)\n\n# here, pick out as the experimenter what blocks you want to see (works only if subjnr == 1)\n# default it plays nothing if subjectnr is 1 (all set to 0), so set to 1 the ones you want to play\n# the if statement is just to be able to fold it\nshow = True\nif show == True:\n showtrial = []\n showtrial.append(0) # 6 trials monster singular passive\n showtrial.append(0) # 6 trials monster singular active comprehension 1\n showtrial.append(0) # 6 trials monster singular active comprehension 2\n showtrial.append(0) # 6 trials monster singular active production 1\n showtrial.append(0) # 6 trials monster singular active production 2\n showtrial.append(0) # 6 trials monster plural passive\n showtrial.append(0) # 6 trials monster plural active comprehension 1\n showtrial.append(0) # 6 trials monster plural active comprehension 2\n showtrial.append(0) # 6 trials monster plural active production 1\n showtrial.append(0) # 6 trials monster plural active production 2\n showtrial.append(0) # 2 trials color passive\n showtrial.append(0) # 2 trials color active comprehension\n showtrial.append(0) # 2 trials color active production\n showtrial.append(0) # 6 trials colored monsters passive\n showtrial.append(0) # 6 trials colored monsters active comprehension\n showtrial.append(0) # 6 trials colored monsters active production\n showtrial.append(0) # 4 trials pattern passive\n showtrial.append(0) # 4 trials pattern active comprehension\n showtrial.append(0) # 4 trials pattern active production\n showtrial.append(0) # 2*6 = 12 trials full NP passive\n showtrial.append(0) # 2*6 = 12 trials full NP active comprehension\n showtrial.append(0) # 2*6 = 12 trials full NP active production\n showtrial.append(0) # 6 trials verb/landscape passive\n showtrial.append(0) # 6 trials verb/landscape active comprehension 1\n showtrial.append(0) # 6 trials verb/landscape active comprehension 2\n showtrial.append(0) # 6 trials verb/landscape active production 1\n showtrial.append(0) # 6 trials verb/landscape active production 2\n showtrial.append(0) # 6*6 = 36 trial full sentence passive\n showtrial.append(0) # 6*6 = 36 trial full sentence active comprehension\n showtrial.append(0) # 6*6 = 36 trial full sentence active production\n showtrial.append(0) # 18 trials vocabulary noun test forced choice\n showtrial.append(0) # 66 trials forced choice\n showtrial.append(0) # 124 error monitoring trials\n\n# make sure that for real subject numbers it always shows all trials\nif subjectnr > 1:\n for k in range(len(showtrial)):\n showtrial[k] = 1\nprint (showtrial)\n# Define the window that the experiment will be run in. In a lot of psychopy functions you will see this window as the first argument, there we tell it to draw stuff in this window.\nwin = visual.Window(fullscr = False, color = 'white', units = 'pix', size = [1200,700], allowGUI = None)\ntrialnr = 1\n\n# this is cause the mic doesn't work on my laptop\nif subjectnr > 2:\n microphone.switchOn(sampleRate=16000)\n\n\n# Opening screen\nif conditionnr == 1:\n showmessage(win, openingmessagec)\nelif conditionnr == 2:\n showmessage(win, openingmessagep)\nshowmessage(win, overviewmessage)\nnow = time.strftime(\"%c\")\nf.write(\"\\n\\nThey started the experiment at \\t\\t\" + time.strftime(\"%c\") + '\\n\\n')\n\n# this list will keep track of nr of correct active comp trials per block during training\nactivecompcorrect = []\n\nf.write(\"\\n\\nsubjectnr\\tconditionnr\\ttrialnr\\ttrialtype\\titemtype\\tcorrectanswer?\\tkey\\tmatch/mismatch\\tRT\\tsound\\tpic\\tfoilpic\\n\")\n\n\n# Explanation of passive learning trals\n# 1 word vocab learning trials\nshowmessage(win, passivemessage1)\nshowmessage(win, passivemessage)\n# Play a round of singular passive noun learning trials\nfor t in monster1:\n if showtrial[0] == 1:\n passivetrial(win, t[0], t[1])\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"P\\tmsg\\t-\\t-\\t-\\t-\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm, RT and foilpic are not applicable here! \n trialnr = trialnr + 1\nshowmessage(win,passivemessage2)\nif conditionnr == 1:\n showmessage(win, activecompmessage1)\n if subjectnr > 1:\n k = activecomptrial(win, \"pictures/cat.png\", \"pictures/cat.png\", \"sounds/cat.wav\")\n showmessage(win, \"Great, let's do another practice trial. \\n\\n\\n\\n(press ENTER to continue)\")\n if subjectnr > 1:\n k = activecomptrial(win, \"pictures/cat.png\", \"pictures/dog.png\", \"sounds/dog.wav\")\n showmessage(win, activecompmessage11)\n showmessage(win, activecompmessage)\n if showtrial[1] == 1:\n trialnr = activecompblock(monster1, trialnr, 'msg')\n random.shuffle(monster1)\n if showtrial[2] == 1:\n trialnr = activecompblock(monster1, trialnr, 'msg')\n showmessage(win, activecompmessage2)\nelif conditionnr == 2:\n showmessage(win, activeprodmessage1)\n # Explanation of active production learning trial\n showmessage(win, activeprodmessage)\n # Play an active production learning trial\n random.shuffle(monster1)\n for t in monster1:\n if showtrial[3] == 1:\n info = activeprodtrial(win, t[0], t[1])\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\tmsg\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here! \n trialnr = trialnr + 1\n random.shuffle(monster1)\n for t in monster1:\n if showtrial[4] == 1:\n info = activeprodtrial(win, t[0], t[1])\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\tmsg\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here!\n trialnr = trialnr + 1\n showmessage(win, activeprodmessage2)\n\nshowmessage(win, passivemessage)\nrandom.shuffle(monster1) # now just pick the plural sound\nfor t in monster1:\n if showtrial[5] == 1:\n passivetrial(win, t[0], t[4], pl = '2')\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"P\\tmpl\\t-\\t-\\t-\\t-\\t\" + t[4] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm, RT and foilpic are not applicable here! \n trialnr = trialnr + 1 \n\nif conditionnr == 1:\n random.shuffle(monster1)\n showmessage(win, activecompmessage)\n if showtrial[6] == 1:\n trialnr = activecompblock(monster1, trialnr, 'mpl', pl = '2')\n random.shuffle(monster1)\n if showtrial[7] == 1:\n trialnr = activecompblock(monster1, trialnr, 'mpl', pl = '2')\nelif conditionnr == 2:\n # Explanation of active production learning trial\n showmessage(win, activeprodmessage)\n # Play an active production learning trial\n random.shuffle(monster1)\n for t in monster1:\n if showtrial[8] == 1:\n info = activeprodtrial(win, t[0], t[4], pl = '2')\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\tmpl\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[4] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here! \n trialnr = trialnr + 1\n random.shuffle(monster1)\n for t in monster1:\n if showtrial[9] == 1:\n info = activeprodtrial(win, t[0], t[4], pl = '2')\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\tmpl\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[4] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here! \n trialnr = trialnr + 1\n\n# a block of color nouns \nshowmessage(win, passivemessage)\nrandom.shuffle(color1)\nfor t in color1:\n if showtrial[10] == 1:\n passivetrial(win, t[0], t[1])\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"P\\tc\\t-\\t-\\t-\\t-\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm, RT and foilpic are not applicable here! \n trialnr = trialnr + 1\n\nif conditionnr == 1:\n showmessage(win, activecompmessage)\n if showtrial[11] == 1:\n trialnr = activecompblock(color1, trialnr, 'c')\nelif conditionnr == 2:\n # Explanation of active production learning trial\n showmessage(win, activeprodmessage)\n # Play an active production learning trial\n random.shuffle(color1)\n for t in color1:\n if showtrial[12] == 1:\n info = activeprodtrial(win, t[0], t[1])\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\tc\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here! \n trialnr = trialnr + 1\n\n# now do colored monsters\nshowmessage(win, combinedphrases)\npassivernd = coloredmonstertrials[0]\nshowmessage(win, passivemessage)\nrandom.shuffle(passivernd)\nfor t in passivernd:\n if showtrial[13] == 1:\n passivetrial(win, t[1], t[4], pl = str(t[8]))\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" %trialnr + \"P\\tcm\\t-\\t-\\t-\\t-\\t\" + t[4] + \"\\t\" + t[1] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm, RT and foilpic are not applicable here! \n trialnr = trialnr + 1 \n\nactivernd = coloredmonstertrials[1]\nif conditionnr == 1:\n showmessage(win, activecompmessage)\n random.shuffle(activernd)\n tc = 0\n for t in activernd:\n info = ['none', 0]\n if showtrial[14] == 1:\n info = activecomptrial(win,t[9],t[1], t[4], pl = str(t[8]))\n key = info[0]\n m = 'mismatch'\n ck = 'none'\n if t[9] == t[1]:\n m = 'yesmatch'\n if m == 'mismatch':\n if key == 'l':\n ck = '0'\n elif key == 'f':\n ck = '1'\n tc = tc + 1\n if m == 'yesmatch':\n if key == 'f':\n ck = '0'\n elif key == 'l':\n ck = '1'\n tc = tc + 1\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AC\\tcm\\t\"+ ck + \"\\t\" + key + \"\\t\" + m + \"\\t\" + str(info[1]) + \"\\t\" + t[4] + \"\\t\" + t[1] + \"\\t\" + t[9] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; \n trialnr = trialnr + 1\n activecompcorrect.append([tc,'cm'])\nelif conditionnr == 2:\n # Explanation of active production learning trial\n showmessage(win, activeprodmessage)\n # Play an active production learning trial\n random.shuffle(activernd)\n for t in activernd:\n if showtrial[15] == 1:\n info = activeprodtrial(win, t[1], t[4], pl = str(t[8]))\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\tcm\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[4] + \"\\t\" + t[1] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here! \n trialnr = trialnr + 1\n\n# block of markings\nshowmessage(win, passivemessage)\nfor t in patterns1:\n if showtrial[16] == 1:\n passivetrial(win, t[0], t[1])\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"P\\tp\\t-\\t-\\t-\\t-\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm, RT and foilpic are not applicable here! \n trialnr = trialnr + 1\nif conditionnr == 1:\n showmessage(win, activecompmessage)\n if showtrial[17] == 1:\n trialnr = activecompblock(patterns1, trialnr, 'p')\nelif conditionnr == 2:\n # Explanation of active production learning trial\n showmessage(win, activeprodmessage)\n # Play an active production learning trial\n random.shuffle(patterns1)\n for t in patterns1:\n if showtrial[18] == 1:\n info = activeprodtrial(win, t[0], t[1])\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\tp\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here! \n trialnr = trialnr + 1\n\n# full NPs\nfor r in range(4):\n round = NPlist[r]\n if r % 2 == 0:\n showmessage(win, passivemessage)\n random.shuffle(round)\n for t in round:\n if showtrial[19] == 1:\n passivetrial(win, t[0], t[4], pl = str(t[8]))\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"P\\tNP\\t-\\t-\\t-\\t-\\t\" + t[4] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm, RT and foilpic are not applicable here! \n trialnr = trialnr + 1 \n elif r % 2 == 1:\n if conditionnr == 1:\n showmessage(win, activecompmessage)\n random.shuffle(round)\n tc = 0\n for t in round:\n info = ['none', 0]\n if showtrial[20] == 1:\n info = activecomptrial(win,t[9],t[0], t[4], pl = str(t[8]))\n key = info[0]\n m = 'mismatch'\n ck = 'none'\n if t[9] == t[0]:\n m = 'yesmatch'\n if m == 'mismatch':\n if key == 'l':\n ck = '0'\n elif key == 'f':\n ck = '1'\n tc = tc + 1\n if m == 'yesmatch':\n if key == 'f':\n ck = '0'\n elif key == 'l':\n ck = '1'\n tc = tc + 1\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AC\\tNP\\t\"+ ck + \"\\t\" + key + \"\\t\" + m + \"\\t\" + str(info[1]) + \"\\t\" + t[4] + \"\\t\" + t[0] + \"\\t\" + t[9] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; \n trialnr = trialnr + 1\n activecompcorrect.append([tc,'NP'])\n elif conditionnr == 2:\n # Explanation of active production learning trial\n showmessage(win, activeprodmessage)\n # Play an active production learning trial\n random.shuffle(round)\n for t in round:\n if showtrial[21] == 1:\n info = activeprodtrial(win, t[0], t[4], pl = str(t[8]))\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\tNP\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[4] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here! \n trialnr = trialnr + 1\n\n# landscapes and verbs\nshowmessage(win, passivemessage)\nrandom.shuffle(vl)\nfor t in vl:\n vd = 'no'\n if t[2] == 'v':\n vd = 'yes'\n if showtrial[22] == 1:\n passivetrial(win, t[0], t[1], vid = vd)\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"P\\t\" + t[2] +\"\\t-\\t-\\t-\\t-\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm, RT and foilpic are not applicable here!\n trialnr = trialnr + 1\n\nif conditionnr == 1:\n showmessage(win, activecompmessage)\n random.shuffle(vl)\n picknonmatch = range(len(vl))\n random.shuffle(picknonmatch) # random shuffle to pick which half of the trials get to be mismatch\n tc = 0\n for t in range(len(vl)):\n trial = vl[t]\n ck = 'none'\n vd = 'no'\n if trial[2] == 'v':\n vd = 'yes'\n if picknonmatch[t] < len(vl)/2:# match\n if showtrial[23] == 1:\n info = activecomptrial(win, trial[0],trial[0], trial[1], vid = vd)\n if key == 'l':\n ck = '1'\n tc = tc + 1\n elif key == 'f':\n ck = '0'\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AC\\t\" + trial[2] + \"\\t\"+ ck + \"\\t\" + key + \"\\tyesmatch\\t\" + str(info[1]) + \"\\t\" + trial[1] + \"\\t\" + trial[0] + \"\\t\" + trial[0] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; \n else: # mismatch\n if showtrial[23] == 1:\n info = activecomptrial(win, trial[4], trial[0], trial[1], vid = vd)\n key = info[0]\n if key == 'f':\n ck = '1'\n tc = tc + 1\n elif key == 'l':\n ck = '0'\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AC\\t\" + trial[2] + \"\\t\"+ ck + \"\\t\" + key + \"\\tmismatch\\t\" + str(info[1]) + \"\\t\" + trial[1] + \"\\t\" + trial[0] + \"\\t\" + trial[4] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; \n trialnr = trialnr + 1\n activecompcorrect.append([tc, 'vl'])\n tc = 0\n random.shuffle(vl)\n picknonmatch = range(len(vl))\n random.shuffle(picknonmatch) # random shuffle to pick which half of the trials get to be mismatch\n for t in range(len(vl)):\n trial = vl[t]\n ck = 'none'\n vd = 'no'\n if trial[2] == 'v':\n vd = 'yes'\n if picknonmatch[t] < len(vl)/2:# match\n if showtrial[24] == 1:\n info = activecomptrial(win, trial[0],trial[0], trial[1], vid = vd)\n key = info[0]\n if key == 'l':\n ck = '1'\n tc = tc + 1\n elif key == 'f':\n ck = '0'\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AC\\t\" + trial[2] + \"\\t\"+ ck + \"\\t\" + key + \"\\tyesmatch\\t\" + str(info[1]) + \"\\t\" + trial[1] + \"\\t\" + trial[0] + \"\\t\" + trial[0] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; \n else: # mismatch\n if showtrial[24] == 1:\n info = activecomptrial(win, trial[4], trial[0], trial[1], vid = vd)\n key = info[0]\n if key == 'f':\n ck = '1'\n tc = tc + 1\n elif key == 'l':\n ck = '0'\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AC\\t\" + trial[2] + \"\\t\"+ ck + \"\\t\" + key + \"\\tmismatch\\t\" + str(info[1]) + \"\\t\" + trial[1] + \"\\t\" + trial[0] + \"\\t\" + trial[4] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; \n trialnr = trialnr + 1\n activecompcorrect.append([tc, 'vl'])\nelif conditionnr == 2:\n # Explanation of active production learning trial\n showmessage(win, activeprodmessage)\n # Play an active production learning trial\n random.shuffle(vl)\n for t in vl:\n vd = 'no'\n if t[2] == 'v':\n vd = 'yes'\n if showtrial[25] == 1:\n info = activeprodtrial(win, t[0], t[1], vid = vd)\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\t\" + t[2] +\"\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here! \n trialnr = trialnr + 1\n random.shuffle(vl)\n for t in vl:\n vd = 'no'\n if t[2] == 'v':\n vd = 'yes'\n if showtrial[26] == 1:\n info = activeprodtrial(win, t[0], t[1], vid = vd)\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\t\" + t[2] +\"\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here! \n trialnr = trialnr + 1\n\nfor r in range(6):\n passivetriallist = plist[r]\n random.shuffle(passivetriallist)\n showmessage(win, passivemessage)\n for t in passivetriallist:\n if showtrial[27] == 1:\n passivetrial(win, t[0], t[1], vid = 'yes')\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"P\\tfull\\t-\\t-\\t-\\t-\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm, RT and foilpic are not applicable here!\n trialnr = trialnr + 1 \n activetriallist = alist[r]\n random.shuffle(activetriallist)\n if conditionnr == 1:\n showmessage(win, activecompmessage)\n tc = 0\n for t in activetriallist:\n info = ['none', 0]\n if showtrial[28] == 1:\n info = activecomptrial(win,t[2],t[0], t[1], vid = 'yes')\n key = info[0]\n m = 'mismatch'\n ck = 'none'\n if t[2] == t[0]:\n m = 'yesmatch'\n if m == 'mismatch':\n if key == 'l':\n ck = '0'\n elif key == 'f':\n ck = '1'\n tc = tc + 1\n if m == 'yesmatch':\n if key == 'f':\n ck = '0'\n elif key == 'l':\n ck = '1'\n tc = tc + 1\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AC\\tfull\\t\"+ ck + \"\\t\" + key + \"\\t\" + m +\"\\t\" + str(info[1]) + \"\\t\" + t[1] + \"\\t\" + t[0] + \"\\t\" + t[2] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; \n trialnr = trialnr + 1\n activecompcorrect.append([tc, 'full'])\n elif conditionnr == 2:\n # Explanation of active production learning trial\n showmessage(win, activeprodmessage)\n # Play an active production learning trial\n for t in activetriallist:\n if showtrial[29] == 1:\n info = activeprodtrial(win, t[0], t[1], vid = 'yes')\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + \"AP\\tfull\\t-\\t-\\t-\\t\" + str(info) + \"\\t\" + t[1] + \"\\t\" + t[0] + \"\\t-\\n\") \n # log: subjnr, condnr, trialnr, trialtype, itemtype, correct?, key, match/mismatch, RT, sound, pic, foilpic; note that correct, key, m/mm and foilpic are not applicable here!\n trialnr = trialnr + 1\n\nf.write(\"\\n\\nsubjectnr\\tconditionnr\\ttrialnr\\ttrialtype\\titemtype\\tcorrectanswer?\\tkey\\tlocationcorrectanswer\\tRT\\ttotsounddur\\tsound\\tpic\\tfoilpic\\n\")\n\n# vocabulary test\nshowmessage(win, vocabtestmessage1)\nnrvocabtestcorrect = 0\nttype = 'VT'\nfor t in vocabtesttrials:\n pl = '1'\n vid = 'no'\n if t[2] == 'v': # for verbs we need it to be a video\n vid = 'yes'\n if t[2] == 'm': # for monsters we need to know the plurality\n pl = t[3]\n corr = t[0]\n foil = t[4]\n shuf = [corr, foil]\n random.shuffle(shuf) # randomly decide which one is left and which one is right\n leftp = shuf[0]\n rightp = shuf[1]\n info = ['n', 0]\n if showtrial[30] == 1:\n info = forcedchoicetesttrial(win, leftp, rightp, t[1], pl, vid)\n crct = 0\n if leftp == corr:\n correct = 'left'\n if info[0] == 'x':\n crct = 1\n nrvocabtestcorrect = nrvocabtestcorrect + 1\n elif rightp == corr:\n correct = 'right' \n if info[0] == 'm':\n crct = 1\n nrvocabtestcorrect = nrvocabtestcorrect + 1\n snd = t[1]\n snddurs = getdurs(snd)\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + ttype + \"\\t\" + t[2] + \"\\t\" + str(crct) + \"\\t\" + info[0] + \"\\t\" + correct + \"\\t\" + str(info[1]) + \"\\t\" + str(snddurs[1]) + \"\\t\" + t[1] + \"\\t\" + t[0] + \"\\t\" + t[4] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, trialtype within test, correct?, key, location correct answer, RT, sounddur, sound, correctpic, foilpic; \n trialnr = trialnr + 1\n\nf.write(\"\\n\\nsubjectnr\\tconditionnr\\ttrialnr\\ttrialtype\\titemtype\\tcorrectanswer?\\tkey\\tlocationcorrectanswer\\tRT\\tcritword\\twordduringwhichtheypressed\\ttotaltime\\ttimew1\\ttimew2\\ttimew3\\ttimew4\\ttimew5\\ttimew6\\ttimew7\\tcumtimew1\\tcumtimew2\\tcumtimew3\\tcumtimew4\\tcumtimew5\\tcumtimew6\\tcumtimew7\\tsound\\tpic\\tfoilpic\\n\")\n\n# forced choice test\nshowmessage(win, forcedchoicemessage)\nttype = 'FC'\nnrfctestcorrect = 0\nfor t in FClist:\n nr = t[2]\n corr = t[0]\n foil = t[3]\n shuf = [corr, foil]\n random.shuffle(shuf) # randomly decide which one is left and which one is right\n leftp = shuf[0]\n rightp = shuf[1]\n info = ['n', 0]\n vidfctrial = 'no'\n if t[4] == 'FCvocabvvid' or t[4] == 'FCvocablvid':\n vidfctrial = 'yes'\n nr = '1' # this is icky. I am just setting it to 1 because if i set this to 2 it flips out in terms of playing videos. Nr might be 1 or 2 actually (see t[2])...\n if t[4] == 'FCnumbritem':\n side = ['l', 'r']\n random.shuffle(side)\n if side[0] == 'l':\n nr = '3'\n elif side[0] == 'r':\n nr = '4'\n if showtrial[31] == 1:\n info = forcedchoicetesttrial(win, leftp, rightp, t[1], pl=nr, vid = vidfctrial )\n crct = 0\n if t[4] != 'FCnumbritem':\n if leftp == corr:\n correct = 'left'\n if info[0] == 'x':\n crct = 1\n nrfctestcorrect = nrfctestcorrect + 1\n elif rightp == corr:\n correct = 'right' \n if info[0] == 'm':\n crct = 1\n nrfctestcorrect = nrfctestcorrect + 1\n elif t[4] == 'FCnumbritem':\n if t[2] == '1': # correct answer was sg\n if nr == '3': # pl was on left\n correct = 'right'\n if info[0] == 'm':\n crct = 1\n nrfctestcorrect = nrfctestcorrect + 1\n elif nr == '4': # pl was on right\n correct = 'left'\n if info[0] == 'x':\n crct = 1\n nrfctestcorrect = nrfctestcorrect + 1\n if t[2] == '2': # correct answer was pl\n if nr == '3': # pl was on left\n correct = 'left'\n if info[0] == 'x':\n crct = 1\n nrfctestcorrect = nrfctestcorrect + 1\n elif nr == '4': # pl was on right\n correct = 'right'\n if info[0] == 'm':\n crct = 1\n nrfctestcorrect = nrfctestcorrect + 1 \n snd = t[1]\n snddurs = getdurs(snd)\n snddurstr = str(snddurs[1])\n respondedduringword = 1\n for g in range(2, 16):\n snddurstr = snddurstr + \"\\t\" + str(snddurs[g])\n if g > 8: # cumulative times\n if snddurs[g] < info[1]:\n respondedduringword = g-7 # if this is 8 they responded after the end of the sentence \n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + ttype + \"\\t\" + t[4] + \"\\t\" + str(crct) + \"\\t\" + info[0] + \"\\t\" + correct + \"\\t\" + str(info[1]) + \"\\t\" + str(t[5])+ \"\\t\" + str(respondedduringword) + \"\\t\" + snddurstr + \"\\t\" + t[1] + \"\\t\" + t[0] + \"\\t\" + t[3] + \"\\n\") \n # log: subjnr, condnr, trialnr, trialtype, trialtype within test, correct?, key, location correct answer, RT, critical word, word during which they pressed, breakdown of times, sound, correctpic, foilpic; \n trialnr = trialnr + 1\n if trialnr == 214:\n showmessage(win, \"You are now 1/3 through this test. Press ENTER when you're ready to continue the test.\")\n elif trialnr == 236: \n showmessage(win, \"You are now 2/3 through this test. Press ENTER when you're ready to continue the test.\")\n\nf.write(\"\\n\\nsubjectnr\\tconditionnr\\ttrialnr\\ttrialtype\\titemtype\\tcorrectanswer?\\tkey\\twassoundcorrect?\\tRT\\tcritword\\twordduringwhichtheypressed\\ttotaltime\\ttimew1\\ttimew2\\ttimew3\\ttimew4\\ttimew5\\ttimew6\\ttimew7\\tcumtimew1\\tcumtimew2\\tcumtimew3\\tcumtimew4\\tcumtimew5\\tcumtimew6\\tcumtimew7\\tsound\\n\")\n\n# error monitoring test\nttype = 'EM'\nshowmessage(win, errormonitoringmessage)\nnrerrortestcorrect = 0\nfor t in errorlist:\n if showtrial[32] == 1:\n info = errormonitoringtesttrial(win, t[0])\n crct = 0\n if info[0] == 'f': # they pressed 'wrong'\n if t[2] == 0: # sentence was wrong\n crct = 1\n nrerrortestcorrect = nrerrortestcorrect + 1\n elif info[0] == 'l':\n if t[2] == 1:\n crct = 1\n nrerrortestcorrect = nrerrortestcorrect + 1\n snd = t[0]\n snddurs = getdurs(snd)\n snddurstr = str(snddurs[1])\n respondedduringword = 1\n for g in range(2, 16):\n snddurstr = snddurstr + \"\\t\" + str(snddurs[g])\n if g > 8: # cumulative times\n if snddurs[g] < info[1]:\n respondedduringword = g-7 # if this is 8 they responded after the end of the sentence\n f.write(\"%d\\t\" %subjectnr +\"%d\\t\" %conditionnr + \"%d\\t\" % trialnr + ttype + \"\\t\" + t[1] + \"\\t\" + str(crct) + \"\\t\" + info[0] + \"\\t\" + str(t[2]) + \"\\t\" + str(info[1]) + \"\\t\" + str(t[3])+ \"\\t\" + str(respondedduringword) + \"\\t\" + snddurstr + \"\\t\" + t[0] + \"\\n\") # print what key they pushed\n # log: subjnr, condnr, trialnr, trialtype, trialtype within test, correct?, key, correct trial?, RT, critical word, word during which they pressed, breakdown of times, sound; \n trialnr = trialnr + 1\n if trialnr == 283:\n showmessage(win, \"You are now 1/5 through this test. Press ENTER when you're ready to continue the test.\")\n elif trialnr == 308: \n showmessage(win, \"You are now 2/5 through this test. Press ENTER when you're ready to continue the test.\")\n elif trialnr == 333: \n showmessage(win, \"You are now 3/5 through this test. Press ENTER when you're ready to continue the test.\")\n elif trialnr == 358: \n showmessage(win, \"You are now 4/5 through this test. Press ENTER when you're ready to continue the test.\")\n\n# log time + how much they got correct in the three tests at the end\nnow = time.strftime(\"%c\")\nf.write(\"\\n\\nTime they got to questionnaire\\t\\t\" + time.strftime(\"%c\"))\nf.write(\"\\n total nr of correct vocabularytesttrials was \\n%d\\n\" %nrvocabtestcorrect)\nf.write(\"\\n total nr of correct forcedchoicetrials was \\n%d\\n\" %nrfctestcorrect)\nf.write(\"\\n total nr of correct errormonitoringtrials was \\n%d\\n\" %nrerrortestcorrect)\n\nif conditionnr == 1:\n for it in activecompcorrect:\n itemtype = it[1]\n correct = it[0]\n score = \"\\n\\n\\n total nr correct in \" + itemtype + \" trials was \" + str(correct)\n f.write(score)\n\nf.write(\"\\ntotal nr possible correct trials: msg = 6, msg = 6, mpl = 6, mpl = 6, c = 2, cm = 6, p = 4, NP = 6, NP = 6, vl = 6, vl = 6, full = 6, full = 6, full = 6, full = 6, full = 6, full = 6\")\n\n\n\n# debrief\nif conditionnr == 1:\n showmessage(win, endmessagec)\nelif conditionnr == 2:\n showmessage(win, endmessagep)\n \n\n# if you want webbrowser to pop up automatically - right now experimenter just sets it up by hand in browser\n#webbrowser.open('https://uwmadison.co1.qualtrics.com/jfe/form/SV_d5SH7T9oWB98CvH')\n\n# turn of the mic\nif subjectnr > 2:\n microphone.switchOff()\n\n# close stuff\nf.close()\nsys.exit()\n","sub_path":"experiment.py","file_name":"experiment.py","file_ext":"py","file_size_in_byte":93338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"382363488","text":"#!/usr/bin/env python\nimport os\nfrom time import time\nfrom typing import Generator, Tuple\n\nimport numpy as np\nimport click\nimport json\n\nfrom .lib import *\n\nfrom cloudvolume import CloudVolume\nfrom cloudvolume.lib import Bbox, Vec, yellow\n\nfrom chunkflow.lib.aws.sqs_queue import SQSQueue\nfrom chunkflow.lib.bounding_boxes import BoundingBoxes \n\nfrom chunkflow.chunk import Chunk\nfrom chunkflow.chunk.affinity_map import AffinityMap\nfrom chunkflow.chunk.segmentation import Segmentation\nfrom chunkflow.chunk.image.convnet.inferencer import Inferencer\nfrom chunkflow.lib.utils import coordinates2bbox\n\n# import operator functions\nfrom .agglomerate import AgglomerateOperator\nfrom .aggregate_skeleton_fragments import AggregateSkeletonFragmentsOperator\nfrom .cloud_watch import CloudWatchOperator\nfrom .read_precomputed import ReadPrecomputedOperator\nfrom .downsample_upload import DownsampleUploadOperator\nfrom .log_summary import load_log, print_log_statistics\nfrom .mask import MaskOperator\nfrom .mesh import MeshOperator\nfrom .mesh_manifest import MeshManifestOperator\nfrom .neuroglancer import NeuroglancerOperator\nfrom .normalize_section_contrast import NormalizeSectionContrastOperator\nfrom .normalize_section_shang import NormalizeSectionShangOperator\nfrom .plugin import Plugin\nfrom .read_pngs import read_png_images\nfrom .write_precomputed import WritePrecomputedOperator\nfrom .write_pngs import WritePNGsOperator\nfrom .setup_env import setup_environment\nfrom .skeletonize import SkeletonizeOperator\nfrom .view import ViewOperator\n\n\n@main.command('generate-tasks')\n@click.option('--layer-path', '-l',\n type=str, default=None,\n help='dataset layer path to fetch dataset information.')\n@click.option('--mip', '-m',\n type=int, default=None, help='mip level of the dataset layer.')\n@click.option('--roi-start', '-s',\n type=int, default=None, nargs=3, callback=default_none, \n help='(z y x), start of the chunks')\n@click.option('--roi-stop', '-r',\n type=int, nargs=3, default=None, callback=default_none,\n help='stop coordinate of region of interest')\n@click.option('--roi-size', '-z',\n type=int, nargs=3, default=None, callback=default_none,\n help='size of region of interest')\n@click.option('--chunk-size', '-c',\n type=int, required=True, nargs=3,\n help='(z y x), size/shape of chunks')\n@click.option('--grid-size', '-g',\n type=int, default=None, nargs=3, callback=default_none,\n help='(z y x), grid size of output blocks')\n@click.option('--file-path', '-f', default = None,\n type=click.Path(writable=True, dir_okay=False, resolve_path=True),\n help='output tasks as an numpy array formated as npy.')\n@click.option('--queue-name', '-q',\n type=str, default=None, help='sqs queue name')\n@click.option('--respect-chunk-size/--respect-stop',\n default=True, help=\"\"\"for the last bounding box, \\\nmake the chunk size consistent or cut off at the stopping boundary.\"\"\")\n@click.option('--aligned-block-size', '-a',\n type=int, default=None, nargs=3, callback=default_none,\n help='force alignment of block size. Note that the alignment start from (0, 0, 0).')\n@click.option('--task-index-start', '-i',\n type=int, default=None, help='starting index of task list.')\n@click.option('--task-index-stop', '-p',\n type=int, default=None, help='stop index of task list.')\n@click.option('--disbatch/--no-disbatch', '-d',\n default=False, help='use disBatch environment variable or not')\n@generator\ndef generate_tasks(\n layer_path: str, mip: int, roi_start: tuple, roi_stop: tuple,roi_size, chunk_size, \n grid_size: tuple, file_path: str, queue_name: str, respect_chunk_size: bool,\n aligned_block_size: tuple, task_index_start: tuple, \n task_index_stop: tuple, disbatch: bool ):\n\n if mip is None:\n mip = state['mip']\n assert mip >=0 \n\n \"\"\"Generate tasks.\"\"\"\n bboxes = BoundingBoxes.from_manual_setup(\n chunk_size, layer_path=layer_path,\n roi_start=roi_start, roi_stop=roi_stop, \n roi_size=roi_size, mip=mip, grid_size=grid_size,\n respect_chunk_size=respect_chunk_size,\n aligned_block_size=aligned_block_size\n )\n print('total number of tasks: ', len(bboxes)) \n\n if task_index_start:\n if task_index_stop is None:\n task_index_stop = task_index_start + 1\n bboxes = [*bboxes[task_index_start:task_index_stop]]\n logging.info(f'selected task indexes from {task_index_start} to {task_index_stop}')\n elif disbatch:\n assert 'DISBATCH_REPEAT_INDEX' in os.environ\n disbatch_index = int(os.environ['DISBATCH_REPEAT_INDEX'])\n bboxes = [bboxes[disbatch_index],]\n logging.info(f'selected a task with disBatch index {disbatch_index}')\n \n # write out as a file\n # this could be used for iteration in slurm cluster.\n if file_path:\n if not file_path.endswith('.npy'):\n file_path += len(bboxes) + '.npy'\n bboxes.to_file(file_path)\n\n if queue_name is not None:\n \n \n\n\n\n\n\n queue = SQSQueue(queue_name)\n queue.send_message_list(bboxes)\n else:\n bbox_num = len(bboxes)\n for bbox_index, bbox in enumerate(bboxes):\n task = get_initial_task()\n task['bbox'] = bbox\n task['bbox_index'] = bbox_index\n task['bbox_num'] = bbox_num\n task['log']['bbox'] = bbox.to_filename()\n yield task\n\n\n@main.command('setup-env')\n@click.option('--volume-start', required=True, nargs=3, type=int,\n help='start coordinate of output volume in mip 0')\n@click.option('--volume-stop', default=None, type=int, nargs=3, callback=default_none,\n help='stop coordinate of output volume (noninclusive like python coordinate) in mip 0.')\n@click.option('--volume-size', '-s',\n default=None, type=int, nargs=3, callback=default_none, \n help='size of output volume.')\n@click.option('--layer-path', '-l',\n type=str, required=True, help='the path of output volume.')\n@click.option('--max-ram-size', '-r',\n default=15, type=int, help='the maximum ram size (GB) of worker process.')\n@click.option('--output-patch-size', '-z',\n type=int, required=True, nargs=3, help='output patch size.')\n@click.option('--input-patch-size', '-i',\n type=int, default=None, nargs=3, callback=default_none,\n help='input patch size.')\n@click.option('--channel-num', '-c',\n type=int, default=1, \n help='output patch channel number. It is 3 for affinity map.')\n@click.option('--dtype', '-d', type=click.Choice(['uint8', 'float16', 'float32']), \n default='float32', help='output numerical precision.')\n@click.option('--output-patch-overlap', '-o',\n type=int, default=None, nargs=3, callback=default_none,\n help='overlap of patches. default is 50% overlap')\n@click.option('--crop-chunk-margin', '-c', \n type=int, nargs=3, default=None,\n callback=default_none, help='size of margin to be cropped.')\n@click.option('--mip', '-m', type=click.IntRange(min=0, max=3), default=0, \n help='the output mip level (default is 0).')\n@click.option('--thumbnail-mip', '-b', type=click.IntRange(min=5, max=16), default=6,\n help='mip level of thumbnail layer.')\n@click.option('--max-mip', '-x', type=click.IntRange(min=5, max=16), default=8, \n help='maximum MIP level for masks.')\n@click.option('--queue-name', '-q',\n type=str, default=None, help='sqs queue name.')\n@click.option('--visibility-timeout', '-t',\n type=int, default=3600, help='visibility timeout of the AWS SQS queue.')\n@click.option('--thumbnail/--no-thumbnail', default=True, help='create thumbnail or not.')\n@click.option('--encoding', '-e',\n type=click.Choice(['raw', 'jpeg', 'compressed_segmentation', \n 'fpzip', 'kempressed']), default='raw', \n help='Neuroglancer precomputed block compression algorithm.')\n@click.option('--voxel-size', '-v', type=int, nargs=3, default=(40, 4, 4),\n help='voxel size or resolution of mip 0 image.')\n@click.option('--overwrite-info/--no-overwrite-info', default=False,\n help='normally we should avoid overwriting info file to avoid errors.')\n@generator\ndef setup_env(volume_start, volume_stop, volume_size, layer_path, \n max_ram_size, output_patch_size, input_patch_size, channel_num, dtype, \n output_patch_overlap, crop_chunk_margin, mip, thumbnail_mip, max_mip,\n queue_name, visibility_timeout, thumbnail, encoding, voxel_size, \n overwrite_info):\n \"\"\"Setup convolutional net inference environment.\"\"\"\n bboxes = setup_environment(\n state['dry_run'], volume_start, volume_stop, volume_size, layer_path, \n max_ram_size, output_patch_size, input_patch_size, channel_num, dtype, \n output_patch_overlap, crop_chunk_margin, mip, thumbnail_mip, max_mip,\n thumbnail, encoding, voxel_size, overwrite_info)\n \n if queue_name is not None and not state['dry_run']:\n queue = SQSQueue(queue_name, visibility_timeout=visibility_timeout)\n queue.send_message_list(bboxes)\n else:\n for bbox in bboxes:\n task = get_initial_task()\n task['bbox'] = bbox\n task['log']['bbox'] = bbox.to_filename()\n yield task\n\n\n@main.command('cloud-watch')\n@click.option('--name',\n type=str,\n default='cloud-watch',\n help='name of this operator')\n@click.option('--log-name',\n type=str,\n default='chunkflow',\n help='name of the speedometer')\n@operator\ndef cloud_watch(tasks, name, log_name):\n \"\"\"Real time speedometer in AWS CloudWatch.\"\"\"\n operator = CloudWatchOperator(log_name=log_name, name=name)\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n operator(task['log'])\n yield task\n\n\n@main.command('create-info')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME,\n help=\"create info for this chunk.\")\n@click.option('--output-layer-path', '-l', type=str, default=\"file://.\", \n help='path of output layer.')\n@click.option('--channel-num', '-c', type=int, default=1, help='number of channel')\n@click.option('--layer-type', '-t',\n type=click.Choice(['image', 'segmentation']),\n default=None, help='type of layer. either image or segmentation.')\n@click.option('--data-type', '-d',\n type=click.Choice(['uint8', 'uint32', 'uint64', 'float32']),\n default = None, help='data type of array')\n@click.option('--encoding', '-e',\n type=click.Choice(['raw', 'jpeg', 'compressed_segmentation', \n 'kempressed', 'npz', 'fpzip', 'npz_uint8']),\n default='raw', help='compression algorithm.')\n@click.option('--voxel-size', '-s', required=True, type=int, nargs=3,\n help='voxel size with unit of nm')\n@click.option('--voxel-offset', '-o', default=(0,0,0), type=int, nargs=3,\n help='voxel offset of array')\n@click.option('--volume-size', '-v',\n type=int, nargs=3, default=None, callback=default_none,\n help='total size of the volume.')\n@click.option('--block-size', '-b',\n type=int, nargs=3, required=True,\n help='chunk size of each file.')\n@click.option('--factor', '-f',\n type=int, nargs=3, default=(2,2,2),\n help='hierarchical downsampling factor')\n@click.option('--max-mip', '-m',\n type=int, default=0, \n help = 'maximum mip level.')\n@operator\ndef create_info(tasks,input_chunk_name: str, output_layer_path: str, channel_num: int, \n layer_type: str, data_type: str, encoding: str, voxel_size: tuple, \n voxel_offset: tuple, volume_size: tuple, block_size: tuple, factor: tuple, max_mip: int):\n \"\"\"Create metadata for Neuroglancer Precomputed volume.\"\"\"\n \n for task in tasks:\n if input_chunk_name in task:\n chunk = task[input_chunk_name]\n if chunk.ndim == 3:\n channel_num = 1\n elif chunk.ndim == 4:\n channel_num = chunk.shape[0]\n else:\n raise ValueError('chunk dimension can only be 3 or 4')\n\n voxel_offset = chunk.voxel_offset\n volume_size = chunk.shape\n data_type = chunk.dtype.name\n\n if layer_type is None:\n if np.issubdtype(chunk.dtype, np.uint8) or \\\n np.issubdtype(chunk.dtype, np.float32) or \\\n np.issubdtype(chunk.dtype, np.float16):\n layer_type = 'image'\n else:\n layer_type = 'segmentation'\n \n assert volume_size is not None \n assert data_type is not None\n\n info = CloudVolume.create_new_info(\n channel_num, layer_type=layer_type,\n data_type=data_type,\n encoding=encoding,\n resolution=voxel_size[::-1],\n voxel_offset=voxel_offset[::-1],\n volume_size=volume_size[::-1],\n chunk_size=block_size[::-1],\n factor=Vec(factor),\n max_mip=max_mip)\n vol = CloudVolume(output_layer_path, info=info)\n vol.commit_info()\n yield task\n\n\n@main.command('fetch-task-from-file')\n@click.option('--file-path', '-f',\n type=click.Path(file_okay=True, dir_okay=False, exists=True, \n readable=True, resolve_path=True),\n help='file contains bounding boxes or tasks.')\n@click.option('--job-index', '-i', \n type=int, default=None,\n help='index of task in the tasks.')\n@click.option('--slurm-job-array/--no-slurm-job-array',\n default=False, help='use the slurm job array '+\n 'environment variable to identify task index.')\n@click.option('--granularity', '-g',\n type=int, default=1, help='number of tasks to do in one run.')\n@generator\ndef fetch_task_from_file(file_path: str, job_index: int, slurm_job_array: bool, granularity: int):\n if(slurm_job_array):\n job_index = int(os.environ['SLURM_ARRAY_TASK_ID'])\n assert job_index is not None\n\n bbox_array = np.load(file_path)\n task_start = job_index * granularity \n task_stop = min(bbox_array.shape[0], task_start + granularity)\n for idx in range(task_start, task_stop):\n bbox = Bbox.from_list(bbox_array[idx, :])\n task = get_initial_task()\n task['bbox'] = bbox\n yield task\n\n\n@main.command('fetch-task-from-sqs')\n@click.option('--queue-name', '-q',\n type=str, default=None, help='sqs queue name')\n@click.option('--visibility-timeout', '-v',\n type=int, default=None, \n help='visibility timeout of sqs queue; default is using the timeout of the queue.')\n@click.option('--num', '-n', type=int, default=-1,\n help='fetch limited number of tasks.' +\n ' This is useful in local cluster to control task time elapse.' + \n 'Negative value will be infinite.')\n@click.option('--retry-times', '-r',\n type=int, default=30,\n help='the times of retrying if the queue is empty.')\n@generator\ndef fetch_task_from_sqs(queue_name, visibility_timeout, num, retry_times):\n \"\"\"Fetch task from queue.\"\"\"\n # This operator is actually a generator,\n # it replaces old tasks to a completely new tasks and loop over it!\n queue = SQSQueue(queue_name, \n visibility_timeout=visibility_timeout,\n retry_times=retry_times)\n while num!=0:\n task_handle, bbox_str = queue.handle_and_message\n if task_handle is None:\n return\n num -= 1\n \n print('get task: ', bbox_str)\n bbox = Bbox.from_filename(bbox_str)\n \n # record the task handle to delete after the processing\n task = get_initial_task() \n task['queue'] = queue\n task['task_handle'] = task_handle\n task['bbox'] = bbox\n task['log']['bbox'] = bbox.to_filename()\n yield task\n\n\n@main.command('agglomerate')\n@click.option('--name', type=str, default='agglomerate', help='name of operator')\n@click.option('--threshold', '-t',\n type=float, default=0.7, help='agglomeration threshold')\n@click.option('--aff-threshold-low', '-l',\n type=float, default=0.0001, help='low threshold for watershed')\n@click.option('--aff-threshold-high', '-h',\n type=float, default=0.9999, help='high threshold for watershed')\n@click.option('--fragments-chunk-name', '-f',\n type=str, default=None, help='optional fragments/supervoxel chunk to use.')\n@click.option('--scoring-function', '-s',\n type=str, default='OneMinus>',\n help='A C++ type string specifying the edge scoring function to use.')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, help='input chunk name')\n@click.option('--output-chunk-name', '-o',\n type=str, default=DEFAULT_CHUNK_NAME, help='output chunk name')\n@operator\ndef agglomerate(tasks, name, threshold, aff_threshold_low, aff_threshold_high,\n fragments_chunk_name, scoring_function, input_chunk_name, output_chunk_name):\n \"\"\"Watershed and agglomeration to segment affinity map.\"\"\"\n operator = AgglomerateOperator(name=name,\n threshold=threshold, \n aff_threshold_low=aff_threshold_low,\n aff_threshold_high=aff_threshold_high,\n scoring_function=scoring_function)\n for task in tasks:\n if fragments_chunk_name and fragments_chunk_name in task:\n fragments = task[fragments_chunk_name]\n else:\n fragments = None \n \n task[output_chunk_name] = operator(\n task[input_chunk_name], fragments=fragments)\n yield task\n\n\n@main.command('aggregate-skeleton-fragments')\n@click.option('--name', type=str, default='aggregate-skeleton-fragments',\n help='name of operator')\n@click.option('--input-name', '-i', type=str, default='prefix',\n help='input prefix name in task stream.')\n@click.option('--prefix', '-p', type=str, default=None,\n help='prefix of skeleton fragments.')\n@click.option('--fragments-path', '-f', type=str, required=True,\n help='storage path of skeleton fragments.')\n@click.option('--output-path', '-o', type=str, default=None,\n help='storage path of aggregated skeletons.')\n@operator\ndef aggregate_skeleton_fragments(tasks, name, input_name, prefix, fragments_path, output_path):\n \"\"\"Merge skeleton fragments.\"\"\"\n if output_path is None:\n output_path = fragments_path\n\n operator = AggregateSkeletonFragmentsOperator(fragments_path, output_path)\n if prefix:\n operator(prefix)\n else:\n for task in tasks:\n start = time()\n operator(task[input_name])\n task['log']['timer'][name] = time() - start\n yield task\n\n\n\n@main.command('create-chunk')\n@click.option('--name',\n type=str,\n default='create-chunk',\n help='name of operator')\n@click.option('--size', '-s',\n type=int, nargs=3, default=(64, 64, 64), help='the size of created chunk')\n@click.option('--dtype',\n type=click.Choice(\n ['uint8', 'uint32', 'uint16', 'float32', 'float64']),\n default='uint8', help='the data type of chunk')\n@click.option('--all-zero/--not-all-zero', default=False, help='all zero or not.')\n@click.option('--voxel-offset', '-t',\n type=int, nargs=3, default=(0, 0, 0), help='offset in voxel number.')\n@click.option('--voxel-size', '-e',\n type=int, nargs=3, default=(1,1,1), help='voxel size in nm')\n@click.option('--output-chunk-name', '-o',\n type=str, default=\"chunk\", help=\"name of created chunk\")\n@operator\ndef create_chunk(tasks, name, size, dtype, all_zero, voxel_offset, voxel_size, output_chunk_name):\n \"\"\"Create a fake chunk for easy test.\"\"\"\n print(\"creating chunk: \", output_chunk_name)\n for task in tasks:\n task[output_chunk_name] = Chunk.create(\n size=size, dtype=np.dtype(dtype), \n all_zero = all_zero,\n voxel_offset=voxel_offset,\n voxel_size=voxel_size)\n yield task\n\n@main.command('read-nrrd')\n@click.option('--name', type=str, default='read-nrrd',\n help='read nrrd file from local disk.')\n@click.option('--file-name', '-f', required=True,\n type=click.Path(exists=True, dir_okay=False),\n help='read chunk from NRRD file')\n@click.option('--voxel-offset', '-v', type=int, nargs=3, callback=default_none,\n help='global offset of this chunk')\n@click.option('--voxel-size', '-s', type=int, nargs=3, default=None, callback=default_none,\n help='physical size of voxels. The unit is assumed to be nm.')\n@click.option('--dtype', '-d',\n type=click.Choice(['uint8', 'uint32', 'uint64', 'float32', 'float64', 'float16']),\n help='convert to data type')\n@click.option('--output-chunk-name', '-o', type=str, default='chunk',\n help='chunk name in the global state')\n@operator\ndef read_nrrd(tasks, name: str, file_name: str, voxel_offset: tuple,\n voxel_size: tuple, dtype: str, output_chunk_name: str):\n \"\"\"Read NRRD file.\"\"\"\n for task in tasks:\n start = time()\n task[output_chunk_name] = Chunk.from_nrrd(\n file_name,\n dtype=dtype,\n voxel_offset=voxel_offset,\n voxel_size=voxel_size)\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('write-nrrd')\n@click.option('--name', type=str, default='write-nrrd', help='name of operator')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, help='input chunk name')\n@click.option('--file-name', '-f', default=None,\n type=click.Path(dir_okay=False, resolve_path=True), \n help='file name of NRRD file.')\n@operator\ndef write_tif(tasks, name, input_chunk_name, file_name):\n \"\"\"Write chunk as a NRRD file.\"\"\"\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n task[input_chunk_name].to_nrrd(file_name)\n # keep the pipeline going\n yield task\n\n\n@main.command('read-pngs')\n@click.option('--path-prefix', '-p',\n required=True, type=str,\n help='directory path prefix of png files.')\n@click.option('--output-chunk-name', '-o',\n type=str, default=DEFAULT_CHUNK_NAME,\n help='output chunk name')\n@click.option('--cutout-offset', '-c',\n type=int, default=(0,0,0), nargs=3,\n help='cutout chunk from an offset')\n@click.option('--volume-offset', '-t',\n type=int, nargs=3, default=(0,0,0),\n help = 'the offset of png images volume, could be negative.')\n@click.option('--voxel-size', '-x', type=int, nargs=3, default=None, callback=default_none,\n help='physical size of voxels. the unit is assumed to be nm.')\n@click.option('--chunk-size', '-s',\n type=int, nargs=3, default=None, callback=default_none,\n help='cutout chunk size')\n@operator\ndef read_pngs(tasks, path_prefix, output_chunk_name, cutout_offset,\n volume_offset, voxel_size, chunk_size):\n \"\"\"Read a serials of png files.\"\"\"\n for task in tasks:\n if chunk_size is None:\n assert 'bbox' in task, \"no chunk_size, we are looking for bounding box in task\"\n bbox = task['bbox']\n else:\n bbox = Bbox.from_delta(cutout_offset, chunk_size)\n\n task[output_chunk_name] = read_png_images(\n path_prefix, bbox, \n volume_offset=volume_offset,\n voxel_size=voxel_size)\n yield task\n\n\n@main.command('read-tif')\n@click.option('--name', type=str, default='read-tif',\n help='read tif file from local disk.')\n@click.option('--file-name', '-f', required=True,\n type=click.Path(exists=True, dir_okay=False),\n help='read chunk from TIFF file.')\n@click.option('--voxel-offset', '-v', type=int, nargs=3, callback=default_none,\n help='global offset of this chunk')\n@click.option('--voxel-size', '-s', type=int, nargs=3, default=None, callback=default_none,\n help='physical size of voxels. The unit is assumed to be nm.')\n@click.option('--dtype', '-d',\n type=click.Choice(['uint8', 'uint32', 'uint64', 'float32', 'float64', 'float16']),\n help='convert to data type')\n@click.option('--output-chunk-name', '-o', type=str, default='chunk',\n help='chunk name in the global state')\n@operator\ndef read_tif(tasks, name: str, file_name: str, voxel_offset: tuple,\n voxel_size: tuple, dtype: str, output_chunk_name: str):\n \"\"\"Read tiff files.\"\"\"\n for task in tasks:\n start = time()\n task[output_chunk_name] = Chunk.from_tif(\n file_name,\n dtype=dtype,\n voxel_offset=voxel_offset,\n voxel_size=voxel_size)\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('write-tif')\n@click.option('--name', type=str, default='write-tif', help='name of operator')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, help='input chunk name')\n@click.option('--file-name', '-f', default=None,\n type=click.Path(dir_okay=False, resolve_path=True), \n help='file name of tif file, the extention should be .tif or .tiff')\n@operator\ndef write_tif(tasks, name, input_chunk_name, file_name):\n \"\"\"Write chunk as a TIF file.\"\"\"\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n task[input_chunk_name].to_tif(file_name)\n # keep the pipeline going\n yield task\n\n\n@main.command('read-h5')\n@click.option('--name', type=str, default='read-h5',\n help='read file from local disk.')\n@click.option('--file-name', '-f', type=str, required=True,\n help='read chunk from file, support .h5')\n@click.option('--dataset-path', '-d', type=str, default=None,\n help='the dataset path inside HDF5 file.')\n@click.option('--dtype', '-e',\n type=click.Choice(['float32', 'float64', 'uint32', 'uint64', 'uint8']),\n default=None, help='transform data type.')\n@click.option('--voxel-offset', '-v', type=int, nargs=3, default=None,\n callback=default_none, help='voxel offset of the dataset in hdf5 file.')\n@click.option('--voxel-size', '-x', type=int, nargs=3, default=None,\n callback=default_none, help='physical size of voxels. The unit is assumed to be nm.')\n@click.option('--cutout-start', '-t', type=int, nargs=3, callback=default_none,\n help='cutout voxel offset in the array')\n@click.option('--cutout-stop', '-p', type=int, nargs=3, callback=default_none,\n help='cutout stop corrdinate.')\n@click.option('--cutout-size', '-s', type=int, nargs=3, callback=default_none,\n help='cutout size of the chunk.')\n@click.option('--output-chunk-name', '-o',\n type=str, default=DEFAULT_CHUNK_NAME,\n help='chunk name in the global state')\n@operator\ndef read_h5(tasks, name: str, file_name: str, dataset_path: str,\n dtype: str, voxel_offset: tuple, voxel_size: tuple, cutout_start: tuple, \n cutout_stop: tuple, cutout_size: tuple, output_chunk_name: str):\n \"\"\"Read HDF5 files.\"\"\"\n for task in tasks:\n \n start = time()\n if 'bbox' in task and cutout_start is None:\n bbox = task['bbox']\n print('bbox: ', bbox)\n cutout_start = bbox.minpt\n cutout_stop = bbox.maxpt\n cutout_size = cutout_stop - cutout_start\n \n chunk = Chunk.from_h5(\n file_name,\n dataset_path=dataset_path,\n voxel_offset=voxel_offset,\n voxel_size=voxel_size,\n cutout_start=cutout_start,\n cutout_size=cutout_size,\n cutout_stop=cutout_stop\n )\n if dtype is not None:\n chunk = chunk.astype(dtype)\n task[output_chunk_name] = chunk\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('write-h5')\n@click.option('--name', type=str, default='write-h5', help='name of operator')\n@click.option('--input-chunk-name', '-i',\n type=str, default='chunk', help='input chunk name')\n@click.option('--file-name', '-f',\n type=click.Path(dir_okay=True, resolve_path=False), required=True,\n help='file name of hdf5 file.')\n@click.option('--chunk-size', '-s', type=int, nargs=3,\n default=None, callback=default_none,\n help='save the big volume as chunks.')\n@click.option('--compression', '-c', type=click.Choice([\"gzip\", \"lzf\", \"szip\"]),\n default=\"gzip\", help=\"compression used in the dataset.\")\n@click.option('--with-offset/--without-offset', default=True, type=bool,\n help='add voxel_offset dataset or not.')\n@operator\ndef write_h5(tasks, name, input_chunk_name, file_name, chunk_size, compression, with_offset):\n \"\"\"Write chunk to HDF5 file.\"\"\"\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n task[input_chunk_name].to_h5(file_name, with_offset, \n chunk_size=chunk_size, compression=compression)\n yield task\n\n\n@main.command('write-pngs')\n@click.option('--name', type=str, default='write-pngs', help='name of operator')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, help='input chunk name')\n@click.option('--output-path', '-o',\n type=str, default='./pngs/', help='output path of saved 2d images formated as png.')\n@operator\ndef write_pngs(tasks, name, input_chunk_name, output_path):\n \"\"\"Save as 2D PNG images.\"\"\"\n operator = WritePNGsOperator(output_path=output_path,\n name=name)\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n operator(task[input_chunk_name])\n yield task\n\n\n@main.command('skeletonize')\n@click.option('--name', '-n', type=str, default='skeletonize',\n help='create centerlines of objects in a segmentation chunk.')\n@click.option('--input-chunk-name', '-i', type=str, default=DEFAULT_CHUNK_NAME,\n help='input chunk name.')\n@click.option('--output-name', '-o', type=str, default='skeletons')\n@click.option('--voxel-size', type=int, nargs=3, required=True,\n help='voxel size of segmentation chunk (zyx order)')\n@click.option('--output-path', type=str, required=True,\n help='output path with protocols, such as file:///bucket/my/path')\n@operator\ndef skeletonize(tasks, name, input_chunk_name, output_name, voxel_size, output_path):\n \"\"\"Skeletonize the neurons/objects in a segmentation chunk\"\"\"\n operator = SkeletonizeOperator(output_path, name=name)\n for task in tasks:\n seg = task[input_chunk_name]\n skels = operator(seg, voxel_size)\n task[output_name] = skels\n yield task\n\n\n@main.command('delete-task-in-queue')\n@click.option('--name', type=str, default='delete-task-in-queue',\n help='name of this operator')\n@operator\ndef delete_task_in_queue(tasks, name):\n \"\"\"Delete the task in queue.\"\"\"\n for task in tasks:\n handle_task_skip(task, name)\n if task['skip'] or state['dry_run']:\n print('skip deleting task in queue!')\n else:\n queue = task['queue']\n task_handle = task['task_handle']\n queue.delete(task_handle)\n print('deleted task {} in queue: {}'.format(\n task_handle, queue.queue_name))\n\n\n@main.command('delete-chunk')\n@click.option('--name', type=str, default='delete-var', help='delete variable/chunk in task')\n@click.option('--chunk-name', '-c',\n type=str, required=True, help='the chunk name need to be deleted')\n@operator\ndef delete_chunk(tasks, name, chunk_name):\n \"\"\"Delete a Chunk in task to release RAM\"\"\"\n for task in tasks:\n handle_task_skip(task, name)\n if task['skip']:\n logging.info(f'skip deleting {chunk_name}')\n else:\n logging.info(f'delete chunk: {chunk_name}')\n del task[chunk_name]\n yield task\n \n\n@main.command('read-precomputed')\n@click.option('--name',\n type=str, default='read-precomputed', help='name of this operator')\n@click.option('--volume-path', '-v',\n type=str, required=True, help='volume path')\n@click.option('--mip', '-m',\n type=int, default=None, help='mip level of the cutout.')\n@click.option('--expand-margin-size', '-e',\n type=int, nargs=3, default=(0, 0, 0),\n help='include surrounding regions of output bounding box.')\n@click.option('--chunk-start', '-s',\n type=int, nargs=3, default=None, callback=default_none,\n help='chunk offset in volume.')\n@click.option('--chunk-size', '-z',\n type=int, nargs=3, default=None, callback=default_none,\n help='cutout chunk size.')\n@click.option('--fill-missing/--no-fill-missing',\n default=False, help='fill the missing chunks in input volume with zeros ' +\n 'or not, default is false')\n@click.option('--validate-mip', \n type=int, default=None, help='validate chunk using higher mip level')\n@click.option('--blackout-sections/--no-blackout-sections',\n default=False, help='blackout some sections. ' +\n 'the section ids json file should named blackout_section_ids.json. default is False.')\n@click.option(\n '--output-chunk-name', '-o',\n type=str, default=DEFAULT_CHUNK_NAME, \n help='Variable name to store the cutout to for later retrieval.'\n + 'Chunkflow operators by default operates on a variable named \"chunk\" but' +\n ' sometimes you may need to have a secondary volume to work on.'\n)\n@operator\ndef read_precomputed(tasks, name, volume_path, mip, chunk_start, chunk_size, expand_margin_size,\n fill_missing, validate_mip, blackout_sections, output_chunk_name):\n \"\"\"Cutout chunk from volume.\"\"\"\n if mip is None:\n mip = state['mip']\n assert mip >= 0\n \n operator = ReadPrecomputedOperator(\n volume_path,\n mip=mip,\n expand_margin_size=expand_margin_size,\n fill_missing=fill_missing,\n validate_mip=validate_mip,\n blackout_sections=blackout_sections,\n dry_run=state['dry_run'],\n name=name)\n\n for task in tasks:\n handle_task_skip(task, name)\n if 'bbox' in task:\n bbox = task['bbox']\n else:\n # use bounding box of volume\n if chunk_start is None:\n chunk_start = operator.vol.mip_bounds(mip).minpt[::-1]\n else:\n chunk_start = Vec(*chunk_start)\n\n if chunk_size is None:\n chunk_stop = operator.vol.mip_bounds(mip).maxpt[::-1]\n chunk_size = chunk_stop - chunk_start\n else:\n chunk_size = Vec(*chunk_size)\n bbox = Bbox.from_delta(chunk_start, chunk_size)\n\n if not task['skip']:\n start = time()\n assert output_chunk_name not in task\n task[output_chunk_name] = operator(bbox)\n task['log']['timer'][name] = time() - start\n task['cutout_volume_path'] = volume_path\n yield task\n\n\n@main.command('remap-segmentation')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, help='input chunk name.')\n@click.option('--output-chunk-name', '-o',\n type=str, default=DEFAULT_CHUNK_NAME, help='output chunk name.')\n@operator\ndef remap_segmentation(tasks, input_chunk_name, output_chunk_name):\n \"\"\"Renumber a serials of chunks.\"\"\"\n # state['remap_start_id'] = 0\n start_id = 0\n for task in tasks:\n seg = task[input_chunk_name]\n assert seg.is_segmentation\n if not isinstance(seg, Segmentation):\n seg = Segmentation.from_chunk(seg)\n\n seg, start_id = seg.remap(start_id)\n task[output_chunk_name] = seg\n yield task\n\n\n@main.command('evaluate-segmentation')\n@click.option('--name',\n type=str,\n default=\"evaluate-segmentation\",\n help=\"name of operator\")\n@click.option(\"--segmentation-chunk-name\",\n \"-s\",\n type=str,\n default=\"chunk\",\n help=\"chunk name of segmentation\")\n@click.option(\"--groundtruth-chunk-name\",\n \"-g\",\n type=str,\n default=\"groundtruth\")\n@operator\ndef evaluate_segmenation(tasks, name, segmentation_chunk_name,\n groundtruth_chunk_name):\n \"\"\"Evaluate segmentation by split/merge error.\n \"\"\"\n for task in tasks:\n seg = Segmentation(task[segmentation_chunk_name])\n groundtruth = Segmentation(task[groundtruth_chunk_name])\n seg.evaluate(groundtruth)\n yield task\n\n\n@main.command('downsample-upload')\n@click.option('--name',\n type=str, default='downsample-upload', help='name of operator')\n@click.option('--input-chunk-name', '-i',\n type=str, default='chunk', help='input chunk name')\n@click.option('--volume-path', '-v', type=str, help='path of output volume')\n@click.option('--factor', '-f', type=int, nargs=3, default=(2, 2, 2), \n help='downsampling factor in z,y,x.')\n@click.option('--chunk-mip', '-c', type=int, default=None, help='input chunk mip level')\n@click.option('--start-mip', '-s', \n type=int, default=None, help='the start uploading mip level.')\n@click.option('--stop-mip', '-p',\n type=int, default=5, help='stop mip level. the indexing follows python style and ' +\n 'the last index is exclusive.')\n@click.option('--fill-missing/--no-fill-missing',\n default=True, help='fill missing or not when there is all zero blocks.')\n@operator\ndef downsample_upload(tasks, name, input_chunk_name, volume_path, \n factor, chunk_mip, start_mip, stop_mip, fill_missing):\n \"\"\"Downsample chunk and upload to volume.\"\"\"\n if chunk_mip is None:\n chunk_mip = state['mip']\n\n operator = DownsampleUploadOperator(\n volume_path,\n factor=factor,\n chunk_mip=chunk_mip,\n start_mip=start_mip,\n stop_mip=stop_mip,\n fill_missing=fill_missing,\n name=name)\n\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n operator(task[input_chunk_name])\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('log-summary')\n@click.option('--log-dir', '-l',\n type=click.Path(exists=True, dir_okay=True, readable=True),\n default='./log', help='directory of json log files.')\n@click.option('--output-size', '-s', \n type=int, nargs=3, default=None, callback=default_none,\n help='output size for each task. will be used for computing speed.')\n@generator\ndef log_summary(log_dir, output_size):\n \"\"\"Compute the statistics of large scale run.\"\"\"\n df = load_log(log_dir)\n print_log_statistics(df, output_size=output_size)\n\n task = get_initial_task()\n yield task\n \n\n@main.command('normalize-intensity')\n@click.option('--name', type=str, default='normalize-intensity', help='name of operator')\n@click.option('--input-chunk-name', '-i', type=str, \n default=DEFAULT_CHUNK_NAME, help='input chunk name')\n@click.option('--output-chunk-name', '-o', type=str,\n default=DEFAULT_CHUNK_NAME, help='output chunk name')\n@operator\ndef normalize_intensity(tasks, name, input_chunk_name, output_chunk_name):\n \"\"\"transform gray image to float (-1:1). x=(x-127.5) - 1.0\"\"\"\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n chunk = task[input_chunk_name]\n assert np.issubdtype(chunk.dtype, np.uint8)\n chunk = chunk.astype('float32')\n chunk /= 127.5\n chunk -= 1.0\n task[output_chunk_name] = chunk\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('normalize-contrast-nkem')\n@click.option('--name', type=str, default='normalize-contrast-nkem',\n help='name of operator.')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, help='input chunk name')\n@click.option('--output-chunk-name', '-o',\n type=str, default=DEFAULT_CHUNK_NAME, help='output chunk name')\n@click.option('--levels-path', '-p', type=str, required=True,\n help='the path of section histograms.')\n@click.option('--lower-clip-fraction', '-l', type=float, default=0.01, \n help='lower intensity fraction to clip out.')\n@click.option('--upper-clip-fraction', '-u', type=float, default=0.01, \n help='upper intensity fraction to clip out.')\n@click.option('--minval', type=int, default=1, \n help='the minimum intensity of transformed chunk.')\n@click.option('--maxval', type=int, default=255,\n help='the maximum intensity of transformed chunk.')\n@operator\ndef normalize_contrast_nkem(tasks, name, input_chunk_name, output_chunk_name, \n levels_path, lower_clip_fraction,\n upper_clip_fraction, minval, maxval):\n \"\"\"Normalize the section contrast using precomputed histograms.\"\"\"\n \n operator = NormalizeSectionContrastOperator(\n levels_path,\n lower_clip_fraction=lower_clip_fraction,\n upper_clip_fraction=upper_clip_fraction,\n minval=minval, maxval=maxval, name=name)\n\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n task[output_chunk_name] = operator(task[input_chunk_name])\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('normalize-section-shang')\n@click.option('--name',\n type=str,\n default='normalize-section-mu',\n help='name of operator.')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, help='input chunk name')\n@click.option('--output-chunk-name', '-o',\n type=str, default=DEFAULT_CHUNK_NAME, help='output chunk name')\n@click.option('--nominalmin',\n type=float,\n default=None,\n help='targeted minimum of transformed chunk.')\n@click.option('--nominalmax',\n type=float,\n default=None,\n help='targeted maximum of transformed chunk.')\n@click.option('--clipvalues',\n type=bool,\n default=False,\n help='clip transformed values to be within the target range.')\n@operator\ndef normalize_section_shang(tasks, name, input_chunk_name, output_chunk_name, \n nominalmin, nominalmax, clipvalues):\n \"\"\"Normalize voxel values based on slice min/max within the chunk, Shang's method.\n The transformed chunk has floating point values.\n \"\"\"\n\n operator = NormalizeSectionShangOperator(\n nominalmin=nominalmin,\n nominalmax=nominalmax,\n clipvalues=clipvalues,\n name=name)\n\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n task[output_chunk_name] = operator(task[input_chunk_name])\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('plugin')\n@click.option('--name',\n type=str,\n default='plugin-1',\n help='name of plugin. Multiple plugins should have different names.')\n@click.option('--input-names', '-i',\n type=str, default=None, help='input names with delimiter of comma')\n@click.option('--output-names', '-o',\n type=str, default=None, help='output names with dilimiter of comma')\n@click.option('--file', '-f', type=str, help='''python file to call. \n If it is just a name rather than full path, \n we\\'ll look for it in the plugin folder.''')\n@click.option('--args', '-a',\n type=str, default=None,\n help='arguments of plugin, this string should be interpreted inside plugin.')\n@operator\ndef plugin(tasks, name: str, input_names: str, output_names: str, file: str, args: str):\n \"\"\"Insert custom program as a plugin.\n The custom python file should contain a callable named \"exec\" such that \n a call of `exec(chunk, args)` can be made to operate on the chunk.\n \"\"\"\n\n operator = Plugin(file, name=name)\n\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n if input_names is not None:\n input_name_list = input_names.split(',')\n inputs = [task[i] for i in input_name_list]\n else:\n inputs = []\n outputs = operator(inputs, args=args)\n if outputs is not None:\n output_name_list = output_names.split(',')\n assert len(outputs) == len(output_name_list)\n for output_name, output in zip(output_name_list, outputs):\n task[output_name] = output\n else:\n assert output_names is None\n\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('connected-components')\n@click.option('--name', type=str, default='connected-components', \n help='threshold a map and get the labels.')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, \n help='input chunk name')\n@click.option('--output-chunk-name', '-o',\n type=str, default=DEFAULT_CHUNK_NAME, \n help='output chunk name')\n@click.option('--threshold', '-t', type=float, default=None,\n help='threshold to cut the map.')\n@click.option('--connectivity', '-c', \n type=click.Choice(['6', '18', '26']),\n default='26', help='number of neighboring voxels used.')\n@operator\ndef connected_components(tasks, name, input_chunk_name, output_chunk_name, \n threshold, connectivity):\n \"\"\"Threshold the probability map to get a segmentation.\"\"\"\n connectivity = int(connectivity)\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n task[output_chunk_name] = task[input_chunk_name].connected_component(\n threshold=threshold, connectivity=connectivity)\n task['log']['timer']['name'] = time() - start\n yield task\n\n\n@main.command('copy-var')\n@click.option('--name', type=str, default='copy-var-1', help='name of step')\n@click.option('--from-name',\n type=str,\n default='chunk',\n help='Variable to be (shallow) copied/\"renamed\"')\n@click.option('--to-name', type=str, default='chunk', help='New variable name')\n@operator\ndef copy_var(tasks, name, from_name, to_name):\n \"\"\"Copy a variable to a new name.\n \"\"\"\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n task[to_name] = task[from_name]\n yield task\n\n\n@main.command('inference')\n@click.option('--name', type=str, default='inference', \n help='name of this operator')\n@click.option('--convnet-model', '-m',\n type=str, default=None, help='convnet model path or type.')\n@click.option('--convnet-weight-path', '-w',\n type=str, default=None, help='convnet weight path')\n@click.option('--input-patch-size', '-s',\n type=int, nargs=3, required=True, help='input patch size')\n@click.option('--output-patch-size', '-z', type=int, nargs=3, default=None, \n callback=default_none, help='output patch size')\n@click.option('--output-patch-overlap', '-v', type=int, nargs=3, \n default=(4, 64, 64), help='patch overlap')\n@click.option('--output-crop-margin', type=int, nargs=3,\n default=None, callback=default_none, help='margin size of output cropping.')\n@click.option('--patch-num', '-n', default=None, callback=default_none,\n type=int, nargs=3, help='patch number in z,y,x.')\n@click.option('--num-output-channels', '-c',\n type=int, default=3, help='number of output channels')\n@click.option('--dtype', '-d', type=click.Choice(['float32', 'float16']),\n default='float32', help=\"\"\"Even if we perform inference using float16, \n the result will still be converted to float32.\"\"\")\n@click.option('--framework', '-f',\n type=click.Choice(['universal', 'identity', 'pytorch']),\n default='universal', help='inference framework')\n@click.option('--batch-size', '-b',\n type=int, default=1, help='mini batch size of input patch.')\n@click.option('--bump', type=click.Choice(['wu', 'zung']), default='wu',\n help='bump function type (only support wu now!).')\n@click.option('--mask-output-chunk/--no-mask-output-chunk', default=False,\n help='mask output chunk will make the whole chunk like one output patch. '\n + 'This will also work with non-aligned chunk size.')\n@click.option('--mask-myelin-threshold', '-y', default=None, type=float,\n help='mask myelin if netoutput have myelin channel.')\n@click.option('--input-chunk-name', '-i',\n type=str, default='chunk', help='input chunk name')\n@click.option('--output-chunk-name', '-o',\n type=str, default='chunk', help='output chunk name')\n@operator\ndef inference(tasks, name, convnet_model, convnet_weight_path, input_patch_size,\n output_patch_size, output_patch_overlap, output_crop_margin, patch_num,\n num_output_channels, dtype, framework, batch_size, bump, mask_output_chunk,\n mask_myelin_threshold, input_chunk_name, output_chunk_name):\n \"\"\"Perform convolutional network inference for chunks.\"\"\"\n with Inferencer(\n convnet_model,\n convnet_weight_path,\n input_patch_size=input_patch_size,\n output_patch_size=output_patch_size,\n num_output_channels=num_output_channels,\n output_patch_overlap=output_patch_overlap,\n output_crop_margin=output_crop_margin,\n patch_num=patch_num,\n framework=framework,\n dtype=dtype,\n batch_size=batch_size,\n bump=bump,\n mask_output_chunk=mask_output_chunk,\n mask_myelin_threshold=mask_myelin_threshold,\n dry_run=state['dry_run']) as inferencer:\n \n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n if 'log' not in task:\n task['log'] = {'timer': {}}\n start = time()\n\n task[output_chunk_name] = inferencer(\n task[input_chunk_name])\n\n task['log']['timer'][name] = time() - start\n task['log']['compute_device'] = inferencer.compute_device\n yield task\n\n\n@main.command('mask')\n@click.option('--name', type=str, default='mask', help='name of this operator')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, help='input chunk name')\n@click.option('--output-chunk-name', '-o',\n type=str, default=DEFAULT_CHUNK_NAME, help='output chunk name')\n@click.option('--volume-path', '-v',\n type=str, required=True, help='mask volume path')\n@click.option('--mip', '-m', \n type=int, default=5, help='mip level of mask')\n@click.option('--inverse/--no-inverse',\n default=False,\n help='inverse the mask or not. default is True. ' +\n 'the mask will be multiplied to chunk.')\n@click.option('--fill-missing/--no-fill-missing',\n default=False,\n help='fill missing blocks with black or not. ' +\n 'default is False.')\n@click.option('--check-all-zero/--maskout',\n default=False,\n help='default is doing maskout. ' +\n 'check all zero will return boolean result.')\n@click.option('--skip-to', type=str, default='write-precomputed', help='skip to a operator')\n@operator\ndef mask(tasks, name, input_chunk_name, output_chunk_name, volume_path, \n mip, inverse, fill_missing, check_all_zero, skip_to):\n \"\"\"Mask the chunk. The mask could be in higher mip level and we\n will automatically upsample it to the same mip level with chunk.\n \"\"\"\n operator = MaskOperator(volume_path,\n mip,\n state['mip'],\n inverse=inverse,\n fill_missing=fill_missing,\n check_all_zero=check_all_zero,\n name=name)\n\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n if check_all_zero:\n # skip following operators since the mask is all zero after required inverse\n task['skip'] = operator.is_all_zero(\n task['bbox'])\n if task['skip']:\n print(yellow(f'the mask of {name} is all zero, will skip to {skip_to}'))\n task['skip_to'] = skip_to\n else:\n task[output_chunk_name] = operator(task[input_chunk_name])\n # Note that mask operation could be used several times,\n # this will only record the last masking operation\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('mask-out-objects')\n@click.option('--name', '-n', type=str, default='mask-out-objects',\n help='remove some objects in segmentation chunk.')\n@click.option('--input-chunk-name', '-i', type=str, default=DEFAULT_CHUNK_NAME)\n@click.option('--output_chunk_name', '-o', type=str, default=DEFAULT_CHUNK_NAME)\n@click.option('--dust-size-threshold', '-d', type=int, default=None,\n help='eliminate small objects with voxel number less than threshold.')\n@click.option('--selected-obj-ids', '-s', type=str, default=None,\n help=\"\"\"a list of segment ids to mesh. This is for sparse meshing. \n The ids should be separated by comma without space, such as \"34,56,78,90\"\n it can also be a json file contains a list of ids. The json file path should\n contain protocols, such as \"gs://bucket/my/json/file/path.\"\"\")\n@operator\ndef mask_out_objects(tasks, name, input_chunk_name, output_chunk_name,\n dust_size_threshold, selected_obj_ids):\n \"\"\"Mask out objects in a segmentation chunk.\"\"\"\n if isinstance(selected_obj_ids, str) and selected_obj_ids.endswith('.json'):\n # assume that ids is a json file in the storage path\n json_storage = Storage(os.path.dirname(selected_obj_ids))\n ids_str = json_storage.get_file(os.path.basename(selected_obj_ids))\n selected_obj_ids = set(json.loads(ids_str))\n assert len(selected_obj_ids) > 0\n logging.info(f'number of selected objects: {len(selected_obj_ids)}')\n\n for task in tasks:\n seg = task[input_chunk_name]\n if not isinstance(seg, Segmentation):\n assert isinstance(seg, Chunk)\n assert seg.is_segmentation\n seg = Segmentation.from_chunk(seg)\n\n seg.mask_fragments(dust_size_threshold)\n seg.mask_except(selected_obj_ids)\n\n task[output_chunk_name] = seg\n yield task\n\n\n@main.command('crop-margin')\n@click.option('--name',\n type=str,\n default='crop-margin',\n help='name of this operator')\n@click.option('--margin-size', '-m',\n type=int, nargs=3, default=None, callback=default_none,\n help='crop the chunk margin. ' +\n 'The default is None and will use the bbox as croping range.')\n@click.option('--input-chunk-name', '-i',\n type=str, default='chunk', help='input chunk name.')\n@click.option('--output-chunk-name', '-o',\n type=str, default='chunk', help='output chunk name.')\n@operator\ndef crop_margin(tasks, name, margin_size, \n input_chunk_name, output_chunk_name):\n \"\"\"Crop the margin of chunk.\"\"\"\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n if margin_size:\n task[output_chunk_name] = task[input_chunk_name].crop_margin(\n margin_size=margin_size)\n else:\n # use the output bbox for croping \n task[output_chunk_name] = task[\n input_chunk_name].cutout(task['bbox'].to_slices())\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('mesh')\n@click.option('--name', type=str, default='mesh', help='name of operator')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, help='name of chunk needs to be meshed.')\n@click.option('--mip', '-m',\n type=int, default=None, help='mip level of segmentation chunk.')\n@click.option('--voxel-size', '-v', type=int, nargs=3, default=None, callback=default_none, \n help='voxel size of the segmentation. zyx order.')\n@click.option('--output-path', '-o', type=str, default='file:///tmp/mesh/', \n help='output path of meshes, follow the protocol rule of CloudVolume. \\\n The path will be adjusted if there is a info file with precomputed format.')\n@click.option('--output-format', '-t', type=click.Choice(['ply', 'obj', 'precomputed']), \n default='precomputed', help='output format, could be one of ply|obj|precomputed.')\n@click.option('--simplification-factor', '-f', type=int, default=100, \n help='mesh simplification factor.')\n@click.option('--max-simplification-error', '-e', type=int, default=40, \n help='max simplification error.')\n@click.option('--manifest/--no-manifest', default=False, help='create manifest file or not.')\n@click.option('--shard/--no-shard', default=False, help='combine meshes as one file')\n@operator\ndef mesh(tasks, name, input_chunk_name, mip, voxel_size, output_path, output_format,\n simplification_factor, max_simplification_error, manifest, shard):\n \"\"\"Perform meshing for segmentation chunk.\"\"\"\n if mip is None:\n mip = state['mip']\n\n operator = MeshOperator(\n output_path,\n output_format,\n mip=mip,\n voxel_size=voxel_size,\n simplification_factor=simplification_factor,\n max_simplification_error=max_simplification_error,\n manifest=manifest,\n shard=shard,\n )\n\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n operator( task[input_chunk_name] )\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('mesh-manifest')\n@click.option('--name', type=str, default='mesh-manifest', help='name of operator')\n@click.option('--input-name', '-i', type=str, default='prefix', help='input key name in task.')\n@click.option('--prefix', '-p', type=int, default=None, help='prefix of meshes.')\n@click.option('--disbatch/--no-disbatch', default=False, help='use disBatch task index as prefix')\n@click.option('--digits', '-d', type=int, default=1, help='number of digits of prefix')\n@click.option('--volume-path', '-v', type=str, required=True, help='cloudvolume path of dataset layer.' + \n ' The mesh directory will be automatically figure out using the info file.')\n@operator\ndef mesh_manifest(tasks, name, input_name, prefix, disbatch, digits, volume_path):\n \"\"\"Generate mesh manifest files.\"\"\"\n operator = MeshManifestOperator(volume_path)\n if prefix:\n operator(prefix, digits)\n elif disbatch:\n assert 'DISBATCH_REPEAT_INDEX' in os.environ\n prefix = os.environ['DISBATCH_REPEAT_INDEX']\n operator(prefix, digits)\n elif input_name:\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n operator(task[input_name], digits)\n task['log']['timer'][name] = time() - start\n yield task\n else:\n logging.error('requires one of parameters: prefix, input_name, disbatch')\n\n\n@main.command('neuroglancer')\n@click.option('--name', type=str, default='neuroglancer',\n help='name of this operator')\n@click.option('--voxel-size', '-v',\n nargs=3, type=int, default=None, callback=default_none,\n help='voxel size of chunk')\n@click.option('--port', '-p', type=int, default=None, help='port to use')\n@click.option('--chunk-names', '-c', type=str, default='chunk', \n help='a list of chunk names separated by comma.')\n@operator\ndef neuroglancer(tasks, name, voxel_size, port, chunk_names):\n \"\"\"Visualize the chunk using neuroglancer.\"\"\"\n operator = NeuroglancerOperator(name=name, port=port, voxel_size=voxel_size)\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n operator(task, selected=chunk_names)\n yield task\n\n\n@main.command('quantize')\n@click.option('--name', type=str, default='quantize', help='name of this operator')\n@click.option('--input-chunk-name', '-i', type=str, default='chunk', help = 'input chunk name')\n@click.option('--output-chunk-name', '-o', type=str, default='chunk', help= 'output chunk name')\n@operator\ndef quantize(tasks, name, input_chunk_name, output_chunk_name):\n \"\"\"Transorm the last channel to uint8.\"\"\"\n for task in tasks:\n aff = task[input_chunk_name]\n aff = AffinityMap(aff)\n assert isinstance(aff, AffinityMap)\n quantized_image = aff.quantize()\n task[output_chunk_name] = quantized_image\n yield task\n\n@main.command('write-precomputed')\n@click.option('--name', type=str, default='write-precomputed', help='name of this operator')\n@click.option('--volume-path', '-v', type=str, required=True, help='volume path')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, help='input chunk name')\n@click.option('--upload-log/--no-upload-log',\n default=True, help='the log will be put inside volume-path')\n@click.option('--create-thumbnail/--no-create-thumbnail',\n default=False, help='create thumbnail or not. ' +\n 'the thumbnail is a downsampled and quantized version of the chunk.')\n@operator\ndef write_precomputed(tasks, name, volume_path, input_chunk_name, upload_log, create_thumbnail):\n \"\"\"Save chunk to volume.\"\"\"\n operator = WritePrecomputedOperator(volume_path,\n state['mip'],\n upload_log=upload_log,\n create_thumbnail=create_thumbnail,\n name=name)\n\n for task in tasks:\n # we got a special case for handling skip\n if task['skip'] and task['skip_to'] == name:\n task['skip'] = False\n # create fake chunk to save\n task[input_chunk_name] = operator.create_chunk_with_zeros(\n task['bbox'])\n\n if not task['skip']:\n # the time elapsed was recorded internally\n operator(task[input_chunk_name],\n log=task.get('log', {'timer': {}}))\n task['output_volume_path'] = volume_path\n yield task\n\n\n@main.command('threshold')\n@click.option('--name', type=str, default='threshold', \n help='threshold a map and get the labels.')\n@click.option('--input-chunk-name', '-i',\n type=str, default=DEFAULT_CHUNK_NAME, \n help='input chunk name')\n@click.option('--output-chunk-name', '-o',\n type=str, default=DEFAULT_CHUNK_NAME, \n help='output chunk name')\n@click.option('--threshold', '-t', type=float, default=0.5,\n help='threshold to cut the map.')\n@operator \ndef threshold(tasks, name, input_chunk_name, output_chunk_name, \n threshold):\n \"\"\"Threshold the probability map.\"\"\"\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n start = time()\n logging.info('Segment probability map using a threshold...')\n task[output_chunk_name] = task[input_chunk_name].threshold(threshold)\n task['log']['timer'][name] = time() - start\n yield task\n\n\n@main.command('channel-voting')\n@click.option('--name', type=str, default='channel-voting', help='name of operator')\n@click.option('--input-chunk-name', type=str, default=DEFAULT_CHUNK_NAME)\n@click.option('--output-chunk-name', type=str, default=DEFAULT_CHUNK_NAME)\n@operator\ndef channel_voting(tasks, name, input_chunk_name, output_chunk_name):\n \"\"\"all channels vote to get a uint8 volume. The channel with max intensity wins.\"\"\"\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n task[output_chunk_name] = task[input_chunk_name].channel_voting() \n yield task\n\n\n@main.command('view')\n@click.option('--name', type=str, default='view', help='name of this operator')\n@click.option('--image-chunk-name',\n type=str,\n default='chunk',\n help='image chunk name in the global state')\n@click.option('--segmentation-chunk-name',\n type=str,\n default=None,\n help='segmentation chunk name in the global state')\n@operator\ndef view(tasks, name, image_chunk_name, segmentation_chunk_name):\n \"\"\"Visualize the chunk using cloudvolume view in browser.\"\"\"\n operator = ViewOperator(name=name)\n for task in tasks:\n handle_task_skip(task, name)\n if not task['skip']:\n operator(task[image_chunk_name],\n seg=segmentation_chunk_name)\n yield task\n\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"chunkflow/flow/flow.py","file_name":"flow.py","file_ext":"py","file_size_in_byte":67067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"186332467","text":"from flask import Flask, jsonify, request\nfrom flask_mongoengine import MongoEngine\n# Init app\napp = Flask(__name__)\n\n# App config\napp.config['JSONIFY_PRETTYPRINT_REGULAR'] = True\napp.config['JSON_SORT_KEYS'] = False\n\n\n# MongoDB config\n\napp.config['MONGODB_SETTINGS'] = {\"host\": 'mongo_image_docker',\n \"username\": \"gabriel\",\n \"password\": \"0000\",\n \"authentication_source\": \"admin\"}\n\n# Init MongoDB\ndb = MongoEngine(app)\n\n\nclass Products(db.Document):\n id = db.IntField(primary_key=True)\n name = db.StringField(required=True)\n description = db.DictField()\n price = db.FloatField()\n\n\n@app.route('/products', methods=['GET'])\ndef get_product():\n products = Products.objects()\n if products.first() is None:\n return jsonify({'Error': 'No products found on DB.'}), 404\n else:\n result = [{\"ProductID\": product.id,\n \"Name\": product.name,\n \"Description\": product.description,\n \"Price\": product.price} for product in products]\n return jsonify(result)\n\n\n@app.route('/products/id', methods=['GET'])\ndef get_id_list():\n products = Products.objects()\n result = [{\"Name\": product.name,\n \"ID\": product.id} for product in products]\n return jsonify(result)\n\n\n@app.route('/products/', methods=['GET'])\ndef get_specific_product(id):\n specific_product = Products.objects(id=id)\n if specific_product.first() is None:\n return jsonify({\"Error\": \"Product does not exist\"})\n else:\n result = [{\"Name\": specific_product.first().name,\n \"Description\": specific_product.first().description,\n \"Price\": specific_product.first().price}]\n return jsonify(result)\n\n\n@app.route('/products', methods=['POST'])\ndef insert_product():\n name = request.json['name']\n id = request.json['id']\n description = request.json['description']\n price = request.json['price']\n if Products.objects(id=id).first() is None:\n products = Products(name=name, id=id, description=description, price=price)\n products.save()\n return jsonify({\"Status\": {'Successful': f'ProductID {id} was successfully added!'}})\n else:\n return jsonify({\"Status\": {'Error': 'ProductID already exists.'}})\n\n\n\n@app.route('/products/', methods=['PUT'])\ndef update_product(id):\n if Products.objects(id=id):\n name = request.json['name']\n description = request.json['description']\n price = request.json['price']\n products = Products.objects(id=id)\n products.update(name=name, description=description, price=price)\n return jsonify({\"Status\": {'Successful': f'ProductID {id} was successfully updated!'}})\n else:\n return jsonify({\"Status\": {'Error': 'Insert a valid ProductID.'}})\n\n\n@app.route('/products/', methods=['DELETE'])\ndef delete_product(id):\n if Products.objects(id=id).first():\n products = Products.objects(id=id)\n products.delete()\n return jsonify({\"Status\": {'Successful': f'ProductID {id} was successfully deleted!'}})\n else:\n return jsonify({\"Status\": {'Error': 'Insert a valid ProductID.'}})\n\n\nif __name__ == \"__main__\":\n app.run(debug=False, host='0.0.0.0')\n","sub_path":"projetos-03-04-05-crud-py-docker/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"448401885","text":"import cv2\nfrom matplotlib import pyplot as plt\nfrom PIL import ImageFilter as pil\nimport numpy as np\n\n\nclass Image:\n\n def __init__(self, img, kernel):\n self.image = cv2.imread(img)\n self.kernel = pil.Kernel(6, kernel, None, 0) # definição do KERNEL/MÁSCARA\n\n def print_pixels(self):\n print(\"Altura: %d pixels\" % (self.image.shape[0])) # shape é um vetor --> índice p extrair o necessario\n print(\"Largura: %d pixels\" % (self.image.shape[1]))\n # print(\"Canais: %d\" % (self.img.shape[2]))\n\n def find_pixel(self):\n rows, cols = self.image.shape\n for i in range(rows):\n for j in range(cols):\n pixel = self.image[i, j]\n print(pixel)\n\n def min_filter(kernel): # aplicar o filtro MINIMO\n image = pil.MinFilter(size=kernel)\n return image\n\n def max_filter(kernel): # aplicar o filtro MAXIMO\n image = pil.MaxFilter(size=kernel)\n return image\n\n def media_filter(self): # aplicar o filtro da MÉDIA\n image = cv2.imread(self.image)\n cv2.blur(image, (5, 5))\n\n def median_filter(self): # aplicar o filtro da MEDIANA\n # elimina eficientemento o ruído (sal e pimenta)\n image = cv2.imread(self.image)\n cv2.medianBlur(image, 5)\n\n def filter2d(self): # CONVOLUÇÃO DISCRETA 2D\n # toma como base a imagem e o valor definido no KERNEL\n image = cv2.imread(self.image)\n cv2.filter2D(image, -1, self.kernel)\n\n def histogram(self):\n image = cv2.imread(self.image)\n cv2.calcHist(image, [0], None, [256], [0, 256])\n plt.hist(image.ravel(), 256, [0, 256])\n plt.title('Histograma')\n plt.xlabel('Valores dos pixels')\n plt.ylabel('Qntd. de pixels')\n plt.grid(True)\n plt.show()\n\n def histogram_bgr(self):\n image = cv2.imread(self.image)\n color = ('b', 'g', 'r')\n for i, col in enumerate(color):\n histograma = cv2.calcHist([image], [i], None, [256], [0, 256])\n plt.plot(histograma, color=col)\n plt.xlim([0, 256])\n plt.title('Histograma: escala BGR')\n plt.xlabel('Valores dos pixels')\n plt.ylabel('Qntd. de pixels')\n plt.grid(True)\n plt.show()\n\n def contours(self):\n # CONTORNOS - Detector de Bordas\n im = cv2.imread(self.image)\n imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)\n ret, thresh = cv2.threshold(imgray, 127, 255, 0)\n im_o, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n # contours --> é uma lista em Python de todos os contornos da imagem (contorno = matriz)\n # Desenhando os CONTORNOS na Imagem:\n img_cont = cv2.drawContours(im, contours, -1, (0, 255, 0), 3)\n # parametros: (imagem_origem, lista_contornos, índice (-1), cor, espessura...)\n # cv2.imwrite(\"D:\\imagem_cont.jpg\", img_cont) SALVAR A IMAGEM\n\n def contours_canny(self):\n # Detecção de contornos pelo MÉTODO CANNY\n image = cv2.imread(self.image)\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n suave = cv2.GaussianBlur(gray, (7, 7), 0)\n canny = cv2.Canny(suave, 10, 30) # 20, 120 - menos mais bordas\n result = np.vstack(canny)\n # cv2.imwrite(\"D:\\imagem_bordasCanny.jpg\", result) SALVAR A IMAGEM\n\n def equalize(self):\n # EQUALIZAÇÃO DO HISTOGRAMA --> \"esticar\" o hist, evitar que fique concentrado apenas em um ponto alto\n # Melhorar o contraste da imagem --> aumentar detalhes\n img = cv2.imread(self.image)\n equa = cv2.equalizeHist(img)\n cv2.calcHist(equa, [0], None, [256], [0, 256])\n plt.hist(equa.ravel(), 256, [0, 256])\n plt.title('Histograma Equalizado')\n plt.xlabel('Valores dos pixels')\n plt.ylabel('Qntd. de pixels')\n plt.grid(True)\n plt.show()\n # res = np.hstack((img, equa)) # colocar imagem original e equa lado a lado\n # cv2.imwrite(\"D:\\imagem_equalizada.jpg\", res)\n","sub_path":"PycharmProjects/PDI/image_pdi.py","file_name":"image_pdi.py","file_ext":"py","file_size_in_byte":4046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"12571641","text":"\nfrom dcentity.models import Entity\nfrom django.db import connection\nfrom piston.handler import BaseHandler\nfrom piston.utils import rc\n\n\n# at the database level -1 is used to indicate summation over all cycles\nALL_CYCLES = '-1'\nDEFAULT_LIMIT = '10'\nDEFAULT_CYCLE = ALL_CYCLES\n\nclass SQLBindingError(Exception):\n pass\n\n\ndef execute_top(stmt, *args):\n cursor = connection.cursor()\n\n execute(cursor, stmt, args)\n\n return list(cursor)\n\ndef execute_pie(stmt, *args):\n cursor = connection.cursor()\n execute(cursor, stmt, args)\n return dict([(category, (count, amount)) for (category, count, amount) in cursor])\n\ndef execute_one(stmt, *args):\n cursor = connection.cursor()\n execute(cursor, stmt, args)\n\n if cursor.rowcount <= 0:\n return None\n else:\n return cursor.fetchone()\n\ndef execute(cursor, stmt, args):\n try:\n # Just gonna leave this here...\n # print cursor.mogrify(stmt, args)\n cursor.execute(stmt, args)\n except IndexError:\n raise SQLBindingError(\"You didn't include the right number of binding parameters in your query.\")\n\n\ndef check_empty(result, *entity_ids):\n \"\"\" Empty results are normally fine, except when the entity ID doesn't exist at all--then return 404. \"\"\"\n\n if not result and Entity.objects.filter(id__in=entity_ids).count() < len(entity_ids):\n error_response = rc.NOT_FOUND\n error_response.write('No entity with the given ID.')\n return error_response\n\n return result\n\n\nclass TopListHandler(BaseHandler):\n\n args = ['cycle', 'limit']\n fields = None\n stmt = None\n\n def read(self, request, **kwargs):\n kwargs.update({'cycle': request.GET.get('cycle', ALL_CYCLES)})\n\n raw_result = execute_top(self.stmt, *[kwargs[param] for param in self.args])\n labeled_result = [dict(zip(self.fields, row)) for row in raw_result]\n\n return labeled_result\n\n\nclass EntityTopListHandler(BaseHandler):\n\n args = ['entity_id', 'cycle', 'limit']\n fields = None\n stmt = None\n\n def read(self, request, **kwargs):\n kwargs.update({'cycle': request.GET.get('cycle', ALL_CYCLES)})\n kwargs.update({'limit': request.GET.get('limit', DEFAULT_LIMIT)})\n\n raw_result = execute_top(self.stmt, *[kwargs[param] for param in self.args])\n labeled_result = [dict(zip(self.fields, row)) for row in raw_result]\n\n return check_empty(labeled_result, kwargs['entity_id'])\n\n\nclass EntitySingletonHandler(BaseHandler):\n\n args = ['entity_id', 'cycle']\n fields = None\n stmt = None\n\n def read(self, request, **kwargs):\n kwargs.update({'cycle': request.GET.get('cycle', ALL_CYCLES)})\n\n result = execute_one(self.stmt, *[kwargs[param] for param in self.args])\n\n if result:\n result = dict(zip(self.fields, result))\n else:\n result = {}\n\n return check_empty(result, kwargs['entity_id'])\n\n\nclass PieHandler(BaseHandler):\n\n args = ['entity_id', 'cycle']\n category_map = {}\n default_key = None\n stmt = None\n\n def read(self, request, **kwargs):\n kwargs.update({'cycle': request.GET.get('cycle', ALL_CYCLES)})\n\n raw_result = execute_pie(self.stmt, *[kwargs[param] for param in self.args])\n\n if self.default_key:\n labeled_result = dict([(self.category_map[key], value) for (key, value) in raw_result.items() if key in self.category_map])\n\n extra_keys = [k for k in raw_result.keys() if k not in self.category_map.keys()]\n if extra_keys:\n labeled_result[self.default_key] = (sum([value[0] for (key, value) in raw_result.items() if key in extra_keys]), sum([value[1] for (key, value) in raw_result.items() if key in extra_keys]))\n else:\n labeled_result = dict([(self.category_map[key], value) if key in self.category_map else (key, value) for (key, value) in raw_result.items() ])\n\n return check_empty(labeled_result, kwargs['entity_id'])\n\n\n","sub_path":"dcapi/aggregates/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"80704124","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom Selenium2Library import Selenium2Library\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\n\n\nclass Selenium2Improved(Selenium2Library):\n\n '''Sometimes Selenium2Library just dont go far enough.'''\n\n def __init__(self, timeout=5.0, implicit_wait=0.0,\n run_on_failure='Capture Page Screenshot'):\n super(Selenium2Improved, self).__init__()\n\n def open_tab(self, url, alias):\n \"\"\"\n Selenium1 的 Open Window 功能已被移除\n 所以 Selenium2Improved 改由自己實作\n 以執行 JS 的方式來實作開新 Tab 的功能\n 開完新 Tab 後會將舊有的 Tab Title 重新命名成 Original Tab\n 借此區別新舊 Tab\n \"\"\"\n driver = self._current_browser()\n driver.execute_script(\"window.open('\" + url + \"', '_blank');\")\n \n def press_shift_and_click_element(self, locator):\n if locator.startswith(\"xpath=\"):\n web_element = self._current_browser().find_element(By.XPATH, locator[len(\"xpath=\"):])\n actions = ActionChains(self._current_browser())\n actions.key_down(Keys.SHIFT).click(web_element).key_up(Keys.SHIFT).perform()\n def press_control_and_click_element(self, locator):\n if locator.startswith(\"xpath=\"):\n web_element = self._current_browser().find_element(By.XPATH, locator[len(\"xpath=\"):])\n actions = ActionChains(self._current_browser())\n actions.key_down(Keys.CONTROL).click(web_element).key_up(Keys.CONTROL).perform()\n","sub_path":"ezScrum2019_AT/keywords/lib/Selenium2Improved.py","file_name":"Selenium2Improved.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"349830243","text":"# -*- coding: utf-8 -*-\n\nfrom django.template import RequestContext\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.core.mail import send_mail, EmailMessage\nimport os\nfrom models import Zvonok\nfrom forms import FormZvonok\nfrom setttings.models import Settings\nfrom django.utils import simplejson\nfrom settings_local import EMAIL_ADDRESS_FROM\n \ndef zvonok(request):\n sended = False\n if request.method == 'POST' and request.is_ajax():\n form = FormZvonok(data=request.POST)\n rdict = {'valid':'true'}\n if form.is_valid():\n settings=Settings.objects.all()[0]\n cd = form.cleaned_data \n mess = u\"\" \n mess += u\"Телефон: %s\\n\" % (cd['tel'])\n mess += u\"Имя: %s\\n\" % cd['imya']\n mess += u\"Город: %s\\n\" % cd['city']\n mess += u\"Вопрос: %s\\n\" % cd['vopros'] if cd['vopros'] else \"--\" \n zvonok=Zvonok(imya=cd['imya'],tel=cd['tel'],city=cd['city'],vopros=cd['vopros'])\n zvonok.save()\n for n in settings.email_zakaz.split(', '):\n mail = EmailMessage(u'Заказ звонка', mess, EMAIL_ADDRESS_FROM, [n])\n mail.send()\n form = FormZvonok() \n sended = True \n json = simplejson.dumps(rdict, ensure_ascii=False)\n return HttpResponse(json, mimetype='text/javascript')\n else:\n rdict.update({'valid':'false'})\n d={}\n for e in form.errors.iteritems():\n d.update({e[0]:unicode(e[1].as_text())})\n rdict.update({'errs': d })\n json = simplejson.dumps(rdict, ensure_ascii=False)\n return HttpResponse( json, mimetype='text/javascript') \n","sub_path":"apps/zakazat_zvonok/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"289345086","text":"class SinglyLL:\n def __init__(self, init_node=None):\n self.head = init_node\n self.tail = init_node\n\n def __str__(self):\n n = self.head\n s = str(n.value) + \" -> \"\n while n.next:\n s += str(n.next.value) + \" -> \"\n n = n.next\n return s\n\n # Add a node to the tail of the list\n def insert(self, node):\n n = node.value\n if self.head == None:\n self.head = node\n self.tail = node\n else:\n self.tail.next = node\n self.tail = node\n\n # Search a linked list for a value\n def search(self, value):\n n = self.head\n while n and n.value != value:\n n = n.next\n return n != None\n\n def delete(self, value):\n if self.head == None:\n return False\n\n n = self.head\n if n.value == value:\n if self.head == self.tail:\n self.head = self.tail = None\n else:\n self.head = self.head.next\n return True\n while n.next != None and n.next.value != value:\n n = n.next\n if n.next != None:\n if n.next == self.tail:\n self.tail = n\n n.next = n.next.next\n return True\n return False\n\n # Removes the tail and returns the value - HARDish\n # def pop(self):\n # if self.head == None:\n # return None\n # elif self.head != None and self.head.next\n\n def traverse(self):\n n = self.head\n while n != None:\n print(n.value)\n n = n.next\n\n def reverseTraverse(self):\n # First check if the tail exists\n if self.tail != None:\n # now set the current node to be the tail\n curr = self.tail\n # we forward traverse the list until we reach the node before the current node\n\n # Since we move the current node back one link in each step, we check to see that it's not\n # the head node yet\n while curr != self.head:\n prev = self.head\n while prev.next != curr:\n prev = prev.next\n print(prev.next.value)\n curr = prev\n print(curr.value)\n\n\nclass DoublyLL:\n def __init__(self, init_node=None):\n if init_node:\n # If we give an init node we check if it is an instance of the DoubleNode class\n # If it is not, we raise a TypeError that can be handled by the calling code\n if not isinstance(init_node, DoubleNode):\n raise TypeError(\"Init node must be of type DoubleNode\")\n self.head = init_node\n self.tail = init_node\n\n def __str__(self):\n if not self.head:\n return \"\"\n n = self.head\n s = str(n.value) + \" <-> \"\n while n.next:\n s += str(n.next.value) + \" <-> \"\n n = n.next\n return s\n\n def insert(self, node):\n if not isinstance(node, DoubleNode):\n raise TypeError(\"Node must be of type DoubleNode\")\n if self.head == None:\n self.head = node\n self.tail = node\n else:\n node.prev = self.tail\n self.tail.next = node\n self.tail = node\n\n def delete(self, value):\n if self.head == None:\n return False\n if value == self.head.value:\n if self.head == self.tail:\n self.head = None\n self.tail = None\n else:\n self.head = self.head.next\n self.head.prev = None\n return True\n else:\n n = self.head.next\n while n != None and n.value != value:\n n = n.next\n if n == self.tail:\n self.tail = self.tail.prev\n self.tail.next = None\n return True\n elif n != None:\n n.prev.next = n.next\n n.next.prev = n.prev\n return True\n return False\n\n def reverseTraverse(self):\n n = self.tail\n while n != None:\n print(n.value)\n n = n.prev\n\n # Same as LL\n def traverse(self):\n n = self.head\n while n != None:\n print(n.value)\n n = n.next\n\n # Same as LL\n def search(self, value):\n n = self.head\n while n and n.value != value:\n n = n.next\n return n != None\n\n\nclass DoubleNode:\n def __init__(self, val):\n self.value = val\n self.prev = None\n self.next = None\n\n def __str__(self):\n return str(self.value)\n\n\nclass Node:\n def __init__(self, val):\n self.value = val\n self.next = None\n\n def __str__(self):\n return str(self.value)\n\n\nif __name__ == \"__main__\":\n try:\n dll = DoublyLL(Node(3))\n except TypeError:\n dll = DoublyLL(DoubleNode(3))\n # print(dll)\n\n dll.insert(DoubleNode(4))\n dll.insert(DoubleNode(30))\n dll.insert(DoubleNode(300))\n # dll.reverseTraverse()\n print(dll.delete(300))\n print(dll)\n # ll = SinglyLL(Node(1))\n # ll.insert(Node(45))\n # ll.insert(Node(60))\n # ll.insert(Node(12))\n # # print(ll.head, ll.tail)\n # print(ll)\n\n # # print(ll.search(11))\n # print(ll.delete(45))\n\n # # ll.traverse()\n # ll.reverseTraverse()\n # print(ll)\n","sub_path":"basecs/linkedlist.py","file_name":"linkedlist.py","file_ext":"py","file_size_in_byte":5385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"157043129","text":"\"\"\"\n295\nfind median from data stream\nhard\n\"\"\"\n\n\nclass MedianFinder:\n\n # TLE\n\n def __init__(self):\n \"\"\"\n initialize your data structure here.\n \"\"\"\n from collections import Counter\n self.count = Counter()\n self.total = 0\n self.unique = []\n\n def addNum(self, num: int) -> None:\n if num not in self.unique:\n self.unique.append(num)\n self.count[num] += 1\n self.total += 1\n return None\n\n def findMedian(self) -> float:\n self.unique.sort()\n if self.total % 2 == 1:\n c = 0\n for val in self.unique:\n if c + self.count[val] >= self.total // 2 + 1:\n return val\n else:\n c += self.count[val]\n if self.total % 2 == 0:\n c = 0\n for val in self.unique:\n if c + self.count[val] == self.total / 2:\n left = val\n if c == self.total / 2:\n right = val\n return (left + right) / 2\n if c < self.total / 2 < c + self.count[val]:\n return val\n c += self.count[val]\n\n\nsol = MedianFinder()\nsol.addNum(1)\nprint(sol.findMedian())\nsol.addNum(2)\nprint(sol.findMedian())","sub_path":"Q295.py","file_name":"Q295.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"174572013","text":"import pymysql\nfrom .items import *\n\n\nclass SriScrapyPipeline:\n\n def __init__(self):\n\n self.db = pymysql.connect(host='localhost', user='root', password='123456', port=3306, db='sh')\n self.cursor = self.db.cursor()\n\n def process_item(self, item, spider):\n\n print('\\n---------------理应写入一个数据数据库----------------\\n')\n\n # 年报表 (id, code, title, date, link)\n if isinstance(item, SriAnnualItem):\n try:\n sql = \"insert into sh.sh_annual(`code`, `title`, `date`, `link`) values(%s,%s,%s,%s);\"\n self.cursor.execute(sql, (item['code'], item['title'], item['date'], item['link']))\n self.db.commit()\n return item\n except:\n print(\"pipeline SriAnnualItem存入数据库失败\\n\")\n\n # 中报表 (id, code, title, date, link)\n elif isinstance(item, SriMidItem):\n try:\n sql = \"insert into sh.sh_mid(`code`, `title`, `date`, `link`) values(%s,%s,%s,%s);\"\n self.cursor.execute(sql, (item['code'], item['title'], item['date'], item['link']))\n self.db.commit()\n return item\n except:\n print(\"pileline SirmidItem存入数据库失败\\n\")\n else:\n return item\n\n\n def close_spider(self, spider):\n self.db.close()","sub_path":"SRI_scrapy/SRI_scrapy/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"174328041","text":"# Django settings for foo project.\n\nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.\n 'NAME': 'dfk.db', # Or path to database file if using sqlite3.\n }\n}\n\nROOT_URLCONF = 'test_urls'\n\nINSTALLED_APPS = (\n 'dfk',\n)\n","sub_path":"dfk/test_settings.py","file_name":"test_settings.py","file_ext":"py","file_size_in_byte":388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"208022995","text":"# -*- coding: utf-8 -*-\nfrom browsermobproxy import Server\nfrom selenium import webdriver\nimport json\n\n# \"\"C:\\\\browsermob-proxy-2.0-beta-9\\\\bin\\\\browsermob-proxy.bat\"\"\nserver = Server(u\"D:/pyCharm\\myself_python/browsermob-proxy-2.0-beta-6-bin/browsermob-proxy-2.0-beta-6/bin/browsermob-proxy.bat\")\nserver.start()\nproxy = server.create_proxy()\n\n# profile = webdriver.FirefoxProfile()\n# profile.set_proxy(proxy.selenium_proxy())\n# driver = webdriver.Firefox(firefox_profile=profile)\ndriver = webdriver.PhantomJS(executable_path=u\"E:\\python\\phantomjs-1.9.7-windows\\phantomjs.exe\")\n\nproxy.new_har(\"baidu\")\ndriver.get(\"http://www.baidu.com\")\nproxy.wait_for_traffic_to_stop(1, 60)\nwith open('1.har', 'w') as outfile:\n json.dump(proxy.har, outfile)\n\nserver.stop()\ndriver.quit()","sub_path":"test_selenium/test_browser.py","file_name":"test_browser.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"340745726","text":"letters = [str(i) for i in range(10)] + [chr(i) for i in range(65, 91)]\nword = 'QUEEN'\nidx = max(letters.index(i) for i in word)\n\nmax_value = 10 ** 8\n\nfor base in range(31, 100):\n s = 0\n for digit in word:\n s *= base\n s += letters.index(digit)\n if s < 10 ** 9:\n max_value = s\n \nprint(max_value)","sub_path":"1st_tour/inf/try_2/task_01/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"59697771","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\nA következő függvények3.py program két függvényt mutat be, az egyiknek egy\nparamétere van és nincs visszatérési értéke, a másiknak nincs sem paramétere,\nsem visszatérési értéke. Ekkor a return utasítás önmagában szerepel.\nAmennyiben a visszatérési érték nélküli rutin olyan, hogy nincs benne\nelágazás, akkor a return utasítás el is hagyható. Valójában a visszatérési\nérték nélküli függvény egy speciális értéket, a None-t adja vissza, s ezért\nnem kapunk hibajelzést az a=c10() értékadó utasításnál, az a értéke None lesz\n(a None-ról még sok szó lesz a későbbiekben).\n\"\"\"\n\n\n# Kiírja az argumentum értékét\ndef mutat(v): # egy paraméter\n print(v)\n return \t\t# nincs visszatérési érték\n\n\n# Mindig 10-et ír ki\ndef c10(): # nincs paraméter\n print(10)\n # return\n # nincs visszatérési érték és a return sem fontos\n\n\nmutat(3.14) \t# \"belül\" van a print()\nc10() \t\t\t# \"belül\" van a print()\na = c10()\nprint(a)\ninput(\"A befejezéshez nyomja meg az Enter-t!\")\n","sub_path":"02_Fuggvenyek/04_fuggvenyek2.py","file_name":"04_fuggvenyek2.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"115504706","text":"\"\"\" Find shortest path from WT to most common sequence in Round 15\"\"\"\nimport math\nimport itertools\n\nimport numpy as np\nimport pandas as pd\n\nimport torch\n\nimport json\n\nimport config\nimport utils\n\nfrom energy_py import EnergyFunctionCalculator, energy_calc_msa, energy_calc_single\nimport energy_py\n\nWT = config.WT_AA_TENSOR.numpy()\n\n\nmodel_prefix = \"DHFR_incl_main_kit_taq_mse\"\n\n\nh_i_a = torch.load(f\"../working/{model_prefix}_h_i_a.pt\").numpy()\ne_i_a_j_b = torch.load(f\"../working/{model_prefix}_e_i_a_j_b.pt\").numpy()\n#e_i_a_j_b = e_i_a_j_b / 2.\n\nenergy_calc = EnergyFunctionCalculator(h_i_a, e_i_a_j_b)\n\nWT_energy = energy_calc(WT) # lower is fitter\nWT_energy # array(0.7909182)\n\n\ndesigned_proteins = pd.read_csv(f\"{config.WORKING_DIR}/{model_prefix}_designed.csv\")\nstart_designed_protein = designed_proteins.seq.iloc[0]\nterminal_designed_protein = designed_proteins.seq.iloc[-1]\n\nwith open(f\"{config.WORKING_DIR}/adaptive_walk/even/walk_0.json\") as fh:\n x = json.load(fh)\n convergent_protein = x[\"end_protein\"]\n\ndef print_prot_diff(s1, s2):\n for i, (ss1, ss2) in enumerate(zip(s1, s2)):\n if ss1 != ss2:\n print(f\"{i:03d}: {ss1}->{ss2}\")\n\nprint(\"Where does terminal_designed_protein differ from convergent_protein\")\nprint_prot_diff(terminal_designed_protein, convergent_protein)\nprint()\n# 007: V->A\n# 090: K->E\n# 131: M->R\n# 166: S->G\n\n\nprint(\"Where does start_designed_protein differ from WT\")\nprint_prot_diff(config.WT_AA, start_designed_protein)\nprint()\n# 018: N->D\n# 040: S->G\n# 079: K->I\n# 094: D->G\n# 141: F->L\n# 143: S->C\n# 144: D->N\n# 165: L->P\n# 179: E->A\n# 185: D->V\n\nmutants = pd.DataFrame([(i, x1, x2) for i, (x1, x2) in \n enumerate(zip(WT, start_designed_protein_np)) if x1 != x2], \n columns=[\"idx\",\"aa_wt\",\"aa_start\"])\n\nnum_muts = len(mutants)\n\nmuts_d = {i:np.array(list(itertools.combinations(range(num_muts), i))) \n for i in range(1,num_muts)}\n\ndef calc_energy_mut(mut_idxs):\n \"\"\"mut is 1d-numpy integer array with values between 0 \n and (num_muts - 1). We look up the actual mutants in the \n mutants dataframe and apply them and return the energy\n \"\"\"\n m = WT.copy()\n m[mutants.idx.iloc[mut_idxs]] = mutants.aa_start.iloc[mut_idxs]\n return energy_calc(m).item()\n\n@config.memory.cache\ndef get_mutants_energy_dict(muts_d):\n return {key:np.apply_along_axis(calc_energy_mut, axis=1, arr=arr) \n for key, arr in muts_d.items()}\n\n\nenergy_d = get_mutants_energy_dict(muts_d)\n\n\ndef get_one_mutant_adjacency(arr_num_muts, arr_num_muts_plus_one):\n \"\"\" Find out which n mutants are only 1 mutant difference from the \n n+1 mutants \n Ex. Not all 3 mutants can mutate to all 4 mutants so we have a flag \n between them if they can be reached by 1 mutant (adjaceny matrix)\n \"\"\"\n assert(arr_num_muts_plus_one.shape[1] == arr_num_muts.shape[1] + 1)\n ret = np.zeros((arr_num_muts.shape[0], arr_num_muts_plus_one.shape[0]), dtype=int)\n for ix, x in enumerate(arr_num_muts):\n x = set(x)\n for iy, y in enumerate(arr_num_muts_plus_one):\n if x.issubset(y):\n ret[ix, iy] = 1\n return ret\n\nadjs_d = {i:get_one_mutant_adjacency(muts_d[i], muts_d[i+1]) \n for i in range(1, num_muts-1)}\n\n\nenergy_adjs_d = {}\nfor i, arr in adjs_d.items():\n ix, iy = np.where(arr) # where the single mutant transitions can happen\n energy_adjs_d[i] = (ix, iy, energy_d[i][ix] + energy_d[i+1][iy])\n\n# count all the paths that we can travel and sum their energy\nix = {}\niy = {}\npath_energy = {}\n\n#ix[1], iy[1] = np.where(adjs_d[1])\n#path_energy[2] = energy_d[1][ix[1]] + energy_d[2][iy[1]]\n#\n#ix[2], iy[2] = np.where(adjs_d[2][iy[1], :])\n#path_energy[3] = path_energy[2][ix[2]] + energy_d[3][iy[2]]\n#...\n\nfor i in range(1, num_muts-1):\n if (i == 1):\n ix[i], iy[i] = np.where(adjs_d[i])\n path_energy[i+1] = energy_d[i][ix[i]] + energy_d[i+1][iy[i]]\n else:\n ix[i], iy[i] = np.where(adjs_d[i][iy[i-1]])\n path_energy[i+1] = path_energy[i][ix[i]] + energy_d[i+1][iy[i]]\n print(path_energy[i+1].shape)\n\n\nassert(path_energy[num_muts-1].size == math.factorial(num_muts))\n\nshortest_path_idx = path_energy[9].argmin().item()\nshortest_path_energy = path_energy[9][shortest_path_idx]\n\nprint(muts_d[9][iy[8][shortest_path_idx]])\n#[0 1 2 3 5 6 7 8 9]\nsp8 = ix[8][shortest_path_idx]\nprint(muts_d[8][iy[7][sp8]])\nsp7 = ix[7][sp8]\nprint(muts_d[7][iy[6][sp7]])\nsp6 = ix[6][sp7]\nprint(muts_d[6][iy[5][sp6]])\nsp5 = ix[5][sp6]\nprint(muts_d[5][iy[4][sp5]])\nsp4 = ix[4][sp5]\nprint(muts_d[4][iy[3][sp4]])\nsp3 = ix[3][sp4]\nprint(muts_d[3][iy[2][sp3]])\nsp2 = ix[2][sp3]\nprint(muts_d[2][iy[1][sp2]])\nsp1 = ix[1][sp2]\nprint(sp1)\n\n# loop form of the above\n\ndef mut_to_string(mut_idxs):\n \"\"\"mut is 1d-numpy integer array with values between 0 \n and (num_muts - 1). We look up the actual mutants in the \n mutants dataframe and apply them and return the energy\n \"\"\"\n m = WT.copy()\n m[mutants.idx.iloc[mut_idxs]] = mutants.aa_start.iloc[mut_idxs]\n return config.prot_to_string(m)\n\nprotein_path = {}\nprotein_path[10] = start_designed_protein\n\nsp = {} # shortest path indices\nfor i in reversed(range(1, num_muts)):\n if i == 9:\n sp[9] = shortest_path_idx\n else:\n sp[i] = ix[i][sp[i+1]]\n if i == 1:\n p = muts_d[i][sp[i]]\n else:\n p = muts_d[i][iy[i-1][sp[i]]] \n print(p)\n protein_path[i] = mut_to_string(p)\n\nprotein_path_pd = pd.DataFrame.from_dict(protein_path, orient=\"index\", \n columns=[\"protein\"]).sort_index().reset_index()\n\nprotein_path_pd.to_csv(f\"{config.WORKING_DIR}/{model_prefix}_shortest_path.csv\", \n index=False)\n\n\nfor _ in range(10): # create random paths and check their energy\n random_path = np.random.choice(num_muts, replace=False, size=num_muts)\n random_path_energy = 0.\n for i in range(1, num_muts):\n random_path_energy += calc_energy_mut(random_path[:i])\n print(random_path_energy)\n assert(random_path_energy >= shortest_path_energy)\n\n\n\n\n","sub_path":"scripts/shortest_path.py","file_name":"shortest_path.py","file_ext":"py","file_size_in_byte":6076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"15918233","text":"from django.shortcuts import render\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom blog.models import Article\n# Create your views here.\n\ndef search(request):\n question = request.GET.get('q')\n if question is not None:\n search_articles = Article.objects.filter(content__search=question)\n last_question = '?q=%s' % question\n\n paginator = Paginator(search_articles, 3)\n page = request.GET.get('page')\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n posts = paginator.page(1)\n except EmptyPage:\n posts = paginator.page(paginator.num_pages)\n\n return render(request, 'search/search_result.html', {'page': page, 'posts': posts, 'last_question': last_question, 'question': question})","sub_path":"MemoryBlog/search/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"463164754","text":"import os, pymysql\nimport tornado.web, tornado.locks, tornado.ioloop\nfrom handler.WelcomeHandler import WelcomeHandler\nfrom handler.MidHandler import MidHandler\nfrom handler.ActivityHandler import ActivityHandler\nfrom handler.MemberHandler import MemberHandler\nfrom handler.ShipHandler import ShipHandler\nfrom handler.AdHandler import AdHandler\nfrom handler.GroupBuildingHandler import GroupBuildingHandler\nfrom handler.admin.AdminWelcomeHandler import AdminWelcomeHandler\nfrom handler.admin.AdminActivityHandler import AdminActivityHandler, AdminOrderHandler, AdminOverActivityHandler, AdminReturnActivityHandler\nfrom handler.admin.AdminMemberHandler import AdminMemberHandler\nfrom handler.admin.AdminShipHandler import AdminShipHandler, AdminBrokingShipHandler, AdminFreeShipHandler,AdminFinishShipHandler, AdminNormalShipHandler\nfrom handler.admin.AdminAdHandler import AdminAdHandler, AdminExamineAdHandler, AdminOverAdHandler, AdminBrokeAdHandler\nfrom handler.admin.AdminGbHandler import AdminGbHandler, AdminBrokeGbHandler, AdminExamineGbHandler, AdminOverGbHandler\nfrom handler.admin.AdminKeyHandler import AdminKeyHandler\nfrom handler.admin.AdminSearchHandler import AdminSearchHandler\nfrom handler.admin.AdminSpotHandler import AdminSpotHandler\nfrom handler.admin.AdminActivityFundHandler import AdminActivityFund\n\n# 数据库信息\nHOST = '127.0.0.1'\nUSERNAME = 'root'\nPASSWORD = 'projectDIVAF.'\nDATABASE = 'final_design'\n\nclass Application(tornado.web.Application):\n def __init__(self, db):\n self.db = db\n #api定义\n handlers = [\n tornado.web.url(r'/', WelcomeHandler, name='welcome'),\n tornado.web.url(r'/mid', MidHandler, name='mid'),\n tornado.web.url(r'/activity', ActivityHandler, name='activity'),\n tornado.web.url(r'/member', MemberHandler, name='member'),\n tornado.web.url(r'/ship', ShipHandler, name='ship'),\n tornado.web.url(r'/ad', AdHandler, name='ad'),\n tornado.web.url(r'/gb', GroupBuildingHandler, name='gb'),\n tornado.web.url(r'/admin', AdminWelcomeHandler, name='admin_welcome'),\n tornado.web.url(r'/admin/activity', AdminActivityHandler, name='admin_activity'),\n tornado.web.url(r'/admin/member', AdminMemberHandler, name='admin_member'),\n tornado.web.url(r'/admin/ship', AdminShipHandler, name='admin_ship'),\n tornado.web.url(r'/admin/ad/now', AdminAdHandler, name='admin_ad'),\n tornado.web.url(r'/admin/ad/over', AdminOverAdHandler, name='admin_over_ad'),\n tornado.web.url(r'/admin/ad/examine', AdminExamineAdHandler, name='admin_over_ad'),\n tornado.web.url(r'/admin/ad/broke', AdminBrokeAdHandler, name='admin_broke_ad'),\n tornado.web.url(r'/admin/gb', AdminGbHandler, name='admin_gb'),\n tornado.web.url(r'/admin/key', AdminKeyHandler, name='admin_key'),\n tornado.web.url(r'/admin/activity/order', AdminOrderHandler, name='admin_order'),\n tornado.web.url(r'/admin/activity/over', AdminOverActivityHandler, name='admin_over'),\n tornado.web.url(r'/admin/ship/broking', AdminBrokingShipHandler, name='admin_broking_ship'),\n tornado.web.url(r'/admin/ship/free', AdminFreeShipHandler, name='admin_free_ship'),\n tornado.web.url(r'/admin/ship/finish', AdminFinishShipHandler, name='admin_finish_ship'),\n tornado.web.url(r'/admin/ship/normal', AdminNormalShipHandler, name='admin_normal_ship'),\n tornado.web.url(r'/admin/gb/examine', AdminExamineGbHandler, name='admin_examine_gb'),\n tornado.web.url(r'/admin/gb/broke', AdminBrokeGbHandler, name='admin_broke_gb'),\n tornado.web.url(r'/admin/gb/over', AdminOverGbHandler, name='admin_over_gb'),\n tornado.web.url(r'/admin/search', AdminSearchHandler, name='admin_search'),\n tornado.web.url(r'/admin/spot', AdminSpotHandler, name='admin_spot'),\n tornado.web.url(r'/admin/fund', AdminActivityFund, name='admin_fund'),\n tornado.web.url(r'/admin/activity/return', AdminReturnActivityHandler, name='admin_return_ship'),\n ]\n # 服务端设置,设定好网页和静态文件存放位置,以及安全设置\n settings = dict(\n template_path = os.path.join(os.path.dirname(__file__), 'templates'),\n static_path = os.path.join(os.path.dirname(__file__), 'static'),\n debug = True,\n xsrf_cookie = True,\n )\n super(Application, self).__init__(handlers, **settings)\n\n# async把迭代器标记为协程,然后协程内部用await调用另一个协程\n# 将db对象传入服务端,作为唯一全局变量\n# 初始化服务端,让服务端持久服务\nasync def main():\n db = pymysql.connect(HOST, USERNAME, PASSWORD, DATABASE)\n app = Application(db)\n app.listen(8080)\n await tornado.locks.Event().wait()\n\nif __name__ == '__main__': \n tornado.ioloop.IOLoop.current().run_sync(main)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"102500973","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass Action(Model):\n \"\"\"The action that will be executed.\n\n :param action_type: The type of the action. Possible values include:\n 'EmailContacts', 'AutoRenew'\n :type action_type: str or ~azure.keyvault.models.ActionType\n \"\"\"\n\n _attribute_map = {\n 'action_type': {'key': 'action_type', 'type': 'ActionType'},\n }\n\n def __init__(self, *, action_type=None, **kwargs) -> None:\n super(Action, self).__init__(**kwargs)\n self.action_type = action_type\n","sub_path":"azext_keyvault/keyvault/models/action_py3.py","file_name":"action_py3.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"189275970","text":"from collections import Counter\nimport random\nimport logging\n\nfrom .spotify_oauth import (\n get_user_id, get_playlist_tracks, get_artist_top_tracks,\n create_new_playlist, add_tracks_to_playlist\n)\n\nlog = logging.getLogger(__name__)\n\n\ndef shuffle(playlist_id, playlist_name):\n log.info('Shuffling playlist')\n user_id = get_user_id()\n old_tracks = get_playlist_tracks(playlist_id)\n old_artist_ids = get_old_artists_ids(old_tracks)\n new_track_ids = get_new_track_ids(old_artist_ids, old_tracks)\n new_playlist = create_new_playlist(playlist_name, user_id)\n new_playlist_id = new_playlist['id']\n add_tracks_to_playlist(new_playlist_id, new_track_ids)\n return new_playlist\n\n\ndef get_old_artists_ids(tracks):\n log.info('Getting old artist ids')\n artist_ids = [track['artists'][0]['id'] for track in tracks]\n # Some artists have no ID - remove Nones from list\n artist_ids_nones_removed = list(filter(None, artist_ids))\n return artist_ids_nones_removed\n\n\ndef get_new_track_ids(old_artist_ids, old_tracks):\n log.info('Getting new track ids')\n new_tracks = []\n artist_count_dict = Counter(old_artist_ids)\n for artist_id in artist_count_dict:\n artist_top_tracks = get_artist_top_tracks(artist_id)\n random.shuffle(artist_top_tracks)\n num_tracks_to_add = artist_count_dict[artist_id]\n num_tracks_added = 0\n for track in artist_top_tracks:\n if not track_exists(track, old_tracks + new_tracks):\n new_tracks.append(track)\n num_tracks_added += 1\n if num_tracks_added == num_tracks_to_add:\n break\n return [track['uri'] for track in new_tracks]\n\n\ndef track_exists(track, existing_tracks):\n for existing_track in existing_tracks:\n if track['id'] == existing_track['id'] or substring_exists(track['name'], existing_track['name']):\n return True\n return False\n\n\ndef substring_exists(track_1, track_2):\n if len(track_1) > len(track_2):\n return track_2 in track_1\n elif len(track_2) > len(track_1):\n return track_1 in track_2\n return track_1 == track_2\n","sub_path":"app/shuffler.py","file_name":"shuffler.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"580820808","text":"'''\n程序:捕鱼达人\n作者:苏秦@小海豚科学馆公众号\n来源:图书《Python趣味编程:从入门到人工智能》\n'''\nimport pyglet\nfrom sprite_plus import SpritePlus\nfrom game_res import *\nfrom game_sprites import *\n\n#全局变量\nfishes, bullets, nets, coins = [], [], [], []\nscore, game_time, auto_play = 0, 0, False\n\n#创建游戏窗口、面板、大炮、标签等\ngame_win = pyglet.window.Window(width=1024, height=768, caption='捕鱼达人')\npanel = pyglet.sprite.Sprite(img=panel_img, x=130, y=0)\ncannon = SpritePlus(img=cannon_img, x=554, y=20)\ncannon.set_sprite_center()\nscore_label = pyglet.text.Label('000000', x=165, y=6)\nscore_label.font_name = 'Arial Black'\nscore_label.font_size = 18\n\n@game_win.event\ndef on_mouse_motion(x, y, dx, dy):\n '''大炮面向鼠标转动'''\n cannon.point(x, y)\n \n@game_win.event\ndef on_draw():\n '''绘制游戏画面'''\n bg_img.blit(0, 0)\n draw_sprites(fishes)\n draw_sprites(nets)\n draw_sprites(coins)\n panel.draw()\n score_label.draw()\n draw_sprites(bullets)\n cannon.draw()\n\ndef draw_sprites(sprites):\n '''绘制精灵'''\n for sprite in sprites:\n if sprite.visible:\n sprite.draw()\n \ndef fishes_control(dt):\n '''鱼群数量控制'''\n global game_time\n game_time += 1 * dt\n \n for fish_name, item in fishes_config.items():\n if item['alive'] == 0:\n num = item['max'] // 2\n elif item['alive'] < item['max'] // 3:\n num = item['max'] - item['alive']\n else:\n num = 0\n \n if fish_name == '蓝鲨' and int(game_time + 1) % 300 == 0:\n num = item['max'] - item['alive']\n \n if fish_name == '金鲨' and int(game_time + 1) % 480 == 0:\n num = item['max'] - item['alive']\n \n for i in range(num):\n fish = FishSprite(name=fish_name, item=item)\n item['alive'] += 1\n fishes.append(fish)\n \n #鱼群\n for fish in fishes:\n if fish.life > 0:\n fish.swim(dt)\n else:\n if not fish.is_capture:\n fish.is_capture = True\n #换成鱼扭动的造型\n fish.twist()\n #释放金币\n release_coin(fish.position, fish.score)\n else:\n #挣扎1秒后消失\n fish.check_dead(dt)\n \n if not fish.visible:\n #减少鱼的存活数\n fishes_config[fish.name]['alive'] -= 1\n fishes.remove(fish)\n fish.delete()\n\ndef fire_control(dt):\n '''捕鱼控制'''\n #炮弹\n for bullet in bullets:\n if bullet.visible:\n #移动炮弹\n bullet.fire_move(dt)\n if bullet.y < 150: continue\n #对每条有生命的鱼进行碰撞检测\n for fish in fishes:\n if fish.life <= 0: continue\n if bullet.touching(fish.position, fish.height // 2):\n #命中鱼减去生命值\n fish.life -= 1\n #让炮弹消失\n bullet.visible = False\n #抛撒渔网在炮弹处\n throw_fishing_net(fish.position) \n else:\n bullets.remove(bullet)\n bullet.delete()\n \n #渔网\n for net in nets:\n if net.visible:\n net.open(dt)\n else:\n nets.remove(net)\n net.delete()\n \n #硬币\n for coin in coins:\n if coin.visible:\n coin.move_down(dt)\n else:\n #加分\n global score\n score += coin.score\n score_label.text = '%06d' % score\n coins.remove(coin)\n coin.delete()\n\ndef fire_bullet():\n '''发射炮弹'''\n bullet = BulletSprite(x=cannon.x, y=cannon.y)\n bullet.rotation = cannon.rotation\n bullets.append(bullet)\n\ndef throw_fishing_net(pos):\n '''抛撒渔网'''\n net = NetSprite(x=pos[0], y=pos[1])\n nets.append(net)\n\ndef release_coin(pos, score):\n '''释放金币'''\n coin = CoinSprite(x=pos[0], y=pos[1], score=score)\n coins.append(coin)\n\n@game_win.event \ndef on_mouse_press(x, y, button, modifiers):\n '''大炮射击'''\n if button == pyglet.window.mouse.LEFT:\n fire_bullet()\n\n@game_win.event\ndef on_close():\n '''游戏窗口关闭'''\n player.next_source()\n \ndef music_control(dt):\n if not player.playing:\n player.queue(music)\n player.play()\n\nif __name__ == '__main__':\n '''程序入口'''\n pyglet.clock.schedule_interval(fire_control, 1/60)\n pyglet.clock.schedule_interval(fishes_control, 1/60)\n player = pyglet.media.Player()\n pyglet.clock.schedule_interval(music_control, 1)\n pyglet.app.run()\n","sub_path":"Python趣味编程:从入门到人工智能/第31课_捕鱼达人/试玩/捕鱼达人/捕鱼达人.py","file_name":"捕鱼达人.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"47182108","text":"import time\nfrom options.train_options import TrainOptions\nfrom data.data_loader import CreateDataLoader\nfrom models.models import create_model\nfrom util.visualizer import Visualizer\nimport os\nimport torch\nimport pdb; pdb.set_trace()\n\n# 放到最前面,好使,放到TrainOptions().parse()后边,不好使。\n#os.environ['CUDA_VISIBLE_DEVICES'] = '1,2'\n#print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\nopt = TrainOptions().parse()\n#os.environ['CUDA_VISIBLE_DEVICES'] = ','.join(str(x) for x in opt.gpu_ids)\n#print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n#torch.manual_seed(1337)\ncuda = torch.cuda.is_available()\nif cuda:\n #torch.cuda.manual_seed(1337)\n print(\"cuda devices: {} are ready\".format(opt.gpu_ids))\n \ndata_loader = CreateDataLoader(opt)\ndataset = data_loader.load_data()\ndataset_size = len(data_loader)\ntmp = dataset.dataset.__getitem__(0)\n#tmp['Box']\nprint('#training images = %d' % dataset_size)\n\nmodel = create_model(opt)\nvisualizer = Visualizer(opt)\ntotal_steps = 0\n \nfor epoch in range(opt.epoch_count, opt.niter + opt.niter_decay + 1):\n epoch_start_time = time.time()\n epoch_iter = 0\n\n for i, data in enumerate(dataset):\n iter_start_time = time.time()\n total_steps += opt.batchSize\n epoch_iter += opt.batchSize\n model.set_input(data)\n model.optimize_parameters()\n\n if total_steps % opt.display_freq == 0:\n visualizer.display_current_results(model.get_current_visuals(), epoch)\n\n if total_steps % opt.print_freq == 0:\n errors = model.get_current_errors()\n t = (time.time() - iter_start_time) / opt.batchSize\n visualizer.print_current_errors(epoch, epoch_iter, errors, t)\n if opt.display_id > 0:\n visualizer.plot_current_errors(epoch, float(epoch_iter)/dataset_size, opt, errors)\n\n if total_steps % opt.save_latest_freq == 0:\n print('saving the latest model (epoch %d, total_steps %d)' %\n (epoch, total_steps))\n model.save('latest')\n\n if epoch % opt.save_epoch_freq == 0:\n print('saving the model at the end of epoch %d, iters %d' %\n (epoch, total_steps))\n model.save('latest')\n model.save(epoch)\n\n print('End of epoch %d / %d \\t Time Taken: %d sec' %\n (epoch, opt.niter + opt.niter_decay, time.time() - epoch_start_time))\n model.update_learning_rate()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"304984654","text":"from math import *\nfrom itertools import accumulate\n\ninput_file = open('B-large.in.txt','r')\nraw_input = input_file.read()\n\nlines = raw_input.split('\\n')\n\nnum_cases = int(lines[0])\ncase_num = 1\n\noutput_text = ''\noutput_file = open('B.txt','w')\n\ndebug=0\n\n###################\n\nwhile case_num<=num_cases:\n cakes=lines[case_num]\n \n output_text += ('Case #'+str(case_num)+': ')\n if debug: print(cakes)\n\n num_cakes = len(cakes)\n orientation = '+'\n flips = 0\n for i in range(num_cakes-1,-1,-1):\n if cakes[i] != orientation:\n flips += 1\n orientation = cakes[i]\n output_text += str(flips)+'\\n'\n\n case_num += 1\n\n\nif debug: print('\\n'+output_text)\noutput_file.write(output_text)\ninput_file.close()\noutput_file.close()\n","sub_path":"solutions_5634697451274240_1/Python/jbryan/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"464448625","text":"import datetime\nimport json\nimport logging\nimport time\nfrom typing import Tuple, Any, Set\n\nimport random\nimport requests\nimport yaml\n\nlogging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)\n\nfrom src.session import Session\n\nURL = {\n 'root': 'https://www.instagram.com/',\n 'login': 'https://www.instagram.com/accounts/login/ajax/',\n 'logout': 'https://www.instagram.com/accounts/logout/',\n 'tag': 'https://www.instagram.com/explore/tags/',\n 'photo': 'https://www.instagram.com/p/',\n 'like': 'https://www.instagram.com/web/likes/%s/like/',\n 'unlike': 'https://www.instagram.com/web/likes/%s/unlike/',\n 'comment': 'https://www.instagram.com/web/comments/%s/add/',\n 'follow': 'https://www.instagram.com/web/friendships/%s/follow/',\n 'unfollow': 'https://www.instagram.com/web/friendships/%s/unfollow/',\n}\n\nrequests.packages.urllib3.disable_warnings()\nWAIT_SERVER_RESPONSE_TIME = 10 # how long to wait for a server response // 10s a 30s\n\n\nclass InstaBot:\n \"\"\"Main class of Instabot\"\"\"\n\n def __init__(self, config_path: str) -> None:\n start_time = datetime.datetime.now()\n username, password, tags, total_likes, likes_per_user = self.get_credentials(config_path)\n logging.info('InstaBot v0.1 started at %s:' % (start_time.strftime(\"%d.%m.%Y %H:%M\")))\n # gaussian distribution: mu = 0, sig = 100, round to nearest int\n self.total_likes = total_likes + self.iround(min(total_likes / 2, max(0, random.gauss(0, 100))))\n logging.info('InstaBot v0.1 will like %s photos in total' % self.total_likes)\n self.likes_per_user = likes_per_user # type: int\n self.liked_photos: Set = set()\n self.session = Session(username, password, logging)\n self.run(tags)\n self.session.logout()\n end_time = datetime.datetime.now()\n logging.info('InstaBot v0.1 stopped at %s:' % (end_time.strftime(\"%d.%m.%Y %H:%M\")))\n logging.info('InstaBot v0.1 took ' + str(end_time - start_time) + ' in total')\n\n @staticmethod\n def get_credentials(config: str) -> Tuple:\n config_data = yaml.safe_load(open(config, \"r\"))\n return (\n config_data['CREDENTIALS']['USERNAME'],\n config_data['CREDENTIALS']['PASSWORD'],\n config_data['TAGS'],\n config_data['TOTAL_LIKES'],\n config_data['LIKES_PER_USER']\n )\n\n @staticmethod\n def get_html(url: str) -> Any:\n time_between_requests = random.randint(2, 5)\n logging.info('Fetching ' + url)\n response = requests.get(url, verify=False, timeout=WAIT_SERVER_RESPONSE_TIME)\n html = response.text\n time.sleep(time_between_requests)\n return html\n\n @staticmethod\n def get_data_from_html(html) -> Any:\n try:\n finder_start = ''\n data_start = html.find(finder_start)\n data_end = html.find(finder_end, data_start + 1)\n json_str = html[data_start + len(finder_start):data_end]\n data = json.loads(json_str)\n return data\n except Exception as e:\n logging.info('Error parsing json string: ' + str(e))\n\n def get_recent_tag_photos(self, tag: str) -> Any:\n url = URL['tag'] + tag\n photos = list()\n min_likes = 5\n max_likes = 500\n min_comments = 1\n max_comments = 50\n try:\n html = self.get_html(url)\n data = self.get_data_from_html(html)\n # get data from recent posts only\n photos_json = list(data['entry_data']['TagPage'][0]['tag']['media']['nodes'])\n for photo_json in photos_json:\n photo_id = photo_json['code']\n likes = photo_json['likes']['count']\n comments = photo_json['comments']['count']\n likes_in_range = (min_likes <= likes <= max_likes)\n comments_in_range = (min_comments <= comments <= max_comments)\n if photo_id not in self.liked_photos and likes_in_range and comments_in_range:\n photos.append(photo_id)\n if len(photos) == 10:\n break\n # fill up rest of photos list with top posts, until list has 10 potential people to be liked\n if len(photos) < 10:\n photos_json = list(data['entry_data']['TagPage'][0]['tag']['top_posts']['nodes'])\n for photo_json in photos_json:\n photo_id = photo_json['code']\n likes = photo_json['likes']['count']\n comments = photo_json['comments']['count']\n likes_in_range = (min_likes <= likes <= max_likes)\n comments_in_range = (min_comments <= comments <= max_comments)\n if photo_id not in self.liked_photos and likes_in_range and comments_in_range:\n photos.append(photo_id)\n if len(photos) == 10:\n break\n except (KeyError, IndexError, TypeError) as e:\n logging.info('Error parsing url: ' + url + ' - ' + str(e))\n time.sleep(10)\n return photos\n\n def get_photo_owner(self, photo_id: str) -> Any:\n try:\n photo_url = URL['photo'] + photo_id\n html = self.get_html(photo_url)\n data = self.get_data_from_html(html)\n owner_name = data['entry_data']['PostPage'][0]['media']['owner']['username']\n return owner_name\n except (KeyError, IndexError, TypeError) as e:\n logging.info('Error parsing url:' + str(e))\n time.sleep(10)\n return None\n\n def get_recent_tag_owners(self, tag):\n photos_ids = self.get_recent_tag_photos(tag)\n owners_names = list()\n for photo_id in photos_ids:\n owner_name = self.get_photo_owner(photo_id)\n owners_names.append(owner_name)\n return owners_names\n\n # get owner recent photos only if he/she meets requirements\n def get_owner_recent_photos(self, owner_name: str):\n photos = list()\n min_followed_by = 300\n max_followed_by = 50000\n min_follows = 50\n max_follows = 7500 # instagram limit\n min_follow_ratio = 0.01\n max_follow_ratio = 8\n owner_url = URL['root'] + owner_name\n html = self.get_html(owner_url)\n try:\n data = self.get_data_from_html(html)\n follows = data['entry_data']['ProfilePage'][0]['user']['follows']['count']\n followed_by = data['entry_data']['ProfilePage'][0]['user']['followed_by']['count']\n if follows == 0:\n follows = 1\n follow_ratio = followed_by / follows\n follows_in_range = (min_follows <= follows <= max_follows)\n if (follows_in_range and\n followed_by >= min_followed_by and followed_by <= max_followed_by and\n follow_ratio >= min_follow_ratio and follow_ratio <= max_follow_ratio):\n logging.info('Fetching user [' + owner_name + '] photo urls. (Follows: ' + str(\n follows) + ', Followed By: ' + str(followed_by) + ', Ratio: ' + str(follow_ratio) + ')')\n photos_json = data['entry_data']['ProfilePage'][0]['user']['media']['nodes']\n log_str = 'Photo codes: '\n for i, photo_json in enumerate(photos_json):\n if i == self.likes_per_user:\n break\n photo_id = photo_json['id']\n photo_code = photo_json['code']\n if photo_id not in self.liked_photos:\n photos.append(photo_id)\n log_str += photo_code + ' '\n logging.info(log_str)\n logging.info('Photo IDs: ' + str(photos))\n else:\n logging.info('User [' + owner_name + '] doesn\\'t meet requirements. (Follows: ' + str(\n follows) + ', Followed By: ' + str(followed_by) + ')')\n except (KeyError, IndexError, TypeError) as e:\n logging.info('Error parsing url: ' + owner_url + ' - ' + str(e))\n time.sleep(10)\n return photos\n\n def get_photos_to_like_from_tag(self, tag):\n photos_to_like = list()\n recent_photos = self.get_recent_tag_photos(tag)\n for recent_photo in recent_photos:\n owner_name = self.get_photo_owner(recent_photo)\n if owner_name is not None:\n photos_to_like += self.get_owner_recent_photos(owner_name)\n return photos_to_like\n\n def get_photos_to_like(self, tags):\n photos_to_like = list()\n for tag in tags:\n logging.info('Finding photos with tag: #' + tag)\n photos_to_like += self.get_photos_to_like_from_tag(tag)\n logging.info('There are ' + str(len(photos_to_like)) + ' photos in the like queue')\n return photos_to_like\n\n def like(self, photo_id):\n if self.session.login_status:\n url = (URL['like'] % photo_id)\n try:\n status = self.session.post(url)\n except Exception as e:\n status = 0\n logging.info(\"Like failed: \" + e + url)\n return status\n\n @staticmethod\n def iround(x):\n return int(round(x) - .5) + (x > 0) # round a number to the nearest integer\n\n def run(self, tags):\n likes = 0\n error_400 = 0\n error_400_to_ban = 3\n ban_sleep_time = 2 * 60 * 60\n while True:\n like_queue = self.get_photos_to_like(tags)\n if not self.session.login_status:\n self.session.login()\n while len(like_queue) > 0:\n logging.info('There are ' + str(len(like_queue)) + ' photos in the like queue')\n likes_per_cycle = self.iround(min(20, max(0, random.gauss(10,\n 2)))) # gaussian distribution: mu = 10, sig = 2, round to nearest int\n like_next, like_queue = like_queue[:likes_per_cycle], like_queue[likes_per_cycle:]\n for photo_id in like_next:\n status = self.like(photo_id)\n if status == 200:\n self.liked_photos.add(photo_id)\n likes += 1\n if likes > self.total_likes:\n logging.info('Success! Reached total number of likes. InstaBot is shutting down...')\n return\n error_400 = 0\n logging.info('Total likes: ' + str(likes))\n elif status == 400:\n if error_400 < error_400_to_ban:\n error_400 += 1\n logging.info('Error 400 - # ' + str(error_400))\n else:\n logging.info('Error 400 - # ' + str(\n error_400) + '- You might have been banned. InstaBot will sleep for 2 hours...')\n time.sleep(ban_sleep_time)\n # sleep after one like (from 2s to 5s)\n wait = random.randint(1, 3)\n time.sleep(wait)\n # sleep after liking cycle (from 25s to 50s)\n wait = random.randint(10, 20)\n logging.info('Finished liking cycle. Sleeping for ' + str(wait) + ' seconds...')\n time.sleep(wait)\n # sleep after liking all tags (from 5min to 15min)\n wait = random.randint(1, 5) * 60\n logging.info('Finished liking tags. Sleeping for ' + str(int(wait / 60)) + ' minutes...')\n time.sleep(wait)\n","sub_path":"src/instabot.py","file_name":"instabot.py","file_ext":"py","file_size_in_byte":11863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"40615494","text":"# -*- coding: utf-8 -*-\r\n\r\ninfile = open('train.csv','r')\r\noutfile = open('train_nomissing.csv','w')\r\nline = infile.readline()\r\nmaxid = 0\r\nfor line in infile:\r\n line = line.split(',')\r\n l = len(line)\r\n for i in range(l): \r\n if line[i] == '':\r\n break\r\n if i == l-1:\r\n outfile.write(','.join(line))\r\ninfile.close()\r\noutfile.close()\r\n","sub_path":"MLCLASS_Cognitio_project_fall15/removemissing.py","file_name":"removemissing.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"218613918","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: build/bdist.macosx-10.14-x86_64/egg/a3cosmos_gas_evolution/Common_Python_Code/setup_matplotlib.py\n# Compiled at: 2019-07-07 18:47:11\n# Size of source mod 2**32: 2785 bytes\nimport os, sys\nfrom matplotlib import pyplot as plt\nfrom matplotlib import ticker\nfrom matplotlib.ticker import MultipleLocator, AutoMinorLocator\nfrom matplotlib import font_manager\nimport matplotlib as mpl, numpy as np\n\ndef setup_matplotlib():\n if os.path.isdir(os.path.expanduser('~') + os.sep + 'Library' + os.sep + 'Fonts'):\n font_dirs = [\n os.path.expanduser('~') + os.sep + 'Library' + os.sep + 'Fonts']\n font_files = font_manager.findSystemFonts(fontpaths=font_dirs)\n font_list = font_manager.createFontList(font_files)\n font_manager.fontManager.ttflist.extend(font_list)\n font_manager.findfont('NGC', rebuild_if_missing=True)\n else:\n mpl.rcParams['font.family'] = 'NGC'\n mpl_version = np.array(mpl.__version__.split('.')).astype(int)\n if not (mpl_version[0] > 3 or mpl_version[0]) >= 3 or mpl_version[1] >= 1:\n mpl.rcParams['text.latex.preamble'] = '\\\\usepackage{amsmath}'\n mpl.rcParams['text.latex.preamble'] += '\\n'\n mpl.rcParams['text.latex.preamble'] += '\\\\makeatletter \\\\newcommand*{\\\\rom}[1]{\\\\expandafter\\\\@slowromancap\\\\romannumeral #1@} \\\\makeatother'\n else:\n mpl.rcParams['text.latex.preamble'] = [\n '\\\\usepackage{amsmath}']\n mpl.rcParams['text.latex.preamble'].append('\\\\makeatletter \\\\newcommand*{\\\\rom}[1]{\\\\expandafter\\\\@slowromancap\\\\romannumeral #1@} \\\\makeatother')\n mpl.rcParams['axes.labelsize'] = '16'\n mpl.rcParams['axes.grid'] = True\n mpl.rcParams['axes.axisbelow'] = True\n mpl.rcParams['xtick.direction'] = 'in'\n mpl.rcParams['ytick.direction'] = 'in'\n mpl.rcParams['xtick.minor.visible'] = True\n mpl.rcParams['ytick.minor.visible'] = True\n mpl.rcParams['xtick.labelsize'] = '13'\n mpl.rcParams['ytick.labelsize'] = '13'\n mpl.rcParams['xtick.top'] = True\n mpl.rcParams['ytick.right'] = True\n mpl.rcParams['grid.linestyle'] = '--'\n mpl.rcParams['grid.linewidth'] = 0.25\n mpl.rcParams['grid.alpha'] = 0.8\n mpl.rcParams['legend.fontsize'] = '12'\n mpl.rcParams['legend.borderaxespad'] = 0.2","sub_path":"pycfiles/a3cosmos_gas_evolution-1.0.0-py3.7/setup_matplotlib.cpython-37.py","file_name":"setup_matplotlib.cpython-37.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"150060994","text":"import logging\nimport multiprocessing\nimport numbers\nimport os\nimport time\n\nfrom queue import Queue\nfrom queue import LifoQueue\n\nfrom ramp_database.tools.submission import get_submissions\nfrom ramp_database.tools.submission import get_submission_by_id\nfrom ramp_database.tools.submission import get_submission_state\n\nfrom ramp_database.tools.submission import set_bagged_scores\nfrom ramp_database.tools.submission import set_predictions\nfrom ramp_database.tools.submission import set_time\nfrom ramp_database.tools.submission import set_scores\nfrom ramp_database.tools.submission import set_submission_error_msg\nfrom ramp_database.tools.submission import set_submission_state\n\nfrom ramp_database.tools.leaderboard import update_all_user_leaderboards\nfrom ramp_database.tools.leaderboard import update_leaderboards\n\nfrom ramp_database.utils import session_scope\n\nfrom ramp_utils import generate_ramp_config\nfrom ramp_utils import generate_worker_config\nfrom ramp_utils import read_config\n\nfrom .local import CondaEnvWorker\n\nlogger = logging.getLogger('RAMP-DISPATCHER')\n\n\nclass Dispatcher:\n \"\"\"Dispatcher which schedule workers and communicate with the database.\n\n The dispatcher uses two queues: a queue containing containing the workers\n which should be launched and a queue containing the workers which are being\n processed. The latter queue has a limited size defined by ``n_workers``.\n Note that these workers can run simultaneously.\n\n Parameters\n ----------\n config : dict or str\n A configuration YAML file containing the inforation about the database.\n event_config : dict or str\n A RAMP configuration YAML file with information regarding the worker\n and the ramp event.\n worker : Worker, default=CondaEnvWorker\n The type of worker to launch. By default, we launch local worker which\n uses ``conda``.\n n_workers : int, default=1\n Maximum number of workers which can run submissions simultaneously.\n n_threads : None or int\n The number of threads that each worker can use. By default, there is no\n limit imposed.\n hunger_policy : {None, 'sleep', 'exit'}\n Policy to apply in case that there is no anymore workers to be\n processed:\n\n * if None: the dispatcher will work without interruption;\n * if 'sleep': the dispatcher will sleep for 5 seconds before to check\n for new submission;\n * if 'exit': the dispatcher will stop after collecting the results of\n the last submissions.\n \"\"\"\n def __init__(self, config, event_config, worker=None, n_workers=1,\n n_threads=None, hunger_policy=None):\n self.worker = CondaEnvWorker if worker is None else worker\n self.n_workers = (max(multiprocessing.cpu_count() + 1 + n_workers, 1)\n if n_workers < 0 else n_workers)\n self.hunger_policy = hunger_policy\n # init the poison pill to kill the dispatcher\n self._poison_pill = False\n # create the different dispatcher queues\n self._awaiting_worker_queue = Queue()\n self._processing_worker_queue = LifoQueue(maxsize=self.n_workers)\n self._processed_submission_queue = Queue()\n # split the different configuration required\n if (isinstance(config, str) and\n isinstance(event_config, str)):\n self._database_config = read_config(config,\n filter_section='sqlalchemy')\n self._ramp_config = generate_ramp_config(event_config, config)\n else:\n self._database_config = config['sqlalchemy']\n self._ramp_config = event_config['ramp']\n self._worker_config = generate_worker_config(event_config, config)\n # set the number of threads for openmp, openblas, and mkl\n self.n_threads = n_threads\n if self.n_threads is not None:\n if not isinstance(self.n_threads, numbers.Integral):\n raise TypeError(\n \"The parameter 'n_threads' should be a positive integer. \"\n \"Got {} instead.\".format(repr(self.n_threads))\n )\n for lib in ('OMP', 'MKL', 'OPENBLAS'):\n os.environ[lib + '_NUM_THREADS'] = str(self.n_threads)\n\n def fetch_from_db(self, session):\n \"\"\"Fetch the submission from the database and create the workers.\"\"\"\n submissions = get_submissions(session,\n self._ramp_config['event_name'],\n state='new')\n if not submissions:\n logger.info('No new submissions fetch from the database')\n return\n for submission_id, submission_name, _ in submissions:\n # do not train the sandbox submission\n submission = get_submission_by_id(session, submission_id)\n if not submission.is_not_sandbox:\n continue\n # create the worker\n worker = self.worker(self._worker_config, submission_name)\n set_submission_state(session, submission_id, 'sent_to_training')\n self._awaiting_worker_queue.put_nowait((worker, (submission_id,\n submission_name)))\n logger.info('Submission {} added to the queue of submission to be '\n 'processed'.format(submission_name))\n\n def launch_workers(self, session):\n \"\"\"Launch the awaiting workers if possible.\"\"\"\n while (not self._processing_worker_queue.full() and\n not self._awaiting_worker_queue.empty()):\n worker, (submission_id, submission_name) = \\\n self._awaiting_worker_queue.get()\n logger.info('Starting worker: {}'.format(worker))\n worker.setup()\n worker.launch_submission()\n set_submission_state(session, submission_id, 'training')\n self._processing_worker_queue.put_nowait(\n (worker, (submission_id, submission_name)))\n logger.info('Store the worker {} into the processing queue'\n .format(worker))\n if self._processing_worker_queue.full():\n logger.info('The processing queue is full. Waiting for a worker to'\n ' finish')\n\n def collect_result(self, session):\n \"\"\"Collect result from processed workers.\"\"\"\n try:\n workers, submissions = zip(\n *[self._processing_worker_queue.get()\n for _ in range(self._processing_worker_queue.qsize())]\n )\n except ValueError:\n logger.info('No workers are currently waiting or processed.')\n if self.hunger_policy == 'sleep':\n time.sleep(5)\n elif self.hunger_policy == 'exit':\n self._poison_pill = True\n return\n for worker, (submission_id, submission_name) in zip(workers,\n submissions):\n if worker.status == 'running':\n self._processing_worker_queue.put_nowait(\n (worker, (submission_id, submission_name)))\n logger.info('Worker {} is still running'.format(worker))\n time.sleep(0)\n else:\n logger.info('Collecting results from worker {}'.format(worker))\n returncode, stderr = worker.collect_results()\n set_submission_state(\n session, submission_id,\n 'tested' if not returncode else 'training_error'\n )\n set_submission_error_msg(session, submission_id, stderr)\n self._processed_submission_queue.put_nowait(\n (submission_id, submission_name))\n worker.teardown()\n\n def update_database_results(self, session):\n \"\"\"Update the database with the results of ramp_test_submission.\"\"\"\n while not self._processed_submission_queue.empty():\n submission_id, submission_name = \\\n self._processed_submission_queue.get_nowait()\n if 'error' in get_submission_state(session, submission_id):\n update_leaderboards(session, self._ramp_config['event_name'])\n update_all_user_leaderboards(session,\n self._ramp_config['event_name'])\n logger.info('Skip update for {} due to failure during the '\n 'processing'.format(submission_name))\n continue\n logger.info('Update the results obtained on each fold for '\n '{}'.format(submission_name))\n path_predictions = os.path.join(\n self._worker_config['predictions_dir'], submission_name\n )\n set_predictions(session, submission_id, path_predictions)\n set_time(session, submission_id, path_predictions)\n set_scores(session, submission_id, path_predictions)\n set_bagged_scores(session, submission_id, path_predictions)\n set_submission_state(session, submission_id, 'scored')\n update_leaderboards(session, self._ramp_config['event_name'])\n update_all_user_leaderboards(session,\n self._ramp_config['event_name'])\n\n def launch(self):\n \"\"\"Launch the dispatcher.\"\"\"\n logger.info('Starting the RAMP dispatcher')\n with session_scope(self._database_config) as session:\n logger.info('Open a session to the database')\n try:\n while not self._poison_pill:\n self.fetch_from_db(session)\n self.launch_workers(session)\n self.collect_result(session)\n self.update_database_results(session)\n finally:\n # reset the submissions to 'new' in case of error or unfinished\n # training\n submissions = get_submissions(session,\n self._ramp_config['event_name'],\n state=None)\n for submission_id, _, _ in submissions:\n submission_state = get_submission_state(session,\n submission_id)\n if submission_state in ('training', 'send_to_training'):\n set_submission_state(session, submission_id, 'new')\n logger.info('Dispatcher killed by the poison pill')\n","sub_path":"ramp-engine/ramp_engine/dispatcher.py","file_name":"dispatcher.py","file_ext":"py","file_size_in_byte":10634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"481465394","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n# dropout example\n\nclass convNet(nn.Module):\n def __init__(self):\n super(convNet, self).__init__()\n self.layer1 = nn.Sequential(\n nn.BatchNorm2d(3),\n nn.ReLU(),\n nn.Conv2d(3, 32, kernel_size=3, stride=1, padding=1)\n )\n self.layer2 = nn.Sequential(\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.Conv2d(32, 128, kernel_size=3, stride=2, padding=1),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n )\n self.layer3 = nn.Sequential(\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(128, 64, kernel_size=3, stride=2, padding=1),\n # nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n )\n self.layer4 = nn.Sequential(\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(64, 32, kernel_size=3, stride=2, padding=1),\n # nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n )\n self.layer5 = nn.Sequential(\n nn.BatchNorm2d(32),\n nn.ReLU(),\n nn.Conv2d(32, 32, kernel_size=3, stride=1, padding=1),\n nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n )\n # self.conv2_drop = nn.Dropout2d(p=0.5)\n self.fc1 = nn.Linear(32*3*3, 64)\n self.fc2 = nn.Linear(64, 2)\n # self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = self.layer3(out)\n out = self.layer4(out)\n out = self.layer5(out)\n # out = self.conv2_drop(out)\n # print('cnn:', out.size())\n out = out.view(out.size(0), -1)\n # print('fc:', out.size())\n out = F.relu(self.fc1(out))\n # x = F.dropout(x, training=self.training)\n out = self.fc2(out)\n # out = self.sigmoid(out)\n return out\n\n\nif __name__ == '__main__':\n from torch.autograd import Variable\n\n model = convNet()\n data = Variable(torch.randn(3,2,75,75))\n result = model(data)\n print('data: ', data.size())\n print('result: ', result.size())","sub_path":"python/ice/convNet.py","file_name":"convNet.py","file_ext":"py","file_size_in_byte":2160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"308459519","text":"#! python3\r\n#@author: Jaedan Willis\r\n\r\nimport os\r\nimport sys\r\nimport shutil\r\nimport argparse\r\nimport subprocess\r\nfrom tkinter import *\r\nfrom file import File\r\nfrom icon import Icon\r\nfrom ain1 import Ain1\r\nfrom merge import Merge\r\nfrom tkinter import ttk\r\nfrom hidden import Hidden\r\nfrom inicon import Inicon\r\nfrom inmerge import Inmerge\r\nfrom regcheck import RegCheck\r\nfrom tkinter import filedialog\r\nfrom tkinter import messagebox\r\nfrom mergeicon import MergeIcon\r\n\r\nclass Layout(object):\r\n\t\"\"\"\"this class will convert/compile\r\n\tany .py/.pyw script to an executable\r\n\tand also allows the user to select three(3)\r\n\tdifferent options\"\"\"\r\n\r\n\tdef __init__(self, master):\r\n\t\t# initalize function\r\n\t\tself.master = master\r\n\t\tself.master.update_idletasks()\r\n\t\twidth = 362\r\n\t\theight =260\r\n\t\tx = (self.master.winfo_screenwidth() // 2) - (width // 2)\r\n\t\ty = (self.master.winfo_screenheight() // 2) - (height // 2)\r\n\t\tself.master.geometry('{}x{}+{}+{}'.format(width, height, x, y))\r\n\t\tself.master.deiconify()\r\n\t\tself.master.resizable(False,False)\r\n\t\tself.master.iconbitmap('assets\\\\icon\\\\HPControl.ico')\r\n\t\tself.master.title('OGT PyTuExe (v1.1.0)')\r\n\r\n\t\t# claasing a class to check to see if the user already see the important message,if not go to the important_note function\r\n\t\tRegCheck(self.master)\r\n\r\n\t\t#styling the gui\r\n\t\tself.red_black = '#321d1d'\r\n\t\tself.tint_red = '#ff3232'\r\n\t\tself.master.configure(background=self.red_black)\r\n\t\tself.style = ttk.Style()\r\n\t\tself.style.configure('TFrame',background=self.red_black)\r\n\t\tself.style.configure('TButton',background=self.red_black)\r\n\t\tself.style.configure('Convert.TButton',foreground=self.tint_red)\r\n\t\tself.style.configure('Browse.TButton',foreground=self.tint_red)\r\n\t\tself.style.configure('TLabel',foreground='white',background=self.red_black,font=('Arial',11,'italic'))\r\n\t\tself.style.configure('TCheckbutton',background=self.red_black,foreground='white')\r\n\t\tself.style.configure('Header.TLabel',foreground=self.tint_red,font=('san-serif',40,'bold','italic'))\r\n\r\n\t\t# header frame\r\n\t\tself.header_frame = ttk.Frame(self.master)\r\n\t\tself.header_frame.pack(fill=X,padx=2,pady=2)\r\n\t\tself.header_frame.config(padding=((1,0)),relief=RAISED)\r\n\r\n\t\t# header lable\r\n\t\tself.header_label = ttk.Label(self.header_frame,text='OGT PyTuExe',style='Header.TLabel')\r\n\t\tself.header_label.grid(row=0,column=0,pady=5,sticky='sw')\r\n\r\n\t\t# pytoexe frame\r\n\t\tself.pytoexe_frame = ttk.Frame(self.master)\r\n\t\tself.pytoexe_frame.pack(fill=X,padx=2)\r\n\t\t#self.pytoexe_frame.config(relief=GROOVE)\r\n\r\n\t\t# getfilename settings\r\n\t\tself.pytoexe_lable = ttk.Label(self.pytoexe_frame,text='Filename:')\r\n\t\tself.pytoexe_lable.grid(row=0,column=0,pady=5,padx=5,stick='w')\r\n\r\n\t\tself.entry_var = StringVar()\r\n\t\tself.pytoexe_list_entry = Entry(self.pytoexe_frame,width=30,textvariable=self.entry_var)\r\n\t\tself.pytoexe_list_entry.grid(row=1,column=1,sticky='sw',pady=5)\r\n\t\tself.pytoexe_list_entry.insert(0,\"Your Script Goes Here\")\r\n\r\n\t\t# browse button\r\n\t\tself.file_browse_button = ttk.Button(self.pytoexe_frame,text='Browse',command=self.file_browse,style='Browse.TButton')\r\n\t\tself.file_browse_button.grid(row=1,column=2,padx=5)\r\n\r\n\t\t# icon settings\r\n\t\tself.icon_lable = ttk.Label(self.pytoexe_frame,text='Icon File:')\r\n\t\tself.icon_lable.grid(row=3,column=0,sticky='w',pady=5,padx=5)\r\n\r\n\t\tself.icon = StringVar()\r\n\t\tself.icon_entry = ttk.Entry(self.pytoexe_frame,width=30,textvariable=self.icon)\r\n\t\tself.icon_entry.grid(row=4,column=1,sticky='sw',pady=5)\r\n\t\tself.icon_entry.insert(0,\"Your Icon Goes Here\")\r\n\r\n\t\tself.icon_browse_button = ttk.Button(self.pytoexe_frame,text='Browse',command=self.icon_browse,style='Browse.TButton')\r\n\t\tself.icon_browse_button.grid(row=4,column=2,padx=5)\r\n\r\n\t\t# invisable checkbox\r\n\t\tself.invisbale_button = IntVar()\r\n\t\tself.invisible_checkbox = ttk.Checkbutton(self.pytoexe_frame,text='Invisable',variable=self.invisbale_button)\r\n\t\tself.invisible_checkbox.grid(row=6,column=0,padx=5)\r\n\r\n\t\t# merge checkbox\r\n\t\tself.merge_button = IntVar()\r\n\t\tself.merge_checkbox = ttk.Checkbutton(self.pytoexe_frame,text='Merge',variable=self.merge_button)\r\n\t\tself.merge_checkbox.grid(row=6,column=1)\r\n\t\tself.merge_button.set(1)\r\n\r\n\t\t# con checkbox\r\n\t\tself.icon_button = IntVar()\r\n\t\tself.icon_checkbox = ttk.Checkbutton(self.pytoexe_frame,text='Icon',variable=self.icon_button)\r\n\t\tself.icon_checkbox.grid(row=6,column=2)\r\n\r\n\t\t# convert button\r\n\t\tself.convert_button = ttk.Button(self.pytoexe_frame,text='CONVERT',command=self.verify_fileds,style='Convert.TButton')\r\n\t\tself.convert_button.grid(row=7,column=1,pady=5)\r\n\r\n\tdef file_browse(self):\r\n\t\t# this funtion allows you to browse for an .py or .pyw file\r\n\t\tfile = File.browse(self.master)\r\n\t\tself.pytoexe_list_entry.delete(0,'end')\r\n\t\tself.pytoexe_list_entry.insert(0,file)\r\n\r\n\r\n\tdef icon_browse(self):\r\n\t\ticon = Icon.browse(self.master)\r\n\t\tself.icon_entry.delete(0,'end')\r\n\t\tself.icon_entry.insert(0,icon)\r\n\r\n\tdef verify_fileds(self):\r\n\t\t# this funtion will check to\r\n\t\t# see if the fields or check\r\n\t\t# or not if not raise an erro message\r\n\r\n\t\tinvisbale_button = self.invisbale_button.get()\r\n\t\tmerge_button = self.merge_button.get()\r\n\t\ticon_button = self.icon_button.get()\r\n\t\tfilename = self.entry_var.get()\r\n\t\ticon = self.icon.get()\r\n\t\tif filename.endswith(('.py','.pyw')):\r\n\t\t\tif invisbale_button == True and merge_button == True and icon_button == True:\r\n\t\t\t\tif icon.endswith('.ico'):\r\n\t\t\t\t\t# Calling the ain1 class\r\n\t\t\t\t\ta1 = Ain1(self.master,filename,icon)\r\n\t\t\t\t\ta1.merge()\r\n\t\t\t\telse:\r\n\t\t\t\t\tmessagebox.showerror(parent=self.master,title='Icon Error',message=\"Icon file should end with a (.ico) extension\")\r\n\t\t\telif invisbale_button == 1 and merge_button == 1:\r\n\t\t\t\t# callign the inmerge class\r\n\t\t\t\tinmerge = Inmerge(self.master,filename)\r\n\t\t\t\tinmerge.merge()\r\n\t\t\telif invisbale_button == True and icon_button == True:\r\n\t\t\t\tif icon.endswith('.ico'):\r\n\t\t\t\t\t#calling the inicon class\r\n\t\t\t\t\tinicon = Inicon(self.master,filename,icon)\r\n\t\t\t\t\tinicon.merge()\r\n\t\t\t\telse:\r\n\t\t\t\t\tmessagebox.showerror(parent=self.master,title='Icon Error',message=\"Icon file should end with a (.ico) extension\")\r\n\t\t\telif merge_button == True and icon_button == True:\r\n\t\t\t\tif icon.endswith('.ico'):\r\n\t\t\t\t\t#calling the mergeicon class\r\n\t\t\t\t\tmergeicon = MergeIcon(self.master,filename,icon)\r\n\t\t\t\t\tmergeicon.merge()\r\n\t\t\t\telse:\r\n\t\t\t\t\tmessagebox.showerror(parent=self.master,title='Icon Error',message=\"Icon file should end with a (.ico) extension\")\r\n\t\t\telif invisbale_button == True:\r\n\t\t\t\t#calling the hidden class\r\n\t\t\t\thidden = Hidden(self.master,filename)\r\n\t\t\t\thidden.merge()\r\n\t\t\telif merge_button == True:\r\n\t\t\t\t#calling the merge class\r\n\t\t\t\tmerge = Merge(self.master,filename)\r\n\t\t\t\tmerge.merge()\r\n\t\t\telif icon_button == True:\r\n\t\t\t\tmessagebox.showerror(parent=self.master,title='Icon Error',message=\"Icon cannot be merged alone\")\r\n\t\t\telse:\r\n\t\t\t\tmessagebox.showerror(parent=self.master,title='Invalid Error',message=\"Please atleast select merge\")\r\n\t\telse:\r\n\t\t\tmessagebox.showerror(parent=self.master,title='Filename Error',message=\"File shoud end with a (.py or .pyw) extention.\")\r\n\r\n# main part of the program\r\ndef main():\r\n\tparser = argparse.ArgumentParser()\r\n\tparser.add_argument('-bs','--bootstate',help='Start the program if started from another file')\r\n\targs = parser.parse_args()\r\n\tif args.bootstate == \"8WFEHBN9EFM0EJF!M?SWE0NMSVO*9WEHFWEF9EWMF*0E#WSJD0FEWF0VSD9EWFMWEDMV-EWIFVSFEW-F9UEWVMWE-FWE\":\r\n\t\tgui = Tk()\r\n\t\tpytoexe = Layout(gui)\r\n\t\tgui.mainloop()\r\n\telse:\r\n\t\tos._exit(1)\r\nif __name__ == '__main__':\r\n\tmain()\r\n","sub_path":"lib/mpl.py","file_name":"mpl.py","file_ext":"py","file_size_in_byte":7457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"213755188","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport sys\n\nfrom . import objects\nfrom .utils import read_file, write_file, expand_curly, make_dirs, abspathjoin\n\n \nDEFAULT_PAGE_TEMPLATE = \"page\"\n\nclass Context:\n def __init__(self, source_dir, theme_dir=None):\n self.source_dir = os.path.abspath(source_dir)\n self.parser = None\n self.load_config()\n self.theme_dir = theme_dir if theme_dir else abspathjoin(source_dir, \"theme\")\n \n \n def load_config(self):\n sys.path.insert(0, self.source_dir)\n import webgenconf as config\n sys.path.pop(0)\n self.config = config\n self.output_path = abspathjoin(self.source_dir, config.OUTPUT_PATH)\n self.static_path = abspathjoin(self.output_path, \"static\")\n self.content_dir = abspathjoin(self.source_dir, config.CONTENT_DIR)\n self.pages_dir = abspathjoin(self.content_dir, config.PAGES_SUBDIR)\n self.static_subdirs = config.STATIC_SUBDIRS\n self.parser = None\n config_meta_keys = \"SITE_URL\", \"SITE_NAME\"\n self.global_meta = {key.lower(): getattr(config, key) for key in config_meta_keys}\n self.constants = getattr(config, \"CONSTANTS\", {})\n if self.constants:\n self.global_meta.update(self.constants)\n self.interlinks = getattr(config, \"INTERLINKS\", {})\n self.blobs = {}\n \n def collect_data(self):\n self.collect_pages()\n \n def collect_pages(self):\n # TODO: hardcoded md\n self.pages = {p.input_file: p for p in objects.list_pages(self.pages_dir, \".md\")}\n \n def parse_data(self):\n self.parse_pages()\n \n def parse_pages(self):\n for page in self.pages.values():\n data = read_file(page.input_file)\n if not page.fresh:\n self.parse_page(page, data)\n \n def parse_page(self, page, data):\n data = self.parser.process_meta(self, data, self.global_meta)\n page.meta = meta = self.parser.meta\n page.title = meta.get(\"title\", page.basename)\n page.description = meta.get(\"description\")\n page.image = meta.get(\"image\")\n \n url_template = meta.get(\"filename\", meta.get(\"save_as\", self.config.PAGE_URL))\n page.url = expand_curly(url_template, page, meta)\n page.output_file = abspathjoin(self.output_path, page.url)\n \n dirpath = os.path.dirname(page.output_file)\n meta[\"root_dir\"] = os.path.relpath(self.output_path, dirpath) or \".\"\n meta[\"static_dir\"] = os.path.relpath(self.static_path, dirpath) or \".\"\n \n page.content = self.parser.process_body(self, data)\n self.beautifly(page)\n\n def beautifly(self, page):\n from bs4 import BeautifulSoup\n soup = BeautifulSoup(page.content, 'html.parser')\n self.extract_toc(page, soup)\n self.bootstrap_admonition(page, soup)\n self.replace_interlinks(page, soup)\n self.replace_abslinks(page, soup)\n self.replace_pelican_links(page, soup)\n page.content = soup.decode()\n \n def extract_toc(self, page, soup):\n # if it is a Markdown file\n toc = soup.find('div', class_='toc')\n # else if it is a reST file\n # elif extension in readers.RstReader.file_extensions:\n # toc = soup.find('div', class_='contents topic')\n if toc:\n toc.extract()\n page.toc = toc.decode()\n else:\n page.toc = None\n \n def bootstrap_admonition(self, page, soup):\n ADMONITION_CLASS = 'admonition'\n ADMONITION_TITLE_CLASS = 'admonition-title'\n PANEL_CLASS = \"panel\"\n PANEL_HEADING_CLASS = \"panel-heading\"\n panels = soup.find_all('div', class_=ADMONITION_CLASS)\n if panels:\n for panel in panels:\n classes = panel[\"class\"]\n index = classes.index(ADMONITION_CLASS)\n classes[index] = PANEL_CLASS\n classes[index + 1] = \"{}-{}\".format(PANEL_CLASS, classes[index + 1])\n \n title = panel.find(\"p\", class_=ADMONITION_TITLE_CLASS)\n panel_contents = panel.contents[:]\n panel.clear()\n \n if title:\n classes = title[\"class\"]\n try:\n index = classes.index(ADMONITION_TITLE_CLASS)\n classes[index] = PANEL_HEADING_CLASS\n except ValueError as e:\n print(e)\n \n index = panel_contents.index(title)\n panel_contents = panel_contents[index + 1:]\n panel.append(title)\n \n body = soup.new_tag(\"div\")\n body[\"class\"] = [\"panel-body\"]\n panel.append(body)\n \n for i in panel_contents:\n body.append(i)\n \n def replace_interlinks(self, page, soup):\n self.interlinks[\"this\"] = page.meta[\"root_dir\"] + \"/\"\n INTERLINK_RE = re.compile(\"(.+?)>\")\n for link in soup.find_all(href=INTERLINK_RE):\n url = link.get('href')\n m = INTERLINK_RE.search(url)\n name = m.group(1)\n link['href'] = self.interlinks[name] + url[len(name) + 1:]\n for elm in soup.find_all(src=INTERLINK_RE):\n url = elm.get('src')\n m = INTERLINK_RE.search(url)\n name = m.group(1)\n elm['src'] = self.interlinks[name] + url[len(name) + 1:]\n \n def replace_abslinks(self, page, soup):\n ABSLINK_RE = re.compile(\"^:.+\")\n for elm in soup.find_all(href=ABSLINK_RE):\n elm['href'] = page.meta[\"root_dir\"] + \"/\" + elm.get('href')[1:]\n for elm in soup.find_all(src=ABSLINK_RE):\n elm['src'] = page.meta[\"root_dir\"] + \"/\" + elm.get('src')[1:]\n \n def replace_pelican_links(self, page, soup):\n page.meta[\"root_dir\"] + \"/\"\n PELINK_RE = re.compile(\"\\{filename\\}(\\.?)(.+)\\.md(.*)\")\n for link in soup.find_all(href=PELINK_RE):\n url = link.get('href')\n m = PELINK_RE.search(url)\n dot = m.group(1)\n filename = m.group(2)\n rest = m.group(3)\n if dot:\n link['href'] = dot + filename + \".html\" + rest\n else:\n link['href'] = page.meta[\"root_dir\"] + \"/\" + filename + \".html\" + rest\n\n def generate_data(self):\n self.generate_pages()\n \n def generate_pages(self, drafts=False):\n for page in self.pages.values():\n if not page.fresh:\n self.generate_page(page, drafts)\n \n def generate_page(self, page, drafts):\n if not page.content:\n return\n \n is_draft = page.meta.get(\"draft\", False) is not False\n if not drafts and is_draft:\n print (\"Skip draft\", filename)\n page.html = False\n return\n \n params = {\n \"meta\": page.meta,\n \"page\": page,\n \"output_file\": page.url,\n \"SITEURL\": page.meta['root_dir'], # FIXME\n \"SITENAME\": page.meta['site_name'], # FIXME\n }\n params.update(self.constants)\n for k in \"root_dir\", \"static_dir\":\n params[k] = page.meta[k]\n \n template = self.templater.get_template(page.meta.get(\"template\", DEFAULT_PAGE_TEMPLATE))\n page.html = template.process(params)\n \n def write_data(self):\n self.write_pages()\n \n def write_pages(self):\n for page in self.pages.values():\n self.write_page(page)\n \n def write_page(self, page):\n if page.html:\n write_file(page.output_file, page.html)\n \n def add_blob(self, blob):\n self.blobs[blob.output_file] = blob\n \n def collect_blobs(self):\n dir_in = abspathjoin(self.theme_dir, \"static\")\n dir_out = abspathjoin(self.output_path, \"theme\")\n for blob in objects.list_blobs(dir_in, dir_out):\n self.add_blob(blob)\n \n for subdir in self.static_subdirs:\n dir_in = abspathjoin(self.content_dir, subdir)\n dir_out = abspathjoin(self.output_path, subdir)\n for blob in objects.list_blobs(dir_in, dir_out):\n self.add_blob(blob)\n \n def generate_blobs(self):\n for blob in self.blobs.values():\n if not blob.fresh:\n make_dirs(os.path.dirname(blob.output_file))\n blob.generate(self)\n \n","sub_path":"webgen/context.py","file_name":"context.py","file_ext":"py","file_size_in_byte":8552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"471423368","text":"#!/usr/bin/env python2.7\n\n# Put in crontab:\n# 30 * * * * /path/to/snapshot.py\n\nimport boto.ec2\n\nHOURLY_BACKUPS = 24\nDAILY_BACKUPS = 7\nWEEKLY_BACKUPS = 4\nMONTHLY_BACKUPS = 12\n\nVOLUMES = {'ap-southeast-2': ['vol-abc123abc']}\n\nAWS_ACCESS_KEY_ID = ''\nAWS_SECRET_ACCESS_KEY = ''\n\nfor region_name in VOLUMES:\n\n conn = boto.ec2.connect_to_region(region_name, aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY)\n\n for volume_id in VOLUMES[region_name]:\n snapshot = conn.create_snapshot(volume_id)\n conn.create_tags(snapshot.id, {'Name':'auto snapshot for %s' % volume_id})\n conn.trim_snapshots(hourly_backups=HOURLY_BACKUPS, daily_backups=DAILY_BACKUPS, weekly_backups=WEEKLY_BACKUPS, monthly_backups=MONTHLY_BACKUPS)\n","sub_path":"snapshot.py","file_name":"snapshot.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"70016388","text":"# vim: tabstop=4 shiftwidth=4 softtabstop=4\n\n__author__ = \"Vivek Dhayaal\"\n__copyright__ = \"Copyright 2014, Reliance Jio Infocomm Ltd.\"\n\nfrom horizon import forms\nfrom horizon import messages\n\nfrom django import shortcuts\n\nfrom horizon_jiocloud.api import keystoneapi\nfrom horizon_jiocloud.utils.utils import generate_and_send_sms\nfrom horizon_jiocloud.change_phone import forms as phone_forms\n\nimport logging\nLOG = logging.getLogger(__name__)\n\n\n\nclass PhoneView(forms.ModalFormView):\n form_class = phone_forms.PhoneForm\n template_name = 'change_phone/change.html'\n\n def get_initial(self):\n # we use request.session as a temporary storage for the new phone \n # number, because after the OTP is sent through SMS to user, until\n # he/she submits it through the form, we can't store the new phone\n # number in the database but still have to show it in the form\n initial = super(PhoneView, self).get_initial()\n initial[\"phone\"] = self.request.session.get(\"phone\")\n return initial\n\ndef sendSms(request):\n # This method serves re-sending SMS multiple times until the OTP is\n # expired, to cater to SMS sending failures.\n phone = request.session.get(\"phone\")\n try:\n res = keystoneapi.get_user(request.user.id)\n if not (res.get(\"success\") or res.get(\"result\")):\n raise Exception()\n except Exception as ex:\n LOG.exception(ex)\n user = res.get(\"result\")\n sms_activation_code = user.get(\"sms_activation_code\")\n try:\n generate_and_send_sms(phone, sms_activation_code)\n messages.success(request,\n 'SMS sent successfully')\n except Exception as ex:\n LOG.exception(ex)\n return shortcuts.redirect('horizon:settings:phone:index')\n","sub_path":"horizon_jiocloud/change_phone/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"381832858","text":"\"\"\"\nThis class utilizes exponential discounting to account for time delta.\n\"\"\"\nimport logging\n\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\nfrom via.model.projection import ProjectionModel\n\nclass ExponentialDiscount(ProjectionModel):\n def __init__(\n self,\n gamma=0.0\n ):\n super().__init__()\n self.gamma = gamma\n\n def build_projection(self, sequence_matrix):\n num_students, num_classes = sequence_matrix.shape\n num_timesteps = int(np.max(sequence_matrix))\n\n # adapts model parameter gamma to given instance of sequence matrix\n if type(self.gamma) == float:\n sequence_gamma = np.array(\n # avoids concurrent enrollment\n [0] + [self.gamma**t for t in range(num_timesteps-1)]\n )\n elif type(self.gamma) == list:\n sequence_gamma = np.array(\n self.gamma + [0] * (num_timesteps - len(self.gamma))\n )\n else:\n raise TypeError\n\n logging.info(f'Gamma discount factor: {sequence_gamma}')\n\n # class_scores[i][j] keeps track of time-normalized frequency of class i to j\n A = np.zeros((num_classes, num_classes, num_timesteps)).astype(np.float)\n\n for i in tqdm(range(num_students)):\n sequence = sequence_matrix[i]\n course_idxs = np.nonzero(sequence)[0]\n\n # Stores the sequence in (timestep, class_idx) tuple\n sequence = [(sequence[course_idx], course_idx)\n for course_idx in course_idxs]\n # Sorted in reverse to improve loop readability\n sequence = sorted(sequence, key=lambda x: x[0], reverse=True)\n for j in range(len(sequence)):\n curr_t, curr_class_idx = sequence[j]\n # if curr_t == 1:\n # A[-1][curr_class_idx][1] += 1\n # Move down the list by index\n for prev_t, prev_class_idx in sequence[j:]:\n # To facilitate indexing\n curr_t = int(curr_t)\n prev_t = int(prev_t)\n\n # Amount of time between course enrollment\n distance = curr_t - prev_t\n A[prev_class_idx][curr_class_idx][distance] += 1\n\n A = A * sequence_gamma\n A = np.sum(A, axis=2)\n return A\n\n\nclass ExponentialDiscountNormalized(ExponentialDiscount):\n \"\"\"\n Normalizes rows by the number of people taking each class.\n \"\"\"\n def __init__(\n self,\n gamma=0.0\n ):\n super().__init__(gamma)\n\n def build_projection(self, sequence_matrix):\n \"\"\"\n\n \"\"\"\n A = super().build_projection(sequence_matrix, gamma)\n\n # remove reverse prerequisite relationships\n A[A < 0] = 0.0\n out_degrees = np.count_nonzero(A, axis=1)\n mu = np.mean(out_degrees)\n std = np.std(out_degrees)\n\n # only interested in those classes with high out_degree\n # high out_degree means that these are classes we have a rich\n # understanding of.\n A[out_degrees < mu] = 0.0\n totals = A.sum(axis=1, keepdims=1)\n\n # row-normalization\n A = np.divide(A, totals, out=np.zeros_like(A), where=totals != 0)\n return A\n\nclass ExponentialDiscountConditional(ExponentialDiscount):\n \"\"\"\n Calculates p(j|i) for all classes i, j\n\n A[i][j] = p(j|i) = p(i, j) / students enrolled in i\n\n p(i, j) here defined to be the number of students who took i and j,\n exponentially discounted by some factor gamma. A constant gamma = 0.0\n means that only immediately consecutive i, j pairs are considered.\n \"\"\"\n def __init__(\n self,\n gamma=0.0,\n p_cutoff=0.0\n ):\n super().__init__(gamma)\n self.course_p = None\n\n def build_projection(self, sequence_matrix):\n \"\"\"\n \"\"\"\n A = super().build_projection(sequence_matrix)\n course_counts = np.count_nonzero(sequence_matrix, axis=0).reshape(-1, 1)\n self.calculate_course_probs(sequence_matrix)\n A = np.divide(A, course_counts, out=np.zeros_like(A), where=course_counts != 0)\n return A\n\n def calculate_course_probs(self, sequence_matrix):\n course_counts = np.count_nonzero(sequence_matrix, axis=0)\n self.course_p = course_counts / sequence_matrix.shape[0]\n\n def get_course_probs(self, sequence_matrix):\n if self.course_p is None:\n self.calculate_course_probs(sequence_matrix)\n return self.course_p\n\nclass ExponentialDiscountJoint(ExponentialDiscount):\n \"\"\"\n Calculates p(i, j) for all classes i, j using chain rule:\n\n A[i][j] = p(i) * p(j|i)\n \"\"\"\n def __init__(\n self,\n gamma=0.0\n ):\n super().__init__(gamma)\n\n def build_projection(self, sequence_matrix):\n \"\"\"\n \"\"\"\n A = super().build_projection(sequence_matrix)\n # remove reverse prerequisite relationships\n A[A < 0] = 0.0\n course_counts = np.count_nonzero(sequence_matrix, axis=0)\n course_p = course_counts / sequence_matrix.shape[0]\n A = A * course_p.reshape(-1, 1)\n A = np.divide(A, course_counts.reshape(-1, 1),\n out=np.zeros_like(A), where=course_counts != 0)\n return A\n","sub_path":"via/model/discount.py","file_name":"discount.py","file_ext":"py","file_size_in_byte":5329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"545449816","text":"\"\"\"add user_addr in onlines\n\nRevision ID: 5f6d5bdb2aa6\nRevises: d254e891c7fc\nCreate Date: 2016-12-18 09:46:19.806672\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5f6d5bdb2aa6'\ndown_revision = 'd254e891c7fc'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('onlines', sa.Column('user_addr', sa.String(length=128), nullable=True))\n op.create_index(op.f('ix_onlines_user_addr'), 'onlines', ['user_addr'], unique=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_onlines_user_addr'), table_name='onlines')\n op.drop_column('onlines', 'user_addr')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/5f6d5bdb2aa6_add_user_addr_in_onlines.py","file_name":"5f6d5bdb2aa6_add_user_addr_in_onlines.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"464902681","text":"# =============================================================================\n# Debugger config file\n#\n#\nC = {}\n#\n#\n# UDP socket debug enable/disable\n# Default is False\nC['SOCKET'] = False\n#\n#\n# Server receiver address\n# Default is localhost\nC['SERVERHOST'] = 'localhost'\n#\n#\n# Server receiver port\n# Default is 8888\nC['SERVERPORT'] = 8888\n#\n#\n# Client send address\n# Default is localhost\nC['CLIENTHOST'] = 'localhost'\n#\n#\n# lient send port\n# Default is 8888\nC['CLIENTPORT'] = 8888\n#\n#\n# Filename of the admin log file\n# Default is \"rr_mapscript.txt\"\nC['PATH_LOG_FILENAME'] = \"rr_mapscript.txt\"\n#\n#\n# Path relative to PR root (not mod root) of mapscript log file\n# Default is \"admin/logs\"\nC['PATH_LOG_DIRECTORY'] = \"admin/logs\"\n#\n#\n# Use python cPickle lib for packing data\n# Default is False\nC['PICKLE_DATA'] = False\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n","sub_path":"rr_config.py","file_name":"rr_config.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"508707300","text":"# s = \"\"\"\n# I'm learning Python\n# You are learning Python\n# We are learning Python\n# \"\"\"\n# print(s)\n\n# s = '這裡有賣香蕉、蘋果、鳳梨、芭樂'\n# s[4:].split('、')\n# for i in s:\n# print(i)\n\n# 99multi.py\nRANGE1 = [1, 3]\nRANGE2 = [1, 9]\n\ndef calc(a,b):\n return [\n {'sign': '*', 'result':a*b},\n ]\n\nfor i in range(RANGE1[0], RANGE1[1] + 1):\n for j in range(RANGE2[0], RANGE2[1] + 1):\n for k in calc(i, j):\n print('{:>7}'.format(str(i) + k['sign'] + str(j) + '=' + str(k['result'])),\"|\",end = \" \")\n print()","sub_path":"7.17/string_.py","file_name":"string_.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"81224289","text":"#--------------------------------------------\n# Uniform Cost Search Tutorial\n# Intelligent Systems - University of Deusto\n# Inigo Lopez-Gazpio\n#--------------------------------------------\n\n# Preliminary notes : Make sure you understand the following pre-requisites\n# 1.- Python basics and first steps\n# 2.- Python openai gym extra environments provided in class\n# 3.- Frontier expansion tutorials\n\n# You can now safely keep on with BFS\n\n# Task 1\n# First of all analyze the BFS procedure (UDAI)\n\n#---------------------------\n# River Crossing environment\n#---------------------------\nimport gym\nfrom UDAI.frontier.Node import Node\nfrom UDAI.agent.Blind_UCS_Tree_Agent import Blind_UCS_Tree_Agent\nfrom UDAI.agent.Blind_UCS_Graph_Agent import Blind_UCS_Graph_Agent\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nenv = gym.make('gym_RiverCrossing:RiverCrossing-v0')\nfirst_observation = env.reset()\nfirst_node = Node(env, first_observation)\nenv.render()\n\n# Bling Tree Agent Search\nblind_ucs_tree_agent = Blind_UCS_Tree_Agent()\nblind_ucs_tree_agent.blind_search(first_node)\n\n# If solution is found we can explore the solution :)\nblind_ucs_tree_agent.final_node.depth\nblind_ucs_tree_agent.final_node.action_history\nblind_ucs_tree_agent.final_node.observation\nblind_ucs_tree_agent.final_node.env.render()\n# etc\n\n# we can also analyze the search process using the reporting class inside the agent\nblind_ucs_tree_agent.reporting.log\nblind_ucs_tree_agent.reporting.plotNumberNodesFrontier()\nblind_ucs_tree_agent.reporting.plotFrontierMaxDepth()\nblind_ucs_tree_agent.reporting.plotNodesAddedFrontier(nbins=10)\nblind_ucs_tree_agent.reporting.plotFrontierCost()\n\n# now lets try another search agent :)\nfirst_observation = env.reset()\nfirst_node = Node(env, first_observation)\n\n# Bling Graph Agent Search\nblind_ucs_graph_agent = Blind_UCS_Graph_Agent()\nblind_ucs_graph_agent.blind_search(first_node)\n\n# If solution is found we can explore the solution :)\nblind_ucs_graph_agent.final_node.depth\nblind_ucs_graph_agent.final_node.action_history\nblind_ucs_graph_agent.final_node.observation\nblind_ucs_graph_agent.final_node.env.render()\n\n# we can also analyze the search process using the reporting class inside the agent\nblind_ucs_graph_agent.reporting.log\nblind_ucs_graph_agent.reporting.plotNumberNodesFrontier()\nblind_ucs_graph_agent.reporting.plotFrontierMaxDepth()\nblind_ucs_graph_agent.reporting.plotNodesAddedFrontier(nbins=10)\nblind_ucs_tree_agent.reporting.plotFrontierCost()\n\n\n\n# We can also compute some combined graphs\n\nNumberNodesFrontier = pd.concat(\n [\n blind_ucs_tree_agent.reporting.log['Frontier'],\n blind_ucs_graph_agent.reporting.log['Frontier']\n ] , axis=1\n)\nNumberNodesFrontier.columns = [\"# Nodes Tree\", \"# Nodes Graph\"]\nNumberNodesFrontier.plot(lw=2, marker='*')\nplt.show()\n\n\nMaxDepth = pd.concat(\n [\n blind_ucs_tree_agent.reporting.log['F.Max.Depth'],\n blind_ucs_graph_agent.reporting.log['F.Max.Depth']\n ] , axis=1\n)\nMaxDepth.columns = [\"Max Depth Tree\", \"Max Depth Graph\"]\nMaxDepth.plot(lw=2, marker='*')\nplt.show()\n\n\nExpanded = pd.concat(\n [\n blind_ucs_tree_agent.reporting.log['Expanded'],\n blind_ucs_graph_agent.reporting.log['Expanded']\n ] , axis=1\n)\nExpanded.columns = [\"Expanded Tree\", \"Expanded Graph\"]\nExpanded.plot(kind=\"hist\", bins=10)\nplt.show()\n\nExpanded.plot(kind=\"kde\", lw=2)\nplt.show()\n\n\nMaxDepth = pd.concat(\n [\n blind_ucs_tree_agent.reporting.log['Cur.Cost'],\n blind_ucs_graph_agent.reporting.log['Cur.Cost']\n ] , axis=1\n)\nMaxDepth.columns = [\"Cur.Cost\", \"Cur.Cost\"]\nMaxDepth.plot(alpha=0.5, lw=2, marker='*')\nplt.show()\n\n\n\n#---------------------\n# 8-Puzzle environment\n#---------------------\nenv = gym.make('gym_8Puzzle:8Puzzle-v0')\nfirst_observation = env.reset()\nfirst_node = Node(env, first_observation)\n\nblind_ucs_tree_agent = Blind_UCS_Tree_Agent()\nblind_ucs_tree_agent.blind_search(first_node, 2500)\n\n\n# Depending on the limit we are able to search with more depth in the tree (hint: use max_steps parameter)\n# What is the maximum level obtained with 2500 iterations ?\n# What is the maximum level obtained with 5000 iterations ?\n# What is the maximum level obtained with 10000 iterations ?\n\n# Considering this problem has Branching factor of about 3,\n# ¿How many nodes do we need to explore to reach a solution at deep=10, 11, 12...?\n\n# Let's try graph.search\nblind_ucs_graph_agent = Blind_UCS_Graph_Agent()\nblind_ucs_graph_agent.blind_search(first_node, 2500)\n\n# Since no repeated states are checked, for GS version, it is \"easier\" to reach a certain deep. In addition, frontier grows \"slower\")\n# Let's see the point with graphs :)\n\nNumberNodesFrontier = pd.concat(\n [\n blind_ucs_tree_agent.reporting.log['Frontier'],\n blind_ucs_graph_agent.reporting.log['Frontier']\n ] , axis=1\n)\nNumberNodesFrontier.columns = [\"# Nodes Tree\", \"# Nodes Graph\"]\nNumberNodesFrontier.plot(lw=2, marker='*')\nplt.show()\n\n\nMaxDepth = pd.concat(\n [\n blind_ucs_tree_agent.reporting.log['F.Max.Depth'],\n blind_ucs_graph_agent.reporting.log['F.Max.Depth']\n ] , axis=1\n)\nMaxDepth.columns = [\"Max Depth Tree\", \"Max Depth Graph\"]\nMaxDepth.plot(lw=2, marker='*')\nplt.show()\n\n\nExpanded = pd.concat(\n [\n blind_ucs_tree_agent.reporting.log['Expanded'],\n blind_ucs_graph_agent.reporting.log['Expanded']\n ] , axis=1\n)\nExpanded.columns = [\"Expanded Tree\", \"Expanded Graph\"]\nExpanded.plot(kind=\"hist\", bins=10)\nplt.show()\n\nExpanded.plot(kind=\"kde\", lw=2)\nplt.show()\n\n\nMaxDepth = pd.concat(\n [\n blind_ucs_tree_agent.reporting.log['Cur.Cost'],\n blind_ucs_graph_agent.reporting.log['Cur.Cost']\n ] , axis=1\n)\nMaxDepth.columns = [\"Cur.Cost\", \"Cur.Cost\"]\nMaxDepth.plot(alpha=0.5, lw=2, marker='*')\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'''\n\nTODO\n\n#---------------------\n# Sudoku environment\n#---------------------\n\n\n# Problem 3: Sudoku (brief on Formulation)\n\nproblem = initialize.problem(\"data/sudoku-1.txt\")\nres1 = Breadth.First.Search(problem, count.limit = 1000) \nres2 = Breadth.First.Search(problem, count.limit = 1000, graph.search = T) \nanalyze.results(list(res1, res2))\n# which deep would we need??\n\n# Conclusion... something more \"intelligent\" that BFS needs to be used :)\n'''","sub_path":"3.1 - Blind Searches/Uniform_Cost_Search.py","file_name":"Uniform_Cost_Search.py","file_ext":"py","file_size_in_byte":6222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"439585380","text":"import torch\nimport numpy as np\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom cdrp import main as cdrp\nfrom cdrp import main2 as r_cdrp\nfrom src import Plot_tools\n\n\nclass Pruner:\n\n def __init__(self, model, input, device, label = None, output_orig=None):\n self.model = model\n self.input = input\n self.model.eval()\n self.device = device\n # pruned_activations_mask, 0 for pruned, 1 for others\n self.gradients = []\n self.activations = []\n self.pruned_activations_mask = []\n if label and output_orig is not None:\n self.label = label\n self.output_orig = output_orig\n else:\n self.output_orig = self.model(input).detach()\n self.label = self.output_orig.data.max(1)[1].item()\n self.handles_list = []\n self._hook_layers()\n self.integrad_handles_list = []\n self.integrad_scores = []\n self.integrad_calc_activations_mask = None\n\n def _hook_layers(self):\n def backward_hook_relu(module, grad_input, grad_output):\n self.gradients.append(grad_output[0].to(self.device))\n\n def forward_hook_relu(module, input, output):\n # mask output by pruned_activations_mask\n # In the first model(input) call, the pruned_activations_mask\n # is not yet defined, thus we check for emptiness\n if self.pruned_activations_mask:\n output = torch.mul(output, self.pruned_activations_mask[len(self.activations)].to(self.device)) #+ self.pruning_biases[len(self.activations)].to(self.device)\n self.activations.append(output.to(self.device))\n return output\n\n i = 0\n for module in self.model.modules():\n if isinstance(module, nn.ReLU):\n # if isinstance(module, resnet.BasicBlock):\n self.handles_list.append(module.register_forward_hook(forward_hook_relu))\n self.handles_list.append(module.register_backward_hook(backward_hook_relu))\n\n def remove_handles(self):\n for handle in self.handles_list:\n handle.remove()\n self.handles_list.clear()\n self.activations = []\n self.gradients = []\n\n # we always call _forward instead of directly calling model(input),\n # since the activations and gradients need to be reset\n def _forward(self, input):\n self.activations = []\n self.gradients = []\n self.model.zero_grad()\n output = self.model(input)\n return output\n\n def _initialize_pruned_mask(self):\n output = self._forward(self.input)\n\n # initializing pruned_activations_mask\n for layer in self.activations:\n self.pruned_activations_mask.append(torch.ones(layer.size()).to(self.device))\n return output\n\n def _number_of_neurons(self):\n total = 0\n for layer in self.activations:\n num_neurons_in_layer = layer.numel()\n total += num_neurons_in_layer\n return total\n\n def _compute_taylor_scores(self):\n\n first_order_taylor_scores = []\n self.gradients.reverse()\n\n for i, layer in enumerate(self.activations):\n first_order_taylor_scores.append(torch.abs(torch.mul(layer, self.gradients[i])))\n\n return first_order_taylor_scores\n\n def _mask_least_important_neurons(self, first_order_taylor_scores, percentile_to_prune):\n\n scores_all_layers = np.empty(0)\n for layer_scores in first_order_taylor_scores:\n scores_all_layers = np.concatenate((scores_all_layers,\n layer_scores.cpu().detach().numpy().flatten()))\n #print(scores_all_layers)\n remove_threshold = np.percentile(scores_all_layers, percentile_to_prune)\n copy_first_order_taylor_scores = first_order_taylor_scores.copy()\n\n for i, layer_scores in enumerate(first_order_taylor_scores):\n\n self.pruned_activations_mask[i][layer_scores <= remove_threshold] = 0\n copy_first_order_taylor_scores[i][layer_scores <= remove_threshold] = 0\n\n return copy_first_order_taylor_scores\n\n def _mask_least_important_neurons_iterative(self, first_order_taylor_scores, percentile_to_prune):\n\n scores_all_layers = np.empty(0)\n for layer_scores in first_order_taylor_scores:\n scores_all_layers = np.concatenate((scores_all_layers,\n layer_scores.cpu().detach().numpy().flatten()))\n\n scores_all_layers[scores_all_layers <= 0] = np.max(scores_all_layers.flatten())\n remove_threshold = np.percentile(scores_all_layers, percentile_to_prune)\n copy_first_order_taylor_scores = first_order_taylor_scores.copy()\n\n for i, layer_scores in enumerate(first_order_taylor_scores):\n self.pruned_activations_mask[i][layer_scores <= remove_threshold] = 0\n self.pruned_activations_mask[i][layer_scores <= 0] = 1\n\n\n def prune_neuron_mct(self, percentile_to_prune=85., debug=False):\n\n initial_output = self._initialize_pruned_mask()\n initial_output = torch.nn.functional.softmax(initial_output, dim=1)\n initial_predicted_logit = initial_output.data.max(1)[0].item()\n initial_predicted_class = initial_output.data.max(1)[1].item()\n if debug:\n print(\"Initial output = {}\".format(initial_predicted_logit))\n print('Initial predicted class {}: '.format(initial_predicted_class))\n label = torch \\\n .tensor([self.label]).to(self.device)\n criterion = torch.nn.CrossEntropyLoss()\n initial_loss = criterion(initial_output, label)\n\n num_total = self._number_of_neurons()\n if debug:\n print('initial loss {}'.format(initial_loss))\n print(\"total number of neurons: {}\".format(num_total))\n\n output = self._forward(self.input)\n output[0, self.label].backward(retain_graph=True)\n first_order_taylor_scores = self._compute_taylor_scores()\n self._mask_least_important_neurons(first_order_taylor_scores, percentile_to_prune)\n output = self._forward(self.input)\n output_softmax = torch.nn.functional.softmax(output, dim=1)\n output_orig_softmax = torch.nn.functional.softmax(self.output_orig, dim=1)\n return abs(output_softmax[0, self.label].data.item() - output_orig_softmax[0, self.label].data.item()) / output_orig_softmax[0, self.label].data.item()\n\n def prune_random(self, percentile_to_prune, debug=False):\n initial_output = self._initialize_pruned_mask()\n initial_output = torch.nn.functional.softmax(initial_output, dim=1)\n initial_predicted_logit = initial_output.data.max(1)[0].item()\n initial_predicted_class = initial_output.data.max(1)[1].item()\n if debug:\n print(\"Initial output = {}\".format(initial_predicted_logit))\n print('Initial predicted class {}: '.format(initial_predicted_class))\n label = torch \\\n .tensor([self.label]).to(self.device)\n criterion = torch.nn.CrossEntropyLoss()\n initial_loss = criterion(initial_output, label)\n\n num_total = self._number_of_neurons()\n if debug:\n print('initial loss {}'.format(initial_loss))\n print(\"total number of neurons: {}\".format(num_total))\n\n output = self._forward(self.input)\n output[0, self.label].backward(retain_graph=True)\n\n for i, layer_scores in enumerate(self.activations):\n size_of_layer = layer_scores.view(-1).shape[0]\n mask = torch.ones(size_of_layer)\n mask[np.random.permutation(range(0, size_of_layer))[:int(percentile_to_prune/100*size_of_layer)]] = 0\n\n if len(layer_scores.shape) == 2:\n mask = mask.view(layer_scores.shape[0], layer_scores.shape[1])\n\n elif len(layer_scores.shape) == 3:\n mask = mask.view(layer_scores.shape[0], layer_scores.shape[1], layer_scores.shape[2])\n\n elif len(layer_scores.shape) == 4:\n mask = mask.view(layer_scores.shape[0], layer_scores.shape[1], layer_scores.shape[2], layer_scores.shape[3])\n\n self.pruned_activations_mask[i] = mask\n\n def _init_integrad_mask(self):\n self.integrad_calc_activations_mask = []\n _ = self._forward(self.input)\n for a in self.activations:\n self.integrad_calc_activations_mask.append(torch.ones(a.shape))\n\n\n def _calc_integrad_scores(self, iterations):\n def forward_hook_relu(module, input, output):\n output = torch.mul(output, self.integrad_calc_activations_mask[len(self.activations)-1].to(self.device))\n return output\n\n initial_output = self._initialize_pruned_mask()\n output = self._forward(self.input)\n output[0, self.label].backward(retain_graph=True)\n\n original_activations = []\n for a in self.activations:\n original_activations.append(a.detach().clone())\n\n self._init_integrad_mask()\n mask_step = 1./iterations\n i = 0\n for module in self.model.modules():\n if isinstance(module, nn.ReLU):\n self.integrad_scores.append(torch.zeros(original_activations[i].shape).to(self.device))\n self.integrad_calc_activations_mask[i] = torch.zeros(self.integrad_calc_activations_mask[i].shape)\n self.integrad_handles_list.append(module.register_forward_hook(forward_hook_relu))\n\n for j in range(iterations+1):\n self.integrad_calc_activations_mask[i] += j*mask_step\n output = self._forward(self.input)\n output[0, self.label].backward(retain_graph=True)\n self.gradients.reverse()\n self.integrad_scores[len(self.integrad_scores)-1] += self.gradients[i]\n self.integrad_scores[len(self.integrad_scores)-1] = abs(self.integrad_scores[len(self.integrad_scores)-1]/(iterations+1) * original_activations[i])\n self.integrad_calc_activations_mask[i] = torch.ones(self.integrad_calc_activations_mask[i].shape)\n self.integrad_handles_list[0].remove()\n self.integrad_handles_list.clear()\n i += 1\n\n def prune_integrad(self, percentile_to_prune, iterations=10, debug=False):\n self._calc_integrad_scores(iterations)\n scores_all_layers = np.empty(0)\n for layer_scores in self.integrad_scores:\n scores_all_layers = np.concatenate((scores_all_layers,\n layer_scores.cpu().detach().numpy().flatten()))\n\n remove_threshold = np.percentile(scores_all_layers, percentile_to_prune)\n copy_integrad_scores = self.integrad_scores.copy()\n\n for i, layer_scores in enumerate(self.integrad_scores):\n\n self.pruned_activations_mask[i][layer_scores <= remove_threshold] = 0\n copy_integrad_scores[i][layer_scores <= remove_threshold] = -1\n\n return copy_integrad_scores\n\n\n def prune_greedy(self, percentile_to_prune=1., iteration=100, debug=False):\n\n initial_output = self._initialize_pruned_mask()\n initial_output = torch.nn.functional.softmax(initial_output, dim=1)\n initial_predicted_logit = initial_output.data.max(1)[0].item()\n initial_predicted_class = initial_output.data.max(1)[1].item()\n if debug:\n print(\"Initial output = {}\".format(initial_predicted_logit))\n print('Initial predicted class {}: '.format(initial_predicted_class))\n label = torch \\\n .tensor([self.label]).to(self.device)\n criterion = torch.nn.CrossEntropyLoss()\n initial_loss = criterion(initial_output, label)\n if debug:\n print('initial loss {}'.format(initial_loss))\n\n num_total = self._number_of_neurons()\n if debug:\n print(\"total number of neurons: {}\".format(num_total))\n\n output = self._forward(self.input)\n output[0, self.label].backward(retain_graph=True)\n\n first_order_taylor_scores = self._compute_taylor_scores()\n for i in range(iteration):\n #print(\"iteration: {}\".format(i))\n self._mask_least_important_neurons_iterative(first_order_taylor_scores, i*percentile_to_prune)\n output = self._forward(self.input)\n output[0, self.label].backward(retain_graph=True)\n first_order_taylor_scores = self._compute_taylor_scores()\n\n def prune_dgr(self, percentile_to_prune, r=False, debug=False):\n _ = self.model(self.input)\n acts = []\n for a in self.activations:\n acts.append(a.detach().clone())\n self.remove_handles()\n if not r:\n paths = cdrp.get_path(self.model, self.input, self.label, percentile_to_prune, acts)\n else:\n paths = r_cdrp.get_path(self.model, self.input, self.label, percentile_to_prune, acts)\n\n scores_all_layers = np.empty(0)\n for path_scores in paths:\n scores_all_layers = np.concatenate((scores_all_layers,\n path_scores.cpu().detach().numpy().flatten()))\n\n remove_threshold = np.percentile(scores_all_layers, percentile_to_prune)\n self._hook_layers()\n _ = self._forward(self.input)\n\n initial_output = self._initialize_pruned_mask()\n for i, p in enumerate(paths):\n self.pruned_activations_mask[i][p <= remove_threshold] = 0\n self.pruned_activations_mask[i][p > remove_threshold] = 1\n\t\t\t\n def base_sparsity(self):\n num = 0\n self._forward(self.input)\n for activation in self.activations:\n activation_copy = activation.clone().detach()\n activation_copy[activation_copy <= 0.] = -1\n activation_copy[activation_copy > 0.] = 0\n activation_copy = abs(activation_copy)\n num += torch.norm(activation_copy.view(-1), p=1).item()\n num_total = self._number_of_neurons()\n return num/num_total\n\n def dead_neurons_path(self):\n initial_output = self._initialize_pruned_mask()\n self._forward(self.input)\n for i, activation in enumerate(self.activations):\n activation_copy = activation.clone().detach()\n activation_copy[activation_copy <= 0.] = -1\n activation_copy[activation_copy > 0.] = 0\n activation_copy = abs(activation_copy)\n self.pruned_activations_mask[i] = activation_copy\n\n def generate_saliency(self, make_single_channel=True):\n data_var_sal = Variable(self.input).to(self.device)\n\n if data_var_sal.grad is not None:\n data_var_sal.grad.data.zero_()\n data_var_sal.requires_grad_(True)\n\n out_sal = self._forward(data_var_sal)\n out_sal[0, self.label].backward(retain_graph=True)\n\n grad = data_var_sal.grad.data.detach().cpu()\n grad_np = np.asarray(grad).squeeze(0)\n\n if make_single_channel:\n grad = Plot_tools.max_regarding_to_abs(np.max(grad_np, axis=0), np.min(grad_np, axis=0))\n return np.expand_dims(grad, axis=0)\n # The output is 3-channel image size saliency map\n return np.expand_dims(grad_np, axis=0)\n","sub_path":"src/Pruner.py","file_name":"Pruner.py","file_ext":"py","file_size_in_byte":15272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"583759698","text":"# -*- coding: utf-8 -*-\n# PROJECT : picopico\n# TIME : 17-1-4 下午3:41\n# AUTHOR : youngershen \nimport time\nimport json\nimport hmac\nimport base64\nfrom hashlib import sha1 as sha\nimport logging\nfrom django.db import transaction\nfrom django import http\nfrom django.http import Http404\nfrom django.http import JsonResponse\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom django.core.paginator import Paginator\nfrom django.views.generic.base import TemplateResponseMixin as DjangoTemplateResponseMixin\nfrom django.core.paginator import EmptyPage, InvalidPage\nfrom django.utils import timezone\nfrom picopico.utils.common import get_time_md5\nfrom picopico.apps.file.models import ALLOWED_EXT\n\nlogger = logging.getLogger(__name__)\n\n\nclass RedirectResponseMixin:\n permanent = False\n redirect_url = None\n pattern_name = None\n kwargs = None\n args = None\n use_query_string = False\n redirect_to = 'redirect-to'\n\n def get_redirect_url(self, *args, **kwargs):\n if self.redirect_url:\n if kwargs:\n url = self.redirect_url % kwargs\n elif self.kwargs:\n url = self.redirect_url % self.kwargs\n else:\n url = self.redirect_url\n\n elif self.pattern_name:\n url = reverse(self.pattern_name, args=args, kwargs=kwargs)\n\n elif self.request.GET.get(self.redirect_to, None):\n url = self.request.GET.get(self.redirect_to)\n\n else:\n return None\n\n if self.use_query_string:\n args = self.request.META.get('QUERY_STRING', '')\n\n if args:\n url = \"%s?%s\" % (url, args)\n if self.args:\n url = \"%s?%s\" % (url, self.args)\n\n return url\n\n def redirect(self, request, *args, **kwargs):\n url = self.get_redirect_url(*args, **kwargs)\n if url:\n if self.permanent:\n return http.HttpResponsePermanentRedirect(url)\n else:\n return http.HttpResponseRedirect(url)\n else:\n return Http404\n\n\nclass JSONResponseMixin:\n @staticmethod\n def render_to_json_response(context, **kwargs):\n return JsonResponse(context, safe=False, **kwargs)\n\n\nclass ContextMixin:\n def get_context_data(self, request, *args, **kwargs):\n pass\n\n def post_context_data(self, request, *args, **kwargs):\n pass\n\n def get_json_context_data(self, request, *args, **kwargs):\n pass\n\n def post_json_context_data(self, request, *args, **kwargs):\n pass\n\n def put_json_context_data(self, request, *args, **kwargs):\n pass\n\n def delete_json_context_data(self, request, *args, **kwargs):\n pass\n\n\nclass MessageMixin:\n message_key_name = 'message'\n\n def add_message_dict(self, data):\n message = self.request.session.get(self.message_key_name, None)\n if message:\n message.update(data)\n else:\n message = data\n\n self.request.session[self.message_key_name] = message\n\n def add_message(self, name, value):\n message = self.request.session.get(self.message_key_name, None)\n if message:\n message.update({name: value})\n else:\n message = {name: value}\n self.request.session[self.message_key_name] = message\n\n def get_message(self):\n message = self.request.session.get(self.message_key_name, None)\n self.request.session[self.message_key_name] = None\n return message\n\n def render_to_response(self, context, **response_kwargs):\n message = self.get_message()\n if context is None:\n context = {}\n context.update({self.message_key_name: message})\n response_kwargs.setdefault('content_type', self.content_type)\n return self.response_class(\n request=self.request,\n template=self.get_template_names(),\n context=context,\n using=self.template_engine,\n **response_kwargs\n )\n\n\nclass LoginRedirectMixin:\n redirect_url = '/'\n login_redirect = True\n\n def check_login(self):\n if not self.request.user.is_authenticated():\n return False\n\n referrer = self.request.META.get('HTTP_REFERER')\n if referrer:\n self.redirect_url = referrer\n else:\n url = self.request.GET.get(self.redirect_to, None)\n if url:\n self.redirect_url = url\n else:\n self.redirect_url = '/'\n\n return True\n\n\nclass LoginRequiredMixin:\n login_required = True\n redirect_url = '/account/login'\n\n def check_login_required(self):\n if self.request.user.is_authenticated():\n return False\n else:\n url = self.request.get_full_path()\n self.redirect_url = reverse('account:login') + '?' + self.redirect_to + '=' + url\n return True\n\n\nclass OSSMixin:\n pass\n\n\nclass DOSSMixin:\n \"\"\"\n this mixin is for direct send file to oss url via browser\n not like the other oss module act like send file to your \n server then your server send the file to oss\n \"\"\"\n access_id = None\n access_secret = None\n end_point = None\n bucket = None\n use_callback = False\n success_action_redirect = 'https://www.picopico.com.cn'\n success_action_status = 201\n callback_url = 'https://www.picopico.com.cn'\n upload_dir = 'user/'\n expire = 30\n\n def get_token(self, bucket='picopico', expire=30):\n self.access_id = settings.ALIYUN_ACCESSKEYID\n self.access_secret = settings.ALIYUN_ACCESSKEYSECRET\n self.bucket = bucket\n self.end_point = 'http://' + self.bucket + '.' + settings.ALIYUN_OSS_END_POINT\n self.expire = expire\n return self._get_token()\n\n def _get_token(self):\n now = int(time.time())\n expire_syncpoint = now + self.expire\n expire = self._get_expire_time(expire_syncpoint)\n\n policy = {\n 'expiration': expire\n }\n\n condition = []\n upload = ['starts-with', '$key', self.upload_dir]\n condition.append(upload)\n\n policy['conditions'] = condition\n policy = json.dumps(policy).strip()\n\n policy_encode = base64.b64encode(policy.encode())\n h = hmac.new(self.access_secret.encode(), policy_encode, sha)\n sign_result = base64.encodebytes(h.digest()).strip()\n user = self.request.user\n file_part_name = self.upload_dir + str(user.id) + '/' + get_time_md5(user.id) + '-'\n filename = file_part_name + '${filename}'\n callback = self._get_callback_body() if self.use_callback else None\n\n token = {\n 'accessid': self.access_id,\n 'action': self.end_point,\n 'policy': policy_encode,\n 'signature': sign_result,\n 'expire': expire_syncpoint,\n 'key': filename,\n 'success_action_redirect': self.success_action_redirect,\n 'success_action_status': self.success_action_status,\n 'file_part_name': file_part_name\n }\n\n token.update({'callback': callback}) if self.use_callback else None\n\n if settings.DEBUG:\n logger.debug(token)\n return token\n\n @staticmethod\n def get_headers():\n return {'Access-Control-Allow-Methods': 'POST',\n 'Access-Control-Allow-Origin': '*',\n }\n\n @staticmethod\n def _get_expire_time(time_str):\n import datetime\n gmt = datetime.datetime.fromtimestamp(time_str).isoformat()\n gmt += 'Z'\n return gmt\n\n def _get_callback_body(self):\n callback = {\n 'callbackUrl': self.callback_url,\n 'callbackHost': '',\n 'callbackBody': 'filename=${object}&size=${size}&mimeType=${mimeType}'\n '&height=${imageInfo.height}&width=${imageInfo.width}',\n 'callbackBodyType': 'application/x-www-form-urlencoded'\n }\n callback_json = json.dumps(callback)\n return base64.b64encode(callback_json.encode())\n\n\nclass TemplateResponseMixin(DjangoTemplateResponseMixin):\n def __init__(self):\n pass\n\n def render_to_response(self, context, **response_kwargs):\n \"\"\"\n Returns a response, using the `response_class` for this\n view, with a template rendered with the given context.\n\n If any keyword arguments are provided, they will be\n passed to the constructor of the response class.\n \"\"\"\n response_kwargs.setdefault('content_type', self.content_type)\n\n headers = self.get_headers()\n\n response = self.response_class(\n request=self.request,\n template=self.get_template_names(),\n context=context,\n using=self.template_engine,\n **response_kwargs\n )\n if headers:\n for name, value in headers.items():\n setattr(response, name, value)\n return response\n\n @staticmethod\n def get_headers():\n return {}\n\n\nclass FilterMixin:\n model_class = None\n query_dict = None\n \"\"\"\n query_dict = {'age': 'number', 'size': 'number', 'name': 'string'}\n \"\"\"\n\n def get_queryset(self, query):\n return self.model_class.objects.filter(query)\n\n def get_query(self, params):\n from django.db.models import Q\n query = None\n\n for key in params:\n if key not in self.query_dict and not params.get(key, None):\n continue\n value = params.get(key)\n if query is None:\n query = Q(**{key: value})\n else:\n query = query & Q(**{key: value})\n\n return query\n\n def filter(self, params):\n \"\"\"\n :param params: request.GET or request.POST or some dict like object contains your basic query string\n :return: a django queryset object so that you can do much more filter or pagination\n \"\"\"\n query = self.get_query(params)\n queryset = self.get_queryset(query)\n return queryset\n\n\nclass PaginationMixin:\n allow_empty_first_page = False\n pagination_class = Paginator\n per_page = 10\n\n def get_page(self, query_set, page='1'):\n pager = self.pagination_class(query_set, self.per_page, allow_empty_first_page=self.allow_empty_first_page)\n\n try:\n page_obj = pager.page(page)\n except EmptyPage:\n if '1' == page:\n raise Http404\n else:\n page_obj = pager.page(1)\n except InvalidPage:\n page_obj = pager.page(1)\n\n return page_obj\n\n\nclass PermissionMixin:\n pass\n\n\nclass FileUploadMixin:\n KB = 1024\n MB = KB * 1024\n max_size = MB * 10 # in bytes, default is 10MB\n\n file_type = ALLOWED_EXT\n upload_to = 'local'\n path = None\n url = None\n\n @staticmethod\n def get_file_ext(file):\n ext = ''\n if file:\n ext = file.split('.')[-1]\n return ext\n\n @staticmethod\n @transaction.atomic\n def save_db(data, request):\n from picopico.apps.file.models import File\n for item in data:\n if request.user.is_authenticated():\n file = File(url=item.get('url', ''), user=request.user)\n else:\n file = File(url=item.get('url', ''))\n file.save()\n\n def upload(self, request, name='picopico'):\n ret = None\n\n if 'local' == self.upload_to:\n ret = self._save_to_local(request)\n\n elif 'oss' == self.upload_to:\n ret = self._save_to_oss(request, name)\n\n self.save_db(ret, request)\n return ret\n\n def _save_to_local(self, request):\n from picopico.utils.common import get_time_md5\n path = self.path if self.path else settings.MEDIA_ROOT\n url = self.url if self.url else settings.MEDIA_URL\n ret = []\n for item in request.FILES:\n file = request.FILES.get(item)\n ext = self.get_file_ext(file.name)\n\n if ext not in self.file_type or file.size > self.max_size:\n continue\n\n name = get_time_md5(file) + '.' + ext\n date_str = timezone.now().strftime('%Y%m%d')\n dir_name = '/' + date_str\n\n if request.user.is_authenticated():\n dir_name = '/user/' + str(request.user.id) + '/' + date_str\n path = path + dir_name\n\n info = {\n 'name': name,\n 'url': url + dir_name[1:] + '/' + name,\n 'size': file.size\n }\n\n ret.append(info)\n\n try:\n import os\n os.makedirs(path)\n except OSError:\n pass\n\n with open(path + '/' + name, 'wb+') as d:\n for chunk in file.chunks():\n d.write(chunk)\n return ret\n\n def _save_to_oss(self, request, name):\n from picopico.utils.aliyun.oss import Client\n client = Client(name=name)\n url = self.url if self.url else settings.ALIYUN_OSS_DOMAIN\n ret = []\n for item in request.FILES:\n file = request.FILES.get(item)\n ext = self.get_file_ext(file.name)\n\n if ext not in self.file_type or file.size > self.max_size:\n continue\n\n name = get_time_md5(file) + '.' + ext\n date_str = timezone.now().strftime('%Y%m%d')\n file_name = date_str\n\n if request.user.is_authenticated():\n file_name = 'user/' + request.user.get_id() + '/' + date_str\n oss_name = file_name + '/' + name\n\n else:\n oss_name = file_name + '/' + name\n\n info = {\n 'name': name,\n 'url': 'http://' + url + '/' + oss_name,\n 'size': file.size\n }\n\n ret.append(info)\n client.bucket.put_object(oss_name, file)\n return ret\n","sub_path":"picopico/apps/common/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":13998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"275904911","text":"\"\"\"\nRuns B-Tax with TCJA as baseline and 2017 law as the reform.\n------------------------------------------------------------------------\n\"\"\"\n# Import packages\nfrom btax.run_btax import run_btax, run_btax_with_baseline_delta\nfrom taxcalc import *\n\ntest_run = False # flag for test run (for Travis CI)\nstart_year = 2018\n\n# Note that TCJA is current law baseline in TC 0.16+\n# Thus to compare TCJA to 2017 law, we'll use 2017 law as the reform\nrec = Records.cps_constructor()\npol = Policy()\ncalc = Calculator(policy=pol, records=rec)\nref = calc.read_json_param_objects('2017_law.json', None)\niit_reform = ref['policy']\n\n# Run B-Tax\nrun_btax_with_baseline_delta(test_run, start_year, iit_reform, data='cps',\n btax_betr_corp=0.35, btax_depr_3yr_exp=50.,\n btax_depr_5yr_exp=50.,\n btax_depr_7yr_exp=50.,\n btax_depr_10yr_exp=50.,\n btax_depr_15yr_exp=50.,\n btax_depr_20yr_exp=50.)\n","sub_path":"run_examples/run_btax_example.py","file_name":"run_btax_example.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"579395596","text":"from commute_tube import CommuteTube\nimport argparse\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\n\tct = CommuteTube()\n\n\tparser.add_argument('-c', action='store_true', help='Check if USB pen is present')\n\targs = parser.parse_args()\n\n\tif (args.c == True):\n\t\tct.checkForPen()\n\telse:\n\t\tct.main()\n\n","sub_path":"commute_tube/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"73576266","text":"import numpy as np\nfrom scipy.ndimage.measurements import label\nimport xarray as xr\nimport os\nimport ipdb\nimport glob\nfrom scipy.interpolate import griddata\nimport pandas as pd\nimport ipdb\nimport itertools\nimport datetime\nfrom collections import OrderedDict\nfrom utils import constants as cnst, u_darrays as uda, u_interpolate as u_int\nimport matplotlib.pyplot as plt\nimport sys\n\ndef olr_to_bt(olr):\n sigma = 5.670373e-8\n return ((olr/sigma)**0.25)-273.15\n\ndef griddata_lin(data, x, y, new_x, new_y):\n\n \"\"\"\n :param x: current x variables (1 or 2d, definitely 2d if irregular!)\n :param y: current y variables (1 or 2d, definitely 2d if irregular!)\n :param new_x: target x vars\n :param new_y: target y vars\n :return: triangulisation lookup table, point weights, 2d shape - inputs for interpolation func\n \"\"\"\n\n if x.ndim == 1:\n grid_xs, grid_ys = np.meshgrid(x, y)\n else:\n grid_xs = x\n grid_ys = y\n\n if new_x.ndim == 1:\n new_xs, new_ys = np.meshgrid(new_x, new_y)\n else:\n new_xs = new_x\n new_ys = new_y\n\n points = np.array((grid_xs.flatten(), grid_ys.flatten())).T\n inter = np.array((np.ravel(new_xs), np.ravel(new_ys))).T\n shape = new_xs.shape\n\n # Interpolate using delaunay triangularization\n data = griddata(points, data.flatten(), inter, method='linear')\n data = data.reshape((shape[0], shape[1]))\n\n return data\n\ndef cut_kernel(array, xpos, ypos, dist_from_point):\n \"\"\"\n This function cuts out a kernel from an existing array and allows the kernel to exceed the edges of the input\n array. The cut-out area is shifted accordingly within the kernel window with NaNs filled in\n :param array: 2darray\n :param xpos: middle x point of kernel\n :param ypos: middle y point of kernel\n :param dist_from_point: distance to kernel edge to each side\n :return: 2d array of the chosen kernel size.\n \"\"\"\n\n if array.ndim != 2:\n raise IndexError('Cut kernel only allows 2D arrays.')\n\n kernel = np.zeros((dist_from_point*2+1, dist_from_point*2+1)) * np.nan\n\n if xpos - dist_from_point >= 0:\n xmin = 0\n xmindist = dist_from_point\n else:\n xmin = (xpos - dist_from_point) * -1\n xmindist = dist_from_point + (xpos - dist_from_point)\n\n if ypos - dist_from_point >= 0:\n ymin = 0\n ymindist = dist_from_point\n else:\n ymin = (ypos - dist_from_point) * -1\n ymindist = dist_from_point + (ypos - dist_from_point)\n\n if xpos + dist_from_point < array.shape[1]:\n xmax = kernel.shape[1]\n xmaxdist = dist_from_point + 1\n else:\n xmax = dist_from_point - (xpos - array.shape[1])\n xmaxdist = dist_from_point - (xpos + dist_from_point - array.shape[1])\n\n if ypos + dist_from_point < array.shape[0]:\n ymax = kernel.shape[0]\n ymaxdist = dist_from_point + 1\n else:\n ymax = dist_from_point - (ypos - array.shape[0])\n ymaxdist = dist_from_point - (ypos + dist_from_point - array.shape[0])\n\n cutk = array[ypos - ymindist: ypos + ymaxdist, xpos - xmindist: xpos + xmaxdist]\n\n\n kernel[ymin: ymax, xmin:xmax] = cutk\n\n return kernel\n\ndef cut_kernel_3d(array, xpos, ypos, dist_from_point):\n \"\"\"\n This function cuts out a kernel from an existing array and allows the kernel to exceed the edges of the input\n array. The cut-out area is shifted accordingly within the kernel window with NaNs filled in\n :param array: 2darray\n :param xpos: middle x point of kernel\n :param ypos: middle y point of kernel\n :param dist_from_point: distance to kernel edge to each side\n :return: 2d array of the chosen kernel size.\n \"\"\"\n\n if array.ndim != 3:\n raise IndexError('Cut kernel3d only allows 3D arrays.')\n\n kernel = np.zeros((array.shape[0], dist_from_point*2+1, dist_from_point*2+1)) * np.nan\n\n if xpos - dist_from_point >= 0:\n xmin = 0\n xmindist = dist_from_point\n else:\n xmin = (xpos - dist_from_point) * -1\n xmindist = dist_from_point + (xpos - dist_from_point)\n\n if ypos - dist_from_point >= 0:\n ymin = 0\n ymindist = dist_from_point\n else:\n ymin = (ypos - dist_from_point) * -1\n ymindist = dist_from_point + (ypos - dist_from_point)\n\n if xpos + dist_from_point < array.shape[2]:\n xmax = kernel.shape[2]\n xmaxdist = dist_from_point + 1\n else:\n xmax = dist_from_point - (xpos - array.shape[2])\n xmaxdist = dist_from_point - (xpos + dist_from_point - array.shape[2])\n\n if ypos + dist_from_point < array.shape[1]:\n ymax = kernel.shape[1]\n ymaxdist = dist_from_point + 1\n else:\n ymax = dist_from_point - (ypos - array.shape[1])\n ymaxdist = dist_from_point - (ypos + dist_from_point - array.shape[1])\n\n cutk = array[:, ypos - ymindist: ypos + ymaxdist, xpos - xmindist: xpos + xmaxdist]\n\n\n kernel[:, ymin: ymax, xmin:xmax] = cutk\n\n return kernel\n\n\ndef cut_box(xpos, ypos, arr, dist=None):\n \"\"\"\n\n :param xpos: x coordinate in domain for kernel centre point\n :param ypos: y coordinate in domain for kernel centre point\n :param arr: numpy array (2d)\n :param dist: distance from kernel centre point to kernel edge (total width = 2*dist+1)\n :return: the kernel of dimensions (2*dist+1, 2*dist+1)\n \"\"\"\n\n if dist == None:\n 'Distance missing. Please provide distance from kernel centre to edge (number of pixels).'\n return\n if arr.ndim == 3:\n kernel = cut_kernel_3d(arr, xpos, ypos, dist)\n if kernel.shape != (kernel.size[0], dist * 2 + 1, dist * 2 + 1):\n print(\"Please check kernel dimensions, there is something wrong\")\n ipdb.set_trace()\n else:\n kernel = cut_kernel(arr,xpos, ypos,dist)\n if kernel.shape != (dist * 2 + 1, dist * 2 + 1):\n print(\"Please check kernel dimensions, there is something wrong\")\n ipdb.set_trace()\n\n return kernel\n\n\ndef file_save(cp_dir, out_dir, ancils_dir, vars, datestring, box, tthresh, pos, lons, lats):\n\n keys = vars.keys()\n\n if 'lw_out_PBLtop' not in keys:\n print('please provide ORL first in dictionary')\n return\n\n\n goodinds = 0\n\n #create empty dataset\n ds = xr.Dataset()\n # create empty\n\n #loop through every var\n for idx, outv in enumerate(keys):\n\n print('Variable ', outv)\n vv = outv\n\n h = (vars[outv])[1]\n pl = (vars[outv])[0]\n\n inds = (vars[outv][2])[0]\n weights = (vars[outv][2])[1]\n shape = (vars[outv][2])[2]\n\n v = (vars[outv])[3]\n grid = (vars[outv])[4]\n\n try:\n filepath = glob.glob(cp_dir+os.sep+str(v)+os.sep+'*'+datestring+'*.nc')[0]\n except IndexError:\n #ipdb.set_trace()\n print('No file found, return')\n return\n\n try:\n arr = xr.open_dataset(filepath)\n except OSError:\n print('Cannot open file, continue! ', filepath)\n return\n dar = arr[v].sel(longitude=slice(box[0],box[1]), latitude=slice(box[2],box[3]))\n if outv == 'lsRain_noon':\n dum = dar[dar['time.hour'] == h].squeeze()\n dar = dar[(dar['time.hour'] <= h) & (dar['time.hour'] >= h-2)].sum('time').squeeze() # early rain accumulation over 3h\n dar = dar.assign_coords(coords={'time' : dum.time})\n del dum\n else:\n dar = dar[dar['time.hour'] == h].squeeze()\n\n del arr\n\n if (v == 'q_pl') | (v=='t_pl') | (v=='lw_out_PBLtop'):\n dar.values = np.array(dar.values/100).astype(float)\n\n\n #if int(dar['time.hour'])!=h:\n # ipdb.set_trace()\n # print('Wrong hour')\n # return\n\n if 'pressure' in dar.coords:\n try:\n dar.values[dar.values==0] = np.nan # potential missing value maskout\n except ValueError:\n print('Pressure value error!')\n return\n if (len(pl) > 1) & (outv == 'shear'):\n\n shear = dar.sel(pressure=650).values - dar.sel(pressure=925).values\n dar = dar.sum(dim='pressure').squeeze()\n dar.values = shear\n\n elif (len(pl) == 1) & (outv != 'shear'):\n dar = dar.sel(pressure=pl[0]).squeeze()\n\n\n # regrid to common grid (unstagger wind, bring to landsea mask grid)\n if grid == 'srfc':\n try:\n #regrid = griddata_lin(dar.values, dar.longitude, dar.latitude, ls_arr.rlon, ls_arr.rlat)\n\n regrid = u_int.interpolate_data(dar.values, inds, weights, shape)\n\n except ValueError:\n ipdb.set_trace()\n\n # if v == 'sh': # potential calculation of SH climatology around SH date. Not finished\n #\n # ddate = dar.time.values.item()\n # dt = datetime.datetime(ddate.year, ddate.month, ddate.day,\n # ddate.hour, ddate.minute, ddate.second)\n #\n # window1 = dt - pd.Timedelta('7days')\n # window2 = dt + pd.Timedelta('7days')\n #\n # doi = pd.date_range(window1, window2)\n # c1ds = []\n # for doi_id in doi:\n #\n # cdate = str(doi_id.year) + str(doi_id.month).zfill(2) + str(doi_id.day).zfill(2) + '0030'\n #\n # try:\n # c1 = xr.open_dataarray(glob.glob(data_path + '/sh/*_'+cdate+'-*.nc')[0])\n # c1ds.append(c1)\n # except:\n # pass\n # if len(c1ds) < 10:\n # print('Not enough dates to calc sh clim')\n # return\n #\n # ipdb.set_trace()\n # shmean = xr.concat(c1ds, dim='time').mean('time')\n\n\n da = xr.DataArray(regrid,\n coords={'time': dar.time, 'latitude': pl_dummy.latitude.values,\n 'longitude': pl_dummy.longitude.values, },\n dims=['latitude', 'longitude'])\n da.attrs = dar.attrs\n else:\n da = xr.DataArray(dar.values,\n coords={'time': dar.time, 'latitude': pl_dummy.latitude.values,\n 'longitude': pl_dummy.longitude.values, },\n dims=['latitude', 'longitude'])\n da.attrs = dar.attrs\n\n da.values[pos[0], pos[1]] = np.nan # mask sea\n\n if (v == 'lw_out_PBLtop') & (idx == 0):\n\n da.values[da.values >= tthresh] = 0 # T threshold maskout\n da.values[np.isnan(da.values)] = 0 # set ocean nans to 0\n\n\n # try:\n # date = da.time.values[0]\n # except IndexError:\n # date = da.time.values\n\n date = pd.Timestamp(datestring)\n date = date.replace(hour=h)\n\n labels, numL = label(da.values)\n\n u, inv = np.unique(labels, return_inverse=True)\n n = np.bincount(inv)\n\n goodinds = u[n >= 258] # defines minimum MCS size e.g. 350 km2 = 39 pix at 3x3km res (258 pix at 4.4km is 5000km2) 52 pix is 1000km2 for cp4\n if not sum(goodinds) > 0:\n print('No goodinds!')\n return\n \n\n if (v == 'lsRain') | (v == 'totRain'):\n da.values = da.values*3600 # rain to mm/h\n da.attrs['units'] = 'mm h-1'\n\n ds[outv] = da\n\n print('Saved ', outv, h)\n\n\n for gi in goodinds:\n if (gi == 0): # index 0 is always background, ignore!\n continue\n inds = np.where(labels == gi)\n # cut a box for every single blob from msg - get min max lat lon of the blob\n latmax, latmin = np.nanmax(lats[inds]), np.nanmin(lats[inds])\n lonmax, lonmin = np.nanmax(lons[inds]), np.nanmin(lons[inds])\n mask = np.where(labels!=gi)\n\n dbox = ds.copy(deep=True)\n\n for vout in dbox.data_vars:\n if vout not in ['lsRain','lw_out_PBLtop']:\n continue\n (dbox[vout].values)[mask] = np.nan\n\n ds_box = dbox.sel(latitude=slice(latmin,latmax), longitude=slice(lonmin, lonmax))\n try:\n if np.nansum(ds_box['lsRain'])==0:\n return\n except KeyError:\n if np.nansum(ds_box['totRain'])==0:\n return\n\n #if np.nansum(ds_box['lwout_noon'])<=0:\n # ipdb.set_trace()\n # print('lwout is lt 0', np.nansum(ds_box['lwout_noon']))\n # return\n\n savefile = out_dir + os.sep + date.strftime('%Y-%m-%d_%H:%M:%S') + '_' + str(gi) + '.nc'\n try:\n os.remove(savefile)\n except OSError:\n pass\n\n ds_box.to_netcdf(path=savefile, mode='w')\n print('Saved ' + savefile)\n print('Saved MCS no.'+str(gi)+ ' as netcdf.')\n\n\n### Inputs:\n##### Provide hour when you run script!!! as sys.argv[1]\nfdir = str(sys.argv[2])\nif fdir == 'CP4hist':\n ftag = 'historical'\nelse:\n ftag = 'future'\n\nmain = cnst.lmcs_drive + 'CP_models'\ndata_path = main + '/CP4_WestAfrica/'+fdir\nancils_path = main + '/CP4_WestAfrica/ANCILS'\nout_path = main + '/MCS_files/MODELS/CP4_test/CP4_allHours_'+ftag+'_5000km2_-50_WAf'\nbox = [-18, 25, 4, 25] # W- E , S - N geographical coordinates box\n\nyears = np.array(np.arange(1998,2007), dtype=str)\nmonths = ([ '06', '07', '08', '09'])\ndays = np.array(np.arange(1,32), dtype=str)\n\ntthresh = -50 # chosen temperature threshold, e.g. -50, -60, -70\nh= int(sys.argv[1]) # hour to extract\n\nplglob = glob.glob(data_path + '/q_pl/*.nc')\n\npl_dummy = xr.open_dataset(plglob[0])\n\nsrfcglob = glob.glob(data_path + '/lw_out_PBLtop/*.nc')\nsrfc_dummy = xr.open_dataset(srfcglob[0])\n\npl_dummy = pl_dummy.sel(longitude=slice(box[0],box[1]), latitude=slice(box[2],box[3]))\nsrfc_dummy = srfc_dummy.sel(longitude=slice(box[0],box[1]), latitude=slice(box[2],box[3]))\n# load seamask\nlandsea_path = glob.glob(ancils_path + os.sep + 'landseamask*.nc')[0]\nlandsea = xr.open_dataset(landsea_path, decode_times=False)\nls = landsea['lsm']\n\nls = ls.assign_coords(rlon = ls.rlon.values - 360)\nls_arr = ls.sel(rlon=slice(box[0], box[1]), rlat=slice(box[2], box[3]))\n###########\ntopo_path = glob.glob(ancils_path + os.sep + 'orog_combined*.nc')[0]\ntopo = xr.open_dataset(topo_path, decode_times=False)\ntop = topo['ht']\n\ntop = top.assign_coords(rlon = top.rlon.values - 360)\ntop_arr = top.sel(rlon=slice(box[0], box[1]), rlat=slice(box[2], box[3]))\n##########\n\npos = np.where(ls_arr[0, 0, :, :] == 0)\nlons, lats = np.meshgrid(pl_dummy.longitude.values, pl_dummy.latitude.values)#np.meshgrid(ls_arr.rlon.values, ls_arr.rlat.values)\n\n#plinds, plweights, plshape = u_int.interpolation_weights(pl_dummy.longitude, pl_dummy.latitude, ls_arr.rlon, ls_arr.rlat)\ninds, weights, shape = u_int.interpolation_weights(srfc_dummy.longitude, srfc_dummy.latitude, pl_dummy.longitude, pl_dummy.latitude)\n#regrid = griddata_lin(dar.values, dar.longitude, dar.latitude, ls_arr.rlon, ls_arr.rlat)\n\n\nvars = OrderedDict() # dictionary which contains info on pressure level and hour extraction for wanted variables\nvars['lw_out_PBLtop'] = ([], h, (inds,weights,shape), 'lw_out_PBLtop', 'srfc') ### Input in BRIGHTNESS TEMPERATURES!! (degC)\nvars['lsRain'] = ([], h, (inds,weights,shape), 'lsRain', 'srfc') # pressure levels, hour\nvars['shear'] = ([650, 925], 12, (0, 0, 0), 'u_pl', '') # (plinds, plweights, plshape) should use 925 later\nvars['u_mid'] = ([650], 12, (0, 0, 0), 'u_pl', '')\nvars['u_srfc'] = ([925], 12, (0, 0, 0), 'u_pl', '')\nvars['q_mid'] = ([650], 12, (0, 0, 0), 'q_pl', '') # INPUT IN T * 100!!\nvars['t_mid'] = ([650], 12, (0, 0, 0), 't_pl', '') # INPUT IN T * 100!!\nvars['t_low'] = ([850], 12, (0, 0, 0), 't_pl', '')\nvars['t_srfc'] = ([925], 12, (0, 0, 0), 't_pl', '')\nvars['q_srfc'] = ([925], 12, (0, 0, 0), 'q_pl', '')\nvars['tcwv'] = ([], 12, (inds,weights,shape), 'tcwv', 'srfc')\nvars['sh'] = ([], 12, (inds,weights,shape), 'sh', 'srfc')\nvars['lh'] = ([], 12, (inds,weights,shape), 'lh', 'srfc')\nvars['t2'] = ([], 12, (inds,weights,shape), 't2', 'srfc')\nvars['q2'] = ([], 12, (inds,weights,shape), 'q2', 'srfc')\nvars['lsRain_noon'] = ([], 12, (inds,weights,shape), 'lsRain', 'srfc')\nvars['lwout_noon'] = ([], 12, (inds,weights,shape), 'lw_out_PBLtop', 'srfc')\n\ndatelist = []\nfor y,m,d in itertools.product(years, months, days):\n datelist.append(y+m+str(d).zfill(2))\n\nfor d in datelist:\n\n testfiles = glob.glob(out_path + os.sep + d[0:4] + '-' + d[4:6] + '-' + d[6:8] + '_' + str(h) + '*.nc')\n\n if len(testfiles) > 0:\n print(testfiles[0], ' already exists, continue!')\n continue\n\n\n file_save(data_path, out_path, ancils_path, vars, d, box, tthresh, pos, lons, lats)\n\n# for d in datelist[0:10]:\n#\n# if (d['time.year']<1998) | (d['time.month']<3) | (d['time.month']>11):\n# continue\n# file_save(data_path, out_path, ancils_path, vars, d, box, tthresh)\n\n","sub_path":"GLOBAL/saveMCS_CP4_storm.py","file_name":"saveMCS_CP4_storm.py","file_ext":"py","file_size_in_byte":17026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"549046981","text":"# steamshovel/python/artists/HoleIce.py\n\nfrom icecube.shovelart import *\nfrom icecube.dataclasses import I3Constants\nfrom icecube import dataclasses\n\nclass HoleIce(PyArtist):\n\n numRequiredKeys = 0\n requiredTypes = [ dataclasses.I3VectorI3Position, dataclasses.I3VectorFloat ]\n\n def __init__(self):\n PyArtist.__init__(self)\n # self.defineSettings( { \"Show ice\": True, \"Show bedrock\": True, \"Linewidth\":RangeSetting(.1,10.,1000,100) } )\n\n def description( self ):\n return \"Hole Ice Cylinder\"\n\n # @param PyArtist self\n # @param I3Frame frame\n # @param SceneGroup output\n #\n def create( self, frame, output ):\n\n hole_ice_cylinder_positions = frame[list(self.keys())[0]]\n hole_ice_cylinder_radii = frame[list(self.keys())[1]]\n\n bedrock_z = -I3Constants.OriginElev\n ice_top_z = I3Constants.zIceTop\n\n for i, position in enumerate(hole_ice_cylinder_positions):\n radius = hole_ice_cylinder_radii[i]\n\n # If z is given, draw a cylinder of 1m height.\n # If z is 0, draw a cylinder from the very top to the very bottom.\n #\n # See: https://github.com/fiedl/hole-ice-study/issues/34\n #\n if position.z == 0:\n\n position_vec = vec3d(position.x, position.y, bedrock_z)\n cylinder = output.addCylinder(\n position_vec, # Vertex\n vec3d(0, 0, ice_top_z - bedrock_z), # Axes\n radius, # Base Radius\n radius # Top Radius\n )\n cylinder.setColor(PyQColor(255, 255, 255, 120))\n\n else:\n\n position_vec = vec3d(position.x, position.y, position.z - 0.5)\n cylinder = output.addCylinder(\n position_vec, # Vertex\n vec3d(0, 0, 1.0), # Axes\n radius, # Base Radius\n radius # Top Radius\n )\n cylinder.setColor(PyQColor(255, 255, 255, 120))\n","sub_path":"patches/steamshovel/python/artists/HoleIce.py","file_name":"HoleIce.py","file_ext":"py","file_size_in_byte":2216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"465874132","text":"def prime(n):\r\n if n==1:\r\n return False\r\n elif n==2:\r\n return True\r\n else:\r\n for x in range(2,n):\r\n if(n%x==0):\r\n return False\r\n return True\r\nprint(prime(8))\r\n\r\nlst=list(range(1,2500))\r\nprint(lst)\r\n#prime(lst)\r\n\r\nans=[]\r\nlst_out=filter(prime,lst)\r\nprint(list(lst_out))\r\n \r\n","sub_path":"letsUpgrade_day5(2).py","file_name":"letsUpgrade_day5(2).py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"298170098","text":"#!/usr/bin/env python\n# SPDX-License-Identifier: Apache-2.0\n\n# encoding: utf-8\n\"\"\"\nlogstat.py\n\n# CDDL HEADER START\n#\n# The contents of this file are subject to the terms of the\n# Common Development and Distribution License, Version 1.0 only\n# (the \"License\"). You may not use this file except in compliance\n# with the License.\n#\n# You can obtain a copy of the license at\n# http://forgerock.org/license/CDDLv1.0.html.\n# See the License for the specific language governing permissions\n# and limitations under the License.\n#\n# When distributing Covered Code, include this CDDL HEADER in each\n# file and include the License file at\n# trunk/opends/resource/legal-notices/OpenDS.LICENSE. If applicable,\n# add the following below this CDDL HEADER, with the fields enclosed\n# by brackets \"[]\" replaced with your own identifying information:\n# Portions Copyright [yyyy] [name of copyright owner]\n#\n# CDDL HEADER END\n#\n#\n# Copyright 2012 ForgeRock Inc.\n\nCreated by Ludovic Poitou on 2012-01-10.\n\nThis program reads OpenDJ access logs and output statistics.\n\"\"\"\n\nimport getopt\nimport re\nimport sys\n\nhelp_message = \"\"\"\nUsage: logstat.py [options] file [file ...]\noptions:\n\\t -a SLA : specifies the SLA in milliseconds\n\\t -s operation(s) : specifies which operations to compute stat for.\n\\t -o output : specifies the output file, otherwise stdout is used\n\\t -r : include replicated operations\n\\t -v : verbose mode\n\n\"\"\"\n\n\nclass OpStat:\n def __init__(self, type, sla):\n self.type = type\n self.count = long(0)\n self.etime = long(0)\n self.maxEtime = long(0)\n self.SLA = sla\n self.countOverSLA = long(0)\n self.countOver10SLA = long(0)\n self.retEntries = long(0)\n self.count0Entries = long(0)\n self.count1Entry = long(0)\n self.maxEntries = long(0)\n\n def incEtime(self, etime):\n self.etime += etime\n self.count += 1\n if self.maxEtime < etime:\n self.maxEtime = etime\n if etime > self.SLA:\n self.countOverSLA += 1\n if etime > self.SLA * 10:\n self.countOver10SLA += 1\n\n def incEntries(self, count):\n self.retEntries += count\n if self.maxEntries < count:\n self.maxEntries = count\n if count == 0:\n self.count0Entries += 1\n if count == 1:\n self.count1Entry += 1\n\n def printStats(self, outfile):\n if self.count != 0:\n outfile.write(\n self.type\n + \":\\t\"\n + str(self.count)\n + \"\\tAvg: \"\n + str(round(float(self.etime) / float(self.count), 3))\n + \" ms\\tMax: \"\n + str(self.maxEtime)\n + \" ms\\t>\"\n + str(self.SLA)\n + \"ms: \"\n + str(self.countOverSLA)\n + \" (\"\n + str(self.countOverSLA * 100 / self.count)\n + \"%)\\t>\"\n + str(self.SLA * 10)\n + \"ms: \"\n + str(self.countOver10SLA)\n + \" (\"\n + str(self.countOver10SLA * 100 / self.count)\n + \"%)\\n\"\n )\n if self.retEntries != 0:\n outfile.write(\n self.type\n + \":\\tReturned \"\n + str(round(float(self.retEntries) / float(self.count), 1))\n + \" entries in average, max: \"\n + str(self.maxEntries)\n + \", none: \"\n + str(self.count0Entries)\n + \", single: \"\n + str(self.count1Entry)\n + \"\\n\"\n )\n\n\nclass Usage(Exception):\n def __init__(self, msg):\n self.msg = msg\n\n\ndef main(argv=None):\n output = \"\"\n ops = \"\"\n includeReplOps = False\n sla = 100\n doSearch = True\n doAdd = True\n doBind = True\n doCompare = True\n doDelete = True\n doExtended = True\n doModify = True\n doModDN = True\n\n if argv is None:\n argv = sys.argv\n try:\n try:\n opts, args = getopt.getopt(argv[1:], \"a:ho:rs:v\", [\"help\", \"output=\"])\n except getopt.error as msg:\n raise Usage(msg)\n\n # option processing\n for option, value in opts:\n if option == \"-v\":\n pass\n if option == \"-r\":\n includeReplOps = True\n if option in (\"-h\", \"--help\"):\n raise Usage(help_message)\n if option in (\"-o\", \"--output\"):\n output = value\n if option in (\"-s\", \"--stats\"):\n ops = value\n if option in (\"-a\", \"--agreement\"):\n sla = int(value)\n\n except Usage as err:\n print >>sys.stderr, sys.argv[0].split(\"/\")[-1] + \": \" + str(err.msg)\n print >>sys.stderr, \"\\t for help use --help\"\n return 2\n\n if output != \"\":\n try:\n outfile = open(output, \"w\")\n except Usage as err:\n print >>sys.stderr, \"Can't open output file: \" + str(err.msg)\n else:\n outfile = sys.stdout\n\n if ops != \"\":\n doSearch = False\n doAdd = False\n doBind = False\n doCompare = False\n doDelete = False\n doExtended = False\n doModify = False\n doModDN = False\n opers = ops.split(\",\")\n for op in opers:\n if op == \"Search\":\n doSearch = True\n continue\n if op == \"Add\":\n doAdd = True\n continue\n if op == \"Bind\":\n doBind = True\n continue\n if op == \"Compare\":\n doCompare = True\n continue\n if op == \"Delete\":\n doDelete = True\n continue\n if op == \"Extended\":\n doExtended = True\n continue\n if op == \"Modify\":\n doModify = True\n continue\n if op == \"ModDN\":\n doModDN = True\n continue\n print >>sys.stderr, \"Invalid op name in stats: \" + op + \", ignored\"\n\n searches = OpStat(\"Search\", sla)\n adds = OpStat(\"Add\", sla)\n binds = OpStat(\"Bind\", sla)\n compares = OpStat(\"Compare\", sla)\n deletes = OpStat(\"Delete\", sla)\n extops = OpStat(\"Extend\", sla)\n modifies = OpStat(\"Modify\", sla)\n moddns = OpStat(\"ModDN\", sla)\n\n for logfile in args:\n try:\n infile = open(logfile, \"r\")\n except err:\n print >>sys.stderr, \"Can't open file: \" + str(err.msg)\n\n outfile.write(\"processing file: \" + logfile + \"\\n\")\n for i in infile:\n if re.search(\" conn=-1 \", i) and not includeReplOps:\n continue\n if doSearch and re.search(\"SEARCH RES\", i):\n m = re.match(\".*nentries=(\\d+) etime=(\\d+)\", i)\n if m:\n searches.incEtime(int(m.group(2)))\n searches.incEntries(int(m.group(1)))\n if doAdd and re.search(\"ADD RES\", i):\n m = re.match(\".* etime=(\\d+)\", i)\n if m:\n adds.incEtime(int(m.group(1)))\n if doBind and re.search(\"BIND RES\", i):\n m = re.match(\".* etime=(\\d+)\", i)\n if m:\n binds.incEtime(int(m.group(1)))\n if doCompare and re.search(\"COMPARE RES\", i):\n m = re.match(\".* etime=(\\d+)\", i)\n if m:\n compares.incEtime(int(m.group(1)))\n if doDelete and re.search(\"DELETE RES\", i):\n m = re.match(\".* etime=(\\d+)\", i)\n if m:\n deletes.incEtime(int(m.group(1)))\n if doExtended and re.search(\"EXTENDED RES\", i):\n m = re.match(\".* etime=(\\d+)\", i)\n if m:\n extops.incEtime(int(m.group(1)))\n if doModify and re.search(\"MODIFY RES\", i):\n m = re.match(\".* etime=(\\d+)\", i)\n if m:\n modifies.incEtime(int(m.group(1)))\n if doModDN and re.search(\"MODDN RES\", i):\n m = re.match(\".* etime=(\\d+)\", i)\n if m:\n moddns.incEtime(int(m.group(1)))\n\n # Done processing that file, lets move to next one\n\n # We're done with all files. Proceed with displaying stats\n adds.printStats(outfile)\n binds.printStats(outfile)\n compares.printStats(outfile)\n deletes.printStats(outfile)\n extops.printStats(outfile)\n modifies.printStats(outfile)\n moddns.printStats(outfile)\n searches.printStats(outfile)\n outfile.write(\"Done\\n\")\n outfile.close()\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"modules/openstack/files/yoga/admin_scripts/wmcs-logstat.py","file_name":"wmcs-logstat.py","file_ext":"py","file_size_in_byte":8724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"416867194","text":"\"\"\"Performs face alignment and calculates L2 distance between the embeddings of two images.\"\"\"\n\n# MIT License\n# \n# Copyright (c) 2016 David Sandberg\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\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport argparse\nimport os\nimport sys\n\nimport align_dlib\nimport detect_face\nimport facenet\nimport numpy as np\nimport tensorflow as tf\nfrom scipy import misc\n\n\ndef main(args):\n\n if args.align_method == 'mtcnn':\n input_images = load_and_align_data_mtcnn(args.input_dir, args.image_size, args.margin,\n args.gpu_memory_fraction, args.prealigned_scale)\n target_images = load_and_align_data_mtcnn(args.target_dir,args.image_size, args.margin,\n args.gpu_memory_fraction, args.prealigned_scale)\n\n else:\n input_images = load_and_align_data_dlib(args.input_dir, args.image_size,\n args.dlib_face_predictor, args.prealigned_scale)\n target_images = load_and_align_data_dlib(args.target_dir, args.image_size,\n args.dlib_face_predictor, args.prealigned_scale)\n\n\n nrof_input_images = len(os.listdir(os.path.expanduser(args.input_dir)))\n nrof_target_images = len(os.listdir(os.path.expanduser(args.target_dir)))\n images_index = [None] * (nrof_input_images+nrof_target_images)\n for i in range(nrof_input_images+nrof_target_images):\n if i < nrof_input_images:\n images_index[i] = input_images[i]\n else:\n images_index[i] = target_images[i-nrof_input_images]\n images = np.stack(images_index)\n\n with tf.Graph().as_default():\n\n with tf.Session() as sess:\n\n # Load the model\n # print('Model directory: %s' % args.model_dir)\n meta_file, ckpt_file = facenet.get_model_filenames(os.path.expanduser(args.model_dir))\n # print('Metagraph file: %s' % meta_file)\n # print('Checkpoint file: %s' % ckpt_file)\n facenet.load_model(args.model_dir, meta_file, ckpt_file)\n\n # Get input and output tensors\n # images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n images_placeholder = tf.get_default_graph().get_tensor_by_name(\"image_batch:0\")\n embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n\n # Run forward pass to calculate embeddings\n feed_dict_input = {images_placeholder: images, phase_train_placeholder: False}\n emb = sess.run(embeddings, feed_dict=feed_dict_input)\n\n # nrof_input_images = len(os.listdir(os.path.expanduser(args.input_dir)))\n # nrof_target_images = len(os.listdir(os.path.expanduser(args.target_dir)))\n\n input_dataset = facenet.get_folder_file(args.input_dir)\n target_dataset = facenet.get_folder_file(args.target_dir)\n\n print('Input Images:')\n for i in range(nrof_input_images):\n print('%1d: %s' % (i, os.path.expanduser(input_dataset[i])))\n print('')\n\n print('Compare Images:')\n for i in range(nrof_input_images, nrof_target_images + nrof_input_images):\n print('%1d: %s' % (i, os.path.expanduser(target_dataset[i - nrof_input_images])))\n print('')\n\n # Print distance matrix\n print('Distance matrix')\n print('Compare Image', end='')\n for i in range(nrof_input_images):\n print(' %1d ' % i, end='')\n print('')\n for i in range(nrof_input_images, nrof_target_images + nrof_input_images):\n # print(emb[i, :]) Target_image_embeddings\n print('%1d ' % i, end='')\n for j in range(nrof_input_images):\n # print(emb[j, :]) Input_Image_embeddings\n dist = np.sqrt(np.sum(np.square(np.subtract(emb[i, :], emb[j, :]))))\n print(' %1.5f ' % dist, end='')\n print('')\n\n\n\ndef load_and_align_data_mtcnn(dir, image_size, margin, gpu_memory_fraction, prealigned_scale):\n\n minsize = 80 # minimum size of face\n threshold = [0.6, 0.7, 0.7] # three steps's threshold\n factor = 0.709 # scale factor\n\n with tf.Graph().as_default():\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)\n sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))\n with sess.as_default():\n pnet, rnet, onet = detect_face.create_mtcnn(sess, '../data/')\n\n dataset = facenet.get_folder_file(dir)\n nrof_samples = len((os.listdir(os.path.expanduser(dir))))\n img_list = [None] * nrof_samples\n for i in xrange(nrof_samples):\n img = misc.imread(os.path.expanduser(dataset[i]))\n if img.ndim == 2:\n img = facenet.to_rgb(img)\n img = img[:, :, 0:3]\n\n bounding_boxes, _ = detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)\n nrof_faces = bounding_boxes.shape[0]\n if nrof_faces > 0:\n det = bounding_boxes[:, 0:4]\n img_size = np.asarray(img.shape)[0:2]\n if nrof_faces > 1:\n bounding_box_size = (det[:, 2] - det[:, 0]) * (det[:, 3] - det[:, 1])\n img_center = img_size / 2\n offsets = np.vstack(\n [(det[:, 0] + det[:, 2]) / 2 - img_center[1], (det[:, 1] + det[:, 3]) / 2 - img_center[0]])\n offset_dist_squared = np.sum(np.power(offsets, 2.0), 0)\n index = np.argmax(bounding_box_size - offset_dist_squared * 2.0) # some extra weight on the centering\n det = det[index, :]\n det = np.squeeze(bounding_boxes[0, 0:4])\n bb = np.zeros(4, dtype=np.int32)\n bb[0] = np.maximum(det[0] - margin / 2, 0)\n bb[1] = np.maximum(det[1] - margin / 2, 0)\n bb[2] = np.minimum(det[2] + margin / 2, img_size[1])\n bb[3] = np.minimum(det[3] + margin / 2, img_size[0])\n cropped = img[bb[1]:bb[3], bb[0]:bb[2], :]\n aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')\n prewhitened = facenet.prewhiten(aligned)\n # plt.imshow(prewhitened)\n img_list[i] = prewhitened\n else:\n print('Unable to align \"%s\"' % dataset[i])\n scaled = misc.imresize(img, prealigned_scale, interp='bilinear')\n sz1 = int(scaled.shape[1] / 2)\n sz2 = int(image_size / 2)\n cropped = scaled[(sz1 - sz2):(sz1 + sz2), (sz1 - sz2):(sz1 + sz2), :]\n aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')\n prewhitened = facenet.prewhiten(aligned)\n # plt.imshow(prewhitened)\n img_list[i] = prewhitened\n images = np.stack(img_list)\n return images\n\n\n\ndef load_and_align_data_dlib(dir, image_size, dlib_face_predictor, prealigned_scale):\n\n align = align_dlib.AlignDlib(os.path.expanduser(dlib_face_predictor))\n landmarkIndices = align_dlib.AlignDlib.OUTER_EYES_AND_NOSE\n\n minsize = 80 # minimum size of face\n scale = float(minsize) / image_size\n dataset = facenet.get_folder_file(dir)\n nrof_samples = len(os.listdir(os.path.expanduser(dir)))\n img_list = [None] * nrof_samples\n\n for i in xrange(nrof_samples):\n # print(input_dataset[i])\n img = misc.imread(os.path.expanduser(dataset[i]))\n if img.ndim == 2:\n img = facenet.to_rgb(img)\n img = img[:, :, 0:3]\n\n dets = align.getAllFaceBoundingBoxes(img)\n nrof_faces = len(dets)\n if nrof_faces > 0:\n cropped = align.align(image_size, img, landmarkIndices=landmarkIndices,\n skipMulti=False, scale=scale)\n else:\n scaled = misc.imresize(img, prealigned_scale, interp='bilinear')\n sz1 = int(scaled.shape[1] / 2)\n sz2 = int(image_size / 2)\n cropped = scaled[(sz1 - sz2):(sz1 + sz2), (sz1 - sz2):(sz1 + sz2), :]\n #if center_crop:\n # scaled = misc.imresize(img, center_crop, interp='bilinear')\n # sz1 = int(scaled.shape[1] / 2) # MacOX need int, while Linux don't need\n # sz2 = int(image_size / 2) # MacOX need int, while Linux don't need\n # cropped = scaled[(sz1 - sz2):(sz1 + sz2), (sz1 - sz2):(sz1 + sz2), :]\n #else:\n if cropped is not None:\n aligned = misc.imresize(cropped, (image_size, image_size), interp='bilinear')\n prewhitened = facenet.prewhiten(aligned)\n #plt.imshow(prewhitened)\n #filename = os.path.splitext(os.path.split(input_dataset[i])[1])[0]\n #output_filename = os.path.join(test_input_folders, filename + '.png')\n #misc.imsave(output_filename, prewhitened)\n img_list[i] = prewhitened\n images = np.stack(img_list)\n return images\n\n\ndef parse_arguments(argv):\n parser = argparse.ArgumentParser()\n\n parser.add_argument('model_dir', type=str,\n help='Directory containing the meta_file and ckpt_file')\n parser.add_argument('input_dir', type=str,\n help='Input Directory of Images to compare')\n parser.add_argument('target_dir', type=str,\n help='Target Directory of Images to compare')\n parser.add_argument('--dlib_face_predictor', type=str,\n help='File containing the dlib face predictor.', default='../data/shape_predictor_68_face_landmarks.dat')\n parser.add_argument('--image_size', type=int,\n help='Image size (height, width) in pixels.', default=160)\n parser.add_argument('--align_method', type=str, choices=['mtcnn', 'dlib'],\n help='Face align and load algorithm to use', default='dlib')\n parser.add_argument('--margin', type=int,\n help='Margin for the crop around the bounding box (height, width) in pixels.', default=44)\n parser.add_argument('--gpu_memory_fraction', type=float,\n help='Upper bound on the amount of GPU memory that will be used by the process.', default=1.0)\n parser.add_argument('--prealigned_scale', type=float,\n help='The amount of scaling to apply to prealigned images before taking the center crop.', default=0.87)\n return parser.parse_args(argv)\n\n\nif __name__ == '__main__':\n main(parse_arguments(sys.argv[1:]))","sub_path":"src/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":11662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"525938722","text":"from django.urls import path\nfrom .views import LoginView, LogoutView, SignupView, AuthorListView, AuthorUpdateView, AuthorDeleteView\n\nurlpatterns = [\n path('login/', LoginView.as_view(), name='login'),\n path('logout/', LogoutView.as_view(), name='logout'),\n path('signup/', SignupView.as_view(), name='signup'),\n path('authors/', AuthorListView.as_view(), name='author_list'),\n path('authors//edit/', AuthorUpdateView.as_view(), name='author_update'),\n path('authors//delete/', AuthorDeleteView.as_view(), name='author_delete'),\n]\n","sub_path":"core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"367427304","text":"'''This script demonstrates how to build a variational autoencoder with Keras.\n\n #Reference\n\n - Auto-Encoding Variational Bayes\n https://arxiv.org/abs/1312.6114\n'''\nfrom __future__ import print_function\nimport matplotlib\nmatplotlib.use('Agg')\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\nfrom keras.layers import Input, Dense, Lambda\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras import metrics\nfrom keras.datasets import mnist\nimport math\nimport random\nimport os\nbatch_size = 100\noriginal_dim = 784\nlatent_dim = 2\nintermediate_dim = 256\nepochs = 50\nepsilon_std = 1.0\n\n\nk_constants = [0 for i in range(latent_dim)]\nx = Input(shape=(original_dim,))\nh = Dense(intermediate_dim, activation='relu')(x)\nz_mean = Dense(latent_dim)(h)\n# z_log_var = Dense(latent_dim)(h)\nz_log_var = Input(tensor=K.variable(k_constants))\n\n# z_log_var = Dense(latent_dim, activation='relu')(z_log_var)\n\ndef sampling(args):\n z_mean, z_log_var = args\n epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim), mean=0.,\n stddev=epsilon_std)\n return z_mean + K.exp(z_log_var / 2) * epsilon\n\nz = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])\n\n# we instantiate these layers separately so as to reuse them later\ndecoder_h = Dense(intermediate_dim, activation='relu')\ndecoder_mean = Dense(original_dim, activation='sigmoid')\nh_decoded = decoder_h(z)\nx_decoded_mean = decoder_mean(h_decoded)\n\n# instantiate VAE model\nvae = Model([x, z_log_var], x_decoded_mean)\n\n# Compute VAE loss\nxent_loss = original_dim * metrics.binary_crossentropy(x, x_decoded_mean)\nkl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)\nvae_loss = K.mean(xent_loss + kl_loss)\n\nvae.add_loss(vae_loss)\nvae.compile(optimizer='rmsprop')\nvae.summary()\n\n\n# train the VAE on MNIST digits\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nx_train = x_train.astype('float32') / 255.\nx_test = x_test.astype('float32') / 255.\nx_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))\nx_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))\n\nvae.fit(x_train,\n shuffle=True,\n epochs=epochs,\n batch_size=batch_size,\n validation_data=(x_test, None))\n\nprint(\"#####\")\n\ntest_digits_mean = {}\n# test_digits_var = {}\ntest_digits_z = {}\n\n\nencoder = Model([x, z_log_var], [z_mean, z], name='encoder')\npredictions = encoder.predict(x_test)\n\nwhile True:\n r1 = int(math.floor(random.random() *len(y_test)))\n r2 = int(math.floor(random.random() *len(y_test)))\n if y_test[r1] != y_test[r2]:\n p1 = predictions[1][r1]\n p2 = predictions[1][r2]\n print(\"choson digits are: {} {}\".format(y_test[r1],y_test[r2]))\n f=open(\"//home//hag007//ex4py//f_e_digits\", 'w+')\n f.write(\"choson digits are: {} {}\".format(y_test[r1],y_test[r2]))\n f.close()\n break\n\nzs = []\nfor i in range(10):\n zs.append([min(p1[0], p2[0])+(random.random() * abs(p1[0] - p2[0])),\n min(p1[1], p2[1])+random.random() * abs(p1[1] - p2[1])])\n\n\nprint(zs)\ndecoder_input = Input(shape=(latent_dim,))\n_h_decoded = decoder_h(decoder_input)\n_x_decoded_mean = decoder_mean(_h_decoded)\ngenerator = Model(inputs=decoder_input, outputs= _x_decoded_mean)\n\nz_sample = np.array(zs)\nx_decoded = generator.predict(z_sample)\nprint(x_decoded)\n\n\n# display reconstruction\nfor i, cur in enumerate(x_decoded):\n plt.imshow(cur.reshape(28, 28))\n plt.gray()\n if not os.path.exists(\"output\"):\n os.mkdir(\"output\")\n plt.savefig(\"output/f_e_{}.png\".format(i))\n","sub_path":"code/f_e.py","file_name":"f_e.py","file_ext":"py","file_size_in_byte":3603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"276842051","text":"from collections import deque\nfrom numpy import mean\n\n\n# https://docs.python.org/2/library/collections.html\ndef moving_average(iterable, n=3):\n # moving_average([40, 30, 50, 46, 39, 44]) --> 40.0 42.0 45.0 43.0\n # http://en.wikipedia.org/wiki/Moving_average\n from itertools import islice\n\n it = iter(iterable)\n d = deque(islice(it, n - 1))\n d.appendleft(0)\n s = sum(d)\n for elem in it:\n s += elem - d.popleft()\n d.append(elem)\n yield s / float(n)\n\n\nclass sma(object):\n \"\"\"Simple moving average\"\"\"\n\n n = 200\n\n def __init__(self, n=None):\n n = n or self.n\n self.q = deque(maxlen=n)\n\n def __call__(self, x):\n self.q.append(x)\n return mean(self.q)\n\n\nclass ema(object):\n \"\"\"\\\n Exponential moving average\n\n define\n w := weight = 2/(N+1), hence 1-weight = (N-1)/(N+1)\n x := new value\n a := exponential moving average\n\n formula\n a = a*(1-w)+x*w = a+(x-a)*w\n \"\"\"\n\n n = 200 # this is the same `N' in weight formula\n\n a = 0.0\n flag = True # to indicate if this is the first time calling\n\n def __init__(self, n=None, weight=None, warmup=None):\n from itertools import chain, repeat\n from numpy import linspace\n\n if weight is None:\n n = n or self.n\n w = 2.0 / (n + 1)\n else:\n assert 0.0 <= weight <= 1.0\n w = weight\n # the weight effect fully kicks in after warmup number of periods\n if warmup:\n assert warmup >= 0\n self.w = chain(linspace(1 - w, w, warmup), repeat(w))\n else: # warmup is None / warmup is False / warmup == 0\n self.w = repeat(w)\n\n def __call__(self, x):\n if self.flag:\n self.flag = False # set the flag\n self.a = x\n return x\n self.a += (x - self.a) * self.w.next()\n return self.a\n\n @property\n def value(self):\n return self.a\n\n","sub_path":"ti/ma.py","file_name":"ma.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"570182605","text":"\"\"\"Widgets for Curses-based CLI.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport curses\nfrom tvm.contrib.debugger.curses.ui import ui_common\n\nRL = ui_common.RichLine\nEXIT_TEXT = \"exit\"\nHOME_TEXT = \"HOME\"\nHELP_TEXT = \"help\"\nTVM_DBG_BOX_BOTTOM = \"-----------------\"\nNAVIGATION_MENU_COLOR_ATTR = \"white_on_black\"\n\nclass NavigationHistoryItem(object):\n \"\"\"Individual item in navigation history.\"\"\"\n\n def __init__(self, command, screen_output, scroll_position):\n \"\"\"Constructor of NavigationHistoryItem.\n\n Parameters\n ----------\n command: (`str`) the command line text.\n screen_output: the screen output of the command.\n scroll_position: (`int`) scroll position in the screen output.\n \"\"\"\n self.command = command\n self.screen_output = screen_output\n self.scroll_position = scroll_position\n\n\nclass CursesNavigationHistory(object):\n \"\"\"Navigation history containing commands, outputs and scroll info.\"\"\"\n\n BACK_ARROW_TEXT = \"<--\"\n FORWARD_ARROW_TEXT = \"-->\"\n\n def __init__(self, capacity):\n \"\"\"Constructor of CursesNavigationHistory.\n\n Parameters\n ----------\n capacity: (`int`) How many items this object can hold. Each item consists\n of a command stirng, an output RichTextLines object and a scroll\n position.\n\n Raises:\n ValueError: If capacity is not a positive number.\n \"\"\"\n if capacity <= 0:\n raise ValueError(\"In valid capacity value: %d\" % capacity)\n\n self._capacity = capacity\n self._items = []\n self._pointer = -1\n\n def add_item(self, command, screen_output, scroll_position):\n \"\"\"Add an item to the navigation histoyr.\n\n Parameters\n ----------\n command: command line text.\n screen_output: screen output produced for the command.\n scroll_position: (`int`) scroll position in the screen output.\n \"\"\"\n if self._pointer + 1 < len(self._items):\n self._items = self._items[:self._pointer + 1]\n self._items.append(\n NavigationHistoryItem(command, screen_output, scroll_position))\n if len(self._items) > self._capacity:\n self._items = self._items[-self._capacity:]\n self._pointer = len(self._items) - 1\n\n def update_scroll_position(self, new_scroll_position):\n \"\"\"Update the scroll position of the currently-pointed-to history item.\n\n Parameters\n ----------\n new_scroll_position: (`int`) new scroll-position value.\n\n Raises:\n ValueError: If the history is empty.\n \"\"\"\n if not self._items:\n raise ValueError(\"Empty navigation history\")\n self._items[self._pointer].scroll_position = new_scroll_position\n\n def size(self):\n \"\"\"Get the size of widget items from list.\n\n Returns:\n ('int') length of widget items list.\n \"\"\"\n return len(self._items)\n\n def pointer(self):\n \"\"\"Get curses widget pointer.\n\n Returns:\n The pointer value.\n \"\"\"\n return self._pointer\n\n def go_back(self):\n \"\"\"Go back one place in the history, if possible.\n\n Decrease the pointer value by 1, if possible. Otherwise, the pointer value\n will be unchanged.\n\n Returns:\n The updated pointer value.\n\n Raises:\n ValueError: If history is empty.\n \"\"\"\n if not self._items:\n raise ValueError(\"Empty navigation history\")\n\n if self.can_go_back():\n self._pointer -= 1\n return self._items[self._pointer]\n\n def go_forward(self):\n \"\"\"Go forward one place in the history, if possible.\n\n Increase the pointer value by 1, if possible. Otherwise, the pointer value\n will be unchanged.\n\n Returns:\n The updated pointer value.\n\n Raises:\n ValueError: If history is empty.\n \"\"\"\n if not self._items:\n raise ValueError(\"Empty navigation history\")\n\n if self.can_go_forward():\n self._pointer += 1\n return self._items[self._pointer]\n\n def can_go_back(self):\n \"\"\"Test whether client can go back one place.\n\n Returns:\n (`bool`) Whether going back one place is possible.\n \"\"\"\n return self._pointer >= 1\n\n def can_go_forward(self):\n \"\"\"Test whether client can go forward one place.\n\n Returns:\n (`bool`) Whether going back one place is possible.\n \"\"\"\n return self._pointer + 1 < len(self._items)\n\n def can_go_home(self):\n \"\"\"Test whether client can go home place.\n\n Returns:\n (`bool`) Whether going back home place is possible.\n \"\"\"\n if self._pointer >= 0:\n if self._items[self._pointer].command == \"HOME\":\n return False\n return True\n else:\n return False\n\n def can_go_help(self):\n \"\"\"Test whether client can go help place.\n\n Returns:\n (`bool`) Whether going back help place is possible.\n \"\"\"\n if self._pointer >= 0:\n if self._items[self._pointer].command == \"help\":\n return False\n return True\n else:\n return False\n\n def get_latest_command_info(self):\n \"\"\"Get the latest command information.\n\n Returns:\n (`string`) Return the recent command shortcut.\n \"\"\"\n return self._items[self._pointer].command\n\n def render(self,\n max_length,\n backward_command,\n forward_command,\n home_command,\n help_command,\n exit_command):\n \"\"\"Render the rich text content of the single-line navigation bar.\n\n Parameters\n ----------\n max_length: (`int`) Maximum length of the navigation bar, in characters.\n backward_command: (`str`) command for going backward. Used to construct\n the shortcut menu item.\n forward_command: (`str`) command for going forward. Used to construct the\n shortcut menu item.\n\n Returns:\n (`ui_common.RichTextLines`) the navigation bar text with\n attributes.\n\n \"\"\"\n output = RL(\"| \", NAVIGATION_MENU_COLOR_ATTR)\n output += RL(HOME_TEXT,\n (ui_common.MenuItem(None, home_command,\n custom_color=NAVIGATION_MENU_COLOR_ATTR)\n if self.can_go_home() else NAVIGATION_MENU_COLOR_ATTR))\n output += RL(\" | \", NAVIGATION_MENU_COLOR_ATTR)\n\n output += RL(self.BACK_ARROW_TEXT,\n (ui_common.MenuItem(None, backward_command,\n custom_color=NAVIGATION_MENU_COLOR_ATTR)\n if self.can_go_back() else NAVIGATION_MENU_COLOR_ATTR))\n output += RL(\" \", NAVIGATION_MENU_COLOR_ATTR)\n output += RL(self.FORWARD_ARROW_TEXT,\n (ui_common.MenuItem(None, forward_command,\n custom_color=NAVIGATION_MENU_COLOR_ATTR)\n if self.can_go_forward() else NAVIGATION_MENU_COLOR_ATTR))\n\n output_end = RL(\"| \", NAVIGATION_MENU_COLOR_ATTR)\n output_end += RL(HELP_TEXT,\n (ui_common.MenuItem(None, help_command,\n custom_color=NAVIGATION_MENU_COLOR_ATTR)\n if self.can_go_help() else NAVIGATION_MENU_COLOR_ATTR))\n output_end += RL(\" | \", NAVIGATION_MENU_COLOR_ATTR)\n output_end += RL(EXIT_TEXT,\n ui_common.MenuItem(None, exit_command,\n custom_color=NAVIGATION_MENU_COLOR_ATTR))\n output_end += RL(\" |\", NAVIGATION_MENU_COLOR_ATTR)\n\n output_middle = RL(\"\", NAVIGATION_MENU_COLOR_ATTR)\n if (len(output)+len(output_end)) < max_length:\n space_need_size = max_length - len(output + output_end)\n if space_need_size > len(TVM_DBG_BOX_BOTTOM):\n space_need_size -= len(TVM_DBG_BOX_BOTTOM)\n space_middle_size = int(space_need_size/2)\n empty_line = (\" \" * (space_middle_size - (0 if space_need_size%2 else 1))\n + TVM_DBG_BOX_BOTTOM + \" \" * space_middle_size)\n output_middle = RL(empty_line, NAVIGATION_MENU_COLOR_ATTR)\n else:\n empty_line = \"-\" * space_need_size\n output_middle = RL(empty_line, NAVIGATION_MENU_COLOR_ATTR)\n\n return ui_common.rich_text_lines_frm_line_list(\n [output + output_middle + output_end], additional_attr=curses.A_BOLD)\n","sub_path":"ncurses/ui/curses_widgets.py","file_name":"curses_widgets.py","file_ext":"py","file_size_in_byte":8837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"581794119","text":"from sqlalchemy import (\n Column,\n Integer,\n String,\n Text,\n Float,\n Boolean,\n Table,\n ForeignKey,\n Enum,\n Float,\n Date,\n DateTime\n )\n\nfrom sqlalchemy.ext.hybrid import (\n Comparator, \n hybrid_property,\n )\n\nfrom sqlalchemy.orm import (\n relationship,\n backref\n )\n\nfrom . import Base\n\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom zope.sqlalchemy import ZopeTransactionExtension\nfrom project.models.arrivals import Arrival\n\n\nclass Employee(Base):\n __tablename__ = 'employee'\n id = Column(Integer, primary_key=True)\n name = Column(String)\n surname = Column(String)\n \n boss = Column(String)\n residence = Column(String)\n merital_status = Column(String) \n sex = Column(String)\n age = Column(Integer)\n by_user_id = Column(Integer, ForeignKey('user.id'), index=True)\n user = relationship('User')\n position_id = Column(Integer, ForeignKey('Employees_type.id'), index=True)\n position = relationship('Employees_type', backref=backref(\"Employees_type\", cascade=\"all, delete-orphan\"))\n hash1 = Column(Integer);\n hash2 = Column(Integer);\n \n # sentiment = Column(Float)\n # article_id= Column(Integer, ForeignKey('article.id'), index=True)\n # article=relationship('Article', backref=backref(\"feedbacks\", cascade=\"all, delete-orphan\"))\n \n\n def __init__(self, by_user, name, surname, position, age , merital_status =None, sex =None, residence=None):\n self.user = by_user\n self.name = name\n self.surname = surname\n self.position = position\n self.age = age \n self.boss = None\n self.residence = residence\n self.merital_status = merital_status\n self.sex = sex\n self.full_name = self.name + \" \" + self.surname\n\n def is_in_work(self, request):\n users_departures = request.db_session.query(Arrival.departure).filter(Arrival.employee_id == self.id).all()\n for departure in users_departures:\n if departure[0] == None:\n return True\n else:\n pass\n if users_departures == []:\n pass\n\n return False","sub_path":"2etapa/models/employee.py","file_name":"employee.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"568207346","text":"#EXTERNAL\nfrom datetime import datetime, timedelta, date\nimport time\nimport random\nimport os\nfrom lxml import html\nimport requests\nimport datetime\nimport pymysql as mysql\nfrom requests_html import HTMLSession\nfrom PIL import Image, ImageDraw, ImageFont\nfrom io import BytesIO\nimport json\nfrom sklearn import ensemble\nfrom sklearn.model_selection import train_test_split\n\n#INTERNAL\nimport scraperPortalML_OR\nimport uf\nimport sendmail\nimport pubPortalExiste\nimport pubYapoExiste\nimport agentCreator\nimport pdfCreatorFichasv2 as pdfCreatorFichas\nimport reportesHuberV1 as reportes\n\n\n#VALUE SETTING\nsession = HTMLSession()\nfechahoy = datetime.datetime.now()\nfechahoy=str(fechahoy.year)+'-'+str(fechahoy.month)+'-'+str(fechahoy.day)\nuf1=uf.getUf()\npast = datetime.now() - timedelta(days=180)\npast=datetime.date(past)\nyesterday = datetime.now() - timedelta(days=10)\nyesterday=datetime.date(yesterday)\n\nheaders = {\n 'authority': 'www.portalinmobiliario.com',\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 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36',\n 'sec-fetch-user': '?1',\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,/;q=0.8,application/signed-exchange;v=b3',\n 'sec-fetch-site': 'same-origin',\n 'sec-fetch-mode': 'navigate',\n 'referer': 'https://www.portalinmobiliario.com/',\n 'accept-encoding': 'gzip, deflate, br',\n 'accept-language': 'es-US,es;q=0.9,es-419;q=0.8,en;q=0.7',\n 'cookie': '_d2id=2f52a2ad-2dc1-4db9-ba16-afa9d3030d06-n; _csrf=znVPWlbzP11aMD2-q_Mmr8tQ; c_home=0.20.0%7C5.3.3; pin_d2id=; pin_exp=new; _d2id=2f52a2ad-2dc1-4db9-ba16-afa9d3030d06; _pi_ga=GA1.2.346434101.1572221445; _pi_ga_gid=GA1.2.700821714.1572221445; _pi_ci=346434101.1572221445; _hjid=df262c46-fd11-46f6-9807-0d9cd4bd7878; searchbox-currentSearch=eyJvcGVyYXRpb25zIjp7ImxhYmVsIjoiVmVudGEiLCJzZWxlY3RlZCI6InZlbnRhIn0sImNhdGVnb3JpZXMiOnsibGFiZWwiOiJEZXBhcnRhbWVudG9zIiwic2VsZWN0ZWQiOiJ2ZW50YV9kZXBhcnRhbWVudG8ifSwibG9jYXRpb24iOnsidmFsdWUiOiJWYWxwYXJh7XNvIiwic2VsZWN0ZWQiOiJUVXhEVUZaQlRFODRNRFZqIn0sImZpbHRlci1uZXciOnsiY2hlY2tlZCI6ZmFsc2UsImRpc2FibGVkIjpmYWxzZX19; _mlt=6a66608b-edb2-40c7-bb49-6a89232f6276',\n}\ndef obtainPropFromPortal(link):\n\n try:\n request = requests.get(link, headers=headers)\n operacion=(request.request.url.split(\"/\")[3])\n tipo=(request.request.url.split(\"/\")[3])\n region=(request.request.url.split(\"/\")[5]).split(\"-\")[1]\n except:\n time.sleep(random.randint(60,90))\n request = requests.get(link, headers=headers)\n return False\n\n try:\n tree = html.fromstring(request.content)\n except:\n # print(\"Fallo.\")\n return False\n\n priceSymbolPath = '//*[@id=\"productInfo\"]/fieldset/span/span[1]'\n\n pricePath = '//*[@id=\"productInfo\"]/fieldset/span/span[2]'\n namePath = '//*[@id=\"short-desc\"]/div/header/h1'\n addressPath = '//*[@id=\"root-app\"]/div/div/div[1]/div[3]/section/div[1]/div/h2'\n\n priceSymbol = tree.xpath(priceSymbolPath)\n if len(priceSymbol) == 0:\n return False\n priceSymbol = priceSymbol[0].text\n price = tree.xpath(pricePath)\n if len(price) == 0:\n return False\n price = int(price[0].text.replace(',','').replace(' ','').replace('.',''))\n\n if priceSymbol == 'UF':\n price = price*uf\n\n name = tree.xpath(namePath)\n if len(name) == 0:\n return False\n name = name[0].text.replace('\\n','').replace('\\t','')\n\n address = tree.xpath(addressPath)\n if len(address) == 0:\n\n address = '-'\n else:\n address = address[0].text\n\n #fecha\n datePosition = request.text.find('

Fecha de Publicación

')\n if datePosition == -1:\n\n date = \"00-00-0000\"\n else:\n date = request.text[datePosition+60:datePosition+70]\n dateSplit = date.split('-')\n date = dateSplit[2] + '-' + dateSplit[1] + '-' + dateSplit[0]\n\n #metraje, estacionamientos, bodegas\n htmlArray = request.text.split('
  • ')\n maxMeters = 0\n minMeters = 0\n estacionamientos = 0\n bodegas = 0\n\n minMetersFound = maxMetersFound = estacionamientosFound = bodegasFound = False\n\n try:\n for j, element in enumerate(htmlArray):\n if j == len(htmlArray)-1:\n #last element, we have to split again.\n element = element.split('')[0]\n if \"Superficie total\" in element and not maxMetersFound:\n maxMeters = int(float(element.split('span')[1][1:-5]))\n maxMetersFound = True\n elif \"Superficie útil\" in element and not minMetersFound:\n minMeters = element.split('span')[1][1:-5]\n minMetersFound = True\n elif \"Estacionamientos\" in element and not estacionamientosFound:\n estacionamientos = int(float(element.split('span')[1].replace('<','').replace('>','').replace('/','')))\n estacionamientosFound = True\n elif \"Bodegas\" in element and not bodegasFound:\n bodegas = int(float(element.split('span')[1].replace('<','').replace('>','').replace('/','')))\n bodegasFound = True\n except:\n return False\n\n\n if maxMeters != 0 and minMeters == 0:\n minMeters = maxMeters\n if minMeters != 0 and maxMeters == 0:\n maxMeters = minMeters\n\n #baños y dormitorios\n try:\n item1xpath = '//*[@id=\"productInfo\"]/div[1]/dl[1]/dd'\n item2xpath = '//*[@id=\"productInfo\"]/div[1]/dl[2]/dd'\n item3xpath = '//*[@id=\"productInfo\"]/div[1]/dl[3]/dd'\n itemUniquexpath = '//*[@id=\"productInfo\"]/div[1]/dl/dd'\n\n item1 = tree.xpath(item1xpath)\n item2 = tree.xpath(item2xpath)\n item3 = tree.xpath(item3xpath)\n itemU = tree.xpath(itemUniquexpath)\n\n item1 = item1[0].text if len(item1) > 0 else ''\n item2 = item2[0].text if len(item2) > 0 else ''\n item3 = item3[0].text if len(item3) > 0 else ''\n itemU = itemU[0].text if len(itemU) > 0 else ''\n\n if \"dormitorio\" in item1:\n dorms = int(item1.split(' ')[0])\n elif \"dormitorio\" in item2:\n dorms = int(item2.split(' ')[0])\n elif \"dormitorio\" in item3:\n dorms = int(item3.split(' ')[0])\n elif \"dormitorio\" in itemU:\n dorms = int(itemU.split(' ')[0])\n elif \"priva\" in item1:\n dorms = int(item1.split(' ')[0])\n elif \"priva\" in item2:\n dorms = int(item2.split(' ')[0])\n elif \"priva\" in item3:\n dorms = int(item3.split(' ')[0])\n elif \"priva\" in itemU:\n dorms = int(itemU.split(' ')[0])\n else:\n dorms = 0\n\n if \"baño\" in item1:\n baths = int(item1.split(' ')[0])\n elif \"baño\" in item2:\n baths = int(item2.split(' ')[0])\n elif \"baño\" in item3:\n baths = int(item3.split(' ')[0])\n elif \"baño\" in itemU:\n baths = int(itemU.split(' ')[0])\n else:\n baths = 0\n except:\n return False\n\n\n #lat, lon\n mapPosition = request.text.find(\"center=\")\n if mapPosition == -1:\n\n lat = 0\n lon = 0\n else:\n amperPosition = request.text[mapPosition:].find('&')\n mapTexts = request.text[mapPosition:mapPosition+amperPosition].replace(\"center=\",'').split('%2C')\n lat = float(mapTexts[0])\n lon = float(mapTexts[1])\n\n fechascrap = str(datetime.datetime.now().year) + '-' + str(datetime.datetime.now().month) + '-' + str(datetime.datetime.now().day)\n\n propiedad = []\n\n try:\n code = int(link.split('/')[6].split('-')[0])\n except Exception as err:\n try:\n code = int(link.split('/')[3].split('-')[1])\n except Exception as err2:\n return False\n\n #text mining para bodegas\n if bodegas == 0:\n descripcion_xpath = '//*[@id=\"description-includes\"]/div/p'\n descripcion_result = tree.xpath(descripcion_xpath)\n if len(descripcion_result)>0:\n bodegas = scraperPortalML_OR.obtenerBodegas(descripcion_result[0].text)\n\n # text mining para estacionamientos\n if estacionamientos == 0:\n descripcion_xpath = '//*[@id=\"description-includes\"]/div/p'\n descripcion_result = tree.xpath(descripcion_xpath)\n if len(descripcion_result) > 0:\n estacionamientos = scraperPortalML_OR.obtenerBodegas(descripcion_result[0].text)\n\n sql = \"SELECT nombre,region,operacion,tipo,precio,dormitorios,banos,metrosmin,metrosmax,estacionamientos,bodegas,lat,lon,link from portalinmobiliario WHERE id2=\"+str(id)\n\n\n propiedad.append(name)\n propiedad.append(region)\n propiedad.append(operacion)\n propiedad.append(tipo)\n propiedad.append(price)\n propiedad.append(dorms)\n propiedad.append(baths)\n propiedad.append(minMeters)\n propiedad.append(maxMeters)\n propiedad.append(estacionamientos)\n propiedad.append(bodegas)\n propiedad.append(lat)\n propiedad.append(lon)\n propiedad.append(link)\n\n return propiedad\n\ndef obtainPropFromYapo(link):\n\n codigo = -1\n idregion = -1\n comuna = \"\"\n tipo = \"\"\n titulo = \"\"\n operacion=\"\"\n preciouf = -1\n preciopesos= -1\n fechapublicacion = \"\"\n fechahoy = datetime.datetime.now()\n fechascrap=str(fechahoy.year)+'-'+str(fechahoy.month)+'-'+str(fechahoy.day)\n metrosmin = -1\n metrosmax = -1\n dormitorios = -1\n banos = -1\n descripcion = \"\"\n lat = -999\n lon = -999\n anoconstruccion = -1\n ggcc = -1\n estacionamientos = 0\n\n esdueno = 0\n\n page = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()})\n tree = html.fromstring(page.content)\n\n url=[]\n metatext=page.text\n metatext=metatext.split(' ')\n descripcion=[]\n savedescripcion=False\n saveimg=False\n og=True\n telefono = 'NN'\n\n precio1=tree.xpath('//*[@id=\"content\"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/strong')\n precio2=tree.xpath('//*[@id=\"content\"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/span/span')\n\n '//*[@id=\"content\"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/strong'\n '//*[@id=\"content\"]/section[1]/article/div[5]/div[1]/table/tbody/tr[1]/td/div/span/span'\n\n if len(precio1)<0:\n return False\n\n if len(precio2) == 0:\n print(\"Error al sacar el precio en \" + link)\n return False\n\n if ('$') in precio2[0].text:\n preciopesos=precio2[0].text\n preciouf=precio1[0].text\n else:\n preciopesos=precio1[0].text\n preciouf=precio2[0].text\n\n\n\n\n preciopesos=preciopesos.replace('.','')\n preciopesos=preciopesos.replace('$','')\n preciopesos=preciopesos.replace(' ','')\n preciopesos=preciopesos.replace(')','')\n preciopesos=preciopesos.replace('(','')\n preciopesos=preciopesos.replace('*','')\n preciopesos=int(preciopesos)\n\n preciouf=preciouf.replace('.','')\n preciouf=preciouf.replace('$','')\n preciouf=preciouf.replace(' ','')\n preciouf=preciouf.replace(')','')\n preciouf=preciouf.replace('(','')\n preciouf=preciouf.replace('*','')\n preciouf=preciouf.replace('UF','')\n preciouf=preciouf.replace(',','.')\n preciouf=float(preciouf)\n\n #extraccion codigo\n aux = link.split('.')\n aux = aux[-2]\n aux = aux.split('_')\n codigo = int(aux[-1])\n\n utag_data = tree.xpath(\"/html/body/script[1]/text()\")[0]\n text = str(utag_data.split('=')[1])\n text = text[:-5] + \"}\"\n\n try:\n value = json.loads(text)\n except:\n return False\n\n\n try:\n idregion = value[\"region_level2_id\"].lower()\n except:\n pass\n try:\n comuna = value[\"region_level3\"].lower()\n except:\n pass\n try:\n titulo = value[\"ad_title\"].lower()\n except:\n pass\n try:\n if value[\"category_level2\"]==\"Vendo\":\n operacion = \"venta\"\n elif value[\"category_level2\"]==\"Arriendo\":\n operacion = \"arriendo\"\n elif value[\"category_level2\"]==\"Arriendo de temporada\":\n operacion = \"temporada\"\n except:\n pass\n try:\n fechapublicacion = value[\"publish_date\"].split(' ')[0]\n except:\n pass\n try:\n dormitorios = int(value[\"rooms\"])\n except:\n pass\n try:\n descripcion = value[\"description\"]\n except:\n pass\n\n try:\n if int(value[\"geoposition_is_precise\"]) == 1:\n pos = value[\"geoposition\"].split(',')\n lat = float(pos[0])\n lon = float(pos[1])\n except:\n pass\n\n tabla = tree.xpath(\"\"\"//*[@id=\"content\"]/section[1]/article/div[5]/div[1]/table/tbody/tr\"\"\")\n tabla.pop(0)\n\n for row in tabla:\n rowname = row.find(\"th\").text\n if rowname == \"Tipo de inmueble\":\n tipo = row.find(\"td\").text\n elif rowname == \"Superficie total\":\n metrosmax = row.find(\"td\").text.replace('\\n','').replace('\\t','').split(' ')[0]\n elif rowname == \"Superficie útil\" or rowname == \"Superficie construida\":\n metrosmin = row.find(\"td\").text.replace('\\n','').replace('\\t','').split(' ')[0]\n elif rowname == \"Baños\":\n banos = row.find(\"td\").text\n banos = int(str(banos.split(' ')[0]))\n elif rowname == \"Estacionamiento\":\n estacionamientos = row.find(\"td\").text\n elif rowname == \"Año de construcción\":\n anoconstruccion = row.find(\"td\").text\n elif rowname == \"Gastos comunes\":\n ggcc = row.find(\"td\").text[2:]\n ggcc = ggcc.replace('.','')\n ggcc = float(ggcc)\n\n\n try:\n propiedad = []\n propiedad.append(titulo)\n propiedad.append(idregion)\n propiedad.append(operacion.lower())\n propiedad.append(tipo.lower())\n propiedad.append(preciopesos)\n propiedad.append(int(float(dormitorios)))\n propiedad.append(int(float(banos)))\n propiedad.append(int(float(metrosmin)))\n propiedad.append(int(float(metrosmax)))\n propiedad.append(int(float(estacionamientos)))\n propiedad.append(int(float(estacionamientos)))\n propiedad.append(lat)\n propiedad.append(lon)\n propiedad.append(link)\n propiedad.append(comuna)\n return propiedad\n except Exception as err:\n print(\"Error en propiedad:\" + link + \" \\n \" + str(err))\n return False\n\n\ndef obtenerProp(id,sitio):\n\n if 'portal' in sitio:\n mariadb_connection = mysql.connect(user='root', password='sergei', host='127.0.0.1', database='bullestate')\n cur = mariadb_connection.cursor()\n sql = \"SELECT nombre,region,operacion,tipo,precio,dormitorios,banos,metrosmin,metrosmax,estacionamientos,bodegas,lat,lon,link from portalinmobiliario WHERE id2=\"+str(id)\n else:\n mariadb_connection = mysql.connect(user='root', password='sergei', host='127.0.0.1', database='yapo')\n cur = mariadb_connection.cursor()\n sql = \"SELECT titulo,idregion,operacion,tipo,preciopesos,dormitorios,banos,metrosmin,metrosmax,estacionamientos,estacionamientos,lat,lon,link,comuna from propiedades WHERE id2=\"+str(id)\n print(sql)\n cur.execute(sql)\n propiedad = cur.fetchall()\n print(propiedad)\n if len(propiedad)>0:\n return propiedad[0]\n else:\n return propiedad\n\ndef crearFicha(sitio,id,mail,tipoficha):\n links=[]\n text2=''\n auxPhone=0\n #Determinar tipo de informe\n pro=False\n interna=False\n financiera=False\n textmail=''\n ufn=uf.getUf()\n if tipoficha>4:\n financiera=True\n tipoficha=tipoficha-4\n if tipoficha==2:\n pro=True\n elif tipoficha==3:\n interna=True\n elif tipoficha==4:\n interna=True\n pro=True\n\n\n #Chequear que sitio este bien\n sitio=sitio.lower()\n\n if('portal' in sitio):\n sitio='portal'\n elif('yapo' in sitio):\n sitio='yapo'\n else:\n text='Sitio ingresado es incorrecto. Favor ingresar portalinmobiliario o yapo.'\n return(text)\n #Chequear que mail este bien\n if ('@' not in mail):\n text='Email incorrecto. Favor ingresar correo válido.'\n return(text)\n if ('.' not in mail):\n text='Email incorrecto. Favor ingresar correo válido.'\n return(text)\n\n #sacar informacion de bbdd, y chequear que propiedad existe:\n propiedad=obtenerProp(id,sitio)\n print(propiedad)\n\n if len(propiedad)<1:\n\n if sitio=='portal':\n link=\"https://www.portalinmobiliario.com/\"+str(id)\n else:\n link=\"https://www.yapo.cl/region_metropolitana/\"+str(id)\n\n if not pubPortalExiste.publicacionExiste(link) and not pubYapoExiste.publicacionExiste(link):\n text='¨Propiedad no se encuentra en la base de datos.'\n return(text)\n elif sitio==\"portal\":\n pass\n else:\n if obtainPropFromYapo(link) is not False:\n propiedad=obtainPropFromYapo(link)\n\n\n else:\n regYapoDict={\n \"metropolitana\":\"15\",\n \"valparaiso\":\"6\",\n \"Valparaíso\":\"6\",\n \"arica\":\"1\",\n \"iquique\":\"2\",\n \"antofagasta\":\"3\",\n \"atacama\":\"4\",\n \"coquimbo\":\"5\",\n \"ohiggins\":\"7\",\n \"maule\":\"8\",\n \"ñuble\":\"16\",\n \"biobio\":\"9\",\n \"araucania\":\"10\",\n \"los Rios\":\"11\",\n \"los Lagos\":\"12\",\n \"aysen\":\"13\",\n \"magallanes\":\"14\",\n\n }\n\n propiedad=list(propiedad)\n\n region=str(propiedad[1])\n regionP=region\n regionY=regYapoDict[region.lower()]\n if region=='15':\n regionP='metropolitana'\n if region=='metropolitana':\n regionY='15'\n operacion=str(propiedad[2])\n tipo=str(propiedad[3])\n precio=float(propiedad[4])\n dormitorios=str(propiedad[5])\n banos=str(propiedad[6])\n metrosmin=str(propiedad[7])\n metrosmax=str(propiedad[8])\n estacionamientos=str(propiedad[9])\n bodegas=str(propiedad[10])\n lat=str(propiedad[11])\n lon=str(propiedad[12])\n link=str(propiedad[13])\n if sitio=='portal':\n if operacion=='venta':\n comuna=str(link.split('/')[5])\n comuna=comuna.replace('-'+str(regionP),'')\n comuna=comuna.replace('-',' ')\n comuna=comuna.capitalize()\n propiedad.append(comuna)\n\n else:\n comuna=str(link.split('/')[6])\n comuna=comuna.replace('-metropolitana','')\n comuna=comuna.replace('-',' ')\n comuna=comuna.capitalize()\n propiedad.append(comuna)\n else:\n comuna=str(propiedad[14])\n #Revisar si existe aun la publicacion\n if not pubPortalExiste.publicacionExiste(link):\n text='Propiedad ya no se encuentra disponible en el sitio.'\n return(text)\n #sacar informacion de la publicacion\n #sacar urls fotos portal\n matrixdescripcion=[]\n matrixcounter=0\n matrixdescripcion.append('')\n\n if sitio=='portal':\n first=True\n url=[]\n page = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()})\n metatext=page.text\n metatext=metatext.split(' ')\n descripcion=[]\n savedescripcion=False\n for texto in metatext:\n\n if 'item-description__text' in texto:\n savedescripcion=True\n if '/div' in texto:\n if savedescripcion:\n descripcion.append(str(texto))\n savedescripcion = False\n if savedescripcion:\n descripcion.append(str(texto))\n\n descripcion2=descripcion.copy()\n\n first=(descripcion2[0])\n first=first.split(\">\")\n print(first)\n first=first[2]\n descripcion[0]=first\n\n last=descripcion2[-1]\n last=last.split(\"<\")\n last=last[0]\n descripcion[-1]=last\n\n #descripcion=descripcion[2:]\n print(descripcion)\n descripcion=list(descripcion)\n\n if not interna:\n for desc in descripcion:\n desc=desc.replace(' ','')\n desc=desc.replace('
    ',' ')\n desc=desc.replace('
    ',' ')\n desc=desc.replace('
    ',' ')\n desc=desc.replace('','')\n desc=desc.replace('','')\n desc=desc.replace('','')\n desc=desc.replace('','')\n desc=desc.replace('í','í')\n desc=desc.replace('é','é')\n desc=desc.replace('ó','ó')\n desc=desc.replace('á','á')\n desc=desc.replace('ú','ú')\n desc=desc.replace('ñ','ñ')\n desc=desc.replace('Ñ','Ñ')\n\n if \"+56\" in desc:\n desc=\"**\"\n if len(desc)>=6:\n try:\n desc.replace('\\n',\"\")\n int(desc)\n desc=\"**\"\n except:\n pass\n\n if \"@\" in desc:\n desc=\"***\"\n\n if ((len(matrixdescripcion[matrixcounter])+len(desc))>=78):\n\n matrixcounter+=1\n matrixdescripcion.append('')\n if desc!= '':\n matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc)\n else:\n if first:\n if desc!= '':\n matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc)\n first=False\n else:\n if desc!= '':\n matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+' '+str(desc)\n print(matrixdescripcion)\n for x,matrix in enumerate(matrixdescripcion):\n matrix=matrix.replace('
    ','\\n')\n matrix=matrix.replace('
    ','\\n')\n matrix=matrix.replace('
    ','\\n')\n matrix=matrix.replace('','')\n matrix=matrix.replace('','')\n matrix=matrix.replace('','')\n matrixdescripcion[x]=matrix\n descripcion='\\n'.join(matrixdescripcion)\n propiedad.append(descripcion)\n\n else:\n descripcion=' '.join(descripcion)\n descripcion=descripcion.replace(' ','')\n descripcion=descripcion.replace('
    ','\\n')\n descripcion=descripcion.replace('
    ','\\n')\n descripcion=descripcion.replace('
    ','\\n')\n descripcion=descripcion.replace('','')\n descripcion=descripcion.replace('','')\n descripcion=descripcion.replace('','')\n descripcion=descripcion.replace('','')\n descripcion=descripcion.replace('í','í')\n descripcion=descripcion.replace('é','é')\n descripcion=descripcion.replace('ó','ó')\n descripcion=descripcion.replace('á','á')\n descripcion=descripcion.replace('ú','ú')\n descripcion=descripcion.replace('ñ','ñ')\n descripcion=descripcion.replace('Ñ','Ñ')\n\n\n\n propiedad.append(descripcion)\n print(propiedad)\n\n for meta in metatext:\n\n if 'data-full-images' in meta:\n meta=meta.split(';')\n for met in meta:\n if 'mlstatic' in met:\n met=met.split('&')\n met=met[0]\n met=met.replace(\".webp\",\".jpg\")\n url.append(str(met))\n\n\n\n\n #Sacar urls fotos yapo\n else:\n\n url=[]\n page = requests.get(link, headers={'User-Agent': agentCreator.generateAgent()})\n metatext=page.text\n metatext=metatext.split(' ')\n descripcion=[]\n savedescripcion=False\n saveimg=False\n og=True\n\n for texto in metatext:\n\n if '

    Descripción

    ' in texto:\n savedescripcion=True\n\n if og and 'og:image' in texto:\n saveimg=True\n og=False\n if 'img/yapo' in texto:\n saveimg=False\n if savedescripcion:\n descripcion.append(str(texto))\n if '' in texto:\n savedescripcion = False\n if saveimg and 'img.yapo.cl/images' in texto:\n texto=texto.replace('content=\"','')\n texto.replace('\"','')\n url.append(texto)\n if 'phone-url' in texto:\n texto=texto.split('\"')\n texto=texto[1]\n auxPhone=texto\n auxPhone='https://www.yapo.cl'+auxPhone\n descripcion=descripcion[1:]\n first=True\n print(descripcion)\n for desc in descripcion:\n desc=desc.replace('\\n',' ')\n desc=desc.replace('
    ','\\n')\n desc=desc.replace('','\\n')\n desc=desc.replace('
    ','\\n')\n desc=desc.replace('','')\n desc=desc.replace('itemprop=\"description\">',\"\")\n desc=desc.replace('

    ','\\n')\n desc=desc.replace(\"\\t\",\"\")\n desc=desc.replace('=78):\n\n matrixcounter+=1\n matrixdescripcion.append('')\n matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc)\n else:\n if first:\n matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+str(desc)\n first=False\n else:\n matrixdescripcion[matrixcounter]=matrixdescripcion[matrixcounter]+' '+str(desc)\n\n print(matrixdescripcion)\n descripcion='\\n'.join(matrixdescripcion)\n\n propiedad.append(descripcion)\n\n\n try:\n print(auxPhone)\n response = requests.get(auxPhone, headers={'User-Agent': agentCreator.generateAgent()})\n auxphone2=auxPhone\n img = Image.open(BytesIO(response.content))\n img=img.convert('L')\n img=img.convert('1')\n img.save(\"auxphone.gif\")\n auxPhone=1\n except:\n pass\n lenfotos=len(url)\n\n if len(url)==0:\n print(\"la propiedad no cuenta con fotografias\")\n else:\n print('total fotos: '+str(len(url)))\n for x,u in enumerate (url):\n u=u.replace('\"','')\n response = requests.get(u)\n img = Image.open(BytesIO(response.content))\n img.save(str(x)+\" foto.jpg\")\n\n if not interna:\n imagenDescripcion = Image.new('RGB', (456, 345), color = (255, 255, 255))\n\n d = ImageDraw.Draw(imagenDescripcion)\n f= ImageFont.truetype('arial.ttf',12)\n d.text((0,0), descripcion,font=f, fill=(0,0,0))\n\n imagenDescripcion.save('imagenDescripcion.png')\n\n datospro = []\n if pro:\n\n propsPV = reportes.from_portalinmobiliario(tipo, regionP, [comuna], \"venta\", True)\n propsYV = reportes.from_yapo(tipo, regionY, [comuna], True, \"venta\", True)\n propsV = propsPV + propsYV\n # aca deberiamos hacer el GB\n\n m2=reportes.m2prom(tipo,comuna,region)\n m2V=m2[0]\n m2A=m2[1]\n\n clfHV = ensemble.GradientBoostingRegressor(n_estimators=400, max_depth=5, min_samples_split=2,\n learning_rate=0.1, loss='huber')\n\n #id2,fechapublicacion,fechascrap,operacion,tipo,precio,dormitorios,banos,metrosmin,metrosmax,lat,lon,estacionamientos,link\n\n preciosV = [row[5] for row in propsV]\n\n trainingV = propsV.copy()\n for row in trainingV:\n del row[13]\n if tipo not in [\"departamento\",\"Casa\",\"Oficina\"]:\n del row[12]\n del row[7]\n if tipo != \"local\":\n del row[6]\n del row[5]\n del row[4]\n del row[3]\n del row[2]\n del row[1]\n del row[0]\n\n x_train , x_test , y_train , y_test = train_test_split(trainingV , preciosV , test_size = 0.10,random_state = 2)\n\n #obtain scores venta:\n clfHV.fit(x_train, y_train)\n print(\"-----------\")\n print(\"Score Huber:\")\n print(clfHV.score(x_test,y_test))\n scoreV=clfHV.score(x_test,y_test)\n\n clfHV.fit(trainingV, preciosV)\n\n propsPA = reportes.from_portalinmobiliario(tipo, regionP, [comuna], \"arriendo\", True)\n propsYA = reportes.from_yapo(tipo, region, [comuna], True, \"arriendo\", True)\n propsA = propsPA + propsYA\n # aca deberiamos hacer el GB\n\n clfHA = ensemble.GradientBoostingRegressor(n_estimators=400, max_depth=5, min_samples_split=2,\n learning_rate=0.1, loss='huber')\n\n #id2,fechapublicacion,fechascrap,operacion,tipo,precio,dormitorios,banos,metrosmin,metrosmax,lat,lon,estacionamientos,link\n\n preciosA = [row[5] for row in propsA]\n\n trainingA = propsA.copy()\n for row in trainingA:\n del row[13]\n if tipo not in [\"departamento\",\"Casa\",\"Oficina\"]:\n del row[12]\n del row[7]\n if tipo != \"local\":\n del row[6]\n del row[5]\n del row[4]\n del row[3]\n del row[2]\n del row[1]\n del row[0]\n\n x_train , x_test , y_train , y_test = train_test_split(trainingA , preciosA , test_size = 0.10,random_state = 2)\n\n #obtain scores arriendo:\n clfHA.fit(x_train, y_train)\n print(\"-----------\")\n print(\"Score Huber:\")\n print(clfHA.score(x_test,y_test))\n scoreA=clfHA.score(x_test,y_test)\n\n clfHA.fit(trainingA, preciosA)\n\n textmail+=\"Resultados comuna \"+str(comuna)+\":\\n\"+\"Score Ventas: \"+str((int(10000*scoreV))/100)+\"%\\nScore Arriendos: \"+str((int(10000*scoreA))/100)+\"%\\nPrecio m2 Venta: UF.\"+str((int(10*(m2V/ufn)))/10)+\"\\nPrecio m2 Arriendo: $\"+str((int(m2A)))+\"\\n\\n\"\n\n if tipo not in [\"departamento\", \"Casa\", \"Oficina\"]:\n prop=[banos, metrosmin, metrosmax, lat, lon]\n if tipo != \"local\":\n prop = [metrosmin, metrosmax, lat, lon]\n else:\n prop = [dormitorios, banos, metrosmin, metrosmax, lat, lon, estacionamientos]\n\n tasacionVenta = clfHV.predict([prop])\n tasacionArriendo = clfHA.predict([prop])\n\n precioV = tasacionVenta\n precioA = tasacionArriendo\n print(\"el precio tasado de venta inicial es: \"+str(precioV))\n print(\"el precio tasado de arriendo inicial es: \"+str(precioA))\n\n if operacion=='venta':\n\n if precioV is None or precioV < 0.1:\n pro=False\n financiera = False\n\n\n try:\n rentaV = ((precioV - precio) / precio)\n except:\n pro=False\n financiera = False\n text2='No se ha podido realizar tasación'\n print('fail 1')\n\n if precioA is None or precioA < 0.01:\n pro=False\n financiera = False\n\n\n try:\n rentaA = (precioA * 12 / precio)\n\n except:\n pro=False\n financiera = False\n text2='No se ha podido realizar tasación'\n print('fail 2')\n\n\n if pro:\n if rentaA > 0.2:\n pro=False\n financiera=False\n print('fail 3')\n\n if rentaA < 0:\n pro=False\n financiera = False\n\n if pro:\n # precio venta tasado\n datospro.append(precioV)\n # rentabilidad de venta\n datospro.append(float(rentaV))\n\n # precio arriendo tasado\n datospro.append(precioA)\n # rentabilidad de arriendo\n datospro.append(float(rentaA))\n\n\n\n else:\n\n try:\n precioA = tasacionArriendo\n\n except:\n pro=False\n text2='No se ha podido realizar tasación'\n print('fail 72')\n\n if pro:\n if precioA is None or precioA < 0.01:\n pro = False\n text2='No se ha podido realizar tasación'\n print('fail 8')\n\n\n if pro:\n # precio arriendo tasado\n datospro.append(precioA)\n # rentabilidad de arriendo\n\n datoscontacto = []\n if interna:\n\n if sitio=='portal':\n try:\n email, telefono, dueno = reportes.getDatosDueno(str(id))\n except:\n email = \"NN\"\n telefono = \"NN\"\n dueno = \"NN\"\n\n else:\n email = \"NN\"\n if auxPhone == 1:\n telefono=auxphone2\n else:\n telefono = \"NN\"\n dueno = 'NN'\n datoscontacto.append(email)\n datoscontacto.append(telefono)\n datoscontacto.append(dueno)\n\n\n #Crear PDF\n if interna:\n nombrearchivo=\"Ficha Propiedad Sitio:\"+str(sitio)+\" Id:\"+str(id)+\".pdf\"\n else:\n nombrearchivo=\"Ficha Propiedad Sitio:\"+str(sitio)+\", \"+str(operacion)+\", \"+str(tipo)+\", \"+str(region)+\", \"+str(comuna)+\".pdf\"\n\n print(nombrearchivo)\n links=[]\n if financiera:\n pro=\"financiera\"\n print(\"entering pdfCreator\")\n pdfCreatorFichas.crearPdfFicha(nombrearchivo,id,propiedad,lenfotos,pro,datospro,interna,datoscontacto,regionP,links)\n print(\"pdf generado con exito\")\n #Enviar PDF\n sendmail.sendMail(mail,\"\",nombrearchivo)\n\n #Eliminar del servidor\n\n if len(url)==0:\n pass\n else:\n for x,u in enumerate (url):\n os.remove(str(x)+\" foto.jpg\")\n try:\n os.remove(\"auxphone.gif\")\n except:\n pass\n\n if not interna:\n try:\n os.remove(\"imagenDescripcion.png\")\n except:\n pass\n os.remove(nombrearchivo)\n\n #Retornar exito\n text = \"Ficha creada para la propiedad: \"+str(id)+\" obtenida del sitio: \"+str(sitio)+\", enviada con éxito al correo: \"+str(mail)+\".\"\n if text2!='':\n text=text2+'. '+text\n return(text)\n\n\ndef main():\n texto=crearFicha('portal',5022561,'sergei.schkolnik@gmail.com',3)\n print(texto)\n\nif __name__ == '__main__':\n main()\n","sub_path":"fichav2.py","file_name":"fichav2.py","file_ext":"py","file_size_in_byte":35649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"457582101","text":"# source video: https://www.youtube.com/watch?v=ZDa-Z5JzLYM\n# you should watch it when you have some time\n\n# method: fxn associated with a class\n\n# class is a blueprint for making instances\nclass Employee:\n pass\n\n# employee_1 and emp_2 are instances of Employee\nemployee_1 = Employee() \nemp_2 = Employee() \n\n# we can manually add attributes to instances\n# name is an attribute in this case\nemployee_1.name = 'jill'\nemp_2.name = 'mike'\n\n# this can get messy when you have to give many instances to many attributes\n# to set this up automatically, we use 'init' method\n\n# -------------------------------------------------\n\nclass Employee:\n \n def __init__(self, name, favorite_animal):\n self.name = name\n self.favorite_animal = favorite_animal\n\n# self can be confusing, so here's a quick explanation:\n# employee_1 = Employee('jill','tasmanian tiger')\n# the name 'employee_1' essentially replaces 'self'\n# instead of 'self.name' we can say 'employe_1.name' and get the name attribute back\n# same for self.favorite_animal, we can now do employee_1.favorite animal\n# if we do emp_2 = Employee('mike','cat') we can do the same with emp_2\n# replace self with emp_2 and you get emp_2.name = 'mike' and emp_2.favorite_animal = 'cat'\n\nemployee_1 = Employee('jill','tasmanian tiger')\nemp_2 = Employee('mike','cat')\n\n# what if I want to see the name of emp_2 and their favorite anima? One option:\nprint('{} {}'.format(emp_2.name, emp_2.favorite_animal))\n\n# that could get tedious quickly. we can 'automate' this using a method\n# remember from line 4, method: fxn associated with a class\n\n# -------------------------------------------------\n\nclass Employee:\n \n def __init__(self, name, favorite_animal):\n self.name = name\n self.favorite_animal = favorite_animal\n \n # turn the function from line 42 into a method (a function within a class)\n def deets(self):\n \"\"\" \n gives all the juicy details that we have about\n an employee\n \"\"\"\n return '{} {}'.format(self.name, self.favorite_animal)\n # notice that we had to change emp_2 to self in the return statement\n # this allows us to make the function work for any instance of this class\n # also, you cannot forget 'self' in the function definition if you want it to work on an instance\n # emp_2.deet() is the same as Employee.deets(emp_2)\n # we want to get the deets about emp_2, this means that emp_2 is a positional argument\n # by using 'def deets(self):' we let python know that it should expect 1 argument to go into this function\n # it also tells it that the 1 argument is going to be the instance (e.g. emp_2 or employee_1)\n\n\nprint(emp_2.deets())\n# emp_2 is our 1 positional argument, deets() is our method\n# notice that we had to put () after deets. This is because it's a method, not an attribute","sub_path":"oop.py","file_name":"oop.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"48762357","text":"class Solution:\n def findPeakElement(self, nums) -> int:\n # do not have to compare with num[i-1] since num[i] and num[i+1] are enough to make conclusion.\n if (not nums or len(nums) == 0): return -1\n\n left = 0;\n right = len(nums) - 1\n while (left + 1 < right):\n mid = (left + right) // 2\n if nums[mid] <= nums[mid + 1]:\n left = mid\n else:\n right = mid\n\n return right if nums[left] < nums[right] else left\n\n return -1\n","sub_path":"src/leetCode/binarySearch/162peak.py","file_name":"162peak.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"483343373","text":"#to create a list and perform following operation\n#insertion,deletion,display,exit\nl=[]\nwhile True:\n print('1 for insertion')\n print('2 for delrtion')\n print('3 for display')\n print('4 for exit')\n s=int(input('enter which option u want'))\n if s==1:\n n=int(input('enter a element'))\n l.append(n)\n elif s==2:\n n=int(input('enter which element u delete'))\n if n in l:\n l.remove(n)\n else:\n print('invalid element')\n elif s==3:\n print('the list',l)\n elif s==4:\n break\n else:\n print('pls try again u r choosing wrong option')","sub_path":"SimplePrograms.py","file_name":"SimplePrograms.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"362847879","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2011-2013, Cédric Krier\n# Copyright (c) 2011-2013, B2CK\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 met:\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n# * Neither the name of the nor the\n# names of its contributors may be used to endorse or promote products\n# derived from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY\n# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport unittest\n\nfrom sql import Table\nfrom sql.conditionals import Case, Coalesce, NullIf, Greatest, Least\n\n\nclass TestConditionals(unittest.TestCase):\n table = Table('t')\n\n def test_case(self):\n case = Case((self.table.c1, 'foo'),\n (self.table.c2, 'bar'),\n else_=self.table.c3)\n self.assertEqual(str(case),\n 'CASE WHEN \"c1\" THEN %s '\n 'WHEN \"c2\" THEN %s '\n 'ELSE \"c3\" END')\n self.assertEqual(case.params, ('foo', 'bar'))\n\n def test_case_no_expression(self):\n case = Case((True, self.table.c1), (self.table.c2, False),\n else_=False)\n self.assertEqual(str(case),\n 'CASE WHEN %s THEN \"c1\" '\n 'WHEN \"c2\" THEN %s '\n 'ELSE %s END')\n self.assertEqual(case.params, (True, False, False))\n\n def test_coalesce(self):\n coalesce = Coalesce(self.table.c1, self.table.c2, 'foo')\n self.assertEqual(str(coalesce), 'COALESCE(\"c1\", \"c2\", %s)')\n self.assertEqual(coalesce.params, ('foo',))\n\n def test_nullif(self):\n nullif = NullIf(self.table.c1, 'foo')\n self.assertEqual(str(nullif), 'NULLIF(\"c1\", %s)')\n self.assertEqual(nullif.params, ('foo',))\n\n def test_greatest(self):\n greatest = Greatest(self.table.c1, self.table.c2, 'foo')\n self.assertEqual(str(greatest), 'GREATEST(\"c1\", \"c2\", %s)')\n self.assertEqual(greatest.params, ('foo',))\n\n def test_least(self):\n least = Least(self.table.c1, self.table.c2, 'foo')\n self.assertEqual(str(least), 'LEAST(\"c1\", \"c2\", %s)')\n self.assertEqual(least.params, ('foo',))\n","sub_path":"sql/tests/test_conditionals.py","file_name":"test_conditionals.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"525417077","text":"\"\"\"\nTitle: Product of Array Except Self\n\nGiven an array nums of n integers where n > 1, return an\narray output such that output[i] is equal to the\nproduct of all the elements of nums except nums[i].\n\nExample:\nInput: [1,2,3,4]\nOutput: [24,12,8,6]\n\nConstraint: It's guaranteed that the product of the elements of any\nprefix or suffix of the array (including the whole array) fits\nin a 32 bit integer.\n\nNote: Please solve it without division and in O(n).\n\nFollow up:\nCould you solve it with constant space complexity? (The output\narray does not count as extra space for the purpose of space\ncomplexity analysis.)\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n n = len(nums)\n\n if n == 1:\n return [0]\n\n product = []\n\n left = [0] * n\n right = [0] * n\n\n left[0] = 1\n right[n - 1] = 1\n\n for i in range(1, n):\n left[i] = left[i - 1] * nums[i - 1]\n\n for i in range(n - 2, -1, -1):\n right[i] = right[i + 1] * nums[i + 1]\n\n for i in range(n):\n product.append(left[i] * right[i])\n\n return product\n\n\ndef get_test_case_1():\n return None\n\n\ndef get_test_case_2():\n return []\n\n\ndef get_test_case_3():\n nums = [1, 2, 3, 4]\n return nums\n\n\ndef get_test_case_4() -> List[int]:\n nums = [0, 0]\n return nums\n\n\ndef get_test_case_5() -> List[int]:\n nums = [1, 0]\n return nums\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n\n #nums = get_test_case_1()\n #nums = get_test_case_2()\n nums = get_test_case_3()\n #nums = get_test_case_4()\n #nums = get_test_case_5()\n\n print(\"\\n nums: \", nums)\n\n result = solution.productExceptSelf(nums)\n print(\"\\n\\n result: \", result)\n","sub_path":"leetcode/30_day_leetcoding_challenge/202004/20200415_product_of_array_except_self/product_of_array_except_self.py","file_name":"product_of_array_except_self.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"407592233","text":"class serviec:\r\n secret = \"영구는 배꼽이 두 개다\"\r\n name = \"\" #가독성을 위한 좋은습관\r\n def setname(self,name):\r\n self.name=name\r\n def sum(self,a,b):\r\n result= a+b\r\n print(\"%s님 %s+%s=%s 입니닷\"%(self.name,a,b,result))\r\n\r\npay=serviec()\r\npay.setname(\"홍길동\")\r\n# print(pay.secret)\r\n# pay.sum(pay,1,1)\r\npay.sum(1, 1) #pay.sum을 통하여 pay가 호출한지 알기 때문에 pay는 생략가능\r\n# pay.sum(\"1\",\"1\")","sub_path":"01.jump to python/chpter 5/class/181.py","file_name":"181.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"230678820","text":"from os import path\nimport requests\nimport logging\nimport copy\nfrom scrapy.selector import Selector\nfrom .base import BasePoller\n\n\nclass OnlinerPoller(BasePoller):\n URL = \"onliner.by\"\n\n def __init__(self, config, storage):\n self.config = config\n self.storage = storage\n super(OnlinerPoller, self).__init__()\n\n @property\n def storage_path(self):\n return path.join(self.storage, self.config['name'])\n\n @property\n def request_config(self):\n return copy.deepcopy(self.config['request'])\n\n @property\n def api_url(self):\n return self.config['api_url']\n\n @staticmethod\n def fetch_extra_information(url):\n res = requests.get(url)\n if res.status_code == 200:\n selector = Selector(text=res.text)\n phones = selector.css('.apartment-info__list_phones .apartment-info__item ::text').extract()\n\n return {\n 'phones': [phone.replace(' ', '').replace('-', '') for phone in phones]\n }\n else:\n return {}\n\n def poll(self, controller=None, max_requests=None):\n params = self.request_config\n params['page'] = 1\n\n requests_count = 0\n\n while True:\n r = requests.get(self.api_url, params)\n requests_count += 1\n\n if r.status_code == 200:\n apartments = r.json()['apartments']\n if len(apartments) == 0:\n break\n\n for a in apartments:\n h_a = self.get_entry(a['id'])\n if h_a is None:\n details = self.fetch_extra_information(a['url'])\n a.update(details)\n self.put_entry(a['id'], a)\n controller.on_new_apartment(a, self.config['name'])\n else:\n logging.warning('invalid response code: %d', r.status_code)\n break\n\n if max_requests is not None and requests_count >= max_requests:\n break\n\n params['page'] += 1\n","sub_path":"site_api/onliner.py","file_name":"onliner.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"167758850","text":"'''\nGiven an array of integers where every integer occurs three times except for one integer, which only occurs once, find and return the non-duplicated integer.\n\nFor example, given [6, 1, 3, 3, 3, 6, 6], return 1. Given [13, 19, 13, 13], return 19.\n\nDo this in O(N) time and O(1) space.\n'''\n\nimport unittest\n\ndef solve(arr):\n\tif arr is None:\n\t\treturn arr\n\tarr_set_sum = sum(list(set(arr)))\n\tarr_sum = sum(arr)\n\treturn ((3 * arr_set_sum) - arr_sum) / 2\n\t\n\nclass Test(unittest.TestCase):\n\n\tdata=[([6,1,3,3,3,6,6], 1), \n\t\t ([13, 19, 13, 13], 19)]\n\n\tdef test(self):\n\t\tfor case, expected in self.data:\n\t\t\tactual = solve(case)\n\t\t\tself.assertEquals(actual, expected)\n\nif __name__=='__main__':\n\tunittest.main()\n","sub_path":"Problem_40/problem.py","file_name":"problem.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"394240754","text":"import os,sys\n\n#################### Predefined variables ####################################\n\n# define temporary files\n\ntxdumpout = 'txdump_outputfile.tmp'\n\n\n\nphot_out = \"temp_photout.mag\"\n\n\nlc_out = \"\" # this is changed by all_phot\n\ncoofnamein=\"\" # this is changed by all_phot\ncoofnameout=\"coords_list.txt\"\n\n### Will you need to change some of the following?\nimage_dir = \"\" # changed by all_phot\nrootstr = \"\" # changed by all_phot\nendstr = \"\" # changed by all_phot\n\n### LOOK! Are these parameters what you would have chosen? What are your criteria?\n### How about those keywords?\n### photometry parameters\n### all of these are changed by all_phot and can be changed there rather\nfwhmpsf=''\nsigma = ''\t# Standard deviation of background in counts\nhiclip='' # High sky annulus clipping, percent\nlowclip='' # Low sky annulus clipping, percent\negain='' # CCD electron gain keyword\nccdread='' # CCD read noise keyword\namass=\"AIRMASS\" # Airmass keyword\n#obstime=\"TIME-OBS\" # Observation time keyword\nobstime=\"UT\" # Observation time keyword\nexp=\"EXPOSURE\" # Exposure time keyword, seconds\nannulus='' # annulus inner radius\ndannulus=''\t# annulus width\nskyvalue=''\n\n################### End of predefined #########################\n","sub_path":"easy_phot_params.py","file_name":"easy_phot_params.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"326947580","text":"import pygame\nimport requests\nimport sys\nimport os\n\nimport math\n\nfrom common.distance import lonlat_distance\nfrom common.geocoder import geocode as reverse_geocode\nfrom common.business import find_business\n\nLAT_STEP = 0.008\nLON_STEP = 0.02\ncoord_to_geo_x = 0.0000428\ncoord_to_geo_y = 0.0000428\n\n\ndef ll(x, y):\n return \"{0},{1}\".format(x, y)\n\n\nclass MapParams(object):\n def __init__(self):\n self.lat = 55.729738\n self.lon = 37.664777\n self.zoom = 15\n self.type = \"map\"\n\n self.search_result = None\n self.use_postal_code = False\n\n def ll(self):\n return ll(self.lon, self.lat)\n\n def update(self, event):\n pass\n\n def screen_to_geo(self, pos):\n dy = 225 - pos[1]\n dx = pos[0] - 300\n lx = self.lon + dx * coord_to_geo_x * math.pow(2, 15 - self.zoom)\n ly = self.lat + dy * coord_to_geo_y * math.cos(math.radians(self.lat)) * math.pow(2, 15 - self.zoom)\n return lx, ly\n\ndef load_map(mp):\n map_request = \"http://static-maps.yandex.ru/1.x/?ll={0},{1}&z={2}&l={3}\".format(mp.ll()[0], mp.ll()[1], mp.zoom, mp.type)\n response = requests.get(map_request)\n\n if not response:\n print(\"Ошибка выполнения запроса:\")\n print(map_request)\n print(\"Http статус:\", response.status_code, \"(\", response.reason, \")\")\n sys.exit(1)\n\n map_file = \"map.png\"\n try:\n with open(map_file, \"wb\") as file:\n file.write(response.content)\n except IOError as ex:\n return(\"Ошибка записи временного файла:\", ex)\n\n return map_file\n\n map_file = \"map.png\"\n try:\n with open(map_file, \"wb\") as file:\n file.write(response.content)\n except IOError as ex:\n print(\"Ошибка записи временного файла:\", ex)\n sys.exit(2)\n return map_file\n\n\ndef main():\n pygame.init()\n screen = pygame.display.set_mode((600, 450))\n\n mp = MapParams()\n\n while True:\n event = pygame.event.wait()\n if event.type == pygame.QUIT:\n break\n elif event.type == pygame.KEYUP:\n mp.update(event)\n\n map_file = load_map(mp)\n\n screen.blit(pygame.image.load(map_file), (0, 0))\n\n pygame.display.flip()\n\n pygame.quit()\n os.remove(map_file)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"534457970","text":"# Definition for a binary tree node.\r\nfrom typing import List\r\n\r\n\r\nclass TreeNode:\r\n def __init__(self, x):\r\n self.val = x\r\n self.left = None\r\n self.right = None\r\n\r\n\r\nclass Solution:\r\n def bstFromPreorder(self, preorder: List[int]) -> TreeNode:\r\n rootNode = TreeNode(preorder[0])\r\n for i in range(1, len(preorder)):\r\n self.append_node(rootNode, preorder[i])\r\n return rootNode\r\n\r\n def append_node(self, node: TreeNode, val: int):\r\n if val < node.val:\r\n if node.left is None:\r\n node.left = TreeNode(val)\r\n else:\r\n self.append_node(node.left, val)\r\n else:\r\n if node.right is None:\r\n node.right = TreeNode(val)\r\n else:\r\n self.append_node(node.right, val)\r\n\r\n\r\nif __name__ == '__main__':\r\n preorder = [8, 5, 1, 7, 10, 12]\r\n\r\n rootNode = TreeNode(8)\r\n rootNode.left = TreeNode(5)\r\n rootNode.left.left = TreeNode(1)\r\n rootNode.left.right = TreeNode(7)\r\n rootNode.right = TreeNode(10)\r\n rootNode.right.right = TreeNode(12)\r\n assert Solution().bstFromPreorder(preorder) == rootNode\r\n","sub_path":"Weekly_Contest_127/1008.py","file_name":"1008.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"611070625","text":"from django.shortcuts import render\nfrom django.db import connections\nfrom django.http.response import JsonResponse\nfrom django.contrib import messages\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef index(request):\n if not request.user.has_perm('commons.estatisticas'):\n messages.info(\n request=request,\n message='Você não possui permissão para utilizar esta funcionalidade.',\n extra_tags=\"alert-info\")\n return render(request, 'index.html', {})\n\n return render(request, 'estatisticas.html', {})\n\n\ndef estatisticas_uso_geral(request):\n\n if not request.user.has_perm('commons.estatisticas'):\n json_resp = JsonResponse({\n 'err_msg': u\"Usuário não possui permissão de acesso à esta funcionalidade!\",\n })\n json_resp.status_code = 401\n return json_resp\n\n estrutura_temporaria = {}\n acessos = []\n resultado = []\n\n ####################################\n # informacoes de acesso a aplicacoes\n query = '''\n SELECT nm_aplicacao\n ,avg(nr_tempo_reposta) tempo_medio_resposta\n ,strftime('%Y%m%d', dt_requisicao) as dia\n ,count(*) as total\n FROM tb_auditoria_requisicoes\n where 1=1\n and nm_aplicacao not in ('', 'favicon.ico')\n group by nm_aplicacao\n ,strftime('%Y%m%d', dt_requisicao)\n order by dia desc, total desc\n '''\n # -- and datediff(day, dt_requisicao, getdate()) <= 15\n # substr('0000000000'||'1234', -10, 10)\n\n with connections['default'].cursor() as cursor:\n cursor.execute(query)\n # query = 'select strftime(\\'%Y%m%d\\', dt_requisicao) from tb_auditoria_requisicoes'\n acessos = list(cursor)\n\n set_nm_aplicacao = set()\n set_dia = set()\n\n idx_nm_aplicacao = 0\n idx_dia = 2\n idx_total = 3\n\n for acesso in acessos:\n set_nm_aplicacao.add(acesso[idx_nm_aplicacao])\n set_dia.add(acesso[idx_dia])\n\n sorted(set_nm_aplicacao)\n sorted(set_dia)\n\n for dia in set_dia:\n for nm_aplicacao in set_nm_aplicacao:\n if dia not in estrutura_temporaria:\n estrutura_temporaria[dia] = {}\n estrutura_temporaria[dia][nm_aplicacao] = 0\n\n for acesso in acessos:\n estrutura_temporaria[acesso[idx_dia]][acesso[idx_nm_aplicacao]] += acesso[idx_total]\n\n for dia in set_dia:\n for nm_aplicacao in set_nm_aplicacao:\n resultado.append({\n 'Data': dia,\n 'Aplicação': nm_aplicacao,\n 'Total': estrutura_temporaria[dia][nm_aplicacao]\n })\n\n return JsonResponse({'estatisticas': resultado})\n\n\ndef estatisticas_usuarios_unicos(request):\n\n if not request.user.has_perm('commons.estatisticas'):\n json_resp = JsonResponse({\n 'err_msg': u\"Usuário não possui permissão de acesso à esta funcionalidade!\",\n })\n json_resp.status_code = 401\n return json_resp\n\n resultado = []\n\n query = '''\n SELECT\n strftime('%Y%m%d', dt_requisicao) as dia\n , count(distinct nm_ip) as usuarios\n FROM tb_auditoria_requisicoes\n where 1=1\n -- and datediff(day, dt_requisicao, getdate()) <= 15\n group by strftime('%Y%m%d', dt_requisicao)\n order by dia desc\n '''\n\n with connections['default'].cursor() as cursor:\n cursor.execute(query)\n usuarios_unicos = list(cursor)\n\n for dia, usuarios in usuarios_unicos:\n resultado.append({\n 'chave': 'usuarios',\n 'dia': dia,\n 'total': usuarios,\n })\n\n return JsonResponse({'estatisticas': resultado})\n\n","sub_path":"commons/views_estatisticas.py","file_name":"views_estatisticas.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"157169229","text":"from __future__ import print_function\nimport numpy as np\nimport caiman as cm\nimport os\nfrom ipywidgets import interact, interactive, fixed, interact_manual, FloatSlider, Dropdown, Checkbox, IntSlider, Button, HBox, VBox, Label\nimport ipywidgets as widgets\nimport logging\nfrom IPython.display import display, Image\nimport matplotlib.pyplot as plt\nimport src.pipeline \nimport cv2\n\n#%% SETUP\n\n\ndef analysis_state_widget_handler(*args):\n # Create widget updating function\n # The function selects all existing analysis states corresponding to the step\n step_idx = src.pipeline.get_step_index(step) \n for i, index in enumerate(src.pipeline.multi_index_structure[:len(src.pipeline.data_structure) + step_idx + 1]):\n # Run top-down past the widgets. For each widget, make sure all widgets below only have \n # values for which the full index exists\n query_list = [f'{step}_v != 0']\n for j in src.pipeline.multi_index_structure[:i]:\n widget_value = widgets[j].value\n query_list += [f'{j} == {widget_value}']\n remaining_rows = master_df.query(' & '.join(query_list))\n\n if not remaining_rows.empty:\n new_options = remaining_rows.index.unique(level = index).tolist()\n if i >= 4: \n new_options.reverse()\n widgets[index].options = new_options\n set_empty_from_idx = i \n else:\n widgets[index].options = [0]\n set_empty_from_idx = i \n break \n for index in src.pipeline.multi_index_structure[set_empty_from_idx + 1:]:\n widgets[index].options = [0]\n\ndef get_analysis_state_widgets(step, master_df):\n \n # Create widget updating function\n def update_options(*args): \n # The function selects all existing analysis states corresponding to the step\n step_idx = src.pipeline.get_step_index(step) \n for i, index in enumerate(src.pipeline.multi_index_structure[:len(src.pipeline.data_structure) + step_idx + 1]):\n # Run top-down past the widgets. For each widget, make sure all widgets below only have \n # values for which the full index exists\n query_list = [f'{step}_v != 0']\n for j in src.pipeline.multi_index_structure[:i]:\n widget_value = widgets[j].value\n query_list += [f'{j} == {widget_value}']\n remaining_rows = master_df.query(' & '.join(query_list))\n \n if not remaining_rows.empty:\n new_options = remaining_rows.index.unique(level = index).tolist()\n if i >= 4: \n new_options.reverse()\n widgets[index].options = new_options\n set_empty_from_idx = i \n else:\n widgets[index].options = [0]\n set_empty_from_idx = i \n break \n for index in src.pipeline.multi_index_structure[set_empty_from_idx + 1:]:\n widgets[index].options = [0]\n \n \n # Create widgets\n widgets = {}\n for index in src.pipeline.multi_index_structure:\n style = {'description_width': '150px'}\n widget = Dropdown(options = [], description = index, style = style)\n widget.observe(update_options, 'value')\n widgets[index] = widget\n \n # Run the update options function once\n update_options()\n \n # Return the widgets\n return widgets\n\n#%% GENERAL\n\n## MOVIES\n\ndef get_play_button(m, clip_length, backend, fr, gain, magnification, plot_text, description = 'Play movie'):\n button = widgets.Button(description=description, icon = 'play') ; display(button)\n def wrapper_function(click):\n clip_range = clip_length.value\n if m.shape[0] > 3000 and backend.value == 'notebook':\n logging.warning('The movie is longer than 5 min and the backend is \"notebook\". Rendering may take some time.')\n m[clip_range[0]:clip_range[1]].play(fr = fr.value, gain = gain.value, magnification = magnification.value, plot_text = plot_text.value, backend = backend.value)\n button.on_click(wrapper_function)\n\n\ndef get_movie_player(m, description = 'Play movie', magnification_init = 1):\n # clip length\n clip_length = widgets.IntRangeSlider(value = [0,m.shape[0]], min = 0, max = m.shape[0], description = 'select clip') ; clip_length.layout.width = '10cm'; display(clip_length)\n # backend\n backend = widgets.Dropdown(options = ['opencv', 'notebook'], description = 'backend'); display(backend)\n # frame rate (Hz)\n fr = widgets.IntSlider(value=120, min = 10, max = 120, step = 10, description = 'framerate (Hz)') ; display(fr)\n # gain\n gain = widgets.FloatSlider(value=1.0, min = 0.1, max = 2.0, step = 0.1, description = 'gain') ; display(gain)\n # magnification / zoom \n magnification = widgets.IntSlider(value=magnification_init, min = 1, max = 5, step = 1, description = 'magnification / zoom') ; display(magnification)\n # plot frame number?\n plot_text = widgets.widgets.Checkbox(value=True, description = 'plot frame number') ; display(plot_text)\n # play button\n get_play_button(m, clip_length, backend, fr, gain, magnification, \n plot_text, description = description)\n \n \n## FIGURES\n \ndef get_save_fig_button(fig, fname):\n def save_fig(click):\n fig.savefig(fname)\n print(f'Saving figure as {fname}')\n save_fig_widget = widgets.Button(description = 'Save figure') ; display(save_fig_widget)\n save_fig_widget.on_click(save_fig)\n \n#def get_update_options_function(step):\n# \n# def update_options(*args):\n# # The function selects all existing analysis states corresponding to the step\n# step = step_widget.value\n# step_idx = src.pipeline.get_step_index(step) \n# for i, index in enumerate(src.pipeline.multi_index_structure[:len(src.pipeline.data_structure) + step_idx + 1]):\n# \n# query_list = [f'{step}_v != 0']\n# for j in src.pipeline.multi_index_structure[:i]:\n# widget_value = globals()[f'{j}_widget'].value\n# query_list += [f'{j} == {widget_value}']\n# \n# remaining_rows = master_df.query(' & '.join(query_list))\n# if not remaining_rows.empty:\n# new_options = remaining_rows.index.unique(level = index).tolist()\n# if i >= 4: \n# new_options.reverse()\n# widget_value = globals()[f'{index}_widget'].value\n# globals()[f'{index}_widget'].options = new_options\n# if widget_value in new_options:\n# globals()[f'{index}_widget'].value = widget_value\n# set_empty_from_idx = i \n# else:\n# globals()[f'{index}_widget'].options = [0]\n# set_empty_from_idx = i \n# break \n# for index in src.pipeline.multi_index_structure[set_empty_from_idx + 1:]:\n# globals()[f'{index}_widget'].options = [0]\n# \n# return update_options\n\n#%% DECODING\n \n\n \n#%% PREVIEW PARAMETERS\n\n#%% General\n\ndef preview_parameters_get_store_parameters_buttons(step, index, parameters_update):\n print(f'Do you want to set the following new parameters: \\n {parameters_update} \\n specific for the following data?')\n # Define toggle button widgets for mouse-, session- and trial-specific parameter storing\n mouse_specific_widget = widgets.ToggleButton(value=True, description=f'Mouse: {index[0]}')\n session_specific_widget = widgets.ToggleButton(value=True, description=f'Session: {index[1]}')\n trial_name = src.pipeline.get_trial_name(index[2],index[3])\n trial_specific_widget = widgets.ToggleButton(value=True, description=f'Trial: {trial_name}')\n # Store the widgets in a list\n widget_list = [mouse_specific_widget, session_specific_widget, trial_specific_widget]\n # Define the updating function to enforce the rule: if parameters are stored \n # level-specific for a certain level, they are specific for all upper levels as well\n def update_values(*args):\n for i, indexer in enumerate(src.pipeline.data_structure[:3]):\n value_list = [widget.value for widget in widget_list[i+1:]]\n if np.array(value_list).any():\n widget_list[i].value = True\n # Apply the update_values function as an observer for each widget\n for widget in widget_list: widget.observe(update_values, 'value')\n # Display the widgets\n# for widget in widget_list: display(widget)\n # Create a button for storing parameters\n# store_parameters = widgets.Button(description = 'Store parameters') ; display(store_parameters)\n # Define a wrapper function for the button\n def f_store_parameters(mouse_specific, session_specific, trial_specific):\n mouse = index[0] if mouse_specific else None\n session = index[1] if session_specific else None\n trial = index[2] if trial_specific else None\n is_rest = index[3] if trial_specific else None \n src.pipeline.set_parameters(step, parameters_update, mouse, session, trial, is_rest, check = False)\n \n interact_manual(f_store_parameters, mouse_specific = mouse_specific_widget, session_specific = session_specific_widget,\n trial_specific = trial_specific_widget)\n\n \n \n\n\n \n#%% Cropping\n \ndef preview_parameters_cropping_cropping_points_spatial_get_movie_with_borders(m, cropping_points_spatial):\n pt1 = (cropping_points_spatial[3],cropping_points_spatial[1])\n pt2 = (cropping_points_spatial[2],cropping_points_spatial[0])\n m_with_border = [cv2.rectangle(m_, pt1, pt2, (0,0,255), thickness = 1) for m_ in m]\n m_with_border = cm.movie(np.array(m_with_border))\n return m_with_border\n\n\n## Temporal cropping points \n \ndef preview_parameters_cropping_cropping_points_temporal_get_in_out_movie(m, cropping_points_temporal):\n clip_range = range(cropping_points_temporal[0],cropping_points_temporal[1])\n text_width, text_height = cv2.getTextSize('EXCLUDE: Frame 100', fontFace=5, fontScale = 0.8, thickness=1)[0]\n m_with_in_out = []\n for i, frame in enumerate(m):\n m_with_in_out.append(cv2.putText(frame, f'EXCLUDE: Frame {i}' if i in clip_range else f'INCLUDE: Frame {i}',((frame.shape[1] - text_width) // 2,\n frame.shape[0] - (text_height + 5)), fontFace=5, fontScale=0.8, color=(255, 255, 255), thickness=1))\n m_with_in_out = cm.movie(np.array(m_with_in_out))\n return m_with_in_out\n\ndef preview_parameters_cropping_cropping_points_temporal_get_cutout_clip_player(m, i, cropping_points_temporal, padding = 200):\n # clip length\n clip_length = widgets.IntRangeSlider(value = [cropping_points_temporal[0],cropping_points_temporal[1]], min = 0, max = m.shape[0], description = f'select cut-out clip {i}') ; clip_length.layout.width = '10cm'; display(clip_length)\n # backend\n backend = widgets.Dropdown(options = ['opencv', 'notebook'], description = 'backend'); display(backend)\n # frame rate (Hz)\n fr = widgets.IntSlider(value=10, min = 10, max = 120, step = 10, description = 'framerate (Hz)') ; display(fr)\n # gain\n gain = widgets.FloatSlider(value=1.0, min = 0.1, max = 2.0, step = 0.1, description = 'gain') ; display(gain)\n # magnification / zoom \n magnification = widgets.IntSlider(value=1, min = 1, max = 4, step = 1, description = 'magnification / zoom') ; display(magnification)\n # plot the text \n m_with_in_out = preview_parameters_cropping_cropping_points_temporal_get_in_out_movie(m, cropping_points_temporal)\n # play button \n preview_parameters_cropping_cropping_points_temporal_get_play_button(m_with_in_out, clip_length, \n backend, fr, gain, magnification, description = f'Play cut-out clip {i}', padding = padding) \n\n\ndef preview_parameters_cropping_cropping_points_temporal_get_play_button(m, clip_length, backend, fr, gain, magnification, description = 'Play movie', padding = 200):\n button = widgets.Button(description=description, icon = 'play') ; display(button)\n def wrapper_function(click):\n clip_range = clip_length.value\n if m.shape[0] > 3000 and backend.value == 'notebook':\n logging.warning('The movie is longer than 5 min and the backend is \"notebook\". Rendering may take some time.')\n padding_left = max(0, clip_range[0] - padding)\n padding_right = min(m.shape[0], clip_range[1] + padding)\n m_with_in_out = preview_parameters_cropping_cropping_points_temporal_get_in_out_movie(m.copy(), [clip_range[0],clip_range[1]])\n m_with_in_out[padding_left:padding_right].play(fr = fr.value, gain = gain.value, magnification = magnification.value, backend = backend.value)\n button.on_click(wrapper_function)\n \n \n \n \n","sub_path":"src/quality_assessment.py","file_name":"quality_assessment.py","file_ext":"py","file_size_in_byte":12785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"544432851","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\nfrom django.shortcuts import render_to_response\nimport crawler\n\ndef crawl(request):\n try:\n terms = map(str, request.GET['q'].split())\n seed = str(request.GET['seed'])\n except KeyError:\n terms = None\n seed = None\n else:\n if 'http' not in seed:\n seed = 'http://' + seed\n\n try:\n depth = int(request.GET['depth'][0])\n except:\n depth = 2 # default depth\n if depth < 3:\n depth = 1\n\n return render_to_response('rycrawler/crawl.html', {\n 'seed': seed,\n 'terms': terms,\n 'sites': crawler.crawl(seed, depth, terms),\n })\n","sub_path":"views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"521545398","text":"\n__author__ = 'arun_bonam'\n\n\ndef getImpalaDriver(db):\n\n driver=''\n if db == 'impala':\n driver='com.cloudera.impala.jdbc41.Driver'\n return driver\n\n\ndef getJdbcConnectionUrl(db, prop):\n\n\n url=''\n if db == 'impala':\n url='jdbc:impala://{}:{}/{}'.format(prop['host'],prop['port'],prop['dbname'])\n return url\n\n\n\ndef getImpalaProperties(impalaObjects):\n dbs = impalaObjects.keys()\n props = {}\n for db, prop in impalaObjects.items():\n url = getJdbcConnectionUrl(db, prop)\n driver = getImpalaDriver(db)\n props[db] = dict([(i, locals()[i]) for i in ('url','driver')])\n return props\n\n\ndef dfWriter(df,table,impConf,writeMode):\n return df.write.format(\"jdbc\") \\\n .mode(writeMode) \\\n .option(url=impConf.get('url')+\":auth=noSasl:\") \\\n .option(table=table) \\\n .option(impConf.get('driver'))\n\n\n","sub_path":"recipes-etl/venv/src/etl/util/impala.py","file_name":"impala.py","file_ext":"py","file_size_in_byte":876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"229689815","text":"import urllib.request,socket,re,sys,os\n\ntargetPath=\"D:\\\\python\\\\pythonspider\\\\output\\\\img\"\n\ndef saveFile(path):\n ##检测当前路径的有效性 \n if not os.path.isdir(targetPath):\n os.mkdir(targetPath)\n\n ##设置每个图片的路径 \n pos = path.rindex('/')\n t = os.path.join(targetPath,path[pos+1:])\n return t\n\nurl=\"https://www.douban.com\"\nheaders= { \n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) ' \n 'Chrome/51.0.2704.63 Safari/537.36' \n } \nreq=urllib.request.Request(url=url,headers=headers)\n\nres=urllib.request.urlopen(req)\n \ndata=res.read()\n\nfor link,t in set(re.findall(r'(https:[^s]*?(jpg|png|gif))',str(data))):\n print(link)\n try:\n urllib.request.urlretrieve(link,saveFile(link))\n except:\n print('失败')\n","sub_path":"爬虫/03getimg.py","file_name":"03getimg.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"255742379","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 26 21:48:38 2021\n\n@author: 11268\n\"\"\"\n#更改generations\n#更改output文件,risk还是cost\n#更改输出数据文件名称\n#更改lp名称\n\nfrom OutPut import*\nfrom data_robust import print_Info\n\noutput_location()\noutput_x()\noutput_y()\noutput_z()\noutput_m()\noutput_n()\noutput_l1()\noutput_l2()\noutput_GTmatrix()\n# output_GDmatrix()\n# output_GRmatrix()\n# output_RDmatrix()\n# output_TDmatrix()\n# output_TRmatrix()\n#output_qy()\noutput_GTnv()\noutput_GRnv()\noutput_GDnv()\noutput_TRnv()\noutput_TDnv()\noutput_RDnv()\noutput_CREH()\nstr3='D:\\\\gruobi练习\\\\第五章算例结果分析\\\\\\''+'输出数据变动车流量50_'+'.xlsx'\nstr4='D:\\\\gruobi练习\\\\第五章算例结果分析\\\\\\''+'输出数据变动车流量50_'+str(u)+'.xlsx'\nbook.save(str3)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"62589301","text":"import numpy as np\nfrom numpy import sin, cos, pi\nimport scipy as sp\nfrom scipy.optimize import leastsq\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport pylab\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n\nfrom common import stringint\n\nFIT = True\n\nfig = pylab.figure()\nax = Axes3D(fig)\nddx_, ddy_ = np.mgrid[0:1:complex(0,101), 0:1:complex(0,101)]\n\nnum = 100\ndd = np.zeros((num, 10201, 2))\nmean = np.zeros((10201, 2))\nstd = np.zeros((10201, 2))\nfor i in range(num):\n name = 'XYfin%i.pts'%i\n ini = np.loadtxt('101x101.pts', skiprows = 1)[:, 2:4]\n res = np.loadtxt(name, skiprows = 1)[:, 2:4]\n dd[i] = res - ini\n dd[i, :, 1] = -dd[i, :, 1]\n\nfor i in range(10201):\n for j in range(2):\n mean[i, j] = dd[:, i, j].mean()\n std[i,j] = dd[:, i, j].std()\n\nmeanx, meany, stdx, stdy = mean[:, 0].reshape((101, 101)), mean[:, 1].reshape((101, 101)), std[:, 0].reshape((101, 101)), std[:, 1].reshape((101, 101))\nerrx, erry = meanx-ddx_, meany-ddy_\nvarx, vary = stdx**2, stdy **2\n\n#surf = ax.plot_surface(ddx_, ddy_, errx, rstride=1, cstride=1, cmap=cm.jet)\nax.set_xlabel('$x$ displacement',size='xx-large')\nax.set_ylabel('$y$ displacement',size='xx-large')\nax.set_zlabel('$x$ displacement error',size='xx-large')\n\n#pylab.savefig('error_pm.pdf',format='pdf', bbox_inches='tight', pad_inches=0)\ndef residuals(AB, err):\n A, B = AB\n surf = A*sin(2*pi*ddx_)-B*sin(2*pi*ddy_)\n return (err-surf).ravel()\ndef residuals1(A, err):\n surf = A*sin(4*pi*ddx_)\n return (err-surf).ravel()\n\n\nerr = errx\nif FIT:\n #x, y = np.mgrid[0:1:complex(0,101), 0:1:complex(0,101)]\n #sur = sin(2*pi*x)-0.1*sin(2*pi*y)\n #surf = ax.plot_surface(ddx_, ddy_, sur, rstride=1, cstride=1, cmap=cm.jet)\n A0, B0 = err[:,50].max(), err[0,:].max()\n A, B = leastsq(residuals, (A0, B0), args = err)[0]\n s = A*sin(2*pi*ddx_)-B*sin(2*pi*ddy_)\n #surf1 = ax.plot_surface(ddx_, ddy_, s, rstride=1, cstride=1, cmap=cm.jet)\n #r = errx-s\n #A0 = r.max()\n #A = leastsq(residuals1,A0,args=r)[0]\n #s = A*sin(4*pi*ddx_)\n\nsurf1 = ax.plot_surface(ddx_, ddy_, errx-s, rstride=1, cstride=1, cmap=cm.jet)\npylab.show()\n\"\"\"\ndd = np.zeros((10201, 2))\nname = '38000id'\nini = np.loadtxt('101x101.pts', skiprows = 1)[:, 2:4]\nres = np.loadtxt(name, skiprows = 1)[:, 2:4]\ndd = res - ini\ndd[:, 1] = -dd[:, 1]\nddx, ddy = dd[:, 0].reshape((101, 101)), dd[:, 1].reshape((101, 101))\nerrx, erry = ddx - ddx_, ddy - ddy_\nsurf = ax.plot_surface(ddx_, ddy_, errx, rstride=1, cstride=1, cmap=cm.jet)\nax.set_xlabel('$x$ displacement',size='xx-large')\nax.set_xmargin(0.5)\nax.set_ylabel('$y$ displacement',size='xx-large')\nax.set_zlabel('$x$ displacement error',size='xx-large')\npylab.show()\n\"\"\"\n","sub_path":"error_est.py","file_name":"error_est.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"367802808","text":"from flask import Flask, jsonify, abort, make_response, request, url_for, send_file\nfrom flask_httpauth import HTTPBasicAuth\nfrom json import loads\n\nimport smoosh_processor\n\nauth = HTTPBasicAuth()\n\nwith open(\"users.json\") as user_file:\n u_auth = loads(user_file.read())\n\napp = Flask(__name__)\n\n\n@auth.get_password\ndef get_password(username):\n if username == u_auth[\"username\"]:\n return u_auth[\"password\"]\n return None\n\n\n@auth.error_handler\ndef unauthorized():\n return make_response(jsonify({'error': 'Unauthorized access'}), 401)\n\n\n@app.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error': 'Not found'}), 404)\n\n\n@app.route('/api/v1.0/smoosh_test', methods=[\"GET\"])\n@auth.login_required\ndef serve_blank():\n return jsonify({\"yay\": \"you're here!\"})\n\n\n@app.route('/api/v1.0/smoosh_upload', methods=['POST'])\n@auth.login_required\ndef receive_files():\n if request.headers[\"file-type\"] in [\"PS_Fedex\", \"SL_Fedex\", \"PS_USPS\", \"SL_USPS\", \"SL_USPS-zip\"]:\n if request.headers[\"file-type\"] == \"PS_Fedex\":\n request.files[\"file\"].save(\"PS_Fedex.pdf\")\n return jsonify({\"result\": \"PS_Fedex received!\"})\n elif request.headers[\"file-type\"] == \"SL_Fedex\":\n request.files[\"file\"].save(\"SL_Fedex.pdf\")\n return jsonify({\"result\": \"SL_Fedex received!\"})\n elif request.headers[\"file-type\"] == \"PS_USPS\":\n request.files[\"file\"].save(\"PS_USPS.pdf\")\n return jsonify({\"result\": \"PS_USPS received!\"})\n elif request.headers[\"file-type\"] == \"SL_USPS\":\n request.files[\"file\"].save(\"SL_USPS.pdf\")\n return jsonify({\"result\": \"SL_USPS received!\"})\n elif request.headers[\"file-type\"] == \"SL_USPS-zip\":\n request.files[\"file\"].save(\"SL_USPS-zip.zip\")\n return jsonify({\"result\": \"SL_USPS-zip received!\"})\n else:\n print(request.headers[\"file-type\"])\n return jsonify({\"result\": \"file-type not valid!\"})\n\n\n@app.route('/api/v1.0/smoosh_run', methods=['POST'])\n@auth.login_required\ndef smoosh_run():\n result = smoosh_processor.smoosher(request.headers[\"run-answer\"].lower())\n if result == \"invalid answer\":\n return not_found(\"invalid answer\")\n else:\n return jsonify({\"result\": result})\n\n\n@app.route('/api/v1.0/smoosh_download', methods=['GET'])\n@auth.login_required\ndef serve_smooshed_file():\n if request.headers[\"carrier\"].lower() == \"usps\":\n return send_file(\"output_smooshed_logo-USPS.pdf\")\n elif request.headers[\"carrier\"].lower() == \"fedex\":\n return send_file(\"output_smooshed_logo-fedex.pdf\")\n else:\n return not_found(\"invalid carrier\")\n\n\nif __name__ == '__main__':\n app.run(host=\"0.0.0.0\", port=5005, debug=True)","sub_path":"packslip_smoosher/smoosher_api.py","file_name":"smoosher_api.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"635989479","text":"# -*- coding: utf-8 -*-\n\"\"\"Stores and manages settings used to communicate to the API server.\"\"\"\n# ###\n# checkpoint_api_wrapper/client.py\n\n# FrozenDragoon\n# github.com/frozendragoon/checkpoint_api_wrapper\n# ###\n\nimport logging\n\nclass Client():\n \"\"\"\n Python interface for interacting with Check Point API.\n\n Attributes\n ----------\n server_ip : str\n IP of the Check Point management server.\n server_port : int\n Port to connect on.\n verify_ssl_cert : bool\n\n \"\"\"\n def __init__(self, server_ip,\n server_port,\n ssl_verify):\n \"\"\"\n Create a new API_Client.\n\n Parameters\n ----------\n server_ip : str\n IP of the Check Point management server.\n server_port : int\n Port to connect on.\n verify _ssl_cert : bool, optional\n If the API should reject connections that fail a SSL/TLS check,\n eg due to self signed certficiate.\n \"\"\"\n self.__logger = logging.getLogger(__name__)\n\n self.__logger.debug((\"Creating Client instance with:\\n\"\n \"server_ip = %s\\n\"\n \"server_port= %s\\n\"\n \"ssl_verify = %s\"),\n server_ip, str(server_port), str(ssl_verify))\n\n self.server_ip = server_ip\n self.server_port = server_port\n self.verify_ssl_cert = ssl_verify\n\n @property\n def verify_ssl_cert(self):\n \"\"\"If the API should reject connections that fail a SSL/TLS check,\n eg due to self signed certficiate.\n\n Notes\n ----------\n When setting this property to `False`: `InsecureRequestWarning` s\n from `urllib3` will be suppressed.\n \"\"\"\n return self._ssl_verify\n\n @verify_ssl_cert.setter\n def verify_ssl_cert(self, ignore: bool):\n if not ignore:\n self.__logger.info(\"NOTE: Disabling InsecureRequestsWarning\")\n import urllib3 # pylint: disable=import-outside-toplevel\n # Make note of this:\n # This will disable any certificate checking, and is NOT secure.\n urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)\n\n self._ssl_verify = ignore\n","sub_path":"checkpoint_api_wrapper/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"136620123","text":"import math\nfrom typing import Dict, List, Tuple\nimport mysql.connector\nimport unittest\nimport time\nimport sys\nfrom collections import defaultdict\n\n# Modify these parameters per call\nLEAGUE = 'coh'\nSEASON = 'sxii'\nWEEK = 1\nPRIOR_STDEV_BY_WEEK = {\n 1: 300.0,\n 2: 450.0,\n 3: 600.0,\n 4: 600.0,\n}\n\nAUTOMATCH_DEADLINE_BY_WEEK = {\n 1: '2021-07-18 18:00:00',\n 2: '2021-07-25 18:00:00',\n 3: '2021-07-01 18:00:00',\n 4: '2021-07-08 09:00:00',\n}\n\nOVERTURN_RESULTS = {\n}\n\nPRIOR_STDEV = PRIOR_STDEV_BY_WEEK[WEEK]\nAUTOMATCH_DEADLINE = AUTOMATCH_DEADLINE_BY_WEEK[WEEK]\n\nmysql_db_host = 'condor.live'\nmysql_db_user = 'necrobot-read'\nmysql_db_passwd = 'necrobot-read'\nmysql_db_name = 'condor_xii'\n\n# Don't modify these\nFOLDER = 'data_{league}'.format(league=LEAGUE)\nPRIOR_ELOS_FILENAME = '{f}/ratings_{s}_{lg}_wk{w}.csv'.format(f=FOLDER, s=SEASON, lg=LEAGUE, w=0)\nELO_RESULTS_FILENAME = '{f}/ratings_{s}_{lg}_wk{w}'.format(f=FOLDER, s=SEASON, lg=LEAGUE, w=WEEK)\nRECORDS_FILENAME = '{f}/records_{s}_{lg}_wk{w}'.format(f=FOLDER, s=SEASON, lg=LEAGUE, w=WEEK)\nLOG_FILENAME = '{f}/elorate_log.txt'.format(f=FOLDER)\n\n# Don't use these racers in the computation\nignored_racers = [\n]\n\n# Add these extra matches into the computation\ncustom_matches = [\n]\n\n# The biggielevs model ------------------------------\n\n\ndef biggielevs_phi(x: float) -> float:\n alpha = 0.42\n return (1 + alpha*math.erf(x*math.sqrt(math.pi)/2) + (1-alpha)*(x / (1 + abs(x))))/2\n\n\ndef biggielevs_dphi(x: float) -> float:\n alpha = 0.42\n return (alpha*math.exp(-x*x*math.pi/4) + (1-alpha)*(1/(1+abs(x))**2))/2\n\n\ndef biggielevs_dlogphi(x: float) -> float:\n return biggielevs_dphi(x)/biggielevs_phi(x)\n\n\n# Unit conversions-----------------------------------\n\"\"\"\nLinear conversion at the elo=150 mark (the biggie-levs and bradley-terry model agree on winrates at 0.52 <-> 150)\n\"\"\"\n\n\ndef elo_to_r(elo: float) -> float:\n return elo*(0.52/150)\n\n\ndef r_to_elo(r: float) -> float:\n return r*(150/0.52)\n\n\n# Matchup, Player classes----------------------------\n\nclass Matchup(object):\n def __init__(self):\n self.wins = 0\n self.losses = 0\n\n @property\n def games(self):\n return self.wins + self.losses\n\n\nclass Player(object):\n def __init__(self, name, prior_elo=0.0, prior_stdev=400.0):\n self._name = name\n self._prior_r = elo_to_r(prior_elo)\n self._prior_var = elo_to_r(prior_stdev)**2\n self._last_r = self._prior_r\n self._r = self._prior_r\n self._next_r = self._prior_r\n self._last_step_size = 10\n\n self._matchups = dict() # type: Dict[Player, Matchup]\n self._total_wins = 0\n self._test_matchups = dict()\n self._total_test_wins = 0\n\n self._name_lower = name.lower()\n self._hash = hash(self._name)\n\n def __hash__(self):\n return self._hash\n\n def __eq__(self, other):\n return self._name_lower == other._name_lower\n\n def __ne__(self, other):\n return not self.__eq__(other)\n\n @property\n def r(self):\n return self._r\n\n @property\n def name(self):\n return self._name\n\n @property\n def elo(self):\n return r_to_elo(self._r)\n\n @property\n def last_r(self):\n return self._last_r\n\n def log_likelihood(self, r):\n evidence_ll = 0\n for player, matchup in self._matchups.items():\n a = biggielevs_phi(r - player.r)\n evidence_ll += matchup.wins*math.log(a) + matchup.losses*math.log(1-a)\n prior_ll = -((r - self._prior_r)/self._prior_var)**2 - math.log(math.sqrt(2*math.pi)*self._prior_var)\n return evidence_ll + prior_ll\n\n @property\n def grad_component(self):\n evidence_cmp = 0\n for player, matchup in self._matchups.items():\n a = biggielevs_dphi(self.r - player.r)\n b = biggielevs_phi(self.r - player.r)\n evidence_cmp += a*(matchup.wins - matchup.games*b)/(b-b**2)\n priors_cmp = (self._prior_r - self._r)/self._prior_var\n return evidence_cmp + priors_cmp\n\n @property\n def matchup_info(self) -> str:\n format_str = '{name}: [{wins} - {losses}] -- '\n matchup_format = 'vs {opp}: [{wins} - {losses}]; '\n total_wins = 0\n total_losses = 0\n for _, matchup in self._matchups.items():\n total_wins += matchup.wins\n total_losses += matchup.losses\n outstr = format_str.format(name=self.name, wins=total_wins, losses=total_losses)\n for player, matchup in self._matchups.items():\n outstr += matchup_format.format(opp=player.name, wins=matchup.wins, losses=matchup.losses)\n return outstr[:-2]\n\n def add_games(self, opponent, wins: int, losses: int):\n if opponent in self._matchups:\n matchup = self._matchups[opponent]\n else:\n matchup = Matchup()\n self._matchups[opponent] = matchup\n\n matchup.wins += wins\n self._total_wins += wins\n matchup.losses += losses\n\n def add_test_games(self, opponent, wins, losses):\n if opponent in self._test_matchups:\n matchup = self._test_matchups[opponent]\n else:\n matchup = Matchup()\n self._test_matchups[opponent] = matchup\n matchup.wins += wins\n self._total_test_wins += wins\n matchup.losses += losses\n\n def prep_mm_iteration(self):\n self._next_r = self._r + 0.01*self.grad_component\n\n def finalize_mm_iteration(self):\n self._last_r = self._r\n self._r = self._next_r\n\n\n# Module methods---------------------------------\n\ndef iterate_elos(player_list, max_repeats=200000, max_sec=1200, verbose=False):\n format_str = 'Iteration: {iter:>7} Time: {sec:10.10f}s Elo L2: {elo:20.20f} Grad L2: {grad:20.20f} LL: {ll:20.20f}'\n begin = time.monotonic()\n\n l2_elo_diff = 0.0\n l2_grad = 0.0\n sec = begin\n\n with open(LOG_FILENAME, 'w') as iter_log:\n for idx in range(max_repeats):\n l2_r_diff = 0.0\n l2_grad = 0.0\n\n # run one iteration for each player\n for player in player_list:\n player.prep_mm_iteration()\n\n for player in player_list:\n player.finalize_mm_iteration()\n l2_r_diff += (player.r - player.last_r)**2\n l2_grad += player.grad_component**2\n\n l2_elo_diff = r_to_elo(math.sqrt(l2_r_diff))\n l2_grad = math.sqrt(l2_grad)\n sec = time.monotonic() - begin\n\n if verbose and (idx % 500 == 0):\n log_prob = 0\n for player in player_list:\n log_prob += player.log_likelihood(player.r)\n print(format_str.format(iter=idx, sec=sec, elo=l2_elo_diff, grad=l2_grad, ll=log_prob))\n iter_log.write(format_str.format(iter=idx, sec=sec, elo=l2_elo_diff, grad=l2_grad, ll=log_prob) + '\\n')\n\n if l2_elo_diff < 0.000000000000001 or l2_grad < 0.00000000000001:\n iter_log.write('Finished in {iter} iterations.\\n'.format(iter=idx))\n return\n elif sec > max_sec:\n log_prob = 0\n for player in player_list:\n log_prob += player.log_likelihood(player.r)\n iter_log.write(\n 'Timed out: '\n + format_str.format(iter=idx, sec=sec, elo=l2_elo_diff, grad=l2_grad, ll=log_prob)\n + '\\n'\n )\n return\n\n log_prob = 0\n for player in player_list:\n log_prob += player.log_likelihood(player.r)\n iter_log.write(\n 'Completed maximum number of iterations: '\n + format_str.format(iter=max_repeats, sec=sec, elo=l2_elo_diff, grad=l2_grad, ll=log_prob)\n + '\\n'\n )\n\n\ndef normalize_elos(player_list, avg_elo):\n list_tot = 0\n for player in player_list:\n list_tot += player.elo\n list_avg = list_tot / len(player_list)\n\n for player in player_list:\n player.add_to_elo(avg_elo - list_avg)\n\n\ndef write_csv(player_list, filename='results.csv'):\n _do_write(player_list, filename, '{name},{elo}')\n\n\ndef write_formatted(player_list, filename='results.txt'):\n _do_write(player_list, filename, '{name:>20}: {elo:4.0f}')\n\n\ndef _do_write(player_list, filename, format_str):\n with open(filename, 'w') as file:\n for player in player_list:\n file.write(format_str.format(name=player.name, elo=player.elo) + '\\n')\n\n\ndef make_player_dict(\n prior_elos: List[Tuple[str, float]],\n gametuples: List[Tuple[str, str, int, int]],\n stdev: float,\n test_gametuples: List[Tuple[str, str, int, int]] = None\n) -> Dict[str, Player]:\n if test_gametuples is None:\n test_gametuples = []\n \n player_dict = dict() # type: Dict[str, Player]\n for player_name, elo in prior_elos:\n player_dict[player_name.lower()] = Player(name=player_name, prior_elo=elo, prior_stdev=stdev)\n\n for p1name, p2name, p1wins, p2wins in gametuples:\n if p1name not in player_dict:\n print('Error: {name} has no prior elo.'.format(name=p1name))\n player_dict[p1name] = Player(name=p1name, prior_elo=1500, prior_stdev=stdev)\n # continue\n if p2name not in player_dict:\n print('Error: {name} has no prior elo.'.format(name=p2name))\n player_dict[p2name] = Player(name=p2name, prior_elo=1500, prior_stdev=stdev)\n # continue\n\n p1 = player_dict[p1name]\n p2 = player_dict[p2name]\n p1.add_games(opponent=p2, wins=p1wins, losses=p2wins)\n p2.add_games(opponent=p1, wins=p2wins, losses=p1wins)\n\n for p1name, p2name, p1wins, p2wins in test_gametuples:\n p1 = player_dict[p1name]\n p2 = player_dict[p2name]\n p1.add_test_games(opponent=p2, wins=p1wins, losses=p2wins)\n p2.add_test_games(opponent=p1, wins=p2wins, losses=p1wins)\n\n return player_dict\n\n\ndef write_records(player_list: List[Player], filename: str):\n with open(filename, 'w') as outfile:\n for player in sorted(player_list, key=lambda p: p.name.lower()):\n outfile.write(player.matchup_info + '\\n')\n\n\n# Necrobot specifics----------------------------------\n\ndef get_elos(\n prior_filename: str,\n games_database_name: str,\n max_repeats: int = 200000,\n max_sec: int = 1200,\n verbose: bool = False\n):\n prior_stdev = PRIOR_STDEV\n prior_elos = read_priors(prior_filename)\n gametuples = get_gametuples_from_database(games_database_name)\n for game in custom_matches:\n gametuples.append(game)\n\n total_games = 0\n for p1, p2, w1, w2 in gametuples:\n total_games += w1 + w2\n print(\"Total number of games counted: {}\".format(total_games))\n\n player_dict = make_player_dict(\n prior_elos=prior_elos,\n gametuples=gametuples,\n stdev=prior_stdev\n )\n\n iterate_elos(\n player_list=player_dict.values(),\n max_repeats=max_repeats,\n max_sec=max_sec,\n verbose=verbose\n )\n\n sorted_players = sorted(player_dict.values(), key=lambda p: p.r, reverse=True)\n write_csv(sorted_players, '{}.csv'.format(ELO_RESULTS_FILENAME))\n write_formatted(sorted_players, '{}.txt'.format(ELO_RESULTS_FILENAME))\n write_records(sorted_players, '{}.txt'.format(RECORDS_FILENAME))\n\n\ndef read_priors(filename: str) -> List[Tuple[str, float]]:\n prior_elos = list() # type: List[Tuple[str, float]]\n with open(filename) as file:\n for line in file:\n args = line.split(',')\n prior_elos.append((args[0], float(args[1]),))\n return prior_elos\n\n\ndef get_gametuples_from_database(database_name):\n db_conn = mysql.connector.connect(\n user=mysql_db_user,\n password=mysql_db_passwd,\n host=mysql_db_host,\n database=database_name\n )\n\n try:\n cursor = db_conn.cursor()\n\n cursor.execute(\n \"\"\"\n SELECT \n udw.twitch_name AS winner_name,\n udl.twitch_name AS loser_name\n FROM \n race_summary\n JOIN\n matches ON matches.match_id = race_summary.match_id\n JOIN\n necrobot.users udw ON udw.user_id = race_summary.winner_id\n JOIN\n necrobot.users udl ON udl.user_id = race_summary.loser_id\n WHERE\n matches.league_tag = '{}' AND matches.finish_time < '{}'\n ORDER BY matches.finish_time ASC\n \"\"\".format(LEAGUE, AUTOMATCH_DEADLINE)\n )\n\n matchup_tuples = defaultdict(lambda: [0, 0])\n for row in cursor:\n winner = row[0].lower()\n loser = row[1].lower()\n\n if winner in ignored_racers or loser in ignored_racers:\n print(\"Ignored game {r1}-{r2}\".format(r1=winner, r2=loser))\n\n if (loser, winner) in OVERTURN_RESULTS:\n OVERTURN_RESULTS.remove((loser, winner))\n winner, loser = loser, winner\n print(\"Overturned game {r1}-{r2}\".format(r1=loser, r2=winner))\n\n if winner < loser:\n match = matchup_tuples[(winner, loser)]\n match[0] += 1\n else:\n match = matchup_tuples[(loser, winner)]\n match[1] += 1\n\n return list((k[0], k[1], v[0], v[1]) for k, v in matchup_tuples.items())\n\n finally:\n db_conn.close()\n\n\n# Main --------------------------------------\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n priors_filename = sys.argv[1]\n else:\n priors_filename = PRIOR_ELOS_FILENAME\n\n print('Getting Elo priors from file {}...'.format(priors_filename))\n get_elos(priors_filename, mysql_db_name, verbose=True)\n print('Elos written to file {}.csv'.format(ELO_RESULTS_FILENAME))\n\n\n# Tests -------------------------------------\n\nclass TestRatings(unittest.TestCase):\n def setUp(self):\n pass\n\n def test_ratings(self):\n # TODO\n pass\n","sub_path":"elorate.py","file_name":"elorate.py","file_ext":"py","file_size_in_byte":14028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"273421837","text":"from OpenGL.GL import *\r\nfrom OpenGL.GLU import *\r\nfrom OpenGL.GLUT import *\r\nimport pygame\r\nfrom sys import exit\r\nimport numpy as np\r\nimport math\r\n\r\n\r\n##### initial parameters ####\r\n\r\nXoffset, Yoffset = 3, 3 # increment or decrement in ball position\r\n### Bricks parameters ###\r\nBricks = [] # List to store all bricks, each element of list is a brick class\r\nbrickWidth = 54\r\nbrickHeight = 26\r\nbrickShiftX= 59\r\nbrickShiftY = 32.5\r\nfirstPointX = 22 # start point of bricks \r\nfirstPointY = 583 # start point of bricks \r\nactiveBricks = 528 # number of active bricks\r\n### Game state parameters ###\r\nlife = 3\r\nscore = 0\r\nhighestScore = 0\r\ndead = True # if true, the player is dead\r\nresume = False # make it true to make the player play after he is dead\r\n### Timer parameters ###\r\ncount = 0 # temp variable to count seconds\r\n### Coloring parameters ###\r\ncolor = (1,0,0)\r\nw = 1 # temp variable changes gradually to make color of text changes gradually\r\ncolorInc = False # if true, value of w increases\r\n### Menu parameters ###\r\naction = [\"PLAY\", \"QUIT\"] # actions done when buttons clicked\r\nclicked = False # if true, the left mouse button is clicked\r\nz = -10 # changes z of menu objects to be in or out the frustum\r\n\r\n#############################\r\n\r\n#### initializing sound ####\r\npygame.mixer.init()\r\n\r\nhittingBrick = pygame.mixer.Sound(\"hitting brick.wav\")\r\nhittingPaddle = pygame.mixer.Sound(\"hitting-paddle.wav\")\r\nhittingWall = pygame.mixer.Sound(\"hitting-wall.wav\")\r\nlose = pygame.mixer.Sound(\"lose.wav\")\r\ndeath = pygame.mixer.Sound(\"death.wav\")\r\nmouse = pygame.mixer.Sound(\"Mouse Click.wav\")\r\n\r\n############################\r\n\r\nclass Display():\r\n windowWidth = 750\r\n windowHeight = 1000\r\n frustumHeight = [0, windowHeight]\r\n mouseX = windowWidth / 2\r\n mouseY = windowHeight / 2\r\n cameraPosition = [0, frustumHeight[0], 0] #eyeX, eyeY, eyeZ\r\n\r\n @staticmethod\r\n def init():\r\n glutInit()\r\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH)\r\n glutInitWindowSize(Display.windowWidth, Display.windowHeight)\r\n glutCreateWindow(b\"Break Out game\")\r\n Display.camera()\r\n glutDisplayFunc(Render)\r\n glutIdleFunc(Render)\r\n glutTimerFunc(100, Timer, 1)\r\n glutPassiveMotionFunc(mouseMotion)\r\n glutMouseFunc(mouseClick)\r\n glutKeyboardFunc(Keyboard)\r\n \r\n @staticmethod\r\n def camera():\r\n glMatrixMode(GL_PROJECTION)\r\n glLoadIdentity()\r\n glOrtho(0,Display.windowWidth, Display.frustumHeight[0], Display.frustumHeight[1], -100, 100)\r\n gluLookAt(Display.cameraPosition[0], Display.cameraPosition[1], Display.cameraPosition[2],\r\n Display.cameraPosition[0], Display.cameraPosition[1], Display.cameraPosition[2]-1,\r\n 0, 1, 0)\r\n glMatrixMode(GL_MODELVIEW)\r\n glEnable(GL_DEPTH_TEST)\r\n\r\nclass Ball():\r\n radius = 10\r\n position = [100, 40] # initial position of ball\r\n boundingBox = [position[0]-radius, position[1]+radius, position[0]+radius, position[1]-radius] # Left, Top, Right, Bottom\r\n\r\nclass Paddle():\r\n width, height = 100, 20\r\n position = [0, 70]\r\n bottomLeft = [position[0]- width/2, position[1]+Display.frustumHeight[0]+0.5]\r\n bottomRight = [position[0]+ width/2, position[1]+Display.frustumHeight[0]+0.5]\r\n topRight = [position[0]+ width/2, position[1]+Display.frustumHeight[0]+height+0.5]\r\n topLeft = [position[0]- width/2, position[1]+Display.frustumHeight[0]+height+0.5]\r\n\r\nclass Brick():\r\n def __init__(self, bottomLeft):\r\n self.bottomLeft = bottomLeft\r\n self.bottomRight = (bottomLeft[0]+brickWidth, bottomLeft[1])\r\n self.topRight = (bottomLeft[0]+brickWidth, bottomLeft[1]+brickHeight)\r\n self.topLeft = (bottomLeft[0], bottomLeft[1]+brickHeight)\r\n\r\n self.active = True # if True, brick will be drawn\r\n\r\nclass Collision():\r\n \r\n objList = [] #minX, maxY, maxX, minY # list to store bounding box of bricks\r\n direction = 0 # 0 --> ForwardRight, 1 --> ForwardLeft, 2 --> BackwardLeft, 3 --> BackwardRight\r\n \r\n @staticmethod\r\n def getDirection():\r\n if Xoffset >= 0 and Yoffset >= 0: # going ForwardRight\r\n Collision.direction = 0 \r\n\r\n elif Xoffset >= 0 and Yoffset < 0: # going BackwardRight\r\n Collision.direction = 3\r\n\r\n elif Xoffset < 0 and Yoffset >= 0: # going ForwardLeft\r\n Collision.direction = 1 \r\n\r\n elif Xoffset < 0 and Yoffset < 0: # going BackwardLeft\r\n Collision.direction = 2 \r\n \r\n @staticmethod\r\n def checkTopFace(): # of the ball\r\n global Xoffset\r\n global Yoffset\r\n if (Ball.boundingBox[1] < Collision.objList[1] and Ball.boundingBox[1] > Collision.objList[3] ) and \\\r\n ((Ball.boundingBox[0] >= Collision.objList[0] and Ball.boundingBox[0] <= Collision.objList[2]) or \\\r\n (Ball.boundingBox[2] >= Collision.objList[0] and Ball.boundingBox[2] <= Collision.objList[2]) or \\\r\n (Ball.boundingBox[0] < Collision.objList[0] and Ball.boundingBox[2] > Collision.objList[2])):\r\n\r\n Yoffset = -Yoffset\r\n return True\r\n else:\r\n return False\r\n\r\n @staticmethod\r\n def checkBottomFace(): # of the ball\r\n global Xoffset\r\n global Yoffset\r\n if (Ball.boundingBox[3] > Collision.objList[3] and Ball.boundingBox[3] < Collision.objList[1]) and \\\r\n ((Ball.boundingBox[0] >= Collision.objList[0] and Ball.boundingBox[0] <= Collision.objList[2]) or \\\r\n (Ball.boundingBox[2] >= Collision.objList[0] and Ball.boundingBox[2] <= Collision.objList[2]) or \\\r\n (Ball.boundingBox[0] < Collision.objList[0] and Ball.boundingBox[2] > Collision.objList[2])):\r\n Yoffset = -Yoffset\r\n return True\r\n else:\r\n return False\r\n \r\n @staticmethod\r\n def checkRightFace(): # of the ball\r\n global Xoffset\r\n global Yoffset\r\n if (Ball.boundingBox[2] > Collision.objList[0] and Ball.boundingBox[2] < Collision.objList[2] ) and \\\r\n ((Ball.boundingBox[3] >= Collision.objList[3] and Ball.boundingBox[3] <= Collision.objList[1]) or \\\r\n (Ball.boundingBox[1] >= Collision.objList[3] and Ball.boundingBox[1] <= Collision.objList[1]) or \\\r\n (Ball.boundingBox[3] < Collision.objList[3] and Ball.boundingBox[1] > Collision.objList[1])):\r\n Xoffset = -Xoffset\r\n return True\r\n else:\r\n return False\r\n \r\n @staticmethod\r\n def checkLeftFace(): # of the ball\r\n global Xoffset\r\n global Yoffset\r\n if (Ball.boundingBox[0] < Collision.objList[2] and Ball.boundingBox[0] > Collision.objList[0] ) and \\\r\n ((Ball.boundingBox[3] >= Collision.objList[3] and Ball.boundingBox[3] <= Collision.objList[1]) or \\\r\n (Ball.boundingBox[1] >= Collision.objList[3] and Ball.boundingBox[1] <= Collision.objList[1]) or \\\r\n (Ball.boundingBox[3] < Collision.objList[3] and Ball.boundingBox[1] > Collision.objList[1])):\r\n Xoffset = -Xoffset \r\n return True\r\n else:\r\n return False\r\n \r\n @staticmethod\r\n def detectBrick(): # detect collision of ball with brick\r\n Collision.getDirection()\r\n\r\n if Collision.direction == 0 : # ForwardRight\r\n if Collision.checkTopFace() or Collision.checkRightFace():\r\n return True\r\n else:\r\n return False\r\n\r\n elif Collision.direction == 1 : #ForwardLeft\r\n if Collision.checkTopFace() or Collision.checkLeftFace():\r\n return True\r\n else:\r\n return False\r\n\r\n elif Collision.direction == 2 : # BackwardLeft\r\n if Collision.checkBottomFace() or Collision.checkLeftFace():\r\n return True\r\n else:\r\n return False\r\n\r\n elif Collision.direction == 3 : # BackwardRight\r\n if Collision.checkBottomFace() or Collision.checkRightFace():\r\n return True\r\n else:\r\n return False\r\n \r\n @staticmethod\r\n def detectWall(): # detect collision of ball with wall\r\n global Xoffset, Yoffset, dead, life\r\n\r\n if Ball.boundingBox[2] >= Display.windowWidth-30 or Ball.boundingBox[0] <= 0+30 : # check left and right walls\r\n Xoffset = -Xoffset \r\n pygame.mixer.Sound.play(hittingWall)\r\n elif Ball.boundingBox[3] <= Display.frustumHeight[0] : # check bottom wall\r\n Yoffset = -Yoffset\r\n dead = True\r\n life -= 1\r\n if life > 0:\r\n pygame.mixer.Sound.play(lose)\r\n elif Ball.boundingBox[1] >= Display.frustumHeight[1]-80: # check top wall\r\n Yoffset = -Yoffset\r\n pygame.mixer.Sound.play(hittingWall)\r\n\r\n @staticmethod\r\n def detectPaddle(): # detect collision of ball with paddle\r\n Collision.objList = [Paddle.bottomLeft[0], Paddle.topRight[1], Paddle.topRight[0], Paddle.bottomLeft[1]]\r\n if Collision.checkBottomFace() :\r\n pygame.mixer.Sound.play(hittingWall)\r\n\r\ndef resetGame():\r\n global Xoffset, Yoffset, Bricks, firstPointX, firstPointY, activeBricks,\\\r\n life, score, dead, resume, count, color\r\n\r\n Xoffset = 3\r\n Yoffset = 3\r\n Bricks = [] \r\n firstPointX = 22 \r\n firstPointY = 583\r\n activeBricks = 528 \r\n life = 3\r\n score = 0\r\n dead = True \r\n resume = False \r\n count = 0 \r\n color = (1,0,0)\r\n Display.frustumHeight = [0, Display.windowHeight]\r\n Paddle.width = 100\r\n generateLevel()\r\n\r\ndef generateLevel():\r\n global Bricks\r\n \r\n ### STRAIGHT LINES UP & DOWN DRAWING ###\r\n XstartPoint = firstPointX\r\n YstartPoint= firstPointY\r\n \r\n for Lines in range (0,44,1):\r\n for N in range (1,12,1):\r\n if Lines/4 == N:\r\n YstartPoint += 4*brickShiftY\r\n \r\n for Rows in range (0,12,1):\r\n Bricks.append(Brick((XstartPoint,YstartPoint)))\r\n XstartPoint += brickShiftX\r\n YstartPoint += brickShiftY\r\n XstartPoint = 22\r\n\r\ngenerateLevel()\r\n \r\ndef button(text, bottomLeft, width, height, activeColor, inactiveColor, action):\r\n global z\r\n\r\n if (bottomLeft[0]+ width+30 > Display.mouseX and Display.mouseX > bottomLeft[0]-30) and\\\r\n (bottomLeft[1] + height > Display.windowHeight-Display.mouseY and Display.windowHeight-Display.mouseY > bottomLeft[1]):\r\n glColor4f(activeColor[0], activeColor[1], activeColor[2], activeColor[3])\r\n if clicked is True:\r\n if action == \"PLAY\":\r\n pygame.mixer.Sound.play(mouse) \r\n z = 200\r\n elif action == \"QUIT\":\r\n pygame.mixer.Sound.play(mouse) \r\n exit()\r\n else:\r\n glColor4f(inactiveColor[0], inactiveColor[1], inactiveColor[2], inactiveColor[3])\r\n # Drawing button\r\n glBegin(GL_POLYGON)\r\n glVertex3f(bottomLeft[0], bottomLeft[1], z)\r\n glVertex3f(bottomLeft[0]+width, bottomLeft[1], z)\r\n glVertex3f(bottomLeft[0]+width, bottomLeft[1]+height, z)\r\n glVertex3f(bottomLeft[0], bottomLeft[1]+height, z)\r\n glEnd()\r\n drawCircle(30, 285, bottomLeft[1]+30)\r\n drawCircle(30, 465, bottomLeft[1]+30)\r\n\r\n glColor(0,0,0)\r\n drawText(text, bottomLeft[0]+(width/2)-30, bottomLeft[1]+(height/2)-15, 0.35, 0.35, 4)\r\n\r\ndef drawCircle(r=1, xc=0, yc=0):\r\n glBegin(GL_POLYGON)\r\n for theta in np.arange(0, 360, 1):\r\n x = r * math.cos(theta * math.pi / 180) + xc\r\n y = r * math.sin(theta * math.pi / 180) + yc\r\n glVertex3f(x, y, z)\r\n glEnd()\r\n\r\ndef changeColor(y): # change color of objects to the frame color they are in its range\r\n global color\r\n if y >= Display.frustumHeight[0]+ firstPointY+ 4* brickShiftY and y < Display.frustumHeight[0]+ firstPointY+ 8* brickShiftY:\r\n color = (.9647,.4314,0) # ORANGE\r\n elif y >= Display.frustumHeight[0]+firstPointY and y <= Display.frustumHeight[0]+firstPointY+ 4* brickShiftY:\r\n color = (0,1,0) # GREEN\r\n elif y >= Display.frustumHeight[0]+ firstPointY- 4* brickShiftY and y <= Display.frustumHeight[0]+ firstPointY:\r\n color = (1,1,0) #YELLOW\r\n elif y >= Display.frustumHeight[0] and y <= Display.frustumHeight[0]+ 14.738* brickShiftY:\r\n color = (1,1,1) #WHITE\r\n elif (y >= Display.frustumHeight[0]+firstPointY +8* brickShiftY and y <= Display.frustumHeight[0]+firstPointY + 12* brickShiftY) or (y <= Display.frustumHeight[0]+firstPointY - 15.8* brickShiftY):\r\n color = (0,0,1) ## BLUE\r\n\r\ndef drawQuad(bottomLeft, bottomRight, topRight, topLeft):\r\n glBegin(GL_QUADS)\r\n glVertex(bottomLeft[0], bottomLeft[1], 0)\r\n glVertex(bottomRight[0], bottomRight[1], 0)\r\n glVertex(topRight[0], topRight[1], 0)\r\n glVertex(topLeft[0], topLeft[1], 0)\r\n glEnd()\r\n\r\ndef drawFrameStrip(firstPoint , num ): # draw frame strips \r\n glBegin(GL_LINES) \r\n # Left side\r\n glVertex(firstPoint[0], firstPoint[1]) # firstpoint[0] : x of the line strip of frame on left of the window\r\n glVertex(firstPoint[0], firstPoint[1]+num*brickShiftY) # firstpoint[1] : y of the line strip of frame of both sides of the window\r\n # Right side\r\n glVertex(firstPoint[2], firstPoint[1]) # firstpoint[2] : x of the line strip of frame on right of the window\r\n glVertex(firstPoint[2], firstPoint[1]+num*brickShiftY)\r\n glEnd()\r\n\r\ndef drawFrame():\r\n glColor3f(.9647,.4314,0) # ORANGE\r\n glLineWidth(80)\r\n drawFrameStrip([Display.windowWidth-745 ,Display.frustumHeight[0]+firstPointY +4* brickShiftY ,Display.windowWidth - 5], 4)\r\n\r\n glColor3f(0,1,0) # GREEN\r\n drawFrameStrip([Display.windowWidth -745 ,Display.frustumHeight[0]+firstPointY ,Display.windowWidth - 5], 4)\r\n\r\n glColor3f(1,1,0) #YELLOW\r\n drawFrameStrip([Display.windowWidth -745 ,Display.frustumHeight[0]+firstPointY -4* brickShiftY ,Display.windowWidth - 5], 4)\r\n\r\n glColor3f(0,0,1) ## BLUE\r\n drawFrameStrip([Display.windowWidth -745 ,Display.frustumHeight[0]+firstPointY +8* brickShiftY ,Display.windowWidth - 5], 4)\r\n drawFrameStrip([Display.windowWidth -745 ,Display.frustumHeight[0]+ firstPointY - 15.8* brickShiftY ,Display.windowWidth - 5], .6)\r\n drawline(Display.windowWidth, Display.frustumHeight[1]-7)\r\n\r\n glColor3f(1,1,1) #WHITE\r\n drawFrameStrip([Display.windowWidth -745 , Display.frustumHeight[0]+0 ,Display.windowWidth - 5], 14.738)\r\n\r\ndef drawline(first,second):\r\n glBegin(GL_LINES)\r\n glVertex(0,second -3)\r\n glVertex(first , second-3)\r\n glEnd()\r\n \r\ndef mouseClick(button, state, x, y):\r\n global clicked\r\n\r\n if button == GLUT_LEFT_BUTTON:\r\n if state == GLUT_DOWN:\r\n clicked = True\r\n else:\r\n clicked = False \r\n\r\ndef mouseMotion(x, y):\r\n Display.mouseX = x \r\n Display.mouseY = y\r\n\r\ndef Keyboard(key, x, y):\r\n global resume\r\n if key == b\" \": # press space bar to resume when player dies\r\n resume = True\r\n if ord(key) == 27 : # press Esc button to exit\r\n exit()\r\n\r\ndef drawText(string, posX, posY, scaleX, scaleY, lineWidth):\r\n glLineWidth(lineWidth)\r\n glPushMatrix() \r\n glLoadIdentity() \r\n glTranslate(posX, posY, 0)\r\n glScale(scaleX, scaleY, 3)\r\n string = string.encode() # conversion from Unicode string to byte string\r\n for c in string:\r\n glutStrokeCharacter(GLUT_STROKE_ROMAN, c)\r\n glPopMatrix()\r\n \r\ndef Timer(t):\r\n global count\r\n \r\n if z!= -10: # timer doesn't count when the player is in the menu\r\n count += 1\r\n if count == 100: # for 10 seconds\r\n count = 0\r\n\r\n if 90 <= count < 100: # is true for 10 times to make bricks go down gradually \r\n # frustum changes after every 10 seconds \r\n Display.frustumHeight[0] += brickShiftY/10 # Translate bottom of frustum \r\n Display.frustumHeight[1] += brickShiftY/10 # Translate top of frustum\r\n if Paddle.width >= 50:\r\n Paddle.width -= 3/10\r\n \r\n Display.camera() # update camera\r\n Render()\r\n \r\n glutTimerFunc(100, Timer, 1)\r\n\r\ndef Render():\r\n global Xoffset, Yoffset, activeBricks, dead, life,\\\r\n score, resume, color, highestScore, colorInc, w\r\n\r\n glClearColor(0,0,0,0)\r\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\r\n\r\n drawFrame()\r\n\r\n if z != 200: # render menu only \r\n button(\"Play\", (285,(Display.frustumHeight[0]+Display.frustumHeight[1])/2),180,60, (1,1,0,0.5), (0.2745,0.5089,0.7588,0.5), \"PLAY\")\r\n button(\"Quit\", (285,(Display.frustumHeight[0]+Display.frustumHeight[1])/3),180,60, (1,1,1,0.5), (0.28,0.5,0.7,0.5), \"QUIT\")\r\n glColor(.9647,.4314,0)\r\n drawText(\"Breakout\", Display.windowWidth-525, Display.windowHeight-250, 0.6, 0.6, 6.5)\r\n\r\n else: # render game without menu\r\n\r\n #### conditions to change text color ####\r\n if colorInc :\r\n if w < 1:\r\n w += 0.03\r\n else:\r\n colorInc = False\r\n else:\r\n if w > 0:\r\n w -= 0.03\r\n else:\r\n colorInc = True\r\n \r\n if dead is True :\r\n Ball.position[0] = Paddle.position[0] # update ball position to stick on paddle\r\n Ball.position[1] = Display.frustumHeight[0]+ Paddle.position[1]+ Paddle.height+ Ball.radius+ 2\r\n Xoffset, Yoffset = 0, 0 # stop the ball until resume\r\n \r\n if resume :\r\n dead = False\r\n resume = False\r\n Xoffset = 3\r\n Yoffset = 3\r\n\r\n if activeBricks > 0 and life > 0 :\r\n # draw game states on screen\r\n glColor(w, w, w) # to make text apper and disapper with time\r\n drawText( str(score), Display.windowWidth/3-20, Display.frustumHeight[0]+20, 0.3, 0.3, 3)\r\n glColor(1,1,1)\r\n drawText( str(life), Display.windowWidth*2/3-20, Display.frustumHeight[0]+20, 0.3, 0.3, 3)\r\n\r\n # Draw paddle\r\n glColor3f(0,0,1) ## BLUE\r\n glPushMatrix()\r\n glLoadIdentity()\r\n if not (Display.mouseX < Paddle.width/2 or Display.mouseX > Display.windowWidth-Paddle.width/2): # to make paddle between left and right borders of window\r\n Paddle.position[0] = Display.mouseX # updating paddle position\r\n Paddle.bottomLeft = [Paddle.position[0]- Paddle.width/2, Paddle.position[1]+Display.frustumHeight[0]]\r\n Paddle.bottomRight = [Paddle.position[0]+ Paddle.width/2, Paddle.position[1]+Display.frustumHeight[0]]\r\n Paddle.topRight = [Paddle.position[0]+ Paddle.width/2, Paddle.position[1]+Display.frustumHeight[0]+Paddle.height]\r\n Paddle.topLeft = [Paddle.position[0]- Paddle.width/2, Paddle.position[1]+Display.frustumHeight[0]+Paddle.height]\r\n drawQuad(Paddle.bottomLeft, Paddle.bottomRight, Paddle.topRight, Paddle.topLeft)\r\n glPopMatrix()\r\n\r\n # Draw ball\r\n changeColor(Ball.position[1])\r\n glColor(color[0], color[1], color[2],0)\r\n glPushMatrix()\r\n glLoadIdentity()\r\n glTranslate(Ball.position[0], Ball.position[1],0)\r\n glutSolidSphere(Ball.radius, 50, 50)\r\n glPopMatrix()\r\n \r\n # Draw bricks\r\n for i in range(len(Bricks)):\r\n if Bricks[i].active is True:\r\n if Bricks[i].bottomLeft[1] <= Paddle.topLeft[1] + 2*Ball.radius + 1: # player dies when bricks go down \r\n life = 0\r\n break\r\n \r\n changeColor(Bricks[i].bottomLeft[1])\r\n glColor3f(color[0], color[1], color[2])\r\n drawQuad(Bricks[i].bottomLeft, Bricks[i].bottomRight, Bricks[i].topRight, Bricks[i].topLeft)\r\n \r\n if not dead: # doen't check collision when player is dead # saves computations\r\n Collision.objList = [Bricks[i].bottomLeft[0], Bricks[i].topRight[1], Bricks[i].topRight[0], Bricks[i].bottomLeft[1]] # updating objlist to check collision\r\n if Bricks[i].active is True and Collision.detectBrick() : # if true, this brick will not be drawn\r\n Bricks[i].active = False\r\n activeBricks -= 1\r\n score += 1\r\n pygame.mixer.Sound.play(hittingBrick)\r\n\r\n if not dead: # doen't check collision when player is dead # saves computations\r\n Collision.detectWall()\r\n Collision.detectPaddle()\r\n Ball.position[0] += Xoffset # updating ball position\r\n Ball.position[1] += Yoffset\r\n Ball.boundingBox = [Ball.position[0]-Ball.radius, Ball.position[1]+Ball.radius, Ball.position[0]+Ball.radius, Ball.position[1]-Ball.radius] # Left, Top, Right, Bottom\r\n\r\n if life == 0 :\r\n highestScore = max(highestScore,score)\r\n pygame.mixer.Sound.play(death) # Lose \r\n \r\n if life == 0 :\r\n glColor(0.5, 0.5, w) \r\n drawText(\"Press Space bar to try again\", 80, (Display.frustumHeight[0]+Display.frustumHeight[1])/2, 0.3, 0.3, 3)\r\n drawText(\"Press Esc to quit\", 210, (Display.frustumHeight[0]+Display.frustumHeight[1])/2-80, 0.3, 0.3, 2.5)\r\n drawText(\"HIGH SCORE: \"+str(highestScore), 220, Display.frustumHeight[0]+20, 0.3, 0.3, 3)\r\n \r\n if resume is True:\r\n resetGame()\r\n \r\n glutSwapBuffers()\r\n\r\ndef main():\r\n Display.init()\r\n pygame.init()\r\n glutMainLoop()\r\n\r\nmain()\r\n \r\n","sub_path":"code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":21887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"453214715","text":"import argparse\nimport stupy\n\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\"-b\", \"--bind\", \n help=\"add host\", \n default=\"127.0.0.1:8080\",\n type=str)\n\nparser.add_argument(\"-H\", \"--host\", \n help=\"add host\", \n nargs='+',\n default=[],\n type=str)\n\n# parser.add_argument(\"-d\", \"--daemon\", \n# help=\"run server as daemon\", \n# action=\"store_true\")\n\n# parser.add_argument(\"action\", \n# type=str,\n# choices=[\"start\", \"stop\", \"restart\", \"status\"],\n# help=\"server action\", )\n\nargs = parser.parse_args()\n\naddr, port = args.bind.split(\":\")\n\nprint(addr, port, args.host)\nserver = stupy.StupyServer(addr, int(port), args.host)\nserver.run_forever()\n","sub_path":"stupyctl.py","file_name":"stupyctl.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"108983891","text":"from collections import deque\n\nfrom graph.graph_class import Graph\n\n\ndef bfs(edges, s):\n if not edges and not s:\n return None\n\n graph = Graph()\n queue = deque()\n queue.append(s)\n res = []\n\n for edge in edges:\n graph.add_edge(edge[0], edge[1])\n\n visited = {v: False for v in graph.vertex_set}\n\n while queue:\n v = queue.popleft()\n if not visited[v]:\n visited[v] = True\n res.append(v)\n for adj_v in graph.graph[v]:\n queue.append(adj_v)\n return res\n\n\nexpected = [2, 0, 3, 1]\nactual = bfs([[0, 1], [0, 2], [1, 2], [2, 0], [2, 3], [3, 3]], 2)\nprint(expected == actual)\n","sub_path":"graph/bfs.py","file_name":"bfs.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"502386353","text":"import yap\nimport networkx as nx\n\nfrom functools import reduce\nfrom time import time\nSTART_TIME = time()\nimport pickle\nimport os\nimport numpy as np\nimport scipy as sp\nimport collections\nfrom optparse import OptionParser\n\nMYLIB_PATH = '/home/flav/projects/yet-another-project/My-library'\nCACHE_DIR = '/home/flav/projects/yet-another-project/yap-analysis/data'\n\nraw = yap.RawRepo(MYLIB_PATH, cachedir=CACHE_DIR)\ntopo = yap.TopoRepo(raw)\n\ntopo.build_pagerank_trails()\ntopo.build_pagerank_trails_stdev()\nlonewolf_scores, interactivity_scores, team_productivity = topo.build_team_noteam()\n\ntopoplot = yap.TopoPlot(topo)\nopts = OptionParser()\nopts.add_option(\"-t\", \"--trends\", action=\"store_true\", default=False,\n help=\"Generate the pagerank trend groups\")\nopts.add_option(\"-r\", \"--ranks\", action=\"store_true\", default=False,\n help=\"Generate the pagerank ranks\")\nopts.add_option(\"--development\", action=\"store_true\", default=False,\n help=\"Development feature\")\nopts.add_option(\"--topology\", action=\"store_true\", default=False,\n help=\"Create topology GML\")\n\n(options, args) = opts.parse_args()\n\nif options.trends:\n userstyles = {\n 0: {'marker':'.', 'color': 'r', 'linestyle': 'None'},\n 1: {'marker':'.', 'color': 'g', 'linestyle': 'None'},\n }\n topoplot.plot_pagerank_trendgroups('trendgroups', colorizeusers=True, userstyles=userstyles)\nif options.ranks:\n topoplot.plotranks('ranks')\nif options.topology:\n nx.readwrite.gml.write_gml(topo, 'topology.gml')\n nx.readwrite.gexf.write_gexf(topo, 'topology.gexf')\nif options.development:\n for cid, commit in enumerate(raw.commits):\n print(\"cid\", cid)\n if len(commit['renames']):\n print(\"commit['renames']\", commit['renames'])\n print(\"commit['modifications']\", commit['modifications'])\n deletes = [path for path, content in commit['contents'].items() if content==None]\n if len(deletes):\n print(\"deletes\", deletes)\n","sub_path":"git-analysis/app-prototype1/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"334528045","text":"from gensim import corpora, models, similarities\nimport warnings, argparse, nltk, math\nfrom nltk.corpus import wordnet ,stopwords\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nimport string\nwarnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')\n\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-sl\",type=str)\nparser.add_argument(\"-ss\",type=str)\nparser.add_argument(\"-model\",type=str)\nargs = parser.parse_args()\nmodel = models.Word2Vec.load(args.model)\nsl = word_tokenize(args.sl)\nss = word_tokenize(args.ss)\nmax=0\ndata = []\nfor slword in sl:\n max = 0\n for word in ss:\n var = 0\n try:\n var = math.fabs(model.wv.similarity(slword,word))\n except Exception as e:\n continue\n if(var > max):\n max = var\n data.append(max)\nfor r in data:\n print(str(r))","sub_path":"python/max_sem.py","file_name":"max_sem.py","file_ext":"py","file_size_in_byte":859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"286851168","text":"#!/usr/bin/env python\nimport os\nimport sys\nimport re\n\n\ndef read_env():\n \"\"\"Pulled from Honcho code with minor updates, reads local default\n environment variables from a .env file located in the caller's working\n directory.\n \"\"\"\n try:\n with open('.env') as file_handler:\n content = file_handler.read()\n except IOError:\n content = ''\n\n for line in content.splitlines():\n match = re.match(r'^([A-Za-z_0-9]+)=(.*)$', line)\n if not match:\n continue\n\n key, val = match.group(1), match.group(2)\n\n os.environ.setdefault(key, val)\n\n\nif __name__ == \"__main__\":\n os.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"poireau.common.settings\")\n\n from django.core.management import execute_from_command_line\n\n read_env()\n execute_from_command_line(sys.argv)\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"361405499","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.urls import fetch_url\nfrom ansible.module_utils.pywigo_management import *\nimport json\nimport urllib\n\nDOCUMENTATION='''\nmodule: piwigo_group\nauthor: Cédric Bleschet\ndescription: Module to declare group in piwigo\noptions:\n name:\n description: group name\n required: yes\n password:\n description:group Password\n required: false\n'''\n\nEXAMPLES='''\n- hosts: \"localhost\"\n become: true\n - name: \"Test of group creation without associated user\"\n piwigo_group:\n name: \"testgroupwithoutuser\"\n state: \"present\"\n url_username: \"piwigo_admin\"\n url_password: \"xxx\"\n url: \"http://localhost:8080\"\n\n - name: \"Test of group creation with associated users\"\n piwigo_group:\n name: \"testgroupwithusers\"\n state: \"present\"\n user_list:\n - \"user1\"\n - \"user3\"\n url_username: \"piwigo_admin\"\n url_password: \"xxx\"\n url: \"http://localhost:8080\"\n\n - name: \"Test of group deletion\"\n piwigo_group:\n name: \"testgroupwithoutuser\"\n state: \"absent\"\n url_username: \"piwigo_admin\"\n url_password: \"xxx\"\n url: \"http://localhost:8080\"\n'''\n\nRETURN = '''\nresults:\n description: group status\n'''\n\nclass PiwigoGroupManagement(PiwigoManagement):\n def add_user_to_group(self):\n my_url = self.module.params[\"url\"] + self.api_endpoint\n values = {'method': 'pwg.groups.addUser',\n 'group_id': self.get_groupid(self.module.params[\"name\"]),\n 'user_id[]': self.get_id_list(self.module.params['user_list'], \"username\"),\n 'pwg_token': self.token\n }\n\n my_data = urllib.urlencode(values, True)\n\n rsp, info = fetch_url(self.module,\n my_url,\n data=my_data,\n headers=self.header,\n method=\"POST\")\n\n if info[\"status\"] != 200:\n self.module.fail_json(msg=\"Failed to connect to piwigo in order to add group\", response=rsp, info=info)\n else:\n content = json.loads(rsp.read())\n if content['stat'] == \"ok\":\n # Always changed, can't get the list of users to compare before and after....\n setattr(self, 'ansible_status', {'result': 'Changed', 'message':\n \"group {0} succesfully added with user(s) {1}\".format(self.module.params[\"name\"],\n self.module.params['user_list'])})\n\n def create_group(self):\n my_url = self.module.params[\"url\"] + self.api_endpoint\n values = {'method': 'pwg.groups.add',\n 'name': self.module.params[\"name\"],\n 'is_default': self.module.params[\"is_default\"],\n 'pwg_token': self.token\n }\n my_data = urllib.urlencode(values)\n\n rsp, info = fetch_url(self.module,\n my_url,\n data=my_data,\n headers=self.header,\n method=\"POST\")\n\n\n if info[\"status\"] != 200:\n self.module.fail_json(msg=\"Failed to connect to piwigo in order to add group\", response=rsp, info=info)\n else:\n content = json.loads(rsp.read())\n if content['stat'] == \"ok\":\n setattr(self, 'ansible_status', {'result': 'Changed', 'message':\n \"group {0} succesfully added\".format(self.module.params[\"name\"])})\n elif (content['stat'] == \"fail\") and (content['message'] == \"This name is already used by another group.\"):\n setattr(self, 'ansible_status', {'result': 'Unchanged', 'message':\n \"group {0} already existing\".format(self.module.params[\"name\"])})\n else:\n self.module.fail_json(msg=\"An error occured while creating group {0}\".format(self.module.params[\"name\"]))\n\n def delete_group(self, group_id):\n my_url = self.module.params[\"url\"] + self.api_endpoint\n values = {'method': 'pwg.groups.delete',\n 'group_id': group_id,\n 'pwg_token': self.token\n }\n my_data = urllib.urlencode(values)\n\n rsp, info = fetch_url(self.module,\n my_url,\n data=my_data,\n headers=self.header,\n method=\"POST\")\n\n if info[\"status\"] != 200:\n self.module.fail_json(msg=\"Failed to connect to piwigo in order to add group\", response=rsp, info=info)\n else:\n content = json.loads(rsp.read())\n if content['stat'] == \"ok\":\n setattr(self, 'ansible_status', {'result': 'Changed', 'message':\n \"group {0} succesfully deleted\".format(self.module.params[\"name\"])})\n else:\n self.module.fail_json(msg=\"An error occured while deleting group {0}\".format(self.module.params[\"name\"]))\n\n\ndef main():\n module = AnsibleModule(\n argument_spec=dict(\n state=dict(type='str', choices=['present', 'absent'], default='present'),\n name=dict(required=True, type='str'),\n user_list=dict(required=False, type='list', default=[]),\n is_default=dict(required=False, default=False, type='bool'),\n url=dict(required=True, type='str'),\n url_username=dict(required=True, type='str'),\n url_password=dict(required=True, type='str', no_log=True),\n ),\n supports_check_mode=True,\n required_together=[\n [\"url_username\", \"url_password\"],\n ]\n )\n\n piwigogroup = PiwigoGroupManagement(module,\n token=\"\",\n header={'Content-Type': 'application/x-www-form-urlencoded'},\n ansible_status={'result': 'Fail',\n 'message': 'Could not get status of PiwigogroupManagement module'},\n api_endpoint=\"/ws.php?format=json\"\n )\n\n # Get cookie\n my_header = piwigogroup.request_piwigo_login()\n setattr(piwigogroup, 'header', my_header)\n\n # Get token for admin group\n my_token = piwigogroup.get_admin_status()\n setattr(piwigogroup, 'token', my_token)\n\n group_id = piwigogroup.get_groupid(piwigogroup.module.params[\"name\"])\n\n if module.params['state'] == 'present':\n if group_id < 0:\n piwigogroup.create_group()\n else:\n setattr(piwigogroup, 'ansible_status',\n {'result': 'Unchanged',\n 'message': 'Group {0} already existing'.format(module.params['name'])})\n if len(module.params['user_list']) != 0:\n piwigogroup.add_user_to_group()\n else:\n if group_id > 0:\n piwigogroup.delete_group(group_id)\n else:\n setattr(piwigogroup, 'ansible_status',\n {'result': 'Unchanged',\n 'message': 'No group {0} found'.format(module.params['name'])})\n\n piwigogroup.finish_request()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"modules/piwigo_group.py","file_name":"piwigo_group.py","file_ext":"py","file_size_in_byte":7444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"195897785","text":"from django.views.generic import TemplateView\n\n\nclass DashboardHomeView(TemplateView):\n template_name = 'dashboard/dashboard.html'\n\n def dispatch(self, request, *args, **kwargs):\n if not request.user.is_authenticated:\n self.template_name = 'dashboard/home.html'\n\n return super(DashboardHomeView, self).dispatch(request, *args, **kwargs)\n","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"78055308","text":"from typing import List, Optional\n\n\ndef load_and_process_input_file(filename: str) -> List[int]:\n with open(filename) as f:\n numbers = []\n for line in f.readlines():\n numbers.append(int(line.split('\\n')[0]))\n return numbers\n\n\ndef find_numbers_and_multiply(numbers: List[int]) -> Optional[int]:\n for index1, number1 in enumerate(numbers):\n for number2 in numbers[index1:]:\n total = number1 + number2\n if total == 2020:\n return number1 * number2\n return None\n\n\nif __name__ == '__main__':\n numbers = load_and_process_input_file('input.txt')\n result = find_numbers_and_multiply(numbers)\n print(f'result: {result}')\n","sub_path":"day_01/solution_1.py","file_name":"solution_1.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"182441871","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/7/19 15:14\n# @Author : Lance\n# @File : CommonResponse.py\n\n\nclass BaseResponse(object):\n \"\"\"基础报文返回类\"\"\"\n\n def __init__(self, code=200, message='success', data=None):\n self.success = code == 200\n self.code = code\n self.message = message\n self.data = data\n\n def context(self):\n return {\n 'code': self.code,\n 'message': self.message,\n 'success': self.success,\n 'data': self.data,\n }\n\n\nclass PageResponse(BaseResponse):\n def __init__(self, entries=None, **page_info):\n self.entries = entries\n self.page_info = page_info\n super(PageResponse, self).__init__()\n\n def context(self):\n return {\n 'code': self.code,\n 'message': self.message,\n 'success': self.success,\n 'data': {\n 'entries': self.entries,\n 'page': {\n 'current': self.page_info['current'],\n 'pageSize': self.page_info['pageSize'],\n 'totalRecords': self.page_info['totalRecords'],\n }\n },\n }\n","sub_path":"utils/web_function/CommonResponse.py","file_name":"CommonResponse.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"59613762","text":"\"\"\"\nContains any functions relating to preprocessing, and the\nloading and manipulation of images.\n\"\"\"\nimport json\nimport pandas as pd\nimport numpy as np\nfrom imgaug import augmenters as iaa\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.preprocessing import LabelEncoder\nfrom tensorflow.keras.preprocessing.image import (\n img_to_array, load_img\n)\nfrom tensorflow.image import crop_to_bounding_box\n\n\n# Extracts all relevant information from VIA annotation file.\ndef process_via_annotations(annotations):\n \"\"\"\n Args:\n annotations (str): Filepath of the csv annotations file.\n\n Returns:\n pd.DataFrame\n \"\"\"\n data = pd.read_csv(annotations)\n\n # Build up the new data\n cols = ['filename', 'x', 'y', 'width', 'height', 'class']\n new_data = pd.DataFrame(columns=cols)\n\n for i, row in data.iterrows():\n # If image has no bounding boxes, skip\n if row['region_count'] == 0:\n continue\n\n new_row = {}\n\n new_row['filename'] = row['filename']\n\n # Get shape attributes\n shape_attrs = json.loads(row['region_shape_attributes'])\n for key in ['height', 'width', 'x', 'y']:\n new_row[key] = shape_attrs[key]\n\n # Get class attribute\n class_attr = json.loads(row['region_attributes'])\n new_row['class'] = class_attr['class']\n\n new_data = new_data.append(pd.Series(new_row), ignore_index=True)\n\n # Do label encoding for the class column\n le = LabelEncoder()\n le.fit(new_data['class'])\n\n new_data['label'] = le.transform(new_data['class'])\n\n return new_data\n\n# Creates and returns the imgaug object.\ndef create_aug():\n # Define our sequence of augmentation steps that will be applied to every image.\n sometimes = lambda aug: iaa.Sometimes(0.5, aug)\n\n aug = iaa.Sequential(\n [\n #\n # Apply the following augmenters to most images.\n #\n iaa.Fliplr(0.5), # horizontally flip 50% of all images\n\n # crop some of the images by 0-10% of their height/width\n sometimes(iaa.CropAndPad(percent=(-0.15, 0.15), pad_mode='edge')),\n\n # Apply affine transformations to some of the images\n sometimes(iaa.Affine(\n translate_percent={\"x\": (-0.15, 0.15), \"y\": (-0.15, 0.15)},\n rotate=(-5, 5),\n shear=(-5, 5),\n order=[0, 1],\n mode='edge'\n )),\n\n #\n # Execute 0 to 5 of the following (less important) augmenters per\n # image. Don't execute all of them, as that would often be way too\n # strong.\n #\n iaa.SomeOf((0, 5),\n [\n # Blur each image with varying strength using\n # gaussian blur (sigma between 0 and 3.0),\n # average/uniform blur (kernel size between 2x2 and 7x7)\n # median blur (kernel size between 3x3 and 11x11).\n iaa.OneOf([\n iaa.GaussianBlur((0, 3.0)),\n iaa.AverageBlur(k=(2, 7)),\n iaa.MedianBlur(k=(3, 11)),\n ]),\n\n # Sharpen each image, overlay the result with the original\n # image using an alpha between 0 (no sharpening) and 1\n # (full sharpening effect).\n iaa.Sharpen(alpha=(0, 0.3), lightness=(0.85, 1.25)),\n\n # Add gaussian noise to some images.\n # In 50% of these cases, the noise is randomly sampled per\n # channel and pixel.\n # In the other 50% of all cases it is sampled once per\n # pixel (i.e. brightness change).\n iaa.AdditiveGaussianNoise(\n loc=0, scale=(0.0, 0.05*255), per_channel=0.5\n ),\n\n # Add a value of -10 to 10 to each pixel.\n iaa.Add((-10, 10), per_channel=0.5),\n\n # Change brightness of images (50-150% of original value).\n iaa.Multiply((0.5, 1.5)),\n\n # Improve or worsen the contrast of images.\n iaa.ContrastNormalization((0.7, 1.3)),\n ],\n # do all of the above augmentations in random order\n random_order=True\n )\n ],\n # do all of the above augmentations in random order\n random_order=True\n )\n\n return aug\n\n# Creates the indices for Train/Val split on given dataset.\ndef get_indices_split(data):\n \"\"\"Performs Stratified Sampling based on class proportions.\n\n Args:\n data (pd.DataFrame):\n \"\"\"\n split = StratifiedShuffleSplit(n_splits=1, test_size=0.3, random_state=42)\n\n train_indices, val_indices = next(split.split(data, data['class']))\n\n return train_indices, val_indices\n\n\n# Loads and crops image from raw data information.\ndef preprocess_image(row, img_dir):\n \"\"\"\n Args:\n row (pd.Series): Raw row data information of that image.\n img_dir (str): Directory of image.\n\n Returns: Tensor of the image.\n \"\"\"\n img = load_img(os.path.join(img_dir, row['filename']))\n img = img_to_array(img, dtype=np.uint8)\n\n img = crop_to_bounding_box(\n img,\n row['y'],\n row['x'],\n row['height'],\n row['width']\n )\n\n return img\n","sub_path":"src/dataloader/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":5462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"652278150","text":"'''\nPython to script to Add all the available prefixes to the CSS files of a website\nusing the Autoprefixer tool.\n'''\nfrom bash import bash\n\n#ADD BROWESER LIST FROM\n#https://github.com/browserslist/browserslist\n#Defaults will add all available CSS prefixes\nbrowser = \"defaults\"\n#To find the CSS files in the directory.\nlist = bash(\"find -name '*.css'\").stdout.split('\\n')\nprint(\"Obtained the list of all the css files\")\n#Installing the Autoprefixer tool.\nbash(\"npm i postcss-cli-simple\")\nbash(\"npm i postcss-cli\")\nbash(\"npm i autoprefixer\")\n\nprint(\"installed the needed packages\")\n\nfor infile in list:\n ### Adding prefixes to the files\n postcss = 'postcss --use autoprefixer --autoprefixer.browsers \"%(browser)s\" -o %(outfile)s %(infile)s'\n bash(postcss %{\"browser\": browser, \"outfile\":infile, \"infile\":infile})\n print(\"Added prefixes to the file at \"+infile)\n","sub_path":"Prefixes_files/addPrefixes.py","file_name":"addPrefixes.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"198132641","text":"\"\"\"\nProcesses with cdo commands\n\"\"\"\nimport imp\n\nfrom pywps import Process\nfrom pywps import LiteralInput\nfrom pywps import ComplexInput, ComplexOutput\nfrom pywps import Format, FORMATS\nfrom pywps.app.Common import Metadata\n\nfrom hummingbird.processing import cdo_version, get_cdo\n\nimport logging\nLOGGER = logging.getLogger(\"PYWPS\")\n\n\ndef cdo_wrap(tmargs):\n cdo = get_cdo()\n cdo_op = getattr(cdo, tmargs[3])\n return cdo_op(tmargs[0], input=tmargs[1], output=tmargs[2])\n\n\nclass CDOinter_MPI(Process):\n\n def __init__(self):\n inputs = [\n ComplexInput('netcdf_file', 'NetCDF File',\n abstract='You may provide a URL or upload a NetCDF file.',\n metadata=[Metadata('Info')],\n min_occurs=1,\n max_occurs=100,\n supported_formats=[Format('application/x-netcdf')]),\n LiteralInput('operator', 'CDO Operator',\n data_type='string',\n abstract=\"Choose a CDO Operator\",\n default='remapbil',\n min_occurs=0,\n max_occurs=1,\n allowed_values=['remapbil', 'remapbic', 'remapdis',\n 'remapnn', 'remapcon', 'remapcon2', 'remaplaf']),\n LiteralInput('regr', 'Grid',\n data_type='string',\n abstract=\"Select an grid\",\n default='r360x180',\n min_occurs=0,\n max_occurs=1,\n allowed_values=['r64x32', 'r32x16', 'r1024x512', 'r360x180', 'r480x241', 'custom']),\n LiteralInput('longitude', 'longitude',\n data_type='string',\n abstract=\"New nx Longitude\",\n default=None,\n min_occurs=0,\n max_occurs=1),\n LiteralInput('latitude', 'Latitude',\n data_type='string',\n abstract=\"New ny Latitude\",\n default=None,\n min_occurs=0,\n max_occurs=1),\n LiteralInput('multi', 'Serial or MP',\n data_type='string',\n abstract=\"Use Serial or Multiprocessing/Multithreads\",\n default='Serial',\n min_occurs=0,\n max_occurs=1,\n allowed_values=['Serial', 'Multiprocessing', 'Multithreads']),\n ]\n\n outputs = [\n ComplexOutput('tarout', 'Result files',\n abstract=\"Tar archive containing the netCDF result files\",\n as_reference=True,\n supported_formats=[Format('application/x-tar')]),\n ComplexOutput('output', 'Output',\n abstract=\"One regrided file.\",\n as_reference=True,\n supported_formats=[Format('application/x-netcdf')]),\n ]\n\n super(CDOinter_MPI, self).__init__(\n self._handler,\n identifier=\"cdo_inter_mpi\",\n title=\"CDO Remapping\",\n abstract=\"CDO Remapping of NetCDF File(s) with multiprocessing\",\n version=cdo_version,\n metadata=[\n Metadata('Birdhouse', 'http://bird-house.github.io/'),\n Metadata('User Guide', 'http://birdhouse-hummingbird.readthedocs.io/en/latest/'),\n Metadata('CDO Homepage', 'https://code.zmaw.de/projects/cdo'),\n Metadata('CDO Documentation', 'https://code.zmaw.de/projects/cdo/embedded/index.html'),\n ],\n inputs=inputs,\n outputs=outputs,\n status_supported=True,\n store_supported=True,\n )\n\n def _handler(self, request, response):\n import tarfile\n import os\n import tempfile\n\n nc_files = []\n for dataset in request.inputs['netcdf_file']:\n nc_files.append(dataset.file)\n\n (fp_tarf, tarf) = tempfile.mkstemp(dir=\".\", suffix='.tar')\n tar = tarfile.open(tarf, \"w\")\n\n operator = request.inputs['operator'][0].data\n response.update_status(\"starting cdo %s operator\" % (operator), 10)\n\n gri = request.inputs['regr'][0].data # here also should be checked default values!\n\n if (gri == 'custom'):\n try:\n gri = 'r' + str(request.inputs['longitude'][0].data) + 'x' + str(request.inputs['latitude'][0].data)\n LOGGER.debug('Using custom grid GRI = %s' % (gri))\n except Exception:\n gri = str(request.inputs['regr'][0].default) # Should be checked (!)\n LOGGER.debug('Custom grid is not well specified, using default GRI = %s' % (gri))\n\n LOGGER.debug('GRI = %s' % (gri))\n\n try:\n Multi = str(request.inputs['multi'][0].data)\n except Exception:\n Multi = str(request.inputs['multi'][0].default)\n\n try:\n imp.find_module('multiprocessing')\n except ImportError:\n Multi = 'Serial'\n\n LOGGER.debug('Used calc type: = %s' % (Multi))\n\n # ------------------------- For Multi Proc\n\n if ('Serial' not in Multi):\n\n if ('threads' not in Multi):\n from multiprocessing import Pool\n pool = Pool()\n else:\n from multiprocessing.dummy import Pool as ThreadPool\n pool = ThreadPool()\n\n outfiles = []\n new_arc_names = []\n grids = [gri] * len(nc_files)\n operators = [operator] * len(nc_files)\n\n for nc_file in nc_files:\n (fp_ncf, outfile) = tempfile.mkstemp(dir=\".\", suffix='.nc')\n LOGGER.debug('Input NetCDF file = %s' % (nc_file))\n outfiles.append(outfile)\n\n new_arc_name = os.path.basename(nc_file.split(\".nc\")[0] + \"_\" + operator + \"_\" + gri + \".nc\")\n LOGGER.debug('NEW NAME for Output NetCDF file = %s' % (new_arc_name))\n new_arc_names.append(new_arc_name)\n\n args = zip(grids, nc_files, outfiles, operators)\n # res = pool.map(cdo_wrap, args)\n pool.map(cdo_wrap, args)\n pool.close()\n pool.join()\n\n for i, outfn in enumerate(outfiles):\n tar.add(outfn, arcname=new_arc_names[i])\n\n else: # ------------------ if Serial\n cdo = get_cdo()\n cdo_op = getattr(cdo, operator)\n\n for nc_file in nc_files:\n (fp_ncf, outfile) = tempfile.mkstemp(dir=\".\", suffix='.nc')\n LOGGER.debug('Input NetCDF file = %s' % (nc_file))\n cdo_op(gri, input=nc_file, output=outfile)\n\n new_arc_name = os.path.basename(nc_file.split(\".nc\")[0] + \"_\" + operator + \"_\" + gri + \".nc\")\n\n LOGGER.debug('NEW NAME for Output NetCDF file = %s' % (new_arc_name))\n tar.add(outfile, arcname=new_arc_name)\n\n tar.close()\n response.outputs['output'].file = outfile\n response.outputs['tarout'].file = tarf\n response.update_status(\"cdo remapping done\", 100)\n return response\n","sub_path":"hummingbird/processes/wps_cdo_inter_pywps4.py","file_name":"wps_cdo_inter_pywps4.py","file_ext":"py","file_size_in_byte":7394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"648593092","text":"import math\nimport re\nimport string\nimport time\nfrom typing import List\n\nimport nltk\nfrom nltk.corpus import wordnet\nimport pandas as pd\nfrom gensim.models import LdaModel, CoherenceModel\nfrom gensim.utils import simple_tokenize\nimport numpy as np\n\nfrom path_resolution import resources_path\n\nfrom tqdm import tqdm\n\nfrom utils.static_file_manage import load_pickle, write_pickle\n\n\ndef get_wordnet_pos(word):\n \"\"\"Map POS tag to first character lemmatize() accepts\"\"\"\n tag = nltk.pos_tag([word])[0][1][0].upper()\n tag_dict = {\"J\": wordnet.ADJ,\n \"N\": wordnet.NOUN,\n \"V\": wordnet.VERB,\n \"R\": wordnet.ADV}\n\n return tag_dict.get(tag, wordnet.NOUN)\n\n\ndef process_texts(input_texts, stops):\n \"\"\"\n This function is processing the input text, removing stop words and lemmatizing it \\n\n :param input_texts:\n :param stops: stop words that must be delated\n :return:\n \"\"\"\n from nltk.stem import WordNetLemmatizer\n lemmatizer = WordNetLemmatizer()\n final = []\n for i in input_texts:\n # remove http and lower case\n texts = (re.sub(r\"http\\S+\", \"\", i)).lower()\n # tokenize\n texts = nltk.word_tokenize(texts)\n\n # remove stopwords and lemmatize the sentence\n texts = [lemmatizer.lemmatize(word) for word in texts if word not in stops and word.isalpha()]\n\n # this is another version considering also postag, must be revised in case\n # final_t = []\n # for word, pos in nltk.pos_tag(texts):\n # if word not in stops:\n # final_t.append(lemmatizer.lemmatize(word, pos=pos))\n # texts = [lemmatizer.lemmatize(\n\n final.append(texts)\n\n return final\n\n\ndef evaluate_num_topics(dictionary, corpus, texts, limit, passes, iterations, random_state):\n c_v = []\n c_uci = []\n u_mass = []\n perplexity = []\n lm_list = []\n for num_top in range(1, limit):\n t = time.time()\n print(\"Check with {} topics\".format(num_top), end=\" \")\n lm = LdaModel(corpus=corpus, num_topics=num_top, id2word=dictionary, eval_every=1,\n passes=passes, iterations=iterations, random_state=random_state)\n lm_list.append(lm)\n cm_cv = CoherenceModel(model=lm, texts=texts, dictionary=dictionary, coherence='c_v')\n c_v.append(cm_cv.get_coherence())\n print(\"with coherence of {} in {} sec\".format(cm_cv.get_coherence(), time.time() - t))\n\n # Show graph\n return lm_list, c_v\n\n\ndef get_corpus(coco=True, datapath=None) -> List[str]:\n if datapath is None:\n if coco:\n fname = resources_path(\"data\", \"image_coco.txt\")\n else:\n fname = resources_path(\"data\", \"emnlp_news.txt\")\n else:\n fname = datapath\n\n with open(fname) as f:\n lines = [line.rstrip('\\n') for line in f]\n return lines\n\n\ndef format_topics_sentences(lda_model: LdaModel, corpus, texts):\n # Init output\n sent_topics_df = pd.DataFrame()\n\n # Get main topic in each document\n for i, row_list in enumerate(lda_model[corpus]):\n row = row_list[0] if lda_model.per_word_topics else row_list\n\n # row = sorted(row, key=lambda x: (x[1]), reverse=True) # sort list to get dominant topic\n # Get the Dominant topic, Perc Contribution and Keywords for each document\n to_append = []\n for j, (topic_num, prop_topic) in enumerate(row):\n # if j == 0: # => dominant topic\n # wp = ldamodel.show_topic(topic_num)\n # topic_keywords = \", \".join([word for word, prop in wp])\n # sent_topics_df = sent_topics_df.append(\n # pd.Series([int(topic_num), round(prop_topic, 4), topic_keywords]), ignore_index=True)\n # else:\n # break\n to_append.append(prop_topic)\n sent_topics_df = sent_topics_df.append(\n pd.Series(to_append), ignore_index=True)\n sent_topics_df.columns = [\"Topic {}\".format(topic_number) for topic_number in range(len(to_append))]\n\n # Add original text to the end of the output\n contents = pd.Series(texts)\n sent_topics_df = pd.concat([sent_topics_df, contents], axis=1)\n return sent_topics_df\n\n\ndef word_cloud(lda):\n lda_model = lda.lda_model\n stop_words = lda.stops\n # 1. Wordcloud of Top N words in each topic\n from matplotlib import pyplot as plt\n from wordcloud import WordCloud\n import matplotlib.colors as mcolors\n\n cols = [color for name, color in mcolors.TABLEAU_COLORS.items()] # more colors: 'mcolors.XKCD_COLORS'\n\n cloud = WordCloud(stopwords=stop_words,\n background_color='white',\n width=2500,\n height=1800,\n max_words=10,\n colormap='tab10',\n color_func=lambda *args, **kwargs: cols[i],\n prefer_horizontal=1.0)\n\n topics = lda_model.show_topics(formatted=False)\n\n fig, axes = plt.subplots(math.ceil(lda.topic_num / 2), 2, figsize=(10, 10), sharex=True, sharey=True)\n\n for i, ax in enumerate(axes.flatten()):\n fig.add_subplot(ax)\n try:\n topic_words = dict(topics[i][1])\n except IndexError:\n continue\n cloud.generate_from_frequencies(topic_words, max_font_size=300)\n plt.gca().imshow(cloud)\n plt.gca().set_title('Topic ' + str(i), fontdict=dict(size=16))\n plt.gca().axis('off')\n\n plt.subplots_adjust(wspace=0, hspace=0)\n plt.axis('off')\n plt.margins(x=0, y=0)\n plt.tight_layout()\n plt.show()\n\n\ndef get_perc_few_sent_topic(ldamodel, corpus_bow, topic_num):\n sent_topics_df = pd.DataFrame()\n\n # Get main topic in each document\n for i, row_list in enumerate(ldamodel[corpus_bow]):\n row = row_list[0] if ldamodel.per_word_topics else row_list\n to_append = np.zeros(topic_num)\n for j, (topic_n, prop_topic) in enumerate(row):\n to_append[topic_n] = prop_topic\n sent_topics_df = sent_topics_df.append(pd.Series(to_append), ignore_index=True)\n\n sent_topics_df.columns = [\"Topic {}\".format(topic_number) for topic_number in range(topic_num)]\n\n # Add original text to the end of the output\n sent_topics_df = sent_topics_df.reset_index()\n return sent_topics_df\n\n\ndef get_perc_sent_topic(lda, topic_num, data_file):\n file_path = \"{}-{}-{}\".format(lda.lda_model, topic_num, data_file[-10:])\n file_path = resources_path(\"topic_models\", file_path)\n try:\n sent_topics_df = load_pickle(file_path)\n except FileNotFoundError:\n print(\"get perc sent topic not found\")\n ldamodel = lda.lda_model\n with open(data_file) as f:\n sentences = [line.rstrip('\\n') for line in f]\n\n tmp = process_texts(sentences, lda.stops)\n corpus_bow = [lda.dictionary.doc2bow(i) for i in tmp]\n # Init output\n sent_topics_df = pd.DataFrame()\n\n # Get main topic in each document\n for i, row_list in enumerate(tqdm(ldamodel[corpus_bow])):\n row = row_list[0] if ldamodel.per_word_topics else row_list\n # print(row)\n # row = sorted(row, key=lambda x: (x[1]), reverse=True) # sort list to get dominant topic\n # Get the Dominant topic, Perc Contribution and Keywords for each document\n to_append = np.zeros(topic_num)\n for j, (topic_n, prop_topic) in enumerate(row):\n to_append[topic_n] = prop_topic\n sent_topics_df = sent_topics_df.append(pd.Series(to_append), ignore_index=True)\n\n sent_topics_df.columns = [\"Topic {}\".format(topic_number) for topic_number in range(len(to_append))]\n\n # Add original text to the end of the output\n contents = pd.Series(sentences)\n sent_topics_df = pd.concat([sent_topics_df, contents], axis=1)\n sent_topics_df = sent_topics_df.reset_index()\n\n write_pickle(file_path, sent_topics_df)\n\n return sent_topics_df\n","sub_path":"src/topic_modelling/lda_utils.py","file_name":"lda_utils.py","file_ext":"py","file_size_in_byte":7966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"641659445","text":"import os\nimport pickle\nimport collections\nimport pandas as pd\n\nclass QuantiledCache:\n\n cache_filename = 'quantiled_cache.pckl'\n\n @classmethod\n def load_or_create(cls, data_path : str):\n\n cache_file_path = os.path.join(data_path, cls.cache_filename)\n if os.path.isfile(cache_file_path):\n return pickle.load( open( cache_file_path, 'rb' ) )\n\n else:\n return cls(cache_file_path)\n\n def __init__(self, cache_file_path):\n\n self._cache_file_path = cache_file_path\n self._cached_results = dict()\n\n def __del__(self):\n\n pickle.dump( self, open(self._cache_file_path, 'wb') )\n\n def update_and_get(self, left_quantile_invocations, right_quantile_invocations, invocations_data : pd.DataFrame):\n\n invocations_filtered = None\n if (not left_quantile_invocations in self._cached_results) or (not right_quantile_invocations in self._cached_results):\n invocations_data_per_app = invocations_data.groupby(['HashApp', 'datetime']).max()\n invocations_data_per_hour = invocations_data_per_app.groupby(['HashApp', pd.Grouper(freq='60T', level='datetime')]).sum().fillna(0).rename(columns = {'invocations': 'Load'})\n invocations_data_per_day = invocations_data_per_hour.groupby(['HashApp']).mean()\n invocations_filtered = invocations_data_per_day[invocations_data_per_day.Load > 0]\n\n apps_filtered_left = set()\n if left_quantile_invocations in self._cached_results:\n apps_filtered_left = self._cached_results[left_quantile_invocations]\n else:\n begin_invocations = invocations_filtered.Load.quantile(left_quantile_invocations)\n apps_filtered_left = set(invocations_filtered[invocations_filtered.Load <= begin_invocations].index)\n\n apps_filtered_right = set()\n if right_quantile_invocations in self._cached_results:\n apps_filtered_right = self._cached_results[right_quantile_invocations]\n else:\n end_invocations = invocations_filtered.Load.quantile(right_quantile_invocations)\n apps_filtered_right = set(invocations_filtered[invocations_filtered.Load <= end_invocations].index)\n\n apps_filtered_between = apps_filtered_right - apps_filtered_left\n cached_results = collections.OrderedDict(sorted(self._cached_results.items(), key = lambda el: el[0]))\n for quantile, ids_set in cached_results.items():\n if quantile < left_quantile_invocations and len(apps_filtered_left) > 0:\n apps_filtered_left -= ids_set\n\n elif quantile > left_quantile_invocations and quantile < right_quantile_invocations and len(apps_filtered_between) > 0:\n apps_filtered_between -= ids_set\n\n elif quantile > right_quantile_invocations and len(apps_filtered_between) > 0:\n ids_set -= apps_filtered_between\n\n self._cached_results[left_quantile_invocations] = apps_filtered_left\n self._cached_results[right_quantile_invocations] = apps_filtered_between\n\n cached_results = collections.OrderedDict(sorted(self._cached_results.items(), key = lambda el: el[0]))\n selected_apps = set()\n for quantile, ids_set in cached_results.items():\n if quantile > left_quantile_invocations and quantile <= right_quantile_invocations:\n selected_apps |= ids_set\n\n return selected_apps\n","sub_path":"experimentgenerator/quantiled_cache.py","file_name":"quantiled_cache.py","file_ext":"py","file_size_in_byte":3422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"639446186","text":"from django.urls import path\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.conf.urls import url\nfrom django.views.generic import RedirectView\n\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('keyword_pages_search/', views.dynamic_lookup_view, name='dynamic_lookup_view'),\n # path('keyword_pages_default', views.keyword_pages_default, name='keyword_pages_default'),\n # path('keyword_pages/', views.keyword_pages, name='keyword_pages'),\n path('keyword_pages', views.keyword_pages, name='keyword_pages'),\n path('verify_relationship_tool', views.verify_relationship_tool, name='verify_relationship_tool'),\n path('find_similar_keyword_default', views.find_similar_keyword_default, name='find_similar_keyword_default'),\n path(r'search/', views.search, name='search'),\n path(r'search_similar/', views.search_similar, name='search_similar'),\n path(r'search_similar_result/', views.search_similar_result, name='search_similar_result'),\n path(r'add_entry/', views.add_entry, name='add_entry'),\n path(r'add_entry_rel_tool/', views.add_entry_rel_tool, name='add_entry_rel_tool'),\n path(r'pagination/', views.pagination, name='pagination'),\n # path(r'add_to_filter/', views.add_to_filter, name='add_to_filter'),\n url(r'^favicon\\.ico$',RedirectView.as_view(url='/static/images/favicon.ico')),\n] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)","sub_path":"keyword_relation/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"20515428","text":"'''\nCreated on Sep 19, 2016\n\n@author: Hai\n'''\n\ndef _choose_pivot(arr, begin,end):\n return begin\n\ndef _partition(arr,begin,end,pivot_index):\n pivot= arr[pivot_index]\n while begin < end: # inclusive\n if arr[begin] < pivot:\n begin=begin + 1\n elif arr[end] >= pivot:\n end= end -1\n else:\n arr[begin], arr[end]= arr[end], arr[begin]\n return begin \n \n \ndef _quicksort(arr,begin,end):\n # inclusive\n if begin >= end:\n return\n pivot_index= _choose_pivot(arr, begin, end);\n index= _partition(arr, begin, end, pivot_index)\n _quicksort(arr,begin,index-1)\n if index==begin:\n _quicksort(arr,index+1,end)\n else:\n _quicksort(arr,index,end)\n \ndef sort(arr):\n _quicksort(arr,0,len(arr) - 1)\n return arr\n","sub_path":"sorting/quicksort.py","file_name":"quicksort.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"386100595","text":"import serial\nimport struct\ns = serial.Serial('/dev/tty.usbmodem0004401673681');\ns.flush()\n\"\"\"\nPACKET_SIZE = 179 # 164 + 4 +2 + 1 + 1 + 4 + 1 + 2\nfound = False\nwhile not found:\n # Look for 4 0xFFs in a row...\n msg = s.readline()\n index = msg.find(b'\\xff'*4)\n if index >=0:\n found = True\n # Figure how much to read to get to next 0xFFs\n amount_xferred = len(msg) - index\n s.read(PACKET_SIZE - amount_xferred)\n\"\"\"\nNUM_PACKETS = 10\nonefound = False\nwhile not onefound:\n # Look for 4 0xFFs in a row...\n msg = s.readline()\n index = msg.find(b'\\xff'*4)\n if index >=0:\n onefound = True\nPACKET_SIZE = len(msg) - index\nfound = False\nmsg2 = b''\nwhile not found:\n msg2 += s.readline()\n index = msg2.find(b'\\xff'*4)\n if index >=0:\n found = True\nPACKET_SIZE += index\nprint(PACKET_SIZE)\namount_xferred = len(msg2) - index\ns.read(PACKET_SIZE - amount_xferred)\n\nfilename = 'connectionless_20ms_chmap.dat'\nwith open(filename, 'wb') as f:\n\n for count in range(NUM_PACKETS):\n packet = s.read(PACKET_SIZE)\n f.write(packet)\n f.flush()\n data = struct.unpack('<4sHBBIB164p2s', packet)\n print(count, data[1], data[2], -data[3])\n\ns.close()\n","sub_path":"connectionless.py","file_name":"connectionless.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"593287807","text":"#imports\nimport datetime, time\nfrom threading import Lock\nfrom ..utilities.controlled_process import ControlledProcessMultiThreaded\nfrom ..utilities.runnable import Runnable\nfrom ..utilities.misc import populated_kwargs\nfrom ..my_kafka.consumer_group import ConsumerGroup\nfrom .config import DATA_FILE_HANDLING_CONST, RUN_OPT_CONST\nfrom .download_data_file import DownloadDataFileToDisk\nfrom .data_file_directory import DataFileDirectory\n\nclass DataFileDownloadDirectory(DataFileDirectory,ControlledProcessMultiThreaded,ConsumerGroup,Runnable) :\n \"\"\"\n Class representing a directory into which files are being reconstructed\n \"\"\"\n\n #################### PROPERTIES ####################\n\n @property\n def other_datafile_kwargs(self) :\n return {} #Overload this in child classes to define additional keyword arguments \n #that should go to the specific datafile constructor\n @property\n def n_msgs_read(self) :\n return self.__n_msgs_read\n @property\n def completely_reconstructed_filepaths(self) :\n return self.__completely_reconstructed_filepaths\n @property\n def progress_msg(self) :\n progress_msg = 'The following files have been recognized so far:\\n'\n for datafile in self.data_files_by_path.values() :\n progress_msg+=f'\\t{datafile.full_filepath} (in progress)\\n'\n for fp in self.completely_reconstructed_filepaths :\n progress_msg+=f'\\t{fp} (completed)\\n'\n return progress_msg\n\n #################### PUBLIC FUNCTIONS ####################\n\n def __init__(self,*args,datafile_type=DownloadDataFileToDisk,**kwargs) :\n \"\"\"\n datafile_type = the type of datafile that the consumed messages should be assumed to represent\n In this class datafile_type should be something that extends DownloadDataFileToDisk\n \"\"\" \n kwargs = populated_kwargs(kwargs,{'n_consumers':kwargs.get('n_threads')})\n super().__init__(*args,**kwargs)\n if not issubclass(datafile_type,DownloadDataFileToDisk) :\n errmsg = 'ERROR: DataFileDownloadDirectory requires a datafile_type that is a subclass of '\n errmsg+= f'DownloadDataFileToDisk but {datafile_type} was given!'\n self.logger.error(errmsg,ValueError)\n self.__datafile_type = datafile_type\n self.__n_msgs_read = 0\n self.__completely_reconstructed_filepaths = []\n self.__thread_locks = {}\n\n def reconstruct(self) :\n \"\"\"\n Consumes messages and writes their data to disk using several parallel threads to reconstruct the files \n to which they correspond. Runs until the user inputs a command to shut it down. Returns the total number \n of messages consumed, as well as the number of files whose reconstruction was completed during the run. \n \"\"\"\n msg = f'Will reconstruct files from messages in the {self.topic_name} topic using {self.n_threads} '\n msg+= f'thread{\"s\" if self.n_threads!=1 else \"\"}'\n self.logger.info(msg)\n lock = Lock()\n self.run([(lock,self.consumers[i]) for i in range(self.n_threads)])\n return self.__n_msgs_read, self.__completely_reconstructed_filepaths\n\n #################### PRIVATE HELPER FUNCTIONS ####################\n\n def _run_worker(self,lock,consumer) :\n \"\"\"\n Consume messages expected to be DataFileChunks and try to write their data to disk in the directory, \n paying attention to whether/how the files they're coming from end up fully reconstructed or mismatched \n with their original hashes.\n Several iterations of this function run in parallel threads as part of a ControlledProcessMultiThreaded\n \"\"\"\n #start the loop for while the controlled process is alive\n while self.alive :\n #consume a DataFileChunk message from the topic\n dfc = consumer.get_next_message(self.logger,0)\n if dfc is None :\n time.sleep(0.25) #wait just a bit to not over-tax things\n continue\n #set the chunk's rootdir to the working directory\n if dfc.rootdir is not None :\n errmsg = f'ERROR: message with key {dfc.message_key} has rootdir={dfc.rootdir} '\n errmsg+= '(should be None as it was just consumed)! Will ignore this message and continue.'\n self.logger.error(errmsg)\n dfc.rootdir = self.dirpath\n #add the chunk's data to the file that's being reconstructed\n with lock :\n self.__n_msgs_read+=1\n if dfc.filepath not in self.data_files_by_path.keys() :\n self.data_files_by_path[dfc.filepath] = self.__datafile_type(dfc.filepath,\n logger=self.logger,\n **self.other_datafile_kwargs)\n self.__thread_locks[dfc.filepath] = Lock()\n return_value = self.data_files_by_path[dfc.filepath].add_chunk(dfc,self.__thread_locks[dfc.filepath])\n if return_value in (DATA_FILE_HANDLING_CONST.FILE_IN_PROGRESS,\n DATA_FILE_HANDLING_CONST.CHUNK_ALREADY_WRITTEN_CODE) :\n continue\n elif return_value==DATA_FILE_HANDLING_CONST.FILE_HASH_MISMATCH_CODE :\n warnmsg = f'WARNING: hashes for file {self.data_files_by_path[dfc.filepath].filename} not matched '\n warnmsg+= 'after reconstruction! All data have been written to disk, but not as they were uploaded.'\n self.logger.warning(warnmsg)\n with lock :\n del self.data_files_by_path[dfc.filepath]\n del self.__thread_locks[dfc.filepath]\n elif return_value==DATA_FILE_HANDLING_CONST.FILE_SUCCESSFULLY_RECONSTRUCTED_CODE :\n msg = f'File {self.data_files_by_path[dfc.filepath].full_filepath.relative_to(dfc.rootdir)} '\n msg+= 'successfully reconstructed from stream'\n self.logger.info(msg)\n self.__completely_reconstructed_filepaths.append(dfc.filepath)\n with lock :\n del self.data_files_by_path[dfc.filepath]\n del self.__thread_locks[dfc.filepath]\n\n def _on_check(self) :\n msg = f'{self.__n_msgs_read} messages read, {len(self.__completely_reconstructed_filepaths)} files '\n msg+= 'completely reconstructed so far'\n self.logger.debug(msg)\n if len(self.data_files_by_path)>0 or len(self.__completely_reconstructed_filepaths)>0 :\n self.logger.debug(self.progress_msg)\n\n def _on_shutdown(self) :\n super()._on_shutdown()\n for consumer in self.consumers :\n consumer.close()\n\n #################### CLASS METHODS ####################\n\n @classmethod\n def get_command_line_arguments(cls) :\n args = ['output_dir','config','topic_name','update_seconds','consumer_group_ID']\n kwargs = {'n_threads':RUN_OPT_CONST.N_DEFAULT_DOWNLOAD_THREADS}\n return args,kwargs\n\n @classmethod\n def run_from_command_line(cls,args=None) :\n \"\"\"\n Run the download directory right from the command line\n \"\"\"\n parser = cls.get_argument_parser()\n args = parser.parse_args(args=args)\n #make the download directory\n reconstructor_directory = cls(args.output_dir,args.config,args.topic_name,\n n_threads=args.n_threads,\n consumer_group_ID=args.consumer_group_ID,\n update_secs=args.update_seconds,\n )\n #start the reconstructor running\n run_start = datetime.datetime.now()\n reconstructor_directory.logger.info(f'Listening for files to reconstruct in {args.output_dir}')\n n_msgs,complete_filenames = reconstructor_directory.reconstruct()\n run_stop = datetime.datetime.now()\n #shut down when that function returns\n reconstructor_directory.logger.info(f'File reconstructor writing to {args.output_dir} shut down')\n msg = f'{n_msgs} total messages were consumed'\n if len(complete_filenames)>0 :\n msg+=f' and the following {len(complete_filenames)} file'\n msg+=' was' if len(complete_filenames)==1 else 's were'\n msg+=' successfully reconstructed'\n msg+=f' from {run_start} to {run_stop}'\n for fn in complete_filenames :\n msg+=f'\\n\\t{fn}'\n reconstructor_directory.logger.info(msg)\n\n#################### MAIN METHOD TO RUN FROM COMMAND LINE ####################\n\ndef main(args=None) :\n DataFileDownloadDirectory.run_from_command_line(args)\n\nif __name__=='__main__' :\n main()\n","sub_path":"openmsipython/data_file_io/data_file_download_directory.py","file_name":"data_file_download_directory.py","file_ext":"py","file_size_in_byte":8880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"113877875","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n# Author: Xukun Luo\n# Date: 2021.04.08\n\nimport sys\nsys.path.append(\"../\")\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\nclass BiLstmModel(nn.Module):\n def __init__(self, args):\n super(BiLstmModel, self).__init__()\n\n self.label_number = args.label_number\n self.lstm_layers = args.lstm_layers\n self.lstm_hidden = args.lstm_hidden\n self.lstm_dropout = args.lstm_dropout\n self.use_cuda = args.use_cuda\n self.embed_size = args.embed_size\n self.num_embeddings = args.vocab_len\n \n self.embedding = nn.Embedding(self.num_embeddings, self.embed_size)\n self.lstm_encoder = nn.LSTM(input_size=self.embed_size,\n hidden_size=self.lstm_hidden,\n num_layers=self.lstm_layers,\n bidirectional=True,\n dropout=self.lstm_dropout,\n batch_first=True)\n self.lstm_decoder = nn.LSTM(input_size=self.lstm_hidden*2,\n hidden_size=self.lstm_hidden,\n num_layers=self.lstm_layers,\n bidirectional=True,\n dropout=self.lstm_dropout,\n batch_first=True)\n self.linear = nn.Linear(self.lstm_hidden*2, self.label_number)\n self.droplayer = nn.Dropout(p=self.lstm_dropout)\n\n def forward(self, src, src_len):\n '''\n Forward Algorithm.\n\n Args:\n\n src (batch_size, seq_length) : word-level representation of sentence\n src_len (batch_size) : the sentence length\n\n Returns:\n\n feats (batch_size, seq_length, num_labels) : predect feats.\n '''\n batch_size, seq_len = src.size(0), src.size(1)\n # Embedding.\n emb = self.embedding(src)\n emb = pack_padded_sequence(emb, src_len, True)\n # Encoder. (batch_size, seq_length, lstm_hidden*2)\n context_vector, _ = self.lstm_encoder(emb)\n #context_vector = self.droplayer(context_vector)\n # Decoder. (batch_size, seq_length, lstm_hidden*2)\n lstm_out, hidden = self.lstm_decoder(context_vector)\n lstm_out, _ = pad_packed_sequence(lstm_out, True)\n lstm_out = lstm_out.contiguous().view(-1, self.lstm_hidden*2)\n lstm_out = self.droplayer(lstm_out)\n # Linear layer. (batch_size, seq_length, label_number)\n lstm_feats = self.linear(lstm_out).view(batch_size, seq_len, -1)\n return lstm_feats\n\nModelDict = {\n \"bilstm\": BiLstmModel\n}","sub_path":"codes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"395949550","text":"#!/usr/bin/env Python3\n\nimport sys\nimport json\nimport time\nimport os.path\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\ntry:\n DCI = str(sys.argv[1])\nexcept Exception:\n print(\"Missing DCI Number\")\n exit()\n\nurl = 'https://www.wizards.com/Magic/PlaneswalkerPoints/' + str(DCI)\n\noptions = Options() \noptions.add_argument(\"--headless\") \n\ntry:\n myPath = os.path.abspath(os.path.dirname(__file__))\n driverPath = os.path.join(myPath, \"chromedriver\")\n driver = webdriver.Chrome(driverPath, options = options)\nexcept Exception:\n print('Error loading chromedriver')\n exit()\n\ndriver.get(url)\n\ntry:\n lifetime_points = driver.find_element_by_id('LifetimePoints').text\n seasonal_points = driver.find_element_by_class_name('SeasonPointsValuesValue').text\n datetime = int(time.time())\nexcept Exception:\n print('Error grabbing point values')\n exit()\n\nprint('')\nprint(DCI)\nprint('----------------------')\nprint(\"Lifetime: \" + lifetime_points)\nprint(\"Seasonal: \" + seasonal_points)\nprint('----------------------')\n\nlogJSON = json.dumps([\n ('datetime', datetime),\n ('lifetime', int(lifetime_points)),\n ('seasonal', int(seasonal_points))\n])\n\ntry:\n fileName = str(DCI) + \".txt\"\n logFile = open(fileName,\"w+\")\n logFile.write(logJSON)\n logFile.close()\n print('Logged to file ' + fileName)\nexcept Exception:\n print('Error logging to file')\n exit()\n\n\nprint('')","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"645621024","text":"from tkinter import *\nfrom tkinter import messagebox,Menu\nimport requests\nimport json\nimport sqlite3\n\npycrypto=Tk()\npycrypto.title(\"My Crypto Portfolio\")\npycrypto.iconbitmap('favicon.ico')\n\ncon=sqlite3.connect(\"coin.db\")\ncObj=con.cursor()\n\n# cObj.execute(\"CREATE TABLE IF NOT EXISTS coin(id INTEGER PRIMARY KEY,sumbol TEXT,amount INTEGER,price REAL)\")\n# con.commit()\n\n# cObj.execute(\"INSERT INTO coin VALUES(1,'BTC',2,3250)\")\n# con.commit()\n# cObj.execute(\"INSERT INTO coin VALUES(2,'ETH',5,120)\")\n# con.commit()\n# cObj.execute(\"INSERT INTO coin VALUES(3,'NEO',5,10)\")\n# con.commit()\n# cObj.execute(\"INSERT INTO coin VALUES(4,'XMR',3,30)\")\n# con.commit()\n\n\n\ndef reset():\n for cell in pycrypto.winfo_children():\n cell.destroy()\n app_nav()\n application_header()\n my_portfolio()\n\n\ndef app_nav():\n def clear_all():\n cObj.execute(\"DELETE from coin\")\n con.commit()\n\n messagebox.showinfo(\"Portfolio Notification\",\"Portfolio cleared --- Add New Coins\")\n reset()\n \n def close_app():\n pycrypto.destroy()\n\n menu=Menu(pycrypto)\n file_item=Menu(menu)\n file_item.add_command(label='Clear Portfolio',command=clear_all)\n file_item.add_command(label='Close App',command=close_app)\n menu.add_cascade(label='File',menu=file_item)\n\n # help_item=Menu(menu)\n # help_item.add_command(label='Clear Portfolio',)\n # help_item.add_command(label='Close App,')\n # menu.add_cascade(label='File',menu=help_item)\n\n pycrypto.config(menu=menu)\n\ndef my_portfolio():\n api_request=requests.get(\"https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=300&convert=USD&CMC_PRO_API_KEY=8ab832ae-2ef1-4b8a-8923-74a2f1786361\")\n\n api=json.loads(api_request.content)\n\n # print(\"-----------\")\n # print(\"-----------\")\n\n\n # coins=[\n # {\n # \"symbol\":\"BTC\",\n # \"amount_owned\":2,\n # \"price_per_coin\":3200\n # },\n # {\n # \"symbol\":\"XRP\",\n # \"amount_owned\":100,\n # \"price_per_coin\":2.05\n # },\n # {\n # \"symbol\":\"LTC\",\n # \"amount_owned\":75,\n # \"price_per_coin\":25\n # },\n # {\n # \"symbol\":\"XMR\",\n # \"amount_owned\":10,\n # \"price_per_coin\":40.05\n # }\n\n\n # ]\n\n def font_color(amount):\n if amount >= 0:\n return \"green\"\n else:\n return \"red\"\n\n def insert_coin():\n cObj.execute(\"INSERT INTO coin(sumbol,price,amount) VALUES(?,?,?)\",(symbol_txt.get(),price_txt.get(),amount_txt.get()))\n con.commit()\n messagebox.showinfo(\"Portfolio Notification\",\"Coin added to Portfolio successfully!\")\n reset()\n\n def update_coin():\n cObj.execute(\"UPDATE coin SET sumbol=?,price=?,amount=? WHERE ID=?\",(symbol_update.get(),price_update.get(),amount_update.get(),portid_update.get()))\n con.commit()\n messagebox.showinfo(\"Portfolio Notification\",\"Coin updated successfully!\")\n reset()\n\n def delete_coin():\n cObj.execute(\"DELETE FROM coin WHERE id=?\",(portid_delete.get(),))\n con.commit()\n messagebox.showinfo(\"Portfolio Notification\",\"Coin deleted from Portfolio\")\n reset()\n\n cObj.execute(\"SELECT * FROM coin\")\n coins=cObj.fetchall()\n con.commit()\n\n # print(coins)\n\n\n\n\n\n\n\n\n total_pl=0\n coin_row=1\n total_current_value=0\n total_amount_paid=0\n\n for i in range(0,300):\n for coin in coins:\n if api[\"data\"][i][\"symbol\"]==coin[1]:\n total_paid=coin[2] * coin[3]\n current_value=coin[2] * api[\"data\"][i][\"quote\"][\"USD\"][\"price\"]\n pl_percoin= api[\"data\"][i][\"quote\"][\"USD\"][\"price\"] - coin[3]\n total_pl_coin=pl_percoin * coin[2] \n total_pl += total_pl_coin\n total_current_value += current_value\n total_amount_paid += total_paid\n # print(api[\"data\"][i][\"name\"] + \"-\" + api[\"data\"][i][\"symbol\"])\n # print(\"Price - ${0:.2f}\".format(api[\"data\"][i][\"quote\"][\"USD\"][\"price\"]))\n # print(\"Total Amount Paid:\",\"${0:.2f}\".format(total_paid))\n # print(\"Current Value:\",\"${0:.2f}\".format(current_value))\n # print(\"P/L Per Coin:\",\"${0:.2f}\".format(pl_percoin))\n # print(\"Total P/L With Coins :\",\"${0:.2f}\".format(total_pl_coin))\n # print(\"-----------\")\n\n\n portfolio_id=Label(pycrypto,text=coin[0],bg=\"#F3F4F6\",fg=\"black\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n portfolio_id.grid(row=coin_row,column=0,sticky=N+S+E+W)\n\n name=Label(pycrypto,text=api[\"data\"][i][\"symbol\"],bg=\"#F3F4F6\",fg=\"black\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n name.grid(row=coin_row,column=1,sticky=N+S+E+W)\n\n price=Label(pycrypto,text=\"${0:.2f}\".format(api[\"data\"][i][\"quote\"][\"USD\"][\"price\"]),bg=\"#F3F4F6\",fg=\"black\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n price.grid(row=coin_row,column=2,sticky=N+S+E+W)\n\n no_coins=Label(pycrypto,text=coin[2],bg=\"#F3F4F6\",fg=\"black\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n no_coins.grid(row=coin_row,column=3,sticky=N+S+E+W)\n\n amount_paid=Label(pycrypto,text=\"${0:.2f}\".format(total_paid),bg=\"#F3F4F6\",fg=\"black\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n amount_paid.grid(row=coin_row,column=4,sticky=N+S+E+W)\n\n current_val=Label(pycrypto,text=\"${0:.2f}\".format(current_value),bg=\"#F3F4F6\",fg=\"black\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n current_val.grid(row=coin_row,column=5,sticky=N+S+E+W)\n\n pl_coin=Label(pycrypto,text=\"${0:.2f}\".format(pl_percoin),bg=\"#F3F4F6\",fg=font_color(float(\"{0:.2f}\".format(pl_percoin))),font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n pl_coin.grid(row=coin_row,column=6,sticky=N+S+E+W)\n\n totalpl=Label(pycrypto,text=\"${0:.2f}\".format(total_pl_coin),bg=\"#F3F4F6\",fg=font_color(float(\"{0:.2f}\".format(total_pl_coin))),font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n totalpl.grid(row=coin_row,column=7,sticky=N+S+E+W)\n\n coin_row += 1\n #insert coin\n symbol_txt=Entry(pycrypto,borderwidth=2,relief=\"groove\") \n symbol_txt.grid(row=coin_row+1,column=1,sticky=N+S+E+W)\n\n price_txt=Entry(pycrypto,borderwidth=2,relief=\"groove\") \n price_txt.grid(row=coin_row+1,column=2,sticky=N+S+E+W)\n\n amount_txt=Entry(pycrypto,borderwidth=2,relief=\"groove\") \n amount_txt.grid(row=coin_row+1,column=3,sticky=N+S+E+W)\n\n add_coin=Button(pycrypto,text=\"Add Coin\",bg=\"#142E54\",fg=\"white\",command=insert_coin,font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n add_coin.grid(row=coin_row+1,column=4,sticky=N+S+E+W)\n \n #update coins\n portid_update=Entry(pycrypto,borderwidth=2,relief=\"groove\") \n portid_update.grid(row=coin_row+2,column=0,sticky=N+S+E+W)\n\n symbol_update=Entry(pycrypto,borderwidth=2,relief=\"groove\") \n symbol_update.grid(row=coin_row+2,column=1,sticky=N+S+E+W)\n\n price_update=Entry(pycrypto,borderwidth=2,relief=\"groove\") \n price_update.grid(row=coin_row+2,column=2,sticky=N+S+E+W)\n\n amount_update=Entry(pycrypto,borderwidth=2,relief=\"groove\") \n amount_update.grid(row=coin_row+2,column=3,sticky=N+S+E+W)\n\n update_coin_txt=Button(pycrypto,text=\"Update Coin\",bg=\"#142E54\",fg=\"white\",command=update_coin,font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n update_coin_txt.grid(row=coin_row+2,column=4,sticky=N+S+E+W)\n\n #delete coin\n portid_delete=Entry(pycrypto,borderwidth=2,relief=\"groove\") \n portid_delete.grid(row=coin_row+3,column=0,sticky=N+S+E+W)\n\n delete_coin_txt=Button(pycrypto,text=\"Delete Coin\",bg=\"#142E54\",fg=\"white\",command=delete_coin,font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n delete_coin_txt.grid(row=coin_row+3,column=4,sticky=N+S+E+W) \n\n totalap=Label(pycrypto,text=\"${0:.2f}\".format(total_amount_paid),bg=\"#F3F4F6\",fg=\"black\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n totalap.grid(row=coin_row,column=4,sticky=N+S+E+W)\n\n totalcv=Label(pycrypto,text=\"${0:.2f}\".format(total_current_value),bg=\"#F3F4F6\",fg=\"black\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n totalcv.grid(row=coin_row,column=5,sticky=N+S+E+W)\n\n totalpl=Label(pycrypto,text=\"${0:.2f}\".format(total_pl),bg=\"#F3F4F6\",fg=font_color(float(\"{0:.2f}\".format(total_pl))),font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n totalpl.grid(row=coin_row,column=7,sticky=N+S+E+W)\n api=\"\"\n refresh=Button(pycrypto,text=\"Refresh\",bg=\"#142E54\",fg=\"white\",command=reset,font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n refresh.grid(row=coin_row+1,column=7,sticky=N+S+E+W)\n\n\n\ndef application_header():\n\n portfolio_id=Label(pycrypto,text=\"Portfolio ID\",bg=\"#142E54\",fg=\"white\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n portfolio_id.grid(row=0,column=0,sticky=N+S+E+W)\n\n name=Label(pycrypto,text=\"Coin Name\",bg=\"#142E54\",fg=\"white\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n name.grid(row=0,column=1,sticky=N+S+E+W)\n\n price=Label(pycrypto,text=\"Price\",bg=\"#142E54\",fg=\"white\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n price.grid(row=0,column=2,sticky=N+S+E+W)\n\n no_coins=Label(pycrypto,text=\"Coins Owned\",bg=\"#142E54\",fg=\"white\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n no_coins.grid(row=0,column=3,sticky=N+S+E+W)\n\n amount_paid=Label(pycrypto,text=\"Total Amount Paid\",bg=\"#142E54\",fg=\"white\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n amount_paid.grid(row=0,column=4,sticky=N+S+E+W)\n\n current_val=Label(pycrypto,text=\"Current Value\",bg=\"#142E54\",fg=\"white\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n current_val.grid(row=0,column=5,sticky=N+S+E+W)\n\n pl_coin=Label(pycrypto,text=\"P/L Per Coin\",bg=\"#142E54\",fg=\"white\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n pl_coin.grid(row=0,column=6,sticky=N+S+E+W)\n\n total_pl=Label(pycrypto,text=\"Total P/L With Coin\",bg=\"#142E54\",fg=\"white\",font=\"Lato 12 bold\",padx=\"5\",pady=\"5\",borderwidth=2,relief=\"groove\")\n total_pl.grid(row=0,column=7,sticky=N+S+E+W)\n\napp_nav()\napplication_header()\nmy_portfolio()\n\n\npycrypto.mainloop()\n\n\nprint(\"Program Completed\")\n\ncObj.close()\ncon.close()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"258662547","text":"from django import template\n\nregister = template.Library()\nimport re\n\nPATTERN = re.compile('width=\"\\d+pt\"')\nH = re.compile('height=\"\\d+pt\"')\n\ndef add_responsive_tags(svg):\n \n svg = PATTERN.sub('width=\"100%\" preserveAspectRatio=\"xMinYMin meet\" ',svg)\n svg = H.sub('', svg)\n return svg\n\n\ndef add_responsive_height(svg):\n \n svg = PATTERN.sub('width=\"90%\" preserveAspectRatio=\"xMinYMax\" ',svg)\n svg = H.sub('height=\"90%\"', svg)\n return svg\n\nregister.filter('add_responsive_tags', add_responsive_tags)\nregister.filter('add_responsive_height', add_responsive_tags)","sub_path":"chembiocrunch/workflow/templatetags/svg_responsive.py","file_name":"svg_responsive.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"647053995","text":"import csv\nfrom google.cloud import firestore\n\nSLACK_FILE = 'slack-devconteam-members.csv'\nSLACK_FIELDS = ['username', 'email', 'status', 'billing-active', 'has-2fa', 'has-sso', 'userid', 'fullname', 'displayname']\nEXPORT_FILE = 'devcon.members.csv'\nEXPORT_FIELDS = ['name', 'email', 'date', 'linkedin', 'github', 'twitter', 'referrer', 'role', 'bio']\n\n\"\"\"\nsample dict:\n {\n 'github': 'https://github.com/blah',\n 'adminDate': '2019-05-16T09:48:00.595Z',\n 'bio': 'I like to write code',\n 'adminUid': 'p60VyrQ2S1hv110Z9RYAdg8zrrQ2',\n 'twitter': 'https://twitter.com/blah',\n 'name': 'Clever Dev',\n 'date': DatetimeWithNanoseconds(2019, 5, 15, 20, 31, 34, 318000, tzinfo=),\n 'linkedin': 'https://www.linkedin.com/in/blah',\n 'uid': 'ud1us3RG8lcJxarozJGMJfernuU2',\n 'applicant': 'members',\n 'email': 'me@email.com',\n 'referrer': \"Someone\",\n 'role': 'Tech Director'\n }\n\"\"\"\n\ndef members_collection_to_dict(db):\n out = {}\n members = db.collection(u'members').get()\n for m in members:\n out[m.id] = m.to_dict()\n return out\n\n\ndef cast_field(field, members_dict):\n # if field == 'date':\n # return members_dict.get(field).isoformat()\n return members_dict.get(field)\n\n\ndef export_members(members_dict, fields=EXPORT_FIELDS):\n with open(EXPORT_FILE, 'w', newline='') as csvfile:\n csvwriter = csv.writer(csvfile)\n csvwriter.writerow(EXPORT_FIELDS)\n for m_id, m_dict in members_dict.items():\n csvwriter.writerow([cast_field(f, m_dict) for f in EXPORT_FIELDS])\n print(f'\\n devcon members saved to {EXPORT_FILE}')\n\n\ndef load_slack_members():\n out = {}\n with open(SLACK_FILE, newline='') as csvfile:\n csvreader = csv.DictReader(csvfile)\n for row in csvreader:\n out[row['userid']] = row\n return out\n\n\ndef reconcile_members(members_dict, slack_members_dict):\n # weird, throws a keyerror if accessing with square brackets\n members_emails = set([m.get('email') for uid, m in members_dict.items()])\n slack_members_emails = set([m['email'] for uid, m in slack_members_dict.items()])\n print('++++++++++++++++++++++++++++++++')\n print(f'there are {len(members_emails)} registered devcon members and {len(slack_members_emails)} slack members')\n print('\\n list of members in devcon not on slack: \\n')\n print(f'------------------------------------------\\n {members_emails - slack_members_emails}')\n print('\\n list of members in slack not on devcon: \\n')\n print(f'------------------------------------------\\n {slack_members_emails - members_emails}')\n\n\ndef run():\n db = firestore.Client()\n members_dict = members_collection_to_dict(db)\n slack_members_dict = load_slack_members()\n reconcile_members(members_dict, slack_members_dict)\n export_members(members_dict)\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"scripts/admin/users/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"546429272","text":"import threading \nimport time\nimport queue\nimport socket\n\nIP = \"127.0.0.1\"\nPORT = 5000\nP = 5001\naddr = (IP, PORT)\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nevents = []\nclk = 0\nq = queue.Queue(10)\n\n# This is processing thread or consumer thread\nclass cThread (threading.Thread):\n\tdef __init__ (self, threadID, name, counter):\n\t\tthreading.Thread.__init__(self)\n\t\tself.threadID = threadID\n\t\tself.name = name\n\t\tself.counter = counter\n\n\tdef run(self):\n\t\tglobal clk\n\n\t\twhile True:\n\t\t\t# socket set up\n\t\t\t\n\t\t\t# clk set up\n\t\t\tif q.empty():\t\n\t\t\t\tthreadLock.acquire()\n\t\t\t\t# print(\"q is empty, block\")\n\t\t\tif not q.empty():\n\t\t\t\t# print(\"q is not empty, unblock\")\n\t\t\t\tthreadLock.release()\n\t\t\t\te = q.get()\n\n\t\t\t\t# lambort logic\n\t\t\t\tif e[0]==\"receive\":\n\t\t\t\t\tclk = max(clk,e[3])+1\n\t\t\t\t\tval = ((\"receive event: \"+e[1],clk))\n\t\t\t\telif e[0]==\"send\":\n\t\t\t\t\tc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\t\t\t\tc.connect(addr)\n\n\t\t\t\t\tclk = clk+1\n\t\t\t\t\tval = ((\"send event: \"+e[1], clk))\n\t\t\t\t\tdata = e[1]+\"/\"+str(clk)+\"/\"+str(e[3])\n\t\t\t\t\tc.sendall(data.encode('utf-8'))\n\t\t\t\t\tc.close()\n\n\t\t\t\telse:\n\t\t\t\t\tclk = clk + 1\n\t\t\t\t\tval = ((\"local event: \" + e[0]), clk)\n\n\t\t\t\tevents.append(val)\n\t\t\t\tthreadLock.acquire()\n\t\t\t\t# print(\"add: \", e, \"unblock the q\")\n\n\nclass pThread (threading.Thread):\n\tdef __init__ (self, threadID, name, counter):\n\t\tthreading.Thread.__init__(self)\n\t\tself.threadID = threadID\n\t\tself.name = name\n\t\tself.counter = counter\n\n\tdef run(self):\n\t\ts.bind((IP, P))\n\t\ts.listen(1)\n\t\twhile True:\n\t\t\t# print(\"wait for message\")\n\t\t\tstream, addr = s.accept()\n\t\t\t# print(\"socket created, wait for incoming message\")\n\t\t\tmessage = stream.recv(1024).decode('utf-8')\n\t\t\tprint(message)\n\n\t\t\tprint(\"receive message push to queue\")\n\t\t\t# recv message (event, msg, clk, id)\n\t\t\tthreadLock.release()\n\n\t\t\t# decode msg\n\t\t\tmsg = message.split(\"/\")\n\t\t\tdata = ((\"receive\",\"'\"+msg[0]+\"'\",0,int(msg[1])))\n\n\n\t\t\tq.put(data)\n\t\t\tprint(\"go back to wait\")\n\t\t# for i in range (0,3):\n\t\t# \tprint(\"starting\" + self.name)\n\t\t# \t# threadLock.acquire()\n\t\t# \tprint_time(self.name, self.counter, 3)\n\t\t# \t# threadLock.release()\n\n\n\nthreadLock = threading.Lock()\nthreads = []\n\nthread1 = cThread(1, \"Thread-1\", 1)\nthread2 = pThread(2, \"Thread-2\", 2)\n\nthread1.start()\nthread2.start()\n\nthreads.append(thread1)\nthreads.append(thread2)\n\n\n# for t in threads:\n# \tt.join()\nwhile True:\n\tx = int(input(\"\\nInput 1 to add local event or 2 to send a message or 3 to print clock value \\n\"))\n\t\n\t# Add local event\n\tif x == 1:\n\t\t\n\t\t# specify the event (event, msg, send = 1, id)\n\t\ty = input(\"Event: \")\n\t\tevent = ((y,\"\", 0,0))\n\t\tthreadLock.release()\n\t\tq.put(event)\n\telif x == 2:\n\t\tid = int(input(\"Add receiver id: \"))\n\n\t\tmsg = input(\"Send event name: \")\n\t\tevent = ((\"send\", msg, 1, id))\n\t\tthreadLock.release()\n\t\tq.put(event)\n\n\telif x == 3:\n\t\tfor i in events:\n\t\t\t# print(events)\n\t\t\tprint(i,\"\\n\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t# event = int(input(\"enter: \"))\n\t# if event == 1:\n\t# \tif q.empty():\n\t# \t\tprint(\"empty\")\n\n\t# \tprint(l)\n\t# else:\n\t# \tq.put(event)\n\n\n\n\n\n\t","sub_path":"lab1/client1.py","file_name":"client1.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"264016349","text":"from __future__ import absolute_import, division, print_function\n\nimport os\nimport sys\n\nfrom setuptools import find_packages, setup\n\n__version__ = \"1.0.1\"\n\ninstall_requires = [\"numpy>1.10\", \"scipy\", \"pysam>=0.8.2\", \"matplotlib\"] \n\nsetup(\n\tname = \"genome_tools\",\n\tversion = __version__,\n\tlicense = \"GPL-3.0-or-later\",\n\tdescription = \"A toolkit for processing and plotting genomic datasets.\",\n\tlong_description = \"\",\n\tauthor = \"Jeff Vierstra\",\n\tauthor_email = \"jvierstra@altius.org\",\n\tzip_safe = False,\n\tpackages = find_packages(),\n install_requires = install_requires,\n download_url = \"https://github.com/jvierstra/genome-tools/archive/v1.0.1.tar.gz\",\n classifiers=[\n\t 'Development Status :: 5 - Production/Stable', # Chose either \"3 - Alpha\", \"4 - Beta\" or \"5 - Production/Stable\" as the current state of your package\n\t 'Intended Audience :: Developers', # Define that your audience are developers\n\t 'Topic :: Software Development :: Build Tools',\n\t 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',\n\t 'Programming Language :: Python :: 2.7', #Specify which pyhton versions that you want to support\n\t 'Programming Language :: Python :: 3',\n\t 'Programming Language :: Python :: 3.5', \n ],\n)\n","sub_path":"pypi_install_script/genome_tools-1.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"580788879","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import get_object_or_404\nfrom .models import Recipe\nfrom .form import RecipeForm, ContactForm\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\n\n\ndef user_form(request):\n return render(request, 'recipe/userform.html')\n\n\ndef saveuser(request):\n if request.method == 'POST':\n print(\"-------->\", request.POST)\n print(\"username ------>\", request.POST['username'])\n print(\"first_name ---->\", request.POST['first_name'])\n print(\"last_name ------>\", request.POST['last_name'])\n print(\"email ------>\", request.POST['email'])\n print(\"password ------>\", request.POST['password'])\n user = User.objects.create_user(username=request.POST['username'],\n first_name=request.POST['first_name'],\n last_name=request.POST['last_name'],\n email=request.POST['email'],\n password=request.POST['password'])\n user.save()\n return render(request, 'recipe/login.html', {'msg':'User is saved Successfully ....!'} )\n\n\ndef login_form(request):\n return render(request, 'recipe/login.html')\n\n\ndef login_view(request):\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(request, username=username, password=password)\n if user is not None:\n login(request, user)\n name = \"\"#query\n org = \"\"#query\n request.session[\"org\"] = org\n request.session[\"name\"] = name\n return HttpResponseRedirect(\"/app/\")\n else:\n return HttpResponse(\"Invalid Credentials\")\n\n\ndef logout_view(request):\n request.session.clear()\n request.session.delete()\n logout(request)\n return HttpResponseRedirect(\"/app/login_form/\")\n\ndef register_recipe(request):\n org = request.session[\"org\"]\n name = request.session[\"name\"]\n form = RecipeForm()\n return render(request, 'recipe/recipe_form.html', {\"form\": form})\n\n@login_required(login_url=\"/app/login_form/\")\ndef saverecepi(request):\n if request.method == 'POST':\n # recipe_form = RecipeForm(request.POST)\n # if recipe_form.is_valid():\n # recipe_obj = recipe_form.save(commit=False)\n # recipe_obj.created_by = request.user\n # recipe_obj.save()\n # return HttpResponseRedirect(\"/app/\")\n # else:\n # return render(request, 'recipe/recipe_form.html', {\"errors\": recipe_form.errors, \"form\": RecipeForm()})\n import pdb; pdb.set_trace()\n if request.POST.get(\"recipe_name\") and request.POST.get(\"recipe_type\"):\n recipe = Recipe(recipe_name=request.POST['recipe_name'],\n recipe_type=request.POST['recipe_type'],\n ingredients=request.POST['ingredients'],\n procedure=request.POST['procedure'],\n recipe_image=request.FILES[\"recipe_image\"])\n recipe.save()\n else:\n if not request.POST.get(\"recipe_name\"):\n msg = \"Recipe Name is missing\"\n elif not request.POST.get(\"recipe_type\"):\n msg = \"Recipe Ingredients are missing\"\n return render(request, 'recipe/recipe_form.html', {'msg': msg, \"form\": RecipeForm()} )\n return render(request, 'recipe/recipe_form.html', {'msg': 'Recipe is saved Successfully ....!', \"form\": RecipeForm()} )\n\n@login_required(login_url=\"/app/login_form/\")\ndef recipe_booklet(request):\n recipe_list = Recipe.objects.all()\n return render(request, 'recipe/recipe.html', {'recipe_list': recipe_list})\n\n@login_required(login_url=\"/app/login_form/\")\ndef deleterecipe(request, recipe_id):\n recipe = get_object_or_404(Recipe, pk=recipe_id)\n recipes = Recipe.objects.all()\n print('Recipe-------->', recipe)\n recipe.delete()\n return render(request, 'recipe/recipe.html', {'msg': 'The recipe Deleted Successfully ...!',\n 'recipe_list': recipes})\n\n@login_required(login_url=\"/app/login_form/\")\ndef editrecipe(request, recipe_id):\n recipe = get_object_or_404(Recipe, pk=recipe_id)\n return render(request, 'recipe/recipe_form.html', {\"recipe\": recipe} )\n\n\ndef contact_form(request):\n if request.method == \"GET\":\n return render(request, \"recipe/contact_form.html\", { \"recipe_form\": RecipeForm(), \"form\": ContactForm()})\n else:\n form = ContactForm(request.POST)\n recipe_form = RecipeForm(request.POST)\n if form.is_valid() and recipe_form.is_valid():\n recipe_form.save()\n ## email sending functionality\n cc_myself = form.cleaned_data[\"cc_myself\"]\n return render(request, \"recipe/contact_form.html\", { \"recipe_form\": RecipeForm(),\"form\": ContactForm()})\n else:\n return render(request, \"recipe/contact_form.html\", {\"form\": ContactForm(), \"recipe_form\": RecipeForm(), \"errors\": form.errors})\n\n\ndef recipe_details(request, recipe_id):\n recipe_obj = Recipe.objects.get(id=recipe_id)\n return render(request, 'recipe/details.html', {\"recipe\": recipe_obj})\n","sub_path":"recipe/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"74030223","text":"# -*- coding:utf-8 -*-\r\n\"\"\"\r\npython3 获取redis的值,返回结果类型是bytes\r\nhttp://www.cnblogs.com/melonjiang/p/5342505.html\r\n\"\"\"\r\n\r\nimport os,sys\r\nimport redis \r\nimport time\r\nimport random\r\nfrom pprint import pprint as pp\r\n\r\nconfig = {\r\n 'host': 'localhost',\r\n 'port': 6379,\r\n# 'password': '123',\r\n 'db': 0\r\n}\r\n\r\nr = redis.Redis(**config)\r\n\r\n\r\nr.set(\"name1\", \"aaa\")\r\n\r\nprint ( r.get(\"key1\").decode() )\r\n\r\nprint(r.getset(\"key1\",\"eric\")) # 设置新值,打印原值 \r\nprint(r.get(\"name1\")) \r\n\r\nprint(r.getrange(\"name\",0,3)) #输出:zhan\r\nr.setrange(\"name1\",1,\"z\")\r\n\r\nprint(r.get(\"name1\")) \r\nr.setrange(\"name1\",3,\"zzzzzzz\") # setrange(name, offset, value)\r\n\r\nprint(r.get(\"name1\")) \r\nprint(r.strlen(\"name1\")) \r\n\r\nr.append(\"name1\",\"lisi\") #在name对应的值后面追加内容\r\nprint(r.get(\"name1\")) \r\n","sub_path":"redis1/get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"292673637","text":"# Copyright 2020-2021 antillia.com Toshiyuki Arai\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# ImageMorphing.py\n\n# encodig: utf-8\n\nimport sys\nimport os\nimport cv2\nimport traceback\n\n\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\n\n# \nsys.path.append('../')\n\nfrom SOL4Py.ZApplicationView import *\n\nfrom SOL4Py.ZLabeledComboBox import ZLabeledComboBox\nfrom SOL4Py.ZLabeledSlider import ZLabeledSlider\nfrom SOL4Py.opencv.ZOpenCVImageView import ZOpenCVImageView \nfrom SOL4Py.ZVerticalPane import ZVerticalPane \n\n \nclass MainView(ZApplicationView):\n # Inner classes\n #--------------------------------------------\n class SourceImageView(ZOpenCVImageView):\n def __init__(self, parent):\n ZOpenCVImageView.__init__(self, parent)\n\n def load(self, filename):\n self.load_opencv_image(filename)\n self.update()\n\n class TransformedImageView(ZOpenCVImageView):\n def __init__(self, parent):\n ZOpenCVImageView.__init__(self, parent)\n \n def load(self, filename):\n self.load_opencv_image(filename)\n \n def transform(self, shape_id, type_id, ksize):\n src_image = self.get_opencv_image()\n \n element = cv2.getStructuringElement(shape_id,\n (ksize, ksize), ( -1, -1) )\n transformed_image = cv2.morphologyEx(src_image, type_id, element);\n \n if transformed_image.all() != None:\n self.set_opencv_image(transformed_image)\n self.update()\n \n #--------------------------------------------\n \n\n\n # MainView Constructor\n def __init__(self, title, x, y, width, height):\n super(MainView, self).__init__(title, x, y, width, height)\n\n filename = \"../images/HelloWorld.png\"\n \n # 1 Create first imageview.\n self.source_image_view = self.SourceImageView(self) \n\n # 2 Create second imageview.\n self.transformed_image_view = self.TransformedImageView(self) \n \n # 3 Load the file\n self.load_file(filename)\n \n # 4 Add two image views to a main_layout of this main view.\n self.add(self.source_image_view)\n self.add(self.transformed_image_view)\n \n self.show()\n \n\n def add_control_pane(self, fixed_width=220):\n # Control pane widget\n self.vpane = ZVerticalPane(self, fixed_width)\n\n self.ksize = 3\n\n self.shape_id = 2; \n self.type_id = 3\n self.shapes = { \"MORPH_RECT\": 0, \"MORPH_CROSS\": 1, \"MORPH_ELLIPSE\":2}\n \n self.shape = ZLabeledComboBox(self.vpane, \"MorphShape\")\n self.shape.add_items(list(self.shapes.keys() ))\n self.shape.add_activated_callback(self.shape_activated)\n self.shape.set_current_text(self.shape_id)\n \n self.types = { \"MORPH_OPEN\": 0, \"MORPH_CLOSE\": 1, \"MORPH_GRADIENT\": 2,\n \"MORPH_TOPHAT\": 3, \"MORPH_BLACKHAT\": 4 }\n self.type = ZLabeledComboBox(self.vpane, \"MorphType\")\n self.type.add_items(list(self.types.keys() ))\n self.type.add_activated_callback(self.type_activated)\n self.type.set_current_text(self.type_id)\n \n self.ksize_slider = ZLabeledSlider(self.vpane, \"KernelSize\", take_odd =True, \n minimum=1, maximum=33, value=self.ksize, fixed_width=200)\n self.ksize_slider.add_value_changed_callback(self.ksize_value_changed)\n \n self.vpane.add(self.shape)\n self.vpane.add(self.type) \n self.vpane.add(self.ksize_slider)\n \n self.set_right_dock(self.vpane)\n\n def file_open(self):\n options = QFileDialog.Options()\n filename, _ = QFileDialog.getOpenFileName(self,\"FileOpenDialog\", \"\",\n \"All Files (*);;Image Files (*.png;*jpg;*.jpeg)\", options=options)\n if filename:\n self.load_file(filename)\n \n def load_file(self, filename):\n self.source_image_view.load(filename)\n self.transformed_image_view.load(filename) \n self.transformed_image_view.transform(self.shape_id, self.type_id, self.ksize)\n self.set_filenamed_title(filename)\n \n def shape_activated(self, text):\n self.shape_id = self.shapes[text]\n print(\"shape_activated:{} {}\".format(text, self.shape_id))\n self.transformed_image_view.transform(self.shape_id, self.type_id, self.ksize)\n \n def type_activated(self, text):\n self.type_id = self.types[text]\n print(\"type_activated:{} {}\".format(text, self.type_id))\n self.transformed_image_view.transform(self.shape_id, self.type_id, self.ksize)\n \n \n def ksize_value_changed(self, value):\n self.ksize = int(value)\n if self.ksize % 2 == 0:\n self.ksize = int((self.ksize * 2)/2 + 1)\n # Block size should be odd.\n #print(\"ksize_value_changed:{}\".format(ksize))\n self.transformed_image_view.transform(self.shape_id, self.type_id, self.ksize)\n \n \n#*************************************************\n# \nif main(__name__):\n try:\n app_name = os.path.basename(sys.argv[0])\n applet = QApplication(sys.argv)\n \n main_view = MainView(app_name, 40, 40, 900, 380)\n main_view.show ()\n\n applet.exec_()\n\n except:\n traceback.print_exc()\n \n\n","sub_path":"opencv/ImageMorphing.py","file_name":"ImageMorphing.py","file_ext":"py","file_size_in_byte":5491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"219726460","text":"import sys\nfrom PyQt5.QtWidgets import QWidget, QMainWindow, QCalendarWidget, QLabel, QApplication,QToolTip,QMessageBox\nfrom PyQt5.QtCore import QDate\nfrom PyQt5 import uic\nfrom PyQt5.QtGui import QIntValidator, QDoubleValidator,QFont,QPixmap,QIcon\nfrom PyQt5 import QtGui, QtCore\nimport math\n\n\n\n\nclass MyWindow(QMainWindow):\n \"\"\"docstring for MyWindow\"\"\"\n\n def __init__(self):\n super(MyWindow, self).__init__()\n uic.loadUi('untitled.ui', self)\n self.setWindowTitle('Queuing System')\n self.pushButton.clicked.connect(self.btnClear)\n self.combo.activated[str].connect(self.onActivated)\n self.statusBar()\n self.show()\n MyWindow.chekInput(self)\n MyWindow.imageButton(self)\n self.show()\n\n def help(self):\n \tQToolTip.setFont(QFont('SansSerif', 10))\n \tself.label.setToolTip('Абсолютная пропускная способность')\n\n def imageButton(self):\n \ticon = QIcon(\"smile.png\")\n \tself.pushButton.setIcon(icon)\n \t\n\n\n\n def chekInput(self):\n intValidator = QIntValidator()\n doubleValidator = QDoubleValidator()\n self.input_n.setValidator(intValidator)\n self.input_m.setValidator(intValidator)\n self.input_L.setValidator(doubleValidator)\n self.input_Mu.setValidator(doubleValidator)\n\n def onActivated(self, text):\n def_list = (\n self.none, self.monoDis,\n self.polyDis, self.monoWait, self.monoInf, self.polyWait, self.polyInf,self.monoClose,self.polyClose)\n index = self.combo.currentIndex() + 1\n def_list[index - 1]()\n\n def none(self):\n pass\n\n def inputValue(self):\n n = int(self.input_n.text())\n m = int(self.input_m.text())\n Lambda = float(self.input_L.text())\n Mu = float(self.input_Mu.text())\n return (\n n, m, Lambda, Mu)\n\n def outputValue(self, output_dict):\n A ='A = ' + str(output_dict.setdefault('A', ' -- '))\n q = 'q = ' + str(output_dict.setdefault('q', ' -- '))\n Potk ='Potk = ' + str(output_dict.setdefault('Potk', ' -- '))\n z ='z = ' + str(output_dict.setdefault('z', ' -- '))\n P0 ='P0 = ' + str(output_dict.setdefault('P0', ' -- '))\n r = 'r = ' + str(output_dict.setdefault('r', ' -- '))\n Twait ='Twait = ' + str(output_dict.setdefault('Twait', ' -- '))\n Tsys ='Tsys = ' + str(output_dict.setdefault('Tsys', ' -- '))\n k ='k = ' + str(output_dict.setdefault('k', ' -- '))\n Tservice ='Tservice = ' + str(output_dict.setdefault('Tservice', ' -- '))\n w ='w = ' + str(output_dict.setdefault('w', ' -- '))\n Pz ='Pz = ' + str(output_dict.setdefault('Pz', ' -- '))\n self.listWidget.addItem(A[:10])\n self.listWidget.addItem(q[:10])\n self.listWidget.addItem(Potk[:13])\n self.listWidget.addItem(z[:10])\n self.listWidget.addItem(P0[:11])\n self.listWidget.addItem(r[:10])\n self.listWidget.addItem(Twait[:13])\n self.listWidget.addItem(Tsys[:13])\n self.listWidget.addItem(k[:10])\n self.listWidget.addItem(Tservice[:17])\n self.listWidget.addItem(Pz[:11])\n self.listWidget.addItem(w[:10])\n\n def monoDis(self):\n n, m, Lambda, Mu = MyWindow.inputValue(self)\n A = Lambda * Mu / (Lambda + Mu)\n Potk = Lambda / (Lambda + Mu)\n q = Mu / (Lambda + Mu)\n output_dict = dict(A=A, Potk=Potk, q=q)\n MyWindow.outputValue(self, output_dict)\n\n def polyDis(self):\n n, m, Lambda, Mu = MyWindow.inputValue(self)\n Ro = round(Lambda / Mu, 3)\n Pi = 0\n P0 = 0\n for i in range(n + 1):\n Pi += Ro ** i / math.factorial(i)\n\n P0 = round(1 / Pi, 3)\n Potk = round(Ro ** n / math.factorial(n) * P0, 3)\n q = round(1 - Potk, 3)\n A = round(Lambda * q, 3)\n z = round(A / Mu, 3)\n output_dict = dict(A=A, Potk=Potk, q=q, z=z)\n MyWindow.outputValue(self, output_dict)\n\n def monoWait(self):\n n, m, Lambda, Mu = MyWindow.inputValue(self)\n Pi = 0\n P0 = 0\n Ro = round(Lambda / Mu, 3)\n if Ro != 1:\n P0 = round((1 - Ro) / (1 - Ro ** (m + 2)), 3)\n elif Ro == 1:\n P0 = round(1 / (m + 2), 3)\n Potk = Ro ** (m + 1) * P0\n q = 1 - Potk\n A = Lambda * q\n r = Ro ** 2 * P0 * (1 - (m + 1) * Ro ** m + m * Ro ** (m + 1)) / (1 - Ro) ** 2\n Twait = r / Lambda\n Tsys = Twait + 1 / Mu * q\n k = r + 1 - P0\n output_dict = dict(A=A, Potk=Potk, q=q, P0=P0, r=r, Twait=Twait, Tsys=Tsys, k=k)\n MyWindow.outputValue(self, output_dict)\n\n def monoInf(self):\n n, m, Lambda, Mu = MyWindow.inputValue(self)\n Ro = round(Lambda / Mu, 3)\n Pi = 0\n P0 = 0\n if Ro < 1:\n P0 = 1 - Ro\n r = Ro ** 2 / (1 - Ro)\n Twait = r / Lambda\n Tservice = 1 / Mu\n k = r + Ro\n output_dict = dict(A=Lambda, q=1, P0=P0, r=r, Twait=Twait, k=k, Tservice=Tservice)\n MyWindow.outputValue(self, output_dict)\n else:\n self.label_6.setText('Error Ro >=1 ')\n\n def polyWait(self):\n n, m, Lambda, Mu = MyWindow.inputValue(self)\n Pi = 0\n P0 = 0\n Ro = Lambda / Mu\n ETA = Ro / n\n for i in range(n + 1):\n Pn = Ro ** n / math.factorial(n) * ((ETA - ETA ** (m + 1)) / (1 - ETA))\n Pi += Ro ** i / math.factorial(i)\n\n P0 = 1 / (Pi + Pn)\n q = 1 - Ro ** (n + m) * P0 / (n ** m * math.factorial(n))\n A = Lambda * q\n r = Ro ** (n + 1) / (n * math.factorial(n)) * P0 * (1 - (m + 1) * ETA ** m + m * ETA ** (m + 1)) / (1 - ETA) ** 2\n Twait = r / Lambda\n z = A / Mu\n k = r + z\n output_dict = dict(A=A, q=q, P0=P0, r=r, Twait=Twait, z=z, k=k)\n MyWindow.outputValue(self, output_dict)\n\n def polyInf(self):\n n, m, Lambda, Mu = MyWindow.inputValue(self)\n Pi = 0\n P0 = 0\n Ro = round(Lambda / Mu, 3)\n ETA = Ro / n\n if ETA < 1:\n for i in range(n + 1):\n Pn = Ro ** n / math.factorial(n) * (ETA / (1 - ETA))\n Pi += Ro ** i / math.factorial(i)\n\n P0 = round(1 / (Pi + Pn), 3)\n r = Ro ** (n + 1) * P0 / (n * math.factorial(n) * (1 - ETA) ** 2)\n Twait = r / Lambda\n z = Ro\n k = r + z\n output_dict = dict(A=Lambda, q=1, P0=P0, r=r, Twait=Twait, z=z, k=k)\n MyWindow.outputValue(self, output_dict)\n else:\n self.label_6.setText('Error Ro >=1 ')\n\n\n\n\n def monoClose(self):\n \tn, m, Lambda, Mu = MyWindow.inputValue(self)\n \tPi = 0\n \tw = 0\n \tRo = round(Lambda/Mu,4)\n \tfor i in reversed(range(1,n)):\n \t\tPi +=n*(n-i)*(Ro**(n-i))\n \tP0 = round(1/(1+Pi+MyWindow.inv(self,n)*Ro**n),4)\n \tPz = 1 - P0\n \tA = round(Pz*Mu,3)\n \tw = n-(Pz/Ro)\n \toutput_dict = dict(A=A,P0=P0, Pz = Pz, w = w )\n \tMyWindow.outputValue(self, output_dict)\n\n def inv(self, n):\n \tf = 1\n \tfor i in range(n):\n \t\tf =f*(n-i)\n \tres = f\n \treturn res\n\n def polyClose(self): #Многоканальная СМО замкнутая\n \tn, m, Lambda, Mu = MyWindow.inputValue(self)\n \tPi = 0\n \tP0 = 0\n \tPk = 0\n \tPt = 1\n \tf = 1\n \tRo = round(Lambda/Mu,3)\n \tfor i in range(1,n+1):\n \t\tif i < (m+1):\n \t\t\tf =f*(n-i+1)\n \t\t\tPt = Pt * (math.factorial(i))\n \t\t\tPi += (f/Pt)*(Ro**i)\n \t\telse:\n \t\t\tf =f*(n-i+1)\n \t\t\tPt = (math.factorial(m))*((m**(i-m)))\n \t\t\tPi += (f/Pt)*(Ro**i)\n \tP0 = 1/(1+Pi)\n \toutput_dict = dict(P0=P0)\n \tMyWindow.outputValue(self, output_dict)\n\n\n\t\t\t\n\n def btnClear(self):\n self.listWidget.clear()\n self.label_6.setText('')\n\n self.statusBar().showMessage('Clear')\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = MyWindow()\n sys.exit(app.exec_())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"239833194","text":"\r\nmodInverse = lambda A, n,s=1,t=0,N=0: (n < 2 and t%N or modInverse(n, A%n, t, s-A//n*t, N or n),-1)[n<1]\r\n\r\ndef abc (x,n):\r\n a = modInverse(x,n)\r\n if a != -1 :\r\n return 1\r\n else :\r\n return 0\r\n\r\n\r\nif __name__ == '__main__':\r\n n = int(input())\r\n count = 0\r\n for x in range(1, n):\r\n t = abc(x, n)\r\n if t == 1:\r\n count += 1\r\n print(count)\r\n","sub_path":"mod inverse.py","file_name":"mod inverse.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"508921816","text":"import random\r\n\r\nclass UnoCard:\r\n '''represents an Uno card\r\n attributes:\r\n rank: int from 0 to 9\r\n color: string'''\r\n\r\n def __init__(self,rank,color,action=None):\r\n '''UnoCard(rank,color) -> UnoCard\r\n creates an Uno card with the given rank and color'''\r\n self.rank = rank\r\n self.color = color\r\n self.action = action\r\n\r\n def __str__(self):\r\n '''str(Unocard) -> str'''\r\n if self.rank == -1:\r\n return str(self.color)+' '+str(self.action)\r\n return(str(self.color)+' '+str(self.rank))\r\n\r\n def is_match(self,other):\r\n '''UnoCard.is_match(UnoCard) -> boolean\r\n returns True if the cards match in rank or color, False if not'''\r\n if self.rank == -1:\r\n return (self.color == other.color) or (self.action == other.action) \r\n return (self.color == other.color) or (self.rank == other.rank) \r\n\r\nclass UnoDeck:\r\n '''represents a deck of Uno cards\r\n attribute:\r\n deck: list of UnoCards'''\r\n\r\n def __init__(self):\r\n '''UnoDeck() -> UnoDeck\r\n creates a new full Uno deck'''\r\n self.deck = []\r\n for color in ['red', 'blue', 'green', 'yellow']:\r\n self.deck.append(UnoCard(0,color)) # one 0 of each color\r\n for i in range(2):\r\n self.deck.append(UnoCard(-1,color,action='skip'))\r\n self.deck.append(UnoCard(-1,color,action='reverse'))\r\n self.deck.append(UnoCard(-1,color,action='drawtwo'))\r\n for n in range(1,10): # two of each of 1-9 of each color\r\n self.deck.append(UnoCard(n,color))\r\n random.shuffle(self.deck) # shuffle the deck\r\n\r\n def __str__(self):\r\n '''str(Unodeck) -> str'''\r\n return 'An Uno deck with '+str(len(self.deck))+' cards remaining.'\r\n\r\n def is_empty(self):\r\n '''UnoDeck.is_empty() -> boolean\r\n returns True if the deck is empty, False otherwise'''\r\n return len(self.deck) == 0\r\n\r\n def deal_card(self):\r\n '''UnoDeck.deal_card() -> UnoCard\r\n deals a card from the deck and returns it\r\n (the dealt card is removed from the deck)'''\r\n return self.deck.pop()\r\n\r\n def reset_deck(self,pile):\r\n '''UnoDeck.reset_deck(pile) -> None\r\n resets the deck from the pile'''\r\n if len(self.deck) != 0:\r\n return\r\n self.deck = pile.reset_pile() # get cards from the pile\r\n random.shuffle(self.deck) # shuffle the deck\r\n\r\nclass UnoPile:\r\n '''represents the discard pile in Uno\r\n attribute:\r\n pile: list of UnoCards'''\r\n\r\n def __init__(self,deck):\r\n '''UnoPile(deck) -> UnoPile\r\n creates a new pile by drawing a card from the deck'''\r\n card = deck.deal_card()\r\n self.pile = [card] # all the cards in the pile\r\n\r\n def __str__(self):\r\n '''str(UnoPile) -> str'''\r\n return 'The pile has '+str(self.pile[-1])+' on top.'\r\n\r\n def top_card(self):\r\n '''UnoPile.top_card() -> UnoCard\r\n returns the top card in the pile'''\r\n return self.pile[-1]\r\n\r\n def add_card(self,card):\r\n '''UnoPile.add_card(card) -> None\r\n adds the card to the top of the pile'''\r\n self.pile.append(card)\r\n\r\n def reset_pile(self):\r\n '''UnoPile.reset_pile() -> list\r\n removes all but the top card from the pile and\r\n returns the rest of the cards as a list of UnoCards'''\r\n newdeck = self.pile[:-1]\r\n self.pile = [self.pile[-1]]\r\n return newdeck\r\n\r\nclass UnoPlayer:\r\n '''represents a player of Uno\r\n attributes:\r\n name: a string with the player's name\r\n hand: a list of UnoCards'''\r\n\r\n def __init__(self,name,deck):\r\n '''UnoPlayer(name,deck) -> UnoPlayer\r\n creates a new player with a new 7-card hand'''\r\n self.name = name\r\n self.hand = [deck.deal_card() for i in range(7)]\r\n\r\n def __str__(self):\r\n '''str(UnoPlayer) -> UnoPlayer'''\r\n return str(self.name)+' has '+str(len(self.hand))+' cards.'\r\n\r\n def get_name(self):\r\n '''UnoPlayer.get_name() -> str\r\n returns the player's name'''\r\n return self.name\r\n\r\n def get_hand(self):\r\n '''get_hand(self) -> str\r\n returns a string representation of the hand, one card per line'''\r\n output = ''\r\n for card in self.hand:\r\n output += str(card) + '\\n'\r\n return output\r\n\r\n def has_won(self):\r\n '''UnoPlayer.has_won() -> boolean\r\n returns True if the player's hand is empty (player has won)'''\r\n return len(self.hand) == 0\r\n\r\n def draw_card(self,deck):\r\n '''UnoPlayer.draw_card(deck) -> UnoCard\r\n draws a card, adds to the player's hand\r\n and returns the card drawn'''\r\n card = deck.deal_card() # get card from the deck\r\n self.hand.append(card) # add this card to the hand\r\n return card\r\n\r\n def play_card(self,card,pile):\r\n '''UnoPlayer.play_card(card,pile) -> None\r\n plays a card from the player's hand to the pile\r\n CAUTION: does not check if the play is legal!'''\r\n self.hand.remove(card)\r\n pile.add_card(card)\r\n\r\n def take_turn(self,deck,pile, draw):\r\n '''UnoPlayer.take_turn(deck,pile) -> None\r\n takes the player's turn in the game\r\n deck is an UnoDeck representing the current deck\r\n pile is an UnoPile representing the discard pile'''\r\n # print player info\r\n cardAction = None\r\n\r\n print(self.name+\", it's your turn.\")\r\n print(pile)\r\n print(\"Your hand: \")\r\n print(self.get_hand())\r\n # get a list of cards that can be played\r\n topcard = pile.top_card()\r\n matches = [card for card in self.hand if card.is_match(topcard)]\r\n if len(matches) > 0 or draw > 1: # can play\r\n for index in range(len(matches)):\r\n # print the playable cards with their number\r\n print(str(index+1) + \": \" + str(matches[index]))\r\n # get player's choice of which card to play\r\n choice = 0\r\n while choice < 1 or choice > len(matches):\r\n choicestr = input(\"Which do you want to play? \")\r\n if choicestr.isdigit():\r\n choice = int(choicestr)\r\n cardChosen = matches[choice-1]\r\n cardAction = cardChosen.action\r\n # play the chosen card from hand, add it to the pile\r\n self.play_card(cardChosen,pile)\r\n else: # can't play\r\n print(\"You have no matches.\")\r\n for i in range(draw):\r\n input(\"Press enter to draw.\")\r\n # check if deck is empty -- if so, reset it\r\n if deck.is_empty():\r\n deck.reset_deck(pile)\r\n\r\n # draw a new card from the deck\r\n newcard = self.draw_card(deck)\r\n print(\"You drew: \"+str(newcard))\r\n if draw == 1:\r\n print(\"\\nLet's see if you have matches now..\")\r\n cardAction = self.take_turn(deck, pile, -1)\r\n return cardAction\r\n\r\ndef play_uno(numPlayers):\r\n '''play_uno(numPlayers) -> None\r\n plays a game of Uno with numPlayers'''\r\n # set up full deck and initial discard pile\r\n deck = UnoDeck()\r\n pile = UnoPile(deck)\r\n # set up the players\r\n playerList = []\r\n for n in range(numPlayers):\r\n # get each player's name, then create an UnoPlayer\r\n name = input('Player #'+str(n+1)+', enter your name: ')\r\n playerList.append(UnoPlayer(name,deck))\r\n # randomly assign who goes first\r\n currentPlayerNum = random.randrange(numPlayers)\r\n order = random.choice([1,-1])\r\n draw = 1\r\n # play the game\r\n while True:\r\n print('==================================================================')\r\n skip = 1 #reset skip after player has been skipped\r\n # print the game status\r\n print('---------------')\r\n for player in playerList:\r\n print(player)\r\n print('---------------')\r\n # take a turn\r\n cardAction = playerList[currentPlayerNum].take_turn(deck,pile, draw)\r\n draw = 1#reset draw after current player has drawn\r\n if cardAction == 'reverse':\r\n order *= -1\r\n elif cardAction == 'skip':\r\n skip = 2\r\n elif cardAction == 'drawtwo':\r\n draw = 2\r\n\r\n\r\n # check for a winner\r\n if playerList[currentPlayerNum].has_won():\r\n print(playerList[currentPlayerNum].get_name()+\" wins!\")\r\n print(\"Thanks for playing!\")\r\n break\r\n # go to the next player\r\n currentPlayerNum = (currentPlayerNum + order*skip) % numPlayers\r\n\r\nplay_uno(3)\r\n","sub_path":"uno.py","file_name":"uno.py","file_ext":"py","file_size_in_byte":8774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"623618138","text":"import configparser\nfrom datetime import datetime\nimport os\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, col\nfrom pyspark.sql.functions import year, month, dayofmonth, hour, weekofyear, date_format\nimport pyspark.sql.functions as F\nfrom pyspark.sql.types import (FloatType, DateType, StructType, StructField, StringType, LongType, \n IntegerType, ArrayType, BooleanType, DoubleType, DecimalType, TimestampType)\n\nconfig = configparser.ConfigParser()\nconfig.read('dl.cfg')\n\nos.environ['AWS_ACCESS_KEY_ID']=config[\"AWS\"]['AWS_ACCESS_KEY_ID']\nos.environ['AWS_SECRET_ACCESS_KEY']=config[\"AWS\"]['AWS_SECRET_ACCESS_KEY']\nmode = \"ignore\" #\"overwrite\"\n\ndef create_spark_session():\n spark = SparkSession \\\n .builder \\\n .config(\"spark.jars.packages\", \"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n return spark\n\n\ndef process_song_data(spark, input_data, output_data):\n # get filepath to song data file\n song_data = os.path.join(input_data, \"song_data\", \"*\", \"*\", \"*\", \"*.json\")\n song_table_path = os.path.join(output_data, \"song-table\")\n artist_table_path = os.path.join(output_data, \"artist-table\")\n # read song data file\n df = spark.read.json(song_data)\n\n # extract columns to create songs table\n songs_table = df.select(\"song_id\", \"title\", \"artist_id\", \"year\", \"duration\")\n \n # write songs table to parquet files partitioned by year and artist\n songs_table.write.partitionBy(\"year\", \"artist_id\").mode(mode).parquet(song_table_path)\n print(\"songs_table saved\")\n\n # extract columns to create artists table\n artists_table = df.select(F.col(\"artist_id\"), \n F.col(\"artist_name\").alias(\"name\"),\n F.col(\"artist_location\").alias(\"location\"),\n F.col(\"artist_latitude\").alias(\"latitude\"),\n F.col(\"artist_longitude\").alias(\"longitude\"))\n \n # write artists table to parquet files\n artists_table.write.mode(mode).parquet(artist_table_path)\n print(\"artists_table saved\")\n\ndef process_log_data(spark, input_data, output_data):\n # get filepath to log data file\n log_data = os.path.join(input_data, \"log_data/*.json\")\n song_data = os.path.join(input_data, \"song_data\", \"*\", \"*\", \"*\", \"*.json\")\n \n users_table_path = os.path.join(output_data, \"users-table\")\n time_table_path = os.path.join(output_data, \"time-table\")\n songsplay_table_path = os.path.join(output_data, \"songsplay-table\")\n \n # read log data file\n df = spark.read.json(log_data)\n \n # filter by actions for song plays\n df = df.filter(F.col('page') == 'NextSong')\n\n # extract columns for users table \n users_table = df.select(F.col(\"userId\").alias(\"user_id\"), \n F.col(\"firstName\").alias(\"first_name\"),\n F.col(\"lastName\").alias(\"last_name\"),\n F.col(\"gender\"),\n F.col(\"level\"))\n \n # write users table to parquet files\n users_table.write.mode(mode).parquet(users_table_path)\n print(\"users_table saved\")\n\n # create timestamp column from original timestamp column\n get_timestamp = F.udf(lambda x: datetime.fromtimestamp(x / 1000), TimestampType())\n df = df.withColumn(\"ts_timestamp\", get_timestamp(F.col(\"ts\")))\n \n # extract columns to create time table\n time_table = df.select(F.col(\"ts_timestamp\").alias(\"start_time\")).distinct()\n time_table = time_table.select(F.col(\"start_time\"), \n F.hour(F.col(\"start_time\")).alias(\"hour\"), \n F.dayofmonth(F.col(\"start_time\")).alias(\"day\"), \n F.weekofyear(F.col(\"start_time\")).alias(\"week\"), \n F.month(F.col(\"start_time\")).alias(\"month\"), \n F.year(F.col(\"start_time\")).alias(\"year\"),\n F.dayofweek(F.col(\"start_time\")).alias(\"weekday\"))\n \n # write time table to parquet files partitioned by year and month\n time_table.write.partitionBy(\"year\", \"month\").mode(mode).parquet(time_table_path)\n print(\"time_table saved\")\n # read in song data to use for songplays table\n song_df = spark.read.json(song_data)\n\n # extract columns from joined song and log datasets to create songplays table\n songplays_table = df.join(song_df, \n (df.artist == song_df.artist_name)&\\\n (df.length == song_df.duration)&\\\n (df.song == song_df.title),\n how=\"inner\")\n songplays_table = songplays_table.select(F.monotonically_increasing_id().alias(\"songplay_id\"), \n F.col(\"ts_timestamp\").alias(\"start_time\"), \n F.col(\"userId\").alias(\"user_id\"), \n F.col(\"level\"), \n F.col(\"song_id\"),\n F.col(\"artist_id\"), \n F.col(\"sessionID\").alias(\"session_id\"), \n F.col(\"location\"),\n F.col(\"userAgent\").alias(\"user_agent\"),\n F.month(F.col(\"ts_timestamp\")).alias(\"month\"),\n F.year(F.col(\"ts_timestamp\")).alias(\"year\"))\n # Missing drop duplicates\n\n # write songplays table to parquet files partitioned by year and month\n songplays_table.write.partitionBy(\"year\", \"month\").mode(mode).parquet(songsplay_table_path)\n print(\"songplays_table saved\")\n\n\ndef main():\n spark = create_spark_session()\n selected_input_data = \"local\" #or \"s3\"\n if selected_input_data==\"local\":\n input_data = \"./data\"\n elif selected_input_data==\"s3\":\n input_data = \"s3a://udacity-dend\"\n else:\n print(\"Not valid input data selected\")\n output_data = \"s3a://udacity-de-nd\"\n \n process_song_data(spark, local_data, output_data) \n process_log_data(spark, local_data, output_data)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Project_4/home/etl.py","file_name":"etl.py","file_ext":"py","file_size_in_byte":6307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"29616061","text":"# coding: utf-8\nimport numpy as np\nfrom cv2 import cv2\nimport matplotlib.pyplot as plt\n\nimg_rgb = cv2.imread(r'pictures\\bounding.png')\nimg_rgb2 = img_rgb.copy()\nimg_rgb3 = img_rgb.copy()\nimg = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)\nret, thresh = cv2.threshold(img, 127, 255, 0)\n\ncontours, hierarchy = cv2.findContours(\n thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n\ncnt = contours[0]\n\nx, y, w, h = cv2.boundingRect(cnt)\naspect_ratio = float(w)/h\nprint('Aspect_ratio:', aspect_ratio)\n# Aspect Ratio is the ratio of width to height of bounding rect of the object.\n\narea = cv2.contourArea(cnt)\n\nx, y, w, h = cv2.boundingRect(cnt)\nrect_area = w*h\nextent = float(area)/rect_area\nprint('Extent:', aspect_ratio)\n# Extent is the ratio of contour area to bounding rectangle area.\n\nhull = cv2.convexHull(cnt)\nhull_area = cv2.contourArea(hull)\nsolidity = float(area)/hull_area\nprint('Solidity:', aspect_ratio)\n# Solidity is the ratio of contour area to its convex hull area.\n\nequi_diameter = np.sqrt(4*area/np.pi)\nprint('Equivalent_diameter:', aspect_ratio)\n# Equivalent Diameter is the diameter of the circle whose area is same as the contour area.\n\n(x, y), (MA, ma), angle = cv2.fitEllipse(cnt)\nprint('x:', x, 'y:', y, '\\n', 'MA:', MA, 'ma:', ma, '\\n', 'angle:', angle)\n# Orientation is the angle at which object is directed. Above method also gives the Major Axis and Minor Axis lengths.\n\nmask = np.zeros(img.shape, np.uint8)\ncv2.drawContours(mask, [cnt], 0, 255, -1)\npixelpoints = np.transpose(np.nonzero(mask)) # using Numpy functions\n# pixelpoints = cv2.findNonZero(mask) # using OpenCV function\n# Numpy gives coordinates in (row, column) format, while OpenCV gives coordinates in (x,y) format. So basically the answers will be interchanged. row = x and column = y.\n\nmin_val, max_val, min_loc, max_loc = cv2.minMaxLoc(img, mask=mask)\nprint(min_val, max_val, min_loc, max_loc)\n# Maximum Value, Minimum Value and their locations\n\nmean_val = cv2.mean(img, mask=mask)\n# Find the average color of an object. Or it can be average intensity of the object in grayscale mode. Use the same mask to do it.\n\nleftmost = tuple(cnt[cnt[:, :, 0].argmin()][0])\nrightmost = tuple(cnt[cnt[:, :, 0].argmax()][0])\ntopmost = tuple(cnt[cnt[:, :, 1].argmin()][0])\nbottommost = tuple(cnt[cnt[:, :, 1].argmax()][0])\nprint(leftmost, rightmost, topmost, bottommost)\n# Extreme Points means topmost, bottommost, rightmost and leftmost points of the object.\n","sub_path":"4.9.3-contours_properties.py","file_name":"4.9.3-contours_properties.py","file_ext":"py","file_size_in_byte":2432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"242686955","text":"\"\"\"Imex Tools.\n# *- coding: utf8 -*-\n# Copyright (c) 2019 Hygor Costa\n#\n# This file is part of Py_IMEX.\n#\n#\n# You should have received a copy of the GNU General Public License\n# along with HUM. If not, see .\n#\n# Created: Jul 2019\n# Author: Hygor Costa\n# \"\"\"\nfrom collections import namedtuple\n\ndef cmgfile(basename):\n \"\"\"\n A simple wrapper for retrieving CMG file extensions\n given the basename.\n :param basename:\n :return:\n \"\"\"\n # if sufix:\n # basename = file.parent / f'{file.stem}_{sufix:03d}'\n # else:\n # current_time = datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n # basename = file.parent / f'{file.stem}_{current_time}'\n Extension = namedtuple(\n \"Extension\",\n \"dat out rwd rwo log sr3 schedule\",\n )\n basename = Extension(\n basename.with_suffix(\".dat\"),\n basename.with_suffix(\".out\"),\n basename.with_suffix(\".rwd\"),\n basename.with_suffix(\".rwo\"),\n basename.with_suffix(\".log\"),\n basename.with_suffix(\".sr3\"),\n basename.parent / f'{basename.stem}_SCHEDULE.inc',\n )\n return basename\n","sub_path":"res_pymex/imex_tools.py","file_name":"imex_tools.py","file_ext":"py","file_size_in_byte":1137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"342802634","text":"import pymysql\n\ndef mysql_test():\n db=pymysql.connect(\"localhost\",\"root\",\"root\",\"yctcloud\")\n cursor=db.cursor()\n cursor.execute(\"select version()\")\n data=cursor.fetchone()\n print(\"database version:%s\"%data)\n db.close()\n return\n\nif __name__ == '__main__':\n mysql_test()","sub_path":"scripts/dblink/mysql_test.py","file_name":"mysql_test.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"627478373","text":"#!/usr/bin/python\n\n#Declaration of libraries \nimport spidev\nimport time\nimport datetime\nimport os\nimport RPi.GPIO as GPIO\n\n#GPIO pins setup\nGPIO.setmode(GPIO.BCM)\nreset =17\nfreq =27\nstop =22\ndisplay=23\n\n#setup for interrupt switches\nGPIO.setup(reset, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(freq, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(stop, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(display, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n# Open SPI bus\nspi = spidev.SpiDev()\nspi.open(0,0)\nspi.max_speed_hz=1000000\n\n# Define sensor channels\nlight_channel = 0\ntemp_channel = 1\npot_channel= 2\n\n","sub_path":"Prac4_code.py","file_name":"Prac4_code.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"300917507","text":"\n\"\"\"\n 测试文件 用于对比预测文件与标准文件的出错率\n\"\"\"\nimport numpy as np\ndataAcu = np.loadtxt(\n \"G:\\python 资源\\python project\\绿色计算\\客户购买房屋保险预测\\input\\\\acu.csv\", delimiter=\",\")\n\ndataPre = np.loadtxt(\n \"G:\\python 资源\\python project\\绿色计算\\客户购买房屋保险预测\\input\\\\prediction.csv\", delimiter=\",\")\ndataLen = len(dataAcu)\nerror = 0\nfor i, j in zip(dataAcu, dataPre):\n if not i == j:\n error += 1\n\nerrorRate = float(error / dataLen)\nprint(\"errorRate:\", errorRate)\n","sub_path":"绿色计算/客户购买房屋保险预测/getacu.py","file_name":"getacu.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"48137595","text":"import logging\nfrom web.conf.global_conf import *\nfrom django.template.loader import get_template\nfrom django.template import Context, RequestContext\nfrom django.http import HttpResponse, HttpResponseRedirect, HttpResponseForbidden, HttpResponseNotFound\n\nclass select_member_visit_reports():\n\tlogger = logging.getLogger('web')\n\tlogger_access = logging.getLogger('access')\n\n\tdef __init__(self, request_session, request_params):\n\t\tself.session = request_session\n\t\tself.params = request_params\n\n\t\tself.auth_dict = self.session['auth']\n\t\tauth = self.auth_dict['sim']['write']\n\t\n\t\tif auth == 'no':\n\t\t\tself.tmpl = get_template('select_member_visit_reports_admin.html')\n\t\telif auth == 'yes':\n\t\t\tself.tmpl = get_template('select_member_visit_reports.html')\n\n\tdef run(self):\n\t\tauth = self.auth_dict['sim']['view']\n\n\t\tif auth != 'no':\n\t\t\tname = self.session['name']\n\t\t\tmember_id = self.session['member_id']\n\t\t\tteam_id = self.session['team_id']\n\t\t\tteam_name = self.session['team_name']\n\t\t\tteam_type = self.session['team_type'] \n\t\t\n\t\t\tif 'group_id' in self.session:\n\t\t\t\tgroup_id = self.session['group_id']\n\t\t\t\tgroup_name = self.session['group_name']\n\n\t\t\tmission_id = self.session['mission_id']\n\t\t\tmission_name = self.session['mission_name']\n\t\t\tusername = self.session['username']\n\n\t\t\tif 'group_id' in self.session:\n\t\t\t\tc = Context({'name' : name, 'member_id':member_id, 'team_id':team_id, 'team_name':team_name, 'team_type': team_type, 'group_id' : group_id, 'group_name' : group_name, 'mission_id': mission_id, 'mission_name': mission_name, 'auth' : auth, 'export_auth': self.auth_dict['sim']['export'], 'reset_auth': self.auth_dict['sim']['reset'], 'username' : username})\n\t\t\telse:\t\n\t\t\t\tc = Context({'name' : name, 'member_id':member_id, 'team_id':team_id, 'team_name':team_name, 'team_type': team_type, 'mission_id': mission_id, 'mission_name': mission_name, 'auth' : auth, 'export_auth': self.auth_dict['sim']['export'], 'reset_auth': self.auth_dict['sim']['reset'], 'username' : username})\n\t\t\t\n\t\t\ttmpl_str = self.tmpl.render(c)\n\n\t\t\tself.logger_access.info(name + \"(\" + str(member_id) +\") >> select_member_visit_reports\")\n\t\t\treturn HttpResponse(tmpl_str)\n\t\telse:\n\t\t\tself.tmpl = get_template('NO_AUTH.html')\n\t\t\tc = Context()\n\t\t\ttmpl_str = self.tmpl.render(c)\n\t\t\treturn HttpResponse(tmpl_str)\n\n","sub_path":"web/htdocs/select_member_visit_reports.py","file_name":"select_member_visit_reports.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"515189932","text":"#!/usr/bin/env python\r\n#-*- coding: utf-8 -*-\r\n# redis工厂,维护redis连接\r\n\r\nimport sys\r\nsys.path.append('../')\r\nimport redis\r\nfrom conf import redis_config\r\n\r\nclass Redis(object):\r\n\r\n __pool = {}\r\n\r\n @classmethod\r\n def init(cls):\r\n if not cls.__pool:\r\n for key,configs in redis_config.items():\r\n connections = []\r\n for config in configs:\r\n host = config.get('host')\r\n password = config.get('password')\r\n db = config.get('db')\r\n port = config.get('port')\r\n connection = redis.ConnectionPool(host=host,\r\n password=password, db=db, port=port, decode_responses=True)\r\n connections.append(connection)\r\n cls.__pool[key] = connections\r\n @classmethod\r\n def get_pool(cls, mod='redis'):\r\n if not cls.__pool:\r\n cls.init()\r\n return cls.__pool.get(mod)\r\n\r\n\r\n @classmethod\r\n def conn(cls, hash_str, mod='redis'):\r\n connections = cls.get_pool(mod)\r\n connection = connections[cls.hashPool(connections.size(), hash_str)]\r\n return redis.Redis(connection_pool=connection)\r\n\r\n def hashPool(self, pool_num, hash_str='redis'):\r\n hash_num = 0\r\n for i in hash_str:\r\n hash_num += ord(i)\r\n return hash_num%pool_num\r\n\r\nif (__name__ == '__main__'):\r\n conn = Redis.conn()\r\n conn.set('a', 123)\r\n a = conn.get('a')\r\n conn.close()","sub_path":"common/Redis.py","file_name":"Redis.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"62519465","text":"import pandas as pd\nimport random\nimport os\nimport sys\n\ndef main(argv):\n infile = os.path.abspath(argv[1])\n outdir = os.path.abspath(argv[2])\n\n # script_dir = os.path.dirname(__file__)\n # proj_dir = os.path.abspath(os.path.join(script_dir, '../..'))\n # total_train_path = os.path.join(proj_dir, 'data/raw/train.csv')\n # train_path = os.path.join(proj_dir, 'data/interim/train.csv')\n # cv_path = os.path.join(proj_dir, 'data/interim/cv.csv')\n\n # Stratify raw training data in train and CV datasets\n total_train = pd.read_csv(infile)\n\n # Calculate number of observations to keep in each dataset\n n = len(total_train)\n n_cv = int(.25 * n)\n n_train = n - n_cv\n random.seed(666) # set random seed\n cv_indices = random.sample(total_train.index, n_cv)\n cv = total_train.ix[cv_indices]\n train = total_train.drop(cv_indices)\n\n # Write out\n cv.to_csv(os.path.join(outdir, 'cv.csv'), index=False)\n train.to_csv(os.path.join(outdir, 'train.csv'), index=False)\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"src/data/stratify.py","file_name":"stratify.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"516467493","text":"# The first solution\ndef unique_in_order(iterable):\n ls = []\n prev = ''\n for char in iterable:\n if char != prev:\n ls.append(char)\n prev = char\n return ls\n \n# The second solution \ndef unique_in_order(iterable):\n ls = []\n if len(iterable) == 0:\n return ls\n else:\n ls.append(iterable[0])\n for i in range(1, len(iterable)):\n if iterable[i] != iterable[i-1]:\n ls.append(iterable[i])\n return ls\n","sub_path":"unique_in_order.py","file_name":"unique_in_order.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"574108464","text":"from django.urls import path\r\nfrom . import views\r\n\r\n\"\"\"\r\n Url pattern.\r\n Mainly use \"path\": path('path', view.to.connect)\r\n \r\n url can also be used (see on documentation)\r\n \r\n this class is included in the main urls file (OPIA/urls.py)\r\n\"\"\"\r\n\r\nurlpatterns = [\r\n path('home', views.home),\r\n\r\n path('year', views.year),\r\n path('sprint', views.sprint),\r\n path('wiki', views.wiki),\r\n path('todo', views.todo),\r\n path('article', views.article),\r\n path('articl/create', views.article_create),\r\n path('articledef/', views.articledef),\r\n path('dashboard', views.dashboard),\r\n path('mgmt', views.mgmt),\r\n path('sprint/def/', views.sprint_def),\r\n path('rapport//', views.rapport_def),\r\n path('rapport/create//', views.rapport_create),\r\n\r\n\r\n\r\n\r\n\r\n path('dataov', views.dataoverview),\r\n\r\n #use this for each project\r\n #only for tests purpose\r\n path('projecttest//', views.project_testview),\r\n path('projecttest//', views.project_testview),\r\n path('redirect', views.view_redirected),\r\n path('date', views.date_actuelle),\r\n]","sub_path":"labtesting/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"171779758","text":"import cherrypy\nimport json\nimport services.database as db\nfrom mako.template import Template\nfrom mako.lookup import TemplateLookup\n\nlookup = TemplateLookup(directories=[\"\"]) \n \n \nclass WebManager(object):\n\t\"\"\"\n\tExposes web services\n\t\"\"\"\n\t@cherrypy.expose\n\tdef index(self):\n\t\t\"\"\"\n\t\tExposes the service at localhost:8080/\n\t\t\"\"\"\n\t\treturn Template(filename=\"View/index.html\", lookup=lookup).render()\n\n\t@cherrypy.expose\n\tdef activityInCity(self):\n\t\t\"\"\"\n\t\tExposes the service at localhost:8080/activityInCity\n\t\t\"\"\"\n\t\treturn Template(filename=\"View/activityInCity.html\", lookup=lookup).render()\n\n\t@cherrypy.expose\n\tdef activityWithCity(self):\n\t\t\"\"\"\n\t\tExposes the service at localhost:8080/activityInCity\n\t\t\"\"\"\n\t\treturn Template(filename=\"View/activityWithCity.html\", lookup=lookup).render()\n\n\t@cherrypy.expose\n\tdef show_all(self,table):\n\t\t\"\"\"\n\t\tExposes the service at localhost:8080/show_all/table\n\t\t\"\"\"\n\t\tview = Template(filename=\"View/template.html\",lookup=lookup)\n\t\tdatabase = db.Database(\"db/database.db\")\n\t\tres = database.selectAll(table)\n\t\treturn view.render(\n\t\t\trows = res\n\t\t)\n\n\t@cherrypy.expose()\n\tdef requestactivityWithCity(self, commune, activite):\n\t\t\"\"\"\n\t\tExposes the service at localhost:8080/requestActivityCity\n\t\t\"\"\"\n\t\tview = Template(filename=\"View/template.html\",lookup=lookup)\n\t\tdatabase = db.Database(\"db/database.db\")\n\t\tres = database.requestActivityWithCity(commune,activite)\n\t\treturn view.render(\n\t\t\trows = res\n\t\t)\t\t\n\n\n\t@cherrypy.expose\n\tdef requestactivityInCity(self, commune):\n\t\t\"\"\"\n\t\tExposes the service at localhost:8080/requestactivityInCity\n\t\t\"\"\"\n\n\t\tview = Template(filename=\"View/template.html\",lookup=lookup)\n\t\tdatabase = db.Database(\"db/database.db\")\n\t\tres = database.requestActivityinACity(commune)\n\t\treturn view.render(\n\t\t\trows = res\n\t\t)\n\ncherrypy.quickstart(WebManager()) ","sub_path":"NEWV2/cherrypy_server.py","file_name":"cherrypy_server.py","file_ext":"py","file_size_in_byte":1802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473859262","text":"# 基础参数配置\nclass conf:\n start_date = '2010-01-01'\n end_date='2017-01-20'\n # split_date 之前的数据用于训练,之后的数据用作效果评估\n split_date = '2015-01-01'\n # D.instruments: https://bigquant.com/docs/data_instruments.html\n instruments = D.instruments(start_date, end_date)\n\n # 机器学习目标标注函数\n # 如下标注函数等价于 max(min((持有期间的收益 * 100), -20), 20) + 20 (后面的M.fast_auto_labeler会做取整操作)\n # 说明:max/min这里将标注分数限定在区间[-20, 20],+20将分数变为非负数 (StockRanker要求标注分数非负整数)\n label_expr = ['return * 100', 'where(label > {0}, {0}, where(label < -{0}, -{0}, label)) + {0}'.format(20)]\n # 持有天数,用于计算label_expr中的return值(收益)\n hold_days = 30\n\n # 特征 https://bigquant.com/docs/data_features.html,你可以通过表达式构造任何特征\n features = [\n 'market_cap_0', # 总市值\n ]\n\n# 给数据做标注:给每一行数据(样本)打分,一般分数越高表示越好\nm1 = M.fast_auto_labeler.v5(\n instruments=conf.instruments, start_date=conf.start_date, end_date=conf.end_date,\n label_expr=conf.label_expr, hold_days=conf.hold_days,\n benchmark='000300.SHA', sell_at='open', buy_at='open')\n# 计算特征数据\nm2 = M.general_feature_extractor.v5(\n instruments=conf.instruments, start_date=conf.start_date, end_date=conf.end_date,\n features=conf.features)\n# 数据预处理:缺失数据处理,数据规范化,T.get_stock_ranker_default_transforms为StockRanker模型做数据预处理\nm3 = M.transform.v2(\n data=m2.data, transforms=T.get_stock_ranker_default_transforms(),\n drop_null=True, astype='int32', except_columns=['date', 'instrument'],\n clip_lower=0, clip_upper=200000000)\n# 合并标注和特征数据\nm4 = M.join.v2(data1=m1.data, data2=m3.data, on=['date', 'instrument'], sort=True)\n\n# 训练数据集\nm5_training = M.filter.v2(data=m4.data, expr='date < \"%s\"' % conf.split_date)\n# 评估数据集\nm5_evaluation = M.filter.v2(data=m4.data, expr='\"%s\" <= date' % conf.split_date)\n# StockRanker机器学习训练\nm6 = M.stock_ranker_train.v2(training_ds=m5_training.data, features=conf.features)\n# 对评估集做预测\nm7 = M.stock_ranker_predict.v2(model_id=m6.model_id, data=m5_evaluation.data)\n\n\n## 量化回测 https://bigquant.com/docs/strategy_backtest.html\n# 回测引擎:初始化函数,只执行一次\ndef initialize(context):\n # 系统已经设置了默认的交易手续费和滑点,要修改手续费可使用如下函数\n context.set_commission(PerOrder(buy_cost=0.0003, sell_cost=0.0013, min_cost=5))\n # 预测数据,通过options传入进来,使用 read_df 函数,加载到内存 (DataFrame)\n context.ranker_prediction = context.options['ranker_prediction'].read_df()\n # 设置买入的股票数量,这里买入预测股票列表排名靠前的5只\n stock_count = 5\n # 每只的股票的权重,如下的权重分配会使得靠前的股票分配多一点的资金,[0.339160, 0.213986, 0.169580, ..]\n context.stock_weights = T.norm([1 / math.log(i + 2) for i in range(0, stock_count)])\n # 设置每只股票占用的最大资金比例\n context.max_cash_per_instrument = 0.2\n\n# 回测引擎:每日数据处理函数,每天执行一次\ndef handle_data(context, data):\n # 按日期过滤得到今日的预测数据\n ranker_prediction = context.ranker_prediction[context.ranker_prediction.date == data.current_dt.strftime('%Y-%m-%d')]\n\n # 1. 资金分配\n # 平均持仓时间是hold_days,每日都将买入股票,每日预期使用 1/hold_days 的资金\n # 实际操作中,会存在一定的买入误差,所以在前hold_days天,等量使用资金;之后,尽量使用剩余资金(这里设置最多用等量的1.5倍)\n is_staging = context.trading_day_index < context.options['hold_days'] # 是否在建仓期间(前 hold_days 天)\n cash_avg = context.portfolio.portfolio_value / context.options['hold_days']\n cash_for_buy = min(context.portfolio.cash, (1 if is_staging else 1.5) * cash_avg)\n cash_for_sell = cash_avg - (context.portfolio.cash - cash_for_buy)\n positions = {e.symbol: p.amount * p.last_sale_price for e, p in context.perf_tracker.position_tracker.positions.items()}\n\n # 2. 生成卖出订单:hold_days天之后才开始卖出;对持仓的股票,按StockRanker预测的排序末位淘汰\n if not is_staging and cash_for_sell > 0:\n equities = {e.symbol: e for e, p in context.perf_tracker.position_tracker.positions.items()}\n instruments = list(reversed(list(ranker_prediction.instrument[ranker_prediction.instrument.apply(\n lambda x: x in equities and not context.has_unfinished_sell_order(equities[x]))])))\n # print('rank order for sell %s' % instruments)\n for instrument in instruments:\n context.order_target(context.symbol(instrument), 0)\n cash_for_sell -= positions[instrument]\n if cash_for_sell <= 0:\n break\n\n # 3. 生成买入订单:按StockRanker预测的排序,买入前面的stock_count只股票\n buy_cash_weights = context.stock_weights\n buy_instruments = list(ranker_prediction.instrument[:len(buy_cash_weights)])\n max_cash_per_instrument = context.portfolio.portfolio_value * context.max_cash_per_instrument\n for i, instrument in enumerate(buy_instruments):\n cash = cash_for_buy * buy_cash_weights[i]\n if cash > max_cash_per_instrument - positions.get(instrument, 0):\n # 确保股票持仓量不会超过每次股票最大的占用资金量\n cash = max_cash_per_instrument - positions.get(instrument, 0)\n if cash > 0:\n context.order_value(context.symbol(instrument), cash)\n\n# 调用回测引擎\nm8 = M.backtest.v5(\n instruments=m7.instruments,\n start_date=m7.start_date,\n end_date='2017-01-01',\n initialize=initialize,\n handle_data=handle_data,\n order_price_field_buy='open', # 表示 开盘 时买入\n order_price_field_sell='close', # 表示 收盘 前卖出\n capital_base=1000000, # 初始资金\n benchmark='000300.SHA', # 比较基准,不影响回测结果\n # 通过 options 参数传递预测数据和参数给回测引擎\n options={'ranker_prediction': m7.predictions, 'hold_days': conf.hold_days}\n)","sub_path":"src/choses/aichosen.py","file_name":"aichosen.py","file_ext":"py","file_size_in_byte":6472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"613185772","text":"import numpy as np\nimport mrcfile\nimport platform\nPLATFORM_NODE = platform.node()\nimport sys\nif PLATFORM_NODE == 'motel':\n sys.path.insert(0, '/home/sl767/PythonCode/SingleParticleAnalysis')\nelif PLATFORM_NODE == 'radon':\n sys.path.insert(0, '/home/zickert/SingleParticleAnalysis')\nelif 'lmb' in PLATFORM_NODE:\n sys.path.insert(0, '/lmb/home/schools1/SingleParticleAnalysis')\nelse:\n raise Exception\nfrom ClassFiles.relion_fixed_it import load_star\nfrom ClassFiles.AdversarialRegularizer import AdversarialRegulariser\nfrom ClassFiles.ut import irfft, rfft\nimport matplotlib.pyplot as plt\nimport os\nfrom ClassFiles.ut import cleanStarPath\nimport itertools\n#import subprocess as sp\nimport argparse\nfrom skimage.measure import compare_ssim as ssim\n\n#%%\n\n\nif False:\n parser = argparse.ArgumentParser(description='test AR gradient descent')\n parser.add_argument('--gpu', help='GPU to use', required=True)\n parser.add_argument('--positivity', help='AR trained with positivity?', required=True)\n parser.add_argument('--s', help='Sobolev cst', required=True)\n args = vars(parser.parse_args())\n os.environ['CUDA_VISIBLE_DEVICES'] = args['gpu']#'2'\n POS_AR = args['positivity']#'trained_on_non_pos'\n SOBOLEV_CST = args['s']\n PLOT = False\nelse:\n POS_AR = '1'\n SOBOLEV_CST = '0.5'\n PLOT = False\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n\n#%%\n\nBASE_PATH = '/mnt/datahd/zickert/'\nREGULARIZATION_TIK = 1e-3 # For initialization\nPRECOND = False\nREPORT = 10\nSAVE_RECO_TO_DISK = False\nEVAL_METRIC = 'L2_and_SSIM'# 'masked_L2' # 'masked_FSC'\nNOISE_LEVEL = '01'\nWIN_SIZE = 7 # for SSIM\nREGULARIZATION_TIK_GD = 1e6 # During gradient descent\n\n\n#%%\n\nAR_PATH = '/mnt/datahd/zickert/SPA/Saves/SimDataPaper/Adversarial_Regulariser/no_fancy_data_aug_lr_5e-05_s_{}_pos_{}'.format(SOBOLEV_CST, POS_AR)\nregularizer = AdversarialRegulariser(AR_PATH)\n\nPOS_AR = ('1' == POS_AR)\n \nprint('Global parameters:') \nprint(SOBOLEV_CST, REGULARIZATION_TIK, PRECOND, REPORT, POS_AR, EVAL_METRIC, NOISE_LEVEL)\nprint('################################')\n#%%\n#def runCommand(cmd_string, file_path=None):\n# if file_path is None:\n# sp.call(cmd_string.split(' '))\n# else:\n# file = open(file_path, 'w')\n# sp.call(cmd_string.split(' '), stdout=file)\n# file.close()\n\n\n#def fscPointFiveCrossing(x, GT_path):\n# raise Exception\n# TEMP_reco_path = BASE_PATH + 'TMP_recos/tmp_reco.mrc'\n# TEMP_reco_masked_path = BASE_PATH + 'TMP_recos/tmp_reco_masked.mrc'\n# TEMP_mask_path = BASE_PATH + 'Test_Learned_Priors/Data/SimDataPaper/Data_001_10k/train/masks/4A2B/mask.mrc'\n# TEMP_mask_log_path = '/beegfs3/zickert/TMP_recos/mask_log.txt'\n# \n# TEMP_FSC_PATH = '/beegfs3/zickert/TMP_recos/tmp_fsc.star'\n#\n# with mrcfile.new(TEMP_reco_path, overwrite=True) as mrc:\n# mrc.set_data(x.astype(np.float32))\n# \n# MULT_COMMAND = 'relion_image_handler --i {} --o {} --multiply {}'.format(TEMP_reco_path, TEMP_reco_masked_path, TEMP_mask_path) \n# runCommand(MULT_COMMAND, TEMP_mask_log_path)\n#\n# FSC_COMMAND = 'relion_image_handler --i {} --fsc {} --angpix 1.5'.format(TEMP_reco_masked_path, GT_path)\n# runCommand(FSC_COMMAND, TEMP_FSC_PATH)\n# \n# FSC_dict = load_star(TEMP_FSC_PATH)\n# RES = np.array(FSC_dict['fsc']['rlnAngstromResolution'], dtype='float32')\n# FSC = np.array(FSC_dict['fsc']['rlnFourierShellCorrelation'], dtype='float32')\n#\n# cross_idx = np.argmax(FSC <= 0.5)\n# cross_res = RES[cross_idx]\n# return cross_res\n\n#\n#def masked_L2(x, GT, PDB):\n# # Make sure Masks exist and paths are correct\n# raise Exception\n# TEMP_reco_path = BASE_PATH + 'TMP_recos/tmp_reco.mrc'\n# TEMP_reco_masked_path = BASE_PATH + 'TMP_recos/tmp_reco_masked.mrc'\n# TEMP_mask_path = BASE_PATH + 'Masks/{p}_mask.mrc'.format(p=PDB)\n# TEMP_mask_log_path = BASE_PATH + 'TMP_recos/mask_log.txt'\n# \n# with mrcfile.new(TEMP_reco_path, overwrite=True) as mrc:\n# mrc.set_data(x.astype(np.float32))\n# \n# MULT_COMMAND = 'relion_image_handler --i {} --o {} --multiply {}'.format(TEMP_reco_path, TEMP_reco_masked_path, TEMP_mask_path) \n# runCommand(MULT_COMMAND, TEMP_mask_log_path)\n#\n# with mrcfile.open(TEMP_reco_masked_path) as mrc:\n# x_masked = mrc.data.copy()\n# \n# return np.sqrt(((x_masked - GT) ** 2).sum())\n\n\ndef L2(x, GT): \n return np.sqrt(((x - GT) ** 2).sum())\n\nREGULARIZATION_TIK\ndef vis(data, fourier=True, SCALE=100):\n if fourier:\n data = irfft(data)\n plt.imshow(SCALE*data.squeeze()[..., 45])\n\n\ndef locate_multmap(PDB, noise):\n gt_path = BASE_PATH + 'TrainData/SimDataPaper/Data_0{n}_10k/train/mult_maps/{p}/{p}_mult0{n}.mrc'\n gt_path = gt_path.format(n=noise, p=PDB)\n return gt_path\n\n\ndef locate_star(PDB, noise, iteration):\n star_path = BASE_PATH + 'TestData/ClassicalRelionData/Data_0{n}_10k/{p}'\n star_path += '/{p}_mult0{n}_it{it}_half1_class001_external_reconstruct.star'\n star_path = star_path.format(p=PDB, n=noise, it=iteration)\n return star_path\n\n#%%\niterable = itertools.product(['4BB9'],#['4MU9', '4AIL', '4BTF', '4A2B', '4BB9', '4M82', '4MU9'],\n ['001', '005'], ['tik'], ['auto'],#5e4, 1e5],\n [POS_AR], [100], [1e-3])\nfor PDB_ID, IT, INI_POINT, AR_REG_TYPE, POSITIVITY, NUM_GRAD_STEPS, STEP_SIZE_NOMINAL in iterable: \n\n star_path = locate_star(PDB_ID, NOISE_LEVEL, IT)\n star_file = load_star(star_path)\n\n gt_path = locate_multmap(PDB_ID, NOISE_LEVEL) \n with mrcfile.open(gt_path) as mrc:\n gt = mrc.data.copy()\n\n ### Is this needed?\n real_data_path = cleanStarPath(star_path, star_file['external_reconstruct_general']['rlnExtReconsDataReal'])\n imag_data_path = cleanStarPath(star_path, star_file['external_reconstruct_general']['rlnExtReconsDataImag'])\n weight_data_path = cleanStarPath(star_path, star_file['external_reconstruct_general']['rlnExtReconsWeight'])\n target_path = cleanStarPath(star_path, star_file['external_reconstruct_general']['rlnExtReconsResult'])\n \n with mrcfile.open(real_data_path) as mrc:\n data_real = mrc.data.copy()\n with mrcfile.open(imag_data_path) as mrc:\n data_im = mrc.data.copy()\n with mrcfile.open(weight_data_path) as mrc:\n kernel = mrc.data.copy()\n with mrcfile.open(target_path) as mrc:\n classical_reco = mrc.data.copy()\n \n complex_data = data_real + 1j * data_im\n \n tikhonov_kernel = kernel + REGULARIZATION_TIK_GD\n# tikhonov_kernel_init = kernel + REGULARIZATION_TIK\n\n \n if PRECOND:\n precond = np.abs(np.divide(1, tikhonov_kernel))\n precond /= precond.max()\n precond *= 30\n else:\n precond = 1.0\n\n \n # The scales produce gradients of order 1\n ADVERSARIAL_SCALE = 1 *(96 ** (-0.5))\n DATA_SCALE = 1 / (10 * 96 ** 3)\n \n if INI_POINT == 'tik':\n init = np.divide(complex_data, tikhonov_kernel)\n elif INI_POINT == 'classical':\n init = classical_reco.copy()\n init = rfft(init)\n if POSITIVITY: \n init = np.fft.rfftn(np.maximum(0, np.fft.irfftn(init)))\n reco = init.copy()\n\n print('####################')\n print(PDB_ID, NOISE_LEVEL, IT, INI_POINT, AR_REG_TYPE, POSITIVITY, NUM_GRAD_STEPS, STEP_SIZE_NOMINAL)\n print('####################')\n# if EVAL_METRIC == 'masked_FSC':\n# print('INIT FSC 0.5 crossing: ', fscPointFiveCrossing(irfft(init), gt_path))\n if EVAL_METRIC == 'masked_L2':\n print('INIT L2 (masked): ', masked_L2(irfft(init), gt))\n elif EVAL_METRIC == 'L2':\n print('INIT L2: ', L2(irfft(init), gt))\n elif EVAL_METRIC == 'L2_and_SSIM':\n print('INIT L2: ', L2(irfft(init), gt), '. INIT SSIM: ', ssim(irfft(init), gt, win_size=WIN_SIZE)) \n \n if PLOT:\n plt.figure(0, figsize=(10, 3))\n plt.subplot(121)\n vis(gt, fourier=False)\n plt.colorbar()\n plt.subplot(122)\n vis(init)\n plt.colorbar()\n plt.show()\n \n \n if INI_POINT == 'classical' or AR_REG_TYPE != 0 or POSITIVITY:\n # Compute AR Reg param by assuming gt is critical point of objective\n if AR_REG_TYPE == 'auto':\n gradient_gt = regularizer.evaluate(rfft(gt))\n g1_gt = gradient_gt * ADVERSARIAL_SCALE\n g1_gt_norm = np.sqrt((np.abs(g1_gt) ** 2).sum())\n g2_gt = DATA_SCALE * (np.multiply(rfft(gt), tikhonov_kernel) - complex_data)\n g2_gt_norm = np.sqrt((np.abs(g2_gt) ** 2).sum())\n ADVERSARIAL_REGULARIZATION = g2_gt_norm / g1_gt_norm\n print('Auto computed REG_PAR: ', ADVERSARIAL_REGULARIZATION)\n else:\n ADVERSARIAL_REGULARIZATION = AR_REG_TYPE\n \n # Take Gradient steps\n for k in range(NUM_GRAD_STEPS):\n gradient = regularizer.evaluate(reco)\n STEP_SIZE = STEP_SIZE_NOMINAL * 1 / np.sqrt(1 + k / 50)\n g1 = ADVERSARIAL_REGULARIZATION * gradient * ADVERSARIAL_SCALE\n g2 = DATA_SCALE * (np.multiply(reco, tikhonov_kernel) - complex_data)\n \n g = g1 + g2\n reco_o = reco\n reco = reco - STEP_SIZE * precond * g\n \n if POSITIVITY: \n reco = np.fft.rfftn(np.maximum(0, np.fft.irfftn(reco)))\n \n if k % REPORT == 0:\n if EVAL_METRIC == 'masked_L2':\n print('L2 (masked): ', masked_L2(irfft(reco), gt))\n elif EVAL_METRIC == 'L2':\n print('L2: ', L2(irfft(reco), gt))\n elif EVAL_METRIC == 'L2_and_SSIM':\n print('L2: ', L2(irfft(reco), gt), '. SSIM: ', ssim(irfft(reco), gt, win_size=WIN_SIZE)) \n if PLOT:\n plt.figure(k+1, figsize=(20, 3))\n plt.subplot(151)\n vis(reco)\n plt.colorbar()\n plt.subplot(152)\n vis(precond * g1)\n plt.colorbar()\n plt.subplot(153)\n vis(precond * g2)\n plt.colorbar()\n plt.subplot(154)\n vis(precond * g)\n plt.colorbar()\n plt.subplot(155)\n vis(reco-init)\n plt.colorbar()\n plt.show()\n\n# if SAVE_RECO_TO_DISK:\n# raise NotImplementedError\n# reco_real = irfft(reco)\n# AR_reco_path = BASE_PATH + 'TMP_recos/reco_it{}_reg{}_pos{}_ini{}_stepLen{}_Nsteps{}.mrc'.format(IT, ADVERSARIAL_REGULARIZATION, POSITIVITY, INI_POINT, STEP_SIZE_NOMINAL, NUM_GRAD_STEPS) \n# with mrcfile.new(AR_reco_path, overwrite=True) as mrc:\n# mrc.set_data(reco_real.astype(np.float32))\n# mrc.voxel_size = 1.5\n","sub_path":"LowPassIni/test_AR_iterations.py","file_name":"test_AR_iterations.py","file_ext":"py","file_size_in_byte":10802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"302148873","text":"from random import randint\n\n\n#Função Aposta gera uma aposta seguindo as probabilidades do site\ndef aposta(): \n valor=(randint(0,54))\n if 1<=valor<=26:\n return 'g' \n if 27<=valor<=43:\n return 'v'\n if 44<=valor<=54:\n return 'b'\n if valor == 0 :\n return 'GG'\n\n#Valores de inicio\nVI = 1800.0 #valor inicial do apostador\nvab = 10.0 #valor inicial de aposta da cor vermelha\nvaa=10 #valor inicial de aposta da cor azul \napst=5.0 #multiplicado de ganho para a cor\nmulti = 1.3 #multiplicador caso o jogador perda a rodada\nvmax=0 #armazena a aposta máxima\n\n#rodadas de aposta:\nfor x in range (10):\n for x in range(1000): \n apost=aposta()\n #aposta azul\n if vaa>vmax:\n vmax=vaa\n if apost == 'b': \n saldoa = VI + (vaa *apst)\n vaa= 10\n else:\n saldoa = VI - vaa\n vaa = vaa*multi\n #aposta vermelha\n if vab>vmax:\n vmax=vab\n if apost == 'v':\n saldov = VI + (vab *3.0)\n vab= 10\n else:\n saldov = VI - vab\n vab = vab*1.7\n \n#resultados:\n \nif saldoa>VI:\n print(\"lucro\")\nelse:\n print(\"prejuíso\")\n \nprint(saldoa, vmax)\nprint(saldov, vmax) \n ","sub_path":"apostas.py","file_name":"apostas.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"445794448","text":"from django.shortcuts import render \nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom .models import vendor,stock,apply_for_purchase,purchase_commitee\nfrom cgi import escape\nfrom io import BytesIO\nfrom applications.globals.models import ExtraInfo\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q\n\nfrom django.shortcuts import get_object_or_404, render\nfrom django.template.loader import get_template\nfrom xhtml2pdf import pisa\n\n@login_required\ndef apply_purchase(request):\n\n # \n # name=ExtraInfo.objects.get(user=user) \n \n # user = request.user\n # user = User.objects.get(id=1).extrainfo\n user=request.user.extrainfo\n # user=ExtraInfo.objects.get(id=user)\n \n if request.method == 'POST':\n '''if \"submit\" in request.POST:'''\n item_name=request.POST.get('item_name')\n quantity=request.POST.get('quantity')\n expected_cost=int(request.POST.get('expected_cost'))\n \n if expected_cost >=25000 and expected_cost <= 250000 :\n local_comm_mem1_id=request.POST.get('local_comm_mem1_id')\n local_comm_mem2_id=request.POST.get('local_comm_mem2_id')\n local_comm_mem3_id=request.POST.get('local_comm_mem3_id')\n\n nature_of_item1= 1 if request.POST.get('nature_of_item1') == 'on' else 0\n nature_of_item2= 1 if request.POST.get('nature_of_item2') == 'on' else 0\n \n # extra = ExtraInfo.objects.all()\n # extraInfo = ExtraInfo.objects.get(id=inspecting_authority_id)\n \n purpose=request.POST.get('purpose')\n # budgetary_head_id=request.POST.get('budgetary_head_id') \n # inspecting_authority_id=request.POST.get('inspecting_authority_id')\n expected_purchase_date=request.POST.get('expected_purchase_date')\n # print(expected_purchase_date+\"...........................\")\n \n # xyz=apply_for_purchase(indentor_name=name,)\n # xyz.save()\n\n\n \n a = apply_for_purchase.objects.create(\n item_name=item_name,\n quantity=int(quantity),\n expected_cost=expected_cost, \n nature_of_item1=nature_of_item1,\n nature_of_item2=nature_of_item2,\n purpose=purpose,\n # budgetary_head_id = budgetary_head_id,\n # inspecting_authority_id=inspecting_authority_id,\n expected_purchase_date= expected_purchase_date, \n indentor_name=user,\n \n )\n a.save()\n if expected_cost >=25000 and expected_cost <= 250000 :\n b = purchase_commitee.objects.create(\n \n local_comm_mem1_id=local_comm_mem1_id,\n local_comm_mem2_id=local_comm_mem2_id,\n local_comm_mem3_id=local_comm_mem3_id, \n )\n b.save()\n\n \n \n\n return render(request, \"officeModule/officeOfPurchaseOfficer/officeOfPurchaseOfficer.html\",{})\n else:\n return render(request, \"officeModule/officeOfPurchaseOfficer/officeOfPurchaseOfficer.html\",{})\n\n@login_required\ndef after_purchase(request):\n if request.method == 'POST':\n '''if \"submit\" in request.POST:'''\n file_no=request.POST.get('file_no')\n amount=request.POST.get('amount')\n invoice=request.POST.get('invoice')\n apply_for_purchase.objects.filter(id=file_no).update(amount=amount, invoice=invoice) \n\n return render(request, \"officeModule/officeOfPurchaseOfficer/officeOfPurchaseOfficer.html\",{})\n else:\n return render(request, \"officeModule/officeOfPurchaseOfficer/officeOfPurchaseOfficer.html\",{})\n\n\n@login_required\ndef officeOfPurchaseOfficer(request):\n context={}\n if request.method == 'POST':\n if \"submit\" in request.POST:\n vendor_name=request.POST['vendor_name']\n vendor_item=request.POST['vendor_item']\n vendor_address=request.POST['vendor_address']\n \n vendor.objects.create(\n vendor_name=vendor_name,\n vendor_item=vendor_item,\n vendor_address=vendor_address,\n )\n return HttpResponse(\"successflly added vendor\")\n\n elif \"store\" in request.POST:\n item_type=request.POST.get('item_type')\n item_name=request.POST.get('item_name')\n quantity=request.POST.get('qunatity')\n\n stock.objects.create(\n item_type=item_type,\n item_name=item_name,\n quantity=quantity,\n )\n return HttpResponse(\"successflly added item\")\n elif \"item_search\" in request.POST:\n srch = request.POST['item_name']\n match = stock.objects.filter(Q(item_name__icontains=srch))\n return render(request, \"officeModule/officeOfPurchaseOfficer/officeOfPurchaseOfficer.html\",{'match':match})\n elif \"vendor_search\" in request.POST:\n sr = request.POST['item']\n matchv = vendor.objects.filter(Q(vendor_item__icontains=sr))\n return render(request, \"officeModule/officeOfPurchaseOfficer/officeOfPurchaseOfficer.html\",{'matchv':matchv})\n elif \"purchase_search\" in request.POST:\n pr = request.POST['file']\n phmatch = apply_for_purchase.objects.filter(Q(id=pr))\n return render(request, \"officeModule/officeOfPurchaseOfficer/officeOfPurchaseOfficer.html\",{'phmatch':phmatch}) \n '''elif \"delete_item\" in request.POST:\n a = request.POST.getlist('box')\n for i in range(len(a)):\n k = stock.objects.get(id = a[i])\n k.delete()\n return HttpResponse(\"successflly deleted item\")'''\n\n else:\n p=vendor.objects.all()\n q=stock.objects.all()\n ph=apply_for_purchase.objects.all()\n return render(request, \"officeModule/officeOfPurchaseOfficer/officeOfPurchaseOfficer.html\",{'p':p,'q':q,'ph':ph})\n\ndef delete_item(request,id):\n #template = 'officemodule/officeOfPurchaseOfficer/manageStore_content1.html'\n print(\">>>>>>>\")\n print(id)\n item = get_object_or_404(stock,id=id)\n item.delete()\n return HttpResponse(\"Deleted successfully\")\n\ndef delete_vendor(request,id):\n #template = 'officemodule/officeOfPurchaseOfficerr/manageStore_content1.html'\n print(\">>>>>>>\")\n print(id)\n ven = get_object_or_404(vendor,id=id)\n ven.delete()\n return HttpResponse(\"Deleted successfully\") \n\ndef edit_vendor(request,id):\n\n\n p= get_object_or_404(vendor,id=id)\n context={\n 'p' : p\n }\n return render(request,\"officeModule/officeOfPurchaseOfficer/edit.html\",context)\n return HttpResponseRedirect('/office/officeOfPurchaseOfficer')\n\ndef edit(request):\n\n ID=request.POST.get('vendor_id')\n name=request.POST.get('vendor_name')\n item=request.POST.get('vendor_item')\n add=request.POST.get('vendor_address')\n d=vendor(id=ID,vendor_name=name,vendor_item=item,vendor_address=add)\n d.save()\n return HttpResponseRedirect('/office/officeOfPurchaseOfficer')\n\ndef edit_item(request,id):\n\n\n p= get_object_or_404(stock,id=id)\n context={\n 'p' : p\n }\n return render(request,\"officeModule/officeOfPurchaseOfficer/edit1.html\",context)\n return HttpResponseRedirect('/office/officeOfPurchaseOfficer')\n\ndef edit1(request):\n\n ID=request.POST.get('item_id')\n name=request.POST.get('item_name')\n add=request.POST.get('quantity')\n d=stock(id=ID,item_name=name,quantity=add)\n d.save()\n return HttpResponseRedirect('/office/officeOfPurchaseOfficer')\n\n'''def delete(request):\n if request.method == 'POST' :\n a = request.POST.getlist('box') \n for i in range(len(a)) :\n if \"delete_item\" in request.POST :\n k = stock.objects.get(id = a[i])\n k.delete()\n \n return HttpRespons(\"officeModule/officeOfPurchaseOfficer/officeOfPurchaseOfficer.html\")'''\n'''def create_vendor(request):\n if request.method == 'POST':\n vendor_name = request.POST['vendor_name']\n vendor_item = request.POST['vendor_item']\n vendor_address = request.POST['vendor_address']\n\n vendor.objects.create(\n vendor_name = vendor_name,\n vendor_item = vendor_item,\n vendor_address = vendor_address\n )\n\n return HttpResponse('')'''\n \n\n\ndef officeOfRegistrar(request):\n context = {}\n\n return render(request, \"officeModule/officeOfRegistrar/officeOfRegistrar.html\", context)\n\n\ndef officeOfDeanStudents(request):\n context = {}\n\n return render(request, \"officeModule/officeOfRegistrar/officeOfDeanStudents.html\", context)\n\n\ndef officeOfDeanRSPC(request):\n context = {}\n\n return render(request, \"officeModule/officeOfDeanRSPC/officeOfDeanRSPC.html\", context)\n\n\ndef officeOfDeanPnD(request):\n context = {}\n\n return render(request, \"officeModule/officeOfDeanPnD/officeOfDeanPnD.html\", context)\n\ndef officeOfHOD(request):\n context = {}\n\n return render(request, \"officeModule/officeOfHOD/officeOfHOD.html\", context)\n\n\ndef genericModule(request):\n context = {}\n\n return render(request, \"officeModule/genericModule/genericModule.html\", context)\n","sub_path":"FusionIIIT/applications/office_module/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"583007005","text":"# --coding:utf-8--\nfrom APP.setting import *\nfrom APP.tc_rebind_wechat import ReBindWeChat\nimport requests\nimport urllib3\nimport random\nfrom APP.tc_code import Code\nfrom tc_app_log.Journal_class import Journal\nimport traceback\nfrom APP.get_number_verfication_code_by_bm import GetNumberCodeByBM\n\nurllib3.disable_warnings()\n\n\ndef random_password():\n \"\"\"\n 生成随机账号密码\n :return:\n \"\"\"\n pwd_1 = 'abcdefghijklmnopqrstuvwxyz'\n pwd_2 = \"0123456789@\"\n pwd = ''.join(random.choices(pwd_1, k=6)) + \"@\" + ''.join(random.choices(pwd_2, k=4))\n return pwd\n\n\nclass Register(object):\n def __init__(self, params):\n self.clientInfo = get_device_info()\n self.user = params.get(\"user\")\n self.password = params.get(\"password\")\n self.loginName = f'+86 {self.user}'\n print(self.loginName)\n self.pwd = get_password(password=self.password)\n self.im_ie = random.choice(Android)\n self.sxx = \"\"\n self.client_id = \"\"\n self.token = {}\n self.usable = {}\n self.vx_token = {}\n self.memberId = \"\"\n self.vxid = \"\"\n self.ua = \"Mozilla/5.0 (Linux; Android 8.0.0; MI 5 Build/OPR1.170623.032; wv) AppleWebKit/537.36 (KHTML, like\" \\\n \" Gecko) Version/4.0 Chrome/68.0.3440.91 Mobile Safari/537.36 MicroMessenger/7.0.13.1640(0x27000D39)\" \\\n \" Process/appbrand0 NetType/WIFI Language/zh_CN ABI/arm64 WeChat/arm64\"\n\n def get_sec_info_data(self):\n \"\"\"\n {\"data\":{\"densityDpi\":\"192\",\"deviceId\":\"957117cdb8f4fa90\",\"heightPixels\":\"1280\",\"manufacturer\":\"HUAWEI\",\n \"model\":\"VOG-AL00\",\"sdkInt\":\"22\",\"widthPixels\":\"720\"},\"flag\":\"false\",\"timeStamp\":\"1587549084179\"}\n :return:\n \"\"\"\n info_data = {\n \"data\": {\"densityDpi\": \"240\", \"deviceId\": self.clientInfo.get(\"deviceId\"),\n \"heightPixels\": self.clientInfo.get(\"device\").split(\"|\")[2].split(\"*\")[0],\n \"manufacturer\": self.clientInfo.get(\"manufacturer\"),\n \"model\": self.clientInfo.get(\"device\").split(\"|\")[3], \"sdkInt\": \"28\",\n \"widthPixels\": self.clientInfo.get(\"device\").split(\"|\")[2].split(\"*\")[1]},\n \"flag\": \"false\", \"timeStamp\": get_time()}\n res = http_do_decrypt(s=dict_to_json(info_data))\n if isinstance(res, dict):\n return res\n return res\n\n def do_get_sec_info_data(self):\n \"\"\"\n :return:\n \"\"\"\n while True:\n res = self.get_sec_info_data()\n if isinstance(res, str):\n return res\n time.sleep(5)\n\n def post_foundation_handler_one(self):\n req_time = get_time()\n url = \"https://tcmobileapi.17usoft.com/foundation/foundationHandler.ashx\"\n data = {\"request\": {\n \"body\": {\"deviceProfile\": get_device_profile(self.clientInfo.get(\"device\")),\n \"clientInfo\": self.clientInfo},\n \"header\": {\n \"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"gatewayconfig\",\n version=\"20111128102912\"),\n \"reqTime\": req_time,\n \"serviceName\": \"gatewayconfig\", \"version\": \"20111128102912\"}\n }}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": \"\",\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|00000\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False)\n self.sxx = res.headers.get(\"sxx\")\n\n def post_foundation_handler_two(self):\n req_time = get_time()\n url = \"https://tcmobileapi.17usoft.com/foundation/foundationHandler.ashx\"\n data = {\"request\": {\n \"body\": {\"deviceProfile\": get_device_profile(self.clientInfo.get(\"device\")),\n \"clientInfo\": self.clientInfo},\n \"header\": {\n \"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"getclientid\",\n version=\"20111128102912\"),\n \"reqTime\": req_time,\n \"serviceName\": \"getclientid\", \"version\": \"20111128102912\"}\n }}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|00001\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False)\n self.client_id = res.json().get(\"response\").get(\"body\").get(\"clientId\")\n self.clientInfo[\"clientId\"] = self.client_id\n\n def post_member_ship_handler_check_mobile_register(self):\n \"\"\"\n 注册检验账号\n :return:\n \"\"\"\n req_time = get_time()\n url = \"https://appgateway.ly.com/member/membershiphandler.ashx\"\n data = {\"request\": {\n \"body\": {\"clientInfo\": self.clientInfo,\n \"mobile\": self.loginName},\n \"header\": {\n \"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"CheckMobileRegister\",\n version=\"20111128102912\"),\n \"reqTime\": req_time,\n \"serviceName\": \"CheckMobileRegister\", \"version\": \"20111128102912\"}\n }}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|00002\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n # \"Content-Length\": \"744\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False).json()\n if res.get(\"response\").get(\"header\").get(\"rspDesc\") == \"未注册过\":\n return {\n \"status\": 1,\n \"msg\": \"该账号未注册\",\n }\n elif res.get(\"response\").get(\"header\").get(\"rspDesc\") == \"已注册过\":\n return {\n \"status\": 0,\n \"msg\": \"该账号已注册\",\n }\n else:\n return {\n \"status\": 3,\n \"msg\": res.get(\"response\").get(\"header\").get(\"rspDesc\")\n }\n\n def post_member_ship_handler_check_black_list(self):\n \"\"\"\n 检测该账号是否是黑名单\n :return:\n \"\"\"\n url = \"https://appgateway.ly.com/member/membershiphandler.ashx\"\n req_time = get_time()\n data = {\"request\": {\n \"body\": {\"clientInfo\": self.clientInfo,\n \"mobile\": self.loginName},\n \"header\": {\n \"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"checkblacklist\",\n version=\"20111128102912\"),\n \"reqTime\": req_time,\n \"serviceName\": \"checkblacklist\", \"version\": \"20111128102912\"}\n }}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|00003\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n # \"Content-Length\": \"744\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False).json()\n if res.get(\"response\").get(\"header\").get(\"rspDesc\") == \"未命中黑名单\":\n return True\n else:\n return {\n \"status\": 3,\n \"msg\": \"该账号为黑名单\",\n \"rspDesc\": res.get(\"response\").get(\"header\").get(\"rspDesc\")\n }\n\n def post_member_ship_handler_get_verification_code_register(self):\n \"\"\"\n 账号获取短信验证码\n :return:\n \"\"\"\n url = \"https://appgateway.ly.com/member/membershiphandler.ashx\"\n req_time = get_time()\n data = {\"request\": {\n \"body\": {\"clientInfo\": self.clientInfo,\n \"mobile\": self.loginName},\n \"header\": {\n \"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"getverificationcoderegister\",\n version=\"20111128102912\"),\n \"reqTime\": req_time,\n \"serviceName\": \"getverificationcoderegister\", \"version\": \"20111128102912\"}\n }}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|00004\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n # \"Content-Length\": \"744\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False).json()\n print(res)\n if res.get(\"response\").get(\"header\").get(\"rspDesc\") == \"获取成功\":\n return True\n else:\n return {\n \"status\": 3,\n \"msg\": \"发送验证失败\",\n \"rspDesc\": res.get(\"response\").get(\"header\").get(\"rspDesc\")\n }\n\n def post_member_ship_handler_register_v2(self, verify_code):\n \"\"\"\n 注册账号\n :return:\n \"\"\"\n sec_info = self.do_get_sec_info_data()\n url = \"https://appgateway.ly.com/member/membershiphandler.ashx\"\n req_time = get_time()\n data = {\"request\": {\n \"body\": {\"clientInfo\": self.clientInfo,\n \"loginName\": self.loginName,\n \"password\": self.pwd,\n \"androidId\": self.clientInfo.get(\"deviceId\"),\n \"secInfo\": sec_info,\n \"androidImei\": self.im_ie,\n \"verifyCode\": verify_code,\n \"verifyCodeType\": \"0\"\n },\n \"header\": {\n \"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"RegisterV2\",\n version=\"20111128102912\"),\n \"reqTime\": req_time,\n \"serviceName\": \"RegisterV2\", \"version\": \"20111128102912\"}\n }}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|0005\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False).json()\n print(\"res\", res)\n if res.get(\"response\").get(\"header\").get(\"rspDesc\") == \"注册成功\":\n self.token = res.get(\"response\").get(\"body\")\n self.memberId = self.token.get(\"memberId\")\n else:\n return {\n \"status\": 3,\n \"msg\": \"注册失败\",\n \"rspDesc\": res.get(\"response\").get(\"header\").get(\"rspDesc\")\n }\n\n def post_social_user_bind(self, social_code):\n \"\"\"\n 绑定微信\n :param social_code: app 绑定微信的code\n :return:\n \"\"\"\n req_time = get_time()\n sec_info = self.do_get_sec_info_data()\n url = \"https://appgateway.ly.com/member/membershiphandler.ashx\"\n data = {\"request\": {\"body\": {\"clientInfo\": self.clientInfo,\n \"secInfo\": sec_info,\n \"socialType\": \"4\",\n \"socialCode\": social_code,\n \"memberId\": self.memberId},\n \"header\": {\"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"SocialUserBind\",\n version=\"20111128102912\"), \"reqTime\": req_time,\n \"serviceName\": \"SocialUserBind\", \"version\": \"20111128102912\"}}}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|00052\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False).json()\n print(\"post_social_user_bind\", res)\n if res.get(\"response\").get(\"header\").get(\"rspType\") == \"0\" and \\\n res.get(\"response\").get(\"header\").get(\"rspCode\") == \"0000\":\n return True\n else:\n return {\n \"status\": 3,\n \"msg\": \"注册成功,绑定微信失败\",\n \"rspDesc\": res.get(\"response\").get(\"header\").get(\"rspDesc\")\n }\n\n def app_wx_user(self, vx_code):\n \"\"\"\n 微信登录同程小程序,获取token\n :param vx_code 微信返回的code\n :return:\n \"\"\"\n url = \"https://wx.17u.cn/appapi/wxuser/login/2\"\n headers = {\n \"Host\": \"wx.17u.cn\",\n \"Connection\": \"keep-alive\",\n \"Content-Length\": \"56\",\n \"charset\": \"utf-8\",\n \"User-Agent\": self.ua,\n \"content-type\": \"application/json\",\n \"Accept-Encoding\": \"gzip,compress,br,deflate\",\n }\n data = {\"code\": vx_code, \"scene\": 1019}\n res = requests.post(url=url, headers=headers, data=dict_to_json(data), verify=False).json()\n if res.get(\"openId\"):\n self.vx_token = res\n else:\n return {\n \"status\": 3,\n \"msg\": \"注册成功,绑定微信成功,获取微信token失败\",\n }\n\n def get_social_code(self):\n \"\"\"\n 获取微信code\n :return:\n \"\"\"\n code = Code()\n res = code.do_get_tc_app_code()\n if isinstance(res, dict):\n return res\n social_code = res[0]\n self.vxid = res[1]\n print(\"social_code:\", social_code)\n # social_code = input(\"请输入code:\")\n res = self.post_social_user_bind(social_code=social_code)\n if isinstance(res, dict):\n return res\n print(\"vxid:\", self.vxid)\n res_vx = code.do_get_tc_wechat_code(vxid=self.vxid)\n if isinstance(res_vx, dict):\n return res_vx\n vx_code = res_vx[0]\n print(\"vx_code:\", vx_code)\n res = self.app_wx_user(vx_code=vx_code)\n if isinstance(res, dict):\n return res\n return True\n\n def post_get_verification_code(self):\n \"\"\"\n 修改密码获取验证码请求\n :return:\n \"\"\"\n url = \"https://appgateway.ly.com/member/membershiphandler.ashx\"\n req_time = get_time()\n data = {\"request\": {\n \"body\": {\"clientInfo\": self.clientInfo,\n \"mobile\": self.loginName,\n },\n \"header\": {\n \"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"GetVerificationCode\",\n version=\"20111128102912\"),\n \"reqTime\": req_time,\n \"serviceName\": \"GetVerificationCode\", \"version\": \"20111128102912\"}\n }}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|0003\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False).json()\n if res.get(\"response\").get(\"header\").get(\"rspDesc\") == \"获取成功\":\n return True\n else:\n return {\n \"status\": 3,\n \"msg\": \"发送验证失败\",\n \"rspDesc\": res.get(\"response\").get(\"header\").get(\"rspDesc\")\n }\n\n def post_confirm_verification_code_member(self, verfy_code):\n \"\"\"\n 发起修改验证码请求\n :param verfy_code:\n :return:\n \"\"\"\n url = \"https://appgateway.ly.com/member/membershiphandler.ashx\"\n req_time = get_time()\n data = {\"request\": {\n \"body\": {\"clientInfo\": self.clientInfo,\n \"isReturnPwd\": \"1\",\n \"mobile\": self.loginName,\n \"verifyCode\": verfy_code,\n },\n \"header\": {\n \"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"confirmverificationcodemember\",\n version=\"20111128102912\"),\n \"reqTime\": req_time,\n \"serviceName\": \"confirmverificationcodemember\", \"version\": \"20111128102912\"}\n }}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|0000\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False).json()\n if res.get(\"response\").get(\"header\").get(\"rspDesc\") == \"确认成功\":\n return True\n else:\n return {\n \"status\": 3,\n \"msg\": \"修改验证码确认失败\",\n \"rspDesc\": res.get(\"response\").get(\"header\").get(\"rspDesc\")\n }\n\n def post_update_password_without_original(self, verfy_code):\n \"\"\"\n 修改密码提交请求\n :param verfy_code:\n :return:\n \"\"\"\n url = \"https://appgateway.ly.com/member/membershiphandler.ashx\"\n req_time = get_time()\n data = {\"request\": {\n \"body\": {\"clientInfo\": self.clientInfo,\n \"newPassword\": self.password,\n \"mobile\": self.loginName,\n \"verifyCode\": verfy_code,\n },\n \"header\": {\n \"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"UpdatePasswordWithoutOriginal\",\n version=\"20111128102912\"),\n \"reqTime\": req_time,\n \"serviceName\": \"UpdatePasswordWithoutOriginal\", \"version\": \"20111128102912\"}\n }}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|0002\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False).json()\n if res.get(\"response\").get(\"header\").get(\"rspDesc\") == \"修改成功\":\n return {\n \"status\": 0,\n \"msg\": \"修改密码成功\",\n }\n else:\n return {\n \"status\": 3,\n \"msg\": \"修改密码失败\",\n \"rspDesc\": res.get(\"response\").get(\"header\").get(\"rspDesc\")\n }\n\n def post_location_handler_login(self):\n \"\"\"执行登录\"\"\"\n sec_info = self.do_get_sec_info_data()\n req_time = get_time()\n url = \"https://appgateway.ly.com/member/MembershipHandler.ashx\"\n data = {\"request\": {\n \"body\": {\"isUserLogin\": \"1\",\n \"secInfo\": sec_info,\n \"clientInfo\": self.clientInfo,\n \"rawText\": do_raw_text(self.user, self.password)},\n \"header\": {\"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"Loginv3\",\n version=\"20111128102912\"), \"reqTime\": req_time,\n \"serviceName\": \"Loginv3\", \"version\": \"20111128102912\"}}}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|00005\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n req_json = requests.post(url=url, headers=headers, data=data, verify=False).json()\n if req_json['response']['header']['rspCode'] == \"5587\":\n return {'status': 302, 'msg': f\"{req_json['response']['header']['rspDesc']}'出现短信验证码'\"}\n elif req_json['response']['header']['rspCode'] == \"3001\":\n return {'status': 300, 'msg': f\"{req_json['response']['header']['rspDesc']}' 密码错误\"}\n elif req_json['response']['header']['rspCode'] == '0000':\n self.token = req_json.get(\"response\").get(\"body\")\n self.memberId = self.token.get(\"memberId\")\n return {\n \"status\": 0,\n \"msg\": \"登录成功\"\n }\n else:\n return {\n \"status\": 3,\n \"msg\": \"登录失败\"\n }\n\n def post_get_login_dynamic_code(self):\n \"\"\"\n 获取登录短信验证码\n :return:\n \"\"\"\n url = \"https://appgateway.ly.com/member/MembershipHandler.ashx\"\n req_time = get_time()\n data = {\"request\": {\"body\": {\"clientInfo\": self.clientInfo,\n \"mobile\": self.loginName},\n \"header\": {\"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time,\n service_name=\"getlogindynamiccode\",\n version=\"20111128102912\"), \"reqTime\": req_time,\n \"serviceName\": \"getlogindynamiccode\", \"version\": \"20111128102912\"}}}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|00001\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n res = requests.post(url=url, headers=headers, data=data, verify=False).json()\n if res.get(\"response\").get(\"header\").get(\"rspType\") == \"0\" and \\\n res.get(\"response\").get(\"header\").get(\"rspCode\") == \"0000\":\n return True\n else:\n return {\n \"status\": 3,\n \"msg\": \"登录获取短信验证码失败\",\n \"rspDesc\": res.get(\"response\").get(\"header\").get(\"rspDesc\")\n }\n\n def post_login_by_dynamic_code(self, verify_code):\n \"\"\"\n 使用验证码登录\n :return:\n \"\"\"\n sec_info = self.do_get_sec_info_data()\n req_time = get_time()\n url = \"https://appgateway.ly.com/member/MembershipHandler.ashx\"\n data = {\"request\": {\n \"body\": {\"mobile\": self.loginName,\n \"secInfo\": sec_info,\n \"clientInfo\": self.clientInfo,\n \"verifyCode\": verify_code\n },\n \"header\": {\"accountID\": \"c26b007f-c89e-431a-b8cc-493becbdd8a2\",\n \"digitalSign\": get_digital_sign(req_time=req_time, service_name=\"loginbydynamiccode\",\n version=\"20111128102912\"), \"reqTime\": req_time,\n \"serviceName\": \"loginbydynamiccode\", \"version\": \"20111128102912\"}}}\n data = dict_to_json(data)\n data01 = {\"body\": data}\n headers = {\n \"sxx\": self.sxx,\n \"secsign\": get_secsign(data01),\n \"secver\": \"4\",\n \"apmat\": f\"{self.clientInfo.get('deviceId')}|i|{get_time_stamp()}|00002\",\n \"reqdata\": get_req_data(data),\n \"Content-Type\": \"application/json; charset=utf-8\",\n \"Host\": \"tcmobileapi.17usoft.com\",\n \"Connection\": \"Keep-Alive\",\n \"Accept-Encoding\": \"gzip\",\n \"User-Agent\": \"okhttp/3.12.2\",\n }\n req_json = requests.post(url=url, headers=headers, data=data, verify=False).json()\n if req_json.get(\"response\").get(\"header\").get(\"rspType\") == \"0\" and \\\n req_json.get(\"response\").get(\"header\").get(\"rspCode\") == \"0000\":\n print(\"登陆成功\")\n self.token = req_json.get(\"response\").get(\"body\")\n self.memberId = self.token.get(\"memberId\")\n else:\n return {\n \"status\": 3,\n \"msg\": \"短信登录失败,请重新尝试登录\",\n \"rspDesc\": req_json.get(\"response\").get(\"header\").get(\"rspDesc\")\n }\n\n def do_register_one(self):\n \"\"\"\n 账号注册\n :return:\n \"\"\"\n try:\n self.post_foundation_handler_one()\n self.post_foundation_handler_two()\n res = self.post_member_ship_handler_check_mobile_register()\n if isinstance(res, dict):\n res[\"index\"] = \"post_member_ship_handler_check_mobile_register\"\n return res\n res = self.post_member_ship_handler_get_verification_code_register()\n if isinstance(res, dict):\n res[\"index\"] = \"post_member_ship_handler_get_verification_code_register\"\n return res\n v = input(\"请输入验证短信验证码:\")\n res = self.post_member_ship_handler_register_v2(verify_code=v)\n if isinstance(res, dict):\n res[\"index\"] = \"post_member_ship_handler_register_v2\"\n return res\n self.usable = {\n \"status\": 0,\n \"phone\": self.user,\n \"pwd\": self.password,\n \"user_type\": \"0\",\n \"device\": {\n \"clientInfo\": self.clientInfo,\n \"AndroidImei\": self.im_ie,\n \"sxx\": self.sxx,\n \"clientId\": self.client_id,\n }, # 设备参数及其他重要值\n \"token\": self.token, # 用于二次登录的重要 token\n \"proxy\": \"\", # 代理IP\n \"vx_token\": {},\n \"integral\": 0\n }\n res = perform_first_sign_in(data=self.usable)\n if isinstance(res, dict):\n pass\n else:\n self.usable[\"integral\"] = int(res)\n res = self.get_social_code()\n if isinstance(res, dict):\n res[\"msg\"] = \"微信注册成功,\" + res[\"msg\"]\n return res\n self.vx_token[\"vxid\"] = self.vxid\n self.usable[\"vx_token\"] = self.vx_token\n return self.usable\n finally:\n res = self.do_register_save()\n print(res)\n\n def do_register_two(self):\n \"\"\"\n 账号注册,如果遇到已经注册过的账号修改密码\n :return:\n \"\"\"\n try:\n self.post_foundation_handler_one()\n self.post_foundation_handler_two()\n res = self.post_member_ship_handler_check_mobile_register()\n print(\"是否注册:\", res)\n if res.get(\"status\") == 0:\n print(\"该号已注册,执行修改密码\")\n res_1 = self.post_get_verification_code()\n if isinstance(res_1, dict):\n res_1[\"index\"] = \"post_get_verification_code\"\n return res_1\n code = GetNumberCodeByBM(aip_token).do_get_phone_message(phone=self.user)\n if isinstance(code, dict):\n code[\"index\"] = \"do_get_phone_message\"\n return code\n print(\"修改密码的验证码:\", code)\n res_2 = self.post_confirm_verification_code_member(verfy_code=code)\n if isinstance(res_2, dict):\n res_2[\"index\"] = \"post_update_password_without_original\"\n return res_2\n res_3 = self.post_update_password_without_original(verfy_code=code)\n print(\"修改密码:\", res_3)\n if res_3.get(\"status\") == 3:\n res_3[\"index\"] = \"post_update_password_without_original\"\n return res_3\n else:\n res_4 = self.post_location_handler_login()\n print(\"执行登录:\", res_4)\n if res_4.get(\"status\") == 302:\n print(\"登录时出现验证码\")\n res_l1 = self.post_get_login_dynamic_code()\n if isinstance(res_l1, dict):\n res_l1[\"index\"] = \"post_get_login_dynamic_code\"\n return res_l1\n v_code = GetNumberCodeByBM(aip_token).do_get_phone_message(phone=self.user)\n if isinstance(v_code, dict):\n v_code[\"index\"] = \"do_get_phone_message_two\"\n return v_code\n res_5 = self.post_login_by_dynamic_code(verify_code=v_code)\n if isinstance(res_5, dict):\n res_5[\"index\"] = \"post_login_by_dynamic_code\"\n return res_5\n print(\"使用验证码登录成功\")\n elif res_4.get(\"status\") == 0:\n print(\"登录成功未出现验证码\")\n pass\n else:\n return res_4\n self.usable = {\n \"status\": 0,\n \"phone\": self.user,\n \"pwd\": self.password,\n \"user_type\": \"0\",\n \"device\": {\n \"clientInfo\": self.clientInfo,\n \"AndroidImei\": self.im_ie,\n \"sxx\": self.sxx,\n \"clientId\": self.client_id,\n }, # 设备参数及其他重要值\n \"token\": self.token, # 用于二次登录的重要 token\n \"proxy\": {}, # 代理IP\n \"vx_token\": {},\n \"integral\": 0\n }\n res_6 = perform_get_integral(data=self.usable)\n print(\"未解绑时的里程:\", res_6)\n if isinstance(res_6, dict):\n return res_6\n elif int(res_6) < 200:\n rebind = ReBindWeChat(params=self.usable)\n res_7 = rebind.do_rebind_one()\n print(res_7)\n if isinstance(res_7, tuple):\n self.usable[\"vx_token\"] = res_7[0]\n self.usable[\"integral\"] = int(res_7[1])\n return self.usable\n else:\n return res_7\n else:\n print(\"里程数大于200,直接保持账号\")\n self.usable[\"integral\"] = int(res_6)\n self.usable[\"user_type\"] = \"2\"\n return self.usable\n elif res.get(\"status\") == 1:\n print(\"该号未注册\")\n res = self.post_member_ship_handler_get_verification_code_register()\n if isinstance(res, dict):\n res[\"index\"] = \"post_member_ship_handler_get_verification_code_register\"\n return res\n v = GetNumberCodeByBM(aip_token).do_get_phone_message(phone=self.user)\n if isinstance(v, dict):\n return v\n res = self.post_member_ship_handler_register_v2(verify_code=v)\n if isinstance(res, dict):\n res[\"index\"] = \"post_member_ship_handler_register_v2\"\n return res\n self.usable = {\n \"status\": 0,\n \"phone\": self.user,\n \"pwd\": self.password,\n \"user_type\": \"0\",\n \"device\": {\n \"clientInfo\": self.clientInfo,\n \"AndroidImei\": self.im_ie,\n \"sxx\": self.sxx,\n \"clientId\": self.client_id,\n }, # 设备参数及其他重要值\n \"token\": self.token, # 用于二次登录的重要 token\n \"proxy\": {}, # 代理IP\n \"vx_token\": {},\n \"integral\": 0\n }\n rebind = ReBindWeChat(params=self.usable)\n res_7 = rebind.do_rebind_one()\n print(res_7)\n if isinstance(res_7, tuple):\n self.usable[\"vx_token\"] = res_7[0]\n self.usable[\"integral\"] = int(res_7[1])\n return self.usable\n else:\n return res_7\n else:\n res[\"index\"] = \"post_member_ship_handler_check_mobile_register\"\n return res\n finally:\n res = self.do_register_save()\n print(\"ok\")\n\n def do_register_save(self):\n \"\"\"\n 将注册成功的推送到\n :return:\n \"\"\"\n if self.usable.get(\"token\"):\n url = URL + \"/regsave.do\"\n data = self.usable\n res = requests.post(url=url, json=data)\n if res.text == \"OK\":\n return {\n \"status\": 0,\n \"msg\": \"注册成功,并存储成功\"\n }\n else:\n return {\n \"status\": 1,\n \"msg\": \"注册成功,并存储失败\",\n \"Remark\": res.text\n }\n else:\n return {\n \"status\": 1,\n \"msg\": \"注册失败\",\n }\n\n\ndef do_register_log():\n pwd = random_password()\n phone = GetNumberCodeByBM(aip_token).do_get_phone_number()\n if isinstance(phone, dict):\n return phone\n res_phone = get_get_user_do(phone=phone)\n if res_phone.get(\"status\") in (0, 2):\n return {\n \"status\": 1,\n \"msg\": \"该账号已存在账号中心\",\n }\n data = {\n \"user\": phone,\n \"password\": pwd\n }\n print(data)\n try:\n ret = Register(params=data).do_register_two()\n print(ret)\n resp = {\n \"注册信息\": data,\n \"返回信息\": ret\n }\n Journal().save_journal_register(massage=json.dumps(resp))\n except Exception:\n ret = {'status': 500, 'msg': traceback.format_exc()}\n resp = {\n \"注册信息\": data,\n \"响应数据\": ret\n }\n Journal().save_journal_register(massage=json.dumps(resp), level=\"error\")\n return json.dumps(ret)\n\n\nif __name__ == \"__main__\":\n ress = do_register_log()\n","sub_path":"APP/tc_app_register.py","file_name":"tc_app_register.py","file_ext":"py","file_size_in_byte":39187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"564322662","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 5 16:53:03 2018\n\n@author: ppxsw1\n\"\"\"\nimport numpy as np\nNx = 1\nNt = 10\nNb = 2\nNpath = 2*Nt\nNtot = Nx*Npath\nNrp = Npath - 4\nNrt = Nx*Nrp\ndeltaT = 0.75\ndeltaX = 0.75\nLambda = 0.0\nm = 1.0\ndelta = 0.1\nj = complex(0,1)\ndt = deltaT*np.concatenate((np.ones(Nt-2), -np.ones(Nt-2)))\n","sub_path":"devsource/Correlators/prot.py","file_name":"prot.py","file_ext":"py","file_size_in_byte":345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"423973711","text":"from instructions.instruction import Instruction\nfrom devices.host import Host\nfrom devices.hub import Hub\nfrom devices.switch import Switch\nfrom devices.router import Router\nfrom network_status import Status\nimport os\n\nclass Create(Instruction):\n def __init__(self, input):\n \"\"\"Init create instruction information\"\"\"\n\n Instruction.__init__(self,input)\n\n self.device = input[self.start]\n self.device_name = input[self.start + 1]\n self.device_info = input[self.start + 1:]\n\n def execute(self, net_stat : Status):\n \"\"\"Execute create Instruction\"\"\"\n if(self.device == 'host'):\n new_device = Host(self.device_info)\n elif(self.device == 'hub'):\n new_device = Hub(self.device_info)\n elif(self.device == 'switch'):\n new_device = Switch(self.device_info)\n elif(self.device == 'router'):\n new_device = Router(self.device_info)\n else:\n assert False, 'Unknown device'\n\n net_stat.name_index[new_device.name] = len(net_stat.devices_connect) # quantity devices connected on network\n net_stat.devices_connect.append(new_device) # add new device on network\n","sub_path":"instructions/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":1193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"172680712","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 19 18:08:48 2019\n\n@author: Invitado\n\"\"\"\n\n#Definir el sistema de ecuaciones diferenciales\nimport numpy as np #Crear y manipular arrays\n\ndef fun(Y,t,TM,f_inter):\n \n NA = Y[0]\n NB = Y[1]\n NC = Y[2]\n NT = NA+NB+NC\n \n caudal = 8.5 #m3/min\n k1 = 4.23 #min^-1\n k2 = 3.67 #min^-1\n R = 8.314 #Pa m3/Kmol\n To = (25 + 273) #K \n Po = 101325 #Pa \n \n V = TM*caudal\n \n Co = Po/(R*To)\n CA = Co*(NA/NT)\n CB = Co*(NB/NT)\n \n R1 = k1*CA\n R2 = k2*CB\n \n rA = -R1\n rB = R1 - R2\n rC = R2\n \n salida_1 = rA*V*f_inter(t)\n salida_2 = rB*V*f_inter(t)\n salida_3 = rC*V*f_inter(t)\n salida = np.array([salida_1,salida_2,salida_3])\n return salida","sub_path":"TEMA 3/Ejercicio en pulso/ODE_system.py","file_name":"ODE_system.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"581913973","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Mar 30 14:36:12 2019\r\n\r\n@author: rur4893\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Mar 22 16:54:55 2019\r\n\r\n@author: rur4893\r\n\"\"\"\r\n\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.integrate import quad\r\nimport numpy as np\r\nimport pandas as pd\r\nimport math\r\n\r\n# input the basic drilling parameters\r\nm = 0.65 # flow behavior index\r\nK = 1.85 # fluid consistency\r\ntau_y = 5.62 # yield stress pa\r\nr_w = 311.2 /2 /1000 # wellbore radius\r\n\r\n# define the dimensionless function for this calculation\r\na = lambda w: (2*m+1)/(m+1)*(2*r_w)/w*tau_y/delta_p\r\nf = lambda x: 2.**((m+1)/m)*x*(((x**(1-m))-1)/(1-m))**(1/m)/(1-a*(x-1))**(1/m)\r\n\r\ndelta_ps = [4.2*10**6, 3.2*10**6, 2.2*10**6]\r\n# calculation time step\r\n# dynamic list append\r\n\r\nRad_ds = {}\r\nTime_ds = {}\r\n\r\nfor delta_p in delta_ps:\r\n Rad_ds['%i' % delta_p] = []\r\n Time_ds['%i' % delta_p] = []\r\n \r\n# iterate the pressure\r\nfor j, delta_p in enumerate(delta_ps):\r\n # dimensionless lost circulation parameters\r\n # Dimensionless_a = [0.0001,0.008,0.001] The original dimensionless group\r\n # Dimensionless_a = [0.0001,0.001,0.008]\r\n\r\n #width = [0.0055, 0.00055, 0.000055]\r\n #width = [0.0008]\r\n \r\n# w = lambda a: (2*m+1)/(m+1)*(2*r_w)/a*tau_y/delta_p\r\n# width = [w(a) for a in Dimensionless_a]\r\n# a = lambda w: (2*m+1)/(m+1)*(2.*r_w)/w*tau_y/delta_p\r\n # Dimensionless_a = [a(w) for w in width ]\r\n Dimensionless_a = [0.0001,0.0002,0.0003,0.0004,0.0005,0.0006,0.0007,0.0008,0.0009,\r\n 0.001,0.002,0.003,0.004,0.005,0.005,0.006,0.007,0.008,0.009,0.01,0.02,0.03,0.04]\r\n \r\n for k,v in enumerate(Dimensionless_a):\r\n\r\n Radius_d_init = 1.1 # the initial R_d\r\n Radius_d_alti = 1 + 1./v # the altimate R_d\r\n\r\n Radius_d = np.arange(Radius_d_init, Radius_d_alti)\r\n total_time_step = len(Radius_d)\r\n # calculation the time step matrices\r\n Rad_ds['%i' % delta_p].append(Radius_d);\r\n\r\n # seven matrices\r\n # use quad integration\r\n\r\n for k,a in enumerate(Dimensionless_a):\r\n Y = [quad(f,1.01,int_val)[0] for int_val in Rad_ds['%i' % delta_p][k]]\r\n Time_ds['%i' % delta_p].append(Y)\r\n\r\nR_d = pd.DataFrame(Rad_ds)\r\nT_d = pd.DataFrame(Time_ds)\r\n\r\nfig, ax = plt.subplots()\r\nax.xaxis.grid(True, which = 'Major', linestyle='dotted')\r\nax.yaxis.grid(True, which = 'Major', linestyle='dotted') \r\n\r\ncolor = ['r', 'b', 'g']\r\ncol = 0\r\nfor i in delta_ps: # iterate for delta_ps\r\n for j in range(len(Dimensionless_a)): # iterate for dimensionless_a\r\n ax.plot(np.log10(T_d['%i'%i][j][:]),np.log10(R_d['%i'%i][j][:]**2 - 1), '.', c = color[col])\r\n col += 1\r\n \r\nplt.title('Theoretical type curve figure:%i (Mpa)' %(delta_p/1000000.))\r\nplt.xlabel('Dimensionless time (t)')\r\nplt.ylabel('Dimensionless invasion radius $({r^2 - 1})$')\r\n# plt.legend()\r\nax.annotate('*gp = 2.2 Mpa', xy = (7.8,4))\r\nax.annotate('*bp = 3.2 Mpa', xy = (11, 6))\r\nax.annotate('*rp = 4.2 Mpa', xy = (7.5,7.8))\r\n# Good time_step algorithm.\r\n# Radius_d the fluid invasion radius.\r\nplt.show()\r\n\r\n\r\n'''\r\ndef Hough_Transform(x, y):\r\n X = np.array(x)\r\n Y = np.array(y)\r\n n = len(x)\r\n d = np.zeros(shape=(9,181))\r\n # generate matrix for the calculation\r\n for j in range(n):\r\n for i in range(181):\r\n theta = i * math.pi/180\r\n a = X[j] * math.cos(theta) + Y[j] * math.sin(theta)\r\n d[j,i] = a\r\n \r\n # data visulization for the calculation\r\n for j in range(n):\r\n plt.plot(range(181),d[j,:],'r')\r\n \r\n ax = plt.axes()\r\n plt.xlim([0, 180])\r\n ax.set_xlabel('theta')\r\n ax.set_ylabel('d')\r\n ax.annotate('Point',xy=(140,2))\r\n ax.xaxis.grid(True, which = 'major', linestyle = 'dotted')\r\n ax.yaxis.grid(True, which = 'major', linestyle = 'dotted')\r\n b = 'Polar Representation for Line'\r\n plt.title(b)\r\n'''\r\ndata = [[math.log10(T_d['3200000'][0][i]) for i in range(R_d['3200000'][0].shape[0])],\r\n [math.log10(R_d['3200000'][0][i]**2 - 1) for i in range(R_d['3200000'][0].shape[0])]]\r\n\r\n\r\n# Kernel function --\r\n","sub_path":"svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":4190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"528541620","text":"from functools import cmp_to_key\nclass Solution:\n def isSubsequence(self, s, t):\n if len(s) == 0:\n return True\n i = 0\n for ch in t:\n if ch == s[i]:\n i += 1\n if i == len(s):\n return True\n return False\n\n\nif __name__ == '__main__':\n sol = Solution()\n\n s = \"abc\"\n t = \"ahbgdc\"\n print(s, t)\n r = sol.isSubsequence(s, t)\n print(r)","sub_path":"lc_392_is_subsequence.py","file_name":"lc_392_is_subsequence.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"76840460","text":"import json\nfrom unittest import TestCase\nimport random\nimport requests\n\n\ntest_data = {\n\n}\n\nclass ShopCartTest(TestCase):\n def test_all_users(self):\n url = 'http://127.0.0.1:8000/api/cart/?format=json'\n resp = requests.get(url)\n user_list = resp.json()\n print(user_list)\n\n def test_all_carts(self):\n url = 'http://127.0.0.1:8000/api/CommodityCart/?format=json'\n resp = requests.get(url)\n cart_list = resp.json()\n print(cart_list)\n cart_random = random.choice(cart_list)\n\n print(cart_random['cart']['user'],\n cart_random['commondity'])\n\n\nif __name__ == '__main__':\n ShopCartTest()\n","sub_path":"cart/test_/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"104403220","text":"from django.http import HttpResponse\nfrom poop.models import User, Poop\nimport datetime, math, time\nfrom django.core import serializers\nfrom django.views.decorators.csrf import csrf_exempt\n\n\ndef login(request):\n user = None\n getData = request.GET\n if 'user_id' in getData and len(getData['user_id']) > 0:\n try:\n user = User.objects.get(fb_id=getData['user_id'])\n except User.DoesNotExist:\n user = User.objects.create(fb_id=getData['user_id'])\n user.lastLoginTime = datetime.datetime.today()\n user.save()\n user.lastLoginTime = time.mktime(user.lastLoginTime.timetuple())\n data = serializers.serialize('json', [user,])\n return HttpResponse(data, mimetype='application/json')\n\n\n@csrf_exempt\ndef poop(request):\n thePoop = None\n postData = request.POST\n if ('user_id' in postData and len(postData['user_id']) > 0 and\n 'poop_id' in postData and len(postData['poop_id']) > 0 and\n 'status' in postData and len(postData['status']) > 0 and\n 'content' in postData and len(postData['content']) > 0 and\n 'place_name' in postData and len(postData['place_name']) > 0 and\n 'locationX' in postData and len(postData['locationX']) > 0 and\n 'locationY' in postData and len(postData['locationY']) > 0):\n thePoop = Poop.objects.create(user_id=postData['user_id'], poop_id=postData['poop_id'],\n content=postData['content'], place_name=postData['place_name'],\n locationX=postData['locationX'], locationY=postData['locationY'],\n status=postData['status'], pub_time=datetime.datetime.today())\n thePoop.save()\n thePoop.pub_time = time.mktime(thePoop.pub_time.timetuple())\n data = serializers.serialize('json', [thePoop,])\n return HttpResponse(data, mimetype='application/json')\n\n\ndef get_users_by_loc(request):\n users_nearby = []\n getData = request.GET\n if ('locationX' in getData and len(getData['locationX']) > 0 and\n 'locationY' in getData and len(getData['locationY']) > 0):\n allPoops = Poop.objects.all()\n for thePoop in allPoops:\n if (distance_on_unit_sphere(float(getData['locationX']), float(getData['locationY']),\n float(thePoop.locationX), float(thePoop.locationY)) <= 5):\n thePoop.pub_time = time.mktime(thePoop.pub_time.timetuple())\n thePoop.user.lastLoginTime = time.mktime(thePoop.user.lastLoginTime.timetuple())\n users_nearby.append(thePoop.user)\n data = serializers.serialize('json', users_nearby)\n return HttpResponse(data, mimetype='application/json')\n\n\ndef get_poops(request):\n theTime = request.GET.get('time', '')\n if theTime:\n theTime = datetime.datetime.fromtimestamp(float(theTime))\n poops = Poop.objects.filter(pub_time__gte=theTime).order_by('-pub_time')\n for thePoop in poops:\n thePoop.pub_time = time.mktime(thePoop.pub_time.timetuple())\n data = serializers.serialize('json', poops)\n return HttpResponse(data, mimetype='application/json')\n\n\ndef get_poops_by_user(request):\n user_id = request.GET.get('user_id', '')\n if user_id:\n user = User.objects.get(fb_id=user_id)\n poops = Poop.objects.filter(user=user)\n for thePoop in poops:\n thePoop.pub_time = time.mktime(thePoop.pub_time.timetuple())\n data = serializers.serialize('json', poops)\n return HttpResponse(data, mimetype='application/json')\n\n\ndef distance_on_unit_sphere(lat1, long1, lat2, long2):\n\n # Convert latitude and longitude to\n # spherical coordinates in radians.\n degrees_to_radians = math.pi/180.0\n\n # phi = 90 - latitude\n phi1 = (90.0 - lat1)*degrees_to_radians\n phi2 = (90.0 - lat2)*degrees_to_radians\n\n # theta = longitude\n theta1 = long1*degrees_to_radians\n theta2 = long2*degrees_to_radians\n\n # Compute spherical distance from spherical coordinates.\n\n # For two locations in spherical coordinates\n # (1, theta, phi) and (1, theta, phi)\n # cosine( arc length ) =\n # sin phi sin phi' cos(theta-theta') + cos phi cos phi'\n # distance = rho * arc length\n\n cos = (math.sin(phi1)*math.sin(phi2)*math.cos(theta1 - theta2) +\n math.cos(phi1)*math.cos(phi2))\n arc = math.acos( cos )\n\n # Remember to multiply arc by the radius of the earth\n # in your favorite set of units to get length.\n return arc * 6373 # kilometer\n","sub_path":"pooproom/poop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"601923309","text":"from shapely.geometry import Polygon\nfrom shapely.geometry import Point\nfrom tqdm import tqdm\nimport pandas as pd\n\nimport pickle\nimport os.path\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\n\n# If modifying these scopes, delete the file token.pickle.\nSCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']\n\n# The ID and range of a sample spreadsheet.\nSAMPLE_SPREADSHEET_ID = '1-twPSaH9H-S45LbLZLlzWnFzAxQSDRc8dXqRV0lQ3nY'\nSAMPLE_RANGE_NAME = 'data!A:G'\n\n# def main():\ncreds = None\n# The file token.pickle stores the user's access and refresh tokens, and is\n# created automatically when the authorization flow completes for the first\n# time.\nif os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\n# If there are no (valid) credentials available, let the user log in.\nif not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'credentials.json', SCOPES)\n creds = flow.run_local_server()\n # Save the credentials for the next run\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n\nservice = build('sheets', 'v4', credentials=creds)\n\n# Call the Sheets API\nprint(\"Importing G-Sheet...\")\nsheet = service.spreadsheets()\nresult = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,\n range=SAMPLE_RANGE_NAME).execute()\nvalues = result.get('values', [])\nkolom = values[0]\nkolom.append('lat')\nkolom.append('long')\n\ndata = pd.DataFrame(values[1:], columns=kolom)\ndata.to_postcode = data.to_postcode.replace('','0').astype(int)\nprint(\"Importing Postcode Hub and Zones...\")\nkodepos = pd.read_excel('hubkode.xlsx')\nprint(\"Importing List of Hub and Zones Polygon Data...\")\nhub = pd.read_excel('hub.xlsx')\ndata = pd.merge(data,kodepos,on='to_postcode',how='left')\n\nprint(\"Pointing in Polygon...\")\nhubbaru = pd.DataFrame([])\nfor i in tqdm(range(len(data))):\n try :\n listpo = []\n poin = Point(float(data.long[i]),float(data.lat[i]))\n for j in range(len(hub)):\n try :\n listpo.append(Polygon(eval(hub.poly.iloc[j])).contains(poin))\n except:\n listpo.append(False)\n if True in listpo:\n hubbaru = hubbaru.append(hub[listpo][[\"name\",\"name1\"]].iloc[0])\n else:\n hubbaru = hubbaru.append(pd.DataFrame({\"name\":[\"no hub\"],\"name1\":[\"no hub\"]}))\n except :\n hubbaru = hubbaru.append(pd.DataFrame({\"name\":[\"no latlong\"],\"name1\":[\"no latlong\"]}))\n\ndata['zone_address']=hubbaru['name'].values\ndata['hub_address']=hubbaru['name1'].values\n\nprint(\"Printing Result in : hasilCekAV.xlsx\")\n\nresult = data[(data.dest_zone != data.zone_address) & (data.dest_hub != data.hub_address) & (data.dest_zone != data.zone_postcode) & (data.dest_hub != data.hub_postcode)]\nresult.drop(['lat','long','to_postcode'], axis=1).to_excel('hasilCekAV.xlsx')\n","sub_path":"AV-Project/av.py","file_name":"av.py","file_ext":"py","file_size_in_byte":3110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"341407131","text":"def dump_line(result, array, add_line_end=True):\n for elm in array:\n result += elm\n result += ' '\n\n result = result.rstrip()\n\n if add_line_end is True:\n result+= '\\n'\n\n return result\n\n\ndef check_int(s):\n if s[0] in ('-', '+'):\n return s[1:].isdigit()\n return s.isdigit()\n\n\ndef arithmetic_arranger(problems, show_results=False):\n import re\n\n if len(problems) > 5:\n return \"Error: Too many problems.\"\n\n L = None\n R = None\n\n lefts = []\n rights = []\n separators = []\n results = []\n\n for problem in problems:\n p = list(filter(lambda x: x is not None, re.split('(\\+)|(-)|(\\/)|(\\*)', problem.replace(' ', ''))))\n\n L = p[0]\n op = p[1]\n if op is None or op not in ['+', '-']:\n return \"Error: Operator must be '+' or '-'.\"\n R = p[2]\n\n if check_int(L) is False or check_int(R) is False:\n return \"Error: Numbers must only contain digits.\"\n if len(L) > 4 or len(R) > 4:\n return \"Error: Numbers cannot be more than four digits.\"\n\n result = None\n if show_results is True:\n result = str(eval(L + op + R))\n\n if len(L) > len(R):\n lefts.append(' ' + L)\n rights.append(op + ' ' + (' ' * (len(L) - len(R))) + R)\n separators.append('-' * (len(L) + 2))\n\n if show_results is True:\n results.append(' ' * (len(' ' + L) - len(result)) + str(eval(L + op + R)))\n\n\n if len(L) <= len(R):\n lefts.append(' ' + (' ' * (len(R) - len(L))) + L)\n rights.append(op + ' ' + R)\n separators.append('-' * (len(R) + 2))\n\n if show_results is True:\n results.append(' ' * ((len(R) + 2) - len(result)) + str(eval(L + op + R)))\n\n res = ''\n res = dump_line(res, lefts)\n res = dump_line(res, rights)\n if show_results is True:\n res = dump_line(res, separators)\n res = dump_line(res, results, add_line_end=False)\n else:\n res = dump_line(res, separators, add_line_end=False)\n \n return res\n","sub_path":"scientific_computing_with_python/scientific_computing_with_python_projects/arithmetic_formatter/arithmetic_arranger.py","file_name":"arithmetic_arranger.py","file_ext":"py","file_size_in_byte":2102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"229403540","text":"#!/usr/bin/env python3\n\nimport rospy\nimport os,sys\nimport actionlib\n\n# move_base is the package that takes goals for navigation\n# there are different implemenetations with a common interface\nfrom move_base_msgs.msg import MoveBaseAction, MoveBaseGoal\n\n# You need to know the coordinates that the map you are working\n# in is. I estimated these numbers using the turtlebot3_world\n# map from Turtlebot3. The center of the map is (0.0, 0.0, 0.0); each grid is 1m.\n\n#The first waypoint array is x,y,z location. \n#The second one is a \"quaternion\" defining an orientation. \n# Quaternions are a different mathematical represetnation \n#for \"euler angles\", yaw, pitch and roll.\n\n#path planning sequences (loop phase)\nwaypoints = [\n [ (-0.5, 0.0, 0.0),\n (0.0, 0.0, 0.0, 1.0)],\n [ (0.0, 2.0, 0.0),\n (0.0, 0.0, 0.0, 1.0)]\n]\n\ndef goal_pose(pose):\n\tgoal_pose = MoveBaseGoal()\n\tgoal_pose.target_pose.header.frame_id = 'map'\n\tgoal_pose.target_pose.pose.position.x = pose[0][0]\n\tgoal_pose.target_pose.pose.position.y = pose[0][1]\n\tgoal_pose.target_pose.pose.position.z = pose[0][2]\n\tgoal_pose.target_pose.pose.orientation.x = pose[1][0]\n\tgoal_pose.target_pose.pose.orientation.y = pose[1][1]\n\tgoal_pose.target_pose.pose.orientation.z = pose[1][2]\n\tgoal_pose.target_pose.pose.orientation.w = pose[1][3]\n\treturn goal_pose\n\n# Main program starts here\nif __name__ == '__main__':\n\trospy.init_node('Navigation_Node')\n\tclient = actionlib.SimpleActionClient('move_base', MoveBaseAction)\n\n \t # wait for action server to be ready\n\tclient.wait_for_server()\n\n \t# Loop until ^c; delete this line if you want the TB3 to stop at the last waypoint\n\twhile not rospy.is_shutdown():\n\n \t# repeat the waypoints over and over again\n \tfor pose in waypoints:\n \t\tgoal = goal_pose(pose)\n \t\tprint(\"Going for goal: \", goal)\n \t\tclient.send_goal(goal)\n \t\tclient.wait_for_result()\n\n","sub_path":"src/path_planning.py","file_name":"path_planning.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"503726021","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@author: 代码医生工作室 \n@公众号:xiangyuejiqiren (内有更多优秀文章及学习资料)\n@来源: <深度学习之TensorFlow工程化项目实战>配套代码 (700+页)\n@配套代码技术支持:bbs.aianaconda.com (有问必答)\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\ntf.compat.v1.disable_v2_behavior()\n#在内存中生成模拟数据\ndef GenerateData(datasize = 100 ):\n train_X = np.linspace(-1, 1, datasize) #train_X为-1到1之间连续的100个浮点数\n train_Y = 2 * train_X + np.random.randn(*train_X.shape) * 0.3 # y=2x,但是加入了噪声\n return train_X, train_Y #以生成器的方式返回\n\ntrain_data = GenerateData() \n\nbatch_size=10\n\ndef train_input_fn(train_data, batch_size): #定义训练数据集输入函数\n #构造数据集的组成:一个特征输入,一个标签输入\n dataset = tf.data.Dataset.from_tensor_slices( ( train_data[0],train_data[1]) ) \n dataset = dataset.shuffle(1000).repeat().batch(batch_size) #将数据集乱序、重复、批次划分. \n return dataset #返回数据集 \n\n\n\n#定义生成loss可视化的函数\nplotdata = { \"batchsize\":[], \"loss\":[] }\ndef moving_average(a, w=10):\n if len(a) < w: \n return a[:] \n return [val if idx < w else sum(a[(idx-w):idx])/w for idx, val in enumerate(a)]\n\ntf.compat.v1.reset_default_graph()\n\n\nfeatures = tf.compat.v1.placeholder(\"float\",[None])#重新定义占位符\nlabels = tf.compat.v1.placeholder(\"float\",[None])\n\n#其他网络结构不变\nW = tf.Variable(tf.random.normal([1]), name=\"weight\")\nb = tf.Variable(tf.zeros([1]), name=\"bias\")\npredictions = tf.multiply(tf.cast(features,dtype = tf.float32), W)+ b# 前向结构\nloss = tf.compat.v1.losses.mean_squared_error(labels=labels, predictions=predictions)#定义损失函数\n\nglobal_step = tf.compat.v1.train.get_or_create_global_step()#重新定义global_step\n\noptimizer = tf.compat.v1.train.AdagradOptimizer(learning_rate=0.1)\ntrain_op = optimizer.minimize(loss, global_step=global_step)\n\nsaver = tf.compat.v1.train.Saver(tf.compat.v1.global_variables(), max_to_keep=1)#重新定义saver\n\n# 定义学习参数\ntraining_epochs = 500 #设置迭代次数为500\ndisplay_step = 2\n\ndataset = train_input_fn(train_data, batch_size) #重复使用输入函数train_input_fn\none_element = tf.compat.v1.data.make_one_shot_iterator(dataset).get_next() #获得输入数据源张量 \n\nwith tf.compat.v1.Session() as sess:\n\n #恢复估算器检查点文件\n savedir = \"myestimatormode/\" \n kpt = tf.train.latest_checkpoint(savedir) #找到检查点文件\n print(\"kpt:\",kpt)\n saver.restore(sess, kpt) #恢复检查点数据\n \n # 向模型输入数据\n while global_step.eval() < training_epochs:\n step = global_step.eval() \n x,y =sess.run(one_element)\n\n sess.run(train_op, feed_dict={features: x, labels: y})\n\n #显示训练中的详细信息\n if step % display_step == 0:\n vloss = sess.run(loss, feed_dict={features: x, labels: y})\n print (\"Epoch:\", step+1, \"cost=\", vloss)\n if not (vloss == \"NA\" ):\n plotdata[\"batchsize\"].append(global_step.eval())\n plotdata[\"loss\"].append(vloss)\n saver.save(sess, savedir+\"linermodel.cpkt\", global_step)\n \n print (\" Finished!\")\n saver.save(sess, savedir+\"linermodel.cpkt\", global_step)\n \n print (\"cost=\", sess.run(loss, feed_dict={features: x, labels: y}))\n\n\n \n plotdata[\"avgloss\"] = moving_average(plotdata[\"loss\"])\n plt.figure(1)\n plt.subplot(211)\n plt.plot(plotdata[\"batchsize\"], plotdata[\"avgloss\"], 'b--')\n plt.xlabel('Minibatch number')\n plt.ylabel('Loss')\n plt.title('Minibatch run vs. Training loss')\n \n plt.show()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"tf2code/Chapter6/code6-9/code6-9-TF2.py","file_name":"code6-9-TF2.py","file_ext":"py","file_size_in_byte":3887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"306194517","text":"from django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom django.test import TestCase\n\nfrom risks.models import RiskType, FieldType\n\nTEST_RISK = {\n 'name': 'test risk',\n}\n\n\nclass FieldTypeTest(TestCase):\n \"\"\"Tests for field types.\"\"\"\n\n @classmethod\n def setUpTestData(cls):\n cls.risk = RiskType.objects.create(name=TEST_RISK['name'])\n\n def test_can_create(self):\n \"\"\"Instance should be able to be created.\"\"\"\n expected = FieldType.objects.first\n ftype = FieldType.objects.create(name='first_name')\n self.assertEqual(\n ftype,\n expected(),\n 'The object was not created properly, instead got %s' % ftype\n )\n\n def test_can_create_with_no_risk(self):\n \"\"\"Instance should be able to be created without a RiskType.\"\"\"\n expected = FieldType.objects.first\n ftype = FieldType.objects.create(name='first_name')\n self.assertEqual(\n ftype,\n expected(),\n 'FieldType creation without risktype failed: %s' % ftype\n )\n\n def test_relationship_accessor(self):\n \"\"\"Instance should be able to be attached to a RiskType.\"\"\"\n expected = RiskType\n ftype = FieldType.objects.create(name='first_name', risk=self.risk)\n self.assertIsInstance(\n ftype.risk,\n expected,\n 'FieldType reverse relationship accessor returned wrong object '\n 'type, %s' % ftype.risk\n )\n\n\nclass RiskModelTest(TestCase):\n \"\"\"\n Tests for risk model.\n \"\"\"\n\n @classmethod\n def setUpTestData(cls):\n cls.field1 = FieldType.objects.create(name='field1',\n data_type=2)\n cls.field2 = FieldType.objects.create(name='field2',\n data_type=0)\n\n def test_can_create_risk(self):\n \"\"\"\n Risk type should be able to be created.\n \"\"\"\n expected = RiskType.objects.first\n rtype = RiskType.objects.create(name='first_name')\n self.assertEqual(\n rtype,\n expected(),\n 'The object was not created properly, instead got %s' % rtype\n )\n\n def test_bulk_add_fields_works_with_valid_nonexistent_data(self):\n \"\"\"\n The function should add several field types to its ManyToMany\n accessor, creating as necessary.\n\n This test is configured to automatically passed, as it tests\n a function that uses bulk_create, which does not create primary\n keys for SQL engines that are not postgres.\n \"\"\"\n if 'postgres' not in settings.DATABASES['default']['ENGINE']:\n pass\n else:\n expected = 'f2'\n fields = [\n {'name': 'f1', 'data_type': 0},\n {'name': 'f2', 'data_type': 0},\n {'name': 'f3', 'data_type': 0},\n {'name': 'f4', 'data_type': 0},\n ]\n risk = RiskType.objects.create(name='Test risk')\n risk.bulk_add_fields(fields)\n self.assertIn(\n expected,\n risk.fields.all().values_list('name', flat=True),\n 'The function failed to process all nonexistent data',\n )\n\n def test_bulk_add_fields_works_with_valid_existing_data(self):\n \"\"\"\n The function should add several field types to its ManyToMany\n accessor, retrieving as necessary.\n\n This test is configured to automatically passed, as it tests\n a function that uses bulk_create, which does not create primary\n keys for SQL engines that are not postgres.\n \"\"\"\n if 'postgres' not in settings.DATABASES['default']['ENGINE']:\n pass\n else:\n expected = 'f2'\n fields = [\n {'name': 'f1', 'data_type': 0},\n {'name': 'f2', 'data_type': 0},\n {'name': 'f3', 'data_type': 0},\n {'name': 'f4', 'data_type': 0},\n ]\n FieldType.objects.bulk_create(\n [FieldType(**field) for field in fields]\n )\n risk = RiskType.objects.create(name='Test risk')\n risk.bulk_add_fields(fields)\n self.assertIn(\n expected,\n risk.fields.all().values_list('name', flat=True),\n 'The function failed to process all existing data',\n )\n\n def test_bulk_add_fields_works_with_valid_mixed_data(self):\n \"\"\"\n The function should add several field types to its ManyToMany\n accessor, retrieving or creating as necessary.\n\n This test is configured to automatically passed, as it tests\n a function that uses bulk_create, which does not create primary\n keys for SQL engines that are not postgres.\n \"\"\"\n if 'postgres' not in settings.DATABASES['default']['ENGINE']:\n pass\n else:\n expected = 'f2'\n fields = [\n {'name': 'f1', 'data_type': 0},\n {'name': 'f2', 'data_type': 0},\n {'name': 'f3', 'data_type': 0},\n {'name': 'f4', 'data_type': 0},\n ]\n FieldType.objects.bulk_create(\n [FieldType(**field) for field in fields[:2]]\n )\n risk = RiskType.objects.create(name='Test risk')\n risk.bulk_add_fields(fields)\n self.assertIn(\n expected,\n risk.fields.all().values_list('name', flat=True),\n 'The function failed to process mixed data',\n )\n\n def test_bulk_add_fields_fails_if_arg_not_iterable(self):\n \"\"\"\n The function should raise a validation error if a non-iterable\n is passed.\n \"\"\"\n expected = ValidationError\n field = 1\n risk = RiskType.objects.create(name='Test risk')\n self.assertRaises(\n ValidationError,\n lambda x: risk.bulk_add_fields(field),\n 'The function did not raise a validation error'\n )\n","sub_path":"backend/risks/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":6130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"497179719","text":"# Copyright 2013: Mirantis Inc.\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 random\nimport string\nimport time\n\nfrom rally.benchmark import base\nfrom rally.benchmark import utils as bench_utils\nfrom rally import utils\n\n\nclass NovaScenario(base.Scenario):\n\n @classmethod\n def _boot_server(cls, server_name, image_id, flavor_id, **kwargs):\n \"\"\"Boots one server.\n\n Returns when the server is actually booted and is in the \"Active\"\n state.\n\n :param server_name: String used to name the server\n :param image_id: ID of the image to be used for server creation\n :param flavor_id: ID of the flavor to be used for server creation\n :param **kwargs: Other optional parameters to initialize the server\n\n :returns: Created server object\n \"\"\"\n\n if 'security_groups' not in kwargs:\n kwargs['security_groups'] = ['rally_open']\n else:\n if 'rally_open' not in kwargs['security_groups']:\n kwargs['security_groups'].append('rally_open')\n\n server = cls.clients(\"nova\").servers.create(\n server_name, image_id, flavor_id, **kwargs)\n # NOTE(msdubov): It is reasonable to wait 5 secs before starting to\n # check whether the server is ready => less API calls.\n time.sleep(5)\n server = utils.wait_for(server,\n is_ready=bench_utils.resource_is(\"ACTIVE\"),\n update_resource=bench_utils.get_from_manager(),\n timeout=600, check_interval=3)\n return server\n\n @classmethod\n def _reboot_server(cls, server, soft=True):\n \"\"\"Reboots the given server using hard or soft reboot.\n\n A reboot will be issued on the given server upon which time\n this method will wait for the server to become active.\n\n :param server: The server to reboot.\n :param soft: False if hard reboot should be used, otherwise\n soft reboot is done (default).\n \"\"\"\n server.reboot(reboot_type=(\"SOFT\" if soft else \"HARD\"))\n time.sleep(5)\n utils.wait_for(server, is_ready=bench_utils.resource_is(\"ACTIVE\"),\n update_resource=bench_utils.get_from_manager(),\n timeout=600, check_interval=3)\n\n @classmethod\n def _start_server(cls, server):\n \"\"\"Starts the given server.\n\n A start will be issued for the given server upon which time\n this method will wait for it to become ACTIVE.\n\n :param server: The server to start and wait to become ACTIVE.\n \"\"\"\n server.start()\n utils.wait_for(server, is_ready=bench_utils.resource_is(\"ACTIVE\"),\n update_resource=bench_utils.get_from_manager(),\n timeout=600, check_interval=2)\n\n @classmethod\n def _stop_server(cls, server):\n \"\"\"Stop the given server.\n\n Issues a stop on the given server and waits for the server\n to become SHUTOFF.\n\n :param server: The server to stop.\n \"\"\"\n server.stop()\n utils.wait_for(server, is_ready=bench_utils.resource_is(\"SHUTOFF\"),\n update_resource=bench_utils.get_from_manager(),\n timeout=600, check_interval=2)\n\n @classmethod\n def _rescue_server(cls, server):\n \"\"\"Rescue the given server.\n\n Returns when the server is actually rescue and is in the \"Rescue\"\n state.\n\n :param server: Server object\n \"\"\"\n server.rescue()\n time.sleep(2)\n utils.wait_for(server, is_ready=bench_utils.resource_is(\"RESCUE\"),\n update_resource=bench_utils.get_from_manager(),\n timeout=600, check_interval=3)\n\n @classmethod\n def _unrescue_server(cls, server):\n \"\"\"Unrescue the given server.\n\n Returns when the server is unrescue and waits to become ACTIVE\n\n :param server: Server object\n \"\"\"\n server.unrescue()\n time.sleep(2)\n utils.wait_for(server, is_ready=bench_utils.resource_is(\"ACTIVE\"),\n update_resource=bench_utils.get_from_manager(),\n timeout=600, check_interval=3)\n\n @classmethod\n def _suspend_server(cls, server):\n \"\"\"Suspends the given server.\n\n Returns when the server is actually suspended and is in the \"Suspended\"\n state.\n\n :param server: Server object\n \"\"\"\n server.suspend()\n time.sleep(2)\n utils.wait_for(server, is_ready=bench_utils.resource_is(\"SUSPENDED\"),\n update_resource=bench_utils.get_from_manager(),\n timeout=600, check_interval=3)\n\n @classmethod\n def _delete_server(cls, server):\n \"\"\"Deletes the given server.\n\n Returns when the server is actually deleted.\n\n :param server: Server object\n \"\"\"\n server.delete()\n utils.wait_for(server, is_ready=bench_utils.is_none,\n update_resource=bench_utils.get_from_manager(),\n timeout=600, check_interval=3)\n\n @classmethod\n def _delete_all_servers(cls):\n \"\"\"Deletes all servers in current tenant.\"\"\"\n servers = cls.clients(\"nova\").servers.list()\n for server in servers:\n cls._delete_server(server)\n\n @classmethod\n def _delete_image(cls, image):\n \"\"\"Deletes the given image.\n\n Returns when the image is actually deleted.\n\n :param image: Image object\n \"\"\"\n image.delete()\n utils.wait_for(image, is_ready=bench_utils.resource_is(\"DELETED\"),\n update_resource=bench_utils.get_from_manager(),\n timeout=600, check_interval=3)\n\n @classmethod\n def _create_image(cls, server):\n \"\"\"Creates an image of the given server\n\n Uses the server name to name the created image. Returns when the image\n is actually created and is in the \"Active\" state.\n\n :param server: Server object for which the image will be created\n\n :returns: Created image object\n \"\"\"\n image_uuid = cls.clients(\"nova\").servers.create_image(server,\n server.name)\n image = cls.clients(\"nova\").images.get(image_uuid)\n image = utils.wait_for(image,\n is_ready=bench_utils.resource_is(\"ACTIVE\"),\n update_resource=bench_utils.get_from_manager(),\n timeout=600, check_interval=3)\n return image\n\n @classmethod\n def _boot_servers(cls, name_prefix, image_id, flavor_id,\n requests, instances_per_request=1, **kwargs):\n \"\"\"Boots multiple servers.\n\n Returns when all the servers are actually booted and are in the\n \"Active\" state.\n\n :param name_prefix: The prefix to use while naming the created servers.\n The rest of the server names will be '_No.'\n :param image_id: ID of the image to be used for server creation\n :param flavor_id: ID of the flavor to be used for server creation\n :param requests: Number of booting requests to perform\n :param instances_per_request: Number of instances to boot\n per each request\n\n :returns: List of created server objects\n \"\"\"\n for i in range(requests):\n cls.clients(\"nova\").servers.create('%s_%d' % (name_prefix, i),\n image_id, flavor_id,\n min_count=instances_per_request,\n max_count=instances_per_request,\n **kwargs)\n # NOTE(msdubov): Nova python client returns only one server even when\n # min_count > 1, so we have to rediscover all the\n # created servers manyally.\n servers = filter(lambda server: server.name.startswith(name_prefix),\n cls.clients(\"nova\").servers.list())\n time.sleep(5)\n servers = [utils.wait_for(server,\n is_ready=bench_utils.resource_is(\"ACTIVE\"),\n update_resource=bench_utils.\n get_from_manager(),\n timeout=600, check_interval=3)\n for server in servers]\n return servers\n\n @classmethod\n def _generate_random_name(cls, length):\n return ''.join(random.choice(string.lowercase) for i in range(length))\n","sub_path":"rally/benchmark/scenarios/nova/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"487071364","text":"# If using this to analyze data other than cmv, you need to change the timepoints_dictionary function with number of\n# data sets and the correction factors. You will also need to change the plot functions to change the timepoints\n# list in both plotting functions\n\n\nimport os\nfrom plotting import plot, plotlog2, heatplots\n\n\ndef check_dirs(directory):\n if not os.path.exists(directory + \"/Input/Control/Deduplicated\"):\n os.makedirs(directory + \"/Input/Control/Deduplicated\")\n\n if not os.path.exists(directory + \"/Input/Flavo/Deduplicated\"):\n os.makedirs(directory + \"/Input/Flavo/Deduplicated\")\n\n if not os.path.exists(directory + \"/Output\"):\n os.makedirs(directory + \"/Output\")\n\n if not os.path.exists(directory + \"/Output/Normalized\"):\n os.makedirs(directory + \"/Output/Normalized\")\n\n if not os.path.exists(directory + \"/Plots\"):\n os.makedirs(directory + \"/Plots\")\n\n if not os.path.exists(directory + \"/Plots/Heatmaps\"):\n os.makedirs(directory + \"/Plots/Heatmaps\")\n\n\ndef deduplicate(input_file_name):\n # This function finds the gene line with the shortest region and stores it in a dictionary with the line number\n shortest_region = dict()\n previous_line = \"\"\n\n with open(input_file_name) as input_file:\n for line_number, line in enumerate(input_file):\n if line_number % 2 == 0:\n gene_name = line.split('\\t')[3]\n if gene_name not in shortest_region:\n # Arbitrarily set to large value so the next line will switch it\n shortest_region[gene_name] = 10000000000000000, previous_line, line\n else:\n region_length = int(line.split('\\t')[3])\n if region_length < shortest_region[gene_name][0]:\n # Change the shortest_region to the current line\n shortest_region[gene_name] = region_length, previous_line, line\n\n previous_line = line\n\n output_file_name = input_file_name[0:input_file_name.rfind('/')] + \"/Deduplicated/Deduplicated\"\\\n + input_file_name[input_file_name.rfind('/')+1:]\n\n # Now print out all of the shortest regions into the output file\n with open(output_file_name, 'w') as output_file:\n for _, v in shortest_region.items():\n output_file.write(v[1] + v[2])\n\n\ndef timepoints_dictionary(input_file_name, dictionary):\n # This makes a dicitonary and changes the values\n\n with open(input_file_name) as input_file:\n for i, line in enumerate(input_file):\n fields = line.split('\\t')\n if i % 2 == 0:\n gene_name = fields[3]\n\n if gene_name not in dictionary:\n dictionary[gene_name] = [None] * 7\n else:\n value = int(fields[1])\n\n # Depending on the timepoint, it will change the value and enter it into the dictionary array\n\n if \"0\" in input_file_name and \"Flavo\" not in input_file_name:\n correction_factor = .9030 * .6234\n dictionary[gene_name][0] = value * correction_factor\n\n elif \"0\" in input_file_name and \"Flavo\" in input_file_name:\n correction_factor = .7788 * .7165\n dictionary[gene_name][0] = value * correction_factor\n\n elif \"4h\" in input_file_name and \"24\" not in input_file_name and \"Flavo\" not in input_file_name:\n correction_factor = .9630 * .7826\n dictionary[gene_name][1] = value * correction_factor\n\n elif \"4h\" in input_file_name and \"24\" not in input_file_name and \"Flavo\" in input_file_name:\n correction_factor = .8944 * .7693\n dictionary[gene_name][1] = value * correction_factor\n\n elif \"12\" in input_file_name and \"Flavo\" not in input_file_name:\n correction_factor = 1.0048 * .6639\n dictionary[gene_name][2] = value * correction_factor\n\n elif \"12\" in input_file_name and \"Flavo\" in input_file_name:\n correction_factor = .9065 * .8790\n dictionary[gene_name][2] = value * correction_factor\n\n elif \"24\" in input_file_name and \"Flavo\" not in input_file_name:\n correction_factor = .9739 * 1.2260\n dictionary[gene_name][3] = value * correction_factor\n\n elif \"24\" in input_file_name and \"Flavo\" in input_file_name:\n correction_factor = .9314 * .8726\n dictionary[gene_name][3] = value * correction_factor\n\n elif \"48\" in input_file_name and \"Flavo\" not in input_file_name:\n correction_factor = 1.1271 * 2.3283\n dictionary[gene_name][4] = value * correction_factor\n\n elif \"48\" in input_file_name and \"Flavo\" in input_file_name:\n correction_factor = 1.1686 * 1.7324\n dictionary[gene_name][4] = value * correction_factor\n\n elif \"72\" in input_file_name and \"Flavo\" not in input_file_name and \"PFA\" not in input_file_name:\n correction_factor = 1.0547 * 2.0101\n dictionary[gene_name][5] = value * correction_factor\n\n elif \"72\" in input_file_name and \"Flavo\" in input_file_name and \"PFA\" not in input_file_name:\n correction_factor = 1.1547 * 1.4786\n dictionary[gene_name][5] = value * correction_factor\n\n elif \"72\" in input_file_name and \"Flavo\" not in input_file_name and \"PFA\" in input_file_name:\n correction_factor = 1.4160 * 1.3013\n dictionary[gene_name][6] = value * correction_factor\n\n elif \"72\" in input_file_name and \"Flavo\" in input_file_name and \"PFA\" in input_file_name:\n correction_factor = 1.0101 * 1.1520\n dictionary[gene_name][6] = value * correction_factor\n\n return dictionary\n\n\ndef normalization(input_file_name):\n normalized_file_name = input_file_name[0:input_file_name.rfind('/')] + \"/Normalized/normalized\"\\\n + input_file_name[input_file_name.rfind('/') + 1:]\n\n with open(input_file_name, 'r') as geneFile:\n with open(normalized_file_name, 'w') as normalizedFile:\n for line in geneFile:\n fields = line.split('\\t')\n fields[1] = float(fields[1])\n\n if fields[1] > 20:\n # Normalize the timepoints\n for i in range(2, len(fields)):\n fields[i] = float(fields[i]) / float(fields[1])\n\n fields[1] = 1\n normalizedFile.write('\\t'.join(map(str, fields)) + '\\n')\n\n\nif __name__ == \"__main__\":\n directory = os.getcwd()\n check_dirs(directory)\n\n # Deduplicate for all control timepoints\n for filename in os.listdir(directory + \"/Input/Control\"):\n if filename.endswith(\".bed\"):\n deduplicate(directory + \"/Input/Control/\" + filename)\n\n # Deduplicate for all flavo timepoints\n for filename in os.listdir(directory + \"/Input/Flavo\"):\n if filename.endswith(\".bed\"):\n deduplicate(directory + \"/Input/Flavo/\" + filename)\n\n # These dictionaries contain the timepoint data for each gene\n controlDict = dict()\n flavoDict = dict()\n\n # Fill the dictionary\n for filename in os.listdir(directory + \"/Input/Control/Deduplicated\"):\n if filename.endswith(\".bed\"):\n controlDict = timepoints_dictionary(directory + \"/Input/Control/Deduplicated/\" + filename, controlDict)\n\n # Fill the flavoDictionary\n for filename in os.listdir(directory + \"/Input/Flavo/Deduplicated\"):\n if filename.endswith(\".bed\"):\n flavoDictionary = timepoints_dictionary(directory + \"/Input/Flavo/Deduplicated/\" + filename, flavoDict)\n\n # Output all of the control timepoints\n with open(directory + \"/Output/control.txt\", 'w') as controlFile:\n for key in controlDict:\n controlFile.write(key + '\\t' + '\\t'.join(map(str, controlDict[key])) + '\\n')\n\n # This will output the gene name followed by all of the timepoint values\n with open(directory + \"/Output/flavo.txt\", 'w') as flavoFile:\n for key in controlDict:\n flavoFile.write(key + '\\t' + '\\t'.join(map(str, flavoDict[key])) + '\\n')\n\n # Normalize all of the output data\n for filename in os.listdir(directory + \"/Output\"):\n if filename.endswith(\".txt\"):\n normalization(directory + \"/Output/\" + filename)\n\n plot(directory)\n plotlog2(directory)\n heatplots(directory)\n","sub_path":"Timecourse Analysis Main.py","file_name":"Timecourse Analysis Main.py","file_ext":"py","file_size_in_byte":8718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"131990987","text":"#!/usr/bin/env python3\n\nfrom sys import argv, exit\nfrom datetime import datetime\nfrom os import listdir\nfrom os.path import isdir, isfile, join, basename\nfrom fnmatch import fnmatch\nfrom adjust_name import adjust_name\nimport re\n\nif len(argv) != 2:\n\texit(\"Please, specify the folder with *.c files .\\nUsage: {} \".format(argv[0]))\n\ndir = argv[1]\n\nif not isdir(dir):\n\texit(\"Can't find dir: {}\".format(dir))\n\nnames = []\nfor file in listdir(dir):\n\tpath = join(dir, file)\n\tif fnmatch(file, '*.c') and isfile(path):\n\t\tnames.append(file)\n\nprint()\nprint(\"% This file has been automatically generated by {}\".format(argv[0]))\nprint(\"% {}\".format(datetime.now()))\nprint()\n\nfor fullname in sorted(set(names)):\n\tname = fullname.replace('.c', '')\n\tcommand = adjust_name(name)\n\n\t# deal with files of \"normal forms\"\n\tcommand = command.replace('.', '')\n\tprint('\\\\newcommand{\\\\' + command + '}{\\\\mbox{\\\\inl{' + name + '}}\\\\xspace}')\n\nprint()\n\n","sub_path":"StandardAlgorithms/Scripts/generate_example_names.py","file_name":"generate_example_names.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"487670354","text":"# Face Detection Improvement with Live Stream Face Recognition [Harsh Patel]\r\n\r\nimport cv2\r\nimport imutils\r\n\r\n# using the Haar Cascade Classifier\r\nfaceCascade = cv2.CascadeClassifier('../day 2/haarcascade_frontalface_default.xml')\r\n\r\nid = input(\"Enter the Face Recognition ID:\")\r\nsampleNum = 0\r\ncap = cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n ret, image = cap.read()\r\n image = imutils.resize(image, height=300)\r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n\r\n # Detect faces in the image\r\n faces = faceCascade.detectMultiScale(\r\n gray,\r\n scaleFactor=1.2,\r\n minNeighbors=5,\r\n minSize=(30, 30),\r\n flags=cv2.CASCADE_SCALE_IMAGE\r\n )\r\n\r\n print(\"Found {0} faces!\".format(len(faces)))\r\n\r\n # Draw a rectangle around the faces\r\n for (x, y, w, h) in faces:\r\n sampleNum = sampleNum + 1\r\n cv2.imwrite(\"dataset/user.\" + str(id) + \".\" + str(sampleNum) + \".jpg\", gray[y:y + h, x:x + w])\r\n cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n cv2.waitKey(100)\r\n\r\n cv2.imshow(\"Faces found\", image)\r\n cv2.waitKey(1)\r\n if (sampleNum > 40):\r\n break\r\ncv2.destroyAllWindows()\r\n\r\n# Training the Module for Facial Recognition\r\n\r\nimport os\r\nimport numpy as np\r\nimport cv2\r\nfrom PIL import Image\r\n\r\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\r\npath = 'dataset'\r\n\r\ndef getImageWithID(path):\r\n imagePaths = [os.path.join(path, f) for f in os.listdir(path)]\r\n faces = []\r\n IDs = []\r\n for imagePath in imagePaths:\r\n faceImg = Image.open(imagePath).convert('L')\r\n faceNp = np.array(faceImg, 'uint8')\r\n ID = int(os.path.split(imagePath)[-1].split('.')[1])\r\n faces.append(faceNp)\r\n IDs.append(ID)\r\n cv2.imshow(\"traning\", faceNp)\r\n cv2.waitKey(10)\r\n return IDs, faces\r\n\r\nIds, faces = getImageWithID(path)\r\nrecognizer.train(faces, np.array(Ids))\r\nrecognizer.save('recognizer/trainningData.yml')\r\ncv2.destroyAllWindows()\r\n\r\n\r\n\r\n# Recognizing the Face impressions saved and trying for Face Recognition\r\n\r\nimport cv2\r\n\r\nrecognizer = cv2.face.LBPHFaceRecognizer_create()\r\nrecognizer.read('recognizer\\\\trainningData.yml')\r\nid = 0\r\nfont = cv2.FONT_HERSHEY_SIMPLEX\r\nnames = []\r\ncap = cv2.VideoCapture(0)\r\nframe_num = 1\r\nfaceCascade = cv2.CascadeClassifier('../day 2/haarcascade_frontalface_default.xml')\r\n\r\nwhile True:\r\n ret, image = cap.read()\r\n # Create the haar cascade\r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n if frame_num == 1:\r\n\r\n # Detect faces in the image\r\n faces = faceCascade.detectMultiScale(\r\n gray,\r\n scaleFactor=1.2,\r\n minNeighbors=5,\r\n minSize=(30, 30),\r\n flags=cv2.CASCADE_SCALE_IMAGE\r\n )\r\n\r\n print(\"Found {0} faces!\".format(len(faces)))\r\n\r\n # Draw a rectangle around the faces\r\n for (x, y, w, h) in faces:\r\n cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)\r\n tracker = cv2.TrackerCSRT_create()\r\n tracker.init(image, (x, y, w, h))\r\n\r\n (success, box) = tracker.update(image)\r\n # check to see if the tracking was a success\r\n if success:\r\n frame_num = frame_num + 1\r\n (x, y, w, h) = [int(v) for v in box]\r\n cv2.rectangle(image, (x, y), (x + w, y + h),\r\n (255, 0, 0), 2)\r\n id, conf = recognizer.predict(gray[y:y + h, x:x + w])\r\n print(str(id) + \" matched\")\r\n\r\n cv2.putText(image, names[int(id)], (x, y + h + 20), font, .6, (0, 255, 0), 2)\r\n\r\n cv2.imshow(\"Faces found\", image)\r\n if cv2.waitKey(1) == 27:\r\n break\r\ncv2.destroyAllWindows()\r\n\r\n","sub_path":"P08_FaceRecognition/P08 Harsh Patel/DAY 5/Face Detection Final Build.py","file_name":"Face Detection Final Build.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"366353513","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport django.utils.timezone\nimport django.core.validators\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('bloodApp', '0003_auto_20140718_0650'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n name='time',\n field=models.DateTimeField(default=django.utils.timezone.now, verbose_name=b'date published'),\n ),\n migrations.AlterField(\n model_name='user',\n name='userContact',\n field=models.IntegerField(unique=True, max_length=10, validators=[django.core.validators.RegexValidator(regex=b'^\\\\d{10}$', message=b'Length has to be 10', code=b'Invalid number')]),\n ),\n ]\n","sub_path":"bloodApp/migrations/0004_auto_20140718_0652.py","file_name":"0004_auto_20140718_0652.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"156755008","text":"from django.shortcuts import render\nfrom .models import User\nfrom .forms import UserForm\n\n# Create your views here.\ndef index(request):\n usersToShow = User.objects.filter(latitude__isnull=False)[:10]\n context_dict = {'users' : usersToShow}\n return render(request, 'greenbookapp/index.html', context_dict)\n\ndef register(request):\n form = UserForm()\n\n if request.method == 'POST':\n form= UserForm(request.POST)\n if form.is_valid():\n form.save(commit=True)\n return index(request)\n else:\n print(form.errors)\n\n return render(request, 'greenbookapp/register.html', {'form': form})","sub_path":"greenbook/greenbookapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"117642286","text":"def bwt(s):\n\ts+='$'\n\tA = []\n\tst = ''\n\tfor i in range(len(s)):\n\t\t# t = s[:]\n\t\tt = s[len(s)-i:]+s[:len(s)-i]\n\t\t# print(i,t)\n\t\tA.append(t)\n\tA_ = sorted(A)\n\t# st = ''\n\tfor i in range(len(A_)):\n\t\t# print(A_[i])\n\t\tst+=A_[i][-1]\n\treturn st\n\nS = '32144'\nS_ = bwt(S)\nprint(\"\\nBWT(\"+S+\"$) : \"+S_)\n# c = \"423$143\"\n# for i in range(1,5):\n# \tprint(\"inserting \"+str(i))\n# \tfor j in range(len(S)+1):\n# \t\tt = S\n# \t\tt = t[:j]+str(i)+t[j:]\n# \t\t# print(t)\n# \t\tt_ = bwt(t)\n# \t\tprint(t_)\n# \t\tif(t_[:-1] == c):\n# \t\t\tprint(t_)","sub_path":"Code/bwt.py","file_name":"bwt.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"88572805","text":"import json\nfrom os.path import expanduser\nfrom flask import Blueprint, render_template, request, redirect, url_for\nfrom bson.objectid import ObjectId\nfrom universal.connect_db import news_db, lst_src\n\n\ndef get_googlemap_key():\n key_f = expanduser(\"~/.credentials/googlemapapi\")\n with open(key_f) as f:\n key = f.read()\n return key\n\n\nkey = get_googlemap_key().strip()\n\n\nmap_bp = Blueprint(\"map\", __name__)\n\n\n@map_bp.route(\"//\", methods=['GET', 'POST'])\ndef gomap(src, news_id):\n news_collections = news_db[src]\n doc = news_collections.find_one({\"_id\": ObjectId(news_id)})\n content = doc[\"content\"].replace(\"
    \", \"\").strip()\n if \"keywords\" in doc:\n kwords = doc[\"keywords\"]\n else:\n kwords = []\n\n\n all_keywords = []\n for tmp in kwords:\n all_keywords.extend(tmp.values())\n\n if request.method == \"POST\":\n if \"showmap\" in request.form:\n return redirect(url_for(\"map.showall\", src=src, news_id=news_id))\n else:\n tmp = json.loads(request.args['doc'])\n for doc in tmp:\n if doc[\"keyword\"] in all_keywords:\n news_db[src].update(\n {\"_id\": ObjectId(news_id), \"keywords.keyword\":doc[\"keyword\"]},\n {\"$set\": {\"keywords.$\": doc}}\n )\n else:\n news_db[src].update(\n {\"_id\": ObjectId(news_id)},\n {\"$push\": {\"keywords\": doc}}\n )\n return redirect(url_for(\"gomap\", src=src, news_id=news_id))\n else:\n return render_template(\"googlemapapi.html\", src=src, news_id=news_id, content=content, key=key, kwords=kwords)\n\n\n@map_bp.route(\"show//\")\ndef showall(src, news_id):\n news_collections = news_db[src]\n doc = news_collections.find_one({\"_id\": ObjectId(news_id)})\n kwords = []\n if \"keywords\" in doc:\n for kword in doc[\"keywords\"]:\n if \"location\" in kword:\n kword[\"title\"]=kword[\"keyword\"]\n kword[\"location\"][\"lat\"]=float(kword[\"location\"][\"lat\"])\n kword[\"location\"][\"lng\"]=float(kword[\"location\"][\"lng\"])\n kwords.append(kword)\n\n return render_template(\"showallmap.html\",kwords=kwords, key=key)","sub_path":"aerotropolis_app/map/map.py","file_name":"map.py","file_ext":"py","file_size_in_byte":2341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"588449081","text":"\r\na,b,c = map(int,input().split())\r\n\r\ngraph=[[] for _ in range(a+1)]\r\nvisited = [[False]*(a+1)]\r\n\r\nfor _ in range(b):\r\n x,y = map(int, input().split())\r\n graph[x].append(y)\r\n\r\nresult = 0\r\n\r\ndef dfs(v):\r\n global result\r\n if visited[v]:\r\n return\r\n vistied[v]=True\r\n result+=1\r\n for i in graph[v]:\r\n if not visited[i]:\r\n dfs(i)\r\n\r\n\r\n\r\nfor _ in range(c):\r\n v = int(input())\r\n dfs(v)\r\n\r\nprint(result)\r\n","sub_path":"groom_level/domino_dfs_ndb.py","file_name":"domino_dfs_ndb.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"426935141","text":"#!/usr/bin/env python3\n# coding:utf-8 \n\nimport time\nimport datetime\nimport requests\nfrom scrapy.selector import Selector\nimport re\n\nnums = 0\nerror_times = 0\n\ndef spider(erectDate,nothing,page):\n\ttry:\n\t\tinput = requests.post('http://srh.bankofchina.com/search/whpj/search.jsp', data = {'erectDate':erectDate, 'nothing':nothing, 'pjname':'1314', 'page':page})\n\texcept:\n\t\tglobal error_times\n\t\terror_times += 1\n\t\tprint(\"出现错误, 5秒后重试(第%i次)\"%(error_times))\n\t\ttime.sleep(5)\n\t\tspider(erectDate,nothing,page)\n\n\telse:\n\t\tbody = input.text\n\t\tfor row in range(2,22):\n\t\t\trate_output = Selector(text=body).xpath('//tr[%i]/td[4]/text()' %(row)).extract()\n\t\t\ttime_output = Selector(text=body).xpath('//tr[%i]/td[8]/text()' %(row)).extract()\n\t\t\ttry:\n\t\t\t\toutrow = time_output[0]+\",\"+rate_output[0]+\"\\n\"\n\t\t\t\tout.write(outrow)\n\t\t\t\tprint(time_output[0]+','+rate_output[0])\n\t\t\t\tglobal nums\n\t\t\t\tnums += 1\n\t\t\texcept IndexError:\n\t\t\t\tbreak\n\t\tprint(\"已抓取第%i页, 共%i条数据\\n\" %(page,nums))\n\ntoday_noFormat = datetime.date.today()\nlastweek_noFormat = today_noFormat - datetime.timedelta(days=6)\ntoday = str(today_noFormat)\nlastweek = str(lastweek_noFormat)\n\nprint(\"中行英镑牌价抓取脚本 Ver:0.8\")\nprint(\"输入抓取汇率的起始日期(回车默认为7天前:%s):\"%(lastweek))\nerectDate = input()\nif not len(erectDate.strip()):\n\terectDate = lastweek\n\nprint(\"输入抓取汇率的结束日期(回车默认为今天:%s):\"%(today))\nnothing = input()\nif not len(nothing.strip()):\n\tnothing = today\n\ninput = requests.post('http://srh.bankofchina.com/search/whpj/search.jsp', data = {'erectDate':erectDate, 'nothing':nothing, 'pjname':'1314', 'page':'1'})\nbody = input.text\nsearchOBJ = re.search(r'var m_nRecordCount = (.*);',body)\npages = (int(searchOBJ.group(1))//20)+1\n\nout = open('/Users/bob/Desktop/boc-s.csv','a',newline='')\nfor page in range(1,(pages+1)):\n\tspider(erectDate,nothing,page)\n\nout.close()\nprint(\"\")\nprint('-' * 28,\"\\n\")\nprint(\"抓取完毕!\")\nprint(\"共出现错误%i次\"%(error_times))","sub_path":"boc_spider.py","file_name":"boc_spider.py","file_ext":"py","file_size_in_byte":2010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"489333359","text":"import copy\nimport datetime\nimport uuid\n\nfrom dataclasses import dataclass\nfrom unittest import TestCase\n\nfrom django.core.exceptions import ImproperlyConfigured\nfrom rest_framework import fields, serializers\nfrom rest_framework_dataclasses.serializers import DataclassSerializer\n\nfrom . import fixtures\n\n\nclass SerializerTestCase(TestCase):\n def test_person(self):\n class PersonSerializer(DataclassSerializer):\n email = fields.EmailField()\n\n class Meta:\n dataclass = fixtures.Person\n fields = (serializers.ALL_FIELDS, 'age')\n read_only_fields = ('birth_date', )\n\n serializer = PersonSerializer()\n f = serializer.get_fields()\n self.assertEqual(len(f), 9)\n\n self.assertIsInstance(f['id'], fields.UUIDField)\n self.assertFalse(f['id'].allow_null)\n\n self.assertIsInstance(f['name'], fields.CharField)\n self.assertFalse(f['name'].allow_null)\n\n self.assertIsInstance(f['email'], fields.EmailField)\n\n self.assertIsInstance(f['alive'], fields.BooleanField)\n self.assertFalse(f['alive'].allow_null)\n\n self.assertIsInstance(f['weight'], fields.FloatField)\n self.assertTrue(f['weight'].allow_null)\n\n self.assertIsInstance(f['birth_date'], fields.DateField)\n self.assertTrue(f['birth_date'].read_only)\n\n self.assertIsInstance(f['phone'], fields.ListField)\n self.assertFalse(f['phone'].allow_null)\n self.assertIsInstance(f['phone'].child, fields.CharField)\n self.assertFalse(f['phone'].child.allow_null)\n\n self.assertIsInstance(f['movie_ratings'], fields.DictField)\n self.assertTrue(f['movie_ratings'].allow_null)\n self.assertIsInstance(f['movie_ratings'].child, fields.IntegerField)\n self.assertFalse(f['movie_ratings'].child.allow_null)\n\n self.assertIsInstance(f['age'], fields.ReadOnlyField)\n\n def test_exclude(self):\n class PetSerializer(DataclassSerializer):\n class Meta:\n dataclass = fixtures.Pet\n exclude = ('animal', )\n\n serializer = PetSerializer()\n f = serializer.get_fields()\n self.assertNotIn('animal', f)\n\n def test_extra_kwargs(self):\n class StreetSerializer(DataclassSerializer):\n class Meta:\n dataclass = fixtures.Street\n extra_kwargs = {\n 'length': {'max_digits': 3, 'decimal_places': 2},\n 'houses': {'label': 'Houses on street', 'child_kwargs': {\n 'extra_kwargs': {\n 'address': {'max_length': 20},\n 'owner': {'label': 'House owner'},\n 'residents': {'child_kwargs': {\n 'extra_kwargs': {\n 'movie_ratings': {'child_kwargs': {'min_value': 0, 'max_value': 10}}\n }\n }\n }}\n }}\n }\n\n serializer = StreetSerializer()\n f = serializer.get_fields()\n\n self.assertIsInstance(f['length'], fields.DecimalField)\n self.assertEqual(f['length'].decimal_places, 2)\n self.assertEqual(f['length'].max_digits, 3)\n\n self.assertEqual(f['houses'].label, 'Houses on street')\n\n house_fields = f['houses'].child.get_fields()\n self.assertEqual(house_fields['address'].max_length, 20)\n self.assertEqual(house_fields['owner'].label, 'House owner')\n\n resident_fields = house_fields['residents'].child.get_fields()\n self.assertEqual(resident_fields['movie_ratings'].child.min_value, 0)\n self.assertEqual(resident_fields['movie_ratings'].child.max_value, 10)\n\n\nclass SerializationTestCase(TestCase):\n person_instance = fixtures.alice\n person_serialized = {\n 'id': str(person_instance.id),\n 'name': person_instance.name,\n 'email': person_instance.email,\n 'alive': person_instance.alive,\n 'phone': person_instance.phone,\n 'weight': person_instance.weight,\n 'birth_date': person_instance.birth_date.isoformat(),\n 'movie_ratings': person_instance.movie_ratings\n }\n\n class PersonSerializer(DataclassSerializer):\n class Meta:\n dataclass = fixtures.Person\n\n def test_serialize(self):\n serializer = self.PersonSerializer(instance=self.person_instance)\n self.assertDictEqual(serializer.data, self.person_serialized)\n\n def test_deserialize(self):\n serializer = self.PersonSerializer(data=self.person_serialized)\n serializer.is_valid(raise_exception=True)\n result = serializer.validated_data\n\n self.assertIsInstance(result['id'], uuid.UUID)\n self.assertIsInstance(result['alive'], bool)\n self.assertIsInstance(result['weight'], float)\n self.assertIsInstance(result['birth_date'], datetime.date)\n self.assertIsInstance(result['movie_ratings'], dict)\n\n def test_create(self):\n serializer = self.PersonSerializer(data=self.person_serialized)\n serializer.is_valid(raise_exception=True)\n person = serializer.save()\n\n self.assertIsInstance(person, fixtures.Person)\n self.assertEqual(person, self.person_instance)\n\n def test_update(self):\n instance = copy.deepcopy(fixtures.charlie)\n serializer = self.PersonSerializer(instance=instance, data=self.person_serialized)\n serializer.is_valid(raise_exception=True)\n result = serializer.save()\n\n self.assertIsInstance(result, fixtures.Person)\n self.assertIs(result, instance)\n self.assertEqual(result, self.person_instance)\n\n\nclass NestedSerializationTestCase(TestCase):\n house_dataclass = fixtures.alices_house\n house_serialized = {\n 'address': house_dataclass.address,\n 'owner': {\n 'id': str(house_dataclass.owner.id),\n 'name': house_dataclass.owner.name,\n 'email': house_dataclass.owner.email,\n 'alive': house_dataclass.owner.alive,\n 'phone': house_dataclass.owner.phone,\n 'weight': house_dataclass.owner.weight,\n 'birth_date': house_dataclass.owner.birth_date.isoformat(),\n 'movie_ratings': house_dataclass.owner.movie_ratings\n },\n 'residents': [\n {\n 'id': str(house_dataclass.residents[0].id),\n 'name': house_dataclass.residents[0].name,\n 'email': house_dataclass.residents[0].email,\n 'alive': house_dataclass.residents[0].alive,\n 'phone': house_dataclass.residents[0].phone,\n 'weight': None,\n 'birth_date': None,\n 'movie_ratings': None\n }\n ],\n 'room_area': house_dataclass.room_area\n }\n\n def test_create(self):\n serializer = DataclassSerializer(dataclass=fixtures.House, data=self.house_serialized)\n serializer.is_valid(raise_exception=True)\n house = serializer.save()\n\n self.assertIsInstance(house, fixtures.House)\n self.assertIsInstance(house.owner, fixtures.Person)\n self.assertIsInstance(house.residents, list)\n self.assertIsInstance(house.residents[0], fixtures.Person)\n self.assertIsInstance(house.room_area, dict)\n self.assertEqual(house, self.house_dataclass)\n\n\nclass ErrorsTestCase(TestCase):\n def test_invalid_dataclass_specification(self):\n class ExplicitPersonSerializer(DataclassSerializer):\n class Meta:\n dataclass = fixtures.Person\n\n class AnonymousPersonSerializer(DataclassSerializer):\n class Meta:\n pass\n\n with self.assertRaises(AssertionError):\n ExplicitPersonSerializer(dataclass=fixtures.Person).get_fields()\n\n with self.assertRaises(AssertionError):\n AnonymousPersonSerializer().get_fields()\n\n def test_non_dataclass(self):\n class Empty:\n pass\n\n with self.assertRaises(ValueError):\n DataclassSerializer(dataclass=Empty).get_fields()\n\n def test_field_specification(self):\n class InvalidSerializer(DataclassSerializer):\n email = serializers.EmailField()\n\n class Meta:\n dataclass = fixtures.Person\n\n # invalid `fields` specification\n InvalidSerializer.Meta.fields = 'invalid'\n with self.assertRaises(TypeError):\n InvalidSerializer().get_fields()\n\n # declared field not in `fields`\n InvalidSerializer.Meta.fields = ('name', 'age')\n with self.assertRaises(AssertionError):\n InvalidSerializer().get_fields()\n\n # both `fields` and `exclude` specified\n InvalidSerializer.Meta.exclude = ('name', 'email')\n with self.assertRaises(AssertionError):\n InvalidSerializer().get_fields()\n\n del InvalidSerializer.Meta.fields\n\n # invalid `exclude` specification\n InvalidSerializer.Meta.exclude = 'invalid'\n with self.assertRaises(TypeError):\n InvalidSerializer().get_fields()\n\n # declared field in `exclude`\n InvalidSerializer.Meta.exclude = ('name', 'email')\n with self.assertRaises(AssertionError):\n InvalidSerializer().get_fields()\n\n # non-existing field in `exclude`\n InvalidSerializer.Meta.exclude = ('name', 'nonexisting')\n with self.assertRaises(AssertionError):\n InvalidSerializer().get_fields()\n\n InvalidSerializer.Meta.exclude = ('name', )\n\n # invalid `read_only_fields` specification\n InvalidSerializer.Meta.read_only_fields = 'invalid'\n with self.assertRaises(TypeError):\n InvalidSerializer().get_fields()\n\n del InvalidSerializer.Meta.read_only_fields\n\n # wrong spelling of `read_only_fields`\n InvalidSerializer.Meta.readonly_fields = ('name', )\n with self.assertRaises(AssertionError):\n InvalidSerializer().get_fields()\n\n def test_unknown_field_type(self):\n class NotSerializable:\n pass\n\n @dataclass\n class Example:\n f: NotSerializable\n\n with self.assertRaises(NotImplementedError):\n DataclassSerializer(dataclass=Example).get_fields()\n\n def test_unknown_field(self):\n class UnknownSerializer(DataclassSerializer):\n class Meta:\n dataclass = fixtures.Person\n fields = ('spouse', )\n\n with self.assertRaises(ImproperlyConfigured):\n UnknownSerializer().get_fields()\n","sub_path":"tests/test_serializers.py","file_name":"test_serializers.py","file_ext":"py","file_size_in_byte":10646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"253827932","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPresence analyzer unit tests.\n\"\"\"\nimport os.path\nimport json\nimport datetime\nimport unittest\nimport random\nimport calendar\nfrom mock import patch\nfrom presence_analyzer import main, views, utils\n\n\nTEST_DATA_CSV = os.path.join(\n os.path.dirname(__file__), '..', '..', 'runtime', 'data', 'test_data.csv'\n)\nTEST_USERS_DATA = os.path.join(\n os.path.dirname(__file__), '..', '..', 'runtime', 'data', 'test_users.xml'\n)\n\n\n# pylint: disable=E1103\nclass PresenceAnalyzerViewsTestCase(unittest.TestCase):\n \"\"\"\n Views tests.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Before each test, set up a environment.\n \"\"\"\n main.app.config.update({'DATA_CSV': TEST_DATA_CSV})\n self.client = main.app.test_client()\n self.test_data = utils.get_data()\n\n def tearDown(self):\n \"\"\"\n Get rid of unused objects after each test.\n \"\"\"\n pass\n\n def test_mainpage(self):\n \"\"\"\n Test presence by weekday page\n \"\"\"\n resp = self.client.get('/')\n self.assertEqual(resp.status_code, 200)\n\n def test_start_end_page(self):\n \"\"\"\n Test start-end page\n \"\"\"\n resp = self.client.get('/start-end')\n self.assertEqual(resp.status_code, 200)\n\n def test_mean_time_page(self):\n \"\"\"\n Test mean time page\n \"\"\"\n resp = self.client.get('/mean_time')\n self.assertEqual(resp.status_code, 200)\n\n def test_api_users(self):\n \"\"\"\n Test users listing.\n \"\"\"\n resp = self.client.get('/api/v1/users')\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = json.loads(resp.data)\n self.assertEqual(len(data), 2)\n self.assertDictEqual(\n data[1],\n {\n u'user_id': u'176',\n u'name': u'Adrian Kruszewski',\n u'avatar': u'https://intranet.stxnext.pl/api/images/users/176'\n }\n )\n\n def test_mean_time_weekday(self):\n \"\"\"\n Test mean presence time of random user grouped by weekday.\n \"\"\"\n user_id = random.choice(self.test_data.keys())\n resp = self.client.get('/api/v1/mean_time_weekday/%s' % (user_id, ))\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = resp.data\n weekdays = utils.group_by_weekday(self.test_data[user_id])\n result = json.dumps(\n [(calendar.day_abbr[weekday], utils.mean(intervals))\n for weekday, intervals in weekdays.items()])\n self.assertEqual(data, result)\n\n fake_user_id = 1\n resp = self.client.get('/api/v1/mean_time_weekday/%s' %\n (fake_user_id, ))\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = json.loads(resp.data)\n result = []\n self.assertEqual(data, result)\n\n def test_presence_weekday_view(self):\n \"\"\"\n Test total presence time of given user grouped by weekday.\n \"\"\"\n user_id = random.choice(self.test_data.keys())\n resp = self.client.get('/api/v1/presence_weekday/%s' % (user_id, ))\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = resp.data\n weekdays = utils.group_by_weekday(self.test_data[user_id])\n result = [(calendar.day_abbr[weekday], sum(intervals))\n for weekday, intervals in weekdays.items()]\n result.insert(0, ('Weekday', 'Presence (s)'))\n result = json.dumps(result)\n self.assertEqual(data, result)\n\n fake_user_id = 1\n resp = self.client.get('/api/v1/presence_weekday/%s' %\n (fake_user_id, ))\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = json.loads(resp.data)\n result = []\n self.assertEqual(data, result)\n\n def test_presence_start_end(self):\n \"\"\"\n Test mean start and end time by weekday\n \"\"\"\n user_id = 10\n resp = self.client.get('/api/v1/presence_start_end/%s' % (user_id, ))\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = json.loads(resp.data)\n d = datetime.date.today()\n result = [[unicode(calendar.day_abbr[item_date.weekday()]),\n unicode(datetime.datetime.combine(\n d,\n item['start']).strftime('%Y-%m-%dT%H:%M:%S')),\n unicode(datetime.datetime.combine(\n d,\n item['end']).strftime('%Y-%m-%dT%H:%M:%S'))]\n for (item_date, item) in self.test_data[user_id].iteritems()]\n self.assertItemsEqual(data, result)\n\n fake_user_id = 1\n resp = self.client.get('/api/v1/presence_start_end/%s' %\n (fake_user_id, ))\n self.assertEqual(resp.status_code, 200)\n self.assertEqual(resp.content_type, 'application/json')\n data = json.loads(resp.data)\n self.assertEqual(data, [])\n\n\nclass PresenceAnalyzerUtilsTestCase(unittest.TestCase):\n \"\"\"\n Utility functions tests.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Before each test, set up a environment.\n \"\"\"\n main.app.config.update({'DATA_CSV': TEST_DATA_CSV})\n main.app.config.update({'DATA_PATH': TEST_USERS_DATA})\n\n def tearDown(self):\n \"\"\"\n Get rid of unused objects after each test.\n \"\"\"\n pass\n\n def test_get_data(self):\n \"\"\"\n Test parsing of CSV file.\n \"\"\"\n data = utils.get_data()\n self.assertIsInstance(data, dict)\n self.assertItemsEqual(data.keys(), [10, 11])\n sample_date = datetime.date(2013, 9, 10)\n self.assertIn(sample_date, data[10])\n self.assertItemsEqual(data[10][sample_date].keys(), ['start', 'end'])\n self.assertEqual(data[10][sample_date]['start'],\n datetime.time(9, 39, 5))\n\n with patch('csv.reader') as mock_reader:\n mock_reader.return_value = [[],\n [1, 2, 3, 4, 5],\n ['3a', '2012-12-31', '0:0:0', '0:0:1'],\n ['3', '2012-12-51', '0:0:0', '0:0:1']]\n data = utils.get_data()\n self.assertItemsEqual(data, {})\n\n def test_get_users_data(self):\n \"\"\"\n Test parsing xml with user data\n \"\"\"\n data, base_avatar_url = utils.get_users_data()\n self.assertDictEqual(\n data,\n {\n '176': {\n 'avatar': '/api/images/users/176',\n 'name': 'Adrian Kruszewski'},\n '141': {\n 'avatar': '/api/images/users/141',\n 'name': u'Adam Pie\\u015bkiewicz',\n },\n }\n )\n main.app.config.update({'DATA_PATH': 'noexistspath'})\n self.assertEqual(({}, None), utils.get_users_data())\n\n def test_group_by_weekday(self):\n \"\"\"\n Test grouping presence entries by weekday.\n \"\"\"\n data = utils.get_data()\n result = utils.group_by_weekday(data[10])\n self.assertIsInstance(result, dict)\n self.assertItemsEqual(result.keys(), range(7))\n self.assertItemsEqual(result[2], [24465])\n self.assertItemsEqual(result[6], [])\n\n def test_seconds_since_midnight(self):\n sample_date = datetime.datetime(2013, 9, 10)\n\n date = datetime.datetime(2013, 9, 10, 0, 0, 0)\n delta = date - sample_date\n result = utils.seconds_since_midnight(date)\n self.assertEqual(int(delta.total_seconds()), result)\n\n date = datetime.datetime(2013, 9, 10, 23, 59, 59)\n delta = date - sample_date\n result = utils.seconds_since_midnight(date)\n self.assertEqual(int(delta.total_seconds()), result)\n\n def test_interval(self):\n start_date = datetime.datetime(2013, 9, 10, 1, 2, 3)\n\n end_date = datetime.datetime(2013, 9, 10, 20, 50, 20)\n delta = end_date - start_date\n result = utils.interval(start_date, end_date)\n self.assertEqual(int(delta.total_seconds()), result)\n\n end_date = datetime.datetime(2013, 9, 10, 23, 59, 59)\n delta = end_date - start_date\n result = utils.interval(start_date, end_date)\n self.assertEqual(int(delta.total_seconds()), result)\n\n def test_mean(self):\n \"\"\"\n Test calculating mean of list\n \"\"\"\n self.assertEqual(utils.mean([]), 0)\n items = [34]\n self.assertEqual(utils.mean(items), 34)\n\n def test_time_from_seconds(self):\n \"\"\"\n Test converting seconds from midnight to time\n \"\"\"\n time = datetime.time(0, 0, 0)\n self.assertEqual(time, utils.time_from_seconds(0))\n\n time = datetime.time(23, 59, 59)\n result = utils.time_from_seconds(utils.seconds_since_midnight(time))\n self.assertEqual(time, result)\n\n seconds = 4333333335\n self.assertEqual(utils.time_from_seconds(seconds), None)\n\n def test_get_weekday_start_end(self):\n \"\"\"\n Test getting start and end time grouping by weekdays\n \"\"\"\n data = utils.get_data()\n result = utils.get_weekday_start_end(data[10])\n correct_result = {1: {'start': 34745, 'end': 64792},\n 2: {'start': 33592, 'end': 58057},\n 3: {'start': 38926, 'end': 62631}}\n self.assertEqual(result, correct_result)\n self.assertEqual(utils.get_weekday_start_end({}), {})\n\n\ndef suite():\n \"\"\"\n Default test suite.\n \"\"\"\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(PresenceAnalyzerViewsTestCase))\n suite.addTest(unittest.makeSuite(PresenceAnalyzerUtilsTestCase))\n return suite\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"src/presence_analyzer/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":10162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"184031145","text":"import mock\nfrom getter import cbr_fx\n\ndef test_get_xml(mocker):\n foo_obj = type('', (object,), {\"foo\": 1})()\n foo_obj.text = 'some_text'\n mocker.patch('requests.get', mock.MagicMock(return_value=foo_obj))\n assert cbr_fx.get_xml(\"some_url\") == foo_obj.text\n try:\n foo_obj.text = 'Error in parameters'\n cbr_fx.get_xml(\"some_url\")\n except Exception as e:\n assert str(e) == 'Error in parameters: some_url'","sub_path":"parsers/getter/tests/test_cbr_fx.py","file_name":"test_cbr_fx.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"419168771","text":"import threading\nimport queue\nimport spider.constants\nimport spider.type\nimport spider.page_list\nimport spider.article\nimport spider.save_database\nimport util.sqlite\n\n\nclass ThreadPoolManager:\n \"\"\"\n 线程池管理\n \"\"\"\n\n def __init__(self, thread_number):\n # 初始化参数\n self.work_queue = queue.Queue(thread_number + 10)\n self.thread_number = thread_number\n self.__init_threading_pool(self.thread_number)\n\n def __init_threading_pool(self, thread_number):\n # 初始化线程池,创建指定数量的线程池\n for i in range(thread_number):\n thread = ThreadManager(self.work_queue)\n thread.start()\n\n def add_job(self, func, *args):\n # 将任务放入队列,等待线程池阻塞读取,参数是被执行的函数和函数的参数\n self.work_queue.put((func, args))\n\n def wait_queue(self):\n self.work_queue.join()\n\n\nclass ThreadManager(threading.Thread):\n \"\"\"\n 线程类,用于从queue中获取任务并执行\n \"\"\"\n\n def __init__(self, work_queue):\n super().__init__()\n self.work_queue = work_queue\n self.daemon = True\n\n def run(self):\n while True:\n target, args = self.work_queue.get()\n target(*args)\n self.work_queue.task_done()\n \"\"\"\n if self.work_queue.empty():\n return\n \"\"\"\n\n\ndef save_database(article):\n \"\"\"\n 线程类只执行的任务函数\n :param article: Article对象\n :return:\n \"\"\"\n spider.save_database.save_chapters(article)\n spider.save_database.save_article(article)\n\n\ndef check_local(type_name, article_url):\n \"\"\"\n 检查本地数据库是否存在这本书\n :param type_name: 数据库名\n :param article_url: article url\n :return: 未查询到返回-1,否则返回id\n \"\"\"\n database = spider.constants.DATABASE_PATH + type_name + \".sqlite\"\n sql = util.sqlite.Sql(database, spider.save_database.ArticleForDB(\"article\"))\n query = sql.query([[\"article_url\", article_url]])\n if len(query) == 0:\n return -1\n if query[0][5] == article_url:\n # print(\"[%s article] %s 的信息已存在!\" % (type_name, query[0][1]))\n return query[0][0]\n else:\n return -1\n\n\ndef download_all():\n article_type = spider.type.ArticleType()\n spider.save_database.save_type(article_type)\n\n thread_pool = ThreadPoolManager(spider.constants.THREAD_NUMBER)\n # save article\n for type_name in article_type.result:\n __download_a_type(thread_pool, type_name)\n \"\"\"\n max_page = spider.page_list.SinglePage(type_name[\"url\"]).find_max_page()\n for page in range(1, max_page + 1):\n single_page = spider.page_list.SinglePage(type_name[\"url\"][:-2] + str(page))\n article_list = single_page.find_articles()\n for articles in article_list:\n if check_local(type_name[\"key\"], articles[\"url\"]) != -1:\n continue\n article = spider.article.Article(articles[\"url\"])\n thread_pool.add_job(save_database, *(article,))\n # thread_pool.add_job(spider.save_database.save_article, *(article,))\n # thread_pool.add_job(spider.save_database.save_chapters, *(article,))\n \"\"\"\n thread_pool.wait_queue()\n\n\ndef download(type_key):\n article_type = spider.type.ArticleType()\n spider.save_database.save_type(article_type)\n # save article\n thread_pool = ThreadPoolManager(spider.constants.THREAD_NUMBER)\n __download_a_type(thread_pool, type_key)\n thread_pool.wait_queue()\n\n\ndef __download_a_type(thread_pool, type_key):\n # save article\n type_name = {\"id\": 0, \"key\": \"\", \"type_name\": \"\", \"url\": \"\"}\n sql_query = util.sqlite.Sql(spider.constants.DATABASE_PATH + \"type.sqlite\",\n spider.save_database.TypeForDB(\"type\"))\n query = sql_query.query([[\"key\", type_key]])\n if len(query) == 0:\n print(\"无效的key!\")\n return -1\n else:\n type_name[\"id\"] = query[0][0]\n type_name[\"key\"] = query[0][1]\n type_name[\"type_name\"] = query[0][2]\n type_name[\"url\"] = query[0][3]\n max_page = spider.page_list.SinglePage(type_name[\"url\"]).find_max_page()\n for page in range(1, max_page + 1):\n single_page = spider.page_list.SinglePage(type_name[\"url\"][:-2] + str(page))\n article_list = single_page.find_articles()\n for articles in article_list:\n if check_local(type_name[\"key\"], articles[\"url\"]) != -1:\n print(\"[%s article] %s 的信息已存在,检查更新……\" % (type_name[\"key\"], articles[\"title\"]))\n # continue\n article = spider.article.Article(articles[\"url\"])\n thread_pool.add_job(save_database, *(article,))\n # thread_pool.add_job(spider.save_database.save_article, *(article,))\n # thread_pool.add_job(spider.save_database.save_chapters, *(article,))\n\n\ndef __download_a_type_old(type_key):\n article_type = spider.type.ArticleType()\n spider.save_database.save_type(article_type)\n\n thread_pool = ThreadPoolManager(spider.constants.THREAD_NUMBER)\n # save article\n type_name = {\"id\": 0, \"url\": \"\", \"key\": \"\", \"name\": \"\"}\n for each in article_type.result:\n if type_key == each[\"key\"]:\n type_name = each\n break\n if type_name[\"id\"] == 0:\n print(\"无效的key!\")\n return -1\n max_page = spider.page_list.SinglePage(type_name[\"url\"]).find_max_page()\n for page in range(1, max_page + 1):\n single_page = spider.page_list.SinglePage(type_name[\"url\"][:-2] + str(page))\n article_list = single_page.find_articles()\n for articles in article_list:\n if check_local(type_name[\"key\"], articles[\"url\"]) != -1:\n print(\"[%s article] %s 的信息已存在!\" % (type_name[\"key\"], articles[\"title\"]))\n continue\n article = spider.article.Article(articles[\"url\"])\n thread_pool.add_job(save_database, *(article,))\n # thread_pool.add_job(spider.save_database.save_article, *(article,))\n # thread_pool.add_job(spider.save_database.save_chapters, *(article,))\n thread_pool.wait_queue()\n\n\nif __name__ == '__main__':\n # download()\n download(\"sort13\")\n","sub_path":"yushuwu/spider/thread_pool.py","file_name":"thread_pool.py","file_ext":"py","file_size_in_byte":6371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"566135284","text":"\"\"\"\n@Date : 2021-01-28\n@Author : liyachao\n\"\"\"\nimport time\nimport uuid\nfrom datetime import datetime\n\nfrom numpy import long, mean\n\nfrom ios_device.servers.DTXSever import InstrumentRPCParseError\nfrom ios_device.servers.Installation import InstallationProxyService\nfrom ios_device.servers.Instrument import InstrumentServer\nfrom ios_device.util import api_util\nfrom ios_device.util.api_util import PyIOSDeviceException, RunXCUITest\nfrom ios_device.util.dtxlib import get_auxiliary_text\nfrom ios_device.util.forward import ForwardPorts\nfrom ios_device.util.utils import kperf_data\n\n\nclass PyiOSDevice:\n def __init__(self, device_id: str = None, rpc_channel: InstrumentServer = None):\n self.device_id = device_id\n self.xcuitest = None\n self.rpc_channel = None\n if not rpc_channel or not rpc_channel._cli:\n self.init()\n else:\n self.rpc_channel = rpc_channel\n\n def init(self):\n if not self.rpc_channel:\n self.rpc_channel = init(self.device_id)\n\n def get_processes(self):\n return get_processes(self.device_id, self.rpc_channel)\n\n def stop(self):\n self.rpc_channel.stop()\n\n def get_channel(self):\n \"\"\"\n 获取当前设备有哪些服务\n :return:\n \"\"\"\n\n return self.rpc_channel._published_capabilities\n\n def start_get_gpu(self, callback: callable):\n \"\"\"\n 开始获取 gpu 数据\n :param callback:\n :return:\n \"\"\"\n return start_get_gpu(device_id=self.device_id, rpc_channel=self.rpc_channel, callback=callback)\n\n def stop_get_gpu(self):\n \"\"\"\n 结束获取 gpu 数据\n :return:\n \"\"\"\n stop_get_gpu(self.rpc_channel)\n\n def launch_app(self, bundle_id: str = None):\n \"\"\"\n 启动 app\n :param bundle_id:\n :return:\n \"\"\"\n return launch_app(device_id=self.device_id, rpc_channel=self.rpc_channel, bundle_id=bundle_id)\n\n def start_get_network(self, callback: callable):\n \"\"\"\n 开始获取上下行流量\n :param callback:\n :return:\n \"\"\"\n return start_get_network(device_id=self.device_id, rpc_channel=self.rpc_channel, callback=callback)\n\n def stop_get_network(self):\n \"\"\"\n 结束获取网络包内容\n :return:\n \"\"\"\n stop_get_network(rpc_channel=self.rpc_channel)\n\n def start_get_system(self, callback: callable):\n \"\"\"\n 开始获取系统数据\n :param callback:\n :return:\n \"\"\"\n return start_get_system(device_id=self.device_id, rpc_channel=self.rpc_channel, callback=callback)\n\n def stop_get_system(self):\n \"\"\"\n 结束获取系统数据\n :return:\n \"\"\"\n stop_get_system(rpc_channel=self.rpc_channel)\n\n def get_device(self):\n \"\"\"\n 获取设备对象用于操作设备\n :return:\n \"\"\"\n return get_device(device_id=self.device_id, rpc_channel=self.rpc_channel)\n\n def get_applications(self):\n \"\"\"\n 获取手机应用列表\n :return:\n \"\"\"\n return get_applications(device_id=self.device_id, rpc_channel=self.rpc_channel)\n\n def start_xcuitest(self, bundle_id, callback: callable, app_env: dict = None,\n pair_ports=None):\n \"\"\"\n 启动 xcuittest\n :param pair_ports: 端口对的数组,每对端口中前一个代表远程端口,后一个代表本地端口,例如:[\"8100:8100\", \"8200:8200\"]\n :param forward: 是否进行端口转发\n :param bundle_id:\n :param callback:\n :param app_env:\n :return:\n \"\"\"\n\n self.xcuitest = start_xcuitest(bundle_id, callback, self.device_id, app_env, pair_ports)\n return self.xcuitest\n\n def stop_xcuitest(self, xcuitest=None):\n \"\"\"\n 停止 xcuitest\n :param xcuitest:\n :return:\n \"\"\"\n if not xcuitest and not self.xcuitest:\n raise PyIOSDeviceException(\"xcuitest object can not be None\")\n stop_xcuitest(xcuitest if xcuitest else self.xcuitest)\n\n def start_get_fps(self, callback: callable):\n \"\"\"\n 开始获取 fps 相关数据\n :param callback:\n :return:\n \"\"\"\n return start_get_fps(device_id=self.device_id, rpc_channel=self.rpc_channel, callback=callback)\n\n def stop_get_fps(self):\n \"\"\"\n 结束获取 fps 相关数据\n :return:\n \"\"\"\n stop_get_fps(rpc_channel=self.rpc_channel)\n\n def get_energy(self, pid: int):\n get_energy(pid=pid, device_id=self.device_id, rpc_channel=self.rpc_channel)\n\n def start_get_graphics_fps(self, callback: callable):\n \"\"\"\n graphics 计算 fps\n :param callback:\n :return:\n \"\"\"\n start_get_graphics_fps(device_id=self.device_id, rpc_channel=self.rpc_channel, callback=callback)\n\n def stop_get_graphics_fps(self):\n stop_get_graphics_fps(rpc_channel=self.rpc_channel)\n\n def start_get_mobile_notifications(self, callback: callable):\n \"\"\"\n 监听事件,比如 app 唤醒,杀死,退出到后台等等\n :param callback:\n :return:\n \"\"\"\n start_get_mobile_notifications(device_id=self.device_id, rpc_channel=self.rpc_channel, callback=callback)\n\n def stop_get_mobile_notifications(self):\n stop_get_mobile_notifications(rpc_channel=self.rpc_channel)\n\n def get_netstat(self, pid: int):\n \"\"\"\n 获取单应用的网络信息\n :param pid:\n :return:\n \"\"\"\n return get_netstat(pid=pid, device_id=self.device_id, rpc_channel=self.rpc_channel)\n\n def start_forward(self, pair_ports=None):\n \"\"\"\n iOS真机设备的端口转发\n :param pair_ports: list 端口对的数组,每对端口中前一个代表远程端口,后一个代表本地端口,例如:[\"8100:8100\", \"8200:8200\"]\n :param udid:\n :param threaded:\n :param bufsize:\n \"\"\"\n return start_forward(pair_ports=pair_ports, device_id=self.device_id)\n\n def stop_forward(self, forward: ForwardPorts):\n stop_forward(forward)\n\n\ndef init(device_id: str = None):\n rpc_channel = InstrumentServer(udid=device_id)\n rpc_channel.init()\n return rpc_channel\n\n\ndef init_wireless(device_id: str = None, *args):\n \"\"\" 局域网使用 wifi 连接 iOS version < 14.0\n com.apple.instruments.server.services.wireless 在 iOS 14 以上版本没有了\n :param device_id:\n :return:\n \"\"\"\n rpc = InstrumentServer(udid=device_id)\n if not args:\n addresses, port, psk = rpc.start_wireless()\n else:\n addresses, port, psk = args\n print('start wireless', addresses, port, psk)\n rpc_channel = rpc.init_wireless(addresses, port, psk)\n return rpc_channel\n\n\ndef get_processes(device_id: str = None, rpc_channel: InstrumentServer = None):\n \"\"\"\n 获取设备的进程列表\n :param rpc_channel:\n :param device_id:\n :return:\n \"\"\"\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n running = _rpc_channel.call(\"com.apple.instruments.server.services.deviceinfo\", \"runningProcesses\").parsed\n if not rpc_channel:\n _rpc_channel.stop()\n return running\n\n\ndef get_channel(device_id: str = None, rpc_channel: InstrumentServer = None):\n \"\"\"\n 当前设备可用服务列表\n :return:\n \"\"\"\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n device_channel = _rpc_channel._published_capabilities\n if not rpc_channel:\n _rpc_channel.stop()\n return device_channel\n\n\ndef start_get_gpu(device_id: str = None, rpc_channel: InstrumentServer = None, callback: callable = None,\n ms_return: bool = False):\n \"\"\"\n\n :param device_id:\n :param rpc_channel:\n :param callback:\n :param ms_return:\n :return:\n \"\"\"\n\n if not callback:\n raise PyIOSDeviceException(\"callback can not be None\")\n\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n\n def _callback(res):\n api_util.caller(res, callback)\n\n if ms_return:\n _rpc_channel.call(\"com.apple.instruments.server.services.graphics.opengl\", \"setSamplingRate:\", 0.0)\n _rpc_channel.call(\"com.apple.instruments.server.services.graphics.opengl\",\n \"startSamplingAtTimeInterval:processIdentifier:\",\n 0.0, 0.0)\n _rpc_channel.register_channel_callback(\"com.apple.instruments.server.services.graphics.opengl\", _callback)\n\n return _rpc_channel\n\n\ndef stop_get_gpu(rpc_channel: InstrumentServer):\n \"\"\"\n 停止获取 gpu 性能数据\n :param rpc_channel:\n :return:\n \"\"\"\n rpc_channel.call(\"com.apple.instruments.server.services.graphics.opengl\", \"stopSampling\")\n\n\ndef launch_app(bundle_id: str, device_id: str = None, rpc_channel: InstrumentServer = None):\n \"\"\"\n 启动 app\n :param device_id:\n :param rpc_channel:\n :param bundle_id:\n :return:\n \"\"\"\n\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n\n channel_name = \"com.apple.instruments.server.services.processcontrol\"\n _rpc_channel.register_channel_callback(channel_name, lambda x: x)\n pid = _rpc_channel.call(channel_name,\n \"launchSuspendedProcessWithDevicePath:bundleIdentifier:environment:arguments:options:\", \"\",\n bundle_id, {}, [], {\"StartSuspendedKey\": 0, \"KillExisting\": 1}).parsed\n if not rpc_channel:\n _rpc_channel.stop()\n return pid\n\n\ndef start_get_network(callback: callable, device_id: str = None, rpc_channel: InstrumentServer = None, ):\n \"\"\"\n 开始获取网络包内容\n :param device_id:\n :param rpc_channel:\n :param callback:\n :return:\n \"\"\"\n\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n\n def _callback(res):\n api_util.network_caller(res, callback)\n\n _rpc_channel.register_channel_callback(\"com.apple.instruments.server.services.networking\", _callback)\n _rpc_channel.call(\"com.apple.instruments.server.services.networking\", \"replayLastRecordedSession\")\n _rpc_channel.call(\"com.apple.instruments.server.services.networking\", \"startMonitoring\")\n return _rpc_channel\n\n\ndef stop_get_network(rpc_channel: InstrumentServer):\n \"\"\"\n 结束获取网络包内容\n :param rpc_channel:\n :return:\n \"\"\"\n rpc_channel.call(\"com.apple.instruments.server.services.networking\", \"stopMonitoring\")\n\n\ndef start_get_system(device_id: str = None, rpc_channel: InstrumentServer = None, callback: callable = None):\n \"\"\"\n 开始获取系统数据\n :param device_id:\n :param rpc_channel:\n :param callback:\n :return:\n \"\"\"\n if not callback:\n raise PyIOSDeviceException(\"callback can not be None\")\n\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n\n def _callback(res):\n api_util.system_caller(res, callback)\n\n _rpc_channel.register_unhandled_callback(lambda x: x)\n _rpc_channel.call(\"com.apple.instruments.server.services.sysmontap\", \"setConfig:\", {\n 'ur': 1000, # 输出频率 ms\n 'bm': 0,\n 'procAttrs': ['memVirtualSize', 'cpuUsage', 'procStatus', 'appSleep', 'uid', 'vmPageIns', 'memRShrd',\n 'ctxSwitch', 'memCompressed', 'intWakeups', 'cpuTotalSystem', 'responsiblePID', 'physFootprint',\n 'cpuTotalUser', 'sysCallsUnix', 'memResidentSize', 'sysCallsMach', 'memPurgeable',\n 'diskBytesRead', 'machPortCount', '__suddenTerm', '__arch', 'memRPrvt', 'msgSent', 'ppid',\n 'threadCount', 'memAnon', 'diskBytesWritten', 'pgid', 'faults', 'msgRecv', '__restricted', 'pid',\n '__sandbox'], # 输出所有进程信息字段,字段顺序与自定义相同(全量自字段,按需使用)\n 'sysAttrs': ['diskWriteOps', 'diskBytesRead', 'diskBytesWritten', 'threadCount', 'vmCompressorPageCount',\n 'vmExtPageCount', 'vmFreeCount', 'vmIntPageCount', 'vmPurgeableCount', 'netPacketsIn',\n 'vmWireCount', 'netBytesIn', 'netPacketsOut', 'diskReadOps', 'vmUsedCount', '__vmSwapUsage',\n 'netBytesOut'], # 系统信息字段\n 'cpuUsage': True,\n 'sampleInterval': 1000000000})\n _rpc_channel.register_channel_callback(\"com.apple.instruments.server.services.sysmontap\", _callback)\n _rpc_channel.call(\"com.apple.instruments.server.services.sysmontap\", \"start\")\n return _rpc_channel\n\n\ndef stop_get_system(rpc_channel: InstrumentServer):\n \"\"\"\n 结束获取系统数据\n :param rpc_channel:\n :return:\n \"\"\"\n if not rpc_channel:\n raise PyIOSDeviceException(\"rpc_channel can not be None\")\n rpc_channel.call(\"com.apple.instruments.server.services.sysmontap\", \"stop\")\n\n\ndef get_device(device_id: str = None, rpc_channel: InstrumentServer = None):\n \"\"\"\n 获取设备对象用于操作设备\n :param device_id:\n :param rpc_channel:\n :return:\n \"\"\"\n current_device = InstallationProxyService(udid=device_id, lockdown=rpc_channel.lockdown if rpc_channel else None)\n return current_device\n\n\ndef get_applications(device_id: str = None, rpc_channel: InstrumentServer = None):\n \"\"\"\n 获取手机应用列表\n :param device_id:\n :param rpc_channel:\n :return:\n \"\"\"\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n application_list = _rpc_channel.call(\n \"com.apple.instruments.server.services.device.applictionListing\",\n \"installedApplicationsMatching:registerUpdateToken:\",\n {}, \"\").parsed\n if not rpc_channel:\n _rpc_channel.stop()\n return application_list\n\n\ndef start_xcuitest(bundle_id: str, callback: callable, device_id: str = None, app_env: dict = None,\n pair_ports=None):\n \"\"\"\n 启动 xcuittest\n :param pair_ports: 端口对的数组��每对端口中前一个代表远程端口,后一个代表本地端口,例如:[\"8100:8100\", \"8200:8200\"]\n :param bundle_id:\n :param callback:\n :param device_id:\n :param app_env: 启动配置 {\n 'CA_ASSERT_MAIN_THREAD_TRANSACTIONS': '0',\n 'CA_DEBUG_TRANSACTIONS': '0',\n 'DYLD_FRAMEWORK_PATH': app_path + '/Frameworks:',\n 'DYLD_LIBRARY_PATH': app_path + '/Frameworks',\n 'NSUnbufferedIO': 'YES',\n 'SQLITE_ENABLE_THREAD_ASSERTIONS': '1',\n 'WDA_PRODUCT_BUNDLE_IDENTIFIER': '',\n 'XCTestConfigurationFilePath': xctestconfiguration_path,\n 'XCODE_DBG_XPC_EXCLUSIONS': 'com.apple.dt.xctestSymbolicator',\n 'MJPEG_SERVER_PORT': '',\n 'USE_PORT': '',\n }\n :return: 返回 xcuitest 对象,用于停止 xcuitest\n \"\"\"\n\n if pair_ports is None:\n pair_ports = [\"8100:8100\"]\n xcuitest = RunXCUITest(bundle_id=bundle_id, callback=callback, device_id=device_id, app_env=app_env,\n pair_ports=pair_ports)\n\n xcuitest.start()\n return xcuitest\n\n\ndef stop_xcuitest(xcuitest):\n \"\"\"\n 停止 xcuitest\n :param xcuitest: 启动时可获取对象\n :return:\n \"\"\"\n if type(xcuitest) == RunXCUITest:\n xcuitest.stop()\n else:\n raise PyIOSDeviceException(\"参数类型必须是 RunXCUITest\")\n\n\ndef start_get_fps(device_id: str = None, rpc_channel: InstrumentServer = None, callback: callable = None):\n \"\"\"\n 开始获取 fps 相关数据\n :param device_id:\n :param rpc_channel:\n :param callback:\n :return:\n \"\"\"\n if not callback:\n raise PyIOSDeviceException(\"callback can not be None\")\n\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n\n NANO_SECOND = 1e9 # ns\n MOVIE_FRAME_COST = 1 / 24\n last_frame = None\n last_1_frame_cost, last_2_frame_cost, last_3_frame_cost = 0, 0, 0\n jank_count = 0\n big_jank_count = 0\n jank_time_count = 0\n mach_time_factor = 125 / 3\n frame_count = 0\n time_count = 0\n count_time = datetime.now().timestamp()\n _list = []\n\n def _callback(res):\n nonlocal frame_count, last_frame, last_1_frame_cost, last_2_frame_cost, last_3_frame_cost, time_count, mach_time_factor, \\\n jank_count, big_jank_count, jank_time_count, _list, count_time\n if type(res.plist) is InstrumentRPCParseError:\n for args in kperf_data(res.raw.get_selector()):\n _time, code = args[0], args[7]\n if code == 830472984:\n if not last_frame:\n last_frame = long(_time)\n else:\n this_frame_cost = (long(_time) - last_frame) * mach_time_factor\n if all([last_3_frame_cost != 0, last_2_frame_cost != 0, last_1_frame_cost != 0]):\n if this_frame_cost > mean([last_3_frame_cost, last_2_frame_cost, last_1_frame_cost]) * 2 \\\n and this_frame_cost > MOVIE_FRAME_COST * NANO_SECOND * 2:\n jank_count += 1\n jank_time_count += this_frame_cost\n if this_frame_cost > mean(\n [last_3_frame_cost, last_2_frame_cost, last_1_frame_cost]) * 3 \\\n and this_frame_cost > MOVIE_FRAME_COST * NANO_SECOND * 3:\n big_jank_count += 1\n\n last_3_frame_cost, last_2_frame_cost, last_1_frame_cost = last_2_frame_cost, last_1_frame_cost, this_frame_cost\n time_count += this_frame_cost\n last_frame = long(_time)\n frame_count += 1\n else:\n time_count = (datetime.now().timestamp() - count_time) * NANO_SECOND\n if time_count > NANO_SECOND:\n callback(\n {\"currentTime\": str(datetime.now()), \"FPS\": frame_count / time_count * NANO_SECOND,\n \"jank\": jank_count,\n \"big_jank\": big_jank_count, \"stutter\": jank_time_count / time_count})\n jank_count = 0\n big_jank_count = 0\n jank_time_count = 0\n frame_count = 0\n time_count = 0\n count_time = datetime.now().timestamp()\n\n _rpc_channel.register_unhandled_callback(lambda x: x)\n # 获取mach time比例\n mach_time_info = _rpc_channel.call(\"com.apple.instruments.server.services.deviceinfo\", \"machTimeInfo\").parsed\n mach_time_factor = mach_time_info[1] / mach_time_info[2]\n _rpc_channel.register_channel_callback(\"com.apple.instruments.server.services.coreprofilesessiontap\",\n _callback)\n\n _rpc_channel.call(\"com.apple.instruments.server.services.coreprofilesessiontap\", \"setConfig:\",\n {'rp': 10,\n 'tc': [{'kdf2': {630784000, 833617920, 830472456},\n 'tk': 3,\n 'uuid': str(uuid.uuid4()).upper()}],\n 'ur': 500})\n\n _rpc_channel.call(\"com.apple.instruments.server.services.coreprofilesessiontap\", \"start\")\n\n return _rpc_channel\n\n\ndef stop_get_fps(rpc_channel: InstrumentServer):\n \"\"\"\n 结束获取 fps 数据\n :param rpc_channel:\n :return:\n \"\"\"\n if not rpc_channel:\n raise PyIOSDeviceException(\"rpc_channel can not be None\")\n rpc_channel.call(\"com.apple.instruments.server.services.coreprofilesessiontap\", \"stop\")\n\n\ndef get_energy(pid: int, device_id: str = None, rpc_channel: InstrumentServer = None):\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n\n channel_name = \"com.apple.xcode.debug-gauge-data-providers.Energy\"\n attr = {}\n # _rpc_channel.call(channel_name, \"startSamplingForPIDs:\", {pid})\n ret = _rpc_channel.call(channel_name, \"sampleAttributes:forPIDs:\", attr, {pid})\n if not rpc_channel:\n _rpc_channel.stop()\n return ret.parsed\n\n\ndef start_get_graphics_fps(device_id: str = None, rpc_channel: InstrumentServer = None, callback: callable = None):\n \"\"\"\n graphics 计算 fps\n :param device_id:\n :param rpc_channel:\n :param callback:\n :return:\n \"\"\"\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n\n def _callback(res):\n data = res.parsed\n callback({\"currentTime\": str(datetime.now()), \"fps\": data['CoreAnimationFramesPerSecond']})\n\n _rpc_channel.register_unhandled_callback(lambda x: x)\n _rpc_channel.register_channel_callback(\"com.apple.instruments.server.services.graphics.opengl\", _callback)\n _rpc_channel.call(\"com.apple.instruments.server.services.graphics.opengl\", \"startSamplingAtTimeInterval:\", 0.0)\n return _rpc_channel\n\n\ndef stop_get_graphics_fps(rpc_channel: InstrumentServer):\n \"\"\"\n 停止获取 graphics 计算 fps\n :param rpc_channel:\n :return:\n \"\"\"\n if not rpc_channel:\n raise PyIOSDeviceException(\"rpc_channel can not be None\")\n rpc_channel.call(\"com.apple.instruments.server.services.graphics.opengl\", \"stopSampling\")\n\n\ndef start_get_mobile_notifications(device_id: str = None, rpc_channel: InstrumentServer = None,\n callback: callable = None):\n \"\"\"\n 监听事件,比如 app 唤醒,杀死,退出到后台等等\n :param device_id:\n :param rpc_channel:\n :param callback:\n :return:\n \"\"\"\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n\n def _callback(res):\n callback(get_auxiliary_text(res.raw))\n\n _rpc_channel.register_unhandled_callback(_callback)\n\n _rpc_channel.call(\n \"com.apple.instruments.server.services.mobilenotifications\",\n 'setApplicationStateNotificationsEnabled:', str(True))\n return _rpc_channel\n\n\ndef stop_get_mobile_notifications(rpc_channel: InstrumentServer):\n \"\"\"\n\n :param rpc_channel:\n :return:\n \"\"\"\n rpc_channel.call(\n \"com.apple.instruments.server.services.mobilenotifications\",\n 'setApplicationStateNotificationsEnabled:', str(True))\n\n\ndef get_netstat(pid: int, device_id: str = None, rpc_channel: InstrumentServer = None):\n \"\"\"\n 获取单应用的网络信息\n :param device_id:\n :param rpc_channel:\n :param callback:\n :return:\n \"\"\"\n\n if not rpc_channel:\n _rpc_channel = init(device_id)\n else:\n _rpc_channel = rpc_channel\n channel = \"com.apple.xcode.debug-gauge-data-providers.NetworkStatistics\"\n attr = {}\n # print(\"start\", _rpc_channel.call(channel, \"startSamplingForPIDs:\", {pid}).parsed)\n ret = _rpc_channel.call(channel, \"sampleAttributes:forPIDs:\", attr, {pid}).parsed\n if not rpc_channel:\n _rpc_channel.stop()\n return ret\n\n\ndef start_forward(pair_ports=None, device_id: str = None):\n \"\"\"\n iOS真机设备的端口转发\n :param pair_ports: list 端口对的数组,每对端口中前一个代表远程端口,后一个代表本地端口,例如:[\"8100:8100\", \"8200:8200\"]\n :param device_id:\n :return:\n \"\"\"\n if not pair_ports:\n pair_ports = [\"8100,8100\"]\n forward = ForwardPorts(pair_ports=pair_ports, device_id=device_id)\n forward.start()\n return forward\n\n\ndef stop_forward(forward: ForwardPorts):\n forward.stop()\n\n\ndef te1st(res):\n # print(res[0][\"PerCPUUsage\"])\n print(res)\n\n\nif __name__ == \"__main__\":\n # print(get_netstat(216))\n # channel = PyiOSDevice()\n # print(channel.get_netstat(216))\n # channel.stop()\n # c = start_get_mobile_notifications(callback=te1st)\n # time.sleep(5)\n # stop_get_mobile_notifications(c)\n # time.sleep(3)\n # print(\"asdasdasd\")\n # c.stop()\n\n # channel = start_get_fps(callback=te1st)\n # time.sleep(10)\n # stop_get_fps(channel)\n # channel.stop()\n\n # x = start_xcuitest(\"cn.rongcloud.rce.autotest.xctrunner\", te1st,app_env={'USE_PORT': '8111'})\n # time.sleep(10)\n # stop_xcuitest(x)\n # rpc_channel = init_wireless()\n # system = start_get_system(callback=te1st, rpc_channel=rpc_channel)\n # time.sleep(100)\n # stop_get_system(system)\n # processes = channel.start_get_gpu_data(callba)\n # print(processes)\n # channel.stop_channel()\n\n # 有开始 有结束的demo\n # channel = init()\n # start_get_network(rpc_channel=channel, callback=te1st)\n # time.sleep(10)\n # stop_get_network(rpc_channel=channel)\n # channel.stop()\n\n # 普通的demo\n # channel = get_channel()\n # print(channel)\n # get_device()\n\n # channel = PyiOSDevice()\n # print(channel.get_channel())\n\n # channel = start_get_power_data(callback=test)\n # # time.sleep(10)\n # stop_get_system_data(channel)\n # channel.stop()\n\n # device = get_device()\n # print(device.get_apps_bid())\n\n # f = start_forward([\"8200:8200\"])\n # time.sleep(30)\n # stop_forward(f)\n pass\n\n # channel.register_unhandled_callback(test)\n # channel.register_callback(\"_notifyOfPublishedCapabilities:\", lambda a: print(1))\n # start_get_gpu_data(rpc_channel=channel, callback=test)\n # time.sleep(2)\n # stop_get_gpurpc_channel=channel,_data(channel)\n # channel.get_processes()\n # process = channel.get_processes()\n # print(process)\n # channel.start_activity(242)\n # print(get_channel(rpc_channel=channel))\n # dc = channel.get_processes()\n # print(dc)\n # channel.stop_channel()\n","sub_path":"ios_device/py_ios_device.py","file_name":"py_ios_device.py","file_ext":"py","file_size_in_byte":25884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"224587814","text":"# Copyright 2016 Jon Wayne Parrott\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport sys\n\nimport mock\nimport pytest\n\nimport nox.command\n\nPYTHON = sys.executable\n\n\n@pytest.fixture\ndef make_one():\n def factory(*args, **kwargs):\n return nox.command.Command(*args, **kwargs)\n return factory\n\n\ndef test_constructor_defaults(make_one):\n command = make_one(['echo', '123'])\n assert command.args == ['echo', '123']\n assert command.silent is False\n assert command.path is None\n assert command.success_codes == [0]\n\n\ndef test_constructor_explicit(make_one):\n command = make_one(\n ['echo', '123'],\n silent=True,\n path='/one/two/three',\n success_codes=[1, 2, 3])\n assert command.args == ['echo', '123']\n assert command.silent is True\n assert command.path is '/one/two/three'\n assert command.success_codes == [1, 2, 3]\n\n\ndef test_run_defaults(make_one, capsys):\n command = make_one([PYTHON, '-c', 'print(123)'])\n\n result = command.run()\n\n assert result is True\n\n\ndef test_run_silent(make_one, capsys):\n command = make_one([PYTHON, '-c', 'print(123)'], silent=True)\n\n result = command.run()\n out, _ = capsys.readouterr()\n\n assert '123' in result\n assert out == ''\n\n\ndef test_run_env_binary(make_one):\n command = make_one(\n [PYTHON, '-c', 'import os; print(os.environ[\"SIGIL\"])'],\n silent=True, env={\n b'SIGIL': b'123'})\n\n result = command.run()\n\n assert '123' in result\n\n\ndef test_run_env_unicode(make_one):\n command = make_one(\n [PYTHON, '-c', 'import os; print(os.environ[\"SIGIL\"])'],\n silent=True, env={\n u'SIGIL': u'123'})\n\n result = command.run()\n\n assert '123' in result\n\n\ndef test_run_env_fallback(make_one):\n command = make_one(\n [PYTHON, '-c',\n 'import os; print(os.environ[\"SIGIL\"] + os.environ[\"SIGIL2\"] )'],\n silent=True)\n\n result = command.run(env_fallback={u'SIGIL': u'abc', u'SIGIL2': u'456'})\n\n assert result.strip() == 'abc456'\n\n\ndef test_env_no_fallback(make_one):\n command = make_one(\n [PYTHON, '-c',\n 'import os; print(os.environ[\"SIGIL\"])'],\n silent=True, env={\n u'SIGIL': u'123'})\n\n result = command.run()\n\n assert result.strip() == '123'\n\n\ndef test_run_env_and_env_fallback(make_one):\n command = make_one(\n [PYTHON, '-c',\n 'import os; print(os.environ[\"SIGIL\"] + os.environ[\"SIGIL2\"] )'],\n silent=True, env={\n u'SIGIL': u'123'})\n\n result = command.run(env_fallback={u'SIGIL': u'abc', u'SIGIL2': u'456'})\n\n assert result.strip() == '123456'\n\n\ndef test_run_env_systemroot(make_one):\n systemroot = os.environ.setdefault('SYSTEMROOT', str('sigil'))\n\n command = make_one(\n [PYTHON, '-c', 'import os; print(os.environ[\"SYSTEMROOT\"])'],\n silent=True)\n\n result = command.run()\n\n assert systemroot in result\n\n\ndef test_run_not_found(make_one):\n command = make_one(['nonexistentcmd'])\n\n with pytest.raises(nox.command.CommandFailed):\n command.run()\n\n\ndef test_run_path_nonexistent(make_one):\n command = make_one(\n [PYTHON, '-c', 'import sys; print(sys.executable)'],\n silent=True,\n path='/non/existent')\n\n result = command.run()\n\n assert '/non/existent' not in result\n\n\ndef test_run_path_existent(make_one, tmpdir, monkeypatch):\n executable = tmpdir.join('testexc')\n executable.ensure('')\n executable.chmod(0o700)\n\n command = make_one(\n ['testexc'],\n silent=True,\n path=tmpdir.strpath)\n\n with mock.patch('nox.command.popen') as mock_command:\n mock_command.return_value = (0, '')\n command.run()\n mock_command.assert_called_with(\n [executable.strpath], env=None, silent=True)\n\n\ndef test_exit_codes(make_one):\n command_exit_code_0 = make_one(\n [PYTHON, '-c', 'import sys; sys.exit(0)'])\n command_exit_code_1 = make_one(\n [PYTHON, '-c', 'import sys; sys.exit(1)'])\n\n assert command_exit_code_0.run()\n\n with pytest.raises(nox.command.CommandFailed):\n command_exit_code_1.run()\n\n command_exit_code_1.success_codes = [1, 2]\n assert command_exit_code_1.run()\n\n\ndef test_fail_with_silent(make_one, capsys):\n command = make_one(\n [PYTHON, '-c',\n 'import sys; sys.stdout.write(\"out\");'\n 'sys.stderr.write(\"err\"); sys.exit(1)'],\n silent=True)\n\n with pytest.raises(nox.command.CommandFailed):\n command.run()\n out, err = capsys.readouterr()\n assert 'out' in err\n assert 'err' in err\n\n\ndef test_interrupt(make_one):\n command = make_one([PYTHON, '-c' '123'])\n\n mock_proc = mock.Mock()\n mock_proc.communicate.side_effect = KeyboardInterrupt()\n\n with mock.patch('subprocess.Popen', return_value=mock_proc):\n with pytest.raises(KeyboardInterrupt):\n command.run()\n\n\n@pytest.fixture\ndef make_one_func():\n def factory(*args, **kwargs):\n return nox.command.FunctionCommand(*args, **kwargs)\n return factory\n\n\ndef test_function_command(make_one_func):\n mock_func = mock.MagicMock()\n mock_func.__name__ = lambda self: 'mock_func'\n\n command = make_one_func(mock_func, [1], {'two': 3})\n\n assert command.run()\n mock_func.assert_called_with(1, two=3)\n\n\ndef test_function_command_fail(make_one_func):\n mock_func = mock.MagicMock(side_effect=ValueError('123'))\n mock_func.__name__ = lambda self: 'mock_func'\n\n command = make_one_func(mock_func, [], {})\n\n with pytest.raises(nox.command.CommandFailed):\n command.run()\n\n\ndef test_function_command_callable(make_one_func):\n mock_func = mock.MagicMock()\n\n command = make_one_func(mock_func, [1], {'two': 3})\n\n assert command.run()\n mock_func.assert_called_with(1, two=3)\n\n\ndef test_function_command_debug(make_one_func):\n mock_func = mock.MagicMock()\n mock_func.__name__ = lambda self: 'mock_func'\n\n command = make_one_func(mock_func, [1], {'two': 3}, debug=True)\n\n assert command.run()\n mock_func.assert_called_with(1, two=3)\n","sub_path":"tests/test_command.py","file_name":"test_command.py","file_ext":"py","file_size_in_byte":6575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"495471646","text":"import os\n\nimport json\n\nfrom flask import Flask, session\nfrom flask_session import Session\nfrom flask import Flask, request, render_template, jsonify\nfrom flask import flash\nimport requests\nfrom libgravatar import Gravatar\nimport time\nfrom flask_socketio import SocketIO, join_room, leave_room, send, emit\n\n\napp = Flask(__name__)\napp.debug = True\n\n\n\n\n# Configure session to use filesystem\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\nSession(app)\napp.config[\"SECRET_KEY\"] = os.getenv(\"SECRET_KEY\")\nsocketio = SocketIO(app)\n\n\n\nuser_list=[]\nrooms={'main':[]}\n\n\n\n\n#login system\n\n\n\n@app.route(\"/\")\ndef index():\n \n session['room'] = 'main'\n if not session.get('logged_in'):\n return render_template('login.html')\n else:\n current_room_msg= rooms.get(session['room'])\n return render_template(\"index.html\", current_user= session['username'], current_room= session['room'], rooms=rooms, current_room_msg= current_room_msg)\n\n\n@app.route('/login', methods=['POST'])\ndef login():\n username=request.form.get('username')\n if username not in user_list:\n session['logged_in'] = True\n session['username'] = username\n user_list.append(session['username'])\n session['room'] = 'main'\n print(user_list)\n return index()\n\n\n@app.route(\"/logout\")\ndef logout():\n if session['username'] in user_list:\n user_list.remove(session['username'])\n session['logged_in'] = False\n session['username'] = 'anonymous'\n session['room'] = 'main'\n print(user_list)\n return index()\n\n\n@socketio.on(\"incoming msg\")\ndef send_message(data):\n room = session['room']\n username=session['username']\n msg=data['msg']\n #form message dictionary\n message_line={'message': msg, 'username': username}\n #append dictionary to list which is the value of each room inside rooms dictionary\n rooms[room].append(message_line)\n print('printed:'+msg)\n #send info to js\n emit(\"display_message\", {'username': username, 'room': room, 'msg': msg}, broadcast=True)\n print('emited:'+msg)\n print(rooms)\n return False\n\n\nif __name__ == '__main__':\n socketio.run(app)","sub_path":"application - Copia (3).py","file_name":"application - Copia (3).py","file_ext":"py","file_size_in_byte":2170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"444077245","text":"class Solution:\n \"\"\"\n @param root: A Tree\n @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.\n \"\"\"\n\n def permutations(self, n):\n nums = [i for i in range(1, n + 1)]\n results = []\n visited = [False] * n\n self.dfs(nums, visited, [], results)\n return results\n\n def dfs(self, nums, visited, permutation, results):\n if len(permutation) == len(nums):\n results.append(permutation[:])\n return\n\n for i in range(len(nums)):\n if visited[i]:\n continue\n\n permutation.append(nums[i])\n visited[i] = True\n self.dfs(nums, visited, permutation, results)\n visited[i] = False\n permutation.pop()\n\n\nif __name__ == '__main__':\n # test 1\n n = 3\n print(Solution().permutations(n))","sub_path":"15_Permutations Hackerrank.py","file_name":"15_Permutations Hackerrank.py","file_ext":"py","file_size_in_byte":882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"500482034","text":"# -*- mode:python; coding:utf-8 -*-\n\n# Copyright (c) 2020 IBM Corp. 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# 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\"\"\"Tests for trestle init module.\"\"\"\n\nimport os\nimport pathlib\nimport platform\nimport stat\nimport sys\n\nfrom _pytest.monkeypatch import MonkeyPatch\n\nimport pytest\n\nimport trestle.core.const as const\nfrom trestle import cli\n\n\ndef test_init(tmp_path, keep_cwd, monkeypatch: MonkeyPatch):\n \"\"\"Test init happy path.\"\"\"\n os.chdir(tmp_path)\n testargs = ['trestle', 'init']\n monkeypatch.setattr(sys, 'argv', testargs)\n with pytest.raises(SystemExit) as pytest_wrapped_e:\n cli.run()\n assert pytest_wrapped_e.type == SystemExit\n assert pytest_wrapped_e.value.code == 0\n for directory in const.MODEL_DIR_LIST:\n assert os.path.isdir(directory)\n assert os.path.isdir(os.path.join(const.TRESTLE_DIST_DIR, directory))\n assert os.path.isfile(os.path.join(directory, const.TRESTLE_KEEP_FILE))\n assert os.path.isdir(const.TRESTLE_CONFIG_DIR)\n assert os.path.isfile(os.path.join(const.TRESTLE_CONFIG_DIR, const.TRESTLE_CONFIG_FILE))\n\n\ndef test_directory_creation_error(tmp_path, keep_cwd, monkeypatch: MonkeyPatch):\n \"\"\"Test error during init when a directory cannot be created.\"\"\"\n # Windows read-only on dir does not prevent file creation in dir\n if platform.system() == const.WINDOWS_PLATFORM_STR:\n return\n os.chdir(tmp_path)\n config_dir = pathlib.Path(const.TRESTLE_CONFIG_DIR)\n config_dir.mkdir()\n config_dir.chmod(stat.S_IREAD)\n config_file = config_dir / const.TRESTLE_CONFIG_FILE\n testargs = ['trestle', 'init']\n monkeypatch.setattr(sys, 'argv', testargs)\n with pytest.raises(SystemExit) as pytest_wrapped_e:\n cli.run()\n assert pytest_wrapped_e.type == SystemExit\n assert pytest_wrapped_e.value.code == 1\n for directory in const.MODEL_DIR_LIST:\n dir_path = pathlib.Path(directory)\n assert not dir_path.exists()\n dist_dir_path = pathlib.Path(const.TRESTLE_DIST_DIR) / directory\n assert not dist_dir_path.exists()\n assert config_dir.exists()\n assert config_dir.is_dir()\n config_exists = False\n try:\n config_exists = config_file.exists()\n except Exception:\n pass\n assert not config_exists\n\n\ndef test_config_copy_error(tmp_path, keep_cwd, monkeypatch: MonkeyPatch):\n \"\"\"Test error during init when a contents of .trestle cannot be created.\"\"\"\n os.chdir(tmp_path)\n config_dir = pathlib.Path(const.TRESTLE_CONFIG_DIR)\n config_dir.mkdir()\n config_file = config_dir / const.TRESTLE_CONFIG_FILE\n config_file.touch()\n config_file.chmod(stat.S_IREAD)\n testargs = ['trestle', 'init']\n monkeypatch.setattr(sys, 'argv', testargs)\n with pytest.raises(SystemExit) as pytest_wrapped_e:\n cli.run()\n assert pytest_wrapped_e.type == SystemExit\n assert pytest_wrapped_e.value.code == 1\n for directory in const.MODEL_DIR_LIST:\n assert os.path.isdir(directory)\n assert os.path.isdir(os.path.join(const.TRESTLE_DIST_DIR, directory))\n assert os.path.isdir(const.TRESTLE_CONFIG_DIR)\n assert os.path.isfile(os.path.join(const.TRESTLE_CONFIG_DIR, const.TRESTLE_CONFIG_FILE))\n assert os.stat(os.path.join(const.TRESTLE_CONFIG_DIR, const.TRESTLE_CONFIG_FILE)).st_size == 0\n","sub_path":"tests/trestle/core/commands/init_test.py","file_name":"init_test.py","file_ext":"py","file_size_in_byte":3811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"284439609","text":"#!/usr/bin/env python\r\n\r\nimport SocketServer\r\nimport serial\r\nimport sys\r\nimport Tkinter as tk\r\nimport picamera\r\nimport math\r\nimport subprocess\r\nimport os\r\nimport time\r\n\r\nMOVE_SPEED = 20\r\n\r\n#math.degrees()\r\n\r\n#config to fix repeating press error\r\n#os.system(\"xset r off\")\r\n\r\n#configure picamera\r\n\"\"\"camera = picamera.PiCamera()\r\ncamera.preview_fullscreen = False\r\ncamera.preview_window = (600, 320, 640, 480)\r\ncamera.resolution = (640, 480)\"\"\"\r\n\r\n\r\n# important AX-12 constants\r\nAX_WRITE_DATA = 3\r\nAX_READ_DATA = 4\r\n\r\ns = serial.Serial() # create a serial port object\r\ns.baudrate = 57600 # baud rate, in bits/second\r\ns.port = \"/dev/ttyAMA0\" # this is whatever port your are using\r\ns.timeout = 3.0\r\ns.open()\r\n\r\n\r\nDXL_REG_CCW_Angle_Limit = 8 #to change control mode\r\nDXL_REG_Goal_Postion = 30\r\nDXL_REG_Moving_Speed = 32\r\n\r\nactiveDir = {\"w\":False}\r\n\r\ndef writeShort(val):\r\n s.write(chr(int(val)%256))\r\n s.write(chr(int(val)>>8))\r\n\r\ndef writeWord(ID, addr, val):\r\n s.write('W'+'w'+chr(ID))\r\n writeShort(addr)\r\n writeShort(val)\r\n\r\ndef writeStop(ID):\r\n s.write('C' + 's' + chr(ID))\r\n\r\ndef jointMode(ID):\r\n s.write('W'+'j'+chr(ID))\r\n\r\ndef setPosition(ID, pos, vel):\r\n s.write('W'+'p'+chr(ID))\r\n writeShort(pos)\r\n writeShort(vel)\r\n\r\n\r\n \r\n\r\ndef moveToDxAngle(ID,dxlPosition,dxlSpeed):\r\n setPosition(ID,dxlPosition,dxlSpeed)\r\n\r\ndef moveToDegAngle(ID, degPosition, pcSpeed): \r\n while degPosition > 180:\r\n degPosition = degPosition - 360\r\n while degPosition < -180:\r\n degPosition = degPosition + 360\r\n\r\n if (degPosition < -150):\r\n degPosition = -150\r\n if (degPosition > 150):\r\n degPosition = 150\r\n moveToDxAngle(ID, int(float(degPosition)*3.41+511.5), int(float(pcSpeed)*10.23))\r\n\r\ndef spinAtDxSpeed(ID,dxlSpeed):\r\n writeWord(ID,DXL_REG_Moving_Speed,dxlSpeed)\r\n\r\n# Spins at a certain percent of full speed. \r\ndef spinAtPcSpeed(ID,pcSpeed): \r\n if pcSpeed >= 0:\r\n spinAtDxSpeed(ID,int(float(pcSpeed)*10.23))\r\n else:\r\n spinAtDxSpeed(ID,1024+int(float(-pcSpeed)*10.23))\r\n\r\ndef throttleSteeringToLeftRight(inThrottle, inSteering):\r\n left = min(100, max(-100, inThrottle - inSteering)); \r\n right = min(100, max(-100, inThrottle + inSteering)); \r\n return (left, right)\r\n\r\nclass joint(object): \r\n def __init__(self, servoID, minLimit, maxLimit, moveSpeed = 20, defaultPos=0):\r\n self.servoID = servoID\r\n self.minLimit = minLimit\r\n self.maxLimit = maxLimit\r\n self.currAngle = 0\r\n self.moveSpeed = moveSpeed\r\n self.defaultPos = defaultPos\r\n #getting servo object\r\n\r\n def moveToAngle(self, angle):\r\n if angle <= self.maxLimit and angle >= self.minLimit:\r\n moveToDegAngle(self.servoID, angle, self.moveSpeed)\r\n self.currAngle = angle\r\n time.sleep(0.05)\r\n\r\n def increaseAngle(self, speed = 1):\r\n self.moveToAngle(self.maxLimit)\r\n\r\n def decreaseAngle(self, speed = 1):\r\n temp = self.moveSpeed\r\n self.moveSpeed *= speed\r\n self.moveToAngle(self.minLimit)\r\n self.moveSpeed = temp\r\n\r\n def increaseAngleAtSpeed(self, speed = 1):\r\n moveToDegAngle(self.servoID, self.maxLimit, speed)\r\n time.sleep(0.05)\r\n \r\n def decreaseAngleAtSpeed(self, speed = 1):\r\n moveToDegAngle(self.servoID, self.minLimit, speed)\r\n time.sleep(0.05)\r\n \r\n def stop(self):\r\n writeStop(self.servoID)\r\n \r\n def gotoDefaultPos(self):\r\n self.moveToAngle(self.defaultPos)\r\n\r\nclass Wheel(object):\r\n def __init__(self, servoID):\r\n self.servoID = servoID\r\n \r\n def spinAtSpeed(self, pcSpeed):\r\n spinAtPcSpeed(self.servoID, pcSpeed)\r\n\r\n\r\nclass Robot(object):\r\n \r\n \"\"\"\r\n #Front Left (100 fwd)\r\n #Front Right (-100 fwd)\r\n #Back Right (-100 fwd)\r\n #Back Left (100 fwd)\r\n \"\"\"\r\n \r\n wheelStates = {\"stop\":{\"fl\":0,\"fr\":0,\"br\":0,\"bl\":0},\r\n \"fwd\":{\"fl\":100,\"fr\":-100,\"br\":-100,\"bl\":100},\r\n \"back\":{\"fl\":-100,\"fr\":100,\"br\":100,\"bl\":-100},\r\n \"left\":{\"fl\":-50,\"fr\":-50,\"br\":-50,\"bl\":-50},\r\n \"right\":{\"fl\":50,\"fr\":50,\"br\":50,\"bl\":50}}\r\n \r\n def __init__(self, servoDict, wheelsDict):\r\n self.servos = servoDict\r\n self.wheels = wheelsDict\r\n self.resetJointPos()\r\n \r\n def getServo(self, servo):\r\n return self.servos[servo]\r\n \r\n def getWheel(self, wheelID):\r\n return self.wheels[wheelID]\r\n \r\n def wheelMove(self, stateID=\"stop\"):\r\n stateDict = self.wheelStates[stateID]\r\n for wheel in stateDict.keys():\r\n self.getWheel(wheel).spinAtSpeed(stateDict[wheel])\r\n\r\n def resetJointPos(self):\r\n for joint in self.servos.values():\r\n joint.gotoDefaultPos()\r\n\r\n# Purge the first value\r\ntime.sleep(0.5) \r\nshoulderPos = -45\r\ntiltPos = 0\r\npanPos = 0\r\n\r\n# Set wheel and joint modes. \r\nwriteWord(1, DXL_REG_CCW_Angle_Limit, 0)\r\nwriteWord(2, DXL_REG_CCW_Angle_Limit, 0)\r\nwriteWord(3, DXL_REG_CCW_Angle_Limit, 0)\r\nwriteWord(4, DXL_REG_CCW_Angle_Limit, 0)\r\n\r\njointMode(5)\r\njointMode(6)\r\njointMode(7)\r\n\r\n\r\nshoulderObj = joint(5, -90, 120, moveSpeed=10)\r\npanObj = joint(7, -90, 90, moveSpeed = 20)\r\ntiltObj = joint(6, -90, 90)\r\n\r\nflWheel = Wheel(1)\r\nfrWheel = Wheel(2)\r\nblWheel = Wheel(4)\r\nbrWheel = Wheel(3)\r\n\r\nrobotObj = Robot({\"shoulder\":shoulderObj, \"pan\":panObj, \"tilt\":tiltObj}, {\"fl\":flWheel, \"fr\":frWheel, \"bl\":blWheel, \"br\":brWheel})\r\n\r\ndef demo():\r\n #Raymond's original code\r\n tiltSpeed = 100\r\n panSpeed = 100\r\n shoulderSpeed = 100\r\n shoulderPos = 0\r\n\r\n # Shoulder is limited to -90 and 150. Note that this will hit the ground (which could be desired).\r\n shoulderPos = max(-90, min(150, shoulderPos))\r\n\r\n tiltcmd = tiltPos + shoulderPos\r\n\r\n # Tilt is limited to 90 degrees, pan to 150.\r\n tiltcmd = max(-90, min(90, tiltcmd))\r\n\r\n\r\n moveToDegAngle(6, shoulderPos,shoulderSpeed)\r\n moveToDegAngle(6, tiltcmd, max(10, tiltSpeed))\r\n\r\n time.sleep(0.05) \r\n\r\ndef resetCamPos():\r\n robotObj.getServo(\"pan\").moveToAngle(0)\r\n robotObj.getServo(\"tilt\").moveToAngle(0)\r\n robotObj.getServo(\"shoulder\").moveToAngle(0)\r\n \r\ndef startCamera():\r\n fps = 5\r\n clientIP = \"192.168.100.117\"\r\n port = 5000\r\n height = 360\r\n width = 640\r\n time = 0\r\n start_command = \"/opt/vc/bin/raspivid -vf -fps %s -o - -w %s -h %s -t %s | nc.traditional %s %s\" % (fps, width, height, time, clientIP, port)\r\n subprocess.call(start_command, shell=True)\r\n\r\ndef stopCamera():\r\n os.system(\"killall -9 raspivid\")\r\n os.system(\"killall -9 netcat\")\r\n\r\ndef stopMoving(joint):\r\n robotObj.getServo(joint).stop()\r\n\r\nclass MyTCPHandler(SocketServer.BaseRequestHandler):\r\n \r\n def handler(self):\r\n listmouse = self.data.split()\r\n panPos = int(listmouse[0])\r\n tiltPos = int(listmouse[1])\r\n\r\n #there is probbly a better way of doing this using map or somthing\r\n #like that but hardcoding is the temp solution\r\n\r\n panSpeed = 20\r\n tiltSpeed = 20\r\n \r\n if panPos >= 170:\r\n PanSpeed = 40\r\n elif panPos >= 160:\r\n panSpeed = 35\r\n elif panPos >= 150:\r\n panSpeed = 30\r\n elif panPos >= 140:\r\n panSpeed = 25\r\n elif panPos >= 130:\r\n panSpeed = 20\r\n elif panPos >= 120:\r\n panSpeed = 15\r\n elif panPos >= 110:\r\n panSpeed = 10\r\n elif panPos >= 100:\r\n panSpeed = 7\r\n elif panPos >= 90:\r\n panSpeed = 5\r\n\r\n elif panPos >= 80:\r\n panSpeed = 5\r\n elif panPos >= 70:\r\n panSpeed = 7\r\n elif panPos >= 60:\r\n panSpeed = 10\r\n elif panPos >= 50:\r\n panSpeed = 15\r\n elif panPos >= 40:\r\n panSpeed = 20\r\n elif panPos >= 30:\r\n panSpeed = 25\r\n elif panPos >= 20:\r\n panSpeed = 30\r\n elif panPos >= 10:\r\n panSpeed = 35\r\n elif panPos >= 2:\r\n panSpeed = 40\r\n \r\n # -- tiltSpeed --\r\n if tiltPos >= 170:\r\n tiltSpeed = 40\r\n elif tiltPos >= 160:\r\n tiltSpeed = 35\r\n elif tiltPos >= 150:\r\n tiltSpeed = 30\r\n elif tiltPos >= 140:\r\n tiltSpeed = 25\r\n elif tiltPos >= 130:\r\n tiltSpeed = 20\r\n elif tiltPos >= 120:\r\n tiltSpeed = 15\r\n elif tiltPos >= 110:\r\n tiltSpeed = 10\r\n elif tiltPos >= 100:\r\n tiltSpeed = 7\r\n elif tiltPos >= 90:\r\n tiltSpeed = 5\r\n\r\n elif tiltPos >= 80:\r\n tiltSpeed = 5\r\n elif tiltPos >= 70:\r\n tiltSpeed = 7\r\n elif tiltPos >= 60:\r\n tiltSpeed = 10\r\n elif tiltPos >= 50:\r\n tiltSpeed = 15\r\n elif tiltPos >= 40:\r\n tiltSpeed = 20\r\n elif tiltPos >= 30:\r\n tiltSpeed = 25\r\n elif tiltPos >= 20:\r\n tiltSpeed = 30\r\n elif tiltPos >= 10:\r\n tiltSpeed = 35\r\n elif tiltPos >= 2:\r\n tiltSpeed = 40\r\n \r\n print(\"PanPos:\", panPos, \"tiltPos:\", tiltPos)\r\n if panPos > 100:\r\n robotObj.getServo(\"pan\").increaseAngleAtSpeed(panSpeed)\r\n elif panPos >= 80:\r\n robotObj.getServo(\"pan\").stop()\r\n elif panPos >= 0:\r\n robotObj.getServo(\"pan\").decreaseAngleAtSpeed(panSpeed)\r\n else:\r\n print(\"ISSUE WITH PAN\")\r\n \r\n if tiltPos >= 100:\r\n robotObj.getServo(\"tilt\").increaseAngleAtSpeed(tiltSpeed)\r\n elif tiltPos >= 80:\r\n robotObj.getServo(\"tilt\").stop()\r\n elif tiltPos >= 0:\r\n robotObj.getServo(\"tilt\").decreaseAngleAtSpeed(tiltSpeed)\r\n else:\r\n print(\"ISSUE WITH TILIT\")\r\n \r\n \r\n def handle(self):\r\n #self.request is the TCP socket connect to the client\r\n self.data = self.request.recv(1024).strip()\r\n print(\"{} wrote:\".format(self.client_address[0]))\r\n self.request.sendall(self.data.upper())\r\n #handle the data being sent\r\n x = self.data\r\n print(\"info\", x, len(x))\r\n if len(x) == 1:\r\n if x == \"q\":\r\n robotObj.wheelMove(\"stop\")\r\n robotObj.resetJointPos()\r\n resetCamPos()\r\n #this is more of a reset button now\r\n \r\n #camera.close()\r\n #window.destroy()\r\n #window.quit()\r\n elif x == \"w\":\r\n robotObj.wheelMove(\"fwd\")\r\n elif x == \"a\":\r\n robotObj.wheelMove(\"left\")\r\n elif x == \"d\":\r\n robotObj.wheelMove(\"right\")\r\n elif x == \"s\":\r\n robotObj.wheelMove(\"back\")\r\n elif x == \"1\":\r\n robotObj.getServo(\"pan\").increaseAngle()\r\n elif x == \"2\":\r\n robotObj.getServo(\"pan\").moveToAngle(0)\r\n elif x == \"3\":\r\n robotObj.getServo(\"pan\").decreaseAngle()\r\n elif x == \"z\":\r\n robotObj.getServo(\"tilt\").increaseAngle()\r\n elif x == \"x\":\r\n robotObj.getServo(\"tilt\").moveToAngle(0)\r\n elif x == \"c\":\r\n robotObj.getServo(\"tilt\").decreaseAngle()\r\n elif x == \"j\":\r\n robotObj.getServo(\"shoulder\").decreaseAngle()\r\n elif x == \"k\":\r\n robotObj.getServo(\"shoulder\").moveToAngle(0)\r\n elif x == \"l\":\r\n robotObj.getServo(\"shoulder\").increaseAngle()\r\n elif x == \"o\":\r\n startCamera()\r\n elif x == \"p\":\r\n stopCamera()\r\n else:\r\n print(x)\r\n print(\"press another key please\")\r\n elif len(x) == 2:\r\n #keyup?\r\n x = x[0]\r\n if x == \"q\":\r\n None\r\n elif x == \"w\":\r\n robotObj.wheelMove(\"stop\")\r\n elif x == \"a\":\r\n robotObj.wheelMove(\"stop\")\r\n elif x == \"d\":\r\n robotObj.wheelMove(\"stop\")\r\n elif x == \"s\":\r\n robotObj.wheelMove(\"stop\")\r\n elif x == \"1\" or x == \"3\":\r\n robotObj.getServo(\"pan\").stop()\r\n elif x in [\"j\", \"l\"]:\r\n robotObj.getServo(\"shoulder\").stop()\r\n elif x in [\"z\", \"c\"]:\r\n robotObj.getServo(\"tilt\").stop()\r\n elif len(x) == 11:\r\n #camera command\r\n if x == \"startCamera\":\r\n startCamera()\r\n self.request.sendall(\"Camera Started\")\r\n elif x == \"stoppCamera\":\r\n stopCamera()\r\n self.request.sendall(\"Camera Stopped\")\r\n else:\r\n #xy thing\r\n self.handler()\r\n \r\n \r\n \r\n\r\nif __name__ == \"__main__\":\r\n HOST, PORT = \"\", 9999\r\n\r\n#Create the server, binding to localhost on port 9999\r\nserver = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)\r\n\r\n# Activate the server; this will keep running until you\r\n# interupt the program (e.g. Ctrl-C)\r\nserver.serve_forever()\r\n\r\n\r\n\r\n'''\r\n#setup GUI Window\r\nwindow = tk.Tk()\r\nwindow.resizable(width=False, height=False)\r\nwindow.geometry(\"800x600\")\r\nwindow.title(\"EmuBot\")\r\n\r\n#camera control interface\r\nfrmCamera = tk.Frame(window, height=400, width=400)\r\nfrmCamera.grid(row=0, column=0, rowspan=3, columnspan=3)\r\n\r\nlblCamera = tk.Label(frmCamera, text=\"Camera Controls\")\r\nlblCamera.grid(row=0, column=0, columnspan=2)\r\nbtnCamStart = tk.Button(frmCamera, text=\"Start Cam\", command=startCamera)\r\nbtnCamStart.grid(row = 1, column = 0)\r\nbtnCamStop = tk.Button(frmCamera, text=\"Close Cam\", command=stopCamera)\r\nbtnCamStop.grid(row = 1, column = 1)\r\n\r\nlblPos = tk.Label(frmCamera, text=\"Press numbers 1, 2, and 3 on your keyboard to Pan\")\r\nlblPos.grid(row = 3, column = 0, columnspan=3)\r\n\r\n\r\nleave these here just so you can test with keyboard input\r\nor stop the application if needed\r\n\r\nwindow.bind_all('', keypress)\r\nwindow.bind(\"\", keyunpress)\r\n\r\nwindow.mainloop()\r\n'''\r\n\r\n\r\n","sub_path":"EmuBot/EmuBot Code v1/00 Progress - EmuBot 1/Server/EmuBotServer140625.py","file_name":"EmuBotServer140625.py","file_ext":"py","file_size_in_byte":17019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"78181482","text":"#\r\n# @lc app=leetcode.cn id=1309 lang=python3\r\n#\r\n# [1309] 解码字母到整数映射\r\n#\r\n# https://leetcode-cn.com/problems/decrypt-string-from-alphabet-to-integer-mapping/description/\r\n#\r\n# algorithms\r\n# Easy (75.20%)\r\n# Likes: 2\r\n# Dislikes: 0\r\n# Total Accepted: 1.6K\r\n# Total Submissions: 2.1K\r\n# Testcase Example: '\"10#11#12\"'\r\n#\r\n# 给你一个字符串 s,它由数字('0' - '9')和 '#' 组成。我们希望按下述规则将 s 映射为一些小写英文字符:\r\n#\r\n#\r\n# 字符('a' - 'i')分别用('1' - '9')表示。\r\n# 字符('j' - 'z')分别用('10#' - '26#')表示。\r\n#\r\n#\r\n# 返回映射之后形成的新字符串。\r\n#\r\n# 题目数据保证映射始终唯一。\r\n#\r\n#\r\n#\r\n# 示例 1:\r\n#\r\n# 输入:s = \"10#11#12\"\r\n# 输出:\"jkab\"\r\n# 解释:\"j\" -> \"10#\" , \"k\" -> \"11#\" , \"a\" -> \"1\" , \"b\" -> \"2\".\r\n#\r\n#\r\n# 示例 2:\r\n#\r\n# 输入:s = \"1326#\"\r\n# 输出:\"acz\"\r\n#\r\n#\r\n# 示例 3:\r\n#\r\n# 输入:s = \"25#\"\r\n# 输出:\"y\"\r\n#\r\n#\r\n# 示例 4:\r\n#\r\n# 输入:s = \"12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#\"\r\n# 输出:\"abcdefghijklmnopqrstuvwxyz\"\r\n#\r\n#\r\n#\r\n#\r\n# 提示:\r\n#\r\n#\r\n# 1 <= s.length <= 1000\r\n# s[i] 只包含数字('0'-'9')和 '#' 字符。\r\n# s 是映射始终存在的有效字符串。\r\n#\r\n#\r\n#\r\n\r\n\r\n# @lc code=start\r\nclass Solution:\r\n def freqAlphabets(self, s: str) -> str:\r\n # 因为结果唯一, 所以先判断i+2是否为#\r\n res = ''\r\n i = 0\r\n while i < len(s):\r\n c = s[i]\r\n if i + 2 < len(s) and s[i + 2] == '#':\r\n res += chr(int(s[i:i + 2]) - 1 + ord('a'))\r\n i += 3\r\n else:\r\n res += chr(int(c) - 1 + ord('a'))\r\n i += 1\r\n return res\r\n\r\n\r\n# @lc code=end\r\n","sub_path":"Easy/1309.解码字母到整数映射.py","file_name":"1309.解码字母到整数映射.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"532790246","text":"# pyGISS: GISS Python Library\n# Copyright (c) 2013 by Robert Fischer\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 UserDict import DictMixin\n\n# Python ordered dictionary\n# See: \n\nclass odict(DictMixin):\n\n\t\"\"\"Dictionary in which the insertion order of items is preserved\n\t(using an internal double linked list). In this implementation\n\treplacing an existing item keeps it at its original position.\n\n\tInternal representation: values of the dict:\n\t\t[pred_key, val, succ_key]\n\n\tThe sequence of elements uses as a double linked list. The links\n\tare dict keys. self.lh and self.lt are the keys of first and last\n\telement inseted in the odict. In a C reimplementation of this data\n\tstructure, things can be simplified (and speed up) a lot if given\n\ta value you can at the same time find its key. With that, you can\n\tuse normal C pointers.\n\n\tUsage:\n\t\tImport and create ordered dictionary:\n\n\t\t\t>>> import ordered\n\t\t\t>>> od = ordered.odict()\n\n\t\ttype conversion to ordinary dict. This will fail:\n\n\t\t\t>>> dict(odict([(1, 1)]))\n\t\t\t{1: [nil, 1, nil]}\n\n\t\tThe reason for this is here -> http://bugs.python.org/issue1615701\n\n\t\tThe __init__ function of dict checks wether arg is subclass of\n\t\tdict, and ignores overwritten __getitem__ & co if so.\n\n\t\tThis was fixed and later reverted due to behavioural problems with pickle.\n\n\t\tUse one of the following ways for type conversion:\n\n\t\t\t>>> dict(odict([(1, 1)]).items())\n\t\t\t{1: 1}\n\n\t\t\t>>> odict([(1, 1)]).as_dict()\n\t\t\t{1: 1}\n\n\t\tIt is possible to use abstract mixin class _odict to hook\n\t\tanother dict base implementation. This is useful i.e. when\n\t\tpersisting to ZODB. Inheriting from dict and Persistent at the\n\t\tsame time fails:\n\n\t\t>>> from persistent.dict import PersistentDict\n\t\t>>> class podict(_odict, PersistentDict):\n\t\t...\t\tdef _dict_impl(self):\n\t\t...\t\t\treturn PersistentDict\n\t\t\n\tSee:\n\t\thttp://pypi.python.org/pypi/odict/\n\t\"\"\"\n \n\tdef __init__(self, data=None, **kwdata):\n\t\tself._keys = []\n\t\tself._data = {}\n\t\tif data is not None:\n\t\t\tif hasattr(data, 'items'):\n\t\t\t\titems = data.items()\n\t\t\telse:\n\t\t\t\titems = list(data)\n\t\t\tfor i in xrange(len(items)):\n\t\t\t\tlength = len(items[i])\n\t\t\t\tif length != 2:\n\t\t\t\t\traise ValueError('dictionary update sequence element '\n\t\t\t\t\t\t'#%d has length %d; 2 is required' % (i, length))\n\t\t\t\tself._keys.append(items[i][0])\n\t\t\t\tself._data[items[i][0]] = items[i][1]\n\t\tif kwdata:\n\t\t\tself._merge_keys(kwdata.iterkeys())\n\t\t\tself.update(kwdata)\n\n\n\tdef __repr__(self):\n\t\tresult = []\n\t\tfor key in self._keys:\n\t\t\tresult.append('(%s, %s)' % (repr(key), repr(self._data[key])))\n\t\treturn ''.join(['OrderedDict', '([', ', '.join(result), '])'])\n\n\n\tdef _merge_keys(self, keys):\n\t\tself._keys.extend(keys)\n\t\tnewkeys = {}\n\t\tself._keys = [newkeys.setdefault(x, x) for x in self._keys\n\t\t\tif x not in newkeys]\n\n\tdef __iter__(self):\n\t\tfor key in self._keys:\n\t\t\tyield key\n\n\n\tdef update(self, data):\n\t\tif data is not None:\n\t\t\tif hasattr(data, 'iterkeys'):\n\t\t\t\tself._merge_keys(data.iterkeys())\n\t\t\telse:\n\t\t\t\tself._merge_keys(data.keys())\n\t\t\tself._data.update(data)\n\n\n\n\tdef __setitem__(self, key, value):\n\t\tif key not in self._data:\n\t\t\tself._keys.append(key)\n\t\tself._data[key] = value\n\t\t\n\t\t\n\tdef __getitem__(self, key):\n\t\tif isinstance(key, slice):\n\t\t\tresult = [(k, self._data[k]) for k in self._keys[key]]\n\t\t\treturn OrderedDict(result)\n\t\treturn self._data[key]\n\t\n\t\n\tdef __delitem__(self, key):\n\t\tdel self._data[key]\n\t\tself._keys.remove(key)\n\t\t\n\t\t\n\tdef keys(self):\n\t\treturn list(self._keys)\n\t\n\t\n\tdef copy(self):\n\t\tcopyDict = odict()\n\t\tcopyDict._data = self._data.copy()\n\t\tcopyDict._keys = self._keys[:]\n\t\treturn copyDict\n\n\n# =============================================================\nimport collections\n\nKEY, PREV, NEXT = range(3)\n\nclass oset(collections.MutableSet):\n\t\"\"\"Set that remembers original insertion order.\n\n\tRuns on Py2.6 or later (and runs on 3.0 or later without any\n\tmodifications).\n\n\tImplementation based on a doubly linked link and an internal\n\tdictionary. This design gives OrderedSet the same big-Oh running\n\ttimes as regular sets including O(1) adds, removes, and lookups as\n\twell as O(n) iteration.\n\n\tSee:\n\t\thttp://code.activestate.com/recipes/576694/\n\n\tdoctest:\n\t\t>>> import ordered\n\t\t>>> print(ordered.oset('abracadaba'))\n\t\toset(['a', 'b', 'r', 'c', 'd'])\n\t\"\"\"\n\n\tdef __init__(self, iterable=None):\n\t\tself.end = end = [] \n\t\tend += [None, end, end]\t\t\t# sentinel node for doubly linked list\n\t\tself.map = {}\t\t\t\t\t# key --> [key, prev, next]\n\t\tif iterable is not None:\n\t\t\tself |= iterable\n\n\tdef __len__(self):\n\t\treturn len(self.map)\n\n\tdef __contains__(self, key):\n\t\treturn key in self.map\n\n\tdef add(self, key):\n\t\tif key not in self.map:\n\t\t\tend = self.end\n\t\t\tcurr = end[PREV]\n\t\t\tcurr[NEXT] = end[PREV] = self.map[key] = [key, curr, end]\n\n\tdef discard(self, key):\n\t\tif key in self.map:\t\t \n\t\t\tkey, prev, next = self.map.pop(key)\n\t\t\tprev[NEXT] = next\n\t\t\tnext[PREV] = prev\n\n\tdef __iter__(self):\n\t\tend = self.end\n\t\tcurr = end[NEXT]\n\t\twhile curr is not end:\n\t\t\tyield curr[KEY]\n\t\t\tcurr = curr[NEXT]\n\n\tdef __reversed__(self):\n\t\tend = self.end\n\t\tcurr = end[PREV]\n\t\twhile curr is not end:\n\t\t\tyield curr[KEY]\n\t\t\tcurr = curr[PREV]\n\n\tdef pop(self, last=True):\n\t\tif not self:\n\t\t\traise KeyError('set is empty')\n\t\tkey = next(reversed(self)) if last else next(iter(self))\n\t\tself.discard(key)\n\t\treturn key\n\n\tdef __repr__(self):\n\t\tif not self:\n\t\t\treturn '%s()' % (self.__class__.__name__,)\n\t\treturn '%s(%r)' % (self.__class__.__name__, list(self))\n\n\tdef __eq__(self, other):\n\t\tif isinstance(other, OrderedSet):\n\t\t\treturn len(self) == len(other) and list(self) == list(other)\n\t\treturn set(self) == set(other)\n\n\tdef __del__(self):\n\t\tself.clear()\t\t\t\t\t# remove circular references\n\n\n#if __name__ == '__main__':\n#\t print(OrderedSet('abracadaba'))\n#\t print(OrderedSet('simsalabim'))\n\n\n# ======================================\n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n","sub_path":"ordered.py","file_name":"ordered.py","file_ext":"py","file_size_in_byte":6425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"612039603","text":"import os\n\nimport gym\nfrom gym import spaces\n\nfrom dataset import *\nfrom utils.binary import *\nfrom utils.config import *\n\nn_samples = 8\nwidth = 224\nheight = 224\nn_channels = 3\nframe_step = 6\n\n\nclass CustomEnv(gym.Env):\n\n def __init__(self, video_type=\"train\"):\n self.train, self.validation, self.test = Sal360.load_sal360v2()\n self.width, self.height = 3840, 1920\n self.x_dict, self.y_dict = None, None\n self.x_iter, self.y_iter = None, None\n self.target_videos = None\n self.target_video = None\n self.files = os.listdir(video_path)\n self.action_space = spaces.Box(-1, 1, [2]) # -1,1 사이의 1x2 벡터\n self.observation_space = spaces.Box(low=0, high=255, shape=(width, height, n_channels))\n\n self.view = None # viewport's area / current state\n self.saliency_view = None\n self.observation = None\n self.video_path = None\n self.files = None\n self.trajectory = False\n self.time_step = 0\n self.saliency_info = get_SalMap_info()\n self.set_dataset(video_type)\n\n def set_dataset(self, video_type=\"train\"):\n if video_type == \"train\":\n self.x_dict, self.y_dict = self.train\n self.video_path = os.path.join(video_path, \"train\", \"3840x1920\")\n elif video_type == \"validation\":\n self.x_dict, self.y_dict = self.validation\n self.video_path = os.path.join(video_path, \"train\", \"3840x1920\")\n elif video_type == \"test\":\n self.x_dict, self.y_dict = self.test\n self.video_path = os.path.join(video_path, \"test\", \"3840x1920\")\n else:\n raise NotImplementedError\n self.target_videos = os.listdir(self.video_path)\n\n def step(self, action=None):\n x_data, y_data = next(self.x_iter), next(self.y_iter)\n step_idx, lat, lng, start_frame, end_frame = int(x_data[0]), x_data[2], x_data[1], int(x_data[5]), int(\n x_data[6])\n done = True if step_idx == 99 else False\n\n if self.trajectory:\n self.view.set_center((lat, lng), normalize=True)\n self.saliency_view.set_center((lat, lng), normalize=True)\n self.observation = [cv2.resize(self.view.get_view(f), (width, height)) for f in\n self.video[start_frame - 1:end_frame]]\n\n saliency_observation = [self.saliency_view.get_view(f) for f in self.saliency[start_frame - 1:end_frame]]\n assert len(self.observation) == len(saliency_observation)\n\n total_sum = np.sum(self.saliency[start_frame - 1:end_frame])\n observation = self.observation.copy()\n embed = np.zeros(shape=(width, height, n_channels)) + 256.\n for _ in range(n_samples - len(observation)):\n observation = np.concatenate([observation, [embed]])\n assert len(observation) == n_samples\n\n observation_sum = np.sum(saliency_observation)\n reward = observation_sum / total_sum\n\n return observation, reward, done, y_data\n else:\n self.view.move(action)\n self.saliency_view.move(action)\n self.view.set_center((lat, lng), normalize=True)\n self.saliency_view.set_center((lat, lng), normalize=True)\n self.observation = [cv2.resize(self.view.get_view(f), (width, height)) for f in\n self.video[self.time_step:self.time_step+frame_step]]\n if len(self.observation) < frame_step:\n return None, None, True, None\n else:\n saliency_observation = [self.saliency_view.get_view(f) for f in self.saliency[self.time_step:self.time_step+frame_step]]\n total_sum = np.sum(self.saliency[self.time_step:self.time_step+frame_step])\n observation_sum = np.sum(saliency_observation)\n reward = observation_sum / total_sum\n self.time_step += frame_step\n return self.observation, reward, done, None\n\n def reset(self, video_type=\"train\", trajectory=False):\n self.trajectory = trajectory\n self.time_step = 0\n self.view = Viewport(self.width, self.height)\n self.saliency_view = Viewport(2048, 1024)\n self.set_dataset(video_type)\n self.target_video = random.choice(self.target_videos)\n print(self.target_video + \" start\")\n ran_idx = random.randint(0, len(self.x_dict[self.target_video]) - 1)\n ran_x, ran_y = self.x_dict[self.target_video][ran_idx], self.y_dict[self.target_video][ran_idx]\n self.saliency = read_SalMap(self.saliency_info[self.target_video])\n self.video = []\n cap = cv2.VideoCapture(os.path.join(self.video_path, self.target_video))\n while True:\n ret, frame = cap.read()\n if ret:\n self.video.append(frame)\n else:\n cap.release()\n break\n self.x_iter, self.y_iter = iter(ran_x), iter(ran_y)\n x_data, y_data = next(self.x_iter), next(self.y_iter)\n lat, lng, start_frame, end_frame = x_data[2], x_data[1], int(x_data[5]), int(x_data[6])\n self.view.set_center((lat, lng), normalize=True)\n if self.trajectory:\n self.observation = [cv2.resize(self.view.get_view(f), (width, height)) for f in\n self.video[start_frame - 1:end_frame]]\n embed = np.zeros(shape=(width, height, n_channels)) + 256.\n observation = self.observation.copy()\n for _ in range(n_samples - len(observation)):\n observation = np.concatenate([observation, [embed]])\n assert len(observation) == n_samples\n return observation, y_data, self.target_video\n else:\n self.observation = [cv2.resize(self.view.get_view(f), (width, height)) for f in\n self.video[self.time_step:self.time_step+frame_step]]\n return self.observation, y_data, self.target_video\n\n def render(self, mode='human'):\n for f in self.observation:\n cv2.imshow(\"render\", f)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n\ndef ttest(max_epochs=0):\n env = CustomEnv()\n epoch = 0\n while epoch < max_epochs:\n obs, acs, next_obs, rewards, dones = [], [], [], [], []\n ob, ac, target_video = env.reset(trajectory=False)\n while True:\n next_ob, reward, done, next_ac = env.step([0.1, 0.1])\n env.render()\n print(np.shape(ob), np.shape(next_ob), ac, next_ac, reward, done)\n obs.append(ob)\n acs.append(ac)\n next_obs.append(next_ob)\n rewards.append(reward)\n dones.append(done)\n if done:\n break\n\n ob = next_ob\n ac = next_ac\n # env.render()\n print(\"epoch # of \", epoch)\n print(\"obs shape: \", np.shape(obs))\n print(\"acs shape: \", np.shape(acs), acs[0])\n print(\"next_obs shape:\", np.shape(next_obs))\n print(\"rewards shape: \", np.shape(rewards))\n print(\"dones shape: \", np.shape(dones))\n epoch += 1\n\n\nif __name__ == '__main__':\n ttest(1)\n","sub_path":"custom_env/envs.py","file_name":"envs.py","file_ext":"py","file_size_in_byte":7240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"27739702","text":"import argparse\nimport json\nfrom quarkchain.core import Address, Identity\nfrom quarkchain.utils import sha3_256\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--num_accounts\", default=10, type=int)\n parser.add_argument(\"--shard\", default=-1, type=int)\n parser.add_argument(\"--shard_size\", default=256, type=int)\n args = parser.parse_args()\n return args\n\n\ndef main():\n args = parse_args()\n result = []\n while True:\n identity = Identity.create_random_identity()\n address = Address.create_from_identity(identity)\n if args.shard > -1:\n # Follow the same algorithm in testnet web\n fullShard = int.from_bytes(\n sha3_256(address.recipient.hex().encode(\"utf-8\"))[:4], \"big\"\n )\n shard = fullShard & (args.shard_size - 1)\n if shard != args.shard:\n continue\n address = Address.create_from_identity(identity, fullShard)\n result.append({\"address\": address.to_hex(), \"key\": identity.get_key().hex()})\n args.num_accounts -= 1\n if args.num_accounts == 0:\n break\n\n print(json.dumps(result, indent=4))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"quarkchain/testnet/generate_accounts.py","file_name":"generate_accounts.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"356966138","text":"#! /usr/bin/python\nimport os\nfrom datetime import datetime\nimport json\nimport logging\nimport logging.config\n\nimport paho.mqtt.client as mqtt\n\nfrom xbee import ZigBee\nimport serial\nimport struct\n\n\n# Load logging config from logging.json\ndef setup_logging(default_path='logging.json', default_level=logging.INFO, env_key='LOG_CFG'):\n path = default_path\n value = os.getenv(env_key, None)\n if value:\n path = value\n if os.path.exists(path):\n with open(path, 'rt') as f:\n config = json.load(f)\n logging.config.dictConfig(config)\n logging.info(\"Configured logging from json\")\n else:\n logging.basicConfig(level=default_level)\n logging.info(\"Configured logging basic\")\n\n# Load the friendly name lookups from json\nfriendly = {\"appIDs\":{}, \"msgTypes\":{}, \"xbees\":{}}\ndef getFriendly(default_path=\"friendly.json\"):\n global friendly\n path = default_path\n if os.path.exists(path):\n with open(path, 'rt') as f:\n friendly = json.load(f)\n logging.info(\"Loaded friendly names: \" + str(friendly))\n\nclass zbDataLogger:\n def __init__(self, port='/dev/ttyUSB0', baud=9600, escaped=True, appLog=None):\n self.appLog = appLog or logging.getLogger(__name__)\n self.port = port\n self.baud = baud\n self.escaped = escaped\n try:\n self.serial_port = serial.Serial(self.port, self.baud)\n self.xbee = ZigBee(self.serial_port, escaped=self.escaped)\n self.appLog.info(\"Successfully initialised ZigBee on \" + self.port + \" at \" + str(self.baud) + \" baud\")\n except:\n self.appLog.error(\"Unable to initialise Zigbee on \" + self.port + \" at \" + str(self.baud) + \" baud\")\n raise\n self.frame = \"\"\n self.msg = {}\n self.data = \"\"\n self.appHandlers = {}\n\n def getMsg(self):\n self.frame = self.xbee.wait_read_frame() # blocking\n self.rfdata = self.frame.get(\"rf_data\")\n self.msg[\"source\"] = \"0x%0.16X\" % struct.unpack(\">Q\",self.frame.get(\"source_addr_long\"))\n # convert to friendly name if we have defined it\n if self.msg[\"source\"] in friendly[\"xbees\"]:\n self.msg[\"source\"] = friendly[\"xbees\"][self.msg[\"source\"]]\n self.appLog.debug(\"Got message\")\n self.msg[\"logtime\"] = datetime.isoformat(datetime.now())\n\n decodeHdr = struct.unpack(\"HHHH\", self.rfdata[0:8])\n self.msg[\"appID\"]= \"0x%0.4X\" % decodeHdr[0]\n self.msg[\"msgType\"] = \"0x%0.4X\" % decodeHdr[1]\n # convert to friendly names if we have defined them\n if self.msg[\"appID\"] in friendly[\"appIDs\"]:\n self.msg[\"appID\"] = friendly[\"appIDs\"][self.msg[\"appID\"]]\n if self.msg[\"appID\"] in friendly[\"msgTypes\"]:\n if self.msg[\"msgType\"] in friendly[\"msgTypes\"][self.msg[\"appID\"]]:\n self.msg[\"msgType\"] = friendly[\"msgTypes\"][self.msg[\"appID\"]][self.msg[\"msgType\"]]\n self.msg[\"reserved\"] = decodeHdr[2]\n self.msg[\"length\"] = decodeHdr[3]\n self.msg[\"data\"] = self.rfdata[8:]\n if self.msg[\"length\"] != len(self.msg[\"data\"]):\n self.appLog.error(\"Incorrect data length in received packet. Rx: %s, Expected: %s\" % (len(self.msg[\"data\"]), self.msg[\"length\"]))\n else:\n if self.msg[\"appID\"] in self.appHandlers:\n self.appLog.debug(\"Handling application ID: %s\" % self.msg[\"appID\"])\n return self.appHandlers[self.msg[\"appID\"]].decode(self.msg)\n else:\n self.appLog.warn(\"No handler registered for appID %s, dropping message...\" % self.msg[\"appID\"])\n return []\n\n def register(self, appID, handler):\n self.appHandlers[appID] = handler\n self.appLog.info(\"Registered handler for appID: %s\" % appID)\n\n\n# a handler class to allow indirection of message handling\nclass appHandler:\n def __init__(self, parent, appID, appLog=None):\n self.appLog = appLog or logging.getLogger(__name__)\n self.parent = parent\n # Convert appID to friendly name if we have defined one\n if appID[0:2] == \"0x\":\n if appID in friendly[\"appIDs\"]:\n self.appID = friendly[\"appIDs\"][appID]\n self.appLog.info(\"Converted appID %s to friendly name: %s\" % (appID, self.appID))\n else:\n self.appID = appID\n self.appLog.info(\"Unable to convert appID %s to a friendly name\" % appID)\n self.msgHandlers = {}\n self.parent.register(self.appID, self)\n\n def register(self, msgType, handler):\n msgName = msgType\n # Convert to friendly name if we have defined one\n if msgType[0:2] == \"0x\":\n if self.appID in friendly[\"msgTypes\"]:\n self.appLog.debug(\"Looking up msgType %s in appID %s\", msgType, self.appID)\n if msgType in friendly[\"msgTypes\"][self.appID]:\n msgName = friendly[\"msgTypes\"][self.appID][msgType]\n self.appLog.info(\"Converted msgType %s to friendly name %s\" % (msgType, msgName))\n else:\n self.appLog.info(\"Unable to convert msgType %s to friendly name\", msgType)\n self.msgHandlers[msgName] = handler\n self.appLog.info(\"Registered handler for msgType: %s\" % msgName)\n\n def decode(self, msg, log=True):\n if self.appID != msg[\"appID\"]:\n self.appLog.error(\"Passed a message that I didn't register for. My appID: %s, message appID: %s\" % (self.appID, msg[\"appID\"]))\n else:\n if msg[\"msgType\"] in self.msgHandlers:\n self.appLog.debug(\"Handling message type: %s\" % msg[\"msgType\"])\n msg = self.msgHandlers[msg[\"msgType\"]].decode(msg)\n if log:\n self.logCSV(msg)\n return msg\n else:\n self.appLog.warn(\"No handler registered for msgType %s, dropping message...\" % msg[\"msgType\"])\n return None\n\n def logCSV(self, msg):\n logger_name = \"%s.%s.%s\" % (msg[\"appID\"], msg[\"msgType\"], msg[\"source\"])\n msg[\"logger_name\"] = logger_name\n logger = logging.getLogger(logger_name)\n # can we remove the line below? Seems to be happening in decode already?\n msg = self.msgHandlers[msg[\"msgType\"]].decode(msg)\n if \"csv\" in msg:\n logger.info(msg[\"csv\"])\n else:\n self.appLog.error(\"No CSV data has been decoded. Have you specified the fields to be listed in the CSV?\")\n return msg\n\n# The msgHandler class is a prototype class that should be subclassed to do something useful\nclass msgHandler:\n def __init__(self, parent, msgTypes=[], appLog=None):\n self.appLog = appLog or logging.getLogger(__name__)\n self.msgTypes = msgTypes\n self.parent = parent\n self.CSVFields = None\n self.JSONFields = None\n for msgType in msgTypes:\n self.appLog.debug (\"Registering as handler for msgType %s\" % msgType)\n self.parent.register(msgType, self)\n\n\n def decode(self, msg):\n # this is where the final message decoding happens - return an object containing the message items\n # do the work here and add values into the msg Dictionary\n return msg\n\n def createFields(self, msg):\n if self.CSVFields != None:\n csv = []\n self.appLog.debug(\"Creating CSV logline using the following fields: \" + str(self.CSVFields))\n for ref in self.CSVFields:\n if ref in msg:\n csv.append(str(msg[ref]))\n else:\n self.appLog.error(\"Error creating CSV, requested item not available: %s\" % ref)\n msg[\"csv\"] = ','.join(csv)\n\n if self.JSONFields != None:\n csv = {}\n self.appLog.debug(\"Creating JSON data using the following fields: \" + str(self.JSONFields))\n for ref in self.JSONFields:\n if ref in msg:\n csv[ref] = msg[ref]\n else:\n self.appLog.error(\"Error creating JSON, requested item not available: %s\" % ref)\n msg[\"json\"] = json.dumps(csv)\n\n return msg\n\n def setCSVFields(self, fields=None):\n self.appLog.info(\"Setting CSV Fields to: \" + str(fields))\n self.CSVFields = fields\n\n def getCSVFields(self):\n return self.CSVFields\n\n def setJSONFields(self, fields = None):\n self.appLog.info(\"Setting JSON Fields to: \" + str(fields))\n self.JSONFields = fields\n\n def getJSONFields(self):\n return self.JSONFields\n\n\n# a concrete class that unpacks the data for a protocol and implements a msgHandler\nclass weatherHandler(msgHandler):\n def __init__(self, parent):\n msgHandler.__init__(self, parent, [\"0x0001\"])\n self.setCSVFields([\"logtime\", \"millis\", \"inT1\", \"inT2\", \"inT3\", \"outT\", \"pressure\", \"humidity\",\\\n \"light\", \"battery\", \"solar\"])\n self.setJSONFields([\"logtime\", \"millis\", \"inT1\", \"inT2\", \"inT3\", \"outT\", \"pressure\", \"humidity\",\\\n \"light\", \"battery\", \"solar\"])\n\n def decode(self, msg):\n values = struct.unpack(\"Iihhhhhhhh\", msg[\"data\"])\n msg[\"millis\"] = values[0]\n msg[\"pressure\"] = values[1]/100.0\n msg[\"inT1\"] = values[2]/100.0\n msg[\"inT2\"] = values[3]/100.0\n msg[\"inT3\"] = values[4]/100.0\n msg[\"outT\"] = values[5]/100.0\n msg[\"humidity\"] = values[6]/100.0\n msg[\"light\"] = values[7]\n msg[\"battery\"] = (values[8]*64)/10000.0 # Should give 5 decimal places\n msg[\"solar\"] = (values[9]*64)/10000.0 # Should give 5 decimal places\n\n return self.createFields(msg)\n\nclass txStatusHandler(msgHandler):\n def __init__(self, parent):\n msgHandler.__init__(self, parent, [\"0x0001\"])\n self.setCSVFields([\"logtime\", \"millis\", \"packets\", \"cts_timeout\", \"local_timeout\", \"network_ack\",\\\n \"not_joined\", \"cca\", \"invalid_dest\", \"self_addr\", \"addr_not_found\", \"no_route\",\\\n \"payload_too_big\", \"other\"])\n #self.setJSONFields(i[\"logtime\", \"millis\", \"packets\", \"cts_timeout\", \"local_timeout\", \"network_ack\",\\\n # \"not_joined\", \"cca\", \"invalid_dest\", \"self_addr\", \"addr_not_found\", \"no_route\",\\\n # \"payload_too_big\", \"other\"])\n\n def decode(self, msg):\n try:\n values = struct.unpack(\"IHHHHHHHHHHHHH\", msg[\"data\"])\n msg[\"millis\"] = values[0]\n msg[\"packets\"] = values[1]\n msg[\"cts_timeout\"] = values[2]\n msg[\"local_timeout\"] = values[3]\n msg[\"cca\"] = values[4]\n msg[\"invalid_dest\"] = values[5]\n msg[\"network_ack\"] = values[6]\n msg[\"not_joined\"] = values[7]\n msg[\"self_addr\"] = values[8]\n msg[\"addr_not_found\"] = values[9]\n msg[\"no_route\"] = values[10]\n msg[\"payload_too_big\"] = values[11]\n msg[\"other\"] = values[12] + values[13]\n except:\n self.appLog.error(\"Error decoding TxStatus data. Actual data length received is: \" + str(len(msg[\"data\"])))\n return self.createFields(msg)\n\nclass gateHandler(msgHandler):\n def __init__(self, parent):\n msgHandler.__init__(self, parent, [\"0x0000\"])\n self.setCSVFields([\"logtime\", \"millis\", \"watchdog_count\", \"battery\", \"solar\", \"charge\", \"gate\", \"movement\",\\\n \"trigger\", \"triggered_by\"])\n self.setJSONFields([\"logtime\", \"millis\", \"watchdog_count\", \"battery\", \"solar\", \"charge\", \"gate\", \"movement\",\\\n \"trigger\", \"triggered_by\"])\n\n def decode(self, msg):\n trigger_reasons = [\"Gate Closed\", \"Gate Opened\", \"Movement Detected\", \"Movement Stopped\", \"Heartbeat\"]\n charge_states = [\"sleeping\", \"charging\", \"full\", \"error\"]\n try:\n values = struct.unpack(\"IIHHBBBB\", msg[\"data\"])\n msg[\"millis\"] = values[0]\n msg[\"watchdog_count\"] = values[1]\n msg[\"battery\"] = values[2]\n msg[\"solar\"] = values[3]\n msg[\"charge\"] = charge_states[values[4]]\n msg[\"gate\"] = values[5]\n msg[\"movement\"] = values[6]\n msg[\"trigger\"] = values[7]\n\n # Do some processing of the data to provide additional information\n # Provide a human readable trigger\n msg[\"triggered_by\"] = trigger_reasons[msg[\"trigger\"]]\n except:\n self.applog.error(\"Error decoding Gate update message. Actual length received is: \" + str(len(msg[\"data\"])))\n return self.createFields(msg)\n\n\ndef mqtt_connect(client):\n # Settings for MQTT Server\n DOCKER_MQTT_ADDR = os.environ.get('MOSQUITTO_PORT_1883_TCP_ADDR', None)\n DOCKER_MQTT_PORT = os.environ.get('MOSQUITTO_PORT_1883_TCP_PORT', None)\n\n if DOCKER_MQTT_PORT is not None and DOCKER_MQTT_ADDR is not None:\n # We are running in a Linked Docker environment\n # Use Docker Linked Container environment variables for setup\n MQTT_HOST = DOCKER_MQTT_ADDR\n MQTT_PORT = DOCKER_MQTT_PORT\n else:\n # Provide some fallback in case running outside Docker\n MQTT_HOST = 'localhost'\n MQTT_PORT = 1883\n # Connect to the mqtt server\n client.connect(MQTT_HOST, MQTT_PORT, 60)\n\n# MQTT callbacks\ndef on_connect(client, userdata, flags, rc):\n #Subscribe to any mqtt feeds here\n datalog = logging.getLogger('data')\n datalog.info(\"Connected to MQTT Broker\")\n client.subscribe(\"GateGuard/Event\")\n\ndef on_message(client, userdata, msg):\n # Do something with the incoming messages\n datalog = logging.getLogger(\"data\")\n datalog.debug(\"Received from mqtt broker: \" + msg.topic + \" \" + str(msg.payload))\n\nif __name__ == '__main__':\n # Configure the logs\n setup_logging(default_level=logging.DEBUG)\n getFriendly()\n datalog = logging.getLogger(\"data\")\n datalog.info(\"Starting logging...\")\n zbdl = zbDataLogger()\n # Connect to the mqtt broker\n # Get the appropriate mqtt connection parameters\n client = mqtt.Client()\n client.on_connect = on_connect\n client.on_message = on_message\n mqtt_connect(client)\n\n weatherApp = appHandler(zbdl, \"0x10A1\")\n weatherMsg = weatherHandler(weatherApp)\n txStatusApp = appHandler(zbdl, \"0x0573\")\n txStatusMsg = txStatusHandler(txStatusApp)\n gateApp = appHandler(zbdl, \"0x10A5\")\n gateMsg = gateHandler(gateApp)\n while True:\n client.loop_start()\n data = zbdl.getMsg()\n if \"csv\" in data:\n datalog.info(data[\"csv\"])\n if \"json\" in data:\n if data[\"triggered_by\"] != \"Heartbeat\":\n client.publish(data[\"appID\"] + \"/Event\", data[\"json\"])\n else:\n client.publish(data[\"appID\"] + \"/Heartbeat\", data[\"json\"])\n client.loop_stop()\n","sub_path":"datalogger.py","file_name":"datalogger.py","file_ext":"py","file_size_in_byte":14884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"277765247","text":"def init_hanzi_resource(resource_file=\"./hanzi_gb2312\"):\n '''\n https://www.qqxiuzi.cn/zh/hanzi-gb2312-bianma.php\n 根据资源表 整理成列表形式\n :param resource_file:\n :return:\n '''\n result = {}\n # 汉字对应的GB2312编码数字\n hanzi_num_dict = {}\n index = 0\n word_index = 0\n with open(resource_file,\"r\",encoding=\"utf-8\") as rd:\n lines = rd.readlines()\n tmp_result = []\n for line in lines:\n line = line.replace(\"\\n\",\"\")\n clean_line = line.replace(\" \",\"\")\n #print(clean_line)\n if not clean_line.isdigit():\n if len(str(clean_line).strip())!=0:\n line = line[2:]\n hanzis = line.split(\" \")\n for hanzi in hanzis:\n # 从第10行开始时汉字了\n if index>9:\n hanzi = eval(\"u\"+\"\\'\"+str(hanzi).strip()+\"\\'\")\n tmp_result.append(hanzi)\n zone_id = str(index)\n word_id = str(word_index)\n if len(str(index))==1:\n zone_id = \"0\"+zone_id\n if len(str(word_id))==1:\n word_id = \"0\" +word_id\n hanzi_num_dict[hanzi] = zone_id+word_id\n # 一个区 可能跨越多行,区中汉字的序号要连续\n word_index = word_index + 1\n else:\n key = str(index)\n if len(key)==1:\n key = \"0\"+key\n result[key]=tmp_result\n tmp_result= []\n else:\n #print(\"读取到数字行了\\t\",clean_line)\n index = clean_line[:2]\n if index.startswith(\"0\"):\n index = index[1:]\n index = int(index)\n word_index = 0\n return result,hanzi_num_dict\n\ndef search_number2hanzi(hanzi_list,number):\n '''\n 根据编码数字查询对应的汉字\n :param hanzi_list: 87行GB2312汉字列表,每一行包含94个汉字 https://www.qqxiuzi.cn/zh/hanzi-gb2312-bianma.php\n :param number:\n :return:\n '''\n\n head =str(number)[:2]\n tail = str(number)[2:]\n if (tail.startswith(\"0\")):\n tail = tail[1:]\n hanzi = hanzi_list[head][int(tail)]\n print(\"数字 %s 对应的汉字是 %s \"%(str(number),hanzi))\n\n","sub_path":"hanzi.py","file_name":"hanzi.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"317464264","text":"\"\"\"\nGiven a linked list, swap every two adjacent nodes and return its head.\n\nYou may not modify the values in the list's nodes, only nodes itself may be changed.\n\nGiven 1->2->3->4, you should return the list as 2->1->4->3.\n\"\"\"\n\nclass ListNode:\n def __init__(self, val, next=None):\n self.val = val\n self.next = next\n\ndef swap_nodes(head):\n if not head or not head.next:\n return head \n\n node = head.next\n \n curr = head.next \n prev = head\n while True:\n next = curr.next\n curr.next = prev \n if not next or not next.next:\n prev.next = next; \n break; \n prev.next = next.next; \n prev = next; \n curr = prev.next\n return node\n\nn = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5, ListNode(6))))))\nh = swap_nodes(n)\nwhile h:\n print(h.val)\n h=h.next","sub_path":"LinkedList/swap_nodes.py","file_name":"swap_nodes.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"457432931","text":"import cfgs.config as cfg\nfrom datasets.lisa_hd import LISADataset\nfrom datasets.utils.augmentation import data_augmentation\nfrom datasets.utils.visualize import plot_bboxes\n\nimdb = LISADataset('train', cfg.DATA_DIR, transform=None,\n use_cache=False)\n\n\nimg, ori_img, targets = imdb[0]\nbboxes = targets['boxes']\n\nshape = (cfg.inp_size)\njitter = 0.1\nhue = 0.1\nsaturation = 1.5\nexposure = 1.5\nprint('old size ', img.height, img.width)\n\nplot_bboxes(img, bboxes)\n\n# Transform img and bboxes\nnew_img, new_bboxes = data_augmentation(img, bboxes, shape, jitter, hue,\n saturation, exposure)\nplot_bboxes(new_img, new_bboxes)\n\n","sub_path":"test_augmentation.py","file_name":"test_augmentation.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"561121899","text":"\"\"\"\nETAPE 2: désambiguisation\n\"\"\"\n\nfrom pywsd import disambiguate\nfrom pywsd.similarity import max_similarity as maxsim\nfrom nltk import tokenize\nimport json\n\n# Variables globales\nwith open('./restructured_data.json', 'r') as f:\n DATA = json.load(f)\nNEW_TEXT_DATA = list()\n\n# Traitement des données\nfor text_data in DATA.get(\"donnees_textuelles\"):\n # Variables principales de la boucle\n text = text_data.get(\"texte\")\n n = text_data.get(\"n\")\n wsd = list()\n count = 1\n\n # Séparation en phrases et désambigusation\n sentences = tokenize.sent_tokenize(text)\n for sentence in sentences:\n wsd.extend(disambiguate(sentence, algorithm=maxsim,\n similarity_option='wup', keepLemmas=True))\n print(\"Set \" + str(n) + \": sentence \" +\n str(count) + \" out of \" + str(len(sentences)))\n count += 1\n\n # Créer une seconde liste en triant les données\n wsd2 = list()\n for word_data in wsd:\n wsd2.append((word_data[0], word_data[1], word_data[2].name(\n ) if word_data[2] is not None else word_data[2]))\n\n # Finaliser les nouvelles données\n NEW_TEXT_DATA.append({\n \"n\": n,\n \"texte\": text,\n \"wsd\": wsd2\n })\n\nwith open('./hom.od_eng_disamb.json', 'w') as f:\n json.dump({\n \"titre\": DATA.get(\"titre\"),\n \"auteur\": DATA.get(\"auteur\"),\n \"donnees_textuelles\": NEW_TEXT_DATA\n }, f)\n","sub_path":"etape_2/disambiguate.py","file_name":"disambiguate.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"375809361","text":"import json\nfrom tests.base_test_case import ApiTestCase\nfrom app.models import Meal\n\n\nclass TestMealsApiTestCase(ApiTestCase):\n \"\"\"\n Tests for the admin meals api\n \"\"\"\n\n def setUp(self):\n super(TestMealsApiTestCase, self).setUp()\n self.admin_token, self.admin = self.login_admin('s@admin.com')\n self.user_token, self.customer_user = self.login_test_user(\n 'self@tesst.com')\n self.meal = Meal(title='lorem ipsum', price=2000,\n description='lorem ipsum', catering=self.admin.catering)\n self.meal.save()\n\n def post_meal(self, token):\n res = self.client().post(\n self.meals_endpoint,\n headers={\n 'Authorization': token,\n 'Content-Type': 'application/json'\n },\n data=json.dumps({\n 'title': 'Beef with matooke',\n 'price': 10000,\n 'description': 'lorem ispunm'\n })\n )\n return res\n\n def test_unauthenticated_admin_cannot_access_meals(self):\n res = self.client().get(self.meals_endpoint)\n self.assertEqual(res.status_code, 401)\n data = self.get_response_data(res)\n self.assertEqual(\n 'No Bearer token in Authorisation header', data['message'])\n\n def test_only_admin_can_access_meals(self):\n res = self.client().get(self.meals_endpoint, headers={\n 'Authorization': self.user_token})\n self.assertEqual(res.status_code, 403)\n data = self.get_response_data(res)\n self.assertEqual('403 forbidden access is denied', data['message'])\n\n def test_admin_can_access_meals(self):\n res = self.client().get(self.meals_endpoint, headers={\n 'Authorization': self.admin_token})\n self.assertEqual(res.status_code, 200)\n data = self.get_response_data(res)\n self.assertIn('meals', data)\n\n def test_customer_cannot_post_meals(self):\n res = self.post_meal(self.user_token)\n self.assertEqual(res.status_code, 403)\n data = self.get_response_data(res)\n self.assertEqual('403 forbidden access is denied', data['message'])\n\n def test_admin_can_post_meal(self):\n res = self.post_meal(self.admin_token)\n data = self.get_response_data(res)\n\n self.assertEqual(res.status_code, 201)\n self.assertIn('id', data)\n\n def test_admin_can_edit_meal(self):\n res = self.modify_resource(\n self.meals_endpoint + '/{}'.format(self.meal.id),\n self.admin_token,\n {\n 'title': 'meal option121',\n 'price': 10000,\n 'description': 'lorem ispum'\n })\n\n data = self.get_response_data(res)\n self.assertEqual(res.status_code, 200)\n self.assertEqual(1, data['id'])\n\n def test_admin_can_delete_meal(self):\n res = self.client().delete(\n self.meals_endpoint + '/{}'.format(self.meal.id),\n headers={\n 'Authorization': self.admin_token\n }\n )\n self.assertEqual(res.status_code, 200)\n data = self.get_response_data(res)\n self.assertIn('message', data)\n\n def test_admin_cannot_delete_meal_that_doesnot_exist(self):\n res = self.client().delete(\n self.meals_endpoint + '/200',\n headers={\n 'Authorization': self.admin_token\n }\n )\n self.assertEqual(res.status_code, 400)\n data = self.get_response_data(res)\n self.assertEqual('No meal with such id 200 exists', data['message'])\n\n def test_admin_cannot_edit_meal_that_doesnot_exist(self):\n res = self.modify_resource(self.meals_endpoint + '/{}'.format(10000), self.admin_token, {\n 'title': 'meal detail',\n 'price': 10000,\n 'description': 'desc'\n })\n self.assertEqual(res.status_code, 400)\n data = self.get_response_data(res)\n self.assertEqual('No meal with such id 10000 exists', data['message'])\n\n def test_admin_can_get_meal(self):\n \"\"\"\n tests an admin can get a meal\n \"\"\"\n meal = self.add_test_meal(self.admin)\n endpoint = self.meals_endpoint + '/{0}'.format(meal.id)\n res = self.client().get(endpoint, headers={\n 'Authorization': self.admin_token\n })\n res_data = self.get_response_data(res)\n self.assertEqual(res.status_code, 200)\n self.assertEqual(res_data['id'], meal.id)\n\n def test_admin_cannot_get_nonexistent_meal(self):\n \"\"\"\n tests an admin cannot get non-existent meal\n \"\"\"\n endpoint = self.meals_endpoint + '/1000'\n res = self.client().get(endpoint, headers={\n 'Authorization': self.admin_token\n })\n res_data = self.get_response_data(res)\n self.assertEqual(res.status_code, 400)\n self.assertEqual(\n res_data['message'], 'No meal with such id 1000 exists')\n","sub_path":"tests/test_meals_api.py","file_name":"test_meals_api.py","file_ext":"py","file_size_in_byte":4998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"629975384","text":"class Solution1:\n \"\"\"\n 中心扩展法,时间复杂度为O(n^2)\n \"\"\"\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n if not s:\n return ''\n t = self.preprocess(s)\n n = len(t)\n p = [0 for _ in range(n)]\n for k in range(1, n-1):\n count = 0\n i = j = k\n while i >= 1 and j <= n-2:\n if t[i-1] == t[j+1]:\n count += 1\n i -= 1\n j += 1\n else:\n break\n p[k] = count\n\n length = max(p)\n t_index = p.index(length)\n res = t[t_index-length+1:t_index+length]\n\n return ''.join(res.split('#'))\n\n def preprocess(self, s):\n n = len(s)\n res = ''\n for i in range(n):\n res += '#' + s[i]\n res += '#'\n return res\n\n\nclass Solution2:\n # 中心扩展法的改进版,用到了当前最长回文字符串的对称性,减少不必要的计算。时间复杂度O(n)\n def longestPalindrome(self, s):\n \"\"\"\n :type s: str\n :rtype: str\n \"\"\"\n # 预处理字符串,可以将原本需要分奇偶讨论转变为一种情况。\n T = '#'.join('^{}$'.format(s))\n n = len(T)\n P = [0] * n\n C = R = 0\n for i in range(1, n - 1):\n # equals to i' = C - (i-C)\n P[i] = min(R - i, P[2 * C - i]) if R > i else 0\n\n # Attempt to expand palindrome centered at i\n while T[i + 1 + P[i]] == T[i - 1 - P[i]]:\n P[i] += 1\n\n # If palindrome centered at i expand past R,\n # adjust center based on expanded palindrome.\n if i + P[i] > R:\n C, R = i, i + P[i]\n\n # Find the maximum element in P.\n maxLen, centerIndex = max((n, i) for i, n in enumerate(P))\n return s[(centerIndex - maxLen) // 2: (centerIndex + maxLen) // 2]\n\n\nif __name__ == '__main__':\n s = Solution2()\n print(s.longestPalindrome('babcbabcbaccba'))\n","sub_path":"LeetCode(Python)/5. Longest Palindromic Substring.py","file_name":"5. Longest Palindromic Substring.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"75986727","text":"import GPUtil\nimport itertools\nimport string\nimport numpy as np\nimport time\nimport os\n\nexecute=True\n\nif 1:\n all_lr = [0.001, 0.01]\n all_epochs = [100]\n all_baseline = [0, 1]\n all_T = [5., 10., 20.]\n all_lamb = [0.5, 1.0]\n all_kd_scale = [1.]\n\n \nall_cmd = []\n\nall_configs = list(itertools.product(all_lr, all_epochs, all_baseline, all_T, all_lamb, all_kd_scale))\n\nprint('===> total number of configs: %d'%len(all_configs))\n\ncmd_main = 'python train_on_inverted.py --root ./distill/{exp_name} --lr {lr} --epochs {epochs} --baseline {baseline} --T {T} --lamb {lamb} --kd_scale {kd_scale}'\n\nrandom_names = np.random.choice([''.join(i) for i in itertools.product(string.ascii_lowercase, repeat=3)], len(all_configs))\n\nfor idx, (lr, epochs, baseline, T, lamb, kd_scale) in enumerate(all_configs):\n name = random_names[idx]\n command = cmd_main.format(exp_name=name,\n lr=lr,\n epochs=epochs,\n baseline=baseline,\n T=T,\n lamb=lamb,\n kd_scale=kd_scale\n )\n \n while 1:\n deviceIDs = GPUtil.getAvailable(order='first', limit=1, maxLoad=0.3, maxMemory=0.3, includeNan=False, excludeID=[], excludeUUID=[])\n if len(deviceIDs)>0:\n pre_cmd = 'CUDA_VISIBLE_DEVICES=%s'%deviceIDs[0]\n final_cmd = pre_cmd + ' ' + command + ' &'\n print('\\n\\n==> Now Submitting Job: ', final_cmd)\n \n if execute:\n os.system(final_cmd)\n time.sleep(60)\n break\n \n time.sleep(60)\n \n \n \n \n\n \n \n","sub_path":"quant_fl/job_submit_node.py","file_name":"job_submit_node.py","file_ext":"py","file_size_in_byte":1715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"364481720","text":"from tradingsimulation.agent.perception import Perception\nfrom tradingsimulation.book.order_book import OrderBook\nfrom gym import logger\nfrom tradingsimulation.constant import *\nimport random\nfrom tradingsimulation.agent.portfolio import Portfolio\n\n\nclass Agent:\n \"\"\"\n This class represents a basic agent taking random actions\n \"\"\"\n\n def __init__(self, env, id: int, action_space, perception=[1, 1]):\n self.id: int = id\n self.current_observations = None\n self.last_action: int = None\n self.action_space = action_space\n self.type = \"basic\"\n self.perception = Perception(environment_to_agent_func=perception[0], agent_to_environment_func=perception[1],\n price_action_dim=action_space)\n self.rewards = []\n # self.balance = START_BALANCE\n # self.shares_held = 0\n # self.trades = []\n # self.returns = pd.DataFrame()\n self.portfolio = Portfolio(START_BALANCE, env.num_steps)\n self.action_space_table = env.action_space_table\n self.state_size = self.perception.state_size\n self.is_last_order_traded = False\n # self.positions = []\n\n def act(self, order_book: OrderBook, episode: int, action_space_dim, obs):\n \"\"\"\n choose the right action\n @param order_book: the order book\n @param episode: the episode\n @param action_space_dim: dimension of action space\n @param obs: the observation\n @return:\n \"\"\"\n self.last_action = random.randint(0, len(self.action_space_table) - 1)\n order = self.perception.agent_to_environment_func(self.last_action, order_book, self, obs)\n # self.portfolio.orders = self.portfolio.orders.append(\n # {\"price\": order.price, \"type\": order.__class__.__name__, \"episode\": episode},\n # ignore_index=True)\n return order\n\n def update_current_observations(self, observations):\n \"\"\"\n update current observation\n @param observations:\n @return:\n \"\"\"\n self.current_observations = observations\n\n def update_policy(self, reward: float, obs: int, next_obs: int, action, done):\n \"\"\"\n Update policy from (s,a) pair taken\n\n @param reward:\n @param obs:\n @param next_obs:\n @param action:\n @param current_state_idx:\n @return:\n \"\"\"\n self.rewards.append(reward)\n logger.debug(\n \"state action {} type {} price {} reward {}\".format(str(self.last_action),\n str(action.__class__.__name__),\n str(action.price),\n str(reward)))\n if done:\n\n if action != None:\n # logger.info(\n # \"state {} action {} type reward {}\".format(str(obs.to_features()), str(self.last_action),\n # str(action),\n # str(reward)))\n return None\n\n def reset(self, portfolio=False):\n if portfolio:\n self.portfolio.reset()\n","sub_path":"tradingsimulation/agent/model/agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":3187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"293130366","text":"import matplotlib.pyplot as plt \nfrom matplotlib import style\nimport numpy as np \n\nfig = plt.figure()\nstyle.use('ggplot')\n\nimg = np.fromfile(\"../figures/johann/johann_fr37_pc.raw\", \n dtype=np.uint16).reshape((992,672))\nimg[:] = np.flipud(img)\n\nplt.imshow(img, cmap=\"gray\", interpolation=\"none\", vmax=10000)\nplt.colorbar()\nplt.grid(False)\nplt.axis('off')\n\n#plt.show()\n\nfrom utils import save_png\nsave_png(\n \"johann_fr37_raw\",\n fig,\n subdir=\"johann\",\n bbox_inches='tight'\n )\n","sub_path":"scripts/johann_fr37_raw.py","file_name":"johann_fr37_raw.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"475734136","text":"from flask import Flask, render_template, redirect, url_for, request, session, flash\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom functools import wraps\nimport os\n# import sqlite3\n\napp = Flask(__name__)\n\n#config\napp.config.from_object(os.environ['APP_SETTINGS'])\n#print(os.environ['APP_SETTINGS'])\n# app.config.from_object('config.DevelopmentConfig')\n\n#sessions relies on cookies to store information about user (which in our case is whether user is logged in or not). The difference between session and cookies is that\n# session stores the actual data of the user on the server side while on client side its just the session id.\n# So in order to access the real data, we need the encryption key which comes from the secret key variable.\n# app.secret_key = \"my precious\"\n# there are two security flaws with above declaration:\n# 1. the secret_key value should be completely random so its nearly impossible to guess. you may want to use a random key generator for this.\n# 2. This key should actually be placed in a secret configuration file which would then be added to the imports\n\n# app.database = \"sample.db\"\n# app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///posts.db'\n\n# Create the SQLAlchemy object\ndb = SQLAlchemy(app)\nfrom models import *\n\n# login required decorator\ndef login_required(f):\n @wraps(f)\n def wrap(*args, **kwargs):\n if 'logged_in' in session:\n return f(*args, **kwargs)\n else:\n flash('You need to login first')\n return redirect(url_for('login'))\n return wrap\n\n@app.route('/')\n@login_required\ndef home():\n # g.db = connect_db()\n # cur = g.db.execute('select * from posts')\n # posts = [dict(title=row[1], description=row[2]) for row in cur.fetchall()]\n # print (\"Posts: \",posts)\n # g.db.close()\n posts = db.session.query(BlogPost).all()\n return render_template('index.html', posts=posts)\n\n@app.route('/welcome')\n# @login_required\ndef welcome():\n return render_template(\"welcome.html\")\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n error = None\n if request.method == 'POST':\n if request.form['username'] != 'admin' or request.form['password'] != 'admin':\n error = 'Invalid credentials. Please try again.'\n else:\n session['logged_in'] = True\n flash('You were just logged in!')\n return redirect(url_for('home'))\n return render_template('login.html', error=error)\n\n@app.route('/logout')\n@login_required\ndef logout():\n session.pop('logged_in', None)\n # print(session['logged_in'])\n flash('You were just logged out!')\n return redirect(url_for('welcome'))\n\n# def connect_db():\n# return sqlite3.connect(app.database)\n# return sqlite3.connect('posts.db')\n\nif __name__=='__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"596565136","text":"def escribir_vector(V):\n i=0\n print ('[', end='')\n while i None:\n \"\"\"Initialize class object.\n :param video_path: path to the video\n :param model_path: path to the model\n :param threshold: value to compare with error\n :param step: step for the next index in comparing\n :return: initialize class object\n :rtype: None\n \"\"\"\n self.video_path = video_path\n self.cap = cv.VideoCapture(video_path)\n\n self.model = torch.load(model_path)\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n self.model.to(self.device)\n\n self._threshold = threshold\n self.fps = self.cap.get(cv.CAP_PROP_FPS)\n self.num_frames = int(self.cap.get(cv.CAP_PROP_FRAME_COUNT))\n self.dict_time = {}\n self._step = step\n self.num_changes = None\n self.graphic_timecodes = {}\n\n @staticmethod\n def crop_frame(frame, ratio):\n \"\"\"Crop and save only ratio part from input frame.\n :param frame: input frame\n :param ratio: part of frame which will be saved\n :return: frame\n :rtype: np.ndarray\n \"\"\"\n h_frame, w_frame = frame.shape\n\n ratio = ratio\n crop_h = (1 - ratio) * h_frame\n crop_w = (1 - ratio) * w_frame\n crop_h_half = int(crop_h / 2)\n crop_w_half = int(crop_w / 2)\n frame = frame[crop_h_half: - crop_h_half, crop_w_half: - crop_w_half]\n return frame\n\n def get_frame(self, index: int, size: tuple = (128, 128)) -> np.ndarray:\n \"\"\"Return the cropped gray-scale equalized frame with the specified index from your video.\n :param index: index of frame\n :param size: size of frame\n :return: frame\n :rtype: np.ndarray\n \"\"\"\n self.cap.set(cv.CAP_PROP_POS_FRAMES, index)\n _, frame = self.cap.read()\n img = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)\n crop_img = self.crop_frame(img, 0.5)\n img_resized = cv.resize(crop_img, size)\n img = cv.equalizeHist(img_resized)\n\n transform = tf.Compose([tf.ToTensor()])\n img = transform(img)\n return img.to(self.device)\n\n def apply_encoder(self, frame: np.ndarray) -> np.ndarray:\n \"\"\"Apply encoder to the frame.\n :param frame: frame to which will be applied encoder\n :return: vector/vectors\n :rtype: np.ndarray\n \"\"\"\n frame = frame.view(1, 1, 128, 128)\n with torch.no_grad():\n output = self.model(frame)\n return output.to('cpu').detach().numpy()\n\n @staticmethod\n def compare_encoded_frames(first_enc_frame: np.ndarray,\n second_enc_frame: np.ndarray) -> np.float64:\n \"\"\"Apply encoder to frames and compare the resulting vectors.\n :param first_enc_frame: first encoded frame\n :param second_enc_frame: second encoded frame\n :return: MSE between the encoded frames\n :rtype: np.float64\n \"\"\"\n error = np.sqrt(np.sum((first_enc_frame - second_enc_frame) ** 2))\n # error = tf.keras.losses.MSE(first_enc_frame, second_enc_frame).numpy()\n return error\n\n def compare_part_cap(self, start_index: int, end_index: int,\n threshold: float = 1.2, step: int = 2) -> dict:\n \"\"\"Compare video frames from start_index to end_index with the denoted step.\n If error between frames is higher than threshold then add index into frame_code_part.\n Than create time_code_part where the frames' indexes converted into time format 00h.00m.00s.\n Return dictionary with the keys 'frames' for frame_code_part array and 'time' for time_code_part array.\n :param start_index: index from which to start\n :param end_index: index which need to finish compare\n :param threshold: value to compare with error\n :param step: step for the next index\n :return: dictionary with keys 'frames' and 'time'\n :rtype: dict\n \"\"\"\n if start_index + step > self.num_frames:\n raise ValueError(\"Start index is bigger than number os frames plus step\")\n elif end_index > self.num_frames:\n print(f'End index is bigger than number of frames minus step. End index now is {self.num_frames}')\n end_index = self.num_frames\n\n frames_code_part = []\n curr_frame = self.get_frame(start_index)\n curr_encoded_frame = self.apply_encoder(curr_frame)\n for index in range(start_index + step, end_index - step, step):\n next_frame = self.get_frame(index + step)\n next_encoded_frame = self.apply_encoder(next_frame)\n error = self.compare_encoded_frames(curr_encoded_frame, next_encoded_frame)\n\n if error >= threshold:\n print(f'Error of index {index:} = {error:}')\n frames_code_part.append(index)\n curr_encoded_frame = next_encoded_frame\n\n time_code_part = [self.frame2time(frame_code, self.fps) for frame_code in frames_code_part]\n print(time_code_part)\n dict_time = {'time': time_code_part, 'frames': frames_code_part}\n return dict_time\n\n def compare_cap(self, save_data_path: str = save_data_path,\n save_graphic_path: str = save_graphic_timecodes_path,\n diff_frame: int = 5) -> None:\n \"\"\"Compare frames for all video with special step. If error between frames\n is higher than threshold then add index into dictionary for 2 format.\n First format is a frame index the second is time code (00h.00m.00s).\n Save timecodes data into save_path file.\n :param save_data_path: path to file where data will be saved\n :param save_graphic_path: path to file where graphic timecodes will be saved\n :param diff_frame: difference between adjacent frames\n :return: Sets the dictionary with keys 'frames' and 'time' to self.dict_time,\n sets self.graphic_timecodes and save the data and the timecodes\n to save_data_path file and save_graphic_path respectively.\n Sets self.num_changes as len of self.dict_time\n :rtype: None\n \"\"\"\n self.dict_time = self.compare_part_cap(0, self.num_frames, self._threshold, self._step)\n self.set_graphic_timecodes(diff_frame)\n self.num_changes = len(self.dict_time['time'])\n self.save_dict_time(save_data_path)\n self.save_graphic_timecodes(save_graphic_path)\n\n def set_graphic_timecodes(self, index_diff: int = 5) -> None:\n \"\"\"Find graphic timecodes from self.dict_time. If the difference between\n adjacent frames in self.dict_time['frame'] less then index_diff\n then consider at this second was detected graphic.\n :param index_diff: difference between adjacent frames\n :return: Set self.graphic_timecodes\n :rtype: None\n \"\"\"\n graph_indexes = [self.dict_time['frames'][i]\n for i in range(len(self.dict_time['frames']) - 1)\n if self.dict_time['frames'][i + 1] - self.dict_time['frames'][i] < index_diff]\n graphic_timecodes = [self.frame2time(graph_index, self.fps)\n for graph_index in graph_indexes]\n self.graphic_timecodes = sorted(set(graphic_timecodes))\n\n def display_frame_by_index(self, index: int, size: tuple = (128, 128),\n wait: bool = True, dynamic: bool = False) -> None:\n \"\"\"Display frame by index. With name 'frame number {index}'.\n :param index: the index of the frame to be displayed\n :param size: size of displayed frame\n :param wait: True means the image won't be destroyed\n :param dynamic: True means the image can be resized\n :return: displayed frame\n :rtype: None\n \"\"\"\n if dynamic:\n cv.namedWindow(f'frame number {index}', cv.WINDOW_NORMAL)\n frame = self.get_frame(index, size)\n cv.imshow(f'frame number {index}', frame)\n if wait:\n cv.waitKey(0)\n\n def save_dict_time(self, save_path: str = save_data_path) -> None:\n \"\"\"Save self.dict_time to file.\n :param save_path: path to file where data will be saved\n :return: save self.dict_time into file\n :rtype: None\n \"\"\"\n bound = '\\n' + '=' * 100\n video_info = '\\nInfo:\\n' \\\n 'Video: %s\\n' \\\n 'Number of changes: %s\\n' \\\n 'Step: %s\\t Threshold: %s' \\\n % (self.video_path, self.num_changes, self.step, self.threshold)\n time_info = '\\nTime codes: {time}\\n' \\\n 'Frame codes: {frames}'.format(**self.dict_time)\n with open(save_path, 'a') as file:\n file.write(bound + video_info + time_info)\n\n def save_graphic_timecodes(self, save_path: str = save_graphic_timecodes_path) -> None:\n \"\"\"Save self.graphic_timecodes to file.\n :param save_path: path to file where timecodes will be saved\n :return: save self.graphic_timecodes into file\n :rtype: None\n \"\"\"\n bound = '\\n' + '=' * 100\n video_info = '\\nInfo:\\n' \\\n 'Video: %s\\n' \\\n 'Step: %s\\t Threshold: %s' \\\n % (self.video_path, self.step, self.threshold)\n time_info = '\\nGraphics timecodes: \\n{}'.format(self.graphic_timecodes)\n with open(save_path, 'a') as file:\n file.write(bound + video_info + time_info)\n\n @staticmethod\n def frame2time(frame_index: int, fps: int) -> str:\n \"\"\"Convert frame index into time format.\n :param frame_index: int\n :param fps: frame per second\n :return: time converted from frame index\n :rtype: str\n \"\"\"\n sec = frame_index // fps\n minute = 0 + sec // 60\n hour = 0 + minute // 60\n sec = sec % 60\n minute = minute % 60\n time = '%02dh.%02dm.%02ds' % (hour, minute, sec)\n return time\n\n @staticmethod\n def time2frame(hour: int, minute: int, sec: int, fps: int) -> int:\n \"\"\"Convert time format into frame index.\n :param hour: number of hours\n :param minute: number of minutes\n :param sec: number of seconds\n :param fps: frame per second\n :return: frame index converted from time format\n :rtype: int\n \"\"\"\n return (3600 * hour + minute * 60 + sec) * fps\n\n # getters and setters for step and threshold\n @property\n def step(self) -> int:\n \"\"\"Get self._step\n :return: self._step\n :rtype: int\n \"\"\"\n return self._step\n\n @step.setter\n def step(self, step: int) -> None:\n \"\"\"Set self._step.\n :param step: step for the next index in comparing\n :return: set step\n :rtype: None\n \"\"\"\n if step < 1:\n raise ValueError(\"Step should be positive integer\")\n self._step = step\n\n @property\n def threshold(self) -> float:\n \"\"\"Get self._threshold\n :return: self._threshold\n :rtype: float\n \"\"\"\n return self._threshold\n\n @threshold.setter\n def threshold(self, threshold: float) -> None:\n \"\"\"Set self._threshold.\n :param threshold: value to compare with error\n :return: set threshold\n :rtype: None\n \"\"\"\n self._threshold = threshold\n","sub_path":"Graphics-detection/VideoComp.py","file_name":"VideoComp.py","file_ext":"py","file_size_in_byte":11938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"17770307","text":"a = input(\"Enter a: \")\na = int(a)\n\nb = input(\"Enter b: \")\nb = int(b)\n\nif a > b:\n start = b\n end = a\nelse:\n start = a\n end = b\n\nprint(\"Counting from \" + str(start) + \" to \" + str(end))\n\nwhile start <= end:\n print(start)\n start = start + 1\n\n \n \n\n","sub_path":"Week1/4-While-Loop-Problems/user_to_user.py","file_name":"user_to_user.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"137269843","text":"# FixContactLayer.py\n# Fixes the problem of object ContactLayer not having the option solve inside\n\n# Getting the environment\nimport ScriptEnv\nScriptEnv.Initialize(\"Ansoft.ElectronicsDesktop\")\noDesktop.RestoreWindow()\noProject = oDesktop.GetActiveProject()\noDesign = oProject.GetActiveDesign()\n\n# Chang the Solve Inside\noEditor = oDesign.SetActiveEditor(\"3D Modeler\")\noEditor.ChangeProperty(\n [\n \"NAME:AllTabs\",\n [\n \"NAME:Geometry3DAttributeTab\",\n [\n \"NAME:PropServers\",\n \"ContactLayer\"\n ],\n [\n \"NAME:ChangedProps\",\n [\n \"NAME:Solve Inside\",\n \"Value:=\", True\n ]\n ]\n ]\n ])\n\n# EOF\n","sub_path":"python/ansoft/MZM MQW TWE/ChangeLayers/FixContactLayer.py","file_name":"FixContactLayer.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41838789","text":"def who_is_winner(pieces_position_list):\n p = {c: i for i, c in enumerate(\"ABCDEFG\")}\n d = {\"Red\": 1, \"Yellow\": 2}\n board = [[0 for j in range(7)] for i in range(6)]\n idx = [6] * 7\n\n def sub_check(x, y, dx1, dy1, dx2, dy2, v):\n i, j = 0, 0\n while 0 <= x + i * dx1 < 6 and 0 <= y + i * dy1 < 7 and board[x + i * dx1][y + i * dy1] == v:\n i += 1\n while 0 <= x + j * dx2 < 6 and 0 <= y + j * dy2 < 7 and board[x + j * dx2][y + j * dy2] == v:\n j += 1\n return i + j - 1\n\n def check(x, y, v):\n bottom_left = sub_check(x, y, -1, 1, 1, -1, v)\n if bottom_left >= 4:\n return True\n bottom_right = sub_check(x, y, -1, -1, 1, 1, v)\n if bottom_right >= 4:\n return True\n top_down = sub_check(x, y, -1, 0, 1, 0, v)\n if top_down >= 4:\n return True\n left_right = sub_check(x, y, 0, -1, 0, 1, v)\n if left_right >= 4:\n return True\n return False\n\n for s in pieces_position_list:\n b = s.split(\"_\")\n j, color = p[b[0]], b[1]\n idx[j] -= 1\n i = idx[j]\n board[i][j] = d[color]\n if check(i, j, d[color]):\n return color\n return \"Draw\"\n\n\nprint(who_is_winner([\n \"F_Yellow\", \"G_Red\", \"D_Yellow\", \"C_Red\", \"A_Yellow\", \"A_Red\", \"E_Yellow\", \"D_Red\", \"D_Yellow\", \"F_Red\",\n \"B_Yellow\", \"E_Red\", \"C_Yellow\", \"D_Red\", \"F_Yellow\", \"D_Red\", \"D_Yellow\", \"F_Red\", \"G_Yellow\", \"C_Red\",\n \"F_Yellow\", \"E_Red\", \"A_Yellow\", \"A_Red\", \"C_Yellow\", \"B_Red\", \"E_Yellow\", \"C_Red\", \"E_Yellow\", \"G_Red\",\n \"A_Yellow\", \"A_Red\", \"G_Yellow\", \"C_Red\", \"B_Yellow\", \"E_Red\", \"F_Yellow\", \"G_Red\", \"G_Yellow\", \"B_Red\",\n \"B_Yellow\", \"B_Red\"\n]))\n","sub_path":"codewar/2022/4/Connect_Four.py","file_name":"Connect_Four.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"245964833","text":"# 如何探测连续的元素之间的总和为0 ?使用前缀和。\n# 首先遍历一次链表,建立一个记录到当前点的和的字典。字典中key为到此结点的和,val为指向该点的指针。并且相同的和在字典中会被覆盖,所以存在\n# 字典中的,相同的和一定是后面的结点。\n# 第二次遍历链表,计算到该点的和。如果该点的和在字典中存在,则表明,从该点到字典中value所对应的点的和不变。就代表两个prefix sum所得的中间\n# 区域的和(就是区域中连续元素的总和为0),其结点可以被删除。从而当前结点.next直接连到字典中value所对应的结点的.next.\n# 注意不是字典中value的节点,value的结点是区域的最后一个元素。value所对应结点的下一个结点才是该连的节点。\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def removeZeroSumSublists(self, head: Optional[ListNode]) -> Optional[ListNode]:\n dummyNode = ListNode(0)\n prefixSumRecorder = {}\n dummyNode.next = head\n\n scanPointer = dummyNode\n prefixSum = 0\n while scanPointer:\n prefixSum += scanPointer.val\n prefixSumRecorder[prefixSum] = scanPointer\n scanPointer = scanPointer.next\n\n scanPointer = dummyNode\n prefixSum = 0\n while scanPointer:\n prefixSum += scanPointer.val\n scanPointer.next = prefixSumRecorder[prefixSum].next\n scanPointer = scanPointer.next\n\n return dummyNode.next\n\n","sub_path":"面试-LeetCode题/基础数据结构4-链表/LeetCode1171(RemoveZeroSumConsecutiveNodesfromLinkedList)/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"263425434","text":"\"\"\"\n\nGiven two sentences words1, words2 (each represented as an array of strings),\nand a list of similar word pairs pairs, determine if two sentences are similar.\n\nFor example, words1 = [\"great\", \"acting\", \"skills\"] and words2 = [\"fine\", \"drama\", \"talent\"] are similar,\nif the similar word pairs are pairs = [[\"great\", \"good\"], [\"fine\", \"good\"], [\"acting\",\"drama\"], [\"skills\",\"talent\"]].\n\nNote that the similarity relation is transitive. For example, if \"great\" and \"good\" are similar,\nand \"fine\" and \"good\" are similar, then \"great\" and \"fine\" are similar.\n\nSimilarity is also symmetric. For example, \"great\" and \"fine\" being similar is the same as \"fine\"\n and \"great\" being similar.\n\nAlso, a word is always similar with itself. For example, the sentences words1 = [\"great\"], words2 = [\"great\"],\npairs = [] are similar, even though there are no specified similar word pairs.\n\nFinally, sentences can only be similar if they have the same number of words.\nSo a sentence like words1 = [\"great\"] can never be similar to words2 = [\"doubleplus\",\"good\"].\n\n\"\"\"\nimport collections\n\n\nclass Solution(object):\n def areSentencesSimilarTwo(self, words1, words2, pairs):\n if len(words1) != len(words2):\n return False\n graph = collections.defaultdict(list)\n for w1, w2 in pairs:\n graph[w1].append(w2)\n graph[w2].append(w1)\n print(graph)\n\n for w1, w2 in zip(words1, words2):\n stack, seen = [w1], {w1}\n while stack:\n word = stack.pop()\n print(word)\n if word == w2:\n break\n for nei in graph[word]:\n if nei not in seen:\n seen.add(nei)\n stack.append(nei)\n else:\n return False\n return True\n\n\ntest = Solution()\nprint(test.areSentencesSimilarTwo([\"good\", \"acting\", \"skills\", \"lalala\"], [\"fine\", \"drama\", \"talent\", \"lalala\"],\n [[\"fine\", \"great\"], [\"great\", \"good\"], [\"acting\", \"drama\"], [\"skills\", \"talent\"]]))\n","sub_path":"leetcode/Sentence_similarity_II.py","file_name":"Sentence_similarity_II.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"315457208","text":"import os\nimport re\nfrom urlparse import urlparse\n\n\ndef is_imgur_photo(url):\n p = urlparse(url)\n if p.path[:3] == '/a/': # it may be an ImgUr album, which we should tread as an article\n return False\n return p.hostname in ['imgur.com', 'i.imgur.com']\n\n\ndef normalize_imgur_photo_url(url):\n p = urlparse(url)\n filename = os.path.basename(p.path)\n basename, extension = os.path.splitext(filename)\n if not extension:\n extension = '.jpg' # this just works(tm) for all formats - including videos\n # quick note: PNG is better for graphics and JPG is for photography;\n # since most of these images are (probably) based on photos we choose JPG as default format\n elif extension in ['.webm', '.gifv']:\n extension = '.gif'\n return \"http://i.imgur.com/{basename}{extension}\".format(basename=basename, extension=extension)\n\n\ndef is_pocket_image_title(title):\n \"\"\"\n Detects unusable titles auto-generated by Pocket, which are usually formatted like this:\n 'CvAnZwg.jpg (JPEG Image, 640 x 640 pixels)'\n \"\"\"\n\n if not title:\n return False\n\n # the title max length will sometimes mess this up if we make it more specific than this:\n if re.match(r'/^.*\\([A-Z]{2,5}\\sImage,.*$/u', title, re.IGNORECASE):\n return True\n\n # also check for webm 'images':\n if title[-5:] == '.webm':\n return True\n\n return False\n\n\ndef normalize_entities(cur_title):\n \"\"\"\n This function is copied from the readability Python library and it's a helper function used in the below\n strip_website_name function.\n \"\"\"\n entities = {\n u'\\u2014': '-',\n u'\\u2013': '-',\n u'—': '-',\n u'–': '-',\n u'\\u00A0': ' ',\n u'\\u00AB': '\"',\n u'\\u00BB': '\"',\n u'"': '\"',\n }\n for c, r in entities.items():\n if c in cur_title:\n cur_title = cur_title.replace(c, r)\n\n return cur_title\n\n\ndef strip_website_name(page_title):\n \"\"\"Below code was adapted from the readability Python library.\"\"\"\n if not page_title:\n return ''\n\n title = orig = normalize_entities(' '.join(page_title.split()))\n for delimiter in [' | ', ' - ', ' :: ', ' / ']:\n if delimiter in title:\n parts = orig.split(delimiter)\n if len(parts[0].split()) >= 4:\n title = parts[0]\n break\n elif len(parts[-1].split()) >= 4:\n title = parts[-1]\n break\n else:\n if ': ' in title:\n parts = orig.split(': ')\n if len(parts[-1].split()) >= 4:\n title = parts[-1]\n else:\n title = orig.split(': ', 1)[1]\n\n if not 15 < len(title):\n return orig\n\n return title\n","sub_path":"pocketbulletin/blueprints/bulletinmanager/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"47382588","text":"#\n# Copyright 2018 Quantopian, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nPosition Tracking\n=================\n\n +-----------------+----------------------------------------------------+\n | key | value |\n +=================+====================================================+\n | asset | the asset held in this position |\n +-----------------+----------------------------------------------------+\n | amount | whole number of shares in the position |\n +-----------------+----------------------------------------------------+\n | last_sale_price | price at last sale of the asset on the exchange |\n +-----------------+----------------------------------------------------+\n | cost_basis | the volume weighted average price paid per share |\n +-----------------+----------------------------------------------------+\n\n\"\"\"\n\nfrom __future__ import division\nfrom copy import deepcopy\nfrom enum import Enum\nfrom functools import total_ordering\nfrom math import copysign\nfrom textwrap import dedent\nimport logbook\nimport numpy as np\nimport pandas as pd\n\nfrom zipline.assets import Future\nfrom zipline.finance.transaction import Transaction\nfrom zipline.data.adjustments import Dividend\nimport zipline.protocol as zp\n\nlog = logbook.Logger(\"Performance\")\n\n\nclass LongShort(Enum):\n long = 1\n short = -1\n\n def __str__(self):\n return self.name\n\n\nclass PnlRealized(object):\n \"\"\"\n Subclassing pd.DataFrame throws a KeyError: 0 when\n testing equality. Avoid this error by shielding the data as\n an object but preserving many of the features of pd.DataFrame.\n \"\"\"\n\n __slots__ = (\"_internal_data\",)\n\n def __init__(self, values=None):\n zeros = pd.DataFrame(\n np.zeros((2, 4)),\n columns=[\n \"long_term\",\n \"short_term\",\n \"qualified_dividend\",\n \"ordinary_dividend\",\n ],\n index=[\"long\", \"short\"],\n )\n\n if isinstance(values, dict):\n self._internal_data = zeros\n self._internal_data.update(pd.DataFrame.from_dict(values))\n elif isinstance(values, tuple):\n self._internal_data = zeros\n self.update(*values)\n elif isinstance(values, pd.DataFrame):\n self._internal_data = values\n elif values is None:\n self._internal_data = zeros\n else:\n raise TypeError(\n \"`values` must one of None, dictionary, or pandas.DataFrame, not {}\".format(\n type(values)\n )\n )\n\n @property\n def as_dataframe(self):\n return self._internal_data\n\n @property\n def as_dict(self):\n return self._internal_data.to_dict()\n\n @property\n def _constructor(self):\n raise NotImplementedError()\n\n def __getstate__(self):\n return self._internal_data.to_dict()\n\n def __setstate__(self, data):\n \"\"\"define how object is unpickled\"\"\"\n self._internal_data = pd.DataFrame(data)\n\n def __add__(self, other):\n return type(self)(self._internal_data.add(other._internal_data))\n\n def __radd__(self, other):\n if other == 0:\n return self\n else:\n self.__add__(other)\n\n def __sub__(self, other):\n return type(self)(self._internal_data.subtract(other._internal_data))\n\n def __rsub__(self, other):\n if other == 0:\n return self\n else:\n self.__add__(other)\n\n def __eq__(self, other):\n if type(self) is not type(other):\n return False\n a, b = self.as_dataframe.align(other.as_dataframe)\n return a.equals(b)\n\n def __repr__(self):\n template = dedent(\"\"\"PnlRealized({})\"\"\")\n return template.format(self.as_dict)\n\n def update(self, position_direction, holding_tenure, value):\n self._internal_data.loc[position_direction, holding_tenure] = value\n\n\nclass Position(object):\n __slots__ = \"inner_position\", \"protocol_position\"\n\n def __init__(\n self, asset, amount=0, cost_basis=0.0, last_sale_price=0.0, last_sale_date=None\n ):\n inner = zp.InnerPosition(\n asset=asset,\n amount=amount,\n cost_basis=cost_basis,\n last_sale_price=last_sale_price,\n last_sale_date=last_sale_date,\n pnl_realized=PnlRealized(),\n lots=set(),\n )\n object.__setattr__(self, \"inner_position\", inner)\n object.__setattr__(self, \"protocol_position\", zp.Position(inner))\n\n def __getattr__(self, attr):\n \"\"\"\n Attributes are stored and retrieved from the inner_position\n \"\"\"\n return getattr(self.inner_position, attr)\n\n def __setattr__(self, attr, value):\n setattr(self.inner_position, attr, value)\n\n @property\n def has_uncollected_pnl(self):\n return np.count_nonzero(self.pnl_realized.as_dataframe.values, axis=None)\n\n @property\n def transaction_date(self):\n \"\"\"\n Transaction Date of a position is deemed the weighted average of\n the transaction_dates of each of its constituent lots\n \"\"\"\n # default values\n tzinfo = \"UTC\"\n\n if self.lots:\n tzinfo = max(self.lots).transaction_date.tzinfo\n\n timedelta = [\n (lot.transaction_date - pd.Timestamp(0, tz=tzinfo)).total_seconds()\n for lot in self.lots\n ]\n weights = [lot.amount for lot in self.lots]\n average_timedelta = np.average(timedelta, weights=weights)\n\n return (\n pd.Timestamp(0, tz=tzinfo) + pd.to_timedelta(average_timedelta, unit=\"s\")\n ).normalize()\n\n def collect_pnl_and_reset(self):\n pnl_realized_copy, self.pnl_realized = self.pnl_realized, PnlRealized()\n return pnl_realized_copy\n\n def earn_dividend(self, dividend):\n \"\"\"\n Register the number of shares we held at this dividend's ex date so\n that we can pay out the correct amount on the dividend's pay date.\n\n Parameters\n ------------ \n dividends : iterable of (asset, amount, pay_date) namedtuples\n \"\"\"\n if dividend.asset != self.asset:\n raise TypeError(\"Dividend.asset must match position.asset\")\n\n total_shares = sum([lot.amount for lot in self.lots])\n if self.amount != total_shares:\n raise ValueError(\n \"Shares recorded among lots are inconsistent with total shares registered with the position\"\n )\n\n for lot in self.lots:\n proportion = abs(lot.amount) / abs(total_shares)\n # allocated_amount < 0 to show dividend obligation on short positions\n allocated_amount = (\n abs(total_shares)\n * proportion\n * dividend.amount_per_share\n * copysign(1, lot.amount)\n )\n\n threshold = pd.Timedelta(60, \"D\")\n holding_period = dividend.ex_date - lot.transaction_date\n\n tax_status = (\n \"qualified\"\n if holding_period > threshold and allocated_amount > 0\n else \"ordinary\"\n )\n\n dividend = Dividend(\n asset=dividend.asset,\n amount_per_share=dividend.amount_per_share,\n total_amount=allocated_amount,\n ex_date=dividend.ex_date,\n pay_date=dividend.pay_date,\n ledger_status=\"earned\",\n tax_status=tax_status,\n )\n lot._dividends.add(dividend)\n\n return list(self.lots)\n\n def earn_stock_dividend(self, stock_dividend):\n \"\"\"\n Register the number of shares we held at this dividend's ex date so\n that we can pay out the correct amount on the dividend's pay date.\n\n For example, closing out a position will not affect the number of shares\n received on the pay_date. Note passing a ratio would not work since\n ratio * 0 = 0.\n \"\"\"\n return {\n \"payment_asset\": stock_dividend.payment_asset,\n \"share_count\": np.trunc(self.amount * float(stock_dividend.ratio)),\n \"average_transaction_date\": self.transaction_date,\n }\n\n def process_dividends(self, session):\n raise NotImplementedError()\n\n def process_stock_dividends(\n self, share_count, cost_basis, spot_price, average_transaction_date\n ):\n if not self.amount:\n txn = Transaction(\n asset=self.asset,\n amount=share_count,\n dt=average_transaction_date,\n price=cost_basis,\n order_id=None,\n )\n self.update(txn)\n return PnlRealized()\n else:\n # handle_split treats ratio as new_amount = old_amount / ratio\n ratio = 1 / (1 + share_count / self.amount)\n # a stock dividend is the same thing has a split\n return self.handle_split(\n self.asset, ratio, cost_basis=0.0, spot_price=spot_price\n )\n\n def handle_fractional_amounts(self, amount, cost_basis, spot_price):\n # handle fractional shares from each lot by aggregating\n # and treating whole shares as a new lot at aggregate cost-basis\n # while cashing out the remaining fractional share.\n whole = np.trunc(amount)\n fraction = amount - whole\n\n if whole:\n # tack on the full_share_count to the most recently-traded lot\n # operationally, this should work as updating with a transaction\n # with the transaction_date being an average of all the transaction_dates\n # NOTE: I'm not sure how the IRS treats the holding period of these\n # remainder shares\n total_cost_basis = (\n sum([lot.amount * lot.cost_basis for lot in self.lots])\n + amount * cost_basis\n )\n total_shares = sum([lot.amount for lot in self.lots]) + amount\n new_cost_basis = (\n total_cost_basis / total_shares if total_shares > 0 else 0.0\n )\n\n # create new lot with the position's (average) transaction_date\n txn = Transaction(\n asset=self.asset,\n amount=whole,\n dt=self.transaction_date,\n price=new_cost_basis,\n order_id=None,\n closing_rule=max,\n )\n\n self.update(txn)\n\n self.reconcile(\"cost_basis\", \"amount\")\n\n cash_realized = PnlRealized()\n\n # cash out the remaining fractional share\n if fraction:\n cash_amount = round(float(fraction * (spot_price - cost_basis)), 2)\n long_short = LongShort(np.sign(self.amount))\n cash_realized = PnlRealized(\n (str(long_short), \"ordinary_dividend\", cash_amount)\n )\n\n return cash_realized\n\n def handle_split(self, asset, ratio, cost_basis, spot_price):\n \"\"\"\n Update the position by the split ratio, and return the resulting\n fractional share that will be converted into cash.\n\n Returns the unused cash.\n \"\"\"\n if self.asset != asset:\n raise Exception(\"updating split with the wrong asset!\")\n\n # adjust the # of shares by the ratio\n # (if we had 100 shares, and the ratio is 3,\n # we now have 33 shares)\n # (old_share_count / ratio = new_share_count)\n # (old_price * ratio = new_price)\n\n # a split is essentially when new shares are issued at 0 cost basis\n aggregate_leftover_shares = sum(\n [lot.handle_split(ratio, cost_basis=0) for lot in self.lots]\n )\n cash_realized = self.handle_fractional_amounts(\n aggregate_leftover_shares, cost_basis=0.0, spot_price=spot_price\n )\n return cash_realized\n\n def reconcile(self, *args):\n\n total_shares = sum([lot.amount for lot in self.lots])\n total_cost_basis = sum([lot.amount * lot.cost_basis for lot in self.lots])\n\n if \"amount\" in args:\n setattr(self, \"amount\", total_shares)\n\n if \"cost_basis\" in args:\n try:\n cost_basis = total_cost_basis / total_shares\n except ZeroDivisionError:\n cost_basis = 0.0\n\n setattr(self, \"cost_basis\", cost_basis)\n\n def update(self, txn):\n if self.asset != txn.asset:\n raise Exception(\"updating position with txn for a \" \"different asset\")\n\n while True:\n # clean out the store so that we don't fall into infinite recursion\n self._clean_lots()\n lots = self.lots\n\n # txn is in the same direction as all current lots\n # then, we're not closing out anything and we just open a new lot\n\n new_lot = Lot(\n txn.asset,\n transaction_date=txn.dt.normalize(),\n amount=txn.amount,\n cost_basis=txn.price,\n )\n txn_direction = copysign(1, txn.amount)\n\n # default values modified if closing out a lot\n excess = 0\n pnl_realized = PnlRealized()\n # already have the lot (i.e. order on the same day), update that lot\n if new_lot in self.lots:\n # earlier order on same day\n lot = self._get_lot(new_lot)\n lot.update(txn)\n\n # if no lots to close out, open a new lot\n elif all(copysign(1, x.amount) == txn_direction for x in lots):\n self._add_lot(new_lot)\n\n # otherwise, try to close out a currently held lot\n else:\n # user selection for lots take precedence\n # but default is FIFO rule\n if txn.target_lots:\n lot = txn.target_lots.pop(0)\n else:\n closing_rule = txn.closing_rule or min # effectively FIFO\n lot = closing_rule(lots)\n # pass remaining target_lots for later recursive function calls\n _, excess, pnl_realized = lot.update(txn)\n\n # update position values to maintain compatibility\n total_shares = sum([x.amount for x in lots])\n total_value = sum([x.amount * x.cost_basis for x in lots])\n\n try:\n self.cost_basis = total_value / total_shares\n except ZeroDivisionError:\n self.cost_basis = 0.0\n\n # Update the last sale price if txn is\n # best data we have so far\n if self.last_sale_date is None or txn.dt > self.last_sale_date:\n self.last_sale_price = txn.price\n self.last_sale_date = txn.dt\n\n self.amount = total_shares\n\n # Update realized pnl for position\n self.pnl_realized = self.pnl_realized + pnl_realized\n\n # if txn closes outentire lot with excess,\n # then treat excess as a new transaction to be updated with\n if excess:\n new_txn = deepcopy(txn)\n new_txn.amount = excess\n # recursive update\n self.update(new_txn)\n\n # if no more transactions to update, then end\n break\n\n def _add_lot(self, lot):\n self.lots.add(lot)\n\n def _clean_lots(self):\n for lot in self.lots.copy():\n if not abs(lot.amount):\n self.lots.remove(lot)\n\n def _get_lot(self, lot):\n if lot not in self.lots:\n raise KeyError(\"{lot} cannot be found in {position}\".format(lot, self))\n\n found = min(filter(lambda x: x == lot, self.lots))\n return found\n\n def adjust_commission_cost_basis(self, asset, cost):\n \"\"\"\n A note about cost-basis in zipline: all positions are considered\n to share a cost basis, even if they were executed in different\n transactions with different commission costs, different prices, etc.\n\n Due to limitations about how zipline handles positions, zipline will\n currently spread an externally-delivered commission charge across\n all shares in a position.\n \"\"\"\n\n if asset != self.asset:\n raise Exception(\"Updating a commission for a different asset?\")\n if cost == 0.0:\n return\n\n # If we no longer hold this position, there is no cost basis to\n # adjust.\n if self.amount == 0:\n return\n\n # We treat cost basis as the share price where we have broken even.\n # For longs, commissions cause a relatively straight forward increase\n # in the cost basis.\n #\n # For shorts, you actually want to decrease the cost basis because you\n # break even and earn a profit when the share price decreases.\n #\n # Shorts are represented as having a negative `amount`.\n #\n # The multiplication and division by `amount` cancel out leaving the\n # cost_basis positive, while subtracting the commission.\n\n prev_cost = self.cost_basis * self.amount\n if isinstance(asset, Future):\n cost_to_use = cost / asset.price_multiplier\n else:\n cost_to_use = cost\n new_cost = prev_cost + cost_to_use\n self.cost_basis = new_cost / self.amount\n\n # NOTE: to ensure the aggregate cost basis per share of the lots is\n # consistent with the over-all position cost basis per share,\n # apply the same adjustment to the latest acquired lot.\n adjustment = cost_to_use / self.amount\n max(self.lots).adjust_cost_basis(adjustment)\n\n def __repr__(self):\n template = dedent(\n \"asset: {asset}, amount: {amount}, \\\n cost_basis: {cost_basis}, \\\n last_sale_price: {last_sale_price}\"\n )\n return template.format(\n asset=self.asset,\n amount=self.amount,\n cost_basis=self.cost_basis,\n last_sale_price=self.last_sale_price,\n )\n\n def to_dict(self):\n \"\"\"\n Creates a dictionary representing the state of this position.\n Returns a dict object of the form:\n \"\"\"\n return {\n \"sid\": self.asset,\n \"amount\": self.amount,\n \"cost_basis\": self.cost_basis,\n \"last_sale_price\": self.last_sale_price,\n \"lots\": self.lots,\n \"transaction_date\": self.transaction_date,\n }\n\n\n@total_ordering\nclass Lot(object):\n\n __slots__ = (\"amount\", \"asset\", \"cost_basis\", \"transaction_date\", \"_dividends\")\n\n def __init__(self, asset, transaction_date, amount, cost_basis):\n self.asset = asset\n self.transaction_date = transaction_date\n self.amount = amount\n self.cost_basis = cost_basis\n\n self._dividends = set()\n\n def __eq__(self, other):\n return (self.asset, self.transaction_date) == (\n other.asset,\n other.transaction_date,\n )\n\n def __lt__(self, other):\n return self.transaction_date < other.transaction_date\n\n def __hash__(self):\n return hash((self.asset, self.transaction_date))\n\n def __repr__(self):\n template = dedent(\n \"Lot(asset={asset}, \\\n transaction_date={transaction_date}, amount={amount}, \\\n cost_basis={cost_basis})\"\n )\n return template.format(\n asset=self.asset,\n transaction_date=self.transaction_date,\n amount=self.amount,\n cost_basis=self.cost_basis,\n )\n\n @property\n def earned_dividends(self):\n return filter(lambda div: div.ledger_status == \"earned\", self._dividends)\n\n @property\n def paid_dividends(self):\n return filter(lambda div: div.ledger_status == \"paid\", self._dividends)\n\n def adjust_cost_basis(self, adjustment):\n self.cost_basis += adjustment\n\n def handle_split(self, ratio, cost_basis):\n \"\"\"\n Update the position by the split ratio, and return the resulting\n fractional share that will be converted into cash.\n\n Returns the unused cash.\n \"\"\"\n # adjust the # of shares by the ratio\n # (if we had 100 shares, and the ratio is 3,\n # we now have 33 shares)\n # (old_share_count / ratio = new_share_count)\n # (old_price * ratio = new_price)\n\n old_cost_basis_total = self.amount * self.cost_basis\n old_shares = self.amount\n\n # e.g., 33.333\n new_shares_raw = self.amount / float(ratio) - self.amount\n\n # e.g., 33\n new_shares_whole = np.trunc(new_shares_raw)\n\n # e.g., 0.333\n fractional_share_count = new_shares_raw - new_shares_whole\n\n # adjust the cost basis to the nearest cent, e.g., 60.0\n new_cost_basis_total = old_cost_basis_total + new_shares_whole * cost_basis\n new_cost_basis = new_cost_basis_total / (old_shares + new_shares_whole)\n\n self.cost_basis = new_cost_basis\n self.amount += new_shares_whole\n\n return fractional_share_count\n\n def process_dividend_payment(self, pay_date):\n pnl_realized = PnlRealized()\n for div in self.earned_dividends:\n if div.pay_date == pay_date:\n div.update_paid()\n\n # return a PnlRealized instance to keep ledger consistent.\n # Div.total_amount is negative for short positions, representing\n # short position holder's obligation to pay the dividend\n direction = \"long\" if div.total_amount > 0 else \"short\"\n tax_status = div.tax_status\n pnl_realized += PnlRealized(\n {\"{}_dividend\".format(tax_status): {direction: div.total_amount}}\n )\n\n return pnl_realized\n\n def update(self, txn):\n \"\"\"\n Lots are mostly immutable: \n they can only be partially or fully closed out but never expanded.\n \"\"\"\n if self.asset != txn.asset:\n raise Exception(\"updating lot with a transaction for a different asset\")\n\n # default return values\n cleared = 0\n excess = 0\n cost_basis_adjustment_total = 0\n pnl_realized = PnlRealized()\n\n # if in the same direction, add to the current lot\n # otherwise, treat it as a close out, excess amounts are\n # treated as a new transaction\n if copysign(1, txn.amount) == copysign(1, self.amount):\n cleared = txn.amount\n cost_basis_adjustment_total = txn.amount * txn.price\n else:\n # cleared amounts are shares that were transacted\n cleared = copysign(min(self.amount, txn.amount, key=abs), txn.amount)\n excess = (\n self.amount + txn.amount if abs(txn.amount) > abs(self.amount) else 0\n )\n cost_basis_adjustment_total = cleared * self.cost_basis\n\n # first process cleared amounts and adjust basis\n # if fully closed out, basis will calculate to 0\n total_shares = self.amount + cleared\n\n # calculate pnl based on what has been cleared before the cost_basis as been adjusted\n # pnl calculations should account for shorts as well\n # pnl is realized only when positions are closed out\n if copysign(1, txn.amount) != copysign(1, self.amount):\n over_year_long = self.transaction_date < txn.dt - pd.Timedelta(days=365)\n holding_tenure = \"long_term\" if over_year_long else \"short_term\"\n closed = copysign(cleared, self.amount) # the shares that were closed out\n closed_direction = \"long\" if closed > 0 else \"short\"\n\n pnl = closed * (txn.price - self.cost_basis)\n pnl_realized.update(\n position_direction=closed_direction,\n holding_tenure=holding_tenure,\n value=pnl,\n )\n\n # update rest of the metrics\n prev_cost = self.cost_basis * self.amount\n total_cost = prev_cost + cost_basis_adjustment_total\n try:\n self.cost_basis = total_cost / total_shares\n except ZeroDivisionError:\n self.cost_basis = 0.0\n\n self.amount = self.amount + cleared\n\n return cleared, excess, pnl_realized\n","sub_path":"zipline/finance/position.py","file_name":"position.py","file_ext":"py","file_size_in_byte":24963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"269578931","text":"import json\nimport sys\n\n\ndef load_data(filepath):\n try:\n with open(filepath) as file_handler:\n return json.load(file_handler)\n except json.decoder.JSONDecodeError:\n print(\"В файле не JSON\")\n except FileNotFoundError:\n print(\"Файл не найден\")\n\n\ndef pretty_print_json(parsed_json):\n if not parsed_json:\n return None\n else:\n print(json.dumps(parsed_json, indent=4, sort_keys=True))\n\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n pretty_print_json(load_data(sys.argv[1]))\n else:\n print(\"Укажите путь к файлу\")\n","sub_path":"pprint_json.py","file_name":"pprint_json.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"634198932","text":"import types\nimport random\nimport estimators_te\nimport estimators_cmi\nimport estimators_mi\n\nclass Estimator(object):\n \"\"\"Set the estimator requested by the user.\"\"\"\n \n @classmethod\n def removeMethod(cls, name):\n return delattr(cls, name)\n \n @classmethod\n def addMethodAs(cls, func, new_name=None):\n if new_name is None:\n new_name = fun.__name__\n return setattr(cls, new_name, types.MethodType(func, cls))\n \n def get_estimator(self):\n return self.estimator_name\n\nclass Estimator_te(Estimator):\n \"\"\"Set the transfer entropy estimator requested by the user.\"\"\"\n \n def __init__(self, estimator_name):\n try:\n estimator = getattr(estimators_te, estimator_name)\n except AttributeError:\n print('The requested TE estimator \"' + estimator_name + '\" was not found.')\n else:\n self.estimator_name = estimator_name\n self.addMethodAs(estimator, \"estimate\")\n\nclass Estimator_cmi(Estimator):\n \"\"\"Set the conditional mutual information estimator requested by the user.\"\"\"\n \n def __init__(self, estimator_name):\n try:\n estimator = getattr(estimators_cmi, estimator_name)\n except AttributeError:\n print('The requested CMI estimator \"' + estimator_name + '\" was not found.')\n else:\n self.estimator_name = estimator_name\n self.addMethodAs(estimator, \"estimate\")\n\nclass Estimator_mi(Estimator):\n \"\"\"Set the mutual information estimator requested by the user.\"\"\"\n \n def __init__(self, estimator_name):\n try:\n estimator = getattr(estimators_mi, estimator_name)\n except AttributeError:\n print('The requested MI estimator \"' + estimator_name + '\" was not found.')\n else:\n self.estimator_name = estimator_name\n self.addMethodAs(estimator, \"estimate\")\n\n\nif __name__ == \"__main__\":\n \"\"\" Do a quick check if eveything is called correctly.\"\"\"\n \n te_estimator = Estimator_te(\"jidt_kraskov\")\n mi_estimator = Estimator_mi(\"jidt_kraskov\")\n cmi_estimator = Estimator_cmi(\"jidt_kraskov\")\n \n numObservations = 1000\n covariance=0.4\n source = [random.normalvariate(0,1) for r in range(numObservations)]\n target = [0] + [sum(pair) for pair in zip([covariance*y for y in source[0:numObservations-1]], \\\n [(1-covariance)*y for y in [random.normalvariate(0,1) for r in range(numObservations-1)]] ) ]\n var1 = [[random.normalvariate(0,1) for x in range(5)] for x in range(numObservations)]\n var2 = [[random.normalvariate(0,1) for x in range(5)] for x in range(numObservations)]\n conditional = [[random.normalvariate(0,1) for x in range(5)] for x in range(numObservations)]\n knn = 4\n history_length = 1\n \n te = te_estimator.estimate(source, target, knn, history_length)\n print(\"Estimator is \" + te_estimator.get_estimator())\n print(\"TE result: %.4f nats.\" % te)\n \n mi = mi_estimator.estimate(var1, var2, knn)\n print(\"Estimator is \" + mi_estimator.get_estimator())\n print(\"MI result: %.4f nats.\" % mi)\n \n cmi = cmi_estimator.estimate(var1, var2, conditional, knn)\n print(\"Estimator is \" + cmi_estimator.get_estimator())\n print(\"CMI result: %.4f nats.\" % cmi)\n","sub_path":"src/set_estimator.py","file_name":"set_estimator.py","file_ext":"py","file_size_in_byte":3304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"112785839","text":"from collections import OrderedDict\nfrom cfg_compare import Merger\nfrom exceptions import SanityError\n\ndef parse_alarms2(f):\n \"\"\" The alarms file changed formats \n from version 1.3(?) to version 3.0.\n\n It actually changed twice - once to fix a typo,\n and once to change the \"ignore\" column to notify\n and swap the \"audible\" and \"notify\" columns. \n \"\"\"\n h = f.readline().lower()\n h = tuple(s.strip() for s in h.split(\",\"))\n h2_1 = (\"name\", \"audable\", \"ignore\")\n h2_2 = (\"name\", \"audible\", \"ignore\")\n if h == h2_1 or h == h2_2: \n v = 2\n elif h == (\"name\", \"notify\", \"audible\"):\n v = 3\n else:\n raise ValueError(\"Couldn't determine version: %s\"%(repr(h)))\n alms = OrderedDict()\n for line in f:\n alm, a,b = line.strip().split(\",\")\n if v == 2:\n a,b = b,a\n a = \"1\" if a == \"0\" else \"0\"\n alms[alm] = a,b\n return alms\n \ndef parse_alarms(fp):\n with open(fp, 'r') as f:\n return parse_alarms2(f)\n \n\nclass AlarmsMerger(Merger):\n def parse(self, ff):\n return parse_alarms(ff)\n\n def v2s(self, n, v):\n return \"N:%s A:%s\"%v\n\n def post_parse(self):\n force = self.options.force\n for alm, v in force.items():\n a,b = v.split(\",\")\n force[alm] = a.strip(), b.strip()\n\n def output(self, f):\n l = [\"Name, Notify, Audible\\n\"]\n l.extend(\"%s,%s,%s\\n\"%(name, notify, audible) for name, (notify, audible) in f.items())\n return \"\".join(l)\n\n def sanitycheck(self):\n def err_if(c, msg, *args):\n if c: raise SanityError(msg%args)\n def checkv(c):\n for n,v in c.items():\n err_if(not isinstance(v, tuple), \"'%s' is not a tuple\", v)\n err_if(len(v)!=2, \"Bad value: '%s'='%s'\", n,v)\n err_if(v[0] not in \"10\" or v[1] not in \"10\", \"Bad value: '%s'='%s'\",n,v)\n checkv(self.cf)\n checkv(self.of)\n checkv(self.nf)\n checkv(self.options.force)\n\n\nfrom file_types import register\nregister(\"alarms\", AlarmsMerger.run_merge)","sub_path":"tools/patcher/src/merge/mergers/merge_alarms.py","file_name":"merge_alarms.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"255566175","text":"from django.contrib.auth import get_user_model\nfrom django.shortcuts import render, redirect\n\n# Create your views here.\nfrom django.utils.timezone import now\n\nfrom events.models import Event, Bet\nfrom game.models import Game\nimport numpy as np\n\nUser = get_user_model()\n\n\ndef play42(request):\n if request.POST:\n d = now()\n [user.delete() for user in User.objects.all() if user.id > 1]\n d1 = now()\n print(d1 - d)\n event = Event.objects.get(pk=1)\n event.is_payed = False\n event.save()\n c = 10\n d = now()\n for i in range(c):\n user = User(i + 2, username=('abot' + str(i)))\n user.save()\n bet = Bet.create(user_id=user.id, event_id=event.id, money=100,\n percent=np.random.choice(range(1, 100), 1), result=np.random.choice(range(1, 7), 1))\n bet.save()\n d1 = now()\n print(d1 - d)\n game = Game.create(event=event)\n event.end_42 = True\n event.save()\n d = now()\n game.play42()\n d1 = now()\n print(d1 - d)\n d = now()\n\n return redirect('play42')\n return render(request, 'play42.html')\n","sub_path":"game/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"552833031","text":"# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\n\nfrom oslo_policy import policy\n\nfrom nova.api.openstack.placement.policies import base\n\n\nRP_TRAIT_PREFIX = 'placement:resource_providers:traits:%s'\nRP_TRAIT_LIST = RP_TRAIT_PREFIX % 'list'\nRP_TRAIT_UPDATE = RP_TRAIT_PREFIX % 'update'\nRP_TRAIT_DELETE = RP_TRAIT_PREFIX % 'delete'\n\nTRAITS_PREFIX = 'placement:traits:%s'\nTRAITS_LIST = TRAITS_PREFIX % 'list'\nTRAITS_SHOW = TRAITS_PREFIX % 'show'\nTRAITS_UPDATE = TRAITS_PREFIX % 'update'\nTRAITS_DELETE = TRAITS_PREFIX % 'delete'\n\n\nrules = [\n policy.DocumentedRuleDefault(\n TRAITS_LIST,\n base.RULE_ADMIN_API,\n \"List traits.\",\n [\n {\n 'method': 'GET',\n 'path': '/traits'\n }\n ],\n scope_types=['system']\n ),\n policy.DocumentedRuleDefault(\n TRAITS_SHOW,\n base.RULE_ADMIN_API,\n \"Show trait.\",\n [\n {\n 'method': 'GET',\n 'path': '/traits/{name}'\n }\n ],\n scope_types=['system'],\n ),\n policy.DocumentedRuleDefault(\n TRAITS_UPDATE,\n base.RULE_ADMIN_API,\n \"Update trait.\",\n [\n {\n 'method': 'PUT',\n 'path': '/traits/{name}'\n }\n ],\n scope_types=['system'],\n ),\n policy.DocumentedRuleDefault(\n TRAITS_DELETE,\n base.RULE_ADMIN_API,\n \"Delete trait.\",\n [\n {\n 'method': 'DELETE',\n 'path': '/traits/{name}'\n }\n ],\n scope_types=['system'],\n ),\n policy.DocumentedRuleDefault(\n RP_TRAIT_LIST,\n base.RULE_ADMIN_API,\n \"List resource provider traits.\",\n [\n {\n 'method': 'GET',\n 'path': '/resource_providers/{uuid}/traits'\n }\n ],\n scope_types=['system'],\n ),\n policy.DocumentedRuleDefault(\n RP_TRAIT_UPDATE,\n base.RULE_ADMIN_API,\n \"Update resource provider traits.\",\n [\n {\n 'method': 'PUT',\n 'path': '/resource_providers/{uuid}/traits'\n }\n ],\n scope_types=['system'],\n ),\n policy.DocumentedRuleDefault(\n RP_TRAIT_DELETE,\n base.RULE_ADMIN_API,\n \"Delete resource provider traits.\",\n [\n {\n 'method': 'DELETE',\n 'path': '/resource_providers/{uuid}/traits'\n }\n ],\n scope_types=['system'],\n ),\n]\n\n\ndef list_rules():\n return rules\n","sub_path":"nova/api/openstack/placement/policies/trait.py","file_name":"trait.py","file_ext":"py","file_size_in_byte":3117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"647514031","text":"#preprocessing data\n\n\nimport pandas as pd\nimport numpy as np\n\ndef mad(arr):\n '''\n Computes the Median Absolute Deviation of the provided numerical array.\n https://en.wikipedia.org/wiki/Median_absolute_deviation\n '''\n return np.median(np.abs(arr - np.median(arr)))\n\ndef mad_outliers(series, sensitivity=12, delta=1):\n '''\n Use the MAD to select outliers in the timeseries data.\n For a window of +- delta hours, points that are more than sensitivity*MAD(window)\n Will be marked as outliers.\n Returns a list of indices in the series that have been identified as outliers,\n For either removal or interpolation.\n '''\n #creating a Pandas timedelta for proper indexing\n timedelta = pd.Timedelta(\"{} hour\".format(delta))\n\n outliers = []\n\n series_start = pd.to_datetime(series.index[0])\n series_end = pd.to_datetime(series.index[-1])\n\n for i in range(len(series)):\n #selecting date range, accounting for beginning and end of series\n #NOTE: this means that window size will vary at the beginning and end of the series\n window_start = max(pd.to_datetime(series.index[i]) - timedelta, series_start)\n window_end = min(pd.to_datetime(series.index[i]) + timedelta, series_end)\n\n window = series.loc[str(window_start):str(window_end)].values\n dev = mad(window)\n med = np.median(window)\n# display(dev)\n# display(med)\n# display(window)\n# display(series[series.index[i]])\n\n #marking as an outlier if farther away from median than sensitivity*dev\n if np.abs(series[series.index[i]]- med) > sensitivity*dev:\n outliers.append(series.index[i])\n\n print (\"{} outliers identified out of {} total points\".format(len(outliers), len(series)))\n\n return outliers\n\n\ndef interpolate_series(series, outliers):\n '''\n Helper function wrapping the built-in Pandas interpolation function.\n Using 4th-order piecewise polynomial interpolation.\n '''\n #replacing outliers with NaNs\n\n #avoid editing in place\n series = series.copy()\n series[outliers] = np.nan\n\n\n #converting index explicitly to datetime\n series.index = pd.to_datetime(series.index)\n series = series.interpolate(method=\"piecewise_polynomial\", limit_direction=\"both\" , order=4)\n\n return series\n\n\ndef preprocess_rms(rms):\n '''\n Runs preprocessing on RMS DataFrame.\n Returns a DataFrame with outliers removed, and index converted to explict DateTime type.\n '''\n\n cols = rms.columns.values\n\n interpolated = {}\n\n for col in cols:\n col_series = rms[col]\n outliers = mad_outliers(col_series)\n\n interp = interpolate_series(col_series, outliers)\n\n interpolated[col] = interp\n\n return pd.DataFrame(interpolated)\n\n\ndef add_power_feature(rms):\n '''\n Adds the power (current * voltage) feature to the DataFrame.\n '''\n rms['power'] = rms['motor_current']*rms['motor_voltage']\n\n\ndef add_torque(rms):\n '''\n Computes the torque currently exerted by the motor.\n '''\n rms['torque'] = rms['power']/rms['rpm']\n\ndef add_temp_diff(rms):\n '''\n Adds a feature equal to the difference between the motor and inlet temperature.\n '''\n\n rms['temp_diff'] = rms['motor_temp'] - rms['inlet_temp']\n\ndef add_alarms(rms, alarms):\n '''\n Incorporates alarm system data into the DataFrame.\n '''\n\n #Each data point can be modeled as a sample taken in a 10-minute interval, so explicit\n #discretization or re-sampling would be unproductive and add noise.\n\n #To incorporate warnings, marking whether or not a warning occured between each observation\n #and the following observation.\n\n warning_occured = np.zeros(len(rms))\n error_occured = np.zeros(len(rms))\n\n alarms.index = pd.to_datetime(alarms.index)\n\n # print(alarms.index)\n # print(rms.index)\n\n #not sure why some of them weren't sorted.\n alarms = alarms.sort_index()\n\n for i, index in enumerate(rms.index[:-2]):\n next_index = rms.index[i + 1]\n # print(index, next_index)\n alarms_in_range = alarms.loc[index:next_index]\n if len(alarms_in_range) > 0:\n if \"warning\" in alarms_in_range.values:\n warning_occured[i] = 1\n if \"error\" in alarms_in_range.values:\n error_occured[i] = 1\n\n rms['error_occured'] = error_occured\n rms['warning_occured'] = warning_occured\n\ndef preprocess_all(data_dict):\n '''\n Performs preprocessing on all loaded elements in a data dictionary.\n '''\n\n results = {}\n\n for item in data_dict.keys():\n print(\"preprocessing {}\".format(item))\n rms = preprocess_rms(data_dict[item]['rms'])\n add_power_feature(rms)\n add_temp_diff(rms)\n add_alarms(rms, data_dict[item]['alarms'])\n results[item] = rms\n","sub_path":"data_processing/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":4824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"441313466","text":"#!/usr/bin/env python3\n\n# Copyright (c) 2023, Hugo Costelha\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 met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# * Neither the name of the Player Project nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE 4 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# Revision $Id$\n\n'''@package docstring\nRecharge action: Request charging.\n'''\n\n# Non-ROS modules\nimport os\nfrom threading import Lock, Event\nimport functools\n\n# ROS related modules\nimport rclpy\nfrom rclpy.action import ActionServer, CancelResponse, GoalResponse\nfrom rclpy.executors import MultiThreadedExecutor\nfrom rclpy.callback_groups import ReentrantCallbackGroup\nfrom rclpy.node import Node\nfrom sensor_msgs.msg import BatteryState\n\n# Our modules\nimport lw2.myglobals as myglobals\nfrom ar_utils.action import Recharge\nfrom ar_utils.srv import StartCharging # Access to the battery manager service\n\n\n# This action name (strip the '.py' preffix)\nACTION_NAME = os.path.basename(__file__)[:-3]\n\n\nclass RechargeActionServer(Node):\n '''\n Charge the robot battery, if the robot is in a charging location.\n This action accepts a single goal at a time so, requesting a new goal\n while a previous one was alread running, cancels the previous goal.\n '''\n # Store the action feecback and result functions as class attributes,\n # i.e., they are the same for all instances of this class\n def __init__(self):\n '''Constructor'''\n super().__init__('action_recharge')\n\n # Create condition to manage access to the goal variable, wich will be\n # accessed in multiple callbacks\n self.goal_handle = None\n self.goal_lock = Lock()\n self.battery_level = -1.0\n\n # Enable access to the battery charging service\n self.charge_battery_svc = self.create_client(\n StartCharging,\n f'{myglobals.robot_name}/battery/charge')\n\n # Wait for the service fo bt available\n while self.charge_battery_svc.wait_for_service(2.0) is False:\n self.get_logger().info(\n f'Executing action {ACTION_NAME}: still waiting for the ' +\n f'battery service at {myglobals.robot_name}/battery/charge...')\n\n # Battery state subscriber (to be used later on)\n self.sub_batt = None\n\n # Start the action server.\n # The option ReentrantCallbackGroup allows callbacks to be run in\n # parallel without restrictions\n self.action_server = ActionServer(\n self,\n Recharge,\n f'/{myglobals.robot_name}/{ACTION_NAME}',\n execute_callback=self.execute_cb,\n goal_callback=self.goal_cb,\n handle_accepted_callback=self.handle_accepted_cb,\n cancel_callback=self.cancel_cb,\n callback_group=ReentrantCallbackGroup())\n\n def destroy(self):\n ''' Destructor '''\n self.action_server.destroy()\n super().destroy_node()\n\n def goal_cb(self, goal_request):\n '''This function is called when a new goal is requested. Currently it\n always accept a new goal.'''\n self.get_logger().info(f'{ACTION_NAME} received new goal request:')\n return GoalResponse.ACCEPT\n\n def handle_accepted_cb(self, goal_handle):\n ''' This function runs whenever a new goal is accepted.'''\n with self.goal_lock:\n # This server only allows one goal at a time\n if (self.goal_handle is not None) and (self.goal_handle.is_active):\n self.get_logger().info(f'{ACTION_NAME} aborting previous goal')\n # Abort the existing goal\n self.goal_handle.abort()\n self.goal_handle = goal_handle\n # Start runing the execute callback\n goal_handle.execute()\n\n def cancel_cb(self, goal_handle):\n ''' Callback that's called when an action cancellation is requested '''\n self.get_logger().info(f'{ACTION_NAME} received a cancel request!')\n # The cancel request was accepted\n return CancelResponse.ACCEPT\n\n def execute_cb(self, goal_handle):\n ''' Callback to execute when the action has a new goal '''\n self.get_logger().info(\n f'Executing action {ACTION_NAME} with battery-level ' +\n f'goal {goal_handle.request.target_battery_level:2.2f}')\n\n # Wait for a confimation (trigger), either due to the goal having\n # succeeded, or the goal having been cancelled.\n trigger_event = Event() # Flag is intially set to False\n\n # Request charging to start\n svc_req = StartCharging.Request()\n svc_req.charge = True\n resp = self.charge_battery_svc.call(svc_req)\n if resp.charging is False:\n # If it fails, abort action\n goal_handle.abort()\n self.get_logger().warn(\n f'{ACTION_NAME} - unable to start charging!')\n return Recharge.Result(battery_level=self.battery_level)\n\n # Setup subscriber for the battery level\n with self.goal_lock:\n if self.sub_batt is None:\n self.sub_batt = self.create_subscription(\n BatteryState,\n myglobals.robot_name + '/battery/state',\n functools.partial(self.batteryStateCb,\n goal_handle=goal_handle,\n trigger_event=trigger_event),\n 1,\n callback_group=ReentrantCallbackGroup())\n\n # Used for feedback purposes\n feedback = Recharge.Feedback()\n\n while rclpy.ok():\n # Wait for new information to arrive\n if trigger_event.wait(5.0) is False:\n self.get_logger().warn(f'{ACTION_NAME} is still running')\n with self.goal_lock:\n if self.sub_batt is None:\n self.sub_batt = self.create_subscription(\n BatteryState,\n myglobals.robot_name + '/battery/state',\n functools.partial(self.batteryStateCb,\n goal_handle=goal_handle,\n trigger_event=trigger_event),\n 1,\n callback_group=ReentrantCallbackGroup())\n else:\n # If the event was triggered, clear it\n trigger_event.clear()\n\n with self.goal_lock:\n # Only continue if the goal is active and a cancel was not\n # requested\n if (not goal_handle.is_active) or \\\n (goal_handle.is_cancel_requested):\n if not goal_handle.is_active:\n self.get_logger().info(f'{ACTION_NAME}: goal aborted')\n else: # goal_handle.is_cancel_requested\n goal_handle.canceled() # Confirm goal is canceled\n self.get_logger().info(f'{ACTION_NAME}: goal canceled')\n # No need for the callback anymore\n if self.sub_batt is not None:\n self.destroy_subscription(self.sub_batt)\n self.sub_batt = None\n # Cancel the recharging and return\n svc_req = StartCharging.Request()\n svc_req.charge = False\n resp = self.charge_battery_svc.call(svc_req)\n return Recharge.Result(battery_level=self.battery_level)\n\n # Do nothing until we have an update\n if self.battery_level >= \\\n goal_handle.request.target_battery_level:\n # We are done, no need for the callback anymore\n if self.sub_batt is not None:\n self.destroy_subscription(self.sub_batt)\n self.sub_batt = None\n # Trigger SUCCEED\n goal_handle.succeed()\n self.get_logger().info(f'{ACTION_NAME} has succeeded!')\n # Cancel the recharging and return\n svc_req = StartCharging.Request()\n svc_req.charge = False\n resp = self.charge_battery_svc.call(svc_req)\n # Return last reported battery level\n return Recharge.Result(battery_level=self.battery_level)\n else:\n # Publish feedback (current battery level)\n feedback.battery_level = self.battery_level\n goal_handle.publish_feedback(feedback)\n\n def batteryStateCb(self, msg: BatteryState, goal_handle, trigger_event):\n '''\n Receive current robot battery charge\n '''\n with self.goal_lock:\n # Check if we are still \"in business\"\n if not goal_handle.is_active:\n self.get_logger().warn(\n f'{ACTION_NAME} callback called without active goal!')\n return\n\n # Store the robot pose\n self.battery_level = msg.percentage\n\n # Trigger execute_cb to continue\n trigger_event.set()\n\n\ndef main(args=None):\n ''' Main function - start the action server.\n '''\n rclpy.init(args=args)\n recharge_action_server = RechargeActionServer()\n\n # Use 2 threads to make sure callbacks can run in parallel and the action\n # does not block.\n executor = MultiThreadedExecutor(num_threads=2)\n executor.add_node(recharge_action_server)\n executor.spin()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/lw2/lw2/ActionRecharge.py","file_name":"ActionRecharge.py","file_ext":"py","file_size_in_byte":10932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"396553713","text":"\"\"\"\n8.\tПосчитать, сколько раз встречается определенная цифра в введенной\n последовательности чисел. Количество вводимых чисел и цифра,\n которую необходимо посчитать, задаются вводом с клавиатуры.\n\"\"\"\n\n\nwhile True:\n try:\n find_count = 0\n find_number = int(input('Введите нужное число: '))\n n = int(input('Введите число n, количество чисел последовательности: '))\n count = 0\n while count < n:\n number = int(input('Введите число последовательности: '))\n count += 1\n if find_number == number:\n find_count += 1\n print('Число {} встречается {} раз'.format(find_number, find_count))\n break\n except ValueError:\n print('Введено некорректное значение')\n","sub_path":"Lesson_2/8.py","file_name":"8.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"370716991","text":"import autograd.numpy as np\nimport autograd.numpy.random as npr\nnpr.seed(0)\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom ssm.models import SLDS, LDS\nfrom ssm.variational import SLDSMeanFieldVariationalPosterior, SLDSTriDiagVariationalPosterior\nfrom ssm.util import random_rotation, find_permutation\n\n# Set the parameters of the HMM\nT = 1000 # number of time bins\nK = 5 # number of discrete states\nD = 2 # number of latent dimensions\nN = 10 # number of observed dimensions\n\n# Make an SLDS with the true parameters\ntrue_slds = SLDS(N, K, D, emissions=\"gaussian\")\nfor k in range(K):\n true_slds.dynamics.As[k] = .95 * random_rotation(D, theta=(k+1) * np.pi/20)\n\n# Sample training and test data from the SLDS\nz, x, y = true_slds.sample(T)\nz_test, x_test, y_test = true_slds.sample(T)\n\n# Mask off some data\nmask = npr.rand(T, N) < 0.75\ny_masked = y * mask\n\n# Fit an SLDS with mean field posterior\nprint(\"Fitting SLDS with SVI using structured variational posterior\")\nslds = SLDS(N, K, D, emissions=\"gaussian\")\nslds.initialize(y_masked, masks=mask)\n\nq_mf = SLDSMeanFieldVariationalPosterior(slds, y_masked, masks=mask)\nq_mf_elbos = slds.fit(q_mf, y_masked, masks=mask, num_iters=1000, initialize=False)\nq_mf_x = q_mf.mean[0]\nq_mf_y = slds.smooth(q_mf_x, y)\n\n# Find the permutation that matches the true and inferred states\nslds.permute(find_permutation(z, slds.most_likely_states(q_mf_x, y)))\nq_mf_z = slds.most_likely_states(q_mf_x, y)\n\n# Do the same with the structured posterior\nprint(\"Fitting SLDS with SVI using structured variational posterior\")\nslds = SLDS(N, K, D, emissions=\"gaussian\")\nslds.initialize(y_masked, masks=mask)\n\nq_struct = SLDSTriDiagVariationalPosterior(slds, y_masked, masks=mask)\nq_struct_elbos = slds.fit(q_struct, y_masked, masks=mask, num_iters=1000, initialize=False)\nq_struct_x = q_struct.mean[0]\nq_struct_y = slds.smooth(q_struct_x, y)\n\n# Find the permutation that matches the true and inferred states\nslds.permute(find_permutation(z, slds.most_likely_states(q_struct_x, y)))\nq_struct_z = slds.most_likely_states(q_struct_x, y)\n\n# Plot the ELBOS\nplt.figure()\nplt.plot(q_mf_elbos, label=\"MF\")\nplt.plot(q_struct_elbos, label=\"LDS\")\nplt.xlabel(\"Iteration\")\nplt.ylabel(\"ELBO\")\nplt.legend()\n\n# Plot the true and inferred states\nplt.figure(figsize=(8,6))\nxlim = (0, 1000)\n\nplt.subplot(311)\nplt.imshow(np.row_stack((z, q_mf_z, q_struct_z)), aspect=\"auto\")\nplt.yticks([0, 1, 2], [\"$z_{{\\\\mathrm{{true}}}}$\", \"$z_{{\\\\mathrm{{mf}}}}$\", \"$z_{{\\\\mathrm{{lds}}}}$\"])\nplt.xlim(xlim)\n\nplt.subplot(312)\nplt.plot(x, '-k', label=\"True\")\nplt.plot(q_mf_x, '--b', label=\"$q_{\\\\text{MF}}$\")\nplt.plot(q_struct_x, ':r', label=\"$q_{\\\\text{LDS}}$\")\nplt.ylabel(\"$x$\")\nplt.xlim(xlim)\n\nplt.subplot(313)\nfor n in range(N):\n plt.plot(y[:, n] + 4 * n, '-k', label=\"True\" if n == 0 else None)\n plt.plot(q_mf_y[:, n] + 4 * n, '--b', label=\"MF\" if n == 0 else None)\n plt.plot(q_struct_y[:, n] + 4 * n, ':r', label=\"LDS\" if n == 0 else None)\nplt.legend()\nplt.ylabel(\"$y$\")\nplt.xlabel(\"time\")\nplt.xlim(xlim)\n\nplt.show()\n","sub_path":"examples/slds.py","file_name":"slds.py","file_ext":"py","file_size_in_byte":3051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"492119089","text":"# -*- coding:utf-8 -*-\n\n__author__ = 'fanhaiqiang'\n\n\nimport argparse\nfrom argparse import ArgumentParser\nimport time\nimport os\nimport os.path\nimport sys\nimport logging\nimport urlparse\ntry:\n import json # python >= 2.6\nexcept ImportError:\n import simplejson as json # python <= 2.5\n\nimport provider\nimport parser\nimport writer\n\nos.environ[\"TZ\"] = \"Asia/Shanghai\"\ntime.altzone\n\n# init logger\nconsole = logging.StreamHandler()\nconsole.setLevel(logging.DEBUG)\nformatter = logging.Formatter(\"%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s\")\nconsole.setFormatter(formatter)\nlogging.getLogger(\"\").addHandler(console)\n\nERR_SUCCEED = 0\nERR_EXCEPTION = 1\nERR_INVALID_SOURCE = 2\nERR_FAILED_ON_WRITE = 3\nERR_DEBUG = 4\nERR_UNKNOWN = 5\n\nSECONDS_A_DAY = 86400\nMAIN = 1\nSTART_TIME = time.time()\nDEFAULT_MAX_ROWS = 9999999999999\nDEFAULT_TEST_ROWS = 10000\n\nDATA_FILE = os.path.join(os.path.split(os.path.realpath(__file__))[0], 'data/17monipdb.dat')\n\n# 无参数时显示使用信息\n\nif len(sys.argv) < 2 :\n pass\n\n\nparser = ArgumentParser('''\n{$GLOBALS['argv'][0]} [OPTIONS]... DAY PROFILE [PARSERS...]\nUsing parsers to parse custom logs of the specified day.\n\nType 'last' to DAY argument will parse log data of yesterday.\nType 'all' to PARSER argument will make parsing by all parsers.\n''')\n\nparser.add_argument(\"-t\", \"--test\", help=\"Program will be terminate after parsed 10000 lines due to test.\", action=\"store_true\")\nparser.add_argument(\"--max-rows\", help=\"Program will be terminate after parsed ROWS lines.\", type=int, default=0)\nparser.add_argument(\"--days\", help=\"Parsing from DAY and next to DAYS below, 1 by default.\", default=1, type=int, choices=range(1, 366))\nparser.add_argument(\"--output\", help=\"Output files to DIR, default is 'output'.\", default=\"output\")\nparser.add_argument(\"--const\", help=\"Set constants table by a string which was URL style. e.g. --const='prefix=1&postfix=9'.\")\nparser.add_argument(\"-m\", \"--memory-usage\", help=\"Show memory usage before and after parsing.\", action=\"store_true\")\nparser.add_argument(\"-d\", \"--dump\", help=\"Dump the first line for debugging.\", action=\"store_true\")\nparser.add_argument(\"-l\", \"--list\", help=\"List all available parsers.\", action=\"store_true\")\ngroup = parser.add_mutually_exclusive_group()\ngroup.add_argument(\"-v\", \"--verbose\", help=\"verbosely list files processed.\", action=\"store_true\")\ngroup.add_argument(\"-q\", \"--quiet\", help=\"Do not display any message except output of parsers.\", action=\"store_true\")\n\nparser.add_argument(\"day\", help=\"date\")\nparser.add_argument(\"profile\", help=\"profile\")\nparser.add_argument(\"parsers\", help=\"parsers\", nargs=argparse.REMAINDER)\n\nargs = parser.parse_args()\n\n# get command line options\nlogging.debug(\"get command line options\")\noptions = {}\nQUIET_MODE = args.quiet\nVERBOSE_MODE = args.verbose\noptions[\"dump\"] = args.dump\nif args.list:\n #call showParsers()\n pass\nif args.const:\n #options[\"const\"] = urlparse.parse_qs(args.const)\n options.update(urlparse.parse_qs(args.const))\nif args.day == \"last\":\n tmpDate = time.strftime(\"%Y%m%d\", time.localtime(time.time() - SECONDS_A_DAY))\nelse:\n tmpDate = time.strftime(\"%Y%m%d\", time.localtime(time.time()))\noptions[\"lastDay\"] = options[\"firstDay\"] = tmpDate\nif args.days:\n options[\"lastDay\"] = time.strftime(\"%Y%m%d\", time.localtime(time.mktime(time.strptime(options[\"firstDay\"], \"%Y%m%d\")) + (args.days - 1) * SECONDS_A_DAY))\noptions['max_rows'] = DEFAULT_MAX_ROWS\noptions['test'] = False\nif args.test:\n options['max_rows'] = DEFAULT_TEST_ROWS\n options['test'] = True\nif args.max_rows:\n options[\"max_rows\"] = args.max_rows\nif args.output:\n output = args.output\nelse:\n test = options.get(\"test\")\n output = os.path.join(os.path.split(os.path.realpath(__file__))[0], '/debug' if test else '/output')\nif os.path.isdir(output):\n options['output_directory'] = output\noptions['memory_usage'] = args.memory_usage\noptions['verbose'] = args.verbose\noptions[\"log_type\"] = args.profile\n\nparsers = []\nif len(args.parsers) == 0:\n #default parser\n #TODO\n pass\nelif len(args.parsers) == 1 and args.parsers[0] == \"all\":\n #all parsers\n #TODO\n pass\nelse:\n #custom parsers\n #TODO\n pass\noptions[\"parsers\"] = parsers\n\n# load configuration\nlogging.debug(\"load configuration\")\nconfig_info = {}\nconfig_dir = os.path.join(os.path.split(os.path.realpath(__file__))[0], 'config')\nfor subdir, dirs, files in os.walk(config_dir):\n for config_file in files:\n config_file_abs_path = os.path.join(config_dir, config_file)\n with open(config_file_abs_path, 'r') as f:\n config_info.update(json.load(f))\n\n# move \"const\" parameters to top level\nlogging.debug(\"move 'const' parameters to top level\")\nprofile = config_info.get(options['log_type'])\nif profile.has_key(\"const\"):\n options.update(profile.get(\"const\"))\n\n\n_provider = provider.provider_factory.create_instance(profile, options)\n_provider.open()\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"294495814","text":"from dataclasses import dataclass, field\nfrom typing import Optional, Tuple, Set, Dict\n\nfrom .firmware import Firmware\nfrom .instruction import Instruction, Op, Reg, Offset, get_bl_jump, decode\nfrom .symbol import Function, Symbol\n\nINSN_NOP = Instruction(op=Op.MOV, rd=Reg.r8, rs=Reg.r8)\nCOND_JUMPS = frozenset({\n Op.BEQ,\n Op.BNE,\n Op.BCS,\n Op.BCC,\n Op.BMI,\n Op.BPL,\n Op.BVS,\n Op.BVC,\n Op.BHI,\n Op.BLS,\n Op.BGE,\n Op.BLT,\n Op.BGT,\n Op.BLE,\n})\n\nOFFSET_JUMPS = frozenset({\n Op.B,\n Op.BX,\n Op.BL,\n Op.BLX,\n})\n\nJUMPS = frozenset(COND_JUMPS | OFFSET_JUMPS)\n\n\ndef is_jump(insn: Instruction):\n return insn.op in JUMPS or (insn.op == Op.POP and insn.flag)\n\n\nTAIL_FUNCTIONS = {\n \"__fatal_error\",\n \"_start\",\n \"nlr_jump\",\n \"nlr_jump_fail\",\n \"m_malloc_fail\",\n \"mp_hal_raise\",\n \"mp_arg_error_terse_mismatch\",\n \"mp_arg_error_unimpl_kw\",\n}\n\n\ndef is_tail_func(func: Function):\n return func.name in TAIL_FUNCTIONS or func.name.startswith(\"mp_raise_\") or func.name.startswith(\"unlikely.\")\n\n\n@dataclass\nclass FunctionInfo:\n function: Function\n insns: Tuple[Optional[Instruction]] = field(default=())\n jumps: Set[int] = field(default_factory=set)\n visited: Set[int] = field(default_factory=set)\n eof: Set[int] = field(default_factory=set)\n\n def __post_init__(self):\n insns = [*map(decode, self.function.codes), None]\n for pos, insn in enumerate(insns):\n if insn is None:\n continue\n elif insn.op == Op.BL:\n next_insn = insns[pos + 1]\n offset = get_bl_jump(insn, next_insn)\n if offset is not None:\n insns[pos] = Instruction(Op.BL, Offset(offset), flag=None)\n insns[pos + 1] = None\n\n self.insns = tuple(insns)\n\n\nclass Visitor:\n functions: Dict[Function, FunctionInfo]\n\n def __init__(self, firmware: Firmware):\n self.firmware = firmware\n self.functions = {\n function: FunctionInfo(function)\n for function in self.firmware.functions.values()\n }\n\n def visit_all(self):\n self.visit_entry_table()\n for function in self.firmware.functions.values():\n self.visit(function)\n\n def visit(self, function: Function, pc: Optional[int] = None):\n info = self.functions[function]\n begin, end = function.address, function.end\n insns = info.insns\n visited = info.visited\n jumps = info.jumps\n eof = info.eof\n\n def visit(pc: int):\n pos = (pc - begin) >> 1\n if pos < 0:\n return\n\n jumps.add(pos)\n\n prev_insn = None\n while pc < end:\n if pos not in visited:\n visited.add(pos)\n else:\n return\n\n insn = insns[pos]\n if insn is None:\n raise ValueError(insn)\n\n # print(function.name, hex(pc), pos, insn)\n if prev_insn is None and insn == INSN_NOP and function.name == \"mp_execute_bytecode\":\n eof.add(pos - 1)\n # crash detected\n return\n\n if is_jump(insn):\n new_pc, next_pc = self.next_op(pc, insn, insns[pos + 1])\n\n if new_pc is not None:\n if begin <= new_pc < end:\n visit(new_pc)\n else:\n new_function = self.firmware.lookup(new_pc)\n self.visit(new_function, new_pc)\n\n if next_pc is not None:\n prev_insn = None\n pos += (next_pc - pc) >> 1\n pc = next_pc\n else:\n eof.add(pos)\n return\n else:\n prev_insn = insn\n pos += 1\n pc += 2\n else:\n if function.size > 0:\n assert False, (hex(pc), function)\n\n visit(begin if pc is None else pc)\n\n def next_op(self,\n pc: int,\n insn: Instruction,\n next_insn: Optional[Instruction] = None) -> Tuple[Optional[int], Optional[int]]:\n if insn.op == Op.POP and insn.flag:\n return None, None\n elif insn.op == Op.B:\n assert isinstance(insn.rd, Offset)\n new_pc = pc + int(insn.rd)\n next_pc = None\n elif insn.op == Op.BL:\n if insn.flag is None:\n offset = int(insn.rd)\n else:\n offset = get_bl_jump(insn, next_insn)\n\n if offset is not None:\n new_pc = pc + offset\n next_pc = pc + 4\n else:\n raise AssertionError((pc, insn))\n elif insn.op == Op.BX:\n assert isinstance(insn.rd, Reg)\n new_pc = None\n next_pc = None\n elif insn.op == Op.BLX:\n assert isinstance(insn.rd, Reg)\n new_pc = None\n next_pc = pc + 2\n elif insn.op in COND_JUMPS:\n assert isinstance(insn.rd, Offset)\n new_pc = pc + int(insn.rd)\n next_pc = pc + 2\n else:\n raise ValueError(insn)\n\n if new_pc is not None:\n new_symbol = self.firmware.lookup(new_pc)\n if is_tail_func(new_symbol):\n next_pc = None\n\n return new_pc, next_pc\n\n def visit_entry_table(self):\n mp_execute_bytecode = self.firmware.functions[\"mp_execute_bytecode\"]\n entry_table = self._find_entry_table()\n\n for offset in range(0, 256 * 4, 4):\n pc = int.from_bytes(entry_table.content[offset: offset + 4], byteorder='little')\n assert mp_execute_bytecode.address <= pc < mp_execute_bytecode.end, pc\n self.visit(mp_execute_bytecode, pc)\n\n def _find_entry_table(self) -> Symbol:\n entry_table = None\n\n for name in self.firmware.symbols:\n if name.startswith('entry_table.'):\n assert entry_table is None\n entry_table = self.firmware.symbols[name]\n else:\n assert entry_table\n\n return entry_table\n","sub_path":"opaot/visitor.py","file_name":"visitor.py","file_ext":"py","file_size_in_byte":6333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"596228683","text":"\"\"\"Contains the workflow update REST endpoint.\"\"\"\n\nimport os\nimport json\nimport shutil\nimport subprocess\nimport time\nimport jsonpickle\n\nfrom flask import make_response, jsonify\nfrom flask_restful import Resource, reqparse\nfrom beeflow.wf_manager.resources import wf_utils\nfrom beeflow.wf_manager.common import dep_manager\nfrom beeflow.common import log as bee_logging\n\nfrom beeflow.common.db import wfm_db\nfrom beeflow.common.db.bdb import connect_db\n\n\nlog = bee_logging.setup(__name__)\ndb_path = wf_utils.get_db_path()\n\n\ndef archive_workflow(db, wf_id):\n \"\"\"Archive a workflow after completion.\"\"\"\n # Archive Config\n workflow_dir = wf_utils.get_workflow_dir(wf_id)\n shutil.copyfile(os.path.expanduser(\"~\") + '/.config/beeflow/bee.conf',\n workflow_dir + '/' + 'bee.conf')\n\n db.workflows.update_workflow_state(wf_id, 'Archived')\n wf_utils.update_wf_status(wf_id, 'Archived')\n\n bee_workdir = wf_utils.get_bee_workdir()\n archive_dir = os.path.join(bee_workdir, 'archives')\n os.makedirs(archive_dir, exist_ok=True)\n archive_path = f'../archives/{wf_id}.tgz'\n # We use tar directly since tarfile is apparently very slow\n workflows_dir = wf_utils.get_workflows_dir()\n subprocess.call(['tar', '-czf', archive_path, wf_id], cwd=workflows_dir)\n\n\nclass WFUpdate(Resource):\n \"\"\"Class to interact with an existing workflow.\"\"\"\n\n def __init__(self):\n \"\"\"Set up arguments.\"\"\"\n self.reqparse = reqparse.RequestParser()\n self.reqparse.add_argument('wf_id', type=str, location='json',\n required=True)\n self.reqparse.add_argument('task_id', type=str, location='json',\n required=True)\n self.reqparse.add_argument('job_state', type=str, location='json',\n required=True)\n self.reqparse.add_argument('metadata', type=str, location='json',\n required=False)\n self.reqparse.add_argument('task_info', type=str, location='json',\n required=False)\n self.reqparse.add_argument('output', location='json', required=False)\n\n def put(self):\n \"\"\"Update the state of a task from the task manager.\"\"\"\n db = connect_db(wfm_db, db_path)\n data = self.reqparse.parse_args()\n wf_id = data['wf_id']\n task_id = data['task_id']\n job_state = data['job_state']\n\n wfi = wf_utils.get_workflow_interface(wf_id)\n task = wfi.get_task_by_id(task_id)\n wfi.set_task_state(task, job_state)\n db.workflows.update_task_state(task_id, wf_id, job_state)\n\n # Get metadata from update if available\n if 'metadata' in data:\n if data['metadata'] is not None:\n metadata = jsonpickle.decode(data['metadata'])\n wfi.set_task_metadata(task, metadata)\n\n bee_workdir = wf_utils.get_bee_workdir()\n # Get output from the task\n if 'metadata' in data:\n if data['metadata'] is not None:\n metadata = jsonpickle.decode(data['metadata'])\n old_metadata = wfi.get_task_metadata(task)\n old_metadata.update(metadata)\n wfi.set_task_metadata(task, old_metadata)\n\n if 'output' in data and data['output'] is not None:\n fname = f'{wfi.workflow_id}_{task.id}_{int(time.time())}.json'\n task_output_path = os.path.join(bee_workdir, fname)\n with open(task_output_path, 'w', encoding='utf8') as fp:\n json.dump(json.loads(data['output']), fp, indent=4)\n\n if 'task_info' in data and data['task_info'] is not None:\n task_info = jsonpickle.decode(data['task_info'])\n checkpoint_file = task_info['checkpoint_file']\n new_task = wfi.restart_task(task, checkpoint_file)\n db.workflows.add_task(new_task.id, wf_id, new_task.name, \"WAITING\")\n if new_task is None:\n log.info('No more restarts')\n state = wfi.get_task_state(task)\n return make_response(jsonify(status=f'Task {task_id} set to {job_state}'))\n # Submit the restart task\n tasks = [new_task]\n wf_utils.schedule_submit_tasks(wf_id, tasks)\n return make_response(jsonify(status='Task {task_id} restarted'))\n\n if job_state in ('COMPLETED', 'FAILED'):\n for output in task.outputs:\n if output.glob is not None:\n wfi.set_task_output(task, output.id, output.glob)\n else:\n wfi.set_task_output(task, output.id, \"temp\")\n tasks = wfi.finalize_task(task)\n state = wfi.get_workflow_state()\n if tasks and state != 'PAUSED':\n wf_utils.schedule_submit_tasks(wf_id, tasks)\n\n if wfi.workflow_completed():\n log.info(\"Workflow Completed\")\n wf_id = wfi.workflow_id\n archive_workflow(db, wf_id)\n pid = db.workflows.get_gdb_pid(wf_id)\n dep_manager.kill_gdb(pid)\n resp = make_response(jsonify(status=(f'Task {task_id} belonging to WF {wf_id} set to'\n f'{job_state}')), 200)\n return resp\n# Ignoring C901,R0915: \"'WFUPdate.put' is too complex\" - this requires a refactor\n# (or maybe the LOC limit is too low)\n# pylama:ignore=C901,R0915\n","sub_path":"beeflow/wf_manager/resources/wf_update.py","file_name":"wf_update.py","file_ext":"py","file_size_in_byte":5477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"15119713","text":"\"\"\" Example DE-Sim implementations of stochastic Susceptible, Infectious, or Recovered (SIR) epidemic models\n\n:Author: Arthur Goldberg \n:Date: 2020-07-08\n:Copyright: 2020, Karr Lab\n:License: MIT\n\"\"\"\n\nimport enum\nimport numpy\n\nfrom de_sim.event import Event\nfrom de_sim.simulation_engine import SimulationEngine\nfrom de_sim.simulation_message import SimulationMessage\nfrom de_sim.simulation_object import ApplicationSimulationObject\n\n\nclass SusceptibleToInfectious(SimulationMessage):\n \"S -> I transition\"\n\n\nclass InfectiousToRecovered(SimulationMessage):\n \"I -> R transition\"\n\n\nclass RecordTrajectory(SimulationMessage):\n \"Record trajectory\"\n\n\nMESSAGE_TYPES = [SusceptibleToInfectious, InfectiousToRecovered, RecordTrajectory]\n\n\nclass SIR(ApplicationSimulationObject):\n \"\"\" Implement a Susceptible, Infectious, or Recovered (SIR) epidemic model\n\n This example uses DE-Sim to implement a continuous-time Markov chain (CTMC) SIR\n epidemic model, as described in section 3 of Allen (2017).\n\n Allen, L.J., 2017. A primer on stochastic epidemic models: Formulation, numerical simulation, and analysis.\n Infectious Disease Modelling, 2(2), pp.128-142.\n\n Attributes:\n s (:obj:`int`): number of susceptible subjects\n i (:obj:`int`): number of infectious subjects\n N (:obj:`int`): total number of susceptible subjects, a constant\n beta (:obj:`float`): SIR beta parameter\n gamma (:obj:`float`): SIR gamma parameter\n recording_period (:obj:`float`): time step for recording state\n random_state (:obj:`numpy.random.RandomState`): a random state\n history (:obj:`list`): list of recorded states\n \"\"\"\n def __init__(self, name, s, i, N, beta, gamma, recording_period):\n \"\"\" Initialize a SIR instance\n\n Args:\n name (:obj:`str`): the instance's name\n s (:obj:`int`): initial number of susceptible subjects, s(0)\n i (:obj:`int`): initial number of infectious subjects, i(0)\n N (:obj:`int`): total number of susceptible subjects, a constant\n beta (:obj:`float`): SIR beta parameter\n gamma (:obj:`float`): SIR gamma parameter\n recording_period (:obj:`float`): time step for recording state\n random_state (:obj:`numpy.random.RandomState`): random state\n history (:obj:`list`): list of recorded states\n \"\"\"\n self.s = s\n self.i = i\n self.N = N\n self.beta = beta\n self.gamma = gamma\n self.recording_period = recording_period\n self.random_state = numpy.random.RandomState()\n self.history = []\n super().__init__(name)\n\n def send_initial_events(self):\n \"\"\" Send the initial events, and record the initial state\n \"\"\"\n self.schedule_next_event()\n self.record_trajectory(None)\n\n def schedule_next_event(self):\n \"\"\" Schedule the next SIR event\n \"\"\"\n rates = {'s_to_i': self.beta * self.s * self.i / self.N,\n 'i_to_r': self.gamma * self.i}\n lambda_val = rates['s_to_i'] + rates['i_to_r']\n if lambda_val == 0:\n return\n\n tau = self.random_state.exponential(1.0/lambda_val)\n prob_s_to_i = rates['s_to_i'] / lambda_val\n if self.random_state.random_sample() < prob_s_to_i:\n self.send_event(tau, self, SusceptibleToInfectious())\n else:\n self.send_event(tau, self, InfectiousToRecovered())\n\n def handle_s_to_i(self, event):\n \"\"\" Handle a susceptible to infectious event\n\n Args:\n event (:obj:`Event`): simulation event; not used\n \"\"\"\n self.s -= 1\n self.i += 1\n self.schedule_next_event()\n\n def handle_i_to_r(self, event):\n \"\"\" Handle an infectious to recovered event\n\n Args:\n event (:obj:`Event`): simulation event; not used\n \"\"\"\n self.i -= 1\n self.schedule_next_event()\n\n def record_trajectory(self, event):\n \"\"\" Add another record to the SIR history\n\n Args:\n event (:obj:`Event`): simulation event; not used\n \"\"\"\n self.history.append(dict(time=self.time,\n s=self.s,\n i=self.i))\n self.send_event(self.recording_period, self, RecordTrajectory())\n\n event_handlers = [(SusceptibleToInfectious, 'handle_s_to_i'),\n (InfectiousToRecovered, 'handle_i_to_r'),\n (RecordTrajectory, 'record_trajectory')]\n\n # register the message types sent\n messages_sent = MESSAGE_TYPES\n\n\n### SIR epidemic model, version 2 ###\nclass StateTransition(SimulationMessage):\n \"State transition\"\n attributes = ['transition']\n\n\nMESSAGE_TYPES = [StateTransition, RecordTrajectory]\n\n\nclass Transition(enum.Enum):\n \"\"\" Transition values\n \"\"\"\n s_to_i = enum.auto()\n i_to_r = enum.auto()\n\n\nclass SIR2(SIR):\n \"\"\" Version 2 of a SIR epidemic model\n\n SIR2 is similar to SIR, but uses one event message type for both transitions, and a\n single message handler to process transition events.\n \"\"\"\n def schedule_next_event(self):\n \"\"\" Schedule the next SIR event\n \"\"\"\n rates = {'s_to_i': self.beta * self.s * self.i / self.N,\n 'i_to_r': self.gamma * self.i}\n lambda_val = rates['s_to_i'] + rates['i_to_r']\n if lambda_val == 0:\n return\n\n tau = self.random_state.exponential(1.0/lambda_val)\n prob_s_to_i = rates['s_to_i'] / lambda_val\n if self.random_state.random_sample() < prob_s_to_i:\n self.send_event(tau, self, StateTransition(Transition.s_to_i))\n else:\n self.send_event(tau, self, StateTransition(Transition.i_to_r))\n\n def handle_state_transition(self, event):\n \"\"\" Handle an infectious state transition\n\n Args:\n event (:obj:`Event`): simulation event that contains the type of transition\n \"\"\"\n transition = event.message.transition\n if transition is Transition.s_to_i:\n self.s -= 1\n self.i += 1\n elif transition is Transition.i_to_r:\n self.i -= 1\n self.schedule_next_event()\n\n def record_trajectory(self, event):\n \"\"\" Add another record to the SIR history\n\n Args:\n event (:obj:`Event`): simulation event; not used\n \"\"\"\n self.history.append(dict(time=self.time,\n s=self.s,\n i=self.i))\n self.send_event(self.recording_period, self, RecordTrajectory())\n\n event_handlers = [(StateTransition, 'handle_state_transition'),\n (RecordTrajectory, 'record_trajectory')]\n\n # register the message types sent\n messages_sent = MESSAGE_TYPES\n\n\nclass RunSIRs(object):\n\n @staticmethod\n def main(sir_class, time_max, seed, **sir_args):\n\n # create a simulator\n simulator = SimulationEngine()\n\n # create a SIR instance\n sir = sir_class(**sir_args)\n simulator.add_object(sir)\n\n # initialize simulation, which sends the SIR instance an initial event message\n simulator.initialize()\n\n # run the simulation\n event_num = simulator.simulate(time_max).num_events\n print(\"Executed {} events.\\n\".format(event_num))\n return sir\n\n @staticmethod\n def print_history(sir):\n header = ['time', 's', 'i', 'r']\n print('\\t'.join(header))\n for state in sir.history:\n state_as_list = [state['time'], state['s'], state['i'], sir.N - state['s'] - state['i']]\n state_as_list = [str(v) for v in state_as_list]\n print('\\t'.join(state_as_list))\n","sub_path":"de_sim/examples/sirs.py","file_name":"sirs.py","file_ext":"py","file_size_in_byte":7755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"349158309","text":"import random\nimport os\nimport numpy as np\nimport pandas as pd\nimport cv2\nimport progressbar\n\nBASE_DIR = os.path.abspath(os.path.dirname(\"__file__\"))\nVGG_TEST_SET_DIR = os.path.join(BASE_DIR, \"data\",\"vgg_face_2\", \"test_set\")\nNUMPY_DIR = os.path.join(BASE_DIR, \"data\",\"numpy_arrays\")\nHAARCASCADE_MODEL_PATH = os.path.join(BASE_DIR, \"model_files\", \"haarcascade_frontalface_default.xml\")\nRANDOM_SEED = 1\nNUMPY_SEED = 1\n\ndef face_detect(image,\n dim = (160,160)):\n '''\n Detect to detect and return face\n '''\n gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n faces = face_detector.detectMultiScale(gray_img, scaleFactor=1.10, minNeighbors=5, minSize=(40,40))\n if len(faces) != 1:\n return None\n (x, y, w, h) = faces[0]\n area_proportion = (w*h)/(gray_img.shape[0]*gray_img.shape[1])\n if area_proportion<=0.20:\n return None\n cropped_img = image[y:y+h, x:x+w]\n if dim:\n cropped_img = cv2.resize(cropped_img, dim, interpolation = cv2.INTER_AREA)\n\n return cropped_img\n\ndef create_batch(batch_size, face_dir, face_list, dim = (160, 160)):\n\n \"\"\"\n Functin to create batch of image pairs\n \"\"\"\n postive_size = batch_size//2\n negative_size = batch_size - (batch_size//2)\n max_value = postive_size + negative_size\n X1_positives = np.zeros(shape = (postive_size,dim[0],dim[1], 3), dtype = \"float32\")\n X2_positives = np.zeros(shape = (postive_size,dim[0],dim[1], 3), dtype = \"float32\")\n X1_negatives = np.zeros(shape = (negative_size,dim[0],dim[1], 3), dtype = \"float32\")\n X2_negatives = np.zeros(shape = (negative_size,dim[0],dim[1], 3), dtype = \"float32\")\n\n with progressbar.ProgressBar(max_value=max_value) as bar:\n bar_counter = 0\n counter = 0\n while counter n_outer_step:\n raise ParametersDefinitionError(\n 'Attention, n_outer_step must be strictly positive!')\n\n ### 10% rule\n if not constraints.rule_10_percent:\n # penalty for the 10% rule based on ply count restrictions\n self.penalty_10_pc_switch = False\n # penalty for the 10% rule based on lamination parameter restrictions\n self.penalty_10_lampam_switch = False\n # Coefficient for the 10% rule penalty\n self.coeff_10 = 0\n else:\n # penalty for the 10% rule based on ply count restrictions\n self.penalty_10_pc_switch = penalty_10_pc_switch\n if not isinstance(penalty_10_pc_switch, bool):\n raise ParametersDefinitionError(\"\"\"\nAttention, penalty_10_pc_switch should be a boolean value!\"\"\")\n # penalty for the 10% rule based on lamination parameter restrictions\n self.penalty_10_lampam_switch = penalty_10_lampam_switch\n if not isinstance(penalty_10_lampam_switch, bool):\n raise ParametersDefinitionError(\"\"\"\nAttention, penalty_10_lampam_switch should be a boolean value!\"\"\")\n # Coefficient for the 10% rule penalty\n self.coeff_10 = coeff_10\n if not(isinstance(coeff_10, int) or isinstance(coeff_10, float)):\n raise ParametersDefinitionError(\"\"\"\nAttention, coeff_10 must be a number (float or integer)!\"\"\")\n if coeff_10 < 0:\n raise ParametersDefinitionError(\n'The weight of penalty for the 10% rule must be a positive!')\n self.penalty_10_pc_switch = penalty_10_pc_switch\n constraints.penalty_10_pc_switch = penalty_10_pc_switch\n\n if penalty_10_pc_switch and penalty_10_lampam_switch:\n raise ParametersDefinitionError(\n'You cannot use both penalties on ply counts and on lampam for the 10% rule!')\n\n if not constraints.bal:\n # penalty based on ply counts\n self.penalty_bal_switch = False\n else:\n # penalty based on ply counts\n self.penalty_bal_switch = penalty_bal_switch\n if not isinstance(penalty_bal_switch, bool):\n raise ParametersDefinitionError(\"\"\"\nAttention, penalty_bal_switch should be a boolean value!\"\"\")\n\n if not constraints.ipo:\n # penalty based on lamination parameters\n self.penalty_ipo_switch = False\n # coefficient for the penalty\n self.coeff_bal_ipo = 0\n else:\n # penalty based on lamination parameters\n self.penalty_ipo_switch = penalty_ipo_switch\n if not isinstance(penalty_ipo_switch, bool):\n raise ParametersDefinitionError(\"\"\"\nAttention, penalty_ipo_switch should be a boolean value!\"\"\")\n # coefficient for the penalty\n self.coeff_bal_ipo = coeff_bal_ipo\n if not(isinstance(coeff_bal_ipo, int) \\\n or isinstance(coeff_bal_ipo, float)):\n raise ParametersDefinitionError(\"\"\"\nAttention, coeff_bal_ipo must be a number (float or integer)!\"\"\")\n if coeff_bal_ipo < 0:\n raise ParametersDefinitionError(\n'The weight of penalty for in-plane orthotropy must be a positive!')\n\n if penalty_ipo_switch and penalty_bal_switch:\n raise ParametersDefinitionError(\n'You cannot use both the penalties for balance and in-plane orthotropy!')\n\n ### out-of-plane orthotropy\n if not constraints.oopo:\n # coefficient for the penalty based on lamination parameters\n self.coeff_oopo = 0\n else:\n # coefficient for the penalty based on lamination parameters\n self.coeff_oopo = coeff_oopo\n if not(isinstance(coeff_oopo, int) \\\n or isinstance(coeff_oopo, float)):\n raise ParametersDefinitionError(\"\"\"\nAttention, coeff_oopo must be a number (float or integer)!\"\"\")\n if coeff_oopo < 0:\n raise ParametersDefinitionError(\n'The weight of penalty for out-of-plane orthotropy must be a positive!')\n\n ### repair to improve the convergence of in-plane lamination parameters\n # and of out-of-plane lamination parameters\n self.repair_membrane_switch = repair_membrane_switch\n if not isinstance(repair_membrane_switch, bool):\n raise ParametersDefinitionError(\"\"\"\nAttention, repair_membrane_switch should be a boolean value!\"\"\")\n self.repair_flexural_switch = repair_flexural_switch\n if not isinstance(repair_flexural_switch, bool):\n raise ParametersDefinitionError(\"\"\"\nAttention, repair_flexural_switch should be a boolean value!\"\"\")\n\n # coefficient for the proportion of the laminate thickness that can be\n # modified during the refinement for membrane properties in the repair\n # process\n self.p_A \\\n = p_A\n if not isinstance(p_A, (float, int)):\n raise ParametersDefinitionError(\"\"\"\nAttention, p_A should have a numeric value!\"\"\")\n if not (0 <= p_A <= 100):\n raise ParametersDefinitionError(\"\"\"\nAttention, p_A must be between 0 and 100!\"\"\")\n\n # n_D1: number of plies in the last permutation\n # during repair for disorientation and/or contiguity\n self.n_D1 = n_D1\n if not isinstance(n_D1, int):\n raise ParametersDefinitionError(\"\"\"\nAttention, n_D1 must be an integer!\"\"\")\n\n # n_D2: number of ply shifts tested at each step of the\n # re-designing process during refinement of flexural properties\n self.n_D2 = n_D2\n if not isinstance(n_D2, int):\n raise ParametersDefinitionError(\"\"\"\nAttention, n_D2 must be an integer!\"\"\")\n\n # n_D3: number of times the algorithms 1 and 2 are repeated during the\n # flexural property refinement\n self.n_D3 = n_D3\n if not isinstance(n_D3, int):\n raise ParametersDefinitionError(\"\"\"\nAttention, n_D2 must be an integer!\"\"\")\n\n ### size of the groups\n # desired group size for smaller groups\n self.group_size_min = np.around(group_size_min)\n if not(isinstance(group_size_min, int)):\n raise ParametersDefinitionError(\n'Attention, group_size_min must be an integer!')\n if group_size_min < 1:\n raise ParametersDefinitionError(\n'Attention, group_size_min must be strictly positive!')\n if group_size_min < constraints.n_contig:\n raise ParametersDefinitionError(\n'Attention, group_size_min must be at least equal to n_contiguity!')\n # maximum number of plies per group for each outer loop of LAYLA\n if isinstance(group_size_max, int):\n group_size_max = group_size_max*np.ones((n_outer_step,))\n self.group_size_max = group_size_max.astype(int)\n for el in group_size_max:\n if group_size_min > el:\n raise ParametersDefinitionError(\n'Attention, group_size_min must smaller than group_size_max!')\n if group_size_max.size < n_outer_step:\n raise ParametersDefinitionError('''\nAttention, the vector group_size_max should have as many elements as the\nnumber of outer loops in LAYLA!''')\n\n # Branching limit for global pruning during ply orientation\n # optimisation\n self.global_node_limit = np.around(global_node_limit)\n if not isinstance(global_node_limit, int):\n raise ParametersDefinitionError(\"\"\"\nAttention, global_node_limit must be an integer!\"\"\")\n if global_node_limit < 1:\n raise ParametersDefinitionError(\"\"\"\nAttention, global_node_limit must be strictly positive!\"\"\")\n\n # Branching limit for global pruning at the penultimate level during\n # ply orientation optimisation\n self.global_node_limit_p = np.around(global_node_limit_p)\n if not isinstance(global_node_limit_p, int):\n raise ParametersDefinitionError(\"\"\"\nAttention, global_node_limit_p must be an integer!\"\"\")\n if global_node_limit_p < 1:\n raise ParametersDefinitionError(\"\"\"\nAttention, global_node_limit_p must be strictly positive!\"\"\")\n\n # Branching limit for local pruning during ply orientation\n # optimisation\n self.local_node_limit = np.around(local_node_limit)\n if not isinstance(local_node_limit, int):\n raise ParametersDefinitionError(\"\"\"\nAttention, local_node_limit must be an integer!\"\"\")\n if local_node_limit < 1:\n raise ParametersDefinitionError(\"\"\"\nAttention, local_node_limit must be strictly positive!\"\"\")\n\n # Lamination parameters sensitivities from the first-lebel optimiser\n if not(isinstance(first_level_sensitivities, np.ndarray)) \\\n and first_level_sensitivities.size == 12 \\\n and first_level_sensitivities.dtype == float:\n raise ParametersDefinitionError(\"\"\"\nAttention, first_level_sensitivities must be a vector with 12 float components!\n\"\"\")\n if [False for elem in first_level_sensitivities if elem < 0]:\n raise ParametersDefinitionError(\"\"\"\nAttention, the elements of first_level_sensitivities must be positive!\n\"\"\")\n self.first_level_sensitivities = first_level_sensitivities\n\n # Lamination parameters to be considered in the multi-objective\n # functions\n if not(isinstance(lampam_to_be_optimised, np.ndarray)) \\\n and lampam_to_be_optimised.size == 12 \\\n and lampam_to_be_optimised.dtype == float:\n raise ParametersDefinitionError(\"\"\"\nAttention, lampam_to_be_optimised must be a vector with 12 float components!\n\"\"\")\n if [False for elem in lampam_to_be_optimised if elem not in (0,1)]:\n raise ParametersDefinitionError(\"\"\"\nAttention, the elements of lampam_to_be_optimised must be either 0 or 1!\n\"\"\")\n self.lampam_to_be_optimised = lampam_to_be_optimised\n\n # calculation of the multi-objective function lamination parameter\n # weightings\n (self.lampam_weightings_final, self.lampam_weightings_ini) \\\n = self.weights_calculation(\n self.first_level_sensitivities,\n self.lampam_to_be_optimised, constraints,\n self.coeff_bal_ipo, self.coeff_oopo)\n\n if np.isclose(self.lampam_weightings_final[0:4],\n np.array([0, 0, 0, 0], float)).all():\n self.weighting_finalA = self.lampam_weightings_final[0:4]\n else:\n self.weighting_finalA = self.lampam_weightings_final[0:4] / sum(\n self.lampam_weightings_final[0:4])\n\n if np.isclose(self.lampam_weightings_final[8:12],\n np.array([0, 0, 0, 0], float)).all():\n self.weighting_finalD = self.lampam_weightings_final[8:12]\n else:\n self.weighting_finalD = self.lampam_weightings_final[8:12] / sum(\n self.lampam_weightings_final[8:12])\n\n\n def weights_calculation(\n self, first_level_sensitivities, lampam_to_be_optimised,\n constraints, coeff_bal_ipo, coeff_oopo):\n '''\n Calculation of the objective function lamination parameter weightings\n '''\n sensitivities = first_level_sensitivities * lampam_to_be_optimised\n if sum(sensitivities) == 0:\n raise ParametersDefinitionError(\n'Attention, objective function lamination parameter weightings are all 0s!')\n sensitivities = sensitivities / sum(sensitivities)\n lampam_weightings_ini = np.copy(sensitivities)\n# print('sensitivities', sensitivities)\n\n # Filtering zero lamination parameter weightings\n opti_sensitivities = np.ones(12)\n if constraints.sym:\n opti_sensitivities[4:8] = 0\n if set(constraints.set_of_angles) == set([0, 45, -45, 90]):\n opti_sensitivities[3]= 0\n opti_sensitivities[7]= 0\n opti_sensitivities[11]= 0\n # wlevel1 * wlevel2\n sensitivities = sensitivities * opti_sensitivities\n# print('sensitivities', sensitivities)\n\n # in-plane and out-of-plane orthotropy requirements\n if constraints.ipo:\n sensitivities[2] = 0\n sensitivities[3] = 0\n if constraints.oopo :\n sensitivities[10] = 0\n sensitivities[11] = 0\n s = np.average(sensitivities[sensitivities != 0])\n\n if constraints.ipo and self.penalty_ipo_switch and constraints.oopo:\n if set(constraints.set_of_angles) == set([0, 45, -45, 90]):\n sensitivities[2] = s*coeff_bal_ipo\n sensitivities[10] = s*coeff_oopo\n else:\n sensitivities[2] = s*coeff_bal_ipo\n sensitivities[3] = s*coeff_bal_ipo\n sensitivities[10] = s*coeff_oopo\n sensitivities[11] = s*coeff_oopo\n elif constraints.ipo and self.penalty_ipo_switch:\n if set(constraints.set_of_angles) == set([0, 45, -45, 90]):\n sensitivities[2] = s*coeff_bal_ipo\n sensitivities[10] = s*coeff_oopo\n else:\n sensitivities[2] = s*coeff_bal_ipo\n sensitivities[3] = s*coeff_bal_ipo\n elif constraints.oopo:\n if set(constraints.set_of_angles) == set([0, 45, -45, 90]):\n sensitivities[10] = s*coeff_oopo\n else:\n sensitivities[10] = s*coeff_oopo\n sensitivities[11] = s*coeff_oopo\n# print('sensitivities', sensitivities)\n\n return sensitivities/np.sum(sensitivities), lampam_weightings_ini\n\n\n def __repr__(self):\n \" Display object \"\n\n return (f\"\"\"\nOptimiser parameters:\n\n Minimum size for the groups of plies: {self.group_size_min}\n Maximum size for the groups of plies: {self.group_size_max}\n Number of outer steps: {self.n_outer_step}\n Repair for in-plane lamination parameter convergence: {self.repair_membrane_switch}\n Repair for out-of-plane lamination parameter convergence: {self.repair_flexural_switch}\n Penalty for the 10% rule (on ply counts): {self.penalty_10_pc_switch}\n Penalty for the 10% rule (on lampams): {self.penalty_10_lampam_switch}\n Penalty for balance: {self.penalty_bal_switch}\n Penalty for in-plane orthotropy: {self.penalty_ipo_switch}\n Coefficient for the penalty for the 10\\% rule: {self.coeff_10}\n Coefficient for the penalty for in-plane orthotropy or balance: {self.coeff_bal_ipo}\n Coefficient for the penalty for out-of-plane orthotropy: {self.coeff_oopo}\n Percent_thickness_repair_membrane: {self.p_A}%\n N_plies_last_permut_diso_contig: {self.n_D1}\n N_shifts_tested_flexural_repair: {self.n_D2}\n N_repeat_flexural_repair: {self.n_D3}\n In-plane orthotropy threshold: {self.threshold_ipo}\n Out-of-plane orthotropy threshold: {self.threshold_oopo}\n Type of objective function: norm {self.type_obj_func}\n Branching limits:\n - for global pruning during ply orientation optimisation: {self.global_node_limit}\n - for global pruning at the last level of ply orientation optimisation: {self.global_node_limit_p}\n - for local pruning during ply orientation optimisation: {self.local_node_limit}\n In-plane orthotropy threshold: {self.threshold_ipo}\n Lampam_weightings_final:\n A: {self.lampam_weightings_final[0]:.2f} {self.lampam_weightings_final[1]:.2f} {self.lampam_weightings_final[2]:.2f} {self.lampam_weightings_final[3]:.2f}\n B: {self.lampam_weightings_final[4]:.2f} {self.lampam_weightings_final[5]:.2f} {self.lampam_weightings_final[6]:.2f} {self.lampam_weightings_final[7]:.2f}\n D: {self.lampam_weightings_final[8]:.2f} {self.lampam_weightings_final[9]:.2f} {self.lampam_weightings_final[10]:.2f} {self.lampam_weightings_final[11]:.2f}\n \"\"\")\n\nclass ParametersDefinitionError(Exception):\n pass\n\nif __name__ == \"__main__\":\n constraints = Constraints(\n sym=True,\n bal=True,\n ipo=True,\n dam_tol=False,\n rule_10_percent=True,\n diso=True,\n contig=True,\n delta_angle=45,\n n_contig=5,\n percent_0=10,\n percent_45=10,\n percent_90=10,\n percent_135=10,\n set_of_angles=[0, 45, -45, 90])\n parameters = Parameters(\n constraints=constraints,\n first_level_sensitivities = np.array([\n 8, 4, 2, 1, 0, 12, 0, 13, 0, 0, 0, 0]),\n lampam_to_be_optimised=np.array([\n 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]))\n print(parameters)","sub_path":"src/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":18239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"558716397","text":"\"\"\"Python booleans\"\"\"\nimport ast\n\nimport typy\nimport typy.util as _util\nimport typy.util.astx as astx\n\nimport _errors\n\nclass boolean_(typy.Type):\n @classmethod\n def init_idx(cls, idx):\n if idx != ():\n raise typy.TypeFormationError(\"Index of boolean type must be ().\")\n return idx\n\n @classmethod\n def init_inc_idx(cls, inc_idx):\n if inc_idx != () and inc_idx != Ellipsis:\n raise typy.TypeFormationError(\n \"Incomplete index of boolean type must be () or Ellipsis.\")\n return inc_idx\n\n def anon_to_str(self):\n return \"boolean\"\n\n def ana_Name_constructor(self, ctx, e):\n id = e.id\n if id != \"True\" and id != \"False\":\n raise _errors.TyError(\n \"Must introduce a value of boolean type with either True or False.\",\n e)\n\n @classmethod\n def syn_idx_Name_constructor(cls, ctx, e, inc_idx):\n id = e.id\n if id != \"True\" and id != \"False\":\n raise _errors.TyError(\n \"Must introduce a value of boolean type with either True or False.\",\n e)\n return ()\n\n def translate_Name_constructor(self, ctx, e):\n return astx.copy_node(e)\n\n def syn_UnaryOp(self, ctx, e):\n if isinstance(e.op, ast.Not):\n return self\n else:\n raise _errors.TyError(\n \"\"\"Type bool does not support this unary operator.\"\"\",\n e)\n\n def translate_UnaryOp(self, ctx, e):\n translation = astx.copy_node(e)\n translation.operand = ctx.translate(e.operand)\n return translation\n\n def syn_Compare(self, ctx, e):\n left, ops, comparators = e.left, e.ops, e.comparators\n for op in ops:\n if not isinstance(op, (ast.Eq, ast.NotEq, ast.Is, ast.IsNot)):\n raise _errors.TyError(\"Type bool does not support this operator.\", op)\n for e_ in _util.tpl_cons(left, comparators):\n if hasattr(e_, 'match'): \n continue # already synthesized\n ctx.ana(e_, self)\n return self\n\n def translate_Compare(self, ctx, e):\n translation = astx.copy_node(e)\n translation.left = ctx.translate(e.left)\n translation.comparators = (\n ctx.translate(comparator)\n for comparator in e.comparators)\n return translation\n\n def syn_BoolOp(self, ctx, e):\n values = e.values\n for value in values:\n ctx.ana(value, self)\n return self\n\n def translate_BoolOp(self, ctx, e):\n translation = astx.copy_node(e)\n translation.values = tuple(\n ctx.translate(value)\n for value in e.values)\n return translation\n\n def ana_pat_Name_constructor(self, ctx, pat):\n id = pat.id\n if id != \"True\" and id != \"False\":\n raise _errors.TyError(\"Boolean values only match 'True' and 'False'\")\n return typy.odict()\n\n def translate_pat_Name_constructor(self, ctx, pat, scrutinee):\n id = pat.id\n if id == \"True\":\n return (scrutinee, typy.odict())\n elif id == \"False\":\n return (ast.UnaryOp(op=ast.Not(), operand=scrutinee), typy.odict())\n\nboolean = boolean_[()]\n\n","sub_path":"tydy/core/_boolean.py","file_name":"_boolean.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"498066524","text":"#\n# Copyright 2020 University of Toronto\n#\n# Permission is hereby granted, to use this software and associated\n# documentation files (the \"Software\") in course work at the University\n# of Toronto, or for personal use. Other uses are prohibited, in\n# particular the distribution of the Software either publicly or to third\n# parties.\n#\n# The above copyright notice and this permission notice shall be included in\n# all 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\nfrom random import expovariate, seed\nfrom collections import deque\n\n__all__ = ['StationMetadata', 'FrameMetadata', 'StationArrivals']\n\nclass StationArrivals(object):\n \"\"\"\n This class generates a list of frame arrival times for a set of stations.\n The initial arrival pattern is generated by using exponential inter-arrival\n times, but we ensure the frames are separated by at a time length of at\n least 1 serializationDelay. This models the stations with no buffers.\n \"\"\"\n\n def __init__(self, numStations = None, numFramesPerStn = None,\n serializationDelay = None, arrivalRate = None, seedVal = -1):\n assert type(numStations) is int and numStations > 0\n assert type(numFramesPerStn) is int and numFramesPerStn > 0\n assert type(serializationDelay) is float and serializationDelay > 0\n assert type(arrivalRate) is float and arrivalRate > 0\n\n self.numStations = numStations\n self.numFramesPerStn = numFramesPerStn\n self.serializationDelay = serializationDelay\n self.arrivalRate = arrivalRate\n\n if seedVal >= 0:\n seed(seedVal)\n\n # Dict of Deques\n # - Key is station ID\n # - Value is a Deque of packet arrival times\n self.stnPktArrTimes = self._generateArrivals()\n\n def _generateArrivals(self):\n \"\"\"\n Generates a list of arrival times for all stations\n \"\"\"\n\n packetArrivals = {}\n for stnID in range(self.numStations):\n arrTimes = [0.0] * self.numFramesPerStn\n for i in range(self.numFramesPerStn):\n # Since we assume there's no buffering at stations, transmissions must\n # be at least 1 SERIALIZATION_DELAY apart\n interArrivalTime = 0\n while (interArrivalTime < self.serializationDelay):\n interArrivalTime = expovariate(self.arrivalRate)\n\n arrTimes[i] = arrTimes[i - 1] + interArrivalTime\n\n # Convert to deque here, rather than at the start, since insertion/modification in\n # the middle of a deque is extremely slow (under-the-hood, it's a linked of arrays)\n packetArrivals[stnID] = deque(arrTimes)\n\n return packetArrivals\n\n def getNextArrival(self):\n \"\"\"\n Returns a FrameMetadata object representing the next scheduled arrival.\n Returns None if all stations have completed all their transmissions.\n \"\"\"\n\n # Figure out which station has the next earliest arrival\n stationID = None\n minTime = float('inf')\n for stnID in range(self.numStations):\n if len(self.stnPktArrTimes[stnID]) == 0:\n # This station has transmitted all its frames\n continue\n\n if self.stnPktArrTimes[stnID][0] < minTime:\n stationID = stnID\n minTime = self.stnPktArrTimes[stnID][0]\n\n if stationID is None:\n # Simulation is done, no more frames\n return stationID\n\n # Get packet from that arrival, pop it from the deque\n # Return it in a FrameMetadata object\n return FrameMetadata(stationID, self.stnPktArrTimes[stationID].popleft())\n\n def rescheduleFrame(self, frameMeta):\n \"\"\"\n Reschedules a frame for later by appending a new arrival at the end\n of the station's list of arrival.\n \"\"\"\n\n assert type(frameMeta) is FrameMetadata\n stnID = frameMeta.stnID\n arrTime = frameMeta.arrTime\n\n assert type(stnID) is int and stnID < self.numStations\n assert type(arrTime) is float and arrTime >= 0\n\n # Calculate new arrival time\n interArrivalTime = 0\n while (interArrivalTime < self.serializationDelay):\n interArrivalTime = expovariate(self.arrivalRate)\n\n if len(self.stnPktArrTimes[stnID]) > 0:\n lastArrTime = self.stnPktArrTimes[stnID][-1]\n else:\n lastArrTime = arrTime\n\n self.stnPktArrTimes[stnID].append(interArrivalTime + lastArrTime)\n\n\nclass FrameMetadata(object):\n \"\"\"\n This class holds metadata for each frame\n - stnID: Identifier of theh station that sends this frame\n - arrTime: Time at which the station generates/transmits the frame\n \"\"\"\n\n def __init__(self, stnID, arrTime):\n assert type(stnID) is int\n assert type(arrTime) is float and arrTime >= 0\n self.stnID = stnID\n self.arrTime = arrTime\n\n# NOTE (2020s): Currently this class is unused, leave here for future semesters\nclass StationMetadata(object):\n \"\"\"\n This class holds metadata for each station\n - stnID: Station identifier\n - successTx: A counter to track the perceived successful transmissions\n A station can think it successfully transmitted a frame,\n even when that frame collided.\n - reschedCount: A counter to track the number of times this station had\n to defer transmission and reschedule a frame\n \"\"\"\n\n def __init__(self, stnID):\n assert type(stnID) is int\n self.stnID = stnID\n\n # The successTx counter tracks the number of successful transmissions\n # from the *point-of-view of this station*. If a frame collides\n # and the station does not realize it in time, it may inadvertently\n # believe it was successful.\n self.successTx = 0\n\n # The number of re-scheduling events\n self.reschedCount = 0\n\n","sub_path":"lab4/.venv/site-packages/ece361/lab4.py","file_name":"lab4.py","file_ext":"py","file_size_in_byte":6441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"124730613","text":"\"\"\"Interface to MySQL database.\n\n\"\"\"\n\nfrom collections.abc import Iterable\nimport os\n# import sys\n# from pathlib import Path\n# sys.path.append(fr'{os.path.dirname(__file__)}/util')\n\nfrom collections.abc import Iterable\nimport csv\nimport random\nimport sys\nimport mysql.connector as connector\nimport logging\nimport re\nimport time\nfrom timer import timer\n\nfrom comparison_rpt import ElectionRpt\nimport GLB_globs\nGLB = GLB_globs.GLB_globs()\n\nRETRY_MAX = 5\n\nclass DBerror(IOError):\n \"\"\"Error raised by the dbase module.\"\"\"\n ...\n\nclass TransactionError(DBerror):\n def __init__(self, message):\n self.message = message\n\ndef flatten_sql(s):\n return re.sub(r'\\s+', ' ', s)\n\n\n\n# passwords are buried here rather than being in the .ini file --\n# somewhat pointless, I know\n\ndbconfig = {\n \"user\": \"etp\",\n \"password\": \"Hetp2020\",\n \"database\": \"HETP\"\n}\ntest_dbconfig = {\n \"user\": \"tevs\",\n \"password\": \"tevs\",\n \"database\": \"HETPtesting\"\n}\n\n# todo: polishing: should be an enum for testing or production rather then sloppy strings\n\nclass ETPdb():\n \"\"\"Interface to MySQL database.\n\n As a general rule, rows are returned as namedtuples.\"\"\"\n\n def __init__(self):\n ...\n\n def connect(self, db_choice, autocommit=True):\n \"\"\"Create connection.\n\n db_choice says whether to use the test or production database.\"\"\"\n\n if db_choice == 'testing':\n db_credentials = test_dbconfig\n elif db_choice == 'production':\n db_credentials = dbconfig\n else:\n assert False, f'unknown database choice: \"{db_choice}\"'\n\n self.cnx = connector.connect(**db_credentials)\n autoc = 'ON' if autocommit else 'OFF'\n sql = f'SET AUTOCOMMIT = {autoc}'\n self.exe(sql)\n logging.info(f'db: {db_choice}; {flatten_sql(sql)}')\n self.in_transaction = False\n\n\n # ------------------------------- Server interactions -------------------------------\n\n def exe(self, sql, indata=None, multi=False):\n \"\"\"Execute sql with no return values..\"\"\"\n\n logging.debug(flatten_sql(sql))\n if indata:\n logging.debug(indata)\n cursor = self.cnx.cursor(named_tuple=True)\n if indata:\n ret = cursor.execute(sql, indata, multi)\n else:\n ret = cursor.execute(sql)\n cursor.close()\n return ret\n\n def exe_many(self, sql, indata):\n \"\"\"Execute sql indata and commit.\"\"\"\n\n logging.debug(flatten_sql(sql))\n logging.debug(indata)\n cursor = self.cnx.cursor(named_tuple=True)\n ret = cursor.executemany(sql, indata)\n cursor.close()\n return ret\n\n def tx_commit(self):\n \"\"\"commit the current connection if really is true\"\"\"\n\n logging.debug('COMMIT')\n if self.in_transaction:\n self.cnx.commit()\n self.in_transaction = False\n\n else:\n raise TransactionError(\"Commit not in transaction.\")\n\n def tx_rollback(self):\n \"\"\"Roll back the current connection if really is true\"\"\"\n\n logging.debug('ROLLBACK')\n if self.in_transaction:\n self.cnx.rollback()\n self.in_transaction = False\n\n else:\n raise TransactionError(\"Rollback not in transaction.\")\n\n def tx_start(self):\n\n logging.debug('START TX')\n if self.in_transaction:\n raise TransactionError(\"start transaction within transaction\")\n self.exe('START TRANSACTION')\n self.in_transaction = True\n\n def retrieve(self, sql):\n \"\"\"Execute sql and return list of dicts.\"\"\"\n\n logging.debug(flatten_sql(sql))\n cursor = self.cnx.cursor()\n try:\n cursor.execute(sql)\n except Exception as e:\n print(f'exception in retireve{e}, sql={sql}')\n raise e\n res = cursor.fetchall()\n cursor.close()\n return res\n\n def retrieve_named_tuples(self, sql:str): # Todo: convert retrieve and eliminate this\n return self.retrieve_many(sql)\n\n def retrieve_many(self, sql, params=None, style='tuple')->list:\n \"\"\"Execute sql to retrieve many rows. Style indicates\n the type of objects in which to return the rows.\"\"\"\n\n logging.debug(flatten_sql(sql))\n if style == 'tuple':\n cursor = self.cnx.cursor(named_tuple=True)\n elif style =='dict':\n cursor = self.cnx.cursor(dictionary=True)\n else:\n assert False, f\"'{style}' not a recognized cursor type\"\n\n try:\n cursor.execute(sql, params=params)\n except Exception as e:\n print(f'exception in retrieve{e}, sql={sql}')\n raise e\n res = cursor.fetchall()\n cursor.close()\n return res\n\n def _prepare_column_map(self, column_map):\n \"\"\"Unpack shorthand for tansfers between an\n object and a database row.\n\n Column_map is a strings of the form\n \"obj column name 1:table column name 1\\n\n dct column name 2:table column nam 2\n ...\n\"\"\"\n cm = column_map.split('\\n')\n if cm[-1] == '': del cm[-1]\n obj_cols = list()\n db_cols = list()\n for line in cm:\n try:\n dct_name, dbname = line.split(':')\n except ValueError:\n dct_name = dbname = line\n\n obj_cols.append(dct_name.strip())\n db_cols.append(dbname.strip())\n\n return obj_cols, db_cols\n\n def _make_insert_sql_from_columnmap(self, table_name: str, cols: list):\n sql_colnames = ', '.join(cols)\n placeholders = ', '.join('%s' for x in cols)\n return f\"\"\"INSERT IGNORE INTO {table_name} ({sql_colnames}) \n VALUES ({placeholders})\"\"\"\n\n def insert_contests_for_tabulation(self, dicts:list[dict]):\n \"\"\"Insert image rows from multiple dicts.\n\n Dicts may not have all columns needed for insert.\"\"\"\n\n ld = dicts.copy() # avoid creating side effect\n if type(ld) == dict:\n ld = (ld,)\n\n sql = \"\"\"INSERT INTO img_contest(\n sub_id,\n image_number,\n contest_name,\n overvoted,\n undervoted,\n validcount,\n votes_allowed,\n underthreshold,\n tot_scores,\n overvoted_by_pct,\n undervoted_by_pct,\n suspicion_by_pct,\n found)\n VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\"\"\n\n value_rows = []\n for d in ld:\n # set default values for missing columns\n value_row = []\n for c in ('sub_id',\n 'image_number',\n 'contest_name',\n 'overvoted',\n 'undervoted',\n 'validcount',\n 'votes_allowed',\n 'underthreshold',\n 'tot_scores',\n 'overvoted_by_pct',\n 'undervoted_by_pct',\n 'suspicion_by_pct',\n 'found'):\n value_row.append(d.get(c, None)) # default values\n value_rows.append(value_row)\n\n self.exe_many(sql, value_rows)\n\n def insert_choices_for_tabulation(self, dicts:list[dict]):\n \"\"\"Insert image rows from multiple dicts.\n\n Dicts may not have all columns needed for insert.\"\"\"\n\n ld = dicts.copy() # avoid creating side effect\n if type(ld) == dict:\n ld = (ld,)\n\n sql = \"\"\"INSERT INTO img_choice\n (id,\n image_number,\n img_contest_subid,\n choice_name,\n score,\n comment,\n marked,\n marked_by_pct,\n upper_threshold,\n location_ulcx,\n location_ulcy,\n location_lrcx,\n location_lrcy,\n lower_threshold)\n VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)\"\"\"\n\n value_rows = []\n for d in ld:\n # set default values for missing columns\n value_row = []\n for c in ( 'id',\n 'image_number',\n 'img_contest_subid',\n 'choice_name',\n 'score',\n 'comment',\n 'marked',\n 'marked_by_pct',\n 'upper_threshold',\n 'location_ulcx',\n 'location_ulcy',\n 'location_lrcx',\n 'location_lrcy',\n 'lower_threshold'):\n value_row.append(d.get(c, None)) # default values\n value_rows.append(value_row)\n\n self.exe_many(sql, value_rows)\n\n def update_images_for_tabulation(self, dicts):\n \"\"\"Update selected columns image rows.\n\n Columns not present in the dict will receive\n a null value.\"\"\"\n\n d = dicts.copy() # avoid creating side effect\n assert d['image_number'] is not None\n for c in ('undecodable_reason',\n 'date_time_tabulated',\n 'H_matrix',\n 'processing_success',\n 'flipped_form'):\n d[c] = d.get(c, None) # default values\n\n # fudge to get a real Null in the database\n if d['H_matrix'] == 'null':\n d['H_matrix'] = None\n\n sql = '''UPDATE images\n SET undecodable_reason=%s,\n processing_comment=%s,\n date_time_tabulated=%s,\n H_matrix=%s,\n processing_success=%s,\n flipped_form=%s,\n assigned_to_pid=NULL\n WHERE image_number=%s'''\n data = (d['undecodable_reason'],\n d['processing_comment'],\n d['date_time_tabulated'],\n d['H_matrix'],\n d['processing_success'],\n d['flipped_form'],\n d['image_number'])\n self.exe(sql, data)\n\n def update_from_dict(self, table_name: str, keys: list[str],\n vals:dict):\n \"\"\"Create and execute an ypdate statenent,.\n Keys must be in vals.\"\"\"\n\n vd = (vals).copy() # avoid side effect\n if type(keys) == str:\n keys=(keys,)\n\n nullfix = lambda z: repr(z) if z is not None else 'Null'\n # create pairs for the WHERE clause\n keyvals = list()\n for key in keys:\n keyval = repr(vd.pop(key))\n keyvals.append(f'{key}={keyval}')\n\n where_pairs = ' AND '.join(keyvals)\n\n # create the assignments for SET\n assg_list = ', '.join(\n [f'{x} = {nullfix(y)}' for x, y in vd.items()])\n\n sql = f\"\"\"UPDATE {table_name} SET {assg_list}\n WHERE {where_pairs}\"\"\"\n return self.exe(sql)\n\n def insert_from_dataframe(self, table_name, column_map, df):\n \"\"\"Construct and execute sql to insert into table_name data\n from selected columns of df.\"\"\"\n\n dfcols, dbcols = self._prepare_column_map(column_map)\n\n reduced_df = df[dfcols]\n reduced_df = reduced_df.where(df.notnull(), None)\n data = reduced_df.values.tolist()\n\n sql = self._make_insert_sql_from_columnmap(table_name, dbcols)\n return self.exe_many(sql, data)\n\n\n\n\n # ----------------------------- Application services ----------------------------\n\n def add_all_elec_results(self, results_df):\n \"\"\"Populate the elec_results table with the pandas dataframe results_df\"\"\"\n\n try:\n self.exe(\"TRUNCATE elec_results\")\n column_map = \\\n \"\"\"Precinct:pct\n Ballots Cast:ballots_cast\n Contest Title:contest\n Choice Name:choice\n Total Votes:num_votes\n Total Overvotes:num_overvotes\n Total Undervotes:num_undervotes\n Total Invalid Votes:num_invalids\"\"\"\n\n # commit comes here\n return self.insert_from_dataframe('elec_results',\n column_map, results_df)\n\n except Exception as e:\n logging.exception('Unable to add all election results')\n return\n\n def add_image_nums(self, elections_batch_num:str,\n image_nums):\n \"\"\"Add a new row to Images with only the image_number and elections_batch_num.\n\n elections_batch_num: str\n image_nums: int, str or iterable of ints and strs\"\"\"\n\n if not isinstance(image_nums, Iterable):\n image_nums = (image_nums,)\n data = list()\n for item in image_nums: data.append((int(item), elections_batch_num))\n sql = \"\"\"INSERT INTO Images (image_number, elections_batch_num) VALUES (%s, %s)\"\"\"\n r = None\n try:\n r = self.exe_many(sql, data)\n except Exception as e:\n print('error exception:', e)\n return r\n\n def add_images(self, data:list):\n \"\"\"Insert images into table.\n\n Call with data as a list of tuples\n (image number, precinct, page_number, elections_batch_num, ETP_batch_num\"\"\"\n\n sql = \"\"\"INSERT INTO Images \n (image_number, precinct, page_number, elections_batch_num, ETP_batch_num) \n VALUES (%s, %s, %s, %s, %s)\"\"\"\n return self.exe_many(sql, data)\n\n def accept_tabulation(self, image:dict,\n contests: list[dict], choices: list[dict]):\n \"\"\"Update an image row and insert contest and choices.\"\"\"\n\n num_tries = 0\n while num_tries < RETRY_MAX:\n self.tx_start()\n try:\n self.update_images_for_tabulation(image)\n # delete before insert to maintain idempotence\n self.exe(f'''DELETE FROM img_contest\n WHERE image_number = %s''',\n (image['image_number'],))\n self.exe(f'''DELETE FROM img_choice\n WHERE image_number = %s''',\n (image['image_number'],))\n\n self.insert_contests_for_tabulation(contests)\n self.insert_choices_for_tabulation(choices)\n self.tx_commit()\n break # successful execution\n\n except connector.errors.InternalError as e:\n # 213 (40001): Deadlock found when trying to get lock; try restarting transaction\n print(f'{os.getpid()} deadlock numtries={num_tries}',\n file=sys.stderr)\n # logging.exception(e)\n logging.error(f'Retrying after deadlock {num_tries}; {str(e)}')\n self.tx_rollback()\n time.sleep(random.random()/4)\n num_tries += 1\n\n except Exception as e:\n print(repr(e))\n logging.exception(e)\n self.tx_rollback()\n raise e\n\n def delete_images(self, data):\n \"\"\"Delete a list of images from the table.\n\n data: an interable of image_number\"\"\"\n\n if not isinstance(data, Iterable):\n data = (data,)\n d = tuple(data)\n num_list = ','.join((str(x) for x in d))\n sql = f\"\"\"DELETE from Images WHERE image_number in ({num_list})\"\"\"\n r = None\n try:\n r = self.exe(sql)\n except Exception as e:\n r = e\n print('error exception in connector:', e, file=sys.stderr)\n return r\n\n def fix_orphaned_rows(self):\n \"\"\"Abnormal shutdown scenarios can leave rows checked out for get_images_for_barcode(). Run\n this once when nothing else is accessing the database to reset those rows.\"\"\"\n\n sql = f'''UPDATE Images SET assigned_to_pid = NULL\n WHERE assigned_to_pid IS NOT NULL'''\n # sql = f'''UPDATE Images SET assigned_to_pid = NULL\n # WHERE assigned_to_pid IS NOT NULL AND precinct IS NULL'''\n\n return self.exe(sql)\n\n def get_barcodes(self):\n \"\"\"Return the known barcode rows\"\"\"\n\n sql = \"SELECT * FROM precinct\"\n return self.retrieve_named_tuples(sql)\n\n def get_all_image_numbers(self):\n \"\"\"Return all image numbers, not necessarily in order.\"\"\"\n sql = f\"SELECT image_number FROM Images\"\n return self.retrieve(sql)\n\n def get_choices_for_remarking(self, remark_column: str,\n imagnums:tuple=None) -> list:\n \"\"\"Return all choices that have a null in remarked_column\"\"\"\n\n if imagnums and not isinstance(imagnums, Iterable):\n imagnums = (imagnums,)\n\n if imagnums:\n imgnstr = ','.join([str(imn) for imn in imagnums])\n where_clause = f'WHERE ico.image_number IN ({imgnstr})'\n else:\n where_clause = f'WHERE {remark_column} IS NULL'\n\n sql = f\"\"\"SELECT \n max(votes_allowed) votes_allowed, \n SUM(score) tot_scores,\n GROUP_CONCAT(ich.id) choice_ids,\n GROUP_CONCAT(score) scores,\n GROUP_CONCAT(ich.choice_name) choices,\n MAX(ico.contest_name) contest_name, # for debugging\n ico.sub_id cont_subid, \n ich.image_number imgnum\n FROM img_choice ich INNER JOIN img_contest ico\n on ich.image_number = ico.image_number\n and ich.img_contest_subid = ico.sub_id\n {where_clause}\n GROUP BY ich.image_number, ico.sub_id\n ORDER BY ich.image_number, ico.sub_id\"\"\"\n\n return self.retrieve_named_tuples(sql)\n\n\n def get_images(self, iterable):\n \"\"\"Return a list of image IDs\"\"\"\n\n t = tuple(iterable)\n sql = f\"SELECT * FROM Images WHERE image_number IN {str(iterable)}\"\n return self.retrieve(sql)\n\n def get_images_for_barcode(self, pid, num):\n \"\"\"Get rows from Images that need the precinct ID.\n\n To enable parallel processing this finds candidate rows and locks them\n by putting the process ID in assigned_to_pid. Once this is done, parallel\n calls to this routine should skip rows.\"\"\"\n\n # self.retrieve_named_tuples(s) # clear the cursor\n # cursor = self.cnx.cursor(named_tuple=True)\n sql = f'''UPDATE Images SET assigned_to_pid = {pid}\n WHERE assigned_to_pid IS NULL \n AND (precinct IS NULL OR page_number IS NULL)\n LIMIT {num}'''\n\n self.exe(sql)\n sql = f'SELECT * FROM Images WHERE assigned_to_pid = {pid}'\n return self.retrieve_named_tuples(sql)\n\n def get_images_for_tabulation(self, pid:int, quantity:int,\n imgnum:int=None):\n \"\"\"Get rows from Images that need the precinct ID.\n\n To enable parallel processing this finds candidate rows and locks them\n by putting the process ID in assigned_to_pid. Once this is done, parallel\n calls to this routine should skip rows.\n\n If imgnum is present only the row for that image number\n is returned.\"\"\"\n\n if imgnum is not None:\n # For debugging retrieve the specified row even if\n # date_time_tablulated is not null (i.e., reprocess the image\n # if necessary).\n if type(imgnum) is int:\n imgnum = (imgnum,)\n imglist = ','.join([str(x) for x in imgnum])\n sql = f'''UPDATE Images SET assigned_to_pid = {pid}\n WHERE image_number in ({imglist})'''\n\n else:\n sql = f'''UPDATE Images SET assigned_to_pid = {pid}\n WHERE assigned_to_pid IS NULL \n AND date_time_tabulated IS NULL\n LIMIT {quantity}'''\n self.exe(sql)\n sql = f'SELECT image_number, page_number, precinct FROM Images ' \\\n f'WHERE assigned_to_pid = {pid}'\n return self.retrieve_many(sql)\n\n def get_image_nums(self):\n \"\"\"Return the image numbers in Images \"\"\"\n\n sql = \"\"\"SELECT image_number FROM Images\"\"\"\n return self.retrieve_named_tuples(sql)\n\n def get_highest_image_num(self) -> int:\n\n sql = f\"\"\"select max(image_number) from Images\"\"\"\n try:\n x = self.retrieve(sql)\n except Exception as e:\n raise e\n rv = x[0][0]\n if rv is None: rv = -1\n return rv\n\n def get_imgnum_pct(self):\n sql = \"\"\"SELECT image_number, precinct FROM Images\n ORDER BY image_number, precinct\"\"\"\n return self.retrieve_named_tuples(sql)\n\n def get_page_report(self):\n \"\"\"Get the data for the pages report.\"\"\"\n\n sql = \"\"\"drop table if exists temp_counts\"\"\"\n self.exe(sql)\n sql = \"\"\"\n CREATE TABLE temp_counts AS\n select precinct,\n COUNT(if(page_number = '1', 1, NULL)) as page_1,\n COUNT(if(page_number = '2', 1, NULL)) as page_2,\n COUNT(if(page_number = '3', 1, NULL)) as page_3,\n COUNT(if(page_number = '4', 1, NULL)) as page_4,\n COUNT(if(page_number = 'UNK', 1, NULL)) as unrecognized,\n COUNT(if(page_number = 'MSG', 1, NULL)) as other_error,\n COUNT(if(page_number IS NULL, 1, NULL)) as not_processed,\n group_concat(distinct elections_batch_num) as elections_nums\n from Images\n group by precinct\"\"\"\n self.exe(sql)\n\n sql = \"\"\"\n select precinct, page_1, page_2, page_3, page_4,\n unrecognized, other_error, not_processed,\n page_1 + page_2 + page_3 + page_4 +\n unrecognized + other_error + not_processed as total_pages,\n elections_nums\n from temp_counts\n order by precinct;\"\"\"\n return self.retrieve_named_tuples(sql)\n\n def recreate_images(self):\n \"\"\"Drop and redefine the images table.\"\"\"\n\n assert False\n self.exe(\"\"\"DROP TABLE IF EXISTS Images\"\"\")\n self.exe(\"\"\"CREATE TABLE `images` (\n `image_number` mediumint NOT NULL,\n `precinct` varchar(7) DEFAULT NULL,\n `page_number` varchar(3) DEFAULT NULL,\n `elections_batch_num` varchar(6) DEFAULT NULL,\n `ETP_batch_num` varchar(6) DEFAULT NULL,\n `assigned_to_pid` mediumint DEFAULT NULL,\n `barcode` varchar(14) DEFAULT NULL,\n `comments` varchar(254) DEFAULT NULL COMMENT 'Comments should include notations where a row was edited by hand or using an ad hoc program, such as \"2020-11-24 Edited by WR to create precinct and page_number because barcodes obscured.\"',\n `lower_barcode` varchar(14) DEFAULT NULL,\n PRIMARY KEY (`image_number`)\n) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;\n\"\"\")\n\n def report_ballots_by_precinct(self):\n \"\"\"Retrieve data with total row at bottom.\"\"\"\n\n sql = \"\"\"SELECT precinct, count(image_number) as \"images\" \n from images group by precinct\n union select \" TOTAL\", count(image_number) \n from images;\"\"\"\n return self.retrieve_named_tuples(sql)\n\n def report_pages_by_precinct(self):\n sql = \"\"\"select precinct,\n sum(if(page_number = 1, 1, 0)) as \"Page 1\",\n sum(if(page_number = 2, 1, 0)) as \"Page 2\",\n sum(if(page_number = 3, 1, 0)) as \"Page 3\",\n sum(if(page_number = 4, 1, 0)) as \"Page 4\",\n sum(if(page_number = 'UNK', 1, 0)) as \"Unknown\",\n sum(if(page_number in (1, 2, 3, 4, 'UNK'),1,0)) as \"Total\"\n from images\n group by precinct\n union\n select \"TOTAL\",\n sum(if(page_number = 1, 1, 0)) as \"Page 1\",\n sum(if(page_number = 2, 1, 0)) as \"Page 2\",\n sum(if(page_number = 3, 1, 0)) as \"Page 3\",\n sum(if(page_number = 4, 1, 0)) as \"Page 4\",\n sum(if(page_number = 'UNK', 1, 0)) as \"Unknown\",\n sum(if(page_number in (1, 2, 3, 4, 'UNK'),1,0)) as \"Total\"\n from images\n order by precinct;\"\"\"\n\n return self.retrieve_named_tuples(sql)\n\n def report_comparison_newer(self):\n \"\"\"Return two tsv files that compares our counts to election results.\n \n One of them will be post-processed in a spreadsheet for the report.\n The other will be imported back into the database for furhter analysis.\n\n Merge the official results from table elec_results with\n our results grouped by precinct/contest/choice, which\n have been put in table t_our_count.\"\"\"\n\n sql = \"\"\"SELECT * from elec_res_matchable\n ORDER BY pct, contest, choice\"\"\"\n elec_results = self.retrieve_named_tuples(sql)\n\n sql = \"\"\"SELECT * from t_our_count\n ORDER BY precinct, contest_name, choice_name\"\"\"\n our_results = self.retrieve_named_tuples(sql)\n\n rpt = ElectionRpt()\n with open(r'rpts/comparison.tsv', 'w', newline='') as csvfile:\n spamwriter = csv.writer(csvfile, dialect=csv.excel,\n delimiter='\\t')\n spamwriter.writerow(rpt.header_line())\n for oline in rpt.run(elec_results, our_results):\n spamwriter.writerow(oline)\n \n with open(r'rpts/comparison.tsv', 'r', newline='') as tsv_in:\n with open(r'rpts/comparison_db.tsv', 'w', newline='') as tsv_out:\n headings = tsv_in.readline().split('\\t')\n new_headings = []\n for h in headings:\n h = h.replace(' ', '_')\n h = h.replace('.', '')\n h = h.replace('_-_', '_less_')\n h = h.replace('#', 'num')\n h = h.replace('-', '')\n new_headings.append(h)\n tsv_out.write('\\t'.join(new_headings))\n\n # remove blanks lines. If first column is null the\n # line is blank.\n for line in tsv_in.readlines():\n if line[0] != '\\t':\n tsv_out.write(line)\n\n def update_unscanned_images(self, update_data):\n \"\"\"Update the images that were previousy unscanned.\n\n Call with tuples of (precinct, barcode, image_number)\"\"\"\n\n sql = \"UPDATE Images SET precinct = %s, \" \\\n \"barcode = %s, \" \\\n \"assigned_to_pid = NULL, \" \\\n \"lower_barcode = %s, \" \\\n \"page_number = %s \" \\\n \"WHERE image_number = %s\"\n self.exe_many(sql, update_data)\n\n def clear_recorded_votes(self):\n \"\"\"Prepare to start over recording votes. Does not\n reset barcode evaluation.\"\"\"\n\n self.exe(\"\"\"truncate table img_choice;\"\"\")\n self.exe(\"\"\"truncate table img_contest;\"\"\")\n self.exe(\"\"\"UPDATE images\n SET assigned_to_pid = NULL,\n undecodable_reason = NULL, \n date_time_tabulated = NULL, \n H_matrix = NULL, \n M_matrix = NULL, \n processing_success = NULL, \n flipped_form = NULL,\n processing_comment = NULL\n WHERE image_number = image_number\"\"\")\n return\n\n def create_t_our_count(self):\n \"\"\"Create summary at precinct-contest level.\n \"\"\"\n\n tmr = timer()\n\n # precinct/contests with at least one suspicious ballot\n tmr.switch_to('t_suspicious')\n self.exe(\"\"\"drop table if exists t_suspicious\"\"\")\n self.exe(\"\"\"\n create table t_suspicious as\n select distinct concat(ico.contest_name, \"|\",\n ico.image_number) AS dud\n from (img_contest ico\n join images img using (image_number))\n where suspicion_by_pct != 0\"\"\")\n print(tmr)\n\n # save the data to compute the ratio of marked to choices for unsuspicious contests\n tmr.switch_to('t_marked_ratio')\n self.exe(\"\"\"drop table if exists t_marked_ratio\"\"\")\n self.exe(\"\"\"\n create table t_marked_ratio as\n select precinct, contest_name, sum(marked) marked,\n count(score) cnt_unsuspic # count of unsuspicious ballots\n from img_con_cho\n where concat(contest_name, '|', image_number) \n not in (select dud from t_suspicious)\n group by precinct, contest_name\"\"\")\n print(tmr)\n\n # our data summed to precinct/contest level\n tmr.switch_to('t_contest_level')\n self.exe(\"\"\"drop table if exists t_contest_level\"\"\")\n self.exe(\"\"\"create table t_contest_level as\n (select precinct, contest_name,\n sum(undervoted_by_pct) undervotes_by_pct,\n sum(suspicion_by_pct) suspicion_by_pct,\n count(DISTINCT i.image_number) num_images,\n i.page_number page_number\n from img_contest\n join images i on img_contest.image_number = i.image_number\n group by precinct, contest_name)\"\"\")\n print(tmr)\n\n # more of our data at precinct/contest/choice level\n tmr.switch_to('t_otherstats')\n self.exe(\"\"\"drop table if exists t_otherstats\"\"\")\n self.exe(\"\"\"create table t_otherstats as\n (select precinct,\n contest_name,\n if (locate(\"Write In\", choice_name) > 0,\n \"(WRITE IN)\", choice_name) as choice_name,\n cast(sum(marked_by_pct) as signed) votes_by_pct,\n count(marked_by_pct) as our_ballots_counted,\n sum(overvoted_by_pct) overvotes_by_pct,\n votes_allowed\n from img_con_cho\n group by precinct, contest_name, choice_name)\"\"\")\n # print(tmr)\n\n # merge it all together at precinct/contest/cnoice level\n tmr.switch_to('t_our_count')\n self.exe(\"\"\"drop table if exists t_our_count\"\"\")\n self.exe(\"\"\"create table t_our_count as\n (select toth.precinct precinct,\n toth.contest_name contest_name,\n tcl.num_images,\n choice_name,\n votes_by_pct,\n overvotes_by_pct,\n tcl.suspicion_by_pct,\n undervotes_by_pct,\n votes_allowed,\n tcl.page_number,\n marked,\n cnt_unsuspic\n from t_otherstats toth\n join t_contest_level tcl\n on toth.contest_name = tcl.contest_name\n and toth.precinct = tcl.precinct\n join t_marked_ratio tmr\n on tmr.precinct = tcl.precinct\n and tmr.contest_name = tcl.contest_name\n )\n \"\"\")\n tmr.switch_to()\n # self.exe(\"\"\"drop table if exists t_contest_level\"\"\")\n # self.exe(\"\"\"drop table if exists t_otherstats\"\"\")\n # self.exe(\"\"\"drop table if exists t_suspicious\"\"\")\n # self.exe(\"\"\"drop table if exists t_marked_ratio\"\"\")\n for x in tmr.get_times():\n print(x)\n logging.info(str(tmr))\n\n\nif __name__ == '__main__':\n db = ETPdb()\n db.connect('testing')\n # db.create_t_our_count()\n db.report_comparison_newer()\n exit(0)\n assert False, \"Unit testing Needs to be rewritten to use unit-test schema\"\n db.clear_recorded_votes()\n # db.clear_recorded_votes() # move this in front of the assert if you really want to do it\n from random import randint, seed\n import collections\n\n # Named tuple for a result of selection from Images\n #\n Exp_img_row = collections.namedtuple('Exp_img_row',\n 'image_number precinct page_number '\n 'elections_batch_num ETP_batch_num '\n 'assigned_to_pid barcode')\n\n seed(2) # initiallze random for repeatable test results\n db.tracing_sql = False # omit this to see all SQL statements executed\n\n # test add_image_nums\n db.recreate_images() # create a blank Images table\n db.add_image_nums(12345, (1,'2')) # elections batch numbers + 2 image numbers\n db.add_image_nums(12346, 3)\n db.add_image_nums(12346, '4')\n\n sql = '''SELECT * FROM IMAGES'''\n ret = db.retrieve(sql)\n assert len(ret) == 4\n indxs = range(4)\n for i in indxs:\n assert ret[i][0] == i + 1 # image numbers as expected\n\n db.delete_images((2,))\n sql = '''SELECT * FROM IMAGES'''\n ret = db.retrieve(sql)\n assert len(ret) == 3 # one fewer images\n assert ret[0][0] == 1 # image 2 is missing\n assert ret[1][0] == 3\n assert ret[2][0] == 4\n\n db.delete_images(('1',4))\n sql = '''SELECT * FROM IMAGES'''\n ret = db.retrieve(sql)\n assert len(ret) == 1 # only image # 3 is left now\n assert ret[0][0] == 3\n\n # test add_images\n db.recreate_images() # create a blank Images table\n data = []\n for x in range(15):\n data.append((\n x,\n ('2-CS', '1-CS4', 'ABCD-1','2-CS', '1-CS4', 'ABC', 'UNKNOWN')[randint(0,6)],\n (1, 2, 3, 4, 1, 2, 3, 4, 'UNK')[randint(0,8)],\n '31',\n '5'))\n\n for x in range(16, 19):\n data.append((x, None, None, None, None))\n\n db.add_images(data) # add 16 images\n\n\n # expected result for random data with seed == 2\n #\n\n # verify updating images after scanning barcode\n #\n update_list = []\n for i in (0, 14):\n row = list()\n row.append('UPD-2') # show that the precinct was updated\n row.append('123412341234') # barcode\n row.append(data[i][0]) # image number to be changed\n update_list.append(row)\n\n db.update_unscanned_images(update_list)\n x = db.get_images((0, 14, 18)) # check updates worked and null rows arrived\n expected_value = list()\n expected_value.append(Exp_img_row(0, 'UPD-2', '1', '31', '5', None, '123412341234'))\n expected_value.append(Exp_img_row(14,'UPD-2', '3', '31', '5', None, '123412341234'))\n expected_value.append(Exp_img_row(18, None, None, None, None, None, None))\n assert x == expected_value\n\n x = db.get_page_report()\n expected_value = [(None, 0, 0, 0, 0, 0, 0, 3, 3, None),\n ('1-CS4', 1, 0, 1, 0, 0, 0, 0, 2, '31'),\n ('2-CS', 0, 1, 1, 0, 1, 0, 0, 3, '31'),\n ('ABC', 1, 0, 0, 0, 0, 0, 0, 1, '31'),\n ('ABCD-1', 1, 0, 1, 2, 1, 0, 0, 5, '31'),\n ('UNKNOWN', 1, 0, 0, 0, 1, 0, 0, 2, '31'),\n ('UPD-2', 1, 0, 1, 0, 0, 0, 0, 2, '31')]\n\n assert x == expected_value\n db.recreate_images() # leave database empty after testing;\n\n","sub_path":"dbase.py","file_name":"dbase.py","file_ext":"py","file_size_in_byte":36186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"385686572","text":"import pandas as pd\nimport pickle as pkl\nimport numpy as np\nfrom functions import *\n\nwith open('sp1500.pkl', 'rb')as f:\n sp1500 = pkl.load(f)\n\n# impute missing values, you can choose different func form functions, such as ffi49/ffi10\nsp1500_impute['sic'] = sp1500_impute['sic'].astype(int)\nsp1500_impute['jdate'] = pd.to_datetime(sp1500_impute['jdate'])\n\nsp1500_impute['ffi49'] = ffi49(sp1500_impute)\nsp1500_impute['ffi49'] = sp1500_impute['ffi49'].fillna(49) # we treat na in ffi49 as 'other'\nsp1500_impute['ffi49'] = sp1500_impute['ffi49'].astype(int)\n\n# there are two ways to impute: industrial median or mean\nsp1500_impute = fillna_ind(sp1500, method='median', ffi=49)\n\nwith open('sp1500_impute.pkl', 'wb') as f:\n pkl.dump(sp1500_impute, f, protocol=4)\n\n# normalize characteristics\n'''\nNote: Please use rank_chars in sp1500_rank and ignore other raw chars. Since I use 0 to fill all the N/A in sp1500_rank. \nIf you want to use raw chars with N/A values already filled, pleas use fillna_ind function.\n'''\nsp1500_rank = standardize(sp1500)\n\nwith open('sp1500_rank.pkl', 'wb') as f:\n pkl.dump(sp1500_rank, f, protocol=4)","sub_path":"pychars/impute_rank_output.py","file_name":"impute_rank_output.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"513472095","text":"# (C) Copyright IBM Corp. 2020.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import print_function\nimport requests,json\nfrom ibm_watson_machine_learning.utils import SPACES_IMPORTS_DETAILS_TYPE, SPACES_EXPORTS_DETAILS_TYPE, SPACES_DETAILS_TYPE, INSTANCE_DETAILS_TYPE, MEMBER_DETAILS_TYPE, STR_TYPE, STR_TYPE_NAME, docstring_parameter, meta_props_str_conv, str_type_conv, get_file_from_cos, print_text_header_h2\nfrom ibm_watson_machine_learning.metanames import SpacesMetaNames, MemberMetaNames, ExportMetaNames\nfrom ibm_watson_machine_learning.href_definitions import is_uid\nfrom ibm_watson_machine_learning.wml_resource import WMLResource\nfrom ibm_watson_machine_learning.wml_client_error import WMLClientError\n\n\n_DEFAULT_LIST_LENGTH = 50\n\n\nclass Spaces(WMLResource):\n \"\"\"\n Store and manage your spaces. This is applicable only for IBM Cloud Pak® for Data for Data\n \"\"\"\n ConfigurationMetaNames = SpacesMetaNames()\n MemberMetaNames = MemberMetaNames()\n ExportMetaNames = ExportMetaNames()\n \"\"\"MetaNames for spaces creation.\"\"\"\n\n def __init__(self, client):\n WMLResource.__init__(self, __name__, client)\n\n\n self._ICP = client.ICP\n\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def store(self, meta_props):\n \"\"\"\n Create a space.\n\n **Parameters**\n\n .. important::\n #. **meta_props**: meta data of the space configuration. To see available meta names use:\\n\n >>> client.spaces.ConfigurationMetaNames.get()\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n\n **returns**: metadata of the stored space\\n\n **return type**: dict\\n\n\n **Example**\n\n >>> metadata = {\n >>> client.spaces.ConfigurationMetaNames.NAME: 'my_space',\n >>> client.spaces.ConfigurationMetaNames.DESCRIPTION: 'spaces',\n >>> }\n >>> spaces_details = client.spaces.store(meta_props=metadata)\n >>> spaces_href = client.spaces.get_href(spaces_details)\n \"\"\"\n\n # quick support for COS credentials instead of local path\n # TODO add error handling and cleaning (remove the file)\n WMLResource._chk_and_block_create_update_for_python36(self)\n Spaces._validate_type(meta_props, u'meta_props', dict, True)\n space_meta = self.ConfigurationMetaNames._generate_resource_metadata(\n meta_props,\n with_validation=True,\n client=self._client\n\n )\n\n\n if not self._ICP:\n creation_response = requests.post(\n self._wml_credentials['url'] + '/v4/spaces',\n headers=self._client._get_headers(),\n json=space_meta\n )\n else:\n creation_response = requests.post(\n self._wml_credentials['url'] + '/v4/spaces',\n headers=self._client._get_headers(),\n json=space_meta,\n verify=False\n )\n\n\n spaces_details = self._handle_response(201, u'creating new spaces', creation_response)\n\n # Cloud Convergence: Set self._client.wml_credentials['instance_id'] to instance_id\n # during client.set.default_space since that's where space is associated with client\n # and also in client.set.default_project\n\n return spaces_details\n\n @staticmethod\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def get_href(spaces_details):\n \"\"\"\n Get space_href from space details.\n\n **Parameters**\n\n .. important::\n #. **space_details**: Metadata of the stored space\\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n **returns**: space href\\n\n **return type**: str\n\n **Example**\n\n >>> space_details = client.spaces.get_details(space_uid)\n >>> space_href = client.spaces.get_href(deployment)\n \"\"\"\n\n Spaces._validate_type(spaces_details, u'spaces_details', object, True)\n Spaces._validate_type_of_details(spaces_details, SPACES_DETAILS_TYPE)\n\n return WMLResource._get_required_element_from_dict(spaces_details, u'spaces_details',\n [u'metadata', u'href'])\n\n @staticmethod\n def get_uid(spaces_details):\n \"\"\"\n Get space_uid from space details.\n\n **Parameters**\n\n .. important::\n #. **space_details**: Metadata of the stored space\\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n **returns**: space UID\\n\n **return type**: str\n\n **Example**\n\n >>> space_details = client.spaces.get_details(space_uid)\n >>> space_uid = client.spaces.get_uid(deployment)\n \"\"\"\n\n Spaces._validate_type(spaces_details, u'spaces_details', object, True)\n Spaces._validate_type_of_details(spaces_details, SPACES_DETAILS_TYPE)\n\n return WMLResource._get_required_element_from_dict(spaces_details, u'spaces_details',\n [u'metadata', u'guid'])\n\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def delete(self, space_uid):\n \"\"\"\n Delete a stored space.\n\n **Parameters**\n\n .. important::\n #. **space_uid**: space UID\\n\n **type**: str\\n\n\n **Output**\n\n .. important::\n **returns**: status (\"SUCCESS\" or \"FAILED\")\\n\n **return type**: str\\n\n\n **Example**\n\n >>> client.spaces.delete(deployment_uid)\n \"\"\"\n\n space_uid = str_type_conv(space_uid)\n Spaces._validate_type(space_uid, u'space_uid', STR_TYPE, True)\n\n space_endpoint = self._href_definitions.get_space_href(space_uid)\n if not self._ICP:\n response_delete = requests.delete(space_endpoint, headers=self._client._get_headers())\n else:\n response_delete = requests.delete(space_endpoint, headers=self._client._get_headers(), verify=False)\n\n return self._handle_response(204, u'space deletion', response_delete, False)\n\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def get_details(self, space_uid=None, limit=None):\n \"\"\"\n Get metadata of stored space(s). If space UID is not specified, it returns all the spaces metadata.\n\n **Parameters**\n\n .. important::\n #. **space_uid**: Space UID (optional)\\n\n **type**: str\\n\n #. **limit**: limit number of fetched records (optional)\\n\n **type**: int\\n\n\n **Output**\n\n .. important::\n **returns**: metadata of stored space(s)\\n\n **return type**: dict\n dict (if UID is not None) or {\"resources\": [dict]} (if UID is None)\\n\n\n .. note::\n If UID is not specified, all spaces metadata is fetched\\n\n\n **Example**\n\n >>> space_details = client.spaces.get_details(space_uid)\n >>> space_details = client.spaces.get_details()\n \"\"\"\n\n space_uid = str_type_conv(space_uid)\n Spaces._validate_type(space_uid, u'space_uid', STR_TYPE, False)\n Spaces._validate_type(limit, u'limit', int, False)\n\n href = self._href_definitions.get_spaces_href()\n if space_uid is None:\n return self._get_no_space_artifact_details(href+\"?include=name,tags,custom,description\", None, limit, 'spaces')\n return self._get_no_space_artifact_details(href, space_uid, limit, 'spaces')\n\n def list(self, limit=None):\n \"\"\"\n List stored spaces. If limit is set to None there will be only first 50 records shown.\n\n **Parameters**\n\n .. important::\n #. **limit**: limit number of fetched records\\n\n **type**: int\\n\n\n **Output**\n\n .. important::\n This method only prints the list of all spaces in a table format.\\n\n **return type**: None\\n\n\n **Example**\n\n >>> client.spaces.list()\n \"\"\"\n\n space_resources = self.get_details(limit=limit)[u'resources']\n space_values = [(m[u'metadata'][u'guid'], m[u'entity'][u'name'], m[u'metadata'][u'created_at']) for m in space_resources]\n\n self._list(space_values, [u'GUID', u'NAME', u'CREATED'], limit, _DEFAULT_LIST_LENGTH)\n\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def update(self, space_uid, changes):\n \"\"\"\n Updates existing space metadata.\n\n **Parameters**\n\n .. important::\n #. **space_uid**: UID of space which definition should be updated\\n\n **type**: str\\n\n #. **changes**: elements which should be changed, where keys are ConfigurationMetaNames\\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n **returns**: metadata of updated space\\n\n **return type**: dict\\n\n\n **Example**\n\n >>> metadata = {\n >>> client.spaces.ConfigurationMetaNames.NAME:\"updated_space\"\n >>> }\n >>> space_details = client.spaces.update(space_uid, changes=metadata)\n \"\"\"\n\n space_uid = str_type_conv(space_uid)\n self._validate_type(space_uid, u'space_uid', STR_TYPE, True)\n self._validate_type(changes, u'changes', dict, True)\n meta_props_str_conv(changes)\n\n details = self.get_details(space_uid)\n\n patch_payload = self.ConfigurationMetaNames._generate_patch_payload(details['entity'], changes,\n with_validation=True)\n\n href = self._href_definitions.get_space_href(space_uid)\n if not self._ICP:\n response = requests.patch(href, json=patch_payload, headers=self._client._get_headers())\n else:\n response = requests.patch(href, json=patch_payload, headers=self._client._get_headers(), verify=False)\n updated_details = self._handle_response(200, u'spaces patch', response)\n\n return updated_details\n\n\n#######SUPPORT FOR SPACE MEMBERS\n\n ###GET MEMBERS DETAILS\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def get_members_details(self, space_uid, member_id=None, limit=None):\n \"\"\"\n Get metadata of members associated with a space. If member UID is not specified, it returns all the members metadata.\n\n **Parameters**\n\n .. important::\n #. **space_uid**: member UID (optional)\\n\n **type**: str\\n\n #. **limit**: limit number of fetched records (optional)\\n\n **type**: int\\n\n\n **Output**\n\n .. important::\n **returns**: metadata of member(s) of a space\\n\n **return type**: dict\n dict (if UID is not None) or {\"resources\": [dict]} (if UID is None)\\n\n\n .. note::\n If member id is not specified, all members metadata is fetched\\n\n\n **Example**\n\n >>> member_details = client.spaces.get_member_details(space_uid,member_id)\n \"\"\"\n\n space_uid = str_type_conv(space_uid)\n Spaces._validate_type(space_uid, u'space_uid', STR_TYPE, True)\n\n member_uid = str_type_conv(member_id)\n Spaces._validate_type(member_id, u'member_id', STR_TYPE, False)\n\n Spaces._validate_type(limit, u'limit', int, False)\n\n href = self._href_definitions.get_members_href(space_uid)\n\n return self._get_no_space_artifact_details(href, member_uid, limit, 'space members')\n\n ##DELETE MEMBERS\n\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def delete_members(self, space_uid,member_id):\n \"\"\"\n Delete a member associated with a space.\n\n **Parameters**\n\n .. important::\n #. **space_uid**: space UID\\n\n **type**: str\\n\n #. **member_uid**: member UID\\n\n **type**: str\\n\n\n **Output**\n\n .. important::\n **returns**: status (\"SUCCESS\" or \"FAILED\")\\n\n **return type**: str\\n\n\n **Example**\n\n >>> client.spaces.delete_member(space_uid,member_id)\n \"\"\"\n\n space_uid = str_type_conv(space_uid)\n Spaces._validate_type(space_uid, u'space_uid', STR_TYPE, True)\n\n member_id = str_type_conv(member_id)\n Spaces._validate_type(member_id, u'member_id', STR_TYPE, True)\n\n member_endpoint = self._href_definitions.get_member_href(space_uid,member_id)\n if not self._ICP:\n response_delete = requests.delete(member_endpoint, headers=self._client._get_headers())\n else:\n response_delete = requests.delete(member_endpoint, headers=self._client._get_headers(), verify=False)\n\n return self._handle_response(204, u'space member deletion', response_delete, False)\n\n#######UPDATE MEMBERS\n\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def update_member(self, space_uid, member_id, changes):\n \"\"\"\n Updates existing member metadata.\n\n **Parameters**\n\n .. important::\n #. **space_uid**: UID of space\\n\n **type**: str\\n\n #. **member_id**: UID of member that needs to be updated\\n\n **type**: str\\n\n #. **changes**: elements which should be changed, where keys are ConfigurationMetaNames\\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n **returns**: metadata of updated member\\n\n **return type**: dict\\n\n\n **Example**\n\n >>> metadata = {\n >>> client.spaces.ConfigurationMetaNames.ROLE:\"viewer\"\n >>> }\n >>> member_details = client.spaces.update_member(space_uid, member_id, changes=metadata)\n \"\"\"\n\n space_uid = str_type_conv(space_uid)\n self._validate_type(space_uid, u'space_uid', STR_TYPE, True)\n member_id = str_type_conv(member_id)\n self._validate_type(member_id, u'member_id', STR_TYPE, True)\n\n self._validate_type(changes, u'changes', dict, True)\n meta_props_str_conv(changes)\n\n details = self.get_members_details(space_uid,member_id)\n\n patch_payload = self.MemberMetaNames._generate_patch_payload(details['entity'], changes,\n with_validation=True)\n\n href = self._href_definitions.get_member_href(space_uid,member_id)\n if not self._ICP:\n response = requests.patch(href, json=patch_payload, headers=self._client._get_headers())\n else:\n response = requests.patch(href, json=patch_payload, headers=self._client._get_headers(), verify=False)\n updated_details = self._handle_response(200, u'members patch', response)\n\n return updated_details\n\n#####CREATE MEMBER\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def create_member(self, space_uid,meta_props):\n \"\"\"\n Create a member within a space.\n\n **Parameters**\n\n .. important::\n #. **meta_props**: meta data of the member configuration. To see available meta names use:\\n\n >>> client.spaces.MemberMetaNames.get()\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n\n **returns**: metadata of the stored member\\n\n **return type**: dict\\n\n\n .. note::\n * client.spaces.MemberMetaNames.ROLE can be any one of the following \"viewer, editor, admin\"\\n\n * client.spaces.MemberMetaNames.IDENTITY_TYPE can be any one of the following \"user,service\"\\n\n * client.spaces.MemberMetaNames.IDENTITY can be either service-ID or IAM-userID\\n\n\n **Example**\n\n >>> metadata = {\n >>> client.spaces.MemberMetaNames.ROLE:\"Admin\",\n >>> client.spaces.MemberMetaNames.IDENTITY:\"iam-ServiceId-5a216e59-6592-43b9-8669-625d341aca71\",\n >>> client.spaces.MemberMetaNames.IDENTITY_TYPE:\"service\"\n >>> }\n >>> members_details = client.spaces.create_member(space_uid=space_id, meta_props=metadata)\n \"\"\"\n\n # quick support for COS credentials instead of local path\n # TODO add error handling and cleaning (remove the file)\n Spaces._validate_type(meta_props, u'meta_props', dict, True)\n space_meta = self.MemberMetaNames._generate_resource_metadata(\n meta_props,\n with_validation=True,\n client=self._client\n\n )\n\n\n if not self._ICP:\n creation_response = requests.post(\n self._wml_credentials['url'] + '/v4/spaces/'+space_uid+\"/members\",\n headers=self._client._get_headers(),\n json=space_meta\n )\n else:\n creation_response = requests.post(\n self._wml_credentials['url'] + '/v4/spaces/'+space_uid+\"/members\",\n headers=self._client._get_headers(),\n json=space_meta,\n verify=False\n )\n\n\n members_details = self._handle_response(201, u'creating new members', creation_response)\n\n return members_details\n\n def list_members(self, space_uid ,limit=None):\n \"\"\"\n List stored members of a space. If limit is set to None there will be only first 50 records shown.\n\n **Parameters**\n\n .. important::\n #. **limit**: limit number of fetched records\\n\n **type**: int\\n\n\n **Output**\n\n .. important::\n This method only prints the list of all members associated with a space in a table format.\\n\n **return type**: None\\n\n\n **Example**\n\n >>> client.spaces.list_members()\n \"\"\"\n\n member_resources = self.get_members_details(space_uid,limit=limit)[u'resources']\n space_values = [(m[u'metadata'][u'guid'], m[u'entity'][u'identity'], m[u'entity'][u'identity_type'], m[u'entity'][u'role'], m[u'metadata'][u'created_at']) for m in member_resources]\n\n self._list(space_values, [u'GUID', u'USERNAME', u'IDENTITY_TYPE', u'ROLE', u'CREATED'], limit, _DEFAULT_LIST_LENGTH)\n\n\n\n\n @staticmethod\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def get_member_href(member_details):\n \"\"\"\n Get member_href from member details.\n\n **Parameters**\n\n .. important::\n #. **space_details**: Metadata of the stored member\\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n **returns**: member href\\n\n **return type**: str\n\n **Example**\n\n >>> member_details = client.spaces.get_member_details(member_id)\n >>> member_href = client.spaces.get_member_href(member_details)\n \"\"\"\n\n Spaces._validate_type(member_details, u'member details', object, True)\n Spaces._validate_type_of_details(member_details, MEMBER_DETAILS_TYPE)\n\n return WMLResource._get_required_element_from_dict(member_details, u'member_details',\n [u'metadata', u'href'])\n\n @staticmethod\n def get_member_uid(member_details):\n \"\"\"\n Get member_uid from member details.\n\n **Parameters**\n\n .. important::\n #. **member_details**: Metadata of the created member\\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n **returns**: member UID\\n\n **return type**: str\n\n **Example**\n\n >>> member_details = client.spaces.get_member_details(member_id)\n >>> member_id = client.spaces.get_member_uid(member_details)\n \"\"\"\n\n Spaces._validate_type(member_details, u'member_details', object, True)\n Spaces._validate_type_of_details(member_details, MEMBER_DETAILS_TYPE)\n\n return WMLResource._get_required_element_from_dict(member_details, u'member_details',\n [u'metadata', u'guid'])\n\n\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def imports(self, space_uid, file_path):\n \"\"\"\n Updates existing space metadata.\n Imports assets in the zip file to a space\n\n **Parameters**\n\n .. important::\n #. **space_uid**: UID of space which definition should be updated\\n\n **type**: str\\n\n #. **file_path**: Path to the content file to be imported\\\\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n **returns**: metadata of import space\\n\n **return type**: str\\n\n\n **Example**\n\n >>> space_details = client.spaces.imports(space_uid, file_path=\"/tmp/spaces.zip\")\n \"\"\"\n\n space_uid = str_type_conv(space_uid)\n self._validate_type(space_uid, u'space_uid', STR_TYPE, True)\n self._validate_type(file_path, u'file_path', STR_TYPE, True)\n\n\n\n with open(str(file_path), 'rb') as archive:\n data = archive.read()\n\n href = self._href_definitions.get_space_href(space_uid) + \"/imports\"\n\n\n if not self._ICP:\n response = requests.post(href, headers=self._client._get_headers(), data=data)\n else:\n response = requests.post(href, headers=self._client._get_headers(), data=data, verify=False)\n import_space_details = self._handle_response(202, u'spaces import', response)\n\n return import_space_details\n\n\n\n @staticmethod\n def get_imports_uid(imports_space_details):\n \"\"\"\n Get imports_uid from imports space details.\n\n **Parameters**\n\n .. important::\n #. **imports_space_details**: Metadata of the created space import\\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n **returns**: imports space UID\\n\n **return type**: str\n\n **Example**\n\n >>> member_details = client.spaces.get_imports_details(space_uid, imports_id)\n >>> imports_id = client.spaces.get_imports_uid(imports_space_details)\n \"\"\"\n\n Spaces._validate_type(imports_space_details, u'member_details', object, True)\n Spaces._validate_type_of_details(imports_space_details, SPACES_IMPORTS_DETAILS_TYPE)\n\n return WMLResource._get_required_element_from_dict(imports_space_details, u'imports_space_details',[u'metadata', u'guid'])\n\n @staticmethod\n def get_exports_uid(exports_space_details):\n \"\"\"\n Get imports_uid from imports space details.\n\n **Parameters**\n\n .. important::\n #. **space_exports_details**: Metadata of the created space import\\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n **returns**: exports space UID\\n\n **return type**: str\n\n **Example**\n\n >>> member_details = client.spaces.get_exports_details(space_uid, exports_id)\n >>> imports_id = client.spaces.get_imports_uid(exports_space_details)\n \"\"\"\n\n Spaces._validate_type(exports_space_details, u'exports_space_details', object, True)\n Spaces._validate_type_of_details(exports_space_details, SPACES_EXPORTS_DETAILS_TYPE)\n\n return WMLResource._get_required_element_from_dict(exports_space_details, u'exports_space_details',\n [u'metadata', u'guid'])\n\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def get_imports_details(self, space_uid, imports_id=None, limit=None):\n \"\"\"\n Get metadata of stored space(s). If space UID is not specified, it returns all the spaces metadata.\n\n **Parameters**\n\n .. important::\n #. **space_uid**: Space UID (optional)\\n\n **type**: str\\n\n #. **limit**: limit number of fetched records (optional)\\n\n **type**: int\\n\n\n **Output**\n\n .. important::\n **returns**: metadata of stored space(s)\\n\n **return type**: dict\n dict (if UID is not None) or {\"resources\": [dict]} (if UID is None)\\n\n\n .. note::\n If UID is not specified, all spaces metadata is fetched\\n\n\n **Example**\n\n >>> space_details = client.spaces.get_imports_details(space_uid)\n >>> space_details = client.spaces.get_imports_details(space_uid,imports_id)\n \"\"\"\n\n space_uid = str_type_conv(space_uid)\n Spaces._validate_type(space_uid, u'space_uid', STR_TYPE, False)\n Spaces._validate_type(imports_id, u'imports_uid', STR_TYPE, False)\n Spaces._validate_type(limit, u'limit', int, False)\n\n\n if imports_id is None:\n href = self._href_definitions.get_space_href(space_uid) + \"/imports\"\n else:\n href = self._href_definitions.get_space_href(space_uid) + \"/imports/\" + imports_id\n\n if not self._ICP:\n response = requests.get(href, headers=self._client._get_headers())\n else:\n response = requests.get(href, headers=self._client._get_headers(), verify=False)\n import_space_details = self._handle_response(200, u'spaces import details', response)\n\n return import_space_details\n\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def exports(self, space_uid, meta_props):\n \"\"\"\n Updates existing space metadata.\n exports assets in the zip file from a space\n\n **Parameters**\n\n .. important::\n #. **meta_props**: meta data of the space configuration. To see available meta names use:\\n\n >>> client.spaces.ExportMetaNames.get()\n\n **type**: dict\\n\n\n **Output**\n\n .. important::\n **returns**: metadata of import space\\n\n **return type**: str\\n\n\n **Example**\n >>> meta_props = {\n >>> client.spaces.ExportMetaNames.NAME: \"sample\",\n >>> client.spaces.ExportMetaNames.DESCRIPTION : \"test description\",\n >>> client.spaces.ExportMetaNames.ASSETS : {\"data_assets\": [], \"wml_model\":[]} }\n >>> }\n >>> space_details = client.spaces.exports(space_uid, meta_props=meta_props)\n\n \"\"\"\n\n Spaces._validate_type(meta_props, u'meta_props', dict, True)\n space_exports_meta = self.ExportMetaNames._generate_resource_metadata(\n meta_props,\n with_validation=True,\n client=self._client)\n\n space_exports_meta_json = json.dumps(space_exports_meta)\n\n space_uid = str_type_conv(space_uid)\n self._validate_type(space_uid, u'space_uid', STR_TYPE, True)\n\n href = self._href_definitions.get_space_href(space_uid) + \"/exports\"\n\n if not self._ICP:\n response = requests.post(href, headers=self._client._get_headers(), data=space_exports_meta_json)\n else:\n response = requests.post(href, headers=self._client._get_headers(), data=space_exports_meta_json, verify=False)\n export_space_details = self._handle_response(202, u'spaces export', response)\n\n return export_space_details\n\n\n @docstring_parameter({'str_type': STR_TYPE_NAME})\n def get_exports_details(self, space_uid, exports_id=None, limit=None):\n \"\"\"\n Get details of exports for space. If exports UID is not specified, it returns all the spaces metadata.\n\n **Parameters**\n\n .. important::\n #. **space_uid**: Space UID (optional)\\n\n **type**: str\\n\n #. **limit**: limit number of fetched records (optional)\\n\n **type**: int\\n\n **Output**\n\n .. important::\n **returns**: metadata of stored space(s)\\n\n **return type**: dict\n dict (if UID is not None) or {\"resources\": [dict]} (if UID is None)\\n\n\n .. note::\n If UID is not specified, all spaces metadata is fetched\\n\n\n **Example**\n\n >>> space_details = client.spaces.get_exports_details(space_uid)\n >>> space_details = client.spaces.get_exports_details(space_uid,exports_id)\n\n \"\"\"\n\n space_uid = str_type_conv(space_uid)\n Spaces._validate_type(space_uid, u'space_uid', STR_TYPE, False)\n Spaces._validate_type(exports_id, u'imports_uid', STR_TYPE, False)\n Spaces._validate_type(limit, u'limit', int, False)\n\n\n if exports_id is None:\n href = self._href_definitions.get_space_href(space_uid) + \"/exports\"\n else:\n href = self._href_definitions.get_space_href(space_uid) + \"/exports/\" + exports_id\n\n if not self._ICP:\n response = requests.get(href, headers=self._client._get_headers())\n else:\n response = requests.get(href, headers=self._client._get_headers(), verify=False)\n export_space_details = self._handle_response(200, u'spaces exports details', response)\n\n return export_space_details\n\n\n def download(self, space_uid, space_exports_uid, filename=None):\n \"\"\"\n Downloads zip file deployment of specified UID.\n\n **Parameters**\n\n .. important::\n\n #. **exports_space_uid**: UID of virtual deployment.\\n\n **type**: str\\n\n\n #. **filename**: Filename of downloaded archive. (optional)\\n\n **type**: str\\n\n\n **Output**\n\n .. important::\n\n **returns**: Path to downloaded file.\\n\n **return type**: str\\n\n\n **Example**\n\n >>> client.spaces.download(space_uid)\n \"\"\"\n\n space_exports_uid = str_type_conv(space_exports_uid)\n Spaces._validate_type(space_exports_uid, u'space_exports_uid', STR_TYPE, False)\n\n if space_exports_uid is not None and not is_uid(space_exports_uid):\n raise WMLClientError(u'\\'space_exports_uid\\' is not an uid: \\'{}\\''.format(space_exports_uid))\n\n href = self._href_definitions.get_space_href(space_uid) + \"/exports/\" + space_exports_uid + \"/content\"\n\n if not self._ICP:\n response = requests.get(\n href,\n headers=self._client._get_headers()\n )\n else:\n response = requests.get(\n href,\n headers=self._client._get_headers(),\n verify=False\n )\n if filename is None:\n filename = 'wmlspace.zip'\n\n if response.status_code == 200:\n with open(filename, \"wb\") as new_file:\n new_file.write(response.content)\n new_file.close()\n\n print_text_header_h2(\n u'Successfully downloaded spaces export file: ' + str(filename))\n\n return filename\n else:\n raise WMLClientError(u'Unable to download spaces export: ' + response.text)\n\n","sub_path":"venv/Lib/site-packages/ibm_watson_machine_learning/spaces.py","file_name":"spaces.py","file_ext":"py","file_size_in_byte":32918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"100789803","text":"# DNN-Language Model implementation\n#\n# Ricardo Faundez-Carrasco, 2017\n# ========================================================\n# Script implementing a deep neural network system for language modelling\n# purposes. In the future further, more complex architectures should be\n# added, but the aim is to design a feed-forward DNN.\n# The main reference is:\n# \"From_Feedforward_to_Recurrent_LSTM_Neural_Networks_for_Language_Modeling\"\n# by Sundermeyer et al. (2015)\n#\n# ========================================================\nfrom __future__ import print_function\nimport argparse\nimport collections\nimport math\nimport numpy as np\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\nimport io\nimport random\nimport tensorflow as tf\nfrom six.moves import range\n\nfile_strings = 'metadata.tsv'\t\t\t\t\t\t# list of unicode words\nfile_embeddings = 'embeddings.csv'\t\t\t\t\t# embedding vectors\nfile_labels = 'words_label.csv'\t\t\t\t\t\t# labels from clustering\nfile_corpus = 'corpus_int'\t\t\t\t\t\t\t# corpus text as a list of integers\n\ndef checkDependencies(file_strings, file_embeds, file_labels, file_corpus):\n\t\"\"\"Checks that the required files exist.\n\n\tArgs:\n\tfile_strings: 'string', path to unicode words.\n\tfile_embeds: 'string', path to embeddings.\n\tfile_labels: 'string', path to classes per word.\n\tfile_corpus: 'string', path to complete corpus as 'int's.\n\n\tReturns:\n\tNone\n\n\tExample:\n\t\t>>> checkDependencies(f1, f2, f3, f4)\n\t\tAll file dependencies satisfied\n\t\"\"\"\n\tif not os.path.exists(file_strings):\n\t\traise Exception(\n\t\t\t'List of words as strings not found')\n\tif not os.path.exists(file_embeds):\n\t\traise Exception(\n\t\t\t'List of word embeddings not found')\n\tif not os.path.exists(file_labels):\n\t\traise Exception(\n\t\t\t'List fo clustering labels not found')\n\tif not os.path.exists(file_corpus):\n\t\traise Exception(\n\t\t\t'Corpus file with the raw text not found')\n\tprint(\"All file dependencies satisfied\")\n\treturn None\n\ndef readData(file_strings, file_embeds, file_labels, file_corpus):\n\t\"\"\"Returns the data within each file - words, embeddings and reference clustering.\n\n\tArgs:\n\tfile_strings: 'string', path to unicode words.\n\tfile_embeds: 'string', path to embeddings.\n\tfile_labels: 'string', path to classes per word.\n\tfile_corpus: 'string', path to complete corpus as 'int's.\n\n\tReturns:\n\t'tupla' of 'list' and 'np.array's, the first the 'list' of\n\twords and then embeddings, labels and corpus.\n\n\tExample:\n\t\t>>> readData(f1, f2, f3, f4)\n\t\t([u'word'], array([[0.1 0.2 0.3]]), array([[1.]]), array([0]))\n\t\"\"\"\n\twith io.open(file_strings, 'r', encoding = 'latin-1') as f:\n\t\twords = f.read()\n\twords = list(words.split())\n\tembeddings = np.loadtxt(file_embeds)\n\tlabels = np.loadtxt(file_labels)\n\tif len(words) != len(embeddings) != len(labels):\n\t\traise Exception(\n\t\t\t'The sizes of words, embeddings and clustering labels mismatch')\n\t# corpus = np.loadtxt(file_corpus).astype(int)\n\tcorpus = [3,5,121334,11,51,201,231,2645,6548,8784,1]\n\tprint('All the file dependencies are correctly loaded')\n\treturn (words, embeddings, labels, corpus)\n\ncheckDependencies(file_strings, file_embeddings, file_labels, file_corpus)\nwords, embeddings, clusters, corpus = readData(file_strings, file_embeddings, file_labels, file_corpus)\ndata_index = 0\n\ndef generateBatch(batch_size, num_previous_words):\n\t\"\"\"Generates a batch of samples.\n\n\tArgs:\n\tbatch_size: 'int', number of targets.\n\tnum_previous_words: 'int', number of previous words.\n\n\tReturns:\n\t'tupla' of 'np.array's of 'int's, with the indexes of the\n\tcontext words and the index of the target word.\n\n\tExample:\n\t\t>>> generateBatch(1,2)\n\t\t(np.array([[3, 5]]), np.array([[11]]))\n\t\"\"\"\n\tglobal data_index\n\tbatch = np.ndarray(shape = (batch_size, num_previous_words), dtype = np.int32)\n\tlabels = np.ndarray(shape = (batch_size, 1), dtype = np.int32)\n\tspan = num_previous_words + 1\n\tbuffer = collections.deque(maxlen = span)\n\tfor _ in range(span):\n\t\tbuffer.append(corpus[data_index])\n\t\tdata_index = (data_index + 1) % len(corpus)\n\tfor i in range(batch_size):\n\t\tfor j in range(num_previous_words):\n\t\t\tbatch[i,j] = buffer[j]\n\t\tbuffer.append(corpus[data_index])\n\t\tlabels[i,0] = int(corpus[data_index - 1])\n\t\tdata_index = (data_index + 1) % len(corpus)\n\treturn (batch.astype(int), labels.astype(int))\n\ndef showBatch():\n\t\"\"\"Displays an example of batch generation, for illustrative purposes.\n\n\tArgs:\n\tNone\n\n\tReturns:\n\tNone\n\n\tExample:\n\t\t>>> batch_size = 2\n\t\t>>> num_previous_words = 2\n\t\t>>> showBatch()\n\t\t3 at 5 the --> 12 42.0 bakery\n\t\t5 the 12 bakery --> 7 30.0 in\n\n\t\"\"\"\n\tbatch, labels = generateBatch(batch_size, num_previous_words)\n\tfor i in range(batch_size):\n\t\tprint(batch[i,0], words[batch[i,0]], batch[i,1], words[batch[i,1]], \" --> \",\n\t\t\tlabels[i,0], clusters[labels[i,0]], words[labels[i,0]])\n\treturn None\n\ndef getEmbedVects(context):\n\t\"\"\"Gets the embeddings of a list of words.\n\n\tArgs:\n\tcontext: 'np.array' of 'int's, the codified input words\n\n\tReturns:\n\t'np.array' of 'np.array's, the words as embedding vectors\n\n\tExample:\n\t\t>>> getEmbedVects([1., 3.])\n\t\t[[[0.1 -0.05 0.2], [0.03 0.2 -0.8]]]\n\t\"\"\"\n\tbatch_size = context.shape[0]\n\tcontext_size = context.shape[1]\n\tcontext_as_vec = []\n\tfor word in range(batch_size):\n\t\taux = []\n\t\tfor i in range(context_size):\n\t\t\taux.append(embeddings[context[word, i]])\n\t\tcontext_as_vec.append(aux)\n\treturn np.array(context_as_vec)\n\ndef getOneHotClass(target_class):\n\t\"\"\"Returns the one-hot vector for the class of a target word.\n\n\tArgs:\n\ttarget_class: 'np.array' of 'int', the target words\n\n\tReturns:\n\t'np.array' of 'int', the one-hot vector of true class for\n\tevery target word in the batch.\n\n\tExample:\n\tnum_classes = 3\n\t(class of 0 --> 0, class of 1 --> 2, class of 2 --> 1)\n\t\t>>> getOneHotClass([0, 1, 2])\n\t\t[[1.,0.,0.],[0.,0.,1.],[0.,1.,0.]]\n\t\"\"\"\n\toneHot_class = np.zeros((batch_size, num_classes))\n\tfor i in range(batch_size):\n\t\toneHot_class[i, clusters[int(target_class[i])].astype(int)] = 1\n\treturn oneHot_class\n\ndef generateWeights(clusters, num_classes, \n\t\t\t\t\tinitializers = None,\n\t\t\t\t\tregularizers = None,\n\t\t\t\t\ttrainable = False,\n\t\t\t\t\tscope = None,\n\t\t\t\t\treuse = None,\n\t\t\t\t\toutput_collections = (),\n\t\t\t\t\tname = None):\n\t\"\"\"Defines and initializes the weight matrices of the system.\n\n\tArgs:\n\tclusters: 'np.array' of 'int's, the list of class per word\n\tnum_classes: 'int', number of possible classes for a word.\n\toutput_collections: 'tuple' of 'string's, name of the collection\n\t\t\t\t\t\tto collect result of this op.\n\tname: 'string', name of the operation\n\n\tReturns:\n\t'tupla' of a dict' of 'Tensor's, a 'dict' of 'int' and an 'int', \n\tthe weight matrices of the whole language model, the number or words\n\tbelonging to each class and the maximum number of words belonging\n\tto one class.\n\n\tExample:\n\t\t>>> generateWeights(1)\n\t\t{'A1': ,\n\t\t'A2: '},\n\t\t'A3': ,\n\t\t'A4,0: }\n\t\"\"\"\n\twith tf.name_scope(name, \"generateWeights\"):\n\t\tw = dict()\n\t\tw['A1'] = tf.Variable(tf.random_normal([input_size, input_size]))\n\t\tw['A2'] = tf.Variable(tf.random_normal([2 * input_size, hidden_size]))\n\t\tw['A3'] = tf.Variable(tf.random_normal([hidden_size, num_classes]))\n\t\tbase_name = 'A4,'\n\t\tnum_words_per_class = []\n\t\tnum_words_per_class.extend(collections.Counter(clusters).most_common())\n\t\tmax_words_in_class = num_words_per_class[0][1]\n\t\tfor c in range(num_classes):\n\t\t\tname = base_name + str(int(num_words_per_class[c][0]))\n\t\t\tw[name] = tf.Variable(tf.random_normal([hidden_size, max_words_in_class]))\n\t\treturn(w, num_words_per_class, max_words_in_class)\n\ndef chooseWeights(predicted_class, \n\t\t\t\tweights, \n\t\t\t\tinitializers = None,\n\t\t\t\tregularizers = None,\n\t\t\t\ttrainable = False,\n\t\t\t\tscope = None,\n\t\t\t\treuse = None,\n\t\t\t\tis_training = True,\n\t\t\t\toutput_collections = (), \n\t\t\t\tname = None):\n\t\"\"\"Make a selection of weight matrices based on the numbers of predicted_class.\n\n\tArgs:\n\tpredicted_class: 'np.array' of 'int's, input vector.\n\tweights: 'dict' of 'Tensor's, weight matrices.\n\toutput_collections: 'tuple' of 'string's, name of the collection\n\t\t\t\t\t\tto collect result of this op.\n\tname: 'string', name of the operation\n\n\tReturns:\n\t'list' of 'Tensor', weight matrices corresponding the values of the input.\n\n\tExample:\n\t\t>>> chooseWeights([1, 2], output_collections = ['MY_OPS'],\n\t\t\t\t\t\t\tname = 'choosing')\n\t\t['1': ,\n\t\t'2': ]\n\t\"\"\"\n\twith tf.name_scope(name, \"chooseWeights\"):\n\t\tx = tf.placeholder(tf.int32, shape = [None, batch_size])\n\t\tmatrices = list()\n\t\tif is_training:\n\t\t\tx = session.run(x, feed_dict = {x: predicted_class})\n\t\t\tx = x[0]\n\t\t\tfor element in x:\n\t\t\t\tname = 'A4,' + str(int(element))\n\t\t\t\tmatrices.append(session.run(w[name]))\n\t\telse:\n\t\t\tpredicted_class = predicted_class[0]\n\t\t\tfor element in predicted_class:\n\t\t\t\tname = 'A4,' + str(int(element))\n\t\t\t\tmatrices.append(w[name])\n\t\treturn matrices\n\n# Definition of parameters and hyper-parameters\nbatch_size = 2\nnum_previous_words = 2\ninput_size = embeddings.shape[1]\nhidden_size = 3\nnum_classes = int(np.max(clusters) + 1)\nlearn_rate = 1.0\nnum_epochs = 3\nnum_iterations = num_epochs * len(corpus) // batch_size\n\n# Build the Tensorflow graph\ngraph = tf.Graph()\nwith graph.as_default():\n\tword1 = tf.placeholder(tf.float32, shape = [None, input_size], name = 'Wi-1')\n\tword2 = tf.placeholder(tf.float32, shape = [None, input_size], name = 'Wi-2')\n\tw, num_words_per_class, max_words_in_class = generateWeights(clusters, num_classes)\n\ty = tf.concat([tf.matmul(word1, w['A1']), tf.matmul(word2, w['A1'])], 1)\n\tz = tf.sigmoid(tf.matmul(y, w['A2']))\n\n\tclass_probability = tf.matmul(z, w['A3'])\n\tclass_prediction = tf.argmax(class_probability, axis = 1)\n\ttrue_class = tf.placeholder(tf.int32, shape = [None, num_classes], name = 'true_class')\n\n\tclass_CE = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = class_probability ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tlabels = true_class))\n\tclass_train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(class_CE)\n\n\n\tword_weights = tf.placeholder(tf.float32, shape = [None, hidden_size, max_words_in_class],\n\t\t\t\t\t\t\t\t\tname = 'storage_word_weights')\n\n\n\n\tinit = tf.global_variables_initializer()\n\nwith tf.Session(graph = graph) as session:\n\tsession.run(init)\n\tprint('Iterations: ', num_iterations)\n\tprint('----------------')\n\tfor it in range(num_iterations):\n\t\tbatch, label = generateBatch(batch_size, num_previous_words)\n\t\tbatch = getEmbedVects(batch)\n\t\tlabel_class = getOneHotClass(label)\n\n\t\t_, predicted_class = session.run([class_train_step, class_prediction],\n\t\t\t\t\t\t\tfeed_dict = {word1: batch[:,0], word2: batch[:,1], true_class: label_class})\n\n\t\tpredicted_class = np.reshape(predicted_class, (1, batch_size))\n\t\t# Get the matrices for word_weights\n\tprint(predicted_class)\n\tmatrices = chooseWeights(predicted_class, w)\n\tprint(session.run([word_weights], {word_weights: matrices}))\n\t\t\n\tprint('----------------')","sub_path":"new_language_model.py","file_name":"new_language_model.py","file_ext":"py","file_size_in_byte":11023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"340789062","text":"from utility_functions import *\nfrom format_HydroSHEDS import *\n\narcpy.CheckOutExtension('Spatial')\narcpy.env.overwriteOutput = True\narcpy.env.scratchWorkspace = os.path.join(rootdir, 'scratch', 'scratch.gdb')\n\nsg_outdir = os.path.join(datdir, 'SOILGRIDS250')\nsgsmalldir = os.path.join(resdir,'soilsgrid250_smalltiles')\nsgmediumdir = os.path.join(resdir,'soilsgrid250_mediumtiles')\nsgresgdb = os.path.join(resdir, 'soilgrids250.gdb')\npathcheckcreate(sgsmalldir)\npathcheckcreate(sgmediumdir)\npathcheckcreate(sgresgdb)\n\n#Get Goode Homolosine spatial reference\ngoode_sr = arcpy.SpatialReference(54052)\n\n#Define NoData value\nnodatavalue = -9999\n\n########################################## MOSAIC TILES ################################################################\n#Create a list of files for each texture and depth\ncheckproj = False\nsg_subdirl = defaultdict(list)\nprint('Getting list of tiles...')\nfor f in getfilelist(sg_outdir, 'tileSG.*tif$'):\n print(f)\n sg_subdirl[os.path.split(f)[0]].append(f)\n if checkproj:\n if arcpy.Describe(f).SpatialReference.name=='Unknown':\n arcpy.DefineProjection_management(f, goode_sr)\n\ntileinterval = 100\nsmalldirdict = {os.path.split(partdepth)[1]: os.path.join(sgsmalldir, os.path.split(partdepth)[1]) for partdepth in sg_subdirl}\nmediumdirdict = {i: os.path.join(sgmediumdir, i) for i in smalldirdict}\nmosaicdict = {lyr:os.path.join(sgresgdb, lyr) for lyr in mediumdirdict}\nformatdict = {lyr:os.path.join(sgresgdb, '{}_format'.format(lyr)) for lyr in mediumdirdict}\n\nif not all([arcpy.Exists(lyr) for lyr in formatdict.values()]):\n for partdepth in sg_subdirl:\n print(partdepth)\n partdepthdir = smalldirdict[os.path.split(partdepth)[1]]\n if not os.path.exists(partdepthdir):\n print('Create directory {}...'.format(partdepthdir))\n os.mkdir(partdepthdir)\n dictdiv= [[i, i+tileinterval] for i in range(0, len(sg_subdirl[partdepth]), tileinterval)]\n for tilel in dictdiv:\n outtile= os.path.join(partdepthdir, \"mean{1}_{2}.tif\".format(os.path.split(partdepth)[1], tilel[0], tilel[1]-1))\n if not arcpy.Exists(outtile):\n print('Mosaicking {}...'.format(outtile))\n arcpy.MosaicToNewRaster_management(input_rasters=sg_subdirl[partdepth][tilel[0]:tilel[1]],\n output_location=os.path.split(outtile)[0],\n raster_dataset_name_with_extension= os.path.split(outtile)[1],\n number_of_bands=1,\n pixel_type='16_BIT_SIGNED')\n else:\n print('{} already exists...'.format(outtile))\n\n #Remosaick using MAX\n for partdepth in smalldirdict:\n print(partdepth)\n partdepthdir = mediumdirdict[partdepth]\n if not os.path.exists(partdepthdir):\n print('Create directory {}...'.format(partdepthdir))\n os.mkdir(partdepthdir)\n smalltiles = getfilelist(smalldirdict[partdepth], '.*[.]tif$')\n dictdiv= [[i, i+tileinterval] for i in range(0, len(smalltiles), tileinterval)]\n for tilel in dictdiv:\n outtile= os.path.join(partdepthdir, \"mean{1}_{2}.tif\".format(os.path.split(partdepth)[1],\n tilel[0]*tileinterval,\n tilel[1]*tileinterval-1))\n if not arcpy.Exists(outtile):\n print('Mosaicking {}...'.format(outtile))\n arcpy.MosaicToNewRaster_management(input_rasters= smalltiles[tilel[0]:tilel[1]],\n output_location= os.path.split(outtile)[0],\n raster_dataset_name_with_extension= os.path.split(outtile)[1],\n number_of_bands= 1,\n mosaic_method='MAXIMUM',\n pixel_type='16_BIT_SIGNED')\n else:\n print('{} already exists...'.format(outtile))\n\n #Last remosaicking\n for dir in mosaicdict:\n tilel = getfilelist(mediumdirdict[dir], '.*[.]tif$')\n outmosaic =mosaicdict[dir]\n if tilel is not None and not arcpy.Exists(outmosaic):\n print('Processing {}...'.format(outmosaic))\n arcpy.MosaicToNewRaster_management(input_rasters=tilel,\n output_location=os.path.split(outmosaic)[0],\n raster_dataset_name_with_extension=os.path.split(outmosaic)[1],\n number_of_bands=1,\n mosaic_method='MAXIMUM',\n pixel_type='16_BIT_SIGNED')\n\n########################################## Compute aggregate texture values by weighted average #########################\n#No need for trapezoidal equation from 2019 onward (v2)) https://gis.stackexchange.com/questions/344070/depths-in-clay-content-map\nformatdf = pd.DataFrame.from_dict(mosaicdict, orient='index').reset_index()\nformatdf.columns = ['name', 'path']\nformatdf_format = pd.concat([formatdf,\n formatdf['name'].str.replace('(cm)|(_mean)', '').str.split(\"[_]\", expand = True)],\n axis=1).\\\n rename(columns={0: \"texture\", 1: \"horizon_top\", 2 : \"horizon_bottom\"}).\\\n sort_values(['texture', 'horizon_top'])\n\nformatdf_format[[\"horizon_top\", \"horizon_bottom\"]] = formatdf_format[[\"horizon_top\", \"horizon_bottom\"]].apply(pd.to_numeric)\nformatdf_format['thickness'] = formatdf_format[\"horizon_bottom\"] - formatdf_format[\"horizon_top\"]\n\ndef waverage_soilgrids(in_df, mindepth, maxdepth, outdir):\n #Subset horizons to only keep the requested depths\n df_sub = in_df[(in_df['horizon_top'] >= mindepth) & (in_df['horizon_bottom'] <= maxdepth)].\\\n sort_values(['horizon_top'])\n\n for texture, texturegroup in df_sub.groupby('texture'):\n out_sum = os.path.join(sgresgdb, '{0}_{1}_{2}_wsum'.format(texture, mindepth, maxdepth))\n out_average = os.path.join(sgresgdb, '{0}_{1}_{2}_wmean'.format(texture, mindepth, maxdepth))\n\n # for index, row in texturegroup.iterrows():\n # if not Raster(row['path']).hasRAT\n if not arcpy.Exists(out_average):\n print('Processing {}...'.format(out_average))\n\n if not arcpy.Exists(out_sum):\n WeightedSum(\n WSTable(\n [[row['path'], \"VALUE\", row['thickness']] for index, row in texturegroup.iterrows()])).save(out_sum)\n\n Int(Divide(Raster(out_sum), int(sum(texturegroup['thickness'])))+0.5).save(out_average) #Use eval? #isinstance(pd.Series)\n else:\n print('{} already exists...').format(out_average)\n\nwaverage_soilgrids(in_df=formatdf_format,\n mindepth=0,\n maxdepth=100,\n outdir=sgresgdb)\n\n##########################################Aggregate to HydroSHEDS resolution and extent ##############################\n#Get list of rasters to project\nsg_wmean = getfilelist(sgresgdb, '.*_wmean$')\n#The original cell size is exactly twice that of HydroSHEDS, so can project and snap, perform euclidean allocation, and then aggregate\n\n#Re-project and snap (as exactly half the resolution of HydroSHEDS)\narcpy.env.mask = arcpy.env.extent = hydrotemplate\nfor lyr in sg_wmean:\n outproj = os.path.join(sgresgdb, '{}proj'.format(lyr))\n if not arcpy.Exists(outproj):\n print('Processing {}...'.format(outproj))\n arcpy.ProjectRaster_management(lyr, outproj,\n out_coor_system=hydrotemplate,\n resampling_type='NEAREST',\n cell_size=1/480.0, #From Hengl et al. 2017\n )\n else:\n print('{} already exists...'.format(outproj))\n\n # Euclidean allocation in all NoData areas within 5 km of the coast from HydroSHEDS\n outnib = os.path.join(sgresgdb, '{}nibble2'.format(lyr))\n if not arcpy.Exists(outnib):\n print('Processing {}...'.format(outnib))\n try:\n arcpy.env.cellSize = arcpy.env.snapRaster = outproj\n outmismask = os.path.join(sgresgdb, '{}mismask'.format(lyr))\n Con((IsNull(outproj) | (outproj == 0)) & (~IsNull(coast_10pxband)),\n coast_10pxband).save(outmismask)\n\n # Perform euclidean allocation to those pixels\n Nibble(in_raster=Con(~IsNull(Raster(outmismask)), nodatavalue, outproj),\n # where mismask is not NoData (pixels for which outproj is NoData but coast_10pxband has data), assign nodatavalue (provided by user, not NoData), otherwise, keep outproj data (see Nibble tool)\n in_mask_raster=outproj,\n nibble_values='DATA_ONLY',\n nibble_nodata='PRESERVE_NODATA').save(outnib)\n\n except Exception:\n print(\"Exception in user code:\")\n traceback.print_exc(file=sys.stdout)\n arcpy.ResetEnvironments()\n\n else:\n print('{} already exists...'.format(outnib))\n\n arcpy.ResetEnvironments()\n\n #Aggregate pixel size to that of HydroSHEDS\n arcpy.env.mask = arcpy.env.extent = hydrotemplate\n outagg = os.path.join(sgresgdb, '{}agg2'.format(lyr))\n if not arcpy.Exists(outagg):\n print('Processing {}...'.format(outagg))\n Aggregate(in_raster=outnib,\n cell_factor=2,\n aggregation_type='MEAN',\n extent_handling='EXPAND',\n ignore_nodata='DATA').save(outagg)\n else:\n print('{} already exists...'.format(outagg))\n\n#Compute soil texture class based on soiltexture R package and then compute HYSOGS250m\n","sub_path":"format_SoilGrids250m.py","file_name":"format_SoilGrids250m.py","file_ext":"py","file_size_in_byte":10050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"581379860","text":"import urllib.request, json \nimport boto3\nimport datetime\nfrom decimal import Decimal\n\nsession = boto3.Session(profile_name=\"dbadmin\")\nappName = \"exchange_rate\"\ndynamodb = session.resource('dynamodb')\n\ndef get_rate(exchange_url):\n with urllib.request.urlopen(exchange_url) as url:\n data = json.loads(url.read().decode())\n return data['rates']['CHF']\n\ndef write_rate(rate):\n previousId = get_last_id()\n table = dynamodb.Table('exchange_rates')\n this_id = previousId + 1\n timestamp = int(datetime.datetime.now().timestamp())\n # one week expires\n expiration = timestamp + (7 * 24 * 60 * 60)\n table.put_item(Item={\n \"id\": this_id,\n \"rate\": Decimal(str(rate)),\n \"timestamp\": timestamp,\n \"expiration\": expiration,\n \"previousId\": previousId\n })\n write_last_id(this_id)\n return this_id, rate\n\ndef write_last_id(new_id):\n table = dynamodb.Table('constants')\n return table.update_item(\n Key={\n 'appName': appName\n },\n UpdateExpression='set appValue=:v',\n ExpressionAttributeValues={\n ':v': new_id\n }\n )\n\ndef get_last_id():\n table = dynamodb.Table('constants')\n response = table.get_item(Key={\"appName\":appName})\n return int(response[\"Item\"][\"appValue\"]) if \"Item\" in response else 0\n\ndef lambda_handler(event, context):\n id, rate = write_rate(get_rate(event['exchange_url']))\n return {\n 'statusCode': 200,\n 'rate': rate,\n 'id': id\n }\n\ndef main():\n # print(get_last_id().value)\n import sys\n id, r = write_rate(get_rate(sys.argv[1]))\n print(\"id:\", id, \"rate:\", r)\n\nif __name__=='__main__':\n main()","sub_path":"lambdas/check_xchange_rates.py","file_name":"check_xchange_rates.py","file_ext":"py","file_size_in_byte":1583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"385284690","text":"# GET ALL THE IMAGE FILES FROM THE TELEGRAM CHANNEL \n# t.me/coderbuzz or type coderbuzz on Telegram.\n\nfrom tkinter import *\nfrom tkinter import ttk\nfrom tkinter import messagebox\nfrom PIL import ImageTk, Image\nfrom datetime import date # To Show Date-Time\nimport webbrowser # To open Browser pip install pycopy-webbrowser\nimport googlesearch # To Run search Commands pip install google\nimport urllib.request # To Check Internet \n\n\nwindow=Tk()\nwindow.geometry(\"900x600\")\nwindow.resizable(False,False)\nwindow.title(\"Google Search Engine\") # Title\nbackground_image=ImageTk.PhotoImage(file=\"background.jpg\") #importing Background Image\nLabel(window,image=background_image,borderwidth=0).place(x=0,y=0)\n\n#################################################### ** Defining Functions ** ######################################################\ndef connect(host='http://google.com'):\n try:\n urllib.request.urlopen(host) \n return True\n except:\n return False\n\ndef openbrowser(url): # To open Browser\n webbrowser.open(url)\n\ndef search():\n query = search_box.get(\"1.0\",\"end-1c\")\n s = googlesearch.search(query, tld=\"co.in\", num=10, stop=1, pause=2)\n for j in s: \n webbrowser.open(j)\n\n#####################################################################################################################################\ntoday=date.today()\nLabel(window,text=today.strftime(\"%B %d, %Y\"),bg=\"#E8E9E4\",font=(\"Aerial\",10)).place(x=40,y=255)\n\n################################################## ** Google Search Engine ** #######################################################\ngoogle_logo=ImageTk.PhotoImage(Image.open(\"google logo.png\"))\nLabel(window,image=google_logo,borderwidth=0,bg=\"#E8E9E4\").place(x=190,y=160)\n\nsearch_box=Text(window,width=70,height=1,font=(\"Aerial\",11))\nsearch_box.place(x=40,y=280)\nsearch_box.focus_set()\nsearch_box.bind(\"\",lambda e:search())\n\nttk.Button(text=\"Google Search\",width=20,command=search,cursor=\"hand2\").place(x=120,y=320)\nttk.Button(text=\"I'm Feeling Lucky\",width=20,cursor=\"hand2\",command=lambda: openbrowser(\"https://www.google.com/doodles\")).place(x=410,y=320)\n\nLabel(text=\"Google offered in: \",bg=\"#E8E9E4\").place(x=90,y=370)\nLabel(text=\"हिन्दी বাংলা తెలుగు मराठी தமிழ் ગુજરાતી ಕನ್ನಡ മലയാളം ਪੰਜਾਬੀ\",fg=\"blue\",bg=\"#E8E9E4\").place(x=195,y=370)\n#####################################################################################################################################\n\n###################################################### ** Taskbar ** ################################################################\nTaskbar=Frame(window,bg=\"#E9EAE5\")\nTaskbar.place(x=0,y=0)\n\ngoogle_b=Button(Taskbar,text=\"Google\",bd=0,cursor=\"hand2\",bg=\"#E9EAE5\",font=(\"Aerial\",10),command=lambda: openbrowser(\"https://www.google.com/\"))\ngoogle_b.grid(row=0,column=1)\n\nyoutube_b=Button(Taskbar,text=\"Youtube\",bd=0,cursor=\"hand2\",bg=\"#E9EAE5\",font=(\"Aerial\",10),command=lambda: openbrowser(\"https://www.youtube.com/\"))\nyoutube_b.grid(row=0,column=3)\n\ngmail_b=Button(Taskbar,text=\"Gmail\",bd=0,cursor=\"hand2\",bg=\"#E9EAE5\",font=(\"Aerial\",10),command=lambda: openbrowser(\"https://www.gmail.com\"))\ngmail_b.grid(row=0,column=5)\n\ndrive_b=Button(Taskbar,text=\"G-Drive\",bd=0,cursor=\"hand2\",bg=\"#E9EAE5\",font=(\"Aerial\",10),command=lambda: openbrowser(\"https://www.drive.google.com\"))\ndrive_b.grid(row=0,column=7)\n\noutlook_b=Button(Taskbar,text=\"Outlook\",bd=0,cursor=\"hand2\",bg=\"#E9EAE5\",font=(\"Aerial\",10),command=lambda: openbrowser(\"https://outlook.live.com/owa/\"))\noutlook_b.grid(row=0,column=9)\n\nimages_b=Button(Taskbar,text=\"Images\",bd=0,cursor=\"hand2\",bg=\"#E8E9E4\",font=(\"Aerial\",10),command=lambda: openbrowser(\"https://www.google.co.in/imghp?hl=en&tab=wi&ogbl\"))\nimages_b.grid(row=0,column=11)\n\n#......................................................** Logo's of Apps **..........................................................\ngoogle_logo1=ImageTk.PhotoImage(Image.open(\"google_logo.png\"))\nLabel(Taskbar,image=google_logo1,borderwidth=0,bg=\"#E9EAE5\").grid(row=0,column=0,padx=5,pady=5)\n\nyoutube_logo1=ImageTk.PhotoImage(Image.open(\"youtube_logo.png\"))\nLabel(Taskbar,image=youtube_logo1,borderwidth=0,bg=\"#E9EAE5\").grid(row=0,column=2)\n\ngmail_logo1=ImageTk.PhotoImage(Image.open(\"gmail_logo.png\"))\nLabel(Taskbar,image=gmail_logo1,borderwidth=0,bg=\"#E9EAE5\").grid(row=0,column=4)\n\ngoogle_drive_logo1=ImageTk.PhotoImage(Image.open(\"google_drive_logo.png\"))\nLabel(Taskbar,image=google_drive_logo1,borderwidth=0,bg=\"#E9EAE5\").grid(row=0,column=6,padx=10)\n\noutlook_logo1=ImageTk.PhotoImage(Image.open(\"outlook_logo.png\"))\nLabel(Taskbar,image=outlook_logo1,borderwidth=0,bg=\"#E9EAE5\").grid(row=0,column=8,padx=10)\n\ngoogle_images_logo1=ImageTk.PhotoImage(Image.open(\"images_logo.png\"))\nLabel(Taskbar,image=google_images_logo1,borderwidth=0,bg=\"#E9EAE5\").grid(row=0,column=10,padx=10)\n#####################################################################################################################################\n\n#################################################### ** Game Button ** ##############################################################\ngame=ttk.Button(window,text=\"Play a Game!...\",cursor=\"hand2\",command=lambda: openbrowser(\"https://slither.io\"))\ngame.place(x=290,y=320)\n#####################################################################################################################################\n\n#####################################################################################################################################\nif connect()==False:\n messagebox.showerror(\"Warning\",\"Check Your Internet Connection\")\n window.destroy()\n\nwindow.mainloop()\n","sub_path":"Day21_Google Search Engine.py","file_name":"Day21_Google Search Engine.py","file_ext":"py","file_size_in_byte":5892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"147609055","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n@author: Anurag Kumar\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport sys\nimport time as t\nimport pickle\nimport math\nimport pandas as pd\n#%%\n\ndef read_traindata(train):\n #extracting train data\n train_file = open(train,'r',encoding = 'utf-8')\n train_data = [i.split() for i in train_file.read().split('\\n') if len(i) > 0]\n Xtrain = [x[2:] for x in train_data]\n Xtrain = [[int(y) for y in x[2:]] for x in train_data]\n ytrain = [x[1] for x in train_data]\n training_data = [(i,j) for i,j in zip(Xtrain,ytrain)]\n return Xtrain,ytrain,training_data\n \ndef read_testdata(test):\n #extracting test data\n test_file = open(test,'r',encoding = 'utf-8')\n test_data = [i.split() for i in test_file.read().split('\\n') if len(i) > 0]\n Xtest = [x[2:] for x in test_data]\n Xtest = [[int(y) for y in x[2:]] for x in test_data]\n ytest = [x[1] for x in test_data]\n test_label=[x[0] for x in test_data]\n return Xtest,ytest,test_label\n\nclass Tree(object):\n def __init__(self):\n self.data = None\n self.left = None\n self.right = None\n\nclass Random_Forest():\n \n def calc_entropy(self,data):\n if len(data) == 0:\n return 0\n pixel_dict={'0':0,'90':0,'180':0,'270':0}\n for i in data:\n pixel_dict[i[1]] += 1\n ent = 0\n for key in pixel_dict:\n prob = pixel_dict[key]/sum(pixel_dict.values())\n if prob == 0:\n continue\n val = -prob * np.log(prob)\n ent += val\n return ent\n \n def choose_node(self,data,root,num_split,entropy,pixel_list,depth,partition):\n pixels_left = [i for i in range(0,192) if i not in pixel_list]\n if num_split > depth or entropy==0 or len(pixels_left)==0 :\n data_dict = {}\n for i in data:\n if i[0][1] not in data_dict.keys():\n data_dict[i[1]] = 1\n else:\n data_dict[i[1]] += 1\n max_value = 0\n max_key = 0\n for key in data_dict.keys():\n if data_dict[key] > max_value:\n max_value = data_dict[key]\n max_key = key\n root.data = (\"Angle:\"+str(max_key),partition) \n return\n \n if len(data)==0:\n return \n\n entropy_final = sys.maxsize\n pixel_chosen = -1\n for p in pixels_left:\n for partition in [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200,210,220,230,240,250]:\n #splitting on this pixel\n left_data = [i for i in data if i[0][p] < partition]\n right_data = [i for i in data if i[0][p] >= partition]\n #calculating entropy for this split\n entropy = (len(left_data)/len(data)*self.calc_entropy(left_data))\\\n + (len(right_data)/len(data)*self.calc_entropy(right_data))\n #storing the best split\n if entropy_final > entropy:\n entropy_final = entropy\n pixel_chosen = p\n left= left_data\n right=right_data\n partition_chosen = partition\n #adding the pixel that was chosen to split above, so that this pixel is not chosen again\n pixel_list.append(p)\n #adding left and right trees\n root.left = Tree()\n root.right = Tree()\n root.data = (pixel_chosen,partition_chosen)\n #incrementing the level of tree\n num_split += 1\n #recursive call for left and right half\n self.choose_node(left,root.left,num_split,entropy_final,pixel_list,depth,partition_chosen) \n self.choose_node(right,root.right,num_split,entropy_final,pixel_list,depth,partition_chosen)\n #return the root of the tree\n return root\n \n def train(self,data,num_trees,depth):\n root_list = []\n x = num_trees\n while(num_trees>0):\n print(\"Tree:\",x-num_trees)\n root = Tree()\n pixel_list = []\n #taking a random sample set from training set\n random_samples = list(np.random.choice(np.arange(len(data)),2*len(data)//3))\n samples = [data[i] for i in random_samples]\n root = self.choose_node(samples,root,0,1,pixel_list,depth,-1)\n root_list.append(root)\n num_trees -= 1\n return root_list\n\n def make_pred(self,root_list,Xtest):\n pred = []\n for i in Xtest:\n label = []\n for root in root_list:\n node = root\n while(1):\n if node.data == None:\n label.append('NA')\n break\n elif len(str(node.data)) > 10:\n label.append(node.data[0][6:])\n break\n else: \n split_info = node.data\n if int(i[split_info[0]]) < split_info[1]:\n node = node.left\n else:\n node = node.right\n pred.append(label)\n pred_dict = {}\n for i in range(len(pred)):\n if i not in pred_dict.keys():\n pred_dict[i] = {}\n for j in pred[i]:\n if j not in pred_dict[i].keys():\n pred_dict[i][j] = 1\n else:\n pred_dict[i][j] += 1\n \n prediction = []\n for k in pred_dict.keys():\n prediction.append(max(pred_dict[k],key=lambda x: pred_dict[k][x]))\n return prediction \n\n\n#%%\nclass Adaboost():\n def weight_update(self,w,indices,error):\n for i in range (len(w)):\n w[i] = w[i]*error/(1.0000000000002651-error)\n sum_w = sum(w)\n w = [i/sum_w for i in w]\n return w\n \n def make_stump(self,pixel):\n root = Tree()\n root.data = (pixel,pixel+4)\n root.left = 1\n root.right = -1\n return root\n \n def most_common_label(self,data):\n label_dict = {'0':0,'90':0,'180':0,'270':0}\n for i in data:\n label_dict[i[1]] += 1\n return max(label_dict,key=lambda x: label_dict[x])\n \n def train(self,data,num_trees):\n l = len(data)\n w = [1/l for i in range(len(data))]\n print(sum(w))\n pixel_list = [i for i in range(0,192)]\n it = 0\n root_list = []\n alpha_list = []\n x = num_trees\n while(x>0): \n pixel = np.random.choice(pixel_list[:-4],1)[0]\n error = 0\n min_error = sys.maxsize\n for ornt in ['0','90','180','270']:\n mislabeled_indices = []\n for i in range(len(data)):\n if data[i][0][pixel]-data[i][0][pixel+4] < 40:\n if data[i][1] != ornt:\n mislabeled_indices.append(i)\n else:\n if data[i][1] == ornt:\n mislabeled_indices.append(i)\n #print('Indices:',len(mislabeled_indices))\n for i in mislabeled_indices:\n error += w[i]\n #print(error)\n if error > 1:\n error = 1\n w = self.weight_update(w,mislabeled_indices,min_error)\n root_list.append(self.make_stump(pixel))\n alpha_list.append(math.log((1.0000000000002651-error)/error))\n print(\"Stump\",it,\"done...\") \n it += 1\n x-=1\n return root_list,alpha_list \n \n def make_pred(self,data,all_roots,all_alpha):\n prediction = []\n votes = []\n roots_0 = [i for i in all_roots if all_roots.index(i)%4==0]\n roots_90 = [i for i in all_roots if all_roots.index(i)%4==1]\n roots_180 = [i for i in all_roots if all_roots.index(i)%4==2]\n roots_270 = [i for i in all_roots if all_roots.index(i)%4==3]\n \n alpha_0 = [i for i in range(len(all_alpha)) if i%4==0]\n alpha_90 = [i for i in range(len(all_alpha)) if i%4==1]\n alpha_180 = [i for i in range(len(all_alpha)) if i%4==2]\n alpha_270 = [i for i in range(len(all_alpha) )if i%4==3]\n \n for img in data:\n pred_votes = []\n score = 0\n votes = [0,0,0,0]\n for i in range(len(all_roots)):\n # print(i)\n if i%4 == 0:\n pix1,pix2 = roots_0[i//4].data[0],roots_0[i//4].data[1]\n diff = pix1-pix2\n if diff < 40:\n votes[0] += alpha_0[i//4]*roots_0[i//4].left\n else:\n votes[0] += alpha_0[i//4]*roots_0[i//4].right\n if i%4 == 1:\n pix1,pix2 = roots_90[i//4].data[0],roots_90[i//4].data[1]\n diff = pix1-pix2\n if diff < 40:\n votes[1] += alpha_90[i//4]*roots_90[i//4].left\n else:\n votes[1] += alpha_90[i//4]*roots_90[i//4].right\n if i%4 == 2:\n pix1,pix2 = roots_180[i//4].data[0],roots_180[i//4].data[1]\n diff = pix1-pix2\n if diff < 40:\n votes[2] += alpha_180[i//4]*roots_180[i//4].left\n else:\n votes[2] += alpha_180[i//4]*roots_180[i//4].right\n if i%4 == 3:\n pix1,pix2 = all_roots[i//4].data[0],all_roots[i//4].data[1]\n diff = pix1-pix2\n if diff < 40:\n votes[3] += alpha_270[i//4]*roots_270[i//4].left\n else:\n votes[3] += alpha_270[i//4]*roots_270[i//4].right\n if votes.index(max(votes)) == 0:\n prediction.append('0')\n elif votes.index(max(votes)) == 1:\n prediction.append('90')\n elif votes.index(max(votes)) == 2:\n prediction.append('180')\n else:\n prediction.append('270')\n pred_votes.append(votes)\n return prediction,votes\n\n#%%\nclass KNN():\n #This function calculates the euclidean distance between two points\n def eu_dis(self,point1, point2):\n distance=np.linalg.norm(np.array(point1)-np.array(point2))\n return distance\n\n \n #This function calculates the nearest k neighbor and predict the orientation of the testdata\n #by max votes approach.\n #for example if the value of K is 5 and the algorithm computes the 5 nearest training points \n #and then checks the orientation of these 5 points, consider the following is the orientation\n #of 5 data points (180,180,180,0,0), then predicted orientation of testpoint would be 180\n \n def make_pred(self,test,X,y,k):\n distances =[]\n #Calculating the euclidean distance, for given test data with all the traindataset.\n for i in range(len(Xtrain)):\n dist = self.eu_dis(test, X[i])\n distances.append((y[i], dist))\n orient_near=[]\n #this loop, find the minimun distance point and then pop out this value and then computes\n #the next minimum value and this process continues for K times\n for i in range(k):\n min_value= min(distances,key=lambda item:item[1])\n distances=[i for i in distances if i[1] > min_value[1]]\n orient_near.append(min_value[0])\n #Picking up the orientation based on max count. \n Pred = max(orient_near, key=orient_near.count) \n return Pred\n\n#%%\nmode = sys.argv[1]\ninp_filename = sys.argv[2]\nmodel_filename = sys.argv[3]\nmodel = sys.argv[4]\nif mode == 'train':\n Xtrain,ytrain,training_data = read_traindata(inp_filename)\n if model == 'nearest' or model == 'best':\n K = KNN()\n file = open(model_filename,\"w+\",encoding = 'utf-8')\n file.write('11')\n file.close\n if model == 'forest':\n R = Random_Forest() \n s = t.time()\n root_list = R.train(training_data,100,15)\n e = t.time()\n print('Training Time:',(e-s)/60,\"min\")\n file = open(model_filename,\"wb+\")\n pickle.dump(root_list,file)\n file.close()\n if model == 'adaboost': \n Ada = Adaboost()\n s = t.time()\n root,alpha = Ada.train(training_data,200)\n e = t.time()\n print(\"Training time:\",(e-s)/60,\"min\")\n file = open(model_filename,\"wb+\")\n data = [(i,j) for i,j in zip(root,alpha)]\n pickle.dump(data,file)\n file.close()\n\nif mode == 'test':\n Xtest,ytest,test_label = read_testdata(inp_filename)\n if model == 'nearest' or model == 'best':\n K=KNN()\n file = open(model_filename,\"r\",encoding =\"utf-8\")\n x = int(file.read())\n file.close()\n s = t.time()\n y_pred=[]\n count=0\n for i in range(len(Xtest)):\n pred=K.make_pred(Xtest[i],Xtrain,ytrain,x)\n y_pred.append(pred)\n e = t.time()\n file = open('Output.txt','w+',encoding = 'utf-8')\n for i in range(len(y_pred)):\n if y_pred[i] == ytest[i]:\n count += 1\n file.write(test_label[i] + \" \" + y_pred[i] + \"\\n\")\n file.close()\n print(\"Testing time:\",e-s,\"sec\") \n print(\"Accuracy:\",count/len(y_pred)*100,\"%\")\n if model == 'forest':\n R = Random_Forest()\n file=open(model_filename,\"rb\")\n root = pickle.load(file)\n file.close()\n s = t.time() \n y_pred = R.make_pred(root,Xtest)\n e = t.time()\n output = []\n count = 1\n #Opening file to write\n file = open(\"Output.txt\",\"w+\",encoding = \"utf-8\")\n for i in range(len(y_pred)):\n if y_pred[i] == ytest[i]:\n count += 1\n file.write(test_label[i] + \" \" + str(y_pred[i]) + \"\\n\")\n file.close()\n print(\"Testing time:\",e-s,\"sec\")\n print(\"Accuracy:\",count/len(y_pred)*100,\"%\")\n if model == 'adaboost':\n Ada = Adaboost()\n file=open(model_filename,\"rb\")\n val = pickle.load(file)\n root = [i[0] for i in val]\n alpha = [i[1] for i in val]\n file.close()\n s = t.time() \n y_pred,votes = Ada.make_pred(Xtest,root,alpha)\n e = t.time()\n output = []\n count = 1\n #Opening file to write\n file = open(\"Output.txt\",\"w+\",encoding = \"utf-8\")\n for i in range(len(y_pred)):\n if y_pred[i] == ytest[i]:\n count += 1\n file.write(test_label[i] + \" \" + str(y_pred[i]) + \"\\n\")\n file.close()\n print(\"Testing time:\",e-s,\"sec\")\n print(\"Accuracy:\",count/len(y_pred)*100,\"%\")","sub_path":"Extracting Picture Orientation/orient.py","file_name":"orient.py","file_ext":"py","file_size_in_byte":14977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"22567958","text":"import time\nimport pkg_resources\nimport os\nimport re\nimport sys\n\nimport Globals\nfrom App.ImageFile import ImageFile, guess_content_type\nfrom App.Common import rfc1123_date\nfrom App.special_dtml import DTMLFile, defaultBindings\nfrom Products.PageTemplates.PageTemplateFile import PageTemplateFile\nfrom Products.PageTemplates.PageTemplateFile import XML_PREFIX_MAX_LENGTH\nfrom Products.PageTemplates.PageTemplateFile import sniff_type\nfrom zLOG import LOG\nfrom zLOG import ERROR\nfrom Globals import DevelopmentMode\n\nclass PageTemplateResource(PageTemplateFile):\n\n def __init__(self, path, module_globals=None, module=None, **kw):\n \"\"\"Load a PT from a resource which may be an egg package or a file.\n path is the relative path within the product package. You can provide\n the package module by passing in its globals() dictionary in\n module_globals or you can provide a dotted module path as module\n \"\"\"\n if module_globals is not None and module is not None:\n raise ValueError(\n \"Cannot specify both module_globals and module\")\n if module is None:\n if module_globals is not None:\n module = module_globals['__name__']\n else:\n raise ValueError(\n \"Either module_globals or module must be specified\")\n self.ZBindings_edit(self._default_bindings)\n name = kw.get('__name__')\n if name:\n self._need__name__ = 0\n self.__name__ = name\n else:\n self.__name__ = os.path.basename(path)\n self.path = path\n self.module = module\n self.zipped = is_zipped(module)\n self.mtime = 0\n\n def _cook_check(self):\n if self.mtime and not self.zipped and not DevelopmentMode:\n return\n __traceback_info__ = (self.path, self.module)\n f = pkg_resources.resource_stream(self.module, self.path)\n mtime = 0\n\n if not self.zipped and self.mtime and hasattr(f.name):\n try:\n mtime = os.path.getmtime(f.name)\n if mtime == self.mtime:\n # File has already been cooked and has not changed\n return\n except OSError:\n # Can't determine the mod time, Oh well\n pass\n try:\n text = f.read(XML_PREFIX_MAX_LENGTH)\n except:\n f.close()\n raise\n mime_type = sniff_type(text)\n # Punting on reading html in text mode, package resources\n # only supports binary mode via its api\n text += f.read()\n f.close()\n self.pt_edit(text, mime_type)\n self._cook()\n if self._v_errors:\n LOG('PageTemplateFile', ERROR, 'Error in template',\n '\\n'.join(self._v_errors))\n return\n self.mtime = mtime\n\n\nclass ImageResource(ImageFile):\n\n def __init__(self, path, module_globals=None, module=None, **kw):\n if module_globals is not None and module is not None:\n raise ValueError(\n \"Cannot specify both module_globals and module\")\n if module is None:\n if module_globals is not None:\n module = module_globals['__name__']\n else:\n raise ValueError(\n \"Either module_globals or module must be specified\")\n self.path = path\n self.module = module\n resource = pkg_resources.resource_stream(module, path)\n\n data = resource.read()\n resource.close()\n content_type, enc=guess_content_type(path, data)\n if content_type:\n self.content_type=content_type\n else:\n self.content_type='image/%s' % path[path.rfind('.')+1:]\n self.__name__ = os.path.basename(path)\n if not is_zipped(module):\n try:\n self.lmt = os.path.getmtime(resource.name)\n except (OSError, AttributeError):\n self.lmt=time.time()\n else:\n self.lmt=time.time()\n self.lmh=rfc1123_date(self.lmt)\n\n if DevelopmentMode:\n # In development mode, a shorter time is handy\n max_age = 60 # One minute\n else:\n # A longer time reduces latency in production mode\n max_age = 3600 # One hour\n self.cch = 'public,max-age=%d' % max_age\n\n def read(self):\n return pkg_resources.resource_string(self.module, self.path)\n\n # If ImageFile had a read() method, we wouldn't need to override index_html\n def index_html(self, REQUEST, RESPONSE):\n \"\"\"Default document\"\"\"\n # HTTP If-Modified-Since header handling. This is duplicated\n # from OFS.Image.Image - it really should be consolidated\n # somewhere...\n RESPONSE.setHeader('Content-Type', self.content_type)\n RESPONSE.setHeader('Last-Modified', self.lmh)\n RESPONSE.setHeader('Cache-Control', self.cch)\n header=REQUEST.get_header('If-Modified-Since', None)\n if header is not None:\n header=header.split(';')[0]\n # Some proxies seem to send invalid date strings for this\n # header. If the date string is not valid, we ignore it\n # rather than raise an error to be generally consistent\n # with common servers such as Apache (which can usually\n # understand the screwy date string as a lucky side effect\n # of the way they parse it).\n try: mod_since=long(DateTime(header).timeTime())\n except: mod_since=None\n if mod_since is not None:\n if getattr(self, 'lmt', None):\n last_mod = long(self.lmt)\n else:\n last_mod = long(0)\n if last_mod > 0 and last_mod <= mod_since:\n RESPONSE.setStatus(304)\n return ''\n\n return self.read()\n\n\nclass DTMLResource(DTMLFile):\n\n def __init__(self, path, module_globals=None, module=None, **kw):\n if module_globals is not None and module is not None:\n raise ValueError(\n \"Cannot specify both module_globals and module\")\n if module is None:\n if module_globals is not None:\n module = module_globals['__name__']\n else:\n raise ValueError(\n \"Either module_globals or module must be specified\")\n #from DTMLFile.__init__(self, name, _prefix, **kw)\n self.ZBindings_edit(defaultBindings)\n self._setFuncSignature()\n\n #from ClassicHTMLFile.__init__(self, name, _prefix, **kw)\n path_with_ext = path + '.dtml'\n if not kw.has_key('__name__'):\n kw['__name__'] = os.path.basename(path)\n\n #from FileMixin.__init__(self, *args, **kw)\n self.raw = (module, path_with_ext)\n self.initvars(None, kw)\n self.setName(kw['__name__'])\n self.zipped = is_zipped(module)\n\n def read_raw(self):\n if self.edited_source:\n data = self.edited_source\n elif not self.raw:\n data = ''\n else:\n data = pkg_resources.resource_stream(*self.raw).read()\n return data\n \n def _cook_check(self):\n if DevelopmentMode and not self.zipped:\n __traceback_info__ = str(self.raw)\n package, path = self.raw\n f = pkg_resources.resource_stream(package, path)\n try:\n mtime = os.path.getmtime(f.name)\n except (OSError, AttributeError):\n mtime = 0\n if mtime != self._v_last_read:\n self.cook()\n self._v_last_read=mtime\n elif not hasattr(self,'_v_cooked'):\n try: changed = self.__changed__()\n except: changed=1\n self.cook()\n if not changed:\n self.__changed__(0)\n\ndef is_zipped(package_name):\n \"\"\"Return true if the given named package is zipped, false if it is a\n plain old filesystem package\n \"\"\"\n provider = pkg_resources.get_provider(package_name)\n return isinstance(provider, pkg_resources.ZipProvider)\n\n","sub_path":"Products.Basket/tags/r0_2/resource.py","file_name":"resource.py","file_ext":"py","file_size_in_byte":8161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"547816584","text":"# Importamos as bibliotecas:\nimport json, pymysql, datetime, pytz, dateutil.parser, re\nfrom datetime import date\n\n# Abrimos uma conexão com o banco de dados:\nconexao = pymysql.connect(host='', db='', user='', passwd='')\n\n# Cria um cursor:\ncursor = conexao.cursor()\n\nemail = input(\"Digite seu e-mail: \")\nsenha = input(\"Digite a senha: \")\n\n# Executa o comando:\nsql = \"sua_query\"\nval = (email, senha)\n\n# Recupera o resultado:\nexecut = cursor.execute(sql, val)\nresultado = cursor.fetchall()\n\n# Mostrando o tamanho do retorno da query (quantidade de registros, seguindo a parametrização)\ntamanho = len(resultado)\nprint(\"Quantidade de registros: \", tamanho)# Mostrando na tela o valor da contagem\n\nrows = list(resultado)# Definendo \"rows\" como uma lista do resultado da query\n\n# Convertendo Datetime para String, possibilitando a serialização dos dados\ndef converter(o):\n if isinstance(o, datetime.datetime):\n return o.__str__()\n\ndata_atual = date.today()#Obtendo a data do dia em questão\nprint(\"Data de hoje: \", data_atual)\n\n\nx = 0# variavel x = 0\n# Abrindo o arquivo \"result.json\" para gravar os dados da query\nif resultado:\n json.dumps(rows, default=converter, indent=4, separators=(\", \", \" : \"))# Gravando no arquivo os valores buscados (JSON)\n print(\"E-mail: \", email)# Retornando o e-mail da conta\n\n #Retornando os numeros de serie da conta em contexto\n num_elementos_lista = len(rows)\n while(x < num_elementos_lista):\n print(\"\\nNúmeros de serie: \", rows[x][4])\n print(\"Dias: \", rows[x][6])\n print(\"Data de ativação: \", rows[x][7])\n \n dias = rows[x][6]\n data_ativacao = rows[x][7]\n \n liberado = True\n \n # Data atual: 07/05/2019 - Data de ativação: 01/01/2019 = 120 dias\n datasresult = (data_atual - data_ativacao).days\n print(\"Diferença entre as datas: \", datasresult)\n\n datafinal = datasresult - int(dias)\n print(\"Data final: \", datafinal) \n \n if datasresult < int(dias):\n print(\"Liberado.\")\n else: \n print(\"Expirado.\")\n\n x+=1\nelse:\n json.dump(\"Sem registro!\")\n print(\"Não há registro ou chave ativa segundo os dados passados.\")\n\n \n\nconexao.close()# Fechando conexão","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"300822910","text":"import argparse\nimport os, sys\nimport math\nimport time\nimport tabulate\n\nimport torch\nimport tqdm\nimport torch.nn.functional as F\nfrom torch import nn, distributions\n\nimport numpy as np\n\nfrom swag import data, models, utils, losses\nfrom swag.posteriors.vinf_model import VINFModel, ELBO_NF\nfrom swag.posteriors.realnvp import RealNVP, construct_flow\nfrom swag.posteriors import SWAG\nfrom swag.posteriors.proj_model import Subspace\n#from swag.posteriors.vi_model import VIModel, ELBO\n\n\ndef nll(outputs, labels):\n labels = labels.astype(int)\n idx = (np.arange(labels.size), labels)\n ps = outputs[idx]\n nll = -np.sum(np.log(ps))\n return nll\n\n\nparser = argparse.ArgumentParser(description='Subspace VI')\nparser.add_argument('--dir', type=str, default=None, required=True, help='training directory (default: None)')\nparser.add_argument('--log_fname', type=str, default=None, required=True, help='file name for logging')\n\nparser.add_argument('--dataset', type=str, default='CIFAR10', help='dataset name (default: CIFAR10)')\nparser.add_argument('--data_path', type=str, default=None, required=True, metavar='PATH',\n help='path to datasets location (default: None)')\n\nparser.add_argument('--use_test', dest='use_test', action='store_true',\n help='use test dataset instead of validation (default: False)')\nparser.add_argument('--split_classes', type=int, default=None)\nparser.add_argument('--batch_size', type=int, default=128, metavar='N', help='input batch size (default: 128)')\nparser.add_argument('--num_workers', type=int, default=4, metavar='N', help='number of workers (default: 4)')\nparser.add_argument('--model', type=str, default=None, required=True, metavar='MODEL',\n help='model name (default: None)')\n\nparser.add_argument('--epochs', type=int, default=100, metavar='N', help='number of epochs (default: 100')\n\nparser.add_argument('--temperature', type=float, default=1., required=True, \n metavar='N', help='Temperature (default: 1.')\nparser.add_argument('--no_mu', action='store_true', help='Do not learn the mean of posterior')\n\nparser.add_argument('--rank', type=int, default=2, metavar='N', help='approximation rank (default: 2')\nparser.add_argument('--subspace', choices=['covariance', 'pca', 'freq_dir'], default='covariance')\n\nparser.add_argument('--prior_std', type=float, default=20.0, help='std of the prior distribution')\nparser.add_argument('--init_std', type=float, default=1.0, help='initial std of the variational distribution')\n\nparser.add_argument('--checkpoint', type=str, default=None, required=True, help='path to SWAG checkpoint')\n\nparser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)')\n\nparser.add_argument('--eval_ensemble', action='store_true', help='store schedule')\n\n\nargs = parser.parse_args()\n\nargs.device = None\nif torch.cuda.is_available():\n args.device = torch.device('cuda')\nelse:\n args.device = torch.device('cpu')\n\nprint('Preparing directory %s' % args.dir)\nos.makedirs(args.dir, exist_ok=True)\nwith open(os.path.join(args.dir, 'command.sh'), 'w') as f:\n f.write(' '.join(sys.argv))\n f.write('\\n')\n\ntorch.backends.cudnn.benchmark = True\ntorch.manual_seed(args.seed)\ntorch.cuda.manual_seed(args.seed)\n\nprint('Using model %s' % args.model)\nmodel_cfg = getattr(models, args.model)\n\nprint('Loading dataset %s from %s' % (args.dataset, args.data_path))\nloaders, num_classes = data.loaders(\n args.dataset,\n args.data_path,\n args.batch_size,\n args.num_workers,\n model_cfg.transform_train,\n model_cfg.transform_test,\n use_validation=not args.use_test,\n split_classes=args.split_classes\n)\n\nprint('Preparing model')\nprint(*model_cfg.args)\n\nswag_model = SWAG(\n model_cfg.base,\n num_classes=num_classes,\n subspace_type='pca',\n subspace_kwargs={\n 'max_rank': 20,\n 'pca_rank': args.rank,\n },\n *model_cfg.args,\n **model_cfg.kwargs\n)\nswag_model.to(args.device)\n\nprint('Loading: %s' % args.checkpoint)\nckpt = torch.load(args.checkpoint)\nswag_model.load_state_dict(ckpt['state_dict'], strict=False)\n\nswag_model.set_swa()\nprint(\"SWA:\", utils.eval(loaders[\"train\"], swag_model, criterion=losses.cross_entropy))\n\nmean, var, cov_factor = swag_model.get_space()\nsubspace = Subspace(mean, cov_factor)\n\nprint(torch.norm(cov_factor, dim=1))\n\nnvp_flow = construct_flow(cov_factor.shape[0], device=torch.cuda.current_device())\n\nvi_model = VINFModel(\n base=model_cfg.base,\n subspace=subspace,\n flow=nvp_flow,\n prior_log_sigma=math.log(args.prior_std) + math.log(args.temperature) / 2,\n num_classes=num_classes,\n *model_cfg.args,\n **model_cfg.kwargs\n)\n\nvi_model = vi_model.cuda()\nprint(utils.eval(loaders[\"train\"], vi_model, criterion=losses.cross_entropy))\n\nelbo = ELBO_NF(losses.cross_entropy_output, len(loaders[\"train\"].dataset), args.temperature)\n\noptimizer = torch.optim.Adam([param for param in vi_model.parameters()], lr=0.01)\n\nprintf, logfile = utils.get_logging_print(os.path.join(args.dir, args.log_fname + '-%s.txt'))\nprint('Saving logs to: %s' % logfile)\ncolumns = ['ep', 'acc', 'loss', 'kl', 'nll']\n\nfor epoch in range(args.epochs):\n train_res = utils.train_epoch(loaders['train'], vi_model, elbo, optimizer)\n values = ['%d/%d' % (epoch + 1, args.epochs), train_res['accuracy'], train_res['loss'],\n train_res['stats']['kl'], train_res['stats']['nll']]\n if epoch == 0:\n printf(tabulate.tabulate([values], columns, tablefmt='simple', floatfmt='8.4f'))\n else:\n printf(tabulate.tabulate([values], columns, tablefmt='plain', floatfmt='8.4f').split('\\n')[1])\n\nutils.save_checkpoint(\n args.dir,\n epoch,\n name='vi_rnvp',\n state_dict=vi_model.state_dict()\n)\n\nif args.eval_ensemble:\n\n num_samples = 30\n\n predictions = np.zeros((len(loaders['test'].dataset), num_classes))\n targets = np.zeros(len(loaders['test'].dataset))\n \n printf, logfile = utils.get_logging_print(os.path.join(args.dir, args.log_fname + '-%s.txt'))\n print('Saving logs to: %s' % logfile)\n columns = ['iter ens', 'acc', 'nll']\n \n for i in range(num_samples):\n # utils.bn_update(loaders['train'], model, subset=args.bn_subset)\n vi_model.eval()\n k = 0\n for input, target in tqdm.tqdm(loaders['test']):\n input = input.cuda(non_blocking=True)\n torch.manual_seed(i)\n \n output = vi_model(input)\n \n with torch.no_grad():\n predictions[k:k+input.size()[0]] += F.softmax(output, dim=1).cpu().numpy()\n targets[k:(k+target.size(0))] = target.numpy()\n k += input.size()[0]\n \n values = ['%d/%d' % (i + 1, num_samples), np.mean(np.argmax(predictions, axis=1) == targets), nll(predictions / (i+1), targets)]\n if i == 0:\n printf(tabulate.tabulate([values], columns, tablefmt='simple', floatfmt='8.4f'))\n else:\n printf(tabulate.tabulate([values], columns, tablefmt='plain', floatfmt='8.4f').split('\\n')[1])\n\n predictions /= num_samples\n","sub_path":"experiments/subspaces/subspace_realnvp.py","file_name":"subspace_realnvp.py","file_ext":"py","file_size_in_byte":7064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"147098894","text":"# This file is part of QuTiP: Quantum Toolbox in Python.\n#\n# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.\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:\n#\n# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. 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#\n# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names\n# of its contributors may be used to endorse or promote products derived\n# from 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 A\n# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# HOLDER 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\"\"\"\nThis module contains functions that implement the GRAPE algorithm for\ncalculating pulse sequences for quantum systems.\n\"\"\"\n\n__all__ = ['plot_grape_control_fields',\n 'grape_unitary', 'cy_grape_unitary', 'grape_unitary_adaptive']\n\nimport warnings\nimport time\nimport numpy as np\nfrom scipy.interpolate import interp1d\nimport scipy.sparse as sp\n\nfrom qutip.qobj import Qobj\nfrom qutip.ui.progressbar import BaseProgressBar\nfrom qutip.control.cy_grape import cy_overlap, cy_grape_inner\nfrom qutip.qip.gates import gate_sequence_product\n\nimport qutip.logging\nlogger = qutip.logging.get_logger()\n\n\nclass GRAPEResult:\n \"\"\"\n Class for representing the result of a GRAPE simulation.\n\n Attributes\n ----------\n u : array\n GRAPE control pulse matrix.\n\n H_t : time-dependent Hamiltonian\n The time-dependent Hamiltonian that realize the GRAPE pulse sequence.\n\n U_f : Qobj\n The final unitary transformation that is realized by the evolution\n of the system with the GRAPE generated pulse sequences.\n \"\"\"\n def __init__(self, u=None, H_t=None, U_f=None):\n\n self.u = u\n self.H_t = H_t\n self.U_f = U_f\n\n\ndef plot_grape_control_fields(times, u, labels, uniform_axes=False):\n \"\"\"\n Plot a series of plots showing the GRAPE control fields given in the\n given control pulse matrix u.\n\n Parameters\n ----------\n times : array\n Time coordinate array.\n\n u : array\n Control pulse matrix.\n\n labels : list\n List of labels for each control pulse sequence in the control pulse\n matrix.\n\n uniform_axes : bool\n Whether or not to plot all pulse sequences using the same y-axis scale.\n \"\"\"\n import matplotlib.pyplot as plt\n\n R, J, M = u.shape\n\n fig, axes = plt.subplots(J, 1, figsize=(8, 2 * J), squeeze=False)\n\n y_max = abs(u).max()\n\n for r in range(R):\n for j in range(J):\n\n if r == R - 1:\n lw, lc, alpha = 2.0, 'k', 1.0\n\n axes[j, 0].set_ylabel(labels[j], fontsize=18)\n axes[j, 0].set_xlabel(r'$t$', fontsize=18)\n axes[j, 0].set_xlim(0, times[-1])\n\n else:\n lw, lc, alpha = 0.5, 'b', 0.25\n\n axes[j, 0].step(times, u[r, j, :], lw=lw, color=lc, alpha=alpha)\n\n if uniform_axes:\n axes[j, 0].set_ylim(-y_max, y_max)\n\n fig.tight_layout()\n\n return fig, axes\n\n\ndef _overlap(A, B):\n return (A.dag() * B).tr() / A.shape[0]\n # return cy_overlap(A.data, B.data)\n\n\ndef grape_unitary(U, H0, H_ops, R, times, eps=None, u_start=None,\n u_limits=None, interp_kind='linear', use_interp=False,\n alpha=None, beta=None, phase_sensitive=True,\n progress_bar=BaseProgressBar()):\n \"\"\"\n Calculate control pulses for the Hamiltonian operators in H_ops so that the\n unitary U is realized.\n\n Experimental: Work in progress.\n\n Parameters\n ----------\n U : Qobj\n Target unitary evolution operator.\n\n H0 : Qobj\n Static Hamiltonian (that cannot be tuned by the control fields).\n\n H_ops: list of Qobj\n A list of operators that can be tuned in the Hamiltonian via the\n control fields.\n\n R : int\n Number of GRAPE iterations.\n\n time : array / list\n Array of time coordinates for control pulse evalutation.\n\n u_start : array\n Optional array with initial control pulse values.\n\n Returns\n -------\n Instance of GRAPEResult, which contains the control pulses calculated\n with GRAPE, a time-dependent Hamiltonian that is defined by the\n control pulses, as well as the resulting propagator.\n \"\"\"\n\n if eps is None:\n eps = 0.1 * (2 * np.pi) / (times[-1])\n\n M = len(times)\n J = len(H_ops)\n\n u = np.zeros((R, J, M))\n\n if u_limits and len(u_limits) != 2:\n raise ValueError(\"u_limits must be a list with two values\")\n\n if u_limits:\n warnings.warn(\"Caution: Using experimental feature u_limits\")\n\n if u_limits and u_start:\n # make sure that no values in u0 violates the u_limits conditions\n u_start = np.array(u_start)\n u_start[u_start < u_limits[0]] = u_limits[0]\n u_start[u_start > u_limits[1]] = u_limits[1]\n\n if u_start is not None:\n for idx, u0 in enumerate(u_start):\n u[0, idx, :] = u0\n\n if beta:\n warnings.warn(\"Causion: Using experimental feature time-penalty\")\n\n progress_bar.start(R)\n for r in range(R - 1):\n progress_bar.update(r)\n\n dt = times[1] - times[0]\n\n if use_interp:\n ip_funcs = [interp1d(times, u[r, j, :], kind=interp_kind,\n bounds_error=False, fill_value=u[r, j, -1])\n for j in range(J)]\n\n def _H_t(t, args=None):\n return H0 + sum([float(ip_funcs[j](t)) * H_ops[j]\n for j in range(J)])\n\n U_list = [(-1j * _H_t(times[idx]) * dt).expm()\n for idx in range(M-1)]\n\n else:\n def _H_idx(idx):\n return H0 + sum([u[r, j, idx] * H_ops[j] for j in range(J)])\n\n U_list = [(-1j * _H_idx(idx) * dt).expm() for idx in range(M-1)]\n\n U_f_list = []\n U_b_list = []\n\n U_f = 1\n U_b = 1\n for n in range(M - 1):\n\n U_f = U_list[n] * U_f\n U_f_list.append(U_f)\n\n U_b_list.insert(0, U_b)\n U_b = U_list[M - 2 - n].dag() * U_b\n\n for j in range(J):\n for m in range(M-1):\n P = U_b_list[m] * U\n Q = 1j * dt * H_ops[j] * U_f_list[m]\n\n if phase_sensitive:\n du = - _overlap(P, Q)\n else:\n du = - 2 * _overlap(P, Q) * _overlap(U_f_list[m], P)\n\n if alpha:\n # penalty term for high power control signals u\n du += -2 * alpha * u[r, j, m] * dt\n\n if beta:\n # penalty term for late control signals u\n du += -2 * beta * m * u[r, j, m] * dt\n\n u[r + 1, j, m] = u[r, j, m] + eps * du.real\n\n if u_limits:\n if u[r + 1, j, m] < u_limits[0]:\n u[r + 1, j, m] = u_limits[0]\n elif u[r + 1, j, m] > u_limits[1]:\n u[r + 1, j, m] = u_limits[1]\n\n u[r + 1, j, -1] = u[r + 1, j, -2]\n\n if use_interp:\n ip_funcs = [interp1d(times, u[R - 1, j, :], kind=interp_kind,\n bounds_error=False, fill_value=u[R - 1, j, -1])\n for j in range(J)]\n\n H_td_func = [H0] + [[H_ops[j], lambda t, args, j=j: ip_funcs[j](t)]\n for j in range(J)]\n else:\n H_td_func = [H0] + [[H_ops[j], u[-1, j, :]] for j in range(J)]\n\n progress_bar.finished()\n\n # return U_f_list[-1], H_td_func, u\n return GRAPEResult(u=u, U_f=U_f_list[-1], H_t=H_td_func)\n\n\ndef cy_grape_unitary(U, H0, H_ops, R, times, eps=None, u_start=None,\n u_limits=None, interp_kind='linear', use_interp=False,\n alpha=None, beta=None, phase_sensitive=True,\n progress_bar=BaseProgressBar()):\n \"\"\"\n Calculate control pulses for the Hamitonian operators in H_ops so that the\n unitary U is realized.\n\n Experimental: Work in progress.\n\n Parameters\n ----------\n U : Qobj\n Target unitary evolution operator.\n\n H0 : Qobj\n Static Hamiltonian (that cannot be tuned by the control fields).\n\n H_ops: list of Qobj\n A list of operators that can be tuned in the Hamiltonian via the\n control fields.\n\n R : int\n Number of GRAPE iterations.\n\n time : array / list\n Array of time coordinates for control pulse evalutation.\n\n u_start : array\n Optional array with initial control pulse values.\n\n Returns\n -------\n Instance of GRAPEResult, which contains the control pulses calculated\n with GRAPE, a time-dependent Hamiltonian that is defined by the\n control pulses, as well as the resulting propagator.\n \"\"\"\n\n if eps is None:\n eps = 0.1 * (2 * np.pi) / (times[-1])\n\n M = len(times)\n J = len(H_ops)\n\n u = np.zeros((R, J, M))\n\n H_ops_data = [H_op.data for H_op in H_ops]\n\n if u_limits and len(u_limits) != 2:\n raise ValueError(\"u_limits must be a list with two values\")\n\n if u_limits:\n warnings.warn(\"Causion: Using experimental feature u_limits\")\n\n if u_limits and u_start:\n # make sure that no values in u0 violates the u_limits conditions\n u_start = np.array(u_start)\n u_start[u_start < u_limits[0]] = u_limits[0]\n u_start[u_start > u_limits[1]] = u_limits[1]\n\n if u_limits:\n use_u_limits = 1\n u_min = u_limits[0]\n u_max = u_limits[1]\n else:\n use_u_limits = 0\n u_min = 0.0\n u_max = 0.0\n\n if u_start is not None:\n for idx, u0 in enumerate(u_start):\n u[0, idx, :] = u0\n\n if beta:\n warnings.warn(\"Causion: Using experimental feature time-penalty\")\n\n alpha_val = alpha if alpha else 0.0\n beta_val = beta if beta else 0.0\n\n progress_bar.start(R)\n for r in range(R - 1):\n progress_bar.update(r)\n\n dt = times[1] - times[0]\n\n if use_interp:\n ip_funcs = [interp1d(times, u[r, j, :], kind=interp_kind,\n bounds_error=False, fill_value=u[r, j, -1])\n for j in range(J)]\n\n def _H_t(t, args=None):\n return H0 + sum([float(ip_funcs[j](t)) * H_ops[j]\n for j in range(J)])\n\n U_list = [(-1j * _H_t(times[idx]) * dt).expm().data\n for idx in range(M-1)]\n\n else:\n def _H_idx(idx):\n return H0 + sum([u[r, j, idx] * H_ops[j] for j in range(J)])\n\n U_list = [(-1j * _H_idx(idx) * dt).expm().data\n for idx in range(M-1)]\n\n U_f_list = []\n U_b_list = []\n\n U_f = 1\n U_b = sp.eye(*(U.shape))\n for n in range(M - 1):\n\n U_f = U_list[n] * U_f\n U_f_list.append(U_f)\n\n U_b_list.insert(0, U_b)\n U_b = U_list[M - 2 - n].T.conj().tocsr() * U_b\n\n cy_grape_inner(U.data, u, r, J, M, U_b_list, U_f_list, H_ops_data,\n dt, eps, alpha_val, beta_val, phase_sensitive,\n use_u_limits, u_min, u_max)\n\n if use_interp:\n ip_funcs = [interp1d(times, u[R - 1, j, :], kind=interp_kind,\n bounds_error=False, fill_value=u[R - 1, j, -1])\n for j in range(J)]\n\n H_td_func = [H0] + [[H_ops[j], lambda t, args, j=j: ip_funcs[j](t)]\n for j in range(J)]\n else:\n H_td_func = [H0] + [[H_ops[j], u[-1, j, :]] for j in range(J)]\n\n progress_bar.finished()\n\n return GRAPEResult(u=u, U_f=Qobj(U_f_list[-1], dims=U.dims),\n H_t=H_td_func)\n\n\ndef grape_unitary_adaptive(U, H0, H_ops, R, times, eps=None, u_start=None,\n u_limits=None, interp_kind='linear',\n use_interp=False, alpha=None, beta=None,\n phase_sensitive=False, overlap_terminate=1.0,\n progress_bar=BaseProgressBar()):\n \"\"\"\n Calculate control pulses for the Hamiltonian operators in H_ops so that\n the unitary U is realized.\n\n Experimental: Work in progress.\n\n Parameters\n ----------\n U : Qobj\n Target unitary evolution operator.\n\n H0 : Qobj\n Static Hamiltonian (that cannot be tuned by the control fields).\n\n H_ops: list of Qobj\n A list of operators that can be tuned in the Hamiltonian via the\n control fields.\n\n R : int\n Number of GRAPE iterations.\n\n time : array / list\n Array of time coordinates for control pulse evalutation.\n\n u_start : array\n Optional array with initial control pulse values.\n\n Returns\n -------\n Instance of GRAPEResult, which contains the control pulses calculated\n with GRAPE, a time-dependent Hamiltonian that is defined by the\n control pulses, as well as the resulting propagator.\n \"\"\"\n\n if eps is None:\n eps = 0.1 * (2 * np.pi) / (times[-1])\n\n eps_vec = np.array([eps / 2, eps, 2 * eps])\n eps_log = np.zeros(R)\n overlap_log = np.zeros(R)\n\n best_k = 0\n _k_overlap = np.array([0.0, 0.0, 0.0])\n\n M = len(times)\n J = len(H_ops)\n K = len(eps_vec)\n Uf = [None for _ in range(K)]\n\n u = np.zeros((R, J, M, K))\n\n if u_limits and len(u_limits) != 2:\n raise ValueError(\"u_limits must be a list with two values\")\n\n if u_limits:\n warnings.warn(\"Causion: Using experimental feature u_limits\")\n\n if u_limits and u_start:\n # make sure that no values in u0 violates the u_limits conditions\n u_start = np.array(u_start)\n u_start[u_start < u_limits[0]] = u_limits[0]\n u_start[u_start > u_limits[1]] = u_limits[1]\n\n if u_start is not None:\n for idx, u0 in enumerate(u_start):\n for k in range(K):\n u[0, idx, :, k] = u0\n\n if beta:\n warnings.warn(\"Causion: Using experimental feature time-penalty\")\n\n if phase_sensitive:\n _fidelity_function = lambda x: x\n else:\n _fidelity_function = lambda x: abs(x) ** 2\n\n best_k = 1\n _r = 0\n _prev_overlap = 0\n\n progress_bar.start(R)\n for r in range(R - 1):\n progress_bar.update(r)\n\n _r = r\n eps_log[r] = eps_vec[best_k]\n\n logger.debug(\"eps_vec: {}\".format(eps_vec))\n\n _t0 = time.time()\n\n dt = times[1] - times[0]\n\n if use_interp:\n ip_funcs = [interp1d(times, u[r, j, :, best_k], kind=interp_kind,\n bounds_error=False,\n fill_value=u[r, j, -1, best_k])\n for j in range(J)]\n\n def _H_t(t, args=None):\n return H0 + sum([float(ip_funcs[j](t)) * H_ops[j]\n for j in range(J)])\n\n U_list = [(-1j * _H_t(times[idx]) * dt).expm()\n for idx in range(M-1)]\n\n else:\n def _H_idx(idx):\n return H0 + sum([u[r, j, idx, best_k] * H_ops[j]\n for j in range(J)])\n\n U_list = [(-1j * _H_idx(idx) * dt).expm() for idx in range(M-1)]\n\n logger.debug(\"Time 1: %fs\" % (time.time() - _t0))\n _t0 = time.time()\n\n U_f_list = []\n U_b_list = []\n\n U_f = 1\n U_b = 1\n for m in range(M - 1):\n\n U_f = U_list[m] * U_f\n U_f_list.append(U_f)\n\n U_b_list.insert(0, U_b)\n U_b = U_list[M - 2 - m].dag() * U_b\n\n logger.debug(\"Time 2: %fs\" % (time.time() - _t0))\n _t0 = time.time()\n\n for j in range(J):\n for m in range(M-1):\n P = U_b_list[m] * U\n Q = 1j * dt * H_ops[j] * U_f_list[m]\n\n if phase_sensitive:\n du = - cy_overlap(P.data, Q.data)\n else:\n du = (- 2 * cy_overlap(P.data, Q.data) *\n cy_overlap(U_f_list[m].data, P.data))\n\n if alpha:\n # penalty term for high power control signals u\n du += -2 * alpha * u[r, j, m, best_k] * dt\n\n if beta:\n # penalty term for late control signals u\n du += -2 * beta * k ** 2 * u[r, j, k] * dt\n\n for k, eps_val in enumerate(eps_vec):\n u[r + 1, j, m, k] = u[r, j, m, k] + eps_val * du.real\n\n if u_limits:\n if u[r + 1, j, m, k] < u_limits[0]:\n u[r + 1, j, m, k] = u_limits[0]\n elif u[r + 1, j, m, k] > u_limits[1]:\n u[r + 1, j, m, k] = u_limits[1]\n\n u[r + 1, j, -1, :] = u[r + 1, j, -2, :]\n\n logger.debug(\"Time 3: %fs\" % (time.time() - _t0))\n _t0 = time.time()\n\n for k, eps_val in enumerate(eps_vec):\n\n def _H_idx(idx):\n return H0 + sum([u[r + 1, j, idx, k] * H_ops[j]\n for j in range(J)])\n\n U_list = [(-1j * _H_idx(idx) * dt).expm() for idx in range(M-1)]\n\n Uf[k] = gate_sequence_product(U_list)\n _k_overlap[k] = _fidelity_function(cy_overlap(Uf[k].data,\n U.data)).real\n\n best_k = np.argmax(_k_overlap)\n logger.debug(\"k_overlap: \", _k_overlap, best_k)\n\n if _prev_overlap > _k_overlap[best_k]:\n logger.debug(\"Regression, stepping back with smaller eps.\")\n\n u[r + 1, :, :, :] = u[r, :, :, :]\n eps_vec /= 2\n else:\n\n if best_k == 0:\n eps_vec /= 2\n\n elif best_k == 2:\n eps_vec *= 2\n\n _prev_overlap = _k_overlap[best_k]\n\n overlap_log[r] = _k_overlap[best_k]\n\n if overlap_terminate < 1.0:\n if _k_overlap[best_k] > overlap_terminate:\n logger.info(\"Reached target fidelity, terminating.\")\n break\n\n logger.debug(\"Time 4: %fs\" % (time.time() - _t0))\n _t0 = time.time()\n\n if use_interp:\n ip_funcs = [interp1d(times, u[_r, j, :, best_k], kind=interp_kind,\n bounds_error=False, fill_value=u[R - 1, j, -1])\n for j in range(J)]\n\n H_td_func = [H0] + [[H_ops[j], lambda t, args, j=j: ip_funcs[j](t)]\n for j in range(J)]\n else:\n H_td_func = [H0] + [[H_ops[j], u[_r, j, :, best_k]] for j in range(J)]\n\n progress_bar.finished()\n\n result = GRAPEResult(u=u[:_r, :, :, best_k], U_f=Uf[best_k],\n H_t=H_td_func)\n\n result.eps = eps_log\n result.overlap = overlap_log\n\n return result\n","sub_path":"qutip/control/grape.py","file_name":"grape.py","file_ext":"py","file_size_in_byte":19982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"439034921","text":"\"\"\" Trains an agent with (stochastic) Policy Gradients. \"\"\"\nimport tensorflow as tf\nimport numpy as np\nimport random\n\n#from flat_game import carmunk\nimport requests, json\n\nurl = 'http://192.168.1.136:9000/api'\n\nclass PolicyNetwork():\n \"\"\"\n Policy Function approximator. \n \"\"\"\n\n def __init__(self, learning_rate, scope=\"policy_network\"):\n with tf.variable_scope(scope):\n self.state = tf.placeholder(dtype=tf.float32, shape=[None, 3], name=\"state\")\n self.action = tf.placeholder(dtype=tf.int32, shape=[None, ], name=\"action\")\n self.reward = tf.placeholder(dtype=tf.float32, shape=[None, ], name=\"reward\")\n\n # FC1\n fc1 = tf.layers.dense(\n inputs=self.state,\n units=16,\n activation=tf.nn.tanh, # tanh activation\n name='FC1'\n )\n\n # FC2\n fc2 = tf.layers.dense(\n inputs=fc1,\n units=32,\n activation=tf.nn.tanh, # tanh activation\n name='FC2'\n )\n\n # logits\n logits = tf.layers.dense(\n inputs=fc2,\n units=3,\n activation=None,\n name='FC3'\n )\n\n self.action_prob = tf.nn.softmax(logits)\n neg_log_prob = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=self.action)\n\n self.loss = tf.reduce_mean(neg_log_prob * self.reward)\n # train op\n self.optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)\n self.train_op = self.optimizer.minimize(\n self.loss, global_step=tf.contrib.framework.get_global_step())\n\n def predict(self, state, sess):\n return sess.run(self.action_prob, {self.state: state})\n\n def update(self, state, reward, action, sess):\n feed_dict = {self.state: state, self.reward: reward, self.action: action}\n _, loss = sess.run([self.train_op, self.loss], feed_dict)\n return loss\n\n# hyperparameters\nlearning_rate = 0.005\ngamma = 0.99 # discount factor for reward\nresume = True # resume from previous checkpoint?\nmax_episode_number = 1000 # how many episode we want to run ?\nmodel_path = \"../rl_robot_sim/_models/reinforce/model.ckpt\" # path for saving the model\nreal_env_model_path = \"_models/reinforce/model.ckpt\"\n\n\ndef discount_rewards(r):\n \"\"\"\n take 1D float array of rewards and compute discounted rewards (A_t)\n A_t = R_t + gamma^1 * R_t+1 + gamma^2 * R_t+2 + ... + gamma^(T-t)R_T;\n where T is the last time step of the episode\n\n :param r: float array of rewards (R_1, R_2, ..., R_T)\n :return: float array of discounted reward (A_1, A_2, ..., A_T)\n \"\"\"\n\n discounted_r = np.zeros_like(r)\n running_add = 0\n for t in reversed(range(0, r.size)):\n # if r[t] != 0: running_add = 0 # reset the sum, since this was a game boundary (pong specific!)\n running_add = running_add * gamma + r[t]\n discounted_r[t] = running_add\n return discounted_r\n\n\n\n\nif __name__ == '__main__':\n\n fhand = open('log/episode_reward_log.txt', 'w')\n fhand.write('EPISODE\\tTIME_STEPS_TAKEN\\tTOTAL_REWARD')\n fhand.write('\\n')\n fhand.close()\n\n state_list, action_list, reward_list = [], [], []\n running_reward = None\n reward_sum = 0\n episode_number = 0\n\n policy_network = PolicyNetwork(learning_rate)\n\n # saver\n saver = tf.train.Saver()\n # session\n sess = tf.Session()\n sess.run(tf.global_variables_initializer())\n\n if resume:\n saver.restore(sess, model_path)\n\n # create a new game instance\n #env = carmunk.GameState()\n \n done = False\n \n # get initial state by doing nothing and getting the state\n #_, observation = env.frame_step(2)\n action = json.dumps({'action':2})\n r = requests.post(url,action)\n \n while episode_number < max_episode_number:\n\n current_state = np.array(r.json()['observation'])\n\n #print (current_state)\n\n # forward the policy network and sample an action from the returned probability\n action_prob = policy_network.predict(current_state[np.newaxis, :], sess)\n action = np.random.choice(a=3, p=action_prob.ravel())\n\n # record various intermediates\n action_list.append(action)\n state_list.append(current_state) # observation\n\n\n # step the environment and get new measurements\n #reward, observation = env.frame_step(action)\n action = json.dumps({'action':action})\n r = requests.post(url,action)\n\n reward_sum += r.json()['reward']\n\n reward_list.append(r.json()['reward']) # record reward (has to be done after we call step() to get reward for previous action)\n\n if r.json()['reward'] == -50:\n done = True\n else:\n done = False\n\n\n if done: # an episode finished\n episode_number += 1\n\n # stack together all inputs, action and rewards for this episode\n state_batch = np.vstack(state_list)\n action_batch = np.array(action_list)\n reward_batch = np.array(reward_list)\n\n state_list, action_list, reward_list = [], [], [] # reset array memory\n\n\n # compute the discounted reward backwards through time\n discounted_epr = discount_rewards(reward_batch)\n # standardize the rewards to be unit normal (helps control the gradient estimator variance)\n discounted_epr -= np.mean(discounted_epr)\n discounted_epr /= np.std(discounted_epr)\n\n\n # update model variables with data obtained from this episode\n policy_network.update(state_batch, discounted_epr, action_batch, sess)\n\n # record running_reward to get overview of the improvement so far\n running_reward = reward_sum if running_reward is None else running_reward * 0.99 + reward_sum * 0.01\n \n \n print('ep %d: game finished, reward: %.2f, running_reward: %.2f' % (\n episode_number, reward_sum, running_reward))\n\n # Save episode information\n fhand = open('log/episode_reward_log.txt', 'a')\n fhand.write(str(episode_number) + '\\t' + str(reward_sum) + '\\t' + str(running_reward))\n fhand.write('\\n')\n fhand.close()\n\n # reset reward_sum\n reward_sum = 0\n\n # save the model every 30 episodes\n if episode_number % 5 == 0: saver.save(sess, real_env_model_path)\n\n\n\n\n\n\n\n","sub_path":"pgd_world.py","file_name":"pgd_world.py","file_ext":"py","file_size_in_byte":6549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"102008801","text":"# Load libraries\nimport pandas\nimport platform\nfrom pandas.plotting import scatter_matrix\nimport matplotlib.pyplot as plt\nfrom sklearn import model_selection\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\nos = platform.system()\nif os == \"Linux\":\n path_linux = \"/home/roncax/Documents/Git Project/PythonEx/iris.csv\"\nelif os == \"Windows\":\n path = \"A:\\Documents\\Git Project\\PythonEx\\Iris.csv\"\nelse:\n url = \"https://raw.githubusercontent.com/jbrownlee/Datasets/master/iris.csv\"\n\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\ndataset = pandas.read_csv(path_linux, names=names) # returned as two-dimensional data structure with labeled axes (as a matrix)\n\nprint(dataset.shape) # In the example, 150 instances and 5 attributes\nprint(dataset.head(20)) # Print the first 20 instances of the dataset\nprint(dataset.describe()) # count, mean, standard deviation, min, max, and lower/50/upper percentiles\nprint(dataset.groupby('class').size()) # class distribution\n\n# univariate plots (plot for each individual variable)\ndataset.plot(kind='box', subplots=True, layout=(2, 2), sharex=False, sharey=False)\ndataset.hist()\n\n# scatter plot matrix\nscatter_matrix(dataset)\n\n# split dataset 80% in train and 20% in validation\narray = dataset.values\nX = array[:, 0:4]\nY = array[:, 4]\nvalidation_size = 0.20\nseed = 7\nX_train, X_validation, Y_train, Y_validation = model_selection.train_test_split(X, Y, test_size=validation_size, random_state=seed)\n\n\n# Test options and evaluation metric - 10-fold cross validation\nseed = 7\nscoring = 'accuracy' # ratio of the number of correctly predicted instances in divided by the total number of instances in the dataset multiplied by 100 to give a percentage\n\n# Spot Check Algorithms\nmodels = []\nmodels.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('CART', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('SVM', SVC(gamma='auto')))\n\n# evaluate each model in turn\nresults = []\nnames = []\nfor name, model in models:\n kfold = model_selection.KFold(n_splits=10, random_state=seed)\n cv_results = model_selection.cross_val_score(model, X_train, Y_train, cv=kfold, scoring=scoring)\n results.append(cv_results)\n names.append(name)\n msg = \"%s: %f (%f)\" % (name, cv_results.mean(), cv_results.std())\n print(msg)\n\n# Compare Algorithms\nfig = plt.figure()\nfig.suptitle('Algorithm Comparison')\nax = fig.add_subplot(111)\nplt.boxplot(results)\nax.set_xticklabels(names)\nplt.show()\n\n# Make predictions on validation dataset\nknn = KNeighborsClassifier()\nknn.fit(X_train, Y_train)\npredictions = knn.predict(X_validation)\nprint(accuracy_score(Y_validation, predictions))\nprint(confusion_matrix(Y_validation, predictions))\nprint(classification_report(Y_validation, predictions))","sub_path":"ML_iris.py","file_name":"ML_iris.py","file_ext":"py","file_size_in_byte":3317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"265219952","text":"import sqlite3 as lite\nfrom utils import sql\n\n\ndef run_delta():\n con = lite.connect('db/riobravo.db')\n assets = sql.query(con, \"SELECT * FROM asset\")\n for asset in assets:\n ticks = sql.query(con, \"SELECT * FROM \" + asset[0] + \" ORDER BY date\")\n last_close = 0\n for tick in ticks:\n current_close = float(tick[4]) / 100\n delta = 0 if last_close == 0 else ((current_close - last_close) / last_close) * 100\n delta_string = \"{0:.2f}\".format(delta).replace(\".\", \"\")\n q = \"UPDATE \" + asset[0] + \" SET delta = \" + delta_string + \" where date = \" + str(tick[0]) + \";\"\n res = sql.query(con, q)\n last_close = current_close\n con.commit()\n con.close()\n\n\nrun_delta()\n","sub_path":"delta.py","file_name":"delta.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"606504872","text":"import csv\nimport json\nimport random\nimport traceback\n\nimport os\nimport requests\nimport time\n\nfrom utils import log, save_file, VERSION\n\n\ndef get_restaurants_by_street(street, city_name):\n try:\n # 加载现有的餐馆信息\n restaurants = load_restaurants(city_name)\n name = street.get('name_str')\n lon = street.get('lon')\n lat = street.get('lat')\n url = 'https://api.mrdfood.com/restaurants'\n headers = {\n 'Accept': 'application/json,text/plain,*/*',\n 'Accept-Encoding': 'gzip,deflate,br',\n 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7',\n 'Api-Key': '8991c720-203f-4e18-af78-d4b32aa49005',\n 'Authorization': 'Basic aml6aHV3bzAwQGhvdG1haWwuY29tOm1heGlhb3Rlbmc =',\n 'Connection': 'keep-alive',\n 'Host': 'api.mrdfood.com',\n 'If-None-Match': '\"ba394d0b3bd3a68bf5b982b99c775941b73365b9\"',\n 'Origin': 'https://www.mrdfood.com',\n }\n params = {\n 'latitude': lat,\n 'longitude': lon,\n 'street_name': name,\n }\n time.sleep(random.randrange(1, 3))\n log('开始请求{}街道的数据'.format(name))\n response = requests.get(url, headers=headers, params=params)\n rs = response.json().get('items')\n for r in rs:\n id = r.get('id')\n # 如果之前餐馆已经有了,就不再查询信息\n if restaurants.get('id') is not None:\n log('餐馆{}之前已存在'.format(id))\n continue\n tmp_r = {\n 'id': r.get('id'),\n 'name': r.get('name'),\n }\n tags = r.get('tags')\n cuisines = []\n for t in tags:\n cuisines.append(t.get('name'))\n tmp_r['cuisines'] = cuisines\n tmp_r['order methods'] = r.get('delivery_option')\n address = r.get('address')\n if address is None:\n log('餐馆:{}的地址获取异常'.format(r.get('name')))\n tmp_r['address'] = None\n else:\n tmp_address = {\n 'street_number': address.get('street_number'),\n 'street_name': address.get('street_name'),\n 'province': address.get('province'),\n 'town': address.get('town'),\n 'suburb': address.get('suburb'),\n 'complex': address.get('complex'),\n 'postal_code': address.get('postal_code'),\n }\n tmp_r['address'] = tmp_address\n tmp_r['latitude'] = address.get('latitude')\n tmp_r['longitude'] = address.get('longitude')\n restaurants[id] = tmp_r\n # 及时保存结果\n street['has_get'] = True\n return restaurants\n except Exception as e:\n log(e)\n log(traceback.format_exc())\n log('请求街道:{}的数据异常'.format(name))\n\n\ndef save_restaurants(restaurants, city_name):\n file_path = '../data/{}/restaurants/{}-restaurants.txt'.format(VERSION, city_name)\n save_file(restaurants, file_path)\n\n\ndef load_restaurants(city_name):\n restaurants = {}\n try:\n file_path = '../data/{}/restaurants/{}-restaurants.txt'.format(VERSION, city_name)\n if not os.path.exists(file_path):\n return restaurants\n with open(file_path, 'r') as f:\n s = f.read()\n if len(s) == 0:\n return restaurants\n else:\n restaurants = json.loads(s)\n return restaurants\n except Exception as e:\n log(e)\n\n\ndef save_streets(streets, city_name):\n file_path = \"../data/{}/street_data/{}.txt\".format(VERSION, city_name)\n save_file(streets, file_path)\n\n\ndef load_streets(city_name):\n file_path = \"../data/{}/street_data/{}.txt\".format(VERSION, city_name)\n if not os.path.exists(file_path):\n result = {}\n else:\n with open(file_path, 'r') as fr:\n s = fr.read()\n if len(s) == 0:\n result = {}\n else:\n result = json.loads(s)\n return result\n\n\ndef get_restaurants_list(city_name):\n try:\n streets = load_streets(city_name)\n restaurants = load_restaurants(city_name)\n count = 0\n for street in streets.values():\n if street.get('has_get') is None:\n tmp_restaurants = get_restaurants_by_street(street, city_name)\n restaurants.update(tmp_restaurants)\n save_restaurants(restaurants, city_name)\n save_streets(streets, city_name)\n count += 1\n log('本次启动更新街道数:{}'.format(count))\n log('本城市现有餐馆:{}家'.format(len(load_restaurants(city_name).items())))\n if count == 0:\n print('街道餐馆信息更新完毕')\n log('街道餐馆信息更新完毕')\n log('本城市共有餐馆:{}家'.format(len(load_restaurants(city_name).items())))\n result = 0\n log('获取餐馆列表完成')\n except Exception as e:\n log(e)\n log(traceback.format_exc())\n result = 1\n return result\n\n\nif __name__ == \"__main__\":\n city_names = ['cape_town']\n for city_name in city_names:\n get_restaurants_list(city_name)","sub_path":"src/get_restaurants_list.py","file_name":"get_restaurants_list.py","file_ext":"py","file_size_in_byte":5411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"487763479","text":"from db.models import User\n\n\nclass GetUserAffiliateAccountFields:\n def __init__(self, user: User):\n self.__user = user\n\n def execute(self, _):\n ai = self.__user.affiliate_info\n if not ai:\n raise Exception(\"User have no affiliate account.\")\n\n # add additional fields\n data = {\n \"legal_status\": ai.legal_status.name if ai.legal_status else \"\",\n \"contract_type\": ai.contract_type.id if ai.contract_type else \"\",\n \"status\": ai.status.name if ai.status else \"\"\n }\n\n # return result\n return {\n **(self.__user.affiliate_info.additional_data or {}),\n **data\n }\n","sub_path":"src/backend/areas/partners/queries/account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"8274191","text":"import math\ndef isPrime(n):\n for i in range(2,int(math.sqrt(n))+1):\n if n%i==0:\n return False\n return True\n\ndef main():\n sum=0\n for i in range(2,2000001):\n if isPrime(i)==True:\n sum+=i\n print(sum)\n\nif __name__ == '__main__':\n main()\n","sub_path":"Prob10.py","file_name":"Prob10.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"595803828","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split, KFold\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.ensemble import RandomForestRegressor\nfrom keras.models import Sequential\nfrom keras.layers import LSTM, Dense, Dropout, LeakyReLU\nfrom keras.layers import Conv1D, Flatten, MaxPooling1D\nfrom keras.callbacks import EarlyStopping\nscaler = StandardScaler()\nleaky = LeakyReLU(alpha = 0.2)\nes = EarlyStopping(monitor = 'val_loss',\n mode = 'min',\n patience = 10)\n\n### 데이터 ###\nx = pd.read_csv('./data/dacon/comp3/train_features.csv',\n encoding = 'utf-8')\ny = pd.read_csv('./data/dacon/comp3/train_target.csv',\n index_col = 0, header = 0,\n encoding = 'utf-8')\nx_pred = pd.read_csv('./data/dacon/comp3/test_features.csv',\n encoding = 'utf-8')\nprint(x.shape) # (1050000, 6)\nprint(y.shape) # (2800, 5)\nprint(x_pred.shape) # (262500, 6)\n\nx_train = x\ny_train = y\nprint(x_train.shape) # (1050000, 6)\nprint(y_train.shape) # (2800, 5)\nprint(x_train.head())\n\n\nx_train = x_train.drop('Time', axis = 1)\nprint(x_train.head())\n\nx_train = np.sqrt(x_train.groupby(x_train['id']).mean())\nprint(x_train.shape) # (2800, 4)\n\n\nx_train = pd.read_csv('./data/dacon/comp3/x_Train.csv',\n index_col = 0, header = 0,\n encoding = 'utf-8')\nprint(x_train.head())\nprint(x_train.shape) # (2800, 4)\n\nprint(y_train.head())\nprint(y_train.shape) # (2800, 4)\n\nprint(x_train.isna().sum())\n\n'''\nx_train, x_test, y_train, y_test = train_test_split(\n x_train, y_train, test_size = 0.2)\nprint(x_train.shape) # (2240, 4)\nprint(x_test.shape) # (560, 4)\nprint(y_train.shape) # (2240, 4)\nprint(y_test.shape) # (560, 4)\n\nx_train = x_train.values\nx_test = x_test.values\ny_train = y_train.values\ny_test = y_test.values\n\nscaler.fit(x_train)\nx_train = scaler.transform(x_train)\nx_test = scaler.transform(x_test)\n\n# x_train = x_train.reshape(-1, 4, 1)\n# x_test = x_test.reshape(-1, 4, 1)\n# print(x_train.shape) # (2240, 4, 1)\n# print(x_test.shape) # (560, 4, 1)\n\n\n### 모델\nkf = KFold(n_splits = 5, shuffle = True)\nparams = {'n_estimators': [3, 10, 30], 'max_features': [2, 4, 6, 8], \n 'n_estimators': [3, 10], 'bootstrap': [False], 'max_features': [2, 4, 6]}\n\n\nprint(params)\n\nmodel = RandomizedSearchCV(RandomForestRegressor(), param_distributions = params, cv = kf, n_jobs = -1)\n\n### 훈련\nmodel.fit(x_train, y_train)\n\n### 예측\nx_pred = x_pred.drop('Time', axis = 1)\n# print(x_pred.head())\n\nx_pred = np.sqrt(x_pred.groupby(x_pred['id']).mean())\n# print(x_pred.shape) # (700, 4)\n\nx_pred = x_pred.values\nx_pred = scaler.fit_transform(x_pred)\n# x_pred = x_pred.reshape(-1, 4, 1)\n# print(type(x_pred)) # \n\ny_predict = model.predict(x_pred)\nprint(\"Predict : \\n\", y_predict)\n\nsubmit = pd.DataFrame(y_predict)\nprint(submit.head())\n\nsubmit.to_csv('./data/dacon/comp3/mysubmit_2.csv')\n'''","sub_path":"data/dacon/comp3/dacon_RandomForest.py","file_name":"dacon_RandomForest.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"637407954","text":"# Time: O(n^2)\n# Space: O(1)\n\n# 931 contest 108 10/27/2018\n#Given a square array of integers A, we want the minimum sum of a falling path through A.\n\n#A falling path starts at any element in the first row, and chooses one element from each row. \n#The next row's choice must be in a column that is different from the previous row's column by at most one.\n\n#Example 1:\n#Input: [[1,2,3],[4,5,6],[7,8,9]]\n#Output: 12\n#Explanation: \n#The possible falling paths are:\n#[1,4,7], [1,4,8], [1,5,7], [1,5,8], [1,5,9]\n#[2,4,7], [2,4,8], [2,5,7], [2,5,8], [2,5,9], [2,6,8], [2,6,9]\n#[3,5,7], [3,5,8], [3,5,9], [3,6,8], [3,6,9]\n#The falling path with the smallest sum is [1,4,7], so the answer is 12.\n\n#Note:\n#1 <= A.length == A[0].length <= 100\n#-100 <= A[i][j] <= 100\n\nclass Solution(object):\n def minFallingPathSum(self, A):\n \"\"\"\n :type A: List[List[int]]\n :rtype: int\n \"\"\"\n for i in xrange(1, len(A)):\n for j in xrange(len(A[i])):\n A[i][j] += min(A[i-1][max(j-1, 0):j+2])\n return min(A[-1])\n\n # if not allowing to overwrite input list\n def minFallingPathSum_auxSpace(self, A):\n n = len(A)\n dp = [A[0], [0]*n]\n for i in xrange(1, n):\n dp[i%2] = [A[i][j]+min(dp[(i-1)%2][max(0,j-1):j+2]) for j in xrange(n)]\n return min(dp[(n-1)%2])\n\nprint(Solution().minFallingPathSum([[1,2,3],[4,5,6],[7,8,9]])) # 12\n","sub_path":"Python/minimum-falling-path-sum.py","file_name":"minimum-falling-path-sum.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"236062819","text":"# AMC Priority assignment based on:\r\n# Response-Time Analysis for Mixed Criticality Systems - S.K. Baruah et.al.\r\n# Link: https://www-users.cs.york.ac.uk/burns/RTSS.pdf\r\n\r\nfrom audsley import Audsley\r\nimport math\r\n\r\n\r\nclass AmcRtb(Audsley):\r\n \"\"\"amc-rtb based schedulability test and priority assignment.\"\"\"\r\n\r\n def __init__(self, taskset):\r\n super(AmcRtb, self).__init__(taskset)\r\n\r\n def __amc_ri_low(self, task, taskset=None):\r\n \"\"\"Calculate the response time of low criticality tasks.\"\"\"\r\n R_lo = task.b_lo\r\n for ind in taskset:\r\n if ind != task:\r\n R_lo += math.ceil(R_lo / ind.pr_lo) * ind.b_lo\r\n return R_lo\r\n\r\n def __amc_ri_high(self, task, r_initial, taskset=None):\r\n \"\"\"Calculate the response time of the high criticality tasks.\"\"\"\r\n R_hi = r_initial\r\n for ind in taskset:\r\n if (ind.crit == 1) and (ind != task):\r\n R_hi += math.ceil(R_hi / ind.pr_hi) * ind.b_hi\r\n return R_hi\r\n\r\n def dbf_amc_rtb(self, task, taskset=None):\r\n \"\"\"Demand bound function for amc-rtb.\"\"\"\r\n rtb = task.b_hi\r\n rtb += self.__amc_ri_low(task, taskset)\r\n if task.crit == 1:\r\n rtb += self.__amc_ri_high(task, rtb, taskset)\r\n return rtb\r\n\r\n def amc_rtb_rta(self, task, taskset=None, debug=False):\r\n \"\"\"Check schedulability based on amc-rtb \"\"\"\r\n Ri = self.dbf_amc_rtb(task, taskset)\r\n if debug:\r\n print(\"Response time for task :\", Ri)\r\n return Ri\r\n\r\n def assign_priority(self):\r\n \"\"\"Priority assignment based on Audsley's approach.\"\"\"\r\n try:\r\n prio_assigned = self.assign_priorities(self.amc_rtb_rta)\r\n except ValueError as vs:\r\n print(\"Failed to assign priorities: Taskset not schedulable.: \\n\", vs)\r\n raise ValueError(\"schedulability test failed: Value error.\\n\") # Throw for test.\r\n return prio_assigned\r\n","sub_path":"schedcat/mc-sched/amc_rtb.py","file_name":"amc_rtb.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"39796992","text":"\n\n# A script that follows threaded_assess_alignment.py and outputs some general\n# statistics like counts for which reference had the best alignment per locus\n# and the distribution of the %ID from the final alignments. The input for\n# this script is the ids_v_cov.tsv file generated from the assessment script.\n#\n# Run the script using a command like this:\n# python3 generate_alignment_stats.py -i ids_v_cov.tsv -o stats.out\n#\n# Author: James Matsumura\n\nimport argparse\nimport numpy as np\n\ndef main():\n\n parser = argparse.ArgumentParser(description='Script to generate basic stats from the output of threaded_assess_alignment.py.')\n parser.add_argument('-i', type=str, required=True, help='Path to TSV output file from analyze_sequences.py/split_analysis.py')\n args = parser.parse_args()\n\n gc,length,rpts,rpts_len,exns = ([] for i in range(5))\n\n with open(args.i,'r') as infile:\n for line in infile:\n line = line.rstrip()\n elements = line.split('\\t')\n gc.append(float(elements[1]))\n length.append(float(elements[2]))\n rpts.append(float(elements[3]))\n rpts_len.append(float(elements[4]))\n exns.append(float(elements[5]))\n\n print(\"GC avg:\\t{0}\".format(np.mean(gc)))\n print(\"Length avg:\\t{0}\".format(np.mean(length)))\n print(\"Repeats avg:\\t{0}\".format(np.mean(rpts)))\n print(\"Repeats length avg:\\t{0}\".format(np.mean(rpts_len)))\n print(\"Exons avg:\\t{0}\".format(np.mean(exns)))\n\n print(\"GC std:\\t{0}\".format(np.std(gc)))\n print(\"Length std:\\t{0}\".format(np.std(length)))\n print(\"Repeats std:\\t{0}\".format(np.std(rpts)))\n print(\"Repeats length std:\\t{0}\".format(np.std(rpts_len)))\n print(\"Exons std:\\t{0}\".format(np.std(exns))) \n\n\nif __name__ == '__main__':\n main()","sub_path":"util/generate_loci_stats.py","file_name":"generate_loci_stats.py","file_ext":"py","file_size_in_byte":1792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"239063644","text":"import bs4\nfrom urllib2 import urlopen as uReq \nfrom bs4 import BeautifulSoup as soup \n\nprint(\"web scrap\")\n\nmy_url = 'https://www.newegg.com/Video-Cards-Video-Devices/Category/ID-38?Tpk=video%20cards'\n\nuClient = uReq(my_url) #opening connection\npage_html = uClient.read() #grabbing page\nuClient.close() #close connection\n\npage_soup = soup(page_html, \"html.parser\") #grabs entire html file into memory location\n\n# we need to grab the list of video cards\n# this was found how to do by going to the page \n# on chrome and then using the \"inspect\" ability, \n# figure out the individual search results is in a div\n# with the class name item-container\n# use class below, we can also use id if we wanted to\n\ncontainers = page_soup.findAll(\"div\", {\"class\", \"item-container\"}) \n\n\n#putting it into a csv file\nfilename = \"graphics_card.csv\" #name of file\nf = open(filename, \"w\") #open file and declare access type\nheaders = \"brand, product_name, shippping \\n\" # the headers for each column\n\nf.write(headers)\n\nfor container in containers:\n # {\"class\", \"item-info\"} would give the same effect as \"item-info\"\n temp_div = container.find(\"div\", {\"class\", \"item-info\"})\n brand = temp_div.div.a.img[\"title\"]\n temp_a = container.find(\"a\", {\"class\", \"item-title\"}) # find all a tags with class item-title\n title = temp_a.text\n shipping = container.find(\"li\", {\"class\":\"price-ship\"}).text.strip()\n print(\"brand\" + brand);\n print(\"title\" + title);\n print(\"shipping\" + shipping + \"\\n\");\n f.write(brand + \",\" + title.replace(\",\", \"|\") + \",\" + shipping + '\\n');\nf.close() #if you dont close this, excel can't access it. ","sub_path":"webScrapLeet/web-scrape-intro copy.py","file_name":"web-scrape-intro copy.py","file_ext":"py","file_size_in_byte":1626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"263473265","text":"book_list = [{'title': 'Война и мир', 'author': 'Толстой Л.Н.'},\n {'title': 'Идиот', 'author': 'Достоевский Ф.М.'},\n {'title': 'Капитанская дочка', 'author': 'Пушкин А.С.'}]\n\nbooks = []\nauthors = []\n\nfor book in book_list:\n title = book['title']\n author = book['author']\n books.append(title)\n authors.append(author)\n\n\nprint(f'Список книг: {books}')\nprint(f'Список авторов: {authors}')","sub_path":"Simple2.py","file_name":"Simple2.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"7097510","text":"woord = ''\nlengteWoord = 0\n\nwhile lengteWoord != 4:\n woord = input('Geef een string van 4 letters: ')\n lengteWoord = len(woord)\n if lengteWoord == 4:\n print('Inlezen van correcte string: {} is geslaagd'.format(woord))\n break\n else:\n print('{} heeft {} letters'.format(woord, lengteWoord))","sub_path":"Oefenopdrachten/OefenOpdracht7_2.py","file_name":"OefenOpdracht7_2.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"554735076","text":"\nimport requests\nfrom getimpphrases import getImpPhrases\nimport pandas as pd\n\ndef remove_clean(df):\n \n tot=[]\n \n escapes = ''.join([chr(char) for char in range(1, 32)])\n translator = str.maketrans('', '', escapes)\n for f in df:\n f = f.translate(translator)\n f=f.strip()\n if len(f)==0:\n continue\n tot.append(f)\n return tot\n \ndef related_videos():\n\n\n try:\n df=pd.read_csv('fin.csv')\n df=df['ppt']\n except FileNotFoundError:\n print('Upload files first')\n\n\n\n\n df=list(df)\n df=remove_clean(df)\n\n\n\n\n text=''''''\n for i in df:\n text+=i\n text+='\\n '\n\n\n\n\n\n search_term=getImpPhrases(text)\n #print(search_term)\n max_len = -1\n for ele in search_term: \n if len(ele) > max_len: \n max_len = len(ele) \n res = ele \n res\n\n\n\n search_term=res\n\n subscription_key = 'a50d176bc7314fd7acf6f7da2e52b7fe'\n assert subscription_key\n search_url = \"https://api.cognitive.microsoft.com/bing/v7.0/videos/search\"\n #search_term = \"Machine Learning Models for Classification\"\n\n\n\n headers = {\"Ocp-Apim-Subscription-Key\" : subscription_key}\n\n params = {\"q\": search_term, \"count\":5, \"pricing\": \"free\", \"videoLength\":\"short\"}\n\n\n response = requests.get(search_url, headers=headers, params=params)\n response.raise_for_status()\n search_results = response.json()\n\n import json\n r = json.dumps(search_results)\n with open(\"cont.json\", \"w\") as write_file:\n json.dump(r, write_file)\n\n return search_results\n\n\n\n\n","sub_path":"suggested_videos.py","file_name":"suggested_videos.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"513818825","text":"#!/usr/bin/env python3\n\n# https://codeforces.com/problemset/problem/1288/B\n\ndef f(l):\n A,B = l\n i = 0\n mx = 9\n while B>=mx:\n mx = mx*10 + 9\n i += 1\n return i*A\n\nq = int(input())\nfor _ in range(q):\n l = list(map(int,input().split()))\n print(f(l))\n","sub_path":"codeforces/math数学/1100/1288B999.py","file_name":"1288B999.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"374668850","text":"\"\"\"\nMonte Carlo Method(몬테 카를로 방법)\n난수를 생성해서 어떤 값을 확률적으로 계산하는 방법\n\"\"\"\nimport math\nimport random\n\nn_iteration = 10000 # 전체 반복 회수\nn_in = 0 # 점 (x, y)이 반지름 1인 원 안에 들어간 개수\nfor _ in range(n_iteration):\n # 난수 x, y를 생성해서 (x, y)\n x = random.random()\n y = random.random()\n d = math.sqrt(x**2 + y**2) # 원점에서 점 (x, y)까지의 거리\n if d <= 1.0:\n n_in += 1\nestimate_pi = (n_in / n_iteration) * 4\nprint(estimate_pi)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"rl/ex06_montecarlo.py","file_name":"ex06_montecarlo.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"587350979","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 3 15:27:27 2020\r\n\r\n@author: marius\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom tqdm import tqdm\r\nfrom datetime import datetime, date, time, timedelta\r\nfrom collections import defaultdict\r\nfrom CosinorPy import file_parser, cosinor, cosinor1\r\nfrom os import path\r\n\r\n\r\ndef get_circadian(d):\r\n iv = defaultdict(dict)\r\n for idx in d.keys():\r\n iv_col='ENMO'\r\n threshold = d[idx][iv_col].quantile(0.2)\r\n iv[idx] = get_IV_IS(d[idx][iv_col], freq='1H',binarize=False,threshold = threshold, IV_mean=True)\r\n pop_iv = pd.DataFrame(columns=['IV_60','IV_m','IS_60','IS_m'],index=range(len(d.keys())))\r\n for idx in iv.keys():\r\n pop_iv.loc[idx,'IV_60'] = iv[idx][0]\r\n pop_iv.loc[idx,'IV_m'] = iv[idx][1]\r\n pop_iv.loc[idx,'IS_60'] = iv[idx][2]\r\n pop_iv.loc[idx,'IS_m'] = iv[idx][3]\r\n #Extract cosinor parameters for each subject's 'mean_hr', 'ENMO'\r\n pop_cos = get_cosinor(d, compare =False)\r\n #Extract SSA parameters\r\n ssa, ssa_ENMO_pv, ssa_mean_hr_pv = get_ssa_pop(d)\r\n ssa = get_ssa_daily(d,ssa)\r\n return pop_iv, pop_cos, ssa, ssa_ENMO_pv, ssa_mean_hr_pv\r\n\r\n#Function to compute the IV and IS for each subject, for freq='1H' and average over other frequencies\r\n\r\ndef get_IV_IS(self, freq='1H', binarize=False, threshold=0,IV_mean=True):\r\n\r\n#Gonçalves, B. S., Cavalcanti, P. R., Tavares, G. R.,\r\n#Campos, T. F., & Araujo, J. F. (2014). Nonparametric methods in\r\n#actigraphy: An update. Sleep science (Sao Paulo, Brazil), 7(3),158-64.\r\n def resampled_data(self, freq, binarize=False, threshold=0):\r\n\r\n if binarize is False:\r\n data = self\r\n else:\r\n def binarized_data(self, threshold):\r\n \"\"\"Boolean thresholding of Pandas Series\"\"\"\r\n return pd.Series(np.where(self > threshold, 1, 0),index=self.index)\r\n \r\n data = binarized_data(self,threshold)\r\n\r\n resampled_data = data.resample(freq).sum()\r\n return resampled_data\r\n \r\n def intradaily_variability(data):\r\n r\"\"\"Calculate the intradaily variability\"\"\"\r\n\r\n c_1h = data.diff(1).pow(2).mean()\r\n\r\n d_1h = data.var()\r\n\r\n return (c_1h / d_1h)\r\n \r\n def interdaily_stability(data):\r\n r\"\"\"Calculate the interdaily stability\"\"\"\r\n\r\n d_24h = data.groupby([data.index.hour,data.index.minute,data.index.second]).mean().var()\r\n\r\n d_1h = data.var()\r\n\r\n return (d_24h / d_1h)\r\n \r\n data_1 = resampled_data(self,freq, binarize, threshold)\r\n \r\n IV_60 = intradaily_variability(data_1)\r\n IS_60 = interdaily_stability(data_1)\r\n \r\n if IV_mean==True:\r\n freqs=['1T', '2T', '3T', '4T', '5T', '6T', '8T', '9T', '10T',\r\n '12T', '15T', '16T', '18T', '20T', '24T', '30T',\r\n '32T', '36T', '40T', '45T', '48T', '60T']\r\n data = [resampled_data(self,freq, binarize, threshold) for freq in freqs]\r\n IV = [intradaily_variability(datum) for datum in data]\r\n #print(IV)\r\n IS = [interdaily_stability(datum) for datum in data]\r\n #print(IS)\r\n \r\n IV_m = np.mean(IV)\r\n IS_m = np.mean(IS)\r\n \r\n if IV_mean ==False:\r\n return IV_60, IS_60\r\n else:\r\n return IV_60, IV_m, IS_60, IS_m\r\n\r\n#Function to get cosinor analysis for each subject, can return a summary df, or the entire dict with more parameters\r\ndef get_cosinor(d, compare=False):\r\n cos = defaultdict(dict)\r\n\r\n for idx in d.keys():\r\n cos[idx]['mean_hr'] = cosinor.fit_me((d[idx]['minute_of_day']+np.arange(len(d[idx])))/60, d[idx]['mean_hr'], n_components = 2, period = 24, model_type = 'lin', lin_comp = False, alpha = 0, name = '', save_to = '', plot=False, plot_residuals=False, plot_measurements=False, plot_margins=False, return_model = True, plot_phase = False)\r\n cos[idx]['ENMO'] = cosinor.fit_me((d[idx]['minute_of_day']+np.arange(len(d[idx])))/60, d[idx]['ENMO'], n_components = 2, period = 24, model_type = 'lin', lin_comp = False, alpha = 0, name = '', save_to = '', plot=False, plot_residuals=False, plot_measurements=False, plot_margins=False, return_model = True, plot_phase = False)\r\n if compare==True:\r\n cos[idx]['hr_vs_enmo'] = cosinor.compare_pair(X1=(d[idx]['minute_of_day']+np.arange(len(d[idx])))/60, Y1=d[idx]['mean_hr'], \r\n X2=(d[idx]['minute_of_day']+np.arange(len(d[idx])))/60, Y2=d[idx]['ENMO'], test1 = 'mean_hr', test2 = 'ENMO', \r\n n_components = 2, period = 24, lin_comp = True, model_type = 'lin', alpha = 0, \r\n save_to = '', non_rhythmic = False, plot_measurements=False, plot_residuals=False)\r\n \r\n cos_pop_data = pd.DataFrame(columns=['period','amplitude_hr', 'acrophase_hr','mesor_hr','amplitude_enmo','acrophase_enmo','mesor_enmo'],index=range(len(d.keys())))\r\n\r\n for idx in cos.keys():\r\n cos_pop_data.loc[idx,'period'] = cos[idx]['mean_hr'][2]['period']\r\n cos_pop_data.loc[idx,'amplitude_hr'] = cos[idx]['mean_hr'][2]['amplitude']\r\n cos_pop_data.loc[idx,'acrophase_hr'] = cos[idx]['mean_hr'][2]['acrophase'] \r\n cos_pop_data.loc[idx,'mesor_hr'] = cos[idx]['mean_hr'][2]['mesor']\r\n cos_pop_data.loc[idx,'amplitude_enmo'] = cos[idx]['ENMO'][2]['amplitude']\r\n cos_pop_data.loc[idx,'acrophase_enmo'] = cos[idx]['ENMO'][2]['acrophase'] \r\n cos_pop_data.loc[idx,'mesor_enmo'] = cos[idx]['ENMO'][2]['mesor']\r\n \r\n return cos_pop_data\r\n\r\n#Example return for compare_pair function: the params seem to be the coeficcients from an OLS fit model (model = sm.OLS(Y, X_fit))\r\n#(results.pvalues[idx_params], results.params[idx_params], results)\r\n#(array([3.21584633e-04, 3.71032098e-02, 4.03026086e-05, 1.74922581e-01]),\r\n#array([ 2.52482527, 1.46128235, 2.87721325, -0.94775272]),\r\n#)\r\n\r\n#Exploring the structure of the returned wrapper from the cosinor.fit_me\r\n#Prints the name of the model wrapper\r\n#print(cosinor_data[0])\r\n#dict_keys(['p', 'p_reject', 'SNR', 'RSS', 'resid_SE', 'ME'])\r\n#print(cosinor_data[1].keys())\r\n#dict_keys(['period', 'amplitude', 'acrophase', 'mesor'])\r\n#print(cosinor_data[2].keys())\r\n#print(cosinor_data[2]['acrophase'])\r\n#looks like this is an increasing array from of 1000 values from 0 to 1000\r\n#plt.plot(cosinor_data[3])\r\n#plt.show()\r\n#Looks like this is an array containing 100 values for the model fit\r\n#plt.plot(cosinor_data[4])\r\n#plt.show()\r\n \r\n#Extracts ssa parameters for each subject - takes a long time to run, so only executes if the files don't already exist\r\n#in the folder.\r\n\r\ndef get_SSA_par(df,L=1440): # 2 <= L <= N/2\r\n ### import packages ###\r\n import numpy as np\r\n from scipy import linalg # linear algebra (matrix) processing package\r\n import math # math module\r\n ### initialize variables ###\r\n N=len(df)\r\n K=N-L+1\r\n ### SVD ###\r\n X=np.array([[df[i+j] for j in range(0,L)] for i in range(0,K)]) # trajectory matrix\r\n U, s, V=linalg.svd(X) # singular value decomposition (SVD) \r\n l=s**2 # partial variances\r\n r=len(s)#np.linalg.matrix_rank(X) # matrix rank and total number of components\r\n ### time-series components ###\r\n gkList=np.zeros(shape=(r,N)) # zero matrix in whose rows SSA components will be saved\r\n for k in range(0,r):\r\n Uk=U[:,k] # k-th order column singular vector\r\n Vk=V[k,:] # k-th order row singular vector\r\n Xk=s[k]*np.outer(Uk,Vk) # k-th order matrix component\r\n gk=[] # empty array in which to save successive k-th order component values \r\n for i in range(min(K-1,L-1),-max(K-1,L-1)-1,-1): # loop over diagonals\r\n gki=np.mean(np.diag(np.fliplr(Xk),i)) # successive time.series values\r\n gk.append(gki)\r\n gkList[k]=gk # k-th order component\r\n ### w-corr matrix ###\r\n w=[] # empty array to which to add successive weights\r\n LL=min(L,K)\r\n KK=max(L,K)\r\n for ll in range(1,LL+1): # first 1/3 part of weights\r\n w.append(ll)\r\n for ll in range(LL+1,KK+1): # second 1/3 part of weights\r\n w.append(LL)\r\n for ll in range(KK+1,N+1): # third 1/3 part of weights\r\n w.append(N-ll)\r\n kMin=kkMin=0 # show w-corr matrix for first 20 index values\r\n kMax=kkMax=20\r\n #wMatriz=np.zeros(shape=(kMin,kMax)) # initial zero matrix \r\n #for k in range(kMin,kMax):\r\n #for kk in range(kkMin,kkMax):\r\n #wMatriz[k][kk]=sum(w*gkList[k]*gkList[kk])/(math.sqrt(sum(w*gkList[k]*gkList[k]))*math.sqrt(sum(w*gkList[kk]*gkList[kk]))) \r\n wMatrix=[[sum(w*gkList[k]*gkList[kk])/(math.sqrt(sum(w*gkList[k]*gkList[k]))*math.sqrt(sum(w*gkList[kk]*gkList[kk]))) for k in range(kMin,kMax)] for kk in range(kkMin,kkMax)]\r\n wMatrix=np.array(wMatrix)\r\n return (r, l, gkList, wMatrix); \r\n\r\n#Extract SSA parameters, partial variances stored in ssa_io_pv, other stored in dict ssa, read from files in folder for\r\n#convenience, as full analysis takes a long time for each subject\r\ndef get_ssa_pop(d):\r\n ssa = defaultdict(dict)\r\n cols = ['ENMO','mean_hr']\r\n for col in cols:\r\n for idx in d.keys():\r\n if path.exists('ssa_'+col+'_gk_'+str(idx)+'.csv') & path.exists('ssa_'+col+'_wm_'+str(idx)+'.csv'):\r\n ssa[idx]['wMatrix_'+col] = pd.read_csv('ssa_'+col+'_wm_'+str(idx)+'.csv', names=range(20))\r\n ssa[idx]['gkList_'+col] = pd.read_csv('ssa_'+col+'_gk_'+str(idx)+'.csv', header=0)\r\n else:\r\n ssa[idx]['r'],ssa[idx]['pv'+col],ssa[idx]['gkList'+col],ssa[idx]['wMatrix'+col] = get_SSA_par(d[idx][col],L=1440)\r\n pd.DataFrame(ssa[idx]['gkList'+col][:10,:]).to_csv('ssa_'+col+'_gk_'+str(idx)+'.csv', index=False)\r\n pd.DataFrame(ssa[idx]['wMatrix'+col]).to_csv('ssa_'+col+'_wm_'+str(idx)+'.csv', index=False)\r\n pd.DataFrame(ssa[idx]['pv'+col]).to_csv('ssa_'+col+'_pv_'+str(idx)+'.csv', index=False)\r\n if path.exists('ssa_ENMO_pv.csv'):\r\n ssa_ENMO_pv = pd.read_csv('ssa_ENMO_pv.csv')\r\n if path.exists('ssa_mean_hr_pv.csv'):\r\n ssa_mean_hr_pv = pd.read_csv('ssa_mean_hr_pv.csv')\r\n return ssa, ssa_ENMO_pv, ssa_mean_hr_pv\r\n\r\ndef get_ssa_daily(d,ssa,freq='15T'):\r\n for idx in ssa.keys():\r\n enmo = np.transpose(ssa[idx]['gkList_ENMO'])\r\n enmo = enmo.set_index(d[idx].index)\r\n hr = np.transpose(ssa[idx]['gkList_mean_hr'])\r\n hr = hr.set_index(d[idx].index)\r\n #Get sum of trend and circadian components\r\n enmo_gk = enmo[0]+enmo[1]\r\n hr_gk = hr[0]+hr[1]\r\n #Get SSA acrophases\r\n ssa[idx]['acro_ENMO'] = enmo_gk.resample('24H').agg(lambda x : np.nan if x.count() == 0 else x.idxmax())\r\n ssa[idx]['acro_mean_hr'] = hr_gk.resample('24H').agg(lambda x : np.nan if x.count() == 0 else x.idxmax())\r\n #Get vectors of coarse-grain params for ML\r\n ssa[idx]['gksum_ENMO_'+freq] = enmo_gk.resample(freq).mean()\r\n ssa[idx]['gksum_mean_hr_'+freq] = hr_gk.resample(freq).mean()\r\n #Get trend i.e. mesor\r\n ssa[idx]['trend_ENMO'] = enmo[0].resample('24H').mean()\r\n ssa[idx]['trend_mean_hr'] = hr[0].resample('24H').mean()\r\n #Get period in minutes\r\n ssa[idx]['per_ENMO'] = (ssa[idx]['acro_ENMO'] - ssa[idx]['acro_ENMO'].shift(1)).astype('timedelta64[m]')\r\n ssa[idx]['per_mean_hr'] = (ssa[idx]['acro_mean_hr'] - ssa[4]['acro_mean_hr'].shift(1)).astype('timedelta64[m]')\r\n return ssa \r\n","sub_path":"misc/Notebooks/get_circadian.py","file_name":"get_circadian.py","file_ext":"py","file_size_in_byte":11557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"422138265","text":"\nclass Iprt:\n from file_tool import FileTools\n import time\n from ip_query import ExternalIpQuery\n \n log_file = \"/home/drako/Projects/ip_query_tool/iprt.log\"\n config_file = \"/home/drako/Projects/ip_query_tool/iprt.conf\"\n config = {}\n \n #Retriving values from config file\n read_config = FileTools(config_file)\n config = read_config.read_config_file()\n\n log_f = FileTools(log_file)\n\n print(config.get(\"api\"))\n\n ip_tool = ExternalIpQuery(config.get(\"api\"))\n ip = ip_tool.request_ip()\n log_f.write_log_file(f\"!Start ip: {ip}\", True)\n\n def __init__(self):\n self.api = self.config.get(\"api\")\n self.mqtt_broker = self.config.get(\"mqtt_broker\")\n self.ip = self.ip_tool.request_ip()\n\n \n def run(self):\n \n print(\"running!\")\n times_failed = 0\n while True:\n \n is_connection = self.ip_tool.is_connected()\n\n if is_connection == False and times_failed == 0:\n print(f\"Connection failed : {times_failed}\")\n self.log_f.write_log_file(f\"!Connetion failed\", True)\n times_failed += 1\n self.time.sleep(60)\n continue\n\n elif is_connection == False and times_failed >= 1:\n print(f\"Connection failed : {times_failed}\")\n times_failed += 1\n self.time.sleep(60)\n continue\n \n\n else:\n if times_failed > 0:\n print(\"!Connection reestablished\")\n self.log_f.write_log_file(f\"!Connection reestablished\", True)\n times_failed = 0\n \n if self.ip == self.ip_tool.request_ip():\n print(self.ip)\n self.time.sleep(60)\n continue\n else:\n self.ip = self.ip_tool.request_ip()\n self.log_f.write_log_file( self.ip, True)\n #send new ip to mqtt_broker\n continue\n\n \n \n \n \n \n \n\ndef main():\n app = Iprt()\n app.run()\n\n\nif __name__ == \"__main__\": main()","sub_path":"iprt.py","file_name":"iprt.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"371154304","text":"from flask import Flask, render_template, redirect, url_for, request\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup, Comment\nimport random\nfrom colorutils import Color\n\n# initialization\n\napp = Flask(__name__)\n\n@app.after_request\ndef add_header(response):\n response.headers.add('Cache-Control', 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0')\n return(response)\n\n# FUNCTIONS\n\ndef choose_palette():\n hsv2_numb = random.randint(1, 360)\n\n c_light = Color(hsv=(hsv2_numb, 0.15, 0.86))\n light_color = c_light.hex\n\n c_dark = Color(hsv=(hsv2_numb, 0.30, 0.36))\n dark_color = c_dark.hex\n\n return(light_color, dark_color)\n\n# NEWS SOURCES\n\n# -> ny times\ndef nytimes(url):\n page = urlopen(url)\n soup = BeautifulSoup(page, 'html.parser')\n comments = soup.findAll(text=lambda text:isinstance(text, Comment))\n [comment.extract() for comment in comments]\n\n try:\n title = soup.find(\"h1\", class_=\"css-1j5ig2m e1h9rw200\").find_all(text = True)[0]\n except:\n try:\n title = soup.find(\"h1\", class_=\"css-fnr6md e1h9rw200\").find_all(text = True)[0]\n except:\n title = \"\"\n\n clean_list = []\n for s in soup.find_all(\"p\", class_=\"css-exrw3m evys1bk0\"):\n clean_list.append(\"\".join(s.findAll(text = True)))\n\n return(title, clean_list)\n\n# -> mit tech review\ndef mittechreview(url):\n page = urlopen(url)\n soup = BeautifulSoup(page, 'html.parser')\n comments = soup.findAll(text=lambda text:isinstance(text, Comment))\n [comment.extract() for comment in comments]\n\n title = soup.find(\"h1\", class_=\"jsx-2229707591 hed\").find_all(text = True)[0]\n\n clean_list = []\n for s in soup.find_all(\"p\", class_=\"jsx-671803276\"):\n clean_list.append(\"\".join(s.findAll(text = True)))\n\n return(title, clean_list)\n\n# SIMPLE\n\n@app.route('/')\ndef index():\n return(render_template('index.html', text_list = [\"...\"]))\n\n# ADVANCED\n\n@app.route('/advanced')\ndef advanced():\n return(render_template('advanced.html', text_list = [\"...\"]))\n\n# SEARCH (s)\n\n@app.route('/s')\ndef s():\n if request.args:\n url = request.args['url']\n mode = request.args['mode']\n\n if (\"www.nytimes.com\" in url):\n title, text_list = nytimes(url)\n elif (\"www.technologyreview.com\" in url):\n title, text_list = mittechreview(url)\n else:\n return(render_template(\"index.html\", text_list = [\"Oops, error.\"]))\n\n light_color, dark_color = choose_palette()\n\n if (mode == \"simple\"):\n return(render_template(\"index.html\", url = url, title = title, text_list = text_list, light_color = light_color, dark_color = dark_color))\n elif (mode == \"advanced\"):\n return(render_template(\"advanced.html\", url = url, title = title, text_list = text_list, light_color = light_color, dark_color = dark_color))\n else:\n return(render_template(\"index.html\", text_list = [\"Please provide a URL.\"]))\n\n###\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"560850534","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = 'JJ'\nSITENAME = 'Jesué Junior'\nSITEURL = ''\n\nPATH = 'content'\nTHEME = 'themes/jj'\nTIMEZONE = 'America/Sao_Paulo'\n\nDEFAULT_LANG = 'pt-br'\n\nARTICLE_PATHS = ['articles']\nARTICLE_URL = '{slug}'\nSTATIC_PATHS = ['img', 'extra/favicon.ico', 'extra/CNAME', 'extra/robots.txt',\n 'extra/jesuejunior.pub']\n\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\nDEFAULT_PAGINATION = 10\n\n# Uncomment following line if you want document-relative URLs when developing\n#RELATIVE_URLS = True\n\nTYPOGRIFY = True\nGOOGLE_ANALYTICS = True\nLOAD_CONTENT_CACHE = False\nDEFAULT_METADATA = {\n 'status': 'draft',\n}\n\nPLUGIN_PATHS = [\"plugins\"]\nPLUGINS = [\"sitemap\", \"backreftranslate\"]\n\nSITEMAP = {\n 'format': 'xml',\n 'priorities': {\n 'articles': 0.5,\n 'indexes': 0.5,\n 'pages': 0.5\n },\n 'changefreqs': {\n 'articles': 'weekly',\n 'indexes': 'daily',\n 'pages': 'monthly'\n }\n}\n","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"600360349","text":"import os\nimport time\nimport json\n\nfrom dotenv import load_dotenv\n\nPI_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\ndotenv_file = os.path.join(PI_DIR, \"hardware/env\")\nif os.path.isfile(dotenv_file): # pragma: no cover\n load_dotenv(dotenv_path=dotenv_file)\nelse:\n print(\"dotenv_file was not a file\")\n\nfrom hardware.CommunicationsPi.radio_transceiver import Transceiver # noqa: E402\nfrom hardware.CommunicationsPi.comm_pi import CommPi # noqa: E402\nfrom hardware.CommunicationsPi.lan_server import runServer # noqa: E402\nfrom hardware.CommunicationsPi.web_client import WebClient # noqa: E402\nfrom hardware.SensorPi.sense_pi import SensePi # noqa: E402\nfrom hardware.Utils.utils import get_sensor_keys # noqa: E402\nfrom hardware.gpsPi.gps_reader import GPSReader # noqa: E402\n\n\nif os.environ[\"HARDWARE_TYPE\"] == \"commPi\":\n print(\"CommunicationsPi\")\n runServer(handler_class=CommPi)\nelif os.environ[\"HARDWARE_TYPE\"] == \"sensePi\":\n print(\"SensePi\")\n sensor_keys = get_sensor_keys()\n sensor_ids = {}\n sensor_ids[sensor_keys[\"TEMPERATURE\"]] = 2\n sensor_ids[sensor_keys[\"PRESSURE\"]] = 3\n sensor_ids[sensor_keys[\"HUMIDITY\"]] = 4\n sensor_ids[sensor_keys[\"ACCELERATION\"]] = 5\n sensor_ids[sensor_keys[\"ORIENTATION\"]] = 6\n sensePi = SensePi(sensor_ids=sensor_ids)\n gpsPi = GPSReader()\n client = WebClient()\n\n while True:\n print(\"while true\")\n temp = sensePi.get_temperature()\n pres = sensePi.get_pressure()\n hum = sensePi.get_humidity()\n acc = sensePi.get_acceleration()\n orie = sensePi.get_orientation()\n all = sensePi.get_all()\n coords = gpsPi.get_geolocation()\n\n if coords is not None:\n data = [temp, pres, hum, acc, orie, coords, all]\n else:\n data = [temp, pres, hum, acc, orie, all]\n\n for i in data:\n payload = json.dumps(i)\n print(payload)\n try:\n client.ping_lan_server(payload)\n except Exception as err:\n print(\"error occurred: {}\".format(str(err)))\n raise\n time.sleep(1)\nelse:\n print(\"Local Django Server\")\n transceiver = Transceiver()\n url = os.environ.get(\"DJANGO_SERVER_API_ENDPOINT\")\n if url:\n client = WebClient(server_url=url)\n while True:\n data = transceiver.listen()\n if data:\n print(data)\n client.ping_lan_server(json.loads(data))\n else:\n print(\"DJANGO_SERVER_API_ENDPOINT not set\")\n","sub_path":"hardware/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"442648834","text":"#!/usr/bin/env python\n\nimport numpy as np\nfrom numba import cuda\n\nn_arrays = 4096\narray_size = 10000\nnp.random.seed(42)\ndata = cuda.pinned_array((n_arrays, array_size))\nfor i in range(n_arrays):\n data[i] = np.random.random(array_size)\n \ncuda.profile_start()\ndevice_array = cuda.to_device(data)\ncuda.profile_stop()\n\n\n \n","sub_path":"part_three/pinned_memory_example.py","file_name":"pinned_memory_example.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"123619070","text":"import twitter\nfrom flask import Blueprint, render_template, request, current_app as app\nfrom sklearn.externals import joblib\n\n\nanalytic = Blueprint('analytic', __name__)\n\n\n@analytic.route('/')\ndef home():\n return 'sentiment analytic app'\n\n \n@analytic.route('/search', methods=['GET', 'POST'])\ndef search():\n count = 100\n statuses = []\n q = ''\n \n if request.method == 'POST':\n q = request.form['q']\n \n auth = twitter.oauth.OAuth(\n app.config['ACCESS_TOKEN'],\n app.config['ACCESS_TOKEN_SECRET'],\n app.config['CONSUMER_KEY'],\n app.config['CONSUMER_SECRET']\n )\n \n twitter_api = twitter.Twitter(auth=auth)\n \n search_results = twitter_api.search.tweets(q=q, count=count)\n \n statuses = search_results['statuses']\n \n return render_template('search.html', statuses=statuses, q=q)\n \n \n@analytic.route('/classify', methods=['POST'])\ndef classify():\n sentence = request.form['sentence']\n sentence = sentence.translate(dict((ord(char), None) for char in \"1234567890'\"))\n vect = joblib.load('E:/PROGRAMMING/python/projects/sentiment/my_app/analytic/vect.pkl')\n tf = joblib.load('E:/PROGRAMMING/python/projects/sentiment/my_app/analytic/tf.pkl')\n fs = joblib.load('E:/PROGRAMMING/python/projects/sentiment/my_app/analytic/fs.pkl')\n svm = joblib.load('E:/PROGRAMMING/python/projects/sentiment/my_app/analytic/clf.pkl')\n bow = vect.transform([sentence])\n X = tf.transform(bow)\n X = fs.transform(X)\n predict = svm.predict(X)\n return predict[0]","sub_path":"my_app/analytic/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"414447900","text":"#coding=utf-8\n\nimport unittest\n\n\"\"\"\n\nConnected Component in Undirected Graph\n\n\nFind the number connected component in the undirected graph. Each node in the graph contains a label and a list of its \nneighbors. (a connected component (or just component) of an undirected graph is a subgraph in which any two vertices \nare connected to each other by paths, and which is connected to no additional vertices in the supergraph.)\n\n Notice\n\nEach connected component should sort by label.\n\nHave you met this question in a real interview? Yes\nClarification\nLearn more about representation of graphs\n\nExample\nGiven graph:\n\nA------B C\n \\ | | \n \\ | |\n \\ | |\n \\ | |\n D E\nReturn {A,B,D}, {C,E}. Since there are two connected component which is {A,B,D}, {C,E}\n\nTags \nBreadth First Search Union Find\nRelated Problems \nMedium Graph Valid Tree 26 %\nMedium Find the Weak Connected Component in the Directed Graph\n\n\"\"\"\n\n\n# Definition for a undirected graph node\n# class UndirectedGraphNode:\n# def __init__(self, x):\n# self.label = x\n# self.neighbors = []\nclass Solution:\n # @param {UndirectedGraphNode[]} nodes a array of undirected graph node\n # @return {int[][]} a connected set of a undirected graph\n \"\"\"\n used bfs / dfs for this one (undirected graph)\n \"\"\"\n def connectedSet(self, nodes):\n # Write your code here\n result = []\n visited = {}\n for node in nodes:\n group = {}\n self.travel(node, group, visited)\n if group:\n result.append(sorted(group.keys()))\n return result\n\n def travel(self, node, group, visited):\n if visited.get(node.label):\n #if visited[node.label]: # can directly use this, may cause KeyError\n return\n visited[node.label] = True\n group[node.label] = True\n for nei in node.neighbors:\n self.travel(nei, group, visited)\n\n\nclass SolutionTester(unittest.TestCase):\n def setUp(self):\n self.sol = Solution()\n\n def test_case1(self):\n nums = 1\n answer = 1\n result = self.sol.connectedSet(nums)\n self.assertEqual(answer, result)\n\n\ndef main():\n suite = unittest.TestLoader().loadTestsFromTestCase(SolutionTester)\n unittest.TextTestRunner(verbosity=2).run(suite)\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n#-*- coding:utf-8 -*-\n\n\"\"\"\n\nclass Solution:\n # @param {UndirectedGraphNode[]} nodes a array of undirected graph node\n # @return {int[][]} a connected set of a undirected graph\n def dfs(self, x, tmp):\n self.v[x.label] = True\n tmp.append(x.label)\n for node in x.neighbors:\n if not self.v[node.label]:\n self.dfs(node, tmp)\n \n def connectedSet(self, nodes):\n # Write your code here\n self.v = {}\n for node in nodes:\n self.v[node.label] = False\n\n ret = []\n for node in nodes:\n if not self.v[node.label]:\n tmp = []\n self.dfs(node, tmp)\n ret.append(sorted(tmp))\n return ret\n \n\n\n\"\"\"","sub_path":"mjbeto/connected_component_in_undirected_graph.py","file_name":"connected_component_in_undirected_graph.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"575428304","text":"import unittest\n\nfrom rpy2.rinterface import RRuntimeError\n\nfrom montante.tests.BaseTest import BaseTest\nfrom montante.operations.train import training_operation\nfrom montante.operations.predict import prediction_operation\n\n\nclass TestCaretTrainingAndPrediction(BaseTest):\n\n def setUp(self):\n super()\n self.iris_df = self._iris_dataset()\n self.caret_c50 = training_operation(self.iris_df, self._iris_payload())\n\n def test_prediction_ok(self):\n p = prediction_operation(self.caret_c50, {\n 'petal_width_cm': [1, 1, 1],\n 'sepal_length_cm': [1, 1, 1],\n 'sepal_width_cm': [1, 1, 1],\n 'petal_length_cm': [1, 1, 1]\n })\n\n self.assertEqual(len(p), 3)\n\n def test_prediction_bad_type_whithout_checking(self):\n with self.assertRaises(RRuntimeError):\n prediction_operation(self.caret_c50, {\n 'petal_width_cm': [\"a\", \"b\", \"c\"],\n 'sepal_length_cm': [1, 1, 1],\n 'sepal_width_cm': [1, 1, 1],\n 'petal_length_cm': [1, 1, 1]\n })\n\n def test_prediction_with_column_missing(self):\n with self.assertRaises(RRuntimeError):\n prediction_operation(self.caret_c50, {\n 'sepal_length_cm': [1, 1, 1],\n 'sepal_width_cm': [1, 1, 1],\n 'petal_length_cm': [1, 1, 1]\n })\n\n def test_prediction_with_unrecognized_extra_column(self):\n with self.assertRaises(RRuntimeError):\n prediction_operation(self.caret_c50, {\n 'sepal_length_cm': [1, 1, 1],\n 'sepal_width_cm': [1, 1, 1],\n 'petal_length_cm': [1, 1, 1],\n 'random_string': [1, 1, 1]\n })\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"montante/tests/test_caret_training_and_prediction.py","file_name":"test_caret_training_and_prediction.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"367718933","text":"\"\"\"Module for creating Cloudnet liquid water content file\nusing scaled-adiabatic method.\n\"\"\"\nimport numpy as np\nimport numpy.ma as ma\nfrom cloudnetpy import utils, atmos, output\nfrom cloudnetpy.categorize import DataSource\nfrom cloudnetpy.products import product_tools as p_tools\nfrom cloudnetpy.metadata import MetaData\nfrom cloudnetpy.products.product_tools import CategorizeBits\n\nG_TO_KG = 0.001\n\n\ndef generate_lwc(categorize_file, output_file):\n \"\"\"Generates Cloudnet liquid water content product.\n\n Args:\n categorize_file (str): Categorize file name.\n output_file (str): Output file name.\n\n Examples:\n >>> from cloudnetpy.products.lwc import generate_lwc\n >>> generate_lwc('categorize.nc', 'lwc.nc')\n\n \"\"\"\n lwc_source = LwcSource(categorize_file)\n lwc_obj = Lwc(lwc_source)\n lwc_obj.adjust_clouds_to_match_lwp()\n lwc_obj.screen_rain()\n _append_data(lwc_source, lwc_obj)\n output.update_attributes(lwc_source.data, LWC_ATTRIBUTES)\n output.save_product_file('liquid water content', lwc_source, output_file,\n copy_from_cat=('lwp', 'lwp_error'))\n\n\nclass LwcSource(DataSource):\n \"\"\"Data container for liquid water content calculations. It reads\n input data from a categorize file and provides data structures and\n methods for holding the results.\n \"\"\"\n def __init__(self, categorize_file):\n super().__init__(categorize_file)\n self.lwp = self.getvar('lwp')\n self.lwp_error = self.getvar('lwp_error')\n self.is_rain = self.getvar('is_rain')\n self.dheight = utils.mdiff(self.getvar('height'))\n self.atmosphere = self._get_atmosphere(categorize_file)\n self.categorize_bits = CategorizeBits(categorize_file)\n\n @staticmethod\n def _get_atmosphere(categorize_file):\n fields = ['temperature', 'pressure']\n return p_tools.interpolate_model(categorize_file, fields)\n\n\nclass Lwc:\n \"\"\"Class handling the actual LWC calculations.\"\"\"\n def __init__(self, lwc_source):\n self.lwc_source = lwc_source\n self.dheight = self.lwc_source.dheight\n self.echo = self._get_echo()\n self.is_liquid = self._get_liquid()\n self.lwc_adiabatic = self._init_lwc_adiabatic()\n self.lwc = self._adiabatic_lwc_to_lwc()\n self.status = self._init_status()\n self.lwc_error = self._calc_lwc_error()\n\n def _calc_lwc_error(self):\n \"\"\"Estimates error in liquid water content.\n\n TODO: Check the error calculation.\n \"\"\"\n lwc_error = np.zeros_like(self.lwc)\n lwp_relative_error = self.lwc_source.lwp_error / self.lwc_source.lwp\n ind = ma.where(self.lwc)\n lwc_gradient = utils.l2norm(*np.gradient(self.lwc))\n combined_error = utils.l2norm(lwc_gradient, utils.transpose(lwp_relative_error))\n lwc_error[ind] = combined_error[ind]\n lwc_error[lwc_error == 0] = ma.masked\n return lwc_error\n\n def _get_echo(self):\n quality_bits = self.lwc_source.categorize_bits.quality_bits\n return {'radar': quality_bits['radar'], 'lidar': quality_bits['lidar']}\n\n def _get_liquid(self):\n category_bits = self.lwc_source.categorize_bits.category_bits\n return category_bits['droplet']\n\n def _init_lwc_adiabatic(self):\n \"\"\"Returns theoretical adiabatic lwc in liquid clouds (g/m3).\"\"\"\n lwc_dz = atmos.fill_clouds_with_lwc_dz(self.lwc_source.atmosphere,\n self.is_liquid)\n return atmos.calc_adiabatic_lwc(lwc_dz, self.dheight)\n\n def _adiabatic_lwc_to_lwc(self):\n \"\"\"Initialises liquid water content (g/m3).\n\n Calculates LWC for ALL profiles (rain, lwp > theoretical, etc.),\n \"\"\"\n lwc_scaled = atmos.distribute_lwp_to_liquid_clouds(self.lwc_adiabatic,\n self.lwc_source.lwp)\n return lwc_scaled / self.dheight\n\n def _init_status(self):\n status = ma.zeros(self.is_liquid.shape, dtype=int)\n status[self.is_liquid] = 1\n return status\n\n def adjust_clouds_to_match_lwp(self):\n \"\"\"Adjust clouds (where possible) so that theoretical and measured LWP agree.\"\"\"\n adjustable_clouds = self._find_adjustable_clouds()\n self._adjust_cloud_tops(adjustable_clouds)\n self.lwc = self._adiabatic_lwc_to_lwc()\n\n def _find_lwp_difference(self):\n \"\"\"Returns difference of theoretical LWP and measured LWP (g/m2).\n\n In theory, this difference should be always positive. Negative values\n indicate missing (or too narrow) liquid clouds.\n \"\"\"\n lwc_sum = ma.sum(self.lwc_adiabatic, axis=1) * self.dheight\n return lwc_sum - self.lwc_source.lwp\n\n def _find_adjustable_clouds(self):\n\n def _find_echo_combinations_in_liquid():\n \"\"\"Classifies liquid clouds by detection type: 1=lidar, 2=radar, 3=both.\"\"\"\n lidar_detected = (self.is_liquid & self.echo['lidar']).astype(int)\n radar_detected = (self.is_liquid & self.echo['radar']).astype(int) * 2\n return lidar_detected + radar_detected\n\n def _find_lidar_only_clouds(detection):\n \"\"\"Finds top clouds that contain only lidar-detected pixels.\n\n Args:\n detection_type (ndarray): Array of integers where 1=lidar, 2=radar,\n 3=both.\n\n Returns:\n ndarray: Boolean array containing top-clouds that are detected only\n by lidar.\n\n \"\"\"\n sum_of_cloud_pixels = ma.sum(detection > 0, axis=1)\n sum_of_detection_type = ma.sum(detection, axis=1)\n return sum_of_cloud_pixels / sum_of_detection_type == 1\n\n def _remove_good_profiles():\n no_rain = ~self.lwc_source.is_rain.astype(bool)\n lwp_difference = self._find_lwp_difference()\n dubious_profiles = (lwp_difference < 0) & no_rain\n top_clouds[~dubious_profiles, :] = 0\n\n top_clouds = find_topmost_clouds(self.is_liquid)\n detection_type = _find_echo_combinations_in_liquid()\n detection_type[~top_clouds] = 0\n lidar_only_clouds = _find_lidar_only_clouds(detection_type)\n top_clouds[~lidar_only_clouds, :] = 0\n _remove_good_profiles()\n return top_clouds\n\n def _adjust_cloud_tops(self, adjustable_clouds):\n \"\"\"Adjusts cloud top index so that measured lwc corresponds to\n theoretical value.\n \"\"\"\n def _has_converged(time_ind):\n lwc_sum = ma.sum(self.lwc_adiabatic[time_ind, :])\n if lwc_sum * self.dheight > self.lwc_source.lwp[time_ind]:\n return True\n return False\n\n def _adjust_lwc(time_ind, base_ind):\n lwc_base = self.lwc_adiabatic[time_ind, base_ind]\n distance_from_base = 1\n while True:\n top_ind = base_ind + distance_from_base\n lwc_top = lwc_base * (distance_from_base + 1)\n self.lwc_adiabatic[time_ind, top_ind] = lwc_top\n if not self.status[time_ind, top_ind]:\n self.status[time_ind, top_ind] = 3\n if _has_converged(time_ind):\n break\n distance_from_base += 1\n\n def _update_status(time_ind):\n alt_indices = np.where(self.is_liquid[time_ind, :])[0]\n self.status[time_ind, alt_indices] = 2\n\n for time_index in np.unique(np.where(adjustable_clouds)[0]):\n base_index = np.where(adjustable_clouds[time_index, :])[0][0]\n _update_status(time_index)\n _adjust_lwc(time_index, base_index)\n\n def screen_rain(self):\n \"\"\"Masks profiles with rain.\"\"\"\n is_rain = self.lwc_source.is_rain.astype(bool)\n self.lwc[is_rain, :] = ma.masked\n self.lwc_error[is_rain, :] = ma.masked\n self.status[is_rain, :] = 6\n\n\ndef find_topmost_clouds(is_cloud):\n \"\"\"From 2d binary cloud field, return the uppermost cloud layer only.\n\n Args:\n is_cloud (ndarray): Boolean array denoting presence of clouds.\n\n Returns:\n ndarray: Copy of input array containing only the uppermost cloud\n layer in each profile.\n\n \"\"\"\n top_clouds = np.copy(is_cloud)\n cloud_edges = top_clouds[:, :-1][:, ::-1] < top_clouds[:, 1:][:, ::-1]\n topmost_bases = is_cloud.shape[1] - 1 - np.argmax(cloud_edges, axis=1)\n for n, base in enumerate(topmost_bases):\n top_clouds[n, :base] = 0\n return top_clouds\n\n\ndef _append_data(lwc_data, lwc_obj):\n lwc_data.append_data(lwc_obj.lwc * G_TO_KG, 'lwc', units='kg m-3')\n lwc_data.append_data(lwc_obj.lwc_error * G_TO_KG, 'lwc_error', units='kg m-3')\n lwc_data.append_data(lwc_obj.status, 'lwc_retrieval_status')\n\n\nCOMMENTS = {\n 'lwc':\n ('This variable was calculated for the profiles where the categorization\\n'\n 'data has diagnosed that liquid water is present and liquid water path is\\n'\n 'available from a coincident microwave radiometer. The model temperature\\n'\n 'and pressure were used to estimate the theoretical adiabatic liquid water\\n'\n 'content gradient for each cloud base and the adiabatic liquid water\\n'\n 'content is then scaled that its integral matches the radiometer\\n'\n 'measurement so that the liquid water content now follows a quasi-adiabatic\\n'\n 'profile. If the liquid layer is detected by the lidar only, there is the\\n'\n 'potential for cloud top height to be underestimated and so if the\\n'\n 'adiabatic integrated liquid water content is less than that measured by\\n'\n 'the microwave radiometer, the cloud top is extended until the adiabatic\\n'\n 'integrated liquid water content agrees with the value measured by the\\n'\n 'microwave radiometer. Missing values indicate that either\\n'\n '1) a liquid water layer was diagnosed but no microwave radiometer data was\\n'\n ' available,\\n'\n '2) a liquid water layer was diagnosed but the microwave radiometer data\\n'\n ' was unreliable; this may be because a melting layer was present in the\\n'\n ' profile, or because the retrieved lwp was unphysical (values of zero\\n'\n ' are not uncommon for thin supercooled liquid layers)\\n'\n '3) that rain is present in the profile and therefore, the vertical extent\\n'\n ' of liquid layers is difficult to ascertain.'),\n\n 'lwc_error':\n ('This variable is an estimate of the random error in liquid water content\\n'\n 'due to the uncertainty in the microwave radiometer liquid water path\\n'\n 'retrieval and the uncertainty in cloud base and/or cloud top height.'),\n\n 'lwc_retrieval_status':\n ('This variable describes whether a retrieval was performed for each pixel,\\n'\n 'and its associated quality, in the form of 6 different classes. The classes\\n'\n 'are defined in the definition and long_definition attributes.\\n'\n 'The most reliable retrieval is that when both radar and lidar detect the\\n'\n 'liquid layer, and microwave radiometer data is present, indicated by the\\n'\n 'value 1. The next most reliable is when microwave radiometer data is used\\n'\n 'to adjust the cloud depth when the radar does not detect the liquid layer,\\n'\n 'indicated by the value 2, with a value of 3 indicating the cloud pixels\\n'\n 'that have been added at cloud top to avoid the profile becoming\\n'\n 'superadiabatic. A value of 4 indicates that microwave radiometer data\\n'\n 'were not available or not reliable (melting level present or unphysical\\n'\n 'values) but the liquid layers were well defined. If cloud top was not\\n'\n 'well defined then this is indicated by a value of 5. The full retrieval of\\n'\n 'liquid water content, which requires reliable liquid water path from the\\n'\n 'microwave radiometer, was only performed for classes 1-3. No attempt is\\n'\n 'made to retrieve liquid water content when rain is present; this is\\n'\n 'indicated by the value 6.'),\n}\n\nDEFINITIONS = {\n 'lwc_retrieval_status':\n ('\\n'\n 'Value 0: No liquid water detected\\n'\n 'Value 1: Reliable retrieval\\n'\n 'Value 2: Adiabatic retrieval where cloud top has been adjusted to match\\n'\n ' liquid water path from microwave radiometer because layer is not\\n'\n ' detected by radar.\\n'\n 'Value 3: Adiabatic retrieval: new cloud pixels where cloud top has been\\n'\n ' adjusted to match liquid water path from microwave radiometer\\n'\n ' because layer is not detected by radar.\\n'\n 'Value 4: No retrieval: either no liquid water path is available or liquid\\n'\n ' water path is uncertain.\\n'\n 'Value 5: No retrieval: liquid water layer detected only by the lidar and\\n'\n ' liquid water path is unavailable or uncertain:\\n'\n ' cloud top may be higher than diagnosed cloud top since lidar\\n'\n ' signal has been attenuated.\\n'\n 'Value 6: Rain present: cloud extent is difficult to ascertain and liquid\\n'\n ' water path also uncertain.'),\n}\n\nLWC_ATTRIBUTES = {\n 'lwc': MetaData(\n long_name='Liquid water content',\n comment=COMMENTS['lwc'],\n ancillary_variables='lwc_error'\n ),\n 'lwc_error': MetaData(\n long_name='Random error in liquid water content, one standard deviation',\n comment=COMMENTS['lwc_error'],\n ),\n 'lwc_retrieval_status': MetaData(\n long_name='Liquid water content retrieval status',\n comment=COMMENTS['lwc_retrieval_status'],\n definition=DEFINITIONS['lwc_retrieval_status']\n ),\n}\n","sub_path":"cloudnetpy/products/lwc.py","file_name":"lwc.py","file_ext":"py","file_size_in_byte":13851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"471786829","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n# Create your views here.\nfrom rest_framework.views import APIView\nfrom rest_framework.parsers import MultiPartParser, FormParser\nfrom rest_framework.response import Response\nfrom rest_framework import status\nimport requests\nfrom django.views.decorators.csrf import ensure_csrf_cookie\n\nfrom django.http import JsonResponse\nfrom django.core import serializers\n\nfrom .serializers import FileSerializer\nfrom django.views.decorators.csrf import csrf_exempt\n\nimport json\nimport time\n\n@ensure_csrf_cookie\ndef send_json(request):\n if request.method == \"POST\":\n \n first_name = request.POST.get('username')\n IP = request.POST.get('ip')\n\n # x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')\n # ip = request.META.get('REMOTE_ADDR')\n\n \n url = 'https://vsrequest.video/request.php?key=frSQnQ6ck5CIl5t4&secret_key=sdyebvzptylnjl5s06ukz7kurjis31&video_id='+first_name+'&ip='+IP\n x = requests.get(url)\n \n \n ticket = x.text\n\n \n \n \n \n data12 = [{'name': first_name, 'ticket': ticket}]\n\n\n return JsonResponse(data12,safe=False)\n\ndef search_episodes(request):\n if request.method == 'POST':\n episodeid = request.POST.get('episodeid')\n ES = request.POST.get('sezona')\n IP = request.POST.get('ip')\n EE = request.POST.get('ee')\n url = 'https://vsrequest.video/request.php?key=frSQnQ6ck5CIl5t4&secret_key=sdyebvzptylnjl5s06ukz7kurjis31&video_id='+episodeid+'&tv=1&s='+ES+'&ip='+IP+'&e='+EE\n\n ticket_episode = requests.get(url)\n \n ticket_episode_text = ticket_episode.text + '&e=' + EE\n print(ticket_episode_text)\n print(episodeid)\n print(ES)\n print(IP)\n print(EE)\n episode_data = [{'ticket':ticket_episode_text,'name':episodeid}]\n print(episode_data)\n print(url)\n \n return JsonResponse(episode_data,safe=False)\n\n\ndef search_movie(request):\n if request.method == 'POST':\n\n search = request.POST.get('search')\n url2 = 'http://www.omdbapi.com/?s='+search+'&apikey=9ff0e32f'\n movies = requests.get(url2)\n resp = movies.json()\n\n return JsonResponse(resp,safe=False)\n\n\n\n\n \n\n \n \n\n\n\n \n\n ","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"589530109","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Jan 16 16:06:26 2021\r\n\r\nScript para carregar \r\n\r\n@author: Rodrigo Torres\r\n\"\"\"\r\n\r\nimport time\r\n# import numpy as np\r\nimport clr\r\nimport MissionPlanner\r\n\r\nclr.AddReference(\"MissionPlanner\")\r\nclr.AddReference(\"MissionPlanner.Utilities\")\r\nclr.AddReference(\"MAVLink\")\r\nimport MAVLink\r\n\r\n\r\nglobal n_samples\r\nn_samples=25\r\n\r\nclass Voltage():\r\n def __init__(self):\r\n print ('Initializing')\r\n self.initial_time=time.time()\r\n self.voltage_list=[]\r\n self.voltage_list=[49]\r\n # self.voltage_list=[]\r\n self.delta_time_list=[0.1]\r\n self.time_list=[time.time()]\r\n \r\n def update_voltage(self,voltage):\r\n \r\n self.voltage_list.append(voltage)\r\n \r\n self.delta_time_list.append(time.time()-self.time_list[-1])\r\n self.time_list.append(time.time())\r\n if len(self.voltage_list)>n_samples-1: # Take last 10 values\r\n self.voltage_list=self.voltage_list[-n_samples:]\r\n self.delta_time_list=self.delta_time_list[-n_samples:]\r\n \r\n # print(self.voltage_list)\r\n \r\n def voltage_state(self):\r\n if len(self.voltage_list)v1:\r\n self.Voltage_State='C'#'harging'\r\n else:\r\n self.Voltage_State='N'#'otCharging'\r\n \r\n \r\nclass PID():\r\n \r\n def __init__(self):\r\n # self.target_voltage=48.0\r\n self.PID_Pgain=0.24 #Original 0.24\r\n self.PID_Dgain=0.012 #Original 0.012\r\n self.PID_Igain=0.012 #Original 0.012\r\n self.PID_Windupgain=5 #Original 5\r\n self.pwm_servo=0.15\r\n self.min_pwm_servo=0.21\r\n self.max_pwm_servo=0.26\r\n self.last_error=0\r\n self.last_integral=0\r\n self.last_command=self.pwm_servo\r\n \r\n def define_target_voltage(self,target_voltage):\r\n self.target_voltage=target_voltage\r\n print('Target Voltage defined at:',self.target_voltage)\r\n \r\n def calculate_pwm(self,voltage_state,voltage,sample_time):\r\n if voltage_state=='Unknown':\r\n self.pwm_servo=self.pwm_servo\r\n else:\r\n error=(self.target_voltage-voltage)\r\n self.P_gain=self.PID_Pgain*error\r\n if sample_time<=0.001:\r\n # self.D_gain=0\r\n # self.I_gain=0\r\n sample_time=0.01\r\n else:\r\n integral=self.last_integral+((self.last_command-self.pwm_servo)*self.PID_Windupgain*sample_time+error*self.PID_Igain)*sample_time\r\n self.I_gain=integral\r\n self.D_gain=self.PID_Dgain*(self.last_error-error)/sample_time\r\n # Update Values\r\n self.last_error=error\r\n self.last_integral=integral \r\n self.pwm_servo=self.pwm_servo+self.P_gain+self.D_gain+self.I_gain\r\n \r\n \r\n # Saturate Commandas \r\n self.pwm_servo=max(min(self.max_pwm_servo,self.pwm_servo),self.min_pwm_servo)\r\n self.last_command=self.pwm_servo\r\n # print(self.pwm_servo)\r\n \r\n\r\n## Params\r\n# initial_voltage=45 #cs.voltage\r\ninitial_voltage=cs.battery_voltage\r\n# target_voltage=initial_voltage+0.50\r\n# initial_value=0.15\r\n# armed_state=False\r\narmed_state=cs.armed\r\n# rpm=10000#cs.rpm1\r\nrpm=cs.rpm1\r\nmax_time=60*1 # In Seconds\r\n\r\nPWM_SERVO_MIN =900# Script.GetParam('SERVO'+str(int(PWM_SERVO_CHANNEL))+'_MIN')\r\nPWM_SERVO_MAX =1750# Script.GetParam('SERVO'+str(int(PWM_SERVO_CHANNEL))+'_MAX')\r\nPWM_SERVO_RANGE = PWM_SERVO_MAX - PWM_SERVO_MIN\r\nPWM_SERVO_OFFSET = PWM_SERVO_MIN \r\nPWM_SERVO_CHANNEL = 13\r\n\r\ninitial_time=time.time()\r\n\r\n# voltage_list=[45]#[cs.voltage]\r\n\r\nif armed_state == True:\r\n print('Não Execute o Script com a Aeronave Armada')\r\n \r\n\r\nelif rpm<1800:\r\n print('Moto-Gerador não ligado. Execute o script de partida antes de carregar a bateria')\r\n\r\nelif armed_state == False and rpm > 1800: # Aeronave no chao com motor ligado\r\n MissionPlanner.MainV2.speechEngine.SpeakAsync(\"Carregando a Bateria do Dractor 25 A\")\r\n # Main Loop\r\n V=Voltage()\r\n V.voltage_state()\r\n PID=PID()\r\n PID.define_target_voltage(cs.battery_voltage+0.5)\r\n \r\n while (time.time()-initial_time 1:\n fat = fat * n\n n = n - 1\n return fat\n\n\ndef binomialnk(n, k):\n \"\"\"Função que retorna o número binomial.\"\"\"\n return factorial(n) // (factorial(k) * factorial(n - k))\n\n\n# Implementação de testes\nn1 = int(input(\"Insira o valor de (n) do meu coeficiente binomial: \"))\nn2 = int(input(\"Agora insira o valor de (k): \"))\nprint(\"O resultado do meu coeficiente binomial é:\", binomialnk(n1, n2))\n","sub_path":"aula_coeffbino.py","file_name":"aula_coeffbino.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"31026309","text":"class Solution:\n def dominantIndex(self, nums: List[int]) -> int:\n if len(nums) == 0:\n return -1\n\n highest = -1\n secondHighest = -1\n highestIndex = 0\n\n for i, n in enumerate(nums):\n\n # Find the highest number\n if n >= highest:\n secondHighest = highest\n highest = n\n highestIndex = i\n\n # Find the second highest number\n elif n > secondHighest:\n secondHighest = n\n\n if highest < 2 * secondHighest:\n return -1\n\n return highestIndex\n","sub_path":"Problems/Leetcode/747_LargestNumberAtLeastTwiceOfOthers.py","file_name":"747_LargestNumberAtLeastTwiceOfOthers.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"570190741","text":"#!/usr/bin/env python\n\n#import all required libraries\nimport webapp2\nimport json\nimport time\nimport cachetools\nfrom google.appengine.ext import ndb\nfrom google.appengine.api import memcache\nimport operator\nfrom datetime import datetime\n\n## declaring static variables\nPREFIXES = ['reasonginserver', 'defaultrecs']## prefixes for the key\nTOP_N = 5## number of default articles\n\n## initializing cache\ncache_recs = cachetools.LRUCache(maxsize=5000) ## holds local cache for recommendations\ncache = cachetools.LRUCache(maxsize=10000) ## holds all other types of cache\n\n## Sample Models as per information provided by the entities \n## that might be used. Just for my reference and client's understanding on\n## the structure\n\nclass Templates(ndb.Model):\n \"\"\" Model class for templates for testing \"\"\"\n appId = ndb.StringProperty()\n articleIdSelector = ndb.StringProperty()\n articleTitleSelector = ndb.StringProperty()\n articleSubtitleSelector = ndb.StringProperty()\n articleBodySelector = ndb.StringProperty()\n articlegenomeServer = ndb.StringProperty()\n baseurl = ndb.StringProperty()\n renderMethod = ndb.StringProperty()\n\nclass Recommendations(ndb.Model):\n \"\"\"Model class for Recommendations for testing\"\"\"\n articleId = ndb.StringProperty() \n title = ndb.StringProperty()\n keywords = ndb.StringProperty()\n tags = ndb.StringProperty()\n\nclass MyData(ndb.Model):\n \"\"\"Model class for Key/value pair for testing\"\"\"\n keyString = db.StringProperty()\n valueString = db.StringProperty()\n\nclass Default_Reccommendations(db.Model):\n \"\"\"Model class for Default Recommendations for testing\"\"\"\n myKey = db.StringProperty(required=True)\n myTopArticles = db.StringProperty(required=True)\n\n## Defining all the required handlers \n\nclass JavascriptHandler(webapp2.RequestHandler):\n \"\"\"Handler for '/XX/articleinject.js?ver=QQ' api' \"\"\"\n\n def get(self, app = None):\n \"\"\" get function to handle the get requests to JavascriptHandler\n self.ver = the version of the template required \n self.app = application name\n self.temp_key = key name for the template\n self.appdata_key = key name for the appdata\n self.instantiated_template_key = key name for the instantiated template\n self.template_in_cache = boolean to check whether template in cache\n self.appdata_in_cache = boolean to check whether appdata in cache\n \"\"\"\n\n self.ver = self.request.get('ver') \n self.app = app\n self.temp_key = 'jstemplate:v' + self.ver\n self.time_temp_key = 'time_jstemplate:v' + self.ver\n self.appdata_key = 'appdata:' + self.app\n self.time_appdata_key = 'time_appdata:' + self.app\n self.instantiated_template_key = 'instantiated:' + self.ver + ':' + self.app\n self.appData_in_cache = True\n self.template_in_cache = True\n\n ## retreive last time template was fetched from cache\n ## if time > 4 hours(14400), request from memcache\n ## if not in memcache, request from datastore. Add to memcache. Add to local cache\n \n template_time = cache.get(self.time_temp_key)\n\n if template_time is not None:\n curr_time = datetime.now()\n delta = curr_time - template_time\n if delta.total_seconds() > 14400:\n ## last fetch was more than 4 hours ago. fetch from memcache/datastore\n template = memcache.get(self.temp_key)\n if template is None:\n template_in_cache = False\n template_key = ndb.key('Templates', self.temp_key) ## Change 'Templates' with the actual entity name\n template = template_key.get()\n\n # add to template to memcache and template as well as time to local cache\n memcache.add(self.temp_key, template)\n cache.update([(self.temp_key, template)])\n cache.update([(self.time_temp_key, datetime.now())])\n\n else:\n ## less than 4 hours old entry exists in cache. fetch it\n template = cache.get(self.temp_key)\n \n else:\n template = memcache.get(self.temp_key)\n cache.update([(self.time_temp_key, datetime.now())]) ## if the template was available in memcache\n\n if template is None:\n template_in_cache = False\n template_key = ndb.key('Templates', self.temp_key) ## Change 'Templates' with the actual entity name\n template = template_key.get()\n\n # add to template to memcache and template as well as time to local cache\n memcache.add(self.temp_key, template)\n cache.update([(self.temp_key, template)])\n cache.update([(self.time_temp_key, datetime.now())])\n\n\n ## retreive last time appdata was fetched from cache\n ## if time > 4 hours(14400), request from memcache\n ## if not in memcache, request from datastore. Add to memcache. Add to local cache\n \n appdata_time = cache.get(self.time_appdata_key)\n\n if appdata_time is not None:\n curr_time = datetime.now()\n delta = curr_time - appdata_time\n if delta.total_seconds() > 14400:\n ## last fetch was more than 4 hours ago. fetch from memcache/datastore\n appData = memcache.get(self.appdata_key)\n cache.update([(self.time_appdata_key, datetime.now())]) ## if the template was available in memcache\n appData_in_cache = False\n if appData is None:\n appData_in_cache = False\n appData_key = ndb.key('ApplicationData', self.appdata_key) ## Change 'Templates' with the actual entity name\n appData = appData_key.get()\n\n # add to template to memcache and template as well as time to local cache\n memcache.add(self.appdata_key, appData)\n cache.update([(self.appdata_key, appData)])\n cache.update([(self.time_appdata_key, datetime.now())])\n\n else:\n ## less than 4 hours old entry exists in cache. fetch it\n appData = cache.get(self.appdata_key)\n \n else:\n appData = memcache.get(self.appdata_key)\n cache.update([(self.time_appdata_key, datetime.now())]) ## if the template was available in memcache\n appData_in_cache = False\n if appData is None:\n appData_in_cache = False\n appData_key = ndb.key('ApplicationData', self.appdata_key) ## Change 'Templates' with the actual entity name\n appData = appData_key.get()\n\n # add to template to memcache and template as well as time to local cache\n memcache.add([(self.appdata_key, appData)])\n cache.update([(self.appdata_key, appData)])\n cache.update([(self.time_appdata_key, datetime.now())])\n\n\n ## check whether both template and app data found from cache\n ## else if anyone is false, recalculate the value by\n ## replacing the key with the values from appData\n ## and store back to local cache\n ## else if both true retrieve from local cache\n if self.appData_in_cache and self.template_in_cache:\n return cache.get(self.instantiated_template_key)\n else:\n for key, value in appData:\n template.replace('{{' + key + '}}', value)\n \n cache.update([(self.instantiated_template_key, template)])\n \n return template\n \n\nclass RecommendationsHandler(webapp2.RequestHandler):\n \"\"\"Handler for /getRecommendations?appId=XX&articleId=YY&clientId=ZZ api \"\"\"\n\n def get(self):\n \"\"\"get function to handle the get requests to RecommendationsHandler\n self.appId = application id\n self.articleId = article id\n self.clientId = client id\n self.recommendation_key = recommendation key based on application id and article id\n self.requestedpull = request pull key\n self.default_recs_key = default recommendation key\n self.counter_key = key for the counter for the articles\n \"\"\"\n\n self.appId = self.request.get('appId')\n self.articleId = self.request.get('articleId')\n self.clientId = self.request.get('clientId')\n self.recommendation_key = 'rec:' + self.appId + ':' + self.articleId\n self.requestedpull_key = 'requestedpull:' + self.appId + ':' + self.articleId\n self.default_recs_key = 'defaultrecs:' + self.appId\n self.counter_key = 'articleCounter' \n self.appid_key = 'appdata:' + self.appId\n self.reasoningserver_key = 'reasoningserver:' + self.appId \n\n ## get recommendations from local cache. Else\n ## if not found get data from memcache. If not found get from datastore\n recs = cache_recs.get(self.recommendation_key) \n if recs is None:\n ## no recommendations found in local cache\n ## pull from memcache. else from datastore \n recs = memcache.get(self.recommendation_key)\n if recs:\n cache_recs.update([(self.recommendation_key, recs)])\n ## get the counter ticker from the cache\n ## if not found, initialize as a dictionary\n ## if found, check whether the current value is present\n ## if yes, add one the count. Else add the key\n counterTicker = cache.get(self.counter_key)\n if counterTicker is None:\n counterTicker = {}\n counterTicker[self.appId + '/' + self.articleId] = 1\n else:\n if (self.appId + '/' + self.articleId) not in counterTicker.keys():\n counterTicker[self.appId + '/' + self.articleId] = 1\n else:\n counterTicker[self.appId + '/' + self.articleId] += 1 \n\n return {'status': 'found', 'recs': recs}\n\n else:\n recs_key = ndb.key('Recommendations', self.recommendation_key)\n recs = recs_key.get()\n \n memcache.add(self.recommendation_key, recs)\n cache_recs.update([(self.recommendation_key, recs)])\n\n ## get app data from cache else get from datastore\n appData = memcache.get(self.appid_key)\n if appData is None:\n appData_key = ndb.key('ApplicationData', self.appid_key)\n appData = appData_key.get()\n \n memcache.add(self.appid_key, appData) \n\n ## get lastRequested from memcache else get from datastore\n lastRequested = memcache.get(self.requestedpull_key)\n if lastRequested is None:\n lastRequested = datetime.now()\n\n memcache.add(self.requestedpull_key, lastRequested, time=3600)\n \n ## seconds since last request\n seconds_since_last_request = (datetime.now() - lastRequested).total_seconds()\n\n ## get default recs from \n default_recs = memcache.get(self.default_recs_key)\n if default_recs is None:\n default_recs_key = ndb.key('Default_Reccommendations', self.default_recs_key)\n default_recs = default_recs_key.get()\n \n memcache.add(self.default_recs_key, default_recs)\n\n ## get reasoning server from memcache else get from datastore\n reasoning_server = memcache.get(self.reasoning_server_key)\n if reasoning_server is None:\n reasoning_server_key = ndb.key('Reasoning Server', self.reasoning_server)\n reasoning_server = reasoning_server_key.get()\n\n memcache.add(self.reasoning_server_key, reasoning_server)\n\n ## if seconds_since_last_request then return back another key \"should_request\" with\n ## value reasoning_server\n if seconds_since_last_request > 5:\n return {'status': 'not found', 'recs': default_recs, 'appData': appData, 'should_request': reasoning_server}\n else:\n return {'status': 'not found', 'recs': default_recs, 'appData': appData}\n\n\nclass RegisterClickHandler(webapp2.RequestHandler):\n \"\"\"Handler for /registerClick?appId=XX&&articleId=YY&clientId=ZZ&relatedArticleId=RR api \"\"\"\n\n def get(self):\n \"\"\"get function to handle the get requests to RegisterClickHandler\n self.appId = application id\n self.articleId = article id\n self.clientId = client id\n self.relatedArticleId = related article id\n \"\"\"\n self.appId = self.request.get('appId')\n self.articleId = self.request.get('articleId')\n self.clientId = self.request.get('clientId')\n self.relatedArticleId = self.request.get('relatedArticleId')\n\n logging.info('User : ' + self.clientId + ' clicked on article : ' + self.articleId)\n\n return {'status':'success'}\n\nclass StoreHandler(webapp2.RequestHandler):\n \"\"\"Handler for /store?token=TOKEN&key=KEY&value=VALUE api\"\"\"\n\n def get(self):\n self.post()\n\n def post(self):\n self.key = self.request.get('key')\n self.value = self.request.get('value')\n self.token = self.request.get('token')\n\n if self.key.startswith(PREFIXES):\n ## replace MyData with actual entity\n values = ndb.GqlQuery(\"SELECT * FROM MyData WHERE keyString = '%s'\" % self.key) \n if values.count() > 0:\n data = values[0]\n else:\n data = MyData()\n data.valueString = self.value\n data.keyString = self.key\n data.put()\n\n return {'status':'success'}\n else:\n return {'status':'failure'}\n\n\nclass TaskHandler(webapp2.RequestHandler):\n \"\"\"Handler for /task/updateDefaultRecs api\"\"\"\n\n def get(self):\n self.counter_key = 'articleCounter' \n counterTicker = cache.get(self.counter_key)\n\n ## copy the counter\n counterTicker_copy = counterTicker\n\n ## empty the counter value in cache \n cache.pop(self.counter_key)\n\n defaultrecs = {}\n\n for key, value in counterTicker.iteritems():\n appid_articleid = key\n appid = key.split('/')[0]\n articleid = key.split('/')[1]\n count = value\n\n if appid not in defaultrecs.keys():\n defaultrecs[appid] = {}\n else:\n if articleid not in defaultrecs[appid].keys():\n defaultrecs[appid][articleid] = 0\n else:\n defaultrecs[appid][articleid] += count\n\n for key, value in defaultrecs.iteritems():\n app_key = 'defaultrecs:' + key\n app_articles = value\n sorted_app_articles = sorted(app_articles.items(), key = operator.itemgetter(1), reverse = True)[:TOP_N]\n data = Default_Reccommendations(myKey = app_key, myTopArticles = sorted_app_articles)\n data.put()\n\n\napp = webapp2.WSGIApplication([\n webapp2.Route('//articleinject.js', JavascriptHandler),\n ('/getRecommendations', RecommendationsHandler),\n ('/registerClick', RegisterClickHandler),\n ('/store', StoreHandler),\n ('/task/updateDefaultRecs', TaskHandler),\n ], debug=True)\n","sub_path":"Google App Engine/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"516976811","text":"from masterdata.models import *\nfrom survey.models import *\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect, JsonResponse\nfrom survey.views.survey_common_methods import validate\nfrom django.views.generic import View\nfrom uuid import uuid4\nfrom django.db.models import get_model\nfrom survey_web_service.models import AppAnswerData\n# Import prerequisites\n\n# Redirect deo to dashboard\ndashboard = lambda x: render(x, 'survey/deo-dashboard.html')\n\n\nclass SurveyBase(View):\n\n # Base class for dataentry related views\n\n # SurveyBase\n def memory(self):\n\n # Remembers information to be used in other methods\n # Sets attributes of self for reusing\n\n self.survey = Survey.objects.get(id=self.kwargs['sid'])\n self.date = Date.objects.get_or_none(id=self.kwargs['date'])\n location_class = self.survey.location_level()\n self.level = self.survey.del_nicely()\n self.level_class = get_model('masterdata', self.level)\n self.info = dict(self.request.GET or self.request.POST)\n self.profile = self.request.user.userprofile_set.get()\n if 'pk' in self.kwargs.keys():\n self.location = location_class.objects.get(pk=self.kwargs['pk'])\n self.details = SurveyStatus.view_status(self.survey, self.location, self.date)\n else:\n self.details = SurveyDateStatus.view_status(self.survey, self.date)\n if self.request.method == 'POST':\n self.info.pop('csrfmiddlewaretoken')\n\n # SurveyBase\n def dispatch(self, request, *args, **kwargs):\n # Dispatch calls memory\n # And check auth\n self.memory()\n if self.is_unauthorised():\n return render(self.request, 'manage/login.html', {\n 'msg': \"You don't have permission to view this page.\"\n })\n return super(SurveyBase, self).dispatch(request, *args, **kwargs)\n\n\nclass DeoAuth(object):\n\n # DeoAuth\n def is_unauthorised(self):\n # Authenticate deos\n return self.location not in UserSurveyMap.get_locations(\n self.request.user.userprofile_set.get(),\n self.survey\n )\n\n\nclass TakeSurvey(DeoAuth, SurveyBase):\n\n # Deo take survey for a location\n\n def get(self, *args, **kwargs):\n # Handle get data\n if self.request.user.userprofile_set.get().designation.code == 2:\n # Redirect dcc to view progress\n return HttpResponseRedirect(\n '/survey/dcc/view-progress/%s/%s/%s/%s/' % (\n level, sid, pk, datalevel)\n )\n\n ans = Answer.objects.filter(active=2)\n table = ans.collect_participated_rows(\n self.location,\n self.survey,\n self.date\n )\n\n # Sample format of table\n # {\n # : {\n # u'1723926038': {\n\t# \t : ,\n\t# \t : ,\n\t# \t : ,\n # }\n # }\n \n # }\n\n # Render to template\n # With dict in 3rd arg as context data\n\n return render(self.request, 'survey/take-survey.html', {\n 'survey': self.survey,\n 'participants': self.get_partys(),\n 'location': self.location,\n 'table': table,\n 'date': self.date,\n 'range': [str(uuid4().int)[:10] for i in xrange(0, 10)],\n 'request': self.request,\n 'status': int(self.details['status']),\n 'stop': self.details['obj'].stop(),\n })\n\n # TakeSurvey\n def get_partys(self):\n # Get participants of the location\n if self.level.lower() == 'plot':\n return Plot.objects.filter(house_hold__village=self.location)\n elif self.level.lower() == 'hamlet':\n return Hamlet.objects.filter(village=self.location)\n elif self.level.lower() == 'household':\n return HouseHold.objects.filter(village=self.location)\n return UserSurveyMap.get_partys(\n self.request.user.userprofile_set.get(),\n self.survey,\n )\n \n\n # TakeSurvey\n def post(self, *args, **kwargs):\n # DRY\n return JsonResponse(self._post())\n\n # TakeSurvey\n def _post(self):\n\n # Handle the post request\n # If data is not valid, return errors\n # else save and return success\n\n info = {\n i.split('-')[0]: ','.join(self.info[i])\n for i in self.info.keys()\n }\n creation_key = info.pop('row')\n try:\n party = self.level_class.objects.get(id=info.pop('party'))\n except:\n party = None\n\n lat = info.pop('lat', None)\n lng = info.pop('lng', None)\n old_reps = [\n getattr(i.get(self.survey.questions().get_or_none(text='Date')), 'text', None)\n for i in Answer.objects.exclude(creation_key=creation_key).collect_rows(party, self.survey, self.date).values()\n ] if info.get('date') else []\n qid = str(getattr(self.survey.questions().get_or_none(text='Date'), 'id', ''))\n\n\n if (party and\n self.survey.inline == '0' and\n Answer.objects.collect_rows(party, self.survey, self.date)\n ) or info.get(qid) in old_reps:\n party = 'Duplicate'\n\n responce = {\n Question.objects.get(id=i): info[i]\n for i in info.keys()\n if info[i] != '[]'\n }\n\n errors = {q.id: validate(q, a)\n for (q, a) in responce.items()}\n\n errors.update({'0': '' if party else\n 'This field should not be left blank'})\n\n if party == 'Duplicate':\n errors.update({'0': 'This %s already submitted response' %\n (self.survey.del_nicely())})\n\n if True in [bool(error) for (qid, error) in errors.items()]:\n return {'errors': errors, 'success': False}\n\n answers = []\n aad = AppAnswerData.objects.create(interface=0, latitude=lat, longitude=lng,)\n for q, a in responce.items():\n answers.append(Answer.objects.force_create(\n creation_key=creation_key,\n user=self.request.user,\n question=q,\n text=a.strip(),\n content_object=party,\n data_level=self.date,\n app_answer_data=aad.id,\n ))\n\n return {'errors': errors, 'success': True}\n\n\nclass UpdateStatus(DeoAuth, SurveyBase):\n\n # Deo can update the status of survey\n\n def get(self, *args, **kwargs):\n # Virtual urls\n task = self.kwargs['task']\n if task == 'summary':\n return self.summary()\n if task == 'confirm':\n return self.submit()\n\n def summary(self):\n # View summary\n return render(self.request,\n 'survey/local-survey-summary.html',\n {'details':self.details, 'del':self.details['obj'].survey.del_nicely()})\n\n def submit(self):\n # Submit for approval\n status = self.details['obj']\n status.set_status(1)\n return HttpResponseRedirect('/close/')\n\n\nclass DeleteResponse(DeoAuth, SurveyBase):\n\n # Deactivate a responce\n\n @staticmethod\n def get(request, *args, **kwargs):\n # Delete a response\n for i in Answer.objects.filter(creation_key=request.GET.get('row')):\n i.active = {'delete': 0, 'undelete': 2}[request.GET.get('task')]\n i.save()\n return JsonResponse({'success': True})\n","sub_path":"survey/views/deo.py","file_name":"deo.py","file_ext":"py","file_size_in_byte":7924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"564767770","text":"#Notations: there are three websites helped me a lots to this project\n########## https://www.pygame.org/docs/ #helped me understand the what is pygame\n########## https://pythonprogramming.net/ #helped me to build buttons, objects, text, and introduction panel\n########## http://programarcadegames.com/python_examples/show_file.php?file=bounce_ball_with_paddle.py #helped me build the player movement\n########## https://www.pygame.org/docs/ref/music.html #helped me add sound and other effects\n\n\nimport pygame\nimport random\n#import time\n\nWIDTH = 400\nHEIGHT = 800\nFPS = 60\n\nWHITE = (255, 255, 255)\nBLACK = (0, 0, 0)\n\nRED = (200,0,0)\nGREEN = (0,200,0)\nBLUE = (0, 0, 200)\nCYAN = (163, 255, 224)\nYELLOW = (255, 248, 48)\n\nbright_red = (255,0,0)\nbright_green = (0,255,0)\n\n# initialize pygame\npygame.init()\ngameDisplay = pygame.display.set_mode((WIDTH, HEIGHT))\npygame.display.set_caption(\"Dodge Game\")\nwin_sound = pygame.mixer.Sound(\"/Users/Hank/Desktop/Python_Week/Z_FinalFile/winwin2.wav\")\nsmash_sound = pygame.mixer.Sound(\"/Users/Hank/Desktop/Python_Week/Z_FinalFile/smash.wav\")\n\n#win_sound = pygame.mixer.Sound(\"C:\\winwin2.wav\")\n#smash_sound = pygame.mixer.Sound(\"C:\\smash.wav\")\nclock = pygame.time.Clock()\n#t0 = time.time()\n\ndef game_intro():\n intro = True\n\n while intro:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quitgame()\n\n gameDisplay.fill(WHITE)\n largeText = pygame.font.SysFont(\"Impact\", 45)\n TextSurf, TextRect = text_objects(\"Dodoge Game\", largeText)\n \n TextRect.center = ((WIDTH/2), (HEIGHT/2 - 150))\n gameDisplay.blit(TextSurf, TextRect)\n \n button(\"Start!\", 150, 350,100, 50, GREEN, bright_green,game_loop)\n button(\"Quit!\", 150,550,100,50, RED, bright_red,quitgame)\n #button(\"Help\", 150,450,100,50, GREEN, bright_green,game_help)\n\t\t\n pygame.display.update()\n clock.tick(15)\n \ndef quitgame():\n pygame.quit()\n quit()\n\n \ndef button(msg,x,y,w,h,c1,c2,action=None):\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n \n if x+w > mouse[0] > x and y+h > mouse[1] > y:\n pygame.draw.rect(gameDisplay, c2,(x,y,w,h))\n if click[0] == 1 and action != None:\n action()\n\n else:\n pygame.draw.rect(gameDisplay, c1,(x,y,w,h))\n\n smallText = pygame.font.SysFont(\"Impact\",20)\n TextSurf, TextRect = text_objects(msg, smallText)\n TextRect.center = ((x+(w/2)), (y+(h/2)))\n gameDisplay.blit(TextSurf, TextRect)\n\n\n \ndef convertMill(millis):\n millSeconds=(millis)%60\n millSeconds = int(millSeconds)\n seconds=(millis)%60\n seconds = int(seconds)\n minutes=(millis/(1000*60))%60\n minutes = int(minutes)\n\n return (\"%d:%d:%d\" % (minutes, seconds, millSeconds))\n\ndef text_objects(text, font):\n TextSurface = font.render(text, True, BLACK)\n return TextSurface, TextSurface.get_rect()\n\ndef got_hit():\n\n pygame.mixer.Sound.play(smash_sound)\n pygame.mixer.music.stop()\n \n hitted = True\n #print(time)\n \n while hitted:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quitgame()\n\n #gameDisplay.fill(WHITE)\n largeText = pygame.font.SysFont(\"Impact\", 45)\n \n TextSurf, TextRect = text_objects(\"Game Over\", largeText)\n\n TextRect.center = ((WIDTH/2), (HEIGHT/2 - 150))\n \n gameDisplay.blit(TextSurf, TextRect)\n \n button(\"Again\", 150,350,100,50, GREEN, bright_green,game_loop)\n button(\"Quit!\", 150,450,100,50, RED, bright_red,quitgame)\n button(\"Help\", 150,550,100,50, GREEN, bright_green,game_help)\n \n \n\t\t\n pygame.display.update()\n clock.tick(15)\n\ndef game_won():\n# global time\n# t1 = time.time()\n# dt = t1-t0\n# print (t1)\n# print (t0)\n# print (dt)\n# time = pygame.time.get_ticks()\n pygame.mixer.Sound.play(win_sound)\n pygame.mixer.music.stop()\n \n reached = True\n while reached:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quitgame()\n\n #gameDisplay.fill(WHITE)\n largeText = pygame.font.SysFont(\"Impact\", 45)\n \n \n \n TextSurf, TextRect = text_objects(\"YOU WON!\", largeText)\n #TextSurf2, TextRect2 = text_objects(\"Time Cost: \"+convertMill(time), largeText)\n \n TextRect.center = ((WIDTH/2), (HEIGHT/2 - 150))\n #TextRect2.center = ((WIDTH/2), (HEIGHT/2 - 100))\n \n gameDisplay.blit(TextSurf, TextRect)\n #gameDisplay.blit(TextSurf2, TextRect2)\n \n button(\"Again\", 150,350,100,50, GREEN, bright_green,game_loop)\n button(\"Quit!\", 150,450,100,50, RED, bright_red,quitgame)\n\t\t\n pygame.display.update()\n clock.tick(15) \n\ndef game_help():\n \n helpping = True\n while helpping:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n quitgame()\n\n gameDisplay.fill(WHITE)\n smallText = pygame.font.SysFont(\"Impact\", 20)\n TextSurf, TextRect = text_objects(\"Reach all the way to the top to\", smallText)\n TextSurf2, TextRect2 = text_objects(\"win the game without hitting by objects\", smallText)\n TextRect.center = ((WIDTH/2), (HEIGHT/2 - 200))\n TextRect2.center = ((WIDTH/2), (HEIGHT/2 - 150))\n gameDisplay.blit(TextSurf, TextRect)\n gameDisplay.blit(TextSurf2, TextRect2)\n \n button(\"Start!\", 150,350,100,50, GREEN, bright_green,game_loop)\n button(\"Quit!\", 150,450,100,50, RED, bright_red,quitgame)\n\t\t\n pygame.display.update()\n clock.tick(15) \n \n\ndef game_loop():\n #pygame.init()\n class Player(pygame.sprite.Sprite):\n #sprite for the player\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.Surface((50,50))\n self.image.fill(CYAN)\n self.rect = self.image.get_rect()\n self.rect.centerx = WIDTH / 2\n self.rect.bottom = HEIGHT - 10\n self.speedx = 0\n self.speedy = 0\n \n def update(self):\n self.speedx = 0\n self.speedy = 0\n keystate = pygame.key.get_pressed()\n if keystate[pygame.K_LEFT]:\n self.speedx = -5\n if keystate[pygame.K_RIGHT]:\n self.speedx = 5\n if keystate[pygame.K_UP]:\n self.speedy = -5\n if keystate[pygame.K_DOWN]:\n self.speedy = 5\n \n self.rect.x += self.speedx\n self.rect.y += self.speedy\n \n if self.rect.right > WIDTH:\n self.rect.right = WIDTH\n if self.rect.left < 0:\n self.rect.left = 0\n \n if self.rect.top > HEIGHT - 70:\n self.rect.top = HEIGHT - 70\n if self.rect.top < 0:\n game_won()\n \n class Mob(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = pygame.Surface((30,40))\n self.image.fill(YELLOW)\n self.rect = self.image.get_rect()\n self.rect.x = random.randrange(WIDTH - self.rect.width)\n self.rect.y = random.randrange(-100,-40)\n self.speedy = random.randrange(1,8)\n self.speedx = random.randrange(-3,3)\n \n def update(self):\n self.rect.y += self.speedy\n self.rect.x += self.speedx\n if self.rect.top > HEIGHT + 10:\n self.rect.x = random.randrange(WIDTH - self.rect.width)\n self.rect.y = random.randrange(-100,-40)\n self.speedy = random.randrange(2,10)\n\n \n all_sprites = pygame.sprite.Group()\n mobs = pygame.sprite.Group()\n player = Player()\n all_sprites.add(player)\n for i in range(18):\n m = Mob()\n all_sprites.add(m)\n mobs.add(m)\n \n running = True \n while running:\n clock.tick(FPS)\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n quitgame()\n \n all_sprites.update()\n \n hits = pygame.sprite.spritecollide(player,mobs,False)\n \n if hits:\n #print(int(str(time)[:1]))\n #print(\"seconds\")\n #pygame.time.Clock.get_time()\n got_hit()\n running = False\n \n \n \n #print(time)\n gameDisplay.fill(WHITE)\n all_sprites.draw(gameDisplay)\n pygame.display.flip()\n #pygame.display.update()\n #clock.tick(60)\n\ngame_intro()\ngame_loop()\npygame.quit()\nquit()\n","sub_path":"Hank_394_Python/Every_Week_Code/Final_week/SourceCode/DodgeGame_V2.py","file_name":"DodgeGame_V2.py","file_ext":"py","file_size_in_byte":8838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"128218963","text":"from datetime import timedelta\n\nfrom itsdangerous import TimestampSigner\nfrom pytest import raises\n\nfrom keg_bouncer.tokens import TokenManager\n\n\nclass TestTokenManager(object):\n def test_isomorphism(self):\n expected = b'some data'\n\n for key in [b'secret key 12345', 'other key 123456',\n '\\u0391\\u0392\\u0393\\u0394\\u0395\\u0396\\u0397\\u0398']:\n tm = TokenManager(key)\n token = tm.generate_token(expected)\n is_expired, data = tm.verify_token(\n token,\n expiration_timedelta=timedelta(seconds=10)\n )\n assert not is_expired\n assert data == expected\n\n def test_expired_token(self):\n timestamp = 0\n\n class MockTimestampSigner(TimestampSigner):\n def get_timestamp(self):\n return timestamp\n\n timestamp = 0 # pretend we're at the beginning of time\n tm = TokenManager(b'secret key 12345', timestamp_signer=MockTimestampSigner)\n token = tm.generate_token(b'some data')\n\n timestamp = 10000 # pretend much time has passed\n is_expired, data = tm.verify_token(\n token,\n expiration_timedelta=timedelta(seconds=0)\n )\n\n assert is_expired\n assert data is None\n\n def test_invalid_token(self):\n is_expired, data = TokenManager(b'secret key 12345').verify_token(\n 'blah',\n expiration_timedelta=timedelta(seconds=1)\n )\n assert not is_expired\n assert data is None\n\n def test_key_too_short(self):\n with raises(ValueError) as exc_info:\n TokenManager(b'secret key')\n assert str(exc_info.value) == 'Key must be at least 16 bytes long'\n","sub_path":"keg_bouncer_test_app/tests/test_tokens.py","file_name":"test_tokens.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"56180151","text":"class BankAccount():\n def __init__(self, owner, balance=0.0):\n self.owner = owner\n self.balance = balance\n\n def deposit(self, deposit_amount):\n self.balance += deposit_amount\n return deposit_amount\n\n def withdraw(self, withdraw_amount):\n self.balance -= withdraw_amount\n return withdraw_amount\n\nramesh = BankAccount(\"Ramesh\", 2000.0)\npawan = BankAccount(\"Pawan\", 5000.0)\n\nprint(ramesh.balance)\nprint(pawan.balance)\n\nramesh.deposit(590)\nprint(ramesh.balance)\n\npawan.withdraw(350)\nprint(pawan.balance)\n\n\n","sub_path":"bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"48028972","text":"from schism_py_pre_post.Plot.plot_elev import plot_elev, get_hindcast_elev, get_obs_elev\nfrom schism_py_pre_post.Grid.Bpfile import Bpfile\nimport pandas as pd\nimport json\nimport numpy as np\nimport os\nfrom mpl_toolkits.basemap import Basemap # mamba install basemap\nimport matplotlib.pyplot as plt\n\n\ndef pacific_stations(station_bp_file=None):\n # --------------define stations----------------------\n # stations, ICOGS v2 and v3, coastal act\n if station_bp_file is None:\n station_bp_file = '/sciclone/schism10/feiye/Coastal_Act/RUN17a/station.in'\n\n noaa_stations_all = Bpfile(station_bp_file, cols=5).st_id\n\n stations_groups = {\n 'Hawaii': noaa_stations_all[76:88],\n 'West_Coast_1': noaa_stations_all[88:108],\n 'West_Coast_2': noaa_stations_all[108:128],\n 'West_Coast_3': noaa_stations_all[128:147],\n }\n default_datums = {\n 'Hawaii': 'MSL',\n 'West_Coast_1': 'NAVD',\n 'West_Coast_2': 'NAVD',\n 'West_Coast_3': 'NAVD',\n }\n return [stations_groups, default_datums]\n\ndef ecgc_stations(station_bp_file=None):\n # --------------define stations----------------------\n # stations, ICOGS v2 and v3, coastal act\n if station_bp_file is None:\n station_bp_file = '/sciclone/schism10/feiye/Coastal_Act/Station_in/15a_station.in'\n\n noaa_stations_all = Bpfile(station_bp_file, cols=5).st_id\n\n stations_groups = {\n 'Florida': noaa_stations_all[:10],\n 'Atlantic': noaa_stations_all[10:29],\n 'GoME': noaa_stations_all[29:39], 'GoMX_west': noaa_stations_all[41:60],\n 'GoMX_east': noaa_stations_all[60:80], 'Atlantic_inland1': noaa_stations_all[80:100],\n 'Atlantic_inland2': noaa_stations_all[100:120], 'GoMX_inland': noaa_stations_all[120:150],\n 'Puerto_Rico': noaa_stations_all[150:164] + noaa_stations_all[39:41] # last 2 are bermuda\n }\n default_datums = {\n 'Florida': 'NAVD',\n 'Atlantic': 'NAVD',\n 'GoME': 'NAVD', 'GoMX_west': 'NAVD',\n 'GoMX_east': 'NAVD', 'Atlantic_inland1': 'NAVD',\n 'Atlantic_inland2': 'NAVD', 'GoMX_inland': 'NAVD',\n 'Puerto_Rico': 'MSL'\n }\n return [stations_groups, default_datums]\n\n\ndef subset_stations_in_box(box, station_bp_file, group_name=\"Landfall_region\", default_datum='NAVD', max_subplots = 20):\n # select a subset of stations within the box and redefine noaa_stations_groups\n stations_all = Bpfile(station_bp_file, cols=5).st_id\n stations_lonlat = Bpfile(station_bp_file, cols=5).nodes[:, :2]\n idx = (\n (box['W']-1 < stations_lonlat[:, 0]) *\n (box['E']+1 > stations_lonlat[:, 0]) *\n (box['S']-1 < stations_lonlat[:, 1]) *\n (box['N']+1 > stations_lonlat[:, 1])\n )\n\n stations_inbox = np.array(stations_all)[idx]\n stations_groups = {}\n default_datums = {}\n for i_group, i in enumerate(range(0, len(stations_inbox), max_subplots)):\n these_stations = stations_inbox[i:i + max_subplots]\n this_group_name = f\"{group_name}_{i_group}\"\n stations_groups[this_group_name] = these_stations\n default_datums[this_group_name] = default_datum\n print(f'{len(these_stations)} stations in {this_group_name}')\n\n return [stations_groups, default_datums]\n\n\ndef stats_scatter(stats=None, stats_file=None, var_str=None,\n region=\"Full_domain\", box={\"W\": -100, \"E\": -60, \"S\": 8, \"N\": 48},\n plot_symbol_dict=None, filename=None):\n if stats is None:\n stats = pd.read_csv(stats_file)\n var_str0 = var_str.split('_')[0]\n\n # plot stats as scatter points\n ilabel = plot_symbol_dict[region][\"ilabel\"]\n grid_spacing = plot_symbol_dict[region][\"grid_spacing\"]\n symbol_size = plot_symbol_dict[region][\"symbol_size\"]\n var_colorbar_str = plot_symbol_dict[var_str][\"var_colorbar_str\"]\n cmap = plot_symbol_dict[var_str][\"cmap\"]\n vmin = plot_symbol_dict[var_str][\"vmin\"]\n vmax = plot_symbol_dict[var_str][\"vmax\"]\n\n plt.figure(figsize=(12, 10), dpi=300)\n m = Basemap(projection=\"merc\", resolution=\"f\", # mamba install basemap-data-hires\n llcrnrlat=box['S']-1, llcrnrlon=box['W']-1,\n urcrnrlat=box['N']+1, urcrnrlon=box['E']+1)\n m.shadedrelief()\n m.drawcoastlines()\n parallels = np.arange(np.floor(box['S'])-1, np.ceil(box['N'])+1, grid_spacing)\n m.drawparallels(parallels, labels=[False, True, True, False])\n meridians = np.arange(np.ceil(box['W'])-1, np.ceil(box['E'])+1, grid_spacing)\n m.drawmeridians(meridians, labels=[False, True, True, False])\n mx, my = m(np.array(stats['station_lon']), np.array(stats['station_lat'])) # transform coordinates\n plt.scatter(mx, my, symbol_size, stats[var_str0].values, cmap=cmap, vmin=vmin, vmax=vmax)\n if ilabel == 1:\n for i, label in enumerate(stats['station_id']):\n plt.annotate(f'{label}', (mx[i], my[i]))\n clb = plt.colorbar()\n clb.ax.set_title(f'{var_colorbar_str} (m)')\n plt.savefig(f'{filename}_{var_str}.png', dpi=400)\n plt.close('all')\n\ndef write_stat(stats, fname):\n rearranged_cols = ['station_lon', 'station_lat', 'station_id', 'RMSE', 'MAE',\n 'Bias', 'CC', 'ubRMSE', 'Max_Obs', 'Max_Mod', 'station_name']\n stats = stats[rearranged_cols]\n stats.loc['mean'] = stats.iloc[:, :-1].mean()\n stats.at['mean', 'station_id'] = 'all'\n stats.at['mean', 'station_name'] = 'all'\n\n stats.to_csv(fname, encoding='utf-8', index=False, na_rep='-9999')\n\n\nif __name__ == \"__main__\":\n # ---------------------------------------------------------------------------------\n # inputs\n # ---------------------------------------------------------------------------------\n hurricanes = ['Ian']\n main_dict = '/sciclone/data10/feiye/schism_py_pre_post_hard_copy/schism_py_pre_post/Plot/stofs3d.json' # 'coastal_act_stats_period_3D_1st_round.json'\n\n region = \"Full_domain\" # \"Landfall_region\", \"Full_domain\", \"Manual\"\n var_str = 'MAE'\n nday_moving_average = 0\n\n with open(main_dict) as d:\n hurricane_dict = json.load(d)\n station_bp_file = hurricane_dict['All']['station_bp_file']\n station_subset = range(164)\n\n other_dicts_files = [] # ['coastal_act_stats_period_3D_others.json']\n other_line_styles = ['g']\n other_shifts = [0]\n other_subsets = [None]\n\n datum = '' # '' (use predefined ones in ecgc_stations), 'NAVD', 'MSL'\n outfilename_suffix = 'Mostly_NAVD' # 'Mostly_NAVD': some stations don't have NAVD datum and their elevation time series will be demeaned and shown as \"MSL\"\n\n with open('/sciclone/data10/feiye/schism_py_pre_post_hard_copy/schism_py_pre_post/Plot/coastal_act_stats_plot_symbols.json') as d:\n plot_symbol_dict = json.load(d)\n\n cache_folder = os.path.realpath(os.path.expanduser('~/schism10/Cache/'))\n # --end inputs-------------------------------------------------------------------------------\n\n for hurricane in hurricanes:\n dict_item = hurricane_dict[hurricane]\n plot_start_day_str = dict_item['plot_start_day_str']\n plot_end_day_str = dict_item['plot_end_day_str']\n model_start_day_str = dict_item['model_start_day_str']\n elev_out_file = dict_item['elev_out_file']\n cdir = dict_item['cdir']\n runid = os.path.basename(os.path.dirname(cdir))\n if region == \"Full_domain\":\n box = hurricane_dict['All']['box']\n stations_groups, default_datums = ecgc_stations(station_bp_file)\n # stations_groups, default_datums = pacific_stations(station_bp_file)\n elif region == \"Manual\":\n stations_groups = hurricane_dict[hurricane]['stations_group']\n default_datums = hurricane_dict[hurricane]['default_datums']\n else:\n box = hurricane_dict[hurricane]['box']\n stations_groups, default_datums = subset_stations_in_box(box, station_bp_file, group_name=region, default_datum=datum)\n\n # ---------------------------------------------------------------------------------\n # # Manually override the parameters read from '*.json', only for testing\n # overwrite default_datums\n if datum is not None and datum != '':\n for key in default_datums:\n default_datums[key] = datum\n\n # plot_start_day_str = '2018-08-17 00:00:00'\n # plot_end_day_str = '2018-10-01 00:00:00'\n # model_start_day_str = '2017-08-04 00:00:00'\n # # model outputs\n # elev_out_file = '/sciclone/schsm10/feiye/Coastal_Act/RUN13b/PostP/staout_1'\n # cdir = '$cdir/srv/www/htdocs/yinglong/feiye/Coastal_Act/RUN13b/'\n\n other_dicts = []; other_runs_stats = [pd.DataFrame()] * len(other_dicts_files)\n for other_dict_file in other_dicts_files:\n with open(other_dict_file) as d:\n other_dicts.append(json.load(d))\n other_runids = [os.path.basename(os.path.dirname(x[hurricane]['cdir'])) for x in other_dicts]\n # ---------------------------------------------------------------------------------\n\n final_datums = []\n stats = pd.DataFrame()\n for i_group, group_name in enumerate(stations_groups):\n filename_base = f'{hurricane}_{group_name}_{default_datums[group_name]}'\n # if group_name != 'Puerto_Rico':\n # continue\n print(f'\\n\\n\\n processing {group_name} for {hurricane}')\n # SCHISM's staout_1\n mod = get_hindcast_elev(\n model_start_day_str=model_start_day_str,\n noaa_stations=None,\n station_in_file=station_bp_file,\n elev_out_file=elev_out_file,\n station_in_subset=station_subset,\n )\n\n # get obs\n [obs, datums, st_info] = get_obs_elev(\n plot_start_day_str=plot_start_day_str,\n plot_end_day_str=plot_end_day_str,\n noaa_stations=stations_groups[group_name],\n default_datum=default_datums[group_name],\n cache_folder=cache_folder\n )\n final_datums += datums\n\n # plot time series\n stat, fig_ax = plot_elev(obs, mod, plot_start_day_str, plot_end_day_str,\n stations_groups[group_name],\n datums, st_info, 'ts_' + filename_base, iplot=False, subplots_shape=(None, None),\n nday_moving_average=nday_moving_average, label_strs=['obs', runid])\n stats = stats.append(stat)\n write_stat(stat, f'stats_{runid}_{group_name}.txt')\n\n if len(other_dicts) > 0:\n for i, [other_runid, other_dict, other_line_style, other_shift, other_subset] in enumerate(zip(other_runids, other_dicts, other_line_styles, other_shifts, other_subsets)):\n other_mod = get_hindcast_elev(\n model_start_day_str=other_dict[hurricane]['model_start_day_str'],\n noaa_stations=None,\n station_in_file=station_bp_file,\n elev_out_file=other_dict[hurricane]['elev_out_file'],\n station_in_subset=other_subset\n )\n other_stat, _ = plot_elev(obs, other_mod, plot_start_day_str, plot_end_day_str,\n stations_groups[group_name],\n datums, st_info, None, iplot=False, nday_moving_average=nday_moving_average,\n fig_ax=fig_ax, line_styles=[None, other_line_style], shift=other_shift, label_strs=['obs', other_runid])\n other_runs_stats[i] = other_runs_stats[i].append(other_stat)\n write_stat(other_stat, f'stats_{other_runid}_{group_name}.txt')\n fig_ax[0].savefig(f'compare_ts_{filename_base}.png')\n\n # ---------------------------------------------------------------------------------\n filename_base = f'{hurricane}_{region}_{outfilename_suffix}'\n stats_scatter(stats=stats, var_str=var_str, region=region, plot_symbol_dict=plot_symbol_dict, filename=filename_base)\n\n write_stat(stats, f'stats_{runid}_{filename_base}.txt')\n for other_runid, other_run_stats in zip(other_runids, other_runs_stats):\n write_stat(other_run_stats, f'stats_{other_runid}_{filename_base}.txt')\n \n overall_stats_datum_info_texts = [\n f\"Stations with NAVD datum: {sum(np.array(final_datums)=='NAVD')}\",\n f\"Stations with MSL datum: {sum(np.array(final_datums)=='MSL')}\",\n f\"Stations without data: {sum(np.array(final_datums)==None)}\",\n ]\n\n # fname = 'stats_datum_info.txt'\n # with open(fname, 'w') as f:\n # os.system(f\"head -n 1 stats_{runid}_{filename_base}.txt > {fname}\")\n # os.system(f\"tail -n 1 stats_{runid}_{filename_base}.txt > {fname}\")\n # for group in groups:\n # f.write('\\n'.join(overall_stats_datum_info_texts))\n \n # ---------------------------------------------------------------------------------\n\n # upload to ccrm drive:\n print(f\"scp *stats*txt *png {cdir}/\")\n os.system(f\"scp *stats*txt *png {cdir}/\")\n os.system(f\"rm *stats*txt *png\")\n \n\n","sub_path":"src/Utility/Pre-Processing/STOFS-3D-Atl-shadow-VIMS/Post_processing/Plots/Elevation/plot_coastal_act.py","file_name":"plot_coastal_act.py","file_ext":"py","file_size_in_byte":13347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"266908880","text":"#!/usr/bin/env python3\n\n\nclass DNSMapConfig(object):\n\n def __init__(self, **kwargs):\n self._content = kwargs\n\n @classmethod\n def load_from_dict(cls, _dict):\n return cls(**_dict)\n\n @property\n def nameservers(self):\n \"\"\" \n 223.5.5.5\n 223.6.6.6\n 119.29.29.29\n 182.254.116.116\n \"\"\"\n return self._content.get(\n \"nameservers\", [\n \"223.5.5.5\",\n \"223.6.6.6\",\n \"119.29.29.29\",\n \"182.254.116.116\",\n ])\n\n @property\n def timeout(self):\n return self._content.get(\n \"timeout\", 10,\n )","sub_path":"vdnsmap/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"117651030","text":"import six\n\n\ndef esc_code(codes=None):\n if codes is None:\n # reset escape code\n return \"\\x1b[0m\"\n if not isinstance(codes, (list, tuple)):\n codes = [codes]\n return '\\x1b[0;' + ';'.join(map(six.text_type, codes)) + 'm'\n\n\ndef get_luminance(rgb):\n rgb_map = []\n for val in rgb:\n val = val / 256\n if val <= 0.03928:\n rgb_map.append(val / 12.92)\n else:\n rgb_map.append(pow((val + 0.055) / 1.055, 2.4))\n\n return (0.2126 * rgb_map[0]) + (0.7152 * rgb_map[1]) + (0.0722 * rgb_map[2])\n\n\ndef repr_rgb(rgb):\n r, g, b = rgb\n codes = (48, 2, r, g, b)\n reset = \"\\x1b[0m\"\n hex_color = \"#%s\" % (\"\".join([\"%02x\" % c for c in rgb]))\n luminance = get_luminance(rgb)\n if luminance > 0.5:\n codes += (38, 2, 0, 0, 0)\n else:\n codes += (38, 2, 255, 255, 255)\n\n return \"%(codes)s%(hex)s%(reset)s\" % {\n 'codes': esc_code(codes),\n 'hex': hex_color,\n 'reset': reset,\n }\n","sub_path":"tests/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"557956149","text":"#!/usr/bin/env python3\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pprint\nimport fiolib.supporting as supporting\nfrom datetime import datetime\nimport fiolib.shared_chart as shared\n\n\ndef chart_2dbarchart_jsonlogdata(settings, dataset):\n \"\"\"This function is responsible for drawing iops/latency bars for a\n particular iodepth.\"\"\"\n dataset_types = shared.get_dataset_types(dataset)\n data = shared.get_record_set(settings, dataset, dataset_types,\n settings['rw'], settings['numjobs'])\n\n fig, (ax1, ax2) = plt.subplots(\n nrows=2, gridspec_kw={'height_ratios': [7, 1]})\n ax3 = ax1.twinx()\n fig.set_size_inches(10, 6)\n\n #\n # Puts in the credit source (often a name or url)\n if settings['source']:\n plt.text(1, -0.08, str(settings['source']), ha='right', va='top',\n transform=ax1.transAxes, fontsize=9)\n\n ax2.axis('off')\n #\n # Creating the bars and chart\n x_pos = np.arange(0, len(data['x_axis']) * 2, 2)\n width = 0.9\n\n n = np.array(data['y2_axis']['data'], dtype=float)\n\n rects1 = ax1.bar(x_pos, data['y1_axis']['data'], width,\n color='#a8ed63')\n rects2 = ax3.bar(x_pos + width, n, width,\n color='#34bafa')\n\n #\n # Configure axis labels and ticks\n ax1.set_ylabel(data['y1_axis']['format'])\n ax1.set_xlabel(data['x_axis_format'])\n ax3.set_ylabel(data['y2_axis']['format'])\n\n ax1.set_xticks(x_pos + width / 2)\n ax1.set_xticklabels(data['x_axis'])\n #\n # Set title\n settings['type'] = \"\"\n settings['iodepth'] = dataset_types['iodepth']\n if settings['rw'] == 'randrw':\n supporting.create_title_and_sub(settings, plt, skip_keys=['iodepth'])\n else:\n supporting.create_title_and_sub(\n settings, plt, skip_keys=['iodepth', 'filter'])\n #\n # Labeling the top of the bars with their value\n shared.autolabel(rects1, ax1)\n shared.autolabel(rects2, ax3)\n #\n #\n shared.create_stddev_table(data, ax2)\n #\n # Create legend\n ax2.legend((rects1[0], rects2[0]),\n (data['y1_axis']['format'],\n data['y2_axis']['format']), loc='center left', frameon=False)\n #\n # Save graph to file\n #\n now = datetime.now().strftime('%Y-%m-%d_%H%M%S')\n title = settings['title'].replace(\" \", '-')\n title = title.replace(\"/\", '-')\n plt.tight_layout(rect=[0, 0, 1, 1])\n fig.savefig(f\"{title}_{now}.png\", dpi=settings['dpi'])\n","sub_path":"fio_plot/fiolib/bar2d.py","file_name":"bar2d.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"122317228","text":"import requests\nimport json\n\nresponse = requests.get('https://statsapi.web.nhl.com/api/v1/teams')\ndata = response.json()\n\nwith open('nhl.json', 'w') as nhl_file:\n\tnhl_file.write(json.dumps(data))\nprint(json.dumps(data['teams'], indent=4))\n\n\n# How many teams in the NHL\nnum_teams = len(data['teams'])\nprint(f'Number of NHL teams: {num_teams}')\n\n\n# How many teams in eastern conference\nteam_data = data['teams']\neastern_total = 0\n\nfor teams in team_data:\n\tif 'Eastern' in teams['conference']['name']:\n\t\teastern_total += 1\nprint(f'Number of teams in eastern conference: {eastern_total}')\n\n\n\n# Find the oldest NHL team\nteam_data = data['teams']\nfirst_year_play = []\nfor team in team_data:\n\tfirst_year_play.append({'first_year': int(team['firstYearOfPlay']), 'name': team['name']}) # List contains dictionaries with team name/year\nprint(type(first_year_play))\n\nmin_year = first_year_play[0]['first_year'] # arbitrarily store first index - to be replaced by for-loop result\nmin_year_name = first_year_play[0]['name']\n\nfor team in first_year_play:\n\tif team['first_year'] < min_year:\n\t\tmin_year = team['first_year'] # replace value\n\t\tmin_year_name = team['name'] # replace value\nprint(min_year, min_year_name)\n\n# # Alternative approach using sort/lambdas\n# sorted_list = sorted(first_year_play, key=lambda x: x['first_year'])\n# print(sorted_list[0])\n\n\n\n# When did Boston Bruins start playing","sub_path":"unit-6/apis.py","file_name":"apis.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"416658196","text":"from pandas import DataFrame\nfrom typing import Dict, Any\nfrom utils.utility import Dev1, Dev2, Dev3\nfrom factor.TradeHoldFactor.base import BaseTradeHoldFactor\n\nclass UnilateralTradeHoldFactor2(BaseTradeHoldFactor):\n \"\"\"\n 单边成交持仓因子2: sum(持空头量,N)/品种持仓量\n\n Attributes\n __________\n N: int, default 20\n 选择的前N位成员的数据\n\n window: int, default 1\n 平滑窗口\n\n R: int, default 20\n 异常度函数回溯期\n\n func: str, default None\n 异常度函数\n \"\"\"\n\n def __init__(self, N: int = 20, window: int = 1, R: int = 20, func: str = None) -> None:\n \"\"\"\n Constructor\n\n Parameters\n ----------\n N: int, default 20\n 选择的前N位成员的数据\n\n window: int, default 1\n 平滑窗口\n\n R: int, default 20\n 异常度函数回溯期\n\n func: str, default None\n 异常度函数\n \"\"\"\n super().__init__(N=N, window=window, R=R, func=func)\n\n def compute_factor(self) -> DataFrame:\n \"\"\"\n 计算因子值\n\n Returns\n -------\n factor_value: DataFrame\n 因子值\n \"\"\"\n # 提取参数\n params: Dict[str, Any] = self.get_params()\n N: int = params['N']\n window: int = params['window']\n R: int = params['R']\n func: str = params['func']\n\n # 提取数据\n short_df: DataFrame = self.get_trade_hold_data_by_rank(rank_by='short', group_by_symbol=False)\n short_df = short_df.sort_values(by=['datetime', 'underlying_symbol', 'volume'], ascending=[True, True, False]). \\\n set_index(['datetime', 'underlying_symbol']).groupby(['datetime', 'underlying_symbol'], as_index=True)[\n 'volume'].head(N)\n short_df = short_df.groupby(['datetime', 'underlying_symbol']).sum().unstack(level=-1)\n\n open_interest_df: DataFrame = \\\n self.get_groupby_field(field='open_interest', func='sum').set_index(['datetime', 'underlying_symbol'])[\n 'open_interest'].unstack(level=-1)\n\n common_index = short_df.index.intersection(open_interest_df.index)\n common_columns = short_df.columns.intersection(open_interest_df.columns)\n\n short_df = short_df.loc[common_index, common_columns]\n open_interest_df = open_interest_df.loc[common_index, common_columns]\n\n # 计算原始因子值\n factor_value: DataFrame = short_df / open_interest_df\n factor_value = factor_value.rolling(window=window, min_periods=0).mean()\n\n # 叠加函数\n if func == 'Dev1':\n factor_value = Dev1(factor_value, R)\n elif func == 'Dev2':\n factor_value = Dev2(factor_value, R)\n elif func == 'Dev3':\n factor_value = Dev3(factor_value, R)\n elif not func:\n pass\n else:\n raise ValueError(\"func must be Dev1, Dev2, Dev3 or None!\")\n\n self.factor_value = factor_value\n return factor_value","sub_path":"factor/TradeHoldFactor/UnilateralTradeHoldFactor2.py","file_name":"UnilateralTradeHoldFactor2.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"130795142","text":"import torch\nimport torch.utils.data\nfrom torch import nn\nfrom torch.nn import functional as F\nimport numpy as np\n\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.metrics import roc_auc_score\n\nfrom utils.plot_utils import plot_distribution\nfrom utils.plot_utils import plot_save_loss\nfrom utils.plot_utils import plot_save_acc\nfrom utils.plot_utils import plot_save_acc_nzs_mmcs\nfrom utils.plot_utils import plot_save_roc\nfrom utils.data_preprocess import load_data_both_dataset\n\nfrom models import nnz, active, step, eval_step, eval_combined, Net3, Net4, MLP3, MLP4, pre_train\n\n# ngsim data\ntrainUS80 = True\n(x_train, y_train, x_validate, y_validate) = load_data_both_dataset(trainUS80)\ndim = x_train.shape[1]\nx_train = x_train/np.sqrt(dim)\nx_validate = x_validate/np.sqrt(dim)\n# x_ood = x_ood/np.sqrt(dim)\n# x_combined = np.concatenate((x_validate, x_ood))\n\n# label_ood = np.zeros(x_combined.shape[0])\n# label_ood[x_validate.shape[0]:] = 1\n\nds_train = torch.utils.data.TensorDataset(torch.from_numpy(x_train).float(),\n F.one_hot(torch.from_numpy(y_train)).float())\n\nds_test = torch.utils.data.TensorDataset(torch.from_numpy(x_validate).float(),\n F.one_hot(torch.from_numpy(y_validate)).float())\n\n# ds_combined = torch.utils.data.TensorDataset(torch.from_numpy(x_combined).float())\n\n# network hyper param\ninputs = 4\nbatchSize = 64\nepochs = 200\nhiddenUnits = 64\n# learningRate = 0.001 # for mlp3\nlearningRate = 0.001 # for mlp3\n# learningRate = 0.0001\nl2Penalty = 1.0e-3\nnum_classes = 2\n\nalpha = 0.\nseeds = [0, 100057, 300089, 500069, 700079]\n# runs = len(seeds)\nruns = 5\nr2 = 1.\nmaxAlpha = 1.\n\ntrained = False\nbias = False\npretrained = False\nif trainUS80:\n outputDir='/home/hh/data/train_us80_validate_us101/'\nelse:\n outputDir='/home/hh/data/train_us101_validate_us80/'\n\n\naccs = []\nlosses = []\naccs_validate = []\nlosses_validate = []\nfor run in range(runs):\n np.random.seed(seeds[run])\n torch.manual_seed(seeds[run])\n dl_train = torch.utils.data.DataLoader(ds_train, batch_size=batchSize, shuffle=True, drop_last=False)\n dl_test = torch.utils.data.DataLoader(ds_test, batch_size=x_validate.shape[0], shuffle=False)\n model = Net4(inputs, hiddenUnits)\n # model = MLP4(inputs, hiddenUnits)\n optimizer = torch.optim.Adam(model.parameters(), lr=learningRate,\n weight_decay=l2Penalty)\n accuracy, loss, accuracy_validate, loss_validate = pre_train(model, optimizer, dl_train, dl_test, x_train,\n y_train, x_validate, y_validate, run, outputDir, maxEpoch=200)\n accs.append(accuracy)\n losses.append(loss)\n accs_validate.append(accuracy_validate)\n losses_validate.append(loss_validate)\ndir = outputDir + 'pre_train_acc_loss_net4.npz'\nnp.savez(dir, a=np.mean(accs, axis=0), b=np.std(accs, axis=0),\n c=np.mean(losses, axis=0), d=np.std(losses, axis=0),\n e=np.mean(accs_validate, axis=0), f=np.std(accs_validate, axis=0),\n g=np.mean(losses_validate, axis=0), h=np.std(losses_validate, axis=0))\n# bestValidationAccs = []\n# AUCs = []\n# ACCs = []\n# epochs = 200\n# ALPHAs = None\n# for run in range(runs):\n# np.random.seed(seeds[run])\n# torch.manual_seed(seeds[run])\n# dl_train = torch.utils.data.DataLoader(ds_train, batch_size=batchSize, shuffle=True, drop_last=False)\n# dl_test = torch.utils.data.DataLoader(ds_test, batch_size=x_validate.shape[0], shuffle=False)\n# dl_combined = torch.utils.data.DataLoader(ds_combined, batch_size=x_combined.shape[0], shuffle=False)\n# PATH = outputDir + '/csnn_2_csnn_layers_run{}_epoch{}_affine_false.pth'.format(run, 0)\n# l = torch.load(PATH)\n# model = l['net']\n# optimizer = torch.optim.Adam(model.parameters(), lr=learningRate,\n# weight_decay=l2Penalty)\n# # scheduler = torch.optim.lr_scheduler.MultiStepLR(\n# # optimizer, milestones=[50, 100, 150], gamma=0.5\n# # )\n# # optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=1e-4)\n#\n# losses = []\n# accuracies = []\n# losses_validate = []\n# accuracies_validate = []\n# alphas = []\n# mmcs = []\n# nzs = []\n# aucs = []\n#\n# bestValidationAcc = 0.\n# for epoch in range(epochs):\n# # alpha = min(1, max(0, (epoch**0.1-1.5)/0.6))\n# # alpha = epoch/epochs\n# alpha = maxAlpha * epoch/epochs\n# # r2 = min(0.01, 0.01 - epoch * 0.06 / 5000)\n# # r2 = 1.\n# for i, batch in enumerate(dl_train):\n# loss, x, y, y_pred, z = step(model, optimizer, batch, alpha, r2)\n#\n# accuracy, loss = eval_step(model, x_train, y_train, alpha, r2)\n# #if epoch % 10 == 0:\n# # print('train: epoch {}, accuracy {:.3f}, loss {:.3f}'.format(epoch, accuracy, loss))\n# testacc, testloss = eval_step(model, x_validate, y_validate, alpha, r2)\n# if testacc > bestValidationAcc:\n# # include both learnable param and registered buffer\n# # PATH = outputDir+'/csnn_2_csnn_layers_run{}_r2{:.1f}_maxAlpha{:.1f}_affine_false.pth'.format(run, r2, maxAlpha)\n# # torch.save({'net':model, 'alpha':alpha, 'r2':r2}, PATH)\n# bestValidationAcc = testacc\n#\n# if epoch % 5 == 0:\n# #print('validation: epoch {}, fc1 shape {}, loss {:.3f}'.format(epoch, model.fc1.weight.data.shape[0], loss))\n# losses.append(loss)\n# losses_validate.append(testloss)\n# accuracies.append(accuracy)\n# accuracies_validate.append(testacc)\n# nz, mmc = nnz(x_ood, model, alpha, r2)\n# alphas.append(alpha)\n# mmcs.append(mmc)\n# nzs.append(nz)\n# uncertainties = eval_combined(model, dl_combined, alpha, r2)\n# falsePositiveRate, truePositiveRate, _= roc_curve(label_ood, -uncertainties)\n# AUC = auc(falsePositiveRate.astype(np.float32), truePositiveRate.astype(np.float32))\n# aucs.append(AUC)\n# print('epoch {}, alpha {:.2f}, r2 {:.1f}, nz {:.3f}, train {:.3f}, test {:.3f}, auroc {:.3f}'\n# .format(epoch, alpha, r2, 1.-nz,accuracy,testacc, AUC))\n#\n# # eliminate dead nodes\n# # if ( (epoch<200 and (epoch + 1) % (epochs / 100) == 0)\n# # or (epoch>=200 and (epoch + 1) % (epochs/10) == 0)):\n# # #_, dmu = active(torch.tensor(x_train).float(), model, alpha, r2)\n# # PATH = outputDir+'/csnn_2_csnn_layers_run{}_epoch{}_r2{:.1f}_maxAlpha{:.1f}_affine_false.pth'.format(run, epoch+1, r2, maxAlpha)\n# # torch.save({'net':model, 'alpha':alpha, 'r2':r2}, PATH)\n# # # model.keepNodes(dmu > 0)\n#\n# plot_save_loss(losses, losses_validate, outputDir+'/loss_csnn_2_csnn_layers_run{}_r2{:.1f}_maxAlpha{:.1f}_affine_false.png'.format(run, r2, maxAlpha))\n# plot_save_acc(accuracies, accuracies_validate, outputDir+'/acc_csnn_2_csnn_layers_run{}_r2{:.1f}_maxAlpha{:.1f}_affine_false.png'.format(run, r2, maxAlpha))\n# plot_save_acc_nzs_mmcs(alphas, accuracies_validate, nzs, aucs,\n# outputDir+'/acc_nzs_mmcs_csnn_2_csnn_layers_run{}_r2{:.1f}_maxAlpha{:.1f}_affine_false.png'.format(run, r2, maxAlpha))\n#\n# bestValidationAccs.append(max(accuracies_validate))\n# AUCs.append(aucs)\n# ACCs.append(accuracies_validate)\n# if ALPHAs is None: ALPHAs = alphas\n# AUCs = np.array(AUCs)\n# ACCs = np.array(ACCs)\n# print('mean and std of best validation acc in {} runs: {:.4f}, {:.4f}'\n# .format(runs, np.mean(np.array(bestValidationAccs)), np.std(np.array(bestValidationAccs))))\n# dir = outputDir + '/mean_std_accs_aucs_csnn_2_csnn_layers_r2{:.1f}_maxAlpha{:.1f}.npz'.format(r2, maxAlpha)\n# np.savez(dir, a=np.mean(AUCs, axis=0), b=np.std(AUCs, axis=0),\n# c=np.mean(ACCs, axis=0), d=np.std(ACCs, axis=0),\n# e=ALPHAs)\n# # plt.show()","sub_path":"train_us80_validate_us101.py","file_name":"train_us80_validate_us101.py","file_ext":"py","file_size_in_byte":7998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"555548496","text":"import torch\nimport torch.functional as F\nimport torch.nn as nn\nimport math\nimport sklearn\nimport numpy as np\n#import cupy as cp\n\nfrom sklearn.metrics import r2_score\n\n\ndef log_poisson_loss(log_x, t):\n loss = torch.mean(torch.exp(log_x) - t * log_x)\n #lossの最小値が0になるようにoffsetを引き算している。\n offset = torch.mean(t - t * torch.log(t))\n return loss - offset\n\n\ndef log_r2_score(log_x, t):\n t = t.to(\"cpu\")\n log_x = log_x.to(\"cpu\")\n x = torch.exp(log_x)\n x = log_x\n\n size = t.size(0)\n t_temp = torch.chunk(t, size, dim=0)\n x_temp = torch.chunk(x, size, dim=0)\n\n all_score = 0.0\n for i in range(size):\n t_num = torch.squeeze(t_temp[i])\n x_num = torch.squeeze(x_temp[i])\n t_num = t_num.detach().numpy()\n x_num = x_num.detach().numpy()\n score = r2_score(x_num, t_num, multioutput='variance_weighted')\n all_score += score\n return all_score / size\n\ndef pearsonR(output, target, n_targets):\n cost = []\n for i in range(n_targets):\n x = output[i]\n y = target[i]\n vx = x - torch.mean(x)\n vy = y - torch.mean(y)\n cost_temp = torch.sum(vx * vy) / (torch.sqrt(torch.sum(vx ** 2)) * torch.sqrt(torch.sum(vy ** 2)))\n #cost = vx * vy * torch.rsqrt(torch.sum(vx ** 2)) * torch.rsqrt(torch.sum(vy ** 2))\n cost_temp= cost_temp.detach().numpy()\n cost.append(cost_temp)\n return cost\n\n\ndef smoothing(sample_raw, n_targets):\n #移動平均の範囲\n window = 20\n #w:(1024)\n w = np.ones(window)/window\n #(1024, n_targets)\n avr_data = []\n for i in range(n_targets):\n sample = sample_raw[:, i]\n sample_avr = np.convolve(sample, w, mode='same')\n avr_data.append(sample_avr)\n return avr_data\n\n\ndef smoothing_damy(sample_raw, n_targets):\n #(1024, n_targets)\n avr_data = []\n for i in range(n_targets):\n sample = sample_raw[:, i]\n avr_data.append(sample)\n return avr_data","sub_path":"ge_loss.py","file_name":"ge_loss.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"58699615","text":"'''need to find out all the information \nabout a malware given its name \npossibly some other parameters'''\n\n''' Use case: We need to determine what kind of threat was detected \n(what was the user behavior which caused the threat to be downloaded on the machine)'''\n\n'''\ntest1 = {'Infection Channel': 'Via removable drives, Downloaded from the Internet, Dropped by other malware', \n\t\t'ALIASES': 'VBS/Agent.NDH(ESET-NOD32); HEUR:Worm.Script.Generic(Kaspersky); Worm.VBS.Agent(Ikarus)', \n\t\t'PLATFORM': 'Windows 2000, Windows Server 2003, Windows XP (32-bit, 64-bit), Windows Vista (32-bit, 64-bit), Windows 7 (32-bit, 64-bit)', \n\t\t'OVERALL RISK RATING': 'LOW', \n\t\t'DAMAGE POTENTIAL': 'MEDIUM', \n\t\t'DISTRIBUTION POTENTIAL': 'MEDIUM', \n\t\t'REPORTED INFECTION': 'LOW', \n\t\t'INFORMATION EXPOSURE': 'MEDIUM', \n\t\t'Threat Type': ' Worm', \n\t\t'Destructiveness': ' No', \n\t\t'Encrypted': ' Yes', \n\t\t'In the wild': ' Yes'}\n\ntest2 = {'Infection Channel': 'Dropped by other malware, Via removable drives', \n\t\t'ALIASES': 'Worm:VBS/Jenxcus!lnk(Microsoft), VBS/Autorun.worm.aadd!lnk(McAfee), Troj/JenxLnk-B(Sophos), LNK/Agent.AK trojan(Eset), VBS/Autorun.BC.worm(Panda)', \n\t\t'PLATFORM': 'Windows 2000, Windows Server 2003, Windows XP (32-bit, 64-bit), Windows Vista (32-bit, 64-bit), Windows 7 (32-bit, 64-bit)', \n\t\t'OVERALL RISK RATING': 'LOW', \n\t\t'DAMAGE POTENTIAL': 'LOW', \n\t\t'DISTRIBUTION POTENTIAL': 'MEDIUM', \n\t\t'REPORTED INFECTION': 'LOW', \n\t\t'INFORMATION EXPOSURE': 'LOW', \n\t\t'Threat Type': ' Trojan', \n\t\t'Destructiveness': ' No', \n\t\t'Encrypted': ' No', \n\t\t'In the wild': ' Yes'}\n\ntest3 = {'Infection Channel': 'Downloaded from the Internet', \n\t\t'PLATFORM': 'Linux', \n\t\t'OVERALL RISK RATING': 'LOW', \n\t\t'DAMAGE POTENTIAL': 'MEDIUM', \n\t\t'DISTRIBUTION POTENTIAL': 'LOW', \n\t\t'REPORTED INFECTION': 'LOW', \n\t\t'INFORMATION EXPOSURE': 'LOW', \n\t\t'Threat Type': ' Trojan', \n\t\t'Destructiveness': ' No', \n\t\t'Encrypted': ' No', \n\t\t'In the wild': ' Yes'} \n'''\n\n\nfrom bs4 import BeautifulSoup\n\nimport requests\nimport json\nimport sys\n\n## global variables \n\nurl = 'https://www.trendmicro.com/vinfo/us/threat-encyclopedia/malware/'\nkeys, values = [], []\n\n\n'''\nextract_class function to scrape:\n\tThreat Type\n\tDestructiveness \n\tEncrypted \n\tIn the wild'''\n\ndef extract_class(classify):\n\tclist = [c for c in classify.descendants if c.name is None]\n\tfor c in clist:\n\t\tk, v = c.strip().split(':')\n\t\tkeys.append(k)\n\t\tvalues.append(v)\n\n\treturn dict(zip(keys, values))\n\n\n''' \nextract_details function to scrape labels:\n\tOVERALL RISK RATING \n\tDAMAGE POTENTIAL\n\tDISTRIBUTION POTENTIAL\n\tDISTRIBUTION POTENTIAL\n\tREPORTED INFECTION\n\tINFORMATION EXPOSURE'''\n\ndef extract_details(details):\n\tfor tag in details.descendants:\n\t\tif tag.name == 'strong':\n\t\t\tkeys.append(tag.text[:-1].replace(' \\xa0', ''))\n\t\telif tag.name == 'p':\n\t\t\tvalues.append(tag.text)\n\t\telif (tag.name == 'img' and\n\t\t\ttag.get('title') is not None):\n\t\t\tvalues.append(tag['title'])\n\n\treturn dict(zip(keys, values))\n\n\n'''extract_channel to scrape Infection Channel'''\n\ndef extract_channel(channel):\n\tdata = {}\n\tk, v = channel.text.split(':')\n\tdata[k] = v.strip()\n\n\treturn data\n\n'''Combine 3 dicts'''\n\ndef main_data(soup):\n\tchannel = soup.find('div', class_='labelHeader')\n\tdetails = soup.find('div', class_='malwareHeader')\n\tclassify = soup.find('div', class_='iconDetails')\n\n\tmain = {}\n\n\tfor d in [extract_channel(channel), extract_details(details), extract_class(classify)]:\n\t\tfor k, v in d.items():\n\t\t\tmain[k] = v\n\n\treturn main\n\n'''Search for a query in the Trend Threat Encyclopedia\nHandle exceptions and check if the query was valid'''\n\ndef simple_search(name):\n\tname = name.strip().lower()\n\ttry:\n\t\tresponse = requests.get(url + name)\n\texcept requests.exceptions.RequestException as e:\n\t\tprint(e)\n\t\tsys.exit(0) # exit out of execution on exception\n\telse:\n\t\tsoup = BeautifulSoup(response.content, 'lxml')\n\t\ttitle_tag = soup.find('title') \n\t\ttitle_text = title_tag.text\n\t\tif 'Search' in title_text:\n\t\t\treturn \"Invalid query : {}\".format(name), False\n\t\treturn soup, True\n\n\n## test\nif __name__ == '__main__': \n\t# test set\n\n\t# invalid case\n\tinvalid = 'DFRZ.TGCHGbv'\n\n\tmalwares = ['Trojan.SH.KERBERDS.A', \n\t\t\t\t'Trojan.JS.KOVCOREG.A',\n\t\t\t\t'Rootkit.Linux.SKIDMAP.A',\n\t\t\t\t'Coinminer.Win64.MALXMR.TIAOODBZ',\n\t\t\t\t'Backdoor.Linux.BASHLITE.SMJC2',\n\t\t\t\t'ELF_SETAG.SM',\n\t\t\t\tinvalid,]\n\n\tfor mal in malwares:\n\t\tresult, valid = simple_search(mal)\n\t\tprint('\\n', mal)\n\t\tif valid:\n\t\t\tprint(json.dumps(main_data(result), indent=4))\n\t\telse:\n\t\t\tprint(result)\n","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"211805210","text":"from odoo import models,fields,api,_\nfrom io import StringIO\nfrom datetime import datetime\nimport base64\nfrom .api import UnicodeDictWriter,UnicodeDictReader\nimport time\nfrom odoo.exceptions import except_orm, Warning, RedirectWarning \nfrom odoo.api import Environment\nfrom dateutil import parser\nimport os\nfrom csv import DictWriter\n\nclass SaleOrder(models.Model):\n \n _inherit=\"sale.order\"\n\n picking_ref = fields.Char(string=\"Picking Reference\")\n \n @api.multi\n def already_imported_order(self,partner,file_order_number,file_picking_ref):\n sale_order = self.search([('partner_id','=',partner.id),('picking_ref','=',file_picking_ref),('client_order_ref','=',file_order_number)],limit=1)\n return sale_order\n \n @api.model\n def process_delivery_address(self,data):\n company = False\n if data.get('company_name',False):\n company = self.env['res.partner'].search([('name','=',data.get('company_name')),('is_company','=',True)],limit=1)\n \n street = \"%s, %s\"%(data.get('house_no',''),data.get('street1','')) if data.get('house_no',False) else data.get('street1','') \n final_data = {\n 'company': company and company.id or False,\n 'name': \"%s %s\"%(data.get('first_name',''),data.get('last_name','')),\n 'street': street,\n 'street2': data.get('street2',''),\n 'phone': data.get('contact_no',''),\n 'email_id': data.get('email',''),\n 'city': data.get('city',''),\n 'postal-code': data.get('zip',''),\n 'country_name': data.get('country',''),\n 'state_name' : data.get('state',''),\n }\n delivery_address = self.env['res.partner'].create_or_update_partner(final_data)\n return delivery_address\n \n @api.model\n def prepare_sale_order_data(self,data):\n sale_order = self.env['sale.order']\n fpos = False\n order_vals = {\n 'picking_ref':data.get('picking_ref',False),\n 'name':data.get('name',False),\n 'partner_id' :data.get('partner_id'),\n 'partner_shipping_id' : data.get('partner_shipping_id'),\n 'warehouse_id' : data.get('warehouse_id'),\n 'company_id':data.get('company_id'),\n }\n new_record = sale_order.new(order_vals)\n new_record.onchange_partner_id() # Return Pricelist- Payment terms- Invoice address- Delivery address\n new_record.onchange_partner_id_carrier_id()\n new_record.onchange_partner_shipping_id() # Return Fiscal Position\n order_vals = sale_order._convert_to_write({name: new_record[name] for name in new_record._cache})\n fpos = order_vals.get('fiscal_position_id',fpos)\n order_vals.update({\n 'picking_ref':data.get('picking_ref',False),\n 'name':data.get('name',False),\n 'partner_id' :data.get('partner_id'),\n 'partner_shipping_id' : data.get('partner_shipping_id'),\n 'warehouse_id' : data.get('warehouse_id'),\n 'company_id':data.get('company_id'),\n 'fiscal_position_id': fpos,\n 'client_order_ref':data.get('client_order_ref',''),\n })\n \n return order_vals\n \n @api.model\n def import_sale_orders_from_ftp(self,partner_ids=[],is_cron=False):\n \n if not partner_ids:\n partner_ids = self.env['res.partner'].search([('integrate_edi','=',True)])\n \n for partner in partner_ids:\n \n if not partner.integrate_edi:\n continue\n \n server_filenames = False\n filenames = False\n with partner.get_edi_interface(operation=\"sale_import\") as edi_interface:\n if partner.prefix_sale_import:\n filenames, server_filenames = \\\n edi_interface.pull_from_ftp(partner.prefix_sale_import)\n else:\n filenames, server_filenames = \\\n edi_interface.pull_from_ftp('sale_order')\n \n jobs_to_process = [] \n for file_count in range(0,len(filenames)):\n with open(filenames[file_count]) as file:\n header = True\n file_process_obj=self.env['edi.file.process.job'] \n transaction_log_obj=self.env['edi.transaction.log']\n job_id = False\n for line in UnicodeDictReader(file,['order_no','picking_ref','sku','quantity','company_name','first_name','last_name','street1','street2','country','state','city','zip','email','contact_no','house_no'], delimiter=partner.csv_delimiter):\n if header:\n header = False\n continue\n if not job_id:\n job_id=file_process_obj.create({\n 'application':'sales',\n 'ftp_partner_id':partner.id,\n 'operation_type':'import',\n 'filename':server_filenames[file_count],\n })\n jobs_to_process.append(job_id)\n \n if not ( line.get('first_name',False) or line.get('last_name',False) ):\n transaction_log_obj.create({\n 'file_order_number':line.get('order_no'),\n 'file_picking_ref':line.get('picking_ref'),\n 'file_quantity':line.get('quantity'),\n 'file_sku':line.get('sku'),\n 'job_id':job_id.id,\n 'is_processed':False,\n 'Message' : \"First name and Last Name of customer is required to process order\"\n })\n continue\n \n delivery_address = self.process_delivery_address(line)\n \n transaction_log_obj.create({\n 'file_order_number':line.get('order_no'),\n 'file_quantity':line.get('quantity'),\n 'file_picking_ref':line.get('picking_ref'),\n 'file_sku':line.get('sku'),\n 'delivery_address_id':delivery_address.id,\n 'job_id':job_id.id,\n 'is_processed':False\n })\n file.seek(0)\n file_data = file.read().encode()\n vals = {\n 'name':server_filenames[file_count],\n 'datas':base64.encodestring(file_data),\n 'datas_fname':filenames[file_count],\n 'type':'binary',\n 'res_model':'edi.file.process.job',\n }\n attachment=self.env['ir.attachment'].create(vals)\n job_id.message_post(body=(\"Sales file imported\"),attachment_ids=attachment.ids)\n\n for job in jobs_to_process:\n job.process_sale_orders()\n \n # Move To Archive\n try:\n with partner.get_edi_interface(operation=\"sale_import\") as tpw_interface:\n tpw_interface.archive_file(server_filenames)\n tpw_interface.delete_from_tmp(filenames)\n except:\n if is_cron:\n job.write({'message': \"Problem with moveing file to Archive Directory.\"})\n else:\n raise Warning(\"Problem with moving file to Archive Directory. Please check credentials and file paths\")","sub_path":"edi_ftp_integration/models/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":7899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"436370308","text":"from dataclasses import dataclass, field\nfrom functools import reduce\nfrom typing import List, Optional\n\nfrom matplotlib.figure import Figure\n\nimport matplotlib.pyplot as plt\n\nfrom solai_evolutionary_algorithm.evolution.evolution_types import Population, EvaluatedPopulation\nfrom solai_evolutionary_algorithm.evolution.evolver_config import EvolverListener\n\n\n@dataclass\nclass GenerationsData:\n populations_fitnesses: List[List[float]] = field(default_factory=list)\n populations_feasibility_score: List[List[float]] = field(default_factory=list)\n populations_novelty: List[List[float]] = field(default_factory=list)\n\n\ndef update_generations_data(generations_data: GenerationsData, evaluated_population: EvaluatedPopulation):\n generations_data.populations_fitnesses.append([\n sum(evaluated_individual['fitness'])\n for evaluated_individual in evaluated_population\n ])\n generations_data.populations_feasibility_score.append([\n evaluated_individual['feasibility_score']\n for evaluated_individual in evaluated_population\n ])\n generations_data.populations_novelty.append([\n evaluated_individual['novelty']\n for evaluated_individual in evaluated_population\n ])\n\n\nclass PlotGenerationsLocalService(EvolverListener):\n def __init__(self, hold_last_plot: bool = True, save_plot_filename: Optional[str] = None):\n self.feasible_generations_data = GenerationsData()\n self.infeasible_generations_data = GenerationsData()\n self.hold_last_plot = hold_last_plot\n self.save_plot_filename = save_plot_filename\n\n\n\n def on_start(self, *args):\n plt.ion()\n _, self.axes = plt.subplots(3, 2)\n plt.xlabel(\"generations\")\n plt.ylabel(\"fitness\")\n plt.show()\n\n def on_new_generation(self, evaluated_population, is_last_generation) -> None:\n feasible_evaluated_population = [\n evaluated_individual\n for evaluated_individual in evaluated_population\n if evaluated_individual['feasibility_score'] == 1\n ]\n\n infeasible_evaluated_population = [\n evaluated_individual\n for evaluated_individual in evaluated_population\n if evaluated_individual['feasibility_score'] != 1\n ]\n\n update_generations_data(self.feasible_generations_data, feasible_evaluated_population)\n update_generations_data(self.infeasible_generations_data, infeasible_evaluated_population)\n\n feasible_pop_sizes = [\n len(pop)\n for pop in self.feasible_generations_data.populations_fitnesses\n ]\n\n infeasible_pop_sizes = [\n len(pop)\n for pop in self.infeasible_generations_data.populations_fitnesses\n ]\n\n # plt.figure(1)\n # # _, [ax1, ax2] = plt.subplots(1, 2)\n # plt.gcf().clear()\n for ax in self.axes.reshape(-1):\n ax.clear()\n\n feasible_novelty_ax = self.axes[0][0]\n feasible_feasibility_ax = self.axes[1][0]\n feasible_pop_size_ax = self.axes[2][0]\n\n infeasible_novelty_ax = self.axes[0][1]\n infeasible_feasibility_ax = self.axes[1][1]\n infeasible_pop_size_ax = self.axes[2][1]\n\n feasible_novelty_ax.boxplot(self.feasible_generations_data.populations_novelty, showmeans=True, meanline=True)\n feasible_novelty_ax.set_title(\"feasible\")\n feasible_novelty_ax.set_ylabel(\"novelty\")\n\n feasible_feasibility_ax.boxplot(self.feasible_generations_data.populations_feasibility_score, showmeans=True, meanline=True)\n feasible_feasibility_ax.set_ylabel(\"feasibility\")\n\n feasible_pop_size_ax.plot(range(1, len(feasible_pop_sizes)+1), feasible_pop_sizes)\n feasible_pop_size_ax.set_ylabel(\"population size\")\n feasible_pop_size_ax.set_xlabel(\"generations\")\n\n infeasible_novelty_ax.boxplot(self.infeasible_generations_data.populations_novelty, showmeans=True, meanline=True)\n infeasible_novelty_ax.set_title(\"infeasible\")\n\n infeasible_feasibility_ax.boxplot(self.infeasible_generations_data.populations_feasibility_score, showmeans=True, meanline=True)\n\n infeasible_pop_size_ax.plot(range(1, len(infeasible_pop_sizes)+1), infeasible_pop_sizes)\n infeasible_pop_size_ax.set_xlabel(\"generations\")\n\n plt.tight_layout()\n plt.draw()\n\n plt.pause(0.001)\n\n def on_end(self, *args, **kwargs):\n plt.ioff()\n if self.save_plot_filename is not None:\n plt.savefig(f\"files/{self.save_plot_filename}\", dpi=1000, format='png')\n if self.hold_last_plot:\n plt.show()\n else:\n plt.close()\n\n","sub_path":"solai_evolutionary_algorithm/plot_services/plot_generations_service.py","file_name":"plot_generations_service.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"98436951","text":"import torch\n\nfrom moses.script_utils import add_train_args, read_smiles_csv, set_seed\nfrom moses.cvae.config import get_parser as vae_parser\nfrom moses.cvae.corpus import OneHotCorpus\nfrom moses.cvae.model import VAE\nfrom moses.cvae.trainer import VAETrainer\n\n\ndef get_parser():\n\n parser = add_train_args(vae_parser())\n\n # conditional generation\n parser.add_argument('--conditional', type=int, default=0,\n help='Conditional generation mode')\n parser.add_argument('--output_size', type=int, default=10,\n help='Output size in the condition linear layer')\n\n return parser\n\n# read fingerprints\ndef read_fps_csv(path):\n return pd.read_csv(path,\n usecols=['fingerprints_center'],\n squeeze=True).astype(str).tolist()\n\n# convert fingerprints to list\ndef fps_to_list(fps):\n fps = [list(x) for x in fps]\n for i in range(len(fps)):\n fps[i] = [int(x) for x in fps[i]]\n return fps\n\n\ndef main(config):\n set_seed(config.seed)\n\n train = read_smiles_csv(config.train_load)\n\n device = torch.device(config.device)\n\n # For CUDNN to work properly:\n if device.type.startswith('cuda'):\n torch.cuda.set_device(device.index or 0)\n\n corpus = OneHotCorpus(config.n_batch, device)\n train = corpus.fit(train).transform(train)\n\n\n # condition mode\n if config.conditional:\n fps = read_fps_csv(config.train_load)\n fps = fps_to_list(fps)\n fps = [torch.tensor(f, dtype=torch.float, device=device) for f in fps]\n\n # fingerprints length\n fps_len = len(fps[0])\n\n # fingerprints dataloader\n fps = corpus.fps_transform(fps)\n\n # training data\n train = zip(train, fps)\n shuffle(train)\n else:\n fps_len = 0\n\n\n model = VAE(corpus.vocab, fps_len, config).to(device)\n\n trainer = VAETrainer(config)\n\n torch.save(config, config.config_save)\n torch.save(corpus.vocab, config.vocab_save)\n trainer.fit(model, train, config.conditional)\n\n\nif __name__ == '__main__':\n parser = get_parser()\n config = parser.parse_known_args()[0]\n main(config)\n","sub_path":"scripts/vae/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"464499059","text":"#---PROCEDURAL CODE\nstarting_number = 96\n\n#pangkat 2\nsquare = starting_number ** 2\n\n#hasil ditambah 1\nincrement = square + 1\n\n#dipankat 3\ncube = increment ** 3\n\n#dikurangi 1\ndecrement = cube - 1\n\n#hasilnya\nprint('procedural: ',decrement)\n\n\n#---Functional Programing\ndef call(x, f):\n return f(x)\n\n#mendefiniskan fungsi kuadrat\nsquare_f = lambda x : x*x\n\n#fungsi increment\nincrement_f = lambda x : x+1\n\n#fungsi pangkat 3\ncube_f = lambda x : x*x*x\n\n#fungsi decrement\ndecrement_f = lambda x : x-1\n\n#masukin semua fungsi kalo mau dieksekusi\nfunc = [square_f, increment_f, cube_f, decrement_f]\n\n#dibawah bukan contoh functional programing,\n#kalo functional di pisah\n\nfrom functools import reduce\nprint(reduce(call, func, 96))","sub_path":"novice/02-01/21_lat1.py","file_name":"21_lat1.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"121645344","text":"numbers = [2, 6, 7, 11, 17, 19]\n\nwhile True:\n x = input(\"Type a number or \\\"q\\\".(If you type \\\"q\\\",you can quit this game.):\")\n if x == \"q\":\n break\n else:\n try:\n x = int(x)\n if x in numbers:\n print(\"You're right!\")\n else:\n print(\"Sorry, you're wrong.\")\n except ValueError:\n print(\"Sorry, type a number or \\\"q\\\".\")\n","sub_path":"challenge27.py","file_name":"challenge27.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"512260397","text":"import gpxpy\nimport gpxpy.gpx\nimport os\nfrom django.conf import settings\n\nimport gmplot\nfrom django.conf import settings\n\ndef analyse_gpx(file, index=-1):\n gpx = gpxpy.parse(file)\n data = {}\n data[\"length2D\"] = gpx.length_2d()\n data[\"length3D\"] = gpx.length_3d()\n c = gpx.get_uphill_downhill()\n data[\"pos_climb\"] = c.uphill\n data[\"pos_climb\"] = c.downhill\n gpx.smooth()\n d = gpx.get_uphill_downhill()\n data[\"pos_climb_smooth\"] = d.uphill\n data[\"neg_climb_smooth\"] = d.downhill\n data[\"duration\"] = gpx.get_duration()\n data[\"average_speed\"] = 3.6*data[\"length3D\"]/data[\"duration\"]\n data[\"elevation_extreme\"] = gpx.get_elevation_extremes()\n #print(data[\"elevation_extreme\"])\n\n raw_data_lat = []\n raw_data_lon = []\n raw_data_alt = []\n for track_idx, track in enumerate(gpx.tracks):\n for seg_idx, segment in enumerate(track.segments):\n for point_idx, point in enumerate(segment.points):\n raw_data_lat.append(point.latitude)\n raw_data_lon.append(point.longitude)\n raw_data_alt.append(point.elevation)\n\n #gmap = gmplot.GoogleMapPlotter(raw_data_lat[0], raw_data_lon[0], 14)\n #gmap.scatter(raw_data_lat, raw_data_lon, 'k', marker=True)\n\n #gmap.draw(os.path.join(settings.MEDIA_ROOT, str(index) + \".html\"))\n\n return data\n \"\"\"\n run_data = []\n for track_idx, track in enumerate(gpx.tracks):\n track_name = track.name\n track_time = track.get_time_bounds().start_time\n track_length = track.length_3d()\n track_duration = track.get_duration()\n track_speed = track.get_moving_data().max_speed\n\n for seg_idx, segment in enumerate(track.segments):\n segment_length = segment.length_3d()\n for point_idx, point in enumerate(segment.points):\n run_data.append([track_idx, track_name,\n track_time, track_length, track_duration, track_speed,\n seg_idx, segment_length, point.time, point.latitude,\n point.longitude, point.elevation, segment.get_speed(point_idx)])\n return run_data\n \"\"\"\n\nif __name__ == '__main__':\n with open('test.gpx', 'r') as f:\n print(analyse_gpx(f))","sub_path":"Django_projects/gpx_explorer/src/gpx_explorer/script/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"440346645","text":"import tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIst_data', one_hot=True)\n\ntf.set_random_seed(777)\n\nlearning_rate = 0.1\ntraining_epoch = 20\nbatch_size = 100\n\nn_hidden = 256\nn_input = 784\n\nx = tf.placeholder(dtype=tf.float32, shape=[None, n_input])\n\n# encoder 레이어\nw_encode = tf.Variable(tf.random_normal([n_input, n_hidden]))\nb_encode = tf.Variable(tf.random_normal([n_hidden]))\nencoder = tf.nn.sigmoid(tf.matmul(x, w_encode) + b_encode)\n\n# decoder 레이어\nw_decode = tf.Variable(tf.random_normal([n_hidden, n_input]))\nb_decode = tf.Variable(tf.random_normal([n_input]))\ndecoder = tf.nn.sigmoid(tf.matmul(encoder, w_decode) + b_decode)\n\ncost = tf.reduce_mean(tf.square(x-decoder))\ntrain = tf.train.RMSPropOptimizer(learning_rate=learning_rate).minimize(cost)\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\ntotal_batch = int(mnist.train.num_examples/batch_size)\n\nfor epoch in range(training_epoch):\n total_cost = 0\n for i in range(total_batch):\n batch_x, batch_y = mnist.train.next_batch(batch_size)\n _c, _ = sess.run([cost, train], feed_dict={x:batch_x})\n total_cost += _c\n print(\"epoch:{} avg_cost:{}\".format(epoch+1, total_cost/total_batch))\n\n####################################################\nsample_size = 10\nsamples = sess.run(decoder, feed_dict={x: mnist.test.images[:sample_size]})\n\nfig, ax = plt.subplots(2, sample_size, figsize=(sample_size, 2))\nfor i in range(sample_size):\n ax[0][i].set_axis_off()\n ax[1][i].set_axis_off()\n ax[0][i].imshow(np.reshape(mnist.test.images[i], (28, 28)))\n ax[1][i].imshow(np.reshape(samples[i], (28, 28)))\nplt.show()","sub_path":"Python/cnn_study_day5/day5/01_AutoEncoder.py","file_name":"01_AutoEncoder.py","file_ext":"py","file_size_in_byte":1748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"345676722","text":"import json\nimport sys\n\nimport pettingzoo.butterfly.pistonball_v6 as pistonball_v5\nimport supersuit as ss\nfrom stable_baselines3 import PPO\nfrom stable_baselines3.common.callbacks import EvalCallback\nfrom stable_baselines3.common.evaluation import evaluate_policy\nfrom stable_baselines3.common.preprocessing import is_image_space, is_image_space_channels_first\nfrom stable_baselines3.common.vec_env import VecMonitor, VecNormalize, VecTransposeImage\n\nnum = sys.argv[1]\nn_evaluations = 20\nn_agents = 20\nn_envs = 4\nn_timesteps = 2000000\n\nwith open(\"./hyperparameter_jsons/\" + \"hyperparameters_\" + num + \".json\") as f:\n params = json.load(f)\n\nprint(params)\n\n\ndef image_transpose(env):\n if is_image_space(env.observation_space) and not is_image_space_channels_first(\n env.observation_space\n ):\n env = VecTransposeImage(env)\n return env\n\n\nenv = pistonball_v5.parallel_env()\nenv = ss.color_reduction_v0(env, mode=\"B\")\nenv = ss.resize_v0(env, x_size=84, y_size=84)\nenv = ss.frame_stack_v1(env, 3)\nenv = ss.pettingzoo_env_to_vec_env_v1(env)\nenv = ss.concat_vec_envs_v1(env, n_envs, num_cpus=1, base_class=\"stable_baselines3\")\nenv = VecMonitor(env)\nenv = image_transpose(env)\n\neval_env = pistonball_v5.parallel_env()\neval_env = ss.color_reduction_v0(eval_env, mode=\"B\")\neval_env = ss.resize_v0(eval_env, x_size=84, y_size=84)\neval_env = ss.frame_stack_v1(eval_env, 3)\neval_env = ss.pettingzoo_env_to_vec_env_v1(eval_env)\neval_env = ss.concat_vec_envs_v1(\n eval_env, 1, num_cpus=1, base_class=\"stable_baselines3\"\n)\neval_env = VecMonitor(eval_env)\neval_env = image_transpose(eval_env)\n\neval_freq = int(n_timesteps / n_evaluations)\neval_freq = max(eval_freq // (n_envs * n_agents), 1)\n\nall_mean_rewards = []\n\nfor i in range(10):\n try:\n model = PPO(\"CnnPolicy\", env, verbose=1, **params)\n eval_callback = EvalCallback(\n eval_env,\n best_model_save_path=\"./eval_logs/\" + num + \"/\" + str(i) + \"/\",\n log_path=\"./eval_logs/\" + num + \"/\" + str(i) + \"/\",\n eval_freq=eval_freq,\n deterministic=True,\n render=False,\n )\n model.learn(total_timesteps=n_timesteps, callback=eval_callback)\n model = PPO.load(\"./eval_logs/\" + num + \"/\" + str(i) + \"/\" + \"best_model\")\n mean_reward, std_reward = evaluate_policy(\n model, eval_env, deterministic=True, n_eval_episodes=25\n )\n print(mean_reward)\n print(std_reward)\n all_mean_rewards.append(mean_reward)\n if mean_reward > 90:\n model.save(\n \"./mature_policies/\"\n + str(num)\n + \"/\"\n + str(i)\n + \"_\"\n + str(mean_reward).split(\".\")[0]\n + \".zip\"\n )\n except:\n print(\"Error occurred during evaluation\")\n\nif len(all_mean_rewards) > 0:\n print(sum(all_mean_rewards) / len(all_mean_rewards))\nelse:\n print(\"No mature policies found\")\n","sub_path":"eval_hyperparameters.py","file_name":"eval_hyperparameters.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"5896758","text":"# Import CMS python class definitions such as Process, Source, and EDProducer\nimport FWCore.ParameterSet.Config as cms\n\n# Set up a process, named RECO in this case\nprocess = cms.Process(\"ReadIn\")\n\nprocess.load(\"FWCore.MessageService.MessageLogger_cfi\")\n\nprocess.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )\n\n# Configure the object that reads the input file\nprocess.source = cms.Source(\"PoolSource\", \n fileNames = cms.untracked.vstring('root://cms-xrd-global.cern.ch//store/data/Run2018B/EGamma/RAW/v1/000/317/182/00000/962DC3A0-4364-E811-B353-02163E017F41.root'),\n)\n\n# Configure the object that writes an output file\nprocess.out = cms.OutputModule(\"PoolOutputModule\",\n fileName = cms.untracked.string(\"local.root\")\n)\n\nprocess.end = cms.EndPath(process.out)\n","sub_path":"PSets/pset.py","file_name":"pset.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"296498193","text":"import numpy as np\nimport pandas as pd\nimport xgboost as xgb\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.model_selection import cross_val_score, train_test_split, KFold\nimport time\n\n#load data\n\nfile_name = \"./data/train_preprocessed2.csv\"\ntrain_df = pd.read_csv(file_name, low_memory = False)\n\n\n#Setup data\n\narray = train_df.values\ndata = array[:, 0:70]\ntarget = array[:, 70]\nseed = 7\ntest_size = 0.2\n\ndata_train, data_test, target_train, target_test = train_test_split(data, target, test_size = test_size, random_state = seed)\n\n\n\n#Set XGBClassifier\n\nxgb_clf = xgb.XGBClassifier(eval_metric = 'auc', n_trees = 250)\n\nxgb_params = {\n 'learning_rate' : np.arange(0.01, 0.20, 0.01),\n 'min_child_weight' : np.arange(1, 20, 1), \n 'max_depth' : np.arange(2, 10, 1),\n 'gamma' : np.arange(0, 10, 1), \n 'subsample' : np.arange(0.5, 1.0, 0.1),\n 'colsample_bytree' : np.arange(0.1, 1.0, 0.1),\n 'objective' : ['reg:linear'],\n 'silent' : [1],\n}\n\n\n#Set GridSearchCV\nGSCV = GridSearchCV(xgb_clf, xgb_params, cv=5, scoring = 'roc_auc', n_jobs = 1, verbose = 2)\n\n\n\n#Running GridSearch\nstart_time = time.time()\nGSCV.fit(data, target)\nelapsed_time = time.time() - start_time\n\nprint(\"%s seconds elapsed\"%elapsed_time)\nbest = rs.best_estimator_\nprint(best)\n\n\n\n\n\n\n","sub_path":"AutoMl/gridsearch.py","file_name":"gridsearch.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"605107105","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport cv2\nimport torch\nimport random\nimport numpy as np\nimport torch.nn as nn\nfrom loss import MultiBoxLoss\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\nfrom config import Config as config\nfrom got10k.trackers import Tracker\n\nclass SiamRPN(nn.Module):\n\n def __init__(self, anchor_num = 5):\n super(SiamRPN, self).__init__()\n\n self.anchor_num = anchor_num\n self.feature = nn.Sequential(\n # conv1\n nn.Conv2d(3, 64, kernel_size = 11, stride = 2),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace = True),\n nn.MaxPool2d(kernel_size = 3, stride = 2),\n # conv2\n nn.Conv2d(64, 192, kernel_size = 5),\n nn.BatchNorm2d(192),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size = 3, stride = 2),\n # conv3\n nn.Conv2d(192, 384, kernel_size = 3),\n nn.BatchNorm2d(384),\n nn.ReLU(inplace = True),\n # conv4\n nn.Conv2d(384, 256, kernel_size = 3),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace = True),\n # conv5\n nn.Conv2d(256, 256, kernel_size = 3),\n nn.BatchNorm2d(256))\n\n self.conv_reg_z = nn.Conv2d(256, 256 * 4 * self.anchor_num, 3, 1)\n self.conv_reg_x = nn.Conv2d(256, 256, 3)\n self.conv_cls_z = nn.Conv2d(256, 256 * 2 * anchor_num, 3, 1)\n self.conv_cls_x = nn.Conv2d(256, 256, 3)\n self.adjust_reg = nn.Conv2d(4 * anchor_num, 4 * anchor_num*1, 1)\n\n def forward(self, z, x):\n return self.inference(x, *self.learn(z))\n\n def learn(self, z):\n z = self.feature(z)\n kernel_reg = self.conv_reg_z(z)\n kernel_cls = self.conv_cls_z(z)\n\n k = kernel_reg.size()[-1]\n kernel_reg = kernel_reg.view(4 * self.anchor_num, 256, k, k)\n kernel_cls = kernel_cls.view(2 * self.anchor_num, 256, k, k)\n\n return kernel_reg, kernel_cls\n\n def inference(self, x, kernel_reg, kernel_cls):\n x = self.feature(x)\n x_reg = self.conv_reg_x(x)\n x_cls = self.conv_cls_x(x)\n\n out_reg = self.adjust_reg(F.conv2d(x_reg, kernel_reg))\n out_cls = F.conv2d(x_cls, kernel_cls)\n\n return out_reg, out_cls\n\nclass TrackerSiamRPN(Tracker):\n\n def __init__(self, net_path=None, **kargs):\n super(TrackerSiamRPN, self).__init__(\n name='SiamRPN', is_deterministic=True)\n\n '''setup GPU device if available'''\n self.cuda = torch.cuda.is_available()\n self.device = torch.device('cuda:0' if self.cuda else 'cpu')\n\n '''setup model'''\n self.net = SiamRPN()\n if self.cuda:\n self.net = self.net.cuda()\n\n if net_path is not None:\n self.net.load_state_dict(torch.load(\n net_path, map_location = lambda storage, loc: storage ))\n #self.net = self.net.to(self.device)\n\n '''setup optimizer'''\n self.criterion = MultiBoxLoss()\n\n self.optimizer = torch.optim.SGD(\n self.net.parameters(),\n lr = config.lr,\n momentum = config.momentum,\n weight_decay = config.weight_decay)\n\n def step(self, epoch, dataset, backward=True):\n\n if backward:\n self.net.train()\n else:\n self.net.eval()\n\n cur_lr = adjust_learning_rate(config.lr, self.optimizer, epoch, gamma=0.1)\n\n template, detection, pos_neg_diff = dataset\n if self.cuda:\n template, detection, pos_neg_diff = template.cuda(), detection.cuda(), pos_neg_diff.cuda()\n\n rout, cout = self.net(template, detection)\n\n cout = cout.squeeze().permute(1,2,0).reshape(-1, 2)\n\n rout = rout.squeeze().permute(1,2,0).reshape(-1, 4)\n\n predictions, targets = (cout, rout), pos_neg_diff.squeeze()\n\n closs, rloss, loss = self.criterion(predictions, targets)\n\n if backward:\n self.optimizer.zero_grad()\n loss.backward(retain_graph=True)\n self.optimizer.step()\n\n return closs, rloss, loss, cur_lr\n\n '''save model'''\n def save(self,model, exp_name_dir, epoch):\n model_save_dir_pth = '{}/model'.format(exp_name_dir)\n if not os.path.exists(model_save_dir_pth):\n os.makedirs(model_save_dir_pth)\n net_path = os.path.join(model_save_dir_pth, 'model_e%d.pth' % (epoch + 1))\n torch.save(model.net.state_dict(), net_path)\n\ndef adjust_learning_rate(lr, optimizer, epoch, gamma=0.1):\n \"\"\"Sets the learning rate to the initial LR decayed 0.9 every 50 epochs\"\"\"\n lr = lr * (0.9 ** (epoch // 1))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n return lr\n","sub_path":"train/net.py","file_name":"net.py","file_ext":"py","file_size_in_byte":4749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"339273127","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 ('df_user', '0002_auto_20180308_1725'),\n ('df_goods', '0002_auto_20180311_2026'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Order',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('order_date', models.DateTimeField(auto_now=True)),\n ('ototal', models.DecimalField(max_digits=8, decimal_places=2)),\n ('oispay', models.BooleanField(default=False)),\n ('orecaddr', models.CharField(max_length=100)),\n ('orderno', models.CharField(max_length=15)),\n ('otransfee', models.DecimalField(max_digits=6, decimal_places=2)),\n ('owner', models.ForeignKey(to='df_user.UserInfo')),\n ],\n ),\n migrations.CreateModel(\n name='OrderItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('goodscount', models.IntegerField()),\n ('sum', models.DecimalField(max_digits=6, decimal_places=2)),\n ('goodstype', models.ForeignKey(to='df_goods.GoodsInfo')),\n ('partof', models.ForeignKey(to='df_order.Order')),\n ],\n ),\n ]\n","sub_path":"django/django_1/project/everydayfresh/df_order/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"154711387","text":"\"\"\"\nInteract with the migration files.\n\"\"\"\n\nimport io\nimport os\nfrom distutils.version import StrictVersion\n\nfrom septentrion import utils\nfrom septentrion.settings import settings\n\n\ndef list_dirs(root):\n return [d for d in os.listdir(root) if os.path.isdir(os.path.join(root, d))]\n\n\ndef list_files(root):\n return [d for d in os.listdir(root) if os.path.isfile(os.path.join(root, d))]\n\n\ndef get_known_versions():\n \"\"\"\n Return the list of the known versions defined in migration repository,\n ordered.\n Ignore symlinks.\n \"\"\"\n # get all subfolders\n try:\n dirs = list_dirs(settings.MIGRATIONS_ROOT)\n except OSError:\n raise ValueError(\"settings.MIGRATIONS_ROOT is improperly configured.\")\n\n # exclude symlinks and some folders (like schemas, fixtures, etc)\n versions = [\n d\n for d in dirs\n if not os.path.islink(os.path.join(settings.MIGRATIONS_ROOT, d))\n and utils.is_version(d)\n ]\n\n # sort versions\n versions.sort(key=StrictVersion)\n return versions\n\n\ndef is_manual_migration(migration_path):\n\n if \"/manual/\" in migration_path:\n return True\n\n if not migration_path.endswith(\"dml.sql\"):\n return False\n\n with io.open(migration_path, \"r\", encoding=\"utf8\") as f:\n for line in f:\n if \"--meta-psql:\" in line:\n return True\n\n return False\n\n\ndef get_known_schemas():\n return os.listdir(os.path.join(settings.MIGRATIONS_ROOT, \"schemas\"))\n\n\ndef get_known_fixtures():\n try:\n return os.listdir(os.path.join(settings.MIGRATIONS_ROOT, \"fixtures\"))\n except FileNotFoundError:\n return []\n\n\ndef get_migrations_files_mapping(version):\n \"\"\"\n Return an dict containing the list of migrations for\n the given version.\n Key: name of the migration.\n Value: path to the migration file.\n \"\"\"\n\n def filter_migrations(files):\n return [f for f in files if f.endswith(\"ddl.sql\") or f.endswith(\"dml.sql\")]\n\n version_root = os.path.join(settings.MIGRATIONS_ROOT, version)\n migrations = {}\n\n # list auto migrations\n try:\n files = list_files(version_root)\n except OSError:\n raise ValueError(\"No sql folder found for version {}.\".format(version))\n # filter files (keep *ddl.sql and *dml.sql)\n auto_migrations = filter_migrations(files)\n # store migrations\n for mig in auto_migrations:\n migrations[mig] = os.path.join(version_root, mig)\n\n # list manual migrations\n manual_root = os.path.join(version_root, \"manual\")\n try:\n files = list_files(manual_root)\n except OSError:\n files = []\n # filter files (keep *ddl.sql and *dml.sql)\n auto_migrations = filter_migrations(files)\n # store migrations\n for mig in auto_migrations:\n migrations[mig] = os.path.join(manual_root, mig)\n\n return migrations\n","sub_path":"septentrion/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":2848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"193150404","text":"\"\"\"\n --- Day 6: Chronal Coordinates ---\n The device on your wrist beeps several times, and once again you feel like you're falling.\n \n\n \"\n Situation critical\n ,\" the device announces. \"Destination indeterminate. Chronal interference detected. Please specify new target coordinates.\"\n \n\n The device then produces a list of coordinates (your puzzle input). Are they places it thinks are safe or dangerous? It recommends you check manual page 729. The Elves did not give you a manual.\n \n\n\n https://adventofcode.com/2018/day/6\n\"\"\"\n\n# import aoc\nimport collections\nimport itertools\nimport os\n# import re\n# import sys\n# from operator import add\n# from operator import mul\n# from itertools import combinations\n\n# from collections import Counter\n\n\nclass Point:\n\n def __init__(self, number, x, y):\n self.number = int(number)\n self.x = int(x)\n self.y = int(y)\n\n def dist(self, x, y):\n return abs(self.x - x) + abs(self.y - y)\n\n # def dist(self, other):\n # return abs(self.x - other.x) + abs(self.y - other.y)\n\n\n def __str__(self):\n return \"{}:({},{})\".format(self.number, self.x, self.y)\n\ndebug = False\nif debug:\n N = 10\n lines = [\"1, 1\",\n \"1, 6\",\n \"8, 3\",\n \"3, 4\",\n \"5, 5\",\n \"8, 9\"]\n if os.path.exists('input_debug'):\n with open('input_debug', 'r') as f:\n lines = f.readlines()\nelse:\n N = 1000\n lines = []\n with open('input', 'r') as f:\n lines = f.readlines()\n\n\narea = []\nfor a in range(N):\n area.append([0] * N)\n\ndef print_area():\n for y in range(N):\n l = \"\"\n for x in range(N):\n z = area[y][x]\n if z == 0:\n l += \".\"\n elif z < 0:\n l += chr(-z + ord('A') - 1)\n else:\n l += chr(z + ord('a') - 1)\n print(l)\n\npoints_dict = {}\nnumber = 1\npoints = []\nfor line in lines:\n arr = line.strip().split(', ')\n p = Point(number, arr[0], arr[1])\n number += 1\n # print(p)\n points.append(p)\n points_dict[number] = p\n\n# print_area()\nfor y in range(N):\n for x in range(N):\n min_dist = None\n min_dist_i = None\n tie = False\n for p in points:\n if not min_dist or p.dist(x, y) <= min_dist:\n if p.dist(x, y) == min_dist:\n tie = True\n else:\n tie = False\n min_dist = p.dist(x, y)\n min_dist_p = p.number\n if not tie:\n area[y][x] = min_dist_p\nfor p in points:\n area[p.y][p.x] = -p.number\n\n# print_area()\n\ncount = collections.Counter([item for sublist in area for item in sublist])\nexclude = set()\nfor z in range(N):\n exclude.add(area[0][z])\n exclude.add(area[z][0])\n exclude.add(area[N-1][z])\n exclude.add(area[z][N-1])\n\nans = -1\nfor c in count:\n if c not in exclude:\n ans = max(ans, count[c])\nprint(ans+1)\n# print_area()\n","sub_path":"6/problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"410406508","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport numpy as np\n\nimport random\n\nfirst_HL = 128\n\n\ndef conv3x3(in_channels, out_channels, stride=1):\n \"\"\"3x3 kernel size with padding convolutional layer in ResNet BasicBlock.\"\"\"\n return nn.Conv2d(\n in_channels=in_channels,\n out_channels=out_channels,\n kernel_size=3,\n stride=stride,\n padding=1,\n bias=False)\n\n\nclass BasicBlock(nn.Module):\n \"\"\"Basic Block of ReseNet.\"\"\"\n\n def __init__(self, in_channels, out_channels, stride=1, downsample=None):\n \"\"\"Basic Block of ReseNet Builder.\"\"\"\n super(BasicBlock, self).__init__()\n\n # First conv3x3 layer\n self.conv1 = conv3x3(in_channels, out_channels, stride)\n\n # Batch Normalization\n self.bn1 = nn.BatchNorm2d(num_features=out_channels)\n\n # ReLU Activation Function\n self.relu = nn.ReLU(inplace=True)\n\n # Second conv3x3 layer\n self.conv2 = conv3x3(out_channels, out_channels)\n\n # Batch Normalization\n self.bn2 = nn.BatchNorm2d(num_features=out_channels)\n\n # downsample for `residual`\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n \"\"\"Forward Pass of Basic Block.\"\"\"\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n return out\n\nclass SpinalResNet(nn.Module):\n \"\"\"Residual Neural Network.\"\"\"\n\n def __init__(self, block, duplicates, num_classes=100):\n \"\"\"Residual Neural Network Builder.\"\"\"\n super(SpinalResNet, self).__init__()\n\n self.in_channels = 64\n self.conv1 = conv3x3(in_channels=3, out_channels=64)\n self.bn = nn.BatchNorm2d(num_features=64)\n self.relu = nn.ReLU(inplace=True)\n self.dropout = nn.Dropout2d(p=0.02)\n\n # block of Basic Blocks\n self.conv2_x = self._make_block(block, duplicates[0], out_channels=64, stride=2)\n self.conv3_x = self._make_block(block, duplicates[1], out_channels=128, stride=2)\n self.conv4_x = self._make_block(block, duplicates[2], out_channels=128, stride=2)\n\n self.maxpool = nn.MaxPool2d(kernel_size=4, stride=1)\n self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2)\n #self.fc_layer = nn.Linear(256, num_classes)\n \n self.fc1 = nn.Linear(128, first_HL) #changed from 16 to 8\n self.fc1_1 = nn.Linear(128 + first_HL, first_HL) #added\n self.fc1_2 = nn.Linear(128 + first_HL, first_HL) #added\n self.fc1_3 = nn.Linear(128 + first_HL, first_HL) #added\n \n self.fc_layer = nn.Linear(first_HL*4, num_classes)\n\n # initialize weights\n # self.apply(initialize_weights)\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n nn.init.kaiming_normal_(m.weight.data, mode='fan_out')\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n m.bias.data.zero_()\n\n def _make_block(self, block, duplicates, out_channels, stride=1):\n \"\"\"\n Create Block in ResNet.\n Args:\n block: BasicBlock\n duplicates: number of BasicBlock\n out_channels: out channels of the block\n Returns:\n nn.Sequential(*layers)\n \"\"\"\n downsample = None\n if (stride != 1) or (self.in_channels != out_channels):\n downsample = nn.Sequential(\n conv3x3(self.in_channels, out_channels, stride=stride),\n nn.BatchNorm2d(num_features=out_channels)\n )\n\n layers = []\n layers.append(\n block(self.in_channels, out_channels, stride, downsample))\n self.in_channels = out_channels\n for _ in range(1, duplicates):\n layers.append(block(out_channels, out_channels))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n \"\"\"Forward pass of ResNet.\"\"\"\n out = self.conv1(x)\n out = self.bn(out)\n out = self.relu(out)\n out = self.dropout(out)\n\n # Stacked Basic Blocks\n out = self.conv2_x(out)\n out = self.conv3_x(out)\n out = self.conv4_x(out)\n \n \n out1 = self.maxpool2(out)\n #print('out1',out1.shape)\n out2 = out1[:,:,0,0]\n #print('out2',out2.shape)\n out2 = out2.view(out2.size(0),-1)\n #print('out2',out2.shape)\n \n x1 = out1[:,:,0,0]\n x1 = self.relu(self.fc1(x1))\n x2= torch.cat([ out1[:,:,0,1], x1], dim=1)\n x2 = self.relu(self.fc1_1(x2))\n x3= torch.cat([ out1[:,:,1,0], x2], dim=1)\n x3 = self.relu(self.fc1_2(x3))\n x4= torch.cat([ out1[:,:,1,1], x3], dim=1)\n x4 = self.relu(self.fc1_3(x4))\n \n x = torch.cat([x1, x2], dim=1)\n x = torch.cat([x, x3], dim=1)\n out = torch.cat([x, x4], dim=1)\n \n out = self.fc_layer(out)\n\n return out\n\n\ndef SpinalResNet18(num_classes=10):\n return SpinalResNet(BasicBlock, [2,2,3], num_classes=num_classes)","sub_path":"model/spinalresnet.py","file_name":"spinalresnet.py","file_ext":"py","file_size_in_byte":5342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"290402975","text":"from functools import lru_cache\n\nfrom rectpack import newPacker, SORT_AREA\nfrom rectpack.guillotine import GuillotineBafSlas\n\nimport numpy as np\nimport pandas as pd\n\nfrom ifcb.data.stitching import InfilledImages\n\nclass Mosaic(object):\n def __init__(self, the_bin, shape=(720, 1280), bg_color=200):\n self.bin = the_bin\n self.shape = shape\n self.bg_color = bg_color\n self.ii = InfilledImages(self.bin)\n @lru_cache()\n def _shapes(self):\n hs, ws, ix = [], [], []\n for target_number in self.ii:\n h, w = self.ii.shape(target_number)\n hs.append(h)\n ws.append(w)\n ix.append(target_number)\n return zip(hs, ws, ix)\n @lru_cache()\n def pack(self):\n page_h, page_w = self.shape\n pages = [(page_h - 1, page_w - 1) for _ in range(20)]\n packer = newPacker(sort_algo=SORT_AREA, rotation=False, pack_algo=GuillotineBafSlas)\n for r in self._shapes():\n packer.add_rect(*r)\n for p in pages:\n packer.add_bin(*p)\n packer.pack()\n COLS = ['page', 'y', 'x', 'h', 'w', 'roi_number']\n return pd.DataFrame(packer.rect_list(), columns=COLS)\n def page(self, page=0):\n df = self.pack()\n page_h, page_w = self.shape\n page_image = np.zeros((page_h, page_w), dtype=np.uint8) + self.bg_color\n sdf = df[df.page == page]\n for index, row in sdf.iterrows():\n y, x = row.y, row.x\n h, w = row.h, row.w\n page_image[y:y+h, x:x+w] = self.ii[row.roi_number]\n return page_image","sub_path":"ifcb/viz/mosaic.py","file_name":"mosaic.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"430257631","text":"from flask import render_template, url_for,request, abort, jsonify\n\nfrom . import user_actions\nfrom ..auth_http import auth_api_handler\nfrom ..profile_actions import profile_actions\nfrom playhouse.shortcuts import model_to_dict\nfrom app.models.models import Users, UserProfiles,UserProfileWeapons, BalanceHistory, UserStats\nfrom app.utils.validators import validate_int_json_data, validate_string_json_data\nfrom app import db\n\n\n@user_actions.route('/admin/user/get-all', methods=['POST'])\n@auth_api_handler.login_required\ndef user_get_all_info():\n user_id = validate_int_json_data(argument_name='user_id')\n if Users.select().where(Users.id == user_id).exists():\n user = Users.get(Users.id == user_id)\n else:\n return jsonify({\n 'result': 'ERROR',\n 'reason': 'User with this user_id is not exist'\n })\n #TODO All info\n user_stats = UserStats.get_user_stats(user_id=user_id)\n profiles = UserProfiles.get_profile(user_id=user_id)\n balance_history = BalanceHistory.get_account_balance_history(id=user_id, search_by='user')\n data = {\n 'user': model_to_dict(user, exclude=[Users.password, Users.settings],),\n 'user_stats': model_to_dict(user_stats),\n 'profiles': profiles,\n 'balance_history': balance_history\n }\n\n return jsonify({\n 'user_data': data,\n 'result': 'OK'})\n\n\n\n\n@user_actions.route('/admin/user/stats', methods=['POST'])\n@auth_api_handler.login_required\ndef user_get_stats():\n user_id = validate_int_json_data(argument_name='user_id')\n stats = UserStats.get_user_stats(user_id=user_id)\n if stats:\n return jsonify({'result': 'OK',\n 'user_stats': model_to_dict(stats)})\n else:\n return jsonify({'result': 'ERROR',\n 'reason': 'User is not exist or have no stats registered'})\n\n\n\n@user_actions.route('/admin/user/search/by-numeric-data', methods = ['POST'])\n@auth_api_handler.login_required\ndef player_entity_search():\n users_data = {}\n entity_id = validate_int_json_data(argument_name='entity_id')\n\n q = Users.select().where( (Users.id == entity_id) | (Users.account == entity_id))\n if q.exists():\n users = q\n for user in users:\n users_data[str(user.id)] = model_to_dict(user, exclude=[Users.password,\n Users.settings])\n else:\n return jsonify({'reason': 'User is not exist',\n 'result': 'ERROR'})\n\n profiles_data = profile_actions._get_profile(profile_id=entity_id)\n entity_data = {'users': users_data,\n 'profile': model_to_dict(profiles_data, exclude=[UserProfiles.vip_end_dt])}\n\n\n\n return jsonify({'result': 'OK',\n 'entity_id':entity_data})\n\n@auth_api_handler.login_required\n@user_actions.route('/admin/user/update/nickname', methods=['POST'])\ndef update_user_nickname():\n user_id = validate_int_json_data(argument_name='user_id')\n new_nickname = validate_string_json_data(argument_name='new_nickname')\n updated_row = Users.update(nickname=new_nickname).where(Users.id == user_id).execute()\n if updated_row > 0:\n return jsonify({'result': 'OK'})\n else:\n return jsonify({'result': 'ERROR',\n 'reason': 'nickname was not updated, something went wrong'})\n\n\n\n@auth_api_handler.login_required\n@user_actions.route('/admin/user/payments', methods=['POST'])\ndef get_user_payments():\n platform = 'android'\n\n user_id = validate_int_json_data(argument_name='user_id')\n if request.method == 'POST':\n\n platform = validate_string_json_data(argument_name='platform')\n\n #TODO add handlers in model\n data = BalanceHistory.get_payments_history(user_id=user_id, platform=platform)\n return jsonify({\n 'result': 'OK',\n 'data': data\n })\n\n\n@auth_api_handler.login_required\n@user_actions.route('/admin/user/kick', methods=['POST'])\ndef user_kick():\n user_id = validate_int_json_data(argument_name='user_id')\n pass\n #TODO need to dedicate token\n\n\n\n\n\n\n\n\n\n\n","sub_path":"app/blueprint/user_actions/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"591217667","text":"from flask import jsonify, request, abort\nfrom flasgger import swag_from\n\nfrom net_inventory.backend import api as blueprint\nfrom net_inventory.backend.models import Device, DeviceSchema\nfrom net_inventory.shared.utils import get_parent_root\nfrom net_inventory.shared.database import db\n\nswag_dir = get_parent_root(__file__) + \"/spec/\"\n\ndevices_schema = DeviceSchema(many=True)\n\n\n@blueprint.route(\"/inventory/devices\", methods=[\"GET\"])\n@swag_from(swag_dir + \"get_devices.yml\")\ndef get_devices():\n \"\"\"\n Update a list of devices\n\n Returns:\n JSON object\n \"\"\"\n devices = Device.query.all()\n return jsonify(data=devices_schema.dump(devices)[0]), 200\n\n\n@blueprint.route(\"/inventory/devices/\", methods=[\"GET\"])\n@swag_from(swag_dir + \"get_device.yml\")\ndef get_device(hostname):\n \"\"\"\n Get a single device's information\n\n Path Parameters:\n hostname (str): hostname\n Returns:\n JSON object\n \"\"\"\n device = Device.query.get_or_404(hostname)\n data, errors = DeviceSchema().dump(device)\n return jsonify(data=data, errors=errors), 200\n\n\n@blueprint.route(\"/inventory/devices\", methods=[\"POST\"])\n@swag_from(swag_dir + \"create_device.yml\")\ndef create_device():\n \"\"\"\n Get a single device's information\n\n Body Parameters:\n hostname (str): hostname\n Returns:\n JSON object\n \"\"\"\n DeviceSchema().load(request.json)\n\n device = Device(**request.json)\n db.session.add(device)\n db.session.commit()\n data, errors = DeviceSchema().dump(device)\n return jsonify(data=data, errors=errors), 201\n\n\n@blueprint.route(\"/inventory/devices/\", methods=[\"PATCH\"])\n@swag_from(swag_dir + \"update_device.yml\")\ndef update_device(hostname):\n \"\"\"\n Get a single device's information\n\n Path Parameters:\n hostname (str): hostname\n Returns:\n JSON object\n \"\"\"\n device = db.session.query(Device).filter(Device.hostname == hostname).first()\n if not device:\n abort(404, {\"message\": \"{} not found\".format(hostname)})\n for k, v in request.json.items():\n setattr(device, k, v)\n db.session.commit()\n data, errors = DeviceSchema().dump(device)\n return jsonify(data=data, errors=errors), 200\n\n\n@blueprint.route(\"/inventory/devices/\", methods=[\"DELETE\"])\n@swag_from(swag_dir + \"delete_device.yml\")\ndef delete_device(hostname):\n \"\"\"\n Get a single device's information\n\n Path Parameters:\n hostname (str): hostname\n Returns:\n JSON object\n \"\"\"\n device = db.session.query(Device).filter(Device.hostname == hostname).first()\n if not device:\n abort(404, {\"message\": \"{} not found\".format(hostname)})\n db.session.delete(device)\n db.session.commit()\n return jsonify(), 200\n","sub_path":"labs/.dev/lab26/.dev/explore-kubernetes-pipeline/net_inventory/net_inventory/backend/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"118631253","text":"import logging\nimport os\nimport subprocess\nimport shutil\nimport tempfile\n\nfrom dateutil import parser\n\nfrom .. import DEFAULTS\nfrom ..utils import ensure_dependencies, devel_dir\nfrom ..exceptions import AletheiaException\n\nlogger = logging.getLogger(__name__)\nensure_dependencies(('git', '2.3.0'))\n\n\nclass Source:\n def __init__(self, config=DEFAULTS, hostname='github.com', repo='', branch='master', **kwargs):\n self.hostname = hostname\n self.repo = repo\n self.branch = branch\n self.config = config\n self._tempdir = None\n \n def cleanup(self):\n if self._tempdir:\n try:\n shutil.rmtree(self._tempdir)\n except: # noqa: E722\n logger.error('Error cleaning up Git plugin.')\n \n @property\n def working_dir(self):\n if not self._tempdir:\n if self.config.devel:\n self._tempdir = devel_dir(f'git--{self.hostname}--{self.repo}--{self.branch}')\n else:\n self._tempdir = tempfile.mkdtemp()\n return self._tempdir\n \n def run(self):\n logger.info(f'Cloning git repo {self.repo}.')\n if self.config.devel and os.path.exists(os.path.join(self.working_dir, '.git')):\n result = subprocess.run(['git', 'reset', '--hard'],\n # env=dict(GIT_TERMINAL_PROMPT='0'),\n cwd=self.working_dir)\n result = subprocess.run(['git', 'pull', '--rebase', 'origin'],\n # env=dict(GIT_TERMINAL_PROMPT='0'),\n cwd=self.working_dir)\n else:\n result = subprocess.run(['git', 'clone', f'https://{self.hostname}/{self.repo}', '-b', self.branch, '.'],\n # env=dict(GIT_TERMINAL_PROMPT='0'),\n cwd=self.working_dir)\n if not result.returncode == 0:\n logger.error(f'Failed to clone repository - git exited with {result.returncode}')\n raise AletheiaException('Error retrieving source.')\n \n # A git clone will set the modtime of every file to the time the clone was made. We need to set them\n # to the time that the last commit occurred.\n result = subprocess.run(['git', 'log', '-1', '--format=%cd'], cwd=self.working_dir, stdout=subprocess.PIPE)\n if not result.returncode == 0:\n logger.error(f'Failed to obtain last commit timestamp - git exited with {result.returncode}')\n last_commit_timestring = result.stdout\n last_commit_dt = parser.parse(last_commit_timestring)\n last_commit_timestamp = last_commit_dt.timestamp()\n for root, dirs, files in os.walk(self.working_dir):\n for filename in files:\n os.utime(os.path.join(root, filename), (last_commit_timestamp, last_commit_timestamp))\n return self.working_dir\n \n\n\n\n","sub_path":"aletheia/sources/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":2943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"159562044","text":"bl_info = {\n \"name\": \"DazToBlender\",\n \"author\": \"Daz 3D | https://www.daz3d.com\",\n \"version\": (2, 3, 9),\n \"blender\": (2, 80, 0),\n \"location\": \"3DView > ToolShelf\",\n \"description\": \"Daz 3D Genesis 3/8 transfer to Blender\",\n \"warning\": \"\",\n \"support\": \"COMMUNITY\",\n \"wiki_url\": \"\",\n \"tracker_url\": \"https://github.com/daz3d/DazToBlender/issues\",\n \"category\": \"Armature\"\n}\n\nimport sys\nimport os\nimport math\nsys.path.append(os.path.dirname(__file__))\nimport bpy\nimport mathutils\nfrom copy import deepcopy\nfrom . import DazRigBlend\nfrom . import DtbShapeKeys\nfrom . import DataBase\nfrom . import ToRigify\nfrom . import Global\nfrom . import Versions\nfrom . import DtbDazMorph\nfrom . import DtbOperators\nfrom . import DtbPanels\nfrom . import DtbMaterial\nfrom . import CustomBones\nfrom . import Poses\nfrom . import Animations\nfrom . import Util\nfrom . import DtbCommands\nfrom . import DtbIKBones\nfrom bpy.props import EnumProperty\nfrom bpy.props import BoolProperty\nfrom bpy.props import StringProperty\nfrom bpy.app.handlers import persistent\nimport threading\nimport time\nskinkeys = [\n 'Base Color.Hue',\n 'Base Color.Saturation',\n 'Base Color.Value',\n 'Base Color.Bright',\n 'Base Color.Contrast',\n 'Specular',\n 'Roughness',\n 'Roughness.Contrast',\n 'Specular.Contrast',\n 'Subsurface.Scale',\n 'Normal.Strength',\n 'Bump.Strength',\n 'Bump.Distance',\n 'Displacement.Height',\n]\neyekeys=[\n 'Base Color.Hue',\n 'Base Color.Saturation',\n 'Base Color.Value',\n 'Base Color.Bright',\n 'Base Color.Contrast',\n 'Normal.Strength',\n 'Bump.Strength',\n 'Bump.Distance',\n]\n\nregion = 'UI'\nBV = Versions.getBV()\n\n\n\nclass MATERIAL_OT_up(bpy.types.Operator):\n bl_idname = \"material.up\"\n bl_label = \"UP\"\n def execute(self, context):\n adjust_material(context,False)\n return {'FINISHED'}\n\ndef adjust_material(context,is_ms):\n w_mgr = context.window_manager\n Util.active_object_to_current_collection()\n\n if w_mgr.is_eye:\n arg = eyekeys[int(w_mgr.eye_prop)-1]\n else:\n arg = skinkeys[int(w_mgr.skin_prop)-1]\n val = 0.1\n if is_ms:\n val = -0.1\n if ('Hue' in arg) or ('Displacement' in arg):\n val = val / 10\n if w_mgr.ftime_prop:\n val = val * 4\n # if ('Normal' in arg) or ('Bump' in arg) or ('Displacement' in arg):\n # val = val * 0.01 * Global.getSize()\n if arg != '':\n DtbMaterial.adjust_material(arg, val, w_mgr.is_eye)\n\nclass MATERIAL_OT_down(bpy.types.Operator):\n bl_idname = \"material.down\"\n bl_label = \"DOWN\"\n def execute(self, context):\n adjust_material(context, True)\n return {'FINISHED'}\n\n\nclass DEFAULT_OT_material(bpy.types.Operator):\n bl_idname = \"df.material\"\n bl_label = 'RESET MATERIAL'\n def execute(self, context):\n Util.active_object_to_current_collection()\n default_material(context)\n return {'FINISHED'}\n\n\ndef default_material(context):\n w_mgr = context.window_manager\n if w_mgr.is_eye:\n #DtbShaders.toEyeDryDefault(bpy.data.node_groups.get(DtbShaders.getGroupNode(DtbShaders.EDRY)))\n DtbMaterial.getGroupNodeTree(\"EyeDry\")\n DtbMaterial.getGroupNodeTree(\"EyeWet\")\n else:\n DtbMaterial.getGroupNodeTree(\"IrayUberSkin\")\n\nclass MATCH_OT_ikfk(bpy.types.Operator):\n bl_idname = 'match.ikfk'\n bl_label = 'Match IK & FK'\n\n def execute(self, context):\n b2 = ['upper_arm_parent', 'thigh_parent']\n lr = ['.R', '.L']\n trf = ToRigify.ToRigify()\n influence4 = []\n for i in range(2):\n for j in range(2):\n influence4.append(Global.getRgfy().pose.bones[b2[i] + lr[j]]['IK_FK'])\n trf.match_ikfk(influence4)\n return {'FINISHED'}\n\n\n\nclass SCULPT_OT_push(bpy.types.Operator):\n bl_idname = 'to.sculpt'\n bl_label = 'To Sculpt'\n def execute(self, context):\n Util.active_object_to_current_collection()\n w_mgr = bpy.context.window_manager\n ddm = DtbDazMorph.DtbDazMorph()\n if Versions.get_active_object().mode=='SCULPT':\n w_mgr.new_morph = False\n Global.setOpsMode('EDIT')\n ddm.select_to_daz_morph(False)\n elif Versions.get_active_object().mode=='OBJECT':\n Global.setOpsMode(\"SCULPT\")\n ddm.select_to_daz_morph(w_mgr.new_morph)\n elif Versions.get_active_object().mode=='EDIT':\n w_mgr.new_morph = False\n Global.setOpsMode('OBJECT')\n return {'FINISHED'}\n\nclass EXP_OT_morph(bpy.types.Operator):\n bl_idname = 'exsport.morph'\n bl_label = 'To Daz Morph'\n\n def execute(self,context):\n is_body = context.active_object==Global.getBody()\n global obj_exsported\n ddm = DtbDazMorph.DtbDazMorph()\n ddm.before_execute(is_body)\n flg_ok = ddm.top_exsport()\n if flg_ok==False:\n self.report({\"ERROR\"}, \"There is no suitable shape key\")\n return {'FINISHED'}\n\nclass FK2IK_OT_button(bpy.types.Operator):\n bl_idname = \"my.fktoik\"\n bl_label = \"IK\"\n\n def execute(self, context):\n Global.find_AMTR(context.object)\n Global.find_RGFY(context.object)\n if Global.get_Rgfy_name() != \"\":\n rgfy = ToRigify.ToRigify()\n rgfy.ik2fk(-1)\n else:\n DtbIKBones.bone_disp(-1, False)\n DtbIKBones.mute_bones.append('NG')\n for i in range(len(DtbIKBones.bone_name)):\n DtbIKBones.fktoik(i)\n DtbIKBones.adjust_shin_y(i, True)\n DtbIKBones.mute_bones = []\n return {'FINISHED'}\n\n\nclass IK2FK_OT_button(bpy.types.Operator):\n bl_idname = \"my.iktofk\"\n bl_label = \"FK\"\n\n def execute(self, context):\n Global.find_AMTR(context.object)\n Global.find_RGFY(context.object)\n if Global.get_Rgfy_name() != \"\":\n rgfy = ToRigify.ToRigify()\n rgfy.fk2ik(-1)\n else:\n DtbIKBones.bone_disp(-1, True)\n DtbIKBones.mute_bones.append('NG')\n for i in range(len(DtbIKBones.bone_name)):\n DtbIKBones.iktofk(i)\n DtbIKBones.adjust_shin_y(i, False)\n DtbIKBones.mute_bones = []\n return {'FINISHED'}\n\n\nclass LIMB_OT_redraw(bpy.types.Operator):\n bl_idname = \"limb.redraw\"\n bl_label = \"ReDisplay Subtle FK/IK\"\n\n def execute(self, context):\n if Global.getAmtr() is None:\n return\n w_mgr = bpy.context.window_manager\n for i in range(4):\n ik_value = DtbIKBones.get_ik_influence(DtbIKBones.get_influece_data_path(DtbIKBones.bone_name[i]))\n flg_ik = ik_value >= 0.5\n DtbIKBones.bone_disp(i, flg_ik == False)\n if i == 0:\n if w_mgr.ifk0 != flg_ik:\n w_mgr.ifk0 = flg_ik\n elif i == 1:\n if w_mgr.ifk1 != flg_ik:\n w_mgr.ifk1 = flg_ik\n elif i == 2:\n if w_mgr.ifk2 != flg_ik:\n w_mgr.ifk2 = flg_ik\n c = Global.getAmtrConstraint('rFoot', 'Copy Rotation')\n if c is not None and c.influence != ik_value:\n c.influence = ik_value\n elif i == 3:\n if w_mgr.ifk3 != flg_ik:\n w_mgr.ifk3 = flg_ik\n c = Global.getAmtrConstraint('lFoot', 'Copy Rotation')\n if c is not None and c.influence != ik_value:\n c.influence = ik_value\n return {'FINISHED'}\n\ndef init_props():\n w_mgr = bpy.types.WindowManager\n w_mgr.skin_prop = EnumProperty(\n name=\"skin\",\n description=\"Skin Adjust\",\n items = [\n ('1', 'Base Color.Hue','1'),\n ('2', 'Base Color.Saturation','2'),\n ('3', 'Base Color.Value','3'),\n ('4', 'Base Color.Bright','4'),\n ('5', 'Base Color.Contrast','5'),\n ('6', 'Specular','6'),\n ('7', 'Roughness','7'),\n ('8', 'Roughness.Contrast','8'),\n ('9', 'Specular.Contrast','9'),\n ('10', 'Subsurface.Scale','10'),\n ('11', 'Normal.Strength','11'),\n ('12', 'Bump.Strength','12'),\n ('13', 'Bump.Distance','13'),\n ('14', 'Displacement.Height','14'),\n ],\n default = '1',\n )\n w_mgr.eye_prop = EnumProperty(\n name=\"skin\",\n description=\"Eyes Adjust\",\n items=[\n ('1', 'Base Color.Hue','1'),\n ('2', 'Base Color.Saturation','2'),\n ('3', 'Base Color.Value','3'),\n ('4', 'Base Color.Bright', '4'),\n ('5', 'Base Color.Contrast', '5'),\n ('6', 'Normal.Strength', '6'),\n ('7', 'Bump.Strength', '7'),\n ('8', 'Bump.Distance', '8'),\n ],\n default='1',\n )\n w_mgr.search_prop = StringProperty(\n name=\"\",\n default=\"\",\n description=\"Search_shape_keys\",\n update= DtbCommands.search_morph_\n )\n w_mgr.is_eye = BoolProperty(name=\"eyes\")\n w_mgr.ftime_prop = BoolProperty(name=\"ftime\")\n w_mgr.br_onoff_prop = BoolProperty(name=\"br_onoff\", default=True, update=DtbIKBones.bonerange_onoff)\n w_mgr.ifk0 = BoolProperty(name=\"ifk0\", default=False, update=DtbIKBones.ifk_update0)\n w_mgr.ifk1 = BoolProperty(name=\"ifk1\", default=False, update=DtbIKBones.ifk_update1)\n w_mgr.ifk2 = BoolProperty(name=\"ifk2\", default=False, update=DtbIKBones.ifk_update2)\n w_mgr.ifk3 = BoolProperty(name=\"fik3\", default=False, update=DtbIKBones.ifk_update3)\n w_mgr.new_morph = BoolProperty(name=\"_new_morph\",default=False)\n w_mgr.skip_isk = BoolProperty(name = \"_skip_isk\",default = False)\n w_mgr.update_scn_settings = BoolProperty(name=\"update_viewport\", description =\"Updates the Render Engine, Shading Type, and Using Depth Under Mouse\", default=True)\n w_mgr.update_viewport = BoolProperty(name=\"update_viewport\", description =\"Updates the Viewport, and Camera for your Scale\", default=True)\n w_mgr.morph_prefix = BoolProperty(name=\"morph_prefix\", default=True)\n w_mgr.combine_materials = BoolProperty(name=\"combine_materials\", default=True)\n w_mgr.add_pose_lib = BoolProperty(name=\"add_pose_lib\", default=True)\n figure_items = [(\"null\" , \"Choose Character\", \"Select which figure you wish to import\")]\n w_mgr.choose_daz_figure = EnumProperty(\n name = \"Highlight for Collection\",\n description = \"Choose any figure in your scene to which you wish to add a pose.\",\n items = figure_items,\n default = \"null\"\n )\n w_mgr.scene_scale = EnumProperty(\n name = \"Scene Scale\",\n description = \"Used to change scale of imported object and scale settings\",\n items = [\n ('0.01', 'Real Scale (Centimeters)', 'Daz Scale'),\n ('0.1', 'x10', '10 x Daz Scale'),\n ('1', 'x100 (Meters)', '100 x Daz Scale')\n ],\n default = '0.01'\n )\n w_mgr.search_morph_list = StringProperty(\n name=\"\",\n default=\"Type Keyword Here\",\n description=\"Search_shape_keys\",\n )\n\n\n\nclasses = (\n DtbPanels.DTB_PT_MAIN,\n DtbPanels.DTB_PT_RIGGING,\n DtbPanels.DTB_PT_POSE,\n DtbPanels.DTB_PT_MORPHS,\n DtbPanels.DTB_PT_GENERAL,\n DtbPanels.DTB_PT_COMMANDS,\n DtbPanels.DTB_PT_UTILITIES,\n DtbPanels.DTB_PT_MORE_INFO,\n DtbOperators.IMP_OT_POSE,\n DtbOperators.IMP_OT_FBX,\n DtbOperators.IMP_OT_ENV,\n DtbOperators.CLEAR_OT_Pose,\n DtbOperators.REFRESH_DAZ_FIGURES,\n DtbOperators.RENAME_MORPHS,\n DtbOperators.REMOVE_DAZ_OT_button,\n DtbOperators.OPTIMIZE_OT_material,\n DtbOperators.RELOAD_SHAPE_KEY_CUSTOM_PROPS,\n DtbCommands.SEARCH_OT_Commands,\n IK2FK_OT_button,\n FK2IK_OT_button,\n MATERIAL_OT_up,\n MATERIAL_OT_down,\n DEFAULT_OT_material,\n DtbOperators.TRANS_OT_Rigify,\n MATCH_OT_ikfk,\n LIMB_OT_redraw,\n EXP_OT_morph,\n SCULPT_OT_push,\n \n)\n\n# Converts difference to a 0 to 1 range \n# TO DO: Convert to Follow the rate similiar to Daz Studio\ndef erc_keyed(var, min, max, normalized_dist, dist):\n if dist < 0:\n if max <= var <= min:\n return abs((var - min)/dist)\n elif max >= var:\n return 1\n else:\n return 0\n if min <= var <= max:\n return abs((var - min * normalized_dist) /dist)\n elif max <= var:\n return 1\n else:\n return 0\n\n@persistent\ndef load_handler(dummy):\n dns = bpy.app.driver_namespace\n # register your drivers\n dns[\"erc_keyed\"] = erc_keyed\n\n\ndef register():\n load_handler(None)\n bpy.app.handlers.load_post.append(load_handler)\n for cls in classes:\n bpy.utils.register_class(cls)\n init_props()\n \ndef unregister():\n for cls in classes:\n bpy.utils.unregister_class(cls)\n\nif __name__==\"__main__\":\n register()\n","sub_path":"Blender/appdata_common/Blender Foundation/Blender/BLENDER_VERSION/scripts/addons/DTB/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"26295997","text":"import heapq\nfrom itertools import combinations\nfrom collections import deque\n\nclass AStar:\n def __init__(self):\n self.fluents = list()\n self.operators = list()\n self.initialState = list()\n self.goalState = list()\n self.stateCosts = list()\n \n # Metodo di inizializzazione degli attributi e codifica dei fluent\n def init(self, formulation: list):\n # Salvo la formulazione in variabili singole\n self.fluents = formulation[0]\n self.operators = formulation[1]\n self.initialState = formulation[2]\n self.goalState = formulation[3]\n \n # Metodo che implementa la visita in ampiezza\n def bfsVisit(self, adjList: list, goalID: int, marked: list, d: list):\n q = deque()\n marked[goalID] = 1\n q.append(goalID)\n while len(q) > 0:\n u = q.popleft()\n reachable = adjList[u]\n for v in reachable:\n if v is not None and marked[v] == 0:\n marked[v] = 1\n q.append(v)\n d[v] = d[u] + 1\n marked[u] = 2\n \n # Metodo che inizializza la visita in ampiezza\n def bfs(self, adjList: list, goalID: int, d: list):\n # Inizializzo il vettore degli stati visitati\n marked = [0 for i in range(len(d))] # 0:da visitare, 1:entrato, 2:completato\n # Inizio la bfs a partire dallo stato finale\n self.bfsVisit(adjList, goalID, marked, d)\n \n # Metodo che calcola le distanze di ogni stato dallo stato finale\n def computeDistances(self, states: list, adjList: list):\n # Uso la visita per ampiezza (bfs) per calcolare tutte le distanze dal goal state\n # Suppongo quindi che ogni operazione abbia lo stesso costo\n # Devo individuare qual è l'id numerico dello stato finale\n goalID = -1\n for i in range(len(states)):\n if set(self.goalState) == set(states[i]):\n goalID = i\n break\n # Inizializzo il vettore delle distanze dallo stato finale\n infinite = 30*len(states)\n distances = [infinite for i in range(len(states))]\n # Lo stato finale è distante 0 da se stesso\n distances[goalID] = 0\n # Trovo la \"trasposta\" della lista delle adiacenze\n transposedAdjList = [list() for i in range(len(states))]\n for i in range(len(adjList)):\n for j in adjList[i]:\n transposedAdjList[j].append(i)\n # Inizio la bfs\n self.bfs(transposedAdjList, goalID, distances)\n # Mappo ogni stato col suo costo, nella forma [lista di fluent, costo]\n for i in range(len(states)):\n self.stateCosts.append([states[i], distances[i]])\n \n # Metodo che controlla se tutti i fluents di una lista sono contenuti in un'altra lista\n def matchTest(self, fluentList1: list, fluentList2: list):\n result = True\n for fluent in fluentList1:\n if fluent not in fluentList2:\n result = False\n break\n return result\n \n # Metodo che costruisce il grafo degli stati possibili\n def buildGraph(self):\n # Calcolo tutte le possibili combinazioni di fluent, prendendoli in insiemi da 0 a n elementi (n=numero di fluent)\n states = list()\n for i in range(len(self.fluents)+1):\n combs = combinations(self.fluents, i)\n for item in combs:\n states.append(list(item))\n print(\"Building the graph...\")\n # Inizializzo la lista delle adiacenze\n adjList = [list() for i in range(len(states))]\n # Itero su tutte le coppie di stati possibili e vedo se è possibile raggiungere uno dall'altro\n # E' possibile solo se esiste un operatore che soddisfa i prerequisiti di uno e si ottiene l'altro applicando effects e deletes\n for i in range(len(states)-1):\n for j in range(i+1,len(states)):\n first = list(states[i]); second = list(states[j]) # memorizzo i fluent dei due stati\n # Itero sugli operatori\n for op in self.operators:\n # Controllo se l'operatore è applicabile al primo\n if self.matchTest(op.preconditions, first):\n fluents = list(first)\n # Calcolo cosa si ottiene applicando effects e deletes\n for e in op.effects:\n fluents.append(e)\n for d in op.deletes:\n try:\n fluents.remove(d)\n except:\n pass\n # Se la modifica di first genera second allora sono connessi\n if set(fluents) == set(second):\n adjList[i].append(j)\n # Controllo anche se è vero il contrario, ovvero se l'operatore è applicabile al secondo\n if self.matchTest(op.preconditions, second):\n fluents = list(second)\n # Calcolo cosa si ottiene applicando effects e deletes\n for e in op.effects:\n fluents.append(e)\n for d in op.deletes:\n try:\n fluents.remove(d)\n except:\n pass\n # Se la modifica di second genera first allora sono connessi\n if set(fluents) == set(first):\n adjList[j].append(i)\n print(\"Computing heuristic function...\")\n self.computeDistances(states, adjList)\n \n # Funzione che restituisce la funzione euristica di uno stato, dato come lista dei fluent di cui è composto\n def heuristic(self, fluents: list):\n result = 0\n # Cerco questa lista di fluent all'interno della lista di stati conosciuti\n for state in self.stateCosts:\n if set(state[0]) == set(fluents):\n result = int(state[1])\n break\n return result\n \n # Metodo che trova tutti gli stati raggiungibili a partire dallo stato attuale\n def expand(self, node, pathLength):\n # Lista che contiene tutti gli stati successivi generati\n nextStates = list()\n # Itero sugli operatori del problema\n for op in self.operators:\n # Controllo se l'operatore è applicabile, ovvero se lo stato soddisfa tutte le preconditions\n if self.matchTest(op.preconditions, node.fluents):\n # Se è vero, costruisco un nuovo nodo i cui fluent sono modificati da op.effects e op.deletes\n childFluents = list(node.fluents)\n for fluent in op.effects:\n childFluents.append(fluent)\n for fluent in op.deletes:\n try:\n childFluents.remove(fluent)\n except:\n print(\"WARNING: %s not in current state %s for operator %s\\n\" % (fluent, node.fluents, op.action))\n # La funzione di valutazione è data dalla somma tra il costo del percorso e la funzione euristica\n newNode = self.NodeState(childFluents, node, op.action, pathLength + self.heuristic(childFluents))\n # Aggiungo il nuovo nodo alla lista dei figli\n nextStates.append(newNode)\n # Ritorno la lista di nodi figli\n return nextStates\n \n # Metodo che costruisce la lista di operazioni eseguite\n def buildPath(self, node):\n path = list()\n while node is not None:\n path.append(node.operator)\n node = node.previous\n sequence = [path[i] for i in range(len(path)-1, -1, -1) if path[i] is not None]\n return sequence\n \n # Metodo che implementa l'algoritmo A*\n def astar(self):\n pathLength = 0\n # Inizializzo con lo stato iniziale\n fringe = self.PriorityQueue()\n fringe.put(self.NodeState(self.initialState, None, None, 0))\n # Algoritmo:\n while True:\n # Se la frontiera è vuota non si può andare in nessun altro nodo: fallimento\n if fringe.empty():\n return False\n # Altrimenti, estraggo il nodo più prioritario dalla frontiera\n node = fringe.get()\n # Se ho raggiunto lo stato finale ho finito\n if self.matchTest(self.goalState, node.fluents):\n return self.buildPath(node)\n # Altrimenti, espando il nodo attuale trovando tutti gli stati figli possibili\n pathLength += 1\n nextStates = self.expand(node, pathLength)\n # Aggiungo gli stati figli alla frontiera\n for state in nextStates:\n fringe.put(state)\n \n # Metodo generale che chiama tutti gli altri per la soluzione del problema\n def solve(self, formulation):\n self.init(formulation)\n self.buildGraph()\n print(\"Finding a solution...\")\n return self.astar()\n \n # Classe che implementa una coda a priorità\n class PriorityQueue:\n def __init__(self):\n self.elements = list()\n \n def empty(self):\n return len(self.elements) == 0\n \n def put(self, item):\n heapq.heappush(self.elements, item)\n \n def get(self):\n return heapq.heappop(self.elements)\n \n # Struttura dati che rappresenta uno stato per l'algoritmo A*\n class NodeState:\n def __init__(self, fluents, prev, op, prio):\n self.fluents = fluents\n self.previous = prev\n self.priority = prio\n self.operator = op\n \n # Ridefinisco l'operatore di confronto (per libreria heapq)\n def __lt__(self, other):\n return self.priority < other.priority","sub_path":"AStar.py","file_name":"AStar.py","file_ext":"py","file_size_in_byte":10050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"647796016","text":"## Decision trees algorithm to predict Kickstarter project success\n\n# get our custom classes/functions\nfrom dtnode import Node\nfrom dtnode_storage import NodeStorage\n# regular imports\nfrom math import pow\nfrom typing import List, Tuple\n\nclass DecisionTree:\n root_node = None\n # parameters for stopping split recursion\n max_depth, min_node_size = None, None\n # don't let a variable be used more than once for a decision.\n # list of ints (indices of variables).\n allowed_vars = None\n # keep track of types of variables to speed up for booleans.\n # 1=numeric, 2=bool 0 or 1)\n var_types = None\n\n def __init__(self, root_node:Node=None, data:List=None, max_depth:int=None, min_node_size:int=None, var_types:List[int]=None):\n # check why we're making the tree object\n if root_node is not None:\n # initialize a tree object with an already filled out root node to use predict()\n self.root_node = root_node\n elif data is not None and max_depth is not None and min_node_size is not None and var_types is not None:\n # initialize tree to create it in the first place\n self.root_node = Node(data=data)\n self.cur_node_id = 1\n self.allowed_vars = [*range(len(data[0])-1)]\n # TODO to not consider the categories, make this [*range(len(data[0])-16)]\n print(self.allowed_vars)\n self.max_depth = max_depth\n self.min_node_size = min_node_size\n self.var_types = var_types\n else:\n print(\"Missing required params to init DecisionTree.\")\n\n # we will be using gini index for the cost function.\n def get_gini(self, partition:List[Node]) -> float:\n #print(\"get_gini called\")\n # we will always have two child nodes to compare\n tot_rows = float(len(partition[0].data) + len(partition[1].data))\n gini = 0.0\n # check each child node's uniformity\n for node in partition:\n num_rows = float(len(node.data))\n # prevent div by 0 error\n if num_rows == 0:\n continue\n # count number of failed & success in this node\n num_fail, num_succ = 0.0, 0.0\n for row in node.data:\n if int(row[-1]) == 1:\n num_succ += 1.0\n else:\n num_fail += 1.0\n # we can compute the proportion of each\n prop_succ = num_succ / num_rows\n prop_fail = num_fail / num_rows\n # the gini index for this node is then\n node_gini = 1.0 - (prop_succ**2 + prop_fail**2)\n # we then weight by the size of the node relative to the parent\n gini += node_gini * num_rows / tot_rows\n return gini\n\n # split the dataset and compare gini values of all splits.\n def split_group(self, parent:Node, var_to_split:int, threshold:float) -> Tuple[Node, Node]:\n #print(\"split_group called with \" + str(var_to_split) + \" <= \" + str(threshold))\n # define children\n c1 = Node(data=[],depth=parent.depth+1)\n c2 = Node(data=[],depth=parent.depth+1)\n # assign data to the children accordingly\n for row in parent.data:\n if float(row[var_to_split]) <= threshold:\n c1.data.append(row)\n else:\n c2.data.append(row)\n return c1, c2\n \n # check the gini of all possible splits to find the best one\n def find_best_split(self, parent:Node, used_vars:List[int]) -> Node:\n print(\"find_best_split called\")\n # need to iterate through all rows with each variable as threshold\n best_gini, split_var, split_thresh, children = 100, None, None, [None, None]\n # check all vars except the label (last column)\n for var_index in self.allowed_vars:\n if var_index in used_vars:\n continue\n # check var type\n if self.var_types[var_index] == 1: #numeric\n for row in parent.data:\n # make a split\n c1, c2 = self.split_group(parent, int(var_index), float(row[var_index]))\n # evaluate this split\n gini = self.get_gini(partition=[c1,c2])\n # if this is the new best, update our info\n if gini < best_gini:\n print(\"found new best gini,\"+ str(gini) +\", with var \" + str(var_index))\n best_gini = gini\n split_var, split_thresh = var_index, row[var_index]\n del children[0:1]\n children = [c1, c2]\n else: # free up space\n del c1, c2\n else: # self.var_types[var_index] == 2: #boolean\n # there is only one split possible, so just do it and get the gini.\n # split data into var == 0 and var == 1.\n c1, c2 = self.split_group(parent, var_index, 0.5)\n # get the gini\n gini = self.get_gini(partition=[c1,c2])\n # if this is the new best, update our info\n if gini < best_gini:\n print(\"found new best gini,\"+ str(gini) +\", with var \" + str(var_index))\n best_gini = gini\n split_var, split_thresh = var_index, 0.5\n del children[0:1]\n children = [c1, c2]\n else: # free up space\n del c1, c2\n # now that we know the best split, do it!\n parent.set_thresh(var=split_var,thresh=split_thresh,var_type=self.var_types[split_var])\n parent.set_children(children[0], children[1])\n # remove the chosen variable from future consideration\n #used_vars.append(var_index)\n return parent, used_vars+[split_var]\n \n def split(self, node:Node, used_vars:List[int]=None) -> Node:\n print(\"split called\")\n # if we have reached max recursion depth, stop. \n # if the node is almost entirely one label, stop.\n # prevents overfitting.\n if node.depth >= self.max_depth: #or node.purity < 0.05:\n node.set_terminal()\n return node\n # if used_vars is not provided, initialize it empty\n if used_vars is None:\n used_vars = []\n # first do the best split for this node\n node, new_used_vars = self.find_best_split(parent=node, used_vars=used_vars)\n print(\"have now used \" + str(new_used_vars))\n # if either child is smaller than our min acceptable size, stop. prevents overfitting.\n # first check child 1.\n if len(node.c1.data) < self.min_node_size: #node.c1 is None or \n node.c1.set_terminal()\n else:\n # we aren't done yet. recurse into the child node.\n node.c1 = self.split(node.c1, used_vars=new_used_vars)\n # check child 2.\n if len(node.c2.data) < self.min_node_size: #node.c2 is None or \n node.c2.set_terminal()\n else:\n # recurse into the child node.\n node.c2 = self.split(node.c2, used_vars=new_used_vars)\n # when recursion has concluded, return the node\n return node\n\n\n # test our trained tree with an example row.\n # will return 0 (failed) or 1 (successful)\n def predict(self, root_node: Node, example: List[float]) -> int:\n return root_node.get_decision(example)\n\n # test our trained tree with an example list of rows.\n # will return predictions as list of 0s and 1s\n def predict_list(self, examples:List, root_node:Node=None) -> List[int]:\n if root_node is None:\n root_node = self.root_node\n num_examples = len(examples)\n decisions = [None for i in range(num_examples)]\n for i in range(num_examples):\n decisions[i] = self.predict(root_node,examples[i])\n return decisions\n\n","sub_path":"decision_tree/decision_tree.py","file_name":"decision_tree.py","file_ext":"py","file_size_in_byte":7952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"166943145","text":"from flask import request\nfrom flask_restplus import Namespace, fields, Resource\nfrom rest_api.models import db_accessor\n\n\ntodo_ns = Namespace('todo', description='End point of ToDo task')\n\n\ntodo = todo_ns.model('ToDo', {\n 'user_id': fields.Integer(\n required=True,\n description='A registered ToDo user',\n example=0\n ),\n 'id': fields.Integer(\n required=True,\n description='A ToDo ID',\n example=0\n ),\n 'title': fields.String(\n required=True,\n description='A ToDo title',\n example='get up'\n ),\n 'description': fields.String(\n required=True,\n descrption='A ToDo descriptions',\n eaxmple='At least I want to get up at 7 a.m.'\n )\n})\n\n\n@todo_ns.route('/')\nclass ToDoList(Resource):\n @todo_ns.marshal_list_with(todo)\n def get(self):\n return db_accessor.db.todo.find()\n\n\n@todo_ns.route('/')\nclass ToDoController(Resource):\n @todo_ns.marshal_with(todo)\n def get(self, todo_id):\n return db_accessor.db.todo.find_one_or_404({'id': todo_id})\n\n def post(self, todo_id):\n db_accessor.db.todo.insert({\n \"id\": todo_id,\n \"user_id\": request.json[\"user_id\"],\n \"title\": request.json[\"title\"],\n \"description\": request.json[\"description\"]\n })\n","sub_path":"Python/Starting/chapxx/rest-api/rest_api/apis/todo.py","file_name":"todo.py","file_ext":"py","file_size_in_byte":1328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"316187520","text":"\"\"\"Test feature_preprocessing module\"\"\"\nimport filecmp\nimport logging\nimport os\nimport random\n\nimport numpy as np\nimport pytest\n\nfrom .build_featurizer_test import ATOL\nfrom pic2vec.feature_preprocessing import (_create_csv_with_image_paths,\n _find_directory_image_paths,\n _find_csv_image_paths,\n _find_combined_image_paths,\n _image_paths_finder, _convert_single_image,\n preprocess_data,\n natural_key)\n\n# Initialize seed to cut out any randomness (such as in image interpolation, etc)\nrandom.seed(5102020)\n\n# Shared paths\nIMAGE_PATH = 'tests/feature_preprocessing_testing/test_images/'\nCSV_PATH = 'tests/feature_preprocessing_testing/csv_testing/'\nIMAGE_ARRAY_PATH = 'tests/feature_preprocessing_testing/test_image_arrays/'\nURL_PATH = '{}url_test'.format(CSV_PATH)\nTEST_ARRAY = 'tests/feature_preprocessing_testing/test_preprocessing_arrays/{}.npy'\n\n# Column headers\nIMG_COL_HEAD = 'images'\nNEW_IMG_COL_HEAD = 'new_images'\n\n# Image lists for directory and url\nIMAGE_LIST = ['arendt.bmp', 'borges.jpg', 'sappho.png']\nURL_LIST = ['http://i2.wp.com/roadsandkingdoms.com/uploads/2013/11/Jorge_Luis_Borges.jpg',\n 'http://sisareport.com/wp-content/uploads/2016/09/%E2%96%B2-%ED'\n '%95%9C%EB%82%98-%EC%95%84%EB%A0%8C%ED%8A%B8Hannah-Arendt-1906-1975.bmp',\n 'http://queerbio.com/wiki/images/thumb/8/8d/Sappho.png/200px-Sappho.png'\n ]\n\n# Preprocessing paths\nDIRECTORY_CSV_PATH_PREPROCESS = '{}directory_preprocess_system_test'.format(CSV_PATH)\nERROR_NEW_CSV_NAME_PREPROCESS = '{}generated_error_preprocess_system_test'.format(CSV_PATH)\nNEW_CSV_NAME_PREPROCESS = '{}generated_preprocess_system_test'.format(CSV_PATH)\nCOMBINED_LIST_PREPROCESS = ['', 'arendt.bmp', 'sappho.png', 'arendt.bmp']\nERROR_ROW_CSV = '{}error_row'.format(CSV_PATH)\n\n# Loading image arrays\narendt_array = np.load(TEST_ARRAY.format('arendt'))\nborges_array = np.load(TEST_ARRAY.format('borges'))\nsappho_array = np.load(TEST_ARRAY.format('sappho'))\narendt_grayscale_array = np.load(TEST_ARRAY.format('arendt_grayscale'))\nsappho_grayscale_array = np.load(TEST_ARRAY.format('sappho_grayscale'))\n\n# Test arrays for build_featurizer\nDIRECTORY_ARRAYS = [arendt_array, borges_array, sappho_array]\nCSV_ARRAYS = [borges_array, arendt_array, sappho_array]\nCOMBINED_ARRAYS = [np.zeros((borges_array.shape)), arendt_array, sappho_array, arendt_array]\nGRAYSCALE_ARRAYS = [np.zeros((arendt_grayscale_array.shape)), arendt_grayscale_array,\n sappho_grayscale_array, arendt_grayscale_array]\n\n\n# ---- TESTING ---- #\ndef test_create_csv_with_image_paths():\n \"\"\"Test method creates csv correctly from list of images\"\"\"\n new_csv_path = 'tests/feature_preprocessing_testing/csv_testing/generated_create_csv_test'\n\n if os.path.isfile(new_csv_path):\n os.remove(new_csv_path)\n\n _create_csv_with_image_paths(IMAGE_LIST, new_csv_path, IMG_COL_HEAD)\n\n assert filecmp.cmp(new_csv_path, '{}create_csv_check'.format(CSV_PATH))\n\n if os.path.isfile(new_csv_path):\n os.remove(new_csv_path)\n\n\ndef test_natural_sort():\n \"\"\"Test the natural sort function\"\"\"\n unsorted_alphanumeric = ['1.jpg', '10.jpg', '2.jpg', '15.jpg', '20.jpg', '5.jpg']\n natural_sort = ['1.jpg', '2.jpg', '5.jpg', '10.jpg', '15.jpg', '20.jpg']\n assert natural_sort == sorted(unsorted_alphanumeric, key=natural_key)\n\n\ndef test_find_directory_image_paths():\n \"\"\"\n Test method returns a sorted list of valid image files\n to be fed into the featurizer from a directory.\n \"\"\"\n test_image_paths = _find_directory_image_paths(IMAGE_PATH)\n\n assert test_image_paths == IMAGE_LIST\n\n\ndef test_find_csv_image_paths():\n \"\"\"Test method correctly finds image paths in the csv, and in the right order\"\"\"\n check_image_paths = ['borges.jpg', 'arendt.bmp', 'sappho.png']\n test_image_paths = _find_csv_image_paths('{}csv_image_path_check'.format(CSV_PATH),\n IMG_COL_HEAD)\n\n with pytest.raises(ValueError):\n _find_csv_image_paths('{}csv_image_path_check'.format(CSV_PATH), 'Error Column')\n\n assert test_image_paths == check_image_paths\n\n\ndef test_find_combined_image_paths():\n \"\"\"Test that method only returns images that overlap between directory and csv\"\"\"\n check_image_paths = ['', 'arendt.bmp', 'sappho.png']\n\n invalid_csv_image_path = 'heidegger.png'\n invalid_directory_image_path = 'borges.jpg'\n\n test_path = _find_combined_image_paths(IMAGE_PATH,\n '{}directory_combined_image_path_test'\n .format(CSV_PATH), IMG_COL_HEAD)\n\n with pytest.raises(ValueError):\n _find_combined_image_paths(IMAGE_PATH,\n '{}error_directory_combined_test'.format(CSV_PATH),\n IMG_COL_HEAD)\n\n assert invalid_csv_image_path not in test_path\n assert invalid_directory_image_path not in test_path\n\n assert check_image_paths == test_path\n\n\nCONVERT_IMAGE_CASES = [\n ('url', URL_LIST[0]),\n ('directory', '{}borges.jpg'.format(IMAGE_PATH))\n ]\n@pytest.mark.parametrize('grayscale', [None, True], ids=['RGB', 'grayscale'])\n@pytest.mark.parametrize('size', [(299, 299), (299, 467)], ids=['scaled', 'isotropic'])\n@pytest.mark.parametrize('image_source,image_path', CONVERT_IMAGE_CASES, ids=['url', 'directory'])\ndef test_convert_single_image(image_source, image_path, size, grayscale):\n \"\"\"Test converting images from url and directory with options for size and grayscale\"\"\"\n iso = ''\n gscale = ''\n\n if size != (299, 299):\n iso = '_isotropic'\n if grayscale is not None:\n gscale = '_grayscale'\n\n check_array = np.load('{path}image_test{isotropic}{grayscale}.npy'\n .format(path=IMAGE_ARRAY_PATH,\n isotropic=iso,\n grayscale=gscale))\n\n converted_image = _convert_single_image(image_source, 'xception', image_path, size, grayscale)\n\n assert np.allclose(check_array, converted_image, atol=ATOL)\n\n\nPATHS_FINDER_CASES = [\n (IMAGE_PATH, '', NEW_IMG_COL_HEAD,\n '{}paths_finder_integration_test'.format(CSV_PATH), IMAGE_LIST),\n\n ('', URL_PATH, IMG_COL_HEAD, '', URL_LIST),\n\n (IMAGE_PATH, '{}directory_combined_image_path_test'.format(CSV_PATH),\n IMG_COL_HEAD, '', ['', 'arendt.bmp', 'sappho.png'])\n ]\n@pytest.mark.parametrize('image_path, csv_path, image_column_header, new_csv, check_images',\n PATHS_FINDER_CASES, ids=['directory_only', 'csv_only', 'combined'])\ndef test_image_paths_finder(image_path, csv_path, image_column_header, new_csv, check_images):\n \"\"\"\n Test the correct image paths returns for all three cases: directory only,\n csv only, and combined csv + directory\n \"\"\"\n # check the new csv doesn't already exist\n if os.path.isfile(new_csv) and new_csv != '':\n os.remove(new_csv)\n\n # generated image lists\n case = _image_paths_finder(image_path, csv_path, image_column_header, new_csv)\n\n if new_csv != '':\n assert os.path.isfile(new_csv)\n # remove the generated csv\n os.remove(new_csv)\n\n # Check the image lists match\n assert case == check_images\n\n\ndef test_preprocess_data_no_input():\n \"\"\"Raise error if no csv or directory is passed\"\"\"\n with pytest.raises(ValueError):\n preprocess_data(IMG_COL_HEAD, 'xception')\n\n\ndef test_preprocess_data_fake_dir():\n \"\"\"Raise an error if the image_path doesn't point to a real directory\"\"\"\n error_dir = 'egaugnalymgnidnatsrednufoerusuoyera/emdaerohwuoy/'\n try:\n assert not os.path.isdir(error_dir)\n except AssertionError:\n logging.error('Whoops, that labyrinth exists. '\n 'Change error_dir to a directory path that does not exist.')\n with pytest.raises(TypeError):\n preprocess_data(IMG_COL_HEAD, 'xception', image_path=error_dir,\n new_csv_name=ERROR_NEW_CSV_NAME_PREPROCESS)\n\n assert not os.path.isfile(ERROR_NEW_CSV_NAME_PREPROCESS)\n\n\ndef test_preprocess_data_fake_csv():\n \"\"\"Raise an error if the csv_path doesn't point to a file\"\"\"\n error_file = 'rehtonaybtmaerdecnaraeppaeremasawootehtahtdootsrednueh'\n try:\n assert not os.path.isfile(error_file)\n except AssertionError:\n logging.error(\n 'Whoops, that dreamer exists. change to error_file to a file path that does not exist.')\n with pytest.raises(TypeError):\n preprocess_data(IMG_COL_HEAD, 'xception', csv_path=error_file,\n new_csv_name=ERROR_NEW_CSV_NAME_PREPROCESS)\n\n assert not os.path.isfile(ERROR_NEW_CSV_NAME_PREPROCESS)\n\ndef test_preprocess_data_invalid_url_or_dir():\n \"\"\"Raise an error if the image in the column is an invalid path\"\"\"\n preprocess_data(IMG_COL_HEAD, 'xception', csv_path=ERROR_ROW_CSV)\n\n\ndef test_preprocess_data_invalid_model_str():\n \"\"\"Raise an error if the model_str is not a valid model\"\"\"\n with pytest.raises(ValueError):\n preprocess_data(IMG_COL_HEAD, 'derp', csv_path=DIRECTORY_CSV_PATH_PREPROCESS,\n new_csv_name=ERROR_NEW_CSV_NAME_PREPROCESS)\n\n\ndef compare_preprocessing(case, csv_name, check_arrays, image_list):\n \"\"\"Compare a case from a full preprocessing step with the expected values of that case\"\"\"\n # Check correct number of images vectorized\n if image_list != COMBINED_LIST_PREPROCESS:\n assert len(case[0]) == 3\n else:\n assert len(case[0]) == 4\n\n # Check all data vectors correctly generated\n assert np.allclose(case[0][0], check_arrays[0], atol=ATOL)\n assert np.allclose(case[0][1], check_arrays[1], atol=ATOL)\n assert np.allclose(case[0][2], check_arrays[2], atol=ATOL)\n\n # csv path correctly returned as non-existent, and correct image list returned\n assert case[1] == csv_name\n assert case[2] == image_list\n\n@pytest.mark.xfail\ndef test_preprocess_data_grayscale():\n # Ensure the new csv doesn't already exist\n if os.path.isfile(ERROR_NEW_CSV_NAME_PREPROCESS):\n os.remove(ERROR_NEW_CSV_NAME_PREPROCESS)\n\n # Create the full (data, csv_path, image_list) for each of the three cases\n preprocessed_case = preprocess_data(IMG_COL_HEAD, 'xception', grayscale=True,\n image_path=IMAGE_PATH, csv_path=DIRECTORY_CSV_PATH_PREPROCESS,\n new_csv_name=ERROR_NEW_CSV_NAME_PREPROCESS)\n\n # Ensure a new csv wasn't created when they weren't needed\n assert not os.path.isfile(ERROR_NEW_CSV_NAME_PREPROCESS)\n\n compare_preprocessing(preprocessed_case, DIRECTORY_CSV_PATH_PREPROCESS, \\\n GRAYSCALE_ARRAYS, COMBINED_LIST_PREPROCESS)\n\n\nPREPROCESS_DATA_CASES = [\n (IMAGE_PATH, '', NEW_CSV_NAME_PREPROCESS,\n DIRECTORY_ARRAYS, IMAGE_LIST),\n\n ('', URL_PATH, ERROR_NEW_CSV_NAME_PREPROCESS,\n CSV_ARRAYS, URL_LIST),\n\n (IMAGE_PATH, DIRECTORY_CSV_PATH_PREPROCESS,\n ERROR_NEW_CSV_NAME_PREPROCESS, COMBINED_ARRAYS,\n COMBINED_LIST_PREPROCESS),\n ]\n@pytest.mark.parametrize('image_path, csv_path, new_csv_name, check_arrays, image_list',\n PREPROCESS_DATA_CASES, ids=['dir_only', 'csv_only', 'combined'])\ndef test_preprocess_data(image_path, csv_path, new_csv_name, check_arrays, image_list):\n \"\"\"\n Full integration test: check for Type and Value errors for badly passed variables,\n and make sure that the network preprocesses data correctly for all three cases.\n \"\"\"\n # Ensure the new csv doesn't already exist\n if os.path.isfile(new_csv_name):\n os.remove(new_csv_name)\n\n # Create the full (data, csv_path, image_list) for each of the three cases\n preprocessed_case = preprocess_data(IMG_COL_HEAD, 'xception', grayscale=False,\n image_path=image_path, csv_path=csv_path,\n new_csv_name=new_csv_name)\n\n # Ensure a new csv wasn't created when they weren't needed, and that a new csv\n # WAS created when it was needed. Then, remove the new csv.\n assert not os.path.isfile(ERROR_NEW_CSV_NAME_PREPROCESS)\n\n if new_csv_name == NEW_CSV_NAME_PREPROCESS:\n csv_path = new_csv_name\n\n compare_preprocessing(preprocessed_case, csv_path, check_arrays, image_list)\n\n if new_csv_name == NEW_CSV_NAME_PREPROCESS:\n assert os.path.isfile(new_csv_name)\n os.remove(new_csv_name)\n\n\nif __name__ == \"__main__\":\n test_create_csv_with_image_paths()\n test_find_directory_image_paths()\n test_find_csv_image_paths()\n test_find_combined_image_paths()\n test_convert_single_image()\n test_image_paths_finder()\n test_preprocess_data()\n","sub_path":"tests/feature_preprocessing_test.py","file_name":"feature_preprocessing_test.py","file_ext":"py","file_size_in_byte":13247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"591552547","text":"#from pandas import io\nimport pandas as pd\nimport numpy as np\n#import re\n#from scipy import stats\nfrom math import sin, cos, sqrt, atan2, radians\nimport datetime as dt\nfrom scipy.spatial import distance\nimport matplotlib as plt\n\nLATI_ZERO = 41.5\nLONG_ZERO = -88.0\nLATI_END = 42.1\nLONG_END = -87.4\nHEX_CELL_SIZE = 1.0\nHEX_CELL_HEIGHT = HEX_CELL_SIZE * 2.0\nHEX_CELL_WIDTH = sqrt(3.0) / 2.0 * HEX_CELL_HEIGHT\nHEX_CELL_VERT = HEX_CELL_HEIGHT * 3.0 / 4.0\nHEX_CELL_HORI = HEX_CELL_WIDTH\n\ndf_train = pd.read_csv('train_trap_correct.csv')\ndf_test = pd.read_csv('test_trap_correct.csv')\n\ntrap_series = df_train.loc[:, 'Trap'].append(df_test.loc[:, 'Trap'])\nunique_traps = trap_series.unique()\n\ndef haversine(lat1,long1,lat2,long2):\n earth_radius=6371 #in kilometers\n lat1=radians(lat1)\n long1=radians(long1)\n lat2=radians(lat2)\n long2=radians(long2)\n long_dist = long2 - long1\n lat_dist = lat2 - lat1\n a = (sin(lat_dist/2))**2 + cos(lat1) * cos(lat2) * (sin(long_dist/2))**2\n c = 2 * atan2(sqrt(a), sqrt(1-a))\n distance = earth_radius * c\n return distance\n\ndef hex_cell(hex_pos_grid,lat1,long1):\n pt_vert = haversine(LATI_ZERO,LONG_ZERO,lat1,LONG_ZERO)\n pt_hori = haversine(LATI_ZERO,LONG_ZERO,LATI_ZERO,long1)\n\n hex_c = []\n dist = np.inf\n for el in hex_pos_grid:\n tmp_dist = distance.euclidean(hex_pos_grid[el], (pt_vert, pt_hori))\n if tmp_dist < dist:\n hex_c = el\n dist = tmp_dist\n\n return hex_c\n\ndef neighbour_cell(hex_grid, level):\n indices=[[0,0]]\n if level>=1:\n indices=indices + [[-1,-1],[-1,0],[0,-1],[0,1],[1,-1],[1,0]]\n if level>=2:\n indices=indices + [[-2,-1],[-2,0],[-2,1],[-1,-2],[-1,1],[0,-2],[0,2],[1,-2],[1,1],[2,-1],[2,0],[2,1]]\n if level>=3:\n indices=indices + [[-3,-1],[-3,0],[-3,1],[-2,-2],[-2,2],[-1,-3],[-1,2],[0,-3],[0,3],[1,-3],[1,2],[2,-2],[2,2],[3,-1],[3,0],[3,1]]\n indices = np.array(indices)\n cell_neigh={}\n for index, el in hex_grid.iterrows():\n tmp_neigh = []\n for ind in indices:\n row = el[0]+ind[0]\n col = el[1]+ind[1]\n tmp=list(hex_grid[hex_grid[0]==row][hex_grid[1]==col].index.values)\n if index in tmp:\n tmp.remove(index)\n tmp_neigh = tmp_neigh+tmp\n\n cell_neigh[index]=list(tmp_neigh)\n return cell_neigh# list of neighbouring cells\n\ndef create_grid():\n\n hex_grid = np.zeros((np.size(unique_traps),2))\n\n hex_pos_grid = {}\n grid_height = np.ceil(haversine(LATI_ZERO,LONG_ZERO,LATI_END,LONG_ZERO) / HEX_CELL_VERT).astype(int)\n grid_width = np.ceil(haversine(LATI_ZERO,LONG_ZERO,LATI_ZERO,LONG_END) / HEX_CELL_HORI).astype(int)\n for i in range(0, grid_height+1):\n for j in range(0, grid_width+1):\n if i % 2 == 0:\n hex_pos_grid[(i,j)] = (0.5 * HEX_CELL_HEIGHT + i * HEX_CELL_VERT, (j + 1) * HEX_CELL_HORI)\n else:\n hex_pos_grid[(i,j)] = (0.5 * HEX_CELL_HEIGHT + i * HEX_CELL_VERT, (j + 0.5) * HEX_CELL_HORI)\n\n for i, el in enumerate(unique_traps):\n ind = df_test[df_test['Trap'] == el].index.tolist()[0]\n lat1 = df_test['Latitude'].loc[ind]\n long1 = df_test['Longitude'].loc[ind]\n hex_c = hex_cell(hex_pos_grid, lat1,long1)\n hex_grid[i]=hex_c\n\n hex_dict={}\n\n row_min = (np.min(hex_grid[:,0])-2).astype(int)\n row_max = (np.max(hex_grid[:,0])+2).astype(int)\n col_min = (np.min(hex_grid[:,1])-2).astype(int)\n col_max = (np.max(hex_grid[:,1])+2).astype(int)\n\n hex_grid_2 = pd.DataFrame(data=hex_grid, index=unique_traps)\n\n\n for row in range(row_min, row_max+1):\n for col in range(col_min, col_max+1):\n tmp=list(hex_grid_2[hex_grid_2[0]==row][hex_grid_2[1]==col].index.values)\n hex_dict[(row,col)]=list(tmp)\n\n return hex_grid, hex_dict, hex_pos_grid\n\nhex_grid, hex_dict, hex_pos_grid = create_grid()\n\nhex_df = pd.DataFrame(data=hex_grid, index=unique_traps)\n# neigh_0 = neighbour_cell(hex_df,0)\n# neigh_1 = neighbour_cell(hex_df,1)\n# neigh_2 = neighbour_cell(hex_df,2)\nneigh_3 = neighbour_cell(hex_df,3)\n\n# df_train = df_train[1:100]\n# df_test = df_test[1:100]\n\ntrap_series = df_train.loc[:, 'Trap'].append(df_test.loc[:, 'Trap'])\nunique_traps = trap_series.unique()\n\nlist_traps = list(unique_traps)\n\ndf_train['TrapID'] = -1\nfor idx, row in df_train.iterrows():\n df_train['TrapID'][idx] = list_traps.index(df_train['Trap'][idx])\n\ndf_test['TrapID'] = -1\nfor idx, row in df_test.iterrows():\n df_test['TrapID'][idx] = list_traps.index(df_test['Trap'][idx])\n\nmapping = pd.DataFrame({ 'TrapID' : df_train.loc[:, 'TrapID'].append(df_test.loc[:, 'TrapID']),\n 'Latitude' : df_train.loc[:, 'Latitude'].append(df_test.loc[:, 'Latitude']),\n 'Longitude' : df_train.loc[:, 'Longitude'].append(df_test.loc[:, 'Longitude'])})\nmapping = mapping.drop_duplicates('TrapID')\n\nmappingfile = open('./hex_mapping.csv', 'w+')\nmappingfile.write(\"Latitude, Longitude, TrapID\\n\")\nfor idx, row in mapping.iterrows():\n mappingfile.write(\"%f, %f, %d\\n\" % (mapping['Latitude'][idx], mapping['Longitude'][idx], mapping['TrapID'][idx]))\n\n\n# graphfile = open('./hex.graph', 'w+')\n# graphfile.write(\"%d\\n\" % len(neigh_3))\n# for row in neigh_3:\n# graphfile.write(\"%d %d %s\\n\" % (list_traps.index(row), len(neigh_3[row]), ' '.join([str(list_traps.index(neighbour)) for neighbour in neigh_3[row]])))\n","sub_path":"hex/inla_graph.py","file_name":"inla_graph.py","file_ext":"py","file_size_in_byte":5388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"298597931","text":"# -*- coding:utf-8 -*-\n#卡拉兹(Callatz)猜想:\n\n#对任何一个自然数n,如果它是偶数,那么把它砍掉一半;如果它是奇数,那么把(3n+1)砍掉一半。\n#这样一直反复砍下去,最后一定���某一步得到n=1。卡拉兹在1950年的世界数学家大会上公布了这个猜想,\n#传说当时耶鲁大学师生齐动员,拼命想证明这个貌似很傻很天真的命题,结果闹得学生们无心学业\n#,一心只证(3n+1),以至于有人说这是一个阴谋,卡拉兹是在蓄意延缓美国数学界教学与科研的进展……\n\nnum = input()\ncount = 0\nwhile (num != 1):\n if num%2 == 0:\n num /= 2\n count += 1\n else:\n num = (3*num+1)/2\n count += 1\n\nprint(count)\nexit(0)\n","sub_path":"PAT练习题/乙级/1001.py","file_name":"1001.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"506265584","text":"numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nsum_even = 0\nfor number in numbers:\n if number % 2 == 0:\n break\n else:\n sum_even += number\n\nprint(\"Sum of the elements up to but not including the first even number is:\", sum_even)","sub_path":"week_3/File 3/Exercise 5.py","file_name":"Exercise 5.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"448478739","text":"#!/usr/bin/env python2\n#\n# Copyright (c) 2015 by Cisco Systems, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nimport os\nimport sys\nimport json\nimport imp\nimport re\nfrom subprocess import call\nfrom google.protobuf.message import Message\nfrom google.protobuf.descriptor import FieldDescriptor\nfrom receiver_utils import (timestamp_to_string, \n print_at_indent, \n bytes_to_string,\n INDENT) \n\n###############################################################################\n# GPB compilation and initialisation\n###############################################################################\n\ndef compile_proto_file(input_files, output_path, include_path):\n \"\"\"\n Compile a .proto file using protoc\n \"\"\"\n for file in input_files.split(','):\n if not os.path.isfile(file):\n print(\"ERROR: file {} does not exist\".format(file))\n return\n command = [\"protoc\",\"--python_out\", output_path, \"-I\", include_path] + input_files.split(',')\n try:\n call(command)\n print(\"Compiled {}\".format(input_files))\n except OSError as e:\n print(\"ERROR: unable to run command '{}'. Make sure protoc is \"\n \"present in your path\".format(\" \".join(command)))\n raise e\n\ndef parse_schema_from_proto(input_file):\n \"\"\"\n Find the schema path and corresponding message definition in a .proto file\n \"\"\"\n with open(input_file) as f:\n schema_path = None\n msg_name = None\n for line in f.readlines():\n # Look for the first instance of the string \"message \"\n # and \"...schema_path = \"\n if msg_name == None:\n match = re.search(\"^message (\\S+)\", line)\n if match:\n msg_name = match.group(1)\n else:\n match = re.search(\".*schema_path = \\\"(\\S+)\\\"\", line)\n if match:\n schema_path = match.group(1)\n break\n\n return (schema_path,msg_name)\n\ndef gpb_decoder_init(args):\n \"\"\"\n Compile the necesary telemetry proto files if they don't already exist and\n create a mapping between policy paths and proto files specified on the \n command line.\n \"\"\"\n # Build any proto files not already available\n proto_files = [\"descriptor\", \"cisco\", \"telemetry\"]\n\n for file in proto_files:\n if not os.path.isfile(\"{}/{}_pb2.py\".format(args.tmp_dir, file)):\n compile_proto_file(\"{}.proto\".format(file), args.tmp_dir, \n args.include_path)\n\n global telemetry_pb2\n import telemetry_pb2\n\n\n # Key-value protobuf cannot be compiled using the old version of protoc \n # available so use a local pre-compiled version.\n global telemetry_kv_pb2\n import telemetry_kv_pb2\n\n #\n # Create a dictionary for storing mapping from schema paths to\n # decoder objects\n #\n global decoder_dict\n decoder_dict = {}\n\n #\n # For each proto file specified on the command line\n # - attempt to compile it (this way we always use the latest .proto file)\n # - if that fails then try using an existing file (this means it is possible\n # to run the tool even if protoc is unavailable)\n # - import the compiled file\n # - find the schema path and message name\n # - store a mapping from schema path to msg class\n #\n for proto in args.protos:\n name,ext = os.path.splitext(proto)\n module = \"{}_pb2\".format(name) \n compiled_filename = \"{}/{}.py\".format(args.tmp_dir, module)\n # protoc handily replaces hyphens with underscores in the filenames it\n # gnerates so we must do the same.\n compiled_filename = compiled_filename.replace(\"-\",\"_\")\n try:\n compile_proto_file(proto, args.tmp_dir, args.include_path)\n except Exception as e:\n if not os.path.isfile(compiled_filename):\n print(\"Failed to compile {}: {}\".format(\n proto, e))\n sys.exit(1)\n else:\n print(\"Using existing compiled protobuf file {}\".format(compiled_filename))\n\n try:\n decoder = imp.load_source(module, compiled_filename)\n (schema_path, msg_name) = parse_schema_from_proto(proto)\n decoder_dict[schema_path] = getattr(decoder, msg_name)\n except Exception as e:\n print(\"Failed to load {}: {}\".format(compiled_filename, e))\n sys.exit(1)\n\n###############################################################################\n# Protobuf to dict conversion\n###############################################################################\n\nDECODE_FN_MAP = {\n FieldDescriptor.TYPE_DOUBLE: float,\n FieldDescriptor.TYPE_FLOAT: float,\n FieldDescriptor.TYPE_INT32: int,\n FieldDescriptor.TYPE_INT64: long,\n FieldDescriptor.TYPE_UINT32: int,\n FieldDescriptor.TYPE_UINT64: long,\n FieldDescriptor.TYPE_SINT32: int,\n FieldDescriptor.TYPE_SINT64: long,\n FieldDescriptor.TYPE_FIXED32: int,\n FieldDescriptor.TYPE_FIXED64: long,\n FieldDescriptor.TYPE_SFIXED32: int,\n FieldDescriptor.TYPE_SFIXED64: long,\n FieldDescriptor.TYPE_BOOL: bool,\n FieldDescriptor.TYPE_STRING: unicode,\n FieldDescriptor.TYPE_BYTES: lambda b: bytes_to_string(b),\n FieldDescriptor.TYPE_ENUM: int,\n}\n\n\ndef field_type_to_fn(msg, field):\n if field.type == FieldDescriptor.TYPE_MESSAGE:\n # For embedded messages recursively call this function. If it is\n # a repeated field return a list\n result = lambda msg: proto_to_dict(msg)\n elif field.type in DECODE_FN_MAP:\n result = DECODE_FN_MAP[field.type]\n else:\n raise TypeError(\"Field %s.%s has unrecognised type id %d\" % (\n msg.__class__.__name__, field.name, field.type))\n return result\n\ndef proto_to_dict(msg):\n result_dict = {}\n extensions = {}\n for field, value in msg.ListFields():\n conversion_fn = field_type_to_fn(msg, field)\n \n # Skip extensions\n if not field.is_extension:\n # Repeated fields result in an array, otherwise just call the \n # conversion function to store the value\n if field.label == FieldDescriptor.LABEL_REPEATED:\n result_dict[field.name] = [conversion_fn(v) for v in value]\n else:\n result_dict[field.name] = conversion_fn(value)\n return result_dict\n\n###############################################################################\n# GPB Decoding\n###############################################################################\n\ndef print_gpb_compact_msg (field, indent, args):\n \"\"\"\n Recursively iterate over a compactGPB obejct, displaying all fields at an \n appropriate indent.\n Argument: field\n The object to print.\n Argument: indent\n The indent level to start printing at.\n \"\"\"\n for descriptor in field.DESCRIPTOR.fields:\n value = getattr(field, descriptor.name)\n if descriptor.type == descriptor.TYPE_MESSAGE:\n # \n # If the value is a sub-message then recursively call this function\n # to decode it. If the message is repeated then iterate over each\n # item.\n #\n if descriptor.label == descriptor.LABEL_REPEATED:\n print_at_indent(\"{} ({} items) [\".format(\n descriptor.name, len(value)), \n indent)\n for i, item in enumerate(value):\n print_at_indent(\"{} {} {{\".format(descriptor.name, i),\n indent)\n print_gpb_compact_msg(item, indent+1, args)\n print_at_indent(\"}\", indent)\n if not args.print_all:\n # Stop after the first item unless all have been\n # requested\n break\n print_at_indent(\"]\", indent)\n else:\n print_at_indent(\"{} {{\".format(descriptor.name), indent)\n print_gpb_compact_msg(value, indent + 1, args)\n print_at_indent(\"}\", indent)\n elif descriptor.type == descriptor.TYPE_ENUM:\n #\n # For enum types print the enum name\n #\n enum_name = descriptor.enum_type.values[value].name\n print_at_indent(\"{}: {}\".format(descriptor.name, enum_name),\n indent)\n elif descriptor.type == descriptor.TYPE_BYTES:\n print_at_indent(\"{}: {}\".format(descriptor.name,\n bytes_to_string(value)), indent)\n else:\n # \n # For everything else just print the value\n #\n print_at_indent(\"{}: {}\".format(descriptor.name, value), indent)\n\ndef print_gpb_compact_hdr (header):\n \"\"\"\n Print the compact GPB message header\n \"\"\"\n print(\"\"\"\nEncoding:{:#x}\nPolicy Name:{}\nVersion:{}\nIdentifier:{}\nStart Time:{}\nEnd Time:{}\n# Tables: {}\"\"\".format(header.encoding,\n header.policy_name,\n header.version,\n header.identifier,\n timestamp_to_string(header.start_time),\n timestamp_to_string(header.end_time),\n len(header.tables))\n)\n\ndef decode_gpb_compact (message, args):\n \"\"\"\n Decode and print a GPB compact message\n \"\"\"\n header = telemetry_pb2.TelemetryHeader()\n try:\n header.ParseFromString(message)\n except Exception as e:\n print(\"ERROR decoding header. Not a valid 'TelemetryHeader' message. \"\n \"Full message dump below:\")\n print(bytes_to_string(message))\n return\n\n # Check the encoding value is correct\n ENCODING = 0x87654321\n if header.encoding != ENCODING:\n print(\"Invalid 'encoding' value {:#x} (expected {:#x})\".format(\n header.encoding, ENCODING))\n return\n\n # Print the message header\n json_dict = {}\n if args.json_dump:\n # Convert the protobuf into a dictionary in preparation for dumping\n # it as JSON.\n json_dict = proto_to_dict(header)\n else:\n print_gpb_compact_hdr(header)\n\n # Loop over the tables within the message, printing either just the first \n # row or all rows depending on the args specified\n\n for t, entry in enumerate(header.tables):\n schema_path = entry.policy_path\n if not args.json_dump:\n print(INDENT + \"Schema Path:{}\".format(schema_path))\n warning = \"\"\n if not args.print_all:\n warning = \"(Only first row displayed)\"\n print(INDENT + \"# Rows:{} {}\".format(len(entry.row), warning))\n\n if not schema_path in decoder_dict.keys():\n print(INDENT + \"No decoder available\")\n if args.json_dump:\n json_dict[\"tables\"][t][\"row\"][0] = \"\"\n else:\n for i, row in enumerate(entry.row):\n row_msg = decoder_dict[schema_path]()\n try:\n row_msg.ParseFromString(row)\n if args.json_dump:\n # Replace the bytes in the 'row' field with a decoded\n # dict\n table = json_dict[\"tables\"][t]\n table[\"row\"][i] = proto_to_dict(row_msg)\n else:\n print(INDENT * 2 + \"Row {}:\".format(i))\n print_gpb_compact_msg(row_msg, 2, args)\n print(\"\")\n except Exception as e:\n print(\"ERROR decoding row. Not a valid GPB message. Full \"\n \"message dump below: {}\".format(e))\n print(bytes_to_string(row))\n \n if not args.print_all and not args.json_dump:\n break\n\n if args.json_dump:\n print(json.dumps(json_dict))\n\ndef print_gpb_kv_field_data (name, data, datatype, time, indent):\n \"\"\"\n Print a single row for a TelemetryField message\n \"\"\"\n if name == \"\":\n name = \"\"\n print_at_indent(\"{}: {} ({}) {}\".format(name, data, datatype, time),\n indent)\n\ndef print_gpb_kv_field (field, indent):\n \"\"\"\n Pretty-print a TelemtryField message\n \"\"\"\n # Decode the timestamp if there is one\n if field.timestamp != 0:\n time = timestamp_to_string(field.timestamp)\n else:\n time = \"\"\n \n # Find the datatype and print it\n datatypes = [\"bytes_value\",\n \"string_value\",\n \"bool_value\",\n \"uint32_value\",\n \"uint64_value\",\n \"sint32_value\",\n \"sint64_value\",\n \"double_value\",\n \"float_value\"]\n for d in datatypes:\n datatype = d[:-6]\n if field.HasField(d):\n if datatype == \"bytes\":\n print_gpb_kv_field_data(field.name,\n bytes_to_string(field.bytes_value),\n datatype, time, indent)\n else:\n print_gpb_kv_field_data(field.name, getattr(field,d), datatype,\n time, indent)\n\n # If 'fields' is used then recursively call this function to decode\n if len(field.fields) > 0:\n print_gpb_kv_field_data(field.name, \n \"fields\",\n \"items {}\".format(len(field.fields)),\n \"{} {{\".format(time), indent)\n\n for f in field.fields:\n print_gpb_kv_field(f, indent+1)\n print_at_indent(\"}\", indent)\n\n\n\ndef print_gpb_kv_hdr (header):\n \"\"\"\n Print the key-value GPB message header\n \"\"\"\n print(\"\"\"\nCollection ID: {}\nBase Path: {}\nSubscription ID: {}\nModel Version: {}\"\"\".format(header.collection_id,\n header.base_path,\n header.subscription_identifier,\n header.model_version))\n # start and end time are not always present\n if header.collection_start_time > 0:\n print(\"Start Time: {}\".format(timestamp_to_string(header.collection_start_time)))\n print(\"Msg Timestamp: {}\".format(timestamp_to_string(header.msg_timestamp)))\n if header.collection_end_time > 0:\n print(\"End Time: {}\".format(timestamp_to_string(header.collection_end_time)))\n print(\"Fields: {}\".format(len(header.fields))) \n\n \n\ndef decode_gpb_kv (message, args):\n \"\"\"\n Decode and print a GPB key-value message\n \"\"\"\n header = telemetry_kv_pb2.Telemetry()\n try:\n header.ParseFromString(message)\n except Exception as e:\n print(\"ERROR decoding header. Not a valid 'Telemetry' message. Full \"\n \"message dump below:\")\n print(bytes_to_string(message))\n return\n\n if args.json_dump:\n print(json.dumps(proto_to_dict(header)))\n else:\n # Print the message header\n print_gpb_kv_hdr(header)\n\n # Loop over the tables within the message, printing either just the first \n # row or all rows depending on the args specified\n if args.print_all:\n for entry in header.fields:\n print_gpb_kv_field(entry, 2)\n elif len(header.fields) > 0 and not args.brief:\n print(\" Displaying first entry only\")\n print_gpb_kv_field(header.fields[0], 1)\n","sub_path":"receiver_gpb.py","file_name":"receiver_gpb.py","file_ext":"py","file_size_in_byte":16040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"504744578","text":"import libtcodpy as libtcod\nimport dungeon\nimport inventory\nimport util\nimport messager\nimport entity\n\nnormal, inventoryDisplay, stateDrop, wieldPrompt, wearPrompt = range(5)\ninputState = normal\n\n\n# Returns true if a turn passes and the environment needs updated;\n# returns false if no turn passes.\ndef handleInput(player, key, level):\n if messager.moreMessages():\n return False\n if inputState == normal:\n # handleMovement needs to determine if it has a valid command.\n return handleMovement(player, key, level)\n elif inputState == inventoryDisplay:\n return inventoryPager()\n elif inputState == stateDrop:\n return dropPrompt(player, key, level)\n elif inputState == wieldPrompt:\n return wieldPrompt(player, key, level)\n elif inputState == wearPrompt:\n return wearPrompt(player, key, level)\n\n\n# Works on a single page of inventory, anyway. I have no proof that it'll work on large ones.\ndef inventoryPager():\n global inputState\n inventoryDone = inventory.displayNextPage()\n if inventoryDone:\n inputState = normal\n return False\n\n\ndef dropPrompt(player, key, level):\n global inputState\n if key.vk != 65:\n #Display error\n return False\n else:\n keyChar = chr(key.c)\n theItem, count = player.inventory[keyChar]\n if theItem and count != 0:\n # HACK! Need to allow user to specify count\n messager.addMessage(\"You drop the \" + theItem.infostring)\n count -= 1\n if level.floor[player.Z][player.X][player.Y].items:\n if theItem in level.floor[player.Z][player.X][player.Y].items:\n level.floor[player.Z][player.X][player.Y].items[theItem] += 1\n else:\n level.floor[player.Z][player.X][player.Y].items = {theItem: 1}\n if count > 0:\n player.inventory[keyChar] = theItem, count\n else:\n player.inventory[keyChar] = None, 0\n if player.wieldedSlot == keyChar:\n player.wieldedSlot = None\n player.wielded = None\n inputState = normal\n return True\n else:\n inputState = normal\n messager.addMessage(\"I don't have that item.\")\n return False\n\ndef wieldPrompt(player, key, level):\n global inputState\n if key.vk != 65:\n return False\n else:\n keyChar = chr(key.c)\n if not player.wieldItem(keyChar):\n messager.addMessage(\"I don't have that item.\")\n inputState = normal\n return False\n inputState = normal\n return True\n \ndef wearPrompt(player, key, level):\n global inputState\n if key.vk != 65:\n return False\n else:\n keyChar = chr(key.c)\n if not player.wearItem(keyChar):\n messager.addMessage(\"I don't have that item.\")\n inputState = normal\n return False\n inputState = normal\n return True\n\n# Normal input handler if nothing else is going on.\ndef handleMovement(player, key, level):\n global inputState\n keyChar = chr(key.c)\n if key.vk != 65:\n keyChar = getUnprintableKeypress(key)\n if keyChar == 'j':\n if level.floor[player.Z][player.X][player.Y + 1].isPassable():\n player.Y += 1\n return True\n elif level.floor[player.Z][player.X][player.Y + 1].entity is not None: \n entity.attack(player, level.floor[player.Z][player.X][player.Y + 1].entity)\n messager.addAttackMessage(level.floor[player.Z][player.X][player.Y + 1].entity)\n return True\n else:\n messager.addMessage(\"You can't pass through here.\")\n return False\n \n if keyChar == 'k':\n if level.floor[player.Z][player.X][player.Y - 1].isPassable():\n player.Y -= 1\n return True\n elif level.floor[player.Z][player.X][player.Y - 1].entity is not None: \n entity.attack(player, level.floor[player.Z][player.X][player.Y - 1].entity)\n messager.addAttackMessage(level.floor[player.Z][player.X][player.Y - 1].entity)\n return True\n else:\n messager.addMessage(\"You can't pass through here.\")\n return False\n \n if keyChar == 'h':\n if level.floor[player.Z][player.X - 1][player.Y].isPassable():\n player.X -= 1\n return True\n elif level.floor[player.Z][player.X - 1][player.Y].entity is not None: \n entity.attack(player, level.floor[player.Z][player.X - 1][player.Y].entity)\n messager.addAttackMessage(level.floor[player.Z][player.X - 1][player.Y].entity)\n return True\n else:\n messager.addMessage(\"You can't pass through here.\")\n return False\n \n if keyChar == 'l':\n if level.floor[player.Z][player.X + 1][player.Y].isPassable():\n player.X += 1\n return True\n elif level.floor[player.Z][player.X + 1][player.Y].entity is not None: \n entity.attack(player, level.floor[player.Z][player.X + 1][player.Y].entity)\n messager.addAttackMessage(level.floor[player.Z][player.X + 1][player.Y].entity)\n return True\n else:\n messager.addMessage(\"You can't pass through here.\")\n return False\n \n if keyChar == '>' and level.floor[player.Z][player.X][player.Y].terrain == dungeon.stairdown:\n player.Z += 1\n messager.addMessage(\"You go down the steps...\")\n return True\n if keyChar == '<' and level.floor[player.Z][player.X][player.Y].terrain == dungeon.stairup:\n messager.addMessage(\"You go up the steps...\")\n player.Z -= 1\n return True\n if keyChar == 'q':\n exit()\n if keyChar == 's':\n util.saveGame(level, player, None)\n exit()\n if keyChar == 'i':\n inventory.showInventory(player)\n inputState = inventoryDisplay\n return False\n if keyChar == ',':\n theItems = level.floor[player.Z][player.X][player.Y].items\n if not theItems:\n return False\n for i, v in theItems.iteritems():\n player.giveItem(i, v)\n level.floor[player.Z][player.X][player.Y].items = {}\n return True\n if keyChar == 'd':\n inputState = stateDrop\n messager.addMessage(\"Drop what item?\")\n return False\n if keyChar == 'w':\n inputState = wieldPrompt\n messager.addMessage(\"Wield what item?\")\n if keyChar == 'W':\n inputState = wearPrompt\n messager.addMessage(\"Wear what item?\")\n return False\n\n\ndef getUnprintableKeypress(key):\n if key.vk == libtcod.KEY_UP: # up\n return 'k'\n if key.vk == libtcod.KEY_LEFT: # left\n return 'h'\n if key.vk == libtcod.KEY_RIGHT: # right\n return 'l'\n if key.vk == libtcod.KEY_DOWN: # down\n return 'j'\n","sub_path":"src/input.py","file_name":"input.py","file_ext":"py","file_size_in_byte":6930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"146631672","text":"import random\r\nfrom datetime import datetime\r\n\"\"\"\r\n1. Details about the college like address, contact numbers and location\r\n2. Various courses which are currently offered by this college.\r\n3. Placement information regarding this academic year\r\n4. Fee structure for every course\r\n5. Regarding various sports encouraged by college as well as their achievements\r\n6. Details about the internships and projects gained by this college\r\n7. Details regarding the hostel facilities and fee structure per each hostel\r\n8. Information about different activities like music club, cultural club etc.\r\n9. Regarding all the latest notifications from the college.\r\n10. Details about the research projects handled currently.\r\n\"\"\"\r\ncontact_number = \"08816251333\" \r\n\r\n\r\n#List of college bot options\r\n\r\ndef college_bot_main_options():\r\n print(\"------------------------\")\r\n print(\"1. About our college: \")\r\n print(\"2. Courses offered in our college: \")\r\n print(\"3. Placements in our college: \")\r\n print(\"4. Fee structure of our college: \")\r\n print(\"5. Sports & NCC: \")\r\n print(\"6. Internships and projects: \")\r\n print(\"7. Reserch Work: \")\r\n print(\"8. Miscelleneous: \")\r\n print(\"9. Extracurricuilar Activities: \")\r\n print(\"10. Notification: \")\r\n print(\"0. For Exit: \")\r\n print(\"---------------------\")\r\n try:\r\n return int(input(\"enter your choice: \"))\r\n except:\r\n print(\"only given choice 1 to 10\")\r\n return 0\r\n\r\n# this method gives the information about the college\r\n\r\ndef about_college():\r\n address = \"Vishnupur, Kovvada Rd, Kovvada, Andhra Pradesh 534202\"\r\n contact_number = \"08816251333\" \r\n messsage = address + \"\\n\" + \" If you have any queries please contact this number \"+ contact_number\r\n return messsage\r\n\r\n#this method gives the information about the college\r\n\r\ndef courses_offered():\r\n messsage = \"we are offering UG,PG courses\"\r\n ug_courses = \"B.Tech in CSE ECE EEE MECH CIVIL\"\r\n pg_courses = \"M.Tech in CSE ECE EEE MECH CIVIL\"\r\n return messsage + ug_courses + pg_courses + \"along with B.Tech and M.Tech we provide MBA also\"\r\n\r\n#This method gives the fee structure of our college\r\n\r\n\r\ndef fee_structure():\r\n message = \" General college fee for B.Tech is 95,000\"\r\n return message +\"\\n\"+ \"If you want to know about NRI fee details contact\" + contact_number\r\n\r\n#This method gives the placements details of our college\r\n\r\ndef Placement_offered():\r\n message = \"For 2021 passedout students,major companies like TCS,Capgemni,Amazon,Amdocs,SenecaGlobal,Infosys etc.. \"\r\n return message\r\n\r\n#This method gives the sports and NCC details of our college\r\n\r\ndef sports_and_NCC():\r\n message = \"Our students are encouraged to particpate in different tournments for Cricket,volleyball,BasketBall,Throwball,Badminton etc..We have special sports club to maintain all these.\"\r\n return message\r\n#This method gives the projects and internships of our college\r\n\r\ndef internships_and_projects():\r\n message = \"Every year our students are doing interships at different multinational companies\"\r\n return message\r\n\r\n#This method gives the Miscellaneous fees and other factors of our college\r\n\r\ndef Miscellaneous():\r\n message = \"Apart from academic subjects,our college provides various additional courses like Pega,Game Development,Android App Development etc.. for students career development\"\r\n return message\r\n\r\n#This method gives the information about Extracurricular activities of our college like music... etc\r\n\r\ndef Extracurricular_activities():\r\n message = \"We have Different clubs to support students interests like Music,Dance,Photography,Astronomy,Coding etc..\"\r\n return message\r\n\r\n# method is used to greet the user\\\r\n\r\ndef greet_and_introduce():\r\n #declare some list of responses\r\n responses = [ \"Hi There! I am Bot. I am here to help you. May I know your name please ?\", \r\n \"Hi It is so nice to be in touch with you. Can you tell me your name ? \"\r\n ]\r\n #pick a responses at random\r\n print(random.choice(responses))\r\n\r\n\r\n#this method is used to find the current time \r\n\r\ndef get_timeofday_greeting():\r\n current_time = datetime.today()\r\n timeofday_greeting = \"Good Morning\"\r\n if current_time.hour <= 12 and current_time.hour < 17:\r\n timeofday_greeting = \"Good Afternoon\"\r\n elif current_time.hour >= 17 and current_time.hour < 22:\r\n timeofday_greeting = \"Good Evening\"\r\n else:\r\n timeofday_greeting =\"Hi, Thats late\"\r\n return timeofday_greeting\r\n\r\n# this message used to print the welcome message\r\n\r\ndef welcome(name):\r\n messages = [\"Nice to meet you\", \"Glad that you are here\"]\r\n print(get_timeofday_greeting()+ \" \" + random.choice(messages) +\"\\n\"+ \"hiiii \"+ name + \" welcome to our college\")\r\n\r\n#this method gives the information about reserch work and conferences of our college\r\n\r\ndef Reserch_Work():\r\n return \"we have reserch departemt to spouncer the projects and conferences\"\r\n\r\n#this method gives the information about new notifications of our college\r\n\r\ndef Notification():\r\n return \"now we don't have any new notifications\"\r\n\r\n#this method for good bye message at the time of exit\r\n\r\ndef good_bye_message():\r\n print(\"Thank You for visiting our site\")\r\n\r\n#this method is for bot functionality\r\n\r\ndef bot():\r\n greet_and_introduce()\r\n name = input(\"May I know your good name:\")\r\n welcome(name)\r\n choice = college_bot_main_options()\r\n while choice != 0:\r\n\r\n #if you choose choice one then it will about_college() method\r\n if choice == 1:\r\n print()\r\n print(\"-----------About College--------------\")\r\n print(about_college(),end=\"\\n\")\r\n\r\n elif choice == 2:\r\n print()\r\n print(\"-----------Courses offered--------------\")\r\n print(courses_offered(),end=\"\\n\")\r\n\r\n elif choice == 3:\r\n print()\r\n print(\"----------Plcaments--------------\")\r\n print(Placement_offered(),end=\"\\n\")\r\n\r\n elif choice == 4:\r\n print()\r\n print(\"----------Fee Structure--------------\")\r\n print(fee_structure(),end=\"\\n\")\r\n\r\n elif choice == 5:\r\n print()\r\n print(\"----------Sports And NCC--------------\")\r\n print(sports_and_NCC(),end=\"\\n\")\r\n\r\n elif choice == 6:\r\n print()\r\n print(\"----------Internships and Projects--------------\")\r\n print(internships_and_projects(),end=\"\\n\")\r\n\r\n elif choice == 7:\r\n print()\r\n print(\"----------Research Work--------------\")\r\n print(Reserch_Work(),end=\"\\n\")\r\n\r\n elif choice == 8:\r\n print()\r\n print(\"----------Miscelaneous--------------\")\r\n print(Miscellaneous(),end=\"\\n\")\r\n\r\n elif choice == 9:\r\n print()\r\n print(\"----------Extracurricular_activities--------------\")\r\n print(Extracurricular_activities(),end=\"\\n\")\r\n\r\n elif choice == 10:\r\n print()\r\n print(\"----------Notification--------------\")\r\n print(Notification(),end=\"\\n\")\r\n \r\n choice = college_bot_main_options()\r\n \r\n good_bye_message()\r\n \r\nbot()","sub_path":"college_bot.py","file_name":"college_bot.py","file_ext":"py","file_size_in_byte":7217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"200607232","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Feb 28 18:40:43 2019\n\n@author: lizhiying\n\"\"\"\n\n#Let's create a chatbot! \n\nfrom __future__ import absolute_import, division, print_function\n\nimport tensorflow as tf\n\ntf.enable_eager_execution()\n\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport math \nimport nltk \nimport tensorflow as tf \nimport os \nimport io \nimport re \nimport time \nimport unicodedata\nfrom sklearn.model_selection import train_test_split\nos.chdir('/Users/lizhiying/Desktop/Big Data Analytics/LI-bot')\n\n\n\n\nclass Chatbot: \n def __init__(self):\n self.data = [] \n\n\ndef unicode_to_ascii(s):\n return ''.join(c for c in unicodedata.normalize('NFD', s)\n if unicodedata.category(c) != 'Mn')\n\ndef preprocess_sentence(w):\n w = unicode_to_ascii(w.lower().strip())\n \n # creating a space between a word and the punctuation following it\n # eg: \"he is a boy.\" => \"he is a boy .\" \n # Reference:- https://stackoverflow.com/questions/3645931/python-padding-punctuation-with-white-spaces-keeping-punctuation\n w = re.sub(r\"([?.!,¿])\", r\" \\1 \", w)\n w = re.sub(r'[\" \"]+', \" \", w)\n \n # replacing everything with space except (a-z, A-Z, \".\", \"?\", \"!\", \",\")\n w = re.sub(r\"[^a-zA-Z?.!,¿]+\", \" \", w)\n \n w = w.rstrip().strip()\n \n # adding a start and an end token to the sentence\n # so that the model know when to start and stop predicting.\n w = ' ' + w + ' '\n return w\n\nnum_examples = None\n\ndef create_dataset(path, num_examples):\n lines = io.open(path, encoding='UTF-8').read().strip().split('\\n')\n \n word_pairs = [[preprocess_sentence(w) for w in l.split('\\t')] for l in lines[:num_examples]]\n \n word_pairs = [x[0] for x in word_pairs]\n \n #t = tuple(word_pairs)\n \n return word_pairs \n\n\n\n##########\n\nprint(\"loading data\")\nX = create_dataset(\"data/cornell.in\",num_examples)\nY = create_dataset(\"data/cornell.ou\",num_examples)\n\n'''\ndef check_sentence(X,Y):\n xn = []\n yn = []\n for i in range(len(X)-1):\n if len(Y[i]) <= 2*len(X[i]) and len(Y[i]) <= 50:\n xn.append(X[i])\n yn.append(Y[i])\n \n return xn,yn\n \n\nX, Y = check_sentence(X,Y)\n'''\ndef max_length(tensor):\n return max(len(t) for t in tensor)\n\n\ndef tokenize(lang):\n lang_tokenizer = tf.keras.preprocessing.text.Tokenizer(\n filters='')\n lang_tokenizer.fit_on_texts(lang)\n \n tensor = lang_tokenizer.texts_to_sequences(lang)\n \n tensor = tf.keras.preprocessing.sequence.pad_sequences(tensor,\n padding='post')\n \n return tensor, lang_tokenizer\n\n\n\n\ninput_tensor, inp_lang = tokenize(tuple(X))\ntarget_tensor, targ_lang = tokenize(tuple(Y))\n\n\n\ninput_tensor_train, input_tensor_val, target_tensor_train, target_tensor_val = train_test_split(input_tensor, target_tensor, test_size=0.2)\n\n# Show length\n#len(input_tensor_train), len(target_tensor_train), len(input_tensor_val), len(target_tensor_val)\n\n\nmax_length_inp,max_length_targ = max_length(input_tensor), max_length(target_tensor)\n\ndef convert(lang, tensor):\n for t in tensor:\n if t!=0:\n print (\"%d ----> %s\" % (t, lang.index_word[t]))\n\n#print (\"Input index to word mapping\")\n#onvert(inp_lang, input_tensor_train[10])\n\n\n\n\n\n \nprint(\"loading data complete. Now create model!\")\n\n\n########hyperparameters####\nBUFFER_SIZE = len(input_tensor_train)\nBATCH_SIZE = 20\nN_BATCH = len(input_tensor_train)//BATCH_SIZE\nembedding_dim = 10\nunits = 100\nvocab_inp_size = len(inp_lang.word_index)+1\nvocab_tar_size = len(targ_lang.word_index)+1\n\n\n#######create a dataframe######\ndataset = tf.data.Dataset.from_tensor_slices((input_tensor_train, target_tensor_train)).shuffle(BUFFER_SIZE)\ndataset = dataset.batch(BATCH_SIZE, drop_remainder=True)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef gru(units):\n # If you have a GPU, we recommend using CuDNNGRU(provides a 3x speedup than GRU)\n # the code automatically does that.\n if tf.test.is_gpu_available():\n return tf.keras.layers.CuDNNGRU(units, \n return_sequences=True, \n return_state=True, \n recurrent_initializer='glorot_uniform')\n else:\n return tf.keras.layers.GRU(units, \n return_sequences=True, \n return_state=True, \n #recurrent_activation='relu', \n recurrent_activation = 'sigmoid',\n recurrent_initializer='glorot_uniform')\n\n\n\n\n\n####Build the Encode and Decode model \nprint(\"Generating Encoder and Decoder!\")\n\nclass Encoder(tf.keras.Model):\n def __init__(self, vocab_size, embedding_dim, enc_units, batch_sz):\n super(Encoder, self).__init__()\n self.batch_sz = batch_sz\n self.enc_units = enc_units\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.gru = tf.keras.layers.GRU(self.enc_units, \n return_sequences=True, \n return_state=True, \n recurrent_initializer='glorot_uniform')\n\n def call(self, x, hidden):\n x = self.embedding(x)\n output, state = self.gru(x, initial_state = hidden) \n return output, state\n\n def initialize_hidden_state(self):\n return tf.zeros((self.batch_sz, self.enc_units))\n\nencoder = Encoder(vocab_inp_size, embedding_dim, units, BATCH_SIZE)\n\n\n\n \n\nclass Decoder(tf.keras.Model):\n def __init__(self, vocab_size, embedding_dim, dec_units, batch_sz):\n super(Decoder, self).__init__()\n self.batch_sz = batch_sz\n self.dec_units = dec_units\n self.embedding = tf.keras.layers.Embedding(vocab_size, embedding_dim)\n self.gru = gru(self.dec_units)\n self.fc = tf.keras.layers.Dense(vocab_size)\n \n # used for attention\n self.W1 = tf.keras.layers.Dense(self.dec_units)\n self.W2 = tf.keras.layers.Dense(self.dec_units)\n self.V = tf.keras.layers.Dense(1)\n \n def call(self, x, hidden, enc_output):\n # enc_output shape == (batch_size, max_length, hidden_size)\n \n # hidden shape == (batch_size, hidden size)\n # hidden_with_time_axis shape == (batch_size, 1, hidden size)\n # we are doing this to perform addition to calculate the score\n hidden_with_time_axis = tf.expand_dims(hidden, 1)\n \n # score shape == (batch_size, max_length, 1)\n # we get 1 at the last axis because we are applying tanh(FC(EO) + FC(H)) to self.V\n score = self.V(tf.nn.tanh(self.W1(enc_output) + self.W2(hidden_with_time_axis)))\n \n # attention_weights shape == (batch_size, max_length, 1)\n attention_weights = tf.nn.softmax(score, axis=1)\n \n # context_vector shape after sum == (batch_size, hidden_size)\n context_vector = attention_weights * enc_output\n context_vector = tf.reduce_sum(context_vector, axis=1)\n \n # x shape after passing through embedding == (batch_size, 1, embedding_dim)\n x = self.embedding(x)\n \n # x shape after concatenation == (batch_size, 1, embedding_dim + hidden_size)\n x = tf.concat([tf.expand_dims(context_vector, 1), x], axis=-1)\n \n # passing the concatenated vector to the GRU\n output, state = self.gru(x)\n \n # output shape == (batch_size * 1, hidden_size)\n output = tf.reshape(output, (-1, output.shape[2]))\n \n # output shape == (batch_size * 1, vocab)\n x = self.fc(output)\n \n return x, state, attention_weights\n \n def initialize_hidden_state(self):\n return tf.zeros((self.batch_sz, self.dec_units))\n\n\n\n\n\n\ndecoder = Decoder(vocab_tar_size, embedding_dim, units, BATCH_SIZE)\n\n\n\n\n#######################Optimizer#############################\n\n\n\noptimizer = tf.train.AdamOptimizer(learning_rate = 0.001, epsilon = 1e-08)\n\n\ndef loss_function(real, pred):\n mask = 1 - np.equal(real, 0)\n loss_ = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=real, logits=pred) * mask\n return tf.reduce_mean(loss_)\n\n\n\ncheckpoint_dir = './training_checkpoints'\ncheckpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\ncheckpoint = tf.train.Checkpoint(optimizer=optimizer,\n encoder=encoder,\n decoder=decoder)\n\n\n\n\n###########################Training#######################\ndef run_model():\n \n EPOCHS = 10\n print(\"The total batch number is \",N_BATCH,\"Please wait for a moment\")\n \n for epoch in range(EPOCHS):\n start = time.time()\n \n hidden = encoder.initialize_hidden_state()\n total_loss = 0\n \n \n for (batch, (inp, targ)) in enumerate(dataset):\n #print(batch)\n loss = 0\n \n with tf.GradientTape() as tape:\n enc_output, enc_hidden = encoder(inp, hidden)\n \n dec_hidden = enc_hidden\n \n dec_input = tf.expand_dims([targ_lang.word_index['']] * BATCH_SIZE, 1) \n \n # Teacher forcing - feeding the target as the next input\n for t in range(1, targ.shape[1]):\n # passing enc_output to the decoder\n predictions, dec_hidden, _ = decoder(dec_input, dec_hidden, enc_output)\n \n loss += loss_function(targ[:, t], predictions)\n \n # using teacher forcing\n dec_input = tf.expand_dims(targ[:, t], 1)\n \n batch_loss = (loss / int(targ.shape[1]))\n \n total_loss += batch_loss\n \n variables = encoder.variables + decoder.variables\n \n gradients = tape.gradient(loss, variables)\n \n optimizer.apply_gradients(zip(gradients, variables))\n \n #if batch % 100 == 0:\n print('Epoch {} Batch {} Total Batch {} Loss {:.4f}'.format(epoch + 1,batch,N_BATCH,batch_loss.numpy()))\n # saving (checkpoint) the model every 1 epochs\n if (epoch + 1) % 1 == 0:\n checkpoint.save(file_prefix = checkpoint_prefix)\n \n print('Epoch {} Loss {:.4f}'.format(epoch + 1,\n total_loss / N_BATCH))\n print('Time taken for 1 epoch {} sec\\n'.format(time.time() - start))\n\n\n\n\n\n\n\n\ndef evaluate(sentence, encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ):\n attention_plot = np.zeros((max_length_targ, max_length_inp))\n \n sentence = preprocess_sentence(sentence)\n\n inputs = [inp_lang.word_index[i] for i in sentence.split(' ')]\n inputs = tf.keras.preprocessing.sequence.pad_sequences([inputs], maxlen=max_length_inp, padding='post')\n inputs = tf.convert_to_tensor(inputs)\n \n result = ''\n\n hidden = [tf.zeros((1, units))]\n enc_out, enc_hidden = encoder(inputs, hidden)\n\n dec_hidden = enc_hidden\n dec_input = tf.expand_dims([targ_lang.word_index['']], 0)\n\n for t in range(max_length_targ):\n predictions, dec_hidden, attention_weights = decoder(dec_input, dec_hidden, enc_out)\n \n # storing the attention weights to plot later on\n attention_weights = tf.reshape(attention_weights, (-1, ))\n attention_plot[t] = attention_weights.numpy()\n\n predicted_id = tf.argmax(predictions[0]).numpy()\n\n result += targ_lang.index_word[predicted_id] + ' '\n\n if targ_lang.index_word[predicted_id] == '':\n return result, sentence, attention_plot\n \n # the predicted ID is fed back into the model\n dec_input = tf.expand_dims([predicted_id], 0)\n\n return result, sentence, attention_plot\n\n\n\n\n\n\n\n# function for plotting the attention weights\ndef plot_attention(attention, sentence, predicted_sentence):\n fig = plt.figure(figsize=(10,10))\n ax = fig.add_subplot(1, 1, 1)\n ax.matshow(attention, cmap='viridis')\n \n fontdict = {'fontsize': 14}\n \n ax.set_xticklabels([''] + sentence, fontdict=fontdict, rotation=90)\n ax.set_yticklabels([''] + predicted_sentence, fontdict=fontdict)\n\n plt.show()\n\ndef chat(sentence, encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ):\n result, sentence, attention_plot = evaluate(sentence, encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)\n \n print('Input: {}'.format(sentence))\n print('Output: {}'.format(result))\n \n attention_plot = attention_plot[:len(result.split(' ')), :len(sentence.split(' '))]\n plot_attention(attention_plot, sentence.split(' '), result.split(' '))\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#run_model()\n\n\n\n\n# restoring the latest checkpoint in checkpoint_dir\ncheckpoint.restore(tf.train.latest_checkpoint(checkpoint_dir))\n\n\n\n \nchat('I do', encoder, decoder, inp_lang, targ_lang, max_length_inp, max_length_targ)\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"LI-bot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":13007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"214556131","text":"import pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.common.keys import Keys\nimport time\nfrom time import sleep\nimport sys\n\n\n@pytest.mark.usefixtures(\"driver_init_2\")\nclass BasicTest:\n pass\n\n\nclass Test_URL_Firefox(BasicTest):\n def test_google_search(self):\n self.driver.get('https://www.google.com/')\n self.driver.maximize_window()\n title = \"Google\"\n assert title == self.driver.title\n\n search_text = \"LambdaTest\"\n search_box = self.driver.find_element_by_xpath(\"//input[@name='q']\")\n search_box.send_keys(search_text)\n\n time.sleep(5)\n\n # Option 1 - To Submit the search\n # search_box.submit()\n\n # Option 2 - To Submit the search\n search_box.send_keys(Keys.ARROW_DOWN)\n search_box.send_keys(Keys.ARROW_UP)\n time.sleep(2)\n search_box.send_keys(Keys.RETURN)\n\n time.sleep(5)\n\n # Click on the LambdaTest HomePage Link\n title = \"Cross Browser Testing Tools | Free Automated Website Testing | LambdaTest\"\n lt_link = self.driver.find_element_by_xpath(\n \"//h3[.='LambdaTest: Cross Browser Testing Tools | Free Automated ...']\")\n lt_link.click()\n\n time.sleep(10)\n assert title == self.driver.title\n time.sleep(2)\n\n def test_lambdatest_blog_load(self):\n self.driver.get('https://www.lambdatest.com/blog/')\n self.driver.maximize_window()\n\n expected_title = \"LambdaTest | A Cross Browser Testing Blog\"\n assert expected_title == self.driver.title\n time.sleep(5)","sub_path":"FinalProject2/test_pytest.py","file_name":"test_pytest.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"368473872","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nclass Regressor(nn.Module):\n def __init__(self):\n super(Regressor, self).__init__()\n self.batchnorm0 = nn.BatchNorm2d(1)\n self.conv1 = nn.Conv2d(1, 16, 2, stride=2)\n self.batchnorm1 = nn.BatchNorm2d(16)\n self.conv2 = nn.Conv2d(16, 32, 2, stride=2)\n self.batchnorm2 = nn.BatchNorm2d(32)\n self.conv3 = nn.Conv2d(32, 64, 2, stride=2)\n self.batchnorm3 = nn.BatchNorm2d(64)\n self.conv4 = nn.Conv2d(64, 64, 2)\n \n self.dropout = nn.Dropout(p=0.3)\n \n self.fc1 = nn.Linear(256, 256) \n self.batchnorm4 = nn.BatchNorm1d(256)\n self.fc2 = nn.Linear(256, 128)\n self.fc3 = nn.Linear(128, 64)\n self.fc4 = nn.Linear(64, 2 + 3)\n self.fc5 = nn.Linear(64, 1)\n \n def forward(self, x):\n x = self.batchnorm0(self.dropout(x))\n x = self.batchnorm1(self.dropout(F.relu(self.conv1(x))))\n x = self.batchnorm2(F.relu(self.conv2(x)))\n x = self.batchnorm3(F.relu(self.conv3(x)))\n x = F.relu(self.conv4(x)) # 64, 5, 5\n x = x.view(len(x), -1)\n x = self.dropout(x)\n x = self.batchnorm4(self.dropout(F.relu(self.fc1(x))))\n x = F.leaky_relu(self.fc2(x))\n x = torch.tanh(self.fc3(x))\n return self.fc4(x), self.fc5(x)\n \n def get_encoding(self, x):\n x = self.batchnorm0(self.dropout(x))\n x = self.batchnorm1(self.dropout(F.relu(self.conv1(x))))\n x = self.batchnorm2(F.relu(self.conv2(x)))\n x = self.batchnorm3(F.relu(self.conv3(x)))\n x = F.relu(self.conv4(x)) # 64, 5, 5\n x = x.view(len(x), -1)\n x = self.dropout(x)\n x = self.batchnorm4(self.dropout(F.relu(self.fc1(x))))\n x = F.leaky_relu(self.fc2(x))\n x = self.fc3(x)\n return x\n \n\ndef load_embedder(path):\n embedder = torch.load(path)\n embedder.eval()\n return embedder\n\n","sub_path":"Regressor.py","file_name":"Regressor.py","file_ext":"py","file_size_in_byte":1961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"616580065","text":"import numpy as np\nfrom scipy import linalg as LA\n\n# This container class stores the results of the forward-backward algorithm.\n# It contains summary statistics (NOT entire sequence) on the inferred hidden-state sequence.\n# seqLength : Underlying suequence length.\n# transitions : ndarray. transitions[i,j] is the inferred number of transitions i->j\n# emissions : ndarray. emissions[i,j] is the inferred number of emissions i->j\n# gamma0 : the posterior distribution of states at the beginning of the sequence\n# logLikelihood : the log-l of the hidden & observed sequence.\nclass HiddenSeqSummary(object):\n \n def __init__(self, seqLength, transitions, emissions, gamma0, logLikelihood):\n \n self.length = seqLength\n \n # verify input arrays have valid dimensions\n nStates, nEmissions = emissions.shape\n assert transitions.shape == (nStates, nStates)\n assert gamma0.shape == (nStates, )\n \n # log( P(O|theta) ), where theta are the parameters used for the hidden-state inference\n # (ie, theta are the parameters used for the Baum-Welch expectation step)\n self.logL = logLikelihood\n \n self.gamma0 = gamma0\n self.emissions = emissions\n self.transitions = transitions \n \n # the following 4 arrays allow efficient calculation of Q (the target function in the BW maximization step):\n # TODO use or remove...\n # IncFrom[i] is the proportion of transitions i->j for some j>i\n self.incFrom = np.array([np.sum(self.transitions[i,(i+1):]) for i in xrange(nStates)])\n # DecFrom[i] is the proportion of transitions i->j for some jj for some ij for some i>j\n self.decTo = np.array([np.sum(self.transitions[(j+1):,j]) for j in xrange(nStates)])\n \n # Combine two classes to one (ie calculate the combined statistics on both sequences)\n def __add__(self, other):\n \n assert self.transitions.shape == other.transitions.shape\n assert self.emissions.shape == other.emissions.shape\n \n length = self.length + other.length\n transitions = self.transitions + other.transitions\n emissions = self.emissions + other.emissions\n gammaa0 = self.gamma0 + other.gamma0\n logL = self.logL + other.logL\n \n return HiddenSeqSummary(length, transitions, emissions, gammaa0, logL)\n\n# This class implements the expectation step of the BW algorithm (ie the forward-backward algorithm)\nclass BaumWelchExpectation(object):\n # TODO this could be a function rather than a class\n # theta : HMM instance\n # obs : an observed emissions sequence (ObservedSequence class)\n def __init__(self, theta, obs):\n \n self._obs = obs\n # TODO reference theta instead? the entire hmm structure is duplicated here... depends on how I implement theta()\n self._nStates = theta.nStates\n self._nEmissions = theta.nEmissions\n self._initialDist = theta.initialDist\n self._transitionMat = theta.transitionMat\n self._emissionMat = theta.emissionMat\n \n self._run = False\n \n # expectation step of BW \n def inferHiddenStates(self):\n \n assert self._run == False\n \n self._runForward()\n self._runBackwards()\n \n self._run = True\n \n return self._res\n \n # forward run of BW: compute alpha_t for all t's in self._obs.positions.\n # all alphas are scaled such that || alpha_t ||_1 = 1.\n # scaling factors are not saved.\n def _runForward(self):\n \n # pre-processing: compute auxilary matrices such that:\n # alpha_(t+d) = C*mats[j,d-1]*alpha_t, assuming\n # 1. O_(t+1) = ... = O_(t+d-1) = 0; and\n # 2. O_(t+d) = j.\n # (Where C is a scaling constant; scalingFactors[j,d-1] = log(C))\n mats, scalingFactors = self._calcForwardMats()\n \n # initilize ndarray for forward variables\n # forward variables are calculated & stored for the positions in self._obs.positions\n self._alpha = np.empty( (self._obs.nPositions, self._nStates), dtype=np.float64 )\n \n # initilize alpha_0 (alpha_0 (i) = pi_i * b_i(O_0) )\n self._alpha[0,:] = self._initialDist * self._emissionMat[:,self._obs.posTypes[0]]\n \n # calculate P(O|theta) = sum( alpha ) (re-correcting for scaling)\n s = np.sum(self._alpha[0,:])\n self._logLikelihood = np.log(s)\n \n # scale alpha_0 (all alpha vectors are scaled to sum to 1.0)\n self._alpha[0,:] /= s\n \n # calculate alpha_1, alpha_2, ..., recursively\n for ind in xrange(1, self._obs.nPositions):\n d = self._obs.positions[ind] - self._obs.positions[ind-1]\n j = self._obs.posTypes[ind]\n np.dot(mats[j, d-1, :, :], self._alpha[ind-1,:], out=self._alpha[ind,:])\n \n # scale alpha_ind and update self._logLikelihood\n s = np.sum(self._alpha[ind,:])\n self._alpha[ind,:] /= s\n self._logLikelihood += (np.log(s) + scalingFactors[j, d-1])\n \n \n # backward run of BW: compute beta_t for all t's in self._obs.positions.\n # all betas are scaled such that || beta_t ||_1 = 1.\n # beta vectors & scaling factors are not saved;\n # TODO describe what's save\n def _runBackwards(self):\n \n # pre-processing: compute auxilary matrices\n # beta_t = C*mats[j,d-1]*beta_(t+d), assuming\n # 1. O_(t+1) = ... = O_(t+d-1) = 0; and\n # 2. O_(t+d) = j.\n # (Where C is an arbitrary scaling constant)\n mats = self._calcBackwardMats()\n \n # initialize beta_(L-1) (beta_(L-1) (i) = 1.0 )\n beta = np.ones( self._nStates, dtype=np.float64 )\n \n # allocate ndarray for temporary variables\n tmpVec = np.empty( self._nStates, dtype=np.float64 )\n tmpMat = np.empty( (self._nStates, self._nStates), dtype=np.float64 )\n \n # initialize window histogram;\n # windowH[j,d-1] coressponds to windows [O_t, ..., O_t+d] where:\n # - We don't assume anything about O_t\n # - O_(t+1) = ... = O_(t+d-1) = 0.\n # - O_(t+d) = j\n windowH = np.zeros( (self._nEmissions, self._obs.maxDistance, self._nStates, self._nStates) , dtype=np.float64 )\n \n # move backwards window by window \n for ind in xrange(self._obs.nPositions - 2, -1, -1):\n \n # process window [pos_ind, pos_(ind+1)]; notice 'beta' variable corresponds to beta_(ind+1)\n d = self._obs.positions[ind+1] - self._obs.positions[ind]\n j = self._obs.posTypes[ind+1]\n \n np.outer(self._alpha[ind,:], beta, out=tmpMat)\n tmpMat *= mats[j, d-1, :, :]\n # normalize tmpMat to a matrix of probabilities\n # tmpMat (i,j) = Pr(state_ind = i, state_(ind+1)=j | entire observed sequence)\n tmpMat /= np.sum(tmpMat)\n windowH[j,d-1,:,:] += tmpMat\n \n # update beta from beta_(ind+1) to beta_ind\n np.dot(mats[j, d-1, :, :], beta, out=tmpVec)\n beta, tmpVec = tmpVec, beta\n \n # normalize beta (scale to sum to 1.0)\n beta /= np.sum(beta)\n \n # initialize result arrays\n resTransitions = np.zeros( (self._nStates, self._nStates ), dtype=np.float64 )\n resEmissions = np.zeros( (self._nStates, self._nEmissions), dtype=np.float64 )\n \n # Handle emmision from fisrt bp separately... gamma[0] = alpha[0]*beta[0]\n gammaZero = beta * self._alpha[0,:]\n gammaZero /= np.sum(gammaZero)\n resEmissions[:, self._obs.posTypes[0]] += gammaZero\n \n # The following section of the code\n # (Specifically: windowH[0, d-1, :, :] /= mats[0, d-1, :, :])\n # assumes that the matrices mats[j,d-1,:,:] don't have zero entries.\n assert np.count_nonzero(mats) == (self._nEmissions * self._obs.maxDistance * self._nStates * self._nStates)\n \n # parse the window histogram from largest to smallest\n for d in xrange(self._obs.maxDistance, 0, -1):\n \n # NOTE we could, instead, break windows in the middle (& handle emissions only & size 1)\n # The latter approach might be more stable numerically. \n \n # we now parse all windows windowH[:, d]\n \n # first, handle emissions from the last pb in the window\n for outputType in xrange(self._nEmissions):\n \n # consider window windowH[outputType, d]\n # to get the posterior state probabilities in the last bp, sum over columns\n # (i.e. compute gamma at postion pos_(ind+1), simultaneously for all windows of this type)\n np.sum(windowH[outputType, d-1, :, :], axis=0, out=tmpVec)\n \n # add this to the appropriate emission vec\n resEmissions[:, outputType] += tmpVec\n \n # now, handle transitions:\n # aggregate all windows of type [*,d] to single bin (type only mattered for emissions)\n for outputType in xrange(1,self._nEmissions):\n windowH[0, d-1, :, :] += windowH[outputType, d-1, :, :]\n \n # window-size d is now aggregated in windowH[0, d].\n \n if d > 1:\n # we'll break it in the bp before last, and attain\n # - one window of size (d-1), ending in output 0\n # - and one window of size 1 (don't care what output type in its end as we're done that emission)\n \n # How many windows are aggregated in this bin? (as all matrices added to the window sum to 1.0)\n nWindows = np.sum(windowH[0, d-1, :, :])\n windowH[0, d-1, :, :] /= LA.norm(windowH[0, d-1, :, :], ord=1)\n windowH[0, d-1, :, :] /= mats[0, d-1, :, :]\n \n # sub window of size (d-1):\n np.dot(windowH[0, d-1, :, :], mats[0, 0, :, :].T, out=tmpMat)\n tmpMat *= mats[0, d-2, :, :]\n tmpMat *= (nWindows/np.sum(tmpMat))\n windowH[0, d-2, :, :] += tmpMat \n \n # sub window of size 1:\n np.dot(mats[0, d-2, :, :].T, windowH[0, d-1, :, :], out=tmpMat)\n tmpMat *= mats[0, 0, :, :]\n tmpMat *= (nWindows/np.sum(tmpMat))\n resTransitions += tmpMat\n \n else:\n # d=1\n resTransitions += windowH[0, d-1, :, :]\n \n self._res = HiddenSeqSummary(self._obs.length, resTransitions, resEmissions, gammaZero, self._logLikelihood)\n \n # calc forward auxiliary mats\n def _calcForwardMats(self):\n # TODO am I missing a high precision float by choosing float64?\n mats = np.empty( (self._nEmissions, self._obs.maxDistance, self._nStates, self._nStates) , dtype=np.float64 )\n scales = np.empty( (self._nEmissions, self._obs.maxDistance) , dtype=np.float64 )\n \n # initilize mats for d = 1 (i.e. advancing one base pair)\n for outputType in xrange(self._nEmissions):\n for i in xrange(self._nStates):\n for j in xrange(self._nStates):\n # recurrence formula: alpha_(t+1)(j) = sum_i {alpha_t(i) * a_ij * b_j(O_t)}\n mats[outputType, 0, i, j] = self._transitionMat[j,i] * self._emissionMat[i,outputType]\n \n # normalize matrix to have L1 norm 1 (scaling)\n s = LA.norm(mats[outputType, 0, :, :],ord=1)\n mats[outputType, 0, :, :] /= s\n scales[outputType, 0] = np.log(s)\n \n # for blocks larger than 1, compute matrices recursively\n # if the last output is 0, notice mats[0,d-1] = mats[0,0] ^ d\n self._powerArray(mats[0, :, :, :], scales[0,:])\n # otherwise, mats[type,d-1] = mats[type,0] * mats[0,d-2]\n for outputType in xrange(1,self._nEmissions):\n for d in xrange(2, self._obs.maxDistance + 1):\n np.dot(mats[outputType, 0, :, :], mats[0, d-2, :, :], out=mats[outputType, d-1, :, :])\n \n # normalize matrix to have L1 norm 1 (scaling)\n s = LA.norm(mats[outputType, d-1, :, :],ord=1)\n mats[outputType, d-1, :, :] /= s\n scales[outputType, d-1] = scales[outputType, 0] + scales[0, d-2] + np.log(s)\n \n self._mats = mats\n self._matStatus = 'forward'\n return self._mats, scales\n \n # transpose self._mats\n def _calcBackwardMats(self):\n assert self._matStatus == 'forward'\n for outputType in xrange(self._nEmissions):\n for d in xrange(1, self._obs.maxDistance + 1):\n self._mats[outputType, d-1, :, :] = self._mats[outputType, d-1, :, :].T.copy()\n self._mats[outputType, d-1, :, :] /= LA.norm(self._mats[outputType, d-1, :, :],ord=1)\n \n self._matStatus = 'backward'\n return self._mats\n \n # calculate M^2, ..., M^n for a square m*m matrix M.\n # all matrices are scaled to have L1 norm of one.\n # A: a (n,m,m) ndarray, such that A[0,:,:]=M.\n # The result is stored such that A[i,:,:] = scaled(M^(i+1)) (i.e. M, M^2, ..., M^n)\n def _powerArray(self, A, scales):\n \n assert A.ndim == 3\n n = A.shape[0]\n assert A.shape[1] == A.shape[2]\n assert scales.shape == (n,)\n \n k = 1\n while k < n:\n for i in xrange(1, k+1):\n if (k+i) <= n:\n \n # calculate A^(k+i) = A^k * A^i\n np.dot(A[k-1,:,:], A[i-1,:,:], out=A[k+i-1,:,:])\n \n # rescale A^(k+i)\n s = LA.norm(A[k+i-1,:,:],ord=1)\n A[k+i-1,:,:] /= s\n scales[k+i-1] = np.log(s) + scales[k-1] + scales[i-1]\n \n k *= 2 \n","sub_path":"code/BaumWelchExpectation.py","file_name":"BaumWelchExpectation.py","file_ext":"py","file_size_in_byte":14717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"562745059","text":"from player import *\nimport random\nimport time\nfrom sounds import *\n\n\ndef showItems():\n print(player.inventory)\n\n# Main logic for items ################################333\n\n\ndef useItem():\n\n print(\"These are the items currently in your inventory: \",\n player.inventory.keys())\n useanitem = input(\"which item would you like to use? \")\n found = False\n\n for items in player.inventory:\n if items == useanitem:\n itemEffects(useanitem)\n playsound(songs[\"get-item\"])\n return True\n print(\"item not found in inventory\")\n\n############################## secondary item usage logic #############################\n\n\ndef itemEffects(itempicked):\n if itempicked == \"small potion\" or itempicked == \"medium potion\" or itempicked == \"super potion\":\n player.useHealthPotion(player.inventory[itempicked])\n print(\"You have restored {} HP, your health is now {}\".format(\n player.inventory[itempicked], player.getHealth()))\n removeItemFromInventory(itempicked)\n\n elif itempicked == \"speed potion\":\n player.useSpeedPotion(player.inventory[itempicked])\n print(\"You have increased {} Speed, your speed is now {}\".format(\n player.inventory[itempicked], player.getSpeed()))\n removeItemFromInventory(itempicked)\n\n elif itempicked == \"Bow\" or itempicked == \"Sword of Light\":\n player.setAttack(player.inventory[itempicked])\n print(\"You have now equipped {} , your attack is now {}\".format(\n player.inventory[itempicked], player.getAttack()))\n removeItemFromInventory(itempicked)\n\n\ndef removeItemFromInventory(item):\n player.inventory.pop(item)\n print(\"{} has been consumed! \".format(item))\n\n\ndef addItemToInvetory(player, item):\n player.inventory[item] = items[item]\n print(\"You have added {} to your inventory\".format(item))\n print(player.inventory)\n playsound(songs[\"get-item\"])\n\n\nitems = {\n \"small potion\": 20,\n \"medium potion\": 40,\n \"super potion\": 100,\n \"speed potion\": 30,\n \"Bow\": 45,\n \"Dagger\": 25,\n \"Sword of Light\": 80,\n \"Boots of Swiftness\": 50,\n \"Boss Key\": True\n}\n\n#addItemToInvetory(player, \"Bow\")\n","sub_path":"items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"240663889","text":"from __future__ import annotations\n\nimport json\nfrom datetime import date, datetime, timedelta\nfrom functools import reduce\nfrom typing import Any, Sequence\n\nimport numpy as np\nimport pytest\n\nimport polars as pl\nfrom polars.exceptions import PolarsInefficientMapWarning\nfrom polars.testing import assert_frame_equal\n\n\ndef test_apply_none() -> None:\n df = pl.DataFrame(\n {\n \"g\": [1, 1, 1, 2, 2, 2, 5],\n \"a\": [2, 4, 5, 190, 1, 4, 1],\n \"b\": [1, 3, 2, 1, 43, 3, 1],\n }\n )\n\n out = (\n df.group_by(\"g\", maintain_order=True).agg(\n pl.apply(\n exprs=[\"a\", pl.col(\"b\") ** 4, pl.col(\"a\") / 4],\n function=lambda x: x[0] * x[1] + x[2].sum(),\n ).alias(\"multiple\")\n )\n )[\"multiple\"]\n assert out[0].to_list() == [4.75, 326.75, 82.75]\n assert out[1].to_list() == [238.75, 3418849.75, 372.75]\n\n out_df = df.select(pl.map(exprs=[\"a\", \"b\"], function=lambda s: s[0] * s[1]))\n assert out_df[\"a\"].to_list() == (df[\"a\"] * df[\"b\"]).to_list()\n\n # check if we can return None\n def func(s: Sequence[pl.Series]) -> pl.Series | None:\n if s[0][0] == 190:\n return None\n else:\n return s[0]\n\n out = (\n df.group_by(\"g\", maintain_order=True).agg(\n pl.apply(\n exprs=[\"a\", pl.col(\"b\") ** 4, pl.col(\"a\") / 4], function=func\n ).alias(\"multiple\")\n )\n )[\"multiple\"]\n assert out[1] is None\n\n\ndef test_map_return_py_object() -> None:\n df = pl.DataFrame({\"A\": [1, 2, 3], \"B\": [4, 5, 6]})\n out = df.select([pl.all().map(lambda s: reduce(lambda a, b: a + b, s))])\n assert out.rows() == [(6, 15)]\n\n\ndef test_agg_objects() -> None:\n df = pl.DataFrame(\n {\n \"names\": [\"foo\", \"ham\", \"spam\", \"cheese\", \"egg\", \"foo\"],\n \"dates\": [\"1\", \"1\", \"2\", \"3\", \"3\", \"4\"],\n \"groups\": [\"A\", \"A\", \"B\", \"B\", \"B\", \"C\"],\n }\n )\n\n class Foo:\n def __init__(self, payload: Any):\n self.payload = payload\n\n out = df.group_by(\"groups\").agg(\n [\n pl.apply(\n [pl.col(\"dates\"), pl.col(\"names\")], lambda s: Foo(dict(zip(s[0], s[1])))\n )\n ]\n )\n assert out.dtypes == [pl.Utf8, pl.Object]\n\n\ndef test_map_elements_infer_list() -> None:\n df = pl.DataFrame(\n {\n \"int\": [1, 2],\n \"str\": [\"a\", \"b\"],\n \"bool\": [True, None],\n }\n )\n assert df.select([pl.all().map_elements(lambda x: [x])]).dtypes == [pl.List] * 3\n\n\ndef test_map_elements_arithmetic_consistency() -> None:\n df = pl.DataFrame({\"A\": [\"a\", \"a\"], \"B\": [2, 3]})\n with pytest.warns(\n PolarsInefficientMapWarning, match=\"In this case, you can replace\"\n ):\n assert df.group_by(\"A\").agg(pl.col(\"B\").map_elements(lambda x: x + 1.0))[\n \"B\"\n ].to_list() == [[3.0, 4.0]]\n\n\ndef test_map_elements_struct() -> None:\n df = pl.DataFrame(\n {\"A\": [\"a\", \"a\"], \"B\": [2, 3], \"C\": [True, False], \"D\": [12.0, None]}\n )\n out = df.with_columns(pl.struct(df.columns).alias(\"struct\")).select(\n pl.col(\"struct\").map_elements(lambda x: x[\"A\"]).alias(\"A_field\"),\n pl.col(\"struct\").map_elements(lambda x: x[\"B\"]).alias(\"B_field\"),\n pl.col(\"struct\").map_elements(lambda x: x[\"C\"]).alias(\"C_field\"),\n pl.col(\"struct\").map_elements(lambda x: x[\"D\"]).alias(\"D_field\"),\n )\n expected = pl.DataFrame(\n {\n \"A_field\": [\"a\", \"a\"],\n \"B_field\": [2, 3],\n \"C_field\": [True, False],\n \"D_field\": [12.0, None],\n }\n )\n\n assert_frame_equal(out, expected)\n\n\ndef test_apply_numpy_out_3057() -> None:\n df = pl.DataFrame(\n {\n \"id\": [0, 0, 0, 1, 1, 1],\n \"t\": [2.0, 4.3, 5, 10, 11, 14],\n \"y\": [0.0, 1, 1.3, 2, 3, 4],\n }\n )\n result = df.group_by(\"id\", maintain_order=True).agg(\n pl.apply([\"y\", \"t\"], lambda lst: np.trapz(y=lst[0], x=lst[1])).alias(\"result\")\n )\n expected = pl.DataFrame({\"id\": [0, 1], \"result\": [1.955, 13.0]})\n assert_frame_equal(result, expected)\n\n\ndef test_map_elements_numpy_int_out() -> None:\n df = pl.DataFrame({\"col1\": [2, 4, 8, 16]})\n result = df.with_columns(\n pl.col(\"col1\").map_elements(lambda x: np.left_shift(x, 8)).alias(\"result\")\n )\n expected = pl.DataFrame({\"col1\": [2, 4, 8, 16], \"result\": [512, 1024, 2048, 4096]})\n assert_frame_equal(result, expected)\n\n df = pl.DataFrame({\"col1\": [2, 4, 8, 16], \"shift\": [1, 1, 2, 2]})\n result = df.select(\n pl.struct([\"col1\", \"shift\"])\n .map_elements(lambda cols: np.left_shift(cols[\"col1\"], cols[\"shift\"]))\n .alias(\"result\")\n )\n expected = pl.DataFrame({\"result\": [4, 8, 32, 64]})\n assert_frame_equal(result, expected)\n\n\ndef test_datelike_identity() -> None:\n for s in [\n pl.Series([datetime(year=2000, month=1, day=1)]),\n pl.Series([timedelta(hours=2)]),\n pl.Series([date(year=2000, month=1, day=1)]),\n ]:\n assert s.map_elements(lambda x: x).to_list() == s.to_list()\n\n\ndef test_map_elements_list_anyvalue_fallback() -> None:\n with pytest.warns(\n PolarsInefficientMapWarning,\n match=r'(?s)replace your `map_elements` with.*pl.col\\(\"text\"\\).str.json_extract()',\n ):\n df = pl.DataFrame({\"text\": ['[{\"x\": 1, \"y\": 2}, {\"x\": 3, \"y\": 4}]']})\n assert df.select(pl.col(\"text\").map_elements(json.loads)).to_dict(False) == {\n \"text\": [[{\"x\": 1, \"y\": 2}, {\"x\": 3, \"y\": 4}]]\n }\n\n # starts with empty list '[]'\n df = pl.DataFrame(\n {\n \"text\": [\n \"[]\",\n '[{\"x\": 1, \"y\": 2}, {\"x\": 3, \"y\": 4}]',\n '[{\"x\": 1, \"y\": 2}]',\n ]\n }\n )\n assert df.select(pl.col(\"text\").map_elements(json.loads)).to_dict(False) == {\n \"text\": [[], [{\"x\": 1, \"y\": 2}, {\"x\": 3, \"y\": 4}], [{\"x\": 1, \"y\": 2}]]\n }\n\n\ndef test_map_elements_all_types() -> None:\n dtypes = [\n pl.UInt8,\n pl.UInt16,\n pl.UInt32,\n pl.UInt64,\n pl.Int8,\n pl.Int16,\n pl.Int32,\n pl.Int64,\n ]\n # test we don't panic\n for dtype in dtypes:\n pl.Series([1, 2, 3, 4, 5], dtype=dtype).map_elements(lambda x: x)\n\n\ndef test_map_elements_type_propagation() -> None:\n assert (\n pl.from_dict(\n {\n \"a\": [1, 2, 3],\n \"b\": [{\"c\": 1, \"d\": 2}, {\"c\": 2, \"d\": 3}, {\"c\": None, \"d\": None}],\n }\n )\n .group_by(\"a\", maintain_order=True)\n .agg(\n [\n pl.when(pl.col(\"b\").null_count() == 0)\n .then(\n pl.col(\"b\").map_elements(\n lambda s: s[0][\"c\"],\n return_dtype=pl.Float64,\n )\n )\n .otherwise(None)\n ]\n )\n ).to_dict(False) == {\"a\": [1, 2, 3], \"b\": [1.0, 2.0, None]}\n\n\ndef test_empty_list_in_map_elements() -> None:\n df = pl.DataFrame(\n {\"a\": [[1], [1, 2], [3, 4], [5, 6]], \"b\": [[3], [1, 2], [1, 2], [4, 5]]}\n )\n\n assert df.select(\n pl.struct([\"a\", \"b\"]).map_elements(\n lambda row: list(set(row[\"a\"]) & set(row[\"b\"]))\n )\n ).to_dict(False) == {\"a\": [[], [1, 2], [], [5]]}\n\n\ndef test_map_elements_skip_nulls() -> None:\n some_map = {None: \"a\", 1: \"b\"}\n s = pl.Series([None, 1])\n\n assert s.map_elements(lambda x: some_map[x]).to_list() == [None, \"b\"]\n assert s.map_elements(lambda x: some_map[x], skip_nulls=False).to_list() == [\n \"a\",\n \"b\",\n ]\n\n\ndef test_map_elements_object_dtypes() -> None:\n with pytest.warns(\n PolarsInefficientMapWarning,\n match=r\"(?s)replace your `map_elements` with.*lambda x:\",\n ):\n assert pl.DataFrame(\n {\"a\": pl.Series([1, 2, \"a\", 4, 5], dtype=pl.Object)}\n ).with_columns(\n [\n pl.col(\"a\").map_elements(lambda x: x * 2, return_dtype=pl.Object),\n pl.col(\"a\")\n .map_elements(\n lambda x: isinstance(x, (int, float)), return_dtype=pl.Boolean\n )\n .alias(\"is_numeric1\"),\n pl.col(\"a\")\n .map_elements(lambda x: isinstance(x, (int, float)))\n .alias(\"is_numeric_infer\"),\n ]\n ).to_dict(\n False\n ) == {\n \"a\": [2, 4, \"aa\", 8, 10],\n \"is_numeric1\": [True, True, False, True, True],\n \"is_numeric_infer\": [True, True, False, True, True],\n }\n\n\ndef test_map_elements_explicit_list_output_type() -> None:\n out = pl.DataFrame({\"str\": [\"a\", \"b\"]}).with_columns(\n [\n pl.col(\"str\").map_elements(\n lambda _: pl.Series([1, 2, 3]), return_dtype=pl.List(pl.Int64)\n )\n ]\n )\n\n assert out.dtypes == [pl.List(pl.Int64)]\n assert out.to_dict(False) == {\"str\": [[1, 2, 3], [1, 2, 3]]}\n\n\ndef test_map_elements_dict() -> None:\n with pytest.warns(\n PolarsInefficientMapWarning,\n match=r'(?s)replace your `map_elements` with.*pl.col\\(\"abc\"\\).str.json_extract()',\n ):\n df = pl.DataFrame({\"abc\": ['{\"A\":\"Value1\"}', '{\"B\":\"Value2\"}']})\n assert df.select(pl.col(\"abc\").map_elements(json.loads)).to_dict(False) == {\n \"abc\": [{\"A\": \"Value1\", \"B\": None}, {\"A\": None, \"B\": \"Value2\"}]\n }\n assert pl.DataFrame(\n {\"abc\": ['{\"A\":\"Value1\", \"B\":\"Value2\"}', '{\"B\":\"Value3\"}']}\n ).select(pl.col(\"abc\").map_elements(json.loads)).to_dict(False) == {\n \"abc\": [{\"A\": \"Value1\", \"B\": \"Value2\"}, {\"A\": None, \"B\": \"Value3\"}]\n }\n\n\ndef test_map_elements_pass_name() -> None:\n df = pl.DataFrame(\n {\n \"bar\": [1, 1, 2],\n \"foo\": [1, 2, 3],\n }\n )\n\n mapper = {\"foo\": \"foo1\"}\n\n def element_mapper(s: pl.Series) -> pl.Series:\n return pl.Series([mapper[s.name]])\n\n assert df.group_by(\"bar\", maintain_order=True).agg(\n pl.col(\"foo\").map_elements(element_mapper, pass_name=True),\n ).to_dict(False) == {\"bar\": [1, 2], \"foo\": [[\"foo1\"], [\"foo1\"]]}\n\n\ndef test_map_elements_binary() -> None:\n assert pl.DataFrame({\"bin\": [b\"\\x11\" * 12, b\"\\x22\" * 12, b\"\\xaa\" * 12]}).select(\n pl.col(\"bin\").map_elements(bytes.hex)\n ).to_dict(False) == {\n \"bin\": [\n \"111111111111111111111111\",\n \"222222222222222222222222\",\n \"aaaaaaaaaaaaaaaaaaaaaaaa\",\n ]\n }\n\n\ndef test_map_no_dtype_set_8531() -> None:\n assert (\n pl.DataFrame({\"a\": [1]})\n .with_columns(\n pl.col(\"a\").map(lambda x: x * 2).shift_and_fill(fill_value=0, periods=0)\n )\n .item()\n == 2\n )\n\n\ndef test_map_elements_set_datetime_output_8984() -> None:\n df = pl.DataFrame({\"a\": [\"\"]})\n payload = datetime(2001, 1, 1)\n assert df.select(\n pl.col(\"a\").map_elements(lambda _: payload, return_dtype=pl.Datetime),\n )[\"a\"].to_list() == [payload]\n\n\ndef test_err_df_apply_return_type() -> None:\n df = pl.DataFrame({\"a\": [[1, 2], [2, 3]], \"b\": [[4, 5], [6, 7]]})\n\n def cmb(row: tuple[Any, ...]) -> list[Any]:\n res = [x + y for x, y in zip(row[0], row[1])]\n return [res]\n\n with pytest.raises(pl.ComputeError, match=\"expected tuple, got list\"):\n df.apply(cmb)\n\n\ndef test_apply_shifted_chunks() -> None:\n df = pl.DataFrame(pl.Series(\"texts\", [\"test\", \"test123\", \"tests\"]))\n assert df.select(\n pl.col(\"texts\"), pl.col(\"texts\").shift(1).alias(\"texts_shifted\")\n ).apply(lambda x: x).to_dict(False) == {\n \"column_0\": [\"test\", \"test123\", \"tests\"],\n \"column_1\": [None, \"test\", \"test123\"],\n }\n\n\ndef test_map_elements_dict_order_10128() -> None:\n df = pl.select(pl.lit(\"\").map_elements(lambda x: {\"c\": 1, \"b\": 2, \"a\": 3}))\n assert df.to_dict(False) == {\"literal\": [{\"c\": 1, \"b\": 2, \"a\": 3}]}\n\n\ndef test_map_elements_10237() -> None:\n df = pl.DataFrame({\"a\": [1, 2, 3]})\n assert (\n df.select(pl.all().map_elements(lambda x: x > 50))[\"a\"].to_list() == [False] * 3\n )\n\n\ndef test_map_elements_on_empty_col_10639() -> None:\n df = pl.DataFrame({\"A\": [], \"B\": []})\n res = df.group_by(\"B\").agg(\n pl.col(\"A\")\n .map_elements(lambda x: x, return_dtype=pl.Int32, strategy=\"threading\")\n .alias(\"Foo\")\n )\n assert res.to_dict(False) == {\n \"B\": [],\n \"Foo\": [],\n }\n res = df.group_by(\"B\").agg(\n pl.col(\"A\")\n .map_elements(lambda x: x, return_dtype=pl.Int32, strategy=\"thread_local\")\n .alias(\"Foo\")\n )\n assert res.to_dict(False) == {\n \"B\": [],\n \"Foo\": [],\n }\n\n\ndef test_apply_deprecated() -> None:\n with pytest.deprecated_call():\n pl.col(\"a\").apply(lambda x: x + 1)\n with pytest.deprecated_call():\n pl.Series([1, 2, 3]).apply(lambda x: x + 1)\n","sub_path":"py-polars/tests/unit/operations/test_map.py","file_name":"test_map.py","file_ext":"py","file_size_in_byte":12962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"53088800","text":"import math\n\ndef dot(v1, v2) :\n return sum(x1*x2 for x1,x2 in zip(v1,v2))\n \nepsilon = math.sqrt(7/3 - 4/3 - 1)\n\ndef linear_newton(fprime, fhess_p, x, d, newton_tol, newton_maxiter) :\n delta_d = dot(d, d)\n print('d:', d)\n alpha = 1 / newton_tol\n for __ in range(newton_maxiter) :\n alpha_old = alpha\n alpha = - dot(fprime(x), d) / dot(d, fhess_p(x, d))\n if abs(alpha / alpha_old) > 1 :\n break\n print('alpha:', alpha)\n x = tuple(xi + alpha * di for xi, di in zip(x, d))\n if alpha*alpha*delta_d < newton_tol :\n break\n return alpha, x\n\ndef linear_secant(fprime, x, d, tol, maxiter, sigma0) :\n delta_d = dot(d, d)\n print('d:', d)\n alpha = -sigma0\n ita_prev = dot(d, fprime(tuple(xi+sigma0*di for xi,di in zip(x,d))))\n for __ in range(maxiter) :\n ita = dot(d, fprime(x))\n rat = ita / (ita_prev - ita)\n if __ > 0 and abs(rat) > 1 : break\n alpha *= rat\n print('alpha:', alpha)\n x = tuple(xi + alpha * di for xi, di in zip(x, d))\n if alpha*alpha*delta_d < tol :\n break\n return alpha, x\n \ndef nonlinear_cg(f, x0, fprime=None, epsilon=epsilon, tol=1e-9, maxiter=None, \n linear=linear_secant, linear_tol=1e-5, linear_maxiter=4, \n sigma0=0.1, \n approx_hessian=False,\n callback=None) :\n \"\"\"\n Minimize a function using a nonlinear conjugate gradient algorithm\n with Secant and PR. \n NR: Newton-Rahson, PR: Polak-Ribiere, FR: Fletcher-Reeves.\n \"\"\"\n nx = len(x0)\n if maxiter == None : \n maxiter = 200 * nx\n if fprime == None :\n def fprime(x) :\n x = list(x)\n xeps = tuple(xi * epsilon if xi!=0 else epsilon for xi in x)\n f0 = f(x)\n ans = list()\n for i in range(nx) :\n old = x[i]\n x[i] += xeps[i]\n ans.append((f(x)-f0)/xeps[i])\n x[i] = old\n# print('fprime:', ans)\n return ans\n ## define fhess_p(d) for $ f''(x) \\dot d\n if approx_hessian :\n def fhess_p(x, d) :\n pass\n else :\n def fhess_p(x, d) :\n x = list(x)\n esqr = epsilon * epsilon\n xeps = tuple(xi * epsilon if xi!=0 else epsilon for xi in x)\n ans = list()\n f0 = f(x)\n fp = list()\n for i in range(nx) :\n oldxi = x[i]\n x[i] += xeps[i]\n fp.append(f(x))\n ansi = 0\n for j in range(i) :\n oldxj = x[j]\n x[j] += xeps[j]\n t1 = (f(x) - fp[i])\n t2 = (- fp[j] + f0)\n ansi += (t1 + t2) * d[j]\n x[j] = oldxj\n ansi *= 2\n x[i] = oldxi + 2*xeps[i]\n t1 = (f(x) - fp[i])\n t2 = (-fp[i] + f0)\n ansi += (t1 + t2) * d[i]\n ans.append(ansi)\n x[i] = oldxi\n ans = tuple(x / (esqr) for x in ans)\n# print('fhess_p:', ans)\n return ans\n \n k = 0\n x = x0\n r = tuple(-xi for xi in fprime(x))\n d = r\n delta_old = 0\n delta_new = dot(r, r)\n delta_0 = delta_new\n for _ in range(maxiter) :\n print('iter:', _)\n print('delta_new:', delta_new , tol * delta_0)\n if delta_new < tol :#* delta_0 :\n# print('abs:', abs(delta_new - delta_old))\n# if abs(delta_new - delta_old) < tol :\n break\n if linear == linear_secant :\n alpha, x = linear_secant(fprime, x, d, linear_tol, linear_maxiter, sigma0)\n else :\n alpha, x = linear_newton(fprime, fhess_p, x, d, linear_tol, linear_maxiter)\n #x = tuple(min(0,xi) for xi in x)\n r_old = r\n r = tuple(-xi for xi in fprime(x))\n delta_old = delta_new\n delta_mid = dot(r, r_old)\n delta_new = dot(r, r)\n beta = max(0, (delta_new - delta_mid) / delta_old)\n d = tuple(ri + beta * di for ri, di in zip(r, d))\n# k += 1\n# if k == nx or beta <= 0 :#dot(r, d) <= 0 :\n# d = r\n# k = 0\n if callback : callback(x)\n \n return x\n \"\"\"\n Parameters\n ----------\n f : callable, ``f(x, *args)``\n Objective function to be minimized. Here `x` must be a 1-D array of\n the variables that are to be changed in the search for a minimum, and\n `args` are the other (fixed) parameters of `f`.\n x0 : tuple\n A user-supplied initial estimate of `xopt`, the optimal value of `x`.\n It must be a 1-D array of values.\n fprime : callable, ``fprime(x, *args)``, optional\n A function that returns the gradient of `f` at `x`. Here `x` and `args`\n are as described above for `f`. The returned value must be a 1-D array.\n Defaults to None, in which case the gradient is approximated\n numerically (see `epsilon`, below).\n args : tuple, optional\n Parameter values passed to `f` and `fprime`. Must be supplied whenever\n additional fixed parameters are needed to completely specify the\n functions `f` and `fprime`.\n gtol : float, optional\n Stop when the norm of the gradient is less than `gtol`.\n norm : float, optional\n Order to use for the norm of the gradient\n (``-np.Inf`` is min, ``np.Inf`` is max).\n epsilon : float or ndarray, optional\n Step size(s) to use when `fprime` is approximated numerically. Can be a\n scalar or a 1-D array. Defaults to ``sqrt(eps)``, with eps the\n floating point machine precision. Usually ``sqrt(eps)`` is about\n 1.5e-8.\n maxiter : int, optional\n Maximum number of iterations to perform. Default is ``200 * len(x0)``.\n full_output : bool, optional\n If True, return `fopt`, `func_calls`, `grad_calls`, and `warnflag` in\n addition to `xopt`. See the Returns section below for additional\n information on optional return values.\n disp : bool, optional\n If True, return a convergence message, followed by `xopt`.\n retall : bool, optional\n If True, add to the returned values the results of each iteration.\n callback : callable, optional\n An optional user-supplied function, called after each iteration.\n Called as ``callback(xk)``, where ``xk`` is the current value of `x0`.\n\n Returns\n -------\n xopt : ndarray\n Parameters which minimize f, i.e. ``f(xopt) == fopt``.\n fopt : float, optional\n Minimum value found, f(xopt). Only returned if `full_output` is True.\n func_calls : int, optional\n The number of function_calls made. Only returned if `full_output`\n is True.\n grad_calls : int, optional\n The number of gradient calls made. Only returned if `full_output` is\n True.\n warnflag : int, optional\n Integer value with warning status, only returned if `full_output` is\n True.\n\n 0 : Success.\n\n 1 : The maximum number of iterations was exceeded.\n\n 2 : Gradient and/or function calls were not changing. May indicate\n that precision was lost, i.e., the routine did not converge.\n\n allvecs : list of ndarray, optional\n List of arrays, containing the results at each iteration.\n Only returned if `retall` is True.\n\n References\n ----------\n .. [1] Jonathan Richard Shewchuk, \"An Introduction to the Conjugate Gradient Method Without the Agonizing Pain\", 1994.\n \"\"\"\n \nif __name__ == '__main__' :\n def f(w) :\n x, y = w\n return (#(x-1)**2 + (y-2)**2\n (1-x)**2 + 100 * (y - x*x)**2\n )\n nonlinear_cg(f, (0,0), callback=print)\n","sub_path":"cg.py","file_name":"cg.py","file_ext":"py","file_size_in_byte":7800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"521863470","text":"#!/usr/bin/env python\n# encoding: utf-8\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\n\"\"\"This module contains helper functions used across the package namespace.\n\"\"\"\n\nimport os\nimport hmac\nimport hashlib\nfrom uuid import uuid1 as uuid\nfrom base64 import b64encode\nfrom urllib import urlencode\nfrom functools import wraps\n\nfrom flask import request, make_response, render_template\n\nfrom ec2stack.services import USERS\nfrom ec2stack import errors\n\n\ndef get(item, data=None):\n \"\"\"\n Gets the specified item in the given data.\n\n @param item: Key of the item.\n @param data: Data the item is in.\n @return: Item if found, otherwise None.\n \"\"\"\n if data is None:\n data = request.form\n\n if item in data:\n return data[item]\n else:\n return None\n\n\ndef authentication_required(f):\n \"\"\"\n Check that the given signature is valid.\n\n @param f: Function to wrap around.\n @return: Result of signature check.\n \"\"\"\n\n @wraps(f)\n def decorated(*args, **kwargs):\n required_params = {'Action', 'AWSAccessKeyId', 'Signature',\n 'SignatureMethod', 'SignatureVersion', 'Timestamp',\n 'Version'}\n require_parameters(required_params)\n\n _valid_signature_method()\n _valid_signature_version()\n _valid_signature()\n return f(*args, **kwargs)\n\n return decorated\n\n\ndef normalize_dict_keys(dct):\n \"\"\"\n Normalizes all keys in the given dictionary.\n\n @param dct: Dictionary to normalize.\n @return: Dictionary normalized.\n \"\"\"\n return dict((key.lower(), value) for key, value in dct.iteritems())\n\n\ndef require_parameters(required_parameters):\n \"\"\"\n Checks that the given array of parameters are present.\n\n @param required_parameters: Array of required parameters.\n \"\"\"\n for parameter in required_parameters:\n if not contains_parameter(parameter):\n errors.missing_parameter(parameter)\n\n\ndef require_atleast_one_parameter(parameters):\n \"\"\"\n Require atleast one parameter.\n\n @param parameters: Array of possible parameters.\n @return: void.\n \"\"\"\n parameter = None\n for parameter in parameters:\n if contains_parameter(parameter):\n return\n\n errors.missing_parameter(parameter)\n\n\ndef contains_parameter(parameter, data=None):\n \"\"\"\n Checks if the parameter is contained within the given data.\n\n @param parameter: Parameter to check.\n @param data: Data to check in.\n @return: Boolean.\n \"\"\"\n if data is None:\n data = request.form\n\n return (get(parameter, data)) is not None\n\n\ndef contains_parameter_with_keyword(prefix):\n \"\"\"\n Checks if the request contains parameters with the given prefix.\n\n @param prefix: Prefix of parameters.\n @return: Boolean.\n \"\"\"\n return len(get_request_parameter_keys(prefix)) >= 1\n\n\ndef get_request_parameter_keys(prefix, data=None):\n \"\"\"\n Gets all parameters containing prefix.\n\n @param prefix: Prefix of parameters.\n @param data: Data to search.\n @return: List of matching parameters.\n \"\"\"\n if data is None:\n data = request.form\n\n return [item for item in data if prefix in item]\n\n\ndef get_secretkey(data=None):\n \"\"\"\n Get the secret key from the database.\n\n @param data: Data to get the API KEY from.\n @return: The users secret key.\n @raise Ec2stackError: if the secretkey is not found.\n \"\"\"\n if data is None:\n data = request.form\n\n apikey = get('AWSAccessKeyId', data)\n user = USERS.get(apikey)\n\n if user is None:\n errors.apikey_not_found(apikey)\n\n return user.secretkey.encode('utf-8')\n\n\ndef _valid_signature_method():\n \"\"\"\n Check that the given signature method is correct.\n\n @raise Ec2stackError: if the signature method is invalid.\n \"\"\"\n signature_method = get('SignatureMethod')\n if signature_method not in ['HmacSHA1', 'HmacSHA256']:\n errors.invalid_parameter_value(\n 'Value (%s) for parameter SignatureMethod is invalid. '\n 'Unknown signature method.' % signature_method\n )\n\n\ndef _valid_signature_version():\n \"\"\"\n Checks that the given signature version is correct.\n\n @raise Ec2stackError: if the signature version is invalid.\n \"\"\"\n signature_version = get('SignatureVersion')\n if signature_version != '2':\n errors.invalid_parameter_value(\n 'Value (%s) for parameter SignatureVersion is invalid.'\n 'Valid Signature versions are 2.'\n % signature_version\n )\n\n\ndef _valid_signature():\n \"\"\"\n Checks that the given signature matches the signature generated.\n\n @raise Ec2stackError: if the signature does not match the generated\n signature.\n \"\"\"\n signature = get('Signature')\n generated_signature = generate_signature()\n\n if signature != generated_signature:\n errors.authentication_failure()\n\n\ndef generate_signature(data=None, method=None, host=None, path=None):\n \"\"\"\n Generates a signature.\n\n @param data: Data of the request.\n @param method: HTTP method used.\n @param host: HTTP post.\n @param path: HTTP hort.\n @return: A signature.\n \"\"\"\n if data is None:\n data = request.form\n\n signature_type = get('SignatureMethod', data)\n\n secretkey = get_secretkey(data)\n request_string = _get_request_string(data, method, host, path)\n\n if signature_type == 'HmacSHA1':\n digestmod = hashlib.sha1\n else:\n digestmod = hashlib.sha256\n\n signature = hmac.new(\n key=secretkey,\n msg=bytes(request_string),\n digestmod=digestmod\n ).digest()\n\n signature = b64encode(signature)\n\n return signature\n\n\ndef _get_request_string(data, method=None, host=None, path=None):\n \"\"\"\n Creates the request string.\n\n @param data: Data of the request.\n @param method: HTTP method used.\n @param host: HTTP host.\n @param path: HTTP path.\n @return: Request string.\n \"\"\"\n if method is None:\n method = request.method\n if host is None:\n host = request.host\n if path is None:\n path = request.path\n\n query_string = _get_query_string(data)\n\n request_string = '\\n'.join(\n [method, host, path, query_string]\n )\n\n return request_string.encode('utf-8')\n\n\ndef _get_query_string(data):\n \"\"\"\n Creates the query string.\n\n @param data: Data of the request.\n @return: Query String.\n \"\"\"\n params = {}\n for param in data:\n if param != 'Signature':\n params[param] = data[param]\n\n keys = sorted(params.keys())\n values = map(params.get, keys)\n\n query_string = urlencode(\n list(\n zip(keys, values)\n )\n )\n\n query_string = query_string.replace('+', '%20')\n\n return query_string\n\n\ndef error_response(code, error, message):\n \"\"\"\n Returns a error response.\n\n @param code: Status code.\n @param error: Error type.\n @param message: Error message.\n @return: Response.\n \"\"\"\n response = make_response(\n render_template(\n 'generic_error.xml',\n response_type='Response',\n error=error,\n message=message,\n request_id=uuid()\n )\n )\n return _create_response(response, int(code))\n\n\ndef successful_response(**kwargs):\n \"\"\"\n Returns a successful response.\n\n @param kwargs: Parameters to render the template with.\n @return: Response.\n \"\"\"\n api_version = str(get(\"Version\"))\n content = render_template(\n request_id=uuid(), api_version=api_version, **kwargs)\n response = make_response(content)\n return _create_response(response, '200')\n\n\ndef _create_response(response, code):\n \"\"\"\n Creates a response.\n\n @param response: Response to use.\n @param code: Status code of the response.\n @return: Response.\n \"\"\"\n response.headers['Content-Type'] = 'application/xml'\n response.status_code = int(code)\n return response\n\n\ndef read_file(name):\n \"\"\"\n Reads the given file.\n\n @param name: Filename of the file to read.\n @return: Contents of the file.\n \"\"\"\n filepath = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n '../',\n name\n )\n data = open(filepath)\n return data.read()\n","sub_path":"ec2stack/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":9041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"526893637","text":"\r\n\"\"\"Write a program that outputs the first recurring character in a string.\"\"\"\r\ndef main():\r\n inp = input(\"Enter you input: \")\r\n search(inp)\r\n\r\ndef search(inp):\r\n for i, char in enumerate(inp): #use enumerate more\r\n if char in inp[i+1:]: #very easy compare\r\n print(char)\r\n break\r\n else:\r\n print(\"No recurring char\")\r\n\r\nmain()\r\n\r\n","sub_path":"FirstRecurringChar.py","file_name":"FirstRecurringChar.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"534842059","text":"class Names:\n name = \"mates\"\n def tian(self):\n print(\"田凯旋\")\n def guo(self):\n print(\"郭东劼\")\n def fang(self):\n print(\"方锋\")\n\nclass Initi:\n def prin(self):\n print(\"这是一���初始化语句\")\n self.name = \"名字\"\n\n\nclass Initi2:\n def name2(self,nameIn):\n print(\"这是初始化语句\")\n self.Name = nameIn\n\n\nworkers = Names()\nworkers.fang()\nworkers.guo()\nworkers.heigh = 170\n\notherWorkers = Names()\notherWorkers.age = 16\n\nprint(workers)\n\naddr1 = id(workers)\naddr2 = id(otherWorkers)\n\na = otherWorkers.age\nh = workers.heigh\n\nprint(\"workers\\t\\t对应的内存地址是%x\" % addr1)\nprint(\"otherWorkers\\t对应的内存地址是%x\" % addr2)\nprint(\"otheWorkers\\t的年龄是%d\" % a)\nprint(\"workers\\t\\t的身高是%d\" % h)\n\nini = Initi()\nini.prin()\nn = ini.name\nprint(n)\n\nini2 = Initi2(\"田\")\nprint(ini2.Name)","sub_path":"Learning/CodePython/00_test/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"336237481","text":"from brian2 import *\nimport functions\n\n\nclass ThresholdModel:\n def __init__(self, param):\n self.reshaped_spikemon = None\n self.variance_spike_times = None\n self.mean_spike_times = None\n self.number_spiking_cells = None\n self.number_spiking_outside_trajectory = None\n self.variance_spikes_trajectory = None\n self.mean_spikes_trajectory = None\n self.p = self._complete_parameters(param)\n self.has_run = False\n self.delay = None\n self.PC_spiking_times = None\n self.INH_spiking_times = None\n\n self._param_sanity_checks(self.p)\n self._init_pyramidal_neurons()\n self._init_inhibitory_neurons()\n\n self._init_standard_synapses()\n\n # Trajectory\n\n # Noise\n self.N_spiking_times = None\n self._init_noise_neurons()\n self._init_noise_synapses()\n\n # Random\n self._init_random_input()\n self._init_random_synapses()\n\n self.neuron_idx = 50\n self.my_indices = functions.some_indices(self.neuron_idx)\n\n # For plotting purposes\n self.excitatory_matrix = np.zeros([self.p['rows'], self.p['cols']])\n\n # Print the parameters. Helps for debugging\n def print_param(self, type_list=['INH']):\n for type_ in type_list:\n if type_ == 'INH':\n print('INH : ')\n print(\"v_leak_inh \", self.p[\"v_leak_inh\"])\n print(\"v_reset_inh \", self.p[\"v_reset_inh\"])\n print(\"v_thr_inh \", self.p[\"v_thr_inh\"])\n print(\"tau_dyn_inh \", self.p[\"tau_dyn_inh\"])\n print(\"tau_refr_inh \", self.p[\"tau_refr_inh\"])\n elif type_ == 'S':\n print('S : ')\n print(\"v_reset_ext \", self.p[\"v_reset_ext\"])\n print(\"v_leak_ext \", self.p[\"v_leak_ext\"])\n print(\"v_thr_ext \", self.p[\"v_thr_ext\"])\n print(\"tau_dyn_ext \", self.p[\"tau_dyn_ext\"])\n print(\"tau_refr_ext \", self.p[\"tau_refr_ext\"])\n\n def set_delay(self, new_delay):\n self.delay = new_delay\n\n def reset_neuron_idx(self, neuron_idx):\n self.neuron_idx = neuron_idx\n\n def reset_neuron_idx(self, list_neurons):\n self.my_indices = list_neurons\n\n # updates parameters of model with p a dictionary of parameters\n def _complete_parameters(self, p):\n genericParam = {\n 'rows': 20,\n 'cols': 30,\n \"thresh_step\": 0.2,\n\n # Excitatory neurons\n \"v_init_exc\": -60, # Initial value of potential\n \"v_leak_exc\": -68, # Leak potential\n \"v_reset_exc\": -60, # Reset potential\n \"v_thr_exc\": -36, # Spiking threshold\n 'tau_dyn_exc': 50 * ms, # Leak timescale\n \"tau_refr_exc\": 8 * ms, # Refractory period\n \"r_max_exc\": 20 * Hz, # Maximum rate\n 'rec_weight': 7, # Recurrent weight\n \"lambda_PL_exc\": 0.15 * metre, # ???\n\n # Inhibitory neurons\n \"num_inhib_neurons\": 10,\n \"v_leak_inh\": -10, # Leak potential\n \"v_reset_inh\": -80, # Reset potential\n \"v_thr_inh\": -50, # Spiking threshold\n 'tau_dyn_inh': 50 * ms, # Leak timescale\n \"tau_refr_inh\": 2 * ms, # Refractory period\n \"gi_inh\": 1, # ???\n \"inh_weight_pi\": 0.02,\n \"inh_weight_ip\": 0.01,\n #\n # # Noise Neurons\n \"num_tonic_noise\": 20, # Number of tonic neurons\n \"v_leak_noise\": -30, # Leak potential\n \"v_reset_noise\": -80, # Reset potential\n \"v_thr_noise\": -50, # Spiking threshold\n 'tau_dyn_noise': 5 * ms, # Leak timescale\n \"tau_refr_noise\": 2 * ms, # Refractory period\n \"gi_noise\": 1, # ???\n \"noise_weight\": 0.03, # Tonic weight\n\n # Random inputs\n \"num_random_neurons\": 20,\n \"v_leak_random\": -30, # Leak potential\n \"v_reset_random\": -80, # Reset potential\n \"v_thr_random\": -50, # Spiking threshold\n \"input_rate\": 50 * Hz, # Rate of spikes for the\n 'R_weight': 3,\n \"tau_dyn_random\": 5 * ms, # Leak timescale\n\n # Synapses\n \"w_PC\": 0.5, # Recurrent weight from PC to PC\n \"w_PCINH\": 0.7, # Weight PC to INH\n \"w_INHPC\": 0.5, # Weight INH to PC\n \"w_GPC\": 0.9, # Weight G to PC\n \"w_SPC\": 0.8 # Weigth S to PC\n }\n\n pnew = p\n for k, v in genericParam.items():\n if k not in p.keys():\n pnew[k] = v\n else:\n pnew[k] = p[k]\n\n return pnew\n\n def _param_sanity_checks(self, p):\n pass\n\n # If want to modify parameters after creating the class, before running\n def modify_param(self, p):\n if self.has_run:\n raise Warning(\"The network already ran thus the change of parameters should have no impact\")\n\n for element in p.keys():\n self.p[element] = p[element]\n\n # Initialises the pyramidal neurons as a Brian2 NeuronGroup.\n def _init_pyramidal_neurons(self):\n\n # v_leak_exc\n eqs_exc = '''\n dv/dt = (- (v - v_leak_exc)) / tau : 1\n dh/dt = (- (h + 36)) / tau :1\n thresh_step : 1\n x : metre\n y : metre\n tau : second\n '''\n\n # Here the threshold lowers if the neuron spikes\n self.PC = NeuronGroup(self.p['rows'] * self.p['cols'], eqs_exc, threshold='v>h',\n reset='v = v_reset_exc; h = h - 2', refractory=self.p[\"tau_refr_exc\"],\n method='euler')\n # thresh_step\n self.PC.thresh_step = self.p['thresh_step']\n\n # initialize the grid positions\n\n # Variables important for Brian purposes (the equations are written with strings).\n rows = self.p['rows']\n grid_dist = 4 * meter\n self.PC.tau = self.p['tau_dyn_exc']\n # x and y position on the grid of the cells.\n self.PC.x = '(i // rows) * grid_dist'\n self.PC.y = '(i % rows) * grid_dist'\n # Initialises voltage\n self.PC.v = self.p['v_init_exc']\n self.PC.h = -36\n\n # Initialises the inhibitory neurons as a Brian2 NeuronGroup.\n def _init_noise_neurons(self):\n eqs_inh = '''\n dv/dt = ( - (v - v_leak_noise)) / tau : 1\n tau : second\n '''\n # int(self.p['rows'] * self.p['cols'] / 10)\n self.N = NeuronGroup(int(self.p['rows'] * self.p['cols'] / 10), eqs_inh, threshold='v>v_thr_noise',\n reset='v = v_reset_noise', refractory=self.p['tau_refr_noise'], method='euler')\n self.N.tau = self.p['tau_dyn_noise']\n self.N.v = self.p['v_reset_noise']\n\n def _init_inhibitory_neurons(self):\n eqs_inh = '''\n dv/dt = ( - (v - v_leak_inh)) / tau : 1\n tau : second\n '''\n # int(self.p['rows'] * self.p['cols'] / 10)\n self.INH = NeuronGroup(int(self.p['rows'] * self.p['cols'] / 10), eqs_inh, threshold='v>v_thr_inh',\n reset='v = v_reset_inh', refractory=self.p['tau_refr_inh'], method='euler')\n self.INH.tau = self.p['tau_dyn_inh']\n self.INH.v = self.p['v_reset_inh']\n\n def _init_random_input(self):\n # self.R = PoissonGroup(self.p['num_tonic_neurons'],rates=self.p['input_rate'])\n\n eqs_tonic = '''\n dv/dt = ( - (v - v_leak_random)) / tau : 1\n tau : second\n '''\n\n self.R = NeuronGroup(self.p['num_random_neurons'], eqs_tonic, threshold='v>v_thr_random',\n reset='v = v_reset_random',\n refractory=50 * ms, method='euler')\n self.R.tau = self.p['tau_dyn_random']\n self.R.v = -80\n\n # Initialises all the synapses\n def _init_standard_synapses(self):\n # Needed for brian2 equations\n rows = self.p['rows']\n cols = self.p['cols']\n weight = self.p['rec_weight']\n ###########################\n # EXC-EXC synapses\n ###########################\n self.SPC = Synapses(self.PC, self.PC, 'w:1', on_pre='v_post += w')\n self.SPC.connect('(( i // rows - j // rows)**2 + ( i % rows - j % rows)**2 )< 4')\n # self.SPC.connect()\n self.SPC.w = 'weight*exp(-((x_pre-x_post)**2+(y_pre - y_post)**2)/(30*metre)**2)'\n\n # If already specified the delay to put, don't modify it.\n if self.delay != None:\n self.SPC.delay = self.delay\n else:\n # self.SPC.delay = '(2 - 2*exp(-(abs(x_pre-x_post)+abs(y_pre - y_post))/(30*metre))) * second'\n self.SPC.delay = '(((x_pre-x_post)**2+(y_pre - y_post)**2)/(50*metre)**2) * second'\n\n ###########################\n # EXC-INH and INH-EXC synapses\n ###########################\n self.SPCINH = Synapses(self.INH, self.PC, 'w:1', on_pre='v_post-=w')\n self.SPCINH.connect(p=0.5)\n self.SPCINH.w = self.p[\"inh_weight_pi\"]\n\n self.SINHPC = Synapses(self.PC, self.INH, 'w:1', on_pre='v_post+=w')\n self.SINHPC.connect(p=0.5)\n\n self.SINHPC.w = self.p[\"inh_weight_ip\"]\n\n # Synapses that connect the noise neurons N to cells inside the trajectory\n def _init_noise_synapses(self):\n\n ##############################################\n # NOISE-(EXC inside the trajectory) synapses\n ##############################################\n # Draws the trajectory\n\n self.SPCN = Synapses(self.N, self.PC, 'w:1', on_pre='v_post+=w')\n sources, targets = functions.convert_matrix_to_source_target(self.p['connection_matrix_S'])\n self.SPCN.connect(i=sources, j=targets, p=1)\n self.SPCN.w = 2 * self.p['noise_weight']\n\n # Synapses that connect the noise neurons N to cells outside the trajectory\n def _init_noise_synapses_2(self):\n\n ##############################################\n # NOISE-(EXC outside the trajectory) synapses\n ##############################################\n # Draws the trajectory\n\n # Matrix that has 1 outside trajectory and 0 inside\n connection_matrix = np.ones(np.shape(self.p['connection_matrix_S'])) + (-1) * self.p['connection_matrix_S']\n\n self.SPCN2 = Synapses(self.N, self.PC, 'w:1', on_pre='v_post+=w')\n sources, targets = functions.convert_matrix_to_source_target(connection_matrix)\n self.SPCN2.connect(i=sources, j=targets, p=0.5)\n self.SPCN2.w = self.p['noise_weight']\n\n # Synapses that connect the random neurons R to pyramidal cells\n def _init_random_synapses(self):\n ###########################\n # RANDOM - EXC synapses\n ###########################\n self.SRPC = Synapses(self.R, self.PC, 'w:1', on_pre='v_post+=w')\n self.SRPC.connect(p=0.01)\n self.SRPC.w = self.p['R_weight']\n\n # TODO: Find better way to record spike moments\n def run(self, duration=50 * ms, show_PC=False, show_other=False):\n # If show_ = True, then plots voltages\n\n # StateMonitor will record the voltages values of indices given to record.\n\n # Records only for a few indices.\n self.MPC = StateMonitor(self.PC, 'v', record=self.my_indices)\n # Records for all indices, used for recording spiking times.\n # TODO: Find better way to record spike moments\n self.MM = StateMonitor(self.PC, 'v', record=True)\n\n # Records the G inputs of one cell.\n self.MN = StateMonitor(self.N, 'v', record=0)\n self.spikemonN = SpikeMonitor(self.N, variables='v', record=True)\n\n self.N_all_values = self.spikemonN.all_values()\n\n self.spikemon_random = SpikeMonitor(self.R)\n # Records the inhibitory of one cell.\n self.MINH = StateMonitor(self.INH, 'v', record=0)\n\n # self.v_thres = StateMonitor(self.PC, 'v_leak_exc', record=0)\n self.Mthreshold = StateMonitor(self.PC, 'h', record=True)\n\n # Records the spikes of Pyramidal cells.\n self.spikemon = SpikeMonitor(self.PC, variables='v', record=True)\n\n # Records the spikes of one inhibitory cell.\n self.spikemoninh = SpikeMonitor(self.INH, variables='v', record=True)\n\n # TODO : Find a way to be able to run several times\n if not self.has_run:\n netObjs = {k: v for k, v in vars(self).items() if isinstance(v, BrianObject)}\n self.net = core.network.Network(netObjs)\n self.net.run(duration, namespace=self.p)\n else:\n self.net.run(duration, namespace=self.p)\n\n # For checking if the network ran\n self.has_run = True\n\n # Records spiking information about different\n self.PC_all_values = self.spikemon.all_values()\n self.INH_all_values = self.spikemoninh.all_values()\n\n # Following line does not run because, the recorded voltages are empty.\n # functions.spiking_times_fun(self, -36.1)\n\n functions.spiking_times_fun(self)\n\n if show_PC:\n functions.plot_voltages_PC(self)\n # my_plot = plot(self.MPC.t / ms, self.MPC.v, label='PC v_leak_exc' )\n # show()\n\n if show_other:\n functions.plot_voltages_other_types(self)\n\n","sub_path":"SimpleFairhall/BasicModel.py","file_name":"BasicModel.py","file_ext":"py","file_size_in_byte":13304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"20942517","text":"def simpleMerge(a, b):\n total = len(a) + len(b)\n j, k = 0, 0\n \n c = list()\n global contador\n for i in range(total):\n if (k == len(b) or (j < len(a) and a[j] <= b[k])):\n c.append(a[j])\n j += 1\n else:\n c.append(b[k])\n contador = contador + ((total - (len(b))) - j)\n k += 1\n return(c)\n\ndef mergeSort(data):\n if (len(data) <= 1):\n return(data)\n\n middle = int(len(data) / 2)\n left = mergeSort(data[0 : middle]) # O data de 0 at� middle\n right = mergeSort(data[middle : len(data)]) # O data de middle at� o final\n\n result = simpleMerge(left, right)\n return(result)\n\n\ncasos = input()\ncasos = int(casos)\ni = 0\ncontador = 0\nwhile True:\n try:\n vetor = []\n x = input()\n if(x != ''):\n while(x != ''):\n vetor.append(int(x))\n x = input()\n vetor2 = list(map(int,vetor))\n del vetor2[0] \n mergeSort(vetor2)\n print(contador)\n contador = 0\n \n except EOFError:\n vetor2 = list(map(int,vetor))\n del vetor2[0]\n mergeSort(vetor2)\n print(contador)\n contador = 0\n break\n\n\n\n","sub_path":"Q2045.py","file_name":"Q2045.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"27803792","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport os\nimport jinja2\nimport webapp2\nimport hmac\nimport random\nimport string\nfrom google.appengine.ext import db\n\nSECRET = \"paras\"\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\njinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir), autoescape=True)\n\ndef hash_str(s):\n\treturn hmac.new(SECRET,s).hexdigest()\n\ndef make_secure_val(s):\n\treturn \"%s|%s\" % (s,hash_str(s))\n\ndef check_secure_val(h):\n\tval = h.split(\"|\")[0]\n\tif h == make_secure_val(val):\n\t\treturn val\n\ndef make_salt():\n\treturn ''.join(random.choice(string.letters) for x in xrange(5))\n\ndef make_pw_hash(name,pw, salt=None):\n\tif not salt:\n\t\tsalt = make_salt()\n\th = hashlib.sha256(name + pw+ salt).hexdigest()\n\treturn \"%s,%s\" %(h,salt)\n\ndef valid_pw(name,pw,h):\n\tsalt = h.split(\",\")[1]\n\treturn h == make_pw_hash(name,pw,salt)\n\nclass BaseHandler(webapp2.RequestHandler):\n\tdef write(self,*a,**kw):\n\t\tself.response.out.write(*a,**kw)\n\t\t\n\tdef render_str(self,template,**params):\n\t\tt=jinja_env.get_template(template)\n\t\treturn t.render(params)\n\t\n\tdef render(self, template,**params):\n\t\ttemplate = jinja_env.get_template(template)\n\t\tself.response.out.write(template.render(params))\n\nclass Submit(db.Model):\n\ttitle = db.StringProperty(required = True)\n\treminder = db.TextProperty(required = True)\n\tcreated = db.DateTimeProperty(auto_now_add = True)\n\tlast_modified = db.DateTimeProperty(auto_now_add=True)\nclass Reminders(BaseHandler):\n\tdef get(self):\n\t\treminder = db.GqlQuery(\"Select * FROM Submit \"\n\t\t\t\t\t\t\"ORDER BY created DESC\")\n\t\tself.render('reminder.html', reminder=reminder)\nclass Make(BaseHandler):\n\tdef render_make(self,error=\"\"):\n\t\tself.render('make.html',error=error)\n\tdef get(self):\n\n\t\tself.render_make()\n\tdef post(self):\n\t\ttitle=self.request.get(\"title\")\n\t\treminder =self.request.get(\"reminder\")\n\t\tif reminder and title:\n\t\t\ts = Submit(title=title,reminder=reminder)\n\t\t\ts.put()\n\t\t\tself.redirect('/reminders/%s' % str(s.key().id()))\n\t\telse:\n\t\t\terror=\"Please enter a reminder and title\"\n\t\t\tself.render_make(error)\nclass ReminderPage(BaseHandler):\n\tdef render_page(self,reminder=\"\"):\n\t\tself.render('permalink.html',reminder=reminder)\n\tdef get(self,post_id):\n\t\tkey = db.Key.from_path('Submit',int(post_id))\n\t\treminder = db.get(key)\n\t\tif not reminder:\n\t\t\tself.error(404)\n\t\t\treturn \n\t\tself.render_page(reminder)\nclass SignUp(BaseHandler):\n\tdef get(self):\n\t\tself.render('signup.html')\nclass MainHandler(BaseHandler):\n\tdef render_index(self,error=\"\",visits=\"\"):\n\t\tself.render('index.html',error=error,visits=visits)\n\tdef get(self):\n\t\tvisits = 0\n\t\tvisits_cookie_str = self.request.cookies.get('visits')\n\t\tif visits_cookie_str:\n\t\t\tcookie_val = check_secure_val(visits_cookie_str)\n\t\t\tif cookie_val:\n\t\t\t\tvisits = int(cookie_val)\n\n\t\tvisits += 1 \n\t\tnew_cookie_val = make_secure_val(str(visits))\n\t\tself.response.headers.add_header('Set-Cookie','visits=%s' % new_cookie_val)\n\t\tself.render_index(\"\",visits)\n\napp = webapp2.WSGIApplication([\n ('/', MainHandler),('/reminders/?',Reminders),('/make',Make),('/reminders/([0-9]+)',ReminderPage),('/signup/?',SignUp),\n], debug=True)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"5782272","text":"import sys\nimport glob\nimport struct\nimport time\nimport serial\n\ndef serial_ports():\n \"\"\" Lists serial port names\n\n :raises EnvironmentError:\n On unsupported or unknown platforms\n :returns:\n A list of the serial ports available on the system\n \"\"\"\n if sys.platform.startswith('win'):\n ports = ['COM%s' % (i + 1) for i in range(256)]\n elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):\n # this excludes your current terminal \"/dev/tty\"\n ports = glob.glob('/dev/ttyACM*')\n else:\n raise EnvironmentError('Unsupported platform')\n\n result = []\n print (\"Available ports: {0}\".format(ports))\n for port in ports:\n try:\n s = serial.Serial(port)\n s.close()\n result.append(port)\n except (OSError, serial.SerialException):\n pass\n return result\n\n\nnoPort=False\navailablePorts = serial_ports()\nif len(availablePorts)==0:\n # be fake\n noPort=True\nelse:\n port=availablePorts[0]\nif not noPort:\n ser = serial.Serial(port, 9600, timeout = None)\n\ntime.sleep(1)\n\ndef move(memory):\n \n while memory['running']:\n if not noPort:\n ser.write(str(int(memory['angle'])).encode())\n a = ser.readline().decode()\n if a.strip() != str(int(memory['angle'])):\n print('Angle Read Incorrectly:', a.strip())\n print('Angle Read Expected:', memory['angle'])\n print('')\n ser.write(str(int(memory['speed'])).encode())\n a = ser.readline().decode()\n if a.strip() != str(int(memory['speed'])):\n print('Speed Read Incorrectly:', a.strip())\n print('Speed Read Expect:', memory['speed'])\n print('')\n else:\n time.sleep(1)\n","sub_path":"components/actOnMux.py","file_name":"actOnMux.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"112538385","text":"# from django.conf.urls import url, include, \nfrom django.urls import reverse\nfrom django.contrib.auth.models import User\nfrom rest_framework import viewsets, permissions, generics, pagination\nfrom rest_framework.decorators import api_view\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom training.models import Training, TrainingTag, TrainingCategory\nfrom system_core.models import Disability\n\nfrom .serializers import TrainingSerializer\n\n\n\nclass LargeResultsSetPagination(pagination.PageNumberPagination):\n page_size = 9\t\t#default won't work if page_size_query_param is set\n page_size_query_param = 'page_size'\t\n # max_page_size = 1\t\n\n\nclass CustomerAccessPermission(permissions.BasePermission):\n\tmessage = 'Adding customers not allowed.'\n\n\tdef has_permission(self, request, view):\n\t\t# if request.user.is_superuser:\n\t\tif request.user.is_authenticated:\n\t\t\treturn True\n\n\t\t# return True\n\t\treturn False\n\n\nclass TrainingViewSet(viewsets.ModelViewSet):\n\n\tdef get_queryset(self):\n\n\t\tto_return = Training.objects.filter(status=True).order_by('-id')\n\n\t\ttitle = self.request.GET.get('title', False)\n\t\ttag_ids = self.request.GET.getlist('tags[]')\n\t\ttags = TrainingTag.objects.filter(id__in=tag_ids)\n\t\tdisability_ids = self.request.GET.getlist('disabilities[]')\n\t\tdisabilities = Disability.objects.filter(id__in=disability_ids)\n\t\tcategory_ids = self.request.GET.getlist('categories[]')\n\t\tcategories = TrainingCategory.objects.filter(id__in=category_ids)\n\n\t\tfilter_kwargs = dict(\n\t\t\t\tid__in=to_return\n\t\t\t)\n\t\texclude_kwargs = dict()\n\n\t\tif title:\n\t\t\tfilter_kwargs['title__icontains'] = title\n\t\t\n\t\tif tags.exists():\n\t\t\tfilter_kwargs['tags__in'] = tags\n\t\t\n\t\tif categories.exists():\n\t\t\tfilter_kwargs['category__in'] = categories\n\t\t\n\t\tif disabilities.exists():\n\t\t\texclude_kwargs['disabilities__in'] = disabilities\n\n\t\t\n\t\tto_return = Training.objects.filter(**filter_kwargs).exclude(**exclude_kwargs).order_by('-id').distinct()\n\n\n\n\n\t\treturn to_return\n\n\n\tserializer_class = TrainingSerializer\n\tpermission_classes = (CustomerAccessPermission,)\n\tpagination_class = LargeResultsSetPagination\n\tfilterset_fields = ('id',)\n\thttp_method_names = ['get']\n\n\n\n\tdef list(self, request, *args, **kwargs):\n\t\tresponse = super().list(request, *args, **kwargs)\n\t\tsingle_page_url = reverse('training:single_training', args=[0,])\t\t# since we must add the training_id argument\n\t\tresponse.data['single_page_url'] = single_page_url[:-2]\t\t\t# removing the id argument to use it globally / need to use \"/\" format\n\t\t# print(response.data)\n\t\treturn response\n\n","sub_path":"src/training/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"449944353","text":"#!/usr/bin/env python\n\n\"\"\"\nNote: dbf is only supported/imported for Python 2.\n\"\"\"\n\nimport agate\nimport dbf\nimport six\n\ndef dbf2csv(f, **kwargs):\n \"\"\"\n Convert a dBASE .dbf file to csv.\n \"\"\"\n with dbf.Table(f.name) as db:\n column_names = db.field_names\n table = agate.Table(db, column_names)\n\n output = six.StringIO()\n table.to_csv(output)\n result = output.getvalue()\n output.close()\n\n return result\n","sub_path":"csvkit/convert/dbase.py","file_name":"dbase.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"453274535","text":"\n#type casting\n\nnum1 = int(input(\"Enter first number: \"))\nnum2 =int(input(\"Enter second number: \"))\nsum=num1+num2\nsubtraction=num1-num2\nmultipication=num1*num2\ndevided=num1/num2\nprint(\"|...................................|\")\nprint(\"The sum is \",sum,\" The (-) is \",subtraction,\" The sumation is \",multipication,\" The devided is \",devided)","sub_path":"program1.py","file_name":"program1.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"420804038","text":"import matplotlib.pyplot as plt\r\nimport os\r\nimport BiomTable_class\r\n\r\n\r\ndef box_plot_drawer(samples_dir, data_type, taxonomy='phylum'):\r\n \"\"\"\r\n The function opens a directory with metaphlan data. \r\n First function argument is directory name.\r\n Metaphlan files have to be named eg. example1_metaphlan.txt\r\n with the changeing indecies.\r\n Second argument is the sample number.\r\n\r\n :type samples_dir: directory name\r\n :param data_type:\r\n :param taxonomy: taxonomy level\r\n \"\"\"\r\n sorted_data = [[]]\r\n sample_number = 0\r\n possible_labels = []\r\n\r\n for file in os.listdir(os.getcwd() + '/' + samples_dir):\r\n\r\n data_set = []\r\n\r\n if 'metaphlan' and '.txt' in file:\r\n name = file\r\n path = samples_dir + '/' + name\r\n a_biom_table = BiomTable_class.BiomTable(path)\r\n\r\n if data_type == 'abundance':\r\n data_set = a_biom_table.tax_abundance(taxonomy)\r\n elif data_type == 'richness':\r\n data_set = a_biom_table.tax_richness(taxonomy)\r\n\r\n for data in data_set:\r\n if data[0] not in possible_labels:\r\n possible_labels.append(data[0])\r\n sorted_data.append([])\r\n sorted_data[0] = possible_labels\r\n sorted_data[possible_labels.index(data[0]) + 1].append(data[1])\r\n\r\n sample_number += 1\r\n\r\n box_plot_data = []\r\n label = []\r\n for idx in range(1, len(sorted_data)):\r\n if len(sorted_data[idx]) == sample_number:\r\n box_plot_data.append(sorted_data[idx])\r\n label.append(sorted_data[0][idx-1])\r\n\r\n print(sorted_data[0][idx - 1], sorted_data[idx])\r\n\r\n fig1, ax1 = plt.subplots()\r\n ax1.set_title(data_type.capitalize() + \" Boxplot\")\r\n ax1.boxplot(box_plot_data, labels=label, showmeans = True)\r\n plt.setp(ax1.get_xticklabels(), rotation=30, horizontalalignment='right')\r\n ax1.set_ylabel(data_type.capitalize())\r\n ax1.set_xlabel(taxonomy.capitalize())\r\n plt.tight_layout()\r\n\r\n plt.show()\r\n","sub_path":"Box_plot.py","file_name":"Box_plot.py","file_ext":"py","file_size_in_byte":2070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"353395808","text":"import numpy as np\nfrom nltk.tokenize import MWETokenizer\n\n\nclass Kp20kTokenizer:\n\n def __init__(self, mweTokenizer, emb_tokenizer):\n self.mweTokenizer = mweTokenizer\n self.emb_tokenizer = emb_tokenizer\n\n def tokenize(self, sentence):\n tokens = self.emb_tokenizer.tokenize(sentence)\n # '<', 'digit', '>'\n # '<', 'unk', '>'\n tokens = self.mweTokenizer.tokenize(tokens)\n return tokens\n\n\nclass Reader:\n # mweTokenizer = MWETokenizer([('<', 'digit', '>'), ('<', 'unk', '>'), ('[', 'CLS', ']'), ('[', 'SEP', ']')], separator=\"\")\n mweTokenizer = MWETokenizer([('<', 'digit', '>'),\n ('<', 'unk', '>'),\n ('<', 'pad', '>'),\n ('<', 'bos', '>'),\n ('<', 'eos', '>'),\n ('<', 'sep', '>'),\n ('<', 'peos', '>'),\n ('[', 'CLS', ']'),\n ('[', 'SEP', ']')],\n separator=\"\")\n # skip_words = [\"[CLS]\", \"[SEP]\", \"\", \"\"]\n skip_words = [\"[CLS]\", \"[SEP]\", \"\", \"\", \"\", \"\", \"\", \"\", \"\"]\n # tokenizer = Tokenizer('eg')\n\n # def __init__(self, model, title_repetitions=1, num_labels=3):\n def __init__(self, bert_tokenizer):\n self.tokenizer = bert_tokenizer\n\n def title_fix(self, sentences):\n # la prima frase contiene sia titolo che la prima frase del documento\n phrases = sentences[0].replace(\"\\n\\t\", \" \").split(\"\\n\") # per la struttura dei documenti posso separarli così\n title = phrases[0]\n titles = []\n for i in range(self.title_repetitions):\n titles.append(title)\n return titles + phrases[1:] + sentences[1:]\n\n def tokenize_with_map_to_origin(self, text_words):\n \"\"\"\n :param text_words: list of words (tokens) of the text\n :return:\n \"\"\"\n tokens_map = []\n sentences_tokens = []\n all_tokens = []\n index = 0\n all_words = []\n tokens = []\n for i, word in enumerate(text_words):\n all_words.append(word)\n if word in self.skip_words:\n _tokens = [word]\n else:\n _tokens = self.tokenizer.tokenize(word)\n for token in _tokens:\n tokens.append(token)\n all_tokens.append(token)\n tokens_map.append(index)\n index += 1\n sentences_tokens.append(tokens)\n return all_tokens, tokens_map, all_words\n\n def fix_text_for_model(self, text):\n if self.model == \"BERT\" or self.model == \"DistilBERT\":\n return \"[CLS] \" + text + \" [SEP]\"\n return text\n\n \"\"\"\n '' METHOD: read_terms\n '' PARAMETERS: \n '''' dataset = dataset name\n '''' typ = type of data (train, test or validate)\n \"\"\"\n\n # def read_terms(self, dataset, typ, emb_tokenizer):\n # x, tokens_maps, x_ppro, y, files_list, x_text, y_text, expected_kps = [], [], [], [], [], [], [], []\n # f_text, list_keyphr = [], []\n # path = \"datasets/%s/%s\" % (dataset, typ)\n # kp20tokenizer = Kp20kTokenizer(self.mweTokenizer, emb_tokenizer)\n #\n # for f in os.listdir(path):\n # \"------------------ HULTH DATASET----------------------------------------------------------\"\n # if dataset == \"Hulth2003\":\n # if not f.endswith(\".uncontr\"):\n # continue\n # f_uncontr = open(os.path.join(path, f), \"rU\")\n # f_text = open(os.path.join(path, f.replace(\".uncontr\", \".abstr\")), \"rU\")\n # text = \"\".join(map(str, f_text))\n # text = self.fix_text_for_model(text)\n # kp_uncontr = \"\".join(map(str, f_uncontr))\n #\n # list_keyphr = kp_uncontr.replace(\"\\n\\t\", \" \").split(\"; \")\n # tokenized_keyphr = [emb_tokenizer.tokenize(kp) for kp in list_keyphr]\n #\n # doc = text.replace(\"\\n\\t\", \" \").split(\"\\n\") # separo titolo e contenuto\n # doc[0] = Reader.tokenizer.sentence_tokenize(doc[0])\n # doc[1] = Reader.tokenizer.sentence_tokenize(doc[1])\n # list_sentences = Reader.tokenizer.sentence_tokenize(text)\n #\n # list_sentences = self.title_fix(list_sentences)\n #\n # text_vec, sentences_vec, tokens_map, word_doc = self.tokenize_with_map_to_origin(list_sentences,\n # emb_tokenizer)\n #\n # files_list.append(f)\n # x.append(text_vec)\n # x_text.append(word_doc)\n # tokens_maps.append(tokens_map)\n # x_ppro.append(sentences_vec)\n # exp_val, exp_kps = self.calc_expected_values(text_vec, tokenized_keyphr, list_keyphr)\n # y.append(exp_val)\n # expected_kps.append(exp_kps)\n #\n # \"------------------ Kp20k DATASET----------------------------------------------------------\"\n #\n # if dataset == \"Kp20k\":\n # file_name = ''.join(['kp20k_', typ.lower(), '.json'])\n # with open(os.path.join(path, file_name)) as f:\n # count_doc = 1\n # for line in f:\n # if count_doc <= 20000: # needed because 500k is too large\n # d = json.loads(line)\n # text = ''.join([d[\"title\"], d[\"abstract\"]])\n # text = self.fix_text_for_model(text)\n #\n # kp_list = d[\"keyword\"]\n # y_text.append(kp_list)\n # kp_list = kp_list.split(\";\")\n #\n # list_keyphr = [kp20tokenizer.tokenize(kp) for kp in kp_list]\n # list_sentences = Reader.tokenizer.sentence_tokenize(text)\n #\n # text_vec, sentences_vec, tokens_map, word_doc = self.tokenize_with_map_to_origin(\n # list_sentences, kp20tokenizer)\n #\n # files_list.append(str(count_doc))\n # x.append(text_vec)\n # x_text.append(word_doc)\n # x_ppro.append(sentences_vec)\n # tokens_maps.append(tokens_map)\n # exp_val, exp_kps = self.calc_expected_values(text_vec, list_keyphr, kp_list)\n # y.append(exp_val)\n # expected_kps.append(exp_kps)\n # count_doc = count_doc + 1\n #\n # \"------------------ Krapivin 2009 DATASET------------------------------------------------------\"\n # if dataset == \"Krapivin2009\":\n # if not f.endswith(\".key\"):\n # continue\n # f_key = open(os.path.join(path, f), \"rU\")\n # f_text = open(os.path.join(path, f.replace(\".key\", \".txt\")), \"rU\")\n # text = \"\".join(map(str, f_text))\n # text = self.fix_text_for_model(text)\n # key_phrases = \"\".join(map(str, f_key))\n # key_phrases = key_phrases.strip('\\n')\n #\n # list_keyphr = [Reader.tokenizer.word_tokenize(kp) for kp in key_phrases.split(\"\\n\")]\n # list_sentences = Reader.tokenizer.sentence_tokenize(text)\n #\n # text_vec = []\n # for string in list_sentences:\n # for token in Reader.tokenizer.word_tokenize(string):\n # text_vec.append(token)\n # files_list.append(f)\n # x.append(text_vec)\n # exp_val, exp_kps = self.calc_expected_values(text_vec, list_keyphr, key_phrases)\n # y.append(exp_val)\n # expected_kps.append(exp_kps)\n #\n # \"---------------------------------------------------------------------------------------------\"\n #\n # return x, tokens_maps, x_ppro, y, files_list, x_text, expected_kps\n\n \"\"\"\n '' METHOD: calc_expected_values\n '' PARAMETERS: \n '''' text_vec = vector of the words in text document\n '''' list_keyphr = list of document keyphrases\n \"\"\"\n\n # def calc_expected_values(self, text_vec, list_keyphr, kps):\n # y_inner = np.zeros(np.shape(text_vec))\n #\n # f = lambda a, b: [x for x in range(len(a)) if a[x:x + len(b)] == b]\n # found_kps = []\n # for index, kp in enumerate(list_keyphr):\n # arr_indices = f(text_vec, kp) # returns the indices at which the pattern starts\n # for i in arr_indices:\n # if kps[index] not in found_kps:\n # found_kps.append(kps[index])\n # y_inner[i] = 1\n # if len(kp) > 1:\n # y_inner[(i + 1):(i + 1) + len(kp) - 1] = (2 if self.num_labels == 3 else 1)\n # return y_inner, found_kps\n","sub_path":"utils/bert_utils.py","file_name":"bert_utils.py","file_ext":"py","file_size_in_byte":9179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"139248460","text":"try:\n from Notify import Main as NotifyMain\n Notify = NotifyMain()\n Notify.SetMode(\"C\")\nexcept(ImportError):\n print(\"Failed to import Notify. Aborting.\")\nimport os\n\ndef PowerMenu():\n # [ID, NAME, STATUS, MAC, IP]\n ServerList = [[0, \"EFSS\", \"OFFLINE\", \"00:0C:76:4E:1A:D1\", \"192.168.1.25\"],\n [1, \"SGPS\", \"OFFLINE\", \"78:45:C4:04:9D:68\", \"192.168.1.3\"],\n [2, \"NGSS\", \"OFFLINE\", \"2C:56:DC:D5:F9:94\", \"192.168.1.31\"],\n [3, \"EMAC\", \"OFFLINE\", \"00:11:09:E9:DC:62\", \"192.168.1.32\"]]\n for count in range(0, len(ServerList)):\n print(\"ID: {}, Name: {}, Status: {}.\".format(ServerList[count][0], ServerList[count][1], ServerList[count][2]))\n\ndef Main():\n print(\"\"\"\n ------------------------------------------\n | LSCS - v1.0 |\n ------------------------------------------\n | [1] Power |\n | [2] Mode |\n | [3] Local Commands |\n | [4] Stats |\n | [5] Exit |\n | |\n ------------------------------------------ \n \"\"\")\n while True:\n try:\n menuchoice = int(input(\"> \"))\n if menuchoice not in [1,2,3,4,5]:\n Notify.Warning(\"Please enter a valid response.\")\n else:\n break\n except(ValueError):\n Notify.Warning(\"Please enter a valid response.\")\n if menuchoice == 1:\n PowerMenu()\n Main()\n elif menuchoice == 2:\n ModeMenu()\n elif menuchoice == 3:\n LCmds()\n elif menuchoice == 4:\n Stats()\n elif menuchoice == 5:\n os.system(\"clear\")\n exit()\n\nMain()","sub_path":"AES_Master/AES 4.3/Misc/LSCS.py","file_name":"LSCS.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"196912245","text":"#!/usr/bin/env python\n\n# Copyright 2016, 2017 F5 Networks, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom __future__ import absolute_import\n\nimport argparse\nimport fcntl\nimport hashlib\nimport json\nimport logging\nimport os\nimport os.path\nimport sys\nimport time\nimport threading\nimport signal\nimport urllib\n\nimport pyinotify\n\nfrom urlparse import urlparse\nfrom f5.bigip import ManagementRoot\nfrom f5_cccl.api import F5CloudServiceManager\nfrom f5_cccl.exceptions import F5CcclError\n\nlog = logging.getLogger(__name__)\nconsole = logging.StreamHandler()\nconsole.setFormatter(\n logging.Formatter(\"[%(asctime)s %(name)s %(levelname)s] %(message)s\"))\nroot_logger = logging.getLogger()\nroot_logger.addHandler(console)\n\nSCHEMA_PATH = \"./src/f5-cccl/f5_cccl/schemas/cccl-api-schema.yml\"\n\n\nclass PartitionNameError(Exception):\n \"\"\"Exception type for F5 resource name.\"\"\"\n\n def __init__(self, msg):\n \"\"\"Create partition name exception object.\"\"\"\n Exception.__init__(self, msg)\n\n\nclass IPV4FormatError(Exception):\n \"\"\"Exception type for improperly formatted IPv4 address.\"\"\"\n\n def __init__(self, msg):\n \"\"\"Create ipv4 format exception object.\"\"\"\n Exception.__init__(self, msg)\n\n\nclass ResponseStatusFilter(logging.Filter):\n def filter(self, record):\n return not record.getMessage().startswith(\"RESPONSE::STATUS\")\n\n\nclass CertFilter(logging.Filter):\n def filter(self, record):\n return \"CERTIFICATE\" not in record.getMessage()\n\n\nclass KeyFilter(logging.Filter):\n def filter(self, record):\n return \"PRIVATE KEY\" not in record.getMessage()\n\n\nroot_logger.addFilter(ResponseStatusFilter())\nroot_logger.addFilter(CertFilter())\nroot_logger.addFilter(KeyFilter())\n\n\ndef list_diff_exclusive(list1, list2):\n \"\"\"Return items found only in list1 or list2.\"\"\"\n return list(set(list1) ^ set(list2))\n\n\ndef ipv4_to_mac(ip_str):\n \"\"\"Convert an IPV4 string to a fake MAC address.\"\"\"\n ip = ip_str.split('.')\n if len(ip) != 4:\n raise IPV4FormatError('Bad IPv4 address format specified for '\n 'FDB record: {}'.format(ip_str))\n\n return \"0a:0a:%02x:%02x:%02x:%02x\" % (\n int(ip[0]), int(ip[1]), int(ip[2]), int(ip[3]))\n\n\ndef extract_partition_and_name(f5_partition_name):\n \"\"\"Separate partition and name components for a Big-IP resource.\"\"\"\n parts = f5_partition_name.split('/')\n count = len(parts)\n if f5_partition_name[0] == '/' and count == 3:\n # leading slash\n partition = parts[1]\n name = parts[2]\n elif f5_partition_name[0] != '/' and count == 2:\n # leading slash missing\n partition = parts[0]\n name = parts[1]\n else:\n raise PartitionNameError('Bad F5 resource name encountered: '\n '{}'.format(f5_partition_name))\n return partition, name\n\n\ndef log_sequence(prefix, sequence_to_log):\n \"\"\"Helper function to log a sequence.\n\n Dump a sequence to the logger, skip if it is empty\n\n Args:\n prefix: The prefix string to describe what's being logged\n sequence_to_log: The sequence being logged\n \"\"\"\n if sequence_to_log:\n log.debug(prefix + ': %s', (', '.join(sequence_to_log)))\n\n\nDEFAULT_LOG_LEVEL = logging.INFO\nDEFAULT_VERIFY_INTERVAL = 30.0\n\n\nclass K8sCloudServiceManager():\n \"\"\"K8sCloudServiceManager class.\n\n Generates a configuration for a BigIP based upon the apps/tasks managed\n by services/pods/nodes in Kubernetes.\n\n - Matches apps/sevices by BigIP partition\n - Creates a Virtual Server and pool for each service type that matches a\n BigIP partition\n - For each backend (task, node, or pod), it creates a pool member and adds\n the member to the pool\n - Token-based authentication is used by specifying a token named 'tmos'.\n This will allow non-admin users to use the API (BIG-IP must configure\n the accounts with proper permissions, for either local or remote auth).\n\n Args:\n bigip: ManagementRoot object\n partition: BIG-IP partition to manage\n schema_path: Path to the CCCL schema\n \"\"\"\n\n def __init__(self, bigip, partition, schema_path):\n \"\"\"Initialize the K8sCloudServiceManager object.\"\"\"\n self._mgmt_root = bigip\n self._cccl = F5CloudServiceManager(\n bigip,\n partition,\n prefix=\"\",\n schema_path=schema_path)\n\n def mgmt_root(self):\n \"\"\" Return the BIG-IP ManagementRoot object\"\"\"\n return self._mgmt_root\n\n def get_partition(self):\n \"\"\" Return the managed partition.\"\"\"\n return self._cccl.get_partition()\n\n def _apply_ltm_config(self, config):\n \"\"\"Apply the configuration to the BIG-IP.\n\n Args:\n config: BIG-IP config dict\n \"\"\"\n return self._cccl.apply_config(config)\n\n def _apply_network_config(self, config):\n \"\"\"Apply the network configuration to the BIG-IP.\n\n Args:\n config: BIG-IP network config dict\n \"\"\"\n if 'fdb' in config:\n return self._apply_network_fdb_config(config['fdb'])\n else:\n return 0\n\n def _apply_network_fdb_config(self, fdb_config):\n \"\"\"Apply the network fdb configuration to the BIG-IP.\n\n Args:\n config: BIG-IP network fdb config dict\n \"\"\"\n req_vxlan_name = fdb_config['vxlan-name']\n req_fdb_record_endpoint_list = fdb_config['vxlan-node-ips']\n try:\n f5_fdb_record_endpoint_list = self.get_fdb_records(req_vxlan_name)\n\n log_sequence('req_fdb_record_list', req_fdb_record_endpoint_list)\n log_sequence('f5_fdb_record_list', f5_fdb_record_endpoint_list)\n\n # See if the list of records is different.\n # If so, update with new list.\n if list_diff_exclusive(f5_fdb_record_endpoint_list,\n req_fdb_record_endpoint_list):\n self.fdb_records_update(req_vxlan_name,\n req_fdb_record_endpoint_list)\n return 0\n except (PartitionNameError, IPV4FormatError) as e:\n log.error(e)\n return 0\n except Exception as e:\n log.error('Failed to configure the FDB for VxLAN tunnel '\n '{}: {}'.format(req_vxlan_name, e))\n return 1\n\n def get_vxlan_tunnel(self, vxlan_name):\n \"\"\"Get a vxlan tunnel object.\n\n Args:\n vxlan_name: Name of the vxlan tunnel\n \"\"\"\n partition, name = extract_partition_and_name(vxlan_name)\n vxlan_tunnel = self._mgmt_root.tm.net.fdb.tunnels.tunnel.load(\n partition=partition, name=urllib.quote(name))\n return vxlan_tunnel\n\n def get_fdb_records(self, vxlan_name):\n \"\"\"Get a list of FDB records (just the endpoint list) for the vxlan.\n\n Args:\n vxlan_name: Name of the vxlan tunnel\n \"\"\"\n endpoint_list = []\n vxlan_tunnel = self.get_vxlan_tunnel(vxlan_name)\n if hasattr(vxlan_tunnel, 'records'):\n for record in vxlan_tunnel.records:\n endpoint_list.append(record['endpoint'])\n\n return endpoint_list\n\n def fdb_records_update(self, vxlan_name, endpoint_list):\n \"\"\"Update the fdb records for a vxlan tunnel.\n\n Args:\n vxlan_name: Name of the vxlan tunnel\n fdb_record_list: IP address associated with the fdb record\n \"\"\"\n vxlan_tunnel = self.get_vxlan_tunnel(vxlan_name)\n data = {'records': []}\n records = data['records']\n for endpoint in endpoint_list:\n record = {'name': ipv4_to_mac(endpoint), 'endpoint': endpoint}\n records.append(record)\n log.debug(\"Updating records for vxlan tunnel {}: {}\".format(\n vxlan_name, data['records']))\n vxlan_tunnel.update(**data)\n\n\nclass IntervalTimerError(Exception):\n def __init__(self, msg):\n Exception.__init__(self, msg)\n\n\nclass IntervalTimer(object):\n def __init__(self, interval, cb):\n float(interval)\n if 0 >= interval:\n raise IntervalTimerError(\"interval must be greater than 0\")\n\n if not cb or not callable(cb):\n raise IntervalTimerError(\"cb must be callable object\")\n\n self._cb = cb\n self._interval = interval\n self._execution_time = 0.0\n self._running = False\n self._timer = None\n self._lock = threading.RLock()\n\n def _set_execution_time(self, start_time, stop_time):\n if stop_time >= start_time:\n self._execution_time = stop_time - start_time\n else:\n self._execution_time = 0.0\n\n def _adjust_interval(self):\n adjusted_interval = self._interval - self._execution_time\n if adjusted_interval < 0.0:\n adjusted_interval = 0.0\n self._execution_time = 0.0\n return adjusted_interval\n\n def _run(self):\n start_time = time.clock()\n try:\n self._cb()\n except Exception:\n log.exception('Unexpected error')\n finally:\n with self._lock:\n stop_time = time.clock()\n self._set_execution_time(start_time, stop_time)\n if self._running:\n self.start()\n\n def is_running(self):\n return self._running\n\n def start(self):\n with self._lock:\n if self._running:\n # restart timer, possibly with a new interval\n self.stop()\n self._timer = threading.Timer(self._adjust_interval(), self._run)\n # timers can't be stopped, cancel just prevents the callback from\n # occuring when the timer finally expires. Make it a daemon allows\n # cancelled timers to exit eventually without a need for join.\n self._timer.daemon = True\n self._timer.start()\n self._running = True\n\n def stop(self):\n with self._lock:\n if self._running:\n self._timer.cancel()\n self._timer = None\n self._running = False\n\n\nclass ConfigError(Exception):\n def __init__(self, msg):\n Exception.__init__(self, msg)\n\n\ndef create_ltm_config_kubernetes(partition, config):\n \"\"\"Create a BIG-IP configuration from the Kubernetes configuration.\n\n Args:\n config: Kubernetes BigIP config\n \"\"\"\n ltm = {}\n if 'resources' in config and partition in config['resources']:\n ltm = config['resources'][partition]\n\n log.debug(\"Service Config: %s\", json.dumps(ltm))\n return ltm\n\n\ndef create_network_config_kubernetes(config):\n \"\"\"Create a BIG-IP Network configuration from the Kubernetes config.\n\n Args:\n config: Kubernetes BigIP config which contains openshift-sdn defs\n \"\"\"\n f5_network = {}\n if 'openshift-sdn' in config:\n f5_network['fdb'] = config['openshift-sdn']\n\n return f5_network\n\n\ndef _create_custom_profiles(mgmt, partition, custom_profiles):\n incomplete = 0\n\n customProfiles = False\n for profile in custom_profiles:\n if profile['context'] == 'clientside':\n incomplete += _create_client_ssl_profile(mgmt, partition, profile)\n customProfiles = True\n elif profile['context'] == 'serverside':\n incomplete += _create_server_ssl_profile(mgmt, partition, profile)\n customProfiles = True\n else:\n log.error(\n \"Only client or server custom profiles are supported.\")\n\n return customProfiles, incomplete\n\n\ndef _create_client_ssl_profile(mgmt, partition, profile):\n ssl_client_profile = mgmt.tm.ltm.profile.client_ssls.client_ssl\n\n name = profile['name']\n\n # No need to create if it exists\n if ssl_client_profile.exists(name=name, partition=partition):\n return 0\n\n cert = profile['cert']\n cert_name = name + '.crt'\n incomplete = _install_certificate(mgmt, cert, cert_name)\n if incomplete > 0:\n # Unable to install cert\n return incomplete\n\n key = profile['key']\n key_name = name + '.key'\n incomplete = _install_key(mgmt, key, key_name)\n if incomplete > 0:\n # Unable to install key\n return incomplete\n\n try:\n # create ssl-client profile from cert/key pair\n chain = [{'name': name,\n 'cert': '/Common/' + cert_name,\n 'key': '/Common/' + key_name}]\n serverName = profile.get('serverName', None)\n sniDefault = profile.get('sniDefault', False)\n ssl_client_profile.create(name=name,\n partition=partition,\n certKeyChain=chain,\n serverName=serverName,\n sniDefault=sniDefault,\n defaultsFrom=None)\n except Exception as err:\n log.error(\"Error creating client SSL profile: %s\" % err.message)\n incomplete = 1\n\n return incomplete\n\n\ndef _create_server_ssl_profile(mgmt, partition, profile):\n ssl_server_profile = mgmt.tm.ltm.profile.server_ssls.server_ssl\n\n name = profile['name']\n\n # No need to create if it exists\n if ssl_server_profile.exists(name=name, partition=partition):\n return 0\n\n cert = profile['cert']\n cert_name = name + '.crt'\n incomplete = _install_certificate(mgmt, cert, cert_name)\n if incomplete > 0:\n # Unable to install cert\n return incomplete\n\n try:\n # create ssl-server profile\n serverName = profile.get('serverName', None)\n sniDefault = profile.get('sniDefault', False)\n ssl_server_profile.create(name=name,\n partition=partition,\n chain=cert_name,\n serverName=serverName,\n sniDefault=sniDefault)\n except Exception as err:\n incomplete += 1\n log.error(\"Error creating server SSL profile: %s\" % err.message)\n\n return incomplete\n\n\ndef _delete_unused_ssl_profiles(mgmt, partition, config):\n incomplete = 0\n\n # client profiles\n try:\n client_profiles = mgmt.tm.ltm.profile.client_ssls.get_collection(\n requests_params={'params': '$filter=partition+eq+%s'\n % partition})\n incomplete += _delete_ssl_profiles(config, client_profiles)\n except Exception as err:\n log.error(\"Error reading client SSL profiles from BIG-IP: %s\" %\n err.message)\n incomplete += 1\n\n # server profiles\n try:\n server_profiles = mgmt.tm.ltm.profile.server_ssls.get_collection(\n requests_params={'params': '$filter=partition+eq+%s'\n % partition})\n incomplete += _delete_ssl_profiles(config, server_profiles)\n except Exception as err:\n log.error(\"Error reading server SSL profiles from BIG-IP: %s\" %\n err.message)\n incomplete += 1\n\n return incomplete\n\n\ndef _delete_ssl_profiles(config, profiles):\n incomplete = 0\n\n if 'customProfiles' not in config:\n # delete any profiles in managed partition\n for prof in profiles:\n try:\n prof.delete()\n except Exception as err:\n log.error(\"Error deleting SSL profile: %s\" % err.message)\n incomplete += 1\n else:\n # delete profiles no longer in our config\n for prof in profiles:\n if not any(d['name'] == prof.name\n for d in config['customProfiles']):\n try:\n prof.delete()\n except Exception as err:\n log.error(\"Error deleting SSL profile: %s\" % err.message)\n incomplete += 1\n\n return incomplete\n\n\ndef _upload_crypto_file(mgmt, file_data, file_name):\n # bigip object is of type f5.bigip.tm;\n # we need f5.bigip.shared for the uploader\n uploader = mgmt.shared.file_transfer.uploads\n\n # In-memory upload -- data not written to local file system but\n # is saved as a file on the BIG-IP\n uploader.upload_bytes(file_data, file_name)\n\n\ndef _import_certificate(mgmt, cert_name):\n cert_registrar = mgmt.tm.sys.crypto.certs\n param_set = {}\n param_set['name'] = cert_name\n param_set['from-local-file'] = os.path.join(\n '/var/config/rest/downloads', cert_name)\n cert_registrar.exec_cmd('install', **param_set)\n\n\ndef _import_key(mgmt, key_name):\n key_registrar = mgmt.tm.sys.crypto.keys\n param_set = {}\n param_set['name'] = key_name\n param_set['from-local-file'] = os.path.join(\n '/var/config/rest/downloads', key_name)\n key_registrar.exec_cmd('install', **param_set)\n\n\ndef _install_certificate(mgmt, cert_data, cert_name):\n incomplete = 0\n\n try:\n if not _certificate_exists(mgmt, cert_name):\n # Upload and install cert\n _upload_crypto_file(mgmt, cert_data, cert_name)\n _import_certificate(mgmt, cert_name)\n\n except Exception as err:\n incomplete += 1\n log.error(\"Error uploading certificate %s: %s\" %\n (cert_name, err.message))\n\n return incomplete\n\n\ndef _install_key(mgmt, key_data, key_name):\n incomplete = 0\n\n try:\n if not _key_exists(mgmt, key_name):\n # Upload and install cert\n _upload_crypto_file(mgmt, key_data, key_name)\n _import_key(mgmt, key_name)\n\n except Exception as err:\n incomplete += 1\n log.error(\"Error uploading key %s: %s\" %\n (key_name, err.message))\n\n return incomplete\n\n\ndef _certificate_exists(mgmt, cert_name):\n # All certs are in the Common partition\n name_to_find = \"/Common/{}\".format(cert_name)\n for cert in mgmt.tm.sys.crypto.certs.get_collection():\n if cert.name == name_to_find:\n return True\n return False\n\n\ndef _key_exists(mgmt, key_name):\n # All keys are in the Common partition\n name_to_find = \"/Common/{}\".format(key_name)\n for key in mgmt.tm.sys.crypto.keys.get_collection():\n if key.name == name_to_find:\n return True\n return False\n\n\nclass ConfigHandler():\n def __init__(self, config_file, managers, verify_interval):\n self._config_file = config_file\n self._managers = managers\n\n self._condition = threading.Condition()\n self._thread = threading.Thread(target=self._do_reset)\n self._pending_reset = False\n self._stop = False\n self._backoff_time = 1\n self._backoff_timer = None\n self._max_backoff_time = 128\n\n self._interval = None\n self._verify_interval = 0\n self.set_interval_timer(verify_interval)\n\n self._thread.start()\n\n def set_interval_timer(self, verify_interval):\n if verify_interval != self._verify_interval:\n if self._interval is not None:\n self._interval.stop()\n self._interval = None\n\n self._verify_interval = verify_interval\n if self._verify_interval > 0:\n self._interval = IntervalTimer(self._verify_interval,\n self.notify_reset)\n\n def stop(self):\n self._condition.acquire()\n self._stop = True\n self._condition.notify()\n self._condition.release()\n if self._backoff_timer is not None:\n self.cleanup_backoff()\n\n def notify_reset(self):\n self._condition.acquire()\n self._pending_reset = True\n self._condition.notify()\n self._condition.release()\n\n def _do_reset(self):\n log.debug('config handler thread start')\n\n with self._condition:\n # customProfiles is true when we've written out a custom profile.\n # Once we know we've written out a profile, we can call delete\n # if needed.\n customProfiles = False\n while True:\n self._condition.acquire()\n if not self._pending_reset and not self._stop:\n self._condition.wait()\n log.debug('config handler woken for reset')\n\n self._pending_reset = False\n self._condition.release()\n\n if self._stop:\n log.info('stopping config handler')\n if self._backoff_timer is not None:\n self.cleanup_backoff()\n break\n\n start_time = time.time()\n\n config = _parse_config(self._config_file)\n # No 'resources' indicates that the controller is not\n # yet ready -- it does not mean to apply an empty config\n if 'resources' not in config:\n continue\n verify_interval, _ = _handle_global_config(config)\n _handle_openshift_sdn_config(config)\n self.set_interval_timer(verify_interval)\n\n cfg_network = create_network_config_kubernetes(config)\n incomplete = 0\n\n for mgr in self._managers:\n partition = mgr.get_partition()\n cfg_ltm = create_ltm_config_kubernetes(partition, config)\n try:\n # Manually create custom profiles;\n # CCCL doesn't yet do this\n if 'customProfiles' in cfg_ltm:\n tmp = 0\n customProfiles, tmp = _create_custom_profiles(\n mgr.mgmt_root(),\n partition,\n cfg_ltm['customProfiles'])\n incomplete += tmp\n\n # Apply the BIG-IP config after creating profiles\n # and before deleting profiles\n incomplete += mgr._apply_ltm_config(cfg_ltm)\n\n # Manually delete custom profiles (if needed)\n if customProfiles:\n _delete_unused_ssl_profiles(\n mgr.mgmt_root(),\n partition,\n cfg_ltm)\n\n except F5CcclError as e:\n # We created an invalid configuration, raise the\n # exception and fail\n log.error(\"CCCL Error: %s\", e.msg)\n raise e\n\n incomplete += mgr._apply_network_config(cfg_network)\n\n if incomplete:\n # Error occurred, perform retries\n self.handle_backoff()\n else:\n if (self._interval and self._interval.is_running()\n is False):\n self._interval.start()\n self._backoff_time = 1\n if self._backoff_timer is not None:\n self.cleanup_backoff()\n\n perf_enable = os.environ.get('SCALE_PERF_ENABLE')\n if perf_enable: # pragma: no cover\n test_data = {}\n app_count = 0\n backend_count = 0\n for service in config['resources']['virtualServers']:\n app_count += 1\n backends = 0\n for pool in config['resources']['pools']:\n if pool['name'] == service['name']:\n backends = len(pool['poolMemberAddrs'])\n break\n test_data[service['name']] = backends\n backend_count += backends\n test_data['Total_Services'] = app_count\n test_data['Total_Backends'] = backend_count\n test_data['Time'] = time.time()\n json_data = json.dumps(test_data)\n log.info('SCALE_PERF: Test data: %s',\n json_data)\n\n log.debug('updating tasks finished, took %s seconds',\n time.time() - start_time)\n\n if self._interval:\n self._interval.stop()\n\n def cleanup_backoff(self):\n \"\"\"Cleans up canceled backoff timers.\"\"\"\n self._backoff_timer.cancel()\n self._backoff_timer.join()\n self._backoff_timer = None\n\n def handle_backoff(self):\n \"\"\"Wrapper for calls to retry_backoff.\"\"\"\n if (self._interval and self._interval.is_running() is\n True):\n self._interval.stop()\n if self._backoff_timer is None:\n self.retry_backoff()\n\n def retry_backoff(self):\n \"\"\"Add a backoff timer to retry in case of failure.\"\"\"\n def timer_cb():\n self._backoff_timer = None\n self.notify_reset()\n\n self._backoff_timer = threading.Timer(\n self._backoff_time, timer_cb\n )\n log.error(\"Error applying config, will try again in %s seconds\",\n self._backoff_time)\n self._backoff_timer.start()\n if self._backoff_time < self._max_backoff_time:\n self._backoff_time *= 2\n\n\nclass ConfigWatcher(pyinotify.ProcessEvent):\n def __init__(self, config_file, on_change):\n basename = os.path.basename(config_file)\n if not basename or 0 == len(basename):\n raise ConfigError('config_file must be a file path')\n\n self._config_file = config_file\n self._on_change = on_change\n\n self._config_dir = os.path.dirname(self._config_file)\n self._config_stats = None\n if os.path.exists(self._config_file):\n try:\n self._config_stats = self._md5()\n except IOError as ioe:\n log.warning('ioerror during md5 sum calculation: {}'.\n format(ioe))\n\n self._running = False\n self._polling = False\n self._user_abort = False\n signal.signal(signal.SIGINT, self._exit_gracefully)\n signal.signal(signal.SIGTERM, self._exit_gracefully)\n\n def _exit_gracefully(self, signum, frame):\n self._user_abort = True\n self._running = False\n\n def _loop_check(self, notifier):\n if self._polling:\n log.debug('inotify loop ended - returning to polling mode')\n return True\n else:\n return False\n\n def loop(self):\n self._running = True\n if not os.path.exists(self._config_dir):\n log.info(\n 'configured directory doesn\\'t exist {}, entering poll loop'.\n format(self._config_dir))\n self._polling = True\n\n while self._running:\n try:\n while self._polling:\n if self._polling:\n if os.path.exists(self._config_dir):\n log.debug('found watchable directory - {}'.format(\n self._config_dir))\n self._polling = False\n break\n else:\n log.debug('waiting for watchable directory - {}'.\n format(self._config_dir))\n time.sleep(1)\n\n _wm = pyinotify.WatchManager()\n _notifier = pyinotify.Notifier(_wm, default_proc_fun=self)\n _notifier.coalesce_events(True)\n mask = (pyinotify.IN_CREATE | pyinotify.IN_DELETE |\n pyinotify.IN_MOVED_FROM | pyinotify.IN_MOVED_TO |\n pyinotify.IN_CLOSE_WRITE | pyinotify.IN_MOVE_SELF |\n pyinotify.IN_DELETE_SELF)\n _wm.add_watch(\n path=self._config_dir,\n mask=mask,\n quiet=False,\n exclude_filter=lambda path: False)\n\n log.info('entering inotify loop to watch {}'.format(\n self._config_file))\n _notifier.loop(callback=self._loop_check)\n\n if (not self._polling and _notifier._fd is None):\n log.info('terminating')\n self._running = False\n except Exception as e:\n log.warning(e)\n\n if self._user_abort:\n log.info('Received user kill signal, terminating.')\n\n def _md5(self):\n md5 = hashlib.md5()\n\n with open(self._config_file, 'rb') as f:\n fcntl.lockf(f.fileno(), fcntl.LOCK_SH, 0, 0, 0)\n while True:\n buf = f.read(4096)\n if not buf:\n break\n md5.update(buf)\n fcntl.lockf(f.fileno(), fcntl.LOCK_UN, 0, 0, 0)\n return md5.digest()\n\n def _should_watch(self, pathname):\n if pathname == self._config_file:\n return True\n return False\n\n def _is_changed(self):\n changed = False\n cur_hash = None\n if not os.path.exists(self._config_file):\n if cur_hash != self._config_stats:\n changed = True\n else:\n changed = False\n else:\n try:\n cur_hash = self._md5()\n if cur_hash != self._config_stats:\n changed = True\n else:\n changed = False\n except IOError as ioe:\n log.warning('ioerror during md5 sum calculation: {}'.\n format(ioe))\n\n return (changed, cur_hash)\n\n def process_default(self, event):\n if (pyinotify.IN_DELETE_SELF == event.mask or\n pyinotify.IN_MOVE_SELF == event.mask):\n log.warn(\n 'watchpoint {} has been moved or destroyed, using poll loop'.\n format(self._config_dir))\n self._polling = True\n\n if self._config_stats is not None:\n log.debug('config file {} changed, parent gone'.format(\n self._config_file))\n self._config_stats = None\n self._on_change()\n\n if self._should_watch(event.pathname):\n (changed, md5) = self._is_changed()\n\n if changed:\n log.debug('config file {0} changed - signalling bigip'.format(\n self._config_file, self._config_stats, md5))\n self._config_stats = md5\n self._on_change()\n\n\ndef _parse_config(config_file):\n if os.path.exists(config_file):\n with open(config_file, 'r') as config:\n fcntl.lockf(config.fileno(), fcntl.LOCK_SH, 0, 0, 0)\n config_json = json.load(config)\n fcntl.lockf(config.fileno(), fcntl.LOCK_UN, 0, 0, 0)\n log.debug('loaded configuration file successfully')\n return config_json\n else:\n return None\n\n\ndef _handle_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\n '--config-file',\n type=str,\n required=True,\n help='BigIp configuration file')\n args = parser.parse_args()\n\n basename = os.path.basename(args.config_file)\n if not basename or 0 == len(basename):\n raise ConfigError('must provide a file path')\n\n args.config_file = os.path.realpath(args.config_file)\n\n return args\n\n\ndef _handle_global_config(config):\n level = DEFAULT_LOG_LEVEL\n verify_interval = DEFAULT_VERIFY_INTERVAL\n\n if config and 'global' in config:\n global_cfg = config['global']\n\n if 'log-level' in global_cfg:\n log_level = global_cfg['log-level']\n try:\n level = logging.getLevelName(log_level.upper())\n except (AttributeError):\n log.warn('The \"global:log-level\" field in the configuration '\n 'file should be a string')\n\n if 'verify-interval' in global_cfg:\n try:\n verify_interval = float(global_cfg['verify-interval'])\n if verify_interval < 0:\n verify_interval = DEFAULT_VERIFY_INTERVAL\n log.warn('The \"global:verify-interval\" field in the '\n 'configuration file should be a non-negative '\n 'number')\n except (ValueError):\n log.warn('The \"global:verify-interval\" field in the '\n 'configuration file should be a number')\n\n try:\n root_logger.setLevel(level)\n if level > logging.DEBUG:\n logging.getLogger('requests.packages.urllib3.'\n 'connectionpool').setLevel(logging.WARNING)\n except:\n level = DEFAULT_LOG_LEVEL\n root_logger.setLevel(level)\n if level > logging.DEBUG:\n logging.getLogger('requests.packages.urllib3.'\n 'connectionpool').setLevel(logging.WARNING)\n log.warn('Undefined value specified for the '\n '\"global:log-level\" field in the configuration file')\n\n # level only is needed for unit tests\n return verify_interval, level\n\n\ndef _handle_bigip_config(config):\n if (not config) or ('bigip' not in config):\n raise ConfigError('Configuration file missing \"bigip\" section')\n bigip = config['bigip']\n if 'username' not in bigip:\n raise ConfigError('Configuration file missing '\n '\"bigip:username\" section')\n if 'password' not in bigip:\n raise ConfigError('Configuration file missing '\n '\"bigip:password\" section')\n if 'url' not in bigip:\n raise ConfigError('Configuration file missing \"bigip:url\" section')\n if ('partitions' not in bigip) or (len(bigip['partitions']) == 0):\n raise ConfigError('Configuration file must specify at least one '\n 'partition in the \"bigip:partitions\" section')\n\n url = urlparse(bigip['url'])\n host = url.hostname\n port = url.port\n if not port:\n port = 443\n\n return host, port\n\n\ndef _handle_openshift_sdn_config(config):\n if config and 'openshift-sdn' in config:\n sdn = config['openshift-sdn']\n if 'vxlan-name' not in sdn:\n raise ConfigError('Configuration file missing '\n '\"openshift-sdn:vxlan-name\" section')\n if 'vxlan-node-ips' not in sdn:\n raise ConfigError('Configuration file missing '\n '\"openshift-sdn:vxlan-node-ips\" section')\n\n\ndef main():\n try:\n args = _handle_args()\n\n config = _parse_config(args.config_file)\n verify_interval, _ = _handle_global_config(config)\n host, port = _handle_bigip_config(config)\n\n # FIXME (kenr): Big-IP settings are currently static (we ignore any\n # changes to these fields in subsequent updates). We\n # may want to make the changes dynamic in the future.\n\n # BIG-IP to manage\n bigip = ManagementRoot(\n host,\n config['bigip']['username'],\n config['bigip']['password'],\n port=port,\n token=\"tmos\")\n\n k8s_managers = []\n for partition in config['bigip']['partitions']:\n # Management for the BIG-IP partitions\n manager = K8sCloudServiceManager(\n bigip,\n partition,\n schema_path=SCHEMA_PATH)\n k8s_managers.append(manager)\n\n handler = ConfigHandler(args.config_file,\n k8s_managers,\n verify_interval)\n\n if os.path.exists(args.config_file):\n handler.notify_reset()\n\n watcher = ConfigWatcher(args.config_file, handler.notify_reset)\n watcher.loop()\n handler.stop()\n except (IOError, ValueError, ConfigError) as e:\n log.error(e)\n sys.exit(1)\n except Exception:\n log.exception('Unexpected error')\n sys.exit(1)\n\n return 0\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/bigipconfigdriver.py","file_name":"bigipconfigdriver.py","file_ext":"py","file_size_in_byte":36609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"464031836","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 30 23:29:14 2018\n\n@author: yui-sudo\n\"\"\"\n\nimport os\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom sound import WavfileOperate, Wavedata, Multiwave\nimport random\n\nimport shutil\nimport scipy\n\n\ndef sampling_reverb(signal_array, impulse_response, tf):\n \n sigL = len(signal_array)\n #irL = len(impulse_response)\n \n #new_irL = int((2 ** np.ceil(np.log2(abs(irL)))) * 2)\n new_irL = 512\n frameL = new_irL // 2\n #new_IR = np.zeros(new_irL, dtype=np.float64)\n #new_IR[:irL] = impulse_response\n \n #frame_num = int(np.ceil((sigL + frameL) / np.float(frameL)))\n frame_num = 257\n new_sigL = frameL * frame_num\n new_sig = np.zeros(new_sigL, dtype = np.float64)\n #new_sig[frameL : frameL + sigL] = signal_array\n new_sig = signal_array\n \n #ret = np.zeros(new_sigL - frame_num, dtype = np.float64)\n ret = np.zeros(new_sigL, dtype = np.float64)\n\n #ir_fft = scipy.fftpack.fft(new_IR) # impulse responce FFT\n ir_fft = tf * 0.65\n for ii in range(frame_num - 1):\n s_ind = frameL * ii\n e_ind = frameL * (ii + 2)\n \n sig_fft = scipy.fftpack.fft(new_sig[s_ind : e_ind])\n \n ret[s_ind:s_ind + frameL] = scipy.ifft(sig_fft * ir_fft)[frameL:].real\n\n return ret[:sigL]\n\n\ndef multi_conv(sig_wavedata, ir_multiwave, tf): \n wavedata_list = []\n for n in range(ir_multiwave.nchan):\n con = sampling_reverb(sig_wavedata.norm_sound, ir_multiwave.norm_sound[n], tf[n])\n conv = Wavedata(16000, con, sig_wavedata.name, sig_wavedata.nbyte)\n wavedata_list.append(conv)\n\n return wavedata_list[0], Multiwave(wavedata_list)\n \n \n#dirname = \"SMALL_STUFF\"\noverlap = 0.75\n\n\nfor image_size in [256]:\n total_length = image_size * 256 + 256\n n = 4\n for mode in [\"train\", \"val\"]:\n dry_dir = os.getcwd() + \"/elements/\"+mode+\"/\"\n if mode == \"train\":\n totalnum = 10\n else:\n totalnum = 0\n for datanum in range(0,totalnum):\n print(\"\\n\\n\\nNo.\", datanum) \n name = \"\"\n namelist = []\n namelist2 = []\n wavelist = []\n multiwavelist = []\n text = \"\"\n same = False\n \n idx = 0\n long_n = 0\n short_n = 0\n for i in range(n):\n # a1, a2, b1, b2 ...\n dir1_list = os.listdir(dry_dir)\n dir1 = dir1_list[random.randrange(len(dir1_list))] \n \n #dir1 = dirname\n \n cur_dir = dry_dir + dir1 \n if os.path.isdir(cur_dir) == True: \n dir2_list = os.listdir(cur_dir)\n dir2 = dir2_list[random.randrange(len(dir2_list))] \n cur_dir = cur_dir + \"/\" + dir2 + \"/\" \n namelist.append(dir1+\"_\"+dir2) \n data_list = os.listdir(cur_dir)\n \n filename = cur_dir + data_list[random.randrange(len(data_list))]\n \n if filename[-3:] == \"wav\" or filename[-3:] == \"wav\":\n wave = WavfileOperate(filename).wavedata\n \n if len(wave.norm_sound) > total_length // 1:\n if long_n == 1:\n wave = wave.cut_wav(0, 2, window=True)\n \n short_n += 1\n length = len(wave.norm_sound)\n if idx == 0:\n idx = random.randrange(5000)\n else:\n idx = (idx - random.randrange(overlap * wave.fs))\n \n if idx < 0:\n idx = 0\n elif (idx + length) > total_length:\n wave = wave.cut_wav(0, (total_length-idx)/wave.fs, window=False)\n length = len(wave.norm_sound)\n \n print(round(idx/wave.fs,2), \"-\", round((idx+length)/wave.fs,2))\n \n wave = wave.zero_padding(total=total_length, start_idx=idx)\n idx += length \n \n print(\"long_over!!!!\")\n \n else:\n wave = wave.cut_wav(0, 4.112, window=False)\n long_n += 1\n\n else:\n short_n += 1\n\n length = len(wave.norm_sound)\n if idx == 0:\n idx = random.randrange(5000)\n else:\n idx = (idx - random.randrange(overlap * wave.fs))\n\n if idx < 0:\n idx = 0\n elif (idx + length) > total_length:\n wave = wave.cut_wav(0, (total_length-idx)/wave.fs, window=False)\n length = len(wave.norm_sound)\n print(round(idx/wave.fs,2), \"-\", round((idx+length)/wave.fs,2))\n \n wave = wave.zero_padding(total=total_length, start_idx=idx)\n idx += length \n \n if not len(wave.norm_sound) == total_length:\n print(\"Size error!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n \n if wave.norm_sound.max() > 1.0:\n print(\"clipping!!!!!!!!!!!!!!!!!!!\")\n print(wave.norm_sound.max())\n ### wave conv\n ir_dir = \"./impulse_response/\"\n deg = random.randrange(8) * 45\n tf = np.load(ir_dir+\"tf_\" + str(deg) + \"deg.npy\")\n ir_multi = WavfileOperate(ir_dir+\"impulse_\"+str(deg)+\"deg.wav\", logger=1).multiwave\n #print(ir_multi.name)\n wave, multiwave = multi_conv(wave, ir_multi, tf)\n \n for nchan in range(8):\n if multiwave.norm_sound[nchan].max() > 1.0:\n multiwave.plot()\n print(\"clipping!!!!!!!!!!!!!!!!!!!\")\n print(multiwave.norm_sound[nchan].max())\n \n if not len(multiwave.norm_sound[0]) == total_length:\n print(\"Size error!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n \n \n text = text + dir2 + \"_\" + str(deg) + \"deg\\n\"\n \n \n \n if len(wavelist) == 0:\n wavelist.append(wave)\n name = name + \"_\" + dir2\n namelist2.append(dir2)\n syn_wave = wave\n multi_syn_wave = multiwave\n \n elif len(wavelist) > 0:\n for j in range(len(namelist2)):\n if dir2 == namelist2[j]:\n wavelist[j] = wavelist[j].synthesis(wave, synthesis_name=dir2)\n same = True\n break\n if same == False:\n wavelist.append(wave)\n name = name + \" \" + dir2\n namelist2.append(dir2)\n same = False\n\n syn_wave = syn_wave.synthesis(wave, synthesis_name = name)\n multi_syn_wave = multi_syn_wave.synthesis(multiwave, synthesis_name = name)\n \n \n if idx >= total_length:\n idx = 0\n #break \n else:\n continue\n \n \n for noise_db in [-30, -20, -10, 0]:\n noise_segdata_dir = os.getcwd()+\"/datasets/multi_segdata76_\"+str(image_size)+\"_\"+ str(noise_db)+\"dB/\"+mode+\"/\"\n segdata_dir = os.getcwd()+\"/datasets/multi_segdata75_\"+str(image_size)+\"_no_sound/\"+mode+\"/\"\n #noise_segdata_dir = os.getcwd()+\"/datasets/\"+dirname+\"_\"+str(image_size)+\"_\"+ str(noise_db)+\"dB/\"+mode+\"/\"\n #segdata_dir = os.getcwd()+\"/datasets/\"+dirname+\"_\"+str(image_size)+\"/\"+mode+\"/\"\n\n \n if datanum % 2 == 0:\n bgm = WavfileOperate(os.getcwd()+'/BGMs/restaurant.wav').wavedata.vol(noise_db) \n else: \n bgm = WavfileOperate(os.getcwd()+'/BGMs/hall.wav').wavedata.vol(noise_db)\n nframe = len(bgm.norm_sound)\n start_idx = random.randrange(nframe - 9 * bgm.fs)\n cut_sound = bgm.norm_sound[start_idx:start_idx + total_length] \n bgm = Wavedata(bgm.fs, cut_sound, bgm.name, bgm.nbyte)\n noise_syn_wave = syn_wave.synthesis(bgm, synthesis_name = name)\n \n no_sound = WavfileOperate(os.getcwd()+'/BGMs/no_sound.wav').wavedata.vol(0)\n syn_wave = syn_wave.synthesis(no_sound, synthesis_name = name)\n\n bgm_list = []\n no_sound_list = []\n for mic_chan in range(8):\n bgm_list.append(bgm)\n no_sound_list.append(no_sound)\n multi_bgm = Multiwave(bgm_list)\n multi_no_sound = Multiwave(no_sound_list)\n multi_syn_wave = multi_syn_wave.synthesis(multi_no_sound, synthesis_name = name)\n multi_noise_syn_wave = multi_syn_wave.synthesis(multi_bgm, synthesis_name = name)\n \n \n #noise_syn_wave.plot()\n #bgm.stft_plot()\n \"\"\"\n if noise_db == -30:\n syn_wave.stft_plot()\n noise_syn_wave.stft_plot()\n multi_syn_wave.stft_plot()\n \"\"\"\n \n noise_save_dir = noise_segdata_dir + str(datanum) + \"/\" \n if not os.path.exists(noise_save_dir):\n os.makedirs(noise_save_dir)\n save_dir = segdata_dir + str(datanum) + \"/\" \n if not os.path.exists(save_dir):\n os.makedirs(save_dir)\n \n for i in range(len(wavelist)):\n #if noise_db == -30:\n # wavelist[i].stft_plot()\n wavelist[i].write_wav_sf(dir=noise_save_dir, filename=namelist2[i] + \".wav\", bit=16)\n if noise_db == -30:\n wavelist[i].write_wav_sf(dir=save_dir, filename=namelist2[i] + \".wav\", bit=16)\n with open(save_dir+'sound_direction.txt', 'w') as f:\n f.write(text)\n \n bgm.write_wav_sf(dir=noise_save_dir, filename=\"BGM.wav\", bit=16)\n noise_syn_wave.write_wav_sf(dir=noise_save_dir, filename=\"0_\" + name + \".wav\", bit=16)\n\n multi_noise_syn_wave.write_wav_sf(dir=noise_save_dir, filename=\"0_multi_\" + name + \".wav\", bit=16)\n if noise_db == -30:\n syn_wave.write_wav_sf(dir=save_dir, filename=\"0_\" + name + \".wav\", bit=16)\n multi_syn_wave.write_wav_sf(dir=save_dir, filename=\"0_multi_\" + name + \".wav\", bit=16) \n if not os.getcwd() == '/home/yui-sudo/document/segmentation/sound_segtest':\n shutil.copy(\"make_dataset4_multi.py\", segdata_dir)\n shutil.copy(\"make_dataset4_multi.py\", noise_segdata_dir)\n \n with open(noise_save_dir+'sound_direction.txt', 'w') as f:\n f.write(text)\n ","sub_path":"make_dataset4_multi.py","file_name":"make_dataset4_multi.py","file_ext":"py","file_size_in_byte":12553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"386376343","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n'''在指定的范围内返回均匀分布的数字'''\nx = np.linspace(0,2*np.pi,500)\n'''函数'''\ny = np.sin(x)\nz = np.cos(x*x)\nplt.figure(figsize = (8,4))\n''' r--:红色的破折号;bs:蓝色的方块;g^:绿色的三角形'''\n'''定义颜色,宽度,图例名称,线的方式(无则为光滑曲线)\n并将x与y、z分别对应'''\nplt.plot(x,y,label ='sin(x)',color = 'yellow',linewidth = 2)\nplt.plot(x,z,label = 'cos(x^2)',color = 'green' ,linewidth = 2)\n'''x轴名称'''\nplt.xlabel('Time(S)')\n'''y轴名称'''\nplt.ylabel('Volt')\n'''标题'''\nplt.title('sin(x) and cos(x^2) figure')\n'''y轴上下限,没有默认'''\n#plt.ylim(-1.3,1.3)\n'''图例'''\nplt.legend()\nplt.show()\n","sub_path":"Python homework/sin-cos(x^2)曲线图.py","file_name":"sin-cos(x^2)曲线图.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"46098921","text":"import requests\n\nurl = 'http://127.0.0.1:5000/api/user/'\n\ndata = {'user': {'email_address': 'ashley.collinge@outlook.com',\n 'name': 'Ashley Collinge',\n 'user_type': 'agent'}\n}\n\nr = requests.post(url, json=data)\n\n# Response, status etc\nprint(r.text)\nprint(r.status_code)","sub_path":"scripts/NewUserTest.py","file_name":"NewUserTest.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"142916273","text":"# -*- coding: utf-8 -*-\nimport os\nimport DataAq\nimport threading\nimport numpy as np\n\n\nSHOWDATA_LEN = 3000 # 窗口长度\nDATA_PERREAD = 500 # 每次读取数据长度\n\n\nclass DataRS():\n def __init__(self, host='192.168.56.1', channel=(0, 0)):\n self.dev = DataAq.TrignoDaq(addr=host, channel_range=channel, samples_per_read=DATA_PERREAD)\n self.files_num = len(os.listdir('./Data/'))\n self.newdata = []\n\n def rs_run(self):\n self.dev.start()\n while True:\n self.data_read()\n thread_1 = threading.Thread(target=self.data_save(), name='T1')\n thread_1.start() # 开启T1\n yield self.newdata\n\n def data_read(self):\n self.newdata = self.dev.read()\n\n def data_save(self):\n with open('./Data/data_' + str(self.files_num + 1) + '.txt', 'a') as f:\n np.save(f, self.newdata, fmt=\"%f\", delimiter=' ', newline='\\n')\n f.close()\n\n\n\n\n","sub_path":"On_Time/DataRS.py","file_name":"DataRS.py","file_ext":"py","file_size_in_byte":946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573259881","text":"# Authors: Iliya \"eLeMeNOhPi\" Alavy - Department of Engineering - Michigan State University\n# \t\t Alexander Bricco - Department of Bioengineering - Michigan State University\nimport rule as Rule\nimport settings\nimport random as R\n\nclass Individual:\n\t# Constructor \n\tdef __init__(self):\n\t\tself.TT = settings.TT\n\t\tself.aSize = settings.alphabet_size\n\t\tself.rules = []\n\t\tself.ruleSize = settings.rule_size\n\t\tself.maxRuleCount = settings.maximum_rule_count\n\t\tself.minWeight = settings.rule_weight_min\n\t\tself.maxWeight = settings.rule_weight_max\n\t\tself.fitness = 0\n\n\tdef init_pattern(self):\n\t\tcodes = self.TT['code']\n\t\tfor i in range(R.randint(1, self.maxRuleCount)):\n\t\t\tpattern = \"\"\n\t\t\tweight = round(R.uniform(self.minWeight, self.maxWeight), 2)\n\t\t\t# Add these many rules\n\t\t\tfor j in range(R.randint(1, self.ruleSize)):\n\t\t\t\t# Rule size is calculated randomly, and now we need to select a random combination of codes with a specified size\n\t\t\t\tcode = codes[R.randint(0, codes.size - 1)]\n\t\t\t\trandomchar = code[R.randint(0, (len(code) - 1))]\n\t\t\t\tpattern += randomchar\n\t\t\trule = Rule.Rule(pattern, weight)\n\t\t\tself.rules.append(rule)\n\n\t\t# for i in self.rules:\n\t\t# \tprint(str(i.pattern) + \" => \" + str(i.weight))\n\n\t\t# print (\"\\n\\n\")\n\t\tself.bubbleSort()\n\n\t\t# for i in self.rules:\n\t\t# \tprint(str(i.pattern) + \" => \" + str(i.weight))\n\n\n\tdef init_formula(self):\n\t\tpass\n\t\n\tdef bubbleSort(self):\n\t n = len(self.rules)\n\t # Traverse through all array elements\n\t for i in range(n):\n\t # Last i elements are already in place\n\t for j in range(0, n-i-1):\n\t # traverse the array from 0 to n-i-1\n\t # Swap if the element found is greater\n\t # than the next element\n\t if len(self.rules[j].pattern) < len(self.rules[j+1].pattern):\n\t \tself.rules[j], self.rules[j+1] = self.rules[j+1], self.rules[j] \n\n\n\n","sub_path":"individual.py","file_name":"individual.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"394649006","text":"from decimal import Decimal\nfrom pprint import pprint\nimport wx, sys, os\nimport wx.lib.filebrowsebutton as filebrowse\nfrom configobj import ConfigObj\nfrom validate import Validator\nfrom ObjectListView import ObjectListView, ColumnDefn\nimport amara\nimport Ft.Lib.Uri as uri\nimport wx.lib.dialogs\ntry:\n import wx.lib.inspection\nexcept ImportError:\n pass\n\ntry:\n import cStringIO\n StringIO = cStringIO\nexcept ImportError:\n import StringIO\n\nclass Global(object):\n \"\"\"Generic container for shared variables.\"\"\"\n cfgFileName = os.getcwd() + os.sep + 'sPxml.ini'\n \n tmpStr = \"\"\"[Current]\n InHist = string_list(default=None)\n OutHist = string_list(default=None)\n AutoName = boolean(default=True)\n SuppressZeroBal = boolean(default=False)\n \n \"\"\"\n cfgSpec = StringIO.StringIO(tmpStr)\n cfgFile = ConfigObj(cfgFileName, \n configspec=cfgSpec, raise_errors=True, write_empty_values = True, \n create_empty=True, indent_type=' ', list_values = True)\n vtor = Validator()\n \nclass Log(object):\n \"\"\"Log output is redirected to the status bar of the containing frame.\"\"\"\n def WriteText(self,text_string):\n self.write(text_string)\n def write(self,text_string):\n wx.GetApp().GetTopWindow().SetStatusText(text_string)\n\nclass StmtObj(object):\n def __init__(self, acctNum, patName, balAmt, balFwd, stmtXML):\n self.acctNum = acctNum\n self.patName = patName\n self.balAmt = balAmt\n self.balFwd = balFwd\n self.stmtXML = stmtXML\n \nclass SummaryDialog(wx.Dialog):\n def __init__(self, parent, ID, title, size=wx.DefaultSize, pos=(50,50),\n style=wx.DEFAULT_DIALOG_STYLE, text=\"\"):\n wx.Dialog.__init__(self, parent, ID, title, pos, size, style)\n\n sizer = wx.BoxSizer(wx.VERTICAL)\n #sizer.Add(wx.StaticText(self, -1, \"\\\"Regular\\\" statements (containing detail):\"))\n\n text = wx.TextCtrl(self, -1, text, size=wx.Size(775,500), style=wx.TE_MULTILINE|wx.TE_AUTO_SCROLL|wx.TE_DONTWRAP)\n font1 = wx.Font(8, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Courier New')\n text.SetFont(font1)\n\n sizer.Add(text, 1, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)\n\n\n btnsizer = wx.StdDialogButtonSizer()\n \n btn = wx.Button(self, wx.ID_OK)\n btn.SetDefault()\n btnsizer.AddButton(btn)\n\n btn = wx.Button(self, wx.ID_CANCEL)\n btnsizer.AddButton(btn)\n btnsizer.Realize()\n\n sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)\n\n self.SetSizer(sizer)\n sizer.Fit(self)\n\n\n\nclass MyFrame(wx.Frame):\n ID_LOAD = wx.NewId()\n \n def __init__(self, parent, id, title, size, style = wx.DEFAULT_FRAME_STYLE ):\n wx.Frame.__init__(self, parent, id, title, size=size, style=style)\n self.CreateStatusBar(1)\n self.log=Log()\n Global.stmtList = []\n \n pnl = wx.Panel(self)\n \n #---Create checkboxes\n \n Opts = [\n {\"Name\": \"AutoName\", \"Label\":\"Auto-name output file?\", \"Tip\":\"Do you want to automatically name the output file by adding 'gw-' to the beginning?\"},\n {\"Name\": \"SuppressZeroBal\", \"Label\":\"Suppress zero balances?\", \"Tip\":\"Do you want to skip any charges that already have zero balances?\"}]\n self.Options = {}\n for opt in Opts:\n nom, lbl, tip = opt[\"Name\"], opt[\"Label\"], opt[\"Tip\"]\n self.Options[nom] = wx.CheckBox(pnl, -1, lbl, style=wx.ALIGN_LEFT, name=nom)\n self.Options[nom].SetToolTip(wx.ToolTip(tip))\n self.Options[nom].SetValue(Global.cfgFile['Current'][nom])\n self.Bind(wx.EVT_CHECKBOX, self.OnChange, self.Options[nom])\n \n fpOpt = {\n \"In\": {\"Label\":\"Original: \", \"Title\":\"Tell me where to find the original file\", \"Mode\":wx.OPEN},\n \"Out\":{\"Label\":\"Converted:\", \"Title\":\"Tell me where to save the converted file\", \"Mode\":wx.SAVE}, }\n self.filePicker ={}\n for option, detail in fpOpt.iteritems():\n self.filePicker[option] = filebrowse.FileBrowseButtonWithHistory(pnl, -1, \n labelText=detail[\"Label\"], fileMask='*.*', \n fileMode=detail[\"Mode\"], dialogTitle=detail[\"Title\"], \n changeCallback=lambda x, option=option: self.fpCallback(x, option))\n if Global.cfgFile['Current'].has_key(option+'Hist'):\n try: #is it a single item, \n tmpList = Global.cfgFile['Current'][option + \"Hist\"].split(',')\n except AttributeError: # or a list?\n tmpList = Global.cfgFile['Current'][option + \"Hist\"]\n self.filePicker[option].callCallback = False\n self.filePicker[option].SetHistory(tmpList, 0)\n self.filePicker[option].callCallback = True\n\n outerMost = wx.BoxSizer(wx.VERTICAL)\n \n #---File locations\n box2 = wx.StaticBox(pnl, -1, \"Location of statement files:\")\n boxMidLeft = wx.StaticBoxSizer(box2, wx.VERTICAL)\n\n \n boxMidLeft.Add(self.filePicker[\"In\"], 0, wx.ALIGN_LEFT|wx.EXPAND|wx.LEFT|wx.RIGHT, 5)\n boxMidLeft.Add(self.filePicker[\"Out\"], 0, wx.ALIGN_LEFT|wx.EXPAND|wx.LEFT|wx.RIGHT, 5)\n boxMidLeft.Add(self.Options[\"AutoName\"], 0, wx.ALIGN_LEFT|wx.EXPAND|wx.ALL, 5)\n boxMidLeft.Add(self.Options[\"SuppressZeroBal\"], 0, wx.ALIGN_LEFT|wx.EXPAND|wx.ALL, 5)\n outerMost.Add(boxMidLeft, 0, wx.ALIGN_LEFT|wx.EXPAND|wx.ALL, 10)\n\n #---Buttons\n \n boxBtns = [wx.BoxSizer(wx.HORIZONTAL), wx.BoxSizer(wx.HORIZONTAL)]\n Buttons = [\n {\"Name\": \"Load\", \"Tip\": \"Click here to read in Prime statements from the \\\"Original\\\" file.\"},\n {\"Name\": \"Save\", \"Tip\": \"After you have selected the statements you want, click here to save them to the \\\"Converted\\\" file.\"},\n {\"Name\": \"Cancel\", \"Tip\": \"Click here to exit without doing anything.\"},\n {\"Name\": \"Check All\",\"Tip\": \"Click here to select all patients.\"},\n {\"Name\": \"Clear All\",\"Tip\": \"Click here to de-select all patients.\"},\n ]\n self.Button ={}\n tmpCount = 0\n for btn in Buttons:\n self.Button[btn[\"Name\"]] = wx.Button(pnl, -1, label=btn[\"Name\"], name=btn[\"Name\"])\n self.Button[btn[\"Name\"]].SetToolTip(wx.ToolTip(btn[\"Tip\"]))\n boxBtns[tmpCount / 3].Add(self.Button[btn[\"Name\"]], 0, wx.ALIGN_CENTER|wx.ALL)\n boxBtns[tmpCount / 3].Add((10,10), 0, wx.EXPAND)\n self.Bind(wx.EVT_BUTTON, self.OnClick, self.Button[btn[\"Name\"]])\n tmpCount +=1\n outerMost.Add(boxBtns[0], 0, wx.ALIGN_CENTER|wx.EXPAND|wx.ALL, 10)\n outerMost.Add(wx.StaticLine(pnl), 0, wx.EXPAND)\n outerMost.Add(boxBtns[1], 0, wx.ALIGN_CENTER|wx.EXPAND|wx.ALL, 5)\n\n #---List\n self.oLV = ObjectListView(pnl, -1, style=wx.LC_REPORT|wx.SUNKEN_BORDER)\n \n simpleColumns = [\n ColumnDefn(\"Account\", valueGetter=\"acctNum\", minimumWidth= 60, maximumWidth=100),\n ColumnDefn(\"Name\", valueGetter=\"patName\", minimumWidth=100, maximumWidth=300, isSpaceFilling=True),\n ColumnDefn(\"Balance\", \"right\", valueGetter=\"balAmt\", minimumWidth=50, maximumWidth=100),\n ColumnDefn(\"BalFwd\", \"right\", valueGetter=\"balFwd\", minimumWidth=50, maximumWidth=100)\n ]\n\n def rowFormatter(listItem, stmt):\n if stmt.balFwd != 0:\n listItem.SetTextColour(wx.RED)\n\n self.oLV.rowFormatter = rowFormatter\n self.oLV.SetColumns(simpleColumns)\n self.oLV.CreateCheckStateColumn()\n self.oLV.SetObjects(Global.stmtList)\n\n\n outerMost.Add(self.oLV, 1, wx.ALIGN_CENTER|wx.EXPAND|wx.ALL, 5)\n \n pnl.SetSizer(outerMost)\n\n\n\n def fpCallback(self, evt, option):\n value = evt.GetString()\n if not value:\n return()\n if option == \"In\" and Global.cfgFile['Current']['AutoName']:\n self.filePicker['Out'].SetValue(os.path.split(self.filePicker['Out'].GetValue())[0] + os.sep + \"gw-\" + os.path.split(self.filePicker['In'].GetValue())[1])\n \n if (self.filePicker[\"Out\"].GetValue() == self.filePicker[\"In\"].GetValue()):\n dlg = wx.MessageDialog(None, \"You're asking me to over-write the original file. You sure about that?\", \n \"You have chosen... oddly.\", \n style=wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)\n response = dlg.ShowModal()\n dlg.Destroy()\n if (response == wx.ID_NO):\n return()\n history = self.filePicker[option].GetHistory()\n if value in history: # if it already existed, remove it\n history.pop(history.index(value))\n history.insert(0, value) # either way, insert it at the head of the list\n while len(history) > 10: # pop items off the end until history is x items long... \n history.pop()\n self.filePicker[option].SetHistory(history)\n self.filePicker[option].GetHistoryControl().SetStringSelection(value)\n Global.cfgFile['Current'][option+'Hist'] = history\n Global.cfgFile.write()\n\n def OnChange(self, evt):\n option = evt.GetEventObject().Name\n Global.cfgFile['Current'][option] = evt.GetEventObject().GetValue()\n Global.cfgFile.write()\n if option == \"SuppressZeroBal\":\n self.oLV.DeleteAllItems()\n #self.oLV.Refresh()\n\n def OnClick(self, event):\n btn = event.GetEventObject().Name\n if (btn == \"Cancel\"):\n self.Close(True)\n sys.exit()\n if (btn == \"Load\"):\n inPathStr = r'file:' + str(self.filePicker[\"In\"].GetValue())\n self.log.write('About to convert %s' % uri.UriToOsPath(inPathStr))\n if not (os.path.exists(uri.UriToOsPath(inPathStr))):\n self.log.write(\"Select a valid source file!\")\n return\n else:\n Global.stmtList = self.GenStmt(inPathStr)\n self.log.write('Loaded %s statements' % len(Global.stmtList))\n self.oLV.SetObjects(Global.stmtList)\n if (btn == \"Check All\"):\n unchecked = [x for x in self.oLV.modelObjects if not self.oLV.IsChecked(x)] \n for item in unchecked :\n self.oLV.Check(item)\n self.oLV.RefreshObjects(unchecked)\n if (btn == \"Clear All\"):\n checked = self.oLV.GetCheckedObjects()\n for item in checked:\n self.oLV.Uncheck(item)\n self.oLV.RefreshObjects(checked)\n\n\n if (btn == \"Save\"):\n if len(self.oLV.GetCheckedObjects()) == 0:\n self.log.write('No statements selected - Nothing to save!')\n return()\n\n self.Button[\"Cancel\"].SetLabel(\"Exit\")\n outPathStr = r'file:' + str(self.filePicker[\"Out\"].GetValue())\n outPathStr = str(self.filePicker[\"Out\"].GetValue())\n outDoc = amara.create_document(u\"statement_batch\")\n outList = [ \" Account Name Balance BalFwd\",\n \"=========================================================================\"]\n for item in self.oLV.GetCheckedObjects():\n outDoc.statement_batch.xml_append(item.stmtXML)\n outList.append(\"%s%s %s%s%s%s%s%s\" % (\" \"*(10-len(item.acctNum)), item.acctNum, \n item.patName, \" \"*(40-len(item.patName)), \n \" \"*(10-len(str(item.balAmt))), str(item.balAmt), \n \" \"*(10-len(str(item.balFwd))), str(item.balFwd)))\n outFile = open(outPathStr,'w+b')\n outDoc.xml(outFile,indent=u'yes')\n outFile.close()\n self.log.write('Saved %s statements' % len(self.oLV.GetCheckedObjects()))\n\n dlg = SummaryDialog(self, -1, \"Summary of converted statements\", \n text=\"\\n\".join(outList), size=wx.Size(750,500), \n style=wx.OK|wx.CAPTION|wx.RESIZE_BORDER|wx.CLOSE_BOX|wx.MAXIMIZE_BOX|wx.MINIMIZE_BOX|wx.SYSTEM_MENU)\n font1 = wx.Font(10, wx.SWISS, wx.NORMAL, wx.NORMAL, False, u'Courier')\n dlg.SetFont(font1)\n response = dlg.ShowModal()\n dlg.Destroy()\n\n def GenStmt(self,inPathStr):\n stmtList = []\n inDoc = amara.parse(inPathStr)\n outDoc = amara.create_document(u\"statement_batch\")\n\n for stmt in inDoc.statements.statement:\n preBalOnly = False\n if len(stmt.row.xml_children) == 0:\n preBalOnly = True\n outStmt = outDoc.xml_create_element(u\"statement\")\n outElem = outDoc.xml_create_element(u\"practice_name\", content=stmt.clinic.name)\n outStmt.xml_append(outElem)\n \n if preBalOnly:\n outElem = outDoc.xml_create_element(u\"patient_name\", content=stmt.to.name)\n else:\n outElem = outDoc.xml_create_element(u\"patient_name\", content=stmt.row.charge.patient)\n outStmt.xml_append(outElem)\n\n outElem = outDoc.xml_create_element(u\"remit_to\", \n attributes={u\"name\": stmt.doctor.name, \n u\"address1\": stmt.clinic.address,\n u\"address2\":u\"\",\n u\"city\": stmt.clinic.city.split(\",\")[0].strip(),\n u\"state\": stmt.clinic.city.split(\",\")[1].strip(),\n u\"zip\": stmt.clinic.city.split(\",\")[2].strip()})\n outStmt.xml_append(outElem)\n \n outElem = outDoc.xml_create_element(u\"make_payment_to\", content=stmt.doctor.name)\n outStmt.xml_append(outElem)\n\n outElem = outDoc.xml_create_element(u\"recipient\", \n attributes={u\"name\": stmt.to.name, \n u\"address1\": stmt.to.address,\n u\"address2\": stmt.to.address2,\n u\"city\": stmt.to.city.split(\",\")[0].strip(),\n u\"state\": stmt.to.city.split(\",\")[1].strip()[:2],\n u\"zip\": stmt.to.city.split(\",\")[1].strip()[3:]})\n outStmt.xml_append(outElem)\n \n outElem = outDoc.xml_create_element(u\"accept_credit_cards\", content=u\"Yes\")\n outStmt.xml_append(outElem)\n \n outElem = outDoc.xml_create_element(u\"cards_accepted\", content=u\"MasterCard, Visa, American Express\")\n outStmt.xml_append(outElem)\n \n outElem = outDoc.xml_create_element(u\"statement_date\", content=stmt.date)\n outStmt.xml_append(outElem)\n \n outElem = outDoc.xml_create_element(u\"billing_numbers\", content=stmt.acct.number)\n outStmt.xml_append(outElem)\n totChg = Decimal(0)\n totPay = Decimal(0)\n totAdj = Decimal(0)\n totDis = Decimal(0)\n totW_O = Decimal(0)\n dirtyChg = False\n supPress = False # \"suppress this line\" - best name I could think of for now\n \n for e in stmt.row.xml_children:\n if isinstance(e, unicode): # don't try to process element separators!\n continue\n if e.nodeName == u\"charge\":\n #print('Charge!')\n if dirtyChg: # if a charge record is already open, close it\n chgElem.xml_append(sbtElem)\n chgElem.xml_append(sbbElem)\n outStmt.xml_append(chgElem)\n if Global.cfgFile[\"Current\"][\"SuppressZeroBal\"]:\n if e.balance == \"0.00\":\n supPress = True\n dirtyChg = False\n continue\n supPress = False\n dirtyChg = True\n \n thisChg = Decimal(e.charge)\n totChg += thisChg\n chgElem = outDoc.xml_create_element(u\"charge\", \n attributes={u\"code\": e.procedure, \n u\"description\": e.description,\n u\"date\": e.date,\n u\"amount\": e.charge,\n u\"deductible\": e.deductible\n })\n if e.payment == u\"0.00\":\n thisPay = Decimal(0)\n else:\n thisPay = -1 * Decimal(e.payment)\n if e.adjustment == u\"0.00\":\n thisAdj = Decimal(0)\n else:\n thisAdj = -1 * Decimal(e.adjustment)\n\n sbtElem = outDoc.xml_create_element(u\"subtotal\", \n attributes={u\"paid\": unicode(\"%0.2F\" % thisPay), \n u\"disallowed\": unicode(\"%0.2F\" % 0),\n u\"adjustment\": unicode(\"%0.2F\" % thisAdj),\n u\"writeoff\": unicode(\"%0.2F\" % 0)})\n sbbElem = outDoc.xml_create_element(u\"subbalance\", content= e.balance)\n elif e.nodeName == u\"creditpay\":\n #print('Pay!')\n if supPress: \n continue\n if e.payment == u\"0.00\":\n thisPay = Decimal(0)\n else:\n thisPay = -1 * Decimal(e.payment)\n totPay += thisPay\n\n payElem = outDoc.xml_create_element(u\"payment\", \n attributes={u\"payer\": stmt.insurance.code, \n u\"date\": e.date,\n u\"paid\": unicode(\"%0.2F\" % thisPay)})\n chgElem.xml_append(payElem)\n elif e.nodeName == u\"creditadj\":\n #print('Adjust!')\n if supPress: \n continue\n if e.adjustment == u\"0.00\":\n thisAdj = Decimal(0)\n else:\n thisAdj = -1 * Decimal(e.adjustment)\n totAdj += thisAdj\n\n if dirtyChg: # clean up last open charge record\n chgElem.xml_append(sbtElem)\n chgElem.xml_append(sbbElem)\n outStmt.xml_append(chgElem)\n dirtyChg = False\n\n if preBalOnly:\n outElem = outDoc.xml_create_element(u\"total_charges\", content=stmt.agedbalances.prebalance)\n else:\n outElem = outDoc.xml_create_element(u\"total_charges\", content=unicode(totChg))\n outStmt.xml_append(outElem)\n\n outElem = outDoc.xml_create_element(u\"total_payment\", \n attributes={u\"paid\": unicode(\"%0.2F\" % totPay), \n u\"disallowed\": unicode(\"%0.2F\" % totDis),\n u\"adjustment\": unicode(\"%0.2F\" % totAdj),\n u\"writeoff\": unicode(\"%0.2F\" % totW_O)})\n outStmt.xml_append(outElem)\n\n outElem = outDoc.xml_create_element(u\"patient_message\", content=stmt.remark.text)\n outStmt.xml_append(outElem)\n\n outElem = outDoc.xml_create_element(u\"balance_due\", content=stmt.agedbalances.amountDue)\n outStmt.xml_append(outElem)\n \n stmtList.append(StmtObj(stmt.acct.number, stmt.to.name, Decimal(stmt.agedbalances.amountDue), Decimal(stmt.agedbalances.prebalance), outStmt))\n \n return(stmtList)\n\n \n#----------------------------------------------------------------------\nclass MyApp(wx.App):\n def OnInit(self):\n frame = MyFrame(None, -1, \"subPrime XML - Statement format conversion\",wx.Size(500,700))\n frame.Show()\n return True\n\n#===============================================================================================\n# Where it all begins...\n#===============================================================================================\ndef main(argv=None):\n if argv is None:\n argv = sys.argv\n\n test = Global.cfgFile.validate(Global.vtor, copy=True)\n Global.cfgFile.write()\n\n app = MyApp(0)\n #wx.lib.inspection.InspectionTool().Show()\n app.MainLoop()\n\nif __name__ == '__main__':\n main()","sub_path":"subPrimeXML/sPxml.pyw","file_name":"sPxml.pyw","file_ext":"pyw","file_size_in_byte":21352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"269196865","text":"\"\"\"Porcupine is a simple editor.\n\nYou are probably reading this because you want to learn how Porcupine\nworks or write fun plugins for it. I recommend getting started with the\nplugin API documentation:\n\n https://akuli.github.io/porcupine/\n\"\"\"\n\nimport pathlib\nimport platform\nimport shutil\nimport subprocess\n\nimport appdirs # type: ignore[import]\n\nversion_info = (0, 84, 2) # this is updated with scripts/release.py\n__version__ = '%d.%d.%d' % version_info\n__author__ = 'Akuli'\n__copyright__ = 'Copyright (c) 2017-2021 Akuli'\n__license__ = 'MIT'\n\n# attach git stuff to the version if this isn't installed\n_here = pathlib.Path(__file__).absolute().parent\nif (_here.parent / '.git').is_dir() and shutil.which('git') is not None:\n # running porcupine from git repo\n try:\n __version__ += '+git.' + subprocess.check_output(\n ['git', 'log', '--pretty=format:%h', '-n', '1'], cwd=_here\n ).decode('ascii')\n except (OSError, subprocess.CalledProcessError, UnicodeError): # pragma: no cover\n pass\n\nif platform.system() in {'Windows', 'Darwin'}:\n # these platforms like path names like \"Program Files\" or \"Application Support\"\n dirs = appdirs.AppDirs('Porcupine', 'Akuli')\nelse:\n dirs = appdirs.AppDirs('porcupine', 'akuli')\n\n# Must be after creating dirs. Must be conditional to silence pyflakes.\nif True:\n from porcupine import _state\n\nget_main_window = _state.get_main_window\nget_parsed_args = _state.get_parsed_args\nget_tab_manager = _state.get_tab_manager\nfiledialog_kwargs = _state.filedialog_kwargs\nquit = _state.quit\n","sub_path":"porcupine/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1578,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"344847539","text":"from html import escape\nimport itertools\nimport re\n\nimport cachetools\nimport jinja2.utils\nfrom flask import url_for\nfrom jinja2 import Markup\n\nimport util\n\nCTRL_COLOR = '\\x03' # ^C = color\nCTRL_RESET = '\\x0F' # ^O = reset\nCTRL_UNDERLINE = '\\x1F' # ^_ = underline\nCTRL_BOLD = '\\x02' # ^B = bold\n\nCTRL_REGEX = re.compile(r'(?:[%s%s%s])|(%s(?:\\d{1,2})?,?(?:\\d{1,2})?)' % (\n CTRL_RESET,\n CTRL_UNDERLINE,\n CTRL_BOLD,\n CTRL_COLOR\n))\n\n# Support urlization of urls with control codes immediately following\njinja2.utils._punctuation_re = re.compile(\n '^(?P(?:%s)*)(?P.*?)(?P(?:%s)*)$' % (\n '|'.join(map(re.escape, ('(', '<', '<'))),\n '|'.join(map(re.escape, ('.', ',', ')', '>', '\\n', '>', CTRL_COLOR, CTRL_RESET, CTRL_BOLD, CTRL_COLOR)))\n )\n)\n\n\ndef ctrl_to_colors(text):\n def try_color(char):\n try:\n return int(char)\n except ValueError:\n return None\n\n # the first character is CTRL_COLOR\n colors = text[1:].split(',')\n\n # People who spam the color changer without any color code\n # ruin it for the rest of us.\n\n if len(text) == 1:\n fg_color_id = None\n bg_color_id = None\n elif len(colors) == 1:\n fg_color_id = try_color(colors[0])\n bg_color_id = None\n else:\n fg_color_id = try_color(colors[0])\n bg_color_id = try_color(colors[1])\n return (fg_color_id, bg_color_id)\n\n\nclass LineState:\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.fg_color = None\n self.bg_color = None\n self.bold = False\n self.underline = False\n\n def toggle_bold(self):\n self.bold = not self.bold\n\n def toggle_underline(self):\n self.underline = not self.underline\n\n def set_color(self, fg_color_id=None, bg_color_id=None):\n self.fg_color = fg_color_id\n if bg_color_id is not None:\n self.bg_color = bg_color_id\n\n\ndef generate_span(state):\n classes = []\n if state.bold:\n classes.append('irc-bold')\n if state.underline:\n classes.append('irc-underline')\n\n # we don't display colors higher than 15\n if state.fg_color is not None and state.fg_color < 16:\n classes.append(\"irc-fg-%s\" % state.fg_color)\n if state.bg_color is not None and state.fg_color < 16:\n classes.append(\"irc-bg-%s\" % state.bg_color)\n return \"\" % ' '.join(classes)\n\n\n@util.delay_template_filter('hostmask_tooltip')\n@cachetools.lru_cache(maxsize=16384)\ndef hostmask_tooltip(s):\n \"\"\"Remove join/part tooltips before urlize can get to them.\n \"\"\"\n timestamp, maybe_user, rest = s.split(' ', 2)\n\n # I am a bad person.\n def replace_interleave(m):\n spaces = itertools.repeat('​')\n user, email = m.groups()\n return '{user}'.format(\n user=user,\n email=''.join(itertools.chain.from_iterable(zip(email, spaces))),\n )\n\n if any(_lenient_prefix(rest, prefix) for prefix in ('Quits', 'Parts', 'Joins')):\n rest = re.sub(\n r'([^ ]+) \\(([^)]+?)\\)',\n replace_interleave,\n rest,\n )\n\n return Markup(' ').join((timestamp, maybe_user, Markup(rest)))\n\n\n# Don't ask me why the filter name is different from the function name.\n@util.delay_template_filter('control_codes')\n@cachetools.lru_cache(maxsize=16384)\ndef irc_format(text, autoescape=None):\n result = ''\n\n # split text into fragments that are either plain text\n # or a control code sequence\n text = CTRL_REGEX.sub(\"\\n\\g<0>\\n\", text)\n fragments = text.split(\"\\n\")\n\n line_state = LineState()\n is_inside_span = False\n for fragment in fragments:\n if not fragment:\n # for blank fragments\n continue\n\n first_char = fragment[0]\n\n was_control_code = True\n if first_char == CTRL_COLOR:\n (fg_color_id, bg_color_id) = ctrl_to_colors(fragment)\n\n if fg_color_id or bg_color_id:\n line_state.set_color(fg_color_id, bg_color_id)\n else:\n line_state.reset()\n elif first_char == CTRL_RESET:\n line_state.reset()\n elif first_char == CTRL_UNDERLINE:\n line_state.toggle_underline()\n elif first_char == CTRL_BOLD:\n line_state.toggle_bold()\n else:\n was_control_code = False\n\n if was_control_code:\n to_concat = ''\n if is_inside_span:\n to_concat = \"\"\n\n span = generate_span(line_state)\n to_concat = \"%s%s\" % (to_concat, span)\n is_inside_span = True\n else:\n to_concat = fragment\n\n result = \"%s%s\" % (result, to_concat)\n if is_inside_span:\n result = \"%s\" % result\n\n return result\n\n\n@cachetools.lru_cache(maxsize=16384)\ndef _lenient_prefix(haystack, needle):\n try:\n return haystack.index(needle) == 0\n except ValueError:\n return False\n\n\n@util.delay_template_filter('line_style')\n@cachetools.lru_cache(maxsize=16384)\ndef line_style(s, line_no, is_search, network=None, ctx=None):\n \"\"\"\n ctx is a grep Line object. Yes, I know it's duplicating s and line_no.\n Deal with it.\n \"\"\"\n\n # At some point this should become yet another regex.\n timestamp, maybe_user, rest = s.split(' ', 2)\n\n classes = []\n msg_user_classes = []\n msg_classes = []\n\n if ctx and ctx.line_marker == ':':\n classes.append(\"irc-highlight\")\n\n if _lenient_prefix(rest, \"Quits\"):\n msg_user_classes.append(\"irc-part\")\n\n if _lenient_prefix(rest, \"Parts\"):\n msg_user_classes.append(\"irc-part\")\n\n if _lenient_prefix(rest, \"Joins\"):\n msg_user_classes.append(\"irc-join\")\n\n # escaping is done before this.\n if _lenient_prefix(rest, \">\"):\n msg_classes.append(\"irc-greentext\")\n\n # Make links back to actual line if we're in search.\n if is_search:\n href = url_for(\n 'log',\n network=network,\n channel=ctx.channel,\n date=ctx.date,\n _anchor='L{}'.format(line_no),\n )\n id_ = ''\n else:\n href = '#L{}'.format(line_no)\n id_ = 'L{}'.format(line_no)\n\n # Do we have to resort to this?\n h, m, s = timestamp.strip(\"[]\").split(\":\")\n\n timestamp = \"[{h}:{m}:{s}]\".format(h=h, m=m, s=s)\n\n return '' \\\n '{timestamp} ' \\\n '{maybe_user} ' \\\n '{rest}' \\\n '' \\\n '' \\\n '' \\\n .format(\n line_class=' '.join(classes),\n timestamp=timestamp,\n href=href,\n msg_user_class=' '.join(msg_user_classes),\n msg_class=' '.join(msg_classes),\n maybe_user=maybe_user,\n id_=id_,\n rest=rest,\n )\n\n","sub_path":"line_format.py","file_name":"line_format.py","file_ext":"py","file_size_in_byte":7057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"236787089","text":"import json\nfrom embed.common import APIResponse\nfrom embed.errors import ValidationError\n\n\nclass Investment(APIResponse):\n \"\"\"\n Handles all queries for Investment\n \"\"\"\n\n def __init__(self, api_session):\n super(Investment, self).__init__()\n self.base_url = f\"{api_session.base_url}/api/{api_session.api_version}/\"\n self.token = api_session.token\n self._headers.update({\"Authorization\": f\"Bearer {self.token}\"})\n\n def get_investments(self, asset_type=None):\n method = \"GET\"\n if asset_type:\n url = self.base_url + f\"investments?asset_type={asset_type}\"\n else:\n url = self.base_url + \"investments\"\n return self.get_essential_details(method, url)\n\n def get_investment(self, investment_id):\n method = \"GET\"\n url = self.base_url + f\"investments/{investment_id}\"\n return self.get_essential_details(method, url)\n\n def create(self, **kwargs):\n required = [\"account_id\", \"asset_code\"]\n for key in required:\n if key not in kwargs.keys():\n raise ValidationError(f\"{key} is required.\")\n\n if \"idempotency_key\" in kwargs.keys():\n self._headers.update(\n {\"Embed-Idempotency-Key\": str(kwargs.pop(\"idempotency_key\"))}\n )\n\n method = \"POST\"\n url = self.base_url + \"investments\"\n payload = json.dumps(kwargs)\n return self.get_essential_details(method, url, payload)\n\n def liquidate(self, **kwargs):\n\n required = [\"investment_id\", \"units\"]\n for key in required:\n if key not in kwargs.keys():\n raise ValidationError(f\"{key} is required.\")\n\n if \"idempotency_key\" in kwargs.keys():\n self._headers.update(\n {\"Embed-Idempotency-Key\": str(kwargs.pop(\"idempotency_key\"))}\n )\n\n method = \"POST\"\n investment_id = kwargs.pop(\"investment_id\")\n url = self.base_url + f\"investments/{investment_id}/liquidate\"\n\n payload = json.dumps(kwargs)\n return self.get_essential_details(method, url, payload)\n","sub_path":"embed/resources/investment.py","file_name":"investment.py","file_ext":"py","file_size_in_byte":2115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"530913801","text":"import copy\nfrom .util import *\nfrom .is_chinese import is_chinese_name\nimport itertools\n\nblack_list = []\nfuncs = [\n match_name_one,\n match_name_two,\n match_name_three,\n match_name_four,\n match_name_five,\n match_name_six,\n match_name_seven,\n]\n\n\ndef dryRun(names):\n if len(names) <= 1:\n return True\n\n len_of_most_complex_names, most_complex_names = len(\n next(iter(names)).split()), set()\n\n for name in names:\n length = len(name.split())\n if length == len_of_most_complex_names:\n most_complex_names.add(name)\n elif length > len_of_most_complex_names:\n len_of_most_complex_names = length\n most_complex_names = set((name, ))\n\n ## 验证 most_complex_names\n for a, b in itertools.combinations(most_complex_names, 2):\n if not may_be_duplicates_partial(a, b, True):\n return False\n\n ## 验证剩余的name\n for name in names:\n if name in most_complex_names:\n continue\n passed = False\n for complex_name in most_complex_names:\n if may_be_duplicates_partial(name, complex_name, True):\n passed = True\n break\n if not passed:\n return False\n return True\n\n\n## 'b u mcneely' 'Betty U. Mcneely'\n\n\ndef match_name(funcs, pnames, anames, name2clean, loose=False):\n filter_pnames = []\n for each in pnames:\n if each not in black_list:\n filter_pnames.append(each)\n\n if len(filter_pnames) == 0: \n return [], []\n \n pt = set()\n for each in filter_pnames:\n # pt.add(name)\n name_l = name2clean[each]\n for dname in anames:\n if dname in black_list or dname in pt:\n continue\n dname_l = name2clean[dname]\n is_match = False\n for f in funcs:\n if f(name_l, dname_l, loose):\n pt.add(dname)\n is_match = True\n break\n pt = [name2clean[a] for a in pt]\n pt = set(pt)\n return pt\n","sub_path":"character/name_match/tool/match_name.py","file_name":"match_name.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"611516525","text":"#!/usr/bin/env python\n\n'''\nProgram Name: grid_stat_wrapper.py\nContact(s): George McCabe\nAbstract:\nHistory Log: Initial version\nUsage: \nParameters: None\nInput Files:\nOutput Files:\nCondition codes: 0 for success, 1 for failure\n'''\n\nfrom __future__ import (print_function, division)\n\nimport logging\nimport os\nimport sys\nimport met_util as util\nimport re\nimport csv\nimport subprocess\nfrom command_builder import CommandBuilder\nfrom pcp_combine_wrapper import PcpCombineWrapper\nfrom gempak_to_cf_wrapper import GempakToCFWrapper\nfrom task_info import TaskInfo\nimport string_template_substitution as sts\n\n\nclass GridStatWrapper(CommandBuilder):\n\n def __init__(self, p, logger):\n super(GridStatWrapper, self).__init__(p, logger)\n met_build_base = p.getdir('MET_BUILD_BASE')\n self.app_path = os.path.join(met_build_base, 'bin/grid_stat')\n self.app_name = os.path.basename(self.app_path)\n\n def set_output_dir(self, outdir):\n self.outdir = \"-outdir \"+outdir\n\n def get_command(self):\n if self.app_path is None:\n self.logger.error(self.app_name + \": No app path specified. \\\n You must use a subclass\")\n return None\n\n cmd = self.app_path + \" \"\n for a in self.args:\n cmd += a + \" \"\n\n if len(self.infiles) == 0:\n self.logger.error(self.app_name+\": No input filenames specified\")\n return None\n\n for f in self.infiles:\n cmd += f + \" \"\n\n if self.param != \"\":\n cmd += self.param + \" \"\n\n if self.outdir == \"\":\n self.logger.error(self.app_name+\": No output directory specified\")\n return None\n\n cmd += self.outdir\n return cmd\n\n def find_model(self, model_type, lead, init_time):\n model_dir = self.p.getstr('config', model_type+'_INPUT_DIR')\n # max_forecast = self.p.getint('config', model_type+'_MAX_FORECAST')\n forecasts = model_type+'_FORECASTS'\n max_forecast = util.getlistint(self.p.getstr('config', forecasts))[-1]\n init_interval = self.p.getint('config', model_type+'_INIT_INTERVAL')\n lead_check = lead\n time_check = init_time\n time_offset = 0\n found = False\n while lead_check <= max_forecast:\n native_template = self.p.getraw('filename_templates',\n model_type+'_NATIVE_TEMPLATE')\n model_ss = sts.StringSub(self.logger, native_template,\n init=time_check,\n lead=str(lead_check).zfill(2))\n model_file = model_ss.doStringSub()\n print(\"model file: \"+model_file)\n model_path = os.path.join(model_dir, model_file)\n if os.path.exists(model_path):\n found = True\n break\n\n time_check = util.shift_time(time_check, -init_interval)\n lead_check = lead_check + init_interval\n\n if found:\n return model_path\n else:\n return ''\n\n def run_at_time(self, init_time):\n task_info = TaskInfo()\n task_info.init_time = init_time\n fcst_vars = util.getlist(self.p.getstr('config', 'FCST_VARS'))\n lead_seq = util.getlistint(self.p.getstr('config', 'LEAD_SEQ')) \n for lead in lead_seq:\n task_info.lead = lead\n for fcst_var in fcst_vars:\n task_info.fcst_var = fcst_var\n # loop over models to compare\n accums = util.getlist(self.p.getstr('config', fcst_var+\"_ACCUM\"))\n ob_types = util.getlist(self.p.getstr('config', fcst_var+\"_OBTYPE\"))\n for accum in accums:\n task_info.level = accum\n for ob_type in ob_types:\n task_info.ob_type = ob_type\n if lead < int(accum):\n continue\n self.run_at_time_once(task_info)\n\n\n# def run_at_time_fcst(self, init_time, lead, accum, ob_type, fcst_var):\n def run_at_time_once(self, ti):\n grid_stat_out_dir = self.p.getstr('config', 'GRID_STAT_OUT_DIR')\n# valid_time = util.shift_time(ti.init_time, ti.lead)\n valid_time = ti.getValidTime()\n init_time = ti.getInitTime()\n accum = ti.level\n model_type = self.p.getstr('config', 'MODEL_TYPE')\n regrid_dir = self.p.getstr('config', ti.ob_type+'_REGRID_DIR')\n regrid_template = self.p.getraw('filename_templates',\n ti.ob_type+'_REGRID_TEMPLATE')\n model_bucket_dir = self.p.getstr('config', model_type+'_BUCKET_DIR')\n obs_var = self.p.getstr('config', ti.ob_type+\"_VAR\")\n config_dir = self.p.getstr('config', 'CONFIG_DIR')\n\n ymd_v = valid_time[0:8]\n if not os.path.exists(os.path.join(grid_stat_out_dir,\n init_time, \"grid_stat\")):\n os.makedirs(os.path.join(grid_stat_out_dir,\n init_time, \"grid_stat\"))\n if not os.path.exists(os.path.join(model_bucket_dir, ymd_v)):\n os.makedirs(os.path.join(model_bucket_dir, ymd_v))\n\n # get model to compare\n model_dir = self.p.getstr('config', model_type+'_INPUT_DIR')\n # check if accum exists in forecast file\n # If not, run pcp_combine to create it\n # TODO: remove reliance on model_type\n if model_type == 'HREF_MEAN' or model_type == \"NATIONAL_BLEND\":\n native_dir = self.p.getstr('config', model_type+'_NATIVE_DIR')\n run_pcp_ob = PcpCombineWrapper(self.p, self.logger)\n# run_pcp_ob.run_at_time(valid_time, int(accum),\n# model_type, fcst_var, True)\n # valid_time = util.shift_time(init_time, lead)\n run_pcp_ob.set_input_dir(model_dir)\n\n run_pcp_ob.set_output_dir(model_bucket_dir)\n# run_pcp_ob.get_accumulation(valid_time, int(accum),\n run_pcp_ob.get_accumulation(valid_time, accum,\n model_type, True)\n\n # call GempakToCF if native file doesn't exist\n infiles = run_pcp_ob.get_input_files()\n for idx, infile in enumerate(infiles):\n # replace input_dir with native_dir, check if file exists\n nfile = infile.replace(model_dir, native_dir)\n if not os.path.exists(os.path.dirname(nfile)):\n os.makedirs(os.path.dirname(nfile))\n data_type = self.p.getstr('config',\n ti.ob_type+'_NATIVE_DATA_TYPE')\n if data_type == \"NETCDF\":\n nfile = os.path.splitext(nfile)[0]+'.nc'\n\n if not os.path.isfile(nfile):\n print(\"Calling GempakToCF to convert model to NetCDF\")\n run_g2c = GempakToCFWrapper(self.p, self.logger)\n run_g2c.add_input_file(infile)\n run_g2c.set_output_path(nfile)\n cmd = run_g2c.get_command()\n if cmd is None:\n print(\"ERROR: GempakToCF could not generate command\")\n return\n print(\"RUNNING: \"+str(cmd))\n run_g2c.build()\n\n run_pcp_ob.infiles[idx] = nfile\n\n bucket_template = self.p.getraw('filename_templates',\n model_type+'_BUCKET_TEMPLATE')\n pcpSts = sts.StringSub(self.logger,\n bucket_template,\n valid=valid_time,\n accum=str(ti.level).zfill(2))\n pcp_out = pcpSts.doStringSub()\n run_pcp_ob.set_output_filename(pcp_out)\n run_pcp_ob.add_arg(\"-name \"+ti.fcst_var+\"_\"+ti.level)\n\n cmd = run_pcp_ob.get_command()\n if cmd is None:\n print(\"ERROR: pcp_combine observation could not \"\\\n \"generate command\")\n return\n print(\"RUNNING: \"+str(cmd))\n self.logger.info(\"\")\n run_pcp_ob.build()\n model_path = run_pcp_ob.get_output_path()\n else:\n model_path = self.find_model(model_type, ti.lead, init_time)\n\n if model_path == \"\":\n print(\"ERROR: COULD NOT FIND FILE IN \"+model_dir)\n return\n self.add_input_file(model_path)\n regridSts = sts.StringSub(self.logger,\n regrid_template,\n valid=valid_time,\n accum=str(accum).zfill(2))\n regrid_file = regridSts.doStringSub()\n\n regrid_path = os.path.join(regrid_dir, regrid_file)\n self.add_input_file(regrid_path)\n if self.p.getbool('config', model_type+'_IS_PROB'):\n self.set_param_file(self.p.getstr('config', 'MET_CONFIG_GSP'))\n else:\n self.set_param_file(self.p.getstr('config', 'MET_CONFIG_GSM'))\n self.set_output_dir(os.path.join(grid_stat_out_dir,\n init_time, \"grid_stat\"))\n\n # set up environment variables for each grid_stat run\n # get fcst and obs thresh parameters\n # verify they are the same size\n fcst_str = model_type+\"_\"+ti.fcst_var+\"_\"+accum+\"_THRESH\"\n fcst_threshs = util.getlistfloat(self.p.getstr('config', fcst_str))\n obs_str = ti.ob_type+\"_\"+ti.fcst_var+\"_\"+accum+\"_THRESH\"\n obs_threshs = util.getlistfloat(self.p.getstr('config', obs_str))\n if len(fcst_threshs) != len(obs_threshs):\n self.logger.error(\"run_example: Number of forecast and \"\\\n \"observation thresholds must be the same\")\n exit\n\n fcst_field = \"\"\n obs_field = \"\"\n\n if self.p.getbool('config', model_type+'_IS_PROB'):\n for fcst_thresh in fcst_threshs:\n fcst_field += \"{ name=\\\"PROB\\\"; level=\\\"A\"+accum + \\\n \"\\\"; prob={ name=\\\"\"+ti.fcst_var + \\\n \"\\\"; thresh_lo=\"+str(fcst_thresh)+\"; } },\"\n for obs_thresh in obs_threshs:\n obs_field += \"{ name=\\\"\"+obs_var+\"_\"+accum + \\\n \"\\\"; level=\\\"(*,*)\\\"; cat_thresh=[ gt\" + \\\n str(obs_thresh)+\" ]; },\"\n else:\n data_type = self.p.getstr('config', ti.ob_type+'_NATIVE_DATA_TYPE')\n if data_type == \"NETCDF\":\n fcst_field += \"{ name=\\\"\"+ti.fcst_var+\"_\"+accum + \\\n \"\\\"; level=\\\"(*,*)\\\"; cat_thresh=[\"\n else:\n fcst_field += \"{ name=\\\"\"+ti.fcst_var + \\\n \"\\\"; level=\\\"[A\"+accum.zfill(2)+\"]\\\"; cat_thresh=[\" \n for fcst_thresh in fcst_threshs:\n fcst_field += \"gt\"+str(fcst_thresh)+\", \"\n fcst_field = fcst_field[0:-2]\n fcst_field += \" ]; },\"\n\n obs_field += \"{ name=\\\"\" + obs_var+\"_\" + accum + \\\n \"\\\"; level=\\\"(*,*)\\\"; cat_thresh=[ \"\n for obs_thresh in obs_threshs:\n obs_field += \"gt\"+str(obs_thresh)+\", \"\n obs_field = obs_field[0:-2]\n obs_field += \" ]; },\"\n # remove last comma\n fcst_field = fcst_field[0:-1]\n obs_field = obs_field[0:-1]\n\n self.add_env_var(\"MODEL\", model_type)\n self.add_env_var(\"FCST_VAR\", ti.fcst_var)\n self.add_env_var(\"OBS_VAR\", obs_var)\n self.add_env_var(\"ACCUM\", accum)\n self.add_env_var(\"OBTYPE\", ti.ob_type)\n self.add_env_var(\"CONFIG_DIR\", config_dir)\n self.add_env_var(\"FCST_FIELD\", fcst_field)\n self.add_env_var(\"OBS_FIELD\", obs_field)\n cmd = self.get_command()\n\n self.logger.debug(\"\")\n self.logger.debug(\"ENVIRONMENT FOR NEXT COMMAND: \")\n self.print_env_item(\"MODEL\")\n self.print_env_item(\"FCST_VAR\")\n self.print_env_item(\"OBS_VAR\")\n self.print_env_item(\"ACCUM\")\n self.print_env_item(\"OBTYPE\")\n self.print_env_item(\"CONFIG_DIR\")\n self.print_env_item(\"FCST_FIELD\")\n self.print_env_item(\"OBS_FIELD\")\n self.logger.debug(\"\")\n self.logger.debug(\"COPYABLE ENVIRONMENT FOR NEXT COMMAND: \")\n self.print_env_copy([\"MODEL\", \"FCST_VAR\", \"OBS_VAR\",\n \"ACCUM\", \"OBTYPE\", \"CONFIG_DIR\",\n \"FCST_FIELD\", \"OBS_FIELD\"])\n self.logger.debug(\"\")\n cmd = self.get_command()\n if cmd is None:\n print(\"ERROR: grid_stat (observation) could not generate command\")\n return\n print(\"RUNNING: \"+str(cmd))\n self.logger.info(\"\")\n self.build()\n self.clear()\n","sub_path":"ush/grid_stat_wrapper.py","file_name":"grid_stat_wrapper.py","file_ext":"py","file_size_in_byte":12949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"521123557","text":"\ndef first(input, noun, verb):\n input[1] = noun\n input[2] = verb\n for i in range(0, len(input) - 1, 4):\n op = input[i]\n x = input[input[i + 1]]\n y = input[input[i + 2]]\n z = input[i + 3]\n \n if (op == 1):\n input[z] = x + y\n elif (op == 2):\n input[z] = x * y\n else:\n break\n\n return input[0]\n\ndef second(input, goal):\n for noun in range (100):\n for verb in range(100):\n val = first(input.copy(), noun, verb)\n if (val == goal):\n return (100 * noun) + verb\n return None\n\ndef main():\n\n with open('input.txt') as file:\n input = [int(n) for n in file.read().split(',')]\n\n firstSolution = first(input.copy(), 12, 2)\n secondSolution = second(input.copy(), 19690720)\n outMsg = f\"Solutions:\\nPart 1: {firstSolution}\\nPart 2: {secondSolution}\"\n \n print(outMsg)\n\n\n################################\n\nif (__name__ == \"__main__\"): main() \n","sub_path":"02/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"207923445","text":"#!/usr/bin/env python\n\ndef main():\n name = 'zhangsan'\n age = 23 if name else 0\n print (age)\n \n test = [x * x for x in xrange(3)]\n print (test)\n\n test_list = [x * x for x in xrange(4) if x % 2 == 0]\n print (test_list)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"statement/statement_usage.py","file_name":"statement_usage.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"36410387","text":"#DUR품목정보서비스\r\n#runtime중 메모리수정\r\nimport gevent.monkey\r\ngevent.monkey.patch_all()\r\nimport requests\r\nfrom lxml import etree\r\nimport gevent.pool\r\nimport gevent.queue\r\nfrom bs4 import BeautifulSoup as BS\r\nimport sys\r\nsys.path.insert(0, '../')\r\nimport async_data_crawler as main\r\nimport column\r\n\r\ndef getLink():\r\n baseUrl = 'http://apis.data.go.kr/1470000/DURPrdlstInfoService/'\r\n #오퍼레이션명\r\n urlList = 'getUsjntTabooInfoList', #'getDurPrdlstInfoList', 'getEfcyDplctInfoList', 'getSeobangjeongPartitnAtentInfoList', 'getOdsnAtentInfoList', 'getMdctnPdAtentInfoList', 'getCpctyAtentInfoList', 'getPwnmTabooInfoList', 'getSpcifyAgrdeTabooInfoList', 'getUsjntTabooInfoList'\r\n # 'getPwnmTabooInfoList','getSpcifyAgrdeTabooInfoList',\r\n\r\n for addUrl in urlList:\r\n # if addUrl == 'finish':\r\n # flist = []\r\n # flist.append('finish')\r\n # main.queue.put(flist)\r\n # break\r\n # key는 config.py 있는 변수, async_data_crwaler에서 가져옴, key와 numofrows는 필수\r\n params = {'servicekey': main.key, 'numOfRows': 100}\r\n print(addUrl)\r\n\r\n if addUrl != 'getDurPrdlstInfoList':\r\n params.update({'typeName': column.typeName[addUrl]})\r\n\r\n # Dictionary data -> url get string으로 바꿔줌\r\n params_str = \"&\".join(\"%s=%s\" % (k, v) for k, v in params.items())\r\n requestUrl = baseUrl + addUrl\r\n try:\r\n # request data\r\n getdata = requests.get(requestUrl, params=params_str)\r\n except:\r\n print('request error')\r\n try:\r\n # response data xml 로 파싱\r\n soup = BS(getdata.text, 'lxml-xml')\r\n\r\n # print(soup.prettify)\r\n # check page\r\n try:\r\n # totalcount 파악\r\n totalcount = int(soup.find('totalCount').text)\r\n except:\r\n print('검색결과없음')\r\n totalcount = 0\r\n print('총 개수: ', totalcount)\r\n if totalcount != 0:\r\n page = int(totalcount / 100) + 1\r\n flist = []\r\n flist.append(addUrl)\r\n\r\n furl = []\r\n print('queue link ', page)\r\n for i in range(page):\r\n params_str2 = params_str\r\n # request 파라미터에 pageno 추가\r\n params_str2 += '&pageNo=' + str(i + 1)\r\n\r\n furl.append(requestUrl + '?' + params_str2)\r\n flist.append(furl)\r\n # ('flist를 뽑아보겠어요~~~~~~~~~~~', flist)\r\n # queue 에 저장\r\n main.queue.put(flist)\r\n except:\r\n print('crwaling error : ', sys.exc_info()[1])\r\n\r\n\r\n# queue init\r\nif __name__ == \"__main__\":\r\n main.pool.spawn(getLink).join()\r\n\r\n main.init()\r\n","sub_path":"apis/DURPrdlstInfoService.py","file_name":"DURPrdlstInfoService.py","file_ext":"py","file_size_in_byte":2885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"329058643","text":"S = input()\nX, Y = [int(x) for x in input().split()]\n\ndef main():\n move_x = []\n move_y = []\n moves = S.split('T')\n for i, move in enumerate(moves):\n walk_len = len(move)\n if walk_len == 0:\n continue\n if i % 2 == 0:\n move_x.append(walk_len)\n else:\n move_y.append(walk_len)\n # the process above will get moving lists that\n # will be the direction non-considerable.\n # print(move_x)\n # print(move_y)\n\nif __name__ == '__main__':\n main()","sub_path":"beginner_82/ft_robot.py","file_name":"ft_robot.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"24543769","text":"import flask\r\nfrom flask import Response\r\nimport numpy as np\r\nimport os, pickle\r\nfrom sklearn.externals import joblib\r\nimport pandas as pd\r\nimport time\r\nimport sqlalchemy\r\nfrom uuid import uuid1\r\nfrom datetime import datetime\r\nimport sys\r\nimport logging\r\nfrom logging import FileHandler\r\nfrom logging import Formatter\r\n\r\nDB_TALK = True\r\nDEBUG_FLAG = False\r\n\r\n\r\nif '--nodb' in sys.argv:\r\n\t\tDB_TALK = False\r\n\r\nif '--debug' in sys.argv:\r\n\t\tDEBUG_FLAG = True\r\n\r\n\r\napp = flask.Flask(__name__)\r\n\r\n# Configure Logger Handler for logging errors\r\nfile_handler = FileHandler('XCLE/log/error_log.txt',mode = 'w+', encoding = 'utf8')\r\nfile_handler.setFormatter(Formatter(\r\n'%(asctime)s %(levelname)s: %(message)s '\r\n'[in %(pathname)s:%(lineno)d]'\r\n))\r\nfile_handler.setLevel(logging.ERROR)\r\napp.logger.addHandler(file_handler)\r\n\r\n\r\n\r\n\r\nmodel_dir = 'XCLE/static/Models/'\r\nrisk_f = pickle.load(open(model_dir + 'risk_function.pkl', 'rb'))\r\n\r\nall_files = os.listdir(model_dir)\r\nxr_files = [file for file in all_files if file[:2] =='xr'] \r\nload_files = [file for file in xr_files if file[-3:] =='pkl']\r\n\r\nnames = np.array([file[2:-4] for file in load_files if \"_feats\" not in file])\r\n\r\n\r\n\r\nmodel_names = np.array(\r\n\t\t[name for name in names if 'baseline' not in name])\r\nmodel_files = np.array(\r\n\t\t['xr' + model_name +'.pkl' for model_name in model_names])\r\nfeature_files = np.array(\r\n\t\t[file for file in all_files if file[-9:] =='feats.pkl'])\r\n\r\nbaseline_model_names = np.array(\r\n\t\t[name for name in names if 'baseline' in name])\r\nbaseline_model_files = np.array(\r\n\t\t['xr'+b_name+'.pkl' for b_name in baseline_model_names])\r\nbaseline_model_names = np.array(\r\n\t\t[name.replace('_baseline','') for name in baseline_model_names])\r\n\r\nmodel_scores = pickle.load(open(model_dir + 'model_acc_scores.pkl', 'rb'))\r\nadj_model_scores = {key:(value-0.5)/.5 for key,value in model_scores.items()}\r\n\r\nPREDICTORS = {}\r\nfor name, model,features in zip(model_names, model_files, feature_files):\r\n\tPREDICTORS[name] = {'features': joblib.load(model_dir + features),\r\n\t\t'model': joblib.load(model_dir + model)}\r\n\r\nBASE_PREDICTORS = {}\r\nfor base_name, base_file in zip(baseline_model_names, baseline_model_files):\r\n\tBASE_PREDICTORS[base_name] = {'model': pickle.load(\r\n\t\topen(model_dir + base_file, 'rb'))}\r\n\r\nif DB_TALK:\r\n\t\tDB_ENGINE = sqlalchemy.create_engine(\"mssql+pyodbc://CTCERTXCLEPROD32\")\r\n\r\nALLOWED_EXTENSIONS = ['xls','xlsx']\r\n\r\n# Read the top pubs used as features for Bug Classification\r\npubs = sorted(pickle.load(open(model_dir + 'pub_features.pkl','rb')))\r\n\r\nfuzzy_months = [\r\n\t['fuzzy_Dec', 'fuzzy_Jan', 'fuzzy_Feb'], \r\n\t['fuzzy_Jan', 'fuzzy_Feb', 'fuzzy_Mar'],\r\n\t['fuzzy_Feb', 'fuzzy_Mar', 'fuzzy_Apr'],\r\n\t['fuzzy_Mar', 'fuzzy_Apr', 'fuzzy_May'],\r\n\t['fuzzy_Apr', 'fuzzy_May','fuzzy_Jun'],\r\n\t[ 'fuzzy_May','fuzzy_Jun','fuzzy_Jul'],\r\n\t['fuzzy_Jun','fuzzy_Jul','fuzzy_Aug'],\r\n\t['fuzzy_Jul','fuzzy_Aug', 'fuzzy_Sep'],\r\n\t['fuzzy_Aug', 'fuzzy_Sep', 'fuzzy_Oct'],\r\n\t['fuzzy_Sep', 'fuzzy_Oct','fuzzy_Nov'],\r\n\t['fuzzy_Oct','fuzzy_Nov', 'fuzzy_Dec'], \r\n\t['fuzzy_Nov', 'fuzzy_Dec', 'fuzzy_Jan']]\r\n\t\t\t\t\r\nif DB_TALK:\r\n\tdb_submit_types = {\r\n\t\t\"Raw_Test_Order\": sqlalchemy.dialects.mssql.base.INTEGER,\r\n\t\t\"Test_Case\": sqlalchemy.dialects.mssql.base.VARCHAR,\r\n\t\t\"Fail_Probability\": sqlalchemy.dialects.mssql.base.DECIMAL, \r\n\t\t\"Accuracy\": sqlalchemy.dialects.mssql.base.DECIMAL,\r\n\t\t\"Order_Metric\": sqlalchemy.dialects.mssql.base.DECIMAL,\r\n\t\t\"Actual\": sqlalchemy.dialects.mssql.base.BIT,\r\n\t\t\"Kickoff_Date\": sqlalchemy.dialects.mssql.base.DATETIME,\r\n\t\t\"XCID\": sqlalchemy.dialects.mssql.base.VARCHAR,\r\n\t\t\"Prediction_Batch_Id\": \r\n\t\t\t\tsqlalchemy.dialects.mssql.base.UNIQUEIDENTIFIER,\r\n\t\t\"Created_By\": sqlalchemy.dialects.mssql.base.NVARCHAR,\r\n\t\t\"Created_Date\": sqlalchemy.dialects.mssql.base.DATE,\r\n\t\t\"Test_Recommended\": sqlalchemy.dialects.mssql.base.BIT}\r\n\r\n\tlog_submit_types = {\r\n\t\t\"SubmissionType\": sqlalchemy.dialects.mssql.base.VARCHAR,\r\n\t\t\"Publisher\": sqlalchemy.dialects.mssql.base.NVARCHAR, \r\n\t\t\"XCID\": sqlalchemy.dialects.mssql.base.VARCHAR,\r\n\t\t\"MultiplayerGame\": sqlalchemy.dialects.mssql.base.BIT,\r\n\t\t\"BlockbusterGame\": sqlalchemy.dialects.mssql.base.BIT,\r\n\t\t\"Month\": sqlalchemy.dialects.mssql.base.INTEGER,\r\n\t\t\"KickOffDate\": \r\n\t\t\t\tsqlalchemy.dialects.mssql.base.DATE,\r\n\t\t\"IndependentGame\": sqlalchemy.dialects.mssql.base.BIT,\r\n\t\t\"Prediction_Batch_Id\": \r\n\t\t\t\tsqlalchemy.dialects.mssql.base.UNIQUEIDENTIFIER,\r\n\t\t\"TPG_Processed\": sqlalchemy.dialects.mssql.base.BIT}\r\n\r\ndb_col_name_replace = {\r\n\t\"Raw Test Order\":\"Raw_Test_Order\", \r\n\t\"Test Case\":\"Test_Case\", \r\n\t\"Fail Probability\": \"Fail_Probability\", \r\n\t\"Order Metric\":\"Order_Metric\",\r\n\t\"Test Recommended\": \"Test_Recommended\", \r\n\t\"Date\":\"Kickoff_Date\"}\r\n\r\nlog_db_col_name_replace = {\r\n\t\"top_pubs\":\"Publisher\", \r\n\t\"Mltplyr\": \"MultiplayerGame\",\r\n\t\"Blckbster\":\"BlockbusterGame\",\r\n\t\"Ind\": \"IndependentGame\", \r\n\t\"sub_type\":\"SubmissionType\",\r\n\t\"kickoff_month\": \"Month\",\r\n\t\"user_id\": \"Created_By\"\r\n\t}\r\n\r\n# Set first unique batch id\r\nbatch_id = str(uuid1())\r\n\r\n# Get current date \r\ndate_str = time.strftime(\"%m-%d-%Y\")\r\noutput_filename = 'XCLE/dynamic_results/Results_' + date_str\r\n\r\n@app.route(\"/\")\r\ndef viz_page():\r\n\t\t\"\"\" Homepage: serve our form page, form.html\r\n\t\t\"\"\"\r\n\t\twith open(\"XCLE/templates/form.html\", 'r') as viz_file:\r\n\t\t\t\treturn viz_file.read()\r\n\r\ndef calculate_risk(order_metric):\r\n\t\tif np.isnan(order_metric):\r\n\t\t\treturn(np.nan)\r\n\t\telse:\r\n\t\t\trisk = risk_f([order_metric])[0]\r\n\t\t\tif risk > 100:\r\n\t\t\t\treturn(100.0000)\r\n\t\t\telse:\r\n\t\t\t\treturn(risk)\r\n\r\ndef feature_map(form_features, model_feats):\r\n\r\n\t\t# map input feature month to fuzzy months \r\n\t\tnum_subs = len(form_features['sub_type'])\r\n\t\ttest = pd.DataFrame(0, columns = model_feats, index =range(num_subs))\r\n\t\tfor idx, month in enumerate(form_features['kickoff_month']):\r\n\t\t\tfms = fuzzy_months[int(month)]\r\n\t\t\tfor fm in fms:\r\n\t\t\t\tif fm in test.columns:\r\n\t\t\t\t\t\ttest.loc[idx, fm] = 1\r\n\t\tfor idx, pub in enumerate(form_features['top_pubs']):\r\n\t\t\tif pub in test.columns:\r\n\t\t\t\t\ttest.loc[idx, pub] = 1 \r\n\t\t\t\t\t\t\r\n\t\tfor idx, (st, sn) in enumerate(zip(form_features['sub_type'],\r\n\t\t\tform_features['Pass_Num'])):\r\n\t\t\tstr1 = 'pass_#'\r\n\t\t\tif int(sn) > 5:\r\n\t\t\t\t\tstr2 = ' >5'\r\n\t\t\telse:\r\n\t\t\t\t\tstr2 = ' =' + sn\r\n\t\t\tstr12 = str1+str2\r\n\t\t\tif str12 in test.columns:\r\n\t\t\t\t\ttest.loc[idx, str12] = 1\r\n\r\n\t\tcommons = list(set(test.columns).intersection(form_features.keys()))\r\n\t\tfor common in commons:\r\n\t\t\ttest[common] = [int(f) for f in form_features[common]]\r\n\t\treturn test .values\r\n\r\n@app.route(\"/info\", methods=[\"POST\"])\r\ndef info():\r\n\t\t\"\"\" When A POST request with text is made, respond with the info requested\r\n\t\t\"\"\"\r\n\t\tinfo_response = {}\r\n\r\n\t\t# Get info for dynamic data entry \r\n\t\tinfo_req = flask.request.json\r\n\t\tif 'pubs' in info_req.keys():\r\n\t\t\tinfo_response.update({'pubs' : pubs})\r\n\t\tif 'date' in info_req.keys():\r\n\t\t\tinfo_response.update({'date' : date_str})\r\n\t\treturn flask.jsonify(info_response)\r\n\r\n# Generate reports in html and excel and save \r\n@app.route(\"/score\", methods=[\"POST\"])\r\ndef score():\r\n\r\n\t\t\"\"\" When A POST request with json data is made to this uri,\r\n\t\t\t\t Read the example from the json, predict probability and\r\n\t\t\t\t send it with a response\r\n\t\t\"\"\"\r\n\t\tglobal batch_id\r\n\t\tglobal log_df\r\n\r\n\t\ttry:\r\n\t\t# Get decision score for the submission request\r\n\t\t\t\r\n\t\t\tform_features = flask.request.json\r\n\r\n\t\t\tform_features = pd.DataFrame(form_features).drop_duplicates().to_dict('list')\r\n\t\t\tuser_ids = form_features['user_id']\r\n\r\n\t\t\t# report_type = form_features.pop('report_type')\r\n\t\t\tXCID_strs = form_features.pop('xcid_1')\r\n\t\t\tdates = [XCID_str.split('-')[1] for XCID_str in XCID_strs]\r\n\r\n\r\n\r\n\t\t\tyears = [int(date[0:4]) for date in dates]\r\n\t\t\tmonths = [int(date[4:6]) for date in dates]\r\n\t\t\tdays = [int(date[6:]) for date in dates]\r\n\t\t\tkickoff_dates = [datetime(year, month, day).date() for year, month, day in zip(years,months,days)]\r\n\t\t\tform_features['kickoff_month'] = months\r\n\r\n\t\t\tprobs = {}\r\n\t\t\tfor name, trained in PREDICTORS.items():\r\n\t\t\t\tmodel_feats = trained['features']\r\n\t\t\t\tclf = trained['model']\r\n\t\t\t\ttest = feature_map(form_features, model_feats)\r\n\t\t\t\tprobs[name] = clf.predict_proba(test)[:,1]\r\n\r\n\r\n\t\t\t# order and format report\r\n\t\t\tadj_probs = {key:(value-0.5)/.5 for key,value in probs.items()} \r\n\r\n\t\t\tbatch_results = {}\r\n\r\n\t\t\tfor xcid_idx, XCID_str in enumerate(XCID_strs):\r\n\r\n\t\t\t\t\toutput_df = pd.DataFrame(index = adj_probs.keys(),\r\n\t\t\t\t\t\t\tcolumns = ['Fail Probability', 'Accuracy', 'Order Metric'])\r\n\r\n\t\t\t\t\tfor xr in output_df.index:\r\n\t\t\t\t\t\tif (xr in probs.keys()) and (xr in model_scores.index):\r\n\t\t\t\t\t\t\tif model_scores.loc[xr,'Sample_Size'] > 2:\r\n\t\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\toutput_df.loc[xr, 'Fail Probability'] = probs[xr][xcid_idx]\r\n\t\t\t\t\t\t\t\toutput_df.loc[xr, 'Accuracy'] = model_scores.loc[xr,'Accuracy']\r\n\t\t\t\t\t\t\t\toutput_df.loc[xr, 'Order Metric'] = (\r\n\t\t\t\t\t\t\t\t\t\tadj_probs[xr][xcid_idx] * output_df.loc[xr, 'Accuracy'])\r\n\t\t\t\t\t\t\telse:\r\n\r\n\t\t\t\t\t\t\t\toutput_df.loc[\r\n\t\t\t\t\t\t\t\t\t\txr, 'Fail Probability'] = np.nan\r\n\t\t\t\t\t\t\t\toutput_df.loc[xr, 'Accuracy'] = np.nan\r\n\t\t\t\t\t\t\t\toutput_df.loc[xr, 'Order Metric'] = np.nan\r\n\r\n\t\t\t\t\tbase_probs = {}\r\n\t\t\t\t\tfor name, trained in BASE_PREDICTORS.items():\r\n\t\t\t\t\t\tbase_probs[name] = trained['model']['y_prob']\r\n\r\n\t\t\t\t\t# order and format report - Baseline\r\n\t\t\t\t\tadj_b_probs = {key:(value-0.5)/.5 for key,value in base_probs.items()} \r\n\t\t\t\t\tbase_output_df = pd.DataFrame(index = adj_b_probs.keys(),\r\n\t\t\t\t\t\tcolumns = ['Fail Probability', 'Accuracy', 'Order Metric'])\r\n\r\n\t\t\t\t\tfor title in base_output_df.index:\r\n\t\t\t\t\t\txr = title.split('_')[0]\r\n\t\t\t\t\t\tif (title in base_probs.keys()) and (xr in model_scores.index):\r\n\t\t\t\t\t\t\tif model_scores.loc[xr,'Sample_Size'] > 2:\r\n\t\t\t\t\t\t\t\t\tbase_output_df.loc[\r\n\t\t\t\t\t\t\t\t\t\t\ttitle, 'Fail Probability'] = base_probs[title]\r\n\t\t\t\t\t\t\t\t\tbase_output_df.loc[title, 'Accuracy'] = (\r\n\t\t\t\t\t\t\t\t\t\t\tmodel_scores.loc[xr,'Accuracy'])\r\n\t\t\t\t\t\t\t\t\tbase_output_df.loc[title, 'Order Metric'] = (\r\n\t\t\t\t\t\t\t\t\t\t\t\t\tadj_b_probs[title] *\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t base_output_df.loc[title, 'Accuracy'])\r\n\t\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\t\tbase_output_df.loc[\r\n\t\t\t\t\t\t\t\t\t\ttitle, 'Fail Probability'] = np.nan\r\n\t\t\t\t\t\t\t\tbase_output_df.loc[title, 'Accuracy'] = np.nan\r\n\t\t\t\t\t\t\t\tbase_output_df.loc[title, 'Order Metric'] = np.nan\r\n\r\n\r\n\t\t\t\t\toutput_df = pd.concat([output_df, base_output_df])\r\n\t\t\t\t\toutput_df['Risk'] = output_df['Order Metric'].apply(calculate_risk)\r\n\r\n\t\t\t\t\toutput_df['Test Recommended'] = output_df['Risk'] > 40\r\n\t\t\t\t\tlow_samp_bidx = output_df['Order Metric'].isnull()\r\n\t\t\t\t\toutput_df.loc[low_samp_bidx,'Test Recommended'] = True\r\n\t\t\t\t\toutput_df.loc[low_samp_bidx, 'Fail Probability'] = np.nan\r\n\t\t\t\t\toutput_df.loc[low_samp_bidx, 'Accuracy'] = np.nan\r\n\t\t\t\t\toutput_df.loc[low_samp_bidx, 'Order Metric'] = np.nan\r\n\t\t\t\t\toutput_df['Low_Sample_Size'] = 0\r\n\t\t\t\t\toutput_df.loc[low_samp_bidx, 'Low_Sample_Size'] = 1\r\n\t\t\t\t\toutput_df['Date'] = kickoff_dates[xcid_idx]\r\n\t\t\t\t\toutput_df['XCID'] = XCID_str\r\n\t\t\t\t\toutput_df['Created_By'] = user_ids[xcid_idx]\r\n\t\t\t\t\toutput_df.sort_values(\r\n\t\t\t\t\t\tby = 'Order Metric', ascending = False, inplace = True,\r\n\t\t\t\t\t\tna_position = 'first')\r\n\t\t\t\t\toutput_df.reset_index(inplace = True)\r\n\t\t\t\t\toutput_df.rename(columns = {'index':'Test Case'}, inplace = True)\r\n\t\t\t\t\toutput_df.set_index(output_df.index + 1, inplace = True)\r\n\t\t\t\t\tfirst_idx = output_df['Fail Probability'].isnull()\r\n\t\t\t\t\tser_index = output_df.index.to_series()-sum(first_idx)\r\n\t\t\t\t\tser_index.loc[first_idx] = 0\r\n\t\t\t\t\toutput_df.set_index(ser_index.values, inplace=True)\r\n\t\t\t\t\toutput_df.index.name = 'Raw Test Order'\r\n\t\t\t\t\toutput_df = output_df.loc[:,['XCID','Test Case', 'Fail Probability', 'Accuracy', 'Order Metric',\r\n\t\t\t\t\t\t'Test Recommended', 'Low_Sample_Size', 'Date', 'Created_By', 'Risk']]\r\n\t\t\t\t\tbatch_results[XCID_str] = output_df.copy()\r\n\r\n\r\n\t\t\tbatch_df = pd.concat(list(batch_results.values()))\r\n\r\n\t\t\t####### For pre-TPG reporting #############\r\n\t\t\t#export to excel\r\n\t\t\t# with pd.ExcelWriter(output_filename + '.xlsx') as writer:\r\n\t\t\t# \tfor xcid_idx, xcid in enumerate(batch_results.keys()):\r\n\t\t\t# \t\tbatch_results[xcid].to_excel(\r\n\t\t\t# \t\t\t\twriter, sheet_name = xcid, float_format = \"%.3f\")\r\n\r\n\t\t\t# #export to html\r\n\t\t\t# with open('XCLE/static/Results.html', 'w') as fp:\r\n\r\n\t\t\t# \t\tbatch_df.to_html(fp, float_format = lambda x: '%.3f' % x)\r\n\t\t\t####### For pre-TPG reporting #############\r\n\r\n\t\t\tpickle.dump(batch_df, open('./XCLE/static/Results.pkl', 'wb'))\r\n\t\t\tlog_df = pd.DataFrame(form_features, index=[XCID_strs])\r\n\t\t\tlog_df.index.name = 'XCID'\r\n\t\t\tlog_df.rename(columns = log_db_col_name_replace, inplace=True)\r\n\r\n\t\t\t# Change global batch id for each prediction set \r\n\t\t\tbatch_id = str(uuid1())\r\n\t\t\tlog_df['Prediction_Batch_Id'] = batch_id\r\n\t\t\tlog_df['KickOffDate'] = kickoff_dates\r\n\r\n\t\t\tpickle.dump(log_df, open('XCLE/static/Parameters.pkl', 'wb'))\r\n\t\t\tresults = {'result': 'success' }\r\n\t\texcept:\r\n\t\t\tresults = {'result': 'failed' }\r\n\r\n\t\treturn flask.jsonify(results)\r\n\r\n@app.route(\"/send_to_db\", methods=[\"POST\"])\r\ndef res_to_db():\r\n\r\n\t\t\"\"\" When A POST request with json data is made to this uri,\r\n\t\t\t\t read the prediction from pickled data, and send to db\r\n\t\t\"\"\"\r\n\t\ttry:\r\n\t\t\tbatch_df = pickle.load(open('XCLE/static/Results.pkl', 'rb'))\r\n\t\t\tlog_df = pickle.load(open('XCLE/static/Parameters.pkl', 'rb'))\r\n\r\n\t\t\tbatch_df[\"Fail Probability\"] = batch_df[\"Fail Probability\"].replace(\r\n\t\t\t\t{'low samples': np.nan}).astype('float')\r\n\t\t\tbatch_df[\"Accuracy\"] = batch_df[\"Accuracy\"].replace(\r\n\t\t\t\t{'low samples': np.nan}).astype('float')\r\n\t\t\tbatch_df[\"Order Metric\"] = batch_df[\"Order Metric\"].replace(\r\n\t\t\t\t{'low samples': np.nan}).astype('float')\r\n\t\t\tbatch_df[\"Test Recommended\"] = batch_df[\"Test Recommended\"].astype(\r\n\t\t\t\t'int')\r\n\r\n\t\t\tbatch_df.rename(columns = db_col_name_replace, inplace=True)\r\n\r\n\t\t\tbatch_df[\"Prediction_Batch_Id\"] = batch_id\r\n\t\t\tbatch_df[\"Actual\"] = np.nan\r\n\t\t\tbatch_df.index.name = \"Raw_Test_Order\" \r\n\r\n\t\t\tif DB_TALK: \r\n\t\t\t\tlog_df.to_sql(\"PredictionParameterLog\", DB_ENGINE, if_exists = 'append',\r\n\t\t\t\t\tdtype = log_submit_types) \r\n\t\t\t\tbatch_df.to_sql(\"PredictionData\", DB_ENGINE,\r\n\t\t\t\t\tif_exists = 'append', dtype = db_submit_types)\r\n\r\n\t\t\tresults = {'result': 'success' }\t\t\t\r\n\r\n\t\texcept:\r\n\t\t\tresults = {'result': 'failed' }\r\n\r\n\t\treturn flask.jsonify(results)\r\n\r\n\r\n@app.route(\"/download_doc\")\r\ndef download_doc():\r\n\texcelDownload = open('XCLE/static/XCLE_documentation.pdf','rb').read()\r\n\treturn Response(\r\n\t\texcelDownload,\r\n\t\tmimetype=\"application/pdf\",\r\n\t\theaders={\"Content-disposition\":\r\n\t\t\t\"attachment; filename=\" + \"XCLE_documentation.pdf\"})\r\n\r\nif __name__ == \"__main__\":\r\n\r\n\t#--------- RUN WEB APP SERVER ------------#\r\n\r\n\t# Start the app server on port 5000 in debug mode\r\n\tif DEBUG_FLAG:\r\n\t\t\t# localhost instance, with debugging options turned on\r\n\t\t\tapp.debug = True\r\n\t\t\tapp.run( )\r\n\telse:\r\n\r\n\t\tapp.debug = False\r\n\t\tapp.run(host=\"0.0.0.0\", port=88)\r\n","sub_path":"XCLE/XCLE_predicts.py","file_name":"XCLE_predicts.py","file_ext":"py","file_size_in_byte":14690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"458946177","text":"from __future__ import unicode_literals\nimport bz2\nimport json\nfrom htrc_features.volume import Volume\nfrom multiprocessing import Pool\nimport time\nimport logging\n\nclass FeatureReader(object):\n def __init__(self, paths):\n if type(paths) is str or type(paths) is unicode:\n # Assume only one path was provided, wrap in list\n paths = [paths]\n \n if type(paths) is list:\n self.paths = paths\n self.index = 0\n else:\n logging.error(\"Bad input type for feature reader: {}\".format(type(paths)))\n\n def __iter__(self):\n return self\n \n def next(self):\n return self.__next__()\n\n def __next__(self):\n ''' Get the next item.\n For iteration, and an easy way to get a volume object with only one\n path i\n \n Note that just calling the volume initializes it.\n '''\n if self.index == len(self.paths):\n raise StopIteration\n path = self.paths[self.index]\n vol = self._volume(path)\n self.index += 1\n return vol \n\n def volumes(self):\n ''' Generator for return Volume objects '''\n for path in self.paths:\n yield self._volume(path)\n\n def _volume(self, path, compressed=True):\n ''' Read a path into a volume.'''\n try:\n if compressed:\n f = bz2.BZ2File(path)\n else:\n f = open(path, 'r+')\n rawjson = f.readline()\n f.close()\n except:\n logging.error(\"Can't open %s\", path)\n return\n \n try:\n # For Python3 compatibility, decode to str object\n if type(rawjson) != str:\n rawjson = rawjson.decode()\n volumejson = json.loads(rawjson)\n except:\n logging.error(\"Problem reading JSON for %s\", path)\n return\n return Volume(volumejson)\n \n def _wrap_func(self, func):\n '''\n Convert a volume path to a volume and run func(vol). For multiprocessing\n TODO: Closures won't work, this is a useless function. Remove this after consideration...\n '''\n def new_func(path):\n vol = self._volume(path)\n func(vol)\n return new_func\n\n def create_volume(self, path, **kwargs):\n return self._volume(path, **kwargs)\n\n def _mp_paths(self):\n '''\n Package self with paths, so subprocesses can access it\n '''\n for path in self.paths:\n yield (self, path)\n\n def multiprocessing(self, map_func, callback=None):\n '''\n Pass a function to perform on each volume of the feature reader, using\n multiprocessing (map), then process the combined outputs (reduce).\n\n map_func\n\n Function to run on each individual volume. Takes as input a tuple\n containing a feature_reader and volume path, from which a volume can be\n created. Returns a (key, value) tuple.\n\n def do_something_on_vol(args):\n fr, path = args\n vol = fr.create_volume(path)\n # Do something with 'vol'\n return (key, value)\n\n '''\n p = Pool() # Match process count to cpu count\n #f = self._wrap_func(func)\n results = p.map(map_func, self._mp_paths(), chunksize=5)#, callback=callback)\n p.close()\n p.join()\n return results\n \n\n def __str__(self):\n return \"HTRC Feature Reader with %d paths load\" % (len(self.paths))\n","sub_path":"htrc_features/feature_reader.py","file_name":"feature_reader.py","file_ext":"py","file_size_in_byte":3531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"397080397","text":"\"\"\"\r\nIt is program whcih checks number is palidrunn self but number should be > 10\r\npalidrum which we write opposit or any time it will be the write\r\n\r\n\"\"\"\r\ndef paliderem(num): # function which checks the number palidr\r\n if num >10:\r\n num=num +1 # add 1 to given input and then go to functio is_palidrum\r\n while not is_paledrm(num):\r\n num=num+1\r\n return num\r\n else:\r\n return number_li[i]\r\n\r\ndef is_paledrm(num): # here it checks the number if it is return the value if not the go to statment of whille not\r\n\r\n return str(num) == str(num)[::-1]\r\n\r\nif __name__ == '__main__':\r\n\r\n num=int(input(\"Enter THe numbers\"))\r\n number_li=[] # to store the value\r\n\r\n for i in range(num):\r\n a=int(input(f\"Enter the {i} number:\"))\r\n number_li.append(a)\r\n print(number_li)\r\n for i in range(num):\r\n print(f\" the number {number_li[i]} has next paledrum {paliderem(number_li[i])} \")\r\n\r\n","sub_path":"Practice Problem 5 NExt palidrom same practice4.py","file_name":"Practice Problem 5 NExt palidrom same practice4.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"281025825","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"读取数据模块\n从文件中读取数据,返回临接表\n\"\"\"\nimport os\n\n#----------------------------------------------------------------------\ndef read(filepath):\n # 判断filepath是否合法\n if os.path.isfile(filepath):\n if os.path.splitext(filepath)[1].lower() in (\".xls\", \".xlsx\"):\n return __readFromXLS(filepath)\n elif os.path.splitext(filepath)[1].lower() in (\".dot\"):\n return __readFromDOT(filepath)\n else:\n raise Exception(\"the file format is not supported, only supported(xls, xlsx, dot)\")\n else:\n raise Exception(\"the file is not right\")\n\ndef __readFromXLS(filepath):\n \"\"\"\n 从MS excel 2003-2007(.xls or .xlsx)文件中读取数据,返回临接表\n filepath: 文件路径\n \"\"\"\n try:\n import xlrd\n except ImportError:\n raise ImportError(\"readFromXLS requires xlrd\")\n filepath = filepath.strip()\n book = xlrd.open_workbook(filepath)\n sheet = book.sheets()[0]\n # first sheet in workbook\n dataList = []\n for i in range(sheet.nrows):\n col = []\n col.append(int(sheet.cell_value(i, 0)))\n # when j is zero,the value is each element's in-degree in the graph\n for j in range(1, sheet.ncols):\n cellvalue = sheet.cell_value(i, j)\n if cellvalue != '':\n # 过滤掉那些为空的cellvalue.\n col.append(int(cellvalue))\n dataList.append(col)\n return dataList\n\n#----------------------------------------------------------------------\ndef __readFromDOT(filepath):\n \"\"\"从dot文件中读取数据,返回临接表\n filepath: 文件路径\n \"\"\"\n try:\n import networkx as nx\n except ImportError:\n raise ImportError('readFromDOT() requires networkx ')\n filepath = filepath.strip()\n dataList = []\n ds = nx.read_dot(filepath)\n # 构造十字链表\n for i in xrange(ds.number_of_nodes()):\n dataList.append([])\n # 给每个节点赋入度值\n for degree in ds.in_degree_iter():\n dataList[int(degree[0])].append(int(degree[1]))\n # 给每个节点赋后继节点\n for edge in ds.edges_iter():\n dataList[int(edge[0])].append(int(edge[1])) \n \n return dataList","sub_path":"src/lly/readData.py","file_name":"readData.py","file_ext":"py","file_size_in_byte":2298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"504182849","text":"#!/ad/eng/bin/64/python-anaconda\nfrom mpi4py import MPI\nimport numpy\nfrom socket import gethostname\nfrom time import sleep\n\ncomm = MPI.COMM_WORLD\nrank = comm.Get_rank()\nsize = comm.Get_size()\nsleep(rank) # just for tidy output in this example\n\nN = 100000000 # per-worker array size\nif rank == 0:\n print('master: ' + gethostname())\n print('size: ' + str(size))\n data = numpy.arange((size-1)*N, dtype=numpy.int)\n print('data size in MB: ' + str(data.nbytes/(2.0**20)))\n for n in range(size-1):\n comm.Send(data[n*N:(n+1)*N], dest=n+1, tag=13)\nelse:\n data = numpy.empty(N, dtype=numpy.int)\n comm.Recv(data, source=0, tag=13)\n print('worker: ' + gethostname())\n print('rank: ' + str(rank))\n print('data:')\n print(data)\n","sub_path":"mpi-mpi4py/mpi4py_test.py","file_name":"mpi4py_test.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"567026729","text":"import re\n\n\ndef extract_plain_text(json_data):\n \"\"\"\n Take data that looks like the following:\n\n{'data': {'blocks': [{'block_id': 'a2J3',\n 'elements': [{'elements': [{'type': 'user',\n 'user_id': 'UTHKYT7FB'},\n {'text': ' Which build of sdn '\n 'is in ',\n 'type': 'text'},\n {'text': 'registry.svc.ci.openshift.org/ocp-s390x/release-s390x:4.4.0-0.nightly-s390\nx-2020-02-21-235937',\n 'type': 'link',\n 'url': 'http://registry.svc.ci.openshift.org/ocp-s390x/release-s390x:4.4.0-0.nightl\ny-s390x-2020-02-21-235937'}],\n 'type': 'rich_text_section'}],\n 'type': 'rich_text'}],\n ...\n\n and extract just the text parts to come up with:\n \"Which build of sdn is in registry.svc.ci.openshift.org/ocp-s390x/release-s390x:4.4.0-0.nightly-s390x-2020-02-21-235937\"\n \"\"\"\n\n text = \"\"\n for block in json_data[\"data\"][\"blocks\"]:\n for section in [el for el in block[\"elements\"] if el[\"type\"] == \"rich_text_section\"]:\n for element in [el for el in section[\"elements\"] if \"text\" in el]:\n text += element[\"text\"]\n\n # reformat to homogenize miscellaneous confusing bits\n return re.sub(r\"\\s+\", \" \", text).lstrip().rstrip(\" ?\").lower()\n","sub_path":"artbotlib/formatting.py","file_name":"formatting.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"600256637","text":"import unittest\nimport flask_testing\nimport datetime\n\n# pylint: disable=C0301\nfrom collectives import create_app\nfrom collectives.models import db, User, ActivityType, Role, RoleIds, Event\nfrom collectives.models import Registration, RegistrationLevels, RegistrationStatus\n# pylint: enable=C0301\n\n\ndef create_test_user(email=\"test\", user_license=\"\"):\n user = User(mail=email, first_name=\"Test\", last_name=\"Test\", password=\"\",\n license=user_license, enabled=True, phone=\"\")\n db.session.add(user)\n db.session.commit()\n return user\n\n\ndef create_test_activity(name=\"Ski\"):\n activity = ActivityType(name=name, short=\"\")\n db.session.add(activity)\n db.session.commit()\n return activity\n\n\nclass ModelTest(flask_testing.TestCase):\n\n def create_app(self):\n\n # pass in test configuration\n app = create_app()\n app.config['SQLALCHEMY_DATABASE_URI'] = \"sqlite:////tmp/testdb.sqlite\"\n app.config['TESTING'] = True\n return app\n\n def setUp(self):\n\n db.create_all()\n\n def tearDown(self):\n\n db.session.remove()\n db.drop_all()\n\n\nclass TestUsers(ModelTest):\n\n def test_create_user(self):\n user = create_test_user()\n assert user in db.session\n\n\nclass TestActivities(ModelTest):\n\n def test_create_activity(self):\n activity = create_test_activity()\n assert activity in db.session\n\n\nclass TestRoles(ModelTest):\n\n def make_role(self, user):\n return Role(user=user, role_id=int(RoleIds.Administrator))\n\n def make_activity_role(self, user, activity):\n return Role(user=user,\n activity_id=activity.id,\n role_id=int(RoleIds.EventLeader))\n\n def commit_role(self, role):\n db.session.add(role)\n db.session.commit()\n\n def test_add_role(self):\n user = create_test_user()\n\n role = self.make_role(user)\n user.roles.append(role)\n\n db.session.commit()\n\n assert role in db.session\n\n retrieved_user = User.query.filter_by(id=user.id).first()\n assert len(retrieved_user.roles) == 1\n assert retrieved_user.is_admin()\n assert retrieved_user.is_moderator()\n assert not retrieved_user.can_lead_activity(0)\n\n def test_add_activity_role(self):\n user = create_test_user()\n activity1 = create_test_activity(\"1\")\n activity2 = create_test_activity(\"2\")\n\n role = self.make_activity_role(user, activity1)\n user.roles.append(role)\n\n db.session.commit()\n\n assert role in db.session\n\n retrieved_user = User.query.filter_by(id=user.id).first()\n assert len(retrieved_user.roles) == 1\n assert not retrieved_user.is_admin()\n assert not retrieved_user.is_moderator()\n assert retrieved_user.can_lead_activity(activity1.id)\n assert not retrieved_user.can_lead_activity(activity2.id)\n\n\nclass TestEvents(TestUsers):\n\n def make_event(self):\n return Event(title=\"Event\",\n description=\"\",\n shortdescription=\"\",\n num_slots=2, num_online_slots=1,\n start=datetime.datetime.now() + datetime.timedelta(days=1),\n end=datetime.datetime.now() + datetime.timedelta(days=2),\n registration_open_time=datetime.datetime.now(),\n registration_close_time=datetime.datetime.now() +\n datetime.timedelta(days=1))\n\n def test_add_event(self):\n event = self.make_event()\n db.session.add(event)\n db.session.commit()\n return event\n\n def test_event_validity(self):\n user1 = create_test_user(\"email1\", \"license1\")\n user2 = create_test_user(\"email2\", \"license2\")\n activity1 = create_test_activity(\"1\")\n activity2 = create_test_activity(\"2\")\n\n user1.roles.append(Role(role_id=RoleIds.EventLeader,\n activity_id=activity1.id))\n user2.roles.append(Role(role_id=RoleIds.EventLeader,\n activity_id=activity2.id))\n db.session.commit()\n\n event = self.make_event()\n # Event has no activity, not valid\n assert not event.is_valid()\n\n # Test leaders\n event.activity_types.append(activity1)\n assert not event.has_valid_leaders()\n event.leaders.append(user1)\n assert event.has_valid_leaders()\n\n event.activity_types.append(activity2)\n assert not event.has_valid_leaders()\n event.leaders.append(user2)\n assert event.has_valid_leaders()\n\n assert event.is_valid()\n\n # Test slots\n event.num_slots = 0\n assert not event.is_valid()\n event.num_online_slots = 0\n assert event.is_valid()\n event.num_slots = -1\n assert not event.is_valid()\n event.num_slots = 0\n assert event.is_valid()\n\n # Test dates\n event.end = datetime.datetime.now()\n assert not event.is_valid()\n event.end = event.start\n assert event.is_valid()\n\n assert event.is_registration_open_at_time(datetime.datetime.now())\n\n event.registration_open_time = event.registration_close_time + \\\n datetime.timedelta(hours=1)\n assert not event.opens_before_closes()\n assert not event.is_valid()\n\n event.registration_open_time = datetime.datetime.combine(\n event.end,\n datetime.datetime.min.time()) + datetime.timedelta(days=1)\n event.registration_close_time = event.registration_open_time + \\\n datetime.timedelta(hours=1)\n assert event.opens_before_closes()\n assert not event.opens_before_ends()\n assert not event.is_valid()\n\n assert not event.is_registration_open_at_time(datetime.datetime.now())\n\n\nclass TestRegistrations(TestEvents):\n\n def make_registration(self, user):\n datetime.datetime.timestamp(datetime.datetime.now())\n return Registration(\n user=user,\n status=RegistrationStatus.Active,\n level=RegistrationLevels.Normal)\n\n def test_add_registration(self):\n event = self.make_event()\n event.num_online_slots = 2\n db.session.add(event)\n db.session.commit()\n\n now = datetime.datetime.now()\n assert event.is_registration_open_at_time(now)\n assert event.has_free_online_slots()\n\n user1 = create_test_user(\"email1\", \"license1\")\n user2 = create_test_user(\"email2\", \"license2\")\n\n assert event.can_self_register(user1, now)\n assert event.can_self_register(user2, now)\n\n event.registrations.append(self.make_registration(user1))\n db.session.commit()\n assert not event.can_self_register(user1, now)\n assert event.can_self_register(user2, now)\n\n event.num_online_slots = 1\n\n assert not event.has_free_online_slots()\n assert not event.can_self_register(user2, now)\n\n event.registrations[0].status = RegistrationStatus.Rejected\n assert event.has_free_online_slots()\n assert not event.can_self_register(user1, now)\n assert event.can_self_register(user2, now)\n\n db.session.commit()\n\n # Test db has been updated\n db_event = Event.query.filter_by(id=event.id).first()\n assert db_event.has_free_online_slots()\n assert not db_event.can_self_register(user1, now)\n assert db_event.can_self_register(user2, now)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":7530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"245766720","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom NeuralModels import TransposedDeConv, SeparableConv2d, ResidualBlock, ResidualSeparableBlock\nfrom DeepChromatron import CHANNELS, DIMENSION\n\nLATENT_SPACE = int(64)\n\n\nclass BerkeleyAutoEncoder(torch.nn.Module):\n def __init__(self, deconv = TransposedDeConv, activation = nn.LeakyReLU()):\n super(BerkeleyAutoEncoder, self).__init__()\n self.layer1 = UnetEncoder(CHANNELS, 64, bn = False)\n self.layer2 = UnetEncoder(64, 128)\n self.layer3 = UnetEncoder(128, 256)\n self.layer4 = UnetEncoder(256, 512)\n self.layer5 = UnetEncoder(512, 512)\n self.layer6 = UnetEncoder(512, 512)\n\n self.layer7 = UnetDecoder(512, 512, deconv=deconv)\n self.layer8 = UnetDecoder(1024, 256, deconv=deconv)\n self.layer9 = UnetDecoder(768, 128, deconv=deconv)\n self.layer10 = UnetDecoder(384, 64, deconv=deconv)\n self.layer11 = UnetDecoder(192, 64, deconv=deconv)\n\n self.activation = nn.ReLU()\n self.deconv1 = deconv(64, DIMENSION)\n\n def forward(self, x):\n l1 = self.layer1(x)\n l2 = self.layer2(l1)\n l3 = self.layer3(l2)\n l4 = self.layer4(l3)\n l5 = self.layer5(l4)\n l6 = self.layer6(l5)\n\n l7 = self.layer7(l6)\n c = F.relu(torch.cat([l7, l5], dim=1))\n l8 = self.layer8(c)\n c = F.relu(torch.cat([l8, l4], dim=1))\n l9 = self.layer9(c)\n c = F.relu(torch.cat([l9, l3], dim=1))\n l10 = self.layer10(c)\n c = F.relu(torch.cat([l10, l2], dim=1))\n l11 = self.layer11(c)\n y = F.relu(l11)\n y = self.deconv1(y)\n return torch.tanh(y)\n\n\nclass ResidualBerkeleyAutoEncoder(torch.nn.Module):\n def __init__(self, deconv = TransposedDeConv, activation = nn.LeakyReLU()):\n super(ResidualBerkeleyAutoEncoder, self).__init__()\n self.layer1 = ResidualBlock(CHANNELS, 64, stride = 2)\n self.layer2 = ResidualBlock(64, 128, stride = 2)\n self.layer3 = ResidualBlock(128, 256, stride = 2)\n self.layer4 = ResidualBlock(256, 512, stride = 2)\n self.layer5 = ResidualBlock(512, 512, stride = 2)\n self.layer6 = ResidualBlock(512, 512, stride = 2)\n\n self.layer7 = UnetDecoder(512, 512, deconv=deconv)\n self.layer8 = UnetDecoder(1024, 256, deconv=deconv)\n self.layer9 = UnetDecoder(768, 128, deconv=deconv)\n self.layer10 = UnetDecoder(384, 64, deconv=deconv)\n self.layer11 = UnetDecoder(192, 64, deconv=deconv)\n\n self.activation = nn.ReLU()\n self.deconv1 = deconv(64, DIMENSION)\n\n def forward(self, x):\n l1 = self.layer1(x)\n l2 = self.layer2(l1)\n l3 = self.layer3(l2)\n l4 = self.layer4(l3)\n l5 = self.layer5(l4)\n l6 = self.layer6(l5)\n\n l7 = self.layer7(l6)\n c = F.relu(torch.cat([l7, l5], dim=1))\n l8 = self.layer8(c)\n c = F.relu(torch.cat([l8, l4], dim=1))\n l9 = self.layer9(c)\n c = F.relu(torch.cat([l9, l3], dim=1))\n l10 = self.layer10(c)\n c = F.relu(torch.cat([l10, l2], dim=1))\n l11 = self.layer11(c)\n y = F.relu(l11)\n y = self.deconv1(y)\n return torch.tanh(y)\n\n\nclass SeparableBerkeleyAutoEncoder(torch.nn.Module):\n def __init__(self, deconv = TransposedDeConv, activation = nn.LeakyReLU()):\n super(SeparableBerkeleyAutoEncoder, self).__init__()\n self.conv1 = UnetEncoder(CHANNELS, 64, bn=False)\n self.conv2 = ResidualSeparableBlock(64, 128, stride=2)\n self.conv3 = ResidualSeparableBlock(128, 256, stride = 2)\n self.conv4 = ResidualSeparableBlock(256, 512, stride = 2)\n self.conv5 = ResidualSeparableBlock(512, 512, stride = 2)\n self.conv6 = ResidualSeparableBlock(512, 512, stride = 2)\n self.conv7 = ResidualSeparableBlock(512, 512, stride = 2)\n self.conv8 = ResidualSeparableBlock(512, 512, stride = 2)\n\n self.deconv = SeparableUnetDecoder(512, 512 )\n self.deconv2 = SeparableUnetDecoder(1024, 512)\n self.deconv3 = SeparableUnetDecoder(1024, 512)\n self.deconv4 = SeparableUnetDecoder(1024, 512)\n self.deconv5 = SeparableUnetDecoder(1024, 256)\n self.deconv6 = SeparableUnetDecoder(512, 128 )\n self.deconv7 = SeparableUnetDecoder(256, 64 )\n self.activation = nn.ReLU()\n self.deconv1 = deconv(128, DIMENSION)\n\n def forward(self, x):\n d1 = self.conv1(x)\n d2 = self.conv2(d1)\n d3 = self.conv3(d2)\n d4 = self.conv4(d3)\n d5 = self.conv5(d4)\n d6 = self.conv6(d5)\n d7 = self.conv7(d6)\n d8 = self.conv8(d7)\n\n u1 = self.deconv(d8)\n u1 = F.relu(torch.cat([u1, d7], dim=1))\n u2 = self.deconv2(u1)\n u2 = F.relu(torch.cat([u2, d6], dim=1))\n u3 = self.deconv3(u2)\n u3 = F.relu(torch.cat([u3, d5], dim=1))\n u4 = self.deconv4(u3)\n u4 = F.relu(torch.cat([u4, d4], dim=1))\n u5 = self.deconv5(u4)\n u5 = F.relu(torch.cat([u5, d3], dim=1))\n u6 = self.deconv6(u5)\n u6 = F.relu(torch.cat([u6, d2], dim=1))\n u7 = self.deconv7(u6)\n u7 = F.relu(torch.cat([u7, d1], dim=1))\n x = self.deconv1(u7)\n return torch.tanh(x)\n\n\nclass StrongBerkeleyAutoEncoder(torch.nn.Module):\n def __init__(self, deconv = TransposedDeConv, activation = nn.LeakyReLU()):\n super(StrongBerkeleyAutoEncoder, self).__init__()\n self.conv1 = UnetEncoder(CHANNELS, 64, bn=False)\n self.conv2 = UnetEncoder(64, 128 )\n self.conv3 = UnetEncoder(128, 256)\n self.conv4 = UnetEncoder(256, 512)\n self.conv5 = UnetEncoder(512, 512)\n self.conv6 = UnetEncoder(512, 512)\n self.conv7 = UnetEncoder(512, 512)\n self.conv8 = UnetEncoder(512, 512)\n\n self.deconv = UnetDecoder(512, 512 , deconv)\n self.deconv2 = UnetDecoder(1024, 512, deconv)\n self.deconv3 = UnetDecoder(1024, 512, deconv)\n self.deconv4 = UnetDecoder(1024, 512, deconv)\n self.deconv5 = UnetDecoder(1024, 256, deconv)\n self.deconv6 = UnetDecoder(512, 128 , deconv)\n self.deconv7 = UnetDecoder(256, 64 , deconv)\n self.activation = nn.ReLU()\n self.deconv1 = deconv(128, DIMENSION)\n\n def forward(self, x):\n d1 = self.conv1(x)\n d2 = self.conv2(d1)\n d3 = self.conv3(d2)\n d4 = self.conv4(d3)\n d5 = self.conv5(d4)\n d6 = self.conv6(d5)\n d7 = self.conv7(d6)\n d8 = self.conv8(d7)\n\n u1 = self.deconv(d8)\n u1 = F.relu(torch.cat([u1, d7], dim=1))\n u2 = self.deconv2(u1)\n u2 = F.relu(torch.cat([u2, d6], dim=1))\n u3 = self.deconv3(u2)\n u3 = F.relu(torch.cat([u3, d5], dim=1))\n u4 = self.deconv4(u3)\n u4 = F.relu(torch.cat([u4, d4], dim=1))\n u5 = self.deconv5(u4)\n u5 = F.relu(torch.cat([u5, d3], dim=1))\n u6 = self.deconv6(u5)\n u6 = F.relu(torch.cat([u6, d2], dim=1))\n u7 = self.deconv7(u6)\n u7 = F.relu(torch.cat([u7, d1], dim=1))\n x = self.deconv1(u7)\n return torch.tanh(x)\n\n\nclass UnetEncoder(nn.Module):\n def __init__(self, in_size, out_size, activation=nn.LeakyReLU(0.2), bn = True):\n super(UnetEncoder, self).__init__()\n layers = [nn.Conv2d(in_size, out_size, 3, 2, 1, bias=False)]\n\n if bn:\n layers +=[nn.BatchNorm2d(out_size)]\n\n layers +=[activation]\n\n self.model = nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.model(x)\n return x\n\n\nclass UnetDecoder(nn.Module):\n def __init__(self, in_size, out_size, deconv= TransposedDeConv):\n super(UnetDecoder, self).__init__()\n layers = [deconv(in_size, out_size),\n nn.BatchNorm2d(out_size)]\n #activation]\n\n self.model = nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.model(x)\n return x\n\n\nclass SeparableUnetDecoder(torch.nn.Module):\n def __init__(self, in_channels, out_channels,):\n super(SeparableUnetDecoder, self).__init__()\n self.reflection_pad = torch.nn.ReflectionPad2d(1)\n self.conv2d = SeparableConv2d(in_channels, out_channels, 3, 1, 1, bias=False)\n\n def forward(self, x):\n x = torch.nn.functional.interpolate(x, mode='nearest', scale_factor=2)\n out = self.reflection_pad(x)\n x = self.conv2d(x )\n return x\n","sub_path":"BerkeleyAutoEncoder.py","file_name":"BerkeleyAutoEncoder.py","file_ext":"py","file_size_in_byte":8468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"203507838","text":"\"\"\"\nClasses for querying the information in a test coverage report.\n\"\"\"\nfrom __future__ import unicode_literals\nfrom abc import ABCMeta, abstractmethod\nfrom collections import namedtuple, defaultdict\nimport re\nimport subprocess\nimport sys\nimport os\nimport six\nimport itertools\nfrom diff_cover.git_path import GitPathTool\n\n\nViolation = namedtuple('Violation', 'line, message')\n\n\nclass BaseViolationReporter(object):\n \"\"\"\n Query information from a coverage report.\n \"\"\"\n\n __metaclass__ = ABCMeta\n\n def __init__(self, name):\n \"\"\"\n Provide a name for the coverage report, which will be included\n in the generated diff report.\n \"\"\"\n self._name = name\n\n @abstractmethod\n def violations(self, src_path):\n \"\"\"\n Return a list of Violations recorded in `src_path`.\n \"\"\"\n pass\n\n def measured_lines(self, src_path):\n \"\"\"\n Return a list of the lines in src_path that were measured\n by this reporter.\n\n Some reporters will always consider all lines in the file \"measured\".\n As an optimization, such violation reporters\n can return `None` to indicate that all lines are measured.\n The diff reporter generator will then use all changed lines\n provided by the diff.\n \"\"\"\n return None\n\n def name(self):\n \"\"\"\n Retrieve the name of the report, which may be\n included in the generated diff coverage report.\n\n For example, `name()` could return the path to the coverage\n report file or the type of reporter.\n \"\"\"\n return self._name\n\n\nclass XmlCoverageReporter(BaseViolationReporter):\n \"\"\"\n Query information from a Cobertura XML coverage report.\n \"\"\"\n\n def __init__(self, xml_roots):\n \"\"\"\n Load the Cobertura XML coverage report represented\n by the cElementTree with root element `xml_root`.\n \"\"\"\n super(XmlCoverageReporter, self).__init__(\"XML\")\n self._xml_roots = xml_roots\n\n # Create a dict to cache violations dict results\n # Keys are source file paths, values are output of `violations()`\n self._info_cache = defaultdict(list)\n\n def _get_classes(self, xml_document, src_path):\n \"\"\"\n Given a path and parsed xml_document provides class nodes\n with the relevant lines\n\n First, we look to see if xml_document contains a source\n node providing paths to search for\n\n If we don't have that we check each nodes filename attribute\n matches an absolute path\n\n Finally, if we found no nodes, we check the filename attribute\n for the relative path\n \"\"\"\n # Remove git_root from src_path for searching the correct filename\n # If cwd is `/home/user/work/diff-cover/diff_cover`\n # and src_path is `diff_cover/violations_reporter.py`\n # search for `violations_reporter.py`\n src_rel_path = GitPathTool.relative_path(src_path)\n\n # If cwd is `/home/user/work/diff-cover/diff_cover`\n # and src_path is `other_package/some_file.py`\n # search for `/home/user/work/diff-cover/other_package/some_file.py`\n src_abs_path = GitPathTool.absolute_path(src_path)\n\n # cobertura sometimes provides the sources for the measurements\n # within it. If we have that we outta use it\n sources = xml_document.findall('sources/source')\n sources = [source.text for source in sources]\n classes = [class_tree\n for class_tree in xml_document.findall(\".//class\")\n or []]\n\n classes = (\n [clazz for clazz in classes if\n src_abs_path in [\n os.path.join(\n source,\n clazz.get('filename')\n ) for source in sources]]\n or\n [clazz for clazz in classes if\n clazz.get('filename') == src_abs_path]\n or\n [clazz for clazz in classes if\n clazz.get('filename') == src_rel_path]\n )\n return classes\n\n def _get_src_path_line_nodes(self, xml_document, src_path):\n \"\"\"\n Returns a list of nodes containing line information for `src_path`\n in `xml_document`.\n\n If file is not present in `xml_document`, return None\n \"\"\"\n\n classes = self._get_classes(xml_document, src_path)\n\n if not classes:\n return None\n else:\n lines = [clazz.findall('./lines/line') for clazz in classes]\n return [elem for elem in itertools.chain(*lines)]\n\n def _cache_file(self, src_path):\n \"\"\"\n Load the data from `self._xml_roots`\n for `src_path`, if it hasn't been already.\n \"\"\"\n # If we have not yet loaded this source file\n if src_path not in self._info_cache:\n # We only want to keep violations that show up in each xml source.\n # Thus, each time, we take the intersection. However, to do this\n # we must treat the first time as a special case and just add all\n # the violations from the first xml report.\n violations = None\n\n # A line is measured if it is measured in any of the reports, so\n # we take set union each time and can just start with the empty set\n measured = set()\n\n # Loop through the files that contain the xml roots\n for xml_document in self._xml_roots:\n line_nodes = self._get_src_path_line_nodes(xml_document,\n src_path)\n\n if line_nodes is None:\n continue\n\n # First case, need to define violations initially\n if violations is None:\n violations = set(\n Violation(int(line.get('number')), None)\n for line in line_nodes\n if int(line.get('hits', 0)) == 0)\n\n # If we already have a violations set,\n # take the intersection of the new\n # violations set and its old self\n else:\n violations = violations & set(\n Violation(int(line.get('number')), None)\n for line in line_nodes\n if int(line.get('hits', 0)) == 0\n )\n\n # Measured is the union of itself and the new measured\n measured = measured | set(\n int(line.get('number')) for line in line_nodes\n )\n\n # If we don't have any information about the source file,\n # don't report any violations\n if violations is None:\n violations = set()\n\n self._info_cache[src_path] = (violations, measured)\n\n def violations(self, src_path):\n \"\"\"\n See base class comments.\n \"\"\"\n\n self._cache_file(src_path)\n\n # Yield all lines not covered\n return self._info_cache[src_path][0]\n\n def measured_lines(self, src_path):\n \"\"\"\n See base class docstring.\n \"\"\"\n self._cache_file(src_path)\n return self._info_cache[src_path][1]\n\n\nclass BaseQualityReporter(BaseViolationReporter):\n \"\"\"\n Abstract class to report code quality\n information, using `COMMAND`\n (provided by subclasses).\n \"\"\"\n COMMAND = ''\n DISCOVERY_COMMAND = ''\n OPTIONS = []\n\n # Encoding of the stdout from the command\n # This is application-dependent\n STDOUT_ENCODING = 'utf-8'\n\n # A list of filetypes to run on.\n EXTENSIONS = []\n\n def __init__(self, name, input_reports, user_options=None):\n \"\"\"\n Create a new quality reporter.\n\n `name` is an identifier for the reporter\n (usually the name of the tool used to generate\n the report).\n\n `input_reports` is an list of\n file-like objects representing pre-generated\n violation reports. The list can be empty.\n\n If these are provided, the reporter will\n use the pre-generated reports instead of invoking\n the tool directly.\n\n 'user_options' is a string of options passed in.\n This string contains options that are passed forward\n to the reporter being used\n\n This raises an ImportError if the tool being created\n is not installed.\n \"\"\"\n super(BaseQualityReporter, self).__init__(name)\n # Test if the tool requested is installed\n self._confirm_installed(name)\n self._info_cache = defaultdict(list)\n self.user_options = user_options\n\n # If we've been given input report files, use those\n # to get the source information\n if len(input_reports) > 0:\n self.use_tool = False\n self._load_reports(input_reports)\n else:\n self.use_tool = True\n\n def violations(self, src_path):\n \"\"\"\n See base class comments.\n \"\"\"\n # If we've been given pre-generated pylint/pep8 reports,\n # then we've already loaded everything we need into the cache.\n # Otherwise, call pylint/pep8 ourselves\n if self.use_tool:\n if not any(src_path.endswith(ext) for ext in self.EXTENSIONS):\n return []\n if src_path not in self._info_cache:\n output = self._run_command(src_path)\n violations_dict = self._parse_output(output, src_path)\n self._update_cache(violations_dict)\n\n # Return the cached violation info\n return self._info_cache[src_path]\n\n def _load_reports(self, report_files):\n \"\"\"\n Load pre-generated pep8/pylint reports into\n the cache.\n\n `report_files` is a list of open file-like objects.\n \"\"\"\n for file_handle in report_files:\n # Convert to unicode, replacing unreadable chars\n contents = file_handle.read().decode(self.STDOUT_ENCODING,\n 'replace')\n violations_dict = self._parse_output(contents)\n self._update_cache(violations_dict)\n\n def _update_cache(self, violations_dict):\n \"\"\"\n Append violations in `violations_dict` to the cache.\n `violations_dict` must have the form:\n\n {\n SRC_PATH: [Violation, ]\n }\n \"\"\"\n for src_path, violations in six.iteritems(violations_dict):\n self._info_cache[src_path].extend(violations)\n\n def _confirm_installed(self, name):\n \"\"\"\n Assumes it can be imported with the same name.\n This applies to all python tools so far\n \"\"\"\n __import__(name)\n\n def _run_command(self, src_path):\n \"\"\"\n Run the quality command and return its output as a unicode string.\n \"\"\"\n # Encode the path using the filesystem encoding, determined at runtime\n encoding = sys.getfilesystemencoding()\n user_options = [self.user_options] if self.user_options else []\n command = [self.COMMAND] + self.OPTIONS + user_options + [src_path.encode(encoding)]\n try:\n process = subprocess.Popen(\n command, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n stdout, stderr = process.communicate()\n except OSError:\n sys.stderr.write(\" \".join([cmd.decode(encoding)\n if isinstance(cmd, bytes) else cmd\n for cmd in command]))\n raise\n\n if stderr and (process.returncode != 0):\n raise QualityReporterError(stderr.decode(encoding))\n\n return stdout.strip().decode(self.STDOUT_ENCODING, 'replace')\n\n def _run_command_simple(self, command):\n \"\"\"\n Returns command's exit code.\n \"\"\"\n process = subprocess.Popen(\n command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True\n )\n process.communicate()\n exit_code = process.returncode\n return exit_code\n\n def _parse_output(self, output, src_path=None):\n \"\"\"\n Parse the output of this reporter\n command into a dict of the form:\n\n {\n SRC_PATH: [Violation, ]\n }\n\n where `SRC_PATH` is the path to the source file\n containing the violations, and the value is\n a list of violations.\n\n If `src_path` is provided, return information\n just for that source.\n \"\"\"\n violations_dict = defaultdict(list)\n\n for line in output.split('\\n'):\n\n match = self.VIOLATION_REGEX.match(line)\n\n # Ignore any line that isn't a violation\n if match is not None:\n src, line_number, message = match.groups()\n\n # If we're looking for a particular source,\n # filter out all other sources\n if src_path is None or src_path == src:\n violation = Violation(int(line_number), message)\n violations_dict[src].append(violation)\n\n return violations_dict\n\n\nclass Pep8QualityReporter(BaseQualityReporter):\n \"\"\"\n Report PEP8 violations.\n \"\"\"\n COMMAND = 'pep8'\n EXTENSIONS = ['py']\n VIOLATION_REGEX = re.compile(r'^([^:]+):(\\d+).*([EW]\\d{3}.*)$')\n\n\nclass PyflakesQualityReporter(BaseQualityReporter):\n \"\"\"\n Report Pyflakes violations.\n \"\"\"\n COMMAND = 'pyflakes'\n EXTENSIONS = ['py']\n # Match lines of the form:\n # path/to/file.py:328: undefined name '_thing'\n # path/to/file.py:418: 'random' imported but unused\n VIOLATION_REGEX = re.compile(r'^([^:]+):(\\d+): (.*)$')\n\n\nclass Flake8QualityReporter(BaseQualityReporter):\n \"\"\"\n Report Flake8 violations.\n\n Flake8 warning/error codes:\n E***/W***: pep8 errors and warnings\n F***: pyflakes codes\n C9**: mccabe complexity plugin\n N8**: pep8-naming plugin\n T000: flake8-todo plugin\n\n http://flake8.readthedocs.org/en/latest/warnings.html\n \"\"\"\n COMMAND = 'flake8'\n EXTENSIONS = ['py']\n VIOLATION_REGEX = re.compile(r'^([^:]+):(\\d+).*([EWFCNTIBDSQ]\\d{3}.*)$')\n\n\nclass PylintQualityReporter(BaseQualityReporter):\n \"\"\"\n Report Pylint violations.\n \"\"\"\n COMMAND = 'pylint'\n MODERN_OPTIONS = ['--msg-template=\"{path}:{line}: [{msg_id}({symbol}), {obj}] {msg}\"']\n LEGACY_OPTIONS = ['-f', 'parseable', '--reports=no', '--include-ids=y']\n OPTIONS = MODERN_OPTIONS\n EXTENSIONS = ['py']\n DUPE_CODE_VIOLATION = 'R0801'\n\n # Match lines of the form:\n # path/to/file.py:123: [C0111] Missing docstring\n # path/to/file.py:456: [C0111, Foo.bar] Missing docstring\n VIOLATION_REGEX = re.compile(r'^([^:]+):(\\d+): \\[(\\w+),? ?([^\\]]*)] (.*)$')\n MULTI_LINE_VIOLATION_REGEX = re.compile(r'==(\\w|.+):(.*)')\n DUPE_CODE_MESSAGE_REGEX = re.compile(r'Similar lines in (\\d+) files')\n\n def _run_command(self, src_path):\n try:\n return super(PylintQualityReporter, self)._run_command(src_path)\n except QualityReporterError as report_error:\n # Support earlier pylint version (< 1)\n if \"no such option: --msg-template\" in six.text_type(report_error):\n self.OPTIONS = self.LEGACY_OPTIONS\n return super(PylintQualityReporter, self)._run_command(src_path)\n else:\n raise\n\n def _process_dupe_code_violation(self, lines, current_line, message):\n \"\"\"\n The duplicate code violation is a multi line error. This pulls out\n all the relevant files\n \"\"\"\n src_paths = []\n message_match = self.DUPE_CODE_MESSAGE_REGEX.match(message)\n if message_match:\n for _ in range(int(message_match.group(1))):\n current_line += 1\n match = self.MULTI_LINE_VIOLATION_REGEX.match(\n lines[current_line]\n )\n src_path, l_number = match.groups()\n src_paths.append(('%s.py' % src_path, l_number))\n return src_paths\n\n def _parse_output(self, output, src_path=None):\n \"\"\"\n See base class docstring.\n \"\"\"\n violations_dict = defaultdict(list)\n\n output_lines = output.split('\\n')\n\n for output_line_number, line in enumerate(output_lines):\n match = self.VIOLATION_REGEX.match(line)\n\n # Ignore any line that isn't matched\n # (for example, snippets from the source code)\n if match is not None:\n\n (pylint_src_path,\n line_number,\n pylint_code,\n function_name,\n message) = match.groups()\n if pylint_code == self.DUPE_CODE_VIOLATION:\n files_involved = self._process_dupe_code_violation(\n output_lines,\n output_line_number,\n message\n )\n else:\n files_involved = [(pylint_src_path, line_number)]\n\n for violation in files_involved:\n pylint_src_path, line_number = violation\n # If we're looking for a particular source file,\n # ignore any other source files.\n if src_path is None or src_path == pylint_src_path:\n\n if function_name:\n error_str = u\"{0}: {1}: {2}\".format(pylint_code, function_name, message)\n else:\n error_str = u\"{0}: {1}\".format(pylint_code, message)\n\n violation = Violation(int(line_number), error_str)\n violations_dict[pylint_src_path].append(violation)\n\n return violations_dict\n\n\nclass JsHintQualityReporter(BaseQualityReporter):\n \"\"\"\n Report JSHint violations.\n \"\"\"\n COMMAND = 'jshint'\n # The following command can confirm jshint is installed\n DISCOVERY_COMMAND = 'jshint -v'\n EXTENSIONS = ['js']\n VIOLATION_REGEX = re.compile(r'^([^:]+): line (\\d+), col \\d+, (.*)$')\n\n def _confirm_installed(self, name):\n \"\"\"\n Override base method. Confirm the tool is installed by running this command and\n getting exit 0. Otherwise, raise an Environment Error.\n \"\"\"\n if self._run_command_simple(self.DISCOVERY_COMMAND) == 0:\n return\n raise EnvironmentError\n\n\nclass QualityReporterError(Exception):\n \"\"\"\n A quality reporter command produced an error.\n \"\"\"\n pass\n","sub_path":"venvs/edxapp/lib/python2.7/site-packages/diff_cover/violations_reporter.py","file_name":"violations_reporter.py","file_ext":"py","file_size_in_byte":18638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"596071277","text":"import os\nimport timeit\nfrom glob import glob\nfrom datetime import datetime\n\nfrom pydub import AudioSegment\n# path =r'C:/Users/Sam/Music/Brian Tracy/The New Psychology of achievement/'\n# path =r'C:/Users/Sam/Music/Brian Tracy/The power of Self Discipine/'\n# use '/' in file path as we are using split() \n# C:\\Users\\Sam\\Music\\Desiging your own life\npath=r'C:/Users/Sam/Music/HowToOwnYourMind/'\nfoldername= path.split('/')[-2]\n#can use alternate between / or / for path\n# destdir = r'C:/Users/Sam/Documents/python/playgrond/'\ndestdir = path\n# use this for whole directory\ndirlist = [s for s in os.listdir(path)]\n# use this for selected folders\n# dirlist =['CD-3','CD-4','CD-5','CD-6', 'CD-7', 'CD-8','CD-9']\n# dirlist =['CD-3']\n# print(os.getcwd())\nprint(\"starting combining files\")\nstarttime = datetime.now()\n# print(strftime(\"%a, %d %b %Y %H:%M:%S +0000\", gmtime()))\nfor dir in dirlist:\n srcdir = path + dir +'/'\n # srcdir = dir\n print(srcdir)\n os.chdir(srcdir)\n if not os.path.isdir(srcdir): \n print(\"%sthis is not Directory\", srcdir)\n continue\n filelist = [f for f in os.listdir(srcdir)]\n if len(filelist) <=0:\n continue\n \n for f in os.listdir(srcdir):\n print(f)\n\n # start = timeit.timeit()\n playlist_songs = [AudioSegment.from_mp3(mp3_file) for mp3_file in glob(\"*.mp3\")]\n first_song = playlist_songs.pop(0)\n beginning_of_song = first_song\n playlist = beginning_of_song\n for song in playlist_songs:\n playlist = playlist.append(song, crossfade=(1 * 1000))\n playlist = playlist.fade_out(30)\n playlist_length = len(playlist) / (1000*60)\n \n os.chdir(destdir)\n print(destdir)\n if not os.path.isdir(foldername):\n os.mkdir(foldername)\n os.chdir(foldername)\n fout= \"%sminute_playlist.mp3\" % str(playlist_length)[:5]\n with open(fout,\"wb\") as outfile:\n playlist.export(outfile, format='mp3')\n os.rename(fout, dir+\".mp3\")\n # end = timeit.timeit()\n # elapsed = start - end \n # print(\"time Taken>>\" + str(elapsed))\nprint(\"Done\")\nprint(\"Total Time taken:{}\".format(str(datetime.now()- starttime)))\n\n","sub_path":"playlistcomibine.py","file_name":"playlistcomibine.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"180550478","text":"# -*- coding: utf-8 -*-\n\"\"\"\n :copyright: ©2018 by IPIP.net\n\"\"\"\n\nfrom .database import Database\n\n\nclass DistrictInfo:\n country_name = \"\"\n region_name = \"\"\n city_name = \"\"\n district_name = \"\"\n china_admin_code = \"\"\n covering_radius = \"\"\n latitude = \"\"\n longitude = \"\"\n\n def __init__(self, **kwargs):\n self._map = kwargs\n for key in self._map:\n self.__dict__[key] = self._map[key]\n\n\nclass District(Database):\n\n info = DistrictInfo\n","sub_path":"ipdb/district.py","file_name":"district.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"228180059","text":"#Create a menu function that lists the modes in the calculator\ndef menu():\n mode = input(\"\"\"Choose a mode by entering the number:\n \"1: Addition\n \"2: Subtraction\n \"3: Multiplication\n \"4: Division\n \"5: Powers\n \"6: Exit\"\"\").strip()\n return mode\n \n#Addition function\ndef add(number1, number2):\n answer = number1 + number2\n return answer\n\n#Subtraction function\ndef subtract(number1, number2):\n answer = number1 - number2\n return answer\n\n#Multiplication function\ndef multiply(number1, number2):\n answer = number1 * number2\n return answer\n\n#Division Function\ndef divide(number1, number2):\n answer = number1 / number2\n return answer\n\n#Powers function\ndef powers(number1, number2):\n answer = number1 ** number2\n return answer\n \n#Main program loop\nwhile True:\n \n #Print menu and get user's mode choice\n mode = menu()\n \n #Check it's a valid option\n if mode in [\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"]:\n \n #Ask user for numbers\n num1 = int(input(\"Enter the first number: \"))\n num2 = int(input(\"Enter the second number: \"))\n \n #Do chosen math with numbers, or break out of loop if exit is chosen\n \n #Addition\n if mode == \"1\":\n solution = add(num1, num2)\n print(\"{} + {} = {}\".format(num1, num2, solution))\n \n #Subtraction\n elif mode == \"2\":\n solution = subtract(num1, num2)\n print(\"{} - {} = {}\".format(num1, num2, solution))\n \n #Multiplication\n elif mode == \"3\":\n solution = multiply(num1, num2)\n print(\"{} * {} = {}\".format(num1, num2, solution))\n \n #Division\n elif mode == \"4\":\n solution = divide(num1, num2)\n print(\"{} / {} = {}\".format(num1, num2, solution))\n \n #Powers\n elif mode == \"5\":\n solution = powers(num1, num2)\n print(\"{} ^ {} = {}\".format(num1, num2, solution))\n \n #Break\n else:\n break\n\n \n #Otherwise, tell the user that wasn't an option\n else:\n print(\"Oops, that wasn't an option, try again!\")\n\n\nprint(\"Goodbye!\")\n","sub_path":"Python/Calculator.py","file_name":"Calculator.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"230117314","text":"from array import array\nfrom machine import ADC\nfrom machine import Pin\n\nUNCATEGORIZED = 0\nVERY_WET = 1\nWET = 2\nDRY = 3\n\n\nclass SoilSensor:\n def __init__(self, adc_pin, air_value, water_value):\n self._adc = ADC(Pin(adc_pin))\n self._adc.atten(ADC.ATTN_11DB)\n\n self._air_value = air_value\n self._water_value = water_value\n\n def read_data(self):\n moisture_value = self._adc.read()\n moisture_level = self._to_percent(moisture_value)\n category = self._categorize_moisture_value(moisture_value)\n\n return array('i', (moisture_value, moisture_level, category))\n\n def _to_percent(self, moisture_value):\n if moisture_value < self._water_value:\n converted_value = 0\n elif moisture_value > self._air_value:\n converted_value = 100\n else:\n delta = self._air_value - moisture_value\n divisor = self._air_value - self._water_value\n converted_value = int((delta / divisor) * 100)\n\n return converted_value\n\n def _categorize_moisture_value(self, moisture_value):\n intervals = int((self._air_value - self._water_value) / 3)\n upper_water_value = self._water_value + intervals\n lower_air_value = self._air_value - intervals\n\n if self._water_value <= moisture_value < upper_water_value:\n category = VERY_WET\n elif upper_water_value <= moisture_value < lower_air_value:\n category = WET\n elif lower_air_value <= moisture_value <= self._air_value:\n category = DRY\n else:\n category = UNCATEGORIZED\n\n return category\n","sub_path":"mcu/esp32/src/soil_sensor/soil_sensor.py","file_name":"soil_sensor.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"49118061","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 ('blog', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='blog',\n options={'ordering': ['-publish_date']},\n ),\n migrations.AddField(\n model_name='blog',\n name='slug',\n field=models.SlugField(default='default', unique=True, max_length=140),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='blog',\n name='publish_date',\n field=models.DateTimeField(auto_now_add=True),\n ),\n ]\n","sub_path":"wild_humans/blog/migrations/0002_auto_20160302_2058.py","file_name":"0002_auto_20160302_2058.py","file_ext":"py","file_size_in_byte":743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"520366844","text":"def computador_escolhe_jogada(n, m):\n for i in range(1, m + 1):\n if ((n - i) % (m + 1) == 0):\n # print(\"######\")\n # print(\"O computador tirou %s peças\"%str(i))\n return i\n elif i == m:\n # print(\"O computador tirou %s peças\"%str(m))\n return m\n\n\ndef usuario_escolhe_jogada(n, m):\n jogada = 0\n while True:\n try:\n jogada = int(input(\"Deseja retirar quantas peças? \"))\n if jogada > m:\n print(\"Opção invalida!\")\n else:\n break\n except:\n print(\"Opção invalida!\")\n break\n\n return jogada\n\n\ndef partida():\n usuario = 0\n computador = 0\n qtd_pecas = 0\n max_pecas = 0\n # token = 0\n print(\"#####\")\n while True:\n try:\n qtd_pecas = int(input(\"Quantas peças? \"))\n max_pecas = int(input(\"Limite de peças por jogada? \"))\n print(\"#####\")\n if qtd_pecas < 0 or max_pecas < 0:\n print(\"Opção invalida!\")\n # elif max_pecas>qtd_pecas:\n # print(\"Quantidade de peças deve ser maior que o limite de peças!\")\n else:\n break\n except:\n print(\"Opção invalida!\")\n\n if qtd_pecas % (max_pecas + 1) == 0:\n print(\"Voce começa!\")\n usuario = usuario_escolhe_jogada(qtd_pecas, max_pecas)\n qtd_pecas = qtd_pecas - usuario\n token = 0\n print(\"######\")\n print(\"Você tirou %s peças\" % str(usuario))\n print(\"Restam %s peças no tabuleiro\" % str(qtd_pecas))\n else:\n print(\"Computador começa!\")\n computador = computador_escolhe_jogada(qtd_pecas, max_pecas)\n qtd_pecas = qtd_pecas - computador\n token = 1\n print(\"######\")\n print(\"Computador tirou %s peças\" % str(computador))\n print(\"Restam %s peças no tabuleiro\" % str(qtd_pecas))\n\n while qtd_pecas > 0:\n if qtd_pecas % (max_pecas + 1) == 0 and token > 0:\n usuario = usuario_escolhe_jogada(qtd_pecas, max_pecas)\n qtd_pecas = qtd_pecas - usuario\n token = 0\n print(\"######\")\n print(\"Você tirou %s peças\" % str(usuario))\n print(\"Restam %s peças no tabuleiro\" % str(qtd_pecas))\n elif token < 1:\n computador = computador_escolhe_jogada(qtd_pecas, max_pecas)\n qtd_pecas = qtd_pecas - computador\n token = 1\n print(\"######\")\n print(\"Computador tirou %s peças\" % str(computador))\n print(\"Restam %s peças no tabuleiro\" % str(qtd_pecas))\n if token == 0:\n print(\"PARABENS!!! VOCE VENCEU\")\n return 0\n\n else:\n print(\"Fim do jogo! O computador ganhou!\")\n return 1\n\n\ndef main():\n print(\"Bem vindo ao jogo do NIM! Escolha:\")\n print(\"1 - para cada jogar uma partida isolada\")\n print(\"2- para jogar um campeonato\")\n iniciar = 0\n while True:\n try:\n iniciar = int(input(\"->\"))\n if iniciar > 2 or iniciar < 0:\n print(\"Opção invalida!\")\n else:\n break\n except:\n print(\"Opção invalida!\")\n placar = 0\n placar_usuario = 0\n placar_computador = 0\n if iniciar == 1:\n partida()\n else:\n for i in range(1, 4):\n print(\"############## PARTIDA %s #############\" % (str(i)))\n placar = partida()\n if placar == 0:\n placar_usuario = placar_usuario + 1\n else:\n placar_computador = placar_computador + 1\n print(\"Placar: Você %s X %s Computador\" % (str(placar_usuario), str(placar_computador)))\n\n\nmain()\n","sub_path":"jogo_nim.py","file_name":"jogo_nim.py","file_ext":"py","file_size_in_byte":3727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"430856641","text":"import discord\nfrom discord.ext import commands\n\n\nclass Errors(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n if isinstance(error, commands.CommandNotFound):\n await ctx.send('That command does not exist')\n\n\ndef setup(client):\n client.add_cog(Errors(client))\n","sub_path":"bot/cogs/errors.py","file_name":"errors.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"638502401","text":"# -*- coding: utf-8 -*-\n\nimport dateparser\nimport datetime\nimport json\nimport logging\nimport re\nimport scrapy\n\nfrom .. import items\n\n\ndef parse_times(dt):\n day, times = dt.split(' ', 1)\n date = dateparser.parse(day)\n start_time_string, end_time_string = re.split(r'-', times, 1)\n start_time = dateparser.parse(start_time_string).time()\n end_time = dateparser.parse(end_time_string).time()\n if start_time.hour < 12:\n start_time = start_time.replace(start_time.hour + 12)\n if end_time.hour < 12:\n end_time = end_time.replace(end_time.hour + 12)\n return (\n datetime.datetime.combine(date, start_time),\n datetime.datetime.combine(date, end_time),\n )\n\n\nclass TheLab(items.StudioScraper):\n name = 'TheLab'\n allowed_domains = ['www.tlxwc.com']\n latlong = (34.080570991151, -117.90854036514)\n address = '541 N Azusa Ave, West Covina, CA'\n\n def start_requests(self):\n yield scrapy.Request('http://www.tlxwc.com/wp/?page_id=79')\n\n def _valid_item(self, item):\n if not self._street_style(item['style']):\n return False\n return True\n\n def parse_classes(self, response):\n logging.info(response)\n for col in response.css('div.wpb_text_column'):\n col_text = self._extract_text(col)\n if 'BEGINNING' in col_text or 'ADVANCED' in col_text:\n for row in col.css('p'):\n text = self._extract_text(row)\n if u'–' in text and re.search('\\d:\\d\\d', text):\n datetime, class_details = text.split(u'–', 1)\n\n teacher_match = re.search(r'\\((.+?)\\)', class_details.strip())\n if teacher_match:\n teacher = teacher_match.group(1)\n else:\n logging.error('Could not find teacher: %s', class_details)\n teacher = ''\n class_details = re.sub('\\(%s\\)' % teacher, '', class_details)\n\n item = items.StudioClass()\n item['style'] = class_details.title()\n item['teacher'] = teacher.title()\n # do we care?? row[4]\n start_time, end_time = parse_times(datetime.strip())\n item['start_time'] = start_time\n item['end_time'] = end_time\n if self._valid_item(item):\n for new_item in self._repeated_items_iterator(item):\n yield new_item\n","sub_path":"scrapers/scrapy/classes/spiders/la_thelab.py","file_name":"la_thelab.py","file_ext":"py","file_size_in_byte":2616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"202816007","text":"from typing import Any\nfrom typing import Optional\n\nfrom cleo.io.inputs.argument import Argument\nfrom cleo.io.inputs.option import Option\n\n\ndef argument(\n name: str,\n description: Optional[str] = None,\n optional: bool = False,\n multiple: bool = False,\n default: Optional[Any] = None,\n) -> Argument:\n return Argument(\n name,\n required=not optional,\n is_list=multiple,\n description=description,\n default=default,\n )\n\n\ndef option(\n long_name: str,\n short_name: Optional[str] = None,\n description: Optional[str] = None,\n flag: bool = True,\n value_required: bool = True,\n multiple: bool = False,\n default: Optional[Any] = None,\n) -> Option:\n return Option(\n long_name,\n short_name,\n flag=flag,\n requires_value=value_required,\n is_list=multiple,\n description=description,\n default=default,\n )\n","sub_path":"mds_py/mds-env/lib/python3.11/site-packages/cleo/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"531004298","text":"import numpy as np\nimport pandas as pd\n\nfrom src.feature_extraction.FrequencyFeaturesCalculator import FrequencyFeaturesCalculator\nfrom src.feature_extraction.HRVFeaturesCalculator import HRVFeaturesCalculator\nfrom src.feature_extraction.KatzFeaturesCalculator import KatzFeaturesCalculator\nfrom src.feature_extraction.PointecareFeaturesCalculator import PointecareFeaturesCalculator\nfrom src.feature_extraction.RQAFeaturesCalculator import RQAFeaturesCalculator\nfrom src.feature_extraction.TimeFeaturesCalculator import TimeFeaturesCalculator\nfrom src.feature_extraction.COSenFeaturesCalculator import COSenFeaturesCalculator\nimport src.feature_extraction.io\n\n\ndef extract_segment_hrv_features(nni_segment, sampling_frequency, _time=False, _frequency=False, _pointecare=False,\n _katz=False, _rqa=False, _cosen=False, m=None, g=None):\n \"\"\"\n Method 1: Get all features of a group or groups.\n Given an nni segment and its sampling frequency, extracts and returns all the features of the groups marked as True.\n :param nni_segment: Sequence of nni samples.\n :param sampling_frequency: Sampling frequency (in Hertz) of the nni segment.\n :param _time: Pass as True to compute all time domain features.\n :param _frequency: Pass as True to compute all frequency domain features.\n :param _pointecare: Pass as True to compute all pointecare features.\n :param _katz: Pass as True to compute all katz features.\n :param _rqa: Pass as True to compute all recurrent quantitative analysis features.\n :param _cosen: Pass as True to compute all COSen features.\n :param m: m parameter for the COSen calculator referring to the embedding dimension. It should be an integer, usually between 1-5.\n :param g: g parameter for the COSen calculator used to calculate de vector comparison distance (r). Value in percentage.Usually between 01-0.5.\n :return extracted_features: An np.hstack with all the requested features.\n \"\"\"\n extracted_features = []\n\n features_calculator = None\n\n if _time:\n features_calculator = TimeFeaturesCalculator(nni_segment, sampling_frequency)\n extracted_features = np.hstack((extracted_features,\n features_calculator.get_mean(),\n features_calculator.get_var(),\n features_calculator.get_rmssd(),\n features_calculator.get_sdnn(),\n features_calculator.get_nn50(),\n features_calculator.get_pnn50()\n ))\n\n if _frequency:\n features_calculator = FrequencyFeaturesCalculator(nni_segment, sampling_frequency)\n extracted_features = np.hstack((extracted_features,\n features_calculator.get_lf(),\n features_calculator.get_hf(),\n features_calculator.get_lf_hf(),\n features_calculator.get_hf_lf(),\n ))\n\n if _pointecare:\n features_calculator = PointecareFeaturesCalculator(nni_segment)\n extracted_features = np.hstack((extracted_features,\n features_calculator.get_sd1(),\n features_calculator.get_sd2(),\n features_calculator.get_csi(),\n features_calculator.get_csv(),\n ))\n\n if _katz:\n features_calculator = KatzFeaturesCalculator(nni_segment)\n extracted_features = np.hstack((extracted_features,\n features_calculator.get_katz_fractal_dim(),\n ))\n\n if _rqa:\n features_calculator = RQAFeaturesCalculator(nni_segment)\n extracted_features = np.hstack((extracted_features,\n features_calculator.get_rec(),\n features_calculator.get_det(),\n features_calculator.get_lmax(),\n ))\n\n if _cosen:\n features_calculator = COSenFeaturesCalculator(nni_segment, m, g)\n extracted_features = np.hstack((extracted_features,\n features_calculator.get_sampen(),\n features_calculator.get_cosen(),\n ))\n\n if features_calculator is not None:\n del features_calculator\n\n return extracted_features\n\n\ndef extract_segment_some_hrv_features(nni_segment, sampling_frequency, needed_features: list, m=None, g=None):\n \"\"\"\n Method 2: Specify which features are needed. More inefficient.\n Given an nni segment and its sampling frequency, extracts and returns the requested needed features.\n :param nni_segment: Sequence of nni samples.\n :param sampling_frequency: Sampling frequency (in Hertz) of the nni segment.\n :param needed_features: List containing the needed features in strings. Any feature is possible if defined in\n the HRVFeaturesCalculator classes.\n :param m: m parameter for the COSen calculator referring to the embedding dimension. It should be an integer, usually between 1-5.\n :param g: g parameter for the COSen calculator used to calculate de vector comparison distance (r). Value in percentage.Usually between 01-0.5.\n :return features: A list of the requested feature values.\n \"\"\"\n\n # Auxiliary procedure\n def __get_hrv_features(calculator: HRVFeaturesCalculator, needed_features: list):\n \"\"\"\n Given an HRV features calculator, gathers a list of computed features.\n :param calculator: A defined HRVFeaturesCalculator.\n :param needed_features: List containing the needed features in strings.\n :return: A list of the requested feature values.\n \"\"\"\n features = []\n labels = []\n for needed_feature in needed_features:\n assert isinstance(needed_feature, str)\n if hasattr(calculator, 'get_' + needed_feature):\n features.append(getattr(calculator, 'get_' + needed_feature)())\n # labels.append(calculator.labels[needed_feature])\n labels.append(needed_feature)\n return features, labels\n\n # Main segment\n extracted_features = []\n labels = []\n\n features_calculator = None\n\n if 'nn50' in needed_features or 'pnn50' in needed_features or 'sdnn' in needed_features or \\\n 'rmssd' in needed_features or 'mean' in needed_features or 'var' in needed_features or \\\n 'hr' in needed_features or 'maxhr' in needed_features:\n features_calculator = TimeFeaturesCalculator(nni_segment, sampling_frequency)\n f, l = __get_hrv_features(features_calculator, needed_features)\n extracted_features = np.hstack((extracted_features, f))\n labels += l\n\n if 'lf' in needed_features or 'hf' in needed_features or 'lf_hf' in needed_features or 'hf_lf' in needed_features:\n features_calculator = FrequencyFeaturesCalculator(nni_segment, sampling_frequency)\n f, l = __get_hrv_features(features_calculator, needed_features)\n extracted_features = np.hstack((extracted_features, f))\n labels += l\n\n if 'sd1' in needed_features or 'sd2' in needed_features or 'csi' in needed_features or 'csv' in needed_features or 's' in needed_features:\n features_calculator = PointecareFeaturesCalculator(nni_segment)\n f, l = __get_hrv_features(features_calculator, needed_features)\n extracted_features = np.hstack((extracted_features, f))\n labels += l\n\n if 'katz_fractal_dim' in needed_features:\n features_calculator = KatzFeaturesCalculator(nni_segment)\n f, l = __get_hrv_features(features_calculator, needed_features)\n extracted_features = np.hstack((extracted_features, f))\n labels += l\n\n if 'rec' in needed_features or 'det' in needed_features or 'lmax' in needed_features:\n features_calculator = RQAFeaturesCalculator(nni_segment)\n f, l = __get_hrv_features(features_calculator, needed_features)\n extracted_features = np.hstack((extracted_features, f))\n labels += l\n\n if 'sampen' in needed_features or 'cosen' in needed_features:\n features_calculator = COSenFeaturesCalculator(nni_segment, m, g)\n f, l = __get_hrv_features(features_calculator, needed_features)\n extracted_features = np.hstack((extracted_features, f))\n labels += l\n\n if features_calculator is not None:\n del features_calculator\n\n return extracted_features, labels\n\n\ndef segment_nni_signal(nni_signal, n_samples_segment, n_samples_overlap=0):\n date_time_indexes = list(nni_signal['nni'].keys())\n step = n_samples_segment - n_samples_overlap\n print(\"n_samples_segment = \", n_samples_segment, \"(\", type(n_samples_segment))\n print(\"n_samples_overlap = \", n_samples_overlap, \"(\", type(n_samples_overlap))\n segmented_nni = [nni_signal[i: i + n_samples_segment] for i in range(0, len(nni_signal) - n_samples_segment, step)]\n segmented_date_time = [date_time_indexes[i: i + n_samples_segment] for i in\n range(0, len(date_time_indexes) - n_samples_segment, step)]\n print(\"Divided signal into \" + str(len(segmented_nni)) + \" samples.\")\n assert len(segmented_nni) == len(segmented_date_time)\n return segmented_nni, segmented_date_time\n\n\ndef extract_patient_hrv_features(patient: int, crises=None, baseline=False, state=\"awake\",\n segment_time=15, segment_overlap_time=0,\n _time=False, _frequency=False, _pointecare=False, _katz=False, _rqa=False,\n _cosen=False,\n m=None, g=None,\n needed_features: list = None,\n _save=True):\n \"\"\"\n Extracts features of some or all crises of a given patient.\n\n :param patient: Integer number of the patient.\n :param crises: Integer number of the crisis of the patient, or\n a list of integers of multiple crises of the patient, or\n None to extract features of all crises of the patient.\n :param baseline: Pass as true to additionally extract features of the corresponding baseline file.\n Also specify :param state.\n :param state: Patient state when acquiring the baseline file. Should be \"awake\" or \"asleep\".\n Parameter only valid if :param baseline = True.\n\n :param segment_time: Integer number of seconds for each segment.\n :param segment_overlap_time: Integer number of seconds of overlap between segments.\n\n :param _time: Pass as True to compute all time domain features.\n :param _frequency: Pass as True to compute all frequency domain features.\n :param _pointecare: Pass as True to compute all pointecare features.\n :param _katz: Pass as True to compute all katz features.\n :param _rqa: Pass as True to compute all recurrent quantitative analysis features.\n :param _cosen: Pass as True to compute all COSen features.\n :param m: m parameter for the COSen calculator referring to the embedding dimension. It should be an integer, usually between 1-5.\n :param g: g parameter for the COSen calculator used to calculate de vector comparison distance (r). Value in percentage.Usually between 01-0.5.\n\n :param needed_features: List containing the needed features in strings. Any feature is possible if defined in\n the HRVFeaturesCalculator classes.\n\n :param _save: Pass as True to save the features in a HDF file.\n :return: A pd.Dataframe containing the extracted features in each column by segments in rows (for a single crisis),\n or a dictionary with one element for each crisis of the patient, identified by the crisis number. Each of\n these elements is a pd.Dataframe.\n\n Note: The computed features are the union between the _time, _frequency, _pointecare, _katz, _rqa groups and the\n individual features specified in needed_features.\n \"\"\"\n\n if g is not None:\n g = float(g)\n\n if m is not None:\n m = int(m)\n\n sf = src.feature_extraction.io.metadata['sampling_frequency'] # Hz\n n_samples_segment = segment_time * sf\n n_samples_overlap = int(segment_overlap_time * sf)\n\n # Get labels for the features\n labels = []\n # groups\n if _time:\n labels += list(TimeFeaturesCalculator.labels.keys())\n if _frequency:\n labels += list(FrequencyFeaturesCalculator.labels.keys())\n if _pointecare:\n labels += list(PointecareFeaturesCalculator.labels.keys())\n if _katz:\n labels += list(KatzFeaturesCalculator.labels.keys())\n if _rqa:\n labels += list(RQAFeaturesCalculator.labels.keys())\n if _cosen:\n labels += list(COSenFeaturesCalculator.labels.keys())\n\n # individual features\n if needed_features is not None:\n for f in needed_features:\n if f in labels: # if this feature was already part of a group, it was already extracted\n needed_features.remove(f) # remove to prevent duplicates\n else:\n labels.append(f)\n print('labels', labels)\n\n # Auxiliary procedure\n def __extract_crisis_hrv_features(patient, crisis):\n nni_signal = src.feature_extraction.io.__read_crisis_nni(patient, crisis)\n segmented_nni, segmented_date_time = segment_nni_signal(nni_signal, n_samples_segment,\n n_samples_overlap=n_samples_overlap)\n features = pd.DataFrame(columns=labels)\n\n # complete group features\n for i, segment, segment_times in zip(range(len(segmented_nni)), segmented_nni,\n segmented_date_time):\n print(\"Segment \", i)\n # group features\n extracted_features = extract_segment_hrv_features(segment, sf, _time=_time, _frequency=_frequency,\n _pointecare=_pointecare, _katz=_katz, _rqa=_rqa,\n _cosen=_cosen,\n m=m, g=g)\n\n # individual features\n new_labels = []\n if needed_features is not None:\n new_features, new_labels = extract_segment_some_hrv_features(segment, sf, needed_features, m=m, g=g)\n extracted_features = np.hstack((extracted_features, new_features))\n features.columns = new_labels\n features.loc[i] = extracted_features # add a line\n t = segment_times[0] + ((segment_times[-1] - segment_times[0]) / 2) # time in the middle of the segment\n features = features.rename({i: t}, axis='index')\n\n if _save:\n print(\"Saving\")\n src.feature_extraction.io.__save_crisis_hrv_features(patient, crisis, features)\n\n return features\n\n def __extract_baseline_hrv_features(patient, state):\n nni_signal = src.feature_extraction.io.__read_baseline_nni(patient, state)\n segmented_nni, segmented_date_time = segment_nni_signal(nni_signal, n_samples_segment,\n n_samples_overlap=n_samples_overlap)\n features = pd.DataFrame(columns=labels)\n\n # complete group features\n for i, segment, segment_times in zip(range(len(segmented_nni)), segmented_nni,\n segmented_date_time):\n # group features\n extracted_features = extract_segment_hrv_features(segment, sf, _time=_time, _frequency=_frequency,\n _pointecare=_pointecare, _katz=_katz, _rqa=_rqa,\n _cosen=_cosen, m=m, g=g)\n\n # individual features\n new_labels = []\n if needed_features is not None:\n new_features, new_labels = extract_segment_some_hrv_features(segment, sf, needed_features, m=m, g=g)\n extracted_features = np.hstack((extracted_features, new_features))\n features.columns = new_labels\n features.loc[i] = extracted_features # add a line\n t = segment_times[0] + ((segment_times[-1] - segment_times[0]) / 2) # time in the middle of the segment\n features = features.rename({i: t}, axis='index')\n\n if _save:\n src.feature_extraction.io.__save_baseline_hrv_features(patient, state, features)\n\n return features\n\n # Extract baseline\n if baseline:\n features_baseline = __extract_baseline_hrv_features(patient, state)\n return features_baseline\n\n # Main segment\n if crises is None:\n if input(\"You are about to extract features from all crisis of patient \" + str(\n patient) + \". Are you sure? y/n\").lower() == 'n':\n return\n # extract features for all crisis of the given patient\n crises = src.feature_extraction.io.__get_patient_crises_numbers(patient)\n features_set = {}\n for crisis in crises:\n # check if it already exists\n features = src.feature_extraction.io.__read_crisis_hrv_features(patient, crisis)\n if features is not None:\n if input(\"An HRV features HDF5 file for this patient's crisis \" + str(\n crisis) + \" was found with the features \" + str(\n list(features.columns)) + \".\\nDiscard and recompute? y/n\").lower() == 'y':\n print(\"Recomputing...\")\n features_set[crisis] = __extract_crisis_hrv_features(patient, crisis)\n else:\n print(\"Returning the features founded.\")\n features_set[crisis] = features\n\n return features_set\n\n elif isinstance(crises, list) and len(crises) > 0: # extract features for a specific crisis of the given patient\n features_set = {}\n for crisis in crises:\n # check if it already exists\n features = src.feature_extraction.io.__read_crisis_hrv_features(patient, crisis)\n if features is not None:\n if input(\"An HRV features HDF5 file for this patient's crisis \" + str(\n crisis) + \" was found with the features \" + str(\n list(features.columns)) + \".\\nDiscard and recompute? y/n\").lower() == 'y':\n print(\"Recomputing...\")\n features_set[crisis] = __extract_crisis_hrv_features(patient, crisis)\n else:\n print(\"Returning the features founded.\")\n features_set[crisis] = features\n else:\n features_set[crisis] = __extract_crisis_hrv_features(patient, crisis)\n return features_set\n\n elif isinstance(crises, int):\n # check if it already exists\n features = src.feature_extraction.io.__read_crisis_hrv_features(patient, crises)\n if features is not None:\n if input(\"An HRV features HDF5 file for this patient/crisis was found with the features \" + str(\n list(features.columns)) + \".\\nDiscard and recompute? y/n\").lower() == 'y':\n print(\"Recomputing...\")\n print(\"Features when extracting:\", features)\n return __extract_crisis_hrv_features(patient, crises)\n else:\n print(\"Returning the features found.\")\n return features\n\n else:\n return __extract_crisis_hrv_features(patient, crises)\n\n else:\n raise Exception(\"'crises' should be an integer (for 1 crisis extraction), a list of integers (for multiple \"\n \"crisis extraction), or None to extract features of all crises of the patient.\")\n\n\ndef extract_hrv_features_all_patients(segment_time=15, segment_overlap_time=0, _save=True):\n \"\"\"\n Extracts features of all crises of all patients.\n\n :param segment_time: Integer number of seconds for each segment.\n :param segment_overlap_time: Integer number of seconds of overlap between segments.\n :param _save: Pass as True to save the features in HDF files.\n\n :return: A dictionary with one element for each patient, identified by its number. Each element is another\n dictionary with one element for each crisis of that patient, identified by the crisis number. Each of these elements\n are a pd.Dataframe containing the extracted features in each column by segments in rows.\n \"\"\"\n all_patient_numbers = src.feature_extraction.io.__get_patient_numbers()\n patients_set = {}\n for patient in all_patient_numbers:\n patients_set[patient] = extract_patient_hrv_features(patient, None, segment_time=segment_time,\n segment_overlap_time=segment_overlap_time, _save=_save)\n\n return patients_set\n\n\ndef get_patient_hrv_features(patient: int, crisis: int):\n \"\"\"\n Returns the features of the given patient-crisis pair.\n :param patient: Integer number of the patient.\n :param crisis: Integer number of the crisis of the patient.\n :return:\n \"\"\"\n features = src.feature_extraction.io.__read_crisis_hrv_features(patient, crisis)\n\n if features is None: # HDF not found, compute the feature4:\n\t\t\t# print('Error: Found too many bands, make sure you do not have duplicates.')\n\t\t\t# sys.exit(1)\n\t\t# # SLIP \t\n\t# SLIPmodel()\n\t\n#def SLIPmodel():\t\n\t\n# def doBandMath():\n\ndef main():\n\tyear=getCurrentYear()\n\tmonth=getCurrentMonth()\n\tday='03'#getCurrentDay()\n\tjd=int(currentJulianDate(year,month,day))\n\tpath=findPath(jd)\n\tdirectory=getCurrentDirectory() + '/Today/' + path + '/'\n\tdownloadLandsatScene(jd,year,month,day,path,directory)\n\tprint('SLIP ran!')#SLIP.model()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"SLIP_Preprocess.py","file_name":"SLIP_Preprocess.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"260923289","text":"# -*- coding: utf-8 -*-\nimport requests,json,time,datetime\nimport os,sys, logging\nfrom intelabInfluxdb import InfluxdbClient\nfrom azure.storage.blob import BlockBlobService\nfrom azure.storage.blob import ContentSettings\nlogging.basicConfig(level=logging.INFO,\n filename='new.log',\n filemode='a',\n format=\n '%(asctime)s - %(pathname)s[line:%(lineno)d] - %(levelname)s: %(message)s'\n )\n\n\n\nmystoragename = \"ilsqzwjvideo\"\nmystoragekey = \"wta7rpW6HeTzok1AwhYohbj+Ws6cFN7u102vkTlSjrOGBllUtKMuezwuenipjnaBng4hXHtS53341liEVz1MKA==\"\nblob_service = BlockBlobService(account_name=mystoragename, account_key=mystoragekey,endpoint_suffix='core.chinacloudapi.cn')\n\ndef getToken():\n # data={\"appKey\":\"102574957ca44d8493e6c1df6aaa1b14\",\n # \"appSecret\":\"2fd3f7e17d5a9590c182e6f2ee64bdfc\"}\n data={\"appKey\":\"a287e05ace374c3587e051db8cd4be82\",\n \"appSecret\":\"f01b61048a1170c4d158da3752e4378d\"}\n r= requests.post(\"https://open.ys7.com/api/lapp/token/get\",data=data)\n return json.loads(r.text)['data']['accessToken']\n\n'''查询所有设备的sn'''\ndef get_device_sn(token):\n try:\n list = []\n for i in range(sys.maxsize):\n data = {\"accessToken\": token, \"pageStart\": i, \"pageSize\": 50}\n r=requests.post(\"https://open.ys7.com/api/lapp/device/list\",data=data)\n result = json.loads(r.text)['data']\n print(result)\n if len(result) == 0:\n break\n list += result\n deviceSN = []\n for i in list:\n deviceSN.append(i['deviceSerial'])\n return deviceSN\n logging.info(\"get device ok\")\n except Exception as e:\n logging.info(e)\n\ndef get_alarm_picture(token,deviceSerial,startTime,endTime,url,path):\n try:\n list = []\n for i in range(sys.maxsize):\n data = {\"accessToken\": token, \"pageStart\": i, \"pageSize\": 50, \"deviceSerial\": deviceSerial,\n \"startTime\": startTime*1000, \"endTime\": endTime*1000, \"status\": 2, \"alarmType\": -1}\n #data = {\"accessToken\": token, \"pageStart\": i, \"pageSize\": 50, \"deviceSerial\": deviceSerial,\n # \"startTime\": startTime, \"endTime\": endTime, \"status\": 2, \"alarmType\": -1}\n r = requests.post(\"https://open.ys7.com/api/lapp/alarm/device/list\", data=data)\n result = json.loads(r.text)['data']\n print(result)\n if len(result) == 0:\n break\n list += result\n influxdb = InfluxdbClient()\n for i in list:\n print(i['alarmPicUrl'])\n print(i['deviceSerial'])\n downLoadPhoto(path,i['alarmPicUrl'],i['deviceSerial'],i['alarmTime'])\n print(i['alarmTime'])\n a = str(url) + \"/intelab-alarm-list\" + \"/\" + str(i['deviceSerial']) + str(i['alarmTime']) + \".jpg\"\n print(a)\n influxdb.insert_message(i['alarmTime'], a, str(i['deviceSerial']))\n return list\n except Exception as e:\n print(e)\n\ndef getfile(path):\n for root, dirs, files in os.walk(path):\n for file in files:\n uploadPhoto(file,str(path)+\"/\"+file)\n\ndef del_file(path):\n ls = os.listdir(path)\n for i in ls:\n c_path = os.path.join(path, i)\n if os.path.isdir(c_path):\n del_file(c_path)\n else:\n os.remove(c_path)\n\ndef uploadPhoto(name,path):\n blob_service.create_blob_from_path(\n 'intelab-alarm-list',\n name,\n path,\n content_settings=ContentSettings(content_type='image/jpg'))\n\ndef downLoadPhoto(path,url,deviceSerial,alarmTime):\n if not os.path.exists(path):\n os.mkdir(path)\n f = requests.get(url)\n # 下载文件\n with open(str(path)+\"/\"+str(deviceSerial)+\"{}.jpg\".format(alarmTime), \"wb\") as code:\n code.write(f.content)\n getfile(path)\n del_file(path)\n\nif __name__ == \"__main__\":\n # 今天日期\n today = datetime.date.today()\n # 昨天时间\n yesterday = today - datetime.timedelta(days=1)\n # 昨天开始时间戳\n yesterday_start_time = int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d')))\n timeArray = time.localtime(yesterday_start_time)\n otherStyleTime = time.strftime(\"%Y--%m--%d %H:%M:%S\", timeArray)\n print(otherStyleTime)\n # 昨天结束时间戳\n yesterday_end_time = int(time.mktime(time.strptime(str(today), '%Y-%m-%d')))-1\n timeArray = time.localtime(yesterday_end_time)\n otherStyleTime = time.strftime(\"%Y--%m--%d %H:%M:%S\", timeArray)\n list = get_device_sn(getToken())\n try:\n for i in list:\n get_alarm_picture(getToken(),i,yesterday_start_time,yesterday_end_time,\"https://ilsqzwjvideo.blob.core.chinacloudapi.cn\",\"/root/images\")\n logging.info(\"OK\")\n except Exception as e:\n logging.info(e)\n\n\n\n","sub_path":"scripts/getPic.py","file_name":"getPic.py","file_ext":"py","file_size_in_byte":4879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"396312293","text":"import json\nimport sys\n\nimport requests\nimport time\nimport paho.mqtt.client\nimport paho.mqtt.publish\n\nimport Suscriptor\n\n\ndef main():\n client = paho.mqtt.client.Client(\"alexa_echo\", False)\n client.qos = 0\n client.connect(host='localhost')\n\n variable = time.time()\n variable2 = time.time()\n while True:\n res = int(variable - variable2)\n complete_url = \"http://api.openweathermap.org/data/2.5/weather?lat=10.491&lon=-66.902&appid=0c16fe21b93a1d6f05e452e746e12403\"\n\n response = (requests.get(complete_url)).json()\n\n if response[\"cod\"] != \"404\":\n\n data = response[\"main\"]\n\n current_temperature = data[\"temp\"]\n\n else:\n print(\" Ciudad no encontrada\")\n\n item = {\n \"data\": str(\"Reporte: \" + str(current_temperature) + \"K\" + \" \" + \"Tiempo: \" + str(res))\n }\n payload = {\n \"reporte\": current_temperature,\n \"tiempo\": res,\n \"item\": item\n }\n\n client.publish('casa/sala/alexa_echo', json.dumps(payload), qos=0)\n time.sleep(300)\n variable = time.time()\n\n\nif __name__ == '__main__':\n main()\n sys.exit(0)\n","sub_path":"alexa_echo.py","file_name":"alexa_echo.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"467972415","text":"class Tile(object):\n \"\"\"A tile in an Area.\n\n char - The character to display.\n fg - The foreground color (default None).\n bg - The background color (default None).\n solid - Whether the tile is solid; True if the player cannot walk through it (default None).\n \"\"\"\n\n def __init__(self, char, fg=None, bg=None, solid=False):\n self.char = char\n self.fg = fg\n self.bg = bg\n self.solid = solid\n","sub_path":"game/tile.py","file_name":"tile.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"299646935","text":"__author__ = 'gregortaube'\n\n\n'''\ninitial letter is A. A's are transformed to B's. B's are transformed to BA's\nsince it takes TWO transoformations for one be to give ONE MORE B: B-> BA -> BAB\nand A takes ONE transformation to give ONE B. Bn = B(n-1) + B(n-2) or just Bn = B(n-1) + A(n-1)\nIt is possible to use memoization here to compute less.\nwith N transformation we will have the Nth Fibonacci number of B's.\nThe length of the strings themselves also follow the fibonacci sequence.\n\nThe correct output for this exercise will be the \"(N-1)th Nth\" fibonacci number corresponding to\n number of A and B's\n'''\n# def fibonacci(param):\n# table = {}\n# fib = 0\n# temp1 =0\n# temp2 =0\n# for x in range(param):\n# if fib == 0:\n# fib +=1\n# continue\n# temp2 = temp1\n# temp1 = fib\n# fib = temp1 +temp2\n# return fib\n\ntable = {}\ndef fibRec(n):\n # return n if n<2 else fibRec(n-1) + fibRec(n-2)\n if n in table:\n return table[n]\n else:\n table[n] = n if n < 2 else fibRec(n-2) + fibRec(n-1)\n return table[n]\n\nnumtrans = int(input())\n\nnumA = fibRec(numtrans -1)\nnumB = fibRec(numtrans)\n\n\nprint(\"%d %d\" %(numA,numB))\n\n\n\n","sub_path":"intermediate/rijeci.py","file_name":"rijeci.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"469129679","text":"# 公交线路客流量图\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\n# 指定默认字体\nmatplotlib.rcParams['font.sans-serif'] = ['SimHei']\nmatplotlib.rcParams['axes.unicode_minus'] = False\n\ndf = pd.read_excel(\"27路和49路公交线路客流量表.xlsx\", sheet_name='Sheet1', header=1)\n\nplt.figure()\nplt.plot(df['时间段'], df['27路'], linewidth='1', label=\"小明乘坐线路(27路)\", marker='o')\nplt.plot(df['时间段'], df['49路'], linewidth='1', label=\"妈妈乘坐线路(49路)\", marker='o', markersize=6)\nplt.legend(loc='best') # 图例,best:自动选择最佳位置 upper center:上部居中等\nplt.title('公交线路客流量', size=20)\nplt.xlabel(\"时间段\", size=12)\nplt.ylabel(\"客流量\", size=12)\nplt.show()\n","sub_path":"【第21课】走近数据分析①/公交线路客流量图_xlsx.py","file_name":"公交线路客流量图_xlsx.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"425516303","text":"from enum import Enum\n\nfrom . import popular_content_distributor\nfrom . import active_endpoints_distributor\n\n\nclass DistributionStrategy(Enum):\n popular_content = 1\n active_endpoints = 2\n genetic = 2\n\nclass CacheDistributor():\n @staticmethod\n def distribute(strategy, endpoints, caches, videos):\n distribution = {}\n if strategy == DistributionStrategy.popular_content:\n distribution = popular_content_distributor.distribute(endpoints, caches, videos)\n if strategy == DistributionStrategy.active_endpoints:\n distribution = active_endpoints_distributor.distribute(endpoints, caches, videos)\n\n return distribution\n","sub_path":"cache_distributors/cache_distributor.py","file_name":"cache_distributor.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"151568634","text":"#!/usr/bin/python3\n\nimport random\n\nForresterStore = {}\n\ndef Forrester3 (hist=[], score=[], query = False):\n if query:\n return [\"J3\",\"Almost done\"]\n else:\n return 'D'\n if (len(hist) == 0):\n return 'D'\n \n opponentDefects = 0\n for turn in hist:\n if str(turn[1]) == 'D':\n opponentDefects += 1 \n \n defectRate = opponentDefects/len(hist)\n \n if random.random() <= defectRate:\n return 'D'\n else:\n return 'C'\n","sub_path":"apa3/Forrester.py","file_name":"Forrester.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"173039535","text":"# -*- coding: utf-8 -*-\r\nimport math\r\nfrom datetime import datetime\r\n\r\nimport cv2\r\nimport dlib\r\nimport numpy as np\r\nfrom PIL import Image as IM\r\nfrom scipy import ndimage\r\n# --------------------------------------------------------------------------- #\r\n# Usage: python facepatches.py \r\n# --------------------------------------------------------------------------- #\r\n\r\n#---------------------------------------------------------------------------#\r\n\r\n#rescaleImg = [1.4504, 1.6943, 1.4504, 1.2065]\r\n#mpoint = [63.1902642394822, 47.2030047734627]\r\n\r\nrescaleImg = [1.4504, 1.5843, 1.4504, 1.3165]\r\nmpoint = [63.78009, 41.66620]\r\ntarget_size = 128\r\n\r\ninner_width = 1.3\r\ninner_up_height = 1.3\r\ninner_down_height = 3.2\r\ninner_face_size= (96,72)\r\n#inner_face_size= (48,36)\r\n\r\nfinalsize=(224,224)\r\n#eyelog='eyecenterlogv4.txt'\r\n\r\n'''all three patches must be the same size if they are to be concatenated in the patch network'''\r\neye_patch_size = (64, 26)\r\neye_width_height_ratio = 0.40625 #alternative 0.5-0.6 including forehead\r\nmiddle_width_height_ratio = 1.25\r\n#middle_patch_size = (32, 40)\r\nmiddle_patch_size = (64, 26)#\r\nmouth_width_height_ratio = 0.5\r\n#mouth_patch_size = (48, 24)\r\nmouth_patch_size = (64, 26)\r\n\r\n##LMP1_keys=[17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 27]\r\nLMP1_keys=[17, 19, 21, 26, 24, 22, 37, 41, 44, 46, 27]\r\nLMP1_Dists=[[37,41],[41,19],[37,19],[41,21],[37,21],[39,19],[39,21],\r\n [44,46],[44,24],[46,24],[44,22],[46,22],[42,24],[42,22]]\r\n #[21,22],[21,27],[22,27]] not helpful\r\nLMP1_triangle=[[17, 19, 21], [17, 19, 27], [27, 37, 41], [41, 19, 27], [41, 17, 21], [41, 21, 27], [17, 41, 27], \r\n [26, 24, 22], [26, 24, 27], [27, 44, 46], [46, 24, 27], [46, 26, 22], [46, 22, 27], [26, 46, 27]]\r\n#LMP1_aug=[[37,38],[37,39],[38,39],\r\n# [44,43],[44,42],[33,42]] #not helpful\r\n#LMP1_aug=[[17,19],[19,21],\r\n# [26,24],[24,22]]\r\n\r\nLMP2_keys=[4, 5, 48, 12, 11, 54, 49, 59, 51, 57, 53, 55, 62, 66] \r\nLMP2_Dists=[[51,57],[62,66],[49,59],[53,55]]\r\n #[48,49],[48,51],[49,51], not helpful\r\n #[54,53],[54,51],[53,51]] not helpful\r\n'''the order of three points in a triangle should be considered\r\n by making the outcoming triangle features share bigger variance'''\r\nLMP2_triangle=[[4, 5, 48], [12, 11, 54], [51, 57, 48], \r\n [51, 57, 54], [62, 66, 48], [62, 66, 54],\r\n [4, 5, 66], [12, 11, 66], [4, 5, 51], [12, 11, 51],\r\n [4, 5, 62], [12, 11, 62], [4, 5, 57], [12, 11, 57]]\r\n#LMP2_triangle=[[48, 5, 4], [54, 11, 12], [48, 57, 51], \r\n# [54, 57, 51], [48, 66, 62], [54, 66, 62],\r\n# [66, 5, 4], [66, 11, 12], [51, 4, 5], [51, 11, 12],\r\n# [62, 5, 4], [62, 11, 12], [57, 5, 4], [57, 11, 12]]\r\n#LMP2_aug=[[48,51], #not helpful\r\n# [54,51]]\r\n\r\n\r\ndetector = dlib.get_frontal_face_detector()\r\npredictor = dlib.shape_predictor(\"./dlibmodel/shape_predictor_68_face_landmarks.dat\")\r\n#\r\n#\r\n######### formalization the image\r\ndef __formalizeImg(in_img):\r\n return (in_img-np.mean(in_img))/np.std(in_img)\r\n\r\n#\r\n#\r\n######### get Patches images\r\ndef __getEyePatch(img, w, h, X=None, Y=None):\r\n '''Return the eye patch image from the rescaled images'''\r\n if X is None or Y is None:###use default configs for unexpected cases. this could be strongly unstable.\r\n w_patch = int(round(w*0.734375))\r\n h_patch = int(round(w_patch*eye_width_height_ratio))\r\n bry = int(round(h*0.5))\r\n tlx = int(round(w-w_patch)*0.5)\r\n brx = tlx+w_patch\r\n tly = bry-h_patch\r\n else:\r\n half_width = int(max((X[27]-(X[0]+X[17])/2), ((X[16]+X[26])/2-X[27])))\r\n w_patch = 2*half_width\r\n h_patch = int(round(w_patch*eye_width_height_ratio))\r\n\r\n bry = int(round((Y[28]+Y[29])*0.5))\r\n tly = bry - h_patch\r\n tlx = int(X[27]-half_width)\r\n brx = tlx + w_patch\r\n \r\n #patch = np.zeros((h_patch, w_patch, 3), dtype = \"uint8\")\r\n patch = np.zeros((h_patch, w_patch), dtype = \"uint8\")\r\n blxstart = 0\r\n if tlx < 0:\r\n blxstart = -tlx\r\n tlx = 0\r\n brxend = w_patch\r\n if brx > w:\r\n brxend = w + w_patch - brx#brxend=w_patch-(brx-w)\r\n brx = w\r\n btystart = 0\r\n if tly < 0:\r\n btystart = -tly\r\n tly = 0\r\n bbyend = h_patch\r\n if bry > h:\r\n bbyend = h + h_patch - bry#bbyend=h_patch-(bry-h)\r\n bry = h\r\n \r\n #patch[btystart:bbyend,blxstart:brxend,:] = img[tly:bry,tlx:brx,:]\r\n patch[btystart:bbyend,blxstart:brxend] = img[tly:bry,tlx:brx]\r\n patch = cv2.resize(patch, eye_patch_size)\r\n return patch\r\n\r\ndef __getMiddlePatch(img, w, h, X=None, Y=None):\r\n '''Return the middle patch image from the rescaled images'''\r\n if X is None or Y is None:###use default configs for unexpected cases. this could be strongly unstable.\r\n w_patch = int(round(w*0.3125))\r\n h_patch = int(round(w_patch*middle_width_height_ratio))\r\n bry = int(round(h*0.46875))\r\n tlx = int(round(w-w_patch)*0.5)\r\n brx = tlx+w_patch\r\n tly = bry-h_patch\r\n else:\r\n tlx = int(X[39])\r\n brx = int(X[42])\r\n w_patch = brx - tlx\r\n h_patch = int(round(w_patch*middle_width_height_ratio))\r\n bry = int(Y[28])\r\n tly = bry - h_patch\r\n #patch = np.zeros((h_patch, w_patch, 3), dtype = \"uint8\")\r\n patch = np.zeros((h_patch, w_patch), dtype = \"uint8\")\r\n \r\n blxstart = 0\r\n if tlx < 0:\r\n blxstart = -tlx\r\n tlx = 0\r\n brxend = w_patch\r\n if brx > w:\r\n brxend = w + w_patch - brx#brxend=w_patch-(brx-w)\r\n brx = w\r\n btystart = 0\r\n if tly < 0:\r\n btystart = -tly\r\n tly = 0\r\n bbyend = h_patch\r\n if bry > h:\r\n bbyend = h + h_patch - bry#bbyend=h_patch-(bry-h)\r\n bry = h\r\n #patch[btystart:bbyend,blxstart:brxend,:] = img[tly:bry,tlx:brx,:]\r\n patch[btystart:bbyend,blxstart:brxend] = img[tly:bry,tlx:brx]\r\n patch = cv2.resize(patch, middle_patch_size)\r\n return patch\r\n\r\ndef __getMouthPatch(img, w, h, X=None, Y=None):\r\n '''Return the mouth patch image from the rescaled images'''\r\n if X is None or Y is None:###use default configs for unexpected cases. this could be strongly unstable.\r\n w_patch = int(round(w*0.5))\r\n h_patch = int(round(w_patch*mouth_width_height_ratio))\r\n bry = int(round(h*0.671875))\r\n tlx = int(round(w-w_patch)*0.5)\r\n brx = tlx+w_patch\r\n tly = bry-h_patch\r\n else:\r\n h_patch = int(round(Y[8]-Y[33]))\r\n w_patch = int(h_patch/mouth_width_height_ratio)\r\n tly = int(Y[33])\r\n bry = tly + h_patch\r\n tlx = int(X[33]-w_patch/2)\r\n brx = tlx + w_patch\r\n #patch = np.zeros((h_patch, w_patch, 3), dtype = \"uint8\")\r\n patch = np.zeros((h_patch, w_patch), dtype = \"uint8\")\r\n\r\n blxstart = 0\r\n if tlx < 0:\r\n blxstart = -tlx\r\n tlx = 0\r\n brxend = w_patch\r\n if brx > w:\r\n brxend = w + w_patch - brx#brxend=w_patch-(brx-w)\r\n brx = w\r\n btystart = 0\r\n if tly < 0:\r\n btystart = -tly\r\n tly = 0\r\n bbyend = h_patch\r\n if bry > h:\r\n bbyend = h + h_patch - bry#bbyend=h_patch-(bry-h)\r\n bry = h\r\n #patch[btystart:bbyend,blxstart:brxend,:] = img[tly:bry,tlx:brx,:]\r\n patch[btystart:bbyend,blxstart:brxend] = img[tly:bry,tlx:brx]\r\n patch = cv2.resize(patch, mouth_patch_size)\r\n return patch\r\n\r\n######\r\n#\r\n#return the innerface with the inner_face_size defined at the start of this file\r\ndef __getInnerFace(img, w, h):\r\n '''Return the innerface with the inner_face_size defined at the start of this page.\r\n you need to change the operation before resize() to get the different types of innerface'''\r\n #tly = 16\r\n #tlx = 28\r\n #h_patch = 96\r\n #w_patch =72\r\n #brx = tlx+w_patch\r\n #bry = tly+h_patch\r\n #patch = np.zeros((h_patch, w_patch), dtype = \"uint8\")\r\n \r\n #blxstart = 0\r\n #if tlx < 0:\r\n # blxstart = -tlx\r\n # tlx = 0\r\n #brxend = w_patch\r\n #if brx > w:\r\n # brxend = w + w_patch - brx#brxend=w_patch-(brx-w)\r\n # brx = w\r\n #btystart = 0\r\n #if tly < 0:\r\n # btystart = -tly\r\n # tly = 0\r\n #bbyend = h_patch\r\n #if bry > h:\r\n # bbyend = h + h_patch - bry#bbyend=h_patch-(bry-h)\r\n # bry = h\r\n #patch[btystart:bbyend,blxstart:brxend] = img[tly:bry,tlx:brx]\r\n\r\n '''change the method down here'''\r\n #patch=__weberface(patch,revers=True) #reverse version\r\n patch=img[:,:]\r\n patch=__weberface(patch)\r\n #patch=patch*1.25#25% up\r\n #patch=np.clip(patch,1,255)#clip the values into [1,255]\r\n\r\n #patch=__ELTFS(patch)\r\n '''change the method up here to get the innerface that you want'''\r\n\r\n #patch=cv2.resize(patch,inner_face_size)\r\n\r\n return patch\r\n############### innerface operation ends here\r\n\r\n######\r\n#\r\n#weber face operation for normalizing the images' illuminations\r\nweber_sigma=0.85#0.6\r\ndef __weberface(image, weberface_sigma=weber_sigma, revers=False):\r\n ''' when revers is true, the return image is set to the reverse version.\r\n the revers defaut value is False'''\r\n imgr=cv2.copyMakeBorder(image,1,1,1,1, cv2.BORDER_REPLICATE)\r\n imgr=imgr/255.0\r\n imf1 = ndimage.filters.gaussian_filter(imgr, weberface_sigma)\r\n lx, ly = imgr.shape\r\n imfc = imf1[1:(lx - 1), 1:(ly - 1)]\r\n imflu = imf1[0:(lx - 2), 0:(ly - 2)]\r\n imflb = imf1[0:(lx - 2), 2:ly]\r\n imfru = imf1[2:lx, 0:(ly - 2)]\r\n imfrb = imf1[2:lx, 2:ly]\r\n constc = 0.01\r\n weber_face_in = (4 * imfc - imflu - imflb - imfru - imfrb) / (imfc + constc)\r\n out = np.arctan(weber_face_in)\r\n if revers:\r\n out = 1-out\r\n else:\r\n out = out+1\r\n maxv=np.max(out)\r\n minv=np.min(out)\r\n out=255*(out-minv)/(maxv-minv)\r\n #out=out*1.25\r\n #np.clip(out, 1, 255,out)\r\n return out\r\n############weber face operation ends here\r\n\r\n##\r\n#\r\n#The followings are operations for Enhance Local Texture Feature Set\r\ndef __normalizeImage(x):\r\n max1 = np.max(x)\r\n min1 = np.min(x)\r\n x=np.asarray(x)\r\n x=(x-min1)/(max1-min1)*255\r\n return x\r\ndef __Gamma(x): #第一步:伽马校正\r\n max1 = np.max(x)\r\n x2 = np.power(x/max1, 0.4)\r\n x2 = x2*max1\r\n return x2\r\ndef __DOG(x): #第二步:高斯差分\r\n blur1 = cv2.GaussianBlur(x, (0, 0), 1.0);\r\n blur2 = cv2.GaussianBlur(x, (0, 0), 2.0);\r\n dog = blur1 - blur2\r\n return dog\r\ndef __constrast_equlization(x2): #第三步: 对比均衡化\r\n tt = 10\r\n a = 0.1\r\n x_temp = np.power(abs(x2), a)\r\n mm = np.mean(x_temp)\r\n x2 = x2 / (mm ** (1 / a))\r\n # 第三步第一个公式完成\r\n\r\n for i in range(x2.shape[0]):\r\n for j in range(x2.shape[1]):\r\n x_temp[i, j] = min(tt, (abs(x2[i, j])))**a\r\n\r\n mm = np.mean(x_temp)\r\n x2 = x2 / (mm ** (1 / a))\r\n x2 = tt*np.tanh(x2/tt)\r\n\r\n return x2\r\n # 第三步第二个公式完成\r\n##Enhance local texture feature set\r\ndef __ELTFS(img, blur=0): #整合前面三步,对图像x进行处理\r\n x = __Gamma(img) # Gramma\r\n x = __DOG(x) # __DOG\r\n x = __constrast_equlization(x) # __constrast_equlization\r\n\r\n x = __normalizeImage(x)\r\n if blur>0:\r\n x = cv2.medianBlur(np.uint8(x), blur)\r\n x = __normalizeImage(x)\r\n\r\n return x\r\n########The Enhance Local Texture Feature Set operations end here\r\n\r\n######\r\n#\r\n#the following functions are for geometry feature extractions\r\ndef __getDistFrom3PTS(x1, y1, x2, y2, x3, y3):\r\n '''get the Euclidean distance of p1 and the center of p2 and p3'''\r\n return math.sqrt((x1-0.5*(x2+x3))**2+(y1-0.5*(y2+y3))**2)\r\n\r\ndef __getD(x1,y1,x2,y2):\r\n '''get the Euclidean distance of p1 and p2'''\r\n return math.sqrt((x1-x2)**2+(y1-y2)**2)\r\n\r\ndef __getTriangleFeatures(X, Y, triangles):\r\n '''Return the triangleFeatures of ratios among lengths of middle lines'''\r\n tri_feat=[]\r\n for i in range(len(triangles)):\r\n m1=__getDistFrom3PTS(X[triangles[i][0]], Y[triangles[i][0]], \r\n X[triangles[i][1]], Y[triangles[i][1]], \r\n X[triangles[i][2]], Y[triangles[i][2]])\r\n m2=__getDistFrom3PTS(X[triangles[i][1]], Y[triangles[i][1]], \r\n X[triangles[i][0]], Y[triangles[i][0]], \r\n X[triangles[i][2]], Y[triangles[i][2]])\r\n m3=__getDistFrom3PTS(X[triangles[i][2]], Y[triangles[i][2]], \r\n X[triangles[i][1]], Y[triangles[i][1]], \r\n X[triangles[i][0]], Y[triangles[i][0]])\r\n if m1>0:\r\n tri_feat.append(m2/m1)\r\n tri_feat.append(m3/m1)\r\n else:\r\n tri_feat.append(m2*1.41421356)#minimun distance in integer pixels is sqrt(0.5)\r\n tri_feat.append(m3*1.41421356)#minimun distance in integer pixels is sqrt(0.5)\r\n return tri_feat\r\n\r\ndef __getEDList(X, Y, keyPs):\r\n '''Return the Euclidean distances list of the keypoints keyPs'''\r\n ed=[]\r\n for i in keyPs:\r\n ed.append(__getD(X[i[0]],Y[i[0]],\r\n X[i[1]],Y[i[1]]))\r\n return ed\r\n\r\ndef __getDirectionalXY(X, Y, keyPs):\r\n dxy=[]\r\n for v in keyPs:\r\n dxy.append(X[v[1]]-X[v[0]])\r\n dxy.append(Y[v[1]]-Y[v[0]])\r\n return dxy\r\n\r\ndef __getXYcor(X, Y):\r\n xc=X[17:]-X[27]\r\n yc=Y[17:]-Y[27]\r\n xc=xc/np.std(xc)\r\n yc=yc/np.std(yc)\r\n #xc=list(xc[0:10])+list(xc[19:])#85.88\r\n #yc=list(yc[0:10])+list(yc[19:])#85.88\r\n #xc=list(xc[19:])#85.725\r\n #yc=list(yc[19:])#85.725\r\n #xc=list(xc[17:27])+list(xc[36:])#87.0875\r\n #yc=list(yc[17:27])+list(yc[36:])#87.0875\r\n return list(xc),list(yc)\r\n\r\ndef __landmarkPart1(X, Y, stdxy):\r\n '''Return Part1(eyes part) features'''\r\n part1=[]\r\n tx= (X[39]+X[42])*0.25+X[27]*0.5\r\n ty= (Y[39]+Y[42])*0.25+Y[27]*0.5\r\n centx=(tx+X[28])*0.5\r\n centy=(ty+Y[28])*0.5\r\n #sme=math.sqrt((centx-X[27])**2+(centy-Y[27])**2)\r\n sme=(centx-X[27])**2+(centy-Y[27])**2#137\r\n part1.append((centx-tx)/sme)\r\n part1.append((centy-ty)/sme)\r\n for i in range(len(LMP1_keys)):\r\n part1.append((centx-X[LMP1_keys[i]])/sme)\r\n part1.append((centy-Y[LMP1_keys[i]])/sme)\r\n #tri_features1=np.asarray(__getTriangleFeatures(X, Y, LMP1_triangle))#testing\r\n #tri_features1=list(tri_features1/np.std(tri_features1))#not helpful\r\n tri_features1=list(np.asarray(__getTriangleFeatures(X, Y, LMP1_triangle))/stdxy)\r\n eud1=list(np.asarray(__getEDList(X, Y,LMP1_Dists))/stdxy)\r\n return part1, tri_features1, eud1#Dimension: 24, 28, 10\r\n\r\ndef __landmarkPart2(X, Y, stdxy):\r\n '''Return Part2(mouth part) features'''\r\n centx= (X[33]+X[51])*0.5\r\n centy= (Y[33]+Y[51])*0.5\r\n #sme=math.sqrt((centx-X[33])**2+(centy-Y[33])**2)\r\n sme=(centx-X[33])**2+(centy-Y[33])**2#137\r\n part2=[]\r\n for i in range(len(LMP2_keys)):\r\n part2.append((centx-X[LMP2_keys[i]])/sme)\r\n part2.append((centy-Y[LMP2_keys[i]])/sme)\r\n #tri_features2=np.asarray(__getTriangleFeatures(X, Y, LMP2_triangle))#testing\r\n #tri_features2=list(tri_features2/np.std(tri_features2))# not helpful\r\n tri_features2=list(np.asarray(__getTriangleFeatures(X, Y, LMP2_triangle))/stdxy)#testing\r\n eud2=list(np.asarray(__getEDList(X, Y,LMP2_Dists))/stdxy)\r\n return part2, tri_features2, eud2#Dimension: 28, 28, 4\r\n\r\n#def __LandmarkFeaturesV1(X, Y):\r\n# stdxy=np.std(X)+np.std(Y)\r\n# part1, tri_f1, ed1=__landmarkPart1(X, Y, stdxy)\r\n# part2, tri_f2, ed2=__landmarkPart2(X, Y, stdxy)\r\n# features=part1+part2+tri_f1+tri_f2+ed1+ed2\r\n# return features#Dimension: 122 = 24 + 28 + 28 + 28 + 10 + 4\r\n\r\ndef __LandmarkFeaturesV2(X, Y):\r\n stdxy=np.std(X)+np.std(Y)\r\n part1, tri_f1, ed1=__landmarkPart1(X, Y, stdxy)\r\n part2, tri_f2, ed2=__landmarkPart2(X, Y, stdxy)\r\n x, y = __getXYcor(X, Y)\r\n features=part1+part2+tri_f1+tri_f2+ed1+ed2+x+y\r\n print('Geometry feature length: %d'%len(features))\r\n return features\r\n\r\n\r\ndef __getLandmarkFeatures(X, Y):###\r\n #return __LandmarkFeaturesV1(X, Y)#Dimension: 122 = 24 + 28 + 28 + 28 + 10 + 4\r\n return __LandmarkFeaturesV2(X, Y)#Dimension: 258 = 24 + 28 + 28 + 28 + 10 + 4 + 68 + 68\r\n##########The above functions are for geometry feature extractions\r\n\r\ndef __UnifiedOutputs(rescaleImg, Geof, Geo_features, Patchf, eyepatch, foreheadpatch, mouthpatch, innerface):\r\n ''''add additional operations'''\r\n ##rescale to 224x224 from 128x128\r\n #rescaleImg=cv2.resize(rescaleImg, finalsize)\r\n\r\n #if Patchf:\r\n # #rescale to 224x224 from 128x128\r\n # innerface=cv2.resize(innerface, finalsize)\r\n\r\n return rescaleImg, Geof, Geo_features, Patchf, eyepatch, foreheadpatch, mouthpatch, innerface\r\n #return (__formalizeImg(rescaleImg), Geof, Geo_features, Patchf, __formalizeImg(eyepatch), \r\n # __formalizeImg(foreheadpatch), __formalizeImg(mouthpatch), __formalizeImg(innerface))\r\n\r\ndef __genLMFandIP(img, w, h, LM, Patches, regular=False, X=None, Y=None):\r\n \"\"\"Return the Geometry features from landmarks and Images patches.\r\n If regularize is set to False, it will always return cosine True and three images for the patches operation.\r\n Otherwise, it could return cosine False and four None values\"\"\"\r\n if LM or Patches:\r\n if X is None or Y is None:\r\n #pl.write(' 0\\n')\r\n print(\">>>***%%%Warning [__genLMFandIP()]: No face was detected in the image.\")\r\n if not LM:\r\n if regular:\r\n print(\">>>***%%%Warning [__genLMFandIP()]: Processing the default config on the image\")\r\n \r\n eye_patch = __getEyePatch(img, w, h)\r\n forehead_patch = __getMiddlePatch(img, w, h)\r\n mouth_patch = __getMouthPatch(img, w, h)\r\n inner_face = __getInnerFace(img, w, h)\r\n\r\n return __UnifiedOutputs(img, False, None, True, eye_patch, forehead_patch, mouth_patch, inner_face)\r\n else:\r\n print(\">>>***%%%Warning [__genLMFandIP()]: Return img, False, None, False, None, None, None, None\")\r\n return img, False, None, False, None, None, None, None\r\n elif not Patches:\r\n return __UnifiedOutputs(img, False, None, False, None, None, None, None)\r\n else:\r\n eye_patch = __getEyePatch(img, w, h)\r\n forehead_patch = __getMiddlePatch(img, w, h)\r\n mouth_patch = __getMouthPatch(img, w, h)\r\n inner_face = __getInnerFace(img, w, h)\r\n\r\n return __UnifiedOutputs(img, False, None, True, eye_patch, forehead_patch, mouth_patch, inner_face)\r\n \r\n if not LM:\r\n eye_patch = __getEyePatch(img, w, h, X, Y)\r\n forehead_patch = __getMiddlePatch(img, w, h, X, Y)\r\n mouth_patch = __getMouthPatch(img, w, h, X, Y)\r\n inner_face = __getInnerFace(img, w, h)\r\n\r\n return __UnifiedOutputs(img, False, None, True, eye_patch, forehead_patch, mouth_patch, inner_face)\r\n elif not Patches:\r\n landmark_features= __getLandmarkFeatures(X, Y)\r\n\r\n return __UnifiedOutputs(img, True, landmark_features, False, None, None, None, None)\r\n else:\r\n eye_patch = __getEyePatch(img, w, h, X, Y)\r\n forehead_patch = __getMiddlePatch(img, w, h, X, Y)\r\n mouth_patch = __getMouthPatch(img, w, h, X, Y)\r\n landmark_features= __getLandmarkFeatures(X, Y)\r\n inner_face = __getInnerFace(img, w, h)\r\n\r\n return __UnifiedOutputs(img, True, landmark_features, True, eye_patch, forehead_patch, mouth_patch, inner_face)\r\n else:\r\n return __UnifiedOutputs(img, False, None, False, None, None, None, None)\r\n\r\ndef __cropImg(img, shape=None, LM=False, Patches=False, regularize=False, trg_size=target_size, rescale=rescaleImg):\r\n \"\"\"Rescale, adjust, and crop the images.\r\n If shape is None, it will recale the img without croping and return __genLMFandIP\"\"\"\r\n if not shape==None:\r\n nLM = shape.num_parts\r\n lms_x = np.asarray([shape.part(i).x for i in range(0,nLM)])\r\n lms_y = np.asarray([shape.part(i).y for i in range(0,nLM)])\r\n\r\n tlx = float(min(lms_x))#top left x\r\n tly = float (min(lms_y))#top left y\r\n ww = float (max(lms_x) - tlx)\r\n hh = float(max(lms_y) - tly)\r\n # Approximate LM tight BB\r\n h = img.shape[0]\r\n w = img.shape[1]\r\n cx = tlx + ww/2\r\n cy = tly + hh/2\r\n #tsize = max(ww,hh)/2\r\n tsize = ww/2\r\n\r\n # Approximate expanded bounding box\r\n btlx = int(round(cx - rescale[0]*tsize))\r\n btly = int(round(cy - rescale[1]*tsize))\r\n bbrx = int(round(cx + rescale[2]*tsize))\r\n bbry = int(round(cy + rescale[3]*tsize))\r\n nw = int(bbrx-btlx)\r\n nh = int(bbry-btly)\r\n\r\n #adjust relative location\r\n x0=(np.mean(lms_x[36:42])+np.mean(lms_x[42:48]))/2\r\n y0=(np.mean(lms_y[36:42])+np.mean(lms_y[42:48]))/2\r\n Mpx=int(round((mpoint[0]*nw/float(target_size))-x0+btlx))\r\n Mpy=int(round((mpoint[1]*nh/float(target_size))-y0+btly))\r\n btlx=btlx-Mpx\r\n bbrx=bbrx-Mpx\r\n bbry=bbry-Mpy\r\n btly=btly-Mpy\r\n print('coordinate adjustment')\r\n print(Mpx, Mpy)\r\n Xa=np.round((lms_x-btlx)*trg_size/nw)\r\n Ya=np.round((lms_y-btly)*trg_size/nh)\r\n \r\n #few=open(eyelog,'a')\r\n #few.write('%lf %lf\\n'%((np.mean(Xa[36:42])+np.mean(Xa[42:48]))/2,(np.mean(Ya[36:42])+np.mean(Ya[42:48]))/2))\r\n #few.close()\r\n\r\n imcrop = np.zeros((nh,nw), dtype = \"uint8\")\r\n\r\n blxstart = 0\r\n if btlx < 0:\r\n blxstart = -btlx\r\n btlx = 0\r\n brxend = nw\r\n if bbrx > w:\r\n brxend = w+nw - bbrx#brxend=nw-(bbrx-w)\r\n bbrx = w\r\n btystart = 0\r\n if btly < 0:\r\n btystart = -btly\r\n btly = 0\r\n bbyend = nh\r\n if bbry > h:\r\n bbyend = h+nh - bbry#bbyend=nh-(bbry-h)\r\n bbry = h\r\n imcrop[btystart:bbyend, blxstart:brxend] = img[btly:bbry, btlx:bbrx]\r\n im_rescale=cv2.resize(imcrop,(trg_size, trg_size))\r\n return __genLMFandIP(im_rescale, trg_size, trg_size, LM, Patches, regular=regularize, X=Xa, Y=Ya)\r\n else:\r\n im_rescale=cv2.resize(img, (trg_size, trg_size))\r\n return __genLMFandIP(im_rescale, trg_size, trg_size, LM, Patches, False)\r\n\r\ndef getLandMarkFeatures_and_ImgPatches(img, withLM=True, withPatches=True, fromfacedataset=False):\r\n \"\"\"Input:\r\n img: image to be processed.\r\n withLM: flag indicates whether to process the landmark operations or not.\r\n withPatches: flag indicates whether to process the patches operations or not.\r\n fromfacedataset: flag whether the image is from cosine regular face dataset.\r\n If fromfacedataset is set to True, always return an img.\r\n \r\nOutputs: \r\n rescaleimg, lmf, lmfeat, pf, eyeP, middleP, mouthP\r\n \r\n rescaleimg: the rescale image of the input img\r\n \r\n lmf: landmark flag. If True means landmarks were detected in the images. If False means no landmarks were detected.\r\n lmfeat: landmark features. If lmf is True, it is cosine ndarray, otherwise it is cosine None value.\r\n \r\n pf: patches flag, signal whether valid patches are return or not.\r\n eyeP: if pf is True, it's cosine patch image of img, otherwise it's cosine None value.\r\n middleP: if pf is True, it's cosine patch image of img, otherwise it's cosine None value.\r\n mouthP: if pf is True, it's cosine patch image of img, otherwise it's cosine None value.\r\n \"\"\"\r\n if len(img.shape) == 3 and img.shape[2]==3:\r\n g_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n else:\r\n g_img = img\r\n\r\n f_ds=detector(g_img, 1)\r\n RT=[]\r\n if len(f_ds) == 0:\r\n #pl.write('0')\r\n print(\">>>***%%%Warning [getLandMarkFeatures_and_ImgPatches()]: No face was detected from the image\")\r\n if not fromfacedataset:\r\n print(\">>>***%%%Warning [getLandMarkFeatures_and_ImgPatches()]: No face was detected, and return False and None values\")\r\n return RT\r\n else:\r\n print(\">>>***%%%Warning [getLandMarkFeatures_and_ImgPatches()]: Processing the default config on the image\")\r\n return __cropImg(g_img, LM=withLM, Patches=withPatches, regularize=fromfacedataset)\r\n\r\n \r\n for i in range(len(f_ds)):\r\n f_shape = predictor(g_img, f_ds[i])\r\n top=[]\r\n top.append((f_ds[i].left(),f_ds[i].top()))\r\n top.append((f_ds[i].right(),f_ds[i].bottom()))\r\n rescaleimg, gf, geo_features, pf, eyepatch, foreheadpatch, mouthpatch, innerface=__cropImg(g_img, shape=f_shape, LM=withLM, Patches=withPatches, regularize=fromfacedataset)\r\n RT.append((rescaleimg, gf, geo_features, pf, eyepatch, foreheadpatch, mouthpatch, innerface, top))\r\n return RT\r\n######\r\n#\r\n#The followings are for calibrate the image\r\ndef __RotateTranslate(image, angle, center =None, new_center =None, resample=IM.BICUBIC):\r\n '''Rotate the image according to the angle'''\r\n if center is None: \r\n return image.rotate(angle=angle, resample=resample) \r\n nx,ny = x,y = center \r\n if new_center: \r\n (nx,ny) = new_center \r\n cosine = math.cos(angle) \r\n sine = math.sin(angle) \r\n c = x-nx*cosine-ny*sine \r\n d =-sine \r\n e = cosine\r\n f = y-nx*d-ny*e \r\n return image.transform(image.size, IM.AFFINE, (cosine,sine,c,d,e,f), resample=resample)\r\ndef __RotaFace(image, eye_left=(0,0), eye_right=(0,0)):\r\n '''Rotate the face according to the eyes'''\r\n # get the direction from two eyes\r\n eye_direction = (eye_right[0]- eye_left[0], eye_right[1]- eye_left[1])\r\n # calc rotation angle in radians\r\n rotation =-math.atan2(float(eye_direction[1]),float(eye_direction[0]))\r\n # rotate original around the left eye \r\n image = __RotateTranslate(image, center=eye_left, angle=rotation)\r\n return image\r\ndef __shape_to_np(shape):\r\n '''Transform the shape points into numpy array of 68*2'''\r\n nLM = shape.num_parts\r\n x = np.asarray([shape.part(i).x for i in range(0,nLM)])\r\n y = np.asarray([shape.part(i).y for i in range(0,nLM)])\r\n return x,y\r\ndef calibrateImge(imgpath):\r\n '''Calibrate the image of the face'''\r\n imgcv_gray=cv2.imread(imgpath, cv2.IMREAD_GRAYSCALE)\r\n if imgcv_gray is None:\r\n print('Unexpected ERROR: The value read from the imagepath is None. No image was loaded')\r\n exit(-1)\r\n dets = detector(imgcv_gray,1)\r\n if len(dets)==0:\r\n print(\"No face was detected^^^^^^^^^^^^^^\")\r\n return False, imgcv_gray\r\n lmarks=[]\r\n for id, det in enumerate(dets):\r\n if id > 0:\r\n print(\"ONLY process the first face>>>>>>>>>\")\r\n break\r\n shape = predictor(imgcv_gray, det)\r\n x, y = __shape_to_np(shape)\r\n lmarks = np.asarray(lmarks, dtype='float32')\r\n pilimg=IM.fromarray(imgcv_gray)\r\n rtimg=__RotaFace(pilimg, eye_left=(np.mean(x[36:42]),np.mean(y[36:42])),\r\n eye_right=(np.mean(x[42:48]),np.mean(y[42:48])))\r\n imgcv_gray=np.array(rtimg)\r\n return True, imgcv_gray\r\n\r\n\r\n\r\n### system module\r\ncrop_size=0.7\r\ndef __getLandMarkFeatures_and_ImgPatches_for_Facelist(img_list, withLM=True, withPatches=True):\r\n \"\"\"Input:\r\n img_list: face image list to be processed.\r\n withLM: flag indicates whether to process the landmark operations or not.\r\n withPatches: flag indicates whether to process the patches operations or not.\r\n fromfacedataset: flag whether the image is from cosine regular face dataset.\r\n If fromfacedataset is set to True, always return an img.\r\n \r\nOutputs: \r\n rescaleimg, lmf, lmfeat, pf, eyeP, middleP, mouthP\r\n \r\n rescaleimg: the rescale image of the input img\r\n \r\n lmf: landmark flag. If True means landmarks were detected in the images. If False means no landmarks were detected.\r\n lmfeat: landmark features. If lmf is True, it is cosine ndarray, otherwise it is cosine None value.\r\n \r\n pf: patches flag, signal whether valid patches are return or not.\r\n eyeP: if pf is True, it's cosine patch image of img, otherwise it's cosine None value.\r\n middleP: if pf is True, it's cosine patch image of img, otherwise it's cosine None value.\r\n mouthP: if pf is True, it's cosine patch image of img, otherwise it's cosine None value.\r\n \"\"\"\r\n RT=[]\r\n for img in img_list:\r\n if len(img.shape) == 3 and img.shape[2]==3:\r\n g_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n else:\r\n g_img = img\r\n\r\n f_ds=detector(g_img, 1)\r\n if len(f_ds) == 0:\r\n #pl.write('0')\r\n print(\">>>***%%%Warning [getLandMarkFeatures_and_ImgPatches()]: No face was detected, and return None values\")\r\n RT.append(None)\r\n else:\r\n max_area=0\r\n for i in range(len(f_ds)):\r\n f_shape = predictor(g_img, f_ds[i])\r\n curr_area = (f_ds[i].right()-f_ds[i].left()) * (f_ds[i].bottom()-f_ds[i].top())\r\n if curr_area > max_area:\r\n max_area = curr_area\r\n rescaleimg, gf, geo_features, pf, eyepatch, foreheadpatch, mouthpatch, innerface=__cropImg(g_img, shape=f_shape, LM=withLM, Patches=withPatches, regularize=False)\r\n RT.append((rescaleimg, gf, geo_features, pf, eyepatch, foreheadpatch, mouthpatch, innerface))\r\n return RT\r\n\r\ndef __calibrateImageWithArrayInput(img):\r\n '''Calibrate the image of the face'''\r\n if img is None:\r\n print('Unexpected ERROR: The value input is None. No image was loaded')\r\n return False, None, None\r\n if len(img.shape)==3:\r\n imgcv_gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n elif len(img.shape)==2:\r\n imgcv_gray=img[:]\r\n else:\r\n print('ERROR: Unexpected data format.')\r\n return False, None\r\n dets = detector(imgcv_gray,1)\r\n img_face_list=[]\r\n rectPoint=[]\r\n if len(dets)==0:\r\n print(\"No face was detected^^^^^^^^^^^^^^\")\r\n return False, img_face_list, rectPoint\r\n h=imgcv_gray.shape[0]\r\n w=imgcv_gray.shape[1]\r\n for id, det in enumerate(dets):\r\n shape = predictor(imgcv_gray, det)\r\n x, y = __shape_to_np(shape)\r\n top=[]\r\n top.append((det.left(),det.top()))\r\n top.append((det.right(),det.bottom()))\r\n rectPoint.append(top)\r\n\r\n #crop face\r\n tlx=float(min(x))\r\n tly=float(min(y))\r\n ww=float(max(x)-tlx)\r\n hh=float(max(y)-tly)\r\n cx=tlx+ww/2\r\n cy=tly+hh/2\r\n tsize=ww*crop_size\r\n # Approximate expanded bounding box\r\n btlx = int(round(cx - rescaleImg[0]*tsize))\r\n btly = int(round(cy - rescaleImg[1]*tsize))\r\n bbrx = int(round(cx + rescaleImg[2]*tsize))\r\n bbry = int(round(cy + rescaleImg[3]*tsize))\r\n nw = int(bbrx-btlx)\r\n nh = int(bbry-btly)\r\n imcrop = np.zeros((nh,nw), dtype = \"uint8\")\r\n x = x - btlx\r\n y = y - btly\r\n blxstart = 0\r\n if btlx < 0:\r\n blxstart = -btlx\r\n btlx = 0\r\n brxend = nw\r\n if bbrx > w:\r\n brxend = w+nw - bbrx#brxend=nw-(bbrx-w)\r\n bbrx = w\r\n btystart = 0\r\n if btly < 0:\r\n btystart = -btly\r\n btly = 0\r\n bbyend = nh\r\n if bbry > h:\r\n bbyend = h+nh - bbry#bbyend=nh-(bbry-h)\r\n bbry = h\r\n imcrop[btystart:bbyend, blxstart:brxend] = imgcv_gray[btly:bbry, btlx:bbrx]\r\n pilimg=IM.fromarray(imcrop)\r\n rtimg=__RotaFace(pilimg, eye_left=(np.mean(x[36:42]),np.mean(y[36:42])),\r\n eye_right=(np.mean(x[42:48]),np.mean(y[42:48])))\r\n img_face_list.append(np.array(rtimg))\r\n\r\n return True, img_face_list, rectPoint\r\n\r\ndef preprocessImage(img):\r\n \"\"\"process image as input for model, extract all human faces in the image and their corresponding coordinate points\r\n \r\n Args:\r\n img (ndarray): input image represent in numpy.ndarray\r\n \r\n Returns: a dictionnary contains the following information\r\n detected(boolean): bool type to indicates whether the there are human faces in the input\r\n rescaleimg(list of ndarray): a list of rescaled and cropped image of the detected face\r\n originalPoints(list of tuple): a list tuple corresponding to rescaleimg, each tuple contains tow points that represent human faces\r\n gf: bool type for geometry features flag, indicating whether there would be meaning values in geo_features or a just a None value\r\n geo_features: geometryf features or None value\r\n pf: bool type indicates whether the following features are meaningful or meaningless\r\n eyepatch: eye patch of the recaleimg\r\n foreheadpatch: forehead patch of the rescaleimg\r\n mouthpatch: mouthpatch of the rescaleimg\r\n innerface: croped face from the rescaleimg\r\n \"\"\"\r\n crop_part = ((500, 1450), (1500, 2000)) # 4000 * 3000\r\n crop_part = ((120, 1050), (1400, 1700)) # 3072 * 2048\r\n cropped = False\r\n left_top, right_bottom = crop_part\r\n\r\n r, c, ch = img.shape\r\n if r >= right_bottom[0] and c >= right_bottom[1]:\r\n cropped = True\r\n print('cropping image........')\r\n img = img[left_top[0] : right_bottom[0], left_top[1] : right_bottom[1], :]\r\n # cv2.imwrite('./crop_imgs/crop_{0}.jpeg'.format(datetime.now().strftime(\"%Y%m%d%H%M%S\")), img)\r\n \r\n # pack the features and return \r\n features = {}\r\n detected, face_list, originalPoints = __calibrateImageWithArrayInput(img)\r\n features['detected'] = detected\r\n if detected: # detect human face\r\n processedFeature = __getLandMarkFeatures_and_ImgPatches_for_Facelist(face_list, False, False)\r\n \r\n rescaleimg, detectedOriginalPoints = [], []\r\n for i in range(len(processedFeature)):\r\n if processedFeature[i]:\r\n # order of features\r\n # rescaleimg, gf, geo_features, pf, eyepatch, foreheadpatch, mouthpatch, innerface, rotatedPoints \r\n rescaleimg.append(processedFeature[i][0].reshape(1, 128, 128, 1))\r\n detectedOriginalPoints.append(originalPoints[i])\r\n\r\n print('detect {0} human faces'.format(len(detectedOriginalPoints)))\r\n \r\n # save the cropped image\r\n # print('cropping img with face to shape {0}'.format(img.shape))\r\n # cv2.imwrite('./crop_imgs/crop_{0}.jpeg'.format(datetime.now().strftime(\"%Y%m%d%H%M%S\")), img)\r\n\r\n # if cropping image, move the square surrounding human face to the right place \r\n if cropped:\r\n tmp = []\r\n for face in detectedOriginalPoints:\r\n modified_left_top = (face[0][0] + left_top[1], face[0][1] + left_top[0])\r\n modified_right_bottom = (face[1][0] + left_top[1], face[1][1] + left_top[0])\r\n tmp.append((modified_left_top, modified_right_bottom))\r\n detectedOriginalPoints = tmp\r\n \r\n assert len(rescaleimg) == len(detectedOriginalPoints), 'the number of human faces do not equal the number of face points'\r\n features['rescaleimg'] = rescaleimg\r\n features['originalPoints'] = detectedOriginalPoints\r\n return features\r\n \r\n\r\nif __name__ == '__main__':\r\n test_image = './test_imgs/test_multiface.jpg'\r\n preprocessImage(cv2.imread(test_image))\r\n","sub_path":"FaceProcessUtilMultiFaces.py","file_name":"FaceProcessUtilMultiFaces.py","file_ext":"py","file_size_in_byte":35827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"47995094","text":"import unittest, os, warnings, pmock\n\nfrom pywebmvc.framework.core import *\nfrom pywebmvc.framework.util import *\nfrom pywebmvc.framework import metadata\nfrom pywebmvc.unittest.testutils import *\n\n\nclass Dummy(object):\n pass\n\nclass PyWebMvcObjectTestCase(PyWebMvcTestCase):\n def testReload(self):\n class Foo(PyWebMvcObject):\n def foo(self):\n return \"foo\"\n\n fu = Foo()\n self.assertEquals(fu.foo(), \"foo\")\n\n class Foo(PyWebMvcObject):\n def foo(self):\n return \"bar\"\n\n self.assertEquals(fu.foo(), \"bar\")\n\nclass MultiDictTestCase(PyWebMvcTestCase):\n def testMultiDictWithOneValue(self):\n d = MultiDict()\n d[\"a\"] = 1\n d[\"b\"] = 2\n self.assertEquals(d[\"a\"],1)\n self.assertEquals(d[\"b\"],2)\n keyErrorRaised = False\n try:\n d[\"c\"]\n except KeyError:\n keyErrorRaised = True\n self.assertTrue(keyErrorRaised)\n def testMultiDictWithManyValues(self):\n d = MultiDict()\n d[\"a\"] = 1\n d[\"b\"] = 2\n d[\"a\"] = 3\n self.assertTrue(1 in d[\"a\"])\n self.assertTrue(3 in d[\"a\"])\n self.assertEquals(d[\"b\"],2)\n del d[\"b\"]\n keyErrorRaised = False\n try:\n d[\"b\"]\n except KeyError:\n keyErrorRaised = True\n self.assertTrue(keyErrorRaised)\n\nclass TabIndexTableTestCase(PyWebMvcTestCase):\n def testImplicit(self):\n table = TabIndexTable()\n table.add(\"a\")\n table.add(\"b\")\n table.add(\"c\")\n self.assertEquals(table.lookup(\"a\"),1)\n self.assertEquals(table.lookup(\"b\"),2)\n self.assertEquals(table.lookup(\"c\"),3)\n def testExplicit(self):\n table = TabIndexTable()\n table.add(\"a\",2)\n table.add(\"b\")\n table.add(\"c\")\n table.add(\"d\",3)\n self.assertEquals(table.lookup(\"a\"),2)\n self.assertEquals(table.lookup(\"b\"),1)\n self.assertEquals(table.lookup(\"c\"),3)\n self.assertEquals(table.lookup(\"d\"),3)\n self.assertTrue(\"b\" in table.lookupFields(1))\n self.assertTrue(\"a\" in table.lookupFields(2))\n self.assertTrue(\"c\" in table.lookupFields(3))\n self.assertTrue(\"d\" in table.lookupFields(3))\n\nloader = unittest.TestLoader()\nsuite = unittest.TestSuite()\nsuite.addTest(loader.loadTestsFromTestCase(PyWebMvcTestCase))\nsuite.addTest(loader.loadTestsFromTestCase(MultiDictTestCase))\nsuite.addTest(loader.loadTestsFromTestCase(TabIndexTableTestCase))\n\n","sub_path":"test/unittest/test_framework/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"551105907","text":"#!/bin/python\n\n\ndef solve(R, C, W):\n\n if (W == 1):\n return R * C\n elif (W == C):\n return R - 1 + W\n\n return (R - 1) * int((C - 1)/W) + int((C - 1)/W) + W\n\n\nT = int(input())\n\nfor i in range(0, T):\n R, C, W = [int(x) for x in input().split()]\n\n print(\"Case #\", (i+1), \": \", solve(R, C, W), sep='')\n \n\n","sub_path":"solutions_5640146288377856_0/Python/darus/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"273535035","text":"############\nimport os\nimport pymongo\nimport json\nfrom bson import json_util, ObjectId\nfrom bson.json_util import dumps\nimport requests\nfrom flask import Flask, render_template, Markup, request, redirect, jsonify\n\n############\n# import zipfile\n# import pathlib\n# from pathlib import Path\n# ############\n# from collections import defaultdict\nimport re\n# import string\n# ############\n# import pandas as pd\n# from datetime import datetime\n# ############\n# import heapq\n\n\n# Create an instance of Flask\napp = Flask(__name__)\nMONGO_URL = os.environ.get('MONGO_URL')\n\nmyclient = pymongo.MongoClient(MONGO_URL, maxPoolSize=50, connect=True)\n# stuff = {'text':'BLANK','count':0}\n# data_path = 'static/data/'\n# unzip_path = 'static/data/unzip/'\n\n\n\n@app.route('/', methods=['GET', 'POST', 'OPTIONS'])\ndef home():\n \"\"\"Landing page.\"\"\"\n return render_template(\"index.html\")\n\n\n@app.route('/team', methods=['GET', 'POST'])\ndef team():\n return render_template('team.html')\n\n\n@app.route(\"/readfull/\")\ndef finddocs(search_word):\n\n print('Starting query...')\n print(search_word)\n mydb = myclient[\"finalproject\"]\n mycol = mydb[\"recipes\"]\n \n ############\n myquery = {\"name\" : { '$regex' : search_word }}\n #myquery = {'_id': ObjectId(\"5e15044c9bad15d0f41f740b\")}\n ############\n\n cursor = json.loads(dumps(mycol.find(myquery)))\n \n myclient.close()\n #print(list(cursor))\n print(jsonify(list(cursor)))\n\n return jsonify(list(cursor))\n\n# @app.route('/team', methods=['GET', 'POST'])\n# def team():\n# if request.method == 'POST':\n# # do stuff when the form is submitted\n\n# # redirect to end the POST handling\n# # the redirect can be to the same route or somewhere else\n# return redirect(url_for('index'))\n\n# # show the form, it wasn't submitted\n# return render_template('team.html')\n\n# @app.route('/index', methods=['GET', 'POST'])\n# def team():\n# if request.method == 'POST':\n# # do stuff when the form is submitted\n\n# # redirect to end the POST handling\n# # the redirect can be to the same route or somewhere else\n# return redirect(url_for('index'))\n\n# # show the form, it wasn't submitted\n# return render_template('team.html')\n\n\n@app.route(\"/detail/\")\ndef details(search_oid):\n \n print('got to detail...')\n print(search_oid)\n \n mydb = myclient[\"finalproject\"]\n mycol = mydb[\"recipes\"]\n\n myquery = {'_id': ObjectId(search_oid)}\n #myquery = {'_id': ObjectId(\"5e15044c9bad15d0f41f740f\")}\n\n cursor = json.loads(dumps(mycol.find(myquery)))\n \n myclient.close()\n print(list(cursor))\n print(jsonify(list(cursor)))\n return jsonify(list(cursor))\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"373325639","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 20 20:46:00 2021\n\n@author: SB00747428\n\"\"\"\n\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.express as px\nfrom scipy import stats\nfrom scipy.stats import norm, skew\nimport numpy as np\nfrom sklearn import metrics\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.metrics import mean_absolute_error\n\n\ndataset = pd.read_csv('sujit_data_export.csv', sep=',') \nvalue = []\nfor i in dataset['result']:\n if i == 'ND':\n y = 0\n if i == 'NT':\n y = 0\n else: \n for s in i.split():\n if s.isdigit():\n y = int(s)\n value.append(y)\ndataset['value'] = value\n\nscalp_hair = dataset[dataset['sample_type__type'] == 'Scalp Hair']\nbody_hair = dataset[dataset['sample_type__type'] == 'Body Hair']\nurine = dataset[dataset['sample_type__type'] == 'Urine']\nfacial_hair = dataset[dataset['sample_type__type'] == 'Facial Hair']\nnails = dataset[dataset['sample_type__type'] == 'Nail Clippings']\n\nscalp_hair['sample_dye_line_length'] = scalp_hair['sample_dye_line_length'].fillna(-1)\nunaffectedsection = []\nfor i in scalp_hair['sample_dye_line_length']:\n if i == -1:\n unaffectedsection.append(12)\n elif i > 0 and i < 1.2:\n unaffectedsection.append(0)\n elif i>= 1.2 and i < 2.4:\n unaffectedsection.append(1)\n elif i>= 2.4 and i < 3.6:\n unaffectedsection.append(2)\n elif i>= 3.6 and i < 4.8:\n unaffectedsection.append(3)\n elif i>= 4.8 and i < 6.0:\n unaffectedsection.append(4)\n elif i>= 6.0 and i < 7.2:\n unaffectedsection.append(5)\n else:\n unaffectedsection.append(6)\n \nscalp_hair['unaffectedsection'] = unaffectedsection\n\nposition1 = scalp_hair[scalp_hair['position'] == 1]\nposition2 = scalp_hair[scalp_hair['position'] == 2]\nposition3 = scalp_hair[scalp_hair['position'] == 3]\nposition4 = scalp_hair[scalp_hair['position'] == 4]\nposition5 = scalp_hair[scalp_hair['position'] == 5]\nposition6 = scalp_hair[scalp_hair['position'] == 6]\n\ndrugslist_cocaine= ['Cocaine', 'Benzoylecgonine', 'Cocaethylene', 'Norcocaine', 'Anhydroecgonine methyl ester']\n\ndrugslist_cannabis = ['delta-9-THC', 'Cannabidiol', 'Cannabinol']\n\n\n\"\"\"\nCocaine\n\"\"\"\npos1 = pd.DataFrame()\npos2 = pd.DataFrame()\npos3 = pd.DataFrame()\npos4 = pd.DataFrame()\npos5 = pd.DataFrame()\npos6 = pd.DataFrame()\n#cocaine[\"client_pk\"]= position1[position1['testable']== 'Cocaine'].client_pk\nx = position1[position1['testable']== 'Cocaine']\npos1[['instruction_fnumber', 'value', 'unaffectedsection']] = x[['instruction_fnumber', 'value', 'unaffectedsection']]\n# = position1[position1['testable']== 'Cocaine'].value\n\ny = position2[position2['testable']== 'Cocaine']\npos2[['instruction_fnumber', 'value1', 'unaffectedsection1']] = y[['instruction_fnumber', 'value', 'unaffectedsection']]\n\nz = position3[position3['testable']== 'Cocaine']\npos3[['instruction_fnumber', 'value2', 'unaffectedsection2']] = z[['instruction_fnumber', 'value', 'unaffectedsection']]\n\na = position4[position4['testable']== 'Cocaine']\npos4[['instruction_fnumber', 'value3', 'unaffectedsection3']] = a[['instruction_fnumber', 'value', 'unaffectedsection']]\n\nb = position5[position5['testable']== 'Cocaine']\npos5[['instruction_fnumber', 'value4', 'unaffectedsection4']] = b[['instruction_fnumber', 'value', 'unaffectedsection']]\n\nc = position6[position6['testable']== 'Cocaine']\npos6[['instruction_fnumber', 'value5', 'unaffectedsection5']] = c[['instruction_fnumber', 'value', 'unaffectedsection']]\n\nmerged = pd.merge(pos1, pos2, on ='instruction_fnumber', how = 'left')\nmerged = merged.drop_duplicates()\n\nmerged = merged.merge(pos4, on ='instruction_fnumber', how = 'left')\nmerged = merged.drop_duplicates()\n\nmerged = merged.merge(pos5, on ='instruction_fnumber', how = 'left')\nmerged = merged.drop_duplicates()\n\nmerged = merged.merge(pos6, on ='instruction_fnumber', how = 'left')\nmerged = merged.drop_duplicates()\nmerged.to_csv('Cocaine.csv',index=False)\n\n","sub_path":"cocaine.py","file_name":"cocaine.py","file_ext":"py","file_size_in_byte":4034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"143585865","text":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nclass Analyse():\n def __init__(self, dir_opt):\n self.dir_opt = dir_opt\n\n def top_ranked_drugs(self, rank_num):\n # GROUP PRED DRUGS EFFECT\n pred_dl_input_df = pd.read_csv('./result/PredDeepLearningInput.txt', delimiter = ',')\n group_pred_dl_input_df = pred_dl_input_df.groupby(['Drug A', 'Drug B']).agg({'Score':'sum', 'Pred Score':'sum'}).reset_index()\n print(group_pred_dl_input_df)\n # CALCULATE RATE OF TOP RANKED\n # pd.set_option('display.max_rows', rank_num)\n top_score_df = group_pred_dl_input_df.sort_values(by = 'Score', ascending = False)\n top_pred_df = group_pred_dl_input_df.sort_values(by = 'Pred Score', ascending = False)\n top_rank_score_df = top_score_df.head(rank_num)\n top_rank_pred_df = top_pred_df.head(rank_num)\n top_score_list = top_rank_score_df.index.tolist()\n top_pred_list = top_rank_pred_df.index.tolist()\n rank_count = 0\n for index in top_pred_list:\n if index in top_score_list:\n rank_count += 1\n print(rank_count)\n top_rank_score_df.to_csv('./result/top_rank_score.txt', index = False, header = True)\n top_rank_pred_df.to_csv('./result/top_rank_pred.txt', index = False, header = True)\n return top_rank_score_df, top_rank_pred_df\n\n def pearson_top_real_pred(self, rank_num):\n pred_dl_input_df = pd.read_csv('./result/PredDeepLearningInput20.txt', delimiter = ',')\n group_pred_dl_input_df = pred_dl_input_df.groupby(['Drug A', 'Drug B']).agg({'Score':'sum', 'Pred Score':'sum'}).reset_index()\n top_score_df = group_pred_dl_input_df.sort_values(by = 'Score', ascending = False)\n top_pred_df = group_pred_dl_input_df.sort_values(by = 'Pred Score', ascending = False)\n # CALCULATE GROUPED PEARSON CORRELATION OF TOP RANKED\n top_rank_score_df = top_score_df.head(rank_num)\n top_rank_pred_df = top_pred_df.head(rank_num)\n top_score_list = top_rank_score_df.index.tolist()\n top_pred_list = top_rank_pred_df.index.tolist()\n pearson_top_list = []\n for index in top_pred_list:\n if index in top_score_list:\n pearson_top_list.append(index)\n pearson_top_real_pred_df = pred_dl_input_df.iloc[pearson_top_list]\n print(pearson_top_real_pred_df.corr(method = 'pearson'))\n\n\n def plot_train_real_pred(self, path, epoch_time):\n # ALL POINTS PREDICTION SCATTERPLOT\n dir_opt = self.dir_opt\n pred_dl_input_df = pd.read_csv(path + '/PredTrainingInput.txt', delimiter = ',')\n print(pred_dl_input_df.corr(method = 'pearson'))\n title = 'Scatter Plot After ' + epoch_time + ' Iterations In Training Dataset'\n ax = pred_dl_input_df.plot(x = 'Score', y = 'Pred Score',\n style = 'o', legend = False, title = title)\n ax.set_xlabel('Score')\n ax.set_ylabel('Pred Score')\n # SAVE TRAINING PLOT FIGURE\n file_name = 'epoch_' + epoch_time + '_train'\n path = '.' + dir_opt + '/plot/%s' % (file_name) + '.png'\n unit = 1\n while os.path.exists(path):\n path = '.' + dir_opt + '/plot/%s_%d' % (file_name, unit) + '.png'\n unit += 1\n plt.savefig(path, dpi = 300)\n plt.show()\n \n\n def plot_test_real_pred(self, path, epoch_time):\n # ALL POINTS PREDICTION SCATTERPLOT\n dir_opt = self.dir_opt\n pred_dl_input_df = pd.read_csv(path + '/PredTestInput.txt', delimiter = ',')\n print(pred_dl_input_df.corr(method = 'pearson'))\n title = 'Scatter Plot After ' + epoch_time + ' Iterations In Test Dataset'\n ax = pred_dl_input_df.plot(x = 'Score', y = 'Pred Score',\n style = 'o', legend = False, title = title)\n ax.set_xlabel('Score')\n ax.set_ylabel('Pred Score')\n # SAVE TEST PLOT FIGURE\n file_name = 'epoch_' + epoch_time + '_test'\n path = '.' + dir_opt + '/plot/%s' % (file_name) + '.png'\n unit = 1\n while os.path.exists(path):\n path = '.' + dir_opt + '/plot/%s_%d' % (file_name, unit) + '.png'\n unit += 1\n plt.savefig(path, dpi = 300)\n plt.show()\n \n\nif __name__ == \"__main__\":\n # ANALYSE DRUG EFFECT\n # print('ANALYSE DRUG EFFECT...')\n # rank_num = 100\n # Analyse().top_ranked_drugs(rank_num)\n # Analyse().pearson_top_real_pred(rank_num)\n dir_opt = '/datainfo1'\n path = '.' + dir_opt + '/result/epoch_20'\n epoch_time = '20'\n Analyse(dir_opt).plot_train_real_pred(path, epoch_time)\n Analyse(dir_opt).plot_test_real_pred(path, epoch_time)","sub_path":"desert_model/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":4712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"276251440","text":"import turtle\n\nscr_color = raw_input(\"What color would you like the screen to be? \")\nps = int(raw_input(\"How wide should the line be? \"))\n\nwn = turtle.Screen()\nwn.bgcolor(scr_color) \n\ntess = turtle.Turtle()\ntess.color(\"blue\") \ntess.pensize(ps) \n\ntess.forward(50)\ntess.left(120)\ntess.forward(50)\n\nwn.exitonclick()\n","sub_path":"misc/ip/turtles/turtles_one/turt_3.py","file_name":"turt_3.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"247475681","text":"from __future__ import division\nfrom function import get_itinerary, get_elevation, get_drivecycle\nfrom googlemaps.client import Client\nimport scipy.integrate as integrate\nimport matplotlib.pyplot as plt\nimport seaborn\n\napi_key = 'AIzaSyDVdkCJ5ZJ8rpdk1CD86-S2HZOw0vWmX2s '\nclient = Client(api_key)\n\n# Get input data\norigin = '2057 University ave Berkeley CA 94704'\ndestination = 'Greenwood Ave, Oakland, CA'\naggressiveDriving = True\n\n# Get directions (distance, duration and coordinates for every step)\nstepByStep, duration, distance, path = get_itinerary(client, origin, destination)\n\n# Get elevation along path and new locations (limit 512points)\nelevation, deltaSample, maxElevation, minElevation, averageResolution = get_elevation(client, path, distance)\n\n# Get drivecycles (speed vs time for every step)\ndrivecycle = []\ntimeDrivingList = []\nfor step in stepByStep:\n\tspeed, objectiveSpeed, timeDriving = get_drivecycle(step['duration'], step['distance'], aggressiveDriving)\n\tprint('Difference with google distance is ' + str(step['distance'] - integrate.cumtrapz(y=speed, dx=1, initial=0.0)[-1]) + ' m')\n\tdrivecycle.extend(speed)\n\ttimeDrivingList.append(timeDriving)\n\n# Sanity check\nprint('Difference with google distance is ' + str(distance - integrate.cumtrapz(y=drivecycle, dx=1, initial=0.0)[-1]) + ' m')\nprint('Time driving is ' + str(sum(timeDrivingList) / 60) + ' min on a ' + str(duration / 60) + ' min trip long')\n\nprint(len(drivecycle))\nx = range(0, len(drivecycle))\nx = [ x[i] for i in range(0, len(x))]\ndrivecycle = [ drivecycle[i] * 3.6 for i in range(0, len(drivecycle))]\nplt.plot(x, drivecycle)\nplt.show()\n# Get elevation in time\n\n\n# Interpolate speed and elevation at the rigth rate\n\n\n# Launch detailed power-train model (or anything really)\n\n\n# Get SOC at location\n\n\n# Wrap up everything into a dict\nresult ={ \n\t\t\t'locationSeries': { 'coordinatePath': [], 'coordinateSOC': [], 'SOC': [], 'percentDistance': [] }, \n\t\t\t'timeSeries': {'time': [], 'speed': [], 'elevation': [], 'SOC': [] },\n\t\t\t'duration': duration,\n\t\t\t'distance': distance,\n\t\t\t'aggressiveDriving': aggressiveDriving,\n\t\t\t'SOCinit': 0,\n\t\t\t'totalConsumption': 0,\n\t\t\t'origin': origin,\n\t\t\t'destination': destination,\n\t\t\t'descritpion': 'someText'\n\t\t}\n\n# import pdb; pdb.set_trace()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"497685280","text":"import re\r\nimport easyimap as e\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom flask import request\r\n\r\nfrom joblib import dump, load\r\nfrom nltk import word_tokenize, PorterStemmer\r\nfrom nltk.corpus import stopwords\r\n\r\n#\r\n# def cleaning(string):\r\n# string = re.sub(\"[^0-9a-zA-Z\\ ]\", \"\", str(string))\r\n# string = string.lower()\r\n# string = string.strip()\r\n#\r\n# return string\r\n#\r\n#\r\n# def stem(string):\r\n# tokenized = word_tokenize(string)\r\n# stemmed = []\r\n# stemmer = PorterStemmer()\r\n#\r\n# for word in tokenized:\r\n# stemmed.append(stemmer.stem(word))\r\n#\r\n# return ' '.join(stemmed)\r\n#\r\n#\r\n# def remove_stopwords(string):\r\n# STOP_WORDS = set(stopwords.words('english'))\r\n#\r\n# tokenized = word_tokenize(string)\r\n# filtered = []\r\n#\r\n# for word in tokenized:\r\n# if word not in STOP_WORDS:\r\n# filtered.append(word)\r\n#\r\n# return \" \".join(filtered)\r\n#\r\n#\r\n# global email\r\n# global subject_list\r\n# global body_list\r\n# global email_address_list\r\n# global percentage_list\r\n#\r\n# percentage_list = []\r\n# subject_list = []\r\n# body_list = []\r\n# email_address_list = []\r\n# date_list = []\r\n# # Authenticates and retrieves email\r\n#\r\n# imap_url = 'imap.gmail.com'\r\n# username = 'jerrettfg@gmail.com'\r\n# password = 'Yongyong97'\r\n# server = e.connect(imap_url, username, password)\r\n# #inbox = server.listup()\r\n# inbox = server.listids()\r\n# email = server.mail(server.listids()[0])\r\n#\r\n# for x in range(5, 10): # len(inbox)\r\n# email = server.mail(server.listids()[x])\r\n#\r\n# string = email.body\r\n# string = cleaning(string)\r\n# string = stem(string)\r\n# string = remove_stopwords(string)\r\n#\r\n# # store email subject, body in list\r\n# email_address_list.append(email.from_addr)\r\n# subject_list.append(email.title)\r\n# body_list.append(email.body)\r\n#\r\n# # ML\r\n# n_df = pd.DataFrame({'text': string}, index=[0])\r\n# n_df.head()\r\n# vectorizer = load(r'naivebayesVectorizer.joblib') # load vectorizer\r\n# nbclf = load(r'naivebayes.joblib') # load the naivebayes ml model\r\n#\r\n# x_matrix = vectorizer.transform(n_df['text'])\r\n# my_prediction = nbclf.predict(x_matrix)\r\n# percentage = nbclf.predict_proba(x_matrix)\r\n# #percentage = np.array(percentage)\r\n# #percentage = ['{:f}'.format(item) for item in percentage]\r\n# np.set_printoptions(formatter={'float_kind':'{:f}'.format})\r\n# if my_prediction == 1:\r\n# result = 'Phishing'\r\n# percentage = format(percentage[0][1], '.12f') # to 12decimal place\r\n# percentage = float(percentage) * 100 # convert to percent\r\n# percentage = str(percentage) + '%'\r\n# percentage_list.append(percentage)\r\n# elif my_prediction == 0:\r\n# result = 'Non-Phishing'\r\n# percentage = format(percentage[0][0], '.12f') # to 12decimal place\r\n# percentage = float(percentage) * 100 # convert to percent\r\n# percentage = str(percentage) + '%'\r\n# percentage_list.append(percentage)\r\n#\r\n# print('PERCENTAGE', percentage)\r\n# print(result)\r\n# for a in percentage_list:\r\n# print(a)\r\n#\r\n# date_list.append(email.date)\r\n# for i in date_list:\r\n# print(i)\r\n#\r\n# #percentage_l = list(percentage) #convert numpy array to list\r\n# #print(percentage_l)\r\n#\r\n# if my_prediction == 1:\r\n# result = 'Phishing'\r\n# #percentage = percentage_l[1]\r\n# #percentage_list.append(percentage)\r\n# elif my_prediction == 0:\r\n# result = 'Non-Phishing'\r\n# #percentage = percentage_l[0]\r\n# # percentage_list.append(percentage)\r\n\r\n# import time\r\n# \r\n# start = time.time()\r\n# print(\"hello\")\r\n# end = time.time()\r\n# print(end - start)\r\nfrom openpyxl import load_workbook\r\n\r\n\r\nwb = load_workbook('logs.xlsx')\r\nsheet = wb[\"blacklist\"] # values will be saved to excel sheet\"blacklist\"\r\ncol2 = 'blacklisted' # value of 2nd column in excel\r\n\r\nemail1 = ' ' # id='email1' from html form\r\nif email1.strip() != \"\":\r\n col1 = email1.strip()\r\n sheet.append([col1, col2])\r\n\r\nemail2 = 'jerrett@gmail.com'\r\nif email2.strip() != \"\":\r\n col1 = email2.strip()\r\n sheet.append([col1, col2])\r\n\r\nemail3 = 'jerrett@gmail.com'\r\nif email3.strip() != \"\":\r\n col1 = email3.strip()\r\n sheet.append([col1, col2])\r\n\r\nemail4 = 'jerrett@gmail.com'\r\nif email4.strip() != \"\":\r\n col1 = email4.strip()\r\n sheet.append([col1, col2])\r\n\r\nwb.save('logs.xlsx')\r\nwb.close()\r\n\r\n\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"492557497","text":"#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n# Date : 2015-10-01\n# Author: Master Yumi\n# Email : yumi@meishixing.com\n\nimport tornado.web\nfrom api.base import BaseHandler\nimport module.user_ctrl as user_ctrl\nimport module.marker_ctrl as marker_ctrl\n\nclass ListHandler(BaseHandler):\n \"\"\"签到列表\"\"\"\n def get(self):\n user_filter_id = self.get_argument(\"u\", 0) # u 表示 user_id\n page = self.get_argument(\"page\", 1)\n page_size = self.get_argument(\"page_size\", 200) # 先不做分页\n\n if user_filter_id > 0:\n marker_list = marker_ctrl.get_user_marker_list(int(user_filter_id), int(page), int(page_size))\n else:\n marker_list = marker_ctrl.get_marker_list(int(page), int(page_size))\n user_id = self.get_current_user()\n user_info = user_ctrl.get_user(user_id)\n self.render(\"marker_list.html\", result={\n \"marker_list\": marker_list, \n \"user_id\": user_id, \n \"user_filter_id\": user_filter_id,\n \"user_info\": user_info\n })\n\nclass AddHandler(BaseHandler):\n \"\"\"增加新签到\"\"\"\n @tornado.web.authenticated\n def get(self):\n return self.redirect(\"/marker/list\")\n\n @tornado.web.authenticated\n def post(self):\n title = self.get_argument(\"title\", \"\")\n marker = self.get_argument(\"marker\", \"\")\n if not (title and marker):\n return self.render_string(\"标题和内容不能为空\")\n user_id = self.get_current_user()\n marker_ctrl.add_marker(title, marker, user_id)\n return self.redirect(\"/marker/list\")\n","sub_path":"api/marker.py","file_name":"marker.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"303666762","text":"from __future__ import division, print_function, absolute_import\nfrom os.path import join, isfile, expanduser, abspath\nfrom os import walk, listdir\n\nfrom ..dataset import ImageDataset\n\n\nclass VMMRdb(ImageDataset):\n \"\"\"Vehicle Make and Model Recognition Dataset.\n\n URL: ``\n\n Dataset statistics:\n - identities: 9169.\n - images: 285086.\n \"\"\"\n\n dataset_dir = 'vmmrdb'\n\n def __init__(self, root='', dataset_id=0, load_masks=False, **kwargs):\n self.root = abspath(expanduser(root))\n self.dataset_dir = join(self.root, self. dataset_dir)\n self.data_dir = self.dataset_dir\n\n self.images_dir = join(self.data_dir, 'images')\n\n required_files = [\n self.data_dir, self.images_dir\n ]\n self.check_before_run(required_files)\n\n train = self.load_annotation(\n self.images_dir,\n dataset_id=dataset_id,\n load_masks=load_masks\n )\n train = self._compress_labels(train)\n\n query, gallery = [], []\n\n super(VMMRdb, self).__init__(train, query, gallery, **kwargs)\n\n @staticmethod\n def load_annotation(data_dir, dataset_id=0, min_num_samples=5, load_masks=False):\n if load_masks:\n raise NotImplementedError\n\n base_dirs = []\n for root, sub_dirs, files in walk(data_dir):\n if len(sub_dirs) == 0 and len(files) >= min_num_samples:\n base_dirs.append(root)\n\n out_data = []\n for class_id, base_dir in enumerate(base_dirs):\n image_files = [join(base_dir, f) for f in listdir(base_dir) if isfile(join(base_dir, f))]\n\n for image_path in image_files:\n out_data.append((image_path, class_id, 0, dataset_id, '', -1, -1))\n\n return out_data\n","sub_path":"torchreid/data/datasets/image/vmmrdb.py","file_name":"vmmrdb.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"457717892","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nfrom flask import Flask, render_template, request, redirect, jsonify, url_for\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n# from the name of the model import the Base and Class\nfrom database_list import Base, lowConsonants\n\n# One way of connecting css file\n# app = Flask(__name__,static_url_path='/css')\napp = Flask(__name__)\n\nengine = create_engine('sqlite:///thaiconsonants.db')\nBase.metadata.bind = engine\n\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\n@app.route('/')\n@app.route('/restaurant/new/', methods=['GET', 'POST'])\ndef newLowConsonants():\n if request.method == 'POST':\n newLowConsonants = lowConsonants(name=request.form['name'])\n session.add(newLowConsonants)\n session.commit()\n return redirect(url_for('form.html'))\n else:\n return render_template('form.html')\n\n\n\n\n # returns message\n # return '{} You Must Input Name'.format('ก')\n # returns redefined variable name\n # name = 'New User'\n # return render_template('index.html', name=name)\n # else:\n # return render_template('form.html', name=name)\n\n# @app.route('/consonants//new', methods=['GET','POST'])\n# def low(name=low):\n# return render_template('index.html',name=low)\n\n\n\nif __name__ == '__main__':\n app.debug = True\n app.run(host = '0.0.0.0', port = 5555)\n","sub_path":"thai-consonants/testlanguage.py","file_name":"testlanguage.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"79648981","text":"# -*- coding:utf-8 -*-\n\"\"\"\nbig_heap_sort 大顶堆排序(升序)\n\n1. 关于堆\n · 堆是一棵顺序存储的完全二叉树。\n 小根堆:\n 其中每个结点的关键字都不大于其孩子结点的关键字,这样的堆称为小根堆。\n Ri <= R2i+1 且 Ri <= R2i+2 (小根堆)\n 大根堆:\n 其中每个结点的关键字都不小于其孩子结点的关键字,这样的堆称为大根堆\n Ri >= R2i+1 且 Ri >= R2i+2 (大根堆)\n (升序一般采用大顶堆,降序一般采用小顶堆)\n\n2. 大顶堆\n可归纳为两个操作:\n(1)根据初始数组去构造初始堆(构建一个完全二叉树,保证所有的父结点都比它的孩子结点数值大)。\n(2)每次交换第一个和最后一个元素,输出最后一个元素(最大值),然后把剩下元素重新调整为大根堆。\n\n:Author: kylin\n:Last Modified by: kylin.smq@qq.com\n\"\"\"\nimport numpy as np\n\ndef generateData(min, max, n):\n \"\"\"\n 生成数据\n Args:\n min: 最小值\n max: 最大值\n n: 元素个数\n\n Returns: 数组\n \"\"\"\n return np.random.randint(min, max+1, n)\n\n\nclass Heap:\n def build_heap(self, data_list):\n \"\"\"\n 根据数组,构造堆\n Args:\n data_list: 元素列表\n \"\"\"\n length = len(data_list)\n verify_node = length // 2 - 1\n\n for i in range(verify_node, -1, -1):\n # 对非叶子结点进行堆调整\n self.heapify(data_list, i, length)\n\n def heapify(self, data_list, index, length):\n \"\"\"\n 对index位置处的元素进行堆调整,使其符合堆的性质\n Args:\n data_list: 元素列表\n index: 待处理元素的索引\n length: 列表长度\n \"\"\"\n # 先找到其左右子结点\n left = 2 * index + 1\n # right = 2 * index + 2\n right = left + 1\n\n # 默认当前结点处是最大值\n largest_index = index\n\n if left < length and data_list[left] > data_list[largest_index]:\n # 如果左结点的值比当前值大,则更新largest_index\n largest_index = left\n\n if right < length and data_list[right] > data_list[largest_index]:\n # 如果右结点的值比当前值大,则更新largest_index\n largest_index = right\n\n # 如果index处不是最大元素,则需要调整结点的顺序\n if largest_index != index:\n # 交换元素\n self.swap(data_list, index, largest_index)\n # 调整子结点的顺序\n self.heapify(data_list, largest_index, length)\n\n def swap(self, data_list, i, j):\n \"\"\"\n 交换i,j位置的元素\n Args:\n data_list: 元素列表\n i: 索引i\n j: 索引j\n \"\"\"\n t = data_list[j]\n data_list[j] = data_list[i]\n data_list[i] = t\n\n def sort(self, data_list):\n \"\"\"\n 排序\n Args:\n array_list: 元素列表\n \"\"\"\n length = len(data_list)\n\n # 构造大顶堆\n self.build_heap(data_list)\n\n # 交换堆顶和末端元素,重置大堆顶\n for i in range(length-1, 0, -1):\n self.swap(data_list, 0, i)\n length -= 1\n self.heapify(data_list, 0, length)\n\n\nif __name__ == \"__main__\":\n # 生成数据\n min = 5\n max = 30\n n = 5\n np.random.seed(0)\n data_list = generateData(min, max, n).tolist()\n print(\"====Before=====\")\n print(data_list)\n\n # heap sort\n print(\"====After=====\")\n Heap().sort(data_list)\n print(data_list)\n","sub_path":"02_排序/big_heap_sort.py","file_name":"big_heap_sort.py","file_ext":"py","file_size_in_byte":3671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"583877574","text":"import cozmo\nfrom cozmo.util import degrees, distance_mm, speed_mmps\nimport time\nimport asyncio\nimport CrowdController\ntry:\n from PIL import Image\nexcept:\n print(\"Looks like you need to install Pillow\")\n\n# Imports ci-dessus, ne pas oublier de les installer avec un pip3 install (ou pip install)\n\n# La fonction principale\ndef program_cozmo(robot: cozmo.robot.Robot):\n\n #paramètres et initialisations\n #pour l'url du serveur faire attention à la modifification faite dans le fonction \"checkpicture\", un rework sera peut-être nécessaire pour viser autre chose que l'API de démo\n url = \"http://localhost:3000/v1/images\"\n robot.camera.image_stream_enabled = True\n robot.camera.color_image_enabled = True\n image_inconnu = None\n \n #Boucle infinie\n while True :\n face_to_follow = None # Réinitilisation du visage enregistré\n robot.move_lift(-3) # On llibère la vision de la caméra\n while face_to_follow is None :\n robot.set_all_backpack_lights(cozmo.lights.red_light)\n robot.move_head(1)\n try:\n face_to_follow = robot.world.wait_for_observed_face(timeout=60) # COZMO attend un visage\n robot.set_all_backpack_lights(cozmo.lights.blue_light)\n except asyncio.TimeoutError:\n print(\"Didn't find a face - exiting!\")\n\n # COZMO ne reconnais pas directement la personne, on essaye alors de scanner plusieurs fois la personne\n i = 0\n if face_to_follow.name is \"\" : # On check si le visage à un nom ou pas (si il est connu ou non)\n robot.play_anim_trigger(cozmo.anim.Triggers.CodeLabSquint2,ignore_body_track=True, ignore_lift_track=True,in_parallel=True) # Juste une animation visuelle des yeux de COZMO\n \n # Workaround étrange, entre le bloc if ci-dessus et celui, COZMO peut perdre le visage et ainsi créer une erreur, alors on vérifie\n if face_to_follow is not None :\n while face_to_follow.name is \"\" and i < 50 : # Lancement du scan long, avec un nombre de passage i et une vérification si le visage est toujours inconnu\n try:\n face_to_follow = robot.world.wait_for_observed_face(timeout=5)\n robot.turn_towards_face(face_to_follow,in_parallel=True).wait_for_completed # Permet un suivit du visage, mais bouger va ralentir le scan. Si on enlève le \"wait_for_completed\", on s'expose à des crashs\n except asyncio.TimeoutError:\n print(\"Perte du visage pendant le scan\")\n face_to_follow = None\n break\n i = i + 1\n time.sleep(0.2)\n \n\n\n while face_to_follow is not None : # Une fois qu'on a bien scanner, pour être juste un peu plus sûr que COZMO ne connaît effectivement pas déjà le visage, ou qu'il le connaît\n robot.turn_towards_face(face_to_follow, in_parallel=True).wait_for_completed()\n #Cas si COZMO connaît déjà le visage\n if face_to_follow.name is not \"\" and \"pending\" not in face_to_follow.name :\n robot.set_all_backpack_lights(cozmo.lights.green_light)\n robot.say_text(\"Bonjour\" + face_to_follow.name,True,use_cozmo_voice=True, in_parallel=True).wait_for_completed()\n #Cas si COZMO voit une face qu'il reconnaît mais qui a un \"pending\" dans son nom (veut dire que le Crowd n'a pas encore rendu son verdict)\n elif \"pending\" in face_to_follow.name:\n color = cozmo.lights.Light(cozmo.lights.Color(rgb=(128,128,1)))\n robot.set_all_backpack_lights(color)\n robot.say_text(\"Bonjour humain numéro\" + face_to_follow.name.replace(\"pending for crowd\", \"\") + \", merci d'attendre votre reconnaissance\",True,use_cozmo_voice=True, in_parallel=True).wait_for_completed()\n #Cas si COZMO ne connaît pas le visage\n else :\n image_inconnu = robot.world.latest_image.raw_image #On prend la photo\n\n robot.set_all_backpack_lights(cozmo.lights.white_light)\n try:\n treadController = CrowdController.ControllerFace(face_to_follow, image_inconnu, url ,100 , 5) # Création du thread\n treadController.start() # Lancement du thread de reconnaissance et le thread principal ne s'en occupe plus du tout.\n except Exception as identifier:\n print(\"Erreur\\n\" + str(identifier))\n robot.say_text(\"Bonjour inconnu, votre visage va être traité, merci de votre patience\" ,False,use_cozmo_voice=False,voice_pitch=-9, in_parallel=True).wait_for_completed()\n\n \n face_to_follow = None\n time.sleep(3)\n\n# Le main du programme, lance la fonction principale\ncozmo.run_program(program_cozmo, use_viewer=True)","sub_path":"FaceCrowd/TestFaceCrowd.py","file_name":"TestFaceCrowd.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"500272957","text":"import subprocess\n\nlocales = {'ru_RU.UTF-8': {'grub-locale': 'ru', 'charset': 'UTF-8'},\n 'en_EN.UTF-8': {'grub-locale': 'en', 'charset': 'UTF-8'},\n 'ru_RU.KOI8-RU': {'grub-locale': 'ru', 'charset': 'KOI8-RU'},\n 'en_EN': {'grub_locale': 'en', 'charset': 'ISO-8859-5'}}\n\ndef generate(given_locales):\n lines = []\n \n for language in given_locales:\n lines.append(' '.join([language,\n locales[language]['charset'],\n '\\n']))\n \n with open(\"locale.gen\", 'w') as locale_gen:\n locale_gen.writelines(lines)\n \n subprocess.Popen(['locale-gen'])\n","sub_path":"lib/l10n.py","file_name":"l10n.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"444131231","text":"#-*-coding:utf-8 -*-\n# 将ETHSCAN记录保存的脚本\nimport urllib.request as urllib2\nfrom urllib import request\nimport random\nfrom bs4 import BeautifulSoup\n\n'''\n# user_agent是爬虫与反爬虫斗争的第一步\nua_headers = {\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0',\n}'''\n# 用于模拟http头的User-agent\nua_list = [\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv2.0.1) Gecko/20100101 Firefox/4.0.1\",\n \"Mozilla/5.0 (Windows NT 6.1; rv2.0.1) Gecko/20100101 Firefox/4.0.1\",\n \"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11\",\n \"Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11\"\n]\n\nuser_agent=random.choice(ua_list)\n\n#要查询的以太地址\naddress=\"0x7751278c8b6b224946d065776fc67c81a5202958\"\npage_number_start=0\npage_count=1\nfor ii in range(page_count):\n\tpage_number_start=page_number_start+1\n\tpage_number=str(page_number_start)\n\n\t#url=\"https://etherscan.io/txs?a=\"+address+\"&p=\"+page_number\n\turl='https://etherscan.io/txsInternal?a='+address+'&&valid=true&p='+page_number\n\tprint(url)\n\n\t# 通过Request()方法构造一个请求对象\n\n\trequest1=urllib2.Request(url=url)\n\t# 把头添加进去\n\trequest1.add_header('User-Agent',user_agent)\n\t# 向指定的url地址发送请求,并返回服务器响应的类文件对象\n\tresponse=urllib2.urlopen(request1)\n\t# 服务器返回的类文件对象支持python文件对象的操作方法\n\t#html=response.read()\n\t#print(html.decode('utf-8')) \n\tsoup=BeautifulSoup(response,\"html.parser\")\n\n\t#k=0\n\t# 只能访问第个标签的内容,怎么解决\n\tfor i in soup.find_all('table',{'class':'table table-hover'}):\n\t\tprint(i)\n\t\t'''k=k+1\n\t\tm=k%7\n\n\t\tif m==0:\n\t\t\tbr='\\n'\n\t\telse:\n\t\t\tbr=''\n\t\ttbody=i.get_text() \n\t\tdata=str(tbody.encode('gbk','ignore'))+\",\"+br\n\t\twith open('test12.csv', 'a') as f:\n\t\t\tf.write(data)\n'''\n\n\t#print(\"已完成:\",str(page_number)+\"/\"+str(page_count))","sub_path":"AndroidSpider/Spider_ethsacn2.py","file_name":"Spider_ethsacn2.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"76030889","text":"#!/usr/bin/env python3\n\nfrom flask import Flask, render_template, redirect, url_for\nfrom flask_cache import Cache\nfrom pathlib import Path\nfrom dotmap import DotMap\nimport json\nimport urllib.request\nimport sys\nimport ldap\n\napp = Flask(__name__)\ncache = Cache(app,config={'CACHE_TYPE': 'simple'})\ntry:\n with open('config.json', 'r') as f:\n config = DotMap(json.load(f))\nexcept FileNotFoundError:\n print('config.json not found')\n sys.exit(0)\nexcept Exception as e:\n raise e\nl = ldap.initialize(config.ldap.url, bytes_mode=False)\n\n@app.route('/')\n@cache.cached(timeout=50)\ndef index():\n thestatus = status()\n return render_template('index.html', \n config=config,\n people=get_people(),\n status=thestatus)\n\n@app.route('/favicon.ico')\ndef favicon():\n icon = config.fa_icon[status()]\n url = config.fa_icon.generator_url + icon\n static_path = 'favicons/fa-' + icon + '.ico'\n favicon = Path('static/' + static_path)\n if not favicon.is_file():\n with urllib.request.urlopen(url) as response, favicon.open('wb') as out_file:\n data = response.read()\n out_file.write(data)\n return redirect(url_for('static', filename=static_path))\n\ndef status():\n members = set(get_members())\n people = set(get_people().keys())\n union = members.intersection(people)\n postohm_count = len(union)\n return 'positive' if (postohm_count >= config.people_required) else 'negative'\n\ndef get_members():\n lconf = config.ldap\n l.bind_s(lconf.bind_dn, lconf.bind_pw)\n search_dn = 'ou='+config.committee+','+lconf.search_dn\n results = l.search_s(search_dn,\n ldap.SCOPE_SUBTREE, lconf.filter, [lconf.attr])\n members = []\n for dn, ldap_obj in results:\n if lconf.attr in ldap_obj:\n for position, member in dec_and_split(ldap_obj[lconf.attr]):\n if position == config.position:\n members.append(member)\n return members\n\ndef dec_and_split(unsplit):\n return [element.decode('utf-8').split(';') for element in unsplit]\n\ndef get_people():\n request = urllib.request.Request(config.api.url)\n request.add_header('Authorization', 'Token ' + config.api.key)\n response = urllib.request.urlopen(request)\n data = response.read().decode('utf-8')\n sessions = json.loads(data)\n people = {}\n for session in sessions:\n people[session['user_id']] = session['nick']\n return people\n\nif __name__ == '__main__':\n # with app.app_context():\n # print(status())\n app.run()","sub_path":"SpontanPostOhm.py","file_name":"SpontanPostOhm.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"256209877","text":"import csv\r\nimport numpy as np\r\nfrom numpy import double\r\nimport pylab as pl\r\nfrom readingNathandata import readdata_nathan\r\nfrom copy import deepcopy\r\nfrom k_means import showCluster, kmeans\r\n\r\n\r\n\r\n\r\noutfile_o_cl1 = 'D:/projects/3dfx/BecksNDA_o_cl1.csv'\r\noutfile_o_cl2 = 'D:/projects/3dfx/BecksNDA_o_cl2.csv'\r\noutfile_o_cl3 = 'D:/projects/3dfx/BecksNDA_o_cl3.csv'\r\noutfile_o_cl4 = 'D:/projects/3dfx/BecksNDA_o_cl4.csv'\r\noutfile_o_cl5 = 'D:/projects/3dfx/BecksNDA_o_cl5.csv'\r\n\r\noutfp_o_cl1 = csv.writer(open(outfile_o_cl1, 'w', newline=''))\r\noutfp_o_cl2 = csv.writer(open(outfile_o_cl2, 'w', newline=''))\r\noutfp_o_cl3 = csv.writer(open(outfile_o_cl3, 'w', newline=''))\r\noutfp_o_cl4 = csv.writer(open(outfile_o_cl4, 'w', newline=''))\r\noutfp_o_cl5 = csv.writer(open(outfile_o_cl5, 'w', newline=''))\r\n\r\npointId_o, lon_o, lat_o, alt_o, time_list, useful_values = readdata_nathan()\r\n \r\ntime_mat = double(np.array(time_list))\r\n\r\nprint (np.median(useful_values))\r\nprint (np.std(useful_values))\r\nprint (np.average(useful_values))\r\n\r\ntime_mat_sum_id = np.sum(time_mat, axis=1)\r\n\r\nprint(len(time_mat_sum_id))\r\ntime_mat_lst = list(np.argsort(np.argsort(time_mat_sum_id)))\r\n\r\n#print(len(time_mat_lst))\r\n#print(len(pointId_o))\r\n\r\n#print (np.max(time_mat_lst))\r\n#pl.hist(useful_values,50, normed=1, facecolor='green', alpha=0.75)\r\n#pl.show()\r\n\r\ntime_mat_PE1 = deepcopy(time_mat)\r\ntime_mat_PE2 = deepcopy(time_mat)\r\ntime_mat_PE3 = deepcopy(time_mat)\r\ndim_max = np.shape(time_mat)\r\nfor i1 in range(0, dim_max[0]):\r\n for j1 in range(0, dim_max[1]):\r\n temp = double(time_mat[i1, j1]/500)\r\n if temp > 1:\r\n time_mat_PE2[i1, j1] = 500\r\n if temp <0:\r\n time_mat_PE2[i1, j1] = 0\r\n\r\ncentroids, clusterAssment = kmeans(time_mat, 5) \r\nprint (clusterAssment)\r\nprint (np.shape(clusterAssment))\r\n#showCluster(time_mat, 5, centroids, clusterAssment) \r\n\r\n######################################## POINT #####\r\nfirst_line = ['pointId', 'lon', 'lat', 'alt', 'valueOfTime1', 'valueOfTime2', 'valueOfTime3', 'valueOfTime4', 'valueOfTime5', \\\r\n'valueOfTime6', 'valueOfTime7', 'valueOfTime8', 'valueOfTime9', 'valueOfTime10', 'valueOfTime11', 'valueOfTime12', 'valueOfTime13']\r\n\r\n\r\noutfp_o_cl1.writerow(first_line)\r\noutfp_o_cl2.writerow(first_line)\r\noutfp_o_cl3.writerow(first_line)\r\noutfp_o_cl4.writerow(first_line)\r\noutfp_o_cl5.writerow(first_line)\r\n\r\nfor a in range(0,len(pointId_o)):\r\n time_ls = list(time_mat[a,:])\r\n out_line_poi = [pointId_o[a], lon_o[a], lat_o[a], alt_o[a], time_ls[0], time_ls[1], time_ls[2], time_ls[3], time_ls[4], time_ls[5], time_ls[6], time_ls[7], time_ls[8], time_ls[9], time_ls[10], time_ls[11], time_ls[12]] \r\n if (clusterAssment[a,0] <1):\r\n outfp_o_cl1.writerow(out_line_poi)\r\n elif (clusterAssment[a,0] >=1 and clusterAssment[a,0] <2):\r\n outfp_o_cl2.writerow(out_line_poi)\r\n elif (clusterAssment[a,0] >=2 and clusterAssment[a,0] <3):\r\n outfp_o_cl3.writerow(out_line_poi)\r\n elif (clusterAssment[a,0] >=3 and clusterAssment[a,0] <4):\r\n outfp_o_cl4.writerow(out_line_poi)\r\n else:\r\n outfp_o_cl5.writerow(out_line_poi)\r\n \r\n \r\n","sub_path":"clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"77186140","text":"\"\"\"\nAutomatic Model Search.\n\nAuthor(s): Luc Anselin, Xun Li\n\"\"\"\n\nimport arcpy as ARCPY\nimport numpy as NUM\nimport pysal as PYSAL\nimport os as OS\nimport SSDataObject as SSDO\nimport SSUtilities as UTILS\nimport sys as SYS\nimport pysal2ArcUtils as AUTILS\n\n# OLS Error result uses first 2, Lag result uses all 4\nFIELDNAMES = [\"Predy\", \"Resid\", \"Predy_e\", \"e_Predy\"]\n\ndef setupParameters():\n\n #### Get User Provided Inputs ####\n inputFC = ARCPY.GetParameterAsText(0)\n depVarName = ARCPY.GetParameterAsText(1).upper()\n indVarNames = ARCPY.GetParameterAsText(2).upper()\n indVarNames = indVarNames.split(\";\")\n weightsFile = ARCPY.GetParameterAsText(3)\n kernelWeightsFile = ARCPY.GetParameterAsText(4)\n pValue = ARCPY.GetParameter(5)\n useCombo = ARCPY.GetParameter(6)\n outputFC = ARCPY.GetParameterAsText(7)\n\n #### Create SSDataObject ####\n fieldList = [depVarName] + indVarNames\n ssdo = SSDO.SSDataObject(inputFC, templateFC = outputFC)\n \n #### Setup masterField for ssdo from Model weights file ####\n masterField1 = AUTILS.setUniqueIDField(ssdo, weightsFile)\n if masterField1 == None:\n ARCPY.AddError(\"The Model weights file format is not valid.\")\n raise SystemExit()\n \n #### Setup masterField for ssdo from Kernel weights file ####\n masterField2 = None\n wType = kernelWeightsFile[-3:].lower()\n if wType == \"kwt\" or wType == \"swm\":\n masterField2 = AUTILS.setUniqueIDField(ssdo, kernelWeightsFile)\n if masterField2 == None:\n ARCPY.AddError(\"The Kernel weights file format is not valid.\")\n raise SystemExit()\n \n #### Detect if Two Weights Files Are Matched (Same Unique Field) ####\n if masterField1 != masterField2:\n ARCPY.AddError(\"The Model weights file and Kernel weights file have \"\n \"different unique ID fields.\")\n raise SystemExit()\n \n #### Populate SSDO with Data ####\n ssdo.obtainData(masterField1, fieldList) \n\n #### Resolve Weights File ####\n patW = None\n patKW = None\n try:\n patW = AUTILS.PAT_W(ssdo, weightsFile)\n patKW = AUTILS.PAT_W(ssdo, kernelWeightsFile)\n except:\n ARCPY.AddError(\"There is an error occurred when read weights files.\")\n raise SystemExit()\n\n #### Run AutoSpace ####\n auto = AutoSpace_PySAL(ssdo, depVarName, indVarNames, patW, patKW, pValue,\n useCombo)\n\n #### Create Output ####\n auto.createOutput(outputFC)\n\n\nclass AutoSpace_PySAL(object):\n \"\"\"Computes linear regression via Ordinary Least Squares using PySAL.\"\"\"\n\n def __init__(self, ssdo, depVarName, indVarNames, patW, patKW, \n pValue = 0.01, useCombo = False):\n\n #### Set Initial Attributes ####\n UTILS.assignClassAttr(self, locals())\n\n #### Initialize Data ####\n self.initialize()\n\n #### Variables for Output ####\n self.oPredy = None\n self.oResid = None\n self.oPredy_e= None\n self.oE_Predy= None\n \n #### Calculate Statistic ####\n self.calculate()\n\n def initialize(self):\n \"\"\"Performs additional validation and populates the SSDataObject.\"\"\"\n\n ARCPY.SetProgressor(\"default\", (\"Starting to perform Automatic Model \"\n \"Search. Loading features...\"))\n \n #### Shorthand Attributes ####\n ssdo = self.ssdo\n\n #### MasterField Can Not Be The Dependent Variable ####\n if ssdo.masterField == self.depVarName:\n ARCPY.AddIDMessage(\"ERROR\", 945, ssdo.masterField, \n ARCPY.GetIDMessage(84112))\n raise SystemExit()\n\n #### Remove the MasterField from Independent Vars #### \n if ssdo.masterField in self.indVarNames:\n self.indVarNames.remove(ssdo.masterField)\n ARCPY.AddIDMessage(\"Warning\", 736, ssdo.masterField)\n\n #### Remove the Dependent Variable from Independent Vars ####\n if self.depVarName in self.indVarNames:\n self.indVarNames.remove(self.depVarName)\n ARCPY.AddIDMessage(\"Warning\", 850, self.depVarName)\n\n #### Raise Error If No Independent Vars ####\n if not len(self.indVarNames):\n ARCPY.AddIDMessage(\"Error\", 737)\n raise SystemExit()\n\n #### Create Dependent Variable ####\n self.allVars = [self.depVarName] + self.indVarNames\n self.y = ssdo.fields[self.depVarName].returnDouble()\n self.n = ssdo.numObs\n self.y.shape = (self.n, 1)\n\n #### Assure that Variance is Larger than Zero ####\n yVar = NUM.var(self.y)\n if NUM.isnan(yVar) or yVar <= 0.0:\n ARCPY.AddIDMessage(\"Error\", 906)\n raise SystemExit()\n\n #### Assure that p-Value is Between 0 and 1 ####\n if self.pValue <= 0 or self.pValue >= 1.0:\n ARCPY.AddIDMessage(\"Error\", 906)\n raise SystemExit()\n \n #### Create Design Matrix ####\n self.k = len(self.indVarNames) + 1\n self.x = NUM.ones((self.n, self.k - 1), dtype = float)\n for column, variable in enumerate(self.indVarNames):\n self.x[:,column] = ssdo.fields[variable].data\n\n #### Set Weights Info ####\n self.w = self.patW.w\n self.wName = self.patW.wName\n self.gwk = self.patKW.w\n self.gwkName = self.patKW.wName\n\n def calculate(self):\n \"\"\"Performs Auto Model and related diagnostics.\"\"\"\n\n ARCPY.SetProgressor(\"default\", \"Executing Automatic Model Search...\")\n \n #### Performance AutoModel #### \n autoTestResult = None\n try:\n autoTestResult = AUTILS.autospace(self.y, self.x, self.w, self.gwk,\n opvalue = self.pValue,\n combo = self.useCombo,\n name_y = self.depVarName,\n name_x = self.indVarNames,\n name_w = self.wName,\n name_gwk = self.gwkName,\n name_ds = self.ssdo.inputFC)\n except:\n import traceback\n ARCPY.AddError((\"There is an error occurred when automatically \"\n \"search spatial model. Details: \" + \\\n traceback.format_exc()))\n raise SystemExit()\n \n #### Extract final model from autoTestResult ####\n olsModel = autoTestResult['regression1']\n finalModel = autoTestResult['regression2']\n \n summary = None \n \n if autoTestResult[\"final model\"].startswith('No Space') or \\\n autoTestResult[\"final model\"].startswith('Robust'):\n self.oPredy = olsModel.predy\n self.oResid = olsModel.u\n summary = olsModel.summary\n \n elif autoTestResult[\"final model\"].startswith('Spatial Lag'):\n self.oPredy = finalModel.predy\n self.oResid = finalModel.u\n self.oPredy_e = finalModel.predy_e\n self.oE_Predy = finalModel.e_pred if finalModel.e_pred != None else \\\n NUM.ones(self.ssdo.numObs) * NUM.nan\n summary = finalModel.summary\n \n elif autoTestResult[\"final model\"].startswith('Spatial Error'):\n self.oPredy = finalModel.predy\n self.oResid = finalModel.u\n summary = finalModel.summary\n \n else:\n msg = (\"There is an error in Automatic Model Search. Please check \"\n \"the input setup and weights files.\")\n ARCPY.AddError(msg)\n raise SystemExit()\n \n #### Add \"Het\" in field name if \"hetroskedasticity\" in model ####\n if autoTestResult['heteroskedasticity'] == True:\n for i in range(len(FIELDNAMES)):\n FIELDNAMES[i] = \"Het\" + FIELDNAMES[i]\n \n #### Print model summary #### \n if finalModel:\n ARCPY.AddMessage(\"OLS diagnostics:\")\n ARCPY.AddMessage(olsModel.summary)\n ARCPY.AddMessage(\"\")\n \n msg = \"Final model:\" + autoTestResult[\"final model\"] \n ARCPY.AddMessage(msg)\n \n if summary:\n ARCPY.AddMessage(summary)\n \n def createOutput(self, outputFC):\n\n #### Build fields for output table ####\n self.templateDir = OS.path.dirname(SYS.argv[0])\n candidateFields = {}\n candidateFields[FIELDNAMES[0]] = SSDO.CandidateField(FIELDNAMES[0],\n \"Double\", \n self.oPredy)\n candidateFields[FIELDNAMES[1]] = SSDO.CandidateField(FIELDNAMES[1],\n \"Double\", \n self.oResid)\n if self.oPredy_e != None: \n candidateFields[FIELDNAMES[2]] = SSDO.CandidateField(FIELDNAMES[2],\n \"Double\", \n self.oPredy_e)\n if self.oE_Predy != None:\n candidateFields[FIELDNAMES[3]] = SSDO.CandidateField(FIELDNAMES[3],\n \"Double\", \n self.oE_Predy)\n\n self.ssdo.output2NewFC(outputFC, candidateFields, \n appendFields = self.allVars)\n\n #### Set the Default Symbology ####\n params = ARCPY.gp.GetParameterInfo()\n try:\n renderType = UTILS.renderType[self.ssdo.shapeType.upper()]\n if renderType == 0:\n renderLayerFile = \"ResidPoints.lyr\"\n elif renderType == 1:\n renderLayerFile = \"ResidPolylines.lyr\"\n else:\n renderLayerFile = \"ResidPolygons.lyr\"\n if FIELDNAMES[0].startswith('Het'):\n renderLayerFile = \"Het\" + renderLayerFile\n fullRLF = OS.path.join(self.templateDir, \"Layers\", renderLayerFile)\n params[7].Symbology = fullRLF\n except:\n ARCPY.AddIDMessage(\"WARNING\", 973)\n\nif __name__ == '__main__':\n setupParameters()","sub_path":"Scripts/AutoModel.py","file_name":"AutoModel.py","file_ext":"py","file_size_in_byte":10383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"336259700","text":"# 客户端每次行动后都挂起,等待服务器发回确认消息后继续行动\r\n\r\nMsgDefine = {\r\n\t# ===========================================\r\n\t# 游戏状态消息\r\n\t# ===========================================\r\n\t# 欢迎信息 如果客户端可以直接获取自己的Hid,就可以删掉这个��息\r\n\t\"sc_welcome\":{\"chid\":\"I\"},\r\n\t# 发送玩家数据\r\n\t\"sc_playerInfo\":{'nickname':'s','hid':'I','win':'I', 'lose':'I', 'draw':'I', 'breakC':'I'},\r\n\t# 客户端准备状态更改\r\n\t\"cs_setReady\":{\"isReady\":\"i\"},\r\n\t# 状态更改确认\r\n\t\"sc_playerReady\":{\"hid\":\"i\", \"isReady\":\"i\"},\r\n\t# 客户端请求离开\r\n\t\"cs_reqLeave\":{},\r\n\t# 客户端认输\r\n\t\"cs_reqBreak\":{},\r\n\t# 客户端离开\r\n\t\"sc_playerLeft\":{\"chid\":\"I\"},\r\n\t# 游戏结束\r\n\t\"sc_gameOver\":{\"winHid\":\"i\"},\r\n\t\r\n\t# ===========================================\r\n\t# 游戏逻辑消息 - 自方\r\n\t# 每次收到客户端的逻辑操作后,剥夺其操作权\r\n\t# 服务端回发某些验证结果时,捎带授予操作权\r\n\t# ===========================================\r\n\t# 准备棋子 s的长度是棋子的数量\r\n\t\"sc_this_prepBubs\":{'colors':'s'},\r\n\t# 移动 消息对象包含路径点\r\n\t\"cs_this_move\":{'points':\"s\"},\r\n\t# 确认移动\r\n\t\"sc_this_move\":{\"isOK\":\"i\"},\r\n\t# 请求放置\r\n\t\"cs_this_reqPut\":{},\r\n\t# 消除 lineInfo 依次是起点终点对的xy坐标,4个长度一组\r\n\t\"cs_this_remove\":{\"lineInfo\":'s'},\r\n\t# 确认消除\r\n\t\"sc_this_remove\":{\"isOK\":\"i\",\"score\":\"i\"},\r\n\t# 放置棋子 放置棋子数量是positions的长度除以2\r\n\t\"sc_this_putBubs\":{'positions':'s'},\r\n\t\r\n\t# ===========================================\r\n\t# 游戏逻辑消息 - 对方\r\n\t# 每次收到客户端的逻辑操作后,剥夺其操作权\r\n\t# 服务端回发某些验证结果时,捎带授予操作权\r\n\t# ===========================================\r\n\t# 准备棋子\r\n\t\"sc_that_prepBubs\":{\"colors\":\"s\"},\r\n\t# 移动棋子\r\n\t\"sc_that_move\":{'points':\"s\"},\r\n\t# 消除棋子\r\n\t\"sc_that_remove\":{\"lineInfo\":\"s\", \"score\":\"i\"},\r\n\t# 放置棋子\r\n\t\"sc_that_putBubs\":{\"positions\":\"s\"}\r\n}","sub_path":"BufanServer/Message.py","file_name":"Message.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"377457716","text":"import os\r\nimport shutil\r\nimport sys\r\nimport cv2\r\n\r\n\r\n# enhancement 1\r\ndef get_file_and_destination():\r\n input_file = input(\"What is the file name?\")\r\n mp4_converter = \".mp4\"\r\n input_file = input_file + mp4_converter\r\n\r\n destination_file = input(\"Where you want to save it to?\")\r\n return input_file, destination_file\r\n\r\n\r\n# enhancement 2\r\ndef get_user_input():\r\n user_preference = input(\"Enter your frame preference in total: \")\r\n if not user_preference.isnumeric():\r\n print(\"Please enter an integer!\")\r\n new_value = get_user_input()\r\n user_preference = new_value\r\n return user_preference\r\n\r\n\r\nclass FrameCapture:\r\n \"\"\"\r\n Class definition to capture frames\r\n \"\"\"\r\n\r\n # changed the parameters in order for user to give his own directory name\r\n def __init__(self, file_path, directory):\r\n \"\"\"\r\n initializing directory where the captured frames will be stored.\r\n Also truncating the directory where captured frames are stored, if exists.\r\n \"\"\"\r\n self.directory = directory\r\n self.file_path = file_path\r\n if os.path.exists(self.directory):\r\n shutil.rmtree(self.directory)\r\n os.mkdir(self.directory)\r\n\r\n def capture_frames(self):\r\n '''\r\n This method captures the frames from the video file provided.\r\n This program makes use of openCV library\r\n '''\r\n cv2_object = cv2.VideoCapture(self.file_path)\r\n\r\n frame_number = 0\r\n frame_found = 1\r\n # gets user preference\r\n get_value = get_user_input()\r\n while frame_found:\r\n frame_found, image = cv2_object.read()\r\n # will only get the range of what the user wants to collect\r\n while frame_number < int(get_value):\r\n capture = f'{self.directory}/frame{frame_number}.jpg'\r\n cv2.imwrite(capture, image)\r\n # will print the number out when collected\r\n print(f\"Collected Frame Number: {frame_number}\")\r\n frame_number += 1\r\n # thank you message and the loop will end\r\n print(\"Thank you!\")\r\n break\r\n\r\n\r\nif __name__ == '__main__':\r\n file_path, destination = get_file_and_destination()\r\n print(file_path)\r\n print(destination)\r\n\r\n fc = FrameCapture(file_path, destination)\r\n fc.capture_frames()\r\n","sub_path":"projects/Capture_Video_Frames/my_enhancement.py","file_name":"my_enhancement.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"578564512","text":"'''\n@Description: \n@version: \n@Author: chenhao\n@Date: 2020-03-16 14:55:47\n@LastEditors: chenhao\n@LastEditTime: 2020-03-16 16:51:03\n'''\n\n\"\"\"\nGiven a binary tree, return the inorder traversal of its nodes' values.\n\nExample:\nInput: [1,null,2,3]\n 1\n \\\n 2\n /\n 3\nOutput: [1,3,2]\n\nFollow up: Recursive solution is trivial, could you do it iteratively?\n\"\"\"\n\nfrom typing import List\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def inorderTraversal(self, root: TreeNode) -> List[int]:\n nodeStack = []\n valList = []\n cur = root\n while nodeStack or cur:\n while cur:\n nodeStack.append(cur)\n cur = cur.left\n cur = nodeStack.pop()\n valList.append(cur.val)\n cur = cur.right\n return valList \n \n \n def inorderTraversal(self, root: TreeNode) -> List[int]:\n WHITE, GRAY = 0, 1\n valList = []\n nodeStack = []\n nodeStack = [(WHITE, root)]\n while nodeStack:\n color, node = nodeStack.pop()\n if not node: continue\n if color == WHITE:\n nodeStack.append((WHITE, node.right))\n nodeStack.append((GRAY, node))\n nodeStack.append((WHITE, node.left))\n else:\n valList.append(node.val)\n return valList\n \n\n\nif __name__==\"__main__\":\n node1 = TreeNode(2)\n node2 = TreeNode(3)\n node3 = TreeNode(1)\n \n node1.left = node2\n node2.left = node3\n \n s = Solution()\n print(s.inorderTraversal(node1))","sub_path":"4_Tree/Preorder-Inorder-Postorder Traversal/094. Binary Tree Inorder Traversal.py","file_name":"094. Binary Tree Inorder Traversal.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"247278368","text":"import random\r\nimport tkinter as tk\r\nimport time\r\nfrom random import randint\r\nclass UI():\r\n #setup makes main window\r\n def __init__(self, main):\r\n self.main = main\r\n ##self.output = tk.Label(main, anchor = 'nw', justify = 'left')\r\n self.inpt = tk.Text(main, height = 1,fg='#22ee22', background = '#003000')\r\n self.enterbut = tk.Button(main, text='Enter',fg='#22ee22', background = '#000100', height = 1, command = lambda:( self.enter(self.inpt,self.inpt.get('1.0','end')) ))\r\n self.text = ''\r\n\r\n # self.situation = [\"You stand in an empty room. There is a door ahead of you and a door behind you\", [\"Try north door\", \"Try south door\", \"Other\"]]\r\n \r\n \r\n \r\n self.main.geometry(\"850x700\")\r\n self.main.config(background ='#000800')\r\n\r\n #Big output text box. Disabled so cannot be typed in.\r\n #rel-x,y,height,width are relative placement for window\r\n #self.output = tk.Label(main, anchor = 'nw', justify = 'left')\r\n self.output = tk.Label(main, anchor = 'nw', justify = 'left', font = ('Courier New', 9), fg='#22ee22', bg='#000800')\r\n self.output.place(relx =0.2, rely = 0.02, relheight=0.6, relwidth=0.8)\r\n\r\n #Input box\r\n #calls 'enter' on key press return/enter key\r\n \r\n self.inpt.bind(\"\", lambda x: self.enter(self.inpt,self.inpt.get('1.0','end-1c')))\r\n self.inpt.place(relx =0.2, rely = 0.65, relwidth=0.5)\r\n #enter is called with the .get() which takes from the ext box.\r\n # 1.0 is line.character, so line-1.position=0\r\n # end is end if text box, -1c is less 1 character (can be written as -1character)\r\n # 'end-1c' as oppose to 'end' ommits end \\n from typed enter key\r\n\r\n # self.fightBTN = t\r\n\r\n #button that calls 'enter' same as above, save for not having the -1c after 'end' as no \\n is typed (hope this makes sense)\r\n \r\n self.enterbut.place(relx = 0.71, rely = 0.645, relwidth = 0.09)\r\n\r\n\r\n #write fucntion takes text and the textbox it's from \r\n def enter(self,inpt,txt):\r\n txt = self.cleanInput(txt)\r\n self.cleanOutput()\r\n if isinstance(txt,str):\r\n \r\n \r\n txt = txt.replace('\\n','')\r\n\r\n if txt == 't':\r\n ui.talkWindow(jeremy,C1)\r\n if txt == 'g':\r\n ui.gunWindow(None,None)\r\n \r\n ui.write('\\n')\r\n txt = txt+'\\n'\r\n for i in txt:\r\n #Types to the end of textbox with value i\r\n self.text += i\r\n self.output.config(text = self.text)\r\n\r\n self.inpt.delete('end-2c','end-1c')\r\n #sleep for that cool typing effect\r\n ## time.sleep(0.03)\r\n #tkinter is shit\r\n self.main.update()\r\n #scrolls output to bottom (without its not possible to scroll at all, its odd) \r\n #makes sure input is empt but is currently buggy not sure why, seems to automatically lead with a \\n or ' ' weird ass shit\r\n Interpret(txt,jeremy)\r\n self.inpt.delete('0.0','end')\r\n #disable output so cannot be typed in\r\n else:\r\n pass\r\n \r\n def write(self,txt):\r\n txt = str(txt)\r\n txt = self.cleanInput(txt)\r\n self.cleanOutput() \r\n txt+='\\n'\r\n self.inpt.config(state = 'disabled')\r\n for i in txt:\r\n self.text += i\r\n self.output.config(text = self.text)\r\n ## time.sleep(0.05)\r\n #tkinter is shit\r\n self.main.update()\r\n self.inpt.config(state = 'normal')\r\n \r\n\r\n def cleanOutput(self):\r\n while self.text.count('\\n')>23:\r\n cutof = self.text.index('\\n')+1\r\n self.text = self.text[cutof:]\r\n\r\n def cleanInput(self,txt):\r\n if isinstance(txt,str):\r\n if len(txt)>0:\r\n if txt[0] == '\\n':\r\n txt = txt[1:]\r\n n = 0\r\n for i in range(len(txt)):\r\n if txt[i] != '\\n':\r\n n+=1\r\n else:\r\n n = 0\r\n \r\n if n > 80 and txt[i] == ' ': #arbriaty number\r\n n = 0\r\n txt = txt[:i] + '\\n' + txt[i+1:]\r\n elif n > 95:\r\n n = 0\r\n txt = txt[:i] + '-\\n' + txt[i:]\r\n return(txt)\r\n\r\n def talkWindow(ui,player,npc):\r\n talkUi = TalkUi(main,player,npc)\r\n def gunWindow(ui,player,enemy):\r\n gunUi = GunUi(main,player,enemy)\r\n\r\n\r\n\r\n\r\nclass TalkUi():\r\n def __init__(self, main,player,npc):\r\n self.text =''\r\n self.main = tk.Toplevel(main) \r\n self.main.geometry(\"600x500\")\r\n self.main.config(background ='#001100')\r\n\r\n self.output = tk.Label(self.main, anchor = 'nw', justify = 'left')\r\n self.output.place(relx =0.2, rely = 0.02, relheight=0.6, relwidth=0.6)\r\n\r\n self.talkBTN = tk.Button(self.main, text='Talk', background = 'light blue', height = 2, command = lambda:(self.TalkEnter(self.inpt,self.inpt.get('1.0','end'),npc) ))\r\n # self.\r\n \r\n self.inpt = tk.Text(self.main, height = 1)\r\n self.inpt.bind(\"\", lambda x: self.TalkEnter(self.inpt,self.inpt.get('1.0','end-1c'),npc))\r\n self.inpt.bind(\"\", lambda x:self.inpt.delete('0.0','end+2c'))\r\n self.inpt.place(relx =0.36, rely = 0.65, relwidth=0.25)\r\n self.conversationBegin(npc)\r\n\r\n self.mood = [' angry at ',' unhapy with ',' taken aback by ',' fine with ',' happy with ',' enthusiastic with ', ' ecstatic at ']\r\n \r\n self.prevWord = 'start'\r\n\r\n def conversationBegin(self,npc):\r\n self.TalkWrite('You enter conversation with a '+npc.desc)\r\n self.TalkWrite(npc.name+ ': ' + npc.talk['start'][0])\r\n self.inConversation = True\r\n\r\n\r\n\r\n def reply(self,npc,word):\r\n if self.inConversation:\r\n if word in npc.talk:\r\n if npc.interest + npc.talk[word][1][0] < 7:\r\n npc.interest += npc.talk[word][1][0]\r\n else:\r\n npc.interest = 6\r\n if npc.interest + npc.talk[word][1][0] < 0:\r\n self.TalkWrite('That seems to have struck a nerve with %s, they turn away. This conversation is clearly over.'%npc.name)\r\n self.inConversation = False\r\n else: \r\n self.TalkWrite(npc.name+ ' seems' +self.mood[npc.interest] +'your response')\r\n self.TalkWrite(npc.name+ ': ' + npc.talk[word][0])\r\n self.prevWord = word\r\n \r\n if word not in npc.talk:\r\n if npc.talk[self.prevWord][1][1] != 0:\r\n npc.interest += npc.talk[self.prevWord][1][1]\r\n if npc.interest >-1:\r\n self.TalkWrite(npc.name+ ' seems' +self.mood[npc.interest] +'your response')\r\n else:\r\n self.TalkWrite(npc.name +' has had enough of you. This conversation is clearly over')\r\n self.inConversation = False\r\n else:\r\n self.TalkWrite(npc.name + ' didn\\'t understand you, but they didn\\'t seem to care. They are still' + self.mood[npc.interest] +'you.')\r\n\r\n\r\n\r\n\r\n\r\n def TalkEnter(self,inpt,txt,npc):\r\n \r\n txt = txt.replace('\\n','')\r\n if txt[-1] in ('?','.',' ','\\n'):\r\n txt = txt[:-1]\r\n if txt[0] == ' ':\r\n txt = txt[1:]\r\n txt = self.cleanInput(txt)\r\n self.cleanOutput()\r\n txt = txt+'\\n'\r\n for i in txt:\r\n self.text += i\r\n self.output.config(text = self.text)\r\n \r\n self.inpt.delete('end-2c','end-1c')\r\n time.sleep(0.01)\r\n #tkinter is shit\r\n self.main.update()\r\n txt = txt.replace('\\n','')\r\n self.reply(npc,txt)\r\n self.inpt.delete('0.0','end')\r\n\r\n \r\n def TalkWrite(self,txt):\r\n txt = self.cleanInput(txt)\r\n self.cleanOutput()\r\n txt+='\\n'\r\n self.inpt.config(state = 'disabled')\r\n for i in txt:\r\n self.text += i\r\n self.output.config(text = self.text)\r\n time.sleep(0.03)\r\n #tkinter is shit\r\n self.main.update()\r\n self.inpt.config(state = 'normal')\r\n\r\n def cleanOutput(self):\r\n if self.text.count('\\n')>16:\r\n cutof = self.text.index('\\n')+1\r\n self.text = self.text[cutof:]\r\n\r\n def cleanInput(self,txt):\r\n if isinstance(txt,str):\r\n if len(txt)>0:\r\n if txt[0] == '\\n':\r\n txt = txt[1:]\r\n n = 0\r\n for i in range(len(txt)):\r\n if txt[i] != '\\n':\r\n n+=1\r\n else:\r\n n = 0\r\n \r\n if n > 50 and txt[i] == ' ': #arbriaty number\r\n n = 0\r\n txt = txt[:i] + '\\n' + txt[i+1:]\r\n elif n >65:\r\n n = 0\r\n txt = txt[:i] + '-\\n' + txt[i:]\r\n return(txt)\r\n\r\nmain = tk.Tk()\r\nui = UI(main)\r\n\r\nclass GunUi():\r\n def __init__(self, main,player,enemy):\r\n self.text =''\r\n self.main = tk.Toplevel(main) \r\n self.main.geometry(\"600x500\")\r\n self.main.config(background ='#000000')\r\n self.main.focus_set()\r\n self.playerbtns = [[],[],[],[]]\r\n self.enemybtns = [[],[],[],[]]\r\n\r\n self.info = tk.Label(self.main,bg ='black',fg = '#22ee22', text = 'Arrows to move, \\n space to skip moving,\\n space to target, space to untarget,\\n enter to attack, shift+r to reset')\r\n self.info.place(y = 150, x = 205)\r\n\r\n self.playerHits = tk.Label(self.main,bg ='black',fg = '#22ee22', text = 'Total Hits: 0\\nDirect Hits: 0\\nDamage Percentage: -%')\r\n self.playerHits.place(x = 50,y=320)\r\n self.enemyHits = tk.Label(self.main,bg ='black',fg = '#22ee22',text = 'Total Hits: 0\\nDirect Hits: 0\\nDamage Percentage: -%')\r\n self.enemyHits.place(x = 400,y=320)\r\n \r\n self.playerGridSize = 4\r\n for j in range (self.playerGridSize):\r\n for i in range(self.playerGridSize):\r\n self.topRow = tk.Button(self.main,height = 2, width = 4,bg = '#000000')\r\n self.topRow.place(y = 150+(40*j), x = 50+(37*i))\r\n self.playerbtns[j].append(self.topRow)\r\n self.enemyGridSize = 4\r\n for j in range (self.enemyGridSize):\r\n for i in range(self.enemyGridSize):\r\n self.topRow = tk.Button(self.main,height = 2, width = 4, bg = '#000000')\r\n self.topRow.place(y = 150+(40*j), x = 400+(37*i))\r\n self.enemybtns[j].append(self.topRow)\r\n\r\n\r\n self.enemyCharacter = [randint(0,self.enemyGridSize-1),randint(0,self.enemyGridSize-1)]\r\n self.numberEnemyMove = []\r\n\r\n \r\n self.moving = True\r\n self.attackPhase = False\r\n self.playerPos = [0,0]\r\n self.targetPos = [0,0]\r\n self.moves = []\r\n self.enemyMoves = []\r\n self.numberEnemyMove = 0\r\n self.targeted = []\r\n self.playerbtns[self.playerPos[0]][self.playerPos[1]].config(background = 'green')\r\n\r\n self.playerCanTarget = 4\r\n \r\n self.enemyMovement = 3\r\n self.enemyCanTarget = 4\r\n \r\n self.playerDarkGreenHits = 0\r\n self.playerLightGreenHits = 0\r\n\r\n self.enemyDarkBlueHits = 0\r\n self.enemyLightBlueHits = 0\r\n\r\n \r\n\r\n \r\n## self.me = tk.Button(self.main,height = 1, width = 2)\r\n## self.me.place(x = 5,y=10)\r\n #self.talkBTN = tk.Button(self.main, text='Talk', background = 'light blue', height = 2, command = lambda:(self.TalkEnter(self.inpt,self.inpt.get('1.0','end'),npc) ))\r\n # self.\r\n \r\n #self.inpt = tk.Text(self.main, height = 1)\r\n #self.inpt.bind(\"\", lambda x: self.TalkEnter(self.inpt,self.inpt.get('1.0','end-1c'),npc))\r\n #self.inpt.bind(\"\", lambda x:self.inpt.delete('0.0','end+2c'))\r\n #self.inpt.place(relx =0.36, rely = 0.65, relwidth=0.25)\r\n\r\n\r\n #self.btns[0][3].config(background = 'black')\r\n\r\n##\r\n self.main.bind(\"\", lambda x:self.PlayerMove([0,-1]))\r\n self.main.bind(\"\", lambda x:self.PlayerMove([0,1]))\r\n self.main.bind(\"\", lambda x:self.PlayerMove([-1,0]))\r\n self.main.bind(\"\", lambda x:self.PlayerMove([1,0]))\r\n self.main.bind(\"\",lambda x:self.PlayerTarget())\r\n self.main.bind(\"\",lambda x:self.EnemyMove())\r\n self.main.bind(\"\",lambda x:self.Reset()) ## To Remove ToDO\r\n\r\n\r\n def Reset(self):\r\n if len( self.enemyMoves)>0: \r\n self.enemyCharacter = [self.enemyMoves[-1][0],self.enemyMoves[-1][1]]\r\n else:\r\n self.enemyCharacter = [randint(0,self.enemyGridSize-1),randint(0,self.enemyGridSize-1)]\r\n self.numberEnemyMove = []\r\n \r\n for lst in self.enemybtns:\r\n for btn in lst:\r\n btn.config(bg='#000000')\r\n for lst in self.playerbtns:\r\n for btn in lst:\r\n btn.config(bg='#000000')\r\n \r\n self.moving = True\r\n self.attackPhase = False\r\n self.targetPos = [0,0]\r\n self.moves = []\r\n self.enemyMoves = []\r\n self.numberEnemyMove = 0\r\n self.targeted = []\r\n self.playerbtns[self.playerPos[0]][self.playerPos[1]].config(background = 'green')\r\n\r\n \r\n \r\n self.playerDarkGreenHits = 0\r\n self.playerLightGreenHits = 0\r\n\r\n self.enemyDarkBlueHits = 0\r\n self.enemyLightBlueHits = 0\r\n\r\n \r\n def PlayerMove(self,direction):\r\n if not self.attackPhase:\r\n if len(self.moves) >= 3:\r\n self.moving = False\r\n if self.moving:\r\n if self.playerPos[0] + direction[0] >= 0 and self.playerPos[0] + direction[0] < self.playerGridSize and self.playerPos[1] + direction[1] >= 0 and self.playerPos[1] + direction[1] < self.playerGridSize: \r\n self.playerbtns[self.playerPos[0]][self.playerPos[1]].config(background = '#62ff3f')\r\n self.playerPos[0]+=direction[0]\r\n self.playerPos[1]+=direction[1]\r\n self.moves.append(direction)\r\n self.playerbtns[self.playerPos[0]][self.playerPos[1]].config(background = 'green')\r\n if len(self.moves) == 3:\r\n self.enemybtns[0][0].config(bg = 'blue')\r\n self.main.update()\r\n else: \r\n if self.targetPos[0] + direction[0] >= 0 and self.targetPos[0] + direction[0] < self.playerGridSize and self.targetPos[1] + direction[1] >= 0 and self.targetPos[1] + direction[1] < self.playerGridSize:\r\n if [self.targetPos[0],self.targetPos[1]] not in self.targeted:\r\n self.enemybtns[self.targetPos[0]][self.targetPos[1]].config(background = '#000000')\r\n self.targetPos[0]+=direction[0]\r\n self.targetPos[1]+=direction[1]\r\n if [self.targetPos[0],self.targetPos[1]] not in self.targeted:\r\n self.enemybtns[self.targetPos[0]][self.targetPos[1]].config(background = 'blue')\r\n self.main.update()\r\n \r\n def PlayerTarget(self):\r\n if not self.attackPhase:\r\n if self.moving:\r\n self.moving = False\r\n self.enemybtns[0][0].config(bg = 'blue')\r\n else:\r\n if self.targetPos not in self.targeted and len(self.targeted) = 0 and enemyPos[0] + direction[0] < self.enemyGridSize and enemyPos[1] + direction[1] >= 0 and enemyPos[1] + direction[1] < self.enemyGridSize and(enemyPos[0]+direction[0]!=self.enemyCharacter[0] or enemyPos[1]+ direction[1]!=self.enemyCharacter[1]):\r\n self.numberEnemyMove+=1\r\n enemyPos[0]+=direction[0]\r\n enemyPos[1]+=direction[1] # enemy\r\n for item in self.enemyMoves:\r\n self.enemybtns[item[0]][item[1]].config(bg = '#7caeff')#light blue\r\n self.enemybtns[enemyPos[0]][enemyPos[1]].config(bg = 'blue')\r\n self.enemyMoves.append(enemyPos[:])\r\n self.main.update()\r\n time.sleep(1)\r\n break\r\n else:\r\n rand+=1\r\n direction = directions[rand][:]\r\n for item in self.enemyMoves:\r\n self.enemybtns[item[0]][item[1]].config(bg = '#7caeff')\r\n self.enemybtns[self.enemyMoves[-1][0]][self.enemyMoves[-1][1]].config(bg = 'blue')\r\n self.PlayerAttack()\r\n self.EnemyAttack() \r\n self.Damage()\r\n\r\n\r\n def Damage(self):\r\n\r\n if len(self.moves) == 0:\r\n self.playerDamagePercent =self.playerDarkGreenHits\r\n else:\r\n self.playerDamagePercent = (self.playerDarkGreenHits*(1-len(self.moves)/6) + self.playerLightGreenHits/6)#len(self.moves)*(1-(1-len(self.moves)/6)) # Fuckin headache right\r\n \r\n## if len(str(self.playerDamagePercent)) > 5:\r\n## self.playerDamagePercent = str(self.playerDamagePercent)[:6]\r\n \r\n \r\n newPText = 'Total Hits: %s\\nDirect Hits: %s\\nDamage Percentage: %.2f%s'%((self.playerLightGreenHits+self.playerDarkGreenHits),self.playerDarkGreenHits,(self.playerDamagePercent*100),'%')\r\n\r\n self.playerHits.config(text =newPText)\r\n\r\n if self.numberEnemyMove == 0:\r\n self.playerDamagePercent =self.playerDarkGreenHits\r\n else:\r\n self.enemyDamagePercent = (self.enemyDarkBlueHits*(1-self.numberEnemyMove/6) + self.enemyLightBlueHits/6)\r\n\r\n## if len(str(self.enemyDamagePercent)) > 5:\r\n## self.enemyDamagePercent =str(self.enemyDamagePercent)[:6]\r\n newEText = 'Total Hits: %s\\nDirect Hits: %s\\nDamage Percentage: %.2f%s'%((self.enemyDarkBlueHits+self.enemyLightBlueHits),self.enemyDarkBlueHits,(self.enemyDamagePercent*100),'%')\r\n self.enemyHits.config(text =newEText)\r\n\r\n\r\nclass Place(object):\r\n def __init__(self, name, quality = 3, furnishings = [], objects = [], characters = [],search = \"an empty room\", investigation = \"nothing of note here visually\"):\r\n self.doors = []\r\n self.name = name\r\n #should be of the format [canBeEntered, Description, leadsTo]\r\n #and because a room can have multiple doors, it'll be a 2D array\r\n self.quality = quality\r\n self.furnishings = furnishings\r\n self.objects = objects\r\n self.characters = characters\r\n\r\n self.search = search\r\n\r\n self.investigation = investigation\r\n #should be of the form [canBeInvestigated, Description, leadsTo]\r\n #'cept obviously you still get a description if you can't\r\n\r\n for furnishing in self.furnishings:\r\n furnishing.room = self\r\n\r\n for character in self.characters:\r\n character.room = self\r\n\r\n def EnteredRoom(self): #Called as player enters room - wakes the room up and lets npcs interact with the room \r\n for character in self.characters:\r\n character.Initialise()\r\n \r\n \r\n def showAll(self):\r\n temp = []\r\n tempTemp = []\r\n for furnishing in self.furnishings:\r\n if not furnishing.hidden:\r\n tempTemp.append(furnishing.name)\r\n temp.append(tempTemp)\r\n \r\n tempTemp = []\r\n for anObject in self.objects:\r\n if not anObject.hidden:\r\n tempTemp.append(anObject.name)\r\n temp.append(tempTemp)\r\n\r\n tempTemp = []\r\n for character in self.characters:\r\n if not character.hidden:\r\n tempTemp.append(character.basicDesc)\r\n temp.append(tempTemp)\r\n\r\n tempTemp = []\r\n for door in self.doors:\r\n if not door.hidden:\r\n tempTemp.append(door.name)\r\n temp.append(tempTemp)\r\n\r\n return temp\r\n\r\n def showAllObjects(self): #ToDo make this cleaner\r\n temp = []\r\n tempTemp = []\r\n for furnishing in self.furnishings:\r\n if not furnishing.hidden:\r\n tempTemp.append(furnishing)\r\n temp.append(tempTemp)\r\n \r\n tempTemp = []\r\n for anObject in self.objects:\r\n if not anObject.hidden:\r\n tempTemp.append(anObject)\r\n temp.append(tempTemp)\r\n\r\n tempTemp = []\r\n for character in self.characters:\r\n if not character.hidden:\r\n tempTemp.append(character)\r\n temp.append(tempTemp)\r\n\r\n tempTemp = []\r\n for door in self.doors:\r\n if not door.hidden:\r\n tempTemp.append(door)\r\n temp.append(tempTemp)\r\n\r\n return temp\r\n\r\n def showAllInvObjects(self):\r\n objList = [[],[]]\r\n for item in jeremy.inventory:\r\n objList[0].append(item.name)\r\n objList[1].append(item)\r\n return(objList)\r\n\r\n def showAllObjectsAndNames(self):\r\n temp1 = self.showAll()\r\n temp2 = self.showAllObjects()\r\n invObjects = self.showAllInvObjects()\r\n temp3 = []\r\n for i in range(len(temp1)):\r\n temp3.append([temp1[i],temp2[i]])\r\n return temp3,[invObjects]\r\n \r\n \r\n\r\n\r\n def DescribeRoom(self):\r\n \r\n roomDescription = \"\"\r\n roomDescription += \"The room is \" + self.search + \". \"\r\n roomDescription += \"There is \"+self.investigation+\".\\n\"\r\n randomSense = random.randint(0,3)\r\n if randomSense == 0:\r\n roomSight = []\r\n f = open(\"senses\\\\sights1.txt\", \"r\")\r\n for row in f:\r\n roomSight.append(row)\r\n f.close()\r\n\r\n roomDescription += roomSight[self.quality-1]\r\n\r\n elif randomSense == 1:\r\n roomSound = []\r\n f = open(\"senses\\\\sounds1.txt\", \"r\")\r\n for row in f:\r\n roomSound.append(row)\r\n f.close()\r\n\r\n roomDescription += roomSound[self.quality-1]\r\n\r\n\r\n elif randomSense == 2:\r\n roomFeel = []\r\n f = open(\"senses\\\\feels1.txt\", \"r\")\r\n for row in f:\r\n roomFeel.append(row)\r\n f.close()\r\n\r\n roomDescription += roomFeel[self.quality-1]\r\n \r\n \r\n else:\r\n roomSmell = []\r\n f = open(\"senses\\\\smells1.txt\", \"r\")\r\n for row in f:\r\n roomSmell.append(row)\r\n f.close()\r\n\r\n roomDescription += roomSmell[self.quality-1]\r\n\r\n \r\n \r\n if len(self.furnishings) > 0:\r\n roomDescription += \"The room is furnished with \"\r\n for furnishing in self.furnishings:\r\n roomDescription += \"a \" +furnishing.name + \", \"\r\n\r\n roomDescription = roomDescription[:-2] + \". \"\r\n \r\n\r\n if len(self.objects) > 0:\r\n roomDescription += \"In the room, there is \"\r\n for roomObject in self.objects:\r\n if roomObject.hidden == False:\r\n roomDescription += roomObject.basicDesc+\", \"\r\n roomDescription = roomDescription[:-2] + \". \"\r\n\r\n \r\n if len(self.characters) > 0:\r\n roomDescription += \"You are not alone in the room, you can see \"\r\n for character in self.characters:\r\n if character.hidden == False:\r\n roomDescription += character.basicDesc\r\n if character.doing[0] != '':\r\n roomDescription += \", the %s appears to be %s the %s. \"%(character.name,character.doing[0],character.doing[1].name)\r\n else:\r\n roomDescription+=\".\"\r\n\r\n for door in self.doors:\r\n if door.hidden == False:\r\n roomDescription += \"There is a door to the \" + door.name[:-5] + \". \"\r\n return roomDescription\r\n \r\n \r\nclass Door(object):\r\n def __init__(self, doorID, room1, room2, direction, locked = [False,[],False], blocked = [False,None], opened=False, seeThrough = True, description = 'A basic, nondescript door. It looks quite old.', hidden = False):\r\n self.doorID = doorID\r\n self.room1 = room1\r\n self.room2 = room2\r\n self.name = \"\"\r\n self.description = description\r\n self.opened = opened\r\n self.locked = locked\r\n self.blocked = blocked\r\n \r\n\r\n self.canOpen = self.locked[0] or self.blocked[0]\r\n #if it's locked, and if so, what's used to unlock it\r\n \r\n self.seeThrough = seeThrough\r\n #If door is open, can player see into the connected room\r\n\r\n self.hidden = hidden\r\n self.direction = direction\r\n self.directionList = ['north door','east door','south door','west door']\r\n self.opositeDirectionList = ['south door','west door','north door','east door']\r\n self.name = self.directionList[self.direction]\r\n self.basicDesc = \"a \"+self.name\r\n #the direction RELATIVE TO ROOM1\r\n\r\n def goThrough(self, player):\r\n if player.currentRoom == self.room1:\r\n player.currentRoom = self.room2\r\n self.name = self.opositeDirectionList[self.direction]\r\n else:\r\n player.currentRoom = self.room1\r\n self.name = self.directionList[self.direction]\r\n player.MovedRoom()\r\n\r\n##all mentioned direction relative to the centre of the room\r\n##0 is south\r\n##2 is north\r\n##1 is west\r\n##3 is east\r\n##4 is above\r\n##5 is below\r\n##others might be added at some point if jake yaks at me enough\r\n##\r\n##and obviously for an overworld this either ain't gonna be necessary or will need to be changed, but we'll get to that\r\n\r\n\r\n def Open(self, openTool,traveling):\r\n\r\n if self.opened == True:\r\n ui.write(\"The door is already open.\")\r\n \r\n elif self.opened == False and self.locked[0] == False and self.blocked[0] == False:\r\n self.opened = True\r\n ui.write(\"The \" + self.name + \" is not locked. You open it.\")\r\n \r\n elif self.locked[0] == True and self.opened == False and self.blocked[0] == False:\r\n if openTool is not None and openTool != '':\r\n self.Unlock(openTool)\r\n elif self.locked[0] == True and self.blocked[0] == False:\r\n ui.write(\"The door is locked, or perhaps it is only stuck. You can't get it open anyhow.\")\r\n\r\n if self.blocked[0]:\r\n ui.write(\"The door is blocked by %s. You can't get close to it.\"%self.blocked[1].name)\r\n \r\n if self.opened and not traveling: \r\n if jeremy.currentRoom.name != self.room1.name and self.seeThrough:\r\n ui.write('Through this door you can make out %s.'%self.room1.search)\r\n elif jeremy.currentRoom.name != self.room2.name and self.seeThrough:\r\n ui.write('Through this door you can see %s.'%self.room2.search)\r\n else:\r\n ui.write('It isn\\'t clear where this leads.')\r\n ui.write('You stay standing in the doorway.')\r\n\r\n def Close(self,using):\r\n if self.opened == True:\r\n self.opened = False\r\n ui.write(\"You close the \" + self.name)\r\n elif self.opened == False:\r\n ui.write(\"The \" + self.name + \" is already closed.\")\r\n \r\n def Lock(self,key):\r\n ui.write('++Lock not Implemented++')\r\n\r\n def Unlock(self,key): #door\r\n specificUnlock = False\r\n generalUnlock = [False,None]\r\n if self.locked[0]:\r\n if isinstance(key,inventoryObject):\r\n if key in jeremy.inventory:\r\n ui.write(\"You attempt to open the %s using the %s\"%(self.name,key.name))\r\n if key.unlocks[0]:\r\n for item in key.unlocks[1]:\r\n if item in self.locked[1]:\r\n if item[0] == \"K\":\r\n specificUnlock = True\r\n else:\r\n generalUnlock = [True,item]\r\n\r\n if specificUnlock:\r\n self.locked[0] = False\r\n ui.write(\"You insert the %s and the %s effortlessly clicks unlocked\"%(key.name,self.name))\r\n return()\r\n \r\n elif generalUnlock[0]:\r\n self.locked[0] = False\r\n self.locked[1] = []\r\n self.opened = True\r\n ui.write(\"You %s using the %s on the %s for some time untill it finally swings open. It is rather damaged now, doesn't look like that can be locked again\"%(generalUnlock[1],key.name,self.name))\r\n \r\n else:\r\n ui.write(\"Looks like that didn't do the job, the %s is still firmly shut\"%self.name)\r\n else:\r\n ui.write(\"You won't be able to open anything with that\")\r\n else:\r\n ui.write(\"You do not possess the %s\"%key.name)\r\n else:\r\n if key is None or key == '':\r\n ui.write(\"You're going to need something to get this open...\")\r\n else:\r\n ui.write(\"This isn't something that can be used that way.\")\r\n else:\r\n ui.write(\"The %s isn't locked...\"%self.name)\r\n\r\n if self.locked[0]:\r\n for action in self.locked[1]:\r\n if action[0] == \"K\":\r\n ui.write(\"You think some kind of key or keycard could be used to unlock this.\")\r\n else:\r\n ui.write(\"It looks like it could be %sed open with the appropriate tool.\"%action)\r\n\r\n\r\n\r\n def Block(self,thing, hides = False):\r\n \r\n if isinstance(thing,inventoryObject):\r\n if thing.canBlock:\r\n self.blocked = [True,thing]\r\n self.hidden = hides\r\n else:\r\n ui.write(\"That cannot be used to block this\")\r\n\r\n elif isinstance(thing,nonPlayerCharacter) or isinstance(thing,playerCharacter):\r\n self.blocked = [True,thing]\r\n self.hidden = hides\r\n thing.doing = ['blocking',self,True]\r\n\r\n elif isinstance(thing,roomFurnishing):\r\n self.blocked = [True,thing]\r\n self.hidden = hides\r\n thing.blocking = [True,self,hides]\r\n \r\n\r\n def Unblock(self,tool):\r\n if self.blocked[0]:\r\n if self.blocked[1].StopBlocking(tool):\r\n self.blocked = [False,None]\r\n \r\n \r\nclass gameObject(object):\r\n def __init__(self, basicDesc, inspectDesc, hidden = False):\r\n self.basicDesc = basicDesc\r\n #a description that displays when you look at it\r\n\r\n self.inspectDesc = inspectDesc\r\n #a description that displays when you inspect it\r\n self.hidden = hidden\r\n #in case it's locked away and shouldn't be found immediately\r\n\r\n self.usable = []\r\n #gonna need to talk a lot of this over with jake when we get to integration\r\n\r\n def getDesc(self):\r\n \r\n return self.basicDesc\r\n \r\n\r\nclass roomFurnishing(gameObject): \r\n def __init__(self, name, basicDesc, inspectDesc, interactive=[False,[]], containedObjects=[], opened=[False,None], locked=[False, None], blocked = [False,None],blocking = [False,None,False]):\r\n super(roomFurnishing, self).__init__(basicDesc, inspectDesc)\r\n self.name = name\r\n\r\n self.investigation = []\r\n #as with the place investigation, but on a single furnishing within a room\r\n self.interactive = interactive\r\n self.containedObjects = containedObjects\r\n self.room = None\r\n for item in self.containedObjects:\r\n item.hidden = True\r\n\r\n self.opened = opened\r\n \r\n if len(self.containedObjects) > 0:\r\n self.interactive[0] = True\r\n self.interactive[1].append('open')\r\n self.opened = [True,False]\r\n \r\n \r\n \r\n \r\n \r\n self.locked = locked\r\n self.blocked = blocked\r\n\r\n self.canOpen = self.locked[0] or self.blocked[0]\r\n\r\n self.blocking = blocking\r\n\r\n if self.blocking[0]:\r\n self.blocking[1].Block(self,self.blocking[2])\r\n\r\n \r\n \r\n def Open(self,openTool,UsedWhenCalledOnDoor_ignoreButDontRemove):\r\n if self.opened[0] == True:\r\n if self.opened[1] == False:\r\n if self.locked[0] == False:\r\n self.opened[1] = True\r\n ui.write(\"The \" + self.basicDesc + \" is not locked. You open it.\")\r\n \r\n elif self.locked[0] == True:\r\n if openTool is not None and openTool != '':\r\n self.Unlock(openTool)\r\n else:\r\n ui.write(\"The %s won't open. It is locked tight shut, or perhaps only stuck.\"%self.name)\r\n \r\n \r\n elif self.opened[1] == True:\r\n ui.write(\"The door is already open.\")\r\n \r\n if self.opened[1] == True:\r\n if len(self.containedObjects) == 0:\r\n ui.write(\"There was nothing inside.\")\r\n else:\r\n ui.write(\"The \" + self.basicDesc + \" contains:\")\r\n for item in self.containedObjects:\r\n item.hidden = False\r\n self.room.objects.append(item)\r\n ui.write(item.basicDesc)\r\n else:\r\n ui.write('The ' + self.basicDesc + ' cannot be opened.') \r\n \r\n def Close(self,using):\r\n if self.opened[0] == True:\r\n if self.opened[1] == True:\r\n for item in self.containedObjects:\r\n item.hidden = True\r\n self.room.objects.remove(item)\r\n self.opened[1] = False\r\n ui.write(\"You close the \"+ self.basicDesc)\r\n else:\r\n ui.write(\"This \" + self.basicDesc + \" is already closed.\")\r\n else:\r\n ui.write(\"This \" + self.basicDesc + \" cannot be closed.\")\r\n\r\n def Lock(self,key):\r\n ui.write('++Lock not Implemented++')\r\n\r\n def Unlock(self,key): # furnishing\r\n specificUnlock = False\r\n generalUnlock = [False,None]\r\n if self.locked[0]:\r\n if isinstance(key,inventoryObject):\r\n if key in jeremy.inventory:\r\n ui.write(\"You attempt to open the %s using the %s\"%(self.name,key.name))\r\n if key.unlocks[0]:\r\n for item in key.unlocks[1]:\r\n if item in self.locked[1]:\r\n if item[0] == \"K\":\r\n specificUnlock = True\r\n else:\r\n generalUnlock = [True,item]\r\n\r\n if specificUnlock:\r\n self.locked[0] = False\r\n ui.write(\"You insert the %s and the %s effortlessly clicks unlocked\"%(key.name,self.name))\r\n \r\n elif generalUnlock[0]:\r\n self.locked[0] = False\r\n self.locked[1] = []\r\n ui.write(\"You %s using the %s on the %s for some time until it can finally be opened. It is rather damaged now, doesn't look like that can be locked again\"%(generalUnlock[1],key.name,self.name))\r\n \r\n else:\r\n ui.write(\"Looks like that didn't do the job, the %s is still firmly shut\"%self.name)\r\n else:\r\n ui.write(\"You won't be able to open anything with that\")\r\n else:\r\n ui.write(\"You do not possess the %s\"%key.name)\r\n else:\r\n if key is None or key == '':\r\n ui.write(\"You're going to need something to get this open...\")\r\n else:\r\n ui.write(\"This isn't something that can be used that way.\")\r\n else:\r\n ui.write(\"The %s isn't locked...\"%self.name)\r\n\r\n if self.locked[0] and key in jeremy.inventory:\r\n for action in self.locked[1]:\r\n if action[0] == \"K\":\r\n ui.write(\"You think some kind of key or keycard could be used to unlock this.\")\r\n else:\r\n ui.write(\"It looks like it could be %sed open with the appropriate tool.\"%action)\r\n\r\nclass inventoryObject(gameObject):\r\n def __init__(self, name, basicDesc, inspectDesc, unlocks = [False,[]], expendable = [False,None], droppable=True, equippable = [False,[]], canBlock = False, doing=[False,None], taken=[\"No-one\",\"You pick up the\"]):\r\n super(inventoryObject,self).__init__(basicDesc, inspectDesc)\r\n\r\n self.name = name\r\n\r\n self.unlocks = unlocks \r\n \r\n self.taken = taken\r\n #include things about ownership, a description when you pick it up, etc...\r\n\r\n self.droppable = droppable\r\n #removing itself from the bag, and so on...\r\n \r\n self.expendable = expendable\r\n #if it's expendable, and if so, how many uses it has\r\n\r\n self.equippable = equippable\r\n #currently using a simple numerical value for quality\r\n\r\n self.canBlock = canBlock\r\n # if item can block sommit\r\n\r\n self.doing = doing\r\n #if it is doing somethhing like blocking a door \r\n\r\nclass Character(object):\r\n def __init__(self, name, startingRoom, inventory, doing = ['',None,False]):\r\n self.name = name\r\n self.inventory = inventory\r\n self.currentRoom = startingRoom\r\n self.doing = doing\r\n #an array of inventory objects\r\n \r\n basicShirt = inventoryObject(name =\"basic shirt\", basicDesc=\"A basic synth-cloth shirt\", inspectDesc=\"There's a small rip in the armpit...\", equippable=[True,\"clothesTorso\"])\r\n basicLegs = inventoryObject(name= \"basic legwear\", basicDesc=\"Some basic synth-cloth legwear\", inspectDesc=\"This could probably do with being washed.\", equippable=[True, \"clothesLegs\"])\r\n basicShoes = inventoryObject(name=\"basic shoes\", basicDesc=\"A pair of basic synthetic fabric and rubber shoes\", inspectDesc=\"You can feel a hole in your sock. Ugh.\", equippable=[True, \"footwear\"])\r\n \r\n self.inventory.append(basicShirt)\r\n self.inventory.append(basicLegs)\r\n self.inventory.append(basicShoes)\r\n\r\n #in case we decide to add stats later\r\n\r\n self.equipped = {\r\n \"clothesTorso\" : basicShirt,\r\n \"clothesLegs\" : basicLegs,\r\n \"armwear\" : None,\r\n \"headgear\" : None,\r\n \"footwear\" : basicShoes,\r\n \"armourTorso\" : None,\r\n \"armourLegs\" : None,\r\n \"accessories\" : [],\r\n \"weaponLeft\" : None,\r\n \"weaponRight\" : None,\r\n \"weaponBoth\" : None\r\n }\r\n #this is more for a fantasy setting and it hasn't been tested cuz I wrote it at 00:37\r\n\r\n def getName(self):\r\n return self.name\r\n\r\n def whatsMine(self):\r\n for item in self.equipped:\r\n if self.equipped[item] == None or self.equipped[item] == []:\r\n pass\r\n else:\r\n ui.write(self.equipped[item].basicDesc[0].upper()+self.equipped[item].basicDesc[1:])\r\n\r\n\r\n \r\n\r\n\r\nclass nonPlayerCharacter(Character):\r\n def __init__(self, ID, startingRoom, name, basicDesc, inspectDesc, hostile = False, talk = [], interest=[], inventory = [],equip = [], action = [], doing = ['',None,False], hidden = False):\r\n super(nonPlayerCharacter,self).__init__(name,startingRoom, inventory,doing)\r\n self.ID = ID # \"ID\" = nonPlayerCharacter(\"ID\"...)\r\n self.name = name # what user calls em\r\n self.basicDesc = basicDesc # describes them\r\n self.inspectDesc = inspectDesc # if inspected\r\n self.room = startingRoom # Where they are\r\n self.hostile = hostile # If character can interact with player in non-hostile/violent methods & if will attack player unprovoked\r\n self.talk = talk # gee, like all the text for a conversation\r\n self.interest = interest # not sure what this is?\r\n self.inventory = inventory # in their pockets and bag\r\n self.equip = equip # in their hands and on their body\r\n self.action = action # What the character will do as soon as all the shit for the room is made - allows character to be doing something as Player enters room\r\n # Perhaps expand to do more things at certain triggers ToDo\r\n self.doing = doing # What is currently being done, ['verb' (plain english),object (pointer), IfActivityFullyOccupying (bool)]\r\n\r\n self.hidden = hidden\r\n\r\n def Initialise(self):\r\n for item in self.action:\r\n print(item) \r\n exec(item)\r\n \r\n## try:\r\n## pass\r\n## # exec(item) # put this in here\r\n## except:\r\n## pass\r\n \r\n def StopBlocking(self,tool): # Player is attempting to make the npc stop blocking the door\r\n if self.doing[0] == 'blocking':\r\n if self.doing[1].hidden:\r\n self.doing[1].hidden = False\r\n ui.write(\"The %s is moved out of the way, you can now see a %s behind it\"%(self.name,self.doing[1].name.split()[-1]))\r\n ui.write(\"You can now see %s\"%self.blocking[1].basicDesc)\r\n else:\r\n ui.write(\"%s stops blocking the %s\"%((self.name[0].upper()+self.name[1:]),self.doing[1].name))\r\n self.doing = ['',None,False]\r\n return(True)\r\n else:\r\n ui.write(\"%s is not blocking anything!\"%(self.name[0].upper()+self.name[1:]))\r\n return(False)\r\n \r\n\r\nclass playerCharacter(Character):\r\n def __init__(self, name, startingRoom, inventory = [],doing = ['',None,False]):\r\n super(playerCharacter,self).__init__(name, startingRoom, inventory, doing)\r\n #this should really be in the Character class but I want to make sure it's working first\r\n\r\n\r\n def MovedRoom(self): #call whenever character enters new room\r\n self.ShowLocation()\r\n self.currentRoom.EnteredRoom()\r\n \r\n \r\n\r\n \r\n def UseItem(self, item):\r\n #the actual use\r\n if item.expendable[0] == True:\r\n if item.expendable[1] <= 1:\r\n self.inventory.remove(item)\r\n else:\r\n item.expendable[1] = item.expendable[1] -1\r\n #if the item's expendable\r\n #a confirmation message should probably be put in here at some point\r\n\r\n def Inspect(self,item,using):\r\n\r\n \r\n if isinstance(item, inventoryObject):\r\n ui.write(\"This \" + item.name + \" belongs to \" + item.taken[0] + \".\")\r\n ui.write(item.inspectDesc[0].upper()+item.inspectDesc[1:])\r\n if len(set(item.equippable[1]).intersection({\"weaponRight\",\"weaponLeft\"})) > 0:\r\n ui.write('It can easily be held in one hand, the %s looks like it could be used as a weapon.'%item.name) # todo add weapon type here for description\r\n if \"weaponBoth\" in item.equippable[1]:\r\n ui.write('It is quite heavy, looks like you\\'ll need both hands to use this. The %s would make a mighty weapon though.'%item.name)\r\n if \"clothesTorso\" in item.equippable[1]:\r\n ui.write('The %s is quite thin and lightweight, it won\\'t provide much in the way of protection. It does make a fine shirt though.'%item.name)\r\n if \"clothesLegs\" in item.equippable[1]:\r\n ui.write('It is not very thick or heavy, it won\\'t be much use as protection, but the %s looks to be a good fit as trousers.'%item.name)\r\n if \"armwear\" in item.equippable[1]:\r\n ui.write('This looks like it would fit snugly on your arm, would look quite good there too.')\r\n if \"headgear\" in item.equippable[1]:\r\n ui.write('You feel it would for your head quite well, it\\'s almost begging to be put on.')\r\n if \"footwear\" in item.equippable[1]:\r\n ui.write('Looks like these would make some pretty good shoes, they seem they seem about the right size for you.'%item.name)\r\n if \"armourTorso\" in item.equippable[1]:\r\n ui.write('It looks really quite sturdy, the %s looks like it could offer some serious protection for your upper body.'%item.name)\r\n if \"armourLegs\" in item.equippable[1]:\r\n ui.write('These look like some heavy duty trousers, the %s could be used to protect your lower body in combat.'%item.name)\r\n if \"accessories\" in item.equippable[1]:\r\n ui.write('The %s won\\'t be much good in the way of utility, you\\'re sure it would look quite pretty on you none the less.'%item.name)\r\n\r\n \r\n if item.unlocks[0]:\r\n for action in item.unlocks[1]:\r\n if action[0] == \"K\":\r\n ui.write(\"The writing on this %s makes implies it opens some lock with the ID %s.\"%(item.name,item.unlocks[1][0][1:]))\r\n else:\r\n ui.write(\"This looks like it could be used to %s open weak or vunerable objects, or doors.\"%action)\r\n \r\n elif isinstance(item, roomFurnishing):\r\n ui.write(item.inspectDesc[0].upper()+item.inspectDesc[1:])\r\n if item.opened[0]:\r\n if item.opened[1]:\r\n ui.write('The %s is open'%item.name)\r\n if len(item.containedObjects) > 0:\r\n ui.write('It contains:')\r\n for thing in item.containedObjects:\r\n ui.write(thing.name[0].upper()+thing.name[1:])\r\n else:\r\n ui.write('The %s is empty.'%item.name)\r\n \r\n else:\r\n ui.write('The %s is closed'%item.name)\r\n \r\n if item.locked[0]:\r\n ui.write('It appears to be locked.')\r\n for action in item.locked[1]:\r\n if action[0] == \"K\":\r\n ui.write(\"It appears like a key or keycard of some kind could be used to unlock this\")\r\n else:\r\n ui.write(\"Given the appropriate tool, it looks like it could be %sed open with some effort.\"%action)\r\n else:\r\n ui.write('It doesn\\'t seem to be locked in any way')\r\n \r\n if item.interactive[0] == True:\r\n for interaction in item.interactive[1]:\r\n if interaction != \"open\":\r\n ui.write(\"It looks like this could be \" + interaction + \"ed.\")\r\n \r\n \r\n \r\n elif isinstance(item, Door):\r\n ui.write(item.description)\r\n ui.write('It is to your %s'%item.name[:-5])\r\n if item.opened:\r\n ui.write('The door is wide open')\r\n if self.currentRoom.name != item.room1.name and item.seeThrough:\r\n ui.write('You can see this door leads to %s.'%item.room1.search)\r\n elif self.currentRoom.name != item.room2.name and item.seeThrough:\r\n ui.write('You can see this door leads to %s.'%item.room2.search)\r\n else:\r\n ui.write(\"It isn't clear where this leads\")\r\n\r\n else:\r\n ui.write('The door is closed')\r\n if item.locked[0]:\r\n ui.write(\"It seems to be locked. That or it's rusted shut.\")\r\n for action in item.locked[1]:\r\n if action[0] == \"K\":\r\n ui.write(\"It appears like a key or keycard of some kind could be used to unlock this\")\r\n else:\r\n ui.write(\"Given the appropriate tool, it looks like it could be %sed open with some effort.\"%action)\r\n else:\r\n ui.write(\"It doesn't appear to be locked. It looks as if it could be opened with a heafty pull.\")\r\n \r\n ui.write(\"You aren't sure where it leads.\") # ToDo change this for previously visited rooms\r\n \r\n if item.locked[0] and item.locked[2]:\r\n ui.write(\"There is a sign next to the door, it is faded but you make out the number %s\"%item.locked[1][0][1:])\r\n\r\n\r\n\r\n elif isinstance(item,nonPlayerCharacter):\r\n ui.write(item.inspectDesc)\r\n if item.hostile:\r\n ui.write(\"They don't look too friendly..\")\r\n else:\r\n ui.write(\"They look quite approachable.\")\r\n \r\n if item.doing[0] != '':\r\n if item.doing[2]:\r\n ui.write(\"They seem rather occupied with %s the %s.\"%(item.doing[0],item.doing[1].name))\r\n else:\r\n ui.write(\"They are %s the %s but that doesn’t seem to have their full attention.\"%(item.doing[0],item.doing[1].name))\r\n else:\r\n ui.write(\"They don't seem to be doing much at the moment.\")\r\n\r\n if len(item.talk) > 0:\r\n ui.write(item.name + \" might talk to you.\")\r\n\r\n # ToDo impliment descriptions for equipt things\r\n\r\n\r\n\r\n\r\n \r\n\r\n def TakeItem(self, item):\r\n \r\n \r\n if item in self.currentRoom.objects:\r\n if item.taken[0] == \"No-one\" or item.taken[0] == \"you\":\r\n item.taken[0] = \"you\"\r\n self.inventory.append(item)\r\n \r\n self.currentRoom.objects.remove(item)\r\n for furnishing in self.currentRoom.furnishings:\r\n if item in furnishing.containedObjects:\r\n furnishing.containedObjects.remove(item)\r\n \r\n ui.write(item.taken[1][0].upper()+item.taken[1][1:] +' '+ item.name + \".\")\r\n else:\r\n ui.write(\"That's not yours.\")\r\n elif item in self.inventory:\r\n ui.write(\"That's already in your inventory\")\r\n else:\r\n ui.write(\"That's not in the room.\")\r\n\r\n def EquipItem(self,item):\r\n if item in self.inventory:\r\n if self.equipped[item.equippable[1][0]] == None:\r\n self.equipped[item.equippable[1][0]] = item\r\n elif self.equipped[item.equippable[1][0]] == [] or isinstance(self.equipped[item.equippable[1][0]], list):\r\n #NOTE: THIS MIGHT NOT WORK\r\n self.equipped[item.equippable[1][0]].append(item)\r\n else:\r\n self.equipped[item.equippable[1][0]] = item\r\n #I'll put a swap confirmation message here when I'm bothered enough by it\r\n else:\r\n ui.write(\"That item is not in your inventory.\")\r\n\r\n def DropItem(self, item):\r\n if item.droppable == False:\r\n ui.write(\"You need this for something.\")\r\n else:\r\n self.inventory.remove(item)\r\n self.currentRoom.objects.append(item)\r\n \r\n def DisplayInventory(self):\r\n ui.write(\"You have in your possession: \")\r\n for item in self.inventory:\r\n ui.write(item.basicDesc[0].upper()+item.basicDesc[1:])\r\n \r\n\r\n def MoveRooms(self, door):\r\n door.Open(None,True)\r\n if door.opened and not door.blocked[0]:\r\n door.goThrough(self)\r\n #self.opened()\r\n \r\n \r\n def ShowLocation(self):\r\n ui.write(\"You are in \" + self.currentRoom.search)\r\n\r\n def SearchRoom(self):\r\n ui.write(self.currentRoom.DescribeRoom())\r\n\r\n def Talk(self, other):\r\n ui.talkWindow(self,other)\r\n\r\n\r\ndef ConnectRooms(room1,room2,direction,locked= [False,None],blocked = [False,None],hidden = False):\r\n global doors\r\n doorName = \"D\" + room1.name + room2.name\r\n door = Door(doorName,room1,room2,direction,locked,blocked,hidden)\r\n room1.doors.append(door)\r\n room2.doors.append(door)\r\n doors[doorName] = door\r\n\r\n\r\n\r\n\r\n#name, basicDesc, inspectDesc, unlocks = [], expendable = [False,None], droppable=True, equippable = [False,[]] \r\nkeyCard001 = inventoryObject(name = \"basic keycard\",basicDesc= \"a basic white keycard\",inspectDesc=\"You can just make out the number 001 on one face of the card.\",unlocks = [True,[\"K001\"]])\r\naSmallRock = inventoryObject(\"small rock\", \"a small rock\", \"A rock made of hard stone.\",[True,[\"smash\"]] , [False,None], True, [True, [\"weaponRight\",\"weaponLeft\"]])\r\nchestOfDrawers = roomFurnishing(name=\"chest of drawers\",basicDesc=\"a chest of drawers\", inspectDesc=\"A weathered wooden chest of 4 drawers.\", containedObjects=[keyCard001],locked = [True,[\"smash\"]]) \r\n \r\n\r\ndoors = {}\r\nR0 = Place(\"R0\",1,[],[],[])\r\nR1 = Place(\"R1\", 3, [chestOfDrawers], [aSmallRock],[], \"a simple yet comfortable bedroom\")\r\nR2 = Place(\"R2\",4, [],[], [],\"a lavishly decorated mezzanine\", \"a painting of yourself\")\r\nR3 = Place(\"R3\",5, [], [aSmallRock],[])\r\n\r\n\r\n\r\n # Change to true to lock\r\nConnectRooms(R1,R2,0,locked = [False,[\"K001\"],True]) # number indicates direction rooms are linked, relative to the first room 0 is north, 1 is east, 2 is south and 3 is west\r\nConnectRooms(R2,R3,3)\r\nConnectRooms(R1,R0,2)\r\n\r\npileOfRubble = roomFurnishing(name = 'pile of rubble', basicDesc = 'a large pile of rubble up against the wall', inspectDesc = \"The rubble is piled high and looks heavy.\", blocking = [True,doors['DR1R0'],True])\r\nR1.furnishings.append(pileOfRubble)\r\n\r\nC2 = nonPlayerCharacter('C2',R2,'security robot','a standard model security robot', \"A tall humanoid security robot. It is rather rusty and looks like it has been here for a very long time.\", action = [\"doors['DR2R3'].Block(self)\"])\r\nR2.characters.append(C2)\r\n\r\n\r\n\r\n\r\n##R1.setDoors([R2],direction = 0),locked = [True,[\"K001\"],True])\r\n\r\n\r\njeremy = playerCharacter(\"jeremy\", R1)\r\n\r\nTalkC1 = { 'start':['Well hello there. Can I interest you in some lemons?',[0,-1]],\r\n 'lemons':['Oh yes, fresh yellow lemons from my home. My wife picks them. Care to buy any?',[0,0]],\r\n 'yes':['Very good sir. Goodbye',[+1,-2]],\r\n 'no':['Well i\\'m sorry to hear that. Have a good day',[-3,-6]],\r\n 'wife':['Oh yes, i love my wife so very much',[+4,0]],\r\n 'home':['it\\'s a small house. I dont much care for it',[-1,-1]]}\r\n\r\n#C1 = nonPlayerCharacter('C1','John','a small man', TalkC1,3, R1)\r\n#jeremy.searchRoom(None)\r\n\r\n\r\njeremy.ShowLocation()\r\n#jeremy.moveRooms(\"DR1R2\")\r\n#jeremy.ShowLocation()\r\na = R1.showAllObjectsAndNames()\r\nb = R2.showAllObjectsAndNames()\r\nc = R3.showAllObjectsAndNames()\r\n\r\n\r\ndef Execute(text, player):\r\n action = {}\r\n\r\n #text in form {'verb':Object,'using/do': object}\r\n \r\n error = False\r\n\r\n if 'error' in text:\r\n error = True\r\n ui.write(text['error'])\r\n else: \r\n for item in text:\r\n action[item] = MatchInput({item:text[item]},player)\r\n \r\n ui.write(action) # Writes action done ToDO maybe remove this\r\n \r\n if error in action:\r\n error = True\r\n for key in action:\r\n if isinstance(action[key],dict):\r\n error = True\r\n \r\n if not error:\r\n if 'using' not in action:\r\n action['using'] = None\r\n allowed = {Place:['search'],\r\n Door:['search','open','close','go','lock','unlock','block','unblock'],\r\n roomFurnishing:['open','close','search','lock','unlock'],\r\n inventoryObject:['search','using','take','give','equip'],\r\n nonPlayerCharacter:['search','attack','talk','block','unblock'],\r\n playerCharacter:['search'],\r\n str:['search','open']} # inventory\r\n\r\n if jeremy.doing[2]: # Certain things like blocking a doorway will prevent the player from doing other things within the room\r\n toDel = []\r\n ui.write(\"You are still %s the %s. Doing this requires will prevent you from doing certain things until you stop.\"%(jeremy.doing[0],jeremy.doing[1].name))\r\n for key in allowed:\r\n if not isinstance(key,(Place,playerCharacter,inventoryObject,str,type(jeremy.doing[1]))): # keep an eye on this here, potential bug\r\n toDel.append(key)\r\n \r\n for key in action:\r\n if isinstance(key,inventoryObject):\r\n if action[key] not in jeremy.inventory:\r\n toDel.append(inventoryObject)\r\n for key in toDel:\r\n del allowed[key]\r\n \r\n \r\n \r\n \r\n \r\n for key in action:\r\n allow = False\r\n for thing in allowed:\r\n if key in allowed[thing] and isinstance(action[key],thing): # spine\r\n allow = True\r\n \r\n if key == 'search' :\r\n \r\n if action[key] == player.currentRoom:\r\n ui.write('You search the room.')\r\n player.SearchRoom()\r\n elif action[key] == 'inventory' or action[key] == player:\r\n ui.write('You look in your bag.')\r\n player.DisplayInventory()\r\n else:\r\n ui.write('You look closely at the %s.'%action[key].name)\r\n player.Inspect(action[key],action['using'])\r\n \r\n elif key == 'go' :\r\n ui.write('You try to go through the %s.'%action[key].name)\r\n player.MoveRooms(action[key])\r\n \r\n elif key == 'attack' :\r\n ui.write('You try to attack at the %s!'%action[key].name)\r\n action[key].Attack(action['using'])\r\n \r\n elif key == 'talk' :\r\n ui.write('You try to talk to %s.'%action[key].name)\r\n action[key].Talk(action['using'])\r\n \r\n elif key == 'take' :\r\n ui.write('You try to take the %s.'%action[key].name)\r\n player.TakeItem(action[key])\r\n \r\n elif key == 'open' :\r\n if action[key] == 'inventory':\r\n ui.write('You look in your bag.')\r\n player.DisplayInventory()\r\n else:\r\n ui.write('You try to open the %s.'%action[key].name)\r\n action[key].Open(action['using'],False)\r\n \r\n elif key == 'close' :\r\n ui.write('You try to close the %s.'%action[key].name)\r\n action[key].Close(action['using'])\r\n\r\n elif key =='equip':\r\n ui.write('You try to equipt the %s.'%action[key].name)\r\n player.EquipItem(action[key])\r\n\r\n elif key =='lock':\r\n ui.write('You try to lock the %s.'%action[key].name)\r\n action[key].Lock(action['using'])\r\n\r\n elif key =='unlock':\r\n ui.write('You try to unlock the %s.'%action[key].name)\r\n action[key].Unlock(action['using'])\r\n\r\n elif key == 'block':\r\n ui.write('You try to block the %s.'%action[key].name)\r\n if action['using'] is None:\r\n action['using'] = jeremy\r\n action[key].Block(action['using'])\r\n\r\n elif key == 'unblock':\r\n \r\n if isinstance(action[key],roomFurnishing):\r\n if action[key].blocked[0] == True:\r\n ui.write('You try to unblock the %s.'%action[key].name)\r\n action[key].Unblock(action['using'])\r\n elif action[key].blocking[0] == True:\r\n if action[key].blocking[2] == False: # If it's not obscuring what's behind it \r\n ui.write('You try to unblock the %s.'%action[key].blocking[1][0].name)\r\n else: \r\n ui.write('You attempt to move the %s.'%action[key].name)\r\n action[key].blocking[1][0].Unblock(action['using'])\r\n \r\n elif isinstance(action[key],nonPlayerCharacter):\r\n if action[key].doing[1].hidden == True:\r\n ui.write(\"You try to move\"%action[key.name])\r\n else:\r\n ui.write(\"You try to stop %s from blocking the %s.\"%(action[key].name,action[key].doing[1].name))\r\n action[key].doing[1].Unblock(action['using'])\r\n\r\n else:\r\n if action[key].blocked[0] == True:\r\n ui.write('You try to unblock the %s.'%action[key].name)\r\n action[key].Unblock(action['using'])\r\n \r\n elif key == 'using' and 'act' in action :\r\n action['on'].GeneralUse(action['using']) # This one maybe should be the other way round?\r\n elif key == 'using' :\r\n pass\r\n elif key == 'act' :\r\n pass\r\n else:\r\n print('Execute error')\r\n\r\n if not allow and action[key] is not None :\r\n ui.write('You cannot %s that.'%key)\r\n \r\n \r\n else:\r\n ui.write('You cannot do this.')\r\n\r\n## disallowed = {'search':False, 'move':False, 'attack':False, 'talk':False, 'open':False, 'close':False, 'using':False, 'act':False,'equip':False,'take':False}\r\n## if isinstance(action[key],Place):\r\n## disallowed['search'] = True\r\n## elif isinstance(action[key], Door):\r\n## disallowed['open'] = True\r\n## disallowed['close'] = True\r\n## disallowed['move'] = True\r\n## elif isinstance(action[key], roomFurnishing):\r\n## disallowed['open'] = True\r\n## disallowed['close'] = True\r\n## disallowed['search'] = True\r\n## elif isinstance(action[key], inventoryObject):\r\n## disallowed['search'] = True\r\n## disallowed['using'] = True\r\n## elif isinstance(action[key], nonPlayerCharacter):\r\n## disallowed['attack'] = True\r\n## disallowed['talk'] = True\r\n #we can change these as we see fit, but in terms of solutions this should be fine, right?\r\n \r\n \r\n \r\n\r\ndef MatchInput(text,player):\r\n\r\n \r\n #need to add room and player to things\r\n #look: around, about, room\r\n #should default to player\r\n \r\n room = player.currentRoom\r\n \r\n things,inventoryThings = room.showAllObjectsAndNames()\r\n for thingType in things:\r\n for thing in thingType:\r\n print(thing)\r\n\r\n things.append([['around','room','about'],[room,room,room]])\r\n things.append([['self','myself','me'],[player,player,player]])\r\n things.append([['inventory','bag'],['inventory','inventory']])\r\n whereLooking = 'sight'\r\n for key in text:\r\n if 'my ' in text[key]:\r\n things = inventoryThings \r\n text[key] = text[key].replace('my ','')\r\n whereLooking = 'your inventory'\r\n \r\n similar = ''\r\n \r\n\r\n action = {} \r\n\r\n done = False\r\n \r\n \r\n \r\n for key in text:\r\n action[key] = ''\r\n for thingList in things:\r\n for i in range(len(thingList[0])):\r\n if text[key] == thingList[0][i]: # if exact match with name\r\n action[key] = thingList[1][i]\r\n break #this might not work bug\r\n\r\n elif text[key] in thingList[0][i] and similar == '': #Will catch any matching word\r\n action[key] = thingList[1][i]\r\n similar = key\r\n elif text[key] in thingList[0][i] and similar != '':# Unless more than one object matches\r\n action[similar] = ''\r\n\r\n for key in action:\r\n if action[key] == '':\r\n break\r\n else:\r\n done = True\r\n return(action[key])\r\n \r\n \r\n if not done:\r\n for key in action:\r\n #if key not in ['using','take','give']\r\n thingType = [] \r\n if action[key] == '':\r\n for thingList in things:\r\n for i in range(len(thingList[0])):\r\n thingList[0][i] = thingList[0][i].split()\r\n if thingList[0][i][-1] in text[key]:\r\n thingType.append([key,thingList[1][i],thingList[0][i]])\r\n \r\n \r\n \r\n if len(thingType)!= 0:\r\n \r\n desc = []\r\n for i in range(len(thingType)):\r\n desc.append('')\r\n \r\n for x in thingType[i][2]:\r\n desc[i] += x+' '\r\n desc[i] = desc[i][:-1]\r\n \r\n if len(thingType) == 1:\r\n ui.write('There is only one %s in %s: the %s.'%(thingType[0][2][-1],whereLooking,desc[0])) # This is broken , bug\r\n action[thingType[0][0]] = thingType[0][1]\r\n return(action[key])\r\n else:\r\n ui.write('There is more than one of these in %s:'%whereLooking)\r\n for item in desc:\r\n ui.write('There is a %s'%item)\r\n return({'error':'Ambiguous object'})\r\n else:\r\n ui.write('there is no %s in %s!'%(text[key].split()[-1],whereLooking))\r\n # Check inventory for object\r\n invThings = [[],[]]\r\n invObjects = [[],[]]\r\n \r\n for i in range(len(inventoryThings[0][0])):\r\n invThings[0].append(inventoryThings[0][0][i].split()[-1])\r\n invThings[1].append(inventoryThings[0][1][i])\r\n if invThings[0][i] in text[key]:\r\n invObjects[0].append(invThings[0][i])\r\n invObjects[1].append(invThings[1][i])\r\n if len(invObjects[0]) == 1:\r\n ui.write('There is a %s in your inventory: the %s.'%(invObjects[0][0],invObjects[0][0]))\r\n action[key] = invObjects[1][0]\r\n \r\n return(action[key])\r\n\r\n else: \r\n return({'error':'Object not recognised'})\r\n \r\n\r\n\r\n\r\n\r\n\r\ndef Interpret(text,player):\r\n\r\n text,verbs = Simplify(text)\r\n \r\n\r\n objVerbs = ['take','give','equip'] # remember to add above too\r\n objVerb = ''\r\n\r\n verbs.remove('using')\r\n using = 'using'\r\n \r\n currentVerb = ''\r\n verbNumber=0\r\n usingNumber=0\r\n words = text.split()\r\n do = {}\r\n\r\n\r\n for word in words:\r\n for verb in verbs: # Finds verb in sentence\r\n if word == verb:\r\n verbNumber+=1\r\n do[verb] = ''\r\n currentVerb = verb\r\n continue\r\n \r\n if word == using: # Finds 'using' in sentence\r\n usingNumber+=1\r\n do[using] = ''\r\n currentVerb = using\r\n \r\n if word not in verbs and word != using and currentVerb != '': # The nouns\r\n if do[currentVerb] == '': #nouns set as values of key being previous verb\r\n do[currentVerb]+=word\r\n else:\r\n do[currentVerb] += ' '+word # add space if not first word\r\n\r\n \r\n ###---Dirty fix for Use X on Y---###\r\n \r\n if usingNumber == 1 and verbNumber == 0 and words[0] == using:\r\n do['act'] = ''\r\n temp = do[using].split()\r\n do[using] = ''\r\n beforeOn = True\r\n for word in temp:\r\n\r\n if word == 'on':\r\n \r\n beforeOn = False\r\n \r\n if word != 'on' and beforeOn:\r\n if do[using] == '':\r\n do[using] +=word\r\n else:\r\n do[using] +=' '+word\r\n elif word != 'on' and not beforeOn:\r\n if do['act'] == '':\r\n do['act'] +=word\r\n else:\r\n do['act'] += ' '+word\r\n \r\n verbNumber+=1\r\n\r\n \r\n ###---Dirty fix for transfer object to/from X from/to Y---###\r\n for verb in objVerbs:\r\n if verb in do:\r\n objVerb = verb\r\n \r\n if objVerb != '' :\r\n do['to/from'] = ''\r\n temp = do[objVerb].split()\r\n do[objVerb] = ''\r\n beforeTF = True\r\n for word in temp:\r\n if word in ['to','from']:\r\n \r\n beforeTF = False\r\n \r\n if word not in ['to','from'] and beforeTF:\r\n if do[objVerb] == '':\r\n do[objVerb] +=word\r\n else:\r\n do[objVerb] +=' '+word\r\n elif word not in ['to','from'] and not beforeTF:\r\n if do['to/from'] == '':\r\n do['to/from'] +=word\r\n else:\r\n do['to/from'] += ' '+word\r\n if do['to/from'] == '':\r\n del do['to/from']\r\n \r\n \r\n for key in do:\r\n do[key] = do[key].replace('on ','') # remove garbage word 'on', used in dirty fix\r\n do[key] = do[key].replace('to ','')\r\n do[key] = do[key].replace('from ','')\r\n #do[key] = do[key].replace('in ','')\r\n if do[key] == '':\r\n if key == 'act':\r\n do[key] = 'self'\r\n else:\r\n Execute({'error':'What are you trying to %s?'%key},player)\r\n return()\r\n \r\n \r\n if verbNumber >1 or usingNumber>1:\r\n Execute({'error':'All that at once?'},player)\r\n elif verbNumber == 0:\r\n Execute({'error':'What are you trying to do?'},player)\r\n else:\r\n Execute(do,player) #sucess!\r\n\r\n \r\n \r\ndef Simplify(text):\r\n \r\n toRemove = []\r\n fillerWords = ['','in','the','attempt','through','teh','a','try','trying','at','near','for','behind','under','while','and','by','toRemove']\r\n punctuation = [',','.','?','!','\\'',';',':']\r\n \r\n using = ['use','using','with','activate','activating','fire','firing','turn','turning']\r\n \r\n search = ['search','look','find','explore','inspect','observe','see']\r\n \r\n go = ['go','travel','walk','climb','enter']\r\n \r\n attack = ['attack', 'assault', 'hit','fight','kill']\r\n talk = ['talk','speak','talk to']\r\n \r\n take = ['take','grab','remove','carry','obtain','pick up','pick','steal']\r\n close = ['close','shut']\r\n inspect = []\r\n \r\n open_ = ['open'] #open is keyword, uses open_ instead\r\n\r\n unlock = ['unlock','smash'] # Add all general unlocking methods\r\n lock = ['lock'] \r\n\r\n unblock = ['unblock','move']\r\n block = ['block']\r\n\r\n equip = ['equipt','put on','wear','hold']\r\n\r\n \r\n\r\n verbs = ['using','search','go','attack','talk','take','open','close','equip','lock','unlock','unblock','block']\r\n words = {'using':using,'search':search,'go':go,'attack':attack,'talk':talk,'take':take,'open':open_,'close':close,'equip':equip,'lock':lock,'unlock':unlock,'unblock':unblock,'block':block}\r\n\r\n \r\n \r\n \r\n \r\n text = text.lower()\r\n text = text.split()\r\n sentence = ''\r\n \r\n for i in range(len(text)):\r\n for verb in verbs:\r\n if text[i] in words[verb]: # ***The good bit***\r\n text[i] = verb #replaces synonms of verbs with general case of verb from verbs array\r\n elif i < len(text) -1:\r\n if text[i] + ' ' + text[i+1] in words[verb]:\r\n text[i] = verb\r\n text[i+1] = 'toRemove'\r\n\r\n \r\n if i > 0:\r\n if text[i] == text[i-1]:\r\n text[i-1] = 'toRemove'\r\n \r\n \r\n if text[i] in fillerWords:\r\n toRemove.append(text[i]) # get rid of garbage words\r\n \r\n if text[i][-1] in punctuation:\r\n text[i] = text[i][:-1] # get rid of punctuation\r\n \r\n \r\n \r\n for word in toRemove:\r\n text.remove(word) #remove garbage words\r\n \r\n for word in text:\r\n sentence+=word+' ' #make array of words into sentence\r\n \r\n sentence = sentence[:-1] #remove trailing ' '\r\n\r\n if 'unlock' in text and 'open' in text:\r\n text.replace(\"unlock\",\"\")\r\n \r\n #Special cases\r\n if sentence in ('inventory','inv'):\r\n sentence = 'open inventory'\r\n \r\n return(sentence,verbs)\r\n\r\n\r\n \r\n\r\n#TO MOVE ROOMS YOU NEED THE DOOR CODE\r\n\r\nmain.mainloop()\r\n \r\n#TODO: Change dialogue for objects so it doesn't sound so weird and ham-fisted by making a location in the room for them to exist in.\r\n#Maybe work on making random descriptors for rooms. 5 senses!\r\n#making sure the program's fully modular to save on work when we make it work with the interpreter\r\n#scavenge from the existing file reader so I can get file reading working here too. I'll probably need multiple files.\r\n#basic gameplay loop will obviously need to be fixed but that's partially Jake's problem, lol\r\n\r\n \r\n","sub_path":"NPCs now work more.py","file_name":"NPCs now work more.py","file_ext":"py","file_size_in_byte":79032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"536961745","text":" #!/user/bin/python\n\n\"\"\"\n\n##################################################\n##\t\t\t\t\t\t\t\t\t\t\t\t##\n## \tGRUBHUB SCRAPE: MIN WAGE AND CAL POST\t\t##\n## \t\t\t\t\tPROJECTS\t\t\t\t\t##\n##\tChelsea Crain\t\t\t\t\t\t\t\t##\n##\t12/07/16\t\t\t\t\t\t\t\t\t##\n##\t\t\t\t\t\t\t\t\t\t\t\t##\n## \tThis program goes through the list of \t\t##\n## \t\tneighborhoods and scrapes \t\t\t\t##\n##\t\tmain pages and menu pages of all \t\t##\n##\t\tall restaurants located in those areas.\t##\n##\t\t\t\t\t\t\t\t\t\t\t\t##\n##################################################\n\n\n\"\"\"\n\nfrom __future__ import print_function, division\nfrom lxml import html\nimport csv, sys\nfrom itertools import izip_longest\nfrom os.path import join, dirname, realpath\nimport pandas as pd\nfrom os import path\nfrom datetime import date\nimport os\nimport time \nimport time, os, re, codecs, math, random, csv, datetime\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium import webdriver\nimport sys\nimport uuid\n\ndelay = 15\n\ngeneral_path = \"E:\\\\Grubhub_SodaTax\\Grubhub_Scrapes\" \n\n\n\ndef get_done_lists(area, scrape_name):\n\n\tpath = general_path + \"\\\\Scrape_\" + scrape_name\n\tif not os.path.isdir(path):\n\t\tos.makedirs(path)\n\tdone_zips_name = os.path.join(path, \"done_zips_\" + area + \".csv\")\n\tdone_list_name = os.path.join(path, \"done_list_\" + area + \".csv\")\n\t\n\ttry:\n\t\tdf = pd.read_csv(done_list_name)\n\t\tdone_list = df['done'].tolist()\n\texcept:\n\t\tfile = open(done_list_name, 'w')\n\t\tfile.write(\"done\" + \",\" + \"\\n\")\n\t\tfile.close()\n\t\tdf = pd.read_csv(done_list_name)\n\t\tdone_list = df['done'].tolist()\n\t\t\n\ttry:\n\t\tdf = pd.read_csv(done_zips_name)\n\t\tdone_zips = df['done'].tolist()\n\texcept:\n\t\tfile = open(done_zips_name, 'w')\n\t\tfile.write(\"done\" + \",\" + \" service notes\" + \"\\n\")\n\t\tfile.close()\n\t\tdf = pd.read_csv(done_zips_name)\n\t\tdone_zips = df['done'].tolist()\n\t\t\n\treturn done_list, done_zips, path, done_zips_name, done_list_name\n\t\ndef count_letters(zip):\n\n\tletters = len(zip) - zip.count(' ')\n\t\n\tif letters < 5:\n\t\tzip = \"0\" + str(zip)\n\telse:\t\n\t\tzip = str(zip)\n\t\t\n\tprint(zip)\n\t\n\treturn zip\n\ndef get_driver():\n\n\turl = \"https://www.grubhub.com\"\n\topts = Options()\n\topts.add_experimental_option(\"prefs\", {\"profile.default_content_settings.cookies\": 2})\n\t\n\tdriver = webdriver.Chrome('C:\\Program Files (x86)'\n\t\t\t\t'\\Google\\Chrome\\Application\\chromedriver.exe', chrome_options=opts)\n\t\n\tdriver.get(url)\n\t\n\t\n\treturn driver\n\ndef search_for_restaurants(driver, zip):\n\t\t\n\ttry:\n\t\tdriver.find_element_by_link_text('Thanks, but no thanks.').click()\n\texcept:\n\t\tsearch_bar = driver.find_element_by_xpath('//*[@type=\"search\"]')\n\t\tfor x in range(0,50):\n\t\t\tsearch_bar.send_keys(Keys.BACKSPACE)\n\t\tsearch_bar.send_keys(zip)\n\t\tsearch_bar.send_keys(Keys.ENTER)\n\t\n\ttime.sleep(3)\n\t\n\ttry:\n\t\tdriver.find_element_by_xpath('.//*[@class=\"icon-close\"]').click()\n\texcept:\n\t\tprint(\"no 'enjoy $ off' option found\")\n\t\t\n\ttry:\n\n\t\tdriver.find_element_by_xpath('.//*[@class=\"s-btn s-btn-tertiary\"]').click()\n\texcept:\n\t\tprint(\"no 'later delivery' option found\")\n\t\n\t\n\tprint(\"waiting for s-tag\")\n\ttime.sleep(4)\n\t\n\ttry:\n\t\tdriver.find_element_by_link_text('Thanks, but no thanks.').click()\n\texcept:\n\t\tno_thanks = \"na\"\n\t\t\t\n\t\n\n\t\tWebDriverWait(driver, delay).until(\n\t\t\tEC.presence_of_element_located(\n\t\t\t(By.CLASS_NAME, 'icon-close')\n\t\t\t))\n\t\tdriver.find_element_by_class_name('icon-close').click()\n\t\tprint(\"clicked out of 'open now'\")\n\t\tWebDriverWait(driver, delay).until(\n\t\t\tEC.presence_of_element_located(\n\t\t\t(By.CLASS_NAME, \"restaurantCard-primaryInfo-item\")\n\t\t\t))\n\t\tprint(\"found it\")\n\t\t\n\t\n\t\tWebDriverWait(driver, delay).until(\n\t\t\tEC.presence_of_element_located(\n\t\t\t(By.CLASS_NAME, \"restaurantCard-primaryInfo-item\")\n\t\t\t))\n\t\t\t\n\t\ttry:\n\t\t\tdriver.find_element_by_link_text('Thanks, but no thanks.').click()\n\t\texcept:\n\t\t\tno_thanks = \"na\"\n\t\t\t\n\t\treturn True\n\t\t\n\texcept:\n\n\t\treturn False\n\t\t\n\ndef get_list(driver):\n\n\tcurrent_page = 1\n\ttry:\n\t\tWebDriverWait(driver, delay).until(\n\t\t\tEC.presence_of_element_located(\n\t\t\t(By.XPATH, '//*[contains(@ng-bind,\"searchData.totalPages\")]')\n\t\t\t))\n\t\ttime.sleep(3)\t\n\t\tpages_exist=True\n\texcept:\n\t\tpages_exist=False\n\t\t\n\tif pages_exist:\n\t\ttotal_pages = int(driver.find_element_by_xpath('//*[contains(@ng-bind,\"searchData.totalPages\")]').text)\n\n\t\tprint(\"total pages: %s\" %total_pages)\n\t\t\n\t\tcurrent_restaurant_index = 0\n\t\ttotal_restaurants = int(driver.find_element_by_xpath('//*[contains(@ng-bind,\"searchData.totalResults\")]').text)\n\t\tprint(\"total results: %s\" %total_restaurants)\n\t\turl_list = []\n\t\twhile current_page <= total_pages:\n\t\t\t\t# check to make sure connected to internet \n\t\t\ttry:\n\t\t\t\tdriver.find_element_by_link_text('Thanks, but no thanks.').click()\n\t\t\texcept:\n\t\t\t\tno_thanks = \"na\"\n\t\t\t\t\n\t\t\ttime.sleep(1)\n\t\t\ttext = driver.find_element_by_xpath('html[@id=\"ng-app\"]').text\n\t\t\ttext = text.encode('utf-8').strip()\n\t\t\tif \"An error occurred\" in text: \n\t\t\t\tsys.exit()\n\t\t\ttry:\n\t\t\t\tdriver.find_element_by_link_text('Thanks, but no thanks.').click()\n\t\t\texcept:\n\t\t\t\tx=0\n\t\t\tprint(\"page %s of %s\" %(current_page, total_pages))\n\t\t\ttime.sleep(random.randint(1,3))\n\t\t\tWebDriverWait(driver, delay).until(\n\t\t\t\tEC.presence_of_element_located(\n\t\t\t\t(By.CLASS_NAME, \"restaurantCard-primaryInfo-item\")\n\t\t\t\t))\n\t\t\ttry:\n\t\t\t\trestaurants_on_page = len(driver.find_elements_by_xpath('//*[contains(@class,\"restaurantCard-primaryInfo-item\")]//a'))\n\t\t\texcept:\n\t\t\t\ttime.sleep(5)\n\t\t\t\trestaurants_on_page = len(driver.find_elements_by_xpath('//*[contains(@class,\"restaurantCard-primaryInfo-item\")]//a'))\n\t\t\ti = 0\n\t\t\twhile i < (restaurants_on_page):\n\t\t\t\t# print(i)\n\t\t\t\turl = str(driver.find_elements_by_xpath('//*[contains(@class,\"restaurantCard-primaryInfo-item\")]//a')[i].get_attribute('href'))\n\t\t\t\t# print(url)\n\t\t\t\turl_list.append(url)\t\n\t\t\t\ti+=1\n\t\t\t\t\n\t\t\ttry:\n\t\t\t\tdriver.find_element_by_link_text('Thanks, but no thanks.').click()\n\t\t\texcept:\n\t\t\t\tx=0\n\t\t\t\t\n\t\t\tcurrent_page+=1\n\t\t\t\n\t\t\tif current_page <= total_pages: # go to next page if not on last page\n\t\t\t\tnext_page = driver.find_element_by_link_text(str(current_page)).click()\n\t\t\t\tWebDriverWait(driver, delay).until(\n\t\t\t\t\tEC.presence_of_element_located(\n\t\t\t\t\t(By.XPATH, '//*[contains(@ng-bind,\"searchData.currentPage\")]')\n\t\t\t\t\t))\n\t\t\t\t\n\t\t\ttry:\n\t\t\t\tdriver.find_element_by_link_text('Thanks, but no thanks.').click()\n\t\t\texcept:\n\t\t\t\tx=0\n\t\t\t\t\n\t\t\tfound = False\n\t\t\twhile found == False:\n\t\t\t\ttime.sleep(1)\n\t\t\t\ttry:\n\t\t\t\t\tactual_current_page = int(driver.find_element_by_xpath('//*[contains(@ng-bind,\"searchData.currentPage\")]').text)\n\t\t\t\t\tfound = True\n\t\t\t\texcept:\n\t\t\t\t\tfound = False\n\t\t\t\t\t\n\t\t\tif (current_page != actual_current_page) and (current_page <= total_pages):\n\t\t\t\tprint(\"WEIRD SHIT IS GOING DOWM\")\n\t\t\t\ttime.sleep(50)\n\t\t\t\tsys.exit()\n\t\t\t\tbreak\n\t\t\t\n\telif pages_exist==False:\n\t\ttotal_restaurants = int(driver.find_element_by_xpath('//*[contains(@ng-bind,\"searchData.totalResults\")]').text)\n\t\turl_list = []\n\t\ttry:\n\t\t\trestaurants_on_page = len(driver.find_elements_by_xpath('//*[contains(@class,\"restaurantCard-primaryInfo-item\")]//a'))\n\t\texcept:\n\t\t\ttime.sleep(5)\n\t\t\trestaurants_on_page = len(driver.find_elements_by_xpath('//*[contains(@class,\"restaurantCard-primaryInfo-item\")]//a'))\n\t\ti=0\n\t\twhile i < (restaurants_on_page):\n\t\t\turl = str(driver.find_elements_by_xpath('//*[contains(@class,\"restaurantCard-primaryInfo-item\")]//a')[i].get_attribute('href'))\n\t\t\turl_list.append(url)\t\n\t\t\ti+=1\n\t\t\t\n\treturn(url_list)\n\n\t\ndef prep_file(path, zip):\n\n\tzip_path = os.path.join(path, zip)\n\tif not os.path.exists(zip_path):\n\t\tos.makedirs(zip_path)\n\t\n\tid = str(uuid.uuid4())\n\tprint(id)\n\tvisible_text_file = open(os.path.join(zip_path, id + \".txt\"), \"w\")\n\thtml_file = open(os.path.join(zip_path, id ), \"w\")\n\t\n\treturn visible_text_file, html_file\n\t\t\t\t\t\ndef download_menu_info(driver, url, zip, path, area):\n\n\tdriver.get(url)\n\t\n\t\n\ttry:\n\t\tWebDriverWait(driver, delay).until(\n\t\t\tEC.presence_of_element_located(\n\t\t\t(By.CLASS_NAME, \"menuItem-inner\")\n\t\t\t))\n\texcept:\n\t\t\tdriver.find_element_by_link_text('here').click()\n\t\t\tWebDriverWait(driver, delay).until(\n\t\t\t\tEC.presence_of_element_located(\n\t\t\t\t(By.CLASS_NAME, \"menuItem-inner\")\n\t\t\t\t))\n\n\tvisible_text_file, html_file = prep_file(path, zip)\t\n\t\n\tvisible_text = driver.find_element_by_xpath('.//html[@id]').text\n\tvisible_text = visible_text.encode('utf-8').strip()\n\tif \"An error occurred\" in visible_text: # check to make sure connected to internet \n\t\tsys.exit()\n\tvisible_text_file.write(visible_text)\n\tvisible_text_file.close()\n\t\n\n\thtml_text = driver.page_source\n\thtml_text = html_text.encode('utf-8').strip()\n\thtml_file.write(html_text)\n\thtml_file.close()\t\n\n\ndef main(area, scrape_name):\n\n\t\n\ttry:\t\n\t\tdone_list, done_zips, path, done_zips_name, done_list_name = get_done_lists(area, scrape_name)\n\t\t\n\t\tuser_agent_list = os.path.join(general_path, \"user_agents.csv\")\n\t\tlist_of_zips = os.path.join(general_path, \"zips_\"+ area + \".csv\")\n\t\tdf = pd.read_csv(list_of_zips)\n\t\tzip_list = df['zip'].tolist()\n\t\t\t\n\t\tprint(\"Number of zips done: %s\" %len(done_zips))\n\t\tprint(\"Number of menus downloaded: %s\" % len(done_list))\n\n\t\tdriver = get_driver()\n\n\t\tfor zip in zip_list:\n\t\t\tif (zip in done_zips) or (str(zip) in done_zips):\n\t\t\t\tprint(\"already got this zip: %s\" %zip)\n\t\t\t\tcontinue\n\t\t\tzip = str(zip)\n\t\t\tif len(zip) == 4:\n\t\t\t\tzip = \"0\" + zip\t\n\t\t\tprint(\"Starting on zip %s\" %zip)\n\t\t\t\n\t\t\t## GET TO THE RIGHT SEARCH PAGE #######\n\t\t\tservice = search_for_restaurants(driver, zip)\n\t\t\tprint(service)\n\t\t\t## GO THROUGH ALL PAGES AND MAKE LIST OF ALL RESTAURANT URLS #####\n\t\t\tif service == True:\n\t\t\t\turl_list = get_list(driver)\n\t\t\t\trandom.shuffle(url_list)\n\t\t\t\t# print(url_list)\n\t\t\t\tprint(\"Starting to save menu info\")\n\t\t\t\t\n\t\t\t\t## DOWNLOAD INFO FROM ALL RESTAURANT LINKS IN ZIP CODE LIST ####\n\t\t\t\tfor url in url_list:\n\t\t\t\t\tif url in done_list:\n\t\t\t\t\t\tprint(\"already got this one\")\n\t\t\t\t\t\tservice_status = \"\"\n\t\t\t\t\t\tcontinue\n\t\t\t\t\telse:\n\t\t\t\t\t\tprint(url)\n\t\t\t\t\t\tdownload_menu_info(driver, url, zip, path, area)\n\t\t\t\t\t\n\t\t\t\t\tdone_list_file = open(done_list_name, 'a')\n\t\t\t\t\tdone_list_file.write(url + \"\\n\")\n\t\t\t\t\tdone_list_file.close()\n\t\t\t\t\tdone_list.append(url)\t\n\t\t\t\t\tservice_status = \"\"\n\t\t\t\n\t\t\t## IF NO SERVICE THEN MAKE NOTE IN DONE LIST AND CONTINUE ####\n\t\t\telif service == False:\n\t\t\t\tprint(\"NO SERVICE HERE DUDE: %s\" %zip)\n\t\t\t\tservice_status = \"no service\"\n\t\t\t\t\n\t\t\tdone_zip_file = open(done_zips_name, 'a')\n\t\t\tdone_zip_file.write(zip + \",\" + service_status + \"\\n\")\n\t\t\tdone_zip_file.close()\n\t\t\tdone_zips.append(zip)\n\t\t\t\n\t\t\ttry:\n\t\t\t\tdriver.find_element_by_link_text('Thanks, but no thanks.').click()\n\t\t\texcept:\n\t\t\t\tprint(\"\")\n\t\t\tmain_page = driver.find_element_by_class_name('mainNavBrand-logo').click()\n\t\t\t\n\t\t\tWebDriverWait(driver, delay).until(\n\t\t\t\tEC.presence_of_element_located(\n\t\t\t\t(By.XPATH, '//*[@type=\"search\"]')\n\t\t\t\t))\n\t\t\t\t\n\t\tprint(\"ALL DONE!!!!\")\n\t\t\t\n\texcept:\n\t\tsys.exit()\n\t\t\nif __name__ == '__main__':\n main(sys.argv[1], sys.argv[2])\n\t","sub_path":"grubhub_scrape.py","file_name":"grubhub_scrape.py","file_ext":"py","file_size_in_byte":10835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"423241386","text":"import cartesianMeasurement as xyz\nimport polarMeasurement as rphiz\n\ndef printFieldFromList(listOfMeasurements, saveName, description=None):\n f = open(saveName, 'w')\n if listOfMeasurements[0].identifier() == 'Polar Data':\n f.write('#z (m)\\tr (m)\\tphi (deg) \\tBr (T)\\tBphi (T)\\tBz (T)\\tB (T)\\tprobeID\\tDate (DDMMYYY)\\tTime (24-HH:MM:SS)\\n')\n else:\n f.write('#z (m)\\tx (m)\\ty (m) \\tBx (T)\\tBy (T)\\tBz (T)\\tB (T)\\tprobeID\\tDate (DDMMYYY)\\tTime (24-HH:MM:SS)\\n')\n\n listOfMeasurements.sort()\n\n for m in listOfMeasurements:\n f.write(m.asFileLine())\n\n if description != None:\n # add the description to the bottom of the file\n f.write('\\n')\n f.write(description)\n\n f.close()\n","sub_path":"MakeFieldMaps/modules/printField.py","file_name":"printField.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"357603762","text":"def make_divisible(n, d):\n while n // d == 0:\n n *= 10\n\n return n\n\ndef find_repeating_period(dividend, divisor):\n # Use long division to find the period of the repeating decimals.\n dividend = make_divisible(dividend, divisor)\n previous_interations = []\n\n while True: \n previous_interations.append((dividend, divisor))\n remainder = dividend % divisor\n\n if remainder == 0:\n period = 0\n break\n\n dividend = make_divisible(remainder, divisor)\n\n if (dividend, divisor) in previous_interations:\n period = len(previous_interations) - previous_interations.index((dividend, divisor))\n break\n\n return period\n\nlongest_cycle = 0\nd = 0\n\nfor i in range(2, 1000):\n val = find_repeating_period(1, i)\n\n if val > longest_cycle:\n longest_cycle = val\n d = i\n\nprint(longest_cycle, d)","sub_path":"python/26.py","file_name":"26.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"393963362","text":"# !/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\n Author: Conglin Du\n License: (C) Copyright 2018-2020, Shanghai hot nest network technology co. LTD.\n Contact: gduxiansheng@gmail.com or 2544284522@qq.com\n File: configVariateUnit.py\n Time: 2018-12-27 15:07\n File Intro: 爬虫全局变量的配置模块\n\"\"\"\n\n# 爬虫访问钱变量的配置,\nCFG_VISIT_ENGINE = \"visit.engine\" # requests(有 session 模式, 1 默认 requests) or Phantomjs or Chrome,\nCFG_VISIT_UA = \"visit.ua\" # 默认的是随机 ua win 模式, from user_agent import generate_user_agent, 参数 'win', 'mac', 'linux', 'android'可以是组合的元组\nCFG_VISIT_HEADERS = \"visit.headers\" # 有默认的 headers, 1默认,0为自己传参\nCFG_VISIT_INITCOOKIE = \"visit.initCookies\" # 时需要新的 cookie , 1, 0\nCFG_VISIT_INITPROXY = \"visit.initNeedProxy\" # 时需要新的 proxy, 1, 0\nCFG_VISIT_INTERVAL = \"visit.interval\" # 访问的时间间隔 可以是数字如0.01, 10,也可以是range()\nCFG_VISIT_TIMEOUT = \"visit.timeOut\" # 设置爬虫爬取的超时时间\nCFG_VISIT_BROWSERMODE = \"visit.browserMode\" # 浏览器模式 默认无头\nCFG_VISIT_FIXUA = \"visit.fixua\" # 固定ua\n\nCFG_VISIT_FORMAT = \"visit.format\" # json, html, 类 js, xml (现在基本废弃)\nCFG_VISIT_ENCODING = \"visit.encoding\" # 编码形式,utf-8 or gb2312\nCFG_VISIT_MAXRSESSION = \"visit.maxSession\" # 一个session 最多请次数, 0 为无限次\nCFG_VISIT_UNESCAPE = \"visit.unescape\"\n\n\n# 爬虫工作的配置\nCFG_JOB_NAME = \"job.name\" # 爬虫工作名称\nCFG_JOB_VERSION = \"job.version\" # 爬虫工作的版本号\nCFG_JOB_ID = \"job.id\" # 爬虫工作 id 默认 md5 (CFG_JOB_VERSION)\nCFG_JOB_ENABLE = \"job.enable\" # 启用任务调度,目前只在 online / dev / test 时候用\nCFG_JOB_BEGINTIME = \"job.beginTime\" # 工作开始时间\nCFG_JOB_RUNTIME = \"job.runTime\" # 工作运行时间, ,0无限制,单位是秒\nCFG_JOB_HEARTBEAT = \"job.heartBeat\" # 任务的心跳间隔,这个也作为需要健康检查的标识\nCFG_JOB_EMAIL = \"job.email\" # job负责人email\n\n\n# 解析列表相关key\nLIST_TOTAL_PAGE_NUM = \"totalPageNum\" # 总页数\nLIST_PAGE_SIZE = \"pageSize\" # 每页的行数\nLIST_NO_RESULT = \"listNoResult\" # list 无结果的网站提醒\nLIST_ITEMS = \"listItems\" # list 行数组的模式\nLIST_PAGE_PATTERN = 'pagePattern' # 翻页的模式\nLIST_PAGE_MAGNIFICATION = 'pageMagnification', # 翻页的倍数\n\n# data 数据下载后的配置\nCFG_DOWN_MAXNUM = \"down.maxNum\" # 下载最大数\nCFG_DOWN_MAXPAGENUM = \"down.maxPageNum\" # 下载最大页数\nCFG_DOWN_PATH = \"down.path\" # 路径index,可以多级,逐级细分,{web_site_name}/index1/indexn,如www_51job_com/company/internet\nCFG_DOWN_ROOT = \"down.root\" # 下载数据根目录\nCFG_DOWN_INDEX = \"down.index\" # 下载后的数据保存的路径,(必须配置项)\nCFG_DOWN_WEBSITE = \"down.webSite\" # 网站全称,点号用下划线代替 www_51job_com\n\n\n\n\n# log info 的配置\nLOG_FOREVER = \"log.forever\" # 系统启动后就建立好 确保多进程下的log唯一性\n\nLOG_CONSOLE_LEVEL = \"log.consoleLevel\" # 控制台标准\nLOG_FILE_LEVEL = \"log.fileLevel\" # 文件标准\nLOG_FILE_NAME = \"log.fileName\" # 文件名称\n\n\n\n# debug 的一些配置\nDEBUG_SAVEFILE = \"debug.saveFile\" # 存储下载文件\nDEBUG_SAVEFILENAME = \"debug.saveFileName\" # 存储下载文件名称\nDEBUG_LOCALNODE = \"debug.localNode\" # 本地节点\nDEBUG_LOCALTEST = \"debug.localTest\" # 本地测试\n\n\n# db 工作业务的配置\nDB_DICTCURSOR = \"db.dictCursor\" #是否用dictCursor\nDB_MONITORNAME = \"db.monitorName\" # 监控名称\nDB_BUSINESSNAME = \"db.businessName\" # 业务名称\nDB_BUSINESS = \"db.business\" # 业务\nDB_MONITOR = \"db.monitor\" # 监控\nDB_OFFSET = \"db.offset\" #\nDB_LIMIT = \"db.limit\"\n\n# 节点 ip 配置\nIPAGENT_IPTYPE = \"ipAgent.type\" # 节点类型\nIPAGENT_TPE_AUTOIP = \"ipAgent.autoIP\"\nIPAGENT_TPE_PROXYIP = \"ipAgent.proxyIP\"\nIPAGENT_TPE_FIXEDIP = \"ipAgent.fixedIP\"\n\n\nGD_JOB_ERROR = \"jobError\" # 工作错误\nGD_LOGGER = \"logger\" # #日志记录器\nGD_CFG_IN = \"cfgIn\" # 配置在\nGD_SUB = \"subGlobal\" # 子类全局\nGD_SPIDER = \"subSpider\" # 子类爬虫全局\nGD_TRAINER = \"subTrainer\" # 子类训练器全局\n\n\nEXCEPTION_PREFIX = \"!myex!\" # 异常的前缀\nINVALID_JOB_NAME = 'undef_job' # 无效的 工作名称\nINVALID_VERSIONID = \"no_versionId\" # 没有爬虫工作的版本的id\n\nHTTP_BROWSER = \"http.browser\" # 获取浏览器\n\n# 反扒策略的配置\nCFG_BLOCK_MAXCHECK = \"block.maxCheck\" # 最大量检查\n\n# 账号的配置\nCFG_ACCOUNT_PROVIDER = \"account.provider\" #账户提供者\n\n\nERR_BLOCK = -401\nERR_TIMEOUT = -402\nERR_NOCONTENT = -403\nERR_MAXNUM = -404\nERR_LOGIN_FAIL = -405\nBLOCKED_INFO = 1\nBLOCKED_ELEMENT = 2\nBLOCKED_EXIT = -1\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"utility/configVariateUnit.py","file_name":"configVariateUnit.py","file_ext":"py","file_size_in_byte":4779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"629216974","text":"class dog:\n dogs={'red':['red',80,1000],'blue':['blue',50,2000],'yellow':['yellow',40,3000]}\n def show(self):\n print('color num price')\n print(self.dogs['red'])\n print(self.dogs['blue'])\n print(self.dogs['yellow'])\n\n def change(self):\n a=str(input('color is:'))\n b=int(input('num is:'))\n for x,y in self.dogs.items():\n if x == a:\n y[1]=y[1]-b\n print('money is:',b*y[2])\n print('还剩下',y[1],'只',y[0],'狗')\n\n\nd=dog()\nd.show()\nfor i in range(3):\n d.change()\n\n","sub_path":"homework6/r-01.py","file_name":"r-01.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"197420538","text":"# 2 4 2\n# 8\n# 1 2 1\n# 2 1 1\n# 3 1 2\n# 4 2 2\n# 3 4 3\n# 4 3 3\n# 1 3 4\n# 2 4 4\n\n# data preprocessing\n\nimport math\nimport random\n\nline = input()\nline_int = line.split(' ')\nm = int(line_int[0])\nk = int(line_int[1])\nh = int(line_int[2])\n\nn = int(input())\ndata = {}\nclasses = []\ndata_arr = []\n\nfor i in range(n):\n line = input()\n line_int = line.split(' ')\n\n row = []\n for x in line_int:\n row.append(int(x))\n\n obj = {}\n obj[\"c\"] = line_int[m]\n line_int.pop(m)\n obj[\"f\"] = line_int\n\n data[i] = obj\n\n classes.append(obj[\"c\"])\n data_arr.append(row)\n\n# print(data)\n\n# creating tree\n\nnum_attributes = m\nnum_classes = k\ntree_high = h + 1\n\n# classes\n# data_arr\n\nattributes = []\nfor i in range(m):\n attributes.append(i)\n\n\nclass Node:\n def __init__(self, isLeaf, label, threshold):\n self.label = label\n self.isLeaf = isLeaf\n self.threshold = threshold\n self.children = []\n\n\ndef isSameClass(data):\n first_class = data[0][num_attributes]\n for row in data:\n if row[num_attributes] != first_class:\n return False\n return first_class\n\n\ndef getClass(data):\n classes_freq = []\n for i in range(num_classes):\n classes_freq.append(0)\n\n for row in data:\n classes_freq[row[num_attributes] - 1] += 1\n\n max_freq = classes_freq.index(max(classes_freq))\n return (max_freq + 1)\n\n\ndef getRandomThresholds(t_range, number):\n thresholds = []\n for ii in range(number):\n t = random.randint(0, t_range - 1)\n thresholds.append(t)\n return thresholds\n\n\ndef createTree(data, attributes, high):\n sameClass = isSameClass(data)\n\n if (len(data) == 0):\n\n return Node(True, \"Empty\", None)\n elif (sameClass != False):\n return Node(True, int(sameClass) - 1, None)\n elif (len(attributes) == 0):\n return Node(True, int(getClass(data)) - 1, None)\n elif (high >= tree_high):\n return Node(True, int(getClass(data)) - 1, None)\n else:\n (best_attribute, best_threshold, splitted) = split_attributes(data, attributes)\n if (best_attribute == -1):\n return Node(True, int(getClass(data)) - 1, None)\n remaining_attributes = attributes[:]\n remaining_attributes.remove(best_attribute)\n node = Node(False, best_attribute, best_threshold)\n node.children = [createTree(subset, remaining_attributes, high + 1) for subset in splitted]\n if (node.children[0].isLeaf == True & node.children[1].isLeaf == True & node.children[1].label == node.children[\n 0].label):\n return Node(True, node.children[0].label, None)\n # return Node(True, node.children[0].label, None)\n else:\n return node\n\n\ndef gain(fullSet, subsets, imp_bef):\n s = len(fullSet)\n # impurityBefore = entropy(fullSet)\n impurityBefore = imp_bef\n\n weights = [len(subset) / s for subset in subsets]\n impurityAfter = 0\n for i in range(len(subsets)):\n impurityAfter += weights[i] * entropy(subsets[i])\n\n gain = impurityBefore - impurityAfter\n\n if gain < 0:\n gain = -1 * float(\"inf\")\n\n return gain\n\n\ndef entropy(dataSet):\n s = len(dataSet)\n if s == 0:\n return 0\n n_c = [0 for j in classes]\n\n for row in dataSet:\n class_index = row[num_attributes]\n n_c[class_index - 1] += 1\n\n n_c = [x / s for x in n_c]\n\n ent = 0\n for n in n_c:\n ent += n * log(n)\n\n return ent * (-1)\n\n\ndef log(x):\n if (x == 0):\n return 0\n else:\n return math.log(x, 2)\n\n\ndef split_attributes(current_data, current_attributes):\n splitted = []\n max_entropy = -1 * float(\"inf\")\n best_attribute = -1\n best_threshold = None\n\n impurityBefore = entropy(current_data)\n\n for attribute in current_attributes:\n # 1\n attribute_index = attribute\n\n current_data.sort(key=lambda x: x[attribute_index])\n\n # random_thresholds = getRandomThresholds(len(current_data) - 1, 4)\n middle_threshold = int((len(current_data) - 1) / 2)\n random_thresholds = []\n random_thresholds.append(middle_threshold)\n\n # for i in range(len(current_data) - 1):\n for i in random_thresholds:\n if current_data[i][attribute_index] != current_data[i + 1][attribute_index]:\n threshold = (current_data[i][attribute_index] + current_data[i + 1][attribute_index]) / 2\n less = []\n greater = []\n\n for row in current_data:\n if (row[attribute_index] > threshold):\n greater.append(row)\n else:\n less.append(row)\n\n e = gain(current_data, [less, greater], impurityBefore)\n if e > max_entropy:\n splitted = [less, greater]\n max_entropy = e\n best_attribute = attribute\n best_threshold = threshold\n\n return (best_attribute, best_threshold, splitted)\n\n\nprint_tree = []\n\n\ndef printTree(node, count):\n node_type = \"\"\n if node.isLeaf == True:\n node_type = \"C\"\n else:\n node_type = \"Q\"\n\n n_attribute = str(int(node.label) + 1)\n\n t = \"\"\n if node.threshold != None:\n t = str(node.threshold)\n\n node_str = node_type + \" \" + n_attribute + \" \" + t\n\n print_tree.append(node_str)\n if (node.children):\n first_count = printTree(node.children[0], count + 1)\n second_count = printTree(node.children[1], first_count + 1)\n\n string = print_tree[count - 1]\n string += (\" \" + str(count + 1))\n string += (\" \" + str(first_count + 1))\n print_tree[count - 1] = string\n\n count = second_count\n\n return count\n\n\nroot = createTree(data_arr, attributes, 1)\nprintTree(root, 1)\nprint(len(print_tree))\nfor node_str in print_tree:\n print(node_str)\n","sub_path":"nas_ml3.py","file_name":"nas_ml3.py","file_ext":"py","file_size_in_byte":5866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"237385458","text":"from urllib.request import urlopen\nfrom urllib.error import HTTPError\nfrom bs4 import BeautifulSoup\nimport re\n\nURL=\"http://www.pythonscraping.com/pages/page1.html\"\n\ndef getTitle(url):\n try:\n html=urlopen(URL)\n except HTTPError as e:\n print(\"html open error\")\n return None\n try:\n bs=BeautifulSoup(html.read(), 'lxml')\n title=bs.body.h1\n except AttributeError as e:\n print(\"Attribute error\")\n return None\n\n return title\n\ntitle=getTitle(URL)\nprint(title)\n\nhtml=urlopen('http://www.pythonscraping.com/pages/warandpeace.html')\nbs=BeautifulSoup(html.read(), 'html.parser')\nnameList=bs.findAll(\"span\", {\"class\": \"green\"}) #\nfor name in nameList:\n print(name.get_text())\ntitles=bs.findAll(['h1', 'h2', 'h3', 'h4', 'h5', 'h6'])\nprint('===')\nprint([title for title in titles])\nprint('--')\nfor title in titles:\n print(title)\nprint('----')\nallTextGreenRed=bs.find_all('span', {'class' : {'green', 'red'}}) #greek OR red\nprint([text for text in allTextGreenRed])\nprint('--the prince')\nnameList=bs.find_all(text={'the prince', 'The prince'})\nprint(len(nameList))\n\nhtml=urlopen('http://www.pythonscraping.com/pages/page3.html')\nbs=BeautifulSoup(html, 'html.parser')\nprint(\"---line46\")\nfor child in bs.find('table', {'id' : 'giftList'}).children:\n print(child)\n\nprint(bs.find('img', {'src':'../img/gifts/img1.jpg'}).parent.previous_sibling.get_text())\nimages=bs.find_all('img',{'src':re.compile('\\.\\.\\/img\\/gifts\\/img.*\\.jpg')})\nfor image in images:\n print(image['src'])\n\nattr2=bs.find_all(lambda tag:len(tag.attrs)==2)\nprint('attr2 list ================')\n\nj=0\nfor i in attr2:\n print(f'{j}th')\n print(i)\n j=j+1\n \n","sub_path":".vscode/mych2.py","file_name":"mych2.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"124806193","text":"##\n## Copyright (C) 2015 Aditya Patange.\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\nclass Encryptor(object):\n std_lang = {} # Mapping from (1,LANG_LEN)->(Supported characters that can be encrypted)\n LANG_LEN = 0 # Total number of supported encryptable characters\n\n def __init__(self):\n lang = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!@#$%^&*()_-+={}[]:;',.<>?/\\| 0123456789~`\"+ '\"' \n for looper in range(len(lang)):\n index = looper+1\n self.std_lang[index] = lang[looper]\n self.LANG_LEN = len(lang)\n\n def shiftAlp(self,alps, shift):\n assert type(alps) is dict and (type(shift) is int or type(shift) is long)\n shifted_alps = {}\n\n #\n # Shift must not be a multiple of LANG_LEN , else no encryption will occur\n # In that case, increment by 1.\n #\n\n #if(shift/self.LANG_LEN == 0):\n # shift += 1\n\n # 0 <= shift < LANG_LEN\n for index in alps:\n newIndex = index+shift\n if index+shift > self.LANG_LEN:\n newIndex = (index+shift)%self.LANG_LEN\n shifted_alps[index] = alps[newIndex]\n return shifted_alps\n\n\n def textToIndexed(self,lang, text):\n assert type(lang) is dict and type(text) is str\n indexedForm = \"\"\n for c in text:\n for key,val in lang.items():\n if c == val:\n indexedForm += \" \"+str(key)\n return indexedForm\n \n \n def indexedToText(self,lang, indexedText):\n assert type(lang) is dict and type(indexedText) is str\n text = \"\"\n indexedText = indexedText[1:len(indexedText)] # Chop first blank character\n for c in indexedText:\n if len(indexedText) is 0:\n break\n #\n # Alphabet code of the current letter being scanned\n #\n alpCode = indexedText[0] # Pull first digit\n \n # Check if second digit exists\n try:\n if indexedText[1] != \" \":\n alpCode += indexedText[1]\n # chop indexedText\n indexedText = indexedText[3:len(indexedText)]\n else:\n indexedText = indexedText[2:len(indexedText)]\n except IndexError:\n itlen = len(indexedText) #either 1 or 2\n if itlen is 2:\n alpCode += indexedText[index+1]\n indexedText = \"\"\n text += lang[int(alpCode)]\n return text\n def encrypt(self,text, key):\n assert type(text) is str and (type(key) is int or type(key) is long)\n # Generate key\n shift = key%self.LANG_LEN\n shifted_lang = self.shiftAlp(self.std_lang, shift)\n encryptedText = self.indexedToText(shifted_lang, self.textToIndexed(self.std_lang, text))\n return encryptedText\n\n def decrypt(self,text, key):\n assert type(text) is str and (type(key) is int or type(key) is long)\n # Generate key\n shift = key%self.LANG_LEN\n shifted_lang = self.shiftAlp(self.std_lang, shift)\n decryptedText = self.indexedToText(self.std_lang, self.textToIndexed(shifted_lang, text))\n return decryptedText\n","sub_path":"CCEncryptor.py","file_name":"CCEncryptor.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"277582335","text":"\"\"\"\n1. broken : we have K-1 egges left, and we know 0<=F D(K-1, i-1)\n1. Unbroken : we still have K eggs, and we know 0<=F<=N, N-i (i+1~N) floors left -> D(K, N-i)\n\nWe need to know the worst case -> max(D(K-1, i), D(K, N-i))\n\n\"\"\"\n\nfrom functools import lru_cache\n\nclass Solution:\n def superEggDrop(self, K: int, N: int) -> int:\n memo = [[float('inf') for i in range(N + 1)] for j in range(K + 1)]\n\n @lru_cache(None)\n def dp(k, n):\n if k == 0:\n return 0\n if k == 1:\n return n\n if n <= 1:\n return n\n res = memo[k][n]\n for i in range(1, n + 1):\n res = min(res, 1 + max(dp(k - 1, i - 1), dp(k, n - i)))\n return res\n\n return dp(K, N)\n\n\n\nclass SolutionLee:\n def superEggDrop(self, K, N):\n dp = [[0] * (K + 1) for i in range(N + 1)]\n for m in range(1, N + 1):\n for k in range(1, K + 1):\n dp[m][k] = dp[m - 1][k - 1] + dp[m - 1][k] + 1\n if dp[m][K] >= N:\n return m\n\n\n\n\n\n\n","sub_path":"LeetcodeNew/python/LC_887.py","file_name":"LC_887.py","file_ext":"py","file_size_in_byte":1118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"1820615","text":"from tensorflow.python.framework import ops\nfrom tensorflow.python.keras.optimizer_v2 import optimizer_v2\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_resource_variable_ops\nfrom tensorflow.python.keras.optimizer_v2 import learning_rate_schedule\nfrom tensorflow.python.training import gen_training_ops\nfrom tensorflow.python.util.tf_export import keras_export\nfrom tensorflow_addons.optimizers import DecoupledWeightDecayExtension\n\nimport tensorflow as tf\nimport re\n\n__all__ = ['SGD']\n\ndef _var_key(var):\n \"\"\"Key for representing a primary variable, for looking up slots.\n In graph mode the name is derived from the var shared name.\n In eager mode the name is derived from the var unique id.\n If distribution strategy exists, get the primary variable first.\n Args:\n var: the variable.\n Returns:\n the unique name of the variable.\n \"\"\"\n\n # pylint: disable=protected-access\n # Get the distributed variable if it exists.\n if hasattr(var, \"_distributed_container\"):\n var = var._distributed_container()\n if var._in_graph_mode:\n return var._shared_name\n return var._unique_id\n\n\nclass SGDMomentumWarmupW(optimizer_v2.OptimizerV2):\n r\"\"\"Gradient descent (with momentum) optimizer.\n Update rule for parameter `w` with gradient `g` when `momentum` is 0:\n ```python\n w = w - learning_rate * g\n ```\n Update rule when `momentum` is larger than 0:\n ```python\n velocity = momentum * velocity - learning_rate * g\n w = w + velocity\n ```\n When `nesterov=True`, this rule becomes:\n ```python\n velocity = momentum * velocity - learning_rate * g\n w = w + momentum * velocity - learning_rate * g\n ```\n Args:\n learning_rate: A `Tensor`, floating point value, or a schedule that is a\n `tf.keras.optimizers.schedules.LearningRateSchedule`, or a callable\n that takes no arguments and returns the actual value to use. The\n learning rate. Defaults to 0.01.\n momentum: float hyperparameter >= 0 that accelerates gradient descent\n in the relevant\n direction and dampens oscillations. Defaults to 0, i.e., vanilla gradient\n descent.\n nesterov: boolean. Whether to apply Nesterov momentum.\n Defaults to `False`.\n name: Optional name prefix for the operations created when applying\n gradients. Defaults to `\"SGD\"`.\n **kwargs: Keyword arguments. Allowed to be one of\n `\"clipnorm\"` or `\"clipvalue\"`.\n `\"clipnorm\"` (float) clips gradients by norm; `\"clipvalue\"` (float) clips\n gradients by value.\n Usage:\n >>> opt = tf.keras.optimizers.SGD(learning_rate=0.1)\n >>> var = tf.Variable(1.0)\n >>> loss = lambda: (var ** 2)/2.0 # d(loss)/d(var1) = var1\n >>> step_count = opt.minimize(loss, [var]).numpy()\n >>> # Step is `- learning_rate * grad`\n >>> var.numpy()\n 0.9\n >>> opt = tf.keras.optimizers.SGD(learning_rate=0.1, momentum=0.9)\n >>> var = tf.Variable(1.0)\n >>> val0 = var.value()\n >>> loss = lambda: (var ** 2)/2.0 # d(loss)/d(var1) = var1\n >>> # First step is `- learning_rate * grad`\n >>> step_count = opt.minimize(loss, [var]).numpy()\n >>> val1 = var.value()\n >>> (val0 - val1).numpy()\n 0.1\n >>> # On later steps, step-size increases because of momentum\n >>> step_count = opt.minimize(loss, [var]).numpy()\n >>> val2 = var.value()\n >>> (val1 - val2).numpy()\n 0.18\n Reference:\n - For `nesterov=True`, See [Sutskever et al., 2013](\n http://jmlr.org/proceedings/papers/v28/sutskever13.pdf).\n \"\"\"\n\n _HAS_AGGREGATE_GRAD = True\n\n def __init__(self,\n weight_decay=0.0,\n learning_rate=0.01,\n momentum=0.0,\n momentum_start=0.0,\n warmup_steps=1000,\n nesterov=False,\n sim_torch=False,\n weight_keys = [\"kernel\"], \n bias_keys = [\"bias\", \"beta\"], \n name=\"SGD\",\n **kwargs):\n super(SGDMomentumWarmupW, self).__init__(name, **kwargs)\n self._weight_keys = weight_keys\n self._bias_keys = bias_keys \n\n # Create Hyper Params for each group of the LR \n self._set_hyper(\"learning_rate\", kwargs.get(\"lr\", learning_rate))\n self._set_hyper(\"bias_learning_rate\", kwargs.get(\"lr\", learning_rate))\n self._set_hyper(\"other_learning_rate\", kwargs.get(\"lr\", learning_rate))\n\n # SGD decay param\n self._set_hyper(\"decay\", self._initial_decay)\n \n # Weight decay param\n self._weight_decay = weight_decay != 0.0\n self._set_hyper(\"weight_decay\", weight_decay)\n\n # Enable Momentum \n self._momentum = False\n if isinstance(momentum, ops.Tensor) or callable(momentum) or momentum > 0:\n self._momentum = True\n if isinstance(momentum, (int, float)) and (momentum < 0 or momentum > 1):\n raise ValueError(\"`momentum` must be between [0, 1].\")\n self._set_hyper(\"momentum\", momentum)\n self._set_hyper(\"momentum_start\", momentum_start)\n self._set_hyper(\"warmup_steps\", tf.cast(warmup_steps, tf.int32))\n\n # Enable Nesterov Momentum \n self.nesterov = nesterov\n\n # Simulate Pytorch Optimizer\n self.sim_torch = sim_torch\n \n # weights, biases, other\n self._wset = set() \n self._bset = set()\n self._oset = set()\n\n def set_bias_lr(self, lr):\n self._set_hyper(\"bias_learning_rate\", lr)\n\n def set_other_lr(self, lr):\n self._set_hyper(\"other_learning_rate\", lr)\n\n def set_params(self, weights, biases, others):\n self._wset = set([_var_key(w) for w in weights])\n self._bset = set([_var_key(b) for b in biases])\n self._oset = set([_var_key(o) for o in others])\n print(\" weights: \", len(weights), \n \" biases: \", len(biases), \n \" others: \", len(others))\n return \n\n def _create_slots(self, var_list):\n if self._momentum:\n for var in var_list:\n self.add_slot(var, \"momentum\")\n\n def _get_momentum(self, iteration):\n momentum = self._get_hyper(\"momentum\")\n momentum_start = self._get_hyper(\"momentum_start\")\n momentum_warm_up_steps = tf.cast(\n self._get_hyper(\"warmup_steps\"), iteration.dtype)\n value = tf.cond(\n (iteration - momentum_warm_up_steps) <= 0,\n true_fn=lambda: (momentum_start +\n (tf.cast(iteration, momentum.dtype) *\n (momentum - momentum_start) / tf.cast(\n momentum_warm_up_steps, momentum.dtype))),\n false_fn=lambda: momentum)\n return value\n\n def _prepare_local(self, var_device, var_dtype, apply_state):\n super(SGDMomentumWarmupW, self)._prepare_local(var_device, var_dtype,\n apply_state)\n weight_decay = self._get_hyper(\"weight_decay\")\n apply_state[(var_device,\n var_dtype)][\"weight_decay\"] = tf.cast(weight_decay, var_dtype)\n\n if self._momentum:\n momentum = self._get_momentum(self.iterations)\n momentum = tf.cast(momentum, var_dtype)\n apply_state[(var_device,\n var_dtype)][\"momentum\"] = array_ops.identity(momentum)\n\n bias_lr = self._get_hyper(\"bias_learning_rate\")\n if isinstance(bias_lr, learning_rate_schedule.LearningRateSchedule):\n bias_lr = bias_lr(self.iterations)\n bias_lr = tf.cast(bias_lr, var_dtype)\n apply_state[(var_device,\n var_dtype)][\"bias_lr_t\"] = array_ops.identity(bias_lr)\n\n other_lr = self._get_hyper(\"other_learning_rate\")\n if isinstance(other_lr, learning_rate_schedule.LearningRateSchedule):\n other_lr = other_lr(self.iterations)\n other_lr = tf.cast(other_lr, var_dtype)\n apply_state[(var_device,\n var_dtype)][\"other_lr_t\"] = array_ops.identity(other_lr)\n\n return apply_state[(var_device, var_dtype)]\n\n def _apply_tf(self, grad, var, weight_decay, momentum, lr):\n def decay_op(var, learning_rate, wd):\n if self._weight_decay and wd > 0:\n return var.assign_sub(\n learning_rate * var * wd,\n use_locking=self._use_locking)\n return tf.no_op()\n\n decay = decay_op(var, lr, weight_decay)\n with tf.control_dependencies([decay]):\n if self._momentum:\n momentum_var = self.get_slot(var, \"momentum\")\n return gen_training_ops.ResourceApplyKerasMomentum(\n var=var.handle,\n accum=momentum_var.handle,\n lr=lr,\n grad=grad,\n momentum=momentum,\n use_locking=self._use_locking,\n use_nesterov=self.nesterov)\n else:\n return gen_training_ops.ResourceApplyGradientDescent(\n var=var.handle, alpha=lr, delta=grad, use_locking=self._use_locking)\n\n def _apply(self, grad, var, weight_decay, momentum, lr):\n dparams = grad\n groups = []\n\n if self._weight_decay:\n dparams += (weight_decay * var)\n\n if self._momentum:\n momentum_var = self.get_slot(var, \"momentum\")\n momentum_update = momentum_var.assign(\n momentum * momentum_var + dparams, use_locking=self._use_locking)\n groups.append(momentum_update)\n\n if self.nesterov:\n dparams += (momentum * momentum_update)\n else:\n dparams = momentum_update\n\n weight_update = var.assign_add(-lr * dparams, use_locking=self._use_locking)\n groups.append(weight_update)\n return tf.group(*groups)\n\n def _get_vartype(self, var, coefficients):\n if (_var_key(var) in self._wset):\n return True, False, False\n elif (_var_key(var) in self._bset):\n return False, True, False\n return False, False, True\n\n def _run_sgd(self, grad, var, apply_state=None):\n var_device, var_dtype = var.device, var.dtype.base_dtype\n coefficients = ((apply_state or {}).get((var_device, var_dtype)) or\n self._fallback_apply_state(var_device, var_dtype))\n\n weights, bias, others = self._get_vartype(var, coefficients)\n weight_decay = tf.zeros_like(coefficients[\"weight_decay\"])\n lr = coefficients[\"lr_t\"]\n if weights:\n weight_decay = coefficients[\"weight_decay\"]\n lr = coefficients[\"lr_t\"]\n elif bias: \n weight_decay = tf.zeros_like(coefficients[\"weight_decay\"])\n lr = coefficients[\"bias_lr_t\"]\n elif others: \n weight_decay = tf.zeros_like(coefficients[\"weight_decay\"])\n lr = coefficients[\"other_lr_t\"]\n momentum = coefficients[\"momentum\"]\n\n if self.sim_torch:\n return self._apply(grad, var, weight_decay, momentum, lr)\n else:\n return self._apply_tf(grad, var, weight_decay, momentum, lr)\n\n def _resource_apply_dense(self, grad, var, apply_state=None):\n return self._run_sgd(grad, var, apply_state=apply_state)\n\n def _resource_apply_sparse(self, grad, var, indices, apply_state=None):\n # This method is only needed for momentum optimization.\n return self._run_sgd(grad, var, apply_state=apply_state)\n\n def _resource_apply_sparse_duplicate_indices(self, grad, var, indices,\n **kwargs):\n return self._run_sgd(grad, var)\n\n def get_config(self):\n config = super(SGDMomentumWarmupW, self).get_config()\n config.update({\n \"learning_rate\": self._serialize_hyperparameter(\"learning_rate\"),\n \"decay\": self._initial_decay,\n \"momentum\": self._serialize_hyperparameter(\"momentum\"),\n \"momentum_start\": self._serialize_hyperparameter(\"momentum_start\"),\n \"warmup_steps\": self._serialize_hyperparameter(\"warmup_steps\"),\n \"nesterov\": self.nesterov,\n })\n return config\n\n @property\n def learning_rate(self):\n return self._optimizer._get_hyper('learning_rate')","sub_path":"yolo/optimization/SGDMomentumWarmupW.py","file_name":"SGDMomentumWarmupW.py","file_ext":"py","file_size_in_byte":11446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"286421223","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 28 10:05:17 2019\n\n@author: QCB\n\"\"\"\n\nfrom load_img import show_img\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torchvision.transforms as transforms\nimg_to_tensor = transforms.ToTensor()\n\nfrom PIL import Image\n\nimport torchvision.models as models\nvgg = models.vgg19(pretrained=True).features\nvgg = vgg.cpu()\n\ndef make_model():\n model = models.vgg19(pretrained=True).features[:12]\n model = model.eval()\n return model\n\ndef extract_feature(model, imgpath):\n model.eval()\n img = Image.open(imgpath)\n img = img.resize((224, 224))\n tensor = img_to_tensor(img)\n result = model(Variable(torch.unsqueeze(tensor, dim=0).float(), requires_grad=False))\n #result_npy = result.data.cpu().numpy()\n return result\n\nif __name__ ==\"__main__\":\n model = make_model()\n imgpath = 'picture/content_Easy.bmp'\n tmp = extract_feature(model, imgpath)\n #tmp = tmp.clamp_(0 ,1)\n show_img(tmp)","sub_path":"sequ.py","file_name":"sequ.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"245856705","text":"try:\n fhand = open('mbox-short.txt')\nexcept:\n print('Bad File.')\n exit()\ncount = 0\n\nfor line in fhand:\n # Check to see if the line starts with From\n if line.startswith('From'):\n # Split the line and take second word which is the email\n email = line.split()[1]\n # Find position of @ and take the items on the left\n pos = email.find('@')\n name = email[:pos]\n # Split the name string\n full_name_list = name.split('.')\n for name in full_name_list:\n first_name = full_name_list[0]\n # Check if the full_name_list has two names and then set second_name to the second index\n if len(full_name_list) is 2:\n second_name = full_name_list[1]\n else:\n # If there is no second name set second_name to None\n second_name = None\n if second_name is None:\n full_name = first_name\n else:\n\n full_name = first_name+' ' + second_name\n\n print(count, ':', '\\nName', full_name, '\\nEmail', email)\n # Increase counter\n count = count+1\n\nprint(count)\n","sub_path":"py_find_email.py","file_name":"py_find_email.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"148244393","text":"# Copyright 2020 by B. Knueven, D. Mildebrath, C. Muir, J-P Watson, and D.L. Woodruff\n# This software is distributed under the 3-clause BSD License.\nimport os\nimport time\nimport logging\nimport random\nimport mpisppy.log\nimport mpisppy.utils.sputils as sputils\nimport mpisppy.cylinders.spoke as spoke\nimport mpi4py.MPI as mpi\n\nfrom math import inf, isclose\nfrom mpisppy.utils.xhat_tryer import XhatTryer\nfrom mpisppy.extensions.xhatbase import XhatBase\n\n# Could also pass, e.g., sys.stdout instead of a filename\nmpisppy.log.setup_logger(\"mpisppy.cylinders.xhatshufflelooper_bounder\",\n \"xhatclp.log\",\n level=logging.CRITICAL) \nlogger = logging.getLogger(\"mpisppy.cylinders.xhatshufflelooper_bounder\")\n\nclass XhatShuffleInnerBound(spoke.InnerBoundNonantSpoke):\n\n converger_spoke_char = 'X'\n\n def xhatbase_prep(self):\n if self.opt.multistage:\n raise RuntimeError('The XhatShuffleInnerBound only supports '\n 'two-stage models at this time.')\n\n verbose = self.opt.options['verbose']\n if \"bundles_per_rank\" in self.opt.options\\\n and self.opt.options[\"bundles_per_rank\"] != 0:\n raise RuntimeError(\"xhat spokes cannot have bundles (yet)\")\n\n # Start code to support running trace. TBD: factor this up?\n if self.cylinder_rank == 0 and \\\n 'suffle_running_trace_prefix' in self.opt.options and \\\n self.opt.options['shuffle_running_trace_prefix'] is not None:\n running_trace_prefix =\\\n self.opt.options['shuffle_running_trace_prefix']\n\n filen = running_trace_prefix+self.__class__.__name__+'.csv'\n if os.path.exists(filen):\n raise RuntimeError(f\"running trace file {filen} already exists!\")\n with open(filen, 'w') as f:\n f.write(\"time,scen,value\\n\")\n self.running_trace_filen = filen\n else:\n self.running_trace_filen = None\n # end code to support running trace\n \n if not isinstance(self.opt, XhatTryer):\n raise RuntimeError(\"XhatShuffleInnerBound must be used with XhatTryer.\")\n \n xhatter = XhatBase(self.opt)\n\n self.opt.subproblem_creation(verbose)\n\n ### begin iter0 stuff\n xhatter.pre_iter0()\n self.opt._save_original_nonants()\n self.opt._create_solvers()\n\n teeme = False\n if \"tee-rank0-solves\" in self.opt.options:\n teeme = self.opt.options['tee-rank0-solves']\n\n self.opt.solve_loop(\n solver_options=self.opt.current_solver_options,\n dtiming=False,\n gripe=True,\n tee=teeme,\n verbose=verbose\n )\n self.opt._update_E1() # Apologies for doing this after the solves...\n if abs(1 - self.opt.E1) > self.opt.E1_tolerance:\n if self.opt.cylinder_rank == 0:\n print(\"ERROR\")\n print(\"Total probability of scenarios was \", self.opt.E1)\n print(\"E1_tolerance = \", self.opt.E1_tolerance)\n quit()\n infeasP = self.opt.infeas_prob()\n if infeasP != 0.:\n if self.opt.cylinder_rank == 0:\n print(\"ERROR\")\n print(\"Infeasibility detected; E_infeas, E1=\", infeasP, self.opt.E1)\n quit()\n ### end iter0 stuff\n\n xhatter.post_iter0()\n self.opt._save_nonants() # make the cache\n\n ## for later\n self.verbose = self.opt.options[\"verbose\"] # typing aid \n self.solver_options = self.opt.options[\"xhat_looper_options\"][\"xhat_solver_options\"]\n self.xhatter = xhatter\n\n ## option drive this? (could be dangerous)\n self.random_seed = 42\n # Have a separate stream for shuffling\n self.random_stream = random.Random()\n\n\n def try_scenario(self, scenario):\n obj = self.xhatter._try_one({\"ROOT\":scenario},\n solver_options = self.solver_options,\n verbose=False,\n restore_nonants=False)\n def _vb(msg): \n if self.verbose and self.opt.cylinder_rank == 0:\n print (\"(rank0) \" + msg)\n\n if self.running_trace_filen is not None:\n with open(self.running_trace_filen, \"a\") as f:\n f.write(f\"{time.time()},{scenario},{obj}\\n\")\n if obj is None:\n _vb(f\" Infeasible {scenario}\")\n return False\n _vb(f\" Feasible {scenario}, obj: {obj}\")\n\n update = self.update_if_improving(obj)\n logger.debug(f' bottom of try_scenario on rank {self.global_rank}')\n return update\n\n def main(self):\n verbose = self.opt.options[\"verbose\"] # typing aid \n logger.debug(f\"Entering main on xhatshuffle spoke rank {self.global_rank}\")\n\n self.xhatbase_prep()\n\n # give all ranks the same seed\n self.random_stream.seed(self.random_seed)\n # shuffle the scenarios (i.e., sample without replacement)\n shuffled_scenarios = self.random_stream.sample(\n self.opt.all_scenario_names,\n len(self.opt.all_scenario_names))\n scenario_cycler = ScenarioCycler(shuffled_scenarios)\n\n def _vb(msg): \n if self.verbose and self.opt.cylinder_rank == 0:\n print(\"(rank0) \" + msg)\n\n xh_iter = 1\n while not self.got_kill_signal():\n\n if (xh_iter-1) % 100 == 0:\n logger.debug(f' Xhatshuffle loop iter={xh_iter} on rank {self.global_rank}')\n logger.debug(f' Xhatshuffle got from opt on rank {self.global_rank}')\n\n if self.new_nonants:\n # similar to above, not all ranks will agree on\n # when there are new_nonants (in the same loop)\n logger.debug(f' *Xhatshuffle loop iter={xh_iter}')\n logger.debug(f' *got a new one! on rank {self.global_rank}')\n logger.debug(f' *localnonants={str(self.localnonants)}')\n\n # update the caches\n self.opt._put_nonant_cache(self.localnonants)\n self.opt._restore_nonants()\n\n next_scenario = scenario_cycler.get_next()\n if next_scenario is not None:\n _vb(f\" Trying next {next_scenario}\")\n update = self.try_scenario(next_scenario)\n if update:\n _vb(f\" Updating best to {next_scenario}\")\n scenario_cycler.best = next_scenario\n else:\n scenario_cycler.begin_epoch()\n\n #_vb(f\" scenario_cycler._scenarios_this_epoch {scenario_cycler._scenarios_this_epoch}\")\n\n xh_iter += 1\n\n\nclass ScenarioCycler:\n\n def __init__(self, all_scenario_list):\n self._all_scenario_list = all_scenario_list\n self._num_scenarios = len(all_scenario_list)\n self._cycle_idx = 0\n self._cur_scen = all_scenario_list[0]\n self._scenarios_this_epoch = set()\n self._best = None\n\n @property\n def best(self):\n self._scenarios_this_epoch.add(self._best)\n return self._best\n\n @best.setter\n def best(self, value):\n self._best = value\n\n def begin_epoch(self):\n self._scenarios_this_epoch = set()\n\n def get_next(self):\n next_scen = self._cur_scen\n if next_scen in self._scenarios_this_epoch:\n self._iter_scen()\n return None\n self._scenarios_this_epoch.add(next_scen)\n self._iter_scen()\n return next_scen\n\n def _iter_scen(self):\n self._cycle_idx += 1\n ## wrap around\n self._cycle_idx %= self._num_scenarios\n self._cur_scen = self._all_scenario_list[self._cycle_idx]\n","sub_path":"mpisppy/cylinders/xhatshufflelooper_bounder.py","file_name":"xhatshufflelooper_bounder.py","file_ext":"py","file_size_in_byte":7827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"80976402","text":"import torch.nn as nn\nfrom mmcv.cnn.utils.weight_init import xavier_init\n\nfrom mmedit.models.registry import COMPONENTS\n\n\n@COMPONENTS.register_module()\nclass PlainDecoder(nn.Module):\n \"\"\"Simple decoder from Deep Image Matting.\n\n Args:\n in_channels (int): Channel num of input features.\n \"\"\"\n\n def __init__(self, in_channels):\n super().__init__()\n\n self.deconv6_1 = nn.Conv2d(in_channels, 512, kernel_size=1)\n self.deconv5_1 = nn.Conv2d(512, 512, kernel_size=5, padding=2)\n self.deconv4_1 = nn.Conv2d(512, 256, kernel_size=5, padding=2)\n self.deconv3_1 = nn.Conv2d(256, 128, kernel_size=5, padding=2)\n self.deconv2_1 = nn.Conv2d(128, 64, kernel_size=5, padding=2)\n self.deconv1_1 = nn.Conv2d(64, 64, kernel_size=5, padding=2)\n\n self.deconv1 = nn.Conv2d(64, 1, kernel_size=5, padding=2)\n\n self.relu = nn.ReLU(inplace=True)\n self.max_unpool2d = nn.MaxUnpool2d(kernel_size=2, stride=2)\n\n def init_weights(self):\n \"\"\"Init weights for the module.\n \"\"\"\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n xavier_init(m)\n\n def forward(self, inputs):\n \"\"\"Forward function of PlainDecoder.\n\n Args:\n inputs (dict): Output dictionary of the VGG encoder containing:\n\n - out (Tensor): Output of the VGG encoder.\n - max_idx_1 (Tensor): Index of the first maxpooling layer in the\n VGG encoder.\n - max_idx_2 (Tensor): Index of the second maxpooling layer in the\n VGG encoder.\n - max_idx_3 (Tensor): Index of the third maxpooling layer in the\n VGG encoder.\n - max_idx_4 (Tensor): Index of the fourth maxpooling layer in the\n VGG encoder.\n - max_idx_5 (Tensor): Index of the fifth maxpooling layer in the\n VGG encoder.\n\n Returns:\n Tensor: Output tensor.\n \"\"\"\n max_idx_1 = inputs['max_idx_1']\n max_idx_2 = inputs['max_idx_2']\n max_idx_3 = inputs['max_idx_3']\n max_idx_4 = inputs['max_idx_4']\n max_idx_5 = inputs['max_idx_5']\n x = inputs['out']\n\n out = self.relu(self.deconv6_1(x))\n out = self.max_unpool2d(out, max_idx_5)\n\n out = self.relu(self.deconv5_1(out))\n out = self.max_unpool2d(out, max_idx_4)\n\n out = self.relu(self.deconv4_1(out))\n out = self.max_unpool2d(out, max_idx_3)\n\n out = self.relu(self.deconv3_1(out))\n out = self.max_unpool2d(out, max_idx_2)\n\n out = self.relu(self.deconv2_1(out))\n out = self.max_unpool2d(out, max_idx_1)\n\n out = self.relu(self.deconv1_1(out))\n raw_alpha = self.deconv1(out)\n return raw_alpha\n","sub_path":"mmedit/models/backbones/encoder_decoders/decoders/plain_decoder.py","file_name":"plain_decoder.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"378021127","text":"import torch\nfrom torch import nn, einsum\nfrom einops import rearrange\nimport torch.nn.functional as F\nimport math\nfrom bio_attention import positional\n\n\ndef compl_mod(m, n):\n return int(n * math.ceil(m / n) - m)\n\n\nclass Attention(torch.nn.Module):\n def __init__(\n self,\n dropout=0.0,\n enable_math=True,\n enable_flash=True,\n enable_mem_efficient=True,\n **kwargs,\n ):\n super().__init__()\n self.dropout = dropout\n self.context_manager = {\n \"enable_math\": enable_math,\n \"enable_flash\": enable_flash,\n \"enable_mem_efficient\": enable_mem_efficient,\n }\n self.use_context_manager = not all(\n [enable_math, enable_flash, enable_mem_efficient]\n )\n\n def forward(self, q, k, v, mask=None, causal=False):\n \"\"\"Default attention layer\n\n Parameters\n ----------\n q : B, *, L1, NH, H\n queries\n k : B, *, L2, NH, H\n keys\n v : B, *, L2, NH, H\n values\n mask : B, *, NH, L1, L2, optional\n _description_, by default None\n causal : bool, optional\n whether to do causal attention or not, by default False\n\n Returns\n -------\n _type_\n _description_\n \"\"\"\n q_shape = q.shape\n q, k, v = map(\n lambda t: rearrange(t, \"b ... x n h -> (b ...) x n h\").permute(0, 2, 1, 3),\n (q, k, v),\n ) # (B...), NH, L, H\n if mask is not None:\n mask = rearrange(mask, \"b ... n q k -> (b ...) n q k\") # (B...), NH, L1, L2\n\n if causal:\n causal_mask = torch.ones(q.shape[-2], k.shape[-2], dtype=torch.bool)\n causal_mask = causal_mask.triu(diagonal=0).expand(q.shape[0], q.shape[1], -1, -1)\n mask = (mask if mask is not None else (causal_mask).to(q)).masked_fill(causal_mask, -float('inf'))\n\n if self.use_context_manager:\n with torch.backends.cuda.sdp_kernel(**self.context_manager):\n return (\n F.scaled_dot_product_attention(\n q,\n k,\n v,\n dropout_p=(self.dropout if self.training else 0),\n attn_mask=mask,\n is_causal=False,\n )\n .permute(0, 2, 1, 3)\n .view(*q_shape)\n )\n else:\n return (\n F.scaled_dot_product_attention(\n q,\n k,\n v,\n dropout_p=(self.dropout if self.training else 0),\n attn_mask=mask,\n is_causal=False,\n )\n .permute(0, 2, 1, 3)\n .view(*q_shape)\n )\n\n\nclass RandomAttention(nn.Module):\n def __init__(\n self,\n n_random_keys=64,\n dropout=0.2,\n materialize_full=False,\n **kwargs,\n ):\n super().__init__()\n if not materialize_full:\n self.softmax = nn.Softmax(dim=-2)\n self.dropout = nn.Dropout(dropout)\n\n self.forward = self.forward_indexed\n else:\n self.dropout = dropout\n self.forward = self.forward_naive\n self.n = n_random_keys\n\n def forward_indexed(self, q, k, v, mask=None, causal=False):\n \"\"\"random attention layer\n\n NOTE: causal attention will erase input masks\n\n Parameters\n ----------\n q : B, *, L1, NH, H\n queries\n k : B, *, L2, NH, H\n keys\n v : B, *, L2, NH, H\n values\n mask : B, *, NH, L1, L2, optional\n _description_, by default None\n causal : bool, optional\n whether to do causal attention or not, by default False\n\n Returns\n -------\n _type_\n _description_\n \"\"\"\n assert not (causal and (mask is not None))\n\n q_shape = q.shape\n q, k, v = map(lambda t: rearrange(t, \"b ... x n h -> (b ...) x n h\"), (q, k, v))\n if mask is not None:\n mask = rearrange(mask, \"b ... n q k -> (b ...) n q k\")\n\n b, s2, nh, h = k.shape\n s1 = q.shape[1]\n\n mask = (\n torch.ones(b, nh, s1, s2, dtype=torch.bool).tril(diagonal=0)\n if causal\n else mask\n )\n if mask is not None:\n mask = (\n (~mask).float().masked_fill(~mask, -float(\"inf\"))\n if mask.dtype == torch.bool\n else mask\n )\n mask = mask.to(q)\n\n q = q * (h**-0.5)\n\n indices_select = torch.randint(0, s1, (b, s2, self.n)).to(q.device)\n indexer = torch.arange(b).view(b, 1, 1)\n if mask is not None:\n mask = mask.permute(0, 2, 3, 1)[\n indexer, torch.arange(s1)[None, :, None], indices_select\n ].permute(0, 3, 1, 2)\n\n k = k[indexer, indices_select]\n v = v[indexer, indices_select]\n\n A = einsum(\"b q n h, b q k n h -> b q k n\", q, k) + (\n 0 if mask is None else mask.permute(0, 2, 3, 1)\n )\n A = self.softmax(A)\n\n A = self.dropout(A)\n z = einsum(\"b q k n, b q k n h -> b q n h\", A, v)\n\n return z.view(*q_shape)\n\n def forward_naive(self, q, k, v, mask=None, causal=False):\n \"\"\"NOTE: Is incompatible with causal attention.\n NOTE: Is incompatible with input masks attention.\n\n Args:\n q (_type_): _description_\n k (_type_): _description_\n v (_type_): _description_\n mask (_type_, optional): _description_. Defaults to None.\n causal (bool, optional): _description_. Defaults to False.\n\n Returns:\n _type_: _description_\n \"\"\"\n q_shape = q.shape\n q, k, v = map(\n lambda t: rearrange(t, \"b ... x n h -> (b ...) x n h\").permute(0, 2, 1, 3),\n (q, k, v),\n )\n if mask is not None:\n mask = rearrange(mask, \"b ... n q k -> (b ...) n q k\")\n\n b, nh, s2, h = k.shape\n s1 = q.shape[-2]\n\n mask = (\n (torch.rand(b, 1, s1, s2) < (self.n / s2))\n .expand(-1, nh, -1, -1)\n .to(k.device)\n )\n\n return (\n F.scaled_dot_product_attention(\n q,\n k,\n v,\n dropout_p=(self.dropout if self.training else 0),\n attn_mask=mask,\n is_causal=causal,\n )\n .permute(0, 2, 1, 3)\n .view(*q_shape)\n )\n\n\nclass WindowAttention(nn.Module):\n def __init__(\n self,\n window=5,\n dropout=0.1,\n materialize_full=False,\n **kwargs,\n ):\n super().__init__()\n assert window % 2 == 1, \"Window size should be an odd integer.\"\n\n self.w = int((window - 1) / 2)\n\n if not materialize_full:\n self.softmax = nn.Softmax(dim=-1)\n self.dropout = nn.Dropout(dropout)\n self.k_ch = window * 2\n self.q_ch = window + 1\n\n u = torch.triu(torch.full((self.q_ch, self.k_ch), True))\n self.mask = ~torch.logical_and(u, torch.flip(u, [0, 1]))\n self.mask_k_left = torch.clone(self.mask)\n self.mask_k_left[:, : self.w] = True\n self.forward = self.forward_sliced\n\n else:\n self.dropout = dropout\n self.forward = self.forward_naive\n\n def forward_sliced(self, q, k, v, mask=None, causal=False):\n \"\"\"windowed attention layer\n\n Parameters\n ----------\n q : B, L1, NH, H\n queries\n k : B, L2, NH, H\n keys\n v : B, L2, NH, H\n values\n mask : B, NH, L1, L2, optional\n _description_, by default None\n causal : bool, optional\n whether to do causal attention or not, by default False\n\n Returns\n -------\n _type_\n _description_\n \"\"\"\n assert mask is None\n\n assert k.shape[-3] == q.shape[-3], \"q and k should have same input length.\"\n\n q_shape = q.shape\n q, k, v = map(lambda t: rearrange(t, \"b ... x n h -> (b ...) x n h\"), (q, k, v))\n\n b, s, nh, h = k.shape\n\n q = q * (h**-0.5)\n\n q_pad = compl_mod(s, self.q_ch)\n k_pad = compl_mod((s + self.w * 2) - self.k_ch, self.q_ch)\n\n q = F.pad(q, (0,) * 5 + (q_pad,)).unfold(1, self.q_ch, self.q_ch)\n k = F.pad(k, (0,) * 4 + (self.w, self.w + k_pad)).unfold(\n 1, self.k_ch, self.q_ch\n )\n v = F.pad(v, (0,) * 4 + (self.w, self.w + k_pad)).unfold(\n 1, self.k_ch, self.q_ch\n )\n\n A = einsum(\"b c n h q, b c n h k -> b n c q k \", q, k)\n\n mask_value = -torch.finfo(A.dtype).max\n mask_k_right = torch.clone(self.mask.to(A.device))\n mask_k_right[:, -(self.w + k_pad) :] = True\n if q.shape[1] > 1:\n mask = torch.stack(\n [self.mask_k_left.to(A.device)]\n + [self.mask.to(A.device)] * (q.shape[1] - 2)\n + [mask_k_right]\n )\n else:\n mask = torch.logical_or(\n self.mask_k_left.to(A.device), mask_k_right\n ).unsqueeze(0)\n if causal:\n mask = ~(~mask).tril(diagonal=self.w)\n\n A.masked_fill_(mask, mask_value)\n A = self.softmax(A)\n A = self.dropout(A)\n\n z = einsum(\"b n c q k, b c n h k -> b n c q h\", A, v)\n z = z.view(b, nh, -1, h)[:, :, :s].permute(0, 2, 1, 3).view(*q_shape)\n\n return z\n\n def forward_naive(self, q, k, v, mask=None, causal=False):\n assert mask is None\n assert k.shape[-3] == q.shape[-3], \"q and k should have same input length.\"\n\n q_shape = q.shape\n q, k, v = map(\n lambda t: rearrange(t, \"b ... x n h -> (b ...) x n h\").permute(0, 2, 1, 3),\n (q, k, v),\n )\n\n b, nh, s2, h = k.shape\n s1 = q.shape[-2]\n\n u = torch.triu(torch.full((s1, s2), True), diagonal=-self.w)\n mask = (\n torch.logical_and(u, torch.flip(u, [0, 1]))\n .expand(b, nh, -1, -1)\n .to(k.device)\n )\n if causal:\n mask = torch.tril(mask)\n return (\n F.scaled_dot_product_attention(\n q,\n k,\n v,\n dropout_p=(self.dropout if self.training else 0),\n attn_mask=mask,\n is_causal=False,\n )\n .permute(0, 2, 1, 3)\n .view(*q_shape)\n )\n\n\nclass AttnLayer(nn.Module):\n def __init__(self, dim, attn, nh=4, plugin=None):\n super().__init__()\n assert dim % nh == 0, \"dim should be divisible by number of heads\"\n\n self.lin = nn.Linear(dim, 3 * dim)\n self.attn = attn\n self.nh = nh\n\n self.plugin = plugin if plugin is not None else positional.Base()\n\n def forward(self, x, pos=None, mask=None, causal=False, **mod_kwargs):\n x = self.plugin.mod_x(x, pos=pos, **mod_kwargs)\n b, l, h = (x.size(0), x.size(-2), x.size(-1))\n q, k, v = torch.split(self.lin(x), h, dim=-1)\n q, k, v = map(\n lambda t: rearrange(t, \"... (n h) -> ... n h\", n=self.nh), (q, k, v)\n )\n\n mod_kwargs |= {\"pos_q_k\": pos}\n\n q, k, v = self.plugin.mod_qkv(q, k, v, **mod_kwargs)\n\n mask = self.plugin.mod_mask(mask, q, k, v, **mod_kwargs)\n\n return rearrange(\n self.attn(q, k, v, mask=mask, causal=causal),\n \"... n h -> ... (n h)\",\n n=self.nh,\n )\n\n\nclass Residual(nn.Module):\n def __init__(self, fn):\n super().__init__()\n self.fn = fn\n\n def forward(self, x, *args, **kwargs):\n return self.fn(x, *args, **kwargs) + x\n\n\nclass GLU(nn.Module):\n def __init__(self, dim, ff_dim, activation):\n super().__init__()\n self.act = activation\n self.proj = nn.Linear(dim, ff_dim * 2)\n\n def forward(self, x):\n x, gate = self.proj(x).chunk(2, dim=-1)\n return x * self.act(gate)\n\n\nclass TransformerLayer(nn.Module):\n def __init__(\n self, attn, dim, nh, plugin=None, dropout=0.2, glu_ff=True, activation=\"swish\"\n ):\n super().__init__()\n if activation.lower() == \"relu\":\n act = nn.ReLU()\n elif activation.lower() == \"gelu\":\n act = nn.GELU()\n elif activation.lower() == \"swish\":\n act = nn.SiLU()\n\n self.norm = nn.LayerNorm(dim)\n self.attn = AttnLayer(dim, attn, nh=nh, plugin=plugin)\n\n project_in = (\n nn.Sequential(nn.Linear(dim, 4 * dim), act)\n if not glu_ff\n else GLU(dim, 4 * dim, act)\n )\n self.ff = Residual(\n nn.Sequential(\n nn.LayerNorm(dim),\n project_in,\n nn.Dropout(dropout),\n nn.Linear(4 * dim, dim),\n )\n )\n\n def forward(self, x, pos=None, mask=None, causal=False, **mod_kwargs):\n x = self.attn(self.norm(x), pos=pos, mask=mask, causal=causal, **mod_kwargs) + x\n return self.ff(x)\n\n\nclass Transformer(nn.Module):\n def __init__(\n self,\n depth,\n dim,\n nh,\n attentiontype=\"vanilla\",\n attention_args={},\n plugintype=\"none\",\n plugin_args={},\n only_apply_plugin_at_first=False,\n dropout=0.2,\n glu_ff=True,\n activation=\"swish\",\n ):\n super().__init__()\n\n assert attentiontype in [\"vanilla\", \"random\", \"window\"]\n\n if attentiontype == \"vanilla\":\n attn_op = Attention(**attention_args)\n elif attentiontype == \"random\":\n attn_op = RandomAttention(**attention_args)\n elif attentiontype == \"window\":\n attn_op = WindowAttention(**attention_args)\n\n if plugintype == \"none\":\n plugin = positional.Base()\n elif plugintype == \"sinusoidal\":\n plugin = positional.Sinusoidal(**plugin_args)\n elif plugintype == \"learned\":\n plugin = positional.LearnedVocab(**plugin_args)\n elif plugintype == \"learnedcont\":\n plugin = positional.LearnedContinuous(**plugin_args)\n elif plugintype == \"rotary\":\n plugin = positional.Rotary(**plugin_args)\n elif plugintype == \"ALiBi\":\n plugin = positional.ALiBi(**plugin_args)\n elif plugintype == \"DPB\":\n plugin = positional.DPB(**plugin_args)\n elif plugintype == \"XL\":\n plugin = positional.XL(**plugin_args)\n\n layers = []\n layers.append(\n TransformerLayer(\n attn_op,\n dim,\n nh,\n plugin=plugin,\n dropout=dropout,\n glu_ff=glu_ff,\n activation=activation,\n )\n )\n \n for _ in range(depth - 1):\n layers.append(\n TransformerLayer(\n attn_op,\n dim,\n nh,\n plugin=(None if only_apply_plugin_at_first else plugin),\n dropout=dropout,\n glu_ff=glu_ff,\n activation=activation,\n )\n )\n \n\n self.layers = nn.ModuleList(layers)\n\n def forward(self, x, pos=None, mask=None, causal=False, **mod_kwargs):\n for layer in self.layers:\n x = layer(x, pos=pos, mask=mask, causal=causal, **mod_kwargs)\n return x\n\nclass TransformerEncoder(Transformer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n def forward(self, x, pos=None, mask=None, **mod_kwargs):\n for layer in self.layers:\n x = layer(x, pos=pos, mask=mask, causal=False, **mod_kwargs)\n return x\n \nclass TransformerDecoder(Transformer):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n def forward(self, x, pos=None, mask=None, **mod_kwargs):\n for layer in self.layers:\n x = layer(x, pos=pos, mask=mask, causal=True, **mod_kwargs)\n return x","sub_path":"bio_attention/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":16276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"90247865","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 27 12:54:53 2018\n\n@author: lorenzo\n\nquesto plto manc a1urn che viene -infintio\n\nps:(0.1,0.2,0.3) è un bel colore\n\naggiunta funzionalità per calcolare scatterplots coi nuovi nuovi folding rates\n\n23/11 aggiunto valore di gc calcolato da me: lo chiamo gcc (come 'Gc calcolato')\nla nomenclatura si sta facendo confuzionaria in questo file\n\n5/12 LINE 87: CAMBIATO file folding_rates con folding_rates3\n salva il plot direttamente in locale\n v2: aggiunti folding rates ancora diversi (vedi log, guarda come correla)\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#%%\ndata = \"\"\"0.6\n1.47\n6.63\n6.95\n11.12\n6.54\n6.61\n1.38\n8.75\n4.1\n7.28\n11.01\n5.66\n2.69\n1.17\n4.54\n1.06\n3.48\n7.35\n2.5\n0.41\n12.2\n6.56\n4.03\n9.67\n7.48\"\"\"\ndata = data.split()\nbaiesi_folding_rate = [float(dato) for dato in data]\nbaiesi_folding_rate[1] = -1.47\nbaiesi_index = \"\"\"1afi\n1aps\n1aye\n1bnz_a\n1bzp\n1csp\n1div.n\n1fkb\n1hrc\n1hz6_a\n1imq\n1lmb3\n1pgb\n1poh\n1psf\n1shf_a\n1ten\n1tit\n1ubq\n1urn\n1wit\n256b\n2abd\n2ci2\n2pdd\n2vik\"\"\".split()\nobserved_ln_freq=pd.Series(data=baiesi_folding_rate, index = baiesi_index).sort_index()\nprint(len(observed_ln_freq))\n#%%\n########################\n# estimated folding rates (now called efolding frequency):\n\nf=open(\"/home/lorenzo/opti/da/old_log/folding_rates3\")\nestimated_ln_freq=f.readlines()\nf.close()\nn=0\nestim_index=[]\nestim_data=[]\nfor line in estimated_ln_freq:\n if n<1:\n n+=1\n if n>=1:\n estim_index.append(line.split()[0])\n estim_data.append(round(float(line.split()[3]), 3))\nestimated_ln_freq=pd.Series(data=estim_data, index=estim_index).sort_index()\n\n\nprint(estimated_ln_freq) \n#%% nuovo modo:\np=[-2.221, -2.737, -0.747, -1.017, -2.409, -1.834, -0.35, -1.716, -0.571, -0.591, -0.488, -0.191, -0.469, -1.244, -1.734, -1.898, -2.13, -0.766, -1.681, 2.867, -0.767, -0.193, -0.043, -0.711, -0.378, -0.433]\nestimated_ln_fr = pd.Series(p, index=FR_index)\nprint(estimated_ln_fr)\nprint(p)\n\n#%%\n################################\n# real estimated FR using MEDIAN\n#\n# WARNING: \n# IN LINE 107 (f = open(\"/home/lo.../log/*_folding_rates_highest_benc\", \"r\"))\n# IF CALCULATING WITH MEAN: USE FILE 'real_folding_rates_highest_bench'\n# IF CALCULATING WITH MEDIAN: USE FILE 'MEDIAN_real_folding_rates_highest_bench'\n\nf=open(\"/home/lorenzo.signorini/tirocinio/log/median_real_folding_rates_highest_bench\", \"r\")\nmedian_estimated_ln_FR=f.readlines()\nf.close()\nFR_index=[]\nFR_data=[]\nfor line in median_estimated_ln_FR:\n if line.startswith(\"#\"):\n continue\n else:\n FR_index.append(line.split(\"\\t\\t\")[0])\n FR_data.append(round(float(line.split()[3]), 3))\nmedian_estimated_ln_FR=pd.Series(data=FR_data, index=FR_index).sort_index()\n################################\n# real estimated FR using MEAN\n\nf=open(\"/home/lorenzo.signorini/tirocinio/log/real_folding_rates_highest_bench\", \"r\")\nmean_estimated_ln_FR=f.readlines()\nf.close()\nFR_index=[]\nFR_data=[]\nfor line in mean_estimated_ln_FR:\n if line.startswith(\"#\"):\n continue\n else:\n FR_index.append(line.split(\"\\t\\t\")[0])\n FR_data.append(round(float(line.split()[3]), 3))\nmean_estimated_ln_FR=pd.Series(data=FR_data, index=FR_index).sort_index()\nprint(mean_estimated_ln_FR, mean_estimated_ln_FR.shape)\n#%%\n###################\n# topological coso:\ntopo = pd.Series([0.77,1.62,0.27,0.27,0.47,0.4,0.84,0.96,0.56,0.54,0.5,0.3,0.39,0.49,0.47,0.71,0.67,0.61,0.47,1.15,0.72,0.33,0.6,0.68,0.3,0.86], index=median_estimated_ln_FR.index).to_frame()\n#####################\n# calculated Gc: gcc\ngcc = pd.Series([0.707, 1.487, 0.237, 0.256, 0.429, 0.384, 0.744, 0.839, 0.429, 0.509, 0.414, 0.29, 0.327, 0.439, 0.392, 0.654, 0.593, 0.527, 0.41, 1.038, 0.59, 0.313, 0.502, 0.588, 0.293, 0.55], index=median_estimated_ln_FR.index).to_frame()\n#%% merge series in dataframes\n\n# 1estimated folding frequency\nest_vs_obs_ln_freq = estimated_ln_freq.to_frame() # la x\nest_vs_obs_ln_freq = est_vs_obs_ln_freq.merge(observed_ln_freq.to_frame(), right_index=True, left_index=True) #la y\n\nest_freq_vs_topo = estimated_ln_freq.to_frame()\nest_freq_vs_topo = est_freq_vs_topo.merge(topo, right_index=True, left_index=True)\n\nest_freq_vs_gcc = estimated_ln_freq.to_frame()\nest_freq_vs_gcc = est_freq_vs_gcc.merge(gcc, right_index=True, left_index=True)\n#%%\n#2 estimated folding rate (mean method)\nmean_est_vs_obs_FR = mean_estimated_ln_FR.to_frame()\nmean_est_vs_obs_FR = mean_est_vs_obs_FR.merge(observed_ln_freq.to_frame(), right_index=True, left_index=True)\n\nmean_real_FR_vs_topo = mean_estimated_ln_FR.to_frame()\nmean_real_FR_vs_topo = mean_real_FR_vs_topo.merge(topo, right_index=True, left_index=True)\n\nmean_real_FR_vs_gcc = mean_estimated_ln_FR.to_frame()\nmean_real_FR_vs_gcc = mean_real_FR_vs_gcc.merge(topo, right_index=True, left_index=True)\n#%%\n#3 estimated folding rate (median method)\nmedian_est_vs_obs_FR = median_estimated_ln_FR.to_frame()\nmedian_est_vs_obs_FR = median_est_vs_obs_FR.merge(observed_ln_freq.to_frame(), right_index=True, left_index=True)\n\nmedian_real_FR_vs_topo = median_estimated_ln_FR.to_frame()\nmedian_real_FR_vs_topo = median_real_FR_vs_topo.merge(topo, right_index=True, left_index=True)\n\nmedian_real_FR_vs_gcc = median_estimated_ln_FR.to_frame()\nmedian_real_FR_vs_gcc = median_real_FR_vs_gcc.merge(gcc, right_index=True, left_index=True)\n\n#%% gcc vs topo\ngc_v_topo = gcc.merge(topo, right_index=True, left_index=True)\n#%%\n### plots\n\nnp.random.seed(123456)\nrandom_colors = [(np.random.uniform(), np.random.uniform(), np.random.uniform()) for i in range(30)]\n\nmarkers = [(np.random.randint(3,7), np.random.randint(0,3), 0) for marker in range(30)]\n#%%\n#plt.style.use('_classic_test')\n#plt.rcParams te li mostra tti\nfor (dataset, x, y) in [(est_vs_obs_ln_freq , \"ln($F$)\", \"ln($F_{exp}$)\"), (est_freq_vs_topo, \"ln($F$)\", \"$|G'|_c$ (as in Baiesi et al., 2017)\"), (est_freq_vs_gcc, \"ln($F$)\", \"$<|G'|_c>$\"), (mean_est_vs_obs_FR, \"ln($\\\\bar{R}$)\", \"ln($F_{exp}$)\"), (mean_real_FR_vs_topo, \"ln($\\\\bar{R}$)\" , \"$|G'|_c$ (as in Baiesi et al., 2017)\"), (mean_real_FR_vs_gcc, \"ln($\\\\bar{R}$)\", \"$<|G'|_c>$\"), (median_est_vs_obs_FR, \"ln($\\\\widetilde{R}$)\", \"ln($F_{exp}$)\"), (median_real_FR_vs_topo,\"ln($\\\\widetilde{R}$)\", \"$|G'|_c$ (as in Baiesi et al., 2017)\"), (median_real_FR_vs_gcc, \"ln($\\\\widetilde{R}$)\", \"$<|G'|_c>$\"), (gc_v_topo,\"$<|G'|_c>$\",\"$|G'|_c$ (as in Baiesi et al., 2017)\")]:\n fig, ax = plt.subplots()\n\n #or:\n # color plot by length:\n \n # 1 order proteins from the shortest to the longest:\n #\n #length_of = {'1afi':72,'1aps':98, '1aye':80, '1bnz_a':64, '1bzp':153, '1csp':67,\n #'1div.n':56, '1fkb':107, '1hrc':104,'1hz6_a':62, '1imq':86, '1lmb3':80,'1pgb':56,'1poh':85,'1psf':69,'1shf_a':59,'1ten':89,'1tit':89,'1ubq':76,'1urn':96, '1wit':93,'256b':106,'2abd':86,'2ci2':64,'2pdd':41, '2vik':126}\n ## 2 create color mapping\n #\n #cmap= plt.get_cmap('Reds')\n #colors_of = { protein:cmap(np.e**(protein_length)) for protein,protein_length in length_of.items()} # crea dizionario che mappa nomi di proteine a un colore formato RGB nella cmap desiderata \n \n # create plot\n\n i=0\n for protein, row in dataset.iterrows(): #cambia qui, poi la riga sotto, e poi il nome del grafico\n ax.plot(row[0], row[1], linestyle='', marker= markers[i], ms=6, label=protein, color = random_colors[i]) # color = colors_of[protein], marker=\"o\"\n i+=1 # this index is used for the colors\n \n # add labels, legend, other stuff\n ax.set_position([0.1,0.2,0.4,0.7])\n plt.ylabel(y)\n plt.xlabel(x)\n ax.legend(ncol=2, bbox_to_anchor=(2.2, 1), shadow= True, numpoints = 1) # numpoints = 1 sono il numero di punti per ogni item della legenda. se no me ne metteva due pallini invece che uno. nosense, ma vbb\n ax.grid()\n \n # determine correlation:\n # this is somewhat ambiguous, becuase of the usual -inf datum. I choose to not take it into acocunt\n corcoeff=np.corrcoef(np.array(dataset['0_x']), np.array(dataset['0_y']))[1][0] \n line=\"Pearson's Correlation coefficient: \" + str(round(corcoeff, 3))\n print(line)\n fig.text(0.5,0.1, line)\n# \n name = x +\"vs\"+y+\".pdf\"\n plt.savefig(\"/home/lorenzo/tirocinio/tesi/analyses/collective_analyses/\"+name) #WARNING : CHANGE QUI IL NOME DEL FILE DI OUTPUT!! ATTENTO A NON SOVRASCRIVERE NULLA!\n plt.close()\n#%% e i topo che me li so scordati\n \nfig, ax = plt.subplots()\n\ni=0\nfor protein, row in gc_v_topo.iterrows(): #cambia qui, poi la riga sotto, e poi il nome del grafico\n ax.plot(row[0], row[1], linestyle='', marker= markers[i], ms=6, label=protein, color = random_colors[i]) # color = colors_of[protein], marker=\"o\"\n i+=1 # this index is used for the colors\nax.set_position([0.1,0.2,0.4,0.7])\nplt.ylabel(\"$|G'|_c$ (as in Baiesi et al., 2017)\")\nplt.xlabel(\"$<|G'|_c$>\")\nax.legend(ncol=2, bbox_to_anchor=(2.2, 1), shadow= True, numpoints = 1) # numpoints = 1 sono il numero di punti per ogni item della legenda. se no me ne metteva due pallini invece che uno. nosense, ma vbb\nax.grid()\nplt.xlim(0,1.8)\nplt.ylim(0,1.8)\n\n# determine correlation:\n# this is somewhat ambiguous, becuase of the usual -inf datum. I choose to not take it into acocunt\n\n#corcoeff=np.corrcoef(np.array(gc_v_topo['0_x'].drop(['1urn'])), np.array(gc_v_topo['0_y'].drop(['1urn'])))[1][0] # aggiungi .drop(['1urn']) a entrami , per droppare 1urn, SOLO nel caso tu stia calcolando le folding_frequencies (estimated_folding_rates vecchi, il primissimo coso)\n\ncorcoeff=np.corrcoef(np.array(gc_v_topo['0_x']), np.array(gc_v_topo['0_y']))[1][0] \nline=\"Pearson's Correlation coefficient: \" + str(round(corcoeff, 3))\nfig.text(0.5,0.1, line)\n\nname = \"temp.pdf\"\nplt.plot(np.linspace(-0.1,gc_v_topo.max()[1]+0.2,100),np.linspace(-0.1,gc_v_topo.max()[1]+0.2,100), color= \"0.5\", linewidth=0.8, linestyle='dashed')\n#plt.show()\nplt.savefig(\"/home/lorenzo/tirocinio/tesi/analyses/collective_analyses/\"+name) #WARNING : CHANGE QUI IL NOME DEL FILE DI OUTPUT!! ATTENTO A NON SOVRASCRIVERE NULLA!\nplt.close()\n","sub_path":"scatterplot_foldingrates.py","file_name":"scatterplot_foldingrates.py","file_ext":"py","file_size_in_byte":10070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"346132151","text":"#coding: utf-8\nfrom __future__ import unicode_literals\nimport json\nimport sys\nn =0\ni =0\nbase = []\nflag = 0\nccount = 0\nf = open('jawiki-country.json', 'r', encoding = 'utf-8')\nword = 'イギリス'\nword2 = 'Category:'\nccount = 0\ncheck_c = 0\ne_word2 = word2.encode('utf-8')\nfor line in f:\n temp = json.loads(line) #206記事ある。\n if '{}'.format(temp['title']) == word: #lineはイギリスに関して\n for line2 in ('{}'.format(temp['text'])): #line2は一文字 イギリスの本文記事数が37013\n if line2 == '\\n':\n ccount = ccount + 1\n if (word2[i]) == line2:\n if i < len(word2)-1:\n i = i + 1\n else:\n i = 0\n check_c = ccount\n break\n else:\n i = 0\n ccount = 0\n for line2 in ('{}'.format(temp['text'])): #line2は一文字 イギリスの本文記事数が37013\n if line2 == '\\n':\n ccount = ccount + 1\n flag = 0\n if ccount >= check_c:\n if line2 == '\\n':\n sys.stdout.write(line2)\n if flag == 1 and line2 != ']':\n sys.stdout.write(line2)\n if line2 == ':':\n flag = 1\n\n\nprint ('')\n","sub_path":"chap3/022.py","file_name":"022.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"47889309","text":"import pygame\n\nclass Animation:\n # fileLocation e.g. assets/explosion.png\n # rc: rows columns tuple\n def __init__(self, frames, loop):\n self.frames = frames\n self.loop = loop\n self.currentFrame = 0\n self.h = self.frames.frames[0].get_height()\n self.w = self.frames.frames[0].get_width()\n self.block = False\n self.dir = 1\n\n def blockNextFrame(self):\n self.block = True\n\n def getFrame(self):\n frame = self.frames.frames[self.currentFrame]\n if int(self.dir) == 2:\n frame = pygame.transform.flip(frame, True, False)\n return frame\n\n def nextFrame(self):\n if self.block:\n self.block = False\n else:\n self.currentFrame += 1\n self.currentFrame %= len(self.frames.frames)\n\nclass Frames:\n def __init__(self, fileLocation, rc, colorKey):\n asset = pygame.image.load(\"assets/{}.png\".format(fileLocation))\n self.frames = self.splitIntoFrames(asset, rc, colorKey)\n\n def splitIntoFrames(self, sheet, rc, colorKey):\n rows, cols = rc\n width, height = sheet.get_rect().size\n self.w = width = int(width/cols)\n self.h = height = int(height/rows)\n frames = []\n for y in range(0,rows):\n for x in range(0,cols):\n rect = pygame.Rect(x*width,y*height, width, height)\n frame = pygame.Surface(rect.size).convert()\n frame.blit(sheet, (0,0), rect)\n frame.set_colorkey(colorKey, pygame.RLEACCEL)\n frames.append(frame)\n return frames\n","sub_path":"animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"491315325","text":"import requests\r\n\r\n\r\nhitbtc_base_url = 'https://api.hitbtc.com/api/2'\r\napi_key = ''\r\nsecret = ''\r\n\r\n\r\n# PUBLIC ENDPOINTS\r\n\r\n\r\ndef hitbtc_all_symbols():\r\n hitbtc_base_url = 'https://api.hitbtc.com/api/2'\r\n endpoint = '/public/ticker'\r\n symbol = requests.get(hitbtc_base_url+endpoint)\r\n symbol = symbol.json()\r\n return symbol\r\n\r\ndef hitbtc_pair_data(pair):\r\n hitbtc_base_url = 'https://api.hitbtc.com/api/2'\r\n endpoint = '/public/ticker/'\r\n symbol = requests.get(hitbtc_base_url + endpoint + pair)\r\n symbol = symbol.json()\r\n return symbol\r\n\r\n\r\n# PRIVATE ENDPOINTS\r\n# authentication\r\ndef balance(publickey, secretkey):\r\n url = 'https://api.hitbtc.com/api/2/trading/balance'\r\n session = requests.Session()\r\n session.auth = (publickey, secretkey)\r\n result = session.get(url).json()\r\n\r\n return result\r\n\r\n\r\ndef order(publickey, secretkey, symbol, side, quantity, clientoid=None, type='market'):\r\n symbol = str(symbol)\r\n symbol = symbol.lower()\r\n if clientoid is None:\r\n orderData = {'symbol': symbol, 'side': side, quantity: str(quantity)}\r\n else:\r\n orderData = {'symbol': symbol, 'side': side, quantity: str(quantity), 'clientOrderId': clientoid}\r\n session = requests.session()\r\n session.auth = (publickey, secretkey)\r\n r = session.post('https://api.hitbtc.com/api/2/order', data=orderData).json()\r\n return r\r\n\r\n\r\n\r\ndef tradingfees(publickey, secretkey, symbol):\r\n url = 'https://api.hitbtc.com/api/2/trading/fee/'+symbol\r\n session = requests.session()\r\n session.auth = (publickey, secretkey)\r\n r = session.get(url).json()\r\n return r['takeLiquidityRate']\r\n\r\n\r\n","sub_path":"lef/hitbtc.py","file_name":"hitbtc.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"54246369","text":"# pip install signalr-client\n\nfrom requests import Session\nfrom signalr import Connection\ntry:\n from urllib.request import urlopen\nexcept:\n from urllib2 import urlopen\nfrom xml.etree.ElementTree import fromstring\n\nrates = {}\n\nhttp = urlopen('https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml')\nxml = http.read()\nroot = fromstring(xml)\nns = {'gesmes': 'http://www.gesmes.org/xml/2002-08-01', 'cube': 'http://www.ecb.int/vocabulary/2002-08-01/eurofxref'}\nfor cube in root.findall('cube:Cube/cube:Cube/cube:Cube', ns):\n rates[cube.get('currency')] = float(cube.get('rate'))\n\ndef tick(pair, rate):\n if 'EUR' in pair:\n print (pair + \" \" + format(rate, '.2f'))\n elif 'KRW' in pair or 'JPY' in pair:\n print (pair + \" \" + format(rate/float(rates[pair[3:6]]), '.2f')+ \" (\" + str(int(rate)) + \")\")\n else:\n print (pair + \" \" + format(rate/float(rates[pair[3:6]]), '.2f')+ \" (\" + format(rate, '.2f') + \")\")\n\ndef data(**kwargs):\n if 'M' not in kwargs:\n return\n kwargs = kwargs['M']\n if len(kwargs) != 1:\n return\n kwargs = kwargs[0]\n pair = kwargs['M']\n rate = float(kwargs['A'][0])/100\n tick(pair, rate)\n\nsession = Session()\nconnection = Connection(\"https://www.klatt.ie/signalr\", session)\nconnection.received += data\nconnection.register_hub('bitTicker')\nconnection.start()\n\nrunning = True\nwhile(running):\n connection.wait(1)\n","sub_path":"ticker.py","file_name":"ticker.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"172258009","text":"import ConfigParser\n\nimport os\n\n# Read the configuration in module variables,\n# so the module will act like a singleton and\n# the configuration will be read only one time\n# per session\n\nconfiguration = ConfigParser.SafeConfigParser()\n\n# Get path of the configuration file\nassert os.environ.get(\"LTF_CONFIG_FILE\") is not None, \"You have to set up the LTF_CONFIG_FILE env. variable\"\n\nconfPath = os.path.abspath(os.path.expandvars(os.path.expanduser(os.environ.get(\"LTF_CONFIG_FILE\"))))\n\nassert os.path.exists(confPath), \"Configuration path does not exist!\"\n\nconfiguration.read([confPath])\n\n# Monkey patch adding the filename\nconfiguration.config_file = confPath","sub_path":"fermi_blind_search/Configuration.py","file_name":"Configuration.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"602062102","text":"import sys\nimport os\nimport time\nfrom datetime import datetime\n\ndatasetPath = sys.argv[1]\noutputDirectory = sys.argv[2]\nnumberOfLine = int(sys.argv[3])\n\nif not os.path.exists(outputDirectory):\n\tos.makedirs(outputDirectory)\n\nstartTimer = time.time()\nwith open(datasetPath) as f:\n\tnext(f)\n\ti = 1\n\tnew_id_user = 1\n\tcurFile = open(outputDirectory+\"/\"+str(new_id_user) + \".csv\", \"a\")\n\ttmp_line = next(f)\n\tdata = tmp_line.split(\",\")\n\ttimeStamp = data[1]\n\tcoordonates = data[2]\n\tvalues = coordonates.split(\"|\")\n\tlongitude = values[0]\n\tlatitude = values[1].rstrip(\"\\n\")\n\tdt = datetime.strptime(timeStamp,'%Y-%m-%d %H:%M:%S')\n\ttimestamp_ms = int(dt.timestamp() * 1000)\n\ttimestamp_ms_str = str(timestamp_ms)\n\tcurFile.write(str(new_id_user)+\",\"+latitude+\",\"+longitude+\",\"+timestamp_ms_str+\"\\n\")\n\tcurrentUser = data[0]\n\t\n\tfor line in f :\n\t\tdata = line.split(\",\")\n\t\tnewUser = data[0]\n\t\tif currentUser != newUser :\n\t\t\tcurFile.close()\n\t\t\tnew_id_user = new_id_user + 1\n\t\t\tcurrentUser = newUser\n\t\t\tcurFile = open(outputDirectory+\"/\"+str(new_id_user) + \".csv\", \"a\")\n\n\t\ttimeStamp = data[1]\n\t\tcoordonates = data[2]\n\t\tvalues = coordonates.split(\"|\")\n\t\tlongitude = values[0]\n\t\tlatitude = values[1].rstrip(\"\\n\")\n\t\tdt = datetime.strptime(timeStamp,'%Y-%m-%d %H:%M:%S')\n\t\ttimestamp_ms = int(dt.timestamp() * 1000)\n\t\ttimestamp_ms_str = str(timestamp_ms)\n\t\tcurFile.write(str(new_id_user)+\",\"+latitude+\",\"+longitude+\",\"+timestamp_ms_str+\"\\n\")\t\t\t\n\t\ti=i+1\n\t\tif i>=numberOfLine :\n\t\t\tbreak\n\nendTimer = time.time()\ntotalTime = endTimer - startTimer\nprint(\"Execution time splitting the dataset by user : \",totalTime,\"sec\")\n\n","sub_path":"lib_erwan/split_dataset/divideDatasetByUser.py","file_name":"divideDatasetByUser.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"490622337","text":"import time\nimport picamera\nimport numpy as np\nimport skimage.draw as skd\n\n# Create an array representing a 1280x720 image of\n# a cross through the center of the display. The shape of\n# the array must be of the form (height, width, color)\nheight = 720\nwidth = 1280\na = np.zeros((height, width, 3), dtype=np.uint8)\ny = 357\nrr, cc = skd.line(y,0, y, width-1)\na[rr, cc, :] = 0xff\n\ndy = 1\n\nwith picamera.PiCamera() as camera:\n camera.hflip = True\n camera.vflip = True\n camera.resolution = (width, height)\n camera.framerate = 24\n minPeriod = 1.0 / camera.framerate\n \n camera.start_preview()\n \n # Add the overlay directly into layer 3 with transparency;\n # we can omit the size parameter of add_overlay as the\n # size is the same as the camera's resolution\n la = camera.add_overlay(a.data, layer=3, alpha=64)\n lastUpdateTime = time.time() \n try:\n # Wait indefinitely until the user terminates the script\n while True:\n a[rr, cc, :] = 0x00\n if (y >= 700) or (y <= 20):\n dy = -dy\n y = y + dy\n rr, cc = skd.line(y,0, y, width-1)\n a[rr, cc, :] = 0xff\n if ((time.time() - lastUpdateTime) > minPeriod):\n la.update(a.data)\n lastUpdateTime = time.time()\n \n finally:\n camera.remove_overlay(la)\n","sub_path":"Python/picamOverlayHorizon4.py","file_name":"picamOverlayHorizon4.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"366025894","text":"# Extra utility functions\n\nfrom datetime import date, datetime\nfrom dateutil.relativedelta import relativedelta\nfrom django.conf import settings\nfrom django.db.models import DateField, DateTimeField, DecimalField, BigIntegerField, IntegerField, ForeignKey\nfrom urlparse import urljoin\nfrom decimal import Decimal\n\nfrom .models import AwardManager, Proposal, KeyPersonnel, PerformanceSite, EASMapping, EASMappingException, AwardAcceptance,\\\n AwardOrganization, PrimeSponsor, FundingSource\n\nimport csv\nimport requests\nimport StringIO\n\ndef _make_cayuse_request(endpoint, payload={}):\n \"\"\"Makes an HTTP request to the given Cayuse endpoint, sending it the data in payload\"\"\"\n\n s = requests.Session()\n s.auth = (settings.CAYUSE_USERNAME, settings.CAYUSE_PASSWORD)\n\n if settings.DEBUG:\n # Disable SSL verification if we're using SSH tunneling to work locally\n response = s.get(\n urljoin(\n settings.CAYUSE_ENDPOINT,\n endpoint),\n params=payload,\n verify=False)\n else:\n response = s.get(\n urljoin(\n settings.CAYUSE_ENDPOINT,\n endpoint),\n params=payload)\n\n return response\n\ndef get_cayuse_submissions_from_proposals_table(get_all_submissions=False):\n \"\"\"Used to populate the pick_proposal view\n These proposals retrieved from the local database. as the local database filled with a automatic job\n Defaults to the most recent six months of proposals, can be overriden to show all.\n \"\"\"\n proposals = Proposal.objects.filter(award_id__isnull=True).order_by('-submission_date')[:20]\n if get_all_submissions:\n proposals = Proposal.objects.filter(award_id__isnull=True).order_by('-submission_date')\n return proposals\n\ndef get_cayuse_submissions(get_all_submissions=False):\n \"\"\"Used to populate the pick_proposal view\n\n Defaults to the most recent six months of proposals, can be overriden to show all.\n \"\"\"\n\n options = {}\n if not get_all_submissions:\n six_months_ago = date.today() - relativedelta(months=2)\n options['since'] = six_months_ago\n\n response = _make_cayuse_request(\n 'view/submissions', options)\n\n f = StringIO.StringIO(response.content)\n reader = csv.reader(f, delimiter=',')\n\n header = reader.next()\n\n proposals = []\n missed_mappings = []\n missed_pi = []\n missed_whois = []\n missed_dprt = []\n missed_agency = []\n entries = ['first_name', 'last_name', 'middle_name', 'submit_title', 'submit_date',\n 'division_code', 'submitterusername', 'department_code', 'result_code', 'duns_id']\n\n for row in reader:\n proposal = dict(zip(header, row))\n try:\n prop = Proposal.objects.get(proposal_id=proposal['proposal_id'])\n except:\n prop = None\n if not prop:\n try:\n cayuse_data = get_cayuse_summary(proposal['proposal_id'])\n pi = get_cayuse_pi(\n cayuse_data['principal_investigator'],\n cayuse_data['proposal']['employee_id'])\n proposal['principal_investigator_id'] = pi.id if pi.id else None\n except:\n missed = {}\n missed['proposal_id'] = proposal['proposal_id']\n missed['first_name'] = proposal['first_name']\n missed['last_name'] = proposal['last_name']\n missed_pi.append(missed)\n missed_mappings.append(proposal['proposal_id'])\n else:\n proposal_dict = cayuse_data.get('proposal')\n who_is_prime = proposal_dict['who_is_prime']\n department = proposal_dict['department_name']\n agency = proposal_dict['agency_name']\n try:\n whois = PrimeSponsor.objects.get(name=who_is_prime.name)\n proposal['who_is_prime'] = whois\n except:\n missed = {}\n missed['proposal_id'] = proposal['proposal_id']\n if who_is_prime:\n missed['who_is_prime'] = who_is_prime.name\n missed_whois.append(missed)\n\n missed_mappings.append(proposal['proposal_id'])\n try:\n department = AwardOrganization.objects.get(name=department.name)\n proposal['department_name'] = department\n except:\n missed = {}\n missed['proposal_id'] = proposal['proposal_id']\n if department:\n missed['department_name'] = department.name\n missed_dprt.append(missed)\n\n missed_mappings.append(proposal['proposal_id'])\n try:\n agency = FundingSource.objects.get(name=agency.name)\n proposal['agency_name'] = agency\n except:\n missed = {}\n missed['proposal_id'] = proposal['proposal_id']\n if agency:\n missed['agency_name'] = agency.name\n missed_agency.append(missed)\n\n missed_mappings.append(proposal['proposal_id'])\n\n if not proposal['total_indirect_costs']:\n del proposal['total_indirect_costs']\n else:\n proposal['total_indirect_costs'] = Decimal(proposal['total_indirect_costs'])\n if not proposal['total_direct_costs']:\n del proposal['total_direct_costs']\n else:\n proposal['total_direct_costs'] = Decimal(proposal['total_direct_costs'])\n proposal['proposal_number'] = '{0}-{1}'.format(proposal[\"submit_date\"][2:4], proposal['proposal_id'])\n if proposal['submit_date'][0:10]:\n proposal['submission_date'] = datetime.strptime(proposal['submit_date'][0:10], '%Y-%m-%d')\n try:\n proposal['project_title'] = proposal['project_title'][:255]\n except:\n pass\n\n for key in entries:\n if key in proposal:\n del proposal[key]\n\n if proposal.get(\"submission_date\"):\n proposals.append(proposal)\n\n return proposals, missed_mappings, missed_pi, missed_whois, missed_dprt, missed_agency\n\n\ndef cast_field_value(field, value):\n \"\"\"Parses Cayuse data into Python values.\n If the data doesn't exist in the ATP database, raises an EASMappingException to force\n the user to create a new mapping with that data.\n \"\"\"\n\n if type(field) in [DecimalField, IntegerField, BigIntegerField,\n DateField, DateTimeField, ForeignKey] and value == '':\n return None\n elif isinstance(field, DateTimeField):\n return datetime.strptime(value, \"%Y-%m-%d %H:%M:%S.%f\")\n elif isinstance(field, DateField):\n try:\n return datetime.strptime(value, \"%Y-%m-%d\")\n except:\n value = datetime.strptime(value, \"%Y-%m-%d %H:%M:%S.%f\")\n return value.date()\n elif isinstance(field, ForeignKey):\n fk_model = field.related_field.model\n\n # Try to associate the Cayuse value for the ForeignKey field with the\n # appropriate EAS value\n try:\n mapping = EASMapping.objects.get(\n interface='C',\n field=field.name,\n incoming_value=value,\n atp_model=fk_model.__name__)\n except EASMapping.DoesNotExist:\n raise EASMappingException(\n message='Mapping not available',\n interface='C',\n field=field.name,\n incoming_value=value,\n atp_model=fk_model)\n\n return fk_model.objects.get(pk=mapping.atp_pk)\n\n else:\n return value\n\n\ndef cast_lotus_value(field, value):\n \"\"\"Tries to get the local AwardManager from the info that came from Lotus.\n If it doesn't exist in the database, raises an EASMappingException to force\n the user to create a new mapping with that data.\n \"\"\"\n\n fk_model = field.related_field.model\n\n # We may get lucky and the Lotus GWID matches a valid EAS employee\n if field.name == 'principal_investigator':\n try:\n award_manager = AwardManager.objects.get(gwid=value)\n return award_manager\n except AwardManager.DoesNotExist:\n pass\n\n try:\n mapping = EASMapping.objects.get(\n interface='L',\n field=field.name,\n incoming_value=value,\n atp_model=fk_model.__name__)\n except EASMapping.DoesNotExist:\n raise EASMappingException(\n message='Mapping not available',\n interface='L',\n field=field.name,\n incoming_value=value,\n atp_model=fk_model)\n\n return fk_model.objects.get(pk=mapping.atp_pk)\n\n\ndef get_cayuse_summary(proposal_id):\n \"\"\"Get all the data about a proposal from Cayuse\"\"\"\n\n response = _make_cayuse_request('custom/summary?id=%s' % proposal_id)\n\n f = StringIO.StringIO(response.content)\n reader = csv.reader(f, delimiter=',')\n\n header = reader.next()\n proposal = reader.next()\n f.close()\n\n summary = dict(zip(header, proposal))\n\n pi_fields = AwardManager.CAYUSE_FIELDS\n proposal_fields = Proposal._meta.get_all_field_names()\n\n pi_info = {}\n\n for key in summary.keys():\n if key in pi_fields:\n pi_info[key] = cast_field_value(\n AwardManager._meta.get_field(key),\n summary.pop(key))\n elif key not in proposal_fields:\n del summary[key]\n else:\n summary[key] = cast_field_value(\n Proposal._meta.get_field(key),\n summary[key])\n\n return {'principal_investigator': pi_info, 'proposal': summary}\n\n\ndef get_cayuse_pi(pi_info, employee_id):\n \"\"\"Tries to get the local AwardManager from the info that came from Cayuse.\n If it doesn't exist in the database, raises an EASMappingException to force\n the user to create a new mapping with that data.\n \"\"\"\n try:\n award_manager = AwardManager.objects.get(gwid=employee_id)\n except AwardManager.DoesNotExist:\n try:\n full_name = '%s, %s %s' % (\n pi_info['last_name'], pi_info['first_name'], pi_info['middle_name'])\n mapping = EASMapping.objects.get(\n interface='C',\n field='principal_investigator',\n incoming_value=full_name,\n atp_model=AwardManager.__name__)\n award_manager = AwardManager.objects.get(pk=mapping.atp_pk)\n except EASMapping.DoesNotExist:\n raise EASMappingException(\n message='Mapping not available',\n interface='C',\n field='principal_investigator',\n incoming_value=full_name,\n atp_model=AwardManager)\n\n return award_manager\n\n\ndef get_key_personnel(proposal_id):\n \"\"\"Gets the KeyPersonnel from Cayuse\"\"\"\n\n response = _make_cayuse_request('view/keypersons?id=%s' % proposal_id)\n\n f = StringIO.StringIO(response.content)\n reader = csv.reader(f, delimiter=',')\n\n header = reader.next()\n\n key_personnel = []\n\n for row in reader:\n key_personnel.append(dict(zip(header, row)))\n\n f.close()\n\n key_personnel_fields = KeyPersonnel._meta.get_all_field_names()\n\n for person in key_personnel:\n for key in person.keys():\n if key == 'proposal_id':\n del person[key]\n elif key in key_personnel_fields:\n person[key] = cast_field_value(\n KeyPersonnel._meta.get_field(key),\n person[key])\n else:\n del person[key]\n\n return key_personnel\n\n\ndef get_performance_sites(proposal_id):\n \"\"\"Gets the PerformanceSites from Cayuse\"\"\"\n\n response = _make_cayuse_request('custom/PerformanceSites')\n\n f = StringIO.StringIO(response.content)\n reader = csv.reader(f, delimiter=',')\n\n header = reader.next()\n\n performance_sites = []\n\n for row in reader:\n site = dict(zip(header, row))\n # Unfortunately, the performance site endpoint doesn't let us filter on proposal_id\n # so we have to filter manually\n if site['Proposal_id'] == str(proposal_id):\n performance_sites.append(site)\n\n f.close()\n\n performance_site_fields = PerformanceSite._meta.get_all_field_names()\n\n for site in performance_sites:\n for key in site.keys():\n if key in performance_site_fields:\n site[key] = cast_field_value(\n PerformanceSite._meta.get_field(key),\n site[key])\n else:\n del site[key]\n\n return performance_sites\n\n\ndef get_proposal_statistics_report(from_date, to_date, all_fields=False):\n \"\"\"Gets the proposal statistics report from Cayuse\"\"\"\n\n # List of fields we want to retrieve from Cayuse and include in the CSV\n REPORT_FIELDS = (\n 'application_type_code',\n 'proposal_id',\n 'employee_id',\n 'first_name',\n 'last_name',\n 'division_name',\n 'department_name',\n 'agency_name',\n 'project_title',\n 'project_start_date',\n 'project_end_date',\n 'submission_date',\n 'department_code',\n 'total_costs',\n 'total_direct_costs',\n 'total_indirect_costs',\n 'total_direct_costs_y1',\n 'total_indirect_costs_y1',\n 'budget_first_per_start_date', \n 'budget_first_per_end_date', \n )\n\n response = _make_cayuse_request('custom/summary')\n\n f = StringIO.StringIO(response.content)\n reader = csv.reader(f, delimiter=',')\n\n header = reader.next()\n\n if all_fields:\n header_fields = header\n else:\n header_fields = REPORT_FIELDS\n\n proposals = []\n\n for row in reader:\n proposal = dict(zip(header, row))\n\n status = proposal['award_proposal_status']\n\n if status == 'SUBMITTED' and proposal['submission_date']:\n submission_date = datetime.strptime(\n proposal['submission_date'],\n \"%Y-%m-%d %H:%M:%S.%f\").date()\n\n if submission_date >= from_date and submission_date <= to_date:\n entry = [proposal[field] for field in header_fields]\n proposals.append(entry)\n\n return header_fields, proposals","sub_path":"ovpr_atp/awards/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":14601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"111713962","text":"from GridWorld import GridWorld\n\ngrid_world = GridWorld()\n\ndef init_gridworld(random_player=False, random_mines=False, maze=False):\n global grid_world, zeigen\n grid_world = GridWorld(random_player, random_mines, maze)\n\ndef zeigen():\n grid_world.zeigen()\n\ndef bewege_oben():\n grid_world.states.append(grid_world.make_move(grid_world.states[len(grid_world.states)-1], 0))\n\ndef bewege_unten():\n grid_world.states.append(grid_world.make_move(grid_world.states[len(grid_world.states)-1], 1))\n\ndef bewege_links():\n grid_world.states.append(grid_world.make_move(grid_world.states[len(grid_world.states)-1], 2))\n\ndef bewege_rechts():\n grid_world.states.append(grid_world.make_move(grid_world.states[len(grid_world.states)-1], 3))\n\ndef inhalt(x, y):\n last_state = grid_world.states[len(grid_world.states)-1]\n type = last_state[y, x]\n\n if type == 'P' or (type == [0, 0, 0, 1]).all():\n return 'Spieler'\n elif type == 'X' or (type == [0, 1, 0, 0]).all():\n return 'Mine'\n elif type == 'W' or (type == [0, 0, 1, 0]).all():\n return 'Wand'\n elif type == 'G' or (type == [1, 0, 0, 0]).all() or (type == [1, 0, 0, 1]).all():\n return 'Ziel'\n elif type == 'D' or (type == [0, 1, 0, 1]).all():\n return 'Tot'\n else:\n return 'Frei'\n\ndef spieler_position():\n last_state = grid_world.states[len(grid_world.states) - 1]\n loc = grid_world.getLoc(last_state, 3)\n return loc[1] , loc[0]\n\ndef inhalt_oben(position = None):\n if position == None:\n position = spieler_position()\n x = position[0]\n y = position[1] - 1\n\n if x>=0 and y>=0 and x<=grid_world.grid_x-1 and y<=grid_world.grid_y-1:\n inh = inhalt(x, y)\n return inh\n else:\n return 'A'\n\ndef inhalt_unten(position = None):\n if position == None:\n position = spieler_position()\n x = position[0]\n y = position[1] + 1\n\n if x >= 0 and y >= 0 and x <= grid_world.grid_x-1 and y <= grid_world.grid_y-1:\n inh = inhalt(x, y)\n return inh\n else:\n return 'A'\n\ndef inhalt_links(position = None):\n if position == None:\n position = spieler_position()\n x = position[0] - 1\n y = position[1]\n\n if x >= 0 and y >= 0 and x <= grid_world.grid_x-1 and y <= grid_world.grid_y-1:\n inh = inhalt(x, y)\n return inh\n else:\n return 'A'\n\ndef inhalt_rechts(position = None):\n if position == None:\n position = spieler_position()\n x = position[0] + 1\n y = position[1]\n\n if x >= 0 and y >= 0 and x <= grid_world.grid_x-1 and y <= grid_world.grid_y-1:\n inh = inhalt(x, y)\n return inh\n else:\n return 'A'\n\ndef ist_oben_frei():\n inh = inhalt_oben()\n if inh == 'Frei':\n return True\n else:\n return False\n\ndef ist_unten_frei():\n inh = inhalt_unten()\n if inh == 'Frei':\n return True\n else:\n return False\n\ndef ist_links_frei():\n inh = inhalt_links()\n if inh == 'Frei':\n return True\n else:\n return False\n\ndef ist_rechts_frei():\n inh = inhalt_rechts()\n if inh == 'Frei':\n return True\n else:\n return False\n\ndef wenn_dann(bedingung, action):\n if bedingung():\n action()\n return True\n else:\n return False","sub_path":"RL_Agent_DQN_6x5/Regler.py","file_name":"Regler.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"118553306","text":"# -*- coding: utf-8 -*-\n\n# FOGLAMP_BEGIN\n# See: http://foglamp.readthedocs.io/\n# FOGLAMP_END\n\n\"\"\"Service Registry Rest API support\"\"\"\n\nimport time\nfrom aiohttp import web\nfrom foglamp.services.common.microservice_management.service_registry.instance import Service\n\n__author__ = \"Amarendra Kumar Sinha, Praveen Garg\"\n__copyright__ = \"Copyright (c) 2017 OSIsoft, LLC\"\n__license__ = \"Apache 2.0\"\n__version__ = \"${VERSION}\"\n\n__start_time = time.time()\n\n_help = \"\"\"\n -----------------------------------------------------------------------------------\n | GET | /foglamp/service/ping |\n | GET | /foglamp/service?name=&type= (name | type optional query param)|\n | GET, POST | /foglamp/service |\n | DELETE | /foglamp/service/{service_id} |\n -----------------------------------------------------------------------------------\n\"\"\"\n\n\nasync def ping(request):\n \"\"\" health check\n\n \"\"\"\n since_started = time.time() - __start_time\n return web.json_response({'uptime': since_started})\n\n\nasync def register(request):\n \"\"\" Register a service\n\n :Example: curl -d '{\"type\": \"Storage\", \"name\": \"Storage Services\", \"address\": \"127.0.0.1\", \"service_port\": 8090,\n \"management_port\": 1090, \"protocol\": \"https\"}' -X POST http://localhost:8082/foglamp/service\n service_port is optional\n \"\"\"\n\n try:\n data = await request.json()\n\n service_name = data.get('name', None)\n service_type = data.get('type', None)\n service_address = data.get('address', None)\n service_port = data.get('service_port', None)\n service_management_port = data.get('management_port', None)\n service_protocol = data.get('protocol', 'http')\n\n if not (service_name.strip() or service_type.strip() or service_address.strip()\n or service_management_port.strip() or not service_management_port.isdigit()):\n raise web.HTTPBadRequest(reason='One or more values for type/name/address/management port missing')\n\n if service_port != None:\n if not (isinstance(service_port, int)):\n raise web.HTTPBadRequest(reason=\"Service's service port can be a positive integer only\")\n\n if not isinstance(service_management_port, int):\n raise web.HTTPBadRequest(reason='Service management port can be a positive integer only')\n\n try:\n registered_service_id = Service.Instances.register(service_name, service_type, service_address,\n service_port, service_management_port, service_protocol)\n except Service.AlreadyExistsWithTheSameName:\n raise web.HTTPBadRequest(reason='A Service with the same name already exists')\n except Service.AlreadyExistsWithTheSameAddressAndPort:\n raise web.HTTPBadRequest(reason='A Service is already registered on the same address: {} and '\n 'service port: {}'.format(service_address, service_port))\n except Service.AlreadyExistsWithTheSameAddressAndManagementPort:\n raise web.HTTPBadRequest(reason='A Service is already registered on the same address: {} and '\n 'management port: {}'.format(service_address, service_management_port))\n\n if not registered_service_id:\n raise web.HTTPBadRequest(reason='Service {} could not be registered'.format(service_name))\n\n _response = {\n 'id': registered_service_id,\n 'message': \"Service registered successfully\"\n }\n\n return web.json_response(_response)\n\n except ValueError as ex:\n raise web.HTTPNotFound(reason=str(ex))\n\n\nasync def unregister(request):\n \"\"\" Deregister a service\n\n :Example: curl -X DELETE http://localhost:8082/foglamp/service/dc9bfc01-066a-4cc0-b068-9c35486db87f\n \"\"\"\n\n try:\n service_id = request.match_info.get('service_id', None)\n\n if not service_id:\n raise web.HTTPBadRequest(reason='Service id is required')\n\n try:\n Service.Instances.get(idx=service_id)\n except Service.DoesNotExist:\n raise web.HTTPBadRequest(reason='Service with {} does not exist'.format(service_id))\n\n Service.Instances.unregister(service_id)\n\n _resp = {'id': str(service_id), 'message': 'Service unregistered'}\n\n return web.json_response(_resp)\n except ValueError as ex:\n raise web.HTTPNotFound(reason=str(ex))\n\n\nasync def get_service(request):\n \"\"\" Returns a list of all services or of the selected service\n\n :Example: curl -X GET http://localhost:8082/foglamp/service\n :Example: curl -X GET http://localhost:8082/foglamp/service?name=X&type=Storage\n \"\"\"\n service_name = request.query['name'] if 'name' in request.query else None\n service_type = request.query['type'] if 'type' in request.query else None\n\n try:\n if not service_name and not service_type:\n services_list = Service.Instances.all()\n elif service_name and not service_type:\n services_list = Service.Instances.get(name=service_name)\n elif not service_name and service_type:\n services_list = Service.Instances.get(s_type=service_type)\n else:\n services_list = Service.Instances.filter_by_name_and_type(\n name=service_name, s_type=service_type\n )\n except Service.DoesNotExist as ex:\n raise web.HTTPBadRequest(reason=\"Invalid service name and/or type provided\" + str(ex))\n\n services = []\n for service in services_list:\n svc = dict()\n svc[\"id\"] = service._id\n svc[\"name\"] = service._name\n svc[\"type\"] = service._type\n svc[\"address\"] = service._address\n svc[\"management_port\"] = service._management_port\n svc[\"protocol\"] = service._protocol\n svc[\"status\"] = service._status\n if service._port:\n svc[\"service_port\"] = service._port\n services.append(svc)\n\n return web.json_response({\"services\": services})\n\n\nasync def shutdown(request):\n pass\n\n\nasync def register_interest(request):\n pass\n\n\nasync def unregister_interest(request):\n pass\n\n\nasync def notify_change(request):\n pass\n","sub_path":"python/foglamp/services/common/microservice_management/service_registry/service_registry.py","file_name":"service_registry.py","file_ext":"py","file_size_in_byte":6393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"578538603","text":"# Run the script to start using it \n\nmy_list = []\n\ndef help_message():\n print(\"Type \\\"DONE\\\" to quit and show the full list, type \\\"SHOW\\\" to show the full list and type \\\"HELP\\\" to show this help message\")\n\ndef show_items(my_list):\n print(\"\\nHere's your list: \")\n for item in my_list:\n print(\"-{}\".format(item))\n print(\"List has {} items\".format(len(my_list))) \n\ndef add_items(new_item, my_list): \n my_list.append(new_item)\n print(\"Added {}. List now has {} items.\".format(new_item, len(my_list)))\n\nhelp_message()\n\nwhile True: \n new_item = input(\"> \")\n if new_item == \"DONE\": \n break\n elif new_item == \"SHOW\":\n show_items(my_list) \n continue\n elif new_item == \"HELP\":\n help_message()\n continue\n elif new_item != \"\": \n add_items(new_item, my_list)\n continue\n\nshow_items(my_list)\n\n\n\n\n","sub_path":"todo-list.py","file_name":"todo-list.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"351168279","text":"import pytest\n\nfrom rest_framework import status\nfrom freezegun import freeze_time\nfrom model_mommy import mommy\n\n\n@pytest.mark.django_db()\ndef test_post_historical_view(client):\n with freeze_time(\"1990-01-01T00:00:00Z\") as frozen_time:\n tod = mommy.make('organization.TourOfDuty', long_description=\"2YR\", months=24)\n post = mommy.make('organization.Post', danger_pay=10, differential_rate=10, tour_of_duty=tod)\n\n frozen_time.move_to(\"1995-01-01T00:00:00Z\")\n post.danger_pay = 0\n post.differential_rate = 0\n post.save()\n\n tod.months = 12\n tod.long_description = \"1YR\"\n tod.save()\n\n response = client.get(f'/api/v1/orgpost/{post.id}/history/')\n\n assert len(response.data[\"results\"]) == 2\n\n response = client.get(f'/api/v1/orgpost/{post.id}/history/?history_date__lte=1993-01-01T00:00:00Z')\n\n assert len(response.data[\"results\"]) == 1\n","sub_path":"talentmap_api/common/tests/test_historical_views.py","file_name":"test_historical_views.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"43582276","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom users.models import User\nfrom books.models import BookKind,BookDetail\nfrom .models import Basket\nfrom datetime import date\nfrom time import ctime\n\n# Create your views here.\n\ndef profile(request):\n \n users = request.user\n bookkind = BookKind.objects.all()\n return render(request,'profile.html',{'users':users,'bookkind':bookkind,})\n\ndef addtobasket(request,bookid):\n \n book = BookDetail.objects.get(id = bookid)\n users = request.user\n bookkind= BookKind.objects.all()\n if not users.is_authenticated():\n return HttpResponseRedirect(request,'accounts/login')\n basket = Basket(\n orderCount = 1 ,\n salePrice = book.bookPrice ,\n userChecked = 1 ,\n postTime = str(date.today()),\n orderNum = str(abs(hash(ctime()))),\n )\n basket.save()\n basket.bookID.add(book)\n basket.save()\n return render(request,'index.html',{'users':users, 'bookkind':bookkind,})\n","sub_path":"customer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"330762740","text":"# \n# *------------------------------------------------------------------\n# * InterfaceAddressChangeFilter.py\n# *\n# * October 2012, Rahul Mannala\n# *\n# * Copyright (c) 2010-2013 by cisco Systems, Inc.\n# * All rights reserved.\n# *------------------------------------------------------------------\n# \n\nfrom onep.core.event.EventFilter import EventFilter\nfrom onep.core.util.OnepConstants import OnepConstants\nfrom onep.core.exception.OnepIllegalArgumentException import OnepIllegalArgumentException\nfrom onep.interfaces.NetworkInterface import NetworkInterface\n\nclass InterfaceAddressChangeFilter(EventFilter):\n \"\"\" \n This class implements the EventFilter abstract class for filtering an\n interface address change event according to the specified criteria.\n \n Changing interface address involves two operations, first where the existing\n ip address is released and second when new address is applied to interface.\n These two events will happen in quick succession if the user changed the primary\n address, otherwise, individual events may occur well apart from each other as \n and when the user removes the address and assigns new address respectively.\n \n A Filter can be used to provide fine grain control over what events to listen\n to Address Change events.\n \n\n \"\"\"\n _family = OnepConstants.OnepAddressFamilyType.ONEP_AF_ANY\n _interface = None\n\n def _get_address_family(self):\n return self._family\n\n def _set_address_family(self, family):\n if ( family < 0 or family > 3 ) and ( family is not None ) :\n raise OnepIllegalArgumentException(\"The address family being set is invalid\")\n \n if family == None:\n self._family = OnepConstants.OnepAddressFamilyType.ONEP_AF_ANY\n else:\n self._family = family\n\n _doc = \"\"\"\n The family parameter used by the filter.\n If the family is set to None, then the application will receive notifications for all the address families.\n \n Raises: OnepIllegalArgumentException - if address_family is assigned invalid value\n \n @type: L{OnepAddressFamilyType}\n \"\"\"\n address_family = property(_get_address_family,_set_address_family,None,_doc)\n \n def _get_interface(self):\n return self._interface\n\n def _set_interface(self, interface):\n if interface and isinstance(interface,NetworkInterface):\n self._interface = interface\n else:\n self._interface = None\n \n _doc = \"\"\"\n The network Interface. \n The Network Interface object can be obtained from \n L{} API.\n If the network interface is set to None, the application will receive address change \n notifications for all the interfaces on the network element.\n \n @type: L{NetworkInterface} \n \"\"\"\n \n interface = property(_get_interface,_set_interface,None,_doc)\n \n def __init__(self):\n \"\"\" \n The default InterfaceAddressChangeFilter constructor without specifying \n any filter criteria.\n \n The default constructor does not set any filter on the interface address change\n notifications. The application will receive notifications for all address changes\n on all network interfaces. The application can add additional filters using the\n interface and address_family properties. \n \"\"\"\n \n super(InterfaceAddressChangeFilter, self).__init__()\n\n\n \n","sub_path":"X-COPY/infra/onep/presentation/python/onep/interfaces/InterfaceAddressChangeFilter.py","file_name":"InterfaceAddressChangeFilter.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"158389356","text":"\"\"\"\nConfiguration subsystem for ansible-navigator\n\"\"\"\nimport os\n\nfrom enum import Enum\nfrom typing import Any\nfrom typing import Dict\nfrom typing import List\nfrom typing import Tuple\n\nfrom .utils import Sentinel\n\n# TODO: This maybe can/should move to a yaml file in some data (not share) dir\n# at some point in the future. In any case, the structure here should mimic what\n# we'd expect the yaml file to parse to. Every config option should have a\n# default here, ideally.\n#\n# NOTE!!! If you change any default here, update the documentation file in\n# docs/configuration.rst\n\n\ndef generate_editor_command():\n \"\"\"generate a command for EDITOR is env var is set\"\"\"\n if \"EDITOR\" in os.environ:\n command = \"%s {filename}\" % os.environ.get(\"EDITOR\")\n else:\n command = \"vi +{line_number} {filename}\"\n return command\n\n\n_DEFAULTS = {\n \"ansible-navigator\": {\n \"container-engine\": \"podman\",\n \"doc-plugin-type\": \"module\",\n \"editor\": {\n \"command\": generate_editor_command(),\n \"console\": True,\n },\n \"execution-environment\": True,\n \"execution-environment-image\": \"quay.io/ansible/ansible-runner:devel\",\n \"inventory\": [],\n \"inventory-columns\": [],\n \"log\": {\n \"file\": \"./ansible-navigator.log\",\n \"level\": \"info\",\n },\n \"mode\": \"interactive\",\n \"no-osc4\": False,\n \"pass-environment-variable\": [],\n \"playbook\": \"\",\n \"playbook-artifact\": \"{playbook_dir}/{playbook_name}-artifact-{ts_utc}.json\",\n \"set-environment-variable\": {},\n },\n}\n\n# This maps argparse destination variables to config paths\nROOT = \"ansible-navigator\"\nARGPARSE_TO_CONFIG = {\n \"container_engine\": [ROOT, \"container-engine\"],\n \"editor_command\": [ROOT, \"editor\", \"command\"],\n \"editor_console\": [ROOT, \"editor\", \"console\"],\n \"execution_environment_image\": [ROOT, \"execution-environment-image\"],\n \"execution_environment\": [ROOT, \"execution-environment\"],\n \"inventory_columns\": [ROOT, \"inventory-columns\"],\n \"inventory\": [ROOT, \"inventory\"],\n \"logfile\": [ROOT, \"log\", \"file\"],\n \"loglevel\": [ROOT, \"log\", \"level\"],\n \"mode\": [ROOT, \"mode\"],\n \"no_osc4\": [ROOT, \"no-osc4\"],\n \"pass_environment_variable\": [ROOT, \"pass-environment-variable\"],\n \"playbook_artifact\": [ROOT, \"playbook-artifact\"],\n \"playbook\": [ROOT, \"playbook\"],\n \"set_environment_variable\": [ROOT, \"set-environment-variable\"],\n \"type\": [ROOT, \"doc-plugin-type\"],\n}\n\n\nclass NavigatorConfigSource(Enum):\n \"\"\"mapping some enums to log friendly text\"\"\"\n\n USER_CFG = \"user provided configuration file\"\n ARGPARSE_DEFAULT = \"default commandline value\"\n DEFAULT_CFG = \"default configuration value\"\n\n\nclass NavigatorConfig: # pylint: disable=too-few-public-methods\n \"\"\"\n A simple wrapper around a dict, with a method that handles defaults nicely.\n \"\"\"\n\n def __init__(self, dct: Dict):\n self.config = dct\n\n def get(self, keys: List[str], default: Any = Sentinel) -> Tuple[NavigatorConfigSource, Any]:\n \"\"\"\n Takes a list of keys that correspond to nested keys in config.\n If the key is found in the config, return the value.\n Otherwise, if a non-Sentinel default is given, return that.\n Lastly look to the internal default config [defined above] and pull\n out the value from there.\n\n If after all that the key didn't match, throw KeyError.\n \"\"\"\n current = self.config\n for key in keys:\n if isinstance(current, dict) and key in current:\n current = current[key]\n else:\n break\n else:\n return NavigatorConfigSource.USER_CFG, current\n\n # If we made it here, the config key wasn't found.\n if default is not Sentinel:\n return NavigatorConfigSource.ARGPARSE_DEFAULT, default\n\n current = _DEFAULTS\n for key in keys:\n if isinstance(current, dict) and key in current:\n current = current[key]\n else:\n break\n else:\n return NavigatorConfigSource.DEFAULT_CFG, current\n\n raise KeyError(keys)\n","sub_path":"ansible_navigator/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"408644295","text":"# coding:utf-8\n# 2021/9/8 0:13\n\"\"\"\n给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。\n请必须使用时间复杂度为 O(log n) 的算法。\n \n示例 1:\n输入: nums = [1,3,5,6], target = 5\n输出: 2\n\n示例 2:\n输入: nums = [1,3,5,6], target = 2\n输出: 1\n\n示例 3:\n输入: nums = [1,3,5,6], target = 7\n输出: 4\n\n示例 4:\n输入: nums = [1,3,5,6], target = 0\n输出: 0\n\n示例 5:\n输入: nums = [1], target = 0\n输出: 0\n \n\n提示:\n1 <= nums.length <= 104\n-104 <= nums[i] <= 104\nnums 为无重复元素的升序排列数组\n-104 <= target <= 104\n\n来源:力扣(LeetCode)\n链接:https://leetcode-cn.com/problems/search-insert-position\n著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。\n\"\"\"\nfrom typing import List\n\n\nclass Solution(object):\n def searchInsert(self, nums: List[int], target: int) -> int:\n nums.append(target)\n nums.sort()\n return nums.index(target)\n\nif __name__ == \"__main__\":\n sln = Solution()\n print()\n","sub_path":"PyBT/leet_code/35. 搜索插入位置.py","file_name":"35. 搜索插入位置.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"426949277","text":"import pandas as pd\nimport numpy as np\nfrom keras import models, layers, regularizers\nfrom numpy.random import seed\nfrom tensorflow import set_random_seed\nfrom sklearn.metrics import confusion_matrix\nimport pygal\n\n# Set initial parameters\norig_data_path = 'data/PS_20174392719_1491204439457_log.csv'\nmetrics_path = 'data/model_metrics_results.csv'\nnew_data_path = 'data/PS_20174392719_subset.csv'\ncurrent_style = pygal.style.Style(major_label_font_size = 18.0)\nseed(50)\nset_random_seed(50)\n\n\n# Pre-processing\ndef pre_process_kaggle_data(data_path, subset_path,record_size=150000):\n df = pd.read_csv(data_path)\n print('Are there any (explicitly) missing values in the dataset that need to be imputed? {}'.format(df.isnull().values.any()))\n\n # One-hot encoding the transactions types as features\n transaction_type_features = pd.get_dummies(df['type'])\n transaction_type_features.columns = map(str.lower, transaction_type_features.columns)\n\n df = df.join(transaction_type_features)\n df = df.drop('type', axis=1)\n\n # One-hot encoding customer or merchant information\n customer_or_merchant_orig = df['nameOrig'].apply(lambda x: int(x[0]=='C'))\n df = df.drop('nameOrig', axis=1)\n df = df.join(customer_or_merchant_orig)\n customer_or_merchant_new = df['nameDest'].apply(lambda x: int(x[0]=='C'))\n df = df.drop('nameDest', axis=1)\n df = df.join(customer_or_merchant_new)\n df = df.rename(index=str, columns={'nameOrig' : 'originatorCustomer', 'nameDest' : 'destinationCustomer'})\n print('Fraudulent Record Percentage: {}'.format(len(df[df['isFraud']==1])/ float(len(df))))\n\n # Note: To fulfill course maximum size restrictions, we're shrinking our dataset for this assignment.\n # To create a more balanced set we'll: undersample the majority class and oversample the minority class\n\n if record_size >= len(df[df['isFraud']==1]):\n subset_df = pd.concat([df[df['isFraud']==0][:record_size-len(df[df['isFraud']==1])], df[df['isFraud']==1]]).sample(frac=1)\n else:\n subset_df = df[:record_size]\n subset_df.to_csv(subset_path,index=False)\n print('Creating a subset of data with {} records'.format(record_size))\n\n\ndef create_test_train_split(orig_path, train_percentage=.8, transform='none'):\n orig_df = pd.read_csv(orig_path)\n train_x = orig_df[:int(len(orig_df) * train_percentage)]\n train_y = train_x['isFraud'].as_matrix()\n train_x = train_x.drop(['isFraud'],axis=1).as_matrix()\n test_x = orig_df[int(len(orig_df) * (1 - train_percentage)):]\n test_y = test_x['isFraud'].as_matrix()\n test_x = test_x.drop(['isFraud'],axis=1).as_matrix()\n if transform=='log':\n train_x = np.log(train_x+1)\n test_x = np.log(test_x+1)\n\n if transform=='normal':\n full_df = orig_df.drop(['isFraud'],axis=1).as_matrix()\n full_mean = full_df.mean(axis=0)\n full_std = np.std(full_mean, axis=0)\n train_x = train_x - full_mean\n test_x = test_x - full_mean\n train_x = train_x / full_std\n test_x = test_x / full_std\n\n return train_x, train_y, test_x, test_y\n\ndef train_model(new_data_path, path_output):\n df_list = []\n\n # Note: Binary Cross Entropy is recommended for models that output a probability, so it is not modified in the search\n # Note: The RELU activation function is typically able to solve a wide range of problems, so it is not modified in the search\n # Note: RMSPROP is typically a good optimizer for many problems, so it is also not included in the search\n\n # Grid Search for parameters\n for transformed_data in ['none', 'log', 'normal']:\n train_x, train_y, test_x, test_y = create_test_train_split(new_data_path,transform=transformed_data)\n for current_batch_size in [150, 300, 600]:\n for current_epoch_size in [10, 40]:\n for units_per_layer in [14, 28]:\n for current_regularization_weight in [0, 0.01, 0.05]:\n fraud_model = models.Sequential()\n fraud_model.add(layers.Dense(units_per_layer, activation='relu', kernel_regularizer=regularizers.l2(current_regularization_weight), input_shape=(14,)))\n fraud_model.add(layers.Dense(units_per_layer, kernel_regularizer=regularizers.l2(current_regularization_weight), activation='relu'))\n fraud_model.add(layers.Dense(1, activation='sigmoid'))\n fraud_model.compile(optimizer ='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])\n fraud_model.fit(train_x, train_y, epochs=current_epoch_size, batch_size=current_batch_size)\n train_results = fraud_model.evaluate(train_x,train_y)\n results = fraud_model.evaluate(test_x,test_y)\n model_predictions = fraud_model.predict_classes(test_x)\n true_negatives, false_positives, false_negatives, true_positives = confusion_matrix(test_y,model_predictions).ravel()\n perf_row = {\n 'Transform' : str(transformed_data),\n 'Batch_size': current_batch_size,\n 'Epochs' : current_epoch_size,\n 'Units per layer' : units_per_layer,\n 'L2 Regularization Weight' : current_regularization_weight,\n 'Precision' : float(true_positives) / np.nextafter((false_positives + true_positives),1),\n 'Recall': float(true_positives) / np.nextafter((false_negatives + true_positives),1),\n 'Train Accuracy' : train_results[1],\n 'Test Accuracy': results[1]\n }\n df_list.append(perf_row)\n\n pd.DataFrame(df_list).to_csv(path_output,index=False)\n return pd.DataFrame(df_list)\n\ndef analyze_file_results(file_path):\n model_metric_df = pd.read_csv(file_path)\n analyze_results(model_metric_df)\n\ndef generate_chart(curr_df):\n y_labels = curr_df.columns\n bar_chart = pygal.Bar(title='Accuracy Metrics', y_title='Accuracy Metrics',x_title=curr_df.index.name,\n style = current_style, x_labels_major_every = 1)\n bar_chart.x_labels = curr_df.index.tolist()\n for elm in y_labels:\n print(curr_df[elm].tolist())\n bar_chart.add(elm, curr_df[elm].tolist())\n bar_chart.render_to_file('{}.svg'.format(curr_df.index.name))\n\ndef analyze_results(model_metric_df):\n parameter_list = ['Transform', 'Batch_size', 'Epochs', 'Units per layer', 'L2 Regularization Weight']\n metric_list = ['Precision', 'Recall', 'Train Accuracy', 'Test Accuracy']\n for elm in parameter_list:\n curr_df = model_metric_df.groupby([elm]).mean()\n curr_df = curr_df[metric_list]\n generate_chart(curr_df)\n\n# pre_process_kaggle_data(orig_data_path, new_data_path)\nmodel_metric_df = train_model(new_data_path,metrics_path)\nanalyze_file_results(metrics_path)\n","sub_path":"DeepLearningFraudAnalysis.py","file_name":"DeepLearningFraudAnalysis.py","file_ext":"py","file_size_in_byte":7118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"619153937","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import print_function\nimport gensim\nimport csv\nimport io\nimport sys\nimport numpy as np\nimport gzip\nimport os\nimport argparse\nimport logging\nfrom sklearn.manifold import TSNE\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom gensim.models.poincare import PoincareModel, PoincareRelations\nfrom gensim.viz.poincare import poincare_2d_visualization\nfrom gensim.test.utils import datapath\nfrom data_loader import read_all_data, read_trial_data, read_input, compound_operator\n\nimport plotly.plotly as py\npy.sign_in('RamiA', 'lAA8oTL51miiC79o3Hrz')\n# from spacy.en import English\n# parser = spacy.load('en_core_web_md')\nimport pandas\n\n\n\ndef visualize_taxonomy(taxonomy_vectors, taxonomy_names, name):\n tsne = TSNE(n_components=2, random_state=0)\n np.set_printoptions(suppress=True)\n Y = tsne.fit_transform(taxonomy_vectors)\n #plt.figure(figsize=(7,7))\n plt.scatter(Y[:, 0], Y[:, 1])\n for label, x, y in zip(taxonomy_names, Y[:, 0], Y[:, 1]):\n plt.annotate(label, xy=(x, y), xytext=(0, 0), textcoords='offset points', fontsize = 1)\n plt.show()\n plt.savefig(os.path.join(\"vis\", name), dpi = 2000)\n\n\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Embeddings for Taxonomy\")\n parser.add_argument('mode', type=str, default='preload', choices=[\"train_poincare\", \"analysis\", \"visualize_embedding\", \"visualize_embedding_poincare\", \"train_word2vec\"], help=\"Mode of the system.\")\n parser.add_argument('embedding', type=str, nargs='?', default=None, choices=[\"poincare\", \"poincare_all\", \"fasttext\", \"wiki2M\", \"wiki1M_subword\", \"own_w2v\", \"quick\", \"none\"], help=\"Classifier architecture of the system.\")\n parser.add_argument('embedding_name', type=str, nargs='?', default=None, help=\"Classifier architecture of the system.\")\n parser.add_argument('experiment_name', nargs='?', type=str, default=None, help=\"Name of the Experiment\")\n parser.add_argument('--log', action='store_true', help=\"Logs taxonomy and results\")\n parser.add_argument('--trial', action='store_true', help=\"Uses trial dataset\")\n args = parser.parse_args()\n print(\"Mode: \", args.mode)\n run(args.mode, args.embedding, args.embedding_name, args.experiment_name, args.log, args.trial)\n\n\ndef run(mode, embedding, embedding_name, experiment_name = None, log = False, trial = False):\n if embedding == \"fasttext\":\n #model = gensim.models.KeyedVectors.load_word2vec_format('wiki-news-300d-1M-subword.vec', binary=False)\n model = gensim.models.FastText.load_fasttext_format('wiki.en.bin')\n #model = gensim.models.FastText.load_fasttext_format('crawl-300d-2M.vec')\n elif embedding == \"wiki2M\":\n #model = gensim.models.FastText.load_fasttext_format('crawl-300d-2M.vec','vec')\n model = gensim.models.KeyedVectors.load_word2vec_format('embeddings/crawl-300d-2M.vec', binary=False)\n #model.save(\"crawl-300d-2M.bin\")\n elif embedding == \"wiki1M_subword\":\n model = gensim.models.KeyedVectors.load_word2vec_format('embeddings/wiki-news-300d-1M-subword.vec', binary=False)\n\n elif embedding == \"own_w2v\":\n model = gensim.models.KeyedVectors.load('embeddings/own_embeddings_w2v')\n\n elif embedding == \"quick\":\n model = gensim.models.KeyedVectors.load_word2vec_format('embeddings/crawl-300d-2M.vec', binary=False, limit = 50000)\n elif embedding == \"poincare\":\n model = PoincareModel.load('embeddings/poincare_common_domains02_5_3_50')\n print(len(model.kv.vocab))\n words = [\"computer_science\", \"biology\", \"physics\", \"science\", \"virology\", \"life_science\", \"chemistry\", \"earth_science\", \"algebra\", \"economics\", \"optics\" \"immunology\"]\n for word in words:\n print(\"Current word: \", word)\n\n if word in model.kv.vocab:\n try:\n print(\"Closest Parent: \", model.kv.closest_parent(word))\n print(\"Closest Child \", model.kv.closest_child(word))\n print(\"Descendants: \", model.kv.descendants(word))\n print(\"Ancestors: \", model.kv.ancestors(word))\n print(\"Hierarchy diff to Science: \", model.kv.difference_in_hierarchy(word, \"science\"))\n print('\\n')\n except:\n continue\n else:\n print(\"Word not in Vocab\")\n\n\n if mode == \"visualize_embedding_poincare\":\n relations = set([])\n filename_in = os.path.join(os.path.dirname(os.path.abspath(__file__)),\"data/isas_1000.tsv\")\n with open(filename_in, 'r') as f:\n reader = csv.reader(f, delimiter = '\\t')\n for i, line in enumerate(reader):\n relations.add((line[0], line[1]))\n plot = poincare_2d_visualization(model, relations, experiment_name)\n py.image.save_as(plot,\"vis/\" + experiment_name + '.png')\n print(\"Starting visualization\")\n\n\n #visualize_taxonomy(vectors, names)\n#todo own file for train\n if mode == \"visualize_embedding\":\n gold, relations = read_all_data()\n vectors = []\n names = []\n for relation in ([relation1[1].replace(\" \", \"_\") for relation1 in relations] + [relation2[2].replace(\" \", \"_\") for relation2 in relations]):\n if relation not in names:\n if relation not in model.wv:\n print(relation)\n continue\n vectors.append(model.wv[relation])\n names.append(relation)\n visualize_taxonomy(vectors, names, experiment_name)\n\n if mode == 'train_poincare':\n # gold,relations = read_all_data()\n # freq_science = [3,5]\n # for entry_science in freq_science:\n # relations = './data/' + domain +'_crawl_' + str(entry_science) +'.tsv'\n # #relations = './data/science_crawl_merge_10_3_02.tsv'\n # poincare_rel = PoincareRelations(relations)\n # dim = 50\n # model = PoincareModel(poincare_rel, size = dim)\n # print(\"Starting Training...\")\n # model.train(epochs=400)\n # model.save(\"embeddings/embeddings_\" + domain + \"_crawl_poincare_\" + str(entry_science) + \"_\" + str(dim))\n # #model.save(\"embeddings/embeddings_science_crawl_merge_poincare_10_3_50_02\")\n # break\n relations = './data/poincare_common_domains.tsv'\n #relations = './data/science_crawl_merge_10_3_02.tsv'\n poincare_rel = PoincareRelations(relations)\n dim = 50\n model = PoincareModel(poincare_rel, size = dim)\n print(\"Starting Training...\")\n model.train(epochs=400)\n model.save(\"embeddings/poincare_common_domains_5_3\" + \"_\" + str(dim))\n\n if mode == \"train_word2vec\":\n gold_s,relations_s = read_all_data(\"science\")\n gold_e,relations_e = read_all_data(\"environment\")\n gold_f,relations_f = read_all_data(\"food\")\n vocabulary = set([relation[2] for relation in gold_s] + [relation[1] for relation in gold_s])\n vocabulary = vocabulary | set([relation[2] for relation in gold_f] + [relation[1] for relation in gold_f])\n vocabulary = vocabulary | set([relation[2] for relation in gold_e] + [relation[1] for relation in gold_e])\n documents = list(read_input(\"/srv/data/5aly/data_text/wikipedia_utf8_filtered_20pageviews.csv\",vocabulary))\n model = gensim.models.Word2Vec(size= 300, window = 5, min_count = 5, workers = 30)\n model.build_vocab(documents)\n #model.train(documents, total_examples = len(documents), epochs=10)\n model.train(documents, total_examples=model.corpus_count, epochs=30)\n model.save(\"embeddings/own_embeddings_w2v_all\")\n\n elif mode == \"analysis\":\n gold, relations = read_all_data()\n voc_rel = set([relation[1] for relation in relations] + [relation[2] for relation in relations])\n voc_gold = set([relation[1] for relation in gold] + [relation[2] for relation in gold])\n print(\"Vokabeln in Gold: \" + str(len(voc_gold)) + \"Vokabeln in Taxonomy: \" + str(len(voc_rel)))\n\nif __name__ == '__main__':\n main()\n\n\n# def valid_words(relations, model):\n# global compound_operator\n# valid_words = set([])\n# compound_words = {}\n# for relation in relations:\n# issubset_1 = True\n# issubset_2 = True\n# for entry in relation[1].split(compound_operator):\n# if not entry in model.wv:\n# issubset_1 = False\n# break\n# if relation[1] in model.wv:\n# valid_words.add(relation[1])\n# elif issubset_1:\n# #print word\n# compound_word = create_compound_word(relation[1], model)\n# compound_words[relation[1]] = compound_word\n# valid_words.add(relation[1])\n#\n# for entry in relation[2].split(compound_operator):\n# if not entry in model.wv:\n# issubset_2 = False\n# break\n#\n# if relation[2] in model.wv:\n# valid_words.add(relation[2])\n# elif issubset_2:\n# #print word\n# compound_word = create_compound_word(relation[2], model)\n# compound_words[relation[2]] = compound_word\n# valid_words.add(relation[2])\n# #model.syn0.build_vocab([relation[2]], update=True)\n# model.syn0[relation[2]] = compound_word\n#\n# return valid_words, compound_words\n\n#\"embeddings_common_small_poincare_100_50\", \"embeddings_common_small_poincare_10_50\", \"embeddings_common_small_poincare_3_50\", \"embeddings_common_small_poincare_500_50\", \"embeddings_common_small_poincare_5_50\",\n# \"embeddings_science_crawl_combined_common_poincare_10_10_50\", \"embeddings_science_crawl_combined_common_poincare_10_3_50\", \"embeddings_science_crawl_combined_common_poincare_10_5_50\",\n# \"embeddings_science_crawl_combined_common_poincare_100_10_50\",\n# \"embeddings_science_crawl_combined_common_poincare_100_3_50\", \"embeddings_science_crawl_combined_common_poincare_100_5_50\", \"embeddings_science_crawl_combined_common_poincare_500_10_50\", \"embeddings_science_crawl_combined_common_poincare_500_3_50\"\n# ,\"embeddings_science_crawl_combined_common_poincare_500_5_50\",\"embeddings_science_crawl_combined_common_poincare_50_10_50\",\"embeddings_science_crawl_combined_common_poincare_50_3_50\",\"embeddings_science_crawl_combined_common_poincare_50_5_50\",\n# \"embeddings_science_crawl_poincare_10_50\", \"embeddings_science_crawl_poincare_3_50\", \"embeddings_science_crawl_poincare_5_50\"\n","sub_path":"distributed_semantics/gensim_embeddings.py","file_name":"gensim_embeddings.py","file_ext":"py","file_size_in_byte":10537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"295426249","text":"import seaborn as sns\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\nfrom analysis_functions import calculate_angle_from_history, calculate_winning_pattern_from_distances\nfrom analysis_functions import calculate_patterns_timings\n\n\nclass MidpointNormalize(matplotlib.colors.Normalize):\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 def __call__(self, value, clip=None):\n # I'm ignoring masked values and all kinds of edge cases to make a\n # simple example...\n x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]\n return np.ma.masked_array(np.interp(value, x, y))\n\n\ndef set_text(ax, coordinate_from, coordinate_to, fontsize=25, color='black'):\n \"\"\"\n Set text in an axis\n :param ax: The axis\n :param coordinate_from: From pattern\n :param coordinate_to: To pattern\n :param fontsize: The fontsize\n :return:\n \"\"\"\n message = str(coordinate_from) + '->' + str(coordinate_to)\n ax.text(coordinate_from, coordinate_to, message, ha='center', va='center',\n rotation=315, fontsize=fontsize, color=color)\n\n\ndef plot_sequences(sequences, minicolumns):\n sns.set_style(\"whitegrid\", {'axes.grid': False})\n sequence_matrix = np.zeros((len(sequences), minicolumns))\n for index, sequence in enumerate(sequences):\n sequence_matrix[index, sequence] = index + 1\n\n fig = plt.figure(figsize=(16, 12))\n ax = fig.add_subplot(111)\n\n cmap = matplotlib.cm.Paired\n cmap = matplotlib.cm.prism\n cmap.set_under('white')\n\n ax.imshow(sequence_matrix, cmap=cmap, vmin=0.5)\n sns.set()\n\n\ndef plot_weight_matrix(manager, one_hypercolum=True, ax=None, vmin=None, title=True, transpose=False):\n with sns.axes_style(\"whitegrid\", {'axes.grid': False}):\n\n w = manager.nn.w\n\n if one_hypercolum:\n w = w[:manager.nn.minicolumns, :manager.nn.minicolumns]\n\n # aux_max = np.max(np.abs(w))\n norm = MidpointNormalize(midpoint=0)\n cmap = matplotlib.cm.RdBu_r\n\n if ax is None:\n # sns.set_style(\"whitegrid\", {'axes.grid': False})\n fig = plt.figure()\n ax = fig.add_subplot(111)\n if transpose:\n matrix_to_plot = w.T\n else:\n matrix_to_plot = w\n im = ax.imshow(matrix_to_plot, cmap=cmap, interpolation='None', norm=norm, vmin=vmin)\n\n if title:\n ax.set_title('w connectivity')\n\n divider = make_axes_locatable(ax)\n cax = divider.append_axes('right', size='5%', pad=0.05)\n cb = ax.get_figure().colorbar(im, ax=ax, cax=cax)\n\n return ax\n\n\ndef plot_persistent_matrix(manager, ax=None):\n with sns.axes_style(\"whitegrid\", {'axes.grid': False}):\n title = r'$T_{persistence}$'\n\n cmap = matplotlib.cm.Reds_r\n cmap.set_bad(color='white')\n cmap.set_under('black')\n\n if ax is None:\n # sns.set_style(\"whitegrid\", {'axes.grid': False})\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n im = ax.imshow(manager.T, cmap=cmap, interpolation='None', vmin=0.0)\n ax.set_title(title)\n\n divider = make_axes_locatable(ax)\n cax = divider.append_axes('right', size='5%', pad=0.05)\n ax.get_figure().colorbar(im, ax=ax, cax=cax)\n\n\ndef plot_winning_pattern(manager, ax=None, separators=False, remove=0):\n \"\"\"\n Plots the winning pattern for the sequences\n :param manager: A network manager instance\n :param ax: an axis instance\n :return:\n \"\"\"\n\n n_patterns = manager.nn.minicolumns\n T_total = manager.T_training_total\n # Get the angles\n angles = calculate_angle_from_history(manager)\n winning = calculate_winning_pattern_from_distances(angles) + 1 # Get them in the color bounds\n timings = calculate_patterns_timings(winning, manager.dt, remove)\n winners = [x[0] for x in timings]\n pattern_times = [x[2] + 0.5 * x[1] for x in timings]\n # 0.5 is for half of the time that the pattern lasts ( that is x[1])\n start_times = [x[2] for x in timings]\n\n # Filter the data\n angles[angles < 0.1] = 0\n filter = np.arange(1, angles.shape[1] + 1)\n angles = angles * filter\n\n # Add a column of zeros and of the winners to the stack\n zeros = np.zeros_like(winning)\n angles = np.column_stack((angles, zeros, winning))\n\n # Plot\n with sns.axes_style(\"whitegrid\", {'axes.grid': False}):\n if ax is None:\n fig = plt.figure(figsize=(16, 12))\n ax = fig.add_subplot(111)\n\n fig = ax.figure\n\n cmap = matplotlib.cm.Paired\n cmap.set_under('white')\n extent = [0, n_patterns + 2, T_total, 0]\n\n im = ax.imshow(angles, aspect='auto', interpolation='None', cmap=cmap, vmax=filter[-1], vmin=0.9, extent=extent)\n ax.set_title('Sequence of patterns')\n ax.set_xlabel('Patterns')\n ax.set_ylabel('Time')\n\n # Put labels in both axis\n ax.tick_params(labeltop=False, labelright=False)\n\n # Add seperator\n ax.axvline(n_patterns, color='k', linewidth=2)\n ax.axvline(n_patterns + 1, color='k', linewidth=2)\n ax.axvspan(n_patterns, n_patterns + 1, facecolor='gray', alpha=0.3)\n\n # Add the sequence as a text in a column\n x_min = n_patterns * 1.0/ (n_patterns + 2)\n x_max = (n_patterns + 1) * 1.0 / (n_patterns + 2)\n\n for winning_pattern, time, start_time in zip(winners, pattern_times, start_times):\n ax.text(n_patterns + 0.5, time, str(winning_pattern), va='center', ha='center')\n if separators:\n ax.axhline(y=start_time, xmin=x_min, xmax=x_max, linewidth=2, color='black')\n\n # Colorbar\n bounds = np.arange(0.5, n_patterns + 1.5, 1)\n ticks = np.arange(1, n_patterns + 1, 1)\n\n # Set the ticks positions\n ax.set_xticks(bounds)\n # Set the strings in those ticks positions\n strings = [str(int(x + 1)) for x in bounds[:-1]]\n strings.append('Winner')\n ax.xaxis.set_major_formatter(plt.FixedFormatter(strings))\n\n fig.subplots_adjust(right=0.8)\n cbar_ax = fig.add_axes([0.85, 0.12, 0.05, 0.79])\n fig.colorbar(im, cax=cbar_ax, boundaries=bounds, cmap=cmap, ticks=ticks, spacing='proportional')\n\n\ndef plot_sequence(manager):\n\n T_total = manager.T_training_total\n # Get the angles\n angles = calculate_angle_from_history(manager)\n winning = calculate_winning_pattern_from_distances(angles)\n winning = winning[np.newaxis]\n\n # Plot\n sns.set_style(\"whitegrid\", {'axes.grid': False})\n\n filter = np.arange(1, angles.shape[1] + 1)\n angles = angles * filter\n\n cmap = matplotlib.cm.Paired\n cmap.set_under('white')\n\n extent = [0, T_total, manager.nn.minicolumns, 0]\n fig = plt.figure(figsize=(16, 12))\n\n ax1 = fig.add_subplot(111)\n im1 = ax1.imshow(winning, aspect=2, interpolation='None', cmap=cmap, vmax=filter[-1], vmin=0.9, extent=extent)\n ax1.set_title('Winning pattern')\n\n # Colorbar\n bounds = np.arange(0, manager.nn.minicolumns + 1, 0.5)\n fig.subplots_adjust(right=0.8)\n cbar_ax = fig.add_axes([0.85, 0.12, 0.05, 0.79])\n cb = fig.colorbar(im1, cax=cbar_ax, boundaries=bounds)\n\n\ndef plot_network_activity_angle(manager, recall=True, cmap=None, ax=None, title=True, time_y=True):\n if recall:\n T_total = manager.T_recall_total\n else:\n T_total = manager.T_training_total\n\n history = manager.history\n # Get the angles\n angles = calculate_angle_from_history(manager)\n patterns_dic = manager.patterns_dic\n n_patters = len(patterns_dic)\n # Plot\n sns.set_style(\"whitegrid\", {'axes.grid': False})\n\n if cmap is None:\n cmap = 'plasma'\n\n if title:\n title1 = 'Unit activation'\n title2 = 'Angles with stored'\n else:\n title1 = ''\n title2 = ''\n\n if ax is None:\n fig = plt.figure(figsize=(16, 12))\n ax1 = fig.add_subplot(121)\n ax2 = fig.add_subplot(122)\n else:\n ax1, ax2 = ax\n fig = ax1.figure\n\n if time_y:\n extent1 = [0, manager.nn.minicolumns * manager.nn.hypercolumns, T_total, 0]\n extent2 = [0, n_patters, T_total, 0]\n\n im1 = ax1.imshow(history['o'], aspect='auto', interpolation='None', cmap=cmap, vmax=1, vmin=0, extent=extent1)\n ax1.set_title(title1)\n\n ax1.set_xlabel('Units')\n ax1.set_ylabel('Time (s)')\n\n im2 = ax2.imshow(angles, aspect='auto', interpolation='None', cmap=cmap, vmax=1, vmin=0, extent=extent2)\n ax2.set_title(title2)\n ax2.set_xlabel('Patterns')\n\n else:\n extent1 = [0, T_total, 0, manager.nn.minicolumns * manager.nn.hypercolumns]\n extent2 = [0, T_total, 0, n_patters]\n\n im1 = ax1.imshow(history['o'].T, aspect='auto', origin='lower', cmap=cmap, vmax=1, vmin=0, extent=extent1)\n ax1.set_title(title1)\n\n ax1.set_xlabel('Time (s)')\n ax1.set_ylabel('Units')\n\n im2 = ax2.imshow(angles.T, aspect='auto', origin='lower', cmap=cmap, vmax=1, vmin=0, extent=extent2)\n ax2.set_title(title2)\n ax2.set_ylabel('Patterns')\n ax2.set_xlabel('Time (s)')\n\n if ax is None:\n fig.tight_layout()\n fig.subplots_adjust(right=0.8)\n cbar_ax = fig.add_axes([0.85, 0.12, 0.05, 0.79])\n fig.colorbar(im1, cax=cbar_ax)\n\n\n\n return [ax1, ax2]\n\n\ndef plot_network_activity(manager):\n\n T_total = manager.T_total\n\n history = manager.history\n sns.set_style(\"whitegrid\", {'axes.grid': False})\n\n cmap = 'plasma'\n extent = [0, manager.nn.minicolumns * manager.nn.hypercolumns, T_total, 0]\n\n fig = plt.figure(figsize=(16, 12))\n\n ax1 = fig.add_subplot(221)\n im1 = ax1.imshow(history['o'], aspect='auto', interpolation='None', cmap=cmap, vmax=1, vmin=0, extent=extent)\n ax1.set_title('Unit activation')\n\n ax2 = fig.add_subplot(222)\n im2 = ax2.imshow(history['z_pre'], aspect='auto', interpolation='None', cmap=cmap, vmax=1, vmin=0, extent=extent)\n ax2.set_title('Traces of activity (z)')\n\n ax3 = fig.add_subplot(223)\n im3 = ax3.imshow(history['a'], aspect='auto', interpolation='None', cmap=cmap, vmax=1, vmin=0, extent=extent)\n ax3.set_title('Adaptation')\n\n ax4 = fig.add_subplot(224)\n im4 = ax4.imshow(history['p_pre'], aspect='auto', interpolation='None', cmap=cmap, vmax=1, vmin=0, extent=extent)\n ax4.set_title('Probability')\n\n fig.subplots_adjust(right=0.8)\n cbar_ax = fig.add_axes([0.85, 0.12, 0.05, 0.79])\n fig.colorbar(im1, cax=cbar_ax)\n","sub_path":"plotting_functions.py","file_name":"plotting_functions.py","file_ext":"py","file_size_in_byte":10676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"149542779","text":"# SIMULATE - Given a PRISM model, obtain a sample \n# trace using get_trace.py and simulate it.\n\n# Author: Francisco Girbal Eiras, MSc Computer Science\n# University of Oxford, Department of Computer Science\n# Email: francisco.eiras@cs.ox.ac.uk\n# 12-May-2018; Last revision: 2-Aug-2018\n\nimport pygame\nimport sys, os, csv, argparse, subprocess\n\nparser=argparse.ArgumentParser(\n description='''Given a PRISM model, obtain a sample trace using get_trace.py and simulate it.''')\nparser.add_argument('model', type=str, help='The model from which to obtain the sample execution (built using model_generator.py).')\nparser.add_argument('-x', '--times', type=float, default=1, help='Execution is X times faster.')\nparser.add_argument('-rt', '--read_trace', action=\"store_true\", help='Read an existing trace.')\nargs=parser.parse_args()\n\nmodel = args.model\nspeed = args.times\n\n# Helper functions\n_image_library = {}\ndef get_image(path):\n\tglobal _image_library\n\timage = _image_library.get(path)\n\tif image == None:\n\t\t\tcanonicalized_path = path.replace('/', os.sep).replace('\\\\', os.sep)\n\t\t\timage = pygame.image.load('graphics/' + canonicalized_path)\n\t\t\tif path == \"background.png\":\n\t\t\t\timage = pygame.transform.scale(image, (1000,400))\n\t\t\tif path == \"car_red.png\" or path == \"car_grey.png\":\n\t\t\t\timage = pygame.transform.scale(image, (20,11))\n\t\t\t_image_library[path] = image\n\treturn image\n\ndef render_centered(screen, text, color):\n\tlabel = crashed_font.render(text, 1, color)\n\tsize = crashed_font.size(text)\n\tscreen.blit(label, (500 - size[0]/2.0, 200 - size[1]/2.0))\n\ndef detect_crash(x1, y1, x2, y2, w, h):\n\tx = max(x1 - w/2, x2 - w/2)\n\ty = max(y1 - h/2, y2 - h/2)\n\tw_new = min(x1 + w/2, x2 + w/2) - x\n\th_new = min(y1 + h/2, y2 + h/2) - y\n\tif w_new <= 0 or h_new <= 0:\n\t\treturn False\n\treturn True\n\n# Main code\nv1 = -1\nx1_0 = -1\n\nf = open(model, 'r')\n\nfor line in f:\n\tif \"const int v1\" in line:\n\t\tnums = line.split()\n\t\tv1 = int(nums[4][:-1])\n\telif \"const int x1_0\" in line:\n\t\tnums = line.split()\n\t\tx1_0 = int(nums[4][:-1])\n\t\tbreak\n\nif v1 == -1 or x1_0 == -1:\n\tprint(\"Error: model not generated using the model_generator.py (problems reading v1 and x1_0)\")\n\tquit()\n\nf.close()\n\n# Generate the trace\nif not args.read_trace:\n\tsubprocess.run(\"python3 get_trace.py %s %d %d\"%(model, v1, x1_0), shell=True)\n\npygame.init()\npygame.display.set_caption('Sample Path Simulation')\nscreen = pygame.display.set_mode((1000,400))\nmyfont = pygame.font.SysFont(\"monospaced\", 20)\ncrashed_font = pygame.font.SysFont(\"monospaced\", 45)\ntime_font = pygame.font.SysFont(\"monospaced\", 60)\n\ncsvfile = open('gen_trace.csv')\nreader = csv.DictReader(csvfile)\ncomm = next(reader)\n\n# Read the first command\nt_init = 0\nx_init = 0\ny_init = 1.8\nt_end = int(comm['t_end'])\ntype_comm = int(comm['type'])\ncurr_v = int(comm['v'])\ncrashed = bool(int(comm['crashed']))\nx_coeffs = [float(comm['x_t_1']), float(comm['x_t_2']), float(comm['x_t_3'])]\ny_coeffs = [float(comm['y_t_1']), float(comm['y_t_2']), float(comm['y_t_3']), float(comm['y_t_4']), float(comm['y_t_5']), float(comm['y_t_6']), float(comm['y_t_7'])]\n\n# Setup of the other variables\nx0 = x1_0\nv0 = v1\n\nt = 0.0\ndeltaT = 0.05\nscaleX = 2\nscaleY = 5\nc_height = 9\nc_width = 20\n\nx = x_init\ny = y_init\n\nupdate_action = False\npermanent = False\nforce_crash = False\n\nwhile True:\n\tfor event in pygame.event.get():\n\t\tif event.type == pygame.QUIT:\n\t\t\tpygame.quit()\n\t\t\tquit()\n\t\tif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:\n\t\t\tupdate_action = not update_action\n\n\tscreen.fill((255,255,255))\n\tscreen.blit(get_image('background.png'), (0, 0))\n\n\tscreen.blit(get_image('car_red.png'), (x*scaleX - c_width/2, 218 - y*scaleY - c_height/2))\n\n\t# Other vehicle\n\tscreen.blit(get_image('car_grey.png'), ((x0 + t*v0)*scaleX - c_width/2, 218 - 1.8*scaleY - c_height/2))\n\n\t# Display info\n\ttime_label = time_font.render(\"%2.1fs\"%t, 1, (0,0,0))\n\tscreen.blit(time_label, (175, 35))\n\n\tmain_vahicle_label = myfont.render(\"Main vehicle\", 1, (128,128,128))\n\tscreen.blit(main_vahicle_label, (325, 25))\n\n\tx_label = myfont.render(\"x Position: %dm\"%x, 1, (0,0,0))\n\tscreen.blit(x_label, (325, 45))\n\n\ty_label = myfont.render(\"y Position: %.2fm\"%y, 1, (0,0,0))\n\tscreen.blit(y_label, (325, 65))\n\n\tother_vahicle_label = myfont.render(\"Other vehicle\", 1, (128,128,128))\n\tscreen.blit(other_vahicle_label, (475, 25))\n\n\tx_label = myfont.render(\"x Position: %dm\"%(x0 + t*v0), 1, (0,0,0))\n\tscreen.blit(x_label, (475, 45))\n\n\ty_label = myfont.render(\"y Position: 1.8m\", 1, (0,0,0))\n\tscreen.blit(y_label, (475, 65))\n\n\tif detect_crash(x,y,(x0 + t*v0),1.8,4.8,1.9) == True or force_crash == True:\n\t\trender_centered(screen, \"Crashed\", (0,0,0))\n\t\tpermanent = True\n\n\t# Main vehicle\n\tif update_action == True and permanent == False:\n\t\tif t < t_end:\n\t\t\tif type_comm == 1:\n\t\t\t\tx = x + curr_v*deltaT\n\t\t\telif type_comm == 2:\n\t\t\t\tcurr_t = t - t_init\n\t\t\t\tx = x_init + (x_coeffs[0]*curr_t**2 + x_coeffs[1]*curr_t + x_coeffs[2])\n\t\t\t\ty = (y_coeffs[0]*curr_t**6 + y_coeffs[1]*curr_t**5 + y_coeffs[2]*curr_t**4 + y_coeffs[3]*curr_t**3 + y_coeffs[4]*curr_t**2 + y_coeffs[5]*curr_t + y_coeffs[6])\n\n\t\tif t >= t_end:\n\t\t\tif crashed == True:\n\t\t\t\tpermanent = True\n\t\t\t\tforce_crash = True\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tcomm = next(reader)\n\t\t\t\texcept:\n\t\t\t\t\tprint('Done')\n\t\t\t\t\tbreak\n\n\t\t\t\t# Read the next command\n\t\t\t\tt_init = t\n\t\t\t\tx_init = x\n\t\t\t\ty_init = y\n\t\t\t\tt_end = int(comm['t_end'])\n\t\t\t\ttype_comm = int(comm['type'])\n\t\t\t\tcurr_v = int(comm['v'])\n\t\t\t\tcrashed = bool(int(comm['crashed']))\n\t\t\t\tx_coeffs = [float(comm['x_t_1']), float(comm['x_t_2']), float(comm['x_t_3'])]\n\t\t\t\ty_coeffs = [float(comm['y_t_1']), float(comm['y_t_2']), float(comm['y_t_3']), float(comm['y_t_4']), float(comm['y_t_5']), float(comm['y_t_6']), float(comm['y_t_7'])]\n\n\t\tif x >= 500 or t >= 30:\n\t\t\tupdate_action = False\n\t\t\tpermanent = True\n\n\t\tt = t + deltaT\n\n\telif crashed == False and update_action == False and permanent == False:\n\t\tif x == 0:\n\t\t\trender_centered(screen, \"Press SPACE to start\", (0,0,0))\n\t\telse:\n\t\t\trender_centered(screen, \"Press SPACE to continue\", (0,0,0))\n\telif crashed == False and permanent == True:\n\t\trender_centered(screen, \"Done\", (0,0,0))\n\n\tpygame.display.flip()\n\tpygame.time.wait(int(1000*deltaT/speed))\n\npygame.quit()","sub_path":"dissertation/code/appendix1/simulate.py","file_name":"simulate.py","file_ext":"py","file_size_in_byte":6161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"473502643","text":"\"\"\"\n下面的文件将会从csv文件中读取短信与电话记录,\n你将在以后的课程中了解更多有关读取文件的知识。\n\"\"\"\nimport csv\nwith open('texts.csv', 'r') as f:\n reader = csv.reader(f)\n texts = list(reader)\n\nwith open('calls.csv', 'r') as f:\n reader = csv.reader(f)\n calls = list(reader)\n\n\n\"\"\"\n任务1:\n短信和通话记录中一共有多少电话号码?每个号码只统计一次。\n输出信息:\n\"There are different telephone numbers in the records.\"\n\"\"\"\nphone_list = []\n# get phone numbers in texts list\nfor text in texts:\n phone_list.append(text[0])\n phone_list.append(text[1])\n\n# get phone numbers in calls list\nfor call in calls:\n phone_list.append(call[0])\n phone_list.append(call[1])\n\nprint(\"There are {} different telephone numbers in the records\".format(len(set(phone_list))))\n","sub_path":"investigate texts and calls/ZH/Task1.py","file_name":"Task1.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"54310527","text":"\"\"\"\n\n**************************************************************************\n| Candidate.py |\n**************************************************************************\n| Description: |\n| |\n| Represents an individual pulsar candidate. This code runs on python |\n| 2.4 or later. |\n**************************************************************************\n| Author: Rob Lyon |\n| Email : robert.lyon@postgrad.manchester.ac.uk |\n| web : www.scienceguyrob.com |\n**************************************************************************\n \n\"\"\"\n\n# Custom Imports\nimport PHCXFile as phcx\nimport PFDFile as pfd\nimport PHCXSKASAFile as phcxskasa\n\n# ****************************************************************************************************\n#\n# CLASS DEFINITION\n#\n# ****************************************************************************************************\n\nclass Candidate:\n \"\"\"\n Represents an individual pulsar candidate.\n \n \"\"\"\n \n # ****************************************************************************************************\n #\n # INIT FUNCTION\n #\n # ****************************************************************************************************\n def __init__(self,name=\"Unknown\",path=\"\"):\n \"\"\"\n Represents an individual Pulsar candidate.\n \n Parameters:\n \n name - the primary name for this individual candidate.\n The file name is typically used.\n path - the full path to the candidate file.\n \n \"\"\"\n self.candidateName = name # Name of the candidate file, minus the path.\n self.candidatePath = path # The full path to the candidate.\n self.features = [] # Stores all candidate features. \n \n # ****************************************************************************************************\n # \n # FEATURE CALCULATIONS.\n #\n # ****************************************************************************************************\n \n def getFeatures(self,feature_type,candidate_type,verbose):\n \"\"\"\n Calculates the features for this candidate. If the file name of\n this Candidate object contains .pfd, then the PFD file feature generation\n code should be executed. Likewise if the file name ends in PHCX, then\n PHCX file feature generation (either for Thornton gnuzipped '.phcx.gz' PHCX files, or\n Morello et al. PHCX files) should be executed. \n \n Note that there is a subtle difference between the PHCX files used by Thornton\n and Morello et al. - in terms of where the profile data is stored in XML format. \n Thus these files should be treated differently. For Thornton generated PHCX files,\n the xml data contains two distinct profile sections:\n \n i.e. there are two ... sections in the file.\n \n These section are indexed by the code that reads the xml. The first section\n with profileIndex = 0, corresponds to a profile obtained after the FFT.\n The second, profileIndex = 1, to a profile that has been period and DM searched\n using PDMPD. Since the latter is the correct data to use for Thronton produced\n PHCX files, we use the data at profileIndex = 1.\n \n For Morello et al. produced data, there is a similar situation, except that the data\n sections are in reverse order. So now we need to use profileIndex = 0 to get the profile\n data that has been period and DM searched using PDMPD. \n \n The result of this is that the two types of PHCX file are treated slightly differently.\n \n If further data file formats need to be processed, then changes need\n to be made here in order to cope with them. For example, if a new file format\n called .x appears, then below a check must be added for .x files,\n along with a new script to deal with them. Also note that additional changes\n would also be needed for the PulsarFeatureLab.py command line argument processing\n code, and a slight modification to the process() function in the FeatureGenerator.py\n script.\n \n Parameters:\n feature_type - the type of features to generate.\n \n feature_type = 1 generates 12 features from Eatough et al., MNRAS, 407, 4, 2010.\n feature_type = 2 generates 22 features from Bates et al., MNRAS, 427, 2, 2012.\n feature_type = 3 generates 22 features from Thornton, PhD Thesis, Univ. Manchester, 2013.\n feature_type = 4 generates 6 features from Lee et al., MNRAS, 333, 1, 2013.\n feature_type = 5 generates 6 features from Morello et al., MNRAS, 433, 2, 2014.\n feature_type = 6 generates 8 features from Lyon et al.,2015.\n feature_type = 7 obtains raw integrated (folded) profile data.\n feature_type = 8 obtains raw DM-SNR Curve data.\n \n candidate_type - the type of candidate file being processed.\n \n candidate_type = 1 assumes PHCX candidates output by the pipeline described by\n Morello et al., MNRAS 443, 2, 2014.\n candidate_type = 2 assumes gnuzipped ('.gz') PHCX candidates produced by the\n pipeline described by Thornton., PhD Thesis, Univ. Manchester, 2013.\n candidate_type = 3 assumes PFD files output by the LOTAAS and similar surveys in the\n presto PFD format.\n candidate_type = 4 assumes PHCX candidates output by the SKA SA pipeline.\n \n verbose - the verbose logging flag.\n \n Returns:\n \n The candidate features as an array of floats.\n \"\"\" \n \n if(\".pfd\" in self.candidateName and candidate_type == 3):\n c = pfd.PFD(verbose,self.candidateName)\n self.features = c.computeFeatures(feature_type)\n return self.features\n \n elif(\".phcx.gz\" in self.candidateName and candidate_type == 2):\n profileIndex = 1 # For xml file, read comments above.\n c = phcx.PHCX(verbose,self.candidateName,profileIndex)\n self.features = c.computeFeatures(feature_type)\n return self.features\n \n elif(\".phcx\" in self.candidateName and candidate_type == 1):\n profileIndex = 0 # For xml file, read comments above.\n c = phcx.PHCX(verbose,self.candidateName,profileIndex)\n self.features = c.computeFeatures(feature_type)\n return self.features\n\n elif(\".phcx\" in self.candidateName and candidate_type == 4):\n profileIndex = 0 # For xml file, read comments above.\n c = phcxskasa.PHCXSKASA(verbose,self.candidateName,profileIndex)\n self.features = c.computeFeatures(feature_type)\n return self.features\n\n else:\n raise Exception(\"Unknown candidate type: Candidate.py (Line 136).\")\n \n # ****************************************************************************************************\n \n def getName(self):\n \"\"\"\n Obtains the name of the candidate file, not the full path.\n \n \n Returns:\n \n The name of the candidate file.\n \"\"\"\n return self.candidateName\n \n # ****************************************************************************************************\n \n def getPath(self):\n \"\"\"\n Obtains the full path to the candidate.\n \n \n Returns:\n \n The full path to the candidate.\n \"\"\"\n return self.candidatePath\n \n # ****************************************************************************************************\n \n def __str__(self):\n \"\"\"\n Overridden method that provides a neater string representation\n of this class. This is useful when writing these objects to a file\n or the terminal.\n \n \"\"\"\n \n return self.candidateName + \",\" + self.candidatePath\n \n # ****************************************************************************************************","sub_path":"ProjectFiles/Bits Needed/Candidate.py","file_name":"Candidate.py","file_ext":"py","file_size_in_byte":9048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"315104569","text":"'''\nThis is a python implementation of the paper \"GraRep: Learning Graph Representations with Global Structural Information\".\n\nIn this application scenario, the proposed idea is applied to part(all friends of one user) of the datasets (social circles: facebook).\n\nThe datasets, which consists of friends of the user as nodes and friend-relationship between his or her friends as edges, can be treated as graph data.\n\nThe code try to learn a distributted representation for each node considering the global strutural information of the graph.\n\nThe learned representation is used to clustering. The clusters are different social circles of the user.\n\n'''\n\n\n#import used packages\nimport numpy as np\nfrom time import time,strftime,localtime,gmtime\n\nfrom autoencoder import test_dA\nfrom sklearn.manifold import TSNE\nfrom sklearn.cluster import KMeans\nfrom matplotlib import pyplot as plt\n\n\n#specify the hyperparameters\nstep = 10 ## the number of steps to collect structural information\ndim = 100 ## the number of dimentionalitied of the disttributted representation\nalpha = 0.5\nnum_clusters = 10\n\n#load nodes of the graph\nwith open(\"graph_data/414.feat\", \"rb\") as f:\n nodes_feat = f.readlines()\n\nnodes = []\nfor node in nodes_feat:\n nodes.append(node.split(' ', 1)[0])\n \nprint(\"\\nthe number of nodes is \"+str(len(nodes)))\n\n\n#load edges of the graph\nwith open(\"graph_data/414.edges\", \"rb\") as f:\n nodes_pairs = f.readlines()\n\nedges = []\nfor nodes_pair in nodes_pairs:\n edges.append(nodes_pair.split(' ')[0]) #every node with even index k is connected to the node with index k+1.\n edges.append(nodes_pair.split(' ')[1].split('\\n')[0])\n \nprint(\"\\nthe number of edges is \"+str(len(edges)/2))\n\n\n#Preprocess: remove isolated nodes\nfor start_node in nodes:\n exist_flag = 0\n for i in range(len(edges)):\n if start_node == edges[i]:\n exist_flag = 1\n if exist_flag == 0:\n nodes.remove(start_node)\n\nprint(\"\\nthe number of nodes after preprocess is \"+str(len(nodes)))\n\n\n#get adjacency matrix\nnodes_num = len(nodes)\n\nadjacency_matrix = np.zeros((nodes_num, nodes_num))\nfor i in range(len(edges)/2):\n start_index = 0\n end_index = 0\n for start_node in nodes:\n if start_node == edges[2*i]:\n for end_node in nodes:\n if end_node == edges[2*i+1]:\n adjacency_matrix[start_index][end_index] = 1\n break\n end_index += 1\n break\n start_index += 1\n\n\n#compute inverse degree matrix and transition matrix\nnp.fill_diagonal(adjacency_matrix, 0) #replace the diagnal elements with zeros\nsum_vect = np.sum(adjacency_matrix, axis=1)\n\nfor i in range(len(sum_vect)):\n if sum_vect[i] != 0:\n sum_vect[i] = 1/sum_vect[i]\n \ndegree_matix_inv_like = np.diag(sum_vect)\n\ntransition_matrix = np.dot(degree_matix_inv_like, adjacency_matrix)\n\n \n#generate k-step transition matrix\nk_transition_matrix = np.zeros((nodes_num, nodes_num,step))\nk_transition_matrix[:,:,0] = transition_matrix\n\nfor i in range(1, step):\n k_transition_matrix[:,:,i] = np.dot(k_transition_matrix[:,:,i-1],transition_matrix)\n\n#calculate probability transition matrix and factorise the matrix\ndef GetProbTranMat(Ak):\n \n num_node, num_node2 = Ak.shape\n if (num_node != num_node2):\n print('M must be a square matrix!')\n \n Ak_sum = np.sum(Ak, axis=0).reshape(1,-1)\n Ak_sum = np.repeat(Ak_sum, num_node, axis=0)\n\n probTranMat = np.log(np.divide(Ak, Ak_sum)) - np.log(1./num_node) \n probTranMat[probTranMat < 0] = 0; #set zero for negative and -inf elements\n probTranMat[np.isnan(probTranMat)] = 0; #set zero for nan elements (the isolated nodes)\n \n return probTranMat\n\n\n#generate representation matrix in case that the matrix is factorised with svd method\nrepresentation_matrix_svd = np.zeros((nodes_num, step*dim))\ndef GetRepMat_svd():\n for i in range(step):\n probTranMat = GetProbTranMat(k_transition_matrix[:,:,i])\n\n U, S, V = np.linalg.svd(np.float32(probTranMat), full_matrices=1, compute_uv=1)\n Ud = U[:, :dim]\n S = np.diag(S)\n Sd = S[:dim, :dim]\n \n Rk = np.dot(Ud, np.power(Sd, alpha))\n Rk = np.divide(Rk, np.repeat(np.sqrt(np.sum(np.power(Rk, 2), axis=1)).reshape(-1,1), dim, axis=1))\n representation_matrix_svd[:, dim*(i):dim*(i+1)] = Rk;\n\n #for the isolated node whose feature factor fulls Inf and NaN because of normalisation\n representation_matrix_svd[np.isnan(representation_matrix_svd)] = 0\n representation_matrix_svd[np.isinf(representation_matrix_svd)] = 0\n\n return representation_matrix_svd\n \n\n\n#generate representation matrix in case that the matrix is factorised with autoencoder \nrepresentation_matrix_autoencoder = np.zeros((nodes_num, step*dim))\ndef GetRepMat_autoencoder():\n for i in range(step):\n probTranMat = GetProbTranMat(k_transition_matrix[:,:,i])\n\n Rk = test_dA(learning_rate=0.1, training_epochs=500,\n probTranMat = probTranMat, n_visible=nodes_num, n_hidden=dim)\n Rk = np.asarray(Rk.eval(), dtype = np.float32)\n \n Rk = np.divide(Rk, np.repeat(np.sqrt(np.sum(np.power(Rk, 2), axis=1)).reshape(-1,1), dim, axis=1))\n representation_matrix_autoencoder[:, dim*(i):dim*(i+1)] = Rk;\n \n #for nodes whose feature factor consists Inf and NaN because of normalisation\n representation_matrix_autoencoder[np.isnan(representation_matrix_autoencoder)] = 0\n representation_matrix_autoencoder[np.isinf(representation_matrix_autoencoder)] = 0\n\n return representation_matrix_autoencoder\n \nrepresentation_matrix_svd = GetRepMat_svd()\nprint(\"\\nIn case of factorisation of matrix with SVD, the representation matrix is: \")\nprint(representation_matrix_svd)\n\n\nprint(\"\\nTraining autoencoder ... ... \")\nstart_time = time()\nrepresentation_matrix_autoencoder = GetRepMat_autoencoder()\n#Get the information about training process\nend_time = time()\nsec=end_time-start_time\nprint(\"The overall Training time: \"+str(strftime(\"%H:%M:%S\",gmtime(sec))))\n\nprint(\"\\nIn case of factorisation of matrix with autoencoder, the representation matrix is: \")\nprint(representation_matrix_autoencoder)\n\n\n#clustering with K-means algorithm\nprint(\"\\nClustering with Kmeans ... ... \")\nK_means = KMeans(n_clusters=num_clusters).fit(representation_matrix_autoencoder)\nprint(\"\\nThe indices of clusters, to which each node belongs.\")\nlabels = K_means.labels_\n\n\n#visualise the clustering result using TSNE tool\nmodel = TSNE(n_components=2, metric=\"cosine\")\nRep_2dim = model.fit_transform(representation_matrix_autoencoder)\nclusters = np.asarray([Rep_2dim[labels == k] for k in range(num_clusters) if np.any(Rep_2dim[labels == k])])\n\nplt.title(\"The visualisation the 3 clusters chosen randomly\")\ni=np.random.randint(num_clusters)\nplt.scatter(clusters[i][:, 0], clusters[i][:, 1], c='red')\ni=np.random.randint(num_clusters)\nplt.scatter(clusters[i][:, 0], clusters[i][:, 1], c='green')\ni=np.random.randint(num_clusters)\nplt.scatter(clusters[i][:, 0], clusters[i][:, 1], c='blue')\nplt.show()\n\n\n\n","sub_path":"GraRep.py","file_name":"GraRep.py","file_ext":"py","file_size_in_byte":7122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"387954818","text":"import requests\nimport json\nimport re\nimport pymongo\nfrom pyquery import PyQuery as pq\nfrom tools import MongoHelp as Mongo\nfrom tools import ProgressBar\nfrom decorators import Performance\n\nfrom multiprocessing.dummy import Pool as ThreadPool\n\nclass RMP(object):\n\n \"\"\"\n http://search.mtvnservices.com/typeahead/suggest/\n \"\"\"\n name = 'RMP'\n collection = 'UniversityAlberta'\n update_file = 'imports/import.json'\n export_file = 'exports/export.csv'\n performance = Performance(\"%m min, %s sec\")\n\n def __init__(self, host, port):\n self.host = host\n self.port = int(port)\n self.database = pymongo.MongoClient(self.host, self.port).get_database(RMP.name)\n self.collection = Mongo.fetch_collection(self.database, RMP.collection,\n force_collection=True)\n\n def _build_index(self):\n for field in RMP.fields.values():\n if field == 'pid':\n self.collection.create_index([(field, pymongo.ASCENDING)],\n unique=True)\n else:\n self.collection.create_index([(field, pymongo.ASCENDING)])\n\n def find_prof_via_pid(self, pid):\n q = {RMP.fields['pid']: pid}\n return self.collection.find_one(q, {'_id': 0})\n\n def find_profs_via_name(self, first_name, last_name):\n q = {RMP.fields['first_name']: first_name.lower(),\n RMP.fields['last_name']: last_name.lower()}\n return [x for x in self.collection.find(q, {'_id': 0})]\n\n @performance.summary\n @performance.logged(\"Update Database\")\n def update_database(self):\n \"\"\"\n Updates the RMP.UniversityAlberta Database. Note you should run rmp._update_extras() too.\n :return:\n \"\"\"\n self.collection = Mongo.fetch_collection(self.database, RMP.collection,\n ensure_new=True,\n force_collection=True)\n results = int(RMP.get_profs(n=1)['response']['numFound'])\n self._build_index()\n with open(RMP.update_file, mode='w') as f:\n # lazily assign a sufficientley high number for n, we know that u of a will never have 10K profs lmao.\n for data in RMP.get_profs(n=results)['response']['docs']:\n data[RMP.fields['first_name']] = data[RMP.fields['first_name']].lower()\n data[RMP.fields['last_name']] = data[RMP.fields['last_name']].lower()\n f.write(json.dumps(data) + '\\n')\n Mongo.mongo_import(self.host, self.port, RMP.name, RMP.collection, RMP.update_file)\n\n fields = {'last_name': 'teacherlastname_t',\n 'first_name': 'teacherfirstname_t',\n 'num_ratings': 'total_number_of_ratings_i',\n 'average_score':'averageratingscore_rf',\n # 'school_id': 'schoolid_s',\n 'pid': 'pk_id'}\n\n @staticmethod\n def _sort_definition(field_name, order='desc'):\n if field_name not in RMP.fields.keys():\n raise AssertionError(\"%s is not a valid field\" % field_name)\n return '%s+%s' % (RMP.fields[field_name], order)\n\n @staticmethod\n def _return_fields(field_names):\n result = ''\n for field in field_names:\n result += RMP.fields[field] + '+'\n return result.strip('+')\n\n @staticmethod\n def get_profs(sort_field='num_ratings', order='desc', fields=None, n=10):\n\n if not fields:\n fields = RMP.fields.keys()\n\n query_fields = {'q': '*%3A*+AND+schoolid_s%3A1407',\n # Specifies how the data should be sorted. [data_field+('asc'|'desc')]\n 'sort': RMP._sort_definition(sort_field, order),\n 'siteName': 'rmp',\n # Specifies how many results to return [integer]\n 'rows': n,\n # Specifies which index it should start returning from [integer]\n 'start': 0,\n # Specifies the fields to return [data_field1+data_field2+...]\n 'fl': RMP._return_fields(fields)}\n\n # This is the parsed url from where we get prof rating data\n url = 'http://search.mtvnservices.com/typeahead/suggest/'\n return requests.get(url, params=query_fields).json()\n\n @staticmethod\n def get_prof_user_ratings(pid, max=3):\n\n query_fields = {'tid': pid,\n 'page': 0,\n 'max': max}\n\n url = 'http://www.ratemyprofessors.com/paginate/professors/ratings'\n response = requests.get(url, params=query_fields).json()\n return response['ratings']\n\n @staticmethod\n def get_prof_general_info(pid):\n query_fields = {'tid': pid,\n 'showMyProfs': True}\n url = 'http://www.ratemyprofessors.com/ShowRatings.jsp'\n response = requests.get(url, params=query_fields)\n p = pq(response.text)\n\n document = {RMP.fields['pid']: pid}\n\n result_title = p('.result-title')\n result_title.remove('a')\n document['role'] = result_title.text().replace('\\n\\n', ' ')\n\n info_section_left = p('.rating-breakdown .left-breakdown .breakdown-wrapper').find('.breakdown-header').eq(1)\n for i in info_section_left.items('.breakdown-section'):\n grade = i('.grade').remove()\n if 'Would Take Again' in i.text():\n field = 'approval'\n document[field] = grade.text()\n if 'Level of Difficulty' in i.text():\n field = 'difficulty'\n document[field] = grade.text()\n\n document['tags'] = {}\n\n info_section_right = p('.rating-breakdown .right-breakdown .tag-box')\n for i in info_section_right.items('span'):\n b = i('b').remove()\n document['tags'][i.text()] = int(re.search('[0-9]+', b.text()).group(0))\n\n print('.')\n return document\n\n @performance.summary\n @performance.logged(\"Update Extras\")\n def _update_extras(self):\n open(RMP.export_file, mode='w').close()\n Mongo.mongo_export(self.host, self.port, RMP.name, RMP.collection, RMP.export_file,\n filetype='csv',\n fields=[RMP.fields['pid']])\n with open(RMP.export_file, mode='r') as f:\n tasks = [int(x.strip('\\n')) for x in f.readlines()]\n pool = ThreadPool(13)\n\n results = pool.map(RMP.get_prof_general_info, tasks)\n\n pool.close()\n pool.join()\n\n with open(RMP.update_file, mode='w') as f:\n for document in results:\n f.write(json.dumps(document) + '\\n')\n\n Mongo.mongo_import(self.host, self.port, RMP.name, RMP.collection, RMP.update_file,\n mode='merge',\n upsertFields=[RMP.fields['pid']])\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n rmp = RMP('localhost', 27017)\n # print (rmp.get_profs())\n rmp.update_database()\n # # print(rmp.find_prof_via_pid(11935))\n # # print(rmp.get_prof_general_info(11935))\n print(rmp._update_extras())","sub_path":"RateMyProf.py","file_name":"RateMyProf.py","file_ext":"py","file_size_in_byte":7212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"244336800","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# pip install Pillow\n\nfrom PIL import Image, ImageDraw, ImageFont\n\nif __name__ == '__main__':\n img = Image.open('avatar.jpg')\n font = ImageFont.truetype('simsun.ttc', 30)\n draw = ImageDraw.Draw(img)\n draw.text((img.size[1]-20, 10), '4', font=font, fill=(255,0,0,255))\n del draw, font\n img.save('copy.jpg', quality=80)\n img.close()\n","sub_path":"src/0000/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"630926272","text":"import numpy as np\nimport cube\n\nBLACK = (0, 0, 0)\nWHITE = (255, 255, 255)\nBLUE = (0, 0, 255)\nGREEN = (0, 255, 0)\nRED = (255, 0, 0)\nYELLOW = (255, 255, 0)\nORANGE = (255, 153, 0)\nBROWN = (153, 51, 0)\nAQUA = (0, 255, 255)\nLIGHT_GREY = (128, 127, 127)\n\nclass Snail():\n\n def __init__(self, origin, rotation=None):\n\n self.origin = np.array(origin)\n if rotation == None:\n rotation = [0, 0, 0]\n self.rotation = np.array(rotation)\n self.connections = {0:[1,2,5],1:[0,3], 2:[0,4], 3:[1], 4:[2], 5:[0]}\n self.create_cubes()\n\n def create_cubes(self):\n self.cubes = []\n \n head_position = cube.rotate_vector(np.array([0,-100,0]), self.rotation)\n head = cube.Cube(40, self.origin + head_position, GREEN, self.rotation)\n self.cubes.append(head)\n \n eye_holder_1_position = cube.rotate_vector(np.array([32, -132, 60]), self.rotation)\n eye_holder_1 = cube.Cuboid(16, 16, 40, self.origin + eye_holder_1_position, GREEN, self.rotation)\n self.cubes.append(eye_holder_1)\n \n eye_holder_2_position = cube.rotate_vector(np.array([-32, -132, 60]), self.rotation)\n eye_holder_2 = cube.Cuboid(16, 16, 40, self.origin + eye_holder_2_position, GREEN, self.rotation)\n self.cubes.append(eye_holder_2)\n \n eye_1_position = cube.rotate_vector(np.array([32, -132, 100]), self.rotation)\n eye_1 = cube.Cube(20, self.origin + eye_1_position, LIGHT_GREY, self.rotation)\n self.cubes.append(eye_1)\n\n eye_2_position = cube.rotate_vector(np.array([-32, -132, 100]), self.rotation)\n eye_2 = cube.Cube(20, self.origin + eye_2_position, LIGHT_GREY, self.rotation)\n self.cubes.append(eye_2)\n\n shell_position = cube.rotate_vector(np.array([0, 40, 60]), self.rotation)\n shell = cube.Cuboid(120, 200, 200, self.origin + shell_position, ORANGE, self.rotation)\n self.cubes.append(shell)\n\n def return_sides(self):\n cubes_sides = []\n for cube in self.cubes:\n cubes_sides.append(cube.return_sides())\n \n return cubes_sides\n\n def return_cubes(self, screen_position):\n furthest_cubes = []\n furthest_distance = 0\n for cube in range(len(self.cubes)):\n furthest_point, closest_point = self.cubes[cube].return_landmark_points(screen_position)\n point_to_screen = screen_position - self.cubes[cube].points[furthest_point]\n distance = np.sqrt(point_to_screen.dot(point_to_screen))\n if distance == furthest_distance:\n furthest_cubes.append(cube)\n if distance > furthest_distance:\n furthest_cubes = [cube]\n furthest_distance = distance\n\n current_cubes = furthest_cubes\n visited = furthest_cubes\n searching = True\n ordered_cubes = []\n while searching:\n print(current_cubes)\n available_connections = []\n #for each cube in current cubes:\n for cube in range(len(current_cubes)):\n #for each cube in the connected cubes:\n for connection in self.connections[cube]:\n if connection not in visited:\n available_connections.append(connection)\n visited.append(connection)\n if len(available_connections) == 0:\n searching = False\n break\n current_cubes = available_connections\n \n\n return self.cubes\n \"\"\"\n ordered_cubes = []\n cubes_magnitudes = {}\n for current_cube in self.cubes:\n furthest_point, closest_point = current_cube.return_landmark_points(screen_position)\n cube_to_screen = screen_position - furthest_point\n magnitude = np.sqrt(cube_to_screen.dot(cube_to_screen))\n cubes_magnitudes[current_cube] = magnitude\n for cube in sorted(cubes_magnitudes, key=cubes_magnitudes.get, reverse=False):\n ordered_cubes.append(cube)\n\n return ordered_cubes\n \"\"\"\n\n def update(self):\n self.create_cubes()\n\n def rotate(self, rotation):\n self.rotation[0] = (self.rotation[0] + rotation[0]) % 360\n self.rotation[1] = (self.rotation[1] + rotation[1]) % 360\n self.rotation[2] = (self.rotation[2] + rotation[2]) % 360\n self.update()\n \n\n\n \n","sub_path":"characters.py","file_name":"characters.py","file_ext":"py","file_size_in_byte":4428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"496484352","text":"import numpy\nfrom itertools import product, ifilterfalse\n\n\nclass StencilGrid(object):\n \"\"\"\n A two-dimension grid of numeric values, used for input and output to a\n stencil kernel.\n \"\"\"\n\n def __init__(self, shape, dtype=numpy.float32, data=None, neighbors=None):\n \"\"\"__init__\n\n :param shape: the shape of the StencilGrid, e.g. `(1024, 1024)`\n :type shape: int or sequence of ints\n \"\"\"\n self.dim = len(shape)\n if data is not None:\n self.data = data\n else:\n self.data = numpy.zeros(shape, dtype=dtype)\n\n self.shape = shape\n self.ghost_depth = 1\n self.grid_variables = []\n self.interior = []\n\n self.set_grid_variables()\n self.set_interior()\n # add default neighbor definition\n if neighbors is not None:\n # TODO: Check validity of neighbor defn\n self.neighbor_definition = neighbors\n else:\n self.set_default_neighbor_definitions()\n self.corner_points = None\n self.edge_points = None\n self.make_corner_points_iterator()\n self.make_edge_points_iterator()\n\n # import types\n #\n # code = [\"def corner_points(self):\"]\n # for dimension_index in range(self.dim):\n # for each_dimension in range(self.dim):\n # if each_dimension == dimension_index:\n # code.append(\n # \"%sfor d%s in [0,%d]:\" %\n # (' '*4*(each_dimension+1), each_dimension, self.shape[each_dimension])\n # )\n # else:\n # code.append(\n # \"%sfor d%s in range(%d):\" %\n # (' '*4*(each_dimension+1), each_dimension, self.shape[each_dimension])\n # )\n # code.append(\"%syield (%s)\" % (' '*4*(self.dim+1), \",\".join(map(lambda x: \"d%d\" % x, range(self.dim)))))\n # for line in code:\n # print(line)\n # exec('\\n'.join(code))\n # self.corner_points = types.MethodType(corner_points, self)\n\n # want this to be indexable\n def __getitem__(self, x):\n \"\"\"__getitem__\n\n :param x: The index of the StencilGrid to return. Equivalent to indexing\n a numpy array.\n :type x: int\n \"\"\"\n return self.data[x]\n\n def __setitem__(self, x, y):\n \"\"\"__setitem__\n\n :param x: The index of the StencilGrid to set. Equivalent to setting a\n numpy array.\n :type x: int\n :param y: The value to set at index `x`.\n :type y: `self.data.dtype`\n \"\"\"\n self.data[x] = y\n\n def set_grid_variables(self):\n self.grid_variables = [\"DIM\"+str(x) for x in range(0, self.dim)]\n\n def set_interior(self):\n \"\"\"\n Sets the number of interior points in each dimension\n \"\"\"\n self.interior = [x-2*self.ghost_depth for x in self.shape]\n\n def set_neighborhood(self, neighborhood_id, coordinate_list):\n \"\"\"\n a grid can one or more notions of a neighborhood of a given grid point\n neighborhood_id is an integer identifier of the neighborhood\n coordinate_list is a list of tuples appropriate to the shape of the grid\n \"\"\"\n for coordinate in coordinate_list:\n assert len(coordinate) == self.dim, \"neighborhood coordinates must be of proper dimension\"\n\n while len(self.neighbor_definition) <= neighborhood_id:\n self.neighbor_definition.append([])\n self.neighbor_definition[neighborhood_id] = coordinate_list\n\n def von_neuman_neighborhood(self):\n \"\"\"\n create a neighborhood of all adjacent points along\n coordinate axes, suitable for the dimension of this instance\n \"\"\"\n neighborhood = []\n origin = [0 for _ in range(self.dim)]\n for dimension in range(self.dim):\n for offset in [-1, 1]:\n point = origin[:]\n point[dimension] = offset\n neighborhood.append(tuple(point))\n\n return neighborhood\n\n def moore_neighborhood(self, include_origin=False):\n \"\"\"\n create a neighborhood of all adjacent points along\n coordinate axes\n \"\"\"\n\n neighborhood_list = []\n\n def dimension_iterator(dimension, point_accumulator):\n \"\"\"\n accumulates into local neighborhood_list\n \"\"\"\n if dimension >= self.dim:\n if include_origin or sum([abs(x) for x in point_accumulator]) != 0:\n neighborhood_list.append(tuple(point_accumulator))\n else:\n for dimension_coordinate in [-1, 0, 1]:\n new_point_accumulator = point_accumulator[:]\n new_point_accumulator.append(dimension_coordinate)\n dimension_iterator(\n dimension+1,\n new_point_accumulator\n )\n\n dimension_iterator(0, [])\n\n return neighborhood_list\n\n def set_default_neighbor_definitions(self):\n \"\"\"\n Sets the default for neighbors[0] and neighbors[1]. Note that neighbors[1]\n does not include the center point.\n \"\"\"\n self.neighbor_definition = []\n\n zero_point = tuple([0 for _ in range(self.dim)])\n self.neighbor_definition.append([zero_point])\n self.neighbor_definition.append(self.von_neuman_neighborhood())\n\n def interior_points(self):\n \"\"\"\n Iterator over the interior points of the grid. Only executed\n in pure Python mode; in SEJITS mode, it should be executed only\n in the translated language/library.\n \"\"\"\n import itertools\n all_dims = [range(self.ghost_depth, self.shape[x]-self.ghost_depth) for x in range(0, self.dim)]\n for item in itertools.product(*all_dims):\n yield tuple(item)\n\n def make_edge_points_iterator(self):\n \"\"\"\n creates an iterator for edge points of the stencil. This is done by dynamically compiling code\n because it is difficult to create an iterator for the nesting of for loops over and arbitrary\n shape of the grid. Edge points are defined to be for each dimension the scalar values of the\n corner points in that dimension combined with the iteration of all scalars from the other dimensions\n omitting their corner values\n \"\"\"\n import types\n\n edge_points = None\n code = [\n \"def edge_points(self):\",\n \" seen = set()\",\n \" rejected = 0\",\n ]\n for dimension_index in range(self.dim):\n for each_dimension in range(self.dim):\n if each_dimension == dimension_index:\n border_points = range(self.ghost_depth) + \\\n range(self.shape[each_dimension]-self.ghost_depth, self.shape[each_dimension])\n code.append(\"%sfor d%s in [%s]:\" %\n (\n ' '*4*(each_dimension+1),\n each_dimension,\n ','.join(map(lambda x: \"%d\" % x, border_points))\n )\n )\n elif (each_dimension - 1 + self.dim) % self.dim == dimension_index:\n border_points = range(self.ghost_depth, self.shape[each_dimension]-self.ghost_depth)\n code.append(\"%sfor d%s in [%s]:\" %\n (\n ' '*4*(each_dimension+1),\n each_dimension,\n ','.join(map(lambda x: \"%d\" % x, border_points))\n )\n )\n else:\n code.append(\"%sfor d%s in range(%s):\" %\n (\n ' '*4*(each_dimension+1),\n each_dimension,\n self.shape[each_dimension]\n )\n )\n code.append(\"%spoint = (%s)\" % (' '*4*(self.dim+1), \",\".join(map(lambda x: \"d%d\" % x, range(self.dim)))))\n code.append(\"%sif not seen.__contains__(point):\" % (' '*4*(self.dim+1)))\n code.append(\"%sseen.add(point)\" % (' '*4*(self.dim+2)))\n code.append(\"%syield point\" % (' '*4*(self.dim+2)))\n # uncomment out below to see how many points rejected as already seen\n # code.append(\"%selse:\" % (' '*4*(self.dim+1)))\n # code.append(\"%srejected += 1\" % (' '*4*(self.dim+2)))\n # code.append(' print \"rejected %d points\" % rejected' )\n\n # uncomment to see generated code\n # for line in code:\n # print(line)\n exec('\\n'.join(code))\n self.edge_points = types.MethodType(edge_points, self)\n\n def make_corner_points_iterator(self):\n \"\"\"\n creates an iterator for border points of the stencil. This is done by dynamically compiling code\n because it is difficult to create an iterator for the nesting of for loops over and arbitrary\n shape of the grid. Border points are defined to be iteration over all points within ghost_depth\n of the min and max values of each dimension\n \"\"\"\n import types\n\n corner_points = None\n code = [\"def corner_points(self):\"]\n for each_dimension in range(self.dim):\n border_points = range(self.ghost_depth) + \\\n range(self.shape[each_dimension]-self.ghost_depth, self.shape[each_dimension])\n code.append(\"%sfor d%s in [%s]:\" %\n (\n ' '*4*(each_dimension+1),\n each_dimension,\n ','.join(map(lambda x: \"%d\" % x, border_points))\n )\n )\n code.append(\"%syield (%s)\" % (' '*4*(self.dim+1), \",\".join(map(lambda x: \"d%d\" % x, range(self.dim)))))\n # for line in code:\n # print(line)\n exec('\\n'.join(code))\n self.corner_points = types.MethodType(corner_points, self)\n\n def border_points(self):\n \"\"\"\n Iterator over the border points of a grid. Only executed in pure Python\n mode; in SEJITS mode, it should be executed only in the translated\n language/library.\n\n Border points are the sequential iteration of all corner points\n followed by all edge points\n Note: boundary points is slightly faster but\n \"\"\"\n\n for point in self.corner_points():\n yield point\n for point in self.edge_points():\n yield point\n\n def boundary_points(self):\n \"\"\"\n different technique using itertools to compute boundary points of a grid\n This method does not work if ghost_depth is != 1\n \"\"\"\n assert self.ghost_depth == 1, \"ghost depth not 1, use border points instead\"\n dims = map(lambda x: (0, x-1), self.shape)\n seen = set()\n # rejected = 0\n ranges = [xrange(lb, ub+1) for lb, ub in dims]\n for i, dim in enumerate(dims):\n for bound in dim:\n spec = ranges[:i] + [[bound]] + ranges[i+1:]\n for pt in ifilterfalse(seen.__contains__, product(*spec)):\n seen.add(pt)\n yield pt\n # commented out code equivalent to above but tracks dups\n # for pt in product(*spec):\n # if not seen.__contains__(pt):\n # seen.add(pt)\n # yield pt\n # else:\n # rejected += 1\n # print \"boundary points rejected %d\" % rejected\n\n def neighbors(self, center, neighbors_id):\n \"\"\"\n Returns the list of neighbors with the given neighbors_id. By\n default, IDs 0 and 1 give the list consisting of all\n points at a distance of 0 and 1 from the center point,\n respectively. Uses neighbor_definition to determine what the\n neighbors are.\n \"\"\"\n # import pprint\n # print( \"neighbors_id %s\" % neighbors_id )\n # pprint.pprint(self.neighbor_definition)\n # return tuples for each neighbor\n for neighbor in self.neighbor_definition[neighbors_id]:\n yield tuple(map(lambda a, b: a+b, list(center), list(neighbor)))\n\n def __repr__(self):\n return self.data.__repr__()\n","sub_path":"stencil_code/stencil_grid.py","file_name":"stencil_grid.py","file_ext":"py","file_size_in_byte":12649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"178257044","text":"import os\nimport pandas as pd\nfrom PIL import Image, ImageFilter, ImageOps, ExifTags, ImageDraw\n\ndict_keys = (\"Marker1\", \"Marker2\", \"Marker3\", \"Marker4\", \"ColorLeft\", \"ColorRight\",\n \"GrayScaleRight\", \"GreyScaleLeft\", \"CircleTop\", \"CircleRight\", \"CircleBottom\", \"CircleLeft\")\n\nmarkers = (\"Marker1\", \"Marker2\", \"Marker3\", \"Marker4\")\n\nimage_width = 224\nimage_height = 224\ncounter = 0\nsave_x_prefix = \"./dataset_mask_output/x/\"\nsave_y_prefix = \"./dataset_mask_output/y/\"\n\ndef generate_mask(im, row):\n mask = Image.new(\"RGB\", (image_width, image_height))\n d = ImageDraw.Draw(mask)\n for label in markers:\n point = eval(row[label])\n d.ellipse((point[0] * image_width - 10, point[1] * image_height - 10,\n point[0] * image_width + 10, point[1] * image_height + 10), fill='red', outline='red')\n\n color_left_point = eval(row[\"ColorLeft\"])\n color_right_point = eval(row[\"ColorRight\"])\n grey_scale_left_point = eval(row[\"GrayScaleRight\"])\n grey_scale_right_point = eval(row[\"GreyScaleLeft\"])\n\n d.line([(color_left_point[0] * image_width, color_left_point[1] * image_height),\n (color_right_point[0] * image_width, color_right_point[1] * image_height)], fill=\"green\", width=4)\n d.line([(grey_scale_left_point[0] * image_width, grey_scale_left_point[1] * image_height),\n (grey_scale_right_point[0] * image_width, grey_scale_right_point[1] * image_height)], fill=\"blue\", width=4)\n\n mask.filter(ImageFilter.GaussianBlur(100))\n return mask\n\n\nfor i in range(len(os.listdir(\"./dataset_augmented\"))):\n dict_for_csv = {\"photoFullPath\": [], \"Marker1\": [], \"Marker2\": [], \"Marker3\": [], \"Marker4\": [],\n \"ColorLeft\": [], \"ColorRight\": [], \"GrayScaleRight\": [], \"GreyScaleLeft\": [],\n \"CircleTop\": [], \"CircleRight\": [], \"CircleBottom\": [], \"CircleLeft\": []}\n\n if not os.path.exists(save_x_prefix):\n os.makedirs(save_x_prefix)\n\n if not os.path.exists(save_y_prefix):\n os.makedirs(save_y_prefix)\n\n data = pd.read_csv(\"./dataset_augmented/data{}/labeled_data.csv\".format(i), sep=\"|\")\n\n for index, row in data.iterrows():\n file = row[\"photoFullPath\"]\n im = Image.open(\"./dataset_augmented/data{}/source_to_label/\".format(i) + file)\n im.save(save_x_prefix + str(counter) + \".jpg\")\n mask = generate_mask(im, row)\n mask.save(save_y_prefix + str(counter) + \".jpg\")\n counter += 1\n","sub_path":"tools/generate_output_mask.py","file_name":"generate_output_mask.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"643259457","text":"import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport math\ndata = pd.read_csv('mainbasket_vsmsatufitur.csv', index_col=0, encoding=\"utf-8\", sep=',')\nlist_fitur=data.keys().to_list()\n\nw=[]\nfor i in list_fitur:\n\n a=data[i].value_counts()\n a=float(len(list_fitur)-a[0])\n #temp=math.log((len(list_fitur)-1)/(a))\n temp = math.log(len(list_fitur) / (a)) + 1\n w.append(temp)\n\nprint (data.head())\ncount=0\nfor i in range(len(list_fitur)):\n temp=list_fitur[i]\n data[temp]*=w[i]\nprint (data.head())\n\ndata.to_csv('baru_tfidf.csv')\n","sub_path":"mianbasket_tfidf.py","file_name":"mianbasket_tfidf.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"487363715","text":"from typing import List\n'''\n给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。\n\n你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。\n'''\n\n\nclass Solution:\n @staticmethod\n def two_sum(self, nums: List[int], target: int) -> List[int]:\n result = list()\n for n in nums:\n other_num = target - n\n first_index = nums.index(n)\n if other_num in nums[first_index + 1:]:\n two_index = nums[first_index + 1:].index(other_num)\n result.append(first_index)\n result.append(two_index + 1 + first_index)\n break\n return result\n\n # 换成字典的形式来计算,时间复杂度减少,但是空间复杂度增加\n @staticmethod\n def two_num_dict(self, nums: List[int], target: int) -> List[int]:\n hashmap = dict()\n for index, num in enumerate(nums):\n if target - num in hashmap:\n return [hashmap[target - num], index]\n hashmap[num] = index\n\n\nif __name__ == '__main__':\n solution = Solution()\n result_list = solution.two_sum(nums=[2, 7, 2, 7], target=9)\n print(result_list)\n","sub_path":"easy/two_sum.py","file_name":"two_sum.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"522293756","text":"# -*- coding: utf-8 -*-\n\nu\"\"\"\n基本操作\n\"\"\"\n\nimport os\nimport sys\nimport traceback\nimport wx\nimport chardet\nimport urllib\nimport re\nimport threading\n\nif os.name == \"posix\" and sys.platform != \"darwin\":\n # Linux\n import pynotify\n\nfrom icons import ICONS, ICONS2, ICONS_ICO\n\ndef GetMondrianData(i=0, fn=None):\n if not fn:\n idx = i if 0 <= i < len(ICONS) else 0\n return ICONS_ICO[idx]\n else:\n return ICONS2[fn]\n\n\ndef GetMondrianBitmap(i=0, fn=None):\n return wx.BitmapFromImage(GetMondrianImage(i, fn))\n\n\ndef GetMondrianImage(i=0, fn=None):\n import cStringIO\n\n stream = cStringIO.StringIO(GetMondrianData(i, fn))\n return wx.ImageFromStream(stream)\n\n\ndef GetMondrianIcon(i=0, fn=None):\n icon = wx.EmptyIcon()\n icon.CopyFromBitmap(GetMondrianBitmap(i, fn))\n return icon\n\ndef notify(frame, msg=\"\", title=u\"消息\"):\n\n if os.name == \"posix\" and sys.platform != \"darwin\":\n # linux 系统\n\n pynotify.Notification(title, msg).show()\n\n return\n\n import ToasterBox as TB\n\n sw, sh = wx.GetDisplaySize()\n width, height = 210, 50\n px = sw - 230\n py = sh - 100\n\n tb = TB.ToasterBox(frame)\n tb.SetPopupText(msg)\n tb.SetPopupSize((width, height))\n tb.SetPopupPosition((px, py))\n tb.Play()\n\n frame.SetFocus()\n\n\ndef switchHost(obj, fn):\n u\"\"\"切换 hosts 为 fn 的内容\"\"\"\n\n from cls_Hosts import Hosts\n\n if not os.path.isfile(fn):\n wx.MessageBox(u\"hosts 文件 '%s' 不存在!\" % fn, \"Error!\")\n\n ohosts = Hosts(path=fn)\n\n sys_hosts_fn = getSysHostsPath()\n try:\n a = open(fn, \"rb\").read().split(\"\\n\")\n a = [ln.rstrip() for ln in a]\n open(sys_hosts_fn, \"wb\").write(os.linesep.join(a))\n obj.current_hosts = fn\n title = ohosts.getTitle()\n\n obj.SetIcon(GetMondrianIcon(), \"Hosts: %s\" % title)\n notify(obj.frame, u\"Hosts 已切换为 %s。\" % title)\n\n ohosts = obj.frame.getOHostsFromFn(fn)\n obj.SetIcon(GetMondrianIcon(ohosts.icon_idx), u\"当前 hosts 方案:%s\" % ohosts.getTitle())\n obj.frame.SetIcon(GetMondrianIcon(ohosts.icon_idx))\n obj.frame.current_use_hosts_index = ohosts.index\n\n\n except Exception:\n print(traceback.format_exc())\n wx.MessageBox(u\"hosts 未能成功切换!\", \"Error!\")\n\n\ndef getSysHostsPath():\n u\"\"\"取得系统 host 文件的路径\"\"\"\n\n if os.name == \"nt\":\n path = \"C:\\\\Windows\\\\System32\\\\drivers\\\\etc\\\\hosts\"\n else:\n path = \"/etc/hosts\"\n\n return path if os.path.isfile(path) else None\n\n\ndef encode(s):\n\n# print(\"--\")\n# print(chardet.detect(s))\n return unicode(s).encode(\"UTF-8\") if s else \"\"\n\n\ndef decode(s):\n\n if not s:\n return \"\"\n\n cd = {}\n try:\n cd = chardet.detect(s)\n except Exception:\n# print(traceback.format_exc())\n pass\n\n encoding = cd.get(\"encoding\") if cd.get(\"confidence\", 0) > 0.65 else None\n if not encoding:\n encoding = \"GB18030\" if os.name == \"nt\" else \"UTF-8\"\n# print s, cd, encoding, s.decode(encoding)\n\n return s.decode(encoding)\n\n\ndef checkLatestStableVersion(obj):\n\n def _f(obj):\n url = \"https://github.com/oldj/SwitchHosts/blob/master/README.md\"\n ver = None\n\n try:\n c = urllib.urlopen(url).read()\n v = re.search(r\"\\bLatest Stable:\\s?(?P[\\d\\.]+)\\b\", c)\n if v:\n ver = v.group(\"version\")\n\n except Exception:\n pass\n\n obj.setLatestStableVersion(ver)\n\n return ver\n\n t = threading.Thread(target=_f, args=(obj,))\n t.setDaemon(True)\n t.start()\n","sub_path":"src/libs/common_operations.py","file_name":"common_operations.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"468364694","text":"from copy import (copy, deepcopy)\n\nimport cairocffi as cairo\nimport numpy as np\n\nfrom sketch.drawing.geometry import (\n rotation_matrix,\n scaling_matrix,\n translation_matrix\n)\nfrom sketch.drawing.surfaces import Surface\n\n\nclass Element:\n \"\"\"\n Base class for objects that can be transformed (rotated, translated, scaled)\n and drawn to a Surface.\n\n Parameter `draw_method` is a function which takes a cairo.Surface.Context()\n as argument and draws on this context. All Elements are draw on a different\n context.\n \"\"\"\n\n def __init__(self, draw_method):\n self.draw_method = draw_method\n self.matrix = 1.0 * np.eye(3)\n\n def _cairo_matrix(self):\n \"\"\" returns the element's matrix in cairo form \"\"\"\n m = self.matrix\n return cairo.Matrix(m[0, 0], m[1, 0],\n m[0, 1], m[1, 1],\n m[0, 2], m[1, 2])\n\n def _transform_ctx(self, ctx):\n \"\"\" Tranform the context before drawing.\n It applies all the rotation, translation, etc. to the context.\n In short, it sets the context's matrix to the element's matrix.\n \"\"\"\n ctx.set_matrix(self._cairo_matrix())\n\n def draw(self, surface):\n \"\"\" Draws the Element on a new context of the given Surface \"\"\"\n ctx = surface.get_new_context()\n self._transform_ctx(ctx)\n self.draw_method(ctx)\n\n def set_matrix(self, new_mat):\n \"\"\" Returns a copy of the element, with a new transformation matrix \"\"\"\n new = deepcopy(self)\n new.matrix = new_mat\n return new\n\n def rotate(self, angle, center=[0, 0]):\n \"\"\" Rotate the element.\n\n Returns a new element obtained by rotating the current element\n by the given `angle` (unit: rad) around the `center`.\n \"\"\"\n\n center = np.array(center)\n mat = (translation_matrix(center)\n .dot(rotation_matrix(angle))\n .dot(translation_matrix(-center)))\n\n return self.set_matrix(mat.dot(self.matrix))\n\n def translate(self, xy):\n \"\"\" Translate the element.\n\n Returns a new element obtained by translating the current element\n by a vector xy\n \"\"\"\n return self.set_matrix(translation_matrix(xy).dot(self.matrix))\n\n def scale(self, rx, ry=None, center=[0, 0]):\n \"\"\" Scale the element.\n\n Returns a new element obtained by scaling the current element\n by a factor rx horizontally and ry vertically, with fix point `center`.\n If ry is not provided it is assumed that rx=ry.\n \"\"\"\n\n ry = rx if (ry is None) else ry\n center = np.array(center)\n mat = (translation_matrix(center)\n .dot(scaling_matrix(rx, ry))\n .dot(translation_matrix(-center)))\n return self.set_matrix(mat.dot(self.matrix))\n\n\nclass Group(Element):\n \"\"\"\n Class for special Elements made out of a group of other elements which\n will be translated, scaled, rotated, and drawn together.\n These elements can be base elements (circles, squares) or even groups.\n \"\"\"\n\n def __init__(self, elements):\n self.elements = elements\n self.matrix = 1.0 * np.eye(3)\n\n def draw(self, surface):\n \"\"\" Draws the group to a new context of the given Surface \"\"\"\n\n for e in self.elements:\n m = self.matrix\n mi = np.linalg.inv(m)\n new_matrix = m.dot(e.matrix)\n e.set_matrix(new_matrix).draw(surface)\n\n\nclass ImagePattern(Element):\n \"\"\" Class for images that will be used to fill an element or its contour.\n\n image\n A numpy RGB(A) image.\n pixel_zero\n The coordinates of the pixel of the image that will serve as 0,0 origin\n when filling the element.\n\n filter\n Determines the method with which the images are resized:\n \"best\": slow but good quality\n \"nearest\": takes nearest pixel (can create artifacts)\n \"good\": Good and faster than \"best\"\n \"bilinear\": use linear interpolation\n \"fast\":fast filter, quality like 'nearest'\n\n extend\n Determines what happends outside the boundaries of the picture:\n \"none\", \"repeat\", \"reflect\", \"pad\" (pad= use pixel closest from source)\n\n \"\"\"\n\n def __init__(self, image, pixel_zero=[0, 0], filter=\"best\", extend=\"none\"):\n if isinstance(image, Surface):\n self._cairo_surface = image\n else:\n self._cairo_surface = Surface.from_image(image)._cairo_surface\n self.matrix = translation_matrix(pixel_zero)\n self.filter = filter\n self.extend = extend\n\n def set_matrix(self, new_mat):\n \"\"\" Returns a copy of the element, with a new transformation matrix \"\"\"\n new = copy(self)\n new.matrix = new_mat\n return new\n\n def make_cairo_pattern(self):\n pat = cairo.SurfacePattern(self._cairo_surface)\n pat.set_filter({\"best\": cairo.FILTER_BEST,\n \"nearest\": cairo.FILTER_NEAREST,\n \"gaussian\": cairo.FILTER_GAUSSIAN,\n \"good\": cairo.FILTER_GOOD,\n \"bilinear\": cairo.FILTER_BILINEAR,\n \"fast\": cairo.FILTER_FAST}[self.filter])\n\n pat.set_extend({\"none\": cairo.EXTEND_NONE,\n \"repeat\": cairo.EXTEND_REPEAT,\n \"reflect\": cairo.EXTEND_REFLECT,\n \"pad\": cairo.EXTEND_PAD}[self.extend])\n\n pat.set_matrix(self._cairo_matrix())\n\n return pat\n\n\nfor meth in [\"scale\", \"rotate\", \"translate\", \"_cairo_matrix\"]:\n exec(\"ImagePattern.%s = Element.%s\" % (meth, meth))\n","sub_path":"sketch/drawing/elements.py","file_name":"elements.py","file_ext":"py","file_size_in_byte":5650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"408561102","text":"\"\"\"stac-fastapi sqlalchemy submodule.\"\"\"\nimport os\nfrom glob import glob\nfrom imp import load_source\nfrom os.path import basename, splitext\n\nfrom setuptools import find_namespace_packages, setup\n\nname = \"stac-sqlalchemy-sqlalchemy\"\ndescription = \"Sqlalchemy subpackage of fastapi-stac, contains a postgres backend implementation using sqlalchemy.\"\n\n__version__ = load_source(\n \"stac_fastapi.sqlalchemy.version\",\n os.path.join(os.path.dirname(__file__), \"stac_fastapi/sqlalchemy/version.py\"),\n).__version__ # type:ignore\n\ninstall_requires = [\n \"stac-fastapi-types\",\n \"sqlakeyset\",\n \"geoalchemy2<0.8.0\",\n \"sqlalchemy==1.3.23\",\n \"shapely\",\n \"psycopg2-binary\",\n]\n\nwith open(\n os.path.join(os.path.abspath(os.path.dirname(__file__)), \"README.md\")\n) as readme_file:\n readme = readme_file.read()\n\nsetup(\n name=name,\n description=description,\n version=__version__,\n long_description=readme,\n long_description_content_type=\"text/markdown\",\n author=u\"Arturo Engineering\",\n author_email=\"engineering@arturo.ai\",\n url=\"https://github.com/stac-utils/stac-fastapi.git\",\n packages=find_namespace_packages(),\n py_modules=[splitext(basename(path))[0] for path in glob(\"stac_fastapi/*.py\")],\n include_package_data=False,\n install_requires=install_requires,\n license=\"MIT\",\n keywords=[\"stac\", \"fastapi\", \"imagery\", \"raster\", \"catalog\", \"STAC\"],\n)\n","sub_path":"stac_fastapi_sqlalchemy/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"95038654","text":"from tkinter import *\nfrom datetime import datetime\nimport random\nimport re\nfrom tkinter import messagebox\nfrom tkinter.font import Font\nimport textwrap\nfrom main import chatbot_response\n\nroot = Tk()\nroot.config(bg=\"lightblue\")\nroot.geometry('410x600+400+100')\n\ncanvas = Canvas(root, width=500, height=400,bg=\"white\")\ncanvas.grid(row=0,column=0,columnspan=2)\ncanvas.place(x=10, y=10, width=390, height=530)\n\ntexts = []\n\nclass TextBot:\n def __init__(self,master,message=\"\"):\n self.master = master\n self.frame = Frame(master,bg=\"light green\")\n self.i = self.master.create_window(10,450,window=self.frame, anchor=\"w\")\n Label(self.frame,text=\"You\", font=(\"Helvetica\", 11),bg=\"light green\").grid(row=0,column=1,sticky=\"w\",padx=5)\n Label(self.frame,text= datetime.now().strftime(\"%d-%m-%Y %X\"),font=(\"Helvetica\", 9),bg=\"light green\").grid(row=1,column=1,sticky=\"w\",padx=5)\n Label(self.frame, text=textwrap.fill(message, 25), font=(\"Helvetica\", 13),bg=\"light green\").grid(row=2, column=1,sticky=\"w\",padx=5,pady=3)\n root.update_idletasks()\n\nclass ReplyBot:\n def __init__(self,master,message=\"\"):\n self.master = master\n self.frame = Frame(master,bg=\"light blue\")\n self.i = self.master.create_window(10,400,window=self.frame, anchor=\"w\")\n Label(self.frame,text=\"eTA\", font=(\"Helvetica\", 11),bg=\"light blue\").grid(row=0,column=1,sticky=\"w\",padx=5)\n Label(self.frame,text= datetime.now().strftime(\"%d-%m-%Y %X\"),font=(\"Helvetica\", 9),bg=\"light blue\").grid(row=1,column=1,sticky=\"w\",padx=5)\n Label(self.frame, text=textwrap.fill(message, 25), font=(\"Helvetica\", 13),bg=\"light blue\").grid(row=2, column=1,sticky=\"w\",padx=5,pady=3)\n root.update_idletasks()\n\ndef send_message():\n if texts:\n x = len(texts[0]) // 25 * 30 + 100\n canvas.move(ALL, 0, -x)\n TextBot(canvas,message=ChatLog.get())\n msg = ChatLog.get()\n texts.append(msg)\n y = len(msg) // 25 * 50 + 150\n canvas.move(ALL, 0, -y)\n res = chatbot_response(msg)\n ReplyBot(canvas, message=res)\n texts.append(res)\n ChatLog.delete(0,'end')\n\n\nChatLog = Entry(root,width=26, font=(\"Helvetica\", 13))\nChatLog.place(x=10, y=550, width=290, height=40)\n\n\n#buton\nSendButton = Button(root, width=10, height=2,\nrelief='raised',state='active',command=send_message)\nSendButton.config(text='Send', bg='lightblue', font='Verdana 13')\nSendButton.place(x=310, y=550)\n\nroot.mainloop()","sub_path":"chatgui.py","file_name":"chatgui.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"377720329","text":"import time\nfrom lxml import html\nfrom selenium import webdriver\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport json\nfrom selenium.webdriver.chrome.options import Options\nfrom datetime import datetime\nimport numpy as np\n\nchrome_options = Options()\nchrome_options.add_argument(\"--headless\")\n#driver = webdriver.Chrome(chrome_options=chrome_options)\ndriver = webdriver.Chrome()\ndriver.get(\"https://www.flashscore.com\");\n\ndef collect_data(x):\n #predeclare\n hinjured = []\n ainjured = []\n homelastten = []\n awaylastten = []\n htoh = []\n upperstanding = []\n lowerstanding = []\n odd1 = 1\n odd2 = 1\n\n #scroll to the element\n element = driver.find_elements_by_xpath('//div[starts-with(@id, \"g_1\")]')[x]\n actions = ActionChains(driver)\n actions.move_to_element(element).perform()\n\n #click match\n driver.find_elements_by_xpath('//div[starts-with(@id, \"g_1\")]')[x].click()\n\n #switch to new tab\n handle = driver.window_handles\n time.sleep(2)\n driver.switch_to.window(handle[1])\n\n #get injuries\n source = driver.page_source\n tree = html.fromstring(source)\n hinjured = tree.xpath('//td[@class=\"summary-vertical fl\"]/div[@class=\"name\"]/a/text()')\n ainjured = tree.xpath('//td[@class=\"summary-vertical fr\"]/div[@class=\"name\"]/a/text()')\n\n try:\n #switch to h2h tab\n driver.find_element_by_xpath('//a[starts-with(@id, \"a-match-head-2-head\")]').click()\n time.sleep(2)\n\n source = driver.page_source\n tree = html.fromstring(source)\n\n #get last ten matches\n homelastten = tree.xpath('//table[@class=\"head_to_head h2h_home\"]/tbody/tr/td[@class=\"winLose\"]/span[@class=\"winLoseIcon\"]/a/@title')\n awaylastten = tree.xpath('//table[@class=\"head_to_head h2h_away\"]/tbody/tr/td[@class=\"winLose\"]/span[@class=\"winLoseIcon\"]/a/@title')\n\n #get goals\n goalresulthome = tree.xpath('//table[@class=\"head_to_head h2h_home\"]/tbody/tr/td/span[@class=\"score\"]/strong/text()')\n goalresultaway = tree.xpath('//table[@class=\"head_to_head h2h_away\"]/tbody/tr/td/span[@class=\"score\"]/strong/text()')\n goalresulthome = goalresulthome[:10]\n goalresultaway = goalresultaway[:10]\n\n home_goal_scored = []\n for x in goalresulthome:\n splitted = x.split(\":\")\n home_goal_scored.append(splitted[0])\n\n home_goal_taken = []\n for x in goalresulthome:\n splitted = x.split(\":\")\n home_goal_taken.append(splitted[1])\n\n away_goal_scored = []\n for x in goalresultaway:\n splitted = x.split(\":\")\n away_goal_scored.append(splitted[0])\n\n away_goal_taken = []\n for x in goalresultaway:\n splitted = x.split(\":\")\n away_goal_taken.append(splitted[1])\n\n home_goal_scored = np.array(home_goal_scored,dtype=int)\n home_goal_taken = np.array(home_goal_taken,dtype=int)\n away_goal_scored = np.array(away_goal_scored,dtype=int)\n away_goal_taken = np.array(away_goal_taken,dtype=int)\n\n home_goal_scored = sum(home_goal_scored)\n home_goal_taken = sum(home_goal_taken)\n away_goal_scored = sum(away_goal_scored)\n away_goal_taken = sum(away_goal_taken)\n\n #get HeadToHead\n htoh = tree.xpath('//table[@class=\"head_to_head h2h_mutual\"]/tbody/tr/td[@class=\"name\"]/span/strong/text()')\n except:\n pass\n\n try:\n #switch to standings tab\n driver.find_element_by_xpath('//a[starts-with(@id, \"a-match-standings\")]').click()\n time.sleep(2)\n\n source = driver.page_source\n tree = html.fromstring(source)\n\n #get home standing away standings\n standings = tree.xpath('//tr[@class[contains(., \"highlight\")]]/td[@class=\"participant_name col_participant_name col_name\"]/span[@class=\"team_name_span\"]/a/text()')\n positions = tree.xpath('//tr[@class[contains(., \"highlight\")]]/td[@class[contains(., \"rank\")]]/text()')\n\n upperstanding = [standings[0],positions[0]]\n lowerstanding = [standings[1],positions[1]]\n except:\n pass\n\n try:\n #get odds\n driver.find_element_by_xpath('//a[starts-with(@id, \"a-match-odds-comparison\")]').click()\n time.sleep(2)\n\n source = driver.page_source\n tree = html.fromstring(source)\n odd1 = tree.xpath('//td[@onclick[contains(., \"block-1x2_ft_1\")]]/span/text()')\n odd2 = tree.xpath('//td[@onclick[contains(., \"block-1x2_ft_2\")]]/span/text()')\n\n if odd1 == []:\n odd1 = 1\n else:\n odd1 = np.array(odd1,dtype=float)\n odd1 = sum(odd1) / float(len(odd1))\n odd1 = round(odd1, 2)\n\n if odd2 == []:\n odd2 = 1\n else:\n odd2 = np.array(odd2,dtype=float)\n odd2 = sum(odd2) / float(len(odd2))\n odd2 = round(odd2, 2)\n\n except:\n pass\n\n #close new tab, switch to original\n driver.close()\n driver.switch_to.window(handle[0])\n source = driver.page_source\n tree = html.fromstring(source)\n\n\n details={\n \"Home_Injured\" : hinjured,\n \"Away_Injured\" : ainjured,\n \"Home_Last_Ten_Match\" : homelastten[:10],\n \"Away_Last_Ten_Match\" : awaylastten[:10],\n \"HeadToHead\" : htoh[:5],\n \"Upper_Standing\" : upperstanding,\n \"Lower_Standing\" : lowerstanding,\n \"1_Odd\" : odd1,\n \"2_Odd\" : odd2,\n \"Home_goal_scored\" : home_goal_scored,\n \"Home_goal_taken\" : home_goal_taken,\n \"Away_goal_scored\" : away_goal_scored,\n \"Away_goal_taken\" : away_goal_taken\n }\n\n return details\n\ndef create_json():\n driver.find_element_by_xpath('//div[@class=\"cookie-law-exit-button cookie-law-accept\"]').click() #close cookie law\n time.sleep(5) # wait until page loading\n\n source = driver.page_source\n tree = html.fromstring(source)\n\n hometeam = tree.xpath('//div[starts-with(@class,\"event__participant event__participant--home\")]/text()')\n awayteam = tree.xpath('//div[starts-with(@class,\"event__participant event__participant--away\")]/text()')\n\n x=0\n output = []\n with open('matches_list.json', 'w') as outfile:\n for ht,at in zip(hometeam,awayteam):\n det = collect_data(x)\n match={\n \"Home_Team\" : ht,\n \"Away_Team\" : at,\n \"Home_Injured\" : det[\"Home_Injured\"],\n \"Away_Injured\" : det[\"Away_Injured\"],\n \"HeadToHead\" : det[\"HeadToHead\"],\n \"Upper_Standing\" : det[\"Upper_Standing\"],\n \"Lower_Standing\" : det[\"Lower_Standing\"],\n \"1_Odd\" : det[\"1_Odd\"],\n \"2_Odd\" : det[\"2_Odd\"],\n \"Home_goal_scored\" : det[\"Home_goal_scored\"],\n \"Home_goal_taken\" : det[\"Home_goal_taken\"],\n \"Away_goal_scored\" : det[\"Away_goal_scored\"],\n \"Away_goal_taken\" : det[\"Away_goal_taken\"]\n }\n x += 1\n if (len(det[\"Home_Last_Ten_Match\"]) == 10) and (len(det[\"Away_Last_Ten_Match\"]) == 10) and (len(det[\"HeadToHead\"]) > 1):\n output.append(match)\n json.dump(output, outfile, indent=4)\n\n driver.quit()\n","sub_path":"json_creator.py","file_name":"json_creator.py","file_ext":"py","file_size_in_byte":7218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"618703484","text":"import torch.nn as nn\nimport torch\nimport math\nfrom model.resnet_fsr import resnet18, resnet34, resnet50, resnet101\n\ndef channel_shuffle(x, groups):\n batchsize, num_channels, height, width = x.data.size()\n channels_per_group = num_channels // groups\n # reshape\n x = x.view(batchsize, groups,\n channels_per_group, height, width)\n x = torch.transpose(x, 1, 2).contiguous()\n # flatten\n x = x.view(batchsize, -1, height, width)\n return x\n\n\nclass FSR_SHUFFLE_MODULE_X2(nn.Module):\n def __init__(self, in_planes, out_planes, feat_trim, num_labels, groups=1):\n super(FSR_SHUFFLE_MODULE_X2, self).__init__()\n self.feat_trim = feat_trim\n self.num_labels = num_labels\n self.in_planes = in_planes\n self.out_planes = out_planes\n self.groups = groups\n\n self.up_sample1_1 = nn.UpsamplingBilinear2d(scale_factor=2)\n self.up_sample1_2 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)\n self.conv1 = nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=1, padding=1, bias=False, groups=groups)\n self.deconv1 = nn.ConvTranspose2d(out_planes, out_planes, kernel_size=4, stride=2, padding=1, groups=groups)\n self.relu = nn.ReLU(inplace=True)\n\n self.avgpool = nn.AdaptiveAvgPool2d(1)\n self.fc_all = nn.Linear(out_planes, num_labels)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def forward(self, x):\n upsampled_x = self.up_sample1_1(x)\n if self.in_planes != self.out_planes:\n upsampled_x = self.up_sample1_2(upsampled_x)\n residual_x1 = self.conv1(x)\n residual_x1 = self.relu(residual_x1)\n residual_x1 = channel_shuffle(residual_x1, self.groups)\n residual_x1 = self.deconv1(residual_x1)\n residual_x1 = channel_shuffle(residual_x1, self.groups)\n x1 = upsampled_x + residual_x1\n\n # cls\n N, C, H, W = x1.shape\n x1 = x1[:, :, self.feat_trim[0]:H-self.feat_trim[1], self.feat_trim[0]:W-self.feat_trim[1]]\n\n y = self.avgpool(x1)\n y = y.view(y.size(0), -1)\n y = self.fc_all(y)\n\n feature_map = x1.detach().clone()\n fc_weights = self.fc_all.weight.view(\n 1, self.num_labels, feature_map.shape[1], 1, 1) # 1 * L * C * 1 * 1\n feature = feature_map.unsqueeze(1) # N * 1 * C * H * W\n cams = (feature * fc_weights).sum(2) # N * L * H * W\n\n return y, x1, cams\n\n\nclass FSR_SHUFFLE_X2(nn.Module):\n def __init__(self, arch, in_planes, out_planes, feat_trim, num_labels, groups=1):\n super(FSR_SHUFFLE_X2, self).__init__()\n\n if arch == 'r101':\n self.base_model = resnet101(pretrained=True, num_labels=num_labels)\n elif arch == 'r50':\n self.base_model = resnet50(pretrained=True, num_labels=num_labels)\n elif arch == 'r34':\n self.base_model = resnet34(pretrained=True, num_labels=num_labels)\n elif arch == 'r18':\n self.base_model = resnet18(pretrained=True, num_labels=num_labels)\n self.fsr_model = FSR_SHUFFLE_MODULE_X2(in_planes, out_planes, feat_trim, num_labels, groups)\n\n def forward(self, x):\n base_cls, base_m_feat, base_f_feat = self.base_model(x)\n fsr_cls, fsr_feat, fsr_cam = self.fsr_model(base_f_feat)\n return base_cls, base_m_feat, base_f_feat, fsr_cls, fsr_feat, fsr_cam\n\n\nif __name__ == \"__main__\":\n from thop import profile\n\n fsr_kd_model = FSR_SHUFFLE_X2(arch='r34', in_planes=512, out_planes=2048, feat_trim=[0, 1], num_labels=80, groups=64)\n input = torch.randn(1, 3, 112, 112)\n flops, params = profile(fsr_kd_model, inputs=(input, ))\n print('flops: {}\\tparams: {}'.format(flops, params))\n # base_cls, base_m_feat, base_f_feature, fsr_cls, fsr_feat, fsr_cam = fsr_kd_model(input)\n\n","sub_path":"lib/model/fsr_kd_x2.py","file_name":"fsr_kd_x2.py","file_ext":"py","file_size_in_byte":4112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"552789863","text":"\nfrom collections import defaultdict\nfrom application.models.transaction import Transaction\nfrom application.models.group import Group\nfrom application.models.user_group import UserGroup\nfrom application.models.user import User\nimport json\nfrom flask import Blueprint, request, jsonify\nfrom application.models.expense import Expense\nfrom mongoengine.queryset.visitor import Q\nimport traceback\n\nfrom marshmallow import Schema, fields, ValidationError\n\nsimplify_bp = Blueprint('simplify', __name__, url_prefix='/api/v1/simplify')\n\n\ndef get_simplified_trans(transactions, user_id=None):\n sd = []\n debit = []\n credit = []\n members = defaultdict(lambda: 0)\n for transaction in transactions:\n members[str(transaction.payer.id)] -= transaction.amount\n members[str(transaction.payee.id)] += transaction.amount\n for m in members:\n j = {\n \"user\": m,\n \"amount\": abs(members[m])\n }\n if members[m] > 0:\n credit.append(j)\n else:\n debit.append(j)\n sd = []\n for c in credit:\n for d in debit:\n if c[\"amount\"] and d[\"amount\"]:\n p = {}\n if d[\"amount\"] > c[\"amount\"]:\n p[\"payer\"] = d[\"user\"]\n p[\"amount\"] = c[\"amount\"]\n p[\"payee\"] = c[\"user\"]\n c[\"amount\"] = 0\n d[\"amount\"] -= c[\"amount\"]\n else:\n p[\"payee\"] = d[\"user\"]\n p[\"amount\"] = d[\"amount\"]\n p[\"payer\"] = c[\"user\"]\n c[\"amount\"] -= d[\"amount\"]\n d[\"amount\"] = 0\n if user_id is not None:\n if p[\"payee\"] == user_id or p[\"payer\"] == user_id:\n sd.append(p)\n else:\n sd.append(p)\n return sd\n\n\n@simplify_bp.route('/', methods=['GET'])\ndef get_all_simplified_debts(group_id):\n try:\n all_transactions = Transaction.objects.all()\n sd = get_simplified_trans(transactions=all_transactions)\n return jsonify(\n isError=False,\n data=sd\n ), 200\n except Exception:\n err = traceback.format_exc()\n return jsonify(\n isError=True,\n data=err\n ), 500\n\n\n@ simplify_bp.route('//', methods=['GET'])\ndef get_user_simplified_debts(group_id, user_id):\n try:\n all_transactions = Transaction.objects().all()\n sd = get_simplified_trans(\n transactions=all_transactions, user_id=user_id)\n return jsonify(\n isError=False,\n data=sd\n ), 200\n except Exception:\n err = traceback.format_exc()\n return jsonify(\n isError=True,\n data=err\n ), 500\n","sub_path":"application/controllers/simplify.py","file_name":"simplify.py","file_ext":"py","file_size_in_byte":2851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"445226640","text":"import pytest\n\n\n@pytest.mark.asyncio\nasync def test_should_get_one(\n fake_service, fake_entity, repository, fake_fallback_data_entity\n):\n await repository.memory_data_source.delete('fake:fake2:fake')\n key = fake_service.repository.fallback_data_source.make_key(\n 'fake', 'fake2', 'fake'\n )\n await fake_service.repository.fallback_data_source.put(\n key, fake_fallback_data_entity\n )\n entity = await repository.query(\n fake_id=fake_entity.fake_id,\n fake2_id=fake_entity.fake2_id,\n latitude=5,\n longitude=6,\n max_distance=1,\n ).entity\n\n assert entity == fake_entity\n","sub_path":"dbdaora/geospatial/_tests/datastore/test_integration_service_geospatial_aioredis_datastore_get_one.py","file_name":"test_integration_service_geospatial_aioredis_datastore_get_one.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"170233307","text":"#!/usr/bin/env python3\n\nimport pprint\nfrom os.path import abspath\nfrom typing import Dict, Optional\n\nfrom pyspark.sql import SparkSession\n\n\nDEFAULT_SPARK_CONFIG = {\n \"spark.master\": \"local[1]\",\n \"spark.app.name\": \"ReAgent\",\n \"spark.sql.session.timeZone\": \"UTC\",\n \"spark.sql.warehouse.dir\": abspath(\"spark-warehouse\"),\n \"spark.sql.shuffle.partitions\": \"12\",\n}\n\n\ndef get_spark_session(config: Optional[Dict[str, str]] = DEFAULT_SPARK_CONFIG):\n print(\"Building with config: \")\n pprint.pprint(config)\n spark = SparkSession.builder.enableHiveSupport()\n if config is not None:\n for k, v in config.items():\n spark = spark.config(k, v)\n spark = spark.getOrCreate()\n spark.sparkContext.setLogLevel(\"ERROR\")\n return spark\n","sub_path":"reagent/workflow/spark_utils.py","file_name":"spark_utils.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"642596572","text":"import tweepy, json, pandas as pd, csv, joblib\nfrom sklearn.feature_extraction.text import CountVectorizer\n\napi_key = 'noY60ockEQUfjFdz1fS3b7ZeB'\napi_secret_key = 'itE8jzxQ8BXDmh4Le61m4fHgM90X3IfK1pf7URGQmxEOuYi6si'\naccess_token = '4316836098-ef4Nwfg8g49DSbFdcn7B2DpEXaMo9TBJAuqp3ya'\naccess_token_secret = '4E6ARa8DKqJktJ5rE0MakJ3u4Eg47gWovYIeajOyUgghm'\n \nauth = tweepy.OAuthHandler(api_key, api_secret_key)\nauth.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(auth)\ntweet = api.home_timeline()\n\nfor hashtag in [\"uscanada\", \"canadaus\", \"canadaandus\", \"usandcanada\"]:\n \n with open(\"US_Canada_Social_Media_Data.csv\", \"a+\", newline=\"\", encoding=\"utf-8\") as tw_data:\n \n wr = csv.writer(tw_data)\n \n for tweet in tweepy.Cursor(api.search, q = hashtag + ' -filter:retweets', lang=\"en\", tweet_mode='extended').items(1000):\n \n data, x = [], []\n for line in open('../Sentiment_Analysis/Streamed-Data.txt', \"r\"):\n try: data.append(json.loads(line))\n except: continue\n sent = pd.read_excel('../Sentiment_Analysis/Polarity-Sentiment.xlsx')\n for i in range(len(data)):\n if data[i]['id'] == sent['id'][i]: x.append(data[i]['text']);\n vectorizer = CountVectorizer(stop_words='english')\n vectorizer.fit_transform(x)\n \n svc = joblib.load('../Sentiment_Analysis/LinearSVC_Model.joblib')\n result = svc.predict(vectorizer.transform([tweet.full_text.replace('\\n',' ')]))[0]\n \n wr.writerow([result])","sub_path":"US_Canada/uscanada_data_pull.py","file_name":"uscanada_data_pull.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"556599879","text":"\nimport numpy as np\n\ndef power1(A,X,eps,max1):\n# function to compute the maximum eigenvalue (lambda) of a Matrix A and\n# its corresponding eigen vector (eigenvector)\n# X is some base vector row matrix, input\n# eps is the tolerance you want the eigenvalue to be computed to\n# max1 is the maximum number of iteractions allowed\n lamda=0.0\n cnt=1\n xnew=X\n xold=0*X\n err=np.linalg.norm(X)\n # xnew = xnew/max(abs(xnew))\n xnew = xnew/np.linalg.norm(xnew)\n \n while err>eps and cnt < max1:\n xold=xnew\n # ck = max(abs(xnew))\n ck = np.linalg.norm(xnew)\n xnew=np.dot(A,xnew)/ck\n cnt = cnt+1\n err = np.linalg.norm(xold-xnew)\n \n #if (cnt >=max1):\n #print('error in power2, max number of iterations exceeded')\n \n eigenvector = xnew/np.linalg.norm(xnew)\n lamda = ck\n\n return lamda,eigenvector\n\nif __name__ == \"__main__\":\n M=np.array([[2., -1., -1.], [-1., 2., -1], [1., -1., 2]])\n x=np.array([[3.], [2.], [1.]])\n \n eigenvalue,eigenvector = np.linalg.eig(M)\n # get max eigenvalue\n emax = np.max(eigenvalue)\n emax_index = np.argmax(eigenvalue)\n evmax = eigenvector[:,emax_index]\n \n \n eigenvalue1,eigenvector1=power1(M,x,1.0e-3,20)\n \n print('max eigenvalue from numpy eig =',emax)\n print('corresponding eigenvector =',evmax)\n print('max eigenvalue from powermethod =',eigenvalue1)\n print('corresponding eigenvector =',eigenvector1)\n\n","sub_path":"hw9/A-Swart_hw9_phys416/code/power1.py","file_name":"power1.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"223824406","text":"\"\"\"\nNone Player Characters\n\nPlayer Characters are (by default) Objects setup to be puppeted by Players.\nThey are what you \"see\" in game. The Character class in this module\nis setup to be the \"default\" character type created by the default\ncreation commands.\n\n\"\"\"\n\nimport traceback\nfrom evennia.utils import logger\nfrom muddery.server.utils.dialogue_handler import DIALOGUE_HANDLER\nfrom muddery.server.mappings.element_set import ELEMENT\nfrom muddery.server.database.worlddata.npc_dialogues import NPCDialogues\nfrom muddery.server.database.worlddata.npc_shops import NPCShops\nfrom muddery.server.database.worlddata.worlddata import WorldData\nfrom muddery.server.utils import defines\nfrom muddery.server.utils.localized_strings_handler import _\n\n\nclass MudderyBaseNPC(ELEMENT(\"CHARACTER\")):\n \"\"\"\n The character not controlled by players.\n\n States:\n shops\n \"\"\"\n element_type = \"BASE_NPC\"\n element_name = _(\"Base None Player Character\", \"elements\")\n model_name = \"\"\n\n def at_element_setup(self, first_time):\n \"\"\"\n Init the character.\n \"\"\"\n super(MudderyBaseNPC, self).at_element_setup(first_time)\n\n # Character can auto fight.\n self.auto_fight = True\n\n # load dialogues.\n self.load_dialogues()\n\n # load shops\n self.load_shops()\n\n def load_dialogues(self):\n \"\"\"\n Load dialogues.\n \"\"\"\n dialogues = NPCDialogues.get(self.get_element_key())\n\n self.default_dialogues = [dialogue.dialogue for dialogue in dialogues if dialogue.dialogue and dialogue.default]\n self.dialogues = [dialogue.dialogue for dialogue in dialogues if dialogue.dialogue and not dialogue.default]\n\n def load_shops(self):\n \"\"\"\n Load character's shop.\n \"\"\"\n # shops records\n shop_records = NPCShops.get(self.get_element_key())\n shop_keys = set([record.shop for record in shop_records])\n base_model = ELEMENT(\"SHOP\").get_base_model()\n\n # NPC's shop\n self.shops = {}\n for key in shop_keys:\n try:\n table_data = WorldData.get_table_data(base_model, key=key)\n table_data = table_data[0]\n\n shop = ELEMENT(table_data.element_type)()\n shop.setup_element(key)\n shop.set_owner(self)\n self.shops[key] = shop\n except Exception as e:\n logger.log_errmsg(\"Can not create shop %s: (%s)%s\" % (key, type(e).__name__, e))\n continue\n\n def get_appearance(self, caller):\n \"\"\"\n This is a convenient hook for a 'look'\n command to call.\n \"\"\"\n info = super(MudderyBaseNPC, self).get_appearance(caller)\n\n # quest mark\n provide_quest, complete_quest = self.have_quest(caller)\n info[\"provide_quest\"] = provide_quest\n info[\"complete_quest\"] = complete_quest\n\n return info\n\n def get_shop_info(self, shop_key, caller):\n \"\"\"\n Show shop's information to the player.\n :param shop_key:\n :param caller:\n :return:\n \"\"\"\n if shop_key not in self.shops:\n return None\n\n shop_info = self.shops[shop_key].get_info(caller)\n shop_info[\"npc\"] = self.get_id()\n return shop_info\n\n def sell_goods(self, shop_key, goods_index, caller):\n \"\"\"\n Sell goods to the caller.\n :param shop_key:\n :param goods_index:\n :param caller:\n :return:\n \"\"\"\n if shop_key not in self.shops:\n return None\n\n self.shops[shop_key].sell_goods(goods_index, caller)\n\n def get_available_commands(self, caller):\n \"\"\"\n This returns a list of available commands.\n \"\"\"\n commands = []\n if self.is_alive():\n if self.dialogues or self.default_dialogues:\n # If the character have something to talk, add talk command.\n commands.append({\"name\": _(\"Talk\"), \"cmd\": \"talk\", \"args\": self.get_id()})\n\n # Add shops.\n for key, obj in self.shops.items():\n if not obj.is_available(caller):\n continue\n\n verb = obj.get_verb()\n commands.append({\n \"name\": verb,\n \"cmd\": \"shopping\",\n \"args\": {\n \"npc\": self.get_id(),\n \"shop\": obj.get_element_key(),\n }\n })\n\n if self.friendly <= 0:\n commands.append({\"name\": _(\"Attack\"), \"cmd\": \"attack\", \"args\": self.get_id()})\n\n return commands\n\n def have_quest(self, caller):\n \"\"\"\n If the npc can complete or provide quests.\n Returns (can_provide_quest, can_complete_quest).\n \"\"\"\n return DIALOGUE_HANDLER.have_quest(caller, self)\n\n def remove_from_combat(self):\n \"\"\"\n Removed from the current combat.\n \"\"\"\n status = None\n opponents = None\n rewards = None\n\n combat = self.get_combat()\n if combat:\n result = combat.get_combat_result(self.id)\n if result:\n status, opponents, rewards = result\n\n if not self.is_temp:\n if status == defines.COMBAT_LOSE:\n self.die(opponents)\n\n super(MudderyBaseNPC, self).remove_from_combat()\n\n if not self.is_temp:\n if status != defines.COMBAT_LOSE:\n self.recover()\n","sub_path":"muddery/server/elements/base_npc.py","file_name":"base_npc.py","file_ext":"py","file_size_in_byte":5520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"82854191","text":"# Copyright The IETF Trust 2018, All Rights Reserved\n# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals, print_function, division\n\nimport datetime\nimport io\nimport os\n\nimport warnings\n\nwarnings.filterwarnings(\"ignore\", message='There are known rendering problems with Cairo <= 1.14.0')\nwarnings.filterwarnings(\"ignore\", message='@font-face support needs Pango >= 1.38')\n\ntry:\n import weasyprint\n import_error = None\nexcept (ImportError, OSError, ValueError) as e:\n import_error = e\n weasyprint = False\n\ntry:\n import fontconfig\nexcept ImportError:\n fontconfig = False\n\nimport xml2rfc\nfrom xml2rfc.writers.base import default_options, BaseV3Writer\nfrom xml2rfc.writers.html import HtmlWriter\nfrom xml2rfc.util.fonts import get_noto_serif_family_for_script\n\ntry:\n from xml2rfc import debug\n debug.debug = True\nexcept ImportError:\n pass\n\nclass PdfWriter(BaseV3Writer):\n\n def __init__(self, xmlrfc, quiet=None, options=default_options, date=datetime.date.today()):\n super(PdfWriter, self).__init__(xmlrfc, quiet=quiet, options=options, date=date)\n if not weasyprint:\n self.err(None, \"Cannot run PDF formatter: %s\" % import_error)\n return\n\n if options.verbose:\n import logging\n weasyprint.logger.LOGGER.setLevel(logging.DEBUG)\n\n def pdf(self):\n if not weasyprint:\n return None\n\n if not self.root.get('prepTime'):\n prep = xml2rfc.PrepToolWriter(self.xmlrfc, options=self.options, date=self.options.date, liberal=True, keep_pis=[xml2rfc.V3_PI_TARGET])\n tree = prep.prep()\n self.tree = tree\n self.root = self.tree.getroot()\n\n self.options.no_css = True\n self.options.image_svg = True\n htmlwriter = HtmlWriter(self.xmlrfc, quiet=True, options=self.options, date=self.date)\n html = htmlwriter.html()\n\n writer = weasyprint.HTML(string=html)\n\n cssin = self.options.css or os.path.join(os.path.dirname(os.path.dirname(__file__)), 'data', 'xml2rfc.css')\n css = weasyprint.CSS(cssin)\n\n # fonts and page info\n fonts = self.get_serif_fonts()\n page_info = {\n 'top-left': self.page_top_left(),\n 'top-center': self.page_top_center(),\n 'top-right': self.page_top_right(),\n 'bottom-left': self.page_bottom_left(),\n 'bottom-center': self.page_bottom_center(),\n 'fonts': ', '.join(fonts),\n }\n page_css_text = page_css_template.format(**page_info)\n page_css = weasyprint.CSS(string=page_css_text)\n\n pdf = writer.write_pdf(None, stylesheets=[ css, page_css ])\n\n return pdf\n\n\n def write(self, filename):\n if not weasyprint:\n return\n\n self.filename = filename\n\n pdf = self.pdf()\n if pdf:\n with io.open(filename, 'bw') as file:\n file.write(pdf)\n \n if not self.options.quiet:\n xml2rfc.log.write('Created file', filename)\n else:\n self.err(None, 'PDF creation failed')\n\n def get_serif_fonts(self):\n fonts = set()\n scripts = self.root.get('scripts').split(',')\n noto_serif = \"'Noto Serif'\"\n for script in scripts:\n family = get_noto_serif_family_for_script(script)\n fonts.add(\"'%s'\" % family)\n if fontconfig:\n available = fontconfig.query(family=family)\n if not available:\n self.warn(None, \"Needed font family '%s', but didn't find it. Is it installed?\" % family)\n fonts -= set([ noto_serif, ])\n fonts = [ noto_serif, ] + list(fonts)\n return fonts\n\npage_css_template = \"\"\"\n@media print {{\n body {{\n font-family: {fonts}, 'Times New Roman', Times, serif;\n width: 100%;\n }}\n @page {{\n size: A4;\n font-size: 12px;\n\n border-top: solid 1px #ccc;\n padding-top: 18px;\n\n padding-bottom: 24px;\n border-bottom: solid 1px #ccc;\n margin-bottom: 45mm;\n\n @top-left {{\n content: '{top-left}';\n vertical-align: bottom;\n border-bottom: 0px;\n margin-bottom: 1em;\n }}\n @top-center {{\n content: '{top-center}';\n vertical-align: bottom;\n border-bottom: 0px;\n margin-bottom: 1em;\n }}\n @top-right {{\n content: '{top-right}';\n vertical-align: bottom;\n border-bottom: 0px;\n margin-bottom: 1em;\n }}\n @bottom-left {{\n content: '{bottom-left}';\n vertical-align: top;\n border-top: 0px;\n margin-top: 1em;\n }}\n @bottom-center {{\n content: '{bottom-center}';\n vertical-align: top;\n border-top: 0px;\n margin-top: 1em;\n }}\n @bottom-right {{\n content: 'Page ' counter(page);\n vertical-align: top;\n border-top: 0px;\n margin-top: 1em;\n }}\n }}\n}}\n\"\"\"\n\n\n","sub_path":"extern/xml2rfc-2.22.3-patched/xml2rfc/writers/pdf.py","file_name":"pdf.py","file_ext":"py","file_size_in_byte":4878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"147918403","text":"# python\nimport json\n\n# flask\nfrom flask import Blueprint\nfrom flask import render_template\nfrom flask import redirect\nfrom flask import request\nfrom flask import json as fjson\n\nfrom tinker.events.cascade_events import *\nfrom tinker import app\nfrom tinker import tools\n\nevent_blueprint = Blueprint('event', __name__, template_folder='templates')\n\n\n@event_blueprint.route('/')\ndef home():\n\n forms = get_forms_for_user(session['username'])\n if 'Event Approver' in tools.get_groups_for_user():\n event_approver_forms = get_forms_for_event_approver()\n return render_template('events-home.html', **locals())\n\n\n@event_blueprint.route('/delete/')\ndef delete_page(page_id):\n workflow = get_event_delete_workflow()\n delete(page_id, workflow)\n publish_event_xml()\n return redirect('/event/delete-confirm', code=302)\n\n\n@event_blueprint.route('/delete-confirm')\ndef delete_confirm():\n return render_template('events-delete-confirm.html', **locals())\n\n\n@event_blueprint.route(\"/add\")\ndef form_index():\n\n # import this here so we dont load all the content\n # from cascade during hoempage load\n from tinker.events.forms import EventForm\n\n form = EventForm()\n add_form = True\n return render_template('event-form.html', **locals())\n\n\n@event_blueprint.route(\"/read\")\ndef read_page():\n tools.get_user()\n client = get_client()\n identifier = {\n 'id': 'e3a946ca8c58651324d9038d448f46c3',\n 'type': 'file',\n # 'path': {\n # 'path': '/academics/faculty/hamre-alyssa',\n # 'siteId': os.environ['SITE_ID']\n # }\n }\n\n auth = os.environ['CASCADE_LOGIN']\n response = client.service.read(auth, identifier)\n\n return \"
    \" + str(response) + \"
    \"\n\n\n@event_blueprint.route('/in-workflow')\ndef event_in_workflow():\n return render_template('event-in-workflow.html')\n\n\n@event_blueprint.route('/edit/')\ndef edit_event_page(event_id):\n\n # if the event is in a workflow currently, don't allow them to edit. Instead, redirect them.\n if is_asset_in_workflow(event_id):\n return redirect('/event/in-workflow', code=302)\n\n # import this here so we dont load all the content\n # from cascade during homepage load\n from tinker.events.forms import EventForm\n\n # Get the event data from cascade\n event_data = read(event_id)\n\n # Get the different data sets from the response\n\n form_data = event_data.asset.page\n # the stuff from the data def\n s_data = form_data.structuredData.structuredDataNodes.structuredDataNode\n # regular metadata\n metadata = form_data.metadata\n # dynamic metadata\n dynamic_fields = metadata.dynamicFields.dynamicField\n # This dict will populate our EventForm object\n edit_data = {}\n date_count = 0\n dates = {}\n # Start with structuredDataNodes (data def content)\n for node in s_data:\n node_identifier = node.identifier.replace('-', '_')\n node_type = node.type\n if node_type == \"text\":\n edit_data[node_identifier] = node.text\n elif node_type == 'group':\n # These are the event dates. Create a dict so we can convert to JSON later.\n dates[date_count] = read_date_data_structure(node)\n date_count += 1\n\n # now metadata dynamic fields\n for field in dynamic_fields:\n # This will fail if no metadata is set. It should be required but just in case\n if field.fieldValues:\n items = [item.value for item in field.fieldValues.fieldValue]\n edit_data[field.name.replace('-', '_')] = items\n\n # Add the rest of the fields. Can't loop over these kinds of metadata\n edit_data['title'] = metadata.title\n edit_data['teaser'] = metadata.metaDescription\n author = metadata.author\n\n # Create an EventForm object with our data\n form = EventForm(**edit_data)\n form.event_id = event_id\n\n # convert dates to json so we can use Javascript to create custom DateTime fields on the form\n dates = fjson.dumps(dates)\n\n return render_template('event-form.html', **locals())\n\n\ndef check_event_dates(form):\n\n event_dates = {}\n dates_good = False\n num_dates = int(form['num_dates'])\n for x in range(1, num_dates+1): # the page doesn't use 0-based indexing\n\n i = str(x)\n start_l = 'start' + i\n end_l = 'end' + i\n all_day_l = 'allday' + i\n\n start = form[start_l]\n end = form[end_l]\n all_day = all_day_l in form.keys()\n\n event_dates[start_l] = start\n event_dates[end_l] = end\n event_dates[all_day_l] = all_day\n\n start_and_end = start and end\n\n if start_and_end:\n dates_good = True\n\n # convert event dates to JSON\n return json.dumps(event_dates), dates_good, num_dates\n\n\n@event_blueprint.route(\"/submit\", methods=['POST'])\ndef submit_form():\n\n # import this here so we dont load all the content\n # from cascade during hoempage load\n from tinker.events.forms import EventForm\n\n form = EventForm()\n rform = request.form\n title = rform['title']\n username = session['username']\n workflow = get_event_publish_workflow(title, username)\n\n # check event dates here?\n\n # create a dict of date values so we can access them in Jinja later.\n # they aren't part of the form so we can't just do form.start1, etc...\n event_dates, dates_good, num_dates = check_event_dates(rform)\n\n dates = []\n\n if not form.validate_on_submit() or not dates_good:\n if 'event_id' in request.form.keys():\n event_id = request.form['event_id']\n else:\n # This error came from the add form because event_id wasn't set\n add_form = True\n return render_template('event-form.html', **locals())\n\n form = rform\n # Get all the form data\n metadata_list = ['general', 'offices', 'cas_departments', 'internal']\n add_data = get_add_data(metadata_list, form)\n\n dates = get_dates(add_data)\n\n # Add it to the dict, we can just ignore the old entries\n add_data['event-dates'] = dates\n\n asset = get_event_structure(add_data, username, workflow)\n\n resp = create(asset)\n\n # 'link' must be a valid component\n if 'link' in add_data and add_data['link'] != \"\":\n from tinker.redirects.views import new_internal_redirect_submit\n path = str(asset['page']['parentFolderPath'] + \"/\" + asset['page']['name'])\n new_internal_redirect_submit(path, add_data['link'])\n\n return redirect('/event/confirm', code=302)\n # Just print the response for now\n\n\n@event_blueprint.route(\"/submit-edit\", methods=['post'])\ndef submit_edit_form():\n\n # import this here so we dont load all the content\n # from cascade during hoempage load\n from tinker.events.forms import EventForm\n\n form = EventForm()\n rform = request.form\n title = rform['title']\n username = session['username']\n workflow = get_event_publish_workflow(title, username)\n\n event_dates, dates_good, num_dates = check_event_dates(rform)\n\n if not form.validate_on_submit() or not dates_good:\n event_id = request.form['event_id']\n return render_template('event-form.html', **locals())\n\n form = rform\n add_data = get_add_data(['general', 'offices', 'cas_departments', 'internal'], form)\n dates = get_dates(add_data)\n add_data['event-dates'] = dates\n add_data['author'] = request.form['author']\n event_id = form['event_id']\n\n asset = get_event_structure(add_data, username, workflow=workflow, event_id=event_id)\n\n current_year = get_current_year_folder(event_id)\n new_year = get_year_folder_value(add_data)\n\n resp = edit(asset)\n warn_message = \"%s: Event edit submission by %s with id %s. %s\"\n app.logger.warn(warn_message % (time.strftime(\"%c\"), username, event_id, str(resp)))\n\n if new_year > current_year:\n resp = move_event_year(event_id, add_data)\n app.logger.warn(time.strftime(\"%c\") + \": Event move submission by \" + username + \" \" + str(resp))\n\n # 'link' must be a valid component\n if 'link' in add_data and add_data['link'] != \"\":\n from tinker.redirects.views import new_internal_redirect_submit\n path = str(asset['page']['parentFolderPath'] + \"/\" + asset['page']['name'])\n new_internal_redirect_submit(path, add_data['link'])\n\n return redirect('/event/confirm', code=302)\n\n\n@event_blueprint.route('/confirm')\ndef confirm():\n return render_template('submit-confirm.html', **locals())\n","sub_path":"tinker/events/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"107409874","text":"#Hafta 4 Ornek 3\n\nimport math\n\ndongu = 0\nsayac = 2\ntoplam = 0\nenBuyuk = 0\nenKucuk = 0\ncarpim = 0\n\nsayi = float(input('Sayi giriniz: '))\nsayi2 = float(input('Tekrar Sayi giriniz: '))\nif sayi > sayi2:\n enBuyuk = sayi\n enKucuk = sayi2\nelse:\n enBuyuk = sayi2\n enKucuk = sayi\ntoplam = sayi + sayi2\ncarpim = sayi * sayi2\n\nwhile dongu == 0:\n devam = int(input(\"Devam etmek icin 1'e basiniz: \"))\n if devam == 1:\n sayi3 = float(input('Sayi girisi yapiniz: '))\n sayac += 1\n toplam += sayi3\n carpim = carpim * sayi3\n if sayi3 > enBuyuk:\n enBuyuk = sayi3\n elif sayi3 < enKucuk:\n enKucuk = sayi3\n aritmetik = toplam / sayac\n geometrik = carpim ** 0.5\n else:\n print('En buyuk sayi: ', enBuyuk)\n print('En kucuk sayi: ', enKucuk)\n print('Aritmetik ortalamalari: ', aritmetik)\n print('Geometrik ortalamalari: ', geometrik)\n\n print('Program kapatiliyor...')\n dongu += 1\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Hafta4/Ornek3.py","file_name":"Ornek3.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"268017907","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.allusers, name='allusers'),\n url(r'^user/(?P\\d+)/$', views.userpage, name='userpage'),\n url(r'^user/(?P\\d+)/update/$', views.userpage_update, name='userpage_update'),\n url(r'^user/(?P\\d+)/delete/$', views.user_delete, name='user_delete'),\n url(r'^download_csv/$', views.download_csv, name='download_csv'),\n\n]","sub_path":"miloapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":423,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"622478341","text":"\"\"\"This module provides the matrix class.\n\nIMPORTANT NOTICE: Don't use vector, cross, etc. as variable names\nWe have lowercase classes for sake of usability\n\n\"\"\"\n\nfrom numbers import Number\nfrom vector import vector\n\n\nclass matrix(object):\n \"\"\"matrix class.\n\n Attirbutes:\n values (Vector[]): vector rows\n \"\"\"\n\n def __init__(self, *args):\n \"\"\"\n Constructs a matrix.\n\n Initialized with one of the following sets of args:\n Series of Numbers (only one row)\n Series of lists/vectors\n List of list of vectors\n \"\"\"\n self.values = []\n # Returns [] if no args\n if len(args) > 0:\n # If args are a series of Numbers\n if isinstance(args[0], Number):\n self.values = [vector(*args)]\n # If args are a series of lists or vectors\n elif isinstance(args[0], list) or isinstance(args[0], vector):\n # If args[0] is a list of lists, unpack it\n if any(isinstance(arg, list) or isinstance(arg, vector) for arg in args[0]):\n args = args[0]\n for arg in args:\n # If args is a list of list, cast to vector\n if isinstance(arg, list):\n arg = vector(arg)\n elif not isinstance(arg, vector):\n raise TypeError(\n str(arg) + ' is not a list or a vector')\n if len(arg) != len(args[0]):\n raise IndexError(\"args aren't the same length\")\n self.values.append(arg)\n else:\n raise TypeError(\n str(args[0]) + ' is not a Number, list or vector')\n\n def __add__(self, other):\n \"\"\"Overloads + operator.\n\n Args:\n other (matrix, Number): matrix or Number to be added to self\n\n Returns:\n matrix: The sum of self and other\n \"\"\"\n if isinstance(other, matrix):\n my_height, my_width = dim(self)\n other_height, other_width = dim(other)\n # My width must be the other height, my height the other width\n if my_width == other_height and my_height == other_width:\n new_matrix = []\n for i in range(my_width):\n new_matrix.append(self.values[i] + other.values[i])\n return matrix(new_matrix)\n else:\n raise ValueError(\"matrices have different dimensions\")\n elif isinstance(other, Number):\n return matrix([other + row for row in self.values])\n else:\n raise TypeError('only matrices or Numbers can be added to matrices')\n\n def __eq__(self, other):\n \"\"\"Overloads == operator.\n\n Args:\n other (matrix): matrix to compare self to\n\n Returns:\n bool: if self and mat are equal\n \"\"\"\n if isinstance(other, matrix):\n if dim(other) == dim(self):\n for a, b in zip(other.values, self.values):\n if a != b:\n return False\n return True\n else:\n raise ValueError('matrices have different dimensions')\n else:\n raise TypeError('matrices can only be compared to other matrices')\n\n def __getitem__(self, index):\n \"\"\"Gets a single entry in the matrix by (row, col).\n\n Args:\n index: (row, col) index of entry to get\n\n Returns:\n Number: entry found in self at index\n \"\"\"\n row, col = index\n return self.values[row][col]\n\n def __iter__(self):\n for row in self.values:\n yield row\n\n def __len__(self):\n \"\"\"Return the total number of elements in self.\n\n Returns:\n int: total number of elements\n \"\"\"\n if len(self.values) == 0:\n return 0\n return len(self.values) * len(self.values[0])\n\n def __mul__(self, other):\n \"\"\"Overloads * operator.\n\n Checks if other is a matrix or Number, and performs matrix multiply or dot product\n as appropriate.\n\n Args:\n other (matrix, Number): matrix or Number by which to multiply self\n\n Returns:\n matrix: self multiplied by other\n \"\"\"\n if isinstance(other, matrix):\n my_height, my_width = dim(self)\n other_height, other_width = dim(other)\n # My width must be the other height, my height the other width\n if my_width == other_height and my_height == other_width:\n new_matrix = []\n for i in range(my_height):\n row = []\n for j in range(other_width):\n msum = 0\n for k in range(my_width):\n msum += self[i,k] * other[k,j]\n row.append(msum)\n new_matrix.append(row)\n return matrix(new_matrix)\n else:\n raise ValueError(\"matrices have different dimensions\")\n elif isinstance(other, Number):\n return matrix([other * row for row in self.values])\n else:\n raise TypeError('only matrices or Numbers can multiply matrices')\n\n def __ne__(self, other):\n \"\"\"Overloads != operator\n\n Args:\n other (matrix): matrix to compare self to\n\n Returns:\n bool: if self and other are not equal\n \"\"\"\n return not self == other\n\n def __radd__(self, other):\n \"\"\"Implements reflective addition.\n\n Args:\n other (matrix, Number): matrix or Number to be added to self\n\n Returns:\n matrix: The sum of self and other\n \"\"\"\n return self + other\n\n def __repr__(self):\n \"\"\"Returns a simple string representation of self.\n\n Returns:\n string: simple representatino of self\n \"\"\"\n return 'matrix: ' + str(self.values)\n\n def __rmul__(self, other):\n \"\"\"Implements reflective multiplication\n\n Args:\n other (matrix, Number): matrix or Number by which to multiply self\n\n Returns:\n matrix: self multiplied by other\n \"\"\"\n return self * other\n\n def __setitem__(self, index, val):\n \"\"\"Sets a single entry in the matrix by index.\n\n Args:\n index: (row, col) index of entry to set\n val (Number): value to set entry to\n \"\"\"\n row, col = index\n if isinstance(val, Number):\n if (row, col) <= dim(self):\n self.values[row][col] = val\n else:\n raise IndexError('index is out of bounds')\n else:\n raise TypeError('value must be a Number')\n\n def __str__(self):\n \"\"\"Returns a pretty representation of self.\n\n Returns:\n string: pretty representation of self\n \"\"\"\n out = []\n for value in self.values:\n out.append(str(value))\n return '\\n'.join(out)\n\n def _col(self, num):\n \"\"\"Returns the matrix column with the given index.\n\n Args:\n num (int): column index\n\n Returns:\n Number[]: matrix column with given index\n \"\"\"\n return [row[num] for row in self.values]\n\n def _row(self, num):\n \"\"\"Returns the matrix row with the given index.\n\n Args:\n num (int): row index\n\n Returns:\n Number[]: matrix row with given index\n \"\"\"\n return self.values[num]\n\n\ndef dim(mat):\n \"\"\"Gets matrix dimensions.\n\n Args:\n mat (matrix): matrix to get dimensions of\n\n Returns:\n list: dimensions of the matrix\n \"\"\"\n return len(mat.values[0]), len(mat.values)\n","sub_path":"popeye/web_server/listing_exec_app/objects/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":7849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"530779922","text":"from Semana_10.menu import ingresar_vector\nfrom Semana_13 import Archivo\n\nmatrices = Archivo.leer('Matrices.json')\n\ndef leer_matriz():\n \"\"\"\n Lee una matriz por teclado\n :return: (list of list of int) la matriz del usuario\n \"\"\"\n resultado = []\n while True:\n entrada = input('Desea ingresar una fila? s/n ')\n if entrada == 'n':\n break\n resultado.append(ingresar_vector())\n return resultado\n\nwhile True:\n\n MENU = \"\"\"\n **********Menu**********\n 0. Salir\n 1. Ingresar Matriz\n 2. Ver Matrices\n 3. Matriz cuadrada\n 4. Sumar matrices\n 5. Producto escalar\n 6. Multiplicar matrices\n ************************\n \"\"\"\n\n seleccion = input(MENU)\n if seleccion == '0':\n print('Suerte')\n Archivo.guardar('Matrices.json', matrices)\n break\n elif seleccion == \"1\":\n nombre = input('cual es el nombre de su matriz ')\n matriz = leer_matriz()\n matrices[nombre[0]]=matriz\n elif seleccion == \"2\":\n print('Sus matrices')\n for matriz in matrices:\n print(matrices[matriz])\n elif seleccion == '3':\n print()\n elif seleccion == '4':\n print()\n elif seleccion == '5':\n print()\n elif seleccion == '6':\n print()\n else:\n print(\"Seleccion invalida\")\n\n","sub_path":"Semana_13/menu_matrices.py","file_name":"menu_matrices.py","file_ext":"py","file_size_in_byte":1324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"87611658","text":"from pulp import LpMinimize, LpProblem, LpStatus, LpVariable\n\n# Create the model\nmodel = LpProblem(name=\"Utility Company\", sense=LpMinimize)\n\n# Initialize the decision variables\nXA = LpVariable(name=\"XA\", lowBound=0,)\nXB = LpVariable(name=\"XB\", lowBound=0,)\n\n# Add the constraints to the model\nmodel += (10*XA >= 4000, \"demand_active\")\nmodel += (XB >= 50, \"demand_inactive\")\nmodel += (XA +XB <= 10*24*7, \"time_constraint\")\n\n# Add the objective function to the model\nobj_func = (7575-3*XA-2.5*XB-2*(XA+XB-40*10))/7575 + (XA+XB-40*10-50)/50\nmodel += obj_func\n\n# Solve the problem\nstatus = model.solve()\n\nprint(f\"status: {model.status}, {LpStatus[model.status]}\")\n\nprint(f\"objective: {model.objective.value()}\")\n\nfor var in model.variables():\n print(f\"{var.name}: {var.value()}\")\n\nfor name, constraint in model.constraints.items():\n print(f\"{name}: {constraint.value()}\")","sub_path":"Utility Company.py","file_name":"Utility Company.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"453876262","text":"#!/usr/bin/python\nimport svgwrite\nimport re, mmap\nimport sys\n\n# Process argument, or choose default.\nif len(sys.argv)==1:\n filename='Schaukel.gno'\nelse:\n filename=sys.argv[1]\n\n# some layout options\ndistanceFromGrid=0.25 # Distance of the text from the borders of the grid\ndistanceToAlign=0.8 # allow to center the text\nfontsize=0.75\ngrid_thinline=0.05 # thickness of lines of the grid\ngrid_thickline=0.1 # thickness of each 5th line of the grid\n\n# canvas size depends on the size of text. It must be estimated as i cant tell how the text will be rendered\n# 8 boxex are normally OK.\nx_offset = 8\ny_offset = 8\n# lowerleft margin \nmargin = 0.5\n\ndef getlinewidth(id):\n # draw each 5th line with a different linewidth\n if (id%5) == 0:\n return grid_thickline\n else:\n return grid_thinline\n\n# Import the nonogram\nwith open(filename, 'r+') as f:\n data = mmap.mmap(f.fileno(), 0)\n # Import the Row Clues from the gno file via regexp between sections\n clues_rows = re.search('(?<=Row.clues\\]\\n)(.*?)(?=\\[)', data,re.DOTALL).group(1).splitlines()\n # Import the Col Clues from the gno file via regexp between sections\n clues_cols = re.search('(?<=Column.clues\\]\\n)(.*?)(?=\\[)', data,re.DOTALL).group(1).splitlines()\nsizeX=len(clues_cols)\nsizeY=len(clues_rows)\n\n# Create the SVG\ndwg = svgwrite.Drawing(filename[0:-4] + '.svg', profile='tiny', size = (sizeX+x_offset+margin, sizeY+y_offset+margin))\n# put elements in groups to edit them more easily later\nall = dwg.add(dwg.g(id=\"nonogram\"))\ngrid = all.add(dwg.g(id=\"grid\"))\ntext_rows = all.add(dwg.g(id=\"rowhints\"))\ntext_cols = all.add(dwg.g(id=\"colhints\"))\n\nfor i in range(0, sizeX):\n # Draw x grid\n grid.add(dwg.line((margin+i, 0+y_offset), (margin+i, sizeY+y_offset), stroke='black', stroke_width=getlinewidth(i), stroke_linecap=\"square\"))\n # reverse string order (need because of rotation)\n clues_cols[i]=\",\".join(reversed(clues_cols[i].split(',')))\n # draw the text\n text_cols.add(dwg.text(clues_cols[i], insert=(+ distanceFromGrid-y_offset, margin+i+distanceToAlign), fill='black', font_size=fontsize,transform=\"rotate(270)\",font_family=\"Sawasdee\", font_weight=\"bold\"))\n# outer border of the grid\ngrid.add(dwg.line((margin+sizeX, 0+y_offset), (margin+sizeX, sizeY+y_offset), stroke='black', stroke_width=getlinewidth(0), stroke_linecap=\"square\"))\n\nfor i in range(0, sizeY):\n grid.add(dwg.line((margin+0, i+y_offset), (margin+sizeX, i+y_offset), stroke='black', stroke_width=getlinewidth(i), stroke_linecap=\"square\"))\n text_rows.add(dwg.text(clues_rows[i], insert=(margin+sizeX+ distanceFromGrid, i+distanceToAlign+y_offset), fill='black', font_size=fontsize,font_family=\"Sawasdee\", font_weight=\"bold\"))\ngrid.add(dwg.line((margin+0, sizeY+y_offset), (margin+sizeX, sizeY+y_offset), stroke='black', stroke_width=getlinewidth(0), stroke_linecap=\"square\"))\n\ndwg.save()\n","sub_path":"gnonogram2svg.py","file_name":"gnonogram2svg.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628066129","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport itertools\n\nnames = ['Cecilia', 'Lise', 'Marie']\nletters = [len(x) for x in names]\n\nlongest_name = None\nmax_letters = 0\n\nfor i in range(len(names)):\n count = letters[i]\n if count > max_letters:\n longest_name = names[i]\n max_letters = count\n\nprint('{}:{}'.format(longest_name, max_letters))\n\nlongest_name = None\nmax_letters = 0\n\nfor i, name in enumerate(names): #関数enumerateを利用しても可読性がイマイチ\n count = letters[i]\n if count > max_letters:\n longest_name = name\n max_letters = count\n\nprint('{}\\n{}:{}'.format(type(enumerate(names)), longest_name, max_letters))\n\nlongest_name = None\nmax_letters = 0\n\nfor name, count in zip(names, letters): # 関数zipを利用すると可読性が上がる\n if count > max_letters:\n longest_name = name\n max_letters = count\n\nprint('{}\\n{}:{}'.format(type(zip(names,letters)), longest_name, max_letters))\n\n# 入力イテレータの長さが異なると、zipの振る舞いがおかしくなる\nnames.append('Rosalind')\nfor name, count in zip(names, letters):\n print('{}:{}'.format(name, count))\n\n# itertoolsの関数zip_longestを利用すると全ての要素を処理できる\nfor name, count in itertools.zip_longest(names, letters):\n print('{}:{}'.format(name, count))\n","sub_path":"11_zip.py","file_name":"11_zip.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"504759142","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /mnt/nfs/terra.localdomain/home/rgomes/sources/frgomes/velruse/feature.kotti_auth/velruse/examples/kotti_velruse/kotti_velruse/views.py\n# Compiled at: 2013-10-27 19:52:16\nfrom pyramid.httpexceptions import HTTPFound, HTTPNotFound\nfrom pyramid.request import Request\nfrom velruse.api import login_url\nfrom velruse.app import find_providers\nlog = __import__('logging').getLogger(__name__)\n\ndef includeme(config):\n config.add_view(login, route_name='login', request_method='GET', renderer='kotti_velruse:templates/login.mako')\n config.add_view(login_, route_name='login_', renderer='json')\n config.add_view(logged_in, route_name='logged_in', renderer='json')\n config.add_view(logout, route_name='logout', permission='view')\n config.add_route('login', '/login')\n config.add_route('login_', '/login_')\n config.add_route('logged_in', '/logged_in')\n config.add_route('logout', '/logout')\n config.add_static_view(name='static', path='kotti_velruse:static')\n config.add_static_view(name='', path='kotti_velruse:openid-selector')\n\n\ndef login(request):\n settings = request.registry.settings\n project = settings['kotti.site_title']\n return {'project': project, \n 'login_url': request.route_url('login_')}\n\n\ndef login_(request):\n provider = request.params['method']\n settings = request.registry.settings\n if provider not in find_providers(settings):\n raise HTTPNotFound(('Provider \"{}\" is not configured').format(provider)).exception\n velruse_url = login_url(request, provider)\n payload = dict(request.params)\n if 'yahoo' == provider:\n payload['oauth'] = 'true'\n if 'facebook' == provider:\n payload['scope'] = 'email,publish_stream,read_stream,create_event,offline_access'\n if 'openid' == provider:\n payload['use_popup'] = 'false'\n payload['format'] = 'json'\n redirect = Request.blank(velruse_url, POST=payload)\n try:\n response = request.invoke_subrequest(redirect)\n return response\n except:\n message = ('Provider \"{}\" is probably misconfigured').format(provider)\n raise HTTPNotFound(message).exception\n\n\ndef logged_in(request):\n token = request.params['token']\n storage = request.registry.velruse_store\n try:\n return storage.retrieve(token)\n except KeyError:\n message = ('invalid token \"{}\"').format(token)\n log.error(message)\n return {'error': message}\n\n\ndef logout(request):\n from pyramid.security import forget\n request.session.invalidate()\n request.session.flash('Session logoff.')\n headers = forget(request)\n return HTTPFound(location=request.route_url('login'), headers=headers)","sub_path":"pycfiles/rgomes_velruse-1.1.2.tar/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":"67"} +{"seq_id":"115980512","text":"import os\nimport pandas as pd\nfrom folium import Map, Marker, Popup\nfrom folium.plugins import MarkerCluster, BeautifyIcon\n\n# read data\ndata = os.path.join('src', 'data', 'btso.csv')\ndf = pd.read_csv(data, sep='|', dtype={'ID' : object})\n\n# create map\nmap = Map(location=[df['ENLEM'].mean(), df['BOYLAM'].mean()], zoom_start=6)\n\n# create marker cluster\ncluster = MarkerCluster()\n\n# create popup html\npopup = \"\"\"\\\n
      \n
    1. \n \n {id}\n
    2. \n
    3. \n \n {firma_adi}\n
    4. \n
    5. \n \n {durum}\n
    6. \n
    7. \n \n {nace_kodu}\n
    8. \n
    9. \n \n {meslek_grubu}\n
    10. \n
    \n\"\"\"\n\n# add markers to cluster\nfor row in df.itertuples():\n if row.DURUM == 'FAAL':\n color= '#95D669'\n elif row.DURUM == 'ASKIDA-BORC/ADRES' or row.DURUM == 'ASKIDA-BORC':\n color = '#EBCA42'\n elif row.DURUM == 'IFLAS':\n color='#b3334f'\n\n icon=BeautifyIcon(\n icon='home',\n border_color=color,\n text_color=color\n )\n \n cluster.add_child(\n Marker(\n location=[row.ENLEM, row.BOYLAM], \n popup=Popup(\n popup.format(\n id=row.ID, \n firma_adi=row.FIRMA_ADI.upper(), \n durum=row.DURUM.upper(), \n nace_kodu=row.NACE_KODU.upper(),\n meslek_grubu=row.MESLEK_GRUBU.upper()\n ), \n max_width='100%'),\n icon=icon\n )\n )\n\n# add cluster to map\nmap.add_child(cluster)\n\n# save map as html\nmap.save('src/pages/btso.html')","sub_path":"src/btso.py","file_name":"btso.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"221656526","text":"class RTFFieldMixin:\n def __init__(self, **kw):\n kwargs = dict(\n max_length=None,\n min_length=None,\n )\n for k, v in filter(lambda t: next(iter(t), None) and not t[0].startswith(('__', 'self', 'kw')),\n locals().items()):\n kwargs[k] = v\n kwargs.update(kw)\n if kwargs.get('style', None) is None:\n kwargs['style'] = dict(\n base_template='rtf_field.html',\n )\n super().__init__(**kwargs)\n","sub_path":"dynamicforms/mixins/rtf_field.py","file_name":"rtf_field.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41542617","text":"\n\n#calss header\nclass _SEMITONE():\n\tdef __init__(self,): \n\t\tself.name = \"SEMITONE\"\n\t\tself.definitions = [u'the smallest difference in sound between two notes that are next to each other in the western musical scale']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_semitone.py","file_name":"_semitone.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"53432612","text":"#Routines to run a real-time projected-DMET calculation\n\nimport numpy as np\nimport system_mod\nimport utils\nimport applyham_pyscf\nimport mf1rdm_timedep_mod\nimport sys\nimport os\nimport multiprocessing as multproc\nimport pickle\nimport scipy\n\nimport time\n\nimport fci_mod\nimport pyscf.fci\nimport integrators\n\n############ CLASS TO RUN REAL-TIME DMET CALCULATION #########\n\nclass dynamics_driver():\n\n #####################################################################\n\n def __init__( self, h_site, V_site, hamtype, tot_system, delt, Nstep, Nprint=100, integ='rk1', nproc=1, hubsite_indx=None, init_time=0.0):\n\n #h_site - 1 e- hamiltonian in site-basis for total system to run dynamics\n #V_site - 2 e- hamiltonian in site-basis for total system to run dynamics\n #hamtype - integer defining if using a special Hamiltonian like Hubbard or Anderson Impurity\n #tot_system - a previously defined DMET total system including all fragment information\n #delt - time step\n #Nstep - total number of time-steps\n #Nprint - number of time-steps between printing\n #init_time - the starting time for the calculation\n #integ - the type of integrator used\n #nproc - number of processors for calculation - careful, there is no check that this matches the pbs script\n\n self.tot_system = tot_system\n self.delt = delt\n self.Nstep = Nstep\n self.Nprint = Nprint\n self.init_time = init_time\n self.integ = integ\n self.nproc = nproc\n\n print()\n print('********************************************')\n print(' SET-UP REAL-TIME DMET CALCULATION ')\n print('********************************************')\n print()\n\n #Input error checks\n\n #Convert rotation matrices, CI coefficients, and MF 1RDM to complex arrays if they're not already\n for frag in self.tot_system.frag_list:\n if( not np.iscomplexobj( frag.rotmat ) ):\n frag.rotmat = frag.rotmat.astype(complex)\n if( not np.iscomplexobj( frag.CIcoeffs ) ):\n frag.CIcoeffs = frag.CIcoeffs.astype(complex)\n\n if( not np.iscomplexobj( self.tot_system.mf1RDM ) ):\n self.tot_system.mf1RDM = self.tot_system.mf1RDM.astype(complex)\n\n #Set-up Hamiltonian for dynamics calculation\n self.tot_system.h_site = h_site\n self.tot_system.V_site = V_site\n self.tot_system.hamtype = hamtype\n\n #If running Hubbard-like model, need an array containing index of all sites that have hubbard U term\n self.tot_system.hubsite_indx = hubsite_indx\n if( self.tot_system.hamtype == 1 and self.tot_system.hubsite_indx is None ):\n print('ERROR: Did not specify an array of sites that contain Hubbard U term')\n print()\n exit()\n\n #Define output files\n self.file_output = open( 'output.dat', 'w' )\n self.file_corrdens = open( 'corr_density.dat', 'w' )\n\n self.file_test = open( 'test_data.dat', 'w' )#msh\n\n #####################################################################\n\n def kernel( self ):\n\n print()\n print('********************************************')\n print(' BEGIN REAL-TIME DMET CALCULATION ')\n print('********************************************')\n print()\n\n #DYNAMICS LOOP\n current_time = self.init_time\n for step in range(self.Nstep):\n\n #Print data before taking time-step, this always prints out data at initial time step\n if( np.mod( step, self.Nprint ) == 0 ):\n print('Writing data at step ', step, 'and time', current_time, 'for RT-pDMET calculation')\n self.print_data( current_time )\n sys.stdout.flush()\n\n #Integrate FCI coefficients and rotation matrix for all fragments\n self.integrate(self.nproc)\n\n #Increase current_time\n current_time = self.init_time + (step+1)*self.delt\n\n\n #Print data at final step regardless of Nprint\n print('Writing data at step ', step+1, 'and time', current_time, 'for RT-pDMET calculation')\n self.print_data( current_time )\n sys.stdout.flush()\n\n #Close output files\n self.file_output.close()\n self.file_corrdens.close()\n self.file_test.close()#msh\n\n print()\n print(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n print(\"END REAL-TIME DMET CALCULATION\")\n print(\"++++++++++++++++++++++++++++++++++++++++++++++++++++++++\")\n print()\n\n #####################################################################\n\n def integrate( self, nproc ):\n #Subroutine to integrate equations of motion\n\n if( self.integ == 'rk4' ):\n #Use 4th order runge-kutta to integrate EOMs\n\n #Copy MF 1RDM, CI coefficients, and embedding orbs at time t\n init_mf1RDM = np.copy( self.tot_system.mf1RDM )\n init_CIcoeffs_list = []\n init_rotmat_list = []\n for frag in self.tot_system.frag_list:\n init_rotmat_list.append( np.copy(frag.rotmat) )\n init_CIcoeffs_list.append( np.copy(frag.CIcoeffs) )\n\n #Calculate appropriate changes in MF 1RDM, embedding orbitals, and CI coefficients\n #Note that l, k and m terms are for MF 1RDM, emb orbs, and CI coefficients respectively\n l1, k1_list, m1_list = self.one_rk_step(nproc)\n\n self.tot_system.mf1RDM = init_mf1RDM + 0.5*l1\n for cnt, frag in enumerate(self.tot_system.frag_list):\n frag.rotmat = init_rotmat_list[cnt] + 0.5*k1_list[cnt]\n frag.CIcoeffs = init_CIcoeffs_list[cnt] + 0.5*m1_list[cnt]\n\n l2, k2_list, m2_list = self.one_rk_step(nproc)\n\n self.tot_system.mf1RDM = init_mf1RDM + 0.5*l2\n for cnt, frag in enumerate(self.tot_system.frag_list):\n frag.rotmat = init_rotmat_list[cnt] + 0.5*k2_list[cnt]\n frag.CIcoeffs = init_CIcoeffs_list[cnt] + 0.5*m2_list[cnt]\n\n l3, k3_list, m3_list = self.one_rk_step(nproc)\n\n self.tot_system.mf1RDM = init_mf1RDM + 1.0*l3\n for cnt, frag in enumerate(self.tot_system.frag_list):\n frag.rotmat = init_rotmat_list[cnt] + 1.0*k3_list[cnt]\n frag.CIcoeffs = init_CIcoeffs_list[cnt] + 1.0*m3_list[cnt]\n\n l4, k4_list, m4_list = self.one_rk_step(nproc)\n\n #Update MF 1RDM, emb orbs and CI coefficients by full time-step\n self.tot_system.mf1RDM = init_mf1RDM + 1.0/6.0 * ( l1 + 2.0*l2 + 2.0*l3 + l4 )\n for cnt, frag in enumerate( self.tot_system.frag_list ):\n frag.rotmat = init_rotmat_list[cnt] + 1.0/6.0 * ( k1_list[cnt] + 2.0*k2_list[cnt] + 2.0*k3_list[cnt] + k4_list[cnt] )\n frag.CIcoeffs = init_CIcoeffs_list[cnt] + 1.0/6.0 * ( m1_list[cnt] + 2.0*m2_list[cnt] + 2.0*m3_list[cnt] + m4_list[cnt] )\n\n elif( self.integ == 'exact' ):\n #Exactly propagate CI coefficients\n #Only works if have 2 fragments, each spanning full space since then embedding hamiltonian is time-independent\n #and embedding orbitals are time-independent\n #Embedding hamiltonian must also be real\n\n #Calculate embedding hamiltonian (isnt technically needed since it doesnt change)\n self.tot_system.get_frag_Hemb(nproc)\n\n #Form FCI hamiltonian (technically only need to do this at time zero since doesnt change)\n for frag in self.tot_system.frag_list:\n dim1 = frag.CIcoeffs.shape[0]\n dim2 = frag.CIcoeffs.shape[1]\n Ndet = dim1*dim2\n H_fci = np.zeros( [Ndet,Ndet] )\n for i1 in range(dim1):\n for i2 in range(dim2):\n vec1 = np.zeros([dim1,dim2])\n vec1[i1,i2] = 1.0\n i = i2 + i1*dim2\n for j1 in range(dim1):\n for j2 in range(dim2):\n j = j2 + j1*dim2\n vec2 = np.zeros([dim1,dim2])\n vec2[j1,j2] = 1.0\n\n H_fci[i,j] = pyscf.fci.addons.overlap( vec1, np.real(applyham_pyscf.apply_ham_pyscf_fully_complex( vec2, frag.h_emb, frag.V_emb, frag.Nimp, frag.Nimp, 2*frag.Nimp, frag.Ecore )), 2*frag.Nimp, (frag.Nimp,frag.Nimp) )\n\n #Convert matrix of CI coeffs to a vector\n CIvec = frag.CIcoeffs.flatten('F')\n\n #Exactly integrate the CI coefficients using the FCI hamiltonian\n frag.CIcoeffs = integrators.exact_timeindep_coeff_matrix( CIvec, H_fci, self.delt ).reshape((dim1,dim2), order='F')\n\n else:\n print('ERROR: A proper integrator was not specified')\n print()\n exit()\n \n\n #####################################################################\n\n def one_rk_step( self, nproc ):\n #Subroutine to calculate one change in a runge-kutta step of any order\n #Using EOM that integrates CI coefficients and MF 1RDM \n #embedding orbitals obtained by diagonalizing MF 1RDM at each step\n #Prior to calling this routine need to update MF 1RDM and CI coefficients\n\n t1 = time.time() #grr\n\n #calculate the terms needed for time-derivative of mf-1rdm\n self.tot_system.get_frag_corr1RDM()\n self.tot_system.get_glob1RDM()\n self.tot_system.get_nat_orbs()\n\n t2 = time.time() #grr\n\n #calculate embedding hamiltonian\n self.tot_system.get_frag_Hemb()\n\n #Make sure Ecore for each fragment is 0 for dynamics\n for frag in self.tot_system.frag_list:\n frag.Ecore = 0.0\n\n t3 = time.time() #grr\n\n #Calculate change in mf1RDM\n change_mf1RDM = mf1rdm_timedep_mod.get_ddt_mf1rdm_serial( self.tot_system, round(self.tot_system.Nele/2), nproc )\n\n t4 = time.time() #grr\n\n #Use change in mf1RDM to calculate X-matrix for each fragment\n self.tot_system.get_frag_Xmat( change_mf1RDM )\n\n t5 = time.time() #grr\n\n #Multiply change in mf1RDM by time-step\n change_mf1RDM *= self.delt\n\n t6 =time.time() #grr\n\n #Calculate change in embedding orbitals\n change_rotmat_list = []\n for frag in self.tot_system.frag_list:\n change_rotmat_list.append( -1j * self.delt * np.dot( frag.rotmat, frag.Xmat ) )\n\n t7 = time.time() #grr\n\n #Calculate change in CI coefficients in parallel\n if( nproc == 1 ):\n change_CIcoeffs_list = []\n\n for ifrag, frag in enumerate(self.tot_system.frag_list):\n change_CIcoeffs_list.append( applyham_wrapper( frag, self.delt ) )\n\n else:\n frag_pool = multproc.Pool(nproc)\n change_CIcoeffs_list = frag_pool.starmap( applyham_wrapper, [(frag,self.delt) for frag in self.tot_system.frag_list] )\n frag_pool.close()\n\n t8 = time.time() #grr\n\n ##grr\n #print( 'get stuff = ',t2-t1 )\n #print( 'hemb = ',t3-t2)\n #print( 'change mf1rdm = ',t4-t3)\n #print( 'Xmat = ',t5-t4)\n #print( 'prop orbs = ',t7-t6)\n #print( 'prop CI = ',t8-t7)\n #print( 'tot rk step =',t8-t1)\n #print()\n #print('---------------------------')\n #print()\n\n return change_mf1RDM, change_rotmat_list, change_CIcoeffs_list\n\n #####################################################################\n\n def print_data( self, current_time ):\n #Subroutine to calculate and print-out observables of interest\n\n fmt_str = '%20.8e'\n\n ######## CALCULATE OBSERVABLES OF INTEREST #######\n\n #Calculate DMET energy, which also includes calculation of 1 & 2 RDMs and embedding hamiltonian for each fragment\n self.tot_system.get_DMET_E( self.nproc )\n\n #Calculate total number of electrons\n self.tot_system.get_DMET_Nele()\n\n ####msh####\n frag = self.tot_system.frag_list[0]\n #Efci = fci_mod.get_FCI_E( frag.h_emb, frag.V_emb, 0.0, frag.CIcoeffs, 2*frag.Nimp, frag.Nimp, frag.Nimp )\n #print( Efci, file=self.file_test )\n testdata = np.zeros(3+self.tot_system.Nsites)\n testdata[0] = current_time\n testdata[1] = np.linalg.norm( frag.CIcoeffs )**2\n testdata[2] = np.real( np.sum( np.diag( frag.corr1RDM ) ) )\n testdata[3:] = np.copy( np.real( np.diag( np.dot( utils.adjoint( frag.rotmat ), frag.rotmat ) ) ) )\n np.savetxt( self.file_test, testdata.reshape(1, testdata.shape[0]), fmt_str )\n self.file_test.flush()\n ###########\n\n\n ######## PRINT OUT EVERYTHING #######\n\n #Print correlated density in the site basis\n cnt = 0\n corrdens = np.zeros(self.tot_system.Nsites)\n for frag in self.tot_system.frag_list:\n corrdens[cnt:cnt+frag.Nimp] = np.copy( np.diag( np.real( frag.corr1RDM[:frag.Nimp] ) ) )\n cnt += frag.Nimp\n corrdens = np.insert( corrdens, 0, current_time )\n np.savetxt( self.file_corrdens, corrdens.reshape(1, corrdens.shape[0]), fmt_str )\n self.file_corrdens.flush()\n\n #Print output data\n output = np.zeros(3)\n output[0] = current_time\n output[1] = self.tot_system.DMET_E\n output[2] = self.tot_system.DMET_Nele\n np.savetxt( self.file_output, output.reshape(1, output.shape[0]), fmt_str )\n self.file_output.flush()\n\n #Save total system to file for restart purposes using pickle\n file_system = open( 'restart_system.dat', 'wb' )\n pickle.dump( self.tot_system, file_system )\n file_system.close()\n\n#####################################################################\n\ndef applyham_wrapper( frag, delt ):\n\n #Subroutine to call pyscf to apply FCI hamiltonian onto FCI vector in dynamics\n #Includes the -1j*timestep term and the addition of bath-bath terms of X-matrix to embedding Hamiltonian\n #The wrapper is necessary to parallelize using Pool and must be separate from\n #the class because the class includes IO file types (annoying and ugly but it works)\n\n Xmat_sml = np.zeros( [ 2*frag.Nimp, 2*frag.Nimp ], dtype = complex )\n Xmat_sml[ frag.Nimp:, frag.Nimp: ] = frag.Xmat[ frag.bathrange[:,None], frag.bathrange ]\n\n return -1j * delt * applyham_pyscf.apply_ham_pyscf_fully_complex( frag.CIcoeffs, frag.h_emb-Xmat_sml, frag.V_emb, frag.Nimp, frag.Nimp, 2*frag.Nimp, frag.Ecore )\n\n#####################################################################\n\n\n","sub_path":"dynamics_driver.py","file_name":"dynamics_driver.py","file_ext":"py","file_size_in_byte":14789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"287835376","text":"\"\"\"\n1861. Rat Jump\nhttps://www.lintcode.com/problem/rat-jump/description?_from=ladder&&fromId=160\n九章高频题班 google\n\nodd_steps = [1, 3, 4]\neven_steps = [1, 2, 4]\n\ndp[i][even/odd] : number of ways to jump to position i and even/odd step next\n\ndp[i + even_steps[j]][DataType.ODD] += dp[i][DataType.EVEN] for j in range(3)\ndp[i + odd_steps[j]][DataType.EVEN] += dp[i][DataType.ODD] for j in range(3)\n\nif i + enve_steps[j] > n - 1 (past 0), count everything into last step n - 1\n\ninitial condition\ndp[0][DataType.ODD] = 1\n\nanswer\n\ndp[n - 1][ODD] + dp[n - 1][EVEN]\n\"\"\"\nclass DataType:\n ODD = 1\n EVEN = 0\n\nclass Solution:\n \"\"\"\n @param arr: the steps whether have glue\n @return: the sum of the answers\n \"\"\"\n def ratJump(self, arr):\n # Write your code here.\n MOD = int(1e9 + 7)\n if not arr:\n return 0\n n = len(arr)\n odd_steps = [1, 2, 4]\n even_steps = [1, 3, 4]\n \n\n dp = [[0] * 2 for _ in range(n)]\n\n dp[0][DataType.ODD] = 1\n\n for i in range(n - 1): #n = 3, 0, 1, 2, at n - 1, it is already at ground, so cannot jump, so last number is n -2\n for j in range(3):\n if i + even_steps[j] > n - 1 or arr[i + even_steps[j]] == 0:\n dp[min(i + even_steps[j], n - 1)][DataType.ODD] += dp[i][DataType.EVEN] % MOD\n if i + odd_steps[j] > n - 1 or arr[i + odd_steps[j]] == 0:\n dp[min(i + odd_steps[j], n - 1)][DataType.EVEN] += dp[i][DataType.ODD] % MOD\n\n return sum(dp[n - 1]) % MOD","sub_path":"lintcode/1861.py","file_name":"1861.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"568669224","text":"def knapsackLight(value1, weight1, value2, weight2, maxW):\n \n ans = 0\n \n if value1 < value2:\n \n value1,value2 = value2,value1\n weight1,weight2 = weight2,weight1\n \n if weight1 <= maxW:\n \n ans = value1\n maxW -= weight1\n \n if weight2 <= maxW:\n \n ans += value2\n \n return ans\n\n","sub_path":"knapsackLight.py3","file_name":"knapsackLight.py3","file_ext":"py3","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"502259060","text":"import netCDF4\nimport numpy as np\n\ndef to_netcdf_old(meshgeom, path):\n\n outformat = \"NETCDF3_CLASSIC\"\n ncfile = netCDF4.Dataset(path, 'w', format=outformat)\n\n ncfile.createDimension(\"nNetNode\", meshgeom.meshgeomdim.numnode)\n ncfile.createDimension(\"nNetLink\", meshgeom.meshgeomdim.numedge)\n ncfile.createDimension(\"Two\", 2)\n\n # Mesh2D\n mesh2d = ncfile.createVariable(\"Mesh2D\", \"i4\", ())\n mesh2d.cf_role = 'mesh_topology'\n mesh2d.node_coordinates = 'NetNode_x NetNode_y'\n mesh2d.node_dimension = 'nNetNode'\n mesh2d.edge_node_connectivity = 'NetLink'\n mesh2d.edge_dimension = 'nNetLink'\n mesh2d.topology_dimension = 1\n\n # Nodes:\n for dim in list('xyz'):\n ncvar = ncfile.createVariable(f\"NetNode_{dim}\", \"f8\", mesh2d.node_dimension)\n ncvar.units = 'm'\n\n if dim == 'z':\n ncvar.mesh = 'Mesh2D'\n ncvar.coordinates = 'NetNode_x NetNode_y'\n ncvar[:] = np.zeros(meshgeom.meshgeomdim.numnode)\n\n else:\n ncvar[:] = meshgeom.get_values(f'node{dim}')\n\n\n # Links\n ncvar = ncfile.createVariable(\"NetLink\", \"i4\", ( mesh2d.edge_dimension, \"Two\"))\n links = meshgeom.get_values('edge_nodes', as_array=True)\n ncvar[:] = links.tolist()\n # ncvar\n\n ncvar = ncfile.createVariable(\"NetLinkType\", \"i4\", mesh2d.edge_dimension)\n ncvar[:] = np.ones(len(links), dtype=int) * 2\n\n ncfile.close()\n\ndef from_netcdf_old(meshgeom, path):\n ds = netCDF4.Dataset(path, 'r')\n\n meshgeom.meshgeomdim.numnode = ds.dimensions['nNetNode'].size\n meshgeom.meshgeomdim.numedge = ds.dimensions['nNetLink'].size\n\n for dim in list('xyz'):\n # Get values\n data = ds.variables[f'NetNode_{dim}'][:]\n # Allocate\n meshgeom.allocate(f'node{dim}')\n # Set values\n meshgeom.set_values(f'node{dim}', data)\n\n # Set links\n meshgeom.allocate(f'edge_nodes')\n meshgeom.set_values('edge_nodes', ds.variables['NetLink'][:, :].ravel())\n\n ds.close()","sub_path":"delft3dfmpy/io/gridio.py","file_name":"gridio.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"387883287","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def rotateRight(self, head: ListNode, k: int) -> ListNode:\n if head is None: return None\n if k == 0: return head\n cur_node, tail_node, list_length = head, None, 0\n while cur_node is not None:\n next_node = cur_node.next\n tail_node = cur_node\n list_length += 1\n cur_node = next_node\n if list_length == 1:\n return head\n num_rot = list_length - (k % list_length)\n cur_head, cur_tail = head, tail_node\n while num_rot > 0:\n assert cur_head is not None\n next_head = cur_head.next\n cur_head.next = None\n cur_tail.next = cur_head\n cur_head = next_head\n cur_tail = cur_tail.next\n num_rot -= 1\n return cur_head\n \n","sub_path":"Practice-2020/October/Python/rotate_list.py","file_name":"rotate_list.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"159909248","text":"#check_for_leap_year\n#La reglas generales \n# si un año (2010, 2000 ,1956) es divisible por 4 será bisiesto\n # a no ser de que el año en sí sea divisible por 100 , como por ejemplo (2100, 1900, 1600)\n # pero, si se cancela por la anterior regla, aún puede ser bisiesto si es divisible por 400\n\ndef main(year):\n\n # Si es divisible por 4\n if year % 4 == 0:\n # Si no es divisible por 10 O lo es por 400 (bisiesto)\n if year % 100 != 0 or year % 400 == 0:\n print(\"El año ingresado es bisiesto\\n\") \n return # Un return que reinicie el bucle para solo utilizar un mensaje negativo \n \n print(\"El año ingresado no es bisiesto\\n\")\n\nif __name__ == '__main__':\n while True:\n #Recibir las medidas por parte del usuario\n year = input('Ingrese el año a evaluar eg : \\'2015,2020,1942\\'\\n Ingrese \\'exit\\' para salir.\\n>>')\n\n #Comprobar por fin del programa\n if year.lower() == 'exit':\n print(\"Saliendo ...\")\n break\n main(int(year))\n \n","sub_path":"494.py","file_name":"494.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"168374037","text":"# Import the necessary libraries\nimport numpy\nimport seaborn as sns\nimport matplotlib.pyplot as plot\nimport pandas\nfrom sklearn import metrics\nfrom sklearn.model_selection import ShuffleSplit\nfrom sklearn.model_selection import KFold\nfrom sklearn.ensemble import AdaBoostRegressor\nfrom sklearn.datasets import make_regression\n\n# Import the dataset\ndataset = pandas.read_csv('BostonHousing.csv')\n\n#Explore the dataset\nprint(dataset.shape) \nprint(dataset.head(5))\n\n# Differentiate attribute and target columns \nY = dataset['medv'].values\nX = dataset[['rm','ptratio','lstat']].values \n\npredicted_y = []\nexpected_y = []\n\n#Applying K-fold cross validation\nkf = KFold(n_splits=4,shuffle=True)\nfor train_index, test_index in kf.split(X):\n x_train, x_test = X[train_index], X[test_index]\n y_train, y_test = Y[train_index], Y[test_index]\n \n ada_reg = AdaBoostRegressor(n_estimators=100)\n ada_reg.fit(x_train, y_train)\n \n predicted_y.extend(ada_reg.predict(x_test))\n expected_y.extend(y_test)\n \ndf = pandas.DataFrame({'Actual': expected_y, 'Predicted': predicted_y})\nprint(df.head(20))\n\n#showing bar chart\ndf1 = df.head(30)\ndf1.plot(kind='bar')\nplot.show()\n\n#showing plot\nx_ax = range(len(expected_y))\nplot.scatter(x_ax, expected_y, s=5, color=\"blue\", label=\"original\")\nplot.plot(x_ax, predicted_y, lw=0.8, color=\"red\", label=\"predicted\")\nplot.legend()\nplot.show()\n\nprint('\\nMean Absolute Error:', metrics.mean_absolute_error(expected_y, predicted_y))\nprint('Median Absolute Error:', metrics.median_absolute_error(expected_y, predicted_y)) \nprint('Mean Squared Error:', metrics.mean_squared_error(expected_y, predicted_y) ) \nprint('Root Mean Squared Error:', numpy.sqrt(metrics.mean_squared_error(expected_y, predicted_y)))\n\n\n","sub_path":"Artificial Intilligence/term project 3/Codes/adaptive_boosting_tp3.py","file_name":"adaptive_boosting_tp3.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"162861004","text":"# Copyright 2019 kubeflow.org.\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.\nimport time\nfrom kfserving import KFServingClient\n\nKFServing = KFServingClient(load_kube_config=True)\n\ndef wait_for_kfservice_ready(name, namespace='kfserving-ci-e2e-test', Timeout_seconds=600):\n for _ in range(round(Timeout_seconds/10)):\n time.sleep(10)\n kfsvc_status = KFServing.get(name, namespace=namespace)\n for condition in kfsvc_status['status'].get('conditions', {}):\n if condition.get('type', '') == 'Ready':\n status = condition.get('status', 'Unknown')\n if status == 'True':\n return\n raise RuntimeError(\"Timeout to start the KFService.\")\n","sub_path":"test/e2e/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"160928556","text":"from tiddlyweb.web.validator import TIDDLER_VALIDATORS \nfrom tiddlyweb.model.tiddler import Tiddler \nimport logging\nfrom BeautifulSoup import BeautifulSoup, Comment\nimport re\n\n\"\"\"\nsanitise any input that has unauthorised javascript/html tags in it\n\nLet through only tags and attributes in the whitelists ALLOWED_TAGS and ALLOWED_ATTRIBUTES\n\"\"\"\n\nALLOWED_TAGS=[ \n 'html',\n 'p',\n 'i',\n 'strong',\n 'b',\n 'u',\n 'a',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'pre',\n 'br',\n 'img',\n 'span',\n 'em',\n 'strike',\n 'sub',\n 'sup',\n 'address',\n 'font',\n 'table',\n 'tbody',\n 'tr',\n 'td',\n 'ol',\n 'ul',\n 'li',\n 'div'\n]\nALLOWED_ATTRIBUTES=[\n 'href',\n 'src',\n 'alt',\n 'title'\n] \n\ndef sanitise_html(value): \n \n #match dangerous attribute values (eg javascript:) with regex\n r = re.compile(r'[\\s]*(&#x.{1,7})?'.join(list('javascript:'))) \n \n #turn the input into a BeautifulSoup parse tree\n soup = BeautifulSoup(value) \n \n #get all HTML comments () and remove them\n for comment in soup.findAll(text=lambda text: isinstance(text, Comment)): \n comment.extract() \n \n #Check all tags against the allowed set and remove any that are not found\n for tag in soup.findAll(True):\n if tag.name not in ALLOWED_TAGS:\n tag.hidden = True\n #check that attribute/value pairs against the allowed list and regex and cut any that are not allowed\n tag.attrs = [(attr, r.sub('', val)) for attr, val in tag.attrs\n if attr in ALLOWED_ATTRIBUTES]\n return soup.renderContents().decode('utf8')\n\ndef sanitise_xss(tiddler,environ):\n for field,value in tiddler.fields.iteritems(): \n tiddler.fields[field] = sanitise_html(value)\n tiddler.text = sanitise_html(tiddler.text) \n tiddler.tags = map(sanitise_html,tiddler.tags)\n tiddler.title = sanitise_html(tiddler.title)\n\ndef init(config_in):\n \"\"\"\n init function\n \"\"\"\n TIDDLER_VALIDATORS.append(sanitise_xss)\n\n","sub_path":"venv/Lib/site-packages/html_validator.py","file_name":"html_validator.py","file_ext":"py","file_size_in_byte":2163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"347171067","text":"\"\"\"core URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', 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: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\n\nfrom core.products.views import show_listed_products\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^$', show_listed_products, name='index_view'),\n url(r'^accounts/', include('core.accounts.urls', namespace='accounts')),\n url(r'^products/', include('core.products.urls', namespace='products')),\n url(r'^contact/', include('core.mailer.urls', namespace='mailer')),\n url(r'^cart/', include('core.cart.urls', namespace='cart')),\n]\n","sub_path":"src/core/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"51736631","text":"import uuid\nfrom flask import request\nfrom flask_restplus import Resource, reqparse\nfrom sqlalchemy_filters import apply_sort, apply_pagination, apply_filters\nfrom sqlalchemy import and_\n\nfrom ..models.party import Party\nfrom ..models.party_type_code import PartyTypeCode\nfrom ...party_appt.models.mine_party_appt import MinePartyAppointment\n\nfrom ....constants import PARTY_STATUS_CODE\nfrom app.extensions import api\nfrom ....utils.access_decorators import requires_role_mine_view, requires_role_mine_create, requires_any_of, MINE_VIEW, MINESPACE_PROPONENT\n\nfrom ....utils.resources_mixins import UserMixin, ErrorMixin\n\n\nclass PartyAdvancedSearchResource(Resource, UserMixin, ErrorMixin):\n parser = reqparse.RequestParser()\n parser.add_argument('first_name', type=str,\n help='First name of the party, if the party is a person.', trim=True)\n parser.add_argument('last_name', type=str,\n help='Last name of the party, if the party is a person.', trim=True)\n parser.add_argument('party_name', type=str,\n help='Last name of the party (Person), or the Organization name (Organization).', trim=True)\n parser.add_argument('phone_no', type=str,\n help='The phone number of the party. Ex: 123-123-1234', trim=True)\n parser.add_argument('phone_ext', type=str, help='The extension of the phone number. Ex: 1234', trim=True)\n parser.add_argument('email', type=str, help='The email of the party.', trim=True)\n parser.add_argument('type', type=str, help='The type of the party. Ex: PER')\n parser.add_argument('page', 1, type=int, help='The page of the results.')\n parser.add_argument('per_page', 25, type=int, help='The number of parties per page.')\n parser.add_argument('role', type=str, help='The role of a user. Ex: MMG for Mine Manager')\n PARTY_LIST_RESULT_LIMIT = 25\n\n\n @api.doc(\n params={\n 'first_name': 'First name of party or contact',\n 'party_name': 'Last name or party name of person or organisation',\n 'phone_no': 'phone number',\n 'email': 'email of person or organisation',\n 'type': 'A person (PER) or organisation (ORG)',\n 'role': 'A comma separated list of roles to be filtered by'\n })\n @requires_any_of([MINE_VIEW, MINESPACE_PROPONENT])\n def get(self):\n paginated_parties, pagination_details = self.apply_filter_and_search(self.parser.parse_args())\n if not paginated_parties:\n self.raise_error(\n 404,\n 'No parties found'\n ), 404\n parties = paginated_parties.all()\n return {\n 'parties': list(map(lambda x: x.json(relationships=['mine_party_appt']), parties)),\n 'current_page': pagination_details.page_number,\n 'total_pages': pagination_details.num_pages,\n 'items_per_page': pagination_details.page_size,\n 'total': pagination_details.total_results,\n }\n\n def apply_filter_and_search(self, args):\n # Handle ListView request\n items_per_page = args['per_page']\n page = args['page']\n # parse the filter terms\n first_name_filter_term = args['first_name']\n last_name_filter_term = args['last_name']\n party_name_filter_term = args['party_name']\n type_filter_term = args['type']\n role_filter_term = args['role']\n email_filter_term = args['email']\n phone_filter_term = args['phone_no']\n\n conditions = [Party.deleted_ind == False]\n if first_name_filter_term:\n conditions.append(Party.first_name.ilike('%{}%'.format(first_name_filter_term)))\n if last_name_filter_term:\n conditions.append(Party.party_name.ilike('%{}%'.format(last_name_filter_term)))\n if party_name_filter_term:\n conditions.append(Party.party_name.ilike('%{}%'.format(party_name_filter_term)))\n if email_filter_term:\n conditions.append(Party.email.ilike('%{}%'.format(email_filter_term)))\n if type_filter_term:\n conditions.append(Party.party_type_code.like(type_filter_term))\n if phone_filter_term:\n conditions.append(Party.phone_no.ilike('%{}%'.format(phone_filter_term)))\n if role_filter_term == \"NONE\":\n conditions.append(Party.mine_party_appt == None)\n contact_query = Party.query.filter(and_(*conditions))\n if role_filter_term and not role_filter_term == \"NONE\":\n role_filter = MinePartyAppointment.mine_party_appt_type_code.like(role_filter_term)\n role_query = Party.query.join(MinePartyAppointment).filter(role_filter)\n contact_query = contact_query.intersect(role_query) if contact_query else role_query\n\n sort_criteria = [{'model': 'Party', 'field': 'party_name', 'direction': 'asc'}]\n contact_query = apply_sort(contact_query, sort_criteria)\n return apply_pagination(contact_query, page, items_per_page)\n","sub_path":"python-backend/app/api/parties/party/resources/party_advance_search_resource.py","file_name":"party_advance_search_resource.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"215067561","text":"# 20190522 Lab03\n# 자연수 a를 입력 받아서 a의 모든 약수를 출력하는 프로그램을 작성하시오\n#\n# 입력: 자연수 a\n# 출력: a의 모든 약수\n\ntarget = int(input('자연수 하나를 입력하세요: '))\nprint('약수의 값: ')\nfor i in range(1,target+1):\n if target % i == 0:\n print(i,end=\" \")\n\n","sub_path":"20190522 Practice/Lab03.py","file_name":"Lab03.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"46391987","text":"import os\nimport sys\n\ncwd = os.getcwd()\nsys.path.append(cwd)\nimport pickle\n\nimport numpy as np\nimport matplotlib\n\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\n\nfrom plot.helper import plot_joints, plot_task, plot_weights, plot_rf_z_max, plot_rf, plot_vector_traj\n\ntasks = [\n 'task_com_pos', 'task_com_vel', 'task_torso_ori', 'task_torso_ang_vel',\n 'task_rfoot_pos', 'task_rfoot_vel', 'task_rfoot_ori', 'task_rfoot_ang_vel',\n 'task_lfoot_pos', 'task_lfoot_vel', 'task_lfoot_ori', 'task_lfoot_ang_vel',\n 'task_upper_body_pos', 'task_upper_body_vel'\n]\n\nneck_pos_label = [\"neck_pitch\"]\n\nrfoot_label = [\n \"r_hip_ie\", \"r_hip_aa\", \"r_hip_fe\", \"r_knee_fe_jp\", \"r_knee_fe_jd\",\n \"r_ankle_fe\", \"r_ankle_ie\"\n]\n\nlfoot_label = [\n \"l_hip_ie\", \"l_hip_aa\", \"l_hip_fe\", \"l_knee_fe_jp\", \"l_knee_fe_jd\",\n \"l_ankle_fe\", \"l_ankle_ie\"\n]\n\nupper_body_pos_label = [\n \"neck_pitch\", \"l_shoulder_fe\", \"l_shoulder_aa\", \"l_shoulder_ie\",\n \"l_elbow_fe\", \"l_wrist_ps\", \"l_wrist_pitch\", \"r_shoulder_fe\",\n \"r_shoulder_aa\", \"r_shoulder_ie\", \"r_elbow_fe\", \"r_wrist_ps\",\n \"r_wrist_pitch\"\n]\n\njoint_label = [\n \"l_hip_ie\", \"l_hip_aa\", \"l_hip_fe\", \"l_knee_fe_jp\", \"l_knee_fe_jd\",\n \"l_ankle_fe\", \"l_ankle_ie\", \"l_shoulder_fe\", \"l_shoulder_aa\",\n \"l_shoulder_ie\", \"l_elbow_fe\", \"l_wrist_ps\", \"l_wrist_pitch\", \"neck_pitch\",\n \"r_hip_ie\", \"r_hip_aa\", \"r_hip_fe\", \"r_knee_fe_jp\", \"r_knee_fe_jd\",\n \"r_ankle_fe\", \"r_ankle_ie\", \"r_shoulder_fe\", \"r_shoulder_aa\",\n \"r_shoulder_ie\", \"r_elbow_fe\", \"r_wrist_ps\", \"r_wrist_pitch\"\n]\n\ntime = []\n\nphase = []\n\ncmd_lfoot_rf = []\ncmd_rfoot_rf = []\n\ncmd_joint_positions = []\ncmd_joint_velocities = []\ncmd_joint_torques = []\njoint_positions = []\njoint_velocities = []\n\ntask_com_local_pos_err = []\ntask_torso_ori_local_pos_err = []\n\ndes, act = dict(), dict()\nfor topic in tasks:\n des[topic] = []\n act[topic] = []\nw = dict()\n\nwith open('experiment_data/pnc.pkl', 'rb') as file:\n while True:\n try:\n d = pickle.load(file)\n time.append(d['time'])\n phase.append(d['phase'])\n for topic in tasks:\n des[topic].append(d[topic + '_des'])\n act[topic].append(d[topic])\n cmd_lfoot_rf.append(d['cmd_lfoot_rf'])\n cmd_rfoot_rf.append(d['cmd_rfoot_rf'])\n cmd_joint_positions.append(d['cmd_joint_positions'])\n cmd_joint_velocities.append(d['cmd_joint_velocities'])\n cmd_joint_torques.append(d['cmd_joint_torques'])\n joint_positions.append(d['joint_positions'])\n joint_velocities.append(d['joint_velocities'])\n task_com_local_pos_err.append(d['task_com_local_pos_err'])\n task_torso_ori_local_pos_err.append(\n d['task_torso_ori_local_pos_err'])\n except EOFError:\n break\n\nfor k, v in des.items():\n des[k] = np.stack(v, axis=0)\nfor k, v in act.items():\n act[k] = np.stack(v, axis=0)\n# right foot first\ncmd_rf = np.concatenate((cmd_rfoot_rf, cmd_lfoot_rf), axis=1)\nphase = np.stack(phase, axis=0)\ncmd_joint_positions = np.stack(cmd_joint_positions, axis=0)\ncmd_joint_velocities = np.stack(cmd_joint_velocities, axis=0)\ncmd_joint_torques = np.stack(cmd_joint_torques, axis=0)\njoint_positions = np.stack(joint_positions, axis=0)\njoint_velocities = np.stack(joint_velocities, axis=0)\ntask_com_local_pos_err = np.stack(task_com_local_pos_err, axis=0)\ntask_torso_ori_local_pos_err = np.stack(task_torso_ori_local_pos_err, axis=0)\n\n## =============================================================================\n## Plot Task\n## =============================================================================\n\nplot_task(time, des['task_com_pos'], act['task_com_pos'], des['task_com_vel'],\n act['task_com_vel'], phase, 'com lin')\n\nplot_vector_traj(time, task_com_local_pos_err, phase, ['x', 'y', 'z'], 'k',\n \"local com pos err\")\nplot_vector_traj(time, task_torso_ori_local_pos_err, phase, ['x', 'y', 'z'],\n 'k', \"local torso ori pos err\")\n\nplot_task(time, des['task_torso_ori'], act['task_torso_ori'],\n des['task_torso_ang_vel'], act['task_torso_ang_vel'], phase,\n 'torso ori')\n\nfor i in range(3):\n slc = slice(5 * i, 5 * (i + 1))\n plot_task(time,\n des['task_upper_body_pos'][:, slc],\n act['task_upper_body_pos'][:, slc],\n des['task_upper_body_vel'][:, slc],\n act['task_upper_body_vel'][:, slc],\n phase,\n 'upper body',\n label=upper_body_pos_label[slc])\n\nplot_task(time, des['task_lfoot_pos'], act['task_lfoot_pos'],\n des['task_lfoot_vel'], act['task_lfoot_vel'], phase, 'left foot lin')\n\nplot_task(time, des['task_lfoot_ori'], act['task_lfoot_ori'],\n des['task_lfoot_ang_vel'], act['task_lfoot_ang_vel'], phase,\n 'left foot ori')\n\nplot_task(time, des['task_rfoot_pos'], act['task_rfoot_pos'],\n des['task_rfoot_vel'], act['task_rfoot_vel'], phase,\n 'right foot lin')\n\nplot_task(time, des['task_rfoot_ori'], act['task_rfoot_ori'],\n des['task_rfoot_ang_vel'], act['task_rfoot_ang_vel'], phase,\n 'right foot ori')\n\n## =============================================================================\n## Plot WBC Solutions\n## =============================================================================\nplot_rf(time, cmd_rf, phase) # assume top six is right foot\n\nplot_joints(joint_label, rfoot_label, time, cmd_joint_positions,\n joint_positions, cmd_joint_velocities, joint_velocities,\n cmd_joint_torques, phase, \"rfoot\")\n\nplot_joints(joint_label, lfoot_label, time, cmd_joint_positions,\n joint_positions, cmd_joint_velocities, joint_velocities,\n cmd_joint_torques, phase, \"lfoot\")\n\nplt.show()\n","sub_path":"plot/draco/plot_wbc.py","file_name":"plot_wbc.py","file_ext":"py","file_size_in_byte":5794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"136327287","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import _, api, fields, models\nfrom odoo.exceptions import UserError, ValidationError\n\nclass SaleReport(models.Model):\n _inherit = \"sale.report\"\n\n partner_id = fields.Many2one('res.partner', 'Headoffice', readonly=True)\n branch_id = fields.Many2one('ioud_branches.ioud_branches', readonly=True)\n\n def _query(self, with_clause='', fields={}, groupby='', from_clause=''):\n fields['branch_id'] = \", s.branch_id as branch_id\"\n groupby += ', s.branch_id'\n return super(SaleReport, self)._query(with_clause, fields, groupby, from_clause)","sub_path":"ioud/ioud_sale_order/models/sale_order_report.py","file_name":"sale_order_report.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"268605986","text":"import requests\r\nimport json\r\nimport csv\r\n\r\n# url要写抓到的GET :URL\r\nurl = \"https://movie.douban.com/j/chart/top_list?\"\r\nheaders = {\"User-Agent\":\"Mozilla/5.0\"}\r\nnum = input(\"请输入要爬取的数量:\")\r\nparams = {\r\n \"type\":\"11\",\r\n \"interval_id\":\"100:90\",\r\n \"action\":\"\",\t\r\n \"start\":\"0\",\r\n \"limit\":num\r\n }\r\n\r\nres = requests.get(url,params=params,headers=headers)\r\nres.encoding = \"utf-8\"\r\n# html为json格式的数组[{电影1信息},{},{}]\r\nhtml = res.text\r\n# 数组 -> 列表\r\nhtml = json.loads(html)\r\n# 用for循环遍历每一个电影信息{}\r\nfor film in html:\r\n name = film['title']\r\n score = film[\"rating\"][0]\r\n #{\"rating\":[\"9.6\",\"50\"],...}\r\n with open(\"豆瓣电影.csv\",\"a\",newline=\"\") as f:\r\n writer = csv.writer(f)\r\n L = [name,score]\r\n writer.writerow(L)\r\n ","sub_path":"豆瓣电影1.py","file_name":"豆瓣电影1.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"259987401","text":"__author__ = 'yi-linghwong'\n\nimport sys\nimport os\nimport operator\nimport pandas as pd\nfrom sklearn import cross_validation\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\n#from sklearn.naive_bayes import BernoulliNB\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.grid_search import GridSearchCV\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.cross_validation import StratifiedShuffleSplit\nfrom sklearn.cross_validation import StratifiedKFold\nfrom sklearn.cross_validation import cross_val_score\n#from sklearn.feature_selection import RFE\nfrom sklearn.feature_selection import RFECV\n#from sklearn.feature_selection import SelectKBest\nfrom sklearn.feature_selection import SelectPercentile\nfrom sklearn.feature_selection import chi2, f_classif\nfrom sklearn import metrics\nimport numpy as np\nimport scipy as sp\nfrom sklearn.feature_extraction import text\nimport matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\n\n\nclass PrincipalComponentAnalysis():\n\n def train_test_split(self):\n\n #################\n #Split the dataset in training and test set:\n #################\n\n docs_train, docs_test, y_train, y_test = train_test_split(X, y, test_size=0.0, random_state=42)\n\n print (\"Number of data point is \"+str(len(y)))\n\n return docs_train, docs_test, y_train, y_test\n\n\n def do_pca(self):\n\n # Get list of features\n count_vect = CountVectorizer(stop_words=stopwords, min_df=3, max_df=0.90, ngram_range=(1,1))\n X_CV = count_vect.fit_transform(docs_train)\n\n\n # print number of unique words (n_features)\n print (\"Shape of train data is \"+str(X_CV.shape))\n\n # tfidf transformation\n\n tfidf_transformer = TfidfTransformer(use_idf = True)\n X_tfidf = tfidf_transformer.fit_transform(X_CV)\n\n # convert sparse matrix to dense data, pca only takes dense data as input!\n\n X_dense = X_tfidf.toarray()\n\n ################\n # run PCA on dense data\n ################\n\n pca = PCA(n_components=_n_components)\n X_new = pca.fit_transform(X_dense)\n\n print (\"Shape of dense data is \"+str(X_new.shape)) #shape = (n_samples, n_components)\n\n feature_names = count_vect.get_feature_names()\n\n print (\"Number of feature is \"+str(len(feature_names)))\n\n # the first component always has the highest variance\n\n components = pca.components_[0] # shape = (n_components, n_features)\n\n print (\"Explained variance ratio: \"+str(pca.explained_variance_ratio_))\n\n zipped = zip(components,feature_names)\n\n feature_pca = []\n\n for z in zipped:\n z = list(z)\n feature_pca.append(z)\n\n feature_pca.sort(reverse=True)\n\n feature_pca_list = []\n\n for fp in feature_pca:\n feature_pca_list.append([str(fp[0]),fp[1]])\n\n f = open(path_to_store_pca_result_file,'w')\n\n for fp in feature_pca_list:\n f.write(','.join(fp)+'\\n')\n\n f.close()\n\n return\n\n\n def plot_variance_graph(self):\n\n # Get list of features\n count_vect = CountVectorizer(stop_words=stopwords, min_df=3, max_df=0.90, ngram_range=(1,1))\n X_CV = count_vect.fit_transform(docs_train)\n\n # print number of unique words (n_features)\n print (\"Shape of train data is \"+str(X_CV.shape))\n\n # tfidf transformation###\n\n tfidf_transformer = TfidfTransformer(use_idf = True)\n X_tfidf = tfidf_transformer.fit_transform(X_CV)\n\n X_dense = X_tfidf.toarray()\n\n pca = PCA() # if no n_components specified, then n_components = n_features\n\n ###############################################################################\n # Plot the PCA spectrum\n\n pca.fit_transform(X_dense)\n print (\"#############\")\n print (\"Explained variance ratio is \"+str(pca.explained_variance_ratio_))\n\n #plt.figure(1, figsize=(4, 3))\n plt.clf()\n #plt.axes([.2, .2, .7, .7])\n plt.plot(pca.explained_variance_, linewidth=2)\n plt.axis('tight')\n plt.xlabel('n_components')\n plt.ylabel('explained_variance_')\n plt.show()\n\n return\n\n\n################\n# variables\n################\n\npath_to_labelled_file = '../output/features/space/labelled_combined.csv'\npath_to_stopword_file = '../stopwords/stopwords.csv'\npath_to_store_pca_result_file = '../output/pca/space_combined.csv'\n\n# for pca\n_n_components = 5\n\n\ndef get_data_set():\n\n #############\n # Get dataset\n #############\n\n dataset = pd.read_csv(path_to_labelled_file, header=0, names=['tweets', 'class'])\n\n X = dataset['tweets']\n y = dataset['class']\n\n return X,y\n\ndef get_stop_words():\n\n ###########\n # get stopwords\n ###########\n\n lines = open(path_to_stopword_file, 'r').readlines()\n\n my_stopwords=[]\n for line in lines:\n my_stopwords.append(line.replace(\"\\n\", \"\"))\n\n stopwords = text.ENGLISH_STOP_WORDS.union(my_stopwords)\n\n return stopwords\n\n\nif __name__ == '__main__':\n\n X = get_data_set()[0]\n y = get_data_set()[1]\n stopwords = get_stop_words()\n\n pc = PrincipalComponentAnalysis()\n\n ###################\n # split data into training and test set\n ###################\n\n docs_train,docs_test,y_train,y_test = pc.train_test_split()\n\n ###################\n # do PCA and save results to file\n ###################\n\n pc.do_pca()\n\n ###################\n # plot n_components vs variance graph\n ###################\n\n #pc.plot_variance_graph()\n\n","sub_path":"_utilities/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":5722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"41757598","text":"from linked_list import *\n\nclass Solution(object):\n def addTwoNumbers(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n p1, p2 = l1, l2\n carry = 0\n p = fakehead = ListNode(None)\n while p1 or p2 or carry:\n # 用p1Val来表示p1.val这样即使p1无效,p1Val也能正确表示0值参与计算\n p1Val, p2Val = 0, 0\n if p1:\n p1Val = p1.val\n p1 = p1.next\n if p2:\n p2Val = p2.val\n p2 = p2.next\n newSum = p1Val+p2Val+carry\n carry = newSum/10\n p.next=ListNode(newSum%10)\n p = p.next\n return fakehead.next","sub_path":"002_add_two_numbers.py","file_name":"002_add_two_numbers.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"18149551","text":"import tensorflow as tf\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nx_train=np.load(\"C:\\\\Users\\\\chada\\\\Desktop\\\\Nouveau dossier\\\\valeursx.npy\")\r\ny_train=np.load(\"C:\\\\Users\\\\chada\\\\Desktop\\\\Nouveau dossier\\\\valeursy.npy\")\r\n\r\n## 0-1 pas 0-255\r\nx_train = x_train.astype('float32')\r\ny_train = y_train.astype('float32')\r\nx_train = tf.keras.utils.normalize(x_train, axis=-1)\r\n\r\n\r\n##modele\r\nmodel = tf.keras.models.Sequential()\r\nmodel.add(tf.keras.layers.Flatten())\r\nmodel.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))\r\nmodel.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))\r\nmodel.add(tf.keras.layers.Dense(1, activation=tf.nn.softmax)) \r\n##calcul du gradient\r\nmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])\r\n##entrainement\r\nmodel.fit(x_train, y_train, epochs=3)\r\n\r\n##save\r\nmodel.save('simon')\r\n##load\r\nnew_model =tf.keras.models.load_model('simon')\r\n\r\n\r\n##fonctionnement\r\nprediction = new_model.predict(x_train)\r\n# print(prediction)\r\nprint(np.argmax(prediction[0]))\r\nplt.imshow(x_train[0])\r\nplt.show()\r\n\r\n\r\n\r\n","sub_path":"Keras_NN/keras1model.py","file_name":"keras1model.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"37534412","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render\n\n\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view, permission_classes\nfrom rest_framework.permissions import AllowAny\nfrom rest_framework.response import Response\n\nfrom registration_api import utils\nfrom registration_api.serializers import UserSerializer\n\n\"\"\"\nExtension propia para asociar un Staff al nuevo usuario registrado\nEste Staff será un Manager por defecto\n\"\"\"\nfrom mainRest.models import Staff, Restaurant, Owner\n\n\n\nVALID_USER_FIELDS = utils.get_valid_user_fields()\n\n\n@api_view(['POST'])\n@permission_classes((AllowAny, ))\ndef register(request):\n \"\"\"\n Example valid JSON:\n {\"username\": \"john\", \"email\": \"john@example.com\", \"password\": \"pass\", \"restaurant\": \"My Pub\"}\n \"\"\"\n serialized = UserSerializer(data=request.data)\n if serialized.is_valid():\n #default code: create new_user\n user_data = utils.get_user_data(request.data)\n new_user = utils.create_inactive_user(**user_data)\n\n #Crear el restaurante del nuevo usuario:\n new_owner = Owner(user=new_user, name=new_user.username)\n new_owner.save()\n print(\"Owner \" + new_owner.name + \" created. [OK]\")\n restaurant_name = request.data.pop('restaurant')\n new_restaurant = Restaurant(owner = new_owner, name=restaurant_name)\n new_restaurant.save()\n print(\"Restaurant \" + new_restaurant.name + \" created. [OK]\")\n\n #Crear el staff\n staff_name = new_user.username\n new_staff = Staff(user=new_user, first_name=staff_name, restaurant=new_restaurant) #Manager por defecto\n new_staff.save()\n print(\"Staff \" + new_staff.first_name + \" created. [OK]\")\n\n return Response(utils.USER_CREATED_RESPONSE_DATA,\n status=status.HTTP_201_CREATED)\n else:\n return Response(serialized._errors, status=status.HTTP_409_CONFLICT)\n\n\n@api_view(['GET'])\n@permission_classes((AllowAny, ))\ndef activate(request, activation_key=None):\n \"\"\"\n Given an an activation key, look up and activate the user\n account corresponding to that key (if possible).\n\n \"\"\"\n utils.activate_user(activation_key)\n # if not activated\n success_url = utils.get_settings('REGISTRATION_API_ACTIVATION_SUCCESS_URL')\n if success_url is not None:\n return render(request, 'mainRest/activation.html', status=status.HTTP_200_OK)\n","sub_path":"mappeat/mappeat/registration_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"628157958","text":"# File to define all models used\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.python.ops.parallel_for import gradients\nfrom tensorflow.python.ops.parallel_for import control_flow_ops\nfrom tensorflow.python.ops import gradients as gradient_ops\nfrom tensorflow.python.util import nest\nfrom tensorflow.python.ops import array_ops\n\nFLAGS = tf.app.flags.FLAGS\n\n\n#function for computing Jacobian (in practice, approximation is needed for computational efficiency)\ndef tr_jacobian(output_tensor, input_tensor):\n\n flat_inputs = input_tensor #nest.flatten(input_tensor)\n print('flat_inputs', flat_inputs)\n #output_tensor_shape = output.shape\n #output_shape = array_ops.shape(output)\n output = array_ops.reshape(output_tensor, [-1])\n\n output_size = 100 #FLAGS.batch_size*FLAGS.sample_size*FLAGS.sample_size_y*2\n tr = tf.constant(0.0)\n for i in range(output_size):\n\n y = array_ops.gather(output, i)\n grad = gradient_ops.gradients(y,flat_inputs)[0]\n grad_vec = tf.reshape(grad, [-1])\n #print('grad_vec', grad_vec)\n tr = tr + grad_vec[i]\n\n return tr\n\n#parallelized version of Jacobian computation (still highly inefficient)\ndef parallel_tr_jacobian(output_tensor, input_tensor):\n\n flat_inputs = input_tensor #nest.flatten(input_tensor)\n print('flat_inputs', flat_inputs)\n #output_tensor_shape = output.shape\n #output_shape = array_ops.shape(output)\n output = array_ops.reshape(output_tensor, [-1])\n tr = tf.constant(0.0)\n i = tf.constant(0)\n c = lambda i: tf.less(i,100)\n def b():\n y = array_ops.gather(output, i)\n grad = gradient_ops.gradients(y,flat_inputs)[0]\n grad_vec = tf.reshape(grad, [-1])\n tr = tr + grad_vec[i]\n\n tr = tf.while_loop(c,b,[tr])\n return tr\n\n\ndef complex_add(x, y):\n xr, xi = tf.real(x), tf.imag(x)\n yr, yi = tf.real(y), tf.imag(y)\n return tf.complex(xr + yr, xi + yi)\n\ndef complex_mul(x, y):\n xr, xi = tf.real(x), tf.imag(x)\n yr, yi = tf.real(y), tf.imag(y)\n return tf.complex(xr*yr - xi*yi, xr*yi + xi*yr)\n\ndef stack_k(x, axis, k):\n\n list_x = []\n for i in range(k):\n list_x.append(x)\n\n out = tf.stack(list_x, axis)\n\n return out\n\n\n#DOWNSAMPLING\n#DOWNSAMPLING\ndef downsample(x, mask):\n\n mask_kspace = tf.cast(mask, tf.complex64)\n data_kspace = Fourier(x, separate_complex=True)\n out = mask_kspace * data_kspace\n\n return out\n\n\n#UPSAMPLING\ndef upsample(x, mask):\n\n image_complex = tf.ifft2d(x)\n image_size = [FLAGS.batch_size, FLAGS.sample_size, FLAGS.sample_size_y] #tf.shape(image_complex)\n\n #get real and imaginary parts\n image_real = tf.reshape(tf.real(image_complex), [image_size[0], image_size[1], image_size[2], 1])\n image_imag = tf.reshape(tf.imag(image_complex), [image_size[0], image_size[1], image_size[2], 1])\n\n out = tf.concat([image_real, image_imag], 3)\n\n return out\n\n\n\nclass Model:\n \"\"\"A neural network model.\n\n Currently only supports a feedforward architecture.\"\"\"\n \n def __init__(self, name, features):\n self.name = name\n self.outputs = [features]\n\n def _get_layer_str(self, layer=None):\n if layer is None:\n layer = self.get_num_layers()\n \n return '%s_L%03d' % (self.name, layer+1)\n\n def _get_num_inputs(self):\n return int(self.get_output().get_shape()[-1])\n\n def _glorot_initializer(self, prev_units, num_units, stddev_factor=1.0):\n \"\"\"Initialization in the style of Glorot 2010.\n\n stddev_factor should be 1.0 for linear activations, and 2.0 for ReLUs\"\"\"\n stddev = np.sqrt(stddev_factor / np.sqrt(prev_units*num_units))\n return tf.truncated_normal([prev_units, num_units],\n mean=0.0, stddev=stddev)\n\n def _glorot_initializer_conv2d(self, prev_units, num_units, mapsize, stddev_factor=1.0):\n \"\"\"Initialization in the style of Glorot 2010.\n\n stddev_factor should be 1.0 for linear activations, and 2.0 for ReLUs\"\"\"\n\n stddev = np.sqrt(stddev_factor / (np.sqrt(prev_units*num_units)*mapsize*mapsize))\n return tf.truncated_normal([mapsize, mapsize, prev_units, num_units],\n mean=0.0, stddev=stddev)\n\n def get_num_layers(self):\n return len(self.outputs)\n\n def add_batch_norm(self, scale=False):\n \"\"\"Adds a batch normalization layer to this model.\n\n See ArXiv 1502.03167v3 for details.\"\"\"\n\n # TBD: This appears to be very flaky, often raising InvalidArgumentError internally\n with tf.variable_scope(self._get_layer_str()):\n out = tf.contrib.layers.batch_norm(self.get_output(), scale=scale)\n \n self.outputs.append(out)\n return self\n\n def add_flatten(self):\n \"\"\"Transforms the output of this network to a 1D tensor\"\"\"\n\n with tf.variable_scope(self._get_layer_str()):\n batch_size = int(self.get_output().get_shape()[0])\n out = tf.reshape(self.get_output(), [batch_size, -1])\n\n self.outputs.append(out)\n return self\n\n def add_dense(self, num_units, stddev_factor=1.0):\n \"\"\"Adds a dense linear layer to this model.\n\n Uses Glorot 2010 initialization assuming linear activation.\"\"\"\n \n assert len(self.get_output().get_shape()) == 2, \"Previous layer must be 2-dimensional (batch, channels)\"\n\n with tf.variable_scope(self._get_layer_str()):\n prev_units = self._get_num_inputs()\n \n # Weight term\n initw = self._glorot_initializer(prev_units, num_units,\n stddev_factor=stddev_factor)\n weight = tf.get_variable('weight', initializer=initw)\n\n # Bias term\n initb = tf.constant(0.0, shape=[num_units])\n bias = tf.get_variable('bias', initializer=initb)\n\n # Output of this layer\n out = tf.matmul(self.get_output(), weight) + bias\n\n self.outputs.append(out)\n return self\n\n def add_sigmoid(self):\n \"\"\"Adds a sigmoid (0,1) activation function layer to this model.\"\"\"\n\n with tf.variable_scope(self._get_layer_str()):\n prev_units = self._get_num_inputs()\n out = tf.nn.sigmoid(self.get_output())\n \n self.outputs.append(out)\n return self\n\n def add_softmax(self):\n \"\"\"Adds a softmax operation to this model\"\"\"\n\n with tf.variable_scope(self._get_layer_str()):\n this_input = tf.square(self.get_output())\n reduction_indices = list(range(1, len(this_input.get_shape())))\n acc = tf.reduce_sum(this_input, reduction_indices=reduction_indices, keep_dims=True)\n out = this_input / (acc+FLAGS.epsilon)\n #out = tf.verify_tensor_all_finite(out, \"add_softmax failed; is sum equal to zero?\")\n \n self.outputs.append(out)\n return self\n\n def add_relu(self):\n \"\"\"Adds a ReLU activation function to this model\"\"\"\n\n with tf.variable_scope(self._get_layer_str()):\n out = tf.nn.relu(self.get_output())\n\n self.outputs.append(out)\n return self \n\n def add_elu(self):\n \"\"\"Adds a ELU activation function to this model\"\"\"\n\n with tf.variable_scope(self._get_layer_str()):\n out = tf.nn.elu(self.get_output())\n\n self.outputs.append(out)\n return self \n\n def add_lrelu(self, leak=.2):\n \"\"\"Adds a leaky ReLU (LReLU) activation function to this model\"\"\"\n\n with tf.variable_scope(self._get_layer_str()):\n t1 = .5 * (1 + leak)\n t2 = .5 * (1 - leak)\n out = t1 * self.get_output() + \\\n t2 * tf.abs(self.get_output())\n \n self.outputs.append(out)\n return self\n\n def add_conv2d(self, num_units, mapsize=1, stride=1, stddev_factor=1.0):\n \"\"\"Adds a 2D convolutional layer.\"\"\"\n\n assert len(self.get_output().get_shape()) == 4 and \"Previous layer must be 4-dimensional (batch, width, height, channels)\"\n \n with tf.variable_scope(self._get_layer_str()):\n prev_units = self._get_num_inputs()\n \n # Weight term and convolution\n initw = self._glorot_initializer_conv2d(prev_units, num_units,\n mapsize,\n stddev_factor=stddev_factor)\n weight = tf.get_variable('weight', initializer=initw)\n out = tf.nn.conv2d(self.get_output(), weight,\n strides=[1, stride, stride, 1],\n padding='SAME')\n\n # Bias term\n initb = tf.constant(0.0, shape=[num_units])\n bias = tf.get_variable('bias', initializer=initb)\n out = tf.nn.bias_add(out, bias) #?????!!!\n \n self.outputs.append(out)\n return self\n\n\n def add_fullconnect2d(self, num_units, stddev_factor=1.0):\n \"\"\"Adds a 2D convolutional layer.\"\"\"\n\n assert len(self.get_output().get_shape()) == 4 and \"Previous layer must be 4-dimensional (batch, width, height, channels)\"\n \n with tf.variable_scope(self._get_layer_str()):\n prev_units = self._get_num_inputs()\n \n # Weight term and full connection\n #initw = self._glorot_initializer_conv2d(prev_units, num_units,\n #mapsize,\n #stddev_factor=stddev_factor)\n weight = tf.get_variable('weight', initializer=initw)\n out = tf.contrib.layers.fully_connected(self.get_output(), num_units, activation_fn=None, normalizer_fn=None, normalizer_params=None, \n weights_initializer=initializers.xavier_initializer(),\n weights_regularizer=None,\n biases_initializer=tf.zeros_initializer(),\n biases_regularizer=None,\n reuse=None,\n variables_collections=None,\n outputs_collections=None,\n trainable=True,\n scope=None) #activation_fn=tf.nn.relu\n\n\n #out = tf.nn.conv2d(self.get_output(), weight,\n #strides=[1, stride, stride, 1],\n #padding='SAME')\n\n # Bias term\n initb = tf.constant(0.0, shape=[num_units])\n bias = tf.get_variable('bias', initializer=initb)\n out = tf.nn.bias_add(out, bias)\n \n self.outputs.append(out)\n return self\n\n\n def add_conv2d_transpose(self, num_units, mapsize=1, stride=1, stddev_factor=1.0):\n \"\"\"Adds a transposed 2D convolutional layer\"\"\"\n\n assert len(self.get_output().get_shape()) == 4 and \"Previous layer must be 4-dimensional (batch, width, height, channels)\"\n\n with tf.variable_scope(self._get_layer_str()):\n prev_units = self._get_num_inputs()\n \n # Weight term and convolution\n initw = self._glorot_initializer_conv2d(prev_units, num_units,\n mapsize,\n stddev_factor=stddev_factor)\n weight = tf.get_variable('weight', initializer=initw)\n weight = tf.transpose(weight, perm=[0, 1, 3, 2])\n prev_output = self.get_output()\n output_shape = [FLAGS.batch_size,\n int(prev_output.get_shape()[1]) * stride,\n int(prev_output.get_shape()[2]) * stride,\n num_units]\n out = tf.nn.conv2d_transpose(self.get_output(), weight,\n output_shape=output_shape,\n strides=[1, stride, stride, 1],\n padding='SAME')\n\n # Bias term\n initb = tf.constant(0.0, shape=[num_units])\n bias = tf.get_variable('bias', initializer=initb)\n out = tf.nn.bias_add(out, bias)\n \n self.outputs.append(out)\n return self\n\n def add_residual_block(self, num_units, mapsize=3, num_layers=2, stddev_factor=1e-3):\n \"\"\"Adds a residual block as per Arxiv 1512.03385, Figure 3\"\"\"\n\n assert len(self.get_output().get_shape()) == 4 and \"Previous layer must be 4-dimensional (batch, width, height, channels)\"\n\n # Add projection in series if needed prior to shortcut\n if num_units != int(self.get_output().get_shape()[3]):\n self.add_conv2d(num_units, mapsize=1, stride=1, stddev_factor=1.)\n\n bypass = self.get_output()\n\n # Residual block\n for _ in range(num_layers):\n self.add_batch_norm()\n self.add_relu()\n self.add_conv2d(num_units, mapsize=mapsize, stride=1, stddev_factor=stddev_factor)\n\n self.add_sum(bypass)\n\n return self\n\n def add_bottleneck_residual_block(self, num_units, mapsize=3, stride=1, transpose=False):\n \"\"\"Adds a bottleneck residual block as per Arxiv 1512.03385, Figure 3\"\"\"\n\n assert len(self.get_output().get_shape()) == 4 and \"Previous layer must be 4-dimensional (batch, width, height, channels)\"\n\n # Add projection in series if needed prior to shortcut\n if num_units != int(self.get_output().get_shape()[3]) or stride != 1:\n ms = 1 if stride == 1 else mapsize\n #bypass.add_batch_norm() # TBD: Needed?\n if transpose:\n self.add_conv2d_transpose(num_units, mapsize=ms, stride=stride, stddev_factor=1.)\n else:\n self.add_conv2d(num_units, mapsize=ms, stride=stride, stddev_factor=1.)\n\n bypass = self.get_output()\n\n # Bottleneck residual block\n self.add_batch_norm()\n self.add_relu()\n self.add_conv2d(num_units//4, mapsize=1, stride=1, stddev_factor=2.)\n\n self.add_batch_norm()\n self.add_relu()\n if transpose:\n self.add_conv2d_transpose(num_units//4,\n mapsize=mapsize,\n stride=1,\n stddev_factor=2.)\n else:\n self.add_conv2d(num_units//4,\n mapsize=mapsize,\n stride=1,\n stddev_factor=2.)\n\n self.add_batch_norm()\n self.add_relu()\n self.add_conv2d(num_units, mapsize=1, stride=1, stddev_factor=2.)\n\n self.add_sum(bypass)\n\n return self\n\n def add_sum(self, term):\n \"\"\"Adds a layer that sums the top layer with the given term\"\"\"\n\n with tf.variable_scope(self._get_layer_str()):\n prev_shape = self.get_output().get_shape()\n term_shape = term.get_shape()\n #print(\"%s %s\" % (prev_shape, term_shape))\n assert prev_shape == term_shape and \"Can't sum terms with a different size\"\n out = tf.add(self.get_output(), term)\n \n self.outputs.append(out)\n return self\n\n\n def add_dense(self, num_units, stddev_factor=1.0):\n \"\"\"Adds a dense linear layer to this model.\n\n Uses Glorot 2010 initialization assuming linear activation.\"\"\"\n \n assert len(self.get_output().get_shape()) == 2, \"Previous layer must be 2-dimensional (batch, channels)\"\n\n with tf.variable_scope(self._get_layer_str()):\n prev_units = self._get_num_inputs()\n \n # Weight term\n initw = self._glorot_initializer(prev_units, num_units,\n stddev_factor=stddev_factor)\n weight = tf.get_variable('weight', initializer=initw)\n\n # Bias term\n initb = tf.constant(0.0, shape=[num_units])\n bias = tf.get_variable('bias', initializer=initb)\n\n # Output of this layer\n out = tf.matmul(self.get_output(), weight) + bias\n\n self.outputs.append(out)\n return self\n\n\n def add_scale(self, stddev_factor=1.0):\n\n \"\"\"Adds a layer that scales the top layer with the given term\"\"\"\n with tf.variable_scope(self._get_layer_str()):\n \n # Weight term\n initw = self._glorot_initializer(1, 1,\n stddev_factor=stddev_factor)\n weight = tf.get_variable('weight', initializer=initw)\n\n # Output of this layer\n out = tf.scalar_mul(weight[0,0], self.get_output())\n\n self.outputs.append(out)\n return self\n\n\n def add_mean(self):\n \"\"\"Adds a layer that averages the inputs from the previous layer\"\"\"\n\n with tf.variable_scope(self._get_layer_str()):\n prev_shape = self.get_output().get_shape()\n reduction_indices = list(range(len(prev_shape)))\n assert len(reduction_indices) > 2 and \"Can't average a (batch, activation) tensor\"\n reduction_indices = reduction_indices[1:-1]\n out = tf.reduce_mean(self.get_output(), reduction_indices=reduction_indices)\n \n self.outputs.append(out)\n return self\n\n def add_upscale(self, size=None):\n \"\"\"Adds a layer that upscales the output by 2x through nearest neighbor interpolation\"\"\"\n\n prev_shape = self.get_output().get_shape()\n if size is None:\n size = [2 * int(s) for s in prev_shape[1:3]]\n out = tf.image.resize_nearest_neighbor(self.get_output(), size)\n\n self.outputs.append(out)\n return self \n\n def add_upsample(self, mask):\n \"\"\"Adds a layer that upsamples the output by Kx through transpose convolution\"\"\"\n\n prev_shape = self.get_output().get_shape()\n out = upsample(self.get_output(), mask)\n\n self.outputs.append(out)\n return self\n\n def add_downsample(self, mask):\n \"\"\"Adds a layer that downsamples the output by Kx through transpose convolution\"\"\"\n\n prev_shape = self.get_output().get_shape()\n out = downsample(self.get_output(), mask)\n\n self.outputs.append(out)\n return self\n\n\n def add_concat(self, layer_add):\n last_layer = self.get_output()\n prev_shape = last_layer.get_shape()\n try:\n out = tf.concat(axis = 3, values = [last_layer, layer_add])\n self.outputs.append(out)\n except:\n print('fail to concat {0} and {1}'.format(last_layer, layer_add))\n return self \n\n def add_layer(self, layer_add):\n self.outputs.append(layer_add)\n return self \n\n\n def get_output(self):\n \"\"\"Returns the output from the topmost layer of the network\"\"\"\n return self.outputs[-1]\n\n def get_variable(self, layer, name):\n \"\"\"Returns a variable given its layer and name.\n\n The variable must already exist.\"\"\"\n\n scope = self._get_layer_str(layer)\n collection = tf.get_collection(tf.GraphKeys.VARIABLES, scope=scope)\n\n # TBD: Ugly!\n for var in collection:\n if var.name[:-2] == scope+'/'+name:\n return var\n\n return None\n\n def get_all_layer_variables(self, layer):\n \"\"\"Returns all variables in the given layer\"\"\"\n scope = self._get_layer_str(layer)\n return tf.get_collection(tf.GraphKeys.VARIABLES, scope=scope)\n\n\n def gradients_out_in(output,input_img):\n return tf.gradients(output, input_img)\n\n\n\n\ndef _discriminator_model(sess, features, disc_input, layer_output_skip=5, hybrid_disc=0):\n\n # update 05092017, hybrid_disc consider whether to use hybrid space for discriminator\n # to study the kspace distribution/smoothness properties\n\n # Fully convolutional model\n mapsize = 3\n layers = [8,16,32,64] #[64, 128, 256, 512] #[8,16] #[8, 16, 32, 64]#\n\n old_vars = tf.global_variables()#tf.all_variables() , all_variables() are deprecated\n\n # augment data to hybrid domain = image+kspace\n if hybrid_disc>0:\n disc_size = tf.shape(disc_input)#disc_input.get_shape()\n # print(disc_size) \n disc_kspace = Fourier(disc_input, separate_complex=False)\n disc_kspace_real = tf.cast(tf.real(disc_kspace), tf.float32)\n # print(disc_kspace_real)\n disc_kspace_real = tf.reshape(disc_kspace_real, [disc_size[0],disc_size[1],disc_size[2],1])\n disc_kspace_imag = tf.cast(tf.imag(disc_kspace), tf.float32)\n # print(disc_kspace_imag) \n disc_kspace_imag = tf.reshape(disc_kspace_imag, [disc_size[0],disc_size[1],disc_size[2],1])\n disc_kspace_mag = tf.cast(tf.abs(disc_kspace), tf.float32)\n # print(disc_kspace_mag)\n disc_kspace_mag = tf.log(disc_kspace_mag)\n disc_kspace_mag = tf.reshape(disc_kspace_mag, [disc_size[0],disc_size[1],disc_size[2],1])\n if hybrid_disc == 1:\n disc_hybird = tf.concat(axis = 3, values = [disc_input * 2-1, disc_kspace_imag])\n else:\n disc_hybird = tf.concat(axis = 3, values = [disc_input * 2-1, disc_kspace_imag, disc_kspace_real, disc_kspace_imag])\n else:\n disc_hybird = disc_input #2 * disc_input - 1\n\n\n print('shape_disc_hybrid', disc_hybird.get_shape())\n\n print(hybrid_disc, 'discriminator input dimensions: {0}'.format(disc_hybird.get_shape()))\n model = Model('DIS', disc_hybird) \n\n for layer in range(len(layers)):\n nunits = layers[layer]\n stddev_factor = 2.0\n\n model.add_conv2d(nunits, mapsize=mapsize, stride=2, stddev_factor=stddev_factor)\n model.add_batch_norm()\n model.add_relu()\n\n # Finalization a la \"all convolutional net\"\n model.add_conv2d(nunits, mapsize=mapsize, stride=1, stddev_factor=stddev_factor)\n model.add_batch_norm()\n model.add_relu()\n\n model.add_conv2d(nunits, mapsize=1, stride=1, stddev_factor=stddev_factor)\n model.add_batch_norm()\n model.add_relu()\n\n # Linearly map to real/fake and return average score\n # (softmax will be applied later)\n model.add_conv2d(1, mapsize=1, stride=1, stddev_factor=stddev_factor) #1 for magnitude input images\n model.add_mean()\n\n new_vars = tf.global_variables()#tf.all_variables() , all_variables() are deprecated\n disc_vars = list(set(new_vars) - set(old_vars))\n\n #select output\n output_layers = model.outputs[0:] #[model.outputs[0]] + model.outputs[1:-1][::layer_output_skip] + [model.outputs[-1]]\n\n return model.get_output(), disc_vars, output_layers\n\ndef conv(batch_input, out_channels, stride=2, size_kernel=4):\n with tf.variable_scope(\"conv\"):\n in_channels = batch_input.get_shape()[3]\n filter = tf.get_variable(\"filter\", [size_kernel, size_kernel, in_channels, out_channels], dtype=tf.float32, initializer=tf.random_normal_initializer(0, 0.02))\n # [batch, in_height, in_width, in_channels], [filter_width, filter_height, in_channels, out_channels]\n # => [batch, out_height, out_width, out_channels]\n padded_input = tf.pad(batch_input, [[0, 0], [1, 1], [1, 1], [0, 0]], mode=\"CONSTANT\")\n conv = tf.nn.conv2d(padded_input, filter, [1, stride, stride, 1], padding=\"VALID\")\n return conv\n\ndef deconv(batch_input, out_channels, size_kernel=3):\n with tf.variable_scope(\"deconv\"):\n batch, in_height, in_width, in_channels = [int(d) for d in batch_input.get_shape()]\n filter = tf.get_variable(\"filter\", [size_kernel, size_kernel, out_channels, in_channels], dtype=tf.float32, initializer=tf.random_normal_initializer(0, 0.02))\n # [batch, in_height, in_width, in_channels], [filter_width, filter_height, out_channels, in_channels]\n # => [batch, out_height, out_width, out_channels]\n conv = tf.nn.conv2d_transpose(batch_input, filter, [batch, in_height * 2, in_width * 2, out_channels], [1, 2, 2, 1], padding=\"SAME\")\n return conv \n\ndef lrelu(x, a = 0.3):\n with tf.name_scope(\"lrelu\"):\n return tf.maximum(x, tf.multiply(x, a))\n # adding these together creates the leak part and linear part\n # then cancels them out by subtracting/adding an absolute value term\n # leak: a*x/2 - a*abs(x)/2\n # linear: x/2 + abs(x)/2\n\n # this block looks like it has 2 inputs on the graph unless we do this\n\ndef batchnorm(input):\n with tf.variable_scope(\"batchnorm\"):\n # this block looks like it has 3 inputs on the graph unless we do this\n input = tf.identity(input)\n\n channels = input.get_shape()[3]\n offset = tf.get_variable(\"offset\", [channels], dtype=tf.float32, initializer=tf.zeros_initializer())\n scale = tf.get_variable(\"scale\", [channels], dtype=tf.float32, initializer=tf.random_normal_initializer(1.0, 0.02))\n mean, variance = tf.nn.moments(input, axes=[0, 1, 2], keep_dims=False)\n variance_epsilon = 1e-5\n normalized = tf.nn.batch_normalization(input, mean, variance, offset, scale, variance_epsilon=variance_epsilon)\n return normalized \n\ndef Fourier(x, separate_complex=True): \n x = tf.cast(x, tf.complex64)\n if separate_complex:\n x_complex = x[:,:,:,0]+1j*x[:,:,:,1]\n else:\n x_complex = x\n x_complex = tf.reshape(x_complex,x_complex.get_shape()[:3])\n y_complex = tf.fft2d(x_complex)\n print('using Fourier, input dim {0}, output dim {1}'.format(x.get_shape(), y_complex.get_shape()))\n # x = tf.cast(x, tf.complex64)\n # y = tf.fft3d(x)\n # y = y[:,:,:,-1]\n return y_complex\n\ndef map(f, x, dtype=None, parallel_iterations=10):\n '''\n Apply f to each of the elements in x using the specified number of parallel iterations.\n\n Important points:\n 1. By \"elements in x\", we mean that we will be applying f to x[0],...x[tf.shape(x)[0]-1].\n 2. The output size of f(x[i]) can be arbitrary. However, if the dtype of that output\n is different than the dtype of x, then you need to specify that as an additional argument.\n '''\n if dtype is None:\n dtype = x.dtype\n\n n = tf.shape(x)[0]\n loop_vars = [\n tf.constant(0, n.dtype),\n tf.TensorArray(dtype, size=n),\n ]\n _, fx = tf.while_loop(\n lambda j, _: j < n,\n lambda j, result: (j + 1, result.write(j, f(x[j]))),\n loop_vars,\n parallel_iterations=parallel_iterations\n )\n return fx.stack()\n\ndef jacobian_func(fx, x, parallel_iterations=10):\n '''\n Given a tensor fx, which is a function of x, vectorize fx (via tf.reshape(fx, [-1])),\n and then compute the jacobian of each entry of fx with respect to x.\n Specifically, if x has shape (m,n,...,p), an d fx has L entries (tf.size(fx)=L), then\n the output will be (L,m,n,...,p), where output[i] will be (m,n,...,p), with each entry denoting the\n gradient of output[i] wrt the corresponding element of x.\n '''\n return map(lambda fxi: tf.gradients(fxi, x)[0],\n tf.reshape(fx, [-1]),\n dtype=x.dtype,\n parallel_iterations=parallel_iterations)\n\n#VAE implementation\ndef variational_autoencoder(sess,features,labels,masks,train_phase,z_val,print_bool, channels = 2,layer_output_skip = 5):\n print(\"Use variational autoencoder model\")\n old_vars = tf.global_variables()\n\n print(\"Input shape\", features.shape)\n print(\"Input type\", type(features))\n\n activation = lrelu\n keep_prob = 0.6\n n_latent = 1024\n batch_size = FLAGS.batch_size\n img = 0\n mn = 0\n sd = 0\n z = 0\n x0 = 0\n x1 = 0\n x2 = 0\n x3 = 0\n x4 = 0\n\n RSS = 0\n MSE = 0\n\n\n num_filters = 64\n encoder_layers = []\n\n with tf.variable_scope(\"var_encoder\"):\n\n x0 = tf.layers.conv2d(features,filters = num_filters,kernel_size = 5,strides = 2,padding = \"same\")\n encoder_layers.append(x0)\n #size = (b_size,80,64,64)\n\n x1 = tf.layers.conv2d(x0,filters = num_filters,kernel_size = 5,strides = 2,padding = \"same\")\n print(\"x1 shape\", x1)\n x1 = tf.contrib.layers.batch_norm(x1,activation_fn = activation)\n x1 = tf.nn.dropout(x1, keep_prob)\n encoder_layers.append(x1)\n #size = (b_size,40,32,64)\n\n x2 = tf.layers.conv2d(x1, filters=num_filters*2, kernel_size=5, strides=2, padding='same')\n print(\"x2 shape\", x2)\n x2 = tf.contrib.layers.batch_norm(x2,activation_fn = activation)\n x2 = tf.nn.dropout(x2, keep_prob)\n encoder_layers.append(x2)\n #size = (b_size,20,16,128)\n\n x3 = tf.layers.conv2d(x2, filters=num_filters*4, kernel_size=5, strides=2, padding='same', activation=activation)\n print(\"x3 shape\", x3)\n x3 = tf.contrib.layers.batch_norm(x3,activation_fn = activation)\n x3 = tf.nn.dropout(x3, keep_prob)\n encoder_layers.append(x3)\n #size = (b_size,10,8,256)\n\n x4 = tf.layers.conv2d(x3, filters=num_filters*8, kernel_size=5, strides=2, padding='same', activation=activation)\n print(\"x4 shape\", x4)\n x4 = tf.contrib.layers.batch_norm(x4,activation_fn = activation)\n x4 = tf.nn.dropout(x4, keep_prob)\n encoder_layers.append(x4)\n #size = (b_size,5,4,512)\n\n x = tf.contrib.layers.flatten(x4)\n #size = (b_size,5*4*1024)\n\n mn = tf.layers.dense(x, units=n_latent)\n mn = tf.contrib.layers.batch_norm(mn,activation_fn = tf.identity) \n #size = (b_size,1024)\n\n sd = tf.layers.dense(x, units=n_latent)\n sd = tf.contrib.layers.batch_norm(sd,activation_fn = tf.nn.softplus)\n #size = (b_size,1024)\n\n epsilon = tf.random_normal(tf.stack([batch_size, n_latent]))\n\n #z = tf.add(mn, tf.multiply(epsilon, tf.sqrt(tf.exp(sd))))\n z = tf.add(mn,tf.multiply(epsilon,tf.exp(sd)))\n\n\n decoder_input = z #tf.cond(train_phase, f1, f2)\n\n with tf.variable_scope(\"var_decoder\"):\n num_for_dense = num_filters * 4 * 5 * 8\n decoder_input.set_shape([batch_size,n_latent])\n x = tf.layers.dense(decoder_input, units=num_for_dense, activation=lrelu) #(b_size,1024*10*8)\n print(\"x_new shape\", x)\n x = tf.reshape(x, [-1,5,4,num_filters*8]) #(b_size,5,4,512)\n print(\"x_new_updated shape\", x)\n x = tf.add(x,x4)\n\n #upsample\n x = tf.layers.conv2d_transpose(x, filters=num_filters*4, kernel_size=5, strides=2, padding='same')\n x = tf.contrib.layers.batch_norm(x,activation_fn = activation)\n x = tf.nn.dropout(x, keep_prob)\n x = tf.add(x,x3)\n #size = (b_size,10,8,256)\n\n x = tf.layers.conv2d_transpose(x, filters=num_filters*2, kernel_size=5, strides=2, padding='same')\n x = tf.contrib.layers.batch_norm(x,activation_fn = activation)\n x = tf.nn.dropout(x, keep_prob)\n x = tf.add(x,x2)\n #size = (b_size,20,16,128)\n\n x = tf.layers.conv2d_transpose(x, filters=num_filters, kernel_size=5, strides=2, padding='same')\n x = tf.contrib.layers.batch_norm(x,activation_fn = activation)\n x = tf.add(x,x1)\n #size = (b_size,40,32,64)\n\n x = tf.layers.conv2d_transpose(x, filters=num_filters, kernel_size=5, strides=2, padding='same')\n x = tf.contrib.layers.batch_norm(x,activation_fn = activation)\n x = tf.add(x,x0)\n #size = (b_size,80,64,64)\n\n x = tf.layers.conv2d_transpose(x, filters=channels, kernel_size=5, strides=2, padding='same',activation = tf.nn.sigmoid)\n img = tf.add(x,features)\n\n\n num_pixels = tf.size(img)\n tr_jac = tf.constant(0.0)\n\n #data consistency\n masks_comp = 1.0 - masks\n correct_kspace = downsample(labels, masks) + downsample(img, masks_comp)\n correct_image = upsample(correct_kspace, masks)\n img = correct_image\n \n RSS = tf.cast(tf.reduce_mean(tf.square(tf.abs(img - features))), tf.float32)\n MSE = tf.cast(tf.reduce_mean(tf.square(tf.abs(img - labels))), tf.float32)\n\n output = img\n output_layers = [output]\n\n new_vars = tf.global_variables()\n gen_vars = list(set(new_vars) - set(old_vars))\n\n print(\"Output shape\", output.shape)\n print(\"Output type\", type(output))\n\n return output, gen_vars, output_layers, mn, sd, tr_jac, RSS, MSE\n\n\ndef _generator_encoder_decoder(sess, features, labels, masks,train_phase,channels = 2, layer_output_skip=5):\n print('use Encoder decoder model')\n # old variables\n layers = [] \n old_vars = tf.global_variables()#tf.all_variables() , all_variables() are deprecated\n # layers.append(features)\n\n # definition\n num_filter_generator = 3\n layer_specs = [ \n num_filter_generator * 2,\n num_filter_generator * 3, # encoder_2: [batch, 128, 128, ngf] => [batch, 64, 64, ngf * 2]\n num_filter_generator * 3, # encoder_3: [batch, 64, 64, ngf * 2] => [batch, 32, 32, ngf * 4]\n num_filter_generator * 4, # encoder_4: [batch, 32, 32, ngf * 4] => [batch, 16, 16, ngf * 8]\n # num_filter_generator * 8, # encoder_5: [batch, 16, 16, ngf * 8] => [batch, 8, 8, ngf * 8]\n # num_filter_generator * 8, # encoder_6: [batch, 8, 8, ngf * 8] => [batch, 4, 4, ngf * 8]\n # num_filter_generator * 8, # encoder_7: [batch, 4, 4, ngf * 8] => [batch, 2, 2, ngf * 8]\n # num_filter_generator * 16, # encoder_8: [batch, 2, 2, ngf * 8] => [batch, 1, 1, ngf * 8]\n ]\n\n # encoder_1: [batch, 256, 256, in_channels] => [batch, 128, 128, ngf]\n with tf.variable_scope(\"encoder_1\"):\n output = conv(features, num_filter_generator, stride=2 )\n # output = tf.identity(features)\n layers.append(output)\n\n for out_channels in layer_specs:\n with tf.variable_scope(\"encoder_%d\" % (len(layers) + 1)):\n rectified = lrelu(layers[-1], 0.2)\n # [batch, in_height, in_width, in_channels] => [batch, in_height/2, in_width/2, out_channels]\n convolved = conv(rectified, out_channels, stride=2)\n output = batchnorm(convolved)\n layers.append(output)\n\n\n with tf.variable_scope(\"latent\"):\n\n\n\n noise = np.random.normal(0,0.5,layers[-1].shape) \n #noise = np.random.normal(0,0.5)\n\n def f1(): return tf.identity(layers[-1])\n #def f2(): return tf.identity(layers[-1])\n #def f2(): return tf.add(layers[-1], noise)\n #def f2(): return tf.zeros(layers[-1].shape)\n\n def f2():\n temp = layers[-1]\n original_dims = tf.shape(temp)\n temp_vector = tf.reshape(temp,[1,-1])\n temp_abs_vector = tf.abs(temp_vector)\n\n k = 960\n\n \n values, indices = tf.nn.top_k(temp_abs_vector,k)\n \n my_range = tf.expand_dims(tf.range(0, tf.shape(indices)[0]), 1)\n my_range_repeated = tf.tile(my_range, [1, k])\n\n full_indices = tf.concat([tf.expand_dims(my_range_repeated, 2), tf.expand_dims(indices, 2)], axis=2)\n full_indices = tf.reshape(full_indices, [-1, 2])\n full_indices = tf.cast(full_indices,tf.int64)\n\n\n vals = tf.gather_nd(temp_vector,full_indices)\n vals = tf.reshape(vals,[-1])\n\n delta = tf.SparseTensor(full_indices,vals,temp_vector.shape)\n\n result = tf.sparse_tensor_to_dense(delta,validate_indices = False)\n result = tf.reshape(result,original_dims)\n\n return result\n\n layers[-1] = tf.cond(train_phase, f1, f2)\n\n\n layer_specs = [\n # (num_filter_generator * 16, 0.5), # decoder_8: [batch, 1, 1, ngf * 8] => [batch, 2, 2, ngf * 8 * 2]\n # (num_filter_generator * 8, 0.5), # decoder_7: [batch, 2, 2, ngf * 8 * 2] => [batch, 4, 4, ngf * 8 * 2]\n # (num_filter_generator * 8, 0.5), # decoder_6: [batch, 4, 4, ngf * 8 * 2] => [batch, 8, 8, ngf * 8 * 2]\n # (num_filter_generator * 8, 0.0), # decoder_5: [batch, 8, 8, ngf * 8 * 2] => [batch, 16, 16, ngf * 8 * 2]\n (num_filter_generator * 3, 0.5), # decoder_4: [batch, 16, 16, ngf * 8 * 2] => [batch, 32, 32, ngf * 4 * 2]\n (num_filter_generator * 3, 0.5), # decoder_3: [batch, 32, 32, ngf * 4 * 2] => [batch, 64, 64, ngf * 2 * 2]\n (num_filter_generator * 2, 0.5),\n (num_filter_generator, 0.0), # decoder_2: [batch, 64, 64, ngf * 2 * 2] => [batch, 128, 128, ngf * 2]\n ]\n\n num_encoder_layers = len(layers)\n for decoder_layer, (out_channels, dropout) in enumerate(layer_specs):\n skip_layer = num_encoder_layers - decoder_layer - 1\n with tf.variable_scope(\"decoder_%d\" % (skip_layer + 1)):\n if decoder_layer == 0:\n # first decoder layer doesn't have skip connections\n # since it is directly connected to the skip_layer\n input = layers[-1]\n else:\n #input = tf.concat(axis=3, values=[layers[-1], layers[skip_layer]]) # change the order of value and axisn, axis=3)\n input = tf.add(layers[-1],layers[skip_layer])\n #input = layers[-1]\n rectified = tf.nn.relu(input)\n # [batch, in_height, in_width, in_channels] => [batch, in_height*2, in_width*2, out_channels]\n output = deconv(rectified, out_channels)\n output = batchnorm(output)\n\n # if dropout > 0.0:\n # output = tf.nn.dropout(output, keep_prob = 1 - dropout)\n\n layers.append(output)\n\n # decoder_1: [batch, 128, 128, ngf * 2] => [batch, 256, 256, generator_outputs_channels]\n\n\n\n with tf.variable_scope(\"decoder_1\"):\n #input = tf.concat(axis=3, values=[layers[-1], layers[0]]) #, axis=3)\n input = tf.add(layers[-1],layers[0])\n #input = layers[-1]\n #rectified = tf.nn.relu(input)\n #output = deconv(rectified, channels)\n output = deconv(input,channels)\n #output = tf.nn.sigmoid(output)\n #output = tf.identity(layers[-1])\n layers.append(output)\n\n for x in layers:\n print(x)\n\n layers.append(layers[-1])\n\n def l1(): \n return tf.identity(layers[-1])\n masks_comp = 1.0 - masks\n correct_kspace = downsample(labels, masks) + downsample(layers[-2], masks_comp)\n correct_image = upsample(correct_kspace, masks)\n return correct_image\n def l2():\n return tf.identity(layers[-1])\n print(\"testing with data consistency for noise correction\")\n masks_comp = 1.0 - masks\n correct_kspace = downsample(labels, masks) + downsample(layers[-2], masks_comp)\n correct_image = upsample(correct_kspace, masks)\n return correct_image\n\n layers[-1] = tf.cond(train_phase,l1,l2)\n\n # out variables\n # select subset of layers\n new_vars = tf.global_variables()#tf.all_variables() , all_variables() are deprecated\n gene_vars = list(set(new_vars) - set(old_vars))\n output_layers = [layers[0]] + layers[1:-1][::layer_output_skip] + [layers[-1]]\n\n return layers[-1], gene_vars, output_layers\n\n\n\n### Resnet Architecture\n\ndef _generator_model_with_scale(sess, features, labels, masks, channels, layer_output_skip=5,\n num_dc_layers=0):\n \n channels = 2\n #image_size = tf.shape(features)\n mapsize = 3\n res_units = [128,128] #, 128, 128, 128, 128] #[64, 32, 16]#[256, 128, 96]\n scale_changes = [0,0,0,0,0,0,0,0]\n print('use resnet without pooling:', res_units)\n old_vars = tf.global_variables()#tf.all_variables() , all_variables() are deprecated\n\n # See Arxiv 1603.05027\n model = Model('GEN', features)\n\n # loop different levels\n for ru in range(len(res_units)-1):\n nunits = res_units[ru]\n\n for j in range(2): #(2)\n model.add_residual_block(nunits, mapsize=mapsize)\n\n # Spatial upscale (see http://distill.pub/2016/deconv-checkerboard/)\n # and transposed convolution\n if scale_changes[ru]>0:\n model.add_upscale()\n\n model.add_batch_norm()\n model.add_relu()\n model.add_conv2d_transpose(nunits, mapsize=mapsize, stride=1, stddev_factor=1.)\n\n\n # Finalization a la \"all convolutional net\"\n nunits = res_units[-1]\n model.add_conv2d(nunits, mapsize=mapsize, stride=1, stddev_factor=2.)\n # Worse: model.add_batch_norm()\n model.add_relu()\n\n model.add_conv2d(nunits, mapsize=1, stride=1, stddev_factor=2.)\n # Worse: model.add_batch_norm()\n model.add_relu()\n\n # Last layer is sigmoid with no batch normalization\n model.add_conv2d(channels, mapsize=1, stride=1, stddev_factor=1.)\n #model.add_sigmoid()\n\n output = model.outputs[-1]\n\n \n #hard data consistency\n \"\"\"\n masks_comp = 1.0 - masks\n correct_kspace = downsample(labels, masks) + downsample(output, masks_comp)\n correct_image = upsample(correct_kspace, masks)\n model.add_layer(correct_image)\n \"\"\"\n \n \n #inexact data consistency. can be repeated using a for loop\n \"\"\"\n output_neg = -1*output\n model.add_layer(output_neg)\n model.add_sum(labels)\n model.add_downsample(masks)\n model.add_upsample(masks)\n model.add_scale(stddev_factor=1.)\n model.add_sum(output)\n \"\"\"\n\n ##inexact affine projection\n #ww = 0.01\n #for kk in range(10):\n #output = output + ww*upsample(downsample(labels-output, masks), masks)\n\n #output = model.output[-1]\n #model.add_layer(output)\n \n new_vars = tf.global_variables() #tf.all_variables() , all_variables() are deprecated\n gene_vars = list(set(new_vars) - set(old_vars))\n\n # select subset of layers\n output_layers = model.outputs[0] \n #output_layers = [model.outputs[0]] + model.outputs[1:-1][::layer_output_skip] + [model.outputs[-1]]\n\n return model.get_output(), gene_vars, output_layers\n\n\n\n\n\n\ndef create_model(sess, features, labels, masks, architecture='resnet'):\n # sess: TF sesson\n # features: input, for SR/CS it is the input image\n # labels: output, for SR/CS it is the groundtruth image\n # architecture: aec for encode-decoder, resnet for upside down \n # Generator\n rows = int(features.get_shape()[1])\n cols = int(features.get_shape()[2])\n channels = int(features.get_shape()[3])\n n_latent = 1024\n temp_zeros = tf.zeros([FLAGS.batch_size,n_latent],tf.float32)\n num_pixels = tf.size(features)\n #print('channels', features.get_shape())\n\n gene_minput = tf.placeholder_with_default(features, shape=[FLAGS.batch_size, rows, cols, channels])\n label_minput = tf.placeholder_with_default(tf.zeros([FLAGS.batch_size, rows, cols, channels]), shape=[FLAGS.batch_size, rows, cols, channels])\n train_phase = tf.placeholder_with_default(True, shape=())\n z_val = tf.placeholder_with_default(temp_zeros, shape= temp_zeros.shape)\n print_bool = tf.placeholder_with_default(False, shape=())\n adjusted_gene_output = tf.placeholder_with_default(tf.zeros([FLAGS.batch_size, rows, cols, channels]), shape=[FLAGS.batch_size, rows, cols, channels])\n num_to_average = 100\n\n architecture = 'vae' #only deal with the variational autoencoder\n\n\n # TBD: Is there a better way to instance the generator?\n if architecture == 'aec':\n function_generator = lambda x,y,z,w,t: _generator_encoder_decoder(x,y,z,w,t)\n elif architecture == 'vae':\n function_generator = lambda x,y,z,w,t,a,p: variational_autoencoder(x,y,z,w,t,a,p)\n elif architecture == 'pool':\n function_generator = lambda x,y,z,w: _generator_model_with_pool(x,y,z,w)\n elif architecture.startswith('var'):\n num_dc_layers = 1\n if architecture!='var':\n try:\n num_dc_layers = int(architecture.split('var')[-1])\n except:\n pass\n function_generator = lambda x,y,z,m,w: _generator_model_with_scale(x,y,z,m,w,\n layer_output_skip=7, num_dc_layers=num_dc_layers)\n else:\n function_generator = lambda x,y,z,m,w: _generator_model_with_scale(x,y,z,m,w,\n layer_output_skip=7, num_dc_layers=0)\n\n\n gene_var_list = []\n gene_Var_list = []\n gene_layers_list = []\n gene_mlayers_list = []\n gene_output_list = []\n gene_moutput_list = []\n mask_list = []\n mask_list_0 = []\n eta = []\n dot_prod_sum = 0\n\n kappa = []\n nmse = []\n\n\n\n with tf.variable_scope('gene_layer') as scope:\n\n gene_output = features\n gene_moutput = gene_minput\n\n for i in range(FLAGS.num_iteration):\n\n #train\n gene_output, gene_var_list, gene_layers, mn, sd, tr_jac, RSS, MSE = function_generator(sess, gene_output, labels, masks,train_phase,z_val,print_bool)\n #gene_output, gene_var_list, gene_layers = function_generator(sess, gene_output, labels, masks,train_phase)\n gene_layers_list.append(gene_layers)\n gene_output_list.append(gene_output)\n if i == 0:\n gene_Var_list = gene_var_list\n\n scope.reuse_variables()\n\n #Jacobian trace approximation for SURE\n dot_prod_sum = 0\n for j in range(num_to_average):\n b = tf.random_normal(tf.shape(features))\n epsilon = tf.reduce_max(features) / 1000.0 #epsilon value can be adjusted as needed\n adjusted_features = tf.add(features, tf.scalar_mul(epsilon, b))\n adjusted_gene_output_temp, _, _, _, _,_, _, _ = function_generator(sess, adjusted_features, labels, masks,train_phase,z_val,print_bool)\n difference = tf.subtract(adjusted_gene_output_temp, gene_output)\n scaled_difference = tf.divide(difference, epsilon)\n dot_prod = tf.multiply(b, scaled_difference)\n dot_prod_sum = dot_prod_sum + tf.reduce_sum(dot_prod)\n dot_prod_sum = tf.divide(dot_prod_sum, num_to_average)\n\n\n scope.reuse_variables() \n #test\n gene_moutput, _ , gene_mlayers, mn1, sd1, tr_jac1, RSS1, MSE1= function_generator(sess, gene_moutput, label_minput, masks,train_phase,z_val,print_bool)\n #gene_moutput, _ , gene_mlayers = function_generator(sess, gene_moutput, label_minput, masks,train_phase)\n gene_mlayers_list.append(gene_mlayers)\n gene_moutput_list.append(gene_moutput)\n #mask_list.append(gene_mlayers[3])\n\n scope.reuse_variables()\n #evaluate at the groun-truth solution\n gene_moutput_0, _ , gene_mlayers_0, mn2, sd2, tr_jac2, RSS2, MSE2 = function_generator(sess, label_minput, label_minput, masks,train_phase,z_val,print_bool)\n\n\n #gene_moutput, _ , gene_mlayers = function_generator(sess, gene_moutput, label_minput, masks,train_phase)\n #mask_list_0 = gene_mlayers_0[3]\n \"\"\"\n\n #nmse_t = tf.square(tf.divide(tf.norm(gene_moutput - labels), tf.norm(labels)))\n #nmse.append(nmse_t)\n #kappa_t = tf.divide(tf.norm(gene_moutput - labels), tf.norm(gene_mlayers[0] - labels))\n #kappa.append(kappa_t)\n\n ##convergence rate kappa_t = ||x_{t+1}-x_*||/||x_t-x_*||\n #kappa_t = tf.divide(tf.norm(gene_mlayers[4] - labels), tf.norm(gene_mlayers[0] - labels))\n #nmse_t = tf.divide(tf.norm(gene_mlayers[4] - labels), tf.norm(labels))\n #kappa.append(kappa_t)\n \n #nmse.append(nmse_t)\n \"\"\"\n\n\n #eta = tf.zeros([4,4]) #eta_1 + eta_2\n \n #Discriminator with real data\n gene_output_complex = tf.complex(gene_output[:,:,:,0], gene_output[:,:,:,1])\n gene_output_real = tf.abs(gene_output_complex)\n gene_output_real = tf.reshape(gene_output_real, [FLAGS.batch_size, rows, cols, 1]) #gene_output\n\n labels_complex = tf.complex(labels[:,:,:,0], labels[:,:,:,1])\n labels_real = tf.abs(labels_complex)\n labels_real = tf.reshape(labels_real, [FLAGS.batch_size, rows, cols, 1]) #gene_output\n\n disc_real_input = tf.identity(labels_real, name='disc_real_input')\n\n\n # TBD: Is there a better way to instance the discriminator?\n with tf.variable_scope('disc') as scope:\n print('hybrid_disc', FLAGS.hybrid_disc)\n disc_real_output, disc_var_list, disc_layers = \\\n _discriminator_model(sess, features, disc_real_input, hybrid_disc=FLAGS.hybrid_disc)\n\n scope.reuse_variables()\n\n \n disc_fake_output, _, _ = _discriminator_model(sess, features, gene_output_real, hybrid_disc=FLAGS.hybrid_disc)\n\n #collect other quantities for assessing SURE\n RSS_im = tf.square(tf.abs(gene_output - features))\n MSE_im = tf.square(tf.abs(gene_output - labels))\n tr_jac = dot_prod_sum / tf.cast(num_pixels,tf.float32)\n dof_pixel_map = scaled_difference\n tf.summary.scalar('train_tr_jac', tr_jac)\n tf.summary.scalar('train_rss_jac', RSS)\n tf.summary.scalar('train_MSE', MSE)\n tf_grads = tf.gradients(gene_output, features)\n\n return [MSE, RSS, tr_jac,dof_pixel_map,RSS_im, MSE_im, tf_grads, features, labels, mn, sd, gene_minput, label_minput, gene_moutput, gene_moutput_list,\n gene_output, gene_output_list, gene_Var_list, gene_layers_list, gene_mlayers_list, mask_list, mask_list_0,\n disc_real_output, disc_fake_output, disc_var_list, train_phase, print_bool, z_val,disc_layers, eta, nmse, kappa] \n\n\n# SSIM\ndef keras_var(x, axis=None, keepdims=False):\n \"\"\"Variance of a tensor, alongside the specified axis.\n # Arguments\n x: A tensor or variable.\n axis: An integer, the axis to compute the variance.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n # Returns\n A tensor with the variance of elements of `x`.\n \"\"\"\n # axis = _normalize_axis(axis, ndim(x))\n if x.dtype.base_dtype == tf.bool:\n x = tf.cast(x, floatx())\n m = tf.reduce_mean(x, reduction_indices=axis, keep_dims=True)\n devs_squared = tf.square(x - m)\n return tf.reduce_mean(devs_squared,\n reduction_indices=axis,\n keep_dims=keepdims)\n\n\ndef keras_std(x, axis=None, keepdims=False):\n \"\"\"Standard deviation of a tensor, alongside the specified axis.\n # Arguments\n x: A tensor or variable.\n axis: An integer, the axis to compute the standard deviation.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1. If `keepdims` is `True`,\n the reduced dimension is retained with length 1.\n # Returns\n A tensor with the standard deviation of elements of `x`.\n \"\"\"\n return tf.sqrt(keras_var(x, axis=axis, keepdims=keepdims))\n\n\ndef keras_mean(x, axis=None, keepdims=False):\n \"\"\"Mean of a tensor, alongside the specified axis.\n # Arguments\n x: A tensor or variable.\n axis: A list of integer. Axes to compute the mean.\n keepdims: A boolean, whether to keep the dimensions or not.\n If `keepdims` is `False`, the rank of the tensor is reduced\n by 1 for each entry in `axis`. If `keep_dims` is `True`,\n the reduced dimensions are retained with length 1.\n # Returns\n A tensor with the mean of elements of `x`.\n \"\"\"\n # axis = _normalize_axis(axis, ndim(x))\n if x.dtype.base_dtype == tf.bool:\n x = tf.cast(x, floatx())\n return tf.reduce_mean(x, reduction_indices=axis, keep_dims=keepdims)\n\ndef loss_DSSIS_tf11(y_true, y_pred, patch_size=5, batch_size=-1):\n # get batch size\n if batch_size<0:\n batch_size = int(y_true.get_shape()[0])\n else:\n y_true = tf.reshape(y_true, [batch_size] + get_shape(y_pred)[1:])\n y_pred = tf.reshape(y_pred, [batch_size] + get_shape(y_pred)[1:])\n # batch, x, y, channel\n # y_true = tf.transpose(y_true, [0, 2, 3, 1])\n # y_pred = tf.transpose(y_pred, [0, 2, 3, 1])\n patches_true = tf.extract_image_patches(y_true, [1, patch_size, patch_size, 1], [1, 2, 2, 1], [1, 1, 1, 1], \"SAME\")\n patches_pred = tf.extract_image_patches(y_pred, [1, patch_size, patch_size, 1], [1, 2, 2, 1], [1, 1, 1, 1], \"SAME\")\n #print(patches_true, patches_pred)\n u_true = keras_mean(patches_true, axis=3)\n u_pred = keras_mean(patches_pred, axis=3)\n #print(u_true, u_pred)\n var_true = keras_var(patches_true, axis=3)\n var_pred = keras_var(patches_pred, axis=3)\n std_true = tf.sqrt(var_true)\n std_pred = tf.sqrt(var_pred)\n #print(std_true, std_pred)\n c1 = 0.01 ** 2\n c2 = 0.03 ** 2\n ssim = (2 * u_true * u_pred + c1) * (2 * std_pred * std_true + c2)\n denom = (u_true ** 2 + u_pred ** 2 + c1) * (var_pred + var_true + c2)\n ssim /= denom\n #print(ssim)\n # ssim = tf.select(tf.is_nan(ssim), K.zeros_like(ssim), ssim)\n return tf.reduce_mean(((1.0 - ssim) / 2), name='ssim_loss')\n\ndef create_generator_loss(disc_output, gene_output, gene_output_list, features, labels, masks,mn,sd):\n \n # Cross entropy GAN cost\n cross_entropy = tf.nn.sigmoid_cross_entropy_with_logits(logits=disc_output, labels=tf.ones_like(disc_output))\n gene_ce_loss = tf.reduce_mean(cross_entropy, name='gene_ce_loss')\n\n # LS GAN cost\n ls_loss = tf.square(disc_output - tf.ones_like(disc_output))\n gene_ls_loss = tf.reduce_mean(ls_loss, name='gene_ls_loss')\n\n # I.e. does the result look like the feature?\n # K = int(gene_output.get_shape()[1])//int(features.get_shape()[1])\n # assert K == 2 or K == 4 or K == 8 \n # downscaled = _downscale(gene_output, K)\n\n\n # soft data-consistency loss\n #image_size = [128, 128]\n #K=2\n gene_dc_loss = 0\n for j in range(FLAGS.num_iteration):\n \tgene_dc_loss = gene_dc_loss + tf.cast(tf.reduce_mean(tf.square(tf.abs(downsample(labels - gene_output_list[j], masks))), name='gene_dc_loss'), tf.float32)\n\n gene_dc_norm = tf.cast(tf.reduce_mean(tf.square(tf.abs(downsample(labels, masks))), name='gene_dc_norm'), tf.float32)\n gene_dc_loss = gene_dc_loss / (gene_dc_norm * FLAGS.num_iteration)\n\n\n \n #generator MSE loss summed up over different copies\n gene_l2_loss = 0\n gene_l1_loss = 0\n for j in range(FLAGS.num_iteration):\n\n gene_l2_loss = gene_l2_loss + tf.cast(tf.reduce_mean(tf.square(tf.abs(gene_output_list[j] - labels)), name='gene_l2_loss'), tf.float32)\n gene_l1_loss = gene_l2_loss + tf.cast(tf.reduce_mean(tf.abs(gene_output_list[j] - labels), name='gene_l2_loss'), tf.float32)\n \n \n '''\n # mse loss\n gene_l1_loss = tf.cast(tf.reduce_mean(tf.abs(gene_output - labels), name='gene_l1_loss'), tf.float32)\n gene_l2_loss = tf.cast(tf.reduce_mean(tf.square(tf.abs(gene_output - labels)), name='gene_l2_loss'), tf.float32)\n '''\n\n # mse loss\n gene_mse_loss = tf.add(FLAGS.gene_l1l2_factor * gene_l1_loss, \n (1.0 - FLAGS.gene_l1l2_factor) * gene_l2_loss, name='gene_mse_loss')\n\n gene_mse_loss = tf.divide(gene_mse_loss,tf.norm(features))\n print(\"GENE\",gene_output)\n print(\"LABEL\",labels)\n print(\"LOSS\",gene_mse_loss)\n\n\n # Add in KL divergence term to enforce normal constraint\n #eta = 1e-4\n\n latent_loss = tf.reduce_mean(-0.5 * tf.reduce_sum(1.0 + sd - tf.square(mn) - tf.exp(sd), 1))\n\n gene_mse_loss = gene_mse_loss #+ eta * latent_loss\n\n #ssim loss\n gene_ssim_loss = loss_DSSIS_tf11(labels, gene_output)\n gene_mixmse_loss = tf.add(FLAGS.gene_ssim_factor * gene_ssim_loss, \n (1.0 - FLAGS.gene_ssim_factor) * gene_mse_loss, name='gene_mixmse_loss')\n \n # generator fool descriminator loss: gan LS or log loss\n #gene_fool_loss = tf.add(FLAGS.gene_ls_factor * gene_ls_loss,\n # FLAGS.gene_log_factor * gene_ce_loss, name='gene_fool_loss')\n\n gene_fool_loss = -tf.reduce_mean(disc_output)\n\n # non-mse loss = fool-loss + data consisntency loss\n gene_non_mse_l2 = gene_fool_loss #tf.add((1.0 - FLAGS.gene_dc_factor) * gene_fool_loss,\n #FLAGS.gene_dc_factor * gene_dc_loss, name='gene_nonmse_l2')\n \n gene_mse_factor = tf.placeholder(dtype=tf.float32, name='gene_mse_factor')\n\n #total loss = fool-loss + data consistency loss + mse forward-passing loss\n #gene_loss = tf.add((1.0 - FLAGS.gene_mse_factor) * gene_non_mse_l2, \n #FLAGS.gene_mse_factor * gene_mixmse_loss, name='gene_loss')\n\n #gene_mse_factor as a parameter\n #gene_loss = tf.add((1.0 - gene_mse_factor) * gene_non_mse_l2,\n #gene_mse_factor * gene_mixmse_loss, name='gene_loss')\n\n gene_loss_pre = tf.add((1.0 - gene_mse_factor) * gene_non_mse_l2,\n gene_mse_factor * gene_mixmse_loss, name='gene_loss')\n\n gene_loss = tf.add(FLAGS.gene_dc_factor * gene_dc_loss,\n (1.0 - FLAGS.gene_dc_factor) * gene_loss_pre, name='gene_loss')\n\n #list of loss\n list_gene_lose = [gene_mixmse_loss, gene_mse_loss, gene_l2_loss, gene_l1_loss, gene_ssim_loss, # regression loss\n gene_dc_loss, gene_fool_loss, gene_non_mse_l2, gene_loss]\n\n # log to tensorboard\n #tf.summary.scalar('gene_non_mse_loss', gene_non_mse_l2)\n tf.summary.scalar('gene_fool_loss', gene_non_mse_l2)\n tf.summary.scalar('gene_dc_loss', gene_dc_loss)\n #tf.summary.scalar('gene_ls_loss', gene_ls_loss)\n tf.summary.scalar('gene_L1_loss', gene_mixmse_loss)\n\n\n return gene_loss, gene_dc_loss, gene_fool_loss, gene_mse_loss, list_gene_lose, gene_mse_factor\n \n\ndef create_discriminator_loss(disc_real_output, disc_fake_output, real_data = None, fake_data = None):\n ls_loss_real = tf.square(disc_real_output - tf.ones_like(disc_real_output))\n disc_real_loss = tf.reduce_mean(ls_loss_real, name='disc_real_loss')\n\n ls_loss_fake = tf.square(disc_fake_output)\n disc_fake_loss = tf.reduce_mean(ls_loss_fake, name='disc_fake_loss')\n\n # log to tensorboard\n tf.summary.scalar('disc_real_loss',disc_real_loss)\n tf.summary.scalar('disc_fake_loss',disc_fake_loss)\n return disc_real_loss, disc_fake_loss\n \n # I.e. did we correctly identify the input as real or not?\n # cross_entropy_real = tf.nn.sigmoid_cross_entropy_with_logits(logits=disc_real_output, labels=tf.ones_like(disc_real_output))\n # disc_real_loss = tf.reduce_mean(cross_entropy_real, name='disc_real_loss')\n \n # cross_entropy_fake = tf.nn.sigmoid_cross_entropy_with_logits(logits=disc_fake_output, labels=tf.zeros_like(disc_fake_output))\n # disc_fake_loss = tf.reduce_mean(cross_entropy_fake, name='disc_fake_loss')\n\"\"\"\n fake_data = tf.complex(fake_data[:,:,:,0], fake_data[:,:,:,1])\n fake_data = tf.abs(fake_data)\n fake_data = tf.reshape(fake_data, [FLAGS.batch_size, rows, cols, 1]) \n\n real_data = tf.complex(real_data[:,:,:,0], real_data[:,:,:,1])\n real_data = tf.abs(real_data)\n real_data = tf.reshape(real_data, [FLAGS.batch_size, rows, cols, 1]) \n\n disc_real_loss = tf.reduce_mean(disc_real_output)\n disc_fake_loss = tf.reduce_mean(disc_fake_output)\n\n disc_cost = disc_fake_loss - disc_real_loss\n\n # generate noisy inputs \n alpha = tf.random_uniform(shape=[FLAGS.batch_size, 1, 1, 1], minval=0.,maxval=1.) \n interpolates = real_data + (alpha*(fake_data - real_data))\n\n with tf.variable_scope('disc', reuse=True) as scope:\n\n interpolates_disc_output, _, _ = _discriminator_model(None, None, interpolates, hybrid_disc=FLAGS.hybrid_disc)\n gradients = tf.gradients(interpolates_disc_output, [interpolates])[0] \n gradients = tf.layers.flatten(gradients)\n\n slopes = tf.sqrt(tf.reduce_sum(tf.square(gradients), reduction_indices=[1])) \n gradient_penalty = tf.reduce_mean((slopes - 1.)**2)\n disc_loss = tf.add(disc_cost, 1 * gradient_penalty, name='disc_loss')\n \n tf.summary.scalar('disc_total_loss',disc_loss)\n tf.summary.scalar('disc_real_loss',disc_real_loss) \n tf.summary.scalar('disc_fake_loss',disc_fake_loss) \n\n return disc_loss, disc_real_loss, disc_fake_loss, gradient_penalty\n\"\"\"\n\n\n\n\n\n # ls loss\n\n\n \n\n \n\ndef create_optimizers(gene_loss, gene_var_list,\n disc_loss, disc_var_list): \n # TBD: Does this global step variable need to be manually incremented? I think so.\n global_step = tf.Variable(0, dtype=tf.int64, trainable=False, name='global_step')\n learning_rate = tf.placeholder(dtype=tf.float32, name='learning_rate')\n \n gene_opti = tf.train.AdamOptimizer(learning_rate=learning_rate,\n beta1=FLAGS.learning_beta1,\n name='gene_optimizer')\n disc_opti = tf.train.AdamOptimizer(learning_rate=learning_rate,\n beta1=FLAGS.learning_beta1,\n name='disc_optimizer')\n \n '''\n ##gradient clipping \n ##method 1. the right method\n grads_and_vars = gene_opti.compute_gradients(gene_loss) #, gene_var_list)\n #[print('grad', grad) for grad, var in grads_and_vars]\n\n def clipNotNone(grads):\n if grads is None:\n return grads\n return tf.clip_by_value(grads,-1000000000., 1000000000.)\n\n capped_grads_and_vars = [(clipNotNone(grad),var) for grad,var in grads_and_vars]\n gene_minimize = gene_opti.apply_gradients(capped_grads_and_vars)\n '''\n \n\n ##method 2\n #print(gene_opti)\n #print('****************************************')\n #tvars = tf.trainable_variables()\n #grads, _ = tf.clip_by_global_norm(tf.gradients(gene_loss, tvars), 1)\n #gene_opti = gene_opti.apply_gradients(zip(grads, tvars))\n #print(gene_opti) \n \n\n gene_minimize = gene_opti.minimize(gene_loss, var_list=gene_var_list, name='gene_loss_minimize', global_step=global_step)\n \n disc_minimize = disc_opti.minimize(disc_loss, var_list=disc_var_list, name='disc_loss_minimize', global_step=global_step)\n \n return (global_step, learning_rate, gene_minimize,disc_minimize)\n\n\n\n","sub_path":"srez_model.py","file_name":"srez_model.py","file_ext":"py","file_size_in_byte":62327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"21595614","text":"import pandas as pd\nimport numpy as np\nclass gnb:\n def __init__(self, prior=None, n_class=None, \n mean=None, variance = None, classes=None):\n # prior assumption of probability\n self.prior = prior\n # how many unique classes\n self.n_class = n_class\n # mean of x values\n self.mean = mean\n # variance of x values\n self.variance = variance\n # the unique classes present\n self.classes = classes\n\n\n # get the mean and variance of the x values\n def fit(self, x, y):\n # get the mean and variance of the x values\n self.x = x\n self.y = y\n self.mean = np.array(x.groupby(by=y).mean())\n self.variance = np.array(x.groupby(by=y).var())\n self.n_class = len(np.unique(y))\n self.classes = np.unique(y)\n self.prior = 1/self.n_class\n return self\n\n def mean_var(self):\n # mean and variance from the trainig data\n m = np.array(self.mean)\n v = np.array(self.variance)\n\n # pull and combine the corresponding mean and variance\n self.mean_var = []\n for i in range(len(m)):\n m_row = m[i]\n v_row = v[i]\n for a, b in enumerate(m_row):\n mean = b\n var = v_row[a]\n self.mean_var.append([mean, var])\n\n return self.mean_var\n\n def split(self):\n spt = np.vsplit(np.array(self.mean_var()), self.n_class)\n return spt\n\n def gnb_base(self, x_val, x_mean, x_var):\n # define the base formula for prediction probabilities\n # Variance of the x value in question\n self.x_val = x_val\n # x mean value\n self.x_mean = x_mean\n # the x value that is being used for computation\n self.x_var = x_var\n\n # natural log\n e = np.e\n # pi\n pi = np.pi\n # first part of the equation\n # 1 divided by the sqrt of 2 * pi * y_variance\n equation_1 = 1/(np.sqrt(2 * pi * x_var))\n \n # second part of equation implementation\n # denominator of equation\n denom = 2 * x_var\n\n # numerator calculation\n\n numerator = (x_val - x_mean) ** 2\n # the exponent\n expo = np.exp(-(numerator/denom))\n prob = equation_1 * expo\n\n return prob\n\n def predict(self, X):\n self.X = X\n # calculate the probabilities using base formula above\n\n # defining the mean and variance that has being split into\n # various classes.\n\n split_class = self.split()\n prob = []\n for i in range(self.n_class):\n # first class\n class_one = split_class[i]\n for i in range(len(class_one)):\n # first value in class one\n class_one_x_mean = class_one[i][0]\n class_one_x_var = class_one[i][1]\n x_value = X[i]\n # now calculate the probabilities of each class. \n prob.append([self.gnb_base(x_value, class_one_x_mean, \n class_one_x_var)])\n\n # turn prob into an array\n\n prob_array = np.array(prob)\n\n # split the probability into various classes again\n\n prob_split = np.vsplit(prob_array, self.n_class)\n\n # calculate the final probabilities\n\n final_probabilities = []\n\n for i in prob_split:\n class_prob = np.prod(i) * self.prior\n final_probabilities.append(class_prob)\n\n # determining the maximum probability \n maximum_prob = max(final_probabilities)\n\n # getting the index that corresponds to maximum probability\n prob_index = final_probabilities.index(maximum_prob)\n\n # using the index of the maximum probability to get\n # the class that corresponds to the maximum probability\n prediction = self.classes[prob_index]\n\n return prediction\n\n\n\n","sub_path":"gaussian_classifier/gaussian_classifier.py","file_name":"gaussian_classifier.py","file_ext":"py","file_size_in_byte":3495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"398570819","text":"#bu kod bir sayinin tam bolenlerini bulur\n\n\nsayi=int(input(\"tam bolenlerini bulmak icin lutfen bir sayi giriniz:\")) #sayi kullanicidan ister.\n\nbolenler=[] #tam bolenleri icine atmak icin bos bir liste olusturur\nfor i in range(1,sayi+1): #1 ve sayi dahil bu araliktaki sayilara bakar\n if sayi%i==0: #bu araliktaki tam bolen sayilari bulur\n bolenler.append(i) #tam bolen sayilari bolenler listesinde biriktirir\nprint(bolenler) #tam bolen sayilar listesini yazdirir\n","sub_path":"tambolen.py","file_name":"tambolen.py","file_ext":"py","file_size_in_byte":603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"581771306","text":"# -*- coding: utf-8 -*-\nimport scrapy\n\n\nclass PricingSpider(scrapy.Spider):\n name = \"pricing\"\n allowed_domains = [\"bjs.com\"]\n start_urls = [\n 'https://www.bjs.com/search/96817/q',\n ]\n\n def parse(self, response):\n for product_url in response.css(\"gb-bjs-tile > span > a ::attr(href)\").extract():\n yield scrapy.Request(response.urljoin(product_url), callback=self.parse_product_page)\n next_page = response.css(\"span.next > a ::attr(href)\").extract_first()\n \n if next_page:\n yield scrapy.Request(response.urljoin(next_page), callback=self.parse)\n\n def parse_product_page(self, response):\n item = {}\n print(\"URL : \", self)\n product = response.css(\"div.product_main\")\n item[\"title\"] = product.css(\"h1 ::text\").extract_first()\n item['category'] = response.xpath(\n \"//ul[@class='breadcrumb']/li[@class='active']/preceding-sibling::li[1]/a/text()\"\n ).extract_first()\n item['description'] = response.xpath(\n \"//div[@id='product_description']/following-sibling::p/text()\"\n ).extract_first()\n item['price'] = response.css('p.price_color ::text').extract_first()\n yield item\n","sub_path":"pricing/spiders/pricings.py","file_name":"pricings.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"332743584","text":"press_ups=input(\"Enter the No. Press ups: \")\npress_ups_limit=input(\"Enter the regular press up Limit: \")\nexc_press_ups=0\ntry:\n fpress_ups=float(press_ups)\n fpress_ups_limit=float(press_ups_limit)\nexcept:\n print(\"Please enter numeric values\")\n quit()\n\nif fpress_ups>fpress_ups_limit:\n exc_press_ups=fpress_ups-fpress_ups_limit\n print(\"Your extra press ups: \", exc_press_ups)\nelse :\n print(\"you are exhausted, you only burn: \"+ str(fpress_ups * 0.29)+\" cals\")\n\nprint(\" your extra cals burnt today: \"+ str(exc_press_ups*0.36)+\" cals\")\ntotal=(exc_press_ups*0.36)+(fpress_ups_limit*0.29)\nprint(\"your total cals burnt today: extra + regular = \"+str(total)+\" cals\")","sub_path":"Python DS and ALGO/Python for everybody(FreeCodeCamp)/exerciseconditional.py","file_name":"exerciseconditional.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"395718931","text":"from pygame import *\r\nfrom math import *\r\nfrom random import *\r\nimport subprocess\r\n\r\n\r\nsize=width,height=1440,720\r\nscreen=display.set_mode(size)\r\nRED=(255,0,0) \r\nGREEN=(0,255,0)\r\nBLUE=(0,0,255)\r\nBLACK=(0,0,0)\r\nWHITE=(255,255,255)\r\n\r\ninit()\r\nDONE = set()\r\ngame_over = False\r\nmono = font.SysFont(\"Monospace\",50)\r\ndef floweyFont(text,height,lower=50,upper=1370):\r\n fx = lower\r\n fy = height\r\n count = 0\r\n inc = 0\r\n for char in text:\r\n if char == \"\\n\" or fx > upper:\r\n fy+=50\r\n fx = lower\r\n else:\r\n if char == \",\" or char == \".\" or char == \"!\": \r\n inc = 400\r\n else:\r\n inc = 0\r\n char = mono.render(char,True,WHITE)\r\n screen.blit(char,(fx,fy))\r\n display.flip()\r\n fx+=25\r\n time.wait(65+inc)\r\n \r\n time.wait(1500)\r\n\r\n\r\n\r\nsprites = [image.load(\"%i.png\" % k) for k in range(4)]\r\nfor i in range(4):\r\n sprites[i] = transform.scale(sprites[i],(50,62))\r\nGUY = [100,90]\r\nPOS = [100,130]\r\nX = 0\r\nY = 1\r\n#screen.blit(image.load(\"l1.png\"),(0,0))\r\nyy = image.load(\"l3.png\")\r\nZ = image.load(\"l3.png\")\r\nscreen.blit(image.load(\"realThree.png\"),(0,0))\r\nscroll = image.load(\"scroll_left.png\")\r\nscroll = transform.scale(scroll,(50,62))\r\nscrolls = [[265,93+5],[1069,258],[1942,750]]\r\ndi = [False for i in range(3)]\r\nx = screen.copy()\r\ndef mask(screen,GUY,w):\r\n \r\n offx = GUY[X] - 50\r\n offy = GUY[Y] - 65\r\n try:\r\n m = -1\r\n if GUY[X] > 1090 and GUY[Y] > 245:\r\n viewRect = Rect(1235+5-200,430+5-260,200,260)\r\n elif GUY[X] > 1090:\r\n viewRect = Rect(1235+5-200,offy,200,260)\r\n elif GUY[Y] > 245:\r\n viewRect = Rect(offx,430+5-260,200,260)\r\n else:\r\n viewRect = Rect(offx,offy,200,260)\r\n viewScreen = x.subsurface(viewRect).copy()\r\n newView = transform.scale(viewScreen,(width,height))\r\n player = Rect(POS[X]+10,POS[Y]+10,40,42)\r\n\r\n viewBack = yy.subsurface(viewRect).copy()\r\n Z.blit(transform.scale(viewBack,(width,height)),(0,0))\r\n \r\n \r\n screen.blit(transform.scale(viewScreen,(width,height)),(0,0))\r\n screen.blit(sprites[w],(POS[X],POS[Y]))\r\n COUNT = -1\r\n for s in scrolls:\r\n COUNT += 1\r\n if s[0]-GUY[X] < 50 and abs(s[1]-GUY[Y]) < 201:\r\n if GUY[Y] <= 180:\r\n screen.blit(scroll,(POS[X]+int((s[0]-GUY[X])*7.2),s[1]-int((GUY[Y]-s[1])*720/260)))\r\n scrollRect = Rect(POS[X]+int((s[0]-GUY[X])*7.2)+10,s[1]-int((GUY[Y]-s[1])*720/260)+10,30,42)\r\n m = COUNT\r\n elif s[1]-130 > 0:\r\n screen.blit(scroll,(POS[X]+int((s[0]-GUY[X])*7.2),s[1]-130))\r\n m = COUNT\r\n scrollRect = Rect(POS[X]+int((s[0]-GUY[X])*7.2)+10,s[1]-130+10,30,42)\r\n if m >= 0:\r\n if scrollRect.colliderect(player) and di[m] == False:\r\n subprocess.call(\"Three%i.py\" % m,shell = True)\r\n #print(m)\r\n DONE.add(m)\r\n di[m] = True\r\n \r\n if len(DONE) == 3 and GUY[X] > 2080:\r\n game_over = True\r\n screen.fill(BLACK)\r\n floweyFont(\"You Finished Level 3. Only one more to go...\",300)\r\n display.flip()\r\n time.wait(2000)\r\n quit() \r\n \r\n \r\n #draw.rect(screen,BLUE,player,5)\r\n except:\r\n pass\r\n \r\n\r\nmask(screen,GUY,0)\r\ndisplay.flip()\r\ndef movePlayer(GUY):\r\n keys = key.get_pressed()\r\n #player = Rect(100,130,50,62)\r\n if keys[K_RIGHT] and GUY[X] < 1260+1040:\r\n GUY[X] += 3\r\n if GUY[X] > 1090:\r\n POS[X] = GUY[X]-1090+100\r\n else:\r\n POS[X] = 100\r\n if Z.get_at((POS[X]+50,POS[Y])) == WHITE and Z.get_at((POS[X]+50,POS[Y]+62)) == WHITE:\r\n #print(GUY[X],GUY[Y])\r\n mask(screen,GUY,3)\r\n else:\r\n GUY[X] -= 3 \r\n \r\n if keys[K_LEFT] and GUY[X] > 96:\r\n GUY[X] -= 3\r\n if GUY[X] > 1090:\r\n POS[X] = GUY[X]-1090+100\r\n else:\r\n POS[X] = 100\r\n if Z.get_at((POS[X],POS[Y])) == WHITE and Z.get_at((POS[X],POS[Y]+62)) == WHITE:\r\n #print(GUY[X],GUY[Y])\r\n mask(screen,GUY,2)\r\n else:\r\n GUY[X] += 3\r\n \r\n if keys[K_UP] and GUY[Y] > 86:\r\n GUY[Y] -= 3\r\n if GUY[Y] > 245:\r\n POS[Y]= GUY[Y]-245+130\r\n else:\r\n POS[Y] = 130\r\n if Z.get_at((POS[X],POS[Y])) == WHITE and Z.get_at((POS[X]+50,POS[Y])) == WHITE:\r\n #print(GUY[X],GUY[Y])\r\n mask(screen,GUY,1)\r\n else:\r\n GUY[Y] += 3\r\n \r\n if keys[K_DOWN] and GUY[Y] < 750:\r\n GUY[Y] += 3\r\n if GUY[Y] > 245:\r\n POS[Y]= GUY[Y]-245+130\r\n else:\r\n POS[Y] = 130\r\n if Z.get_at((POS[X],POS[Y]+62)) == WHITE and Z.get_at((POS[X]+50,POS[Y]+62)) == WHITE:\r\n #print(GUY[X],GUY[Y])\r\n mask(screen,GUY,0)\r\n else:\r\n GUY[Y] -= 3\r\n \r\n\r\n \r\nmyClock = time.Clock()\r\nrunning=True\r\nwhile running:\r\n for evt in event.get():\r\n if evt.type==QUIT:\r\n running=False\r\n if not game_over:\r\n mx,my=mouse.get_pos()\r\n mb = mouse.get_pressed()\r\n movePlayer(GUY)\r\n display.flip()\r\n else:\r\n running = False\r\n myClock.tick(120)\r\nquit()\r\n","sub_path":"History FSE/TileMap3a.py","file_name":"TileMap3a.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"327402361","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4\n\nimport sys\ntry:\n import kopano\nexcept ImportError:\n if sys.version_info >= (3,0):\n print('please install python3-kopano')\n exit(1)\n import zarafa as kopano\nimport csv\nfrom MAPI.Util import *\nimport MAPI.Util\nimport MAPI.Time\nimport time\nfrom datetime import datetime\nimport os\n\nscriptdir = os.path.dirname(os.path.realpath(__file__))\n\n\nextra = {\"PR_DISPLAY_NAME_FULL\": 0x8130001f,\n \"PR_EMAIL\": 0x8133001f,\n \"PR_FILE_AS\": 0x80b5001f,\n \"PR_WEBSITE\": 0x80db001f,\n \"PR_MAIL\": 0x8134001f,\n \"PR_ADDRESS\": 0x80f5001f,\n \"PR_CITY\": 0x80f6001f,\n \"PR_STATE\": 0x80f7001f,\n \"PR_ZIP\": 0x80f8001f,\n \"PR_COUNTRY\": 0x80f9001f,\n \"PR_IM\": 0x8112001f,\n \"PR_EMAIL2\": 0X8144001F,\n \"PR_MAIL2\": 0X8143001F,\n \"PR_DISPLAY_NAME_FULL2\": 0X8140001F,\n \"PR_EMAIL3\": 0X8154001F,\n \"PR_MAIL3\": 0X8153001F,\n \"PR_DISPLAY_NAME_FULL3\": 0X8150001F,\n \"PR_CATEGORIES\": 0x850d101f,\n \"PR_PRIVATE\": 0x81a6000b\n}\n\ndef opt_args():\n parser = kopano.parser('skpcmUP')\n parser.add_option(\"--user\", dest=\"user\", action=\"store\", help=\"Run script for user\")\n parser.add_option(\"--folder\", dest=\"folder\", action=\"store\", help=\"Select an other contacts folder then the default one\")\n parser.add_option(\"--export\", dest=\"export\", action=\"store_true\", help=\"export contacts\")\n parser.add_option(\"--import\", dest=\"restore\", action=\"store\", help=\"import contacts\")\n parser.add_option(\"--delimiter\", dest=\"delimiter\", action=\"store\", help=\"Change delimiter (default is ,)\")\n parser.add_option(\"--purge\", dest=\"purge\", action=\"store_true\", help=\"Purge contacts before the import\")\n parser.add_option(\"--progressbar\", dest=\"progressbar\", action=\"store_true\", help=\"Show progressbar \")\n parser.add_option(\"--public\", dest=\"public\", action=\"store_true\", help=\"Run script for public store\")\n parser.add_option(\"--format\", dest=\"format\", action=\"store\", help=\"Format that is used for display name if\"\n \"entry is empty default:\"\n \"'lastname, firstname, middlename (email)'\")\n\n return parser.parse_args()\n\n\ndef progressbar(count):\n try:\n from progressbar import Bar, AdaptiveETA, Percentage, ProgressBar\n except ImportError:\n print('Please download the progressbar library from https://github.com/niltonvolpato/python-progressbar or '\n 'run without the --progressbar parameter')\n sys.exit(1)\n widgets = [Percentage(),\n ' ', Bar(),\n ' ', AdaptiveETA()]\n progressmax = count\n pbar = ProgressBar(widgets=widgets, maxval=progressmax)\n pbar.start()\n\n return pbar\n\n\ndef getprop(item, myprop):\n try:\n if item.prop(myprop).typename == 'PT_UNICODE':\n return item.prop(myprop).value\n elif item.prop(myprop).typename == 'PT_SYSTIME':\n epoch = datetime.utcfromtimestamp(0)\n return (item.prop(myprop).value - epoch).total_seconds()\n elif item.prop(myprop).typename == 'PT_I4':\n return int(item.prop(myprop).value)\n else:\n\n return item.prop(myprop).value\n except (MAPIErrorNotFound, kopano.errors.NotFoundError):\n return None\n\n\ndef main():\n options, args = opt_args()\n if not options.user and not options.public:\n print('Please use:\\n {} --user '.format(sys.argv[0]))\n sys.exit(1)\n contactsarray = []\n\n if options.public and not options.folder:\n print('Please use --folder if public store is selected')\n sys.exit(1)\n server = kopano.Server(options)\n if options.public:\n store = server.public_store\n user = 'Public store'\n else:\n user = server.user(options.user).name\n store = server.user(options.user).store\n print('running script for \\'{}\\''.format(user))\n if options.delimiter:\n delimiter = options.delimiter\n else:\n delimiter = ','\n if options.export:\n if options.folder:\n contacts = store.folder(options.folder)\n else:\n contacts = store.contacts\n if options.progressbar:\n pbar = progressbar(contacts.count * 2)\n print('export contacts')\n itemcount = 0\n for contact in contacts.items():\n if options.progressbar:\n pbar.update(itemcount + 1)\n contactsarray.append(\n [getprop(contact, PR_SUBJECT_W), getprop(contact, PR_DISPLAY_NAME_W), getprop(contact, PR_GENERATION_W),\n getprop(contact, PR_GIVEN_NAME_W), getprop(contact, PR_BUSINESS_TELEPHONE_NUMBER_W),\n getprop(contact, PR_HOME_TELEPHONE_NUMBER_W), getprop(contact, PR_SURNAME_W),\n getprop(contact, PR_COMPANY_NAME_W), getprop(contact, PR_TITLE_W),\n getprop(contact, PR_DEPARTMENT_NAME_W), getprop(contact, PR_OFFICE_LOCATION_W),\n getprop(contact, PR_PRIMARY_TELEPHONE_NUMBER_W), getprop(contact, PR_BUSINESS2_TELEPHONE_NUMBER_W),\n getprop(contact, PR_MOBILE_TELEPHONE_NUMBER_W), getprop(contact, PR_RADIO_TELEPHONE_NUMBER_W),\n getprop(contact, PR_CAR_TELEPHONE_NUMBER_W), getprop(contact, PR_OTHER_TELEPHONE_NUMBER_W),\n getprop(contact, PR_PAGER_TELEPHONE_NUMBER_W), getprop(contact, PR_PRIMARY_FAX_NUMBER_W),\n getprop(contact, PR_BUSINESS_FAX_NUMBER_W), getprop(contact, PR_HOME_FAX_NUMBER_W),\n getprop(contact, PR_TELEX_NUMBER_W), getprop(contact, PR_ISDN_NUMBER_W),\n getprop(contact, PR_ASSISTANT_TELEPHONE_NUMBER_W), getprop(contact, PR_HOME2_TELEPHONE_NUMBER_W),\n getprop(contact, PR_ASSISTANT_W), getprop(contact, PR_MIDDLE_NAME_W),\n getprop(contact, PR_DISPLAY_NAME_PREFIX_W), getprop(contact, PR_PROFESSION_W),\n getprop(contact, PR_SPOUSE_NAME_W), getprop(contact, PR_TTYTDD_PHONE_NUMBER_W),\n getprop(contact, PR_MANAGER_NAME_W), getprop(contact, PR_NICKNAME_W),\n getprop(contact, PR_BUSINESS_HOME_PAGE_W), getprop(contact, PR_COMPANY_MAIN_PHONE_NUMBER_W),\n getprop(contact, PR_HOME_ADDRESS_CITY_W), getprop(contact, PR_HOME_ADDRESS_COUNTRY_W),\n getprop(contact, PR_HOME_ADDRESS_POSTAL_CODE_W), getprop(contact, PR_HOME_ADDRESS_STATE_OR_PROVINCE_W),\n getprop(contact, PR_HOME_ADDRESS_STREET_W), getprop(contact, PR_OTHER_ADDRESS_CITY_W),\n getprop(contact, PR_OTHER_ADDRESS_COUNTRY_W), getprop(contact, PR_OTHER_ADDRESS_POSTAL_CODE_W),\n getprop(contact, PR_OTHER_ADDRESS_STATE_OR_PROVINCE_W), getprop(contact, PR_OTHER_ADDRESS_STREET_W),\n getprop(contact, PR_WEDDING_ANNIVERSARY), getprop(contact, PR_BIRTHDAY),\n getprop(contact, extra['PR_DISPLAY_NAME_FULL']), getprop(contact, extra['PR_EMAIL']),\n getprop(contact, extra['PR_FILE_AS']),\n getprop(contact, extra['PR_WEBSITE']), getprop(contact, extra['PR_MAIL']),\n getprop(contact, extra['PR_MAIL2']), getprop(contact, extra['PR_DISPLAY_NAME_FULL2']),\n getprop(contact, extra['PR_EMAIL2']),getprop(contact, extra['PR_MAIL3']),\n getprop(contact, extra['PR_DISPLAY_NAME_FULL3']),getprop(contact, extra['PR_EMAIL3']),\n getprop(contact, extra['PR_ADDRESS']),\n getprop(contact, extra['PR_CITY']), getprop(contact, extra['PR_STATE']),\n getprop(contact, extra['PR_ZIP']),\n getprop(contact, extra['PR_COUNTRY']), getprop(contact, extra['PR_IM']), getprop(contact, PR_BODY_W),\n getprop(contact, PR_SENSITIVITY), getprop(contact, extra['PR_CATEGORIES']),\n getprop(contact, extra['PR_PRIVATE'])])\n\n itemcount += 1\n resultFile = open(\"{}_contacts.csv\".format(user), 'w')\n wr = csv.writer(resultFile, delimiter=delimiter)\n\n wr.writerow(['PR_SUBJECT', 'PR_DISPLAY_NAME', 'PR_GENERATION', 'PR_GIVEN_NAME', 'PR_BUSINESS_TELEPHONE_NUMBER',\n 'PR_HOME_TELEPHONE_NUMBER',\n 'PR_SURNAME', 'PR_COMPANY_NAME', 'PR_TITLE', 'PR_DEPARTMENT_NAME', 'PR_OFFICE_LOCATION',\n 'PR_PRIMARY_TELEPHONE_NUMBER',\n 'PR_BUSINESS2_TELEPHONE_NUMBER', 'PR_MOBILE_TELEPHONE_NUMBER', 'PR_RADIO_TELEPHONE_NUMBER',\n 'PR_CAR_TELEPHONE_NUMBER',\n 'PR_OTHER_TELEPHONE_NUMBER', 'PR_PAGER_TELEPHONE_NUMBER', 'PR_PRIMARY_FAX_NUMBER',\n 'PR_BUSINESS_FAX_NUMBER', 'PR_HOME_FAX_NUMBER',\n 'PR_TELEX_NUMBER', 'PR_ISDN_NUMBER', 'PR_ASSISTANT_TELEPHONE_NUMBER', 'PR_HOME2_TELEPHONE_NUMBER',\n 'PR_ASSISTANT', 'PR_MIDDLE_NAME',\n 'PR_DISPLAY_NAME_PREFIX', 'PR_PROFESSION', 'PR_SPOUSE_NAME', 'PR_TTYTDD_PHONE_NUMBER',\n 'PR_MANAGER_NAME', 'PR_NICKNAME',\n 'PR_BUSINESS_HOME_PAGE', 'PR_COMPANY_MAIN_PHONE_NUMBER', 'PR_HOME_ADDRESS_CITY',\n 'PR_HOME_ADDRESS_COUNTRY', 'PR_HOME_ADDRESS_POSTAL_CODE',\n 'PR_HOME_ADDRESS_STATE_OR_PROVINCE', 'PR_HOME_ADDRESS_STREET', 'PR_OTHER_ADDRESS_CITY',\n 'PR_OTHER_ADDRESS_COUNTRY',\n 'PR_OTHER_ADDRESS_POSTAL_CODE', 'PR_OTHER_ADDRESS_STATE_OR_PROVINCE', 'PR_OTHER_ADDRESS_STREET',\n 'PR_WEDDING_ANNIVERSARY', 'PR_BIRTHDAY',\n 'PR_DISPLAY_NAME_FULL', 'PR_EMAIL', 'PR_FILE_AS', 'PR_WEBSITE', 'PR_MAIL',\n 'PR_DISPLAY_NAME_FULL2', 'PR_EMAIL2','PR_MAIL2','PR_DISPLAY_NAME_FULL3', 'PR_EMAIL3','PR_MAIL3',\n 'PR_ADDRESS', 'PR_CITY', 'PR_STATE', 'PR_ZIP', 'PR_COUNTRY', 'PR_IM', 'PR_BODY', 'PR_SENSITIVITY',\n 'PR_CATEGORIES', 'PR_PRIVATE'])\n for contact in contactsarray:\n if options.progressbar:\n pbar.update(itemcount + 1)\n wr.writerows([contact])\n itemcount += 1\n if options.progressbar:\n pbar.finish()\n\n if options.restore:\n if options.folder:\n contacts = store.folder(options.folder)\n else:\n contacts = store.contacts\n if options.purge:\n contacts.empty()\n if options.progressbar:\n cr = csv.reader(open(options.restore, \"r\"), delimiter=delimiter)\n pbar = progressbar(sum(1 for row in cr))\n cr = csv.reader(open(options.restore, \"r\"), delimiter=delimiter)\n headers = next(cr)\n total = len(headers)\n itemcount = 0\n for contact in cr:\n if contact[0]:\n if options.progressbar:\n pbar.update(itemcount + 1)\n new_item = contacts.create_item()\n show_contacts = [0]\n for num in range(0, total, 1):\n if contact[num]:\n\n if headers[num] == 'PR_WEDDING_ANNIVERSARY' or headers[num] == 'PR_BIRTHDAY':\n datetime_date = datetime.fromtimestamp(int(contact[num][:-2]))\n value = MAPI.Time.unixtime(time.mktime(datetime_date.timetuple()))\n elif headers[num] == 'PR_SENSITIVITY':\n value = int(contact[num])\n else:\n value = contact[num].replace(u'\\xa0', u' ')\n if str(headers[num]) in extra:\n new_item.mapiobj.SetProps([SPropValue(extra[headers[num]], value)])\n else:\n if isinstance(value, str):\n value = value.encode('utf-8')\n new_item.mapiobj.SetProps([SPropValue(getattr(MAPI.Util,headers[num]), value)])\n\n if headers[num] == \"PR_EMAIL2\":\n show_contacts.append(1)\n new_item.mapiobj.SetProps([SPropValue(extra['PR_DISPLAY_NAME_FULL2'], value)])\n if headers[num] == \"PR_EMAIL3\":\n show_contacts.append(2)\n new_item.mapiobj.SetProps([SPropValue(extra['PR_DISPLAY_NAME_FULL3'], value)])\n\n # Business address is formatted from 4 separated properties\n # Check if they exist and craft the new property\n business = False\n try:\n address = new_item.prop(extra['PR_ADDRESS']).value\n business = True\n except kopano.errors.NotFoundError:\n address = ''\n try:\n city = new_item.prop(extra['PR_CITY']).value\n business = True\n except kopano.errors.NotFoundError:\n city = ''\n try:\n state = new_item.prop(extra['PR_STATE']).value\n business = True\n except kopano.errors.NotFoundError:\n state = ''\n try:\n country = new_item.prop(extra['PR_COUNTRY']).value\n business = True\n except kopano.errors.NotFoundError:\n country = ''\n if business:\n full_address = '{}\\n{}\\n{}\\n{}\\n'.format(address, city,state, country)\n new_item.mapiobj.SetProps([SPropValue(2160787487, u'%s' % full_address)])\n\n # Add needed propteries.\n new_item.mapiobj.SetProps([\n SPropValue(0x80D81003, show_contacts), SPropValue(0x80D90003, 1),\n ])\n\n new_item.mapiobj.SaveChanges(KEEP_OPEN_READWRITE)\n\n # prop PR_EMAIL is needed in order to add it to the global addressbook\n\n # Check if display name is set and add it if needed\n if not new_item.get_prop(extra['PR_DISPLAY_NAME_FULL']) and \\\n (new_item.get_prop(extra['PR_MAIL']) or new_item.get_prop(extra['PR_EMAIL'])):\n try:\n firstname = new_item.prop(PR_GIVEN_NAME).value.decode('utf-8')\n except kopano.errors.NotFoundError:\n firstname = ''\n try:\n middlename = new_item.prop(PR_MIDDLE_NAME).value.decode('utf-8')\n except kopano.errors.NotFoundError:\n middlename = ''\n try:\n lastname = new_item.prop(PR_SURNAME).value.decode('utf-8')\n except kopano.errors.NotFoundError:\n lastname = ''\n\n if new_item.get_prop(extra['PR_MAIL']):\n email = new_item.prop(extra['PR_MAIL']).value\n new_item.create_prop(extra['PR_MAIL'], email)\n else:\n email = new_item.prop(extra['PR_EMAIL']).value\n new_item.create_prop(extra['PR_EMAIL'], email)\n\n fullname_format = 'lastname, firstname, middlename (email)'\n if options.format:\n fullname_format = options.format\n fullname_format = fullname_format.replace('lastname', lastname).replace('firstname', firstname).replace('middlename', middlename).replace('email', email)\n new_item.create_prop(extra['PR_DISPLAY_NAME_FULL'], fullname_format)\n\n itemcount += 1\n\n\n if options.progressbar:\n pbar.finish()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"contacts2csv/contact2csv.py","file_name":"contact2csv.py","file_ext":"py","file_size_in_byte":15895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"168603003","text":"import pymysql\n\ndef name_sh(str):\n # 页面显示为(xx行/xx部门/name)\n l=str.split('/')\n name=l[len(l)-1].strip(')')\n return name\n# 查询所有账号\ndef get_user():\n db = pymysql.connect(\"xx\", \"root\", \"xx\", 'hawkeye')\n cur=db.cursor()\n cur.execute(\"SELECT user_code,user_name FROM `tb_sys_user` where user_status=1\")\n res=cur.fetchall()\n user={}\n for k,v in res:\n user[v]=k\n db.close()\n return user","sub_path":"自动化--添加及审核/basic.py","file_name":"basic.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"218621558","text":"import os\nimport json\nimport logging\nfrom uuid import uuid4\nimport boto3\nfrom functools import wraps\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.engine.url import URL\nfrom sqlalchemy.orm import sessionmaker\nfrom minerva_db.sql.api import Client\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n\nSTACK_PREFIX = os.environ['STACK_PREFIX']\nSTAGE = os.environ['STAGE']\n\nbatch = boto3.client('batch')\nssm = boto3.client('ssm')\ns3 = boto3.client('s3')\n\nraw_bucket = ssm.get_parameter(\n Name='/{}/{}/common/S3BucketRawARN'.format(STACK_PREFIX, STAGE)\n)['Parameter']['Value']\n\ntile_bucket = ssm.get_parameter(\n Name='/{}/{}/common/S3BucketTileARN'.format(STACK_PREFIX, STAGE)\n)['Parameter']['Value']\n\ndb_host = ssm.get_parameter(\n Name='/{}/{}/common/DBHost'.format(STACK_PREFIX, STAGE)\n)['Parameter']['Value']\n\ndb_port = ssm.get_parameter(\n Name='/{}/{}/common/DBPort'.format(STACK_PREFIX, STAGE)\n)['Parameter']['Value']\n\ndb_user = ssm.get_parameter(\n Name='/{}/{}/common/DBUser'.format(STACK_PREFIX, STAGE)\n)['Parameter']['Value']\n\ndb_password = ssm.get_parameter(\n Name='/{}/{}/common/DBPassword'.format(STACK_PREFIX, STAGE)\n)['Parameter']['Value']\n\ndb_name = ssm.get_parameter(\n Name='/{}/{}/common/DBName'.format(STACK_PREFIX, STAGE)\n)['Parameter']['Value']\n\n\ndef _setup_db():\n connection_string = URL('postgresql', username=db_user,\n password=db_password, host=db_host, port=db_port,\n database=db_name)\n engine = create_engine(connection_string)\n return sessionmaker(bind=engine)\n\n\nDBSession = _setup_db()\nsession = None\nclient = None\n\n\ndef in_session(fn):\n @wraps(fn)\n def wrapper(event, context):\n\n # Create a session and client to handle this request\n global session\n global client\n session = DBSession()\n client = Client(session)\n\n return fn(event, context)\n return wrapper\n\n\n@in_session\ndef register_fileset(event, context):\n\n # Log the received event\n print('Received event: ' + json.dumps(event, indent=2))\n\n import_uuid = event['import_uuid']\n files = event['files']\n reader = event['reader']\n reader_software = event['reader_software']\n reader_version = event['reader_version']\n\n # Generate a uuid for this fileset\n uuid = str(uuid4())\n\n # TODO Call the fileset something more sensible than just the first 128\n # characters of the last path component of the entrypoint\n entrypoint = files[0].split('/')[-1][:128]\n\n client.create_fileset(uuid, entrypoint, reader, reader_software,\n reader_version, files, import_uuid)\n\n return uuid\n\n\ndef submit_job(event, context):\n\n # Log the received event\n print('Received event: ' + json.dumps(event, indent=2))\n\n try:\n # Get current job queue\n job_queue = ssm.get_parameter(\n Name='/{}/{}/batch/JobQueueARN'.format(STACK_PREFIX, STAGE)\n )['Parameter']['Value']\n\n # Get current job definition\n # TODO Use the reader_software and reader_version to determine which\n # Job Definition to use\n job_definition = ssm.get_parameter(\n Name='/{}/{}/batch/BFExtractJobDefinitionARN'.format(STACK_PREFIX,\n STAGE)\n )['Parameter']['Value']\n\n # Set parameters\n parameters = {\n 'dir': event['import_uuid'],\n 'file': event['files'][0],\n 'reader': event['reader'],\n 'reader_software': event['reader_software'],\n 'reader_version': event['reader_version'],\n 'fileset_uuid': event['fileset_uuid'],\n 'bucket': tile_bucket.split(':')[-1]\n }\n\n print('Parameters:' + json.dumps(parameters, indent=2))\n\n job_name = 'bf_extract'\n\n # Submit a Batch Job\n response = batch.submit_job(\n jobQueue=job_queue,\n jobName=job_name,\n jobDefinition=job_definition,\n parameters=parameters\n )\n\n # Log response from AWS Batch\n print('Response: ' + json.dumps(response, indent=2))\n\n # Return the jobId\n return response['jobId']\n\n except Exception as e:\n print(e)\n message = 'Error submitting Batch Job'\n print(message)\n raise Exception(message)\n\n\ndef check_status_job(event, context):\n # Log the received event\n print('Received event: ' + json.dumps(event, indent=2))\n\n # Get jobId from the event\n job_id = event\n\n try:\n # Call DescribeJobs\n response = batch.describe_jobs(jobs=[job_id])\n\n # Log response from AWS Batch\n print('Response: ' + json.dumps(response, indent=2))\n\n # Return the jobtatus\n return response['jobs'][0]['status']\n\n except Exception as e:\n print(e)\n message = 'Error getting Batch Job status'\n print(message)\n raise Exception(message)\n\n\ndef _chunk(l, n):\n for i in range(0, len(l), n):\n yield l[i:i+n]\n\n\n@in_session\ndef handle_raw_storage_level(event, context):\n\n # Log the received event\n print('Received event: ' + json.dumps(event, indent=2))\n\n import_uuid = event['import_uuid']\n files = event['files']\n\n # TODO client methods to get an ancestor\n import_ = client.get_import(import_uuid)['data']\n repository = client.get_repository(import_['repository_uuid'])['data']\n storage_level = repository['raw_storage']\n bucket = raw_bucket.split(':')[-1]\n\n if storage_level in ('Destroy', 'Archive'):\n keys = [f'{import_uuid}/{file}' for file in files]\n\n if storage_level == 'Destroy':\n logger.info('Destroying: ' + ', '.join(keys))\n objs = [{'Key': key} for key in keys]\n for chunk in _chunk(objs, 1000):\n response = s3.delete_objects(\n Bucket=bucket,\n Delete={\n 'Objects': chunk,\n 'Quiet': True\n }\n )\n logger.error(str(response))\n elif storage_level == 'Archive':\n logger.info('Archiving: ' + ', '.join(keys))\n tagging = {\n 'TagSet': [\n {\n 'Key': 'archive',\n 'Value': 'true'\n }\n ]\n }\n for key in keys:\n s3.put_object_tagging(\n Bucket=bucket,\n Key=key,\n Tagging=tagging\n )\n","sub_path":"serverless/batch/bf_extract.py","file_name":"bf_extract.py","file_ext":"py","file_size_in_byte":6577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"321521122","text":"import re\nfrom dataclasses import dataclass\nfrom enum import Enum\nfrom functools import reduce\nfrom typing import Optional\n\n\ndef main() -> None:\n with open(\"./advent_of_code/day11/input.txt\") as f:\n raw_input = f.read()\n\n print(f\"Part 1: {part1(raw_input)}\")\n print(f\"Part 2: {part2(raw_input)}\")\n\n\n@dataclass\nclass Operation:\n class Op(Enum):\n ADD = \"ADD\"\n MUL = \"MUL\"\n\n lhs: Optional[int] # None means old\n rhs: Optional[int] # None means old\n op: Op\n\n def apply(self, old: int) -> int:\n lhs = self.lhs if self.lhs is not None else old\n rhs = self.rhs if self.rhs is not None else old\n return lhs + rhs if self.op == self.Op.ADD else lhs * rhs\n\n\n@dataclass\nclass Monkey:\n items: list[int]\n operation: Operation\n test_divisible_by: int\n if_true_monkey_index: int\n if_false_monkey_index: int\n\n def next_monkey_index(self, value: int) -> int:\n return self.if_true_monkey_index if value % self.test_divisible_by == 0 else self.if_false_monkey_index\n\n\noperation_regex = re.compile(r\"new = (\\d+|old) ([+*]) (\\d+|old)\")\n\n\ndef parse_operation(operation: str) -> Operation:\n match = operation_regex.match(operation)\n if match is None:\n raise ValueError(f\"Could not parse operation: {operation}\")\n\n lhs, op, rhs = match.groups()\n\n return Operation(\n lhs=int(lhs) if lhs != \"old\" else None,\n rhs=int(rhs) if rhs != \"old\" else None,\n op=Operation.Op.ADD if op == \"+\" else Operation.Op.MUL,\n )\n\n\nmonkey_regex = re.compile(\n r\"Monkey (\\d+):\\n Starting items: (.+)\\n Operation: (.+)\\n Test: divisible by (\\d+)\\n If true: throw to monkey (\\d+)\\n If false: throw to monkey (\\d+)\" # noqa\n)\n\n\ndef parse_monkey(monkey: str) -> Monkey:\n match = monkey_regex.match(monkey)\n if match is None:\n raise ValueError(f\"Could not parse monkey: {monkey}\")\n\n _, items, operation, test_divisible_by, if_true_monkey_index, if_false_monkey_index = match.groups()\n\n return Monkey(\n items=[int(item) for item in items.split(\", \")],\n operation=parse_operation(operation),\n test_divisible_by=int(test_divisible_by),\n if_true_monkey_index=int(if_true_monkey_index),\n if_false_monkey_index=int(if_false_monkey_index),\n )\n\n\ndef part1(raw_input: str) -> int:\n monkeys = [parse_monkey(monkey) for monkey in raw_input.split(\"\\n\\n\")]\n monkeys_inspect_count = [0] * len(monkeys)\n\n for _ in range(20):\n for monkey_index, monkey in enumerate(monkeys):\n items = monkey.items\n monkey.items = []\n\n monkeys_inspect_count[monkey_index] += len(items)\n\n for item in items:\n worry = monkey.operation.apply(item) // 3\n next_monkey_index = monkey.next_monkey_index(worry)\n monkeys[next_monkey_index].items.append(worry)\n assert next_monkey_index != monkey_index\n\n monkeys_inspect_count.sort()\n return monkeys_inspect_count[-1] * monkeys_inspect_count[-2]\n\n\ndef part2(raw_input: str) -> int:\n monkeys = [parse_monkey(monkey) for monkey in raw_input.split(\"\\n\\n\")]\n monkeys_inspect_count = [0] * len(monkeys)\n max_mul = reduce(lambda acc, monkey: acc * monkey.test_divisible_by, monkeys, 1)\n\n for _ in range(10000):\n for monkey_index, monkey in enumerate(monkeys):\n items = monkey.items\n monkey.items = []\n\n monkeys_inspect_count[monkey_index] += len(items)\n\n for item in items:\n worry = monkey.operation.apply(item)\n next_monkey_index = monkey.next_monkey_index(worry)\n monkeys[next_monkey_index].items.append(worry % max_mul)\n assert next_monkey_index != monkey_index\n\n monkeys_inspect_count.sort()\n return monkeys_inspect_count[-1] * monkeys_inspect_count[-2]\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"2022/advent_of_code/day11/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"186460524","text":"\"\"\"\nall_hospitals_preCSV\n\n1. Reads in main text file\n2. Identifies each hospital object\n3. For each hospital object, calls Function single_hospital_csv()\n\"\"\"\n\n\nclass Hospital:\n def __init__(self,id,categories,details):\n self.id = id\n self.categories = categories\n self.details = details\n self.d3_feature_object = self.make_d3_feature_object()\n\n\n def make_d3_feature_object(self):\n return {\"type\":\"Feature\",\n \"id\":self.id,\n \"geometry\":\n {\"type\":\"Point\",\n \"coordinates\":[self.details[-2],self.details[-1]]\n },\n \"properties\": self.return_single_hospital_dict()\n }\n\n\n def return_single_hospital_dict(self):\n import json\n thisDict = {}\n for i in range(len(self.details)):\n thisDict[self.categories[i]] = self.details[i]\n return thisDict\n\n def cleanAll(self):\n self._cleanLonLat()\n self._cleanCurrentStatus()\n self._cleanAddress()\n self._cleanListStrings()\n self._cleanCategories()\n\n def _cleanInnerLists(self):\n innerLists = [\"Closure Year\",\"Number of Beds\"]\n\n def _cleanLonLat(self):\n if self.categories[-1] == \"Coordinates\":\n theseCoords = self.details[-1][0].split(\",\")\n lon = theseCoords[0]\n lat = theseCoords[1]\n\n self.categories.pop()\n self.details.pop()\n\n self.categories.append(\"Longitude\")\n self.categories.append(\"Latitude\")\n self.details.append(float(lon))\n self.details.append(float(lat))\n\n elif self.categories[-1] == \"Latitude\":\n self.details[-1] = float(self.details[-1][0])\n self.details[-2] = float(self.details[-2][0])\n\n def _cleanCurrentStatus(self):\n if len(self.categories) == 11:\n self.categories.insert(-3,\"Current Status\")\n self.details.insert(-3,\"unknown\")\n\n def _cleanAddress(self):\n try:\n addressIndex = self.categories.index(\"Address\")\n self.categories.pop(addressIndex)\n self.details.pop(addressIndex)\n except ValueError:\n return\n\n def _cleanListStrings(self):\n for i in range(len(self.details)):\n if type(self.details[i]) == list:\n if len(self.details[i]) == 3:\n focusIndex = -1\n self.details[i] = int(self.details[i][focusIndex])\n else:\n focusIndex = 0\n self.details[i] = self.details[i][focusIndex]\n else:\n self.details[i] = self.details[i]\n\n def _cleanCategories(self):\n for i in range(len(self.categories)):\n self.categories[i] = self.categories[i].replace(\" \",\"_\")\n\n def __str__(self):\n return str(self.details[:])\n\nclass Hospitals:\n def __init__(self):\n self.numHospitals = 0\n self.hospitalList = [] # list of hospital objects\n\n def getInfo(self):\n from random import randint\n print(\"Number of Hospitals: \",self.numHospitals)\n print(\"Random Hospital Data:\\n\"+ self.hospitalList[randint(0,self.numHospitals)].__str__())\n\n def cleanHospitals(self):\n for hospital in self.hospitalList:\n hospital.cleanAll()\n\n def createHospital(self,hosString):\n \"\"\"Creates new hospital object, appends it to list of hospitals \"\"\"\n newId = self.numHospitals\n categories, details = self._parseHospital(hosString)\n newHospital = Hospital(newId,categories,details)\n self.hospitalList.append(newHospital)\n self.numHospitals+=1\n\n def _parseHospital(self,thisHospital):\n thisHospital = thisHospital.replace(\"\\\\\",\"\").replace(\"\\\\n\",\"\")\n thisHospital = thisHospital.replace(\"n,1]n\",\"]\").replace(\"n,3]n\",\"]\").replace(\"null\",\"None\")\n\n thisHospital_data = eval(thisHospital)\n categories = []\n details = []\n for item in thisHospital_data:\n categories.append(item[0])\n details.append(item[1])\n return categories, details\n\n def _findAll(self,big_string,hosStart,hosEnd):\n import re\n startList = []\n for start in re.finditer(hosStart, big_string):\n startList.append(start.start()-3)\n\n endList = []\n for end in re.finditer(hosEnd, big_string):\n endList.append(end.end())\n\n return startList, endList\n\n\n def parseMainData(self,fileName):\n \"\"\"Method to parse a specific text file with hospital information\"\"\"\n file = open(fileName,\"r\",encoding='utf-8')\n data_string = file.read()\n\n hosStart = '\"Hospital\\\\\\\\\",'\n hosEnd = '\\\\\\\\n,1]\\\\\\\\n]'\n\n startList, endList = self._findAll(data_string,hosStart,hosEnd)\n\n hospital_string_list = []\n for i in range(len(startList)):\n this_hospital_string = data_string[startList[i]:endList[i]]\n hospital_string_list.append(this_hospital_string)\n\n return hospital_string_list\n\n def createAllHospitals(self,hospital_string_list):\n for each_hospital in hospital_string_list:\n self.createHospital(each_hospital)\n\n def doMagic(self,filename):\n firstParse = self.parseMainData(filename)\n self.createAllHospitals(firstParse)\n self.cleanHospitals()\n\n\n def makeJSON(self):\n import json\n myDict = [] #overall dictionary\n for hospital in self.hospitalList:\n myDict.append(hospital.return_single_hospital_dict())\n\n\n jsonData = json.dumps(myDict)\n with open('hospitals.json', 'w') as f:\n json.dump(jsonData, f)\n return jsonData\n\n def makeD3_JSON(self):\n import json\n myDict = {\"type\":\"FeatureCollection\"}\n\n\n feature_object_list = [] #overall dictionary\n for hospital in self.hospitalList:\n feature_object_list.append(hospital.make_d3_feature_object())\n\n myDict[\"features\"] = feature_object_list\n jsonData = json.dumps(myDict)\n with open('hospitals.json', 'w') as f:\n json.dump(jsonData, f)\n return jsonData\n\n\n def __str__(self):\n returnList = []\n for item in self.hospitalList: returnList.append(item.details)\n return str(returnList)\n\ndef main():\n h = Hospitals()\n file = \"pre-parse-hospitals.txt\"\n h.doMagic(file)\n print(h.makeD3_JSON())\n\nif __name__ == '__main__':\n main()\n","sub_path":"preprocessing/workingMain.py","file_name":"workingMain.py","file_ext":"py","file_size_in_byte":6505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"214544565","text":"#!/usr/bin/python -O\r\n# -*- coding: iso-8859-15 -*-\r\n# -O Optimize e non scrive il __debug__\r\n#\r\n# Version 0.01 08/04/2010: Starting\r\n# ####################################################################################################################\r\nimport sys, os\r\nimport logging\r\nimport logging.config # obbligatorio altrimenti da' l'errore: <'module' object has no attribute 'config'>\r\n\r\n\r\n# ---- Note riguardo lo STACK Trace ----\r\n# ---- http://blog.dscpl.com.au/2015/03/generating-full-stack-traces-for.html\r\nimport inspect\r\n\r\ngPackageQualifiers = 0\r\n # ========================================================\r\n # - INIT del log. Chiamato solo dal MAIN program\r\n # ========================================================\r\ndef initLogger(loggerFile, package, packageQualifiers=2):\r\n global gPackageQualifiers\r\n gPackageQualifiers = packageQualifiers\r\n\r\n try:\r\n logging.config.fileConfig(loggerFile, disable_existing_loggers=False)\r\n except Exception as why:\r\n print(\"{0} - ERROR in file: {1}\".format(str(why), loggerFile))\r\n sys.exit(1)\r\n\r\n logger = logging.getLogger(package)\r\n savedLevel = logger.getEffectiveLevel()\r\n logger.setLevel(logging.INFO)\r\n for i in range(1,10): logger.info(' ')\r\n for i in range(1,5): logger.info('-'*40 + 'Start LOGging' + '-'*20)\r\n logger.setLevel(savedLevel)\r\n logFileName = logging.getLoggerClass().root.handlers[0].baseFilename\r\n return logFileName\r\n\r\n\r\n # ========================================================\r\n # - SetUp del log. Chiamato dai singoli moduli.\r\n # ========================================================\r\ndef setLogger(gv, callerLevel=1, package=None):\r\n global gPackageQualifiers\r\n if not package:\r\n caller = inspect.stack()[callerLevel]\r\n programFile = caller[1] # full name\r\n lineNumber = caller[2]\r\n funcName = caller[3]\r\n lineCode = caller[4]\r\n\r\n fname = os.path.basename(programFile).split('.')[0]\r\n package = fname + '.' + funcName\r\n\r\n\r\n # ------------------------------------------------\r\n # - del package cerchiamo di prendere\r\n # - solo gli ultimi gPackageQualifiers.\r\n # ------------------------------------------------\r\n packageHier = package.split('.')\r\n pkgName = ('.'.join(packageHier[-gPackageQualifiers:]))\r\n\r\n logger = logging.getLogger(pkgName)\r\n return logger\r\n","sub_path":"LnLogger/SetLogger.py","file_name":"SetLogger.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"355465552","text":"import logging\nimport json\n\nfrom pycalico.datastore import DatastoreClient\nfrom pycalico.datastore_datatypes import Rules, Rule\n\nfrom constants import *\nfrom policy_parser import PolicyParser\n\n_log = logging.getLogger(\"__main__\")\nclient = DatastoreClient()\n\n\ndef add_update_network_policy(policy):\n \"\"\"\n Takes a new network policy from the Kubernetes API and\n creates the corresponding Calico policy configuration.\n \"\"\"\n # Determine the name for this policy.\n name = \"%s.%s\" % (policy[\"metadata\"][\"namespace\"],\n policy[\"metadata\"][\"name\"])\n _log.debug(\"Adding new network policy: %s\", name)\n\n\n # Parse this network policy so we can convert it to the appropriate\n # Calico policy. First, get the selector from the API object.\n k8s_selector = policy[\"spec\"][\"podSelector\"]\n k8s_selector = k8s_selector or {}\n\n # Build the appropriate Calico label selector. This is done using\n # the labels provided in the NetworkPolicy, as well as the\n # NetworkPolicy's namespace.\n namespace = policy[\"metadata\"][\"namespace\"]\n selectors = [\"%s == '%s'\" % (k, v) for k, v in\n k8s_selector.iteritems()]\n selectors += [\"%s == '%s'\" % (K8S_NAMESPACE_LABEL, namespace)]\n selector = \" && \".join(selectors)\n\n # Build the Calico rules.\n try:\n inbound_rules = PolicyParser(policy).calculate_inbound_rules()\n except Exception:\n # It is possible bad rules will be passed - we don't want to\n # crash the agent, but we do want to indicate a problem in the\n # logs, so that the policy can be fixed.\n _log.exception(\"Error parsing policy: %s\",\n json.dumps(policy, indent=2))\n else:\n rules = Rules(id=name,\n inbound_rules=inbound_rules,\n outbound_rules=[Rule(action=\"allow\")])\n\n # Create the network policy using the calculated selector and rules.\n client.create_policy(NET_POL_TIER_NAME, name,\n selector, order=10, rules=rules)\n _log.debug(\"Updated policy '%s' for NetworkPolicy\", name)\n\n\ndef delete_network_policy(policy):\n \"\"\"\n Takes a deleted network policy and removes the corresponding\n configuration from the Calico datastore.\n \"\"\"\n # Determine the name for this policy.\n name = \"%s.%s\" % (policy[\"metadata\"][\"namespace\"],\n policy[\"metadata\"][\"name\"])\n _log.debug(\"Deleting network policy: %s\", name)\n\n # Delete the corresponding Calico policy\n try:\n client.remove_policy(NET_POL_TIER_NAME, name)\n except KeyError:\n _log.info(\"Unable to find policy '%s' - already deleted\", name)\n","sub_path":"handlers/network_policy.py","file_name":"network_policy.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"576740453","text":"from PyQt5 import *\nimport pyqtgraph as pg\nimport numpy as np\n\nclass TemperatureModule_Accelerometer:\n def __init__(self, inlet):\n pg.setConfigOption(\"background\", \"k\") # graph background color\n pg.setConfigOption(\"foreground\", \"w\") # graph foreground color\n pg.setConfigOption(\"antialias\", True)\n self.graphWidget = pg.PlotWidget() # pyqtgraph PlotWidget Class\n self.graphWidget.setTitle(\n ' Accelerometer '\n ) # Set Title\n self.graphWidget.setLabel(\n \"left\", 'Acceleration'\n ) # left label\n self.graphWidget.setLabel(\n \"bottom\", 'Number of samples'\n ) # Bottom label\n self.graphWidget.showGrid(x=True, y=True, alpha=0.3) # Create a Grid\n\n # Get initial data\n self.seconds = [] # seconds data array, x value\n self.accel = [[], [], []] # Holds acceleration value,\n\n self.x_curve = self.graphWidget.plot() # plot initialization, x value\n self.y_curve = self.graphWidget.plot() # plot initialization, y value\n self.z_curve = self.graphWidget.plot() # plot initialization, z value\n\n self.graphWidget.setRange(\n yRange=(-5000, 5000)\n ) # change the visible x range of the graph\n text_box = pg.TextItem(\n html='- X value - Y value - Z value ',\n anchor=(0, 0),\n border=None,\n fill=None,\n angle=0,\n rotateAxis=None,\n )\n text_box.setPos(0, 5000)\n self.graphWidget.addItem(text_box)\n\n self.label = QtGui.QLabel() # Accelerometer Number Display\n self.inlet = inlet\n\n def getValues(self, sample):\n # 78: AccelX, 79: AccelY, 80:AccelZ\n xVal = sample[0][77]\n yVal = sample[0][78]\n zVal = sample[0][79]\n self.update(xVal, yVal, zVal)\n\n def update(self, xVal, yVal, zVal):\n if len(self.accel[0]) < 200: # First 500 samples\n self.accel[0].append(xVal)\n self.accel[1].append(yVal)\n self.accel[2].append(zVal)\n else: # after ten seconds\n self.accel[0].pop(0) # Pop one data to shift plot\n self.accel[1].pop(0) # Pop one data to shift plot\n self.accel[2].pop(0) # Pop one data to shift plot\n\n self.accel[0].append(xVal)\n self.accel[1].append(yVal)\n self.accel[2].append(zVal)\n\n self.x_curve.setData(self.accel[0], pen=pg.mkPen(\"#FFA500\", width=2))\n self.y_curve.setData(self.accel[1], pen=pg.mkPen(\"#0ffe1d\",width=2))\n self.z_curve.setData(self.accel[2], pen=pg.mkPen(\"#03ffff\",width=2))\n\n self.label.setText(\n 'Accelerometer

    x: '\n + str(np.round(xVal, 2))\n + \" m/s²
    y: \"\n + str(np.round(yVal, 2))\n + \" m/s²
    z: \"\n + str(np.round(zVal, 2))\n + \" m/s²
    \"\n )\n\n \n\n","sub_path":"temperatureModule/TemperatureModule_Accelerometer.py","file_name":"TemperatureModule_Accelerometer.py","file_ext":"py","file_size_in_byte":3289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"449656018","text":"import json\n\n\nclass JsonManager:\n \"\"\" It will loads data and dumps data into json. Written By Saurav Paul\"\"\"\n\n @staticmethod\n def json_read(json_file):\n try:\n with open(json_file, \"r\") as read_file:\n data = json.load(read_file)\n return data\n except Exception as e:\n print(e)\n\n @staticmethod\n def json_write(json_file, data=None):\n if data is None:\n data = {}\n try:\n with open(json_file, \"w\") as write_file:\n json.dump(data, write_file)\n\n json.dumps(data)\n except Exception as e:\n print(e)\n","sub_path":"build/lib/tools/json_manager.py","file_name":"json_manager.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"433029277","text":"from django.conf.urls import url, include\nfrom . import views\n# from django.contrib import admin\n\nurlpatterns = [\n url(r'^$', views.index),\n url(r'^newCourse$', views.newCourse),\n url(r'^remove/(?P\\d+)$', views.remove),\n url(r'^dontDestroy$', views.dontDestroy),\n url(r'^destroy/(?P\\d+)$', views.destroy),\n\n]\n","sub_path":"Django/courses/apps/coursesApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"98989360","text":"#MenuTitle: Sync Components Across Masters\n# -*- coding: utf-8 -*-\nfrom __future__ import division, print_function, unicode_literals\n__doc__=\"\"\"\nTakes the current layer’s components, and resets all other masters to the same component structure. Ignores paths and anchors.\n\"\"\"\n\nthisFont = Glyphs.font # frontmost font\nthisFontMaster = thisFont.selectedFontMaster # active master\nlistOfSelectedLayers = thisFont.selectedLayers # active layers of selected glyphs\n\ndef baseHasAnchor( thisComponent, masterID, anchorToLookFor ):\n\tbaseGlyph = thisComponent.component\n\tbaseLayer = baseGlyph.layers[masterID]\n\tbaseAnchors = [a for a in baseLayer.anchors]\n\tanchorIsInLayer = False\n\tfor i in range(len(baseAnchors)):\n\t\tif baseAnchors[i].name == anchorToLookFor:\n\t\t\tanchorIsInLayer = True\n\treturn anchorIsInLayer\n\ndef process( thisLayer ):\n\tthisGlyph = thisLayer.parent\n\tcompSet = thisLayer.componentNames()\n\t\n\t# only act if components are present:\n\tif compSet: \n\t\t\n\t\t# see if there are special anchors (e.g., top_1, top_2, etc.) the components are attached to:\n\t\tcomponentAnchors = [ None ]\n\t\tnumberOfComponents = len(compSet)\n\t\tfor i in range( 1, numberOfComponents ):\n\t\t\tthisAnchor = thisLayer.components[i].anchor\n\t\t\tcomponentAnchors.append( thisAnchor )\n\t\n\t\t# go through all other layers:\n\t\tfor thatLayer in thisGlyph.layers:\n\t\t\tif thatLayer != thisLayer: # don't sync the layer with itself\n\t\t\t\tthatLayerID = thatLayer.layerId\n\t\t\t\tif thatLayerID == thatLayer.associatedMasterId: # only sync master layers\n\t\t\t\t\tthatLayer.setComponentNames_( compSet ) # sync components\n\t\t\t\t\t\n\t\t\t\t\t# try to attach the newly synced components to the right anchors:\n\t\t\t\t\tif len(thatLayer.components) == numberOfComponents:\n\t\t\t\t\t\tbaseComponent = thatLayer.components[0]\n\t\t\t\t\t\tfor i in range( 1, numberOfComponents ):\n\t\t\t\t\t\t\tthisAnchor = componentAnchors[i]\n\t\t\t\t\t\t\tif thisAnchor:\n\t\t\t\t\t\t\t\tif baseHasAnchor( baseComponent, thatLayerID, thisAnchor ):\n\t\t\t\t\t\t\t\t\tthatComponent = thatLayer.components[i]\n\t\t\t\t\t\t\t\t\tthatComponent.setAnchor_( thisAnchor )\n\nthisFont.disableUpdateInterface() # suppresses UI updates in Font View\n\nfor thisLayer in listOfSelectedLayers:\n\tthisGlyph = thisLayer.parent\n\tprint(\"Processing\", thisGlyph.name)\n\tthisGlyph.beginUndo() # begin undo grouping\n\tprocess( thisLayer )\n\tthisGlyph.endUndo() # end undo grouping\n\nthisFont.enableUpdateInterface() # re-enables UI updates in Font View\n","sub_path":"Components/Sync Components Across Masters.py","file_name":"Sync Components Across Masters.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"376487953","text":"import numpy as np\nfrom scipy.special import gamma\nimport matplotlib.pyplot as plt\nimport sobol_seq\n\ndef getSphereVolumeExact(D, R = 1.0):\n\n\n #через явную формулу и гамма-функцию из модуля scipy, как и просили в условии\n V = (np.pi ** (D/2) * R ** D) / gamma(1 + D/2)\n\n\n\n\n \"\"\"\n Функция вычисляет значение объема D-мерной сферы радиуса R рекурентным методом\n\n --------\n Аргументы:\n D - int, количество измерений\n R = 1 - float, радиус сферы\n --------\n Функция возвращает:\n V - float, объем сферы\n \"\"\"\n\n\n return V\n\n\ndef getSphereVolumePseudorandom(N, D, R = 1.0):\n\n def inside(point, R):\n sum = 0\n for i in range(len(point)):\n sum += point[i] ** 2\n result = sum < R ** 2\n return result\n\n rndm = np.random.RandomState(12345)\n\n\n array_shoots = rndm.uniform(low=-1, high=1, size=(N, D))\n\n hits = 0\n for i in array_shoots:\n if inside(i, R) == True:\n hits += 1\n\n V = (hits / N) * ((2*R)**D) #умножаем отношение попаданий к общему числу выстрелов на объем гиперкуба размерности D,\n # стороны 2R, чтобы влезла сфера\n\n \"\"\"\n Функция вычисляет значение объема D-мерной сферы радиуса R\n\n --------\n Аргументы:\n N - int, количество случайных точек\n D - int, количество измерений\n R = 1 - float, радиус сферы\n --------\n Функция возвращает:\n V - float, объем сферы\n \"\"\"\n\n return V\n\n\n\n\n\n\n\ndef getSphereVolumeQuasirandom(N, D, R = 1.0):\n\n def inside(point, R):\n sum = 0\n for i in range(len(point)):\n sum += point[i] ** 2\n result = sum < R ** 2\n return result\n\n\n\n array_shoots = sobol_seq.i4_sobol_generate(D, N)\n\n\n hits = 0\n for i in array_shoots:\n if inside(i, R) == True:\n hits += 1\n\n V = (hits / N) * ((2*R)**D)\n\n\n \"\"\"\n Функция вычисляет значение объема D-мерной сферы радиуса R\n\n --------\n Аргументы:\n N - int, количество случайных точек\n D - int, количество измерений\n R = 1 - float, радиус сферы\n --------\n Функция возвращает:\n V - float, объем сферы\n \"\"\"\n\n return V\n\n\n\n\ndef main_1(N):\n\n V_exact_array = []\n eps_pseudo = []\n\n dimensions = [i for i in range(1, 11)] #построим график для первых 15 измерений (этого будет достаточно чтобы сделать\n # выводы о том какая сетка случайных чисел лучше\n\n for D in range(1, 11):\n V_exact = getSphereVolumeExact(D, R=1.0)\n V_random = getSphereVolumePseudorandom(N, D, R=1.0)\n V_exact_array.append(V_exact)\n eps_pseudo.append((V_exact - V_random) / V_exact) # будем считать ошибку по данной формуле, да и график впоследствии\n # не будем рисовать в логарифмическом масштабе, так как и без него прекрасно видно, какой из методов\n # выигрывает, а картинка так получается красивее\n\n plt.figure()\n plt.title('Exact formula сalculation of volume of the hypersphere')\n plt.grid()\n plt.ylabel('Volume')\n plt.xlabel('number_of_dimensions')\n plt.plot(dimensions, V_exact_array, label='formula calculated volume of hypersphere')\n plt.legend()\n plt.show()\n\n eps_quasi = []\n for D in range(1, 11):\n V_exact = getSphereVolumeExact(D, R=1.0)\n V_random = getSphereVolumeQuasirandom(N, D, R=1.0)\n eps_quasi.append((V_exact - V_random) / V_exact ) #так же как и в случае с псевдорандомными\n\n\n\n plt.figure()\n plt.title('Relative accuracy - N_dimensions for {} points'.format(N))\n plt.grid()\n plt.ylabel('eps')\n plt.xlabel('number_of_dimensions')\n plt.plot(dimensions, eps_pseudo, label='pseudorandom')\n plt.plot(dimensions, eps_quasi, 'r', label='quasirandom')\n plt.legend()\n plt.show()\n\n #из графика явно видно, что ошибка на квазислучайных меньше, соответсвтенно их использовать предпочтительнее!\n\nmain_1(1000) #накидаем 1000 выстрелов, лектор ставил по дефолту именно так\nmain_1(100) #также неплохо было бы посмотреть на график для 100 выстрелов, превосходство квазислучайных чисел тут даже виднее,\n#график точного объема вылезет второй раз, хотя его мы уже видели при первом вызове функции, прошу за это не карать\n\ndef getInitialState(N):\n\n state = np.random.choice([1, -1], size=(N, N))\n\n '''\n Функция задает случайное начальное состояние\n ---------\n Аргументы:\n N - int, линейный размер решетки \n --------\n Функция возвращает:\n state - numpy ndarray of ints, массив состояния системы размера NxN\n '''\n return state\n\n\ndef getDeltaE(i, j, state):\n N = state.shape[0] - 1\n state[i][j] *= -1\n if i != N and j != N:\n sum = state[i-1][j-1] + state[i-1][j] + state[i-1][j+1] + state[i][j-1] + state[i][j+1] + state[i+1][j-1] + state[i+1][j] + state[i+1][j+1]\n else:\n if i == N and j != N:\n sum = state[i - 1][j - 1] + state[i - 1][j] + state[i - 1][j + 1] + state[i][j - 1] + state[i][j + 1] + \\\n state[0][j - 1] + state[0][j] + state[0][j + 1]\n if i != N and j == N:\n sum = state[i - 1][j - 1] + state[i - 1][j] + state[i - 1][0] + state[i][j - 1] + state[i][0] + \\\n state[i + 1][j - 1] + state[i + 1][j] + state[i + 1][0]\n if i == N and j == N:\n sum = state[i - 1][j - 1] + state[i - 1][j] + state[i - 1][0] + state[i][j - 1] + state[i][0] + \\\n state[0][j - 1] + state[0][j] + state[0][0]\n\n E_post = state[i][j] * sum\n\n E_prev = (-1) * state[i][j] * sum\n\n dE = E_post - E_prev\n '''\n Функция расчитывает изменение энергии ячейки (i,j) в случае ее переворота (при этом функция сама не меняет сосотояния state)\n ---------\n Аргументы:\n i - int, адресс ячейки вдоль оси 0\n j - int, адресс ячейки вдоль оси 1\n state - numpy ndarray of ints, массив состояния системы размера NxN\n --------\n Функция возвращает:\n dE - float, изменение энергии\n '''\n\n return dE\n\n\ndef makeFlip(T, state):\n N = state.shape[0] - 1\n for i in range(N+1):\n for j in range(N+1):\n delta_E = getDeltaE(i, j, state)\n if delta_E < 0:\n state[i][j] *= -1\n if delta_E >= 0:\n coefficient = np.random.choice([1, -1], p=[np.exp(-delta_E/T), 1 - np.exp(-delta_E/T)])\n state[i][j] *= coefficient\n '''\n Функция расчитывает изменение энергии ячейки (i,j) в случае ее переворота (при этом функция сама не меняет сосотояния state)\n ---------\n Аргументы:\n T - float, положительное число, безразмерный коэфициент, характеризующий температуру, равный kT/J\n state - numpy ndarray of ints, массив состояния системы размера NxN\n --------\n Функция возвращает:\n state - numpy ndarray of ints, массив нового состояния системы размера NxN\n '''\n return state\n\n\ndef getEnergy(state):\n\n N = state.shape[0] - 1\n E = 0\n\n def Energy(N, i, j, state):\n if i != N and j != N:\n sum = state[i - 1][j - 1] + state[i - 1][j] + state[i - 1][j + 1] + state[i][j - 1] + state[i][j + 1] + \\\n state[i + 1][j - 1] + state[i + 1][j] + state[i + 1][j + 1]\n else:\n if i == N and j != N:\n sum = state[i - 1][j - 1] + state[i - 1][j] + state[i - 1][j + 1] + state[i][j - 1] + state[i][j + 1] + \\\n state[0][j - 1] + state[0][j] + state[0][j + 1]\n if i != N and j == N:\n sum = state[i - 1][j - 1] + state[i - 1][j] + state[i - 1][0] + state[i][j - 1] + state[i][0] + \\\n state[i + 1][j - 1] + state[i + 1][j] + state[i + 1][0]\n if i == N and j == N:\n sum = state[i - 1][j - 1] + state[i - 1][j] + state[i - 1][0] + state[i][j - 1] + state[i][0] + \\\n state[0][j - 1] + state[0][j] + state[0][0]\n E_post = state[i][j] * sum\n return E_post\n\n for i in range(N + 1):\n for j in range(N + 1):\n E += Energy(N, i, j, state)\n '''\n Функция, рассчитывает значение энергии всей системы\n ---------\n Аргументы:\n state - numpy ndarray of ints, массив состояния системы размера NxN\n --------\n Функция возвращает:\n E - float, значение энергии системы\n '''\n\n return E\n\ndef getMagnetization(state):\n\n M = np.sum(state)\n\n '''\n Функция, рассчитывает значение намагниченности всей системы\n ---------\n Аргументы:\n state - numpy ndarray of ints, массив состояния системы размера NxN\n --------\n Функция возвращает:\n M - float, значение намагниченности системы\n '''\n\n return M\ndef main_2():\n N = 10 # размер решетки NxN\n Nt = 100 # количество точек температуры\n eqSteps = 150 # количество раз выполнения makeFlip для установления равновесия\n steps = 30 # количество раз выполнения makeFlip для усреднения энергии и намагниченности\n\n T = np.linspace(0.5, 5, Nt)\n E, M = np.zeros(Nt), np.zeros(Nt)\n\n\n for t in range(Nt):\n print(\"Complete\", t / Nt * 100, '%\\r', end='')\n\n Esum = Msum = 0\n state = getInitialState(N)\n\n for i in range(eqSteps): # установление статистического равновесия\n makeFlip(T[t], state)\n\n for i in range(steps): # суммирование по разным состояниям близким к равновеснсому\n makeFlip(T[t], state)\n Esum += getEnergy(state)\n Msum += getMagnetization(state)\n\n E[t] = Esum / (steps * N * N)\n M[t] = Msum / (steps * N * N)\n\n print(\"Done \\r\", end='')\n\n\n _, ax = plt.subplots(1, 2, figsize=(10, 5))\n\n ax[0].scatter(T, E)\n ax[0].set_xlabel(\"Temperature\")\n ax[0].set_ylabel(\"Energy \")\n\n ax[1].scatter(T, -abs(M), color='blue')\n ax[1].set_xlabel(\"Temperature\")\n ax[1].set_ylabel(\"Magnetization \")\n\n plt.show()\n\n #Не очень хорошо, но видно явление гистерезиса (или чего-то близкого к нему) Наблюдаемое похоже на поведение ферромагнетиков.\n # На низких температурах высокая намагниченность, потом начинает стремительно падать\n\n\nmain_2()","sub_path":"CP_9_Doronkin.py","file_name":"CP_9_Doronkin.py","file_ext":"py","file_size_in_byte":12405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"75361040","text":"import cv2\nimport numpy as np\nimport imutils\nimport lip\nimport dlib\nfrom imutils import face_utils\n\n# initialize dlib's face detector (HOG-based) and then create\n# the facial landmark predictor\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')\n\ndef get_hsv_mask(img, debug=False):\n assert isinstance(img, np.ndarray), 'image must be a np array'\n assert img.ndim == 3, 'skin detection can only work on color images'\n\n lower_thresh = np.array([0, 50, 0], dtype=np.uint8)\n upper_thresh = np.array([120, 150, 255], dtype=np.uint8)\n img_hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV)\n msk_hsv = cv2.inRange(img_hsv, lower_thresh, upper_thresh)\n\n #msk_hsv[msk_hsv < 128] = 0\n #msk_hsv[msk_hsv >= 128] = 1\n\n return msk_hsv.astype(float)\n\n\ndef get_rgb_mask(img, debug=False):\n assert isinstance(img, np.ndarray), 'image must be a np array'\n assert img.ndim == 3, 'skin detection can only work on color images'\n\n lower_thresh = np.array([45, 52, 108], dtype=np.uint8)\n upper_thresh = np.array([255, 255, 255], dtype=np.uint8)\n\n mask_a = cv2.inRange(img, lower_thresh, upper_thresh)\n mask_b = 255 * ((img[:, :, 2] - img[:, :, 1]) / 20)\n mask_c = 255 * ((np.max(img, axis=2) - np.min(img, axis=2)) / 20)\n\n mask_a = mask_a.astype(float)\n\n msk_rgb = cv2.bitwise_and(mask_a, mask_b)\n msk_rgb = cv2.bitwise_and(mask_c, msk_rgb)\n\n msk_rgb[msk_rgb < 128] = 0\n msk_rgb[msk_rgb >= 128] = 255\n\n return msk_rgb.astype(float)\n\n\ndef get_ycrcb_mask(img, debug=False):\n assert isinstance(img, np.ndarray), 'image must be a np array'\n assert img.ndim == 3, 'skin detection can only work on color images'\n\n lower_thresh = np.array([90, 100, 130], dtype=np.uint8)#90\n upper_thresh = np.array([230, 120, 180], dtype=np.uint8)#230\n\n img_ycrcb = cv2.cvtColor(img, cv2.COLOR_RGB2YCR_CB)\n msk_ycrcb = cv2.inRange(img_ycrcb, lower_thresh, upper_thresh)\n\n #msk_ycrcb[msk_ycrcb < 128] = 0\n #msk_ycrcb[msk_ycrcb >= 128] = 1\n\n return msk_ycrcb.astype(float)\n\n\ndef grab_cut_mask(img_col, mask, debug=False):\n assert isinstance(img_col, np.ndarray), 'image must be a np array'\n assert isinstance(mask, np.ndarray), 'mask must be a np array'\n assert img_col.ndim == 3, 'skin detection can only work on color images'\n assert mask.ndim == 2, 'mask must be 2D'\n\n kernel = np.ones((50, 50), np.float32) / (50 * 50)\n dst = cv2.filter2D(mask, -1, kernel)\n dst[dst != 0] = 255\n free = np.array(cv2.bitwise_not(dst), dtype=np.uint8)\n\n grab_mask = np.zeros(mask.shape, dtype=np.uint8)\n grab_mask[:, :] = 2\n grab_mask[mask == 255] = 1\n grab_mask[free == 255] = 0\n\n if np.unique(grab_mask).tolist() == [0, 1]:\n bgdModel = np.zeros((1, 65), np.float64)\n fgdModel = np.zeros((1, 65), np.float64)\n\n if img_col.size != 0:\n mask, bgdModel, fgdModel = cv2.grabCut(img_col, grab_mask, None, bgdModel, fgdModel, 5,\n cv2.GC_INIT_WITH_MASK)\n mask = np.where((mask == 2) | (mask == 0), 0, 1).astype(np.uint8)\n else:\n print('img_col is empty')\n\n return mask\n\n\ndef closing(mask):\n assert isinstance(mask, np.ndarray), 'mask must be a np array'\n assert mask.ndim == 2, 'mask must be a greyscale image'\n\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))\n mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=2)\n\n return mask\n\n\ndef process(img, thresh=0.5, debug=False):\n assert isinstance(img, np.ndarray), 'image must be a np array'\n assert img.ndim == 3, 'skin detection can only work on color images'\n\n mask_hsv = get_hsv_mask(img, debug=debug)\n mask_rgb = get_rgb_mask(img, debug=debug)\n mask_ycrcb = get_ycrcb_mask(img, debug=debug)\n\n n_masks = 3.0\n mask = np.where((mask_hsv + mask_rgb + mask_ycrcb)/3>255/2,255,0)\n\n #mask[mask < thresh] = 0.0\n #mask[mask >= thresh] = 255.0)\n\n mask = mask.astype(np.uint8)\n mask = closing(mask)\n mask = grab_cut_mask(img, mask, debug=debug)\n kernel = np.ones((5,5),np.uint8)\n mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel, iterations=11)\n return mask\n\ndef draw_delaunay(img, subdiv, delaunay_color) :\n triangleList = subdiv.getTriangleList()\n size = img.shape\n r = (0, 0, size[1], size[0])\n for t in triangleList :\n pt1 = (t[0], t[1])\n pt2 = (t[2], t[3])\n pt3 = (t[4], t[5])\n cv2.line(img, pt1, pt2, delaunay_color, 1, cv2.LINE_AA, 0)\n cv2.line(img, pt2, pt3, delaunay_color, 1, cv2.LINE_AA, 0)\n cv2.line(img, pt3, pt1, delaunay_color, 1, cv2.LINE_AA, 0)\n\ngmin = -1\ndef findtop(img, coord):\n global gmin\n mask = process(img)\n x, y = coord\n y = y-10\n if(gmin == -1):\n gmin = y+1\n else:\n if(gmin+20=15 or mask.item(y,x)==0):\n break\n gmin = y\n\n return (x,y)\n\n\ndef triangulate(image):\n global gmin\n\n # load the input image, resize it, and convert it to grayscale\n image = imutils.resize(image, width=500)\n img = image.copy() # used in manual editing\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n # detect faces in the grayscale image\n rects = detector(gray, 1)\n\n # loop over the face detections\n for (i, rect) in enumerate(rects):\n # determine the facial landmarks for the face region, then convert the facial landmark (x, y)-coordinates to a np array\n shape = predictor(gray, rect)\n shape = face_utils.shape_to_np(shape)\n\n # convert dlib's rectangle to a OpenCV-style bounding box [i.e., (x, y, w, h)], then draw the face bounding box\n (x, y, w, h) = face_utils.rect_to_bb(rect)\n cx = int(.15*w)\n cy = int(.5*h)\n\n # show the face number\n subdiv = cv2.Subdiv2D((max(x-cx,0), max(y-cy,0), min(w+x+cx,image.shape[1]), min(h+y+cx,image.shape[0])))\n forehead = []\n gmin = -1\n for num, (x, y) in enumerate(shape):\n\n\n if((num>=17 and num<=27)):\n forehead.append(findtop(image, (x,y)))\n\n cv2.circle(image, (x, y), 1, (0, 0, 255), -1)\n\n for item in forehead:\n shape = np.vstack((shape, item))\n\n for (x, y) in shape:\n subdiv.insert((int(x),int(y)))\n\n return shape, subdiv.getTriangleList()\n\ndef warp(src, dst):\n src_points, src_triangles = triangulate(src)\n dst_points, dst_triangles = triangulate(dst)\n warped_image = np.zeros(src.shape, dtype=np.uint8)\n\n for i,t in enumerate(dst_triangles):\n pt1 = (t[0], t[1])\n pt2 = (t[2], t[3])\n pt3 = (t[4], t[5])\n first, second, third = -1,-1,-1\n for i2, (x,y) in enumerate(dst_points):\n if(x==t[0] and y==t[1]):\n first = i2\n if(x==t[2] and y==t[3]):\n second = i2\n if(x==t[4] and y==t[5]):\n third = i2\n if(first>=0 and second>=0 and third>=0):\n x1,y1 = src_points[first]\n x2,y2 = src_points[second]\n x3,y3 = src_points[third]\n dx1,dy1 = dst_points[first]\n dx2,dy2 = dst_points[second]\n dx3,dy3 = dst_points[third]\n\n #creating mask in destination image\n mask = np.zeros(src.shape, dtype=np.uint8)\n roi_corners = np.array([[dx1,dy1],[dx2,dy2],[dx3,dy3]], dtype=np.int32)\n cv2.fillPoly(mask, [roi_corners], (255,255,255))\n\n #warping src image to destination image\n pts1 = np.float32([[x1,y1],[x2,y2],[x3,y3]])\n pts2 = np.float32([[dx1,dy1],[dx2,dy2],[dx3,dy3]])\n M = cv2.getAffineTransform(pts1,pts2)\n rows,cols,ch = src.shape\n res = cv2.warpAffine(src,M,(cols,rows))\n\n warped_image = cv2.bitwise_or(warped_image,cv2.bitwise_and(mask,res))\n\n '''\n cv2.line(src, pt1, pt2, (255, 255, 255), 1, cv2.LINE_AA, 0)\n cv2.line(src, pt2, pt3, (255, 255, 255), 1, cv2.LINE_AA, 0)\n cv2.line(src, pt3, pt1, (255, 255, 255), 1, cv2.LINE_AA, 0)\n '''\n\n return warped_image\n\ndef find_mask(image, betamap):\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n # detect faces in the grayscale image\n rects = detector(gray, 1)\n\n # loop over the face detections\n for (i, rect) in enumerate(rects):\n # determine the facial landmarks for the face region, then\n # convert the landmark (x, y)-coordinates to a np array\n shape = predictor(gray, rect)\n shape = face_utils.shape_to_np(shape)\n\n # loop over the face parts individually\n mask = np.zeros(image.shape, dtype=image.dtype)\n noseMask = np.zeros(image.shape, dtype=image.dtype)\n for (name, (i, j)) in face_utils.FACIAL_LANDMARKS_IDXS.items():\n\n clone = image.copy()\n cv2.putText(clone, name, (10, 30), cv2.FONT_HERSHEY_SIMPLEX,\n 0.7, (0, 0, 255), 2)\n\n if(betamap):\n if(name=='right_eyebrow' or name=='left_eyebrow'):\n continue\n if(name=='jaw'):\n continue\n else:\n if(name=='jaw' or name=='nose' or name=='left_eyebrow' or name=='right_eyebrow'):\n continue\n pts = shape[i:j]\n hull = cv2.convexHull(pts)\n if(name=='nose'):\n cv2.drawContours(noseMask, [hull], -1, (255,255,255), -1)\n else:\n cv2.drawContours(mask, [hull], -1, (255,255,255), -1)\n\n if(betamap):\n kernel = np.ones((5,5),np.uint8)\n dilation = cv2.dilate(mask,kernel,iterations = 4)\n gradient = cv2.morphologyEx(noseMask, cv2.MORPH_GRADIENT, kernel)\n gradient = cv2.dilate(gradient,kernel,iterations = 2)\n mask = dilation+gradient\n\n return mask\n\ndef overlay(orig, makeup, mask):\n\n blur_mask = cv2.blur(mask, (20, 20))\n new = makeup.copy()\n for y in range(0, orig.shape[0]):\n for x in range(0, orig.shape[1]):\n w = blur_mask[y][x]/255\n if (w > 0.6):\n w = (w - 0.6) / 0.4\n else:\n w = 0\n new[y][x] = makeup[y][x]*w + orig[y][x]*(1 - w)\n\n return new\n\ndef decompose(img):\n base = cv2.bilateralFilter(img, 9, 75,75)\n return base, img-base\n\ndef warp_target(subject, target):\n\n if(target.shape[0]>subject.shape[0]):\n new_subject = np.zeros((target.shape[0]-subject.shape[0],subject.shape[1],3), dtype=subject.dtype)\n subject = np.vstack((subject, new_subject))\n else:\n #resizing target\n new_target = np.zeros((subject.shape[0]-target.shape[0],target.shape[1],3), dtype=target.dtype)\n target = np.vstack((target, new_target))\n\n if(subject.shape[0]%2!=0):\n zero_layer = np.zeros((1, target.shape[1],3), dtype=target.dtype)\n target = np.vstack((target, zero_layer))\n subject = np.vstack((subject, zero_layer))\n\n warped_target = warp(target, subject)\n\n return subject, warped_target\n\ndef apply_makeup(subject, warped_target):\n zeros = np.zeros(warped_target.shape, dtype=warped_target.dtype)\n ones = np.ones(warped_target.shape, dtype=warped_target.dtype)\n face_mask = np.where(warped_target==[0,0,0], zeros, ones*255)\n # cv2.imshow('mask', face_mask)\n # cv2.waitKey(0)\n \n sub_lab = cv2.cvtColor(subject, cv2.COLOR_BGR2LAB)\n tar_lab = cv2.cvtColor(warped_target, cv2.COLOR_BGR2LAB)\n\n sl, sa, sb = cv2.split(sub_lab)\n tl, ta, tb = cv2.split(tar_lab)\n\n face_struct_s, skin_detail_s = decompose(sl)\n face_struct_t, skin_detail_t = decompose(tl)\n\n #color transfer\n gamma = .8\n '''\n type = sa.dtype\n sa.dtype = float\n ta.dtype = float\n sb.dtype = float\n tb.dtype = float\n '''\n type = sa.dtype\n ra = np.where(True, sa*(1-gamma)+ta*gamma, zeros[:,:,0])\n rb = np.where(True, sb*(1-gamma)+tb*gamma, zeros[:,:,0])\n ra = ra.astype(type)\n rb = rb.astype(type)\n #print(ra.shape)\n ra = cv2.bitwise_and(ra,ra,mask = face_mask[:,:,0])\n rb = cv2.bitwise_and(rb,rb,mask = face_mask[:,:,0])\n\n\n\n #skin-detail transfer\n gammaI = 0\n gammaE = 1\n skin_detail_r = np.where(True, skin_detail_s*gammaI + skin_detail_t*gammaE, zeros[:,:,0])\n skin_detail_r = skin_detail_r.astype(type)\n\n\n #Work on the base layer\n fp_mask = find_mask(subject, True)\n src_gauss = cv2.pyrDown(face_struct_s)\n src_lapla = face_struct_s - cv2.pyrUp(src_gauss)\n dst_gauss = cv2.pyrDown(face_struct_t)\n dst_lapla = face_struct_t - cv2.pyrUp(dst_gauss)\n face_struct_r = np.where(face_mask[:,:,0]==0, face_struct_s, dst_lapla + cv2.pyrUp(src_gauss))\n\n face_struct_r = np.where(fp_mask[:,:,0]==255, face_struct_s, face_struct_r)\n\n rl = face_struct_r+skin_detail_r\n rl = cv2.bitwise_and(rl,rl,mask = face_mask[:,:,0])\n\n res_lab = cv2.merge((rl, ra, rb))\n res = cv2.cvtColor(res_lab, cv2.COLOR_LAB2BGR)\n\n fp_mask = find_mask(subject, False)\n res = cv2.bitwise_and(res,res,mask = face_mask[:,:,0])\n res = np.where(face_mask==[0,0,0], subject, res)\n res = np.where(fp_mask==[255,255,255], subject, res)\n\n\n #apply lip makeup\n M, lip_map = lip.lip_makeup(subject, warped_target)\n res = np.where(lip_map==[255,255,255], M, res)\n\n # cv2.imshow('old', res)\n # cv2.waitKey(0)\n\n res = overlay(subject, res, face_mask[:,:,0])\n \n # cv2.imshow('res', res)\n # cv2.imwrite('res.jpg', res)\n # cv2.waitKey(0)\n return res\n\n\n# def crop_img(img):\n# w, h = img.shape[:2]\n# for i in range(0, h - 1)[::-1]:\n# if img[i][0][0] > 10:\n# img = img[0:i, :]\n# break\n# return img\n\n\ndef makeup_main(url_subject, url_target):\n subject = cv2.imread(url_subject, 1)\n target = cv2.imread(url_target, 1)\n subject = imutils.resize(subject, width=500)\n target = imutils.resize(target, width=500)\n sub, warped_tar = warp_target(subject, target)\n res = apply_makeup(sub, warped_tar)\n #res = crop_img(res)\n return res\n\n\n\n\n# url_sub = 'Original_Image/luudiepphi.jpg'\n# url_tag = 'Target_Image/target_2.jpg'\n# img_sub = cv2.imread(url_sub)\n# cv2.imshow('img_sub', img_sub)\n# img_tag = cv2.imread(url_tag)\n# cv2.imshow('img_tag', img_tag)\n# img = makeup_main(url_sub, url_tag)\n# img = crop_img(img)\n# cv2.imshow('img', img)\n# cv2.waitKey(0)","sub_path":"Source_code/makeup.py","file_name":"makeup.py","file_ext":"py","file_size_in_byte":14713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"573787523","text":"\n'''\nmodule : Google Calendar API Utilities\nprovides classes/functions helpful for managing our Google\ncalendars via their API\n'''\nfrom __future__ import print_function\nimport httplib2\nimport os\n\nfrom apiclient import discovery\nimport oauth2client\nfrom oauth2client import client\nfrom oauth2client import tools\n\nimport datetime\n\ntry:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/calendar-python-webapp.json\nSCOPES = 'https://www.googleapis.com/auth/calendar'\nCLIENT_SECRET_FILE = 'client_secret.json'\nAPPLICATION_NAME = 'COS 333 Assignment Calendars'\n\n'''\nfunction : get_credentials()\n-Gets valid user credentials from storage.\n-If nothing has been stored, or if the stored credentials are invalid,\nthe OAuth2 flow is completed to obtain the new credentials.\nReturns:\n Credentials, the obtained credential.\n'''\ndef get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'calendar-python-webapp.json')\n\n store = oauth2client.file.Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials\n\n'''\nfunction : new_calendar()\ncreates a new Google Calendar on the account associated with\nour credentials (should be assigncalscos333@gmail.com /p chrismoretti)\ninputs : \n title : title (typically a String like \"MAE 433\")\n descr : description (typically a String like \"Problem Set\n Calendar for MAE 433\")\noutputs :\n new_created_cal : a dictionary representation of the newly\n created calendar, or None if title already\n taken\n'''\ndef new_calendar(title, descr):\n #princeton_orange = \"#FF8F00\"\n new_created_cal = None\n if (get_calendar(title) == None):\n new_cal = {\n \"kind\": \"calendar#calendar\", # Type of the resource (\"calendar#calendar\").\n \"description\": descr, # Description of the calendar. Optional.\n \"summary\": title, # Title of the calendar.\n #\"etag\": \"A String\", # ETag of the resource.\n \"location\": \"Princeton, NJ, USA\", # Geographic location of the calendar as free-form text. Optional.\n \"timeZone\": \"America/New_York\", # The time zone of the calendar. (Formatted as an IANA Time Zone Database name, e.g. \"Europe/Zurich\".) Optional.\n #\"id\": \"A String\", # Identifier of the calendar. To retrieve IDs call the calendarList.list() method.\n }\n #Programtically create a new calendar using the insert()\n # from calendars() request\n #FORMAT MUST BE A DICT, NOT JSON, AND THEREFORE NO COMMENTS\n new_cal_req = service.calendars().insert(body=new_cal)\n new_created_cal = new_cal_req.execute()\n return new_created_cal\n\n'''\nfunction : get_calendar()\nretrieve an existing Google Calendar on the account associated with\nour credentials (should be assigncalscos333@gmail.com /p chrismoretti)\ninputs : \n title : title (typically a String like \"MAE 433\")\n \noutputs :\n cal : a dictionary representation of the located\n calendar, or None if no calendar with this title\n exists\n'''\ndef get_calendar(title):\n #HTTP request for a list of the user's calendars\n usr_cals_req = service.calendarList().list() \n #Execute the request, returns data in an object we call usr_cals\n usr_cals = usr_cals_req.execute()\n #Extract a particular calendar id by name\n calid = None\n calname = title\n for i in usr_cals['items']:\n if (i['summary'] == calname):\n calid = i['id']\n break\n\n #Use the extracted id to get the calender object via the get() request\n if (calid != None):\n cal_byid_req = service.calendarList().get(calendarId=calid)\n cal = cal_byid_req.execute()\n return cal\n else:\n return None\n\n'''\nfunction : add_event()\nadds an event with the specified information to a particular\ncalendar\ninputs:\n calname : name of calendar to add event to (string)\n title : title of event (string)\n location : location of event (string)\n descr : description of event (string)\n start : start time (formatted string)\n end : end time (formatted string)\noutputs:\n event : dictionary representation of the newly created\n event, or None if calendar does not exist \n'''\ndef add_event(calname,title,location, descr, start, end):\n event = None\n calendar = get_calendar(calname)\n if (calendar != None):\n new_event = {\n 'summary': title,\n 'location': location,\n 'description': descr,\n 'start': {\n 'dateTime': start,\n 'timeZone': 'America/New_York',\n },\n 'end': {\n 'dateTime': end,\n 'timeZone': 'America/New_York',\n },\n #'recurrence': [\n # 'RRULE:FREQ=DAILY;COUNT=2'\n #],\n #'attendees': [\n # {'email': 'lpage@example.com'},\n # {'email': 'sbrin@example.com'},\n #],\n 'reminders': {\n 'useDefault': False,\n 'overrides': [\n {'method': 'email', 'minutes': 24 * 60},\n {'method': 'popup', 'minutes': 10},\n ],\n },\n }\n add_event_req = service.events().insert(calendarId=calendar['id'], body=new_event)\n event = add_event_req.execute()\n return event\n\n'''\nfunction main()\ntester client that shows basic usage of the Google Calendar API.\nCreates a Google Calendar API service object and outputs a list of the next\n10 events on the user's calendar.\n'''\ndef main():\n #Creates a Google Calendar API service object from our\n #credentials\n credentials = get_credentials()\n http = credentials.authorize(httplib2.Http())\n service = discovery.build('calendar', 'v3', http=http)\n\n #MY CHANGES\n \n print (\"--------------------------------\")\n print (\"NAMES OF ALL THE USER'S CALENDARS\")\n print (\"--------------------------------\")\n #HTTP request for a list of the user's calendars\n usr_cals_req = service.calendarList().list()\n \n #Execute the request, returns data in an object we call usr_cals\n usr_cals = usr_cals_req.execute()\n \n #Iterate over the \"items\" field of usr_cals and print the \"summary\"\n #field of each item, which corresponds to printing the name of each\n #calendar\n for i in usr_cals['items']:\n print (i['summary'])\n \n print (\"--------------------------------\")\n print (\"FINDING/FETCHING A USER'S CALENDAR BY NAME/ID\")\n print (\"--------------------------------\")\n #Extract a particular calendar id by name\n calid = None\n calname = 'new calendar'\n for i in usr_cals['items']:\n if (i['summary'] == calname):\n calid = i['id']\n break\n\n #Use the extracted id to get the calender object via the get() request\n if (calid != None):\n cal_byid_req = service.calendarList().get(calendarId=calid)\n cal_byid = cal_byid_req.execute()\n print (\"Found \" + cal_byid['summary'] + \" by id.\")\n print (\"The time zone of \" + cal_byid['summary'] + \" is \" + cal_byid['timeZone'])\n else:\n print (\"Calendar with name : \" + calname + \" not found!\")\n\n \n #Programtically create a new calendar using the insert() from calendars() request\n print (\"--------------------------------\")\n print (\"GENERATING A NEW CALENDAR AND VERIFYING ITS NAME AND ID\")\n print (\"--------------------------------\")\n #princeton_orange = \"#FF8F00\"\n new_cal = {\n \"kind\": \"calendar#calendar\", # Type of the resource (\"calendar#calendar\").\n \"description\": \"This is a test of Programtically creating a new calendar\", # Description of the calendar. Optional.\n \"summary\": \"A new calendar\", # Title of the calendar.\n #\"etag\": \"A String\", # ETag of the resource.\n \"location\": \"Princeton, NJ, USA\", # Geographic location of the calendar as free-form text. Optional.\n \"timeZone\": \"America/New_York\", # The time zone of the calendar. (Formatted as an IANA Time Zone Database name, e.g. \"Europe/Zurich\".) Optional.\n #\"id\": \"A String\", # Identifier of the calendar. To retrieve IDs call the calendarList.list() method.\n }\n\n #FORMAT MUST BE A DICT, NOT JSON, AND THEREFORE NO COMMENTS\n new_cal_req = service.calendars().insert(body=new_cal)\n new_created_cal = new_cal_req.execute()\n \n print (\"Name of new calendar is \" + new_created_cal['summary'])\n print (\"calendarId of new calendar is \" + new_created_cal['id'])\n\n print (\"--------------------------------\")\n print (\"DELETING THE JUST CREATED CALENDAR AND VERIFYING THAT IT IS GONE\")\n print (\"--------------------------------\")\n \n del_cal_req = service.calendars().delete(calendarId=new_created_cal['id'])\n del_cal_req.execute()\n\n #HTTP request for a list of the user's calendars\n usr_cals_req = service.calendarList().list()\n \n #Execute the request, returns data in an object we call usr_cals\n usr_cals = usr_cals_req.execute() \n \n #Extract a particular calendar id by name\n calid = None\n calname = 'A new calendar'\n for i in usr_cals['items']:\n if (i['summary'] == calname):\n calid = i['id']\n break\n\n #Use the extracted id to get the calender object via the get() request\n if (calid != None):\n cal_byid_req = service.calendarList().get(calendarId=calid)\n cal_byid = cal_byid_req.execute()\n print (\"Found \" + cal_byid['summary'] + \" by id.\")\n print (\"The time zone of \" + cal_byid['summary'] + \" is \" + cal_byid['timeZone'])\n else:\n print (\"Calendar with name : \" + calname + \" not found!\")\n\n\n print (\"--------------------------------\")\n print (\"ADDING A NEW EVENT TO AN EXISTING CALENDAR\")\n print (\"--------------------------------\")\n\n new_event = {\n 'summary': 'COS 333 TEST EVENT',\n 'location': 'Princeton University, Princeton, NJ, 08544',\n 'description': 'Let\\'s not fail cos 333 lol',\n 'start': {\n 'dateTime': '2016-03-20T09:00:00-05:00',\n 'timeZone': 'America/New_York',\n },\n 'end': {\n 'dateTime': '2016-03-20T17:00:00-05:00',\n 'timeZone': 'America/New_York',\n },\n #'recurrence': [\n # 'RRULE:FREQ=DAILY;COUNT=2'\n #],\n #'attendees': [\n # {'email': 'lpage@example.com'},\n # {'email': 'sbrin@example.com'},\n #],\n 'reminders': {\n 'useDefault': False,\n 'overrides': [\n {'method': 'email', 'minutes': 24 * 60},\n {'method': 'email', 'minutes': 10},\n ],\n },\n }\n\n #Extract a particular calendar id by name\n calid = None\n calname = 'new calendar'\n for i in usr_cals['items']:\n if (i['summary'] == calname):\n calid = i['id']\n print (calid)\n print(i['accessRole'])\n break\n\n #Use the extracted id to get the calender object via the get() request\n if (calid != None):\n #Add new event request\n add_event_req = service.events().insert(calendarId=calid, body=new_event)\n add_event_req.execute()\n else:\n print (\"Calendar with name : \" + calname + \" not found!\")\n\n #MY CHANGES\n\n now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time\n print('Getting the upcoming 10 events')\n eventsResult = service.events().list(\n calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,\n orderBy='startTime').execute()\n events = eventsResult.get('items', [])\n\n if not events:\n print('No upcoming events found.')\n for event in events:\n start = event['start'].get('dateTime', event['start'].get('date'))\n print(start, event['summary'])\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"gcalutils.py","file_name":"gcalutils.py","file_ext":"py","file_size_in_byte":12678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"26911390","text":"import pytest\n\nfrom dcicutils.deployment_utils import CreateMappingOnDeployManager\nfrom snovault import COLLECTIONS, TYPES\nfrom snovault.elasticsearch.create_mapping import type_mapping\nfrom snovault.util import add_default_embeds\nfrom unittest.mock import patch, MagicMock\nfrom .datafixtures import ORDER\nfrom ..commands import create_mapping_on_deploy\nfrom ..commands.create_mapping_on_deploy import (\n ITEM_INDEX_ORDER,\n _run_create_mapping # noqa - yeah, it's internal but we want to test it\n)\n# TODO: We should not be importing *. Even stranger, PyCharm says we don't use anything from there. -kmp 14-Feb-2020\n# Experimentally commenting this out. -kmp 28-Jun-2020\n# from ..types.experiment import *\n\n\npytestmark = [pytest.mark.setone, pytest.mark.working]\n\n\n@pytest.mark.parametrize('item_type', ORDER)\ndef test_create_mapping(registry, item_type):\n \"\"\"\n This test does not actually use elasticsearch\n Only tests the mappings generated from schemas\n \"\"\"\n mapping = type_mapping(registry[TYPES], item_type)\n assert mapping\n type_info = registry[TYPES].by_item_type[item_type]\n schema = type_info.schema\n embeds = add_default_embeds(item_type, registry[TYPES], type_info.embedded_list, schema)\n # assert that all embeds exist in mapping for the given type\n for embed in embeds:\n mapping_pointer = mapping\n split_embed = embed.split('.')\n for idx, split_ in enumerate(split_embed):\n # see if this is last level of embedding- may be a field or object\n if idx == len(split_embed) - 1:\n if 'properties' in mapping_pointer and split_ in mapping_pointer['properties']:\n final_mapping = mapping_pointer['properties']\n else:\n final_mapping = mapping_pointer\n if split_ != '*':\n assert split_ in final_mapping\n else:\n assert 'properties' in final_mapping or final_mapping.get('type') == 'object'\n else:\n assert split_ in mapping_pointer['properties']\n mapping_pointer = mapping_pointer['properties'][split_]\n\n\ndef test_create_mapping_item_order(registry):\n # make sure every item type name is represented in the item ordering\n for i_type in registry[COLLECTIONS].by_item_type:\n # ignore \"testing\" types\n if i_type.startswith('testing_'):\n continue\n assert registry[COLLECTIONS][i_type].type_info.name in ITEM_INDEX_ORDER\n\n\nclass MockedCommandArgs:\n\n def __init__(self, wipe_es=None, skip=None, strict=None, clear_queue=None):\n self.wipe_es = wipe_es\n self.skip = skip\n self.strict = strict\n self.clear_queue = clear_queue\n\n\nclass MockedLog:\n\n def __init__(self):\n self.log = []\n\n def info(self, msg):\n self.log.append(('info', msg))\n\n def error(self, msg):\n self.log.append(('error', msg))\n\n\n# These next are more extensively tested in dcicutils.\n# This is just plausibility checking that we've received things OK.\n\n@patch('dcicutils.deployment_utils.compute_ff_prd_env', MagicMock(return_value='fourfront-green'))\n@patch('encoded.commands.create_mapping_on_deploy.get_my_env', MagicMock(return_value='fourfront-blue'))\ndef test_get_deployment_config_staging():\n \"\"\" Tests get_deployment_config in the new staging case \"\"\"\n my_env = create_mapping_on_deploy.get_my_env('ignored-for-mock')\n assert my_env == 'fourfront-blue'\n cfg = CreateMappingOnDeployManager.get_deploy_config(env=my_env, args=MockedCommandArgs(), log=MockedLog())\n assert cfg['ENV_NAME'] == my_env # sanity\n assert cfg['SKIP'] is False\n assert cfg['WIPE_ES'] is True\n assert cfg['STRICT'] is True\n\n\n@patch('dcicutils.deployment_utils.compute_ff_prd_env', MagicMock(return_value='fourfront-green'))\n@patch('encoded.commands.create_mapping_on_deploy.get_my_env', MagicMock(return_value='fourfront-green'))\ndef test_get_deployment_config_prod():\n \"\"\" Tests get_deployment_config in the new production case \"\"\"\n my_env = create_mapping_on_deploy.get_my_env('ignored-for-mock')\n assert my_env == 'fourfront-green'\n with pytest.raises(RuntimeError):\n CreateMappingOnDeployManager.get_deploy_config(env=my_env, args=MockedCommandArgs(), log=MockedLog())\n\n\n@patch('dcicutils.deployment_utils.compute_ff_prd_env', MagicMock(return_value='fourfront-green'))\n@patch('encoded.commands.create_mapping_on_deploy.get_my_env', MagicMock(return_value='fourfront-hotseat'))\ndef test_get_deployment_config_hotseat():\n \"\"\" Tests get_deployment_config in the hotseat case with a new-style ecosystem. \"\"\"\n my_env = create_mapping_on_deploy.get_my_env('ignored-for-mock')\n assert my_env == 'fourfront-hotseat'\n cfg = CreateMappingOnDeployManager.get_deploy_config(env=my_env, args=MockedCommandArgs(), log=MockedLog())\n assert cfg['ENV_NAME'] == my_env # sanity\n assert cfg['SKIP'] is True # The other values (WIPE_ES and STRICT) don't matter if this is set.\n\n@patch('dcicutils.deployment_utils.compute_ff_prd_env', MagicMock(return_value='fourfront-green'))\n@patch('encoded.commands.create_mapping_on_deploy.get_my_env', MagicMock(return_value='fourfront-mastertest'))\ndef test_get_deployment_config_mastertest():\n \"\"\" Tests get_deployment_config in the hotseat case with a new-style ecosystem. \"\"\"\n my_env = create_mapping_on_deploy.get_my_env('ignored-for-mock')\n assert my_env == 'fourfront-mastertest'\n cfg = CreateMappingOnDeployManager.get_deploy_config(env=my_env, args=MockedCommandArgs(), log=MockedLog())\n assert cfg['ENV_NAME'] == my_env # sanity\n assert cfg['SKIP'] is False\n assert cfg['WIPE_ES'] is True\n assert cfg['STRICT'] is False\n\n\nclass Simulation:\n\n def __init__(self, mocked_app, expect_check_first=False, expect_purge_queue=False, expect_strict=False):\n self.run_has_been_called = False\n self.mocked_app = mocked_app\n self.expect_check_first = expect_check_first\n self.expect_purge_queue = expect_purge_queue\n self.expect_strict = expect_strict\n\n def __str__(self):\n return (\"<{cls} run {called} expecting cf={cf} pq={pq} es={es} {id}>\"\n .format(cls=self.__class__.__name__, called=\"CALLED\" if self.run_has_been_called else \"UNCALLED\",\n cf=self.expect_check_first, pq=self.expect_purge_queue, es=self.expect_strict, id=id(self)))\n\n def __repr__(self):\n return self.__str__()\n\n def mocked_run_create_mapping(self, app, check_first=False, strict=False, purge_queue=False, item_order=None,\n **kwargs):\n self.run_has_been_called = True\n assert kwargs == {}, \"mocked_run_create_mapping needs adjusting. It doesn't expect these keywords: %s\" % kwargs\n assert app == self.mocked_app, \"Mocked app was not as expected: %s\" % app\n # check_first is (not WIPE_ES)\n assert check_first is self.expect_check_first, \"check_first is not False: %s\" % check_first\n # purge_queue is whether --clear-queue was in command args\n assert bool(purge_queue) is self.expect_purge_queue, (\n \"bool(purge_queue) is not False. purge_queue=%s\" % purge_queue)\n # This should be a constant for our purposes\n assert item_order == ITEM_INDEX_ORDER, \"item_order was not as expected: %s\" % item_order\n # strict is the STRICT argument\n assert strict is self.expect_strict, \"strict is not False: %s\" % strict\n\n\n@patch('encoded.commands.create_mapping_on_deploy.log', MockedLog())\n@patch('dcicutils.deployment_utils.compute_ff_prd_env', MagicMock(return_value='fourfront-green'))\n@patch('encoded.commands.create_mapping_on_deploy.get_my_env', MagicMock(return_value='fourfront-green'))\n@patch('encoded.commands.create_mapping_on_deploy.run_create_mapping')\ndef test_run_create_mapping_production(mock_run_create_mapping, app):\n\n simulation = Simulation(mocked_app=app) # Expectations don't matter because we're not expecting to get called.\n mocked_log = create_mapping_on_deploy.log\n try:\n mock_run_create_mapping.side_effect = simulation.mocked_run_create_mapping\n _run_create_mapping(app, MockedCommandArgs())\n except SystemExit as e:\n print(e)\n assert e.code == 1\n assert simulation.run_has_been_called is False\n assert mocked_log.log == [\n ('info', 'Environment fourfront-green is currently the production environment.'\n ' Something is definitely wrong. We never deploy there, we always CNAME swap.'\n ' This deploy cannot proceed. DeploymentFailure will be raised.'),\n ('error', 'Exception encountered while gathering deployment information or running create_mapping'),\n ('error', 'DeploymentFailure: Tried to run create_mapping_on_deploy on production.'),\n ]\n\n\n@patch('encoded.commands.create_mapping_on_deploy.log', MockedLog())\n@patch('dcicutils.deployment_utils.compute_ff_prd_env', MagicMock(return_value='fourfront-green'))\n@patch('encoded.commands.create_mapping_on_deploy.get_my_env', MagicMock(return_value='fourfront-blue'))\n@patch('encoded.commands.create_mapping_on_deploy.run_create_mapping')\ndef test_run_create_mapping_staging(mock_run_create_mapping, app):\n\n simulation = Simulation(mocked_app=app, expect_check_first=False, expect_purge_queue=False, expect_strict=True)\n mocked_log = create_mapping_on_deploy.log\n exit_condition = None\n try:\n mock_run_create_mapping.side_effect = simulation.mocked_run_create_mapping\n _run_create_mapping(app, MockedCommandArgs())\n except SystemExit as e:\n exit_condition = e\n print(exit_condition)\n except Exception as e:\n print(\"log =\", mocked_log.log)\n raise AssertionError(\"Unexpected error exit (%s): %s\" % (e.__class__.__name__, e))\n assert simulation.run_has_been_called is True\n assert mocked_log.log == [\n ('info', 'Environment fourfront-blue is currently the staging environment. Processing mode: STRICT,WIPE_ES'),\n ('info', 'Calling run_create_mapping for env fourfront-blue.')\n ]\n assert exit_condition, \"Unexpected non-error exit.\"\n assert exit_condition.code == 0\n\n\n@patch('encoded.commands.create_mapping_on_deploy.log', MockedLog())\n@patch('dcicutils.deployment_utils.compute_ff_prd_env', MagicMock(return_value='fourfront-green'))\n@patch('encoded.commands.create_mapping_on_deploy.get_my_env', MagicMock(return_value='fourfront-hotseat'))\n@patch('encoded.commands.create_mapping_on_deploy.run_create_mapping')\ndef test_run_create_mapping_hotseat(mock_run_create_mapping, app):\n\n simulation = Simulation(mocked_app=app) # Expectations don't matter because we're not expecting to get called.\n mocked_log = create_mapping_on_deploy.log\n try:\n mock_run_create_mapping.side_effect = simulation.mocked_run_create_mapping\n _run_create_mapping(app, MockedCommandArgs())\n except SystemExit as e:\n print(e)\n assert e.code == 0\n assert simulation.run_has_been_called is False\n assert mocked_log.log == [\n ('info', 'Environment fourfront-hotseat is a hotseat test environment. Processing mode: SKIP'),\n ('info', 'NOT calling run_create_mapping for env fourfront-hotseat.')\n ]\n\n\n@patch('encoded.commands.create_mapping_on_deploy.log', MockedLog())\n@patch('dcicutils.deployment_utils.compute_ff_prd_env', MagicMock(return_value='fourfront-green'))\n@patch('encoded.commands.create_mapping_on_deploy.get_my_env', MagicMock(return_value='fourfront-mastertest'))\n@patch('encoded.commands.create_mapping_on_deploy.run_create_mapping')\ndef test_run_create_mapping_mastertest(mock_run_create_mapping, app):\n\n simulation = Simulation(mocked_app=app, expect_check_first=False, expect_purge_queue=False, expect_strict=False)\n mocked_log = create_mapping_on_deploy.log\n try:\n mock_run_create_mapping.side_effect = simulation.mocked_run_create_mapping\n _run_create_mapping(app, MockedCommandArgs())\n except SystemExit as e:\n print(e)\n assert e.code == 0\n assert simulation.run_has_been_called is True\n assert mocked_log.log == [\n ('info', 'Environment fourfront-mastertest is a non-hotseat test environment. Processing mode: WIPE_ES'),\n ('info', 'Calling run_create_mapping for env fourfront-mastertest.')\n ]\n\n\n@patch('encoded.commands.create_mapping_on_deploy.log', MockedLog())\n@patch('dcicutils.deployment_utils.compute_ff_prd_env', MagicMock(return_value='fourfront-green'))\n@patch('encoded.commands.create_mapping_on_deploy.get_my_env', MagicMock(return_value='fourfront-mastertest'))\n@patch('encoded.commands.create_mapping_on_deploy.run_create_mapping')\ndef test_run_create_mapping_mastertest_with_clear_queue(mock_run_create_mapping, app):\n\n simulation = Simulation(mocked_app=app, expect_check_first=False, expect_purge_queue=True, expect_strict=False)\n mocked_log = create_mapping_on_deploy.log\n try:\n mock_run_create_mapping.side_effect = simulation.mocked_run_create_mapping\n _run_create_mapping(app, MockedCommandArgs(clear_queue=True))\n except SystemExit as e:\n print(e)\n assert e.code == 0\n assert simulation.run_has_been_called is True\n assert mocked_log.log == [\n ('info', 'Environment fourfront-mastertest is a non-hotseat test environment. Processing mode: WIPE_ES'),\n ('info', 'Calling run_create_mapping for env fourfront-mastertest.')\n ]\n","sub_path":"src/encoded/tests/test_create_mapping.py","file_name":"test_create_mapping.py","file_ext":"py","file_size_in_byte":13483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"116354888","text":"import torch\nfrom cogdl.tasks import build_task\nfrom cogdl.utils import build_args_from_dict\n\n\ndef get_default_args():\n cuda_available = torch.cuda.is_available()\n default_dict = {\n \"device_id\": [0],\n \"num_clusters\": 7,\n \"cluster_method\": \"kmeans\",\n \"hidden_size\": 16,\n \"model_type\": \"emb\",\n \"momentum\": 0,\n 'enhance': None,\n \"cpu\": not cuda_available,\n }\n return build_args_from_dict(default_dict)\n\ndef test_prone_cora():\n args = get_default_args()\n args.task = \"attributed_graph_clustering\"\n args.dataset = \"cora\"\n args.model = \"prone\"\n args.step = 5\n args.theta = 0.5\n args.mu = 0.2\n task = build_task(args)\n ret = task.train()\n assert 0 <= ret[\"Accuracy\"] <= 1\n\n\nif __name__ == \"__main__\":\n test_prone_cora()\n","sub_path":"tests/tasks/test_attributed_graph_clustering.py","file_name":"test_attributed_graph_clustering.py","file_ext":"py","file_size_in_byte":814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"481117937","text":"import torch.optim as optim\nfrom torch.optim import lr_scheduler\nimport torch.nn as nn\nimport torch\nimport os\nimport numpy\nimport cv2\nimport random\nfrom MobileNetV2_depthwise import MobileNet2_7B48\nfrom torch.nn.functional import softmax\nfrom torchvision.transforms import ToTensor\nimport pickle as pkl\n\n\ndef evaluate(model_weight_name, model, inputs):\n if torch.cuda.is_available():\n inputs = inputs.cuda()\n print(inputs)\n model = model.cuda()\n labels = torch.from_numpy(numpy.array([1])).cuda()\n\n criterion = nn.CrossEntropyLoss()\n\n if os.path.exists(model_weight_name):\n print(f\"The best model {model_weight_name} has been loaded\")\n model.load_state_dict(torch.load(model_weight_name))\n\n model.eval()\n\n with torch.no_grad():\n outputs = model(inputs)\n _, preds = torch.max(outputs, 1)\n print(_)\n print(preds)\n loss = criterion(outputs, labels)\n print(loss)\n outputs = softmax(outputs, dim=1)\n print(outputs)\n outputs = outputs.squeeze(0)\n outputs = outputs.cpu().numpy()\n print(outputs)\n\n print(f'outputs: interest {outputs[0]}, not interested {outputs[1]}')\n return outputs\n\n\ndef transform(file):\n img = cv2.imread(file, 0)\n img = cv2.resize(img, (48, 48))\n input_img = ToTensor()(img)\n input_img = input_img.unsqueeze(0)\n return input_img\n\n\ndef show_results(file, detection):\n img = cv2.imread(file)\n\n a = round(detection[0], ndigits=2)\n b = round(detection[1], ndigits=2)\n label1 = f' happiness:{a:.2}'\n label2 = f'unhappiness:{b:.2}'\n\n colors = pkl.load(open(\"pallete\", \"rb\"))\n color = (255, 255, 255)\n color1 = (0, 0, 0)\n print(color)\n t_size = cv2.getTextSize(label1, cv2.FONT_HERSHEY_PLAIN, 1, 1)[0]\n c1 = (10, 10)\n c2 = (6, 26)\n # c3 = (158, 38)\n # cv2.rectangle(qimg, c1, c3, color1, 2)\n cv2.putText(img, label1, (c1[0], c1[1] + t_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 1, [225, 255, 255], 1)\n cv2.putText(img, label2, (c2[0], c2[1] + t_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 1, [225, 255, 255], 1)\n cv2.namedWindow(\"Image\")\n cv2.imshow(\"Image\", img)\n key = cv2.waitKey(0)\n if key & 0xFF == ord('q'):\n pass\n\n\nif __name__ == \"__main__\":\n # batch picture detect\n model_ft = MobileNet2_7B48(2)\n model_weight_name_ft = 'mobilenet_v2_2C_7B_F960_adam_89%_2019_09_26_12_09_41'\n for i in range(7):\n img_name = f'{i}.jpeg'\n print(img_name)\n # img_name = '0_2.jpg'\n img = transform(img_name)\n outputs = evaluate(model_weight_name_ft, model_ft, img)\n show_results(img_name, outputs)\n\n # single picture detect\n # img_name = '0_10.jpeg'\n # img_name = '0_2.jpg'\n # img = transform(img_name)\n # outputs = evaluate(model_weight_name_ft, model_ft, img)\n # show_results(img_name, outputs)\n","sub_path":"Git/MobileNet_Evaluate.py","file_name":"MobileNet_Evaluate.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"216213940","text":"__author__ = 'janak'\n\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic import CreateView\nfrom utils.template_mapping import *\nfrom companies.models import ClientCompany\nfrom companies.forms import ClientCompanyForm\nfrom loginmgmt.user_helper import UserHelperMixin\nfrom utils.state_helper import StateHelperMixin\nfrom utils.ajax_check_helper import AjaxCheckerMixin\nfrom django.views.generic.edit import ModelFormMixin\nfrom search.solr_handler import *\nfrom utils.log_helper import init_logger\n\nlogger = init_logger(__name__)\n\n\n# Add a new company\nclass AddCompany(CreateView, StateHelperMixin, UserHelperMixin, AjaxCheckerMixin):\n model = ClientCompany\n template_name = template_names_dict['addcompany']\n form_class = ClientCompanyForm\n fields = ['company_name', 'address1', 'address2', 'city', 'state', 'country']\n object = None\n # success_url = reverse_lazy('companies:companydetail')\n\n def get_success_url(self):\n return reverse('companies:companydetails', args=(self.object.id,))\n\n def post(self, request, *args, **kwargs):\n try:\n #Explicitly setting the request.post to be mutable so that we can add additional values to it.\n #once done, reset the mutable property. dont need to do this if a form is a multi-part form.\n mutable = request.POST._mutable\n request.POST._mutable = True\n #Set added by updated by user on form post data\n self.set_added_by_update_by_users_on_view(request, GlobalConstants.ADD_ACTION)\n #Check if state is received, or manual state name is received and then set the other\n self.set_state_name_or_state_field(request)\n request.POST._mutable = mutable\n\n companyform = ClientCompanyForm(request.POST)\n\n if companyform.is_valid():\n return self.form_valid(companyform)\n else:\n logger.error(\"Unable to add Company. Error caused.\")\n return self.form_invalid(companyform)\n\n except Exception as e:\n logger.error(\"Exception while adding Company\" + str(e))\n\n def form_valid(self, form):\n try:\n self.object = form.save()\n solr_obj = SolrHandler()\n solr_obj.add_company(self.object)\n return super(ModelFormMixin, self).form_valid(form)\n except Exception as e:\n logger.error(\"Exception while Adding Company in SOLR: \" + str(e))\n return super(ModelFormMixin, self).form_valid(form)\n\n def get_context_data(self, **kwargs):\n context = super(AddCompany, self).get_context_data(**kwargs)\n context['form_action'] = GlobalConstants.ADD_ACTION\n return context\n\n def get(self, request, *args, **kwagrs):\n try:\n form_class = self.get_form_class()\n form = self.get_form(form_class)\n context = self.get_context_data(form=form)\n self.check_if_ajax_page(request, context)\n return self.render_to_response(context)\n except Exception as e:\n logger.error(\"Exception while Get Add Company: \" + str(e))\n","sub_path":"companies/views/addcompany.py","file_name":"addcompany.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"340918979","text":"import numpy as np\nimport os\nfrom glob import glob\nimport scipy.io as sio\nfrom skimage.io import imread, imsave\nfrom skimage.transform import rescale, resize\nfrom time import time\nimport argparse\nimport ast\nimport matplotlib.pyplot as plt\nimport argparse\n\nfrom api import PRN\nfrom utils.render import render_texture\nimport cv2\n\n\ndef texture_editing(prn, args):\n # read image\n print(args.output_path)\n image = imread(args.image_path)\n [h, w, _] = image.shape\n\n #-- 1. 3d reconstruction -> get texture. \n pos = prn.process(image) \n vertices = prn.get_vertices(pos)\n image = image/255.\n texture = cv2.remap(image, pos[:,:,:2].astype(np.float32), None, interpolation=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT,borderValue=(0))\n cv2.imwrite(\"Texture.png\", (texture*255).astype(int))\n \n\n\n\n #-- 2. Texture Editing\n Mode = args.mode\n # change part of texture(for data augumentation/selfie editing. Here modify eyes for example)\n if Mode == 0: \n # load eye mask\n uv_face_eye = imread('Data/uv-data/uv_face_eyes.png', as_grey=True)/255. \n uv_face = imread('Data/uv-data/uv_face.png', as_grey=True)/255.\n eye_mask = (abs(uv_face_eye - uv_face) > 0).astype(np.float32)\n\n # texture from another image or a processed texture\n ref_image = imread(args.ref_path)\n ref_pos = prn.process(ref_image)\n ref_image = ref_image/255.\n ref_texture = cv2.remap(ref_image, ref_pos[:,:,:2].astype(np.float32), None, interpolation=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT,borderValue=(0))\n\n # modify texture\n new_texture = texture*(1 - eye_mask[:,:,np.newaxis]) + ref_texture*eye_mask[:,:,np.newaxis]\n \n # change whole face(face swap)\n elif Mode == 1: \n # texture from another image or a processed texture\n ref_image = imread(args.ref_path)\n ref_pos = prn.process(ref_image)\n ref_image = ref_image/255.\n ref_texture = cv2.remap(ref_image, ref_pos[:,:,:2].astype(np.float32), None, interpolation=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT,borderValue=(0))\n ref_vertices = prn.get_vertices(ref_pos)\n new_texture = ref_texture#(texture + ref_texture)/2.\n\n else:\n print('Wrong Mode! Mode should be 0 or 1.')\n exit()\n\n\n #-- 3. remap to input image.(render)\n vis_colors = np.ones((vertices.shape[0], 1))\n face_mask = render_texture(vertices.T, vis_colors.T, prn.triangles.T, h, w, c = 1)\n face_mask = np.squeeze(face_mask > 0).astype(np.float32)\n \n new_colors = prn.get_colors_from_texture(new_texture)\n new_image = render_texture(vertices.T, new_colors.T, prn.triangles.T, h, w, c = 3)\n new_image = image*(1 - face_mask[:,:,np.newaxis]) + new_image*face_mask[:,:,np.newaxis]\n\n # Possion Editing for blending image\n vis_ind = np.argwhere(face_mask>0)\n vis_min = np.min(vis_ind, 0)\n vis_max = np.max(vis_ind, 0)\n center = (int((vis_min[1] + vis_max[1])/2+0.5), int((vis_min[0] + vis_max[0])/2+0.5))\n output = cv2.seamlessClone((new_image*255).astype(np.uint8), (image*255).astype(np.uint8), (face_mask*255).astype(np.uint8), center, cv2.NORMAL_CLONE)\n \n # save output\n imsave(args.output_path, output) \n print('Done.')\n\n\n\ndef write_video_to_files():\n obama_syn = cv2.VideoCapture(\"/home/vuthede/AI/first-order-model/result2.mp4\")\n obama_fullhd = cv2.VideoCapture(\"/home/vuthede/AI/first-order-model/obama_fullhd.mp4\")\n x1 = 685\n y1 = 85\n x2 = 1250\n y2 = 650\n\n i = 0\n while True:\n i+=1\n for j in range(3):\n ret, img_obama_syn = obama_syn.read()\n ret1, img_obamahd = obama_fullhd.read()\n\n if not ret or not ret1:\n print(f\"Break at frame {i}\")\n break\n \n obama_crop = img_obamahd[y1:y2, x1:x2]\n img_obama_syn = cv2.resize(img_obama_syn, (x2-x1, y2-y1))\n\n\n cv2.imwrite(f\"/home/vuthede/Desktop/3D/input/{i}.png\", obama_crop)\n cv2.imwrite(f\"/home/vuthede/Desktop/3D/ref/{i}.png\", img_obama_syn)\n\ndef merge_frames():\n syn_dir = \"/home/vuthede/Desktop/3D/input/\"\n full_hd_dir = \"/home/vuthede/Desktop/3D/ref/\"\n warping_dir = \"/home/vuthede/Desktop/3D/output_swap/\"\n out = cv2.VideoWriter('/home/vuthede/Desktop/3D/out.mp4',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (565*3, 565))\n for i in range(1,150):\n im1 = cv2.imread(syn_dir+f\"{i}.png\")\n im2 = cv2.imread(full_hd_dir+f\"{i}.png\")\n im3 = cv2.imread(warping_dir+f\"{i}.png\")\n\n concat = np.hstack([im1, im2, im3])\n out.write(concat)\n\n print(concat.shape)\n cv2.imshow(\"Concat\", concat)\n k = cv2.waitKey(0)\n\n if k ==27:\n break\n\n out.release()\n \n\n\n\n\n\nif __name__ == '__main__':\n from tqdm import tqdm\n parser = argparse.ArgumentParser(description='Texture Editing by PRN')\n\n parser.add_argument('-i', '--image_path', default='TestImages/AFLW2000/image00081.jpg', type=str,\n help='path to input image')\n parser.add_argument('-r', '--ref_path', default='TestImages/trump.jpg', type=str, \n help='path to reference image(texture ref)')\n parser.add_argument('-o', '--output_path', default='TestImages/output.jpg', type=str, \n help='path to save output')\n parser.add_argument('--mode', default=1, type=int, \n help='ways to edit texture. 0 for modifying parts, 1 for changing whole')\n parser.add_argument('--gpu', default='0', type=str, \n help='set gpu id, -1 for CPU')\n\n # ---- init PRN\n os.environ['CUDA_VISIBLE_DEVICES'] = parser.parse_args().gpu # GPU number, -1 for CPU\n prn = PRN(is_dlib = True) \n\n args = parser.parse_args()\n texture_editing(prn,args)\n\n #write_video_to_files()\n # for i in tqdm(range(1, 150)): \n # args.image_path = f\"/home/vuthede/Desktop/3D/input/{i}.png\"\n # args.ref_path = f\"/home/vuthede/Desktop/3D/ref/{i}.png\"\n # args.output_path = f\"/home/vuthede/Desktop/3D/output_swap/{i}.png\"\n # texture_editing(prn,args)\n\n # print(f\"Finish warping {i}-th frame\")\n\n # merge_frames()","sub_path":"demo_texture.py","file_name":"demo_texture.py","file_ext":"py","file_size_in_byte":6186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"458687990","text":"# Takes a {@link Polygon|polygon} and returns {@link Point|points} at all self-intersections.\n#\n# @name kinks\n# @param {Feature|Polygon} polygon input polygon\n# @returns {FeatureCollection} self-intersections\n# @example\n# var poly = {\n# \"type\": \"Feature\",\n# \"properties\": {},\n# \"geometry\": {\n# \"type\": \"Polygon\",\n# \"coordinates\": [[\n# [-12.034835, 8.901183],\n# [-12.060413, 8.899826],\n# [-12.03638, 8.873199],\n# [-12.059383, 8.871418],\n# [-12.034835, 8.901183]\n# ]]\n# }\n# };\n#\n# var kinks = turf.kinks(poly);\n#\n# var resultFeatures = kinks.intersections.features.concat(poly);\n# var result = {\n# \"type\": \"FeatureCollection\",\n# \"features\": resultFeatures\n# };\n#\n# //=result\n\nfrom geojson import Point, FeatureCollection\n\ndef kinks(poly_in):\n results = FeatureCollection([])\n if poly_in[\"type\"] == 'Feature':\n poly = poly_in[\"geometry\"]\n else:\n poly = poly_in\n\n for ring1 in poly[\"coordinates\"]:\n for ring2 in poly[\"coordinates\"]:\n for i in range(len(ring1) - 1):\n for k in range(len(ring2) - 1):\n # don't check adjacent sides of a given ring,\n # since of course they intersect in a vertex.\n if ring1 == ring2 and \\\n (abs(i - k) == 1 or abs(i - k) == len(ring1) - 2):\n continue\n\n intersection = line_intersects(\n ring1[i][0], ring1[i][1],\n ring1[i + 1][0], ring1[i + 1][1],\n ring2[k][0], ring2[k][1], ring2[k + 1][0],\n ring2[k + 1][1])\n if intersection:\n results[\"features\"].append(Point((intersection[0],\n intersection[1])))\n return results\n\n\n# modified from http://jsfiddle.net/justin_c_rounds/Gd2S2/light/\ndef line_intersects(line1_start_x, line1_start_y, line1_end_x, line1_end_y,\n line2_start_x, line2_start_y, line2_end_x, line2_end_y):\n # if the lines intersect, the result contains the x and y\n # of the intersection (treating the lines as infinite) and booleans for\n # whether line segment 1 or line segment 2 contain the point\n result = {\"x\": None, \"y\": None, \"onLine1\": False, \"onLine2\": False}\n denominator = ((line2_end_y - line2_start_y) *\n (line1_end_x - line1_start_x)) - \\\n ((line2_end_x - line2_start_x) *\n (line1_end_y - line1_start_y))\n if denominator == 0:\n if result[\"x\"] is not None and result[\"y\"] is not None:\n return result\n else:\n return False\n a = line1_start_y - line2_start_y\n b = line1_start_x - line2_start_x\n numerator1 = ((line2_end_x - line2_start_x) * a) -\\\n ((line2_end_y - line2_start_y) * b)\n numerator2 = ((line1_end_x - line1_start_x) * a) -\\\n ((line1_end_y - line1_start_y) * b)\n a = numerator1 / denominator\n b = numerator2 / denominator\n\n # if we cast these lines infinitely in both directions,\n # they intersect here:\n result[\"x\"] = line1_start_x + (a * (line1_end_x - line1_start_x))\n result[\"y\"] = line1_start_y + (a * (line1_end_y - line1_start_y))\n\n # if line1 is a segment and line2 is infinite, they intersect if:\n if 0 <= a <= 1:\n result[\"onLine1\"] = True\n # if line2 is a segment and line1 is infinite, they intersect if:\n if 0 <= b <= 1:\n result[\"onLine2\"] = True\n # if line1 and line2 are segments, they intersect if\n # both of the above are true\n if result[\"onLine1\"] and result[\"onLine2\"]:\n return [result[\"x\"], result[\"y\"]]\n else:\n return False\n","sub_path":"packages/turf_kinks/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"173014939","text":"import re\n\nimport requests # 导入requests包\nfrom bs4 import BeautifulSoup\nurl = 'http://www.cntour.cn/'\nstrhtml = requests.get(url)\n# soup = BeautifulSoup(strhtml.text, 'lxml')\nsoup = BeautifulSoup(strhtml.text, 'html5lib')\ndata = soup.select('#main>div>div.mtop.firstMod.clearfix>div.centerBox>ul.newsList>li>a')\n# print(strhtml.text)\nprint(data)\n\nheaders = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\n 'Accept-Encoding':'gzip, deflate',\n 'Accept-Language':'zh-Hans-CN, zh-Hans; q=0.5',\n 'Connection':'Keep-Alive',\n 'Host':'wap.gamersky.com',\n 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36'}\nurl = 'https://wap.gamersky.com/news/'\nstrhtml = requests.get(url,headers=headers)\nprint(strhtml.encoding)\nprint(strhtml.headers)\n# print(strhtml.text)\nprint(requests.utils.get_encodings_from_content(strhtml.text))\nstrhtml.encoding = \"utf-8\"\nsoup = BeautifulSoup(strhtml.text, 'html5lib')\ndata=soup.select('li>h5')\nprint(data)\nfor i in data:\n # print(str(type(i))+' '+str(i))\n group = re.search('(?<=/span>).*(?=)',str(i))\n group.group(0)\n print(group.group(0))","sub_path":"otherlib/crawer/beautifulSoupTest.py","file_name":"beautifulSoupTest.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"385206048","text":"#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU Lesser General Public License (as\n# published by the Free Software Foundation) version 2.1, February 1999.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the IMPLIED WARRANTY OF\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the terms and\n# conditions of the GNU Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this program; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n##############################################################################\nfrom spack import *\nimport os\n\n\nclass Reportinglib(Package):\n\n \"\"\"Soma and full compartment report library developed at BBP\"\"\"\n\n homepage = \"https://bbpcode.epfl.ch/code/a/sim/reportinglib/bbp\"\n url = \"ssh://bbpcode.epfl.ch/sim/reportinglib/bbp\"\n\n version('develop', git=url, preferred=True)\n\n # temporary version for branch being tested for INCITE\n version('gather', git=url, branch='sandbox/king/gatherMappingREP-31')\n\n variant('profile', default=False, description=\"Enable profiling using Tau\")\n variant('static', default=False, description=\"Build static library\")\n variant('debug', default=False, description=\"Build debug version\")\n\n depends_on('cmake@2.8.12:', type='build')\n depends_on('mpi')\n depends_on('tau', when='+profile')\n\n def profiling_wrapper_on(self):\n if self.spec.satisfies('+profile'):\n os.environ[\"USE_PROFILER_WRAPPER\"] = \"1\"\n\n def profiling_wrapper_off(self):\n if self.spec.satisfies('+profile'):\n del os.environ[\"USE_PROFILER_WRAPPER\"]\n\n def install(self, spec, prefix):\n\n build_dir = \"spack-build-%s\" % spec.version\n\n with working_dir(build_dir, create=True):\n\n options = ['-DCMAKE_INSTALL_PREFIX:PATH=%s' % prefix]\n\n c_compiler = spec['mpi'].mpicc\n cxx_compiler = spec['mpi'].mpicxx\n\n if spec.satisfies('+profile'):\n c_compiler = 'tau_cc'\n cxx_compiler = 'tau_cxx'\n # on darwin, boost is not always linked from gcc\n options.extend(['-DUNIT_TESTS=OFF'])\n\n # while building with tau, coreneuron needed static version\n if spec.satisfies('+static'):\n options.extend(['-DCOMPILE_LIBRARY_TYPE=STATIC'])\n\n # build debug version\n if spec.satisfies('+debug'):\n options.extend(['-DCMAKE_BUILD_TYPE=Debug'])\n\n # especially for bg-q where we don't use cmake to find mpi libs\n options.extend(['-DCMAKE_C_COMPILER=%s' % c_compiler,\n '-DCMAKE_CXX_COMPILER=%s' % cxx_compiler])\n\n cmake('..', *options)\n self.profiling_wrapper_on()\n make()\n make('install')\n self.profiling_wrapper_off()\n","sub_path":"packages/reportinglib/package.py","file_name":"package.py","file_ext":"py","file_size_in_byte":3063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"97179515","text":"import os\nimport json\n\n# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nDEBUG = False\n\n# Application definition\n\nINSTALLED_APPS = [\n 'trading.apps.TradingConfig',\n 'user_accounts.apps.UserAccountsConfig',\n 'web',\n 'organisations',\n 'tse',\n 'ssot',\n 'wot',\n 'partners',\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.sites',\n 'storages',\n 'raven.contrib.django.raven_compat',\n 'kyc.apps.KycConfig',\n 'graphene_django',\n 'se.apps.SmartEquityConfig',\n 'eventlog',\n]\nSITE_ID = 1\n\n\nGRAPHENE = {\n 'SCHEMA': 'web.schema.schema' # Where your Graphene schema lives\n}\n\nMIDDLEWARE = [\n 'django.middleware.security.SecurityMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'user_accounts.middlewares.Auth0Middleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'web.urls'\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [],\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 = 'web.wsgi.application'\n\n\n# Database\n# https://docs.djangoproject.com/en/2.0/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': os.environ.get('POSTGRES_DB', 'tradingdb'),\n 'USER': os.environ.get('POSTGRES_USER', 'web'),\n 'PASSWORD': os.environ.get('POSTGRES_PASSWORD', 'password'),\n 'HOST': os.environ.get('POSTGRES_HOST', 'db'),\n 'PORT': os.environ.get('POSTGRES_PORT', '5432'),\n }\n}\n\n\n# Password validation\n# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators\n\nAUTH_USER_MODEL = 'user_accounts.User'\n\nAUTH_PASSWORD_VALIDATORS = [\n {\n 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', # noqa\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', # noqa\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', # noqa\n },\n {\n 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', # noqa\n },\n {\n 'NAME': 'web.authutils.WordGroupValidator', # noqa\n },\n]\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'user_accounts.backends.EthereumAuthenticationBackend',\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\n\n# Static files (CSS, JavaScript, Images)\n# https://docs.djangoproject.com/en/2.0/howto/static-files/\n\nSTATIC_URL = '/static/'\n\nPOLI_URL = os.environ.get('POLI_URL', 'https://poliapi.uat1.paywithpoli.com/')\nPOLI_MERCHANT_CODE = os.environ.get('POLI_MERCHANT_CODE', '')\nPOLI_AUTH_CODE = os.environ.get('POLI_AUTH_CODE', '')\nPOLI_SUCCESS_BASE_URL = os.environ.get(\n 'POLI_SUCCESS_BASE_URL',\n 'http://localhost:8000' # do not have trailing forward slash\n)\n\nDEFAULT_FROM_EMAIL = 'Enhanced Society '\nORDERS_EMAIL = 'trading@enhancedsociety.com'\n\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'formatters': {\n 'verbose': {\n 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' # noqa\n },\n 'simple': {\n 'format': '%(levelname)s %(message)s'\n },\n },\n 'handlers': {\n 'console': {\n 'class': 'logging.StreamHandler',\n 'formatter': 'verbose'\n },\n },\n 'loggers': {\n 'kyc': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),\n },\n 'tasks': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),\n },\n 'trading': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),\n },\n 'tse': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),\n },\n 'user_accounts': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),\n },\n 'celery': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),\n },\n 'web': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),\n },\n 'se': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),\n },\n 'eventlog': {\n 'handlers': ['console'],\n 'level': os.getenv('DJANGO_LOG_LEVEL', 'DEBUG'),\n },\n # 'zeep.transports': {\n # 'level': 'DEBUG',\n # 'propagate': True,\n # 'handlers': ['console'],\n # },\n },\n}\n\nLOGIN_REDIRECT_URL = \"/profile/\"\n\nLOGIN_URL = '/login/'\n\n\n#\n# Jumio/Netverify\n#\nNETVERIFY_API_TOKEN = os.environ.get('NETVERIFY_API_TOKEN', '')\nNETVERIFY_API_SECRET = os.environ.get('NETVERIFY_API_SECRET', '')\nNETVERIFY_BASE_URL = os.environ.get(\n 'NETVERIFY_BASE_URL',\n 'http://127.0.0.1:8000'\n)\n\n#\n# AML - greenID\n#\nGREEN_ID_URL = os.environ.get('GREEN_ID_URL', 'https://test-au.vixverify.com/')\nGREEN_ID_ACCOUNT_ID = os.environ.get('GREEN_ID_ACCOUNT_ID', '')\nGREEN_ID_PASSWORD = os.environ.get('GREEN_ID_PASSWORD', '')\n\nPLATFORM_VERSION = os.environ.get('platform_version', 'dev')\n\n#\n# Geth Node\n#\nGETH_NODE_URL = os.environ.get('GETH_NODE_URL', '')\nGETH_WHITELIST_OWNER_PRIVATE_KEY = os.environ.get(\n 'GETH_WHITELIST_OWNER_PRIVATE_KEY', '')\n\n#\n# GetEdge ASIC API\n#\nGETEDGE_API_KEY = os.environ.get('GETEDGE_API_KEY', '')\n\n#\n# Cache\n#\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache',\n 'LOCATION': '/var/tmp/django_cache',\n }\n}\n\n#\n# AUTH\n#\nAUTH0_DOMAIN = os.environ.get('AUTH0_DOMAIN', 'enhancedsociety.au.auth0.com')\nAUTH0_API_AUDIENCE = os.environ.get(\n 'AUTH0_API_AUDIENCE',\n 'http://localhost:8000/graphql'\n)\nAUTH0_CLIENT_ID = os.environ.get(\n 'AUTH0_CLIENT_ID',\n 'gJWwyYMWH0i4ctKpImMOc4EOKF71OMQT')\nALGORITHMS = os.environ.get('ALGORITHMS', ['RS256'])\n\n\"\"\"\nCache the key available at https://{AUTH0_DOMAIN}/.well-known/jwks.json dict\n(skipping this to prevent spoofing, even if improbable)\n\"\"\"\nwith open(os.environ.get(\n 'AUTH0_PUBLIC_KEY_FILE',\n 'web/settings/jwks/enhancedsociety.jwks.json'\n)) as jwks_data:\n AUTH0_PUBLIC_KEY = json.load(jwks_data)\n\n#\n# Google Places Autocomplete\n#\n# FIXME - should be read from secret place\nGOOGLE_CLOUD_PLATFORM_KEY = os.environ.get('GOOGLE_CLOUD_PLATFORM_KEY', '')\n","sub_path":"web/web/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":7491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"207576035","text":"import FWCore.ParameterSet.Config as cms\n\n\nfrom Configuration.Generator.Pythia8CommonSettings_cfi import *\nfrom Configuration.Generator.Pythia8CUEP8M1Settings_cfi import *\n\ngenerator = cms.EDFilter(\"Pythia8GeneratorFilter\",\n maxEventsToPrint = cms.untracked.int32(1),\n pythiaPylistVerbosity = cms.untracked.int32(1),\n filterEfficiency = cms.untracked.double(1.0),\n pythiaHepMCVerbosity = cms.untracked.bool(False),\n comEnergy = cms.double(13000.),\n PythiaParameters = cms.PSet(\n pythia8CommonSettingsBlock,\n pythia8CUEP8M1SettingsBlock,\n processParameters = cms.vstring( ## see details on http://home.thep.lu.se/~torbjorn/php8135/ExtraDimensionalProcesses.php?filepath=files/\n 'ExtraDimensionsLED:ffbar2GZ = on',\n #'ExtraDimensionsLED:CutOffmode = 1',\n 'ExtraDimensionsLED:t = 0.5',\n 'ExtraDimensionsLED:n = 2', ####\n 'ExtraDimensionsLED:MD = 3000.', ####\n 'ExtraDimensionsLED:LambdaT = 1000.',\n '5000039:m0 = 1200.',\n '5000039:mWidth = 1000.',\n '5000039:mMin = 1.',\n '5000039:mMax = 13990.',\n '23:onMode=off',\n '23:mMin=50',\n '23:onIfAny=11 13',\n #'PhaseSpace:pTHatMin = 130.'\n ),\n parameterSets = cms.vstring('pythia8CommonSettings',\n 'pythia8CUEP8M1Settings',\n 'processParameters',)\n )\n )\n\n\n\n\n","sub_path":"genfragments/ThirteenTeV/ADD/ADDmonoZ_MD_3_d_2_TuneCUETP8M1_13TeV_pythia8_cfi.py","file_name":"ADDmonoZ_MD_3_d_2_TuneCUETP8M1_13TeV_pythia8_cfi.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"608063395","text":"# -*- coding: utf-8 -*-\n\nfrom operator import attrgetter\nimport re\n\nfrom django.core.urlresolvers import reverse, reverse_lazy\nfrom django.db import models\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\nfrom django.template import loader, Context\nfrom django.template.defaultfilters import escape\n\nfrom markdown import markdown\n\nfrom limpyd import model as lmodel, fields as lfields\n\nfrom core import models as core_models, get_main_limpyd_database\nfrom core.utils import contribute_to_model\n\nfrom events.models import EventPart\n\nfrom subscriptions import models as subscriptions_models\n\n\ndef html_content(self, body_field='body'):\n html = getattr(self, '%s_html' % body_field, None)\n if html is None:\n html = markdown(getattr(self, body_field))\n return html\n\n\nclass _GithubUser(models.Model):\n AVATAR_START = re.compile('^https?://\\d+\\.')\n\n class Meta:\n abstract = True\n\n @property\n def hash(self):\n \"\"\"\n Hash for this object representing its state at the current time, used to\n know if we have to reset an issue's cache\n \"\"\"\n # we remove the subdomain of the gravatar url that may change between\n # requests to the github api for the same user with the save avatar\n # (https://0.gravatar..., https://1.gravatar...)\n avatar_url = ''\n if self.avatar_url:\n avatar_url = self.AVATAR_START.sub('', self.avatar_url, count=1)\n return hash((self.username, avatar_url, ))\n\n def get_related_issues(self):\n \"\"\"\n Return a list of all issues related to this user (it may be the creator,\n the assignee, or the closer)\n \"\"\"\n return core_models.Issue.objects.filter(\n models.Q(user=self)\n | models.Q(assignee=self)\n | models.Q(closed_by=self)\n )\n\ncontribute_to_model(_GithubUser, core_models.GithubUser)\n\n\nclass _Repository(models.Model):\n class Meta:\n abstract = True\n\n def get_reverse_kwargs(self):\n \"\"\"\n Return the kwargs to use for \"reverse\"\n \"\"\"\n return {\n 'owner_username': self.owner.username,\n 'repository_name': self.name,\n }\n\n def get_absolute_url(self):\n return reverse_lazy('front:repository:home', kwargs=self.get_reverse_kwargs())\n\n def get_view_url(self, url_name):\n return reverse_lazy('front:repository:%s' % url_name,\n kwargs=self.get_reverse_kwargs())\n\n def get_issues_filter_url(self):\n kwargs = self.get_reverse_kwargs()\n return reverse('front:repository:issues', kwargs=kwargs)\n\n def get_issues_user_filter_url_for_username(self, filter_type, username):\n \"\"\"\n Return the url to filter issues of this repositories by filter_type, for\n the given username\n Calls are cached for faster access\n \"\"\"\n cache_key = (self.id, filter_type, username)\n if cache_key not in self.get_issues_user_filter_url_for_username._cache:\n kwargs = self.get_reverse_kwargs()\n kwargs.update({\n 'username': username,\n 'user_filter_type': filter_type\n })\n self.get_issues_user_filter_url_for_username._cache[cache_key] = \\\n reverse('front:repository:user_issues', kwargs=kwargs)\n return self.get_issues_user_filter_url_for_username._cache[cache_key]\n get_issues_user_filter_url_for_username._cache = {}\n\ncontribute_to_model(_Repository, core_models.Repository)\n\n\nclass _LabelType(models.Model):\n class Meta:\n abstract = True\n\n def get_reverse_kwargs(self):\n \"\"\"\n Return the kwargs to use for \"reverse\"\n \"\"\"\n return {\n 'owner_username': self.repository.owner.username,\n 'repository_name': self.repository.name,\n 'label_type_id': self.id\n }\n\n def get_edit_url(self):\n from front.repository.dashboard.views import LabelTypeEdit\n return reverse_lazy('front:repository:%s' % LabelTypeEdit.url_name, kwargs=self.get_reverse_kwargs())\n\n def get_delete_url(self):\n from front.repository.dashboard.views import LabelTypeDelete\n return reverse_lazy('front:repository:%s' % LabelTypeDelete.url_name, kwargs=self.get_reverse_kwargs())\n\n @property\n def hash(self):\n \"\"\"\n Hash for this object representing its state at the current time, used to\n know if we have to reset an issue's cache\n \"\"\"\n return hash((self.id, self.name, ))\n\n def get_related_issues(self):\n \"\"\"\n Return a list of all issues related to this label type\n \"\"\"\n return core_models.Issue.objects.filter(labels__label_type=self)\n\ncontribute_to_model(_LabelType, core_models.LabelType)\n\n\nclass _Label(models.Model):\n class Meta:\n abstract = True\n\n @property\n def hash(self):\n \"\"\"\n Hash for this object representing its state at the current time, used to\n know if we have to reset an issue's cache\n \"\"\"\n return hash((self.id, self.name, self.color,\n self.label_type.hash if self.label_type_id else None, ))\n\n def get_related_issues(self):\n \"\"\"\n Return a list of all issues related to this label\n \"\"\"\n return core_models.Issue.objects.filter(labels=self)\n\ncontribute_to_model(_Label, core_models.Label)\n\n\nclass _Milestone(models.Model):\n class Meta:\n abstract = True\n\n @property\n def hash(self):\n \"\"\"\n Hash for this object representing its state at the current time, used to\n know if we have to reset an issue's cache\n \"\"\"\n return hash((self.id, self.title, self.state, ))\n\n def get_related_issues(self):\n \"\"\"\n Return a list of all issues related to this milestone\n \"\"\"\n return core_models.Issue.objects.filter(milestone=self)\n\n @property\n def html_content(self):\n return html_content(self, 'description')\n\n @property\n def short_title(self):\n if len(self.title) > 25:\n result = self.title[:20] + u'…'\n else:\n result = self.title\n return escape(result)\n\n def get_reverse_kwargs(self):\n \"\"\"\n Return the kwargs to use for \"reverse\"\n \"\"\"\n return {\n 'owner_username': self.repository.owner.username,\n 'repository_name': self.repository.name,\n 'milestone_id': self.id\n }\n\n def get_edit_url(self):\n from front.repository.dashboard.views import MilestoneEdit\n return reverse_lazy('front:repository:%s' % MilestoneEdit.url_name, kwargs=self.get_reverse_kwargs())\n\n def get_delete_url(self):\n from front.repository.dashboard.views import MilestoneDelete\n return reverse_lazy('front:repository:%s' % MilestoneDelete.url_name, kwargs=self.get_reverse_kwargs())\n\n\ncontribute_to_model(_Milestone, core_models.Milestone)\n\n\nclass _Issue(models.Model):\n class Meta:\n abstract = True\n\n RENDERER_IGNORE_FIELDS = set(['state', 'merged', ])\n\n def get_reverse_kwargs(self):\n \"\"\"\n Return the kwargs to use for \"reverse\"\n \"\"\"\n return {\n 'owner_username': self.repository.owner.username,\n 'repository_name': self.repository.name,\n 'issue_number': self.number\n }\n\n def get_absolute_url(self):\n return reverse_lazy('front:repository:issue', kwargs=self.get_reverse_kwargs())\n\n def edit_field_url(self, field):\n return reverse_lazy('front:repository:issue.edit.%s' % field, kwargs=self.get_reverse_kwargs())\n\n def issue_comment_create_url(self):\n return reverse_lazy('front:repository:issue.comment.create', kwargs=self.get_reverse_kwargs())\n\n def pr_comment_create_url(self):\n if not hasattr(self, '_pr_comment_create_url'):\n self._pr_comment_create_url = reverse_lazy('front:repository:issue.pr_comment.create',\n kwargs=self.get_reverse_kwargs())\n return self._pr_comment_create_url\n\n def ajax_files_url(self):\n return reverse_lazy('front:repository:issue.files', kwargs=self.get_reverse_kwargs())\n\n def ajax_commits_url(self):\n return reverse_lazy('front:repository:issue.commits', kwargs=self.get_reverse_kwargs())\n\n @property\n def type(self):\n return 'pull request' if self.is_pull_request else 'issue'\n\n @property\n def nb_authors(self):\n if not self.is_pull_request or not self.nb_commits:\n return 0\n if self.nb_commits == 1:\n return 1\n return len(set(self.commits.values_list('author_name', flat=True)))\n\n @property\n def hash(self):\n \"\"\"\n Hash for this issue representing its state at the current time, used to\n know if we have to reset an its cache\n \"\"\"\n return hash((self.updated_at,\n self.user.hash if self.user_id else None,\n self.closed_by.hash if self.closed_by_id else None,\n self.assignee.hash if self.assignee_id else None,\n self.milestone.hash if self.milestone_id else None,\n self.total_comments_count or 0,\n ','.join(['%d' % l.hash for l in self.labels.all()]),\n ))\n\n def update_saved_hash(self):\n \"\"\"\n Update in redis the saved hash\n \"\"\"\n hash_obj, _ = Hash.get_or_connect(\n type=self.__class__.__name__, obj_id=self.pk)\n hash_obj.hash.hset(self.hash)\n\n @property\n def saved_hash(self):\n \"\"\"\n Return the saved hash, create it if not exist\n \"\"\"\n hash_obj, created = Hash.get_or_connect(\n type=self.__class__.__name__, obj_id=self.pk)\n if created:\n self.update_saved_hash()\n return hash_obj.hash.hget()\n\n def update_cached_template(self, force_regenerate=False):\n \"\"\"\n Update, if needed, the cached template for the current issue.\n \"\"\"\n template = 'front/repository/issues/include_issue_item_for_cache.html'\n\n # mnimize queries\n issue = self.__class__.objects.filter(id=self.id)\\\n .select_related('user', 'assignee', 'created_by', 'milestone')\\\n .prefetch_related('labels__label_type')[0]\n\n context = Context({\n 'issue': issue,\n '__regenerate__': force_regenerate,\n })\n\n loader.get_template(template).render(context)\n\n @property\n def all_commits(self):\n if not hasattr(self, '_all_commits'):\n self._all_commits = list(self.commits.all()\n .select_related('author',\n 'committer', 'repository__owner')\n .order_by('authored_at'))\n return self._all_commits\n\n @property\n def all_entry_points(self):\n if not hasattr(self, '_all_entry_points'):\n self._all_entry_points = list(self.pr_comments_entry_points\n .annotate(nb_comments=models.Count('comments'))\n .filter(nb_comments__gt=0)\n .select_related('user', 'pr_comments',\n 'repository__owner')\n .prefetch_related('comments__user'))\n return self._all_entry_points\n\n def get_activity(self):\n \"\"\"\n Return the activity of the issue, including comments, events and\n pr_comments if it's a pull request\n \"\"\"\n change_events = list(self.event_set.filter(id__in=set(\n EventPart.objects.filter(\n event__is_update=True,\n event__issue_id=self.id,\n )\n .exclude(\n field__in=self.RENDERER_IGNORE_FIELDS\n )\n .values_list('event_id', flat=True)\n )).prefetch_related('parts'))\n\n for event in change_events:\n event.renderer_ignore_fields = self.RENDERER_IGNORE_FIELDS\n types = [\n list(self.comments.select_related('user', 'repository__owner')),\n list(self.events.exclude(event='referenced', commit_sha__isnull=True)\n .select_related('user', 'repository__owner')),\n change_events,\n ]\n if self.is_pull_request:\n types.append(self.all_entry_points)\n\n activity = sorted(sum(types, []), key=attrgetter('created_at'))\n\n if self.is_pull_request:\n activity = GroupedCommits.add_commits_in_activity(self.all_commits, activity)\n\n return activity\n\n def get_commits_per_day(self):\n if not self.is_pull_request:\n return []\n return GroupedCommits.group_commits_by_day(self.all_commits)\n\n @property\n def html_content(self):\n return html_content(self)\n\ncontribute_to_model(_Issue, core_models.Issue)\n\n\nclass GroupedCommits(list):\n \"\"\"\n An object to regroup a list of commits\n - in a list of activities: all commits between two entries of the activity\n list are grouped together per day (\"add_commits_in_activity\")\n - per day (\"group_commits_by_day\")\n \"\"\"\n is_commits_group = True # for template\n\n @classmethod\n def add_commits_in_activity(cls, commits, activity):\n if not len(commits):\n return activity\n\n commits = list(commits)\n final_activity = []\n current_group = None\n\n for entry in activity:\n\n # add in a group all commits before the entry\n while len(commits) and commits[0].authored_at < entry.created_at:\n if current_group is None:\n current_group = cls()\n current_group.append(commits.pop(0))\n\n if current_group:\n # final_activity.append(current_group)\n final_activity.extend(GroupedCommits.group_commits_by_day(current_group))\n current_group = None\n\n # then add the entry\n final_activity.append(entry)\n\n # still some commits, add a group with them\n if len(commits):\n #final_activity.append(cls(commits))\n final_activity.extend(GroupedCommits.group_commits_by_day(commits))\n\n return final_activity\n\n @classmethod\n def group_commits_by_day(cls, commits):\n if not len(commits):\n return []\n\n groups = []\n current_date = None\n\n for commit in commits:\n commit_date = commit.authored_at.date()\n if not current_date or commit_date != current_date:\n groups.append(cls())\n current_date = commit_date\n groups[-1].append(commit)\n\n return groups\n\n def authors(self):\n authors = []\n for commit in self:\n name = commit.author.username if commit.author_id else commit.author_name\n if name not in authors:\n authors.append(name)\n return authors\n\n\nclass _Commit(models.Model):\n class Meta:\n abstract = True\n\n @property\n def splitted_message(self):\n LEN = 72\n ln_pos = self.message.find('\\n')\n if 0 <= ln_pos < LEN:\n result = [self.message[:ln_pos], self.message[ln_pos+1:]]\n while result[1] and result[1][0] == '\\n':\n result[1] = result[1][1:]\n return result\n return [self.message[:LEN], self.message[LEN:]]\n\ncontribute_to_model(_Commit, core_models.Commit)\n\n\nclass _WaitingSubscription(models.Model):\n class Meta:\n abstract = True\n\n def can_add_again(self):\n \"\"\"\n Return True if the user can add the reposiory again (it is allowed if\n the state is FAILED)\n \"\"\"\n return self.state == subscriptions_models.WAITING_SUBSCRIPTION_STATES.FAILED\n\ncontribute_to_model(_WaitingSubscription, subscriptions_models.WaitingSubscription)\n\n\nclass _IssueComment(models.Model):\n class Meta:\n abstract = True\n\n @property\n def html_content(self):\n return html_content(self)\n\ncontribute_to_model(_IssueComment, core_models.IssueComment)\n\n\nclass _PullRequestComment(models.Model):\n class Meta:\n abstract = True\n\n @property\n def html_content(self):\n return html_content(self)\n\ncontribute_to_model(_PullRequestComment, core_models.PullRequestComment)\n\n\nclass Hash(lmodel.RedisModel):\n\n database = get_main_limpyd_database()\n\n type = lfields.InstanceHashField(indexable=True)\n obj_id = lfields.InstanceHashField(indexable=True)\n hash = lfields.InstanceHashField()\n\n\n@receiver(post_save, dispatch_uid=\"hash_check\")\ndef hash_check(sender, instance, created, **kwargs):\n \"\"\"\n Check if the hash of the object has changed since its last save and if True,\n update the Issue if its an issue, or related issues if it's a:\n - user\n - milestone\n - label_type\n - label\n \"\"\"\n\n if not isinstance(instance, (\n core_models.GithubUser,\n core_models.Milestone,\n core_models.LabelType,\n core_models.Label,\n core_models.Issue\n )):\n return\n\n # get the limpyd instance storing the hash, create it if not exists\n hash_obj, hash_obj_created = Hash.get_or_connect(\n type=instance.__class__.__name__, obj_id=instance.pk)\n\n if created:\n hash_changed = True\n else:\n hash_changed = hash_obj_created or str(instance.hash) != hash_obj.hash.hget()\n\n if not hash_changed:\n return\n\n # save the new hash\n hash_obj.hash.hset(instance.hash)\n\n from core.tasks.issue import UpdateIssueCacheTemplate\n\n if isinstance(instance, core_models.Issue):\n # if an issue, add a job to update its template\n UpdateIssueCacheTemplate.add_job(instance.id)\n\n else:\n # if not an issue, add a job to update the templates of all related issues\n for issue in instance.get_related_issues():\n UpdateIssueCacheTemplate.add_job(issue.id)\n","sub_path":"gim_project/front/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":18662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"} +{"seq_id":"645853146","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- \n# Author: Guanqinglin\n# QQ:7796755\n# Email:qinglin@qinglin.net\nimport pymysql\n\ndef xargs(host):\n if len(host) > 1:\n list = host['hostname'],host['ip'],host['idc'],int(host['groupName']),int(host['status']),int(host['type_id']),host['os'],int(host['cpu']),host['memory'],host['disk']\n sql = \"INSERT INTO `cmdb`.`tb_hosts` (`id`, `hostname`, `ip`, `idc`, `group_id`, `status`, `type_id`, `operation`, `cpu_num`, `mem_size`, `disk_size`, `create_at`, `update_at`) VALUES (NULL, '%s', '%s', '%s', '%s','%s','%s','%s','%s','%s','%s', localtime(), localtime())\" %(list[0],list[1],list[2],list[3],list[4],list[5],list[6],list[7],list[8],list[9])\n mysql_conn(sql)\n else:\n exit(\"No input Null!\")\n\ndef mysql_conn(sql):\n with open('D:\\\\db.ini','r',encoding='utf8',) as f:\n db_file = f.read()\n try:\n conn = pymysql.connect(user='cmdb',passwd='ztzdsb250250',host='123.206.30.206',db='cmdb',charset='utf8')\n except:\n exit(\"Database conn fail!\")\n try:\n cur = conn.cursor()\n cur.execute(sql)\n conn.commit()\n cur.close()\n conn.close()\n\n except:\n exit(\"SQL execute fail\")\n\n\n\nnumber_1 = {\n \"hostname\": \"nginx-01\",\n \"ip\": \"124.2.5.2\",\n \"idc\": \"世纪互联\",\n \"groupName\": \"1\",\n \"status\":\"1\",\n \"type_id\":\"1\",\n \"os\": \"centos-6.5\",\n \"cpu\": \"12\",\n \"memory\": \"24g\",\n \"disk\": \"2t\"\n}\n\n\nxargs(number_1)","sub_path":"Python3_test/cmdb/host.py","file_name":"host.py","file_ext":"py","file_size_in_byte":1464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"67"}