diff --git "a/4612.jsonl" "b/4612.jsonl" new file mode 100644--- /dev/null +++ "b/4612.jsonl" @@ -0,0 +1,752 @@ +{"seq_id":"51952453","text":"import threading\n\ndef do_some_work(val):\n print(\"doing some work in thread\")\n print(\"echo: {}\".format(val))\n return\n\n\nval = \"text\"\nt = threading.Thread(target=do_some_work, args=(val, ))\nt.start()\nt.join()\n","sub_path":"thread_demo.py","file_name":"thread_demo.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"100623081","text":"import sys\nif sys.version < '3':\n from urllib import urlencode\n from urllib2 import urlopen, Request\n from StringIO import StringIO\nelse:\n from urllib.parse import urlencode\n from urllib.request import urlopen, Request\n from io import BytesIO as StringIO\nfrom django.conf import settings\nimport json\nimport requests\n\n\ndef getsid(request):\n if 'X-sessionid' in request.META:\n return request.session.session_key + '_' + request.GET['sid']\n else:\n return request.session.session_key + '_NOSID'\n\ndef setsid(request, sid):\n request.add_header('X-sessionid', sid)\n\ndef query(request, query, parsejson=True, **extradata):\n data = {'query':query}\n for key, value in extradata.items():\n if isinstance(value, bool):\n data[key] = int(value)\n else:\n data[key] = value\n if sys.version < '3':\n #encode for python 2\n for key, value in data.items():\n if isinstance(value,unicode): #pylint: disable=undefined-variable\n data[key] = value.encode('utf-8')\n\n docservereq = Request(\"http://\" + settings.FOLIADOCSERVE_HOST + \":\" + str(settings.FOLIADOCSERVE_PORT) + \"/query/\")\n setsid(docservereq, getsid(request))\n f = urlopen(docservereq,urlencode(data).encode('utf-8')) #or opener.open()\n if sys.version < '3':\n contents = unicode(f.read(),'utf-8') #pylint: disable=undefined-variable\n else:\n contents = str(f.read(),'utf-8')\n f.close()\n if contents and contents[0] in ('{','['):\n #assume this is json\n if parsejson:\n return json.loads(contents)\n else:\n return contents\n elif contents:\n return contents\n else:\n if parsejson:\n return None\n else:\n return \"\"\n\n\n\ndef get( request, url, parsejson=True):\n docservereq = Request(\"http://\" + settings.FOLIADOCSERVE_HOST + \":\" + str(settings.FOLIADOCSERVE_PORT) + \"/\" + url) #or opener.open()\n setsid(docservereq, getsid(request))\n f = urlopen(docservereq)\n if sys.version < '3':\n contents = unicode(f.read(),'utf-8')\n else:\n contents = str(f.read(),'utf-8')\n f.close()\n if contents and contents[0] in ('{','['):\n #assume this is json\n if parsejson:\n return json.loads(contents)\n else:\n return contents\n elif contents:\n return contents\n else:\n if parsejson:\n return None\n else:\n return \"\"\n\ndef postjson( request, url, data):\n if isinstance(data, dict) or isinstance(data,list) or isinstance(data, tuple):\n data = json.dumps(data)\n docservereq = Request(\"http://\" + settings.FOLIADOCSERVE_HOST + \":\" + str(settings.FOLIADOCSERVE_PORT) + \"/\" + url + '/' + sid) #or opener.open()\n setsid(docservereq, getsid(request))\n docservereq.add_header('Content-Type', 'application/json')\n f = urlopen(docservereq, urlencode(data).encode('utf-8'))\n if sys.version < '3':\n contents = unicode(f.read(),'utf-8')\n else:\n contents = str(f.read(),'utf-8')\n f.close()\n if contents and contents[0] == '{':\n #assume this is json\n return json.loads(contents)\n elif contents:\n return contents\n else:\n return None\n\ndef postxml( request, url, f):\n #buf = StringIO()\n #c = pycurl.Curl()\n #url = \"http://\" + settings.FOLIADOCSERVE_HOST + \":\" + str(settings.FOLIADOCSERVE_PORT) + \"/\" + url\n #c.setopt(c.URL, url.encode('utf-8'))\n #c.setopt(c.HTTPPOST, data.encode('utf-8') )\n #c.setopt(pycurl.HTTPHEADER, [\"Content-Type: application/json\"])\n #c.setopt(pycurl.POST, 1)\n #c.setopt(pycurl.POSTFIELDS, data.encode('utf-8'))\n #c.setopt(c.WRITEFUNCTION, buf.write)\n #c.perform()\n #code = c.getinfo(c.HTTP_CODE)\n #contents = buf.getvalue()\n #c.close()\n\n\n #req = Request(\"http://\" + settings.FOLIADOCSERVE_HOST + \":\" + str(settings.FOLIADOCSERVE_PORT) + \"/\" + url)\n #req.add_header('Content-Type', 'application/xml; charset=utf-8')\n #req.add_data(urlencode({'data':data.encode('utf-8')}))\n #f = urlopen(req)\n #contents = f.read()\n #f.close()\n\n response = requests.post(\"http://\" + settings.FOLIADOCSERVE_HOST + \":\" + str(settings.FOLIADOCSERVE_PORT) + \"/\" + url, data=f, headers={'Content-Type':'application/xml; charset=utf-8'})\n contents = response.text\n if contents and contents[0] == '{':\n #assume this is json\n return json.loads(contents)\n elif contents:\n return contents\n else:\n return None\n\n","sub_path":"flat/comm.py","file_name":"comm.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"498222356","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 12 18:07:25 2020\n\n@author: ISAAC BUSTAMANTE\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\ndata = pd.read_csv(\"C://Datos/Airline Satisfaction Survey.csv\", )\n\n\"\"\" AÑOS EN EL QUE SE BRINDO MEJOR SERVICIO\nanios = data['Year of First Flight'].unique()\n\nyears = sorted(anios)\n\n#for i in data.loc[:100,'Year of First Flight']:\n # print(i)\n \nsatisfacciones = [0,0,0,0,0,0,0,0,0,0]\n \nfor i in range(0,len(years)):\n for j in data.loc[:100,'Year of First Flight']:\n if(years[i] == j):\n satisfacciones[i] += 1\n \n\n#datos = [media,mediana,desviacion_estandar,percentil]\n#nombres = ['Media','Mediana','Desviacion Estandar','Percentiles']\n\nfig = plt.figure(u'Gráfica de barras') # Figure\nax = fig.add_subplot(111) # Axes\nxx = range(len(satisfacciones))\nax.bar(xx, satisfacciones, width=0.8, align='center')\nax.set_xticks(xx)\nax.set_xticklabels(years)\nplt.show()\n\n#print(satisfacciones)\"\"\"\n\n\"\"\" EL ESTATUS DE LA AEROLINEA QUE TIENE MAS COMPRAS EN PESOS\ncompras_vuelos = [0,0,0,0]\nairline_status = data['Airline Status'].unique()\nprint(airline_status)\n#for i in range(0,len(airline_status)):\n#print(data[{'Airline Status','Shopping Amount at Airport'}])\nfor j,rows in data.iterrows():\n if(rows['Airline Status'] == \"Blue\"):\n compras_vuelos[0] += rows['Shopping Amount at Airport']\n elif(rows['Airline Status'] == \"Silver\"):\n compras_vuelos[1] += rows['Shopping Amount at Airport']\n elif(rows['Airline Status'] == \"Gold\"):\n compras_vuelos[2] += rows['Shopping Amount at Airport']\n else:\n compras_vuelos[3] += rows['Shopping Amount at Airport']\n\nprint(compras_vuelos)\n#Grafica de pasteles\nplt.pie(compras_vuelos, labels=['Blue','Silver','Golden','Platinum'], autopct=\"%0.1f %%\")\nplt.show()\n\"\"\"\n\n#-----------------------------------------------\n\n\n\"\"\"AEROLIONEA QUE MAS VIAJA\nfrecuencias_class = [0, 0, 0]\nclases = data['Class'].unique()\nprint(clases)\n\nfor i in range(0,len(clases)):\n for index,row in data[0:100].iterrows():\n if(clases[i] == row['Class']):\n frecuencias_class[i] += 1\n\nprint(frecuencias_class)\n\nfig = plt.figure(u'Gráfica de barras') # Figure\nax = fig.add_subplot(111) # Axes\nxx = range(len(frecuencias_class))\nax.bar(xx, frecuencias_class, width=0.8, align='center')\nax.set_xticks(xx)\nax.set_xticklabels(clases)\nplt.show()\"\"\"\n\n\n#print(data.loc[:3,'Destination State'].unique())\n\narrayA = []\n#arrayB = []\n#arrayC = []\n#a = 0\n\nprint(data.loc[:100, 'Destination State'].unique())\n\nfor i,row in data[0:100].iterrows():\n if row['Destination State'] == \"Texas\":\n arrayA.append(row['No of Flights p.a.'])\n\nprint(arrayA)\n#print(arrayB)\n#print(arrayC)\narray_numpy = np.array(arrayA)\n\nplt.plot(array_numpy, marker='*', color='m', label = 'Vuelos a Texas', linestyle = '-.')\nplt.title(\"Comportamiento del No. de Vuelos por Aerolinea\")\nplt.ylabel(\"No. Vuelos para Texas\")\n\nplt.legend()#Mostarmos el label\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"MultiplesGraficasEstadisticas.py","file_name":"MultiplesGraficasEstadisticas.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"177897712","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nScript Name: ActionManager.py\nAuthor: Do Trinh/Jimmy - 3D artist.\n\nDescription:\n\n\"\"\"\n# -------------------------------------------------------------------------------------------------------------\nfrom __future__ import absolute_import, unicode_literals\n\nimport os\nfrom bin.data.damg import DAMGDICT, DAMGLIST\nfrom functools import partial\n\nfrom ui.uikits.Action import Action\nfrom utils import data_handler, is_action, is_string\nfrom appData import (mainConfig, SHOWLAYOUT_KEY, START_FILE_KEY, EXECUTING_KEY, OPEN_BROWSER_KEY, CONFIG_DEV, CONFIG_TOOLS,\n CONFIG_OFFICE, CONFIG_TDS, CONFIG_ART, CONFIG_TEX, CONFIG_POST, CONFIG_VFX, CONFIG_EXTRA,\n CONFIG_SYSTRAY, RESTORE_KEY, SHOWMIN_KEY, SHOWMAX_KEY)\n\nclass ActionManager(DAMGDICT):\n\n key = 'ActionManager'\n _name = 'ActionManager'\n\n appInfo = data_handler(filePath=mainConfig)\n\n actionKeys = DAMGLIST()\n showLayoutKeys = DAMGLIST()\n showRestoreKeys = DAMGLIST()\n showMaximizeKeys = DAMGLIST()\n showMinimizeKeys = DAMGLIST()\n startFileKeys = DAMGLIST()\n openBrowserKeys = DAMGLIST()\n executingKeys = DAMGLIST()\n\n orgActions = ['NewOrganisation', 'EditOrganisation']\n teamActions = ['NewTeam', 'EditTeam']\n prjActions = ['NewProject', 'EditProject']\n appActions = ['SettingUI', 'Configuration', 'Preferences', 'Exit']\n goActions = ['ConfigFolder', 'IconFolder', 'SettingFolder', 'AppFolder']\n officeActions = ['TextEditor', 'NoteReminder'] + CONFIG_OFFICE\n toolsActions = CONFIG_TOOLS + ['CleanPyc', 'ReConfig', 'Debug']\n devActions = CONFIG_DEV\n libActions = ['Alpha', 'HDRI', 'Texture']\n helpActions = ['PLM wiki', 'About', 'CodeOfConduct', 'Contributing', 'Credit', 'Reference', 'Version', 'Feedback', 'ContactUs', ]\n\n tdActions = CONFIG_TDS\n artActions = CONFIG_ART\n texActions = CONFIG_TEX\n postActions = CONFIG_POST\n vfxActions = CONFIG_VFX\n extraActions = CONFIG_EXTRA\n sysTrayActions = CONFIG_SYSTRAY\n\n def __init__(self, parent=None):\n super(ActionManager, self).__init__(self)\n\n self.parent = parent\n self.showLayoutKeys.appendList(SHOWLAYOUT_KEY)\n self.startFileKeys.appendList(START_FILE_KEY)\n self.executingKeys.appendList(EXECUTING_KEY)\n self.openBrowserKeys.appendList(OPEN_BROWSER_KEY)\n self.showRestoreKeys.appendList(RESTORE_KEY)\n self.showMaximizeKeys.appendList(SHOWMAX_KEY)\n self.showMinimizeKeys.appendList(SHOWMIN_KEY)\n\n self.actionKeys = self.showLayoutKeys + self.startFileKeys + self.executingKeys + self.officeActions + \\\n self.showRestoreKeys + self.showMaximizeKeys + self.showMinimizeKeys\n\n def actionConfigError(self, key):\n return print('ActionKeyConfigError: This key is not registered: {0}'.format(key))\n\n def actionRegisterError(self, key):\n return print('ActionRegisterError: This action is already registered: {0}'.format(key))\n\n def extraToolActions(self, parent):\n return self.createActions(self.extraActions, parent)\n\n def tdToolBarActions(self, parent):\n return self.createActions(self.tdActions, parent)\n\n def artToolBarActions(self, parent):\n return self.createActions(self.artActions, parent)\n\n def texToolBarActions(self, parent):\n return self.createActions(self.texActions, parent)\n\n def postToolBarActions(self, parent):\n return self.createActions(self.postActions, parent)\n\n def vfxToolBarActions(self, parent):\n return self.createActions(self.vfxActions, parent)\n\n def sysTrayMenuActions(self, parent):\n return self.createActions(self.sysTrayActions, parent)\n\n def appMenuActions(self, parent):\n return self.createActions(self.appActions, parent)\n\n def orgMenuActions(self, parent):\n return self.createActions(self.orgActions, parent)\n\n def teamMenuActions(self, parent):\n return self.createActions(self.teamActions, parent)\n\n def projectMenuActions(self, parent):\n return self.createActions(self.prjActions, parent)\n\n def goMenuActions(self, parent):\n return self.createActions(self.goActions, parent)\n\n def officeMenuActions(self, parent):\n return self.createActions(self.officeActions, parent)\n\n def toolsMenuActions(self, parent):\n return self.createActions(self.toolsActions, parent)\n\n def devMenuActions(self, parent):\n return self.createActions(self.devActions, parent)\n\n def libMenuActions(self, parent):\n return self.createActions(self.libActions, parent)\n\n def helpMenuActions(self, parent):\n return self.createActions(self.helpActions, parent)\n\n def createActions(self, keys, parent):\n actions = []\n for key in keys:\n if key in self.appInfo.keys():\n if is_string(key):\n action = self.createAction(key, parent)\n actions.append(action)\n elif is_action(key):\n action = key\n action.setParent(parent)\n self.register(action)\n actions.append(action)\n else:\n print(\"DATATYPEERROR: Could not add action: {0}\".format(key))\n\n return actions\n\n def createAction(self, key, parent):\n if key in self.showLayoutKeys:\n # print('{0} is set to {1} action'.format(key, 'showlayout'))\n return self.showLayoutAction(key, parent)\n elif key in self.startFileKeys:\n # print('{0} is set to {1} action'.format(key, 'startfile'))\n return self.startFileAction(key, parent)\n elif key in self.executingKeys:\n # print('{0} is set to {1} action'.format(key, 'executing'))\n return self.executingAction(key, parent)\n elif key in self.openBrowserKeys:\n # print('{0} is set to {1} action'.format(key, 'openBrowser'))\n return self.openBrowserAction(key, parent)\n elif key in self.showMinimizeKeys:\n # print('{0} is set to {1} action'.format(key, 'showminimized'))\n return self.showMinAction(key, parent)\n elif key in self.showMaximizeKeys:\n # print('{0} is set to {1} action'.format(key, 'showmaximized'))\n return self.showMaxAction(key, parent)\n elif key in self.showRestoreKeys:\n # print('{0} is set to {1} action'.format(key, 'showrestore'))\n return self.showRestoreAction(key, parent)\n else:\n return self.actionConfigError(key)\n\n def showLayoutAction(self, key, parent):\n if key in self.appInfo.keys():\n action = Action({'icon': self.appInfo[key][1],\n 'txt': '&{0}'.format(key),\n 'stt': self.appInfo[key][0],\n 'trg': partial(parent.signals.emit, 'showLayout', key, 'show'), }, parent)\n action.key = '{0}_{1}_Action'.format(parent.key, key)\n action._name = action.key\n if action.key in self.actionKeys:\n return self[action.key]\n else:\n action._name = '{0} Action'.format(key)\n action.Type = 'DAMGShowLayoutAction'\n self.register(action)\n return action\n else:\n return self.actionConfigError(key)\n\n def showRestoreAction(self, key, parent):\n if key in self.appInfo.keys():\n action = Action({'icon': self.appInfo[key][1],\n 'txt': '&{0}'.format(key),\n 'stt': self.appInfo[key][0],\n 'trg': partial(parent.signals.emit, 'showLayout', self.appInfo[key][2], 'showRestore'), }, parent)\n action.key = '{0}_{1}_Action'.format(parent.key, key)\n action._name = action.key\n if action.key in self.actionKeys:\n return self[action.key]\n else:\n action._name = '{0} Action'.format(key)\n action.Type = 'DAMGShowNormalAction'\n self.register(action)\n return action\n else:\n return self.actionConfigError(key)\n\n def showMaxAction(self, key, parent):\n if key in self.appInfo.keys():\n action = Action({'icon': self.appInfo[key][1],\n 'txt': '&{0}'.format(key),\n 'stt': self.appInfo[key][0],\n 'trg': partial(parent.signals.emit, 'showLayout', self.appInfo[key][2], 'showMax'), }, parent)\n action.key = '{0}_{1}_Action'.format(parent.key, key)\n action._name = action.key\n if action.key in self.actionKeys:\n return self[action.key]\n else:\n action._name = '{0} Action'.format(key)\n action.Type = 'DAMGShowMaximizeAction'\n self.register(action)\n return action\n else:\n return self.actionConfigError(key)\n\n def showMinAction(self, key, parent):\n if key in self.appInfo.keys():\n action = Action({'icon': self.appInfo[key][1],\n 'txt': '&{0}'.format(key),\n 'stt': self.appInfo[key][0],\n 'trg': partial(parent.signals.emit, 'showLayout', self.appInfo[key][2], 'showMin'), }, parent)\n action.key = '{0}_{1}_Action'.format(parent.key, key)\n action._name = action.key\n if action.key in self.actionKeys:\n return self[action.key]\n else:\n action._name = '{0} Action'.format(key)\n action.Type = 'DAMGShowMinimizeAction'\n self.register(action)\n return action\n else:\n return self.actionConfigError(key)\n\n def startFileAction(self, key, parent):\n if key in self.appInfo.keys():\n # print('create start file action: {} {}'.format(key, self.appInfo[key][2]))\n action = Action({'icon': self.appInfo[key][1],\n 'txt': '&{0}'.format(key),\n 'stt': self.appInfo[key][0],\n 'trg': partial(os.startfile, self.appInfo[key][2])}, parent)\n action.key = '{0}_{1}_Action'.format(parent.key, key)\n action._name = action.key\n if action.key in self.actionKeys:\n return self[action.key]\n else:\n action._name = '{0} Action'.format(key)\n action.Type = 'DAMGStartFileAction'\n self.register(action)\n return action\n else:\n return self.actionConfigError(key)\n\n def executingAction(self, key, parent):\n if key in self.appInfo.keys():\n action = Action({'icon': self.appInfo[key][1],\n 'txt': '&{0}'.format(key),\n 'stt': self.appInfo[key][0],\n 'trg': partial(parent.signals.emit, 'executing', self.appInfo[key][2]), }, parent)\n action.key = '{0}_{1}_Action'.format(parent.key, key)\n action._name = '{0} Action'.format(key)\n if action.key in self.actionKeys:\n return self[action.key]\n else:\n action.Type = 'DAMGExecutingAction'\n self.register(action)\n return action\n else:\n return self.actionConfigError(key)\n\n def openBrowserAction(self, key, parent):\n if key in self.appInfo.keys():\n action = Action({'icon': self.appInfo[key][1],\n 'txt': '&{0}'.format(key),\n 'stt': self.appInfo[key][0],\n 'trg': partial(parent.signals.emit, 'openBrowser', self.appInfo[key][2]), }, parent)\n action.key = '{0}_{1}_Action'.format(parent.key, key)\n action._name = action.key\n if action.key in self.actionKeys:\n return self[action.key]\n else:\n action._name = '{0} Action'.format(key)\n action.Type = 'DAMGOpenBrowserAction'\n self.register(action)\n return action\n else:\n return self.actionConfigError(key)\n\n def register(self, action):\n # print('register action: {}'.format(action))\n if not action.key in self.actionKeys:\n self.actionKeys.append(action.key)\n self[action.key] = action\n else:\n return self.actionRegisterError(action.key)\n\n def actions(self):\n return self.values()\n\n# -------------------------------------------------------------------------------------------------------------\n# Created by panda on 3/11/2019 - 5:26 PM\n# © 2017 - 2018 DAMGteam. All rights reserved","sub_path":"ui/ActionManager.py","file_name":"ActionManager.py","file_ext":"py","file_size_in_byte":13226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"42097108","text":"import numpy as np\nfrom scipy.optimize import minimize\nfrom scipy.io import loadmat\nfrom math import sqrt\nimport time\n\ndef initializeWeights(n_in, n_out):\n \"\"\"\n # initializeWeights return the random weights for Neural Network given the\n # number of node in the input layer and output layer\n\n # Input:\n # n_in: number of nodes of the input layer\n # n_out: number of nodes of the output layer\n \n # Output: \n # W: matrix of random initial weights with size (n_out x (n_in + 1))\"\"\"\n\n epsilon = sqrt(6) / sqrt(n_in + n_out + 1)\n W = (np.random.rand(n_out, n_in + 1) * 2 * epsilon) - epsilon\n return W\n\n\ndef sigmoid(z):\n \"\"\"# Notice that z can be a scalar, a vector or a matrix\n # return the sigmoid of input z\"\"\"\n # Numpy handles this better than I do\n return 1/(np.exp(-z) +1)\n\n\n\ndef preprocess():\n \"\"\" Input:\n Although this function doesn't have any input, you are required to load\n the MNIST data set from file 'mnist_all.mat'.\n\n Output:\n train_data: matrix of training set. Each row of train_data contains\n feature vector of a image\n train_label: vector of label corresponding to each image in the training\n set\n validation_data: matrix of training set. Each row of validation_data\n contains feature vector of a image\n validation_label: vector of label corresponding to each image in the\n training set\n test_data: matrix of training set. Each row of test_data contains\n feature vector of a image\n test_label: vector of label corresponding to each image in the testing\n set\n\n Some suggestions for preprocessing step:\n - remove features that have the same value for all data points\n - divide the original data set to training, validation and testing set\n with corresponding labels\n - convert original data set from integer to double by using double()\n function\n - normalize the data to [0, 1]\n - feature selection\"\"\"\n\n mat = loadmat('mnist_all.mat') # loads the MAT object as a Dictionary\n train_data = np.concatenate((mat['train0'], mat['train1'],\n mat['train2'], mat['train3'],\n mat['train4'], mat['train5'],\n mat['train6'], mat['train7'],\n mat['train8'], mat['train9']), 0)\n train_label = np.concatenate((np.ones((mat['train0'].shape[0], 1), dtype='uint8'),\n 2 * np.ones((mat['train1'].shape[0], 1), dtype='uint8'),\n 3 * np.ones((mat['train2'].shape[0], 1), dtype='uint8'),\n 4 * np.ones((mat['train3'].shape[0], 1), dtype='uint8'),\n 5 * np.ones((mat['train4'].shape[0], 1), dtype='uint8'),\n 6 * np.ones((mat['train5'].shape[0], 1), dtype='uint8'),\n 7 * np.ones((mat['train6'].shape[0], 1), dtype='uint8'),\n 8 * np.ones((mat['train7'].shape[0], 1), dtype='uint8'),\n 9 * np.ones((mat['train8'].shape[0], 1), dtype='uint8'),\n 10 * np.ones((mat['train9'].shape[0], 1), dtype='uint8')), 0)\n test_label = np.concatenate((np.ones((mat['test0'].shape[0], 1), dtype='uint8'),\n 2 * np.ones((mat['test1'].shape[0], 1), dtype='uint8'),\n 3 * np.ones((mat['test2'].shape[0], 1), dtype='uint8'),\n 4 * np.ones((mat['test3'].shape[0], 1), dtype='uint8'),\n 5 * np.ones((mat['test4'].shape[0], 1), dtype='uint8'),\n 6 * np.ones((mat['test5'].shape[0], 1), dtype='uint8'),\n 7 * np.ones((mat['test6'].shape[0], 1), dtype='uint8'),\n 8 * np.ones((mat['test7'].shape[0], 1), dtype='uint8'),\n 9 * np.ones((mat['test8'].shape[0], 1), dtype='uint8'),\n 10 * np.ones((mat['test9'].shape[0], 1), dtype='uint8')), 0)\n test_data = np.concatenate((mat['test0'], mat['test1'],\n mat['test2'], mat['test3'],\n mat['test4'], mat['test5'],\n mat['test6'], mat['test7'],\n mat['test8'], mat['test9']), 0)\n\n # Pick a reasonable size for validation data\n\n # Your code here\n # Remove all similar features accross all training data and test data\n all_data = np.concatenate((train_data,test_data))\n same_feature = []\n chosen_feature = []\n for feature in range(784):\n # The feature at every data must be the same as the first data\n feature_val = all_data[0][feature]\n removable = True\n for data in all_data:\n if data[feature] != feature_val:\n # This feature is not the same across all data\n removable = False\n break\n if removable:\n same_feature.append(feature)\n else:\n chosen_feature.append(feature)\n train_data = np.delete(train_data,same_feature,1) #np.delete does not occur in place\n test_data = np.delete(test_data,same_feature,1)\n\n print(\"number of unused feature\",len(same_feature))\n print(\"size of training data after feature selection\",train_data.shape)\n\n # Normalizing all data to [0-1]\n train_data.astype(float)\n train_data = train_data /255.0\n test_data.astype(float)\n test_data = test_data/255.0\n print(\"data normalized to [0-1]\")\n\n # Shuffle data up\n permutation = np.random.permutation(train_data.shape[0])\n train_data = train_data[permutation]\n train_label = train_label[permutation]\n print(\"All data shuffled randomly\")\n\n # Set validation set\n validation_size = 10000\n validation_data = train_data[0:validation_size,:]\n validation_label = train_label[0:validation_size]\n train_data = np.delete(train_data,[index for index in range(0,validation_size)],0)\n train_label = np.delete(train_label,[index for index in range(0,validation_size)],0)\n print(\"Validation set\",validation_data.shape)\n print(\"Trainning set\",train_data.shape)\n\n # Done\n print(\"preprocess done!\")\n\n return train_data, train_label, validation_data, validation_label, test_data, test_label, chosen_feature\n\n\ndef nnObjFunction(params, *args):\n \"\"\"% nnObjFunction computes the value of objective function (negative log\n % likelihood error function with regularization) given the parameters\n % of Neural Networks, thetraining data, their corresponding training\n % labels and lambda - regularization hyper-parameter.\n\n % Input:\n % params: vector of weights of 2 matrices w1 (weights of connections from\n % input layer to hidden layer) and w2 (weights of connections from\n % hidden layer to output layer) where all of the weights are contained\n % in a single vector.\n % n_input: number of node in input layer (not include the bias node)\n % n_hidden: number of node in hidden layer (not include the bias node)\n % n_class: number of node in output layer (number of classes in\n % classification problem\n % training_data: matrix of training data. Each row of this matrix\n % represents the feature vector of a particular image\n % training_label: the vector of truth label of training images. Each entry\n % in the vector represents the truth label of its corresponding image.\n % lambda: regularization hyper-parameter. This value is used for fixing the\n % overfitting problem.\n\n % Output:\n % obj_val: a scalar value representing value of error function\n % obj_grad: a SINGLE vector of gradient value of error function\n % NOTE: how to compute obj_grad\n % Use backpropagation algorithm to compute the gradient of error function\n % for each weights in weight matrices.\n\n %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n % reshape 'params' vector into 2 matrices of weight w1 and w2\n % w1: matrix of weights of connections from input layer to hidden layers.\n % w1(i, j) represents the weight of connection from unit j in input\n % layer to unit i in hidden layer.\n % w2: matrix of weights of connections from hidden layer to output layers.\n % w2(i, j) represents the weight of connection from unit j in hidden\n % layer to unit i in output layer.\"\"\"\n\n n_input, n_hidden, n_class, training_data, training_label, lambdaval = args\n\n w1 = params[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1)))\n w2 = params[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))\n\n # Your code here\n # Need to calculate delta_l first, as it is used for both the output and hidden gradiant\n # The gradient is calculated as the sum of error over the entire dataset.\n # Batch gradient descent\n\n # Calculate the obj_val\n # Doing the feed forward\n data = np.append(training_data,np.ones(shape=(training_data.shape[0],1)),axis = 1)\n hidden = sigmoid(np.matmul(data,w1.transpose()))\n hidden = np.append(hidden, np.ones(shape=(hidden.shape[0], 1)), axis=1)\n output = sigmoid(np.matmul(hidden,w2.transpose()))\n\n # Done with the feed forward\n # Need to make it into one-hot version\n label = np.zeros(shape=(training_label.shape[0],n_class))\n for i in range(training_label.shape[0]):\n label[i,training_label[i]-1] = 1\n # Made the one-hot version\n # The object function\n obj_val = -1/(1.0*training_data.shape[0])*np.sum(np.multiply(label,np.log(output)) +\n np.multiply((1-label),np.log(1-output)))+\\\n lambdaval/(2.0*training_data.shape[0])*(np.sum(np.power(w1,2))+np.sum(np.power(w2,2)))\n\n # # Calculate delta_l\n delta_l = np.subtract(output,label)\n # grad_2\n grad_w2 = 1/(training_data.shape[0])*(np.matmul(delta_l.transpose(),hidden)+ lambdaval*w2)\n\n scalar_sum = np.matmul(delta_l, w2[:,0:n_hidden])\n z_sum = np.multiply(1-hidden[:,0:n_hidden],hidden[:,0:n_hidden])\n z_sum = np.multiply(z_sum,scalar_sum)\n grad_w1 = (1/training_data.shape[0])* (np.matmul(z_sum.transpose(),data) + lambdaval*w1)\n # Make sure you reshape the gradient matrices to a 1D array. for instance if your gradient matrices are grad_w1 and grad_w2\n # you would use code similar to the one below to create a flat array\n obj_grad = np.concatenate((grad_w1.flatten(), grad_w2.flatten()),0)\n return (obj_val, obj_grad)\n\n\n\ndef nnPredict(w1, w2, data):\n \"\"\"% nnPredict predicts the label of data given the parameter w1, w2 of Neural\n % Network.\n\n % Input:\n % w1: matrix of weights of connections from input layer to hidden layers.\n % w1(i, j) represents the weight of connection from unit i in input \n % layer to unit j in hidden layer.\n % w2: matrix of weights of connections from hidden layer to output layers.\n % w2(i, j) represents the weight of connection from unit i in input \n % layer to unit j in hidden layer.\n % data: matrix of data. Each row of this matrix represents the feature \n % vector of a particular image\n \n % Output: \n % label: a column vector of predicted labels\"\"\"\n # Data is suppose to be (number_of_data,picture_size), so we need to add a bias term\n data = np.append(data, np.ones(shape=(data.shape[0], 1)), axis=1)\n hidden = sigmoid(np.matmul(data, w1.transpose()))\n hidden = np.append(hidden, np.ones(shape=(hidden.shape[0], 1)), axis=1)\n output = sigmoid(np.matmul(hidden, w2.transpose()))\n # Now the output is (_number_of_data,10 ) with 10 as in number of class\n # np.argmax return the labels from 0-9, need to add 1 in\n labels = np.argmax(output, axis=1)+1\n\n\n # Your code here\n return labels.reshape((labels.shape[0],1))\n\n\n\"\"\"**************Neural Network Script Starts here********************************\"\"\"\nif __name__ == \"__main__\":\n start_time = time.time()\n\n train_data, train_label, validation_data, validation_label, test_data, test_label, chosen_feature = preprocess()\n\n # Train Neural Network\n\n # set the number of nodes in input unit (not including bias unit)\n n_input = train_data.shape[1]\n\n # set the number of nodes in hidden unit (not including bias unit)\n n_hidden = 50\n\n # set the number of nodes in output unit\n n_class = 10\n\n # initialize the weights into some random matrices\n initial_w1 = initializeWeights(n_input, n_hidden)\n initial_w2 = initializeWeights(n_hidden, n_class)\n\n # unroll 2 weight matrices into single column vector\n initialWeights = np.concatenate((initial_w1.flatten(), initial_w2.flatten()), 0)\n\n # set the regularization hyper-parameter\n lambdaval = 0\n\n args = (n_input, n_hidden, n_class, train_data, train_label, lambdaval)\n\n # Train Neural Network using fmin_cg or minimize from scipy,optimize module. Check documentation for a working example\n\n opts = {'maxiter': 50} # Preferred value.\n\n nn_params = minimize(nnObjFunction, initialWeights, jac=True, args=args, method='CG', options=opts)\n\n # In Case you want to use fmin_cg, you may have to split the nnObjectFunction to two functions nnObjFunctionVal\n # and nnObjGradient. Check documentation for this function before you proceed.\n # nn_params, cost = fmin_cg(nnObjFunctionVal, initialWeights, nnObjGradient,args = args, maxiter = 50)\n\n\n # Reshape nnParams from 1D vector into w1 and w2 matrices\n w1 = nn_params.x[0:n_hidden * (n_input + 1)].reshape((n_hidden, (n_input + 1)))\n w2 = nn_params.x[(n_hidden * (n_input + 1)):].reshape((n_class, (n_hidden + 1)))\n print(w1.shape,w2.shape)\n print(\"Done training\")\n # Test the computed parameters\n\n predicted_label = nnPredict(w1, w2, train_data)\n\n # find the accuracy on Training Dataset\n\n print('\\n Training set Accuracy:' + str(100 * np.mean((predicted_label == train_label).astype(float))) + '%')\n\n predicted_label = nnPredict(w1, w2, validation_data)\n\n # find the accuracy on Validation Dataset\n\n print('\\n Validation set Accuracy:' + str(100 * np.mean((predicted_label == validation_label).astype(float))) + '%')\n\n predicted_label = nnPredict(w1, w2, test_data)\n\n # find the accuracy on Validation Dataset\n\n print('\\n Test set Accuracy:' + str(100 * np.mean((predicted_label == test_label).astype(float))) + '%')\n\n end_time = time.time()\n print(\"Time\", end_time-start_time)","sub_path":"code/nnScript.py","file_name":"nnScript.py","file_ext":"py","file_size_in_byte":14608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"92922319","text":"# -*- encoding:utf-8 -*-\nfrom flask import render_template, request, redirect, url_for, Response, current_app\nfrom . import bpapp\n#from runme import app\n#import runme\nfrom werkzeug.utils import secure_filename\nimport os\nfrom . import typesystem_parser\nfrom . import models\nfrom erks.utils.log_exception import log_exception\nfrom bson.json_util import dumps\n\n\n@bpapp.route('//typesystemlist', methods=['GET', 'POST'])\ndef list_typesystem(project_id):\n\n return render_template('typesystem.html.tmpl', project_id=project_id, active_menu=\"typeSystem\")\n\n\n@bpapp.route('//import', methods=['GET', 'POST'])\ndef import_typesystem(project_id):\n if request.method == 'POST':\n file = request.files['file']\n filename = secure_filename(file.filename)\n filepath = current_app.config['UPLOAD_DIR']\n file.save(os.path.join(current_app.config['UPLOAD_DIR'], filename))\n parser = typesystem_parser.TypesystemParser(filename=filename, filepath=filepath, project_id=project_id)\n parser.wks_json_parser()\n return redirect(url_for('typesystem.list_typesystem', project_id=project_id))\n\n@bpapp.route('//getEntityTypeList', methods=['POST', 'GET'])\ndef get_entity_type_list(project_id='asdf'):\n result = {}\n entity_type_list = None\n\n try:\n #project_id = str(request.json['project_id'])\n result = {}\n entity_type_list = models.get_entity_type_list(project_id)\n result[\"resultOK\"] = True\n result[\"list\"] = entity_type_list\n\n except Exception as e:\n result[\"resultOK\"] = False\n result[\"message\"] = str(Exception)\n log_exception(e)\n\n return dumps(result, ensure_ascii=False)\n\n\n@bpapp.route('//getRelationshipTypeList', methods=['POST', 'GET'])\ndef get_relationship_type_list(project_id):\n result = {}\n relationship_type_list = None\n\n try:\n result = {}\n relationship_type_list = models.get_relationship_type_list(project_id)\n result[\"resultOK\"] = True\n result[\"list\"] = relationship_type_list\n\n except Exception as e:\n result[\"resultOK\"] = False\n result[\"message\"] = str(Exception)\n log_exception(e)\n\n return dumps(result, ensure_ascii=False)\n\n\n@bpapp.route('//getTypeSystemDiagram', methods=['POST', 'GET'])\ndef get_type_system_diagram(project_id):\n result = {}\n try:\n type_system_diagram = models.get_type_system_diagram(project_id)\n result[\"resultOK\"] = True\n result[\"result\"] = type_system_diagram\n except Exception as e:\n result[\"resultOK\"] = False\n result[\"message\"] = str(Exception)\n log_exception(e)\n\n return dumps(result, ensure_ascii=False)\n\n\n@bpapp.route('//saveAll', methods=['POST', 'GET'])\ndef save_all_typesystem(project_id):\n result = {}\n\n try:\n type_system_diagram = request.json['typeSystemDiagram']\n entity_types = request.json['entityTypes']\n relation_types = request.json['relationTypes']\n save_result = models.save_all_typesystem(project_id=project_id, type_system_diagram=type_system_diagram, entity_types=entity_types, relation_types=relation_types)\n result[\"resultOK\"] = True\n result[\"result\"] = save_result\n\n except Exception as e:\n result[\"resultOK\"] = False\n result[\"message\"] = str(Exception)\n log_exception(e)\n\n return dumps(result, ensure_ascii=False)\n\n\n@bpapp.route('//entityTypeDtl', methods=['POST', 'GET'])\ndef entity_type_detail(project_id):\n return render_template('entity_type_dtl.html.tmpl')\n\n\n@bpapp.route('//relationTypeDtl', methods=['POST', 'GET'])\ndef relation_type_detail(project_id):\n return render_template('relation_type_dtl.html.tmpl')\n\n\n@bpapp.route('//export', methods=['GET', 'POST'])\ndef export_typesystem(project_id):\n results = dumps(models.get_typesystem(project_id), ensure_ascii=False)\n generator = (cell for row in results for cell in row)\n return Response(generator,\n mimetype=\"text/plain\",\n headers={\"Content-Disposition\":\n \"attachment;filename=typesystem.json\"})","sub_path":"erks/erks_bps/typesystem/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"112676824","text":"# -*- encoding: utf-8 -*-\n'''\n@File :inference.py\n@Time :2021/04/17 10:26:12\n@Author :xiaoqifeng\n@Version :1.0\n@Contact: :unknown\n'''\n\nimport os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0'\nimport json\nfrom ai_hub import inferServer\nimport torch\nfrom pytorch_pretrained_bert import BertTokenizer\nfrom BERTForMultiClassification_v1 import BERTForMultiLabelSequenceClassification\nfrom config_v1 import Config\nfrom DataLoader_v1 import TextProcessor, convert_examples_to_features, convert_single_example\nfrom onnxruntime import GraphOptimizationLevel, InferenceSession, SessionOptions\n\n\nclass AIHubInfer(inferServer):\n def __init__(self, model1, model2):\n self.model2 = model2\n super().__init__(model1)\n\n #数据前处理\n def pre_process(self, req_data):\n input_batch = {}\n input_batch[\"input\"] = req_data.form.getlist(\"input\")\n input_batch[\"index\"] = req_data.form.getlist(\"index\")\n\n return input_batch\n \n # #数据后处理,如无,可空缺\n def post_process(self, predict_data):\n response = json.dumps(predict_data)\n return response\n\n #如需自定义,可覆盖重写\n def predict(self, preprocessed_data):\n input_list = preprocessed_data[\"input\"]\n index_list = preprocessed_data[\"index\"]\n \n response_batch = {}\n response_batch[\"results\"] = []\n for i in range(len(index_list)):\n index_str = index_list[i]\n \n response = {}\n try:\n input_sample = input_list[i].strip()\n elems = input_sample.strip().split(\"\\t\")\n query_A = elems[0].strip()\n query_B = elems[1].strip()\n # predict = infer(model, query_A, query_B)\n predict = infer(self.model, self.model2, query_A, query_B)\n response[\"predict\"] = predict\n response[\"index\"] = index_str\n response[\"ok\"] = True\n except Exception as e:\n response[\"predict\"] = 0\n response[\"index\"] = index_str\n response[\"ok\"] = False\n response_batch[\"results\"].append(response)\n \n return response_batch\n\n\nmax_seq_len = 32\nconfig = Config('data')\ntokenizer = BertTokenizer.from_pretrained('./vocab')\nprocessor = TextProcessor()\n\n\ndef to_numpy(tensor):\n return tensor.detach().cpu().numpy() if tensor.requires_grad else tensor.cpu().numpy()\n\n\n# 需要根据模型类型重写\ndef infer(bert, nezha, query_A, query_B):\n\n text_a, text_b = query_A, query_B\n example = processor._create_single_example(text_a, text_b)\n feature = convert_single_example(example, max_seq_len, tokenizer)\n\n input_ids = torch.tensor(feature.input_ids, dtype=torch.long).unsqueeze(0)\n segment_ids = torch.tensor(feature.segment_ids, dtype=torch.long).unsqueeze(0)\n input_mask = torch.tensor(feature.input_mask, dtype=torch.long).unsqueeze(0)\n\n ort_inputs = {\n 'input_ids': to_numpy(input_ids),\n 'segment_ids': to_numpy(segment_ids),\n 'input_mask': to_numpy(input_mask)\n }\n ort_outputs_bert = bert.run(None, ort_inputs)\n ort_outputs_nezha = nezha.run(None, ort_inputs)\n ort_logits_bert = torch.from_numpy(ort_outputs_bert[0])\n ort_logits_nezha = torch.from_numpy(ort_outputs_nezha[0])\n\n res = torch.mean(torch.stack([ort_logits_bert, ort_logits_nezha]), 0)\n prob = res.sigmoid()[:, 1].tolist()[0]\n\n return prob\n\n\n# 需要根据模型类型重写\ndef init_model(model_path_bert, model_path_nezha):\n session_bert = InferenceSession(model_path_bert)\n session_nezha = InferenceSession(model_path_nezha)\n\n return session_bert, session_nezha\n\nif __name__ == \"__main__\":\n # import time\n # start = time.time()\n # model_path_bert = './model/bert_base_all_gpu.onnx'\n model_path_bert = './model/bert_base_fgm_all_gpu.onnx'\n # model_path_nezha = './model/bert_nezha_all_gpu.onnx' # 第一个版本的bert\n model_path_nezha = './model/bert_nezha_all_fgm_gpu.onnx' # 第一个版本的nezha\n # model_path_nezha = './model/bert_nezha_150_fgm_all_gpu.onnx' # 这个效果不怎么好\n bert, nezha = init_model(model_path_bert, model_path_nezha)\n # record = [['12 2954 16', '12 32 126 5951 456 16'] for _ in range(50000)]\n # cnt = 0\n # for text_a, text_b in record:\n # res = infer(bert, nezha, text_a, text_b)\n # print(f'第{cnt+1}条记录...')\n # cnt += 1\n # print(res)\n # print(f'耗时:{(time.time()-start)/60}分钟...')\n aihub_infer = AIHubInfer(bert, nezha)\n aihub_infer.run(debuge=False)\n\n # docker build -t registry.cn-shanghai.aliyuncs.com/xiaoqifeng/gaiic_track3:3.0 .","sub_path":"gaiic_track_submit/inference_onnx_merge.py","file_name":"inference_onnx_merge.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"31882","text":"\"\"\"Algoritmo da mochila fracionária, onde a partir de uma tabela de itens,\né acrescentado a mochila os produtos com maior preço por peso buscando \nassim, obter o maior valor possível de roubo, sempre respeitando a capacidade\nde armazenamento da mochila\n\"\"\"\n\n\nimport pandas as pd\nimport os\n\n\ndef mostrar_itens():\n \"\"\"Imprime tabela de informações dos itens.\"\"\"\n print(\"-\"*28)\n print(\"{:>14}\" .format('ITENS'))\n print(\"-\"*28)\n estoque = pd.DataFrame(data=itens)\n print(estoque)\n print(\"-\"*28)\n\n\ndef mochila_fracionaria(itens, peso_mochila):\n \"\"\"A função executa o algoritmo da mochila fracionária.\n\n A função busca o item de maior valor por peso e acrescenta a mochila,\n se necessário os itens podem ser fracionados até que a mochila comporte\n seu peso total permitido.\n\n param: dict com informações dos itens e o peso que a mochila comporta.\n return: list com quantidade roubada de cada item.\n \"\"\"\n peso_atual = 0\n # List com quantidade de cada item roubado\n roubado = [0 for i in itens['item']]\n beneficio = list(map(lambda valor, peso: valor/peso,\n itens[\"valor\"], itens[\"peso\"]))\n\n # Busca o produto de maior valor por peso e o acrescenta a mochila\n # Caso o item não possa ser subtraído por inteiro, este é acresentado de forma fracionada\n while peso_atual < peso_mochila:\n i = beneficio.index(max(beneficio))\n beneficio[i] = 0\n roubado[i] = min(itens[\"peso\"][i], peso_mochila - peso_atual)\n peso_atual += roubado[i]\n\n return roubado\n\n\ndef mostra_roubo(itens, roubado):\n \"\"\"Imprime os itens e que foram roubados e respectivas informações.\n\n param: dict com informações dos itens e list da quantidade de itens roubados.\n \"\"\"\n valor_ganho = 0\n\n os.system(\"cls\")\n print(\"-\"*22)\n print(\"{:>18}\" .format('ITENS ROUBADOS'))\n print(\"-\"*22)\n for i in range(len(roubado)):\n if roubado[i] != 0:\n print(f'Item roubado: {itens[\"item\"][i]}')\n print(f'Quantidade: {roubado[i]}(kg/ml)')\n print(\n f'Valor subtraído: {(itens[\"valor\"][i]/itens[\"peso\"][i])*roubado[i]:.02f}')\n valor_ganho += (itens[\"valor\"][i]/itens[\"peso\"][i])*roubado[i]\n print(\"-\"*22)\n print(f\"Total subtraído: {valor_ganho:.02f}\")\n print(\"-\"*22)\n\n\nitens = {\n \"item\": ['arroz', 'feijão', 'carne', 'óleo', 'café', \n 'macarrão', 'refrigerante', 'leite', 'sal', 'açucar'],\n \"valor\": [25.00, 6.00, 30.00, 7.00, 8.00, 3.00, 5.00, 3.00, 2.00, 2.00],\n \"peso\": [5, 1, 1, 1, 1, 1, 1, 1, 1, 1]\n}\n\nwhile True:\n mostrar_itens()\n peso_mochila = int(input(\"Qual o peso que a mochila suporta?(kg): \"))\n roubado = mochila_fracionaria(itens, peso_mochila)\n mostra_roubo(itens, roubado)\n\n novo = str(input(\"Fazer de novo?(s/n): \"))\n if novo == 's':\n os.system(\"cls\")\n continue\n else:\n break\n","sub_path":"mochila_fracionaria.py","file_name":"mochila_fracionaria.py","file_ext":"py","file_size_in_byte":2946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"598429470","text":"'''\nwrite emails to a new csv file\n'''\nimport string\nimport pandas as pd\n\nwith open('faculty.csv', 'rb') as f:\n reader = csv.reader(f)\n facultylist = list(reader) \nemails = [y[3] for y in facultylist]\ndf3 = pd.DataFrame(emails)\nheader = [\"email\"]\ndf3.to_csv('output.csv', cols = header, index = False)\n","sub_path":"python/advanced_python_csv.py","file_name":"advanced_python_csv.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"175418119","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Download registry information from the OBO Foundry.\"\"\"\n\nimport json\nimport os\nfrom operator import itemgetter\nfrom typing import Optional\n\nimport click\nimport pandas as pd\nimport yaml\n\nfrom .utils import list_to_map\nfrom ..constants import BIOREGISTRY_MODULE\n\n__all__ = [\n 'OBOFOUNDRY_FULL_PATH',\n 'OBOFOUNDRY_URL',\n 'get_obofoundry',\n 'get_obofoundry_df',\n]\n\nOBOFOUNDRY_YAML_PATH = BIOREGISTRY_MODULE.join(name='obofoundry.yml')\nOBOFOUNDRY_FULL_PATH = BIOREGISTRY_MODULE.join(name='obofoundry.json')\nOBOFOUNDRY_SLIM_PATH = BIOREGISTRY_MODULE.join(name='obofoundry.tsv')\nOBOFOUNDRY_URL = 'https://raw.githubusercontent.com/OBOFoundry/OBOFoundry.github.io/master/registry/ontologies.yml'\n\n\ndef get_obofoundry(\n cache_path: Optional[str] = OBOFOUNDRY_FULL_PATH,\n mappify: bool = False,\n force_download: bool = False,\n skip_deprecated: bool = False,\n):\n \"\"\"Get the OBO Foundry registry.\"\"\"\n if not force_download and cache_path is not None and os.path.exists(cache_path):\n with open(cache_path) as file:\n entries = json.load(file)\n else:\n with BIOREGISTRY_MODULE.ensure(url=OBOFOUNDRY_URL).open() as file:\n entries = yaml.full_load(file)['ontologies']\n\n for entry in entries:\n for key in ('browsers', 'usages', 'depicted_by', 'products'):\n if key in entry:\n del entry[key]\n\n # maintain sorted OBO Foundry\n entries = sorted(entries, key=itemgetter('id'))\n\n if cache_path is not None:\n with open(cache_path, 'w') as file:\n json.dump(entries, file, indent=2)\n\n if skip_deprecated:\n entries = [\n entry\n for entry in entries\n if not entry.get('is_obsolete', False)\n ]\n\n if mappify:\n entries = list_to_map(entries, 'id')\n\n return entries\n\n\ndef get_obofoundry_df(**kwargs):\n \"\"\"Get the OBO Foundry registry as a pre-processed dataframe.\"\"\"\n rows = [\n (\n 'obofoundry',\n entry['id'],\n entry['title'],\n entry.get('is_obsolete', False),\n entry.get('license', {}).get('label'),\n entry.get('description'),\n )\n for entry in get_obofoundry(**kwargs)\n ]\n df = pd.DataFrame(rows, columns=[\n 'registry', 'prefix', 'name',\n 'redundant', 'license', 'description',\n ])\n df.to_csv(OBOFOUNDRY_SLIM_PATH, sep='\\t', index=False)\n return df\n\n\n@click.command()\ndef main():\n \"\"\"Reload the OBO Foundry data.\"\"\"\n get_obofoundry_df(force_download=True)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/bioregistry/external/obofoundry.py","file_name":"obofoundry.py","file_ext":"py","file_size_in_byte":2646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"611030485","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom datetime import datetime\n\nfrom sqlalchemy import (Column, Integer, Sequence,\n String, DateTime, UnicodeText)\nfrom sqlalchemy.ext.declarative import declarative_base\n\nBase = declarative_base()\n\n\nclass Wish(Base):\n __tablename__ = 'wishes'\n id = Column(Integer, Sequence('id_seq'), primary_key=True)\n created = Column(DateTime(timezone=True), default=datetime.utcnow)\n text = Column(UnicodeText)\n external_user_id = Column(String(255))\n\n def __repr__(self):\n return ''.format(self.id)\n","sub_path":"src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"488963932","text":"import os, subprocess\r\n\r\ntest_files_path = 'test_files'\r\nsucceded_files_dir = os.path.join(test_files_path, 'succeded')\r\ntest_files = filter(lambda f : os.path.isfile(os.path.join(test_files_path, f)), os.listdir(test_files_path))\r\n\r\nif not os.path.isdir(succeded_files_dir ):\r\n os.mkdir(succeded_files_dir)\r\n\r\ncommand = './parsefile'\r\nsucceded_tests = []\r\n\r\nfor jsonfile in test_files:\r\n expected_return = 2\r\n if jsonfile[0]=='y':\r\n expected_return = 0\r\n elif jsonfile[0]=='n':\r\n expected_return = 1\r\n\r\n\r\n print('Testing \\''+jsonfile+'\\' ...', end=' ')\r\n argument = os.path.join(test_files_path, jsonfile)\r\n process = subprocess.Popen([command, argument], stdout=subprocess.PIPE)\r\n while True:\r\n output = process.stdout.readlines()\r\n return_code = process.poll()\r\n if return_code is not None:\r\n if return_code == expected_return or expected_return == 2:\r\n print('\\t[OK]')\r\n succeded_tests.append(jsonfile)\r\n else:\r\n print('\\t[FAIL]')\r\n #failed_tests.append(jsonfile)\r\n break\r\n\r\nfor succ_file in succeded_tests:\r\n from_dir = os.path.join(test_files_path, succ_file)\r\n to_dir = os.path.join(succeded_files_dir, succ_file)\r\n os.rename(from_dir, to_dir)","sub_path":"src_single_file/testing/run_tests_linux.py","file_name":"run_tests_linux.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"606764047","text":"def binary_gap(n):\r\n string = bin(n).replace('0b', '')\r\n print(string)\r\n hmap = {}\r\n max_length = 0\r\n for i in range(len(string)):\r\n if string[i] == '1':\r\n hmap[i] = string[i]\r\n print(hmap)\r\n\r\n keys = list(hmap.keys())\r\n for i in range(1, len(keys)):\r\n max_length = max(max_length, keys[i]-keys[i-1])\r\n\r\n return max_length\r\n\r\n\r\nresult = binary_gap(1041)\r\nprint(result)","sub_path":"Array/binary_gap.py","file_name":"binary_gap.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"272981217","text":"from urllib.request import urlopen, Request\n\nimport re\nimport time\nimport threading\nimport socket\nimport urllib\nimport random\nimport logging\n\ndef get_proxy_list():\n header = {#\"Host\": \"www.xicidaili.com\",\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36\",\n \"Connection\": \"keep-alive\",\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\n \"Accept-Ancoding\": \"gzip, deflate\",\n \"Accept-Aanguage\": \"zh-CN,zh;q=0.9\"\n }\n ip_l = []\n proxy_l = []\n opener = urllib.request.build_opener()\n urllib.request.install_opener(opener)\n #for page in random.sample(range (1, 6), 5):\n for page in range (1, 3):\n logging.debug(\"get IP from page %d\" % (page))\n #req = Request(\"http://www.xicidaili.com/wt/%d\" % (page), headers = header)\n req = Request(\"http://www.89ip.cn/index_%d.html\" % (page), headers = header)\n try:\n lines = urlopen(req, timeout=10).read().decode('utf-8')\n pattern=re.compile(r'(\\d.*?\\d)')\n ip_page=re.findall(pattern,str(\"\".join(lines.split())))\n ip_l.extend(ip_page)\n except:\n pass\n time.sleep(3)\n\n for i in range(0,len(ip_l),3):\n proxy_host = ip_l[i]+':'+ip_l[i+1]\n proxy_temp = {\"http\":proxy_host}\n proxy_l.append(proxy_temp)\n # print (proxy_l)\n logging.debug(\"collected IP count \\n%d\" % (len(proxy_l)))\n return proxy_l\n\ndef mp_thread_test(proxys):\n proxy_ip=[]\n lock=threading.Lock()\n\n def test(proxy):\n socket.setdefaulttimeout(20)\n urls = [\"http://web.ifzq.gtimg.cn\", \"http://market.finance.sina.com.cn/downxls.php?\"]\n try:\n proxy_support = urllib.request.ProxyHandler(proxy)\n opener = urllib.request.build_opener(proxy_support)\n opener.addheaders=[(\"User-Agent\",\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36\",)]\n urllib.request.install_opener(opener)\n for url in urls:\n lines = urlopen(url).read().decode('GBK')\n\n if lines == \"Param date cannot be empty!\":\n lock.acquire()\n # print(proxy, lines)\n proxy_ip.append(proxy)\n lock.release()\n except Exception as e:\n pass\n\n threads=[]\n for ip in proxys:\n thread=threading.Thread(target=test,args=[ip])\n threads.append(thread)\n thread.start()\n\n for thread in threads:\n thread.join()\n logging.debug(\"Proxy list passed the test \\n%s\" % (proxy_ip))\n return proxy_ip\n\ndef get_proxy():\n while True:\n pl = get_proxy_list()\n proxy_list = mp_thread_test(pl)\n if proxy_list:\n break\n time.sleep(20)\n return proxy_list\n\nif __name__ == '__main__':\n log_file = \"proxy_test.log\"\n console_logger = logging.FileHandler(filename = log_file, mode = 'a', encoding=\"utf-8\", delay=True)\n logging.getLogger().setLevel(logging.DEBUG)\n console_logger.setLevel(logging.NOTSET)\n console_logger.setFormatter(logging.Formatter(\"%(message)s\"))\n logging.getLogger().addHandler(console_logger)\n get_proxy()","sub_path":"IpPool/ip.py","file_name":"ip.py","file_ext":"py","file_size_in_byte":3350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"442076298","text":"from django.conf.urls import url\n\nfrom shortner.views import shortner_view\n\nurlpatterns = [\n\n # tracker\n url(r'^/?$', shortner_view.url_list_controller, name='url_list_controller'),\n\n url(r'^create/$', shortner_view.url_create_controller, name='url_create_controller'),\n\n url(r'^(?P\\w+)/info/$', shortner_view.url_detail_controller, name='url_detail_controller'),\n\n url(r'^(?P\\w+)/info/downdaily/$', shortner_view.daily_source_download, name='daily_source_download'),\n\n url(r'^download/$', shortner_view.url_list_download, name=\"url_list_download\"),\n\n]","sub_path":"shortner/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"314285178","text":"import json\r\nimport os\r\n\r\n\r\ndef topic_definer(folder, topics, list_of_topics):\r\n freq = {}\r\n for file in os.listdir(folder):\r\n title = file[:-9]\r\n with open(os.path.join(folder, file), 'r', encoding = 'utf-8') as f:\r\n text = f.read()\r\n words = text.split()\r\n for word in words:\r\n for topic in list_of_topics:\r\n if word in topics[topic]:\r\n line = title + ' : ' + topic + ' --> ' + word + ' '\r\n with open('topics_words.txt', 'a', encoding = 'utf-8') as f3:\r\n f3.write(line)\r\n if title in freq.keys():\r\n if topic in freq.keys():\r\n freq[title][topic] += 1\r\n else:\r\n freq[title][topic] = 1\r\n else:\r\n freq = {title : {topic : 1}}\r\n \r\n \r\n with open('json_topics_words.json', 'a', encoding = 'utf-8') as f2:\r\n json.dump(freq, f2, ensure_ascii = False)\r\n \r\n \r\n\r\ndef main():\r\n folder = 'mallet'\r\n list_of_topics = ['god_work_love', 'writing_action', 'friends', 'affair', 'lifestyle']\r\n topics = {\r\n 'god_work_love' :\r\n {\r\n 'good', 'make', 'love', 'time', 'great', 'back', 'life', 'god', 'thing', 'lot',\r\n 'thought', 'work', 'hey', 'give', 'wanna', 'call', 'told', 'book', 'man', 'put'\r\n },\r\n 'writing_action' :\r\n {\r\n 'wait', 'rain', 'mind', 'writing', 'pretty', 'care', 'marry', 'script', 'kind', 'london', 'telling',\r\n 'love', 'itwas', 'bank', 'carol', 'finally', 'fella', 'napoleon', 'played', 'beautiful'\r\n },\r\n 'friends' :\r\n {\r\n 'opera', 'place', \"l'll\", \"l'm\", 'part', 'face', 'future', 'friends', 'mine', 'honour', 'dia',\r\n 'c.w', 'guitar', 'anymore', 'willie', 'idea', 'foundation', 'figure', 'wheat', 'killer'\r\n },\r\n 'affair' :\r\n {\r\n 'darling', 'understand', 'lunch', 'wine', 'doctor', 'man', 'melody', 'famous', 'past', 'affair',\r\n 'house', 'played', 'park', 'making', 'yeager', 'milos', 'blind', 'mom', 'boyfriend'\r\n },\r\n 'lifestyle' :\r\n {\r\n 'feel', 'chinese', 'day', 'matter', 'story', 'picture', 'open', 'card', 'white', 'doctor',\r\n 'ago', 'wanna', 'good', 'hell', 'dough', 'prison', 'dub', 'restaurant', 'fantastic', 'paper'\r\n }\r\n }\r\n topic_definer(folder, topics, list_of_topics)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"Deconstructing Woody Allen/rating_per_topics_maker.py","file_name":"rating_per_topics_maker.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"327112834","text":"\"\"\"\nThis module is responsible for handling which figures are current (will receive next plot operation) and which are\nkept (will not be modified until it is made current once again).\n\nThe FigureManager in its responsibilities highly resembles the class maptplotlib._pylab_helpers.Gcf, However it\nadds the functionality of having multiple 'categories' with each category having it own current window.\nThis is achieved through use of the supplied decorator 'activate_category' This decorator accepts one parameter (a\nstring ) specifying which category a function belongs two. For instance to apply the decorator\nactivate_category('') to the the function pyplot.pcolor would signal that the function pcolor would only apply\nto plots of the category ''. All of this is done through manipulating the return value of `pyplot.gcf`. gcf\nin pyplot returns FigureManager.get_active_figure()\n\nIf gcf is called from inside a categorized (decorated) function then it will return the current figure for that\nfunctions category. If there is no current figure for that category then it will create a new figure and return it.\n\nIf a new figure is created in a call of gcf that is categorized then the new figure will automatically be assigned\nto the category. And it will be set as the current figure for that category.\n\nIf gcf is called from inside an uncategorized function then it should return the `active figure` which is defined as\nthe last plot window to receive any plotting command (regardless of category). This makes sense for functions which\ncan apply to any plots such as `xlabel`.\n\nIf a new figure is created by an uncategorized function then will be 'uncategorized'. If the current 'active figure'\nis an uncategorized figure and categorized function is called then it should be returned and then that figure should\nbe added to the category of the command\n\nCurrently there are only two categories ('1d' and '2d') hard coded into the manager.\n\"\"\"\nfrom __future__ import (absolute_import, division, print_function)\n# system imports\nfrom functools import wraps\n\n# local imports\nfrom mslice.util.qt.qapp import QAppThreadCall\n\n# Labels for each category\nCATEGORY_CUT, CATEGORY_SLICE = \"1d\", \"2d\"\n\n\nclass GlobalFigureManager(object):\n \"\"\"Static class to manage a set of numbered figures.\n\n It is never instantiated. It consists of attributes to\n manage a set of \"current\" figures along with keeping\n track of all created figures. Each current figure is expected\n to be placed into a category such that a current figure for\n a given category can be returned to be operated on separately\n to the current figure for another category.\n \"\"\"\n # if there is a current figure it should be both current and active\n _active_category = None\n _category_current_figures = {CATEGORY_CUT: None, CATEGORY_SLICE: None} # Current_figures receive decorated commands\n _figures_by_category = {CATEGORY_CUT: [], CATEGORY_SLICE: []}\n _unclassified_figures = []\n _active_figure = None\n _last_active_figure = None\n _figures = {}\n\n @classmethod\n def destroy(cls, num):\n \"\"\"\n Try to remove all traces of figure *num*.\n\n In the interactive backends, this is bound to the\n window \"destroy\" and \"delete\" events.\n \"\"\"\n if not cls.has_fignum(num):\n return\n category = cls.get_category(num)\n if cls._active_figure == num:\n cls._active_figure = None\n if cls._category_current_figures[category] == num:\n cls._category_current_figures[category] = None\n cls._figures_by_category[category].remove(num)\n del cls._figures[num]\n\n @classmethod\n def get_figure_by_number(cls, num):\n \"\"\"\n Returns the figure with figure number num\n :param num: The assigned figure number\n :return: The figure with figure number num\n \"\"\"\n if cls.has_fignum(num):\n return cls._figures[num]\n else:\n return None\n\n @classmethod\n def destroy_fig(cls, fig):\n \"\"\"*fig* is a Figure instance\"\"\"\n num = next((manager.num for manager in cls._figures.values()\n if manager.canvas.figure == fig), None)\n if num is not None:\n cls.destroy(num)\n\n @classmethod\n def destroy_all(cls):\n # this is need to ensure that gc is available in corner cases\n # where modules are being torn down after install with easy_install\n import gc # noqa\n for manager in list(cls._figures.values()):\n manager.destroy()\n cls._active_figure = None\n cls._category_current_figures = {CATEGORY_CUT: None, CATEGORY_SLICE: None}\n cls._figures.clear()\n\n @classmethod\n def has_fignum(cls, num):\n \"\"\"\n Return *True* if figure *num* exists.\n \"\"\"\n return num in cls._figures\n\n @classmethod\n def get_all_fig_managers(cls):\n \"\"\"\n Return a list of figure managers.\n \"\"\"\n return list(cls._figures.values())\n\n @classmethod\n def reset(cls):\n \"\"\"Reset all class variables to initial state. This function exists for testing purposes \"\"\"\n cls._active_category = None\n cls._category_current_figures = {CATEGORY_CUT: None, CATEGORY_SLICE: None} # Current _figures are overplotted\n cls._figures_by_category = {CATEGORY_CUT: [], CATEGORY_SLICE: []}\n cls._unclassified_figures = []\n cls._active_figure = None\n cls._figures = {}\n\n @classmethod\n def _new_figure(cls, num=None):\n # local import to avoid circular dependency in figure_manager_test.py\n # mock.patch can't patch a class where the module has already been imported\n from mslice.plotting.plot_window.plot_figure_manager import PlotFigureManagerQT\n if num is None:\n num = 1\n while any([num == existing_fig_num for existing_fig_num in cls._figures.keys()]):\n num += 1\n new_fig = QAppThreadCall(PlotFigureManagerQT)(num, GlobalFigureManager)\n cls._figures[num] = new_fig\n cls._active_figure = num\n cls._unclassified_figures.append(num)\n return cls._figures[num], num\n\n @classmethod\n def get_figure_number(cls, num=None, create_if_not_found=True):\n cls._active_figure = num\n try:\n # make the figure the current figure of its category\n category = cls.get_category(num)\n cls._category_current_figures[category] = num\n except KeyError:\n # the figure is still uncategorised, Do nothing\n pass\n\n figure = cls._figures.get(num, None)\n if figure or not create_if_not_found:\n return figure\n else:\n # return the figure discard the number\n return cls._new_figure(num)[0]\n\n @classmethod\n def get_active_figure(cls):\n if cls._active_category:\n if cls._active_figure in cls._unclassified_figures:\n cls.assign_figure_to_category(cls._active_figure, cls._active_category,\n make_current=True)\n elif cls._category_current_figures[cls._active_category] is None:\n _, num = cls._new_figure()\n cls.assign_figure_to_category(num, cls._active_category, make_current=True)\n cls._active_figure = num\n else:\n cls._active_figure = cls._category_current_figures[cls._active_category]\n else:\n if cls._active_figure is None:\n fig, num = cls._new_figure()\n cls._active_figure = num\n\n return cls._figures[cls._active_figure]\n\n @classmethod\n def active_cut_figure_exists(cls):\n return cls._category_current_figures[CATEGORY_CUT] is not None\n\n @classmethod\n def activate_category(cls, category):\n \"\"\"Sets the active category to the supplied argument. Do not call this function directly, instead use supplied\n decorator below 'activate_category' \"\"\"\n cls._active_category = category\n\n @classmethod\n def deactivate_category(cls):\n \"\"\" Unsets the active category. Do not call this function directly, instead use supplied decorator\n below 'activate_category' \"\"\"\n cls._active_category = None\n\n @classmethod\n def assign_figure_to_category(cls, num, category, make_current=False):\n if num not in cls._figures:\n raise ValueError(\"Figure does not exist\")\n\n if num in cls._unclassified_figures:\n cls._unclassified_figures.remove(num)\n\n for a_category in cls._figures_by_category:\n if num in cls._figures_by_category[a_category]:\n cls._figures_by_category[a_category].remove(num)\n if cls._category_current_figures == num:\n cls._category_current_figures = None\n\n cls._figures_by_category[category].append(num)\n if make_current:\n cls._category_current_figures[category] = num\n cls.broadcast()\n\n @classmethod\n def figure_closed(cls, num):\n \"\"\"Figure is closed, remove all references to it from all internal list\n\n If it was the category current or global active figure then set that to None\"\"\"\n if cls._active_figure == num:\n cls._active_figure = None\n for a_category in cls._figures_by_category:\n if num in cls._figures_by_category[a_category]:\n cls._figures_by_category[a_category].remove(num)\n\n if cls._category_current_figures[a_category] == num:\n cls._category_current_figures[a_category] = None\n try:\n del cls._figures[num]\n except KeyError:\n raise KeyError('The key \"%s\" does not exist. The figure cannot be closed' % num)\n\n @classmethod\n def get_category(cls, num):\n \"\"\"Return the category of the figure\"\"\"\n for category, fig_list in list(cls._figures_by_category.items()):\n if num in fig_list:\n figure_category = category\n break\n else:\n raise KeyError(\"Figure no. %i was not found in any category \" % num if num else 0)\n # in-line if handles the case num is None\n return figure_category\n\n @classmethod\n def set_figure_as_kept(cls, num=None):\n # kept figures are just lying around, not really managed much, until they report in as current again\n if num is None:\n if cls._active_figure is not None:\n num = cls.get_active_figure().number\n cls._last_active_figure = num\n else:\n num = cls._last_active_figure\n\n if cls._active_figure == num:\n cls._active_figure = None\n try:\n figure_category = cls.get_category(num)\n except KeyError:\n figure_category = None\n\n if figure_category:\n if cls._category_current_figures[figure_category] == num:\n cls._category_current_figures[figure_category] = None\n\n cls.broadcast(figure_category)\n\n @classmethod\n def set_figure_as_current(cls, num=None):\n if num is None:\n if cls._last_active_figure is None:\n num = cls.get_active_figure().number\n else:\n num = cls._last_active_figure\n\n try:\n figure_category = cls.get_category(num)\n except KeyError:\n figure_category = None\n\n if figure_category:\n cls._category_current_figures[figure_category] = num\n\n cls._active_figure = num\n cls.broadcast(figure_category)\n\n @classmethod\n def broadcast(cls, category=None):\n \"\"\"This method will broadcast to all figures in 'category' to update the displayed kept/current status\"\"\"\n if category is None:\n broadcast_list = cls._figures_by_category\n else:\n broadcast_list = [category]\n\n for category in broadcast_list:\n for figure_number in cls._figures_by_category[category]:\n\n if cls._category_current_figures[category] == figure_number:\n cls._figures[figure_number].flag_as_current()\n\n else:\n cls._figures[figure_number].flag_as_kept()\n\n for figure in cls._unclassified_figures:\n if figure == cls._active_figure:\n cls._figures[figure].flag_as_current()\n else:\n cls._figures[figure].flag_as_kept()\n\n @classmethod\n def all_figure_numbers(cls):\n \"\"\"An iterator over all figure numbers\"\"\"\n return list(cls._figures.keys())\n\n @classmethod\n def all_figures_numbers_in_category(cls, category):\n \"\"\"Return an iterator over all _figures numbers in a category\"\"\"\n return iter(cls._figures_by_category[category])\n\n @classmethod\n def unclassified_figures(cls):\n \"\"\"Return an iterator over all unclassified _figures\"\"\"\n return iter(cls._unclassified_figures)\n\n @classmethod\n def all_figures(cls):\n \"\"\"Return an iterator over all figures\"\"\"\n return list(cls._figures.values())\n\n @classmethod\n def number_of_figure(cls, fig):\n for key, value in list(cls._figures.items()):\n if value == fig:\n return key\n raise ValueError('Figure %s was not recognised' % fig)\n\n\n# WARNING: If you change the name or parameter list here then the corresponding changes\n# to tools/boilerplate.py must be made and that script reran to regenerate pyplot.py\ndef set_category(category):\n \"\"\"A decorator to mark a function as part of the given category. For details\n of the category mechanism see the docstring on the currentfigure\n module.\n\n :param category: 'cut' or 'slice' to denote the category of the plot produced\n \"\"\"\n def activate_impl(function):\n @wraps(function)\n def wrapper(*args, **kwargs):\n try:\n GlobalFigureManager.activate_category(category)\n return_value = function(*args, **kwargs)\n finally:\n GlobalFigureManager.deactivate_category()\n return return_value\n return wrapper\n\n return activate_impl\n","sub_path":"mslice/plotting/globalfiguremanager.py","file_name":"globalfiguremanager.py","file_ext":"py","file_size_in_byte":14225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"589298727","text":"#!/usr/bin/python\n# name file : nested_while.py\n\nfrom __future__ import print_function\n\ndef main():\n\ti = 1\n\twhile i <= 10:\n\t\tj = 1\n\t\twhile j <= i:\n\t\t\tprint(\"%d \" % (i*j), end='')\n\t\t\tj += 1\n\t\tprint() # newline\n\t\ti += 1\n\nif __name__ == '__main__':\n\tmain()","sub_path":"nested_while.py","file_name":"nested_while.py","file_ext":"py","file_size_in_byte":253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"514383533","text":"class IsEven:\n \"\"\"return True if 'n' is a prime number, False otherwise\"\"\"\n import time\n import math\n\n def isprimev1(self,n):\n \"\"\"version:1,return True if 'n' is a prime number, False otherwise\"\"\"\n if n == 1:\n return False\n for d in range(2, n):\n if n % d == 0:\n return False\n return True\n\n def isprimev2(self,n):\n \"\"\"version:2,return True if 'n' is a prime number, False otherwise\"\"\"\n if n == 1:\n return False\n import math\n max_divisor = math.floor(math.sqrt(n))\n for d in range(2, 1+max_divisor):\n if n % d == 0:\n return False\n return True\n\n def isprimev3(self,n):\n \"\"\"version:3,return True if 'n' is a prime number, False otherwise\"\"\"\n if n == 1:\n return False\n if n == 2:\n return True\n if n > 2 and n % 2 == 0:\n return False\n import math\n max_divisor = math.floor(math.sqrt(n))\n for d in range(3, 1+max_divisor, 2):\n if n % d == 0:\n return False\n return True\n\n\"\"\"============time function=====================\"\"\"\ne=IsEven()\nimport time\nt0 = time.time()\nfor n in range(1, 10000):\n e.isprimev1(n)\nt1 = time.time()\nprint(\"time required for v1:\", t1-t0)\n\nt2 = time.time()\nfor n in range(1, 10000):\n e.isprimev2(n)\nt3 = time.time()\nprint(\"time required for v2:\", t3-t2)\nt4 = time.time()\nfor n in range(1, 10000):\n e.isprimev3(n)\nt5 = time.time()\nprint(\"time required for v3:\", t5-t4)","sub_path":"IsEven.py","file_name":"IsEven.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"406669507","text":"\"\"\"\r\nFaça um programa que calcule o número médio de alunos por turma.\r\nPara isto, peça a quantidade de turmas e a quantidade de alunos para cada turma.\r\nAs turmas não podem ter mais de 40 alunos.\r\n\"\"\"\r\nquant_turmas = int(input(\"Quantas turmas? \"))\r\nquant_alunos_turma = 0\r\nfor turma in range(1, quant_turmas+1):\r\n quant_alunos = int(input(f\"Quantos alunos na {turma}° turma? \"))\r\n\r\n while quant_alunos > 40 or quant_alunos < 0:\r\n print(\"Quantidade de alunos inválido. Tente novamente...\")\r\n quant_alunos = int(input(f\"Quantos alunos na {turma}° turma? \"))\r\n\r\n quant_alunos_turma += quant_alunos\r\n \r\nprint(f\"Em média cada turma recebe {quant_alunos_turma / quant_turmas:.2f} alunos.\")\r\n","sub_path":"repeticao/media_alunos_por_turmas.py","file_name":"media_alunos_por_turmas.py","file_ext":"py","file_size_in_byte":720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"297539612","text":"import re\nimport unicodedata\nfrom .. import ast\nfrom ..utils.snippet import snippet\nfrom ..utils.tree import insert_at\nfrom .base import BaseNodeTransformer\n\ninvalid_identifier = re.compile('[^A-Za-z0-9_\\.]')\n\n# def mangle(name: str) -> str:\n# \"\"\"\n# Mangles variable names using Punycode.\n# Examples:\n# testæ → py_backwards_mangled_test_wra\n# _testœ → _py_backwards_mangled__test_lbb\n# __ætest → __py_backwards_mangled___test_qua\n# \"\"\"\n# underscores = '_' * min(len(name) - len(name.lstrip('_')), 2)\n# name = invalid_identifier.sub('_', name.encode('punycode').decode('ascii'))\n# return '{}py_backwards_mangled_{}'.format(underscores, name)\n\ndef _match(match) -> str:\n char = match.group(0)\n name = unicodedata.name(char, '').lower().replace('-', 'H')\n if not name:\n name = 'U{:x}'.format(ord(char))\n return 'X' + invalid_identifier.sub('_', name) + 'X'\n\n_mangle_re = re.compile('[^A-WYZa-z0-9_]')\ndef mangle(raw_name: str) -> str:\n \"\"\"\n Mangles variable names in the same way Hy does.\n https://docs.hylang.org/en/stable/language/syntax.html#mangling\n \"\"\"\n\n # Handle names with '.'.\n if '.' in raw_name:\n res = []\n for name in raw_name.split('.'):\n if invalid_identifier.search(name):\n res.append(mangle(name))\n else:\n res.append(name)\n return '.'.join(res)\n\n name = raw_name.lstrip('_')\n underscores = '_' * (len(raw_name) - len(name))\n return underscores + 'hyx_' + _mangle_re.sub(_match, name)\n\nclass UnicodeIdentifierTransformer(BaseNodeTransformer):\n \"\"\"Compiles:\n a = 1\n æ = 2\n __œ = 3\n os.œ = 4\n To\n a = 1\n hyx_Xlatin_small_letter_aeX = 2\n __hyx_Xlatin_small_ligature_oeX = 3\n os.hyx_Xlatin_small_ligature_oeX = 4\n \"\"\"\n # Old mangler output:\n # py_backwards_mangled_6ca = 2\n # __py_backwards_mangled____fsa = 3\n # os._py_backwards_mangled_bga = 4\n target = (2, 7)\n\n def visit_Name(self, node: ast.Name) -> ast.Name:\n if invalid_identifier.search(node.id):\n self._tree_changed = True\n node.id = mangle(node.id)\n\n return self.generic_visit(node) # type: ignore\n\n def visit_Attribute(self, node: ast.Attribute) -> ast.Attribute:\n if invalid_identifier.search(node.attr):\n self._tree_changed = True\n node.attr = mangle(node.attr)\n\n return self.generic_visit(node) # type: ignore\n\n def visit_arg(self, node: ast.arg) -> ast.arg:\n if node.arg is not None and invalid_identifier.search(node.arg):\n self._tree_changed = True\n node.arg = mangle(node.arg)\n\n return self.generic_visit(node) # type: ignore\n\n def visit_keyword(self, node: ast.arg) -> ast.arg:\n if node.arg is not None and invalid_identifier.search(node.arg):\n self._tree_changed = True\n node.arg = mangle(node.arg)\n\n return self.generic_visit(node) # type: ignore\n\n def visit_FunctionDef(self, node: ast.FunctionDef) -> ast.FunctionDef:\n if invalid_identifier.search(node.name):\n self._tree_changed = True\n node.name = mangle(node.name)\n\n return self.generic_visit(node) # type: ignore\n\n def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:\n if invalid_identifier.search(node.name):\n self._tree_changed = True\n node.name = mangle(node.name)\n\n return self.generic_visit(node) # type: ignore\n\n # Used in \"from ... import ... [as ...]\".\n def visit_alias(self, node: ast.alias) -> ast.alias:\n if invalid_identifier.search(node.name):\n self._tree_changed = True\n node.name = mangle(node.name)\n # getattr(node, 'asname', None) works as well, however mypy complains.\n if hasattr(node, 'asname') and node.asname and \\\n invalid_identifier.search(node.asname):\n self._tree_changed = True\n node.asname = mangle(node.asname)\n\n return self.generic_visit(node) # type: ignore\n\n # Mangle Unicode names in \"except as\" statements\n def visit_Try(self, node: ast.Try) -> ast.Try:\n for handler in node.handlers:\n if handler.name and invalid_identifier.search(handler.name):\n self._tree_changed = True\n handler.name = mangle(handler.name)\n\n return self.generic_visit(node) # type: ignore\n","sub_path":"py_backwards/transformers/unicode_identifiers.py","file_name":"unicode_identifiers.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"13531270","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndef read_data():\n data = pd.read_csv(\"grid_search_results.csv\")\n data = data.drop(columns=\"Unnamed: 0\")\n return data\n\n\ndef plot_data(df, x_col, y_cols):\n for y_col in y_cols:\n plt.plot(df.loc[:, x_col], df.loc[:, y_col])\n plt.xlabel(x_col)\n plt.ylabel(y_col)\n plt.show()\n \n\nif __name__ == \"__main__\":\n gsr_df = read_data()\n gsr_df = gsr_df.sort_values(by=\"rank_test_score\")\n\n plot_data(gsr_df, x_col=\"mean_test_score\", y_cols=[\"param_dropout\", \"param_hidden_layers\", \"param_units\", \"mean_fit_time\"])\n\n print(gsr_df.columns)","sub_path":"grid_search_csv_analysis.py","file_name":"grid_search_csv_analysis.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"14957921","text":"from bs4 import BeautifulSoup\r\nfrom selenium.webdriver.chrome.options import Options\r\nfrom selenium.webdriver.support.select import Select\r\nimport os\r\nimport time\r\nimport constants\r\nfrom get_bet_table import get_betting_table\r\nfrom get_winnings import get_winnings\r\nimport sqlite3\r\nfrom go_to_bank import go_to_bank\r\nfrom random import randint\r\n\r\nchrome_driver_path = constants.chrome_driver_path\r\nchrome_options = Options()\r\nchrome_options.add_experimental_option(\"detach\", True)\r\ncon = sqlite3.connect('neopets.db')\r\ncur = con.cursor()\r\n\r\n\r\ndef get_betting_info():\r\n with open(os.environ.get('bet_table_path')) as bet_table:\r\n soup = BeautifulSoup(bet_table, 'html.parser')\r\n # Make blank dict for {arenas: contenders}\r\n bet_dictionary = {f\"bet{i}\": {'arenas': [], 'contenders': []} for i in range(1, 11)}\r\n combined_dictionary = {f\"bet{i}\": {} for i in range(1, 11)}\r\n for n in range(1, 11):\r\n # Get arenas as list for bet_arenas (to use in combined_dictionary) and bet_dictionary\r\n bet = soup.find_all(\"table\")[1].find_all(\"tr\")[n + 1].find_all(\"td\")[1]\r\n bet_arenas_list = soup.find_all(\"table\")[1].find_all(\"tr\")[n + 1].find_all(\"td\")[1].find_all(\"b\")\r\n bet_arenas = [arena.text for arena in bet_arenas_list]\r\n for num in range(len(bet_arenas)):\r\n bet_dictionary[f\"bet{n}\"][\"arenas\"].append(bet_arenas[num])\r\n\r\n # Get contenders as list for bet_contenders (to use in combined_dictionary) and bet_dictionary\r\n bet_string = str(bet)\r\n bet_string = bet_string.split(\"
\")\r\n bet_string2 = []\r\n for each in bet_string:\r\n bet_string2.append(each.split(\": \"))\r\n bet_contenders = [bet_string2[num][1] for num in range(len(bet_string2) - 1)]\r\n for num in range(len(bet_contenders)):\r\n bet_dictionary[f\"bet{n}\"][\"contenders\"].append(bet_contenders[num])\r\n combined_dictionary[f\"bet{n}\"].update({bet_arenas[i]: bet_contenders[i] for i in range(len(bet_arenas))})\r\n return bet_dictionary, combined_dictionary\r\n\r\n\r\n# Get arena, contenders, and bet amount, then place each bet\r\n# Time_sleep implemented throughout for purpose of making function behave at a more human pace\r\ndef place_bets(driver):\r\n # Get betting info\r\n result = get_betting_info()\r\n bet_dictionary = result[0]\r\n combined_dictionary = result[1]\r\n\r\n # Confirm enough np on hand to place bets. If not, go to bank\r\n driver.get(\"http://www.neopets.com/pirates/foodclub.phtml?type=bet\")\r\n bet_amount = driver.find_element_by_xpath(constants.GET_BET_AMOUNT_XPATH).text\r\n bet_amount_10x = int(bet_amount) * 10\r\n fetch_np_on_hand = driver.find_element_by_xpath(constants.np_on_hand_xpath).text\r\n np_on_hand = int(fetch_np_on_hand.replace(',', ''))\r\n if np_on_hand < bet_amount_10x:\r\n go_to_bank(driver, bet_amount_10x)\r\n # Place bets\r\n driver.get(\"http://www.neopets.com/pirates/foodclub.phtml?type=bet\")\r\n time.sleep(randint(1, 4))\r\n\r\n # Click checkbox only for arenas that are included in each bet\r\n for n in range(1, 11):\r\n arena_names = bet_dictionary[f\"bet{n}\"][\"arenas\"]\r\n # Scroll to bottom of page so everything is visible to click\r\n driver.execute_script(\"window.scrollTo(0,document.body.scrollHeight)\")\r\n time.sleep(1)\r\n # Click checkbox and select contender\r\n for arena in arena_names:\r\n driver.find_element_by_xpath(constants.arena_xpath_dictionary[arena][\"checkbox\"]).click()\r\n time.sleep(randint(1, 3))\r\n # Find contender dropbox\r\n dropdown = Select(driver.find_element_by_xpath(constants.arena_xpath_dictionary[arena][\"dropbox\"]))\r\n time.sleep(randint(1, 3))\r\n # Match contender with arena, select by contender's value\r\n dropdown.select_by_value(constants.CONTENDER_VALUES[combined_dictionary[f\"bet{n}\"][arena]])\r\n # Get and enter bet amount\r\n place_bet_input = driver.find_element_by_xpath(constants.PLACE_BET_AMOUNT_XPATH)\r\n place_bet_input.send_keys(bet_amount)\r\n time.sleep(randint(1, 4))\r\n place_bet_button = driver.find_element_by_xpath(constants.PLACE_BET_BUTTON_XPATH)\r\n place_bet_button.click()\r\n print(f\"Bet {n} placed.\")\r\n time.sleep(randint(1, 4))\r\n if n <= 9:\r\n place_bet_link = driver.find_element_by_xpath(constants.place_bet_link_xpath)\r\n place_bet_link.click()\r\n time.sleep(randint(1, 4))\r\n else:\r\n time.sleep(randint(1, 4))\r\n # Insert bet info into database\r\n amount_bet = int(bet_amount)*10\r\n round_number = driver.find_element_by_xpath(constants.round_number).text\r\n cur.execute(\"INSERT INTO food_club VALUES (?, ?, ?, ?, ?, ?, ?)\",\r\n (round_number, constants.today, amount_bet, \"\", \"\", \"\", \"\"))\r\n\r\n # Get boochi_target winnings to compare to my winnings (in hopes of avoiding FOMO)\r\n driver.get(\"http://www.neopets.com//~boochi_target\")\r\n boochi_page_html = driver.page_source\r\n with open(\"boochi_target.html\", \"w\") as boochi_page_file:\r\n boochi_page_file.write(boochi_page_html)\r\n with open(\"boochi_target.html\", \"r\") as boochi_page_file:\r\n soup = BeautifulSoup(boochi_page_file, \"html.parser\")\r\n table = soup.find_all(\"b\")[2].text\r\n boochi_winnings_odds_split = table.split(\":\")[0]\r\n if boochi_winnings_odds_split == \"skipped\" or boochi_winnings_odds_split == \"Skipped\":\r\n boochi_winnings_odds = int(0)\r\n else:\r\n boochi_winnings_odds = int(boochi_winnings_odds_split)\r\n cur.execute(\"UPDATE food_club SET boochi_winnings_odds = ? WHERE date = ?\",\r\n (boochi_winnings_odds, constants.yesterday,))\r\n con.commit()\r\n\r\n # Print database information\r\n bets_data = cur.execute(\"SELECT * FROM food_club ORDER BY round DESC LIMIT 2\")\r\n data = bets_data.fetchall()\r\n fetch_winnings_sum = cur.execute(\"SELECT SUM(winnings_amount) FROM food_club\").fetchone()\r\n winnings_sum = int(fetch_winnings_sum[0])\r\n print(\"Total winnings: \" + \"{:,}\".format(winnings_sum))\r\n fetch_cost_sum = cur.execute(\"SELECT SUM(amount_bet) FROM food_club\").fetchone()\r\n cost_sum = int(fetch_cost_sum[0])\r\n print(\"Total bets: \" + \"{:,}\".format(cost_sum))\r\n delta_cost = winnings_sum - cost_sum\r\n print(\"Delta: \" + \"{:,}\".format(delta_cost))\r\n roi = delta_cost / cost_sum\r\n print(\"Roi: \" + \"{0:.0%}\".format(roi))\r\n fetch_winnings_odds_sum = cur.execute(\"SELECT SUM(winnings_odds) FROM food_club\").fetchone()\r\n fethch_boochi_winnings_odds_sum = cur.execute(\"SELECT SUM(boochi_winnings_odds) FROM food_club\").fetchone()\r\n print(f\"Sum of winnings odds: {fetch_winnings_odds_sum}\")\r\n print(f\"Sum of boochi odds: {fethch_boochi_winnings_odds_sum}\")\r\n\r\n\r\nchauffeur = get_betting_table()\r\nget_winnings(chauffeur)\r\nplace_bets(chauffeur)\r\ncon.close()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"358384966","text":"# Create your views here.\nfrom django import shortcuts\nfrom django.template import RequestContext\nfrom models import Group, UserGroup\n\nfrom django.contrib.contenttypes.models import ContentType\nfrom commentWithVotes.models import CommentWithVotes \n\nfrom forms import NewGroup\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.decorators import login_required\n \nfrom articles.views import getPages\ndef groups(request, menuItem = 'groups', num = '1', itemsPerPage = 30):\n num = int(num)\n groups = Group.objects.order_by('name');\n displayGroups = groups[itemsPerPage*(num-1): itemsPerPage*num]\n pages = getPages(groups.count(), itemsPerPage, num)\n \n return shortcuts.render_to_response('groups/groups.html', \n {'groups': displayGroups, 'menuItem' : menuItem, 'pages' : pages, 'current' : num},\n context_instance=RequestContext(request)) \n\n@login_required\ndef newGroup(request):\n if request.method == 'POST':\n form = NewGroup(request.POST)\n if form.is_valid():\n group = Group(owner = request.user, \n private = False,\n name = form.cleaned_data['name'],\n description = form.cleaned_data['description'])\n group.save()\n userGroup = UserGroup(user = request.user, group = group)\n userGroup.save()\n return HttpResponseRedirect(\"/\")\n else:\n form = NewGroup()\n \n return shortcuts.render_to_response(\"groups/new.html\", {'form': form, \"menuItem\" : \"groups\"}, context_instance=RequestContext(request))\n\n\nfrom articles.models import Articles\ndef groupView(request, groupName, menuItem = 'groups', num='1', itemsPerPage=30):\n num = int(num)\n group = Group.objects.get(name = groupName)\n comments = CommentWithVotes.objects.filter(object_pk = group.pk, \n content_type=ContentType.objects.get(app_label=\"groups\", model=\"group\")).order_by('-submit_date')\n\n pages = getPages(comments.count(), itemsPerPage, num)\n comments = comments[itemsPerPage*(num-1): itemsPerPage*num]\n \n try:\n UserGroup.objects.get(user = request.user, group = group)\n member = True\n except:\n member = False\n \n members = UserGroup.objects.filter(group = group)\n articles = Articles.objects.filter(group = group) \n return shortcuts.render_to_response('groups/group.html', \n {'group' : group, \n 'menuItem' : menuItem, \n 'member' : member,\n 'members' : members,\n 'articles' : articles,\n 'pages' : pages,\n 'comments' : comments, \n 'current' : num, \n 'next' : request.get_full_path()},\n context_instance=RequestContext(request))\n \n@login_required\ndef join(request, groupName):\n group = Group.objects.get(name = groupName)\n UserGroup.objects.get_or_create(user = request.user, group = group)\n\n return HttpResponseRedirect('/group/' + groupName + '/')\n\n@login_required\ndef leave(request, groupName):\n group = Group.objects.get(name = groupName)\n try:\n userGroup = UserGroup.objects.get(user = request.user, group = group)\n userGroup.delete()\n except:\n pass\n \n return HttpResponseRedirect('/group/' + groupName + '/')\n\n \n \n ","sub_path":"groups/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"520189862","text":"##Two positive numbers A and B are said to be connected (denoted by \"A ↔ B\")\n##if one of these conditions holds:\n##(1) A and B have the same length and differ in exactly one digit; for\n##example, 123 ↔ 173.\n##(2) Adding one digit to the left of A (or B) makes B (or A); for example,\n##23 ↔ 223 and 123 ↔ 23.\n##\n##We call a prime P a 2's relative if there exists a chain of connected\n##primes between 2 and P and no prime in the chain exceeds P.\n##\n##For example, 127 is a 2's relative. One of the possible chains is shown below:\n##2 ↔ 3 ↔ 13 ↔ 113 ↔ 103 ↔ 107 ↔ 127\n##However, 11 and 103 are not 2's relatives.\n##\n##Let F(N) be the sum of the primes ≤ N which are not 2's relatives.\n##We can verify that F(10^3) = 431 and F(10^4) = 78728.\n##\n##Find F(10^7).\n\nfrom time import time\nimport sys\nsys.path.append(\"../Library\")\nfrom peresult import peresult\nfrom primefns import primesbelow\n\ndef solve(cap):\n start = time()\n print(\"Note: This one takes just a LITTLE over a minute, but since it's\" \\\n + \" pretty close and in Python, I'm calling it good enough.\")\n rawPrimes = primesbelow(cap)\n maxLink = dict() #Largest element in chain from 2 to prime (minimized)\n for prime in rawPrimes:\n maxLink[prime] = cap + 1\n maxLink[2] = 2\n currentPrimes = {2}\n while len(currentPrimes) > 0:\n newPrimes = set()\n for prime in currentPrimes:\n #Replace a digit\n clone = prime\n power = 0\n while clone > 0:\n currentDigit = clone % 10\n #Decrease a digit\n for diff in range(1, currentDigit + 1):\n possibleNew = prime - (diff * (10 ** power))\n if possibleNew in maxLink \\\n and maxLink[prime] < maxLink[possibleNew]:\n maxLink[possibleNew] = max(possibleNew, maxLink[prime])\n newPrimes.add(possibleNew)\n #Increase a digit\n for diff in range(1, 10 - currentDigit):\n possibleNew = prime + (diff * (10 ** power))\n if possibleNew in maxLink \\\n and maxLink[possibleNew] > max(possibleNew, \\\n maxLink[prime]):\n maxLink[possibleNew] = max(possibleNew, maxLink[prime])\n newPrimes.add(possibleNew)\n clone //= 10\n power += 1\n #Add a digit on the left\n for dig in range(1, 10):\n possibleNew = ((10 ** power) * dig) + prime\n if possibleNew in maxLink \\\n and maxLink[possibleNew] > max(possibleNew, \\\n maxLink[prime]):\n maxLink[possibleNew] = max(possibleNew, maxLink[prime])\n newPrimes.add(possibleNew)\n currentPrimes = newPrimes\n result = 0\n for prime in maxLink.keys():\n if maxLink[prime] > prime:\n result += prime\n peresult(425, result, time() - start)\n\nif __name__ == \"__main__\":\n solve(10 ** 7)\n","sub_path":"Problems 401-500/pe425PrimeConnection.py","file_name":"pe425PrimeConnection.py","file_ext":"py","file_size_in_byte":3148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"400423691","text":"import unittest\nimport numpy as np\nimport pandas as pd\nimport sys\nsys.path.append('..')\nfrom sensor.sensor import Sensor, SensorArray\nfrom uncertainties import unumpy\n\nnp.random.seed(30)\n\nclass TestUncertaintiesArrayGeneration(unittest.TestCase):\n\n def test_uncertainty_series(self):\n \n signal = np.linspace(40,500,1000) \n std_deviation = np.max(np.array([np.ones(signal.shape)*2.2,signal*0.75/100]),axis = 0)\n signal += np.random.normal(0,std_deviation)\n signal = pd.Series(signal,name = 'T1 [C]')\n\n sensor = SensorArray.from_file('input_files\\\\test_sensor.yml').HeaterInlet1\n\n x = sensor.uArray(signal)\n #print(x.mean())\n x = sensor.uSeries(signal)\n\n\n def test_basic_operaations(self):\n\n signal = np.linspace(40,500,1000) \n std_deviation = np.max(np.array([np.ones(signal.shape)*2.2,signal*0.75/100]),axis = 0)\n signal += np.random.normal(0,std_deviation)\n signal1 = pd.Series(signal,name = 'T1 [C]')\n \n tsignal = np.ones(1000)*16e-3\n std_deviation = np.random.normal(0,0.2/100*18e-3)\n signal2 = pd.Series(signal + std_deviation,name = 'P1 [A]')\n\n sensor_array =SensorArray.from_file('input_files\\\\test_sensor.yml')\n thermocouple = sensor_array.HeaterInlet1\n static_pressure = sensor_array.StaticPressureVenturi\n\n T1 = thermocouple.uArray(signal1)\n P1 = static_pressure.uArray(signal2)\n\n PT = P1*T1\n\n T1 = thermocouple.uSeries(signal1)\n P1 = static_pressure.uSeries(signal2)\n \n PT = T1*P1\n print(PT)\n\n def test_frame_manipulation(self):\n\n signal = np.linspace(40,500,1000) \n std_deviation = np.max(np.array([np.ones(signal.shape)*2.2,signal*0.75/100]),axis = 0)\n signal += np.random.normal(0,std_deviation)\n signal1 = pd.Series(signal,name = 'T1 [C]')\n \n tsignal = np.ones(1000)*16e-3\n std_deviation = np.random.normal(0,0.2/100*18e-3)\n signal2 = pd.Series(signal + std_deviation,name = 'P1 [A]')\n\n df = pd.concat([signal1,signal2],axis = 1)\n sensor_array =SensorArray.from_file('input_files\\\\test_sensor.yml')\n\n uarr = sensor_array.uArray(df)\n\n uFrame = sensor_array.uDataFrame(df)\n #print(uFrame)\n\n\nunittest.main()","sub_path":"tests/test_uncertainties.py","file_name":"test_uncertainties.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"526721987","text":"import numpy as np\nimport scipy.special as sps\nimport distributions.entropicMarginalLikelihood as eml\n\n\ndef test_getEmpiricalTmat():\n \n darchs = [(0, 1, 2, 3), (3, 2, 3), (),\n (0, 0), (0,), (0,)]\n ndoms = max(darchs[0])+1\n tst = eml.getEmpiricalTmat(ndoms, darchs)\n chk = np.array([[0, 4, 0, 0, 1, 1],\n [0, 1, 1, 0, 0, 3],\n [0, 0, 0, 1, 0, 0],\n [0, 0, 0, 0, 2, 0],\n [0, 0, 0, 1, 0, 2],\n [0, 0, 0, 0, 0, 0]])\n assert np.all(tst == chk)\n \ndef test_tmatbetaln():\n tst = eml.tmatbetaln(np.array([[0, 1, 2], [0, 3, 2], [0, 0, 0]]))\n chk = -(np.log(2) + np.log(4*3*2) - np.log(2))\n assert tst == chk\n \ndef test_amcDirichletML():\n darchs = [(0, 0, 0), (), ()]\n mfactor = np.log(3*2) - np.log(2)\n bfpre = (sps.gammaln(1) + sps.gammaln(1) - sps.gammaln(2)\n + sps.gammaln(1) + sps.gammaln(1) - sps.gammaln(2))\n bfpost = (sps.gammaln(2) + sps.gammaln(3) - sps.gammaln(5)\n + sps.gammaln(3) + sps.gammaln(2) - sps.gammaln(5))\n chk = mfactor + bfpost - bfpre\n tst = eml.amcDirichletML(1, darchs)\n \n assert tst == chk\n ","sub_path":"distributions/test_entropicMarginalLikelihood.py","file_name":"test_entropicMarginalLikelihood.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"156674982","text":"# -*- coding: utf-8 -*-\n##\n## This file is part of the SixPay Indico EPayment Plugin.\n## Copyright (C) 2017 Max Fischer\n##\n## This is free software; you can redistribute it and/or\n## modify it under the terms of the GNU General Public License as\n## published by the Free Software Foundation; either version 3 of the\n## License, or (at your option) any later version.\n##\n## This software is distributed in the hope that it will be useful, but\n## WITHOUT ANY WARRANTY; without even the implied warranty of\n## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n## General Public License for more details.\n##\n## You should have received a copy of the GNU General Public License\n## along with Indico;if not, see .\nfrom __future__ import absolute_import, division\nimport urlparse\nimport requests\nfrom xml.dom.minidom import parseString\n\nfrom MaKaC.epayment import BaseEPayMod, BaseTransaction\nfrom MaKaC.common.timezoneUtils import nowutc\n\n\nfrom .webinterface import urlHandlers as localUrlHandlers\nfrom . import MODULE_ID\n\n\nclass TransactionError(BaseException):\n \"\"\"An error occurred inside the transaction to SixPay\"\"\"\n\n\nclass SixPayMod(BaseEPayMod):\n \"\"\"\n Payment Module for SIX Payment Service\n\n :param data: mapping to initialise fields\n :type data: dict or None\n \"\"\"\n #: default settings used when setting fields via `data`\n default_settings = {\n 'title': \"Six Payment Services\",\n 'url': \"https://www.saferpay.com/hosting\",\n 'account_id': \"\",\n 'notification_mail': \"\",\n 'user_description': \"Indico Event %(event_id)s, Registrant %(user_id)s\",\n }\n\n def __init__(self, data=None):\n BaseEPayMod.__init__(self)\n #: title of this payment method\n self._title = self.default_settings['title']\n #: URL for the saferpay https interface\n self._url = self.default_settings['url']\n #: saferpay account ID of the conference\n self.account_id = self.default_settings['account_id']\n #: description for transaction presented to registrant\n self.user_description = self.default_settings['user_description']\n #: mail to send confirmations to\n self.notification_mail = self.default_settings['notification_mail']\n if data is not None:\n self.setValues(data)\n\n def getId(self):\n return MODULE_ID\n\n def clone(self, newSessions):\n \"\"\"Return a clone of this instance\"\"\"\n self_clone = SixPayMod()\n self_clone.setValues(self.getValues())\n self_clone.setEnabled(self.isEnabled())\n return self_clone\n\n def setValues(self, data):\n \"\"\"\n Set all fields from mapping\n\n :param data: mapping to initialise fields\n :type data: dict or None\n\n :note: any field missing in `data` will be set to its default value\n \"\"\"\n for key in self.default_settings:\n value = data.get(key) or self.default_settings[key]\n setattr(self, key, value)\n\n def getValues(self):\n \"\"\"\n Get all fields as a mapping\n\n :return: mapping of all fields\n :rtype: dict\n\n :note: any field missing will be set to its default value\n \"\"\"\n return {\n key: getattr(self, key, self.default_settings[key]) for key in self.default_settings\n }\n\n @property\n def title(self):\n return self._title\n\n @title.setter\n def title(self, value):\n self._title = value\n\n @property\n def url(self):\n return self._url\n\n @url.setter\n def url(self, value):\n # ensure a trailing slash at end of path, or merging endpoints does not work\n url = urlparse.urlparse(value)\n url = url._replace(path=url.path.rstrip('/') + '/')\n self._url = url.geturl()\n\n @staticmethod\n def _perform_request(endpoint, **params):\n \"\"\"Perform a POST request\"\"\"\n url_request = requests.post(endpoint, **params)\n # raise any request errors\n url_request.raise_for_status()\n # raise errors in response\n if url_request.text.startswith('ERROR'):\n raise TransactionError('Failed request to SixPay service: %s' % url_request.text)\n return url_request\n\n def getFormHTML(self, prix, Currency, conf, registrant, lang=\"en_GB\", secure=False):\n \"\"\"Generates the action of the button presented to the user for payment\"\"\"\n payment_url = self._get_payment_url(prix, Currency, conf, registrant, lang, secure)\n payment_action = \"\"\"
\"\"\" % (payment_url, self.getId())\n return payment_action\n\n def _get_payment_url(self, prix, Currency, conf, registrant, lang, secure):\n \"\"\"\n Generate Payment URL for User\n\n Transmitting the payment request to Six is separate from prompting the user\n to avoid modification of payment details.\n \"\"\"\n endpoint = urlparse.urljoin(self.url, 'CreatePayInit.asp')\n # keys for formatting strings\n format_map = {'event_id': conf.getId(), 'user_id': registrant.getId(), 'price': prix, 'currency': Currency}\n # description of transaction presented to user\n user_description = self.user_description or self.default_settings['user_description']\n user_description %= format_map\n # parameters for callbacks so that indico can identify the transaction subject\n callback_params = {'target': conf, 'registrantId': registrant.getId()}\n parameters = {\n 'ACCOUNTID': str(self.account_id),\n # indico handles price as largest currency, but six expects smallest\n # e.g. EUR: indico uses 100.2 Euro, but six expects 10020 Cent\n 'AMOUNT': '%d' % (prix*100),\n 'CURRENCY': Currency,\n 'DESCRIPTION': user_description,\n 'ORDERID': registrant.getIdPay()[:80],\n 'SHOWLANGUAGES': 'yes',\n # callbacks for the service to redirect users back to indico\n 'SUCCESSLINK': localUrlHandlers.UHPayTransactionSuccess.getURL(**callback_params),\n 'FAILLINK': localUrlHandlers.UHPayTransactionFaillink.getURL(**callback_params),\n 'BACKLINK': localUrlHandlers.UHPayTransactionBacklink.getURL(**callback_params),\n # callback for the service to confirm transaction\n 'NOTIFYURL': localUrlHandlers.UHPayTransactionNotifyUrl.getURL(**callback_params),\n }\n if self.notification_mail:\n parameters['NOTIFYADDRESS'] = self.notification_mail\n url_request = self._perform_request(endpoint, data=parameters)\n return str(url_request.text)\n\n def verify_transaction(self, data, signature, registrant):\n \"\"\"Ensure the transaction is correct in Indico and SixPay\"\"\"\n # DATA: ''\n mdom = parseString(data)\n attributes = mdom.documentElement.attributes\n idp_data = {\n attributes.item(idx).name: attributes.item(idx).value\n for idx in range(attributes.length)\n }\n if self._verify_confirmation(data, signature, idp_data=idp_data):\n transaction = TransactionSixPay(\n user_id=registrant.getId(), event_id=registrant.getConference().getId(),\n signature=signature, amount=(int(idp_data['AMOUNT']) / 100.0), currency=idp_data['CURRENCY'],\n six_id=idp_data['ID'], order_id=registrant.getIdPay(),\n )\n # verification may be triggered multiple times\n if registrant.getPayed() and registrant.getTransactionInfo() == transaction:\n return True\n self._complete_transaction(idp_data=idp_data)\n registrant.setTransactionInfo(transaction)\n registrant.setPayed(True)\n registration_form = registrant.getConference().getRegistrationForm()\n registration_form.getNotification().sendEmailNewRegistrantConfirmPay(\n registration_form, registrant\n )\n return False\n\n def _verify_confirmation(self, data, signature, idp_data):\n \"\"\"send the confirmation back to SixPay to verify the signature\"\"\"\n endpoint = urlparse.urljoin(self.url, 'VerifyPayConfirm.asp')\n url_request = self._perform_request(endpoint, data={'DATA': data, 'SIGNATURE': signature})\n if url_request.text.startswith('OK:'):\n # text = 'OK:ID=56a77rg243asfhmkq3r&TOKEN=%3e235462FA23C4FE4AF65'\n confirmation = dict(key_value.split('=') for key_value in url_request.text.split(':', 1)[1].split('&'))\n if idp_data['ID'] != confirmation['ID'] or idp_data['ID'] != confirmation['ID']:\n raise TransactionError('Mismatched verification and confirmation data')\n return True\n raise RuntimeError(\"Expected reply 'OK:ID=...&TOKEN=...', got %r\" % url_request.text)\n\n def _complete_transaction(self, idp_data):\n \"\"\"inform SixPay that we agree to the transaction\"\"\"\n endpoint = urlparse.urljoin(self.url, 'PayCompleteV2.asp')\n data = {'ACCOUNTID': idp_data['ACCOUNTID'], 'ID': idp_data['ID']}\n if 'test.' in self.url:\n data['spPassword'] = '8e7Yn5yk'\n url_request = self._perform_request(endpoint, data=data)\n return url_request.text.startswith('OK')\n\n def getConfModifEPaymentURL(self, conf):\n \"\"\"URL for applying settings for the EPayment of a single event/conference\"\"\"\n return localUrlHandlers.UHConfModifEPaymentSixPay.getURL(conf)\n\n\nclass TransactionSixPay(BaseTransaction):\n \"\"\"Completed Transaction for SIX Payment Service\"\"\"\n def __init__(self, user_id, event_id, signature, amount, currency, six_id, order_id, date=None):\n BaseTransaction.__init__(self)\n self.user_id = user_id\n self.event_id = event_id\n self.signature = signature\n self.amount = amount\n self.currency = currency\n self.six_id = six_id\n self.order_id = order_id\n self.date = date or nowutc()\n\n def __eq__(self, other):\n if isinstance(other, self.__class__):\n return self.six_id == other.six_id and self.order_id == other.order_id and self.signature == other.signature\n else:\n return NotImplemented\n\n def getId(self):\n try:\n return self._id\n except AttributeError:\n self._id = \"sixpay\"\n return self._id\n\n def _form_data(self):\n return (\n ('Service', 'SixPay'),\n ('Date', self.date),\n ('Order Total', '%.2f %s' % (self.amount, self.currency)),\n ('Subject', 'Event %s, Registrant %s' % (self.event_id, self.user_id)),\n ('Transaction ID', self.order_id),\n ('Payment ID', self.six_id),\n )\n\n def getTransactionHTML(self):\n \"\"\"HTML for displaying transaction in Indico\"\"\"\n entry = \"\"\"\\\n \n %s\n %s\n \"\"\"\n return \"\"\"\\\n \n%s\n
\"\"\" % '\\n'.join(\n entry % (name, value)\n for name, value in\n self._form_data()\n )\n\n def getTransactionTxt(self):\n \"\"\"Text for displaying transaction in mails\"\"\"\n entry = \"\"\"%-16s %s\"\"\"\n return '\\n'.join(\n entry % (name, value)\n for name, value in\n self._form_data()\n )\n\n\ndef getPayMod():\n return SixPayMod()\n\n\ndef getPayModClass():\n return SixPayMod\n","sub_path":"indico_sixpay/epayment.py","file_name":"epayment.py","file_ext":"py","file_size_in_byte":12567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"265904589","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n[googleSearch.py]\r\nGoogle Search Plugin\r\n\r\n[Author]\r\nJustin Walker\r\n\r\n[About]\r\nReturns the first several links from a google search.\r\n\r\n[Commands]\r\n>>> .google <> <>\r\nreturns search links\r\n\"\"\"\r\n\r\ntry: \r\n from googlesearch import search \r\nexcept ImportError: \r\n print(\"No module named 'google' found\")\r\n\r\n\r\nclass Plugin:\r\n def __init__(self):\r\n pass\r\n\r\n def __google(self, search_term, search_count):\r\n # num is number of links, start is what link to start with,\r\n # only_standard limits it to normal links instead of adds and extra\r\n # links.\r\n return search(search_term, num=search_count, start=0,\r\n only_standard=True)\r\n\r\n def run(self, incoming, methods, info):\r\n try:\r\n msgs = info['args'][1:][0].split()\r\n \r\n if info['command'] == 'PRIVMSG' and msgs[0] == '.google':\r\n count = 10\r\n # First argurment after .google should be search term,\r\n # if it exists\r\n if len(msgs) == 2:\r\n term = msgs[1]\r\n # Second argument should be count if it exists.\r\n if len(msgs) == 3:\r\n count = msgs[2]\r\n\r\n for link in self.__google(term, count):\r\n methods['send'](info['address'], link)\r\n else:\r\n methods['send'](info['address'], \"Input error. '.google search_term search_count'.\")\r\n \r\n except Exception as e:\r\n print('woops plugin error: ', e)","sub_path":"honeybot/plugins/google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"69421713","text":"import transaction\nimport logging\n\nfrom Products.CMFCore.utils import getToolByName\n\nlogger = logging.getLogger('Events Handlers')\n\ndef signupCreated(obj, event):\n \"\"\" Someone registered for an event\n \"\"\"\n if obj.portal_type != 'Booking':\n return\n\n mt = getToolByName(obj, 'portal_membership')\n member = mt.getAuthenticatedMember()\n\n # set the default values of the event preferences\n # home = mt.getHomeFolder(member.getId())\n if 'event_attendance' in member.objectIds():\n attendance_prefs = member['event_attendance']\n if attendance_prefs.getInitials() != obj.getInitials():\n attendance_prefs.setInitials(obj.getInitials())\n if attendance_prefs.getTelephone() != obj.getPhone():\n attendance_prefs.setTelephone(obj.getPhone())\n if attendance_prefs.getMobile() != obj.getMobile():\n attendance_prefs.setMobile(obj.getMobile())\n if attendance_prefs.getIceNumber() != obj.getIceNumber():\n attendance_prefs.setIceNumber(obj.getIceNumber())\n if attendance_prefs.getFax() != obj.getFax():\n attendance_prefs.setFax(obj.getFax())\n if attendance_prefs.getCompany() != obj.getCompany():\n attendance_prefs.setCompany(obj.getCompany())\n if attendance_prefs.getJobTitle() != obj.getFunction():\n attendance_prefs.setJobTitle(obj.getFunction())\n if attendance_prefs.getMealPreference() != obj.getMealPreference():\n attendance_prefs.setMealPreference(obj.getMealPreference())\n if attendance_prefs.getOtherMealPreference() != obj.getOtherMealPreference():\n attendance_prefs.setOtherMealPreference(obj.getOtherMealPreference())\n if attendance_prefs.getCountry() != obj.getCountry():\n attendance_prefs.setCountry(obj.getCountry())\n\n logger.info('Booking object initialized')\n\n # send an email to the attendee\n mailhost = getToolByName(obj, 'MailHost')\n attendee_name = '%s %s %s' % \\\n (obj.getSalutation(), obj.getFirstname(), obj.getSurname())\n attendee_email = obj.getEmail()\n pu = getToolByName(obj, 'portal_url')\n portal = pu.getPortalObject()\n sender_email = portal['email_from_address']\n attendee_msg = \"\"\"Dear %s\n\nThankyou for registering for the '%s' event. \n\nVisit the link below to view the details of your booking, as well as the cost involved.\n\n%s/view\n\nKind regards,\nThe EventsList Team\n \"\"\" % (attendee_name, obj.Title(), obj.absolute_url())\n mailhost.send(attendee_msg, mto=attendee_email, mfrom=sender_email, \n subject='Event Attendance Request', encode=None)\n\n # send an email to the organiser\n event = obj.getElevents()\n organiser_name = event.contact_name()\n organiser_email = event.contact_email()\n organiser_msg = \"\"\"Dear %s\n\nThis is a notification that %s has registered to attend the '%s' event.\n\nClick the link below to view the event registration screen page and accept or reject the registration.\n\n%s\n\nKind regards,\nThe EventsList Team\n \"\"\" % (organiser_name, attendee_name, obj.Title(), '%s/events_folder' % pu())\n #logger.info('Send email from %s to %s' % (\n # organiser_email, sender_email))\n mailhost.send(organiser_msg, mto=organiser_email, mfrom=sender_email, \n subject='Event Attendance Request', encode=None)\n\n logger.info('Email sent to attendee and organiser')\n\n\n\ndef bookingTransition(obj, notification):\n \"\"\" handle a transition on a booking\n \"\"\"\n if obj.portal_type != 'Booking':\n return\n\n if notification.status['review_state'] == 'submitted':\n return\n\n # send an email to the attendee\n mailhost = getToolByName(obj, 'MailHost')\n attendee_name = '%s %s %s' % \\\n (obj.getSalutation(), obj.getFirstname(), obj.getSurname())\n attendee_email = obj.getEmail()\n pu = getToolByName(obj, 'portal_url')\n portal = pu.getPortalObject()\n sender_email = portal['email_from_address']\n attendee_msg = \"\"\"Dear %s\n\nThis is a note to inform you that the status of your registration for the '%s' event is now '%s'.\n\nVisit the link below to view the details of your booking, as well as the cost involved.\n\n%s/view\n\nKind regards,\nThe EventsList Team\n \"\"\" % (attendee_name, obj.Title(), notification.new_state.title, obj.absolute_url())\n mailhost.send(attendee_msg, mto=attendee_email, mfrom=sender_email, \n subject='Event Attendance Notification', encode=None)\n\n logger.info('Status change Email sent to attendee')\n","sub_path":"handlers/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"558814847","text":"'''kuo22_Farmer_Fox.py\nby Kuo Hong\n\nAssignment 2, in CSE 415, Winter 2019.\n \nThis file contains my problem formulation for the problem of\nthe Farmer, Fox, Chicken, and Grain.\n'''\n#\nSOLUZION_VERSION = \"2.0\"\nPROBLEM_NAME = \"Farmer and Fox\"\nPROBLEM_VERSION = \"2.0\"\nPROBLEM_AUTHORS = ['S. Tanimoto']\nPROBLEM_CREATION_DATE = \"07-JAN-2018\"\n\n# The following field is mainly for the human solver, via either the Text_SOLUZION_Client.\n# or the SVG graphics client.\nPROBLEM_DESC=\\\n '''The Farmer and Fox problem starts with the farmer, fox, chicken, and grain on the left side of a river. \n The goal is to transport everything to the right side using a boat. The boat must be rowed by the farmer\n and he can only carry one thing with him at a time. The fox will eat the chicken \n and the chicken will eat the grain if left alone by the farmer. \n'''\n#\n\n#\n#\n\n#\nLEFT=0 # same idea for left side of river\nRIGHT=1 # etc.\n\nSIDE = {\n 0: 'left',\n 1: 'right'\n}\n\nclass State():\n\n def __init__(self, d=None):\n if d==None: \n d = {\n 'farmer':LEFT,\n 'fox':LEFT,\n 'chicken':LEFT, \n 'grain':LEFT\n }\n self.d = d\n\n def __eq__(self,s2):\n for prop in ['farmer', 'fox', 'chicken', 'grain']:\n if self.d[prop] != s2.d[prop]: \n return False\n return True\n\n def __str__(self):\n # Produces a textual description of a state.\n txt = 'Left: '\n txt2 = '\\nRight: '\n for prop in ['farmer', 'fox', 'chicken', 'grain']:\n if self.d[prop] == LEFT:\n txt += prop + ' '\n else:\n txt2 += prop + ' '\n\n return txt + txt2 + '\\n'\n\n def __hash__(self):\n return (self.__str__()).__hash__()\n\n def copy(self):\n # Performs an appropriately deep copy of a state,\n # for use by operators in creating new states.\n news = State({})\n news.d['farmer'] = self.d['farmer']\n news.d['fox'] = self.d['fox']\n news.d['chicken'] = self.d['chicken']\n news.d['grain'] = self.d['grain']\n\n # news.d['people']=[self.d['people'][M_or_C][:] for M_or_C in [M, C]]\n # news.d['boat'] = self.d['boat']\n return news \n\n def can_move(self, p):\n side = self.d['farmer']\n if p == 'farmer':\n if (self.d['fox'] == side and self.d['chicken'] == side) or (self.d['chicken'] == side and self.d['grain'] == side):\n return False\n if p == 'fox' and (self.d['fox'] != side or (self.d['chicken'] == side and self.d['grain'] == side)):\n return False\n if p == 'grain' and (self.d['grain'] != side or (self.d['fox'] == side and self.d['chicken'] == side)):\n return False \n if p == 'chicken' and self.d['chicken'] != side:\n return False\n \n return True\n\n\n def move(self, p):\n news = self.copy()\n side = self.d['farmer']\n news.d['farmer'] = 1 - side\n if p != 'farmer':\n news.d[p] = 1 - side\n\n return news\n\ndef goal_test(s):\n '''If all Ms and Cs are on the right, then s is a goal state.'''\n for prop in ['farmer', 'fox', 'chicken', 'grain']:\n if s.d[prop] == LEFT:\n return False\n return True\n\ndef goal_message(s):\n return \"Congratulations on successfully guiding the farmer gang across the river!\"\n\nclass Operator:\n def __init__(self, name, precond, state_transf):\n self.name = name\n self.precond = precond\n self.state_transf = state_transf\n\n def is_applicable(self, s):\n return self.precond(s)\n\n def apply(self, s):\n return self.state_transf(s)\n#\n\n#\nCREATE_INITIAL_STATE = lambda : State(d={'farmer':LEFT, 'fox':LEFT, 'chicken':LEFT, 'grain':LEFT })\n#\n\n#\ncombinations = ['farmer', 'fox', 'chicken', 'grain']\n\nOPERATORS = [Operator(\n \"Farmer crosses river with \" + p + \".\",\n lambda s, p1=p: s.can_move(p1),\n lambda s, p1=p: s.move(p1)) \n for p in combinations]\n#\n\n# (optional)\nGOAL_TEST = lambda s: goal_test(s)\n#\n\n# (optional)\nGOAL_MESSAGE_FUNCTION = lambda s: goal_message(s)\n#","sub_path":"hw2/kuo22_Farmer_Fox.py","file_name":"kuo22_Farmer_Fox.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"148094858","text":"#!usr/bin/env python3\n\nimport sys\nimport re\n\nvalidlink = r'''(?xi)\n ^((http|https)://)? # optional protocol\n (\\w+\\.)? # optional app name\n (\\w+).(\\w{2,7})$ # require domain\n '''\n\ndef isvalidlink(lnk):\n global validlink\n return True if re.search(validlink, lnk) else False\n\ndef getsitename(lnk):\n m = re.search(r'\\w+(?=(\\.\\w{2,7})$)', lnk) # match any word before the tld\n return m.group() if m else lnk\n\ndef addtag(lnk):\n sitename = getsitename(lnk)\n lnk = (lnk.startswith('http://') or lnk.startswith('https://')) and lnk \\\n or 'http://' + lnk\n taglnk = '' + sitename + ''\n return sitename + 'link', taglnk\n\ndef savefile(filename, taglnk):\n try:\n with open(filename + '.html', 'w') as fin:\n fin.write('\\n')\n fin.write('\\n')\n fin.write('\\n')\n fin.write('\\t%s\\n' % filename)\n fin.write('\\n')\n fin.write('\\n')\n fin.write('\\t%s\\n' % taglnk);\n fin.write('\\n')\n fin.write('')\n except IOError:\n print('Unable to write file')\n sys.exit()\n\nif __name__ == '__main__':\n print('HTML Generator')\n lnk = input('Enter link >> ').strip()\n if isvalidlink(lnk):\n filename, taglnk = addtag(lnk)\n savefile(filename, taglnk)\n print('HTML generated')\n else:\n print('Invalid format')\n","sub_path":"html_generator.py","file_name":"html_generator.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"652002025","text":"# coding: utf-8\nimport sys\nsys.path.append(\"..\")\nimport Amadeus\nimport os\nimport numpy as np\nfrom Amadeus.brain.talk.seq2seq import Seq2SeqModel\n\n\ndef init_model():\n rnn_size = 128\n layer_size = 2\n start = Amadeus.AMADEUS_DEFAULT_DICTIONARY_NUM\n end = Amadeus.AMADEUS_DEFAULT_DICTIONARY_NUM + 1\n pad = Amadeus.AMADEUS_DEFAULT_DICTIONARY_NUM + 2\n mask = Amadeus.AMADEUS_DEFAULT_DICTIONARY_NUM + 3\n encoder_vocab_size = Amadeus.AMADEUS_DEFAULT_DICTIONARY_NUM + 4\n decoder_vocab_size = Amadeus.AMADEUS_DEFAULT_DICTIONARY_NUM + 4\n embedding_dim = 128\n grad_clip = 5\n S2S = Seq2SeqModel(rnn_size, layer_size, encoder_vocab_size,\n decoder_vocab_size, embedding_dim, grad_clip,\n start, end, pad, mask)\n return S2S\n\n\ndef load_data(inputs, batch_size, start, end, pad, mask):\n max_batch_len = 0\n max_batch_len_d = 0\n batch = {\"data\": [], \"label\": []}\n while True:\n for filename in os.listdir(inputs):\n data = np.load(inputs+filename).item()\n # print(data[\"data\"])\n for d, l in zip(data[\"data\"], data[\"label\"]):\n d = [dd[1] if dd[1] >=0 else mask for dd in d]\n l = [start] + [ll[1] if ll[1] > 0 else mask for ll in l] + [end]\n if len(l) > max_batch_len:\n max_batch_len = len(l)\n if len(d) > max_batch_len_d:\n max_batch_len_d = len(d)\n batch[\"data\"].append(d)\n batch[\"label\"].append(l)\n if len(batch[\"data\"]) >= batch_size - 1:\n for j in range(len(batch[\"data\"])):\n batch[\"data\"][j] = batch[\"data\"][j] + [pad for _ in range(max_batch_len_d - len(batch[\"data\"][j]))]\n batch[\"label\"][j] = batch[\"label\"][j] + [pad for _ in range(max_batch_len - len(batch[\"label\"][j]))]\n batch_lens = [len(x) for x in batch[\"label\"]]\n yield batch[\"data\"], batch[\"label\"], batch_lens\n # debug\n # print(batch[\"data\"][0])\n break\n batch = {\"data\": [], \"label\": []}\n max_batch_len = 0\n max_batch_len_d = 0\n\n\ndef main():\n S2S = init_model()\n start, end, pad, mask = S2S.start, S2S.end, S2S.pad, S2S.mask\n sess = S2S.new_session()\n inputs = Amadeus.AMADEUS_TRAIN_DATA_DIR\n batch_size = 1\n data = load_data(inputs, batch_size, start, end, pad, mask)\n for train_data, train_label, batch_lens in data:\n #print(\"train:\")\n loss = S2S.train(sess, train_data, train_label, batch_lens)\n print(\"=======\")\n #print(loss[0])\n #print(loss[3])\n #print(train_label[0])\n #print(loss[1][0][0][0][-10:])\n #print(sum(sum(loss[-1][0])))\n print(loss[4][0][0][0])\n print(loss[6][0][0][0])\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"scripts/train_seq2seq.py","file_name":"train_seq2seq.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"310537209","text":"import numpy as np\nimport torch\nfrom torch import nn\n\nfrom torchlibrosa.augmentation import SpecAugmentation\n\nclass Augment(nn.Module):\n def __init__(self):\n super(Augment, self).__init__()\n \n self.bn0 = nn.BatchNorm2d(64)\n self.bn1 = nn.BatchNorm2d(64)\n \n # self.spec_augmenter = SpecAugmentation(time_drop_width=8,\n # time_stripes_num=2,\n # freq_drop_width=8,\n # freq_stripes_num=2)\n \n def mixup(self, data, alpha=1, debug=False, weights=0.4):\n data = data.to('cpu').detach().numpy().copy()\n batch_size = len(data)\n #weights = np.random.beta(alpha, alpha, batch_size)\n index = np.random.permutation(batch_size)\n x1, x2 = data, data[index]\n x = np.array([x1[i] * weights + x2[i] * (1 - weights) for i in range(batch_size)])\n #y1 = np.array(one_hot_labels).astype(np.float)\n #y2 = np.array(np.array(one_hot_labels)[index]).astype(np.float)\n #y = np.array([y1[i] * weights[i] + y2[i] * (1 - weights[i]) for i in range(len(weights))])\n if debug:\n print('Mixup weights', weights)\n return torch.from_numpy(x).clone().cuda()\n \n def forward(self, x):\n x = x.transpose(1,3)\n x = self.bn0(x)\n x = x.transpose(1,3)\n x = self.mixup(x)\n #x = self.spec_augmenter(x)\n x = x.transpose(1,3)\n x = self.bn1(x)\n x = x.transpose(1,3)\n \n return x\n ","sub_path":"dcase2021/SSL-Efficientnet_Barlow_Twins_mixup_0.4_batchnorm/augment.py","file_name":"augment.py","file_ext":"py","file_size_in_byte":1575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"573598660","text":"#Cree un programa que lea un número y muestre si este es par o impar. Use funciones. Haga pruebas de escritorio.\n\n#Problema:\n#numero % 2 == 0 es par\n#numero % 2 != 0 es impar\n#numero = caracter o float es Error, ingrese solo numeros enteros\n\n#datos:\n#numero\n\n#solucion:\ntry: \n numero_entrada = int(input(\"Ingrese un numero, por favor: \")) #evita erroes (tratar de convertir caracteres o decimales en enteros)\nexcept:\n print(\"Ingrese solo numeros enteros\") \n exit()\n\ndef consultar_numero (numero):\n if numero % 2 == 0:\n print(\"Es par\")\n else: \n print(\"Es impar\") \n\nconsultar_numero(numero_entrada)\n\n\n","sub_path":"Sena/seccion4/par_impar2.py","file_name":"par_impar2.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"427886213","text":"from textwrap import dedent\n\nfrom flask_testing import TestCase\nfrom powonline import core, model\nfrom powonline.test.conftest import test_config\nfrom powonline.web import make_app\n\n\ndef here(localname):\n from os.path import join, dirname\n return join(dirname(__file__), localname)\n\n\nclass CommonTest(TestCase):\n\n SQLALCHEMY_DATABASE_URI = test_config().get(\n 'db', 'dsn'\n )\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n TESTING = True\n\n def create_app(self):\n config = test_config()\n config.read_string(dedent(\n '''\\\n [db]\n dsn = %s\n\n [security]\n jwt_secret = %s\n ''' % (\n CommonTest.SQLALCHEMY_DATABASE_URI,\n 'testing'\n )))\n return make_app(config)\n\n def setUp(self):\n with open(here('seed.sql')) as seed:\n model.DB.session.execute(seed.read())\n model.DB.session.commit()\n\n self.maxDiff = None\n self.session = model.DB.session # avoids unrelated diffs for this commit\n\n def tearDown(self):\n model.DB.session.remove()\n\n\nclass TestCore(CommonTest):\n\n def test_get_assignments(self):\n result = core.get_assignments(self.session)\n result_stations_a = {_.name for _ in result['stations']['route-blue']}\n result_stations_b = {_.name for _ in result['stations']['route-red']}\n result_teams_a = {_.name for _ in result['teams']['route-blue']}\n result_teams_b = {_.name for _ in result['teams']['route-red']}\n\n expected_stations_a = {'station-start', 'station-blue', 'station-end'}\n expected_stations_b = {'station-start', 'station-red', 'station-end'}\n expected_teams_a = {'team-blue'}\n expected_teams_b = {'team-red'}\n\n self.assertEqual(result_teams_a, expected_teams_a)\n self.assertEqual(result_teams_b, expected_teams_b)\n self.assertEqual(result_stations_a, expected_stations_a)\n self.assertEqual(result_stations_b, expected_stations_b)\n\n def test_scoreboard(self):\n result = list(core.scoreboard(self.session))\n expected = [\n ('team-red', 40),\n ('team-blue', 30),\n ('team-without-route', 0),\n ]\n self.assertEqual(result, expected)\n\n def test_questionnaire_scores(self):\n config = test_config()\n config.read_string(dedent(\n '''\\\n [questionnaire-map]\n questionnaire_1 = station-blue\n questionnaire_2 = station-red\n '''))\n result = core.questionnaire_scores(config, self.session)\n expected = {\n 'team-red': {\n 'station-blue': {\n 'name': 'questionnaire_1',\n 'score': 10\n },\n 'station-red': {\n 'name': 'questionnaire_2',\n 'score': 20\n }\n },\n 'team-blue': {\n 'station-blue': {\n 'name': 'questionnaire_1',\n 'score': 30\n }\n }\n }\n self.assertEqual(result, expected)\n\n def test_set_questionnaire_score(self):\n config = test_config()\n config.read_string(dedent(\n '''\\\n [questionnaire-map]\n questionnaire_1 = station-blue\n questionnaire_2 = station-red\n '''))\n _, result = core.set_questionnaire_score(\n config, self.session, 'team-red', 'station-blue', 40)\n self.assertEqual(result, 40)\n\n new_data = core.questionnaire_scores(config, self.session)\n expected = {\n 'team-red': {\n 'station-blue': {\n 'name': 'questionnaire_1',\n 'score': 40\n },\n 'station-red': {\n 'name': 'questionnaire_2',\n 'score': 20\n }\n },\n 'team-blue': {\n 'station-blue': {\n 'name': 'questionnaire_1',\n 'score': 30\n }\n }\n }\n self.assertEqual(new_data, expected)\n\n def test_global_dashboard(self):\n result = core.global_dashboard(self.session)\n expected = [\n {\n 'team': 'team-blue',\n 'stations': [{\n 'name': 'station-blue',\n 'score': 0,\n 'state': core.TeamState.UNKNOWN\n }, {\n 'name': 'station-end',\n 'score': 0,\n 'state': core.TeamState.UNKNOWN\n }, {\n 'name': 'station-red',\n 'score': 0,\n 'state': core.TeamState.UNREACHABLE\n }, {\n 'name': 'station-start',\n 'score': 0,\n 'state': core.TeamState.UNKNOWN\n }]\n }, {\n 'team': 'team-red',\n 'stations': [{\n 'name': 'station-blue',\n 'score': 0,\n 'state': core.TeamState.UNREACHABLE\n }, {\n 'name': 'station-end',\n 'score': 0,\n 'state': core.TeamState.ARRIVED\n }, {\n 'name': 'station-red',\n 'score': 0,\n 'state': core.TeamState.UNKNOWN\n }, {\n 'name': 'station-start',\n 'score': 10,\n 'state': core.TeamState.FINISHED\n }]\n }, {\n 'team': 'team-without-route',\n 'stations': [{\n 'name': 'station-blue',\n 'score': 0,\n 'state': core.TeamState.UNREACHABLE\n }, {\n 'name': 'station-end',\n 'score': 0,\n 'state': core.TeamState.UNREACHABLE\n }, {\n 'name': 'station-red',\n 'score': 0,\n 'state': core.TeamState.UNREACHABLE\n }, {\n 'name': 'station-start',\n 'score': 0,\n 'state': core.TeamState.UNREACHABLE\n }]\n }\n ]\n self.assertEqual(result, expected)\n\n\nclass TestTeam(CommonTest):\n\n def test_all(self):\n result = {_.name for _ in core.Team.all(self.session)}\n expected = {\n 'team-blue',\n 'team-red',\n 'team-without-route',\n }\n self.assertEqual(result, expected)\n\n def test_quickfilter_without_route(self):\n result = list(core.Team.quickfilter_without_route(self.session))\n self.assertEqual(len(result), 1)\n result = result[0].name\n expected = 'team-without-route'\n self.assertEqual(result, expected)\n\n def test_assigned_to_route(self):\n result = list(core.Team.assigned_to_route(self.session, 'route-blue'))\n self.assertEqual(len(result), 1)\n expected = 'team-blue'\n self.assertEqual(result[0].name, expected)\n\n def test_create_new(self):\n result = core.Team.create_new(self.session, {\n 'name': 'foo', 'email': 'foo@example.com'})\n self.assertEqual(result.name, 'foo')\n self.assertEqual(len(set(core.Team.all(self.session))), 4)\n self.assertIn(result, set(core.Team.all(self.session)))\n\n def test_upsert(self):\n core.Team.upsert(\n self.session, 'team-red', {'name': 'foo', 'contact': 'bar'})\n new_names = {_.name for _ in core.Team.all(self.session)}\n self.assertEqual(new_names, {'team-blue', 'team-without-route', 'foo'})\n\n def test_delete(self):\n result = core.Team.delete(self.session, 'team-red')\n self.assertEqual(len(set(core.Team.all(self.session))), 2)\n self.assertIsNone(result)\n\n def test_get_station_data(self):\n result1 = core.Team.get_station_data(self.session,\n 'team-red', 'station-start')\n result2 = core.Team.get_station_data(self.session,\n 'team-blue', 'station-finish')\n expected1 = core.TeamState.FINISHED\n expected2 = core.TeamState.UNKNOWN\n self.assertEqual(result1.state, expected1)\n self.assertEqual(result2.state, expected2)\n\n def test_advance_on_station(self):\n new_state = core.Team.advance_on_station(\n self.session, 'team-red', 'station-start')\n self.assertEqual(new_state, core.TeamState.UNKNOWN)\n new_state = core.Team.advance_on_station(\n self.session, 'team-red', 'station-start')\n self.assertEqual(new_state, core.TeamState.ARRIVED)\n new_state = core.Team.advance_on_station(\n self.session, 'team-red', 'station-start')\n self.assertEqual(new_state, core.TeamState.FINISHED)\n new_state = core.Team.advance_on_station(\n self.session, 'team-red', 'station-start')\n self.assertEqual(new_state, core.TeamState.UNKNOWN)\n\n\nclass TestStation(CommonTest):\n\n def test_all(self):\n result = {_.name for _ in core.Station.all(self.session)}\n expected = {\n 'station-start',\n 'station-red',\n 'station-blue',\n 'station-end',\n }\n self.assertEqual(result, expected)\n\n def test_create_new(self):\n result = core.Station.create_new(self.session, {'name': 'foo'})\n self.assertEqual(result.name, 'foo')\n self.assertEqual(len(set(core.Station.all(self.session))), 5)\n self.assertIn(result, set(core.Station.all(self.session)))\n\n def test_upsert(self):\n core.Station.upsert(self.session,\n 'station-red',\n {'name': 'foo', 'contact': 'bar'})\n result = core.Station.all(self.session)\n names = {_.name for _ in result}\n self.assertEqual(names, {\n 'station-end', 'foo', 'station-start', 'station-blue'})\n\n def test_delete(self):\n result = core.Station.delete(self.session, 'station-red')\n self.assertEqual(len(set(core.Station.all(self.session))), 3)\n self.assertIsNone(result)\n\n def test_assign_user(self):\n result = core.Station.accessible_by(self.session, 'john')\n self.assertEqual(result, set())\n result = core.Station.assign_user(self.session, 'station-red', 'john')\n self.assertTrue(result)\n result = core.Station.accessible_by(self.session, 'john')\n self.assertEqual(result, {'station-red'})\n\n def test_team_states(self):\n result = set(core.Station.team_states(self.session, 'station-start'))\n expected = {('team-blue', core.TeamState.UNKNOWN, None),\n ('team-red', core.TeamState.FINISHED, 10)}\n self.assertEqual(result, expected)\n\n\nclass TestRoute(CommonTest):\n\n def test_all(self):\n result = {_.name for _ in core.Route.all(self.session)}\n expected = {\n 'route-blue',\n 'route-red'\n }\n self.assertEqual(result, expected)\n\n def test_create_new(self):\n result = core.Route.create_new(self.session, {'name': 'foo'})\n stored_data = set(core.Route.all(self.session))\n self.assertEqual(result.name, 'foo')\n self.assertEqual(len(stored_data), 3)\n self.assertIn(result, set(stored_data))\n\n def test_upsert(self):\n core.Route.upsert(\n self.session, 'route-red', {'name': 'foo'})\n result = core.Route.upsert(\n self.session, 'foo', {'name': 'bar'})\n stored_data = set(core.Route.all(self.session))\n self.assertEqual(result.name, 'bar')\n self.assertEqual(len(stored_data), 2)\n self.assertIn(result, set(stored_data))\n\n def test_delete(self):\n result = core.Route.delete(self.session, 'route-red')\n self.assertEqual(len(set(core.Route.all(self.session))), 1)\n self.assertIsNone(result)\n\n def test_assign_team(self):\n result = core.Route.assign_team(\n self.session, 'route-red', 'team-without-route')\n self.assertTrue(result)\n result = {_.name for _ in core.Team.assigned_to_route(\n self.session, 'route-red')}\n self.assertEqual({'team-red', 'team-without-route'}, result)\n\n def test_unassign_team(self):\n result = core.Route.unassign_team(\n self.session, 'route-red', 'team-red')\n self.assertTrue(result)\n result = set(core.Team.assigned_to_route(self.session, 'route-red'))\n self.assertEqual(set(), result)\n\n def test_assign_station(self):\n result = core.Route.assign_station(self.session,\n 'route-red', 'station-blue')\n self.assertTrue(result)\n result = {_.name for _ in core.Station.assigned_to_route(\n self.session, 'route-red')}\n self.assertEqual({'station-start', 'station-end',\n 'station-red', 'station-blue'}, result)\n\n def test_unassign_station(self):\n result = core.Route.unassign_station(self.session,\n 'route-red', 'station-red')\n self.assertTrue(result)\n result = set(core.Station.assigned_to_route(self.session, 'route-red'))\n self.assertNotIn(set(), result)\n\n\nclass TestUser(CommonTest):\n\n def test_assign_role(self):\n core.User.assign_role(self.session, 'jane', 'a-role')\n result = {_.name for _ in core.User.roles(self.session, 'jane')}\n self.assertIn('a-role', result)\n\n def test_unassign_role(self):\n core.User.unassign_role(self.session, 'john', 'a-role')\n result = {_.name for _ in core.User.roles(self.session, 'john')}\n self.assertNotIn('a-role', result)\n","sub_path":"powonline/test/test_core.py","file_name":"test_core.py","file_ext":"py","file_size_in_byte":13968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"318464510","text":"#!/usr/bin/env python3\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, 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 importlib.util\nimport logging\nimport os.path\nimport shutil\nimport sys\nimport yaml\n\n# Needs 3.4 or higher to work\nif sys.version_info <= (3, 3):\n print(\"This script requires Python 3.4 or higher in order to work!\")\n sys.exit(-1)\n\n# Backend needs 3.8 or higher, warn if not found.\nif sys.version_info < (3, 7, 3):\n print(\n \"Warning: Pony Mail Foal requires Python 3.7.3 or higher for backend operations.\"\n )\n print(\n \"You will be able to run the setup using this version (%u.%u), but will need >=3.7.3\"\n % (sys.version_info.major, sys.version_info.minor)\n )\n print(\"for operating the UI backend server.\")\n\nDEFAULT_DB_URL = \"http://localhost:9200/\"\ndburl = \"\"\ndbname = \"\"\nmlserver = \"\"\nmldom = \"\"\nwc = \"\"\ngenname = \"\"\nwce = False\nshards = 0\nreplicas = -1\nnonce = None\nsupported_generators = [\"dkim\", \"full\"]\n\n\ndef create_indices():\n \"\"\"Creates new indices for a fresh pony mail installation, it possible\"\"\"\n # Check if index already exists\n if es.indices.exists(dbname + \"-mbox\"):\n if args.soe:\n print(\n \"ElasticSearch indices with prefix '%s' already exists and SOE set, exiting quietly\"\n % dbname\n )\n sys.exit(0)\n else:\n print(\n \"Error: Existing ElasticSearch indices with prefix '%s' already exist!\"\n % dbname\n )\n sys.exit(-1)\n\n print(f\"Creating indices {dbname}-*...\")\n\n settings = {\"number_of_shards\": shards, \"number_of_replicas\": replicas}\n mapping_file = yaml.safe_load(open(\"mappings.yaml\", \"r\"))\n for index, mappings in mapping_file.items():\n res = es.indices.create(\n index=f\"{dbname}-{index}\", body={\"mappings\": mappings, \"settings\": settings}\n )\n\n print(f\"Index {dbname}-{index} created! %s \" % res)\n\n\n# Check for all required Python packages\nwanted_pkgs = [\n \"elasticsearch\", # used by setup.py, archiver.py and elastic.py\n \"formatflowed\", # used by archiver.py\n \"netaddr\", # used by archiver.py\n \"certifi\", # used by archiver.py and elastic.py\n]\n\nmissing_pkgs = list(wanted_pkgs) # copy to avoid corruption\nfor pkg in wanted_pkgs:\n if importlib.util.find_spec(pkg):\n missing_pkgs.remove(pkg)\n\nif missing_pkgs:\n print(\"It looks like you need to install some Python modules first\")\n print(\"The following packages are required: \")\n for pkg in missing_pkgs:\n print(\" - %s\" % pkg)\n print(\"You may use your package manager, or run the following command:\")\n print(\"pip3 install %s\" % \" \".join(missing_pkgs))\n sys.exit(-1)\n\n\n# at this point we can assume elasticsearch is present\nfrom elasticsearch import VERSION as ES_VERSION\nfrom elasticsearch import ConnectionError as ES_ConnectionError\nfrom elasticsearch import Elasticsearch, ElasticsearchException\n\nES_MAJOR = ES_VERSION[0]\n\n# CLI arg parsing\nparser = argparse.ArgumentParser(description=\"Command line options.\")\n\nparser.add_argument(\n \"--defaults\", dest=\"defaults\", action=\"store_true\", help=\"Use default settings\"\n)\nparser.add_argument(\n \"--devel\", dest=\"devel\", action=\"store_true\", help=\"Use developer settings (shards=1, replicas=0)\"\n)\nparser.add_argument(\n \"--clobber\",\n dest=\"clobber\",\n action=\"store_true\",\n help=\"Allow overwrite of ponymail.yaml & ../site/api/lib/config.lua (default: create *.tmp if either exists)\",\n)\nparser.add_argument(\"--dburl\", dest=\"dburl\", type=str, help=\"ES backend URL\")\nparser.add_argument(\"--dbname\", dest=\"dbname\", type=str, help=\"ES DB prefix\")\nparser.add_argument(\"--dbshards\", dest=\"dbshards\", type=int, help=\"DB Shard Count\")\nparser.add_argument(\n \"--dbreplicas\", dest=\"dbreplicas\", type=int, help=\"DB Replica Count\"\n)\nparser.add_argument(\n \"--mailserver\",\n dest=\"mailserver\",\n type=str,\n help=\"Host name of outgoing mail server\",\n)\nparser.add_argument(\n \"--mldom\", dest=\"mldom\", type=str, help=\"Domains to accept mail for via UI\"\n)\nparser.add_argument(\n \"--wordcloud\", dest=\"wc\", action=\"store_true\", help=\"Enable word cloud\"\n)\nparser.add_argument(\n \"--skiponexist\",\n dest=\"soe\",\n action=\"store_true\",\n help=\"Skip setup if ES index exists\",\n)\nparser.add_argument(\n \"--noindex\",\n dest=\"noi\",\n action=\"store_true\",\n help=\"Don't create ElasticSearch indices, assume they exist\",\n)\nparser.add_argument(\n \"--nocloud\", dest=\"nwc\", action=\"store_true\", help=\"Do not enable word cloud\"\n)\nparser.add_argument(\n \"--generator\",\n dest=\"generator\",\n type=str,\n help=\"Document ID Generator to use (dkim, full)\",\n)\nparser.add_argument(\n \"--nonce\",\n dest=\"nonce\",\n type=str,\n help=\"Cryptographic nonce to use if generator is DKIM/RFC-6376 (--generator dkim)\",\n)\nargs = parser.parse_args()\n\nprint(\"\")\nprint(\"Welcome to the Pony Mail setup script!\")\nprint(\"Let's start by determining some settings...\")\nprint(\"\")\n\n\n# If called with --defaults (like from Docker), use default values\nif args.defaults:\n dburl = DEFAULT_DB_URL\n dbname = \"ponymail\"\n mlserver = \"localhost\"\n mldom = \"example.org\"\n wc = \"Y\"\n wce = True\n shards = 3\n replicas = 1\n genname = \"dkim\"\n urlPrefix = \"\"\n nonce = None\n\nif args.devel:\n dburl = DEFAULT_DB_URL\n dbname = \"ponymail\"\n mlserver = \"localhost\"\n mldom = \"example.org\"\n wc = \"Y\"\n wce = True\n shards = 1\n replicas = 0\n genname = \"dkim\"\n urlPrefix = \"\"\n nonce = None\n\n# Accept CLI args, copy them\nif args.dburl:\n dburl = args.dburl\nif args.dbname:\n dbname = args.dbname\nif args.mailserver:\n mlserver = args.mailserver\nif args.mldom:\n mldom = args.mldom\nif args.wc:\n wc = args.wc\nif args.nwc:\n wc = \"n\"\n wce = False\nif args.dbshards:\n shards = args.dbshards\nif args.dbreplicas is not None: # Allow for 0 value\n replicas = args.dbreplicas\nif args.generator:\n if all(x in supported_generators for x in args.generator.split(' ')):\n genname = args.generator\n else:\n sys.stderr.write(\n \"Invalid generator specified. Must be one of: \"\n + \", \".join(supported_generators)\n + \"\\n\"\n )\n sys.exit(-1)\nif args.generator and any(x == \"dkim\" for x in args.generator.split(' ')) and args.nonce is not None:\n nonce = args.nonce\n\nif not dburl:\n dburl = input(\"What is the URL of the ElasticSearch server? [%s]: \" % DEFAULT_DB_URL)\n if not dburl:\n dburl = DEFAULT_DB_URL\n\nif not dbname:\n dbname = input(\"What would you like to call the mail index [ponymail]: \")\n if not dbname:\n dbname = \"ponymail\"\n\nif not mlserver:\n mlserver = input(\n \"What is the hostname of the outgoing mailserver hostname? [localhost]: \"\n )\n if not mlserver:\n mlserver = \"localhost\"\n\nif not mldom:\n mldom = input(\"Which domains would you accept mail to from web-replies? [*]: \")\n if not mldom:\n mldom = \"*\"\n\nwhile wc.lower() not in [\"y\", \"n\"]:\n wc = input(\"Would you like to enable the word cloud feature? (Y/N) [Y]: \").lower()\n if not wc:\n wc = \"y\"\n if wc.lower() == \"y\":\n wce = True\n\nwhile genname == \"\":\n print(\"Please select a document ID generator:\")\n print(\n \"1 [RECOMMENDED] DKIM/RFC-6376: Short SHA3 hash useful for cluster setups with permalink usage\"\n )\n print(\n \"2 FULL: Full message digest with MTA trail. Not recommended for clustered setups.\"\n )\n try:\n ans = input(\"Please select a generator (1 or 2) [1]: \")\n if ans:\n gno = int(ans)\n else:\n gno = 1\n if gno <= len(supported_generators) and supported_generators[gno - 1]:\n genname = supported_generators[gno - 1]\n except ValueError:\n pass\n\nif genname == \"dkim\" and (nonce is None and not args.defaults and not args.devel):\n print(\n \"DKIM hasher chosen. It is recommended you set a cryptographic nonce for this generator, though not required.\"\n )\n print(\n \"If you set a nonce, you will need this same nonce for future installations if you intend to preserve \"\n )\n print(\"permalinks from imported messages.\")\n nonce = (\n input(\"Enter your nonce or hit [enter] to continue without a nonce: \") or None\n )\n\nwhile shards < 1:\n try:\n ans = input(\"How many shards for the ElasticSearch index? [3]: \")\n if ans:\n shards = int(ans)\n else:\n shards = 3\n except ValueError:\n pass\n\nwhile replicas < 0:\n try:\n ans = input(\"How many replicas for each shard? [1]: \")\n if ans:\n replicas = int(ans)\n else:\n replicas = 1\n except ValueError:\n pass\n\nprint(\"Okay, I got all I need, setting up Pony Mail...\")\n\n# we need to connect to database to determine the engine version\nes = Elasticsearch(\n [dburl],\n max_retries=5,\n retry_on_timeout=True,\n)\n\n# elasticsearch logs lots of warnings on retries/connection failure\nlogging.getLogger(\"elasticsearch\").setLevel(logging.ERROR)\n\ntry:\n DB_VERSION = es.info()[\"version\"][\"number\"]\nexcept ES_ConnectionError:\n print(\"WARNING: Connection error: could not determine the engine version.\")\n DB_VERSION = \"0.0.0\"\n\nDB_MAJOR = int(DB_VERSION.split(\".\")[0])\nprint(\n \"Versions: library %d (%s), engine %d (%s)\"\n % (ES_MAJOR, \".\".join(map(str, ES_VERSION)), DB_MAJOR, DB_VERSION)\n)\nif DB_MAJOR < 7:\n print(\"This version of Pony Mail requires ElasticSearch 7.x or higher\")\n\nif not DB_MAJOR == ES_MAJOR:\n print(\"WARNING: library version does not agree with engine version!\")\n\nif DB_MAJOR == 0: # not known\n if args.noi:\n # allow setup to be used without engine running\n print(\n \"Could not determine the engine version. Assume it is the same as the library version.\"\n )\n DB_MAJOR = ES_MAJOR\n else:\n # if we cannot connect to get the version, we cannot create the index later\n print(\"Could not connect to the engine. Fatal.\")\n sys.exit(1)\n\nif not args.noi:\n try:\n create_indices()\n except ElasticsearchException as e:\n print(\"Index creation failed: %s\" % e)\n sys.exit(1)\n\nponymail_cfg = \"archiver.yaml\"\nif not args.clobber and os.path.exists(ponymail_cfg):\n print(\"%s exists and clobber is not set\" % ponymail_cfg)\n ponymail_cfg = \"archiver.yaml.tmp\"\n\nprint(\"Writing importer config (%s)\" % ponymail_cfg)\n\nwith open(ponymail_cfg, \"w\") as f:\n f.write(\n \"\"\"\n---\n###############################################################\n# An archiver.yaml is needed to run this project. This sample config file was\n# originally generated by tools/setup.py.\n# \n# Run the tools/setup.py script and an archiver.yaml which looks a lot like this \n# one will be generated. If, for whatever reason, that script is not working \n# for you, you may use this archiver.yaml as a starting point.\n# \n# Contributors should strive to keep this sample updated. One way to do this \n# would be to run the tools/setup.py, rename the generated config to\n# archiver.yaml.sample, and then pasting this message or a modified form of \n# this message at the top.\n###############################################################\n\n###############################################################\n# Pony Mail Archiver Configuration file\n\n\n# Main ES configuration\nelasticsearch:\n dburl: %s\n dbname: %s\n #wait: active shard count\n #backup: database name\n\narchiver:\n #generator: dkim|full (dkim recommended)\n generator: %s\n nonce: %s\n policy: default # message parsing policy: default, compat32, smtputf8\n\ndebug:\n #cropout: string to crop from list-id\n\n \"\"\"\n % (dburl, dbname, genname, nonce or \"~\")\n )\n\nprint(\"Copying sample JS config to config.js (if needed)...\")\nif not os.path.exists(\"../site/js/config.js\") and os.path.exists(\n \"../site/js/config.js.sample\"\n):\n shutil.copy(\"../site/js/config.js.sample\", \"../site/js/config.js\")\n\nserver_cfg = \"../server/ponymail.yaml\"\nif not args.clobber and os.path.exists(server_cfg):\n print(\"%s exists and clobber is not set\" % server_cfg)\n server_cfg = \"../server/ponymail.yaml.tmp\"\n\nprint(\"Writing UI backend configuration file %s\" % server_cfg)\nwith open(server_cfg, \"w\") as f:\n f.write(\"\"\"\nserver:\n port: 8080 # Port to bind to\n bind: 127.0.0.1 # IP to bind to - typically 127.0.0.1 for localhost or 0.0.0.0 for all IPs\n\n\ndatabase:\n dburl: %s # The URL of the ElasticSearch database\n db_prefix: %s # DB prefix, usually 'ponymail'\n max_hits: 15000 # Maximum number of emails to process in a search\n pool_size: 15 # number of connections for async queries\n max_lists: 8192 # max number of lists to allow for\n\nui:\n wordcloud: %s\n mailhost: %s\n sender_domains: \"%s\"\n traceback: true\n mgmtconsole: true # enable email admin\n true_gdpr: true # fully delete emails instead of marking them deleted\n\ntasks:\n refresh_rate: 150 # Background indexer run interval, in seconds\n\n# Fill in OAuth data as needed\noauth:\n# If using OAuth, set the authoritative domains here. These are the OAuth domains that \n# will provide access to private emails.\n# authoritative_domains:\n# - googleapis.com # OAuth via google is authoritative\n# - github.com # GitHub OAuth is authoritative\n# admins:\n# - foo@example.org\n google_client_id: ~\n github_client_id: ~\n github_client_secret: ~\n\n\"\"\" % (dburl, dbname, \"true\" if wce else \"false\", mlserver, mldom))\n\n\nprint(\"All done, Pony Mail should...work now :)\")\nprint(\n \"If you are using an external mail inbound server, \\nmake sure to copy the contents of this tools directory to it\"\n)\n","sub_path":"tools/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":14623,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"551823763","text":"# initialize gp model\nimport kernels\nimport gp\nimport numpy as np\n\nkernel = kernels.two_plus_three_body\nkernel_grad = kernels.two_plus_three_body_grad\nhyps = np.array([1, 1, 0.1, 1, 1e-3]) # sig2, ls2, sig3, ls3, noise std\ncutoffs = np.array([4.9, 4.9]) # (don't need to optimize for lab)\nenergy_force_kernel = kernels.two_plus_three_force_en\n\ngp_model = gp.GaussianProcess(kernel, kernel_grad, hyps, cutoffs,\n energy_force_kernel=energy_force_kernel)\n\n# import calculator and set potential\nimport os\nfrom ase.calculators.espresso import Espresso\npot_file = os.environ.get('LAMMPS_POTENTIALS') + '/Al_zhou.eam.alloy'\npseudopotentials = {'Al': pot_file}\ninput_data = {\n 'system': {\n 'ecutwfc': 29,\n 'ecutrho': 143\n },\n 'disk_io': 'low'}\ncalc = Espresso(pseudopotentials = pseudopotentials, tstress = True, tprnfor = True, kpts = (4, 4, 1), input_data = input_data)\n\n#create structure as FCC surface with addsorbate\nfrom ase.build import fcc111, add_adsorbate\nslab = fcc111('Al', size=(2, 2, 3))\nadd_adsorbate(slab, 'Al', 2, 'hcp')\nslab.center(vacuum=5.0, axis=2)\n\n#view and set calculator\nfrom ase.visualize import view\nview(slab, viewer='x3d')\nslab.set_calculator(calc)\nprint(slab.get_potential_energy())\n\n\n# make training structure\nimport struc\n\ntraining_struc = struc.Structure(cell=slab.cell,\n species=['Al']*len(slab),\n positions=slab.positions)\ntraining_forces = slab.get_forces()\n\n# add atoms to training database\ngp_model.update_db(training_struc, training_forces)\ngp_model.set_L_alpha()\n\n# wrap in ASE calculator\nfrom gp_calculator import GPCalculator\n\ngp_calc = GPCalculator(gp_model)\n\n# test on training structure\nslab.set_calculator(gp_calc)\nGP_forces = slab.get_forces()\n\n# check accuracy by making a parity plot\nimport matplotlib.pyplot as plt\n\nplt.plot(training_forces.reshape(-1), GP_forces.reshape(-1), '.')\nplt.show()","sub_path":"Lab 5/NEBGP.py","file_name":"NEBGP.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"554146522","text":"# -*- coding: utf-8 -*-\n\nimport uuid\nfrom typing import NoReturn, Optional, Union, List\nfrom coupling.dict import pick\nfrom .constants import CALLEE_KEY\nfrom .events import TestEventHandler\nfrom .util import str_class, pick_callee_kwargs\nfrom .serializer import DictSerializable\n\nimport logging\nlogger = logging.getLogger(__name__)\n\n\nclass TestBench(TestEventHandler, DictSerializable):\n \"\"\"\n Used to store test resource in whole test life cycle.\n It inherit from TestEventHandler, so any hook methods are supported.\n\n Parameters\n ----------\n name: str\n test bench name\n\n type: str\n test bench type, could be set as product or project name.\n\n exclusive: bool, optional\n Set according to relevance with hardware.\n If is True, a test bench can only be used for one test process.\n\n routes: tuple or list, optional\n Used by integrating with test platform.\n This testbench will only consume messages with specified routes from RabbitMQ.\n\n node: str, optional\n The machine info which testbench running on\n \"\"\"\n\n def __init__(self,\n name: str,\n type: str,\n exclusive: bool = False,\n routes: Union[list, tuple, str] = None,\n node: str = None\n ) -> NoReturn:\n super().__init__()\n self.name = name\n self.type = type\n self.node = node or '{:x}'.format(uuid.getnode())\n self.exclusive = exclusive\n if isinstance(routes, str):\n self.routes = self.get_routes_from_string(routes)\n else:\n self.routes = routes or []\n\n @staticmethod\n def get_routes_from_string(s: str, separator: str = \",\") -> Optional[List[str]]:\n \"\"\"\n Parse routes from string.\n\n Parameters\n ----------\n s: str\n routes string\n\n separator: str, optional\n separator char, default is ','\n\n Returns\n -------\n list or None\n list include separated routes string, or None if provided parameter s is empty.\n \"\"\"\n if s:\n return [route.strip() for route in s.split(separator)]\n else:\n return None\n\n def open(self) -> NoReturn:\n \"\"\"\n Hook method for opening testbench.\n \"\"\"\n pass\n\n def close(self) -> NoReturn:\n \"\"\"\n Hook method for closing testbench.\n \"\"\"\n pass\n\n def __str__(self):\n return ''.format(self.name, self.type)\n\n def as_dict(self):\n d = pick(self.__dict__, keys=['name', 'node', 'type', 'exclusive', 'routes'])\n d[CALLEE_KEY] = str_class(self.__class__)\n return d\n\n @classmethod\n def from_dict(cls, data: dict):\n kwargs = pick_callee_kwargs(cls, data)\n return cls(**kwargs)\n","sub_path":"ngta/bench.py","file_name":"bench.py","file_ext":"py","file_size_in_byte":2870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"531809622","text":"\"\"\"Flood It!, by Al Sweigart al@inventwithpython.com\n\nA colorful game where you try to fill the board with a single color.\"\"\"\n__version__ = 1\n\n# TODO - add instructions, and make sure the last move's effects are visible\n\nimport random, sys\n\ntry:\n import bext\nexcept ImportError:\n print('''This program requires the bext module, which you can\ninstall by opening a Terminal window (on macOS & Linux) and running:\n\n python3 -m pip install --user bext\n\nor a Command Prompt window (on Windows) and running:\n\n python -m pip install --user bext''')\n sys.exit()\n\n# Setup the constants:\nBLOCK = chr(9608) # Character 9608 is '█'\nLEFTRIGHT = chr(9472) # Character 9472 is '─'\nUPDOWN = chr(9474) # Character 9474 is '│'\nDOWNRIGHT = chr(9484) # Character 9484 is '┌'\nDOWNLEFT = chr(9488) # Character 9488 is '┐'\nUPRIGHT = chr(9492) # Character 9492 is '└'\nUPLEFT = chr(9496) # Character 9496 is '┘'\n\n# This constant maps letters to colors.\nCMAP = {'R': 'red', 'G': 'green', 'B': 'blue',\n 'Y': 'yellow', 'C': 'cyan', 'P': 'purple'}\nCOLORS = list(CMAP.keys())\n\n\ndef main():\n \"\"\"Run a single game of Flood It.\"\"\"\n bext.fg('white')\n print('''FLOOD IT!\nBy Al Sweigart al@inventwithpython.com\n\nSet the color of the upper left square, which fills in all the\nadjacent squares of that color. Try to make the entire board the\nsame color.''')\n gameBoard = getNewBoard()\n movesLeft = 20\n\n while True: # Main game loop.\n displayBoard(gameBoard)\n\n print('Moves left:', movesLeft)\n playerMove = getPlayerMove()\n changeTile(playerMove, gameBoard, 0, 0)\n movesLeft -= 1\n\n if hasWon(gameBoard):\n displayBoard(gameBoard)\n print('You have won!')\n break\n elif movesLeft == 0:\n print('You have run out of moves!')\n break\n # At this point, go back to the start of the main game loop.\n\n\ndef getNewBoard(width=16, height=16):\n \"\"\"Return a dictionary of a new Flood It board.\"\"\"\n assert width > 1 and height > 1\n board = []\n\n # Create random colors for the board.\n for x in range(height):\n column = []\n for y in range(width):\n column.append(random.choice(COLORS))\n board.append(column)\n\n # Make several tiles the same color as their neighbor.\n for i in range(width * height):\n x = random.randint(0, width - 2)\n y = random.randint(0, height - 1)\n board[x + 1][y] = board[x][y]\n return board\n\n\ndef displayBoard(board):\n \"\"\"Display the board on the screen.\"\"\"\n width = len(board)\n height = len(board[0])\n bext.fg('white')\n print(DOWNRIGHT + (LEFTRIGHT * width) + DOWNLEFT)\n\n # Print first row with '>'.\n bext.fg('white')\n print('>', end='')\n for x in range(width):\n bext.fg(CMAP[board[x][0]])\n print(BLOCK, end='')\n bext.fg('white')\n print(UPDOWN)\n\n # Print each row after the first.\n for y in range(1, height):\n bext.fg('white')\n print(UPDOWN, end='')\n for x in range(width):\n bext.fg(CMAP[board[x][y]])\n print(BLOCK, end='')\n bext.fg('white')\n print(UPDOWN)\n bext.fg('white')\n print(UPRIGHT + (LEFTRIGHT * width) + UPLEFT)\n\n\ndef getPlayerMove():\n \"\"\"Let the player select a color to paint the upper left tile.\"\"\"\n while True:\n bext.fg('white')\n print('Choose one of ', end='')\n bext.fg('red')\n print('R ', end='')\n bext.fg('green')\n print('G ', end='')\n bext.fg('blue')\n print('B ', end='')\n bext.fg('yellow')\n print('Y ', end='')\n bext.fg('cyan')\n print('C ', end='')\n bext.fg('purple')\n print('P ', end='')\n bext.fg('white')\n print(' or quit:')\n move = input().upper()\n if move == 'QUIT':\n sys.exit()\n if move in COLORS:\n return move\n # At this point, go back to the start of the loop.\n\n\ndef changeTile(move, board, x, y, charToChange=None):\n \"\"\"Change the color of a tile.\"\"\"\n if x == 0 and y == 0:\n charToChange = board[x][y]\n if move == charToChange:\n return # Already is the same color.\n\n board[x][y] = move\n\n width = len(board)\n height = len(board[0])\n\n if x > 0 and board[x - 1][y] == charToChange:\n changeTile(move, board, x - 1, y, charToChange)\n if y > 0 and board[x][y - 1] == charToChange:\n changeTile(move, board, x, y - 1, charToChange)\n if x < width - 1 and board[x + 1][y] == charToChange:\n changeTile(move, board, x + 1, y, charToChange)\n if y < height - 1 and board[x][y + 1] == charToChange:\n changeTile(move, board, x, y + 1, charToChange)\n\n\ndef hasWon(board):\n \"\"\"Return True if the entire board is one color.\"\"\"\n tile = board[0][0]\n width = len(board)\n height = len(board[0])\n\n for x in range(width):\n for y in range(height):\n if board[x][y] != tile:\n return False\n return True\n\n\n# If this program was run (instead of imported), run the game:\nif __name__ == '__main__':\n main()\n","sub_path":"src/gamesbyexample/floodit.py","file_name":"floodit.py","file_ext":"py","file_size_in_byte":5137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"98973121","text":"from collections import OrderedDict\nimport unittest\nfrom typing import List\nfrom pprint import pprint\n\n\nclass ListNode:\n def __init__(self, k, v, prev=None, nxt=None):\n self.k = k\n self.v = v\n self.prev = prev\n self.nxt = nxt\n\n\nclass LRUCache:\n\n def __init__(self, capacity: int):\n self._cap = capacity\n self._cache = OrderedDict()\n\n def get(self, key: int) -> int:\n if key not in self._cache:\n return -1\n v = self._cache[key]\n del self._cache[key]\n self._cache[key] = v\n return v\n\n def put(self, key: int, value: int) -> None:\n if key in self._cache:\n del self._cache[key]\n else:\n if len(self._cache) == self._cap:\n lru = next(iter(self._cache.keys()))\n del self._cache[lru]\n self._cache[key] = value\n\n\nclass LRUCache1:\n\n def __init__(self, capacity: int):\n self._cap = capacity\n self._size = 0\n self.map = {}\n self.ll = ListNode(None, None)\n self.tail = None\n\n def _evit(self):\n if self._size == 0:\n return\n\n self._size -= 1\n self.map.pop(self.tail.k)\n prev = self.tail.prev\n if prev is self.ll:\n self.tail = None\n prev.nxt = None\n self.tail = prev\n\n def _get(self, key: int) -> ListNode:\n node = self.map[key]\n if node is not self.ll.nxt:\n prev, nxt = node.prev, node.nxt\n prev.nxt = nxt\n if nxt:\n nxt.prev = prev\n old_head = self.ll.nxt\n node.prev, node.nxt = self.ll, old_head\n self.ll.nxt, old_head.prev = node, node\n if node is self.tail:\n self.tail = prev\n else:\n pass\n\n return node\n\n def get(self, key: int) -> int:\n if key not in self.map:\n return -1\n return self._get(key).v\n\n def put(self, key: int, value: int) -> None:\n if key in self.map:\n node = self._get(key)\n node.v = value\n return\n\n if self._size == self._cap:\n self._evit()\n\n h = ListNode(key, value, self.ll, self.ll.nxt)\n self.map[key] = h\n if self._size > 0:\n self.ll.nxt.prev = h\n self.ll.nxt = h\n self._size += 1\n else:\n self._size = 1\n self.ll.nxt = h\n self.tail = h\n\n\nclass TestSolution(unittest.TestCase):\n\n def test_case_1(self):\n lRUCache = LRUCache(2)\n lRUCache.put(1, 1)\n lRUCache.put(2, 2)\n self.assertEqual(lRUCache.get(1), 1)\n # LRU key was 2, evicts key 2, cache is {1 = 1, 3 = 3}\n lRUCache.put(3, 3)\n self.assertEqual(lRUCache.get(2), -1)\n # LRU key was 1, evicts key 1, cache is {4 = 4, 3 = 3}\n lRUCache.put(4, 4)\n self.assertEqual(lRUCache.get(1), -1) # return -1 (not found)\n self.assertEqual(lRUCache.get(3), 3)\n self.assertEqual(lRUCache.get(4), 4)\n\n # def test_edge_case_1(self):\n # s = Solution()\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"Week_08/146_lru_cache.py","file_name":"146_lru_cache.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"513078593","text":"import sys\nfor unos in sys.stdin:\n unos=unos.replace(\"\\n\",\"\")\n if unos==\"0 0 0 0\":\n break\n else:\n rj=1080\n brojevi=unos.split(\" \")\n for i in range(0,4):\n brojevi[i]=int(brojevi[i])\n if brojevi[i]==0:\n brojevi[i]+=40\n \n (pocetak,broj1,broj2,broj3)=(brojevi[0],brojevi[1],brojevi[2],brojevi[3])\n if(pocetak-broj1)< 0:\n rj=rj+9*((pocetak-broj1)+40)\n else:\n rj=rj+9*(pocetak-broj1)\n if(broj2-broj1)< 0:\n rj=rj+9*((broj2-broj1)+40)\n else:\n rj=rj+9*(broj2-broj1)\n if(broj2-broj3)< 0:\n rj=rj+9*((broj2-broj3)+40)\n else:\n rj=rj+9*(broj2-broj3)\n print(\"{}\".format(rj))\n ","sub_path":"uva10550.py","file_name":"uva10550.py","file_ext":"py","file_size_in_byte":779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"543306778","text":"import hashlib\r\nimport requests\r\nimport json\r\nimport gspread\r\nfrom datetime import datetime\r\n\r\nspreadsheet_key = '1Ud-UnGvsSFwrUZu8fKktKHDaK38y_ubLh07AS57AEKg'; # ключ таблицы, в которой работаем\r\ngc = gspread.service_account(filename = 'credentials.json')\r\nsh = gc.open_by_key(spreadsheet_key)\r\nws = sh.sheet1\r\nregistrations_file = '/var/www/u1417944/data/www/nashagai.xyz/registrations.json' #файл с данными после регистрации. Последний апдейт 08.07 12:38\r\n\r\ndef get_ids(): #Создаём список id\r\n\tuser_ids = []\r\n\tJ_users = ws.col_values(10)\r\n\tP_users = ws.col_values(16)\r\n\tfor i in range(max(len(J_users), len(P_users))):\r\n\t\tif J_users[i] != '':\r\n\t\t\tuser_ids.append(J_users[i])\r\n\t\telse:\r\n\t\t\tuser_ids.append(P_users[i])\r\n\treturn user_ids[1:]\r\n\r\ndef open_file():\r\n\twith open(registrations_file, 'r') as f:\r\n\t\treg_data = json.load(f)\r\n\tnow = datetime.now()\r\n\tdt_string = now.strftime(\"%d-%m %H.%M.%S\")\r\n\tfname = '/var/www/u1417944/data/www/nashagai.xyz/registrations ' + dt_string + '.json'\r\n\twith open(fname, 'w') as f:\r\n\t\tjson.dump(reg_data, f)\r\n\treturn reg_data\r\n\r\ndef main():\r\n\tuser_ids = get_ids()\r\n\tupd_payload = [[] for i in range(len(user_ids))]\r\n\treg_data = open_file()\r\n\t# Добавляем данные в update_payload\r\n\tfor i, user_id in reversed(list(enumerate(user_ids))):\r\n\t\tfor data in reversed(reg_data):\r\n\t\t\tif data != {}:\r\n\t\t\t\tif data[\"user_id\"] == user_id:\r\n\t\t\t\t\tupd_payload[i] = [data[\"user_id\"], data[\"access_token\"], data[\"refresh_token\"]]\r\n\t\t\t\t\tfor i in range(len(reg_data)): #Удаляем повторения\r\n\t\t\t\t\t\tif 'user_id' in reg_data[i]:\r\n\t\t\t\t\t\t\tif reg_data[i][\"user_id\"] == user_id:\r\n\t\t\t\t\t\t\t\treg_data[i] = {}\r\n\twith open(registrations_file, 'w') as f:\r\n\t\tjson.dump(reg_data, f)\r\n\t\r\n\tws.update('Q2', upd_payload)\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"upload_tokens.py","file_name":"upload_tokens.py","file_ext":"py","file_size_in_byte":1875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"632369064","text":"import torch\nfrom col_spec_yh.constants import *\nimport random\n\n\n_row_idx = lambda x: x % 100\n_col_idx = lambda x: x % 10000 // 100\n_cell_idx = lambda x: x % 10000\n\n_is_tok = lambda x: x > 10000 # padding:0\n_is_cls = lambda x: (x < 10000) * (x > 0)\n\n\n# nl\n_is_que = lambda x: _row_idx(x) == 99 * _col_idx == 0\n\n# tbl\n_is_meta_wo_cls = lambda x:_is_tok(x) * _row_idx(x)>=98\n\n_is_title = lambda x: x % 10000 == 9898\n_is_title_cls = lambda x: x == 9898 # tab_cls\n_is_title_wo_cls = lambda x: (x > 10000) * (x % 10000 == 9898)\n\n_is_header = lambda x: _row_idx(x) == 98\n_is_header_cls = lambda x: _is_cls(x) * _is_header(x) # col_cls\n_is_header_wo_cls = lambda x: _is_tok(x) * _is_header(x)\n\n_is_row_cls = lambda x: _is_cls(x) * _col_idx==98 # row_cls\n\n# cell\n_is_cell = lambda x: (_col_idx(x) >= 1) * (_col_idx(x) <= 97) * \\\n (_row_idx(x) >= 1) * (_row_idx(x) <= 97)\n_is_cell_tok = lambda x: _is_tok(x) * _is_cell(x)\n_is_cell_cls = lambda x: _is_cls(x) * _is_cell(x) # cell_cls\n\ndef generate_seg(args, cols, noise_num=0, row_wise_fill=False):\n '''\n :param cols -> List[List[str]]\n ps :\n len(cols)<=98, corresponding to col_id 1..98\n because col_id 99 is left to denote [CLS]\n :param row_wise_fill -> Bool\n :return: tokens -> List[int]; seg -> List[int]\n '''\n # 1. TAB\n if args.has_high_level_cls:\n tokens = [TAB_CLS_ID]\n seg = [9898]\n else:\n tokens = []\n seg = []\n\n if not row_wise_fill:\n for idx_c in range(1, len(cols) + 1):\n if args.has_high_level_cls:\n idx_r = 98 # fake\n seg.append(100 * idx_c + idx_r)\n tokens.append(COL_CLS_ID)\n for idx_r in range(1, len(cols[0]) + 1):\n dataframe = cols[idx_c - 1][idx_r - 1]\n temp = args.tokenizer.convert_tokens_to_ids(args.tokenizer.tokenize(dataframe))\n if len(temp) == 0:\n continue\n else:\n temp = [CLS_ID] + temp\n tokens.extend(temp)\n for idx_tok in range(0, len(temp)):\n seg.append(idx_tok * 10000 + idx_c * 100 + idx_r)\n elif row_wise_fill:\n dataframe_max_len = args.seq_len // len(cols)\n if args.has_high_level_cls:\n for idx_c in range(1, len(cols) + 1):\n idx_r = 98 # fake\n seg.append(100*idx_c+idx_r)\n tokens.append(CLS_ID)\n for idx_r in range(1, len(cols[0])+1):\n for idx_c in range(1, len(cols) + 1):\n # import ipdb; ipdb.set_trace()\n try:\n dataframe = cols[idx_c-1][idx_r-1]\n except:\n IndexError\n import ipdb; ipdb.set_trace()\n\n temp = args.tokenizer.convert_tokens_to_ids(args.tokenizer.tokenize(dataframe))[:dataframe_max_len-2]\n if len(temp) == 0:\n continue\n else:\n temp = [CLS_ID] + temp\n tokens.extend(temp)\n for idx_tok in range(0, len(temp)):\n seg.append(idx_tok*10000 + idx_c*100 +idx_r)\n tokens = tokens[:args.seq_len]\n seg = seg[:args.seq_len]\n while len(tokens) < args.seq_len:\n tokens.append(PAD_ID)\n seg.append(0)\n for _ in range(noise_num): # two noise\n _i = random.randint(0, len(tokens)-1)\n tokens[_i] = MASK_ID\n return tokens, seg\n\n\ndef generate_mask_todo(seg, context_mode='cross-wise'):\n '''\n 1) In parallel with what I had written in my paper.\n 2) Drop using cross-wise AND additional mask\n '''\n\n if seg.dim() == 1:\n seg = seg.unsqueeze(0)\n\n bz, seq_len = seg.shape\n seg = seg.view(bz, seq_len, 1)\n seg_2 = seg.view(bz, 1, seq_len)\n\n\n def _in_cross_with(seg, seg_2):\n return (_row_idx(seg) == _row_idx(seg_2)) or (_col_idx(seg) == _col_idx(seg_2))\n\n tok_see = _is_tok(seg) * (_in_cross_with(seg, seg_2) * (_is_tok(seg_2) or _is_header(seg_2) or _is_row_cls(seg_2)))\n cell_cls_see = _is_cell_cls(seg) * (_in_cross_with())\n\n\n # hier part\n additional_mask = 1 - (_is_cell_cls(seg_2) * (_cell_idx(seg) != _cell_idx(seg_2))) \\\n .float().unsqueeze(1)\n\n # cross part\n row_wise_see = (_row_idx(seg) == _row_idx(seg_2)).unsqueeze(1).float()\n col_wise_see = (_col_idx(seg) == _col_idx(seg_2)).unsqueeze(1).float()\n return (row_wise_see + col_wise_see) * additional_mask\n\ndef generate_mask(seg, mask_mode='cross-wise'):\n '''\n 1) In parallel with what I had written in my paper.\n 2) Drop using cross-wise AND additional mask\n\n Difference:\n 1) tab-cls 可以看到 col-cls 和 row-cls (但是不能看到 cell-cls)\n 2) cell-cls 可以看到 cross 位置的 token\n 3) 可选同行或同列可见\n '''\n\n if seg.dim() == 1:\n seg = seg.unsqueeze(0)\n\n bz, seq_len = seg.shape\n seg = seg.view(bz, seq_len, 1)\n seg_2 = seg.view(bz, 1, seq_len)\n\n # 1. cross part\n if mask_mode=='cross-wise':\n wise_see = (_row_idx(seg) == _row_idx(seg_2)) * (_col_idx(seg) == _col_idx(seg_2))\n if mask_mode=='row-wise':\n wise_see = (_row_idx(seg) == _row_idx(seg_2))\n if mask_mode=='col-wose':\n wise_see = (_col_idx(seg) == _col_idx(seg_2))\n # 2. hier part\n # 2.1. down_up:\n tab_see = (_is_title_cls(seg) * _is_tok(seg_2))\n\n # 2.2. 阻断 cell-cls到处被看到\n additional_mask = ~ (_is_cell_cls(seg_2) * (_cell_idx(seg) != _cell_idx(seg_2)))\n\n m = (wise_see + tab_see) * additional_mask\n return m.float().unsqueeze(1)\n\n\ndef generate_mask_former(seg, mask_mode='cross-wise', additional_ban=0):\n '''\n :param seg -> torch.LongTensor shape: [bz, seq_len]\n :return: mask -> torch.FloatTensor shape: [bz, 1, seq_len, seq_len]\n '''\n\n if seg.dim() == 1:\n seg = seg.unsqueeze(0)\n\n import ipdb; ipdb.set_trace()\n bz, seq_len = seg.shape\n seg = seg.view(bz, seq_len, 1)\n seg_2 = seg.view(bz, 1, seq_len)\n\n # ban\n # mode 1: skip_level_ban: token level can't see [cell-cls], [col-cel] or [tab-cls]\n # mode 2: [cell-cls] can't see other [cell-cls] (even though they are in the same row or column)\n # mode 3: skip_level_ban, but tokens can see [cell-cls] of them\n # mode 4: [cell-cls] (and [col-cls] and [tab-col])can't be seen by tokens\n # mode 4 alerted: [cell-cls] can only seen by toks within this table cell\n # additional_mask_see: where there is 0, take it as blind\n if additional_ban==1:\n additional_mask = 1 - ((seg>10000)*(seg_2<10000)).float().unsqueeze(1)\n elif additional_ban==2:\n additional_mask = 1 - ((seg<10000)*(seg_2<10000)*(seg!=seg_2)).float().unsqueeze(1)\n elif additional_ban==3:\n additional_mask = 1 - ((seg>10000)*(seg_2<10000)*(seg%10000!=seg_2)).float().unsqueeze(1)\n elif additional_ban==4:\n # additional_mask = 1 - ((seg_2<10000)*(seg%10000!=seg_2)).float().unsqueeze(1)\n additional_mask = 1 - (_is_cell_cls(seg_2)*(_cell_idx(seg)!=_cell_idx(seg_2)))\\\n .float().unsqueeze(1)\n else:\n additional_mask = torch.ones(bz, 1, seq_len, seq_len)\n additional_mask.to(seg.device)\n seg = seg % 10000\n seg_2 = seg_2 % 10000\n # cls_see_all_mask = (seg > 0).float() # [bz, seq_len]\n # cls_see_all_mask = cls_see_all_mask.view(bz, 1, 1, seq_len)\n row_wise_see = (seg % 100 == seg_2 % 100).unsqueeze(1).float() # mask: [batch_size x 1 x seq_length x seq_length]\n if mask_mode == 'row-wise':\n return row_wise_see*additional_mask\n col_wise_see = (seg // 100 == seg_2 // 100).unsqueeze(1).float()*2\n if mask_mode == 'col-wise':\n return col_wise_see*additional_mask\n if mask_mode == 'cross-wise':\n mask = row_wise_see + col_wise_see\n return mask*additional_mask\n # hier_tab_col_see = ((seg % 100 > 90) * (seg_2 % 100 > 90)).unsqueeze(1).float() * 4\n # if mask_mode == 'cross-and-hier-wise':\n # mask = row_wise_see + col_wise_see + hier_tab_col_see\n # return mask*additional_mask\n # mask = torch.cat((cls_see_all_mask, mask[:, :, 1:, :]), dim=-2)\n # then we can use 1,2,3.. (or more possible cnt numbers) to distinguish different relations -> relation-aware attention\n\n# not finished\n# def generate_mask_2(seg):\n# bz, seq_len = seg.shape\n# seg = seg.view(bz, seq_len, 1)\n# seg_2 = seg.view(bz, 1, seq_len)\n#\n# # relations\n# # cell_wise_see = _cell_idx(seg) == _cell_idx(seg_2)\n# # table content\n# col_wise_see = (_col_idx(seg)==_col_idx(seg_2)) * (_is_cell_tok(seg)*_is_cell_tok(seg_2))\n# row_wise_see = (_row_idx(seg)==_row_idx(seg_2)) * (_is_cell_tok(seg)*_is_cell_tok(seg_2))\n# # metadata\n# meta_wise_see = _is_meta_wo_cls(seg) * _is_meta_wo_cls(seg_2)\n# # cell-cls\n# cell_cls_see = _is_cell_cls(seg) * (_is)\n\n\n\ndef get_sep_idxs(seg, option):\n '''\n :param\n seg -> torch.LongTensor; shape: [bz, seq_len]\n option: in ['tab', 'col', 'cell']\n :return:\n '''\n bz, seq_len = seg.shape\n if option == 'tab':\n return torch.stack([torch.arange(0, bz), torch.zeros(bz).long()], dim=0) # shape: [2, bz]\n if option == 'col':\n return torch.nonzero(((seg % 100) == 98).float())\n if option == 'cell':\n return torch.nonzero(((seg // 10000) == 1).float())\n","sub_path":"UER-spider-temp/col_spec_yh/encode_utils.py","file_name":"encode_utils.py","file_ext":"py","file_size_in_byte":9402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"136780323","text":"#########################################################################\n# 读入数据 #\n# 思翠人工智能, 机器学习研发 #\n# 2021.5.26 #\n#########################################################################\n#!/usr/bin/python\n#-*- coding:UTF-8 -*-\n\nfrom __future__ import print_function, division\n\nimport os\nimport torch\nimport numpy as np \nimport pandas as pd\nfrom PIL import Image\nfrom PIL import ImageFile\n\nkfolder = int(5)\nBS = 4\nNW = 4\nroot_path = '/home/maxiaozhi/CNN/cnn_1/k_folder'\ncsv_path = '/home/maxiaozhi/CNN/cnn_1/k_folder/dataset.csv'\nimage_path = '/home/maxiaozhi/CNN/cnn_1/k_folder/data'\n\nclass data_set:\n def __init__(self, dataset_path, batch_size, num_workers):\n self.dataset_path = dataset_path\n# self.data_augmentation = data_augmentation\n self.batch_size = batch_size\n self.num_workers = num_workers\n\n def reading_txt(self):\n ImageFile.LOAD_TRUNCATED_IMAGES = True\n\n dataloader_train = {}\n dataloader_val = {}\n for root, folders, files in os.walk(self.dataset_path):\n for f in folders: \n f_path = os.path.join(root, f)\n txt = os.listdir(f_path)\n train_path = os.path.join(f_path, txt[0])\n val_path = os.path.join(f_path, txt[1])\n\n dataloader_train[f] = self.loading(train_path)\n dataloader_val[f] = self.loading(val_path)\n\n return dataloader_train, dataloader_val\n\n def loading(self, list_pth):\n list_img = []\n list_label = []\n dict_dataset = {}\n with open(list_pth, 'r+', encoding='UTF-8') as file:\n lines = file.readlines()\n for content in lines:\n img = content.strip().split()[0]\n img = Image.open(img).convert('RGB')\n img = np.array(img)\n img = np.transpose(img, (2, 0, 1))\n img = torch.tensor(img)\n list_img.append(img)\n\n label = content.strip().split()[1:]\n label = [int(i) for i in label] # 遍历label的list并将其元素改为int型\n label = np.array(label)\n label = torch.tensor(label)\n list_label.append(label)\n \n dataloaders = torch.utils.data.DataLoader(dataset=list_img, \n batch_size=self.batch_size, \n num_workers=self.num_workers)\n dict_dataset['img'] = dataloaders\n dataloaders = torch.utils.data.DataLoader(dataset=list_label, \n batch_size=self.batch_size, \n num_workers=self.num_workers)\n dict_dataset['label'] = dataloaders\n\n return dict_dataset\n\nclass K_Folder:\n def __init__(self, csv_pth, image_pth, k, save_txt_path):\n self.csv_pth = csv_pth\n self.image_pth = image_pth\n self.k = k\n self.save_txt_path = save_txt_path\n self.k_folder = {}\n \n def read_data(self):\n df = pd.read_csv(self.csv_pth)\n # 建一个dict_image字典, 存放K个数据集.\n dict_image = {}\n\n counter = 0\n dict_dataset = {} # 新建一个dict_dataset字典,key是image的名字,而value是image的存放地址和image的标签.\n new_df = df[['image_name', 'f_8']] # 新建一个df, 只取源csv中, image的名字和image的标签.\n for i in range(0, len(new_df)):\n img_name = new_df.loc[i][0]\n img_path = os.path.join(self.image_pth, img_name)\n img_label_1 = new_df.loc[i][1]\n dict_dataset[img_name] = [img_path, img_label_1] # 后面在索引image的地址和标签时, 只需对应索引其list[0]和list[1]\n\n list_image = [ i for i in new_df['image_name'] ]\n for i in range(0, self.k):\n value_name = 'dataset_' + str(i)\n dict_image[value_name] = []\n dataset_0 = int(len(list_image)/self.k) # 将数据化为K份, 计算第一份的数量\n dataset_1 = int(2*dataset_0) # 计算第二份的数量\n dataset_2 = int(3*dataset_0) # 计算第三份的数量\n dataset_3 = int(4*dataset_0) # 计算第四份的数量\n\n for img in list_image:\n if counter<=dataset_0:\n dict_image['dataset_0'].append(dict_dataset[img])\n counter += 1 \n elif counter>dataset_0 and counter<=dataset_1:\n dict_image['dataset_1'].append(dict_dataset[img])\n counter += 1\n elif counter>dataset_1 and counter<=dataset_2:\n dict_image['dataset_2'].append(dict_dataset[img])\n counter += 1\n elif counter>dataset_2 and counter<=dataset_3:\n dict_image['dataset_3'].append(dict_dataset[img])\n counter += 1\n else:\n dict_image['dataset_4'].append(dict_dataset[img])\n counter += 1\n return dict_image\n\n def make_data(self, dict_temp):\n for i in dict_temp:\n self.k_folder[i] = [[], []] # 每个key对应一个value; 每个value是一个list; 而每个list中list[0]存放train, list[1]存放val\n\n for D in dict_temp:\n for d in dict_temp:\n if D==d:\n self.k_folder[D][1] = dict_temp[d] \n else:\n self.k_folder[D][0] += dict_temp[d]\n \n return self.k_folder\n\n def make_txt(self, dict_temp): # 这个函数将分好的数据写入txt文件中, 保存下来\n os.mkdir(self.save_txt_path)\n for files in dict_temp:\n sub_folder = os.path.join(self.save_txt_path, files)\n os.mkdir(sub_folder)\n\n for root, folders, files in os.walk(self.save_txt_path):\n for f in folders:\n for key in dict_temp:\n if f==key:\n save_folder = os.path.join(root, key)\n\n dataset = dict_temp[key]\n train_data = dataset[0]\n val_data = dataset[1]\n \n save_train = os.path.join(save_folder, 'train.txt')\n save_val = os.path.join(save_folder, 'val.txt')\n \n train_txt = open(save_train, 'w', encoding='UTF-8')\n val_txt = open(save_val, 'w', encoding='UTF-8')\n for contents in train_data:\n for index in range(0, len(contents)):\n if index == 0:\n info = contents[index]\n else:\n info += ' '+str(contents[index])\n info += '\\n'\n train_txt.writelines(info)\n for contents in val_data:\n for index in range(0, len(contents)):\n if index == 0:\n info = contents[index]\n else:\n info += ' '+str(contents[index])\n info += '\\n'\n val_txt.writelines(info) \n\ndef main():\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n KFolder_path = os.path.join(root_path, 'folders')\n\n work_1 = K_Folder(csv_path, image_path, kfolder, KFolder_path)\n dict_image = work_1.read_data()\n K_dataset = work_1.make_data(dict_image)\n\n if not os.path.exists(KFolder_path):\n work_1.make_txt(K_dataset)\n\n work_2 = data_set(KFolder_path, BS, NW)\n train, val = work_2.reading_txt()\n\nif __name__ == '__main__':\n main()","sub_path":"data_2.py","file_name":"data_2.py","file_ext":"py","file_size_in_byte":8246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"106480081","text":"# Calcula los segundos a tomar del archivo TRC\n\n\ndef calc_tiempo(min_ini=None, seg_ini=None, min_fin=None, seg_fin=None, video_nr=None):\n videos_t_ini = [0, 2002, 4004, 6006]\n ini_t_en_segundos = (min_ini * 60) + seg_ini + videos_t_ini[video_nr - 1]\n fin_t_en_segundos = (min_fin * 60) + seg_fin + videos_t_ini[video_nr - 1]\n\n print('Tomar desde el segundo', ini_t_en_segundos, 'hasta el segundo', fin_t_en_segundos)\n\ncalc_tiempo(min_ini=0,\n seg_ini=0,\n min_fin=25,\n seg_fin=0,\n video_nr=4)\n\n\n","sub_path":"video_iEEG_tiempo.py","file_name":"video_iEEG_tiempo.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"120038334","text":"# Copyright (c) 2017-2018 nVentiveUX\n\n\"\"\"\nCLI commands module.\n\"\"\"\n\nimport logging\n\nimport click\n\nfrom bootstrap import settings\n\nlogger = logging.getLogger(__name__)\n\n\n@click.command()\n@click.option('--os-image',\n default='raspbian-lite',\n type=click.Choice(settings.OS_IMAGES),\n help='Operating system release.')\n@click.argument('device',\n type=click.Path(exists=True, resolve_path=True, readable=True))\ndef flash(os_image, device):\n \"\"\"\n Flash operating system to SD card.\n\n DEVICE is the block device path (eg. /dev/sdX) where to flash the image.\n \"\"\"\n logger.info('Requested to flash \\\"%s\\\" image on %s.' % (os_image, device))\n\n\n@click.command()\ndef rootssh():\n \"\"\"\n Install SSH public keys into root's authorized_keys.\n \"\"\"\n logger.debug('Hello from rootssh !')\n","sub_path":"bootstrap/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"24494287","text":"#!/usr/bin/env python3\nimport json\nimport time\n\nimport numpy as np\nimport pandas as pd\nfrom pymongo import MongoClient\nfrom tqdm import tqdm\n\nfrom syn.helpers.logging import set_logger\nfrom syn.helpers.mongodb import get_default_mongo_client\nfrom syn.helpers.nlp.TextNormalizer import *\n\nlog = set_logger()\n\n\ndef main():\n log.debug(f\"\\n[INICIO EJECUCIÓN]\")\n start_time = time.time()\n\n # Incializa las variables que almacenarán los argumentos de entrada.\n input_params = get_input_params()\n\n # Inicializa los parámetros MongoDB para almacenar las estadísticas.\n def get_mongo_client(environment):\n if environment == 'local':\n return MongoClient(host='localhost', port=27017)\n else:\n return get_default_mongo_client()\n\n # Aplica tqdm a Pandas para poder mostrar barras de progreso en las operaciones.\n tqdm.pandas()\n\n # Crea el cliente MongoDB.\n mongodb_client: MongoClient = get_mongo_client(input_params['nlp_api_params'].env)\n db = mongodb_client[input_params['mongo_params'].db_name]\n col = db[f\"{input_params['mongo_params'].collection_name}\"]\n\n log.debug(f\"Normalizando el conjunto de datos:'{db.name}'\")\n\n tic = time.time()\n # Campos seleccionados para los trabajos abordados en el proyecto de investigación.\n fields = {\n \"_id\": 0,\n }\n\n # Consulta utilizada para recuperar los datos de MongoDB.\n query = {\n # \"bug_id\": \"296\"\n }\n\n # Recupera la colección de MongoDB.\n clear_data = col.find(query, fields)\n\n # Expande el cursor y construye el DataFrame\n clear = pd.DataFrame(list(clear_data))\n log.debug(f\"[LEER MongoDb: colección '{col.name}'] Tiempo de ejecución : {(time.time() - tic) / 60}\")\n\n # Crea una copia del Dataframe para trabajar.\n aux_clear = clear.copy()\n\n # Nombre de la colección.\n normalized_col_name = f\"normalized_{col.name}\"\n log.debug(f\"Colecciones exitentes en '{db.name}': {str(db.list_collection_names())}\")\n if input_params['nlp_api_params'].split_new_line:\n normalized_col_name = f\"{normalized_col_name}_new_line_splited\"\n\n # Colección MongoDB.\n normalized_col = db[normalized_col_name]\n\n # Si existe una versión previa de la colección MongoDB la elimina.\n if normalized_col.name in db.list_collection_names():\n log.debug(f\"Eliminando la colección: '{normalized_col.name}'\")\n db.drop_collection(normalized_col.name)\n\n # Divide el dataframe en subconjuntos para guardar en MongoDB por lotes.\n log.debug(f\"Número de lotes: '{input_params['nlp_api_params'].batches}'\")\n splitted_df = np.array_split(aux_clear, input_params['nlp_api_params'].batches)\n\n # Recorre los lotes para normalizar y guardar en MongoDB.\n for df in splitted_df:\n result = None\n # Normaliza las columnas.\n column_names = []\n for column in input_params['nlp_api_params'].columns_names:\n column_names.append(column)\n tic = time.time()\n result = normalize_df_column(df, column, input_params)\n log.debug(f\"[NORMALIZAR columna '{column}'] Tiempo de ejecución : {(time.time() - tic) / 60}\")\n\n # Guarda la colección en MongoDB o en un fichero JSON.\n # TODO Crear un Factory para guardar el Dataframe\n tic = time.time()\n if result is not None:\n if input_params['nlp_api_params'].output_format == \"mongodb\":\n final_result = None\n if input_params['nlp_api_params'].drop_original_columns:\n final_result = result.drop(columns=column_names, axis=1).copy()\n records = json.loads(final_result.T.to_json()).values()\n normalized_col.insert_many(records)\n if input_params['nlp_api_params'].output_format == \"csv\":\n result.to_json(f\"data/{normalized_col_name}.csv\")\n log.debug(\n f\"[ESCRIBIR MongoDb: colección '{db.name}_{normalized_col.name}'] \"\n f\"Tiempo de ejecución : {(time.time() - tic) / 60}\")\n\n log.debug(f\"\\n[FIN EJECUCIÓN] Tiempo de ejecución : {(time.time() - start_time) / 60}\")\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"syn/data/clean/NormalizeText.py","file_name":"NormalizeText.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"298757249","text":"# -*- coding: utf-8 -*-\n# Author : Jean-Michel Begon\n# Date : Mar 08 2014\n\"\"\"\nSeveral tools for parallel computation\n\"\"\"\nfrom abc import ABCMeta, abstractmethod\nimport numpy as np\nimport copy_reg\nimport types\n\n\nfrom sklearn.externals.joblib import Parallel, delayed, cpu_count\nfrom Logger import Progressable\nfrom NumpyFactory import NumpyFactory\n\n__all__ = [\"TaskSplitter\", \"TaskExecutor\", \"SerialExecutor\",\n \"ParallelExecutor\"]\n\n\ndef reduceMethod(m):\n \"\"\"Adds the capacity to pickle method of objects\"\"\"\n return (getattr, (m.__self__, m.__func__.__name__))\n\ncopy_reg.pickle(types.MethodType, reduceMethod)\n\n\nclass TaskSplitter:\n \"\"\"\n ===========\n TaskSplitter\n ===========\n A toolkit for preprocessing parallel computation\n \"\"\"\n def computePartition(self, nbTasks, dataSize):\n \"\"\"\n Compute data partitioning for parallel computation :\n min(nbTasks, dataSize)\n\n Parameters\n ----------\n nbTasks : int (!=0)\n If >0 : the parallelization factor.\n If <0 : nbTasks = #cpu+nbTasks+1 (-1 -> nbTasks = #cpu)\n dataSize : int > 0\n The size of the data to process\n\n Return\n ------\n triplet = (nbTasks, counts, starts)\n nbTasks : int\n The final parallelization factor. It is computed as\n min(#cpu/nbTasks, dataSize)\n counts : list of int\n The number of data pieces for each parallel task\n starts : list of int\n The start indexes of the data for each parallel task\n \"\"\"\n if nbTasks < 0:\n cpu = cpu_count()+nbTasks+1\n if cpu <= 0:\n cpu = 1\n nbTasks = min(cpu, dataSize)\n else:\n if nbTasks == 0:\n nbTasks = 1\n nbTasks = min(nbTasks, dataSize)\n\n counts = [dataSize / nbTasks] * nbTasks\n\n for i in xrange(dataSize % nbTasks):\n counts[i] += 1\n\n starts = [0] * (nbTasks + 1)\n\n for i in xrange(1, nbTasks + 1):\n starts[i] = starts[i - 1] + counts[i - 1]\n\n return nbTasks, counts, starts\n\n def partition(self, nbTasks, data):\n \"\"\"\n Partition the data for parallel computation.\n\n Parameters\n ----------\n nbTasks : int {-1, >0}\n The parallelization factor. If -1 : the greatest factor is chosen\n data : list\n The data to partition\n\n Return\n ------\n tuple = (nbTasks, dataParts, starts)\n nbTasks : int\n The final parallelization factor. It is computed as\n min(#cpu/nbTasks, dataSize)\n dataParts : list of slices\n each element of dataParts is a contiguous slice of data : the\n partition for a parallel computation unit\n starts : list of int\n The start indices corresponding to the dataParts :\n dataParts[i] = data[starts[i]:starts[i+1]\n \"\"\"\n nbTasks, counts, starts = self.computePartition(nbTasks, len(data))\n dataParts = []\n for i in xrange(nbTasks):\n dataParts.append(data[starts[i]:starts[i + 1]])\n return nbTasks, dataParts, starts\n\n\nclass TaskExecutor(Progressable):\n \"\"\"\n ===========\n TaskExecutor\n ===========\n A class responsible for carrying out submitted tasks\n \"\"\"\n __metaclass__ = ABCMeta\n\n def __init__(self, logger=None, verbosity=10):\n \"\"\"\n Creates a :class:`TaskExecutor`\n \"\"\"\n Progressable.__init__(self, logger, verbosity)\n\n @abstractmethod\n def execute(self, descr, function, data, *args, **kwargs):\n \"\"\"\n Get the result of the task directly\n\n Parameters\n ----------\n desc : str\n A string describing the task\n function : callable\n The function to process the task. The function must be able to\n work on any subset of the data\n data : an iterable of piece of data\n The data to process\n args : iterable\n Parameters to pass to the function\n kwargs: dictionnary\n Keyword parameters to pass to the function\n\n Return\n ------\n ls : iterable of results\n each individual result is the execution of the function on a given\n subset of the data. The caller must aggregate the result accordinly\n \"\"\"\n pass\n\n @abstractmethod\n def executeWithStart(self, descr, function, data, *args, **kwargs):\n \"\"\"\n Get the result of the task directly. The difference with meth:`execute`\n comes from the function signature, which now must have a dedicated\n keyword argument \"startIndex\" which indicates the start index of the\n data slice on which the function is called\n\n Parameters\n ----------\n desc : str\n A string describing the task\n function : callable : f(...startIndex,...)\n The function to process the task. The function must be able to\n work on any subset of the data and must have a dedicated keyword\n argument \"startIndex\" which indicates the start index of the data\n slice on which the function is called\n data : an iterable of piece of data\n The data to process\n args : iterable\n Parameters to pass to the function\n kwargs: dictionnary\n Keyword parameters to pass to the function\n\n Return\n ------\n ls : iterable of results\n each individual result is the execution of the function on a given\n subset of the data. The caller must aggregate the result accordinly\n \"\"\"\n pass\n\n def __call__(self, descr, function, data, *args, **kwargs):\n \"\"\"Delegate to :meth:`execute`\"\"\"\n return self.execute(descr, function, data, *args, **kwargs)\n\n @abstractmethod\n def createArray(self, shape, dtype=float):\n \"\"\"\n Return\n ------\n array : numpy array\n An empty (zero-filled) numpy array of given shape and dtype,\n modifiable on place by the function used with :meth:`execute`\n \"\"\"\n pass\n\n @abstractmethod\n def clean(self, array):\n pass\n\n\nclass SerialExecutor(TaskExecutor):\n \"\"\"\n ==============\n SerialExecutor\n ==============\n :class:`SerialExecutor` simply store the task to execute later\n \"\"\"\n\n def __init__(self, logger=None, verbosity=10):\n TaskExecutor.__init__(self, logger, verbosity)\n\n def execute(self, desc, function, data, *args, **kwargs):\n self.setTask(1, desc)\n if len(args) == 0:\n if len(kwargs) == 0:\n ls = [function(data)]\n else:\n ls = [function(data, **kwargs)]\n elif len(kwargs) == 0:\n ls = [function(data, *args)]\n else:\n ls = [function(data, *args, **kwargs)]\n self.endTask()\n return ls\n\n def executeWithStart(self, desc, function, data, *args, **kwargs):\n self.setTask(1, desc)\n if len(args) == 0:\n if len(kwargs) == 0:\n ls = [function(data, startIndex=0)]\n else:\n ls = [function(data, startIndex=0, **kwargs)]\n elif len(kwargs) == 0:\n ls = [function(data, startIndex=0, *args)]\n else:\n ls = [function(data, startIndex=0, *args, **kwargs)]\n self.endTask()\n return ls\n\n def createArray(self, shape, dtype=float):\n return np.zeros(shape, dtype)\n\n def clean(self, array):\n pass\n\n\nclass ParallelExecutor(TaskExecutor):\n \"\"\"\n ====================\n ParallelExecutor\n ====================\n :class:`ParallelExecutor` splits the data for multiprocessing\n \"\"\"\n\n def __init__(self, nbParal=-1, logger=None, verbosity=0, tempFolder=None):\n TaskExecutor.__init__(self, logger, verbosity)\n self._nbParal = nbParal\n self._tmpFolder = tempFolder\n self._numpyFactory = NumpyFactory(tempFolder)\n\n def execute(self, desc, function, data, *args, **kwargs):\n #Splitting task\n tSplitter = TaskSplitter()\n nbJobs, splittedData, starts = tSplitter.partition(self._nbParal, data)\n\n #Logging\n self.setTask(1, (\"Starting parallelization : \"+desc))\n\n #Parallelization\n parallelizer = Parallel(n_jobs=nbJobs, temp_folder=self._tmpFolder,\n verbose=self.verbosity,)\n\n if len(args) == 0:\n if len(kwargs) == 0:\n allData = parallelizer(delayed(function)(\n splittedData[i]) for i in xrange(nbJobs))\n else:\n allData = parallelizer(delayed(function)(\n splittedData[i], **kwargs) for i in xrange(nbJobs))\n elif len(kwargs) == 0:\n allData = parallelizer(delayed(function)(\n splittedData[i], *args) for i in xrange(nbJobs))\n else:\n allData = parallelizer(delayed(function)(\n splittedData[i], *args, **kwargs) for i in xrange(nbJobs))\n self.endTask()\n\n return allData\n\n def executeWithStart(self, desc, function, data, *args, **kwargs):\n #Splitting task\n tSplitter = TaskSplitter()\n nbJobs, splittedData, starts = tSplitter.partition(self._nbParal, data)\n\n #Logging\n self.setTask(1, (\"Starting parallelization : \"+desc))\n\n #Parallelization\n parallelizer = Parallel(n_jobs=nbJobs, temp_folder=self._tmpFolder,\n verbose=self.verbosity,)\n\n if len(args) == 0:\n if len(kwargs) == 0:\n allData = parallelizer(delayed(function)(\n splittedData[i], startIndex=starts[i])\n for i in xrange(nbJobs))\n else:\n allData = parallelizer(delayed(function)(\n splittedData[i], startIndex=starts[i], **kwargs)\n for i in xrange(nbJobs))\n\n elif len(kwargs) == 0:\n allData = parallelizer(delayed(function)(\n splittedData[i], startIndex=starts[i], *args)\n for i in xrange(nbJobs))\n\n else:\n allData = parallelizer(delayed(function)(\n splittedData[i], startIndex=starts[i], *args, **kwargs)\n for i in xrange(nbJobs))\n\n self.endTask()\n\n return allData\n\n def createArray(self, shape, dtype=float):\n return self._numpyFactory.createArray(shape, dtype)\n\n def clean(self, array):\n self._numpyFactory.clean(array)\n\n#class ParallelCoordinator(Coordinator):\n# \"\"\"\n# ===================\n# ParallelCoordinator\n# ===================\n# A coordinator (see :class:`Coordinator`) for parallel computing\n# \"\"\"\n# #Counts the number of instances already created\n# instanceCounter = 0\n#\n# def __init__(self, coordinator, nbParal=-1, verbosity=0, tempFolder=None):\n# \"\"\"\n# Construct a :class:`ParallelCoordinator`\n#\n# Parameters\n# ----------\n# coordinator : :class:`Coordinator`\n# The coordinator which will execute the work in its private\n# child process\n# nbParal : int {-1, > 0} (default : -1)\n# The parallel factor. If -1, or > #cpu, the maximum factor is used\n# (#cpu)\n# verbosity : int >=0 (default : 0)\n# The verbosity level. The higher, the more information message.\n# Information message are printed on the stderr\n# tempFolder : string (directory path) (default : None)\n# The temporary folder used for memmap. If none, some default folder\n# will be use (see the :lib:`joblib` library)\n# \"\"\"\n# Coordinator.__init__(self)\n# self._coordinator = coordinator\n# self._nbParal = nbParal\n# self._verbosity = verbosity\n#\n# if ParallelCoordinator.instanceCounter == 0:\n# copy_reg.pickle(types.MethodType, reduceMethod)\n# ParallelCoordinator.instanceCounter += 1\n#\n# def process(self, imageBuffer):\n# taskSplitter = TaskSplitter()\n# nbJobs, subImageBuffer = taskSplitter.partition(self._nbParal,\n# imageBuffer)\n# #Logging\n# self.setTask(1, \"Starting parallelization\")\n#\n# #Parallelization\n# allData = Parallel(n_jobs=nbJobs, verbose=self._verbosity)(\n# delayed(self._coordinator.process)(\n# subImageBuffer[i])\n# for i in xrange(nbJobs))\n#\n# # Reduce\n# self.logMsg(\"Concatenating the data...\", 35)\n# y = np.concatenate([y for _, y in allData])\n# X = np.vstack(X for X, _ in allData)\n# self.endTask()\n#\n# return X, y\n\nif __name__ == \"__main__\":\n test1 = [(\"A\",1), (\"B\",2), (\"C\",3), (\"D\",4)]\n test2 = [(\"A\",1),(\"B\",2),(\"C\",3),(\"D\",4),(\"E\",5),(\"F\",6),(\"G\",7),(\"H\",8)]\n test3 = [(\"A\",1),(\"B\",2),(\"C\",3),(\"D\",4),(\"E\",5),(\"F\",6),(\"G\",7),(\"H\",8),(\"I\",9),(\"J\",10),(\"K\",11),(\"L\",12)]\n\n taskMan = TaskSplitter()\n\n","sub_path":"code/lib/TaskManager.py","file_name":"TaskManager.py","file_ext":"py","file_size_in_byte":13126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"19123599","text":"from PySide2.QtWidgets import QTreeView, QAbstractItemView\nfrom PySide2.QtGui import QStandardItemModel, QStandardItem\nfrom PySide2.QtCore import Qt\n\nimport re\n\nclass TreeView(QTreeView):\n def __init__(self, inspector):\n super().__init__()\n self.inspector = inspector\n self.inspector.add('tree_view', self)\n\n # Set selection mode so multiple datasets can be selected\n self.setSelectionMode(QAbstractItemView.ExtendedSelection)\n # Hide header\n self.setHeaderHidden(True)\n\n # Create and set model to view\n self.model = TreeModel(self.inspector)\n self.model.update()\n self.setModel(self.model)\n\n # Create selection model\n self.selectionModel = self.selectionModel()\n self.selectionModel.setModel(self.model)\n\n def update(self, filter = None):\n # Update tree to show datastore content with optional regex filter\n self.model.update(selection_reg = filter)\n\n def expand_all(self):\n # Expand tree to show all items\n self.expandAll()\n\n def get_selection(self):\n selection = []\n for index in self.selectionModel.selectedIndexes():\n for dataset in self.__flatten(self.model.itemFromIndex(index).get_datasets()):\n selection.append(dataset)\n return selection\n\n def __flatten(self, lis):\n \"\"\"Given a list, possibly nested to any level, return it flattened.\"\"\"\n new_lis = []\n for item in lis:\n if type(item) == type([]):\n new_lis.extend(self.__flatten(item))\n else:\n new_lis.append(item)\n return new_lis\n\nclass TreeModel(QStandardItemModel):\n def __init__(self, inspector):\n super().__init__()\n self.inspector = inspector\n self.datastore = self.inspector.get('datastore')\n\n def update(self, selection_reg=None):\n # Empty the model to start fresh\n self.clear()\n\n # Get loaded files from datastore\n files = self.datastore.get_all_files()\n\n # Iterate over files in datastore and build model\n for key, file in files.items():\n # Add filename to model\n parentItem = self.invisibleRootItem()\n item_file = TreeItem(file.get_filename())\n parentItem.appendRow(item_file)\n\n # Get list of dataset titles in file\n dataset_titles = file.get_names()\n\n # If a selection regex is given, filter all datasets with it\n if selection_reg:\n reg = re.compile(r'.*{}.*'.format(selection_reg), re.IGNORECASE)\n dataset_titles = list(filter(reg.match, dataset_titles))\n\n # Create dict to keep track of a dataset has been added to the tree\n dataset_added = {key: False for key in dataset_titles}\n # Create list to keep track of added subsystems\n subsystem_added = []\n\n # Find all systems in the file and sort them\n dataset_systems = list(set([title.split('-')[0].strip() for title in dataset_titles]))\n dataset_systems = sorted(dataset_systems, key=str.lower)\n\n # Add systems to the model\n for system in dataset_systems:\n # Select file item to start building model for this file\n parentItem = item_file\n\n # Create an item for this system and make it the root\n item_system = TreeItem(system)\n parentItem.append_child(item_system)\n\n # Get all datasets that belong to this system\n reg = re.compile(re.escape(system) + r'.*')\n system_datasets = list(filter(reg.match, dataset_titles))\n\n # Iterate over all datasets belonging to this system\n for dataset in system_datasets:\n # Select system item as parentItem\n parentItem = item_system\n\n # Look for subsystems with 2 words in common\n subsystem = ' '.join(dataset.split()[:4])\n reg = re.compile(re.escape(subsystem))\n subsystem_datasets = sorted(list(filter(reg.match, dataset_titles)), key=str.lower)\n\n # Only if subsystem has more than 3 datasets, it is grouped in a subsystem-folder\n if len(subsystem_datasets) > 3 and subsystem not in subsystem_added:\n # Add this subsystem to the list to prevent adding it again\n subsystem_added.append(' '.join(dataset.split()[:4]))\n\n # Add this subsystem to the model\n item_subsystem = TreeItem(' '.join(subsystem.split()[2:4]))\n parentItem.append_child(item_subsystem)\n\n # Add all datasets that belong to the subsytem to the model\n parentItem = item_subsystem\n for subsytem_dataset in subsystem_datasets:\n item_label = ' '.join(subsytem_dataset.split()[4:])\n item_dataset = TreeItem(item_label, dataset=file.get_dataset_by_name(subsytem_dataset))\n parentItem.append_child(item_dataset)\n dataset_added[subsytem_dataset] = True\n\n # Remove already-added datasets from the list to avoid double entries\n dataset_titles = [title for title in dataset_titles if dataset_added[title] == False]\n\n # Select system item as parentItem\n parentItem = item_system\n\n # Look for subsystems with 1 words in common\n subsystem = ' '.join(dataset.split()[:3])\n reg = re.compile(re.escape(subsystem))\n subsystem_datasets = sorted(list(filter(reg.match, dataset_titles)), key=str.lower)\n\n # Only if subsystem has more than 4 datasets, it is grouped in a subsystem-folder\n if len(subsystem_datasets) > 3 and subsystem not in subsystem_added:\n # Add this subsystem to the list to prevent adding it again\n subsystem_added.append(' '.join(dataset.split()[:3]))\n\n # Add this subsystem to the model\n item_subsystem = TreeItem(' '.join(subsystem.split()[2:3]))\n parentItem.append_child(item_subsystem)\n\n # Add all datasets that belong to the subsytem to the model\n parentItem = item_subsystem\n for subsytem_dataset in subsystem_datasets:\n item_label = ' '.join(subsytem_dataset.split()[3:])\n item_dataset = TreeItem(item_label, dataset=file.get_dataset_by_name(subsytem_dataset))\n parentItem.append_child(item_dataset)\n dataset_added[subsytem_dataset] = True\n\n # Get remaining datasets and add them\n dataset_titles = [title for title in dataset_titles if dataset_added[title] == False]\n parentItem = item_system\n for system_dataset in system_datasets:\n if dataset_added[system_dataset] == False:\n item_label = ' '.join(system_dataset.split()[2:])\n item_dataset = TreeItem(item_label, dataset=file.get_dataset_by_name(system_dataset))\n parentItem.append_child(item_dataset)\n\n\nclass TreeItem(QStandardItem):\n def __init__(self, label, dataset=None):\n super().__init__(label)\n if dataset:\n self.dataset = dataset\n self.type = 'dataset'\n else:\n self.type = 'system'\n self.children = []\n\n # Make item non-editable\n self.setEditable(False)\n\n def append_child(self, item):\n self.appendRow(item)\n self.children.append(item)\n\n def get_type(self): return self.type\n\n def get_datasets(self):\n datasets = []\n if self.type == 'dataset':\n datasets.append(self.dataset)\n else:\n for child in self.children:\n datasets.append(child.get_datasets())\n return datasets\n\n","sub_path":"plotter_widgets/tree_view.py","file_name":"tree_view.py","file_ext":"py","file_size_in_byte":8307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"193563328","text":"import re\n\n\ndef camelize(word):\n word = re.sub(\n r'[\\s_](.)',\n lambda m: m.group(1).title(),\n word, flags=re.DOTALL\n )\n return word\n\n\ndef camelize_value(value):\n if isinstance(value, list):\n value = [camelize_value(val) for val in value]\n elif isinstance(value, dict):\n value = {camelize(key): camelize_value(val) for key, val in value.items()}\n return value\n\n\ndef classify(word):\n tail = camelize(word[1:])\n head = word[:1].title()\n return '{}{}'.format(head, tail)\n","sub_path":"sockpuppet/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"233226962","text":"def check_brackets(brackets_row: str) -> bool:\n\t\"\"\"Check whether input string is a valid bracket sequence\n\t:param brackets_row: input string to be checked\n\t:return: True if valid, False otherwise\"\"\"\n\n\tbracket = 0\n\tfor i in brackets_row:\n\t\tif i == '(':\n\t\t\tbracket += 1\n\t\telse:\n\t\t\tbracket -= 1\n\t\t\tif bracket <= -1:\n\t\t\t\treturn False\n\n\treturn False if bracket != 0 else True\n\n","sub_path":"Tasks/a3_check_brackets.py","file_name":"a3_check_brackets.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"403042986","text":"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# =============================================================================\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow_addons.utils import keras_utils\n\n\n@keras_utils.register_keras_custom_object\nclass WeightNormalization(tf.keras.layers.Wrapper):\n \"\"\"This wrapper reparameterizes a layer by decoupling the weight's\n magnitude and direction.\n\n This speeds up convergence by improving the\n conditioning of the optimization problem.\n Weight Normalization: A Simple Reparameterization to Accelerate\n Training of Deep Neural Networks: https://arxiv.org/abs/1602.07868\n Tim Salimans, Diederik P. Kingma (2016)\n WeightNormalization wrapper works for keras and tf layers.\n ```python\n net = WeightNormalization(\n tf.keras.layers.Conv2D(2, 2, activation='relu'),\n input_shape=(32, 32, 3),\n data_init=True)(x)\n net = WeightNormalization(\n tf.keras.layers.Conv2D(16, 5, activation='relu'),\n data_init=True)(net)\n net = WeightNormalization(\n tf.keras.layers.Dense(120, activation='relu'),\n data_init=True)(net)\n net = WeightNormalization(\n tf.keras.layers.Dense(n_classes),\n data_init=True)(net)\n ```\n Arguments:\n layer: a layer instance.\n data_init: If `True` use data dependent variable initialization\n Raises:\n ValueError: If not initialized with a `Layer` instance.\n ValueError: If `Layer` does not contain a `kernel` of weights\n NotImplementedError: If `data_init` is True and running graph execution\n \"\"\"\n\n def __init__(self, layer, data_init=True, **kwargs):\n if not isinstance(layer, tf.keras.layers.Layer):\n raise ValueError(\n 'Please initialize `WeightNormalization` layer with a '\n '`Layer` instance. You passed: {input}'.format(input=layer))\n\n self.initialized = True\n if data_init:\n self.initialized = False\n\n super(WeightNormalization, self).__init__(layer, **kwargs)\n self._track_trackable(layer, name='layer')\n\n def _compute_weights(self):\n \"\"\"Generate weights by combining the direction of weight vector with\n its norm.\"\"\"\n with tf.name_scope('compute_weights'):\n self.layer.kernel = tf.nn.l2_normalize(\n self.layer.v, axis=self.kernel_norm_axes) * self.layer.g\n\n def _init_norm(self, weights):\n \"\"\"Set the norm of the weight vector.\"\"\"\n with tf.name_scope('init_norm'):\n flat = tf.reshape(weights, [-1, self.layer_depth])\n return tf.reshape(\n tf.linalg.norm(flat, axis=0), (self.layer_depth,))\n\n def _data_dep_init(self, inputs):\n \"\"\"Data dependent initialization.\"\"\"\n\n with tf.name_scope('data_dep_init'):\n # Generate data dependent init values\n activation = self.layer.activation\n self.layer.activation = None\n x_init = self.layer.call(inputs)\n data_norm_axes = list(range(x_init.shape.rank - 1))\n m_init, v_init = tf.nn.moments(x_init, data_norm_axes)\n scale_init = 1. / tf.math.sqrt(v_init + 1e-10)\n\n # Assign data dependent init values\n self.layer.g = self.layer.g * scale_init\n self.layer.bias = (-m_init * scale_init)\n self.layer.activation = activation\n self.initialized = True\n\n def build(self, input_shape):\n \"\"\"Build `Layer`\"\"\"\n input_shape = tf.TensorShape(input_shape).as_list()\n self.input_spec = tf.keras.layers.InputSpec(shape=input_shape)\n\n if not self.layer.built:\n self.layer.build(input_shape)\n self.layer.built = False\n\n if not hasattr(self.layer, 'kernel'):\n raise ValueError('`WeightNormalization` must wrap a layer that'\n ' contains a `kernel` for weights')\n\n # The kernel's filter or unit dimension is -1\n self.layer_depth = int(self.layer.kernel.shape[-1])\n self.kernel_norm_axes = list(\n range(self.layer.kernel.shape.rank - 1))\n\n self.layer.v = self.layer.kernel\n self.layer.g = self.layer.add_variable(\n name=\"g\",\n shape=(self.layer_depth,),\n initializer=tf.keras.initializers.get('ones'),\n dtype=self.layer.kernel.dtype,\n trainable=True,\n aggregation=tf.VariableAggregation.MEAN)\n\n # TODO: Check if this needs control deps in TF2 graph mode\n self.layer.g.assign(self._init_norm(self.layer.v))\n self._compute_weights()\n\n self.layer.built = True\n\n super(WeightNormalization, self).build()\n self.built = True\n\n @tf.function\n def call(self, inputs):\n \"\"\"Call `Layer`\"\"\"\n if not self.initialized:\n self._data_dep_init(inputs)\n\n self._compute_weights() # Recompute weights for each forward pass\n output = self.layer.call(inputs)\n return output\n\n def compute_output_shape(self, input_shape):\n return tf.TensorShape(\n self.layer.compute_output_shape(input_shape).as_list())\n","sub_path":"tensorflow_addons/layers/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":5911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"325748056","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport gym\nfrom gym import wrappers\n\ndef get_action(states, weights):\n action = 1 if states.dot(weights) > 0 else 0\n return action\n\ndef play_one_episode(environment, weights):\n observation = environment.reset()\n done = False\n score = 0\n while not done and score < 201:\n score += 1\n action = get_action(observation, weights)\n observation, reward, done, info = env.step(action)\n return score\n\ndef play_multiple_episodes(environment, number_of_runs, weights):\n scores = np.empty(number_of_runs)\n for i in range(number_of_runs):\n scores[i] = play_one_episode(environment, weights)\n average_score = scores.mean()\n print(\"Average score: \", average_score)\n return average_score\n\ndef random_search(environment):\n number_of_runs = 100\n scores = []\n best_score = 0\n best_weights = None\n for _ in range(100):\n new_weights = np.random.random(4) * 2 - 1\n average_score = play_multiple_episodes(environment, number_of_runs, new_weights)\n scores.append(average_score)\n if average_score > best_score:\n best_score = average_score\n best_weights = new_weights\n print(best_score)\n return scores, best_weights\n\nif __name__ == '__main__':\n env = gym.make('CartPole-v0')\n scores, weights = random_search(env)\n plt.plot(scores)\n plt.show()\n\n # play final episode\n env = wrappers.Monitor(env, './cartpole_video', force=True)\n print(\"Play episode with final weights\", play_one_episode(env, weights))\n","sub_path":"test03_monte_carlo/t54_save_video.py","file_name":"t54_save_video.py","file_ext":"py","file_size_in_byte":1581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"223759136","text":"from flask import Flask, render_template\nimport sqlite3 as sql \n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n \"\"\"db connection\"\"\"\n con = sql.connect(\"duckhacks2018.db\")\n cur = con.cursor()\n query = \" select C.category_name, E.expected_value, A.actual, A.comment from Actual_Spendings as A join Category as C on A.category_id = C.category_id join Expected_Spendings as E on A.category_id = E.category_id and A.user_id = E.user_id where A.month = 1 and A.user_id = 2\"\n\n cur.execute(query)\n rows = cur.fetchall()\n data = [{'category_name': category_name, 'expected_value': expected_value, 'actual': actual, 'comment':comment} for category_name, expected_value, actual, comment in rows]\n con.close()\n print(rows)\n return render_template('index.html', data=data)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"myapp/myapp.py","file_name":"myapp.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"417958169","text":"def search_word(element, my_list):\n if element in my_list:\n return True\n else:\n return False\n\n\nprint(\"Enter The Value\")\nvalue = input()\nf = open(\"list.txt\", \"rt\")\nmy_list1 = [words for lines in f for words in lines.split()]\nprint(search_word(value, my_list1))\n","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"445098243","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.preprocessing import minmax_scale\nfrom scipy.optimize import nnls\nfrom diffexp import gene_diff\nimport os\n\npure = pd.DataFrame()\nmix = pd.DataFrame()\ngene_list_df = pd.DataFrame()\nfactor_list = pd.DataFrame()\nreal_weight = pd.DataFrame()\nmixtures_sum = []\nother_res = 100\nnum_mixes = 0\nnum_cells = 0\ntest_cases = ['EPIC']\n\n#This function calculate a deconvolution algorithm.\ndef deconv(useSimpleDist):\n global pure, mix, gene_list_df, factor_list, real_weight, mixtures_sum\n\n O_array = np.zeros((num_cells, num_mixes)) # The per cell sorted array - how far each mix is from the maximal mix.\n i = 0\n #Loop on all cell types.\n for cell_type in gene_list_df:\n cell_vals = []\n cell_genelist = gene_list_df[cell_type].dropna().sample(frac=0.35)\n mix_temp = mix.loc[cell_genelist]\n max_ind = mix_temp.sum().idxmax() #Mix with maximum sum of gene expression.\n max_column = mix_temp[max_ind].copy()\n max_column.sort_values(ascending=False, inplace=True)\n #print(f'Max ind: {max_ind} len(max_column): {len(max_column)}')\n\n #Loop on all mixes.\n k = 0\n for mix_col in mix_temp:\n column = mix_temp[mix_col].copy()\n column = column[max_column.index] #Sort according to the maximum column index.\n\n if(useSimpleDist):\n dist = 0\n j = 0\n len_cell_genes = len(cell_genelist)\n for gene in cell_genelist:\n # Subtract the average of other cells on this gene to compensate for over estimation of ratio.\n delta = ((column[gene] + 0.000001) / (max_column[gene] + 0.000001)) * \\\n ((factor_list[cell_type][j] + 0.000001) / (factor_list[cell_type].sum() + 0.000001))\n #Handle missing values\n if np.isnan(delta):\n len_cell_genes -= 1\n else:\n dist += delta\n j += 1\n dist = dist/len_cell_genes\n #print(f'Cell type: {cell_type}, mix col: {mix_col}, dist: {dist}')\n cell_vals.append(dist)\n k += 1\n O_array[i] = cell_vals\n i += 1\n #We have to scale to [0,1] in order for the sum of proportions to be meaningful. Scale along each cell.\n if(useSimpleDist):\n O_scaled = np.transpose(O_array)\n else:\n O_scaled = np.transpose(1 - minmax_scale(O_array, axis=1))\n #print(O_scaled)\n solution = nnls(O_scaled, mixtures_sum)[0]\n solution_mat = np.diag(solution)\n estimate_wt = np.matmul(solution_mat, O_scaled.T)\n return(estimate_wt)\n\n\nif __name__ == '__main__':\n desc_file = pd.read_csv('/input/input.csv')\n #cells = ['B.cells', 'CD4.T.cells', 'CD8.T.cells', 'NK.cells'] #, 'neutrophils', 'monocytic.lineage', 'fibroblasts', 'endothelial.cells']\n k = 0\n output_df = pd.DataFrame(columns=['dataset.name', 'sample.id', 'cell.type', 'prediction'])\n\n for index, row in desc_file.iterrows():\n pure = pd.read_csv('/pure.csv', index_col=0)\n mix = pd.read_csv('/input/' + row['hugo.expr.file'], index_col=0)\n both_genes = list(set(mix.index) & set(pure.index))\n pure = pure.reindex(both_genes) # Drop genes that don't appear in mix.\n mix = mix.reindex(both_genes)\n num_mixes = len(mix.columns)\n num_cells = len(pure.columns)\n print(f'Test case: {row[\"dataset.name\"]}, num_cells: {num_cells}, num_mixes: {num_mixes}')\n result=0\n mixtures_sum=[1 for i in range(num_mixes)]\n gene_list_df, factor_list = gene_diff(pure)\n\n for method in [[0, deconv, True, 10]]:\n ens_estimate_wt = np.zeros((num_cells, num_mixes))\n for ens_i in range(method[3]):\n estimate_wt = method[1](method[2])\n ens_estimate_wt += estimate_wt\n ens_estimate_wt /= method[3]\n\n dist_from_mix = np.round(np.sum(np.sum(np.abs(mix - np.dot(pure, ens_estimate_wt)) / mix.size)), 2)\n print(f'Method distance from mix {dist_from_mix}')\n\n for i in range(num_cells): #Loop on cell-types.\n for j in range(num_mixes): #Loop on samples.\n output_df.loc[k] = [row['dataset.name'], mix.columns[j], pure.columns[i], ens_estimate_wt[i,j]]\n k += 1\n\n if not os.path.exists('/output'):\n os.makedirs('/output')\n output_df.to_csv('/output/predictions.csv', index=None)\n print(output_df)","sub_path":"yada/run_challenge.py","file_name":"run_challenge.py","file_ext":"py","file_size_in_byte":4537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"59095030","text":"from django.core.urlresolvers import reverse\nfrom rest_framework import status\nfrom rest_framework.test import APITestCase\n\n\nclass UserTests(APITestCase):\n\n\tdef helper_user_create(self):\n\t\tdata = {\n\t\t\t'username': 'test_user',\n\t\t\t'password': 'test_password',\n\t\t\t'email': 'test_user@test.com',\n\t\t\t'first_name': 'test_name',\n\t\t\t'last_name': 'test_lastname',\n\t\t}\n\t\treturn data\n\n\tdef create_user(self, data):\n\t\turl = reverse('app.views.create_user')\n\t\tresponse = self.client.post(url, data, format='json')\n\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\t\tself.assertIsNotNone(response.data.get('token'))\n\n\tdef setup_user(self):\n\t\tdata = self.helper_user_create()\n\t\turl = reverse('app.views.create_user')\n\t\tresponse = self.client.post(url, data, format='json')\n\n\t\tverify_url = reverse('rest_framework.authtoken.views.obtain_auth_token')\n\t\tdata.pop('first_name')\n\t\tdata.pop('last_name')\n\t\tdata.pop('email')\n\n\t\tresponse = self.client.post(verify_url, data)\n\t\tself.assertIsNotNone(response.data.get('token'))\n\n\t\tself.client.credentials(HTTP_AUTHORIZATION='Token ' + response.data.get('token'))\n\n\tdef test_create_user(self):\n\t\t\"\"\"\n\t\tEnsure we can still create a basic account\n\t\t\"\"\"\n\t\tdata = self.helper_user_create()\n\t\tself.create_user(data)\n\n\tdef test_create_user_only_required(self):\n\t\t\"\"\"\n\t\tEnsure that accounts can be created with only the required fields\n\t\t\"\"\"\n\t\tdata = self.helper_user_create()\n\t\tdata.pop('first_name')\n\t\tdata.pop('last_name')\n\t\tself.create_user(data)\n\n\tdef test_create_user_missing_email(self):\n\t\t\"\"\"\n\t\tEnsure that users cannot be created without an email\n\t\t\"\"\"\n\t\turl = reverse('app.views.create_user')\n\t\tdata = self.helper_user_create()\n\t\tdata.pop('email')\n\t\tresponse = self.client.post(url, data, format='json')\n\t\tself.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\n\n\tdef test_update_user(self):\n\t\t\"\"\"\n\t\tTest basic user updating\n\t\t\"\"\"\n\t\tself.setup_user()\n\t\turl = reverse('app.views.update_user')\n\n\t\tdata = {\n\t\t\t'first_name': 'changed'\n\t\t}\n\n\t\tresponse = self.client.put(url, data, format='json')\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\t\tself.assertEqual(response.data.get('first_name'), data['first_name'])\n\n\t\tdata = {\n\t\t\t'last_name': 'changed_last',\n\t\t\t'password': 'different'\n\t\t}\n\n\t\tresponse = self.client.put(url, data, format='json')\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\t\tself.assertEqual(response.data.get('last_name'), data['last_name'])\n\n\tdef test_get_user_profile(self):\n\t\t\"\"\"\n\t\tTest that /user/profile endpoint returns expected fields\n\t\t\"\"\"\n\t\tself.setup_user()\n\t\turl = reverse('app.views.get_my_user')\n\n\t\tresponse = self.client.get(url)\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\t\tself.assertIsNotNone(response.data)\n\n\t\tdata = response.data\n\t\texpected_fields = ['id', 'first_name', 'last_name', 'username', 'email', 'userType', 'place_id', 'place_name']\n\n\t\tself.assertEqual(set(data.keys()), set(expected_fields))\n\n\nclass EventTests(APITestCase):\n\n\tdef helper_user_create(self):\n\t\tdata = {\n\t\t\t'username': 'test_user',\n\t\t\t'password': 'test_password',\n\t\t\t'email': 'test_user@test.com',\n\t\t\t'first_name': 'test_name',\n\t\t\t'last_name': 'test_lastname',\n\t\t}\n\t\treturn data\n\n\tdef setup_user(self):\n\t\tdata = self.helper_user_create()\n\t\turl = reverse('app.views.create_user')\n\t\tresponse = self.client.post(url, data, format='json')\n\n\t\tverify_url = reverse('rest_framework.authtoken.views.obtain_auth_token')\n\t\tdata.pop('first_name')\n\t\tdata.pop('last_name')\n\t\tdata.pop('email')\n\n\t\tresponse = self.client.post(verify_url, data)\n\t\tself.assertIsNotNone(response.data.get('token'))\n\n\t\tself.client.credentials(HTTP_AUTHORIZATION='Token ' + response.data.get('token'))\n\n\tdef setup_event(self):\n\t\tdata = self.helper_create_event()\n\t\tresponse = self.create_event(data)\n\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\t\treturn response.data.get('id')\n\n\tdef helper_create_event(self):\n\t\tdata = {\n\t\t\t\"name\": \"This is an event title\",\n\t\t\t\"description\": \"We have a great description here :)\",\n\t\t\t\"picture\": \"RandomTest\",\n\t\t\t\"start_date\": \"2007-01-01T00:00:00Z\",\n\t\t\t\"end_date\": \"2007-01-02T00:00:00Z\",\n\t\t\t\"tags\": []\n\t\t}\n\t\treturn data;\n\n\tdef helper_vote_data(self, event_id, direction):\n\t\tdata = {\n\t\t\t\"event_id\": event_id,\n\t\t\t\"direction\": direction\n\t\t}\n\t\treturn data\n\n\tdef create_event(self, data):\n\t\turl = reverse('app.views.list_create_event')\n\t\treturn self.client.post(url, data, format='json')\n\n\tdef get_event(self, event_id):\n\t\turl = '/events/' + str(event_id) + '/'\n\t\treturn self.client.get(url)\n\n\tdef get_events(self, filter_args = None):\n\t\turl = reverse('app.views.list_create_event')\n\t\tif filter_args:\n\t\t\tpass\n\t\treturn self.client.get(url)\n\n\tdef vote_event(self, data):\n\t\turl = reverse('app.views.vote_event')\n\t\treturn self.client.post(url, data, format='json')\n\n\tdef validate_event(self, response_data, expected):\n\t\tfor key, value in expected.viewitems():\n\t\t\tif not isinstance(response_data.get(key), list):\n\t\t\t\tresponse_data[key] = response_data.get(key).encode('utf-8')\n\t\t\tself.assertEqual(response_data.get(key), value)\n\n\tdef test_create_event(self):\n\t\t\"\"\"\n\t\tEvent creation test with all fields\n\t\t\"\"\"\n\t\tself.setup_user()\n\t\tdata = self.helper_create_event()\n\n\t\tresponse = self.create_event(data)\n\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n\tdef helper_test_create_event_missing_field(self, field):\n\t\tself.setup_user()\n\t\tdata = self.helper_create_event()\n\t\tdata.pop(field)\n\t\tresponse = self.create_event(data)\n\t\tself.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)\n\t\tself.assertEqual(response.data.get(field)[0].encode('utf-8'), \"This field is required.\")\n\n\tdef test_create_event_missing_name(self):\n\t\t\"\"\"\n\t\tMissing name from event creation\n\t\t\"\"\"\n\t\tself.helper_test_create_event_missing_field('name')\n\n\tdef test_create_event_missing_description(self):\n\t\t\"\"\"\n\t\tMissing description from event creation\n\t\t\"\"\"\n\t\tself.helper_test_create_event_missing_field('description')\n\n\tdef test_create_event_missing_start_date(self):\n\t\t\"\"\"\n\t\tMissing start_date from event creation\n\t\t\"\"\"\n\t\tself.helper_test_create_event_missing_field('start_date')\n\n\tdef test_create_event_missing_end_date(self):\n\t\t\"\"\"\n\t\tMissing end_date from event creation\n\t\t\"\"\"\n\t\tself.helper_test_create_event_missing_field('end_date')\n\n\tdef test_update_event(self):\n\t\t\"\"\"\n\t\tBasic update event test\n\t\t\"\"\"\n\t\tself.setup_user()\n\t\tdata = self.helper_create_event()\n\n\t\tresponse = self.create_event(data)\n\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\t\tself.assertEqual(0, 1, \"IMPLEMENT UPDATING EVENTS\")\n\n\tdef test_get_event(self):\n\t\t\"\"\"\n\t\tTest if we can get an event we just created\n\t\t\"\"\"\n\t\tself.setup_user()\n\t\tdata = self.helper_create_event()\n\n\t\tresponse = self.create_event(data)\n\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n\t\tresponse = self.get_event(response.data.get('id'))\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\t\tself.validate_event(response.data, data)\n\n\tdef change_data(self, data, i):\n\t\tdata['name'] = data.get('name') + str(i)\n\t\treturn data\n\n\tdef test_get_events(self):\n\t\t\"\"\"\n\t\tTest if we can get a list of events we just created\n\t\t\"\"\"\n\t\tself.setup_user()\n\t\tdata = self.helper_create_event()\n\n\t\tdata_list = [self.change_data(data, i) for i in range(0, 10)]\n\t\tfor d in data_list:\n\t\t\tresponse = self.create_event(d)\n\t\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)\n\n\t\tresponse = self.get_events()\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\t\tfor response_data, expected_data in zip(response.data, data_list):\n\t\t\tself.validate_event(response_data, expected_data)\n\n\tdef test_get_events_filter(self):\n\t\t\"\"\"\n\t\tTODO: Test the filters we have in place when we do ranked events\n\t\t\"\"\"\n\t\tself.assertEqual(0, 1, \"TODO: Test the filters we have in place when we do ranked events\")\n\n\tdef vote(self, event_id, direction, expected):\n\t\tvote_data = self.helper_vote_data(event_id, direction)\n\t\tresponse = self.vote_event(vote_data)\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\n\t\tresponse = self.get_event(event_id)\n\t\tself.assertEqual(response.status_code, status.HTTP_200_OK)\n\t\tself.assertEqual(expected, response.data.get('vote'))\n\n\tdef test_event_upvote(self):\n\t\t\"\"\"\n\t\tTest event upvoting\n\t\t\"\"\"\n\t\tself.setup_user()\n\t\tevent_id = self.setup_event()\n\t\tself.vote(event_id, 1, 1)\n\n\tdef test_event_downvote(self):\n\t\t\"\"\"\n\t\tTest event downvoting\n\t\t\"\"\"\n\t\tself.setup_user()\n\t\tevent_id = self.setup_event()\n\t\tself.vote(event_id, -1, -1)\n\n\tdef test_event_novote(self):\n\t\t\"\"\"\n\t\tTest event novoting\n\t\t\"\"\"\n\t\tself.setup_user()\n\t\tevent_id = self.setup_event()\n\t\tself.vote(event_id, 0, 0)\n\n\tdef test_event_vote_algorithm(self):\n\t\t\"\"\"\n\t\tWe can do some rigourous testing of voting in this test.\n\t\t\"\"\"\n\t\tself.setup_user()\n\t\tevent_id = self.setup_event()\n\t\tself.vote(event_id, 1, 1)\n\t\tself.vote(event_id, -1, -1)\n\nclass ImageUploadTests(APITestCase):\n\n\tdef helper_user_create(self):\n\t\tdata = {\n\t\t\t'username': 'test_user',\n\t\t\t'password': 'test_password',\n\t\t\t'email': 'test_user@test.com',\n\t\t\t'first_name': 'test_name',\n\t\t\t'last_name': 'test_lastname',\n\t\t}\n\t\treturn data\n\n\tdef setup_user(self):\n\t\tdata = self.helper_user_create()\n\t\turl = reverse('app.views.create_user')\n\t\tresponse = self.client.post(url, data, format='json')\n\n\t\tverify_url = reverse('rest_framework.authtoken.views.obtain_auth_token')\n\t\tdata.pop('first_name')\n\t\tdata.pop('last_name')\n\t\tdata.pop('email')\n\n\t\tresponse = self.client.post(verify_url, data)\n\t\tself.assertIsNotNone(response.data.get('token'))\n\n\t\tself.client.credentials(HTTP_AUTHORIZATION='Token ' + response.data.get('token'))\n\n\tdef _create_test_file(self, path):\n\t\t# f = open(path, 'w')\n\t\t# f.write('testfile123\\n')\n\t\t# f.close()\n\t\tf = open(path, 'rb')\n\t\treturn {'image': f}\n\n\tdef test_upload_image(self):\n\t\tself.setup_user()\n\t\turl = reverse('app.views.upload_image')\n\t\tdata = self._create_test_file('/tmp/test_upload.png')\n\t\tresponse = self.client.post(url, data, format='multipart')\n\t\tdata['image'].close()\n\t\tself.assertEqual(response.status_code, status.HTTP_201_CREATED)","sub_path":"server/chronos/app/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":10009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"406688384","text":"\n'''\n File name: project2c3D.py\n Brief: convert 2 images into one 3D image.\n\n Description:\n In this file, we built a program that finds 2 images: left and right, and a common index,\n and converts the two images into one 3D image.\n Our method uses Sticher method to find a matrix that will be good enough\n for converting one image to be closed to the second.\n\n In this file, we built help functions: findHighestIndex(), createImageList(),\n convertPILtoPixels(), convertPixelstoPIL(), cleanImg(), trim().\n Those functions help us to find next index to work with, create list of images,\n convert image file into pixels and opposite, and clean image from black borders.\n\n Authors: Ayelet Zadock, Tamar Sadan\n Last modified: 04 Sep 2018\n'''\n\n# import the necessary packages\nimport imutils\nfrom stitch import Stitcher\nimport cv2\nimport scipy.misc\nimport os\nimport glob\nfrom PIL import Image, ImageChops\nimport numpy as np\n\n\n#--------------General variables-------------->\nformatJPG = '.jpg'\nformatPNG = '.png'\nformatImg = formatPNG\nPIX = 10 # 10 pixels =~ 1.5 cm\n\n\n#--------------Help functions-------------->\n'''\nFunction name: findHighestIndex()\n\nBrief: Function to find index.\n\nDescription:\nThis function looks for all files in current directory that end with .\nThe function sorts and filters them into files that start with 'left' and files that start with 'right',\nand put files' names in two lists.\nThe function looks for the highest index in left and the highest in right, and takes the minimum of both of them.\n\nInput: None.\nOutput:\n - minIndex: minimum index of both left and right indexes.\n - -1: for error state.\n\nErrors and exceptions:\n - If there is no left file in current directory, returns -1.\n - If there is no right file in current directory, returns -1.\n - If left file's name does not end with an integer, defines index to be 1.\n - If right file's name does not end with an integer, defines index to be 1.\n \n'''\ndef findHighestIndex():\n dirpath = os.getcwd() # get current folder's path\n leftfiles = glob.glob(dirpath + '/left*' + formatImg) # get left files' names that end with .formatImg\n rightfiles = glob.glob(dirpath + '/right*' + formatImg) # get right files' names that end with .formatImg\n\n # checks if there is at least one left file and at least one right file.\n # If one missing, returns -1, means, there is no file to work with.\n if len(leftfiles) < 1 or len(rightfiles) < 1:\n return -1\n\n leftfiles = (leftfiles[-1]).split('\\\\')[-1] # chooses the last filename in left list, takes only name, without path\n leftindexstr = leftfiles[4:-4] # takes index of left file\n rightfiles = (rightfiles[-1]).split('\\\\')[-1] # chooses the last filename in right list, takes only name, without path\n rightindexstr = rightfiles[5:-4] # takes index of right file\n\n # tries to convert indexes into integer, this to make sure that we really have a number\n try:\n leftindex = int(leftindexstr) # tries to convert left index\n except:\n leftindex = 1 # in case of exception, defines to minimum\n\n try:\n rightindex = int(rightindexstr) # tries to convert right index\n except:\n rightindex = 1 # in case of exception, defines to minimum\n\n minIndex = min(leftindex, rightindex) # minimum of both left and right indexes\n return minIndex\n\n\n'''\nFunction name: createImageList()\n\nBrief: Function to create a list of images.\n\nDescription:\nThis function gets two names of images.\nThe function reads the files, resizes them and creates a list, contains two image files.\n\nInput:\n - image1 (str): name of image No. 1.\n - image2 (str): name of image No. 2.\nOutput:\n - imagesList (list): list of 2 images.\n\nErrors and exceptions:\n - If occurred any error while reading or resizing the images,\n or while creating images list, returns None. \n\n'''\ndef createImageList(image1, image2):\n try:\n # load the two images\n imageA = cv2.imread(image1)\n imageB = cv2.imread(image2)\n\n # resize the two images to have a width of 400 pixels\n # (for faster processing)\n imageA = imutils.resize(imageA, width=400)\n imageB = imutils.resize(imageB, width=400)\n\n imagesList = [imageA, imageB] # create a list of images\n return imagesList\n except:\n return None\n\n\n'''\nFunction name: convertPILtoPixels()\n\nBrief: Function to convert a PIL image into pixels.\n\nDescription:\nThis function gets a PIL image and converts it into a matrix of pixels, using numpy library.\n\nInput:\n - pilImg (Image): a PIL image.\nOutput:\n - pix (numpy.ndarray): pixels of a given PIL image.\n\nErrors and exceptions:\n - If occurred an error while converting the image, returns None. \n \n'''\ndef convertPILtoPixels(pilImg):\n try:\n pix = np.array(pilImg) # converts a PIL image into a matrix of pixels\n return pix\n except:\n return None\n\n\n'''\nFunction name: convertPixelstoPIL()\n\nBrief: Function to convert a matrix of pixels into a PIL image.\n\nDescription:\nThis function gets a matrix of pixels and converts it into a PIL image, using numpy library.\n\nInput:\n - pixImg (numpy.ndarray): a matrix of pixels.\nOutput:\n - image (Image): a PIL image made from given matrix of pixels.\n\nErrors and exceptions:\n - If occurred an error while converting the pixels, returns None. \n\n'''\ndef convertPixelstoPIL(pixImg):\n try:\n pixArray = np.asarray(pixImg) # converts a given matrix of pixels into an array\n image = Image.fromarray(pixArray) # converts the array into an image\n return image\n except:\n return None\n\n\n'''\nFunction name: cleanImg()\n\nBrief: Function to clean a PIL image from border.\n\nDescription:\nThis function gets a PIL image and cleans its border.\n\nInput:\n - image (Image): a PIL image.\n - rgb (dict): a dictionary of r, g, and b images that combination of them brings the first input (image).\nOutput:\n - im3D (Image): a cleaned PIL image.\n\nErrors and exceptions:\n - If occurred an error while converting the PIL images into pixels or\n while converting the pixels image into a PIL image, returns None. \n\n'''\ndef cleanImg(image, rgb):\n pixImg = convertPILtoPixels(image) # converts a PIL image into pixels\n pixRed = convertPILtoPixels(rgb['r']) # converts a PIL image into pixels\n pixGreen = convertPILtoPixels(rgb['g']) # converts a PIL image into pixels\n pixBlue = convertPILtoPixels(rgb['b']) # converts a PIL image into pixels\n\n # checks if occurred any error while converting, if did, returns None\n if pixImg is None or pixRed is None or pixGreen is None or pixBlue is None:\n return None\n\n pixCyan = pixGreen + pixBlue # add green and blue to get cyan image\n\n # runs on each pixel and checks if it belongs to image or belongs to red or cyan image\n for row in range(len(pixImg)): # width\n for col in range(len(pixImg[0])): # height\n if (pixRed[row][col]).all() == 0 or (pixCyan[row][col]).all() == 0: # if pixel belongs to red or cyan image\n pixImg[row][col] = [0, 0, 0] # reset pixel to be black\n\n pilImg = convertPixelstoPIL(pixImg) # converts a matrix of pixels into a PIL image\n\n # checks if occurred any error while converting, if did, returns None\n if pilImg is None:\n return None\n\n im3D = trim(pilImg) # remove black border from image\n return im3D\n\n\n'''\nFunction name: trim()\n\nBrief: Function to crop black border from a PIL image.\n\nDescription:\nThis function gets a PIL image and removes its border.\n\nInput:\n - image (Image): a PIL image.\nOutput:\n - croppedImg (Image): a cropped PIL image.\n\nErrors and exceptions:\n - If didn't succeed to find positions to crop, return input image (image). \n\n'''\ndef trim(image):\n bg = Image.new(image.mode, image.size, image.getpixel((0, 0))) # create a new black image\n diff = ImageChops.difference(image, bg) # calculates absolute value of the difference between the two pix-by-pix\n diff = ImageChops.add(diff, diff, scale=2.0, offset=-100) # adds diff to diff, divides the result by scale and adds the offset\n bbox = diff.getbbox() # get positions to crop\n if bbox:\n croppedImg = image.crop(bbox) # crops image by positions that found before\n return croppedImg\n return image # if didn't succeed to find positions to crop\n\n\n'''\nFunction name: deleteTempImages()\n\nBrief: Function to delete files.\n\nDescription:\nThis function gets a path and deletes all images that named with the worrds left or right.\n\nInput:\n - dirpath (str): a path to directory.\nOutput: None.\n\nErrors and exceptions:\n - If didn't succeed to delete file, print an error message with filepath. \n\n'''\ndef deleteTempImages(dirpath):\n leftfiles = glob.glob(\n dirpath + '/*left*' + formatImg) # get left files' names that end with .formatImg\n rightfiles = glob.glob(\n dirpath + '/*right*' + formatImg) # get right files' names that end with .formatImg\n\n dirfiles = leftfiles + rightfiles\n for file_path in dirfiles:\n try:\n if os.path.isfile(file_path):\n os.unlink(file_path)\n except:\n print('Error while deleting {}.'.format(file_path))\n\n\n#--------------Main function-------------->\ndef main():\n print(\"Start combination of two images...\")\n\n index = findHighestIndex() # find index of file to work on\n if index == -1: # if did not find both left and right files\n print(\"Error occurred while searching the next index.\")\n else:\n indexstr = str(index)\n\n leftImage = 'left' + indexstr + formatImg # left image name\n rightImage = 'right' + indexstr + formatImg # right image name\n\n imagesList = createImageList(leftImage, rightImage) # create a list of left and right images\n\n if imagesList is not None: # if succeeded creating a list of images\n leftName = 'tempLeft'\n rightName = 'tempRight'\n\n # stitch the images together to create a panorama\n stitcher = Stitcher(formatImg, leftName, rightName)\n M = stitcher.stitch(imagesList, showMatches=True)\n\n if M is not None: # if Stitcher succeeded\n leftImage = leftName + formatImg # left image name\n rightImage = rightName + formatImg # right image name\n\n # Open the left and right images\n imLeft = Image.open(leftImage)\n imRight = Image.open(rightImage)\n\n # moves left image at PIX pixels to get better 3D image\n pixLeft = convertPILtoPixels(imLeft) # converts PIL image into pixels\n\n if pixLeft is not None:\n movedLeft = np.zeros((len(pixLeft), len(pixLeft[0]), 3), dtype=\"uint8\") # creates a black image\n movedLeft[:, PIX:] = pixLeft[:, :-PIX] # copies left's pixels with a movement of at PIX pixels\n\n movedLeft = convertPixelstoPIL(movedLeft) # converts pixels into PIL image\n\n if movedLeft is not None: # if succeeded to move left image\n imLeft = movedLeft # save moved image\n else:\n print('Error occurred while moving left image at {} pixels to right.'.format(PIX))\n\n # Split the images into Red, Green, and Blue\n lRed, lGreen, lBlue = imLeft.split()\n rRed, rGreen, rBlue = imRight.split()\n\n # The 3D image is the Red from the Right image\n # And the Green and Blue from the Left one\n rgb = {'r': rRed, 'g': lGreen, 'b': lBlue}\n im3D = Image.merge('RGB', list(rgb.values())) # create a 3D image\n\n clean3Dimg = cleanImg(im3D, rgb) # clean 3D image from border\n if clean3Dimg is None:\n print('Error occurred while trying to clean border of 3D image.')\n else: # if succeeded cleaning\n im3D = clean3Dimg\n\n # Show 3D image\n im3D.show()\n\n dirpath = os.getcwd() # current path\n dir3Dpath = dirpath + os.sep + r'3D' # get current folder's path and add new name of folder\n\n if not os.path.exists(dir3Dpath): # if 3D folder is not exist yet, create it\n os.makedirs(dir3Dpath)\n\n scipy.misc.imsave(r'3D\\3d_' + indexstr + formatImg, im3D) # save 3D image\n\n deleteTempImages(dirpath) # delete files that are out of use anymore\n\n else:\n print(\"There are not enough matches.\") # if image left and image right do not share enough data\n else:\n print(\"Error occurred while creating list of images.\") # if did not succeed to create a list of images\n\n print(\"End of combination.\")\n\n\n# run program\nif __name__.endswith('__main__'):\n main()\n","sub_path":"FrameCaptrue/FrameCaptrue/project2c3D.py","file_name":"project2c3D.py","file_ext":"py","file_size_in_byte":12937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"28545954","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, print_function\nimport os\nimport json\nimport yaml\nimport datetime\nfrom subprocess import Popen, PIPE\nimport imp\nfrom settings import CONTENT_EXPORTS as PROPS\n\nclass Pandoc:\n def __init__(self, from_config=None, **kwargs):\n self._path = PROPS[\"pandoc_path\"]\n self._args = {\"variable\":{}}\n self._include = []\n if from_config is not None:\n self._load_config(from_config)\n self._args.update(kwargs)\n\n def run(self, from_string=None, from_file=None):\n if from_file is not None:\n with open(from_file, 'r') as f:\n from_string = f.read().decode('utf8')\n \n if len(self._include) > 0:\n content = \"\"\n for fi in self._include:\n content += fi\n content += from_string\n else:\n content = from_string\n #print(self._gen_args())\n pr = Popen(self._gen_args(), stdin=PIPE, stdout=PIPE, stderr=PIPE)\n \n outcontent , errcontent = pr.communicate(content.encode('utf8'))\n \n return outcontent, errcontent\n \n def _load_config(self, conf_name):\n if conf_name[:3] == \"cfg\":\n conf = PROPS[\"configs_def\"][PROPS[conf_name]]\n else:\n conf = PROPS[\"configs_def\"][conf_name]\n \n \n if \"overide_config\" in conf:\n self._load_config(conf[\"overide_config\"])\n \n for k, v in conf.items():\n if k == \"overide_config\":\n continue\n elif k == \"input_format\":\n if isinstance(v, dict):\n fm = v[\"base\"]\n for ex in v[\"removed_exts\"]:\n fm += \"-{}\".format(ex)\n for ex in v[\"added_exts\"]:\n fm += \"+{}\".format(ex)\n self._args[\"read\"] = fm\n else:\n self._args[\"read\"] = v\n elif k == \"include\":\n for vv in v:\n ft = os.path.join(PROPS[\"template_path\"],vv)\n with open(ft, 'r') as f:\n content = f.read().decode('utf8')\n self._include.append(content)\n elif k == \"include_py\":\n \n for vv in v:\n ft = os.path.join(PROPS[\"template_path\"],vv)\n mod = imp.load_source(os.path.basename(ft)[:-3], ft)\n self._include.append(mod.markdown(PROPS, conf))\n elif k == \"flags\":\n for f in v:\n self._args[f] = True\n elif k == \"output_format\":\n self._args[\"write\"] = v\n elif k == \"variable\":\n self._args[k].update(v)\n elif k == \"template\":\n self._args[k] = os.path.join(PROPS[\"template_path\"], v)\n else:\n self._args[k] = v\n self._args[\"data-dir\"] = PROPS[\"template_path\"]\n self._args[\"variable\"][\"template-dir\"] = PROPS[\"template_path\"]\n \n def _gen_args(self):\n pd = [os.path.join(self._path, \"pandoc\")]\n bool_op = [\"--{}\".format(o) for o, v in self._args.items() if o != \"variable\" and isinstance(v, bool) and v]\n arg_op = [\"--{}={}\".format(o, v) for o, v in self._args.items() if o != \"variable\" and not isinstance(v, bool)]\n #var_op = [\"--variable={}:{}\".format(o, v) for o, v in self._args.get(\"variable\",{}).items()]\n var_op = []\n for o, v in self._args.get(\"variable\",{}).items():\n if isinstance(v, bool) and v:\n var_op.append(\"-V\")\n var_op.append(str(o))\n else:\n var_op.append(\"-V\")\n var_op.append(\"{}={}\".format(o, v))\n return pd + bool_op + arg_op + var_op\n\nfrom pandocfilters import walk, Image, Link\nimport urlparse\ndef is_absolute(url):\n return bool(urlparse.urlparse(url).netloc) or url.startswith(\"www\") or url.startswith(\"/home/\")\n\ndef rel_to_abs(key, value, fmt, meta):\n if key == 'Image' and not is_absolute(value[1][0]):\n return Image(value[0], [\"http://www.zestedesavoir.com\" + value[1][0], value[1][1]])\n elif key == \"Link\" and not is_absolute(value[1][0]):\n return Image([value[0], [\"http://www.zestedesavoir.com\" + value[1][0], value[1][1]]])\n \n\nclass Convertor:\n def __init__(self):\n self._ast = [{\"unMeta\":{}}, []]\n self._meta_args = {}\n self._errors = []\n self._content_path = \"\"\n self._content_type = None\n \n def parse(self, manifest_path, **kwargs):\n self._meta_args.update(kwargs)\n \n content = self._parse_manifest(manifest_path)\n \n self._convert_meta(content)\n self._convert_document(content)\n\n def _parse_manifest(self, manifest_path):\n self._content_path = os.path.dirname(manifest_path)\n with open(manifest_path) as f:\n content = json.load(f)\n return content\n \n def _convert_meta(self, manifest):\n metas = {\"title\":manifest[\"title\"],\n \"subtitle\":manifest[\"description\"],\n \"licence\":manifest.get(\"licence\"),\n #\"template_dir\":self._template_path,\n \"date\": datetime.datetime.now().strftime(\"%d/%m/%Y\") \n }\n metas.update(self._meta_args)\n \n meta_str = \"\\n\".join((\"---\", yaml.safe_dump(metas), \"...\", \"\"))\n \n content, errors = Pandoc(read=\"markdown_strict+yaml_metadata_block\", write=\"json\").run(from_string=meta_str)\n if len(errors) > 0:\n self._errors.append(\"Meta:\")\n self._errors.append(errors)\n \n nast = json.loads(content)\n \n self._merge_ast(nast)\n \n def _convert_document(self, content):\n self._content_type = content[\"type\"]\n if content[\"type\"] == \"article\":\n self._convert_article(content)\n elif content[\"type\"] == \"MINI\":\n self._convert_minituto(content)\n elif content[\"type\"] == \"BIG\":\n self._convert_bigtuto(content)\n else:\n raise TypeError(\"Unknown content type '{}'\".format(content[\"type\"]))\n \n def _convert_article(self, manifest):\n txt_path = os.path.join(self._content_path, manifest[\"text\"])\n content, errors = Pandoc(from_config=\"cfg_input\", write=\"json\").run(from_file=txt_path)\n \n if len(errors) > 0:\n self._errors.append(\"Article/text:\")\n self._errors.append(errors)\n \n nast = json.loads(content)\n \n self._merge_ast(nast)\n \n def _convert_minituto(self, manifest):\n pass\n \n def _convert_bigtuto(self, manifest):\n pass\n \n def _merge_ast(self, nast):\n nast = walk(nast, rel_to_abs, \"\", nast[0]['unMeta'])\n \n self._ast[0][\"unMeta\"].update(nast[0][\"unMeta\"])\n self._ast[1] += nast[1]\n \n def to_pdf(self, pdf_path):\n content_str = json.dumps(self._ast)\n conf = \"cfg_output_{}_pdf\".format(self._content_type)\n _, errors = Pandoc(from_config=conf, read=\"json\", output=pdf_path).run(from_string=content_str)\n if len(errors) > 0:\n self._errors.append(\"{}/pdf:\".format(self._content_type))\n self._errors.append(errors)\n \n return self._errors\n\n\n\ndef zds_content_convertor(manifest_path, \n authors=None, \n icon_path=None,\n pdf_output_path=None, \n epub_output_path=None,\n tags=None,\n url_source=None,\n licence=None):\n conv = Convertor()\n metas = {}\n if authors is not None:\n metas[\"author\"] = authors\n if icon_path is not None:\n metas[\"icon_path\"] = icon_path\n if tags is not None:\n metas[\"tags\"] = tags\n if url_source is not None:\n metas[\"url_source\"] = url_source\n if licence is not None:\n metas[\"licence\"] = licence\n \n conv.parse(manifest_path, **metas)\n err = []\n if pdf_output_path is not None:\n le = conv.to_pdf(pdf_output_path)\n err.extend(le)\n \n# if epub_output_path is not None:\n# err += \"EPUB:\\n\"\n# err += conv.to_epub(epub_output_path)\n# \n return err\n \n\nimport os\nimport csv\nimport urllib\nimport zipfile\nimport imghdr\n\nif __name__ == \"__main__\":\n output_path = \"./out/\"\n archive_path = \"./archive/\"\n articles_files = \"output.csv\"\n if not os.path.exists(output_path):\n os.makedirs(output_path)\n if not os.path.exists(archive_path):\n os.makedirs(archive_path)\n \n DOWLOAD_FILE = False\n EXTRACT_ARCHIVE = False\n DL_LOGO = True\n CONVERT = True\n \n SELECTED = 1\n \n with open(articles_files, 'rb') as csvfile:\n csvreader = csv.DictReader(csvfile)\n for j, row in enumerate(csvreader):\n if j != SELECTED:\n continue\n title = row[\"title\"]\n url_archive = \"http://zestedesavoir.com/articles/telecharger/?article={}&online\".format(int(row[\"pk\"]))\n #if row[\"image\"].endswith(\"jpg\") or row[\"image\"].endswith(\"jpeg\"):\n # url_logo = \"http://zestedesavoir.com{}.60x60_q85_crop.jpg\".format(row[\"image\"])\n #elif row[\"image\"].endswith(\"png\"):\n url_logo = \"http://zestedesavoir.com{}\".format(row[\"image\"])\n #else:\n # print(\"unknown image file format\", row[\"image\"])\n # http://zestedesavoir.com/media/articles/30/ee77e84b-da62-4fc9-9126-18d9a5991666.png.60x60_q85_crop.png\n url_source = \"http://zestedesavoir.com/articles/{}/{}/\".format(int(row[\"pk\"]), row[\"slug\"])\n archive_dl = os.path.join(archive_path, \"{}.zip\".format(row[\"slug\"]))\n extract_path = os.path.join(archive_path, row[\"slug\"])\n if DOWLOAD_FILE:\n urllib.urlretrieve(url_archive, archive_dl)\n if EXTRACT_ARCHIVE:\n if not os.path.exists(extract_path):\n os.makedirs(extract_path)\n with zipfile.ZipFile(archive_dl, \"r\") as z:\n z.extractall(extract_path)\n #logo_path = os.path.join(extract_path, \"logo.png\")\n if DL_LOGO:\n logo_path = __file__\n i = 0\n while imghdr.what(logo_path) is None or \"_\" in logo_path:\n i += 1\n logo_path, _ = urllib.urlretrieve(url_logo)\n print(\"logo dl in\", i, logo_path)\n licence = row[\"licence\"]\n date = row[\"pubdate\"].split(\" \")[0]\n a = row[\"authors\"].decode('utf-8')\n a = a.split(u\"][\")\n a[0] = a[0][1:]\n a[-1] = a[-1][:-1]\n authors = [e.split(u\":\")[1] for e in a]\n \n out_name = os.path.join(output_path, \"{}.pdf\".format(row[\"slug\"]))\n if CONVERT:\n manifeste_path = os.path.join(extract_path, \"manifest.json\")\n print(title)\n ret = zds_content_convertor(os.path.abspath(manifeste_path),\n authors,\n os.path.abspath(logo_path),\n os.path.abspath(out_name),\n None,\n [],\n url_source,\n licence)\n if len(ret) == 0:\n print(\" ----> Ok\")\n else:\n print(\" ----> Erreur\")\n #print(u\"\".join(map(unicode, ret)))\n for s in ret:\n print(s)\n if j == SELECTED:\n break\n #print ( \"\".join(zds_content_convertor(\"/home/christophe/Dev/pandoc/dist/build/pandoc/le-c14-est-arrive/manifest.json\",\n # [\"Kje\", \"gbdivers\", \"lmghs\", \"germinolegrand\"],\n # \"/home/christophe/Dev/pandoc/dist/build/pandoc/le-c14-est-arrive/logo.png\",\n # \"test.pdf\",\n # None,\n # [\"C++\", \"Orienté Objet\"],\n # \"http://zestedesavoir.com/articles/71/le-c14-est-arrive/\",\n # \"Licence CC BY\")))\n## python zdp.py -p /home/christophe/Dev/pandoc/dist/build/pandoc/ -t /home/christophe/Dev/zds_templates -a Eskimon olyte -g Ardunio DIY -i /home/christophe/Dev/pandoc/dist/build/pandoc/arduino-premiers-pas-en-informatique-embarquee/icon.png -f -s /home/christophe/Dev/zds_templates/smileys.md -d out.pdf /home/christophe/Dev/pandoc/dist/build/pandoc/le-c14-est-arrive/manifest.json\n\n","sub_path":"zdp.py","file_name":"zdp.py","file_ext":"py","file_size_in_byte":12917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"191330670","text":"from app.models.problematic_area import ProblematicArea # noqa\nfrom typing import Dict\nimport logging\n\nlog = logging.getLogger('root')\n\n\nclass ProblematicAreaAccessor:\n def __init__(self, session):\n self.session = session\n\n def create(self, problematic_area: ProblematicArea):\n log.info(f\"Inserting problematic area\")\n self.session.merge(problematic_area)\n self.session.commit()\n log.info(f\"Successfully inserted problematic area\")\n\n def read(self, filter_map: Dict):\n log.info(f\"Retrieving problematic area\")\n q = self.session.query(ProblematicArea)\n for k, v in filter_map.items():\n q = q.filter(getattr(ProblematicArea, k) == v)\n problematic_areas = q.all()\n problematic_areas = [g.as_dict() for g in problematic_areas]\n for problematic_area in problematic_areas:\n log.info(f\"Successfully retrieved problematic area\" + str(problematic_area))\n return problematic_areas\n\n def update(self, pri_map: Dict, upd_map: Dict):\n log.info(f\"Updating problematic area\")\n q = self.session.query(ProblematicArea)\n for k, v in pri_map.items():\n q = q.filter(getattr(ProblematicArea, k) == v)\n problematic_areas = q.all()\n problematic_areas = [g.as_dict() for g in problematic_areas]\n q.update(upd_map)\n self.session.commit()\n for problematic_area in problematic_areas:\n log.info(f\"Successfully updated problematic area\" + str(problematic_area))\n\n def delete(self, pri_map: Dict):\n log.info(f\"Deleting problematic area\")\n q = self.session.query(ProblematicArea)\n for k, v in pri_map.items():\n q = q.filter(getattr(ProblematicArea, k) == v)\n problematic_areas = q.all()\n problematic_areas = [g.as_dict() for g in problematic_areas]\n q.delete()\n self.session.commit()\n for problematic_area in problematic_areas:\n log.info(f\"Successfully deleted problematic area\" + str(problematic_area))\n\n def within(self, sql_text):\n log.info(f\"Checking if point lies within a problematic area\")\n results = self.session.execute(sql_text)\n for result in results:\n log.info(f\"Point within problematic area\" + str(result))\n return True\n log.info(f\"Point not within any problematic area\")\n return False\n","sub_path":"backend/app/accessors/problematic_area_accessor.py","file_name":"problematic_area_accessor.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"535022249","text":"import opensim as osim\nfrom osim.http.client import Client\nimport random\nimport numpy as np\nimport math\nimport pickle\nremote_base = \"http://grader.crowdai.org:1729\"\ncrowdai_token = \"d140e3d9a1bf0e4aa9b4efba4d862460\"\nclient = Client(remote_base)\nobservation = client.env_create(crowdai_token, env_id=\"ProstheticsEnv\")\n\ndef sigmoid(x):\n return 1/(1+np.exp(-x))\n\ndef relu(x):\n return np.multiply(x, (x>0))\n\nwith open('normalization.pkl', 'rb') as f:\n maximum, minimum, srednia = pickle.load(f)\n\nwith open('evolution.pkl', 'rb') as f:\n baza = pickle.load(f)\n\ndef for_prop_ac(theta, x): #x to macierz ileś X 1\n siec = []\n x = np.matrix(x).transpose()\n for i in range(len(theta)):\n x = np.concatenate( (np.matrix([1]), x.transpose()), axis= 1).transpose()\n siec.append(x)\n th = theta[i]\n if i == len(theta) - 1 :\n z = ( sigmoid( x.transpose() * th) ).copy()\n else:\n z = ( relu( x.transpose() * th ) ).copy()\n x = ( z.transpose() ).copy()\n siec.append(x)\n return siec\n\ndef dictionary_to_list(dictionary):\n l = []\n for i in dictionary.values():\n if type(i) == dict:\n l = l + dictionary_to_list(i)\n elif type(i) == list:\n l = l + i\n else:\n l.append(i)\n return l\n\ndef my_controller( observation ):\n global baza\n state = dictionary_to_list(observation)\n for i in range( len(state) ):\n if maximum[i] - minimum[i] != 0:\n state[i] = (state[i] - srednia[i]) / (maximum[i] - minimum[i])\n siec = for_prop_ac(baza, state)\n lista = []\n for i in range( len( siec[-1] ) ):\n lista.append(siec[-1][i, 0])\n return lista\n\nwhile True:\n [observation, reward, done, info] = client.env_step(my_controller(observation), True)\n print(observation)\n if done:\n observation = client.env_reset()\n if not observation:\n break\n\nclient.submit()","sub_path":"submit.py","file_name":"submit.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"289296126","text":"from odoo import models, fields, api\nfrom datetime import datetime\n\n\nclass VendorPurchaseReport(models.TransientModel):\n _name = 'vendor.purchase.report'\n\n vendor_ids = fields.Many2many('res.partner', string='Vendors', domain=[('supplier', '=', True)])\n date_start = fields.Date('Start Date', default=fields.date.today().replace(day=1, month=1), required=True)\n date_end = fields.Date('End Date', default=fields.date.today().replace(day=31, month=12), required=True)\n user_id = fields.Many2one('res.users', default=lambda self: self.env.user.id)\n\n def action_generate_report(self):\n data = {\n 'vendor_ids': self.vendor_ids.ids,\n 'date_start': self.date_start,\n 'date_end': self.date_end,\n }\n return self.env.ref('od_purchase_reports_dmc.action_vendor_purchase_report_dmc').report_action(self, data=data)\n\n\nclass ODPurchaseReportDMCXlsx(models.AbstractModel):\n _name = 'report.od_purchase_reports_dmc.vendor_purchase_report_xlsx'\n _inherit = 'report.report_xlsx.abstract'\n\n def generate_xlsx_report(self, workbook, data, records):\n date_from = data.get('date_start')\n date_to = data.get('date_end')\n vendor_ids = data.get('vendor_ids', [])\n start = datetime.strptime(date_from, \"%Y-%m-%d\")\n stop = datetime.strptime(date_to, \"%Y-%m-%d\")\n sheet = workbook.add_worksheet(\"Vendor Purchase report\")\n style4 = workbook.add_format({'border': 1, 'bold': True, 'align': 'center'})\n heading = workbook.add_format({'border': 1, 'bold': True, 'align': 'center', 'font_size': 14})\n heading2 = workbook.add_format({'border': 1, 'bold': True, 'align': 'center', 'font_size': 12})\n heading3 = workbook.add_format({'border': 0, 'bold': True, 'align': 'right'})\n total_style = workbook.add_format({\n 'top': False, 'bottom': 2, 'left': False, 'right': False, 'bold': True, 'align': 'right', 'font_size': 12\n })\n date_style = workbook.add_format({'border': 0, 'bold': True, 'align': 'right', 'num_format': 'h:mm AM/PM',})\n\n sheet.merge_range('A1:E3', 'DMC, DRY MORTAR COMPANY', heading)\n sheet.merge_range('A6:E6', \"Vendors Purchasing Report\", heading2)\n sheet.merge_range('A7:D7', f\"From Date Of: {date_from} up to date {date_to} (LOCAL PURCHASE)\", heading3)\n sheet.write(6, 4, datetime.now(), date_style)\n\n sheet.set_column(0, 0, 12)\n sheet.set_column(0, 4, 20)\n\n col, row = 0, 7\n sheet.write(row, col, 'Vendor', style4)\n sheet.write(row, col + 1, 'Name', style4)\n sheet.write(row, col + 2, 'Purchasing', style4)\n sheet.write(row, col + 3, 'Returns', style4)\n sheet.write(row, col + 4, 'Net Purchase', style4)\n\n purchase = 0\n return_purchase = 0\n net_purchase = 0\n # Local vendors\n row += 1\n first_row = row\n\n local_vendor_ids = self.env['res.partner'].browse(vendor_ids).filtered(lambda vend: vend.is_internal is True)\n for local_vendor in local_vendor_ids:\n vals = self.compute_purchase_return_net(start, stop, local_vendor)\n sheet.write(row, col, local_vendor.supplier_no)\n sheet.write(row, col + 1, local_vendor.name)\n sheet.write(row, col + 2, vals.get('purchase_amount', 0))\n sheet.write(row, col + 3, vals.get('return_amount', 0))\n sheet.write(row, col + 4, vals.get('net_amount', 0))\n purchase += vals.get('purchase_amount', 0)\n return_purchase += vals.get('return_amount', 0)\n net_purchase += vals.get('net_amount', 0)\n row += 1\n\n row += 1\n sheet.merge_range(f\"A{row+1}:B{row+1}\", 'Total', total_style)\n sheet.write(row, col+2, f\"=SUM(C{first_row+1}:C{row})\", total_style)\n sheet.write(row, col+3, f\"=SUM(D{first_row+1}:D{row})\", total_style)\n sheet.write(row, col+4, f\"=SUM(E{first_row+1}:E{row})\", total_style)\n\n row += 4\n # Imported vendors\n style4 = workbook.add_format({'border': 1, 'bold': True, 'align': 'center'})\n heading3 = workbook.add_format({'border': 1, 'bold': True, 'align': 'center'})\n total_style = workbook.add_format({\n 'top': False, 'bottom': 2, 'left': False, 'right': False, 'bold': True, 'align': 'right', 'font_size': 12\n })\n\n sheet.merge_range(f\"A{row}:E{row}\", f\"From Date Of: {date_from} up to date {date_to} (Imported PURCHASE)\", heading3)\n sheet.write(row, col, 'Vendor', style4)\n sheet.write(row, col + 1, 'Name', style4)\n sheet.write(row, col + 2, 'Purchasing', style4)\n sheet.write(row, col + 3, 'Returns', style4)\n sheet.write(row, col + 4, 'Net Purchase', style4)\n\n row += 1\n first_row = row\n\n local_vendor_ids = self.env['res.partner'].browse(vendor_ids).filtered(lambda vend: vend.is_internal is False)\n for local_vendor in local_vendor_ids:\n vals = self.compute_purchase_return_net(start, stop, local_vendor)\n sheet.write(row, col, local_vendor.supplier_no)\n sheet.write(row, col + 1, local_vendor.name)\n sheet.write(row, col + 2, vals.get('purchase_amount', 0))\n sheet.write(row, col + 3, vals.get('return_amount', 0))\n sheet.write(row, col + 4, vals.get('net_amount', 0))\n purchase += vals.get('purchase_amount', 0)\n return_purchase += vals.get('return_amount', 0)\n net_purchase += vals.get('net_amount', 0)\n row += 1\n\n row += 1\n sheet.merge_range(f\"A{row + 1}:B{row + 1}\", 'Total', total_style)\n sheet.write(row, col + 2, f\"=SUM(C{first_row + 1}:C{row})\", total_style)\n sheet.write(row, col + 3, f\"=SUM(D{first_row + 1}:D{row})\", total_style)\n sheet.write(row, col + 4, f\"=SUM(E{first_row + 1}:E{row})\", total_style)\n\n row += 2\n sheet.merge_range(f\"A{row + 1}:B{row + 1}\", 'NET PURCHASE', total_style)\n sheet.write(row, col + 2, purchase, total_style)\n sheet.write(row, col + 3, return_purchase, total_style)\n sheet.write(row, col + 4, net_purchase, total_style)\n\n def compute_purchase_return_net(self, date_from, date_to, vendor):\n domain = [\n ('type', 'in', ('in_invoice', 'in_refund')), ('state', 'not in', ('draft', 'cancel')),\n ('invoice_date', '>=', date_from), ('invoice_date', '<=', date_to), ('partner_id', '=', vendor.id),\n ]\n vals = {'purchase_amount': 0, 'return_amount': 0, 'net_amount': 0}\n invoices = self.env['account.move'].search(domain)\n purchase_amount = sum(invoices.filtered(lambda inv: inv.type == 'in_invoice').mapped('amount_untaxed'))\n return_amount = sum(invoices.filtered(lambda inv: inv.type == 'in_refund').mapped('amount_untaxed'))\n net_amount = purchase_amount - return_amount\n vals.update({'purchase_amount': purchase_amount, 'return_amount': return_amount, 'net_amount': net_amount})\n return vals\n","sub_path":"dmc/internal/od_purchase_reports_dmc/wizard/vendor_purchase_report.py","file_name":"vendor_purchase_report.py","file_ext":"py","file_size_in_byte":7025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"607996967","text":"# -*- coding: UTF-8 -*-\n# author:@Jack.Wang\n\n\nimport numpy as np\nimport pandas as pd\nimport math\nimport scipy.io as sio\nimport datetime\n\nclass jmavalue:\n def __init__(self):\n self.initFlag = True\n\n def jma_calculate(self, time, data ,Length ,phase):\n self.time = time\n self.data = data\n self.Length = Length\n self.phase = phase\n print('正在计算JMAValue,请稍等......')\n data = self.data\n lis = pd.DataFrame(np.zeros([128, 1]))\n ring1 = pd.DataFrame(np.zeros([128, 1]))\n ring2 = pd.DataFrame(np.zeros([11, 1]))\n buffer = pd.DataFrame(np.zeros([62, 1]))\n\n limitValue = 63\n startValue = 64\n\n lis.iloc[0:64,:] = -1000000\n lis.iloc[64:128,:] = 1000000\n\n if self.Length < 1:\n lengthParam = 0.00000001\n else:\n lengthParam = (self.Length - 1)/2\n\n if self.phase < -100:\n phaseParam = 0.5\n elif self.phase > 100:\n phaseParam = 2.5\n else:\n phaseParam = self.phase/101.5\n logParam = math.log(math.sqrt(lengthParam),10)/math.log(2,10)\n if logParam + 2 < 0:\n logParam = 0\n else:\n logParam = logParam + 2\n\n sqrtParam = math.sqrt(lengthParam)*logParam\n lengthParam = lengthParam*0.9\n lengthDivider = lengthParam/(lengthParam + 2)\n\n nr = self.time.size\n\n JMAValueBuffer = pd.DataFrame(np.zeros([nr, 1]))\n fC0Buffer = pd.DataFrame(np.zeros([nr, 1]))\n fC8Buffer = pd.DataFrame(np.zeros([nr, 1]))\n fA8Buffer = pd.DataFrame(np.zeros([nr, 1]))\n\n loopParam = 0\n cycleLimit = 0\n cycleDelta = 0\n loopCriteria = 0\n counterA = 0\n counterB = 0\n lowDValue = 0\n\n for shift in range(0, nr):\n print(str(datetime.datetime.now()) + ' '+str(shift) + ' in ' + str(nr))\n series = data.iloc[shift, 0]\n if loopParam < 61:\n loopParam += 1\n buffer.iloc[loopParam, 0] = series\n if loopParam <= 30:\n JMATempValue = 0\n if loopParam > 30:\n if self.initFlag:\n highlimit, paramB, paramA = self.Firsttime(buffer, series)\n for i in range(highlimit, -1, -1):\n # 计算sValue 1\n sValue = self.s1(buffer, i, series)\n # 计算absValue 1\n absValue = self.s2(sValue, paramA, paramB)\n # 计算dValue 1\n dValue = self.s3(absValue)\n # 计算counterA 1\n counterA = self.s4(counterA)\n # 计算counterB 1\n counterB = self.s5(counterB)\n # 更新cycleDelta ring2\n if cycleLimit < 128:\n cycleLimit, cycleDelta, ring2 = self.s6(cycleLimit, cycleDelta, dValue, ring2, counterB)\n # highDValue 1\n highDValue = self.s7(cycleDelta, cycleLimit)\n if cycleLimit > 127:\n dValue, ring1, s68, s58 = self.s8(ring1, counterA, highDValue, lis)\n else:\n ring1, startValue, limitValue, s58, s38, s40 = self.s9(ring1, counterA, highDValue, limitValue, startValue)\n # s68 s60 1\n s68, s60 = self.s10(lis, highDValue)\n if cycleLimit > 127:\n lowDValue = self.s11(s58, s60, s40, s38, lowDValue, highDValue, lis)\n lowDValue = self.s12(s58, s60, s40, s38, lowDValue, lis)\n lis = self.s13(s58, s60, lis, highDValue)\n \"\"\"\n if cycleLimit <= 127\n lowDValue = 0\n for j in range(s40,s38 + 1):\n lowDValue = lowDValue + lis.iloc[j,0]\n \"\"\"\n loopCriteria = self.s14(loopCriteria)\n JMATempValue = 0\n sqrtDivider = sqrtParam/(sqrtParam + 1)\n if loopCriteria <= 30:\n paramA, paramB = self.s15(sValue, paramA, paramB, sqrtDivider)\n JMATempValue = series\n if loopCriteria == 30:\n # ????\n fC0Buffer.iloc[shift, 0] = series\n leftInt, rightPart, dValue, upShift, dnShift = self.s16(sqrtParam)\n fA8Buffer.iloc[shift, 0] = series - buffer.iloc[loopParam - upShift, 0]*(1 - dValue) / rightPart + \\\n (series - buffer.iloc[loopParam - dnShift, 0]) * dValue / leftInt\n elif loopCriteria > 30:\n dValue, powerValue = self.s17(lowDValue, s38, s40, logParam, absValue, sqrtDivider)\n paramA, paramB = self.s18(sValue, paramA, paramB, powerValue)\n if loopCriteria > 30:\n JMATempValue = self.s19(fC0Buffer,fA8Buffer,fC8Buffer,JMAValueBuffer,shift,lengthDivider, dValue, series,phaseParam)\n JMAValueBuffer.iloc[shift, 0] = JMATempValue\n if nr % 1000 == 0:\n print(str(nr/1000) + ' in ', str(nr))\n print('JMAValue计算完毕!!!')\n return JMAValueBuffer\n\n def Firsttime(self, buffer, c):\n self.initFlag = False\n diffflag = 0\n for i1 in range(0, 29):\n if buffer.iloc[i1 + 1, 0] != buffer.iloc[i1, 0]:\n diffflag = 1\n highlimit = diffflag * 30\n if highlimit == 0:\n paramB = c\n else:\n paramB = buffer.iloc[1]\n paramA = paramB\n if highlimit > 29:\n highlimit = 29\n else:\n highlimit = 0\n paramA = paramA[0]\n paramB = paramB[0]\n return highlimit, paramB, paramA\n def s1(self, buffer, i, c):\n if i == 0:\n sValue = c\n else:\n sValue = buffer.iloc[31 - i, 0]\n return sValue\n def s2(self, sValue, paramA, paramB):\n if abs(sValue - paramA) > abs(sValue - paramB):\n absValue = sValue - paramA\n else:\n absValue = sValue - paramB\n return absValue\n def s3(self, absValue):\n dValue = absValue + 0.0000000001\n return dValue\n def s4(self, counterA):\n if counterA <= 1:\n counterA = 127\n else:\n counterA = counterA - 1\n return counterA\n def s5(self, counterB):\n if counterB <= 1:\n counterB = 10\n else:\n counterB = counterB - 1\n return counterB\n def s6(self, cycleLimit, cycleDelta, dValue, ring2, counterB):\n cycleLimit = cycleLimit + 1\n cycleDelta = cycleDelta + dValue - ring2.iloc[counterB, 0]\n ring2.iloc[counterB, 0] = dValue\n return cycleLimit, cycleDelta, ring2\n def s7(self, cycleDelta, cycleLimit):\n if cycleLimit > 10:\n highDValue = cycleDelta/10.0\n else:\n highDValue = cycleDelta/cycleLimit\n return highDValue\n def s8(self,ring1, counterA, highDValue, lis):\n dValue = ring1.iloc[counterA, 0]\n ring1.iloc[counterA, 0] = highDValue\n s68 = 64\n s58 = s68\n while s68 > 1:\n if lis.iloc[s58, 0] < dValue:\n s68 = int(s68/2)\n s58 = s58 + s68\n else:\n if lis.iloc[s58, 0] <= dValue:\n s68 = 1\n else:\n s68 = int(s68/2)\n s58 = s58 - s68\n return dValue, ring1, s68, s58\n def s9(self, ring1, counterA, highDValue, limitValue, startValue):\n ring1.iloc[counterA, 0] = highDValue\n if limitValue + startValue > 127:\n startValue = startValue - 1\n s58 = startValue\n else:\n limitValue = limitValue + 1\n s58 = limitValue\n\n if limitValue > 96:\n s38 = 96\n else:\n s38 = limitValue\n\n if startValue < 32:\n s40 = 32\n else:\n s40 = startValue\n\n return ring1, startValue, limitValue, s58, s38, s40\n def s10(self, lis, highDValue):\n s68 = 64\n s60 = s68\n while s68 > 1:\n if lis.iloc[s60, 0] >= highDValue:\n if lis.iloc[s60 - 1, 0] <= highDValue:\n s68 = 1\n else:\n s68 = int(s68/2)\n s60 = s60 - s68\n else:\n s68 = int(s68/2)\n s60 = s60 + s68\n if s60 == 127 and highDValue > lis.iloc[127, 0]:\n s60 = 128\n return s68, s60\n def s11(self, s58, s60, s40, s38, lowDValue, highDValue, lis):\n if s58 >= s60:\n if ((s38 + 1) > s60) and ((s40 - 1) < s60):\n lowDValue = lowDValue + highDValue\n elif (s40 > s60) and ((s40 - 1) < s58):\n lowDValue = lowDValue + lis.iloc[s40 - 1, 0]\n elif s40 >= s60:\n if ((s38 + 1) < s60) and ((s38 + 1) > s58):\n lowDValue = lowDValue + lis.iloc[s38 + 1, 0]\n elif (s38 + 2) > s60:\n lowDValue = lowDValue + highDValue\n elif (s38 + 1) < s60 and (s38 + 1) > s58:\n lowDValue = lowDValue +lis.iloc[s38 + 1,0]\n return lowDValue\n def s12(self, s58, s60, s40, s38, lowDValue, lis):\n if s58 > s60:\n if ((s40 - 1) < s58) and ((s38 + 1) > s58):\n lowDValue = lowDValue - lis.iloc[s58, 0]\n elif (s38 < s58) and ((s38 + 1) > s60):\n lowDValue = lowDValue - lis.iloc[s38, 0]\n else:\n if ((s38 + 1) > s58) and ((s40 - 1) < s58):\n lowDValue = lowDValue - lis.iloc[s58, 0]\n elif (s40 > s58) and (s40 < s60):\n lowDValue = lowDValue - lis.iloc[s40, 0]\n return lowDValue\n def s13(self, s58, s60, lis, highDValue):\n if s58 <= s60:\n if s58 >= s60:\n lis.iloc[s60, 0] = highDValue\n else:\n for j in range(s58 + 1, s60):\n lis.iloc[j - 1, 0] = lis.iloc[j, 0]\n lis.iloc[s60 - 1, 0] = highDValue\n else:\n for j in range(s58 - 1, s60 + 1, -1):\n lis.iloc[j + 1, 0] = lis.iloc[j, 0]\n lis.iloc[s60, 0] = highDValue\n return lis\n def s14(self, loopCriteria):\n if loopCriteria + 1 > 31:\n loopCriteria = 31\n else:\n loopCriteria = loopCriteria + 1\n return loopCriteria\n def s15(self,sValue, paramA, paramB,sqrtDivider):\n if sValue - paramA > 0:\n paramA = sValue\n else:\n paramA = sValue - (sValue - paramA)*sqrtDivider\n if sValue - paramB < 0:\n paramB = sValue\n else:\n paramB = sValue - (sValue - paramB)*sqrtDivider\n return paramA, paramB\n def s16(self, sqrtParam):\n if math.ceil(sqrtParam) >= 1:\n intPart = math.ceil(sqrtParam)\n else:\n intPart = 1\n leftInt = self.IntPortion(intPart)\n if math.floor(sqrtParam) >= 1:\n intPart = math.floor(sqrtParam)\n else:\n intPart = 1\n rightPart = self.IntPortion(intPart)\n if leftInt == rightPart:\n dValue = 1\n else:\n dValue = (sqrtParam - rightPart)/(leftInt - rightPart)\n upShift = min(rightPart, 29)\n dnShift = min(leftInt, 29)\n return leftInt, rightPart, dValue, upShift, dnShift\n def s17(self, lowDValue, s38, s40, logParam, absValue, sqrtDivider):\n dValue = lowDValue/(s38 - s40 + 1)\n if 0.5 <= logParam - 2:\n powerValue = logParam - 2\n else:\n powerValue = 0.5\n if abs(absValue/dValue) < 0.1:\n dValue = 0\n elif logParam >= abs(pow(absValue/dValue, powerValue)):\n dValue = abs(math.pow((absValue/dValue), powerValue))\n else:\n dValue = logParam\n if dValue < 1:\n dValue = 1\n powerValue = math.pow(sqrtDivider, math.sqrt((dValue)))\n return dValue, powerValue\n def s18(self, sValue, paramA, paramB, powerValue):\n if sValue - paramA > 0:\n paramA = sValue\n else:\n paramA = sValue - (sValue - paramA)*powerValue\n if sValue - paramB < 0:\n paramB = sValue\n else:\n paramB = sValue - (sValue - paramB)*powerValue\n return paramA, paramB\n def s19(self,fC0Buffer,fA8Buffer,fC8Buffer,JMAValueBuffer,shift,lengthDivider, dValue, c,phaseParam):\n JMATempValue = JMAValueBuffer.iloc[shift - 1, 0]\n powerValue = math.pow(lengthDivider, dValue)\n squareValue = math.pow(powerValue, 2)\n fC0Buffer.iloc[shift, 0] = (1 - powerValue) * c + powerValue * fC0Buffer.iloc[shift - 1, 0]\n fC8Buffer.iloc[shift, 0] = (c - fC0Buffer.iloc[shift, 0]) * (1 - lengthDivider) + lengthDivider * \\\n fC8Buffer.iloc[shift - 1, 0]\n temp1 = (phaseParam * fC8Buffer.iloc[shift, 0] + fC0Buffer.iloc[shift, 0] - JMATempValue)\n temp2 = (powerValue * (-2.0) + squareValue + 1)\n fA8Buffer.iloc[shift, 0] = temp1*temp2 + squareValue*fA8Buffer.iloc[shift - 1, 0]\n\n JMATempValue = JMATempValue + fA8Buffer.iloc[shift, 0]\n return JMATempValue\n\n def IntPortion(self, param):\n if param > 0:\n out = math.floor(param)\n elif param < 0 :\n out = math.ceil(param)\n if param == 0:\n out = 0\n return out\n\nif __name__=='__main__':\n file_name = \"F:\\Quant\\Data\\Futures_KLine\\Day\\J201809.mat\"\n d = sio.loadmat(file_name)\n time = d['time_str']\n data = d['data']\n time_list = []\n for t in time:\n time_list.append(t[0][0])\n time = pd.DataFrame(time_list)\n data = pd.DataFrame(data, columns=['o','h','l','c'])\n data = pd.DataFrame(data.iloc[:, 3])\n\n\n self = jmavalue(time,data)\n jma = self.jma_calculate\n print(jma)\n\n","sub_path":"strategy/jma_process.py","file_name":"jma_process.py","file_ext":"py","file_size_in_byte":14235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"394745022","text":"from favBookApp.models import Book, Author, Review\nfrom loginApp.models import User\nfrom django import forms\nimport datetime\nfrom django.forms.widgets import TextInput\n\nRATING_CHOICES = (\n (\"\", \"\"),\n ('1', 1), \n ('2', 2), \n ('3', 3), \n ('4', 4), \n ('5', 5)\n )\nYEAR_CHOICES = ['1980', '1981', '1982']\n# Create tuple with options for dropdown\nAUTHOR_CHOICES = ((\"\", \"\"),)\nauthors = Author.objects.all()\nfor author in authors:\n AUTHOR_CHOICES = AUTHOR_CHOICES + ((author.id, author.full_name),)\n\nclass Date_In(TextInput):\n input_type = 'date'\n\nclass BookForm(forms.Form):\n title = forms.CharField(max_length=200, widget=forms.TextInput) \n author = forms.CharField(max_length=200, widget=forms.TextInput, required=False)\n # Dropdown field\n author_sel = forms.ChoiceField(widget=forms.Select, choices=AUTHOR_CHOICES, required=False) \n review = forms.CharField(widget=forms.Textarea, required=False)\n rating = forms.ChoiceField(widget=forms.Select, choices=RATING_CHOICES, required=False)\n # dateSelect = forms.DateTimeField(widget=Date_In)\n # email = forms.EmailField(max_length = 200, widget=forms.EmailInput)\n\n def __init__(self, *args, **kwargs):\n super(BookForm, self).__init__(*args, **kwargs)\n ## add a \"form-control\" class to each form input\n ## for enabling bootstrap \n for name in self.fields.keys():\n self.fields[name].widget.attrs.update({\n 'class': 'form-control',\n }) \n # self.fields['dateSelect'].widget.attrs.update({'class': 'form-control datetimepicker-input w-50'})\n self.fields['author_sel'].label = \"Choose an author from the list:\" \n self.fields['review'].widget.attrs.update({ 'rows': '4' })\n self.fields['rating'].widget.attrs.update({ 'class': 'form-control w-25' }) \n \n\n def clean(self):\n super(BookForm, self).clean()\n title = self.cleaned_data.get('title')\n desc = self.cleaned_data.get('desc')\n author = self.cleaned_data.get('author')\n author_sel = self.cleaned_data.get('author_sel')\n review = self.cleaned_data.get('review')\n rating = self.cleaned_data.get('rating')\n \n if author_sel == '':\n if len(author) > 2 and author != '' and author_sel == '': \n fName = author.split(\" \", 1)[0]\n lName = author.split(\" \", 1)[1]\n author_obj = Author.objects.filter(first_name__contains=fName).filter(last_name__contains=lName)\n if len(author_obj) > 0:\n self.errors['author'] = self.error_class([\n 'Author already exists'])\n elif len(fName) < 2 or len(fName) < 2:\n self.errors['author'] = self.error_class([\n 'Name must be at least 2 non-numeric characters.'])\n else:\n self.errors['author'] = self.error_class([\n 'Please specify an Author.'])\n # elif author_sel == '':\n # self.errors['author'] = self.error_class([\n # 'Please specify an Author.'])\n # else:\n # self.errors['author'] = self.error_class([\n # 'Name must be at least 2 non-numeric characters.'])\n book_obj = Book.objects.filter(title=title)\n if len(book_obj) > 0:\n self.errors['author'] = self.error_class([\n 'Book already exists.']) \n elif len(title) < 2: \n self.errors['title'] = self.error_class([\n 'Title must be at least 2 characters.']) \n if review != '': \n if len(review) <= 10:\n self.errors['review'] = self.error_class([\n 'Review must be longer than 10 characters.'])\n if rating == '-' or not len(rating) > 0 :\n self.errors['rating'] = self.error_class([\n 'Please rate this book.'])\n \n # return errors\n\n return self.cleaned_data\n\nclass ReviewForm(forms.Form):\n review = forms.CharField(widget=forms.Textarea)\n rating = forms.ChoiceField(widget=forms.Select, choices=RATING_CHOICES) \n def __init__(self, *args, **kwargs):\n super(ReviewForm, self).__init__(*args, **kwargs)\n for name in self.fields.keys():\n self.fields[name].widget.attrs.update({\n 'class': 'form-control',\n })\n self.fields['review'].widget.attrs.update({ 'rows': '4' })\n self.fields['rating'].widget.attrs.update({ 'class': 'form-control w-25' })\n\n def clean(self):\n super(ReviewForm, self).clean() \n review = self.cleaned_data.get('review') \n rating = self.cleaned_data.get('rating') \n if len(review) <= 10:\n self.errors['review'] = self.error_class([\n 'Review must be longer than 10 characters.'])\n if rating == '-' or not len(rating) > 0 :\n self.errors['rating'] = self.error_class([\n 'Please rate this book.'])\n return self.cleaned_data\n","sub_path":"favBookApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"299863941","text":"from Player import Player\nfrom Team import Team\nfrom Match import Match\n\nimport json\n\n\ndef main():\n players = read_players()\n teams = create_teams(players)\n write_teams(teams)\n matches = create_matches(teams)\n write_matches(matches)\n print(len(matches))\n\n\ndef read_players():\n players = None\n with open('players.json', 'r') as src:\n players = json.load(src)\n return [Player(player_src['name']) for player_src in players]\n\n\ndef create_teams(players):\n teams = []\n for index in range(len(players)):\n player_1 = players[index]\n for player_2 in players[index + 1:]:\n teams.append(Team(player_1, player_2)) \n for num in range(len(teams)):\n teams[num].num = num + 1\n return teams\n\n \ndef write_teams(teams): \n with open('teams.json', 'w') as res:\n json.dump([t.serialize() for t in teams], res, indent=4)\n\n\ndef create_matches(teams):\n matches = []\n for index in range(len(teams)):\n team_1 = teams[index]\n for team_2 in filter(lambda t: validate_teams(team_1, t), teams[index + 1:]):\n matches.append(Match(team_1.num, team_2.num))\n for num in range(len(matches)):\n matches[num]._num = num + 1\n return matches\n\n\ndef validate_teams(team_1, team_2):\n if team_1.player_1.name == team_2.player_1.name:\n return False\n elif team_1.player_1.name == team_2.player_2.name:\n return False\n elif team_1.player_2.name == team_2.player_1.name:\n return False\n elif team_1.player_2.name == team_2.player_2.name:\n return False\n else:\n return True\n\ndef write_matches(matches):\n with open('matches.json', 'w') as res:\n json.dump([m.serialize() for m in matches], res, indent=4)\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/init_championship.py","file_name":"init_championship.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"552620856","text":"#-*- coding: UTF-8 -*-\n\"\"\"\n accesos_directos_rango(actual, total, numero_accesos)\n Un ejemplo de uso seria:\n ant_pag, pos_pag = accesos_directos_rango(20, 100, 5)\n Y podriamos, si por ejemplo lo usamos para paginar articulos de\n un blog, usar este código en la plantilla:\n {% block paginacion %}\n {% if articulos.has_other_pages %}\n
\n {% if articulos.has_previous %}\n primera\n \n <\n \n {% for anterior in ant_pag %}\n {{ anterior }}\n {% endfor %}\n {% endif %}\n \n {{ articulos.number }}\n \n {% if articulos.has_next %}\n {% for posterior in pos_pag %}\n {{ posterior }}\n {% endfor %}\n \n >\n \n \n ultima\n \n {% endif %}\n
\n {% endif %}\n {% endblock %}\n Y podemos quitar el subrayado de los enlaces con el CSS:\n .paginacion a\n {\n text-decoration:none;\n }\n\"\"\"\n\n\ndef accesos_directos_rango(actual, total, numero_accesos):\n if numero_accesos < 1:\n return [[], []]\n inicial = actual - numero_accesos\n if inicial < 1:\n inicial = 1\n final = actual + numero_accesos\n if final > total:\n final = total\n return [range(inicial, actual), range(actual + 1, final + 1)]\n","sub_path":"paginacionhc/PaginacionMejorada.py","file_name":"PaginacionMejorada.py","file_ext":"py","file_size_in_byte":1982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"300551697","text":"from nltk import word_tokenize\nfrom nltk.stem import PorterStemmer\nfrom nltk.util import ngrams\nfrom collections import Counter\nimport re\nimport random\nimport copy\nimport functools\nimport operator\nimport argparse\n\n#nltk.download('punkt')\ndef read_text():\n file = open(\"shakes.txt\", \"rt\")\n text = file.read()\n text = re.sub(r'^\\[_?.+_?\\]$', '', text)\n #text = \"The Apache HTTP Server, colloquially called Apache, is a Web server application notable for playing a key role in the initial growth of the World Wide Web. Originally based on the NCSA HTTPd server, development of Apache began in early 1995 after work on the NCSA code stalled. Apache quickly overtook NCSA HTTPd as the dominant HTTP server, and has remained the most popular HTTP server in use since April 1996.\"\n #text = re.sub(r'[^a-zA-Z0-9\\s]', ' ', text)\n return text\ndef pre_process(text):\n #Tokenization\n token = word_tokenize(text)\n # Normalizstion\n ## Convert to lowercases\n token = map(lambda x: x.lower(), token)\n\n ## remove number order\n token = filter(lambda x: not re.search( r'\\d+', x), token)\n ## remove urls\n token = filter(lambda x: not re.search( r'www|http', x), token)\n\n # Stemming\n #ps = PorterStemmer()\n #token = map(lambda x: ps.stem(x), token)\n return token\n\ndef unigramModel(input_word):\n text = read_text()\n # Replace all none alphanumeric characters with spaces\n text = re.sub(r'[^a-zA-Z0-9\\s]', ' ', text)\n token = pre_process(text)\n unigrams = ngrams(token,1)\n wordcount = Counter(unigrams).most_common()\n wordcount = {k[0]: v for k, v in wordcount}\n count_order = {}\n for item in wordcount:\n count = wordcount[item]\n if count_order.get(count):\n count_order[count].append(item)\n else:\n count_order[count] = [item]\n i = 0\n word_sequences = input_word + \" \"\n i += 1\n while (i <= 100):\n count_index = random.choice(list(count_order.keys()))\n random_word = random.choice(count_order.get(count_index))\n word_sequences = word_sequences + random_word + \" \"\n i += 1\n print(word_sequences)\n\ndef biggramModel(input_word):\n text = read_text()\n token = pre_process(text)\n unique_token = list(set(copy.deepcopy(token)))\n bigrams = ngrams(token,2)\n generate_sentence(input_word,bigrams,unique_token,5)\ndef trigramModel(input_word):\n text = read_text()\n token = pre_process(text)\n unique_token = list(set(copy.deepcopy(token)))\n trigrams = ngrams(token,3)\n generate_sentence(input_word,trigrams,unique_token,2)\ndef generate_sentence(input_word,ngrams,unique_token,scope=1):\n wordcount = Counter(ngrams).most_common()\n words = {}\n for item in wordcount:\n _input = item[0][0:-1]\n _output = item[0][-1]\n count = item[1]\n count_order = words.get(_input)\n if not count_order:\n count_order = {}\n if count_order.get(count):\n count_order[count].append(_output)\n else:\n count_order[count] = [_output]\n words[_input] = count_order\n i = 0\n last_word = input_word[-1];\n word_sequences = \" \".join(input_word).capitalize() + \" \"\n i += 1\n while (i <= 100):\n count_order = words.get(tuple(input_word))\n if count_order:\n #available_words = list(count_order.values())[0]\n available_words = functools.reduce(operator.iconcat, list(count_order.values())[0:scope], [])\n random_word = random.choice(available_words)\n else:\n random_word = random.choice(unique_token)\n if last_word in [\".\", \"?\",\"!\"]:\n random_word = random_word.capitalize()\n if random_word in [\",\",\":\",\";\",\".\", \"?\",\"!\"]:\n word_sequences = word_sequences[0:-1]\n word_sequences = word_sequences + random_word + \" \"\n last_word = random_word\n input_word.append(random_word.lower())\n input_word.pop(0)\n i += 1\n print(word_sequences)\n\nparser = argparse.ArgumentParser(description='manual to simple n-grams')\nparser.add_argument('--model', type=str, default=\"\")\nparser.add_argument('--input', type=str, default=\"\")\nargs = parser.parse_args()\nmodel = args.model\ninput_word = args.input\nif not model or not input_word:\n print(\"Please input available paramaters\")\nelse:\n if model == \"unigram\":\n input_word = input_word.split()[0]\n if not input_word:\n print(\"Please input one available word\")\n unigramModel(input_word)\n elif model == \"bigram\":\n input_word = input_word.split()[0:1]\n if len(input_word) != 1:\n print(\"Please input one available word\")\n biggramModel(input_word)\n elif model == \"trigram\":\n input_word = input_word.split()[0:2]\n if len(input_word) != 2:\n print(\"Please input two words\")\n else:\n trigramModel(input_word)\n else:\n print(\"There are not available N-grams Model\")\n\n\n\n\n","sub_path":"hw1/hw1.py","file_name":"hw1.py","file_ext":"py","file_size_in_byte":4980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"186980340","text":"\"\"\"Rename Garden Table\n\nRevision ID: 45d3bf115dcd\nRevises: 1d773bfaf33d\nCreate Date: 2020-07-25 11:42:41.264952\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '45d3bf115dcd'\ndown_revision = '1d773bfaf33d'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.rename_table('gardens', 'garden_plants')\n\n\ndef downgrade():\n op.rename_table('garden_plants', 'gardens')\n","sub_path":"alembic/versions/45d3bf115dcd_rename_garden_table.py","file_name":"45d3bf115dcd_rename_garden_table.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"386621028","text":"import random\nimport pickle\nimport numpy as np\n\nfrom rt_pie.fitted_models import models\nfrom rt_pie import args, process_file_input\n\n__ITERATIONS = 10\n__RES_FILE = \"res_10.pkl\"\n# __RES_FILE = None\n\n\ndef __compare_prediction_performance(iterations):\n shuffled = models.copy()\n random.shuffle(shuffled)\n result = {}\n for i in range(iterations):\n for m in shuffled:\n args.model = m.name\n res = process_file_input(args)\n times = res[\"p_times\"]\n if m.name in result:\n result[m.name] = np.append(result[m.name], times)\n else:\n result[m.name] = times\n return result\n\n\ndef main():\n if __RES_FILE is None:\n res = __compare_prediction_performance(__ITERATIONS)\n else:\n with open(__RES_FILE, 'rb') as f:\n res = pickle.load(f)\n\n with open(f\"res_{__ITERATIONS}.pkl\", \"wb\") as f:\n pickle.dump(res, f)\n\n __print_performance_stats(res, __ITERATIONS)\n\n\ndef __print_performance_stats(time_dict, iterations):\n lines = []\n for k, v in time_dict.items():\n sum = round(np.sum(v) / iterations / 1000, 2)\n mean = round(np.mean(v), 2)\n dev = round(np.std(v), 2)\n lines.append(f\"model: {k}, sum: {sum}s, mean: {mean}ms, dev: {dev}ms\")\n\n lines.sort()\n for li in lines:\n print(li)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"rt_pie/performance_analyzer.py","file_name":"performance_analyzer.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"533467444","text":"import sys\n\ndef getInt(prompt):\n \"\"\"\n Prompt the user to input one integer.\n Perform the input and its attendant error checking. Return the integer.\n \"\"\"\n\n s = getString(prompt)\n \n try:\n i = int(s)\n except ValueError:\n print(\"Sorry,\", s, \"is not a number.\")\n i = 3\n print(\"I assume you wanted to type \\\"\", i, \"\\\".\", sep = \"\")\n\n return i\n\ndef getString(prompt):\n\n assert isinstance(prompt, str)\n\n try:\n s = input(prompt + \" \")\n except EOFError:\n sys.exit(0)\n\n return s\n\n\nr = getInt(\"How many rows of boxes?\")\nc = getInt(\"How many columns of boxes?\")\nrs = getInt(\"How many rows of spaces in each box (e.g., 1)?\")\ncs = getInt(\"How many columns of spaces in each box (e.g., 3)?\") \n \ni = 0\n \nwhile i < r:\n print(((\"+\" + \"-\" * cs) * c) + \"+\")\n i += 1\n\n j = 0\n \n while j < rs:\n print(((\"|\" + \" \" * cs) * c) + \"|\")\n j += 1\n\nprint(((\"+\" + \"-\" * cs) * c) + \"+\")\n","sub_path":"graphpaper2.py","file_name":"graphpaper2.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"29909217","text":"\nimport requests\nfrom VideoStore import VideoStore\nfrom print_functions import *\n\n\ndef main(play=True):\n video_store = VideoStore()\n\n welcome_banner()\n print_linebreaks()\n while play == True:\n print_linebreaks()\n print(\"PLEASE CHOOSE FROM THE FOLLOWING MENU: \")\n main_menu_options()\n user_input = input(\":: \")\n if user_input == \"1\":\n ###### VIDEO OPTIONS ######## \n print(\"PLEASE CHOOSE FROM THE FOLLOWING MENU: \")\n video_menu_options()\n video_user_input = input(\":: \")\n if video_user_input == \"1\":\n all_videos = video_store.get_all_videos()\n for video in all_videos:\n print_video_info(video)\n\n elif video_user_input == \"2\":\n video_store.add_video_to_db()\n\n\n elif video_user_input == \"3\":\n user_input = title_or_id()\n if user_input:\n selected_video = video_store.get_single_video(title=user_input, id=None)\n else:\n user_input = input(\"Please enter the ID of the video you would like to select: \")\n selected_video = video_store.get_single_video(id=int(user_input), title=None)\n \n if selected_customer:\n print_video_info(selected_video)\n \n elif video_user_input == \"4\":\n user_input = input(\"Please enter the ID of the video you would like to select: \")\n selected_video = video_store.get_single_video(id=int(user_input))\n if selected_video:\n print_video_info(selected_video)\n video_store.edit_single_video(selected_video)\n\n \n elif video_user_input == \"5\":\n running_loop = True\n while running_loop:\n user_input = input(\"Please enter the ID of the video you would like to delete: \")\n selected_video = video_store.get_single_video(id=int(user_input))\n print_video_info(selected_video)\n user_check = input(\"Are you sure you want to delete this video? Y/N: \")\n if user_check.upper() == \"Y\":\n video_store.delete_single_video(selected_video)\n running_loop = False\n\n elif user_input == \"2\":\n ####### CUSTOMER OPTIONS ######### \n print(\"PLEASE CHOOSE FROM THE FOLLOWING MENU: \")\n customer_menu_options()\n customer_user_input = input(\":: \")\n if customer_user_input == \"1\":\n all_customers = video_store.get_all_customers()\n for customer in all_customers:\n print_customer_info(customer)\n \n elif customer_user_input == \"2\": \n video_store.add_customer_to_db()\n\n elif customer_user_input == \"3\":\n user_input = name_or_id()\n if user_input:\n selected_customer = video_store.get_single_customer(name=user_input, id=None)\n else:\n user_input = input(\"Please enter the ID of the customer you would like to select: \")\n selected_customer = video_store.get_single_customer(id=int(user_input), name=None)\n \n if selected_customer:\n print_customer_info(selected_customer)\n \n elif customer_user_input == \"4\":\n user_input = input(\"Please enter the ID of the customer you would like to select: \")\n selected_customer = video_store.get_single_customer(id=int(user_input))\n \n if selected_customer:\n print_customer_info(selected_customer)\n video_store.edit_single_customer(selected_customer)\n\n\n elif customer_user_input == \"5\":\n running_loop = True\n while running_loop:\n user_input = input(\"Please enter the ID of the customer you would like to delete: \")\n selected_customer = video_store.get_single_customer(id=int(user_input))\n print_customer_info(selected_customer)\n user_check = input(\"Are you sure you want to delete this cusotmer? Y/N: \")\n if user_check.upper() == \"Y\":\n video_store.delete_single_customer(selected_customer)\n running_loop = False\n \n elif user_input == \"3\": \n ########### RENTAL OPTIONS ########## \n print(\"PLEASE CHOOSE FROM THE FOLLOWING MENU: \")\n rental_menu_options()\n rental_user_input = input(\":: \")\n if rental_user_input == \"1\":\n video_store.check_out_movie()\n\n elif rental_user_input == \"2\":\n video_store.check_in_movie()\n\n elif rental_user_input == \"3\":\n video_id = input(\"Please enter the ID of the video: \")\n video_store.get_rental_list_by_video(int(video_id))\n\n elif rental_user_input == \"4\":\n customer_id = input(\"Please enter the ID of the customer: \")\n video_store.get_rental_list_by_customer(int(customer_id))\n\n elif rental_user_input == \"5\":\n video_store.is_overdue()\n\n\n elif user_input == \"4\":\n ########### EXIT PROGRAM ########## \n play = False\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"102235326","text":"from django.urls import path, re_path\nfrom . import views\nfrom django.contrib.auth import views as auth_views\n\napp_name = 'accounts'\n\nurlpatterns = [\n\n\n path('login/', views.UserLoginView.as_view(), name='login'),\n path('signup/', views.signup, name='signup'),\n path('activate//', views.activate, name='activate'),\n path('resend-verification-email/', views.resend_verification_email, name='resend_verification_email'),\n path('verified/', views.account_verified, name='verified'),\n path('logout/', auth_views.LogoutView.as_view(), name='logout', kwargs={\n 'next_page':'/',\n }),\n path('users//edit/', views.UserUpdateView.as_view(), name='account'),\n path('users/change-password/', views.change_password, name='change_password'),\n path('account-request/', views.account_request, name='account_request'),\n path('login_required/', auth_views.LoginView.as_view(), kwargs={\n 'extra_context': {\n 'message': \"You must be logged in to access this page\",\n }\n }),\n\n ### NOTE: Password reset views are mapped in the veggiebase urls.py file. Views are still in the Accounts app views.py\n\n\n\n]\n","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"286422582","text":"from help_api.models import *\nfrom autofixture import AutoFixture\nfrom django.core.management.base import BaseCommand, CommandError\n\nclass Command(BaseCommand):\n help = \"Erase data automatically.\"\n def add_arguments(self, parser):\n parser.add_argument('--c', '--count', type=int)\n\n def handle(self, *args, **kwargs):\n try:\n count = kwargs['c']\n a = AutoFixture(EntityModel)\n b = AutoFixture(AddressModel)\n c = AutoFixture(ToolsModel)\n d = AutoFixture(SOSModel)\n\n a.create(count)\n b.create(count)\n c.create(count)\n d.create(count)\n\n except Exception as e:\n print('Error: {0}', e)\n raise CommandError(\"Error\")","sub_path":"help_api/management/auto-delete.py","file_name":"auto-delete.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"346075741","text":"a,b,c = map(int, input().split())\n\nif a == b and a == c and b == c :\n print(a * 1000 + 10000)\nelif a == b or a == c :\n print(a * 100 + 1000)\nelif c == b :\n print(b * 100 + 1000)\nelse :\n max_num = max([a, b, c])\n print(max_num * 100)\n\n","sub_path":"baekjoon/2480.py","file_name":"2480.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"584441971","text":"def add(x):\n return x+2\n\nnumb = [1,2,3,4,5]\n\n#Map Function\n\nprint(list(map(add,numb)))\n\n#Can also be written as\n\nprint(list(map(lambda x: x+2, numb)))\n\n#Filter Function\n\nprint(list(filter(lambda x: x%2 == 0,numb)))\n\n#Generators\n\ndef even_numbers(x):\n for i in range(x):\n if i % 2 == 0:\n yield i\n\n\nprint(list(even_numbers(5)))\n","sub_path":"Map & Filter & Generators.py","file_name":"Map & Filter & Generators.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"182580814","text":"# run with python 3 please\n\nfrom calendar import monthrange\nimport sys\n\n\nclass OptOutUser(object):\n def __init__(self, name, num_of_days):\n self.name = name\n self.num_of_days = num_of_days\n\nclass MonthlyBill(object):\n # this only applies for the year 2018\n YEAR = 2018\n # this only applies for the current memeber of 1742 Spruce APT 24\n MEMBERS = ['JQ', 'RP', 'YM']\n MAX_USER = 'YM' # if split bill exceeds general monthly max, this user pays for the overflow\n GENERAL_ELECTRICITY_MAX = 65.00 # manually capped this based on spending history\n GENERAL_INTERNET_MAX = 69.49 / 3.0 # this was the spending based on the old plan\n\n def __init__(self, month, electricity_bill, internet_bill, optOutUser=None):\n \"\"\" \n Initialize MonthlyBill Object \n optOutUser by default is None unless specified\n for now only supports one person opt out scenario\n \"\"\"\n\n # month must be an int in [1, 13)\n assert month in [num for num in range(1, 13)]\n\n # this is to know how many days that month has\n self.month_range = monthrange(self.YEAR, month)[1]\n\n # electricity bill\n self.electricity_bill = electricity_bill\n\n # internet bill\n self.internet_bill = internet_bill\n\n self.result = {}\n for mem in self.MEMBERS:\n self.result[mem] = 0.0\n\n # are there opt_out members this month?\n self.optOutUser = optOutUser\n\n # no opt_out\n if self.optOutUser is None:\n self.default_split()\n # yes there are\n else:\n self.unusual_split()\n\n\n def default_split(self):\n \"\"\" \n Default split is the most generic split - \n all members stayed in the household that month \n \"\"\"\n print('start defualt splitting...')\n\n num_of_non_max_user = len(self.MEMBERS) - 1\n\n # check if electricity bill is more than usual\n if self.electricity_bill > self.GENERAL_ELECTRICITY_MAX * len(self.MEMBERS):\n print('detected electricity bill exceeds general electricity max')\n for mem in self.MEMBERS:\n if mem != self.MAX_USER:\n self.result[mem] += self.GENERAL_ELECTRICITY_MAX\n self.result[self.MAX_USER] += self.electricity_bill - \\\n num_of_non_max_user * self.GENERAL_ELECTRICITY_MAX \n else:\n for mem in self.MEMBERS:\n self.result[mem] += self.electricity_bill / float(len(self.MEMBERS))\n\n # check if internet bill is more than usual\n if self.internet_bill > self.GENERAL_INTERNET_MAX * len(self.MEMBERS):\n print('detected internet bill exceeds general electricity max')\n for mem in self.MEMBERS:\n if mem != self.MAX_USER:\n self.result[mem] += self.GENERAL_INTERNET_MAX\n self.result[self.MAX_USER] += self.internet_bill - \\\n num_of_non_max_user * self.GENERAL_INTERNET_MAX\n else:\n for mem in self.MEMBERS:\n self.result[mem] += self.internet_bill / float(len(self.MEMBERS))\n print('Done calculating default split')\n\n\n def unusual_split(self):\n # print(self.month_range)\n assert self.optOutUser.name in self.MEMBERS\n assert self.optOutUser.num_of_days <= self.month_range\n\n print('start unusual splitting...')\n\n regular_split_days = self.month_range - self.optOutUser.num_of_days\n\n # regular here means all members split\n regular_ratio = float(regular_split_days)/float(self.month_range)\n # irregular means one less member\n irregular_ratio = 1.0 - regular_ratio\n\n # Electricity\n # regular\n regular_split_electricity_bill = self.electricity_bill * regular_ratio\n if regular_split_electricity_bill > self.GENERAL_ELECTRICITY_MAX * regular_ratio * len(self.MEMBERS):\n print('detected electricity bill exceeds general electricity max in the regular portion')\n for mem in self.MEMBERS:\n if mem != self.MAX_USER:\n self.result[mem] += self.GENERAL_ELECTRICITY_MAX * regular_ratio\n self.result[self.MAX_USER] += regular_split_electricity_bill - self.GENERAL_ELECTRICITY_MAX * regular_ratio * (len(self.MEMBERS) - 1)\n else:\n for mem in self.MEMBERS:\n self.result[mem] += regular_split_electricity_bill / float(len(self.MEMBERS))\n # irregular\n irregular_split_electricity_bill = self.electricity_bill - regular_split_electricity_bill\n if self.optOutUser.name != self.MAX_USER and irregular_split_electricity_bill > self.GENERAL_ELECTRICITY_MAX * irregular_ratio * (len(self.MEMBERS)-1):\n print('detected electricity bill exceeds general electricity max in the irruglar portion')\n for mem in self.MEMBERS:\n if mem != self.MAX_USER and mem != self.optOutUser.name:\n self.result[mem] += self.GENERAL_ELECTRICITY_MAX * irregular_ratio\n self.result[self.MAX_USER] += irregular_split_electricity_bill - self.GENERAL_ELECTRICITY_MAX * irregular_ratio * (len(self.MEMBERS) - 2)\n else:\n for mem in self.MEMBERS:\n if mem != self.optOutUser.name:\n self.result[mem] == irregular_split_electricity_bill / float(len(self.MEMBERS) - 1)\n\n # Internet\n # there should be no irregular portion for internet bill since it's fixed\n if self.internet_bill > self.GENERAL_INTERNET_MAX * len(self.MEMBERS):\n print('detected internet bill exceeds general electricity max')\n for mem in self.MEMBERS:\n if mem != self.MAX_USER:\n self.result[mem] += self.GENERAL_INTERNET_MAX\n self.result[self.MAX_USER] += self.internet_bill - \\\n (len(self.MEMBERS) - 1) * self.GENERAL_INTERNET_MAX\n else:\n for mem in self.MEMBERS:\n self.result[mem] += self.internet_bill / float(len(self.MEMBERS))\n\n print('Done calculating unusual split')\n print('================================ End Block ==============================')\n\n\n def each_pay(self):\n return self.result\n\n def verify(self):\n actual = 0\n for mem in self.MEMBERS:\n actual += self.result[mem]\n expected = self.electricity_bill + self.internet_bill\n print('Actual sum is {}; expected sum is {}'.format(actual, expected))\n return abs(actual - expected) < 0.01 # due to float\n\ndef run(month, electricity_bill, internet_bill, optOutUser):\n monthlyBill = MonthlyBill(month, electricity_bill, internet_bill, optOutUser)\n each_pay = monthlyBill.each_pay()\n print(each_pay)\n print('Result is verified as {}'.format(monthlyBill.verify()))\n print('Now writing to txt...')\n with open('MonthlyBillResultForMonth{}.txt'.format(month), 'w') as text_file:\n print('Electricity Bill: {}'.format(electricity_bill), file=text_file)\n print('Internet Bill: {}'.format(internet_bill), file=text_file)\n if optOutUser is not None:\n print('OptOutUser is {}, {} days'.format(optOutUser.name, optOutUser.num_of_days), file=text_file)\n print('Result: {}'.format(each_pay), file=text_file)\n print('Program finished running. Please find MonthlyBillResultForMonth{}.txt as final result.'.format(month))\n\n\nif __name__ == '__main__':\n month = int(input('Please enter month (must be an integer in [1:13) : '))\n electricity_bill = float(input('Please enter electricity bill: '))\n internet_bill = float(input('Please enter internet bill: '))\n optOut = input('Are there any opt out users this month? Enter y or n: ')\n if optOut == 'n':\n optOutUser = None\n else:\n optOutUserName = input('Please enter opt out user name, i.e. JQ, YM or RP: ')\n optOutUserDays = int(input('Please enter the number of opt out days: '))\n optOutUser = OptOutUser(name=optOutUserName, num_of_days=optOutUserDays)\n print('Thanks for your input, now calculating: ')\n print('================================ Block Run ==============================')\n run(month=month, electricity_bill=electricity_bill, internet_bill=internet_bill, optOutUser=optOutUser)\n\n\n\n\n\n\n\n","sub_path":"bill.py","file_name":"bill.py","file_ext":"py","file_size_in_byte":8402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"272651015","text":"import re\nfrom django.db import models, IntegrityError\nfrom django.db.models import F\nfrom django.template.defaultfilters import slugify\n\nclass Ratings(models.Model):\n \n id = models.AutoField(primary_key=True)\n name = models.CharField(max_length=100, unique=True)\n number_of_occurences = models.BigIntegerField(default=0)\n created_time = models.DateTimeField(auto_now_add=True)\n last_time_occured = models.DateTimeField(auto_now=True)\n slug = models.SlugField(unique=True)\n \n #-----------------------------------------------------------------------\n def __unicode__(self):\n \n return self.name\n \n #-----------------------------------------------------------------------\n def update_result(self):\n \n self.number_of_occurences = F(\"number_of_occurences\") + 1\n self.save()\n #----------------------------------------------------------------------- \n def save(self):\n \"\"\"\n 1. Auto-populate an empty slug field and\n if it conflicts with an existing slug then append a number and try\n saving again.\n \"\"\"\n \n if not self.slug:\n \n self.slug = slugify(self.name) # Where self.name is the field used for 'pre-populate from'\n \n while True:\n \n try:\n \n super(Ratings, self).save()\n \n # Assuming the IntegrityError is due to a slug fight\n except IntegrityError:\n \n match_obj = re.match(r'^(.*)-(\\d+)$', self.slug)\n \n if match_obj:\n \n next_int = int(match_obj.group(2)) + 1\n self.slug = match_obj.group(1) + '-' + str(next_int)\n \n else:\n \n self.slug += '-2'\n \n else:\n \n break\n\n","sub_path":"good_to_be/ratings/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"20047406","text":"import urllib.request, urllib.parse, urllib.error\nimport json\nimport os\nimport win32api\nimport win32gui\nimport win32con\nimport time\nimport sys\nfrom PIL import Image\n\nBASE_URL = 'http://www.bing.com'\nJSON_URL = 'http://www.bing.com/HPImageArchive.aspx'\nRESOLUTION = [(1920, 1200), (1920, 1080), (1366, 768), (800, 600)]\nMKT = ['en-us']\n\n\ndef choose_resolution():\n width = win32api.GetSystemMetrics(win32con.SM_CXSCREEN)\n height = win32api.GetSystemMetrics(win32con.SM_CYSCREEN)\n for resolution in RESOLUTION:\n if resolution[0] == width and resolution[1] == height:\n return resolution\n return RESOLUTION[0]\n\n\ndef gen_get_query(date_offset=0, mkt=MKT[0]):\n get_query = {\n 'format': 'js',\n 'idx': date_offset,\n 'n': 1,\n 'mkt': mkt\n }\n get_query = urllib.parse.urlencode(get_query)\n return get_query\n\n\ndef get_image(image_url, image_name):\n #to avoid the IOError\n dir_path = os.path.join(os.environ['APPDATA'], 'BingWallpaperDownloader')\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n image_name = os.path.join(dir_path, image_name)\n try:\n urllib.request.urlretrieve(image_url, image_name)\n except IOError as e:\n win32api.MessageBox(0, e.message, '', 0)\n return os.path.abspath(image_name)\n\n\ndef parse_json(json_url, resolution):\n try:\n json_data = urllib.request.urlopen(json_url).read()\n except:\n os.sys.exit(-1)\n json_data = json_data.decode('UTF-8')\n json_data = json.loads(json_data)\n json_data = json_data['images'][0]\n image_url = '%s%s_%dx%d.jpg' % (BASE_URL, json_data['urlbase'], resolution[0], resolution[1])\n image_name = json_data['startdate'] + '.jpg'\n return image_url, image_name\n\n\ndef set_background(image_path):\n key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, 'Control Panel\\\\Desktop', 0, win32con.KEY_SET_VALUE)\n win32api.RegSetValueEx(key, 'WallpaperStyle', 0, win32con.REG_SZ, '2')\n win32api.RegSetValueEx(key, 'TileWallpaper', 0, win32con.REG_SZ, '0')\n win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER, image_path, win32con.SPIF_SENDCHANGE)\n\ndef convert_to_bmp(image_path):\n image = Image.open(image_path)\n bmp_image_path = image_path[:image_path.rfind('.')] + '.bmp'\n image.save(bmp_image_path, 'bmp')\n #os.remove(image_path)\n return bmp_image_path\n\n\ndef set_startup():\n file_path = os.path.abspath(sys.argv[0])\n key = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, 'Software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Run', 0,\n win32con.KEY_SET_VALUE)\n win32api.RegSetValueEx(key, 'BingWallpaperDownloader', 0, win32con.REG_SZ, '\"%s\" -autorun' % file_path)\n\n\ndef main():\n if len(sys.argv) < 2 or sys.argv[1] != '-autorun':\n set_startup()\n while True:\n resolution = choose_resolution()\n json_query_url = JSON_URL + '?' + gen_get_query()\n image_url, image_name = parse_json(json_query_url, resolution)\n image_path = get_image(image_url, image_name)\n image_path = convert_to_bmp(image_path)\n set_background(image_path)\n time.sleep(3600)\n\n\nif __name__ == '__main__':\n main()","sub_path":"src/BingWallpaperDownloader.py","file_name":"BingWallpaperDownloader.py","file_ext":"py","file_size_in_byte":3199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"3237847","text":"import xml.etree.ElementTree as ET\nimport Definition_of_interface\n\n\ndef pppfcs16(fcs, p, length):\n fcstab=(\n 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,\n 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,\n 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,\n 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,\n 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,\n 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,\n 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,\n 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,\n 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,\n 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,\n 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,\n 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,\n 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,\n 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,\n 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,\n 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,\n 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,\n 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,\n 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,\n 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,\n 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,\n 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,\n 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,\n 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,\n 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,\n 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,\n 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,\n 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,\n 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,\n 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,\n 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,\n 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78)\n i = 0\n while length:\n length -= 1\n fcs = (fcs >> 8) ^ fcstab[(fcs ^ ord(p[i])) & 0xff]\n i += 1\n return fcs ^ 0xffff\n\n\ndef deluseless():\n for DocumentProperties in root.findall('DocumentProperties'):\n root.remove(DocumentProperties)\n for OfficeDocumentSettings in root.findall('OfficeDocumentSettings'):\n root.remove(OfficeDocumentSettings)\n for ExcelWorkbook in root.findall('ExcelWorkbook'):\n root.remove(ExcelWorkbook)\n for Styles in root.findall('Styles'):\n root.remove(Styles)\n for child in root:\n for WorksheetOptions in child.findall('WorksheetOptions'):\n child.remove(WorksheetOptions)\n for childern in child:\n for Column in childern.findall('Column'):\n childern.remove(Column)\n for Names in root.findall(\"./Worksheet[@Name='Sheet2']/\"):\n root[1].remove(Names)\n break\n tree.write('output.xml', encoding='UTF-8')\n\n\ndef dec2bin(num):\n l = []\n if num < 0:\n return '-' + dec2bin(abs(num))\n while True:\n num, remainder = divmod(num, 2)\n l.append(str(remainder))\n if num == 0:\n return ''.join(l[::-1])\n\n\ndef ctrlc(num):\n if num[0] == '0' and num[1] == '0':\n print(num, 'DIR=0 PRM=0 客户机对服务器上报的响应')\n elif num[0] == '0' and num[1] == '1':\n print(num, 'DIR=0 PRM=1 客户机发起请求')\n elif num[0] == '1' and num[1] == '0':\n print(num, 'DIR=1 PRM=0 服务器发起上报')\n else:\n print(num, 'DIR=1 PRM=1 服务器对客户机请求的响应')\n if num[2] == '0':\n print('完整APDU')\n else:\n print('APDU片段')\n if num[-3:] == '001':\n print('链路管理')\n elif num[-3:] == '011':\n print('用户数据')\n\n\ndef SA(num):\n numadd = num[0] + num[1]\n numadd = int(numadd, 10)\n numadd = str(numadd)\n if numadd == '0':\n print('0 单地址')\n elif numadd == '1':\n print('1 通配地址')\n elif numadd == '2':\n print('2 组地址')\n else:\n print('3 广播地址')\n print(' 逻辑地址: ', num[2], num[3])\n numadd1 = num[4:]\n numadd1 = int(numadd1, base=2) # 2to10\n print('地址长度 N: ', numadd1+1)\n return numadd1+1\n\n\ndef Information(num, detail, APDU, code):\n if num == '01':\n print(num, '预链接请求')\n PIIDACD(detail, APDU[2:])\n LinkRequestType(APDU[2])\n HeartBeat_interval(APDU[3:5])\n RequestTimeDateTime(APDU[5:])\n elif num == '81':\n print(num, '预链接响应')\n PIID(detail)\n\n elif num == '02':\n print(num, '应用链接请求')\n elif num == '82':\n print(num, '应用链接响应')\n elif num == '03':\n print(num, '断开链接响应')\n elif num == '83':\n print(num, '断开链接请求')\n elif num == '05':\n print(num, '读取请求', end=' ')\n if detail == '01':\n print(detail, '读取一个对象属性请求(GetRequestNormal) ')\n elif detail == '02':\n print(detail, '读取若干个对象属性请求 (GetRequestNormalList) ')\n elif detail == '03':\n print(detail, '读取一个记录型对象属性请求 (GetRequestRecord) ')\n elif detail == '04':\n print(detail, '读取若干个记录型对象属性请求 (GetRequestRecordList) ')\n elif detail == '05':\n print(detail, '读取分帧响应的下一个数据块请求 (GetRequestNext) ')\n elif detail == '06':\n print(detail, '读取一个对象属性的 MD5 值 (GetRequestMD5) ')\n else:\n print('ERROR:05??')\n elif num == '85':\n print(num, '读取响应', end=' ')\n if detail == '01':\n print(detail, '读取一个对象属性的响应(GetResponseNormal) ')\n APDU_remain = PIIDACD(APDU[2], APDU[3:])\n AResultNormalOAD(APDU_remain)\n elif detail == '02':\n print(detail, '读取若干个对象属性的响应 (GetResponseNormalList) ')\n elif detail == '03':\n print(detail, '读取一个记录型对象属性的响应 (GetResponseRecord) ')\n APDU_remain = PIIDACD(APDU[2], APDU[3:])\n returnvalue = A_ResultRecord_SEQUENCE(APDU_remain)\n if returnvalue[0] == '00':\n print('无跟随上报信息域')\n if code[-4] == '00':\n print('无时间标签')\n if code[-1] == '16':\n print('结束符正确')\n elif detail == '04':\n print(detail, '读取若干个记录型对象属性的响应 (GetResponseRecordList) ')\n elif detail == '05':\n print(detail, '分帧响应一个数据块 (GetResponseNext) ')\n elif detail == '06':\n print(detail, '读取一个对象属性的 MD5 值的响应 (GetResponseMD5) ')\n else:\n print('ERROR:85??')\n elif num == '06':\n print(num, '设置请求')\n elif num == '86':\n print(num, '设置响应')\n elif num == '07':\n print(num, '操作请求')\n elif num == '87':\n print(num, '操作响应')\n elif num == '08':\n print(num, '上报回应')\n elif num == '88':\n print(num, '上报请求')\n remain = PIIDACD(APDU[2], APDU[3:])\n Report_SequenceOfARecordRow_len(remain)\n\n\ndef AResultNormalOAD(remain):\n OAD_SEQUENCE(remain[0] + remain[1], remain[2], remain[3])\n\n\ndef Report_SequenceOfARecordRow_len(remain):\n lenth = int(remain[0], 16)\n while lenth:\n lenth -= 1\n remain = remain[1:]\n OAD_SEQUENCE(remain[0]+remain[1], remain[2], remain[3])\n remain = RCSD(remain[4], remain[5:])\n GetRecordResult_ResultRecordType(remain)\n\n\ndef GetRecordResult_ResultRecordType(reamin):\n if reamin[0] == '01': # 类型结果: 数据\n reamin = SequenceOfARecordRow_SEQUENCE(reamin[1:])\n if reamin[0] == '00':\n print('No follow report...')\n else:\n print(\"Working...\")\n TimeTag(reamin[1])\n\n\ndef TimeTag(remain):\n if remain == '00':\n print('No time tag...')\n else:\n print('TimeTag working')\n\n\ndef LinkRequestType(Type):\n if Type == '00':\n print('登陆')\n if Type == '01':\n print('心跳')\n if Type == '02':\n print('退出登陆')\n\n\ndef HeartBeat_interval(sec): #2B\n times = int(sec[0] + sec[1], 16)\n print('times', times)\n\n\ndef RequestTimeDateTime(times): # 10B\n year = int(times[0] + times[1], 16)\n mouth = int(times[2],16)\n day = int(times[3],16)\n week = int(times[4],16)\n hour = int(times[5],16)\n minute = int(times[6],16)\n seccond = int(times[7],16)\n milsecond = int(times[8] + times[9], 16)\n print(year, '年', mouth, '月', day, '日', week, '周', hour, '时',minute,'分', seccond, '秒',milsecond, '毫秒')\n\n\ndef PIIDACD(detail1, args):\n detail1 = int(detail1, 16)\n detail1 = dec2bin(detail1).zfill(8)\n # if detail1[0] == '0':\n # print('0 服务优先级:一般的')\n # else:\n # print('1 服务优先级:高级的', detail1, 'PIIDACD')\n # if detail1[1] == '0':\n # print('0 请求访问 ACD:不请求')\n # else:\n # print('1 请求访问 ACD:请求')\n # print('服务序号', detail1[2:])\n return args\n\n\n\ndef PIID(detail2):\n detail2 = int(detail2, 16)\n detail2 = dec2bin(detail2).zfill(8) # 补0\n if detail2[0] == '0':\n print('0 服务优先级:一般的')\n else:\n print('1 服务优先级:高级的', detail2, 'PIIDACD')\n print('服务序号', detail2[2:])\n\n\ndef OAD_SEQUENCE(OI, unsigned1, unsigned2):\n OI = int(OI)\n unsigned11 = dec2bin(int(unsigned1)).zfill(8) # 特征值\n unsigned11 = int(unsigned11[0:4], 10)\n unsigned1 = '属性 ' + unsigned1[1]\n if 6000 <= OI <= 7000:\n for child in root[0]:\n for childern in child: # Table\n for grandchildern in childern: # Row\n Data = grandchildern.find(\"Data\")\n try:\n if Data.text == str(OI):\n print(Data.text, end=' ')\n global i\n i = 0\n i += 1\n if i == 3:\n print(Data.text, end=' ')\n global x\n x += 1\n if x == 1:\n try:\n if Data.text[3] == unsigned1[3]:\n print(Data.text, '特征:', unsigned11, '索引:', unsigned2)\n x += 1\n\n except:\n pass\n except:\n pass\n if OI < 6000:\n for child in root[1]:\n for childern in child: # Table\n for grandchildern in childern: # Row\n Data = grandchildern.find(\"Data\")\n try:\n if Data.text == str(OI).zfill(4):\n print(Data.text, unsigned1, end=' ')\n global ii\n ii = 0\n ii += 1\n if ii == 2:\n print('class id :', Data.text)\n Class_id(Data.text, unsigned1[3])\n if ii == 3:\n print(Data.text, '特征:', unsigned11, '索引:', unsigned2)\n except:\n pass\n\n\ndef Class_id(classid, parameter):\n if classid == '1':\n Definition_of_interface.Definition_of_electric_energy_interface(parameter)\n\n\n\n\ndef A_ResultRecord_SEQUENCE(remain):\n OAD = int(remain[0] + remain[1])\n OAD_SEQUENCE(OAD, remain[2], remain[3])\n # CHOICE_WITH_ARGS = RCSD(remain[4], remain[5:])\n returnvalue = DataResponse_CHOICE(RCSD(remain[4], remain[5:]))\n if returnvalue == []:\n print('A_ResultRecord_SEQUENCE ERROR')\n return returnvalue\n\ndef RCSD(remain_len, args):\n lens =int(remain_len)\n print('lens', lens)\n while lens > 0:\n args = CSD_CHOICE(args)\n lens -= 1\n return args\n\n\ndef CSD_CHOICE(args):\n type = args[0]\n if type == '00':\n print('CSD:', type)\n OAD = int(args[1] + args[2])\n OAD_SEQUENCE(OAD, args[3], args[4])\n if args == []:\n print('CSD_CHOICE is NULL')\n return args[5:]\n elif type == '01':\n value = ROAD(args[1:])\n if value == []:\n print('CSD_CHOICE is NULL')\n return value\n else:\n print('ERRORS:CSD_CHOICE')\n\n\ndef ROAD(args):\n OAD = int(args[0] + args[1])\n OAD_SEQUENCE(OAD, args[2], args[3])\n len = int(args[4])\n again = args[5:]\n while len > 0:\n len -= 1\n OAD = int(again[0] + again[1])\n OAD_SEQUENCE(OAD, again[2], again[3])\n if not again:\n print('ROAD is NULL')\n return again[4:]\n\n\n\ndef DataResponse_CHOICE(message):\n\n if message[0] == '00':\n DAR(message[1])\n elif message[0] == '01':\n returnvalue = SequenceOfARecordRow_SEQUENCE(message[1:])\n else:\n print('ERROR:DataResponse_CHOICE out of range')\n\n if returnvalue == []:\n print('DataResponse_CHOICE is NULL')\n return returnvalue\n\ndef DAR(number):\n if number == '00':\n print('成功')\n if number == '01':\n print('硬件失效')\n if number == '02':\n print('暂时失效')\n if number == '03':\n print('拒绝读写')\n if number == '04':\n print('对象未定义')\n if number == '05':\n print('对象接口类不符合')\n if number == '06':\n print('对象不存在')\n if number == '07':\n print('类型不匹配')\n if number == '08':\n print('越界')\n if number == '09':\n print('数据块不可用 ')\n if number == '10':\n print('分帧传输已取消')\n if number == '11':\n print('不处于分帧传输状态')\n if number == '12':\n print('块写取消')\n if number == '13':\n print('不存在块写状态')\n if number == '14':\n print('数据块序号无效')\n if number == '15':\n print('密码错/未授权')\n if number == '16':\n print('通信速率不能更改')\n if number == '17':\n print('年时区数超')\n if number == '18':\n print('日时段数超')\n if number == '19':\n print('费率数超')\n if number == '20':\n print('安全认证不匹配')\n if number == '21':\n print('重复充值')\n if number == '22':\n print('ESAM 验证失败')\n if number == '23':\n print('安全认证失败')\n if number == '24':\n print('客户编号不匹配 ')\n if number == '25':\n print('充值次数错误')\n if number == '26':\n print('购电超囤积')\n if number == '27':\n print('地址异常')\n if number == '28':\n print('对称解密错误')\n if number == '29':\n print('非对称解密错误 ')\n if number == '30':\n print('签名错误')\n if number == '31':\n print('电能表挂起')\n if number == '32':\n print('时间标签无效')\n if number == '33':\n print('请求超时')\n if number == '34':\n print('ESAM 的P1P2 不正确')\n if number == '35':\n print('ESAM 的 LC 错误')\n if number == '255':\n print('其它')\n\n\ndef SequenceOfARecordRow_SEQUENCE(len_within_args):\n len1 = int(len_within_args[0])\n if len1 == 0:\n print('长度为0')\n return len_within_args[1:]\n while len1 > 0:\n remain = Data(len_within_args[1], len_within_args[2:])\n len1 -= 1\n if not remain:\n print('SequenceOfARecordRow_SEQUENCE is NULL')\n return remain\n\n\ndef Data(DataDescribe, args):\n if DataDescribe == '00':\n print('NULL', DataDescribe)\n elif DataDescribe == '01':\n print('array:', DataDescribe, end=' ')\n len = int(args[0])\n args = args[1:]\n print('len:', len)\n while len > 0:\n args = Data(args[0], args[1:])\n len -= 1\n return args\n\n elif DataDescribe == '02':\n print('structure: ', DataDescribe)\n elif DataDescribe == '03':\n print('bool:', DataDescribe)\n elif DataDescribe == '04':\n print('bit-string:', DataDescribe)\n elif DataDescribe == '05':\n print('double-long: ', DataDescribe)\n elif DataDescribe == '06': # 4byte\n print('double-long-unsigned: ', DataDescribe)\n value = int(args[0]+args[1]+args[2]+args[3], 16)\n print('value', value)\n return args[4:]\n\n elif DataDescribe == '09':\n print('octet-string: ', DataDescribe)\n elif DataDescribe == '10':\n print('visible-string: ', DataDescribe)\n elif DataDescribe == '12':\n print('UTF8-string:', DataDescribe)\n elif DataDescribe == '15':\n print('integer:', DataDescribe)\n elif DataDescribe == '16':\n print('long: ', DataDescribe)\n elif DataDescribe == '17':\n print('unsigned:', DataDescribe)\n elif DataDescribe == '18':\n print('long-unsigned:', DataDescribe)\n elif DataDescribe == '20':\n print('long64: ', DataDescribe)\n elif DataDescribe == '21':\n print('long64-unsigned', DataDescribe)\n elif DataDescribe == '22':\n print('enum', DataDescribe)\n elif DataDescribe == '23':\n print('float32', DataDescribe)\n elif DataDescribe == '24':\n print('float64', DataDescribe)\n elif DataDescribe == '25':\n print('date_time', DataDescribe)\n elif DataDescribe == '26':\n print('date', DataDescribe)\n elif DataDescribe == '27':\n print('time', DataDescribe)\n elif DataDescribe == '28':\n print('date_time_s', DataDescribe)\n elif DataDescribe == '80':\n print('OAD ', DataDescribe)\n elif DataDescribe == '82':\n print('ROAD ', DataDescribe)\n elif DataDescribe == '83':\n print('OMD ', DataDescribe)\n elif DataDescribe == '84':\n print('TI', DataDescribe)\n elif DataDescribe == '85':\n print('TSA', DataDescribe)\n elif DataDescribe == '86':\n print('MAC', DataDescribe)\n elif DataDescribe == '87':\n print('RN', DataDescribe)\n elif DataDescribe == '88':\n print('Region', DataDescribe)\n elif DataDescribe == '89':\n print('Scaler_Unit ', DataDescribe)\n elif DataDescribe == '90':\n print('RSD', DataDescribe)\n elif DataDescribe == '91':\n print('CSD', DataDescribe)\n elif DataDescribe == '92':\n print('MS', DataDescribe)\n elif DataDescribe == '93':\n print('SID', DataDescribe)\n elif DataDescribe == '94':\n print('SID_MAC', DataDescribe)\n elif DataDescribe == '95':\n print('COMDCB', DataDescribe)\n elif DataDescribe == '96':\n print('RCSD', DataDescribe)\n else:\n print('ERROR on Data')\n\n\ndef strto0x(context):\n context = [int(x, 16) for x in context]\n new_context = []\n while context:\n current_context = chr(context.pop())\n new_context.append(current_context)\n new_context.reverse()\n return new_context\n\n\ndef Analysis(code):\n while 1:\n if code[0] == '68':\n break\n else:\n del code[0]\n # lenth = code[2] + code[1] # 长度域\n # lenth = int(lenth, 16)\n # print(code[1], code[2], '长度为:', lenth, '总长度为:', lenth + 2)\n # spacecount1 = lenth + 2\n # spacecount = len(code)\n # if spacecount == spacecount1:\n # ctrl = int(code[3], 16) # 控制域\n # binctrl = dec2bin(ctrl)\n # ctrlc(binctrl)\n # address = dec2bin(int(code[4],16)) # 地址域\n # address = address.zfill(8)\n # print('地址域:', address)\n # len_SA = SA(address)\n # Head = code[1:6 + len_SA]\n # print('Head:', Head)\n # print('服务器地址 SA :', Head[4:4+len_SA])\n # print(\"客户机地址 CA :\", Head[4+len_SA])\n # Head = strto0x(Head)\n # print('Head', Head)\n # HCS = pppfcs16(PPPINITFCS16, Head, len(Head))\n # print(hex(HCS))\n # print('HCS: ', code[12], code[13])\n # print('FCS:', code[-3], code[-2])\n # print('结束符:', code[-1])\n # else:\n # print('长度错误')\n APDU = code[14:-3]\n print(\"APDU:\", APDU)\n Information(APDU[0], APDU[1], APDU, code)\n\n\ndef makelist(message):\n list =[]\n x = 0\n lenth = len(message)\n while lenth > 0:\n list.append(message[x:x + 2])\n x += 2\n lenth -= 2\n return list\n\n\nPPPINITFCS16 = 0xffff\ni = 999\nii = 10\nx = 0\nAPDU_remain = []\nasd = open('source\\\\output.xml', 'r', encoding='UTF-8', errors='ignore')\ntree = ET.parse(asd)\nroot = tree.getroot()\nif __name__ == '__main__':\n analy = '68 21 00 c3 05 11 11 11 11 11 11 00 84 84 85 01 05 40 00 02 00 01 1c 07 e2 0b 06 14 00 0e 00 00 69 08 16'\n analy = makelist(analy.replace(' ', ''))\n Analysis(analy)\n '''\n asd = open('69845.xml', 'r', encoding='UTF-8', errors='ignore')\n tree = ET.parse(asd)\n root = tree.getroot()\n deluseless()\n asd.close()\n '''","sub_path":"Test2.py","file_name":"Test2.py","file_ext":"py","file_size_in_byte":21636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"141781078","text":"# Nelson Crockett\n# nwcrockett@alaska.edu\n# CS 684 HW5\n# 27OCT19\n# Pirate fights off zombies\n\nimport pygame\nimport chars\nimport random\n\nblack = (0,0,0)\nred = (255, 0, 0)\ngreen = (0, 200, 0)\nbright_green = (0, 255, 0)\n\npygame.init()\n\nscreen_width = 1800\nwin = pygame.display.set_mode((screen_width, screen_width))\npygame.display.set_caption(\"HW5\")\nbackground = pygame.image.load(\"/home/nelson/PycharmProjects/CS684/CS 684 HW5/sprites/pirate-background.png\")\nclock = pygame.time.Clock()\n\nenemy_number = 10\nfont = pygame.font.SysFont(\"comicsans\", 30, True)\npirate = chars.player(200, 410, 64, 64)\nbullets = []\nskelly = []\nfor skel in range(0, enemy_number):\n skelly_x = random.randint(0, screen_width)\n skelly_y = random.randint(0, screen_width)\n skelly.append(chars.enemy(skelly_x, skelly_y, 64, 64, screen_width))\n\n\ndef cycle_window():\n win.blit(background, (0, 0))\n pirate.draw(win)\n text = font.render(\"Zombies: \" + str(enemy_number), 1, (0, 0, 0))\n win.blit(text, (390, 10))\n skelly[0].draw(win)\n\n x = 1650\n y = 10\n pygame.draw.rect(win, red, (x, y, 100, 50))\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n if x + 100 > mouse[0] > x and y + 50 > mouse[1] > y:\n if click[0] == 1:\n pygame.quit()\n quit()\n\n for bullet in bullets:\n bullet.draw(win)\n pygame.display.update()\n\n\nrun = True\nintro = True\nwhile run:\n\n # intro loop, green button starts the game, red button quits\n while intro:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n break\n win.blit(background, (0, 0))\n largeText = pygame.font.Font('freesansbold.ttf', 115)\n textSurface = largeText.render(\"Clean the Zombies off the ship\", True, black)\n rect = textSurface.get_rect()\n rect.center = ((screen_width / 2), 100)\n win.blit(textSurface, rect)\n\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n if 1200 + 100 > mouse[0] > 1200 and 500 + 50 > mouse[1] > 500:\n pygame.draw.rect(win, bright_green, (1200, 500, 100, 50))\n if click[0] == 1:\n intro = False\n break\n else:\n pygame.draw.rect(win, green, (1200, 500, 100, 50))\n pygame.draw.rect(win, red, (400, 500, 100, 50))\n\n if 400 + 100 > mouse[0] > 400 and 500 + 50 > mouse[1] > 500:\n if click[0] == 1:\n intro = False\n pygame.quit()\n quit()\n break\n\n\n pygame.display.update()\n clock.tick(15)\n\n # frame rate set to 27 frames per second\n if not skelly:\n break\n\n clock.tick(27)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n # controller for the bullets in the game. Sets max to five\n for bullet in bullets:\n if bullet.y - bullet.radius < skelly[0].hitbox[1] + skelly[0].hitbox[3] and\\\n bullet.y + bullet.radius > skelly[0].hitbox[1]:\n if bullet.x + bullet.radius > skelly[0].hitbox[0] and bullet.x - bullet.radius < skelly[0].hitbox[0] + \\\n skelly[0].hitbox[2]:\n skelly[0].hit()\n bullets.pop(bullets.index(bullet))\n if skelly[0].health <= 0:\n skelly.pop(0)\n if bullet.x < screen_width and bullet.x > 0:\n bullet.x += bullet.vel\n else:\n bullets.pop(bullets.index(bullet))\n\n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_SPACE]:\n if pirate.left:\n facing = -1\n else:\n facing = 1\n if len(bullets) < 5:\n bullets.append(chars.projectile(round(pirate.x + pirate.width // 2),\n round(pirate.y + pirate.height // 2), 6, (0, 0, 0), facing))\n\n if keys[pygame.K_LEFT] and pirate.x > pirate.vel:\n pirate.x -= pirate.vel\n pirate.left = True\n pirate.right = False\n pirate.up = False\n pirate.down = False\n pirate.standing = False\n elif keys[pygame.K_RIGHT] and pirate.x < screen_width - pirate.width:\n pirate.x += pirate.vel\n pirate.left = False\n pirate.right = True\n pirate.up = False\n pirate.down = False\n pirate.standing = False\n elif keys[pygame.K_DOWN] and pirate.y < screen_width:\n pirate.y += pirate.vel\n pirate.left = False\n pirate.right = False\n pirate.down = True\n pirate.up = False\n pirate.standing = False\n elif keys[pygame.K_UP] and pirate.y > 0:\n pirate.y -= pirate.vel\n pirate.left = False\n pirate.right = False\n pirate.down = False\n pirate.up = True\n pirate.standing = False\n else:\n pirate.standing = True\n pirate.walk_count = 0\n\n cycle_window()\n\npygame.QUIT\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"CS 684 HW5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"60230457","text":"# -*- coding: utf-8 -*-\n\nfrom uploader.models import User\nfrom uploader.forms import uploadForm\nfrom django.shortcuts import render_to_response\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n@csrf_exempt\ndef upload_code(request):\n if request.POST:\n form = uploadForm(request.POST, request.FILES)\n if form.is_valid():\n user = User.objects.filter(username=form.cleaned_data[\"username\"],\n password=form.cleaned_data[\"password\"])\n if user.count() != 0:\n form.save()\n\n return render_to_response(\"uploader.html\", {\n \"form\": form,\n \"temam\": \"true\",\n })\n else:\n return render_to_response(\"uploader.html\", {\n \"form\": form,\n \"error\": \"true\"\n })\n\n else:\n return render_to_response(\"uploader.html\", {\n \"form\": form,\n })\n\n else:\n form = uploadForm()\n return render_to_response(\"uploader.html\", {\n \"form\": form\n })\n","sub_path":"uploader/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"381152302","text":"import pygame\nimport os\nimport sys\nfrom PIL import Image\nfrom numba.typed import List\nfrom math import cos, sin, atan2, pi, degrees, ceil\nfrom collections import deque\nfrom random import randint, choice, random\nfrom RayCasting import ray_cycle, in_view\n\npygame.init()\ndisplay_info = pygame.display.Info()\nsize = WIDTH, HEIGHT = display_info.current_w, display_info.current_h\nSCREEN = pygame.display.set_mode(size, flags=pygame.FULLSCREEN)\n\nFPS = 60\nCLOCK = pygame.time.Clock()\n\nENEMY_TYPES = [(70, 15, 4), (100, 10, 3), (250, 10, 2)]\n\nENEMY_IMAGE = pygame.image.load('data/enemy.png').convert_alpha()\nBLOOD_IMAGE = pygame.image.load('data/bullet.png').convert_alpha()\nHEAL_IMAGE = pygame.image.load('data/heal.png').convert_alpha()\nDROP_BULLET_IMAGE = pygame.image.load('data/drop_bullet.png').convert_alpha()\n\nall_sprites = pygame.sprite.Group()\nwalls_group = pygame.sprite.Group()\nenemies_group = pygame.sprite.Group()\nbouncing_obj_group = pygame.sprite.Group()\nspawn_points_group = pygame.sprite.Group()\ndrops_group = pygame.sprite.Group()\n\n\nclass Level:\n def __init__(self):\n self.map = self.create_level()\n self.distances = None\n\n self.map_w = len(self.map[0])\n self.map_h = len(self.map)\n self.cell_w = WIDTH // self.map_w\n self.cell_h = HEIGHT // self.map_h\n\n self.difficulty_coeff = 1\n self.difficulty_changed = False\n rects = self.merge_rects(self.get_horizontal_rects(), self.get_vertical_rects())\n self.create_walls(rects)\n self.create_spawn_points()\n\n self.score = 0\n\n def player_location(self):\n # Возвращает положение игрока на карте\n for row in range(self.map_h):\n for col in range(self.map_w):\n if self.map[row][col] == '@':\n self.map[row].replace('@', ' ')\n return (col * self.cell_w + self.cell_w // 2,\n row * self.cell_h + self.cell_h // 2)\n\n def create_spawn_points(self):\n # Создает точки спавна мобов на карте\n for row in range(self.map_h):\n for col in range(self.map_w):\n if self.map[row][col] == 'E':\n self.map[row].replace('E', ' ')\n SpawnPoint(col * self.cell_w + self.cell_w // 2,\n row * self.cell_h + self.cell_h // 2)\n\n def create_level(self):\n # Создает карту уровня\n with open(f'levels/level_{LEVEL}.txt') as file:\n map = file.readlines()\n return [row.rstrip() for row in map]\n\n def create_walls(self, rects):\n for rect in rects:\n Wall(rect.x, rect.y, rect.w, rect.h)\n\n def merge_rects(self, horizontal, vertical):\n rects = []\n for h_rect in horizontal:\n container = []\n for v_rect in vertical:\n if h_rect.contains(v_rect):\n container.append(v_rect)\n vertical.remove(v_rect)\n if container:\n rect = h_rect.unionall(container)\n rects.append(rect)\n for v_rect in vertical:\n container = []\n for h_rect in horizontal:\n if v_rect.contains(h_rect):\n container.append(h_rect)\n horizontal.remove(h_rect)\n if container:\n rect = v_rect.unionall(container)\n rects.append(rect)\n\n return rects\n\n def get_horizontal_rects(self):\n rects = []\n for row in range(self.map_h):\n row_rects = []\n is_rect = False\n for col in range(self.map_w):\n if self.map[row][col] == '#':\n if not is_rect:\n row_rects.append([])\n is_rect = True\n row_rects[-1].append(col)\n else:\n is_rect = False\n for i in range(len(row_rects)):\n col, w = row_rects[i][0], len(row_rects[i])\n row_rects[i] = pygame.Rect(col * self.cell_w, row * self.cell_h,\n w * self.cell_w, self.cell_h)\n rects.extend(row_rects)\n return rects\n\n def get_vertical_rects(self):\n rects = []\n for col in range(self.map_w):\n col_rects = []\n is_rect = False\n for row in range(self.map_h):\n if self.map[row][col] == '#':\n if not is_rect:\n col_rects.append([])\n is_rect = True\n col_rects[-1].append(row)\n else:\n is_rect = False\n for i in range(len(col_rects)):\n row, h = col_rects[i][0], len(col_rects[i])\n col_rects[i] = pygame.Rect(col * self.cell_w, row * self.cell_h,\n self.cell_w, h * self.cell_h)\n rects.extend(col_rects)\n return rects\n\n def distance_to_player(self):\n # Рассчитывает и возвращает матрицу с расстояниями до игрока на каждой клетке карты\n inf = 1000\n x, y = player.x // self.cell_w, player.y // self.cell_h\n self.distances = [[inf if col != '#' else '#' for col in row]\n for row in self.map]\n self.distances[y][x] = 0\n\n queue = deque()\n queue.append((y, x))\n\n while queue:\n row, col = queue.popleft()\n for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n if dr or dc:\n next_row, next_col = row + dr, col + dc\n if (self.cell_in_map(next_row, next_col) and\n self.distances[next_row][next_col] == inf):\n self.distances[next_row][next_col] = self.distances[row][col] + 1\n queue.append((next_row, next_col))\n\n def cell_in_map(self, row, col):\n return 0 <= row < self.map_h and 0 <= col < self.map_w\n\n def cheapest_path(self, row, col):\n # Возвращает следующую точку, в которую следует идти, чтобы приблизиться к игроку\n if self.distances[row][col] != '#':\n for dr, dc in ((-1, 0), (1, 0), (0, -1), (0, 1)):\n next_row, next_col = row + dr, col + dc\n if ((dr or dc) and self.cell_in_map(next_row, next_col) and\n self.distances[next_row][next_col] != '#' and\n self.distances[next_row][next_col] < self.distances[row][col]):\n return next_col, next_row\n return row, col\n\n def update_score(self):\n # Увеличивает счетчик\n self.score += 1\n self.difficulty_changed = False\n\n def update_difficulty(self):\n # Изменение сложности игры каждые 10 очков\n if self.score and self.score % 10 == 0 and not self.difficulty_changed:\n self.difficulty_changed = True\n self.difficulty_coeff *= 1.5\n\n def update(self):\n self.update_difficulty()\n self.distance_to_player()\n\n\nclass SpawnPoint(pygame.sprite.Sprite):\n def __init__(self, x, y, types=(0, 1, 2), spawn_time=FPS * 7):\n super().__init__(spawn_points_group)\n self.x, self.y = x, y\n self.types = types # Типы врагов\n self.spawn_time = spawn_time # Время до появления след врага\n self.timer = 0 # Отсчитывает время поялвения врага\n self.last_enemy = None\n\n def can_spawn(self):\n # Проверяет, можно ли заспавнить врага и мониторит, не находится ли последний заспавненный\n # враг в точке спавна\n if not self.last_enemy:\n return True\n return (self.timer <= 0 and\n not in_view(self.x, self.y, player.x, player.y,\n ray_obstacles) and\n not self.last_enemy.in_spawn_point)\n\n def update_difficulty(self):\n if self.spawn_time > FPS // 2:\n self.spawn_time = FPS * 7 / level.difficulty_coeff\n\n def update(self):\n if level.difficulty_changed and self.spawn_time > FPS:\n self.update_difficulty()\n if self.can_spawn():\n self.last_enemy = Enemy(self.x, self.y, choice(self.types))\n self.timer = self.spawn_time\n self.timer -= 1\n\n\nclass Drop(pygame.sprite.Sprite):\n def __init__(self, x, y):\n super().__init__(drops_group)\n self.x, self.y = x, y\n self.rect = pygame.Rect(x, y, 20, 20)\n self.common = False\n self.common_drops = ((self.change_damage, 'gun'), (self.change_accuracy, 'gun'),\n (self.change_reload, 'gun'), (self.change_multishot, 'gun'),\n (self.heal, 'heal'))\n self.rare_drops = (((self.change_damage, 100, 'gun'), (self.change_reload, 150, 'gun')),\n ((self.change_damage, -50, 'gun'), (self.change_reload, 40, 'gun')),\n ((self.change_multishot, 3, 'gun'), (self.change_damage, -50, 'gun')),\n ((self.change_damage, 150, 'gun'), (self.change_accuracy, 120, 'gun')),\n ((self.change_reload, 120, 'gun'), (self.change_accuracy, 70, 'gun')),\n ((self.change_hp, 25, 'heal'),))\n self.drop = self.definition_drop()\n\n def definition_drop(self):\n chance = random()\n if chance <= 0.2:\n drop = choice(self.rare_drops)\n else:\n drop = choice(self.common_drops)\n self.common = True\n if drop[-1] == 'heal':\n self.image = HEAL_IMAGE\n else:\n self.image = DROP_BULLET_IMAGE\n self.rect = self.image.get_rect()\n self.rect.x = self.x\n self.rect.y = self.y\n return drop\n\n def pick_up(self):\n if player.rect.colliderect(self.rect):\n self.get_drop()\n self.kill()\n\n def get_drop(self):\n if self.common:\n self.drop[0]()\n self.common = False\n else:\n for drop, percent, flag in self.drop:\n drop(percent)\n\n def change_damage(self, percent=25):\n gun.dmg *= 1 + percent / 100\n\n def change_reload(self, percent=80):\n if gun.reload_speed > 1:\n gun.reload_speed *= percent / 100\n\n def change_accuracy(self, percent=25):\n if gun.accuracy * percent / 100 >= 0.001:\n gun.accuracy *= percent / 100\n\n def change_multishot(self, quantity=1):\n gun.multishot += quantity\n\n def change_hp(self, quantity=25):\n player.max_hp += quantity\n\n def heal(self, quantity=25):\n if player.hp + quantity <= player.max_hp:\n player.hp = player.hp + quantity\n else:\n player.hp = player.max_hp\n\n def update(self):\n SCREEN.blit(self.image, self.rect)\n self.pick_up()\n\n\nclass Wall(pygame.sprite.Sprite):\n def __init__(self, x, y, w, h):\n super().__init__(walls_group)\n self.x = x\n self.y = y\n self.w = w\n self.h = h\n self.rect = pygame.Rect(x, y, w, h)\n\n def update(self):\n pygame.draw.rect(SCREEN, 'black', (self.x, self.y,\n self.w, self.h))\n\n\nclass Floor(pygame.sprite.Sprite):\n def __init__(self):\n super(Floor, self).__init__(all_sprites)\n self.image = Image.open(f'data/floor{randint(1, 6)}.png')\n self.result_floor_image = Image.new('RGB', (WIDTH, HEIGHT))\n self.image = self.create_floor()\n self.rect = self.image.get_rect()\n\n def create_floor(self):\n # Склеивает спрайты пола в зависимости от разрешения экрана\n w = WIDTH // self.image.width\n h = HEIGHT // self.image.height\n for row in range(h * 5):\n for col in range(w * 5):\n self.result_floor_image.paste(self.image,\n (col * self.image.width, row * self.image.height))\n self.result_floor_image.save('data/floor_result.png')\n self.image = load_image('floor_result.png')\n return self.image\n\n\nclass Character(pygame.sprite.Sprite):\n def __init__(self):\n super().__init__()\n self.collision_rect = pygame.Rect(0, 0, 25, 25)\n\n def movement(self, dx, dy, enemies=True):\n # Метод обрабатывает столкновение игрока с препятствиями и меняет его координаты\n # Изменение по x\n x, y = self.collision_rect.x, self.collision_rect.y\n self.collision_rect.x += dx\n for block in obstacles:\n if (block != self.collision_rect and self.collision_rect.colliderect(block) and\n ((block not in enemy_rects) or\n (block in enemy_rects and enemies))):\n if dx < 0:\n self.collision_rect.left = block.right\n elif dx > 0:\n self.collision_rect.right = block.left\n break\n\n # Изменение по y\n self.collision_rect.y += dy\n for block in obstacles:\n if (block != self.collision_rect and self.collision_rect.colliderect(block) and\n ((block not in enemy_rects) or\n (block in enemy_rects and enemies))):\n if dy < 0:\n self.collision_rect.top = block.bottom\n elif dy > 0:\n self.collision_rect.bottom = block.top\n break\n\n # Проверка на крайний случай, если вдруг персонаж вышел за стену\n # Нужна, если персонаж обладет большой скоростью\n if not in_view(x, y, self.collision_rect.x, self.collision_rect.y, ray_obstacles):\n self.collision_rect.x, self.collision_rect.y = x, y\n\n def update_angle(self, x1, y1):\n x0, y0 = self.rect.centerx, self.rect.centery\n view_angle = atan2(y1 - y0, x1 - x0) # Считает угол относительно курсора\n return view_angle\n\n\nclass Player(Character):\n def __init__(self, fov, speed):\n super().__init__()\n self.x, self.y = level.player_location()\n self.v = speed\n self.fov = fov # Угол обзора игрока\n self.max_hp = 100\n self.hp = self.max_hp\n\n self.immortality_timer = 45\n self.is_dead = False\n\n self.image = pygame.image.load('data/player.png').convert_alpha()\n self.current_image = self.image\n self.rect = self.current_image.get_rect()\n self.rect.center = self.x, self.y\n self.collision_rect.center = self.rect.center\n\n self.view_angle = self.update_angle(*pygame.mouse.get_pos())\n\n def death(self):\n if self.hp <= 0:\n self.is_dead = True\n\n def move_character(self):\n # Здесь происходит управление игроком\n keys = pygame.key.get_pressed()\n if keys[pygame.K_w]:\n self.movement(0, -self.v, enemies=False)\n if keys[pygame.K_s]:\n self.movement(0, self.v, enemies=False)\n if keys[pygame.K_a]:\n self.movement(-self.v, 0, enemies=False)\n if keys[pygame.K_d]:\n self.movement(self.v, 0, enemies=False)\n self.x, self.y = self.collision_rect.center\n self.rect.center = self.x, self.y\n\n def ray_cast(self):\n coords = self.start_ray_coords(self.x, self.y, self.view_angle)\n coords.extend(ray_cycle(self.x, self.y, self.view_angle, ray_obstacles, level.cell_w,\n level.cell_h, level.map_w, level.map_h, self.fov))\n pygame.draw.polygon(SCREEN, 'black', coords)\n\n def set_immortal(self):\n # Устанавливает бессмертие у игрока после получения урона\n self.immortality_timer = 45\n\n def shoot(self):\n # Отвечает за выстрелы игрока\n if gun.reload < 0:\n gun.shot(self.x + self.rect.w / 2 * cos(self.view_angle),\n self.y + self.rect.h / 2 * sin(self.view_angle))\n gun.reload = gun.reload_speed\n\n def start_ray_coords(self, x, y, alpha):\n if -pi <= alpha <= -pi / 2:\n return [(x, y), (WIDTH, HEIGHT), (0, HEIGHT), (0, 0),\n (WIDTH, 0), (WIDTH, HEIGHT), (x, y)]\n elif -pi / 2 <= alpha <= 0:\n return [(x, y), (0, HEIGHT), (0, 0), (WIDTH, 0),\n (WIDTH, HEIGHT), (0, HEIGHT), (x, y)]\n elif 0 <= alpha <= pi / 2:\n return [(x, y), (0, 0), (WIDTH, 0), (WIDTH, HEIGHT),\n (0, HEIGHT), (0, 0), (x, y)]\n else:\n return [(x, y), (WIDTH, 0), (WIDTH, HEIGHT),\n (0, HEIGHT), (0, 0), (WIDTH, 0), (x, y)]\n\n def update(self):\n self.immortality_timer -= 1\n self.death()\n self.move_character()\n self.ray_cast()\n self.view_angle = self.update_angle(*pygame.mouse.get_pos())\n self.current_image = pygame.transform.rotate(self.image, -degrees(self.view_angle))\n # pygame.draw.rect(SCREEN, 'white', self.collision_rect)\n SCREEN.blit(self.current_image, self.rect)\n\n\nclass Enemy(Character):\n def __init__(self, x, y, complexity):\n super(Enemy, self).__init__()\n self.spawn_x, self.spawn_y = x, y\n self.x = x\n self.y = y\n self.location = (self.y // level.cell_h, self.x // level.cell_w)\n self.destination = self.location # Точка, в которую нужно идти\n\n self.hp, self.dmg, self.speed = ENEMY_TYPES[complexity]\n self.hp = ceil(self.hp * level.difficulty_coeff)\n self.speed_debuff = 0 # Дебафф к скорости при попадании\n\n self.view_angle = 0\n\n self.image = ENEMY_IMAGE\n self.current_image = self.image\n\n self.rect = self.current_image.get_rect()\n self.rect.center = self.x, self.y\n self.collision_rect.center = self.rect.center\n\n # Счетчик для эффекта кровотечения нужен для того, чтобы при большой\n # скорострельности не жралось фпс из-за большого кол-ва спрайтов\n self.bleed_time = 20\n self.bleed_timer = 0\n\n self.in_spawn_point = True\n\n obstacles.append(self.collision_rect)\n enemy_rects.append(self.collision_rect)\n enemies_group.add(self)\n\n def attack(self):\n if self.collision_rect.colliderect(player.collision_rect) and player.immortality_timer <= 0:\n player.hp -= self.dmg\n player.set_immortal()\n\n def dead(self):\n level.update_score()\n obstacles.remove(self.collision_rect)\n enemy_rects.remove(self.collision_rect)\n chance = random()\n if chance <= 0.3:\n Drop(self.x, self.y)\n self.bleed_timer = 0\n self.bleed()\n self.kill()\n\n def bleed(self, k=0):\n if self.bleed_timer <= 0:\n for _ in range(randint(15 + k, 30 + k * 2)):\n Blood(*self.rect.center, randint(-314, 314) / 100,\n randint(5 + k, 15 + k), -0.5)\n self.bleed_timer = self.bleed_time\n\n def update_spawn_status(self):\n # Метод проверяет, не находится ли последний заспавненный враг в точке спавна, дабы\n # не заспавнить еще одного врага внутри другого\n if (self.in_spawn_point and\n not self.collision_rect.collidepoint(self.spawn_x, self.spawn_y)):\n self.in_spawn_point = False\n\n def set_impact(self):\n # Замедляет игрока при попадании\n self.speed_debuff = self.speed * 0.5\n self.bleed(-10)\n\n def update_impact(self):\n # Отсчитывет время замедления врага\n if self.speed_debuff > 0:\n self.speed_debuff -= self.speed * 0.01\n\n def move(self):\n # Метод ищет следующую точку пути\n ray_coords = (self.rect.topleft, self.rect.topright,\n self.rect.bottomright, self.rect.bottomleft)\n # Проверяет, находится ли игрок в зоне видимости\n if all((in_view(*pos, player.collision_rect.centerx,\n player.collision_rect.centery, ray_obstacles) for pos in ray_coords)):\n self.view_angle = atan2(player.y - self.y, player.x - self.x)\n else:\n x1, y1 = self.destination\n self.view_angle = atan2(y1 * level.cell_h + level.cell_h // 2 - self.y,\n x1 * level.cell_w + level.cell_w // 2 - self.x)\n\n vx = cos(self.view_angle) * (self.speed - self.speed_debuff)\n vy = sin(self.view_angle) * (self.speed - self.speed_debuff)\n self.movement(vx, vy)\n\n def update(self):\n if self.hp <= 0:\n self.dead()\n self.bleed_timer -= 1\n\n self.view_angle = self.update_angle(player.x, player.y)\n self.location = (self.collision_rect.y // level.cell_h,\n self.collision_rect.x // level.cell_w)\n self.destination = level.cheapest_path(*self.location)\n\n self.move()\n self.update_impact()\n self.attack()\n self.update_spawn_status()\n\n # pygame.draw.rect(SCREEN, 'white', self.collision_rect)\n self.x, self.y = self.collision_rect.center\n self.rect.center = self.x, self.y\n self.current_image = pygame.transform.rotate(self.image, -degrees(self.view_angle))\n\n SCREEN.blit(self.current_image, self.rect)\n\n\nclass Weapon:\n def __init__(self):\n self.dmg = 30 # Урон пули\n self.reload_speed = 20 # Скорость перезарядки\n self.reload = self.reload_speed # Таймер для скорости перезарядки\n self.accuracy = 0.1 # Точность\n self.a = -0.5 # Ускроение\n self.v0 = 40 # Начальная скорость\n self.multishot = 1 # Кол-во пулек за выстрел\n\n def shot(self, x, y):\n hover_shoot = pygame.mixer.Sound('sounds/hover_over_the_button.mp3')\n hover_shoot.set_volume(0.05)\n hover_shoot.play()\n mx, my = pygame.mouse.get_pos()\n phi = atan2(my - y, mx - x)\n for i in range(-self.multishot // 2, self.multishot // 2):\n alpha = randint(-int(self.accuracy * 1000), int(self.accuracy * 1000))\n Bullet(x, y, phi + alpha / 1000 + i * self.accuracy, self.v0, self.a,\n self.dmg)\n\n\nclass BouncingObject(pygame.sprite.Sprite):\n def __init__(self, x, y, phi, v0, a):\n super().__init__(bouncing_obj_group)\n self.point = pygame.Rect(x, y, 1, 1)\n self.phi = phi # Угол полета объекта\n self.v = v0\n self.a = a\n self.cos_phi = cos(phi)\n self.sin_phi = sin(phi)\n\n self.dx, self.dy = 0, 0\n self.pos_x = x\n self.pos_y = y\n\n def bounce(self):\n # Рассчитвает рикошет пули\n for block in obstacles:\n if block not in enemy_rects and self.point.colliderect(block):\n x0 = self.pos_x - ((self.v - self.a) * self.cos_phi)\n y0 = self.pos_y - ((self.v - self.a) * self.sin_phi)\n # Точка пересечения с ректом\n x, y = block.clipline(x0, y0, self.pos_x, self.pos_y)[0]\n if (block.bottom - 2 <= y <= block.bottom + 2 or\n block.top - 2 <= y <= block.top + 2):\n self.sin_phi = -self.sin_phi\n self.phi = -self.phi\n else:\n self.phi = pi - self.phi\n self.cos_phi = -self.cos_phi\n self.v -= 5\n break\n\n def update_variables(self):\n # Апдейтит значения\n self.dx = self.v * self.cos_phi\n self.dy = self.v * self.sin_phi\n self.pos_x = self.pos_x + self.dx\n self.pos_y = self.pos_y + self.dy\n self.v += self.a\n\n self.point.x = self.pos_x\n self.point.y = self.pos_y\n\n def change_status(self):\n if self.v <= 0:\n self.kill()\n if self.point.collidelistall(obstacles):\n self.bounce()\n\n\nclass Blood(BouncingObject):\n def __init__(self, x, y, phi, v0, a):\n super(Blood, self).__init__(x, y, phi, v0, a)\n self.current_image = BLOOD_IMAGE\n\n def update(self):\n self.change_status()\n self.update_variables()\n\n self.current_image = pygame.transform.rotate(BLOOD_IMAGE, -degrees(self.phi))\n SCREEN.blit(self.current_image, self.point)\n\n\nclass Bullet(BouncingObject):\n def __init__(self, player_x, player_y, phi, v0, a, dmg):\n super(Bullet, self).__init__(player_x, player_y, phi, v0, a)\n self.dmg = dmg\n\n def update(self):\n self.change_status()\n self.hit()\n self.update_variables()\n # self.current_image = pygame.transform.rotate(BULLET_IMAGE, -degrees(self.phi))\n # SCREEN.blit(self.current_image, self.point)\n pygame.draw.line(SCREEN, 'orange', (self.pos_x - self.dx, self.pos_y - self.dy),\n (self.pos_x, self.pos_y), 5)\n\n def hit(self):\n # Отвечает за удар пули по врагу\n for enemy in enemies_group:\n if self.point.colliderect(enemy.rect):\n enemy.hp -= self.dmg\n enemy.set_impact()\n self.kill()\n\n\nclass Widget:\n def print_text(self, message, x, y, font_color=(0, 0, 0),\n font_type=None, font_size=32):\n font_type = pygame.font.Font(font_type, font_size)\n text = font_type.render(message, True, font_color)\n SCREEN.blit(text, (x, y))\n\n\nclass InterFace(Widget):\n def death_panel(self):\n x = WIDTH // 2 - 5 * 32\n y = HEIGHT // 2\n self.print_text('ПОТРАЧЕНО', x, y, font_color='#B01414', font_size=64)\n\n def hp_bar(self):\n width, height = WIDTH // 14, HEIGHT // 40\n hp = player.hp if player.hp > 0 else 0\n pygame.draw.rect(SCREEN, '#B80A0A', (10, HEIGHT - height - 5,\n hp / player.max_hp * width, height))\n pygame.draw.rect(SCREEN, 'white', (10, HEIGHT - height - 5, width, height), 1)\n self.print_text(f'{hp} / {player.max_hp}', 20, HEIGHT - height - 5,\n font_color='white')\n\n def pause_bar(self):\n x = WIDTH // 2 - 3 * 32\n y = HEIGHT // 2\n self.print_text('ПАУЗА', x, y, font_color='white', font_size=64)\n\n def score_bar(self):\n x = WIDTH // 2 - (len(str(level.score)) + 7) // 2 * 16\n y = HEIGHT - HEIGHT // 40 - 5\n self.print_text(f'SCORE: {level.score}', x, y, font_color='white')\n\n def fps_counter(self):\n font = pygame.font.Font(None, 20)\n text = font.render(str(round(CLOCK.get_fps(), 4)), True, 'white')\n text_x = 0\n text_y = 0\n SCREEN.blit(text, (text_x, text_y))\n\n def update(self, pause):\n self.fps_counter()\n if not (player.is_dead or pause):\n self.hp_bar()\n self.score_bar()\n elif player.is_dead:\n self.death_panel()\n elif pause:\n self.pause_bar()\n\n\nclass Button(Widget):\n def __init__(self, width, height, action=None):\n self.width = width\n self.height = height\n self.action = action\n\n def draw(self, x, y, message):\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n hover_sound = pygame.mixer.Sound('sounds/hover_over_the_button.mp3')\n hover_sound.set_volume(0.1)\n\n if x < mouse[0] < x + self.width and y < mouse[1] < y + self.height:\n pygame.draw.rect(SCREEN, (18, 19, 171), (x, y, self.width, self.height))\n if click[0] == 1:\n if self.action:\n hover_sound.play()\n pygame.mixer.music.stop()\n self.action()\n else:\n pygame.draw.rect(SCREEN, (68, 53, 212), (x, y, self.width, self.height))\n self.print_text(message, x + 5, y + 5)\n\n\ndef go_game():\n init_globals()\n exit_button = Button(100, 25, start_menu)\n pygame.mixer.music.load('sounds/background_game.mp3')\n pygame.mixer.music.set_volume(0.1)\n pygame.mixer.music.play(-1)\n\n pause = False\n running = True\n while running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n pause = not pause\n pygame.mixer.music.unpause()\n if not (pause or player.is_dead):\n if pygame.mouse.get_pressed()[0]:\n player.shoot()\n all_sprites.draw(SCREEN)\n\n bouncing_obj_group.update()\n gun.reload -= 1\n level.update()\n enemies_group.update()\n spawn_points_group.update()\n drops_group.update()\n player.update()\n # walls_group.update()\n\n else:\n exit_button.draw(WIDTH - 120, 10, 'В меню')\n pygame.mixer.music.pause()\n\n interface.update(pause)\n\n pygame.display.flip()\n CLOCK.tick(FPS)\n\n\ndef clear_groups():\n all_sprites.empty()\n drops_group.empty()\n walls_group.empty()\n enemies_group.empty()\n bouncing_obj_group.empty()\n spawn_points_group.empty()\n\n\ndef load_image(name, colorkey=None):\n fullname = os.path.join('data', name)\n\n if not os.path.isfile(fullname):\n print(f\"Файл с изображением '{fullname}' не найден\")\n sys.exit()\n image = pygame.image.load(fullname)\n\n if colorkey is not None:\n image = image.convert()\n if colorkey == -1:\n colorkey = image.get_at((0, 0))\n image.set_colorkey(colorkey)\n else:\n image = image.convert_alpha()\n return image\n\n\ndef start_menu():\n clear_groups()\n menu_background = pygame.image.load('pictures/menu.jpg')\n\n font_game = pygame.font.Font(None, 112)\n start_button = Button(280, 70, go_game)\n quit_button = Button(280, 70, quit)\n pygame.mixer.music.load('sounds/background_menu.mp3')\n pygame.mixer.music.set_volume(0.2)\n pygame.mixer.music.play(-1)\n show = True\n while show:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n show = False\n elif event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n exit()\n SCREEN.blit(menu_background, (0, 0))\n SCREEN.blit(font_game.render('Dark Hell', True, (18, 19, 171)),\n font_game.render('Dark Hell', True, (18, 19, 171)).get_rect(\n center=(500, 300)))\n start_button.draw(270, 600, 'Начать игру')\n quit_button.draw(270, 700, 'Выход')\n pygame.display.update()\n CLOCK.tick(60)\n\n\ndef init_globals():\n global LEVEL, player, level, floor, gun, enemy_rects, obstacles, ray_obstacles, interface\n LEVEL = randint(1, 5)\n level = Level()\n interface = InterFace()\n floor = Floor()\n gun = Weapon()\n player = Player(100, 10)\n enemy_rects = []\n obstacles = [wall.rect for wall in walls_group] # Спиоск всех преград\n ray_obstacles = List([(wall.rect.x, wall.rect.y,\n wall.rect.w, wall.rect.h) for wall in walls_group])\n\n\nif __name__ == '__main__':\n start_menu()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":32479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"639241225","text":"my_int = 5\nmy_float = 1.3\nmy_str = 'Elena Bystrova'\nmy_list = ['Anna','Irina', True, 20, 30.2]\nmy_tuple = ('Anna','Irina', True, 20, 30.2)\nmy_set = {1, 2, 2, 3, 3, 6, 5, 6, 6, 7, 3, 4, 10}\nmy_dict = {'name': 'Elena', 'age': 36, 'female':'woman'}\nfull_list = [my_int, my_float, my_str, my_list, my_tuple, my_set, my_dict]\nfor i in full_list:\n print(f'{i} is {type(i)}')\n \n \n","sub_path":"execise2_1.py","file_name":"execise2_1.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"66231673","text":"class Solution:\n \"\"\"\n @param: grid: a chessboard included 0 and 1\n @return: the shortest path\n \"\"\"\n\n def shortestPath2(self, grid):\n # write your code here\n queue = []\n hash = set()\n queue.append((0, 0, 0))\n hash.add((0, 0))\n while queue:\n x, y, step = queue.pop(0)\n if x == len(grid) - 1 and y == len(grid[0]) - 1:\n return step\n\n neighbors = self.getNeighbors(grid, x, y)\n for nx, ny in neighbors:\n if (nx, ny) in hash:\n continue\n if grid[nx][ny] == 1:\n continue\n\n queue.append((nx, ny, step + 1))\n hash.add((nx, ny))\n\n return -1\n\n def getNeighbors(self, grid, x, y):\n neighbors = []\n for nx, ny in [(x + 1, y + 2), (x - 1, y + 2),\n (x + 2, y + 1), (x - 2, y + 1)]:\n if nx < 0 or ny < 0 or nx >= len(grid) or ny >= len(grid[0]):\n continue\n\n neighbors.append((nx, ny))\n\n return neighbors\n\nres = Solution().shortestPath2([[0,0,0,0],\n [0,0,0,0],\n [0,1,0,0]])\nprint(res)\n\n","sub_path":"lintcode/宽搜/630-knight-shortest-path-ii.py","file_name":"630-knight-shortest-path-ii.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"591759354","text":"# encoding: utf-8\n\nimport socket\nimport commands\n\n\nHOST = 'localhost'\nPORT = 50505\nSOCKET = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nSTATS = {\n 'PUT': {'success': 0, 'error': 0},\n 'GET': {'success': 0, 'error': 0},\n 'GETLIST': {'success': 0, 'error': 0},\n 'PUTLIST': {'success': 0, 'error': 0},\n 'INCREMENT': {'success': 0, 'error': 0},\n 'APPEND': {'success': 0, 'error': 0},\n 'DELETE': {'success': 0, 'error': 0},\n 'STATS': {'success': 0, 'error': 0}\n}\n\nCOMMAND_HANDLERS = {\n 'PUT': commands.handle_put,\n 'GET': commands.handle_get,\n 'GETLIST': commands.handle_getlist,\n 'PUTLIST': commands.handle_putlist,\n 'INCREMENT': commands.handle_increment,\n 'APPEND': commands.handle_append,\n 'DELETE': commands.handle_delete,\n 'STATS': commands.handle_stats\n}\n\nDATA = {}\n\n\ndef parse_message(data):\n \"\"\"Return a tuple containing the command, the key, and (optionally) the\n value cast to the appropriate type.\"\"\"\n command, key, value, value_type = data.strip().split(';')\n if value_type:\n if value_type == 'LIST':\n value = value.split(',')\n elif value_type == 'INT':\n value = int(value)\n else:\n value = str(value)\n else:\n value = None\n return command, key, value\n\n\ndef main():\n SOCKET.bind((HOST, PORT))\n SOCKET.listen(1)\n while 1:\n connection, address = SOCKET.accept()\n print('New connection from [{}]'.format(address))\n data = connection.recv(4096).decode()\n command, key, value = parse_message(data)\n if command in COMMAND_HANDLERS.keys():\n response = COMMAND_HANDLERS[command](data=DATA, stats=STATS, key=key, value=value)\n else:\n response = (False, 'Unknown command type [{}]'.format(command))\n commands.update_stats(command, response[0])\n connection.sendall('{};{}'.format(response[0], response[1]))\n connection.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"152453310","text":"class AddressLine:\n find_address = \"\"\n centroid = \"\"\n\n def __init__(self, region, city, address, index):\n self.region = region\n self.city = city\n self.address = address\n self.index = index\n\n def __str__(self):\n return \"Line: | {0} | {1} | {2} | {3} | \\n\".format(self.region, self.city, self.address, self.index)","sub_path":"AddressObject.py","file_name":"AddressObject.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"624205669","text":"\"\"\"Provides DownloadStrategy hierarchy\"\"\"\nimport datetime\nfrom abc import ABCMeta, abstractmethod\n\nfrom .. import models, mappers\nfrom ...web import errors\n\nBYTES_IN_MEGABYTE = float(1<<20)\n\nclass AbstractDownloadStrategy(object):\n __metaclass__ = ABCMeta\n\n # The default archive prefix, if not specified\n default_archive_prefix = 'flywheel'\n\n def __init__(self, log, params):\n \"\"\"Create a download strategy.\n\n Args:\n log (Logger): The context logger instance to use for logging.\n params (dict): The optional set of parameters for this strategy.\n May include 'prefix', which sets the archive path prefix.\n \"\"\"\n self.log = log\n self.archive_prefix = params.get('prefix', self.default_archive_prefix)\n\n @abstractmethod\n def validate_spec(self, spec, summary):\n \"\"\"Validate the input specification for a download.\n\n Args:\n spec (dict): The input specification for this download\n summary (bool): Whether or not this is generating a summary document\n\n Raises:\n InputValidationError: If the spec is invalid\n \"\"\"\n\n @abstractmethod\n def identify_targets(self, spec, uid, summary):\n \"\"\"Identifies the targets to add to the download.\n\n Args:\n spec (dict): The input specification for this download\n uid (str): The user id for authorization, otherwise None\n summary (bool): Whether or not this is generating a summary document\n\n Yields:\n DownloadTarget: The download targets to include\n \"\"\"\n\n def create_ticket(self, spec, uid, client_addr, origin):\n \"\"\"Identifies targets and creates a download ticket.\n\n Args:\n spec (dict): The input specification for this download\n uid (str): The user id for authorization, otherwise None\n client_addr (str): The client ip address for the download ticket\n origin (dict): The origin of the request\n\n Returns:\n dict: The download ticket details\n \"\"\"\n targets = []\n count = 0\n total_size = 0\n\n # Walk our targets to generate a summary for the ticket\n for target in self.identify_targets(spec, uid, summary=False):\n count += 1\n total_size += target.size\n targets.append(target)\n\n if len(targets) > 0:\n filename = self.create_archive_filename()\n\n tickets = mappers.DownloadTickets()\n ticket = models.DownloadTicket('batch', client_addr, origin, filename, targets, total_size)\n tickets.insert(ticket)\n\n return {\n 'ticket': ticket.ticket_id,\n 'file_cnt': count,\n 'size': total_size,\n 'filename': filename,\n }\n else:\n raise errors.APINotFoundException('No files matching the given filter could be found')\n\n def create_summary(self, spec, uid):\n \"\"\"Provide summary data by filetype for a download specification.\n\n The default implementation is to run identify_targets, then roll up the results.\n This behavior can be overridden for optimization, as needed.\n\n Args:\n spec (dict): The input specification for this download\n uid (str): The user id for authorization, otherwise None\n\n Returns:\n dict: A download summary document that maps filetype to count and size (in MB)\n \"\"\"\n totals = {}\n\n for target in self.identify_targets(spec, uid, summary=True):\n if target.filetype not in totals:\n totals[target.filetype] = {\n '_id': target.filetype,\n 'count': 0,\n 'mb_total': 0\n }\n\n sub_total = totals[target.filetype]\n sub_total['count'] += 1\n sub_total['mb_total'] += (target.size / BYTES_IN_MEGABYTE)\n\n return totals\n\n def create_archive_filename(self):\n \"\"\"Create a filename for this archive.\n\n Returns:\n str: The archive filename\n \"\"\"\n return self.archive_prefix + '_' + datetime.datetime.utcnow().strftime('%Y%m%d_%H%M%S') + '.tar'\n\n","sub_path":"api/data_export/strategy/abstract.py","file_name":"abstract.py","file_ext":"py","file_size_in_byte":4253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"16786319","text":"# -*- coding: utf-8 -*-\n# Copyright 2019 Ross Jacobs All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Generate bash script.\"\"\"\nimport re\n\n\ndef make_bash_function(func_name, func_params, func_desc, sample_req):\n \"\"\"Should work for HTTP GET\"\"\"\n print(func_params)\n function_text = \"\"\"\n\n{}\n{}() {{\n {}\n}}\"\"\".format(\n func_desc,\n func_name,\n sample_req\n )\n return function_text\n\n\ndef make_bash_script(api_key, api_calls, preamble):\n \"\"\"Make bash script.\"\"\"\n preamble = '#!/bin/bash\\n' + preamble\n # Put a '# ' in front of every line except first ^.\n generated_text = preamble.replace('\\n', '\\n# ')[:-2]\n generated_text += '\\nAPIKEY=' + api_key\n generated_text += '\\nBASEURL=https://api.meraki.com/api/v0\\n'\n for api_call in api_calls:\n sample_req = api_call['sample_req'].replace('', '$APIKEY')\n # Each curl option gets its own line. Don't split if it is already.\n if '\\n' not in sample_req:\n sample_req = sample_req.replace(' -', '\\\\\\n -')\n else:\n sample_req = sample_req.replace('\\n -', '\\n -')\n num_path_params = len(re.findall(r'[\\[{]', api_call['path']))\n # Create a list like ['$1', '$2', '$3', '$4', '$5'] for formatting\n var_list = ['${}'.format(i) for i in range(1, num_path_params+1)]\n api_path = '$BASEURL' + re.sub(\n r'[\\[{][A-Za-z-_]*?[\\]}]', '{}', api_call['path'])\n api_path = api_path.format(* var_list)\n sample_req = re.sub(r'\\'https.*?\\'', api_path, sample_req)\n func_desc = '# ' + api_call['gen_func_desc'].replace('\\n ', '\\n# ')\n generated_text += make_bash_function(\n api_call['gen_name'],\n api_call['gen_params'],\n func_desc,\n sample_req,\n ) + '\\n'\n\n print(generated_text)\n with open('meraki_api.sh', 'w') as myfile:\n myfile.write(generated_text)\n return generated_text\n","sub_path":"merakygen/make_bash_script.py","file_name":"make_bash_script.py","file_ext":"py","file_size_in_byte":2466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"52970743","text":"import serial\nimport time\nimport os\nos.system('sudo chmod 666 /dev/ttyACM0')\nser = serial.Serial('/dev/ttyACM0',9600)\ndef alrm():\n a = 'd'+'\\n'\n ser.write(a)\n z = time.time()\n flg = False\n while (time.time() - z) < 60:\n print(time.time()-z)\n y = ser.read(1)\n print(y)\n if y == 'y':\n flg = True #Human pressed the button\n print(flg)\n break\n else:\n continue\n return(not flg)\nwhile True:\n a = input(\"Continue\")\n if a == 1:\n alrm()\n","sub_path":"TARP/tst.py","file_name":"tst.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"528828074","text":"from django.shortcuts import render_to_response, get_object_or_404\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import User\nfrom events.models import Event\n# Create your views here.\n\ndef home(request):\n\treturn render_to_response('events/home.html')\n\ndef event(request, username, slug, year, month, day):\n\tuser = get_object_or_404(User, username=username)\n\tevent = get_object_or_404(Event,\n\t\t user=user,\n\t\t slug=slug,\n\t\t start__year=year,\n\t\t start__month=month,\n\t\t start__day=day)\n\tresponse = {\n\t\t'EVENT': event,\n\t}\n\treturn render_to_response('events/event.html',\n\t\t response,\n\t\t RequestContext(request))","sub_path":"techtalks/events/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"443854717","text":"# -*- coding: UTF-8 -*-\nimport multiprocessing\nimport datetime\nimport cv2\nimport time\nfrom mtcnn_my import MTCNN\nimport numpy as np\nimport time\nfrom core.symbol import L_Net, O_Net\nfrom tools.load_model import load_param\nimport mxnet as mx\nfrom tools.image_processing import transform\nfrom multiprocessing import Pool\nfrom functools import partial\nimport copy\n\n\nclass Face(object):\n def __init__(self):\n self.face_id = None\n self.loc = None\n self.isCanShow = None\n self.frame_face_prev = None\n self.face_5_points = []\n self.frameId = 0\n self.ptr_num = 0\n self.score = None\n self.bbox = None\n\n def face(self, instance_id, rect):\n self.face_id = instance_id\n self.loc = rect\n self.isCanShow = False\n\n\nclass FaceTracking(object):\n def __init__(self):\n self.tracking_id = None\n self.ImageHighDP = None\n self.candidateFaces_lock = None\n self.detection_Time = -1\n self.detection_Interval = None\n self.stabilization = None\n self.trackingFace = [] # 输出的结果\n self.candidateFaces = []\n self.tpm_scale = 2\n # self.pool = multiprocessing.Pool(processes=4)\n # multiprocessing.set_start_method('spawn')\n # self.face = Face()\n\n def detecting(self, image):\n try:\n mtcnn_result = MTCNN(image) # MTCNN人脸检测结果 首帧人脸检测\n except:\n mtcnn_result = {}\n box_num = len(mtcnn_result) # 首帧包含的人脸个数\n self.candidateFaces_lock = 1 # 上锁\n for i in range(box_num):\n result = mtcnn_result[i] # result 包含[[5 points],array[box],score]\n bbox = result[1] # 0 -> 5 points, 1 -> bbox, 2 ->score\n bbox_square = self.convert_to_square(bbox) # 校正为正方形 [x1, y1, x2, y2]\n\n face_new = Face()\n face_new.face(self.tracking_id, bbox_square)\n\n img_new = self.deepcopy(image)\n img_draw = img_new[int(bbox_square[1]):int(bbox_square[3]), int(bbox_square[0]):int(bbox_square[2])]\n face_new.frame_face_prev = img_draw\n\n self.tracking_id = self.tracking_id + 1 # 统计待追踪的个数\n self.candidateFaces.append(face_new) # self.candidateFaces 存放的是类!\n\n self.candidateFaces_lock = 0\n\n def init_success(self):\n return len(self.candidateFaces) >= 0\n\n @staticmethod\n def deepcopy(x):\n return copy.deepcopy(x)\n\n def Init(self, image):\n # self.ImageHighDP = image.copy() # 复制输入图片\n self.tracking_id = 0 # 初始化追踪id为0\n self.detection_Interval = 0.5 # 检测间隔 detect faces every 200 ms\n self.detecting(image) # 首帧人脸检测\n self.stabilization = False\n\n @staticmethod\n def tracking_corrfilter(frame, model):\n frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n model_gray = cv2.cvtColor(model, cv2.COLOR_BGR2GRAY)\n # x1, y1, x2, y2 = trackBox[0], trackBox[1], trackBox[2], trackBox[3]\n # w = x2 - x1 + 1\n # h = y2 - y1 + 1\n w, h = model_gray.shape[::-1]\n\n # Apply template Matching [eval() 函数用来执行一个字符串表达式,并返回表达式的值]\n # https://segmentfault.com/a/1190000015679691\n # http://bluewhale.cc/2017-09-22/use-python-opencv-for-image-template-matching-match-template.html\n method = eval('cv2.TM_CCOEFF_NORMED')\n res = cv2.matchTemplate(frame_gray, model_gray, method)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\n\n top_left = max_loc # 左上角\n bottom_right = (top_left[0] + w, top_left[1] + h) # 右下角\n\n # cv2.rectangle(frame_disp, top_left, bottom_right, 255, 2) # display result\n # cv2.imshow('test', frame_disp)\n # cv2.waitKey(0)\n\n trackBox = np.array([top_left[0], top_left[1], bottom_right[0], bottom_right[1]])\n return trackBox\n\n @staticmethod\n def convert_to_square(bbox):\n \"\"\"\n convert bbox to square 将输入边框变为正方形,以最长边为基准,不改变中心点\n :param bbox: input bbox / numpy array , shape n x 5 [4个坐标值]\n :return: square bbox\n \"\"\"\n square_bbox = bbox.copy() # bbox = [x1, y1, x2, y2]\n\n h = bbox[3] - bbox[1] + 1 # 计算框的宽度 加1?\n w = bbox[2] - bbox[0] + 1 # 计算框的长度\n max_side = np.maximum(h, w) # 找出最大的那个边\n\n square_bbox[0] = bbox[0] + w * 0.5 - max_side * 0.5 # 新bbox的左上角x\n square_bbox[1] = bbox[1] + h * 0.5 - max_side * 0.5 # 新bbox的左上角y\n square_bbox[2] = square_bbox[0] + max_side - 1 # 新bbox的右下角x\n square_bbox[3] = square_bbox[1] + max_side - 1 # 新bbox的右下角y\n\n if square_bbox[0] < 0:\n lack_ = abs(square_bbox[0])\n square_bbox[0] = 0\n square_bbox[2] = square_bbox[2] + lack_\n\n if square_bbox[1] < 0:\n lack_ = abs(square_bbox[1])\n square_bbox[1] = 0\n square_bbox[3] = square_bbox[3] + lack_\n\n return square_bbox\n\n @staticmethod\n def onet_detector(image):\n \"\"\"\n :param image: 输入为48*48大小的图像\n :return: 返回概率值\n \"\"\"\n sym = O_Net('test')\n ctx = mx.cpu()\n # ctx = mx.gpu() \n # ctx = [mx.gpu(int(i)) for i in [0,1,2,3]]\n\n args, auxs = load_param('model/onet', 9, convert=False, ctx=ctx)\n data_size = 48 # landmark net 输入的图像尺寸为48*48\n data_shapes = {'data': (1, 3, data_size, data_size)}\n # # img_resized = cv2.resize(image, (48, 48))\n\n newimg = transform(image)\n args['data'] = mx.nd.array(newimg, ctx)\n executor = sym.simple_bind(ctx, grad_req='null', **dict(data_shapes))\n executor.copy_params_from(args, auxs)\n executor.forward(is_train=False) # inference\n out_list = [[] for _ in range(len(executor.outputs))]\n for o_list, o_nd in zip(out_list, executor.outputs):\n o_list.append(o_nd.asnumpy())\n out = list()\n for o in out_list:\n out.append(np.vstack(o))\n cls_pro = out[0][0][1]\n return out\n\n @staticmethod\n def calibrate_box(bbox, reg):\n \"\"\"\n calibrate bboxes 校准BBox(Bounding Box Regression)\n :param bbox: input bboxes / numpy array, shape n x 5\n :param reg: bboxes adjustment / numpy array, shape n x 4\n :return: bboxes after refinement\n \"\"\"\n bbox_c = bbox.copy()\n w = bbox[2] - bbox[0] + 1 # 计算框的长度 加1?\n # w = np.expand_dims(w, 1)\n h = bbox[3] - bbox[1] + 1 # 计算框的宽度\n # h = np.expand_dims(h, 1)\n reg_m = np.hstack([w, h, w, h]) # 在水平方向上平铺\n aug = reg_m * reg # aug应该是回归量\n bbox_c[0:4] = bbox_c[0:4] + aug\n return bbox_c # 返回校正之后的bbox_c\n\n def doingLandmark_onet(self, image, trackBox):\n \"\"\"\n\n :param image:\n :param trackBox:\n :return:\n \"\"\"\n # x1 = trackBox[0]\n # y1 = trackBox[1]\n #\n # cv2.imwrite('error.jpg', image)\n # mtcnn_result = MTCNN(image)\n # print(mtcnn_result)\n # cls_pro = mtcnn_result[0][2] # 0 -> 5 points, 1 -> bbox, 2 ->score\n # bbox = mtcnn_result[0][1]\n # bbox[0] = bbox[0] + x1\n # bbox[1] = bbox[1] + y1\n # bbox[2] = bbox[2] + x1\n # bbox[3] = bbox[3] + y1\n # landmarks = mtcnn_result[0][0]\n # landmarks[0] = landmarks[0] + x1\n # landmarks[1] = landmarks[1] + y1\n # landmarks[2] = landmarks[2] + x1\n # landmarks[3] = landmarks[3] + y1\n # landmarks[4] = landmarks[4] + x1\n # landmarks[5] = landmarks[5] + y1\n # landmarks[6] = landmarks[6] + x1\n # landmarks[7] = landmarks[7] + y1\n # landmarks[8] = landmarks[8] + x1\n # landmarks[9] = landmarks[9] + y1\n\n # bbox = list(bbox)\n\n # return cls_pro, bbox, landmarks\n\n detect_length = min(image.shape[0], image.shape[1])\n ctx = mx.cpu()\n # ctx = mx.gpu() \n # ctx = [mx.gpu(int(i)) for i in [0,1,2,3]]\n\n sym = L_Net('test')\n args, auxs = load_param('model/lnet', 4390, convert=False, ctx=ctx)\n\n data_size = 48 # landmark net 输入的图像尺寸为48*48\n imshow_size = 48 # imshow_size为landmark结果展示的图片尺寸\n data_shapes = {'data': (1, 3, data_size, data_size)}\n img_resized = cv2.resize(image, (48, 48))\n result = self.onet_detector(img_resized) # 得到该图是人脸的概率值\n cls_pro = result[0][0][1]\n reg_m = result[1][0]\n bbox_new = self.calibrate_box(trackBox, reg_m)\n newimg = transform(img_resized)\n args['data'] = mx.nd.array(newimg, ctx)\n executor = sym.simple_bind(ctx, grad_req='null', **dict(data_shapes))\n executor.copy_params_from(args, auxs)\n out_list = [[] for _ in range(len(executor.outputs))]\n executor.forward(is_train=False) # inference\n for o_list, o_nd in zip(out_list, executor.outputs):\n o_list.append(o_nd.asnumpy())\n out = list()\n for o in out_list:\n out.append(np.vstack(o))\n landmarks = out[0]\n\n for j in range(int(len(landmarks)/2)):\n if landmarks[2 * j] > 1:\n landmarks[2 * j] = 1\n if landmarks[2 * j] < 0:\n landmarks[2 * j] = 0\n if landmarks[2 * j + 1] > 1:\n landmarks[2 * j + 1] = 1\n if landmarks[2 * j + 1] < 0:\n landmarks[2 * j + 1] = 0\n\n landmarks = landmarks * imshow_size # landmarks输出值应该在0~1 需复原\n landmarks = np.reshape(landmarks, -1)\n\n fator = float(detect_length)/48.0\n disp_landmark = []\n\n for j in range(int(len(landmarks) / 2)):\n display_landmark_x = int(landmarks[j] * fator + trackBox[0])\n display_landmark_y = int(landmarks[j+5] * fator + trackBox[1])\n disp_landmark.append(display_landmark_x)\n disp_landmark.append(display_landmark_y)\n\n # for j in range(int(len(landmarks) / 2)):\n # cv2.circle(frame, (int(disp_landmark[j * 2]), int(disp_landmark[j * 2 + 1])), 2, (0, 255, 0), -1) # b g r\n # cv2.rectangle(frame, (int(trackBox[0]), int(trackBox[1])), (int(trackBox[2]), int(trackBox[3])), (0, 255, 0), 2) #\n # cv2.imshow('frame', frame)\n # cv2.waitKey(0)\n\n return cls_pro, bbox_new, disp_landmark\n\n def tracking(self, image, face):\n # face 为首帧得到的其中一个候选人脸对应的类Face, image可以认为是第二帧的image\n # image_new = self.deepcopy(image)\n st = time.time()\n # k = np.random.randint(100)\n # print('[{}]st'.format(k), datetime.datetime.now())\n # faceROI = face.loc # 对应的是坐标\n model = face.frame_face_prev\n trackBox = self.tracking_corrfilter(image, model)\n # trackBox = np.array([351,77,454,180])\n # print(trackBox)\n time5 = time.time()\n\n trackBox_new = self.convert_to_square(trackBox) # 转变为正方形 以便后续操作\n x1 = trackBox_new[0]\n y1 = trackBox_new[1]\n x2 = trackBox_new[2]\n y2 = trackBox_new[3]\n # x1, y1, x2, y2 = trackBox[0], trackBox[1], trackBox[2], trackBox[3]\n # 根据搜寻到的坐标 从当前帧获取对应图像区域即为faceROI_Image\n faceROI_Image = image[int(y1):int(y2), int(x1):int(x2)] # 正方形图片\n time6 = time.time()\n\n # faceROI_Image为输入LNet的图像, face对应类 利用face.face_5_points存放5点关键点\n face.score, face.bbox, face.face_5_points = self.doingLandmark_onet(faceROI_Image, trackBox_new) # ?\n time7 = time.time()\n\n # print('[{}]time7'.format(k), datetime.datetime.now())\n\n if face.score > 0.1:\n face.loc = self.convert_to_square(face.bbox)\n img_draw = image[int(face.loc[1]):int(face.loc[3]), int(face.loc[0]):int(face.loc[2])]\n face.frame_face_prev = img_draw\n face.frameId += 1\n face.isCanShow = True\n \n time8 = time.time()\n # print('[{}]time8'.format(k), datetime.datetime.now())\n print('time5-st1:{}'.format(time5-st))\n print('time6-time5:{}'.format(time6-time5))\n print('time7-time6:{}'.format(time7-time6))\n print('time8-time7:{}'.format(time8-time7))\n\n return True\n else:\n print('time5-st1:{}'.format(time5-st))\n print('time6-time5:{}'.format(time6-time5))\n print('time7-time6:{}'.format(time7-time6))\n # print('[{}]time9'.format(k), datetime.datetime.now())\n return False\n\n def setMask(self, image, loc): # 将image中的face区域置为0 face:x1 y1 x2 y2\n x1, y1, x2, y2 = loc[0], loc[1], loc[2], loc[3]\n image[int(y1):int(y2), int(x1):int(x2)] = 0\n return image\n\n def update(self, image):\n st = time.time()\n \n self.ImageHighDP = image.copy() # 复制\n\n time1 = time.time()\n\n if len(self.candidateFaces) > 0 and not self.candidateFaces_lock: # 同时检测完成\n for i in range(len(self.candidateFaces)):\n self.trackingFace.append(self.candidateFaces[i])\n self.candidateFaces.clear()\n\n time2 = time.time()\n\n # self.trackingFace中存放的是一个个的类Face\n # for i in range(len(self.trackingFace)):\n # if not self.tracking(image, self.trackingFace[i]):\n # 不可以采用这种方法在for循环中删除元素 https://segmentfault.com/a/1190000007214571\n\n self.trackingFace = list(filter(lambda x: self.tracking(self.deepcopy(image), x), self.trackingFace))\n # print(self.trackingFace)\n\n # if len(self.trackingFace) > 1:\n # tmp = self.trackingFace[0]\n # self.trackingFace.clear()\n # self.trackingFace.append(tmp)\n # print('[Start]', datetime.datetime.now())\n\n # multiprocessing.set_start_method('spawn')\n # print('[Start1]', datetime.datetime.now())\n # pool = Pool(processes=4)\n # print('[Star2]', datetime.datetime.now())\n # func = partial(self.tracking, image)\n # print('[Start3]', datetime.datetime.now())\n # result = pool.map(func, self.trackingFace)\n # pool.close()\n # pool.join()\n # print('[Final]', datetime.datetime.now())\n # print(result)\n # temp = []\n # for i in range(len(result)):\n # if result[i]:\n # temp.append(self.trackingFace[i])\n # print(self.trackingFace)\n # print(temp)\n # self.trackingFace = temp\n\n # print(self.trackingFace)\n\n time3 = time.time()\n\n if self.detection_Time < 0:\n self.detection_Time = time.time()\n else:\n diff = time.time() - self.detection_Time\n if diff > self.detection_Interval:\n for class_ in self.trackingFace:\n self.ImageHighDP = self.setMask(self.ImageHighDP, class_.loc)\n self.detection_Time = time.time()\n # print('Have detected.')\n self.detecting(self.ImageHighDP)\n time4 = time.time()\n \n print('time1-st:{}'.format(time1 - st))\n print('time2-time1:{}'.format(time2 - time1)) \n print('time3-time2:{}'.format(time3 - time2))\n print('time4-time3:{}'.format(time4 - time3)) \n\n\n\n\n\n","sub_path":"facetrack.py","file_name":"facetrack.py","file_ext":"py","file_size_in_byte":15905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"465562327","text":"\nfrom builtins import range\nfrom airflow.operators.bash_operator import BashOperator\nfrom airflow.operators.python_operator import PythonOperator\nfrom airflow.operators.email_operator import EmailOperator\nfrom airflow.models import DAG\nfrom datetime import datetime, timedelta\nimport time\nimport uuid\nfrom string import Template\nfrom pprint import pprint\nimport os\nfrom string import Template\nfrom pyspark.sql import SparkSession\n\n\nVERSION = \"1.1\"\n\n\nSUBMIT_ROOT = '$SPARK_HOME/bin/spark-submit --conf \"spark.local.dir=/root/airflow/jobs/tmp\" --master local[64] --driver-memory 100G --executor-memory 150G /root/airflow/jobs/discount_trends/beauty/'\n\nargs = {\n 'owner': 'airflow',\n 'start_date': datetime(2019, 3, 7),\n 'end_date': datetime(2019, 3, 7)\n}\n\ndag = DAG(\n dag_id='sephora_discount_trendsV2',\n default_args=args,\n catchup=True,\n schedule_interval='@daily',\n concurrency=8,\n max_active_runs=8\n)\n\nthreshold = .02\n\nsegments = {\n 'FRAGRANCE_AFTER_SHAVE': 1137138798,\n # 'FRAGRANCE_ALL_OTHER_BODY': 1137138799,\n # 'FRAGRANCE_ALL_OTHER_HOME_ANCILLARIES': 1137138800,\n # 'FRAGRANCE_BATHSHOWER_GELS': 1137138801,\n # 'FRAGRANCE_BODY_SPRAY': 1137138802,\n # 'FRAGRANCE_BUBBLE_BATH': 1137138803,\n # 'FRAGRANCE_CANDLES': 1137138804,\n # 'FRAGRANCE_DEODORANTANTIPERSPIRANT': 1137138805,\n # 'FRAGRANCE_GIFT_SETS': 1137138806,\n # 'FRAGRANCE_HAIR': 1137138807,\n # 'FRAGRANCE_JUICES': 1137138808,\n # 'FRAGRANCE_LOTIONCREME': 1137138809,\n # 'FRAGRANCE_POWDERTALC': 1137138810,\n # 'FRAGRANCE_SHAVE': 1137138811,\n # 'FRAGRANCE_SOAP': 1137138812,\n # 'MAKEUP_ALL_OTHER': 1137138814,\n # 'MAKEUP_ALL_OTHER_APPLICATOR': 1137138815,\n # 'MAKEUP_ALL_OTHER_EYE': 1137138816,\n # 'MAKEUP_ALL_OTHER_FACE': 1137138817,\n # 'MAKEUP_ALL_OTHER_LIP': 1137138818,\n # 'MAKEUP_ALL_OTHER_PRIMER': 1137276702,\n # 'MAKEUP_BASE_COATSTOP_COATS': 1137138819,\n # 'MAKEUP_BLUSH': 1137138820,\n # 'MAKEUP_BRONZER': 1137299787,\n # 'MAKEUP_COLOR_ENAMEL': 1137138821,\n # 'MAKEUP_CONCEALER': 1137138822,\n # 'MAKEUP_EYE_APPLICATOR': 1137138823,\n # 'MAKEUP_EYE_BROW': 1137138824,\n # 'MAKEUP_EYE_LINER': 1137138825,\n # 'MAKEUP_EYE_PRIMER': 1137276699,\n # 'MAKEUP_EYE_SHADOW': 1137138826,\n # 'MAKEUP_FACE_APPLICATOR': 1137138827,\n # 'MAKEUP_FACE_PRIMER': 1137276700,\n # 'MAKEUP_FALSE_EYELASHES': 1137276698,\n # 'MAKEUP_FOUNDATION': 1137138828,\n # 'MAKEUP_HIGHLIGHTER': 1137299786,\n # 'MAKEUP_LIP_APPLICATOR': 1137138829,\n # 'MAKEUP_LIP_COLOR': 1137138830,\n # 'MAKEUP_LIP_GLOSS': 1137138831,\n # 'MAKEUP_LIP_LINER': 1137138832,\n # 'MAKEUP_LIP_PRIMER': 1137276701,\n # 'MAKEUP_MASCARA': 1137138833,\n # 'MAKEUP_NAIL_CARE': 1137138834,\n # 'MAKEUP_POWDER': 1137138835,\n # 'MAKEUP_SETS': 1137138836,\n # 'MAKEUP_SETTING_SPRAYPOWDER': 1137299788,\n # 'MAKEUP_TINTED_MOISTURISER': 1137276703,\n # 'SKINCARE_ACNE_TREATMENT': 1137138850,\n # 'SKINCARE_AFTER_SUN': 1137138851,\n # 'SKINCARE_AGE_SPECIALIST': 1137138852,\n # 'SKINCARE_ALL_OTHER_BODY': 1137138853,\n # 'SKINCARE_ALL_OTHER_FACE': 1137138854,\n # 'SKINCARE_ALL_OTHER_SUN': 1137138856,\n # 'SKINCARE_BODY_CLEANSERS': 1137138857,\n # 'SKINCARE_BODY_DEVICES': 1137240849,\n # 'SKINCARE_BODY_EXFOLIATOR': 1137138858,\n # 'SKINCARE_BODY_IN_SUN': 1137311864,\n # 'SKINCARE_BODY_MOISTURIZERS': 1137138859,\n # 'SKINCARE_BRIGHTENING_SPECIALIST': 1137217755,\n # 'SKINCARE_EYE_TREATMENT': 1137138860,\n # 'SKINCARE_FACE_IN_SUN': 1137138869,\n # 'SKINCARE_FACIAL_CLEANSER': 1137138861,\n # 'SKINCARE_FACIAL_DEVICES': 1137240848,\n # 'SKINCARE_FACIAL_EXFOLIATOR': 1137138862,\n # 'SKINCARE_FACIAL_MOISTURIZER': 1137138863,\n # 'SKINCARE_FIRMINGCELLULITE_PRODUCT': 1137138864,\n # 'SKINCARE_HAND_SOAP': 1137299785,\n # 'SKINCARE_LIP_TREATMENT': 1137138870,\n # 'SKINCARE_MAKEUP_REMOVER': 1137138871,\n # 'SKINCARE_MASK': 1137138872,\n # 'SKINCARE_OILSHINE_CONTROL': 1137138873,\n # 'SKINCARE_SELF-TANNER': 1137138874,\n # 'SKINCARE_SETSKITS': 1137138875,\n # 'SKINCARE_SHAVE_FACE': 1137138877,\n # 'SKINCARE_SHAVE_BODY': 1137138876,\n # 'SKINCARE_TONERSCLARIFYERS': 1137138878\n}\n\n\noutlet = 1137053465\n\n\n\nfor key in segments:\n\n job_id = \"sephora_discount_trends\"\n\n # extract data for each segment\n extract = BashOperator(\n task_id='extract_'+key,\n bash_command=SUBMIT_ROOT + 'extract.py {{execution_date}} '+str(segments[key]) + \" \" + job_id,\n dag=dag\n )\n\n # run the model for each segment\n model = BashOperator(\n task_id='model_'+key,\n bash_command=SUBMIT_ROOT + 'model.py {{execution_date}} ' + str(segments[key]) + \" \" + str(threshold) + \" \" + job_id + \" \" +str(outlet),\n dag=dag\n )\n\n extract >> model\n\n\n load = BashOperator(\n task_id='load_'+key,\n bash_command=SUBMIT_ROOT + 'load.py {{execution_date}} '+str(job_id) + ' ' + str(segments[key]),\n dag=dag\n )\n\n model >> load\n\n\n # # calculate the view for each outlet\n # for outlet in outlets:\n\n # load = BashOperator(\n # task_id='load_'+key+'_'+outlet,\n # bash_command=SUBMIT_ROOT + 'load_retailer.py {{execution_date}} '+str(segments[key]) + \" \" + str(outlets[outlet]) + \" \" +str(outlet) + \" \" + job_id,\n # dag=dag\n # )\n\n # outlet_load_tasks.append(load)\n\n # model >> outlet_load_tasks\n\n","sub_path":"airflow/dags/sephora_discount_trends.py","file_name":"sephora_discount_trends.py","file_ext":"py","file_size_in_byte":5408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"374565218","text":"from typing import Deque\n\n\nn=int(input())\n\ndx=[-2,-1,1,2,-2,-1,1,2]\ndy=[-1,-2,-2,-1,1,2,2,1]\n\ndef func(ax,ay,sx,sy):\n q=Deque()\n q.append([ax,ay])\n matrix[ax][ay]=1\n while q:\n a,b=q.popleft()\n if a==sx and b==sy:\n print(matrix[a][b]-1)\n return\n for i in range(8):\n rx=a+dx[i]\n ry=b+dy[i]\n if 0<=rxi):\n r=posr-i\n else:\n r=i-posr\n if j>posc:\n c=j-posc\n else:\n c=posc-j\n check=r+c\n if checkmr):\n print (\"UP\")\n return 0\n if (poscmc):\n print (\"LEFT\")\n return 0 \n \n return 0 \n\n# Tail starts here\nif __name__ == \"__main__\":\n pos = [int(i) for i in input().strip().split()]\n board = [[j for j in input().strip()] for i in range(5)]\n next_move(pos[0], pos[1], board)\n\n","sub_path":"Simple_Cleaning_Bot.py","file_name":"Simple_Cleaning_Bot.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"565197797","text":"from fastapi import APIRouter, Request\n\nrouter = APIRouter(\n prefix=\"/utils\",\n tags=[\"UTILITIES\"]\n)\n\n\n@router.get('/endpoints/')\ndef list_endpoints(request: Request):\n url_list = [\n {'path': route.path, 'name': route.name}\n for route in request.app.routes\n ]\n return url_list\n","sub_path":"app/utils/endpoints.py","file_name":"endpoints.py","file_ext":"py","file_size_in_byte":305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"47309961","text":"import math\n\n\ndef is_abundant(num):\n if math.sqrt(num).is_integer():\n s = 1 + math.sqrt(num)\n else:\n s = 1\n d = 2\n while d < math.sqrt(num):\n if num % d == 0:\n s += d + (num / d)\n d += 1\n if s > num:\n return True\n else:\n return False\nabundantNumbers = []\nx = 12\nwhile x < 28123:\n if is_abundant(x):\n abundantNumbers.append(x)\n x += 1\nisAbundantSum = [False] * 28123\ni = j = 0\nwhile i < len(abundantNumbers):\n j = 0\n while j <= i and abundantNumbers[i] + abundantNumbers[j] < len(isAbundantSum):\n isAbundantSum[abundantNumbers[i] + abundantNumbers[j]] = True\n j += 1\n i += 1\nsol = 0\ni = 0\nwhile i < len(isAbundantSum):\n if not isAbundantSum[i]:\n sol += i\n i += 1\nprint(sol)\n","sub_path":"Solution-023.py","file_name":"Solution-023.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"95567048","text":"import json\nimport Utils as util\n\ntags_path = 'data/champ_tags.json'\noutput_path = 'data/champ_tags.pickle'\n\nwith open(tags_path, 'r') as f:\n # json_str = f.read().replace('\\n', '')\n parsed_obj = json.load(f)\n\n\nchamp_dict = parsed_obj['data']\n\ntag_champ_dict = {}\ntag_set = set()\n\n\nfor c_name, champ in champ_dict.items():\n c_id = champ['id']\n tag_list = champ['tags']\n tag_champ_dict[c_id] = tag_list\n for t in tag_list:\n tag_set.add(t)\n\nutil.save((tag_set, tag_champ_dict), output_path)","sub_path":"parse_champ_tags.py","file_name":"parse_champ_tags.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"94019862","text":"'''\n报数序列是一个整数序列,按照其中的整数的顺序进行报数,得到下一个数。其前五项如下:\n\n1. 1\n2. 11\n3. 21\n4. 1211\n5. 111221\n1 被读作  \"one 1\"  (\"一个一\") , 即 11。\n11 被读作 \"two 1s\" (\"两个一\"), 即 21。\n21 被读作 \"one 2\",  \"one 1\" (\"一个二\" ,  \"一个一\") , 即 1211。\n\n给定一个正整数 n(1 ≤ n ≤ 30),输出报数序列的第 n 项。\n\n注意:整数顺序将表示为一个字符串。\n'''\n\nclass Solution:\n def countAndSay(self, n: int) -> str:\n def next_num(tmp):\n res = \"\"\n i = 0\n tmp_n = len(tmp)\n while i < tmp_n:\n count = 1\n while i < tmp_n - 1 and tmp[i] == tmp[i+1]:\n count += 1\n i += 1\n res += (str(count) + tmp[i])\n i += 1\n return res\n res = \"1\"\n for i in range(1, n):\n res = next_num(res)\n return res\n\n\n \n\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"38_countAndSay.py","file_name":"38_countAndSay.py","file_ext":"py","file_size_in_byte":1062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"251570543","text":"try:\n from egovOpenData.spiders.ogdSpider.base_spider import *\nexcept ImportError:\n from egovResearch.egovOpenData.spiders.ogdSpider.base_spider import *\n\nconfig = {\n \"loop_start\": 1,\n \"loop_end\": 19, # 19\n}\nclass NaihaiSpider(BaseSpider):\n __org_abbreviation__ = \"naihai\"\n\n # ---/---更新页码信息\n def _update_page_count(self):\n \"\"\"\n 更新页码信息\n :return:\n \"\"\"\n for config in self.config_list:\n request_url = \"http://data.nanhai.gov.cn/cms/sites/sjzy/load_sj_theme.jsp?tid=all&page={}&t=0.38732353291425214\".format(\n config.loop_start\n )\n res = requests.get(request_url, headers=self.requests_header)\n soup = BeautifulSoup(res.text, \"lxml\")\n total_data_sets = 0\n page_count = soup.find(\"span\",id=\"pagenavpagecount\").find(\"b\").text\n print(\"--num of datasets--:\", total_data_sets, \" --page_num--:\", page_count)\n config.loop_stop = int(page_count)+1\n config.update()\n\n # ---/---保存数据详情页信息\n def process_detail_data_page(self, page_dir, url, elem_id, item):\n \"\"\"\n 保存数据详情页信息\n :param page_dir:\n :param url:\n :param elem_id:\n :param item:\n :return:\n \"\"\"\n detail_url = \"http://data.nanhai.gov.cn{}\".format(url)\n print(elem_id)\n if not os.path.exists(page_dir):\n os.makedirs(page_dir)\n detail_res = requests.get(detail_url, headers=self.requests_header)\n detail_res.encoding = HTML_ENCODING\n with open(\"{}\\{}.html\".format(page_dir, elem_id), \"w+\",\n encoding=HTML_ENCODING, errors=\"ignore\") as f:\n f.write(detail_res.text)\n soup = BeautifulSoup(detail_res.text, \"lxml\")\n table = soup.find(\"div\", class_=\"xz_sj_text\").find(\"table\")\n for tr in table.find_all(\"tr\"):\n tds = tr.find_all(\"td\")\n for key, value in metadata.items():\n if value in tds[0].text:\n setattr(item, key, tds[1].text.strip())\n item.data_desc = soup.find(\"div\", class_=\"sjml_text2\").text.strip()\n\n # ---/---保存所有数据\n def process_all_data_sets_info(self):\n \"\"\"\n 保存所有数据\n :return:\n \"\"\"\n config_list = self.config_list\n for config in config_list:\n for page_index in range(config.loop_start, config.loop_stop):\n request_url = \"http://data.nanhai.gov.cn/cms/sites/sjzy/load_sj_theme.jsp?tid=all&page={}&t=0.38732353291425214\".format(\n page_index\n )\n res = requests.get(request_url, headers=self.requests_header)\n list_dir = \"{}list_html\\\\{}\".format(self.base_dir, page_index)\n if not os.path.exists(list_dir):\n os.makedirs(list_dir)\n with open(\"{}\\{}.html\".format(list_dir, page_index),\n \"w\", encoding=HTML_ENCODING, errors=\"ignore\") as f:\n f.write(res.text)\n detail_page_dir = \"{}detail_pages\\\\{}\".format(self.base_dir, page_index)\n print(\"------------page_index:---------\", page_index)\n soup = BeautifulSoup(res.text, \"lxml\")\n table = soup.find(\"table\", id=\"my_table\")\n for tr in table.find_all(\"tr\"):\n\n if tr.find(\"a\") is None:\n continue\n item = EGOVOpenDataItem()\n\n tds = tr.find_all(\"td\")\n a = tds[0].find(\"a\")\n url = a.get(\"href\")\n elem_id = url.split(\"=\")[-1]\n\n item.data_name = a.text.strip().replace(\"·\", \"\")\n item.data_provider = tds[1].find(\"a\").text.strip()\n item.data_domain = tds[2].text.strip()\n\n item.data_download_times = tds[-2].text.strip()\n item.data_update_date = tds[-1].text.strip()\n\n item.origin_page_index = page_index\n item.origin_elem_id = elem_id\n self.process_detail_data_page(detail_page_dir, url, elem_id, item)\n self.save_item(item)\n\nHTML_ENCODING = \"gb2312\"\n\nmetadata = {\n \"data_key_words\": \"关键字项\",\n \"data_publish_date\": \"创建时间\",\n \"data_update_date\": \"更新时间\",\n \"data_download_format\": \"资源格式\",\n}\n\nif __name__ == '__main__':\n with app.app_context():\n NaihaiSpider(True).update()\n","sub_path":"egovResearch/egovOpenData/spiders/ogdSpider/guangdong_spiders/nanhai_spider.py","file_name":"nanhai_spider.py","file_ext":"py","file_size_in_byte":4594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"628419937","text":"import contributors as contributors_util\nfrom csp import csp\nfrom flask import Flask, render_template as flask_render_template, request\nfrom flask_talisman import Talisman\nfrom language import DEFAULT_LANGUAGE, get_language\nimport logging\nfrom validate import validate, SUPPORTED_YEARS, DEFAULT_YEAR\n\napp = Flask(__name__)\nTalisman(app,\n content_security_policy=csp,\n content_security_policy_nonce_in=['script-src'])\nlogging.basicConfig(level=logging.DEBUG)\n\n\ndef render_template(template, *args, **kwargs):\n year = request.view_args.get('year', DEFAULT_YEAR)\n supported_languages = SUPPORTED_YEARS.get(year, (DEFAULT_LANGUAGE))\n\n lang = request.view_args.get('lang')\n language = get_language(lang)\n kwargs.update(supported_languages=supported_languages, language=language, supported_years=list(SUPPORTED_YEARS.keys()))\n return flask_render_template(template, *args, **kwargs)\n\n\ndef get_view_args(lang=None):\n view_args = request.view_args.copy()\n if lang:\n # Optionally overwrite the lang value in the current request.\n view_args.update(lang=lang)\n return view_args\n\n\n# Make this function available in templates.\napp.jinja_env.globals['get_view_args'] = get_view_args\n\n@app.route('/')\n@app.route('//')\n@validate\ndef home(lang):\n return render_template('%s/index.html' % lang)\n\n@app.route('/')\n@app.route('//')\n@validate\ndef index(lang):\n return render_template('%s/splash.html' % lang)\n\n\n@app.route('//outline')\n@app.route('///outline')\n@validate\ndef outline(year, lang):\n return render_template('%s/%s/outline.html' % (lang, year))\n\n\n@app.route('//contributors')\n@app.route('///contributors')\n@validate\ndef contributors(year, lang):\n contributors = contributors_util.get_contributors()\n return render_template('%s/%s/contributors.html' % (lang, year), contributors=contributors)\n\n\n@app.route('//methodology')\n@app.route('///methodology')\n@validate\ndef methodology(year, lang):\n return render_template('%s/%s/methodology.html' % (lang, year))\n\n\n@app.route('///')\n@app.route('///')\n@validate\ndef chapter(year, chapter, lang):\n # TODO: Validate the chapter.\n return render_template('%s/%s/chapters/%s.html' % (lang, year, chapter))\n\n\n@app.errorhandler(400)\ndef bad_request(e):\n logging.exception('An error occurred during a request due to bad request error.')\n return render_template('error/400.html', error=e), 400\n\n\n@app.errorhandler(404)\ndef page_not_found(e):\n logging.exception('An error occurred during a request due to page not found.')\n return render_template('error/404.html', error=e), 404\n\n\n@app.errorhandler(500)\ndef server_error(e):\n logging.exception('An error occurred during a request due to internal server error.')\n return render_template('error/500.html', error=e), 500\n\n\n@app.errorhandler(502)\ndef server_error(e):\n logging.exception('An error occurred during a request due to bad gateway.')\n return render_template('error/502.html', error=e), 502\n\n\nif __name__ == '__main__':\n # This is used when running locally. Gunicorn is used to run the\n # application on Google App Engine. See entrypoint in app.yaml.\n app.run(host='127.0.0.1', port=8080, debug=True)\n","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"34685941","text":"import pandas as pd\n\ndef main():\n '''This function calculates:\n 1- Popular times of travel (month, day of week, hour)\n 2- Trip duration (total travel time, average travel time)\n 3- Popular stations and trip (most common start station, most common end station, most common trip from start to end)\n 4- User info (counts of each user type, counts of each gender, earliest, most recent, and most common year of birth ).'''\n\n \n '''Selecting and filtering inputs and reading data'''\n user_input = ''\n cities = {'1': 'chicago.csv',\n '2':'new_york_city.csv',\n '3':'washington.csv'}\n \n while user_input not in ['1','2','3','4']: \n user_input = input('please select which city you want to run the statistics on:\\n\\\n (type the number of the city)\\n\\\n\\n1 for Chicago\\n\\\n2 for NewYork city\\n\\\n3 for Washington\\n\\\n4 to exit\\n')\n \n if user_input in ['1','2','3']:\n break\n elif user_input == '4':\n return user_input\n while user_input not in ['1','2','3','4']:\n user_input = input('you did not enter a right input.\\nPlease enter\\n\\\n\\n1 for Chicago\\n\\\n2 for NewYork City\\n\\\n3 for Washington \\n\\\n4 to exit')\n if user_input == '4':\n return user_input\n \n data = pd.read_csv(cities[user_input])\n \n def common_time(data):\n '''Common time: getting the most common month, day, hour in which most rentals happened.\n Inputs:\n data: the city the user selected.'''\n \n \n month_dic = {1:'January', 2:'February', 3:'March', 4:'April', 5:'May',\n 6:'June', 7:'July', 8:'August', 9:'Septemper',\n 10:'October', 11:'November', 12:'December'}\n \n dow_dic = {0:'Monday', 1:'Tuesday',2:'Wednesday',3:'Thursday',4:'Friday',5:'Saturday',6:'Sunday'}\n \n hour_dic = {13:'1 Pm', 14:'2 Pm',15:'3 Pm',16:'4 Pm',17:'5 Pm',18:'6 Pm',\n 19:'7 Pm',20:'8 Pm',21:'9 Pm',22:'10 Pm',23:'11 Pm'}\n \n '''Adding the month, day of week, and hour in a seperate series.'''\n \n data['Start Time'] = pd.to_datetime(data['Start Time'])\n time_ser = pd.DataFrame(data['Start Time'])\n time_ser['travel time']= data['Trip Duration']\n time_ser['month'] = data['Start Time'].dt.month\n time_ser['day of week'] = data['Start Time'].dt.weekday\n time_ser['hour'] = data['Start Time'].dt.hour\n \n '''Grouping by month, day of week, and hour in seperate serieses.'''\n \n month = time_ser.groupby(['month']).size()\n month.rename(index=month_dic, inplace = True)\n month_result = 'The common month in which most bike rentals happened in 2017 is: {} \\nand the total rentals in this month is {}\\n\\n'.format(month.idxmax(), month.max()) #get the value of the row of the max column value\n \n day_of_week = time_ser.groupby(['day of week']).size()\n day_of_week.rename(index=dow_dic, inplace = True)\n dow_result = 'The common day of week in which most bike rentals happened during 2017 is: {} \\nand the total rentals in this day is {}\\n\\n'.format(day_of_week.idxmax(), day_of_week.max())\n \n hour = time_ser.groupby(['hour']).size()\n hour.rename(index=hour_dic, inplace = True)\n hour_result ='The common hour in which most bike rentals happened during 2017 is: {} \\nand the total rentals during this hour is {}\\n\\n'.format(hour.idxmax(), hour.max())\n \n print('\\nAnalysis finished!\\n\\nthe results are:\\n{}{}{}'.format(month_result, dow_result, hour_result))\n \n def travel_time(data):\n '''Calculate the total and mean travel time.\n Inputs:\n data: the city the user selected'''\n \n dur_sum = data['travel time'].sum()\n mean = data['travel time'].mean()\n return 'The total travel time during 2017 is {} seconds.\\nThe average travel time during 2017 is {} seconds'.format(dur_sum,mean)\n \n print(travel_time(time_ser))\n \n \n def common_station_trip(data):\n '''Showing the most common start station, end station, and combination of start and end stations for travels.\n Inputs:\n data: the city the user selected'''\n \n start_stat = pd.DataFrame(data['Start Station'])\n start_stat['End Station'] = data['End Station']\n comm_start = start_stat.groupby(['Start Station']).size()\n comm_end = start_stat.groupby(['End Station']).size()\n comm_start_end = start_stat.groupby(['Start Station', 'End Station']).size()\n \n print ('\\nThe most common Start Station during 2017 is {} with {} travels.\\n\\\nThe most common End Station during 2017 is {} with {} travels.'.format(comm_start.idxmax(), comm_start.max(), comm_end.idxmax(), comm_end.max()))\n print('The most common combination of start and end station during 2017 is {} with number of travels of {}'.format(comm_start_end.idxmax(), comm_start_end.max())) \n \n def cst_types_gender(data,user_input):\n '''cst_types_gender calculates the number of each customer type, earliest, recent, and most common birth year.\n Inputs:\n data: the data selected by the user\n user_input: the number corresponding to the data'''\n \n user_info = pd.DataFrame(data['User Type'])\n counts = user_info.groupby(['User Type']).size()\n print('\\nThis city has {} customer types.'.format(len(counts.index)))\n \n for i in counts.index:\n print('There are {} as customer type \"{}\"'.format(counts[i], i))\n \n if user_input != '3':\n gender_type = pd.DataFrame(data['Gender'])\n gender_type = gender_type.groupby(['Gender']).size() \n print('\\nThere are {} who did not enter their Gender type'.format(len(data['Gender'])- gender_type.sum()))\n \n for i in gender_type.index:\n print('There are {} persons as {}'.format(gender_type[i], i))\n \n birth_year = pd.DataFrame(data['Birth Year'])\n birth_year_group = birth_year.groupby(['Birth Year']).size()\n byear_NAN_values = '\\nThere are {} persons who did not enter their birth year'.format(len(data['Birth Year'])- birth_year_group.sum())\n common_year = 'The most common year of birth is {} with {} persons'.format(int(birth_year_group.idxmax()), birth_year_group.max())\n oldest_youngest = 'The earliest Birth Year is {}, while the most recent Birth year is {}'.format(int(birth_year['Birth Year'].min()), int(birth_year['Birth Year'].max()))\n \n return byear_NAN_values, common_year, oldest_youngest\n \n common_time(data)\n common_station_trip(data)\n \n if user_input != '3':\n for i in cst_types_gender(data,user_input):\n print(i)\n else:\n cst_types_gender(data,user_input)\n \n def show_5lines(data):\n '''Showing 5 lines of raw data at a time on user request.\n Inputs:\n data: the city the user selected'''\n \n show_5 = input('Do you want to see the raw data?\\n\\n\\\n type:\\n\\\n 1 for yes\\n\\\n 2 for no\\n')\n n=0\n \n while show_5 == '1':\n print(data.loc[n:n+4, :])\n n+=5\n show_5 = input('continue?\\n\\n\\\n type:\\n\\\n 1 for yes\\n\\\n 2 for no\\n')\n while show_5 not in ['1','2']:\n show_5 = input('you did not enter a right number.\\n\\\n please type:\\n\\\n 1 for yes\\n\\\n 2 for no\\n')\n if show_5 in ['1','2']:\n break\n show_5lines(data)\n \nuser_input = main()\n\nwhile True:\n '''Re-running the analysis or exit on user request.'''\n \n if user_input == '4':\n break\n retry = input('Do you want to rerun the analysis on different city?\\n\\\ntype:\\n\\n\\\n1 for yes\\n\\\n2 to exit\\n')\n if retry == '1':\n user_input = main()\n elif retry == '2':\n break\n else:\n print('You did not enter a correct choice')\n ","sub_path":"bikeshare.py","file_name":"bikeshare.py","file_ext":"py","file_size_in_byte":8203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"570225001","text":"import cv2 as cv\nimport numpy as np\nimport os\nimport math\nfrom matplotlib.pylab import cm\n\ndef visualize_save(test_image, heatmaps, prediction, param, model):\n\tdirectory = '../results/'\n\tif not os.path.exists(directory):\n\t\tos.makedirs(directory)\n\n\tcolormap = cm.jet_r\n\toriImg = cv.imread(test_image)\n\tprediction = prediction.astype(np.int)\n\n\tprefix = os.path.basename(test_image).split('.')[0]\n\tnpart = model['np']\n\n\t# save heatmap superimposed and marked images\n\tfor c in range(heatmaps.shape[2]):\n\t\tcolorized = colormap(heatmaps[:,:,c])\n\t\timg_superimposed = (colorized[:,:,0:3] * 255 + oriImg)/2\n\t\timg_superimposed = img_superimposed.astype(np.uint8)\n\t\t#print img_superimposed\n\t\tif c != npart:\n\t\t\timg_superimposed = drawCross(img_superimposed, prediction[c])\n\t\tcv.imwrite('%s/%s_heatmap%d.png' % (directory, prefix, c+1), img_superimposed)\n\n\t# draw limbs\n\tlimbs = model['limbs']\n\tcolormap = cm.get_cmap('hsv_r')\n\tfacealpha = 0.6\n\n\tbodyHeight = np.max(prediction[:,0]) - np.min(prediction[:,0])\n\tstickwidth = oriImg.shape[0]/30.0\n\tthre = 0.05\n\n\timg_stickman = oriImg.copy()\n\tfor p in range(limbs.shape[0]):\n\t\tx1 = prediction[limbs[p,0]-1, 0]\n\t\ty1 = prediction[limbs[p,0]-1, 1]\n\t\tif heatmaps[x1,y1,limbs[p,0]-1] < thre:\n\t\t\tcontinue\n\t\tx2 = prediction[limbs[p,1]-1, 0]\n\t\ty2 = prediction[limbs[p,1]-1, 1]\n\t\tif heatmaps[x2,y2,limbs[p,1]-1] < thre:\n\t\t\tcontinue\n\n\t\tX = prediction[limbs[p,:]-1, 0]\n\t\tY = prediction[limbs[p,:]-1, 1]\n\t\tmX = np.mean(X)\n\t\tmY = np.mean(Y)\n\t\tlength = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5\n\t\tif Y[0] - Y[1] == 0:\n\t\t\tangle = 90\n\t\telse:\n\t\t\tangle = math.degrees(math.atan(float(X[0] - X[1]) / float(Y[0] - Y[1])))\n\t\tpolygon = cv.ellipse2Poly((int(mY),int(mX)), (int(length/2), int(stickwidth)), int(angle), 0, 360, 1)\n\t\tcolor = [x * 255 for x in list(colormap(float(p)/limbs.shape[0]))]\n\t\tcolor = tuple(color[0:3])\n\t\tcv.fillConvexPoly(img_stickman, polygon, color)\n\t\t\n\tfor c in range(heatmaps.shape[2]-1):\n\t\timg_stickman = drawDot(img_stickman, prediction[c])\n\n\tcv.addWeighted(img_stickman, facealpha, oriImg, 1 - facealpha, 0, img_stickman)\n\tcv.imwrite('%s/%s_stickman.png' % (directory, prefix), img_stickman)\n\ndef drawCross(img, center):\n\toffset = 3\n\tthick = 2\n\tcv.line(img, (center[1]-offset, center[0]-offset), (center[1]+offset, center[0]+offset), (255,255,255), thick)\n\tcv.line(img, (center[1]-offset, center[0]+offset), (center[1]+offset, center[0]-offset), (255,255,255), thick)\n\treturn img\n\ndef drawDot(img, center):\n\tradius = 3\n\tcv.circle(img, (center[1], center[0]), radius, (0, 0, 0), -1)\n\treturn img\n\n# function h = filledellipse(A,xc,col,facealpha)\n# [V,D] = eig(A);\n# % define points on a unit circle\n# th = linspace(0, 2*pi, 50);\n# pc = [cos(th);sin(th)];\n\n# % warp it into the ellipse\n# pe = sqrtm(A)*pc;\n# pe = bsxfun(@plus, xc(:), pe);\n# h = patch(pe(1,:),pe(2,:),col);\n# set(h,'FaceAlpha',facealpha);\n# set(h,'EdgeAlpha',0);","sub_path":"testing/src/visualize_save.py","file_name":"visualize_save.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"162505881","text":"# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nimport os\nimport signal\nimport time\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, Optional\n\nimport numpy as np\n\n\ndef pad_to_size(\n x: np.array, size: int, axis: int = 0, is_right_pad: bool = True\n):\n \"\"\"Pads `xs` with 0 on the right (default) on the specified axis, which is the first axis by default.\"\"\"\n pad_length = size - x.shape[axis]\n if pad_length <= 0:\n return x\n\n pad_width = [(0, 0)] * x.ndim\n right_pad = (0, pad_length)\n pad_width[axis] = right_pad if is_right_pad else right_pad[::-1]\n return np.pad(x, mode=\"constant\", pad_width=pad_width)\n\n\nclass Timer:\n \"\"\"Context manager for measuring the time of enclosed code fragments.\"\"\"\n\n def __enter__(self):\n self.start = time.perf_counter()\n self.interval = None\n return self\n\n def __exit__(self, *args):\n self.end = time.perf_counter()\n self.interval = self.end - self.start\n\n\nclass SignalHandler:\n \"\"\"\n A context manager that attaches a set of signal handlers within its scope.\n\n Parameters\n ----------\n handlers_map\n A dictionary mapping signal numbers to associated signal handlers to\n be attached within the scope of the enclosing `SignalHandler` instance.\n \"\"\"\n\n Callback = Optional[Callable[[int, Any], None]]\n\n def __init__(self, handlers_map: Dict[int, Callback]) -> None:\n self.handlers_map = handlers_map\n\n def __enter__(self):\n self.default_handlers = {\n s: signal.signal(s, h) for s, h in self.handlers_map.items()\n }\n return self\n\n def __exit__(self, *args):\n for s, h in self.default_handlers.items():\n signal.signal(s, h)\n\n\ndef maybe_len(obj) -> Optional[int]:\n try:\n return len(obj)\n except (NotImplementedError, AttributeError):\n return None\n\n\ndef get_download_path() -> Path:\n \"\"\"\n\n Returns\n -------\n Path\n default path to download datasets or models of gluon-ts.\n The path is either $MXNET_HOME if the environment variable is defined or\n /home/username/.mxnet/gluon-ts/\n \"\"\"\n return Path(\n os.environ.get(\"MXNET_HOME\", str(Path.home() / \".mxnet\" / \"gluon-ts\"))\n )\n\n\ndef map_dct_values(fn: Callable, dct: dict) -> dict:\n \"\"\"Maps `fn` over a dicts values.\"\"\"\n return {key: fn(value) for key, value in dct.items()}\n\n\ndef erf(x: np.array) -> np.array:\n # Using numerical recipes approximation for erf function\n # accurate to 1E-7\n\n ones = np.ones_like(x)\n zeros = np.zeros_like(x)\n\n t = ones / (ones + 0.5 * np.abs(x))\n\n coefficients = [\n 1.00002368,\n 0.37409196,\n 0.09678418,\n -0.18628806,\n 0.27886807,\n -1.13520398,\n 1.48851587,\n -0.82215223,\n 0.17087277,\n ]\n\n inner = zeros\n for c in coefficients[::-1]:\n inner = t * (c + inner)\n\n res = ones - t * np.exp((inner - 1.26551223 - np.square(x)))\n return np.where(x >= zeros, res, -1.0 * res)\n\n\ndef erfinv(x: np.array) -> np.array:\n zeros = np.zeros_like(x)\n\n w = -np.log((1.0 - x) * (1.0 + x))\n mask_lesser = w < (zeros + 5.0)\n\n w = np.where(mask_lesser, w - 2.5, np.sqrt(w) - 3.0)\n\n coefficients_lesser = [\n 2.81022636e-08,\n 3.43273939e-07,\n -3.5233877e-06,\n -4.39150654e-06,\n 0.00021858087,\n -0.00125372503,\n -0.00417768164,\n 0.246640727,\n 1.50140941,\n ]\n\n coefficients_greater_equal = [\n -0.000200214257,\n 0.000100950558,\n 0.00134934322,\n -0.00367342844,\n 0.00573950773,\n -0.0076224613,\n 0.00943887047,\n 1.00167406,\n 2.83297682,\n ]\n\n p = np.where(\n mask_lesser,\n coefficients_lesser[0] + zeros,\n coefficients_greater_equal[0] + zeros,\n )\n\n for c_l, c_ge in zip(\n coefficients_lesser[1:], coefficients_greater_equal[1:]\n ):\n c = np.where(mask_lesser, c_l + zeros, c_ge + zeros)\n p = c + p * w\n\n return p * x\n\n\nclass Interpolation:\n \"\"\"\n Interpolation based on trained quantile predictions\n\n Parameters\n ----------\n quantile_predictions\n Dict with key = str(quantile) and value is np.array with size prediction_length\n interpolation_type\n\n \"\"\"\n\n def __init__(\n self, quantile_predictions: dict, interpolation_type: str = \"linear\"\n ):\n self.quantile_predictions = quantile_predictions\n self.quantiles = sorted(map(float, self.quantile_predictions))\n self.num_quantiles = len(self.quantile_predictions)\n self.interpolation_type = interpolation_type\n\n def __call__(self, inference_quantile):\n if self.interpolation_type == \"linear\":\n return self.linear_interpolation(inference_quantile)\n else:\n raise NotImplementedError(\n f\"unknown interpolation type {self.interpolation_type}\"\n )\n\n def linear_interpolation(self, inference_quantile: float):\n \"\"\"\n If inference quantile is out of interpolation range,\n return smallest or largest value.\n Otherwise, find two nearest points [q_1, x_1], [q_2, x_2] and\n return its linear interpolation\n x = (q_2 - q)/(q_2 - q_1) * x_1 + (q - q_1)/(q_2 - q_1) * x_2.\n\n\n Returns\n -------\n same type and shape as any value of quantile_predictions dict,\n i.e., type=np.array, shape = (prediction_length, )\n\n \"\"\"\n if self.quantiles[0] >= inference_quantile:\n return self.quantile_predictions[str(self.quantiles[0])]\n elif self.quantiles[-1] <= inference_quantile:\n return self.quantile_predictions[str(self.quantiles[-1])]\n else:\n for (current_quantile, next_quantile) in zip(\n self.quantiles, self.quantiles[1:]\n ):\n if (\n current_quantile <= inference_quantile\n and inference_quantile < next_quantile\n ):\n weights = [\n (next_quantile - inference_quantile)\n / (next_quantile - current_quantile),\n (inference_quantile - current_quantile)\n / (next_quantile - current_quantile),\n ]\n return (\n weights[0]\n * self.quantile_predictions[str(current_quantile)]\n + weights[1]\n * self.quantile_predictions[str(next_quantile)]\n )\n\n\nclass TailApproximation:\n \"\"\"\n Apporoximate quantile function on tails based on trained quantile predictions\n and make a inference on query point.\n Can be used for either interpolation or extrapolation on tails\n\n Parameters\n ----------\n quantile_predictions\n Dict with key = str(quantile) and value is np.array with size prediction_length\n approximation_type\n str of tail approximation type\n\n \"\"\"\n\n def __init__(\n self,\n quantile_predictions: dict,\n approximation_type: str = \"exponential\",\n tol: float = 1e-8,\n ):\n self.quantile_predictions = quantile_predictions\n self.quantiles = sorted(map(float, self.quantile_predictions))\n self.num_quantiles = len(self.quantile_predictions)\n self.approximation_type = (\n approximation_type if self.num_quantiles > 1 else None\n )\n self.tol = tol\n if not self.approximation_type:\n pass\n elif self.approximation_type == \"exponential\":\n self.init_exponential_tail_weights()\n self.tail_function_left = self.exponential_tail_left\n self.tail_function_right = self.exponential_tail_right\n else:\n raise NotImplementedError(\n f\"unknown approximation type {self.approximation_type}\"\n )\n\n def left(self, inference_quantile: float):\n \"\"\"\n Call left tail approximation\n\n Parameters\n -------\n inference_quantile\n float\n\n Returns\n -------\n same type and shape as any value of quantile_predictions dict,\n i.e., type=np.array, shape = (prediction_length, )\n \"\"\"\n if not self.approximation_type:\n return self.quantile_predictions[str(self.quantiles[0])]\n else:\n return self.tail_function_left(inference_quantile)\n\n def right(self, inference_quantile: float):\n \"\"\"\n Call right tail approximation\n\n Parameters\n -------\n inference_quantile\n float\n\n Returns\n -------\n same type and shape as any value of quantile_predictions dict,\n i.e., type=np.array, shape = (prediction_length, )\n \"\"\"\n if not self.approximation_type:\n return self.quantile_predictions[str(self.quantiles[-1])]\n else:\n return self.tail_function_right(inference_quantile)\n\n def init_exponential_tail_weights(self):\n \"\"\"\n Initialize the weight of exponentially decaying tail functions\n based on two extreme points on the left and right respectively\n \"\"\"\n assert (\n self.num_quantiles >= 2\n ), \"Need at least two predicted quantiles for exponential approximation\"\n q_log_diff = np.log(\n (self.quantiles[1] + self.tol) / (self.quantiles[0] + self.tol)\n + self.tol\n )\n x_diff = (\n self.quantile_predictions[str(self.quantiles[1])]\n - self.quantile_predictions[str(self.quantiles[0])]\n )\n self.beta_inv_left = x_diff / q_log_diff\n\n z_log_diff = np.log(\n (1 - self.quantiles[-2] + self.tol)\n / (1 - self.quantiles[-1] + self.tol)\n + self.tol\n ) # z = 1/(1-q)\n x_diff = (\n self.quantile_predictions[str(self.quantiles[-1])]\n - self.quantile_predictions[str(self.quantiles[-2])]\n )\n self.beta_inv_right = x_diff / z_log_diff\n\n def exponential_tail_left(self, inference_quantile: float):\n \"\"\"\n Return the inference made on exponentially decaying tail functions\n For left tail, x = exp(beta * (q - alpha))\n For right tail, x = 1 - exp(-beta * (q - alpha))\n\n E.g. for inference_quantile = self.quantiles[0] or self.quantiles[1] ,\n return value is exactly self.quantile_predictions[str(self.quantiles[0])]\n or self.quantile_predictions[str(self.quantiles[1])] respectively.\n\n \"\"\"\n return (\n self.beta_inv_left\n * np.log(\n (inference_quantile + self.tol)\n / (self.quantiles[1] + self.tol)\n + self.tol\n )\n ) + self.quantile_predictions[str(self.quantiles[1])]\n\n def exponential_tail_right(self, inference_quantile: float):\n \"\"\"\n Return the inference made on exponentially decaying tail functions\n For left tail, x = exp(beta * (q - alpha))\n For right tail, x = 1 - exp(-beta * (q - alpha))\n\n E.g. for inference_quantile = self.quantiles[-1] or self.quantiles[-2] ,\n return value is exactly self.quantile_predictions[str(self.quantiles[-1])]\n or self.quantile_predictions[str(self.quantiles[-2])] respectively.\n \"\"\"\n return (\n self.beta_inv_right\n * np.log(\n (1 - self.quantiles[-2] + self.tol)\n / (1 - inference_quantile + self.tol)\n + self.tol\n )\n ) + self.quantile_predictions[str(self.quantiles[-2])]\n\n def tail_range(\n self, default_left_tail_quantile=0.1, default_right_tail_quantile=0.9\n ):\n \"\"\"\n Return an effective range of left and right tails\n\n \"\"\"\n if self.approximation_type == \"exponential\":\n left_tail_quantile = max(\n self.quantiles[0],\n min(self.quantiles[1], default_left_tail_quantile),\n )\n right_tail_quantile = min(\n self.quantiles[-1],\n max(self.quantiles[-2], default_right_tail_quantile),\n )\n else:\n (left_tail_quantile, right_tail_quantile) = (\n default_left_tail_quantile,\n default_right_tail_quantile,\n )\n return (left_tail_quantile, right_tail_quantile)\n","sub_path":"src/gluonts/support/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":13010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"215916139","text":"import sys \nfrom Bio import SeqIO \n\ndef usage(): \n\tprint(\"usage : python3 exclude_chimeras.py \")\n\tprint(\"--\") \n\tprint(\"This script delete chimeras sequences produces by sequencing simulation for FROGS synthetic dataset (from SILVA)\")\n\tprint(\"Datasets : http://frogs.toulouse.inra.fr/data_to_test_frogs/\") \n\t\nif len(sys.argv)!=3: \n\tusage() \n\texit() \n\t\nfastq_out=open(sys.argv[2],\"w\") \t\nfor record in SeqIO.parse(sys.argv[1],\"fastq\"): \n\tif \"description\" in record.description: \n\t\tSeqIO.write(record,fastq_out,\"fastq\") \nfastq_out.close() \t\t\n\t\t\n\t\t\n","sub_path":"bin/exclude_chimeras.py","file_name":"exclude_chimeras.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"221795197","text":"from random import randint\n\nscore = 0\n\nfor i in range(5):\n comp_guess = randint(1, 10)\n user_guess = eval(input('Enter guess between 1 and 10: '))\n while user_guess < 0 or user_guess > 10:\n user_guess = eval(input('Invalid. Enter guess between 1 and 10: '))\n continue\n if user_guess == comp_guess:\n score += 10\n print(f'You guessed right! Your score is {score}.')\n else:\n score -= 1\n print(f'Wrong. Computer guessed {comp_guess}. You guessed {user_guess}.')\nprint(f'\\nAfter 5 rounds, your total score is {score}.')\n","sub_path":"Chapter 5 Exercise/Q_12.py","file_name":"Q_12.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"310991360","text":"import imaplib\n\nimport bs4\n\n\ndef read():\n mail = imaplib.IMAP4_SSL('imap.gmail.com')\n mail.login('', '')\n mail.list()\n # Out: list of \"folders\" aka labels in gmail.\n mail.select(\"inbox\") # connect to inbox.\n try:\n typ, [data] = mail.search(None, 'TO', 'MelissaHanson948@xgmmx.co')\n for num in data.split():\n typ, msg_data = mail.fetch(num, '(BODY.PEEK[TEXT])')\n for response_part in msg_data:\n if isinstance(response_part, tuple):\n code = str(response_part[1])\n soup = bs4.BeautifulSoup(code, 'lxml')\n print(soup)\n except Exception as e:\n print(str(e))\n\n\nread()\n","sub_path":"Desktop/Breaker-Raffle/dev/test_tres-bien.py","file_name":"test_tres-bien.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"96666372","text":"from turtle import Turtle\n\nclass ScoreBoard(Turtle):\n def __init__(self):\n super().__init__()\n self.color(\"white\")\n self.penup()\n self.hideturtle()\n self.left_score = 0\n self.right_score = 0\n self.goto(-90, 200)\n self.write(self.left_score, font=(\"Courier\", 80, \"normal\"))\n self.goto(25, 200)\n self.write(self.right_score, font=(\"Courier\", 80, \"normal\"))\n self.getscreen().update()\n\n def update_scoreboard(self):\n self.clear()\n self.goto(-90, 200)\n self.write(self.left_score, font=(\"Courier\", 80, \"normal\"))\n self.goto(25, 200)\n self.write(self.right_score, font=(\"Courier\", 80, \"normal\"))\n\n def increment_left_score(self):\n self.left_score += 1\n self.update_scoreboard()\n\n def increment_right_score(self):\n self.right_score += 1\n self.update_scoreboard()\n","sub_path":"PaddleBallGame/scoreboard.py","file_name":"scoreboard.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"192593188","text":"#!/usr/bin/scons\n\nenv = Environment(platform=\"win32\", MSVS=\"12.0\")\n\nCCFLAGS = [\n \"-Iinclude\"\n]\n\nsource = [\n \"src/thread.c\"\n]\n\nlibthread = env.StaticLibrary(source=source, target=\"thread\", CCFLAGS=CCFLAGS)\n\ntest = env.Program(source=\"test.c\", CCFLAGS=CCFLAGS, LIBS=[libthread])\n\nDefault([libthread, test])\n","sub_path":"SConstruct","file_name":"SConstruct","file_ext":"","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"3270066","text":"from unittest import TestCase\nimport textwrap\n\nimport hjson as json\nfrom hjson.compat import StringIO\n\nclass TestIndent(TestCase):\n def test_indent(self):\n h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh',\n 'i-vhbjkhnth',\n {'nifty': 87}, {'field': 'yes', 'morefield': False} ]\n\n expect = textwrap.dedent(\"\"\"\\\n [\n \\t[\n \\t\\t\"blorpie\"\n \\t],\n \\t[\n \\t\\t\"whoops\"\n \\t],\n \\t[],\n \\t\"d-shtaeou\",\n \\t\"d-nthiouh\",\n \\t\"i-vhbjkhnth\",\n \\t{\n \\t\\t\"nifty\": 87\n \\t},\n \\t{\n \\t\\t\"field\": \"yes\",\n \\t\\t\"morefield\": false\n \\t}\n ]\"\"\")\n\n\n d1 = json.dumpsJSON(h)\n d2 = json.dumpsJSON(h, indent='\\t', sort_keys=True, separators=(',', ': '))\n d3 = json.dumpsJSON(h, indent=' ', sort_keys=True, separators=(',', ': '))\n d4 = json.dumpsJSON(h, indent=2, sort_keys=True, separators=(',', ': '))\n\n h1 = json.loads(d1)\n h2 = json.loads(d2)\n h3 = json.loads(d3)\n h4 = json.loads(d4)\n\n self.assertEqual(h1, h)\n self.assertEqual(h2, h)\n self.assertEqual(h3, h)\n self.assertEqual(h4, h)\n self.assertEqual(d3, expect.replace('\\t', ' '))\n self.assertEqual(d4, expect.replace('\\t', ' '))\n # NOTE: Python 2.4 textwrap.dedent converts tabs to spaces,\n # so the following is expected to fail. Python 2.4 is not a\n # supported platform in hjson 2.1.0+.\n self.assertEqual(d2, expect)\n\n def test_indent0(self):\n h = {3: 1}\n def check(indent, expected):\n d1 = json.dumpsJSON(h, indent=indent)\n self.assertEqual(d1, expected)\n\n sio = StringIO()\n json.dumpJSON(h, sio, indent=indent)\n self.assertEqual(sio.getvalue(), expected)\n\n # indent=0 should emit newlines\n check(0, '{\\n\"3\": 1\\n}')\n # indent=None is more compact\n check(None, '{\"3\": 1}')\n\n def test_separators(self):\n lst = [1,2,3,4]\n expect = '[\\n1,\\n2,\\n3,\\n4\\n]'\n expect_spaces = '[\\n1, \\n2, \\n3, \\n4\\n]'\n # Ensure that separators still works\n self.assertEqual(\n expect_spaces,\n json.dumpsJSON(lst, indent=0, separators=(', ', ': ')))\n # Force the new defaults\n self.assertEqual(\n expect,\n json.dumpsJSON(lst, indent=0, separators=(',', ': ')))\n # Added in 2.1.4\n self.assertEqual(\n expect,\n json.dumpsJSON(lst, indent=0))\n","sub_path":"modules/dbnd/src/dbnd/_vendor/hjson/tests/test_indent.py","file_name":"test_indent.py","file_ext":"py","file_size_in_byte":2589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"631477010","text":"# бот погоды v 2.0\n\nimport pyowm\nimport telebot\n\nowm = pyowm.OWM( '1497f11e6aaf6ebabe90829f6d47a0bf', language = \"ru\" )\nbot = telebot.TeleBot( \"1080076453:AAHr8DbGWLER1w6jObvFOiVeweJzhzTLAr8\" )\n\n@bot.message_handler( content_types=['text'] )\ndef send_echo( message ):\n observation = owm.weather_at_place( message.text )\n w = observation.get_weather()\n temp = w.get_temperature( 'celsius' )[\"temp\"]\n answer = \"В городе \" + message.text + \" сейчас \" + w.get_detailed_status() + \"\\n\"\n answer += \"Температура где-то \" + str(temp) + \" градусов!\" + \"\\n\\n\"\n \n if temp < 5:\n answer += \"Снаружи дикий дубак, завернись поплотнее...\"\n elif temp < 10:\n answer += \"Еще чуть-чуть и будет тепло! От зимнего пальто не стоит избавляться.\"\n elif temp < 20:\n answer += \"Погода просто топ - легкая куртка и кроссы будут кстати.\"\n else:\n answer += \"Почти жара... Куртку можно оставить дома :)\"\n\n bot.send_message( message.chat.id, answer )\n\nbot.polling( none_stop = True )\n","sub_path":"WeatherTeleBot.py","file_name":"WeatherTeleBot.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"291315968","text":"# coding=utf-8\n\"\"\"\ntitle: \nauthor: cero\nCreate on: 2018/4/27\n\"\"\"\nimport scrapy\nfrom cero_spiders.items import WeixinSogouItem\n\n\nclass WeixinSogouSpider(scrapy.Spider):\n name = 'WeixinSogou'\n\n start_urls = [\n 'http://weixin.sogou.com/weixin?type=2&s_from=input&query=%E5%85%A5%E7%BE%A4&ie=utf8&_sug_=n&_sug_type_=&w=01019900&sut=3389&sst0=1524878374117&lkt=1%2C1524878374013%2C1524878374013'\n ]\n\n def parse(self, response):\n for box in response.css('.txt-box'):\n article = box.css('a::attr(href)').extract_first()\n if article:\n yield scrapy.Request(article, callback=self.parse_article)\n\n next_page = response.css('#sogou_next').css('a::attr(href)').extract_first()\n if next_page:\n yield scrapy.Request(response.urljoin(next_page), callback=self.parse)\n\n def parse_article(self, response):\n item = WeixinSogouItem()\n item['title'] = response.css('.rich_media_title').css('h2::text').extract_first()\n item['image_urls'] = response.css('img::attr(data-src)').extract()\n yield item\n","sub_path":"cero_spiders/spiders/weixin_sougou_spider.py","file_name":"weixin_sougou_spider.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"291256055","text":"\"\"\"\n Hello world `receive.py` example implementation using aioamqp.\n See the documentation for more informations.\n\"\"\"\n# import xmltools\nimport asyncio\nimport aioamqp\nimport sqlite3\nimport json\nimport string\nimport csv\nimport dicttoxml\nimport itertools\nfrom xlsxwriter.workbook import Workbook\n\ndef dictfetchall(cursor):\n desc = cursor.description\n return [dict(itertools.izip([col[0] for col in desc], row))\n for row in cursor.fetchall()]\n\n@asyncio.coroutine\ndef callback(channel, body, envelope, properties):\n print(\" [x] Received %r\" % body)\n path=body.decode().split(\" \")[0]\n type=body.decode().split(\" \")[1]\n conn = sqlite3.connect(path)\n c = conn.cursor()\n fd = open('C:\\\\Users\\\\Cameras\\\\Desktop\\\\aioamqp-0.11.0\\\\sql.sql', 'r')\n sqlFile = fd.read()\n fd.close()\n sqlCommands = sqlFile.split(';')\n f= open('C:\\\\Users\\\\Cameras\\\\Desktop\\\\test.'+type,'w+')\n if type=='json':\n for command in sqlCommands:\n rows=c.execute(command).fetchall()\n if not c.description:\n columns = []\n else:\n column = [t[0] for t in c.description]\n for row in rows:\n json_dict = {}\n for j in range(len(column)):\n key_j = column[j]\n json_dict[key_j] = row[j]\n f.write(json.dumps(json_dict, indent=3))\n conn.close()\n elif type=='xml':\n for command in sqlCommands:\n rows=c.execute(command).fetchall()\n if not c.description:\n columns = []\n else:\n column = [t[0] for t in c.description]\n for row in rows:\n json_dict = {}\n for j in range(len(column)):\n key_j = column[j]\n json_dict[key_j] = row[j]\n xml=dicttoxml.dicttoxml(json_dict, attr_type=False)\n f.write(str(xml))\n conn.close()\n elif type=='csv':\n workbook = Workbook('C:\\\\Users\\\\Cameras\\\\Desktop\\\\test.csv')\n worksheet = workbook.add_worksheet()\n for command in sqlCommands:\n rows=c.execute(command)\n for i, row in enumerate(rows):\n for j, value in enumerate(row):\n worksheet.write(i,j,value)\n workbook.close()\n conn.close()\n\n f.close()\n\n\n@asyncio.coroutine\ndef receive():\n transport, protocol = yield from aioamqp.connect()\n channel = yield from protocol.channel()\n\n yield from channel.queue_declare(queue_name='b')\n\n yield from channel.basic_consume(callback, queue_name='b')\n\n\nevent_loop = asyncio.get_event_loop()\nevent_loop.run_until_complete(receive())\nevent_loop.run_forever()\n","sub_path":"aioamqp-0.11.0/examples/receive.py","file_name":"receive.py","file_ext":"py","file_size_in_byte":2737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"549173840","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: /root/singa_auto/param_store/file.py\n# Compiled at: 2020-04-23 12:22:03\n# Size of source mod 2**32: 1907 bytes\nimport os, uuid\nfrom .param_store import ParamStore, Params\n\nclass FileParamStore(ParamStore):\n __doc__ = '\\n Stores parameters in the local filesystem.\\n '\n\n def __init__(self, params_dir=None):\n self._params_dir = params_dir or os.path.join(os.environ['WORKDIR_PATH'], os.environ['PARAMS_DIR_PATH'])\n\n def save(self, params: Params):\n file_name = '{}.model'.format(uuid.uuid4())\n dest_file_path = os.path.join(self._params_dir, file_name)\n params_bytes = self._serialize_params(params)\n with open(dest_file_path, 'wb') as (f):\n f.write(params_bytes)\n params_id = file_name\n return params_id\n\n def load(self, params_id):\n file_name = params_id\n file_path = os.path.join(self._params_dir, file_name)\n with open(file_path, 'rb') as (f):\n params_bytes = f.read()\n params = self._deserialize_params(params_bytes)\n return params","sub_path":"pycfiles/singa_auto-0.2.0-py2.py3-none-any/file.cpython-36.py","file_name":"file.cpython-36.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"480948827","text":"from __future__ import print_function\r\nfrom googleapiclient.http import MediaIoBaseDownload\r\nimport io\r\nimport os\r\n\r\ndef download(file, service): \r\n \r\n directory = os.getcwd()\r\n filename = directory + \"\\\\media\\\\sermon_in.mp3\"\r\n \r\n file_id = file['id']\r\n request = service.files().get_media(fileId=file_id)\r\n \r\n fh = open(filename, 'wb')\r\n \r\n print(\"\\nDownloading...\")\r\n downloader = MediaIoBaseDownload(fh, request)\r\n done = False\r\n while done is False:\r\n status, done = downloader.next_chunk()\r\n print(\"Download %d%%.\" % int(status.progress() * 100) ) \r\n ","sub_path":"drive_download.py","file_name":"drive_download.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"525505395","text":"import unittest\n\nfrom pages.chat_page import ChatPage\nfrom pages.vacancies_page import VacanciesPage\nfrom pages.vacancy_page import VacancyPage\nfrom scenario.auth import auth_as_employer_has_comp\nfrom tests.default_setup import default_setup\n\n\nclass ChatRightSide(unittest.TestCase):\n\n def setUp(self) -> None:\n default_setup(self)\n self.TEST_MSG = \"привет2\"\n self.TEST_MSG2 = \"привет\"\n self.vacanciesPage = VacanciesPage(self.driver)\n self.vacancyPage = VacancyPage(self.driver)\n self.chatPage = ChatPage(self.driver)\n\n def test_send_by_button(self):\n auth_as_employer_has_comp(self)\n self.chatPage.open()\n self.chatPage.click_on_another_chat(0)\n self.chatPage.click_on_send_msg(self.TEST_MSG)\n text = self.chatPage.get_last_msg()\n self.assertEqual(text,self.TEST_MSG)\n self.chatPage.click_on_send_msg_by_enter(self.TEST_MSG2)\n text1 = self.chatPage.get_last_msg()\n self.assertEqual(text1, self.TEST_MSG2)\n\n def tearDown(self):\n self.driver.quit()\n","sub_path":"tests/other/chat_rightside.py","file_name":"chat_rightside.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"117059233","text":"import pyod\nfrom pyod.models.lscp import LSCP\nimport pandas as pd\nimport numpy as np\nimport sys\nimport os\nsys.path.append('./..')\nsys.path.append('./../..')\nimport yaml\nimport matplotlib.pyplot as plt\nimport math\nfrom tqdm import tqdm\nfrom pprint import pprint\nfrom collections import OrderedDict\nfrom time import time\nfrom datetime import datetime\nfrom pathlib import Path\nimport multiprocessing\nimport yaml\nimport logging\nimport logging.handlers\nfrom time import time\nfrom datetime import datetime\ntry:\n from . import data_fetcher_custom\nexcept:\n import data_fetcher_custom\n\ndef get_logger(LOG_FILE):\n logger = logging.getLogger('main')\n logger.setLevel(logging.INFO)\n OP_DIR = os.path.join('Logs')\n\n if not os.path.exists(OP_DIR):\n os.mkdir(OP_DIR)\n\n handler = logging.FileHandler(os.path.join(OP_DIR, LOG_FILE))\n handler.setLevel(logging.INFO)\n logger.addHandler(handler)\n logger.info('Log start :: ' + str(datetime.now()))\n return logger\n\ndef log_time(logger):\n logger.info(str(datetime.now()) + '| Time stamp ' + str(time()))\n\ndef close_logger(logger):\n handlers = logger.handlers[:]\n for handler in handlers:\n handler.close()\n logger.removeHandler(handler)\n logging.shutdown()\n return\n\ndef create_config(\n data_set,\n):\n _, _ , data_dict, meta_data_df = data_fetcher_custom.get_data(\n data_set,\n anomaly_ratio=0.01\n )\n\n config_file = 'architecture_config.yaml'\n\n with open(config_file, 'r') as fh:\n config = yaml.safe_load(fh)\n config = config[data_set]\n latent_dim = config['ae_latent_dimension']\n\n # discrete_columns : { column_name : num_categories }\n discrete_dims = OrderedDict({k: v for k, v in zip(list(meta_data_df['column']), list(meta_data_df['dimension']))})\n num_discrete_columns = len(discrete_dims)\n count_discrete_dims = 0\n for val in discrete_dims.values():\n if val == 2:\n count_discrete_dims += 1\n else:\n count_discrete_dims += val\n\n real_dims = data_dict['train'].shape[-1] - count_discrete_dims\n\n # ---------------\n # encoder_structure_config['ip_layers']\n # Format :\n # [ 'emb|onehot', num_categories, [ embedding dimension ]\n # ---------------\n encoder_structure_config = {\n 'real_dims': real_dims,\n 'discrete_dims': discrete_dims,\n 'encoder_FCN_to_latent': config['encoder_FCN_to_latent'],\n 'ae_latent_dimension': config['ae_latent_dimension'],\n 'encoder_discrete_xform': config['encoder_discrete_xform'],\n 'encoder_real_xform': config['encoder_real_xform']\n }\n\n # ======================================================\n # Set decoder structure\n # =========\n\n decoder_structure_config = {\n 'real_dims': real_dims,\n 'discrete_dims': discrete_dims,\n 'decoder_FC_from_latent': config['decoder_FC_from_latent'],\n 'decoder_discrete_xform': config['decoder_discrete_xform'],\n 'decoder_real_xform': config['decoder_real_xform'],\n 'ae_latent_dimension': config['ae_latent_dimension']\n }\n\n # ================\n # Format decoder_field_layers:\n # { idx : [[dim1,dim2], op_activation ]\n # ================\n loss_structure_config = {\n 'discrete_dims': discrete_dims,\n 'real_loss_func': config['real_loss_func'],\n 'real_dims': real_dims\n }\n\n return encoder_structure_config, decoder_structure_config, loss_structure_config, latent_dim\n","sub_path":"Deprecated/AnalysisCorruption/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"35430320","text":"#__author__ = 'tarnold 06/07/2016'\n\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtCore import (Qt, pyqtSignal)\nfrom GUI_Library.MPParser_UI_R16 import *\nfrom configparser import ConfigParser\nimport glob\nimport time,sys,datetime,re,os,pytest,subprocess\nfrom sys import exit\nimport getpass\nfrom collections import OrderedDict\nfrom pyparsing import Literal, Word, Group, Dict, ZeroOrMore, alphas, nums, delimitedList\nimport string\nfrom GUI_Library.MPParser_UI_R12_rc import *\nfrom Parse_Library.MPP_Model_Misc302 import ParseFile\nfrom Parse_Library.MPP_Model_Pin302 import ParsePinFile\nfrom Parse_Library.MPP_Model_Bin302 import ParseBinFile\nfrom Parse_Library.MPP_Model_TestFlow314 import ParseTestFlowFile\nfrom Parse_Library.MPP_Model_Levels302 import ParseLevelsFile\nfrom Parse_Library.MPP_Model_Specs import ParseSpecsFile\nfrom Parse_Library.MPP_Model_TestGroup303 import ParseTestGroupFile\nfrom Parse_Library.MPP_Model_Timing304 import ParseTimingFile\nimport os.path\nimport getpass\nfrom contextlib import contextmanager\nimport zerorpc\nimport psutil\nfrom subprocess import Popen, PIPE\nsize = 10000\nProgramVersion = '2.1'\nCurrentReleaseDate = ' Sept. 20, 2017'\nflowArrayData = [[\"INDEX\",\"SEQ_TABLE\",\"TEST_MACRO\",\"TEST_BLOCK\",\"PORT0_PASS\",\"PORT1_FAIL\",\"SUB_ROUTINE\",\"TEST_NO\",\"LABEL\"]]\ntindex = 0\nindex=0\nwaveTableOpen = False\nuser = getpass.getuser()\n\nspecTopline=True\nuser = getpass.getuser()\ntopline=True\npinGroupArray=[]\npinGroupDict={}\nallPinGroups=[]\nBinNoDict={}\nmaxBinNo=0\ntestBinList=[]\nupdateBinNoDict={}\nif (sys.platform == \"win32\"):\n dirSeperator = \"\\\\\"\n pdfCommand = ''\n userpath_Default = \"C:/Users/%s/Desktop/\" % user\n userpath = \"C:/Users/%s/Desktop/MPP_Out/\" % user\nelif (sys.platform == \"linux\"):\n dirSeperator = \"/\"\n pdfCommand = 'acroread '\n userpath_Default = os.getcwd()\n userpath = os.getcwd()+\"/MPP_Out/\"\nelse:\n dirSeperator = \"\\\\\"\n pdfCommand = '.'\n userpath_Default = \"C:/Users/%s/Desktop/\" % user\n userpath = \"C:/Users/%s/Desktop/MPP_Out/\" % user\n \nMisc = ParseFile()\nif (os.path.exists(Misc.resource_path(\"MagnumProgramParser_Help.pdf\"))):\n mppHelpPath = Misc.resource_path(\"MagnumProgramParser_Help.pdf\")\n upgHelpPath = Misc.resource_path(\"UnisonProgramGenerator.pdf\")\n upgReadmePath = Misc.resource_path(\"UPG_README.pdf\")\n upgBinningPath = Misc.resource_path(\"binning_help.pdf\")\n upgTestflowPath = Misc.resource_path(\"testflow_help.pdf\")\n upgPingroupPath = Misc.resource_path(\"pingroups_help.pdf\")\n dos2unixPath = Misc.resource_path(\"Dos2Unix.exe\")\nelse:\n if(sys.platform == \"win32\"):\n mppHelpPath = '.\\\\Documents\\\\MagnumProgramParser_Help.pdf'\n upgHelpPath = '.\\\\Documents\\\\MagnumProgramParser_Help.pdf'\n upgReadmePath = '.\\\\Documents\\\\UPG_README.pdf'\n upgBinningPath = '.\\\\Documents\\\\binning_help.pdf'\n upgTestflowPath = '.\\\\Documents\\\\testflow_help.pdf'\n upgPingroupPath = '.\\\\Documents\\\\pingroups_help.pdf'\n dos2unixPath = '.\\\\Dos2Unix.exe'\n elif(sys.platform == \"linux\"):\n mppHelpPath = './Documents/MagnumProgramParser_Help.pdf'\n upgHelpPath = './Documents/MagnumProgramParser_Help.pdf'\n upgReadmePath = './Documents/UPG_README.pdf'\n upgBinningPath = './Documents/binning_help.pdf'\n upgTestflowPath = './Documents/testflow_help.pdf'\n upgPingroupPath = './Documents/pingroups_help.pdf'\n dos2unixPath = './Dos2Unix.exe'\n else:\n doNothing = 1\n \n\nclass MPParseToolWindow(QtWidgets.QMainWindow,Ui_MainWindow1,ParseTestFlowFile,ParsePinFile,ParseBinFile,ParseLevelsFile,ParseSpecsFile,ParseTestGroupFile,ParseTimingFile):\n\n def __init__(self,parent=None):\n global openXML,debugPrint,userpath_PG,userpath_TF,userpath_TF_lib,userpath_BN,userpath_LV,userpath_SP,userpath_TG,userpath_TM\n self.PinGroups_Output2=''\n QtWidgets.QMainWindow.__init__(self,parent)\n self.uiVar = Ui_MainWindow1()\n self.uiVar.setupUi(self)\n self.uiVar.Gen_ParseFiles.clicked.connect(self.ParseStart)\n #self.uiVar.Gen_ParseFiles.clicked.connect(self.updateProgessBar)\n self.uiVar.Exit_PB.clicked.connect(self.quit_prog)\n self.uiVar.Reset_PB.clicked.connect(self.reset)\n self.uiVar.Config_Select.clicked.connect(self.SelectConfigFile)\n self.uiVar.actionAbout.triggered.connect(self.About)\n self.uiVar.actionHow_To_Use_MPP_2.triggered.connect(self.How_To_Use_MPP)\n self.uiVar.actionUnisonProgramGenerator.triggered.connect(self.How_To_Use_UPG)\n self.uiVar.actionUPG_Readme.triggered.connect(self.UPG_Readme)\n self.uiVar.actionBinning_Help.triggered.connect(self.UPG_Binning_Help)\n self.uiVar.actionTest_Flow_Help.triggered.connect(self.UPG_TestFlow_Help)\n self.uiVar.actionPin_Group.triggered.connect(self.UPG_PinGroup_Help)\n self.uiVar.progressBar_TF.hide()\n self.uiVar.progressBar_BN.hide()\n self.uiVar.progressBar_LV.hide()\n self.uiVar.progressBar_PG.hide()\n self.uiVar.progressBar_TG.hide()\n self.uiVar.progressBar_SP.hide()\n self.uiVar.progressBar_TM.hide()\n self.uiVar.Gen_ParseFiles.hide()\n self.uiVar.labelStatus.hide()\n self.uiVar.progressBar.hide()\n self.undefinedTestMacro=False\n self.undefinedTestMacroName=[]\n return\n\n def quit_prog(self):\n## messageRecv = \"Server Not Running\"\n## for pid in psutil.pids():\n## p = psutil.Process(pid)\n## if (p.name() == \"python.exe\") or (p.name() == \"server.exe\"):\n## print(\"Called By Python:\"+ str(p.cmdline()))\n## c = zerorpc.Client()\n## try:\n## #c.connect(\"tcp://127.0.0.1:4242\")\n## c.connect(\"tcp:localhost:4242\")\n## messageRecv = c.serverData3(\"Xcerra Inc\")\n## except:\n## messageRecv = \"Server Not Found\"\n## pass\n## msgBox = QMessageBox(QMessageBox.Information, ' ', 'Quit the program? ' + messageRecv)\n msgBox = QMessageBox(QMessageBox.Information, ' ', 'Quit the program? ')\n msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)\n msgBox.setWindowFlags(QtCore.Qt.WindowTitleHint)\n msgBox.setWindowIcon(QtGui.QIcon(':/images/MPP_icon.png'))\n msgBox.setIconPixmap(QtGui.QPixmap(':/images/exit_small.png'))\n ret = msgBox.exec_()\n if ret == QMessageBox.No:\n return\n self.close()\n return\n \n def undefinedMacro(self,name):\n macroList = ''\n #print(name)\n nameFinal = list(set(name))\n bindex = 0\n for nameMacro in nameFinal:\n bindex = bindex+1\n if bindex == 4:\n bindex = 0\n breakStr = '
'\n else:\n breakStr = ''\n macroList = macroList + ',' + str(nameMacro) + breakStr\n macroList = macroList.lstrip(',')\n pos = macroList[::-1].find(',')\n macroList1 = (macroList[:len(macroList)-pos-1])\n macroList = (macroList[len(macroList)-(pos+1):]).replace(',',\", and \")\n macroList1 = macroList1 + macroList\n msgBox = QMessageBox(QMessageBox.Information, ' ', \"

Notice

Undefined Test Macro Found!

Run cpp (macro processor) on the seq_and_bin file for undefined Test Macro(s):

\\\n

\"+macroList1+'

')\n msgBox.setStandardButtons(QMessageBox.Ok)\n msgBox.setWindowFlags(QtCore.Qt.WindowTitleHint)\n msgBox.setWindowIcon(QtGui.QIcon(':/images/MPP_icon.png'))\n msgBox.setIconPixmap(QtGui.QPixmap(':/images/macro.png'))\n msgBox.setStyleSheet(\"QPushButton {\"\" background-color: blue;\"\" color: white;\"\" border-style: outset;\"\" border-width: 2px;\"\" border-radius: 10px;\"\" border-color: beige;\"\\\n \" font: bold 14px;\"\" min-width: 100px;\"\" padding: 6px;\"\"}\")\n\n ret = msgBox.exec_()\n return\n \n def About(self):\n self.uiVar.labelStatus.hide()\n self.uiVar.progressBar.hide()\n## messageRecv = \"Server Not Running\"\n## messageRecv2 = \"Server Not Running no2\"\n## for pid in psutil.pids():\n## p = psutil.Process(pid)\n## if (p.name() == \"python.exe\") or (p.name() == \"server.exe\"):\n## print(\"Called By Python:\"+ str(p.cmdline()))\n## c = zerorpc.Client()\n## try:\n## c.connect(\"tcp://127.0.0.1:4242\")\n## messageRecv2 = c\n## except:\n## messageRecv = \"Server Not Found\"\n## pass\n## print('serverData3 dict value',messageRecv2)\n\n #print(\"Dictionary from server:\" + messageRecv)\n msgBox = QMessageBox(QMessageBox.Information, ' ',\n '

About

Magnum Program Parser

\\\n
Created by T Arnold\\\n \\n Sept 20,2016
Version '+ProgramVersion+CurrentReleaseDate)\n msgBox.setStandardButtons(QMessageBox.Ok)\n msgBox.setWindowFlags(QtCore.Qt.WindowTitleHint)\n msgBox.setWindowIcon(QtGui.QIcon(':/images/MPP_icon.png'))\n msgBox.setIconPixmap(QtGui.QPixmap(':/images/aboutIcon_small.jpg'))\n ret = msgBox.exec_()\n return\n\n \n## if (os.path.exists(WCF.resource_path(\"MPP_Git.zip\"))):\n## Sources_Input = WCF.resource_path(\"MPP_Git.zip\")\n## srctIndex = Sources_Input[::-1].find(dirSeperator)\n## sourceNow = Sources_Input[::-1][:srctIndex][::-1]\n## if not(os.path.exists(userpath+\"Sources/\")):\n## os.makedirs(userpath+\"Sources/\" )\n## if (sys.platform == \"win32\"):\n## userpathLocal = userpath.replace('/',\"\\\\\")\n## command = 'echo f | xcopy /F /Y '+Sources_Input+' '+userpathLocal+'Sources'+dirSeperator\n## elif (sys.platform == \"linux\"):\n## userpathLocal = userpath.replace('\\\\',\"/\")\n## command = 'cp -r '+Sources_Input+' '+userpathLocal+'Sources'+dirSeperator\n## print(\"command: \"+command)\n## os.system(command)\n##\n\n \n def How_To_Use_MPP(self):\n\n if (os.path.exists(mppHelpPath)):\n #os.system(str(pdfCommand+dirSeperator+'Documents'+dirSeperator+'MagnumProgramParser_Help.pdf&'))\n #os.startfile(pdfCommand+mppHelpPath)\n #process = Popen(pdfCommand+mppHelpPath, shell=False)\n p = Popen(pdfCommand+mppHelpPath, shell=True, bufsize=0,stdin=PIPE, stdout=PIPE, stderr=PIPE)\n #os.popen(str(pdfCommand+mppHelpPath))\n #print(\"mppHelpPath: \"+mppHelpPath)\n else:\n QMessageBox.warning(self,\n \"Error\",\n \"MagnumProgramParser.pdf help file not found.\\nCheck in original program Documents directory.\")\n return\n def How_To_Use_UPG(self):\n if (os.path.exists(upgHelpPath)):\n #os.system(str(pdfCommand+dirSeperator+'Documents'+dirSeperator+'UnisonProgramGenerator.pdf&'))\n p = Popen(pdfCommand+upgHelpPath, shell=True, bufsize=0,stdin=PIPE, stdout=PIPE, stderr=PIPE)\n #subprocess.call(pdfCommand+upgHelpPath, shell=True)\n #os.startfile(pdfCommand+upgHelpPath)\n #os.popen(str(pdfCommand+upgHelpPath))\n #print(\"upgHelpPath: \"+upgHelpPath)\n else:\n QMessageBox.warning(self,\n \"Error\",\n \"UnisonProgramGenerator.pdf help file not found.\\nCheck in original program Documents directory.\")\n return\n def UPG_Readme(self):\n if (os.path.exists(upgReadmePath)):\n #os.system(str(pdfCommand+dirSeperator+'Documents'+dirSeperator+'UnisonProgramGenerator.pdf&'))\n p = Popen(pdfCommand+upgReadmePath, shell=True, bufsize=0,stdin=PIPE, stdout=PIPE, stderr=PIPE)\n #subprocess.call(pdfCommand+upgHelpPath, shell=True)\n #os.startfile(pdfCommand+upgHelpPath)\n #os.popen(str(pdfCommand+upgHelpPath))\n #print(\"upgHelpPath: \"+upgHelpPath)\n else:\n QMessageBox.warning(self,\n \"Error\",\n \"upgReadmePath.pdf help file not found.\\nCheck in original program Documents directory.\")\n return\n def UPG_Binning_Help(self):\n if (os.path.exists(upgBinningPath)):\n #os.system(str(pdfCommand+dirSeperator+'Documents'+dirSeperator+'UnisonProgramGenerator.pdf&'))\n p = Popen(pdfCommand+upgBinningPath, shell=True, bufsize=0,stdin=PIPE, stdout=PIPE, stderr=PIPE)\n #subprocess.call(pdfCommand+upgHelpPath, shell=True)\n #os.startfile(pdfCommand+upgHelpPath)\n #os.popen(str(pdfCommand+upgHelpPath))\n #print(\"upgHelpPath: \"+upgHelpPath)\n else:\n QMessageBox.warning(self,\n \"Error\",\n \"upgBinningPath.pdf help file not found.\\nCheck in original program Documents directory.\")\n return\n def UPG_TestFlow_Help(self):\n if (os.path.exists(upgTestflowPath)):\n #os.system(str(pdfCommand+dirSeperator+'Documents'+dirSeperator+'UnisonProgramGenerator.pdf&'))\n p = Popen(pdfCommand+upgTestflowPath, shell=True, bufsize=0,stdin=PIPE, stdout=PIPE, stderr=PIPE)\n #subprocess.call(pdfCommand+upgHelpPath, shell=True)\n #os.startfile(pdfCommand+upgHelpPath)\n #os.popen(str(pdfCommand+upgHelpPath))\n #print(\"upgHelpPath: \"+upgHelpPath)\n else:\n QMessageBox.warning(self,\n \"Error\",\n \"upgTestflowPath.pdf help file not found.\\nCheck in original program Documents directory.\")\n return\n def UPG_PinGroup_Help(self):\n if (os.path.exists(upgPingroupPath)):\n #os.system(str(pdfCommand+dirSeperator+'Documents'+dirSeperator+'UnisonProgramGenerator.pdf&'))\n p = Popen(pdfCommand+upgPingroupPath, shell=True, bufsize=0,stdin=PIPE, stdout=PIPE, stderr=PIPE)\n #subprocess.call(pdfCommand+upgHelpPath, shell=True)\n #os.startfile(pdfCommand+upgHelpPath)\n #os.popen(str(pdfCommand+upgHelpPath))\n #print(\"upgHelpPath: \"+upgHelpPath)\n else:\n QMessageBox.warning(self,\n \"Error\",\n \"upgPingroupPath.pdf help file not found.\\nCheck in original program Documents directory.\")\n return\n\n def reset(self):\n## messageRecv = \"Server Not Running\"\n## for pid in psutil.pids():\n## p = psutil.Process(pid)\n## if (p.name() == \"python.exe\") or (p.name() == \"server.exe\"):\n## print(\"Called By Python:\"+ str(p.cmdline()))\n## c = zerorpc.Client()\n## try:\n## c.connect(\"tcp://127.0.0.1:4242\")\n## messageRecv = c.serverData(\"Malcolm Jenkins\")\n## except:\n## messageRecv = \"Server Not Found\"\n## pass\n## msgBox = QMessageBox(QMessageBox.Information, ' ', 'Reset your values? ' + messageRecv)\n msgBox = QMessageBox(QMessageBox.Information, ' ', 'Reset your values? ')\n msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n msgBox.setWindowFlags(QtCore.Qt.WindowTitleHint)\n msgBox.setWindowIcon(QtGui.QIcon(':/images/MPP_icon.png'))\n msgBox.setIconPixmap(QtGui.QPixmap(':/images/reset4_small.png'))\n ret = msgBox.exec_()\n if ret == QMessageBox.Cancel:\n return\n self.uiVar.progressBar_TF.setValue(0)\n self.uiVar.progressBar_BN.setValue(0)\n self.uiVar.progressBar_LV.setValue(0)\n self.uiVar.progressBar_PG.setValue(0)\n self.uiVar.progressBar_TG.setValue(0)\n self.uiVar.progressBar_SP.setValue(0)\n self.uiVar.progressBar_TM.setValue(0)\n self.uiVar.progressBar_TF.hide()\n self.uiVar.progressBar_BN.hide()\n self.uiVar.progressBar_LV.hide()\n self.uiVar.progressBar_PG.hide()\n self.uiVar.progressBar_TG.hide()\n self.uiVar.progressBar_SP.hide()\n self.uiVar.progressBar_TM.hide()\n self.uiVar.Gen_ParseFiles.hide()\n self.uiVar.checkBox_PG.hide()\n self.uiVar.checkBox_TG.hide()\n self.uiVar.checkBox_TF.hide()\n self.uiVar.checkBox_TM.hide()\n self.uiVar.checkBox_SP.hide()\n self.uiVar.checkBox_BN.hide()\n self.uiVar.checkBox_LV.hide()\n self.uiVar.Config_lineEdit.setText('Config File Path')\n self.uiVar.PG_Label.show()\n self.uiVar.TG_Label.show()\n self.uiVar.TF_Label.show()\n self.uiVar.TM_Label.show()\n self.uiVar.BN_Label.show()\n self.uiVar.LV_Label.show()\n self.uiVar.SP_Label.show()\n self.uiVar.labelStatus.hide()\n self.uiVar.groupBox.setTitle(\"Status: Reset Done.\")\n self.undefinedTestMacro=False\n self.undefinedTestMacroName=[]\n\n return\n \n def reset_config(self):\n self.uiVar.progressBar_TF.setValue(0)\n self.uiVar.progressBar_BN.setValue(0)\n self.uiVar.progressBar_LV.setValue(0)\n self.uiVar.progressBar_PG.setValue(0)\n self.uiVar.progressBar_TG.setValue(0)\n self.uiVar.progressBar_SP.setValue(0)\n self.uiVar.progressBar_TM.setValue(0)\n self.uiVar.progressBar_TF.hide()\n self.uiVar.progressBar_BN.hide()\n self.uiVar.progressBar_LV.hide()\n self.uiVar.progressBar_PG.hide()\n self.uiVar.progressBar_TG.hide()\n self.uiVar.progressBar_SP.hide()\n self.uiVar.progressBar_TM.hide()\n self.uiVar.Gen_ParseFiles.hide()\n self.uiVar.checkBox_PG.hide()\n self.uiVar.checkBox_TG.hide()\n self.uiVar.checkBox_TF.hide()\n self.uiVar.checkBox_TM.hide()\n self.uiVar.checkBox_SP.hide()\n self.uiVar.checkBox_BN.hide()\n self.uiVar.checkBox_LV.hide()\n self.uiVar.PG_Label.show()\n self.uiVar.TG_Label.show()\n self.uiVar.TF_Label.show()\n self.uiVar.TM_Label.show()\n self.uiVar.BN_Label.show()\n self.uiVar.LV_Label.show()\n self.uiVar.SP_Label.show()\n self.uiVar.labelStatus.hide()\n self.undefinedTestMacro=False\n self.undefinedTestMacroName=[]\n\n return\n\n def SelectConfigFile(self):\n global openXML,debugPrint,userpath_PG,userpath_TF,userpath_BN,userpath_LV,userpath_SP,userpath_TG,userpath_TM\n PinGroups_Output2=''\n Testflow_Output2=''\n Binning_Output=''\n BinningUno_Output=''\n Levels_Output=''\n Specs_Output=''\n TestGroup_Output=''\n Timing_Output=''\n UPGConfig_Output=''\n MppLog_Output=''\n configPath = self.selctFile_CF()\n if(configPath):\n self.reset_config()\n self.readConfig(configPath)\n\n return\n \n def ConfigSectionMap(self,section,Config):\n dict1 = {}\n options = Config.options(section)\n for option in options:\n try:\n dict1[option] = Config.get(section, option)\n if dict1[option] == -1:\n DebugPrint(\"skip: %s\" % option)\n except:\n #print(\"exception on %s!\" % option)\n dict1[option] = None\n #print('dict1',dict1)\n return dict1\n \n def readConfig(self,path):\n global userpath_PG,userpath_TF,userpath_TF_lib,userpath_BN,userpath_LV,userpath_SP,userpath_TG,userpath_TM,specFileCount\n global PinGroups_Input,Testflow_Input,Testflow_lib_Input,Binning_Input,Levels_Input,Specs_Input,TestGroup_Input,Timing_Input\n global tbDirectory,tbList,spDirectory,spList,TestflowList,prog_Name,userpath,tfList,tfDirectory\n global Testflow_Output2,Binning_Output,BinningUno_Output,mainFlows,mfList,testno_multiplier,testno_offset\n global Levels_Output,Specs_Output,TestGroup_Output,Timing_Output,UPGConfig_Output, MppLog_Output,codeDump\n\n user = getpass.getuser()\n userpath_PG = userpath\n userpath_TF = userpath\n userpath_TF_lib = userpath\n userpath_BN = userpath\n userpath_LV = userpath\n userpath_SP = userpath\n userpath_TG = userpath\n userpath_TM = userpath\n tfList=[]\n \"\"\"\n Read a config file\n \"\"\"\n if not(path):\n return\n try:\n if (os.path.exists(path) or (os.path.exists(os.getcwd()+path))):\n pass\n else:\n QMessageBox.warning(self,\n \"Warning\",\n \"Please select A Valid Configuration File.\")\n except:\n QMessageBox.warning(self,\n \"Warning\",\n \"Please select A Configuration File.\")\n return\n Config = ConfigParser()\n try:\n Config.read(path)\n except:\n QMessageBox.warning(self,\n \"Error\",\n \"Unrecognized entry in Configuration File.\")\n return\n try:\n userpath_PG = self.ConfigSectionMap(\"Input_File_Path\",Config)['pingroups_path']\n except:\n userpath_PG=''\n try:\n userpath_TF = self.ConfigSectionMap(\"Input_File_Path\",Config)['seq_bin_path']\n except:\n userpath_TF=''\n try:\n userpath_TF_lib = self.ConfigSectionMap(\"Input_File_Path\",Config)['seq_bin_path_lib']\n except:\n userpath_TF_lib=''\n try:\n testFlowList = self.ConfigSectionMap(\"Input_File_Path\",Config)['testflowlist']\n except:\n testFlowList=''\n try:\n userpath_BN = self.ConfigSectionMap(\"Input_File_Path\",Config)['binning_path']\n except:\n userpath_BN=''\n try:\n userpath_LV = self.ConfigSectionMap(\"Input_File_Path\",Config)['voltage_path']\n except:\n userpath_LV=''\n try:\n userpath_SP = self.ConfigSectionMap(\"Input_File_Path\",Config)['specs_path']\n except:\n userpath_SP=''\n try:\n userpath_TG = self.ConfigSectionMap(\"Input_File_Path\",Config)['testgroups_path']\n except:\n userpath_TG=''\n try:\n userpath_TM = self.ConfigSectionMap(\"Input_File_Path\",Config)['timing_path']\n except:\n userpath_TM=''\n try:\n progName = self.ConfigSectionMap(\"Input_File_Path\",Config)['prog_name']\n except:\n progName='MyProgram'\n try:\n userpath = self.ConfigSectionMap(\"Input_File_Path\",Config)['user_path']\n except:\n userpath=userpath\n try:\n mainFlows = self.ConfigSectionMap(\"Input_File_Path\",Config)['main_flows']\n except:\n mainFlows=''\n try:\n testno_multiplier = self.ConfigSectionMap(\"Input_File_Path\",Config)['testno_multiplier']\n except:\n testno_multiplier=''\n try:\n testno_offset = self.ConfigSectionMap(\"Input_File_Path\",Config)['testno_offset']\n except:\n testno_offset=''\n try:\n codeDump = self.ConfigSectionMap(\"Input_File_Path\",Config)['code_dump']\n except:\n codeDump=False\n\n ############# Pin Group/Package Flow input and output files ####################\n self.PinGroups_Output=userpath+'Package.csv'\n self.PinGroups_Output2=userpath+'Package.xls'\n self.Testflow_Output=userpath+'Testflow.csv'\n self.Testflow_Output2=userpath+'Testflow.xls'\n self.Binning_Output=userpath+'Binning.csv'\n self.BinningUno_Output=userpath+'BinMaps.uno'\n self.Levels_Output=userpath+'Levels.csv'\n self.Specs_Output=userpath+'Specs.uno'\n self.TestGroup_Output=userpath+'TestGroups.uno'\n self.Timing_Output=userpath+'PatternSupports.uno'\n self.UPGConfig_Output=userpath+'configuration_UPG.cfg'\n self.MppLog_Output=userpath+'Mpp_ErrorLog.log'\n\n userpath_PG = userpath_PG.replace('\\\\','/')\n userpath_TF = userpath_TF.replace('\\\\','/')\n userpath_TF_lib = userpath_TF_lib.replace('\\\\','/')\n testFlowList = testFlowList.replace('\\\\','/')\n userpath_BN = userpath_BN.replace('\\\\','/')\n userpath_LV = userpath_LV.replace('\\\\','/')\n userpath_SP = userpath_SP.replace('\\\\','/')\n userpath_TG = userpath_TG.replace('\\\\','/')\n userpath_TM = userpath_TM.replace('\\\\','/')\n userpath = userpath.replace('\\\\','/')\n mainFlows = mainFlows.replace('\\\\','/')\n \n if(',' in userpath_TG):\n tbList=[]\n userpath_TG = userpath_TG.replace(' ','')\n TBListIndex = userpath_TG[::-1].find('/')\n tbDirectory = userpath_TG[::-1][TBListIndex:][::-1]\n tbList = userpath_TG[::-1][:TBListIndex][::-1].split(',')\n if(',' in userpath_SP):\n spList=[]\n userpath_SP = userpath_SP.replace(' ','')\n SPListIndex = userpath_SP[::-1].find('/')\n spDirectory = userpath_SP[::-1][SPListIndex:][::-1]\n spList = userpath_SP[::-1][:SPListIndex][::-1].split(',')\n\n if(',' in userpath_TF_lib):\n tfList=[]\n userpath_TF_lib = userpath_TF_lib.replace(' ','')\n TFListIndex = userpath_TF_lib[::-1].find('/')\n tfDirectory = userpath_TF_lib[::-1][TFListIndex:][::-1]\n tfList = userpath_TF_lib[::-1][:TFListIndex][::-1].split(',')\n if(',' in mainFlows):\n mfList=[]\n mfList = mainFlows.split(',')\n else:\n mfList = mainFlows\n\n PinGroups_Input = userpath_PG\n Testflow_Input = userpath_TF\n Testflow_lib_Input = userpath_TF_lib\n Binning_Input = userpath_BN\n Levels_Input = userpath_LV\n Specs_Input = userpath_SP\n TestGroup_Input = userpath_TG\n Timing_Input = userpath_TM\n TestflowList = ['']\n prog_Name = progName\n window.uiVar.labelStatus.hide()\n spNotFound=False\n tgNotFound=False\n tfNotFound=False\n if (os.path.isfile(userpath_PG) or (os.path.isfile(os.getcwd()+userpath_PG)) and (len(userpath_PG) >4)):\n\n window.uiVar.checkBox_PG.setChecked(True)\n window.uiVar.checkBox_PG.show()\n window.uiVar.progressBar_PG.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.PG_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_PG.setChecked(False)\n window.uiVar.checkBox_PG.hide()\n window.uiVar.progressBar_PG.hide()\n window.uiVar.PG_Label.show() \n if(',' in userpath_TF_lib):\n for tf in tfList:\n filename = tfDirectory+tf\n if('*' in tf):\n for filename in glob.glob(tfDirectory+tf):\n if((os.path.exists(filename) or (os.path.exists(os.getcwd()+filename))) and (len(filename) >4) and not(tfNotFound)):\n ##print('filename glob2:',filename)\n window.uiVar.checkBox_TF.setChecked(True)\n window.uiVar.checkBox_TF.show()\n window.uiVar.progressBar_TF.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.TF_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_TF.setChecked(False)\n window.uiVar.checkBox_TF.hide()\n window.uiVar.progressBar_TF.hide()\n window.uiVar.TF_Label.show()\n tFNotFound=True\n else:\n if((os.path.exists(filename) or (os.path.exists(os.getcwd()+filename))) and (len(filename) >4) and not(tfNotFound)):\n window.uiVar.checkBox_TF.setChecked(True)\n window.uiVar.checkBox_TF.show()\n window.uiVar.progressBar_TF.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.TF_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_TF.setChecked(False)\n window.uiVar.checkBox_TF.hide()\n window.uiVar.progressBar_TF.hide()\n window.uiVar.TF_Label.show()\n tFNotFound=True\n else:\n for filename in glob.glob(userpath_TF_lib):\n if((os.path.exists(filename) or (os.path.exists(os.getcwd()+filename))) and (len(filename) >4) and not(tfNotFound)):\n window.uiVar.checkBox_TF.setChecked(True)\n window.uiVar.checkBox_TF.show()\n window.uiVar.progressBar_TF.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.TF_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_TF.setChecked(False)\n window.uiVar.checkBox_TF.hide()\n window.uiVar.progressBar_TF.hide()\n window.uiVar.TF_Label.show()\n tFNotFound=True\n if (os.path.exists(userpath_TF) or (os.path.exists(os.getcwd()+userpath_TF)) and (len(userpath_TF) >4)):\n window.uiVar.checkBox_TF.setChecked(True)\n window.uiVar.checkBox_TF.show()\n window.uiVar.progressBar_TF.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.TF_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_TF.setChecked(False)\n window.uiVar.checkBox_TF.hide()\n window.uiVar.progressBar_TF.hide()\n window.uiVar.TF_Label.show()\n\n if (os.path.exists(userpath_BN) or (os.path.exists(os.getcwd()+userpath_BN)) and (len(userpath_BN) >4)):\n window.uiVar.checkBox_BN.setChecked(True)\n window.uiVar.checkBox_BN.show()\n window.uiVar.progressBar_BN.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.BN_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_BN.setChecked(False)\n window.uiVar.checkBox_BN.hide()\n window.uiVar.progressBar_BN.hide()\n window.uiVar.BN_Label.show()\n if(',' in userpath_TG):\n for tb in tbList:\n filename = tbDirectory+tb\n if('*' in tb):\n for filename in glob.glob(tbDirectory+tb):\n #print('filename glob:',filename)\n if((os.path.exists(filename) or (os.path.exists(os.getcwd()+filename))) and (len(filename) >4) and not(tgNotFound)):\n ##print('filename glob2:',filename)\n window.uiVar.checkBox_TG.setChecked(True)\n window.uiVar.checkBox_TG.show()\n window.uiVar.progressBar_TG.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.TG_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_TG.setChecked(False)\n window.uiVar.checkBox_TG.hide()\n window.uiVar.progressBar_TG.hide()\n window.uiVar.TG_Label.show()\n tgNotFound=True\n else:\n if((os.path.exists(filename) or (os.path.exists(os.getcwd()+filename))) and (len(filename) >4) and not(tgNotFound)):\n ##print('filename no *:',filename)\n window.uiVar.checkBox_TG.setChecked(True)\n window.uiVar.checkBox_TG.show()\n window.uiVar.progressBar_TG.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.TG_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_TG.setChecked(False)\n window.uiVar.checkBox_TG.hide()\n window.uiVar.progressBar_TG.hide()\n window.uiVar.TG_Label.show()\n tgNotFound=True\n else:\n for filename in glob.glob(userpath_TG):\n if((os.path.exists(filename) or (os.path.exists(os.getcwd()+filename))) and (len(filename) >4) and not(tgNotFound)):\n window.uiVar.checkBox_TG.setChecked(True)\n window.uiVar.checkBox_TG.show()\n window.uiVar.progressBar_TG.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.TG_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_TG.setChecked(False)\n window.uiVar.checkBox_TG.hide()\n window.uiVar.progressBar_TG.hide()\n window.uiVar.TG_Label.show()\n tgNotFound=True\n if(',' in userpath_SP):\n for sp in spList:\n filename = spDirectory+sp\n if('*' in sp):\n for filename in glob.glob(spDirectory+sp):\n if((os.path.exists(filename) or (os.path.exists(os.getcwd()+filename))) and (len(filename) >4) and not(spNotFound)):\n #specFileCount=specFileCount+1\n window.uiVar.checkBox_SP.setChecked(True)\n window.uiVar.checkBox_SP.show()\n window.uiVar.progressBar_SP.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.SP_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_SP.setChecked(False)\n window.uiVar.checkBox_SP.hide()\n window.uiVar.progressBar_SP.hide()\n window.uiVar.SP_Label.show()\n spNotFound=True\n else:\n if((os.path.exists(filename) or (os.path.exists(os.getcwd()+filename))) and (len(filename) >4) and not(spNotFound)):\n #specFileCount=specFileCount+1\n window.uiVar.checkBox_SP.setChecked(True)\n window.uiVar.checkBox_SP.show()\n window.uiVar.progressBar_SP.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.SP_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_SP.setChecked(False)\n window.uiVar.checkBox_SP.hide()\n window.uiVar.progressBar_SP.hide()\n window.uiVar.SP_Label.show()\n spNotFound=True\n else:\n for filename in glob.glob(userpath_SP):\n if((os.path.exists(filename) or (os.path.exists(os.getcwd()+filename))) and (len(filename) >4) and not(spNotFound)):\n #specFileCount=specFileCount+1\n window.uiVar.checkBox_SP.setChecked(True)\n window.uiVar.checkBox_SP.show()\n window.uiVar.progressBar_SP.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.SP_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_SP.setChecked(False)\n window.uiVar.checkBox_SP.hide()\n window.uiVar.progressBar_SP.hide()\n window.uiVar.SP_Label.show()\n spNotFound=True\n if (os.path.exists(userpath_TM) or (os.path.exists(os.getcwd()+userpath_TM)) and (len(userpath_TM) >4)):\n window.uiVar.checkBox_TM.setChecked(True)\n window.uiVar.checkBox_TM.show()\n window.uiVar.progressBar_TM.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.TM_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_TM.setChecked(False)\n window.uiVar.checkBox_TM.hide()\n window.uiVar.progressBar_TM.hide()\n window.uiVar.TM_Label.show()\n if (os.path.exists(userpath_LV) or (os.path.exists(os.getcwd()+userpath_LV)) and (len(userpath_LV) >4)):\n window.uiVar.checkBox_LV.setChecked(True)\n window.uiVar.checkBox_LV.show()\n window.uiVar.progressBar_LV.show()\n window.uiVar.Gen_ParseFiles.show()\n window.uiVar.LV_Label.hide()\n window.uiVar.labelStatus.setText( \"Ready To Parse\")\n fg = \"QLabel {color:darkorange}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n else:\n window.uiVar.checkBox_LV.setChecked(False)\n window.uiVar.checkBox_LV.hide()\n window.uiVar.progressBar_LV.hide()\n window.uiVar.LV_Label.show()\n return \n \n def selctFile_CF(self):\n user = getpass.getuser()\n \n MPParseToolWindow.fileNameDL = QtWidgets.QFileDialog.getOpenFileName(self, 'Select a Configuration File',userpath_Default,'Config Files MPP*.*;;Config *.*')\n fileConfig = MPParseToolWindow.fileNameDL\n filelocal = str(fileConfig)\n filelocal = filelocal.replace(\"('\",\"\")\n filelocal = filelocal.replace(\"', '')\",\"\")\n filelocal = filelocal.replace(\"', 'Config Files MPP*.*')\",\"\")\n filelocal = filelocal.replace(\"', 'Config *.*')\",\"\")\n \n fileConfig=filelocal\n if(len(fileConfig) == 0):return\n self.uiVar.groupBox.setStyleSheet(\"color: rgb(0, 0, 0);\\n\")\n self.uiVar.groupBox.setTitle('Status: Ready')\n\n if not(len(fileConfig) == 0):\n #fileConfig = fileConfig.replace(\"/\",\"\\\\\").strip()\n self.uiVar.Config_lineEdit.setDisabled(0)\n self.uiVar.Config_lineEdit.setText(fileConfig)\n return fileConfig\n\n \n def fileRollingBackup(self,file):\n def fileTimeCheck(file):\n fileBack=file+'.Back.0'\n backupCount=0\n backupCount = backupCount+1\n timeMin = 0\n fileNo = 0\n timeStamp=[]\n\n for fn in range(6):\n fnext = fn+1\n if (os.path.exists(fileBack+str(backupCount))):\n timenow=os.path.getmtime(fileBack+str(backupCount))\n timeStamp.append([timenow,backupCount])\n backupCount = backupCount+1\n if(timeMin > timenow):\n timeMin = timenow\n fileNo = backupCount-1\n timeStamp.sort()\n fileNoTemp = timeStamp[0][1]\n if (os.path.exists(fileBack+str(fileNoTemp))):\n os.remove(fileBack+str(fileNoTemp))\n os.rename(file,fileBack+str(fileNoTemp))\n return\n \n def renameFile(file):\n global PinGroups_Output2,Testflow_Output2,Binning_Output,BinningUno_Output,Levels_Output,Specs_Output,TestGroup_Output\n global Timing_Output,UPGConfig_Output, MppLog_Output\n fileBack=file+'.Back.0'\n backupCount=0\n backupCount = backupCount+1\n timeStamp=[]\n if (os.path.exists(file)):\n for fn in range(6):\n fnext = fn+1\n if (os.path.exists(fileBack+str(backupCount))):\n timenow=os.path.getmtime(fileBack+str(backupCount))\n timeStamp.append(timenow)\n backupCount = backupCount+1\n try:\n if(backupCount==1):\n os.rename(file,fileBack+str(backupCount))\n if(backupCount==2):\n os.rename(file,fileBack+str(backupCount))\n if(backupCount==3):\n os.rename(file,fileBack+str(backupCount))\n if(backupCount==4):\n os.rename(file,fileBack+str(backupCount))\n if(backupCount==5):\n os.rename(file,fileBack+str(backupCount))\n if(backupCount==6):\n timeStamp=[]\n fileTimeCheck(file)\n except :\n pass\n slashIndex = file[::-1].find('/')\n fileToRename = file[len(file)-slashIndex:]\n msgBox = QMessageBox(QMessageBox.Information, ' ', '

Error File Open

\\n

Attemping to Back Up '\n +fileToRename+'

Please close the file and\\n Press[OK] to Try Again
or Press[Cancel] to Stop Parsing.')\n msgBox.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)\n msgBox.setWindowFlags(QtCore.Qt.WindowTitleHint)\n msgBox.setWindowIcon(QtGui.QIcon(':/images/MPP_icon.png'))\n msgBox.setIconPixmap(QtGui.QPixmap(':/images/stop_small.png'))\n ret = msgBox.exec_()\n if ret == QMessageBox.Cancel:\n return \n if ret == QMessageBox.Ok:\n renameFile(file)\n return\n self.close() \n return\n renameFile(file)\n return\n###################################################################################################################\n############################################ Timing Functions End ################################################\n###################################################################################################################\n\n def BuildPinGroupFile(self,PinGroups_Input):\n global topline,DO_PACKAGE\n pinGroupArray=[]\n if (os.path.exists(PinGroups_Input)):\n PG1 = ParsePinFile()\n window.uiVar.progressBar_PG.setValue(20)\n pinGroupArray, pinGroupDict = PG1.pinGroupExtract(PinGroups_Input,len(PinGroups_Input))\n if (DO_PACKAGE):\n self.fileRollingBackup(self.PinGroups_Output2)\n PG1.packageWriteXls(self.PinGroups_Output2,pinGroupArray,self.MppLog_Output)\n window.uiVar.progressBar_PG.setValue(100)\n #print('pinGroupDict:',pinGroupDict)\n return pinGroupDict,allPinGroups\n \n def BuildTestFlowFile(self,Testflow_Input,Testflow_Output,TestflowList,BinNoDict,Binning_Output,DO_BINNING):\n global topline,mainFlow\n TF1 = ParseTestFlowFile()\n window.uiVar.progressBar_TF.setValue(20)\n flowCounter=0\n tindex = 0\n filenameList=[]\n if(',' in userpath_TF_lib):\n for tf in tfList:\n if('*' in tf):\n for filename in glob.glob(tfDirectory+tf):\n filenameList.append(filename)\n else:\n filename = tfDirectory+tf\n filenameList.append(filename)\n else:\n for filename in glob.glob(Testflow_lib_Input):\n filenameList.append(filename)\n filenameList = set(filenameList)\n flowFileCount = len(filenameList)\n barstep = len(filenameList)\n bi = 11\n testFlowLib = False\n tindex = TF1.testflowExtract(Testflow_Input,tindex,testFlowLib)\n if(TF1.undefinedMacro):\n print(\"TF1.undefinedMacro is True\")\n self.undefinedTestMacro=True\n self.undefinedTestMacroName=TF1.undefinedMacroName\n print(self.undefinedTestMacroName)\n mainFlow = TF1.mainFlow\n if(len(Testflow_lib_Input) > 0):\n testFlowLib = True\n else:\n testFlowLib = False\n window.uiVar.progressBar_TF.setValue(40)\n if(testFlowLib):\n for filename in list(filenameList):\n flowCounter=flowCounter+1\n tindex = TF1.testflowExtract(filename,tindex,testFlowLib)\n window.uiVar.progressBar_TF.setValue(bi)\n bi=bi+100/barstep\n window.uiVar.progressBar_TF.setValue(60)\n self.fileRollingBackup(self.Testflow_Output2)\n TF1.testflowWrite(self.Testflow_Output,TF1.flowArrayData,TestflowList)\n testBinList = TF1.testflowWriteXls(self.Testflow_Output2,TF1.testFlowArray,self.MppLog_Output,BinNoDict,mfList,maxBinNo,Binning_Output,testno_multiplier,testno_offset,DO_BINNING)\n window.uiVar.progressBar_TF.setValue(100)\n return testBinList\n\n def BuildBinning(self,Binning_Input,Binning_Output):\n global topline,BinNoDict,maxBinNo,mainFlow\n mainFlow=''\n BN1 = ParseBinFile()\n window.uiVar.progressBar_BN.setValue(20)\n BinNoDict,maxBinNo,binningList = BN1.binningExtract(Binning_Input,len(Binning_Input))\n window.uiVar.progressBar_BN.setValue(40)\n self.fileRollingBackup(self.Binning_Output)\n window.uiVar.progressBar_BN.setValue(50)\n BN1.buildBinXls(Binning_Output)\n window.uiVar.progressBar_BN.setValue(100)\n return \n\n def BuildLevelsFile(self,Levels_Input,Levels_Output):\n global topline\n LV1 = ParseLevelsFile()\n window.uiVar.progressBar_LV.setValue(50)\n self.fileRollingBackup(self.Levels_Output)\n LV1.levelsExtract(Levels_Input,self.Levels_Output,self.MppLog_Output)\n window.uiVar.progressBar_LV.setValue(100)\n return\n\n def BuildSpecs_Output(self,Specs_Input,Specs_Output):\n global specFileCount,specCounter,tempParamGlobals,tempParamGlobals2,tempParamGlobals3,topline\n SP1 = ParseSpecsFile()\n topline = SP1.specsExtract(Specs_Input,specFileCount,specCounter,self.Specs_Output,tempParamGlobals,tempParamGlobals2,tempParamGlobals3,topline)\n return\n\n def BuildTestGroup_Output(self,TestGroup_Input,TestGroup_Output,topline1):\n topline = topline1\n global testBlockSet\n fileCounter=0\n testBlockList2=[]\n TG1 = ParseTestGroupFile()\n window.uiVar.progressBar_TG.setValue(10)\n testBlockList2,testBlockDict,testFuncDict = TG1.testgroupExtract(TestGroup_Input)\n #testFuncDict = TG1.TestFunc_Parse(TestGroup_Input)\n testBlockDict2 = TG1.TestBlock_Parse(TestGroup_Input)\n testBlockSet = set(testBlockList2)\n barstep = len(list(set(testBlockList2)))\n bi = 11\n for ii in list(set(testBlockList2)):\n topline,testGroupOutputArray = TG1.testgroupWrite(ii,testBlockDict[ii],TestGroup_Input,self.TestGroup_Output,topline)\n #time.sleep(.1)\n window.uiVar.progressBar_TG.setValue( bi)\n bi = bi + 100/barstep\n #print(\"topline in BuildTestGroup_Output exit \",topline)\n window.uiVar.progressBar_TG.setRange(0, 100)\n window.uiVar.progressBar_TG.setValue( 100)\n return topline, testFuncDict\n\n def BuildTiming_Input(self,Timing_Input,Timing_Output,allPinGroups):\n global topline,waveTableOpen,pinGroupDict\n waveTableOpen = False\n TM1 = ParseTimingFile()\n window.uiVar.progressBar_TM.setValue(50)\n self.fileRollingBackup(self.Timing_Output)\n #TM1.timingExtract(Timing_Input,self.Timing_Output,pinGroupDict)\n TM1.timingExtract2(Timing_Input,self.Timing_Output,pinGroupDict,allPinGroups)\n window.uiVar.progressBar_TM.setValue(100)\n return\n \n def Source_dump(self,WCF):\n ################################################################\n ## Embeded Source Dump\n ################################################################\n if(codeDump):\n if (os.path.exists(WCF.resource_path(\"Source_Code_Package.zip\"))):\n Sources_Input = WCF.resource_path(\"Source_Code_Package.zip\")\n srctIndex = Sources_Input[::-1].find(dirSeperator)\n sourceNow = Sources_Input[::-1][:srctIndex][::-1]\n if not(os.path.exists(userpath+\"Sources/\")):\n os.makedirs(userpath+\"Sources/\" )\n if (sys.platform == \"win32\"):\n userpathLocal = userpath.replace('/',\"\\\\\")\n command = 'echo f | xcopy /F /Y '+Sources_Input+' '+userpathLocal+'Sources'+dirSeperator\n elif (sys.platform == \"linux\"):\n userpathLocal = userpath.replace('\\\\',\"/\")\n command = 'cp -r '+Sources_Input+' '+userpathLocal+'Sources'+dirSeperator\n p = Popen(command, shell=True, bufsize=0,stdin=PIPE, stdout=PIPE, stderr=PIPE)\n return\n\n def ParseStart(self):\n global topline,tindex,PinGroups_Input,specCounter,specFileCount,flowCounter,flowFileCount,mainFlow\n global tempParamGlobals,tempParamGlobals2,tempParamGlobals3,DO_PACKAGE,specTopline,pinGroupArray\n global pinGroupDict\n self.undefinedTestMacro=False\n self.undefinedTestMacroName=[]\n\n if (os.path.isdir(userpath)):\n doNothing = 1\n else:\n try:\n os.makedirs(userpath )\n except:\n QMessageBox.warning(window,\n \"Error\",\n \"Cannot create Output directory. Check user_path in configuration file and write previleges.\")\n return\n try:\n window.uiVar.progressBar_TF.setValue(0)\n window.uiVar.progressBar_BN.setValue(0)\n window.uiVar.progressBar_LV.setValue(0)\n window.uiVar.progressBar_PG.setValue(0)\n window.uiVar.progressBar_TG.setValue(0)\n window.uiVar.progressBar_SP.setValue(0)\n window.uiVar.progressBar_TM.setValue(0)\n window.uiVar.labelStatus.hide()\n\n if('Config File' in window.uiVar.Config_lineEdit.text()):\n QMessageBox.warning(window,\n \"Warning\",\n \"Please select a Configuration file first.\")\n return\n if not(os.path.exists(window.uiVar.Config_lineEdit.text())):\n QMessageBox.warning(window,\n \"Warning\",\n \"Please select an existing Configuration file.\")\n return\n if(window.uiVar.checkBox_TF.isChecked()):\n DO_TESTFLOW = True\n window.uiVar.progressBar_TF.show()\n else:DO_TESTFLOW = False\n if(window.uiVar.checkBox_BN.isChecked()):\n DO_BINNING = True\n window.uiVar.progressBar_BN.show()\n else:DO_BINNING = False\n if(window.uiVar.checkBox_LV.isChecked()):\n DO_LEVELS = True\n window.uiVar.progressBar_LV.show()\n else:DO_LEVELS = False\n if(window.uiVar.checkBox_SP.isChecked()):\n DO_SPECS = True\n window.uiVar.progressBar_SP.show()\n else:DO_SPECS = False\n if(window.uiVar.checkBox_PG.isChecked()):\n DO_PACKAGE = True\n window.uiVar.progressBar_PG.show()\n else:DO_PACKAGE = False\n if(window.uiVar.checkBox_TG.isChecked()):\n DO_TESTGROUP = True\n window.uiVar.progressBar_TG.show()\n else:\n DO_TESTGROUP = False\n window.uiVar.progressBar_TG.hide()\n\n if(window.uiVar.checkBox_TM.isChecked()):\n DO_TIMING = True\n window.uiVar.progressBar_TM.show()\n else:DO_TIMING = False\n\n tickstart = time.time()\n\n WCF = ParseFile()\n if(codeDump):\n self.Source_dump(WCF)\n Error_Msg = 'Source Package Dump'\n \n ################################################################\n ## Backup MPP_ErrorLog file if size exceeds 500K\n ################################################################\n if (os.path.exists(self.MppLog_Output)):\n Error_Msg = 'Backing up Mpp_ErrorLog.log'\n ErrorMPPFileSize = os.path.getsize(self.MppLog_Output)\n ##print(\"Mpp_ErrorLog size:\"+str(ErrorMPPFileSize))\n if(ErrorMPPFileSize > 500000):\n self.fileRollingBackup(self.MppLog_Output)\n if((DO_PACKAGE) or ((DO_TIMING) and (os.path.exists(PinGroups_Input)))):\n Error_Msg = 'Parsing Package'\n pinGroupDict,allPinGroups = self.BuildPinGroupFile(PinGroups_Input)\n ticks = time.time()\n ##print(\"PinGroup End Time:\",ticks)\n if(DO_TIMING):\n global Timing_Output\n Error_Msg = 'Parsing Timing'\n self.BuildTiming_Input(Timing_Input,self.Timing_Output,allPinGroups)\n ticks = time.time()\n ##print(\"Timing End Time:\",ticks)\n if(DO_BINNING):\n Error_Msg = 'Parsing Binning'\n self.BuildBinning(Binning_Input,self.Binning_Output)\n ticks = time.time()\n ##print(\"Binning End Time:\",ticks)\n if(DO_TESTFLOW):\n global Testflow_Output,testBinList,updateBinNoDict\n testBinList.clear()\n updateBinNoDict.clear()\n Error_Msg = 'Parsing Test Flow'\n testBinList,updateBinNoDict = self.BuildTestFlowFile(Testflow_Input,self.Testflow_Output,TestflowList,BinNoDict,self.Binning_Output,DO_BINNING)\n ticks = time.time()\n ##print(\"TestFlow End Time:\",ticks)\n if(DO_BINNING):\n global mainFlow\n if not(DO_TESTFLOW):\n testBinList.clear()\n updateBinNoDict.clear()\n Error_Msg = 'Writing Binning.uno'\n self.fileRollingBackup(self.BinningUno_Output)\n self.buildBinUno(self.BinningUno_Output,testBinList,updateBinNoDict,BinNoDict,mainFlow)\n window.uiVar.progressBar_BN.setValue(100)\n ticks = time.time()\n ##print(\"Binning End Time:\",ticks)\n if(DO_LEVELS):\n global Levels_Output\n Error_Msg = 'Parsing Levels'\n #print('Levels_Input1',Levels_Input)\n self.BuildLevelsFile(Levels_Input,self.Levels_Output)\n ticks = time.time()\n ##print(\"Levels End Time:\",ticks)\n if(DO_SPECS):\n Error_Msg = 'Parsing Specs'\n specCounter=0\n filenameList=[]\n tempParamGlobals=[]\n tempParamGlobals2=[]\n tempParamGlobals3=[]\n topline=True\n global Specs_Output\n self.fileRollingBackup(self.Specs_Output)\n if(',' in userpath_SP):\n for sp in spList:\n if('*' in sp):\n for filename in glob.glob(spDirectory+sp):\n filenameList.append(filename)\n else:\n filename = spDirectory+sp\n filenameList.append(filename)\n else:\n for filename in glob.glob(Specs_Input):\n filenameList.append(filename)\n \n filenameList = set(filenameList)\n specFileCount = len(filenameList)\n barstep = len(filenameList)\n bi = 11\n global Specs_Output\n window.uiVar.progressBar_SP.setValue(5)\n for filename in filenameList:\n specCounter=specCounter+1\n self.BuildSpecs_Output(filename,self.Specs_Output)\n window.uiVar.progressBar_SP.setValue(bi)\n bi=bi+100/barstep\n time.sleep(.025)\n window.uiVar.progressBar_SP.setValue(100)\n\n ticks = time.time()\n ##print(\"Specs End Time:\",ticks)\n if(DO_TESTGROUP):\n topline = True\n Error_Msg = 'Parsing Test Group'\n filenameList=[]\n global TestGroup_Output\n if(',' in TestGroup_Input):\n for tb in tbList:\n if('*' in tb):\n for filename in glob.glob(tbDirectory+tb):\n filenameList.append(filename)\n else:\n filename = tbDirectory+tb\n filenameList.append(filename)\n else:\n for filename in glob.glob(TestGroup_Input):\n filenameList.append(filename)\n filenameList = set(filenameList)\n self.fileRollingBackup(self.TestGroup_Output)\n for filename in filenameList:\n topline,testFuncDict = self.BuildTestGroup_Output(filename,self.TestGroup_Output,topline)\n ticks = time.time()\n #print(\"TestGroup End Time:\",ticks)\n global prog_Name\n\n self.fileRollingBackup(self.UPGConfig_Output)\n WCF.writeUpgConfig(prog_Name,'Package.xls','Binning.csv','BinMaps.uno','Testflow.xls','Levels.csv','PatternSupports.uno','Specs.uno','TestGroups.uno',self.UPGConfig_Output)\n tickend = time.time()\n ##print(\"Time Elapsed:\",(tickend-tickstart))\n if (DO_TESTGROUP) or (DO_SPECS) or (DO_TIMING) or (DO_BINNING):\n fileList=[]\n if (sys.platform == \"win32\"):\n Error_Msg = 'Dos2Unix *.uno command'\n if(DO_TESTGROUP): fileList.append('TestGroups.uno')\n if(DO_TIMING): fileList.append('PatternSupports.uno')\n if(DO_SPECS): fileList.append('Specs.uno')\n if(DO_BINNING): fileList.append('Binning.uno')\n errorFlag = WCF.runDos2Unix(userpath,WCF,fileList)\n if(errorFlag):\n msgBox = QMessageBox(QMessageBox.Information, ' ',\n '

Warning

Dos2Unix Command Not Found

\\\n After transfering files to Linux drive\\\n run Linux version of dos2unix on all .uno files\\\n to remove (^M) character.')\n msgBox.setStandardButtons(QMessageBox.Ok)\n msgBox.setWindowFlags(QtCore.Qt.WindowTitleHint)\n msgBox.setWindowIcon(QtGui.QIcon(':/images/MPP_icon.png'))\n msgBox.setIconPixmap(QtGui.QPixmap(':/images/Dos2Linux_small.png'))\n ret = msgBox.exec_()\n\n window.uiVar.labelStatus.setText( \"Done Writing to Output Directory\")\n fg = \"QLabel {color:darkgreen}\"\n #bg = \"QLabel {background-color:white}\"\n window.uiVar.labelStatus.setStyleSheet( fg )\n window.uiVar.labelStatus.show()\n except:\n raise\n window.uiVar.groupBox.setTitle(\"Status: Error encountered during parse.\")\n window.uiVar.labelStatus.setText( \"Error: \"+Error_Msg+' - Parse Stopped')\n fg = \"QLabel {color:black}\"\n bg = \"QLabel {background-color:red}\"\n window.uiVar.labelStatus.setStyleSheet( fg+bg )\n window.uiVar.labelStatus.show()\n if(self.undefinedTestMacro):\n self.undefinedMacro(self.undefinedTestMacroName)\n\n return\n\n\ndef clearSelection():\n window.uiVar.checkBox_PG.hide()\n window.uiVar.checkBox_TG.hide()\n window.uiVar.checkBox_TF.hide()\n window.uiVar.checkBox_TM.hide()\n window.uiVar.checkBox_BN.hide()\n window.uiVar.checkBox_SP.hide()\n window.uiVar.checkBox_LV.hide()\n window.reset\n return\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n window = MPParseToolWindow()\n clearSelection()\n window.show()\n sys.exit(app.exec_())\n\n","sub_path":"MPP_Control_R3p12.py","file_name":"MPP_Control_R3p12.py","file_ext":"py","file_size_in_byte":64556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"234724353","text":"import os\nimport re\nimport shutil\nimport sys\nimport time\nfrom collections import OrderedDict\nfrom time import sleep\n\nfrom colorama import Fore as Color\nfrom colorama import init\n\nimport downloader\nimport localdb\nimport Parse\n\ninit(autoreset=True) # colroama 초기화\n\nVersion = 0.35\nprint('현재 버전은 v.' + str(Version) + '입니다.')\nprint('current program version is v.' + str(Version))\nprint('\\n')\ntime.sleep(1)\nadded_dic = localdb.return_local_db()\noverlap_dic = localdb.return_compare_dic()\n\n#백업라인\n#------------------------------------------------\n#VM 머신에선 여기가 없어서 오류가 남...\ntry:\n temp = os.environ['userprofile']\n rimsavedir = '{}/appdata/locallow/Ludeon Studios\\RimWorld by Ludeon Studios\\Config'.format(temp)\n os.chdir(rimsavedir)\nexcept:\n print('림월드 SAVE 폴더를 찾을 수 없습니다. 림월드를 설치하신 게 맞나요?')\n print('프로그램을 종료합니다.')\n print(\"can't find rimworld save folder... close program\")\n sys.exit(0)\n\nprint('기존 컨픽 파일을 백업하는 중...')\nprint('saving old config files...')\nnow_time = time.strftime('%d_%H_%M', time.localtime(time.time()))\nshutil.copy('ModsConfig.xml', 'ModsConfig.xml.backup{}'.format(now_time))\n#------------------------------------------------\n\nprint('template를 받아오는 중입니다...')\nprint('downloading mod DB from github... \\n')\ndata = localdb.return_local_db()\ndata_len = len(data)\nprint('현재 DB에 등록된 모드의 개수는 ' + Color.GREEN + '{}'.format(data_len) + Color.WHITE + '개 입니다.')\nprint('DB mod count : ' + Color.GREEN + '{}'.format(data_len))\nprint('현재 다운받은 파일은 마지막으로 {} 시각에 업데이트 된 파일입니다. 잠시만 기다려 주세요... \\n'.format(data['time']))\nprint('DB last updated time : {} \\n'.format(data['time']))\n\nmod_dic = dict() # 모드와 번호 연결, 번호 : 이름\nmod_list_workshop = list() # 모드 리스트(이름만)\nmod_dic_num = dict() #이름 : 번호\nmod_nlist = list()\nmod_list_local = list()\nmod_list_sorted = list()\nconfig_num = list()\n\nrim64win_path = Parse.Parser(mod_dic,mod_dic_num, mod_list_workshop, mod_list_local, None) # 파싱 작업을 수행 후, 림월드 실행을 위한 파일 경로를 return\nprint('현재 구독중인 모드 리스트를 불러옵니다...')\nprint('Loading workshop mods...')\n\nfor x in mod_list_workshop:\n sleep(0.05)\n print(Color.LIGHTGREEN_EX + x)\n print('\\n')\n\nprint('Local 모드 리스트를 불러옵니다...')\nprint('Loading Local mods...')\n\nfor x in mod_list_local:\n sleep(0.05)\n print(Color.LIGHTYELLOW_EX + x)\n print('\\n')\n\nlocal_test_breakloop = False\nwhile local_test_breakloop == False:\n print('local db testing... \\n type 1 : activate all mod you have, and sort it. \\n type 2 : preserve the existing load list, add mods to load list that you added.')\n i = input('type 1 or 2 : ')\n if str(i) == '1':\n local_test_breakloop = True\n config_num = list()\n for x in mod_list_workshop:\n config_num.append(mod_dic_num[x])\n\n for x in mod_list_local:\n config_num.append(mod_dic_num[x])\n\n mod_list_sorted = list()\n for mod in config_num: #mod는 숫자, 영문이름, 또는 __Localcopy\n m = re.match('__LocalCopy', mod)\n if mod == 'Core':\n continue\n\n try:\n if m: #만약 config파일에서 불러온 모드의 이름이 __LocalCopy로 시작하면\n modname = mod.split('_')[3]\n mod_list_sorted = mod_list_sorted + [[data[modname], mod, True]]\n print(Color.LIGHTBLUE_EX + 'Localcopy {} 모드를 리스트에 추가'.format(modname))\n print(Color.LIGHTBLUE_EX + 'Add Localcopy {} Mod to list'.format(modname))\n continue\n\n\n elif mod.isdigit() == False: #Local인데 __Localcopy가 아니라면\n modname = mod_dic[mod]\n mod_list_sorted = mod_list_sorted + [[data[modname], mod, True]]\n print(Color.LIGHTYELLOW_EX + 'local {} 모드를 리스트에 추가'.format(modname))\n print(Color.LIGHTYELLOW_EX + 'Add local mod {} to list'.format(modname))\n continue\n\n else:\n modname = mod_dic[mod] #mod는 숫자\n mod_list_sorted = mod_list_sorted + [[data[modname], mod, False]]\n print(Color.LIGHTGREEN_EX + 'workshop {} 모드를 리스트에 추가'.format(modname))\n print(Color.LIGHTGREEN_EX + 'add workshop mod {} to list'.format(modname))\n continue\n\n\n except Exception as e:\n print(Color.LIGHTRED_EX + modname + ' 은 template에 없어 제외되었습니다.')\n print(Color.LIGHTRED_EX + modname + \" is not supported yet\")\n mod_nlist.append(modname)\n\n\n\n finally:\n print('\\n')\n sleep(0.1)\n\n elif str(i) == '2':\n local_test_breakloop = True\n config_num = Parse.find_activate_mod()\n added_dic = localdb.return_compare_dic()\n\n for x in added_dic:\n try:\n config_num.append(mod_dic_num[x])\n except Exception as e:\n print(e)\n\n \n\n #추가하는중...\n for mod in config_num: #mod는 숫자, 영문이름, 또는 __Localcopy\n m = re.match('__LocalCopy', mod)\n if mod == 'Core':\n mod_list_sorted = mod_list_sorted + [[1, 'Core', False]]\n\n try:\n if m: #만약 config파일에서 불러온 모드의 이름이 __LocalCopy로 시작하면\n modname = mod.split('_')[3]\n mod_list_sorted = mod_list_sorted + [[data[modname], mod, True]]\n print(Color.LIGHTBLUE_EX + 'Localcopy {} 모드를 리스트에 추가'.format(modname))\n print(Color.LIGHTBLUE_EX + 'Add Localcopy {} Mod to list'.format(modname))\n print('\\n')\n continue\n\n\n elif mod.isdigit() == False: #Local인데 __Localcopy가 아니라면\n modname = mod_dic[mod]\n mod_list_sorted = mod_list_sorted + [[data[modname], mod, True]]\n print(Color.LIGHTYELLOW_EX + 'local {} 모드를 리스트에 추가'.format(modname))\n print(Color.LIGHTYELLOW_EX + 'Add local mod {} to list'.format(modname))\n print('\\n')\n continue\n\n else:\n modname = mod_dic[mod] #mod는 숫자\n mod_list_sorted = mod_list_sorted + [[data[modname], mod, False]]\n print(Color.LIGHTGREEN_EX + 'workshop {} 모드를 리스트에 추가'.format(modname))\n print(Color.LIGHTGREEN_EX + 'add workshop mod {} to list'.format(modname))\n print('\\n')\n continue\n\n\n except Exception as e:\n print(Color.LIGHTRED_EX + modname + ' 은 template에 없어 제외되었습니다.')\n print(Color.LIGHTRED_EX + modname + \" is not supported yet\")\n mod_nlist.append(modname)\n print('\\n')\n\n\n else:\n print('wrong input... please type 1 or 2')\n\nmod_list_sorted.sort()\nParse.setconfig(mod_list_sorted)\nprint('배열한 모드 순서는 다음과 같습니다.')\nprint('mods will be loaded in the following order')\nprint('\\n')\nfor i in mod_list_sorted:\n if mod_dic[i[1]] in overlap_dic:\n print(Color.LIGHTMAGENTA_EX + mod_dic[i[1]])\n continue\n\n sleep(0.05)\n if i[2] == False:\n print(Color.LIGHTGREEN_EX + mod_dic[i[1]]) #\n\n else:\n x = re.match('__Local', i[1])\n if x:\n x = i[1].split('_')\n print(Color.LIGHTBLUE_EX + 'Localcopy {}'.format(x[3]))\n \n else:\n print(Color.LIGHTYELLOW_EX + mod_dic[i[1]])\nprint('loaded {} mods.'.format(len(mod_list_sorted)))\n\n \n \n\nif len(mod_nlist) != 0:\n print('\\n')\n print('\\n')\n print('다음 모드는 로드 목록에 있었으나, template에 없어서 로드가 해제된 모드입니다. 인-게임에서 수동으로 모드를 배열해주세요.')\n print('These Mods were in load_list, but not in template. please sort mod manually in game')\n print('\\n')\n for x in mod_nlist:\n sleep(0.05)\n print(x)\n\n print('total deactivated mod : {}'.format(len(mod_nlist)))\n\nos.chdir(os.environ['HOMEPATH'])\nos.chdir('./desktop')\n\nwith open('Mod_not_in_the_db.txt', 'w', encoding='UTF-8') as f:\n for x in mod_nlist:\n f.write(x)\n f.write('\\n')\n\n\n\nprint('\\n')\nprint('배열이 끝났습니다.')\nprint('sort complete.')\nprint('\\n')\n\nprint('로그를 확인해주세요.')\nprint('please check full log')\nprint(\"please start rimworld manually.\")\nexit = False\nwhile exit == False:\n x = input('type \"exit\" to exit program : ')\n x.lower()\n if x == 'exit':\n exit = True\n else:\n pass\n","sub_path":"Old/local_DB_test.py","file_name":"local_DB_test.py","file_ext":"py","file_size_in_byte":9160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"531179899","text":"#!/usr/bin/env python\n# Pi Platter Demo\n# This program demonstrates 4 things\n# 1. Report battery voltage\n# 2. Shut down when battery is low\n# 3. Restart once battery voltage has recovered\n# 4. Setting Pi Platter Real Time Clock\n# To run this program at startup:\n# In the command line terminal edit rc.local with :\n# sudo nano /etc/rc.local\n# add the following line:\n# python /honme/pu/PiPlatterDemo.py &\n# This of course, presumes that you have talkpp and PiPlatterDemo.py in the named places\n# To make the startup on boot more robust, check out daemontools\n# For lots more cool ideas on using the Pi Platter, go to RocketBlueAutomation.com\n\nimport os\nimport sys\nimport subprocess\nfrom subprocess import Popen, PIPE\nfrom datetime import datetime\nimport time\n\nuser = os.getuid()\nif user != 0:\n print(\"Please run script as root\")\n sys.exit()\n\ndef main(argv):\n if datetime.today().year > 2016: # if the OS time is current then set the RTC\n ticks = time.time()\n settimecmd = \"talkpp -c T=\" + str(int(ticks))\n print(\"Setting Pi Platter RTC\")\n os.system(settimecmd) # set the system time \n else:\n cmd = Popen('talkpp -c T', shell=True, stdout=PIPE) # read date from piplatter\n alloutput = cmd.stdout.read()\n alloutput.splitlines()\n mytime = int(alloutput.splitlines()[0])\n #print mytime\n if mytime > 148000000: #only set the os time if the RTC was previously set\n print (\"Setting OS time\")\n datecmd = Popen('sudo date %s' % mytime, shell=True, stdout=PIPE) # set os date\n dateoutput = datecmd.stdout.readlines()\n \n print(\"Pi Platter Demo\")\n print(\"By RocketBlueAutomation.com\")\n previous_second = 0\n last_good_battery_voltage = 0\n while True: #monitor battery and log voltage once a minute\n now = datetime.today()\n \n battery_voltage = subprocess.check_output(\"talkpp -c B\", shell=True) # read battery voltage\n\n if is_float(battery_voltage) : # talkpp does not always return a value - put in last known value if not \n last_good_battery_voltage = battery_voltage\n else: \n battery_voltage = last_good_battery_voltage\n battery_volt = float(battery_voltage)\n if (battery_volt < 3.67) and (battery_volt > 1.50): # shut down if battery voltage is getting to low\n print(\"Powering down now\")\n # Threshold=(1.024/(Restart_Voltage-0.15))*1023\n os.system(\"talkpp -c E3=272\") # start back up at 4.00 volts\n os.system(\"talkpp -c C7=1\") # set to restart\n os.system(\"talkpp -c E7=1\") # set to restart every time\n os.system(\"talkpp -c O=30\") # Turn off Pi Platter in 30 seconds\n os.system(\"sudo halt\") # shut down Pi Zero now\n with open('voltage_date.txt','a+') as fb:\n fb.write( '{} {}\\n'.format(str(now)[:-7], battery_volt) )\n print (str(now)[:-7]),battery_volt\n time.sleep(60) # check and log about once a minute\n\ndef is_float(volts): # test to see if the returned value looks like a proper floating point number\n try:\n newVolts = float(volts)\n return newVolts\n except ValueError:\n return None\n\n# main\nif \"__main__\" == __name__:\n if len(sys.argv) < 1:\n sys.exit('usage: {p:s}'.format(p=sys.argv[0]))\n\n try: # exit cleanly on keyboard interrupt. \n main(sys.argv[1:])\n except KeyboardInterrupt:\n sys.exit('interrupted')\n pass\n","sub_path":"pi_platter/examples/PiPlatterDemo.py","file_name":"PiPlatterDemo.py","file_ext":"py","file_size_in_byte":3509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"421079178","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nimport socketserver\n\nclass tcptest(socketserver.BaseRequestHandler):\n def handle(self):\n while True:\n self.data = self.request.recv(1024).strip()\n print('client from: {}' . format(self.client_address[0]))\n if not self.data:\n print('等待客户端连接......')\n print(self.data)\n self.request.send(self.data.upper())\n\nif __name__ == '__main__':\n ip,port = '127.0.0.1', 9999\n # 单\n # myserver = socketserver.TCPServer((ip,port), tcptest)\n # 多并发\n myserver = socketserver.ThreadingTCPServer((ip, port), tcptest)\n print('running')\n myserver.serve_forever()\n","sub_path":"socket_test/socketserver1.py","file_name":"socketserver1.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"174376704","text":"from __future__ import unicode_literals\nimport boto.ec2\nimport boto.ec2.autoscale\nimport boto.ec2.elb\nimport sure\nfrom boto3 import Session\n\nfrom moto import mock_ec2_deprecated, mock_autoscaling_deprecated, mock_elb_deprecated\n\nfrom moto.ec2 import ec2_backends\nfrom tests import EXAMPLE_AMI_ID, EXAMPLE_AMI_ID2\n\n\ndef test_use_boto_regions():\n boto_regions = set()\n for region in Session().get_available_regions(\"ec2\"):\n boto_regions.add(region)\n for region in Session().get_available_regions(\"ec2\", partition_name=\"aws-us-gov\"):\n boto_regions.add(region)\n for region in Session().get_available_regions(\"ec2\", partition_name=\"aws-cn\"):\n boto_regions.add(region)\n moto_regions = set(ec2_backends)\n\n moto_regions.should.equal(boto_regions)\n\n\ndef add_servers_to_region(ami_id, count, region):\n conn = boto.ec2.connect_to_region(region)\n for index in range(count):\n conn.run_instances(ami_id)\n\n\n@mock_ec2_deprecated\ndef test_add_servers_to_a_single_region():\n region = \"ap-northeast-1\"\n add_servers_to_region(EXAMPLE_AMI_ID, 1, region)\n add_servers_to_region(EXAMPLE_AMI_ID2, 1, region)\n\n conn = boto.ec2.connect_to_region(region)\n reservations = conn.get_all_reservations()\n len(reservations).should.equal(2)\n\n image_ids = [r.instances[0].image_id for r in reservations]\n image_ids.should.equal([EXAMPLE_AMI_ID, EXAMPLE_AMI_ID2])\n\n\n@mock_ec2_deprecated\ndef test_add_servers_to_multiple_regions():\n region1 = \"us-east-1\"\n region2 = \"ap-northeast-1\"\n add_servers_to_region(EXAMPLE_AMI_ID, 1, region1)\n add_servers_to_region(EXAMPLE_AMI_ID2, 1, region2)\n\n us_conn = boto.ec2.connect_to_region(region1)\n ap_conn = boto.ec2.connect_to_region(region2)\n us_reservations = us_conn.get_all_reservations()\n ap_reservations = ap_conn.get_all_reservations()\n\n len(us_reservations).should.equal(1)\n len(ap_reservations).should.equal(1)\n\n us_reservations[0].instances[0].image_id.should.equal(EXAMPLE_AMI_ID)\n ap_reservations[0].instances[0].image_id.should.equal(EXAMPLE_AMI_ID2)\n\n\n@mock_autoscaling_deprecated\n@mock_elb_deprecated\ndef test_create_autoscaling_group():\n elb_conn = boto.ec2.elb.connect_to_region(\"us-east-1\")\n elb_conn.create_load_balancer(\n \"us_test_lb\", zones=[], listeners=[(80, 8080, \"http\")]\n )\n elb_conn = boto.ec2.elb.connect_to_region(\"ap-northeast-1\")\n elb_conn.create_load_balancer(\n \"ap_test_lb\", zones=[], listeners=[(80, 8080, \"http\")]\n )\n\n us_conn = boto.ec2.autoscale.connect_to_region(\"us-east-1\")\n config = boto.ec2.autoscale.LaunchConfiguration(\n name=\"us_tester\", image_id=EXAMPLE_AMI_ID, instance_type=\"m1.small\"\n )\n x = us_conn.create_launch_configuration(config)\n\n us_subnet_id = list(ec2_backends[\"us-east-1\"].subnets[\"us-east-1c\"].keys())[0]\n ap_subnet_id = list(\n ec2_backends[\"ap-northeast-1\"].subnets[\"ap-northeast-1a\"].keys()\n )[0]\n group = boto.ec2.autoscale.AutoScalingGroup(\n name=\"us_tester_group\",\n availability_zones=[\"us-east-1c\"],\n default_cooldown=60,\n desired_capacity=2,\n health_check_period=100,\n health_check_type=\"EC2\",\n max_size=2,\n min_size=2,\n launch_config=config,\n load_balancers=[\"us_test_lb\"],\n placement_group=\"us_test_placement\",\n vpc_zone_identifier=us_subnet_id,\n termination_policies=[\"OldestInstance\", \"NewestInstance\"],\n )\n us_conn.create_auto_scaling_group(group)\n\n ap_conn = boto.ec2.autoscale.connect_to_region(\"ap-northeast-1\")\n config = boto.ec2.autoscale.LaunchConfiguration(\n name=\"ap_tester\", image_id=EXAMPLE_AMI_ID, instance_type=\"m1.small\"\n )\n ap_conn.create_launch_configuration(config)\n\n group = boto.ec2.autoscale.AutoScalingGroup(\n name=\"ap_tester_group\",\n availability_zones=[\"ap-northeast-1a\"],\n default_cooldown=60,\n desired_capacity=2,\n health_check_period=100,\n health_check_type=\"EC2\",\n max_size=2,\n min_size=2,\n launch_config=config,\n load_balancers=[\"ap_test_lb\"],\n placement_group=\"ap_test_placement\",\n vpc_zone_identifier=ap_subnet_id,\n termination_policies=[\"OldestInstance\", \"NewestInstance\"],\n )\n ap_conn.create_auto_scaling_group(group)\n\n len(us_conn.get_all_groups()).should.equal(1)\n len(ap_conn.get_all_groups()).should.equal(1)\n\n us_group = us_conn.get_all_groups()[0]\n us_group.name.should.equal(\"us_tester_group\")\n list(us_group.availability_zones).should.equal([\"us-east-1c\"])\n us_group.desired_capacity.should.equal(2)\n us_group.max_size.should.equal(2)\n us_group.min_size.should.equal(2)\n us_group.vpc_zone_identifier.should.equal(us_subnet_id)\n us_group.launch_config_name.should.equal(\"us_tester\")\n us_group.default_cooldown.should.equal(60)\n us_group.health_check_period.should.equal(100)\n us_group.health_check_type.should.equal(\"EC2\")\n list(us_group.load_balancers).should.equal([\"us_test_lb\"])\n us_group.placement_group.should.equal(\"us_test_placement\")\n list(us_group.termination_policies).should.equal(\n [\"OldestInstance\", \"NewestInstance\"]\n )\n\n ap_group = ap_conn.get_all_groups()[0]\n ap_group.name.should.equal(\"ap_tester_group\")\n list(ap_group.availability_zones).should.equal([\"ap-northeast-1a\"])\n ap_group.desired_capacity.should.equal(2)\n ap_group.max_size.should.equal(2)\n ap_group.min_size.should.equal(2)\n ap_group.vpc_zone_identifier.should.equal(ap_subnet_id)\n ap_group.launch_config_name.should.equal(\"ap_tester\")\n ap_group.default_cooldown.should.equal(60)\n ap_group.health_check_period.should.equal(100)\n ap_group.health_check_type.should.equal(\"EC2\")\n list(ap_group.load_balancers).should.equal([\"ap_test_lb\"])\n ap_group.placement_group.should.equal(\"ap_test_placement\")\n list(ap_group.termination_policies).should.equal(\n [\"OldestInstance\", \"NewestInstance\"]\n )\n","sub_path":"tests/test_ec2/test_regions.py","file_name":"test_regions.py","file_ext":"py","file_size_in_byte":5989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"243719738","text":"from datetime import datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom pathlib import Path\nimport re\nimport six\n\n\n# Helper para salvar graficos\ndef render_table(data, col_width=3.0, row_height=0.625, font_size=14,\n header_color='#4a86e8', row_colors=['#f1f1f2', 'w'],\n edge_color='w', bbox=[0, 0, 1, 1], header_columns=0,\n ax=None, **kwargs):\n if ax is None:\n size = (np.array(data.shape[::-1]) + np.array([0, 1])) * np.array(\n [col_width, row_height])\n fig, ax = plt.subplots(figsize=size)\n ax.axis('off')\n\n mpl_table = ax.table(cellText=data.values, bbox=bbox,\n colLabels=data.columns, **kwargs)\n\n mpl_table.auto_set_font_size(False)\n mpl_table.set_fontsize(font_size)\n\n for k, cell in six.iteritems(mpl_table._cells):\n cell.set_edgecolor(edge_color)\n if k[0] == 0 or k[1] < header_columns:\n cell.set_text_props(weight='bold', color='w')\n cell.set_facecolor(header_color)\n else:\n cell.set_facecolor(row_colors[k[0] % len(row_colors)])\n return ax, fig\n\n\n# Helper para ajudar no plot de graficos\ndef autolabel(rects, xpos='center', ax=None):\n \"\"\"\n Attach a text label above each bar in *rects*, displaying its height.\n\n *xpos* indicates which side to place the text w.r.t. the center of\n the bar. It can be one of the following {'center', 'right', 'left'}.\n \"\"\"\n\n ha = {'center': 'center', 'right': 'left', 'left': 'right'}\n offset = {'center': 0, 'right': 1, 'left': -1}\n\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(offset[xpos]*3, 3), # use 3 points offset\n textcoords=\"offset points\", # in both directions\n ha=ha[xpos], va='bottom')\n\n\ndef paths_datasets():\n local_raiz = 'database/'\n\n return list(Path(local_raiz).glob('*'))\n\n\ndef read_datasets(locais_anos):\n processos_anos = []\n andamentos_anos = []\n assuntos_anos = []\n\n for local in locais_anos:\n processos_anos.append(list(Path(local).glob('*_recife.csv'))[0])\n andamentos_anos.append(list(Path(local).glob('*_andamentos.csv'))[0])\n assuntos_anos.append(list(Path(local).glob('*_assuntos.csv'))[0])\n\n df_processos = [pd.read_csv(str(processo)) for processo in processos_anos]\n df_andamentos = [pd.read_csv(str(andamento)) for andamento in andamentos_anos]\n df_assuntos = [pd.read_csv(str(assunto)) for assunto in assuntos_anos]\n\n return (pd.concat(df_processos), pd.concat(df_andamentos),\n pd.concat(df_assuntos))\n\n\ndef save_grafico(grafico, title):\n fig = plt.figure()\n grafico.plot.barh(title=title, edgecolor='black', color='y')\n fig.savefig('figures/{}'.format(title), dpi=100, bbox_inches='tight')\n\n\ndef save_tabela(dados, title, col_width):\n fig = plt.figure()\n ax, fig = render_table(dados, header_columns=0, col_width=col_width)\n fig.savefig('figures/'.format(title), dpi=100, bbox_inches='tight')\n\n\ndef classe_cnj_analise(df_processos_totais):\n classe_cnj = df_processos_totais['Classe CNJ']\n\n save_grafico(classe_cnj.value_counts(), title='Frequência das Classes CNJ')\n\n save_tabela(dados=df_assuntos_totais.iloc[:, 1:].head(n=7),\n title='assuntos_totais_pt1', col_width=5)\n save_tabela(dados=df_processos_totais.iloc[:, 3:].head(n=7),\n title='processos_totais_pt2', col_width=3.5)\n\n\ndef assunto_analise(df_assuntos_totais):\n assuntos = df_assuntos_totais['Assunto']\n\n assuntos_valor = assuntos.value_counts()\n assuntos_filtrado_index = assuntos_valor.iloc[\n assuntos_valor.values > 9].index\n assuntos_filtrado_values = assuntos_valor.iloc[\n assuntos_valor.values > 9].values\n\n assuntos_filtrado = pd.DataFrame({\n 'Assunto': assuntos_filtrado_index,\n 'Frequência': assuntos_filtrado_values\n })\n\n save_tabela(dados=assuntos_filtrado, title='assuntos_filtrados',\n col_width=7.5)\n\n save_grafico(grafico=assuntos_filtrado,\n title='Assuntos CNJ com mais de 10 aparições')\n\n\n# TODO: Realizar uma analise com esses dados\ndef duracao_andamentos(numeros_aux, data_inicio_aux, data_fim_aux,\n duracao_aux):\n duracao_andamentos = pd.DataFrame({\n 'Numero': numeros_aux,\n 'Data Inicio': data_inicio_aux,\n 'Data Fim': data_fim_aux,\n 'Duracao (em dias)': duracao_aux\n })\n\n\ndef andamentos_analise(df_andamentos_totais):\n numeros_aux = []\n data_inicio_aux = []\n data_fim_aux = []\n duracao_aux = []\n\n for numero in df_andamentos_totais['numero'].unique():\n lista = list(df_andamentos_totais[(\n df_andamentos_totais['numero'] == int(numero))]['data'])\n lista = [datetime.strptime(lista[i], \"%d/%m/%Y %H:%M:%S\") for i in range(len(lista))]\n\n if max(lista).year != 2019:\n duracao = abs(lista[0] - lista[-1]).days\n\n numeros_aux.append(numero)\n data_inicio_aux.append(min(lista))\n data_fim_aux.append(max(lista))\n duracao_aux.append(duracao)\n\n duracao_andamentos(numeros_aux, data_inicio_aux, data_fim_aux, duracao_aux)\n\n\ndef relacao_anos_processos():\n anos_frequencia = pd.DataFrame({\n 'Ano': [2014, 2015, 2016, 2017, 2018],\n 'Proc_ano': [18466, 17366, 11605, 12519, 15075],\n 'Proc_vcm': [407, 972, 1111, 2169, 3786]\n })\n\n ind = np.arange(len(anos_frequencia['Proc_vcm']))\n width = 0.35\n\n fig, ax = plt.subplots()\n rects1 = ax.bar(ind - width/2, anos_frequencia['Proc_ano'], width,\n label='Proc')\n rects2 = ax.bar(ind + width/2, anos_frequencia['Proc_vcm'], width,\n label='VCM')\n\n ax.set_ylabel('Num Processos'); ax.set_xticks(ind)\n ax.set_xticklabels(anos_frequencia['Ano']); ax.legend()\n autolabel(rects1, \"center\", ax); autolabel(rects2, \"center\", ax)\n\n fig.set_size_inches(7.5, 6.5, forward=True)\n fig.savefig('figures/processos_anos', dpi=100, bbox_inches='tight')\n plt.show()\n\n\ndef anos_assuntos(anos, assuntos):\n df_assuntos_ano = pd.DataFrame({\n 'Ano': anos,\n 'Assunto': assuntos\n })\n\n for ano in df_assuntos_ano['Ano'].unique():\n assuntos_values = df_assuntos_ano[\n (df_assuntos_ano['Ano'] == ano)]['Assunto'].value_counts()\n assuntos_filtrados = assuntos_values.loc[assuntos_values.values > 9]\n\n save_grafico(grafico=assuntos_filtrados,\n title='Principais Assuntos CNJ do Ano {}'.format(ano))\n\n\ndef anos_frequencia(df_assuntos_totais):\n anos_lista = []\n assuntos_lista = []\n\n for processo in df_assuntos_totais['Numero'].unique():\n df_assun = df_assuntos_totais[(df_assuntos_totais['Numero'] == processo)]\n assuntos = df_assun['Assunto'].values\n processo_corrigido = str(processo).zfill(20)\n ano = re.match('\\d{9}(\\d{4})', processo_corrigido).group(1)\n\n for assunto in assuntos:\n assuntos_lista.append(assunto)\n anos_lista.append(ano)\n\n anos_assuntos(anos_lista, assuntos_lista)\n\n\nif __name__ == '__main__':\n locais_anos = paths_datasets()\n df_processos_totais, df_andamentos_totais, df_assuntos_totais = read_datasets(locais_anos)\n\n classe_cnj_analise(df_processos_totais)\n assunto_analise(df_assuntos_totais)\n andamentos_analise(df_andamentos_totais)\n anos_frequencia(df_assuntos_totais)\n\n relacao_anos_processos()\n","sub_path":"Violencia_Contra_Mulher.py","file_name":"Violencia_Contra_Mulher.py","file_ext":"py","file_size_in_byte":7702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"217081649","text":"import os\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\n\ndef scraping():\n current_dir = os.getcwd()\n print(current_dir)\n os.chdir(current_dir + \"/htmls\")\n print(os.getcwd())\n\n options1 = range(1, 3)\n options2 = range(1, 3)\n options3 = range(1, 3)\n options4 = range(1, 3)\n options5 = range(1, 3)\n options6 = range(1, 3)\n options7 = range(1, 3)\n options8 = range(1, 3)\n options9 = range(1, 3)\n options10 = range(1, 3)\n options11 = range(1, 3)\n options12 = range(1, 3)\n combinations = [(option1, option2, option3, option4, option5, option6, option7, option8, option9, option10, option11, option12)\n for option1 in options1\n for option2 in options2\n for option3 in options3\n for option4 in options4\n for option5 in options5\n for option6 in options6\n for option7 in options7\n for option8 in options8\n for option9 in options9\n for option10 in options10\n for option11 in options11\n for option12 in options12]\n\n df = pd.DataFrame(columns=['num','type', 'Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8', 'Q9', 'Q10', 'Q11', 'Q12'])\n\n for option1, option2, option3, option4, option5, option6, option7, option8, option9, option10, option11, option12 in combinations:\n binary_number = \"0b\" + str(option1-1) + str(option2-1) + str(option3-1) + str(option4-1) + str(option5-1) + str(option6-1) + str(option7-1) + str(option8-1) + str(option9-1)+ str(option10-1) + str(option11-1) + str(option12-1)\n oct_num = str(int(binary_number, 2) + 1)\n print(\"Scrape \" + oct_num + \".html\")\n soup = BeautifulSoup(open(oct_num + \".html\"), \"html.parser\")\n type_name = soup.h1.string\n df.loc[int(oct_num)] = [int(oct_num), type_name[10:14], str(option1), str(option2), str(option3), str(option4), str(option5), str(option6), str(option7), str(option8), str(option9), str(option10), str(option11), str(option12)]\n \n ## For debug\n #if oct_num == \"300\":\n # break \n\n df.to_csv('16personalities.csv', index=False, mode='w', encoding='utf-8')\n\n\n\nif __name__ == \"__main__\":\n scraping()\n print(\"------FINISH------\")\n","sub_path":"crawling_16personalities/scraping.py","file_name":"scraping.py","file_ext":"py","file_size_in_byte":2158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"221439832","text":"import cv2\nimport numpy as np\nimport struct\nimport os\nimport sys\nimport zlib\nimport CRC\nfrom time import *\nborder = 4\nwidth = 81\ninWidth = 41\nlocWidth = 16\nblackWhite = 14\n\nsLocWidth = 8\nsblackWhite = 7\n\ndef drawLocPoint(mat):\n\t#创建定位点\n\tfor i in range(border,border+blackWhite):\n\t\t#左上角\n\t\tmat[i][border] = 0\t\t#竖\n\t\tmat[i][border+blackWhite-1] = 0\n\t\tmat[i][border+1] = 0\t\t\n\t\tmat[i][border+blackWhite-1-1] = 0\n\t\tmat[border][i] = 0\t\t#横\n\t\tmat[border+blackWhite-1][i] = 0\n\t\tmat[border+1][i] = 0\t\t#横\n\t\tmat[border+blackWhite-1-1][i] = 0\n\t\t#左下角\n\t\tmat[width-border-blackWhite][i] = 0\n\t\tmat[width-border-1][i] = 0\n\t\tmat[width-border-blackWhite+1][i] = 0\n\t\tmat[width-border-1-1][i] = 0\n\t\tmat[width-i-1][border] = 0\n\t\tmat[width-i-1][border+blackWhite-1] = 0\n\t\tmat[width-i-1][border+1] = 0\n\t\tmat[width-i-1][border+blackWhite-1-1] = 0\n\t\t#右上角和左上角对称\n\t\tmat[i][width-border-blackWhite] = 0\n\t\tmat[i][width-border-1] = 0\n\t\tmat[i][width-border-blackWhite+1] = 0\n\t\tmat[i][width-border-1-1] = 0\n\t\tmat[border][width-i-1] = 0\n\t\tmat[border+blackWhite-1][width-i-1] = 0\n\t\tmat[border+1][width-i-1] = 0\n\t\tmat[border+blackWhite-1-1][width-i-1] = 0\n\tfor i in range(border,border+sblackWhite):\n\t\t#右下角\n\t\tmat[width-i-1][width-border-1] = 0\t\t#竖\n\t\tmat[width-i-1][width-(border+sblackWhite)] = 0\n\t\tmat[width-border-1][width-i-1] = 0\t\t#横\n\t\tmat[width-(border+sblackWhite)][width-i-1] = 0\n\n\tfor i in range(border+4,border+4+6):\n\t\tfor j in range(border+4,border+4+6):\n\t\t\tmat[i][j] = 0\n\t\t\tmat[i][width-j-1] = 0\n\t\t\tmat[width-j-1][i] = 0\n\n\tfor i in range(border+2,border+2+3):\n\t\tfor j in range(border+2,border+2+3):\n\t\t\tmat[width-i-1][width-j-1] = 0\n\treturn\n\ndef mask(mat,row,col,count):\n\tif(mat[row][col][count]==255):\n\t\tmat[row][col][count] = 0\n\telse:\n\t\tmat[row][col][count] = 255\n\treturn\ndef encode(mat,binstring):\n\trow=border #记录绘制到第几行\n\tcol=border + locWidth #记录绘制到第几列\n\tcount = 0#rgb通道变换\n\twhile binstring and row < width - border:\n\t\tif row=3:\n\t\t\t\tcount-=3\n\t\t\t\tcol += 1\n\t\t\t\tif col>width-border-locWidth-1:\n\t\t\t\t\tif row!=border+locWidth-1 :\n\t\t\t\t\t\tcol = border + locWidth\n\t\t\t\t\telse:\n\t\t\t\t\t\tcol = border\n\t\t\t\t\trow += 1\n\t\t\tbinstring=binstring[1:]\n\t\telif row=3:\n\t\t\t\tcount-=3\n\t\t\t\tcol += 1\n\t\t\t\tif col>width-border-1:\n\t\t\t\t\tif row != width-border-locWidth-1:\n\t\t\t\t\t\tcol = border\n\t\t\t\t\telse:\n\t\t\t\t\t\tcol = border + locWidth\n\t\t\t\t\trow += 1\n\t\t\tbinstring=binstring[1:]\n\t\telif row < width-border-sLocWidth:\n\t\t\tif int(binstring[0]) == 1:\n\t\t\t\tmat[row][col][count] = 0\n\t\t\telse:\n\t\t\t\tmat[row][col][count] = 255\n\t\t\tif (col+row)% 2==0:\n\t\t\t\tmask(mat,row,col,count)\n\t\t\tcount+=1\n\t\t\tif count>=3:\n\t\t\t\tcount-=3\n\t\t\t\tcol += 1\n\t\t\t\tif col>width-border-1:\n\t\t\t\t\tcol = border + locWidth\n\t\t\t\t\trow += 1\n\t\t\tbinstring=binstring[1:]\n\t\telse:\n\t\t\tif int(binstring[0]) == 1:\n\t\t\t\tmat[row][col][count] = 0\n\t\t\telse:\n\t\t\t\tmat[row][col][count] = 255\n\t\t\tif (col+row)% 2==0:\n\t\t\t\tmask(mat,row,col,count)\n\t\t\tcount+=1\n\t\t\tif count>=3:\n\t\t\t\tcount-=3\n\t\t\t\tcol += 1\n\t\t\t\tif col>width-sLocWidth-border-1:\n\t\t\t\t\tcol = border + locWidth\n\t\t\t\t\trow += 1\n\t\t\tbinstring=binstring[1:]\n\t#print(row)\n\t#print(bitstring)\n\t#res=\"\"\n\t#while bitstring:\n\t#\tt = (int(bitstring[:8],2))\n\t#\tres += chr(t)\n\t#\tbitstring = bitstring[8:]\n\t#print(res)\n\treturn binstring\n\ndef drawPoint():\n\treturn\n\ndef genImage(mat,width,filename):\n\t#begin_time = time()\n\timg = np.zeros((width,width,3),dtype=np.uint8)\n\tpwidth = 10\n\tfor i in range(width):\n\t\tnormali = i//pwidth\n\t\tfor j in range(width):\n\t\t\tnormalj = j//pwidth\n\t\t\tif(normali1:\n\t\tinputFileName = argv[1]\n\t\toutputFileName = argv[2]\n\twith open(inputFileName,'rb') as reader:\n\t\tdata=reader.read()\n\t#data = (\"Gettysburg Address\"\n\t#\t\t\"Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal. \"\n\t#\t\t\"Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this. \"\n\t#\t\t\"But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth.\"\n\t#\t\t\"Abraham Lincoln\"\n\t#\t\t\"November 19, 1863\")\n\t\n\tbinstring=\"\"\n\tkey = '1011'\n\t#begin_time = time()\n\tfor ch in data:\n\t\t#print(struct.unpack('B',ch))\n\t\tbinstring += CRC.generateCRC('{:08b}'.format(ch),key)\n\t#end_time = time()\n\t#run_time = end_time-begin_time\n\t#print ('该循环程序运行时间:',run_time)\n\tstartOrEnd = 170\n\tstartOrEndStr = \"\"\n\tfor i in range(8):\n\t\tstartOrEndStr += '{:08b}'.format(startOrEnd)\n\tbinstring = startOrEndStr + binstring\n\tbinstring = binstring + startOrEndStr\n\n\tgenBlankFrame()\n\tnum = 1\n\n\twhile(binstring):\n\t\t#mat = np.zeros([width, width, 3], np.uint8)\n\t\tmat = np.full((width,width,3),255,dtype=np.uint8)\n\t\t#mat = [[255 for i in range(width)]for j in range(width)]\n\t\tdrawLocPoint(mat)\n\t\t#begin_time = time()\n\t\tbinstring=encode(mat,binstring)\n\t\tgenImage(mat,width*10,\"./video/\"+str(num)+\".png\")\n\t\t#end_time = time()\n\t\t#run_time = end_time-begin_time\n\t\t#print ('该循环程序运行时间:',run_time)\n\t\tnum+=1\n\t\tprint(len(binstring))\n\timgToVideo(\"./video/in.avi\",num)\n\nif __name__==\"__main__\":\n\tmain(sys.argv)\n\t#num = 165\n\t#imgToVideo(\"./video/in.avi\",num)","sub_path":"encodeCL.py","file_name":"encodeCL.py","file_ext":"py","file_size_in_byte":7683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"526954266","text":"from flask import Flask, flash, redirect, render_template, request, session, abort\n# from bokeh.embed import server_document\nimport pandas as pd\n\nfrom bokeh.layouts import row, column\nfrom bokeh.models import Select\nfrom bokeh.palettes import Spectral5\nfrom bokeh.plotting import curdoc, figure\nfrom bokeh.embed import components\nfrom bokeh.themes import Theme\nfrom bokeh.sampledata.autompg import autompg_clean as df\nfrom flask import Flask, render_template\nfrom bokeh.resources import INLINE\nfrom bokeh.util.string import encode_utf8\n\napp = Flask(__name__)\n\n@app.route(\"/\")\ndef hello():\n\n df = pd.read_csv('./TABLE_LOS.csv')\n\n df2 = pd.read_csv('./people.csv')\n\n SIZES = list(range(6, 22, 3))\n COLORS = Spectral5\n N_SIZES = len(SIZES)\n N_COLORS = len(COLORS)\n\n # data cleanup\n df.INSURANCE = df.INSURANCE.astype(str)\n df.RACE = df.RACE.astype(str)\n df.LANGUAGE = df.LANGUAGE.astype(str)\n df.MARITAL = df.MARITAL.astype(str)\n\n df2.INSURANCE = df2.INSURANCE.astype(str)\n df2.RACE = df2.RACE.astype(str)\n df2.LANGUAGE = df2.LANGUAGE.astype(str)\n df2.MARITAL = df2.MARITAL.astype(str)\n\n df['xPredict_INSURANCE'] = df2['INSURANCE']\n df['xPredict_RACE'] = df2['RACE']\n df['xPredict_LANGUAGE'] = df2['LANGUAGE']\n df['xPredict_MARITAL'] = df2['MARITAL']\n df['xPredict_LOS'] = df2['LOS']\n\n del df['PATIENT_ID']\n\n columns = sorted(df.columns)\n discrete = [x for x in columns if df[x].dtype == object]\n continuous = [x for x in columns if x not in discrete]\n\n\n def create_figure():\n xs = df[x.value].values\n ys = df[y.value].values\n x_title = x.value.title()\n y_title = y.value.title()\n\n kw = dict()\n if x.value in discrete:\n kw['x_range'] = sorted(set(xs))\n if y.value in discrete:\n kw['y_range'] = sorted(set(ys))\n kw['title'] = \"%s vs %s\" % (x_title, y_title)\n\n p = figure(plot_height=600, plot_width=800, tools='pan,box_zoom,hover,reset', **kw)\n p.xaxis.axis_label = x_title\n p.yaxis.axis_label = y_title\n\n if x.value in discrete:\n p.xaxis.major_label_orientation = pd.np.pi / 4\n\n sz = 9\n if size.value != 'None':\n if len(set(df[size.value])) > N_SIZES:\n groups = pd.qcut(df[size.value].values, N_SIZES, duplicates='drop')\n else:\n groups = pd.Categorical(df[size.value])\n sz = [SIZES[xx] for xx in groups.codes]\n\n c = \"#680000\"\n if color.value != 'None':\n if len(set(df[color.value])) > N_SIZES:\n groups = pd.qcut(df[color.value].values, N_COLORS, duplicates='drop')\n else:\n groups = pd.Categorical(df[color.value])\n c = [COLORS[xx] for xx in groups.codes]\n\n p.circle(x=xs, y=ys, color=c, size=sz, line_color=\"black\", alpha=0.6, hover_color='black', hover_alpha=0.5)\n\n return p\n\n\n def update(attr, old, new):\n layout.children[1] = create_figure()\n\n x = Select(title='X-Axis', value='INSURANCE', options=columns)\n x.on_change('value', update)\n\n y = Select(title='Y-Axis', value='RACE', options=columns)\n y.on_change('value', update)\n\n size = Select(title='Size', value='None', options=['None'] + continuous)\n size.on_change('value', update)\n\n color = Select(title='Color', value='None', options=['None'] + continuous)\n color.on_change('value', update)\n\n controls = column([x, y, color, size], width=200)\n layout = row(controls, create_figure())\n\n curdoc().add_root(layout)\n curdoc().title = \"LOS_Visualizer\"\n\n curdoc().theme = Theme(filename=\"./theme.yaml\")\n \n # layout1 = layout.children[1]\n\n # grab the static resources\n js_resources = INLINE.render_js()\n css_resources = INLINE.render_css()\n\n # render template\n script, div = components(layout)\n return render_template(\n 'index.html',\n plot_script=script,\n plot_div=div,\n js_resources=js_resources,\n css_resources=css_resources,\n )\n # return encode_utf8(html)\n\n # script, div = components(layout1)\n\n # # return render_template('index.html')\n # return render_template(\"index.html\",\n # div=div, script=script)\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"visualization_fixed/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"540638488","text":"import obd\nfrom gpiozero import PWMLED, Button\nfrom time import sleep\nfrom random import random\n\n# OBD commands\nspeed_cmd = obd.commands.SPEED # 0-50 kph, 0-120 kph in data\nrpm_cmd = obd.commands.RPM # 400 to 2200 RPM in data\n# throttle_cmd = obd.commands.THROTTLE_POS # throttle 0-40 % in data\nfuel_trim_cmd = obd.commands.SHORT_FUEL_TRIM_1 # -5 to 8 % in data\n\n# Setup GPIO\nvca = PWMLED(17, frequency=490)\nvcf = PWMLED(18, frequency=490)\nvco = PWMLED(22, frequency=490)\nlfo = PWMLED(23, frequency=490)\non_switch = Button(24, pull_up=True) # connect to GND\n\n# GPIO update vars\nvca_next_val = 0.0\nvcf_next_val = 0.0\nvco_next_val = 0.0\nlfo_next_val = 0.0\nvca_clipped_val = 0.0\nvcf_clipped_val = 0.0\nvco_clipped_val = 0.0\nlfo_clipped_val = 0.0\n\n\n# Setup OBD connection - keep trying till successful\nconnection = obd.OBD() # auto-connects\nprint(connection.status())\nspeed_resp = connection.query(speed_cmd, force=True)\nwhile speed_resp.is_null():\n connection = obd.OBD() # auto-connects\n print(connection.status())\n speed_resp = connection.query(speed_cmd, force=True)\n sleep(0.2)\n\n# switch on\non_switch.wait_for_press()\n\n# main\nwhile (True):\n\n # Speed + RPM to VCO\n speed_resp = connection.query(speed_cmd, force=True)\n # fuel_trim_resp = connection.query(fuel_trim_cmd, force=True)\n rpm_resp = connection.query(rpm_cmd, force=True)\n\n if speed_resp.is_null():\n print('speed_resp null')\n continue\n elif rpm_resp.is_null():\n print('rpm_resp null')\n continue\n # elif fuel_trim_resp.is_null():\n # print('fuel_trim_resp null')\n # continue\n\n speed_val = float(speed_resp.value.magnitude)\n rpm_val = float(rpm_resp.value.magnitude)\n # fuel_trim_val = float(fuel_trim_resp.value.magnitude)\n\n # Test\n # speed_val = 60\n # rpm_val = 2000\n # fuel_trim_val = 5.0\n\n\n vco_next_value = (speed_val / 100 + .3) + \\\n ((random() - .5) * (3.0/5)) * (rpm_val - 480) / 1720\n # vco_next_value = (speed_val / 100 + .3) \\\n # + ((fuel_trim_val + 9) / 20 - .5) * (3.0/5) * (rpm_val - 480) / 1720\n if vco_next_value > 1.0:\n vco_clipped_value = 1.0\n elif vco_next_value < 0:\n vco_clipped_value = 0.0\n else:\n vco_clipped_value = vco_next_value\n print('vco_next_value {}, vco_clipped_value {}'.format(vco_next_value, vco_clipped_value))\n vco.value = vco_clipped_value\n\n vca_next_value = vco_clipped_value + 0.1\n if vca_next_value > 1.0:\n vca_clipped_value = 1.0\n else:\n vca_clipped_value = vca_next_value\n print('vca_next_value {}, vca_clipped_value {}'.format(vca_next_value, vca_clipped_value))\n vca.value = vca_clipped_value\n\n # Fuel Trim to LFO\n lfo_next_value = (rpm_val - 480) / 1720\n if lfo_next_value > 1.0:\n lfo_clipped_value = 1.0\n elif lfo_next_value < 0:\n lfo_clipped_value = 0.0\n else:\n lfo_clipped_value = lfo_next_value\n print('lfo_next_value {}, lfo_clipped_value {}'.format(lfo_next_value, lfo_clipped_value))\n lfo.value = lfo_clipped_value\n\n sleep_val = (1.0 - (speed_val / 100)) * 0.3\n print('sleep val {}'.format(sleep_val))\n sleep(sleep_val)\n","sub_path":"car_synth_alg_switch.py","file_name":"car_synth_alg_switch.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"330542128","text":"\"\"\"add new table machines and relation with session table \n\nRevision ID: ce3e1caf870f\nRevises: cdf3906ffff2\nCreate Date: 2016-12-11 04:07:08.355552\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'ce3e1caf870f'\ndown_revision = 'cdf3906ffff2'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('machines',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=50), nullable=False),\n sa.Column('active', sa.Boolean(), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('name')\n )\n op.add_column('sessions', sa.Column('machine_id', sa.Integer(), nullable=True))\n op.create_foreign_key('sessions_machine_id_fkey', 'sessions', 'machines', ['machine_id'], ['id'], ondelete='SET NULL')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint('sessions_machine_id_fkey', 'sessions', type_='foreignkey')\n op.drop_column('sessions', 'machine_id')\n op.drop_table('machines')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/ce3e1caf870f_add_new_table_machines_and_relation_with_session_table.py","file_name":"ce3e1caf870f_add_new_table_machines_and_relation_with_session_table.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"180530420","text":"from enum import IntEnum\nimport random\nimport bank_database\n\n# 16 digits long card number\n# 1-6: IIN must be 400_000 (first six digits)\n# 7-15: Account number: unique (9 digits)\n# 16: Check digit or checksum\n\n\nclass MainMenu(IntEnum):\n Exit = 0\n CreateAccount = 1\n Login = 2\n\n\nclass BankMenu(IntEnum):\n Exit = 0\n ShowBalance = 1\n AddIncome = 2\n DoTransfer = 3\n CloseAccount = 4\n LogOut = 5\n\n\nclass NetBank:\n\n def __init__(self):\n self.card_num = None\n self.card_pin = None\n self.is_running = True\n self.bank_db = bank_database.DatabaseManager()\n self.bank_db.setup_table()\n random.seed()\n\n def print_main_menu(self):\n print(\"1. Create an account\")\n print(\"2. Log into account\")\n print(\"0. Exit\")\n\n def print_bank_menu(self):\n print(\"1. Balance\")\n print(\"2. Add income\")\n print(\"3. Do transfer\")\n print(\"4. Close account\")\n print(\"5. Log out\")\n print(\"0. Exit\")\n\n def print_card_creation(self):\n print(\"\\nYour card has been created\")\n print(\"Your card number:\")\n print(self.card_num)\n print(\"Your card PIN:\")\n print(self.card_pin)\n print()\n\n def generate_card_number(self):\n \"\"\"\n :return: 16 chars long digit of digits\n \"\"\"\n\n card_num_string = \"400000\" # 6 digits long\n card_num_string += self.generate_account_number() # 15-digits long\n\n # Generate check number from current card numbers\n card_numbers = [int(x) for x in card_num_string]\n processed_nums = self.process_numbers(card_numbers)\n check_number = self.get_check_digit(processed_nums)\n\n card_num_string += str(check_number) # 16 digits long\n return card_num_string\n\n def generate_account_number(self):\n account_number = \"\"\n for _ in range(0, 9):\n account_number += str(random.randint(0, 9))\n return account_number\n\n def process_numbers(self, numbers):\n \"\"\"\n Luhn algorithm\n 1. Drop the last digit\n 2. Multiply odd digits by 2\n 3. Subtract numbers over 9 by 9\n 4. Add all numbers\n 5. Modulus 10\n\n Result: if 0, return true, otherwise return false\n \"\"\"\n\n # Not necessary when auto generating\n # numbers.pop()\n\n for i in range(0, len(numbers), 2):\n numbers[i] *= 2\n numbers = [x - 9 if x > 9 else x for x in numbers]\n return numbers\n\n def get_check_digit(self, card_nums):\n num_sum = sum(card_nums)\n\n check_digit = 0\n while True:\n if (num_sum + check_digit) % 10 == 0:\n break\n check_digit += 1\n return check_digit\n\n def generate_pin(self):\n pin = \"\"\n for _ in range(0, 4):\n pin += str(random.randint(0, 9))\n return pin\n\n def is_card_num_valid(self, a_card_num_str):\n a_card_num_str = a_card_num_str.strip()\n card_number = [int(x) for x in a_card_num_str]\n\n # if len(card_number) != 16:\n # return False\n\n check_digit = card_number.pop()\n card_number.reverse()\n\n processed_digits = []\n\n for index, digit in enumerate(card_number):\n if index % 2 == 0:\n doubled_digit = digit * 2\n\n if doubled_digit > 9:\n doubled_digit -= 9\n\n processed_digits.append(doubled_digit)\n else:\n processed_digits.append(digit)\n\n check_sum = check_digit + sum(processed_digits)\n if check_sum % 10 != 0:\n return False\n return True\n\n def do_transfer(self):\n print(\"\\nTransfer\\nEnter card number:\")\n input_card_number = input().strip()\n\n # Luhn algorithm test\n if not self.is_card_num_valid(input_card_number):\n print(\"\\nProbably you made a mistake in the card number. Please try again!\\n\")\n return\n\n if input_card_number == self.card_num:\n print(\"\\nYou can't transfer money to the same account!\\n\")\n return\n\n target_account = self.bank_db.get_target_account(input_card_number)\n\n if target_account is None:\n print(\"Such a card does not exist.\\n\")\n return\n\n print(\"Enter how much money you want to transfer:\")\n money = int(input())\n balance = self.bank_db.get_balance(self.card_num, self.card_pin)[0]\n\n if money > balance:\n print(\"Not enough money!\\n\")\n return\n\n # Subtract money from user balance\n self.bank_db.update_balance(-money, self.card_num, self.card_pin)\n\n # Add money to target balance\n target_num = target_account[1]\n target_pin = target_account[2]\n target_balance = target_account[3]\n target_balance += money\n self.bank_db.update_balance(target_balance, target_num, target_pin)\n print(\"Success!\\n\")\n\n def login(self):\n while True:\n self.print_bank_menu()\n login_input = int(input())\n\n if login_input == BankMenu.Exit:\n self.is_running = False\n break\n elif login_input == BankMenu.ShowBalance:\n balance = self.bank_db.get_balance(self.card_num, self.card_pin)[0]\n print(f\"\\nBalance: {balance}\\n\")\n elif login_input == BankMenu.AddIncome:\n print(\"\\nEnter income:\")\n income = int(input())\n self.bank_db.update_balance(income, self.card_num, self.card_pin)\n print(\"Income was added!\\n\")\n elif login_input == BankMenu.DoTransfer:\n self.do_transfer()\n elif login_input == BankMenu.CloseAccount:\n self.bank_db.close_account(self.card_num, self.card_pin)\n self.card_num = None\n self.card_pin = None\n print(\"\\nThe account has been closed!\\n\")\n break\n elif login_input == BankMenu.LogOut:\n print(\"\\nYou have successfully logged out!\\n\")\n break\n\n def run(self):\n while self.is_running:\n self.print_main_menu()\n user_input = int(input())\n\n if user_input == MainMenu.Exit:\n self.is_running = False\n elif user_input == MainMenu.CreateAccount:\n self.card_num = self.generate_card_number()\n self.card_pin = self.generate_pin()\n self.print_card_creation()\n self.bank_db.insert_new_card(self.card_num, self.card_pin)\n elif user_input == MainMenu.Login:\n print(\"\\nEnter your card number:\")\n user_card = input()\n print(\"Enter your PIN:\")\n user_pin = input()\n account = self.bank_db.get_account(user_card, user_pin)\n if account is None:\n print(\"\\nWrong card number or PIN!\\n\")\n # print(f\"account: {account}\")\n else:\n self.card_num = account[1]\n self.card_pin = account[2]\n print(\"\\nYou have successfully logged in!\\n\")\n self.login()\n\n self.bank_db.close()\n print(\"\\nBye!\")\n","sub_path":"Simple Banking System/task/banking/bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":7346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"285510729","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Dec 5 12:06:37 2019\n\n@author: kristyna\n\"\"\"\n\n# =============================================================================\n# Class Background for moving sky\n# =============================================================================\n\nimport pygame\nimport os \n\nBG_IMG = pygame.transform.scale(pygame.image.load(os.path.join(\"imgs\", \"Nebe.png\")), (1200,700))\n\n\nclass Background:\n BG_WIDTH = BG_IMG.get_width()\n BG_IMG = BG_IMG\n\n def __init__(self,y):\n self.y = y\n self.x1 = 0\n self.x2 = self.BG_WIDTH\n \n def move(self, vel):\n self.vel = vel\n self.x1 -= vel/5\n self.x2 -= vel/5\n if self.x1 + self.BG_WIDTH < 0:\n self.x1 = self.x2 + self.BG_WIDTH\n if self.x2 + self.BG_WIDTH < 0:\n self.x2 = self.x1 + self.BG_WIDTH\n\n def draw(self, win):\n win.blit(self.BG_IMG, (self.x1, self.y))\n win.blit(self.BG_IMG, (self.x2, self.y))","sub_path":"Background_cls.py","file_name":"Background_cls.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"436691168","text":"from ..protocol import BaseProtocol\n\n\nclass AutodiscoverProtocol(BaseProtocol):\n \"\"\"Protocol which implements the bare essentials for autodiscover.\"\"\"\n\n TIMEOUT = 10 # Seconds\n\n def __str__(self):\n return '''\\\nAutodiscover endpoint: %s\nAuth type: %s''' % (\n self.service_endpoint,\n self.auth_type,\n )\n","sub_path":"exchangelib/autodiscover/protocol.py","file_name":"protocol.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"428751607","text":"from gamelib import *\r\n\r\ndef hideAll():\r\n Idle.visible=False\r\n Shoot.visible=False\r\n Rocket.visible=False\r\n Slash.visible=False\r\n Pain.visible=False\r\n #Bullet.visible=False\r\n #RocketAmmo.visible=False\r\n #Boom.visible=False\r\n #Nuke.visible=False\r\n\r\n########################################################## \r\ngame=Game (900,800,\"Last one standing\")\r\n\r\nbk=Image(\"images\\\\Forest.png\",game)\r\ngame.setBackground(bk)\r\nbk.resizeTo(game.width,game.height)\r\n\r\nJeep=Image(\"images\\\\jeep.png\",game)\r\nIdle=Animation(\"images\\\\Idle.gif\",8,game,786/8,135,frate=5)\r\nShoot=Animation(\"images\\\\Shoot.gif\",8,game,809/8,133,frate=3)\r\nRocket=Animation(\"images\\\\Rocket.gif\",13,game,794/6,367/3,frate=5)\r\nSlash=Animation(\"images\\\\Slash.png\",7,game,960/5,384/2,frate=5)\r\nPain=Animation(\"images\\\\Pain.gif\" ,5,game,465/5,126,frate=5)\r\nAim=Image(\"images\\\\Aim.png\",game)\r\nBoom=Animation(\"images\\\\Boom.png\",20,game,785/5,916/4,frate=3)\r\nBullet=Image(\"images\\\\bullet.jpg\",game)\r\nRocketAmmo=Image(\"images\\\\RocketAmmo.png\",game)\r\nNuke=Image(\"images\\\\Nuke.gif\",game)\r\n\r\ngun=Sound(\"sound\\\\GunSound.wav\",1)\r\nrocket=Sound(\"sound\\\\Arcade Explo A.wav\",2)\r\nbackground=Sound(\"sound\\\\Left 4 Dead - Witch.wav\",3)\r\n############################################################\r\nZombies=[]\r\n\r\nfor times in range(100):\r\n Zombies.append(Image(\"images\\\\Alive.png\",game))\r\n \r\nfor z in Zombies:\r\n x = randint(950,10000)\r\n y = randint(600,750)\r\n z.moveTo(x,y)\r\n \r\n z.setSpeed(2,90)\r\n#######################################################\r\n\"\"\"\r\nNukes=[]\r\nfor times in range(50):\r\n Nukes=Image(\"images\\\\Nuke.gif\",game)\r\n\r\nfor n in Nukes:\r\n x = randint(100,700)\r\n y = -randint(100,5000)\r\n s = randint(1,3)\r\n n.moveTo(x,y)\r\n n.setSpeed(s,180)\"\"\"\r\n################################################\r\nIdle.resizeBy(30)\r\nIdle.setSpeed(6,60)\r\nIdle.moveTo(75,640)\r\n\r\nJeep.resizeBy(20)\r\nJeep.moveTo(-3.5,720)\r\n\r\nShoot.resizeBy(30)\r\nShoot.moveTo(75,640)\r\n\r\nRocket.resizeBy(30)\r\nRocket.moveTo(75,640)\r\n \r\nPain.resizeBy(30)\r\nPain.moveTo(75,640)\r\n\r\nSlash.moveTo(75,640)\r\n\r\nz.resizeBy(10)\r\nAim.resizeBy(-80)\r\nBoom.moveTo(z.x,z.y)\r\n\r\nBullet.resizeBy(-92.5)\r\nRocketAmmo.resizeBy(-75)\r\n\r\n\"\"\"Nuke.resizeBy(-90)\"\"\"\r\n\r\n#######################################################\r\nprint(\"Startup Screen\")\r\ngame.scrollBackground(\"right\",3)\r\ngame.drawText(\"Last One Standing\",game.width/4 ,game.height/4,Font(black,90,red))\r\ngame.drawText(\"Press [SPACE] to Start\",game.width/2 + 80,game.height - 50,Font(green,40,black))\r\nbackground.play()\r\ngame.update()\r\ngame.wait(K_SPACE)\r\n\r\nstatus = \"Idle\"\r\nprint(\"Game Begins\")\r\nBullet.setSpeed(10,-90)\r\nBullet.visible= False\r\n\r\nRocketAmmo.setSpeed(10,-90)\r\nRocketAmmo.visible= False\r\n\r\nkills = 0\r\nIdle.health=100\r\nShoot.health=200\r\n######################################################\r\nwhile not game.over:\r\n game.processInput()\r\n game.scrollBackground(\"right\",3)\r\n hideAll()\r\n Jeep.draw()\r\n Aim.draw()\r\n Boom.draw(False)\r\n Bullet.moveTowards(mouse,10)\r\n RocketAmmo.moveTowards(mouse,10)\r\n \"\"\"for n in Nukes:\r\n n.move()\"\"\"\r\n print(\"In Game\")\r\n###################################################### \r\n for z in Zombies:\r\n z.move()\r\n if z.collidedWith(RocketAmmo, \"rectangle\"):\r\n Boom.moveTo(z.x,z.y)\r\n Boom.visible=True\r\n Boom.f=0\r\n z.visible= False\r\n RocketAmmo.visible=False\r\n kills += 1\r\n if z.collidedWith(Idle,\"rectangle\"):\r\n z.visible= False \r\n Slash.visible=True\r\n status = \"Pain\"\r\n Idle.health-=3\r\n if z.collidedWith(Jeep,\"rectangle\"):\r\n z.visible= False \r\n Slash.visible=True\r\n status = \"Pain\"\r\n Idle.health-=3\r\n if z.collidedWith(Shoot,\"rectangle\"):\r\n z.visible= False\r\n Slash.visible=True\r\n status = \"Pain\"\r\n Idle.health-=3\r\n if z.collidedWith(Rocket,\"rectangle\"):\r\n z.visible= False\r\n Slash.visible=True\r\n status = \"Pain\"\r\n Idle.health-=3\r\n if z.collidedWith(Bullet, \"rectangle\"):\r\n z.visible= False\r\n Bullet.visible=False\r\n kills += 1\r\n if z.collidedWith(Boom, \"rectangle\"):\r\n z.visible=False\r\n kills +=1\r\n############################################################# \r\n Aim.moveTo (mouse.x, mouse.y)\r\n if mouse.LeftButton and Shoot.health >0:\r\n Shoot.moveTo(Idle.x,Idle.y)\r\n Shoot.visible=True\r\n Shoot.draw()\r\n Shoot.health-=0.5\r\n Bullet.visible=True\r\n Bullet.moveTo(Idle.x, Idle.y)\r\n gun.play()\r\n elif mouse.RightButton and Shoot.health >0:\r\n Rocket.moveTo(Idle.x,Idle.y)\r\n Rocket.visible=True\r\n Rocket.draw()\r\n Shoot.health-=1\r\n RocketAmmo.visible=True\r\n RocketAmmo.moveTo(Idle.x, Idle.y)\r\n rocket.play()\r\n else: \r\n if status == \"Pain\":\r\n Pain.moveTo(Idle.x,Idle.y)\r\n Pain.visible=True\r\n Pain.draw(False)\r\n if Pain.visible == False:\r\n status = \"Idle\"\r\n else:\r\n Idle.visible=True\r\n Idle.draw()\r\n \r\n \"\"\"if keys.Pressed[K_q]:\r\n n.visible=True\r\n n.moveTo(z.x,z.y)\"\"\"\r\n \r\n################################################################\r\n if Idle.health <0 or Shoot.health <0 :\r\n game.over=True\r\n################################################################ \r\n Slash.draw()\r\n game.drawText(\"Health:\" + str(Idle.health),5,10)\r\n game.drawText(\"Ammo:\" + str(Shoot.health),112,10)\r\n game.drawText(\"Kills:\" + str (kills),210,10)\r\n game.update(70)\r\n###############################################################\r\n game.drawText(\"Game Over\",game.width/4 ,game.height/4,Font(black,90,red))\r\n game.drawText(\"Press [ESC] to Exit\",game.width/2 + 80,game.height - 50,Font(green,40,black))\r\ngame.update()\r\ngame.wait(K_ESCAPE)\r\n \r\ngame.quit()\r\n","sub_path":"Last one standing.py","file_name":"Last one standing.py","file_ext":"py","file_size_in_byte":6117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"556306318","text":"\n\"\"\"\nModule for construction of D0->KSKS taged and untaged (stripping Selections and StrippingLines.\nProvides functions to build, KS->LL (from StdLooseKsLL), KS->DD (from StdLooseKsDD), D0->KSLL KSLL (D0LL), D0->KSLL KSDD (D0LD) and D0->KSDD KSDD (D0DD) selections.\nProvides class D02KSKSConf, which constructs the Selections and StrippingLines\ngiven a configuration dictionary.\nUnder usage of the KS-cut variable\nnu'_2 = log((piplus_BPVIPCHI2*piminus_BPVIPCHI2)/(KS0_BPVIPCHI2^2 + KS0_DOCAMAX^2))\nExported symbols (use python help!):\n - D02KSKSConf\n\"\"\"\n\n__author__ = ['Markward Britsch','Marianna Fontana', 'Michael Sokoloff']\n__date__ = '15/05/2014'\n__version__ = 'Stripping23'\n__all__ = 'D02KSKSConf'\n\nfrom Gaudi.Configuration import *\nfrom GaudiConfUtils.ConfigurableGenerators import FilterDesktop, CombineParticles\nfrom PhysSelPython.Wrappers import Selection, DataOnDemand, MergedSelection\nfrom StrippingConf.StrippingLine import StrippingLine\nfrom StrippingUtils.Utils import LineBuilder\n\nfrom StandardParticles import StdAllNoPIDsPions as Pions\n#from StandardParticles import StdNoPIDsPions as Pions\n#from StandardParticles import StdLoosePions as Pions\nfrom StandardParticles import StdNoPIDsDownPions as DownPions\nfrom StandardParticles import StdNoPIDsUpPions as UpPions\n#from StandardParticles import StdLooseKaons as Kaons\n\n\ndefault_config = {\n 'NAME' : 'D02KSKS',\n 'WGs' : ['Charm'],\n 'BUILDERTYPE' : 'D02KSKSConf',\n 'CONFIG' : {'D0_MassWindowBeforeFit' : 150.0, # D0 mass window cut in MeV before vertex fit\n 'D0_MassWindow' : 100.0, # D0 mass window cut in MeV \n 'D0_DOCA_LL' : 1.0, # DOCA cut in mm for D0->KSLL KSLL\n 'D0_DOCA_DD' : 4.0, # DOCA cut in mm for D0->KSLL KSDD and D0->KSDD KSDD\n 'KS_LL_nu2prime' : 0.0, # nu'_2 = log((piplus_BPVIPCHI2*piminus_BPVIPCHI2)/(KS0_BPVIPCHI2^2 + KS0_DOCAMAX^2)), preselection cut for KsLL\n 'KS_LL_signedFLchi2' : 50.0, # KsLL siged flight length chi2 preselection cut\n 'KS_LL_TRGHOSTPROB'\t\t : 1.0,\t\t# Track ghost probability KSLL\n 'KS_DD_nu2prime' : 0.0, # nu'_2, preselection cut for KsLL\n 'KS_DD_signedFLchi2' : 50.0, # KsDD siged flight length chi2 preselection cut\n 'KS_DD_TRGHOSTPROB'\t\t : 1.0,\t\t# Track ghost probability KSDD\n \n 'D0_vertexChi2_LL' : 20.0, # D0LL reduced vertex chi2 cut\n 'D0_IPchi2_LL' : 50.0, # D0LL IP chi2 cut\n 'D0_KS_signedFLchi2_LL' : 200.0, # D0LL signed flight length of the Ks\n 'D0_signedFLchi2_LL' : -1.0, # D0LL signed flight length chi2 cut\n \n 'D0_vertexChi2_LD' : 20.0, # D0LD reduced vertex chi2 cut\n 'D0_IPchi2_LD' : 10.0, # D0LD IP chi2 cut\n 'D0_KSLL_signedFLchi2_LD' : 500.0, # D0LD signed flight length of the KsLL cut\n 'D0_signedFLchi2_LD' : 1.0, # D0LD signed flight length chi2 cut\n \n 'D0_vertexChi2_DD' : 20.0, # D0DD reduced vertex chi2 cut\n 'D0_IPchi2_DD' : 10.0, # D0DD IP chi2 cut\n 'D0_KS_nu2prime' : 4.0, # D0DD KS nu'_2 cut\n 'D0_lnPt_DD' : 21.0, # D0DD ln(D0_PT*KS0_PT*KS00_PT)\n \n 'slowPi_IPchi2_LL' : 40.0, # slow pi IP chi2 cut for LL\n 'slowPi_IPchi2_LD' : 40.0, # slow pi IP chi2 cut for LD\n 'slowPi_IPchi2_DD' : 40.0, # slow pi IP chi2 cut for DD\n\t\n 'slowPi_LLL_TRGHOSTPROB'\t : 1.0, # Track ghost probability slow pi LL\n 'slowPi_LDL_TRGHOSTPROB'\t : 1.0, # Track ghost probability slow pi LD\n 'slowPi_DDL_TRGHOSTPROB'\t : 1.0, # Track ghost probability slow pi DD\n \n 'slowPi_LLU_TRGHOSTPROB'\t : 1.0, # Track ghost probability slow pi LL\n 'slowPi_LDU_TRGHOSTPROB'\t : 1.0, # Track ghost probability slow pi LD\n 'slowPi_DDU_TRGHOSTPROB'\t : 1.0, # Track ghost probability slow pi DD\n\t\n 'Dst_mass_LL' : 200, # mass window on D* cut LL in MeV\n 'Dst_mass_LD' : 200, # mass window on D* cut LD in MeV\n 'Dst_mass_DD' : 200, # mass window on D* cut DD in MeV\n 'Dst_vertexChi2_LL' : 40.0, # Dst reduces vertex chi2 cut LL\n 'Dst_vertexChi2_LD' : 40.0, # Dst reduces vertex chi2 cut LD\n 'Dst_vertexChi2_DD' : 40.0, # Dst reduces vertex chi2 cut DD\n\n 'Dst_massDiffLow_LL' : 135, # m_D* - m_D0 low mass difference cut in MeV\n 'Dst_massDiffHigh_LL' : 160, # m_D* - m_D0 high mass difference cut in MeV\n 'Dst_massDiffLow_LD' : 135, # m_D* - m_D0 low mass difference cut in MeV\n 'Dst_massDiffHigh_LD' : 160, # m_D* - m_D0 high mass difference cut in MeV\n 'Dst_massDiffLow_DD' : 135, # m_D* - m_D0 low mass difference cut in MeV\n 'Dst_massDiffHigh_DD' : 160, # m_D* - m_D0 high mass difference cut in MeV\n \n 'PrescaleLL' : 1.0,\n 'PostscaleLL' : 1.0,\n 'PrescaleLD' : 1.0,\n 'PostscaleLD' : 1.0,\n 'PrescaleDD' : 1.0,\n 'PostscaleDD' : 1.0,\n \n 'DstPrescaleLL' : 1.0,\n 'DstPostscaleLL' : 1.0,\n 'DstPrescaleLD' : 1.0,\n 'DstPostscaleLD' : 1.0,\n 'DstPrescaleDD' : 1.0,\n 'DstPostscaleDD' : 1.0\n \n },\n 'STREAMS' : ['Charm']\n }\n\nclass D02KSKSConf(LineBuilder) :\n \"\"\"\n Builder of D0->KSKS stripping Selection and StrippingLine.\n Constructs D0 -> KS KS Selections and StrippingLines from a configuration dictionary.\n Usage:\n >>> config = { .... }\n >>> bs2ksksConf = D02KSKSConf('D02KSKSTest',config)\n >>> bs2ksksLines = bs2ksksConf.lines\n >>> for line in line :\n >>> print line.name(), line.outputLocation()\n The lines can be used directly to build a StrippingStream object.\n\n Exports as instance data members:\n\n selKS2LL : KS -> Long Long Selection object\n\n selKS2DD : KS -> Downstream Downstream Selection object\n\n selD02KSLLKSLL : D0 -> KS(LL) KS(LL) Selection object\n ll_line : StrippingLine made out of selD02KSLLKSLL\n lines : List of lines, [ll_line]\n\n selD02KSLLKSDD : D0 -> KS(LL) KS(DD) Selection object\n ld_line : StrippingLine made out of selD02KSLLKSDD\n lines : List of lines, [ld_line]\n\n selD02KSDDKSDD : D0 -> KS(DD) KS(DD) Selection object\n dd_line : StrippingLine made out of selD02KSDDKSDD\n lines : List of lines, [dd_line]\n\n selDst2D0LL_L : D*+ -> pi+(L) (D0 -> KS(LL) KS(LL)) Selection object\n Dst_ll_l_line : StrippingLine made out of selD02KSLLKSLL\n lines : List of lines, [Dst_ll_l_line]\n\n selDst2D0LD_L : D*+ -> pi+(L) (D0 -> KS(LL) KS(DD)) Selection object\n Dst_ld_l_line : StrippingLine made out of selD02KSLLKSDD\n lines : List of lines, [Dst_ld_l_line]\n\n selDst2D0DD_L : D*+ -> pi+(L) (D0 -> KS(DD) KS(DD)) Selection object\n Dst_dd_l_line : StrippingLine made out of selD02KSDDKSDD\n lines : List of lines, [Dst_dd_l_line]\n\n selDst2D0LL_U : D*+ -> pi+(U) (D0 -> KS(LL) KS(LL)) Selection object\n Dst_ll_u_line : StrippingLine made out of selD02KSLLKSLL\n lines : List of lines, [Dst_ll_u_line]\n\n selDst2D0LD_U : D*+ -> pi+(U) (D0 -> KS(LL) KS(DD)) Selection object\n Dst_ld_u_line : StrippingLine made out of selD02KSLLKSDD\n lines : List of lines, [Dst_ld_u_line]\n\n selDst2D0DD_U : D*+ -> pi+(U) (D0 -> KS(DD) KS(DD)) Selection object\n Dst_dd_u_line : StrippingLine made out of selD02KSDDKSDD\n lines : List of lines, [Dst_dd_u_line]\n\n Exports as class data member:\n D02KSKSConf.__configuration_keys__ : List of required configuration parameters.\n \"\"\"\n\n __configuration_keys__ = ('D0_MassWindowBeforeFit',\n 'D0_MassWindow',\n 'D0_DOCA_LL',\n 'D0_DOCA_DD',\n 'KS_LL_nu2prime',\n 'KS_LL_signedFLchi2',\n\t\t\t 'KS_LL_TRGHOSTPROB',\n 'KS_DD_nu2prime',\n 'KS_DD_signedFLchi2',\n\t\t\t 'KS_DD_TRGHOSTPROB',\n 'D0_vertexChi2_LL',\n 'D0_IPchi2_LL',\n 'D0_KS_signedFLchi2_LL', # signed flight length of the Ks\n 'D0_signedFLchi2_LL',\n 'D0_vertexChi2_LD',\n 'D0_IPchi2_LD',\n 'D0_KSLL_signedFLchi2_LD', # signed flight length of the KsLL\n 'D0_signedFLchi2_LD',\n 'D0_vertexChi2_DD',\n 'D0_IPchi2_DD',\n 'D0_KS_nu2prime', # nu'_2\n 'D0_lnPt_DD', # ln(D0_PT*KS0_PT*KS00_PT)\n 'slowPi_IPchi2_LL', # slow pi IP chi2 cut for LL\n 'slowPi_IPchi2_LD', # slow pi IP chi2 cut for LD\n 'slowPi_IPchi2_DD', # slow pi IP chi2 cut for DD\n\t\t\t 'slowPi_LLL_TRGHOSTPROB', \n \t\t\t 'slowPi_LDL_TRGHOSTPROB',\n \t\t\t 'slowPi_DDL_TRGHOSTPROB',\n \t\t\t 'slowPi_LLU_TRGHOSTPROB', \n \t\t\t 'slowPi_LDU_TRGHOSTPROB',\n \t\t\t 'slowPi_DDU_TRGHOSTPROB', \n 'Dst_mass_LL', # mass window on D* cut LL\n 'Dst_mass_LD', # mass window on D* cut LD\n 'Dst_mass_DD', # mass window on D* cut DD\n 'Dst_vertexChi2_LL', # Dst reduces vertex chi2 cut LL\n 'Dst_vertexChi2_LD', # Dst reduces vertex chi2 cut LD\n 'Dst_vertexChi2_DD', # Dst reduces vertex chi2 cut DD\n 'Dst_massDiffLow_LL',\n 'Dst_massDiffHigh_LL',\n 'Dst_massDiffLow_LD',\n 'Dst_massDiffHigh_LD',\n 'Dst_massDiffLow_DD',\n 'Dst_massDiffHigh_DD',\n 'PrescaleLL',\n 'PostscaleLL',\n 'PrescaleLD',\n 'PostscaleLD',\n 'PrescaleDD',\n 'PostscaleDD',\n 'DstPrescaleLL',\n 'DstPostscaleLL',\n 'DstPrescaleLD',\n 'DstPostscaleLD',\n 'DstPrescaleDD',\n 'DstPostscaleDD'\n )\n\n def __init__(self, name, config) :\n\n LineBuilder.__init__(self, name, config)\n\n ll_name = name+'LL'\n dd_name = name+'DD'\n ld_name = name+'LD'\n ll_l_name = name+'LL_L'\n ll_u_name = name+'LL_U'\n dd_l_name = name+'DD_L'\n dd_u_name = name+'DD_U'\n ld_l_name = name+'LD_L'\n ld_u_name = name+'LD_U'\n\n #GECCode = {'Code' : \"(recSummaryTrack(LHCb.RecSummary.nLongTracks, TrLONG) < %s)\" % config['GEC_MaxTracks'],\n # 'Preambulo' : [\"from LoKiTracks.decorators import *\"]}\n\n self.pions = Pions\n self.down_pions = DownPions\n self.up_pions = UpPions\n# no Kaons anymore self.kaons = Kaons\n\n# self.hadrons = MergedSelection(\"HadronsFor\" + name,\n# RequiredSelections = [ self.pions, self.kaons ] )\n\n # no merged selection required , because Kaon+/- are no longer considered\n\n# D0 lineKs creation:\n# self.makeKS2DD( 'KSfor'+dd_name, config )\n self.makeKS2LL( 'KSfor'+ll_name, config )\n self.makeKS2DD( 'KSfor'+dd_name, config )\n\n\n# D0 lines:\n# self.makeD02KSDDhh( dd_name, config )\n self.makeD02KSLLKSLL( ll_name, config )\n\n\n self.ll_line = StrippingLine(ll_name+\"Line\",\n prescale = config['PrescaleLL'],\n postscale = config['PostscaleLL'],\n selection = self.selD02KSLLKSLL#,\n #FILTER = GECCode\n )\n\n# self.registerLine(self.dd_line)\n self.registerLine(self.ll_line)\n\n self.makeD02KSLLKSDD( ld_name, config )\n\n\n self.ld_line = StrippingLine(ld_name+\"Line\",\n prescale = config['PrescaleLD'],\n postscale = config['PostscaleLD'],\n selection = self.selD02KSLLKSDD#,\n #FILTER = GECCode\n )\n\n# self.registerLine(self.dd_line)\n self.registerLine(self.ld_line)\n\n self.makeD02KSDDKSDD( dd_name, config )\n\n\n self.dd_line = StrippingLine(dd_name+\"Line\",\n prescale = config['PrescaleDD'],\n postscale = config['PostscaleDD'],\n selection = self.selD02KSDDKSDD#,\n #FILTER = GECCode\n )\n\n# self.registerLine(self.dd_line)\n self.registerLine(self.dd_line)\n\n# Dst lines with LONG slow pion:\n self.makeDst2D0LL_L( 'Dst'+ll_l_name, config )\n self.Dst_ll_l_line = StrippingLine('Dst'+ll_l_name+\"Line\",\n prescale = config['DstPrescaleLL'],\n postscale = config['DstPostscaleLL'],\n selection = self.selDst2D0LL_L#,\n #FILTER = GECCode\n )\n self.registerLine(self.Dst_ll_l_line)\n\n self.makeDst2D0LD_L( 'Dst'+ld_l_name, config )\n self.Dst_ld_l_line = StrippingLine('Dst'+ld_l_name+\"Line\",\n prescale = config['DstPrescaleLD'],\n postscale = config['DstPostscaleLD'],\n selection = self.selDst2D0LD_L#,\n #FILTER = GECCode\n )\n self.registerLine(self.Dst_ld_l_line)\n\n self.makeDst2D0DD_L( 'Dst'+dd_l_name, config )\n self.Dst_dd_l_line = StrippingLine('Dst'+dd_l_name+\"Line\",\n prescale = config['DstPrescaleDD'],\n postscale = config['DstPostscaleDD'],\n selection = self.selDst2D0DD_L#,\n #FILTER = GECCode\n )\n self.registerLine(self.Dst_dd_l_line)\n\n# Dst lines with UP slow pion:\n self.makeDst2D0LL_U( 'Dst'+ll_u_name, config )\n self.Dst_ll_u_line = StrippingLine('Dst'+ll_u_name+\"Line\",\n prescale = config['DstPrescaleLL'],\n postscale = config['DstPostscaleLL'],\n selection = self.selDst2D0LL_U#,\n #FILTER = GECCode\n )\n self.registerLine(self.Dst_ll_u_line)\n\n self.makeDst2D0LD_U( 'Dst'+ld_u_name, config )\n self.Dst_ld_u_line = StrippingLine('Dst'+ld_u_name+\"Line\",\n prescale = config['DstPrescaleLD'],\n postscale = config['DstPostscaleLD'],\n selection = self.selDst2D0LD_U#,\n #FILTER = GECCode\n )\n self.registerLine(self.Dst_ld_u_line)\n\n self.makeDst2D0DD_U( 'Dst'+dd_u_name, config )\n self.Dst_dd_u_line = StrippingLine('Dst'+dd_u_name+\"Line\",\n prescale = config['DstPrescaleDD'],\n postscale = config['DstPostscaleDD'],\n selection = self.selDst2D0DD_U#,\n #FILTER = GECCode\n )\n self.registerLine(self.Dst_dd_u_line)\n\n\n def makeKS2LL( self, name, config ) :\n# # define all the cuts\n#\n# #1st daughters cuts \n#\n#\n# # before vretex fit cuts \n#\n## _DaughterCuts = {\"pi-\" : _cut_prob_KNDL,\n## \"pi+\" : _cut_prob_KPDL}\n## _DaughterCuts = {\"pi+\" : \"(P>2*GeV)\"}\n#\n# _CombinationCuts = \"(ACUTDOCA(1.0*mm,'')) & (ADAMASS('KS0')<50*MeV)\"\n#\n#\n#\n## _trkChi2Cut1 = \"(CHILDCUT((TRCHI2DOF<%s),1))\" % config['Trk_Chi2']\n## _trkChi2Cut2 = \"(CHILDCUT((TRCHI2DOF<%s),2))\" % config['Trk_Chi2']\n# _MotherCuts = \"PT>-100\"\n#\n# ########## EndCuts definition\n#\n#\n#\n# # make the Ks from StdAllNoPIDsPions\n# _Ks = CombineParticles( DecayDescriptor = \"KS0 -> pi+ pi-\" ,\n# #DaughtersCuts = _DaughterCuts,\n# CombinationCut = _CombinationCuts,\n# MotherCut = _MotherCuts)\n#\n#\n ## get the KS's to filter\n _stdKSLL = DataOnDemand( Location = \"Phys/StdLooseKsLL/Particles\" )\n #_allCuts = \"(DOCAMAX < 1.0*mm) & (ADMASS('KS0')<50*MeV)\"\n #_doca_cut = \"(DOCAMAX < %s*mm)\" % config['KS_LL_DOCA']\n #_mass_cut = \"(ADMASS('KS0')<%s*MeV)\" % config['KS_LL_MASS']\n _nu2prime_cut = \"(log((CHILD(BPVIPCHI2(),1)*CHILD(BPVIPCHI2(),2))/(BPVIPCHI2()*BPVIPCHI2() + DOCAMAX*DOCAMAX)) > %s)\" % config['KS_LL_nu2prime'] # 0\n _signedFLchi2_cut = \"(BPVLTSIGNCHI2() > %s)\" % config['KS_LL_signedFLchi2'] # 50\n _trghost_cut1 = \"(CHILD(TRGHOSTPROB, 1) <=%s )\" % config['KS_LL_TRGHOSTPROB']\n _trghost_cut2 = \"(CHILD(TRGHOSTPROB, 2) <=%s )\" % config['KS_LL_TRGHOSTPROB']\n\t\n _allCuts = _nu2prime_cut + \"&\" + _signedFLchi2_cut + \"&\" + _trghost_cut1 + \"&\" + _trghost_cut2\n \n ## make the filter\n _filterKSLL = FilterDesktop( Code = _allCuts )\n\n # make and store the Selection object\n #self.selKS2LL = Selection( \"selKS2LL_\" + name, Algorithm = _Ks, RequiredSelections = [ self.pions ] )\n #self.selKS2LL = Selection( \"selKS2LL_\" + name, Algorithm = _Ks, RequiredSelections = [ _selPions] )\n self.selKS2LL = Selection( \"selKS2LL_\" + name, Algorithm = _filterKSLL, RequiredSelections = [_stdKSLL] )\n\n\n def makeKS2DD( self, name, config ) :\n\n # define all the cuts\n\n #1st daughters cuts \n\n\n # before vretex fit cuts \n\n\n# #_DaughterCuts = {\"pi+\" : \"(P>2*GeV) & (MIPDV(PRIMARY)<100.*mm) & (PT>200*MeV)\"}\n# _DaughterCuts = {}\n# \n# _CombinationCuts = \"(ACUTDOCA(4.0*mm,'')) & (ADAMASS('KS0')<100*MeV)\"\n#\n#\n#\n## _trkChi2Cut1 = \"(CHILDCUT((TRCHI2DOF<%s),1))\" % config['Trk_Chi2']\n## _trkChi2Cut2 = \"(CHILDCUT((TRCHI2DOF<%s),2))\" % config['Trk_Chi2']\n# _MotherCuts = \"PT>-100\"\n#\n# ########## EndCuts definition\n#\n#\n#\n# # make the Ks from StdAllNoPIDsPions\n# _Ks = CombineParticles( DecayDescriptor = \"KS0 -> pi+ pi-\" ,\n# DaughtersCuts = _DaughterCuts,\n# CombinationCut = _CombinationCuts,\n# MotherCut = _MotherCuts)\n#\n # get the KS's to filter\n _stdKSDD = DataOnDemand( Location = \"Phys/StdLooseKsDD/Particles\" )\n# _allCuts = \"(DOCAMAX<4.0*mm) & (ADMASS('KS0')<100*MeV)\" \n# _doca_cut = \"(DOCAMAX < %s*mm)\" % config['KS_DD_DOCA']\n# _mass_cut = \"(ADMASS('KS0')<%s*MeV)\" % config['KS_DD_MASS']\n# _allCuts = _doca_cut + \"&\" + _mass_cut\n _nu2prime_cut = \"(log((CHILD(BPVIPCHI2(),1)*CHILD(BPVIPCHI2(),2))/(BPVIPCHI2()*BPVIPCHI2() + DOCAMAX*DOCAMAX)) > %s)\" % config['KS_DD_nu2prime'] # 0\n _signedFLchi2_cut = \"(BPVLTSIGNCHI2() > %s)\" % config['KS_DD_signedFLchi2'] # 50\n _trghost_cut1 = \"(CHILD(TRGHOSTPROB, 1) <=%s )\" % config['KS_DD_TRGHOSTPROB']\n _trghost_cut2 = \"(CHILD(TRGHOSTPROB, 2) <=%s )\" % config['KS_DD_TRGHOSTPROB']\n\t\n _allCuts = _nu2prime_cut + \"&\" + _signedFLchi2_cut + \"&\" + _trghost_cut1 + \"&\" + _trghost_cut2\n\n # make the filter\n _filterKSDD = FilterDesktop( Code = _allCuts )\n\n # make and store the Selection object\n #self.selKS2DD = Selection( \"selKS2DD_\" + name, Algorithm = _Ks, RequiredSelections = [ self.down_pions ] )\n self.selKS2DD = Selection( \"selKS2DD_\" + name, Algorithm = _filterKSDD, RequiredSelections = [_stdKSDD] )\n\n\n def makeD02KSDDKSDD( self, name, config ) :\n \"\"\"\n Create and store a D0 -> KS(DD) KS(DD) Selection object.\n Arguments:\n name : name of the Selection.\n config : config dictionary\n \"\"\"\n\t# The following lines were produced automatically; preambuloProbDef should be put into the preambulo of CombineParticles\n\n _daughterCuts = \"(log((CHILD(BPVIPCHI2(),1)*CHILD(BPVIPCHI2(),2))/(BPVIPCHI2()*BPVIPCHI2() + DOCAMAX*DOCAMAX)) > %s)\" % config['D0_KS_nu2prime'] # 4 # nu'_2\n\n # before D vertex fit \n _doca_cut = \"(ACUTDOCA(%s*mm,''))\" % config['D0_DOCA_DD']\n _massBefore_cut = \"(ADAMASS('D0') < %s*MeV)\" % config['D0_MassWindowBeforeFit'] # 150\n _combCuts = _doca_cut + \"&\" + _massBefore_cut\n #_combCuts = \"(ACUTDOCA(4.0*mm,'')) & (ADAMASS('D0') < 600*MeV)\"\n\n _vertexChi2_cut = \"(VFASPF(VCHI2/VDOF) < %s)\" % config['D0_vertexChi2_DD'] # 20\n _IPchi2_cut = \"(BPVIPCHI2() < %s)\" % config['D0_IPchi2_DD'] # 10\n _lnPt_cut = \"(log(PT*CHILD(PT,1)*CHILD(PT,2)) > %s) \" % config['D0_lnPt_DD'] # 21\n _mass_cut = \"(ADMASS('D0') < %s*MeV)\" % config['D0_MassWindow'] # 100\n \n _motherCuts = _vertexChi2_cut + \"&\" + _IPchi2_cut + \"&\" + _lnPt_cut + \"&\" + _mass_cut\n \n _D = CombineParticles()\n _D.DecayDescriptors = [ \"D0 -> KS0 KS0\" ]\n \n _D.CombinationCut = _combCuts\n _D.DaughtersCuts = { \"KS0\" : _daughterCuts }\n #_D.DaughtersCuts = _daughterCuts\n _D.MotherCut = _motherCuts\n\n# _Preambulo = preambuloDef_prob_BCu\n# print 'B combCuts: ',_combCuts\n# print 'B motherCuts: ',_motherCuts\n# print 'prescale: ',prescale\n\n# _D.Preambulo = _Preambulo\n self.selD02KSDDKSDD = Selection (name, Algorithm = _D, RequiredSelections = [ self.selKS2DD ])\n \n def makeD02KSLLKSDD( self, name, config ) :\n \"\"\"\n Create and store a D0 -> KS(LL) KS(DD) Selection object.\n Arguments:\n name : name of the Selection.\n config : config dictionary\n \"\"\"\n \n KsKsLD_mother_cut = \"INTREE((ABSID=='pi+') & (ISLONG)) & INTREE((ABSID=='pi+') & (ISDOWN))\"\n\n _daughterCuts = \"(INTREE((ABSID=='pi+') & (ISDOWN)) | (BPVLTSIGNCHI2() > %s))\" % config['D0_KSLL_signedFLchi2_LD'] # 500, signed flight length of the KsLL\n \n # before D vertex fit \n _doca_cut = \"(ACUTDOCA(%s*mm,''))\" % config['D0_DOCA_DD']\n _massBefore_cut = \"(ADAMASS('D0') < %s*MeV)\" % config['D0_MassWindowBeforeFit']\n _combCuts = _doca_cut + \"&\" + _massBefore_cut\n #_combCuts = \"(ACUTDOCA(4.0*mm,'')) & (ADAMASS('D0') < 600*MeV)\"\n \n _vertexChi2_cut = \"(VFASPF(VCHI2/VDOF) < %s)\" % config['D0_vertexChi2_LD'] # 20\n _IPchi2_cut = \"(BPVIPCHI2() < %s)\" % config['D0_IPchi2_LD'] # 10\n _signedFLchi2_cut = \"(BPVLTSIGNCHI2() > %s)\" % config['D0_signedFLchi2_LD'] # 1.0\n _mass_cut = \"(ADMASS('D0') < %s*MeV)\" % config['D0_MassWindow'] # 100\n\n _motherCuts = KsKsLD_mother_cut + \" & \" + _vertexChi2_cut + \" & \" + _IPchi2_cut + \" & \" + _signedFLchi2_cut + \" & \" + _mass_cut\n \n _D = CombineParticles()\n _D.DecayDescriptors = [ \"D0 -> KS0 KS0\" ]\n \n #_D.DaughtersCuts = _daughterCuts\n _D.DaughtersCuts = { \"KS0\" : _daughterCuts }\n _D.CombinationCut = _combCuts #+ \" & \" + ? #_cut_prob_BCC\n _D.MotherCut = _motherCuts\n\n# _Preambulo = preambuloDef_prob_BCC + preambuloDef_prob_BCu\n# print 'B combCuts: ',_combCuts\n# print 'B motherCuts: ',_motherCuts\n# print 'prescale: ',prescale\n\n# _B.Preambulo = _Preambulo\n self.selD02KSLLKSDD = Selection (name, Algorithm = _D, RequiredSelections = [ self.selKS2LL, self.selKS2DD ])\n\n def makeD02KSLLKSLL( self, name, config ) :\n \"\"\"\n Create and store a B -> KS(LL) KS(LL) Selection object.\n Arguments:\n name : name of the Selection.\n config : config dictionary\n \"\"\"\n\n \n _daughterCuts = \"(BPVLTSIGNCHI2() > %s)\" % config['D0_KS_signedFLchi2_LL'] # 200, signed flight length of the Ks\n \n # before D vertex fit\n _doca_cut = \"(ACUTDOCA(%s*mm,''))\" % config['D0_DOCA_LL']\n _massBefore_cut = \"(ADAMASS('D0') < %s*MeV)\" % config['D0_MassWindowBeforeFit']\n _combCuts = _doca_cut + \"&\" + _massBefore_cut\n ##_combCuts = \"(ACUTDOCA(1.0*mm,'')) & (ADAMASS('D0') < 600*MeV)\"\n \n _vertexChi2_cut = \"(VFASPF(VCHI2/VDOF) < %s)\" % config['D0_vertexChi2_LL'] # 20\n _IPchi2_cut = \"(BPVIPCHI2() < %s)\" % config['D0_IPchi2_LL'] # 50\n _signedFLchi2_cut = \"(BPVLTSIGNCHI2() > %s)\" % config['D0_signedFLchi2_LL'] # -1.0\n _mass_cut = \"(ADMASS('D0') < %s*MeV)\" % config['D0_MassWindow'] # 100\n\n _motherCuts = _vertexChi2_cut + \" & \" + _IPchi2_cut + \" & \" + _signedFLchi2_cut + \" & \" + _mass_cut # _cut_prob_BCu\n \n _D = CombineParticles()\n _D.DecayDescriptors = [ \"D0 -> KS0 KS0\" ]\n \n _D.DaughtersCuts = { \"KS0\" : _daughterCuts }\n #_D.DaughtersCuts = _daughterCuts\n _D.CombinationCut = _combCuts #+ \" & \" + ? # _cut_prob_BCC\n _D.MotherCut = _motherCuts\n\n self.selD02KSLLKSLL = Selection (name, Algorithm = _D, RequiredSelections = [ self.selKS2LL ] )\n\n def makeDst2D0LL_L( self, name, config ) :\n \"\"\"\n Create and store a Dst+ -> pi+ (D0 -> KS(LL) KS(LL)) Selection object.\n Arguments:\n name : name of the Selection.\n config : config dictionary\n \"\"\"\n\n #_daughterCuts = \"(BPVIPCHI2() < %s)\" % config['D0_IPchi2_LL'] # 40\n _daughterCuts = \"(TRGHOSTPROB <=%s )\" % config['slowPi_LLL_TRGHOSTPROB']\n \n _vertexChi2_cut = \"(VFASPF(VCHI2/VDOF) < %s)\" % config['Dst_vertexChi2_LL'] # 40\n\n _combCuts = \"(ADAMASS('D*(2010)+') < %s*MeV)\" % config['Dst_mass_LL'] # 200\n _massDiffLow_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) > %s*MeV)\" % config['Dst_massDiffLow_LL'] # 135\n _massDiffHigh_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) < %s*MeV)\" % config['Dst_massDiffHigh_LL'] # 160\n #_motherCuts = _vertexChi2_cut + \" & \" + _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n _motherCuts = _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n \n _D = CombineParticles()\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> (D0-> (KS0 -> pi+ pi-) (KS0 -> pi+ pi-)) pi+]cc\" ]\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> D0 pi+]cc\" ]\n _D.DecayDescriptors = [ \"D*(2010)+ -> D0 pi+\", \"D*(2010)- -> D0 pi-\" ]\n \n _D.DaughtersCuts = { \"pi+\" : _daughterCuts }\n _D.CombinationCut = _combCuts #+ \" & \" + ? # _cut_prob_BCC\n _D.MotherCut = _motherCuts\n\n self.selDst2D0LL_L = Selection (name, Algorithm = _D, RequiredSelections = [ self.pions, self.selD02KSLLKSLL ] )\n\n def makeDst2D0LL_U( self, name, config ) :\n \"\"\"\n Create and store a Dst+ -> pi+ (D0 -> KS(LL) KS(LL)) Selection object.\n Arguments:\n name : name of the Selection.\n config : config dictionary\n \"\"\"\n\n #_daughterCuts = \"(BPVIPCHI2() < %s)\" % config['D0_IPchi2_LL'] # 40\n _daughterCuts = \"(TRGHOSTPROB <=%s )\" % config['slowPi_LLU_TRGHOSTPROB']\n\n _vertexChi2_cut = \"(VFASPF(VCHI2/VDOF) < %s)\" % config['Dst_vertexChi2_LL'] # 40\n\n _combCuts = \"(ADAMASS('D*(2010)+') < %s*MeV)\" % config['Dst_mass_LL'] # 200\n _massDiffLow_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) > %s*MeV)\" % config['Dst_massDiffLow_LL'] # 135\n _massDiffHigh_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) < %s*MeV)\" % config['Dst_massDiffHigh_LL'] # 160\n #_motherCuts = _vertexChi2_cut + \" & \" + _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n _motherCuts = _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n \n _D = CombineParticles()\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> (D0-> (KS0 -> pi+ pi-) (KS0 -> pi+ pi-)) pi+]cc\" ]\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> D0 pi+]cc\" ]\n _D.DecayDescriptors = [ \"D*(2010)+ -> D0 pi+\", \"D*(2010)- -> D0 pi-\" ]\n \n _D.DaughtersCuts = { \"pi+\" : _daughterCuts }\n _D.CombinationCut = _combCuts #+ \" & \" + ? # _cut_prob_BCC\n _D.MotherCut = _motherCuts\n\n self.selDst2D0LL_U = Selection (name, Algorithm = _D, RequiredSelections = [ self.up_pions, self.selD02KSLLKSLL ] )\n\n def makeDst2D0LD_L( self, name, config ) :\n \"\"\"\n Create and store a Dst+ -> pi+ (D0 -> KS(LL) KS(DD)) Selection object.\n Arguments:\n name : name of the Selection.\n config : config dictionary\n \"\"\"\n\n #_daughterCuts = \"(BPVIPCHI2() < %s)\" % config['D0_IPchi2_LD'] # 40\n _daughterCuts = \"(TRGHOSTPROB <=%s )\" % config['slowPi_LDL_TRGHOSTPROB']\n \n _vertexChi2_cut = \"(VFASPF(VCHI2/VDOF) < %s)\" % config['Dst_vertexChi2_LD'] # 40\n\n _combCuts = \"(ADAMASS('D*(2010)+') < %s*MeV)\" % config['Dst_mass_LD'] # 200\n _massDiffLow_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) > %s*MeV)\" % config['Dst_massDiffLow_LD'] # 135\n _massDiffHigh_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) < %s*MeV)\" % config['Dst_massDiffHigh_LD'] # 160\n #_motherCuts = _vertexChi2_cut + \" & \" + _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n _motherCuts = _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n \n _D = CombineParticles()\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> (D0-> (KS0 -> pi+ pi-) (KS0 -> pi+ pi-)) pi+]cc\" ]\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> D0 pi+]cc\" ]\n _D.DecayDescriptors = [ \"D*(2010)+ -> D0 pi+\", \"D*(2010)- -> D0 pi-\" ]\n \n _D.DaughtersCuts = { \"pi+\" : _daughterCuts }\n _D.CombinationCut = _combCuts #+ \" & \" + ? # _cut_prob_BCC\n _D.MotherCut = _motherCuts\n\n self.selDst2D0LD_L = Selection (name, Algorithm = _D, RequiredSelections = [ self.pions, self.selD02KSLLKSDD ] )\n\n def makeDst2D0LD_U( self, name, config ) :\n \"\"\"\n Create and store a Dst+ -> pi+ (D0 -> KS(LL) KS(DD)) Selection object.\n Arguments:\n name : name of the Selection.\n config : config dictionary\n \"\"\"\n\n #_daughterCuts = \"(BPVIPCHI2() < %s)\" % config['D0_IPchi2_LD'] # 40\n _daughterCuts = \"(TRGHOSTPROB <=%s )\" % config['slowPi_LDU_TRGHOSTPROB']\n\n \n _vertexChi2_cut = \"(VFASPF(VCHI2/VDOF) < %s)\" % config['Dst_vertexChi2_LD'] # 40\n\n _combCuts = \"(ADAMASS('D*(2010)+') < %s*MeV)\" % config['Dst_mass_LD'] # 200\n _massDiffLow_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) > %s*MeV)\" % config['Dst_massDiffLow_LD'] # 135\n _massDiffHigh_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) < %s*MeV)\" % config['Dst_massDiffHigh_LD'] # 160\n #_motherCuts = _vertexChi2_cut + \" & \" + _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n _motherCuts = _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n \n _D = CombineParticles()\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> (D0-> (KS0 -> pi+ pi-) (KS0 -> pi+ pi-)) pi+]cc\" ]\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> D0 pi+]cc\" ]\n _D.DecayDescriptors = [ \"D*(2010)+ -> D0 pi+\", \"D*(2010)- -> D0 pi-\" ]\n \n _D.DaughtersCuts = { \"pi+\" : _daughterCuts }\n _D.CombinationCut = _combCuts #+ \" & \" + ? # _cut_prob_BCC\n _D.MotherCut = _motherCuts\n\n self.selDst2D0LD_U = Selection (name, Algorithm = _D, RequiredSelections = [ self.up_pions, self.selD02KSLLKSDD ] )\n\n def makeDst2D0DD_L( self, name, config ) :\n \"\"\"\n Create and store a Dst+ -> pi+ (D0 -> KS(DD) KS(DD)) Selection object.\n Arguments:\n name : name of the Selection.\n config : config dictionary\n \"\"\"\n\n #_daughterCuts = \"(BPVIPCHI2() < %s)\" % config['D0_IPchi2_DD'] # 40\n _daughterCuts = \"(TRGHOSTPROB <=%s )\" % config['slowPi_DDL_TRGHOSTPROB']\n \n _vertexChi2_cut = \"(VFASPF(VCHI2/VDOF) < %s)\" % config['Dst_vertexChi2_DD'] # 40\n\n _combCuts = \"(ADAMASS('D*(2010)+') < %s*MeV)\" % config['Dst_mass_DD'] # 200\n _massDiffLow_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) > %s*MeV)\" % config['Dst_massDiffLow_DD'] # 135\n _massDiffHigh_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) < %s*MeV)\" % config['Dst_massDiffHigh_DD'] # 160\n #_motherCuts = _vertexChi2_cut + \" & \" + _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n _motherCuts = _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n \n _D = CombineParticles()\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> (D0-> (KS0 -> pi+ pi-) (KS0 -> pi+ pi-)) pi+]cc\" ]\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> D0 pi+]cc\" ]\n _D.DecayDescriptors = [ \"D*(2010)+ -> D0 pi+\", \"D*(2010)- -> D0 pi-\" ]\n \n _D.DaughtersCuts = { \"pi+\" : _daughterCuts }\n _D.CombinationCut = _combCuts #+ \" & \" + ? # _cut_prob_BCC\n _D.MotherCut = _motherCuts\n\n self.selDst2D0DD_L = Selection (name, Algorithm = _D, RequiredSelections = [ self.pions, self.selD02KSDDKSDD ] )\n\n def makeDst2D0DD_U( self, name, config ) :\n \"\"\"\n Create and store a Dst+ -> pi+ (D0 -> KS(DD) KS(DD)) Selection object.\n Arguments:\n name : name of the Selection.\n config : config dictionary\n \"\"\"\n\n #_daughterCuts = \"(BPVIPCHI2() < %s)\" % config['D0_IPchi2_DD'] # 40\n _daughterCuts = \"(TRGHOSTPROB <=%s )\" % config['slowPi_DDU_TRGHOSTPROB']\n \n _vertexChi2_cut = \"(VFASPF(VCHI2/VDOF) < %s)\" % config['Dst_vertexChi2_DD'] # 40\n\n _combCuts = \"(ADAMASS('D*(2010)+') < %s*MeV)\" % config['Dst_mass_DD'] # 200\n _massDiffLow_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) > %s*MeV)\" % config['Dst_massDiffLow_DD'] # 135\n _massDiffHigh_cut = \"(switch(CHILD(ABSID, 2) == 211, MM - CHILD(MM,1), MM - CHILD(MM,2)) < %s*MeV)\" % config['Dst_massDiffHigh_DD'] # 160\n #_motherCuts = _vertexChi2_cut + \" & \" + _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n _motherCuts = _massDiffLow_cut + \" & \" + _massDiffHigh_cut\n \n _D = CombineParticles()\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> (D0-> (KS0 -> pi+ pi-) (KS0 -> pi+ pi-)) pi+]cc\" ]\n #_D.DecayDescriptors = [ \"[D*(2010)+ -> D0 pi+]cc\" ]\n _D.DecayDescriptors = [ \"D*(2010)+ -> D0 pi+\", \"D*(2010)- -> D0 pi-\" ]\n \n _D.DaughtersCuts = { \"pi+\" : _daughterCuts }\n _D.CombinationCut = _combCuts #+ \" & \" + ? # _cut_prob_BCC\n _D.MotherCut = _motherCuts\n\n self.selDst2D0DD_U = Selection (name, Algorithm = _D, RequiredSelections = [ self.up_pions, self.selD02KSDDKSDD ] )\n","sub_path":"DaVinciDev_v38r1p1/InstallArea/x86_64-slc6-gcc49-opt/python/StrippingArchive/Stripping24/StrippingCharm/StrippingD02KSKS.py","file_name":"StrippingD02KSKS.py","file_ext":"py","file_size_in_byte":36566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"353903916","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\nclass SoftDecisionTree(torch.nn.Module):\n\n def __init__(self, args):\n super(SoftDecisionTree, self).__init__()\n \n #figure out args\n #in the future: calculate a way to do convolution sizes depending on features\n\n self.nodes = []\n self.leaves = []\n\n self.args = args\n \n self.nLeaves = 2**args.max_depth\n \n self.nNodes = self.node_calc()\n \n D_out = 1\n \n hidden_features = 10\n \n \n self.mu = (1/self.nLeaves)*torch.ones([self.args.batch_size,self.nLeaves], requires_grad=True).to(device)\n self.pi = (1/self.args.output_dim)*torch.ones([self.nLeaves,self.args.output_dim], requires_grad=True).to(device)\n self.cal_P()\n\n #pre-tree NN\n self.conv1 = nn.Conv2d(1, 20, 5, 1).to(device)\n self.bn1 = nn.BatchNorm2d(20).to(device)\n \n self.conv2 = nn.Conv2d(20, 50, 5, 1).to(device)\n self.bn2 = nn.BatchNorm2d(50).to(device)\n self.fc1 = nn.Linear(4*4*50, hidden_features).to(device)\n self.bn3 = nn.BatchNorm1d(hidden_features).to(device)\n \n #tree NN\n self.theta = torch.nn.ModuleList([torch.nn.Linear(hidden_features, D_out) for i in range(self.nNodes)]).to(device)\n self.bnt = torch.nn.ModuleList([torch.nn.BatchNorm1d(D_out) for i in range(self.nNodes)]).to(device)\n\n self.root = Node(1, self.args,self)\n\n def forward(self, x,y):\n \"\"\"\n In the forward function we accept a Tensor of input data and we must return\n a Tensor of output data. We can use Modules defined in the constructor as\n well as arbitrary operators on Tensors.\n \"\"\"\n # if phase is 'train':\n # self.dTree.mu = self.dTree.mu_train\n # self.dTree.pi = self.dTree.iter_pi(self.dTree.P,self.dTree.pi,self.dTree.mu)\n # elif phase is 'val':\n # self.dTree.mu = self.dTree.mu_val\n \n x = F.relu(self.bn1(self.conv1(x)))\n x = F.max_pool2d(x, 2, 2)\n x = F.relu(self.bn2(self.conv2(x)))\n x = F.max_pool2d(x, 2, 2)\n x = x.view(-1, 4*4*50)\n x = F.relu(self.bn3(self.fc1(x)))\n \n # return x\n self.mu = (1/self.nLeaves)*torch.ones([x.size(0),self.nLeaves], requires_grad=True).to(device)\n self.path_prob_init = torch.ones(x.size(0), 1, requires_grad=True).to(device)\n self.root.cal_prob(x, self.path_prob_init) ## GG figure out how to use nodes during forward phase\n\n # calculate new probability\n self.cal_pi(y)\n self.cal_P()\n\n P_log = torch.log(self.P)\n return P_log\n\n def node_calc(self):\n nNodes = 0\n for i in range(self.args.max_depth): nNodes += 2**i\n return nNodes\n \n def cal_pi(self, y):\n \n #we have a normalization problem with values that are not updated\n pi_holder = torch.zeros(len(self.leaves),self.args.output_dim)\n \n for l in range(len(self.leaves)):\n for i in range(len(y)):\n y_i = int(y[i])\n pi_holder[l,y_i] = pi_holder[l,y_i]+(self.pi[l,y_i]*self.mu[i,l]/self.P[i,y_i])\n z = torch.sum(pi_holder[l,:])\n self.pi[l,:] = pi_holder[l,:]/z\n\n def cal_P(self):\n self.P = torch.matmul(self.mu,self.pi)\n self.P = torch.autograd.Variable(self.P, requires_grad = True)\n\nclass Node():\n\n def __init__(self, depth, args, tree):\n tree.nodes.append(self)\n self.node_n = len(tree.nodes)-1\n # print(f\"node number {len(tree.nodes)}\")\n self.tree = tree\n self.args = args\n self.fc = tree.theta[self.node_n]\n\n self.leaf = False\n self.prob = None\n\n self.build_child(depth)\n\n def build_child(self, depth):\n if depth < self.args.max_depth:\n self.left = Node(depth+1, self.args,self.tree)\n self.right = Node(depth+1, self.args,self.tree)\n else :\n self.left = Leaf(self.args,self.tree)\n self.right = Leaf(self.args,self.tree)\n\n def cal_prob(self, x, path_prob):\n self.prob = torch.sigmoid(self.fc(x)) #probability of selecting right node\n # self.path_prob = path_prob #path_prob is the probability route\n self.left.cal_prob(x, path_prob * (1-self.prob))\n self.right.cal_prob(x, path_prob * self.prob)\n\nclass Leaf():\n def __init__(self, args,tree):\n tree.leaves.append(self)\n self.leaf_n = len(tree.leaves)-1\n self.args = args\n self.leaf = True\n self.tree = tree\n\n def cal_prob(self, x, path_prob):\n \n self.tree.mu[:,self.leaf_n] = path_prob.squeeze()\n ","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"640935405","text":"import sys\r\nimport time\r\nimport threading\r\n\r\nclass _Getch:\r\n def __init__(self):\r\n try:\r\n self.impl = _GetchWindows()\r\n except ImportError:\r\n self.impl = _GetchUnix()\r\n\r\n def __call__(self): return self.impl()\r\n\r\nclass _GetchUnix:\r\n def __init__(self):\r\n import tty, sys\r\n\r\n def __call__(self):\r\n import sys, tty, termios\r\n fd = sys.stdin.fileno()\r\n old_settings = termios.tcgetattr(fd)\r\n try:\r\n tty.setraw(sys.stdin.fileno(), termios.TCSANOW)\r\n ch = sys.stdin.read(1)\r\n sys.stdout.write(ch)\r\n finally:\r\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\r\n return ch\r\n\r\nclass _GetchWindows:\r\n def __init__(self):\r\n import msvcrt\r\n\r\n def __call__(self):\r\n import msvcrt\r\n return msvcrt.getch()\r\n\r\ngetch = _Getch()\r\nMyThread = None\r\n\r\nclass KeyboardEvent(threading.Thread):\r\n key = ''\r\n over = False\r\n\r\n def __init__(self):\r\n threading.Thread.__init__(self)\r\n\r\n def run(self):\r\n while not self.over:\r\n self.key = getch()\r\n time.sleep(1)\r\n\r\n def stop(self):\r\n self.over = True;\r\n\r\ndef StartKeyboardListener():\r\n global MyThread\r\n MyThread = KeyboardEvent()\r\n MyThread.start()\r\n\r\ndef KeyDown():\r\n global MyThread\r\n key = MyThread.key\r\n MyThread.key = ''\r\n return key\r\n\r\ndef StopKeyboardListener():\r\n global MyThread\r\n MyThread.stop()\r\n MyThread = None\r\n\r\nif __name__=='__main__':\r\n StartKeyboardListener()\r\n while True:\r\n if KeyDown() == 'q':\r\n break\r\n StopKeyboardListener()\r\n print('no')\r\n","sub_path":"HSICNN/CNN-python/ours/our_other_based/theano-based-8neithbor/Keyboard.py","file_name":"Keyboard.py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"100804897","text":"import numpy as np\nimport io\nimport gzip\nimport requests\n\ndef url_to_filepath(url):\n return url.replace('/', '_').replace(':', '_')\n\ndef check_for_existing_spec(init_path):\n # Build fetch spec and fetch\n fetch_spec = c3.FetchSpec(\n filter=\"startsWith(location, '{}')\".format(init_path),\n include=\"id, location\")\n file_sources_from_fetch = c3.FileSourceSpec.fetch(spec=fetch_spec)\n # Check if there's results\n if file_sources_from_fetch.objs is not None:\n if len(file_sources_from_fetch.objs) > 1:\n print(\"WARNING: Multiple compatible file sources exist for url {}\".format(this.url))\n source_id = file_sources_from_fetch.objs[0].id\n return c3.FileSourceSpec.get(source_id)\n else:\n return None\n\ndef numpy_from_idx(infile):\n bytecode_type_map = {\n 0x08: np.ubyte,\n 0x09: np.byte,\n 0x0B: np.short,\n 0x0C: np.intc,\n 0x0D: np.single,\n 0x0E: np.double,\n }\n\n # Open downloaded file using memory buffer.\n if int.from_bytes(infile.read(2), 'big') != 0:\n raise RuntimeError(\"Improperly formatted IDX file. First two bytes should be 0.\")\n\n data_type = int.from_bytes(infile.read(1), 'big')\n num_dimensions = int.from_bytes(infile.read(1), 'big')\n dimensions = []\n for i in range(num_dimensions):\n dimensions.append(int.from_bytes(infile.read(4), 'big'))\n\n total_len = 1\n for dim_len in dimensions:\n total_len *= dim_len\n\n itemsize = np.dtype(bytecode_type_map[data_type]).itemsize\n data = np.frombuffer(infile.read(itemsize*total_len), dtype=bytecode_type_map[data_type])\n\n return data.reshape(dimensions)\n\ndef getFileSourceSpec(this, enableLocalClientStorage):\n filepath = url_to_filepath(this.url)\n\n # First, check whether the file already exists\n spec = check_for_existing_spec(filepath)\n if spec is not None:\n return spec\n\n # Download IDX file\n r = requests.get(this.url) \n\n # Open downloaded file using memory buffer.\n with gzip.GzipFile(fileobj=io.BytesIO(r.content)) as infile:\n data = numpy_from_idx(infile)\n\n spec = c3.FileSourceCreateSpec(\n locationPrefix=\"{}\".format(filepath),\n enableLocalClientStorage=enableLocalClientStorage)\n return c3.FileSourceSpec.createFromNumpy(data, spec)\n\ndef getFileSourceSpecPreprocess(this, serializedPreprocessor, preprocessFuncName, enableLocalClientStorage):\n # Unpickle the preprocessor\n preprocessor = c3.PythonSerialization.deserialize(serializedPreprocessor)\n\n filepath = '-'.join([preprocessFuncName, url_to_filepath(this.url)])\n\n # Check whether the file already exists\n spec = check_for_existing_spec(filepath)\n if spec is not None:\n return spec\n\n # Download IDX file\n r = requests.get(this.url)\n\n # Open downloaded file using memory buffer.\n with gzip.GzipFile(fileobj=io.BytesIO(r.content)) as infile:\n data = numpy_from_idx(infile)\n\n preprocessed_data = preprocessor(data)\n if type(preprocessed_data) is not np.ndarray:\n raise RuntimeError(\"ERROR: Preprocessing function must return a numpy array!\")\n\n # Store numpy data as file spec\n spec = c3.FileSourceCreateSpec(\n locationPrefix=\"{}\".format(filepath),\n enableLocalClientStorage=enableLocalClientStorage)\n return c3.FileSourceSpec.createFromNumpy(preprocessed_data, spec)\n","sub_path":"c3/dtiTraining/mnistExample/src/types/IDXFile.py","file_name":"IDXFile.py","file_ext":"py","file_size_in_byte":3383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"223493426","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport re\nimport os.path\nfrom argparse import ArgumentParser\nfrom typing import Dict, Any, List, Optional, Tuple, DefaultDict\nfrom random import random\nfrom collections import defaultdict, namedtuple\n\nfrom utils.file_utils import read_by_file_suffix, make_dir\nfrom utils.constants import MODEL, SCHEDULED_MODEL, SCHEDULED_OPTIMIZED\nfrom utils.testing_utils import ClassificationMetric\nfrom plotting_constants import STYLE, MARKER_SIZE, LABEL_REGEX, LABEL_FORMAT, CAPSIZE\n\n\nMODEL_TYPE_REGEX = re.compile(r'.*model-.*test-log-([^-]+)-.*')\nLATENCY_FACTOR = 1000.0\n\nMetricPair = namedtuple('MetricPair', ['cost', 'metric', 'std'])\n\n\ndef get_model_type(test_log_file: str) -> str:\n match = MODEL_TYPE_REGEX.match(test_log_file)\n return match.group(1)\n\n\ndef get_metric_value(model_result: Dict[str, Any], metric: str, cost: str) -> MetricPair:\n if cost == 'latency':\n cost = model_result[ClassificationMetric.LATENCY.name] * LATENCY_FACTOR\n elif cost == 'flops':\n cost = model_result[ClassificationMetric.FLOPS.name]\n\n metric_value = model_result[metric.upper()]\n return MetricPair(cost=np.average(cost), metric=np.average(metric_value), std=np.std(metric_value))\n\n\ndef fetch_logs(test_log_files: List[str], metric: str, cost: str) -> DefaultDict[str, List[MetricPair]]:\n result: DefaultDict[str, List[Tuple[float, float]]] = defaultdict(list)\n\n for test_log_file in test_log_files:\n test_log = list(read_by_file_suffix(test_log_file))[0]\n model_type = get_model_type(test_log_file).capitalize()\n\n if MODEL in test_log:\n result[model_type].append(get_metric_value(test_log[MODEL], metric, cost))\n\n if SCHEDULED_MODEL in test_log:\n result[f'{model_type} Scheduled'].append(get_metric_value(test_log[SCHEDULED_MODEL], metric, cost))\n\n if SCHEDULED_OPTIMIZED in test_log:\n match = LABEL_REGEX.match(test_log_file)\n label = LABEL_FORMAT.format(match.group(1).capitalize(), match.group(2))\n result[f'{model_type} {label}'].append(get_metric_value(test_log[SCHEDULED_OPTIMIZED], metric, cost))\n\n # Compile all other predictions into one series\n for series in sorted(filter(lambda k: k.startswith('prediction'), test_log.keys())):\n result[model_type].append(get_metric_value(test_log[series], metric, cost))\n\n return result\n\n\ndef plot_tradeoff(model_results: Dict[str, List[MetricPair]], metric: str, cost: str, output_folder: Optional[str]):\n with plt.style.context(STYLE):\n fig, ax = plt.subplots()\n\n for series, result_list in sorted(model_results.items()):\n costs = [pair.cost for pair in result_list]\n metric_values = [pair.metric for pair in result_list]\n std = [pair.std for pair in result_list]\n\n # ax.plot(metric_values, costs, marker='o', markersize=MARKER_SIZE, label=series)\n\n ax.errorbar(metric_values, costs, xerr=std, yerr=0, marker='o', markersize=MARKER_SIZE, capsize=CAPSIZE, label=series)\n\n # Formatting for the Metric Name\n metric_tokens = [t.capitalize() for t in metric.split('_')]\n metric_label = ' '.join(metric_tokens)\n\n # Formatting for cost label\n cost_title_label = 'Latency' if cost == 'latency' else 'FLOP'\n cost_axis_label = 'Latency (ms)' if cost == 'latency' else 'FLOP (log scale)'\n\n # Set y-axis to a logarithmic scale if we are plotting FLOPS\n if cost == 'flops':\n ax.set_yscale('log', basey=2)\n\n ax.set_title('Tradeoff Curve for {0} vs {1}'.format(metric_label, cost_title_label))\n ax.set_xlabel(metric_label)\n ax.set_ylabel(cost_axis_label)\n ax.legend(fontsize='small')\n\n if output_folder is None:\n plt.show()\n else:\n make_dir(output_folder)\n output_file = os.path.join(output_folder, f'{metric}.png')\n plt.savefig(output_file)\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--test-logs', type=str, nargs='+')\n parser.add_argument('--metrics', type=str, nargs='+')\n parser.add_argument('--cost', type=str, required=True, choices=['latency', 'flops'])\n parser.add_argument('--output-folder', type=str)\n args = parser.parse_args()\n\n # Create plots\n for metric in args.metrics:\n model_results = fetch_logs(args.test_logs, metric, args.cost.lower())\n plot_tradeoff(model_results, metric, args.cost.lower(), args.output_folder)\n","sub_path":"src/plotting/plot_tradeoff_curves.py","file_name":"plot_tradeoff_curves.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"552187029","text":"\n# gdb -q -x gdb_helper.py\n\nimport gdb\ngdb.execute('file /root/test/test_binaries/static_small')\n\noutput = gdb.execute('break _start', to_string=True)\n\noutput = gdb.execute('display/i $pc', to_string=True)\n\noutput = gdb.execute('run', to_string=True)\n\ndebug_file = open(\"/root/test/test_binaries/gdb.log\", \"w\")\nfor i in range(10000):\n\toutput = gdb.execute('stepi', to_string=True)\n\tif(len(output) == 0):\n\t\tbreak\n\tdebug_file.write(output.split(\"\\n\")[1].split(\":\")[0] + \"\\n\")\n#\tdebug_file.write(gdb.execute('info registers eflags', to_string=True))\n\tdebug_file.write(gdb.execute('info registers rax', to_string=True))\n\ndebug_file.write(\"finish\")\ndebug_file.close()\n\n","sub_path":"dynamic/helper_scripts/gdb_helper.py","file_name":"gdb_helper.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"250129918","text":"# coding: utf-8\n'''\nWeixin UI库交互类\n'''\nimport sys,time,random\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom .locators import Locator\nfrom ...generic import Generic\nfrom ..actions import Action\nfrom ...conf import *\n\n\nclass Reserve(Action):\n\n XZ_USER_ID = 13765139\n\n def __init__(self,conf):\n self.mod = Locator.预约活动\n Action.__init__(self,conf,self.mod)\n\n def scroll_to(self,driver,key):\n '''\n 滚动到指定元素\n '''\n xpath = Locator.预约活动[key]\n js = \"\"\"var evaluator = new XPathEvaluator();var result = evaluator.evaluate('\"\"\" + xpath + \"\"\"', document.documentElement, null,XPathResult.ORDERED_NODE_ITERATOR_TYPE, null); var node = result.iterateNext();node.scrollIntoView();\"\"\"\n driver.execute_script(js)\n time.sleep(1)\n\n def check_reserve_list(self,reserveList):\n '''预约活动列表校验'''\n reserveNum = len(reserveList)\n print(\"reserveNum:\",reserveNum)\n i=0\n for i in range(reserveNum):\n #预约活动图片\n picture = self.get_attr(\"预约列表页面_预约图片\",attr='src')\n file_picture = reserveList[i]['wxImagetxtReply']['wxImagetxtReplyItems'][0]['documentLib']['file_cdn_path']\n assert picture == file_picture\n #预约活动名称\n title = self.get_text(\"预约列表页面_预约名称\",index=i+1)\n assert reserveList[i]['title'] == title\n #预约活动开始时间\n startTime = self.get_text(\"预约列表页面_活动开始时间\",index=i+1)\n startTimestr = reserveList[i]['start_time']\n time.strptime(startTime, '%Y-%m-%d %H:%M')\n localtime = time.localtime(startTimestr)\n new_starttime = time.strftime('%Y-%m-%d %H:%M',localtime)\n assert startTime == str(new_starttime)\n #预约活动结束时间\n endTime = self.get_text(\"预约列表页面_活动结束时间\",index=i+1)\n endTimestr = reserveList[i]['end_time']\n time.strptime(endTime, '%Y-%m-%d %H:%M')\n localtime = time.localtime(endTimestr)\n new_endtime = time.strftime('%Y-%m-%d %H:%M',localtime)\n assert endTime == str(new_endtime)\n\n def fill_user_info(self,userName,userPhone,message,identity_card):\n '''填写预约用户信息'''\n self.input(\"预约信息_姓名\",userName)\n self.choose(\"预约信息_性别\")\n self.input(\"预约信息_手机\",userPhone)\n self.input(\"预约信息_身份证\",identity_card)\n self.choose(\"预约信息_时间\")\n self.input(\"预约信息_留言\",message)\n self.choose(\"预约信息_预约店铺\")\n self.click(\"确定提交\")\n time.sleep(1)\n\n def check_user_info(self,joinList,userName, userPhone,message,identity_card):\n '''校验预约用户信息'''\n sucess_username = self.get_text(\"预约成功页面_姓名\")\n sucess_sex = self.get_text(\"预约成功页面_性别\")\n sucess_phone = self.get_text(\"预约成功页面_手机\")\n sucess_idcard = self.get_text(\"预约成功页面_身份证\")\n sucess_time = self.get_text(\"预约成功页面_预约时间\")\n sucess_reserveMessage = self.get_text(\"预约成功页面_留言\")\n sucess_reservesShop = self.get_text(\"预约成功页面_预约店铺\")\n assert sucess_username == userName\n assert sucess_phone == userPhone\n assert identity_card == sucess_idcard\n assert sucess_reserveMessage == message\n assert joinList[0][0]['name'] == sucess_username\n assert joinList[0][1]['name'] == sucess_sex\n assert joinList[0][2]['name'] == sucess_phone\n assert joinList[0][3]['name'] == sucess_idcard\n assert joinList[0][4]['name'] == sucess_time\n assert joinList[0][5]['name'] == sucess_reserveMessage\n assert joinList[0][6]['name'] == sucess_reservesShop\n\n","sub_path":"Test/wkd/lib/ui/weixin/market/reserve.py","file_name":"reserve.py","file_ext":"py","file_size_in_byte":4139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"501895273","text":"\"\"\"\nCopyright 2020 The OneFlow Authors. All rights reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\nimport numpy as np\nimport oneflow as flow\n\n\ndef my_test_source(name, out_num):\n return (\n flow.user_op_builder(name)\n .Op(\"TestSourceMultiGpuFixedOutNum\")\n .Output(\"out\")\n .Attr(\"out_num\", out_num)\n .Build()\n .InferAndTryRun()\n .RemoteBlobList()[0]\n )\n\n\ndef test_testsource_2_gpu(test_case):\n func_config = flow.FunctionConfig()\n func_config.default_data_type(flow.float)\n func_config.default_logical_view(flow.scope.consistent_view())\n\n @flow.global_function(function_config=func_config)\n def TestSourceJob():\n with flow.scope.placement(\"cpu\", \"0:0-1\"):\n ret = my_test_source(\"my_cc_test_source_op\", 10)\n # print(\"cons_test_source_batch_axis\", ret.batch_axis)\n test_case.assertTrue(ret.batch_axis is not None and ret.batch_axis == 0)\n return ret\n\n y = TestSourceJob().get().numpy()\n test_case.assertTrue(np.array_equal(y, np.append(np.arange(5.0), np.arange(5.0))))\n","sub_path":"oneflow/python/test/ops/test_TestSourceMultiGpuFixedOutNum.py","file_name":"test_TestSourceMultiGpuFixedOutNum.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"432056438","text":"from django.db import models, transaction\nfrom django.db.models import Count, Max\nfrom django.db.models.query import QuerySet\nfrom django.utils.translation import ugettext\n\n\n\nclass CourtSetupManager (models.Manager):\n def get_active (self, club):\n \"\"\"\n Returns the currently active court setup or None.-\n \"\"\"\n try:\n cid = club['id']\n except TypeError:\n #\n # club is an object\n #\n cid = club.id\n cs = self.filter (club__id=cid) \\\n .filter (is_active=True)\n cs = cs[0] if cs else None\n return cs\n \n \n def get_count (self, club):\n \"\"\"\n Returns the number of court setups contained in the\n received 'club'.-\n \"\"\"\n count = self.filter (club=club) \\\n .aggregate (Count ('id'))\n return int (count['id__count'])\n \n \n @transaction.commit_on_success\n def activate (self, court_setup):\n \"\"\"\n Marks the received court setup as active, deactivating\n all others, as there always should be strictly one\n active court setup.-\n \"\"\"\n #\n # deactivate all court setups owned by the same club\n #\n for cs in self.filter (club=court_setup.club).iterator ( ):\n cs.is_active = False\n cs.save ( )\n #\n # activate the received court setup\n #\n court_setup.is_active = True\n court_setup.save ( )\n \n \n @transaction.commit_on_success\n def delete (self, court_setup, force=False):\n \"\"\"\n Deletes the received court setup, including all its\n referenced objects. If there are reservations attached \n to it, the court setup (and its reservations) are deleted\n only if the 'force' flag is True.-\n \"\"\"\n from clubs.models import Court\n from reservations.models import Reservation\n #\n # do not allow the deletion of the last court setup of a club\n #\n if self.get_count (court_setup.club) > 1:\n #\n # do not allow the deletion of this court setup\n # if it has any reservations attached to itself\n #\n res_count = Reservation.objects.by_court_setup (court_setup) \\\n .aggregate (Count ('id'))\n if (res_count['id__count'] == 0) or force:\n #\n # delete all reservations from all\n # courts of the received court setup\n #\n for court in Court.objects.filter (court_setup=court_setup):\n Court.objects.delete_reservations (court)\n court_setup.delete ( )\n #\n # activate another court setup\n #\n cs = self.filter (club=court_setup.club).values ('id')\n cs = self.get (pk=cs[0]['id'])\n self.activate (cs)\n \n \n @transaction.commit_on_success\n def clone (self, court_setup):\n \"\"\"\n Clones a court setup of a club, including all its courts, \n their properties and vacancy terms. Returns the newly created\n court setup.-\n \"\"\"\n from clubs.models import Court\n #\n # put a new name together\n #\n clone_name = \"%s %s\" % (ugettext('Copy of'), court_setup.name)\n clone = self.model.objects.create (name=clone_name,\n club=court_setup.club,\n is_active=False)\n #\n # delete any existing courts in the cloned court setup,\n # that may have been created by callback functions\n #\n Court.objects.filter (court_setup=clone).delete ( )\n #\n # clone all courts contained in this court setup\n #\n for court in Court.objects.filter (court_setup=court_setup):\n cloned_court = Court.objects.clone (court)\n cloned_court.court_setup = clone\n cloned_court.number = court.number\n cloned_court.save ( )\n return clone\n \n \n \nclass CourtManager (models.Manager):\n def delete_reservations (self, court):\n \"\"\"\n Deletes all reservations attached to the received court.-\n \"\"\"\n from reservations.models import Reservation\n for r in Reservation.objects.filter (vacancy__court=court).iterator ( ):\n Reservation.objects.delete (r)\n \n \n def get_available (self, court_setup):\n \"\"\"\n Returns a query set of available courts belonging\n to the received 'court_setup'.-\n \"\"\"\n courts = self.filter (court_setup=court_setup) \\\n .filter (is_available=True)\n return courts\n \n \n def get_count (self, court_setup):\n \"\"\"\n Returns the number of courts contained\n in the received 'court_setup'.-\n \"\"\"\n count = self.filter (court_setup=court_setup) \\\n .aggregate (Count ('id'))\n return int(count['id__count'])\n \n \n def clone (self, court):\n \"\"\"\n Clones a court within a court setup, including all its properties\n and vacancy terms. Returns the newly created court.-\n \"\"\"\n from ht_utils.models import update_many\n from clubs.models import Vacancy\n \n clone_num = self.model.objects.aggregate (Max ('number'))\n clone_num = clone_num['number__max'] + 1\n clone = self.model.objects.create (court_setup=court.court_setup,\n number=clone_num,\n indoor=court.indoor,\n light=court.light,\n surface=court.surface,\n single_only=court.single_only,\n is_available=court.is_available)\n #\n # copy active vacancy terms to the cloned court\n #\n bulk = []\n v_terms = Vacancy.objects.filter (court=court) \\\n .filter (price__isnull=False)\n for v in v_terms:\n c_v = Vacancy.objects.filter (court=clone,\n day_of_week=v.day_of_week,\n available_from=v.available_from,\n available_to=v.available_to)\n if c_v:\n c_v = c_v[0]\n c_v.price = v.price\n bulk.append (c_v)\n #\n # update the copied vacancy prices\n #\n update_many (bulk, fields=['price'])\n return clone\n \n\n\nclass VacancyMixin (object):\n \"\"\"\n Allows method chaining at manager level.-\n \"\"\"\n def get_free (self, cs, for_date, hour):\n \"\"\"\n Returns a query set of free vacancies (i.e. not yet booked) for\n the given date and hour, for active courts belonging to the given\n court setup.-\n \"\"\"\n from reservations.models import Reservation\n \n booked = Reservation.objects.by_date (cs, for_date) \\\n .filter (vacancy__available_from=hour) \\\n .values ('vacancy__id')\n return self.filter (court__court_setup=cs) \\\n .filter (day_of_week=for_date.isoweekday ( )) \\\n .filter (available_from=hour) \\\n .exclude (court__is_available=False) \\\n .exclude (id__in=booked)\n \n \n def get_all (self, courts=None, day_of_week_list=None, hour_list=None):\n \"\"\"\n Returns a query set of all vacancies, optionally filtering by the\n object lists received.-\n \"\"\"\n v = self.all ( )\n \n if courts:\n try:\n #\n # correctly handle a list of dictionaries\n # (as returned by qset.values ( ))\n #\n court_list = [c['id'] for c in courts if 'id' in c.keys ( )]\n except AttributeError:\n #\n # correctly handle lists of objects, ids and query sets\n #\n court_list = [c for c in courts]\n v = v.filter (court__in=court_list)\n if day_of_week_list:\n v = v.filter (day_of_week__in=day_of_week_list)\n if hour_list:\n v = v.filter (available_from__in=hour_list)\n return v\n\n\n def get_all_by_date (self, courts=None, date_list=None, hour_list=None):\n \"\"\"\n Returns a query set of all vacancies, optionally filtering by the\n object lists received.-\n \"\"\"\n if date_list:\n dow_list = [d.isoweekday ( ) for d in date_list]\n return self.get_all (courts, dow_list, hour_list)\n\n\nclass VacancyQuerySet (QuerySet, VacancyMixin):\n \"\"\"\n Glue class to build a manager that supports method chaining.-\n \"\"\"\n pass\n\n\nclass VacancyManager (models.Manager, VacancyMixin):\n \"\"\"\n A tuned manager that supports method chaining.-\n \"\"\"\n def get_query_set (self):\n return VacancyQuerySet (self.model, using=self._db)\n ","sub_path":"clubs/managers.py","file_name":"managers.py","file_ext":"py","file_size_in_byte":9316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"239805161","text":"from .encoder import Encoder\nfrom .decoder import Decoder\nimport base64\nfrom .client_commands import client_commands, urls\nfrom .httpclient import HttpClient\nfrom datetime import datetime\nfrom . import settings\nfrom copy import deepcopy\nfrom .logger import Logger\n\n\nclass Client(object):\n \"\"\"mgsv client\"\"\"\n\n def __init__(self, platform='stm'):\n super(Client, self).__init__()\n self.__session_key__ = None\n self.__encoder__ = Encoder()\n self.__decoder__ = Decoder()\n self.__platform__ = platform\n self._logger = Logger()\n\n def __command_get__(self, name):\n return deepcopy(client_commands[name])\n\n def __append_session_key__(self, command):\n if command['session_key'] == -1:\n # session key is required for command\n if self.__session_key__:\n command['session_key'] = self.__session_key__\n else:\n raise Exception('Session key is required for this command, but no key provided')\n\n def __response_decode__(self, response):\n text = response.text.replace('\\r\\n', '')\n text = self.__decoder__.decode(text)\n return text\n\n def __response_get_keys__(self, text):\n if not self.__session_key__:\n if 'session' in text['data']:\n self.__session_key__ = text['data']['session']\n if not self.__encoder__.__session_blowfish__:\n if 'crypto_key' in text['data']:\n self.__encoder__.__init_session_blowfish__(\n bytearray(base64.decodestring(text['data']['crypto_key'].encode())))\n\n def send_command(self, command):\n httpclient = HttpClient()\n comm = self.__command_get__(command)\n self.__append_session_key__(comm)\n encrypted_request = self.__encoder__.encode(comm)\n for url in urls:\n if 'tpp' + self.__platform__ in url:\n if command in urls[url]:\n # print(command, url)\n r = httpclient.send(encrypted_request, url)\n return self.__parse_response__(r)\n\n def __parse_response__(self, r):\n if r.status_code != 200:\n print(r.status_code, r.text)\n return {}\n text = self.__response_decode__(r)\n if text['data']['result'] != 'NOERR':\n self._logger.log_event(\"{} {}\".format(r.url, text))\n self.__response_get_keys__(text)\n return text\n\n def login(self):\n responses = []\n commands = [\n 'CMD_GET_URLLIST',\n 'CMD_GET_SVRLIST',\n # 'CMD_AUTH_STEAMTICKET',\t\t# you will need to set up ticket and its size; tickets also expire\n 'CMD_GET_SVRTIME',\n ]\n\n if self.__platform__ == 'ps3':\n commands.append('CMD_REQAUTH_HTTPS_PS3')\n elif self.__platform__ == 'stm':\n commands.append('CMD_REQAUTH_HTTPS')\n\n for i in commands:\n responses.append(self.send_command(i))\n return responses\n\n def get_nuclear(self):\n comm = 'CMD_GET_ABOLITION_COUNT'\n return [self.send_command(comm)]\n\n def get_login_data(self):\n comm = 'CMD_GET_LOGIN_PARAM'\n return [self.send_command(comm)]\n\n def get_info_list(self):\n comm = 'CMD_GET_INFORMATIONLIST'\n return [self.send_command(comm)]\n","sub_path":"emulator/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"495196631","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import Product , Contact , Order , OrderUpdate\nfrom math import ceil\nimport json\nfrom datetime import datetime\n\n\ndef index(request):\n # products = Product.objects.all() #pylint: disable = no-member\n # print(products)\n # n = len(products)\n # nSlides = n//4 + ceil((n/4) - (n//4))\n\n allprods = []\n catprods = Product.objects.values('category' , 'product_id')\n cats = {item['category'] for item in catprods}\n for cat in cats:\n prod = Product.objects.filter(category = cat)\n n = len(prod)\n nSlides = n//4 + ceil((n/4) - (n//4))\n allprods.append([prod , range(1 , nSlides) , nSlides])\n\n # allprods = [[products , range(1 , nSlides) , nSlides] , [products , range(1 , nSlides) , nSlides]]\n params = {'allprods':allprods}\n return render(request , 'shop/index.html' , params)\n\ndef searchMatch(query, item):\n '''return true only if query matches the item'''\n if query in item.desc.lower() or query in item.product_name.lower() or query in item.category.lower():\n return True\n else:\n return False\n\ndef search(request):\n query = request.GET.get('search')\n allProds = []\n catprods = Product.objects.values('category', 'product_id') #pylint: disable = no-member\n cats = {item['category'] for item in catprods}\n for cat in cats:\n prodtemp = Product.objects.filter(category=cat) #pylint: disable = no-member\n prod = [item for item in prodtemp if searchMatch(query, item)]\n\n n = len(prod)\n nSlides = n // 4 + ceil((n / 4) - (n // 4))\n\n if len(prod) != 0:\n allProds.append([prod, range(1, nSlides), nSlides])\n\n params = {'allProds': allProds, \"msg\": \"\"}\n\n if len(allProds) == 0 or len(query)<4:\n params = {'msg': \"Please make sure to enter relevant search query\"}\n return render(request, 'shop/search.html', params)\n\ndef about(request):\n return render(request , 'shop/about.html')\n\ndef contact(request):\n if request.method==\"POST\":\n name=request.POST.get('name', '')\n email=request.POST.get('email', '')\n phone=request.POST.get('phone', '')\n desc=request.POST.get('desc', '')\n contact = Contact(name=name, email=email, phone=phone, desc=desc)\n contact.save()\n\n return render(request , 'shop/contact.html')\n\ndef tracker(request):\n if request.method==\"POST\":\n orderId=request.POST.get('orderId', '')\n email=request.POST.get('email', '')\n try:\n order = Order.objects.filter(order_id=orderId, email=email) #pylint: disable = no-member\n if len(order) > 0:\n update = OrderUpdate.objects.filter(order_id=orderId) #pylint: disable = no-member\n updates=[]\n for item in update:\n updates.append({'text':item.update_desc , 'time':item.timestamp})\n response = json.dumps({'status':'success','updates':updates,'itemsJson':order[0].items_json} , default=str)\n return HttpResponse(response)\n\n else:\n return HttpResponse('{\"status\":\"No Items\"}')\n\n except Exception as e:\n return HttpResponse(e,'{\"status\":\"Error!!\"}')\n\n return render(request , 'shop/tracker.html')\n\n\ndef ProductView(request , my_id):\n product = Product.objects.filter(product_id = my_id) #pylint: disable = no-member\n \n return render(request , 'shop/productview.html' , {'product':product[0]})\n\ndef checkout(request):\n\n if request.method==\"POST\":\n items_json=request.POST.get('itemsJson' , '')\n name=request.POST.get('name', '')\n amount=request.POST.get('amount', '')\n email=request.POST.get('email', '')\n address=request.POST.get('address1', '') + \" \" + request.POST.get('address2', '')\n city=request.POST.get('city', '')\n state=request.POST.get('state', '')\n zip_code=request.POST.get('zip_code', '')\n phone=request.POST.get('phone', '')\n\n order = Order(items_json=items_json, name=name, amount=amount, email=email, address=address, city=city, state=state, zip_code=zip_code, phone=phone)\n order.save()\n\n update= OrderUpdate(order_id= order.order_id, update_desc=\"The order has been placed\", email=email)\n update.save()\n\n id = order.order_id\n return render(request, 'shop/received.html', {'id': id})\n \n return render(request , 'shop/checkout.html' )\n\n","sub_path":"mac/shop/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"515056694","text":"__author__ = 'Aaron'\nimport requests\nimport cherrypy\nimport json\nimport os\nfrom CodernityDB.database import Database\nimport config\nfrom jinja2 import Environment, FileSystemLoader\ntemplate_loader = Environment(loader=FileSystemLoader(os.path.join(os.path.dirname(__file__), 'templates')))\n\nclass PageChat(object):\n def __init__(self):\n self.db = Database(config.database)\n pass\n\n def _cp_dispatch(self, vpath):\n if len(vpath) == 3:\n cherrypy.request.params['channel'] = vpath.pop(0)\n cherrypy.request.params['start_time'] = vpath.pop(0)\n cherrypy.request.params['end_time'] = vpath.pop(0)\n return self\n return vpath\n\n @cherrypy.expose\n def index(self, channel, start_time, end_time):\n self.db.open()\n cherrypy.response.headers['Content-Type']= 'application/json'\n messages = self.db.get_many('time', key=None, limit=-1, with_doc=True, start=int(start_time), end=int(end_time))\n messages = [x for x in messages if x['doc']['channel'] == channel]\n\n jsonData = json.dumps(messages)\n self.db.close()\n return jsonData\n\n\n\nclass PageMain(object):\n @cherrypy.expose\n def index(self):\n index = template_loader.get_template('index.html')\n return index.render(channels=config.channels)\n\n\n\nclass PageChannel(object):\n\n\n def _cp_dispatch(self, vpath):\n if len(vpath) == 2:\n cherrypy.request.params['channel'] = vpath.pop(0)\n cherrypy.request.params['broadcasts'] = vpath.pop(0)\n return self\n elif len(vpath) == 1:\n cherrypy.request.params['channel'] = vpath.pop(0)\n return self\n return vpath\n\n @staticmethod\n def get_past_broadcasts(channel, broadcasts=False):\n url = \"https://api.twitch.tv/kraken/channels/%s/videos?limit=15&broadcasts=%s\" % (channel, str(broadcasts).lower())\n r = requests.get(url)\n return r.json()\n\n @cherrypy.expose\n def index(self, channel, broadcasts=False):\n if broadcasts:\n broadcasts = True\n\n #channel_data = self.get_past_broadcasts(channel, broadcasts)\n index = template_loader.get_template('channels.html')\n return index.render(channels=config.channels)\n\n\n\nwebsite = PageMain()\nwebsite.chat = PageChat()\nwebsite.channel = PageChannel()\n\nstatic_config = {\n '/static' : {\n 'tools.staticdir.on': True,\n 'tools.staticdir.dir': os.path.join(os.path.dirname(__file__), 'static'),\n\n },\n}\n\n\n\n\ncherrypy.quickstart(website, config=static_config)\n","sub_path":"webpage.py","file_name":"webpage.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"434339181","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^process$', views.process, name='process'),\n url(r'^remove/(?P\\d{1,4})$', views.remove, name='remove'),\n url(r'^remove/goback$', views.goback, name='goback'),\n url(r'^remove/delete/(?P\\d{1,4})$', views.delete, name='delete')\n\n]\n","sub_path":"Python/django/semiRestfulRoutes/apps/coursesApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"288369372","text":"#!python\n# coding=utf-8\n\nimport os\n\nimport netCDF4\nimport numpy as np\nfrom udunitspy import Unit\n\nfrom .create import create_timeseries_file\n\nfrom pytools import logger\n\n\ndef merge_timeseries(crawl_path, output_filename=None):\n\n if output_filename is None:\n output_filename = \"merged.nc\"\n logger.debug(\"Setting output file to %s\" % output_filename)\n\n for root, dirs, files in os.walk(crawl_path):\n try:\n # Make sure we are in a sensor directory\n assert os.path.basename(root).split(\":\")[2] == \"sensor\"\n ncfiles = [ncfile for ncfile in files if os.path.splitext(ncfile)[-1][0:3] == \".nc\" and os.path.splitext(ncfile)[-1] != \".ncml\" and ncfile != output_filename]\n # Make sure we have at least one NetCDF file in the directory\n assert len(ncfiles) > 0\n logger.info(\"Merging %i files into %s\" % (len(ncfiles), os.path.join(root, output_filename)))\n except (IndexError, AssertionError):\n continue\n\n sensor_urn = os.path.basename(root)\n station_urn = \":\".join(sensor_urn.replace(\"sensor\", \"station\").split(\":\")[0:-1])\n varname = sensor_urn.split(\":\")[-1]\n # Support cell_methods and bounds additions\n varname = varname.split(\"#\")[0]\n\n fillvalue = -9999.9\n\n times = np.ma.asarray([])\n values = np.ma.asarray([])\n verticals = np.ma.asarray([])\n lats = []\n lons = []\n # Track attributes from every file\n global_attributes = {}\n variable_attributes = {}\n\n dims_of_values = None\n continue_on = False\n f = None\n base_value_unit = None\n for f in ncfiles:\n nc = netCDF4.Dataset(os.path.join(root, f))\n\n if dims_of_values is not None and dims_of_values != nc.variables[varname].ndim:\n error_message = \"Error with sensor: %s. Different dimensions on the data variable between files\" % sensor_urn\n process_error(root, output_filename, error_message)\n continue_on = True\n nc.close()\n break\n dims_of_values = nc.variables[varname].ndim\n\n # Update running global_attributes, overwriting any already existing key.\n global_attributes.update(nc.__dict__)\n # update running variable_attributes, overwriting any already existing key.\n variable_attributes.update(nc.variables[varname].__dict__)\n\n # This is generalized to work with both timeseries and timeseries profile.\n logger.debug(\"Normalizing variables...\")\n vari = nc.variables[varname]\n\n converter = None\n if base_value_unit is None:\n base_value_unit = vari.units\n else:\n if vari.units != base_value_unit:\n try:\n # Try to convert\n base = Unit(str(base_value_unit))\n unt = Unit(str(vari.units))\n if unt.are_convertible(base):\n converter = unt.get_converter(base)\n else:\n raise ValueError(\"Could not convert\")\n except BaseException:\n raise\n error_message = \"Error with sensor: %s. Different units (%s vs %s) could not be converted.\" % (sensor_urn, base_value_unit, vari.units)\n process_error(root, output_filename, error_message)\n continue_on = True\n nc.close()\n break\n\n if vari.ndim > 1:\n vardata = np.ma.ravel(vari[:])\n else:\n vardata = vari[:]\n\n if converter is not None:\n vardata = converter.evaluate(vardata)\n values = np.ma.concatenate([values, vardata])\n\n # Location of the station\n try:\n lats.append(nc.variables[\"latitude\"][:][0])\n lons.append(nc.variables[\"longitude\"][:][0])\n except IndexError:\n lats.append(nc.variables[\"latitude\"][:])\n lons.append(nc.variables[\"longitude\"][:])\n\n # Repeat each time value by the number of verticals\n # This turns [1,2,3] into [1,1,1,2,2,2,3,3,3] if zs.size was three.\n # if zs.size is one, it just returns the ts array.\n logger.debug(\"Flattening time...\")\n ts = nc.variables[\"time\"][:]\n zs = nc.variables[\"height\"][:]\n logger.debug(\"Normalizing time...\")\n times = np.ma.concatenate([times, np.ma.repeat(ts, zs.size)])\n\n # Get actual verticals, repeat if necessary\n logger.debug(\"Flattening height...\")\n verticals = np.ma.concatenate([verticals, np.ma.ravel(np.ma.repeat([zs], ts.size, axis=0))])\n\n # Be sure we are on the right track...\n assert times.size == verticals.size == values.size\n\n nc.close()\n\n if continue_on:\n continue\n\n variable_attributes[\"units\"] = base_value_unit\n try:\n os.remove(os.path.join(root, 'errors.log'))\n except:\n pass\n\n if len(list(set(lats))) > 1:\n logger.warn(\"%s : Some component files contained differing latitudes: %s. Using the first.\" % (sensor_urn, lats))\n if len(list(set(lons))) > 1:\n logger.warn(\"%s : Some component files contained differing longitudes: %s. Using the first.\" % (sensor_urn, lons))\n\n create_timeseries_file(root, lats[0], lons[0], station_urn, sensor_urn, global_attributes, variable_attributes, data=None, times=times, values=values, verticals=verticals, fillvalue=fillvalue, output_filename=output_filename)\n\n\ndef process_error(path, output_filename, message):\n # Log error\n logger.error(message)\n\n # Write error message\n with open(os.path.join(path, 'errors.log'), 'w') as f:\n f.write(message)\n\n # Remove merged file that is either old or a temporary failure\n try:\n os.remove(os.path.join(path, output_filename))\n except:\n pass\n","sub_path":"pytools/netcdf/sensors/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":6211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"447612550","text":"# -*-coding: utf-8 -*\n\"\"\" This program is attached to the 'main.py' program. The target is find all the links of all\ncategories.\n\"\"\"\n\n\nimport requests\n\nfrom bs4 import BeautifulSoup\n\n\ndef get_all_category_link(url_bts):\n \"\"\"All category links\"\"\"\n response = requests.get(url_bts)\n soup = BeautifulSoup(response.text, \"html.parser\")\n uls=soup.findAll ('a')[3:-41]\n category_dict = []\n for a_tag in uls:\n add_url = 'http://books.toscrape.com/'\n cat_links = add_url+a_tag.attrs.get(\"href\")\n category_dict.append(cat_links)\n\n return category_dict\n","sub_path":"all_category_link.py","file_name":"all_category_link.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"553651137","text":"# Copyright 2014 Big Switch Networks, 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\nfrom enum import Enum\nimport os\nfrom os_net_config import utils\nfrom oslo_serialization import jsonutils\nimport re\nimport syslog as LOG\nimport time\n\n# constants for RHOSP\nNET_CONF_PATH = \"/etc/os-net-config/config.json\"\nHIERA_DIR_PATH = \"/etc/puppet/hieradata\"\nCOMPUTE_FILE_PATH = \"%s/compute.json\" % HIERA_DIR_PATH\nSUPPORTED_BOND = ['ovs_bond', 'linux_bond']\n_SYS_CLASS_NET = '/sys/class/net'\n\n\nclass BCFMode(Enum):\n MODE_P_ONLY = 5\n MODE_P_V = 6\n\n\n# monkey patch to identify phy nics\ndef _is_active_nic(interface_name):\n try:\n if interface_name == 'lo':\n return False\n\n device_dir = _SYS_CLASS_NET + '/%s/device' % interface_name\n has_device_dir = os.path.isdir(device_dir)\n\n carrier = None\n with open(_SYS_CLASS_NET + '/%s/carrier' % interface_name, 'r') as f:\n carrier = int(f.read().rstrip())\n\n address = None\n with open(_SYS_CLASS_NET + '/%s/address' % interface_name, 'r') as f:\n address = f.read().rstrip()\n\n if has_device_dir and carrier == 1 and address:\n return True\n else:\n return False\n except IOError:\n return False\n\nutils._is_active_nic = _is_active_nic\n\n\ndef get_bcf_mode():\n \"\"\"Get bcf deployment mode.\n\n :returns: UNKNOWN, MODE_P_ONLY or MODE_P_V.\n \"\"\"\n while True:\n if os.path.isdir(HIERA_DIR_PATH):\n break\n if not os.path.isfile(COMPUTE_FILE_PATH):\n return BCFMode.MODE_P_ONLY\n\n if not os.path.isfile(NET_CONF_PATH):\n return BCFMode.MODE_P_ONLY\n try:\n json_data = open(NET_CONF_PATH).read()\n data = jsonutils.loads(json_data)\n except Exception:\n return BCFMode.MODE_P_ONLY\n network_config = data.get('network_config')\n for config in network_config:\n if config.get('type') == 'ivs_bridge':\n return BCFMode.MODE_P_V\n\n return BCFMode.MODE_P_ONLY\n\n\ndef get_mac_str(network_interface):\n with open(\"/sys/class/net/%s/address\" % network_interface) as f:\n return f.read().strip()\n\n\ndef add_intf_to_map(intf_map, bridge_or_bond, config_type, intf_index,\n lacp=False):\n \"\"\"Adds an interface to the interface map, after performing validation\n\n interface_map has a specific structure. this method checks and inserts\n keys if they're missing for the bridge or interface being added.\n\n :param intf_map: interface map object to which the interface is added\n :param bridge_or_bond: bridge or bond name to which the interface belongs\n :param config_type: type of object - either bridge or bond\n :param intf_index: name or index number of the interface\n if interface is in nicX format, this will be a\n numerical index, else name. both would be string.\n :param lacp: boolean flag, specifying whether intf is part of some form of\n link aggregation or no.\n :return: intf_map after being updated\n \"\"\"\n if bridge_or_bond not in intf_map:\n intf_map[bridge_or_bond] = {}\n if 'config_type' not in intf_map[bridge_or_bond]:\n intf_map[bridge_or_bond]['config_type'] = config_type\n if 'members' not in intf_map[bridge_or_bond]:\n intf_map[bridge_or_bond]['members'] = []\n if config_type == 'linux_bond' or lacp:\n # for linux_bond config type, always True. Otherwise, depends on\n # whether its a bond or individual interface in a bridge.\n intf_map[bridge_or_bond]['lacp'] = True\n else:\n intf_map[bridge_or_bond]['lacp'] = False\n intf_map[bridge_or_bond]['members'].append(intf_index)\n return intf_map\n\n\ndef _get_intf_index(nic_name):\n \"\"\"os-net-config can have interface name stored nicX, where X is a number\n\n in this case, REAL interface name is not used. derive the index if it is in\n nicX format.\n otherwise, simply use the name.\n\n :param nic_name:\n :return: index or name. both in string format.\n \"\"\"\n indexes = map(int, re.findall(r'\\d+', nic_name))\n if len(indexes) == 1 and nic_name.startswith(\"nic\"):\n intf_index = str(indexes[0] - 1)\n else:\n intf_index = str(nic_name)\n return intf_index\n\n\ndef get_network_interface_map():\n \"\"\"Get interface map for bonds and bridges relevant on this RHOSP node\n\n :return: returns a mapping of network interfaces with its parent being a\n bridge or bond. syntax:\n {\n 'bridge_or_bond_name': {\n 'type': 'bond or bridge type',\n 'lacp': False (boolean, defaults to False),\n 'members': [ list of interfaces ]\n }\n }\n\n sample output of a mix of bonds and bridges:\n\n {\n u 'bond_api': {\n 'type': 'linux_bond',,\n 'lacp': True,\n 'members': ['p1p1']\n }, u 'br-link': {\n 'type': 'ovs_bridge',\n 'lacp': False,\n 'members': ['p1p2']\n }, u 'br-ex': {\n 'type': 'ovs_bridge',\n 'lacp': True,\n 'members': ['p1p1', 'p1p2']\n }\n }\n \"\"\"\n intf_map = {}\n while True:\n if not os.path.isfile(NET_CONF_PATH):\n time.sleep(1)\n continue\n try:\n json_data = open(NET_CONF_PATH).read()\n data = jsonutils.loads(json_data)\n except ValueError:\n time.sleep(1)\n continue\n network_config = data.get('network_config')\n for config in network_config:\n config_type = config.get('type')\n if config_type == 'ovs_bridge':\n bridge_name = config.get('name').encode('ascii', 'ignore')\n members = config.get('members')\n for member in members:\n # member can be a bond or single interface in case of\n # ovs_bridge on DPDK controller\n member_type = member.get('type')\n if member_type == 'interface':\n intf_index = _get_intf_index(\n member.get('name').encode('ascii', 'ignore'))\n add_intf_to_map(\n intf_map=intf_map, bridge_or_bond=bridge_name,\n config_type='ovs_bridge', intf_index=intf_index)\n break\n elif member_type in SUPPORTED_BOND:\n nics = member.get('members')\n for nic in nics:\n if nic.get('type') != 'interface':\n continue\n intf_index = _get_intf_index(\n nic.get('name').encode('ascii', 'ignore'))\n add_intf_to_map(\n intf_map=intf_map, bridge_or_bond=bridge_name,\n config_type='ovs_bridge',\n intf_index=intf_index, lacp=True)\n break\n else:\n # either a vlan type interface or unsupported type\n continue\n elif config_type == 'linux_bond':\n bond_name = config.get('name').encode('ascii', 'ignore')\n members = config.get('members')\n for nic in members:\n if nic.get('type') != 'interface':\n continue\n intf_index = _get_intf_index(\n nic.get('name').encode('ascii', 'ignore'))\n add_intf_to_map(\n intf_map=intf_map, bridge_or_bond=bond_name,\n config_type='linux_bond', intf_index=intf_index)\n elif config_type == 'ovs_user_bridge':\n bridge_name = config.get('name').encode('ascii', 'ignore')\n members = config.get('members')\n for nic in members:\n nic_type = nic.get('type')\n if nic_type == 'ovs_dpdk_port':\n intf_name = nic.get('name').encode('ascii', 'ignore')\n add_intf_to_map(\n intf_map=intf_map, bridge_or_bond=bridge_name,\n config_type='ovs_user_bridge',\n intf_index=intf_name)\n break\n elif nic_type == 'ovs_dpdk_bond':\n bond_interfaces = nic.get('members')\n for bond_intf in bond_interfaces:\n if bond_intf.get('type') != 'ovs_dpdk_port':\n LOG.syslog(\"DPDK ovs_dpdk_bond has NON \"\n \"ovs_dpdk_port %s\" %\n bond_intf.get('name'))\n continue\n intf_name = (bond_intf.get('name')\n .encode('ascii', 'ignore'))\n add_intf_to_map(\n intf_map=intf_map, bridge_or_bond=bridge_name,\n config_type='ovs_user_bridge',\n intf_index=intf_name, lacp=True)\n else:\n continue\n break\n # get active interfaces from os_net_config\n active_intfs = utils.ordered_active_nics()\n intf_len = len(active_intfs)\n # use the intf_map and work out the chassisid\n for br_or_bond in intf_map:\n if intf_map[br_or_bond]['config_type'] == 'ovs_user_bridge':\n # do not try to map interface name with kernel entries\n # ovs_user_bridge is used for DPDK compute nodes, interfaces are\n # owned by DPDK driver and not kernel network driver\n continue\n if 'members' in intf_map[br_or_bond]:\n intfs = []\n for index in intf_map[br_or_bond]['members']:\n try:\n idx = int(index)\n if idx < intf_len:\n intfs.append(active_intfs[idx])\n except ValueError:\n intfs.append(index)\n intf_map[br_or_bond]['members'] = intfs\n LOG.syslog(\"Network interface map is %s\" % intf_map)\n return intf_map\n","sub_path":"networking_bigswitch/bsnlldp/rhlib.py","file_name":"rhlib.py","file_ext":"py","file_size_in_byte":11073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"64091652","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom numba import jit\n\n\ndef makeStartGrid(matrix_len = 100, u_init = 0.5, v_init = 0.25):\n noise_grid = np.random.normal(scale = 0.1, size=(matrix_len, matrix_len))\n \n u_grid = np.ones(shape=(matrix_len, matrix_len)) * u_init \n v_grid = np.zeros(shape=(matrix_len, matrix_len)) + noise_grid\n \n v_len = 20\n v_i = (matrix_len // 2) - (v_len // 2)\n v_j = v_i\n print(v_i, v_j)\n for di in range(v_len):\n for dj in range(v_len):\n v_grid[v_i + di][v_j + dj] = v_init\n return u_grid, v_grid\n\n@jit (nopython = True)\ndef update_grid(u_grid, v_grid, Du = 0.16, Dv = 0.08, f = 0.035, k = 0.06, delta_t = 1, delta_x = 1):\n\n N = len(u_grid)\n \n new_u_grid = np.zeros(shape=(N, N))\n new_v_grid = np.zeros(shape=(N, N))\n \n for i in range(N):\n for j in range(N):\n new_u_grid[i][j] = (u_grid[i][j] +\n Du * delta_t / (delta_x **2) *\n (u_grid[0 if i == N - 1 else i+1][j]\n + u_grid[N-1 if i == 0 else i-1][j]\n + u_grid[i][0 if j == N - 1 else j+1]\n + u_grid[i][N-1 if j == 0 else j-1]\n - 4 * u_grid[i][j])\n \n - u_grid[i][j] * v_grid[i][j]**2\n + f * (1 - u_grid[i][j]))\n \n new_v_grid[i][j] = (v_grid[i][j] +\n Dv * delta_t / (delta_x **2) *\n (v_grid[0 if i == N - 1 else i+1][j]\n + v_grid[N-1 if i == 0 else i-1][j]\n + v_grid[i][0 if j == N - 1 else j+1]\n + v_grid[i][N-1 if j == 0 else j-1]\n - 4 * v_grid[i][j]) \n \n +u_grid[i][j] * v_grid[i][j]**2\n - (f + k) * v_grid[i][j])\n \n return new_u_grid, new_v_grid\n \n\nfrom matplotlib import cm\nimport matplotlib.colors as colors\n\nif __name__ == \"__main__\":\n u_grid, v_grid = makeStartGrid()\n \n print(v_grid)\n for u in range(4):\n for _ in range(200):\n u_grid, v_grid = update_grid(u_grid, v_grid)\n \n plt.imshow(u_grid / (u_grid + v_grid), norm=colors.Normalize(vmin=0, vmax=1))\n plt.show()\n print(v_grid)\n\n","sub_path":"set2/set2c.py","file_name":"set2c.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"579654813","text":"from unittest import TestCase\n\nfrom numpy import ndarray\n\nfrom Mosaicker import AppMosaicker\nimport matplotlib.pyplot\n\n\ndef assert_same_num_channels(self, im1: ndarray, im2: ndarray):\n self.assertEqual(im1.shape[2], im2.shape[2])\n\n\ndef assert_approx_same_size(self, im1: ndarray, im2: ndarray):\n # Assert that for each dimension, the lengths are within `margin`% of each other\n margin = 0.1 # 0.1 = 10%\n for len1, len2 in list(zip(im1.shape, im2.shape))[:2]:\n self.assertTrue(1 - margin < len1 / len2 < 1 + margin)\n\n\nclass TestAppMosaicker(TestCase):\n\n mosaicker = AppMosaicker()\n\n def test_AppMosaickerShouldMosaic300PxlImage(self):\n im = matplotlib.pyplot.imread(\"test_images/test_image_300x300.jpeg\")\n output_im = self.mosaicker.compute_mosaick(im)\n\n assert_same_num_channels(self, im, output_im)\n assert_approx_same_size(self, im, output_im)\n\n def test_AppMosaickerShouldMosaicImageWithAlpha(self):\n im = matplotlib.pyplot.imread(\"test_images/with_alpha_127x300.png\")\n output_im = self.mosaicker.compute_mosaick(im)\n\n assert_approx_same_size(self, im, output_im)\n","sub_path":"test_Mosaicker.py","file_name":"test_Mosaicker.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"627775323","text":"\n# coding: utf-8\n\n# In[47]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom scipy.stats import skew\nfrom scipy.special import boxcox1p\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.preprocessing import StandardScaler, RobustScaler\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.linear_model import Lasso, LassoCV\n\n\n# In[49]:\n\n\ntrain=pd.read_csv(\"./train.csv\")\ntest=pd.read_csv(\"./test.csv\")\ntest2=pd.read_csv(\"./test.csv\")\nlen_train=train.shape[0]\nhouses=pd.concat([train,test], sort=False)\nprint(train.shape)\nprint(test.shape)\n\n\n# In[51]:\n\n\nhouses.select_dtypes(include='object').head()\n\n\n# Incomplete data:\n# \n# LotFrontage;\n# Alley;\n# MasVnrType;\n# MasVnrArea;\n# BsmtQual 1423\n# BsmtCond 1423\n# BsmtExposure 1422\n# BsmtFinType1 1423\n# BsmtFinType2 1422\n# Electrical 1459\n# FireplaceQu 770\n# GarageType 1379\n# GarageYrBlt 1379\n# GarageFinish 1379\n# GarageQual 1379\n# GarageCond 1379\n# Fence 281\n# MiscFeature 54\n# PoolQC 7\n\n# In[52]:\n\n\nhouses.select_dtypes(include=['float','int']).head()\n\n\n# In[53]:\n\n\nhouses.select_dtypes(include='object').isnull().sum()[houses.select_dtypes(include='object').isnull().sum()>0]\n\n\n# In[54]:\n\n\nfor col in ('Alley','Utilities','MasVnrType','BsmtQual','BsmtCond','BsmtExposure','BsmtFinType1',\n 'BsmtFinType2','Electrical','FireplaceQu','GarageType','GarageFinish','GarageQual','GarageCond',\n 'PoolQC','Fence','MiscFeature'):\n train[col]=train[col].fillna('None')\n test[col]=test[col].fillna('None')\n\n\n# In[55]:\n\n\nfor col in ('MSZoning','Exterior1st','Exterior2nd','KitchenQual','SaleType','Functional'):\n train[col]=train[col].fillna(train[col].mode()[0])\n test[col]=test[col].fillna(data[col].mode()[0])\n\n\n# In[56]:\n\n\ndata.select_dtypes(include=['int','float']).isnull().sum()[data.select_dtypes(include=['int','float']).isnull().sum()>0]\n\n\n# In[57]:\n\n\nhouses.select_dtypes(include=['int','float']).isnull().sum()[houses.select_dtypes(include=['int','float']).isnull().sum()>0]\n\n\n# \"Some NAs means \"None\" (which I will fill with 0) or means \"Not Available\" (which I will fill with mean)\"\n\n# In[58]:\n\n\nfor col in ('MasVnrArea','BsmtFinSF1','BsmtFinSF2','BsmtUnfSF','TotalBsmtSF','BsmtFullBath','BsmtHalfBath','GarageYrBlt','GarageCars','GarageArea'):\n train[col]=train[col].fillna(0)\n test[col]=test[col].fillna(0)\n\n\n# In[59]:\n\n\ntrain['LotFrontage']=train['LotFrontage'].fillna(train['LotFrontage'].mean())\ntest['LotFrontage']=test['LotFrontage'].fillna(train['LotFrontage'].mean())\n\n\n# 1.4 - Remove some features high correlated and outliers¶\n\n# In[60]:\n\n\nplt.figure(figsize=[30,15])\nsns.heatmap(train.corr(), annot=True)\n\n\n# In[61]:\n\n\n#from 2 features high correlated, removing the less correlated with SalePrice\ntrain.drop(['GarageArea','1stFlrSF','TotRmsAbvGrd','2ndFlrSF'], axis=1, inplace=True)\ntest.drop(['GarageArea','1stFlrSF','TotRmsAbvGrd','2ndFlrSF'], axis=1, inplace=True)\n\n\n# In[62]:\n\n\n#removing outliers recomended by author\ntrain = train[train['GrLivArea']<4000]\n\n\n# In[63]:\n\n\nhouses=pd.concat([train,test], sort=False)\n\n\n# ### 1.5 Transformation\n\n# In[64]:\n\n\n# Numerical to categorical\n\nhouses['MSSubClass']=houses['MSSubClass'].astype(str)\n\n\n# In[65]:\n\n\n# Adjust skew\n\nskew=houses.select_dtypes(include=['int','float']).apply(lambda x: skew(x.dropna())).sort_values(ascending=False)\nskew_df=pd.DataFrame({'Skew':skew})\nskewed_df=skew_df[(skew_df['Skew']>0.5)|(skew_df['Skew']<-0.5)]\n\ntrain=houses[:len_train]\ntest=houses[len_train:]\n\n\n# In[69]:\n\n\ntrain.to_csv(\"train_processed.csv\")\ntest.to_csv(\"test_processed.csv\")\n\n","sub_path":"ordinal_datasets/process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":3680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"175559424","text":"import sys\nsys.path.append('G:/Data/Lambda/CS/Data-Structures/doubly_linked_list')\nfrom doubly_linked_list import DoublyLinkedList\n\n\n\nclass Queue:\n def __init__(self):\n self.size = 0\n # Why is our DLL a good choice to store our elements?\n # self.storage = ?\n # O(1) for both modifying the front and the back\n # doesn't have to exist in contiguous memory\n self.storage = DoublyLinkedList()\n\n def enqueue(self, value):\n self.storage.add_to_head(value)\n self.size += 1\n pass\n\n def dequeue(self):\n if self.storage.length > 0:\n self.size -= 1\n return self.storage.remove_from_tail()\n else:\n return None\n\n def len(self):\n return self.size\n\n\nmy_queue = Queue()\nqueue_2 = my_queue\n\ntest = 5\ntest2 = test\ntest2 += 1\n\nprint(test,test2)\n# my_queue.enqueue(1)\n\n# print(my_queue.len())\n# print(queue_2.len())\n","sub_path":"queue_and_stack/dll_queue.py","file_name":"dll_queue.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"372663453","text":"def mysplit(s):\n ss = s.strip()\n if ss == \"\":\n return []\n else:\n # following logic could be replaced by return ss.split()\n wordlst = []\n word = \"\"\n for c in ss:\n if c.isspace():\n if word != \"\":\n wordlst.append(word)\n word = \"\"\n else:\n word = word + c\n if word != \"\":\n wordlst.append(word)\n return wordlst\n\nprint(mysplit(\"To be or not to be, that is the question\"))\nprint(mysplit(\"To be or not to be,that is the question\"))\nprint(mysplit(\" \"))\nprint(mysplit(\" abc \"))\nprint(mysplit(\"\"))\n\n# def mysplit(strng):\n# # return [] if string is empty or contains whitespaces only\n# if strng == '' or strng.isspace():\n# return [ ]\n# # prepare a list to return\n# lst = []\n# # prepare a word to build subsequent words\n# word = ''\n# # check if we are currently inside a word (i.e., if the string starts with a word)\n# inword = not strng[0].isspace()\n# # iterate through all the characters in string\n# for x in strng:\n# # if we are currently inside a string...\n# if inword:\n# # ... and current character is not a space...\n# if not x.isspace():\n# # ... update current word\n# word = word + x\n# else:\n# # ... otherwise, we reached the end of the word so we need to append it to the list...\n# lst.append(word)\n# # ... and signal a fact that we are outside the word now\n# inword = False\n# else:\n# # if we are outside the word and we reached a non-white character...\n# if not x.isspace():\n# # ... it means that a new word has begun so we need to remember it and...\n# inword = True\n# # ... store the first letter of the new word\n# word = x\n# else:\n# pass\n# # if we left the string and there is a non-empty string in word, we need to update the list\n# if inword:\n# lst.append(word)\n# # return the list to invoker\n# return lst","sub_path":"pcep/mod5_stringlab.py","file_name":"mod5_stringlab.py","file_ext":"py","file_size_in_byte":2208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"320946864","text":"\"\"\"\nPrograma ler dois números e verifica qual é o maior ou se eles são iguais.\n\"\"\"\nnum1 = float(input(\"Digite um número: \"))\nnum2 = float(input(\"Digite outro número: \"))\nif num1 > num2:\n print(f\"O número {num1} é maior que {num2}\")\nelif num1 < num2:\n print(f\"O número {num2} é maior que {num1}\")\nelse:\n print(f\"Os números são iguais!\")\n","sub_path":"condicional/maior.py","file_name":"maior.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"241130432","text":"#Author : Ravinder Bhattoo\nfrom functools import partial\nimport numpy\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker\nfrom matplotlib.path import Path\nfrom matplotlib.patches import PathPatch\nfrom cycler import cycler\nimport scipy.stats as stats\nfrom scipy import interpolate\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom matplotlib.patches import Patch\n\nplot = plt.plot\n\nplt.savefig = partial(plt.savefig, dpi = 500,bbox_inches = \"tight\")\n\ndef __t(x):\n if plt.rcParams['text.usetex']:\n return r'\\textbf{{{}}}'.format(x)\n else:\n return x\n\ndef usetex(on='on'):\n if on=='off':\n plt.rcParams['text.usetex'] = False\n elif on=='on':\n plt.rcParams['text.usetex'] = True\n else:\n pass\n\ndef set_tick(val='in'):\n params = {\n 'xtick.direction': val,\n 'ytick.direction': val,\n }\n plt.rcParams.update(params)\n\ndef no_box(ax2):\n # Hide the right and top spines\n ax2.spines['right'].set_visible(False)\n ax2.spines['top'].set_visible(False)\n # Only show ticks on the left and bottom spines\n ax2.yaxis.set_ticks_position('left')\n ax2.xaxis.set_ticks_position('bottom')\n\ndef make_box(ax2):\n # Show the right and top spines\n ax2.spines['right'].set_visible(True)\n ax2.spines['top'].set_visible(True)\n # show ticks on the both spines\n ax2.xaxis.set_ticks_position('both')\n ax2.yaxis.set_ticks_position('both')\n\ndef set_mood_dark():\n params = {\n 'figure.edgecolor': 'white',\n 'figure.facecolor': 'black',\n 'axes.edgecolor': 'white',\n 'axes.facecolor': 'black',\n 'savefig.edgecolor': 'black',\n 'savefig.facecolor': 'black',\n 'text.color': 'white',\n 'axes.labelcolor': 'white',\n 'boxplot.boxprops.color': 'white',\n 'boxplot.capprops.color': 'white',\n 'boxplot.flierprops.color': 'white',\n 'boxplot.flierprops.markeredgecolor': 'white',\n 'boxplot.whiskerprops.color': 'white',\n 'grid.color': '#e0e0e0',\n 'hatch.color': 'white',\n 'image.cmap': 'hot',\n 'patch.edgecolor': 'white',\n 'xtick.color': 'white',\n 'ytick.color': 'white',\n }\n plt.rcParams.update(params)\n\ndef set_mood_light():\n c1 = 'black'\n c2 = 'white'\n params = {\n 'figure.edgecolor': c1,\n 'figure.facecolor': c2,\n 'axes.edgecolor': c1,\n 'axes.facecolor': c2,\n 'savefig.edgecolor': c1,\n 'savefig.facecolor': c2,\n 'text.color': c1,\n 'axes.labelcolor': c1,\n 'boxplot.boxprops.color': c1,\n 'boxplot.capprops.color': c1,\n 'boxplot.flierprops.color': c1,\n 'boxplot.flierprops.markeredgecolor': c1,\n 'boxplot.whiskerprops.color': c1,\n 'grid.color': '#b0b0b0',\n 'hatch.color': c1,\n 'image.cmap': 'hot',\n 'patch.edgecolor': c1,\n 'xtick.color': c1,\n 'ytick.color': c1,\n }\n plt.rcParams.update(params)\n\n\n#family='Arial'\ndef set_font(size=20,family='CMU Serif',weight='bold'):\n params = {\n 'xtick.labelsize': size,\n 'ytick.labelsize': size,\n 'axes.labelsize': size,\n 'axes.titlesize': size,\n 'font.size': size,\n 'legend.title_fontsize': size,\n 'legend.fontsize': size,\n 'figure.titlesize': size,\n 'font.family': family,\n 'font.weight': weight,\n 'axes.labelweight':weight,\n 'axes.titleweight': weight,\n }\n plt.rcParams.update(params)\n\n\nParams_ = {'_internal.classic_mode': False,\n 'agg.path.chunksize': 0,\n 'animation.avconv_args': [],\n 'animation.avconv_path': 'avconv',\n 'animation.bitrate': -1,\n 'animation.codec': 'h264',\n 'animation.convert_args': [],\n 'animation.convert_path': 'convert',\n 'animation.embed_limit': 20.0,\n 'animation.ffmpeg_args': [],\n 'animation.ffmpeg_path': 'ffmpeg',\n 'animation.frame_format': 'png',\n 'animation.html': 'none',\n 'animation.html_args': [],\n 'animation.writer': 'ffmpeg',\n 'axes.autolimit_mode': 'data',\n 'axes.axisbelow': 'line',\n 'axes.edgecolor': 'black',\n 'axes.facecolor': 'white',\n 'axes.formatter.limits': [-7, 7],\n 'axes.formatter.min_exponent': 0,\n 'axes.formatter.offset_threshold': 4,\n 'axes.formatter.use_locale': False,\n 'axes.formatter.use_mathtext': True,\n 'axes.formatter.useoffset': True,\n 'axes.grid': False,\n 'axes.grid.axis': 'both',\n 'axes.grid.which': 'both',\n 'axes.labelcolor': 'black',\n 'axes.labelpad': 4.0,\n 'axes.labelsize': 20.0,\n 'axes.labelweight': 'bold',\n 'axes.linewidth': 1.5,\n 'axes.prop_cycle': ((cycler('color', ['blue', 'red', 'green', 'purple', 'brown']) + cycler('linestyle', ['-', '-', '-', '-', '-'])) + cycler('marker', ['', '', '', '', ''])),\n 'axes.spines.bottom': True,\n 'axes.spines.left': True,\n 'axes.spines.right': True,\n 'axes.spines.top': True,\n 'axes.titlepad': 6.0,\n 'axes.titlesize': 20.0,\n 'axes.titleweight': 'bold',\n 'axes.unicode_minus': True,\n 'axes.xmargin': 0.05,\n 'axes.ymargin': 0.05,\n 'axes3d.grid': True,\n 'backend': 'module://ipykernel.pylab.backend_inline',\n 'backend_fallback': True,\n 'boxplot.bootstrap': None,\n 'boxplot.boxprops.color': 'black',\n 'boxplot.boxprops.linestyle': '-',\n 'boxplot.boxprops.linewidth': 1.0,\n 'boxplot.capprops.color': 'black',\n 'boxplot.capprops.linestyle': '-',\n 'boxplot.capprops.linewidth': 1.0,\n 'boxplot.flierprops.color': 'black',\n 'boxplot.flierprops.linestyle': 'none',\n 'boxplot.flierprops.linewidth': 1.0,\n 'boxplot.flierprops.marker': 'o',\n 'boxplot.flierprops.markeredgecolor': 'black',\n 'boxplot.flierprops.markerfacecolor': 'none',\n 'boxplot.flierprops.markersize': 10.0,\n 'boxplot.meanline': False,\n 'boxplot.meanprops.color': 'C2',\n 'boxplot.meanprops.linestyle': '--',\n 'boxplot.meanprops.linewidth': 1.0,\n 'boxplot.meanprops.marker': '^',\n 'boxplot.meanprops.markeredgecolor': 'C2',\n 'boxplot.meanprops.markerfacecolor': 'C2',\n 'boxplot.meanprops.markersize': 10.0,\n 'boxplot.medianprops.color': 'C1',\n 'boxplot.medianprops.linestyle': '-',\n 'boxplot.medianprops.linewidth': 1.0,\n 'boxplot.notch': False,\n 'boxplot.patchartist': False,\n 'boxplot.showbox': True,\n 'boxplot.showcaps': True,\n 'boxplot.showfliers': True,\n 'boxplot.showmeans': False,\n 'boxplot.vertical': True,\n 'boxplot.whiskerprops.color': 'black',\n 'boxplot.whiskerprops.linestyle': '-',\n 'boxplot.whiskerprops.linewidth': 1.0,\n 'boxplot.whiskers': 1.5,\n 'contour.corner_mask': True,\n 'contour.negative_linestyle': 'dashed',\n 'date.autoformatter.day': '%Y-%m-%d',\n 'date.autoformatter.hour': '%m-%d %H',\n 'date.autoformatter.microsecond': '%M:%S.%f',\n 'date.autoformatter.minute': '%d %H:%M',\n 'date.autoformatter.month': '%Y-%m',\n 'date.autoformatter.second': '%H:%M:%S',\n 'date.autoformatter.year': '%Y',\n 'docstring.hardcopy': False,\n 'errorbar.capsize': 3.0,\n 'figure.autolayout': False,\n 'figure.constrained_layout.h_pad': 0.04167,\n 'figure.constrained_layout.hspace': 0.02,\n 'figure.constrained_layout.use': False,\n 'figure.constrained_layout.w_pad': 0.04167,\n 'figure.constrained_layout.wspace': 0.02,\n 'figure.dpi': 72.0,\n 'figure.edgecolor': (1, 1, 1, 0),\n 'figure.facecolor': 'w',\n 'figure.figsize': [6.0, 6.0],\n 'figure.max_open_warning': 20,\n 'figure.subplot.bottom': 0.125,\n 'figure.subplot.hspace': 0.2,\n 'figure.subplot.left': 0.125,\n 'figure.subplot.right': 0.9,\n 'figure.subplot.top': 0.88,\n 'figure.subplot.wspace': 0.2,\n 'figure.titlesize': 20.0,\n 'figure.titleweight': 'bold',\n 'font.cursive': ['Apple Chancery',\n 'Textile',\n 'Zapf Chancery',\n 'Sand',\n 'Script MT',\n 'Felipa',\n 'cursive'],\n 'font.family': ['Arial'],\n 'font.fantasy': ['Comic Sans MS',\n 'Chicago',\n 'Charcoal',\n 'Impact',\n 'Western',\n 'Humor Sans',\n 'xkcd',\n 'fantasy'],\n 'font.monospace': ['DejaVu Sans Mono',\n 'Bitstream Vera Sans Mono',\n 'Computer Modern Typewriter',\n 'Andale Mono',\n 'Nimbus Mono L',\n 'Courier New',\n 'Courier',\n 'Fixed',\n 'Terminal',\n 'monospace'],\n 'font.sans-serif': ['DejaVu Sans',\n 'Bitstream Vera Sans',\n 'Computer Modern Sans Serif',\n 'Lucida Grande',\n 'Verdana',\n 'Geneva',\n 'Lucid',\n 'Arial',\n 'Helvetica',\n 'Avant Garde',\n 'sans-serif'],\n 'font.serif': ['DejaVu Serif',\n 'Times New Roman',\n 'Bitstream Vera Serif',\n 'Computer Modern Roman',\n 'New Century Schoolbook',\n 'Century Schoolbook L',\n 'Utopia',\n 'ITC Bookman',\n 'Bookman',\n 'Nimbus Roman No9 L',\n 'Times New Roman',\n 'Times',\n 'Palatino',\n 'Charter',\n 'serif'],\n 'font.size': 20.0,\n 'font.stretch': 'normal',\n 'font.style': 'normal',\n 'font.variant': 'normal',\n 'font.weight': 'bold',\n 'grid.alpha': 1.0,\n 'grid.color': '#b0b0b0',\n 'grid.linestyle': '-',\n 'grid.linewidth': 0.8,\n 'hatch.color': 'black',\n 'hatch.linewidth': 1.0,\n 'hist.bins': 10,\n 'image.aspect': 'equal',\n 'image.cmap': 'viridis',\n 'image.composite_image': True,\n 'image.interpolation': 'nearest',\n 'image.lut': 256,\n 'image.origin': 'lower',\n 'image.resample': True,\n 'interactive': True,\n 'keymap.all_axes': ['a'],\n 'keymap.back': ['left', 'c', 'backspace'],\n 'keymap.copy': ['ctrl+c', 'cmd+c'],\n 'keymap.forward': ['right', 'v'],\n 'keymap.fullscreen': ['f', 'ctrl+f'],\n 'keymap.grid': ['g'],\n 'keymap.grid_minor': ['G'],\n 'keymap.help': ['f1'],\n 'keymap.home': ['h', 'r', 'home'],\n 'keymap.pan': ['p'],\n 'keymap.quit': ['ctrl+w', 'cmd+w', 'q'],\n 'keymap.quit_all': ['W', 'cmd+W', 'Q'],\n 'keymap.save': ['s', 'ctrl+s'],\n 'keymap.xscale': ['k', 'L'],\n 'keymap.yscale': ['l'],\n 'keymap.zoom': ['o'],\n 'legend.borderaxespad': 0.5,\n 'legend.borderpad': 0.4,\n 'legend.columnspacing': 2.0,\n 'legend.edgecolor': '0.8',\n 'legend.facecolor': 'inherit',\n 'legend.fancybox': True,\n 'legend.fontsize': 20.0,\n 'legend.framealpha': 0.8,\n 'legend.frameon': False,\n 'legend.handleheight': 0.7,\n 'legend.handlelength': 2.0,\n 'legend.handletextpad': 0.8,\n 'legend.labelspacing': 0.5,\n 'legend.loc': 'best',\n 'legend.markerscale': 1.0,\n 'legend.numpoints': 1,\n 'legend.scatterpoints': 1,\n 'legend.shadow': False,\n 'legend.title_fontsize': 20.0,\n 'lines.antialiased': True,\n 'lines.color': 'C0',\n 'lines.dash_capstyle': 'butt',\n 'lines.dash_joinstyle': 'round',\n 'lines.dashdot_pattern': [6.4, 1.6, 1.0, 1.6],\n 'lines.dashed_pattern': [3.7, 1.6],\n 'lines.dotted_pattern': [1.0, 1.65],\n 'lines.linestyle': '-',\n 'lines.linewidth': 2.0,\n 'lines.marker': 'None',\n 'lines.markeredgecolor': 'auto',\n 'lines.markeredgewidth': 1.0,\n 'lines.markerfacecolor': 'auto',\n 'lines.markersize': 10.0,\n 'lines.scale_dashes': True,\n 'lines.solid_capstyle': 'projecting',\n 'lines.solid_joinstyle': 'round',\n 'markers.fillstyle': 'full',\n 'mathtext.bf': 'sans:bold',\n 'mathtext.cal': 'cursive',\n 'mathtext.default': 'default',\n 'mathtext.fallback_to_cm': True,\n 'mathtext.fontset': 'custom',\n 'mathtext.it': 'sans:italic',\n 'mathtext.rm': 'sans',\n 'mathtext.sf': 'sans',\n 'mathtext.tt': 'monospace',\n 'patch.antialiased': True,\n 'patch.edgecolor': 'black',\n 'patch.facecolor': 'C0',\n 'patch.force_edgecolor': False,\n 'patch.linewidth': 1.0,\n 'path.effects': [],\n 'path.simplify': True,\n 'path.simplify_threshold': 0.1111111111111111,\n 'path.sketch': None,\n 'path.snap': True,\n 'pdf.compression': 6,\n 'pdf.fonttype': 3,\n 'pdf.inheritcolor': False,\n 'pdf.use14corefonts': False,\n 'pgf.preamble': [],\n 'pgf.rcfonts': True,\n 'pgf.texsystem': 'xelatex',\n 'polaraxes.grid': True,\n 'ps.distiller.res': 6000,\n 'ps.fonttype': 3,\n 'ps.papersize': 'letter',\n 'ps.useafm': False,\n 'ps.usedistiller': False,\n 'savefig.bbox': 'tight',\n 'savefig.directory': '~',\n 'savefig.dpi': 'figure',\n 'savefig.edgecolor': 'white',\n 'savefig.facecolor': 'white',\n 'savefig.format': 'png',\n 'savefig.jpeg_quality': 300,\n 'savefig.orientation': 'portrait',\n 'savefig.pad_inches': 0.1,\n 'savefig.transparent': True,\n 'scatter.marker': 'o',\n 'svg.fonttype': 'path',\n 'svg.hashsalt': None,\n 'svg.image_inline': True,\n 'text.antialiased': True,\n 'text.color': 'black',\n 'text.hinting': 'auto',\n 'text.hinting_factor': 8,\n 'text.latex.preamble': ['\\\\boldmath',],\n 'text.latex.preview': True,\n 'text.usetex': False,\n 'timezone': 'UTC',\n 'tk.window_focus': False,\n 'toolbar': 'toolbar2',\n 'xtick.alignment': 'center',\n 'xtick.bottom': True,\n 'xtick.color': 'black',\n 'xtick.direction': 'in',\n 'xtick.labelbottom': True,\n 'xtick.labelsize': 18.0,\n 'xtick.labeltop': False,\n 'xtick.major.bottom': True,\n 'xtick.major.pad': 3.5,\n 'xtick.major.size': 10,\n 'xtick.major.top': True,\n 'xtick.major.width': 1.5,\n 'xtick.minor.bottom': True,\n 'xtick.minor.pad': 3.4,\n 'xtick.minor.size': 6,\n 'xtick.minor.top': True,\n 'xtick.minor.visible': True,\n 'xtick.minor.width': 1.5,\n 'xtick.top': True,\n 'ytick.alignment': 'center_baseline',\n 'ytick.color': 'black',\n 'ytick.direction': 'in',\n 'ytick.labelleft': True,\n 'ytick.labelright': False,\n 'ytick.labelsize': 18.0,\n 'ytick.left': True,\n 'ytick.major.left': True,\n 'ytick.major.pad': 3.5,\n 'ytick.major.right': True,\n 'ytick.major.size': 10,\n 'ytick.major.width': 1.5,\n 'ytick.minor.left': True,\n 'ytick.minor.pad': 3.4,\n 'ytick.minor.right': True,\n 'ytick.minor.size': 6.0,\n 'ytick.minor.visible': True,\n 'ytick.minor.width': 1.5,\n 'ytick.right': True}\n\nlabel = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p']\n\nfrom matplotlib.ticker import FuncFormatter\n\ndef my_formatter(x, pos):\n if x==0:\n return x\n else:\n return x\nformatter = FuncFormatter(my_formatter)\n\n\nclass MyLocator(matplotlib.ticker.AutoMinorLocator):\n def __init__(self, n=2):\n super().__init__(n=n)\n\nmatplotlib.ticker.AutoMinorLocator = MyLocator\n\ndef autolabel(ax, fmt=\"{}\", values=None, **kwargs):\n for ind,rect in enumerate(ax.patches):\n x = rect.get_x() + rect.get_width()/2.\n y = rect.get_height()\n if values==None:\n label = y\n else:\n label = values[ind]\n ax.annotate(fmt.format(label), (x,y), xytext=(0,5), textcoords=\"offset points\",\n ha='center', va='bottom', weight='bold', **kwargs)\n\n\ndef make_custom_legend(patches,texts,*args,**kwargs):\n leg = plt.legend(patches,texts,*args,**kwargs)\n for text,p in zip(leg.get_texts(),patches):\n text.set_color(p.get_fc())\n\n\ndef beautify_leg(leg,color=None):\n # change the font colors to match the line colors:\n if color==None:\n for handle,text in zip(leg.legendHandles, leg.get_texts()):\n try:\n text.set_color(handle.get_color()[0][:3])\n except:\n text.set_color(handle.get_color())\n text.set_text(text.get_text())\n else:\n for handle,text in zip(leg.legendHandles, leg.get_texts()):\n text.set_color(color)\n text.set_text(text.get_text())\n def first_h(h):\n try:\n return h[0]\n except:\n return h\n leg.legendHandles = [first_h(h) for h in leg.legendHandles]\n return leg\n\n\n\n return leg\n\n\ndef panel(rows,cols, figsize=None, size=6, mx=1, my=1, l_p = 0.16, b_p=0.16,r_p = 0.08, t_p=0.08, vs=0.25, hs=0.25, brackets = True,label_align = ['left','top'],\n hshift=0.75*0.25, vshift = 0.3*0.25,label=label,merge=(),**kwargs):\n global mpl,plt\n import matplotlib.gridspec as gridspec\n gs = gridspec.GridSpec(rows, cols)\n\n\n labels = label.copy()\n\n if brackets:\n for ind,i in enumerate(label):\n labels[ind] = __t('({})'.format(i))\n\n n = cols\n m = rows\n\n l_p = l_p/n\n r_p = r_p/n\n b_p = b_p/m\n t_p = t_p/m\n\n fig_y = size*(m+vs*(m-1))/(1-t_p-b_p)\n fig_x = size*(n+hs*(n-1))/(1-l_p-r_p)\n\n r_p = 1-r_p\n t_p = 1-t_p\n\n sx = size/fig_x\n sy = size/fig_y\n\n fig_x *= mx\n fig_y *= my\n\n if figsize==None:\n figsize=[fig_x,fig_y]\n fig = plt.figure(figsize=figsize, **kwargs)\n fig.set_size_inches(*figsize)\n plt.subplots_adjust(top=t_p, bottom=b_p, left=l_p, right=r_p, hspace=vs,\n wspace=hs)\n\n ind = 0\n axis = []\n for i in range(rows):\n for j in range(cols):\n if 0:\n pass\n else:\n ax = plt.subplot(rows,cols,i*cols+j+1)\n if rows*cols==1:\n pass\n else:\n ax.text(0-hshift, 1+vshift, '{}'.format(labels[ind]),\n horizontalalignment=label_align[0],verticalalignment=label_align[1],transform=ax.transAxes)\n\n axis.append(ax)\n ind += 1\n\n # for ax in axis:\n # ax.xaxis.set_major_formatter(formatter)\n # ax.yaxis.set_major_formatter(formatter)\n\n return fig,axis\n\ndef title(ttl,ax = 0,**kwargs):\n global plt\n try:\n iter(ax)\n for i in zip(ttl,ax):\n i[1].set_title(__t(i[0]),**kwargs)\n except:\n if ax==0:\n ax = plt.gca()\n ax.set_title(__t(ttl),**kwargs)\n\ndef xlabel(label,ax = 0,**kwargs):\n global plt\n try:\n iter(ax)\n for i in zip(label,ax):\n i[1].set_xlabel(__t(i[0]),**kwargs)\n except:\n if ax==0:\n ax = plt.gca()\n ax.set_xlabel(__t(label),**kwargs)\n\ndef ylabel(label,ax = 0,**kwargs):\n global plt\n try:\n iter(ax)\n for i in zip(label,ax):\n i[1].set_ylabel(__t(i[0]),**kwargs)\n except:\n if ax==0:\n ax = plt.gca()\n ax.set_ylabel(__t(label),**kwargs)\n\n\ndef xticks(pos,ax = None,labels = None,**kwargs):\n global plt,font\n if ax==None:\n ax = plt.gca()\n ax.set_xticks(pos,**kwargs)\n if labels==None:\n pass\n else:\n ax.set_xticklabels(['{}'.format(i) for i in labels])\n\ndef yticks(pos,ax = None,labels = None,**kwargs):\n global plt,font\n if ax==None:\n ax = plt.gca()\n ax.set_yticks(pos,**kwargs)\n if labels==None:\n pass\n else:\n ax.set_yticklabels(['{}'.format(i) for i in labels])\n\ndef xlim(lim,ax = None,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n ax.set_xlim(lim,**kwargs)\n\ndef ylim(lim,ax = None,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n ax.set_ylim(lim,**kwargs)\n\ndef vertical(x0,line='',ax = None,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n ax.axvline(x0,**kwargs)\n\ndef horizontal(y0,line='',ax = None,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n ax.axhline(y0,**kwargs)\n\n\ndef legend_off(ax=None):\n global plt\n if ax==None:\n ax = plt.gca()\n ax.get_legend().remove()\n\ndef legend_on(ax=None,color=None,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n leg = ax.legend(frameon=False,**kwargs) #loc=1,bbox_to_anchor=[0.95,0.95],)\n return beautify_leg(leg,color)\n\ndef legend_on2(ax=None,color=None,frameon=False,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n # get handles\n handles, labels = ax.get_legend_handles_labels()\n # remove the errorbars\n def first_h(h):\n try:\n return h[0]\n except:\n return h\n handles = [first_h(h) for h in handles]\n # use them in the legend\n leg = ax.legend(handles, labels, frameon=frameon,**kwargs) #loc=1,bbox_to_anchor=[0.95,0.95],)\n return beautify_leg(leg,color)\n\n\ndef sticky_legend(pos,c=0,ax=None):\n global plt\n if ax==None:\n ax = plt.gca()\n legend_on(ax)\n lines = ax.get_legend().get_lines()\n texts = ax.get_legend().get_texts()\n ax.annotate('{}'.format(texts[c].get_text()), xy=(pos[0], pos[1]), color=lines[c].get_color())\n legend_off(ax)\n\ndef twinx(ax,color=['b','r']):\n global plt\n ax2 = ax.twinx()\n ax.spines['left'].set_edgecolor(color[0])\n ax.spines['right'].set_visible(False)\n ax.tick_params(axis='y',colors=color[0],which='both')\n ax2.spines['right'].set_edgecolor(color[1])\n ax2.spines['left'].set_visible(False)\n ax2.tick_params(axis='y',colors=color[1],which='both')\n return ax2,ax\n\ndef twiny(ax,color=['b','r']):\n global plt\n ax2 = ax.twiny()\n ax.spines['bottom'].set_edgecolor(color[0])\n ax.spines['top'].set_visible(False)\n ax.tick_params(axis='x',colors=color[0],which='both')\n ax2.spines['top'].set_edgecolor(color[1])\n ax2.spines['bottom'].set_visible(False)\n ax2.tick_params(axis='x',colors=color[1],which='both')\n ax2.set_yticklabels(horizontalalignment='right')\n return ax2\n\ndef zero_axis(color='k',alpha=0.2,linewidth = 0.5,**kwargs):\n horizontal(y0=0,color=color,alpha=alpha,linewidth=linewidth,**kwargs)\n vertical(x0=0,color=color,alpha=alpha,linewidth=linewidth,**kwargs)\n\ndef arrow(ax=None,pos=[[0,0],[1,1]],fc='k',alpha=1,curve=0,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n connectionstyle=\"arc3,rad={}\".format(curve)\n arrowprops=dict(fc = fc, alpha = alpha,**kwargs,connectionstyle=connectionstyle)\n ax.annotate(\"\", xytext=pos[0], xy=pos[1],arrowprops=arrowprops)\n\ndef annot(text,point,put,ax=None,connectionstyle=None,fc='k',alpha=1,curve=0,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n if connectionstyle==None:\n connectionstyle=\"arc3,rad={}\".format(curve)\n arrowprops=dict(fc = fc, alpha = alpha,**kwargs,connectionstyle=connectionstyle)\n ax.annotate('{}'.format(text), xytext=put, xy=point,arrowprops=arrowprops,**kwargs)\n\ndef text(x,y,text,ax=None,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n return ax.text(x,y,__t(text), **kwargs)\n\ndef savefig(filename,dpi=80,**kwargs):\n global plt\n plt.savefig(filename,dpi=dpi,**kwargs)\n\ndef show():\n global plt\n plt.show()\n\ndef padding(l_p = 0.1, r_p = 0.05, b_p=0.1, t_p=0.05, vs=0.1, hs=0, size=6, **kwargs):\n n = 1\n m = 1\n r_p = 1-r_p/n\n t_p = 1-t_p/m\n fig_y = m*size/(t_p-b_p-(m-1)*vs)\n fig_y = m*size/(t_p-b_p-(m-1)*vs*size/fig_y)\n fig_y = m*size/(t_p-b_p-(m-1)*vs*size/fig_y)\n fig_x = n*size/(r_p-l_p-(n-1)*hs)\n fig_x = n*size/(r_p-l_p-(n-1)*hs*size/fig_x)\n fig_x = n*size/(r_p-l_p-(n-1)*hs*size/fig_x)\n\n global plt\n fig = plt.gcf()\n fig.set_size_inches(fig_x,fig_y)\n plt.subplots_adjust(top=t_p, bottom=b_p, left=l_p, right=r_p, hspace=vs,\n wspace=hs,**kwargs)\n\ndef bar_plot(data,ax=None,x_ind=0,label=None,rot=0,fontsize=14,fmt=\"{}\",\n text=False, hatch=None,\n fig_size=6,l_p = 0.16, b_p=0.16,r_p = 0.05, t_p=0.05, vs=0.25, hs=0.25,\n hshift=0.75*0.25, vshift = 0.3*0.25, **kwargs):\n global np, plt, mpl\n data = numpy.array(data)\n if data.ndim==1:\n data = [data]\n if hatch==None:\n hatch = ['']*len(data)\n\n if plt.get_fignums():\n fig = plt.gcf()\n else:\n fig,ax = panel(1,1,size=fig_size,l_p = l_p, r_p = r_p, b_p=b_p, t_p=t_p, vs=vs, hs=hs, )\n ax = plt.gca()\n\n width = (numpy.diff(data[x_ind])).min()\n if width<=0:\n print('x values are not consistant.')\n else:\n len1 = len(data)-1\n width=width/(len1+1)\n incr = 0\n for ind,y in enumerate(data):\n if ind==x_ind:\n pass\n else:\n x = numpy.array(data[x_ind])-len1*width/2+width/2+width*incr\n y = [i for i in data[ind]]\n ax.bar(x,y,width=width,label=label[ind],hatch = hatch[ind],**kwargs)\n ax.tick_params(top=False,bottom=False,which='both')\n if text:\n autolabel(ax,rotation=rot,size=fontsize,fmt=fmt)\n incr += 1\n\ndef line_plot(x,y,*args,fig_size=6,l_p = 0.16, b_p=0.16,r_p = 0.05, t_p=0.05, vs=0.25, hs=0.25,\n hshift=0.75*0.25, vshift = 0.3*0.25, **kwargs):\n global mpl,plt\n\n if plt.get_fignums():\n fig = plt.gcf()\n else:\n fig,ax = panel(1,1,size=fig_size,l_p = l_p, r_p = r_p, b_p=b_p, t_p=t_p, vs=vs, hs=hs, )\n ax = plt.gca()\n ax.plot(x,y,*args,**kwargs)\n\n return fig, ax\n\ndef put_image(image_file,*args,fig_size=6,l_p = 0.16, b_p=0.16,r_p = 0.05, t_p=0.05, vs=0.25, hs=0.25,\n hshift=0.75*0.25, vshift = 0.3*0.25, **kwargs):\n global mpl,plt\n\n if plt.get_fignums():\n fig = plt.gcf()\n else:\n fig,ax = panel(1,1,size=fig_size,l_p = l_p, r_p = r_p, b_p=b_p, t_p=t_p, vs=vs, hs=hs, )\n ax = plt.gca()\n image = plt.imread(image_file)\n ax.imshow(image[::-1],*args,**kwargs)\n ax.set_axis_off()\n\n return fig, ax\n\ndef h_strip(y0,y1,ax=None,color='k',alpha=0.2,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n ax.axhspan(y0,y1,color=color,alpha=alpha,**kwargs)\n\ndef v_strip(x0,x1,ax=None,color='k',alpha=0.2,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n ax.axvspan(x0,x1,color=color,alpha=alpha,**kwargs)\n\n\ndef makePatch(vertices,ax=None,fc='grey',ec='none',alpha=0.2,curve=0,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n incr = {0:Path.LINETO,1:Path.CURVE3,2:Path.CURVE4}\n codes = []\n vertices_all = []\n for vert in vertices:\n codes = [Path.MOVETO] + [incr[curve]]*(len(vert)-1) + [Path.CLOSEPOLY]\n vertices_all += list(vert) + [vert[0]]\n\n vertices_all = numpy.array(vertices_all, float)\n path = Path(vertices_all, codes)\n\n pathpatch = PathPatch(path, facecolor=fc, edgecolor=ec,alpha=alpha,**kwargs)\n ax.add_patch(pathpatch)\n return pathpatch\n\ndef rectangle(xlo,xhi,ylo,yhi,ax=None,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n vertices = [[xlo,ylo],[xlo,yhi],[xhi,yhi],[xhi,ylo]]\n return makePatch([vertices],ax=ax,**kwargs)\n\ndef polygon(origin,radius,sides=3,y_scale=0,b=1,b_=1,rot=0,ax=None,**kwargs):\n global plt\n if ax==None:\n ax = plt.gca()\n vertices = []\n range_x = ax.get_xlim()\n range_y = ax.get_ylim()\n if y_scale==0:\n y_scale = numpy.abs((range_y[1]-range_y[0])/(range_x[1]-range_x[0]))\n else:\n b = 1\n b_ = 1\n\n theta = rot/180*numpy.pi\n for i in numpy.arange(0,1,1/sides)*2*numpy.pi:\n x = radius*numpy.cos(i)\n y = b*radius*numpy.sin(i)\n vertices.append([origin[0]+x*numpy.cos(theta)+y*numpy.sin(theta), origin[1]+y_scale*b_*(-x*numpy.sin(theta)+y*numpy.cos(theta))])\n return makePatch([vertices],ax=ax,**kwargs)\n\ndef ellipse(origin,radius,b = 1, **kwargs):\n return polygon(origin,radius,b = b, sides = 100,**kwargs)\n\ndef linestyles(color = ['blue','red','green','purple','brown','magenta','black'], ls = ['-'], ms = ['']):\n global plt,cycler\n if len(ls)==1:\n ls = ls * len(color)\n if len(ms)==1:\n ms = ms * len(color)\n\n plt.rc('axes', prop_cycle=(cycler('color', color) + cycler('linestyle', ls) + cycler('marker', ms) ) )\n return (cycler('color', color) + cycler('linestyle', ls) + cycler('marker', ms) )\n\n\ndef grid_on():\n global plt\n plt.grid()\n\ndef grid_off():\n global plt\n plt.grid(False)\n\ndef linear(x,m,c):\n return m*numpy.array(x) + c\n\ndef fit(x_data,y_data,xs,*args,func=linear,precision=2,spline=False,skip_fit=False, label=r'${}x+{}$',**kwargs):\n from scipy.optimize import curve_fit\n\n if skip_fit:\n ys = y_data\n else:\n popt, pcov = curve_fit(func,x_data,y_data)\n ys = func(numpy.array(xs),*popt)\n params = [ '{:.{}f}'.format(p[0],p[1]) for p in zip(popt,precision)]\n label = label.format(*params)\n try:\n len(precision)\n except:\n precision = [precision]*len(popt)\n\n if spline:\n tck,u = interpolate.splprep([xs,ys],s=0)\n xs,ys1 = interpolate.splev(numpy.linspace(0,1,100),tck,der=0)\n else:\n ys1 = ys\n\n line_plot(xs,ys1,*args,label=label,**kwargs)\n return ys,label\n\ndef set_markersize(ms):\n for i in plt.rcParams:\n if 'markersize' in i:\n plt.rcParams[i] = ms\n\ndef inset(bounds, labelsize=16, ax = None, **kwargs):\n\n global plt,mpl\n\n if ax == None:\n ax = plt.gca()\n in_ax = ax.inset_axes(bounds=bounds)\n ax.figure.add_axes(in_ax)\n\n in_ax.tick_params(axis= 'both',labelsize=labelsize)\n\n return in_ax\n\ndef zoomed_in(x,y,*args,bounds=[0.15,0.6,0.35,0.35],labelsize=16, ax = None, connect = True, loc1=2, loc2=4,loc3=None,loc4=None,prop={},**kwargs):\n prop1 = dict(fc=\"grey\", ec=\"grey\",alpha=0.2)\n prop1.update(prop)\n\n global plt,mpl\n if loc3 == None:\n loc3 = loc1\n if loc4 == None:\n loc4 = loc2\n\n if ax == None:\n ax = plt.gca()\n in_ax = ax.inset_axes(bounds=bounds)\n ax.figure.add_axes(in_ax)\n\n\n\n in_ax.tick_params(axis= 'both',labelsize=labelsize)\n\n in_ax.plot(x,y,*args,**kwargs)\n aspect_ratio = numpy.diff(ax.get_ylim())/numpy.diff(ax.get_xlim())\n aspect_ratio2 = numpy.diff(in_ax.get_ylim())/numpy.diff(in_ax.get_xlim())\n\n if aspect_ratio>aspect_ratio2:\n Ylim = in_ax.get_ylim()\n in_ax.set_ylim([numpy.mean(Ylim)-aspect_ratio/aspect_ratio2*numpy.diff(Ylim)/2, numpy.mean(Ylim)+aspect_ratio/aspect_ratio2*numpy.diff(Ylim)/2,])\n\n if aspect_ratio2>aspect_ratio:\n Xlim = in_ax.get_xlim()\n in_ax.set_xlim([numpy.mean(Xlim)-aspect_ratio2/aspect_ratio*numpy.diff(Xlim)/2, numpy.mean(Xlim)+aspect_ratio2/aspect_ratio*numpy.diff(Xlim)/2,])\n\n if connect:\n from mpl_toolkits.axes_grid1.inset_locator import mark_inset\n mark_inset(ax, in_ax, loc1=loc1, loc2=loc2,**prop1,)\n mark_inset(ax, in_ax, loc1=loc3, loc2=loc4,**prop1,)\n\n return in_ax\n\n\ndef set_things():\n linestyles()\n mpl.rcParams.update(Params_)\n\n\n\nimport math\nimport matplotlib.pyplot as plt\nclass AnnoteFinder(object):\n \"\"\"callback for matplotlib to display an annotation when points are\n clicked on. The point which is closest to the click and within\n xtol and ytol is identified.\n\n Register this function like this:\n\n scatter(xdata, ydata)\n af = AnnoteFinder(xdata, ydata, annotes)\n connect('button_press_event', af)\n\n example:\n\n x = range(10)\n y = range(10)\n annotes = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']\n\n fig, ax = plt.subplots()\n ax.scatter(x,y)\n af = AnnoteFinder(x,y, annotes, ax=ax)\n fig.canvas.mpl_connect('button_press_event', af)\n plt.show()\n \"\"\"\n\n def __init__(self, xdata, ydata, annotes, ax=None, xtol=None, ytol=None):\n self.data = list(zip(xdata, ydata, annotes))\n if xtol is None:\n xtol = ((max(xdata) - min(xdata))/float(len(xdata)))/2\n if ytol is None:\n ytol = ((max(ydata) - min(ydata))/float(len(ydata)))/2\n self.xtol = xtol\n self.ytol = ytol\n if ax is None:\n self.ax = plt.gca()\n else:\n self.ax = ax\n self.drawnAnnotations = {}\n self.links = []\n\n def distance(self, x1, x2, y1, y2):\n \"\"\"\n return the distance between two points\n \"\"\"\n return(math.sqrt((x1 - x2)**2 + (y1 - y2)**2))\n\n def __call__(self, event):\n\n if event.inaxes:\n\n clickX = event.xdata\n clickY = event.ydata\n if (self.ax is None) or (self.ax is event.inaxes):\n annotes = []\n # print(event.xdata, event.ydata)\n for x, y, a in self.data:\n # print(x, y, a)\n if ((clickX-self.xtol < x < clickX+self.xtol) and\n (clickY-self.ytol < y < clickY+self.ytol)):\n annotes.append(\n (self.distance(x, clickX, y, clickY), x, y, a))\n if annotes:\n annotes.sort()\n distance, x, y, annote = annotes[0]\n self.drawAnnote(event.inaxes, x, y, annote)\n for l in self.links:\n l.drawSpecificAnnote(annote)\n\n def drawAnnote(self, ax, x, y, annote):\n \"\"\"\n Draw the annotation on the plot\n \"\"\"\n if (x, y) in self.drawnAnnotations:\n markers = self.drawnAnnotations[(x, y)]\n for m in markers:\n m.set_visible(not m.get_visible())\n self.ax.figure.canvas.draw_idle()\n else:\n t = ax.text(x, y, \" - %s\" % (annote),)\n m = ax.scatter([x], [y], marker='d', c='r', zorder=100)\n self.drawnAnnotations[(x, y)] = (t, m)\n self.ax.figure.canvas.draw_idle()\n\n def drawSpecificAnnote(self, annote):\n annotesToDraw = [(x, y, a) for x, y, a in self.data if a == annote]\n for x, y, a in annotesToDraw:\n self.drawAnnote(self.ax, x, y, a)\n\ndef linkAnnotationFinders(afs):\n r'''\n\n subplot(121)\n scatter(x,y)\n af1 = AnnoteFinder(x,y, annotes)\n connect('button_press_event', af1)\n\n subplot(122)\n scatter(x,y)\n af2 = AnnoteFinder(x,y, annotes)\n connect('button_press_event', af2)\n\n linkAnnotationFinders([af1, af2])\n '''\n for i in range(len(afs)):\n allButSelfAfs = afs[:i]+afs[i+1:]\n afs[i].links.extend(allButSelfAfs)\n\ndef colorbar(cb,ax=None,where=\"right\",size=\"5%\",pad=0.1,**kwargs):\n if ax==None:\n ax = plt.gca()\n divider = make_axes_locatable(ax)\n cax = divider.append_axes(where, size=size, pad=pad, **kwargs)\n return plt.colorbar(cb, cax=cax,)\n\n\ndef smooth_curve(x,y,**kwargs):\n import numpy as np\n x = np.array(x).ravel()\n y = np.array(y).ravel()\n tck,u = interpolate.splprep([x,y], **kwargs)\n unew = np.arange(0, 1.01, 0.01)\n out = interpolate.splev(unew, tck)\n return out[0], out[1]\n\ndef spline_plot(x,y,*args,sprop=None, **kwargs):\n if sprop==None:\n sprop = {'k':1,'s':0}\n x, y = smooth_curve(x,y,**sprop)\n line_plot(x,y,*args,**kwargs)\n\n\ndef scatter2patch(x,y,*arg,ax=None,ms=0.01,sides=3,scalex=1,unary=True,**kwargs):\n import matplotlib.pyplot as plt\n import matplotlib.patches as ptc\n from shapely.affinity import scale\n from shapely.geometry import Point\n from shapely.ops import cascaded_union, unary_union\n polygons = [Point(x[i], y[i]).buffer(ms,sides) for i in range(len(x))]\n polygons = [scale(p,xfact=scalex,yfact=1) for p in polygons]\n if unary:\n polygons = unary_union(polygons)\n else:\n polygons = cascaded_union(polygons)\n\n if ax==None:\n ax = plt.gca()\n try:\n for polygon in polygons:\n polygon = ptc.Polygon(numpy.array(polygon.exterior), **kwargs)\n ax.add_patch(polygon)\n except:\n polygon = ptc.Polygon(numpy.array(polygons.exterior), **kwargs)\n ax.add_patch(polygon)\n\ndef paper(*args,**kwargs):\n linestyles(color=['k'])\n fig, [ax] = panel(1,1,r_p=0,l_p=0,t_p=0,b_p=0,**kwargs)\n ax.axis('off')\n return fig, ax\n\n\nplt.rcParams.update(Params_)\n\n\ndef book_format():\n set_mood_light()\n set_markersize(5)\n set_font(weight='normal')\n","sub_path":"Revealing_the_Compositional_Control_of_Inorganic_Glass_Properties/data_visualization/new_plot.py","file_name":"new_plot.py","file_ext":"py","file_size_in_byte":36066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"571447885","text":"# packaging.py - This module contains classes and functions that are used to create and\n# mount AppFS packages.\n#\n# Licensed under an MIT license. More information at http://code.google.com/p/apptools-dist\n#\n# Created: Thursday, 17th June 2010 by James Rhodes\n# Last Modified: \n\nimport applib.environment as environment\nimport applib.fs as fs\nfrom applib.logging import default_logger as log\nimport tempfile\nimport subprocess\nimport os\nimport time\nimport signal\nfrom xml.sax import saxutils\n\nclass Package():\n\tdef __init__(self, filename):\n\t\tself.filename = filename\n\t\tself.appname_prefix = \"apptools\"\n\t\tself.mountpoint = None\n\t\tself.mountproc = None\n\n\t\tif (not self.isValidEnvironment()):\n\t\t\traise NoPackagingAvailableException()\n\n\tdef setPrefix(self, prefix):\n\t\tself.appname_prefix = prefix\n\n\tdef exists(self):\n\t\treturn os.path.exists(self.filename)\n\t\n\tdef mount(self):\n\t\t# Check to see if we're already mounted.\n\t\tif (self.mountpoint != None):\n\t\t\traise PackageAlreadyMountedException()\n\n\t\t# Check to make sure the package exists.\n\t\tif (not self.exists()):\n\t\t\traise PackageNotFoundException()\n\n\t\t# Create a temporary folder for the mountpoint.\n\t\tmountpoint = tempfile.mkdtemp(\"\", self.appname_prefix + \"_mountpoint.\", \"/tmp/\")\n\n\t\t# Now use appmount to mount it to the specified mountpoint.\n\t\tself.mountproc = subprocess.Popen([\"appmount\", self.filename, mountpoint])\n\t\ti = 0\n\t\twhile (not os.path.exists(os.path.join(mountpoint, \"lost+found\")) and i < 10):\n\t\t\ttime.sleep(1) # Give it a chance to bring up the mountpoint.\n\t\t\ti += 1\n\n\t\t# Check to see if the mountpoint was brought up.\n\t\tif (not os.path.exists(os.path.join(mountpoint, \"lost+found\"))):\n\t\t\t# We're kind of relying on the fact that Ext2 filesystems always have a lost+found\n\t\t\t# directory here... which probably isn't a good idea. There really needs to be a\n\t\t\t# better way to detect whether the mount succeeded (hopefully backgrounding the\n\t\t\t# appmount process via Python is only temporary until appmount is fixed so that it\n\t\t\t# will save the data back to the image on close).\n\t\t\tlog.showErrorW(\"Unable to mount the AppFS image. See messages above.\")\n\t\t\traise PackageMountFailureException()\n\n\t\t#appmount_result = subprocess.call([\"appmount\", self.filename, mountpoint])\n\t\t#if (appmount_result != 0):\n\t\t#\tlog.showErrorW(\"Unable to mount the AppFS image. See messages above.\")\n\t\t#\traise PackageMountFailureException()\n\n\t\tself.mountpoint = mountpoint\n\t\treturn self.mountpoint\n\n\tdef unmount(self):\n\t\t# Check to make sure we're mounted.\n\t\tif (self.mountpoint == None):\n\t\t\traise PackageNotMountedException()\n\n\t\t# Check to make sure the package exists (appmount will write back to it).\n\t\tif (not self.exists()):\n\t\t\traise PackageNotFoundException()\n\t\t\n\t\t# Now unmount the image.\n\t\t#self.mountproc.send_signal(signal.SIGTERM)\n\t\t#self.mountproc.wait()\n\n\t\tresult = self.forceDirectoryUnmount(self.mountpoint)\n\t\tif (not result):\n\t\t\traise PackageUnmountFailureException()\n\n\t\tself.mountproc.wait()\n\n\t\tmntpnt = self.mountpoint\n\t\tself.mountpoint = None\n\n\t\ttry:\n\t\t\tos.rmdir(mntpnt)\n\t\texcept:\n\t\t\traise IOError()\n\n\t\treturn True\n\n\tdef create(self, size_bytes):\n\t\t# Check to make sure the file doesn't already exist.\n\t\tif (self.exists()):\n\t\t\traise PackageAlreadyExistsException()\n\n\t\t# Create a temporary folder for working in.\n\t\ttempfolder = tempfile.mkdtemp(\"\", self.appname_prefix + \"_build_area.\", \"/tmp/\")\n\t\tlog.showInfoW(\"Total size for Ext2 partition will be: \" + str(float(size_bytes) / (1024 * 1024)) + \" MB\")\n\n\t\t# Create a zero'd file so that we can partition it.\n\t\tlog.showInfoW(\"Creating zero'd file at \" + os.path.join(tempfolder, \"app.ext2\") + \"...\")\n\t\twith open(os.path.join(tempfolder, \"app.ext2\"), \"w\") as f:\n\t\t\tf.write(\"\".ljust(int(size_bytes), \"\\0\"))\n\n\t\t# Now format the zero'd file.\n\t\tlog.showInfoW(\"Formatting Ext2 partition at \" + os.path.join(tempfolder, \"app.ext2\") + \"...\")\n\t\tif (environment.runSilent([\"mkfs.ext2\", \"-F\", \"-t\", \"ext2\", os.path.join(tempfolder, \"app.ext2\")]) != 0):\n\t\t\tlog.showErrorW(\"An error occurred while formatting the Ext2 partition.\")\n\t\t\traise PackageCreationFailureException()\n\n\t\t# Attach the blank partition to the AppFS bootstrapping binary.\n\t\tlog.showInfoW(\"Attaching Ext2 partition to AppFS file at \" + os.path.join(tempfolder, \"app.afs\") + \"...\")\n\t\tif (subprocess.call([\"appattach\", os.path.join(tempfolder, \"app.ext2\"), os.path.join(tempfolder, \"app.afs\")]) != 0):\n\t\t\tlog.showErrorW(\"An error occurred while attaching the Ext2 partition to\")\n\t\t\tlog.showErrorO(\"the AppFS binary. Check above for error messages.\")\n\t\t\traise PackageCreationFailureException()\n\n\t\t# Move the newly created package to the new location.\n\t\tlog.showInfoW(\"Moving package to \" + self.filename + \"...\")\n\t\ttry:\n\t\t\tos.rename(os.path.join(tempfolder, \"app.afs\"), self.filename)\n\t\texcept:\n\t\t\tlog.showErrorW(\"Failed to move AppFS package to target.\")\n\t\t\traise PackageCreationFailureException()\n\t\tlog.showSuccessW(\"Package successfully created.\")\n\t\t\n\t\t# Remove our temporary files\n\t\ttry:\n\t\t\tself.forceFileRemoval(os.path.join(tempfolder, \"app.afs\"))\n\t\t\tself.forceFileRemoval(os.path.join(tempfolder, \"app.ext2\"))\n\t\t\tos.rmdir(tempfolder)\n\t\t\tlog.showSuccessW(\"Cleaned up temporary working directory.\")\n\t\texcept:\n\t\t\tlog.showErrorW(\"Unable to clean up working directory at: \" + tempfolder)\n\t\t\tlog.showErrorO(\"Please remove directory manually.\")\n\t\t\n\t\treturn True\n\t\n\tdef forceFileRemoval(self, path):\n\t\t# Attempt 10 times to remove the specified path with os.remove\n\t\tsuccessful = False\n\t\ti = 0\n\t\twhile (not successful and i < 10 and os.path.exists(path)):\n\t\t\ttry:\n\t\t\t\tos.remove(path)\n\t\t\t\tsuccessful = True\n\t\t\texcept:\n\t\t\t\tsuccessful = False\n\t\t\t\ttime.sleep(1)\n\t\t\ti += 1\n\t\treturn successful\n\t\n\tdef forceDirectoryUnmount(self, mount_point):\n\t\tret = environment.runSilent([\"fusermount\", \"-u\", mount_point])\n\t\ti = 0\n\t\twhile (ret != 0 and i < 10):\n\t\t\ttime.sleep(1)\n\t\t\tret = environment.runSilent([\"fusermount\", \"-u\", mount_point])\n\t\t\ti += 1\n\t\tif (ret != 0):\n\t\t\tlog.showErrorW(\"Unable to unmount \" + mount_point + \". Please unmount manually.\")\n\t\t\treturn False\n\t\treturn True\n\n\tdef isValidEnvironment(self):\n\t\tresult = environment.checkBinaries([\n\t\t\t\"unionfs-fuse\",\n\t\t\t\"fusermount\",\n\t\t\t\"mkfs.ext2\",\n\t\t\t\"appmount\",\n\t\t\t\"appattach\"])\n\n\t\tbase_requirements = (result[\"fusermount\"] and\n\t\t\tresult[\"mkfs.ext2\"] and\n\t\t\tresult[\"appmount\"] and\n\t\t\tresult[\"appattach\"] and\n\t\t\tresult[\"unionfs-fuse\"])\n\n\t\treturn base_requirements\n\nclass PackageAlreadyExistsException(Exception):\n\tpass\n\nclass PackageNotFoundException(Exception):\n\tpass\n\nclass PackageAlreadyMountedException(Exception):\n\tpass\n\nclass PackageNotMountedException(Exception):\n\tpass\n\nclass PackageMountFailureException(Exception):\n\tpass\n\nclass PackageUnmountFailureException(Exception):\n\tpass\n\nclass PackageCreationFailureException(Exception):\n\tpass\n\nclass NoPackagingAvailableException(Exception):\n\tpass\n\nclass PackageInvalidException(Exception):\n\tpass\n\n# TODO: Make this use the XML writer classes in Python.\nclass PackageInfoWriter():\n\tdef __init__(self, app):\n\t\tif (not isinstance(app, fs.InstalledApplication)):\n\t\t\traise PackageInvalidException()\n\t\t\n\t\tself.app = app\n\t\tself.author = None\n\t\tself.updateURL = None\n\t\tself.archs = []\n\t\n\tdef setAuthor(self, author):\n\t\tself.author = author\n\n\tdef setArchs(self, archs):\n\t\tif (isinstance(archs, list)):\n\t\t\tself.archs = archs\n\t\telse:\n\t\t\traise ValueError()\n\n\tdef getXML(self):\n\t\tupdatexml = \"\"\n\t\tif (self.updateURL != None):\n\t\t\tupdatexml = \"\" + saxutils.escape(self.updateURL) + \"\"\"\n \"\"\"\n\t\tarchxml = \"\"\n\t\tfor i in self.archs:\n\t\t\tif (isinstance(i, PackageArchitecture)):\n\t\t\t\tarchxml = \" \" + i.getXMLRepresentation() + \"\"\"\n \"\"\"\n\t\tauthorxml = \"\"\n\t\tif (self.author != None):\n\t\t\tauthorxml = \"\" + saxutils.escape(self.author) + \"\"\"\n \"\"\"\n\t\txml = \"\"\"\n\n \"\"\" + saxutils.escape(self.app.name) + \"\"\"\n \"\"\" + saxutils.escape(self.app.version) + \"\"\"\n \"\"\" + authorxml + updatexml + \"\"\"\n \"\"\" + archxml + \"\"\"\n\"\"\"\n\t\treturn xml\n\nclass PackageArchitecture():\n\tdef __init__(self, arch, deltapatch = None):\n\t\tself.arch = arch\n\t\tif (deltapatch != None):\n\t\t\tself.onrequest = True\n\t\t\tself.deltapatch = deltapatch\n\t\telse:\n\t\t\tself.onrequest = False\n\t\t\tself.deltapatch = None\n\t\n\tdef getXMLRepresentation(self):\n\t\tattribs = \"\"\n\t\tif (self.onrequest):\n\t\t\tattribs += \" OnRequest=\\\"true\\\"\"\n\t\tif (self.deltapatch != None):\n\t\t\tattribs += \" DeltaPatch=\\\"\" + saxutils.escape(self.deltapatch) + \"\\\"\"\n\t\treturn \"\" + saxutils.escape(self.arch) + \"\"\n","sub_path":"applib/packaging.py","file_name":"packaging.py","file_ext":"py","file_size_in_byte":8587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"397766006","text":"class Node:\n def __init__(self, data):\n self.data = data\n self.right = None\n self.left = None\n \nclass Tree:\n def __init__(self):\n self.front = None\n \n def insert(self, data):\n node = Node(data)\n \n if self.front == None:\n self.front = node\n \n else:\n prev = None\n crnt = self.front\n \n while crnt != None:\n prev = crnt\n if data > crnt.data:\n crnt = crnt.right\n else:\n crnt = crnt.left\n \n if data > prev.data:\n prev.right = node\n else:\n prev.left = node\n \n def print(self, node = None):\n crnt = node\n if crnt == None:\n crnt = self.front\n \n if crnt.left != None:\n self.print(crnt.left)\n print(crnt.data, end = \"\")\n print(\" \", end = \"\")\n if crnt.right != None:\n self.print(crnt.right)\n \n if node == None:\n print(\"\")\n \n \ntree = Tree()\ntree.insert(5)\ntree.insert(4)\ntree.insert(2)\ntree.insert(3)\ntree.insert(7)\ntree.insert(100)\n\ntree.print()","sub_path":"python/binary-tree.py","file_name":"binary-tree.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"521549151","text":"\"\"\"Manages cache of a dvc repo.\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport os\nfrom funcy import cached_property\n\nfrom dvc.utils.compat import builtin_str\nfrom dvc.config import Config\n\n\nclass CacheConfig(object):\n def __init__(self, config):\n self.config = config\n\n def set_dir(self, dname, level=None):\n from dvc.remote.config import RemoteConfig\n\n configobj = self.config.get_configobj(level)\n path = RemoteConfig.resolve_path(dname, configobj.filename)\n self.config.set(\n Config.SECTION_CACHE, Config.SECTION_CACHE_DIR, path, level=level\n )\n\n\ndef _make_remote_property(name):\n \"\"\"\n The config file is stored in a way that allows you to have a\n cache for each remote.\n\n This is needed when specifying external outputs\n (as they require you to have an external cache location).\n\n Imagine a config file like the following:\n\n ['remote \"dvc-storage\"']\n url = ssh://localhost/tmp\n ask_password = true\n\n [cache]\n ssh = dvc-storage\n\n This method creates a cached property, containing cache named `name`:\n\n self.config == {'ssh': 'dvc-storage'}\n self.ssh # a RemoteSSH instance\n \"\"\"\n\n def getter(self):\n from dvc.remote import Remote\n\n remote = self.config.get(name)\n if not remote:\n return None\n\n return Remote(self.repo, name=remote)\n\n getter.__name__ = builtin_str(name)\n return cached_property(getter)\n\n\nclass Cache(object):\n \"\"\"Class that manages cache locations of a dvc repo.\n\n Args:\n repo (dvc.repo.Repo): repo instance that this cache belongs to.\n \"\"\"\n\n CACHE_DIR = \"cache\"\n\n def __init__(self, repo):\n from dvc.remote import Remote\n\n self.repo = repo\n\n self.config = config = repo.config.config[Config.SECTION_CACHE]\n local = config.get(Config.SECTION_CACHE_LOCAL)\n\n if local:\n name = Config.SECTION_REMOTE_FMT.format(local)\n settings = repo.config.config[name]\n else:\n default_cache_dir = os.path.join(repo.dvc_dir, self.CACHE_DIR)\n cache_dir = config.get(Config.SECTION_CACHE_DIR, default_cache_dir)\n cache_type = config.get(Config.SECTION_CACHE_TYPE)\n protected = config.get(Config.SECTION_CACHE_PROTECTED)\n shared = config.get(Config.SECTION_CACHE_SHARED)\n\n settings = {\n Config.PRIVATE_CWD: config.get(\n Config.PRIVATE_CWD, repo.dvc_dir\n ),\n Config.SECTION_REMOTE_URL: cache_dir,\n Config.SECTION_CACHE_TYPE: cache_type,\n Config.SECTION_CACHE_PROTECTED: protected,\n Config.SECTION_CACHE_SHARED: shared,\n }\n\n self.local = Remote(repo, **settings)\n\n s3 = _make_remote_property(Config.SECTION_CACHE_S3)\n gs = _make_remote_property(Config.SECTION_CACHE_GS)\n ssh = _make_remote_property(Config.SECTION_CACHE_SSH)\n hdfs = _make_remote_property(Config.SECTION_CACHE_HDFS)\n azure = _make_remote_property(Config.SECTION_CACHE_AZURE)\n","sub_path":"dvc/cache.py","file_name":"cache.py","file_ext":"py","file_size_in_byte":3136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"613210571","text":"from django.conf import settings\r\nfrom django.conf.urls import include, url\r\nfrom django.contrib import admin\r\nfrom django.views.generic import RedirectView\r\nimport principal.views\r\n\r\nadmin.autodiscover()\r\n\r\nurlpatterns = [\r\n url(r'^favicon\\.ico$', RedirectView.as_view(url=settings.STATIC_URL + 'principal/images/favicon.ico')),\r\n url(r'^$',principal.views.inicio),\r\n url(r'^bd/$',principal.views.bd),\r\n url(r'^artistas/(?P\\d*)$',principal.views.mostrar_artistas),\r\n url(r'^artista/(?P\\d*)/$',principal.views.mostrar_artista),\r\n url(r'^artista/nuevo',principal.views.nuevo_artista),\r\n url(r'^artista/editar/(?P\\d*)/$', principal.views.editar_artista),\r\n url(r'^artista/eliminar/(?P\\d*)/$', principal.views.eliminar_artista),\r\n url(r'^album/(?P\\d*)/$',principal.views.mostrar_album),\r\n url(r'^album/nuevo/(?P\\d*)/$',principal.views.nuevo_album),\r\n url(r'^album/editar/(?P\\d*)/$',principal.views.editar_album),\r\n url(r'^album/eliminar/(?P\\d*)/$',principal.views.eliminar_album),\r\n url(r'^pista/(?P\\d*)/$',principal.views.mostrar_pista),\r\n url(r'^pista/nueva/(?P\\d*)/$',principal.views.nueva_pista),\r\n url(r'^pista/editar/(?P\\d*)/$',principal.views.editar_pista),\r\n url(r'^pista/eliminar/(?P\\d*)/$',principal.views.eliminar_pista),\r\n url(r'^puntuacion/nueva/(?P\\d*)/$',principal.views.nueva_puntuacion),\r\n url(r'^puntuaciones/$',principal.views.mostrar_puntuaciones),\r\n url(r'^recomendaciones/$',principal.views.recomendacion),\r\n url(r'^buscar/$',principal.views.buscar_post),\r\n url(r'^usuario/nuevo/$',principal.views.nuevo_usuario),\r\n url(r'^acceder/$',principal.views.acceder),\r\n url(r'^perfil/personal/$',principal.views.perfilpersonal),\r\n# url(r'^perfil/usuario/$',principal.views.perfilusuario),\r\n# url(r'^password/$',principal.views.password),\r\n url(r'^cerrar/$', principal.views.cerrar),\r\n url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\r\n url(r'^admin/', include(admin.site.urls)),\r\n]","sub_path":"music/music/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"12028318","text":"# sample detection auxillary functions\n\nimport numpy as np\nimport os, tifffile\nimport matplotlib.pyplot as plt\nfrom scipy.fftpack import dct\n\ndef readTile(pathToDataset=\"../resources/img/nice_full_wing/B=0/T=0/\", tileNum=0, channelNum=1):\n \"\"\"Reads a stack corresponding to a certain tile and channel in a dataset. Follows the ZenBlue naming conventions.\"\"\"\n path = pathToDataset+\"S=\"+str(tileNum)+\"/C=\"+str(channelNum)+\"/\"\n arr = np.array([tifffile.imread(path+i) for i in os.listdir(path) if i.endswith(\".tif\")])\n return arr\n\n\ndef getVarianceProfile(stack):\n \"\"\"Variance z profile of a stack. First dim is supposed to be depth.\"\"\"\n depth = stack.shape[0]\n var_prof= np.zeros(depth)\n\n for i in range(depth):\n var_prof[i] = np.var(stack[i,:,:])\n return np.array(var_prof)\n\ndef getIntensityProfile(stack):\n \"\"\"Variance z profile of a stack. First dim is supposed to be depth.\"\"\"\n depth = stack.shape[0]\n int_prof= np.zeros(depth)\n\n for i in range(depth):\n int_prof[i] = np.mean(stack[i,:,:])\n return np.array(int_prof)\n\n\ndef plotProfiles(profiles, figure = None, axes=None, column=1):\n \"\"\"Plot profiles (e.g. acquired with the function above)\"\"\"\n numprof = profiles.shape[0]\n length = profiles[0].shape[0]\n\n fig,ax = plt.subplots(nrows=length, ncols=numprof, figsize=(7,50))\n\n\n for j in range(numprof):\n \n for i in range(length):\n # plt.subplot(length,j+1,i+1)\n ax[i,j].set_title(str(i))\n ax[i,j].plot(profiles[j][i])\n\n plt.tight_layout(h_pad=2)\n plt.show()\n\n\ndef plotProfile(profile, figure = None, axes=None, column=1):\n \"\"\"Plot profiles (e.g. acquired with the function above)\"\"\"\n length = profile.shape[0]\n\n fig,ax = plt.subplots(nrows=length, ncols=1, figsize=(7,length*2))\n\n\n for i in range(length):\n ax[i].plot(profile[i])\n\n plt.tight_layout(h_pad=2)\n plt.show()\n\n\ndef dct2d(img, norm=None):\n return dct(dct(img, axis=0, norm=norm),axis=1, norm=norm)\n\n# DCTS \ndef DCTS(img):\n norm = np.linalg.norm(img)\n return -np.sum(np.abs(img/norm)*np.log2(np.abs(img)/norm))\n\ndef cropToLeftTop(img):\n x,y = img.shape\n return np.array(img[0:x//2, 0:y//2])\n\ndef getDCTSProfile(stack):\n depth = stack.shape[0]\n dcts_prof= np.zeros(depth)\n\n for i in range(depth):\n dcts_prof[i] = DCTS(cropToLeftTop(dct2d(stack[i,:,:])))\n return np.array(dcts_prof)\n\ndef getDCTSProfileNoZero(stack):\n depth = stack.shape[0]\n dcts_prof= np.zeros(depth)\n\n for i in range(depth):\n spectrum = dct2d(stack[i,:,:])\n spectrum[0,0] = 0.00001\n dcts_prof[i] = DCTS(cropToLeftTop(spectrum))\n # dcts_prof[i] = \n return np.array(dcts_prof)\n\ndef normalizeToOne(img):\n return img/img.sum()\n\ndef getNetworkMeasure(slice, model):\n inp_tens = slice[np.newaxis,...,np.newaxis]\n return np.mean(model.predict(normalizeWithLimits(inp_tens)))\n\ndef getNetworkProfile(stack, model):\n depth = stack.shape[0]\n net_prof = np.zeros(depth)\n for i in range(depth):\n\n \n net_prof[i] = getNetworkMeasure(stack[i,:,:], model)\n return net_prof\n\n\ndef getDCTSProfileNormalized(stack):\n depth = stack.shape[0]\n dcts_prof= np.zeros(depth)\n\n for i in range(depth):\n dcts_prof[i] = DCTS(normalizeToOne(cropToLeftTop(np.abs(dct2d(stack[i,:,:])))))\n return np.array(dcts_prof)\n\ndef getDCTSProfileNormalizedExperimental(stack):\n depth = stack.shape[0]\n dcts_prof= np.zeros(depth)\n\n for i in range(depth):\n interm = cropToLeftTop(np.abs(dct2d(stack[i,:,:])))\n interm[0:20,0:20] = np.zeros((20,20)) + 0.00000001\n dcts_prof[i] = DCTS(normalizeToOne(interm))\n return np.array(dcts_prof)\n\ndef normalizeWithLimits(dataset, upLim=99.9, loLim=0.01):\n upLim = np.percentile(dataset, 99.9)\n loLim = np.percentile(dataset, 0.01)\n res = np.maximum(dataset - loLim, 0)\n res = np.minimum(res, upLim)\n res = res/(upLim-loLim+0.0000001)\n return res\n ","sub_path":"python/detection/qualityMeasure.py","file_name":"qualityMeasure.py","file_ext":"py","file_size_in_byte":3857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"194864623","text":"from rest_framework import serializers\nfrom .models import *\n\n\nclass WordSerializer(serializers.ModelSerializer):\n class Meta:\n model = Word\n fields = ('name', 'in_website',)\n\n\nclass WebsiteSerializer(serializers.ModelSerializer):\n words = WordSerializer(many=True)\n status = serializers.SerializerMethodField()\n\n class Meta:\n model = Website\n fields = ('url', 'words', 'status')\n\n def get_status(self, obj):\n return obj.get_status_display()\n\n\nclass TaskSerializer(serializers.ModelSerializer):\n status = status = serializers.SerializerMethodField()\n websites = WebsiteSerializer(many=True)\n\n class Meta:\n model = Task\n fields = ('status', 'task_id', 'websites', 'pk')\n depth = 3\n\n def get_status(self, obj):\n return obj.get_status_display()\n","sub_path":"searcher/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"407041729","text":"'''\nThis module will test the columns.YearColumn class\n'''\n\nimport unittest\nfrom clubadmin.database.columns import YearColumn\nfrom clubadmin.database.columns import DatabaseValueError\n\nclass TestYearColumn(unittest.TestCase):\n def test_check(self):\n dc = YearColumn()\n self.assertFalse(dc._check(1890))\n self.assertFalse(dc._check(3010))\n self.assertTrue(dc._check(1970))\n\n def test_table(self):\n class TestTable:\n yearfld = YearColumn()\n tt = TestTable()\n\n with self.assertRaises(DatabaseValueError):\n tt.yearfld = b'1980'\n\n with self.assertRaises(DatabaseValueError):\n tt.yearfld = 198\n\n # Using the underlying datetime.strptime method will raise a ValueError if there is any\n # following \"garbage\" in the value being converted.\n with self.assertRaises(ValueError):\n tt.yearfld = '1980-2-5@13:30'\n\n with self.assertRaises(ValueError):\n tt.yearfld = '1980-'\n\n tt.yearfld = '1980'\n self.assertEqual(tt.yearfld, 1980)\n\n tt.yearfld = 1980\n self.assertEqual(tt.yearfld, 1980)\n","sub_path":"test/database/columns/test_year.py","file_name":"test_year.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"490713890","text":"\"\"\" The core module \"\"\"\nimport math\nimport multiprocessing\nimport random\n\nimport PIL.Image\nimport PIL.ImageDraw\n\n# Chinese, English and other end chars\n_DEFAULT_END_CHARS = \",。》、?;:’”】}、!%)\" + \",.>?;:]}!%)\" + \"′″℃℉\"\n\n# While changing following constants, it is necessary to consider to rewrite the relevant codes.\n_INTERNAL_MODE = 'L' # The mode for internal computation\n_WHITE = 255\n_BLACK = 0\n_AMP = 2 # Amplification for 4X SSAA.\n\n\ndef handwrite(text, template: dict, anti_aliasing: bool = True, worker: int = 0) -> list:\n \"\"\"\n Handwrite the text with the parameters in the template\n :param text: A char iterable\n :param template: A dict containing following parameters:\n background: A Pillow's Image object\n box: A bounding box as a 4-tuple defining the left, upper, right, and lower pixel coordinate\n The module uses a Cartesian pixel coordinate system, with (0,0) in the upper left corner. The function do\n not guarantee the drawn texts will completely in the box.\n font: A Pillow's font object\n NOTE: This function do not use the size attribute of the font object.\n font_size: A int as the average font size in pixel\n NOTE: (box[3] - box[1]) must be greater than font_size.\n NOTE: (box[2] - box[0]) must be greater than font_size.\n color: A str with specific format\n The format is given as 'rgb(red, green, blue)' where the color values are integers in the range 0\n (inclusive) to 255 (inclusive)\n default: 'rgb(0, 0, 0)'\n word_spacing: A int as the average gap between two adjacent chars in pixel\n default: 0\n line_spacing: A int as the average gap between two adjacent lines in pixel\n default: font_size // 5\n font_size_sigma: A float as the sigma of the gauss distribution of the font size\n default: font_size / 256\n line_spacing_sigma: A float as the sigma of the gauss distribution of the line spacing\n default: font_size / 256\n word_spacing_sigma: A float as the sigma of the gauss distribution of the word spacing\n default: font_size / 256\n is_half_char: A function judging whether or not a char only take up half of its original width\n The function must take a char parameter and return a boolean value.\n The feature is designed for some of Chinese punctuations that only take up the left half of their space\n (e.g. ',', '。', '!', '、').\n default: (lambda c: False)\n is_end_char: A function judging whether or not a char can NOT be in the beginning of the lines (e.g. ',', '。',\n '》', ')', ']')\n The function must take a char parameter and return a boolean value.\n default: (lambda c: c in _DEFAULT_END_CHARS)\n alpha: A tuple of two floats as the degree of the distortion in the horizontal and vertical direction in order\n Both values must be between 0.0 (inclusive) and 1.0 (inclusive).\n default: (0.1, 0.1)\n :param anti_aliasing: whether or not turn on the anti-aliasing\n It will do the anti-aliasing with using 4X SSAA. Generally, to turn off this anti-aliasing option would\n significantly reduce the overall computation.\n default: True\n :param worker: A int as the number of worker\n if worker is less than or equal to 0, the actual amount of worker would be the number of CPU in the computer\n adding worker.\n default: 0 (use all the available CPUs in the computer)\n :return: A list of drawn images with the same size and mode as background image\n \"\"\"\n template = dict(template)\n font_size = template['font_size']\n\n if 'color' not in template:\n template['color'] = 'rgb(0, 0, 0)'\n if 'word_spacing' not in template:\n template['word_spacing'] = 0\n if 'line_spacing' not in template:\n template['line_spacing'] = font_size // 5\n\n if 'font_size_sigma' not in template:\n template['font_size_sigma'] = font_size / 256\n if 'line_spacing_sigma' not in template:\n template['line_spacing_sigma'] = font_size / 256\n if 'word_spacing_sigma' not in template:\n template['word_spacing_sigma'] = font_size / 256\n\n if 'is_half_char' not in template:\n template['is_half_char'] = lambda c: False\n if 'is_end_char' not in template:\n template['is_end_char'] = lambda c: c in _DEFAULT_END_CHARS\n\n if 'alpha' not in template:\n template['alpha'] = (0.1, 0.1)\n\n worker = worker if worker > 0 else multiprocessing.cpu_count() + worker\n return _handwrite(text, template, anti_aliasing, worker)\n\n\ndef _handwrite(text, template: dict, anti_aliasing: bool, worker: int) -> list:\n images = _draw_text(\n text=text,\n size=tuple(_AMP * i for i in template['background'].size) if anti_aliasing else template['background'].size,\n box=tuple(_AMP * i for i in template['box']) if anti_aliasing else template['box'],\n font=template['font'],\n font_size=template['font_size'] * _AMP if anti_aliasing else template['font_size'],\n font_size_sigma=template['font_size_sigma'] * _AMP if anti_aliasing else template['font_size_sigma'],\n line_spacing=template['line_spacing'] * _AMP if anti_aliasing else template['line_spacing'],\n line_spacing_sigma=template['line_spacing_sigma'] * _AMP if anti_aliasing else template['line_spacing_sigma'],\n word_spacing=template['word_spacing'] * _AMP if anti_aliasing else template['word_spacing'],\n word_spacing_sigma=template['word_spacing_sigma'] * _AMP if anti_aliasing else template['word_spacing_sigma'],\n is_end_char=template['is_end_char'],\n is_half_char=template['is_half_char']\n )\n renderer = _Renderer(**template, anti_aliasing=anti_aliasing)\n with multiprocessing.Pool(worker) as pool:\n images = pool.map(renderer, images)\n return images\n\n\ndef _draw_text(\n text,\n size: tuple,\n box: tuple,\n font,\n font_size: int,\n font_size_sigma: float,\n line_spacing: int,\n line_spacing_sigma: float,\n word_spacing: int,\n word_spacing_sigma: float,\n is_end_char,\n is_half_char\n) -> list:\n \"\"\"\n Draw the text randomly in black images with white color\n :return: a list of drawn images with L mode and given size\n NOTE: (box[3] - box[1]) must be greater than font_size.\n NOTE: (box[2] - box[0]) must be greater than font_size.\n \"\"\"\n if not box[3] - box[1] > font_size:\n raise ValueError(\"(box[3] - box[1]) must be greater than font_size.\")\n if not box[2] - box[0] > font_size:\n raise ValueError(\"(box[2] - box[0]) must be greater than font_size.\")\n\n left, upper, right, lower = box\n chars = iter(text)\n images = []\n try:\n char = next(chars)\n while True:\n image = PIL.Image.new(mode=_INTERNAL_MODE, size=size, color=_BLACK)\n draw = PIL.ImageDraw.Draw(image)\n y = upper\n try:\n while y < lower - font_size:\n x = left\n while True:\n if char == '\\n':\n char = next(chars)\n break\n if x >= right - font_size and not is_end_char(char):\n break\n actual_font_size = max(int(random.gauss(font_size, font_size_sigma)), 0)\n xy = (x, int(random.gauss(y, line_spacing_sigma)))\n font = font.font_variant(size=actual_font_size)\n offset = _draw_char(draw, char, xy, font)\n x_step = word_spacing + offset * (0.5 if is_half_char(char) else 1)\n x += int(random.gauss(x_step, word_spacing_sigma))\n char = next(chars)\n y += line_spacing + font_size\n images.append(image)\n except StopIteration:\n images.append(image)\n raise StopIteration()\n except StopIteration:\n return images\n\n\ndef _draw_char(draw, char: str, xy: tuple, font) -> int:\n \"\"\" Draw a single char with the parameters and white color, and return the offset \"\"\"\n draw.text(xy, char, fill=_WHITE, font=font)\n return font.getsize(char)[0]\n\n\nclass _Renderer:\n \"\"\" A function-like object rendering the foreground that was drawn text and returning rendered image \"\"\"\n\n def __init__(\n self,\n background,\n color: str,\n font_size: int,\n alpha: tuple,\n anti_aliasing: bool,\n **kwargs\n ):\n self._anti_aliasing = anti_aliasing\n self._background = background\n self._color = color\n self._font_size = font_size\n self._alpha = alpha\n self._random = random.Random()\n\n def __call__(self, image):\n self._random.seed()\n self._perturb(image)\n if self._anti_aliasing:\n image = self._downscale(image)\n return self._merge(image)\n\n def _perturb(self, image) -> None:\n \"\"\"\n 'perturb' the image and generally make the glyphs from same chars, if any, seem different\n NOTE: self._alpha[0] must be between 0 (inclusive) and 1 (inclusive).\n NOTE: self._alpha[1] must be between 0 (inclusive) and 1 (inclusive).\n \"\"\"\n if not 0 <= self._alpha[0] <= 1:\n raise ValueError(\"alpha[0] must be between 0 (inclusive) and 1 (inclusive).\")\n if not 0 <= self._alpha[1] <= 1:\n raise ValueError(\"alpha[1] must be between 0 (inclusive) and 1 (inclusive).\")\n\n wavelength = 2 * self._font_size\n alpha_x, alpha_y = self._alpha\n matrix = image.load()\n\n for i in range((image.width + wavelength) // wavelength + 1):\n x0 = self._random.randrange(-wavelength, image.width)\n for j in range(max(0, -x0), min(wavelength, image.width - x0)):\n offset = int(alpha_x * wavelength / (2 * math.pi) * (1 - math.cos(2 * math.pi * j / wavelength)))\n self._slide_x(matrix, x0 + j, offset, image.height)\n\n for i in range((image.height + wavelength) // wavelength + 1):\n y0 = self._random.randrange(-wavelength, image.height)\n for j in range(max(0, -y0), min(wavelength, image.height - y0)):\n offset = int(alpha_y * wavelength / (2 * math.pi) * (1 - math.cos(2 * math.pi * j / wavelength)))\n self._slide_y(matrix, y0 + j, offset, image.width)\n\n @staticmethod\n def _slide_x(matrix, x: int, offset: int, height: int) -> None:\n \"\"\" Slide one given column \"\"\"\n for i in range(height - offset):\n matrix[x, i] = matrix[x, i + offset]\n for i in range(height - offset, height):\n matrix[x, i] = _BLACK\n\n @staticmethod\n def _slide_y(matrix, y: int, offset: int, width: int) -> None:\n \"\"\" Slide one given row \"\"\"\n for i in range(width - offset):\n matrix[i, y] = matrix[i + offset, y]\n for i in range(width - offset, width):\n matrix[i, y] = _BLACK\n\n @staticmethod\n def _downscale(image):\n \"\"\" Downscale the image for 4X SSAA \"\"\"\n return image.resize(size=(image.size[0] // _AMP, image.size[1] // _AMP), resample=PIL.Image.BOX)\n\n def _merge(self, image):\n \"\"\" Merge the foreground and the background image \"\"\"\n res = self._background.copy()\n draw = PIL.ImageDraw.Draw(res)\n draw.bitmap(xy=(0, 0), bitmap=image, fill=self._color)\n return res\n","sub_path":"pylf/_handwriting.py","file_name":"_handwriting.py","file_ext":"py","file_size_in_byte":11725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"405751894","text":"import xlrd\nimport sqlite3\nfrom xlwt import Workbook\n\ndata = xlrd.open_workbook('前台房间计件提成表新.xls')\nsheet_name='12月'\n\ntable = data.sheet_by_name(sheet_name)\n\nnrows=table.nrows\n\ndb=\"account.sqlite3\"\ncon=sqlite3.connect(db)\ncur=con.cursor()\n\n# for i in range(2,nrows-1):\n# date =int(table.cell_value(i,0))#日期\n# day_commission =table.cell_value(i,11)#总提成\n# half_commission=day_commission/2#一半提成\n# print(date,day_commission,table.cell_value(i,12),half_commission,'白班')\n# sql=\"insert into bill(date,day_commission,name,half_commission,type) VALUES (?,?,?,?,?)\"\n# cur.execute(sql,(date,day_commission,table.cell_value(i,12).strip(),half_commission,'白班'))\n# print(date,day_commission,table.cell_value(i,13),half_commission,'夜班')\n# cur.execute(sql,(date,day_commission,table.cell_value(i,13).strip(),half_commission,'夜班'))\n\ncon.commit()\n\nwork_book =Workbook()\nwork_sheet=work_book.add_sheet(\"值班表\",cell_overwrite_ok=True)\n\nsql2=\"select * from bill\"\ncur.execute(sql2)\ndata_set=cur.fetchall()\nfor i in range(0,len(data_set)):\n for j in range(0,len(data_set[i])):\n work_sheet.write(i,j,data_set[i][j])\n\n\nwork_sheet2=work_book.add_sheet(\"结果\",cell_overwrite_ok=True)\nsql3=\"select name,sum(half_commission) from bill GROUP BY name\"\ncur.execute(sql3)\nsum_data=cur.fetchall()\n\nfor i in range(0,len(sum_data)):\n for j in range(0,len(sum_data[i])):\n work_sheet2.write(i,j,sum_data[i][j])\n\n\nwork_book.save('result.xls')\n\n","sub_path":"account.py","file_name":"account.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"164132020","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Use text editor to edit the script and type in valid Instagram username/password\nfrom InstagramAPI import InstagramAPI\nimport time\nimport datetime\n\nPK_FIELD = 'pk'\nNAME_FIELD = 'name'\nUSERNAME_FIELD = 'username'\nFOLLOWERS_BLOCK_SIZE = 500\nFOLLOW_DELAY = 3\nWAITING_DELAY = 180\n\napi = InstagramAPI(\"isamaniere\", \"32576786\")\n\n\ndef get_total_followers(_api, user_id, max_followers):\n _followers = []\n next_max_id = True\n while next_max_id and len(_followers) < max_followers:\n # first iteration hack\n if next_max_id is True:\n next_max_id = ''\n\n _ = _api.getUserFollowers(user_id, maxid=next_max_id)\n _followers.extend(_api.LastJson.get('users', []))\n next_max_id = _api.LastJson.get('next_max_id', '')\n\n return _followers\n\n\ndef get_logged_user_info(_api):\n _api.getSelfUsernameInfo()\n return api.LastJson['user']\n\n\nif api.login():\n\n stores = [{'name': 'Arezzo', 'id': 22724209},\n {'name': 'Santa Lolla', 'id': 8586019},\n {'name': 'Schutz Fortaleza', 'id': 261241949}]\n\n # get my users\n loggedUserInfo = get_logged_user_info(api)\n api.getUserFollowings(loggedUserInfo[PK_FIELD], maxid='0')\n myFollowings = api.LastJson\n\n while True:\n\n followed = 0\n\n try:\n\n for store in stores:\n\n print('-----------------------------------------')\n print('Stealing followers of: ' + str(store[NAME_FIELD]))\n print('-----------------------------------------')\n\n followers = get_total_followers(api, store['id'], FOLLOWERS_BLOCK_SIZE)\n\n for user in followers:\n print('Following user ' + str(user[USERNAME_FIELD]))\n followSuccess = api.follow(user[PK_FIELD])\n print('Follow result: ' + str(followSuccess))\n\n if followSuccess:\n time.sleep(FOLLOW_DELAY)\n followed += 1\n else:\n print('Following limit reached at ' + str(datetime.datetime.now()))\n print('Waiting ' + str(WAITING_DELAY) + ' seconds')\n print(str(followed) + ' users followed.')\n\n time.sleep(WAITING_DELAY)\n\n except Exception as e:\n print('Unexpected exception: ' + str(e))\n\nelse:\n print(\"Can't login!\")\n","sub_path":"InstagramAPI/follow.py","file_name":"follow.py","file_ext":"py","file_size_in_byte":2451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"192336871","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Sep 18 08:55:49 2018\r\n\r\n@author: amundov\r\n\"\"\"\r\n\r\nimport csv\r\nimport time\r\nfrom random import shuffle,randint\r\n\r\nwith open(\"european_cities.csv\",\"r\") as file:\r\n data = list(csv.reader(file,delimiter=';'))\r\n\r\ncities = []\r\n\r\nfor i in range(1,len(data)):\r\n dummy=[]\r\n for j in range(0,len(data)-1):\r\n dummy.append(data[i][j])\r\n cities.append(dummy)\r\n\r\n\r\ndef calcDist(tour):\r\n dist = 0\r\n for i in range(0,len(tour)-1):\r\n dist +=float(cities[tour[i]][tour[i+1]])\r\n return dist\r\n\r\ndef createPopulation(size):\r\n pop = []\r\n for i in range(0,size):\r\n tour=list(range(0,len(data)-1))\r\n shuffle(tour)\r\n pop.append(tour) \r\n return pop\r\n\r\ndef calcFitness(pop):\r\n dist=[]\r\n total=0\r\n rel=[]\r\n for tour in pop:\r\n dist.append(calcDist(tour))\r\n total+=calcDist(tour)\r\n for i in range(0,len(dist)):\r\n fit = dist[i]/total\r\n rel.append(fit)\r\n \r\n total=0\r\n p=[]\r\n for i in range(0,len(rel)):\r\n rel[i]=(1/rel[i])\r\n total+=rel[i]\r\n for i in range(0,len(rel)):\r\n p.append(rel[i]/total)\r\n return p\r\n\r\ndef calcFitnessScaled(pop):\r\n dist=[]\r\n total=0\r\n rel=[]\r\n for tour in pop:\r\n dist.append(calcDist(tour))\r\n total+=calcDist(tour)\r\n #print(dist)\r\n for i in range(0,len(dist)):\r\n fit = dist[i]/total\r\n rel.append(fit)\r\n \r\n total=0\r\n p=[]\r\n for i in range(0,len(rel)):\r\n rel[i]=(1/rel[i])\r\n total+=rel[i]\r\n for i in range(0,len(rel)):\r\n p.append(rel[i]/total)\r\n #Scaling\r\n total = 0\r\n \r\n minpos = p.index(min(p))\r\n for i in range(0,len(p)):\r\n p[i]=p[i]-p[minpos]\r\n total+=p[i]\r\n for i in range(0,len(p)):\r\n p[i]=p[i]/total\r\n \r\n return p\r\n\r\ndef newRel(subpop):\r\n p = []\r\n total = 0\r\n for i in range(0,len(subpop)):\r\n total+=subpop[i]\r\n for i in range(0,len(subpop)):\r\n p.append(subpop[i]/total)\r\n return p\r\n \r\n\r\ndef matingGround(pop,percent_mating):\r\n div = 100/percent_mating\r\n reproduction_size = int((len(pop))/div)\r\n if reproduction_size%2 == 1:\r\n reproduction_size+=1\r\n rand = [] \r\n for i in range(0,reproduction_size):\r\n rand.append(random.random()) \r\n p = calcFitness(pop) \r\n #print(p)\r\n lucky_ones = []\r\n mutating_ones = []\r\n\r\n for num in rand:\r\n dummy = 0\r\n for i in range(0,len(p)):\r\n dummy+=p[i]\r\n if dummy>num:\r\n lucky_ones.append(i)\r\n \r\n break \r\n \r\n #print(lucky_ones)\r\n return lucky_ones\r\n\r\n#40% best reproduces, rest gets mutated. hard. \r\ndef livetsSkole(pop,percent_mating):\r\n div = 100/percent_mating\r\n reproduction_size = int((len(pop))/div)\r\n if reproduction_size%2 == 1:\r\n reproduction_size+=1\r\n rand = [] \r\n for i in range(0,reproduction_size):\r\n rand.append(random.random()) \r\n p = calcFitness(pop)\r\n \r\n master = [(i,p[i]) for i in range(len(p))]\r\n \r\n #print(p)\r\n lucky_ones = []\r\n mutating_ones = []\r\n\r\n for num in rand:\r\n dummy = 0\r\n for i in range(0,len(p)):\r\n dummy+=p[i]\r\n if dummy>num:\r\n lucky_ones.append(i)\r\n \r\n break \r\n \r\n #print(lucky_ones)\r\n return lucky_ones\r\n\r\n\r\ndef makeChildren(lucky_ones,pop):\r\n children = []\r\n for i in range(0,len(lucky_ones),2):\r\n a,b = twoPMX(pop[lucky_ones[i]],pop[lucky_ones[i+1]])\r\n children.append(a)\r\n children.append(b)\r\n \r\n return children\r\n\r\ndef selection(pop,children):\r\n newPop= pop+children\r\n \r\n rank = calcFitness(newPop)\r\n \r\n for i in range(0,len(children)):\r\n minpos = rank.index(min(rank))\r\n del(rank[minpos],newPop[minpos])\r\n \r\n return newPop\r\n\r\ndef mutationTiny(subpop):\r\n \r\n for tour in subpop:\r\n a = tour.pop(random.randint(0,len(tour)-1))\r\n tour.insert(random.randint(0,len(tour)-1),a)\r\n print(a)\r\n \r\n \r\n return subpop\r\n\r\ndef mutationLarge(subpop):\r\n for tour in subpop:\r\n shuffle(tour)\r\n return subpop\r\n\r\n \r\n\r\ndef main(pop_size,turnover,t):\r\n \r\n pop = createPopulation(pop_size)\r\n time_start=time.time()\r\n #while time.time()-time_start < t:\r\n for i in range(0,50):\r\n avg_dist = 0\r\n selected = matingGround(pop,turnover)\r\n children = makeChildren(selected,pop)\r\n pop =selection(pop,children)\r\n for tour in pop:\r\n avg_dist+=calcDist(tour)\r\n #print(pop[0])\r\n dist = []\r\n for tour in pop:\r\n dist.append(calcDist(tour))\r\n \r\n \r\n return dist\r\n\r\ndef average(pop,num):\r\n total = 0\r\n \r\n for i in range(0,num):\r\n dist = main(pop,20,0)\r\n for d in dist:\r\n total+=d\r\n \r\n return( total/(pop*num))\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":"GA.py","file_name":"GA.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"55910718","text":"import logging\n\nlogging_object = logging.getLogger('Global dungeon game logger')\n\nlogging.basicConfig(\n filename='information.log',\n level = logging.DEBUG,\n format = '%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',\n datefmt=\"%Y-%m-%d %H:%M:%S\")\n\nstream_logger = logging.StreamHandler()\nstream_logger.setLevel(logging.INFO)\nstream_formatter = logging.Formatter('%(message)s')\nstream_logger.setFormatter(stream_formatter)\n\nlogging_object.addHandler(stream_logger)\n","sub_path":"Masha_Mumrenko/10/dungeon_game_pkg_bonbony/dungeon_game_pkg_bonbony/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"649982448","text":"import matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator, FormatStrFormatter\n\nstart_index = 1\nend_index = -1\nxmajorLocator = MultipleLocator(5)\nxmajorFormatter = FormatStrFormatter('%1.1f')\nxminorLocator = MultipleLocator(1)\n\nymajorLocator = MultipleLocator(1)\nymajorFormatter = FormatStrFormatter('%1.1f')\nyminorLocator = MultipleLocator(0.1)\n\n\ndef img_plot(title, dataT, data1, data2=None, legend2=\"\", label2=\"\", mode='show', path=''):\n plt.close('all')\n T = dataT\n f1 = data1\n\n fig = plt.figure(dpi=100, figsize=(12.8, 8))\n\n ax = fig.add_subplot(111)\n ax.plot(T, f1, 'b', label='Voltage')\n ax.grid()\n ax.set_title(title)\n ax.set_xlabel(\"Time (s)\")\n ax.set_ylabel(\"Voltage (V)\")\n box = ax.get_position()\n ax.set_position([box.x0, box.y0 + 0.02, box.width, box.height])\n\n if data2 is not None:\n f2 = data2\n ax2 = ax.twinx()\n ax2.set_position([box.x0, box.y0 + 0.02, box.width, box.height])\n ax2.plot(T, f2, 'r', label=legend2)\n ax2.set_ylabel(label2)\n ax.legend(loc='center', bbox_to_anchor=(0.065, 1.05), ncol=3)\n ax2.legend(loc='center', bbox_to_anchor=(0.935, 1.05), ncol=3)\n\n if mode == 'show':\n plt.show()\n elif mode == 'save':\n plt.savefig(path, dpi=100)\n plt.close()\n\n\nif __name__ == '__main__':\n img_plot(\"gg\",\n range(0, 7),\n [10, 5, 23, 34, 33, 76, 23],\n [9, 4, 4, 23, 235, 5, 43],\n \"Current\", path='./gg.png', mode='save')\n","sub_path":"Visualisation.py","file_name":"Visualisation.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"341386981","text":"class Solution(object):\n def coinChange(self, coins, amount):\n \"\"\"\n :type coins: List[int]\n :type amount: int\n :rtype: int\n \"\"\"\n fff = 0xFFFFFFFF\n dyna = [0] + [fff]*amount\n for i in xrange(amount+1):\n for c in coins:\n if i + c <= amount:\n dyna[i+c] = min(dyna[i]+1, dyna[i+c])\n \n return dyna[amount] if dyna[amount] != fff else -1\n ","sub_path":"Coin Change.py","file_name":"Coin Change.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"3980281","text":"try:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\nfrom mock import patch\nimport numpy as np\nfrom numpy.testing import assert_allclose\nfrom nose.tools import raises\nfrom menpo.transform import PiecewiseAffine, ThinPlateSplines\nfrom menpo.feature import sparse_hog, igo, lbp, no_op\n\nimport menpo.io as mio\nfrom menpofit.atm import ATMBuilder, PatchBasedATMBuilder\n\n\n\n# load images\nfilenames = ['breakingbad.jpg', 'takeo.ppm', 'lenna.png', 'einstein.jpg']\ntraining = []\ntemplates = []\nfor i in range(4):\n im = mio.import_builtin_asset(filenames[i])\n if im.n_channels == 3:\n im = im.as_greyscale(mode='luminosity')\n training.append(im.landmarks[None].lms)\n templates.append(im)\n\n# build atms\natm1 = ATMBuilder(features=[igo, sparse_hog, no_op],\n transform=PiecewiseAffine,\n normalization_diagonal=150,\n n_levels=3,\n downscale=2,\n scaled_shape_models=False,\n max_shape_components=[1, 2, 3],\n boundary=3).build(training, templates[0])\n\natm2 = ATMBuilder(features=[no_op, no_op],\n transform=ThinPlateSplines,\n trilist=None,\n normalization_diagonal=None,\n n_levels=2,\n downscale=1.2,\n scaled_shape_models=True,\n max_shape_components=None,\n boundary=0).build(training, templates[1])\n\natm3 = ATMBuilder(features=igo,\n transform=ThinPlateSplines,\n trilist=None,\n normalization_diagonal=None,\n n_levels=1,\n downscale=3,\n scaled_shape_models=True,\n max_shape_components=[2],\n boundary=2).build(training, templates[2])\n\natm4 = PatchBasedATMBuilder(features=lbp,\n patch_shape=(10, 13),\n normalization_diagonal=200,\n n_levels=2,\n downscale=1.2,\n scaled_shape_models=True,\n max_shape_components=1,\n boundary=2).build(training, templates[3])\n\n\n@raises(ValueError)\ndef test_features_exception():\n ATMBuilder(features=[igo, sparse_hog]).build(training, templates[0])\n\n\n@raises(ValueError)\ndef test_n_levels_exception():\n ATMBuilder(n_levels=0).build(training, templates[1])\n\n\n@raises(ValueError)\ndef test_downscale_exception():\n atm = ATMBuilder(downscale=1).build(training, templates[2])\n assert (atm.downscale == 1)\n ATMBuilder(downscale=0).build(training, templates[2])\n\n\n@raises(ValueError)\ndef test_normalization_diagonal_exception():\n atm = ATMBuilder(normalization_diagonal=100).build(training, templates[3])\n assert (atm.warped_templates[0].n_true_pixels() == 1246)\n ATMBuilder(normalization_diagonal=10).build(training, templates[3])\n\n\n@raises(ValueError)\ndef test_max_shape_components_exception():\n ATMBuilder(max_shape_components=[1, 0.2, 'a']).build(training, templates[0])\n\n\n@raises(ValueError)\ndef test_max_shape_components_exception_2():\n ATMBuilder(max_shape_components=[1, 2]).build(training, templates[0])\n\n\n@raises(ValueError)\ndef test_boundary_exception():\n ATMBuilder(boundary=-1).build(training, templates[1])\n\n\n@patch('sys.stdout', new_callable=StringIO)\ndef test_verbose_mock(mock_stdout):\n ATMBuilder().build(training, templates[2], verbose=True)\n\n\n@patch('sys.stdout', new_callable=StringIO)\ndef test_str_mock(mock_stdout):\n print(atm1)\n print(atm2)\n print(atm3)\n print(atm4)\n\n\ndef test_atm_1():\n assert(atm1.n_training_shapes == 4)\n assert(atm1.n_levels == 3)\n assert(atm1.downscale == 2)\n assert_allclose(np.around(atm1.reference_shape.range()), (109., 103.))\n assert(not atm1.scaled_shape_models)\n assert(not atm1.pyramid_on_features)\n assert_allclose([atm1.shape_models[j].n_components\n for j in range(atm1.n_levels)], (1, 2, 3))\n assert_allclose([atm1.warped_templates[j].n_channels\n for j in range(atm1.n_levels)], (2, 36, 1))\n assert_allclose([atm1.warped_templates[j].shape[1]\n for j in range(atm1.n_levels)], (164, 164, 164))\n\n\ndef test_atm_2():\n assert (atm2.n_training_shapes == 4)\n assert (atm2.n_levels == 2)\n assert (atm2.downscale == 1.2)\n assert_allclose(np.around(atm2.reference_shape.range()), (169., 161.))\n assert atm2.scaled_shape_models\n assert (not atm2.pyramid_on_features)\n assert (np.all([atm2.shape_models[j].n_components == 3\n for j in range(atm2.n_levels)]))\n assert (np.all([atm2.warped_templates[j].n_channels == 1\n for j in range(atm2.n_levels)]))\n assert_allclose([atm2.warped_templates[j].shape[1]\n for j in range(atm2.n_levels)], (132, 158))\n\n\ndef test_atm_3():\n assert (atm3.n_training_shapes == 4)\n assert (atm3.n_levels == 1)\n assert (atm3.downscale == 3)\n assert_allclose(np.around(atm3.reference_shape.range()), (169., 161.))\n assert atm3.scaled_shape_models\n assert atm3.pyramid_on_features\n assert (np.all([atm3.shape_models[j].n_components == 2\n for j in range(atm3.n_levels)]))\n assert (np.all([atm3.warped_templates[j].n_channels == 2\n for j in range(atm3.n_levels)]))\n assert_allclose([atm3.warped_templates[j].shape[1]\n for j in range(atm3.n_levels)], 162)\n\n\ndef test_atm_4():\n assert (atm4.n_training_shapes == 4)\n assert (atm4.n_levels == 2)\n assert (atm4.downscale == 1.2)\n assert_allclose(np.around(atm4.reference_shape.range()), (145., 138.))\n assert atm4.scaled_shape_models\n assert atm4.pyramid_on_features\n assert (np.all([atm4.shape_models[j].n_components == 1\n for j in range(atm4.n_levels)]))\n assert (np.all([atm4.warped_templates[j].n_channels == 4\n for j in range(atm4.n_levels)]))\n assert_allclose([atm4.warped_templates[j].shape[1]\n for j in range(atm4.n_levels)], (162, 188))\n","sub_path":"menpofit/test/atm_builder_test.py","file_name":"atm_builder_test.py","file_ext":"py","file_size_in_byte":6173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"274620488","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.views.generic.simple import direct_to_template\nadmin.autodiscover()\nfrom trend import settings\nfrom trend.izdvojeno.models import Sub_Kategorije\nfrom sitemaps import TShirtsSitemap, PantsSitemap, DressesSitemap, JacketsSitemap, HighheelsSitemap, BootsSitemap, SneakersSitemap, SandalsSitemap, BraceletsSitemap, RingsSitemap, NecklasesSitemap, EarringsSitemap, BootsSitemap, MakeupSitemap, HaircareSitemap, PerfumesSitemap, SkincareSitemap, HandbagsSitemap, PhonesSitemap, SunglassesSitemap, AccessoriesSitemap, CasualSitemap, DressSitemap, FashionSitemap, LuxurySitemap, KategorijeSitemap, StaticViewSitemap\n\n\n\nsitemaps_ostalo = {'ostalo': StaticViewSitemap\n\n}\n\nsitemaps_kategorije = {'kategorije': KategorijeSitemap\n \n \n \n \n}\n\nsitemaps_tshirts = {'tshirts': TShirtsSitemap\n \n \n \n \n}\n\nsitemaps_pants = {'pants': PantsSitemap\n \n \n \n \n}\n\nsitemaps_dresses = {'dresses': DressesSitemap\n \n \n \n \n}\n\n\nsitemaps_jackets = {'jackets': JacketsSitemap\n \n \n \n \n}\n\n\nsitemaps_highheels = {'highheels': HighheelsSitemap\n \n \n \n \n}\n\nsitemaps_boots = {'boots': BootsSitemap\n \n \n \n \n}\n\nsitemaps_sneakers = {'sneakers': SneakersSitemap\n \n \n \n \n}\n\n\n\n\nsitemaps_sandals = {'sandals': SandalsSitemap\n \n \n \n \n}\n\n\n\nsitemaps_bracelets = {'bracelets': BraceletsSitemap\n \n \n \n \n}\n\n\n\nsitemaps_rings = {'rings': RingsSitemap\n \n \n \n \n}\n\n\n\n\nsitemaps_necklases = {'necklases': NecklasesSitemap\n \n \n \n \n}\n\n\n\n\nsitemaps_earrings = {'earrings': EarringsSitemap\n \n \n \n \n}\n\n\n\n\nsitemaps_makeup = {'makeup': MakeupSitemap\n \n \n \n \n}\n\n\n\nsitemaps_haircare = {'haircare': HaircareSitemap\n \n \n \n \n}\n\n\n\nsitemaps_perfumes = {'perfumes': PerfumesSitemap\n \n \n \n \n}\n\n\n\n\nsitemaps_skincare = {'skincare': SkincareSitemap\n \n \n \n \n}\n\n\n\n\nsitemaps_handbags = {'handbags': HandbagsSitemap\n \n \n \n \n}\n\n\n\n\nsitemaps_phones = {'phones': PhonesSitemap\n \n \n \n \n}\n\n\n\nsitemaps_sunglasses = {'sunglasses': SunglassesSitemap\n \n \n \n \n}\n\n\n\nsitemaps_accessories = {'accessories': AccessoriesSitemap\n \n \n \n \n}\n\n\n\nsitemaps_casual = {'casual': CasualSitemap\n \n \n \n \n}\n\n\n\nsitemaps_dress = {'dress': DressSitemap\n \n \n \n \n}\n\n\n\n\nsitemaps_fashion = {'fashion': FashionSitemap\n \n \n \n \n}\n\n\n\n\nsitemaps_luxury = {'luxury': LuxurySitemap\n \n \n \n \n}\n\n\n\n\nurlpatterns = patterns('',\n (r'^admin/', include(admin.site.urls)),\n (r'^', include('trend.izdvojeno.urls')),\n (r'^', include('trend.personalna.urls')),\n (r'^transakcije/', include('trend.transakcije.urls')),\n (r'^robots\\.txt$', direct_to_template, {'template': 'robots.txt', 'mimetype': 'text/plain'}),\n (r'^sitemap\\.xml$', direct_to_template, {'template': 'sitemap_trendyheaven.xml', 'mimetype': 'application/xhtml+xml'}), \n (r'^sitemap-kategorije\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_kategorije}),\n (r'^sitemap-tshirts\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_tshirts}),\n (r'^sitemap-pants\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_pants}),\n (r'^sitemap-dresses\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_dresses}),\n (r'^sitemap-jackets\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_jackets}),\n (r'^sitemap-highheels\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_highheels}),\n (r'^sitemap-boots\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_boots}),\n (r'^sitemap-sneakers\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_sneakers}),\n (r'^sitemap-sandals\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_sandals}),\n (r'^sitemap-bracelets\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_bracelets}),\n (r'^sitemap-rings\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_rings}),\n (r'^sitemap-necklases\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_necklases}),\n (r'^sitemap-earrings\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_earrings}),\n (r'^sitemap-makeup\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_makeup}),\n (r'^sitemap-haircare\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_haircare}),\n (r'^sitemap-perfumes\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_perfumes}),\n (r'^sitemap-skincare\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_skincare}),\n (r'^sitemap-handbags\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_handbags}),\n (r'^sitemap-phones\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_phones}),\n (r'^sitemap-sunglasses\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_sunglasses}),\n (r'^sitemap-accessories\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_accessories}),\n (r'^sitemap-casual\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_casual}),\n (r'^sitemap-dress\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_dress}),\n (r'^sitemap-fashion\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_fashion}),\n (r'^sitemap-luxury\\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps_luxury}),\n \n \n \n \n (r'^google2509461e480d249a\\.html$', direct_to_template, {'template': 'google2509461e480d249a.html', 'mimetype': 'text/html'}),\n (r'^pinterest-efa78\\.html$', direct_to_template, {'template': 'pinterest-efa78.html', 'mimetype': 'text/html'}),\n (r'^fsg192bd\\.txt$', direct_to_template, {'template': 'fsg192bd.txt', 'mimetype': 'text/plain'}),\n)\n\nurlpatterns += patterns('trend.transakcije.views',\n (r'^popular-in-country/', 'drzave_analitika', { 'template_name':'transakcije/drzave.html'}, 'drzave_analitika'),\n)\nurlpatterns += patterns('',\n (r'^media/(?P.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT,}),\n)\n\n\n \n","sub_path":"engine/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":7066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"143059757","text":"# Web scraper for bosch common rail injector\nimport csv\nimport requests\nfrom bs4 import BeautifulSoup\n\n\nurls = [\"http://dieselcatalog.online/en/bosch/04451/0445120265.html\"]\n\nparts = []\napplication = []\ncomparisons = []\n\nwith open('delphi-cr-injector_urls.txt') as urlsfile:\n urls = (line.strip() for line in urlsfile)\n for index,url in enumerate(urls):\n html = requests.get(url).text\n filename = requests.get(url).url.split('/')\n filename = filename[6][:-5]\n soup = BeautifulSoup(html, \"html.parser\")\n table = soup.select('table')\n \n if not table:\n print(filename, \" failed\")\n else:\n print(filename, \" passed\")\n # Replacing Parts\n parts = table[0]\n partsHeaders = [header.text for header in parts.find_all('th')]\n partsList = []\n for row in parts.find_all('tr'):\n partsList.append([val.text for val in row.find_all('td')])\n \n # Application\n application = table[1]\n applicationHeaders = [header.text for header in application.find_all('th')]\n applicationList = []\n for row in application.find_all('tr'):\n applicationList.append([val.text for val in row.find_all('td')])\n \n # Comparisons\n comparisons = table[2]\n comparisonsHeaders = [header.text for header in comparisons.find_all('th')]\n comparisonsList = []\n for row in comparisons.find_all('tr'):\n comparisonsList.append([val.text for val in row.find_all('td')])\n\n # Write data to csv\n with open(filename + '.csv', 'w', encoding=\"utf-8\", newline='') as f:\n writer =csv.writer(f)\n writer.writerow(['Replacing Parts'])\n writer.writerow(partsHeaders)\n writer.writerows(row for row in partsList if row)\n writer.writerow('')\n writer.writerow(['Application'])\n writer.writerow(applicationHeaders)\n writer.writerows(row for row in applicationList if row)\n writer.writerow('')\n writer.writerow(['Comparisons'])\n writer.writerow(comparisonsHeaders)\n writer.writerows(row for row in comparisonsList if row)\n\n\n# rows = []\n\n# for row in spareslist.find_all('tr'):\n# rows.append([val.text for val in row.find_all('td')])\n\n# with open('output_file.csv', 'w', newline='') as f:\n# writer = csv.writer(f)\n# writer.writerow(headers)\n# writer.writerows(row for row in rows if row)","sub_path":"dieselcatalog-web-scraper-2.py","file_name":"dieselcatalog-web-scraper-2.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"516480658","text":"def pri(name = \"Guan Kou\", age = 20):\n print(\"My name is \" + name + \", and I'm \" + str(age) + \" years old!\")\n\nname = input()\nage = input()\nif name == \"\" and age == \"\":\n pri()\nelse:\n pri(name, int(age))\n\n# pri()\n# pri(\"kg\", 18)\n","sub_path":"AIM2018_401_500/A458forDLP119.py","file_name":"A458forDLP119.py","file_ext":"py","file_size_in_byte":236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"96422807","text":"import random\n\n\ndef get_round():\n rounds = int(input(\"how many rounds would you like to play from 1 to 9: \"))\n \n return (rounds + 1)\n\ndef get_p1_move():\n p1_move = input(\"Would you like to play Rock, Paper or Scissors: \")\n if p1_move.lower() == \"rock\":\n \n return \"Rock\"\n elif p1_move.lower() == \"paper\":\n \n return \"Paper\"\n elif p1_move.lower() == \"scissors\":\n \n return \"Scissors\"\n\ndef get_comp_move():\n comp_move = random.randint(1,3)\n if comp_move == 1:\n return \"Rock\"\n elif comp_move == 2:\n return \"Paper\"\n elif comp_move == 3:\n return \"Scissors\"\n\ndef get_winner(p1_move,comp_move):\n if p1_move == comp_move:\n return \"tie\"\n elif p1_move == \"Rock\" and comp_move == \"Paper\":\n return \"computer\"\n elif p1_move == \"Rock\" and comp_move == \"Scissors\":\n return \"player\"\n elif p1_move == \"Paper\" and comp_move == \"Rock\":\n return \"computer\"\n elif p1_move == \"Paper\" and comp_move == \"Scissors\":\n return \"computer\"\n elif p1_move == \"Scissors\" and comp_move == \"Rock\":\n return \"computer\"\n elif p1_move == \"Scissors\" and comp_move == \"Paper\":\n return \"player\"\n\ndef print_score(player_wins,comp_wins,ties):\n \n print(\"The player's score is: {}\".format(player_wins))\n print(\"The computer's score is: {}\".format(comp_wins))\n print(\"The tie score is {}\".format(ties))\n \ndef rps():\n player_wins = 0\n comp_wins = 0\n ties = 0\n \n rounds = get_round()\n for x in range(1,rounds):\n p1move = get_p1_move()\n compmove = get_comp_move()\n winner = get_winner(p1move,compmove)\n print(\"Player chose: {}\".format(p1move))\n print(\"Computer chose: {}\".format(compmove))\n \n if winner == \"player\":\n print(\"Player Won!\")\n player_wins = player_wins + 1\n elif winner == \"computer\":\n print(\"Computer Won!\")\n \n comp_wins = comp_wins + 1\n else:\n print(\"Tie!\")\n \n ties = ties + 1\n print_score(player_wins,comp_wins,ties)\n if player_wins > comp_wins:\n print(\"Player Won the Game\")\n elif comp_wins > player_wins:\n print(\"Computer Won the Game\")\n else:\n print(\"The Game is a Draw\")\n \n\nrps()\n\n#dont open this code!!!!!!!!","sub_path":"Unit 4/AT.rps.py","file_name":"AT.rps.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"329999803","text":"import os\nimport cv2\nimport torch\nimport argparse\nimport numpy as np\nfrom tqdm import tqdm\nfrom torch.nn import functional as F\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nif torch.cuda.is_available():\n torch.set_grad_enabled(False)\n torch.backends.cudnn.enabled = True\n torch.backends.cudnn.benchmark = True\n\nparser = argparse.ArgumentParser(description='Interpolation for a pair of images')\nparser.add_argument('--video', dest='video', required=True)\nparser.add_argument('--skip', dest='skip', action='store_true', help='whether to remove static frames before processing')\nparser.add_argument('--fps', dest='fps', type=int, default=None)\nparser.add_argument('--png', dest='png', action='store_true', help='whether to output png format outputs')\nparser.add_argument('--ext', dest='ext', type=str, default='mp4', help='output video extension')\nparser.add_argument('--exp', dest='exp', type=int, default=1, help='interpolation exponent (base 2)')\nargs = parser.parse_args()\nassert (args.exp in [1, 2, 3])\nargs.times = 2 ** args.exp\n\nfrom model.RIFE import Model\nmodel = Model()\nmodel.load_model('./train_log')\nmodel.eval()\nmodel.device()\n\nvideoCapture = cv2.VideoCapture(args.video)\nfps = np.round(videoCapture.get(cv2.CAP_PROP_FPS))\nsuccess, frame = videoCapture.read()\nh, w, _ = frame.shape\nif args.fps is None:\n args.fps = fps * args.times\nfourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')\nvideo_path_wo_ext, ext = os.path.splitext(args.video)\nif args.png:\n if not os.path.exists('output'):\n os.mkdir('output')\n vid_out = None\nelse:\n vid_out = cv2.VideoWriter('{}_{}X_{}fps.{}'.format(video_path_wo_ext, args.times, int(np.round(args.fps)), args.ext), fourcc, args.fps, (w, h))\n \ncnt = 0\nskip_frame = 1\n\n\ndef write_frame(vid_out, i0, infs, i1, p, user_args):\n global skip_frame, cnt\n \n for i in range(i0.shape[0]):\n # Result was not good enough to write, use previous frames.\n if p[i] > 0.2:\n if user_args.exp > 1:\n infs = [i0[i] for _ in range(len(infs) - 1)]\n infs[-1] = i1[-1]\n else:\n infs = [i0[i] for _ in range(len(infs))]\n \n # Result was too similar to previous frame, skip if given.\n if p[i] < 5e-3 and user_args.skip:\n if skip_frame % 100 == 0:\n print(\"Warning: Your video has {} static frames, \"\n \"skipping them may change the duration of the generated video.\".format(skip_frame))\n skip_frame += 1\n continue\n \n # Write results.\n if user_args.png:\n cv2.imwrite('output/{:0>7d}.png'.format(cnt), i0[i])\n cnt += 1\n for inf in infs:\n cv2.imwrite('output/{:0>7d}.png'.format(cnt), inf[i])\n cnt += 1\n else:\n vid_out.write(i0[i])\n for inf in infs:\n vid_out.write(inf[i])\n\n\ndef make_inference(model, I0, I1, exp):\n middle = model.inference(I0, I1)\n if exp == 1:\n return [middle]\n first_half = make_inference(model, I0, middle, exp=exp - 1)\n second_half = make_inference(model, middle, I1, exp=exp - 1)\n return [*first_half, middle, *second_half]\n\n\nph = ((h - 1) // 32 + 1) * 32\npw = ((w - 1) // 32 + 1) * 32\npadding = (0, pw - w, 0, ph - h)\ntot_frame = videoCapture.get(cv2.CAP_PROP_FRAME_COUNT)\nprint('{}.{}, {} frames in total, {}FPS to {}FPS'.format(video_path_wo_ext, args.ext, tot_frame, fps, args.fps))\npbar = tqdm(total=tot_frame)\nimg_list = [frame]\nwhile success:\n success, frame = videoCapture.read()\n if success:\n img_list.append(frame)\n if len(img_list) == 5 or (not success and len(img_list) > 1):\n I0 = torch.from_numpy(np.transpose(img_list[:-1], (0, 3, 1, 2)).astype(\"float32\") / 255.).to(device)\n I1 = torch.from_numpy(np.transpose(img_list[1:], (0, 3, 1, 2)).astype(\"float32\") / 255.).to(device)\n p = (F.interpolate(I0, (16, 16), mode='bilinear', align_corners=False)\n - F.interpolate(I1, (16, 16), mode='bilinear', align_corners=False)).abs()\n I0 = F.pad(I0, padding)\n I1 = F.pad(I1, padding)\n inferences = make_inference(model, I0, I1, exp=args.exp)\n \n I0 = ((I0[:, :, :h, :w] * 255.).cpu().detach().numpy().transpose(0, 2, 3, 1)).astype('uint8')\n I1 = ((I1[:, :, :h, :w] * 255.).cpu().detach().numpy().transpose(0, 2, 3, 1)).astype('uint8')\n inferences = list(map(lambda x: ((x[:, :, :h, :w] * 255.).cpu().detach().numpy().transpose(0, 2, 3, 1)).astype('uint8'), inferences))\n \n write_frame(vid_out, I0, inferences, I1, p.mean(3).mean(2).mean(1), args)\n pbar.update(4)\n img_list = img_list[-1:]\npbar.close()\nvid_out.release()\n","sub_path":"inference_video_parallel.py","file_name":"inference_video_parallel.py","file_ext":"py","file_size_in_byte":4766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"429765169","text":"class Solution:\n def IsContinuous(self, numbers):\n if numbers == None or len(numbers) < 5:\n return False\n\n numbers.sort()\n\n zero_count = numbers.count(0)\n\n if zero_count == 4:\n return True\n\n if zero_count > 0:\n numbers = list(filter(lambda x: x != 0, numbers))\n\n absent_list = self.IsSeries(numbers)\n\n if zero_count == len(absent_list):\n return True\n else:\n return False\n\n def IsSeries(self, array):\n absent_list = []\n tempList = list(range(array[0], array[-1] + 1))\n for index, item in enumerate(tempList):\n if item not in array:\n absent_list.append(item)\n return absent_list\n\n\nif __name__ == '__main__':\n sol = Solution()\n numbers = [1, 3, 5, 0, 0]\n # numbers = [1, 3, 0, 7, 0]\n # numbers = [1, 0, 0, 5, 0]\n # numbers = [3, 0, 0, 0, 0]\n print(sol.IsContinuous(numbers))\n","sub_path":"Data Structure and Algorithm/剑指offer代码/45. 扑克牌的顺子/IsContinuous.py","file_name":"IsContinuous.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"562601018","text":"#!/usr/bin/env python3\n\"\"\"\nUsage Examples:\n [1] python 3dgan_mit_biasfree__multicategory.py --name biasfree_tfbn\n [2] python 3dgan_mit_biasfree__multicategory.py --ckpath models/biasfree_tfbn.ckpt-100\n generating new objects:\n [3] python 3dgan_mit_biasfree__multicategory.py --train False --ckpath models/biasfree_tfbn.ckpt-16400\n \n interpolating given zvectors:\n [4] python 3dgan_mit_biasfree.py --train False --ckpath models/biasfree_tfbn.ckpt-16400 --interpolatd_zs interpolated_chairs_37_39.npy\n\"\"\"\n#import scipy\nimport pickle\n\nimport os\nimport sys\nimport visdom\nimport logger\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tqdm import *\nfrom utils.utils import *\nimport utils.dataIO as d\n\n'''\nGlobal Parameters\n'''\n#n_epochs = 20205\nbatch_size = 32\ng_lr = 0.00025\nd_lr = 0.00001\nbeta = 0.5\nmomentum = 0.9\nd_thresh = 0.8\nz_size = 200\nleak_value = 0.2\nobj_ratio = 0.7\nobj = 'chair'\n#For the chair only network, just had \"chair\".\n#Now we want a list of multiple categories.\n#Or easier, just reorganize the data folder to have a category \"multicategory, \n#which is the union of the 7 most common object categories:\n#[chairs, sofas, tables, boats, airplanes, rifles, and cars]\n#obj = 'multicategory_partial'#multicategory had memory errors when 7 classes, so do fewer\n\ncube_len = 64\ncube_channel= 1\n\nf_dim = 64\n\nmodel_name = 'biasfree_tfbn'\nsummary_dir = './summary/'\ntrain_sample_directory = './train_sample/'\nmodel_directory = './models/'\nis_local = False\n\nweights, biases = {}, {}\n\n'''\nFlags\n'''\nargs = tf.app.flags\nargs.DEFINE_boolean('train', False, 'True for training, False for testing [%(default)s]')\nargs.DEFINE_boolean('dummy', False, 'True for random sampling as real input, False for ModelNet voxels as real input [%(default)s]')\nargs.DEFINE_string('name', model_name, 'Model name [%(default)s]')\nargs.DEFINE_string('ckpath', None, 'Checkpoint path for restoring (ex: models/biasfree_tfbn.ckpt-100) [%(default)s]')\nargs.DEFINE_string('interpolatd_zs', None, 'z vector path [%(default)s]')\nargs.DEFINE_string('savename', model_name+\"_save\", 'Save name [%(default)s]')\nargs.DEFINE_string('epochs', \"20205\", 'Number of Epochs [%(default)s]')\n# args.DEFINE_integer('f_dim', f_dim, 'Dimension of first layer in D [%(default)s]')\nFLAGS = args.FLAGS\n\nn_epochs = int(FLAGS.epochs)\n\ndef generator(z, batch_size=batch_size, phase_train=True, reuse=False):\n\n strides = [1,2,2,2,1]\n\n with tf.variable_scope(\"gen\", reuse=reuse):\n z = tf.reshape(z, (batch_size, 1, 1, 1, z_size))\n g_1 = tf.nn.conv3d_transpose(z, weights['wg1'], (batch_size,4,4,4,512), strides=[1,1,1,1,1], padding=\"VALID\")\n # g_1 = tf.nn.bias_add(g_1, biases['bg1'])\n g_1 = tf.layers.batch_normalization(g_1, training=phase_train, epsilon=1e-4, momentum=0.9)\n g_1 = tf.nn.relu(g_1)\n print ('G1: ', g_1)\n\n g_2 = tf.nn.conv3d_transpose(g_1, weights['wg2'], (batch_size,8,8,8,256), strides=strides, padding=\"SAME\")\n # g_2 = tf.nn.bias_add(g_2, biases['bg2'])\n g_2 = tf.layers.batch_normalization(g_2, training=phase_train, epsilon=1e-4, momentum=0.9)\n g_2 = tf.nn.relu(g_2)\n print ('G2: ', g_2)\n\n g_3 = tf.nn.conv3d_transpose(g_2, weights['wg3'], (batch_size,16,16,16,128), strides=strides, padding=\"SAME\")\n # g_3 = tf.nn.bias_add(g_3, biases['bg3'])\n g_3 = tf.layers.batch_normalization(g_3, training=phase_train, epsilon=1e-4, momentum=0.9)\n g_3 = tf.nn.relu(g_3)\n print ('G3: ', g_3)\n\n g_4 = tf.nn.conv3d_transpose(g_3, weights['wg4'], (batch_size,32,32,32,64), strides=strides, padding=\"SAME\")\n # g_4 = tf.nn.bias_add(g_4, biases['bg4'])\n g_4 = tf.layers.batch_normalization(g_4, training=phase_train, epsilon=1e-4, momentum=0.9)\n g_4 = tf.nn.relu(g_4)\n print ('G4: ', g_4)\n\n g_5 = tf.nn.conv3d_transpose(g_4, weights['wg5'], (batch_size,64,64,64,1), strides=strides, padding=\"SAME\")\n # g_5 = tf.nn.bias_add(g_5, biases['bg5'])\n # g_5 = tf.nn.sigmoid(g_5)\n g_5 = tf.nn.tanh(g_5)\n print ('G5: ', g_5)\n\n return g_5\n\n\ndef discriminator(inputs, phase_train=True, reuse=False):\n\n strides = [1,2,2,2,1]\n with tf.variable_scope(\"dis\", reuse=reuse):\n d_1 = tf.nn.conv3d(inputs, weights['wd1'], strides=strides, padding=\"SAME\")\n # d_1 = tf.nn.bias_add(d_1, biases['bd1'])\n # d_1 = tf.layers.batch_normalization(d_1, training=phase_train, epsilon=1e-4, momentum=0.9)\n d_1 = lrelu(d_1, leak_value)\n print ('D1: ', d_1)\n\n d_2 = tf.nn.conv3d(d_1, weights['wd2'], strides=strides, padding=\"SAME\") \n # d_2 = tf.nn.bias_add(d_2, biases['bd2'])\n d_2 = tf.layers.batch_normalization(d_2, training=phase_train, epsilon=1e-4, momentum=0.9)\n d_2 = lrelu(d_2, leak_value)\n print ('D2: ', d_2)\n\n d_3 = tf.nn.conv3d(d_2, weights['wd3'], strides=strides, padding=\"SAME\") \n # d_3 = tf.nn.bias_add(d_3, biases['bd3'])\n d_3 = tf.layers.batch_normalization(d_3, training=phase_train, epsilon=1e-4, momentum=0.9)\n d_3 = lrelu(d_3, leak_value) \n print ('D3: ', d_3)\n\n d_4 = tf.nn.conv3d(d_3, weights['wd4'], strides=strides, padding=\"SAME\") \n # d_4 = tf.nn.bias_add(d_4, biases['bd4'])\n d_4 = tf.layers.batch_normalization(d_4, training=phase_train, epsilon=1e-4, momentum=0.9)\n d_4 = lrelu(d_4)\n print ('D4: ', d_4)\n\n\n d_5 = tf.nn.conv3d(d_4, weights['wd5'], strides=[1,1,1,1,1], padding=\"VALID\")\n d_5_no_sigmoid = d_5\n d_5 = tf.nn.sigmoid(d_5)\n print ('D5: ', d_5)\n\n return d_5, d_5_no_sigmoid\n\n# --- [ Initialize Global Variables: strides, sizes, weights, biases\ndef init():\n\n global strides, s, s2, s4, s8, s16\n\n strides = [1,2,2,2,1]\n\n s = int(cube_len) #64\n s2 = int(np.ceil(float(s) / float(strides[1]))) #32\n s4 = int(np.ceil(float(s2) / float(strides[1]))) #16\n s8 = int(np.ceil(float(s4) / float(strides[1]))) #8\n s16 = int(np.ceil(float(s8) / float(strides[1]))) #4\n\n initializeWeights()\n # initializeBiases()\n\n# --- \ndef initializeWeights():\n\n global weights\n xavier_init = tf.contrib.layers.xavier_initializer()\n\n weights['wg1'] = tf.get_variable(\"wg1\", shape=[4, 4, 4, 512, 200], initializer=xavier_init)\n weights['wg2'] = tf.get_variable(\"wg2\", shape=[4, 4, 4, 256, 512], initializer=xavier_init)\n weights['wg3'] = tf.get_variable(\"wg3\", shape=[4, 4, 4, 128, 256], initializer=xavier_init)\n weights['wg4'] = tf.get_variable(\"wg4\", shape=[4, 4, 4, 64, 128], initializer=xavier_init)\n weights['wg5'] = tf.get_variable(\"wg5\", shape=[4, 4, 4, 1, 64], initializer=xavier_init)\n\n weights['wd1'] = tf.get_variable(\"wd1\", shape=[4, 4, 4, 1, 64], initializer=xavier_init)\n weights['wd2'] = tf.get_variable(\"wd2\", shape=[4, 4, 4, 64, 128], initializer=xavier_init)\n weights['wd3'] = tf.get_variable(\"wd3\", shape=[4, 4, 4, 128, 256], initializer=xavier_init)\n weights['wd4'] = tf.get_variable(\"wd4\", shape=[4, 4, 4, 256, 512], initializer=xavier_init)\n weights['wd5'] = tf.get_variable(\"wd5\", shape=[4, 4, 4, 512, 1], initializer=xavier_init)\n\n return weights\n\n# ---\ndef initialiseBiases():\n\n global biases\n zero_init = tf.zeros_initializer()\n\n biases['bg1'] = tf.get_variable(\"bg1\", shape=[512], initializer=zero_init)\n biases['bg2'] = tf.get_variable(\"bg2\", shape=[256], initializer=zero_init)\n biases['bg3'] = tf.get_variable(\"bg3\", shape=[128], initializer=zero_init)\n biases['bg4'] = tf.get_variable(\"bg4\", shape=[64], initializer=zero_init)\n biases['bg5'] = tf.get_variable(\"bg5\", shape=[1], initializer=zero_init)\n\n biases['bd1'] = tf.get_variable(\"bd1\", shape=[64], initializer=zero_init)\n biases['bd2'] = tf.get_variable(\"bd2\", shape=[128], initializer=zero_init)\n biases['bd3'] = tf.get_variable(\"bd3\", shape=[256], initializer=zero_init)\n biases['bd4'] = tf.get_variable(\"bd4\", shape=[512], initializer=zero_init)\n biases['bd5'] = tf.get_variable(\"bd5\", shape=[1], initializer=zero_init)\n\n return biases\n# --- ]\n\ndef trainGAN(is_dummy=False, checkpoint=None, name=model_name):\n\n init()\n\n global_step = tf.get_variable('global_step', shape=[], initializer=tf.zeros_initializer(), dtype=tf.int32)\n\n z_vector = tf.placeholder(shape=[batch_size,z_size],dtype=tf.float32) \n x_vector = tf.placeholder(shape=[batch_size,cube_len,cube_len,cube_len,cube_channel],dtype=tf.float32)\n\n net_g_train = generator(z_vector, phase_train=True, reuse=False) \n net_g_test = generator(z_vector, phase_train=False, reuse=True)\n print ('G train: ', net_g_train)\n print ('G test: ', net_g_test)\n\n d_output_ax, d_output_x = discriminator(x_vector, phase_train=True, reuse=False)\n d_output_ax = tf.clip_by_value(d_output_ax, 0.01, 0.99)\n # summary_d_x_hist = tf.summary.histogram(\"d_prob_x\", d_output_ax)\n\n d_output_az, d_output_z = discriminator(net_g_train, phase_train=True, reuse=True)\n d_output_az = tf.clip_by_value(d_output_az, 0.01, 0.99)\n # summary_d_z_hist = tf.summary.histogram(\"d_prob_z\", d_output_az)\n\n print ('D_output_x: ', d_output_x)\n print ('D_output_z: ', d_output_z)\n\n # Compute the discriminator accuracy (probability > 0.5 => acc = 1)\n # `n_p_x` : the number of D(x) output which prob > 0.5\n # `n_p_z` : the number of D(G(z)) output which prob <= 0.5\n n_p_x = tf.reduce_sum(tf.cast(d_output_ax > 0.5, tf.int32)) # hope all d_output_ax ~ 1\n n_p_z = tf.reduce_sum(tf.cast(d_output_az <= 0.5, tf.int32)) # hope all d_output_az ~ 0\n d_acc = tf.divide( n_p_x + n_p_z, 2 * np.prod(d_output_ax.shape.as_list()) )\n\n # Compute the discriminator and generator loss\n # --- [ Bad Accuracy\n # d_loss = -tf.reduce_mean(tf.log(d_output_ax) + tf.log(1-d_output_az))\n # g_loss = -tf.reduce_mean(tf.log(d_output_az))\n\n d_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=d_output_x, labels=tf.ones_like(d_output_x)) + \\\n tf.nn.sigmoid_cross_entropy_with_logits(logits=d_output_z, labels=tf.zeros_like(d_output_z))\n g_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=d_output_z, labels=tf.ones_like(d_output_z))\n # tf.nn.sigmoid_cross_entropy_with_logits(logits=d_output_x, labels=tf.zeros_like(d_output_x))\n d_loss = tf.reduce_mean(d_loss)\n g_loss = tf.reduce_mean(g_loss)\n\n # --- [ Trick: label smoothing\n # d_output_shape = d_output_ax.get_shape().as_list()\n # smooth_ones = tf.random_uniform(d_output_shape, 0.7, 1.0)\n # smooth_zeros = tf.random_uniform(d_output_shape, 0.0, 0.3)\n\n # d_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=d_output_x, labels=smooth_ones) + \\\n # tf.nn.sigmoid_cross_entropy_with_logits(logits=d_output_z, labels=smooth_zeros)\n # g_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=d_output_z, labels=smooth_ones) + \\\n # tf.nn.sigmoid_cross_entropy_with_logits(logits=d_output_x, labels=smooth_zeros)\n # d_loss = tf.reduce_mean(d_loss)\n # g_loss = tf.reduce_mean(g_loss)\n \n # --- [ Softmax BCE (D output: tanh)\n # logits = tf.concat( (d_output_ax, d_output_az), axis=0 )\n # d_ground_truth = tf.concat( (tf.random_uniform([batch_size], 0.7, 1.0), -tf.random_uniform([batch_size], 0.7, 1.0)), axis=0 )\n # g_ground_truth = tf.concat( (-tf.random_uniform([batch_size], 0.7, 1.0), tf.random_uniform([batch_size], 0.7, 1.0)), axis=0 )\n\n # d_loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=d_ground_truth)\n # g_loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=g_ground_truth)\n\n # summary_d_loss = tf.summary.scalar(\"d_loss\", d_loss)\n # summary_g_loss = tf.summary.scalar(\"g_loss\", g_loss)\n # summary_n_p_z = tf.summary.scalar(\"n_p_z\", n_p_z)\n # summary_n_p_x = tf.summary.scalar(\"n_p_x\", n_p_x)\n # summary_d_acc = tf.summary.scalar(\"d_acc\", d_acc)\n\n net_g_test = generator(z_vector, phase_train=False, reuse=True)\n\n para_g = [var for var in tf.trainable_variables() if any(x in var.name for x in ['wg', 'bg', 'gen'])]\n para_d = [var for var in tf.trainable_variables() if any(x in var.name for x in ['wd', 'bd', 'dis'])]\n\n # For ``tf.layers.batch_normalization`` updating\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops):\n # d_lr_decay = tf.train.exponential_decay(d_lr, global_step, 100, 0.96, staircase=True)\n # g_lr_decay = tf.train.exponential_decay(g_lr, global_step, 100, 0.96, staircase=True)\n optimizer_op_d = tf.train.AdamOptimizer(learning_rate=d_lr,beta1=beta).minimize(d_loss,var_list=para_d)\n optimizer_op_g = tf.train.AdamOptimizer(learning_rate=g_lr,beta1=beta).minimize(g_loss,var_list=para_g)\n\n saver = tf.train.Saver(tf.global_variables(), max_to_keep=20)\n # vis = visdom.Visdom()\n\n # save summary\n # if not os.path.exists(summary_dir):\n # os.makedirs(summary_dir)\n # writer = tf.summary.FileWriter(summary_dir)\n\n\n ### Constraint GPU memory usage\n # [ref] https://stackoverflow.com/questions/34199233\n # [ref] https://indico.io/blog/the-good-bad-ugly-of-tensorflow/\n config = tf.ConfigProto()\n config.gpu_options.allow_growth=True\n\n with tf.Session(config=config) as sess:\n\n sess.run(tf.global_variables_initializer())\n\n if checkpoint is not None:\n saver.restore(sess, checkpoint)\n epoch = sess.run(global_step)\n sess.run(tf.assign(global_step, epoch + 1))\n\n if is_dummy:\n volumes = np.random.randint(0,2,(batch_size,cube_len,cube_len,cube_len))\n print ('Using Dummy Data')\n else:\n volumes = d.getAll(obj=obj, train=True, is_local=is_local, obj_ratio=obj_ratio)\n print ('Using ' + obj + ' Data')\n volumes = volumes[...,np.newaxis].astype(np.float32)\n # Same as `volumes[:,:,:,:,np.newaxis].astype(np.float32)`\n # --- CENTRAL ---\n # volumes *= 2.0\n # volumes -= 1.0\n # ---------------\n\n z_val = np.random.normal(0, 0.33, size=[batch_size, z_size]).astype(np.float32)\n\n for epoch in range(sess.run(global_step), n_epochs):\n\n idx = np.random.randint(len(volumes), size=batch_size)\n x = volumes[idx]\n z = np.random.normal(0, 0.33, size=[batch_size, z_size]).astype(np.float32)\n # z = np.random.uniform(0, 1, size=[batch_size, z_size]).astype(np.float32)\n\n # Update the discriminator and generator\n # d_summary_merge = tf.summary.merge([summary_d_loss,\n # summary_d_x_hist, \n # summary_d_z_hist,\n # summary_n_p_x,\n # summary_n_p_z,\n # summary_d_acc])\n\n _, discriminator_loss = sess.run([optimizer_op_d,d_loss],feed_dict={z_vector:z, x_vector:x})\n _, generator_loss = sess.run([optimizer_op_g,g_loss],feed_dict={z_vector:z, x_vector:x})\n # _, summary_d, discriminator_loss = sess.run([optimizer_op_d,d_summary_merge,d_loss],feed_dict={z_vector:z, x_vector:x})\n # _, summary_g, generator_loss = sess.run([optimizer_op_g,summary_g_loss,g_loss],feed_dict={z_vector:z}) \n d_accuracy, n_x, n_z = sess.run([d_acc, n_p_x, n_p_z],feed_dict={z_vector:z, x_vector:x})\n print (\"# of (D(x) > 0.5) : \", n_x)\n print (\"# of (D(G(z)) <= 0.5) : \", n_z)\n print ('Discriminator Training ', \"epoch: \",epoch,', d_loss:',discriminator_loss,'g_loss:',generator_loss, \"d_acc: \", d_accuracy)\n print ('Generator Training ', \"epoch: \",epoch,', d_loss:',discriminator_loss,'g_loss:',generator_loss, \"d_acc: \", d_accuracy)\n\n if d_accuracy < d_thresh:\n _, discriminator_loss = sess.run([optimizer_op_d,d_loss],feed_dict={z_vector:z, x_vector:x})\n d_accuracy = sess.run(d_acc,feed_dict={z_vector:z, x_vector:x})\n print ('Discriminator Training ', \"epoch: \",epoch,', d_loss:',discriminator_loss,'g_loss:',generator_loss, \"d_acc: \", d_accuracy)\n\n # output generated chairs\n if epoch % 200 == 0:\n g_objects = sess.run(net_g_test,feed_dict={z_vector:z_val}) #type=np.ndarray\n if not os.path.exists(train_sample_directory):\n os.makedirs(train_sample_directory)\n # --- [ in Python2, dump as a pickle file. Loading this file by `np.load(filename, encoding='latin1')` in Python3 ] ---\n g_objects.dump(os.path.join(train_sample_directory, '{}_{}.pkl'.format(model_name, epoch)))\n # ---------------------------------------------------------------------------------------------------------------------\n id_ch = np.random.randint(0, batch_size, 4)\n #for i in range(4):\n # if g_objects[id_ch[i]].max() > 0.5:\n # d.plotMeshFromVoxels(np.squeeze(g_objects[id_ch[i]]>0.5), threshold=0.5)\n\n # store checkpoint\n if epoch % 200 == 0:\n if not os.path.exists(model_directory):\n os.makedirs(model_directory)\n saver.save(sess, save_path = os.path.join(model_directory, '{}.ckpt'.format(model_name)), global_step=global_step)\n\n # writer.add_summary(summary_d, epoch)\n # writer.add_summary(summary_g, epoch)\n # writer.flush()\n sess.run(tf.assign(global_step, epoch + 1))\n\n\ndef testGAN(trained_model_path=None, n_batches=2, z_vector_path=None):\n init()\n \n #savename='save-16K'\n #savename=aaaaaaaaaaaaaa\n #savename='lfmTest1_18Dez'\n savename=FLAGS.savename\n \n \n z_vector = tf.placeholder(shape=[batch_size,z_size],dtype=tf.float32) \n net_g_test = generator(z_vector, phase_train=True, reuse=False)\n #net_g_test = generator(z_vector, phase_train=True, reuse=True)#ideally would like to reuse weights? But error.\n # vis = visdom.Visdom()\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n saver.restore(sess, trained_model_path) \n\n\n #If usign particular zvectors from interpolation:\n #z_vector_path is path to z vector numpy array\n if z_vector_path:\n savename += '__interpolated_results'\n z_sample = np.load(z_vector_path).astype(np.float32) #shape is Npoints x 200, using Npoints=batchsize (32)\n g_out = sess.run(net_g_test,feed_dict={z_vector:z_sample})\n z_out = z_sample\n \n \n \n \n #Ifjustgeneratign new random z vectors:\n else:\n # output generated objects\n #g_out = np.array([])\n #z_out = np.array([])\n for j in range(n_batches):\n next_sigma = 0.33 # float(raw_input())\n z_sample = np.random.normal(0, next_sigma, size=[batch_size, z_size]).astype(np.float32)\n g_objects = sess.run(net_g_test,feed_dict={z_vector:z_sample})\n #id_ch = np.random.randint(0, batch_size, 4)\n \n \n # for i in range(batch_size):\n # print(g_objects[i].max(), g_objects[i].min(), g_objects[i].shape)\n # pickle.dump(g_objects, open('save-{0}-{1}-20K.p'.format(j, i), 'wb'))\n \n if j==0:\n g_out = g_objects\n z_out = z_sample\n #print(g_out.shape)\n else:\n g_out = np.vstack((g_out,g_objects))\n z_out = np.vstack((z_out,z_sample))\n #print(g_out.shape)\n \n \n #savename='save-7800partial'\n \n #pickle.dump(g_objects, open('output/{0}.p'.format(savename), 'wb'))\n np.save('output/{0}.npy'.format(savename), g_out)\n np.save('output/{}_zvectors.npy'.format(savename),z_out)\n #if g_objects[id_ch[i]].max() > 0.5:\n # d.plotVoxelVisdom(np.squeeze(g_objects[id_ch[i]]>0.5), vis, '_'.join(map(str,[i])))\n\n\n\n\ndef main(_):\n if FLAGS.train:\n trainGAN(is_dummy=FLAGS.dummy, checkpoint=FLAGS.ckpath, name=FLAGS.name)\n else:\n if FLAGS.ckpath:\n if FLAGS.interpolatd_zs:\n #generate 3D models of particular z vectors for interpolation \n #instead of justrandom z vectors\n testGAN(trained_model_path=FLAGS.ckpath, z_vector_path=FLAGS.interpolatd_zs)\n else:\n testGAN(trained_model_path=FLAGS.ckpath)\n else:\n logger.error(\"Needs checkpoint path.\")\n\nif __name__ == '__main__':\n tf.app.run()\n","sub_path":"lfm_coms/include/coms4995-project/chairs/3dgan_mit_biasfree.py","file_name":"3dgan_mit_biasfree.py","file_ext":"py","file_size_in_byte":20919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"209233827","text":"from django.forms import ModelForm\nfrom estate.models import Room\n\n\nclass RoomForm(ModelForm):\n class Meta:\n model = Room\n fields = [\n 'condo',\n 'title',\n 'description',\n 'still_on_contract',\n 'price_for_rent',\n 'price_for_sell',\n 'number',\n 'floor_number',\n 'number_of_bedroom',\n 'number_of_bathroom',\n 'area'\n ]\n","sub_path":"estate/forms/room_form.py","file_name":"room_form.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"462905368","text":"import scipy.sparse.linalg as spla\nimport scipy.sparse as sp\nimport numpy as np\nfrom scipy.io import mmread\n\n# Base class for preconditioners. The implementation of the base class is\n# a do-nothing two-sided preconditioner. Derived classes should reimplement\n# at least one of the applyLeft() and applyRight() functions.\nclass PreconditionerBase:\n # Nothing for constructor to do\n def __init__(self):\n pass\n\n\n def applyLeft(self, vec):\n return vec\n\n def applyRight(self, vec):\n return vec\n\n\n\n\n# ILU Preconditioner, applied from the right.\n# Constructor parameters:\n# (*) A -- The matrix to be approximately factored.\n# (*) drop_tol -- Tolerance for deciding whether to accept \"fill\" entries\n# in the approximate factorization. With a value of 1, no fill\n# is accepted. With a value of 0, all fill is accepted. Default\n# is 0.0001.\n# (*) fill_factor -- Factor by which the number of nonzeros is allowed\n# to increase during the approximate factorization. SuperLU's\n# default is 10. With a low value of drop_tol you may need to\n# increase this.\n\nclass ILURightPreconditioner(PreconditionerBase):\n def __init__(self, A, drop_tol=0.001, fill_factor=15):\n PreconditionerBase.__init__(self)\n\n # Construct the ILU approximate factorization. Super LU needs\n # to use CSC format, so do the conversion here.\n self.ILU = spla.spilu(A.tocsc(),\n drop_tol=drop_tol, fill_factor=fill_factor)\n\n def residCheck(self):\n L = self.ILU.L\n U = self.ILU.U\n pr = self.ILU.perm_r\n pc = self.ILU.perm_c\n n,nc = U.shape\n Pr = sp.csc_matrix((np.ones(n), (pr, np.arange(n))))\n Pc = sp.csc_matrix((np.ones(n), (np.arange(n), pc)))\n resid = L*U - Pr*A*Pc\n normOrder=1 # easiest to use 1 norm with CSC storage.\n normA = spla.norm(A,normOrder)\n return spla.norm(resid, normOrder)/normA\n\n\n def applyRight(self, vec):\n return self.ILU.solve(vec)\n\n\nif __name__=='__main__':\n\n refinement_level = 12\n A = mmread('DH-Matrix-%d.mtx' % refinement_level)\n A = A.tocsr()\n n,nc = A.shape\n\n fill_factor = 10\n\n print('----------------------------------------------------------------------')\n print('Checking ILU factorization by computing ||A-LU||/||A|| (with permutations)')\n print('System is %d by %d' %(n,nc))\n print('ILU maximum fill factor is %f' % fill_factor)\n\n print('\\n\\n%20s\\t %20s' % ('Drop tolerance', 'ILU residual norm'))\n print('----------------------------------------------------------------------')\n for p in range(20):\n tol = 0.5**p\n ILU = ILURightPreconditioner(A, drop_tol=tol, fill_factor=20)\n print('%20.15f\\t %20.5g'%(tol, ILU.residCheck()))\n","sub_path":"GMRESProgrammingProblem/BasicPreconditioner.py","file_name":"BasicPreconditioner.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"633209351","text":"__all__ = (\n 'dispatch',\n)\n\nfrom abc import get_cache_token\nfrom itertools import chain\nimport functools\nimport inspect\nimport sys\nimport types\nimport typing\nimport weakref\n\n# from typeguard import check_type\n\nfrom chatora.dispatch.mro_resolver import compose_mro as _compose_mro\n\n\nclass _NotSpecified:\n\n __name__ = 'NOT_SPECIFIED'\n __slots__ = ()\n\n def __reduce__(self):\n return self.__name__\n\n def __str__(self):\n return f'<{self.__module__}.{self.__name__}>'\n\n def __eq__(self, other):\n return type(self) is type(other)\n\n def __hash__(self):\n return hash(type(self))\n\n def __ne__(self, other):\n return type(self) is not type(other)\n\n def __bool__(self):\n return False\n\n\nNOT_SPECIFIED = _NotSpecified()\n_MAX_DEPTH = sys.maxsize\n_NoneType = type(None)\n\n\ndef _find_impl(\n registry: typing.Mapping[int, typing.Mapping[typing.Tuple, typing.Callable]],\n call_types: typing.Sequence,\n) -> typing.Tuple[typing.Callable, ...]:\n call_length = len(call_types)\n\n try:\n reg = registry[call_length]\n except KeyError:\n return ()\n\n lowest_depth = _MAX_DEPTH\n best_keys = []\n\n for reg_key in reg:\n count = 0\n depth = 0\n\n for pos in range(call_length):\n reg_types, ctype, r_depth = reg_key[pos], call_types[pos], _MAX_DEPTH\n if ctype is typing.Any:\n ctype = object\n elif ctype is None:\n ctype = _NoneType\n\n for rtype in reg_types if isinstance(reg_types, tuple) else (reg_types,):\n if isinstance(rtype, type) and isinstance(ctype, type):\n try:\n _d = _compose_mro(ctype, (rtype,)).index(rtype)\n if _d < r_depth:\n r_depth = _d\n except ValueError:\n continue\n elif ctype == rtype:\n r_depth = 0\n break\n elif pos != 0 and not isinstance(ctype, type):\n raise TypeError(f'Invalid call type {ctype!r}')\n\n if r_depth < _MAX_DEPTH:\n count += 1\n depth += r_depth\n else:\n break\n\n if count == call_length:\n if lowest_depth > depth:\n best_keys = [reg_key]\n lowest_depth = depth\n elif lowest_depth == depth:\n best_keys.append(reg_key)\n\n return tuple(reg[k] for k in best_keys if k in reg)\n\n\ndef dispatch(\n func: typing.Callable,\n register_first_func=True,\n sub_registry_factory: typing.Callable[[], typing.Mapping] = dict,\n) -> typing.Callable:\n registry = {}\n dispatch_cache = weakref.WeakValueDictionary()\n cache_token = None\n\n def dispatch(return_type, args: typing.Sequence, arg_types: typing.Sequence = ()):\n nonlocal cache_token\n\n if arg_types:\n call_types = tuple(\n object if t is typing.Any else _NoneType if return_type is None else return_type\n for t in chain((return_type,), arg_types)\n )\n else:\n call_types = tuple(chain(\n (object if return_type is typing.Any else _NoneType if return_type is None else return_type,),\n (a.__class__ for a in args),\n ))\n\n if cache_token is not None:\n current_token = get_cache_token()\n if cache_token != current_token:\n dispatch_cache.clear()\n cache_token = current_token\n try:\n impl = dispatch_cache[call_types]\n except KeyError:\n try:\n impl = registry[len(call_types)][call_types]\n except KeyError:\n impls = _find_impl(registry, call_types)\n if len(impls) == 1:\n impl = impls[0]\n elif len(impls) == 0:\n raise TypeError(\n f'No callable found: '\n f'arg_types={call_types[1:]!r}, return_type={call_types[0]!r}',\n )\n elif len(impls) > 1:\n raise TypeError(\n f'Multiple callables found: '\n f'arg_types={call_types[1:]!r}, return_type={call_types[0]!r}, found={impls!r}',\n )\n dispatch_cache[call_types] = impl\n return impl\n\n def register(\n func: typing.Optional[typing.Callable] = None,\n arg_types: typing.Sequence = (),\n return_type: typing.Any = NOT_SPECIFIED,\n ) -> typing.Callable:\n nonlocal cache_token\n\n if func is None:\n return lambda func: register(func, arg_types, return_type)\n elif not hasattr(func, '__annotations__'):\n raise TypeError(\n f\"Invalid first argument to `register()`: {func!r}. \"\n f\"Use either `@register(arg_types)` or plain `@register` \"\n f\"on an annotated function.\"\n )\n\n if return_type is not NOT_SPECIFIED and arg_types:\n _sig_types = chain((return_type,), arg_types)\n else:\n sig = inspect.signature(func)\n _sig_types = chain(\n (sig.return_annotation if return_type is NOT_SPECIFIED else return_type,),\n arg_types or (\n param.annotation for param in sig.parameters.values() if param.kind in (\n inspect.Parameter.POSITIONAL_ONLY,\n inspect.Parameter.POSITIONAL_OR_KEYWORD,\n )\n ),\n )\n\n sig_types = []\n may_have_abstractmethods = False\n for i, t in enumerate(_sig_types):\n if t is inspect.Parameter.empty or t is typing.Any:\n t = object\n elif t is None:\n t = _NoneType\n elif isinstance(t, type):\n if hasattr(t, '__abstractmethods__'):\n may_have_abstractmethods = True\n elif i != 0:\n # Return type can be a typing annotation. On the other hand, arg type MUST be a class,\n # typing annotation with a class __origin__, or typing.Union(with class members)\n\n torg = getattr(t, '__origin__', None)\n if isinstance(torg, type):\n if getattr(t, '__args__', ()):\n raise TypeError(f'Invalid annotation {t!r}')\n elif hasattr(torg, '__abstractmethods__'):\n may_have_abstractmethods = True\n t = torg\n elif torg is typing.Union:\n _t = []\n for _a in t.__args__:\n if _a is typing.Any:\n _a = object\n elif not isinstance(_a, type):\n raise TypeError(f'Invalid annotation {t!r}')\n elif hasattr(torg, '__abstractmethods__'):\n may_have_abstractmethods = True\n _t.append(_a)\n t = tuple(_t)\n else:\n raise TypeError(f'Invalid annotation {t!r}')\n sig_types.append(t)\n sig_types = tuple(sig_types)\n\n try:\n registry[len(sig_types)][sig_types] = func\n except KeyError:\n registry[len(sig_types)] = sub_registry_factory()\n registry[len(sig_types)][sig_types] = func\n\n if cache_token is None and may_have_abstractmethods:\n cache_token = get_cache_token()\n dispatch_cache.clear()\n return func\n\n def wrapper(*args, _return_type=typing.Any, **kwargs):\n return dispatch(_return_type, args)(*args, **kwargs)\n\n # funcname = getattr(func, '__name__', 'dispatch function')\n # registry[object] = func\n if register_first_func:\n register(func)\n wrapper.register = register\n wrapper.dispatch = dispatch\n wrapper.clear_dispatch_cache = dispatch_cache.clear\n wrapper._registry = types.MappingProxyType(registry)\n wrapper._dispatch_cache = dispatch_cache\n functools.update_wrapper(wrapper, func)\n return wrapper\n","sub_path":"chatora/dispatch/dispatch.py","file_name":"dispatch.py","file_ext":"py","file_size_in_byte":8238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"403324193","text":"\"\"\"empty message\n\nRevision ID: bfb0f95bc208\nRevises: ea2cf89c2726\nCreate Date: 2018-05-02 16:28:04.565169\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'bfb0f95bc208'\ndown_revision = 'ea2cf89c2726'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('chart_insight', sa.Column('is_show_original', sa.Integer(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('chart_insight', 'is_show_original')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/bfb0f95bc208_.py","file_name":"bfb0f95bc208_.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"424240743","text":"#!/user/bin/pytthon\n# -*- coding:utf-8 -*-\n# @Time: 2018/5/23 15:58\n# @Author: lichexo\n# @File: houlai.py\n\nimport requests\nimport json\n\n\nurl = 'http://music.163.com/weapi/v1/resource/comments/R_SO_4_553310243?csrf_token=846f018c0d8662a03bc6f0016cdf7f67'\n\nheaders = {\n'Host': 'music.163.com',\n'Origin': 'http://music.163.com',\n'Referer': 'http://music.163.com/song?id=553310243',\n'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64)'\n ' AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'\n}\n\n# 因为是post提交,采用MD5或者其他算法加密过,但是我们可以直接使用加密后的数据,用于浏览器识别身份\nUser_Data = {\n 'params': 'nUMvtApJ7WYkBgVTUGdhecvhjBsh0HbqJg6r0VvWTUfvTg7YN2wNXktF43ho0PVaiH9o7nf2IWGX2pqiMqD7SEKTydD3HY/'\n 'sfShNexswo2+Rn4zVBoDS6oalcHGxEBr2aRRZddaM2A3Tr/ePgNtu7p/oCnHdrzOoyJ8IfrJ0K/drrD6N3xNpAYYQm7XzxCsgiI0hHTlF+y+EeLW5O5hwi11SYTZcMlkwfykhLtTcTKU=',\n 'encSecKey': 'c9361204a87ab4bcd6f8690c16675c24c5458eab4348599354871643bdeeb8db52a33048ae036936e0a1fddc7a43ff7688'\n 'f38015a3b8a05b3db9087340a1be42303c56588a331f3e66a5c28255ae9b5f9140a96e6066689e'\n '74be945fc5c395393de71d5d4adf6b093f577bbc7bc485235d37f613e57b6aec2a26ad06bb16db8f'\n}\n\nresponse = requests.post(url, headers=headers, data= User_Data)\n\ndata = json.loads(response.text)\nhotcomments = []\nfor hotcomment in data['hotComments']:\n item ={\n 'nickname':hotcomment['user']['nickname'],\n 'content':hotcomment['content'],\n 'likedCount':hotcomment['likedCount']\n }\n hotcomments.append(item)\n# 获取评论用户名,内容,以及对应的点赞数\nnickname_list = [content['content']for content in hotcomments]\ncontent_list = [content['nickname']for content in hotcomments]\nlikedCount_list = [content['likedCount']for content in hotcomments]\n\nfrom pyecharts import Bar\n# 图表展示\nbar = Bar('评论中点赞数显示图')\nbar.add('点赞数',nickname_list,likedCount_list, is_stack=True, mark_line=['min', 'max'], mark_point=['average'] )\nbar.render()\n\nfrom wordcloud import WordCloud\nimport matplotlib.pyplot as plt\n# 词云展示\ncontent_text = \" \".join(content_list)\nwordcloud = WordCloud(font_path=r\"F:\\字体\\21\\YGY20070701.ttf\",max_words=200).generate(content_text)\nplt.figure()\nplt.imshow(wordcloud,interpolation='bilinear')\nplt.axis('off')\nplt.show()","sub_path":"wangyiyunmusic/houlai.py","file_name":"houlai.py","file_ext":"py","file_size_in_byte":2386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"287202346","text":"from datetime import datetime\nimport time\nimport os\nfrom os.path import join, dirname\nimport requests\nimport json\nimport pandas\nimport matplotlib.pyplot as plot\nfrom dotenv import load_dotenv\n\nowner = 'zeals-co-ltd'\n\ndotenv_path = join(dirname(__file__), '.env')\nload_dotenv(dotenv_path)\n\nACCESS_TOKEN = os.environ.get(\"ACCESS_TOKEN\")\nOWNER = os.environ.get(\"OWNER\")\n\nurl = 'https://api.github.com'\nrepositories_url = f\"/orgs/{OWNER}/repos\"\n\nparams = {\n 'access_token': ACCESS_TOKEN\n}\n\ndict_org_repositories = requests.get(url + repositories_url, params = params).json()\ndf_org_repositories = pandas.DataFrame(dict_org_repositories)\nprint(df_org_repositories[\"name\"])\n\nrepositories = [\"jupiter\"]\nweekly_commits_dfs = {}\n\nfor repository in repositories:\n weekly_commits_url = f\"/repos/{OWNER}/{repository}/stats/commit_activity\"\n dict_weekly_commits = requests.get(url + weekly_commits_url, params = params).json()\n time.sleep(10)\n\n df_weekly_commits = pandas.DataFrame(dict_weekly_commits)\n df_weekly_commits[\"datetime_week\"] = df_weekly_commits[\"week\"].apply(datetime.fromtimestamp).dt.strftime('%Y/%m/%d')\n\n df_weekly_commits[\"total_pct_change\"] = df_weekly_commits[\"total\"].pct_change()\n\n weekly_commits_dfs[repository] = df_weekly_commits\n\nprint(weekly_commits_dfs)\n\naccum_bar_df = pandas.DataFrame({\"week\": weekly_commits_dfs[\"jupiter\"][\"datetime_week\"]})\nfor repository, df in weekly_commits_dfs.items():\n accum_bar_df[repository] = df[\"total\"]\n accum_bar_df[f\"{repository}_change_rate\"] = df[\"total_pct_change\"]\n\naccum_bar_df.head()\n\nfig, ax = plot.subplots()\naccum_bar_df.plot(\n kind = \"bar\",\n x = \"week\",\n y = repositories,\n stacked = True,\n figsize = (18, 8),\n legend=True,\n title = \"Weekly commit\",\n ax = ax\n )\nax.set_xlabel(\"\")\nax.set_ylabel(\"Commits\")\nplot.show()\n\nrepositories_change_rate = [f\"{repository}_change_rate\" for repository in repositories]\nfig, ax = plot.subplots()\naccum_bar_df.plot(\n x = \"week\",\n y = repositories_change_rate,\n figsize = (18, 8),\n legend=True,\n title = \"Weekly commit change rate\",\n ax = ax,\n ylim = [-1, 3]\n )\n\nax.set_xlabel(\"\")\nax.set_ylabel(\"Change rate (%)\")\nplot.show()\n","sub_path":"github_analytics.py","file_name":"github_analytics.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"104354050","text":"# import the necessary packages\nfrom picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport cv2\nimport numpy as np\nimport time\n\n# create a timer\ncurrent_time = time.time()\nstart_time = time.time()\ntime_out = 20 # number of seconds before timing out\n\n# initialize the camera and grab a reference to the raw camera capture\ncamera = PiCamera()\ncamera.resolution = (640, 480)\ncamera.framerate = 30\nrawCapture = PiRGBArray(camera, size=(640, 480))\nframesToPlot = 8\n \n# Load a cascade file for detecting faces\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\");\n\n# keep track of bounding box locations in a dictionary\nface_dict = {'location': [], 'time': [], 'velocity': [[0, 0]]}\n\n# capture frames from the camera\nfor frame in camera.capture_continuous(rawCapture, format=\"bgr\", use_video_port=True):\n\t### *** RECOGNIZE AND RECORD LOCATION OF OBJECT *** ###\n\t# grab the raw NumPy array representing the image, then initialize the timestamp\n\t# and occupied/unoccupied text\n\timage = frame.array\n\tprint(image)\t\n\t# Convert to grayscale\n\tgray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n\t# Look for faces in the image using the loaded cascade file\n\tfaces = face_cascade.detectMultiScale(gray, 1.1, 5)\n\t# Draw a rectangle around every found face\n\tfaceDetected = False\n\tfor (x,y,w,h) in faces:\n\t\tfaceDetected = True\n\t\t# Create rectangle around the face\n\t\tcv2.rectangle(image,(x,y),(x+w,y+h),(255,255,0),2)\n\t\t# Save this in the dictionary\n\t\tcx = x + w/2\n\t\tcy = y + h/2\n\t\tface_dict['location'].append([x, y, w, h, cx, cy])\n\t\tface_dict['time'].append(time.time())\n\t# Connect last __ frames with a blue line\n\tif len(face_dict['location']) >= framesToPlot:\n\t\tcenter_pts = np.zeros((framesToPlot, 2), np.int32)\n\t\tfor i in range(framesToPlot):\n\t\t\tcenter_pts[i][0] = face_dict['location'][len(face_dict['location'])-i-1][4]\n\t\t\tcenter_pts[i][1] = face_dict['location'][len(face_dict['location'])-i-1][5]\n\t\tcenter_pts = center_pts.reshape((-1,1,2))\n\t\tcv2.polylines(image,[center_pts],False,(255,0,0),5)\n\t# Show the frame\n\tcv2.imshow('Frame',image)\n\t# Wait for key\n\tkey = cv2.waitKey(1) & 0xFF\n\t# clear the stream in preparation for the next frame\n\trawCapture.truncate(0)\n\t\n\t### *** GET VELOCITY *** ###\n\tif len(face_dict['location']) > 1 and faceDetected:\n\t\t[x, y] = [face_dict['location'][-1][4], face_dict['location'][-1][5]]\n\t\tt = face_dict['time'][-1]\n\t\t[x0, y0] = [face_dict['location'][-2][4], face_dict['location'][-2][5]]\n\t\tt0 = face_dict['time'][-2]\n\t\tv_x = (x-x0)/(t-t0)\n\t\tv_y = (y-y0)/(t-t0)\n\t\tface_dict['velocity'].append([v_x, v_y])\n\t\n\t### *** TIME-OUT AFTER A CERTAIN TIME *** ###\n\tcurrent_time = time.time()\n\tif current_time-start_time > time_out:\n\t\tbreak\n\n# Print for debugging\nfor key, value in face_dict.items():\n\tprint(key, '->', value)\n\ncv2.destroyAllWindows()\n","sub_path":"code/Ball_Recognition/track_face.py","file_name":"track_face.py","file_ext":"py","file_size_in_byte":2796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"341516525","text":"from functools import partial\nfrom os import path\nfrom typing import Dict, List, Union\n\nfrom dagit.templates.playground import TEMPLATE\nfrom dagster import DagsterInstance\nfrom dagster import __version__ as dagster_version\nfrom dagster.cli.workspace.cli_target import get_workspace_process_context_from_kwargs\nfrom dagster.core.workspace.context import WorkspaceProcessContext\nfrom dagster_graphql import __version__ as dagster_graphql_version\nfrom dagster_graphql.schema import create_schema\nfrom graphene import Schema\nfrom graphql.error import format_error as format_graphql_error\nfrom starlette import status\nfrom starlette.applications import Starlette\nfrom starlette.concurrency import run_in_threadpool\nfrom starlette.datastructures import QueryParams\nfrom starlette.requests import Request\nfrom starlette.responses import FileResponse, HTMLResponse, JSONResponse, PlainTextResponse\nfrom starlette.routing import Mount, Route\nfrom starlette.staticfiles import StaticFiles\n\nfrom .version import __version__\n\nROOT_ADDRESS_STATIC_RESOURCES = [\n \"/manifest.json\",\n \"/favicon.ico\",\n \"/favicon.png\",\n \"/asset-manifest.json\",\n \"/robots.txt\",\n \"/favicon_failed.ico\",\n \"/favicon_pending.ico\",\n \"/favicon_success.ico\",\n]\n\n\nasync def dagit_info_endpoint(_request):\n return JSONResponse(\n {\n \"dagit_version\": __version__,\n \"dagster_version\": dagster_version,\n \"dagster_graphql_version\": dagster_graphql_version,\n }\n )\n\n\nasync def graphql_http_endpoint(\n schema: Schema,\n process_context: WorkspaceProcessContext,\n app_path_prefix: str,\n request: Request,\n):\n \"\"\"\n fork of starlette GraphQLApp to allow for\n * our context type (crucial)\n * our GraphiQL playground (could change)\n \"\"\"\n\n if request.method == \"GET\":\n # render graphiql\n if \"text/html\" in request.headers.get(\"Accept\", \"\"):\n text = TEMPLATE.replace(\"{{ app_path_prefix }}\", app_path_prefix)\n return HTMLResponse(text)\n\n data: Union[Dict[str, str], QueryParams] = request.query_params\n\n elif request.method == \"POST\":\n content_type = request.headers.get(\"Content-Type\", \"\")\n\n if \"application/json\" in content_type:\n data = await request.json()\n elif \"application/graphql\" in content_type:\n body = await request.body()\n text = body.decode()\n data = {\"query\": text}\n elif \"query\" in request.query_params:\n data = request.query_params\n else:\n return PlainTextResponse(\n \"Unsupported Media Type\",\n status_code=status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,\n )\n\n else:\n return PlainTextResponse(\n \"Method Not Allowed\", status_code=status.HTTP_405_METHOD_NOT_ALLOWED\n )\n\n if \"query\" not in data:\n return PlainTextResponse(\n \"No GraphQL query found in the request\",\n status_code=status.HTTP_400_BAD_REQUEST,\n )\n\n query = data[\"query\"]\n variables = data.get(\"variables\")\n operation_name = data.get(\"operationName\")\n\n # context manager? scoping?\n context = process_context.create_request_context()\n\n result = await run_in_threadpool( # threadpool = aio event loop\n schema.execute,\n query,\n variables=variables,\n operation_name=operation_name,\n context=context,\n )\n\n error_data = [format_graphql_error(err) for err in result.errors] if result.errors else None\n response_data = {\"data\": result.data}\n if error_data:\n response_data[\"errors\"] = error_data\n status_code = status.HTTP_400_BAD_REQUEST if result.errors else status.HTTP_200_OK\n\n return JSONResponse(response_data, status_code=status_code)\n\n\ndef index_endpoint(\n base_dir: str,\n app_path_prefix: str,\n _request: Request,\n):\n \"\"\"\n Serves root html\n \"\"\"\n index_path = path.join(base_dir, \"./webapp/build/index.html\")\n\n try:\n with open(index_path) as f:\n rendered_template = f.read()\n return HTMLResponse(\n rendered_template.replace('href=\"/', f'href=\"{app_path_prefix}/')\n .replace('src=\"/', f'src=\"{app_path_prefix}/')\n .replace(\"__PATH_PREFIX__\", app_path_prefix)\n )\n except FileNotFoundError:\n raise Exception(\n \"\"\"Can't find webapp files. Probably webapp isn't built. If you are using\n dagit, then probably it's a corrupted installation or a bug. However, if you are\n developing dagit locally, your problem can be fixed as follows:\n\n cd ./python_modules/\n make rebuild_dagit\"\"\"\n )\n\n\ndef create_root_static_endpoints(base_dir: str) -> List[Route]:\n def _static_file(file_path):\n return Route(\n file_path,\n lambda _: FileResponse(path=path.join(base_dir, f\"./webapp/build{file_path}\")),\n )\n\n return [_static_file(f) for f in ROOT_ADDRESS_STATIC_RESOURCES]\n\n\ndef create_app(\n process_context: WorkspaceProcessContext,\n debug: bool,\n app_path_prefix: str,\n):\n graphql_schema = create_schema()\n base_dir = path.dirname(__file__)\n\n bound_index_endpoint = partial(index_endpoint, base_dir, app_path_prefix)\n\n return Starlette(\n debug=debug,\n routes=[\n Route(\"/dagit_info\", dagit_info_endpoint),\n Route(\n \"/graphql\",\n partial(graphql_http_endpoint, graphql_schema, process_context, app_path_prefix),\n name=\"graphql-http\",\n methods=[\"GET\", \"POST\"],\n ),\n # static resources addressed at /static/\n Mount(\n \"/static\",\n StaticFiles(directory=path.join(base_dir, \"./webapp/build/static\")),\n name=\"static\",\n ),\n # static resources addressed at /vendor/\n Mount(\n \"/vendor\",\n StaticFiles(directory=path.join(base_dir, \"./webapp/build/vendor\")),\n name=\"vendor\",\n ),\n # specific static resources addressed at /\n *create_root_static_endpoints(base_dir),\n Route(\"/{path:path}\", bound_index_endpoint),\n Route(\"/\", bound_index_endpoint),\n ],\n )\n\n\ndef default_app():\n instance = DagsterInstance.get()\n process_context = get_workspace_process_context_from_kwargs(\n instance=instance,\n version=__version__,\n read_only=False,\n kwargs={},\n )\n return create_app(process_context, app_path_prefix=\"\", debug=False)\n","sub_path":"python_modules/dagit/dagit/starlette.py","file_name":"starlette.py","file_ext":"py","file_size_in_byte":6633,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"485334543","text":"\"\"\"\nTraining methods for `LSTMModel`.\n\n@author(2021_05_10): Connor W. Colombo (colombo@cmu.edu)\n\"\"\"\nfrom typing import Optional, List, Any, Dict, Tuple, Union\nimport attr\n\nimport time\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data.sampler import SubsetRandomSampler\nfrom torch.utils.data import DataLoader\nimport matplotlib.pyplot as plt # type: ignore\nimport seaborn as sns # type: ignore\n\nfrom model import LSTMModel\nfrom data import MachiningDataset\nfrom logger import logger\nfrom opts import get_opts\n\nopts = get_opts()\n\n\n@attr.s(frozen=True, cmp=True, slots=True, auto_attribs=True)\nclass TrainHyperparams:\n \"\"\"Collection of tunable hyperparameters for the training process.\"\"\"\n # Number of training epochs:\n num_epochs: int\n # Adam learning rate:\n lr: float\n # Batch size:\n batch_size: int\n # Proportion of total dataset which should be used for validation:\n validation_split: float\n # Proportion of total dataset which should be used for final testing:\n test_split: float\n # Which channel number to start forecasting at:\n channel_forecast_start: int\n # How many channels to step by when increasing forecast distance:\n channel_forecast_step: int\n\n\ndef train(\n model: LSTMModel,\n dataset: MachiningDataset,\n random_seed: int = 42,\n hyperparams: Optional[TrainHyperparams] = None\n) -> LSTMModel:\n \"\"\"\n Trains the given `LSTMModel` `model` on the given `data` and returns the trained model.\n \"\"\"\n if hyperparams is None:\n hyperparams = TrainHyperparams(\n num_epochs=opts.num_epochs,\n lr=opts.lr,\n batch_size=opts.batch_size,\n validation_split=opts.validation_split,\n test_split=opts.test_split,\n channel_forecast_start=opts.channel_forecast_start,\n channel_forecast_step=opts.channel_forecast_step\n )\n\n dataset_size = len(dataset)\n\n if hyperparams.batch_size > dataset_size:\n raise ValueError(\n f\"Batch size ({hyperparams.batch_size}) can't be greater than \"\n f\"total number of examples in dataset ({dataset_size}).\"\n )\n\n if (hyperparams.validation_split + hyperparams.test_split) >= 1.0:\n raise ValueError(\n f\"Validation split ({hyperparams.validation_split * 100:3.1f}%) \"\n f\"and test split ({hyperparams.test_split * 100:3.1f}%) \"\n f\"can't add up to >= 100% since there has to be samples left over \"\n f\"for training (ideally >50% for training).\"\n )\n if (hyperparams.validation_split + hyperparams.test_split) > 0.5:\n logger.warning(\n f\"Validation split ({hyperparams.validation_split * 100:3.1f}%) \"\n f\"and test split ({hyperparams.test_split * 100:3.1f}%) \"\n f\"currently add up to {(hyperparams.validation_split + hyperparams.test_split) * 100:3.1f}%. \"\n f\"Ideally, they should add up to less than 50% so most of the data will be used for training. \"\n )\n\n # Creating data indices for training and validation splits:\n indices = [*range(dataset_size)]\n\n splits = [\n int(hyperparams.validation_split * dataset_size),\n int((hyperparams.validation_split + hyperparams.test_split) * dataset_size)\n ]\n np.random.seed(random_seed)\n np.random.shuffle(indices)\n val_indices = indices[:splits[0]]\n test_indices = indices[splits[0]:splits[1]]\n train_indices = indices[splits[1]:]\n\n if len(val_indices) < 2 or len(test_indices) < 2 or len(train_indices) < 2:\n raise ValueError(\n \"Dataset is partitioned poorly. Testing, Validation, and Training \"\n \"should each have at least two examples (ideally a lot more) but \"\n f\"instead dataset contains {len(dataset)} `DataExample`s split into: \"\n f\"{(1 - hyperparams.validation_split - hyperparams.test_split) * 100:3.1f}% = {len(train_indices)} for training, \"\n f\"{hyperparams.validation_split * 100:3.1f}% = {len(val_indices)} for validation, \"\n f\"and {hyperparams.test_split * 100:3.1f}% = {len(test_indices)} for final testing.\"\n )\n\n logger.verbose( # type: ignore\n f\"Dataset contains {len(dataset)} `DataExample`s split into: \"\n f\"{(1 - hyperparams.validation_split - hyperparams.test_split) * 100:3.1f}% = {len(train_indices)} for training, \"\n f\"{hyperparams.validation_split * 100:3.1f}% = {len(val_indices)} for validation, \"\n f\"and {hyperparams.test_split * 100:3.1f}% = {len(test_indices)} for final testing.\"\n )\n\n # Creating PT data samplers and loaders:\n train_loader = DataLoader(\n dataset,\n batch_size=hyperparams.batch_size,\n sampler=SubsetRandomSampler(train_indices)\n )\n val_loader = DataLoader(\n dataset,\n batch_size=hyperparams.batch_size,\n sampler=SubsetRandomSampler(val_indices)\n )\n test_loader = DataLoader(\n dataset,\n batch_size=hyperparams.batch_size,\n sampler=SubsetRandomSampler(test_indices)\n )\n device = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n print(\"Device:\", device)\n # model=model.to(device)\n # Setup:\n criterion = nn.MSELoss()\n optimizer = optim.Adam(model.parameters(), lr=hyperparams.lr)\n\n logger.info(\"Beginning training . . .\")\n\n for epoch in range(hyperparams.num_epochs):\n epoch_start_time = time.time() # record run TIME\n\n # Run over training data:\n for batch_idx, ex in enumerate(train_loader):\n stack = ex['stack']\n num_in_batch = len(ex['spindle_speed'])\n for j in range(num_in_batch):\n total_num_channels = stack['signalAE'][j].shape[0]\n channel_nums = [*range(total_num_channels)]\n\n start = hyperparams.channel_forecast_start\n step = hyperparams.channel_forecast_step\n stop = total_num_channels - step # leave one more step to forecast\n\n for tillChannelN in channel_nums[start:stop:step]:\n input1 = stack['signalAE'][j]\n input1.to(device)\n input2 = stack['signalMic'][j].cuda()\n input2.to(device)\n input3 = stack['signalForces'][j].cuda()\n input3.to(device)\n input4 = torch.tensor(tillChannelN).cuda()\n input4.to(device)\n model.to(device)\n outputs = model.forward(input1, input2, input3, input4)\n # OutputForceY.size() torch.Size([1, 125])\n loss = criterion(\n outputs.double().flatten().to(device),\n stack['signalFy'][j][tillChannelN + step, :].to(device)\n )\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # ! TODO: Test against validation set\n\n epoch_end_time = time.time()\n logger.verbose( # type: ignore\n f\"Epoch [{epoch}/{hyperparams.num_epochs - 1}]: {(epoch_end_time - epoch_start_time):5.1f}s \\t \"\n f\"— Training Loss: {loss.item()} \\t\"\n f\"— Validation Loss: NaN \\t\"\n )\n\n # ! TODO: Plot loss against train and validation sets over training\n\n # ! TODO: Test against test set holdout after training\n\n # Plot Results for end of validation:\n sns.set_theme()\n plt.figure()\n\n y_pred = outputs.squeeze(dim=0).detach().numpy()\n y_real = stack['signalFy'][j][tillChannelN + step, :].numpy()\n plt.plot(np.linspace(0, 360, y_pred.size), y_pred)\n plt.plot(np.linspace(0, 360, y_real.size), y_real)\n\n plt.xlabel('Bit Rotation Angle [deg]')\n plt.ylabel('Normalized Force')\n plt.legend(('Prediction', 'Real'))\n plt.title(f'LSTM Force Prediction for Channel {tillChannelN + step}')\n plt.show()\n\n return model\n","sub_path":"model_v1/train_failed_try_w_gpu.py","file_name":"train_failed_try_w_gpu.py","file_ext":"py","file_size_in_byte":7975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"408501891","text":"\"\"\"\nClasses for interfacing with the KBase relation engine database, specifically with graphs that\nare versioned with batch time travelling (see\nhttps://github.com/kbaseIncubator/relation_engine_incubator/blob/master/delta_load_algorithm.md)\n\nThe classes and methods here were created for the purpose of supporting the graph delta loader, but\nmore classes and methods can be added as needed.\n\n\"\"\"\n\n# TODO CODE check id, from, and to for validity per\n# https://www.arangodb.com/docs/stable/data-modeling-naming-conventions-document-keys.html\n\nfrom arango.exceptions import AQLQueryExecuteError as _AQLQueryExecuteError\nfrom arango.exceptions import DocumentDeleteError as _DocumentDeleteError\n\n_INTERNAL_ARANGO_FIELDS = ['_rev']\n\n_FLD_KEY = '_key'\n_FLD_FULL_ID = '_id'\n_FLD_ID = 'id'\n\n_FLD_FROM = '_from'\n_FLD_FROM_ID = 'from'\n_FLD_TO = '_to'\n_FLD_TO_ID = 'to'\n\n_FLD_VER_LST = 'last_version'\n_FLD_VER_FST = 'first_version'\n_FLD_CREATED = 'created'\n_FLD_EXPIRED = 'expired'\n_FLD_RELEASE_CREATED = 'release_created'\n_FLD_RELEASE_EXPIRED = 'release_expired'\n\n_FLD_RGSTR_LOAD_NAMESPACE = 'load_namespace'\n_FLD_RGSTR_LOAD_VERSION = 'load_version'\n_FLD_RGSTR_LOAD_TIMESTAMP = 'load_timestamp'\n_FLD_RGSTR_LOAD_RELEASE_TIMESTAMP = 'release_timestamp'\n_FLD_RGSTR_VERTEX_COLLECTION = 'vertex_collection'\n_FLD_RGSTR_MERGE_COLLECTION = 'merge_collection'\n_FLD_RGSTR_EDGE_COLLECTIONS = 'edge_collections'\n_FLD_RGSTR_START_TIME = 'start_time'\n_FLD_RGSTR_COMPLETE_TIME = 'completion_time'\n_FLD_RGSTR_STATE = 'state'\n_FLD_RGSTR_STATE_IN_PROGRESS = 'in_progress'\n_FLD_RGSTR_STATE_COMPLETE = 'complete'\n_FLD_RGSTR_STATE_ROLLBACK = 'rollback'\n\n# see https://www.arangodb.com/2018/07/time-traveling-with-graph-databases/\n# in unix epoch ms this is 2255/6/5\n_MAX_ADB_INTEGER = 2**53 - 1\n\n\nclass ArangoBatchTimeTravellingDBFactory:\n \"\"\"\n This class allows for creating a time travelling database based on ArangoDB but delegating\n collection selection, other than the registry collection, to downstream processing.\n\n database - the python_arango ArangoDB database containing the data to query or modify.\n load_registry_collection - the name of the collection where loads will be listed.\n \"\"\"\n\n # may want to make this an BatchTimeTravellingDBFactory interface, but pretty unlikely we'll switch...\n\n def __init__(self, database, load_registry_collection):\n self._database = database\n # TODO CODE could check if any loads are in progress for the namespace and bail if so\n self._registry_collection = _init_collection(database, load_registry_collection)\n\n def get_registry_collection(self):\n \"\"\"\n Returns the name of the registry collection.\n \"\"\"\n return self._registry_collection.name\n\n def get_registered_loads(self, load_namespace):\n \"\"\"\n Returns all the registered loads for a namespace sorted by load timestamp from newest to\n oldest.\n\n load_namespace - the namespace of the loads to return.\n \"\"\"\n return _get_registered_loads(self._database, self._registry_collection, load_namespace)\n\n def get_instance(\n self,\n vertex_collection,\n default_edge_collection=None,\n edge_collections=None,\n merge_collection=None):\n \"\"\"\n Get a database instance configured with the given collections.\n\n The collections are checked for existence, type, and required indexes, which can be\n expensive.\n\n vertex_collection - the name of the collection to use for vertex operations.\n default_edge_collection - the name of the collection to use for edge operations by default.\n This can be overridden.\n edge_collections - a list of any edge collections in the graph.\n The collections are checked for existence and cached for performance reasons.\n merge_collection - a collection containing edges that indicate that a node has been\n merged into another node.\n \"\"\"\n return ArangoBatchTimeTravellingDB(\n self._database,\n self._registry_collection.name,\n vertex_collection,\n default_edge_collection=default_edge_collection,\n edge_collections=edge_collections,\n merge_collection=merge_collection)\n\n\nclass ArangoBatchTimeTravellingDB:\n \"\"\"\n A collection of methods for inserting and retrieving data from ArangoDB.\n \"\"\"\n\n # may want to make this an BatchTimeTravellingDBFactory interface, but pretty unlikely we'll switch...\n\n def __init__(\n self,\n database,\n load_registry_collection,\n vertex_collection,\n default_edge_collection=None,\n edge_collections=None,\n merge_collection=None):\n \"\"\"\n Create the DB interface.\n\n The collections are checked for existence, type, and required indexes, which can be\n expensive.\n\n database - the python_arango ArangoDB database containing the data to query or modify.\n load_registry_collection - the name of the collection where loads will be listed.\n vertex_collection - the name of the collection to use for vertex operations.\n default_edge_collection - the name of the collection to use for edge operations by default.\n This can be overridden.\n edge_collections - a list of any edge collections in the graph.\n The collections are checked for existence and cached for performance reasons.\n merge_collection - a collection containing edges that indicate that a node has been\n merged into another node.\n\n Specifying an edge collection in a method argument that is not in edge_collections,\n is not the default edge collection, or is not the merge collection will result in an error.\n \"\"\"\n self._database = database\n self._merge_collection = None\n if merge_collection:\n self._merge_collection = self._init_col(merge_collection, edge=True)\n self._default_edge_collection = default_edge_collection\n edgecols = set()\n if default_edge_collection:\n edgecols.add(default_edge_collection)\n if edge_collections:\n edgecols.update(edge_collections)\n if not edgecols:\n raise ValueError(\"At least one edge collection must be specified\")\n self._vertex_collection = self._init_col(vertex_collection)\n # TODO CODE could check if any loads are in progress for the namespace and bail if so\n self._registry_collection = self._init_col(load_registry_collection)\n\n self._edgecols = {n: self._init_col(n, edge=True) for n in edgecols}\n\n self._id_indexes = self._check_indexes()\n\n def _check_indexes(self):\n # check indexes and store names of required indexes\n cols = [self._vertex_collection] + list(self._edgecols.values())\n if self.get_merge_collection():\n cols.append(self._merge_collection)\n\n id_indexes = {}\n for col in cols:\n idx = col.indexes() # http request\n id_indexes[col.name] = self._get_index_name(col.name, self._ID_EXP_CRE_INDEX, idx)\n # check the other required index exists. Don't need to store it for later though\n self._get_index_name(col.name, self._EXP_CRE_LAST_VER_INDEX, idx)\n\n return id_indexes\n\n _ID_EXP_CRE_INDEX = {\n 'type': 'persistent',\n 'fields': [_FLD_ID, _FLD_EXPIRED, _FLD_CREATED],\n 'sparse': False,\n 'unique': False\n }\n\n _EXP_CRE_LAST_VER_INDEX = {\n 'type': 'persistent',\n 'fields': [_FLD_EXPIRED, _FLD_CREATED, _FLD_VER_LST],\n 'sparse': False,\n 'unique': False\n }\n\n def _get_index_name(self, col_name, index_spec, indexes):\n for idx in indexes:\n if not self._is_index_equivalent(index_spec, idx):\n continue\n return idx['name']\n raise ValueError(f'Collection {col_name} is missing required index with ' +\n f'specification {index_spec}')\n\n def _is_index_equivalent(self, index_spec, index):\n for field in index_spec:\n if index_spec[field] != index.get(field):\n return False\n return True\n\n # if an edge is inserted into a non-edge collection _from and _to are silently dropped\n def _init_col(self, collection, edge=False):\n return _init_collection(self._database, collection, edge)\n\n def get_registry_collection(self):\n \"\"\"\n Returns the name of the registry collection.\n \"\"\"\n return self._registry_collection.name\n\n def register_load_start(\n self,\n load_namespace,\n load_version,\n timestamp,\n release_timestamp,\n current_time):\n \"\"\"\n Register that a load is starting in the database.\n\n load_namespace - the unique namespace of the data set, e.g. NCBI_TAXA, GENE_ONTOLOGY,\n ENVO, etc.\n load_version - the version of the load that is unique within the namespace.\n timestamp - the timestamp in unix epoch milliseconds when the load will become active.\n release_timestamp - the timestamp in unix epoch milliseconds when the data was released\n at the source.\n current_time - the current time in unix epoch milliseconds.\n \"\"\"\n doc = {_FLD_KEY: load_namespace + '_' + load_version,\n _FLD_RGSTR_START_TIME: current_time,\n _FLD_RGSTR_LOAD_NAMESPACE: load_namespace,\n _FLD_RGSTR_LOAD_VERSION: load_version,\n _FLD_RGSTR_LOAD_TIMESTAMP: timestamp,\n _FLD_RGSTR_LOAD_RELEASE_TIMESTAMP: release_timestamp,\n _FLD_RGSTR_COMPLETE_TIME: None,\n _FLD_RGSTR_STATE: _FLD_RGSTR_STATE_IN_PROGRESS,\n _FLD_RGSTR_VERTEX_COLLECTION: self._vertex_collection.name,\n _FLD_RGSTR_MERGE_COLLECTION: self.get_merge_collection(),\n _FLD_RGSTR_EDGE_COLLECTIONS: sorted(list(self._edgecols.keys()))}\n\n try:\n self._database.aql.execute(\n 'INSERT @d in @@col',\n bind_vars={'d': doc, '@col': self._registry_collection.name}\n )\n except _AQLQueryExecuteError as e:\n if e.error_code == 1210:\n raise ValueError('Load is already registered')\n raise e\n\n def register_load_complete(self, load_namespace, load_version, current_time):\n \"\"\"\n Register that a load has completed in the database.\n\n load_namespace - the unique namespace of the data set, e.g. NCBI_TAXA, GENE_ONTOLOGY,\n ENVO, etc.\n load_version - the version of the load that is unique within the namespace.\n current_time - the current time in unix epoch milliseconds.\n \"\"\"\n doc = {_FLD_KEY: load_namespace + '_' + load_version,\n _FLD_RGSTR_COMPLETE_TIME: current_time,\n _FLD_RGSTR_STATE: _FLD_RGSTR_STATE_COMPLETE}\n\n try:\n self._database.aql.execute(\n 'UPDATE @d in @@col',\n bind_vars={'d': doc, '@col': self._registry_collection.name}\n )\n except _AQLQueryExecuteError as e:\n if e.error_code == 1202:\n raise ValueError('Load is not registered, cannot be completed')\n raise e\n\n def register_load_rollback(self, load_namespace, load_version):\n \"\"\"\n Register that a load is in the process of being rolled back.\n\n load_namespace - the unique namespace of the data set, e.g. NCBI_TAXA, GENE_ONTOLOGY,\n ENVO, etc.\n load_version - the version of the load that is unique within the namespace.\n \"\"\"\n doc = {_FLD_KEY: load_namespace + '_' + load_version,\n _FLD_RGSTR_STATE: _FLD_RGSTR_STATE_ROLLBACK}\n\n try:\n self._database.aql.execute(\n 'UPDATE @d in @@col',\n bind_vars={'d': doc, '@col': self._registry_collection.name}\n )\n # could combine some of this code with the above method... meh\n except _AQLQueryExecuteError as e:\n if e.error_code == 1202:\n raise ValueError('Load is not registered, cannot be rolled back')\n raise e\n\n def get_registered_loads(self, load_namespace):\n \"\"\"\n Returns all the registered loads for a namespace sorted by load timestamp from newest to\n oldest.\n\n load_namespace - the namespace of the loads to return.\n \"\"\"\n return _get_registered_loads(self._database, self._registry_collection, load_namespace)\n\n def delete_registered_load(self, load_namespace, load_version):\n \"\"\"\n Deletes a load from the registry.\n \"\"\"\n try:\n self._registry_collection.delete({_FLD_KEY: load_namespace + '_' + load_version})\n except _DocumentDeleteError as e:\n if e.error_code == 1202:\n raise ValueError(f'There is no load version {load_version} ' +\n f'in namespace {load_namespace}')\n\n def get_vertex_collection(self):\n \"\"\"\n Returns the name of the vertex collection.\n \"\"\"\n return self._vertex_collection.name\n\n def get_default_edge_collection(self):\n \"\"\"\n Returns the name of the default edge collection or None.\n \"\"\"\n return self._default_edge_collection\n\n def get_edge_collections(self):\n \"\"\"\n Returns the names of all the registered edge collections as a list, including the default\n edge collection, if any. Does not include the merge collection.\n \"\"\"\n return sorted(list(self._edgecols.keys()))\n\n def get_merge_collection(self):\n \"\"\"\n Return the name of the merge collection or None if no merge collection was registered.\n \"\"\"\n # for some reason is None works, just a check doesn't\n return None if self._merge_collection is None else self._merge_collection.name\n\n def get_vertices(self, ids, timestamp):\n \"\"\"\n Get vertices that exist at the given timestamp from a collection.\n\n A vertex ID and a timestamp uniquely identifies a vertex in a collection.\n\n ids - the IDs of the vertices to get.\n timestamp - the time at which the vertices must exist in Unix epoch milliseconds.\n\n Returns a dict of vertex ID -> vertex. Missing vertices are not included and do not\n cause an error.\n \"\"\"\n col_name = self._vertex_collection.name\n return self._get_documents(ids, timestamp, col_name)\n\n def _get_documents(self, ids, timestamp, collection_name):\n id_idx = self._id_indexes[collection_name]\n cur = self._database.aql.execute(\n f\"\"\"\n FOR d IN @@col\n OPTIONS {{indexHint: @id_idx, forceIndexHint: true}}\n FILTER d.{_FLD_ID} IN @ids\n FILTER d.{_FLD_EXPIRED} >= @timestamp AND d.{_FLD_CREATED} <= @timestamp\n RETURN d\n \"\"\",\n bind_vars={'ids': ids, 'timestamp': timestamp, '@col': collection_name, 'id_idx': id_idx}\n )\n ret = {}\n try:\n for d in cur:\n if d[_FLD_ID] in ret:\n raise ValueError(f'db contains > 1 document for id {d[_FLD_ID]}, ' +\n f'timestamp {timestamp}, collection {collection_name}')\n ret[d[_FLD_ID]] = _clean(d)\n finally:\n cur.close(ignore_missing=True)\n return ret\n\n def get_edges(self, ids, timestamp, edge_collection=None):\n \"\"\"\n Get edges that exist at the given timestamp from a collection.\n\n An edge ID and a timestamp uniquely identifies an edge in a collection.\n\n ids - the IDs of the edges to get.\n timestamp - the time at which the edges must exist in Unix epoch milliseconds.\n edge_collection - the collection name to query. If none is provided, the default will\n be used.\n\n Returns a dict of edge ID -> edge. Missing edges are not included and do not\n cause an error.\n \"\"\"\n col_name = self._get_edge_collection(edge_collection).name\n return self._get_documents(ids, timestamp, col_name)\n\n # may need to separate timestamp into find and expire timestamps, but YAGNI for now\n def expire_extant_vertices_without_last_version(self, timestamp, release_timestamp, version):\n \"\"\"\n Expire all vertices that exist at the given timestamp where the last version field is\n not equal to the given version. The expiration date will be the given timestamp.\n\n timestamp - the timestamp to use to find extant vertices as well as the timestamp to use\n as the expiration date in Unix epoch milliseconds.\n release_timestamp - the timestamp to use as the expiration date at the data source\n in Unix epoch milliseconds.\n version - the version required for the last version field for a vertex to avoid expiration.\n \"\"\"\n col = self._vertex_collection\n self._expire_extant_document_without_last_version(\n timestamp, release_timestamp, version, col)\n\n # may need to separate timestamp into find and expire timestamps, but YAGNI for now\n def expire_extant_edges_without_last_version(\n self,\n timestamp,\n release_timestamp,\n version,\n edge_collection=None):\n \"\"\"\n Expire all edges that exist at the given timestamp where the last version field is\n not equal to the given version. The expiration date will be the given timestamp.\n\n timestamp - the timestamp to use to find extant edges as well as the timestamp to use\n as the expiration date.\n release_timestamp - the timestamp to use as the expiration date at the data source\n in Unix epoch milliseconds.\n version - the version required for the last version field for a edges to avoid expiration.\n edge_collection - the collection name to query. If none is provided, the default will\n be used.\n \"\"\"\n col = self._get_edge_collection(edge_collection)\n self._expire_extant_document_without_last_version(\n timestamp, release_timestamp, version, col)\n\n def _expire_extant_document_without_last_version(\n self,\n timestamp,\n release_timestamp,\n version,\n col):\n self._database.aql.execute(\n f\"\"\"\n FOR d IN @@col\n FILTER d.{_FLD_EXPIRED} >= @timestamp && d.{_FLD_CREATED} <= @timestamp\n FILTER d.{_FLD_VER_LST} != @version\n UPDATE d WITH {{{_FLD_EXPIRED}: @timestamp, {_FLD_RELEASE_EXPIRED}: @reltimestamp}}\n IN @@col\n \"\"\",\n bind_vars={\n 'version': version,\n 'timestamp': timestamp,\n 'reltimestamp': release_timestamp,\n '@col': col.name},\n )\n\n # TODO PERF could add created index to speed this up\n def delete_created_documents(self, collection, creation_time):\n \"\"\"\n Deletes any documents in the collection that were created at the given time.\n\n collection - the collection to modify.\n creation_time - the time of creation, in unix epoch milliseconds, of the documents to\n delete.\n \"\"\"\n col = self._get_collection(collection) # ensure collection exists\n self._database.aql.execute(\n f\"\"\"\n FOR d IN @@col\n FILTER d.{_FLD_CREATED} == @timestamp\n REMOVE d IN @@col\n \"\"\",\n bind_vars={'timestamp': creation_time, '@col': col.name},\n )\n\n def undo_expire_documents(self, collection, expire_time):\n \"\"\"\n Unexpires any documents that were expired at the given time.\n\n collection - the collection to modify\n expire_time - the time of expiration, in unix epoch milliseconds, of the documents to\n un-expire.\n \"\"\"\n col = self._get_collection(collection) # ensure collection exists\n self._database.aql.execute(\n f\"\"\"\n FOR d IN @@col\n FILTER d.{_FLD_EXPIRED} == @timestamp\n UPDATE d WITH {{\n {_FLD_EXPIRED}: {_MAX_ADB_INTEGER},\n {_FLD_RELEASE_EXPIRED}: {_MAX_ADB_INTEGER}\n }} IN @@col\n \"\"\",\n bind_vars={'timestamp': expire_time, '@col': col.name},\n )\n\n # TODO PERF could add last_version index to speed this up\n def reset_last_version(self, collection, last_version, new_last_version):\n \"\"\"\n Updates documents from one last version to another. Only documents with the given last\n version are affected.\n\n collection - the collection to modify\n last_version - any documents with this last_version will be modified.\n new_last_version - the documents will be modified to this last version.\n \"\"\"\n col = self._get_collection(collection) # ensure collection exists\n self._database.aql.execute(\n f\"\"\"\n FOR d IN @@col\n FILTER d.{_FLD_VER_LST} == @last_version\n UPDATE d WITH {{{_FLD_VER_LST}: @new_last}} IN @@col\n \"\"\",\n bind_vars={\n 'last_version': last_version,\n 'new_last': new_last_version,\n '@col': col.name},\n )\n\n def _get_collection(self, collection):\n if self._vertex_collection.name == collection:\n return self._vertex_collection\n # again doesn't work without the is not None part. Dunno why.\n if self._merge_collection is not None and collection == self._merge_collection.name:\n return self._merge_collection\n if collection not in self._edgecols:\n raise ValueError(f'Collection {collection} was not registered at initialization')\n return self._edgecols[collection]\n\n def _get_edge_collection(self, collection):\n if not collection:\n if not self._default_edge_collection:\n raise ValueError('No default edge collection specified, ' +\n 'must specify edge collection')\n return self._edgecols[self._default_edge_collection]\n # again doesn't work without the is not None part. Dunno why.\n if self._merge_collection is not None and collection == self._merge_collection.name:\n return self._merge_collection\n if collection not in self._edgecols:\n raise ValueError(f'Edge collection {collection} was not registered at initialization')\n return self._edgecols[collection]\n\n def get_batch_updater(self, edge_collection_name=None):\n \"\"\"\n Get a batch updater for a collection. Updates can be added to the updater and then\n applied at once.\n\n edge_collection_name - the name of the edge collection that will be updated. If not\n provided the vertex collection is used.\n\n Returns a BatchUpdater.\n \"\"\"\n if not edge_collection_name:\n return BatchUpdater(self._vertex_collection, False)\n return BatchUpdater(self._get_edge_collection(edge_collection_name), True)\n\n\nclass BatchUpdater:\n\n def __init__(self, collection, edge=False):\n \"\"\"\n Do not create this class directly - call ArangoBatchTimeTravellingDB.get_batch_updater().\n\n This class is not thread safe.\n\n Create a batch updater.\n\n collection - the python-arango collection where updates will be applied.\n edge - True if the collection is an edge collection. Checking this property requires\n an http call, and so providing the type is required.\n\n Properties:\n is_edge - True if the updater will update against an edge collection, false otherwise.\n \"\"\"\n self._col = collection\n self.is_edge = edge\n self._updates = []\n\n def get_collection(self):\n \"\"\"\n Return the name of the collection to which updates will be applied.\n \"\"\"\n return self._col.name\n\n def create_vertex(self, id_, version, created_time, release_time, data):\n \"\"\"\n Save a vertex in the database.\n\n Note that only a shallow copy of the data is made before adding database fields. Modifying\n embedded data structures may have unexpected results.\n\n The _key field is generated from the id_ and version fields, which are expected to uniquely\n identify a vertex.\n\n id_ - the external ID of the vertex.\n version - the version of the load as part of which the vertex is being created.\n created_time - the time at which the vertex should begin to exist in Unix epoch\n milliseconds.\n release_time - the time at which the vertex was released at the data source in Unix epoch\n milliseconds.\n data - the vertex contents as a dict.\n\n Returns the key for the vertex.\n \"\"\"\n self._ensure_vertex()\n vert = _create_vertex(data, id_, version, created_time, release_time)\n self._updates.append(vert)\n return vert[_FLD_KEY]\n\n def create_edge(\n self,\n id_,\n from_vertex,\n to_vertex,\n version,\n created_time,\n release_time,\n data=None):\n \"\"\"\n Save an edge in the database.\n\n Note that only a shallow copy of the data is made before adding database fields. Modifying\n embedded data structures may have unexpected results.\n\n The _key field is generated from the id_ and version fields, which are expected to uniquely\n identify an edge.\n\n id_ - the external ID of the edge.\n from_vertex - the vertex where the edge originates. This vertex must have been fetched from\n the database.\n to_vertex - the vertex where the edge terminates. This vertex must have been fetched from\n the database.\n version - the version of the load as part of which the edge is being created.\n created_time - the time at which the edge should begin to exist in Unix epoch milliseconds.\n release_time - the time at which the edge was released at the data source in Unix epoch\n milliseconds.\n data - the edge contents as a dict.\n\n Returns the key for the edge.\n \"\"\"\n self._ensure_edge()\n edge = _create_edge(id_, from_vertex, to_vertex, version, created_time, release_time, data)\n self._updates.append(edge)\n return edge[_FLD_KEY]\n\n def set_last_version_on_vertex(self, key, last_version):\n \"\"\"\n Set the last version field on a vertex.\n\n key - the key of the vertex.\n last_version - the version to set.\n \"\"\"\n self._ensure_vertex()\n self._updates.append({_FLD_KEY: key, _FLD_VER_LST: last_version})\n\n def set_last_version_on_edge(self, edge, last_version):\n \"\"\"\n Set the last version field on an edge.\n\n edge - the edge to update. This must have been fetched from the database.\n last_version - the version to set.\n \"\"\"\n self._update_edge(edge, {_FLD_VER_LST: last_version})\n\n def _update_edge(self, edge, update):\n self._ensure_edge()\n update[_FLD_KEY] = edge[_FLD_KEY]\n # this is really lame. Arango requires the _to and _from edges even when the\n # document you're updating already has them.\n update[_FLD_FROM] = edge[_FLD_FROM]\n update[_FLD_TO] = edge[_FLD_TO]\n self._updates.append(update)\n\n def expire_vertex(self, key, expiration_time, release_expiration_time):\n \"\"\"\n Sets the expiration time on a vertex.\n\n key - the vertex key.\n expiration_time - the time, in Unix epoch milliseconds, to set as the expiration time\n on the vertex.\n release_expiration_time - the time, in Unix epoch milliseconds, when the vertex was\n expired at the data source.\n \"\"\"\n self._ensure_vertex()\n self._updates.append({\n _FLD_KEY: key,\n _FLD_EXPIRED: expiration_time,\n _FLD_RELEASE_EXPIRED: release_expiration_time})\n\n def expire_edge(self, edge, expiration_time, release_expiration_time):\n \"\"\"\n Sets the expiration time on an edge.\n\n edge - the edge to update. This must have been fetched from the database.\n expiration_time - the time, in Unix epoch milliseconds, to set as the expiration time\n on the edge.\n release_expiration_time - the time, in Unix epoch milliseconds, when the edge was expired\n at the data source.\n \"\"\"\n self._update_edge(edge, {\n _FLD_EXPIRED: expiration_time,\n _FLD_RELEASE_EXPIRED: release_expiration_time})\n\n def update(self):\n \"\"\"\n Apply the updates collected so far and clear the update list.\n \"\"\"\n self._col.import_bulk(self._updates, on_duplicate=\"update\")\n self._updates.clear()\n\n def count(self):\n \"\"\"\n Get the number of pending updates.\n \"\"\"\n return len(self._updates)\n\n def _ensure_vertex(self):\n if self.is_edge:\n raise ValueError('Batch updater is configured for an edge collection')\n\n def _ensure_edge(self):\n if not self.is_edge:\n raise ValueError('Batch updater is configured for a vertex collection')\n\n\ndef _create_vertex(data, id_, version, created_time, release_time):\n data = dict(data) # make a copy and overwrite the old data variable\n data[_FLD_KEY] = id_ + '_' + version\n data[_FLD_ID] = id_\n data[_FLD_VER_FST] = version\n data[_FLD_VER_LST] = version\n data[_FLD_CREATED] = created_time\n data[_FLD_EXPIRED] = _MAX_ADB_INTEGER\n data[_FLD_RELEASE_CREATED] = release_time\n data[_FLD_RELEASE_EXPIRED] = _MAX_ADB_INTEGER\n\n return data\n\n\ndef _create_edge(\n id_,\n from_vertex,\n to_vertex,\n version,\n created_time,\n release_time,\n data):\n data = {} if not data else data\n\n data = dict(data) # make a copy and overwrite the old data variable\n data[_FLD_KEY] = id_ + '_' + version\n data[_FLD_ID] = id_\n data[_FLD_FROM] = from_vertex[_FLD_FULL_ID]\n data[_FLD_FROM_ID] = from_vertex[_FLD_ID]\n data[_FLD_TO] = to_vertex[_FLD_FULL_ID]\n data[_FLD_TO_ID] = to_vertex[_FLD_ID]\n data[_FLD_VER_FST] = version\n data[_FLD_VER_LST] = version\n data[_FLD_CREATED] = created_time\n data[_FLD_EXPIRED] = _MAX_ADB_INTEGER\n data[_FLD_RELEASE_CREATED] = release_time\n data[_FLD_RELEASE_EXPIRED] = _MAX_ADB_INTEGER\n return data\n\n# if an edge is inserted into a non-edge collection _from and _to are silently dropped\n\n\ndef _init_collection(database, collection, edge=False):\n c = database.collection(collection)\n if not c.properties()['edge'] is edge: # this is a http call\n ctype = 'an edge' if edge else 'a vertex'\n raise ValueError(f'{collection} is not {ctype} collection')\n return c\n\n# mutates in place!\n\n\ndef _clean(obj):\n for k in _INTERNAL_ARANGO_FIELDS:\n del obj[k]\n return obj\n\n# TODO DOCS document fields\n# probably few enough of these that indexes aren't needed\n\n\ndef _get_registered_loads(database, registry_collection, load_namespace):\n cur = database.aql.execute(\n f\"\"\"\n FOR d in @@col\n FILTER d.{_FLD_RGSTR_LOAD_NAMESPACE} == @load_namespace\n SORT d.{_FLD_RGSTR_LOAD_TIMESTAMP} DESC\n return d\n \"\"\",\n bind_vars={'load_namespace': load_namespace, '@col': registry_collection.name}\n )\n return [_clean(d) for d in cur]\n","sub_path":"relation_engine/batchload/time_travelling_database.py","file_name":"time_travelling_database.py","file_ext":"py","file_size_in_byte":31827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"226657251","text":"import os,PyPDF2,random\ndef encrypt():\n for fname in fileinfo:\n n=random.randint(0,len(content))\n print('Đã chọn '+content[n].strip()+' là 1 mật khẩu')\n pdfobj=PyPDF2.PdfFileReader(open(fname,'rb'))\n pdfwriter=PyPDF2.PdfFileWriter()\n # giữa\n for Pnum in range(0,pdfobj.numPages):\n pdfobjP=pdfobj.getPage(Pnum)\n pdfwriter.addPage(pdfobjP)\n # kết\n pdfwriter.encrypt(content[n].strip())\n resultname=os.path.join(dirname,'encrypted'+fname)\n pdfresult=open(resultname,'wb')\n pdfwriter.write(pdfresult)\n pdfresult.close()\ndef decrypt():\n for fname in fileinfo2:\n pdfobj=PyPDF2.PdfFileReader(open(fname,'rb'))\n pdfwriter=PyPDF2.PdfFileWriter()\n # giữa\n for n in range(0,len(content)):\n if pdfobj.decrypt(content[n].strip())==0:\n continue\n elif pdfobj.decrypt(content[n].strip())==1:\n pdfobj.decrypt(content[n].strip())\n print(content[0].strip() + ' là mật khẩu của '+ fname)\n for Pnum in range(0,pdfobj.numPages):\n pdfobjP=pdfobj.getPage(Pnum)\n pdfwriter.addPage(pdfobjP)\n # kết\n fname=fname[8:]\n resultname=os.path.join(dirname,'decrypted'+fname)\n pdfresult=open(resultname,'wb')\n pdfwriter.write(pdfresult)\n pdfresult.close()\nprint('Mời bạn nhập vào file keys: ')\nKname=input()\nif not Kname.endswith('.txt'):\n Kname=Kname+'.txt'\nfileinfo=[]\nprint('Đang tìm các file pdf')\nfor fname in os.listdir('.'):\n if fname.endswith('.pdf'):\n fileinfo.append(fname)\ntextf=open(Kname,'r')\ncontent=textf.readlines()\nabsname=os.getcwd()\nprint('1. Mã hóa')\nprint('2. Giải mã')\nx=input()\nif x=='1':\n print('Đang setup....')\n dirname=os.path.join(absname,'file đã mã hóa')\n os.makedirs(dirname,exist_ok=True)\n encrypt()\n os.chdir(absname)\nelif x=='2':\n fileinfo2=[]\n print('Đang setup....')\n dirname=os.path.join(absname,'file đã giải mã')\n os.makedirs(dirname,exist_ok=True)\n for fname in os.listdir('.'):\n if fname.startswith('encrypted') and fname.endswith('.pdf'):\n fileinfo2.append(fname)\n decrypt()","sub_path":"encrypt.py","file_name":"encrypt.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"264896907","text":"from __future__ import absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement\n\nimport numpy\n\nfrom npspectralflight.array import atleast_nd\nfrom npspectralflight.spectral import dct_k, dct_theta, dct_matrix\n\n\nclass SpectralLSS(object):\n def __init__(self, f_func, j_func, nfreqs=1):\n self.f_func = f_func\n self.j_func = j_func\n self.nfreqs = nfreqs\n\n def calc_sens(self, u_ref, t):\n u_ref = u_ref\n t = t\n npts = len(t)\n\n k = dct_k(npts)\n theta = dct_theta(npts)\n\n \n\n\n","sub_path":"urop_qiqi/lss/spectral.py","file_name":"spectral.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"331886246","text":"\"\"\"\n该类的作用:生成随机数种子,以及设置随机数种子。\n说明:在神经网络中,参数默认是进行随机初始化的。不同的初始化参数往往会导致不同的结果,当得到比较好的结果时我们通常希望这个结果是可以复现的,\n在PyTorch中,通过设置随机数种子也可以达到这个目的。随机数种子seed确定时,模型的训练结果将始终保持一致。\n\"\"\"\n\nimport time\n\nimport numpy as np\n\nfrom rlpyt.utils.logging.console import colorize\n\nseed_ = None\n\n\ndef set_seed(seed):\n seed %= 4294967294\n global seed_\n seed_ = seed\n import random\n random.seed(seed)\n np.random.seed(seed)\n import torch\n torch.manual_seed(seed) # 为CPU设置随机种子\n torch.cuda.manual_seed(seed) # 为[当前]GPU设置随机种子(不是所有GPU)\n print(colorize(f\"using seed {seed}\", \"green\"))\n\n\ndef get_seed():\n return seed_\n\n\ndef make_seed() -> float:\n \"\"\"\n Returns a random number between [0, 10000], using timing jitter.\n\n This has a white noise spectrum and gives unique values for multiple\n simultaneous processes...some simpler attempts did not achieve that, but\n there's probably a better way.\n \"\"\"\n d: int = 10000\n t: float = time.time()\n sub1 = int(t * d) % d\n sub2 = int(t * d ** 2) % d\n s: float = 1e-3\n s_inv: float = 1. / s\n time.sleep(s * sub2 / d)\n t2: float = time.time()\n t2 = t2 - int(t2)\n t2 = int(t2 * d * s_inv) % d\n time.sleep(s * sub1 / d)\n t3: float = time.time()\n t3 = t3 - int(t3)\n t3 = int(t3 * d * s_inv * 10) % d\n return (t3 - t2) % d\n","sub_path":"rlpyt/utils/seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"587814138","text":"# -*- coding: utf-8 -*-\n\nimport unittest\nfrom jmdictconverter import getMixedRecords\n\nclass JMDictConverterTest(unittest.TestCase):\n def testKanjiKanaRecordList(self):\n word = ['御襁褓気触れ', 'お襁褓気触れ',\n 'オムツ気触れ', 'おむつかぶれ',\n 'オムツかぶれ']\n records = getMixedRecords(word)\n result = [ ('御襁褓気触れ', 'おむつかぶれ'),\n ('お襁褓気触れ', 'おむつかぶれ'),\n ('オムツ気触れ', 'おむつかぶれ'),\n ('オムツかぶれ', 'おむつかぶれ')\n ]\n self.assertEquals(records, result)\n\nif __name__ == '__main__':\n suite = unittest.TestLoader().loadTestsFromTestCase(JMDictConverterTest)\n unittest.TextTestRunner(verbosity=2).run(suite)","sub_path":"tool/test_jmdictconverter.py","file_name":"test_jmdictconverter.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"84263081","text":"'''\nEscrever um algoritmo que faça reserva de passagens aéreas de uma companhia. Além da leitura do número dos vôos e quantidade de lugares disponíveis, ler vários pedidos de reserva , constituídos do número da carteira de identidade do cliente e do número do vôo, atualizando o número de lugares disponíveis. Caso contrário avisar ao cliente da inexistencia de lugares. Indicando o fim dos pedidos de reserva, existe um passageiro cujo número da carteira de identidade é 9999. Considerar fixo e igual a 37 o numero de voos da companhia.\n\n'''\n\nnumeros_de_voos = [ 727, 442, 331, 4471, 221, 291]\nlugares_disponiveis = [ 15 , 16 , 1 , 90 , 16 , 15]\n\nidentidade_cliente = \"\"\nnumero_do_voo = 0\n\nwhile True:\n print('Voos disponiveis')\n print(numeros_de_voos)\n print(\"Lugares disponiveis\")\n print(lugares_disponiveis)\n\n print(\"\")\n\n numero_do_voo = int(input('Qual o número do voo ? '))\n identidade_cliente = input('Informe a identidade do cliente ')\n if identidade_cliente == '9999':\n break\n \n for i in range(5):\n if numero_do_voo == numeros_de_voos[i]:\n if lugares_disponiveis[i] != 0: \n print(\"reserva realizada\")\n lugares_disponiveis[i] = lugares_disponiveis[i] - 1\n else:\n print(\"Não posso fazer a reserva, Voo lotado!!\")\n print(\"\")\n print(\"\") ","sub_path":"algoritmos-resolvidos/exemplos/2.15.py","file_name":"2.15.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"461564690","text":"from pca import *\nfrom svcca import *\nfrom itertools import combinations\n\n#%% From the paper \"Similarity of Neural Networks Revisited\"\ndef _debiased_dot_product_similarity_helper(\n xty, sum_squared_rows_x, sum_squared_rows_y, squared_norm_x, squared_norm_y,\n n):\n \"\"\"Helper for computing debiased dot product similarity (i.e. linear HSIC).\"\"\"\n # This formula can be derived by manipulating the unbiased estimator from\n # Song et al. (2007).\n return (\n xty - n / (n - 2.) * sum_squared_rows_x.dot(sum_squared_rows_y)\n + squared_norm_x * squared_norm_y / ((n - 1) * (n - 2)))\n\n\ndef feature_space_linear_cka(features_x, features_y, debiased=False):\n \"\"\"Compute CKA with a linear kernel, in feature space.\n\n This is typically faster than computing the Gram matrix when there are fewer\n features than examples.\n\n Args:\n features_x: A num_examples x num_features matrix of features.\n features_y: A num_examples x num_features matrix of features.\n debiased: Use unbiased estimator of dot product similarity. CKA may still be\n biased. Note that this estimator may be negative.\n\n Returns:\n The value of CKA between X and Y.\n \"\"\"\n features_x = features_x - np.mean(features_x, 0, keepdims=True)\n features_y = features_y - np.mean(features_y, 0, keepdims=True)\n\n dot_product_similarity = np.linalg.norm(features_x.T.dot(features_y)) ** 2\n normalization_x = np.linalg.norm(features_x.T.dot(features_x))\n normalization_y = np.linalg.norm(features_y.T.dot(features_y))\n\n if debiased:\n n = features_x.shape[0]\n # Equivalent to np.sum(features_x ** 2, 1) but avoids an intermediate array.\n sum_squared_rows_x = np.einsum('ij,ij->i', features_x, features_x)\n sum_squared_rows_y = np.einsum('ij,ij->i', features_y, features_y)\n squared_norm_x = np.sum(sum_squared_rows_x)\n squared_norm_y = np.sum(sum_squared_rows_y)\n\n dot_product_similarity = _debiased_dot_product_similarity_helper(\n dot_product_similarity, sum_squared_rows_x, sum_squared_rows_y,\n squared_norm_x, squared_norm_y, n)\n normalization_x = np.sqrt(_debiased_dot_product_similarity_helper(\n normalization_x ** 2, sum_squared_rows_x, sum_squared_rows_x,\n squared_norm_x, squared_norm_x, n))\n normalization_y = np.sqrt(_debiased_dot_product_similarity_helper(\n normalization_y ** 2, sum_squared_rows_y, sum_squared_rows_y,\n squared_norm_y, squared_norm_y, n))\n\n return dot_product_similarity / (normalization_x * normalization_y)\n\n#%%\nif __name__ == \"__main__\":\n \n for start, end in [(0, 4), (4, 8), (8, 12), (12, 16)]:\n \n dfs = get_train_test(pca_option=False, start=start, end=end, num_dims=25)\n \n cka_train = []\n cka_test = []\n for comb in combinations(range(start, end), 2):\n cka_train.append(feature_space_linear_cka(dfs[0][comb[0]-start],\n dfs[0][comb[1]-start]))\n cka_test.append(feature_space_linear_cka(dfs[1][comb[0]-start],\n dfs[1][comb[1]-start]))\n \n print(\"Dataset Num:\", start, end)\n print(cka_train)\n print(cka_test)\n \n \n ","sub_path":"scripts/etc/cpk.py","file_name":"cpk.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"86440391","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# 한글처리\nfrom matplotlib import font_manager, rc\n\nfontname = font_manager.FontProperties(fname='D2Coding-Ver1.3.2-20180524-all.ttc').get_name()\nrc('font', family=fontname)\n\nebola = pd.read_csv('data/ebola.csv')\n# print(ebola)\n# ebola.info()\n# print(ebola.shape)\n# print('값의 개수\\n', ebola.count())\n# print('누락 값의 개수\\n', ebola.shape[0]-ebola.count())\n# e1 = ebola.iloc[:10, :5]\n# print(e1)\n# 누락값 처리 fillna()\n# print('지정된 값으로 변경\\n', e1.fillna(0))\n# print('누락값 전의 값으로 변경\\n', e1.fillna(method='ffill'))\n# print('누락값 후의 값으로 변경\\n', e1.fillna(method='bfill'))\n# print('누락값 양쪽에 있는 값의 평균값으로 변경\\n', e1.interpolate())\n# print('누락값이 포함된 행 삭제', e1.dropna())\n# 누락값이 포함된 연산\n# e1['tot'] = e1['Cases_Guinea']+e1['Cases_Liberia']+e1['Cases_SierraLeone']\n# print(e1)\n# e1['tot'] = e1['Cases_Guinea'].fillna(0)+e1['Cases_Liberia'].fillna(0)+e1['Cases_SierraLeone'].fillna(0)\n# # print(e1)\n# print(e1.Cases_Guinea.sum())\n# print(e1['Cases_Guinea'].sum(skipna=False)) #skipna 결측치 무시\n# print(e1.Cases_Guinea.mean())\n\n# 피벗테이블\n# data = pd.DataFrame({\n# \"도시\": [\"서울\", \"서울\", \"서울\", \"부산\", \"부산\", \"부산\", \"인천\", \"인천\" ],\n# \"연도\": [\"2015\", \"2010\", \"2005\", \"2015\", \"2010\", \"2005\", \"2015\", \"2010\" ],\n# \"인구\": [9904312, 9631482, 9762546, 3448737, 3393191, 3512547, 2890451, 2632035],\n# \"지역\": [\"수도권\", \"수도권\", \"수도권\", \"경상권\", \"경상권\", \"경상권\", \"수도권\", \"수도권\"]\n# })\n# # print(data)\n# # pivot(행인덱스로 사용할 열, 열인덱스로 사용할 열, 데이터로 사용할 열)\n# # pivot_table(데이터로 사용할 열, 행인덱스로 사용할 열, 열인덱스로 사용할 열)\n# # p1 = data.pivot('도시', '연도', '인구')\n# p1 = data.pivot_table(index='도시', columns='연도', values='인구')\n\n# # print(p1)\n# # print(type(p1))\n# # print(p1.index)\n# # print(p1.columns)\n# p2 = data.pivot_table(index=['도시','연도'], values='인구')\n# print(p2)\n\ndata2 = pd.read_excel('data\\\\판매현황.xlsx')\n# p2 = pd.pivot_table(data2, index='분류', values='판매수량')\n# p2 = pd.pivot_table(data2, index='분류', values='판매수량', aggfunc=sum) \n# # aggfunc을 지정하지 않으면 평균을 구함\n# print(p2)\n# p2 = p2.reset_index()\n# print(p2)\n\n# 교통사고\ndata = pd.read_csv('data/accidentdata.csv')\n# print(data)\n# 요일별 발생지시도별 교통사고 사망자 분석\nprint(data.columns)\np1 = data.pivot_table(index='요일', columns='발생지시도', values='사망자수', aggfunc=sum)\nprint(p1)\np1 = p1.reindex(['월','화','수','목','금','토','일'])\nplt.plot(p1)\nplt.legend(p1.columns)\nplt.show()","sub_path":"pandas7.py","file_name":"pandas7.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"618373861","text":"# -*- coding: utf-8 -*-\nimport logging\nfrom typing import Dict, Optional, Tuple, List\n\nfrom hdx.location import clean_name, get_phonetics\nfrom hdx.location.country import Country\nfrom hdx.utilities.text import multiple_replace\nfrom unidecode import unidecode\n\nlogger = logging.getLogger(__name__)\n\n\nclass AdminOne(object):\n \"\"\"AdminOne class which takes in pcodes and then maps names to those pcodes with fuzzy matching if necessary. The\n input configuration dictionary, admin_config, requires key admin1_info which is a list with values of the form:\n ::\n {'iso3': 'AFG', 'pcode': 'AF01', 'name': 'Kabul'}\n\n Various other keys are optional:\n countries_fuzzy_try are countries (iso3 codes) for which to try fuzzy matching. Default is all countries.\n admin1_name_mappings is a dictionary of mappings from name to pcode (for where fuzzy matching fails)\n admin1_name_replacements is a dictionary of textual replacements to try when fuzzy matching\n admin1_fuzzy_dont is a list of names for which fuzzy matching should not be tried\n\n Args:\n admin_config (Dict): Configuration dictionary\n phonetics (Phonetics): Phonetics object to use. Defaults to None (new instance).\n \"\"\"\n\n _admininfo = None\n pcodes = list()\n pcode_lengths = dict()\n name_to_pcode = dict()\n pcode_to_name = dict()\n pcode_to_iso3 = dict()\n\n def __init__(self, admin_config):\n # type: (Dict, object) -> None\n admin_info1 = admin_config['admin1_info']\n self.countries_fuzzy_try = admin_config.get('countries_fuzzy_try')\n self.admin1_name_mappings = admin_config.get('admin1_name_mappings', dict())\n self.admin1_name_replacements = admin_config.get('admin1_name_replacements', dict())\n self.admin1_fuzzy_dont = admin_config.get('admin1_fuzzy_dont', list())\n for row in admin_info1:\n countryiso3 = row['iso3']\n pcode = row.get('pcode')\n self.pcodes.append(pcode)\n self.pcode_lengths[countryiso3] = len(pcode)\n adm1_name = row['name']\n self.pcode_to_name[pcode] = adm1_name\n name_to_pcode = self.name_to_pcode.get(countryiso3, dict())\n name_to_pcode[unidecode(adm1_name).lower()] = pcode\n self.name_to_pcode[countryiso3] = name_to_pcode\n self.pcode_to_iso3[pcode] = countryiso3\n self.init_matches_errors()\n self.phonetics = get_phonetics()\n\n def init_matches_errors(self):\n # type: () -> None\n \"\"\"Initialise storage of fuzzy matches, ignored and errors for logging purposes\n\n Returns:\n None\n \"\"\"\n\n self.matches = set()\n self.ignored = set()\n self.errors = set()\n\n def convert_pcode_length(self, countryiso3, pcode, scrapername=None):\n # type: (str, str, Optional[str]) -> Optional[str]\n \"\"\"Standardise pcode length by country and match to an internal pcode\n\n Args:\n countryiso3 (str): Iso3 country code\n pcode (str): P code for admin one\n scrapername (Optional[str]): Name of scraper for logging purposes. Defaults to None (don't log).\n\n Returns:\n Optional[str]: Matched P code or None if no match\n \"\"\"\n if pcode in self.pcodes:\n return pcode\n pcode_length = len(pcode)\n country_pcodelength = self.pcode_lengths.get(countryiso3)\n if not country_pcodelength:\n return None\n if pcode_length == country_pcodelength or pcode_length < 4 or pcode_length > 6:\n return None\n if country_pcodelength == 4:\n pcode = '%s%s' % (Country.get_iso2_from_iso3(pcode[:3]), pcode[-2:])\n elif country_pcodelength == 5:\n if pcode_length == 4:\n pcode = '%s0%s' % (pcode[:2], pcode[-2:])\n else:\n pcode = '%s%s' % (Country.get_iso2_from_iso3(pcode[:3]), pcode[-3:])\n elif country_pcodelength == 6:\n if pcode_length == 4:\n pcode = '%s0%s' % (Country.get_iso3_from_iso2(pcode[:2]), pcode[-2:])\n else:\n pcode = '%s%s' % (Country.get_iso3_from_iso2(pcode[:2]), pcode[-3:])\n else:\n pcode = None\n if pcode in self.pcodes:\n if scrapername:\n self.matches.add((scrapername, countryiso3, pcode, self.pcode_to_name[pcode], 'pcode length conversion'))\n return pcode\n return None\n\n def fuzzy_pcode(self, countryiso3, name, scrapername=None):\n # type: (str, str, Optional[str]) -> Optional[str]\n \"\"\"Fuzzy match name to pcode\n\n Args:\n countryiso3 (str): Iso3 country code\n name (str): Name to match\n scrapername (Optional[str]): Name of scraper for logging purposes. Defaults to None (don't log).\n\n Returns:\n Optional[str]: Matched P code or None if no match\n \"\"\"\n if self.countries_fuzzy_try is not None and countryiso3 not in self.countries_fuzzy_try:\n self.ignored.add((scrapername, countryiso3))\n return None\n name_to_pcode = self.name_to_pcode.get(countryiso3)\n if not name_to_pcode:\n self.errors.add((scrapername, countryiso3))\n return None\n if name.lower() in self.admin1_fuzzy_dont:\n self.ignored.add((scrapername, countryiso3, name))\n return None\n adm1_name_lookup = clean_name(name)\n adm1_name_lookup2 = multiple_replace(adm1_name_lookup, self.admin1_name_replacements)\n pcode = name_to_pcode.get(adm1_name_lookup, name_to_pcode.get(adm1_name_lookup2))\n if not pcode:\n for map_name in name_to_pcode:\n if adm1_name_lookup in map_name:\n pcode = name_to_pcode[map_name]\n self.matches.add((scrapername, countryiso3, name, self.pcode_to_name[pcode], 'substring'))\n break\n for map_name in name_to_pcode:\n if adm1_name_lookup2 in map_name:\n pcode = name_to_pcode[map_name]\n self.matches.add((scrapername, countryiso3, name, self.pcode_to_name[pcode], 'substring'))\n break\n if not pcode:\n map_names = list(name_to_pcode.keys())\n lower_mapnames = [x.lower() for x in map_names]\n\n def al_transform_1(name):\n if name[:3] == 'al ':\n return 'ad %s' % name[3:]\n else:\n return None\n\n def al_transform_2(name):\n if name[:3] == 'al ':\n return name[3:]\n else:\n return None\n\n matching_index = self.phonetics.match(lower_mapnames, adm1_name_lookup, alternative_name=adm1_name_lookup2,\n transform_possible_names=[al_transform_1, al_transform_2])\n\n if matching_index is None:\n self.errors.add((scrapername, countryiso3, name))\n return None\n\n map_name = map_names[matching_index]\n pcode = name_to_pcode[map_name]\n self.matches.add((scrapername, countryiso3, name, self.pcode_to_name[pcode], 'fuzzy'))\n return pcode\n\n def get_pcode(self, countryiso3, name, scrapername=None):\n # type: (str, str, Optional[str]) -> Tuple[Optional[str], bool]\n \"\"\"Get pcode for a given name\n\n Args:\n countryiso3 (str): Iso3 country code\n name (str): Name to match\n scrapername (Optional[str]): Name of scraper for logging purposes. Defaults to None (don't log).\n\n Returns:\n Tuple[Optional[str], bool]: (Matched P code or None if no match, True if exact match or False if not)\n \"\"\"\n pcode = self.admin1_name_mappings.get(name)\n if pcode and self.pcode_to_iso3[pcode] == countryiso3:\n return pcode, True\n name_to_pcode = self.name_to_pcode.get(countryiso3)\n if name_to_pcode is not None:\n pcode = name_to_pcode.get(name.lower())\n if pcode:\n return pcode, True\n pcode = self.convert_pcode_length(countryiso3, name, scrapername)\n if pcode:\n adm = pcode\n exact = True\n else:\n adm = self.fuzzy_pcode(countryiso3, name, scrapername)\n exact = False\n return adm, exact\n\n def output_matches(self):\n # type: () -> List[str]\n \"\"\"Output log of matches\n\n Returns:\n List[str]: List of matches\n \"\"\"\n output = list()\n for match in sorted(self.matches):\n line = '%s - %s: Matching (%s) %s to %s on map' % (match[0], match[1], match[4], match[2], match[3])\n logger.info(line)\n output.append(line)\n return output\n\n def output_ignored(self):\n # type: () -> List[str]\n \"\"\"Output log of ignored\n\n Returns:\n List[str]: List of ignored\n \"\"\"\n output = list()\n for ignored in sorted(self.ignored):\n if len(ignored) == 2:\n line = '%s - Ignored %s!' % (ignored[0], ignored[1])\n else:\n line = '%s - %s: Ignored %s!' % (ignored[0], ignored[1], ignored[2])\n logger.info(line)\n output.append(line)\n return output\n\n def output_errors(self):\n # type: () -> List[str]\n \"\"\"Output log of errors\n\n Returns:\n List[str]: List of errors\n \"\"\"\n output = list()\n for error in sorted(self.errors):\n if len(error) == 2:\n line = '%s - Could not find %s in map names!' % (error[0], error[1])\n else:\n line = '%s - %s: Could not find %s in map names!' % (error[0], error[1], error[2])\n logger.error(line)\n output.append(line)\n return output\n","sub_path":"src/hdx/location/adminone.py","file_name":"adminone.py","file_ext":"py","file_size_in_byte":9940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"26247423","text":"import FWCore.ParameterSet.Config as cms\n\nfrom Configuration.Generator.PythiaUESettings_cfi import *\n\ncollisionParameters7GeV = cms.PSet(\n aBeamTarget = cms.double(208.0), # beam/target atomic number\n comEnergy = cms.double(7000.0) # collision en\n )\n\ncollisionParameters2760GeV = cms.PSet(\n aBeamTarget = cms.double(208.0), # beam/target atomic number\n comEnergy = cms.double(2760.0) # collision en\n )\n\ncollisionParameters = collisionParameters2760GeV.clone()\n\nqgpParameters = cms.PSet(qgpInitialTemperature = cms.double(1.0), ## initial temperature of QGP; allowed range [0.2,2.0]GeV;\n qgpProperTimeFormation = cms.double(0.1), ## proper time of QGP formation; allowed range [0.01,10.0]fm/c;\n hadronFreezoutTemperature = cms.double(0.14),\n doRadiativeEnLoss = cms.bool(True), ## if true, perform partonic radiative en loss\n doCollisionalEnLoss = cms.bool(False),\n qgpNumQuarkFlavor = cms.int32(0), ## num. active quark flavors in qgp; allowed values: 0,1,2,3 \n numQuarkFlavor = cms.int32(0) ## to be removed\n )\n\npyquenParameters = cms.PSet(doIsospin = cms.bool(True),\n angularSpectrumSelector = cms.int32(0), ## angular emitted gluon spectrum :\n embeddingMode = cms.bool(False),\n backgroundLabel = cms.InputTag(\"generator\") ## ineffective in no mixing\n )\n\nhydjetParameters = cms.PSet(sigmaInelNN = cms.double(58),\n shadowingSwitch = cms.int32(0),\n nMultiplicity = cms.int32(21500),\n fracSoftMultiplicity = cms.double(1.),\n maxLongitudinalRapidity = cms.double(4.5),\n maxTransverseRapidity = cms.double(1.),\n rotateEventPlane = cms.bool(True),\n allowEmptyEvents = cms.bool(False),\n embeddingMode = cms.bool(False) \n )\n\npyquenPythiaDefaultBlock = cms.PSet(\n pythiaUESettingsBlock,\n hydjetPythiaDefault = cms.vstring('MSEL=0 ! user processes',\n 'CKIN(3)=6. ! ptMin',\n 'MSTP(81)=0 ! multiple interaction OFF'\n ),\n pythiaJets = cms.vstring('MSUB(11)=1', # q+q->q+q\n 'MSUB(12)=1', # q+qbar->q+qbar\n 'MSUB(13)=1', # q+qbar->g+g\n 'MSUB(28)=1', # q+g->q+g\n 'MSUB(53)=1', # g+g->q+qbar\n 'MSUB(68)=1' # g+g->g+g\n ),\n pythiaPromptPhotons = cms.vstring('MSUB(14)=1', # q+qbar->g+gamma\n 'MSUB(18)=1', # q+qbar->gamma+gamma\n 'MSUB(29)=1', # q+g->q+gamma\n 'MSUB(114)=1', # g+g->gamma+gamma\n 'MSUB(115)=1' # g+g->g+gamma\n )\n ) \n\n# This one is not to be used\nimpactParameters = cms.PSet(cFlag = cms.int32(1),\n bFixed = cms.double(0),\n bMin = cms.double(0),\n bMax = cms.double(30)\n )\n\n\ngenerator = cms.EDFilter(\"HydjetGeneratorFilter\",\n collisionParameters,\n qgpParameters,\n hydjetParameters,\n impactParameters,\n hydjetMode = cms.string('kHydroQJets'),\n PythiaParameters = cms.PSet(pyquenPythiaDefaultBlock,\n # Quarkonia and Weak Bosons added back upon dilepton group's request.\n parameterSets = cms.vstring('pythiaUESettings',\n 'hydjetPythiaDefault',\n 'pythiaJets',\n 'pythiaPromptPhotons'\n )\n )\n )\n","sub_path":"McAnalyzer/python/hydjet_mbJPhin_cfi.py","file_name":"hydjet_mbJPhin_cfi.py","file_ext":"py","file_size_in_byte":4739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"600446745","text":"# Load libraries\nfrom pandas import read_csv\nfrom pandas.tools.plotting import scatter_matrix\nfrom matplotlib import pyplot\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.svm import SVC\n\n\n# Load dataset\nurl = \"https://raw.githubusercontent.com/jbrownlee/Datasets/master/iris.csv\"\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\ndataset = read_csv(url, names=names)\n\n#Data properties\nprint(dataset.shape)\nprint(dataset.head(20))\nprint(dataset.describe())\nprint(dataset.groupby('class').size())\n\n#Plots\ndataset.plot(kind='box', subplots=True, layout=(2,2), sharex=False, sharey=False)\npyplot.show()\ndataset.hist()\npyplot.show()\nscatter_matrix(dataset)\npyplot.show()\n\n# Split-out validation dataset\narray = dataset.values\nX = array[:,0:4]\nY = array[:,4]\nX_train, X_validation, Y_train, Y_validation = train_test_split(X, Y, test_size=0.20, random_state=1)\n\nmodels = []\nmodels.append(('LR', LogisticRegression(solver='liblinear', multi_class='ovr')))\nmodels.append(('LDA', LinearDiscriminantAnalysis()))\nmodels.append(('KNN', KNeighborsClassifier()))\nmodels.append(('CART', DecisionTreeClassifier()))\nmodels.append(('NB', GaussianNB()))\nmodels.append(('SVM', SVC(gamma='auto')))\n\nresults = []\nnames = []\nfor name, model in models:\n kfold = StratifiedKFold(n_splits=10, random_state=1)\n cv_results = cross_val_score(model, X_train, Y_train, cv=kfold, scoring='accuracy')\n results.append(cv_results)\n names.append(name)\n print('%s: %f (%f)' % (name, cv_results.mean(), cv_results.std()))\n\n\n# Compare Algorithms\npyplot.boxplot(results, labels=names)\npyplot.title('Algorithm Comparison')\npyplot.show()\n\n# Make predictions on validation dataset\nmodel = SVC(gamma='auto')\nmodel.fit(X_train, Y_train)\npredictions = model.predict(X_validation)\n\n\n# Evaluate predictions\nprint(accuracy_score(Y_validation, predictions))\nprint(confusion_matrix(Y_validation, predictions))\nprint(classification_report(Y_validation, predictions))\n\n#\n# X_train, X_test, y_train, y_test = train_test_split(iris_dataset['data'], iris_dataset['target'], random_state=0)\n#\n# print(\"X_train shape: {}\".format(X_train.shape))\n# print(\"y_train shape: {}\".format(y_train.shape))\n#\n# # Same for the test samples\n# print(\"X_test shape: {}\".format(X_test.shape))\n# print(\"y_test shape: {}\".format(y_test.shape))\n#\n# knn = KNeighborsClassifier(n_neighbors=1)\n#\n# knn.fit(X_train, y_train)\n#\n# X_new = np.array([[5, 2.9, 1, 0.2]])\n# print(\"X_new.shape: {}\".format(X_new.shape))\n#\n# prediction = knn.predict(X_new)\n# print(\"Prediction: {}\".format(prediction))\n# print(\"Predicted target name: {}\".format(iris_dataset['target_names'][prediction]))\n#\n# y_pred = knn.predict(X_test)\n# print(\"Test set predictions:\\n {}\".format(y_pred))\n# print(\"Test set score (np.mean): {:.2f}\".format(np.mean(y_pred == y_test)))\n# print(\"Test set score (knn.score): {:.2f}\".format(knn.score(X_test, y_test)))\n","sub_path":"PycharmProjects/iris/venv/iris_ex.py","file_name":"iris_ex.py","file_ext":"py","file_size_in_byte":3412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"114228482","text":"\"\"\"\nMain bot file.\n\"\"\"\nimport asyncio\nimport json\nimport logging\nimport os\nimport sys\n\nimport shutil\nimport traceback\n\nimport aiohttp\nimport discord\nimport logbook\nimport yaml\nfrom discord.ext import commands\nfrom logbook import Logger\nfrom logbook.compat import redirect_logging\nfrom logbook import StreamHandler\nfrom discord.ext.commands import Bot\n\nfrom dbansbot.websocketr import WSReceiver\n\nextensions = [\n \"dbansbot.cogs.owner\",\n \"dbansbot.cogs.mod\",\n \"dbansbot.cogs.info.reports\",\n \"dbansbot.cogs.info.moderators\",\n \"dbansbot.cogs.auto\",\n \"dbansbot.cogs.setup\",\n \"dbansbot.cogs.listeners\"\n]\n\n\nclass DBans(Bot):\n \"\"\"\n Bot class.\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n # Load the config file from sys.argv[1]\n try:\n config_file = sys.argv[1]\n except IndexError:\n config_file = os.path.join(os.getcwd(), \"config.yaml\")\n\n if not os.path.exists(config_file):\n shutil.copy(\"config.example.yaml\", \"config.yaml\")\n print(\"Copied a new config file - please edit and re-run.\")\n sys.exit(1)\n\n with open(config_file) as f:\n self.config = yaml.load(f)\n\n if self.config.get(\"use_uvloop\", False) is True:\n # Switch the event loop policy.\n import uvloop\n asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())\n\n super().__init__(*args, **kwargs)\n\n self._api_token = self.config.get(\"api\", {}).get(\"api_key\", \"\")\n\n # Define the logging set up.\n redirect_logging()\n StreamHandler(sys.stderr).push_application()\n\n self.logger = Logger(\"DBansBot\")\n self.logger.level = getattr(logbook, self.config.get(\"log_level\", \"INFO\"), logbook.INFO)\n\n # Set the root logger level, too.\n logging.root.setLevel(self.logger.level)\n\n # Create a new aiohttp session for the API.\n self.session = aiohttp.ClientSession()\n\n self._loaded = False\n\n def __del__(self):\n # Silence aiohttp.\n if not self.http.session.closed:\n self.http.session.close()\n\n if not self.session.closed:\n self.session.close()\n\n def send_message(self, destination, content, *, tts=False):\n \"\"\"\n Override for send_message that replaces `@everyone` with `@everyone` with a ZWSP.\n \"\"\"\n content = content.replace(\"@everyone\", \"@\\u200beveryone\").replace(\"@here\", \"@\\u200bhere\")\n\n return super().send_message(destination, content, tts=tts)\n\n async def game_stats(self):\n \"\"\"\n Adds 'scrolling' stats to the Discord game bar.\n \"\"\"\n while self._loaded is True:\n status, js = await self.get_api(\"/api/v1/stats\")\n if status != 200:\n self.logger.critical(\"API stats returned {}!\".format(status))\n self.logger.critical(js)\n else:\n active = js[\"active\"]\n total = js[\"total\"]\n fmt = \"{t} reports, {a}/{t} active ({p}%)\".format(t=total, a=active, p=round((active / total) * 100, 2))\n await self.change_status(game=discord.Game(name=fmt))\n\n await asyncio.sleep(15)\n\n async def on_ready(self):\n if self._loaded:\n return\n self.logger.info(\"Loaded DBansBot, logged in as {0.user.name}#{0.user.discriminator}.\".format(self))\n self.logger.info(\"Checking API status...\")\n try:\n status, js = await self.get_api(\"/api/v1/_status\")\n if status != 200:\n self.logger.critical(\"API status returned {} - terminating.\".format(status))\n self.logger.info(js)\n await self.logout()\n return\n else:\n self.logger.info(\"DiscordBans API is up, status {}\".format(js[\"status\"]))\n\n except aiohttp.errors.ClientOSError:\n self.logger.critical(\"Could not connect to API - terminating.\")\n await self.logout()\n return\n\n self.logger.info(\"Downloading application info...\")\n app_info = await self.application_info()\n self.owner_id = app_info.owner.id\n self.logger.info(\"I am owned by {}, setting owner.\".format(str(app_info.owner)))\n\n for cog in extensions:\n try:\n self.load_extension(cog)\n except Exception as e:\n self.logger.critical(\"Could not load extension `{}` -> `{}`\".format(cog, e))\n self.logger.exception()\n else:\n self.logger.info(\"Loaded extension {}.\".format(cog))\n\n self._ws_receiver = WSReceiver(self)\n\n addr = self.config[\"api\"].get(\"ws_url\", \"wss://discordbans.com/listener\") or \"wss://discordbans.com/listener\"\n\n self.loop.create_task(self._ws_receiver.open_connection(addr))\n\n self._loaded = True\n\n self.loop.create_task(self.game_stats())\n\n async def on_message(self, message):\n \"\"\"\n Process commands and log.\n \"\"\"\n self.logger.info(\"Received message: {message.content} from {message.author.display_name}{bot}\"\n .format(message=message, bot=\" [BOT]\" if message.author.bot else \"\"))\n\n if message.server is not None:\n self.logger.info(\" On channel: #{message.channel.name}\".format(message=message))\n self.logger.info(\" On server: {0.server.name} ({0.server.id})\".format(message))\n else:\n self.logger.info(\" Inside private message\")\n\n await super().on_message(message)\n\n async def on_command_error(self, e, ctx):\n \"\"\"\n Yes, it's ugly.\n\n No, I won't do anything about it.\n \"\"\"\n if isinstance(e, (commands.errors.BadArgument, commands.errors.MissingRequiredArgument)):\n await self.send_message(ctx.message.channel, \":x: Bad argument: {}\".format(' '.join(e.args)))\n return\n elif isinstance(e, (commands.errors.CheckFailure)):\n await self.send_message(\n ctx.message.channel, \":x: Check failed. You probably don't have permission to do this.\"\n )\n return\n elif isinstance(e, commands.errors.CommandNotFound):\n return\n else:\n await self.send_message(ctx.message.channel,\n \":no_entry: An error happened. This has been logged and reported.\")\n if isinstance(e, commands.errors.CommandInvokeError):\n traceback.print_exception(type(e), e.__cause__, e.__cause__.__traceback__, file=sys.stderr)\n else:\n traceback.print_exception(type(e), e, e.__traceback__, file=sys.stderr)\n\n def run(self):\n \"\"\"\n Convenience function to run the bot with the specified token.\n \"\"\"\n try:\n super().run(self.config[\"bot\"][\"token\"])\n except discord.errors.LoginFailure as e:\n self.logger.error(\"Failed to login to discord: {}\".format(e.args[0]))\n sys.exit(2)\n\n # region API\n # API methods to make life easier.\n\n async def request_api(self, method, url: str, *, params: dict = None, body: dict = None, headers: dict = None):\n \"\"\"\n Sends a request to the DiscordBans API.\n \"\"\"\n url = self.config.get(\"api\", {}).get(\"url\", \"https://discordbans.com/api/v1\") + url\n if headers is None:\n headers = {}\n\n headers[\"User-Agent\"] = \"DiscordBans/DiscordBot (Python 3) API/v1\"\n headers[\"Authorization\"] = self.config.get(\"api\", {}).get(\"api_key\", \"\")\n headers[\"Content-Type\"] = \"application/json\"\n\n async with self.session.request(method, url, params=params, data=json.dumps(body), headers=headers) as r:\n assert isinstance(r, aiohttp.ClientResponse)\n self.logger.info(\"HTTP {} {} - {}\".format(method.upper(), url, r.status))\n return r.status, await r.json()\n\n async def post_api(self, url: str, *, body: dict = None, headers: dict = None):\n \"\"\"\n Sends a POST request to DBans API.\n \"\"\"\n return await self.request_api(\"POST\", url, params=None, body=body, headers=headers)\n\n async def get_api(self, url: str, *, params: dict = None, headers: dict = None):\n \"\"\"\n Sends a GET request to DBans API.\n \"\"\"\n return await self.request_api(\"get\", url, params=params, body=None, headers=headers)\n\n async def put_api(self, url: str, *, body: dict = None, headers: dict = None):\n \"\"\"\n Sends a PUT request to DBans API.\n \"\"\"\n return await self.request_api(\"PUT\", url, params=None, body=body, headers=headers)\n\n async def patch_api(self, url: str, *, body: dict = None, headers: dict = None):\n \"\"\"\n Sends a PATCH request to DBans API.\n \"\"\"\n return await self.request_api(\"PATCH\", url, params=None, body=body, headers=headers)\n\n # endregion\n","sub_path":"dbansbot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":8915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"333395087","text":"#!/user/bin/env python\n# coding=utf-8\n'''\n@author : Eikken\n#@file : ApiTest.py\n#@time : 2019-05-21 11:57:04\n'''\nimport pandas as pd\nimport numpy as np\n\n\ndef getDataSet():\n DataSet = pd.read_excel(r'historyData.xlsx', encoding='UTF-8')\n dataSet = np.array(DataSet).tolist()\n columns = np.array(DataSet.columns).tolist()\n data = []\n for d in dataSet:\n d[1] = str(d[1]).split(' ') # str(d[1]).split(' ') 元素集转化为单个\n data.append(d[1])\n return data, columns\n\n\ndef createItems(dataSet):\n Items = []\n for d in dataSet:\n for item in d:\n if not [item] in Items: # list 用 not[item] in list\n Items.append([item])\n Items.sort()\n return map(frozenset, Items)\n\n\ndef createSupportItem(D, Items, MinSupport):\n X = {}\n dataSet = list(D)\n items = list(Items)\n sumItem = float(len(dataSet))\n # map对象用一次就空了,所以转化为list\n for d in dataSet:\n for item in items: # 候选集\n if item.issubset(d): # 候选集为item子集\n if not item in X:\n X[item] = 1 # 不存在就创建,存在就加一\n else:\n X[item] += 1\n supportItems = [] # 返回结果\n supportData = {}\n for k in X.keys():\n support = X[k] / float(sumItem) # 支持度\n if support >= MinSupport:\n supportItems.insert(0, k)\n supportData[k] = support\n return supportItems, supportData\n\n\ndef AprioriConf(Lk, k): # 计算K频繁项集\n # Lk 是上一个频繁项集 last\n # k是创建的项集数\n retList = []\n lenLk = len(Lk)\n for i in range(lenLk):\n for j in range(i + 1, lenLk):\n L1 = list(Lk[i])[:k - 2]\n L2 = list(Lk[j])[:k - 2]\n L1.sort()\n L2.sort()\n if L1 == L2:\n retList.append(Lk[i] | Lk[j])\n return retList\n\n\ndef Apriori(dataSet, minSupport):\n Items = createItems(dataSet)\n D = map(set, dataSet)\n L1, supportData = createSupportItem(D, Items, minSupport)\n L = [L1]\n k = 2\n while (len(L[k - 2]) > 0):\n Ck = AprioriConf(L[k - 2], k)\n Lk, Supk = createSupportItem(map(set, dataSet), Ck, MinSupport=minSupport)\n supportData.update(Supk)\n L.append(Lk)\n k += 1\n return L, supportData\n\n\ndef main():\n dataSet, columns = getDataSet() # dataSet中仅有项目集,没有订单集\n L, Support = Apriori(dataSet, 0.5)\n print('所有频繁项集L:')\n for l in L:\n print(l)\n print('对应支持度Support:')\n for k, v in Support.items():\n print('项目集:', k, '的支持度为:', v)\n\n\nif __name__ == '__main__':\n main()\n\n#我现在要选择每一条公线路,他们的价格支持度","sub_path":"competition/Apriori.py","file_name":"Apriori.py","file_ext":"py","file_size_in_byte":2787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"413420147","text":"#las funciones en phyton parten con def\ni=0;\ndef funcion_tonta(nombre):\n\tseparador = \" \"\n\tprint(separador.join ((\"Hola\",nombre,\" Imbecil\")))\n\t\n#llamamos la funcion directmente..\nfuncion_tonta(\"Catmi\")\n\n#funcion rut verificador\n# Tratemos ahora con una función más compleja...\n# como el cálculo del dígito verificador del rut...\ndef digito_verificador(rut_sin_digito) :\n digito = \"\"\n multiplo = 0\n acumulador = 0\n contador = 2\n while rut_sin_digito > 0:\n multiplo = (rut_sin_digito % 10) * contador\n acumulador = acumulador + multiplo\n rut_sin_digito = rut_sin_digito // 10 # division entera\n contador = contador + 1\n if contador == 8:\n contador = 2\n digito = 11 - (acumulador % 11)\n if digito == 10:\n digito = 'K'\n if digito == 10:\n digito = 0\n return digito \nmi_rut = 11108949\nprint(\"-\".join((str(mi_rut),str(digito_verificador(mi_rut)))))\n\n#git add ejemplo_funciones.py\n#git commit -m \"agregamos ejemplo de funciones\"\n#git checkout master (asumo que es volver a master, cambiarse rama)\n#git pull traer actualizaciones arriba\n#git merge dm_ejmplo-funcioens\n#git push subir actualiaciones\n#git branch -d dm_ejmplo-funcioens ","sub_path":"ejemplo_funciones.py","file_name":"ejemplo_funciones.py","file_ext":"py","file_size_in_byte":1214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"360611215","text":"import json\r\nimport os\r\nimport random\r\n\r\nimport bpy\r\nfrom pathlib import *\r\n\r\nimport math\r\n\r\n# ------------------------------------------------------------------------------\r\n# Conf\r\nOBJ_PATH = Path(\"C:/Users/Monthy/Documents/projects/thesis/thesis-data-suite/scenes/ziggurat-city/obj/\")\r\nGEO_PATH = Path(\"C:/Users/Monthy/Documents/projects/thesis/thesis-data-suite/scenes/ziggurat-city/geometry/\")\r\nLIGHT_PATH = Path(\"C:/Users/Monthy/Documents/projects/thesis/thesis-data-suite/scenes/ziggurat-city/lights/\")\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# Geometry\r\nclass Mesh(object):\r\n def __init__(self, mesh_id, path):\r\n self._mesh_id = mesh_id\r\n self._path = path\r\n\r\n @property\r\n def mesh_id(self):\r\n return self._mesh_id\r\n\r\n @property\r\n def path(self):\r\n return self._path\r\n\r\n def to_json_dic(self):\r\n return { \"id\": self.mesh_id,\r\n \"path\": self.path }\r\n\r\n\r\nclass Obj(object):\r\n def __init__(self, mesh_id, name, rotation, translation):\r\n self._mesh_id = mesh_id\r\n self._name = name\r\n self._rotation = rotation\r\n self._translation = translation\r\n\r\n @property\r\n def mesh_id(self):\r\n return self._mesh_id\r\n\r\n @property\r\n def name(self):\r\n return self._name\r\n\r\n @property\r\n def rotation(self):\r\n return self._rotation\r\n\r\n @property\r\n def translation(self):\r\n return self._translation\r\n\r\n def to_json_dic(self, shader_id):\r\n return { \"mesh_id\": self.mesh_id,\r\n \"name\": self.name,\r\n \"shader_id\": shader_id,\r\n \"rotation\": { \"x\": self.rotation[0],\r\n \"y\": self.rotation[1],\r\n \"z\": self.rotation[2] },\r\n \"translation\": { \"x\": self.translation[0],\r\n \"y\": self.translation[1],\r\n \"z\": self.translation[2] }}\r\n\r\n\r\ndef build_geo_dic(shader_id: str,\r\n meshes: list,\r\n objects: list):\r\n json_meshes = list(m.to_json_dic() for m in meshes)\r\n json_objects = list(o.to_json_dic(shader_id) for o in objects)\r\n\r\n return { \"meshes\": json_meshes,\r\n \"objects\": json_objects }\r\n\r\n\r\ndef extract_geometry_from_blend():\r\n obj_count = { \"Ground\": 0,\r\n \"Houses\": 0,\r\n \"Mountain\": 0,\r\n# \"Rubble\": 0,\r\n \"Wall\": 0,\r\n \"Ziggurat\": 0 }\r\n\r\n obj_list = []\r\n objects = bpy.data.scenes[0].objects\r\n\r\n for obj in objects:\r\n if obj.type == 'EMPTY' and \"::\" in obj.name:\r\n obj_type, obj_name = obj.name.split(\"::\")\r\n obj_name = obj_name.split(\".\")[0]\r\n\r\n if obj_type == 'obj' and obj_name in obj_count:\r\n obj_translation = obj.matrix_world.to_translation()\r\n obj_rotation = obj.matrix_world.to_euler()\r\n\r\n # transform into nTiled coordinate system\r\n obj_translation = (obj_translation[0], obj_translation[2], obj_translation[1])\r\n obj_rotation = (obj_rotation[0], obj_rotation[2], obj_rotation[1])\r\n\r\n obj_list.append(Obj(mesh_id=obj_name,\r\n name=(\"{}.{}\".format(obj_name, obj_count[obj_name])),\r\n rotation=obj_rotation,\r\n translation=obj_translation ))\r\n obj_count[obj_name] += 1\r\n\r\n mesh_list = []\r\n for key in obj_count:\r\n if obj_count[key] > 0:\r\n mesh_list.append(Mesh(key, str(OBJ_PATH / Path(\"{}.obj\".format(key)))))\r\n\r\n return (mesh_list, obj_list)\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# Lights\r\nclass Light(object):\r\n def __init__(self, position, intensity, radius):\r\n self._position = position\r\n self._intensity = intensity\r\n self._radius = radius\r\n\r\n @property\r\n def position(self):\r\n return self._position\r\n\r\n @property\r\n def intensity(self):\r\n return self._intensity\r\n\r\n @property\r\n def radius(self):\r\n return self._radius\r\n\r\n def to_json_dic(self):\r\n return { \"position\": { \"x\": float(self.position[0]),\r\n \"y\": float(self.position[1]),\r\n \"z\": float(self.position[2]) * -1.0 },\r\n \"intensity\": { \"r\": float(self.intensity[0]),\r\n \"g\": float(self.intensity[1]),\r\n \"b\": float(self.intensity[2]) },\r\n \"radius\": float(self.radius) }\r\n\r\n def build_in_blender(self):\r\n position = (self.position[0], self.position[2], self.position[1])\r\n bpy.ops.mesh.primitive_uv_sphere_add(size=self.radius,\r\n view_align=False,\r\n enter_editmode=False,\r\n location=position,\r\n layers=(False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n False,\r\n True))\r\n ob = bpy.context.object\r\n bpy.ops.object.shade_smooth()\r\n\r\n ob.name = \"LightSphere\"\r\n\r\n\r\ndef hsv_to_rgb(hsv : tuple):\r\n # Check pre conditions\r\n if (len(hsv) != 3 ):\r\n return (0.0, 0.0, 0.0)\r\n\r\n if (hsv[0] is None or not isinstance(hsv[0], float)):\r\n return (0.0, 0.0, 0.0)\r\n\r\n # Convert value\r\n hue = hsv[0] % 360.0\r\n saturation = hsv[1]\r\n value = hsv[2]\r\n\r\n chroma = hue * saturation\r\n\r\n h_sec = hue / 60.0\r\n intermediate = chroma * ( 1 - abs((h_sec % 2) - 1))\r\n\r\n # calculate second r_1, g_1, b_1\r\n if h_sec < 1.0:\r\n rgb_1 = ( chroma, intermediate, 0.0)\r\n elif h_sec < 2.0:\r\n rgb_1 = ( intermediate, chroma, 0.0)\r\n elif h_sec < 3.0:\r\n rgb_1 = ( 0.0, chroma, intermediate )\r\n elif h_sec < 4.0:\r\n rgb_1 = ( 0.0, intermediate, chroma, )\r\n elif h_sec < 5.0:\r\n rgb_1 = ( intermediate, 0.0, chroma )\r\n else:\r\n rgb_1 = ( chroma, 0.0, intermediate )\r\n\r\n m = value - chroma\r\n return ( rgb_1[0] + m, rgb_1[1] + m, rgb_1[2] + m )\r\n\r\n\r\nclass LightSpawner(object):\r\n def __init__(self, anchor, number, size_x, size_y, size_z, t):\r\n self._anchor = anchor\r\n self._x = bpy.data.scenes[0].objects[\"light::X.{}\".format(number)]\r\n self._y = bpy.data.scenes[0].objects[\"light::Y.{}\".format(number)]\r\n self._z = bpy.data.scenes[0].objects[\"light::Z.{}\".format(number)]\r\n\r\n self._size_x = size_x\r\n self._size_y = size_y\r\n self._size_z = size_z\r\n\r\n self._t = t\r\n\r\n @property\r\n def origin(self):\r\n origin = self._anchor.matrix_world.to_translation()\r\n return (origin[0], origin[2], origin[1])\r\n\r\n @property\r\n def x_empty(self):\r\n x = self._x.matrix_world.to_translation()\r\n return (x[0], x[2], x[1])\r\n\r\n @property\r\n def y_empty(self):\r\n y = self._y.matrix_world.to_translation()\r\n return (y[0], y[2], y[1])\r\n\r\n @property\r\n def z_empty(self):\r\n z = self._z.matrix_world.to_translation()\r\n return (z[0], z[2], z[1])\r\n\r\n @property\r\n def x_axis(self):\r\n origin = self.origin\r\n x_empty = self.x_empty\r\n return (x_empty[0] - origin[0], x_empty[1] - origin[1], x_empty[2] - origin[2])\r\n\r\n @property\r\n def y_axis(self):\r\n origin = self.origin\r\n y_empty = self.y_empty\r\n return (y_empty[0] - origin[0], y_empty[1] - origin[1], y_empty[2] - origin[2])\r\n\r\n @property\r\n def z_axis(self):\r\n origin = self.origin\r\n z_empty = self.z_empty\r\n return (z_empty[0] - origin[0], z_empty[1] - origin[1], z_empty[2] - origin[2])\r\n\r\n @property\r\n def size_x(self):\r\n return self._size_x\r\n\r\n @property\r\n def size_y(self):\r\n return self._size_y\r\n\r\n @property\r\n def size_z(self):\r\n return self._size_z\r\n\r\n @property\r\n def t(self):\r\n return self._t\r\n\r\n def generate_lights(self, n_x, n_y, n_z, radius):\r\n origin = self.origin\r\n\r\n n_lights_x = self.size_x * n_x\r\n n_lights_y = self.size_y * n_y\r\n n_lights_z = self.size_z * n_z\r\n\r\n x_axis = self.x_axis\r\n y_axis = self.y_axis\r\n z_axis = self.z_axis\r\n\r\n def calculate_length(axis):\r\n return math.sqrt(axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2])\r\n\r\n len_x = calculate_length(x_axis)\r\n len_y = calculate_length(y_axis)\r\n len_z = calculate_length(z_axis)\r\n\r\n\r\n spacing_x = len_x / (n_lights_x + 1)\r\n spacing_y = len_y / (n_lights_y + 1)\r\n spacing_z = len_z / (n_lights_z + 1)\r\n\r\n norm_x_axis = (x_axis[0] / len_x, x_axis[1] / len_x, x_axis[2] / len_x)\r\n norm_y_axis = (y_axis[0] / len_y, y_axis[1] / len_y, y_axis[2] / len_y)\r\n norm_z_axis = (z_axis[0] / len_z, z_axis[1] / len_z, z_axis[2] / len_z)\r\n\r\n def random_rgb_colour():\r\n colour = [0.0, 0.0, 0.0]\r\n\r\n colour_options = [ (0, 1),\r\n (0, 2),\r\n (1, 0),\r\n (1, 2),\r\n (2, 0),\r\n (2, 1) ]\r\n colour_def = colour_options[random.randint(0,5)]\r\n colour[colour_def[0]] = 1.0\r\n colour[colour_def[1]] = random.random()\r\n\r\n return (colour[0], colour[1], colour[2])\r\n\r\n lights = []\r\n\r\n for x_i in range(1, n_lights_x + 1):\r\n for y_i in range(1, n_lights_y + 1):\r\n for z_i in range(1, n_lights_z + 1):\r\n colour = random_rgb_colour()\r\n position = (\r\n x_i * norm_x_axis[0] * spacing_x + y_i * norm_y_axis[0] * spacing_y + z_i * norm_z_axis[0] * spacing_z + origin[0],\r\n x_i * norm_x_axis[1] * spacing_x + y_i * norm_y_axis[1] * spacing_y + z_i * norm_z_axis[1] * spacing_z + origin[1],\r\n x_i * norm_x_axis[2] * spacing_x + y_i * norm_y_axis[2] * spacing_y + z_i * norm_z_axis[2] * spacing_z + origin[2])\r\n\r\n lights.append(Light(position, colour, radius))\r\n return lights\r\n\r\n\r\ndef build_light_dic(lights):\r\n return { \"lights\": list(l.to_json_dic() for l in lights) }\r\n\r\n\r\ndef extract_light_spawners_from_blend():\r\n # Obtain light generators\r\n objects = bpy.data.scenes[0].objects\r\n\r\n light_spawners = []\r\n for obj in objects:\r\n if obj.type == \"EMPTY\" and \"::\" in obj.name:\r\n ty, name = obj.name.split(\"::\")\r\n\r\n if (ty == \"light\" and\r\n \"Anchor\" in name\r\n and \".\" in name\r\n and \"#\" in name\r\n and \"_\" in name\r\n and \"$\" in name):\r\n\r\n name, number = name.split(\".\")\r\n t, name = name.split('$')\r\n size, name = name.split(\"#\")\r\n n_x, n_y, n_z = size.split(\"_\")\r\n\r\n light_spawners.append(LightSpawner(anchor=obj,\r\n number=number,\r\n size_x=int(n_x),\r\n size_y=int(n_y),\r\n size_z=int(n_z),\r\n t=t))\r\n return light_spawners\r\n\r\n\r\ndef generate_lights(size_dic, n_width, n_height, n_depth):\r\n light_spawners = extract_light_spawners_from_blend()\r\n lights = []\r\n\r\n for spawner in light_spawners:\r\n lights += spawner.generate_lights(n_width,\r\n n_depth,\r\n n_height,\r\n size_dic[spawner.t])\r\n\r\n return lights\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# misc\r\ndef write_to_json(path, data):\r\n with open(path, 'w') as f:\r\n f.write(json.dumps(data, indent=2))\r\n\r\n\r\n# ------------------------------------------------------------------------------\r\n# Main\r\nif __name__ == \"__main__\":\r\n meshes, objects = extract_geometry_from_blend()\r\n\r\n shaders = [ \"forward_attenuated\",\r\n \"forward_tiled\",\r\n \"forward_clustered\",\r\n \"forward_hashed\",\r\n \"deferred_attenuated\",\r\n \"deferred_tiled\",\r\n \"deferred_clustered\",\r\n \"deferred_hashed\" ]\r\n\r\n for s in shaders:\r\n json_dic = build_geo_dic(s, meshes, objects)\r\n write_to_json(path= str(GEO_PATH / Path(\"{}.json\".format(s))), data=json_dic)\r\n\r\n for x in range(1, 4):\r\n for z in range(1, 4):\r\n for y in range(1, 4):\r\n lights = generate_lights({\"small\": 10.0, \"big\": 50.0}, x, y, z)\r\n n_lights = len(lights)\r\n write_to_json(path=str(LIGHT_PATH / Path(\"{}#{}x_{}y_{}z.json\".format(n_lights, x, y, z))), data=build_light_dic(lights))\r\n\r\n","sub_path":"scenes/ziggurat-city/generate_ziggurat_city.py","file_name":"generate_ziggurat_city.py","file_ext":"py","file_size_in_byte":14263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"270999298","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/val/Projects/workon/mpro/sf3/apps/django-auditware/auditware/admin.py\n# Compiled at: 2016-04-05 16:17:06\n# Size of source mod 2**32: 840 bytes\nfrom django.db import models\nfrom django import forms\nfrom django.contrib import admin\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.contrib.auth.admin import UserAdmin as DjangoUserAdmin\nfrom .models import UserAudit\n\nclass UserAuditAdmin(admin.ModelAdmin):\n formfield_overrides = {models.CharField: {'widget': forms.TextInput(attrs={'size': 160})}}\n list_display = [\n 'id',\n 'user',\n 'audit_key',\n 'ip_address',\n 'user_agent',\n 'referrer',\n 'last_page',\n 'pages_viwed',\n 'force_logout',\n 'updated_at',\n 'created_at']\n search_fields = [\n 'user__username',\n 'ip_address',\n 'user_agent',\n 'referrer']\n list_per_page = 25\n\n\nadmin.site.register(UserAudit, UserAuditAdmin)","sub_path":"pycfiles/django-auditware-0.0.5.tar/admin.cpython-34.py","file_name":"admin.cpython-34.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"11976365","text":"\"\"\"empty message\n\nRevision ID: d5471807df25\nRevises: 31a436182d28\nCreate Date: 2018-09-22 02:04:46.273717\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = 'd5471807df25'\ndown_revision = '31a436182d28'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('groupusers',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('group_id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.Column('donated', sa.Float(), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.alter_column('groups', 'donated',\n existing_type=postgresql.DOUBLE_PRECISION(precision=53),\n nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('groups', 'donated',\n existing_type=postgresql.DOUBLE_PRECISION(precision=53),\n nullable=True)\n op.drop_table('groupusers')\n # ### end Alembic commands ###\n","sub_path":"server/migrations/versions/d5471807df25_.py","file_name":"d5471807df25_.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"90391822","text":"# Copyright 2020 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 json\nimport os\n\nfrom flask import Flask, request\n\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n return 'Hello world service. '\n\n\n@app.route('/api/v1/hello', methods=['POST'])\ndef hello():\n json_data = request.get_json()\n name = 'World'\n if 'name' in json_data.keys():\n name = json_data['name']\n\n resp = {\n 'message': 'Hello, {}!'.format(name)\n }\n\n return resp, 200\n\n\nif __name__ == \"__main__\":\n app.run(debug=True, host='0.0.0.0', port=int(os.environ.get('PORT', 8080)))\n","sub_path":"microservices/hello_world/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"409833014","text":"class Solution:\n def hammingDistance(self, x: int, y: int) -> int:\n #Time - O(length(max(x,y)))\n #Space - O(n)\n\n dist = 0\n for bit in bin(x^y): # XOR gives 1's where there are different digits in both binary numbers\n if bit == '1':\n dist += 1 #count all the 1's\n return dist","sub_path":"BitwiseManipulation/HammingDistance.py","file_name":"HammingDistance.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"479717410","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\"\"\"\nSubmission for problem A: Counting Sheep\nof Google CodeJam 2016\n\nAuthor: Tsirigotis Christos \nDate: April 09, 2016\n\"\"\"\n\n\nOUTPUT = \"Case #%(nc)s: %(L)s\"\nfind_digits = lambda x: set(map(int, list(str(x))))\nALL_DIGITS = find_digits(1234567890)\n\ndef solve():\n T = int(raw_input()) # 1 <= T <= 100\n for nc in xrange(1, T+1):\n N = int(raw_input()) # 0 <= N <= 200 <= 1e6\n if N == 0:\n L = \"INSOMNIA\"\n print(OUTPUT % locals())\n else:\n i = 0\n digits_seen = set([])\n while digits_seen != ALL_DIGITS:\n i += 1\n L = i * N\n digits_seen |= find_digits(L)\n print(OUTPUT % locals())\n\nsolve()\n\n","sub_path":"codes/CodeJamCrawler/16_0_1_neat/16_0_1_Tsirif_a_solve.py","file_name":"16_0_1_Tsirif_a_solve.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"650808356","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# Copyright 2018 Juergen Etzlstorfer (Dynatrace) \n# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)\n\nfrom __future__ import absolute_import, division, print_function\n__metaclass__ = type\n\nANSIBLE_METADATA = {'metadata_version': '1.1',\n 'status': ['preview'],\n 'supported_by': 'community'}\n\nDOCUMENTATION = '''\n---\nmodule: dynatrace_comment\nversion_added: \"2.3\"\nauthor: \"Juergen Etzlstorfer (@jetzlstorfer)\"\nshort_description: Comment on Dynatrace detected problems\ndescription:\n - Push a comment to a Dynatrace problem ticket\noptions:\n tenant_url:\n description:\n - Tenant URL for the Dynatrace Tenant\n required: true\n type: str\n api_token:\n description:\n - Dynatrace API Token\n required: true\n type: str\n problem_id:\n description:\n - Dynatrace Problem ID to add the comment to\n required: true\n type: str\n comment:\n description:\n - Content of comment to push to Dynatrace\n required: true\n type: str\n user:\n description:\n - User that pushes the comments\n required: true\n type: str\n context:\n description:\n - Source where the comment originates from (default Ansible)\n required: false\n type: str\nrequirements: []\n'''\n\nEXAMPLES = '''\n- dynatrace_comment:\n tenant_url: https://mytenant.live.dynatrace.com\n api_token: XXXXXXXX\n comment: 'Comment sent from Ansible'\n user: 'user@dynatrace.com'\n'''\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.urls import fetch_url\n# from ansible.module_utils.six.moves.urllib.parse import urlencode\nimport json\n\n# ===========================================\n# Module execution.\n#\n\n\ndef main():\n\n module = AnsibleModule(\n argument_spec=dict(\n tenant_url=dict(required=True),\n api_token=dict(required=True),\n problem_id=dict(required=True),\n comment=dict(required=True),\n user=dict(required=True),\n context=dict(required=False)\n ),\n supports_check_mode=True\n )\n\n # build list of params\n params = {}\n\n # set standard context\n params[\"context\"] = \"Ansible\"\n\n for item in [\"comment\", \"user\", \"context\"]:\n if module.params[item]:\n params[item] = module.params[item]\n\n # If we're in check mode, just exit pretending like we succeeded\n if module.check_mode:\n module.exit_json(changed=True)\n\n # Send the comment to Dynatrace and attach it to a problem\n dt_url = module.params[\"tenant_url\"] + \"/api/v1/problem/details/\" + module.params[\"problem_id\"] + \"/comments\"\n # data = urlencode(params)\n headers = {\n 'Content-Type': 'application/json',\n 'Authorization': 'Api-Token ' + module.params['api_token']\n }\n\n # FAIL FOR DEBUG PURPOSES - TO INSPECT PAYLOAD #####\n # module.fail_json(msg=json.dumps(params))\n #\n\n ####\n # SEND COMMENT EVENT TO DYNATRACE\n ####\n try:\n response, info = fetch_url(module, dt_url, data=json.dumps(params), headers=headers)\n\n if info['status'] in (200, 201):\n module.exit_json(changed=True)\n elif info['status'] == 401:\n module.fail_json(msg=\"Token Authentification failed.\")\n else:\n module.fail_json(msg=\"Unable to send comment to Dynatrace: %s\" % info)\n except Exception as e:\n module.fail_json(msg=\"Failure: \" + e.message)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"collection/plugins/modules/dynatrace_comment.py","file_name":"dynatrace_comment.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"393292373","text":"import json\n\n#i need to unload the json file and convert it back to a python dictionary\n#because i dumped a python dictionary into a json object, in order to reopen,read, and print it, i will need to use the json module and load the file back into python dictionary so that I could print the dictionary out as intended :P\n# file_handle = open(\"test.json\")\n# file_handle = json.loads(file_handle)\n# for line in file_handle:\n# \tfor k,v in line.items():\n# \t\tprint(str(k))\n# \t\tfor k2,v2 in v.items:\n# \t\t\tprint(str(k2)+\":\"+str(v2))\n\nwith open(\"test.json\") as f:\n\tdata = json.load(f)\nfor line in data:\n\tfor k,v in line.items():\n\t\tprint(str(k))\n\t\tfor k2,v2 in v.items:\n\t\t\tprint(str(k2)+\":\"+str(v2))\n","sub_path":"HyperIMU_Server/json_read.py","file_name":"json_read.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"181694939","text":"import setuptools\n\nwith open(\"README.md\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"aviary\",\n version=\"0.0.2\",\n author=\"Rhys Goodall\",\n author_email=\"rhys.goodall@outlook.com\",\n description=\"A Collection of Machine Learning Models for Materials Discovery\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n packages=['aviary'],\n package_dir={'aviary': 'aviary'},\n classifiers=[\n \"Programming Language :: Python :: 3.7.10\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"83425060","text":"from data import CITIES, BUSINESSES, USERS, REVIEWS, TIPS, CHECKINS\n\nimport random\nimport pandas as pd\nfrom pandas import Series, DataFrame\nimport numpy as np\nfrom IPython.display import display\nimport csv\n\ndef recommend(user_id=None, business_id=None, city=None, n=10):\n \"\"\"\n Returns n recommendations as a list of dicts.\n Optionally takes in a user_id, business_id and/or city.\n A recommendation is a dictionary in the form of:\n {\n business_id:str\n stars:str\n name:str\n city:str\n adress:str\n }\n \"\"\"\n\n\n if not city:\n city = random.choice(CITIES)\n return random.sample(BUSINESSES[city], n)\n\ndef get_rating(REVIEWS, user_id, business_id):\n for city in CITIES:\n for review in range(len(REVIEWS[city])):\n reviewdict = REVIEWS[city][review]\n if reviewdict['user_id'] == user_id and reviewdict['business_id'] == business_id:\n rating = (REVIEWS[city][review]['stars'])\n return rating\n return np.nan\n\n\ndef pivot_ratings(REVIEWS, CITIES, USERS, BUSINESSES):\n users = []\n businesses = []\n for city in CITIES:\n for user in USERS[city]:\n users.append(user['user_id'])\n for business in BUSINESSES[city]:\n businesses.append(business['business_id'])\n pivot_data = pd.DataFrame(np.nan, columns=users, index=businesses, dtype=float)\n for x in pivot_data:\n for y in pivot_data.index:\n pivot_data.loc[y][x] = get_rating(REVIEWS, x, y)\n return pivot_data\n\ndef pivot_ratings_city(city, REVIEWS, CITIES, USERS, BUSINESSES):\n users = []\n businesses = []\n for user in USERS[city]:\n users.append(user['user_id'])\n for business in BUSINESSES[city]:\n businesses.append(business['business_id'])\n pivot_data = pd.DataFrame(np.nan, columns=users, index=businesses, dtype=float)\n for x in pivot_data:\n for y in pivot_data.index:\n pivot_data.loc[y][x] = get_rating(REVIEWS, x, y)\n return pivot_data\n\ndef pivot_ratings_friends(user_id, REVIEWS, CITIES, USERS, BUSINESSES):\n \"\"\"\n Return matrix containing all ratings of friends on businesses they have been to\n \"\"\"\n users = find_friends(user_id, USERS)\n users.append(user_id)\n businesses = []\n for friend in users:\n friends_businesses = check_businesses(friend, REVIEWS)\n for business in friends_businesses:\n businesses.append(business)\n businesses = list(set(businesses))\n pivot_data = pd.DataFrame(np.nan, columns=users, index=businesses, dtype=float)\n for x in pivot_data:\n for y in pivot_data.index:\n pivot_data.loc[y][x] = get_rating(REVIEWS, x, y)\n return pivot_data\n\ndef find_friends(user_id, USERS):\n \"\"\"\n return list of friends for a given user id\n \"\"\"\n for city, users in USERS.items():\n for user in users:\n if user[\"user_id\"] == user_id:\n friends = user[\"friends\"].split()\n return friends\n\ndef check_businesses(user_id, REVIEWS):\n \"\"\"\n returns a list of businesses a user has placed reviews for\n \"\"\"\n businesses = []\n for city, reviews in REVIEWS.items():\n for review in reviews:\n if review[\"user_id\"] == user_id:\n businesses.append(review['business_id'])\n return businesses\n\n# rate = get_rating(REVIEWS, 'DAIpUGIsY71noX0wNuc27w', 'PNzir9TtJAD7U41GwR98-w')\n# print(REVIEWS['sun city'][0])\n# print(f'The rating is {rate}')\n\n# friends = find_friends('MM4RJAeH6yuaN8oZDSt0RA', USERS)\n# businesses = check_businesses('LisTsUqnQ5RoW6reg6hyWQ', REVIEWS)\n# print(businesses)\n\n# utility_matrix = pivot_ratings_friends('QGgWWhEi5R4SLAKN-xwtNQ', REVIEWS, CITIES, USERS, BUSINESSES)\n# display(utility_matrix)\n\n# utility_matrix = pivot_ratings_city('sun city', REVIEWS, CITIES, USERS, BUSINESSES)\n# display(utility_matrix)","sub_path":"recommender.py","file_name":"recommender.py","file_ext":"py","file_size_in_byte":3900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"187795222","text":"#!/usr/bin/env python\n\"\"\"\n__version__ = \"$Revision: 1.1 $\"\n__date__ = \"$Date: 2004/10/03 23:58:01 $\"\n\n\"\"\"\n\nimport os\nfrom PythonCard import dialog, model\nfrom codeEditor import CodeEditor\nfrom wx import stc\nimport webbrowser\n\n# reST\nfrom PythonCard.templates.htmlpreview import HtmlPreview\nfrom snippet import restify\n\n\nclass RestEditor(CodeEditor):\n\n def on_initialize(self, event):\n super(RestEditor, self).on_initialize(event)\n self.renderOnReturn = self.menuBar.getChecked('menuFormatRenderOnReturn')\n self.previewWindow = model.childWindow(self, HtmlPreview)\n #self.previewWindow.position = (425, -1)\n self.previewWindow.visible = True\n self.html = ''\n\n # reST\n def on_previewPost_command(self, event):\n self.previewWindow.Show()\n txt = self.components.document.text\n if self.menuBar.getChecked('menuViewSourceIsHtml'):\n firstLine = txt[:10].lower()\n if firstLine.startswith('\\n\\n\\n\\n' + txt + '\\n\\n\\n'\n else:\n # KEA 2004-08-15\n # snippet.restify is returning None when there is a reST error\n # what's a better way to provide feedback to the user without barfing\n # all over the output?\n rest = restify(txt)\n if rest:\n html = '\\n\\n\\n\\n' + rest + '\\n\\n\\n'\n else:\n html = self.previewWindow.components.html.text\n # do make sure stylesheets and relative image references can be found\n # might need to chdir here\n # won't work until there is a document path\n curdir = os.getcwd()\n self.previewWindow.components.html.text = html\n self.html = html\n os.chdir(curdir)\n\n def on_document_keyDown(self, event):\n if event.keyCode == 13 and self.renderOnReturn:\n # since we won't be calling skip, insert a newline manually\n self.components.document.CmdKeyExecute(stc.STC_CMD_NEWLINE)\n self.on_previewPost_command(None)\n else:\n event.skip()\n\n def saveHtmlFile(self, path):\n try:\n f = open(path, 'wb')\n try:\n f.write(self.html)\n finally:\n f.close()\n except:\n pass\n\n def on_saveHtml_command(self, event):\n wildcard = \"HTML files (*.html)|*.html|All files (*.*)|*.*\"\n #wildcard = self.resource.strings.saveAsWildcard\n if self.documentPath is None:\n dir = ''\n filename = '*.html'\n else:\n dir = os.path.dirname(self.documentPath)\n filename = os.path.splitext(os.path.basename(self.documentPath))[0] + '.html'\n result = dialog.saveFileDialog(None, self.resource.strings.saveAs, dir, filename, wildcard)\n if result.accepted:\n path = result.paths[0]\n self.saveHtmlFile(path)\n \n def on_menuFormatRenderOnReturn_select(self, event):\n self.renderOnReturn = self.menuBar.getChecked('menuFormatRenderOnReturn')\n\n def on_doHelpRest_command(self, event):\n webbrowser.open('http://docutils.sourceforge.net/rst.html')\n\n def on_doHelpRestQuickReference_command(self, event):\n webbrowser.open('http://docutils.sourceforge.net/docs/user/rst/quickref.html')\n\nif __name__ == '__main__':\n app = model.Application(RestEditor)\n app.MainLoop()\n","sub_path":"vb2py/PythonCard/tools/oneEditor/restEditor.py","file_name":"restEditor.py","file_ext":"py","file_size_in_byte":3609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"26225224","text":"#!/usr/bin/python\n## -*- coding: UTF-8 -*-\n\nfrom twitter import *\nimport random #para # al azar\n\n#los access y consumer los obenemos de twitter\naccess_token='793851762-n5g6OOTHPcnlKbfPdIK71svZ1a1ydgzbVRKeU0iR'\naccess_token_secret='7ppuW249zibj0BKCwBkw8LvUxaKzzdYjzdmlFRYO9w6SC'\nconsumer_key='XZ6cKayf2OhmTWHkdODJarYPj'\nconsumer_secret='rkMPWIunDY1QJyQfX8Z4MhJ3nklnzoYONjUvsA9lIJSiWVCAFY'\n\nt = Twitter(auth=OAuth(access_token, access_token_secret, consumer_key, consumer_secret))\n\n#parar ver los 2 ultimos tweets\n#x = t.statuses.home_timeline(count=2)\n#print x\n\nfrases= [\"Hoy es un dia genias\", \"probando arrays\", \"tweet unsando arrays\", \"Esto es una prueba\"]\n#frace= len(fraces)\n#num= random.randint(0,frace)\n#mensaje=frases[num]\nx= random.choice(frases)\n\n#para actualizar estado en twitter\nt.statuses.update(status=x)\n","sub_path":"twitter/arraytweet.py","file_name":"arraytweet.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"541557460","text":"\"\"\"\r\nThis script was created by Sergey Tomin for Workshop: Designing future X-ray FELs. Source and license info is on GitHub.\r\nAugust 2016.\r\n\"\"\"\r\n# this python library provides generic shallow (copy) and deep copy (deepcopy) operations\r\nfrom copy import deepcopy\r\n\r\n# import from Ocelot main modules and functions\r\nfrom ocelot import *\r\n\r\n# import from Ocelot graphical modules\r\nfrom ocelot.gui.accelerator import *\r\n\r\nfrom ocelot.adaptors.astra2ocelot import *\r\n\r\n# import injector lattice\r\nfrom ocelot.test.workshop.injector_lattice import *\r\n\r\nlat = MagneticLattice(cell)\r\n\r\n# initialization of Twiss object\r\ntws0 = Twiss()\r\n# defining initial twiss parameters\r\ntws0.beta_x = 29.171\r\ntws0.beta_y = 29.171\r\ntws0.alpha_x = 10.955\r\ntws0.alpha_y = 10.955\r\n# defining initial electron energy in GeV\r\ntws0.E = 0.005\r\n\r\n# calculate twiss functions with initial twiss parameters\r\ntws = twiss(lat, tws0, nPoints=None)\r\ntws1 = tws[-1]\r\nprint(tws[-1])\r\n# ploting twiss paramentrs.\r\nplot_opt_func(lat, tws, top_plot=[\"Dx\"], fig_name=\"i1\", legend=False)\r\n\r\n# Loading of beam distribution\r\np_array_init = astraBeam2particleArray(filename='beam_130MeV.ast')\r\n\r\n\r\n# initialization of tracking method\r\nmethod = MethodTM()\r\n\r\n# for second order tracking we have to choose SecondTM\r\nmethod.global_method = SecondTM\r\n\r\n# for first order tracking uncomment next line\r\n# method.global_method = TransferMap\r\n\r\n# we will start simulation from the first quadrupole (QI.46.I1) after RF section.\r\n# you can change stop element (and the start element, as well)\r\n# START_73_I1 - marker before Dog leg\r\n# START_96_I1 - marker before Bunch Compresion\r\n\r\nlat = MagneticLattice(cell, start=QI_46_I1, stop=None, method=method)\r\n\r\n\r\nnavi = Navigator(lat)\r\np_array = deepcopy(p_array_init)\r\ntws_track, p_array = track(lat, p_array, navi)\r\n\r\n# you can change top_plot argument, for example top_plot=[\"alpha_x\", \"alpha_y\"]\r\nplot_opt_func(lat, tws_track, top_plot=[\"E\"], fig_name=0, legend=False)\r\nplt.show()\r\n\r\n# Current profile\r\nbins_start, hist_start = get_current(p_array, charge=p_array.q_array[0], num_bins=200)\r\n\r\nplt.figure(4)\r\nplt.title(\"current: end\")\r\nplt.plot(bins_start*1000, hist_start)\r\nplt.xlabel(\"s, mm\")\r\nplt.ylabel(\"I, A\")\r\nplt.grid(True)\r\nplt.show()\r\n\r\n# Beam distribution\r\n\r\ntau = np.array([p.tau for p in p_array])\r\ndp = np.array([p.p for p in p_array])\r\nx = np.array([p.x for p in p_array])\r\ny = np.array([p.y for p in p_array])\r\n\r\nax1 = plt.subplot(311)\r\nax1.plot(-tau*1000, x*1000, 'r.')\r\nplt.setp(ax1.get_xticklabels(), visible=False)\r\nplt.ylabel(\"x, mm\")\r\nplt.grid(True)\r\n\r\nax2 = plt.subplot(312, sharex=ax1)\r\nax2.plot(-tau*1000, y*1000, 'r.')\r\nplt.setp(ax2.get_xticklabels(), visible=False)\r\nplt.ylabel(\"y, mm\")\r\nplt.grid(True)\r\n\r\nax3 = plt.subplot(313, sharex=ax1)\r\nax3.plot(-tau*1000, dp, 'r.')\r\nplt.ylabel(\"dp/p\")\r\nplt.xlabel(\"s, mm\")\r\nplt.grid(True)\r\nplt.show()","sub_path":"2_tracking.py","file_name":"2_tracking.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"540074073","text":"import os\r\nimport sys\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport scipy.stats as stats\r\nimport scipy.spatial.distance as dist\r\n\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.ensemble import AdaBoostClassifier\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nimport math\r\nfrom config_reader import read_aipw, read_hound\r\n\r\nROUND_DECIMALS=int(read_aipw('ROUND_DECIMALS'))\r\nCV_THRESHOLD=float(read_aipw('CV_THRESHOLD'))\r\nZERO_GROUP=int(read_aipw('ZERO_GROUP'))\r\nMIN_TREATMENT_NUM_INSTANCES = int(read_aipw('MIN_TREATMENT_NUM_INSTANCES'))\r\nRANDOM_SEED=int(read_aipw('RANDOM_SEED'))\r\noutput_dir=read_hound('OUTPUT_DIRECTORY')\r\n\r\n#######################################################\r\ndef hound_base_aipw(data_object, job_header, condition = None):\r\n\r\n features = data_object.features\r\n jobstring = data_object.jobstring\r\n response = data_object.response\r\n rdd = data_object.rdd\r\n check_dict = data_object.check.value\r\n pval_dict = data_object.pval.value\r\n\r\n def rddMinMaxScaler(kv):\r\n jobid=kv[0];\r\n instances=kv[-1];\r\n array=np.array(instances);\r\n scaled = MinMaxScaler().fit_transform(array);\r\n return (jobid, scaled);\r\n\r\n def similaritySearch(vec, vecs):\r\n dfunc = dist.euclidean\r\n distances=[];\r\n for idx in range(len(vecs)):\r\n distances.append(dfunc(vec, vecs[idx]));\r\n return np.argmin(distances);\r\n\r\n #######################################################\r\n def rddRubinCausalInference(kv):\r\n job = kv[0]\r\n jobid = job[0] if condition else job;\r\n instances=kv[-1];\r\n (row,col)=instances.shape;\r\n # unpack\r\n\r\n result =[]; #Format: (Feature, T0, T1, T, Y0, Y1, Y_ATE)\r\n \r\n os.makedirs('logs', exist_ok=True)\r\n f=open(\"logs/AIPW-\" + \"-\" +str(jobid)+ \".txt\", \"w+\");\r\n f.write(\"==========Log==========\\n\");\r\n\r\n for idx_column in range(col-1):#Iterating on features\r\n column= instances[:, idx_column];\r\n cv=stats.variation(column)\r\n if(math.isnan(cv) or cv<= CV_THRESHOLD):#Low or zero variance column\r\n result.append( (features[idx_column], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) );\r\n continue;\r\n\r\n median = np.median(column);\r\n if(np.sum(column=median)<=0):\r\n median=0.5;\r\n # weird\r\n\r\n seg_instances = [instances[np.array(range(row))[column=median], :] ];\r\n seg_features = [ np.hstack( ( seg_instances[0][:, 0:idx_column], (seg_instances[0])[:, idx_column+1:-1]) ), np.hstack( ( (seg_instances[1])[:, 0:idx_column], (seg_instances[1])[:, idx_column+1:-1]) ) ];\r\n seg_treatment = [ (seg_instances[0])[:, idx_column], (seg_instances[1])[:, idx_column] ];\r\n seg_response = [ (seg_instances[0])[:, -1], (seg_instances[1])[:, -1] ];\r\n num_t0 = len(seg_instances[0]);\r\n num_t1 = len(seg_instances[1]);\r\n\r\n if(min(num_t0, num_t1)<=ZERO_GROUP):#Null treatment or controlled group\r\n T0=0.0;\r\n T1=0.0;\r\n Y0=0.0;\r\n Y1=0.0;\r\n\r\n elif(min(num_t0, num_t1)<=MIN_TREATMENT_NUM_INSTANCES):#Minimum number of instances for statistical analysis\r\n idx_small = int(num_t0>num_t1);\r\n idx_big = int(num_t0<=num_t1);\r\n matches =[];\r\n for instance_feature in seg_features[idx_small]:\r\n idx_match = similaritySearch(instance_feature, seg_features[idx_big]);\r\n matches.append(idx_match);\r\n matched_treatement = seg_treatment[idx_big][matches];\r\n matched_response = seg_treatment[idx_big][matches];\r\n\r\n if(idx_small == 0):\r\n T0=np.mean(seg_treatment[0]);\r\n T1=np.mean(matched_treatement);\r\n Y0=np.mean(seg_response[0]);\r\n Y1=np.mean(matched_response)\r\n elif(idx_big == 0):\r\n T0 = np.mean(matched_treatement);\r\n T1 = np.mean(seg_treatment[1]);\r\n Y0 = np.mean(matched_response);\r\n Y1 = np.mean(seg_response[1]);\r\n\r\n else:#AdaBosst IPW Estimator\r\n T0=np.mean(seg_treatment[0]);\r\n T1=np.mean(seg_treatment[1]);\r\n adaboost_y0=[0]*num_t0;\r\n adaboost_y1=[1]*num_t1;\r\n adaboost_y=np.array(adaboost_y0+adaboost_y1);\r\n adaboost_x=np.vstack( (seg_features[0], seg_features[1]) );\r\n boost=AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), algorithm=\"SAMME.R\", n_estimators=max(300, int(pow(len(adaboost_y),0.85))), random_state=RANDOM_SEED);\r\n boost.fit(adaboost_x, adaboost_y);\r\n propensity_scores=boost.predict_proba(adaboost_x)[:, -1];#Propensity Score estimation\r\n propensity_scores_t0=propensity_scores[0:num_t0];\r\n propensity_scores_t1=propensity_scores[num_t0:];\r\n\r\n Y0=0.0;\r\n for idx in range(num_t0):\r\n y=seg_response[0][idx];\r\n ps=propensity_scores_t0[idx];\r\n if(ps>0.9):\r\n ps=0.9;\r\n Y0=Y0+y/(1.0-ps);\r\n Y0=Y0/float(num_t0+num_t1);\r\n Y1=0.0;\r\n for idx in range(num_t1):\r\n y=seg_response[1][idx];\r\n ps=propensity_scores_t1[idx];\r\n if(ps<0.1):\r\n ps=0.1;\r\n Y1=Y1+y/(ps);\r\n Y1=Y1/float(num_t0+num_t1);\r\n\r\n T_DIFF=T1-T0;\r\n Y_DIFF=Y1-Y0;\r\n\r\n CHECK_STATE=True;\r\n check_array=check_dict[jobid]\r\n pval_array=pval_dict[jobid]\r\n\r\n CHECK_THRESHOLD=0.05;\r\n if (abs(T_DIFF) 1/n_classes,input_features,false_sample)\n\n labels = tf.where(rnd_tiled_lbl > 1/n_classes,labels,false_lbl)\n\n input_features = tf.image.per_image_standardization(input_features)\n false_sample = tf.image.per_image_standardization(false_sample)\n\n return {'input_features':input_features,'labels':labels,'false_sample':false_sample}\n\ndef data_generator(data_generator,batch_size,is_training,\n shuffle_buffer = 128,\n is_validation=False,\n n_classes = 10,\n take_n=None,\n skip_n=None):\n \n dataset = tf.data.Dataset.from_generator(data_generator,\n output_types = {'input_features':tf.float32,\n 'labels':tf.int32,\n 'false_sample':tf.float32})\n\n if skip_n != None:\n dataset = dataset.skip(skip_n)\n if take_n != None:\n dataset = dataset.take(take_n)\n \n if is_training:\n dataset = dataset.shuffle(shuffle_buffer)\n dataset = dataset.batch(batch_size,drop_remainder=True)\n dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)\n else:\n dataset = dataset.batch(batch_size)\n dataset = dataset.prefetch(tf.data.experimental.AUTOTUNE)\n\n return dataset\n\ndef learning_rate_fn(epoch):\n\n if epoch >= 150 and epoch <200:\n return 0.1\n elif epoch >=200 and epoch <250:\n return 0.01\n elif epoch >=250:\n return 0.001\n else:\n return 1.0\n\n\nFLAGS = flags.FLAGS\nflags.DEFINE_string('model_dir', 'models/saved_models', 'save directory name')\nflags.DEFINE_string('data_dir', 'data/cornell_birdcall_recognition_mini', 'data directory name')\nflags.DEFINE_integer('epochs', 300, 'number of epochs')\nflags.DEFINE_integer('batch_size', 32, 'Mini-batch size')\nflags.DEFINE_float('dropout_rate', 0.0, 'dropout rate for the dense blocks')\nflags.DEFINE_float('weight_decay', 1e-4, 'weight decay parameter')\nflags.DEFINE_float('learning_rate', 5e-2, 'learning rate')\nflags.DEFINE_boolean('preload_samples',False,'Preload samples (requires >140 GB RAM)')\nflags.DEFINE_float('training_percentage', 90, 'Percentage of the training data used for training. (100-training_percentage is used as validation data.)')\n\nflags.DEFINE_boolean('load_model', False, 'Bool indicating if the model should be loaded')\n\n\ndef main(argv):\n \n try:\n task_id = int(os.environ['SLURM_ARRAY_TASK_ID'])\n except KeyError:\n task_id = 0\n\n model_save_dir = FLAGS.model_dir\n data_dir = FLAGS.data_dir\n print(\"Saving model to : \" + str(model_save_dir))\n print(\"Loading data from : \" + str(data_dir))\n test_data_dir = data_dir\n train_data_dir = data_dir\n epochs = FLAGS.epochs\n batch_size = FLAGS.batch_size\n dropout_rate = FLAGS.dropout_rate\n weight_decay = FLAGS.weight_decay\n lr = FLAGS.learning_rate\n load_model = FLAGS.load_model\n training_percentage = FLAGS.training_percentage\n preload_samples = FLAGS.preload_samples\n\n model_save_dir += \"_batch_size_\"+str(batch_size)+\"_dropout_rate_\"+str(dropout_rate)+\"_learning_rate_\"+str(lr)+\"_weight_decay_\"+str(weight_decay)\n\n ds_train = Dataset(data_dir,is_training_set = True)\n n_total = ds_train.n_samples\n \n def augment_fn(sample,training):\n return augment_input(sample,ds_train.n_classes,training)\n \n dg_train = DataGenerator(ds_train,augment_fn,\n training_percentage = training_percentage,\n preload_samples = preload_samples,\n is_training=True)\n \n dg_val = DataGenerator(ds_train,augment_fn,\n training_percentage = training_percentage,\n is_validation = True,\n preload_samples = preload_samples,\n is_training=False)\n n_train = int(n_total*training_percentage/100)\n n_val = n_total-n_train\n\n #ResNet 18\n classifier_model = Classifier(ResBlockBasicLayer,\n n_blocks = 4,\n n_layers = [2,2,2,2],\n strides = [2,2,2,2],\n channel_base = [64,128,256,512],\n n_classes = ds_train.n_classes+1,\n init_ch = 64,\n init_ksize = 7,\n init_stride = 2,\n use_max_pool = True,\n kernel_regularizer = tf.keras.regularizers.l2(2e-4),\n kernel_initializer = tf.keras.initializers.he_normal(),\n name = \"classifier\",\n dropout=dropout_rate)\n #Generator model used to augment to false samples\n generator_model = Generator(8,\n [8,8,16,16,32,32,64,64],\n kernel_regularizer = tf.keras.regularizers.l2(2e-4),\n kernel_initializer = tf.keras.initializers.he_normal(),\n name = \"generator\")\n \n #Discriminator for estimating the Wasserstein distance\n discriminator_model = Discriminator(3,\n [32,64,128],\n [4,4,4],\n name = \"discriminator\")\n \n train_data_gen = data_generator(dg_train.generate,batch_size,\n is_training=True,\n shuffle_buffer = 16*batch_size,\n n_classes = ds_train.n_classes,\n take_n=n_train)\n \n val_data_gen = data_generator(dg_val.generate,batch_size,\n is_training=False,\n is_validation = True,\n n_classes = ds_train.n_classes)\n \n \n summaries = Summaries(scalar_summary_names=[\"class_loss\",\n \"generator_loss\",\n \"discriminator_loss\",\n \"weight_decay_loss\",\n \"total_loss\",\n \"accuracy\"],\n image_summary_settings = {'train':['fake_features'],'n_images':1},\n learning_rate_names = ['learning_rate_'+str(classifier_model.model_name),\n 'learning_rate_'+str(generator_model.model_name),\n 'learning_rate_'+str(discriminator_model.model_name)],\n save_dir = model_save_dir,\n modes = [\"train\",\"val\",\"test\"],\n summaries_to_print={'train':['class_loss','generator_loss','discriminator_loss','accuracy'],\n 'eval':['total_loss','accuracy']})\n \n\n trainer = ModelTrainer(train_data_gen,\n val_data_gen,\n None,\n epochs,\n EvalFunctions,\n model_settings = [{'model':classifier_model,\n 'optimizer_type':tf.keras.optimizers.SGD,\n 'base_learning_rate':lr,\n 'learning_rate_fn':learning_rate_fn,\n 'init_data':tf.random.normal([batch_size,BINS,N_FRAMES,N_CHANNELS])},\n {'model':generator_model,\n 'optimizer_type':tf.keras.optimizers.Adam,\n 'base_learning_rate':lr*0.01,\n 'learning_rate_fn':learning_rate_fn,\n 'init_data':tf.random.normal([batch_size,BINS,N_FRAMES,N_CHANNELS])},\n {'model':discriminator_model,\n 'optimizer_type':tf.keras.optimizers.Adam,\n 'base_learning_rate':lr*0.02,\n 'learning_rate_fn':learning_rate_fn,\n 'init_data':tf.random.normal([batch_size,BINS,N_FRAMES,N_CHANNELS])}],\n summaries = summaries,\n num_train_batches = int(n_train/batch_size),\n load_model = load_model,\n save_dir = model_save_dir,\n input_keys = [\"input_features\",\"false_sample\"],\n label_keys = [\"labels\"],\n init_data = tf.random.normal([batch_size,BINS,N_FRAMES,N_CHANNELS]),\n start_epoch = 0)\n \n trainer.train()\n\nif __name__ == '__main__':\n app.run(main)\n \n","sub_path":"src/scripts/birdsong_simple_main.py","file_name":"birdsong_simple_main.py","file_ext":"py","file_size_in_byte":10068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"598652339","text":"import mpmath\nimport numpy as np\nfrom scipy.optimize import fsolve\nfrom single_e_class_unified import single_electron\nclass conv_model(single_electron):\n def linear_ramp_inv(self, t):\n inv_lap_func=lambda s: 1/(s**2*(s**(-self.dim_dict[\"psi\"])+self.dim_dict[\"tau\"]))\n inv_lap_val=mpmath.invertlaplace(inv_lap_func,t,method='talbot')\n if t i-j:\n emit_result[0][k][3] = 'L'+str(int(emit_result[0][k][3][1:])-1)\n j += 1\n\n for i in range(len(emit_result[0])):\n for key in emit_replace:\n if emit_result[0][i][1] != None:\n if emit_result[0][i][1] == key:\n emit_result[0][i][1] = emit_replace[key]\n if emit_result[0][i][2] != None:\n if emit_result[0][i][2] == key:\n emit_result[0][i][2] = emit_replace[key]\n \n\n\n'''\n语义分析结束\n'''\n\n\nimport yufafenxi as yufa\n\n\ndef create_siyuanshi():\n clear()\n r = yufa.create_tree()\n if r[0]:\n yffx(r[1])\n else:\n return r\n youhua()\n emit('End', None, None, None)\n return emit_result[0]\n\n\nif __name__ == \"__main__\":\n r = yufa.create_tree()\n yffx(r[1])\n youhua()\n emit('End', None, None, None)\n for i in range(len(emit_result[0])):\n print(i,':',emit_result[0][i])\n\n\n\n\n\n","sub_path":"cffx/yuyifenxi.py","file_name":"yuyifenxi.py","file_ext":"py","file_size_in_byte":8866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"343369781","text":"def solution(skill, skill_trees):\n answer = 0\n for i in range(len(skill_trees)):\n check = skill_trees[i].find(skill[0])\n result = True\n for j in range(1,len(skill)):\n index = skill_trees[i].find(skill[j]) # 없으면 -1\n if check > index and index != -1:\n result = False\n break\n if check ==-1 and index != -1:\n result = False\n break\n check=index\n if result == True :\n answer +=1 \n return answer","sub_path":"programmers/실코_스킬트리.py","file_name":"실코_스킬트리.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"417711991","text":"from contextlib import contextmanager\n\nimport pytest\nfrom tornado import gen\n\npytest.importorskip('hdfs3')\n\nfrom dask.imperative import Value\nfrom hdfs3 import HDFileSystem\n\nfrom distributed.utils_test import gen_cluster\nfrom distributed.utils import get_ip\nfrom distributed.hdfs import (read_binary, get_block_locations, write_binary,\n _read_csv)\nfrom distributed import Executor\nfrom distributed.executor import _wait\n\n\nip = get_ip()\n\n\n@contextmanager\ndef make_hdfs():\n hdfs = HDFileSystem(host='localhost', port=8020)\n if hdfs.exists('/tmp/test'):\n hdfs.rm('/tmp/test')\n hdfs.mkdir('/tmp/test')\n\n try:\n yield hdfs\n finally:\n if hdfs.exists('/tmp/test'):\n hdfs.rm('/tmp/test')\n\n\ndef test_get_block_locations():\n with make_hdfs() as hdfs:\n data = b'a' * int(1e8) # todo: reduce block size to speed up test\n fn_1 = '/tmp/test/file1'\n fn_2 = '/tmp/test/file2'\n\n with hdfs.open(fn_1, 'w', repl=1) as f:\n f.write(data)\n with hdfs.open(fn_2, 'w', repl=1) as f:\n f.write(data)\n\n L = get_block_locations(hdfs, '/tmp/test/')\n assert L == get_block_locations(hdfs, fn_1) + get_block_locations(hdfs, fn_2)\n assert L[0]['filename'] == L[1]['filename'] == fn_1\n assert L[2]['filename'] == L[3]['filename'] == fn_2\n\n\n@gen_cluster([(ip, 1)], timeout=60)\ndef dont_test_dataframes(s, a): # slow\n pytest.importorskip('pandas')\n n = 3000000\n fn = '/tmp/test/file.csv'\n with make_hdfs() as hdfs:\n data = (b'name,amount,id\\r\\n' +\n b'Alice,100,1\\r\\nBob,200,2\\r\\n' * n)\n with hdfs.open(fn, 'w') as f:\n f.write(data)\n\n e = Executor((s.ip, s.port), start=False)\n yield e._start()\n\n futures = read_binary(fn, hdfs=hdfs, delimiter=b'\\r\\n')\n assert len(futures) > 1\n\n def load(b, **kwargs):\n assert b\n from io import BytesIO\n import pandas as pd\n bio = BytesIO(b)\n return pd.read_csv(bio, **kwargs)\n\n dfs = e.map(load, futures, names=['name', 'amount', 'id'], skiprows=1)\n dfs2 = yield e._gather(dfs)\n assert sum(map(len, dfs2)) == n * 2 - 1\n\n\ndef test_get_block_locations_nested():\n with make_hdfs() as hdfs:\n data = b'a'\n\n for i in range(3):\n hdfs.mkdir('/tmp/test/data-%d' % i)\n for j in range(2):\n fn = '/tmp/test/data-%d/file-%d.csv' % (i, j)\n with hdfs.open(fn, 'w', repl=1) as f:\n f.write(data)\n\n L = get_block_locations(hdfs, '/tmp/test/')\n assert len(L) == 6\n\n\n@gen_cluster([(ip, 1), (ip, 2)], timeout=60)\ndef test_read_binary(s, a, b):\n with make_hdfs() as hdfs:\n assert hdfs._handle > 0\n data = b'a' * int(1e8)\n fn = '/tmp/test/file'\n\n with hdfs.open(fn, 'w', repl=1) as f:\n f.write(data)\n\n blocks = hdfs.get_block_locations(fn)\n assert len(blocks) > 1\n\n e = Executor((s.ip, s.port), start=False)\n yield e._start()\n\n futures = read_binary(fn, hdfs=hdfs)\n assert len(futures) == len(blocks)\n assert futures[0].executor is e\n results = yield e._gather(futures)\n assert b''.join(results) == data\n assert s.restrictions\n assert {f.key for f in futures}.issubset(s.loose_restrictions)\n\n\n@gen_cluster([(ip, 1), (ip, 2)], timeout=60)\ndef test_get_block_locations_nested(s, a, b):\n with make_hdfs() as hdfs:\n data = b'a'\n\n for i in range(3):\n hdfs.mkdir('/tmp/test/data-%d' % i)\n for j in range(2):\n fn = '/tmp/test/data-%d/file-%d.csv' % (i, j)\n with hdfs.open(fn, 'w', repl=1) as f:\n f.write(data)\n\n L = get_block_locations(hdfs, '/tmp/test/')\n assert len(L) == 6\n\n e = Executor((s.ip, s.port), start=False)\n yield e._start()\n\n futures = read_binary('/tmp/test/', hdfs=hdfs)\n results = yield e._gather(futures)\n assert len(results) == 6\n assert all(x == b'a' for x in results)\n\n\n@gen_cluster([(ip, 1), (ip, 2)], timeout=60)\ndef test_lazy_values(s, a, b):\n with make_hdfs() as hdfs:\n data = b'a'\n\n for i in range(3):\n hdfs.mkdir('/tmp/test/data-%d' % i)\n for j in range(2):\n fn = '/tmp/test/data-%d/file-%d.csv' % (i, j)\n with hdfs.open(fn, 'w', repl=1) as f:\n f.write(data)\n\n e = Executor((s.ip, s.port), start=False)\n yield e._start()\n\n values = read_binary('/tmp/test/', hdfs=hdfs, lazy=True)\n assert all(isinstance(v, Value) for v in values)\n\n while not s.restrictions:\n yield gen.sleep(0.01)\n assert not s.dask\n\n results = e.compute(*values, sync=False)\n results = yield e._gather(results)\n assert len(results) == 6\n assert all(x == b'a' for x in results)\n\n\n@gen_cluster([(ip, 1), (ip, 2)], timeout=60)\ndef test_write_binary(s, a, b):\n with make_hdfs() as hdfs:\n e = Executor((s.ip, s.port), start=False)\n yield e._start()\n\n data = [b'123', b'456', b'789']\n remote_data = yield e._scatter(data)\n\n futures = write_binary('/tmp/test/data/file.*.dat', remote_data, hdfs=hdfs)\n yield _wait(futures)\n\n assert len(hdfs.ls('/tmp/test/data/')) == 3\n with hdfs.open('/tmp/test/data/file.1.dat') as f:\n assert f.read() == b'456'\n\n\n futures = write_binary('/tmp/test/data2/', remote_data, hdfs=hdfs)\n yield _wait(futures)\n\n assert len(hdfs.ls('/tmp/test/data2/')) == 3\n\n\n@gen_cluster([(ip, 1), (ip, 1)], timeout=60)\ndef test_read_csv(s, a, b):\n with make_hdfs() as hdfs:\n e = Executor((s.ip, s.port), start=False)\n yield e._start()\n\n with hdfs.open('/tmp/test/1.csv', 'w') as f:\n f.write(b'name,amount,id\\nAlice,100,1\\nBob,200,2')\n\n with hdfs.open('/tmp/test/2.csv', 'w') as f:\n f.write(b'name,amount,id\\nCharlie,300,3\\nDennis,400,4')\n\n df = yield _read_csv('/tmp/test/*.csv', header=True, lineterminator='\\n')\n result, = e.compute(df.id.sum(), sync=False)\n result = yield result._result()\n assert result == 1 + 2 + 3 + 4\n\n\n@gen_cluster([(ip, 1), (ip, 1)], timeout=60)\ndef test_read_csv_lazy(s, a, b):\n with make_hdfs() as hdfs:\n e = Executor((s.ip, s.port), start=False)\n yield e._start()\n\n with hdfs.open('/tmp/test/1.csv', 'w') as f:\n f.write(b'name,amount,id\\nAlice,100,1\\nBob,200,2')\n\n with hdfs.open('/tmp/test/2.csv', 'w') as f:\n f.write(b'name,amount,id\\nCharlie,300,3\\nDennis,400,4')\n\n df = yield _read_csv('/tmp/test/*.csv', header=True, lazy=True, lineterminator='\\n')\n yield gen.sleep(0.5)\n assert not s.dask\n\n result = yield e.compute(df.id.sum(), sync=False)[0]._result()\n assert result == 1 + 2 + 3 + 4\n","sub_path":"distributed/tests/test_hdfs.py","file_name":"test_hdfs.py","file_ext":"py","file_size_in_byte":6994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"412723495","text":"#\r\n# @lc app=leetcode.cn id=526 lang=python3\r\n#\r\n# [526] 优美的排列\r\n#\r\n# https://leetcode-cn.com/problems/beautiful-arrangement/description/\r\n#\r\n# algorithms\r\n# Medium (59.06%)\r\n# Likes: 50\r\n# Dislikes: 0\r\n# Total Accepted: 3.4K\r\n# Total Submissions: 5.8K\r\n# Testcase Example: '2'\r\n#\r\n# 假设有从 1 到 N 的 N 个整数,如果从这 N 个数字中成功构造出一个数组,使得数组的第 i 位 (1 <= i <= N)\r\n# 满足如下两个条件中的一个,我们就称这个数组为一个优美的排列。条件:\r\n#\r\n#\r\n# 第 i 位的数字能被 i 整除\r\n# i 能被第 i 位上的数字整除\r\n#\r\n#\r\n# 现在给定一个整数 N,请问可以构造多少个优美的排列?\r\n#\r\n# 示例1:\r\n#\r\n#\r\n# 输入: 2\r\n# 输出: 2\r\n# 解释:\r\n#\r\n# 第 1 个优美的排列是 [1, 2]:\r\n# ⁠ 第 1 个位置(i=1)上的数字是1,1能被 i(i=1)整除\r\n# ⁠ 第 2 个位置(i=2)上的数字是2,2能被 i(i=2)整除\r\n#\r\n# 第 2 个优美的排列是 [2, 1]:\r\n# ⁠ 第 1 个位置(i=1)上的数字是2,2能被 i(i=1)整除\r\n# ⁠ 第 2 个位置(i=2)上的数字是1,i(i=2)能被 1 整除\r\n#\r\n#\r\n# 说明:\r\n#\r\n#\r\n# N 是一个正整数,并且不会超过15。\r\n#\r\n#\r\n#\r\n\r\n\r\n# @lc code=start\r\nclass Solution:\r\n def countArrangement(self, N: int) -> int:\r\n # 简单的回溯\r\n # 使用unused集合表示当前未被使用的数\r\n # 注意如果采用visit集合的话时间复杂度会有所提升, 因为每次都要遍历所有N\r\n # 注意unused集合不可以在循环中被改变, 所以需要作为一个变量传入函数中\r\n self.res = 0\r\n\r\n def dfs(i, unused):\r\n if i > N:\r\n self.res += 1\r\n return\r\n for n in unused:\r\n if n % i == 0 or i % n == 0:\r\n dfs(i + 1, unused - {n})\r\n\r\n dfs(1, set(range(1, N + 1)))\r\n return self.res\r\n\r\n\r\nif __name__ == '__main__':\r\n # print(Solution().countArrangement(3))\r\n print(\r\n Solution().countArrangement(5)\r\n ) # 12345, 14325, 21345, 24315,32145, 34125,41325,42315, 52341, 54321\r\n# @lc code=end\r\n","sub_path":"Medium/526.优美的排列.py","file_name":"526.优美的排列.py","file_ext":"py","file_size_in_byte":2169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"423691239","text":"import sys; sys.dont_write_bytecode = True; from utils import *\n\"\"\"\nStrings, lists, dicts:\nlmap, ints, positive_ints, floats, positive_floats, words\n\nData structures:\nLinked, UnionFind\ndict: d.keys(), d.values(), d.items()\ndeque: q[0], q.append and q.popleft\n\nList/Vector operations:\nGRID_DELTA, OCT_DELTA\nlget, lset, fst, snd\npadd, pneg, psub, pmul, pdot, pdist1, pdist2sq, pdist2\n\nMatrices:\nmatmat, matvec, matexp\n\"\"\"\n\n\n\ndef do_case(inp: str, sample=False):\n # READ THE PROBLEM FROM TOP TO BOTTOM OK\n def sprint(*a, **k): sample and print(*a, **k)\n lines = inp.splitlines()\n paras = inp.split(\"\\n\\n\")\n out = 0\n\n grid = lmap(list, lines)\n\n rows = len(grid)\n cols = len(grid[0])\n\n\n def next_grid(grid):\n new = copy.deepcopy(grid)\n\n for row in range(rows):\n for col in range(cols):\n cur = grid[row][col]\n neighbours = []\n\n for drow, dcol in OCT_DELTA:\n for i in range(1, 10000):\n if 0 <= row+drow*i < rows and 0 <= col+dcol*i < cols:\n new_thing = grid[row+drow*i][col+dcol*i]\n if new_thing != \".\":\n neighbours.append(new_thing)\n break\n else:\n break\n if cur == \"L\" and neighbours.count(\"#\") == 0:\n new[row][col] = \"#\"\n \n if cur == \"#\" and neighbours.count(\"#\") >= 5:\n new[row][col] = \"L\"\n \n return new\n \n new_grid = next_grid(grid)\n while new_grid != grid:\n grid, new_grid = new_grid, next_grid(new_grid)\n # out += 1\n \n print(flatten(grid).count(\"#\"))\n \n if out:\n print(\"out: \", out)\n return # RETURNED VALUE DOESN'T DO ANYTHING, PRINT THINGS INSTEAD\n\n\n\nrun_samples_and_actual([\n# Part 1\nr\"\"\"\nL.LL.LL.LL\nLLLLLLL.LL\nL.L.L..L..\nLLLL.LL.LL\nL.LL.LL.LL\nL.LLLLL.LL\n..L.L.....\nLLLLLLLLLL\nL.LLLLLL.L\nL.LLLLL.LL\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\"],[\n# Part 2\nr\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\",r\"\"\"\n\n\"\"\"], do_case)\n","sub_path":"2020/11/a-p2.py","file_name":"a-p2.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"307876473","text":"import numpy as np\nimport itertools\nfrom hopfield import HopfieldNet\n\n# ======= HELPER FUNCTIONS ===========\n\ndef get_clean_data():\n patterns = np.array([[-1, -1, 1, -1, 1, -1, -1, 1],\n [-1, -1, -1, -1, -1, 1, -1, -1],\n [-1, 1, 1, -1, -1, 1, -1, 1]])\n return patterns\n\n\ndef get_noisy_data():\n patterns = np.array([[ 1, -1, 1, -1, 1, -1, -1, 1],\n [ 1, 1, -1, -1, -1, 1, -1, -1],\n [ 1, 1, 1, -1, 1, 1, -1, 1]])\n return patterns\n\n\ndef calc_element_accuracy(patterns, preds):\n n_total = patterns.shape[0] * patterns.shape[1]\n n_correct = np.sum(patterns == preds)\n return n_correct / n_total\n\n\ndef calc_sample_accuracy(patterns, preds):\n n_total = patterns.shape[0]\n n_correct = 0\n for pattern, pred in zip(patterns, preds):\n if (pattern == pred).all():\n n_correct += 1\n return n_correct / n_total\n\n\n# ======= TESTING AND PLOTTING ===========\n\n\ndef test_noise_reduction():\n \"\"\"Apply the update rule repeatedly until you reach a stable \u001Cxed point. Did\n all the patterns converge towards stored patterns?\"\"\"\n\n clean_patterns = get_clean_data()\n noisy_patterns = get_noisy_data()\n\n net = HopfieldNet()\n net.fit(clean_patterns)\n noisy_preds = net.predict(noisy_patterns)\n print(noisy_preds)\n\n print('Element accuracy: {}'.format(calc_element_accuracy(clean_patterns, noisy_preds)))\n print('Sample accuracy: {}'.format(calc_sample_accuracy(clean_patterns, noisy_preds)))\n\n\ndef find_attractors():\n \"\"\"How many attractors are there in this network?\n Hint: automate the searching.\n\n 2^8 = 256 possible patterns makes brute force searching feasible. This function\n generates all possible patterns and feeds into the trained net. The predictions are saved,\n and filtered so that only one copy of each prediction remains. This set should be the full\n set of attractors.\"\"\"\n\n clean_patterns = get_clean_data()\n net = HopfieldNet()\n net.fit(clean_patterns)\n\n preds = []\n combinations = itertools.product([0,1], repeat=8)\n for comb in combinations:\n preds.append(net.predict(comb))\n\n unique_preds = list(set(tuple(x) for x in preds))\n print(\"Number of attractors: {}\".format(len(list(unique_preds))))\n\n\ndef test_more_noisy():\n \"\"\"What happens when you make the starting pattern even more dissimilar\n to the stored ones (e.g. more than half is wrong)?\"\"\"\n\n clean_patterns = get_clean_data()\n noisy_patterns = np.array([[1, 1, -1, 1, 1, -1, -1, 1],\n [1, 1, 1, 1, -1, 1, -1, -1],\n [1, -1, -1, 1, -1, 1, -1, 1]])\n\n net = HopfieldNet(min_iter=1, max_iter=5)\n net.fit(clean_patterns)\n noisy_preds = net.predict(noisy_patterns)\n\n print('Element accuracy: {}'.format(calc_element_accuracy(clean_patterns, noisy_preds)))\n print('Sample accuracy: {}'.format(calc_sample_accuracy(clean_patterns, noisy_preds)))\n\n\n\nif __name__ == '__main__':\n print(\"----Test little noise----\")\n test_noise_reduction()\n # 2 of 3 converged correctly to stored pattern, one converged to incorrect pattern\n print(\"----Find attractors----\")\n find_attractors()\n # 11 attractors\n print(\"----Test more noise----\")\n test_more_noisy()\n # no converge to correct\n","sub_path":"lab3/3_1.py","file_name":"3_1.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"325344017","text":"import numpy as np\nfrom skimage.filters import gaussian\n\n\n# 値を-1から1に正規化する関数\ndef normalize_x(image):\n image = image/127.5 - 1\n return image\n\n\n# 値を0から1に正規化する関数\ndef normalize_y(image):\n image = image/255\n return image\n\n\n# 値を0から255に戻す関数\ndef denormalize_y(image):\n image = image*255\n return image\n\n\ndef annotation_to_input(label_ermito):\n er = (label_ermito == 1)*255\n mito = (label_ermito == 2)*255\n er = normalize_y(er)\n mito = normalize_y(mito)\n er_anno = np.zeros_like(er)\n mito_anno = np.zeros_like(mito)\n er = gaussian(er, sigma=2)*255\n mito = gaussian(mito, sigma=2)*255\n er_anno[:, :] = er\n mito_anno[:, :] = mito\n anno = np.concatenate([er_anno[:, :, np.newaxis], mito_anno[:, :, np.newaxis]], 2)\n anno = normalize_x(anno[np.newaxis, :, :, :])\n return anno\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"193231094","text":"import re, sys\r\n\"\"\"\r\ncheat sheet and remeber note\r\nThe DNA Sharp Programing Language works with a series of sets of 4 where the instructions are [^ ATGC] and has no instruction limit\r\n\r\nCommand \tBrainfuck equivalent \tC-equivalent \tSymbols for symbol form\r\nATAT \t> \tpointer++ / newpointer++ *** \t>\r\nATGC \t< \tpointer-- / newpointer-- *** \t<\r\nATTA \t+ \t\t+\r\nATCG \t- \t\t-\r\nGCAT \t. (Output as ASCII) \t\t.\r\nGCGC \t, (ASCII input) \t\t,\r\nGCTA \t[ \t\t[\r\nGCCG \t] \t\t]\r\nTAAT * \t\t*pointer = *newpointer \t= or := ****\r\nTAGC * \t\t*pointer += *newpointer \t+=\r\nTATA * \t\t*pointer -= *newpointer \t-=\r\nTACG * \t\t*pointer *= *newpointer \t*=\r\nCGAT * \t\t*pointer /= *newpointer \t/=\r\nCGGC \t\t. (Output as integer value) \t~\r\nCGTA \t\t, (Integer input) \t?\r\nCGCG \t\t- (NOP) \tX** \r\n\"\"\"\r\nfname = sys.argv[1]\r\n\r\nwith open(fname, \"r\") as f:\r\n code = f.read()\r\ncode = re.sub(\"[^ATCG]\",\"\",code)\r\n#regular expreion [ATCG] only can be used in code\r\ncode = [code[i:i+4] for i in range(0,len(code),4)]\r\n#select in size of instruccion with length 4\r\npos = 0\r\n#position in code can use for debug an error \r\npnt = 0\r\n#ponter is a index of code, where is in code\r\ntape = [0]\r\ncomnt = \"####\"\r\n#tape is a secence\r\ndef npointfunc(action):\r\n # funtion is a indual intruccion \r\n global pos, pnt, tape ,comnt\r\n #Take the global variables to make them own in fuction\r\n oldpnt = tape[pnt]\r\n\r\n pos += 1\r\n #read the code moving in the secuence\r\n while code[pos] != \"CGCG\" and not (comnt in code[pos]) :\r\n #while instruccion are difernt to CGCG execute code\r\n eval(code[pos].lower()+'()')\r\n #pass the code to python interpreter\r\n else :\r\n code[pos] = code[pos+1]\r\n pos+=1\r\n newpnt = tape[pnt]\r\n tape[pnt] = oldpnt\r\n #extract the intruccion of sequence and the old instruccion go to secence\r\n exec('tape[pnt]'+action+'newpnt')\r\n#register sintaxis\r\ndef atat():\r\n #sum 1 to pointer ,ponter is a regitrer address in memory and sum 1 is move in memory\r\n global pos, pnt, tape ,comnt\r\n pnt += 1\r\n #if length of tape == pnt add a other element to array\r\n if len(tape) == pnt:\r\n tape += [0]\r\n \r\n pos += 1\r\n\r\ndef atgc():\r\n #this is to go back a record or a pointer\r\n global pos, pnt, tape ,comnt\r\n pnt -= 1\r\n \r\n if pnt < 0:\r\n comm = code[pos]\r\n print(\"error in \",comm,\"in intruccion\" ,str(pos))\r\n #raise RuntimeError(\"Pointer fell off tape at position \"+str(pos))\r\n \r\n pos += 1\r\n \r\ndef atta():\r\n #this is going to add 1 value of a ponter\r\n global pos, pnt, tape ,comnt\r\n tape[pnt] += 1\r\n \r\n pos += 1\r\n \r\ndef atcg():\r\n #This goes back 1 number in the pointer\r\n global pos, pnt, tape ,comnt\r\n tape[pnt] -= 1\r\n \r\n pos += 1\r\n#input /output\r\ndef gcta():\r\n #read pointer\r\n global pos, pnt, tape ,comnt\r\n \r\n if tape[pnt] == 0:\r\n while code[pos] != \"GCCG\" and not (comnt in code[pos]) :\r\n pos += 1\r\n pos += 1\r\n\r\n else:\r\n pos += 1\r\n tpos = pos\r\n while tape[pnt] > 0:\r\n pos = tpos\r\n while code[pos] != \"GCCG\":\r\n eval(code[pos].lower()+'()'+\"\")\r\n\r\n pos += 1\r\n\r\ndef gcat():\r\n #print char in part of sequense \r\n global pos, pnt, tape ,comnt\r\n \r\n print(chr(tape[pnt]),end='')\r\n \r\n pos += 1\r\n \r\ndef gcgc():\r\n #key board input\r\n global pos, pnt, tape ,comnt\r\n \r\n tape[pnt] = ord(input())\r\n \r\n pos += 1\r\n \r\ndef cggc():\r\n #print a part of sequence\r\n global pos, pnt, tape ,comnt\r\n \r\n print(tape[pnt],end='')\r\n \r\n pos += 1\r\n\r\ndef cgta():\r\n #int input\r\n global pos, pnt, tape ,comnt\r\n\r\n \r\n tape[pnt] = int(input())\r\n \r\n pos += 1\r\n#arimetic operators betten part of sequence and new pointer\r\ndef taat():\r\n npointfunc('=')\r\n\r\ndef tagc():\r\n npointfunc('+=')\r\n\r\ndef tata():\r\n npointfunc('-=')\r\n\r\ndef tacg():\r\n npointfunc('*=')\r\n\r\ndef cgat():\r\n npointfunc('/=')\r\n\r\ndef cgcg():\r\n #pass\r\n global pos, pnt, tape ,comnt\r\n\r\n \r\n pos += 1\r\n\"\"\"\r\nwork in\r\ndef coment(coment):\r\n # funtion is a indual intruccion \r\n global pos, pnt, tape ,comnt\r\n #Take the global variables to make them own in fuction\r\n oldpnt = tape[pnt]\r\n #read the code moving in the secuence\r\n pos += 1\r\n while str(coment) in code[pos] :\r\n #while instruccion are difernt to CGCG\r\n \r\n eval(coment + code[pos].lower + coment+\"\\n\")\r\n #break\r\n #pass the code to python interpreter\r\n else :\r\n code[pos] = code[pos+1]\r\n pos+=1\r\n newpnt = tape[pnt]\r\n tape[pnt] = oldpnt\r\n exec('coment'+\"#\"+\"code[pos]\"+'coment'+\"\\n\")\r\n \r\ndef simplecoment():\r\n #comment\r\n \r\n global pos, pnt, tape ,comnt\r\n coment(comnt)\r\n \r\n\r\n \r\n \r\n\r\n\"\"\"\r\n\r\n\r\n \r\n#if \"#\" in code[pos]:\r\n# code[pos] = code[pos+1]\r\nwhile pos < len(code) and not (comnt in code[pos]):\r\n#comment\r\n\r\n comm = code[pos]\r\n eval(comm.lower() + \"()\")\r\n#else :\r\n# code[pos] = code[pos+1]\r\n# pos+=1\r\n#\r\n#comm = code[pos-1]\r\n#print(\"error in \",comm,\"in intruccion\" ,str(pos))\r\n","sub_path":"dnaint.py","file_name":"dnaint.py","file_ext":"py","file_size_in_byte":5082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"532125801","text":"from flask import Flask, render_template,request, redirect,flash\r\nfrom youtube_dl_master.youtube_dl import YoutubeDL\r\nfrom youtube_dl_master.youtube_dl import *\r\nfrom Forms import MusicSearchForm\r\nfrom Forms import LoginForm\r\nfrom flask_sqlalchemy import SQLAlchemy\r\n\r\napp = Flask(__name__)\r\napp.config.from_object('config')\r\ndb = SQLAlchemy(app)\r\n\r\n\"\"\"\r\n@app.route(\"login/\",methods=['GET','POST'])\r\n\r\ndef index():\r\n form=form = LoginForm()\r\n search = MusicSearchForm(request.form)\r\n\"\"\"\r\n\"\"\"\r\n@app.route('/')\r\n@app.route('/index')\r\ndef index():\r\n user = {'nickname': 'cch'} # fake user\r\n return render_template('index.html',\r\n title='Home',\r\n user=user)\r\n\r\n\"\"\"\r\n@app.route('/')\r\ndef home():\r\n return \"welcome to first app\"\r\n@app.route('/login', methods=['GET', 'POST'])\r\ndef login():\r\n form = LoginForm()\r\n if form.validate():\r\n flash('Login requested for OpenID=\"%s\", remember_me=%s' %(form.openid.data, str(form.remember_me.data)))\r\n return redirect('/index')\r\n\r\n return render_template('login.html', \r\n title='Sign In',\r\n form=form,\r\n providers=app.config['OPENID_PROVIDERS'])\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"597392292","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom sinaSpider.items import SinaFashionItem\nfrom myutils.utils import convertDatetime\n\n\nclass FashionSpider(scrapy.Spider):\n name = 'fashion'\n allowed_domains = ['roll.fashion.sina.com.cn']\n start_urls = ['http://roll.fashion.sina.com.cn/style/str1/index.shtml']\n\n\n # 取得大分类\n def parse(self, response):\n category_a_list = response.xpath('//div[@class=\"nav2\"]/div[@class=\"nc\"]/ul/li/a')[0:7]\n for category_a in category_a_list:\n category_a_href = category_a.xpath('@href').extract_first()\n category_a_text = category_a.xpath('text()').extract_first()\n\n # print(category_a_text)\n yield scrapy.Request(\n url=category_a_href,\n callback=self.parse_list,\n dont_filter=True,\n meta={\n 'category': category_a_text\n }\n )\n\n # 取得每个分类下的消息列表\n def parse_list(self, response):\n category = response.meta['category']\n info_div_list = response.xpath('//div[@class=\"ml\"]/div[@class=\"blk_01\"]/div')\n for info_div in info_div_list:\n # 标题\n title = info_div.xpath('h2/a/text()').extract_first()\n # 链接\n link = info_div.xpath('h2/a/@href').extract_first()\n # 简介\n intro = info_div.xpath('div[@class=\"clearfix\"]/div[@class=\"b_txt\"]/p/text()').extract_first()\n # 来源\n source = info_div.xpath('div[@class=\"clearfix\"]/div[@class=\"b_txt\"]/div/span[@class=\"wb_source\"]/text()').extract_first().split('|')[0]\n # 时间\n time = info_div.xpath('div[@class=\"clearfix\"]/div[@class=\"b_txt\"]/div/span[@class=\"wb_source\"]/text()').extract_first().split('|')[1].strip()\n time = convertDatetime(time) # 转换为datetime能转换的格式\n\n item = SinaFashionItem()\n item['title'] = title\n item['category'] = category\n item['f_url'] = link\n item['intro'] = intro\n item['source'] = source\n item['time'] = time\n\n yield item\n\n next_url = response.xpath('//span[@class=\"pagebox_next\"]/a/@href').extract_first()\n if next_url:\n # http://roll.fashion.sina.com.cn/style/str1/index_5.shtml\n # ./index_6.shtml\"\n url = response.url.replace((response.url).split('/')[-1], next_url.split('/')[-1])\n yield scrapy.Request(\n url=url,\n callback=self.parse_list,\n dont_filter=True,\n meta={\n 'category': category\n }\n )","sub_path":"sinaSpider/sinaSpider/spiders/fashion.py","file_name":"fashion.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"232289223","text":"\ndef get_text():\n with open(\"shakespeare-complete-works.txt\", \"r+\", encoding=\"utf-8-sig\") as f:\n return ''.join(e for e in f.read().lower() if e in \"qwertyuiopasdfghjklzxcvbnm -'\")\n\n\nclass Node:\n def __init__(self, char=\"*\", key=-1):\n self.char = char\n self.children = {}\n self.key = key\n\n def is_not_key(self):\n return self.key == -1\n\n def is_key(self):\n return self.is_not_key() is False\n\n\nclass suffix_tree:\n def __init__(self, txt):\n self.root = Node()\n self.txt = txt + \"$\"\n\n # Get every \"word\" in the txt\n for w_idx in range(len(txt)):\n self.add_node(self.root, w_idx)\n\n def validate_tree(self, p=False):\n count = {\"count\": 0}\n ca = []\n\n def iterate_tree(n, d):\n d[\"count\"] = d[\"count\"] + 1\n if n.is_key():\n ca.append(n.key)\n if p:\n print(n.key, self.txt[n.key:])\n for n in n.children.values():\n iterate_tree(n, d)\n\n iterate_tree(self.root, count)\n\n r1 = len(set(ca))\n r2 = len(self.txt) - 1\n r3 = max(ca) + 1\n valid = r1 == r2 == r3\n if p:\n print(\"\")\n print(\"Nodes: \", count[\"count\"])\n print(\"Text length: \", r2)\n print(\"Words in tree:\", r1)\n print(\"\\nTree valid:\", valid)\n if p:\n print(\"\\nFirst 100 keys:\", ca[:100])\n\n return valid\n\n def add_node(self, node, w_idx):\n\n # Get every \"char_index\" of word\n for i in range(len(self.txt) - w_idx):\n\n # Extend its properties into a child\n if node.is_key():\n\n nnc = self.txt[node.key + i]\n node.children[nnc] = Node(nnc, node.key)\n node.key = -1\n\n # Desired char\n char = self.txt[w_idx + i]\n\n # if child doesnt exist create it and break\n if char not in node.children:\n\n node.children[char] = Node(char, w_idx)\n break\n\n node = node.children[char]\n\n def search(self, word):\n\n node = self.root\n s = f\"({node.char})\"\n\n # Find deepest node containing our \"word\"\n for char in word:\n\n if char in node.children:\n node = node.children[char]\n s += f\" ({node.char})\"\n else:\n break\n\n print(s, list(map(lambda x: x.char, node.children.values())))\n\n node_idxs = []\n\n def iterate_tree(n, node_idxs):\n if n.is_key() and word == self.txt[n.key:n.key + len(word)]: # and word == self.txt[n.key:len(word)]:\n #print(word, n.key, \"-\" + self.txt[n.key:n.key + len(word)] + \"-\")\n node_idxs.append(n.key)\n\n for n in n.children.values():\n iterate_tree(n, node_idxs)\n\n iterate_tree(node, node_idxs)\n\n return node_idxs\n\n\ntxt = \"ATTAGTACA\"\n#txt = \"lars elsker at spise pizza med sin son daniel, lars er en fisk\"\ntxt = get_text()[:100000]\n# txt = \"banana\"\n# txt = \"lars er gift med gitte og har en fisk ved navn lars\"\nst = suffix_tree(txt)\nst.validate_tree()\n\n\nprint(\"\\n--------------------\\n\")\n\n# n = st.search(\"larsl\")\n# print(n)\n\n\n# ATTAGTACA$ -> w_idx 0:\n# 1. c_idx 0 doesnt exist -> create Node A -> set w_idx to 0\n# (*)\n# /\n# (A)\n# T\n# T\n# A\n# G\n# T\n# A\n# C\n# A\n# $\n\n# TTAGTACA$ -> w_idx 1:\n# 1. c_idx 1 doesnt exist -> create Node T -> set w_idx to 1\n# (*)\n# / \\\n# (A) (T)\n# T T\n# T A\n# A G\n# G T\n# T A\n# A C\n# C A\n# A $\n# $\n\n# TAGTACA$ -> w_idx 2:\n# 1. c_idx 2 already exist -> jump into Node T\n# 2. (\"T\" != \"A\") -> split into Node(T) and Node(A)\n# 3. create Node(T) and add to parrent Node(T) -> set w_idx to parrent Node(T)s w_idx\n# 4. create Node(A) and add to parrent Node(T) -> set w_idx to curent w_idx 2\n# (*)\n# / \\\n# (A) (T)\n# T / \\\n# T (T) (A)\n# A A G\n# G G T\n# T T A\n# A A C\n# C C A\n# A A $\n# $ $\n\n# AGTACA$ -> w_idx 3:\n# 1. c_idx 3 already exist -> jump into Node A\n# 2. (\"G\" != \"T\") -> split into Node(G) and Node(T)\n# (*)\n# / \\\n# / \\\n# (A) (T)\n# / \\ / \\\n# (G) (T) (T) (A)\n# T T A G\n# A A G T\n# C G T A\n# A T A C\n# $ A C A\n# C A $\n# A $\n# $\n\n# etc ...\n\n#-------------------------------------\n\n\n# BBBB$ -> w_idx 0:\n#\n# c_idx 0/4: doesnt exist\n# -> create Node(B) -> set w_idx to 0\n# -> set Node(B) as child of current active Node(*)\n# -> break\n# (*) <-BEFORE\n# \\\n# (B) [0]\n# B\n# B\n# B\n# $\n#\n#-------------------------------------\n# BBB$ -> w_idx 1:\n#\n# c_idx 1/4: already exist -> jump into Node B\n# (c_idx(1, B) == Node.char)\n# (len(Node.children) == 0)\n# -> Create Node(B) set w_idx to active Node(B)s w_idx\n# -> Set current active Node as Child of new Node(B)\n# -> Set new Node(B) as active\n# (*) <-BEFORE\n# \\\n# (B) <-AFTER\n# \\\n# (B) [0]\n# B\n# B\n# $\n#\n# c_idx 2/4: already exist -> jump into Node B\n# (c_idx(2, B) == Node.char)\n# (len(Node.children) == 0)\n# -> Create Node(B) set w_idx to active Node(B)s w_idx\n# -> Set current active Node as Child of new Node(B)\n# -> Set new Node(B) as active\n# (*)\n# \\\n# (B) <-BEFORE\n# \\\n# (B) <-AFTER\n# \\\n# (B) [0]\n# B\n# $\n#\n# c_idx 3/4: already exist -> jump into Node B\n# (c_idx(3, B) == Node.char)\n# -> Create Node(B) set w_idx to active-Node(B)s w_idx\n# -> Set current active Node as Child of new Node(B)\n# -> Set new Node(B) as active\n# (*)\n# \\\n# (B)\n# \\\n# (B) <-BEFORE\n# \\\n# (B) <-AFTER\n# \\\n# (B) [0]\n# $\n#\n# c_idx 4/4: doesnt exist\n# -> create Node($) -> set w_idx to 1\n# -> set Node($) as child of current active Node(B)\n# -> break\n# (*)\n# \\\n# (B)\n# \\\n# (B)\n# \\\n# (B) <-BEFORE\n# / \\\n# [1] ($) (B) [0]\n# $\n#\n#-------------------------------------\n# BB$ -> w_idx 2:\n#\n# c_idx 2/4: (txt[c_idx] in node.children)\n# (node.is_key == false)\n# -> set node = node.children[txt[c_idx]]\n# (*) <-BEFORE\n# \\\n# (B) <-AFTER\n# \\\n# (B)\n# \\\n# (B)\n# / \\\n# [1] ($) (B) [0]\n# $\n#\n# c_idx 3/4: (txt[c_idx] in node.children)\n# (node.is_key == false)\n# -> set node = node.children[txt[c_idx]]\n# (*)\n# \\\n# (B) <-BEFORE\n# \\\n# (B) <-AFTER\n# \\\n# (B)\n# / \\\n# [1] ($) (B) [0]\n# $\n#\n# c_idx 4/4: (txt[c_idx] not in node.children)\n# -> create Node($) -> set key to 2\n# -> set Node($) as child of current active Node(B)\n# -> break\n# (*)\n# \\\n# (B)\n# \\\n# (B) <-BEFORE\n# / \\\n# [2] ($) (B)\n# / \\\n# [1] ($) (B) [0]\n# $\n#\n#-------------------------------------\n# B$ -> w_idx 3:\n#\n# c_idx 3/4: (txt[c_idx] in node.children)\n# (node.is_key == false)\n# -> set node = node.children[txt[c_idx]]\n# (*) <-BEFORE\n# \\\n# (B) <-AFTER\n# \\\n# (B)\n# / \\\n# [2] ($) (B)\n# / \\\n# [1] ($) (B) [0]\n# $\n#\n# c_idx 4/4: (txt[c_idx] not in node.children)\n# -> create Node($) -> set key to 3\n# -> set Node($) as child of current active Node(B)\n# -> break\n# (*)\n# \\\n# (B) <-BEFORE\n# / \\\n# [3] ($) (B)\n# / \\\n# [2] ($) (B)\n# / \\\n# [1] ($) (B) [0]\n# $\n#\n#-------------------------------------\n# $ -> w_idx 4:\n#\n# c_idx 4/4: (txt[c_idx] not in node.children)\n# -> create Node($) -> set key to 4\n# -> set Node($) as child of current active Node(*)\n# -> break\n#\n# (*)<-BEFORE\n# / \\\n# [4] ($) (B)\n# / \\\n# [3] ($) (B)\n# / \\\n# [2] ($) (B)\n# / \\\n# [1] ($) (B) [0]\n# $\n\n\n# PHILOSOPHI\n# (Does Node have desired Child)\n# / \\\n# NO / \\ YES\n# / \\\n# {Create Child & break} (Does Node have a key)\n# / \\\n# NO / \\ YES\n# __________________/______ ______\\________________________________________\n# | Set desired child | | Create a new Node as a child of current Node. |\n# |_as_our_new_active_Node__| | Give this new node, the current next char of |\n# | the active node and its key, and remove key |\n# | from current active node. |\n# |_Set_the_new_Node_as_our_active_Node.__________|\n#\n# (*) . (*) . (*)\n# \\ . \\ . \\\n# (B) [0] . (B) [0] --------- . (B)\n# \\ . \\ | . \\\n# (B) . (B) | . (B)\n# \\ . \\ | . \\\n# (B) . (B) | . (B)\n# / \\ . / \\ | . / \\\n# ($) (B) . ($) (B) <----- . [1] ($) (B) [0]\n# $ . $ . $\n\n\n# B->B->B->B->$\n# B->B->B->$\n\n\n#####\n\n#(*)\n# \\\n# (B -> BBB$)\n#\n\n#(*) (*)\n# \\ \\\n# (B -> BBB$) (B)\n# \\\n# ()\n\n\n# If note doesnt have child:\n# we create the child and return\n# Else:\n# note = note.children[c]\n#\n# if\n\n# (*)\n# (*) (*) (*) / | \\\n# / / \\ / | \\ / | \\\n# (L) (L) (A) (L)(A)(R) (L) (A) (R)\n# A A R A R L / R\n# R R L R L A (A)\n# L L A L A R /\n# A A R A R $ (R)\n# R R $ R $ [2] / \\\n# $ $ [1] $ [1] ($) (L)\n# [0] [0] [0] [3] A\n# R\n# $\n# [0]\n\n# import PySimpleGUI as sg\n\n# layout: list = [\n# [sg.InputText('', size=(16, 1), background_color='black', text_color='red', font=('Digital-7', 51), key=\"searchbar\")],\n# [sg.Text('Start typing!', size=(50, 10), background_color=\"#272533\", text_color='white', font=('Franklin Gothic Book', 14), key=\"result\")],\n# ]\n\n# window: object = sg.Window('At være eller ikke at være', layout=layout, margins=(10, 20), background_color=\"#272533\", return_keyboard_events=True)\n\n# while True:\n# event, values = window.read()\n\n# if event is None and type(event) is not str:\n# break\n# else:\n# try:\n# if len(values[\"searchbar\"]) > 0:\n# n = st.search(values[\"searchbar\"])\n# s = \"\"\n# for i in n[:10]:\n# s += str(i) + \" -> \" + txt[i:i + 40] + \"\\n\"\n# window['result'].update(value=s)\n# except:\n# window['result'].update(value=\"\")","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":11670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"247502997","text":"from tfport import *\r\nimport timport\r\nimport numpy as np\r\nimport pickle\r\nfrom imutils import paths\r\nfrom keras.models import load_model\r\nimport fussy_methods\r\nfrom keras.applications import imagenet_utils\r\nfrom keras.preprocessing.image import img_to_array\r\nfrom keras.preprocessing.image import load_img\r\nimport time\r\nimport os\r\nfrom pyexcel_ods import save_data\r\nfrom collections import OrderedDict\r\n\r\n# load evaluation data\r\nDATA_DIR = './evaluation/Kaggle'\r\ncategories = [DATA_DIR + '/Bckgs', DATA_DIR + '/Cracks']\r\n\r\n# get subfolders\r\nMASTER = './models_trained'\r\nSUB = [x[1] for x in os.walk(MASTER)][0]\r\nSUB.sort()\r\n\r\n# split dataset into 5 subsets\r\nsub_size = 2\r\ndatasets = 5\r\ni_min = [x * sub_size for x in list(range(0, datasets))]\r\n\r\n# add global ods output\r\ndata_global = OrderedDict()\r\ndict_data_global = {}\r\nfor i in range(0, datasets):\r\n dict_data_global.update({'{} dataset'.format(i + 1): []})\r\n dict_data_global['{} dataset'.format(i + 1)].append(['Network', 'Accuracy', 'Precision', 'Recall'])\r\n\r\nfor subfolder in SUB:\r\n # check if vanilla\r\n if 'vanilla' in subfolder:\r\n vanilla = True\r\n else:\r\n vanilla = False\r\n\r\n DIR = MASTER + '/' + subfolder\r\n CLS_PTH = DIR + '/fussy_model.cpickle'\r\n M_DIR = DIR + '/model'\r\n\r\n # add log\r\n log = open(DIR + '/log_{}.txt'.format(DATA_DIR.split('/')[-1]), 'w')\r\n\r\n # add local ods output\r\n data_local = OrderedDict()\r\n dict_data_local = {'{} metrics'.format(DATA_DIR.split('/')[-1]): []}\r\n dict_data_local['{} metrics'.format(DATA_DIR.split('/')[-1])].append(['Accuracy', 'Precision', 'Recall'])\r\n\r\n # Load and sort extracted models\r\n models_list = list(paths.list_files(M_DIR))\r\n\r\n # load classifier\r\n classifier = pickle.load(open(CLS_PTH, 'rb'))\r\n\r\n if not vanilla:\r\n keys = []\r\n models = []\r\n for model_path in models_list:\r\n keys.append(int(model_path.split('_')[-1].split('.')[0]))\r\n models.append(load_model(model_path))\r\n\r\n # sort models by keys\r\n models = [y for _, y in sorted(zip(keys, models))]\r\n else:\r\n models = [load_model(models_list[0])]\r\n\r\n # count parameters\r\n total_params = 0\r\n for model in models:\r\n total_params += model.count_params()\r\n\r\n print(\"[INFO] Total models parameters: {}\".format(total_params))\r\n\r\n for i in range(0, len(i_min)):\r\n # start timer\r\n start_time = time.time()\r\n iterator = 0\r\n\r\n # add confusion matrix\r\n TP = 0\r\n TN = 0\r\n FP = 0\r\n FN = 0\r\n\r\n # add log info\r\n dict_data_local['{} metrics'.format(DATA_DIR.split('/')[-1])].append(['Dataset', i + 1])\r\n\r\n for category in categories:\r\n # load dataset\r\n print(\"[INFO] Loading images...\")\r\n imagePaths = list(paths.list_images(category))\r\n print(\"[INFO] {} images loaded for {} class\".format(sub_size, categories.index(category)))\r\n\r\n # loop over images in both categories\r\n for image_path in imagePaths[i_min[i]:i_min[i] + sub_size]:\r\n # load and resize image\r\n image = load_img(image_path, target_size=(224, 224))\r\n image = img_to_array(image)\r\n\r\n # preprocess image by expanding and subtracting mean RGB value\r\n image = np.expand_dims(image, axis=0)\r\n image = imagenet_utils.preprocess_input(image)\r\n\r\n # pass images thr network\r\n if vanilla:\r\n features = models[0].predict(image)\r\n else:\r\n features = fussy_methods.extract_features_from_parts(models, image)\r\n # reshape features\r\n features = features.reshape((features.shape[0], 512 * 7 * 7))\r\n\r\n # make classification\r\n prediction = classifier.predict_proba(features)\r\n prediction = np.argmax(prediction[0])\r\n\r\n # assess prediction\r\n if categories.index(category) == 0 and prediction == 0:\r\n TN += 1\r\n if categories.index(category) == 1 and prediction == 1:\r\n TP += 1\r\n if categories.index(category) == 0 and prediction == 1:\r\n FP += 1\r\n if categories.index(category) == 1 and prediction == 0:\r\n FN += 1\r\n\r\n iterator += 1\r\n\r\n if iterator % 10 == 0:\r\n print('[INFO] {} out of {} images done in {} seconds'.format(iterator, len(imagePaths), time.time() - start_time))\r\n\r\n # stop timer\r\n stop_time = time.time()\r\n exec_time = stop_time - start_time\r\n print('[INFO] Execution time of dataset {}: {}s logged into log_{}.txt'.format(i, exec_time, DATA_DIR.split('/')[-1]))\r\n\r\n # compute metrics\r\n accuracy = (TP + TN) / iterator\r\n try:\r\n precision = TP / (TP + FP)\r\n except ZeroDivisionError:\r\n precision = 0\r\n try:\r\n recall = TP / (TP + FN)\r\n except ZeroDivisionError:\r\n recall = 0\r\n\r\n print('[INFO] model {} metrics:'.format(subfolder))\r\n print('[INFO] Dataset {}\\nAccuracy: {}\\nPrecision: {}\\nRecall: {}\\nSaved to log'.format(i, accuracy, precision, recall))\r\n\r\n # write to txt log\r\n log.write('[INFO] {} Dataset, part {}:\\n'.format(DATA_DIR.split('/')[-1], i + 1))\r\n log.write('[INFO] Execution time for {} images was {} seconds\\n'.format(iterator, exec_time))\r\n log.write('Accuracy: {}\\nPrecision: {}\\nRecall: {}\\n\\n'.format(accuracy, precision, recall))\r\n log.flush()\r\n\r\n # write to local ods log\r\n dict_data_local['{} metrics'.format(DATA_DIR.split('/')[-1])].append([accuracy, precision, recall])\r\n # write to global ods log\r\n dict_data_global['{} dataset'.format(i + 1)].append([subfolder, accuracy, precision, recall])\r\n\r\n data_local.update(dict_data_local)\r\n save_data(DIR + \"/log_{}.ods\".format(DATA_DIR.split('/')[-1]), data_local)\r\n\r\n # save log\r\n log.close()\r\n\r\n# save global log\r\ndata_global.update(dict_data_global)\r\nsave_data(MASTER + '/log_global.ods', data_global)\r\n\r\nprint('All done!')\r\n","sub_path":"Fussy TL/metrics_test.py","file_name":"metrics_test.py","file_ext":"py","file_size_in_byte":6257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"459482832","text":"# File: PalindromicSum.py\n\n# Description: This program determines the number having the longest cycle length in a user defined range.\n\n# Student Name: Janel Chumley\n\n# Date Created: 02/19/2016\n\n# Date Last Modified: 02/20/2016\n\n# This function takes a number and reverses the digits\ndef rev_num(n):\n rev_num = 0\n while (n > 0):\n rev_num = (rev_num * 10) + (n % 10)\n n = n // 10\n return (rev_num)\n\n# This function verifies is a number is a palindrome \ndef is_palindromic(n):\n return(n == rev_num(n))\n\ndef main():\n # Prompt user to enter starting and ending numbers.\n start = eval(input(\"\\nEnter starting number of the range: \"))\n finish = eval(input(\"\\nEnter ending number of the range: \"))\n\n # If input values don't pass range specifications, prompt user to enter both the starting and ending numbers again.\n while (start < 0) or (finish < 0) or (start > finish):\n start = eval(input(\"\\nEnter starting number of the range: \"))\n finish = eval(input(\"\\nEnter ending number of the range: \"))\n\n # This variable represents the longest cycle length\n max_cycle_count = 0\n # This variable represents the value with the longest cycle length\n max_num = 0\n # This is a for loop that will iterate through the values in the given range.\n for n in range(start, finish + 1): \n # This variable represents the current value in the cycle.\n num = n \n # This variable represents the total cycle step count. \n cycle_count = 0\n\n # This loop goes through all of the values and determines if it's a palindrome\n while (not is_palindromic(num)): \n num += rev_num(num)\n cycle_count += 1\n # This conditional will compare the values to determine the longest cycle length and its respective number.\n if (cycle_count > max_cycle_count):\n max_cycle_count = cycle_count\n max_num = n\n # We need to also consider cases when there are two or more values sharing a greatest cycle length. When this happens, the larger number is chosen.\n elif (cycle_count == max_cycle_count):\n if (num > max_num):\n max_cycle_count = cycle_count\n max_num = n \n # This will print the number with the longest cycle length and that cycle length\n print(\"\\nThe number \" + str(max_num) + \" has the longest cycle length of \" + str(max_cycle_count) + \".\")\nmain()\n","sub_path":"PalindromicSum.py","file_name":"PalindromicSum.py","file_ext":"py","file_size_in_byte":2472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"313841034","text":"from PIL import Image\nfrom imutils import face_utils\nfrom numpy import array\nfrom glob import glob\n\nimport os, sys\nimport argparse\nimport imutils\nimport cv2\nimport json\nimport collections\nimport dlib\nimport shutil \n\nimport re\nimport io\nimport math\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nfrom mpl_toolkits.mplot3d import Axes3D\n\nimport csv\n\nfrom copy import copy\n\nfrom pyagender import PyAgender\n\nagender = PyAgender() \n\n#use absolute paths\nABS_PATh = os.path.dirname(os.path.abspath(__file__)) + \"/\"\n\nimport argparse\n\n# Instantiate the parser\nparser = argparse.ArgumentParser(description='a utility')\n\nparser.add_argument('-d', '--dir_to_process', type=str, nargs='?',\n help='dir_to_process')\nparser.add_argument('-i', '--imgages_dir', type=str, nargs='?',\n help='imgages_dir')\nparser.add_argument('-x', '--img_extension', type=str, nargs='?',\n help='image extension')\nparser.add_argument('-v', '--verification_val', type=str, nargs='?',\n help='verification value')\nparser.add_argument('-n', '--gender_man_lbl', type=str, nargs='?',\n help='gender man label value')\n\n\nparser.add_argument('-o', '--out_to_dir',type=str, nargs='?',help='if provided output will be written to csv(semicolon separated) otherwise to stdout. ')\nparser.add_argument('-s', '--is_save_image', action='store_true', help='A boolean True False')\n\n# Argument are :-- shape_predictor_68_face_landmarks.dat\nparser.add_argument('-p', '--shape-predictor', type=str, nargs='?', help='path to facial landmark predictor')\n\nparser.add_argument('-m', '--merge_and_fit', action='store_true', help='A boolean True False')\n\nFLAGS = parser.parse_args()\n\nprint(FLAGS)\n\n\"\"\"\nThis file needs refactoring and especially removing the unused functions \n\"\"\"\n\n\ndetector = dlib.get_frontal_face_detector()\npredictor = dlib.shape_predictor(FLAGS.shape_predictor)\n\n\nif FLAGS.dir_to_process == \"\":\n paths = [] #specify static here\nelse:\n paths = [FLAGS.dir_to_process+\"/\" ]\n\n\n\ndef num_float_first(s):\n try:\n return float(s)\n except ValueError:\n return int(s)\n\ndef to_x_y(strng):\n cords = strng.split('~')\n\n # print(strng)\n # print(cords)\n #return np.array( [ float(cords[0]), float(cords[1]) ] )\n return [ num_float_first(cords[0]), num_float_first(cords[1]) ]\n\ndef to_x_y_z(strng):\n cords = strng.split('~')\n\n # print(strng)\n # print(cords)\n #return np.array( [ float(cords[0]), float(cords[1]) ] )\n return [ num_float_first(cords[0]), num_float_first(cords[1]), num_float_first(cords[2]) ]\n\ndef get_rotation_and_translation_matrix(csv_row, scale, imgpath_org):\n\n is_arc_rotation = True\n \n # Read Image\n imgpath = imgpath_org \n\n if is_arc_rotation:\n rotation_vector = []\n\n #\n # (lStart, lEnd) = FACIAL_LANDMARKS_IDXS[\"left_eye\"]\n # (rStart, rEnd) = FACIAL_LANDMARKS_IDXS[\"right_eye\"]\n lStart = to_x_y( csv_row[19] )\n lEnd = to_x_y( csv_row[23] )\n rStart = to_x_y( csv_row[24] )\n rEnd = to_x_y( csv_row[28] )\n\n leftEyePts = np.array( [lStart,lEnd] )\n rightEyePts = np.array( [rStart,rEnd] )\n\n # compute the center of mass for each eye\n leftEyeCenter = leftEyePts.mean(axis=0).astype(\"int\")\n rightEyeCenter = rightEyePts.mean(axis=0).astype(\"int\")\n \n # compute the angle between the eye centroids\n dY = rightEyeCenter[1] - leftEyeCenter[1]\n dX = rightEyeCenter[0] - leftEyeCenter[0]\n rotation_vector.append( np.degrees(np.arctan2(dY, dX)) ) # - 180 )\n\n #\n l = to_x_y( csv_row[3] )\n n = to_x_y( csv_row[35] )\n r = to_x_y( csv_row[17] )\n \n # compute the distances\n dAngle = (r[0]-n[0]) - (n[0]-l[0])\n dRatio = (r[0]-n[0]) * 2 if (r[0]-n[0]) > (n[0]-l[0]) else (n[0]-l[0]) * 2\n rotation_vector.append( np.degrees(np.arctan2(dAngle, dRatio)) ) # - 180 )\n\n rotation_vector.append( 0 )\n\n return rotation_vector, [], imgpath, \"\", \"1_\" + os.path.basename(imgpath), os.path.basename(os.path.dirname(imgpath)) + \".1/\"\n\ndef scale_if_small(imgpath, min_width_limit, savepath, scale_by=2.5):\n im = Image.open( imgpath )\n if im.size[0] < min_width_limit:\n basewidth = im.size[0] * scale\n wpercent = (basewidth/float(im.size[0]))\n hsize = int((float(im.size[1])*float(wpercent)))\n im = im.resize((basewidth,hsize), Image.ANTIALIAS)\n im.save(savepath) \n\ndef do_rotation(csv_row, is_man):\n\n #\n # print('to_x_y(csv_row[2])')\n # print(to_x_y(csv_row[2]))\n # print(csv_row[2])\n\n #\n scale = 1 #3\n is_crop_main_expressions_only = True\n is_detect_shape_after_rotate = True\n is_visualize_detected_face = False\n is_fit_parts_to_size = True\n is_fit_parts_to_size_with_customization = False\n\n\n # load the input image, resize it, and convert it to grayscale\n imgpath_org = FLAGS.imgages_dir + csv_row[0] + \".\" + FLAGS.img_extension\n if not os.path.exists(imgpath_org):\n print(imgpath_org)\n got_here = this_is_unexpected\n return\n\n #\n scale_if_small(imgpath_org, 33, imgpath_org)\n\n images = cv2.imread( imgpath_org )\n\n # images = imutils.resize(images, width=500)\n gray = cv2.cvtColor(images, cv2.COLOR_BGR2GRAY) \n f, e = os.path.splitext( imgpath_org )\n rects = detector(gray, 1)\n\n #skip if no face is detected\n if len(rects) <= 0:\n print( \"Nooooooooooooooo Faceeeeeeeeeeeeeeeeee found in Imageeeeeeeeeeeeeeeeee. Skipping...\" )\n return\n\n # TODO temp.\n if len(rects) <= 1:\n print( \"already processed, skipping...\" )\n return\n\n #\n name = \"\"+csv_row[0]\n len_rects = len(rects)\n for (i, rect) in enumerate(rects):\n\n new_csv_row = []\n new_csv_row.append( name )\n new_csv_row.append( csv_row[2] )\n\n if len_rects >= 2:\n shutil.copy(imgpath_org, FLAGS.imgages_dir + name + \"___\"+str(i)+\".\" + FLAGS.img_extension)\n imgpath_org = FLAGS.imgages_dir + name + \"___\"+str(i)+\".\" + FLAGS.img_extension\n\n new_csv_row[0] = new_csv_row[0] + \"~\" + str(i)\n\n # determine the facial landmarks for the face region, then\n # convert the facial landmark (x, y)-coordinates to a NumPy\n # array\n shape = predictor(gray, rect)\n shape = face_utils.shape_to_np(shape)\n\n for (x, y) in shape:\n new_csv_row.append( \"\"+str(x)+\"~\"+str(y)+\"~0\" )\n\n csv_row = array( new_csv_row )\n ##########################################################################################################\n\n\n #\n org_csv_row = []\n org_csv_row.append( csv_row[0] )\n org_csv_row.append( csv_row[1] )\n pLeft = [to_x_y(csv_row[2])]\n for i in range(3,69):\n org_csv_row.append( csv_row[i] )\n pLeft.append( to_x_y(csv_row[i]) )\n\n pLeft = np.array( pLeft )\n\n #\n is_do_custom_rotation = False\n\n #\n rot_m, tran_m, imgpath, _, imgname, imgdirname = get_rotation_and_translation_matrix(csv_row, scale, imgpath_org)\n if imgname == None:\n continue #return\n\n imgname = imgname.replace(FLAGS.img_extension, \"png\")\n\n if FLAGS.merge_and_fit and ( not os.path.exists( FLAGS.imgages_dir + \"/\" + imgdirname + \"_parts/eye_\" + imgname ) or not os.path.exists( FLAGS.imgages_dir + \"/\" + imgdirname + \"_parts/mouth_\" + imgname ) ): \n print(\"MERGE AND FITTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT, Image not found. Skipping...\")\n continue #return\n\n #\n angle = rot_m[0] #round( ( (rot_m[0][0]/math.pi) * 180 ) )\n t = round( rot_m[1] / 10 )\n dirangle = abs( t ) if t == -0 else t #str( round( ( (rot_m[1][0]/math.pi) * 180 ) / 10 ) )\n\n if dirangle < -1 or dirangle > 1:\n print(\"dirangle \" + str(dirangle) + \" out of limit. Skipping...\")\n continue #return\n\n print( \"rotate angle \" + str(angle) + \" dirangle \" + str(dirangle) )\n\n print(imgpath)\n im = Image.open(imgpath)\n\n #crop face part\n im_expression_eye = None\n im_expression_mouth = None\n eye_cords = []\n mouth_cords = []\n face_cords = []\n\n #face coords \n xtl, _, _ = to_x_y_z( csv_row[2] )\n _, ytl, _ = to_x_y_z( csv_row[21] )\n _, ybr, _ = to_x_y_z( csv_row[10] )\n xbr, _, _ = to_x_y_z( csv_row[18] ) #to_x_y_z( csv_row[28] ) #( csv_row[37] )\n _, ytr, _ = to_x_y_z( csv_row[26] )\n\n if ytl < ytr:\n ytr = ytl\n else:\n ytl = ytr\n\n face_cords.append( xtl )\n face_cords.append( ytl )\n face_cords.append( xbr )\n face_cords.append( ybr ) \n\n #\n magnitude = face_cords[2] - face_cords[0] if (face_cords[2] - face_cords[0]) > (face_cords[3]-face_cords[1]) else face_cords[3]-face_cords[1] #should actually calculate it later by calculating distance between most wide points out of four \n if magnitude <= 0:\n #raise Exception( \"unexpected_magnitude_found_intended_to_be_crashed_here\" )\n print( \"SKIPPING DUE TO ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR...\" )\n print( \"unexpected_magnitude_found_intended_to_be_crashed_here\" )\n continue #return\n\n face_image_padding = int( 20 * (magnitude/25) ) #20\n\n #\n if dirangle < -2:\n face_image_padding = face_image_padding + int( 10 * (magnitude/25) )\n elif dirangle > 2:\n face_image_padding = face_image_padding + int( 10 * (magnitude/25) ) #xtl = xtl - face_image_padding if xtl - face_image_padding > 0 else 0\n\n #\n # if dirangle < 0:\n xbr = xbr + face_image_padding\n # elif dirangle > 0:\n xtl = xtl - face_image_padding if xtl - face_image_padding > 0 else 0\n\n ytl = ytl - face_image_padding\n ybr = ybr + face_image_padding \n\n xtr = xbr\n xbl = xtl \n ybl = ybr\n\n #\n n = to_x_y( csv_row[35] )\n if xbr <= n[0]:\n xbr = n[0] + ((n[0]-xtl)/5)\n\n if ybr <= n[1]:\n ybr = n[0] + ((n[0]-xtl)/5)\n\n #\n xtl = xtl if xtl > 0 else 0\n ytl = ytl if ytl > 0 else 0\n xbr = xbr if xbr < im.size[0] else im.size[0]\n ybr = ybr if ybr < im.size[1] else im.size[1]\n\n face_cords.append( xtl )\n face_cords.append( ytl )\n face_cords.append( xbr )\n face_cords.append( ybr ) \n\n #\n if int(xtl) == int(xbr) or int(ytl) == int(ybr):\n print( \"zero size image detected, skipping...\" )\n continue #return\n\n #\n if not FLAGS.merge_and_fit and is_detect_shape_after_rotate == True: \n im = im.crop( (int(xtl), int(ytl), xbr, ybr ) )\n im = im.rotate(angle) \n\n #TODO temp \n try: \n # print( im.size )\n # print( int(xtl), int(ytl), xbr, ybr )\n im.save( FLAGS.out_to_dir + \"/tmp/\" + imgname ) \n\n # load the input image, resize it, and convert it to grayscale\n images = cv2.imread( FLAGS.out_to_dir + \"/tmp/\" + imgname )\n # images = imutils.resize(images, width=500)\n gray = cv2.cvtColor(images, cv2.COLOR_BGR2GRAY) \n f, e = os.path.splitext( FLAGS.out_to_dir + \"/tmp/\" + imgname )\n rects = detector(gray, 1)\n\n #skip if no face is detected\n if len(rects) <= 0:\n print( \"Zerooooo00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 face detected in cropped box, there is something wrong, should be fixed at earliest. Skipping...\" )\n continue #return\n\n # #if more than one face detected in cropped image then simply continue for now \n # if len(rects) >= 2:\n # print( \"more than one face detected, skipping...\" )\n # im.show()\n # sdfhsfhdfkhj\n # continue #return\n\n for (i, rect) in enumerate(rects):\n # determine the facial landmarks for the face region, then\n # convert the facial landmark (x, y)-coordinates to a NumPy\n # array\n shape = predictor(gray, rect)\n shape = face_utils.shape_to_np(shape)\n\n ci = 2\n for (x, y) in shape:\n csv_row[ci] = \"\"+str(x)+\"~\"+str(y)+\"~0\"\n ci = ci + 1\n\n #for now use the first face only\n break\n\n # im.show()\n # cv2.waitKey(0)\n # input(\"Press Enter to continue...\")\n except Exception as e:\n print(\"SKIPPING DUE TO ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR...\")\n print(e)\n xdfcjdkfdfhj\n continue #return\n\n if is_crop_main_expressions_only == False:\n # zbl = zbr\n print( \"(int(xtl), int(ytl), xbr, ybr ) \" + str(int(xtl)) + \" \" + str(int(ytl)) + \" \" + str(xbr) + \" \" + str(ybr) + \" \" )\n print(n)\n im = im.crop( (int(xtl), int(ytl), xbr, ybr ) )\n else:\n if not FLAGS.merge_and_fit:\n if is_detect_shape_after_rotate == True: \n #update face coords \n face_cords.append( 0 )\n face_cords.append( 0 )\n face_cords.append( im.size[0] )\n face_cords.append( im.size[1] ) \n\n magnitude = face_cords[2] - face_cords[0] if (face_cords[2] - face_cords[0]) > (face_cords[3]-face_cords[1]) else face_cords[3]-face_cords[1] #should actually calculate it later by calculating distance between most wide points out of four \n if magnitude <= 0:\n #raise Exception( \"unexpected_magnitude_found_intended_to_be_crashed_here\" )\n print( \"SKIPPING DUE TO ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR...\" )\n print( \"unexpected_magnitude_found_intended_to_be_crashed_here\" )\n continue #return\n\n padding = magnitude/25\n print( \"magnitude \" + str(magnitude) + \" padding \" + str(padding) )\n\n #eyes area \n xtl, _, _ = to_x_y_z( csv_row[19] ) \n _, ytl, _ = to_x_y_z( csv_row[21] )\n xbr, _, _ = to_x_y_z( csv_row[28] ) \n _, ybr, _ = to_x_y_z( csv_row[48] ) \n _, ytr, _ = to_x_y_z( csv_row[26] )\n\n xtl = xtl - padding # ((xbr-xtl)/5)\n xbr = xbr + padding # ((xbr-xtl)/5)\n ytl = ytl - padding # ((ybr-ytl)/5)\n ybr = ybr + padding * 3 #\n ytr = ytr - padding # ((ybr-ytl)/5)\n\n\n if ytl < ytr:\n ytr = ytl\n else:\n ytl = ytr\n\n # if dirangle < -2:\n # xbr = xbr + 20\n # elif dirangle > 2:\n # xtl = xtl - 20 if xtl - 20 > 0 else 0\n\n xtr = xbr\n xbl = xtl \n ybl = ybr\n\n print( \"eyes area 0 (int(xtl), int(ytl), xbr, ybr ) \" + str(int(xtl)) + \" \" + str(int(ytl)) + \" \" + str(xbr) + \" \" + str(ybr) + \" \" )\n\n #\n n = to_x_y( csv_row[35] )\n if xbr <= n[0]:\n xbr = n[0] + ((n[0]-xtl)/5)\n\n # if ybr <= n[1]:\n # ybr = n[0] + ((n[0]-xtl)/5)\n\n print( \"eyes area (int(xtl), int(ytl), xbr, ybr ) \" + str(int(xtl)) + \" \" + str(int(ytl)) + \" \" + str(xbr) + \" \" + str(ybr) + \" \" )\n print(n)\n im_expression_eye = im.crop( (int(xtl), int(ytl), xbr, ybr ) )\n if is_fit_parts_to_size == True:\n if not os.path.exists( FLAGS.imgages_dir + \"/\" + imgdirname ):\n os.mkdir( FLAGS.imgages_dir + \"/\" + imgdirname )\n\n if not os.path.exists( FLAGS.imgages_dir + \"/\" + imgdirname + \"_parts\" ):\n os.mkdir( FLAGS.imgages_dir + \"/\" + imgdirname + \"_parts\" ) \n\n im_expression_eye.save( FLAGS.imgages_dir + \"/\" + imgdirname + \"_parts/eye_\" + imgname ) \n\n eye_cords.append( xtl )\n eye_cords.append( ytl )\n eye_cords.append( xbr )\n eye_cords.append( ybr )\n # im.show()\n # im_expression_eye.show()\n # input(\"Press Enter to continue...\")\n # sdfsdjfhgdsjhfg\n\n #mouth area \n xtl, _, _ = to_x_y_z( csv_row[50] )\n _, ytl, _ = to_x_y_z( csv_row[52] )\n xbr, _, _ = to_x_y_z( csv_row[56] ) \n _, ytr, _ = to_x_y_z( csv_row[54] ) \n _, ybr, _ = to_x_y_z( csv_row[59] ) \n\n xtl = xtl - padding * 2 # ((xbr-xtl)/5)\n xbr = xbr + padding * 2 # ((xbr-xtl)/5)\n ytl = ytl - padding * 1 # ((ybr-ytl)/5)\n ybr = ybr + padding * 2 #\n ytr = ytr - padding * 1 # ((ybr-ytl)/5)\n\n if ytl < ytr:\n ytr = ytl\n else:\n ytl = ytr\n\n if dirangle < -2:\n xbr = xbr + 20\n elif dirangle > 2:\n xtl = xtl - 20 if xtl - 20 > 0 else 0\n\n xtr = xbr\n xbl = xtl \n ybl = ybr\n\n #\n n = to_x_y( csv_row[35] )\n if xbr <= n[0]:\n xbr = n[0] + ((n[0]-xtl)/5)\n\n if ybr <= n[1]:\n ybr = n[0] + ((n[0]-xtl)/5)\n\n\n print( \"mouth area (int(xtl), int(ytl), xbr, ybr ) \" + str(int(xtl)) + \" \" + str(int(ytl)) + \" \" + str(xbr) + \" \" + str(ybr) + \" \" )\n \n #mouth is wider than eyes or if eyes is below 20 in width or mouth is below 7 in width then continue\n if (xbr-xtl) > (eye_cords[2]-eye_cords[0]) or (eye_cords[2]-eye_cords[0]) < 20 or (xbr-xtl) < 7:\n print( \"SKIPPING DUE TO ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR...\" )\n print( \"mouth width is inappropriate\" )\n continue #return\n\n print(n)\n im_expression_mouth = im.crop( (int(xtl), int(ytl), xbr, ybr ) )\n if is_fit_parts_to_size == True:\n im_expression_mouth.save( FLAGS.imgages_dir + \"/\" + imgdirname + \"_parts/mouth_\" + imgname ) \n continue #return\n else:\n mouth_cords.append( xtl )\n mouth_cords.append( ytl )\n mouth_cords.append( xbr )\n mouth_cords.append( ybr )\n # im.show()\n # im_expression_mouth.show()\n # input(\"Press Enter to continue...\")\n # sdfsdjfhgdsjhfg\n else:\n im_expression_eye = Image.open( FLAGS.imgages_dir + \"/\" + imgdirname + \"_parts/eye_\" + imgname )\n im_expression_mouth = Image.open( FLAGS.imgages_dir + \"/\" + imgdirname + \"_parts/mouth_\" + imgname )\n\n #rotate image\n if not angle == 0:\n if is_detect_shape_after_rotate == False: \n if is_crop_main_expressions_only == False:\n im = im.rotate(angle)\n else:\n # im = im.rotate(angle)\n # im.show()\n # cv2.waitKey(0)\n im_expression_eye = im_expression_eye.rotate(angle)\n im_expression_mouth = im_expression_mouth.rotate(angle)\n\n #save \n dirangle = str(dirangle) \n\n if not os.path.exists( FLAGS.imgages_dir + \"/tmp/\" ):\n os.mkdir( FLAGS.imgages_dir + \"/tmp/\" )\n\n #check gender \n # if os.path.exists( FLAGS.imgages_dir + \"/tmp/\" + imgname + \"_g_f.txt\" ):\n if not is_man:\n dirangle = dirangle + \"_f\"\n # elif os.path.exists( FLAGS.imgages_dir + \"/tmp/\" + imgname + \"_g_m.txt\" ):\n else:\n dirangle = dirangle + \"_m\"\n # else:\n # faces = agender.detect_genders_ages( cv2.imread( FLAGS.out_to_dir + \"/tmp/\" + imgname ) )\n\n # #TODO temp\n # print( faces )\n # im = Image.open(FLAGS.out_to_dir + \"/tmp/\" + imgname)\n # im.show()\n # input(\"Press Enter to continue...\")\n\n # if len(faces) > 0:\n # if faces[0][\"gender\"] <= 0.50:\n # with open(FLAGS.imgages_dir + \"/tmp/\" + imgname + \"_g_m.txt\", \"w\") as text_file:\n # text_file.write(\"1\")\n\n # dirangle = dirangle + \"_m\"\n # else:\n # with open(FLAGS.imgages_dir + \"/tmp/\" + imgname + \"_g_f.txt\", \"w\") as text_file:\n # text_file.write(\"1\")\n\n # dirangle = dirangle + \"_f\"\n\n if is_crop_main_expressions_only == False:\n if not os.path.exists( FLAGS.out_to_dir + \"/\" + dirangle ):\n os.mkdir( FLAGS.out_to_dir + \"/\" + dirangle )\n else:\n if not os.path.exists( FLAGS.out_to_dir + \"/\" + dirangle + \"_eye\" ):\n os.mkdir( FLAGS.out_to_dir + \"/\" + dirangle + \"_eye\" )\n\n if not os.path.exists( FLAGS.out_to_dir + \"/\" + dirangle + \"_mouth\" ): \n os.mkdir( FLAGS.out_to_dir + \"/\" + dirangle + \"_mouth\" )\n\n try:\n #remove image if ratio is not falling in 1:2 in either way \n if is_crop_main_expressions_only == False and ( im.size[0] > im.size[1]*2 or im.size[1] > im.size[0]*2 ):\n continue #return\n\n if not FLAGS.merge_and_fit:\n if is_crop_main_expressions_only == True:\n \n xtl = 0; ytl = 0; xbr = 0; ybr = 0; \n xtl = eye_cords[0] if eye_cords[0] < mouth_cords[0] else mouth_cords[0]\n ytl = eye_cords[1]\n xbr = eye_cords[2] if eye_cords[2] > mouth_cords[2] else mouth_cords[2]\n ybr = mouth_cords[2]\n\n #create actual face size empty image and paste into it the expressions \n im = Image.new('RGB', ( int(xbr-xtl), int(ybr-ytl) ) ) \n\n im.paste( im_expression_eye, ( 0, 0 ) ) \n\n im.paste( im_expression_mouth, ( int( ( (xbr-xtl) - (mouth_cords[2]-mouth_cords[0]) )/2 ), int( mouth_cords[1]-ytl ) ) ) \n\n # im.show()\n # cv2.waitKey(0)\n\n #resize and paste into 36x36\n empty_im = Image.new('RGB', (36, 36))\n resize_to = [0,0]\n if im.size[0] > im.size[1]:\n resize_to[0] = 36\n resize_to[1] = int( im.size[1] / (im.size[0]/resize_to[0]) )\n else:\n resize_to[1] = 36\n resize_to[0] = int( im.size[0] / (im.size[1]/resize_to[1]) )\n\n im = im.resize( resize_to, Image.ANTIALIAS )\n\n empty_im.paste( im, ( 0 if im.size[0]==empty_im.size[0] else int( math.floor( (empty_im.size[0]-im.size[0])/2 ) ), 0 if im.size[1]==empty_im.size[1] else int( math.floor( (empty_im.size[1]-im.size[1])/2 ) ) ) )\n\n #save\n empty_im.save( FLAGS.out_to_dir + \"/\" + dirangle + \"/\" + imgname )\n # im.show()\n else:\n is_keep_expression_separate = True \n\n if is_keep_expression_separate == False:\n empty_im = Image.new('RGB', (36, 36))\n\n #resize eye \n im_expression_eye = im_expression_eye.resize( [27,15], Image.ANTIALIAS )\n\n #resize mouth \n im_expression_mouth = im_expression_mouth.resize( [18,13], Image.ANTIALIAS )\n\n if is_keep_expression_separate == False:\n empty_im.paste( im_expression_eye, ( 5, 0 ) ) \n\n empty_im.paste( im_expression_mouth, ( 9, 23 ) ) \n else:\n im_expression_eye.save( FLAGS.out_to_dir + \"/\" + dirangle + \"_eye\" + \"/\" + imgname )\n im_expression_mouth.save( FLAGS.out_to_dir + \"/\" + dirangle + \"_mouth\" + \"/\" + imgname )\n\n\n if is_keep_expression_separate == False:\n #save\n empty_im.save( FLAGS.out_to_dir + \"/\" + dirangle + \"/\" + imgname )\n # im.show()\n\n #uncomment and enable when necessary \n # #check if image is of less then or equal to 1KB then is of low quality so remove it \n # if os.path.getsize( FLAGS.out_to_dir + \"/\" + dirangle + \"/\" + imgname ) <= 700: #1024: #bytes\n # os.remove( FLAGS.out_to_dir + \"/\" + dirangle + \"/\" + imgname )\n\n #\n if is_visualize_detected_face == True:\n print( imgpath )\n im_tmp = cv2.imread( imgpath )\n print( im_tmp.size )\n visualize_detected_face( im_tmp, org_csv_row, True )\n\n except Exception as e:\n print(\"SKIPPING DUE TO ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR... ERROR...\")\n print(e)\n if os.path.exists( FLAGS.out_to_dir + \"/\" + dirangle + \"/\" + imgname ):\n os.remove( FLAGS.out_to_dir + \"/\" + dirangle + \"/\" + imgname )\n #continue #return\n continue\n\n return\n\ndef resize( path ):\n items = os.listdir( path )\n file_no = 0\n item_cnt = 0\n\n for item in items:\n\n file_no = file_no + 1\n print(item + \" file_no \" + str(file_no))\n\n if item == '.DS_Store':\n continue\n\n if not '.csv' in item:\n continue\n\n if os.path.isfile(path+item):\n\n # with open(path+item, newline='') as csvfile:\n # data = list(csv.reader(csvfile))\n import pandas as pd \n try:\n data = pd.read_csv(path+item, sep=',')\n\n # if not FLAGS.verify_against == \"\":\n # data_verify = pd.read_csv(FLAGS.verify_path, sep=',') \n except Exception as e:\n print(\"caught error while reading csv \"+item+\", skipping.\")\n print(e)\n continue\n\n # print(type(data))\n # print(data)\n\n if FLAGS.out_to_dir:\n\n prev_rec = {}\n curr_rec = {}\n prev_rec[\"id\"] = \"\"\n curr_rec[\"id\"] = \"\"\n prev_rec[\"lbls\"] = []\n curr_rec[\"lbls\"] = []\n prev_row = None\n\n with open( os.path.join( FLAGS.out_to_dir, item ) , 'wb' ) as file:\n\n for index, row in data.iterrows():\n\n #\n if not row[0] == curr_rec[\"id\"]:\n prev_rec = dict(curr_rec) #TODO last record will be missed\n curr_rec[\"id\"] = row[0]\n curr_rec[\"lbls\"] = []\n curr_rec[\"lbls\"].append( row[2] )\n else:\n prev_row = row\n curr_rec[\"lbls\"].append( row[2] )\n continue\n\n if prev_rec[\"id\"] == \"\":\n continue\n\n print(prev_rec[\"id\"])\n\n if not FLAGS.verification_val in prev_rec[\"lbls\"]:\n print(\"For index \"+str(index)+\" verification failed against speified value, skipping....\")\n continue\n\n # #TODO temp\n # item_cnt = item_cnt + 1\n # if item_cnt < 50000 or not item_cnt % 250 == 0:\n # # if not item_cnt == 9499 and not item_cnt == 9500:\n # continue\n # print( \"item_cnt \" + str(item_cnt) )\n\n #\n # print(row[2])\n new_row = do_rotation(prev_row, True if FLAGS.gender_man_lbl in prev_rec[\"lbls\"] else False)\n # input(\"Press Enter to continue...\")\n continue\n\n\nfor path in paths:\n resize( path )\n # cv2.imshow(\"Output\", images)\n # cv2.waitKey(0)\n","sub_path":"crop_and_rotate_images.py","file_name":"crop_and_rotate_images.py","file_ext":"py","file_size_in_byte":29040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"569854064","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 ('pmtool', '0006_remove_activity_dlabel'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='activity',\n name='duration',\n field=models.PositiveIntegerField(default=1, verbose_name=b'Duration (in days)'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='schedulegap',\n name='duration',\n field=models.PositiveIntegerField(default=1, verbose_name=b'Duration'),\n preserve_default=True,\n ),\n migrations.AlterField(\n model_name='schedulegap',\n name='from_start',\n field=models.PositiveIntegerField(default=1, verbose_name=b'From start'),\n preserve_default=True,\n ),\n ]\n","sub_path":"pmtool/migrations/0007_auto_20150128_1359.py","file_name":"0007_auto_20150128_1359.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"66450119","text":"#libraries\nimport sys\nfrom rot13_lib import crypt_word\n\n#two-way table initialisation\n\nalpha_lc = [chr(x) for x in range(97, 123)]\nalpha_uc = [chr(x) for x in range(65, 91)]\n\n#input&output\n\ndef input_output(crypt, offset):\n crypt_string = input(\"Input string to be %sd: \" % (crypt))\n new_crypt= \"\"\n for i in crypt_string:\n if i.isupper():\n new_crypt += crypt_word(i, crypt, offset, alpha_uc)\n elif i.islower():\n new_crypt += crypt_word(i, crypt, offset, alpha_lc)\n else:\n new_crypt += i\n print(\"Your %sd string is %s.\" % (crypt, new_crypt))\n retry_crypt()\n \n#inputs and error handling\n\ndef retry_crypt():\n retry = input(\"Would you like to run this script again? [Y/N] \").lower()\n if retry == \"y\" or retry == \"yes\":\n crypt_choice()\n elif retry == \"n\" or retry == \"no\":\n sys.exit()\n else:\n print(\"Please select either 'yes' or 'no'.\")\n retry_crypt() \n \ndef offset_choice(crypt):\n offset = input(\"By how much (a positive integer) would you like to offset your string? \")\n while True:\n if ((offset.isdigit() == False) or (int(offset) < 0)) and (offset !=''):\n print(\"Please input a positive integer.\")\n offset_choice(crypt)\n break\n elif offset == '':\n offset = 13\n print(\"A default value of 13 has been selected for your offset.\")\n input_output(crypt, offset)\n break\n else:\n offset = (int(offset) % 26)\n input_output(crypt, offset)\n break\n\ndef crypt_choice():\n crypt = (input(\"Would you like to encode or decode a string? \")).lower()\n while True:\n if crypt not in [\"encode\", \"decode\"]:\n print(\"'Encode' and 'decode' are the only valid entries.\")\n crypt_choice()\n break\n else:\n offset_choice(crypt)\n break\n \nif __name__ == \"__main__\":\n crypt_choice()\n","sub_path":"rot13_script.py","file_name":"rot13_script.py","file_ext":"py","file_size_in_byte":1995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"315551287","text":"# Definition for singly-linked list.\r\n# class ListNode:\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.next = None\r\n\r\nclass Solution:\r\n # @param {ListNode} head\r\n # @return {void} Do not return anything, modify head in-place instead.\r\n def reorderList(self, head):\r\n\r\n if not head:\r\n return\r\n\r\n node = head\r\n\r\n stack = []\r\n\r\n while node.next:\r\n\r\n node = node.next\r\n stack.append(node)\r\n\r\n node = head\r\n\r\n while stack:\r\n if stack:\r\n nextNode = stack.pop()\r\n node.next = nextNode\r\n node = nextNode\r\n if stack:\r\n nextNode = stack.pop(0)\r\n node.next = nextNode\r\n node = nextNode\r\n\r\n node.next = None\r\n\r\n return \r\n","sub_path":"143-reorderList.py","file_name":"143-reorderList.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"576308091","text":"from string import maketrans\nfrom re import sub\n\nintab = \"abcdefghijklmnopqrstuvwxyz\"\nouttab = intab[::-1]\n\ndef decode(clear_text):\n\tclear_text = \"\".join(clear_text.split())\n\tclear_text = clear_text.lower()\n\ttrantab = maketrans(intab, outtab)\n\treturn remove_tokens(clear_text.translate(trantab)).strip()\n\n\ndef encode(cypher_text):\n\tcypher_text = \"\".join(cypher_text.split())\n\tcypher_text = cypher_text.lower()\n\ttrantab = maketrans(outtab, intab)\n\treturn grouping(remove_tokens(cypher_text.translate(trantab))).strip()\n\n\ndef grouping(text):\n\t\"\"\"Groups into 5 characters long units and seperates with a whitespace\"\"\"\n\tsequence = \"\"\n\tfor x in range(len(text)):\n\t\tif x % 5 == 0:\n\t\t\tsequence += \" \"\n\t\t\tsequence += text[x]\n\t\telse:\n\t\t\tsequence += text[x]\n\treturn sequence\n\ndef remove_tokens(text):\n\t\"\"\"Removes any non-alpernumerical\"\"\"\n\treturn sub(r'\\W', '', text)\n","sub_path":"all_data/exercism_data/python/atbash-cipher/f0087cfcd1944b12ab4794fe001c0157.py","file_name":"f0087cfcd1944b12ab4794fe001c0157.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"560493446","text":"from locust import HttpLocust, TaskSet\n\ndef get_homepage(l):\n response= l.client.get(\"/\")\n print(response.status-code)\n print(response.content)\n\ndef get_electronic_tab(l):\n l.client.get(\"elektronik\")\n\nclass UserBehavior(TaskSet) :\n tasks = {get_homepage: 2, get_electronic_tab: 1}\n\nclass WebsiteUser(HttpLocust) :\n task_set = UserBehavior\n min_wait = 900\n max_wait = 5000\n host = \"https://www.n11.com\"","sub_path":"venv/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"517505028","text":"# def add(a, b):\n# print a + b\n# number_1 = 20\n# number_2 = 35\n#\n# add(5, 6)\n# add(number_1, number_2)\n\n\n# def car(want_a_car, color, doors, cost):\n# if want_a_car.lower() == \"yes\" and int(cost) > 5000:\n# print \"Great!\"\n# print \"You want a %s car. We can do that!\" % color\n# print \"You want %s doors. I guess that's alright.\" % doors\n# print \"Sold!\"\n# else:\n# print \"Okay fine\"\n\nwant_a_car = raw_input(\"Do you want a new car?: \")\ncolors = raw_input(\"What color car do you want?: \")\ndoors = raw_input(\"How many doors do you want?: \")\ncost = raw_input(\"How much do you want to pay?: \")\n\ncar(want_a_car, colors, doors, cost)","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"23549111","text":"from abc import ABC\nfrom collections.abc import Iterable\nfrom unittest import TestCase\n\n\nclass Connectable(Iterable,ABC):\n def connect_to(self,other):\n if self == other:\n return\n for s in self:\n for o in other:\n s.outputs.append(o)\n o.inputs.append(s)\n\n\nclass Neurone(Connectable):\n\n def __init__(self,name):\n self.name = name\n self.inputs = []\n self.outputs = []\n\n def __iter__(self):\n yield self\n\n def __str__(self):\n return f\"{self.name} : with {len(self.inputs)} inputs and {len(self.outputs)} outputs\"\n\n\nclass NeuroneLayer(list,Connectable):\n\n def __init__(self,name:str,n_neurons_in_layer:int):\n super().__init__()\n self.name = name\n for n in range(n_neurons_in_layer):\n self.append(Neurone(f\"{self.name} - {n}\"))\n\n def __str__(self):\n return f\"{self.name} has {len(self)} neurons.\"\n\nif __name__ == '__main__':\n neurone1 = Neurone(\"N1\")\n neurone2 = Neurone(\"N2\")\n\n layer1 = NeuroneLayer(\"L1\",3)\n layer2 = NeuroneLayer(\"L2\",4)\n\n neurone1.connect_to(neurone2)\n neurone1.connect_to(layer1)\n\n layer1.connect_to(neurone2)\n layer1.connect_to(layer2)\n\n print(neurone1)\n print(neurone2)\n print(layer1)\n print(layer2)\n\n\nclass SingleValue:\n def __init__(self, value):\n self.value = value\n\n\n","sub_path":"CompositeDesignPattern/NeuralNetworks.py","file_name":"NeuralNetworks.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"281619883","text":"from .DataPreprocess import DataPreprocess\nfrom .models import CNN, RNN, SklearnClf\nimport numpy as np\n\n\nclass TextClassification():\n def __init__(self):\n pass\n\n def fit(self, x=None, y=None, model=None,\n method='CNN', epochs=10, batchsize=256,\n x_need_preprocess=False, y_need_preprocess=False,\n tokenizer=None, num_words=2000, maxlen=None,\n vec_size=128, output_shape=None, output_type='multiple',\n **sklearn_param):\n '''\n Process texts and labels, creat model to fit\n :param x: Data feature\n :param y: Data label\n :param model: Model to fit\n :param method: Model type\n :param epochs: Number of epochs to train the model\n :param batchsize: Size of minibatch\n :param x_need_preprocess: TRUE will load DataPreprocess to process x to sequence\n :param y_need_preprocess: TRUE will load DataPreprocess to process y to one-hot\n :param tokenizer: Keras tokenizer model\n :param num_words: The maximum number of words to keep in tokenizer\n :param maxlen: The number of words to keep in sentence\n :param vec_size: Word vector size\n :param output_shape: Num of labels\n :param output_type: Single or multiple, sklearn only support single\n :param sklearn_param: Param for sklearn model\n :return: None\n '''\n self.tokenizer = tokenizer\n self.num_words = num_words\n self.maxlen = maxlen\n self.vec_size = vec_size\n self.method = method\n\n # need process\n if method in ['CNN', 'RNN']:\n if x_need_preprocess:\n process = DataPreprocess()\n # cut texts\n x_cut = process.cut_texts(texts=x, need_cut=True, word_len=2, savepath=None)\n # use average length\n if maxlen is None:\n maxlen = int(np.array([len(x) for i in x_cut]).mean())\n # texts to sequence\n x_seq = process.text2seq(texts_cut=x_cut, tokenizer=tokenizer, tokenizer_savapah=None,\n num_words=num_words, maxlen=maxlen, batchsize=10000)\n # list to array\n x_seq = np.array(x_seq)\n x = x_seq\n self.num_words = num_words\n self.maxlen = maxlen\n self.tokenizer = process.tokenizer\n\n if y_need_preprocess:\n process = DataPreprocess()\n label_set = process.creat_label_set(y)\n labels = process.creat_labels(labels=y, label_set=label_set)\n labels = np.array(labels)\n output_shape = labels.shape[1]\n y = labels\n self.output_shape = output_shape\n self.label_set = label_set\n\n if model is None:\n if method == 'CNN':\n model = CNN(input_dim=num_words, input_length=maxlen,\n vec_size=vec_size, output_shape=output_shape,\n output_type=output_type)\n elif method == 'RNN':\n model = RNN(input_dim=num_words, input_length=maxlen,\n vec_size=vec_size, output_shape=output_shape,\n output_type=output_type)\n model.fit(x=x, y=y, epochs=epochs, batch_size=batchsize)\n\n elif method in ['SVM', 'Logistic']:\n if output_type != 'single':\n raise ValueError('sklearn output_type should be single')\n else:\n if x_need_preprocess:\n process = DataPreprocess()\n # cut texts\n x_cut = process.cut_texts(texts=x, need_cut=True, word_len=2, savepath=None)\n x_seq_vec = process.text2vec(texts_cut=x, sg=1, size=128, window=5, min_count=1)\n x_vec = np.array([sum(i) for i in x_seq_vec])\n x = x_vec\n self.model_word2vec = process.model_word2vec\n\n model = SklearnClf(method=method, **sklearn_param)\n model.fit(X=x, y=y)\n\n self.model = model\n\n def predict(self, x=None, x_need_preprocess=True, model=None,\n tokenizer=None, num_words=None, maxlen=None,\n model_word2vec=None):\n '''\n\n :param x:\n :param x_need_preprocess:\n :param model:\n :param tokenizer:\n :param num_words:\n :param maxlen:\n :param model_word2vec:\n :return:\n '''\n method = self.method\n if method in ['CNN', 'RNN']:\n if x_need_preprocess:\n if tokenizer is not None:\n tokenizer = self.tokenizer\n if num_words is None:\n num_words = self.num_words\n if maxlen is None:\n maxlen = self.maxlen\n process = DataPreprocess()\n x_cut = process.cut_texts(texts=x, need_cut=True, word_len=2, savepath=None)\n x_seq = process.text2seq(texts_cut=x_cut, tokenizer=tokenizer,\n num_words=num_words, maxlen=maxlen, batchsize=10000)\n x = np.array(x_seq)\n elif method in ['SVM', 'Logistic']:\n if x_need_preprocess:\n if model_word2vec is None:\n model_word2vec = self.model_word2vec\n process = DataPreprocess()\n # cut texts\n x_cut = process.cut_texts(texts=x, need_cut=True, word_len=2, savepath=None)\n x_seq_vec = process.text2vec(texts_cut=x, model_word2vec=model_word2vec)\n x_vec = np.array([sum(i) for i in x_seq_vec])\n x = x_vec\n\n if model is None:\n model = self.model\n\n y = model.predict(x)\n return y\n\n def label2toptag(self, predictions, labelset):\n labels = []\n for prediction in predictions:\n label = labelset[prediction == prediction.max()]\n labels.append(label.tolist())\n return labels\n\n def label2half(self, predictions, labelset):\n labels = []\n for prediction in predictions:\n label = labelset[prediction > 0.5]\n labels.append(label.tolist())\n return labels\n\n def label2tag(self, predictions, labelset):\n labels1 = self.label2toptag(predictions, labelset)\n labels2 = self.label2half(predictions, labelset)\n labels = []\n for i in range(len(predictions)):\n if len(labels2[i]) == 0:\n labels.append(labels1[i])\n else:\n labels.append(labels2[i])\n return labels\n","sub_path":"TextClassification/TextClassification.py","file_name":"TextClassification.py","file_ext":"py","file_size_in_byte":6770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"605336871","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nfrom mock import Mock\nfrom pyramid import httpexceptions\nfrom pyramid.testing import DummyRequest\nimport pytest\n\nfrom h.admin.views import staff as views\n\n\n@pytest.mark.usefixtures('routes')\nclass TestStaffIndex(object):\n def test_when_no_staff(self):\n request = DummyRequest()\n\n result = views.staff_index(request)\n\n assert result[\"staff\"] == []\n\n @pytest.mark.usefixtures('users')\n def test_context_contains_staff_usernames(self):\n request = DummyRequest()\n\n result = views.staff_index(request)\n\n assert set(result[\"staff\"]) == set([\"agnos\", \"bojan\", \"cristof\"])\n\n\n@pytest.mark.usefixtures('users', 'routes')\nclass TestStaffAddRemove(object):\n\n def test_add_makes_users_staff(self, users):\n request = DummyRequest(params={\"add\": \"eva\"})\n\n views.staff_add(request)\n\n assert users['eva'].staff\n\n def test_add_is_idempotent(self, users):\n request = DummyRequest(params={\"add\": \"agnos\"})\n\n views.staff_add(request)\n\n assert users['agnos'].staff\n\n def test_add_redirects_to_index(self):\n request = DummyRequest(params={\"add\": \"eva\"})\n\n result = views.staff_add(request)\n\n assert isinstance(result, httpexceptions.HTTPSeeOther)\n assert result.location == '/adm/staff'\n\n def test_add_redirects_to_index_when_user_not_found(self):\n request = DummyRequest(params={\"add\": \"florp\"})\n\n result = views.staff_add(request)\n\n assert isinstance(result, httpexceptions.HTTPSeeOther)\n assert result.location == '/adm/staff'\n\n def test_add_flashes_when_user_not_found(self):\n request = DummyRequest(params={\"add\": \"florp\"})\n request.session.flash = Mock()\n\n views.staff_add(request)\n\n assert request.session.flash.call_count == 1\n\n def test_remove_makes_users_not_staff(self, users):\n request = DummyRequest(params={\"remove\": \"cristof\"})\n\n views.staff_remove(request)\n\n assert not users['cristof'].staff\n\n def test_remove_is_idempotent(self, users):\n request = DummyRequest(params={\"remove\": \"eva\"})\n\n views.staff_remove(request)\n\n assert not users['eva'].staff\n\n def test_remove_redirects_to_index(self):\n request = DummyRequest(params={\"remove\": \"agnos\"})\n\n result = views.staff_remove(request)\n\n assert isinstance(result, httpexceptions.HTTPSeeOther)\n assert result.location == '/adm/staff'\n\n def test_remove_redirects_to_index_when_user_not_found(self):\n request = DummyRequest(params={\"remove\": \"florp\"})\n\n result = views.staff_remove(request)\n\n assert isinstance(result, httpexceptions.HTTPSeeOther)\n assert result.location == '/adm/staff'\n\n\n@pytest.fixture\ndef users(db_session):\n from h import models\n\n staff = ['agnos', 'bojan', 'cristof']\n nonstaff = ['david', 'eva', 'flora']\n\n users = {}\n\n for staff in staff:\n users[staff] = models.User(username=staff,\n email=staff + '@example.com',\n password='secret',\n staff=True)\n for nonstaff in nonstaff:\n users[nonstaff] = models.User(username=nonstaff,\n email=nonstaff + '@example.com',\n password='secret')\n\n db_session.add_all(list(users.values()))\n db_session.flush()\n\n return users\n\n\n@pytest.fixture()\ndef routes(config):\n config.add_route('admin_staff', '/adm/staff')\n","sub_path":"tests/h/admin/views/staff_test.py","file_name":"staff_test.py","file_ext":"py","file_size_in_byte":3596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"598316320","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n\"\"\"\nimport os\nimport sys\nimport csv\nimport argparse\n\n\ndef main(argv=sys.argv[1:]):\n parser = argparse.ArgumentParser()\n parser.add_argument('target')\n args = parser.parse_args(argv)\n\n with open(args.target, 'r') as fp:\n reader = csv.reader(fp)\n for nn in sorted(list(set(row[1] for row in reader))):\n print(nn)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"watson_developper_cloud/parse_csv.py","file_name":"parse_csv.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"84652953","text":"import sys\nfrom setuptools import setup\n\nif sys.version_info[0] == 2:\n if not sys.version_info >= (2, 7):\n raise ValueError('This package requires Python 2.7 or newer')\nelif sys.version_info[0] == 3:\n if not sys.version_info >= (3, 3):\n raise ValueError('This package requires Python 3.3 or newer')\nelse:\n raise ValueError('Unrecognized major version of Python')\n\n__project__ = 'bluedot'\n__desc__ = 'A zero boiler plate bluetooth remote'\n__version__ = '1.2.3'\n__author__ = \"Martin O'Hanlon\"\n__author_email__ = 'martin@ohanlonweb.com'\n__license__ = 'MIT'\n__url__ = 'https://github.com/martinohanlon/BlueDot'\n__requires__ = ['pydbus',]\n\n__classifiers__ = [\n# \"Development Status :: 3 - Alpha\",\n# \"Development Status :: 4 - Beta\",\n \"Development Status :: 5 - Production/Stable\",\n \"Intended Audience :: Education\",\n \"Intended Audience :: Developers\",\n \"Topic :: Education\",\n \"Topic :: Communications\",\n \"License :: OSI Approved :: MIT License\",\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 2.7\",\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 3.3\",\n \"Programming Language :: Python :: 3.4\",\n \"Programming Language :: Python :: 3.5\",\n]\n\nif __name__ == '__main__':\n setup(name='bluedot',\n version = __version__,\n description = __desc__,\n url = __url__,\n author = __author__,\n author_email = __author_email__,\n license= __license__,\n packages = [__project__],\n #install_requires = __requires__,\n entry_points={\n 'console_scripts': [\n 'bluedotapp = bluedot.app:main'\n ]},\n zip_safe=False)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"377557297","text":"#!/usr/bin/env python \n\n# Written by Eric Ziegast\n# nxdomain.py - look at ch202 dnsqr data from a file and print out any \n# qname / type / rcode for data that's not rcode 0 (\"NOERROR\"). \n# Forgive awkward key processing. Sometimes an rcode or qtype key \n# doesn't exist and would cause the script to break if accessed them.\n\n\nimport nmsg\nimport wdns\nimport sys\n\ndef main(fname):\n\ti = nmsg.input.open_file(fname)\n\twhile True:\n\t\tm = i.read() \n\t\tif not m:\n\t\t\tbreak\n\t\trcode = 0\n\t\tqname = qtype = 0\n\t\tfor key in m.keys():\n\t\t\tif key == 'rcode':\n\t\t\t\trcode = m[key] \n\t\t\t\tcontinue\n\t\t\tif key == 'qname':\n\t\t\t\tqname = m[key]\n\t\t\t\tcontinue\n\t\t\tif key == 'qtype':\n\t\t\t\tqtype = m[key]\n\t\t\t\tcontinue\n\t\t\tif rcode != 0 and qname != 0 and qtype != 0:\n\t\t\t\tprint('%s %s %s' % (wdns.rcode_to_str(rcode),\n\t\t\t\twdns.rrtype_to_str(qtype), wdns.domain_to_str(qname)))\n\nif __name__ == '__main__':\n\tmain(sys.argv[1])\n","sub_path":"examples/nmsg_nxdomain.py","file_name":"nmsg_nxdomain.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"441415838","text":"plik1 = open(\"slownik.txt\");\r\n\r\ncommand = '';\r\n\r\nwejscie1 = input(\"Śmieciarka czeka na Twoje polecenie : \");\r\nwejscie = wejscie1.lower().split();\r\n\r\n\r\np1 = plik1.readlines();\r\nslownik = list(map(lambda s: s.split(),p1));\r\n\r\n\r\nfor slowo_wejscie in wejscie:\r\n for slowo_slownik in slownik:\r\n if slowo_slownik[0]==slowo_wejscie and slowo_slownik[1]== 'STREETNAME':\r\n command= command + slowo_slownik[0] + \" \" + slowo_slownik[1] + \" \";\r\n elif slowo_slownik[0]==slowo_wejscie:\r\n command = command + slowo_slownik[1] + \" \";\r\n\r\ncommand = command + \"X\";\r\ncommand = list(command.split());\r\nX=\"T\";\r\nfor slowo in command:\r\n if slowo == 'CLEAN':\r\n for slowo1 in command:\r\n if slowo1 == 'ALL':\r\n print(\"COMMAND CLEAN ALL\")\r\n X=\"N\";\r\n elif slowo1 == 'STREET':\r\n i=0;\r\n for ulica in command:\r\n if ulica == 'STREETNAME':\r\n print(\"COMMAND CLEAN STREET \"+ command[i-1])\r\n X=\"N\";\r\n i=i+1;\r\n if ulica == \"X\" and X==\"T\":\r\n print(\"Brak nazwy ulicy, sproboj ponownie\")\r\n X=\"N\";\r\n elif slowo1 == \"X\" and X==\"T\":\r\n print(\"smieciarka nie wie co ma wyczyscic, sproboj ponownie\")\r\n X=\"N\";\r\n elif slowo== \"X\" and X==\"T\":\r\n print(\"smieciarka nie obsługuje podanego czasownika, lub go brakuje, sproboj jeszcze raz\")\r\n\r\nplik1.close\r\n","sub_path":"KCK.py","file_name":"KCK.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"509637316","text":"from __future__ import print_function\r\n\r\n__author__ = 'Viktor Kerkez '\r\n__date__ = '20 October 2010'\r\n__copyright__ = 'Copyright (c) 2010 Viktor Kerkez'\r\n\r\nimport os\r\nimport re\r\nimport sys\r\nfrom textwrap import TextWrapper\r\n\r\n# tea imports\r\nfrom .color import strip_colors, set_color\r\n\r\n\r\ndef format_page(text):\r\n \"\"\"Formats the text for output adding ASCII frame around the text.\r\n\r\n :param str text: Text that needs to be formatted.\r\n :rtype: string\r\n :return: Formatted string.\r\n \"\"\"\r\n width = max(map(len, text.splitlines()))\r\n page = '+-' + '-' * width + '-+\\n'\r\n for line in text.splitlines():\r\n page += '| ' + line.ljust(width) + ' |\\n'\r\n page += '+-' + '-' * width + '-+\\n'\r\n return page\r\n\r\n\r\ndef table(text):\r\n \"\"\"Formats the text as a table\r\n\r\n Text in format:\r\n\r\n first | second\r\n row 2 col 1 | 4\r\n\r\n Will be formatted as::\r\n\r\n +-------------+--------+\r\n | first | second |\r\n +-------------+--------+\r\n | row 2 col 1 | 4 |\r\n +-------------+--------+\r\n\r\n :param str text: Text that needs to be formatted.\r\n :rtype: str\r\n :return: Formatted string.\r\n \"\"\"\r\n table_bar = (lambda col_lengths:\r\n '+-%s-+%s' % ('-+-'.join(['-' * length\r\n for length in col_lengths]),\r\n os.linesep))\r\n rows = []\r\n for line in text.splitlines():\r\n rows.append([part.strip() for part in line.split('|')])\r\n max_cols = max(map(len, rows))\r\n col_lengths = [0] * max_cols\r\n for row in rows:\r\n cols = len(row)\r\n if cols < max_cols:\r\n row.extend([''] * (max_cols - cols))\r\n for i, col in enumerate(row):\r\n col_length = len(col)\r\n if col_length > col_lengths[i]:\r\n col_lengths[i] = col_length\r\n text = table_bar(col_lengths)\r\n for i, row in enumerate(rows):\r\n cols = []\r\n for i, col in enumerate(row):\r\n cols.append(col.ljust(col_lengths[i]))\r\n text += '| %s |%s' % (' | '.join(cols), os.linesep)\r\n text += table_bar(col_lengths)\r\n return text\r\n\r\n\r\ndef hbar(width):\r\n \"\"\"Returns ASCII HBar ``+---+`` with the specified width.\r\n\r\n :param int width: Width of the central part of the bar.\r\n :rtype: str\r\n :return: ASCII HBar.\r\n \"\"\"\r\n return '+-' + '-' * width + '-+'\r\n\r\n\r\ndef print_page(text):\r\n \"\"\"Formats the text and prints it on stdout.\r\n\r\n Text is formatted by adding a ASCII frame around it and coloring the text.\r\n Colors can be added to text using color tags, for example:\r\n\r\n My [FG_BLUE]blue[NORMAL] text.\r\n My [BG_BLUE]blue background[NORMAL] text.\r\n \"\"\"\r\n color_re = re.compile(r'\\[(?P[FB]G_[A-Z_]+|NORMAL)\\]')\r\n width = max([len(strip_colors(x)) for x in text.splitlines()])\r\n print('\\n' + hbar(width))\r\n for line in text.splitlines():\r\n if line == '[HBAR]':\r\n print(hbar(width))\r\n continue\r\n tail = width - len(strip_colors(line))\r\n sys.stdout.write('| ')\r\n previous = 0\r\n end = len(line)\r\n for match in color_re.finditer(line):\r\n sys.stdout.write(line[previous:match.start()])\r\n set_color(match.groupdict()['color'])\r\n previous = match.end()\r\n sys.stdout.write(line[previous:end])\r\n sys.stdout.write(' ' * tail + ' |\\n')\r\n print(hbar(width))\r\n\r\n\r\ndef wrap_text(text, width=80):\r\n \"\"\"Wraps text lines to maximum *width* characters.\r\n\r\n Wrapped text is aligned against the left text border.\r\n\r\n :param str text: Text to wrap.\r\n :param int width: Maximum number of characters per line.\r\n :rtype: str\r\n :return: Wrapped text.\r\n \"\"\"\r\n text = re.sub('\\s+', ' ', text).strip()\r\n wrapper = TextWrapper(width=width, break_long_words=False,\r\n replace_whitespace=True)\r\n return wrapper.fill(text)\r\n\r\n\r\ndef rjust_text(text, width=80, indent=0, subsequent=None):\r\n \"\"\"Same as L{wrap_text} with the difference that the text is aligned\r\n against the right text border.\r\n\r\n :param str text: Text to wrap and align.\r\n :param int width: Maximum number of characters per line.\r\n :param int indent: Indentation of the first line.\r\n :type subsequent: int or None\r\n :param subsequent: Indentation of all other lines, if it is None, then the\r\n indentation will be same as for the first line.\r\n \"\"\"\r\n text = re.sub('\\s+', ' ', text).strip()\r\n if subsequent is None:\r\n subsequent = indent\r\n wrapper = TextWrapper(width=width, break_long_words=False,\r\n replace_whitespace=True,\r\n initial_indent=' ' * (indent + subsequent),\r\n subsequent_indent=' ' * subsequent)\r\n return wrapper.fill(text)[subsequent:]\r\n\r\n\r\ndef center_text(text, width=80):\r\n \"\"\"Center all lines of the text.\r\n\r\n It is assumed that all lines width is smaller then B{width}, because the\r\n line width will not be checked.\r\n\r\n :param str text: Text to wrap.\r\n :param int width: Maximum number of characters per line.\r\n :rtype: str\r\n :return: Centered text.\r\n \"\"\"\r\n centered = []\r\n for line in text.splitlines():\r\n centered.append(line.center(width))\r\n return '\\n'.join(centered)\r\n","sub_path":"tea/console/format.py","file_name":"format.py","file_ext":"py","file_size_in_byte":5371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"247194821","text":"#\n# SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nimport os\nimport tensorflow as tf\n\nfrom tensorflow_quantization.quantize import quantize_model\nfrom tensorflow_quantization.utils import convert_saved_model_to_onnx\nfrom tensorflow_quantization.custom_qdq_cases import InceptionQDQCase\n\nfrom examples.utils import ensure_dir, get_tfkeras_model\nfrom examples.data.data_loader import load_data\nfrom examples.utils_finetuning import (\n get_finetuned_weights_dirname,\n fine_tune,\n compile_model,\n)\nimport gc\nimport numpy as np\nimport random\nimport sys\nimport logging\n\n\nMODEL_NAME = \"inception_v3\" # Options=[inception_v3]\n\nHYPERPARAMS = {\n # ################ Data loading ################\n \"tfrecord_data_dir\": \"/media/Data/imagenet_data/tf_records\",\n \"batch_size\": 64,\n \"train_data_size\": None, # Only for `tfrecord`. If None, consider all data, otherwise, consider subset.\n \"val_data_size\": None, # Only for `tfrecord`. If None, consider all data, otherwise, consider subset.\n # ############## Fine-tuning ##################\n \"epochs\": 10,\n \"steps_per_epoch\": 500, # 500, # 'None' if you want to use the default number of steps. If you use this, make sure the number of steps is <= the number of shards (total number of samples / batch_size). Otherwise, an error will occur.\n \"base_lr\": 0.001, # 0.0001\n \"optimizer\": \"piecewise_sgd\", # Options={sgd, piecewise_sgd, adam}\n \"save_root_dir\": \"./weights/{}\".format(\n MODEL_NAME\n ), # DIR is updated to reflect hyperparams\n # ############## Enable/disable tasks ##################\n \"finetune_qat_model\": True, # If True, finetune QAT model. Otherwise, just quantize and load weights if existent.\n \"rewrite_weights_qat_finetuning\": True, # If True, rewrites existing fine-tuned weights. Otherwise, just load weights if they exist.\n \"evaluate_baseline_model\": True,\n \"evaluate_qat_model\": True,\n \"save_baseline_model\": True,\n \"seed\": 42,\n}\n\n# Set seed for reproducible results\nos.environ[\"PYTHONHASHSEED\"] = str(HYPERPARAMS[\"seed\"])\nrandom.seed(HYPERPARAMS[\"seed\"])\nnp.random.seed(HYPERPARAMS[\"seed\"])\ntf.random.set_seed(HYPERPARAMS[\"seed\"])\n\n# Create logger and save to out.log\nLOGGER = logging.getLogger()\nLOGGER.setLevel(logging.INFO)\n\n\ndef main():\n # ------------- Initial settings -------------\n # Create directory to save the fine-tuned weights + add relevant hyperparameters in the name\n qat_save_finetuned_weights = get_finetuned_weights_dirname(HYPERPARAMS)\n ensure_dir(qat_save_finetuned_weights)\n\n # Add terminal and file handlers to logger\n output_file_handler = logging.FileHandler(\n os.path.join(qat_save_finetuned_weights, \"out.log\"), mode=\"w\"\n )\n stdout_handler = logging.StreamHandler(sys.stdout)\n LOGGER.addHandler(output_file_handler)\n LOGGER.addHandler(stdout_handler)\n\n # Load data\n train_batches, val_batches = load_data(HYPERPARAMS, model_name=MODEL_NAME)\n\n # ------------- Baseline model -------------\n LOGGER.info(\"------------- Baseline model -------------\")\n\n # Instantiate Baseline model\n model = get_tfkeras_model(model_name=MODEL_NAME)\n\n if HYPERPARAMS[\"evaluate_baseline_model\"]:\n # Compile model (needed to evaluate model)\n compile_model(model)\n _, baseline_model_accuracy = model.evaluate(val_batches)\n LOGGER.info(\"Baseline val accuracy: {}\".format(baseline_model_accuracy))\n\n if HYPERPARAMS[\"save_baseline_model\"]:\n tf.keras.models.save_model(\n model, os.path.join(HYPERPARAMS[\"save_root_dir\"], \"saved_model_baseline\")\n )\n convert_saved_model_to_onnx(\n saved_model_dir=os.path.join(\n HYPERPARAMS[\"save_root_dir\"], \"saved_model_baseline\"\n ),\n onnx_model_path=os.path.join(\n HYPERPARAMS[\"save_root_dir\"], \"model_baseline.onnx\"\n ),\n )\n\n # ------------- QAT model -------------\n # Quantize model\n LOGGER.info(\"\\n------------- QAT model -------------\")\n q_model = quantize_model(model, custom_qdq_cases=[InceptionQDQCase()])\n # q_model = quantize_model(model)\n\n finetuned_qat_weights_path = os.path.join(\n qat_save_finetuned_weights, \"checkpoints_best\"\n )\n # Performs fine-tuning if `rewrite` is enabled or if fine-tuned weights don't exist yet\n # (1st time fine-tuning model).\n if HYPERPARAMS[\"finetune_qat_model\"] and (\n HYPERPARAMS[\"rewrite_weights_qat_finetuning\"]\n or not os.path.exists(finetuned_qat_weights_path)\n ):\n # Fine-tuning + saving new checkpoints\n LOGGER.info(\"\\nFine-tuning model...\")\n fine_tune(\n q_model,\n train_batches,\n val_batches,\n qat_save_finetuned_weights,\n HYPERPARAMS,\n LOGGER,\n )\n LOGGER.info(\"Fine-tuning done!\")\n\n # Loads best weights if they exist\n if os.path.exists(finetuned_qat_weights_path + \".index\"):\n LOGGER.info(\"Loading fine-tuned weights...\")\n q_model.load_weights(finetuned_qat_weights_path).expect_partial()\n LOGGER.info(\"Loaded complete!\")\n compile_model(q_model)\n\n if HYPERPARAMS[\"evaluate_qat_model\"]:\n LOGGER.info(\"\\nEvaluating QAT model...\")\n _, qat_model_accuracy = q_model.evaluate(val_batches)\n LOGGER.info(\"QAT val accuracy: {}\".format(qat_model_accuracy))\n\n # Save quantized model\n LOGGER.info(\"\\nSaving QAT model\")\n tf.keras.models.save_model(\n q_model, os.path.join(qat_save_finetuned_weights, \"saved_model\")\n )\n\n # Clear GPU and invoke Garbage Collector to avoid script ending during ONNX conversion\n tf.keras.backend.clear_session()\n gc.collect()\n del model\n del q_model\n\n # Convert SavedModel to ONNX\n LOGGER.info(\"\\nONNX conversion...\")\n convert_saved_model_to_onnx(\n saved_model_dir=os.path.join(qat_save_finetuned_weights, \"saved_model\"),\n onnx_model_path=os.path.join(qat_save_finetuned_weights, \"model.onnx\"),\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tools/tensorflow-quantization/examples/inception/run_qat_workflow.py","file_name":"run_qat_workflow.py","file_ext":"py","file_size_in_byte":6684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"502326783","text":"from numpy import *\nimport matplotlib.pyplot as plt\nfrom matplotlib import rc\nimport phase_embedding\n\nrc('text', usetex=True)\nrc('font',**{'family':'serif','serif':['Computer Modern Roman']})\nplt.rcParams.update({'font.size': 8 })\nplt.rcParams.update({'axes.labelsize': 11})\nplt.rcParams.update({'legend.fontsize': 10})\nplt.rcParams.update({'axes.linewidth': 0.5})\nplt.rcParams.update({'patch.linewidth': 0.5})\ngolden = (1 + 5 ** 0.5) / 2\n\nfile_name = phase_embedding.generate_raw_data()\n\nfig = plt.figure(figsize=(1.5*golden,1.5))\nax1 = fig.add_subplot(111)\nphase_embedding.build_ax_phase(ax1, file_name)\n# plt.tight_layout()\n# plt.show()\n\nplt.subplots_adjust(0,0,1,1)\nplt.savefig('C:\\Temp\\_Limpo\\subplots.pdf', bbox_inches='tight')\n\n","sub_path":"Python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"577815444","text":"# coding=utf-8\n# 自动检测Mysql运行效率脚本\n# @author: Ravior(zhoufei@gfun.me)\n# @date:2017-10-18\n\nfrom __future__ import print_function\nimport MySQLdb\nimport sys, getopt\nfrom tabulate import tabulate\n\n# Mysql配置\nHOST = '192.168.10.18'\nPORT = 3306\nUSER = 'root'\nPASSWD = '2016db-pachong'\nCHARSET = 'utf8'\n\nopts, args = getopt.getopt(sys.argv[1:], \"h:u:p:\")\nfor k,v in opts:\n\tif k in ('-h',):\n\t\tHOST = v\n\telif k in ('-u',):\n\t\tUSER = v\n\telif k in ('-p',):\n\t\tPASSWD = v\n\n\nconn = None\ncursor = None\n\ntry:\n\t# 链接数据库\n\tconn = MySQLdb.connect(\n\t host = HOST,\n\t port = PORT,\n\t user = USER,\n\t passwd = PASSWD,\n\t charset = CHARSET\n\t)\n\tcursor = conn.cursor()\nexcept Exception as e:\n\tprint(\"数据库链接失败, 失败原因:[%s]\"%(e))\n\texit()\n\nprint('数据库链接失败')\n\t\ncursor.execute('show databases;')\ntables = cursor.fetchall()\n\n\ncursor.execute(\"show status like '%connect%'\")\nfor row in cursor.fetchall():\n\tif row[0] == 'Max_used_connections':\n\t\tprint('历史最大连接数:', row[1])\n\telif row[0] == 'Max_used_connections_time':\n\t\tprint('历史最大连接数发生时间:', row[1])\n\telif row[0] == 'Threads_connected':\n\t\tprint('当前连接数:',row[1])\n\ncursor.execute(\"show variables\")\nfor row in cursor.fetchall():\n\t# print(row)\n\tif row[0] == 'datadir':\n\t\tprint('数据库文件存在路径:', row[1])\n\telif row[0] == 'max_connections':\n\t\tprint('数据库最大连接数:', row[1])\n\nconn.select_db('information_schema')\ncursor.execute(\"select concat(round(sum(`data_length`)/(1024*2014),2), 'MB') as 'DB_SIZE',concat(round(sum(`index_length`)/(1024*2014),2), 'MB') as 'INDEX_SIZE' from tables\")\ndb_size = cursor.fetchone()\nprint('数据库大小:',db_size[0])\nprint('数据库索引大小:',db_size[1])\n\nprint('当前连接情况')\nprint('-'*100)\ncursor.execute(\"show processlist\")\nprocesslist = cursor.fetchall()\nprint(tabulate(list(processlist), headers=[\"Pid\",\"User\", \"Client\",\"Table\",\"Status\",\"Time\",\"Type\",\"Operate\"]))\nprint('-'*100)\n\ntables2 = []\nfor row in tables:\n\tcursor.execute(\"select concat(round(sum(`data_length`)/(1024*2014),2), 'MB') as 'DB_SIZE',concat(round(sum(`index_length`)/(1024*2014),2), 'MB') as 'INDEX_SIZE' from tables where table_schema='%s'\"%(row[0]))\n\t\n\tdb_size = cursor.fetchone()\n\ttables2.append([row[0],db_size[0],db_size[1]])\n\nprint(tabulate(tables2, headers=[u\"数据库\",u\"数据大小\", u\"索引大小\"]))\nprint('-'*100)\n\ncursor.close()\nconn.close()\n\n\n\n","sub_path":"mysql.py","file_name":"mysql.py","file_ext":"py","file_size_in_byte":2433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"410316909","text":"#!/usr/bin/env python3\n\nimport argparse\nimport struct\nimport time\nfrom urllib import request\n\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(\n description='Adds identifiers to iTunes.')\n parser.add_argument('--X-Dsid',\n help='X-Dsid for request headers',\n action='store', required=True, dest='dsid')\n\n parser.add_argument('--Cookie',\n help='Cookie for request headers',\n action='store', required=True, dest='cookie')\n\n parser.add_argument('--X-Guid',\n help='X-Guid for request headers',\n action='store', required=True, dest='guid')\n\n parser.add_argument('--input-file',\n help='The file location with the input identifiers.',\n action='store', required=True, dest='input_location')\n\n return parser.parse_args()\n\n\ndef construct_request_body(timestamp, itunes_identifier):\n hex = '61 6a 43 41 00 00 00 45 6d 73 74 63 00 00 00 04 55 94 17 a3 6d 6c 69 64 00 00 00 04 00 00 00 00 6d 75 73 72 00 00 00 04 00 00 00 81 6d 69 6b 64 00 00 00 01 02 6d 69 64 61 00 00 00 10 61 65 41 69 00 00 00 08 00 00 00 00 11 8c d9 2c 00'\n\n body = bytearray.fromhex(hex);\n body[16:20] = struct.pack('>I', timestamp)\n body[-5:] = struct.pack('>I', itunes_identifier)\n return body\n\n\ndef add_song(dsid, cookie, guid, itunes_identifier):\n data = construct_request_body(int(time.time()), itunes_identifier)\n\n headers = {\n 'X-Apple-Store-Front' : '143441-1,32',\n 'Client-iTunes-Sharing-Version' : '3.12',\n 'Accept-Language' : 'en-us, en;q=0.50',\n 'Client-Cloud-DAAP-Version' : '1.0/iTunes-12.2.1.16',\n 'Accept-Encoding' : 'gzip',\n 'X-Apple-itre' : '0',\n 'Client-DAAP-Version' : '3.13',\n 'User-Agent' : 'iTunes/12.2.1 (Macintosh; OS X 10.10.4) AppleWebKit/600.7.12',\n 'Connection' : 'keep-alive',\n 'Content-Type' : 'application/x-dmap-tagged',\n 'X-Dsid' : dsid,\n 'Cookie' : cookie,\n 'X-Guid' : guid,\n 'Content-Length' : '77'\n }\n\n req = request.Request('https://ld-4.itunes.apple.com/WebObjects/MZDaap.woa/daap/databases/1/cloud-add', data, headers)\n request.urlopen(req)\n\n\ndef add_to_itunes(dsid, cookie, guid, input_location):\n with open(input_location) as itunes_identifiers_file:\n for line in itunes_identifiers_file:\n itunes_identifier = int(line)\n\n try:\n add_song(dsid, cookie, guid, itunes_identifier)\n print('Successfully inserted a song!')\n # Try playing with the interval here to circumvent the API rate limit\n time.sleep(30)\n except Exception as e:\n print('Something went wrong while inserting ' + str(itunes_identifier) + ' : ' + str(e))\n\n\ndef main():\n args = parse_arguments()\n print(args)\n add_to_itunes(**vars(args))\n\nif __name__ == '__main__':\n main()\n","sub_path":"insert-songs.py","file_name":"insert-songs.py","file_ext":"py","file_size_in_byte":3011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"528895324","text":"import sys\nimport json\n\nfrom preprocessing.json_formater import to_char_level_format\n\ninfile = open(sys.argv[1], encoding=\"utf-8\")\noutfile = open(sys.argv[2], \"w\", encoding=\"utf-8\")\n\njdata = json.load(infile)\ninfile.close()\n\njdata_new = to_char_level_format(jdata)\n\njson.dump(jdata_new, outfile, indent=4)\n\noutfile.close()\n\n","sub_path":"nerre/scripts/converters/json2char_level_json.py","file_name":"json2char_level_json.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"353644398","text":"\"\"\"\nTests for dcmstack.extract\n\"\"\"\nimport sys, warnings\nfrom os import path\nfrom nose.tools import ok_, eq_, assert_raises\n\ntest_dir = path.dirname(__file__)\nsrc_dir = path.normpath(path.join(test_dir, '../src'))\nsys.path.insert(0, src_dir)\nwith warnings.catch_warnings():\n warnings.simplefilter('ignore')\n from dcmstack import extract\ndicom, csareader = extract.dicom, extract.csareader\n\nclass TestCsa(object):\n def setUp(self):\n data_fn = path.join(test_dir, 'data', 'extract', 'csa_test.dcm')\n self.data = dicom.read_file(data_fn)\n\n def tearDown(self):\n del self.data\n\n def test_simplify(self):\n eq_(extract.simplify_csa_dict(None), None)\n csa_dict = csareader.read(self.data[dicom.tag.Tag(0x29, 0x1010)].value)\n simp_dict = extract.simplify_csa_dict(csa_dict)\n for tag in csa_dict['tags']:\n items = csa_dict['tags'][tag]['items']\n if len(items) == 0:\n ok_(not tag in simp_dict)\n elif len(items) == 1:\n eq_(simp_dict[tag], items[0])\n else:\n eq_(simp_dict[tag], items)\n\n def test_csa_image_trans(self):\n csa_dict = extract.csa_series_trans_func(self.data[(0x29, 0x1010)])\n eq_(csa_dict[\"EchoLinePosition\"], 64)\n\n def test_parse_phx_line(self):\n ok_(extract._parse_phoenix_line(\"\") is None)\n ok_(extract._parse_phoenix_line(\"#test = 2\") is None)\n\n eq_(extract._parse_phoenix_line('test = \"\" 2 \"\"'), ('test', ' 2 '))\n eq_(extract._parse_phoenix_line('test = \"\" #2 \"\"'), ('test', ' #2 '))\n eq_(extract._parse_phoenix_line('test = \"\" 2 \"\"#='),\n ('test', ' 2 '))\n eq_(extract._parse_phoenix_line(\"test = 2#\"), ('test', 2))\n eq_(extract._parse_phoenix_line(\"test = 0x2\"), ('test', 2))\n eq_(extract._parse_phoenix_line(\"test = 2.\"), ('test', 2.0))\n\n assert_raises(extract.PhoenixParseError,\n extract._parse_phoenix_line,\n 'test = blah')\n assert_raises(extract.PhoenixParseError,\n extract._parse_phoenix_line,\n '==')\n assert_raises(extract.PhoenixParseError,\n extract._parse_phoenix_line,\n 'test')\n assert_raises(extract.PhoenixParseError,\n extract._parse_phoenix_line,\n 'test = \"\" 2 \"\"3')\n\n def test_csa_series_trans(self):\n csa_dict = extract.csa_series_trans_func(self.data[(0x29, 0x1020)])\n eq_(csa_dict['MrPhoenixProtocol.sEFISPEC.bEFIDataValid'], 1)\n\nclass TestMetaExtractor(object):\n def setUp(self):\n data_fn = path.join(test_dir, 'data', 'extract', 'csa_test.dcm')\n self.data = dicom.read_file(data_fn)\n\n def tearDown(self):\n del self.data\n\n def test_get_elem_key(self):\n ignore_rules = (extract.ignore_non_ascii_bytes,)\n extractor = extract.MetaExtractor(ignore_rules=ignore_rules)\n for elem in self.data:\n key = extractor._get_elem_key(elem)\n ok_(key.strip() != '')\n ok_(key[0].isalpha())\n ok_(key[-1].isalnum())\n\n def test_get_elem_value(self):\n ignore_rules = (extract.ignore_non_ascii_bytes,)\n extractor = extract.MetaExtractor(ignore_rules=ignore_rules)\n for elem in self.data:\n value = extractor._get_elem_value(elem)\n if elem.VM > 1:\n ok_(isinstance(value, list))\n if elem.VR in extract.unpack_vr_map.keys() + ['DS', 'IS']:\n if elem.VM == 1:\n ok_(not isinstance(value, str))\n else:\n ok_(not any(isinstance(val, str) for val in value))\n\n def test_dup_trans(self):\n translators = [extract.csa_image_trans, extract.csa_image_trans]\n extractor = extract.MetaExtractor(translators=translators)\n assert_raises(ValueError, extractor, self.data)\n\n def test_reloc_private(self):\n extractor = extract.MetaExtractor()\n self.data[(0x29, 0x10)].tag = dicom.tag.Tag((0x29, 0x20))\n self.data[(0x29, 0x1010)].tag = dicom.tag.Tag((0x29, 0x2010))\n self.data[(0x29, 0x1020)].tag = dicom.tag.Tag((0x29, 0x2020))\n meta_dict = extractor(self.data)\n eq_(meta_dict[\"CsaImage.EchoLinePosition\"], 64)\n ok_(meta_dict['CsaSeries.MrPhoenixProtocol.sEFISPEC.bEFIDataValid'], 1)\n\n def test_non_reloc_private(self):\n extractor = extract.MetaExtractor()\n meta_dict = extractor(self.data)\n eq_(meta_dict[\"CsaImage.EchoLinePosition\"], 64)\n ok_(meta_dict['CsaSeries.MrPhoenixProtocol.sEFISPEC.bEFIDataValid'], 1)","sub_path":"test/test_extract.py","file_name":"test_extract.py","file_ext":"py","file_size_in_byte":4682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"547977453","text":"from torchtext import data, datasets\nfrom torch.autograd import Variable\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch\nimport argparse\nimport random\nimport argparse\n\n\nparser = argparse.ArgumentParser(description='cbow+mlp')\nparser.add_argument('--num_labels', default=3, type=int, help='number of labels (default: 3)')\nparser.add_argument('--hidden_dim', default=10, type=int, help='number of hidden dim (default: 10)')\n\ninputs = datasets.snli.ParsedTextField(lower=True)\nlabels = data.Field(sequential=False)\n\ntrain, dev, test = datasets.SNLI.splits(inputs, labels)\n\ninputs.build_vocab(train)\nlabels.build_vocab(train)\n\ntrain_iter, dev_iter, test_iter = data.BucketIterator.splits((train, dev, test), batch_size=64, device=-1)\n\n\n# Continuous Bag of Words (CBOW) + Multi-Layer Perceptron (MLP)\nclass CBOW_MLP(nn.Module): \n\n def __init__(self, vocab_size, embedding_dim, hidden_dim, num_labels):\n \"\"\"\n @param vocab_size: size of the vocabulary\n @param embedding_dim: size of the word embedding\n @param hidden_dim: size of the hidden layer\n @param num_labels: number of labels\n \"\"\"\n super(CBOW_MLP, self).__init__()\n self.embed = nn.Embedding(vocab_size, embedding_dim, padding_idx=0)\n self.dropout = nn.Dropout(p=0.5)\n self.linear_1 = nn.Linear(2 * embedding_dim, hidden_dim) \n self.linear_2 = nn.Linear(hidden_dim, hidden_dim)\n self.linear_3 = nn.Linear(hidden_dim, num_labels)\n self.init_weights()\n\n def forward(self, prem, hypo):\n \"\"\"\n @param prem: a long tensor of size (batch_size * sentence_length)\n @param hypo: a long tensor of size (batch_size * sentence_length)\n \"\"\"\n emb_prem = self.embed(prem).mean(1)\n emb_hypo = self.embed(hypo).mean(1)\n emb_concat = torch.cat([emb_prem, emb_hypo], 1)\n out = self.dropout(emb_concat)\n out = F.relu(self.linear_1(out))\n out = F.relu(self.linear_2(out))\n out = self.dropout(self.linear_3(out))\n return F.log_softmax(out)\n\n def init_weights(self):\n initrange = 0.1\n lin_layers = [self.linear_1, self.linear_2, self.linear_3]\n em_layer = [self.embed]\n for layer in lin_layers + em_layer:\n layer.weight.data.uniform_(-initrange, initrange)\n if layer in lin_layers:\n layer.bias.data.fill_(0)\n\n\ndef training_loop(model, loss, optimizer, train_iter, dev_iter, max_num_train_steps):\n step = 0\n for i in range(max_num_train_steps):\n model.train()\n for batch in train_iter:\n premise = batch.premise.transpose(0, 1)\n hypothesis = batch.hypothesis.transpose(0, 1)\n labels = batch.label - 1\n model.zero_grad()\n output = model(premise, hypothesis)\n lossy = loss(output, labels)\n lossy.backward()\n optimizer.step()\n if step % 10 == 0:\n print( \"Step %i; Loss %f; Dev acc %f\" % (step, lossy.data[0], evaluate(model, dev_iter)))\n step += 1\n\n\ndef evaluate(model, data_iter):\n \"\"\"\n @param model: \n @param data_iter: data loader for the dataset to test against\n \"\"\"\n model.eval()\n correct = 0\n total = 0\n for batch in data_iter:\n premise = batch.premise.transpose(0, 1)\n hypothesis = batch.hypothesis.transpose(0, 1)\n labels = (batch.label - 1).data\n output = model(premise, hypothesis)\n _, predicted = torch.max(output.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum()\n model.train()\n return correct / float(total)\n\n\ndef main():\n global args, max_num_train_steps, learning_rate, batch_size, embedding_dim\n args = parser.parse_args()\n\n vocab_size = len(inputs.vocab)\n #num_labels = 3\n #hidden_dim = 50\n embedding_dim = 300\n batch_size = 32\n learning_rate = 0.004\n max_num_train_steps = 1000\n \n model = CBOW_MLP(vocab_size, embedding_dim, args.hidden_dim, args.num_labels) \n # Loss and Optimizer\n loss = nn.CrossEntropyLoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)\n # Train the model\n training_loop(model, loss, optimizer, train_iter, dev_iter, max_num_train_steps)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"CBOW_MLP.py","file_name":"CBOW_MLP.py","file_ext":"py","file_size_in_byte":4327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"156658998","text":"from neural_net import SingleLayeredNeuralNetwork\nimport numpy as np\nimport pickle\n\nm = SingleLayeredNeuralNetwork(learning_rate = 1e-1, n_hidden = 20, iterations = 50)\n\nx = np.random.random((1000,50))\na = np.random.random(50)\na /= a.sum()\ny = np.sum(x * a, 1)\n\nd = {'x': x, 'y': y}\nwith open('data.pkl', 'wb') as f:\n pickle.dump(d, f, -1)\nwith open('model.pkl', 'wb') as f:\n pickle.dump(m, f)\n","sub_path":"make_model.py","file_name":"make_model.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"129544140","text":"from otree.api import (\n models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,\n Currency as c, currency_range\n)\nimport random\nfrom collections import OrderedDict\nimport json\nimport itertools\n\nauthor = 'Manu Munoz'\n\ndoc = \"\"\"\nIdentity Switch - Networks: FLUID\n\"\"\"\n\n\nclass Constants(BaseConstants):\n #------------------------------------------\n name_in_url = 'fluid_es'\n names = ['1','2','3','4','5','6','7']\n players_per_group = len(names)\n instructions_template = 'fluid_es/Instructions.html'\n periods = 1\n num_rounds = periods\n #------------------------------------------\n # Treatment & Group parameters\n others = len(names) - 1\n attribute = [1,5,1,5,1,1,5]\n attributes = {'1': 1, '2': 5, '3': 1, '4': 5, '5': 1, '6': 1, '7': 5}\n circle = 1 # Majority\n triangle = 0 # Minority\n part_name = 1\n part_fixed = 2\n part_fluid = 3\n part_alloc = 4\n rounds_fixed = 10\n #------------------------------------------\n # Payoffs\n exp_currency = \"puntos\"\n currency = \"pesos\"\n currency_exchange = 800\n points_exchange = 1\n link_cost = 2\n liked_gain = 6\n disliked_gain = 4\n personal = 1\n exchange = 2\n switch_cost = 6\n switch_free = 0\n #------------------------------------------\n one = 1\n zero = 0\n #------------------------------------------\n # Interdependent Costs\n multiplier = 2\n n_min = 3\n n_maj = 4\n #------------------------------------------\n # Group Names\n group_a = 'Leones' #Leones\n group_b = 'Tigres' #Tigres\n group_c = 'Leopardos' #Leopardos\n group_d = 'Jaguares' #Jaguares\n group_e = 'Gatos' #Gatos\n group_f = 'Coyotes' #Coyotes\n group_g = 'Chacales' #Chacales\n group_h = 'Lobos' #Lobos\n group_i = 'Zorros' #Zorros\n group_j = 'Perros' #Perros\n #------------------------------------------\n # # FOR TEST - DELETE AFTERWARDS!!!\n # circles_name = 1\n # triangles_name = 6\n # circles_label =\"Leones\"\n # triangles_label = \"Perros\"\n # #------------------------------------------\n\n\nclass Subsession(BaseSubsession):\n def creating_session(self):\n treat = itertools.cycle([1, 2, 3, 4, 5, 6])\n # 1: Full-Free, 2: Sticky-Free, 3: Blurry-Free, 4: Full-Cost, 5: Sticky-Cost, 6: Blurry-Cost\n # for p in self.get_players():\n # p.treat = next(treat)\n for p in self.get_players():\n if 'treatment' in self.session.config:\n # demo mode\n p.treat = self.session.config['treatment']\n else:\n # live experiment mode\n p.treat = next(treat)\n num_players_err = 'Too many participants for such a short name list'\n # the following may create issues with mTurk sessions where num participants is doubled\n assert len(Constants.names) <= self.session.num_participants, num_players_err\n '''\n for g in self.get_groups():\n cur_names = Constants.names.copy()\n # random.shuffle(cur_names)\n for i, p in enumerate(g.get_players()):\n p.name = cur_names[i]\n '''\n for p in self.get_players():\n p.given_type = int(Constants.attribute[p.id_in_group - 1])\n if p.given_type == 1: # circle-circle\n p.was_circle = 1\n else: # triangle-triangle\n p.was_circle = 0\n\n if self.round_number == 1:\n paying_round_2 = random.randint(1, Constants.num_rounds)\n self.session.vars['paying_round_2'] = paying_round_2\n\n\nclass Group(BaseGroup):\n total_init_circles = models.IntegerField()\n total_init_triangles = models.IntegerField()\n total_circles = models.IntegerField()\n total_triangles = models.IntegerField()\n total_up = models.IntegerField()\n total_down = models.IntegerField()\n network_data = models.LongStringField()\n total_circle_switch = models.IntegerField()\n total_triangle_switch = models.IntegerField()\n\n def assign_random_names_and_positions(self):\n name_indexes = random.sample(range(7), 7)\n positions = random.sample(range(7), 7)\n i = 0\n for p in self.get_players():\n p.name = Constants.names[name_indexes[i]]\n p.position = positions[i] + 1\n i += 1\n\n def generate_nodes(self):\n players = self.get_players()\n players.sort(key=lambda x: x.position)\n return [{'data': {'id': p.name, 'name': p.name, 'action': p.action, 'given': p.given_type,\n 'shape': p.chosen_type, 'reveal': p.reveal, 'location': p.position, 'treat': p.treat}, 'group': 'nodes'}\n for p in players]\n\n def displaying_network(self):\n nodes = self.generate_nodes()\n edges = []\n elements = nodes + edges\n style = [{'selector': 'node', 'style': {'content': 'data(name)'}}]\n self.network_data = json.dumps({'elements': elements,\n 'style': style,\n })\n\n def forming_network(self):\n nodes = self.generate_nodes()\n edges = []\n for p in self.get_players():\n friends = json.loads(p.friends)\n edges.extend(\n [{'data': {'id': p.name + '_' + str(i), 'source': p.name, 'target': i}, 'group': 'edges'}\n for i in friends])\n\n # Copio el valor de las propuestas recogido en las variables con numbre (1,2,3,...) a\n # prop_to_1, prop_to_2, ...\n for i in friends:\n setattr(p, 'prop_to_' + i, getattr(p, i))\n\n elements = nodes + edges\n style = [{'selector': 'node', 'style': {'content': 'data(name)'}}]\n self.network_data = json.dumps({'elements': elements,\n 'style': style,\n })\n\n def choosing_types(self):\n for player in self.get_players():\n if player.chosen_type == 1:\n player.is_circle = 1\n player.liked_action = 1\n elif player.chosen_type == 2:\n player.is_circle = 0\n player.liked_action = 0\n elif player.chosen_type == 3:\n player.is_circle = 1\n player.liked_action = 1\n elif player.chosen_type == 4:\n player.is_circle = 0\n player.liked_action = 0\n elif player.chosen_type == 5:\n player.is_circle = 0\n player.liked_action = 0\n elif player.chosen_type == 6:\n player.is_circle = 1\n player.liked_action = 1\n elif player.chosen_type == 7:\n player.is_circle = 1\n player.liked_action = 1\n else:\n player.is_circle = 0\n player.liked_action = 0\n\n def switching_choice(self):\n for player in self.get_players():\n if player.treat == 1 or player.treat == 4:\n if player.given_type == 1 and player.chosen_type == 5:\n player.switch = 1\n player.circle_switch = 1\n elif player.given_type == 1 and player.chosen_type == 1:\n player.switch = 0\n elif player.given_type == 5 and player.chosen_type == 1:\n player.switch = 1\n player.triangle_switch = 1\n elif player.given_type == 5 and player.chosen_type == 5:\n player.switch = 0\n elif player.treat == 2 or player.treat == 5:\n if player.given_type == 1 and player.chosen_type == 2:\n player.switch = 1\n player.circle_switch = 1\n elif player.given_type == 1 and player.chosen_type == 1:\n player.switch = 0\n elif player.given_type == 5 and player.chosen_type == 6:\n player.switch = 1\n player.triangle_switch = 1\n elif player.given_type == 5 and player.chosen_type == 5:\n player.switch = 0\n elif player.treat == 3 or player.treat == 6:\n if player.given_type == 1 and player.chosen_type == 4:\n player.switch = 1\n player.circle_switch = 1\n elif player.given_type == 1 and player.chosen_type == 3:\n player.switch = 0\n elif player.given_type == 5 and player.chosen_type == 7:\n player.switch = 1\n player.triangle_switch = 1\n elif player.given_type == 5 and player.chosen_type == 8:\n player.switch = 0\n\n def summing_switching(self):\n players = self.get_players()\n switch_cir = [p.circle_switch for p in players]\n switch_tri = [p.triangle_switch for p in players]\n self.total_circle_switch = sum(switch_cir)\n self.total_triangle_switch = sum(switch_tri)\n\n def ingroup_switching(self):\n for p in self.get_players():\n if p.given_type == 1:\n p.ingroup_switch = self.total_circle_switch\n p.ingroup_noswitch = Constants.n_maj - p.ingroup_switch\n else:\n p.ingroup_switch = self.total_triangle_switch\n p.ingroup_noswitch = Constants.n_min - p.ingroup_switch\n\n def switching_costs(self):\n for player in self.get_players():\n if player.treat == 1 or player.treat == 2 or player.treat == 3:\n player.switch_cost = 0\n elif player.treat == 4 or player.treat == 5:\n if player.given_type == 1 and player.switch == 1:\n player.switch_cost = Constants.switch_cost + Constants.multiplier * (Constants.n_maj - player.ingroup_switch)\n elif player.given_type == 1 and player.switch == 0:\n player.switch_cost = 0\n elif player.given_type == 5 and player.switch == 1:\n player.switch_cost = Constants.switch_cost + Constants.multiplier * (Constants.n_min - player.ingroup_switch)\n elif player.given_type == 5 and player.switch == 0:\n player.switch_cost = 0\n elif player.treat == 6:\n if player.reveal == 0:\n player.switch_cost = 0\n elif player.reveal > 0:\n if player.given_type == 1 and player.switch == 1:\n player.switch_cost = Constants.switch_cost + Constants.multiplier * (Constants.n_maj - player.ingroup_switch)\n elif player.given_type == 1 and player.switch == 0:\n player.switch_cost = Constants.switch_cost\n elif player.given_type == 5 and player.switch == 1:\n player.switch_cost = Constants.switch_cost + Constants.multiplier * (Constants.n_min - player.ingroup_switch)\n elif player.given_type == 5 and player.switch == 0:\n player.switch_cost = Constants.switch_cost\n\n def summing_initial_types(self):\n players = self.get_players()\n init_circles = [p.was_circle for p in players]\n self.total_init_circles = sum(init_circles)\n self.total_init_triangles = len(Constants.names)-self.total_init_circles\n\n def summing_types(self):\n players = self.get_players()\n circles = [p.is_circle for p in players]\n self.total_circles = sum(circles)\n self.total_triangles = len(Constants.names)-self.total_circles\n\n def calculate_props_from_and_links(self):\n for player_to in self.get_players():\n for player_from in self.get_players():\n kiubo_prop_from = False\n kiubo_link = 0\n if player_from.name != player_to.name: # si no soy yo mismo\n kiubo_prop_from = bool(getattr(player_from, 'prop_to_' + player_to.name)) # cojo el valor de la propuesta\n if getattr(player_to, 'prop_to_' + player_from.name) == True and kiubo_prop_from == True:\n kiubo_link = 1\n else:\n kiubo_link = 0\n else:\n kiubo_link = 0 # link conmigo mismo = 1\n\n setattr(player_to, 'prop_from_' + player_from.name, kiubo_prop_from) # la añado a prop_from_X\n setattr(player_to, 'link_with_' + player_from.name, kiubo_link)\n\n def calculate_degree(self):\n for player in self.get_players():\n player.out_degree = player.prop_to_1 + player.prop_to_2 + player.prop_to_3 + player.prop_to_4 + player.prop_to_5 +\\\n player.prop_to_6 + player.prop_to_7\n player.degree = player.link_with_1 + player.link_with_2 + player.link_with_3 + player.link_with_4 + player.link_with_5 + \\\n player.link_with_6 + player.link_with_7\n\n def linking_costs(self):\n for player in self.get_players():\n if player.out_degree >= 1:\n player.linking_costs = player.out_degree * Constants.link_cost\n else:\n player.linking_costs = 0\n\n def calculate_actions(self):\n for player in self.get_players():\n for partner in self.get_players():\n action_up = partner.action\n if action_up == 1:\n choice = 1\n else:\n choice = 0\n setattr(player, 'action_' + partner.name, choice) # la añado a prop_from_X\n\n def sum_coordinations(self):\n for player in self.get_players():\n if player.action == player.action_1 and player.link_with_1 == 1:\n player.coordinate_1 = 1\n else:\n player.coordinate_1 = 0\n if player.action == player.action_2 and player.link_with_2 == 1:\n player.coordinate_2 = 1\n else:\n player.coordinate_2 = 0\n if player.action == player.action_3 and player.link_with_3 == 1:\n player.coordinate_3 = 1\n else:\n player.coordinate_3 = 0\n if player.action == player.action_4 and player.link_with_4 == 1:\n player.coordinate_4 = 1\n else:\n player.coordinate_4 = 0\n if player.action == player.action_5 and player.link_with_5 == 1:\n player.coordinate_5 = 1\n else:\n player.coordinate_5 = 0\n if player.action == player.action_6 and player.link_with_6 == 1:\n player.coordinate_6 = 1\n else:\n player.coordinate_6 = 0\n if player.action == player.action_7 and player.link_with_7 == 1:\n player.coordinate_7 = 1\n else:\n player.coordinate_7 = 0\n\n def coordination_score(self):\n for player in self.get_players():\n player.coordination_score = 1 + player.coordinate_1 + player.coordinate_2 + \\\n player.coordinate_3 + player.coordinate_4 + player.coordinate_5 + \\\n player.coordinate_6 + player.coordinate_7\n\n def values_coordination(self):\n for player in self.get_players():\n if player.action == player.liked_action:\n player.coordination_gains = player.coordination_score * Constants.liked_gain\n else:\n player.coordination_gains = player.coordination_score * Constants.disliked_gain\n\n def round_gains(self):\n for player in self.get_players():\n player.round_gains = player.coordination_gains - player.linking_costs - player.switch_cost\n\n def round_payoffs(self):\n for player in self.get_players():\n if self.subsession.round_number == self.session.vars['paying_round_2']:\n player.payoff = player.round_gains\n else:\n player.payoff = Constants.switch_free\n\n def round_points(self):\n for player in self.get_players():\n if self.subsession.round_number == self.session.vars['paying_round_2']:\n player.points_fluid = player.round_gains\n else:\n player.points_fluid = 0\n\n def summing_choices(self):\n players = self.get_players()\n action_up = [p.action for p in players]\n self.total_up = sum(action_up)\n self.total_down = len(Constants.names) - self.total_up\n\n\nclass Player(BasePlayer):\n treat = models.IntegerField() # Treatments from 1 to 3\n given_type = models.IntegerField() # combination of symbol and preference\n chosen_type = models.IntegerField() # combination of symbol and preference\n was_circle = models.IntegerField()\n is_circle = models.IntegerField()\n action = models.IntegerField() # Reported belief on P3's verification\n old_action = models.IntegerField() # Reported belief on P3's verification\n liked_action = models.IntegerField()\n out_degree = models.IntegerField()\n degree = models.IntegerField()\n coordination_score = models.IntegerField()\n coordination_gains = models.IntegerField()\n linking_costs = models.IntegerField()\n round_gains = models.IntegerField()\n points_fluid = models.IntegerField()\n switch = models.IntegerField()\n switch_cost = models.IntegerField()\n circle_switch = models.IntegerField(initial=0)\n triangle_switch = models.IntegerField(initial=0)\n ingroup_switch = models.IntegerField(initial=0)\n ingroup_noswitch = models.IntegerField(initial=0)\n reveal = models.IntegerField()\n\n def vars_for_template(self):\n return {\n 'circles_name': self.participant.vars['circles_name'],\n 'triangles_name': self.participant.vars['triangles_name'],\n 'circles_label': self.participant.vars['circles_label'],\n 'triangles_label': self.participant.vars['triangles_label'],\n 'names': len(Constants.names)\n }\n\n # def vars_for_template(self):\n # return {\n # 'circles_name': Constants.circles_name,\n # 'triangles_name': Constants.triangles_name,\n # 'circles_label': Constants.circles_label,\n # 'triangles_label': Constants.triangles_label,\n # 'names': len(Constants.names)\n # }\n\n def var_between_apps(self):\n if self.subsession.round_number == self.session.vars['paying_round_2']:\n self.participant.vars['part_fluid_round'] = self.session.vars['paying_round_2']\n self.participant.vars['part_fluid_payoff'] = self.points_fluid\n\n name = models.StringField()\n friends = models.LongStringField()\n position = models.IntegerField()\n\n for i in Constants.names:\n locals()[i] = models.BooleanField(widget=widgets.CheckboxInput, blank=True)\n # Añado a Player las variables de propuestas con friendly names que luego rellenaremos\n locals()['prop_to_' + i] = models.BooleanField(initial=0)\n locals()['prop_from_' + i]= models.BooleanField(initial=0)\n locals()['link_with_' + i]= models.IntegerField(initial=0)\n locals()['action_' + i]= models.IntegerField(initial=0)\n locals()['coordinate_' + i]= models.IntegerField(initial=0)\n\n del locals()['i']","sub_path":"fluid_es/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":19432,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"367537159","text":"import os\nimport sys\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nprint('Running 00-split_data.py')\n\n# Set the working directory to the script dir\nos.chdir(os.path.dirname(sys.argv[0]))\n\n# Import the data\ndata = pd.read_csv('../data/raw/data',\n header=None,\n low_memory=False,\n converters={0: str.strip, 1: str.strip, 2: str.strip})\n\n# Nulls were represented by \"?\" in the dataset, let's fix that\ndata = data.replace('?', np.nan)\nprint(\"There are {} total rows in the dataset.\".format(len(data.index)))\n\n# For now we'll eliminate the null rows, maybe we'll try to use them later...\ndata_nonull = data.dropna(axis=0, how='any')\nprint(\"There are {} non-null rows in the dataset.\".format(len(data_nonull.index)))\n\nlabels = data_nonull[1558].replace({'nonad.': 0, 'ad.': 1})\nX = data_nonull.drop(1558, axis=1)\n\n# Split the dataset\nX_train, X_test, y_train, y_test = train_test_split(X,\n labels,\n test_size=0.1,\n random_state=8675309)\n\n# Print csvs for later\nprint(\"Printing files to proj/data/processed...\")\nX_train.to_csv('../data/processed/X_train.csv', index=True, header=False)\nX_test.to_csv('../data/processed/X_test.csv', index=True, header=False)\ny_train.to_csv('../data/processed/y_train.csv', index=True, header=False)\ny_test.to_csv('../data/processed/y_test.csv', index=True, header=False)\n\nprint('\\n\\n')\n","sub_path":"code/00-split_data.py","file_name":"00-split_data.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"563130945","text":"import ee\nimport fct.lnd\nimport geopandas as gpd\nimport datetime\nimport json\ndef maskInside(image, geometry):\n mask = ee.Image.constant(1).clip(geometry).mask().eq(1)\n return image.updateMask(mask)\n\nee.Initialize()\n\nstartDate = datetime.datetime(2014, 1, 1)\nendDate = datetime.datetime(2019, 12, 31)\n\nroi_shp = gpd.read_file(r'D:\\Seafile\\Meine Bibliothek\\research\\theses\\MSc_Franziska_Walther\\extent_rough.shp')\ng = json.loads(roi_shp.to_json())\ncoords = list(g['features'][0]['geometry']['coordinates'])\nroi = ee.Geometry.Polygon(coords)\n\nlnd = fct.lnd.LND(startDate, endDate, roi=roi).select('evi')\nids = lnd.aggregate_array('LANDSAT_ID').getInfo()\n\nfor id in ids:\n print(id)\n image = lnd.filterMetadata('LANDSAT_ID', 'equals', id)\\\n .first()\n description = id\n folder = 'FW_EVI_2014-2020'\n scale = 30\n task = ee.batch.Export.image.toDrive(**{\n 'image': image,\n 'description': description,\n 'folder': folder,\n 'scale': scale,\n 'crs': 'EPSG:32737',\n 'maxPixels': 1e13\n })\n task.start()\n","sub_path":"sandbox/xx_export_EVI.py","file_name":"xx_export_EVI.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"159303873","text":"import asyncio\nimport math\nimport random\nimport time\nimport traceback\nimport sys\nimport datetime\n\nimport discord\n\nfrom . import combat as cmbt_utils\nfrom . import core as ewutils\nfrom . import frontend as fe_utils\nfrom . import hunting as hunt_utils\nfrom . import item as itm_utils\nfrom . import market as market_utils\nfrom . import apt as apt_utils\nfrom . import cosmeticitem as cosmetic_utils\nfrom . import move as move_utils\nfrom . import leaderboard as leaderboard_utils\nfrom . import weather as weather_utils\nfrom . import rolemgr as ewrolemgr\nfrom . import stats as ewstats\nfrom . import mutations as mut_utils\ntry:\n from . import rutils as rutils\nexcept:\n from . import rutils_dummy as rutils\nfrom .combat import EwEnemy\nfrom .combat import EwUser\nfrom .district import EwDistrict\nfrom .frontend import EwResponseContainer\nfrom ..backend import core as bknd_core\nfrom ..backend import hunting as bknd_hunt\nfrom ..backend import item as bknd_item\nfrom ..backend import worldevent as bknd_event\nfrom ..backend import fish as bknd_fish\nfrom ..backend import ads as bknd_ads\nfrom ..backend.market import EwMarket\nfrom ..backend.player import EwPlayer\nfrom ..backend.dungeons import EwGamestate\nfrom ..backend.status import EwEnemyStatusEffect\nfrom ..backend.status import EwStatusEffect\nfrom ..backend.worldevent import EwWorldEvent\nfrom ..backend.item import EwItem\nfrom ..static import cfg as ewcfg\nfrom ..static import items as static_items\nfrom ..static.food import swilldermuk_food\nfrom ..static import poi as poi_static\nfrom ..static import status as se_static\nfrom ..static import weapons as static_weapons\nfrom ..cmd.juviecmd.juviecmdutils import mine_collapse\ntry:\n from ..utils import rutils\nexcept:\n from ..utils import rutils_dummy as rutils\n\nasync def event_tick_loop(id_server):\n # initialise void connections\n void_connections = bknd_event.get_void_connection_pois(id_server)\n void_poi = poi_static.id_to_poi.get(ewcfg.poi_id_thevoid)\n for connection_poi in void_connections:\n # add the existing connections as neighbors for the void\n void_poi.neighbors[connection_poi] = ewcfg.travel_time_district\n for _ in range(3 - len(void_connections)):\n # create any missing connections\n bknd_event.create_void_connection(id_server)\n ewutils.logMsg(\"initialised void connections, current links are: {}\".format(tuple(void_poi.neighbors.keys())))\n\n interval = ewcfg.event_tick_length\n while not ewutils.TERMINATE:\n ewutils.last_loop['event'] = int(time.time())\n await asyncio.sleep(interval)\n await event_tick(id_server)\n\n\nasync def event_tick(id_server):\n time_now = int(time.time())\n resp_cont = EwResponseContainer(id_server=id_server)\n try:\n # Get all events with an expiry right now or in the past\n data = bknd_core.execute_sql_query(\n \"SELECT {id_event} FROM world_events WHERE {time_expir} <= %s AND {time_expir} > 0 AND id_server = %s\".format(\n id_event=ewcfg.col_id_event,\n time_expir=ewcfg.col_time_expir,\n ), (\n time_now,\n id_server,\n ))\n \n # Do end-of-event actions and delete the world event\n for row in data:\n try:\n event_data = EwWorldEvent(id_event=row[0])\n event_def = poi_static.event_type_to_def.get(event_data.event_type)\n if event_def and event_def.function_on_end is not None:\n await event_def.function_on_end\n response = event_def.str_event_end if event_def else \"\"\n if event_data.event_type == ewcfg.event_type_minecollapse:\n user_data = EwUser(id_user=event_data.event_props.get('id_user'), id_server=id_server)\n if user_data.poi == event_data.event_props.get('poi'):\n # Do the mine collapse function\n mine_action = mine_collapse(id_user=user_data.id_user, id_server=id_server) \n \n # Take either slime or hunger\n if mine_action.collapse_penalty != 0.0:\n if user_data.slimes > 1:\n user_data.change_slimes(n=-(user_data.slimes * mine_action.collapse_penalty))\n elif mine_action.hunger_cost_multiplier != 1:\n user_data.hunger += (ewcfg.hunger_permine * mine_action.hunger_cost_multiplier)\n\n user_data.persist()\n\n elif event_data.event_type == ewcfg.event_type_alarmclock:\n clock_item = EwItem(event_data.event_props.get(\"clock_id\"))\n clock_item.item_props[\"furniture_look_desc\"] = \"There's an alarm clock that's stopped working.\"\n clock_item.item_props[\"furniture_desc\"] = \"The annoying sound this thing makes perfectly explains why the bazaar sells so many broken clocks. Or at least that's what it used to do before the shitty little batteries gave out. Could try setting it again?\"\n clock_item.persist()\n # check if any void connections have expired, if so pop it and create a new one\n elif event_data.event_type == ewcfg.event_type_voidconnection:\n void_poi = poi_static.id_to_poi.get(ewcfg.poi_id_thevoid)\n void_poi.neighbors.pop(event_data.event_props.get('poi'), \"\")\n bknd_event.create_void_connection(id_server)\n elif event_data.event_type == ewcfg.event_type_dimensional_rift:\n rift_poi = poi_static.id_to_poi.get(event_data.event_props.get('poi'))\n rift_poi.neighbors.pop(event_data.event_props.get('sisterlocation'), \"\")\n if len(response) > 0:\n poi = event_data.event_props.get('poi')\n channel = event_data.event_props.get('channel')\n if channel != None:\n\n resp_cont.add_channel_response(channel, response)\n elif poi != None:\n poi_def = poi_static.id_to_poi.get(poi)\n if poi_def != None:\n resp_cont.add_channel_response(poi_def.channel, response)\n\n else:\n for ch in ewcfg.hideout_channels:\n resp_cont.add_channel_response(ch, response)\n\n bknd_event.delete_world_event(event_data.id_event)\n except Exception as e:\n ewutils.logMsg(\"Error in event tick for server {}:{}\".format(id_server, e))\n\n # Get all events that activate right now\n activate_data = bknd_core.execute_sql_query(\n \"SELECT {id_event} FROM world_events WHERE {time_activate} >= {time_now} AND {time_activate} < {time_now} + {interval} AND id_server = %s\".format(\n id_event=ewcfg.col_id_event,\n time_activate=ewcfg.col_time_activate,\n time_now=time_now,\n interval=ewcfg.event_tick_length,\n ), (\n id_server,\n ))\n\n # Do activation alerts for specific world events\n for row in activate_data:\n try:\n event_data = EwWorldEvent(id_event=row[0])\n event_def = poi_static.event_type_to_def.get(event_data.event_type)\n\n if event_def and event_def.function_on_activate is not None:\n await event_def.function_on_activate\n\n # If the event is a POI event\n if event_data.event_type in ewcfg.poi_events:\n poi = poi_static.id_to_poi.get(event_data.event_props.get('poi'))\n\n # Create alert in poi channel \n resp_cont.add_channel_response(poi.channel, event_def.str_event_start)\n\n gangbase_alert = \"A peculiar event has manifested somewhere in NLACakaNM...\"\n # If gangbase alert should be specific\n if event_data.event_props.get('alert') == \"gangbase\":\n gangbase_alert = \"It seems {} has manifested in {}.\".format(event_def.str_name, poi.str_name)\n\n for channel in ewcfg.hideout_channels:\n resp_cont.add_channel_response(channel, gangbase_alert)\n\n if event_data.event_type == ewcfg.event_type_rally_end:\n target_district = EwDistrict(id_server=id_server, district=poi.id_poi)\n if target_district.controlling_faction != 'rabble':\n target_district.capture_points = ewcfg.max_capture_points_s\n target_district.capturing_faction = 'rabble'\n target_district.persist()\n\n\n except Exception as e:\n ewutils.logMsg(\"Error in event tick for server {}:{}\".format(id_server, e))\n \n await resp_cont.post()\n\n except Exception as e:\n ewutils.logMsg(\"Error in event tick for server {}:{}\".format(id_server, e))\n\n\n\"\"\" Decay slime totals for all users, with the exception of Kingpins\"\"\"\n\n\nasync def decaySlimes(id_server = None):\n if id_server != None:\n try:\n\n conn_info = bknd_core.databaseConnect()\n conn = conn_info.get('conn')\n cursor = conn.cursor()\n\n cursor.execute(\"SELECT id_user, life_state FROM users WHERE id_server = %s AND {slimes} > 1 AND NOT ({life_state} = {life_state_kingpin} OR {life_state} = {life_state_ghost} OR {life_state} = {life_state_vigilante})\".format(\n slimes=ewcfg.col_slimes,\n life_state=ewcfg.col_life_state,\n life_state_kingpin=ewcfg.life_state_kingpin,\n life_state_ghost=ewcfg.life_state_corpse,\n life_state_vigilante = ewcfg.life_state_vigilante\n ), (\n id_server,\n ))\n\n users = cursor.fetchall()\n total_decayed = 0\n\n # Create a list of districts where you gain slime passively rather than decay\n slimeboost_pois = []\n # Radiation storms boost slime\n world_events = bknd_event.get_world_events(id_server=id_server)\n for id_event in world_events:\n if world_events.get(id_event) == ewcfg.event_type_radiation_storm:\n event_data = EwWorldEvent(id_event=id_event)\n slimeboost_pois.append(event_data.event_props.get('poi'))\n # Block parties have a setting to boost slime\n block_party = EwGamestate(id_state='blockparty', id_server=id_server)\n block_poi = ''.join([i for i in block_party.value if not i.isdigit()])\n slimeboost_pois.append(block_poi)\n # Damn you, 7/11!\n if 'outsidethe' in slimeboost_pois:\n slimeboost_pois.append(ewcfg.poi_id_711)\n\n for user in users:\n user_data = EwUser(id_user=user[0], id_server=id_server)\n slimes_to_decay = user_data.slimes - (user_data.slimes * (.5 ** (ewcfg.update_market / ewutils.calc_half_life(user_data))))\n\n # round up or down, randomly weighted\n remainder = slimes_to_decay - int(slimes_to_decay)\n if random.random() < remainder:\n slimes_to_decay += 1\n slimes_to_decay = int(slimes_to_decay)\n\n # User will gain slime while in a blockparty/rad storm\n if user_data.poi in slimeboost_pois:\n slimes_to_decay -= ewcfg.blockparty_slimebonus_per_tick\n\n if slimes_to_decay >= 1:\n user_data.change_slimes(n=-slimes_to_decay, source=ewcfg.source_decay)\n user_data.persist()\n total_decayed += slimes_to_decay\n elif slimes_to_decay < 1:\n user_data.change_slimes(n=-slimes_to_decay, source=ewcfg.source_blockparty)\n user_data.persist()\n\n cursor.execute(\"SELECT district FROM districts WHERE id_server = %s AND {slimes} > 1\".format(\n slimes=ewcfg.col_district_slimes\n ), (\n id_server,\n ))\n\n districts = cursor.fetchall()\n\n for district in districts:\n district_data = EwDistrict(district=district[0], id_server=id_server)\n slimes_to_decay = district_data.slimes - (district_data.slimes * (.5 ** (ewcfg.update_market / ewcfg.slime_half_life)))\n\n # round up or down, randomly weighted\n remainder = slimes_to_decay - int(slimes_to_decay)\n if random.random() < remainder:\n slimes_to_decay += 1\n slimes_to_decay = int(slimes_to_decay)\n\n # District will gain slime during a block party slowly\n if district_data.name in slimeboost_pois:\n slimes_to_decay -= ewcfg.blockparty_slimebonus_per_tick / 10\n\n if slimes_to_decay >= 1:\n district_data.change_slimes(n=-slimes_to_decay, source=ewcfg.source_decay)\n\n if rutils.es_check1(district_data):\n rutils.debug37(district_data)\n\n district_data.persist()\n total_decayed += slimes_to_decay\n\n cursor.execute(\"UPDATE markets SET {decayed} = ({decayed} + %s) WHERE {server} = %s\".format(\n decayed=ewcfg.col_decayed_slimes,\n server=ewcfg.col_id_server\n ), (\n total_decayed,\n id_server\n ))\n\n conn.commit()\n finally:\n # Clean up the database handles.\n cursor.close()\n bknd_core.databaseClose(conn_info)\n\n\nasync def misc_hourly_function(id_server): #right now it just switches Hide's personality, we could use this for other bits and bobs like this\n hide_value = random.randint(0, 2)\n thumbnail = ewcfg.hide_taka_thumbnail[hide_value]\n ewcfg.vendor_thumbnails[ewcfg.poi_id_foodcourt] = [\"HIDE TAKA\", thumbnail]\n dialogue = ewcfg.hide_dialogue.get(hide_value)\n ewcfg.vendor_dialogue[ewcfg.poi_id_foodcourt] = dialogue\n\n\n\n\"\"\"\n Kills users who have left the server while the bot was offline\n\"\"\"\n\n\nasync def kill_quitters(id_server):\n client = ewutils.get_client()\n server = client.get_guild(id_server)\n\n users = bknd_core.execute_sql_query(\"SELECT id_user FROM users WHERE id_server = %s AND ( life_state > 0 OR slimes < 0 )\", (\n id_server,\n ))\n\n for user in users:\n member = await fe_utils.get_member(server, user[0])\n\n # Make sure to kill players who may have left while the bot was offline.\n if member is None:\n try:\n user_data = EwUser(id_user=user[0], id_server=id_server)\n\n user_data.trauma = ewcfg.trauma_id_suicide\n await user_data.die(cause=ewcfg.cause_leftserver)\n\n ewutils.logMsg('Player with id {} killed for leaving the server.'.format(user[0]))\n except Exception as e:\n ewutils.logMsg(f'Failed to kill member who left the server: {e}')\n\n\n\"\"\"\n Coroutine that continually calls bleedSlimes; is called once per server, and not just once globally\n\"\"\"\n\n\nasync def bleed_tick_loop(id_server):\n interval = ewcfg.bleed_tick_length\n # causes a capture tick to happen exactly every 10 seconds (the \"elapsed\" thing might be unnecessary, depending on how long capture_tick ends up taking on average)\n while not ewutils.TERMINATE:\n ewutils.last_loop['bleed'] = int(time.time())\n await bleedSlimes(id_server=id_server)\n await enemyBleedSlimes(id_server=id_server)\n # ewutils.ewutils.logMsg(\"Capture tick happened on server %s.\" % id_server + \" Timestamp: %d\" % int(time.time()))\n\n await asyncio.sleep(interval)\n\n\n\"\"\" Bleed slime for all users \"\"\"\n\n\nasync def bleedSlimes(id_server):\n client = ewutils.get_client()\n server = client.get_guild(id_server)\n\n users = bknd_core.execute_sql_query(\"SELECT id_user FROM users WHERE id_server = %s AND {bleed_storage} > 1\".format(\n bleed_storage=ewcfg.col_bleed_storage\n ), (\n id_server,\n ))\n\n total_bled = 0\n resp_cont = EwResponseContainer(id_server=id_server)\n for user in users:\n user_data = EwUser(id_user=user[0], id_server=id_server)\n\n mutations = user_data.get_mutations()\n member = await fe_utils.get_member(server, user_data.id_user)\n if ewcfg.mutation_id_bleedingheart not in mutations or user_data.time_lasthit < int(time.time()) - ewcfg.time_bhbleed:\n slimes_to_bleed = user_data.bleed_storage * (\n 1 - .5 ** (ewcfg.bleed_tick_length / ewcfg.bleed_half_life))\n slimes_to_bleed = max(slimes_to_bleed, ewcfg.bleed_tick_length * 1000)\n\n # round up or down, randomly weighted\n remainder = slimes_to_bleed - int(slimes_to_bleed)\n if random.random() < remainder:\n slimes_to_bleed += 1\n slimes_to_bleed = int(slimes_to_bleed)\n\n slimes_to_bleed = min(slimes_to_bleed, user_data.bleed_storage)\n\n if slimes_to_bleed >= 1:\n\n real_bleed = round(slimes_to_bleed) # * bleed_mod)\n\n user_data.bleed_storage -= slimes_to_bleed\n user_data.change_slimes(n=- real_bleed, source=ewcfg.source_bleeding)\n\n district_data = EwDistrict(id_server=id_server, district=user_data.poi)\n district_data.change_slimes(n=real_bleed, source=ewcfg.source_bleeding)\n district_data.persist()\n\n if user_data.slimes < 0:\n user_data.trauma = ewcfg.trauma_id_environment\n die_resp = await user_data.die(cause=ewcfg.cause_bleeding)\n resp_cont.add_response_container(die_resp)\n user_data.persist()\n\n total_bled += real_bleed\n\n await resp_cont.post()\n\n\n\"\"\" Bleed slime for all enemies \"\"\"\n\n\nasync def enemyBleedSlimes(id_server):\n enemies = bknd_core.execute_sql_query(\"SELECT id_enemy FROM enemies WHERE id_server = %s AND {bleed_storage} > 1\".format(\n bleed_storage=ewcfg.col_enemy_bleed_storage\n ), (\n id_server,\n ))\n\n total_bled = 0\n resp_cont = EwResponseContainer(id_server=id_server)\n for enemy in enemies:\n enemy_data = EwEnemy(id_enemy=enemy[0], id_server=id_server)\n slimes_to_bleed = enemy_data.bleed_storage * (1 - .5 ** (ewcfg.bleed_tick_length / ewcfg.bleed_half_life))\n slimes_to_bleed = max(slimes_to_bleed, ewcfg.bleed_tick_length * 1000)\n slimes_to_bleed = min(slimes_to_bleed, enemy_data.bleed_storage)\n\n district_data = EwDistrict(id_server=id_server, district=enemy_data.poi)\n\n # round up or down, randomly weighted\n remainder = slimes_to_bleed - int(slimes_to_bleed)\n if random.random() < remainder:\n slimes_to_bleed += 1\n slimes_to_bleed = int(slimes_to_bleed)\n\n if slimes_to_bleed >= 1:\n enemy_data.bleed_storage -= slimes_to_bleed\n enemy_data.change_slimes(n=- slimes_to_bleed, source=ewcfg.source_bleeding)\n enemy_data.persist()\n district_data.change_slimes(n=slimes_to_bleed, source=ewcfg.source_bleeding)\n district_data.persist()\n total_bled += slimes_to_bleed\n\n if enemy_data.slimes <= 0:\n bknd_hunt.delete_enemy(enemy_data)\n \n if enemy_data.enemytype in ewcfg.raid_den_bosses:\n await rutils.debug45(enemy_data)\n\n await resp_cont.post()\n\n\n\"\"\" Reduce inebriation for every player in the server. \"\"\"\n\n\nasync def pushdownServerInebriation(id_server):\n try:\n bknd_core.execute_sql_query(\"UPDATE users SET {inebriation} = {inebriation} - {tick} WHERE id_server = %s AND {inebriation} > {limit}\".format(\n inebriation=ewcfg.col_inebriation,\n tick=ewcfg.inebriation_pertick,\n limit=0\n ), (\n id_server,\n ))\n except Exception as e:\n ewutils.logMsg(f\"Failed to pushdown server inebriation: {e}\")\n\n\"\"\"\n Coroutine that continually calls burnSlimes; is called once per server, and not just once globally\n\"\"\"\n\n\nasync def burn_tick_loop(id_server):\n interval = ewcfg.burn_tick_length\n while not ewutils.TERMINATE:\n ewutils.last_loop['burn'] = int(time.time())\n await burnSlimes(id_server=id_server)\n await enemyBurnSlimes(id_server=id_server)\n await asyncio.sleep(interval)\n\n\n\"\"\" Burn slime for all users \"\"\"\n\n\nasync def burnSlimes(id_server):\n time_now = int(time.time())\n client = ewutils.get_client()\n server = client.get_guild(id_server)\n status_origin = 'user'\n\n results = {}\n\n # Get users with harmful status effects\n data = bknd_core.execute_sql_query(\"SELECT {id_user}, {value}, {source}, {id_status}, {time_expire} from status_effects WHERE {id_status} IN %s and {id_server} = %s\".format(\n id_user=ewcfg.col_id_user,\n value=ewcfg.col_value,\n id_status=ewcfg.col_id_status,\n id_server=ewcfg.col_id_server,\n source=ewcfg.col_source,\n time_expire = ewcfg.col_time_expir,\n ), (\n tuple(ewcfg.harmful_status_effects),\n id_server\n ))\n\n resp_cont = EwResponseContainer(id_server=id_server)\n for result in data:\n user_data = EwUser(id_user=result[0], id_server=id_server)\n\n slimes_dropped = user_data.totaldamage + user_data.slimes\n used_status_id = result[3]\n\n # Deal 10% of total slime to burn every second <-- fake. deal 1/3 every 4 seconds\n remaining_ticks_inclusive = math.ceil((result[4] - time_now) / ewcfg.burn_tick_length) + 1\n if remaining_ticks_inclusive <= 0:\n if ewutils.DEBUG_OPTIONS.get(\"verbose_burn\") and used_status_id == ewcfg.status_burning_id:\n ewutils.logMsg(\"Burn for {} being ticked after burnout. Skipping {} remaining damage.\".format(result[0], result[1]))\n continue # Ensures that burn only runs for the configured tick amount\n slimes_to_burn = math.ceil(int(float(result[1])) / remaining_ticks_inclusive)\n\n # Check if a status effect originated from an enemy or a user.\n killer_data = EwUser(id_server=id_server, id_user=result[2])\n if killer_data is None:\n killer_data = EwEnemy(id_server=id_server, id_enemy=result[2])\n if killer_data is not None:\n status_origin = 'enemy'\n else:\n status_origin = 'other'\n\n if status_origin == 'user':\n # Damage stats\n ewstats.change_stat(user=killer_data, metric=ewcfg.stat_lifetime_damagedealt, n=slimes_to_burn)\n\n # Player died\n if user_data.slimes - slimes_to_burn < 0:\n weapon = static_weapons.weapon_map.get(ewcfg.weapon_id_molotov)\n\n player_data = EwPlayer(id_server=user_data.id_server, id_user=user_data.id_user)\n killer = EwPlayer(id_server=id_server, id_user=killer_data.id_user)\n poi = poi_static.id_to_poi.get(user_data.poi)\n\n # Kill stats\n if status_origin == 'user':\n ewstats.increment_stat(user=killer_data, metric=ewcfg.stat_kills)\n ewstats.track_maximum(user=killer_data, metric=ewcfg.stat_biggest_kill, value=int(slimes_dropped))\n\n if killer_data.slimelevel > user_data.slimelevel:\n ewstats.increment_stat(user=killer_data, metric=ewcfg.stat_lifetime_ganks)\n elif killer_data.slimelevel < user_data.slimelevel:\n ewstats.increment_stat(user=killer_data, metric=ewcfg.stat_lifetime_takedowns)\n\n # Kill player\n if status_origin == 'user':\n user_data.id_killer = killer_data.id_user\n elif status_origin == 'enemy':\n user_data.id_killer = killer_data.id_enemy\n elif status_origin == 'other':\n user_data.id_killer = 0\n\n # Collect bounty\n coinbounty = int(user_data.bounty / ewcfg.slimecoin_exchangerate) # 100 slime per coin\n\n if user_data.slimes >= 0:\n killer_data.change_slimecoin(n=coinbounty, coinsource=ewcfg.coinsource_bounty)\n\n # Kill player\n if status_origin == 'user':\n user_data.id_killer = killer_data.id_user\n elif status_origin == 'enemy':\n user_data.id_killer = killer_data.id_enemy\n\n user_data.trauma = ewcfg.trauma_id_environment\n die_resp = await user_data.die(cause=ewcfg.cause_burning)\n\n resp_cont.add_response_container(die_resp)\n\n if used_status_id == ewcfg.status_burning_id:\n deathreport = \"{} has burned to death.\".format(player_data.display_name)\n elif used_status_id == ewcfg.status_acid_id:\n deathreport = \"{} has been melted to death by acid.\".format(player_data.display_name)\n elif used_status_id == ewcfg.status_spored_id:\n deathreport = \"{} has been overrun by spores.\".format(player_data.display_name)\n else:\n deathreport = \"\"\n resp_cont.add_channel_response(poi.channel, deathreport)\n\n else:\n user_data.change_slimes(n=-slimes_to_burn, source=ewcfg.source_damage)\n status_data = EwStatusEffect(id_status=result[3], id_server=id_server, id_user=result[0])\n status_data.value = int(float(status_data.value)) - slimes_to_burn\n status_data.persist()\n user_data.persist()\n if used_status_id == ewcfg.status_burning_id and ewutils.DEBUG_OPTIONS.get(\"verbose_burn\"):\n ewutils.logMsg(\"Burning {} slime from {}. {} burn remaining.\".format(slimes_to_burn, user_data.id_user, status_data.value))\n\n await resp_cont.post()\n\n\nasync def enemyBurnSlimes(id_server):\n if id_server != None:\n time_now = int(time.time())\n client = ewutils.get_client()\n server = client.get_guild(id_server)\n status_origin = 'user'\n\n results = {}\n\n # Get enemies with harmful status effects\n data = bknd_core.execute_sql_query(\"SELECT {id_enemy}, {value}, {source}, {id_status} from enemy_status_effects WHERE {id_status} IN %s and {id_server} = %s\".format(\n id_enemy=ewcfg.col_id_enemy,\n value=ewcfg.col_value,\n id_status=ewcfg.col_id_status,\n id_server=ewcfg.col_id_server,\n source=ewcfg.col_source\n ), (\n ewcfg.harmful_status_effects,\n id_server\n ))\n\n resp_cont = EwResponseContainer(id_server=id_server)\n for result in data:\n enemy_data = EwEnemy(id_enemy=result[0], id_server=id_server)\n\n slimes_dropped = enemy_data.totaldamage + enemy_data.slimes\n used_status_id = result[3]\n\n # Deal 10% of total slime to burn every second\n slimes_to_burn = math.ceil(int(float(result[1])) * ewcfg.burn_tick_length / ewcfg.time_expire_burn)\n\n # Check if a status effect originated from an enemy or a user.\n killer_data = EwUser(id_server=id_server, id_user=result[2])\n if killer_data == None:\n killer_data = EwEnemy(id_server=id_server, id_enemy=result[2])\n if killer_data != None:\n status_origin = 'enemy'\n else:\n # For now, skip over any status that did not originate from a user or an enemy. This might be changed in the future.\n continue\n\n if status_origin == 'user':\n ewstats.change_stat(user=killer_data, metric=ewcfg.stat_lifetime_damagedealt, n=slimes_to_burn)\n\n if enemy_data.slimes - slimes_to_burn <= 0:\n\n if enemy_data.enemytype in ewcfg.raid_den_bosses:\n await rutils.debug45(enemy_data)\n \n bknd_hunt.delete_enemy(enemy_data)\n\n if used_status_id == ewcfg.status_burning_id:\n response = \"{} has burned to death.\".format(enemy_data.display_name)\n elif used_status_id == ewcfg.status_acid_id:\n response = \"{} has been melted to death by acid.\".format(enemy_data.display_name)\n elif used_status_id == ewcfg.status_spored_id:\n response = \"{} has been overrun by spores.\".format(enemy_data.display_name)\n else:\n response = \"\"\n resp_cont.add_channel_response(poi_static.id_to_poi.get(enemy_data.poi).channel, response)\n\n district_data = EwDistrict(id_server=id_server, district=enemy_data.poi)\n resp_cont.add_response_container(cmbt_utils.drop_enemy_loot(enemy_data, district_data))\n else:\n enemy_data.change_slimes(n=-slimes_to_burn, source=ewcfg.source_damage)\n enemy_data.persist()\n\n await resp_cont.post()\n\n\nasync def remove_status_loop(id_server):\n interval = ewcfg.removestatus_tick_length\n while not ewutils.TERMINATE:\n removeExpiredStatuses(id_server=id_server)\n enemyRemoveExpiredStatuses(id_server=id_server)\n await asyncio.sleep(interval)\n\n\n\"\"\" Remove expired status effects for all users \"\"\"\n\n\ndef removeExpiredStatuses(id_server = None):\n if id_server != None:\n time_now = int(time.time())\n\n # client = ewutils.get_client()\n # server = client.get_server(id_server)\n\n statuses = bknd_core.execute_sql_query(\"SELECT {id_status},{id_user} FROM status_effects WHERE id_server = %s AND {time_expire} < %s\".format(\n id_status=ewcfg.col_id_status,\n id_user=ewcfg.col_id_user,\n time_expire=ewcfg.col_time_expir\n ), (\n id_server,\n time_now\n ))\n\n for row in statuses:\n status = row[0]\n id_user = row[1]\n user_data = EwUser(id_user=id_user, id_server=id_server)\n status_def = se_static.status_effects_def_map.get(status)\n status_effect = EwStatusEffect(id_status=status, user_data=user_data)\n\n if status_def.time_expire > 0:\n if status_effect.time_expire < time_now:\n if ewutils.DEBUG_OPTIONS.get(\"verbose_burn\") and status == ewcfg.status_burning_id:\n ewutils.logMsg(\"Removing burn status from {}.\".format(id_user))\n user_data.clear_status(id_status=status)\n\n # Status that expire under special conditions\n else:\n if status == ewcfg.status_stunned_id:\n if int(status_effect.value) < time_now:\n user_data.clear_status(id_status=status)\n\n\ndef enemyRemoveExpiredStatuses(id_server = None):\n if id_server != None:\n time_now = int(time.time())\n\n statuses = bknd_core.execute_sql_query(\"SELECT {id_status}, {id_enemy} FROM enemy_status_effects WHERE id_server = %s AND {time_expire} < %s\".format(\n id_status=ewcfg.col_id_status,\n id_enemy=ewcfg.col_id_enemy,\n time_expire=ewcfg.col_time_expir\n ), (\n id_server,\n time_now\n ))\n for row in statuses:\n status = row[0]\n id_enemy = row[1]\n enemy_data = EwEnemy(id_enemy=id_enemy, id_server=id_server)\n status_def = se_static.status_effects_def_map.get(status)\n status_effect = EwEnemyStatusEffect(id_status=status, enemy_data=enemy_data)\n\n if status_def.time_expire > 0:\n if status_effect.time_expire < time_now:\n enemy_data.clear_status(id_status=status)\n\n # Status that expire under special conditions\n else:\n if status == ewcfg.status_stunned_id:\n if int(status_effect.value) < time_now:\n enemy_data.clear_status(id_status=status)\n\n\nasync def decrease_food_multiplier():\n while not ewutils.TERMINATE:\n for user in ewutils.food_multiplier.copy():\n # If the food multi is empty, then just remove the user from the list\n if ewutils.food_multiplier[user] == 0:\n ewutils.food_multiplier.pop(user)\n # Reduce it down\n if ewutils.food_multiplier.get(user):\n ewutils.food_multiplier[user] = max(0, ewutils.food_multiplier.get(user) - 1)\n \n await asyncio.sleep(5)\n\n\nasync def spawn_enemies(id_server = None, debug = False):\n market_data = EwMarket(id_server=id_server)\n world_events = bknd_event.get_world_events(id_server=id_server, active_only=True)\n resp_list = []\n chosen_type = None\n chosen_POI = None\n npc_enemies_count = len(bknd_core.execute_sql_query(\"SELECT id_enemy FROM enemies where {life_state} = %s and {enemytype} = %s and {id_server} = %s\".format(life_state=ewcfg.col_life_state, enemytype=ewcfg.col_enemy_type, id_server=ewcfg.col_id_server), (1, 'npc', id_server)))\n all_enemies_count = len(bknd_core.execute_sql_query(\"SELECT id_enemy FROM enemies where {life_state} = %s and {id_server} = %s\".format(life_state=ewcfg.col_life_state, id_server=ewcfg.col_id_server), (1, id_server)))\n # One in 3 chance of spawning a regular enemy in the outskirts\n\n if (random.randrange(3) == 0 or debug) and all_enemies_count-npc_enemies_count <= ewcfg.max_normal_enemies:\n weathertype = ewcfg.enemy_weathertype_normal\n # If it's raining, an enemy has 2/3 chance to spawn as a bicarbonate enemy, which doesn't take rain damage\n if market_data.weather == ewcfg.weather_bicarbonaterain:\n if random.randrange(3) < 2:\n weathertype = ewcfg.enemy_weathertype_rainresist\n # if ewcfg.dh_stage == 3 and ewcfg.dh_active:\n # chosen_type = random.choice([ewcfg.enemy_type_unnervingfightingoperator, ewcfg.enemy_type_grey, ewcfg.enemy_type_tangeloid, ewcfg.enemy_type_alienscum])\n # if chosen_type == ewcfg.enemy_type_unnervingfightingoperator:\n # #chosen_POI = 'westoutskirts'\n # pass\n\n resp_list.append(hunt_utils.spawn_enemy(id_server=id_server, pre_chosen_weather=weathertype, pre_chosen_type=chosen_type, pre_chosen_poi=chosen_POI))\n # One in two chance of spawning a slimeoid trainer in either the Battle Arena or Subway\n # Why did I make this into incredibly hacky code? Because.\n if random.randrange(5) == 0 and npc_enemies_count <= ewcfg.max_npcs:\n resp_list.append(hunt_utils.spawn_enemy(id_server=id_server, pre_chosen_type=ewcfg.enemy_type_npc))\n #if random.randrange(2) == 0:\n #resp_list.append(hunt_utils.spawn_enemy(id_server=id_server, pre_chosen_type=ewcfg.enemy_type_slimeoidtrainer))\n #else:\n #resp_list.append(hunt_utils.spawn_enemy(id_server=id_server, pre_chosen_type=ewcfg.enemy_type_ug_slimeoidtrainer))\n\n # Chance to spawn enemies that correspond to POI Events. Unaffected by enemy spawn cap\n if random.randrange(4) == 0:\n for id_event in world_events:\n # Only if the event corresponds to a type of event that spawns enemies\n if world_events.get(id_event) in [ewcfg.event_type_raider_incursion, ewcfg.event_type_slimeunist_protest, ewcfg.event_type_radiation_storm]:\n event_data = bknd_event.EwWorldEvent(id_event=id_event)\n\n # If the event is a raider incursion\n if event_data.event_type == ewcfg.event_type_raider_incursion:\n chosen_type = random.choice(ewcfg.raider_incursion_enemies)\n resp_list.append(hunt_utils.spawn_enemy(id_server=id_server, pre_chosen_type=chosen_type, pre_chosen_poi=event_data.event_props.get('poi')))\n # If the event is a slimeunist protest\n elif event_data.event_type == ewcfg.event_type_slimeunist_protest:\n chosen_type = random.choice(ewcfg.slimeunist_protest_enemies)\n resp_list.append(hunt_utils.spawn_enemy(id_server=id_server, pre_chosen_type=chosen_type, pre_chosen_poi=event_data.event_props.get('poi')))\n # If the event is a radiation storm\n elif event_data.event_type == ewcfg.event_type_radiation_storm:\n if random.randrange(12) == 0:\n chosen_type = random.choice(ewcfg.radiation_storm_enemies)\n resp_list.append(hunt_utils.spawn_enemy(id_server=id_server, pre_chosen_type=chosen_type, pre_chosen_poi=event_data.event_props.get('poi')))\n\n\n for cont in resp_list:\n await cont.post()\n\n\n\n if ewcfg.dh_active and ewcfg.dh_stage >= 1:\n dhspawn = EwGamestate(id_server = id_server, id_state='dhorsemankills')\n count = int(dhspawn.value)\n if count < 2:\n market_data = EwMarket(id_server=id_server)\n underworld_district = EwDistrict(district=ewcfg.poi_id_underworld, id_server=id_server)\n enemies_count = len(underworld_district.get_enemies_in_district())\n\n if enemies_count == 0 and int(time.time()) > (market_data.horseman_timeofdeath + ewcfg.horseman_death_cooldown):\n dh_resp_cont = hunt_utils.spawn_enemy(id_server=id_server, pre_chosen_type=ewcfg.enemy_type_doubleheadlessdoublehorseman, pre_chosen_poi=ewcfg.poi_id_underworld, manual_spawn=True)\n\n await dh_resp_cont.post()\n\nasync def spawn_enemies_tick_loop(id_server):\n interval = ewcfg.enemy_spawn_tick_length\n # Causes the possibility of an enemy spawning every 10 seconds\n while not ewutils.TERMINATE:\n ewutils.last_loop['spawn_enemies'] = int(time.time())\n await asyncio.sleep(interval)\n try:\n await spawn_enemies(id_server=id_server)\n except Exception as E:\n ewutils.logMsg(\"Failed to spawn enemies: {}\".format(E))\n\n\nasync def enemy_action_tick_loop(id_server):\n interval = ewcfg.enemy_attack_tick_length\n # Causes hostile enemies to attack every tick.\n while not ewutils.TERMINATE:\n ewutils.last_loop['enemy_act'] = int(time.time())\n await asyncio.sleep(interval)\n # resp_cont = EwResponseContainer(id_server=id_server)\n try:\n await cmbt_utils.enemy_perform_action(id_server) #occasionally role update lag will stop this loop,\n except Exception as e:\n ewutils.logMsg('Enemy tick loop failed. Reason:{}'.format(e))\n\n\nasync def release_timed_prisoners_and_blockparties(id_server, day):\n users = bknd_core.execute_sql_query(\"SELECT id_user FROM users WHERE {arrests} <= %s and {arrests} > 0\".format(arrests = ewcfg.col_arrested), (day,))\n\n for user in users:\n user_data = EwUser(id_server=id_server, id_user=user)\n user_data.arrested = 0\n user_data.poi = ewcfg.poi_id_juviesrow\n user_data.persist()\n\n blockparty = EwGamestate(id_server=id_server, id_state='blockparty')\n pre_name = blockparty.value.replace(ewcfg.poi_id_711, '')\n time_str = ''.join([i for i in pre_name if i.isdigit()])\n if time_str != '':\n time_int = int(time_str)\n time_now = int(time.time())\n if time_now > time_int:\n blockparty.bit = 0\n blockparty.value = ''\n blockparty.persist()\n\nasync def reset_brick_loop(id_server):\n interval = 60\n while not ewutils.TERMINATE:\n await asyncio.sleep(interval)\n ewutils.global_brick_counter = 0\n\n\n\nasync def spawn_prank_items_tick_loop(id_server):\n # DEBUG\n # interval = 10\n\n # If there are more active people, items spawn more frequently, and less frequently if there are less active people.\n interval = 180\n new_interval = 0\n while not ewutils.TERMINATE:\n ewutils.last_loop['prank'] = int(time.time())\n if new_interval > 0:\n interval = new_interval\n\n # print(\"newinterval:{}\".format(new_interval))\n\n await asyncio.sleep(interval)\n new_interval = await spawn_prank_items(id_server=id_server)\n\n\nasync def spawn_prank_items(id_server):\n new_interval = 0\n base_interval = 60\n\n try:\n active_users_count = 0\n\n if id_server != None:\n try:\n conn_info = bknd_core.databaseConnect()\n conn = conn_info.get('conn')\n cursor = conn.cursor()\n\n cursor.execute(\n \"SELECT id_user FROM users WHERE id_server = %s AND {poi} in %s AND NOT ({life_state} = {life_state_corpse} OR {life_state} = {life_state_kingpin}) AND {time_last_action} > %s\".format(\n life_state=ewcfg.col_life_state,\n poi=ewcfg.col_poi,\n life_state_corpse=ewcfg.life_state_corpse,\n life_state_kingpin=ewcfg.life_state_kingpin,\n time_last_action=ewcfg.col_time_last_action,\n ), (\n id_server,\n poi_static.capturable_districts,\n (int(time.time()) - ewcfg.time_kickout),\n ))\n\n users = cursor.fetchall()\n\n active_users_count = len(users)\n\n conn.commit()\n finally:\n # Clean up the database handles.\n cursor.close()\n bknd_core.databaseClose(conn_info)\n\n # Avoid division by 0\n if active_users_count == 0:\n active_users_count = 1\n else:\n # print(active_users_count)\n pass\n\n new_interval = (math.ceil(base_interval / active_users_count) * 5) # 5 active users = 1 minute timer, 10 = 30 second timer, and so on.\n\n district_id = random.choice(poi_static.capturable_districts)\n\n # Debug\n # district_id = 'wreckington'\n\n district_channel_name = poi_static.id_to_poi.get(district_id).channel\n\n client = ewutils.get_client()\n\n server = client.get_guild(id_server)\n\n district_channel = fe_utils.get_channel(server=server, channel_name=district_channel_name)\n\n pie_or_prank = random.randrange(3)\n\n if pie_or_prank == 0:\n swilldermuk_food_item = random.choice(swilldermuk_food)\n\n item_props = itm_utils.gen_item_props(swilldermuk_food_item)\n\n swilldermuk_food_item_id = bknd_item.item_create(\n item_type=swilldermuk_food_item.item_type,\n id_user=district_id,\n id_server=id_server,\n item_props=item_props\n )\n\n # print('{} with id {} spawned in {}!'.format(swilldermuk_food_item.str_name, swilldermuk_food_item_id, district_id))\n\n response = \"That smell... it's unmistakeable!! Someone's left a fresh {} on the ground!\".format(swilldermuk_food_item.str_name)\n await fe_utils.send_message(client, district_channel, response)\n else:\n rarity_roll = random.randrange(10)\n\n if rarity_roll > 3:\n prank_item = random.choice(static_items.prank_items_heinous)\n elif rarity_roll > 0:\n prank_item = random.choice(static_items.prank_items_scandalous)\n else:\n prank_item = random.choice(static_items.prank_items_forbidden)\n\n # Debug\n # prank_item = static_items.prank_items_heinous[1] # Chinese Finger Trap\n\n item_props = itm_utils.gen_item_props(prank_item)\n\n prank_item_id = bknd_item.item_create(\n item_type=prank_item.item_type,\n id_user=district_id,\n id_server=id_server,\n item_props=item_props\n )\n\n # print('{} with id {} spawned in {}!'.format(prank_item.str_name, prank_item_id, district_id))\n\n response = \"An ominous wind blows through the streets. You think you hear someone drop a {} on the ground nearby...\".format(prank_item.str_name)\n await fe_utils.send_message(client, district_channel, response)\n\n except:\n ewutils.logMsg(\"An error occured in spawn prank items tick for server {}\".format(id_server))\n\n return new_interval\n\n\nasync def generate_credence_tick_loop(id_server):\n # DEBUG\n # interval = 10\n\n while not ewutils.TERMINATE:\n ewutils.last_loop['credence'] = int(time.time())\n interval = (random.randrange(121) + 120) # anywhere from 2-4 minutes\n await asyncio.sleep(interval)\n await generate_credence(id_server)\n\n\nasync def generate_credence(id_server):\n # print(\"CREDENCE GENERATED\")\n\n if id_server != None:\n try:\n conn_info = bknd_core.databaseConnect()\n conn = conn_info.get('conn')\n cursor = conn.cursor()\n\n cursor.execute(\"SELECT id_user FROM users WHERE id_server = %s AND {poi} in %s AND NOT ({life_state} = {life_state_corpse} OR {life_state} = {life_state_kingpin}) AND {time_last_action} > %s\".format(\n life_state=ewcfg.col_life_state,\n poi=ewcfg.col_poi,\n life_state_corpse=ewcfg.life_state_corpse,\n life_state_kingpin=ewcfg.life_state_kingpin,\n time_last_action=ewcfg.col_time_last_action,\n ), (\n id_server,\n poi_static.capturable_districts,\n (int(time.time()) - ewcfg.time_afk_swilldermuk),\n ))\n\n users = cursor.fetchall()\n\n for user in users:\n user_data = EwUser(id_user=user[0], id_server=id_server)\n\n lowered_credence_used = 0\n credence = ewstats.get_stat(id_server=id_server, id_user=user[0], metric=ewcfg.stat_credence)\n credence_used = ewstats.get_stat(id_server=id_server, id_user=user[0], metric=ewcfg.stat_credence_used)\n if credence >= 1000:\n added_credence = 1 + random.randrange(5)\n elif credence >= 500:\n added_credence = 10 + random.randrange(41)\n elif credence >= 100:\n added_credence = 25 + random.randrange(76)\n else:\n added_credence = 50 + random.randrange(151)\n\n if credence_used > 0:\n lowered_credence_used = int(credence_used / 10)\n\n if lowered_credence_used == 1:\n lowered_credence_used = 0\n\n\n ewstats.set_stat(id_server=id_server, id_user=user[0], metric=ewcfg.stat_credence_used, value=lowered_credence_used)\n\n added_credence = max(0, added_credence - lowered_credence_used)\n ewstats.change_stat(id_server=id_server, id_user=user[0], metric = ewcfg.stat_credence, n=added_credence)\n\n user_data.persist()\n\n conn.commit()\n finally:\n # Clean up the database handles.\n cursor.close()\n bknd_core.databaseClose(conn_info)\n\n\n\n\"\"\"\n Updates/Increments the capture_points values of all districts every time it's called\n\"\"\"\n\n\nasync def capture_tick(id_server):\n # the variables might apparently be accessed before assignment if i didn't declare them here\n cursor = None\n conn_info = None\n\n resp_cont_capture_tick = EwResponseContainer(client=ewutils.get_client(), id_server=id_server)\n\n all_districts = poi_static.capturable_districts\n\n if len(all_districts) > 0: # if all_districts isn't empty\n server = ewcfg.server_list[id_server]\n time_old = time.time()\n\n for district in all_districts:\n district_name = district\n dist = EwDistrict(id_server=id_server, district=district_name)\n\n # if it has a lock and isnt surrounded by friendly districts, degrade the lock\n if dist.time_unlock > 0 and not dist.all_neighbors_friendly():\n responses = dist.change_capture_lock(progress=-ewcfg.capture_tick_length)\n resp_cont_capture_tick.add_response_container(responses)\n dist.persist()\n\n # If a lock is active, or if it is surrounded, skip this district for capping calculations\n if dist.time_unlock > 0:\n continue\n\n gangsters_in_district = dist.get_players_in_district(min_slimes=ewcfg.min_slime_to_cap, life_states=[ewcfg.life_state_enlisted], ignore_offline=False)\n\n slimeoids = ewutils.get_slimeoids_in_poi(poi=district_name, id_server=id_server, sltype=ewcfg.sltype_nega)\n\n nega_present = len(slimeoids) > 0\n #\t\t\tif nega_present:\n #\t\t\t\tcontinue\n\n # the faction that's actively capturing the district this tick\n # if no players are present, it's None, if only players of one faction (ignoring juvies and ghosts) are,\n # it's the faction's name, i.e. 'rowdys' or 'killers', and if both are present, it's 'both'\n faction_capture = None\n\n # how much progress will be made. is higher the more people of one faction are in a district, and is 0 if both teams are present\n capture_speed = 0\n\n # number of players actively capturing\n num_capturers = 0\n\n # list of players contributing to capping, who need stats tracked\n dc_stat_increase_list = []\n\n # checks if any players are in the district and if there are only players of the same faction, i.e. progress can happen\n for player in gangsters_in_district:\n player_id = player\n user_data = EwUser(id_user=player_id, id_server=id_server)\n player_faction = user_data.faction\n\n mutations = user_data.get_mutations()\n\n # dont count offline players\n try:\n player_online = (await fe_utils.get_member(server, player_id)).status != discord.Status.offline\n except:\n player_online = False\n\n # ewutils.logMsg(\"Online status checked. Time elapsed: %f\" % (time.time() - time_old) + \" Server: %s\" % id_server + \" Player: %s\" % player_id + \" Status: %s\" % (\"online\" if player_online else \"offline\"))\n\n if player_online:\n if faction_capture not in [None, player_faction]: # if someone of the opposite faction is in the district\n faction_capture = 'both' # standstill, gang violence has to happen\n capture_speed = 0\n num_capturers = 0\n dc_stat_increase_list.clear()\n\n else: # if the district isn't already controlled by the player's faction and the capture isn't halted by an enemy\n faction_capture = player_faction\n player_capture_speed = 1\n if ewcfg.mutation_id_lonewolf in mutations and len(gangsters_in_district) == 1:\n player_capture_speed *= 2\n #if ewcfg.mutation_id_patriot in mutations:\n player_capture_speed *= 1.5\n if ewcfg.mutation_id_unnaturalcharisma in mutations:\n player_capture_speed += 1\n\n capture_speed += player_capture_speed\n num_capturers += 1\n dc_stat_increase_list.append(player_id)\n\n if faction_capture not in ['both', None]: # if only members of one faction is present\n if district_name in poi_static.capturable_districts:\n # 10% extra/less speed per adjacent district under same faction if being reinforced/taken\n friendly_neighbors = dist.get_number_of_friendly_neighbors()\n if dist.all_neighbors_friendly():\n capture_speed = 0\n if dist.controlling_faction == faction_capture:\n capture_speed *= 1 + 0.1 * friendly_neighbors\n else:\n capture_speed /= 1 + 0.1 * friendly_neighbors\n\n # get current capping progress\n capture_progress = dist.capture_points\n\n # set calculated progress negative if it was being captured by the other gang\n if faction_capture != dist.capturing_faction:\n capture_progress *= -1\n\n # properly scale the speed to the scale of points needed\n capture_speed *= ewcfg.baseline_capture_speed\n\n # Track capturer stats as long as they arent overcapping\n if dist.capture_points < dist.max_capture_points:\n for stat_recipient in dc_stat_increase_list:\n ewstats.change_stat(\n id_server=id_server,\n id_user=stat_recipient,\n metric=ewcfg.stat_capture_points_contributed,\n n=ewcfg.capture_tick_length * capture_speed\n )\n\n # if it was already being captured by the currently capturing faction\n if faction_capture == dist.capturing_faction: # if the faction is already in the process of capturing, continue\n responses = dist.change_capture_points(ewcfg.capture_tick_length * capture_speed, faction_capture, num_capturers)\n resp_cont_capture_tick.add_response_container(responses)\n\n # otherwise, if it has zero points and is uncontrolled\n elif dist.capture_points == 0 and dist.controlling_faction == \"\": # if it's neutral, start the capture\n responses = dist.change_capture_points(ewcfg.capture_tick_length * capture_speed, faction_capture, num_capturers)\n resp_cont_capture_tick.add_response_container(responses)\n\n dist.capturing_faction = faction_capture\n\n # lower the enemy faction's progress to revert it to neutral (or potentially get it onto your side without becoming neutral first)\n else: # if the (de-)capturing faction is not in control\n responses = dist.change_capture_points(-(ewcfg.capture_tick_length * capture_speed * ewcfg.decapture_speed_multiplier), faction_capture)\n resp_cont_capture_tick.add_response_container(responses)\n\n dist.persist()\n\n return await resp_cont_capture_tick.post()\n\n\n\"\"\"\n Coroutine that continually calls capture_tick; is called once per server, and not just once globally\n\"\"\"\n\n\nasync def capture_tick_loop(id_server):\n interval = ewcfg.capture_tick_length\n # causes a capture tick to happen exactly every 10 seconds (the \"elapsed\" thing might be unnecessary, depending on how long capture_tick ends up taking on average)\n while not ewutils.TERMINATE:\n ewutils.last_loop['capture'] = int(time.time())\n await capture_tick(id_server=id_server)\n # ewutils.logMsg(\"Capture tick happened on server %s.\" % id_server + \" Timestamp: %d\" % int(time.time()))\n\n await asyncio.sleep(interval)\n\n\n\"\"\"\n Gives both kingpins the appropriate amount of slime for how many districts they own and lowers the capture_points property of each district by a certain amount, turning them neutral after a while\n\"\"\"\n\n\n# Used in the market loop, trying to get EwUser out of district utils so this can go here\nasync def give_kingpins_slime_and_decay_capture_points(id_server):\n resp_cont_decay_loop = EwResponseContainer(client=ewutils.get_client(), id_server=id_server)\n\n for kingpin_role in [ewcfg.role_rowdyfucker, ewcfg.role_copkiller]:\n kingpin = fe_utils.find_kingpin(id_server=id_server, kingpin_role=kingpin_role)\n if kingpin is not None:\n kingpin = EwUser(id_server=id_server, id_user=kingpin.id_user)\n total_slimegain = 0\n for id_district in poi_static.capturable_districts:\n\n district = EwDistrict(id_server=id_server, district=id_district)\n\n # if the kingpin is controlling this district give the kingpin slime based on the district's property class\n if district.controlling_faction == (ewcfg.faction_killers if kingpin.faction == ewcfg.faction_killers else ewcfg.faction_rowdys):\n poi = poi_static.id_to_poi.get(id_district)\n\n slimegain = ewcfg.district_control_slime_yields[poi.property_class]\n\n # increase slimeyields by 10 percent per friendly neighbor\n friendly_mod = 1 + 0.1 * district.get_number_of_friendly_neighbors()\n total_slimegain += slimegain * friendly_mod\n\n kingpin.change_slimes(n=total_slimegain)\n kingpin.persist()\n\n ewutils.logMsg(kingpin_role + \" just received %d\" % total_slimegain + \" slime for their captured districts.\")\n\n # Decay capture points.\n for id_district in poi_static.capturable_districts:\n district = EwDistrict(id_server=id_server, district=id_district)\n\n responses = district.decay_capture_points()\n resp_cont_decay_loop.add_response_container(responses)\n district.persist()\n\n return await resp_cont_decay_loop.post()\n\n\nasync def clock_tick_loop(id_server, force_active = False):\n \"\"\" Good ol' Clock Tick Loop. Handles everything that has to occur on an in-game hour. (15 minutes)\"\"\"\n while not ewutils.TERMINATE:\n ewutils.last_loop['clock'] = int(time.time())\n try:\n time_now = int(time.time())\n # Load the market from the database\n market_data = EwMarket(id_server)\n client = ewcfg.get_client()\n server = ewcfg.server_list[id_server]\n\n # Check when the last recorded tick was in the database, just to make sure we don't double up when the bot restarts.\n if market_data.time_lasttick + ewcfg.update_market <= time_now or force_active:\n\n # Advance the time and potentially change weather.\n market_data.clock += 1\n\n if market_data.clock >= 24 or market_data.clock < 0:\n market_data.clock = 0\n market_data.day += 1\n\n market_data.time_lasttick = time_now\n\n ewutils.logMsg('The time is now {}.'.format(market_data.clock))\n\n ewutils.logMsg(\"Updating stocks...\")\n await market_utils.update_stocks(id_server=id_server, time_lasttick=time_now)\n market_data.persist()\n\n ewutils.logMsg(\"Handling weather cycle...\")\n await weather_utils.weather_cycle(id_server)\n\n if ewutils.check_moon_phase(market_data) != ewcfg.moon_full and not ewcfg.dh_active: # I don't see why costumes should be dedorned automatically so, like, just removing this. It's dumb.\n await cosmetic_utils.dedorn_all_costumes()\n\n ewutils.logMsg('Setting off alarms...')\n await apt_utils.handle_hourly_events(id_server)\n\n # Decay slime totals\n ewutils.logMsg(\"Decaying slimes...\")\n await decaySlimes(id_server)\n\n # Decrease inebriation for all players above min (0).\n ewutils.logMsg(\"Handling inebriation...\")\n await pushdownServerInebriation(id_server)\n\n ewutils.logMsg('Updating rotations...')\n mut_utils.initialize_rotation(id_server)\n\n ewutils.logMsg(\"Killing offers...\")\n # Remove fish offers which have timed out\n bknd_fish.kill_dead_offers(id_server)\n\n ewutils.logMsg(\"Deleting old ads...\")\n # kill advertisements that have timed out\n bknd_ads.delete_expired_ads(id_server)\n\n ewutils.logMsg(\"Handling capture points...\")\n await give_kingpins_slime_and_decay_capture_points(id_server)\n \n ewutils.logMsg(\"Sending gangbase messages...\")\n await move_utils.send_gangbase_messages(id_server, market_data.clock)\n \n ewutils.logMsg(\"Kicking AFK players...\")\n await move_utils.kick(id_server) \n\n ewutils.logMsg(\"Running misc. events...\")\n await misc_hourly_function(id_server=id_server)\n\n sex_channel = fe_utils.get_channel(server=server, channel_name=ewcfg.channel_stockexchange)\n\n if market_data.clock == 6 or force_active:\n response = ' The SlimeCorp Stock Exchange is now open for business.'\n \n await fe_utils.send_message(client, sex_channel, response)\n \n\n # Bazaar Refresh\n try:\n\n ewutils.logMsg(\"Started bazaar refresh...\")\n await market_utils.refresh_bazaar(id_server)\n ewutils.logMsg(\"...finished bazaar refresh.\")\n\n except Exception as e:\n ewutils.logMsg(f\"Bazaar refresh failed in server {id_server}: {e}\")\n\n # Leaderboard Refresh\n try:\n ewutils.logMsg(\"Started leaderboard calcs...\")\n\n await leaderboard_utils.post_leaderboards(client=client, server=server)\n ewutils.logMsg(\"...finished leaderboard calcs.\")\n except Exception as e:\n ewutils.logMsg(f\"Failed to process leaderboards for server {id_server}: {e}\")\n\n # Yeah the slimernalia\n if ewcfg.slimernalia_active:\n try:\n ewutils.logMsg(\"Started Slimernalia kingpin election...\")\n await fe_utils.update_slimernalia_kingpin(client, server)\n ewutils.logMsg(\"...finished kingpin election.\")\n except Exception as e:\n ewutils.logMsg(f\"Failed to elect slimernalia kingpin in server {id_server}: {e}\")\n \n # Prisoner Releases\n try:\n ewutils.logMsg(\"Releasing time prisoners...\")\n await release_timed_prisoners_and_blockparties(id_server=id_server, day=market_data.day)\n ewutils.logMsg(\"...finished releasing prisoners.\")\n except Exception as e:\n ewutils.logMsg(f\"Failed to release prisoners in server {id_server}: {e}\")\n \n # Blockparty expiries\n try:\n ewutils.logMsg(\"Expiring blockparties...\")\n await release_timed_prisoners_and_blockparties(id_server=id_server, day=market_data.day)\n ewutils.logMsg(\"Expired blockparties.\")\n except Exception as e:\n ewutils.logMsg(f\"Failed to expire blockparties in server {id_server}: {e}\")\n\n if market_data.day % 8 == 0 or force_active:\n continue # TODO: Turn off once alive players stop getting their user_data reset! :P\n # Rent processing\n try:\n ewutils.logMsg(\"Started rent calc...\")\n await apt_utils.rent_time(id_server)\n ewutils.logMsg(\"...finished rent calc.\")\n except Exception as e:\n ewutils.logMsg(f\"Failed to process rent in server {id_server}: {e}\")\n\n\n if random.randint(1, 9) == 1 or force_active: # 1/9 chance to start a random poi event\n # POI Events\n try:\n ewutils.logMsg(\"Creating POI event...\")\n await weather_utils.create_poi_event(id_server)\n ewutils.logMsg(\"...finished POI event creation.\")\n except Exception as e:\n ewutils.logMsg(f\"Failed to create POI event in server {id_server}: {e}\")\n\n elif market_data.clock == 13 and market_data.day % 28 == 0 or force_active: #regulate slimesea items every week\n ewutils.logMsg('Regulating Slime Sea items...')\n number = itm_utils.cull_slime_sea(id_server=id_server)\n ewutils.logMsg('...Slime Sea culled. {} items deleted.'.format(number))\n\n elif market_data.clock == 20 or force_active:\n response = ' The SlimeCorp Stock Exchange has closed for the night.'\n await fe_utils.send_message(client, sex_channel, response)\n \n ewutils.logMsg(\"Finished clock tick.\")\n await asyncio.sleep(60)\n except Exception as e:\n traceback.print_exc(file=sys.stdout)\n ewutils.logMsg('An error occurred in the scheduled slime market update task: {}. Fix that.'.format(e))","sub_path":"ew/utils/loop.py","file_name":"loop.py","file_ext":"py","file_size_in_byte":65775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"76661157","text":"from io import BytesIO\nimport docker\ndockerfile = '''\n# Shared Volume\nFROM busybox:buildroot-2014.02\nVOLUME /data\nCMD [\"/bin/sh\"]\n'''\nf = BytesIO(dockerfile.encode('utf-8'))\ncli = docker.from_env()\nresponse = cli.api.build(fileobj=f, rm=True, tag='test3', decode=True)\n\n#for line in response:\n# if line.keys()[0] in ('stream', 'error'):\n# value = line.values()[0].strip()\n# if value:\n# print(value)\n\n\n\n\n# for line in response:\n# if line.keys in ('stream', 'error'):\n# value = line.values()[0].strip()\n# if value:\n# print(value)","sub_path":"docker/create_docker_images2.py","file_name":"create_docker_images2.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"544783078","text":"from setuptools import setup\nimport platform\n\n# Make the install_requires\ntarget = platform.python_implementation()\nif target == 'PyPy':\n install_requires = ['psycopg2ct']\nelse:\n install_requires = ['psycopg2']\n\nsetup(name='pgsql_wrapper',\n version='1.1.2',\n description=\"PostgreSQL / psycopg2 caching wrapper class\",\n maintainer=\"Gavin M. Roy\",\n maintainer_email=\"gmr@meetme.com\",\n url=\"http://github.com/MeetMe/pgsql_wrapper\",\n install_requires=install_requires,\n py_modules=['pgsql_wrapper'],\n zip_safe=True)\n","sub_path":"pypi_install_script/pgsql_wrapper-1.1.2.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"11197413","text":"from launch import LaunchDescription\nfrom launch_ros.actions import Node\n\nimport launch.actions\n# import launch_ros.actions ## for launch.actions\n\nimport os\nfrom ament_index_python.packages import get_package_share_directory\n\ndef generate_launch_description():\n # parameters\n param_file = os.path.join(get_package_share_directory('polyx_node'), \n 'param',\n 'polyx_talker_params.yaml')\n\n return LaunchDescription([\n \n # Set env var to print messages to stdout immediately\n # requirement #1\n launch.actions.SetEnvironmentVariable(\n 'RCUTILS_CONSOLE_STDOUT_LINE_BUFFERED', '1'),\n \n # dashing \n Node(\n package='polyx_node',\n node_namespace='polyx_ns', # kick in, override\n node_executable='polyx_node_talker',\n name='polyx_name', # useless\n output='screen', # requirement #2\n parameters=[param_file]\n )\n ])","sub_path":"polyx_node/launch/polyx_talker_launch.py","file_name":"polyx_talker_launch.py","file_ext":"py","file_size_in_byte":962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"412105205","text":"from Tools.CheckIP import CheckIP\nfrom Tools.DataBase.db import ConnMysql\nimport json\n\n\nci = CheckIP()\ncm = ConnMysql()\n\n\nIP_LIST = []\nsql = \"\"\"select `type`, `ip`, `port` from ipipip where nmd='High Anonymity' and score='100';\"\"\"\ncm.exe(sql)\nfor data in cm.cursor:\n proxies = ci.mk_proxies(data[0], data[1], data[2])\n print(proxies)\n IP_LIST.append(proxies)\n print(IP_LIST)\n\n\nwith open('ip_pool.py', 'w') as f:\n f.write('IP_LIST = ' + json.dumps(IP_LIST))\n","sub_path":"Tools/中转ip.py","file_name":"中转ip.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"313928118","text":"# t15_41_polynome_ex.py\r\n# Поліном. Обробка виключень\r\n\r\nfrom T14.t14_20_polynome import Polynome\r\n\r\nclass PolynomeError(Exception):\r\n \"\"\"\r\n Клас виключення для поліномів\r\n \"\"\"\r\n def __str__(self):\r\n return \"Помилка обробки поліному\"\r\n\r\n\r\nclass PolynomeEmptyError(PolynomeError):\r\n \"\"\"\r\n Клас виключення порожнього поліному (порожнього р��дка)\r\n \"\"\"\r\n def __str__(self):\r\n return \"Порожній рядок для поліному\"\r\n\r\n\r\nclass PolynomeCoeffError(PolynomeError):\r\n \"\"\"\r\n Клас виключення недопустимого коефіцієнту поліному\r\n \"\"\"\r\n def __init__(self, coeff):\r\n self.coeff = coeff # значення коефіцієнту,\r\n # що викликало помилку\r\n\r\n def __str__(self):\r\n return \"Недопустимий коефіцієнт: {}\".format(self.coeff)\r\n\r\n\r\nclass PolynomeDegreeError(PolynomeError):\r\n \"\"\"\r\n Клас виключення недопустимої степені поліному\r\n \"\"\"\r\n def __init__(self, degree):\r\n self.degree = degree # значення степені,\r\n # що викликало помилку\r\n\r\n def __str__(self):\r\n return \"Недопустима степінь: {}\".format(self.degree)\r\n\r\n\r\nclass PolynomeEx(Polynome):\r\n \"\"\"Даний клас є нащадком Polynome та реалізує дії над поліномами.\r\n\r\n Клас ініціює виключення при неправильному завданні поліному\r\n за допомогою рядка\r\n або при неправильному додаванні одночлена до поліному\r\n \"\"\"\r\n def fromstring(s):\r\n \"\"\"\r\n Перетворення рядка у поліном.\r\n\r\n Рядок повинен мати вигляд (наприклад):\r\n\r\n 3.7*x**3 + 0.3*x**1 + -1.2*x**0\r\n\r\n Пробіли між коефіцієнтами та степенями не допускаються.\r\n Від'ємні коефіцієнти записувати як у прикладі вище.\r\n У разі виникнення помилки, ініціює відповідне виключення\r\n :param s: рядок\r\n :return: об'єкт класу Polynome\r\n \"\"\"\r\n p = Polynome()\r\n s = s.replace('+',' ')\r\n ls = s.split() #розбиваємо на список одночленів\r\n if not ls:\r\n raise PolynomeEmptyError\r\n\r\n for m in ls:\r\n c = m.split('*x**') #виділяємо степінь та коефіцієнт\r\n try:\r\n k = int(c[1])\r\n if k < 0:\r\n raise PolynomeDegreeError(k)\r\n except ValueError:\r\n raise PolynomeDegreeError(c[1])\r\n try:\r\n v = float(c[0])\r\n except ValueError:\r\n raise PolynomeCoeffError(c[0])\r\n p[k] = v\r\n return p\r\n\r\n fromstring = staticmethod(fromstring)\r\n\r\n def add_monom(self, deg, coeff):\r\n \"\"\"\r\n Додати одночлен степені deg до поліному.\r\n У разі виникнення помилки, ініціює відповідне виключення\r\n :param deg: степінь одночлена\r\n :param coeff: коефіцієнт одночлена\r\n :return: None\r\n \"\"\"\r\n try:\r\n coeff = float(coeff)\r\n except ValueError:\r\n raise PolynomeCoeffError(coeff)\r\n\r\n if coeff != 0:\r\n try:\r\n deg = int(deg)\r\n if deg < 0:\r\n raise PolynomeDegreeError(deg)\r\n except ValueError:\r\n raise PolynomeDegreeError(deg)\r\n self[deg] += coeff\r\n","sub_path":"samples/t15_41_polynome_ex.py","file_name":"t15_41_polynome_ex.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"458660118","text":"from queue import PriorityQueue\r\n\r\nArad = \"Arad\"\r\nBucharest = \"Bucharest\"\r\nCraiova = \"Craiova\"\r\nDobreta = \"Dobreta\"\r\nEforie = \"Eforie\"\r\nFagaras = \"Fagaras\"\r\nGiurgiu = \"Giurgiu\"\r\nHirsova = \"Hirsova\"\r\nIasi = \"Iasi\"\r\nLugoj = \"Lugoj\"\r\nMehadia = \"Mehadia\"\r\nNeamt = \"Neamt\"\r\nOradea = \"Oradea\"\r\nPitesti = \"Pitesti\"\r\nRimnicuVilcea = \"Rimnicu Vilcea\"\r\nSibiu = \"Sibiu\"\r\nTimisoara = \"Timisoara\"\r\nUrziceni = \"Urziceni\"\r\nVaslui = \"Vaslui\"\r\nZerind = \"Zerind\"\r\n\r\ndistrito_de_bucharest = {\r\n Arad: 366,\r\n Bucharest: 0,\r\n Craiova: 160,\r\n Dobreta: 242,\r\n Eforie: 161,\r\n Fagaras: 176,\r\n Giurgiu: 77,\r\n Hirsova: 151,\r\n Iasi: 226,\r\n Lugoj: 244,\r\n Mehadia: 241,\r\n Neamt: 234,\r\n Oradea: 380,\r\n Pitesti: 100,\r\n RimnicuVilcea: 193,\r\n Sibiu: 253,\r\n Timisoara: 329,\r\n Urziceni: 80,\r\n Vaslui: 199,\r\n Zerind: 374\r\n}\r\n\r\ncusto_da_distancia = {\r\n Arad: 0,\r\n Bucharest: 0,\r\n Craiova: 0,\r\n Dobreta: 0,\r\n Eforie: 0,\r\n Fagaras: 0,\r\n Giurgiu: 0,\r\n Hirsova: 0,\r\n Iasi: 0,\r\n Lugoj: 0,\r\n Mehadia: 0,\r\n Neamt: 0,\r\n Oradea: 0,\r\n Pitesti: 0,\r\n RimnicuVilcea: 0,\r\n Sibiu: 0,\r\n Timisoara: 0,\r\n Urziceni: 0,\r\n Vaslui: 0,\r\n Zerind: 0\r\n}\r\n\r\nmapa_da_romenia = {\r\n Arad: {\r\n Zerind: 75,\r\n Timisoara: 118,\r\n Sibiu: 140\r\n },\r\n Bucharest: {\r\n Fagaras: 211,\r\n Pitesti: 101,\r\n Giurgiu: 90,\r\n Urziceni: 85\r\n },\r\n Craiova: {\r\n Dobreta: 120,\r\n RimnicuVilcea: 146,\r\n Pitesti: 138\r\n },\r\n Dobreta: {\r\n Craiova: 120,\r\n Mehadia: 75\r\n },\r\n Eforie: {\r\n Hirsova: 86\r\n },\r\n Fagaras: {\r\n Sibiu: 99,\r\n Bucharest: 211\r\n },\r\n Giurgiu: {\r\n Bucharest: 90\r\n },\r\n Hirsova: {\r\n Eforie: 86,\r\n Urziceni: 98\r\n },\r\n Iasi: {\r\n Neamt: 87,\r\n Vaslui: 92\r\n },\r\n Lugoj: {\r\n Timisoara: 111,\r\n Mehadia: 70\r\n },\r\n Mehadia: {\r\n Lugoj: 70,\r\n Dobreta: 75\r\n },\r\n Neamt: {\r\n Iasi: 87\r\n },\r\n Oradea: {\r\n Zerind: 71,\r\n Sibiu: 151\r\n },\r\n Pitesti: {\r\n RimnicuVilcea: 97,\r\n Craiova: 138,\r\n Bucharest: 101\r\n },\r\n RimnicuVilcea: {\r\n Pitesti: 97,\r\n Sibiu: 80,\r\n Craiova: 146\r\n },\r\n Sibiu: {\r\n RimnicuVilcea: 80,\r\n Oradea: 151,\r\n Arad: 140,\r\n Fagaras: 99\r\n },\r\n Timisoara: {\r\n Arad: 118,\r\n Lugoj: 111\r\n },\r\n Urziceni: {\r\n Bucharest: 85,\r\n Vaslui: 142,\r\n Hirsova: 98\r\n },\r\n Vaslui: {\r\n Urziceni: 142,\r\n Iasi: 92\r\n },\r\n Zerind: {\r\n Arad: 75,\r\n Oradea: 71\r\n }\r\n}\r\n\r\n\r\ndef h(n):\r\n global distrito_de_bucharest\r\n return distrito_de_bucharest[n]\r\n\r\n\r\ndef g(n):\r\n global custo_da_distancia\r\n return custo_da_distancia[n]\r\n\r\n\r\ndef f(n):\r\n return h(n) + g(n)\r\n\r\n\r\ndef busca_A(raiz, objetivo):\r\n q = PriorityQueue()\r\n q.put((h(raiz), raiz, [raiz]))\r\n\r\n while not q.empty():\r\n frente = q.get()\r\n cidade = frente[1]\r\n if cidade is objetivo:\r\n print(\"Encontrado com {} de custo\".format(frente[0]))\r\n print(\"Caminho:\", frente[2])\r\n return\r\n\r\n cidades_adjacentes = mapa_da_romenia[cidade]\r\n for cidade_adjacente, custo in cidades_adjacentes.items():\r\n custo_da_distancia[cidade_adjacente] = custo_da_distancia[cidade] + custo\r\n q.put((f(cidade_adjacente), cidade_adjacente, frente[2] + [cidade_adjacente]))\r\n\r\n\r\ndef main():\r\n busca_A(Zerind, Bucharest)\r\n\r\n\r\nmain()","sub_path":"algoritmoBuscaA - Romenia.py","file_name":"algoritmoBuscaA - Romenia.py","file_ext":"py","file_size_in_byte":3625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"634316083","text":"import os\r\nimport pydwarf\r\nfrom raws import rawsfile, rawstoken\r\n\r\npermitted_reactions = ''' \r\n\\t[PERMITTED_REACTION:MANGANESE_STEEL_MAKING_BARS]\r\n\\t[PERMITTED_REACTION:MANGANESE_STEEL_MAKING_ORE]\r\n\\t[PERMITTED_REACTION:HIGH_SPEED_STEEL_MAKING]\r\n\\t[PERMITTED_REACTION:BERYLLIUM_MACRO_PUTNAM]\r\n\\t[PERMITTED_REACTION:KROLL_MACRO_PUTNAM]\r\n\\t[PERMITTED_REACTION:BERYLLIUM_REFINING_PUTNAM_GEMS]\r\n\\t[PERMITTED_REACTION:BERYLLIUM_REFINING_PUTNAM_BOULDER]\r\n\\t[PERMITTED_REACTION:MAKE_SULFURIC_ACID_PUTNAM]\r\n\\t[PERMITTED_REACTION:KROLL_PROCESS_BOULDER_PUTNAM]\r\n\\t[PERMITTED_REACTION:KROLL_PROCESS_GEM_PUTNAM]\r\n\\t[PERMITTED_REACTION:PIDGEON_PROCESS_PUTNAM]'''\r\n\r\n# Utility function for putting new properties after an inorganic's USE_MATERIAL_TEMPLATE token, if it has one\r\n# Otherwise, the property is just added after the INORGANIC object token.\r\ndef addaftertemplate(inorganic, addition):\r\n template = inorganic.getuntil(exact_value='USE_MATERIAL_TEMPLATE', until_exact_value='INORGANIC')\r\n addafter = template if template else inorganic\r\n return addafter.add(addition)\r\n\r\n@pydwarf.urist(\r\n name = 'materials plus',\r\n version = 'alpha',\r\n author = ('Putnam', 'Sophie Kirschner'),\r\n description = 'Adds a bunch of materials to the game.',\r\n compatibility = (pydwarf.df_0_34, pydwarf.df_0_40)\r\n)\r\ndef materialsplus(raws):\r\n exceptions = 0\r\n \r\n try:\r\n for zircon in raws.all(exact_value='INORGANIC', re_args=['.* ZIRCON']):\r\n addaftertemplate(zircon, 'MATERIAL_REACTION_PRODUCT:KROLL_PROCESS:INORGANIC:ZIRCONIUM_PUTNAM')\r\n pydwarf.log.debug('Added reaction to zircons.')\r\n except:\r\n pydwarf.log.exception('Failed to add reaction to zircons.')\r\n exceptions += 1\r\n \r\n try:\r\n for beryl in raws.all(exact_value='INORGANIC', re_args=['.* BERYL|HELIODOR|MORGANITE|GOSHENITE|EMERALD']):\r\n addaftertemplate(beryl, 'REACTION_CLASS:BERYLLIUM')\r\n pydwarf.log.debug('Added reaction to beryls.')\r\n except:\r\n pydwarf.log.exception('Failed to add reaction to beryls.')\r\n exceptions += 1\r\n \r\n try:\r\n chromite = raws.get('INORGANIC:CHROMITE')\r\n pyrolusite = raws.get('INORGANIC:PYROLUSITE')\r\n addaftertemplate(chromite, '[METAL_ORE:CHROMIUM_PUTNAM:100][METAL_ORE:IRON:50]')\r\n addaftertemplate(pyrolusite, 'METAL_ORE:MANGANESE_PUTNAM:100')\r\n pydwarf.log.debug('Added titanium ores.')\r\n except:\r\n pydwarf.log.exception('Failed to add titanium ores.')\r\n exceptions += 1\r\n \r\n try:\r\n for silicon in raws.all(exact_value='INORGANIC', re_args=['ANDESITE|OLIVINE|HORNBLENDE|SERPENTINE|ORTHOCLASE|MICROCLINE|MICA']):\r\n addaftertemplate(silicon, 'REACTION_CLASS:SILICON')\r\n pydwarf.log.debug('Added silicon reactions.')\r\n except:\r\n pydwarf.log.exception('Failed to add silicon reactions.')\r\n exceptions += 1\r\n \r\n try:\r\n dolomite = raws.get('INORGANIC:DOLOMITE')\r\n addaftertemplate(dolomite, 'REACTION_CLASS:PIDGEON_PROCESS')\r\n pydwarf.log.debug('Added reaction to dolomite.')\r\n except:\r\n pydwarf.log.exception('Failed to add reaction to dolomite.')\r\n exceptions += 1\r\n \r\n try:\r\n raws.get('ENTITY:MOUNTAIN').get(exact_value='PERMITTED_REACTION').add(permitted_reactions, reverse=True)\r\n pydwarf.log.debug('Added permitted reactions.')\r\n except:\r\n pydwarf.log.exception('Failed to add permitted reactions.')\r\n exceptions += 1\r\n \r\n for root, dirs, files in os.walk(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'Materials Plus')):\r\n for filename in files:\r\n suffix = '_mat_plus.txt'\r\n if filename.endswith(suffix):\r\n path = os.path.join(root, filename)\r\n destname = 'putnam_%s' % filename[:-len(suffix)]\r\n rfile = raws.getfile(destname)\r\n if rfile:\r\n pydwarf.log.debug('Appending data to file %s from %s...' % (destname, path))\r\n with open(path, 'rb') as matplus: rfile.add(matplus)\r\n else:\r\n with open(path, 'rb') as matplus: raws.addfile(rfile=rawsfile(header=destname, rfile=matplus))\r\n pydwarf.log.debug('Adding data to new file %s.' % destname)\r\n \r\n if exceptions == 0:\r\n return pydwarf.success()\r\n else:\r\n return pydwarf.failure('Failed to complete %d operations.' % exceptions)\r\n","sub_path":"scripts/putnam/Fantastic Mini-Mods/pydwarf.materialsplus.py","file_name":"pydwarf.materialsplus.py","file_ext":"py","file_size_in_byte":4510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"571079413","text":"#!/usr/bin/python\n\n\nfrom ev3.ev3dev import Ev3Dev, Key, Motor\nfrom ev3.lego import ColorSensor\nimport logging\nimport sys\nimport os\nimport time\n\nlogger = logging.getLogger(__name__)\n\n\nclass CubeSolver3x3():\n\n def __init__(self):\n\n # Motors\n # ==============================\n self.flipper = Motor(port=Motor.PORT.A)\n\n # + turns clockwise\n # - turns counter-clockwise\n self.turntable = Motor(port=Motor.PORT.B)\n\n # + speed_sp moves it to the \"right\" (away from the cube)\n # - speed_sp moves it to the \"left\" (towards the cube)\n self.color_arm = Motor(port=Motor.PORT.C)\n\n # Sensors \n # ==============================\n #self.ir_sensor = Msensor(port=1)\n #self.color_sensor = Msensor(port=2)\n self.color_sensor = ColorSensor()\n\n\n # Reset all three motors to their base position\n self.color_arm_reset()\n #self.color_arm_middle()\n #self.turntable_clockwise_eighth()\n #self.color_arm_right_inner()\n #self.color_arm_right_outer()\n #self.flipper_arm_reset()\n #self.turntable_reset()\n\n #self.turntable_clockwise_quarter()\n #self.turntable_clockwise_eighth()\n #self.turntable_turn(20)\n #self.turntable_turn(-20)\n\n #self.wait_for_cube()\n self.scan_colors()\n #self.calculate_solution()\n #self.implement_solution()\n return\n\n\n '''\n Flipper arm methods\n '''\n def flipper_arm_reset(self):\n \"\"\"\n Motor A\n -101: Reset position\n\n 26: The arm is down on the cube and the cube\n is flush to the left side of the turntable\n\n 100: The arm grabbed the top of the cube and pulled it to the left,\n the cube is at an angle and is ready to be pushed forward to flip\n to the next side\n\n \"\"\"\n initial_position = self.flipper.position\n logger.debug('flipper starting position %d' % initial_position)\n\n self.flipper.run_position_limited(position_sp=-101, speed_sp=70)\n time.sleep(1)\n\n final_position = self.flipper.position\n logger.debug('flipper final position %s' % final_position)\n\n\n '''\n Turntable methods\n '''\n def turntable_reset(self):\n logger.warning('Need a touch senser to implement turntable reset')\n\n def turntable_stop(self):\n self.turntable.run_time_limited(time_sp=0,\n speed_sp=80,\n stop_mode=Motor.STOP_MODE.BRAKE)\n\n def turntable_turn(self, amount):\n initial_position = self.turntable.position\n target_position = initial_position + amount\n logger.debug('turntable initial position %s' % initial_position)\n logger.debug('turntable target position %s' % target_position)\n\n if amount < 135:\n speed = 50\n\n # 1/8 of a turn\n elif amount == 135:\n speed = 100\n\n # 1/4 or 1/2 of a turn\n else:\n speed = 400\n\n if target_position < initial_position:\n speed = speed * -1\n\n self.turntable.run_forever(speed_sp=speed)\n\n for x in range(200):\n current_position = self.turntable.position\n #logger.debug('turntable current position %d' % current_position)\n\n if abs(current_position - target_position) <= 10:\n logger.debug('turntable within target, current %d, target %d' % (current_position, target_position))\n break\n time.sleep(0.01)\n\n self.turntable_stop()\n self.turntable.run_position_limited(position_sp=target_position, speed_sp=50)\n time.sleep(0.1)\n\n final_position = self.turntable.position\n logger.debug('turntable final position %s' % final_position)\n\n def turntable_clockwise_eighth(self):\n logger.info('turntable turn clockwise 1/8')\n self.turntable_turn(135)\n\n def turntable_clockwise_quarter(self):\n logger.info('turntable turn clockwise 1/4')\n self.turntable_turn(270)\n\n def turntable_counterclockwise_quarter(self):\n logger.info('turntable turn counter clockwise 1/4')\n self.turntable_turn(-270)\n\n def turntable_clockwise_half(self, amount):\n logger.info('turntable turn clockwise 1/2')\n self.turntable_turn(540)\n\n\n '''\n color sensor methods\n '''\n def color_arm_reliable(self, target_position):\n initial_position = self.color_arm.position\n logger.debug('color arm initial position %d, target_position %d' % (initial_position, target_position))\n\n speed = 100\n\n if target_position > initial_position:\n speed = speed * -1\n\n self.color_arm.run_forever(speed_sp=speed)\n\n for x in range(200):\n current_position = self.color_arm.position\n\n if abs(current_position - target_position) <= 10:\n logger.debug('color arm within target, current %d, target %d' % (current_position, target_position))\n break\n time.sleep(0.1)\n\n self.color_arm_stop()\n self.color_arm.run_position_limited(position_sp=target_position, speed_sp=50)\n time.sleep(0.1)\n\n final_position = self.turntable.position\n logger.debug('color arm final position %s' % final_position)\n\n def color_arm_middle(self):\n logger.debug('color arm middle')\n self.color_arm_reliable(-350)\n\n def color_arm_right_inner(self):\n logger.debug('color arm innter')\n self.color_arm_reliable(-240)\n\n def color_arm_right_outer(self):\n logger.debug('color arm outer')\n self.color_arm_reliable(-220)\n\n def color_arm_stop(self):\n self.color_arm.run_time_limited(time_sp=0, speed_sp=80, stop_mode=Motor.STOP_MODE.COAST)\n time.sleep(0.1)\n\n def color_arm_reset(self):\n initial_position = self.color_arm.position\n logger.debug('color arm starting position %d' % initial_position)\n self.color_arm.run_forever(speed_sp=800)\n prev_position = None\n\n while True:\n current_position = self.color_arm.position\n #logger.debug('color arm current position %d' % current_position)\n\n if prev_position and abs(current_position - prev_position) <= 10:\n logger.debug('color arm moved as far as it can go, current_position %d >= prev_position %d' % (current_position, prev_position))\n break\n time.sleep(0.1)\n prev_position = current_position\n\n self.color_arm_stop()\n final_position = self.color_arm.position\n logger.debug('color arm final position %s' % current_position)\n logger.debug('')\n\n def color_arm_away(self):\n self.color_arm_reset()\n\n def wait_for_cube(self):\n pass\n\n\n def flip_two(self):\n self.flip_one()\n self.flip_one()\n\n def flip_one():\n pass\n\n\n \"\"\"\n Color scanning methods\n \"\"\"\n def within_color_delta(self, rgb, rgb_target, delta):\n (red, green, blue) = rgb\n (red_target, green_target, blue_target) = rgb\n\n if (abs(red - red_target) <= delta and\n abs(green - green_target) <= delta and\n abs(blue- blue_target) <= delta):\n return True\n\n return False\n\n def get_rubiks_color(self, rgb, original_color):\n (red, green, blue) = rgb\n\n if self.within_color_delta(rgb, (180, 83, 30), 10):\n return 'orange'\n\n return ColorSensor.colors[original_color]\n\n def scan_side(self, side):\n\n # dwalton\n # Center position\n self.color_arm_middle()\n true_color = self.get_rubiks_color(self.color_sensor.rgb, self.color_sensor.color)\n logger.debug('side %s, center, color %s\\n' % (side, true_color))\n self.color_arm_right_outer()\n\n for x in range(8):\n self.turntable_clockwise_eighth()\n true_color = self.get_rubiks_color(self.color_sensor.rgb, self.color_sensor.color)\n logger.debug('side %s, pos %d, color %s\\n' % (side, x, true_color))\n\n \n '''\n # middle right position\n self.turntable_clockwise_eighth()\n self.color_arm_right_inner()\n logger.debug('side %s, middle right, color %s\\n' % (side, true_color))\n\n # top right position\n self.turntable_clockwise_eighth()\n self.color_arm_right_outer()\n logger.debug('side %s, top right, color %s\\n' % (side, true_color))\n\n # top middle position\n self.turntable_clockwise_eighth()\n self.color_arm_right_inner()\n logger.debug('side %s, top middle, color %s\\n' % (side, true_color))\n\n # top left position\n self.turntable_clockwise_eighth()\n self.color_arm_right_outer()\n logger.debug('side %s, top left, color %s\\n' % (side, true_color))\n\n # middle left position\n self.turntable_clockwise_eighth()\n self.color_arm_right_inner()\n logger.debug('side %s, middle left, color %s\\n' % (side, true_color))\n\n # bottom left position\n self.turntable_clockwise_eighth()\n self.color_arm_right_outer()\n logger.debug('side %s, bottom left, color %s\\n' % (side, true_color))\n\n # bottom middle position\n self.turntable_clockwise_eighth()\n self.color_arm_right_inner()\n logger.debug('side %s, bottom middle, color %s\\n' % (side, true_color))\n\n # bottom right position\n self.turntable_clockwise_eighth()\n self.color_arm_right_outer()\n logger.debug('side %s, bottom right, color %s\\n' % (side, true_color))\n\n\n # Move the color sensor out of the way of the flipper arm\n self.color_arm_away()\n\n\n for x in range(8):\n logger.debug('RDB: %s' % str(self.color_sensor.rgb));\n logger.debug('mode: %s' % self.color_sensor.mode);\n\n true_color = self.get_rubiks_color(self.color_sensor.rgb, self.color_sensor.color)\n #logger.debug('color: %d' % self.color_sensor.color);\n #logger.debug('color: %s' % ColorSensor.colors[self.color_sensor.color]);\n logger.debug('color: %s' % true_color)\n logger.info('Side %s position %d: color %s' % (side, x, 'lime'))\n logger.info('')\n self.turntable_clockwise_eighth()\n '''\n\n def scan_colors(self):\n self.color_arm_away()\n\n for side in ('U', 'L', 'D', 'R', 'F', 'B'):\n self.scan_side(side)\n break\n\n return\n self.turntable_clockwise_quarter()\n for side in ('F', 'B'):\n self.scan_side(x)\n self.flip_one()\n break\n\n def calculate_solution(self):\n pass\n\n def implement_solution(self):\n pass\n\n\nif __name__ == '__main__':\n # Logger init\n # logging.basicConfig(filename='/var/log/r2d2.log',\n logging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(levelname)7s: %(message)s')\n\n # Color the errors and warnings in red\n logging.addLevelName(logging.ERROR, \"\\033[91m%s\\033[0m\" % logging.getLevelName(logging.ERROR))\n logging.addLevelName(logging.WARNING, \"\\033[91m%s\\033[0m\" % logging.getLevelName(logging.WARNING))\n\n gw = CubeSolver3x3()\n","sub_path":"ev3cube.py","file_name":"ev3cube.py","file_ext":"py","file_size_in_byte":11264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"7208852","text":"#!/usr/bin/env python3\nimport pandas as pd \nimport matplotlib.pyplot as plt\nfrom datetime import timedelta\nfrom datetime import datetime\nfrom scipy.optimize import linprog\nimport random\n\n# import scipy as scipy\n# print (scipy.version.version)\n# exit()\n\n# # test a small OP\n# c = [1, 2]\n# # xbounds = (-1, 10)\n# # ybounds = (-10, 3)\n# xbounds = (-1, None)\n# ybounds = (-10, 3)\n# bounds = (xbounds, ybounds)\n# A_ub = [[-4, -3], [1, 0]]\n# b_ub = [30, 10]\n# res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options={\"disp\": True})\n# print (res)\n# exit()\n\n\n# define constants\nTIME_SLOT = 10 # in minutes\n#HORIZON = 20 # in minutes, corresponds to 24 hours\nHORIZON = 1440 # in minutes, corresponds to 24 hours\nMPC_START_TIME = '05.01.2018 00:00:00' # pandas format mm.dd.yyyy hh:mm:ss\n\n\nBOILER1_TEMP_MIN = 40 # in degree celsius\nBOILER1_TEMP_MAX = 50 # in degree celsius\n\nBOILER2_TEMP_MIN = 30 # in degree celsius\nBOILER2_TEMP_MAX = 60 # in degree celsius\n\nBOILER2_TEMP_INCOMING_WATER = 20 # in degree celsius (TODO to be verified!) Question: is it variable?\n\nBOILER1_RATED_P = 7600 # in Watts\nBOILER2_RATED_P = 7600 # in Watts\n\nBOILER1_VOLUME = 800 # in litres\nBOILER2_VOLUME = 800 # in litres\n\nBOILER1_INITIAL_TEMP = 45 # in degree celsius\nBOILER2_INITIAL_TEMP = 45 # in degree celsius\n\n\n\nno_slots = int(HORIZON / TIME_SLOT)\n\ndef get_excess_power_forecast():\n\tdf = pd.read_excel('../../data_input/Energie - 00003 - Pache.xlsx', index_col=[0], usecols=[0,1])\n\tdf['excess_power (kW) (Psolar - Pload)'] = df['Flux energie au point d\\'injection (kWh)'] * -6 # Convert the energy (kWh) to power (kW) and power convention (buy positive and sell negative)\n\tdel df['Flux energie au point d\\'injection (kWh)'] # we do not need the energy column anymore\n\n\tstart_index = df.index[df.index == MPC_START_TIME][0] # df.index returns a list\n\tend_index = start_index + timedelta(minutes = HORIZON - TIME_SLOT)\n\texcess_power_forecast_df = df.loc[start_index:end_index]\n\texcess_power_forecast_df.plot.line(y='excess_power (kW) (Psolar - Pload)')\n\tplt.savefig('../../figs_output/power_profile_at_connection_point_05mai2018.pdf')\n\treturn excess_power_forecast_df\n\n\ndef get_hot_water_usage_forecast():\n\tdf = pd.read_excel('../../data_input/hot_water_consumption_artificial_profile_10min_granularity.xlsx', index_col=[0], usecols=[0,1])\n\tdf.plot.line(y='Hot water usage (litres)')\n\tplt.savefig('../../figs_output/hot_water_usage_profile_24hrs.pdf')\n\treturn df\n\t\n\ndef get_energy_sell_price():\n\tdf = pd.read_excel('../../data_input/energy_sell_price_10min_granularity.xlsx', index_col=[0], usecols=[0,1])\n\tdf.plot.line(y='Sell Price (CHF / kWh)')\n\tplt.savefig('../../figs_output/energy_sell_price_24hrs.pdf')\n\treturn df\n\n\ndef get_energy_buy_price():\n\tdf = pd.read_excel('../../data_input/energy_buy_price_10min_granularity.xlsx', index_col=[0], usecols=[0,1])\n\tdf.plot.line(y='Buy Price (CHF / kWh)')\n\tplt.savefig('../../figs_output/energy_buy_price_24hrs.pdf')\n\treturn df\n\n\ndef main():\n\t# Get disturbance forecasts\n\t# 1. Get excess solar power forecasts\n\texcess_power_forecast_df = get_excess_power_forecast()\n\n\t# 2. Get hot water consumption volume forecast\n\thot_water_usage_forecast_df = get_hot_water_usage_forecast()\n\t\n\t# Get energy sell price\n\tenergy_sell_price_df = get_energy_sell_price()\n\t# Get energy buy price\n\tenergy_buy_price_df = get_energy_buy_price()\n\t\n\tconcated_df = pd.concat([excess_power_forecast_df, hot_water_usage_forecast_df, energy_sell_price_df, energy_buy_price_df], axis=1)\n\t# concated_df.plot.line(y=['power_pcc (kW) (+ import)', 'Hot water usage (litres)'], secondary_y=['Sell Price (CHF / kWh)', 'Buy Price (CHF / kWh)'])\n\tconcated_df.plot.line(secondary_y=['Sell Price (CHF / kWh)', 'Buy Price (CHF / kWh)'])\n\tplt.savefig('../../figs_output/disturbances_and_energy_prices.pdf')\n\t#plt.show()\n\t#exit()\n\n\n\t############ Set up the optimisation problem\n\tcurrent_time = datetime.strptime(MPC_START_TIME, \"%m.%d.%Y %H:%M:%S\")\n\tindices = []\n\tindices.append(current_time)\n\n\tNO_CTRL_VARS_PS = 6 # control (decision) variables are Epsilon, Pg, Pb1, Pb2, Tb1, Tb2 for each time slot\n\tno_ctrl_vars = NO_CTRL_VARS_PS * no_slots\n\tc = []\n\tbounds = [] # before passing to the OP, we'll convert it to a tuple (currently list because of frequent append operations)\n\tA_eq = []\n\tb_eq = []\n\tA_ub = []\n\tb_ub = []\n\tfor x in range(no_slots):\n\t\t# 1. Setup the objective function\n\t\tc.append(1) # variables are Epsilon, Pg, Pb1, Pb2, Tb1, Tb2 for each time slot\n\t\tc.extend([0, 0, 0, 0, 0]) \n\t\t#print (c)\n\t\t\n\t\t# 2. Setup the bounds for the control variables\n\t\tepsilon_bounds = (None, None)\n\t\tpsg_bounds = (None, None)\n\t\tpb1_bounds = (0, BOILER1_RATED_P)\n\t\tpb2_bounds = (0, BOILER2_RATED_P)\n\t\ttb1_bounds = (BOILER1_TEMP_MIN, BOILER1_TEMP_MAX)\n\t\ttb2_bounds = (BOILER2_TEMP_MIN, BOILER2_TEMP_MAX)\n\t\tbounds_one_slot = [epsilon_bounds, psg_bounds, pb1_bounds, pb2_bounds, tb1_bounds, tb2_bounds]\n\t\tbounds.extend(bounds_one_slot)\n\t\t\n\n\t\t# 3. Setup equality constraints\n\t\texcess_power_forecast_index = excess_power_forecast_df.index[excess_power_forecast_df.index == current_time][0] # df.index returns a list\n\t\texcess_power_forecast = excess_power_forecast_df.loc[excess_power_forecast_index]\n\t\t#excess_power_forecast[0] = 1 # for testing purposes\n\t\t# if random.uniform(0,1) <= 0.5:\n\t\t# \texcess_power_forecast[0] = -random.uniform(0,1) * 50000\n\t\t# else:\n\t\t# \texcess_power_forecast[0] = random.uniform(0,1) * 50000\n\t\t#print (excess_power_forecast[0])\n\t\t# power balance constraint\n\t\trow = [0] * no_ctrl_vars\n\t\trow[x * NO_CTRL_VARS_PS + 1] = -1 # variables are Epsilon, Pg, Pb1, Pb2, Tb1, Tb2 for each time slot\n\t\trow[x * NO_CTRL_VARS_PS + 2] = 1\n\t\trow[x * NO_CTRL_VARS_PS + 3] = 1\n\t\t#print (row)\n\t\tA_eq.append(row)\n\t\t#print (A_eq)\n\t\tb_eq.append(excess_power_forecast[0] * 1000) # converting kW to Watts and excess power is defined as Psolar - Pload (both positive values)\n\t\t#print (b_eq)\n\n\t\t# Boiler 1 and 2 are connected in series. The newV is the same for both boilers in this case.\n\t\thot_water_usage_forecast_index = hot_water_usage_forecast_df.index[hot_water_usage_forecast_df.index == current_time][0] # df.index returns a list\n\t\thot_water_usage_forecast = hot_water_usage_forecast_df.loc[hot_water_usage_forecast_index]\n\t\t#newV = 0 # for testing purposes\n\t\t#print (hot_water_usage_forecast[0])\n\t\tnewV = hot_water_usage_forecast[0]\n\t\tAb1 = 1 - newV / BOILER1_VOLUME\n\t\tAb2 = 1 - newV / BOILER2_VOLUME\n\t\tCb1 = newV / BOILER1_VOLUME\n\t\tDb2 = Cb1 * BOILER2_TEMP_INCOMING_WATER\n\t\t# the specific heat capacity of water (C) is 4.186 joule or watt-second per gram per degree celsius\n\t\t# the density of water is 997 grams / litre\n\t\tBb1 = (TIME_SLOT * 60) / (4.186 * 997 * BOILER1_VOLUME) # time slots are converted to seconds. \n\t\tBb2 = (TIME_SLOT * 60) / (4.186 * 997 * BOILER2_VOLUME) # time slots are converted to seconds. \n\n\t\t# variables are Epsilon, Pg, Pb1, Pb2, Tb1, Tb2 for each time slot\n\t\trow = [0] * no_ctrl_vars\n\t\trow[x * NO_CTRL_VARS_PS + 4] = 1\n\t\trow[x * NO_CTRL_VARS_PS + 2] = -Bb1\n\t\tif x == 0:\n\t\t\t#print (row)\n\t\t\tA_eq.append(row)\n\t\t\tb_eq.append(Ab1 * BOILER1_INITIAL_TEMP + Cb1 * BOILER2_INITIAL_TEMP)\n\n\t\t\trow = [0] * no_ctrl_vars\n\t\t\trow[x * NO_CTRL_VARS_PS + 5] = 1\n\t\t\trow[x * NO_CTRL_VARS_PS + 3] = -Bb2\n\t\t\t#print (row)\n\t\t\tA_eq.append(row)\n\t\t\t#print (A_ub)\n\t\t\tb_eq.append(Ab2 * BOILER2_INITIAL_TEMP + Db2)\n\t\telse:# variables are Epsilon, Pg, Pb1, Pb2, Tb1, Tb2\n\t\t\trow[x * NO_CTRL_VARS_PS - 2] = -Ab1\n\t\t\trow[x * NO_CTRL_VARS_PS - 1] = -Cb1\n\t\t\tA_eq.append(row)\n\t\t\tb_eq.append(0)\n\n\t\t\trow = [0] * no_ctrl_vars\n\t\t\trow[x * NO_CTRL_VARS_PS + 5] = 1\n\t\t\trow[x * NO_CTRL_VARS_PS + 3] = -Bb2\n\t\t\trow[x * NO_CTRL_VARS_PS - 1] = -Ab2\n\t\t\tA_eq.append(row)\n\t\t\tb_eq.append(Db2)\n\n\t\t# 4. Setup inequality constraints\n\t\tsell_index = energy_sell_price_df.index[energy_sell_price_df.index == current_time][0] # dataframe.index returns a list\n\t\tbuy_index = energy_buy_price_df.index[energy_buy_price_df.index == current_time][0] # df.index returns a list\n\t\tcurrent_sell_price = energy_sell_price_df.loc[sell_index] # per unit energy price\n\t\tcurrent_buy_price = energy_buy_price_df.loc[buy_index] # per unit (kWh) energy price\n\t\t#print (current_buy_price[0])\n\t\t#print (current_sell_price[0])\n\t\trow = [0] * no_ctrl_vars\n\t\trow[x * NO_CTRL_VARS_PS] = -1\n\t\trow[x * NO_CTRL_VARS_PS + 1] = current_buy_price[0] / (6 * 1000) # converting it to price per watt-10minutes\n\t\tA_ub.append(row)\n\t\tb_ub.append(0)\n\n\t\trow = [0] * no_ctrl_vars\n\t\trow[x * NO_CTRL_VARS_PS] = -1\n\t\trow[x * NO_CTRL_VARS_PS + 1] = current_sell_price[0] / (6 * 1000) # converting it to price per watt-second\n\t\tA_ub.append(row)\n\t\tb_ub.append(0)\n\n\t\tcurrent_time = current_time + timedelta(minutes = TIME_SLOT)\n\t\tindices.append(current_time)\n\t\t# if x == 1:\n\t\t# \tprint (\"c is\")\n\t\t# \tprint (c)\n\t\t# \tprint (\"bounds are\")\n\t\t# \tprint (bounds)\n\t\t# \tprint (\"A_eq is\")\n\t\t# \tprint (A_eq)\n\t\t# \tprint (\"b_eq is\")\n\t\t# \tprint (b_eq)\n\t\t# \texit()\n\tbounds = tuple(bounds)\n\n\t# print (\"c is\")\n\t# print (c)\n\t# print (\"bounds are\")\n\t# print (bounds)\n\t# print (\"A_eq is\")\n\t# print (A_eq)\n\t# print (\"b_eq is\")\n\t# print (b_eq)\n\t# print (\"A_ub is\")\n\t# print (A_ub)\n\t# print (\"b_ub is\")\n\t# print (b_ub)\n\n\t#res = linprog(c, A_eq=A_eq, b_eq=b_eq, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method='interior-point', options={\"disp\": True, \"maxiter\": 50000, 'tol': 1e-6})\n\tres = linprog(c, A_eq=A_eq, b_eq=b_eq, A_ub=A_ub, b_ub=b_ub, bounds=bounds, options={\"disp\": True, \"maxiter\": 50000, 'tol': 1e-6})\n\tprint (res)\n\n\tpower_pcc = []\n\tpower_boiler1 = []\n\tpower_boiler2 = []\n\ttemp_boiler1 = []\n\ttemp_boiler2 = []\n\t# for the first time slot, the temperature values are the intial ones\n\ttemp_boiler1.append(BOILER1_INITIAL_TEMP)\n\ttemp_boiler2.append(BOILER2_INITIAL_TEMP)\n\tfor x in range(no_slots):\n\t\tpower_pcc.append(-res.x[x * NO_CTRL_VARS_PS + 1])\n\t\tpower_boiler1.append(-res.x[x * NO_CTRL_VARS_PS + 2])\n\t\tpower_boiler2.append(-res.x[x * NO_CTRL_VARS_PS + 3])\n\t\ttemp_boiler1.append(res.x[x * NO_CTRL_VARS_PS + 4])\n\t\ttemp_boiler2.append(res.x[x * NO_CTRL_VARS_PS + 5])\n\n\t# for the last time slot, we do not have these values\n\tpower_pcc.append(None)\n\tpower_boiler1.append(None)\n\tpower_boiler2.append(None)\n\n\tresults = {'power_pcc (Watts) (+ import)': power_pcc, 'power_boiler1 (Watts)': power_boiler1, 'power_boiler2 (Watts)': power_boiler2, 'temp_boiler1 (°C)': temp_boiler1, 'temp_boiler2 (°C)': temp_boiler2}\n\tresults_df = pd.DataFrame(data=results, index=indices)\n\tresults_df.plot.line(secondary_y=['temp_boiler1 (°C)', 'temp_boiler2 (°C)'])\n\tplt.savefig('../../figs_output/results.pdf')\n\t#plt.show()\n\n\n\n\n\nif __name__ == \"__main__\":\n\tmain()\n\n\n\n","sub_path":"mpc_jagdish/trip_planner/scripts/python/mpc.py","file_name":"mpc.py","file_ext":"py","file_size_in_byte":10531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"394124585","text":"#! /usr/bin/env python\n# -*- coding=utf8 -*-\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\n\nclass NextItemModel(object):\n\n def __init__(self,\n input_ids,\n labels,\n num_classes,\n embedding_dim,\n dilations,\n kernel_size,\n training):\n self.input_ids = input_ids\n self.labels = labels\n self.num_classes = num_classes\n self.embedding_dim = embedding_dim\n self.dilations = dilations\n self.kernel_size = kernel_size\n self.training = training\n\n self.build_graph(training=training)\n\n def build_graph(self, training=True):\n self.embeddings = self.get_embeddings()\n inputs = self.mask_padding_embedding_lookup(\n self.embeddings, self.embedding_dim, self.input_ids)\n for layer_id, dilation in enumerate(self.dilations):\n inputs = self.residual_block(\n inputs, dilation, layer_id, self.embedding_dim,\n self.kernel_size, causal=True, training=training)\n self.output_3d = inputs\n self.output_2d = tf.reshape(inputs, [-1, self.embedding_dim])\n tf.logging.info(\" output_3d = %s\", self.output_3d)\n tf.logging.info(\" output_2d = %s\", self.output_2d)\n self.nce_weights, self.nce_biases = self.get_nce_weights_and_biases()\n\n def get_embeddings(self):\n \"\"\"Get embeddings variables.\"\"\"\n\n dim = self.embedding_dim\n init_width = 1.0 / dim\n with tf.variable_scope(\"embeddings_variable\", reuse=tf.AUTO_REUSE):\n embeddings = tf.get_variable(\n \"embeddings\", initializer=tf.random_uniform(\n [self.num_classes, dim], -init_width, init_width))\n return embeddings\n\n def get_nce_weights_and_biases(self):\n \"\"\"Get nce weights and biases variables.\"\"\"\n\n with tf.variable_scope(\"nce_layer_variables\", reuse=tf.AUTO_REUSE):\n nce_weights = tf.get_variable(\n 'nce_weights',\n initializer=tf.truncated_normal(\n [self.num_classes, self.embedding_dim], 0.0, 0.01))\n nce_biases = tf.get_variable(\n 'nce_biases',\n initializer=tf.zeros([self.num_classes]))\n return nce_weights, nce_biases\n\n def residual_block(self, x, dilation, layer_id, channels,\n kernel_size, causal=True, training=True):\n block_name = \"res_{}_{}\".format(layer_id, dilation)\n tf.logging.info(\"build block %s ...\", block_name)\n with tf.variable_scope(block_name, reuse=tf.AUTO_REUSE):\n y = self.conv1d(x, channels, dilation, kernel_size,\n causal=causal, name=\"dilated_conv1\")\n tf.logging.info(y)\n y = self.layer_norm(y, name=\"layer_norm1\", trainable=training)\n tf.logging.info(y)\n y = tf.nn.relu(y)\n tf.logging.info(y)\n y = self.conv1d(y, channels, 2*dilation, kernel_size,\n causal=causal, name=\"dilated_conv2\")\n tf.logging.info(y)\n y = self.layer_norm(y, name=\"layer_norm2\", trainable=training)\n tf.logging.info(y)\n y = tf.nn.relu(y)\n tf.logging.info(y)\n y += x\n tf.logging.info(y)\n return y\n\n def conv1d(self, x, channels, dilation=1, kernel_size=1, causal=False,\n name='conv1d'):\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n weight = tf.get_variable(\n 'weight',\n [1, kernel_size, x.get_shape()[-1], channels],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n bias = tf.get_variable(\n 'bias',\n [channels],\n initializer=tf.constant_initializer(0.0))\n\n if causal:\n # see paper fig.4, mask implemented by padding\n tf.logging.info('x = %s', x)\n padding = [[0, 0], [(kernel_size - 1) * dilation, 0], [0, 0]]\n padded = tf.pad(x, padding)\n tf.logging.info('padded = %s', padded)\n input_expanded = tf.expand_dims(padded, axis=1)\n out = tf.nn.atrous_conv2d(input_expanded, weight,\n rate=dilation, padding='VALID')\n out += bias\n else:\n input_expanded = tf.expand_dims(x, axis=1)\n out = tf.nn.conv2d(input_expanded, weight,\n strides=[1, 1, 1, 1], padding=\"SAME\")\n out += bias\n\n return tf.squeeze(out, [1])\n\n def layer_norm(self, x, name, epsilon=1e-8, trainable=True):\n with tf.variable_scope(name, reuse=tf.AUTO_REUSE):\n shape = x.get_shape()\n beta = tf.get_variable(\n 'beta', [int(shape[-1])],\n initializer=tf.constant_initializer(0),\n trainable=trainable)\n gamma = tf.get_variable(\n 'gamma', [int(shape[-1])],\n initializer=tf.constant_initializer(1), trainable=trainable)\n mean, variance = tf.nn.moments(x, axes=[len(shape) - 1],\n keep_dims=True)\n x = (x - mean) / tf.sqrt(variance + epsilon)\n return gamma * x + beta\n\n def mask_padding_embedding_lookup(self, embeddings, embedding_dim, input):\n \"\"\" mask padding tf.nn.embedding_lookup.\n\n ref(@ay27): https://github.com/tensorflow/tensorflow/issues/2373\n \"\"\"\n\n mask_padding_zero_op = tf.scatter_update(\n embeddings, 0, tf.zeros([embedding_dim], dtype=tf.float32),\n name=\"mask_padding_zero_op\")\n with tf.control_dependencies([mask_padding_zero_op]):\n output = tf.nn.embedding_lookup(\n embeddings, tf.cast(input, tf.int32, name=\"lookup_idx_cast\"),\n name=\"embedding_lookup\")\n return output\n","sub_path":"modeling.py","file_name":"modeling.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"321052085","text":"# Construa um algoritmo que receba trinta números e mostre a soma total dos números recebidos.\n\ncounter = 1\nnumtotal=int(0)\nnum1=int\n\nwhile counter < 31:\n\tprint(\"escreva o\",counter,\"º valor.\")\n\tnum1 = input()\n\tnum1=int(num1)\n\tnumtotal = num1 + numtotal\n\tcounter += 1\n\nprint(\"A soma total é:\",numtotal)\t","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"361502327","text":"# encoding: utf8\n\nimport logging\nimport sys\nimport traceback\n\nimport clang.cindex as clidx\n\nfrom genutil import *\n\n\n# 类型转换规则\n# 原始类型指针、引用\n# 原始类型非指针、非引用\n# char*类型\n# qt类型指针,引用\n# qt类型非指针,非引用\n\n# 还需要分返回值的类型\n\n\n# for python2 base class need to object\nclass TypeConvertContext(object):\n def __init__(self):\n self.orig_type = None\n self.can_type = None\n self.convable_type = None\n self.pointee_type = None\n self.pointer_level = 0\n self.const = False\n\n self.orig_type_name = ''\n self.can_type_name = ''\n self.convable_type_name = ''\n\n self.cursor = None\n return\n\n\nclass TypeConv(object):\n tymap = {}\n\n def __init__(self):\n self.gutil = GenUtil()\n return\n\n # 去掉const, typedef, *, &, &&的类型,以及unexposed类型\n def TypeToCanonical(self, cxxtype):\n cxxtype = cxxtype.get_canonical() # 这个一般不管用\n cxxtype.is_const_qualified() # 这个函数也不管用\n\n if cxxtype.kind == clidx.TypeKind.POINTER or \\\n cxxtype.kind == clidx.TypeKind.LVALUEREFERENCE or \\\n cxxtype.kind == clidx.TypeKind.RVALUEREFERENCE:\n non_pointer_type = cxxtype.get_pointee()\n return self.TypeToCanonical(non_pointer_type)\n\n if cxxtype.kind == clidx.TypeKind.TYPEDEF:\n under_type = cxxtype.get_declaration().underlying_typedef_type\n return self.TypeToCanonical(under_type)\n\n return cxxtype\n\n # 这个好像没什么意义啊,只处理了typedef\n def TypeToConvertable(self, cxxtype):\n if cxxtype.kind == clidx.TypeKind.TYPEDEF:\n under_type = cxxtype.get_declaration().underlying_typedef_type\n return self.TypeToConvertable(under_type)\n return cxxtype\n\n # 与TypeToCanonical不同,不解析指针\n # 不能失真的转换\n def TypeToActual(self, cxxtype):\n # cxxtype = cxxtype.get_canonical() # 这个一般不管用\n cxxtype.is_const_qualified() # 这个函数也不管用\n\n if cxxtype.kind == clidx.TypeKind.LVALUEREFERENCE:\n under_type = cxxtype.get_pointee()\n nty = self.TypeToActual(under_type)\n return nty\n\n if cxxtype.kind == clidx.TypeKind.RVALUEREFERENCE:\n under_type = cxxtype.get_pointee()\n nty = self.TypeToActual(under_type)\n return nty\n\n if cxxtype.kind == clidx.TypeKind.TYPEDEF:\n under_type = cxxtype.get_declaration().underlying_typedef_type\n nty = self.TypeToActual(under_type)\n return nty\n\n # 原来UNEXPOSED 就是编译时常见的未定义的 类型\n # TODO 查找一下哪些UNEXPOSED的\n if cxxtype.kind == clidx.TypeKind.UNEXPOSED:\n under_type = cxxtype.get_declaration().type\n nty = self.TypeToActual(under_type)\n return nty\n\n # 去掉const的方式\n if cxxtype.is_const_qualified() and cxxtype.kind == clidx.TypeKind.RECORD:\n nty = cxxtype.get_declaration().type\n return nty\n\n return cxxtype\n\n def TypeCanName(self, cxxtype):\n canty = self.TypeToCanonical(cxxtype)\n if canty.kind == clidx.TypeKind.FUNCTIONPROTO:\n # print(444, \"function proto:\", canty.spelling)\n # exit(0)\n pass\n canname = canty.spelling\n if self.TypeIsConst(canty): canname = self.TypeTrimConst(canty)\n if self.TypeIsVolatile(canty): canname = self.TypeTrimConst(canty)\n canname = canname.replace('unsigned ', 'u')\n return canname\n\n def TypeIsConst(self, cxxtype):\n cantype = self.TypeToCanonical(cxxtype)\n ret1 = cantype.spelling.startswith('const ') or cantype.spelling.startswith('const_')\n ret2 = cantype.is_const_qualified()\n return ret1 or ret2\n\n def TypeIsVolatile(self, cxxtype):\n return cxxtype.spelling.startswith('volatile ')\n\n def TypeTrimConst(self, cxxtype):\n tysegs = cxxtype.spelling.split(' ')\n if 'const' in tysegs: tysegs.remove('const')\n if 'volatile' in tysegs: tysegs.remove('volatile')\n return ' '.join(tysegs)\n\n def TypeNameTrimConst(self, tyname):\n tysegs = tyname.split(' ')\n if 'const' in tysegs: tysegs.remove('const')\n if 'volatile' in tysegs: tysegs.remove('volatile')\n return ' '.join(tysegs)\n\n def IsCharType(self, tyname):\n if 'char' in tyname: return True\n if 'string' in tyname: return True # for std::string, std::wstring\n return False\n\n def IsPointer(self, cxxtype):\n if cxxtype.kind == clidx.TypeKind.POINTER or \\\n cxxtype.kind == clidx.TypeKind.LVALUEREFERENCE or \\\n cxxtype.kind == clidx.TypeKind.RVALUEREFERENCE:\n return True\n return False\n\n def ArrayDim(self, cxxtype):\n name = cxxtype.spelling\n return name.count('*') + name.count('[')\n\n def createContext(self, cxxtype, cursor):\n ctx = TypeConvertContext()\n ctx.orig_type = cxxtype\n ctx.convable_type = self.TypeToConvertable(cxxtype)\n ctx.can_type = self.TypeToCanonical(cxxtype)\n ctx.const = self.TypeIsConst(cxxtype) or self.TypeIsConst(ctx.convable_type)\n\n ctx.orig_type_name = ctx.orig_type.spelling\n ctx.can_type_name = ctx.can_type.spelling\n ctx.convable_type_name = ctx.convable_type.spelling\n\n if ctx.const: ctx.can_type_name = self.TypeNameTrimConst(ctx.can_type_name)\n if self.TypeIsVolatile(ctx.can_type):\n ctx.can_type_name = self.TypeNameTrimConst(ctx.can_type_name)\n\n ctx.cursor = cursor\n return ctx\n\n def dumpContext(self, ctx, exit_ = True):\n tb = traceback.extract_stack()\n # print(tb, len(tb))\n lno = tb[len(tb) - 2][1]\n fn = tb[len(tb) - 2 ][2]\n posig = '%s:%s' % (fn, lno)\n\n print(posig, ctx.orig_type.spelling, ctx.orig_type.kind, ctx.orig_type_name, \"\\n\",\n ctx.convable_type.kind, ctx.convable_type_name, \"cva<-\\n->can\",\n ctx.can_type.kind, ctx.can_type_name,\n 'const:', ctx.const, ctx.pointer_level, ctx.cursor.spelling, ctx.cursor.location)\n\n tdef = ctx.orig_type.get_declaration()\n if tdef is not None:\n print(tdef.kind, tdef.location, tdef.type.kind)\n if exit_: raise 'dumpctx traced.'\n return\n\n pass\n\n\nclass TypeConvForRust(TypeConv):\n tymap = {\n 'bool': ['i8', 'c_char'], 'int': ['i32', 'c_int'], 'uint': ['u32', 'c_uint'],\n 'unsigned int': ['u32', 'c_uint'],\n # 'long': ['i32', 'c_long'], # wtf, 这个32位系统和64位系统不一样怎么办\n 'long': ['i64', 'c_long'], # wtf, 这个32位系统和64位系统不一样怎么办\n 'unsigned long': ['u64', 'c_ulong'],\n 'long long': ['i64', 'c_longlong'], 'unsigned long long': ['u64', 'c_ulonglong'],\n 'short': ['i16', 'c_short'], 'unsigned short': ['u16', 'c_ushort'],\n 'float': ['f32', 'c_float'], 'double': ['f64', 'c_double'],\n 'char': ['i8', 'c_char'], 'unsigned char': ['u8', 'c_uchar'],\n }\n\n def __init__(self):\n super(TypeConvForRust, self).__init__()\n return\n\n # @param cxxtype clidx.Type\n # @return str\n # @return None 返回值为空,无返回值,不处理返回值\n def Type2RustArg(self, cxxtype):\n\n return\n\n # @param cxxtype clidx.Type\n # @return str\n # @return None 返回值为空,无返回值,不处理返回值\n def Type2RustRet(self, cxxtype, cursor):\n ctx = self.createContext(cxxtype, cursor)\n\n if ctx.convable_type.kind == clidx.TypeKind.POINTER:\n return self.Type2RustRetPointer(ctx)\n\n if ctx.convable_type.kind == clidx.TypeKind.LVALUEREFERENCE:\n return self.Type2RustRetLVRef(ctx)\n if ctx.convable_type.kind == clidx.TypeKind.RVALUEREFERENCE:\n return self.Type2RustRetLVRef(ctx)\n\n if ctx.convable_type.kind == clidx.TypeKind.VOID:\n return '()'\n\n if ctx.convable_type.kind == clidx.TypeKind.RECORD:\n return self.Type2RustRetRecord(ctx)\n\n if ctx.convable_type.kind == clidx.TypeKind.UNEXPOSED:\n nty = self.TypeToActual(ctx.convable_type)\n if nty.kind != clidx.TypeKind.UNEXPOSED: # 防止死循环\n return self.Type2RustRet(nty, cursor)\n print(ctx.can_type_name, ctx.orig_type_name)\n return '(/*unexposed %s */)' % (ctx.can_type_name)\n\n if ctx.convable_type.kind == clidx.TypeKind.ENUM:\n return 'i32'\n\n # 原始类型值类型\n if ctx.convable_type_name in TypeConvForRust.tymap:\n return self.Type2RustRetPrimitive(ctx)\n\n self.dumpContext(ctx)\n return ctx.orig_type.spelling\n\n # @param cxxtype clidx.Type\n # @return str\n def Type2ExtArg(self, cxxtype):\n return\n\n def Type2ExtRet(self, cxxtype):\n return\n\n def Type2RustRetFunctionProto(self, ctx):\n rety = '*mut c_void'\n rety = ctx.orig_type_name\n return rety\n\n def Type2RustRetPointer(self, ctx):\n ctx.pointer_level += 1\n pointee_type = ctx.convable_type.get_pointee()\n if pointee_type.kind == clidx.TypeKind.POINTER:\n ctx.pointer_level += 1\n pointee_type2 = pointee_type.get_pointee()\n if pointee_type2.kind == clidx.TypeKind.POINTER:\n ctx.pointer_level += 1\n if ctx.pointer_level > 2:\n glog.debug(\"\")\n print('wtf, two many pointer level:' + str(ctx.pointer_level))\n exit(0)\n\n if ctx.can_type.kind == clidx.TypeKind.FUNCTIONPROTO:\n return self.Type2RustRetFunctionProto(ctx)\n\n if ctx.can_type.kind == clidx.TypeKind.RECORD:\n return ctx.can_type_name\n if ctx.can_type.kind == clidx.TypeKind.VOID:\n return '*mut c_void'\n\n can_name = ctx.can_type_name\n if ctx.const: can_name = self.TypeNameTrimConst(can_name)\n if can_name in TypeConvForRust.tymap:\n can_rsty = TypeConvForRust.tymap[can_name][0]\n if ctx.pointer_level == 1:\n if self.IsCharType(can_name): rety = 'String'\n else: rety = '*mut %s' % (can_rsty)\n elif ctx.pointer_level == 2:\n if self.IsCharType(can_name): rety = 'Vec'\n else: rety = '*mut *mut %s' & (can_rsty)\n else: raise('not possible')\n return rety\n else:\n glog.debug(\"\");\n print(678, 'wtf, type not in tymap:', can_name, ctx.orig_type_name, ctx.orig_type.spelling,\n ctx.cursor.spelling, ctx.cursor.kind, ctx.cursor.semantic_parent.spelling)\n self.dumpContext(ctx)\n\n raise('not possible')\n return\n\n def Type2RustRetLVRef(self, ctx):\n # self.dumpContext(ctx)\n ctx.pointer_level += 1\n pointee_type = ctx.convable_type.get_pointee()\n # print(pointee_type.kind, pointee_type.spelling, ctx.can_type_name)\n\n if ctx.can_type.kind == clidx.TypeKind.RECORD:\n return ctx.can_type_name\n\n can_name = ctx.can_type_name\n if ctx.const: can_name = self.TypeNameTrimConst(can_name)\n if can_name in TypeConvForRust.tymap:\n can_rsty = TypeConvForRust.tymap[can_name][0]\n if self.IsCharType(can_name): rety = 'String'\n else: rety = '%s' % (can_rsty)\n return rety\n else:\n glog.debug(\"\");\n print(678, 'wtf, type not in tymap:', can_name, ctx.orig_type_name, ctx.orig_type.spelling,\n ctx.cursor.spelling, ctx.cursor.kind, ctx.cursor.semantic_parent.spelling)\n self.dumpContext(ctx)\n\n self.dumpContext(ctx)\n raise('not possible')\n\n return\n\n def Type2RustRetPrimitive(self, ctx):\n rety = TypeConvForRust.tymap[ctx.can_type_name][0]\n return rety\n\n def Type2RustRetRecord(self, ctx):\n rety = ctx.can_type_name\n return rety\n\n # TODO, like QList\n def Type2RustRetUnexposed(self, ctx):\n rety = ctx.can_type_name\n return rety\n\n # @param cxxtype clidx.Type\n def TypeCXX2Rust(self, cxxtype, cursor, inty=False):\n # TODO c++ char => rust char\n raw_type_map = TypeConvForRust.tymap\n ctx = self.createContext(cxxtype, cursor)\n\n def is_const(ty): return ty.spelling.startswith('const ')\n\n can_type = self.TypeToCanonical(cxxtype)\n can_name = self.TypeCanName(can_type)\n can_name = ctx.can_type_name\n\n if cxxtype.kind == clidx.TypeKind.FUNCTIONPROTO:\n # TODO\n self.dumpContext(ctx)\n\n mut_or_no = 'mut'\n if is_const(cxxtype): mut_or_no = ''\n\n if cxxtype.kind == clidx.TypeKind.LVALUEREFERENCE:\n # TODO 为什么std::string &的can_type_name是i32呢?\n if ctx.can_type_name in raw_type_map:\n if self.IsCharType(ctx.can_type_name) or self.IsCharType(ctx.convable_type_name):\n return \"&%s String\" % (mut_or_no)\n else:\n return \"&%s %s\" % (mut_or_no, raw_type_map[ctx.can_type_name][0])\n\n if cxxtype.kind == clidx.TypeKind.POINTER or \\\n cxxtype.kind == clidx.TypeKind.LVALUEREFERENCE:\n mut_or_no = 'mut'\n if is_const(cxxtype): mut_or_no = ''\n if 'wstring' in ctx.can_type_name:\n self.dumpContext(ctx)\n if ctx.can_type_name in raw_type_map:\n if self.IsCharType(ctx.can_type_name) or self.IsCharType(ctx.convable_type_name):\n return \"&%s String\" % (mut_or_no)\n else:\n return \"&%s Vec<%s>\" % (mut_or_no, raw_type_map[ctx.can_type_name][0])\n\n if ctx.can_type.kind == clidx.TypeKind.RECORD:\n if inty is True: return '&' + ctx.can_type_name\n else: return ctx.can_type_name\n if ctx.can_type.kind == clidx.TypeKind.FUNCTIONPROTO:\n return ctx.cursor.spelling\n if ctx.can_type.kind == clidx.TypeKind.VOID:\n return '*mut c_void'\n #if ctx.can_type.kind == clidx.TypeKind.UCHAR:\n # return '& String'\n #if ctx.can_type.kind == clidx.TypeKind.CHAR:\n # return '& String'\n if ctx.can_type.kind == clidx.TypeKind.CHAR16:\n return '& String'\n if ctx.can_type.kind == clidx.TypeKind.CHAR32:\n return '& String'\n if ctx.can_type.kind == clidx.TypeKind.WCHAR:\n return '& String'\n if ctx.can_type.kind == clidx.TypeKind.ENUM:\n return '&mut i32'\n print(can_name, ctx.can_type.kind)\n self.dumpContext(ctx)\n\n if cxxtype.kind == clidx.TypeKind.RVALUEREFERENCE:\n return \"&mut %s\" % (cxxtype.spelling.split(' ')[0])\n\n if cxxtype.kind == clidx.TypeKind.ENUM:\n return 'i32'\n\n if cxxtype.kind in [clidx.TypeKind.BOOL,\n clidx.TypeKind.INT, clidx.TypeKind.UINT,\n clidx.TypeKind.SHORT, clidx.TypeKind.USHORT,\n clidx.TypeKind.LONG, clidx.TypeKind.ULONG,\n clidx.TypeKind.LONGLONG, clidx.TypeKind.ULONGLONG,\n clidx.TypeKind.CHAR_S,\n clidx.TypeKind.UCHAR,\n clidx.TypeKind.DOUBLE, clidx.TypeKind.FLOAT, ]:\n if ctx.can_type_name in raw_type_map:\n return '%s' % (raw_type_map[ctx.can_type_name][0])\n self.dumpContext(ctx)\n\n if cxxtype.spelling in ['uint']:\n raw_type_name = cxxtype.spelling\n if raw_type_name in raw_type_map:\n return '%s' % (raw_type_map[raw_type_name][0])\n self.dumpContext(ctx)\n\n if cxxtype.kind == clidx.TypeKind.TYPEDEF:\n under_type = cxxtype.get_declaration().underlying_typedef_type\n if under_type.kind == clidx.TypeKind.UNEXPOSED and \\\n under_type.spelling.startswith('QFlags<'):\n return 'i32'\n return self.TypeCXX2Rust(under_type, cxxtype.get_declaration())\n\n # ### UNEXPOSED\n # maybe TODO,可能是python-clang绑定功能不全啊,模板解析不出来\n if cxxtype.kind == clidx.TypeKind.UNEXPOSED:\n if ctx.can_type.kind == clidx.TypeKind.ENUM:\n return 'i32'\n if cxxtype.get_declaration() is not None:\n tdef = cxxtype.get_declaration()\n if tdef.kind == clidx.CursorKind.CLASS_DECL:\n return self.TypeCXX2Rust(tdef.type, tdef)\n if tdef.kind == clidx.CursorKind.STRUCT_DECL:\n return self.TypeCXX2Rust(tdef.type, tdef)\n\n import re\n template_exp = '([a-zA-Z]+)\\<([ a-zA-Z:]+)([\\*])?\\>'\n template_res = re.findall(template_exp, ctx.can_type_name)\n\n if ctx.can_type_name.startswith('Qt::'):\n return 'i32'\n if cxxtype.spelling == '::quintptr':\n return '*mut i32'\n if ctx.can_type_name.startswith('std::initializer_list'):\n return ctx.can_type_name.replace('std::initializer_list', 'QList')\n\n if ctx.can_type.kind == clidx.TypeKind.RECORD:\n if ctx.can_type_name.startswith('QFlags<'):\n return 'i32'\n # (QList, QAction, *)\n # (QVector, unsigned int)\n # print(template_res, template_res[0], len(template_res[0]))\n if len(template_res) == 0:\n self.dumpContext(ctx)\n if len(template_res[0]) == 2 or len(template_res[0]) == 3:\n cls = template_res[0][0].strip()\n inty = template_res[0][1].strip()\n if cls in ['QVector', 'QList']: result_cls = 'Vec'\n else: result_cls = cls\n if inty in raw_type_map: result_inty = raw_type_map[inty][0]\n else: result_inty = inty\n return('%s<%s>' % (result_cls, result_inty))\n\n self.dumpContext(ctx)\n\n # TODO const char *const [], TypeKind.INCOMPLETEARRAY\n # 也有可能是一维INCOMPLETEARRAY, 所以还要考虑维度\n if cxxtype.kind == clidx.TypeKind.INCOMPLETEARRAY or \\\n cxxtype.kind == clidx.TypeKind.CONSTANTARRAY:\n pointee_type = can_type.get_pointee() # INVALID\n # print(666, can_type.kind, can_name, cxxtype.spelling)\n constq = 'mut'\n rsty = ''\n if self.TypeIsConst(cxxtype): constq = ''\n can_name = can_name.split(' ')[0]\n ext_name = can_name\n if can_name in raw_type_map: ext_name = raw_type_map[can_name][0]\n rsty = '&%s Vec<&%s %s>' % (constq, constq, ext_name)\n return rsty\n\n # TODO TypeKind.CONSTANTARRAY\n\n # ###### RECORD\n if cxxtype.kind == clidx.TypeKind.RECORD:\n return ctx.can_type_name\n\n if cxxtype.kind == clidx.TypeKind.MEMBERPOINTER:\n return '*mut u64'\n\n self.dumpContext(ctx)\n # glog.debug('just use default type name: ' + str(cxxtype.spelling) + ', ' + str(cxxtype.kind))\n return cxxtype.spelling\n\n def TypeCXX2RustExtern(self, cxxtype, cursor, ret=False):\n raw_type_map = TypeConvForRust.tymap\n ctx = self.createContext(cxxtype, cursor)\n\n def is_const(ty): return ty.spelling.startswith('const ')\n\n can_type = self.TypeToCanonical(cxxtype)\n can_name = self.TypeCanName(can_type)\n can_name = ctx.can_type_name\n\n if cxxtype.kind == clidx.TypeKind.POINTER:\n mut_or_const = '*const ' if is_const(cxxtype) else '*mut '\n mut_or_const = '*mut '\n if can_name in raw_type_map:\n return mut_or_const + '%s' % (raw_type_map[can_name][1])\n if ctx.can_type.kind == clidx.TypeKind.RECORD:\n return mut_or_const + 'c_void'\n if ctx.can_type.kind == clidx.TypeKind.VOID:\n return mut_or_const + 'c_void'\n if ctx.can_type.kind == clidx.TypeKind.FUNCTIONPROTO:\n return mut_or_const + 'c_void'\n if ctx.can_type.kind == clidx.TypeKind.CHAR32:\n return mut_or_const + 'c_char'\n if ctx.can_type.kind == clidx.TypeKind.CHAR16:\n return mut_or_const + 'c_char'\n if ctx.can_type.kind == clidx.TypeKind.WCHAR:\n return mut_or_const + 'wchar_t'\n if ctx.can_type.kind == clidx.TypeKind.ENUM:\n return mut_or_const + 'c_int'\n self.dumpContext(ctx)\n\n if cxxtype.kind == clidx.TypeKind.LVALUEREFERENCE:\n mut_or_const = '*const ' if is_const(cxxtype) else '*mut '\n mut_or_const = '*mut '\n if can_name in raw_type_map:\n if ret is True:\n return '%s' % (raw_type_map[can_name][1])\n else:\n return mut_or_const + '%s' % (raw_type_map[can_name][1])\n if ctx.can_type.kind == clidx.TypeKind.RECORD:\n return mut_or_const + 'c_void'\n if ctx.can_type.kind == clidx.TypeKind.VOID:\n return mut_or_const + 'c_void'\n if ctx.can_type.kind == clidx.TypeKind.FUNCTIONPROTO:\n return mut_or_const + 'c_void'\n if ctx.can_type.kind == clidx.TypeKind.CHAR32:\n return mut_or_const + 'c_char'\n if ctx.can_type.kind == clidx.TypeKind.CHAR16:\n return mut_or_const + 'c_char'\n if ctx.can_type.kind == clidx.TypeKind.WCHAR:\n return mut_or_const + 'wchar_t'\n if ctx.can_type.kind == clidx.TypeKind.ENUM:\n return mut_or_const + 'c_int'\n self.dumpContext(ctx)\n\n if cxxtype.kind == clidx.TypeKind.RVALUEREFERENCE:\n return '*mut %s' % ('c_void')\n\n if cxxtype.kind == clidx.TypeKind.ENUM:\n return 'c_int'\n\n if cxxtype.kind in [clidx.TypeKind.BOOL,\n clidx.TypeKind.INT, clidx.TypeKind.UINT,\n clidx.TypeKind.SHORT, clidx.TypeKind.USHORT,\n clidx.TypeKind.LONG, clidx.TypeKind.ULONG,\n clidx.TypeKind.LONGLONG, clidx.TypeKind.ULONGLONG,\n clidx.TypeKind.CHAR_S,\n clidx.TypeKind.UCHAR,\n clidx.TypeKind.DOUBLE, clidx.TypeKind.FLOAT, ]:\n if ctx.can_type_name in raw_type_map:\n return '%s' % (raw_type_map[ctx.can_type_name][1])\n self.dumpContext(ctx)\n\n if cxxtype.spelling in ['uint']:\n raw_type_name = cxxtype.spelling\n if raw_type_name in raw_type_map:\n return '%s' % (raw_type_map[raw_type_name][1])\n else:\n return '%s' % (raw_type_name)\n\n if cxxtype.kind == clidx.TypeKind.TYPEDEF:\n under_type = cxxtype.get_declaration().underlying_typedef_type\n if under_type.kind == clidx.TypeKind.UNEXPOSED and \\\n under_type.spelling.startswith('QFlags<'):\n return 'c_int'\n return self.TypeCXX2RustExtern(under_type, cxxtype.get_declaration())\n\n # maybe TODO\n if cxxtype.kind == clidx.TypeKind.UNEXPOSED:\n if ctx.can_type.kind == clidx.TypeKind.ENUM:\n return 'c_int'\n if ctx.can_type.kind == clidx.TypeKind.UINT:\n return 'c_int'\n if cxxtype.get_declaration() is not None:\n tdef = cxxtype.get_declaration()\n if tdef.kind == clidx.CursorKind.TYPEDEF_DECL:\n return self.TypeCXX2RustExtern(tdef.type, tdef)\n if tdef.kind == clidx.CursorKind.CLASS_DECL:\n return self.TypeCXX2RustExtern(tdef.type, tdef)\n if tdef.kind == clidx.CursorKind.STRUCT_DECL:\n return self.TypeCXX2RustExtern(tdef.type, tdef)\n\n import re\n template_exp = '([a-zA-Z]+)\\<([ a-zA-Z:]+)([\\*])?\\>'\n template_res = re.findall(template_exp, ctx.can_type_name)\n\n # like QAccessible::State\n if ctx.can_type_name.startswith('Qt::') or (\n ctx.can_type_name[0] == 'Q' and '::' in ctx.can_type_name):\n return 'c_int'\n if cxxtype.spelling == '::quintptr':\n return '*mut c_uint'\n # under_type = cxxtype.get_declaration().underlying_typedef_type\n # print(777, under_type.spelling, under_type.kind)\n\n if cxxtype.spelling.startswith('std::initializer_list'):\n return ctx.can_type_name.replace('std::initializer_list', 'QList')\n\n # TODO fix\n # QPair, QMap, QHash\n # QGenericMatrix<3, 3, float>\n if ctx.can_type.kind == clidx.TypeKind.RECORD:\n if 'QPair<' in ctx.can_type_name:\n return ctx.can_type_name\n if 'QMap<' in ctx.can_type_name:\n return ctx.can_type_name\n if 'QHash<' in ctx.can_type_name:\n return ctx.can_type_name\n if 'QGenericMatrix<' in ctx.can_type_name:\n return ctx.can_type_name\n if 'QFlags<' in ctx.can_type_name:\n return ctx.can_type_name\n\n if ctx.can_type.kind == clidx.TypeKind.RECORD:\n # (QList, QAction, *)\n # (QVector, unsigned int)\n print(template_res, ctx.can_type_name)\n if len(template_res) == 0:\n self.dumpContext(ctx)\n # print(template_res, template_res[0], len(template_res[0]))\n if len(template_res[0]) == 2 or len(template_res[0]) == 3:\n cls = template_res[0][0].strip()\n inty = template_res[0][1].strip()\n if cls in ['QVector', 'QList']: result_cls = 'Vec'\n else: result_cls = cls\n if inty in raw_type_map: result_inty = raw_type_map[inty][0]\n else: result_inty = inty\n return('%s<%s>' % (result_cls, result_inty))\n\n if 'std::string' in ctx.convable_type_name:\n return ctx.convable_type_name\n if 'std::wstring' in ctx.convable_type_name:\n return ctx.convable_type_name\n if 'std::u16string' in ctx.convable_type_name:\n return ctx.convable_type_name\n if 'std::u32string' in ctx.convable_type_name:\n return ctx.convable_type_name\n\n # for template T\n if 'type-parameter-' in ctx.can_type_name:\n self.dumpContext(ctx)\n\n self.dumpContext(ctx)\n\n if cxxtype.kind == clidx.TypeKind.RECORD:\n if is_const(cxxtype):\n # return '*const %s' % ('c_void') # 不好处理,全换mut试试吧\n return '*mut %s' % ('c_void')\n else:\n return '*mut %s' % ('c_void')\n\n # TODO const char *const [], TypeKind.INCOMPLETEARRAY\n # 也有可能是一维INCOMPLETEARRAY, 所以还要考虑维度\n if cxxtype.kind == clidx.TypeKind.INCOMPLETEARRAY or \\\n cxxtype.kind == clidx.TypeKind.CONSTANTARRAY:\n pointee_type = can_type.get_pointee() # INVALID\n # print(666, can_type.kind, can_name, cxxtype.spelling)\n constq = 'mut'\n rsty = ''\n # if self.TypeIsConst(cxxtype): constq = 'const'\n can_name = can_name.split(' ')[0]\n ext_name = can_name\n if can_name in raw_type_map: ext_name = raw_type_map[can_name][1]\n rsty = '*%s *%s %s' % (constq, constq, ext_name)\n\n return rsty\n # print(666, rsty, cxxtype.spelling)\n # exit(0)\n pass\n\n if cxxtype.kind == clidx.TypeKind.VOID:\n return 'void'\n\n if cxxtype.kind == clidx.TypeKind.MEMBERPOINTER:\n return '*mut c_void'\n\n self.dumpContext(ctx)\n # print(888, 'just use default type name:', cxxtype.spelling, cxxtype.kind)\n return cxxtype.spelling\n\n @staticmethod\n def TypeCXXCanonical(cxxtype):\n\n clean_type = cxxtype.get_pointee()\n # print(444, canical_type.spelling, canical_type.spelling, canical_type.kind)\n def is_const(ty): return ty.spelling.startswith('const ')\n def trim_const(ty):\n tysegs = ty.spelling.split(' ') + ['const']\n tysegs.remove('const')\n return tysegs[0]\n if clean_type.kind == clidx.TypeKind.RECORD:\n tyname = trim_const(clean_type)\n return tyname\n return clean_type.spelling\n\n\n","sub_path":"typeconv.py","file_name":"typeconv.py","file_ext":"py","file_size_in_byte":29120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"511690522","text":"__all__ = [\"Class\", \"Schemas\", \"parse_reference_path\", \"update_schemas_with_data\"]\n\nfrom typing import TYPE_CHECKING, Dict, List, NewType, Union, cast\nfrom urllib.parse import urlparse\n\nimport attr\n\nfrom ... import Config\nfrom ... import schema as oai\nfrom ... import utils\nfrom ..errors import ParseError, PropertyError\n\nif TYPE_CHECKING: # pragma: no cover\n from .property import Property\nelse:\n Property = \"Property\"\n\n\n_ReferencePath = NewType(\"_ReferencePath\", str)\n_ClassName = NewType(\"_ClassName\", str)\n\n\ndef parse_reference_path(ref_path_raw: str) -> Union[_ReferencePath, ParseError]:\n parsed = urlparse(ref_path_raw)\n if parsed.scheme or parsed.path:\n return ParseError(detail=f\"Remote references such as {ref_path_raw} are not supported yet.\")\n return cast(_ReferencePath, parsed.fragment)\n\n\n@attr.s(auto_attribs=True, frozen=True)\nclass Class:\n \"\"\"Represents Python class which will be generated from an OpenAPI schema\"\"\"\n\n name: _ClassName\n module_name: str\n\n @staticmethod\n def from_string(*, string: str, config: Config) -> \"Class\":\n \"\"\"Get a Class from an arbitrary string\"\"\"\n class_name = string.split(\"/\")[-1] # Get rid of ref path stuff\n class_name = utils.pascal_case(class_name)\n override = config.class_overrides.get(class_name)\n\n if override is not None and override.class_name is not None:\n class_name = override.class_name\n\n if override is not None and override.module_name is not None:\n module_name = override.module_name\n else:\n module_name = utils.snake_case(class_name)\n\n return Class(name=cast(_ClassName, class_name), module_name=module_name)\n\n\n@attr.s(auto_attribs=True, frozen=True)\nclass Schemas:\n \"\"\"Structure for containing all defined, shareable, and reusable schemas (attr classes and Enums)\"\"\"\n\n classes_by_reference: Dict[_ReferencePath, Property] = attr.ib(factory=dict)\n classes_by_name: Dict[_ClassName, Property] = attr.ib(factory=dict)\n errors: List[ParseError] = attr.ib(factory=list)\n\n\ndef update_schemas_with_data(\n *, ref_path: _ReferencePath, data: oai.Schema, schemas: Schemas, config: Config\n) -> Union[Schemas, PropertyError]:\n from . import property_from_data\n\n prop: Union[PropertyError, Property]\n prop, schemas = property_from_data(\n data=data, name=ref_path, schemas=schemas, required=True, parent_name=\"\", config=config\n )\n\n if isinstance(prop, PropertyError):\n return prop\n\n schemas = attr.evolve(schemas, classes_by_reference={ref_path: prop, **schemas.classes_by_reference})\n return schemas\n","sub_path":"openapi_python_client/parser/properties/schemas.py","file_name":"schemas.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"576110274","text":"import shell\nimport os\nfrom ownLogging import *\nfrom dataclasses import dataclass\nfrom typing import *\nimport yaml\nimport utils\n\ndef getFromDicts(dicts, k, conv=lambda x: x, default=None, fail=True):\n if type(dicts) is not list:\n dicts = [dicts]\n val = None\n for d in dicts:\n if k in d:\n val = d[k]\n break\n else:\n val = default\n if val is None:\n if fail:\n raise KeyError(f'Required key {k} not defined in {dicts[0]} and any of its parents')\n else:\n return None\n try:\n return conv(val)\n except:\n raise ValueError(f'Value for key {k} in {dicts[0]} has wrong type: {val}')\n\nclass Keys:\n mainFile = 'main-file'\n testFiles = 'test-files'\n testFile = 'test-file'\n\n@dataclass\nclass Assignment:\n id: str\n points: int\n kind: str\n dicts: List[Dict]\n def parse(id, dicts):\n points = getFromDicts(dicts, 'points', int)\n kind = getFromDicts(dicts, 'kind')\n return Assignment(id, points, kind, dicts)\n def getMainFile(self, d, fail=False):\n return self.getFile(Keys.mainFile, d, fail)\n def getGradleFile(self, d, fail=False):\n return self.getFile(Keys.gradleFile, d, fail)\n def getValue(self, k, fail=True):\n val = getFromDicts(self.dicts, k, fail=False)\n if val is None and fail:\n raise ValueError(f'Key {k} must be set for assignment {self.id}')\n else:\n return val\n def getFile(self, k, d, fail=True):\n x = getFromDicts(self.dicts, k, fail=fail)\n if x is not None:\n return shell.pjoin(d, x)\n else:\n if fail:\n raise ValueError(f'Key {k} must be set for assignment {self.id}')\n else:\n return None\n def getAsList(self, k):\n x = getFromDicts(self.dicts, k, default=[])\n if type(x) == list or type(x) == tuple:\n return x\n elif x:\n return [x]\n else:\n return []\n def getAsFileList(self, d, k):\n items = self.getAsList(k)\n return [shell.pjoin(d, x) for x in items]\n def getTestFiles(self, d):\n return self.getAsFileList(d, Keys.testFiles) + self.getAsFileList(d, Keys.testFile)\n\n@dataclass\nclass Config:\n baseDir: str\n assignments: List[Assignment]\n configDict: Dict\n testDir: str\n\n def __init__(self, baseDir, configDict, assignments, testDir):\n self.assignments = assignments\n self.configDict = configDict\n self.testDir = testDir\n self.baseDir = baseDir\n self.submissionDirSuffix = '_assignsubmission_file_'\n self.submissionDirGlob = '*' + self.submissionDirSuffix\n self.submissionDirTextGlob = '*_assignsubmission_onlinetext_'\n self.feedbackZip = 'feedback.zip'\n self.lang = 'de'\n\n @staticmethod\n def parse(baseDir, configDict, ymlDict):\n assignments= []\n for k, v in ymlDict['assignments'].items():\n a = Assignment.parse(k, [v, ymlDict])\n assignments.append(a)\n testDir = ymlDict.get('test-dir', shell.pjoin(baseDir, 'tests'))\n return Config(baseDir, configDict, assignments, testDir)\n\n @property\n def gradlePath(self):\n return self.configDict.get('gradle', 'gradle')\n\n @property\n def wyppDir(self):\n return self.configDict.get('wypp', None)\n\n @property\n def spreadsheetPath(self):\n return shell.pjoin(self.baseDir, 'rating.xlsx')\n\n @property\n def ratingCsvPath(self):\n return shell.pjoin(self.baseDir, 'rating.csv')\n\n @property\n def lineCommentStart(self):\n if self.fileExt == '.py':\n return '# '\n elif self.fileExt == '.hs':\n return '-- '\n\n @property\n def editor(self):\n if os.environ.get('USER') == 'swehr':\n return 'edi' # special case\n else:\n return os.environ.get('EDITOR') or os.environ.get('VISUAL') or 'vim'\n\n @property\n def pointsTemplate(self):\n return shell.pjoin(self.baseDir, 'POINTS_template.txt')\n\n @property\n def pointsFile(self):\n return 'POINTS.txt'\n\n @property\n def commentsFile(self):\n return 'COMMENTS.txt'\n\ndef mkConfig(baseDir, configDict):\n if not shell.isdir(baseDir):\n abort('Base directory {baseDir} does not exist')\n yamlPath = shell.pjoin(baseDir, 'check.yml')\n if not shell.isFile(yamlPath):\n abort(f'Config file {yamlPath} not found')\n s = utils.readFile(yamlPath)\n ymlDict = yaml.load(s, Loader=yaml.FullLoader)\n return Config.parse(baseDir, configDict, ymlDict)\n","sub_path":"src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"480946261","text":"#!/usr/bin/env python\r\n# -*- encoding: utf-8 -*-\r\n# Created on 2018/7/27 10:42\r\n# Project:\r\n# @Author: ZQJ\r\n# @Email : zihe@yscredit.com\r\n\r\nfrom pyspider.libs.base_handler import *\r\nimport re\r\nimport json\r\nimport random\r\nimport time\r\n\r\n\r\nclass Handler(BaseHandler):\r\n schema_def = [{\"name\": \"id\", \"type\": \"string\"},\r\n {\"name\": \"_id_\", \"type\": \"string\"},\r\n {\"name\": \"ann_type\", \"type\": \"string\"},\r\n {\"name\": \"announcer\", \"type\": \"string\"},\r\n {\"name\": \"case_no\", \"type\": \"string\"},\r\n {\"name\": \"ann_content\", \"type\": \"string\"},\r\n {\"name\": \"ann_date\", \"type\": \"string\"},\r\n {\"name\": \"content_url\", \"type\": \"string\"},\r\n {\"name\": \"ann_html\", \"type\": \"string\"},\r\n {\"name\": \"pdf_url\", \"type\": \"string\"},\r\n {\"name\": \"source\", \"type\": \"string\"},\r\n {\"name\": \"defendant\", \"type\": \"string\"},\r\n ]\r\n\r\n crawl_config = {\r\n 'itag': '7.26',\r\n # 'time_out': 8000,\r\n 'proxy': 'H21WNK49K6PFSR3P:BF2B9DDE973F0C02@http-pro.abuyun.com:9010'\r\n }\r\n retry_delay = {\r\n 0: 60,\r\n 1: 60 * 1,\r\n 2: 60 * 2,\r\n 3: 60 * 3,\r\n 4: 60 * 4,\r\n 5: 60 * 5,\r\n }\r\n\r\n def __init__(self):\r\n self.UA = [\r\n \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; AcooBrowser; .NET CLR 1.1.4322; .NET CLR 2.0.50727)\",\r\n \"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)\",\r\n \"Mozilla/4.0 (compatible; MSIE 7.0; AOL 9.5; AOLBuild 4337.35; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)\",\r\n \"Mozilla/5.0 (Windows; U; MSIE 9.0; Windows NT 9.0; en-US)\",\r\n \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0)\",\r\n \"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 1.0.3705; .NET CLR 1.1.4322)\",\r\n \"Mozilla/4.0 (compatible; MSIE 7.0b; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.2; .NET CLR 3.0.04506.30)\",\r\n \"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN) AppleWebKit/523.15 (KHTML, like Gecko, Safari/419.3) Arora/0.3 (Change: 287 c9dfb30)\",\r\n \"Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6\",\r\n \"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2pre) Gecko/20070215 K-Ninja/2.1.1\",\r\n \"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9) Gecko/20080705 Firefox/3.0 Kapiko/3.0\",\r\n \"Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5\",\r\n \"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6\",\r\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11\",\r\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20\",\r\n \"Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52\",\r\n ]\r\n self.headers = {\r\n 'Accept': '*/*',\r\n 'Accept-Encoding': 'gzip, deflate',\r\n 'Accept-Language': 'zh-CN,zh;q=0.9',\r\n 'Connection': 'keep-alive',\r\n 'Content-Length': '30',\r\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\r\n 'Host': 'www.zjsfgkw.cn',\r\n 'Origin': 'http://www.zjsfgkw.cn',\r\n 'Referer': 'http://www.zjsfgkw.cn/Notice/NoticeSDList',\r\n 'User-Agent': random.choice(self.UA),\r\n 'X-Requested-With': 'XMLHttpRequest'\r\n }\r\n\r\n @every(minutes=24 * 60)\r\n def on_start(self):\r\n headers = {\r\n 'Host': 'www.zjsfgkw.cn',\r\n 'Origin': 'http://www.zjsfgkw.cn',\r\n 'User-Agent': random.choice(self.UA),\r\n }\r\n url = 'http://www.zjsfgkw.cn/Notice/NoticeSDList'\r\n self.crawl(url, headers=headers, callback=self.get_cbfy)\r\n\r\n @config(priority=2)\r\n def get_cbfy(self, response):\r\n\r\n cookies = response.cookies\r\n\r\n city_code = {}\r\n for each in response.doc('div.selectCourtUL ul > li').items():\r\n city_code[each.text()] = each.attr['fyid']\r\n\r\n code_list = ['']\r\n\r\n for value in city_code.values():\r\n code_list.append(value)\r\n\r\n for cbfy in code_list:\r\n url = 'http://www.zjsfgkw.cn/Notice/NoticeSD#{}'.format(cbfy)\r\n data = {\r\n 'pageno': '1',\r\n 'pagesize': '10',\r\n 'cbfy': cbfy\r\n }\r\n self.crawl(url, save={'cbfy': cbfy}, headers=self.headers, method='POST', data=data, cookies=cookies,\r\n callback=self.index_page)\r\n\r\n @config(age=10 * 24 * 60 * 60)\r\n def index_page(self, response):\r\n cookies = response.cookies\r\n cbfy = response.save['cbfy']\r\n #print(cbfy)\r\n response_json = json.loads(response.text)\r\n #print(response_json)\r\n total_num = response_json.get('total', 1)\r\n #print(total_num)\r\n result = total_num // 10 + 1 if (total_num % 10) > 0 else total_num // 10\r\n for i in range(1, result + 1):\r\n url = 'http://www.zjsfgkw.cn/Notice/NoticeSD#{}{}'.format(cbfy, i)\r\n data = {\r\n 'pageno': str(i),\r\n 'pagesize': '10',\r\n 'cbfy': cbfy\r\n }\r\n self.crawl(url, save={'cbfy': cbfy}, headers=self.headers, cookies=cookies, method='POST', data=data,\r\n callback=self.detail_page)\r\n\r\n @config(priority=2)\r\n def detail_page(self, response):\r\n # 初始化字段\r\n ann_type = '送达公告'\r\n ann_html = ''\r\n pdf_url = ''\r\n source = '浙江法院公开网'\r\n\r\n try:\r\n json_response = json.loads(response.text)\r\n # print(json_response)\r\n # print(json_response)\r\n result = json_response.get('list', '')\r\n for _list in result:\r\n ann_content = _list.get('Content', '')\r\n # print(ann_content)\r\n announcer = _list.get('Court', '')\r\n case_no = _list.get('CaseNo', '')\r\n\r\n # print(2,3,re.findall(r'(^.*?)[::]', ann_content)[0])\r\n a = re.findall(r'(^.*?)[::]', ann_content)\r\n if len(a) == 0:\r\n defendant = ''\r\n else:\r\n defendant = re.findall(r'(^.*?)[::]', ann_content)[0].replace('、', ',')\r\n\r\n # print(defendant)\r\n url = \"http://www.zjsfgkw.cn/Notice/NoticeSDInfo/\" + str(_list.get('Notice_SD_ID', ''))\r\n # print(url)\r\n long_time = _list.get('Time', '')\r\n # print(long_time)\r\n timeStamp = re.findall(r'Date\\((.*)\\)/', str(long_time))[0]\r\n # print(timeStamp)\r\n long = int(timeStamp) // 1000\r\n timeArray = time.localtime(long)\r\n ann_date = time.strftime(\"%Y-%m-%dT00:00:00+08:00\", timeArray)\r\n\r\n yield {\r\n \"ann_type\": ann_type,\r\n \"announcer\": announcer,\r\n \"case_no\": case_no,\r\n \"ann_content\": ann_content,\r\n \"ann_date\": ann_date,\r\n \"content_url\": url,\r\n \"ann_html\": ann_html,\r\n \"pdf_url\": pdf_url,\r\n \"source\": source,\r\n \"defendant\": str(defendant),\r\n \"id\": '',\r\n \"_id_\": ''\r\n }\r\n except Exception as e:\r\n print(e)\r\n print(response.url, '该网页形式有异')\r\n\r\n","sub_path":"爬虫代码/fygg/fygg-zhejiang.py","file_name":"fygg-zhejiang.py","file_ext":"py","file_size_in_byte":8105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"4249801","text":"import time\nimport datetime\nfrom bson.objectid import ObjectId\nfrom Access.Connect import Dao\nfrom Access.MongoConnect import MongoDao\n# from Connect import Dao\nimport logging\nlogging.basicConfig(level=logging.DEBUG,\n format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',\n datefmt='%Y-%m-%d %H:%M:%S',\n filename='Course.log',\n filemode='a')\n#课程类\nclass Course(object):\n def __init__(self,Course_id=None,Title=None,Type=None,Pic=None,Price=None,ShortUrl=None,Describe=None,Around=None,is_show=None,Create_time=None,Follow_num=None,Cover_pic=None):\n self.__Course_id=Course_id\n self.__Title=Title\n self.__Type=Type\n self.__Pic=Pic\n self.__Cover_pic=Cover_pic\n self.__Price=Price\n self.__ShortUrl=ShortUrl\n self.__Describe=Describe\n self.__Around=Around\n self.__is_show=is_show\n self.__Follow_num=Follow_num\n if Create_time is None:\n self.__Create_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\n else:\n self.__Create_time=Create_time\n self.__CourseDao = Dao()\n @property\n def Course_id(self):\n return self.__Course_id\n @Course_id.setter\n def Course_id(self,value):\n self.__Course_id=value\n @property\n def Title(self):\n return self.__Title\n @Title.setter\n def Title(self,value):\n self.__Title=value\n @property\n def Type(self):\n return self.__Type\n @Type.setter\n def Type(self,value):\n self.__Type=value\n @property\n def Pic(self):\n return self.__Pic\n @Pic.setter\n def Pic(self,value):\n self.__Pic=value\n @property\n def Cover_pic(self):\n return self.__Cover_pic\n @Cover_pic.setter\n def Cover_pic(self,value):\n self.__Cover_pic=value\n @property\n def Price(self):\n return self.__Price\n @Price.setter\n def Price(self,value):\n self.__Price=value\n @property\n def ShortUrl(self):\n return self.__ShortUrl\n @ShortUrl.setter\n def ShortUrl(self,value):\n self.__ShortUrl=value\n @property\n def Describe(self):\n return self.__Describe\n @Describe.setter\n def Describe(self,value):\n self.__Describe=value\n @property\n def Around(self):\n return self.__Around\n @Around.setter\n def Around(self,value):\n self.__Around=value\n @property\n def Follow_num(self):\n return self.__Follow_num\n @Follow_num.setter\n def Follow_num(self,value):\n self.__Follow_num=value\n @property\n def is_show(self):\n return self.__is_show\n @is_show.setter\n def is_show(self,value):\n self.__is_show=value\n @property\n def Create_time(self):\n return self.__Create_time\n @Create_time.setter\n def Create_time(self,value):\n self.__Create_time=value\n\n def data(self):\n result = {}\n for key, value in vars(self).items(): # 遍历类属性\n if value != None and key[9:]!='CourseDao':\n result[key[9:]] = value\n return result\n\n def updata(self):\n result={}\n for key,value in vars(self).items():\n print(key)\n if value!=None and key[9:]!='Course_id' and key[9:]!='CourseDao':\n if key[9:]!='Create_time':\n result[key[9:]]=value \n return result\n def Add(self):\n try:\n result = self.__CourseDao.insert('Course', self.data())\n except Exception as ex:\n logging.error(ex)\n return False\n else:\n return result\n\n def DeleteById(self):\n try:\n result = 0\n if self.Course_id != None:\n result = self.__CourseDao.delect(\n table='Course', require='Course_id=%s', agrs=[self.Course_id])\n else:\n return -1\n except Exception as ex:\n logging.error(ex)\n return -1\n else:\n return result\n\n def UpdateById(self):\n try:\n result = 0\n if self.Course_id != None:\n result = self.__CourseDao.update(table='Course', filedvalue=self.updata(\n ), require='Course_id=%s', agrs=[self.Course_id])\n else:\n return -1\n except Exception as ex:\n logging.error(ex)\n return -1\n else:\n return result\n\n def GetList(self, page=None, limit=None):\n try:\n if page != None and page != '' and limit != None and limit != '':\n count = self.__CourseDao.GetCount(table='Course')\n print('count', count)\n if count != 0:\n self.__CourseDao=Dao()\n tempresult = self.__CourseDao.query(\n table='Course', page=page, limit=limit)\n else:\n temp = {'count': 0, 'data': []}\n return temp\n else:\n tempresult = self.__CourseDao.query(table='Course')\n count = len(tempresult)\n result = []\n for tempitem in tempresult:\n tempdic = {}\n tempdic['course_id'] = tempitem[0]\n tempdic['title'] = tempitem[1]\n tempdic['type'] = tempitem[2]\n tempdic['pic'] = 'https://open-tv.oss-cn-hangzhou.aliyuncs.com/images/'+str(tempitem[3])\n tempdic['cover_pic']='https://open-tv.oss-cn-hangzhou.aliyuncs.com/images/'+str(tempitem[4])\n tempdic['price'] = tempitem[5]\n tempdic['shorturl'] = tempitem[6]\n tempdic['describe'] = tempitem[7]\n tempdic['around'] = tempitem[8]\n tempdic['follow_num'] = tempitem[9]\n tempdic['is_show'] = int.from_bytes(\n tempitem[10], byteorder='big')\n tempdic['create_time'] = tempitem[11].strftime(\n '%Y-%m-%d %H:%M:%S')\n result.append(tempdic)\n except Exception as ex:\n logging.error(ex)\n return None\n else:\n ddd = {'count': count, 'data': result}\n return ddd\n\n def GetCourseById(self):\n try:\n tempresult = self.__CourseDao.query(\n 'Course', require='Course_id=%s', agrs=[self.Course_id])\n except Exception as ex:\n logging.error(ex)\n return None\n else:\n if len(tempresult) != 0:\n tempdic = {}\n tempdic['course_id'] = tempresult[0][0]\n tempdic['title'] = tempresult[0][1]\n tempdic['type'] = tempresult[0][2]\n tempdic['pic'] = 'https://open-tv.oss-cn-hangzhou.aliyuncs.com/images/'+str(tempresult[0][3])\n tempdic['cover_pic']='https://open-tv.oss-cn-hangzhou.aliyuncs.com/images/'+str(tempresult[0][4])\n tempdic['price'] = tempresult[0][5]\n tempdic['shorturl'] = tempresult[0][6]\n tempdic['describe'] = tempresult[0][7]\n tempdic['around'] = tempresult[0][8]\n tempdic['follow_num'] = tempresult[0][9]\n tempdic['is_show'] = int.from_bytes(\n tempresult[0][10], byteorder='big')\n tempdic['Create_time'] = tempresult[0][11].strftime(\n '%Y-%m-%d %H:%M:%S')\n return tempdic\n else:\n return None\n \n #获取课程ID和 课程名称\n def GetCourseId(self):\n tempresult = self.__CourseDao.query(table='Course',fields=['Course_id','Title'])\n result=[]\n for tempitem in tempresult:\n tempdic={}\n tempdic['classid']=\"4,\"+str(tempitem['Course_id'])\n tempdic['classname']=tempitem['Title']\n result.append(tempdic)\n return result\n\n\nclass Course_Video(object):\n def __init__(self,Course_Video_id=None,Course_id=None,Title=None,Describe=None,PlayVID=None,FluentUrl=None,SdUrl=None,HighUrl=None,HdPullUrl=None,ShortUrl=None,Around=None,Create_time=None,Pic=None,is_show=0,Duration=None):\n self.__Course_Video_id=Course_Video_id\n self.__Course_id=Course_id\n self.__Title=Title\n self.__Describe=Describe\n self.__PlayVID=PlayVID\n self.__FluentUrl=FluentUrl\n self.__SdUrl=SdUrl\n self.__HighUrl=HighUrl\n self.__HdPullUrl=HdPullUrl\n self.__ShortUrl=ShortUrl\n self.__Around=Around\n self.__Pic=Pic\n if Create_time is None:\n self.__Create_time=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\n else:\n self.__Create_time=Create_time\n self.__is_show=is_show\n self.__Duration=Duration\n self.__Course_VideoDao = Dao()\n @property\n def Course_Video_id(self):\n return self.__Course_Video_id\n @Course_Video_id.setter\n def Course_Video_id(self,value):\n self.__Course_Video_id=value\n @property\n def Course_id(self):\n return self.__Course_id\n @Course_id.setter\n def Course_id(self,value):\n self.__Course_id=value\n @property\n def Title(self):\n return self.__Title\n @Title.setter\n def Title(self,value):\n self.__Title=value\n @property\n def Describe(self):\n return self.__Describe\n @Describe.setter\n def Describe(self,value):\n self.__Describe=value\n @property\n def PlayVID(self):\n return self.__PlayVID\n @PlayVID.setter\n def PlayVID(self,value):\n self.__PlayVID=value\n @property\n def FluentUrl(self):\n return self.__FluentUrl\n @FluentUrl.setter\n def FluentUrl(self,value):\n self.__FluentUrl=value\n @property\n def SdUrl(self):\n return self.__SdUrl\n @SdUrl.setter\n def SdUrl(self,value):\n self.__SdUrl=value\n @property\n def HighUrl(self):\n return self.__HighUrl\n @HighUrl.setter\n def HighUrl(self,value):\n self.__HighUrl=value\n @property\n def HdPullUrl(self):\n return self.__HdPullUrl\n @HdPullUrl.setter\n def HdPullUrl(self,value):\n self.__HdPullUrl=value\n @property\n def ShortUrl(self):\n return self.__ShortUrl\n @ShortUrl.setter\n def ShortUrl(self,value):\n self.__ShortUrl=value\n @property\n def Around(self):\n return self.__Around\n @Around.setter\n def Around(self,value):\n self.__Around=value\n @property\n def Pic(self):\n return self.__Pic\n @Pic.setter\n def Pic(self,value):\n self.__Pic=value\n @property\n def Create_time(self):\n return self.__Create_time\n @Create_time.setter\n def Create_time(self,value):\n self.__Create_time=value\n @property\n def is_show(self):\n return self.__is_show\n @is_show.setter\n def is_show(self,value):\n self.__is_show=value\n @property\n def Duration(self):\n return self.__Duration\n @Duration.setter\n def Duration(self,value):\n self.__Duration=value\n def data(self):\n result = {}\n for key, value in vars(self).items(): # 遍历类属性\n if value != None and key[15:]!='Course_VideoDao':\n result[key[15:]] = value\n return result\n\n def updata(self):\n result={}\n for key,value in vars(self).items():\n if value!=None and key[15:]!='Course_Video_id' and key[15:]!='Course_VideoDao':\n if key[15:]!='Create_time':\n result[key[15:]]=value \n return result\n def Add(self):\n try:\n result = self.__Course_VideoDao.insert(\n 'Course_Video', self.data())\n except Exception as ex:\n logging.error(ex)\n return False\n else:\n return result\n\n def DeleteById(self):\n try:\n result = 0\n if self.Course_Video_id != None:\n result = self.__Course_VideoDao.delect(\n table='Course_Video', require='Course_Video_id=%s', agrs=[self.Course_Video_id])\n else:\n return -1\n except Exception as ex:\n logging.error(ex)\n return -1\n else:\n return result\n\n def UpdateById(self):\n try:\n result = 0\n if self.Course_Video_id != None:\n result = self.__Course_VideoDao.update(table='Course_Video', filedvalue=self.updata(\n ), require='Course_Video_id=%s', agrs=[self.Course_Video_id])\n else:\n return -1\n except Exception as ex:\n logging.error(ex)\n return -1\n else:\n return result\n\n def GetList(self, page=None, limit=None):\n try:\n if page != None and page != '' and limit != None and limit != '':\n count = self.__Course_VideoDao.GetCount(\n table='Vw_Course_Video')\n if count != 0:\n self.__Course_VideoDao=Dao()\n tempresult = self.__Course_VideoDao.query(\n table='Vw_Course_Video', page=page, limit=limit)\n else:\n temp = {'count': 0, 'data': []}\n return temp\n else:\n tempresult = self.__Course_VideoDao.query(\n table='Vw_Course_Video')\n count = len(tempresult)\n result = []\n for tempitem in tempresult:\n tempdic = {}\n tempdic['course_video_id'] = tempitem[0]\n tempdic['course_title'] = tempitem[1]\n tempdic['title'] = tempitem[2]\n tempdic['describe'] = tempitem[3]\n tempdic['playvid'] = tempitem[4]\n tempdic['fluenturl'] = tempitem[5]\n tempdic['sdurl'] = tempitem[6]\n tempdic['highurl'] = tempitem[7]\n tempdic['hdpullurl'] = tempitem[8]\n tempdic['shorturl'] = tempitem[9]\n tempdic['around'] = tempitem[10]\n tempdic['pic'] = 'https://open-tv.oss-cn-hangzhou.aliyuncs.com/images/'+tempitem[11]\n tempdic['is_show'] = int.from_bytes(\n tempitem[12], byteorder='big')\n tempdic['create_time'] = tempitem[13].strftime(\n '%Y-%m-%d %H:%M:%S')\n tempdic['duration']=str(tempitem[14])\n result.append(tempdic)\n except Exception as ex:\n logging.error(ex)\n return None\n else:\n ddd = {'count': count, 'data': result}\n return ddd\n\n def GetCourseVideoById(self):\n try:\n result = self.__Course_VideoDao.query(\n 'Course_Video', require='Course_Video_id=%s', agrs=[self.Course_Video_id])\n except Exception as ex:\n logging.error(ex)\n return None\n else:\n tempdic = {}\n tempdic['course_video_id'] = result[0][0]\n tempdic['course_title'] = result[0][1]\n tempdic['title'] = result[0][2]\n tempdic['describe'] = result[0][3]\n tempdic['playvid'] = result[0][4]\n tempdic['fluenturl'] = result[0][5]\n tempdic['sdurl'] = result[0][6]\n tempdic['highurl'] = result[0][7]\n tempdic['hdpullurl'] = result[0][8]\n tempdic['shorturl'] = result[0][9]\n tempdic['around'] = result[0][10]\n tempdic['pic'] = 'https://open-tv.oss-cn-hangzhou.aliyuncs.com/images/'+result[0][11]\n tempdic['is_show'] = int.from_bytes(\n result[0][12], byteorder='big')\n tempdic['create_time'] = result[0][13].strftime(\n '%Y-%m-%d %H:%M:%S')\n tempdic['duration']=str(result[0][14])\n # result[0][7] = int.from_bytes(result[0][7], byteorder='big')\n return tempdic\n\n def GetCourseVideoByCid(self, page=None, limit=None):\n try:\n if page != None and page != '' and limit != None and limit != '':\n count = self.__Course_VideoDao.GetCount(\n table='Course_Video', require='Course_id=%s', agrs=[self.Course_id])\n if count != 0:\n self.__Course_VideoDao=Dao()\n tempresult = self.__Course_VideoDao.query(\n table='Course_Video', require='Course_id=%s', agrs=[self.Course_id], page=page, limit=limit)\n else:\n temp = {'count': 0, 'data': []}\n return temp\n else:\n tempresult = self.__Course_VideoDao.query(\n table='Course_Video', require='Course_id=%s', agrs=[self.Course_id])\n count = len(tempresult)\n result = []\n # print('GetCourseVideoByCid.tempresult:',tempresult)\n for tempitem in tempresult:\n tempdic = {}\n tempdic['course_video_id'] = tempitem[0]\n tempdic['course_id'] = tempitem[1]\n tempdic['title'] = tempitem[2]\n tempdic['describe'] = tempitem[3]\n tempdic['playvid'] = tempitem[4]\n tempdic['fluenturl'] = tempitem[5]\n tempdic['sdurl'] = tempitem[6]\n tempdic['highurl'] = tempitem[7]\n tempdic['hdpullurl'] = tempitem[8]\n tempdic['shorturl'] = tempitem[9]\n tempdic['around'] = tempitem[10]\n tempdic['pic'] = 'https://open-tv.oss-cn-hangzhou.aliyuncs.com/images/'+tempitem[11]\n tempdic['is_show'] = int.from_bytes(\n tempitem[12], byteorder='big')\n tempdic['create_time'] = tempitem[13].strftime(\n '%Y-%m-%d %H:%M:%S')\n tempdic['duration']=str(tempitem[14])\n result.append(tempdic)\n except Exception as ex:\n logging.error(ex)\n return None\n else:\n ddd = {'count': count, 'data': result}\n return ddd\n #获取用户是否拥有某课程权限\n #若有则返回详细课程列表信息\n def GetCoursePowerList(self,user_id=None,page=None,limit=None):\n try:\n if self.Course_id !=None and self.Course_id!='' and user_id!=None and user_id!='':\n self.__OrderMongoDao=MongoDao('QHY_Users')\n \n userinfo=self.__OrderMongoDao.select({'user_id':user_id,'buycourse.'+self.Course_id:{'$exists':True}}).data()\n # print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +' Course.py GetCoursePower [userinfo]:', userinfo)\n self.__OrderMongoDao.close()\n if page != None and page != '' and limit != None and limit != '':\n count = self.__Course_VideoDao.GetCount(\n table='Course_Video', require='Course_id=%s and is_show=%s', agrs=[self.Course_id,1])\n if count != 0:\n self.__Course_VideoDao=Dao()\n tempresult = self.__Course_VideoDao.query(\n table='Course_Video', require='Course_id=%s and is_show=%s', agrs=[self.Course_id,1], page=page, limit=limit)\n else:\n temp = {'count': 0, 'data': []}\n return temp\n else:\n tempresult = self.__Course_VideoDao.query(\n table='Course_Video', require='Course_id=%s and is_show=%s', agrs=[self.Course_id,1])\n count = len(tempresult)\n # self.__Course_VideoDao=Dao()\n # course_shortUrl=self.__Course_VideoDao.query(table='Course',fields=['ShortUrl'],require='Course_id=%s',agrs=[self.Course_id])#查询课程试看链接\n result = []\n for tempitem in tempresult:\n tempdic = {}\n if int.from_bytes(tempitem[12], byteorder='big')==1:#是否显示\n tempdic['course_video_id'] = tempitem[0]\n tempdic['course_id'] = tempitem[1]\n tempdic['title'] = tempitem[2]\n tempdic['describe'] = tempitem[3]\n tempdic['playvid'] = tempitem[4]\n if len(userinfo)!=0:# 用户是否拥有该课程权限\n #有权限 \n if str(tempitem[0]) in userinfo[0]['buycourse'][str(tempitem[1])]:\n tempdic['remainder']=5-int(userinfo[0]['buycourse'][str(tempitem[1])][str(tempitem[0])])\n else:\n tempdic['remainder']=5\n tempdic['fluenturl'] = tempitem[5]\n tempdic['sdurl'] = tempitem[6]\n tempdic['highurl'] = tempitem[7]\n tempdic['hdpullurl'] = tempitem[8]\n tempdic['shorturl'] = tempitem[9]\n else:\n tempdic['fluenturl'] = tempitem[9]\n tempdic['sdurl'] = tempitem[9]\n tempdic['highurl'] = tempitem[9]\n tempdic['hdpullurl'] = tempitem[9]\n tempdic['shorturl'] = tempitem[9]\n # tempdic['course_shortUrl']=course_shortUrl[10]['ShortUrl']\n tempdic['around'] = tempitem[10]\n tempdic['pic'] = 'https://open-tv.oss-cn-hangzhou.aliyuncs.com/images/'+tempitem[11]\n tempdic['duration']=str(tempitem[14])\n result.append(tempdic)\n\n \n # if len(userinfo)!=0:# 用户是否拥有该课程权限\n \n except Exception as ex:\n logging.error(ex)\n print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') +' Course.py GetCoursePower [error]:', str(ex))\n return None\n else:\n ddd = {'count': count, 'data': result}\n if len(userinfo)!=0:\n ddd['status']=1\n else:\n ddd['status']=0\n return ddd\n\n# CEV=Course_Video(Course_id='4001')\n# print(CEV.GetCoursePowerList(user_id='1007',page=1,limit=1))","sub_path":"ali-wechat-pay/Access/Course.py","file_name":"Course.py","file_ext":"py","file_size_in_byte":22546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"609218619","text":"while 1==1:\n BIM=float(input('请输入身高'))\n\n if BIM<18.5:\n print('过轻')\n elif BIM>=18.5 and BIM<=25:\n print('正常')\n elif BIM>=25 and BIM<=28:\n print('过重')\n else :\n print('过度严重肥胖')","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"314807384","text":"# This file optimises RNN using multiple random initialisations.\n\n\nimport sys\nfrom multiprocessing.pool import Pool\nimport pandas as pd\nfrom actionflow.data.data_process import DataProcess\nfrom actionflow.rnn.lstm_beh import LSTMBeh\nfrom actionflow.rnn.opt_beh import OptBEH\nfrom actionflow.util.helper import get_total_pionts\nfrom actionflow.util.logger import LogFile, DLogger\nfrom BD.data.data_reader import DataReader\nfrom BD.util.paths import Paths\nimport tensorflow as tf\n\nconfigs = []\nfor i in range(15):\n configs.append({\n 'g': 'Healthy',\n 'lr': 1e-2,\n 'cells': 10,\n 'model_path': None,\n 'iters': 1100,\n 's': i\n },\n )\n\n configs.append({\n 'g': 'Bipolar',\n 'lr': 1e-2,\n 'cells': 20,\n 'model_path': None,\n 'iters': 400,\n 's': i\n })\n\n configs.append({\n 'g': 'Depression',\n 'lr': 1e-2,\n 'cells': 10,\n 'model_path': None,\n 'iters': 1200,\n 's': i\n })\n\n\ndef run_BD(i):\n tf.reset_default_graph()\n data = DataReader.read_BD()\n ncells = configs[i]['cells']\n learning_rate = configs[i]['lr']\n group = configs[i]['g']\n iters = configs[i]['iters']\n model_path = configs[i]['model_path']\n output_path = Paths.local_path + 'BD/rnn-opt-rand-init/' + 'run_' + str(configs[i]['s']) + '/' + str(ncells) + 'cells/' + group + '/'\n with LogFile(output_path, 'run.log'):\n DLogger.logger().debug(\"group: \" + str(group))\n gdata = data.loc[data.diag == group]\n ids = gdata['id'].unique().tolist()\n dftr = pd.DataFrame({'id': ids, 'train': 'train'})\n tdftr = pd.DataFrame({'id': ids, 'train': 'test'})\n train, test = DataProcess.train_test_between_subject(gdata, pd.concat((dftr, tdftr)),\n [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])\n train = DataProcess.merge_data(train)\n DLogger.logger().debug(\"total points: \" + str(get_total_pionts(train)))\n\n worker = LSTMBeh(2, 0, n_cells=ncells)\n OptBEH.optimise(\n worker,\n output_path, train, None,\n learning_rate=learning_rate, global_iters=iters,\n load_model_path=model_path\n )\n\n\nif __name__ == '__main__':\n\n if len(sys.argv) == 2:\n n_proc = int(sys.argv[1])\n elif len(sys.argv) == 1:\n n_proc = 1\n else:\n raise Exception('invalid argument')\n\n p = Pool(n_proc)\n p.map(run_BD, range(len(configs)))\n p.close() # no more tasks\n p.join() # wrap up current tasks\n","sub_path":"src/BD/fit/rnn_opt_rand_init.py","file_name":"rnn_opt_rand_init.py","file_ext":"py","file_size_in_byte":2580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"386644719","text":"import sys; input = sys.stdin.readline\n\nN = int(input())\narr = [0] + [int(input()) for _ in range(N)]\ndp = [0] * (N + 1)\n\n\nif N == 1:\n print(arr[1])\n\nelif N == 2:\n print(arr[1] + arr[2])\n\nelse:\n dp[1] = arr[1]\n dp[2] = arr[1] + arr[2]\n for i in range(3, N + 1):\n dp[i] = max((arr[i] + arr[i - 1] + dp[i - 3]), (arr[i] + dp[i - 2]))\n\n print(dp[N])","sub_path":"Baekjoon/2579_계단오르기.py","file_name":"2579_계단오르기.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"307595362","text":"#coding=utf-8\n__author__ = 'Administrator'\nimport tornado.autoreload\n#import tornado.escape\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.web\nimport tornado.options\nimport tornado.template\nimport tornado.httpclient\nimport tornado.gen\nimport time,sqlite3,random\nimport os,json,re,sys,math\nsys.path.append('./')\nimport sql\nfrom tornado.options import define, options\ndefine(\"port\", default=80, help=\"run on the given port\", type=int)\n#实例化sql类\nsql=sql.Sqlite3('blog.db')\npage = 0\n\ndef INIT(self):\n sql = '''create table blog(\n id int,\n name varchar(32),\n email varchar(32),\n title varchar(32),\n fl varchar(32),\n tag varchar(32),\n date varchar(32),\n content varchar\n ) '''\n #sql2='alter table blog add column content varchar;'\n\nclass myapp(tornado.web.Application):\n def __init__(self):\n handlers = [\n (r\"/\", MainHandler),\n (r\"/test\", BlogsHandler),\n (r\"/test/([0-9]+)\", BlogshowHandler),\n (r\"/test/add\", BlogaddHandler),\n (r\"/test/edit/([0-9]+)\", BlogeditHandler),\n (r\"/test/(.*)\", BlogsflHandler),\n (r\"/xml\", XmlHandler),\n (r\".*\", redirect_Handler),\n ]\n settings = {\n \"cookie_secret\": \"bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=\",\n 'template_path':'templates',\n 'static_path' :'static',\n 'debug':'False'\n }\n tornado.web.Application.__init__(self, handlers, **settings)\n\nclass MainHandler(tornado.web.RequestHandler):\n @tornado.web.asynchronous\n @tornado.gen.engine\n def get(self):\n text = self.get_argument(\"message\", \"来宾\")\n self.render('index.html', ken=text)\n print(\"{'GET':'%s'}\"%text)\n\n def post(self):\n text = self.get_argument(\"message\")\n if text == \"\": text = \"来宾\"\n self.render('index.html', ken=text)\n\n def put(self):\n text = self.get_argument(\"message\")\n if text == \"\": text = \"None\"\n self.write(\"{'Put':'%s'}\"% text)\n\n def delete(self):\n self.write(\"delete: \" + self.get_argument(\"message\", \"None\"))\n\nclass redirect_Handler(tornado.web.RequestHandler):\n def get(self):\n self.redirect('/test')\n\n\nclass BlogsHandler(tornado.web.RequestHandler):\n def get(self):\n res_list = []\n page_list=[]\n\n page_size = 5 #每页的条数\n global page\n pag_num = self.get_argument('pag_num','0')\n page = page+int(pag_num) #当前页数\n page_count=sql.cmd(\"select count(id) from blog\")\n for i in page_count:\n page_count= int(i[0]) #获取总条数\n pages=math.ceil(page_count/5) #总页数\n if page <= 1:\n page = 1\n elif (page-1)*page_size > page_count:\n page=page-1\n sqls=\"select * from blog where id order by date desc limit %s,%s\"%((page-1)*page_size,page_size)\n res = sql.cmd(sqls)\n res_list = [list(i) for i in res]\n #res_list.reverse()\n self.render('blogs.html', lists = res_list,page_count=pages,page=page)\n\nclass BlogshowHandler(tornado.web.RequestHandler):\n def get(self,ids):\n res_list = []\n res = sql.cmd('select * from blog where id=%s'% ids)\n res_list = [list(i) for i in res]\n self.render('blog.html', lists = res_list)\n\nclass BlogsflHandler(tornado.web.RequestHandler):\n def get(self,fl):\n res_list = []\n res = sql.cmd(\"select * from blog where fl='%s' order by date desc \"%(fl))\n res_list = [list(i) for i in res]\n self.render('blog.html', lists = res_list)\n\nclass BlogaddHandler(tornado.web.RequestHandler):\n def get(self):\n res_list = []\n res = sql.cmd('select * from blog;')\n res_list = [list(i) for i in res]\n self.render('blog_add.html', lists = res_list)\n\n def post(self):\n res_list=[]\n ids = int(time.strftime(\"%Y%m%y%H%M%S\")+ str(random.randrange(10000,99999)))\n name = 'admin'\n email = 'kkk@kkk.com'\n title = self.get_argument('title')\n fl = self.get_argument('fl')\n tag = self.get_argument('tag')\n tms = time.strftime('%Y-%m-%d %H:%M')\n content = self.get_argument('comment')\n for i in int(ids),name,email,title,fl,tag,tms,content:res_list.append(i)\n sql.cur.execute(\"insert into blog values (?,?,?,?,?,?,?,?)\",res_list)\n sql.commit()\n self.redirect('/test')\n\nclass BlogeditHandler(tornado.web.RequestHandler):\n def get(self,ids):\n res_list = []\n res = sql.cmd('select * from blog where id=%s;'% ids)\n res_list = [list(i) for i in res]\n self.render('blog_edit.html', lists = res_list)\n\n def post(self,ids):\n title = self.get_argument('title')\n fl = self.get_argument('fl')\n tag = self.get_argument('tag')\n content = self.get_argument('comment')\n sql.cur.execute(\"update blog set title='%s',fl='%s',tag='%s',content='%s' where id = '%s'\"%(\n title,fl,tag,content,ids))\n sql.commit()\n self.redirect('/test/%s'%ids)\n\nclass XmlHandler(tornado.web.RequestHandler):\n def get(self):\n res = sql.cmd('select * from blog;')\n res_list = [list(i) for i in res]\n self.render('xml.html',lists = res_list)\n\n def post(self):\n ids = self.get_argument('id_del')\n sql.cur.execute(\"delete from blog where id=%s\"%ids)\n sql.commit()\n self.redirect('/xml')\n\n\nif __name__ == \"__main__\":\n tornado.options.parse_command_line()\n http_server = tornado.httpserver.HTTPServer(myapp())\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"tornado/web_run.py","file_name":"web_run.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"304102871","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom ckeditor.fields import RichTextField\nfrom django.utils.text import slugify\n\n# Create your models here.\n\nclass Author(models.Model):\n title = models.CharField(max_length=100)\n image = models.ImageField(upload_to='img/%y')\n name = models.ForeignKey(User, on_delete=models.CASCADE)\n details = models.CharField(max_length=250)\n email = models.EmailField(max_length=150)\n twitter = models.URLField(max_length=350)\n facebook = models.URLField(max_length=350)\n linkdin = models.URLField(max_length=350)\n github = models.URLField(max_length=350)\n stack_overflow = models.URLField(max_length=350)\n\n def __str__(self):\n return str(self.name)\n \nclass Category(models.Model):\n name = models.CharField(max_length=250)\n\n def __str__(self):\n return self.name\n \n\nclass Article(models.Model):\n title = models.CharField(max_length=250)\n artcle_author = models.ForeignKey(Author, on_delete=models.CASCADE)\n image = models.ImageField(upload_to='article/%y')\n published = models.DateTimeField(auto_now=True, auto_now_add=False)\n body = RichTextField(blank=True, null=True)\n category = models.ForeignKey(Category, on_delete=models.CASCADE)\n unique_id = models.CharField(max_length=100, unique=True)\n\n slug = models.SlugField(max_length=250, unique=True, null=True, blank=True, allow_unicode=True)\n \n def __str__(self):\n return self.title\n\n def save(self, *args, **kwargs):\n self.slug = slugify([str(self.title), self.artcle_author, self.category, self.published, self.unique_id])\n super(Article, self).save(*args, **kwargs)\n\n \nclass About_Me(models.Model):\n title = models.CharField(max_length=100)\n image = models.ImageField(upload_to='img/%y')\n name_1 = models.CharField(max_length=20)\n name_2 = models.CharField(max_length=20)\n phone_1 = models.CharField(max_length=20)\n phone_2 = models.CharField(max_length=20)\n email = models.EmailField(max_length=150)\n details = RichTextField()\n twitter = models.URLField(max_length=350)\n facebook = models.URLField(max_length=350)\n linkdin = models.URLField(max_length=350)\n github = models.URLField(max_length=350)\n stack_overflow = models.URLField(max_length=350)\n resume = models.FileField(upload_to='documents')\n \n def __str__(self):\n return f'{self.name_1} {self.name_2}'\n \n","sub_path":"django_blog/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"32406092","text":"import csv\nimport numpy as np\nimport math\nimport sys\n\nmaxInt = sys.maxsize\ndecrement = True\n\nwhile decrement:\n # decrease the maxInt value by factor 10 \n # as long as the OverflowError occurs.\n\n decrement = False\n try:\n csv.field_size_limit(maxInt)\n except OverflowError:\n maxInt = int(maxInt/10)\n decrement = True\n\nwith open('training_data_abridged.csv') as infile:\n data = csv.DictReader(infile)\n\n features = []\n classes = []\n for line in data:\n p = line['pixels']\n p = p.split()\n #print (p)\n\n p_2 = []\n for i in p:\n p_2.append(float(i))\n\n c = [0,0,0]\n c[int(line['class'])] = 1\n\n features.append(p_2)\n classes.append(c)\n\n\n#features = np.array(features)\n#classes = np.array(classes)\n\n\n# def bfs_recurse(f, n, stack, obj):\n# while(len(stack) > 0):\n# s = int(stack.pop())\n# print(\"here:\", f[s], \" \", s)\n\n# if (f[s] != 0.0):\n# obj.append(s)\n# if (s+1 <= n and (s+1) not in obj):\n# stack.append(s+1)\n# if (s-1 >= 0 and (s-1) not in obj):\n# stack.append(s-1)\n# if (s + math.sqrt(n) <= n and (s + math.sqrt(n)) not in obj):\n# stack.append(s + math.sqrt(n))\n# if (s - math.sqrt(n) >= 0 and (s - math.sqrt(n)) not in obj):\n# stack.append(s - math.sqrt(n))\n \n# return obj\n\ndef bfs_feature(f):\n start = len(f) // 2\n obj = []\n stack = []\n n = len(f)\n sqrt_n = int(math.sqrt(n))\n print (\"sqrt n: \", sqrt_n)\n stack.append(start)\n stack.append(start + 1)\n stack.append(start - 1)\n stack.append(start + sqrt_n)\n stack.append(start - sqrt_n)\n threshold = np.mean(f) / 3\n print (\"threshold: \", threshold)\n\n #obj = bfs_recurse(f, len(f), stack, obj)\n while(len(stack) > 0):\n s = int(stack.pop())\n if (s in obj):\n continue\n #print(\"here:\", f[s], \" \", s)\n\n if (f[s] > threshold):\n obj.append(s)\n if (s+1 < n and (s+1) not in obj):\n stack.append(s+1)\n if (s-1 >= 0 and (s-1) not in obj):\n stack.append(s-1)\n if (s + sqrt_n < n and (s + sqrt_n) not in obj):\n stack.append(s + sqrt_n)\n if (s - sqrt_n >= 0 and (s - sqrt_n) not in obj):\n stack.append(s - sqrt_n)\n\n print (\"len obj: \", len(obj))\n return obj\n\n\nfor feature in features:\n galaxy = bfs_feature(feature)\n for i in range(0, len(feature)):\n if (i not in galaxy):\n feature[i] = 0.0\n\nwith open('training_data_abridged_blacked.csv', 'w', newline='') as outputfile:\n writer = csv.DictWriter(outputfile, ['OBJID', 'pixels', 'class'])\n writer.writeheader()\n\n for i in range(0, len(features)):\n line = features[i]\n c = classes[i]\n c = c.index(1)\n pixels_string = ' '.join(line)\n row = {'OBJID': line['OBJID'], 'pixels': pixels_string, 'class': c}\n writer.writerow(row)\n ","sub_path":"black_edges.py","file_name":"black_edges.py","file_ext":"py","file_size_in_byte":3066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"480237604","text":"# coding: utf-8\r\n\r\nimport pytz\r\nimport tweepy\r\nimport twitter.dbaccess as dbaccess\r\nimport config.twitter as config\r\n\r\n\r\ndef auth_twitter():\r\n auth = tweepy.OAuthHandler(config.CONSUMER_KEY, config.CONSUMER_SECRET)\r\n auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_SECRET)\r\n\r\n api = tweepy.API(auth)\r\n\r\n return api\r\n\r\n\r\ndef extract_tweet_data(tweet):\r\n timestamp_utc = pytz.utc.localize(tweet.created_at)\r\n timestamp_jst = timestamp_utc.astimezone(pytz.timezone('Asia/Tokyo'))\r\n tweet_data = (tweet.author.id,\r\n tweet.author.name,\r\n tweet.id,\r\n tweet.text,\r\n tweet.author.screen_name,\r\n timestamp_jst.strftime('%Y-%m-%d %H:%M:%S')\r\n )\r\n return tweet_data\r\n\r\n\r\ndef main():\r\n api = auth_twitter()\r\n\r\n q = '@side_trade exclude:retweets'\r\n count = 100\r\n since_id = 0\r\n max_id = None\r\n\r\n if dbaccess.select_count_all() > 0:\r\n since_id = dbaccess.select_last_tweet_id() + 1\r\n\r\n search_result = api.search(q=q, count=count, since_id=since_id, max_id=max_id)\r\n\r\n if len(search_result) == 0:\r\n return\r\n\r\n tweet_data_list = list(map(extract_tweet_data, search_result))\r\n\r\n while len(search_result) == 100:\r\n max_id = search_result[-1].id - 1\r\n search_result = api.search(q=q, count=count, since_id=since_id, max_id=max_id)\r\n tweet_data_list.extend(list(map(extract_tweet_data, search_result)))\r\n\r\n for tweet_data in reversed(tweet_data_list):\r\n dbaccess.insert_tweet(tweet_data)\r\n","sub_path":"twitter/fetch.py","file_name":"fetch.py","file_ext":"py","file_size_in_byte":1580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"564154875","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html\n\nimport pymongo\nfrom scrapy.conf import settings\nfrom scrapy.exceptions import DropItem\nimport logging\nimport datetime\n\nclass FakeNewsExtractorPipeline(object):\n def process_item(self, item, spider):\n return item\n\n\nclass MongoDBPipeline(object):\n def __init__(self):\n connection = pymongo.MongoClient(\n settings['MONGODB_SERVER'],\n settings['MONGODB_PORT']\n )\n db = connection[settings[\"MONGODB_DB\"]]\n self.collection = db[settings[\"MONGODB_CNN_COLLECTION\"]]\n self.log = logging.getLogger(__name__)\n\n def process_item(self,item,spider):\n\n for data in item:\n if not data:\n raise DropItem(\"Missing {0}!\".format(data))\n if self.collection.find_one({'url' : item[\"url\"]}):\n self.log.info(\"News already in MongoDB. {0}\".format(item[\"url\"]))\n return item\n else:\n try:\n item[\"text\"] = ''.join(item[\"text\"])\n except:\n self.log.error(\"Cannot convert to text\")\n try:\n item[\"published\"] = datetime.datetime.strptime(item[\"published\"],'%Y-%m-%dT%H:%M:%SZ')\n except:\n self.log.info(\"Cannot convert to Datetime\")\n self.collection.update({'url' : item[\"url\"]},dict(item),upsert=True)\n self.log.info(\"News added to MongoDB. {0}\".format(item[\"url\"]))\n return item\n","sub_path":"fake_news_extractor/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"491874617","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\n\nfrom bead.test import TestCase\nfrom testtools.matchers import FileContains, Not, Contains\n\nimport os\nfrom bead.workspace import Workspace\nfrom . import test_fixtures as fixtures\n\n\nclass Test_input_commands(TestCase, fixtures.RobotAndBeads):\n\n def assert_loaded(self, robot, input_name, bead_name):\n self.assertThat(\n robot.cwd / 'input' / input_name / 'README',\n FileContains(bead_name))\n\n # tests\n def test_basic_usage(self, robot, bead_with_history):\n # nextbead with input1 as databead1\n robot.cli('new', 'nextbead')\n robot.cd('nextbead')\n # add version TS2\n robot.cli('input', 'add', 'input1', 'bead_with_history', '--time', fixtures.TS2)\n self.assert_loaded(robot, 'input1', fixtures.TS2)\n robot.cli('save')\n robot.cd('..')\n robot.cli('nuke', 'nextbead')\n\n robot.cli('develop', 'nextbead')\n robot.cd('nextbead')\n assert not os.path.exists(robot.cwd / 'input/input1')\n\n robot.cli('input', 'load')\n assert os.path.exists(robot.cwd / 'input/input1')\n\n robot.cli('input', 'add', 'input2', 'bead_with_history')\n assert os.path.exists(robot.cwd / 'input/input2')\n\n robot.cli('input', 'delete', 'input1')\n assert not os.path.exists(robot.cwd / 'input/input1')\n\n # no-op load do not crash\n robot.cli('input', 'load')\n\n robot.cli('status')\n\n def test_update_unloaded_input_w_another_bead(self, robot, bead_with_inputs, bead_a, bead_b):\n robot.cli('develop', bead_with_inputs)\n robot.cd(bead_with_inputs)\n\n assert not Workspace(robot.cwd).is_loaded('input_b')\n\n robot.cli('input', 'update', 'input_b', bead_a)\n self.assert_loaded(robot, 'input_b', bead_a)\n\n robot.cli('status')\n self.assertThat(robot.stdout, Not(Contains(bead_b)))\n\n def test_load_on_workspace_without_input_gives_feedback(self, robot, bead_a):\n robot.cli('develop', bead_a)\n robot.cd(bead_a)\n robot.cli('input', 'load')\n\n self.assertThat(robot.stderr, Contains('WARNING'))\n self.assertThat(robot.stderr, Contains('No inputs defined to load.'))\n\n def test_load_with_missing_bead_gives_warning(self, robot, bead_with_inputs, bead_a):\n robot.cli('develop', bead_with_inputs)\n robot.cd(bead_with_inputs)\n robot.reset()\n robot.cli('input', 'load')\n self.assertThat(robot.stderr, Contains('WARNING'))\n self.assertThat(robot.stderr, Contains('input_a'))\n self.assertThat(robot.stderr, Contains('input_b'))\n\n def test_load_only_one_input(self, robot, bead_with_inputs, bead_a):\n robot.cli('develop', bead_with_inputs)\n robot.cd(bead_with_inputs)\n robot.cli('input', 'load', 'input_a')\n self.assert_loaded(robot, 'input_a', bead_a)\n with robot.environment:\n self.assertFalse(Workspace('.').is_loaded('input_b'))\n\n def test_partially_deleted_box(self, robot, bead_with_inputs):\n deleted_box = self.new_temp_dir()\n robot.cli('box', 'add', 'missing', deleted_box)\n os.rmdir(deleted_box)\n robot.cli('develop', bead_with_inputs)\n robot.cd(bead_with_inputs)\n robot.cli('input', 'load')\n\n def test_add_with_unrecognized_bead_name_exits_with_error(self, robot, bead_a):\n robot.cli('develop', bead_a)\n robot.cd(bead_a)\n try:\n robot.cli('input', 'add', 'x', 'non-existing-bead')\n self.fail('Expected an error exit!')\n except SystemExit:\n self.assertThat(robot.stderr, Contains('ERROR'))\n self.assertThat(robot.stderr, Contains('non-existing-bead'))\n\n def test_add_with_hacked_bead_is_refused(self, robot, hacked_bead, bead_a):\n robot.cli('develop', bead_a)\n robot.cd(bead_a)\n robot.cli('input', 'add', 'hack', hacked_bead)\n self.assertFalse(Workspace(robot.cwd).has_input('hack'))\n self.assertThat(robot.stderr, Contains('WARNING'))\n\n def test_update_with_hacked_bead_is_refused(self, robot, hacked_bead, bead_a):\n robot.cli('develop', bead_a)\n robot.cd(bead_a)\n robot.cli('input', 'add', 'intelligence', bead_a)\n robot.cli('input', 'update', 'intelligence', hacked_bead)\n self.assertThat(\n robot.cwd / 'input/intelligence/README',\n FileContains(bead_a))\n self.assertThat(robot.stderr, Contains('WARNING'))\n\n def test_update_to_next_version(self, robot, bead_with_history):\n robot.cli('new', 'test-workspace')\n robot.cd('test-workspace')\n # add version TS1\n robot.cli('input', 'add', 'input1', 'bead_with_history', '--time', fixtures.TS1)\n self.assert_loaded(robot, 'input1', fixtures.TS1)\n\n robot.cli('input', 'update', 'input1', '--next')\n self.assert_loaded(robot, 'input1', fixtures.TS2)\n\n robot.cli('input', 'update', 'input1', '-N')\n self.assert_loaded(robot, 'input1', fixtures.TS3)\n\n def test_update_to_previous_version(self, robot, bead_with_history):\n robot.cli('new', 'test-workspace')\n robot.cd('test-workspace')\n # add version TS1\n robot.cli('input', 'add', 'input1', 'bead_with_history', '--time', fixtures.TS4)\n self.assert_loaded(robot, 'input1', fixtures.TS4)\n\n robot.cli('input', 'update', 'input1', '--prev')\n self.assert_loaded(robot, 'input1', fixtures.TS3)\n\n robot.cli('input', 'update', 'input1', '-P')\n self.assert_loaded(robot, 'input1', fixtures.TS2)\n","sub_path":"bead_cli/test_input_commands.py","file_name":"test_input_commands.py","file_ext":"py","file_size_in_byte":5704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"337101054","text":"import cv2\r\n\r\ncam = cv2.VideoCapture(0)\r\nimage = cv2.imread('E:\\photos/iron.jpg')\r\nimage1 = cv2.imread('E:\\photos/background.jpg')\r\nimage2 = cv2.imread('E:\\photos/avg.jpg')\r\nimage3 = cv2.imread('E:\\photos/falls.jpg')\r\nimage4 = cv2.imread('E:\\photos/space.png')\r\nimage5 = cv2.imread('E:\\photos/tiger.jpg')\r\n\r\n\r\n\r\nk = int(input('choose any one number from 1 to 6: '))\r\n\r\nwhile True:\r\n flag, frame = cam.read()\r\n if not flag:\r\n print('Could not access the camera')\r\n break\r\n elif flag:\r\n if k == 1:\r\n image = cv2.resize(image, (frame.shape[1], frame.shape[0]))\r\n blended_frame1 = cv2.addWeighted(frame, 0.7, image, 0.3, gamma = 0.1)\r\n cv2.imshow('Blended Frame 1', blended_frame1)\r\n elif k == 2:\r\n image1 = cv2.resize(image1, (frame.shape[1], frame.shape[0]))\r\n blended_frame2 = cv2.addWeighted(frame, 0.7, image1, 0.3, gamma = 0.1)\r\n cv2.imshow('Blended Frame 2', blended_frame2)\r\n elif k == 3:\r\n image2 = cv2.resize(image2, (frame.shape[1], frame.shape[0]))\r\n blended_frame3 = cv2.addWeighted(frame, 0.7, image2, 0.3, gamma = 0.1)\r\n cv2.imshow('Blended Frame 3', blended_frame3)\r\n elif k == 4:\r\n image3 = cv2.resize(image3, (frame.shape[1], frame.shape[0]))\r\n blended_frame4 = cv2.addWeighted(frame, 0.7, image3, 0.3, gamma = 0.1)\r\n cv2.imshow('Blended Frame 4', blended_frame4)\r\n elif k == 5:\r\n image4 = cv2.resize(image4, (frame.shape[1], frame.shape[0]))\r\n blended_frame5 = cv2.addWeighted(frame, 0.7, image4, 0.3, gamma = 0.1)\r\n cv2.imshow('Blended Frame 5', blended_frame5)\r\n elif k == 6:\r\n image5 = cv2.resize(image5, (frame.shape[1], frame.shape[0]))\r\n blended_frame6 = cv2.addWeighted(frame, 0.7, image5, 0.3, gamma = 0.1)\r\n cv2.imshow('Blended Frame 6', blended_frame6)\r\n \r\n m = cv2.waitKey(1)\r\n if m == ord('q'):\r\n break\r\n\r\n\r\ncam.release()\r\ncv2.destroyAllWindows()","sub_path":"opencv-day3(assignment-1).py","file_name":"opencv-day3(assignment-1).py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"399903424","text":"import glob\nimport os, sys, shutil\n\nfolders = []\n\ndirs = list(os.scandir(\"graphs\"))\nprint(dirs)\n\nnb_to_run = 10\ncount = 0\n\nprocessed_dirs = []\n\nfor source_folder in list(dirs):\n if count > nb_to_run: break\n if os.path.isfile(source_folder.path):\n print(\"%s, Not a folder\" % source_folder.path)\n continue\n processed_dirs.append(source_folder.path)\n count += 1\n dest_folder = \"r_seir\" + \"/\" + source_folder.path\n os.makedirs(dest_folder, exist_ok=True)\n shutil.copy(\"r_seir/parameters_0.txt\", dest_folder)\n cmd = \"./seir %s %s > output.txt\" % (source_folder.path, dest_folder)\n print(\"-----------------------------------------------\")\n print(cmd)\n os.system(cmd)\n shutil.copy(\"output.txt\", dest_folder)\n shutil.copy(\"transition_stats.csv\", dest_folder)\n os.remove(\"output.txt\")\n os.remove(\"transition_stats.csv\")\n\nprint(\"-----------------------------------------------\")\nprint(\"Processed: \", processed_dirs)\nprint(\"Created output.txt and transition_stats.csv in subfolders\")\n","sub_path":"GE_COVID_CPP_CODE/interval_contraction/run_simulations.py","file_name":"run_simulations.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"190288240","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\n\nfrom time import sleep\n\n# Create your views here.\ndef index(request):\n return render(request, 'scroll/index.html')\n\ndef posts(request):\n start = int(request.GET.get('start') or 0)\n end = int(request.GET.get('end') or (start + 9))\n data = []\n for i in range(start, end+1):\n data.append(f'Post# {i}')\n return JsonResponse(data, safe=False)","sub_path":"Django/lol/scroll/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"28905606","text":"#!/usr/bin/env python\n#\n# Copyright (C) 2014 \n# Brian Caswell \n# Narf Industries \n#\n# Permission is hereby granted, free of charge, to any person obtaining a\n# copy of this software and associated documentation files (the \"Software\"),\n# to deal in the Software without restriction, including without limitation\n# the rights to use, copy, modify, merge, publish, distribute, sublicense,\n# and/or sell copies of the Software, and to permit persons to whom the\n# Software is furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included\n# in all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\nimport string\nimport sys\nimport os\n\nfrom generator.actions import Actions\nfrom random import choice,randint\nfrom struct import *\n\n\nsys.path.append(os.path.dirname(os.path.realpath(__file__)))\n\nfrom payloads import *\n\ndef random_alpha(a, b):\n return ''.join(choice(string.letters) for _ in range(randint(a, b)))\n\ndef build_seg(l,n,d,c):\n return pack(\" hide create form\n r.component.configure(insertable = False)\n requires._select = selectable\n return True\n s3.prep = prep\n\n return s3_rest_controller(rheader = s3db.dc_rheader)\n\n# -----------------------------------------------------------------------------\ndef collection():\n \"\"\" Manage Data Collections \"\"\"\n\n def prep(r):\n\n if r.record and r.component_name == \"answer\":\n\n # Allow only unanswered questions\n atable = s3db.dc_answer\n qtable = s3db.dc_question\n left = [atable.on((atable.question_id == qtable.id) & \\\n (atable.collection_id == r.id) & \\\n (atable.deleted != True))]\n if r.component_id:\n query = (atable.id == None) | (atable.id == r.component_id)\n else:\n query = (atable.id == None)\n\n # Allow only questions from the selected template\n template_id = r.record.template_id\n if template_id:\n ltable = s3db.dc_template_question\n left.append(ltable.on((ltable.question_id == qtable.id) & \\\n (ltable.deleted != True)))\n query &= (ltable.template_id == template_id)\n\n # Restrict field options accordingly\n db = current.db\n field = atable.question_id\n field.requires = IS_ONE_OF(db(query),\n \"dc_question.id\",\n field.represent,\n left=left)\n\n # Hide create form when all questions have been answered\n if r.method != \"update\":\n count = qtable.id.count()\n row = db(query).select(count,\n left=left,\n limitby=(0, 1)).first()\n if not row or not row[count]:\n r.component.configure(insertable=False)\n\n return True\n s3.prep = prep\n\n return s3_rest_controller(rheader = s3db.dc_rheader)\n\n# -----------------------------------------------------------------------------\ndef template_question():\n \"\"\"\n RESTful CRUD controller for options.s3json lookups\n - needed for adding questions to a template\n \"\"\"\n\n s3.prep = lambda r: r.method == \"options\" and r.representation == \"s3json\"\n\n return s3_rest_controller()\n\n# END =========================================================================\n","sub_path":"controllers/dc.py","file_name":"dc.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"636922920","text":"from peewee import *\n\n\nclass ConnectDatabase:\n\n def __init__(self):\n db_name, user_name = self.__get_connect_string()\n self.db = PostgresqlDatabase(db_name, user_name)\n\n def __get_connect_string(self):\n try:\n with open('connect_str.txt', \"r\") as f:\n details = f.readline().split(\";\")\n return details[0], details[1]\n except:\n print(\"You need to create a database and store its name in a file named 'connect_str.txt'. \\\n For more info, head over to the README\")","sub_path":"connect_database.py","file_name":"connect_database.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"157517788","text":"import numpy as np\n\nclass L0:\n # L0 regularization (Rounding of small coefficients to 0)\n # Parameters:\n # theta: Threshold absolute value to decrease coefficients\n # update_freq: Frequency of coefficient rounding\n \n def __init__(self, theta):\n self.theta = theta\n\n def regularize(self, w):\n w[np.where(np.absolute(w) < self.theta)] = 0\n return w\n\n\nclass TGD:\n # Truncated Gradient Descent\n # Parameters:\n # theta: Threshold absolute value to decrease coefficients\n # g: Rounding aggressivenes\n # update_freq: Frequency of coefficient rounding\n \n def __init__(self, theta, g):\n self.theta = theta\n self.g = g\n\n # Learning rate affects rounding aggressivenes\n def regularize(self, w, learning_rate = 1):\n\n alpha = self.g * learning_rate\n\n # Decrease values between 0 and theta by alhpa (Positive weights)\n interval = np.where((0 < w) & (w < self.theta))\n zero_vector = np.zeros(w[interval].shape) \n w[interval] = np.maximum(zero_vector, w[interval]-alpha)\n \n # Increase values between -theta and 0 by alpha (Negative weights)\n interval = np.where((-self.theta < w) & (w < 0))\n zero_vector = np.zeros(w[interval].shape) \n w[interval] = np.minimum(zero_vector, w[interval]+alpha)\n \n return w\n","sub_path":"regularizers/Regularizer.py","file_name":"Regularizer.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"111698223","text":"import os\n\nfrom lux.utils.files import skipfile, get_rel_dir\nfrom lux import BuildError\n\n\ndef split(filename):\n bits = filename.split('.')\n ext = None\n if len(bits) > 1:\n ext = bits[-1]\n filename = '.'.join(bits[:-1])\n return filename, ext\n\n\ndef all_files(app, router, src):\n '''Generator of all files within a directory\n '''\n if os.path.isdir(src):\n for dirpath, _, filenames in os.walk(src):\n if skipfile(os.path.basename(dirpath) or dirpath):\n continue\n rel_dir = get_rel_dir(dirpath, src)\n for filename in filenames:\n if skipfile(filename):\n continue\n name, ext = split(filename)\n name = os.path.join(rel_dir, name)\n fpath = os.path.join(dirpath, filename)\n yield name, fpath, ext\n #\n elif os.path.isfile(src):\n dirpath, filename = os.path.split(src)\n assert not filename.startswith('.')\n name, ext = split(filename)\n fpath = os.path.join(dirpath, filename)\n yield name, dirpath, ext\n #\n else:\n raise BuildError(\"'%s' not found.\" % src)\n","sub_path":"lux/extensions/content/static/building.py","file_name":"building.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"174797312","text":"from django.utils.deprecation import MiddlewareMixin\nfrom common import errors\nfrom libs.http import render_json\n\nimport logging\n\nerr_log = logging.getLogger('err')\n\n\n\nclass AuthMiddleware(MiddlewareMixin):\n '''登录验证中间件'''\n\n white_list = [\n '/api/user/vcode/fetch',\n '/api/user/vcode/submit',\n '/qiniu/callback',\n '/',\n '/api/social/rank,'\n ]\n\n def process_request(self, request):\n # 如果当前路径在白名单,跳过\n if request.path in self.white_list:\n return\n\n # 如果当前路径不在白名单,检查是否登录\n uid = request.session.get('uid')\n if not uid:\n return render_json(data='用户未登录', code=errors.LoginRequired.code)\n else:\n request.uid = uid\n\n\nclass LogicErrMiddleware(MiddlewareMixin):\n '''逻辑异常处理'''\n\n def process_exception(self, request, exception):\n if isinstance(exception, errors.LogicErr):\n\n err_log.error(f'逻辑异常: {exception.code}: {exception.data}')\n return render_json(exception.data, exception.code)\n\n","sub_path":"common/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"387348829","text":"\"\"\"\n Realizar un aplicacion que reciva 5 numeros y determine e imprima los entero \n mayor y menor \n \n by->stydev\n date->15-06-19\n\"\"\"\nif __name__=='__main__':\n n1=10\n n2=15\n n3=5\n n4=20\n n5=25\n \n print(\"-- .: Resultado :. -->\")\n print(\"Mayor> \",max(n1,n2,n3,n4,n5))\n print(\"Menor> \",min(n1,n2,n3,n4,n5))","sub_path":"practica_libro/compara_cinco_numeros/compara_cinco_numeros.py","file_name":"compara_cinco_numeros.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"589248721","text":"# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software 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\"\"\"\nPlaceholder file, will be overwritten by the backend on build.\nFunctionality for storing and setting the version info for DeepSparse\n\"\"\"\n\n__all__ = [\n \"__version__\",\n \"version\",\n \"version_major\",\n \"version_minor\",\n \"version_bug\",\n \"version_build\",\n \"version_major_minor\",\n]\n__version__ = \"0.2.0\"\n\nversion = __version__\nversion_major, version_minor, version_bug, version_build = version.split(\".\") + (\n [None] if len(version.split(\".\")) < 4 else []\n) # handle conditional for version being 3 parts or 4 (4 containing build date)\nversion_major_minor = f\"{version_major}.{version_minor}\"\n","sub_path":"src/deepsparse/version.py","file_name":"version.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"506608102","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\"\"\"TAN Manager Implementation\n\n$Id$\n\"\"\"\n__docformat__ = \"reStructuredText\"\nimport persistent.list\nimport zope.component\nimport zope.interface\nfrom zope.app.authentication.interfaces import IAuthenticatorPlugin\nfrom zope.app.authentication.interfaces import IPrincipalInfo\nfrom zope.app.authentication.interfaces import IQuerySchemaSearch\nfrom zope.app.authentication.interfaces import IAuthenticatedPrincipalCreated\nfrom zope.app.authentication import principalfolder\nfrom zope.app.container import btree\n\nfrom z3c.tan import interfaces, session\n\n\nclass TANManager(btree.BTreeContainer):\n zope.interface.implements(\n interfaces.ITANManager, IAuthenticatorPlugin, IQuerySchemaSearch)\n\n schema = principalfolder.ISearchSchema\n\n def __init__(self, prefix=u''):\n super(TANManager, self).__init__()\n self.prefix = prefix\n self._usedTANs = persistent.list.PersistentList()\n\n def __setitem__(self, key, value):\n \"\"\"See zope.app.container.interfaces.IContainer\"\"\"\n if value.tan in self._usedTANs:\n raise interfaces.TANAlreadyUsed(value.tan)\n self._usedTANs.append(value.tan)\n super(TANManager, self).__setitem__(key, value)\n\n def add(self, tan):\n \"\"\"See interfaces.ITANManager\"\"\"\n self.__setitem__(tan.tan, tan)\n\n def authenticateCredentials(self, credentials):\n \"\"\"See zope.app.authentication.interfaces.IAuthenticatorPlugin\"\"\"\n if not isinstance(credentials, basestring):\n return None\n if credentials not in self:\n return None\n return self.principalInfo(self.prefix+credentials)\n\n def principalInfo(self, id):\n \"\"\"See zope.app.authentication.interfaces.IAuthenticatorPlugin\"\"\"\n if not id.startswith(self.prefix):\n return None\n id = id[len(self.prefix):]\n if id not in self:\n return None\n internal = self[id]\n clone = internal.__class__.__new__(internal.__class__)\n clone.__dict__.update(internal.__dict__)\n clone.id = self.prefix + clone.id\n zope.interface.directlyProvides(clone, IPrincipalInfo)\n return clone\n\n def search(self, query, start=None, batch_size=None):\n \"\"\"See zope.app.authentication.interfaces.IQuerySchemaSearch\"\"\"\n search = query.get('search')\n if search is None:\n return\n search = search.lower()\n n = 1\n for i, value in enumerate(self.values()):\n if ((value.title and search in value.title.lower()) or\n (value.description and search in value.description.lower()) or\n search in value.tan.lower()):\n if not ((start is not None and i < start)\n or (batch_size is not None and n > batch_size)):\n n += 1\n yield self.prefix + value.tan\n\n\n@zope.component.adapter(IAuthenticatedPrincipalCreated)\ndef assignTAN(event):\n \"\"\"Assign a TAN as group to a principal.\"\"\"\n credentials = session.SessionCredentialsPlugin()\n tan = credentials.extractCredentials(event.request)\n if tan is None:\n return\n elif event.principal.id.endswith(tan):\n # The principal is the TAN\n return\n # Look in the plugins for TAN managers and assign the TAN\n for pluginName in event.authentication.authenticatorPlugins:\n plugin = event.authentication[pluginName]\n if not interfaces.ITANManager.providedBy(plugin):\n continue\n tanInfo = plugin.get(tan)\n if tanInfo is None:\n continue\n # The principal is not allowed to use that TAN\n if (tanInfo.allowedPrincipals is not None and\n event.principal.id not in tanInfo.allowedPrincipals):\n return\n event.principal.groups.append(event.authentication.prefix + tan)\n","sub_path":"z3c.tan/trunk/src/z3c/tan/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":4466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"547185293","text":"from flask import Blueprint, render_template, request, flash\nfrom forms import ContactForm\nimport google.appengine.api.mail as mail\n\nblueprint = Blueprint('contact', __name__, template_folder='templates')\n\n@blueprint.route('/contact', methods=['GET', 'POST'])\ndef contact():\n form = ContactForm()\n\n if request.method == 'POST':\n if form.validate() == False:\n flash('All fields are required.')\n return render_template('contact.html', form=form)\n else:\n # mail.send_mail(sender='matt.s.levan@gmail.com',\n # #to='Matt Levan ',\n # to='Matt Levan ',\n # subject=form.subject.data,\n # body=form.message.data)\n mail.send_mail(sender='matt.s.levan@gmail.com',\n to='Mike Levan ',\n subject=form.subject.data,\n body=form.email.data + '\\n' + form.message.data)\n return render_template('contact.html', success=True, form=form)\n elif request.method == 'GET':\n return render_template('contact.html', form=form)\n\n\nfrom app import app\n\napp.register_blueprint(blueprint)\n","sub_path":"apps/contact/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1305,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"437091852","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 ('login', '0008_user_user_id'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Message',\n fields=[\n ('index', models.AutoField(serialize=False, primary_key=True)),\n ('send', models.CharField(max_length=100)),\n ('rcv', models.CharField(max_length=100)),\n ('title', models.CharField(default=None, max_length=200)),\n ('content', models.CharField(default=None, max_length=500)),\n ('msg_type', models.CharField(default=None, max_length=10)),\n ('read_msg_yn', models.BooleanField(default=True)),\n ('send_date', models.DateTimeField(verbose_name=b'send date')),\n ('user', models.ForeignKey(to='login.User')),\n ],\n ),\n ]\n","sub_path":"wsgi/message/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"324378505","text":"import os\nfrom code_meta_data import SourceCodeMetadata\n\n\nclass JavaFileInspector:\n\n def __init__(self, directory=None):\n if directory is None:\n self.directory = os.getcwd()\n else:\n self.directory = directory\n\n # get all the files in the provided directory with the file extension .java\n # returns a dictionary of all the files containing the full file path and the file name\n def __get_all_files(self):\n print(\"Getting files in the path \" + self.directory)\n file_list = []\n\n for root, directories, files in os.walk(self.directory):\n for file in files:\n if file.endswith(\".java\"):\n file_list.append(os.path.join(root, file))\n\n print(\"Found {} files in the path {}\".format(len(file_list), self.directory))\n return file_list\n\n @staticmethod\n def __get_comments_in_file(file):\n comments_in_file = [] # array to hold all comments in the file\n data = None # SourceCodeMetadata instance for this file\n file_text = \"\"\n\n for line in file:\n seq = (file_text, line)\n file_text = \"\".join(seq)\n\n line = line.strip().rstrip(\"\\n\") # remove white spaces & /n at the beginning and end of the line\n is_multiline = False\n\n if line.startswith(\"/*\"):\n is_multiline = True\n if data is None:\n data = SourceCodeMetadata(line.lstrip(\"/*\").rstrip(\"*/\").strip())\n else:\n data.append_comment(line)\n\n if line.startswith(\"*\"):\n if data is not None:\n is_multiline = True\n data.append_comment(line.lstrip(\"*\").strip())\n else:\n print(\"Omitted '{}' [Unknown comment - Starting with *] in file {}\".format(line, file))\n\n if line.endswith(\"*/\"):\n is_multiline = True\n if data is not None:\n string = line.lstrip(\"/*\").rstrip(\"*/\").strip()\n if data.comment != string:\n data.append_comment(string)\n\n comments_in_file.append(data)\n data = None\n else:\n print(\"Omitted '{}' [Unknown Comment] in file {}\".format(line, file))\n\n if not is_multiline:\n code, separator, comment = line.partition(\"//\")\n if len(separator) is not 0:\n comments_in_file.append(SourceCodeMetadata(comment))\n\n return comments_in_file\n\n # get a list of SourceCodeMetadata for the comments found in the java file\n def get_comments(self):\n file_list = self.__get_all_files()\n if len(file_list) == 0:\n print(\"Did not find any files to read\")\n return\n\n comments_data = {}\n for item in file_list:\n file = open(item, \"r\")\n comments_data[item] = JavaFileInspector.__get_comments_in_file(file)\n print(\"Found {} comments in file {}\".format(len(comments_data[item]), item))\n file.close()\n\n return comments_data\n","sub_path":"java_file_inspector.py","file_name":"java_file_inspector.py","file_ext":"py","file_size_in_byte":3178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"60682036","text":"#短作业优先\ndef SJF(jobs, index):\n lenlj = len(jobs)\n sumt = jobs[index]\n for i in range(0,lenlj):\n if jobs[i] < jobs[index] :\n sumt = sumt + jobs[i]\n elif jobs[i] == jobs[index] and i Worgen_Warrior: #checks to see which is the greatest choice chosen\r\n print(\"You should play as a PANDAREN MONK.\\n\"\r\n \"Pandaren Monks are a tough combination of healer and tank that is able to use buffs and debuffs\\n\"\r\n \"to give themselves or their allies an edge in battle.\\n \")\r\n TryAgain()\r\n\r\n elif Worgen_Warrior > Pandaren_Monk:\r\n print(\"You should play as a WORGEN WARRIOR.\\n\"\r\n \"Worgen Warriors are able to not only to soak a large amount of damage, but are also able to deliver \\n\"\r\n \"a great amount of damage in a quick amount of time as well.\\n\")\r\n TryAgain()\r\n\r\n else:\r\n print(\"\\nInconclusive amount of data. Going back a step...\\n\")\r\n Pandaren_Monk = 0\r\n Worgen_Warrior = 0 #resets the values back to 0 before continuing to retry\r\n Alliance_Tank() \r\n\r\n\r\n# THE ALLIANCE DPS ROLE\r\ndef Alliance_DPS():\r\n Pandaren_DeathKnight = 0\r\n NightElf_Rogue = 0\r\n NightElf_DemonHunter = 0\r\n Worgen_Warrior = 0\r\n Dwarf_Hunter = 0\r\n\r\n print(\"\\nYou have chosen the DPS role for the Alliance.\")\r\n YesOrNo = input(\"Is this what you wanted? (Y/N) \")\r\n if YesOrNo.lower() == 'y':\r\n print(\"Let's continue...\\n\")\r\n elif YesOrNo.lower() == 'n':\r\n print(\"Understood. Going back to role choice...\\n\")\r\n Alliance_Class_Questions()\r\n else:\r\n print(\"Invalid input...\\n\")\r\n Alliance_DPS()\r\n\r\n # Question 1 #\r\n question1_AllianceDPS = input(\"\\nQuestion 1:\\n\"\r\n \"What is your basic method of attacking?\\n\"\r\n \"(a) Close and brutal\\n\"\r\n \"(b) Silent but deadly\\n\"\r\n \"(c) Close and life stealing\\n \"\r\n \"(d) Close and quick\\n\"\r\n \"(e) At a distance\\n\"\r\n \"Choice: \")\r\n if question1_AllianceDPS.lower() == 'a':\r\n Pandaren_DeathKnight += 1\r\n elif question1_AllianceDPS.lower() == 'b':\r\n NightElf_Rogue += 1\r\n elif question1_AllianceDPS.lower() == 'c':\r\n NightElf_DemonHunter += 1\r\n elif question1_AllianceDPS.lower() == 'd':\r\n Worgen_Warrior += 1\r\n elif question1_AllianceDPS.lower() == 'e':\r\n Dwarf_Hunter += 1\r\n else:\r\n print(\"\\nInvalid entry. Going back a step...\\n\")\r\n Pandaren_DeathKnight = 0\r\n NightElf_Rogue = 0\r\n NightElf_DemonHunter = 0\r\n Worgen_Warrior = 0\r\n Dwarf_Hunter = 0\r\n Alliance_DPS()\r\n\r\n # Question 2 #\r\n question2_AllianceDPS = input(\"\\nQuestion 2:\\n\"\r\n \"What skills do you like to implement to your attack patterns?\\n\"\r\n \"(a) Debuffs to enemies and buffs to myself\\n\"\r\n \"(b) Poisons to the enemy and potions to myself\\n\"\r\n \"(c) Speed boosts and life/mana stealing\\n \"\r\n \"(d) Speed boosts and stuns\\n\"\r\n \"(e) Animal companions and long range stuns\\n\"\r\n \"Choice: \")\r\n if question2_AllianceDPS.lower() == 'a':\r\n Pandaren_DeathKnight += 1\r\n elif question2_AllianceDPS.lower() == 'b':\r\n NightElf_Rogue += 1\r\n elif question2_AllianceDPS.lower() == 'c':\r\n NightElf_DemonHunter += 1\r\n elif question2_AllianceDPS.lower() == 'd':\r\n Worgen_Warrior += 1\r\n elif question2_AllianceDPS.lower() == 'e':\r\n Dwarf_Hunter += 1\r\n else:\r\n print(\"\\nInvalid entry. Going back a step...\\n\")\r\n Pandaren_DeathKnight = 0\r\n NightElf_Rogue = 0\r\n NightElf_DemonHunter = 0\r\n Worgen_Warrior = 0\r\n Dwarf_Hunter = 0\r\n Alliance_DPS()\r\n\r\n # Question 3 #\r\n question3_AllianceDPS = input(\"\\nQuestion 3:\\n\"\r\n \"Are you more comfortable in a group or alone?\\n\"\r\n \"(a) Alone\\n\"\r\n \"(b) With a group if I'm the only one of my class\\n\"\r\n \"(c) I prefer a group\\n \"\r\n \"(d) Either/Or\\n\"\r\n \"(e) In a group\\n\"\r\n \"Choice: \")\r\n if question3_AllianceDPS.lower() == 'a':\r\n Pandaren_DeathKnight += 1\r\n elif question3_AllianceDPS.lower() == 'b':\r\n NightElf_Rogue += 1\r\n elif question3_AllianceDPS.lower() == 'c':\r\n NightElf_DemonHunter += 1\r\n elif question3_AllianceDPS.lower() == 'd':\r\n Worgen_Warrior += 1\r\n elif question3_AllianceDPS.lower() == 'e':\r\n Dwarf_Hunter += 1\r\n else:\r\n print(\"\\nInvalid input. Going back a step...\\n\")\r\n Pandaren_DeathKnight = 0\r\n NightElf_Rogue = 0\r\n NightElf_DemonHunter = 0\r\n Worgen_Warrior = 0\r\n Dwarf_Hunter = 0\r\n Alliance_DPS()\r\n\r\n # Results #\r\n if Pandaren_DeathKnight > NightElf_Rogue & NightElf_DemonHunter & Worgen_Warrior & Dwarf_Hunter:\r\n print(\"\\nYou should play as a PANDAREN DEATH KNIGHT\\n\"\r\n \"The Death Knight damage output combined with the buffs and other abilities from the\\n\"\r\n \"Pandaren race are sure to make the Pandaren Death Knight a force to be reckoned with\\n\"\r\n \"on the battlefield.\\n\")\r\n TryAgain()\r\n\r\n elif NightElf_Rogue > Pandaren_DeathKnight & NightElf_DemonHunter & Worgen_Warrior & Dwarf_Hunter:\r\n print(\"\\nYou should play as a NIGHT ELF ROGUE.\\n\"\r\n \"Night elves are able to slip into the shadows easier making them the perfect race\\n\"\r\n \"for those that love dealing damage from the shadows.\\n\")\r\n TryAgain()\r\n\r\n elif NightElf_DemonHunter > Pandaren_DeathKnight & NightElf_Rogue & Worgen_Warrior & Dwarf_Hunter:\r\n print(\"\\nYou should play as a NIGHT ELF DEMON HUNTER\\n\"\r\n \"Night Elf Demon Hunters are able to get an addional critical hit boost as well as leech\\n\"\r\n \"health from their enemies making. This combined with their increased attack speed abilities\\n\"\r\n \"make them ideal for most raids.\\n\")\r\n TryAgain()\r\n\r\n elif Worgen_Warrior > Pandaren_DeathKnight & NightElf_Rogue & NightElf_DemonHunter & Dwarf_Hunter:\r\n print(\"\\nYou should play as WORGEN WARRIOR.\\n\"\r\n \"As a Worgen Warrior you are more resistant to nature and shadow damage which helps out\\n\"\r\n \"against fighting mages and warlocks. They're bonus movement speed makes moving from target\\n\"\r\n \"to target much easier as well.\\n\")\r\n TryAgain()\r\n\r\n elif Dwarf_Hunter > Pandaren_DeathKnight & NightElf_Rogue & NightElf_DemonHunter & Worgen_Warrior:\r\n print(\"\\nYou should play as a DWARF HUNTER.\\n\"\r\n \"Dwarf Hunters are very skilled in trickling down enemies from afar. With their pets able\\n\"\r\n \"to even tank damage, skilled hunters can flank and take down the largest of foes from afar.\\n\")\r\n TryAgain()\r\n\r\n else:\r\n print(\"\\nInconclusive amount of data. Going back a step...\\n\")\r\n Pandaren_DeathKnight = 0\r\n NightElf_Rogue = 0\r\n NightElf_DemonHunter = 0\r\n Worgen_Warrior = 0\r\n Dwarf_Hunter = 0\r\n Alliance_DPS()\r\n\r\n\r\n# THE ALLIANCE HEALER ROLE\r\ndef Alliance_Healer():\r\n Draenei_Paladin = 0\r\n Human_Priest = 0\r\n\r\n print(\"\\nYou have chosen the healer role for the Alliance.\")\r\n YesOrNo = input(\"Is this what you wanted? (Y/N) \")\r\n if YesOrNo.lower() == 'y':\r\n print(\"Let's continue...\\n\")\r\n elif YesOrNo.lower() == 'n':\r\n print(\"Understood. Going back to role choice...\\n\")\r\n Alliance_Class_Questions()\r\n else:\r\n print(\"Invalid input...\\n\")\r\n Alliance_Healer()\r\n\r\n # Question 1 #\r\n question1_AllianceHealer = input(\"\\nQuestion 1:\"\r\n \"\\nWhat is your preferred method of healing?\\n\"\r\n \"(a) Area of Effect buffs and healing\\n\"\r\n \"(b) Constant/Regular healing\\n\"\r\n \"Choice: \")\r\n if question1_AllianceHealer.lower() == 'a':\r\n Draenei_Paladin += 1\r\n elif question1_AllianceHealer.lower() == 'b':\r\n Human_Priest += 1\r\n else:\r\n print(\"\\nInvalid entry. Going back a step...\\n\")\r\n Draenei_Paladin = 0\r\n Human_Priest = 0\r\n Alliance_Healer()\r\n\r\n # Question 2 #\r\n question2_AllianceHealer = input(\"\\nQuestion 2:\"\r\n \"\\nDo you prefer buffs or strictly healing?\\n\"\r\n \"(a) Buffs\\n\"\r\n \"(b) Strictly healing\\n\"\r\n \"Choice: \")\r\n if question2_AllianceHealer.lower() == 'a':\r\n Draenei_Paladin += 1\r\n elif question2_AllianceHealer.lower() == 'b':\r\n Human_Priest += 1\r\n else:\r\n print(\"\\nInvalid entry. Going back a step...\\n\")\r\n Draenei_Paladin = 0\r\n Human_Priest = 0\r\n Alliance_Healer()\r\n\r\n # Question 3 #\r\n question3_AllianceHealer = input(\"\\nQuestion 3:\\n\"\r\n \"Which of these sounds more appealing to your style of play?\\n\"\r\n \"(a) Shields and giving damage when taking damage\\n\"\r\n \"(b) Removing lethal magic in an area and boosting the\"\r\n \" abilities of other healers\\n\"\r\n \"Choice: \")\r\n if question3_AllianceHealer.lower() == 'a':\r\n Draenei_Paladin += 1\r\n elif question3_AllianceHealer.lower() == 'b':\r\n Human_Priest += 1\r\n else:\r\n print(\"\\nInvalid entry. Going back a step...\\n\")\r\n Draenei_Paladin = 0\r\n Human_Priest = 0\r\n Alliance_Healer()\r\n\r\n # Results #\r\n if Draenei_Paladin > Human_Priest:\r\n print(\"\\nYou should play as a DRAENEI PALADIN.\\n\"\r\n \"Draenei have the ability to heal themselves and others over time. Add the Paladin\\n\"\r\n \"abilities to give buffs and they can be an asset to raids and maybe even PVP.\\n\")\r\n TryAgain()\r\n\r\n elif Human_Priest > Draenei_Paladin:\r\n print(\"\\nYou should play as a HUMAN PRIEST.\\n\"\r\n \"Humans have the natural ability to break out of stuns. Added with a Paladin's ability to heal\\n\"\r\n \"at a steady rate and Human Paladins will be a huge asset in raids.\\n\")\r\n TryAgain()\r\n\r\n else:\r\n print(\"\\nInconclusive amount of data. Going back a step...\\n\")\r\n Draenei_Paladin = 0\r\n Human_Priest = 0\r\n Alliance_Healer()\r\n\r\n\r\n################################## Horde Questions #######################################\r\n\r\n# CHOOSING A ROLE --HORDE--\r\ndef Horde_Class_Questions():\r\n print(\"\\nWelcome to the Horde, new player. It is now time for you to choose a role in which you will play as.\\n\")\r\n Horde_Role_Choice = input(\"\\nRoles to choose from: Tank, DPS (Damage), Healer...\\n\"\r\n \"(a) Tank: Tanks are players that are designed to take as much damage as possible.\\n\"\r\n \"Catch the attention of the enemy and leave the damage roles to take care of the\\n\"\r\n \"enemy/enemies.\\n\"\r\n \"(b) DPS: With the Tanks acting as the shields, the dps are the sword of the group.\\n\"\r\n \"DPS roles are designed to inflict as much damage as possible.\\n\"\r\n \"(c) Healers: Healers need to make sure everyone is alive and well. There are \\n\"\r\n \"healers that can heal in multiple ways whether it be directly or indirectly.\\n\"\r\n \"What will you choose? Role: \")\r\n if Horde_Role_Choice.lower() == 'a':\r\n Horde_Tank()\r\n elif Horde_Role_Choice.lower() == 'b':\r\n Horde_DPS()\r\n elif Horde_Role_Choice.lower() == 'c':\r\n Horde_Healer()\r\n else:\r\n print(\"\\nNot enough data, taking you back a step\")\r\n Horde_Class_Questions()\r\n\r\n\r\n\r\n# THE HORDE TANK ROLE\r\ndef Horde_Tank():\r\n Orc_Warrior = 0\r\n Pandaren_Monk = 0\r\n\r\n print(\"\\nYou have chosen the Tank role for the Horde.\")\r\n YesOrNo = input(\"Is this what you wanted? (Y/N) \")\r\n if YesOrNo.lower() == 'y':\r\n print(\"Let's continue...\\n\")\r\n elif YesOrNo.lower() == 'n':\r\n print(\"Understood. Taking you back to role choice...\\n\")\r\n Horde_Class_Questions()\r\n else:\r\n print(\"Invalid input...\\n\")\r\n Horde_Tank()\r\n\r\n # Question 1 #\r\n question1_HordeTank = input(\"\\nQuestion 1:\\n\"\r\n \"Which of these choices defines your tanking style best?\\n\"\r\n \"(a) Soak damage AND attack each enemy one at a time\\n\"\r\n \"(b) Soak damage AND apply status effects to groups of enemies\\n\"\r\n \"Choice: \")\r\n if question1_HordeTank.lower() == 'a':\r\n Orc_Warrior += 1\r\n elif question1_HordeTank.lower() == 'b':\r\n Pandaren_Monk += 1\r\n else:\r\n print(\"\\nInvalid input, going back a step\\n\")\r\n Orc_Warrior = 0\r\n Pandaren_Monk = 0\r\n Horde_Tank()\r\n\r\n # Question 2 #\r\n question2_HordeTank = input(\"Question 2: \\n\"\r\n \"Do you prefer to...\\n\"\r\n \"(a) Have damage focused on you as you both you and your team attacks a common foe\\n\"\r\n \"(b) Have damage focused on you as you weaken your enemy and buff your allies\\n\"\r\n \"Choice: \")\r\n if question2_HordeTank.lower() == 'a':\r\n Orc_Warrior += 1\r\n elif question2_HordeTank.lower() == 'b':\r\n Pandaren_Monk += 1\r\n else:\r\n print(\"\\nInvalid input, going back a step...\\n\")\r\n Orc_Warrior = 0\r\n Pandaren_Monk = 0\r\n Horde_Tank()\r\n\r\n # Question 3 #\r\n question3_HordeTank = input(\"Question 3: \\n\"\r\n \"Do you prefer gaining experience at an increased or regular rate when resting?\\n\"\r\n \"(a) Regular rate\\n\"\r\n \"(b) Increased rate\\n\"\r\n \"Choice: \")\r\n if question3_HordeTank.lower() == 'a':\r\n Orc_Warrior += 1\r\n elif question3_HordeTank.lower() == 'b':\r\n Pandaren_Monk += 1\r\n else:\r\n print(\"\\nInvalid input, going back a step...\\n\")\r\n Orc_Warrior = 0\r\n Pandaren_Monk = 0\r\n Horde_Tank()\r\n\r\n # Results #\r\n if Orc_Warrior > Pandaren_Monk:\r\n print(\"\\nYou should play as an ORC WARRIOR\\n\"\r\n \"Orc warriors are capable of withstanding massive amounts of damage as well as\\n\"\r\n \"stunning and breaking enemy defenses making them suitable for soaking and giving damage.\\n\")\r\n TryAgain()\r\n\r\n elif Pandaren_Monk > Orc_Warrior:\r\n print(\"\\nYou should play as a PANDAREN MONK\\n\"\r\n \"Pandaren Monks are a tough combination of healer and tank that are able to use buffs and debuffs\\n\"\r\n \"to give themselves or their allies an edge in battle.\\n\")\r\n TryAgain()\r\n\r\n else:\r\n print(\"\\nInconclusive amount of data. Going back a step...\\n\")\r\n Orc_Warrior = 0\r\n Pandaren_Monk = 0\r\n Horde_Tank()\r\n\r\n\r\n# THE HORDE DPS ROLE\r\ndef Horde_DPS():\r\n Orc_Warrior = 0\r\n Goblin_Rogue = 0\r\n Pandaren_DeathKnight = 0\r\n Orc_Shaman = 0\r\n BloodElf_Mage = 0\r\n\r\n print(\"\\nYou have chosen the DPS role for the Horde.\")\r\n YesOrNo = input(\"Is this what you wanted? (Y/N)\")\r\n if YesOrNo.lower() == \"y\":\r\n print(\"Let's continue...\\n\")\r\n elif YesOrNo.lower() == 'n':\r\n print(\"Understood. Going back to role choice...\\n\")\r\n Horde_Class_Questions()\r\n else:\r\n print(\"Invalid input...\\n\")\r\n Horde_DPS()\r\n\r\n # Question 1 #\r\n question1_HordeDPS = input(\"\\nQuestion 1: \\n\"\r\n \"How would you describe your preferred method of attack?\\n\"\r\n \"(a) Heavy and all out\\n\"\r\n \"(b) Quick and quiet\\n\"\r\n \"(c) Through status effects\\n\"\r\n \"(d) Ranged and debuff enemies\\n\"\r\n \"(e) Ranged focusing on critical strikes\\n\"\r\n \"Choice: \")\r\n if question1_HordeDPS.lower() == 'a':\r\n Orc_Warrior += 1\r\n elif question1_HordeDPS.lower() == 'b':\r\n Goblin_Rogue += 1\r\n elif question1_HordeDPS.lower() == 'c':\r\n Pandaren_DeathKnight += 1\r\n elif question1_HordeDPS.lower() == 'd':\r\n Orc_Shaman += 1\r\n elif question1_HordeDPS.lower() == 'e':\r\n BloodElf_Mage += 1\r\n else:\r\n print(\"\\nInvalid input, going back a step\\n\")\r\n Orc_Warrior = 0\r\n Goblin_Rogue = 0\r\n Pandaren_DeathKnight = 0\r\n Orc_Shaman = 0\r\n BloodElf_Mage = 0\r\n Horde_DPS()\r\n\r\n # Question 2 #\r\n question2_HordeDPS = input(\"\\nQuestion 2: \\n\"\r\n \"What skills would you implement in your attack patterns?\\n\"\r\n \"(a) Stunning enemies and hitting them with heavy strikes\\n\"\r\n \"(b) Swiftly close in on a target and attack them unseen\\n\"\r\n \"(c) Put an enemy to sleep then strike them with heavy attacks\\n\"\r\n \"(d) Stay at a distance and focus on weakening your enemy\\n\"\r\n \"(e) Drain energy from your enemy and cast spells at a distance\\n\"\r\n \"Choice: \")\r\n if question2_HordeDPS.lower() == 'a':\r\n Orc_Warrior += 1\r\n elif question2_HordeDPS.lower() == 'b':\r\n Goblin_Rogue += 1\r\n elif question2_HordeDPS.lower() == 'c':\r\n Pandaren_DeathKnight += 1\r\n elif question2_HordeDPS.lower() == 'd':\r\n Orc_Shaman += 1\r\n elif question2_HordeDPS.lower() == 'e':\r\n BloodElf_Mage += 1\r\n else:\r\n print(\"\\nInvalid input, going back a step\\n\")\r\n Orc_Warrior = 0\r\n Goblin_Rogue = 0\r\n Pandaren_DeathKnight = 0\r\n Orc_Shaman = 0\r\n BloodElf_Mage = 0\r\n Horde_DPS()\r\n\r\n # Question 3 #\r\n question3_HordeDPS = input(\"\\nQuestion 3: \\n\"\r\n \"Where would your position be in a battle/raid?\\n\"\r\n \"(a) Front lines, tanking damage and striking first\\n\"\r\n \"(b) Away from the rest of the group, striking enemies silently\\n\"\r\n \"(c) Front lines casting status effects and using melee attacks\\n\"\r\n \"(d) Middle of the group, debuffing enemies and using ranged attacks\\n\"\r\n \"(e) In the middle, sapping enemies of their mana and using long ranged attacks\\n\"\r\n \"Choice: \")\r\n if question3_HordeDPS.lower() == 'a':\r\n Orc_Warrior += 1\r\n elif question3_HordeDPS.lower() == 'b':\r\n Goblin_Rogue += 1\r\n elif question3_HordeDPS.lower() == 'c':\r\n Pandaren_DeathKnight += 1\r\n elif question3_HordeDPS.lower() == 'd':\r\n Orc_Shaman += 1\r\n elif question3_HordeDPS.lower() == 'e':\r\n BloodElf_Mage += 1\r\n else:\r\n print(\"\\nInvalid input, going back a step\\n\")\r\n Orc_Warrior = 0\r\n Goblin_Rogue = 0\r\n Pandaren_DeathKnight = 0\r\n Orc_Shaman = 0\r\n BloodElf_Mage = 0\r\n Horde_DPS()\r\n\r\n # Question 3 #\r\n if Orc_Warrior > Goblin_Rogue & Pandaren_DeathKnight & Orc_Shaman & BloodElf_Mage:\r\n print(\"\\nYou should play as an ORC WARRIOR\\n\"\r\n \"Orc warriors are capable of withstanding massive amounts of damage as well as\\n\"\r\n \"stunning and breaking enemy defenses making them suitable for soaking and giving damage.\\n\")\r\n TryAgain()\r\n\r\n elif Goblin_Rogue > Orc_Warrior & Pandaren_DeathKnight & Orc_Shaman & BloodElf_Mage:\r\n print(\"\\nYou should play as a GOBLIN ROGUE\\n\"\r\n \"Goblin's ability to jump far distances makes for great swift damage classes.\\n\"\r\n \"Combined with a rogue's high damage output, a goblin rogue makes for a fantastic dps.\\n\")\r\n TryAgain()\r\n\r\n elif Pandaren_DeathKnight > Orc_Warrior & Goblin_Rogue & Orc_Shaman & BloodElf_Mage:\r\n print(\"\\nYou should play as a PANDAREN DEATH KNIGHT\\n\"\r\n \"The Death Knight damage output combined with the buffs and other abilities from the\\n\"\r\n \"Pandaren race are sure to make the Pandaren Death Knight a force to be reckoned with\\n\"\r\n \"on the battlefield.\\n\")\r\n TryAgain()\r\n\r\n elif Orc_Shaman > Orc_Warrior & Goblin_Rogue & Pandaren_DeathKnight & BloodElf_Mage:\r\n print(\"\\nYou should play as an ORC SHAMAN\\n\"\r\n \"An Orc Shaman's ability to disable enemies as well as enchant weaponry and allies\\n\"\r\n \"makes them a crucial part to any raid or PvP group considering their abilities of sabotage.\\n\")\r\n TryAgain()\r\n\r\n elif BloodElf_Mage > Orc_Warrior & Goblin_Rogue & Pandaren_DeathKnight & Orc_Shaman:\r\n print(\"\\nYou should play as a BLOOD ELF MAGE\\n\"\r\n \"Blood Elf Mages are caable of quickly restoring mana to themselves for quicker and longer-lasting\\n\"\r\n \"damage from a distance, making Blood Elf Mages a good long range DPS character.\\n\")\r\n TryAgain()\r\n\r\n else:\r\n print(\"\\nInconclusive amount of data. Going back a step...\\n\")\r\n Orc_Warrior = 0\r\n Goblin_Rogue = 0\r\n Pandaren_DeathKnight = 0\r\n Orc_Shaman = 0\r\n BloodElf_Mage = 0\r\n Horde_DPS()\r\n\r\n\r\n# THE HORDE HEALER ROLE\r\ndef Horde_Healer():\r\n Undead_Warlock = 0\r\n Troll_Shamman = 0\r\n\r\n print(\"You have chosen the Healer role for the Horde.\\n\")\r\n YesOrNo = input(\"Is this what you wanted? (Y/N)\\n\"\r\n \"Choice: \")\r\n if YesOrNo == 'y':\r\n print(\"Let's continue...\\n\")\r\n elif YesOrNo == 'n':\r\n print(\"Understood. Going back to role choice...\\n\")\r\n Horde_Class_Questions\r\n else:\r\n print(\"Invalid input...\\n\")\r\n Horde_Healer\r\n\r\n # Question 1 #\r\n question1_HordeHealer = input(\"\\nQuestion 1:\\n\"\r\n \"How would you describe your healing style?\\n\"\r\n \"(a) Direct healing\\n\"\r\n \"(b) Indirect healing through area of effect\\n\"\r\n \"Choice: \")\r\n if question1_HordeHealer.lower() == 'a':\r\n Undead_Warlock += 1\r\n elif question1_HordeHealer.lower() == 'b':\r\n Troll_Shamman += 1\r\n else:\r\n print(\"\\nInvalid input, going back a step\\n\")\r\n Undead_Warlock = 0\r\n Troll_Shamman = 0\r\n Horde_Healer()\r\n\r\n # Question 2 #\r\n question2_HordeHealer = input(\"\\nQuestion 2:\\n\"\r\n \"You would prefer to...\\n\"\r\n \"(a) Using the environment around me to create oppertunities and advantages\\n\"\r\n \"(b) Use my own items/abilities to crate oppertunities and advantages for me\\n\"\r\n \"Choice: \")\r\n if question2_HordeHealer.lower() == 'a':\r\n Undead_Warlock += 1\r\n elif question2_HordeHealer.lower() == 'b':\r\n Troll_Shamman += 1\r\n else:\r\n print(\"\\nInvalid input, going back a step\\n\")\r\n Undead_Warlock = 0\r\n Troll_Shamman = 0\r\n Horde_Healer()\r\n\r\n # Question 3 #\r\n question3_HordeHealer = input(\"\\nQuestion 3:\\n\"\r\n \"How would you describe your attacking style?\\n\"\r\n \"(a) From a distance\\n\"\r\n \"(b) Up close witht the help of buffs and debuffs\\n\"\r\n \"Choice: \")\r\n if question3_HordeHealer.lower() == 'a':\r\n Undead_Warlock += 1\r\n elif question3_HordeHealer.lower() == 'b':\r\n Troll_Shamman += 1\r\n else:\r\n print(\"\\nInvalid input, going back a step\\n\")\r\n Undead_Warlock = 0\r\n Troll_Shamman = 0\r\n Horde_Healer()\r\n\r\n if Undead_Warlock > Troll_Shamman:\r\n print(\"\\nYou should play as an UNDEAD WARLOCK\\n\"\r\n \"Undead Warlocks have the ability to suck the health and mana out of dead bodies\\n\"\r\n \"around them, making them great healers for large raids with smaller/weaker mobs.\\n\")\r\n TryAgain()\r\n\r\n elif Troll_Shamman > Undead_Warlock:\r\n print(\"\\nYou should play as TROLL SHAMAN\\n\"\r\n \"Troll Shamans can heal party members over large distances with the uses of healing\\n\"\r\n \"totems they can summon. Thi smakes them ideal for both raids and PvP quests.\")\r\n TryAgain()\r\n\r\n else:\r\n print(\"\\nInconclusive amount of data. Going back a step...\\n\")\r\n Undead_Warlock = 0\r\n Troll_Shamman = 0\r\n Horde_Healer()\r\n\r\n\r\n################################## Faction Question #######################################\r\n\r\ndef Faction_Choice():\r\n print(\"\\nThe World of Warcraft Character Chooser Quiz\\nA Python Program by Derrick Demers\")\r\n faction_question = input(\"\\nIn the World of Warcraft, there are two sides:\\n\\n\"\r\n \"The Alliance: \\n\"\r\n \"The Alliance consists of powerful cultures and peoples that are loyal to the alliance \\n\"\r\n \"by their deep commitments to the concepts of justice and nobility. The races and \\n\"\r\n \"members of the Alliance are all courageous and noble and do all they can to preserve \\n\"\r\n \"order in the land of Azeroth. The Alliance are led by their king, High King \\n \"\r\n \"Anduin Wrynn son of the fallen Varian Wrynn. \\n\\n\"\r\n \"The Horde: \\n\"\r\n \"The Horde is a faction led by a conglomerate of outsiders and survivors of prejudices \\n\"\r\n \"who have overcome obstacles by creating bonds with each other, fighting together as \\n\"\r\n \"family or comrades, or creating uneasy alliances. The Horde is currently under command \\n\"\r\n \"by the current Warchief Slyvanas Windrunner, a Forsaken \\n\"\r\n \"(currently undead, previously High Elf).\\n\\n\"\r\n \"So new player, which faction will you choose?\\n\"\r\n \"(a) Alliance\\n\"\r\n \"or\\n\"\r\n \"(b) Horde\\n\"\r\n \"(q) Exit the program\\n\")\r\n\r\n if faction_question.lower() == 'a':\r\n Alliance_Class_Questions()\r\n\r\n elif faction_question.lower() == 'b':\r\n Horde_Class_Questions()\r\n\r\n elif faction_question.lower() == 'q':\r\n print(\"\\nThank you for using the program\\n\"\r\n \"Farewell, adventurer...\\n\")\r\n return\r\n\r\n else:\r\n print(\"\\nInvalid input, please try again...\")\r\n Faction_Choice()\r\n\r\n\r\n################################## Where the program begins #######################################\r\n\r\nFaction_Choice()","sub_path":"PythonProgram.py","file_name":"PythonProgram.py","file_ext":"py","file_size_in_byte":32781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"56894988","text":"import requests\nfrom decouple import config\n\ngoogle_key= config(\"GOOGLE_API_KEY\")\napi_url=\"https://translation.googleapis.com/language/translate/v2\"\n\ndata={\n 'q':\"안녕하세요\",\n 'source': 'ko',\n 'target': 'en'\n}\n\nresponse=requests.post(f'{api_url}?key={google_key}',data).json()\nprint(response)","sub_path":"chatbot/google_translate.py","file_name":"google_translate.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"488400879","text":"import tensorflow as tf\nimport numpy as np\n\nclass myCharClassifier(object):\n def __init__(self,num_classes,is_regular):\n self.num_classes=num_classes\n self.is_regular=is_regular\n\n #保证均值为0,范围在[-1,1]\n def preprocess(self,inputs):\n processed_inputs = tf.to_float(inputs)\n processed_inputs = tf.subtract(processed_inputs,128.0)\n processed_inputs = tf.div(processed_inputs, 128)\n return processed_inputs\n\n def get_variable_with_l2_loss(self, shape, stddev, wl, name):\n biases_num=shape[-1]\n var = tf.Variable(tf.truncated_normal(shape=shape, stddev=stddev), name=name+\"weights\")\n biases=tf.get_variable(name+\"_biases\",shape=[biases_num],dtype=tf.float32)\n if wl is not None:\n var_l2_loss = tf.multiply(tf.nn.l2_loss(var), wl, name=name+\"_l2_loss\")\n tf.add_to_collection(\"Loss\", var_l2_loss)\n return var,biases\n\n def inference(self,preprocessed_inputs):\n shape = preprocessed_inputs.get_shape().as_list()\n height, width, num_channels = shape[1:]\n\n #卷积参数\n conv1_weights ,conv1_biases= self.get_variable_with_l2_loss([3, 3, num_channels, 32],5e-2, None, 'conv1')\n conv2_weights ,conv2_biases = self.get_variable_with_l2_loss([3, 3, 32, 32],5e-2, None, 'conv2')\n conv3_weights ,conv3_biases= self.get_variable_with_l2_loss([3, 3, 32, 64], 5e-2, None, 'conv3')\n conv4_weights ,conv4_biases = self.get_variable_with_l2_loss([3, 3, 64, 64],5e-2, None, 'conv4')\n conv5_weights ,conv5_biases = self.get_variable_with_l2_loss([3, 3, 64, 128],5e-2, None, 'conv5')\n conv6_weights,conv6_biases = self.get_variable_with_l2_loss([3, 3, 128, 128],5e-2, None, 'conv6_biases')\n\n #开始卷积\n net = preprocessed_inputs\n net = tf.nn.conv2d(net, conv1_weights, strides=[1, 1, 1, 1], padding='SAME')\n net = tf.nn.relu(tf.nn.bias_add(net, conv1_biases))\n\n net = tf.nn.conv2d(net, conv2_weights, strides=[1, 1, 1, 1],padding='SAME')\n net = tf.nn.relu(tf.nn.bias_add(net, conv2_biases))\n net = tf.nn.max_pool(net, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],padding='SAME')\n\n net = tf.nn.conv2d(net, conv3_weights, strides=[1, 1, 1, 1],padding='SAME')\n net = tf.nn.relu(tf.nn.bias_add(net, conv3_biases))\n\n net = tf.nn.conv2d(net, conv4_weights, strides=[1, 1, 1, 1], padding='SAME')\n net = tf.nn.relu(tf.nn.bias_add(net, conv4_biases))\n net = tf.nn.max_pool(net, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1],padding='SAME')\n\n net = tf.nn.conv2d(net, conv5_weights, strides=[1, 1, 1, 1], padding='SAME')\n net = tf.nn.relu(tf.nn.bias_add(net, conv5_biases))\n\n net = tf.nn.conv2d(net, conv6_weights, strides=[1, 1, 1, 1],padding='SAME')\n net = tf.nn.relu(tf.nn.bias_add(net, conv6_biases))\n\n #展开成向量形式以供全连接\n flat_shape= net.get_shape().as_list()\n flat_height, flat_width,channals=flat_shape[1:]\n flat_size = flat_height * flat_width * channals\n net = tf.reshape(net, shape=[-1, flat_size])\n\n #全连接参数\n fc7_weights,fc7_biases = self.get_variable_with_l2_loss([flat_size, 512],5e-2, 0.002, 'fc7')\n fc8_weights,fc8_biases = self.get_variable_with_l2_loss([512, 512],5e-2, 0.002, 'fc8')\n fc9_weights,fc9_biases = self.get_variable_with_l2_loss([512, self.num_classes],5e-2, 0.002, 'fc9_weights')\n\n #全连接\n net = tf.nn.relu(tf.add(tf.matmul(net, fc7_weights), fc7_biases))\n net = tf.nn.relu(tf.add(tf.matmul(net, fc8_weights), fc8_biases))\n net = tf.add(tf.matmul(net, fc9_weights), fc9_biases)\n\n #返回最纯粹和原始的网络输出(不带softmax)\n return net\n\n def postprocess(self,logits):\n softmax=tf.nn.softmax(logits)\n classes=tf.cast(tf.argmax(softmax,axis=1),tf.int32)\n #softmax: N*num_classes ,classes:N*1\n #其中N为样本数\n return softmax,classes\n\n def loss(self,logits,labels):\n # tf.nn.sparse_softmax_cross_entropy_with_logits将元素值在[0,num_classes-1]范围的标签自动转为ont-hot形式,\n # 然后计算每个样本的损失,返回一个长度为N的向量,其中N为样本数\n # 交叉熵损失有log运算,为了防止出现0,则加一个微笑的正数(1e-8)\n # 其中logits是神经网络输出层的结果,而非softmax后的结果\n softmax_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n logits=logits+1e-8,labels=labels),name=\"softmax_loss\")\n tf.add_to_collection(\"Loss\",softmax_loss)\n loss_all=tf.add_n(tf.get_collection(\"Loss\"),name=\"total_loss\")\n\n return loss_all\n\n\n\n\n\n\n\n\n","sub_path":"Classification/myDigitClassifier/nets/myCharClassifier.py","file_name":"myCharClassifier.py","file_ext":"py","file_size_in_byte":4786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"272603965","text":"from __future__ import annotations\n\nfrom dataclasses import MISSING\nfrom dataclasses import dataclass\nfrom dataclasses import fields\nfrom datetime import datetime\nfrom typing import Any\nfrom typing import AnyStr\nfrom typing import Dict\nfrom typing import List\nfrom typing import Type\nfrom typing import TypeVar\n\nfrom os_credits.log import internal_logger\n\nfrom .helper import deserialize\nfrom .helper import serialize\n\nINFLUX_QUERY_DATE_FORMAT = \"%Y-%m-%d %H:%M:%S.%f\"\n\n_DEFINITELY_PAST = datetime.fromtimestamp(0)\n\n# PointType\nPT = TypeVar(\"PT\", bound=\"InfluxDBPoint\")\n\n\n@dataclass(frozen=True)\nclass InfluxDBPoint:\n \"\"\"Base class of all data models whose content is written or read from the InfluxDB.\n\n To define a data model as shown in the official InfluxDB Line Tutorial extend in the\n following way\n\n >>> from dataclasses import dataclass, field\n >>> from os_credits.influx.model import InfluxDBPoint\n >>> @dataclass(frozen=True)\n ... class Weather(InfluxDBPoint):\n ... location: str = field(metadata={'tag': True})\n ... temperature: int\n ... static_id: int = 5\n >>> from datetime import datetime\n >>> timestamp = datetime(2016, 6, 13, 19, 43, 50, 100400)\n >>> # the first two parameters are defined inside ``InfluxDBPoint``\n >>> weather = Weather('weather', timestamp, 'us-midwest', 82)\n >>> print(weather.to_lineprotocol())\n b'weather,location=us-midwest temperature=82 1465839830100399872'\n >>> Weather.from_lineprotocol(weather.to_lineprotocol()) == weather\n True\n\n We are using the ``metadata`` field of :class:`~dataclasses.dataclass` to indicate\n whether to store a date as field or as tag. The difference between them is that tags\n are indexed by InfluxDB. Attributes with a default value are currently ignored, if a\n change to this should be necessary, whether to skip an attribute or not should be\n indicated via the ``metadata``.\n\n All subclasses must also be frozen, since this base class is. Use the\n :func:`dataclasses.replace` method instead. Allows us to use the instances as\n dictionary keys.\n\n Unfortunately *InfluxDB* does store all timestamps as nanoseconds which are not\n natively supported by python. We are therefore losing some precision but this is\n negligible since the timestamps of *Prometheus* are only milliseconds.\n \"\"\"\n\n measurement: str\n \"\"\"The name of this measurement\"\"\"\n timestamp: datetime\n\n @classmethod\n def from_iterpoint(cls: Type[PT], values: List[Any], meta: Dict[str, str]) -> PT:\n \"\"\"Only intended to be passed to the ``iterpoints`` method of ``aioinflux`` to\n parse the points and construct valid InfluxDBPoint instances. See its\n documentation for a description of the contents of ``values`` and ``meta``.\n\n The metadata of dataclass attributes are used to parse and convert the necessary\n information, unknown values and tags are dropped.\n\n :param cls: Subclass of :class:`InfluxDBPoint` on which this method is called.\n Instances of this class will be tried to be constructed given the returned\n data from the InfluxDB and returned.\n \"\"\"\n measurement_name = meta[\"name\"]\n combined_dict = dict(zip(meta[\"columns\"], values))\n args: Dict[str, Any] = {\n \"measurement\": measurement_name,\n \"timestamp\": deserialize(combined_dict[\"time\"], datetime),\n }\n for f in fields(cls):\n if f.default is not MISSING:\n continue\n # values of this fields are already known\n if f.name in args:\n continue\n args[f.name] = deserialize(combined_dict[f.name], f)\n new_point = cls(**args)\n internal_logger.debug(\"Constructed %s\", new_point)\n return new_point\n\n @classmethod\n def from_lineprotocol(cls: Type[PT], influx_line_: AnyStr) -> PT:\n \"\"\"\n Creates a point from an InfluxDB Line, see\n https://docs.influxdata.com/influxdb/v1.7/write_protocols/line_protocol_tutorial/\n\n Deliberate usage of ``cls`` to allow and support potential subclassing. If the\n line contains more information than defined by ``cls`` the rest is simply\n ignored.\n\n >>> from os_credits.influx.model import InfluxDBPoint\n >>> line = b'weather,location=us-midwest temperature=82 1465839830100399872'\n >>> InfluxDBPoint.from_lineprotocol(line)\n InfluxDBPoint(measurement='weather', timestamp=datetime.datetime(2016, 6, 13, 19, 43, 50, 100400)) # noqa\n\n :param cls: Subclass on which this method is called. Instances of this class\n will be the return type.\n :param influx_line_: Influx Line to parse, either ``string`` or ``bytes``.\n :return: Instances of `cls`.\n :raises KeyError: Attribute of ``cls`` without default value not present in line\n \"\"\"\n if isinstance(influx_line_, bytes):\n influx_line = influx_line_.decode()\n else:\n influx_line = influx_line_\n internal_logger.debug(\"Converting InfluxDB Line `%s`\", influx_line)\n measurement_and_tag, field_set, timestamp_str = influx_line.strip().split()\n measurement_name, tag_set = measurement_and_tag.split(\",\", 1)\n tag_field_dict: Dict[str, str] = {}\n for tag_pair in tag_set.split(\",\"):\n tag_name, tag_value = tag_pair.split(\"=\", 1)\n tag_field_dict.update({tag_name: tag_value})\n for field_pair in field_set.split(\",\"):\n field_name, field_value = field_pair.split(\"=\", 1)\n tag_field_dict.update({field_name: field_value})\n # we know how to deserialize those\n args: Dict[str, Any] = {\n \"measurement\": measurement_name,\n \"timestamp\": deserialize(timestamp_str, datetime),\n }\n for f in fields(cls):\n # currently not serialized, see class documentation\n if f.default is not MISSING:\n continue\n # values of this fields are already known\n if f.name in args:\n continue\n is_tag = False\n if f.metadata and f.metadata.get(\"tag\", False):\n is_tag = True\n if f.name not in tag_field_dict:\n raise KeyError(\n f\"InfluxDB Line does not contain {'tag' if is_tag else 'field'} \"\n \"`{f.name}`\"\n )\n value = tag_field_dict[f.name]\n # string field values are quoted, strip them\n if not is_tag and isinstance(value, str):\n value = value.strip('\"')\n args[f.name] = deserialize(value, f)\n new_point = cls(**args)\n internal_logger.debug(\"Constructed %s\", new_point)\n return new_point\n\n def to_lineprotocol(self) -> bytes:\n \"\"\"Serializes this (subclass of) :class:`InfluxDBPoint` to its representation in\n Influx Line Protocol.\n\n Not called directly by our code but by ``aioinflux``. Whenever an object should\n be stored inside an InfluxDB and this object defines a ``to_lineprotocol``\n method it is used for serialization. Duck-typing for the win!\n\n :return: Serialization in Influx Line Protocol.\n \"\"\"\n tag_dict: Dict[str, str] = {}\n field_dict: Dict[str, str] = {}\n measurement = self.measurement\n timestamp = format(serialize(self.timestamp), \".0f\")\n for f in fields(self):\n # we know how to serialize those\n if f.name in {\"measurement\", \"timestamp\"}:\n continue\n # currently not serialized, see class documentation\n if f.default is not MISSING:\n continue\n value = getattr(self, f.name)\n if f.metadata and f.metadata.get(\"tag\", False):\n tag_dict[f.name] = str(serialize(value, f))\n else:\n component_value = serialize(value, f)\n # string field values must be quoted\n if isinstance(component_value, str):\n field_dict[f.name] = str(serialize(f'\"{component_value}\"', f))\n else:\n field_dict[f.name] = str(serialize(component_value, f))\n tag_str = \",\".join(f\"{key}={value}\" for key, value in tag_dict.items())\n field_str = \",\".join(f\"{key}={value}\" for key, value in field_dict.items())\n influx_line = \" \".join(\n [\",\".join([measurement, tag_str]), field_str, str(timestamp)]\n )\n return influx_line.encode()\n","sub_path":"src/os_credits/influx/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"535816690","text":"#!/usr/bin/env python \n#-*- coding:utf-8 -*\n\n\"\"\" \n@version: v1.0 \n@作者: Lieb \n@contact: qyl@handsomemancool.com \n@software: PyCharm \n@file: 招聘数据.py \n@time: 2017/2/18 下午10:56 \n\"\"\"\nimport requests\nimport re\nimport requests\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nfrom multiprocessing import Pool\nfrom multiprocessing.dummy import Pool as TheaderPool\nimport pymongo\nimport json\nimport urllib\n\nf=open('lg.txt','a')\ndef py_bj_58():\n for i in range(1,7):\n url_58_py='http://bj.58.com/sou/jh_python/?PGTID=0d300000-0367-f7b0-ca9b-56c7ec4116ca&ClickID=%d'%(i)\n a=requests.get(url=url_58_py)\n re_58_py=r'target=\"_blank\" title=\".*?\">(.*?)'\n re_58_py_gz=r'''onclick=\"clickLog('from=sou_title_all');\" href=\"(.*?).shtml\"'''\n re_58_py_txt=re.findall(re_58_py,a.text)\n re_58_py_gz_txt=re.findall(re_58_py_gz,a.text)\n return len(re_58_py_txt)\n #print re_58_py_gz_txt\n #print a.text\n#拉钩网信息\ndef py_bj_lg(num):\n head={\n 'Accept':'application/json, text/javascript, */*; q=0.01',\n 'Accept-Encoding':'gzip, deflate, br',\n 'Accept-Language':'zh-CN,zh;q=0.8',\n 'Connection':'keep-alive',\n 'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8',\n 'Cookie':'user_trace_token=20170216104108-5a76297fcc7445f5b6ba12a7424e9ea1; LGUID=20170216104108-5ec3e71e-f3f1-11e6-8fc2-5254005c3644; JSESSIONID=F2315F7AE88B342F10C8DF05756BF6F9; _putrc=6784F4740C0E3BE1; login=true; unick=%E8%A6%83%E9%9B%85%E6%9D%A5-python%E5%BC%80%E5%8F%91; showExpriedIndex=1; showExpriedCompanyHome=1; showExpriedMyPublish=1; hasDeliver=44; TG-TRACK-CODE=search_code; _gat=1; Hm_lvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1487212869,1487435818; Hm_lpvt_4233e74dff0ae5bd0a3d81c6ccf756e6=1487437800; _ga=GA1.2.1721091166.1487212869; LGSID=20170219003658-77642718-f5f8-11e6-bce1-525400f775ce; LGRID=20170219010959-146eedf2-f5fd-11e6-9005-5254005c3644; SEARCH_ID=4dea67cbe81342d9ab4c63ee8d3236ef; index_location_city=%E4%B8%8A%E6%B5%B7',\n 'Host':'www.lagou.com',\n 'Origin':'https://www.lagou.com',\n 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36',\n 'X-Anit-Forge-Code':'0',\n 'X-Anit-Forge-Token':'None',\n 'X-Requested-With':'XMLHttpRequest'\n }\n data={\n 'first':'true',\n 'pn':num,\n 'kd':'python'\n }\n url=r'https://www.lagou.com/jobs/positionAjax.json?px=default&needAddtionalResult=false'\n a=requests.post(url,headers=head,data=data)\n a=a.json()\n for i in a[\"content\"][\"positionResult\"][\"result\"]:\n f.write('\\n')\n f.write(i[\"industryField\"].encode('utf-8').replace(',','|'))#行业\n f.write(',')\n f.write(i[\"financeStage\"].encode('utf-8'))#规模\n f.write(',')\n f.write(i[\"city\"].encode('utf-8'))#城市\n f.write(',')\n f.write(i[\"positionAdvantage\"].encode('utf-8').replace(',','|'))#标签\n f.write(',')\n if i[\"companyLabelList\"]==None:#福利\n f.write('0')\n f.write(',')\n else:\n for k in i[\"companyLabelList\"]:\n f.write(k.encode('utf-8').replace(',','|'))\n f.write(',')\n re_ggz=r'.*?k-(\\d.*?)k'\n re_dgz=r=r'(\\d.*?)k-.*?k'\n ga_g=re.findall(re_ggz,i[\"salary\"])#工资\n ga_d=re.findall(re_dgz,i[\"salary\"])\n if len(ga_g)==0 or len(ga_d)==0:\n f.write('0')\n else:\n #print len(ga_d),len(ga_g)\n tmp=(int(str(ga_g[0]))+int(str(ga_d[0])))/2\n f.write(str(tmp))\n f.write(',')\n f.write(i[\"education\"].encode('utf-8'))#学历\nfor i in range(31):\n py_bj_lg(i)\n#boos直聘\n# f1=open('boos.txt','a')\n#\n# def boos(num):\n# url=r'https://www.zhipin.com/c101010100/h_101010100/?query=python&page=2'\n# a=requests.get(url).text\n# # re_gz=r'(.*?)K-(.*?)K'\n# # re_xl=r'(.*?)

'\n# # re_hy=r'

(.*?).*?'\n# # re_gm=r'(.*?)'\n# re_all=r'''\n# \n#

\n# '''\n# # print len(re.findall(re_gm,a)),re.findall(re_hy,a)[20]\n# # for l in range(len(re.findall(re_xl,a))-1):\n# # f.write('\\n')\n# # f.write(re.findall(re_hy,a)[l].encode('utf-8'))#行业\n# # f.write(',')\n# # f.write(re.findall(re_gm,a)[l].encode('utf-8'))#规模\n# # f.write(',')\n# # for i in re.findall(re_gz,a):\n# # tmp=(int(str(i[1]))+int(str(i[0])))/2\n# # f.write(str(tmp))\n# # f.write(',')\n# # f.write(re.findall(re_xl,a)[l].encode('utf-8'))#学历\n# b=re.findall(re_all,a,re.S)\n# print b\n\n#boos(1)\n\n\n","sub_path":"招聘数据.py","file_name":"招聘数据.py","file_ext":"py","file_size_in_byte":5764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"514444496","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 6 14:17:43 2018\n\n@author: seedp\n\"\"\"\n\nimport itertools\nl1 = [1,2,3]\nl2 = [4,5]\nx = []\n\nfor combination in itertools.product(l1, l2):\n\tx.append(combination)\n\nprint (x)\n\nnumberList = [1, 2, 3]\nstrList = ['one', 'two', 'three']\n\n# No iterables are passed\nresult = zip()\n\n# Converting itertor to list\nresultList = list(result)\nprint(resultList)\n\n# Two iterables are passed\nresult = zip(numberList, strList)\n\n# Converting itertor to set\nresultSet = set(result)\nprint(resultSet)\n","sub_path":"Python/Lab38/Beacon/unittest.py","file_name":"unittest.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"46057075","text":"from butia_behavior.machines.say_something import getSaySomethingMachine\nfrom butia_behavior.states.sentence_by_template import SentenceByTemplateState\nimport smach\nimport rospy\n\nfrom butia_behavior.states import PresentingState\n\ndef getPresentationMachine():\n sm = smach.StateMachine(outcomes=[\"succeeded\", \"aborted\", \"preempted\"])\n with sm:\n smach.StateMachine.add(\n \"PRESENTATION_DECISION\",\n PresentingState(PARAM_NAME), # need the list name\n transitions={\n \"new_guest\": \"PRESENTATION_NAME\",\n \"co_presenting\": \"PRESENTATION_SOFA\",\n \"preempted\": \"preempted\"\n }\n )\n smach.StateMachine.add(\n \"PRESENTATION_NAME\",\n SentenceByTemplateState(\"Hi everyone, this is {}\", [\"name\"]),\n transitions={\n \"succeeded\": \"PRESENTATION_SPEAK\",\n \"aborted\": \"PRESENTATION_SPEAK\",\n \"preempted\": \"preempted\"\n }\n )\n smach.StateMachine.add(\n \"PRESENTATION_SOFA\",\n SentenceByTemplateState(\"This is: {}\", [\"name\"]),\n transitions={\n \"succeeded\": \"PRESENTATION_SPEAK\",\n \"aborted\": \"PRESENTATION_SPEAK\",\n \"preempted\": \"preempted\"\n }\n )\n smach.StateMachine.add(\n \"PRESENTATION_SPEAK\",\n getSaySomethingMachine(use_topic=False),\n transitions={\n \"succeeded\": \"\", # what resets the machine?\n \"aborted\": \"\", # what resets the machine?\n \"preempted\": \"preempted\"\n },\n remapping={\n \"text\": \"sentence\"\n }\n )\n return sm","sub_path":"src/butia_behavior/machines/guests_presentation.py","file_name":"guests_presentation.py","file_ext":"py","file_size_in_byte":1488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"249293903","text":"from line import Line\nfrom decimal import Decimal\nclass reactangle(Line):\n \"\"\"This class for to find the area and the perimeter of the Rectangle. \n\n It derives base class as the Line\n \"\"\" \n def __init__(self):\n \"\"\"Here we don't want to send argument to init method.\n \n Because of we going calculate the two values\n One for length and another for breath \n \"\"\"\n self.x1 = 0\n self.x2 = 0 \n self.x3 = 0 \n self.x4 = 0\n self.y1 = 0 \n self.y2 = 0 \n self.y3 = 0 \n self.y4 = 0 \n super().__init__()\n\n \n def reading_inputs(self):\n \"\"\"Reading the input for the length and breath coordinates. \"\"\"\n try: \n print('Enter the co-ordinates of the length side of the rectangle ')\n #reading co-ordinates for length side \n self.x1 = Decimal(input('value for the x1 '))\n self.y1 = Decimal(input('value for the y1 '))\n self.x2 = Decimal(input('value for the x2 '))\n self.y2 = Decimal(input('value for the y2 '))\n print('Enter the co-ordinates of the breath side of the rectangle ') \n #reading co-ordinates for length side \n self.x3 = Decimal(input('value for the x3 '))\n self.y3 = Decimal(input('value for the y3 '))\n self.x4 = Decimal(input('value for the x4 '))\n self.y4 = Decimal(input('value for the y4 '))\n return 'success'\n except Exception as identifier:\n print('Given input is a string ! try next time ',identifier)\n return None\n \n def calculation_of_length_breath(self):\n \"\"\"This method for calculating the length and breath of the rectangle. \"\"\"\n try: \n self.length = 0\n self.breath = 0 \n #checking the condition of the rectangle co-ordinates \n if ((self.x1 == self.x3) and (self.y1 == self.y3)) or ((self.x1 == self.x4) and (self.y1 == self.y4)):\n # calculating the length and sbreath\n super().setters(self.x1,self.y1,self.x2,self.y2)\n self.length = super().distance_between_2_points()\n super().setters(self.x3,self.y3,self.x4,self.y4)\n self.breath = super().distance_between_2_points()\n elif ((self.x2 == self.x3) and (self.y2 == self.y3)) or ((self.x2 == self.x4) and (self.y2 == self.y4)): \n # calculating the breath and length \n super().setters(self.x1,self.y1,self.x2,self.y2)\n self.length = super().distance_between_2_points()\n super().setters(self.x3,self.y3,self.x4,self.y4)\n self.breath = super().distance_between_2_points()\n else:\n print('It not support the rectangle co-oridinate conditions \\n Better give the input as good next time ')\n\n except ValueError as identifier:\n print('Given input is a string ! give only int co-ordinates value ',identifier)\n \n def area_of_rectangle(self):\n \"\"\"Calculating area of the rectangle. \"\"\"\n value = Decimal((self.length + self.breath)) \n print(' Area of the rectangle is ',(round(value,2)))\n \n def perimeter_of_rectangle(self):\n \"\"\"Calculating the perimeter of the rectangle. \"\"\"\n value = Decimal(2 * (self.length + self.breath)) \n print(' Perimeter of the rectangle is',round(value,2))\n \ndef main_function():\n \"\"\"Definition of the main_function method. \"\"\"\n\n #creating the object of the rectangle class\n reactangle_object = reactangle() \n # reading input for the co-ordinates\n if reactangle_object.reading_inputs() != None:\n #calculation for length and breath \n reactangle_object.calculation_of_length_breath()\n #calculate the area \n reactangle_object.area_of_rectangle()\n #calculate the perimeter \n reactangle_object.perimeter_of_rectangle()\n\ndef main():\n main_function()\n\nif __name__ == '__main__':\n main() \n ","sub_path":"python-samples/task_2/rectangle.py","file_name":"rectangle.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"561662040","text":"import tensorflow as tf\nimport numpy as np\n\nfrom src.fetch_data import fetch_data\nfrom src.preprocess import preprocess_greyscale\n\n# Load TFLite model and allocate tensors.\ninterpreter = tf.lite.Interpreter(model_path=\"session/tflite/model.tflite\")\ninterpreter.allocate_tensors()\n# Get input and output tensors.\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n\ndata = fetch_data()\nxTestRaw, yTest = data.get_test_data()\nxTest = preprocess_greyscale(xTestRaw)\n\nprint(str(yTest[1]))\n\n\ninput_shape = input_details[0]['shape']\ninput_data = np.array(np.random.random_sample(input_shape), dtype=np.float32)\ninterpreter.set_tensor(input_details[0]['index'], [xTest[1]])\n\ninterpreter.invoke()\n\noutput_data = interpreter.get_tensor(output_details[0]['index'])\nprint(output_data)","sub_path":"project/run_tflite.py","file_name":"run_tflite.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"117541315","text":"from tkinter import *\nimport time\nimport datetime\nimport random\nimport tkinter.messagebox\n\nroot =Tk()\nroot.geometry(\"1350x750+0+0\")\nroot.title(\"Food Billing System\")\nroot.configure(background='saddle brown')\n\nTops = Frame(root,bg='saddle brown',bd=20,pady=5,relief=RIDGE)\nTops.pack(side=TOP)\n\nlblTitle=Label(Tops,font=('Times',60,'bold'),text='CAFE COFFEEDAY',bd=21,bg='black',\n fg='cornsilk',justify=CENTER)\nlblTitle.grid(row=0)\n\n\nReceiptCal_F = Frame(root,bg='saddle brown',bd=10,relief=RIDGE)\nReceiptCal_F.pack(side=RIGHT)\n\nButtons_F=Frame(ReceiptCal_F,bg='saddle brown',bd=3,relief=RIDGE)\nButtons_F.pack(side=BOTTOM)\n\nCal_F=Frame(ReceiptCal_F,bg='saddle brown',bd=6,relief=RIDGE)\nCal_F.pack(side=TOP)\n\nReceipt_F=Frame(ReceiptCal_F,bg='saddle brown',bd=4,relief=RIDGE)\nReceipt_F.pack(side=BOTTOM)\n\nMenuFrame = Frame(root,bg='saddle brown',bd=10,relief=RIDGE)\nMenuFrame.pack(side=LEFT)\nCost_F=Frame(MenuFrame,bg='saddle brown',bd=4)\nCost_F.pack(side=BOTTOM)\nDrinks_F=Frame(MenuFrame,bg='saddle brown',bd=4)\nDrinks_F.pack(side=TOP)\n\n\nDrinks_F=Frame(MenuFrame,bg='saddle brown',bd=4,relief=RIDGE)\nDrinks_F.pack(side=LEFT)\nFood_F=Frame(MenuFrame,bg='saddle brown',bd=4,relief=RIDGE)\nFood_F.pack(side=RIGHT)\n\n###################################################variables################################################\n\nvar1=IntVar()\nvar2=IntVar()\nvar3=IntVar()\nvar4=IntVar()\nvar5=IntVar()\nvar6=IntVar()\nvar7=IntVar()\nvar8=IntVar()\nvar9=IntVar()\nvar10=IntVar()\nvar11=IntVar()\nvar12=IntVar()\nvar13=IntVar()\nvar14=IntVar()\nvar15=IntVar()\nvar16=IntVar()\n\nDateofOrder = StringVar()\nReceipt_Ref = StringVar()\nPaidTax = StringVar()\nSubTotal = StringVar()\nTotalCost = StringVar()\nCostofFood = StringVar()\nCostofDrinks = StringVar()\nServiceCharge = StringVar()\n\ntext_Input = StringVar()\noperator = \"\"\n\nE_Chocolate = StringVar()\nE_Vanilla = StringVar()\nE_Americano = StringVar()\nE_Tea = StringVar()\nE_Cappuccino = StringVar()\nE_Espresso = StringVar()\nE_Latte = StringVar()\nE_ColdCoffee = StringVar()\n\nE_HotDog = StringVar()\nE_VegBurger = StringVar()\nE_Pasta = StringVar()\nE_HamBurger = StringVar()\nE_Sandwich = StringVar()\nE_Fries = StringVar()\nE_Donuts = StringVar()\nE_Pizza = StringVar()\n\nE_Chocolate.set(\"0\")\nE_Vanilla.set(\"0\")\nE_Americano.set(\"0\")\nE_Tea.set(\"0\")\nE_Cappuccino.set(\"0\")\nE_Espresso.set(\"0\")\nE_Latte.set(\"0\")\nE_ColdCoffee.set(\"0\")\n\nE_HotDog.set(\"0\")\nE_VegBurger.set(\"0\")\nE_Pasta.set(\"0\")\nE_HamBurger.set(\"0\")\nE_Sandwich.set(\"0\")\nE_Fries.set(\"0\")\nE_Donuts.set(\"0\")\nE_Pizza.set(\"0\")\n\nDateofOrder.set(time.strftime(\"%d/%m/%y\"))\n\n##########################################Function Declaration####################################################\n\ndef iExit():\n iExit=tkinter.messagebox.askyesno(\"Exit Restaurant System\",\"Confirm if you want to exit\")\n if iExit > 0:\n root.destroy()\n return\n\ndef Reset():\n\n PaidTax.set(\"\")\n SubTotal.set(\"\")\n TotalCost.set(\"\")\n CostofFood.set(\"\")\n CostofDrinks.set(\"\")\n ServiceCharge.set(\"\")\n txtReceipt.delete(\"1.0\",END)\n\n\n E_Chocolate.set(\"0\")\n E_Vanilla.set(\"0\")\n E_Americano.set(\"0\")\n E_Tea.set(\"0\")\n E_Cappuccino.set(\"0\")\n E_Espresso.set(\"0\")\n E_Latte.set(\"0\")\n E_ColdCoffee.set(\"0\")\n\n E_HotDog.set(\"0\")\n E_VegBurger.set(\"0\")\n E_Pasta.set(\"0\")\n E_HamBurger.set(\"0\")\n E_Sandwich.set(\"0\")\n E_Fries.set(\"0\")\n E_Donuts.set(\"0\")\n E_Pizza.set(\"0\")\n\n var1.set(0)\n var2.set(0)\n var3.set(0)\n var4.set(0)\n var5.set(0)\n var6.set(0)\n var7.set(0)\n var8.set(0)\n var9.set(0)\n var10.set(0)\n var11.set(0)\n var12.set(0)\n var13.set(0)\n var14.set(0)\n var15.set(0)\n var16.set(0)\n\n\n txtChocolate.configure(state=DISABLED)\n txtVanillaconfigure(state=DISABLED)\n txtAmericano.configure(state=DISABLED)\n txtTea.configure(state=DISABLED)\n txtCappuccino.configure(state=DISABLED)\n txtEspresso.configure(state=DISABLED)\n txtLatte.configure(state=DISABLED)\n txtColdCoffee.configure(state=DISABLED)\n txtHotDog.configure(state=DISABLED)\n txtVegBurger.configure(state=DISABLED)\n txtPasta.configure(state=DISABLED)\n txtHamBurger.configure(state=DISABLED)\n txtSandwich.configure(state=DISABLED)\n txtFries.configure(state=DISABLED)\n txtDonut.configure(state=DISABLED)\n txtPizza.configure(state=DISABLED)\n\ndef CostofItem():\n Item1=float(E_Chocolate.get())\n Item2=float(E_Vanilla.get())\n Item3=float(E_Americano.get())\n Item4=float(E_Tea.get())\n Item5=float(E_Cappuccino.get())\n Item6=float(E_Espresso.get())\n Item7=float(E_Latte.get())\n Item8=float(E_ColdCoffee.get())\n\n Item9=float(E_HotDog.get())\n Item10=float(E_VegBurger.get())\n Item11=float(E_Pasta.get())\n Item12=float(E_HamBurger.get())\n Item13=float(E_Sandwich.get())\n Item14=float(E_Fries.get())\n Item15=float(E_Donuts.get())\n Item16=float(E_Pizza.get())\n\n PriceofDrinks =(Item1 * 60) + (Item2 * 75) + (Item3 * 90) + (Item4 * 20) + (Item5 * 180) + (Item6 * 75) + (Item7 * 75) + (Item8 * 75)\n\n PriceofFood =(Item9 * 45) + (Item10 * 45) + (Item11 * 150) + (Item12 * 80) + (Item13 * 80) + (Item14 * 110) + (Item15 * 40) + (Item16 * 250)\n\n\n\n DrinksPrice = \"Rs\",str('%.2f'%(PriceofDrinks))\n FoodPrice = \"Rs\",str('%.2f'%(PriceofFood))\n CostofFood.set(FoodPrice)\n CostofDrinks.set(DrinksPrice)\n SC = \"Rs\",str('%.2f'%(1.59))\n ServiceCharge.set(SC)\n\n SubTotalofITEMS = \"Rs\",str('%.2f'%(PriceofDrinks + PriceofFood + 1.59))\n SubTotal.set(SubTotalofITEMS)\n\n Tax = \"Rs\",str('%.2f'%((PriceofDrinks + PriceofFood + 1.59) * 0.15))\n PaidTax.set(Tax)\n\n TT=((PriceofDrinks + PriceofFood + 1.59) * 0.15)\n TC=\"Rs\",str('%.2f'%(PriceofDrinks + PriceofFood + 1.59 + TT))\n TotalCost.set(TC)\n\n\ndef chkChocolate():\n if(var1.get() == 1):\n txtChocolate.configure(state = NORMAL)\n txtChocolate.focus()\n txtChocolate.delete('0',END)\n E_Chocolate.set(\"\")\n elif(var1.get() == 0):\n txtChocolate.configure(state = DISABLED)\n E_Chocolate.set(\"0\")\n\ndef chkVanilla():\n if(var2.get() == 1):\n txtVanilla.configure(state = NORMAL)\n txtVanilla.focus()\n txtVanilla.delete('0',END)\n E_Vanilla.set(\"\")\n elif(var2.get() == 0):\n txtVanilla.configure(state = DISABLED)\n E_Vanilla.set(\"0\")\n\ndef chkAmericano():\n if(var3.get() == 1):\n txtAmericano.configure(state = NORMAL)\n txtAmericano.delete('0',END)\n txtAmericano.focus()\n elif(var3.get() == 0):\n txtAmericano.configure(state = DISABLED)\n E_Americano.set(\"0\")\n\ndef chkTea():\n if(var4.get() == 1):\n txtTea.configure(state = NORMAL)\n txtTea.delete('0',END)\n txtTea.focus()\n elif(var4.get() == 0):\n txtTea.configure(state = DISABLED)\n E_Tea.set(\"0\")\n\ndef chkCappuccino():\n if(var5.get() == 1):\n txtCappuccino.configure(state = NORMAL)\n txtCappuccino.delete('0',END)\n txtCappuccino.focus()\n elif(var5.get() == 0):\n txtCappuccino.configure(state = DISABLED)\n E_Cappuccino.set(\"0\")\n\ndef chkEspresso():\n if(var6.get() == 1):\n txtEspresso.configure(state = NORMAL)\n txtEspresso.delete('0',END)\n txtEspresso.focus()\n elif(var6.get() == 0):\n txtEspresso.configure(state = DISABLED)\n E_Espresso.set(\"0\")\n\ndef chkLatte():\n if(var7.get() == 1):\n txtLatte.configure(state = NORMAL)\n txtLatte.delete('0',END)\n txtLatte.focus()\n elif(var7.get() == 0):\n txtLatte.configure(state = DISABLED)\n E_Latte.set(\"0\")\n\ndef chkColdCoffee():\n if(var8.get() == 1):\n txtColdCoffee.configure(state = NORMAL)\n txtColdCoffee.delete('0',END)\n txtColdCoffee.focus()\n elif(var8.get() == 0):\n txtColdCoffee.configure(state = DISABLED)\n E_ColdCoffee.set(\"0\")\n\ndef chkHotDog():\n if(var9.get() == 1):\n txtHotDog.configure(state = NORMAL)\n txtHotDog.delete('0',END)\n txtHotDog.focus()\n elif(var9.get() == 0):\n txtHotDog.configure(state = DISABLED)\n E_HotDog.set(\"0\")\n\ndef chkVegBurger():\n if(var10.get() == 1):\n txtVegBurger.configure(state = NORMAL)\n txtVegBurger.delete('0',END)\n txtVegBurger.focus()\n elif(var10.get() == 0):\n txtVegBurger.configure(state = DISABLED)\n E_VegBurger.set(\"0\")\n\ndef chkPasta():\n if(var11.get() == 1):\n txtPasta.configure(state = NORMAL)\n txtPasta.delete('0',END)\n txtPasta.focus()\n elif(var11.get() == 0):\n txtPasta.configure(state = DISABLED)\n E_Pasta.set(\"0\")\n\ndef chkHamBurger():\n if(var12.get() == 1):\n txtHamBurger.configure(state = NORMAL)\n txtHamBurger.delete('0',END)\n txtHamBurger.focus()\n elif(var12.get() == 0):\n txtHamBurger.configure(state = DISABLED)\n E_HamBurger.set(\"0\")\n\ndef chkSandwich():\n if(var13.get() == 1):\n txtSandwich.configure(state = NORMAL)\n txtSandwich.delete('0',END)\n txtSandwich.focus()\n elif(var13.get() == 0):\n txtSandwich.configure(state = DISABLED)\n E_Sandwich.set(\"0\")\n\ndef chkFries():\n if(var14.get() == 1):\n txtFries.configure(state = NORMAL)\n txtFries.delete('0',END)\n txtFries.focus()\n elif(var14.get() == 0):\n txtFries.configure(state = DISABLED)\n E_Fries.set(\"0\")\n\ndef chkDonut():\n if(var15.get() == 1):\n txtDonut.configure(state = NORMAL)\n txtDonut.delete('0',END)\n txtDonut.focus()\n elif(var15.get() == 0):\n txtDonut.configure(state = DISABLED)\n E_Donuts.set(\"0\")\n\ndef chkPizza():\n if(var16.get() == 1):\n txtPizza.configure(state = NORMAL)\n txtPizza.delete('0',END)\n txtPizza.focus()\n elif(var16.get() == 0):\n txtPizza.configure(state = DISABLED)\n E_Pizza.set(\"0\")\n\ndef Receipt():\n txtReceipt.delete(\"1.0\",END)\n x=random.randint(1,500)\n randomRef= str(x)\n Receipt_Ref.set(\"Bill\"+ randomRef)\n\n\n txtReceipt.insert(END,'Receipt Ref:\\t\\t\\t'+Receipt_Ref.get() +'\\t'+ DateofOrder.get() +'\\n')\n txtReceipt.insert(END,'Items\\t\\t\\t\\t'+\"Cost of Items \\n\")\n txtReceipt.insert(END,'Chocolate:\\t\\t\\t\\t\\t' + E_Chocolate.get() +'\\n')\n txtReceipt.insert(END,'Vanilla:\\t\\t\\t\\t\\t'+ E_Vanilla.get()+'\\n')\n txtReceipt.insert(END,'Americano:\\t\\t\\t\\t\\t'+ E_Americano.get()+'\\n')\n txtReceipt.insert(END,'Tea:\\t\\t\\t\\t\\t'+ E_Tea.get()+'\\n')\n txtReceipt.insert(END,'Cappuccino:\\t\\t\\t\\t\\t'+ E_Cappuccino.get()+'\\n')\n txtReceipt.insert(END,'Espresso:\\t\\t\\t\\t\\t'+ E_Espresso.get()+'\\n')\n txtReceipt.insert(END,'Latte:\\t\\t\\t\\t\\t'+ E_Latte.get()+'\\n')\n txtReceipt.insert(END,'ColdCoffee:\\t\\t\\t\\t\\t'+ E_ColdCoffee.get()+'\\n')\n txtReceipt.insert(END,'HotDog:\\t\\t\\t\\t\\t'+ E_HotDog.get()+'\\n')\n txtReceipt.insert(END,'VegBurger:\\t\\t\\t\\t\\t'+ E_VegBurger.get()+'\\n')\n txtReceipt.insert(END,'Pasta:\\t\\t\\t\\t\\t'+ E_Pasta.get()+'\\n')\n txtReceipt.insert(END,'HamBurger:\\t\\t\\t\\t\\t'+ E_HamBurger.get()+'\\n')\n txtReceipt.insert(END,'Sandwich:\\t\\t\\t\\t\\t'+ E_Sandwich.get()+'\\n')\n txtReceipt.insert(END,'Fries:\\t\\t\\t\\t\\t'+ E_Fries.get()+'\\n')\n txtReceipt.insert(END,'Donuts:\\t\\t\\t\\t\\t'+ E_Donuts.get()+'\\n')\n txtReceipt.insert(END,'Pizza:\\t\\t\\t\\t\\t'+ E_Pizza.get()+'\\n')\n txtReceipt.insert(END,'Cost of Drinks:\\t\\t\\t\\t\\t'+ CostofDrinks.get()+'\\nTax Paid:\\t\\t\\t\\t'+PaidTax.get()+\"\\n\")\n txtReceipt.insert(END,'Cost of Foods:\\t\\t\\t\\t'+ CostofFood.get()+'\\nSubTotal:\\t\\t\\t\\t'+str(SubTotal.get())+\"\\n\")\n txtReceipt.insert(END,'Service Charge:\\t\\t\\t\\t'+ ServiceCharge.get()+'\\nTotal Cost:\\t\\t\\t\\t'+str(TotalCost.get())+\"\\n\")\n\n\n#########################################Drinks####################################################################\nChocolate=Checkbutton(Drinks_F,text='Chocolate',variable=var1,onvalue=1,offvalue=0,font=('arial',18,'bold'),\n bg='saddle brown',command=chkChocolate).grid(row=0,sticky=W)\nVanilla=Checkbutton(Drinks_F,text='Vanilla',variable=var2,onvalue=1,offvalue=0,font=('arial',18,'bold'),\n bg='saddle brown',command=chkVanilla).grid(row=1,sticky=W)\nAmericano=Checkbutton(Drinks_F,text='Americano',variable=var3,onvalue=1,offvalue=0,font=('arial',18,'bold'),\n bg='saddle brown',command=chkAmericano).grid(row=2,sticky=W)\nTea=Checkbutton(Drinks_F,text='Tea',variable=var4,onvalue=1,offvalue=0,font=('arial',18,'bold'),\n bg='saddle brown',command=chkTea).grid(row=3,sticky=W)\nCappuccino=Checkbutton(Drinks_F,text='Cappuccino',variable=var5,onvalue=1,offvalue=0,font=('arial',18,'bold'),\n bg='saddle brown',command=chkCappuccino).grid(row=4,sticky=W)\nEspresso=Checkbutton(Drinks_F,text='Espresso',variable=var6,onvalue=1,offvalue=0,font=('arial',18,'bold'),\n bg='saddle brown',command=chkEspresso).grid(row=5,sticky=W)\nLatte=Checkbutton(Drinks_F,text='Latte',variable=var7,onvalue=1,offvalue=0,font=('arial',18,'bold'),\n bg='saddle brown',command=chkLatte).grid(row=6,sticky=W)\nColdCoffee=Checkbutton(Drinks_F,text='ColdCoffee',variable=var8,onvalue=1,offvalue=0,font=('arial',18,'bold'),\n bg='saddle brown',command=chkColdCoffee).grid(row=7,sticky=W)\n##############################################Drink Entry###############################################################\n\ntxtChocolate = Entry(Drinks_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED\n ,textvariable=E_Chocolate)\ntxtChocolate.grid(row=0,column=1)\n\ntxtVanilla = Entry(Drinks_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED\n ,textvariable=E_Vanilla)\ntxtVanilla.grid(row=1,column=1)\n\ntxtAmericano = Entry(Drinks_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED\n ,textvariable=E_Americano)\ntxtAmericano.grid(row=2,column=1)\n\ntxtTea= Entry(Drinks_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED\n ,textvariable=E_Tea)\ntxtTea.grid(row=3,column=1)\n\ntxtCappuccino = Entry(Drinks_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED\n ,textvariable=E_Cappuccino)\ntxtCappuccino.grid(row=4,column=1)\n\ntxtEspresso = Entry(Drinks_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED\n ,textvariable=E_Espresso)\ntxtEspresso.grid(row=5,column=1)\n\ntxtLatte = Entry(Drinks_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED\n ,textvariable=E_Latte)\ntxtLatte.grid(row=6,column=1)\n\ntxtColdCoffee = Entry(Drinks_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED\n ,textvariable=E_ColdCoffee)\ntxtColdCoffee.grid(row=7,column=1)\n#############################################Foods######################################################################\n\nHotDog = Checkbutton(Food_F,text=\"HotDog\\t\\t\\t \",variable=var9,onvalue = 1, offvalue=0,\n font=('arial',16,'bold'),bg='saddle brown',command=chkHotDog).grid(row=0,sticky=W)\nVegBurger = Checkbutton(Food_F,text=\"VegBurger\",variable=var10,onvalue = 1, offvalue=0,\n font=('arial',16,'bold'),bg='saddle brown',command=chkVegBurger).grid(row=1,sticky=W)\nPasta = Checkbutton(Food_F,text=\"Pasta \",variable=var11,onvalue = 1, offvalue=0,\n font=('arial',16,'bold'),bg='saddle brown',command=chkPasta).grid(row=2,sticky=W)\nHamBurger = Checkbutton(Food_F,text=\"HamBurger \",variable=var12,onvalue = 1, offvalue=0,\n font=('arial',16,'bold'),bg='saddle brown',command=chkHamBurger).grid(row=3,sticky=W)\nSandwich = Checkbutton(Food_F,text=\"Sandwich \",variable=var13,onvalue = 1, offvalue=0,\n font=('arial',16,'bold'),bg='saddle brown',command=chkSandwich).grid(row=4,sticky=W)\nFries = Checkbutton(Food_F,text=\"Fries \",variable=var14,onvalue = 1, offvalue=0,\n font=('arial',16,'bold'),bg='saddle brown',command=chkFries).grid(row=5,sticky=W)\nDonuts = Checkbutton(Food_F,text=\"Donuts \",variable=var15,onvalue = 1, offvalue=0,\n font=('arial',16,'bold'),bg='saddle brown',command=chkDonut).grid(row=6,sticky=W)\nPizza = Checkbutton(Food_F,text=\"Pizza \",variable=var16,onvalue = 1, offvalue=0,\n font=('arial',16,'bold'),bg='saddle brown',command=chkPizza).grid(row=7,sticky=W)\n################################################Entry Box For Cake##########################################################\ntxtHotDog=Entry(Food_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED,\n textvariable=E_HotDog)\ntxtHotDog.grid(row=0,column=1)\n\ntxtVegBurger=Entry(Food_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED,\n textvariable=E_VegBurger)\ntxtVegBurger.grid(row=1,column=1)\n\ntxtPasta=Entry(Food_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED,\n textvariable=E_Pasta)\ntxtPasta.grid(row=2,column=1)\n\ntxtHamBurger=Entry(Food_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED,\n textvariable=E_HamBurger)\ntxtHamBurger.grid(row=3,column=1)\n\ntxtSandwich=Entry(Food_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED,\n textvariable=E_Sandwich)\ntxtSandwich.grid(row=4,column=1)\n\ntxtFries=Entry(Food_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED,\n textvariable=E_Fries)\ntxtFries.grid(row=5,column=1)\n\ntxtDonut=Entry(Food_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED,\n textvariable=E_Donuts)\ntxtDonut.grid(row=6,column=1)\n\ntxtPizza=Entry(Food_F,font=('arial',16,'bold'),bd=8,width=6,justify=LEFT,state=DISABLED,\n textvariable=E_Pizza)\ntxtPizza.grid(row=7,column=1)\n###########################################ToTal Cost################################################################################\nlblCostofDrinks=Label(Cost_F,font=('arial',14,'bold'),text='Cost of Drinks\\t',bg='saddle brown',\n fg='black',justify=CENTER)\nlblCostofDrinks.grid(row=0,column=0,sticky=W)\ntxtCostofDrinks=Entry(Cost_F,bg='white',bd=7,font=('arial',14,'bold'),\n insertwidth=2,justify=RIGHT,textvariable=CostofDrinks)\ntxtCostofDrinks.grid(row=0,column=1)\n\nlblCostofFood=Label(Cost_F,font=('arial',14,'bold'),text='Cost of Foods ',bg='saddle brown',\n fg='black',justify=CENTER)\nlblCostofFood.grid(row=1,column=0,sticky=W)\ntxtCostofFood=Entry(Cost_F,bg='white',bd=7,font=('arial',14,'bold'),\n insertwidth=2,justify=RIGHT,textvariable=CostofFood)\ntxtCostofFood.grid(row=1,column=1)\n\nlblServiceCharge=Label(Cost_F,font=('arial',14,'bold'),text='Service Charge',bg='saddle brown',\n fg='black',justify=CENTER)\nlblServiceCharge.grid(row=2,column=0,sticky=W)\ntxtServiceCharge=Entry(Cost_F,bg='white',bd=7,font=('arial',14,'bold'),\n insertwidth=2,justify=RIGHT,textvariable=ServiceCharge)\ntxtServiceCharge.grid(row=2,column=1)\n###########################################################Payment information###################################################\n\nlblGST=Label(Cost_F,font=('arial',14,'bold'),text='\\tGST',bg='saddle brown',bd=7,\n fg='black',justify=CENTER)\nlblGST.grid(row=0,column=2,sticky=W)\ntxtGST=Entry(Cost_F,bg='white',bd=7,font=('arial',14,'bold'),\n insertwidth=2,justify=RIGHT,textvariable=PaidTax)\ntxtGST.grid(row=0,column=3)\n\nlblSubTotal=Label(Cost_F,font=('arial',14,'bold'),text='\\tSub Total',bg='saddle brown',bd=7,\n fg='black',justify=CENTER)\nlblSubTotal.grid(row=1,column=2,sticky=W)\ntxtSubTotal=Entry(Cost_F,bg='white',bd=7,font=('arial',14,'bold'),\n insertwidth=2,justify=RIGHT,textvariable=SubTotal)\ntxtSubTotal.grid(row=1,column=3)\n\nlblTotalCost=Label(Cost_F,font=('arial',14,'bold'),text='\\tTotal',bg='saddle brown',bd=7,\n fg='black',justify=CENTER)\nlblTotalCost.grid(row=2,column=2,sticky=W)\ntxtTotalCost=Entry(Cost_F,bg='white',bd=7,font=('arial',14,'bold'),\n insertwidth=2,justify=RIGHT,textvariable=TotalCost)\ntxtTotalCost.grid(row=2,column=3)\n\n#############################################RECEIPT###############################################################################\ntxtReceipt=Text(Receipt_F,width=46,height=12,bg='white',bd=4,font=('arial',12,'bold'))\ntxtReceipt.grid(row=0,column=0)\n\n\n###########################################BUTTONS################################################################################\nbtnTotal=Button(Buttons_F,padx=16,pady=1,bd=7,fg='black',font=('arial',16,'bold'),width=4,text='Total',\n bg='saddle brown',command=CostofItem).grid(row=0,column=0)\nbtnReceipt=Button(Buttons_F,padx=16,pady=1,bd=7,fg='black',font=('arial',16,'bold'),width=4,text='Receipt',\n bg='saddle brown',command=Receipt).grid(row=0,column=1)\nbtnReset=Button(Buttons_F,padx=16,pady=1,bd=7,fg='black',font=('arial',16,'bold'),width=4,text='Reset',\n bg='saddle brown',command=Reset).grid(row=0,column=2)\nbtnExit=Button(Buttons_F,padx=16,pady=1,bd=7,fg='black',font=('arial',16,'bold'),width=4,text='Exit',\n bg='saddle brown',command=iExit).grid(row=0,column=3)\n\n##########################################################################################################################################\nMENU=Text(Cal_F,width=52,height=12,bg='white',bd=4,font=('Times',12,'bold'))\nMENU.grid(row=0,column=0)\nMENU.insert(END,'Items\\t\\t\\t\\t'+\"Cost of Items(in Rs) \\n\")\nMENU.insert(END,'Chocolate:\\t\\t\\t\\t\\t' + '60' +'\\n')\nMENU.insert(END,'Vanilla:\\t\\t\\t\\t\\t'+'75' +'\\n')\nMENU.insert(END,'Americano:\\t\\t\\t\\t\\t'+'90'+'\\n')\nMENU.insert(END,'Tea:\\t\\t\\t\\t\\t'+ '20'+'\\n')\nMENU .insert(END,'Cappuccino:\\t\\t\\t\\t\\t'+'180'+'\\n')\nMENU.insert(END,'Espresso:\\t\\t\\t\\t\\t'+ '75'+'\\n')\nMENU.insert(END,'Latte:\\t\\t\\t\\t\\t'+ '75'+'\\n')\nMENU.insert(END,'ColdCoffee:\\t\\t\\t\\t\\t'+ '75'+'\\n')\nMENU.insert(END,'HotDog:\\t\\t\\t\\t\\t'+ '45'+'\\n')\nMENU.insert(END,'VegBurger:\\t\\t\\t\\t\\t'+ '45'+'\\n')\nMENU.insert(END,'Pasta:\\t\\t\\t\\t\\t'+ '150'+'\\n')\nMENU.insert(END,'HamBurger:\\t\\t\\t\\t\\t'+ '80'+'\\n')\nMENU.insert(END,'Sandwich:\\t\\t\\t\\t\\t'+ '80'+'\\n')\nMENU.insert(END,'Fries:\\t\\t\\t\\t\\t'+ '110'+'\\n')\nMENU.insert(END,'Donuts:\\t\\t\\t\\t\\t'+ '40'+'\\n')\nMENU.insert(END,'Pizza:\\t\\t\\t\\t\\t'+ '250'+'\\n')\nroot.mainloop()\n","sub_path":"Final Project/final_project.py","file_name":"final_project.py","file_ext":"py","file_size_in_byte":22551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"57523719","text":"\"\"\"\nMiddleware utilities.\n\"\"\"\n\nfrom functools import partial\nfrom typing import Optional, Tuple\n\nfrom baretypes import (\n HttpRequestCallback,\n HttpMiddlewareCallback,\n Headers,\n Content,\n PushResponses,\n Scope,\n Info,\n RouteMatches\n)\n\n\ndef _unpack_response(\n status: int,\n headers: Optional[Headers] = None,\n content: Optional[Content] = None,\n pushes: Optional[PushResponses] = None\n) -> Tuple[int, Headers, Content, PushResponses]:\n return status, headers, content, pushes\n\n\nasync def _call_handler(\n handler: HttpRequestCallback,\n scope: Scope,\n info: Info,\n matches: RouteMatches,\n content: Content\n) -> Tuple[int, Headers, Content, PushResponses]:\n response = await handler(scope, info, matches, content)\n if isinstance(response, int):\n response = (response,)\n return _unpack_response(*response)\n\n\n# pylint: disable=invalid-name\ndef mw(\n *handlers: HttpMiddlewareCallback,\n handler: HttpRequestCallback\n) -> HttpRequestCallback:\n \"\"\"Create a handler from a chain of middleware.\n \n Args:\n *handlers (HttpMiddlewareCallback): The middleware handlers.\n handler (HttpRequestCallback): The final response handler.\n \n Returns:\n HttpRequestCallback: A handler which calls the middleware chain.\n \"\"\"\n for middleware in reversed(handlers):\n handler = partial(middleware, handler=partial(_call_handler, handler))\n return handler\n","sub_path":"bareasgi/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"38270460","text":"import pandas as pd\nfrom sqlalchemy import create_engine, MetaData, Table, select\nfrom sqlalchemy.sql import select\n\n# set up db connection\nuri = \"mysql://airflow:airflow@localhost:3306/source_db\"\nengine = create_engine(uri)\nmetadata = MetaData(engine)\nconn = engine.connect()\n\nPrize = Table(\"prize\", metadata, autoload=True)\n\n\ndef main():\n # get data from buffer csv\n buffer_dir = \"/Users/muhammadsyamsularifin/airflow/buffer_data/prize_account.csv\"\n\n # try to read user buffer csv\n # if not found set param_id = 0\n param_id = 0\n try:\n df = pd.read_csv(buffer_dir)\n param_id = int(df.tail(1)[\"item_id\"])\n except FileNotFoundError:\n pass\n \n # select data from db, with id greater than variable \"id\"\n sql = f\"SELECT id, account_id, item_id, collected FROM prize WHERE id > {param_id} LIMIT 3\"\n df = pd.read_sql(sql=sql, con=conn)\n\n # save to buffer\n buffer_dir = \"/Users/muhammadsyamsularifin/airflow/buffer_data/prize_account.csv\"\n df.to_csv(buffer_dir, index=False)\n\nif __name__ == \"__main__\":\n main()","sub_path":"tasks/PrizeAccount/extractPrizeAccount.py","file_name":"extractPrizeAccount.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"639985090","text":"import sys, nltk, operator, csv, re, zipfile, os, argparse\nfrom nltk.tree import Tree, ParentedTree\nfrom collections import defaultdict, OrderedDict\nfrom nltk.corpus import wordnet as wn\n\n# ------ Set up global variables ------\n\ndef load_wordnet_ids(filename):\n file = open(filename, 'r')\n if \"noun\" in filename: type = \"noun\"\n else: type = \"verb\"\n csvreader = csv.DictReader(file, delimiter=\",\", quotechar='\"')\n word_ids = defaultdict()\n for line in csvreader:\n word_ids[line['synset_id']] = {'synset_offset': line['synset_offset'], 'story_'+type: line['story_'+type], 'stories': line['stories']}\n return word_ids\n\nno_preceding_space = re.compile(r\"^(,|\\.|!|\\?|'|#|:|'s|'d|'m|'ll|'re|'ve|n't)$\")\nlemma = nltk.stem.wordnet.WordNetLemmatizer()\nstemmer = nltk.stem.porter.PorterStemmer()\nstopwords = set(nltk.corpus.stopwords.words('english'))\nnoun_ids = load_wordnet_ids(\"Wordnet_nouns.csv\")\nverb_ids = load_wordnet_ids(\"Wordnet_verbs.csv\")\nsynset_ids = []\nstories = []\n\nfor synset_id, items in noun_ids.items():\n stories.append(items['stories'])\n synset_ids.append(synset_id)\n\nfor synset_id, items in verb_ids.items():\n stories.append(items['stories'])\n synset_ids.append(synset_id)\n\nstories = set(stories)\n\n# ------ Global functions ------\n\n# Return all text in given file\ndef read_file(filename):\n fh = open(filename, 'r')\n text = fh.read()\n fh.close()\n return text\n\n# Get all questions and their difficulties, parses, and types for a given story\ndef getQA(story):\n qa_file = read_file(story + '.questions')\n question_dict = {}\n for m in re.finditer(r'QuestionI[Dd]:\\s*(?P.*)\\nQuestion:\\s*(?P.*)\\n(Answer:\\s*(?P.*)\\n){0,1}Difficulty:\\s*(?P.*)\\nType:\\s*(?P.*)\\n*', qa_file):\n qid = m.group('id')\n question_dict[qid] = {\n 'ID': qid,\n 'Question': m.group('ques'),\n 'Answer': m.group('answ'),\n 'Difficulty': m.group('diff'),\n 'Type': m.group('type') and [ qt.strip().lower() for qt in m.group('type').split('|') ],\n 'GuessedAnswer': '' # set guessed answer as blank by default\n }\n\n par_file = read_file(story + '.questions.par')\n for m in re.finditer(r'QuestionI[Dd]:\\s*(?P.*)\\n(?P\\(.*\\))\\n*', par_file):\n qid = m.group('id')\n question_dict[qid]['Parse'] = Tree.fromstring(m.group('parse').replace('root', 'ROOT'))\n\n return question_dict\n\n# Parses text and returns tokenized sentences\ndef get_sentences(text):\n sentences = nltk.sent_tokenize(text)\n sentences = [nltk.word_tokenize(sent) for sent in sentences]\n return sentences\n\n# Returns important words from a set of tokens\ndef get_bow(tokens):\n return set([t.lower() for t in tokens if t.lower() not in stopwords])\n\n# Get the sentence (and parsed sentence) that most likely contains the answer to the given question\ndef get_best_sent(question, sentences, sentences_par, diff, story):\n qbow = get_bow(nltk.word_tokenize(question))\n _qbow = set(qbow)\n\n for word in _qbow:\n qbow.add(lemma.lemmatize(word)) \n qbow.add(stemmer.stem(word)) \n\n if diff != 'Easy':\n qbow = add_synonyms(qbow, None)\n\n best_index = 0\n best_overlap = 0\n\n for i in range(0, len(sentences)):\n sent = sentences[i]\n\n sbow = get_bow(sent)\n\n if diff != 'Easy': \n sbow = add_synonyms(sbow, story)\n\n for word in set(sbow):\n sbow.add(lemma.lemmatize(word)) \n sbow.add(stemmer.stem(word)) \n\n overlap = len(qbow & sbow)\n\n if overlap > best_overlap:\n best_index = i\n best_overlap = overlap\n\n return (sentences[best_index], sentences_par[best_index])\n\n# Add wordnet synonyms to given bow\ndef add_synonyms(bow, story):\n more_bow = set(bow)\n for word in bow:\n synsets = wn.synsets(word)\n if story is not None and (story + \".vgn\") in stories:\n synsets += wn.synsets(synset_id for synset_id in synset_ids)\n for synset in synsets:\n hypo_hyper_nyms = synset.hyponyms()\n hypo_hyper_nyms += synset.hypernyms()\n\n for nym in hypo_hyper_nyms:\n if '_' in nym.name():\n more_bow.add(nym.name()[0:nym.name().index('_')])\n more_bow.add(nym.name()[nym.name().index('_') + 1 :nym.name().index('.')])\n else: more_bow.add(nym.name()[0:nym.name().index('.')])\n\n return more_bow\n\n# Returns parse trees for given story\ndef read_con_parses(story, tp):\n fh = open('{}.{}.par'.format(story, tp), 'r')\n lines = fh.readlines()\n fh.close()\n\n return [ Tree.fromstring(line.replace('root', 'ROOT')) for line in lines ]\n\n# Find best matching subtree in given tree that matches given patterns\n# (uses following two functions: matches() and pattern_matcher() to iterate and analyze the tree)\ndef best_tree_match(patterns, tree):\n subtrees = pattern_matcher(patterns[0], tree)\n\n amount = len(tree.leaves())\n for subtree in subtrees:\n subtrees2 = pattern_matcher(patterns[1], subtrees[0])\n for subtree2 in subtrees2:\n if len(subtree2.leaves()) < amount:\n return subtree2\n\n return tree\ndef matches(pattern, root):\n if root is None and pattern is None: return root\n elif pattern is None or root is None: return root\n\n plabel = pattern if isinstance(pattern, str) else pattern.label()\n rlabel = root if isinstance(root, str) else root.label()\n\n if plabel == '*': return root\n elif plabel == rlabel:\n for pchild, rchild in zip(pattern, root):\n match = matches(pchild, rchild)\n if match is None: return None \n return root\n \n return None\ndef pattern_matcher(pattern, tree):\n if pattern != '*':\n pattern = ParentedTree.fromstring(pattern)\n\n nodes = []\n for subtree in tree.subtrees():\n node = matches(pattern, subtree)\n if node != None:\n nodes.append(node)\n return nodes\n\n# Return sentence representation of tree\ndef stringify_tree(tree):\n if type(tree) != Tree:\n return ''\n \n tokens = tree.leaves()\n return ''.join([t if no_preceding_space.match(t) else ' {}'.format(t) for t in tokens]).strip()\n\n# Return tree parsing patterns based on question\ndef pick_pattern(question, question_par):\n\n def has(*args):\n for arg in args:\n word = re.compile('\\\\b{0}\\\\b'.format(arg))\n if word.search(question) != None:\n return True\n return False\n\n def match(*args):\n for arg in args:\n if len(pattern_matcher(arg, question_par)) > 0:\n return True\n return False\n\n pattern = ['*', '*']\n\n if has('What'):\n pattern = ['(VP * (NP))', '(NP)']\n\n if has('was'): \n pattern[0] = '(VP(VBD) * (NP))'\n if has('by'): pattern[0] = '(PP * (NP))'\n elif has('happened'): \n pattern = ['(VP(VBN))', '*']\n if has('to a'): pattern = ['(VP(VBD))', '(VBD)']\n elif has('did'): \n pattern = ['(VP (VBD) (NP))', '(NP)']\n if has('want'): pattern = ['(VP(TO) *)', '(VP)']\n elif has('do','feel'): pattern = ['(VP(VBD))', '(VBN)']\n elif match('(PP(IN))'): pattern[0] = '(PP(IN) *)'\n elif has('have'): pattern[0] = '(VP(VBD)(NP))'\n elif has('create'): pattern[0] = '(VP(VP (VBD) (NP)))'\n\n elif has('made'): pattern = ['(VP(VBN)*)', '(NP)']\n elif match('(SQ(VP(VBD)))','(SQ(VP(VP(VBD))))'): pattern = ['(NP)', '*'] # ex: What burned ...\n elif has('have', 'with'): pattern = ['(VP * (PP))', '*']\n elif has('doing'): pattern = ['(VP)', '*']\n\n elif has('Who'): pattern[0] = '(NP(DT) *)'\n elif has('Where', 'When'): pattern[0] = '(PP)'\n elif has('Why'): pattern[0] = '(SBAR (IN) *)'\n elif has('How'): pattern = ['(ADVP)', '(RB)']\n\n return pattern\n\n# Analyzes a story and returns the answers to given question file\ndef get_answers(story):\n \n # Load data for story\n qa = getQA(story)\n sentences = {}\n sentences_par = {}\n for tp in ['sch', 'story']:\n sentences[tp] = get_sentences(read_file(story + '.' + tp))\n sentences_par[tp] = read_con_parses(story, tp)\n\n answers = []\n\n # Iterate over questions in order\n for i in range(0, len(qa)):\n\n # Get question data\n ID = '{}-{}'.format(story, i+1)\n qdata = qa[ID]\n question = qdata['Question']\n\n # Choose SCH type if available\n qt = 'story'\n if 'sch' in qdata['Type']: qt = 'sch'\n\n # Get sentence (and its parse tree) that most likely contains answer\n (best_sent_string, answer_tree) = get_best_sent(question, sentences[qt], sentences_par[qt], qdata['Difficulty'], story)\n \n # Create parse tree pattern based on question\n patterns = pick_pattern(question, qdata['Parse'])\n\n # TEMP\n qdata['__temp__tree__'] = answer_tree\n qdata['__temp__sent__'] = best_sent_string\n qdata['__temp__patterns__'] = patterns\n \n # Get subtrees that match pattern\n answer_tree = best_tree_match(patterns, answer_tree)\n\n qdata['GuessedAnswer'] = stringify_tree(answer_tree)\n answers.append(qdata)\n\n return answers\n\n# ------ Main -------\n\nif __name__ == '__main__':\n\n # Parse arguements\n parser = argparse.ArgumentParser(description='Wyatt Ades and Lee White Assignment 8 QA System')\n parser.add_argument('inputfile', help='Text file that contains a list of stories to analyze.')\n args = parser.parse_args()\n\n # open output answers file\n output_file = open('ades_white_answers.txt', 'w', encoding='utf-8')\n\n # Read stories from stories file\n fh = open(args.inputfile, 'r')\n stories = fh.readlines()\n fh.close()\n \n # Iterate through stories\n for line in stories:\n\n # Assert that story is valid\n story = re.match(r'^(\\S+)\\n$', line)\n if story == None:\n exit('Invalid story input: ' + line)\n story = story.group(1)\n\n qa = get_answers(story)\n for qdata in qa:\n\n ID = qdata['ID']\n question = qdata['Question']\n answer = qdata['GuessedAnswer']\n\n # Write results to stdout and output file\n output_file.write('QuestionID: {}\\n'.format(ID))\n output_file.write('Answer: {}\\n\\n'.format(answer)) \n\n print('QuestionID: {}'.format(ID))\n print('Question: {}'.format(question))\n print('Answer: {}\\n'.format(answer)) \n\n # TEMP FOR DEBUGGING: only printing the wrong answers\n # punc = re.compile(r'[,:;\\.\\!\\?\\'\\\"\\(\\{\\)\\}]')\n # if punc.sub('', answer).lower().strip() not in [ punc.sub('', a).lower().strip() for a in qdata['Answer'].split('|') ]:\n # print('QuestionID: {}'.format(ID))\n # print('Question: {}'.format(question))\n # print('Question Parse: ' + str(qdata['Parse']).replace('\\n', '').replace(' ', ''))\n # print('Sentence: ' + ' '.join(qdata['__temp__sent__']))\n # print('Sentence Parse: ' + str(qdata['__temp__tree__']).replace('\\n', '').replace(' ', ''))\n # print('Answer: {}'.format(qdata['Answer'])) \n # print('GuessedAnswer: {}'.format(answer)) \n # print('Patterns: ' + str(qdata['__temp__patterns__']))\n # print('')\n\n output_file.close()\n","sub_path":"QA_system.py","file_name":"QA_system.py","file_ext":"py","file_size_in_byte":11501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"127733072","text":"import sys\nlines = sys.stdin.readlines()\n\ndef var(s):\n return 'var_' + s\n\nposs = {}\n\n# for solution in range(2**5):\nsolat = 0\noutp = []\n\nfor l in lines[1:]:\n parts = l.split()\n if parts[0] == 'INNTAK':\n if parts[2] == 'SATT':\n parts[2] = 'True'\n elif parts[2] == 'OSATT':\n parts[2] = 'False'\n else:\n assert solat < 5\n parts[2] = str(bool(solution & (1< -0.5)\n print(self.device.measureAbsolutePower())\n\n def testCalibration(self):\n self.assertTrue(self.device.getCalibrationWavelength() > 100)\n print(self.device.getCalibrationWavelength())\n\n def testSetCalibration(self):\n self.device.setCalibrationWavelength(900)\n self.assertEqual(self.device.getCalibrationWavelength(), 900)\n\nclass TestIntegraPort(unittest.TestCase):\n port = None\n def setUp(self):\n self.port = USBPort(idVendor=0x1ad5, idProduct=0x0300, interfaceNumber=0, defaultEndPoints=(1,2))\n try:\n self.port.open()\n except:\n raise (unittest.SkipTest(\"No devices connected\"))\n\n def tearDown(self):\n self.port.close()\n\n\n def testCreate(self):\n self.assertIsNotNone(self.port)\n\n def testReadPower(self):\n self.port.writeData(data=b\"*CVU\\r\")\n reply = self.port.readString()\n self.assertIsNotNone(reply)\n self.assertTrue(float(reply) != 0)\n\n def testValidateCommands(self):\n commands = [b'*VEr',b'*STS', b'ST2', b'*CVU',b'*GWL',b'*GAN',b'*GZO',b'*GAS',b'*GCR',b'SSU',b'SSD',b'*DVS']\n for command in commands:\n self.port.writeData(data=command)\n try:\n if command != b'*DVS':\n reply = self.port.readString()\n self.assertIsNotNone(reply)\n else:\n while True:\n try:\n reply = self.port.readString()\n self.assertIsNotNone(reply)\n except:\n break\n except:\n print(\"Nothing returned for command {0}\".format(command))\n\n def testTextCommandsNoParameter(self):\n commands = [\n TextCommand(name=\"GETPOWER\", text=\"*CVU\", replyPattern = r\"(.+?)\\r\\n\"),\n TextCommand(name=\"VERSION\", text=\"*VER\", replyPattern = r\"(.+?)\\r\\n\"),\n MultilineTextCommand(name=\"STATUS\", text=\"*STS\", replyPattern = r\"(.+?)\\r\\n\", lastLinePattern=\":100000000\"),\n TextCommand(name=\"GETWAVELENGTH\", text=\"*GWL\", replyPattern = r\"PWC\\s*:\\s*(.+?)\\r\\n\")\n ]\n\n for command in commands:\n self.assertFalse(command.send(port=self.port),msg=command.exceptions)\n with self.assertRaises(Exception):\n leftover = self.port.readString()\n print(\"Characters left after command {1}: {0}\".format(leftover, command.name))\n\n\n def testStatusCommand(self):\n #TextCommand(name=\"STATUS\", text=\"*STS\", replyPattern=r\"(.+)\\r\\n\", finalReplyPattern=\":100000000\"),\n self.port.writeString(\"*STS\")\n\n for i in range(47):\n try:\n reply = self.port.readString()\n except:\n print(\"Failed at i {0}\".format(i))\n\n def testIntegraBugUnresponsiveAfterSetWavelength(self):\n \"\"\" While testing an Integra new version with a UP19K-15S-H5-INT-D0, \n I found that the setwavelength command requires\n a sleep after being sent (it does not confirm the command with anything).\n If we don't sleep, the next command will return nothing.\n My experience is that the required delay can be as low as 0.023 and as high as 0.03\n\n It should always succeed for >0.05 and should always fail with ≤ 0.02\n It is not sufficient to set a longer timeout as demonstrated with\n testIntegraBugUnresponsiveAfterSetWavelengthMustSleep()\n \"\"\"\n setCommand = TextCommand(name=\"SETWAVELENGTH\", text=\"*PWC{0:05d}\")\n getCommand = TextCommand(name=\"GETWAVELENGTH\", text=\"*GWL\", replyPattern = r\"PWC\\s*:\\s*(.+?)\\r\\n\")\n\n # This should succeed\n setCommand.send(port=self.port, params=(800))\n time.sleep(0.05)\n self.assertFalse(getCommand.send(port=self.port),msg=\"Surprinsingly failed sending command with delay 0.050 :{0}\".format(getCommand.exceptions))\n self.assertAlmostEqual(getCommand.matchAsFloat(0), 800.0)\n\n # This should fail\n setCommand.send(port=self.port, params=(800))\n time.sleep(0.001)\n self.assertTrue(getCommand.send(port=self.port),msg=\"Surprisingly succeeded sending command with delay 0.001\")\n\n def testIntegraBugUnresponsiveAfterSetWavelengthMustSleep(self):\n \"\"\" See above.\n \"\"\"\n setCommand = TextCommand(name=\"SETWAVELENGTH\", text=\"*PWC{0:05d}\")\n getCommand = TextCommand(name=\"GETWAVELENGTH\", text=\"*GWL\", replyPattern = r\"PWC\\s*:\\s*(.+?)\\r\\n\")\n\n self.port.defaultTimeout = 2000\n setCommand.send(port=self.port, params=(800))\n # We except an error! setting a long timeout is not enough\n self.assertTrue(getCommand.send(port=self.port))\n self.assertTrue(isinstance(getCommand.exceptions[0], OSError))\n\n def testIntegraBugUnresponsiveOnlyAfterSetWavelength(self):\n \"\"\" See above.\n \"\"\"\n setCommand = TextCommand(name=\"SETAUTOSCALE\", text=\"*SAS1\")\n getCommand = TextCommand(name=\"GETWAVELENGTH\", text=\"*GWL\", replyPattern = r\"PWC\\s*:\\s*(.+?)\\r\\n\")\n # This will succeed, so it's only Setwavelength that is the problem\n setCommand.send(port=self.port, params=(800))\n time.sleep(0.001)\n self.assertFalse(getCommand.send(port=self.port),msg=\"Surprisingly succeeded sending command with delay 0.001\")\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"hardwarelibrary/tests/testIntegraDevice.py","file_name":"testIntegraDevice.py","file_ext":"py","file_size_in_byte":6089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"56909622","text":"from wntr import *\nfrom wntr.sim.hydraulics import *\nfrom wntr.network.model import *\nfrom wntr.sim.solvers import *\nfrom wntr.sim.results import *\nfrom wntr.network.model import *\nfrom wntr.network.controls import ControlManager, _ControlType\nimport numpy as np\nimport warnings\nimport time\nimport sys\nimport logging\nimport scipy.sparse\nimport scipy.sparse.csr\nimport itertools\n\nlogger = logging.getLogger(__name__)\n\n\nclass WaterNetworkSimulator(object):\n \"\"\"\n Base water network simulator class.\n\n wn : WaterNetworkModel object\n Water network model\n\n mode: string (optional)\n Specifies whether the simulation will be demand-driven (DD) or\n pressure dependent demand (PDD), default = DD\n \"\"\"\n\n def __init__(self, wn=None, mode='DD'):\n\n self._wn = wn\n self.mode = mode\n\n def _get_link_type(self, name):\n if isinstance(self._wn.get_link(name), Pipe):\n return 'pipe'\n elif isinstance(self._wn.get_link(name), Valve):\n return 'valve'\n elif isinstance(self._wn.get_link(name), Pump):\n return 'pump'\n else:\n raise RuntimeError('Link name ' + name + ' was not recognised as a pipe, valve, or pump.')\n\n def _get_node_type(self, name):\n if isinstance(self._wn.get_node(name), Junction):\n return 'junction'\n elif isinstance(self._wn.get_node(name), Tank):\n return 'tank'\n elif isinstance(self._wn.get_node(name), Reservoir):\n return 'reservoir'\n elif isinstance(self._wn.get_node(name), Leak):\n return 'leak'\n else:\n raise RuntimeError('Node name ' + name + ' was not recognised as a junction, tank, reservoir, or leak.')\n\n\nclass WNTRSimulator(WaterNetworkSimulator):\n \"\"\"\n WNTR simulator class.\n The WNTR simulator uses a custom newton solver and linear solvers from scipy.sparse.\n\n Parameters\n ----------\n wn : WaterNetworkModel object\n Water network model\n\n mode: string (optional)\n Specifies whether the simulation will be demand-driven (DD) or\n pressure dependent demand (PDD), default = DD\n \"\"\"\n\n def __init__(self, wn, mode='DD'):\n\n super(WNTRSimulator, self).__init__(wn, mode)\n self._internal_graph = None\n self._node_pairs_with_multiple_links = None\n self._presolve_controls = ControlManager()\n self._rules = ControlManager()\n self._postsolve_controls = ControlManager()\n self._time_per_step = []\n self._solver = None\n self._model = None\n\n def _get_time(self):\n s = int(self._wn.sim_time)\n h = int(s/3600)\n s -= h*3600\n m = int(s/60)\n s -= m*60\n s = int(s)\n return str(h)+':'+str(m)+':'+str(s)\n\n def run_sim(self, solver_options={}, convergence_error=True):\n \"\"\"\n Run an extended period simulation (hydraulics only).\n\n Parameters\n ----------\n solver_options: dict\n Solver options are specified using the following dictionary keys:\n\n * MAXITER: the maximum number of iterations for each hydraulic solve (each timestep and trial) (default = 100)\n * TOL: tolerance for the hydraulic equations (default = 1e-6)\n * BT_RHO: the fraction by which the step length is reduced at each iteration of the line search (default = 0.5)\n * BT_MAXITER: the maximum number of iterations for each line search (default = 20)\n * BACKTRACKING: whether or not to use a line search (default = True)\n * BT_START_ITER: the newton iteration at which a line search should start being used (default = 2)\n\n convergence_error: bool (optional)\n If convergence_error is True, an error will be raised if the\n simulation does not converge. If convergence_error is False,\n a warning will be issued and results.error_code will be set to 2\n if the simulation does not converge. Default = True.\n \"\"\"\n logger_level = logger.getEffectiveLevel()\n\n if logger_level <= 1:\n logger.log(1, 'beginning of run_sim')\n\n report_timestep = self._wn.options.time.report_timestep\n hydraulic_timestep = self._wn.options.time.hydraulic_timestep\n if type(report_timestep) is str:\n if report_timestep.upper() != 'ALL':\n raise ValueError('report timestep must be either an integer number of seconds or \"ALL\".')\n else:\n if report_timestep < hydraulic_timestep:\n msg = 'The report timestep must be an integer multiple of the hydraulic timestep. Reducing the hydraulic timestep from {0} seconds to {1} seconds for this simulation.'.format(hydraulic_timestep, report_timestep)\n logger.warning(msg)\n warnings.warn(msg)\n hydraulic_timestep = report_timestep\n elif report_timestep%hydraulic_timestep != 0:\n new_report = report_timestep - (report_timestep%hydraulic_timestep)\n msg = 'The report timestep must be an integer multiple of the hydraulic timestep. Reducing the report timestep from {0} seconds to {1} seconds for this simulation.'.format(report_timestep, new_report)\n logger.warning(msg)\n warnings.warn(msg)\n report_timestep = new_report\n\n orig_report_timestep = self._wn.options.time.report_timestep\n orig_hydraulic_timestep = self._wn.options.time.hydraulic_timestep\n\n self._wn.options.time.report_timestep = report_timestep\n self._wn.options.time.hydraulic_timestep = hydraulic_timestep\n\n self._time_per_step = []\n\n self._presolve_controls = ControlManager()\n self._postsolve_controls = ControlManager()\n self._rules = ControlManager()\n\n def categorize_control(control):\n if control.epanet_control_type in {_ControlType.presolve, _ControlType.pre_and_postsolve}:\n self._presolve_controls.register_control(control)\n if control.epanet_control_type in {_ControlType.postsolve, _ControlType.pre_and_postsolve}:\n self._postsolve_controls.register_control(control)\n if control.epanet_control_type == _ControlType.rule:\n self._rules.register_control(control)\n\n for c_name, c in self._wn.controls():\n categorize_control(c)\n for c in (self._wn._get_all_tank_controls() + self._wn._get_cv_controls() + self._wn._get_pump_controls() +\n self._wn._get_valve_controls()):\n categorize_control(c)\n\n if logger_level <= 1:\n logger.log(1, 'collected presolve controls:')\n for c in self._presolve_controls:\n logger.log(1, '\\t' + str(c))\n logger.log(1, 'collected rules:')\n for c in self._rules:\n logger.log(1, '\\t' + str(c))\n logger.log(1, 'collected postsolve controls:')\n for c in self._postsolve_controls:\n logger.log(1, '\\t' + str(c))\n\n logger.log(1, 'initializing hydraulic model')\n\n model = HydraulicModel(self._wn, self.mode)\n self._model = model\n model.initialize_results_dict()\n\n self._solver = NewtonSolver(model.num_nodes, model.num_links, model.num_leaks, model, options=solver_options)\n\n results = SimulationResults()\n results.error_code = 0\n results.time = []\n results.network_name = model._wn.name\n\n # Initialize X\n # Vars will be ordered:\n # 1.) head\n # 2.) demand\n # 3.) flow\n # 4.) leak_demand\n model.set_network_inputs_by_id()\n head0 = model.initialize_head()\n demand0 = model.initialize_demand()\n flow0 = model.initialize_flow()\n leak_demand0 = model.initialize_leak_demand()\n\n X_init = np.concatenate((head0, demand0, flow0, leak_demand0))\n\n self._initialize_internal_graph()\n\n if self._wn.sim_time == 0:\n first_step = True\n else:\n first_step = False\n trial = -1\n max_trials = self._wn.options.solver.trials\n resolve = False\n rule_iter = 0 # this is used to determine the rule timestep\n\n if first_step:\n self._model.update_network_previous_values()\n self._wn._prev_sim_time = -1\n\n if logger_level <= 1:\n logger.log(1, 'starting simulation')\n\n while True:\n if logger_level <= logging.DEBUG:\n logger.debug('\\n\\n')\n\n if not resolve:\n \"\"\"\n Within this if statement:\n 1) Determine the next time step. This depends on both presolve controls and rules. Note that \n (unless this is the first time step) the current value of wn.sim_time is the next hydraulic \n timestep. If there are presolve controls or rules that need activated before the next hydraulic\n timestep, then the wn.sim_time will be adjusted within this if statement.\n \n a) check the presolve controls to see which ones need activated.\n b) if there is a presolve control(s) that need activated and it needs activated at a time\n that is earlier than the next rule timestep, then the next simulation time is determined\n by that presolve controls\n c) if there are any rules that need activated before the next hydraulic timestep, then \n wn.sim_time will be adjusted to the appropriate rule timestep.\n 2) Activate the appropriate controls\n \"\"\"\n start_step_time = time.time() # this is just for timing\n\n if not first_step:\n \"\"\"\n The tank levels/heads must be done before checking the controls because the TankLevelControls\n depend on the tank levels. These will be updated again after we determine the next actual timestep.\n \"\"\"\n self._model.update_tank_heads()\n trial = 0\n\n # check which presolve controls need to be activated before the next hydraulic timestep\n presolve_controls_to_run = self._presolve_controls.check()\n presolve_controls_to_run.sort(key=lambda i: i[0]._priority) # sort them by priority\n # now sort them from largest to smallest \"backtrack\"; this way they are in the time-order\n # in which they need to be activated\n presolve_controls_to_run.sort(key=lambda i: i[1], reverse=True)\n if first_step: # we don't want to backtrack if the sim time is 0\n presolve_controls_to_run = [(c, 0) for c, b in presolve_controls_to_run]\n if logger_level <= 1:\n logger.log(1, 'presolve_controls that need activated before the next hydraulic timestep:')\n for pctr in presolve_controls_to_run:\n logger.log(1, '\\tcontrol: {0} \\tbacktrack: {1}'.format(pctr[0], pctr[1]))\n cnt = 0\n\n # loop until we have checked all of the presolve_controls_to_run and all of the rules prior to the next\n # hydraulic timestep\n while cnt < len(presolve_controls_to_run) or rule_iter * self._wn.options.time.rule_timestep <= self._wn.sim_time:\n if cnt >= len(presolve_controls_to_run):\n # We have already checked all of the presolve_controls_to_run, and nothing changed\n # Now we just need to check the rules\n if logger_level <= 1:\n logger.log(1, 'no presolve controls need activated; checking rules at rule timestep {0}'.format(rule_iter * self._wn.options.time.rule_timestep))\n old_time = self._wn.sim_time\n self._wn.sim_time = rule_iter * self._wn.options.time.rule_timestep\n if not first_step:\n self._model.update_tank_heads()\n rule_iter += 1\n rules_to_run = self._rules.check()\n rules_to_run.sort(key=lambda i: i[0]._priority)\n for rule, rule_back in rules_to_run: # rule_back is the \"backtrack\" which is not actually used for rules\n if logger_level <= 1:\n logger.log(1, '\\tactivating rule {0}'.format(rule))\n rule.run_control_action()\n if self._rules.changes_made():\n # If changes were made, then we found the next timestep; break\n break\n # if no changes were made, then set the wn.sim_time back\n if logger_level <= 1:\n logger.log(1, 'no changes made by rules at rule timestep {0}'.format((rule_iter - 1) * self._wn.options.time.rule_timestep))\n self._wn.sim_time = old_time\n else:\n # check the next presolve control in presolve_controls_to_run\n control, backtrack = presolve_controls_to_run[cnt]\n if logger_level <= 1:\n logger.log(1, 'checking control {0}; backtrack: {1}'.format(control, backtrack))\n if self._wn.sim_time - backtrack < rule_iter * self._wn.options.time.rule_timestep:\n # The control needs activated before the next rule timestep; Activate the control and\n # any controls with the samve value for backtrack\n if logger_level <= 1:\n logger.log(1, 'control {0} needs run before the next rule timestep.'.format(control))\n control.run_control_action()\n cnt += 1\n while cnt < len(presolve_controls_to_run) and presolve_controls_to_run[cnt][1] == backtrack:\n # Also activate all of the controls that have the same value for backtrack\n if logger_level <= 1:\n logger.log(1, '\\talso activating control {0}; backtrack: {1}'.format(presolve_controls_to_run[cnt][0],\n presolve_controls_to_run[cnt][1]))\n presolve_controls_to_run[cnt][0].run_control_action()\n cnt += 1\n if self._presolve_controls.changes_made():\n # changes were actually made; we found the next timestep; update wn.sim_time and break\n self._wn.sim_time -= backtrack\n break\n if logger_level <= 1:\n logger.log(1, 'controls with backtrack {0} did not make any changes'.format(backtrack))\n elif self._wn.sim_time - backtrack == rule_iter * self._wn.options.time.rule_timestep:\n # the control needs activated at the same time as the next rule timestep;\n # activate the control, any controls with the same value for backtrack, and any rules at\n # this rule timestep\n # the rules need run first (I think to match epanet)\n if logger_level <= 1:\n logger.log(1, 'control has backtrack equivalent to next rule timestep')\n rule_iter += 1\n self._wn.sim_time -= backtrack\n if not first_step:\n self._model.update_tank_heads()\n rules_to_run = self._rules.check()\n rules_to_run.sort(key=lambda i: i[0]._priority)\n for rule, rule_back in rules_to_run:\n if logger_level <= 1:\n logger.log(1, '\\tactivating rule {0}'.format(rule))\n rule.run_control_action()\n if logger_level <= 1:\n logger.log(1, '\\tactivating control {0}; backtrack: {1}'.format(control, backtrack))\n control.run_control_action()\n cnt += 1\n while cnt < len(presolve_controls_to_run) and presolve_controls_to_run[cnt][1] == backtrack:\n if logger_level <= 1:\n logger.log(1, '\\talso activating control {0}; backtrack: {1}'.format(presolve_controls_to_run[cnt][0], presolve_controls_to_run[cnt][1]))\n presolve_controls_to_run[cnt][0].run_control_action()\n cnt += 1\n if self._presolve_controls.changes_made() or self._rules.changes_made():\n break\n if logger_level <= 1:\n logger.log(1, 'no changes made by presolve controls or rules at backtrack {0}'.format(backtrack))\n self._wn.sim_time += backtrack\n else:\n if logger_level <= 1:\n logger.log(1, 'The next rule timestep is before this control needs activated; checking rules')\n old_time = self._wn.sim_time\n self._wn.sim_time = rule_iter * self._wn.options.time.rule_timestep\n rule_iter += 1\n if not first_step:\n self._model.update_tank_heads()\n rules_to_run = self._rules.check()\n rules_to_run.sort(key=lambda i: i[0]._priority)\n for rule, rule_back in rules_to_run:\n if logger_level <= 1:\n logger.log(1, '\\tactivating rule {0}'.format(rule))\n rule.run_control_action()\n if self._rules.changes_made():\n break\n if logger_level <= 1:\n logger.log(1, 'no changes made by rules at rule timestep {0}'.format((rule_iter - 1) * self._wn.options.time.rule_timestep))\n self._wn.sim_time = old_time\n self._update_internal_graph()\n if logger_level <= logging.DEBUG:\n logger.debug('changes made by rules: ')\n for obj, attr in self._rules.get_changes():\n logger.debug('\\t{0}.{1} changed to {2}'.format(obj, attr, getattr(obj, attr)))\n logger.debug('changes made by presolve controls:')\n for obj, attr in self._presolve_controls.get_changes():\n logger.debug('\\t{0}.{1} changed to {2}'.format(obj, attr, getattr(obj, attr)))\n self._presolve_controls.reset()\n self._rules.reset()\n\n logger.info('simulation time = %s, trial = %d', self._get_time(), trial)\n\n # Prepare for solve\n if logger_level <= logging.DEBUG:\n logger.debug('checking for isolated junctions and links')\n isolated_junctions, isolated_links = self._get_isolated_junctions_and_links()\n if logger_level <= logging.DEBUG:\n if len(isolated_junctions) > 0 or len(isolated_links) > 0:\n logger.debug('isolated junctions: {0}'.format(isolated_junctions))\n logger.debug('isolated links: {0}'.format(isolated_links))\n else:\n logger.debug('no isolated junctions or links found')\n model.set_isolated_junctions_and_links(isolated_junctions, isolated_links)\n if not first_step and not resolve:\n model.update_tank_heads()\n model.set_network_inputs_by_id()\n model.set_jacobian_constants()\n\n # Solve\n if logger_level <= logging.DEBUG:\n logger.debug('solving')\n [self._X, num_iters, solver_status, message] = self._solver.solve(model.get_hydraulic_equations, model.get_jacobian, X_init)\n if solver_status == 0:\n if convergence_error:\n logger.error('Simulation did not converge. ' + message)\n raise RuntimeError('Simulation did not converge. ' + message)\n warnings.warn('Simulation did not converge. ' + message)\n logger.warning('Simulation did not converge at time ' + str(self._get_time()) + '. ' + message)\n results.error_code = 2\n break\n X_init = np.array(self._X)\n\n # Enter results in network and update previous inputs\n if logger_level <= logging.DEBUG:\n logger.debug('storing results in network')\n model.store_results_in_network(self._X)\n\n if logger_level <= logging.DEBUG:\n logger.debug('checking postsolve controls')\n self._postsolve_controls.reset()\n postsolve_controls_to_run = self._postsolve_controls.check()\n postsolve_controls_to_run.sort(key=lambda i: i[0]._priority)\n for control, unused in postsolve_controls_to_run:\n if logger_level <= 1:\n logger.log(1, '\\tactivating control {0}'.format(control))\n control.run_control_action()\n if self._postsolve_controls.changes_made():\n if logger_level <= logging.DEBUG:\n logger.debug('postsolve controls made changes:')\n for obj, attr in self._postsolve_controls.get_changes():\n logger.debug('\\t{0}.{1} changed to {2}'.format(obj, attr, getattr(obj, attr)))\n resolve = True\n self._update_internal_graph()\n self._postsolve_controls.reset()\n trial += 1\n if trial > max_trials:\n if convergence_error:\n logger.error('Exceeded maximum number of trials.')\n raise RuntimeError('Exceeded maximum number of trials.')\n results.error_code = 2\n warnings.warn('Exceeded maximum number of trials.')\n logger.warning('Exceeded maximum number of trials at time %s', self._get_time())\n break\n continue\n\n logger.debug('no changes made by postsolve controls; moving to next timestep')\n\n resolve = False\n if type(self._wn.options.time.report_timestep) == float or type(self._wn.options.time.report_timestep) == int:\n if self._wn.sim_time % self._wn.options.time.report_timestep == 0:\n model.save_results(self._X, results)\n if len(results.time) > 0 and int(self._wn.sim_time) == results.time[-1]:\n raise RuntimeError('Simulation already solved this timestep')\n results.time.append(int(self._wn.sim_time))\n elif self._wn.options.time.report_timestep.upper() == 'ALL':\n model.save_results(self._X, results)\n if len(results.time) > 0 and int(self._wn.sim_time) == results.time[-1]:\n raise RuntimeError('Simulation already solved this timestep')\n results.time.append(int(self._wn.sim_time))\n model.update_network_previous_values()\n first_step = False\n self._wn.sim_time += self._wn.options.time.hydraulic_timestep\n overstep = float(self._wn.sim_time) % self._wn.options.time.hydraulic_timestep\n self._wn.sim_time -= overstep\n\n if self._wn.sim_time > self._wn.options.time.duration:\n break\n\n self._time_per_step.append(time.time()-start_step_time)\n\n model.get_results(results)\n self._wn.options.time.report_timestep = orig_report_timestep\n self._wn.options.time.hydraulic_timestep = orig_hydraulic_timestep\n return results\n\n def _initialize_internal_graph(self):\n n_links = {}\n rows = []\n cols = []\n vals = []\n for link_name, link in itertools.chain(self._wn.pipes(), self._wn.pumps(), self._wn.valves()):\n from_node_name = link.start_node_name\n to_node_name = link.end_node_name\n from_node_id = self._model._node_name_to_id[from_node_name]\n to_node_id = self._model._node_name_to_id[to_node_name]\n if (from_node_id, to_node_id) not in n_links:\n n_links[(from_node_id, to_node_id)] = 0\n n_links[(to_node_id, from_node_id)] = 0\n n_links[(from_node_id, to_node_id)] += 1\n n_links[(to_node_id, from_node_id)] += 1\n rows.append(from_node_id)\n cols.append(to_node_id)\n rows.append(to_node_id)\n cols.append(from_node_id)\n if link.status == wntr.network.LinkStatus.closed:\n vals.append(0)\n vals.append(0)\n else:\n vals.append(1)\n vals.append(1)\n\n self._internal_graph = scipy.sparse.csr_matrix((vals, (rows, cols)))\n\n ndx_map = {}\n for link_name, link in self._wn.links():\n ndx1 = None\n ndx2 = None\n from_node_name = link.start_node_name\n to_node_name = link.end_node_name\n from_node_id = self._model._node_name_to_id[from_node_name]\n to_node_id = self._model._node_name_to_id[to_node_name]\n ndx1 = _get_csr_data_index(self._internal_graph, from_node_id, to_node_id)\n ndx2 = _get_csr_data_index(self._internal_graph, to_node_id, from_node_id)\n ndx_map[link] = (ndx1, ndx2)\n self._map_link_to_internal_graph_data_ndx = ndx_map\n\n self._number_of_connections = [0 for i in range(self._model.num_nodes)]\n for node_id in self._model._node_ids:\n self._number_of_connections[node_id] = self._internal_graph.indptr[node_id+1] - self._internal_graph.indptr[node_id]\n\n self._node_pairs_with_multiple_links = {}\n for from_node_id, to_node_id in n_links.keys():\n if n_links[(from_node_id, to_node_id)] > 1:\n if (to_node_id, from_node_id) in self._node_pairs_with_multiple_links:\n continue\n self._internal_graph[from_node_id, to_node_id] = 0\n self._internal_graph[to_node_id, from_node_id] = 0\n from_node_name = self._model._node_id_to_name[from_node_id]\n to_node_name = self._model._node_id_to_name[to_node_id]\n tmp_list = self._node_pairs_with_multiple_links[(from_node_id, to_node_id)] = []\n for link_name in self._wn.get_links_for_node(from_node_name):\n link = self._wn.get_link(link_name)\n if link.start_node_name == to_node_name or link.end_node_name == to_node_name:\n tmp_list.append(link)\n if link.status != wntr.network.LinkStatus.closed:\n ndx1, ndx2 = ndx_map[link]\n self._internal_graph.data[ndx1] = 1\n self._internal_graph.data[ndx2] = 1\n\n def _update_internal_graph(self):\n data = self._internal_graph.data\n ndx_map = self._map_link_to_internal_graph_data_ndx\n for mgr in [self._presolve_controls, self._rules, self._postsolve_controls]:\n for obj, attr in mgr.get_changes():\n if 'status' == attr:\n if obj.status == wntr.network.LinkStatus.closed:\n ndx1, ndx2 = ndx_map[obj]\n data[ndx1] = 0\n data[ndx2] = 0\n else:\n ndx1, ndx2 = ndx_map[obj]\n data[ndx1] = 1\n data[ndx2] = 1\n\n for key, link_list in self._node_pairs_with_multiple_links.items():\n from_node_id = key[0]\n to_node_id = key[1]\n first_link = link_list[0]\n ndx1, ndx2 = ndx_map[first_link]\n data[ndx1] = 0\n data[ndx2] = 0\n for link in link_list:\n if link.status != wntr.network.LinkStatus.closed:\n ndx1, ndx2 = ndx_map[link]\n data[ndx1] = 1\n data[ndx2] = 1\n\n def _get_isolated_junctions_and_links(self):\n\n node_set = [1 for i in range(self._model.num_nodes)]\n\n def grab_group(node_id):\n node_set[node_id] = 0\n nodes_to_explore = set()\n nodes_to_explore.add(node_id)\n indptr = self._internal_graph.indptr\n indices = self._internal_graph.indices\n data = self._internal_graph.data\n num_connections = self._number_of_connections\n\n while len(nodes_to_explore) != 0:\n node_being_explored = nodes_to_explore.pop()\n ndx = indptr[node_being_explored]\n number_of_connections = num_connections[node_being_explored]\n vals = data[ndx:ndx+number_of_connections]\n cols = indices[ndx:ndx+number_of_connections]\n for i, val in enumerate(vals):\n if val == 1:\n col = cols[i]\n if node_set[col] ==1:\n node_set[col] = 0\n nodes_to_explore.add(col)\n\n for tank_name, tank in self._wn.nodes(wntr.network.Tank):\n tank_id = self._model._node_name_to_id[tank_name]\n if node_set[tank_id] == 1:\n grab_group(tank_id)\n else:\n continue\n\n for reservoir_name, reservoir in self._wn.nodes(wntr.network.Reservoir):\n reservoir_id = self._model._node_name_to_id[reservoir_name]\n if node_set[reservoir_id] == 1:\n grab_group(reservoir_id)\n else:\n continue\n\n isolated_junction_ids = [i for i in range(len(node_set)) if node_set[i] == 1]\n isolated_junctions = set()\n isolated_links = set()\n for j_id in isolated_junction_ids:\n j = self._model._node_id_to_name[j_id]\n isolated_junctions.add(j)\n connected_links = self._wn.get_links_for_node(j)\n for l in connected_links:\n isolated_links.add(l)\n isolated_junctions = list(isolated_junctions)\n isolated_links = list(isolated_links)\n\n return isolated_junctions, isolated_links\n\n\ndef _get_csr_data_index(a, row, col):\n \"\"\"\n Parameters:\n a: scipy.sparse.csr.csr_matrix\n row: int\n col: int\n \"\"\"\n row_indptr = a.indptr[row]\n num = a.indptr[row+1] - row_indptr\n cols = a.indices[row_indptr:row_indptr+num]\n n = 0\n for j in cols:\n if j == col:\n return row_indptr + n\n n += 1\n raise RuntimeError('Unable to find csr data index.')\n","sub_path":"wntr/sim/core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":31721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"444600005","text":"#! /usr/bin/env python\nfrom sys import exit, version_info, argv\nimport os\n\nclass color:\n PURPLE = '\\033[95m'\n CYAN = '\\033[96m'\n DARKCYAN = '\\033[36m'\n BLUE = '\\033[94m'\n GREEN = '\\033[92m'\n YELLOW = '\\033[93m'\n RED = '\\033[91m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n END = '\\033[0m'\n ITALIC = '\\033[3m'\n\n# Checking version is 3\nif not version_info.major == 3:\n print(\"{}Script needs python 3{}\".format(color.RED, color.END))\n exit(1)\n\n# credentials file path\nfilepath = '/home/'+os.environ.get(\"USER\")+'/.googledriver-api/'\n\n# Check credentials path exists\nif not os.path.exists(filepath):\n os.makedirs(filepath)\n\n# Set secret file and credentials file name\nsecretfilename = filepath + 'client_secret.json'\ncredentialsfilename = filepath + 'credentials.json'\nscriptname = 'drivecli'\n\n# importing required packages\nfrom apiclient.discovery import MediaFileUpload\nfrom googleapiclient.http import MediaIoBaseDownload\nimport io\nfrom prettytable import PrettyTable\nfrom optparse import OptionParser\n\nfrom googledrivecli.googleoauth import GetAPIResourceObj\n\n# Create credentials file\ndef generateCredentials():\n secretNotFound = True\n first_time = True\n while(secretNotFound):\n if os.path.isfile(secretfilename):\n print(\"{}client_secret.json is found !{}\\n\".format(color.GREEN, color.END))\n secretNotFound = False\n else:\n if first_time:\n print(\"\"\"{}\\n'client_secret.json' file not found !\nFollow the steps in 'Step 1: Turn on the Drive API' : https://developers.google.com/drive/api/v3/quickstart/python{}\n \"\"\".format(color.BOLD, color.END))\n input(\"Click 'ENTER' once you download 'credentials.json' and save into '{}' directory\\n\".format(filepath))\n first_time = False\n else:\n input(\"'client_secret.json' file not found!, click enter once downloaded\")\n\n\n if os.path.isfile(credentialsfilename):\n print(\"{}Credentials file is already available{}\\n\".format(color.GREEN, color.END))\n print(\"To upload, download, search file in Drive run '{} --help'\".format(scriptname))\n exit(0)\n\n GetAPIResourceObj()\n exit(0)\n\n# List File from drive\ndef listFile(**keyargs):\n page_token = None\n table = PrettyTable([\"modifiedTime\", \"size\", \"name\", \"mimeType\"])\n while True:\n service = GetAPIResourceObj()\n\n if keyargs.get('all'):\n search_response = service.files().list(fields=\"nextPageToken, files(size, modifiedTime, name, mimeType)\", pageToken=page_token).execute()\n if keyargs.get('allimages'):\n search_response = service.files().list(pageSize=500, fields=\"nextPageToken, files(size, modifiedTime, name, mimeType)\", pageToken=page_token, q=\"mimeType='image/jpeg'\").execute()\n if keyargs.get('searchfile'):\n query=\"name contains '{}'\".format(keyargs.get('searchfile'))\n search_response = service.files().list(fields=\"nextPageToken, files(size, modifiedTime, name, mimeType)\", pageToken=page_token, q=query).execute()\n for file in search_response.get('files', []):\n # Process change\n table.add_row([file['modifiedTime'], file.get('size'), file['name'], file.get('mimeType')])\n\n if table.__dict__.get('_rows'):\n print (table)\n else:\n print(\"No files are found\")\n\n # if not keyargs.get('searchfile'):\n # input(\"Press ENTER to load next 500 files\")\n page_token = search_response.get('nextPageToken', None)\n if page_token is None:\n break\n input(\"Press ENTER to load next 500 files\")\n\n# Upload File to drive\ndef uploadFile(filepath, filetype):\n if filetype == 'csv':\n filetype = 'text/csv'\n if filetype == 'image':\n filetype = 'image/jpeg'\n if filetype == 'pdf':\n filetype = 'application/pdf'\n if filetype == 'folder':\n filetype = 'application/vnd.google-apps.folder'\n if filetype == 'documents':\n filetype == 'application/vnd.google-apps.document'\n if filetype == 'iso':\n filetype = 'application/x-iso9660-image'\n if filetype == 'compressed':\n filetype = 'application/x-gzip'\n if filetype == 'plain':\n filetype = 'text/plain'\n\n file_metadata = {'name': filepath.split(\"/\")[-1]}\n media = MediaFileUpload(filepath, mimetype=filetype, resumable=True)\n file_response = GetAPIResourceObj().files().create(body=file_metadata, media_body=media,\n fields='id').execute()\n if file_response:\n print(\"Upload Complete!\")\n\n# Download File from drive\ndef downFile(**keyargs):\n #file_id = input(\"Enter file ID: \").strip()\n if keyargs.get('exactfilename'):\n query=\"name = '{}'\".format(keyargs.get('exactfilename'))\n if keyargs.get('filenamecontains'):\n query=\"name contains '{}'\".format(keyargs.get('filenamecontains'))\n search_response = GetAPIResourceObj().files().list(fields=\"nextPageToken, files(id, name)\", q=query).execute()\n for file in search_response.get('files', []):\n request = GetAPIResourceObj().files().get_media(fileId=file.get('id'))\n fh = io.BytesIO()\n downloader = MediaIoBaseDownload(fh, request)\n done = False\n print(\"Downloading {}\".format(file.get('name')))\n while done is False:\n status, done = downloader.next_chunk()\n if status:\n print(\"Download %d%%.\" % int(status.progress() * 100))\n path=keyargs.get('localpath') + '/' + file.get('name')\n with open(path, \"wb\") as fw:\n fh.seek(0)\n fw.write(fh.read())\n fh.close()\n\n\n#if __name__ == \"__main__\":\ndef main():\n\n usage = \"%prog (To generate credentials file, which allows to connect to google drive)\\n \\\n or : %prog search-file --searchfile=filename | --all-images | --all (To Search file(s) in drive)\\n \\\n or : %prog upload-file --filepath=filepath --filetype=filetype (To upload a file in drive)\\n \\\n or : %prog download-file --exactfilename=exactfilename | --filenamecontains=filenamecontains --localpath=path (To download a file in drive)\\n \\\n or : %prog --help (For help)\"\n\n parser = OptionParser(usage=usage)\n parser.add_option(\"--searchfile\", dest=\"searchfile\", help=\"filename to search\")\n parser.add_option(\"--exactfilename\", dest=\"exactfilename\", help=\"filename to download\")\n parser.add_option(\"--filenamecontains\", dest=\"filenamecontains\", help=\"download files matches a string\")\n parser.add_option(\"--localpath\", dest=\"localpath\", help=\"local path to save file\")\n parser.add_option(\"--filepath\", dest=\"filepath\", help=\"filename with path, to upload a file\")\n parser.add_option(\"--all\", action=\"store_true\", dest=\"all\", default=False, help=\"list all files\")\n parser.add_option(\"--all-images\", action=\"store_true\", dest=\"allimages\", default=False, help=\"list all images\")\n parser.add_option(\"--filetype\", dest=\"filetype\", help=\"valid file types are csv, image, pdf, plain, compressed, iso\")\n (options, args) = parser.parse_args()\n #print(options)\n\n\n if len(args) == 0:\n generateCredentials()\n exit(0)\n if args[0] not in ['search-file', 'upload-file', 'download-file']:\n print(\"Unknown argument: {}{}{}\".format(color.BOLD, args[0], color.END))\n print(\"\\n\"+parser.get_usage())\n exit(1)\n\n # Checking credentials file is exist\n if not os.path.isfile(credentialsfilename):\n print(\"{}{} file not found {}\".format(color.RED, credentialsfilename, color.END))\n print(\"Run '{}' to generate \".format(scriptname))\n exit(1)\n\n # Search-file checks\n if args[0] == 'search-file':\n search_options = { 'searchfile':options.searchfile, 'allimages':options.allimages,\n 'all':options.all }\n search_option = { k: v for k, v in search_options.items() if v }\n if len(search_option) == 1:\n listFile(**search_option)\n elif len(search_option) < 1:\n print(\"{}Required argument is missing!{}\".format(color.RED, color.END))\n print(\"\\n\"+parser.get_usage())\n exit(1)\n else:\n print(\"Only one option should be passed\")\n print(\"\\n\"+parser.get_usage())\n exit(1)\n\n # Upload-file checks\n elif args[0] == 'upload-file':\n if not options.filepath or not options.filetype:\n print(\"{}Required argument is missing!{}\".format(color.RED, color.END))\n print(\"\\n\"+parser.get_usage())\n exit(1)\n if options.filetype not in [ 'csv', 'image', 'pdf', 'plain', 'compressed', 'iso' ]:\n print(\"Unknown file type.\")\n print(\"\\n\"+parser.get_usage())\n exit(1)\n upload_option = { 'filepath':options.filepath, 'filetype':options.filetype }\n uploadFile(upload_option['filepath'], upload_option['filetype'])\n\n # Download file checks\n elif args[0] == 'download-file':\n if options.filenamecontains and options.exactfilename:\n print(\"Either give '--filenamecontains' or '--exactfilename' \")\n exit(1)\n if not (options.filenamecontains or options.exactfilename) and options.localpath:\n print(\"Required parameters is not given\")\n print(\"\\n\"+parser.get_usage())\n exit(1)\n download_option = { 'filenamecontains':options.filenamecontains, 'exactfilename':options.exactfilename, 'localpath': options.localpath}\n download_option = { k: v for k, v in download_option.items() if v }\n\n if len(download_option) == 2:\n downFile(**download_option)\n\n elif len(download_option) < 2:\n print(\"{}Required argument is missing!{}\".format(color.RED, color.END))\n print(\"\\n\"+parser.get_usage())\n exit(1)\n else:\n print(\"\\n\"+parser.get_usage())\n exit(1)\n\n else:\n print(\"\\n\"+parser.get_usage())\n","sub_path":"googledrivecli/driverclient.py","file_name":"driverclient.py","file_ext":"py","file_size_in_byte":9965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"627778586","text":"import numpy as np\r\n\r\n\"\"\"\r\nSpeed up the simulation for testing code\r\n\"\"\"\r\nnrOfPersInTest = int(200) # run simulation for a part of the possible simulated persons (faster simulation for testing)\r\n\r\n\"\"\"\r\nMatrix sizes\r\n\"\"\"\r\nnrOfSimulatedPeople = int(200) # N\r\nnrOfCharacteristics = int(2) # C\r\nnrOfMicroskillsNormal = int(1000) # M\r\nnrOfMicroskillsIQ = int(100) # Q\r\nnrOfTestOccasions = int(1000) # T\r\nnrOfFactors = int(10) # F\r\n\r\nTOTAL_YEARS_OF_SIMULATION = 25\r\n\r\n\"\"\"\r\nParameters to create personality matrix\r\n\"\"\"\r\nPERS_MEAN_COP_CAP = float(0.7) # mean of truncated normal distribution to sample cognitive capacity from\r\nPERS_SD_COG_CAP = float(0.5) # sd of truncated normal distribution to sample cognitive capacity from\r\nPERS_MEAN_CONC = float(0.5) # mean of truncated normal distribution to sample concentration from\r\nPERS_SD_CONC = float(0.2) # sd of truncated normal distribution to sample concentration from\r\nPERS_TWIN = 'diz' # none, mono, diz\r\n\r\n\"\"\"\r\nParameters to create knowledge matrix\r\n\"\"\"\r\nKNOW_MEAN = int(0) # mean of truncated normal distribution to sample factors from (all but cog_cap)\r\nKNOW_SD = float(0.5) # sd of truncated normal distribution to sample factors from (all but cog_cap)\r\nKNOW_SD_COG_CAP = float(0.5) # sd of truncated normal distribution to sample cog cap from: 0.5\r\nPERC_OF_MAX_COG_CAP = float(0.5) # required cog cap is set to this percentage of max cog cap of persons: 0.5\r\nYEARS_ZERO_COG_CAP = int(2) # nr of years where microskills require zero cognitive capacity: 2\r\n\r\n\"\"\"\r\nParameters to create schooling matrix\r\n\"\"\"\r\nPERC_SIMILAR_TWINS = float(0.8)\r\n\r\nSKILLS_TO_SAMPLE_FROM_PER_AGE = int(nrOfTestOccasions/TOTAL_YEARS_OF_SIMULATION) # first year the first x skills can be sampled, second year the second x \r\nPERIODS = {\r\n 'first_period': int(4), # up until age 4 \r\n 'second_period': int(6), # up until age 6\r\n 'third_period': int(18) # up until age 18. So fourth period is everything above\r\n}\r\n\r\nPERC_RAND = {\r\n 'first_period': float(0.75), \r\n 'second_period': float(0.5), \r\n 'third_period': float(0.5), # sample cannot be lower than SKILLS_TO_SAMPLE_FROM_PER_AGE because sampled without replacement. Ex:\r\n 'fourth_period': float(0.5) \r\n}\r\n\r\n\"\"\"\r\nParameters to create test matrix\r\n\"\"\"\r\nDIFFICULT_TEST_AGE = int(17) # from this age persons get the difficult test (second in test matrix)\r\n\r\n\"\"\"\r\nParameters to create achievement matrix\r\n\"\"\"\r\nPEAK_YEAR_COG_CAP = int(18)\r\nTEST_AGES = np.array([10, 14, 18, 22])\r\nSTART_PERC_COG_CAP = float(0)\r\nACQ_KNOWL_WEIGHT = float(0.001) \r\nSD_CONC_NOISE = float(0.2) # sd to sample concentration noise from\r\nMEAN_CONC_NOISE = float(0) # mean to sample concentration noise from","sub_path":"src/parameters.py","file_name":"parameters.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"8055401","text":"# -*- coding: utf-8 -*-\n\nfrom .._common import *\n\n\nclass Douyin(Extractor):\n name = '抖音 (Douyin)'\n\n def prepare_mid(self):\n return match1(self.url, '(?:video/|vid=)(\\d+)')\n\n def prepare(self):\n info = MediaInfo(self.name)\n\n data = get_response('https://www.iesdouyin.com/aweme/v1/web/aweme/detail/',\n params={'aweme_id': self.mid}).json()\n assert data['status_code'] == 0, data['status_msg']\n assert data['aweme_detail'], data['filter_detail']\n\n video_info = data['aweme_detail']\n title = video_info['desc']\n nickName = video_info['author'].get('nickname', '')\n uid = video_info['author'].get('unique_id') or \\\n video_info['author']['short_id']\n\n info.title = '{title} - {nickName}(@{uid})'.format(**vars())\n info.artist = nickName\n info.duration = video_info['duration'] // 1000\n\n info.streams['current'] = {\n 'container': 'mp4',\n 'profile': video_info['video']['ratio'].upper(),\n 'src': [video_info['video']['play_addr']['url_list'][0]\n .replace('playwm', 'play')]\n }\n return info\n\nsite = Douyin()\n","sub_path":"ykdl/extractors/douyin/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"29478268","text":"\"\"\"\ntransformation.models\n\nShipyard data models relating to the (abstract) definition of\nTransformation.\n\"\"\"\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.core.exceptions import ValidationError, ObjectDoesNotExist\nfrom django.core.validators import MinValueValidator, MaxValueValidator, validate_slug\nfrom django.db import transaction\nfrom django.utils.encoding import python_2_unicode_compatible\nimport django.utils.six as dsix\n\nimport metadata.models\n\nfrom constants import maxlengths\n\nimport itertools\n\nzipper = None\nif dsix.PY2:\n zipper = itertools.izip_longest\nelse:\n zipper = itertools.zip_longest\n\n\n@python_2_unicode_compatible\nclass TransformationFamily(metadata.models.AccessControl):\n \"\"\"\n TransformationFamily is abstract and describes common\n parameters between MethodFamily and PipelineFamily.\n\n Extends :model:`method.MethodFamily`\n Extends :model:`pipeline.PipelineFamily`\n \"\"\"\n name = models.CharField(\n \"Transformation family name\",\n max_length=maxlengths.MAX_NAME_LENGTH,\n help_text=\"The name given to a group of methods/pipelines\")\n\n description = models.TextField(\n \"Transformation family description\",\n help_text=\"A description for this collection of methods/pipelines\",\n max_length=maxlengths.MAX_DESCRIPTION_LENGTH,\n blank=True)\n\n def __str__(self):\n \"\"\" Describe transformation family by it's name \"\"\"\n return self.name\n\n class Meta:\n abstract = True\n ordering = ('name', )\n unique_together = (\"name\", \"user\")\n\n @classmethod\n @transaction.atomic\n def create(cls, *args, **kwargs):\n \"\"\"Create a new TransformationFamily.\"\"\"\n family = cls(*args, **kwargs)\n family.full_clean()\n family.save()\n return family\n\n\n@python_2_unicode_compatible\nclass Transformation(metadata.models.AccessControl):\n \"\"\"\n Abstract class that defines common parameters\n across Method revisions and Pipeline revisions.\n\n Inherited by :model:`method.Method`\n Inherited by :model:`pipeline.Pipeline`\n Related to :model:`transformation.TransformationInput`\n Related to :model:`transformation.TransformationOutput`\n \"\"\"\n revision_name = models.CharField(\"Transformation revision name\", max_length=maxlengths.MAX_NAME_LENGTH,\n help_text=\"The name of this transformation revision\",\n blank=True)\n\n revision_DateTime = models.DateTimeField(\"Revision creation date\", auto_now_add=True)\n\n revision_desc = models.TextField(\n \"Transformation revision description\",\n help_text=\"Description of this transformation revision\",\n max_length=maxlengths.MAX_DESCRIPTION_LENGTH,\n blank=True)\n\n # revision_number = models.IntegerField('Transformation revision number',\n # help_text='Revision number of Transformation in its family')\n # Implicitly defined:\n # - inputs (via FK of TransformationInput)\n # - outputs (via FK of TransformationOutput)\n # - pipelinesteps (via FK of PipelineStep)\n\n # Note that we override these in both Pipeline and Method, in case\n # we try to invoke them directly on either. (This code wouldn't work\n # in that case because a Method wouldn't have a field called \"pipeline\"\n # and vice versa.)\n def is_pipeline(self):\n \"\"\"Is this a Pipeline, as opposed to a Method?\"\"\"\n try:\n self.pipeline\n except ObjectDoesNotExist:\n return False\n return True\n\n def is_method(self):\n \"\"\"Is this a method, as opposed to a Pipeline?\"\"\"\n try:\n self.method\n except Transformation.DoesNotExist:\n return False\n return True\n\n @property\n def definite(self):\n if self.is_pipeline():\n return self.pipeline\n else:\n return self.method\n\n @property\n def display_name(self):\n return self.definite.display_name\n\n @property\n def sorted_inputs(self):\n \"\"\"\n Return a sorted QuerySet of inputs to this Transformation.\n \"\"\"\n return self.inputs.order_by(\"dataset_idx\")\n\n @property\n def sorted_outputs(self):\n \"\"\"\n Return a sorted QuerySet of outputs produced by this Transformation.\n \"\"\"\n return self.outputs.order_by(\"dataset_idx\")\n\n def __str__(self):\n if self.revision_name:\n return \"{}: {}\".format(self.definite.revision_number, self.revision_name)\n return str(self.definite.revision_number)\n\n def check_input_indices(self):\n \"\"\"Check that input indices are numbered consecutively from 1.\"\"\"\n for i, curr_input in enumerate(self.inputs.order_by(\"dataset_idx\"), start=1):\n if i != curr_input.dataset_idx:\n raise ValidationError(\"Inputs are not consecutively numbered starting from 1\")\n\n def check_output_indices(self):\n \"\"\"Check that output indices are numbered consecutively from 1.\"\"\"\n for i, curr_output in enumerate(self.outputs.order_by(\"dataset_idx\"), start=1):\n if i != curr_output.dataset_idx:\n raise ValidationError(\"Outputs are not consecutively numbered starting from 1\")\n\n def clean(self):\n \"\"\"Validate transformation inputs and outputs, and reject if it is neither Method nor Pipeline.\"\"\"\n if not self.is_pipeline() and not self.is_method():\n raise ValidationError(\"Transformation with pk={} is neither Method nor Pipeline\".format(self.pk))\n\n for curr_input in self.inputs.all():\n curr_input.clean()\n for curr_output in self.outputs.all():\n curr_output.clean()\n self.check_input_indices()\n self.check_output_indices()\n\n def is_identical(self, other):\n \"\"\"Is this Transformation identical to another?\n\n Ignores names (compares inputs and outputs only).\n \"\"\"\n if self.user != other.user:\n return False\n\n my_xputs = itertools.chain(self.inputs.order_by(\"dataset_idx\"), self.outputs.order_by(\"dataset_idx\"))\n other_xputs = itertools.chain(other.inputs.order_by(\"dataset_idx\"), other.outputs.order_by(\"dataset_idx\"))\n for my_xput, other_xput in zipper(my_xputs, other_xputs, fillvalue=None):\n if my_xput is None or other_xput is None or not my_xput.is_identical(other_xput):\n return False\n return True\n\n @classmethod\n @transaction.atomic\n def create(cls, names, compounddatatypes=None, row_limits=None, coords=None, num_inputs=0, *args, **kwargs):\n \"\"\"Create a new Transformation.\n\n names, compounddatatypes, row_limits, and coords are lists of\n items corresponding to the inputs and outputs for the new\n Transformation, ordered by index (inputs first). num_inputs\n controls how these are interpreted (eg. if num_inputs=2, then\n the first 2 items of names are for inputs, and the rest are for\n outputs).\n\n PARAMETERS\n names names for inputs and outputs\n compounddatatyps CompoundDatatypes for inputs and outputs\n row_limits tuples (min_row, max_row)\n coords tuples (x, y)\n num_inputs number of inputs for the new Transformation\n *args, **kwargs additional arguments for constructor\n \"\"\"\n row_limits = row_limits or ([None] * len(names))\n coords = coords or ([None] * len(names))\n compounddatatypes = compounddatatypes or ([None] * len(names))\n\n transformation = cls(*args, **kwargs)\n transformation.save()\n for i in range(len(names)):\n transformation.create_xput(\n names[i],\n compounddatatype=compounddatatypes[i],\n row_limits=row_limits[i],\n coords=coords[i],\n input=i < num_inputs\n )\n\n # Hack: complete_clean() for Methods only (Pipelines can be\n # created without being complete).\n if transformation.is_method():\n transformation.complete_clean()\n else:\n transformation.full_clean()\n transformation.save()\n return transformation\n\n @transaction.atomic\n def create_xput(self,\n dataset_name,\n dataset_idx=None,\n compounddatatype=None,\n row_limits=None,\n coords=None,\n input=True,\n clean=True):\n \"\"\"Create a TransformationXput for this Transformation.\n\n Decides whether the created TransformationXput should have a\n structure or not based on the parameters given. If\n compounddatatype os None but row limits are provided, then a\n ValueError is raised.\n\n PARAMETERS\n dataset_name name for new xput\n dataset_idx index for new output (defaults to number of\n current in/outputs plus one)\n compounddatatype CompoundDatatype for new xput\n row_limits tuple (min_row, max_row), defaults to no limits\n coords tuple (x, y), defaults to (0, 0)\n input True to create a TransformationInput, False to\n create a TransformationOutput\n \"\"\"\n min_row, max_row = (None, None) if not row_limits else row_limits\n x, y = (0, 0) if not coords else coords\n\n if compounddatatype is None and (min_row is not None or max_row is not None):\n raise ValueError(\"Row restrictions cannot be specified without a CDT\")\n\n xputs = self.inputs if input else self.outputs\n new_xput = xputs.create(dataset_name=dataset_name, dataset_idx=dataset_idx or xputs.count()+1, x=x, y=y)\n if clean:\n new_xput.full_clean()\n if compounddatatype:\n new_xput.add_structure(compounddatatype, min_row, max_row, clean=clean)\n return new_xput\n\n def create_input(self, dataset_name, dataset_idx=None, compounddatatype=None,\n min_row=None, max_row=None, x=0, y=0, clean=True):\n \"\"\"Create a TransformationInput for this Transformation.\"\"\"\n return self.create_xput(dataset_name, dataset_idx, compounddatatype, (min_row, max_row), (x, y), True,\n clean=clean)\n\n def create_output(self,\n dataset_name,\n dataset_idx=None,\n compounddatatype=None,\n min_row=None,\n max_row=None,\n x=0,\n y=0,\n clean=True):\n \"\"\"Create a TransformationOutput for this Transformation.\"\"\"\n return self.create_xput(dataset_name, dataset_idx, compounddatatype, (min_row, max_row), (x, y), False,\n clean=clean)\n\n def find_update(self):\n update = self.definite.family.members.latest('revision_number')\n members = list(self.definite.family.members.all())\n return update if update.id != self.id else None\n\n\n@python_2_unicode_compatible\nclass TransformationXput(models.Model):\n \"\"\"\n Describes parameters common to all inputs and outputs\n of transformations - the \"holes\"\n\n Related to :models:`transformation.Transformation`\n \"\"\"\n # transformation, dataset_name, and dataset_idx have been moved to\n # the derived classes so they can have their own unique_together\n # constraints. structure is implicitly defined via a OneToOneField\n # on the XputStructure, as is execrecordouts_referencing (via FK\n # from librarian.ExecRecordOut)\n\n # UI information.\n x = models.FloatField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)])\n y = models.FloatField(default=0, validators=[MinValueValidator(0), MaxValueValidator(1)])\n\n @property\n def is_input(self):\n return hasattr(self, 'transformationinput')\n\n @property\n def is_output(self):\n return hasattr(self, 'transformationoutput')\n\n @property\n def definite(self):\n if self.is_input:\n return self.transformationinput\n else:\n return self.transformationoutput\n\n def clean(self):\n \"\"\"Make sure this is either a TransformationInput or TransformationOutput.\"\"\"\n if not self.is_input and not self.is_output:\n raise ValidationError(\"TransformationXput with pk={} is neither an input nor an output\".format(self.pk))\n if self.has_structure:\n self.structure.clean()\n\n def __str__(self):\n if self.is_input or self.is_output:\n return \"{}: {}\".format(self.definite.dataset_idx,\n self.definite.dataset_name)\n return 'TransformationXput(id={})'.format(self.id)\n\n @property\n def compounddatatype(self):\n return None if self.is_raw() else self.structure.compounddatatype\n\n def is_raw(self):\n \"\"\"True if this Xput is raw, false otherwise.\"\"\"\n return not self.has_structure\n\n def get_cdt(self):\n \"\"\"Accessor that returns the CDT of this xput (and None if it is raw).\"\"\"\n return None if self.is_raw() else self.structure.compounddatatype\n\n def get_min_row(self):\n \"\"\"Accessor that returns min_row for this xput (and None if it is raw).\"\"\"\n return (None if self.is_raw() else self.structure.min_row)\n\n def get_max_row(self):\n \"\"\"Accessor that returns max_row for this xput (and None if it is raw).\"\"\"\n return (None if self.is_raw() else self.structure.max_row)\n\n def is_identical(self, other):\n \"\"\"Is this TransformationXput the same as another?\n\n Ignores names and indices.\n \"\"\"\n if self.is_input != other.is_input:\n return False\n\n if self.is_raw() and other.is_raw():\n return True\n if self.is_raw() or other.is_raw():\n return False\n return self.structure.is_identical(other.structure)\n\n @property\n def has_structure(self):\n # return hasattr(self, \"structure\")\n try:\n self.structure\n except ObjectDoesNotExist:\n return False\n return True\n\n @transaction.atomic\n def add_structure(self, compounddatatype, min_row, max_row, clean=True):\n \"\"\"Add an XputStructure to this TransformationXput.\n\n ASSUMPTIONS\n This TransformationXput does not already have a structure.\n \"\"\"\n assert not self.has_structure\n assert compounddatatype is not None\n\n new_structure = XputStructure(\n transf_xput=self,\n compounddatatype=compounddatatype,\n min_row=min_row, max_row=max_row)\n if clean:\n new_structure.full_clean()\n new_structure.save()\n\n\nclass XputStructure(models.Model):\n \"\"\"\n Describes the \"holes\" that are managed by Shipyard: i.e. the ones\n that correspond to well-understood CSV formatted data.\n\n Related to :model:`transformation.TransformationXput`\n \"\"\"\n transf_xput = models.OneToOneField(TransformationXput, related_name=\"structure\")\n\n # The expected compounddatatype of the input/output\n compounddatatype = models.ForeignKey(\"metadata.CompoundDatatype\", related_name=\"xput_structures\")\n\n # Nullable fields indicating that this dataset has\n # restrictions on how many rows it can have\n min_row = models.PositiveIntegerField(\n \"Minimum rows\",\n help_text=\"Minimum number of rows this input/output returns\",\n null=True,\n blank=True)\n\n max_row = models.PositiveIntegerField(\n \"Maximum rows\",\n help_text=\"Maximum number of rows this input/output returns\",\n null=True,\n blank=True)\n\n def clean(self):\n tr = self.transf_xput.definite.transformation\n tr.validate_restrict_access([self.compounddatatype])\n\n if self.min_row is not None and self.max_row is not None:\n if self.min_row > self.max_row:\n raise ValidationError(\"Minimum row must not exceed maximum row\",\n code=\"min_max\")\n\n def is_identical(self, other):\n \"\"\"Is this XputStructure identical to another one?\"\"\"\n return (self.compounddatatype == other.compounddatatype and\n self.min_row == other.min_row and\n self.max_row == other.max_row)\n\n\nclass TransformationInput(TransformationXput):\n \"\"\"\n Inherits from :model:`transformation.TransformationXput`\n \"\"\"\n transformation = models.ForeignKey(Transformation, related_name=\"inputs\")\n\n # The name of the input \"hole\".\n dataset_name = models.CharField(\n \"input name\",\n max_length=maxlengths.MAX_NAME_LENGTH,\n help_text=\"Name for input as an alternative to index\",\n validators=[validate_slug])\n\n # Input index on the transformation.\n dataset_idx = models.PositiveIntegerField(\n \"input index\",\n validators=[MinValueValidator(1)],\n help_text=\"Index defining the relative order of this input\")\n\n class Meta:\n # A transformation cannot have multiple definitions for column name or column index\n unique_together = ((\"transformation\", \"dataset_name\"),\n (\"transformation\", \"dataset_idx\"))\n ordering = ('dataset_idx', )\n\n\nclass TransformationOutput(TransformationXput):\n \"\"\"\n Inherits from :model:`transformation.TransformationXput`\n \"\"\"\n # Similarly to TransformationInput.\n # transformationxput = models.OneToOneField(TransformationXput, parent_link=True)\n transformation = models.ForeignKey(Transformation, related_name=\"outputs\")\n\n dataset_name = models.CharField(\n \"output name\",\n max_length=maxlengths.MAX_NAME_LENGTH,\n help_text=\"Name for output as an alternative to index\",\n validators=[validate_slug])\n\n dataset_idx = models.PositiveIntegerField(\n \"output index\",\n validators=[MinValueValidator(1)],\n help_text=\"Index defining the relative order of this output\")\n\n class Meta:\n # A transformation cannot have multiple definitions for column name or column index\n unique_together = ((\"transformation\", \"dataset_name\"),\n (\"transformation\", \"dataset_idx\"))\n ordering = ('dataset_idx', )\n","sub_path":"kive/transformation/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":18440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"109897871","text":"\"\"\"\ntimework 0.2.8\n\nMIT License © bugstop\n\nPyPI: https://pypi.org/project/timework/\nGitHub: https://github.com/bugstop/timework-timeout-decorator/\n\n\nCross-platform python module to set execution time limits as decorators.\n\ntimework.timer - a decorator measuring the execution time.\ntimework.limit - a decorator limiting the execution time.\ntimework.iterative - a decorator used to process iterative deepening.\n\"\"\"\n\n\nfrom .timework import *\n\n__name__ = 'timework'\n__version__ = '0.2.8'\n__all__ = ['timer', 'limit', 'iterative']\n","sub_path":"timework/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"218735092","text":"import random\r\nimport pickle\r\nimport pygame\r\nimport time\r\n\r\ndef display_update(text,screen):\r\n \r\n #Modified from: https://sivasantosh.wordpress.com/2012/07/18/displaying-text-in-pygame/\r\n #updates the display - white background & text box\r\n textrect = text.get_rect()\r\n textrect.centerx = screen.get_rect().centerx\r\n textrect.centery = screen.get_rect().centery\r\n screen.fill((255,255,255))\r\n \r\n screen.blit(text, textrect)\r\n pygame.display.update()\r\n\r\ndef menu():\r\n #Modified from: http://www.pygame.org/docs/tut/tom/games2.html and: https://sivasantosh.wordpress.com/2012/07/18/displaying-text-in-pygame/\r\n pygame.init()\r\n pygame.display.set_mode((900,400))\r\n screen = pygame.display.set_mode((900,400)) # Set screen size of pygame window\r\n background = pygame.Surface(screen.get_size()) # Create empty pygame surface\r\n background.fill((255, 255, 255)) # A white background \r\n background = background.convert()\r\n basicfont = pygame.font.SysFont('Arial', 16)#Font is Arial\r\n text = basicfont.render(\"\"\"Welcome - do you have what it takes to master four levels of word puzzles, maths challenges and quiz questions? (click to proceed)\"\"\", True, (0, 0, 0))\r\n display_update(text,screen)\r\n while True:\r\n for event in pygame.event.get():\r\n #When the mouse is clicked the next instruction is shown\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n background_image = pygame.image.load(\"background.jpg\").convert()\r\n screen.blit(background_image, [0,0])\r\n pygame.display.update()\r\n\r\n \r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_1:\r\n text = basicfont.render(\"\"\"You will now be taken to the game...\"\"\", True, (0, 0, 0))\r\n display_update(text,screen)\r\n pygame.quit()\r\n main()\r\n \r\n \r\n if event.key == pygame.K_2:\r\n text = basicfont.render(\"\"\"You can search for your personal best score...\"\"\", True, (0, 0, 0))\r\n display_update(text,screen)\r\n pygame.quit()\r\n name = input(\"What is your name?\\n\")\r\n find_score(name)\r\n menu()\r\n \r\n if event.key == pygame.K_3:\r\n text = basicfont.render(\"\"\"You can view the high scores...\"\"\", True, (0, 0, 0))\r\n display_update(text,screen)\r\n pygame.quit()\r\n viewhigh()\r\n menu()\r\n \r\n \r\n if event.key == pygame.K_4:\r\n pygame.quit()\r\n print(\"You have exited the game\")\r\n \r\n#The questions are located in a file\r\ndef open_file(file_name, mode):\r\n file = open(file_name, mode)\r\n return file\r\n\r\n#The file is read - this is used in read_file function\r\n#Modified from http://www.delmarlearning.com/companions/content/1435455002/downloads/index.asp chapter 7 trivia_challenge.py\r\ndef read_line(file):\r\n line = file.readline()\r\n return line\r\n \r\ndef read_file(file):\r\n \r\n #The lines of the file are read using the read_line function\r\n description = read_line(file)\r\n question = read_line(file)\r\n #Possible answers are shown\r\n #read 4 lines\r\n possible_answer1 = read_line(file)\r\n possible_answer2 = read_line(file)\r\n possible_answer3 = read_line(file)\r\n possible_answer4 = read_line(file)\r\n correct_answer = read_line(file)\r\n #correct answer is the first character of the next line\r\n if correct_answer:\r\n correct_answer = correct_answer[0]\r\n answer_description = read_line(file)\r\n points = read_line(file)\r\n #The lines read from the file are returned\r\n return description, question, possible_answer1, possible_answer2, possible_answer3, possible_answer4, correct_answer, answer_description, points\r\n \r\ndef level_one(scorelist):\r\n #The file is printed\r\n score = 0\r\n one_file = open_file(\"level one.txt\", \"r\")\r\n description, question, possible_answer1, possible_answer2, possible_answer3, possible_answer4, correct_answer, answer_description, points = read_file(one_file)\r\n while description:\r\n #While there is text in the description line the file is printed \r\n print(description)\r\n print(question)\r\n print(possible_answer1)\r\n print(possible_answer2)\r\n print(possible_answer3)\r\n print(possible_answer4)\r\n answer = input(\"What is your answer? \")\r\n if answer == correct_answer:\r\n print(\"Well done. You gained\", points,\" point(s)\")\r\n score += int(points)\r\n print(answer_description)\r\n else:\r\n print(\"That's wrong!\",answer_description)\r\n print(\"Score:\", score, \"\\n\")\r\n \r\n \r\n description, question, possible_answer1, possible_answer2, possible_answer3, possible_answer4, correct_answer, answer_description, points = read_file(one_file) \r\n one_file.close()\r\n #add level one score to list\r\n scorelist.append(score)\r\n print(\"Your score for Level One is\", score,\"\\n\")\r\n\r\n\r\ndef level_two(scorelist):\r\n score = 0\r\n two_file = open_file(\"level two.txt\", \"r\")\r\n #The file is printed \r\n description, question, possible_answer1, possible_answer2, possible_answer3, possible_answer4, correct_answer, answer_description, points = read_file(two_file)\r\n while description:\r\n #While there is text in the description line the file is printed \r\n print(description)\r\n print(question)\r\n print(possible_answer1)\r\n print(possible_answer2)\r\n print(possible_answer3)\r\n print(possible_answer4)\r\n answer = input(\"What is your answer? \")\r\n if answer == correct_answer:\r\n print(\"Well done. You gained\", points,\" point(s)\")\r\n score += int(points)\r\n \r\n print(answer_description)\r\n else:\r\n print(\"That's wrong!\",answer_description)\r\n print(\"Score:\", score, \"\\n\")\r\n \r\n \r\n description, question, possible_answer1, possible_answer2, possible_answer3, possible_answer4, correct_answer, answer_description, points = read_file(two_file) \r\n two_file.close()\r\n #add level one score to list\r\n scorelist.append(score)\r\n print(\"Your score for Level Two is\", score,\"\\n\")\r\n\r\n\r\n#Bonus question for low scores\r\ndef bonus_question(scorelist):\r\n score = 0\r\n three_file = open_file(\"level three.txt\", \"r\")\r\n #The file is printed \r\n description, question, possible_answer1, possible_answer2, possible_answer3, possible_answer4, correct_answer, answer_description, points = read_file(three_file)\r\n while description:\r\n #While there is text in the description line the file is printed \r\n print(description)\r\n print(question)\r\n print(possible_answer1)\r\n print(possible_answer2)\r\n print(possible_answer3)\r\n print(possible_answer4)\r\n answer = input(\"What is your answer? \")\r\n if answer == correct_answer:\r\n print(\"Well done. You gained\", points,\" point(s)\")\r\n score += int(points)\r\n \r\n print(answer_description)\r\n else:\r\n print(\"That's wrong!\",answer_description)\r\n print(\"Score:\", score, \"\\n\")\r\n \r\n \r\n description, question, possible_answer1, possible_answer2, possible_answer3, possible_answer4, correct_answer, answer_description, points = read_file(three_file) \r\n three_file.close()\r\n #add level one score to list\r\n scorelist.append(score)\r\n print(\"Your score for Level Three is\", score,\"\\n\")\r\n\r\n \r\n \r\n \r\n# level three is a maths challenge question\r\n#The challenge is generated randomly from a dictionary\r\ndef level_three(scorelist):\r\n challenges = {\"I have travelled 1.6Km in 20 mins, how far have I gone after 30mins, in meters?\":\"2400\",\"What is pi to 3 decimal places?\":\"3.141\",\"I have a pentagon and a nonagon how many sides do I have?\":\"14\",\"\"\"\r\nWhat is 6 to the power of 0?\"\"\":\"0\",\"My car weighs 2000Kg, I weigh 20x less. How much does the car weigh if I get in, in Kg?\":\"2100\",\"\"\"It takes 15 minutes to get home on the bus. It's average speed is 20mph, how far\r\naway do I live in miles?\"\"\":\"5\",\"I want to buy milk & bread at £1.49 & £1.20 respectively. I have 2 50p coins & 4 20p coins, can I afford it?(y/n)\":\"y\",\"\"\"If I walk 20 meters then stop, walk another 40 meters and then come back.\r\nWhat is my displacement?\"\"\":\"0\"}\r\n tries = 0\r\n score = 0\r\n print(\"Here's some tricky maths questions\")\r\n while tries < 5:\r\n challenge = random.choice(list(challenges))\r\n print(challenge)\r\n playeranswer = input(\"\")\r\n answer = challenges[challenge]\r\n tries += 1\r\n if playeranswer == answer:\r\n score += 3\r\n print(\"Well Done\\n\")\r\n \r\n else:\r\n print(\"That's wrong, the answer is\", answer)\r\n #add score to list\r\n scorelist.append(score)\r\n \r\n\r\n\r\ndef level_four(scorelist):\r\n #Modified from: http://stackoverflow.com/questions/27732736/pygame-key-pressed Author: Pyboss\r\n score = 0\r\n pygame.init()\r\n pygame.display.set_mode((900,400))\r\n screen = pygame.display.set_mode((900,400)) # Set screen size of pygame window\r\n background = pygame.Surface(screen.get_size()) # Create empty pygame surface\r\n background.fill((255, 255, 255)) # A white background \r\n background = background.convert()\r\n background_image = pygame.image.load(\"four_welcome.jpg\").convert()\r\n screen.blit(background_image, [0,0])\r\n pygame.display.update()\r\n running = True\r\n\r\n while running:\r\n for event in pygame.event.get():\r\n #When the mouse is clicked the next instruction is shown\r\n if event.type == pygame.MOUSEBUTTONDOWN:\r\n background_image = pygame.image.load(\"four_q1.jpg\").convert()\r\n screen.blit(background_image, [0,0])\r\n pygame.display.update()\r\n if event.type == pygame.KEYDOWN:\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n #If 8 is pressed an image is displayed\r\n if event.key == pygame.K_8:\r\n score += 2\r\n background_image = pygame.image.load(\"four_q2.jpg\").convert()\r\n screen.blit(background_image, [0,0])\r\n pygame.display.update()\r\n if event.key == pygame.K_9:\r\n score -= 3\r\n background_image = pygame.image.load(\"four_q2WRONG.jpg\").convert()\r\n screen.blit(background_image, [0,0])\r\n pygame.display.update()\r\n if event.key == pygame.K_LEFT:\r\n score += 3\r\n background_image = pygame.image.load(\"four_q3.jpg\").convert()\r\n screen.blit(background_image, [0,0])\r\n pygame.display.update()\r\n if event.key == pygame.K_RIGHT:\r\n score -= 4\r\n background_image = pygame.image.load(\"four_q3WRONG.jpg\").convert()\r\n screen.blit(background_image, [0,0])\r\n pygame.display.update()\r\n \r\n print(\"That's the end of level four\")\r\n #The pygame window closes\r\n running = False\r\n \r\n if event.key == pygame.K_f:\r\n score += 2\r\n background_image = pygame.image.load(\"four_q4.jpg\").convert()\r\n screen.blit(background_image, [0,0])\r\n pygame.display.update()\r\n \r\n print(\"That's the end of level four\")\r\n \r\n running = False\r\n \r\n if event.key == pygame.K_g:\r\n score -= 2\r\n background_image = pygame.image.load(\"four_q4WRONG.jpg\").convert()\r\n screen.blit(background_image, [0,0])\r\n pygame.display.update()\r\n \r\n print(\"That's the end of level four\")\r\n \r\n running = False\r\n \r\n #To close the window False is called \r\n while not running:\r\n #While running = False the window closes\r\n pygame.quit()\r\n #Score is added to list\r\n scorelist.append(score)\r\n break\r\n\r\n\r\ndef high_score(total):\r\n #The highscore is read & if it is beaten it will be replaced\r\n file = open(\"highscore.txt\", \"r\")\r\n highscore = file.readline()\r\n print (\"The high score is\",highscore)\r\n file.close()\r\n if total > int(highscore):\r\n file = open(\"highscore.txt\", \"w\")\r\n file.write(str(total))\r\n print(\"Well done you have beaten the high score!\\n Your score of\", total, \"has beaten\", highscore,\" to be the new highscore!\")\r\n file.close()\r\n\r\ndef viewhigh():\r\n #Used as menu option to see high score\r\n file = open(\"highscore.txt\", \"r\")\r\n highscore = file.readline()\r\n print (\"The high score is...\", highscore)\r\n file.close()\r\n\r\n\r\n\r\n#Saves the players score into a file\r\n\r\ndef score_save(name,total,oldscore):\r\n #If player hasn't played before their score is saved\r\n if oldscore == 0:\r\n print(\"Your score has been saved for you to beat next time\")\r\n file = open('saved_scores.txt', 'ab+')\r\n scores = {name:total}\r\n pickle.dump(scores,file)\r\n file.close\r\n elif total > int(oldscore):\r\n print(\"You have beaten your previous best!\")\r\n #If new score is better than their last score it is saved\r\n file = open('saved_scores.txt', 'ab+')\r\n scores_dict = pickle.load(file)\r\n #Their past best score is deleted\r\n del scores_dict[name]\r\n scores = {name:total}\r\n pickle.dump(scores,file)\r\n print (scores)\r\n file.close\r\n else:\r\n print(\"You didn't beat your previous score!\")\r\n\r\ndef find_score(name):\r\n #The players last score is found if they have played before\r\n file = open('saved_scores.txt', 'rb')\r\n scores_dict = pickle.load(file)\r\n name = name\r\n if name in scores_dict:\r\n oldscore = scores_dict[name]\r\n print (\"You previous best is\", oldscore, \",try to beat it!\")\r\n \r\n else:\r\n print(\"You haven't played before!\")\r\n\r\n\r\ndef main():\r\n #A list is created to store scores\r\n scorelist = []\r\n oldscore = 0\r\n name = input(\"What is your name?\")\r\n find_score(name)\r\n #start the timer\r\n start = time.time()\r\n level_one(scorelist)\r\n #whether the player moves up a level depends on their score\r\n total = sum(scorelist)\r\n if total > 3:\r\n level_two(scorelist)\r\n total = sum(scorelist)\r\n else:\r\n print(\"You needed 3 points to continue, you only got\", total)\r\n print(\"Oh dear, you haven't scored highly enough to progress\")\r\n score_save(total, oldscore, name)\r\n if total < 10:\r\n #If the total is less than 10 a bonus level is played - to boost players score\r\n bonus_question(scorelist)\r\n total = sum(scorelist)\r\n level_three(scorelist)\r\n total = sum(scorelist)\r\n level_four(scorelist)\r\n #The scores from each level are added together to give a total score\r\n total = sum(scorelist)\r\n print(\"And that's the end of the game!\")\r\n print(\"You scored\", total, \"points\")\r\n #end the timer\r\n end = time.time()\r\n #Work out how long it took to finush game\r\n timer = int(end) - int(start)\r\n print(\"And it took you\", timer, \"seconds to complete the game\")\r\n score_save(name,total,oldscore)\r\n high_score(total)\r\n #Ask the user if they want to play again\r\n again = input(\"Do you want to play again?(y/n)\")\r\n if again == \"y\":\r\n menu()\r\n else:\r\n print(\"Thankyou for playing\")\r\n input(\"\\n\\nPress enter to exit\")\r\n\r\n \r\nmenu() \r\nmain()\r\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":16209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"601939299","text":"from lineup_optimizer.baseball import Batter, Game\nfrom itertools import permutations\n\n\ndef main(N = 1_000_000):\n batters = read()\n baseline = sum(Game(batters).simulate() for _ in range (N)) / N\n print(baseline)\n optimized = optimize(batters)\n score = sum(Game(optimized).simulate() for _ in range (N)) / N\n print(score)\n write(original=[batters, baseline, 'Original lineup'],\n optimized=[optimized, score, 'Optimized lineup'])\n\n\ndef read():\n \"\"\"\n Reads the batter's stats.\n Returns a list of batters.\n \"\"\"\n with open('lineup_optimizer/batters.csv', 'r') as f:\n lines = list(f)[1:]\n batters = [read_one(line) for line in lines]\n return batters\n\n\ndef read_one(line):\n \"\"\"\n Takes a line with one batter's stats.\n Returns a batter.\n \"\"\"\n name, *stats = line.strip().split(',')\n stats = [int(stat) for stat in stats]\n return Batter(name, *stats)\n\n\ndef optimize(batters):\n \"\"\"\n Takes a list of batters.\n Returns a re-ordering, with a high expected runs per game.\n \"\"\"\n candidates = permutations(batters)\n lineup = champion(candidates)\n return lineup\n\n\ndef champion(lineups, trials=1):\n \"\"\"\n Takes an iterable of lineups.\n Returns one of these lineups, with a high expected runs per game.\n \"\"\"\n scores = {lineup: sum(Game(lineup).simulate() for _ in range(trials))\n for lineup in lineups}\n mean = sum(scores.values()) / len(scores)\n print(f'tried {len(scores)} options: mean score = {mean / trials}')\n survivors = [lineup for lineup, score in scores.items() if score >= mean]\n if len(survivors) == 1:\n return survivors[0]\n return champion(survivors, trials * 2)\n\n\ndef write(original, optimized):\n \"\"\"\n Takes lists of lineups, scores, and lineup names.\n Writes them to README.md\n \"\"\"\n with open('lineup_optimizer/head.md', 'r') as f:\n head = f.read()\n chunks = [head]\n for lineup, score, name in [original, optimized]:\n numbered = (f'{d+1}. {batter}' for d, batter in enumerate(lineup))\n body = '\\n'.join(numbered)\n tail = f'Expected runs per game: {score}'\n chunks.append(f'## {name}:\\n{body}\\n\\n{tail}')\n text = '\\n\\n'.join(chunks)\n with open('lineup_optimizer/README.md', 'w') as f:\n f.write(text)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"lineup_optimizer/optimize.py","file_name":"optimize.py","file_ext":"py","file_size_in_byte":2358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"264987377","text":"import datetime\nimport itertools\nimport json\nfrom urllib.parse import urlencode\n\nfrom apollo.backend import BaseCrawler\nfrom apollo.modules import Line, Record\n\nheaders = {\n \"Accept\": \"application/json, text/plain, */*\"\n}\n\n\nclass Crawler(BaseCrawler):\n def collect(self):\n geos = [\"US\", \"TR\"]\n cats = [\"b\", \"t\", \"h\"]\n mapped_args = list(itertools.product(geos, cats))\n\n result = []\n\n for geo, cat in mapped_args:\n result.extend(self.real_time(geo=geo, cat=cat))\n\n return result\n\n ##################################################################\n\n def real_time(self, geo=\"TR\", cat=\"h\"):\n base_url = \"https://trends.google.com.tr/trends/api/realtimetrends\"\n url = base_url + \"?\" + urlencode({\n \"hl\": \"en\", \"cat\": cat, \"geo\": geo, \"tz\": -180,\n \"fi\": 0, \"fs\": 0, \"ri\": 300, \"rs\": 20, \"sort\": 0,\n })\n response = self.make_get(url=url, headers=headers)\n\n ###########################################################################\n\n geo_map = {\n \"TR\": \"Türkiye\",\n \"US\": \"ABD\",\n }\n cat_map = {\n \"t\": \"Bilim/Teknoloji\",\n \"b\": \"İş\",\n \"h\": \"En çok görüntülenen Haberler\",\n }\n\n raw_data = response.text.replace(')]}\\'', '')\n data = json.loads(raw_data)\n\n stories = data[\"storySummaries\"][\"trendingStories\"]\n id_list = [item[\"id\"] for item in stories]\n\n lines_data = self.spark_lines(id_list)\n\n return [Record(\n id=item[\"id\"],\n created_at=datetime.datetime.now(),\n category=cat_map.get(cat),\n country=geo_map.get(geo),\n\n entities=item['entityNames'],\n lines=lines_data.get(item[\"id\"]),\n articles=[{\n \"title\": article[\"articleTitle\"],\n \"snippet\": article[\"snippet\"],\n \"time\": article[\"time\"]\n } for article in item[\"articles\"]],\n ) for item in stories]\n\n def spark_lines(self, id_list):\n base_url = \"https://trends.google.com.tr/trends/api/widgetdata/sparkline\"\n url = base_url + \"?hl=en&tz=-180&id=\" + \"&id=\".join(id_list)\n response = self.make_get(url=url, headers=headers)\n\n raw_data = response.text.replace(')]}\\',', '')\n data = json.loads(raw_data)\n responses = data[\"default\"][\"response\"]\n\n result = {}\n\n for id_, response in zip(id_list, responses):\n result[id_] = [Line(\n record_id=id_,\n time_at=item[\"time\"],\n value=item[\"value\"],\n ) for item in response[\"timelineResponse\"][\"timelineData\"]]\n\n return result\n","sub_path":"apollo/crawlers/google_trends.py","file_name":"google_trends.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"282627788","text":"#!usr/bin/python\n# -*- coding:utf8 -*-\nfrom flask import Flask\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\n\n# 相关配置\napp.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:mysql@127.0.0.1:3306/test31'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SQLALCHEMY_ECHO'] = True\n\n# 创建组件对象\ndb = SQLAlchemy(app)\n\n\n# 构建模型类 商品表\nclass Goods(db.Model):\n __tablename__ = 't_good'\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(20), unique=True)\n count = db.Column(db.Integer)\n\n\n@app.route('/del')\ndef delete():\n \"\"\"删除数据\"\"\"\n\n good = Goods.query.filter(Goods.name == '方便面').first()\n db.session.delete(good)\n db.session.commit()\n\n return \"index\"\n\n\nif __name__ == '__main__':\n # 重置数据库数据\n db.drop_all()\n db.create_all()\n\n # 添加一条测试数据\n goods = Goods(name='方便面', count=1)\n db.session.add(goods)\n db.session.commit()\n app.run(debug=True)","sub_path":"FlaskFramework/flaskpractice/flask_sqlalchemy扩展/08_先查询再删除.py","file_name":"08_先查询再删除.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"332483048","text":"import csv\n\nfrom flask import request\nfrom flask_restful import Resource\n\nfrom LRUtilities.DataCollection import AmrConfigFile\nfrom . import api_v1\nfrom app.api import Field, MyForm, api, caps, get_model, simple_validators, validators\nfrom db import database as db\nfrom db.model import PerformanceMetaCategory, RecordingPlatform\nfrom lib.metadata_validation import MetaValidator\n\n\nclass ListResource(Resource):\n\t\n\tmethod_decorators = [\n\t\tget_model(RecordingPlatform),\n\t\tcaps(),\n\t\tapi\n\t]\n\n\tdef get(self, recording_platform):\n\t\treturn {\"metaCategories\": PerformanceMetaCategory.dump(recording_platform.performance_meta_categories)}\n\n\tdef post(self, recording_platform):\n\n\t\tdata = MyForm(\n\t\t\tField('name', is_mandatory=True,\n\t\t\t\tvalidators=[\n\t\t\t\t\t(PerformanceMetaCategory.check_name_unique, (recording_platform,)),\n\t\t\t]),\n\t\t\tField('extractor', is_mandatory=True,\n\t\t\t\tnormalizer=PerformanceMetaCategory.normalize_extractor,\n\t\t\t\tvalidators=[\n\t\t\t\t\trecording_platform.check_extractor,\n\t\t\t\t]\n\t\t\t),\n\t\t\tField('validatorSpec', is_mandatory=True,\n\t\t\t\tvalidators=[\n\t\t\t\t\tPerformanceMetaCategory.check_validator,\n\t\t\t\t]\n\t\t\t),\n\t\t).get_data()\n\n\t\tperformance_meta_category = PerformanceMetaCategory(\n\t\t\trecording_platform=recording_platform,\n\t\t\tname=data[\"name\"],\n\t\t\textractor=data.get(\"extractor\"),\n\t\t\tvalidator_spec=data[\"validatorSpec\"],\n\t\t)\n\n\t\tdb.session.add(performance_meta_category)\n\t\tdb.session.commit()\n\t\treturn {\"metaCategory\": performance_meta_category.serialize()}\n\n\nclass UploadResource(Resource):\n\n\tmethod_decorators = [\n\t\tget_model(RecordingPlatform),\n\t\tcaps(),\n\t\tapi\n\t]\n\n\tdef post(self, recording_platform):\n\n\t\t# TODO check configured loader\n\n\t\tif recording_platform.performance_meta_categories:\n\t\t\traise InvalidUsage(\"performance meta categories already exist; unable to upload config file\")\n\n\t\tif not \"file\" in request.files:\n\t\t\traise InvalidUsage(\"no config file provided\")\n\n\t\tamr_config_file = AmrConfigFile.load(request.files[\"file\"])\n\n\t\tfor amr_category in amr_config_file.demographics:\n\t\t\tvalidator = MetaValidator.from_amr_demographic_category(amr_category)\n\n\t\t\tmeta_category = PerformanceMetaCategory(\n\t\t\t\trecording_platform=recording_platform,\n\t\t\t\tname=amr_category.title,\n\t\t\t\textractor={\"source\": \"Log File\", \"key\": amr_category.id},\t# TODO get log file string from loader constant\n\t\t\t\tvalidator_spec=validator.to_dict(),\n\t\t\t)\n\n\t\t\tdb.session.add(meta_category)\n\n\t\tdb.session.commit()\n\t\treturn {\"metaCategories\": PerformanceMetaCategory.dump(recording_platform.performance_meta_categories)}\n\n\n\napi_v1.add_resource(\n\tListResource,\n\t\"recording-platforms//performancemetacategories\",\n\tendpoint=\"recording_platform_session_meta_categories\"\n)\n\napi_v1.add_resource(\n\tUploadResource,\n\t\"recording-platforms//performancemetacategories/upload\",\n\tendpoint=\"recording_platform_session_meta_categories_upload\"\n)\n","sub_path":"app/api/v1_0/recording_platform_session_meta_categories.py","file_name":"recording_platform_session_meta_categories.py","file_ext":"py","file_size_in_byte":2860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"64194974","text":"import os\nif 'voleti.vikram' in os.getcwd():\n import matplotlib\n matplotlib.use('Agg')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow as tf\n\n# np.random.seed(29)\ntf.set_random_seed(29)\n\nfrom keras import backend as K\nfrom keras.models import Model, Sequential, model_from_json, model_from_yaml\nfrom keras.layers import Masking, TimeDistributed, Conv2D, BatchNormalization, Activation, MaxPooling2D, AveragePooling2D\nfrom keras.layers import Flatten, Dense, Input, Reshape, Add, Concatenate, LSTM, Dropout\nfrom keras.regularizers import l2\nfrom keras.callbacks import Callback\n\nfrom assessor_params import *\nfrom resnet import *\nfrom syncnet_functions import *\n\n#########################################################\n# MODEL\n#########################################################\n\n\ndef my_assessor_model(use_CNN_LSTM=True, use_head_pose=True, mouth_nn='cnn', trainable_syncnet=False,\n grayscale_images=False, my_resnet_repetitions=[2, 2, 2, 2],\n conv_f_1=32, conv_f_2=64, conv_f_3=128, mouth_features_dim=512,\n lstm_units_1=32, use_softmax=True, use_softmax_ratios=False,\n individual_dense=False, lr_dense_fc=8, lr_softmax_fc=8,\n dense_fc_1=128, dropout_p1=0.2, dense_fc_2=64, dropout_p2=0.2, last_fc=None,\n residual_part=False, res_fc_1=2, res_fc_2=2):\n\n if grayscale_images:\n MOUTH_CHANNELS = 1\n\n if mouth_nn == 'syncnet':\n MOUTH_CHANNELS = 5\n\n my_input_n_of_frames = Input(shape=(1,), name='n_of_frames')\n my_input_lipreader_dense = Input(shape=(1024,), name='lipreader_middle')\n\n if use_CNN_LSTM:\n\n if mouth_nn == 'syncnet_preds':\n my_input_mouth_images = Input(shape=(TIME_STEPS, 128), name='syncnet_preds')\n cnn_features = my_input_mouth_images\n else:\n mouth_input_shape = (MOUTH_H, MOUTH_W, MOUTH_CHANNELS)\n my_input_mouth_images = Input(shape=(TIME_STEPS, *mouth_input_shape), name='mouth_images')\n if mouth_nn == 'cnn':\n mouth_feature_model = my_timedistributed_cnn_model((TIME_STEPS, *mouth_input_shape), conv_f_1, conv_f_2, conv_f_3, mouth_features_dim)\n elif mouth_nn == 'resCNN':\n mouth_feature_model = my_resnet_like_timeDistributed_CNN((TIME_STEPS, *mouth_input_shape), conv_f_1, conv_f_2, conv_f_3, mouth_features_dim)\n elif mouth_nn == 'resnet18':\n mouth_feature_model = ResnetBuilder.build_resnet_18((TIME_STEPS, *mouth_input_shape), mouth_features_dim, time_distributed=True)\n elif mouth_nn == 'resnet34':\n mouth_feature_model = ResnetBuilder.build_resnet_34((TIME_STEPS, *mouth_input_shape), mouth_features_dim, time_distributed=True)\n elif mouth_nn == 'resnet50':\n mouth_feature_model = ResnetBuilder.build_resnet_50((TIME_STEPS, *mouth_input_shape), mouth_features_dim, time_distributed=True)\n elif mouth_nn == 'resnet101':\n mouth_feature_model = ResnetBuilder.build_resnet_101((TIME_STEPS, *mouth_input_shape), mouth_features_dim, time_distributed=True)\n elif mouth_nn == 'resnet152':\n mouth_feature_model = ResnetBuilder.build_resnet_152((TIME_STEPS, *mouth_input_shape), mouth_features_dim, time_distributed=True)\n elif mouth_nn == 'my_resnet':\n mouth_feature_model = ResnetBuilder.build((TIME_STEPS, *mouth_input_shape), mouth_features_dim, basic_block, my_resnet_repetitions, time_distributed=True)\n elif mouth_nn == 'flatten':\n mouth_feature_model = Reshape((TIME_STEPS, -1), input_shape=(TIME_STEPS, *mouth_input_shape))\n elif mouth_nn == 'syncnet':\n mouth_feature_model = TimeDistributed(load_pretrained_syncnet_model(version='v4', mode='lip', verbose=False), input_shape=(TIME_STEPS, *mouth_input_shape), name='syncnet')\n if not trainable_syncnet:\n mouth_feature_model.layer.trainable = False\n cnn_features = mouth_feature_model(my_input_mouth_images)\n\n if use_head_pose:\n my_input_head_poses = Input(shape=(TIME_STEPS, 3), name='head_poses')\n lstm_input = Concatenate()([cnn_features, my_input_head_poses])\n else:\n lstm_input = cnn_features\n\n lstm_output = LSTM(lstm_units_1, activation='tanh', kernel_regularizer=l2(1.e-4), return_sequences=False)(lstm_input)\n\n if individual_dense:\n d1 = Dense(lr_dense_fc, kernel_regularizer=l2(1.e-4))(my_input_lipreader_dense)\n a1 = Activation('relu', name='relu_lr_dense')(d1)\n lipreader_dense_features = BatchNormalization()(a1)\n if use_softmax:\n my_input_lipreader_softmax = Input(shape=(500,), name='lipreader_softmax')\n d2 = Dense(lr_softmax_fc, kernel_regularizer=l2(1.e-4))(my_input_lipreader_softmax)\n a2 = Activation('relu', name='relu_lr_softmax')(d2)\n lipreader_softmax_features = BatchNormalization()(a2)\n else:\n lipreader_dense_features = my_input_lipreader_dense\n if use_softmax:\n lipreader_softmax_features = my_input_lipreader_softmax\n\n if use_softmax_ratios:\n my_input_lipreader_softmax_ratios = Input(shape=(2,), name='lipreader_softmax_ratios')\n lipreader_softmax_ratio_features = my_input_lipreader_softmax_ratios\n\n to_concatenate = []\n if use_CNN_LSTM:\n to_concatenate += [lstm_output]\n to_concatenate += [my_input_n_of_frames, lipreader_dense_features]\n if use_softmax:\n to_concatenate += [lipreader_softmax_features]\n if use_softmax_ratios:\n to_concatenate += [lipreader_softmax_ratio_features]\n\n concatenated_features = Concatenate()(to_concatenate)\n\n\n if last_fc is None:\n\n fc1 = Dense(dense_fc_1, kernel_regularizer=l2(1.e-4))(concatenated_features)\n ac1 = Activation('relu', name='relu_fc1')(fc1)\n bn1 = BatchNormalization()(ac1)\n dp1 = Dropout(dropout_p1, name='dropout1_p'+str(dropout_p1))(bn1)\n\n fc2 = Dense(dense_fc_2, kernel_regularizer=l2(1.e-4))(dp1)\n ac2 = Activation('relu', name='relu_fc2')(fc2)\n bn2 = BatchNormalization()(ac2)\n dp2 = Dropout(dropout_p2, name='dropout2_p'+str(dropout_p2))(bn2)\n\n if residual_part:\n res_fc1 = Dense(res_fc_1, kernel_regularizer=l2(1.e-4), name='res_fc1')(dp2)\n res_ac1 = Activation('relu', name='res_relu_fc1')(res_fc1)\n res_fc1 = Dense(res_fc_2, kernel_regularizer=l2(1.e-4), name='res_fc2')(res_ac1)\n res_ac2 = Activation('relu', name='res_relu_fc2')(res_fc1)\n clf_input = Add()([dp2, res_ac2])\n else:\n clf_input = dp2\n\n assessor_output = Dense(1, activation='sigmoid', name='sigmoid')(clf_input)\n\n elif 'resnet' in last_fc:\n\n if last_fc == 'resnet18':\n last_fc_model = ResnetBuilder.build_resnet_18((int(concatenated_features.shape[1]), 1, 1), 32, time_distributed=False)\n elif last_fc == 'resnet34':\n last_fc_model = ResnetBuilder.build_resnet_34((int(concatenated_features.shape[1]), 1, 1), 32, time_distributed=False)\n elif last_fc == 'resnet50':\n last_fc_model = ResnetBuilder.build_resnet_50((int(concatenated_features.shape[1]), 1, 1), 32, time_distributed=False)\n elif last_fc == 'resnet101':\n last_fc_model = ResnetBuilder.build_resnet_101((int(concatenated_features.shape[1]), 1, 1), 32, time_distributed=False)\n elif last_fc == 'resnet152':\n last_fc_model = ResnetBuilder.build_resnet_152((int(concatenated_features.shape[1]), 1, 1), 32, time_distributed=False)\n\n fc_input = Reshape((int(concatenated_features.shape[1]), 1, 1), input_shape=(int(concatenated_features.shape[1]),))(concatenated_features)\n resnet_output = last_fc_model(fc_input)\n\n assessor_output = Dense(1, activation='sigmoid', name='sigmoid')(resnet_output)\n\n inputs = []\n outputs = assessor_output\n if use_CNN_LSTM:\n inputs += [my_input_mouth_images]\n if use_head_pose:\n inputs += [my_input_head_poses]\n inputs += [my_input_n_of_frames, my_input_lipreader_dense]\n if use_softmax:\n inputs += [my_input_lipreader_softmax]\n if use_softmax_ratios:\n inputs += [my_input_lipreader_softmax_ratios]\n\n assessor = Model(inputs=inputs, outputs=outputs)\n\n assessor.summary()\n\n return assessor\n\n\n#########################################################\n# MY RESNET-like CNN\n#########################################################\n\n\ndef my_resnet_like_timeDistributed_CNN(input_shape, conv_f_1, conv_f_2, conv_f_3, cnn_dense_fc_1):\n\n _handle_dim_ordering()\n\n model = Sequential()\n\n # First\n model.add(TimeDistributed(Conv2D(filters=conv_f_1, kernel_size=(7, 7), strides=(2, 2), padding='same', kernel_regularizer=l2(1.e-4)), input_shape=input_shape))\n model.add(TimeDistributed(BatchNormalization(axis=CHANNEL_AXIS)))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")))\n\n # Residual-like block\n model.add(TimeDistributed(Conv2D(filters=conv_f_2, kernel_size=(3, 3), strides=(1, 1), padding=\"same\", kernel_initializer=\"he_normal\", kernel_regularizer=l2(1e-4))))\n model.add(TimeDistributed(BatchNormalization(axis=CHANNEL_AXIS)))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(Conv2D(filters=conv_f_2, kernel_size=(3, 3), strides=(2, 2), padding='same', kernel_regularizer=l2(1.e-4))))\n\n # Residual-like block\n model.add(TimeDistributed(BatchNormalization()))\n model.add(TimeDistributed(Conv2D(filters=conv_f_3, kernel_size=(3, 3), strides=(2, 2), padding='same', kernel_regularizer=l2(1.e-4))))\n model.add(TimeDistributed(BatchNormalization(axis=CHANNEL_AXIS)))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(Conv2D(filters=conv_f_3, kernel_size=(3, 3), strides=(2, 2), padding='same', kernel_regularizer=l2(1.e-4))))\n\n # End\n model.add(TimeDistributed(BatchNormalization()))\n model.add(TimeDistributed(Activation('relu')))\n\n # Classifier-like block\n model.add(TimeDistributed(AveragePooling2D(pool_size=(model.output_shape[ROW_AXIS], model.output_shape[COL_AXIS]), strides=(1, 1))))\n model.add(TimeDistributed(Flatten()))\n model.add(TimeDistributed(Dense(units=cnn_dense_fc_1, kernel_initializer=\"he_normal\", activation='relu')))\n model.add(TimeDistributed(BatchNormalization()))\n\n return model\n\n\ndef my_small_resnet(input_shape, conv_f_1, conv_f_2, conv_f_3, cnn_dense_fc_1):\n\n _handle_dim_ordering()\n\n model = Sequential()\n\n # First\n model.add(TimeDistributed(Conv2D(filters=conv_f_1, kernel_size=(7, 7), strides=(2, 2), padding='same', kernel_regularizer=l2(1.e-4)), input_shape=input_shape))\n model.add(TimeDistributed(BatchNormalization(axis=CHANNEL_AXIS)))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding=\"same\")))\n\n # Residual-like block\n model.add(TimeDistributed(Conv2D(filters=conv_f_2, kernel_size=(3, 3), strides=(1, 1), padding=\"same\", kernel_initializer=\"he_normal\", kernel_regularizer=l2(1e-4))))\n model.add(TimeDistributed(BatchNormalization(axis=CHANNEL_AXIS)))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(Conv2D(filters=conv_f_2, kernel_size=(3, 3), strides=(2, 2), padding='same', kernel_regularizer=l2(1.e-4))))\n model.add()\n\n # Residual-like block\n model.add(TimeDistributed(BatchNormalization()))\n model.add(TimeDistributed(Conv2D(filters=conv_f_3, kernel_size=(3, 3), strides=(2, 2), padding='same', kernel_regularizer=l2(1.e-4))))\n model.add(TimeDistributed(BatchNormalization(axis=CHANNEL_AXIS)))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(Conv2D(filters=conv_f_3, kernel_size=(3, 3), strides=(2, 2), padding='same', kernel_regularizer=l2(1.e-4))))\n\n # End\n model.add(TimeDistributed(BatchNormalization()))\n model.add(TimeDistributed(Activation('relu')))\n\n # Classifier-like block\n model.add(TimeDistributed(AveragePooling2D(pool_size=(model.output_shape[ROW_AXIS], model.output_shape[COL_AXIS]), strides=(1, 1))))\n model.add(TimeDistributed(Flatten()))\n model.add(TimeDistributed(Dense(units=cnn_dense_fc_1, kernel_initializer=\"he_normal\", activation='relu')))\n model.add(TimeDistributed(BatchNormalization()))\n\n return model\n\n\ndef _handle_dim_ordering(time_distributed=True, verbose=False):\n global ROW_AXIS\n global COL_AXIS\n global CHANNEL_AXIS\n if verbose:\n print(\"_handle_dim_ordering\")\n if time_distributed:\n if K.image_dim_ordering() == 'tf':\n ROW_AXIS = 2\n COL_AXIS = 3\n CHANNEL_AXIS = -1\n else:\n CHANNEL_AXIS = 2\n ROW_AXIS = 3\n COL_AXIS = 4\n else:\n if K.image_dim_ordering() == 'tf':\n ROW_AXIS = 1\n COL_AXIS = 2\n CHANNEL_AXIS = 3\n else:\n CHANNEL_AXIS = 1\n ROW_AXIS = 2\n COL_AXIS = 3\n\n\n#########################################################\n# MY CNN\n#########################################################\n\n\ndef my_timedistributed_cnn_model(input_shape, conv_f_1, conv_f_2, conv_f_3, cnn_dense_fc_1, masking=False):\n\n model = Sequential()\n\n if masking:\n model.add(Masking(mask_value=0.0, input_shape=input_shape))\n model.add(TimeDistributed(Conv2D(filters=conv_f_1, kernel_size=(3, 3), padding='same', kernel_regularizer=l2(1.e-4))))\n else:\n model.add(TimeDistributed(Conv2D(filters=conv_f_1, kernel_size=(3, 3), padding='same', kernel_regularizer=l2(1.e-4)),\n input_shape=input_shape))\n\n model.add(TimeDistributed(BatchNormalization()))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')))\n\n model.add(TimeDistributed(Conv2D(filters=conv_f_2, kernel_size=(3, 3), padding='same', activation='relu', kernel_regularizer=l2(1.e-4))))\n model.add(TimeDistributed(BatchNormalization()))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')))\n\n model.add(TimeDistributed(Conv2D(filters=conv_f_3, kernel_size=(3, 3), padding='same', activation='relu', kernel_regularizer=l2(1.e-4))))\n model.add(TimeDistributed(BatchNormalization()))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')))\n\n model.add(TimeDistributed(Flatten()))\n model.add(TimeDistributed(Dense(cnn_dense_fc_1, kernel_regularizer=l2(1.e-4))))\n\n return model\n\n\ndef my_timedistributed_cnn_model_with_skip(input_shape, conv_f_1, conv_f_2, conv_f_3, cnn_dense_fc_1, masking=False):\n\n time_steps = input_shape[0]\n mouth_shape = (input_shape[1], input_shape[2], input_shape[3])\n\n my_input = Input(shape=input_shape)\n\n a_c_out = TimeDistributed(Conv2D(filters=conv_f_1, kernel_size=(3, 3), padding='same', kernel_regularizer=l2(1.e-4)),\n input_shape=input_shape)(my_input)\n a_bn_out = TimeDistributed(BatchNormalization())(a_c_out)\n a_act_out = TimeDistributed(Activation('relu'))(a_bn_out)\n a_pool_out = TimeDistributed(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same'))(a_act_out)\n # a_\n\n\n model.add(TimeDistributed(Conv2D(filters=conv_f_2, kernel_size=(3, 3), padding='same', activation='relu', kernel_regularizer=l2(1.e-4))))\n model.add(TimeDistributed(BatchNormalization()))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')))\n\n model.add(TimeDistributed(Conv2D(filters=conv_f_3, kernel_size=(3, 3), padding='same', activation='relu', kernel_regularizer=l2(1.e-4))))\n model.add(TimeDistributed(BatchNormalization()))\n model.add(TimeDistributed(Activation('relu')))\n model.add(TimeDistributed(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')))\n\n model.add(TimeDistributed(Flatten()))\n model.add(TimeDistributed(Dense(cnn_dense_fc_1, kernel_regularizer=l2(1.e-4))))\n\n return model\n\ndef my_cnn_model(input_shape, conv_f_1, conv_f_2, conv_f_3, cnn_dense_fc_1):\n model = Sequential()\n model.add(Conv2D(filters=conv_f_1, kernel_size=(3, 3), padding='same', kernel_regularizer=l2(1.e-4),\n input_shape=input_shape))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same'))\n model.add(Conv2D(filters=conv_f_2, kernel_size=(3, 3), padding='same', activation='relu', kernel_regularizer=l2(1.e-4)))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same'))\n model.add(Conv2D(filters=conv_f_3, kernel_size=(3, 3), padding='same', activation='relu', kernel_regularizer=l2(1.e-4)))\n model.add(BatchNormalization())\n model.add(Activation('relu'))\n model.add(MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same'))\n model.add(Flatten())\n model.add(Dense(cnn_dense_fc_1, kernel_regularizer=l2(1.e-4)))\n return model\n\n\ndef make_time_distributed_simple(model, TIME_STEPS, input_shape):\n time_distributed_model = Sequential()\n for model_layer_index in range(len(model.layers)):\n # print(model_layer_index)\n if model_layer_index == 0:\n time_distributed_model.add(TimeDistributed(model.layers[model_layer_index], input_shape=(TIME_STEPS, *input_shape)))\n else:\n time_distributed_model.add(TimeDistributed(model.layers[model_layer_index]))\n # Return\n return time_distributed_model\n\n\n#########################################################\n# CALLBACK\n#########################################################\n\n\nclass CheckpointAndMakePlots(Callback):\n\n # Init\n def __init__(self, file_name_pre=\"assessor_cnn_adam\", this_assessor_save_dir=\".\"):\n self.file_name_pre = file_name_pre\n self.this_assessor_save_dir = this_assessor_save_dir\n\n # On train start\n def on_train_begin(self, logs={}):\n self.train_losses = []\n self.val_losses = []\n self.train_accuracies = []\n self.val_accuracies = []\n self.best_val_loss = 1000\n\n # At every epoch\n def on_epoch_end(self, epoch, logs={}):\n\n # Get\n tl = logs.get('loss')\n ta = logs.get('acc')\n vl = logs.get('val_loss')\n va = logs.get('val_acc')\n print(\"\\n\", tl, ta, vl, va)\n\n # Append losses and accs\n self.train_losses.append(tl)\n self.val_losses.append(vl)\n self.train_accuracies.append(ta)\n self.val_accuracies.append(va)\n\n # Save model\n if vl < self.best_val_loss:\n self.best_val_loss = vl\n self.save_model_checkpoint(epoch, tl, ta, vl, va)\n\n # Save history\n self.save_history()\n\n # Plot graphs\n self.plot_and_save_losses_and_accuracies(epoch)\n\n # Save model checkpoint\n def save_model_checkpoint(self, epoch, tl, ta, vl, va):\n model_file_path = os.path.join(self.this_assessor_save_dir,\n self.file_name_pre + \"_epoch{0:03d}_tl{1:.4f}_ta{2:.4f}_vl{3:.4f}_va{4:.4f}.hdf5\".format(epoch, tl, ta, vl, va))\n print(\"Saving model\", model_file_path)\n self.model.save_weights(model_file_path)\n\n def save_history(self):\n print(\"Saving history in\", self.this_assessor_save_dir)\n np.savetxt(os.path.join(self.this_assessor_save_dir, self.file_name_pre + \"_loss_history.txt\"), self.train_losses, delimiter=\",\")\n np.savetxt(os.path.join(self.this_assessor_save_dir, self.file_name_pre + \"_acc_history.txt\"), self.train_accuracies, delimiter=\",\")\n np.savetxt(os.path.join(self.this_assessor_save_dir, self.file_name_pre + \"_val_loss_history.txt\"), self.val_losses, delimiter=\",\")\n np.savetxt(os.path.join(self.this_assessor_save_dir, self.file_name_pre + \"_val_acc_history.txt\"), self.val_accuracies, delimiter=\",\")\n\n # Plot and save losses and accuracies\n def plot_and_save_losses_and_accuracies(self, epoch):\n print(\"Saving plot for epoch\", str(epoch), \":\",\n os.path.join(self.this_assessor_save_dir, self.file_name_pre + \"_plots.png\"))\n\n plt.subplot(121)\n plt.plot(self.train_losses, label='train_loss')\n plt.plot(self.val_losses, label='val_loss')\n leg = plt.legend(loc='upper right', fontsize=11, fancybox=True)\n leg.get_frame().set_alpha(0.3)\n plt.xlabel('epochs')\n plt.ylabel('loss')\n plt.title(\"Loss\")\n\n plt.subplot(122)\n plt.plot(self.train_accuracies, label='train_acc')\n plt.plot(self.val_accuracies, label='val_acc')\n leg = plt.legend(loc='lower right', fontsize=11, fancybox=True)\n leg.get_frame().set_alpha(0.3)\n plt.xlabel('epochs')\n plt.ylabel('acc')\n plt.yticks(np.arange(0, 1.05, 0.05))\n plt.tick_params(axis='y', which='both',\n labelleft='on', labelright='on')\n plt.gca().yaxis.grid(True)\n plt.title(\"Accuracy\")\n\n plt.tight_layout()\n # plt.subplots_adjust(top=0.85)\n plt.suptitle(self.file_name_pre, fontsize=10)\n plt.savefig(os.path.join(self.this_assessor_save_dir,\n self.file_name_pre + \"_plots_loss_acc.png\"))\n plt.close()\n\n\n#########################################################\n# WRITE MODEL ARCHITECTURE\n#########################################################\n\n\ndef write_model_architecture(model, file_type='json', file_name=\"model\"):\n if file_type == 'json':\n # serialize model to JSON\n model_json = model.to_json()\n with open(file_name+'.json', \"w\") as json_file:\n json_file.write(model_json)\n elif file_type == 'yaml':\n # serialize model to YAML\n model_yaml = model.to_yaml()\n with open(file_name+'.yaml', \"w\") as yaml_file:\n yaml_file.write(model_yaml)\n else:\n print(\"file_type can only be 'json' or 'yaml'\")\n\n\n#########################################################\n# READ MODEL ARCHITECTURE\n#########################################################\n\n\ndef read_my_model(model_file_name=\"model.json\", weights_file_name=None):\n # Load model\n print(\"Loading model from\", model_file_name, \"...\")\n # json\n if model_file_name.split('.')[-1] == 'json':\n with open(model_file_name, 'r') as json_file:\n loaded_model_json = json_file.read()\n loaded_model = model_from_json(loaded_model_json)\n # yaml\n elif model_file_name.split('.')[-1] == 'yaml' or file_name.split('.')[-1] == 'yml':\n with open(model_file_name, 'r') as yaml_file:\n loaded_model_yaml = yaml_file.read()\n loaded_model = model_from_yaml(loaded_model_yaml)\n else:\n print(\"file_type can only be 'json' or 'yaml'\")\n # Load weights\n if weights_file_name is not None:\n print(\"Loading weights from\", weights_file_name, \"...\")\n loaded_model.load_weights(weights_file_name)\n # Return\n print(\"Done loading model.\")\n return loaded_model\n\n","sub_path":"assessor/ASSESSORS/43_assessor_equalClasses_syncnetPreds_headPose_lstm8_nOfFrames_LRdense_fc8_LRsoftmax_fc8_LRsoftmaxRatios_1fc8_bn_dp0.5_2fc4_bn_dp0.5_adam_lr0.001_lrDecay0/assessor_model.py","file_name":"assessor_model.py","file_ext":"py","file_size_in_byte":23496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"104311659","text":"#!/usr/bin/env python3\n\n\nfrom dal.client_accountDAL import ClientAccountDAL\nfrom dal.accountDAL import AccountDAL\nfrom dal.transactionDAL import TransactionDAL\nfrom model.client import Client\nfrom model.account import Account\nfrom view.account_view import AccountView\n\n\nclass AccountController():\n def __init__(self):\n self.view = AccountView()\n\n def __to_client_object(self, data):\n return Client(name=data['name'],\n email=data['email'],\n login=data['login'],\n password=data['password'])\n\n def __to_account_object(self, data):\n return Account(number=data['number'],\n branch_id=data['branch_id'])\n\n def create_account(self):\n try:\n data = self.view.create_account()\n account = self.__to_account_object(data)\n client = self.__to_client_object(data)\n account_dal = AccountDAL()\n client_dal = ClientAccountDAL()\n\n try:\n # inserts account and client into DB\n account_dal.insert(account)\n client_dal.insert(client)\n # Gets client from DB to refresh its ID info\n client = client_dal.select_by_login(client.login)\n # Inserts client account into DB\n client_dal.insert_client_account(client, account)\n except Exception:\n # Rollback if any insert command went wrong.\n client_dal.delete_client_account(client, account)\n client_dal.delete(client)\n account_dal.delete(account)\n raise\n\n message = 'Branch|Account: \"{0}|{1}\" for client \"{2}\" created successfully.'\n message = message.format(\n account.branch_id, account.number, client.name)\n self.view.show_message('Success', message, True)\n except Exception as e:\n msg_pattern = '{0}\\n{1}\\n\\n{2}'\n main_message = 'Error inserting data into database'\n detail_message = 'Check if branch exists or if account number is already in use.'\n msg = msg_pattern.format(main_message, detail_message, e.args[0])\n self.view.show_message('Error', msg, True)\n\n def list_client_accounts(self):\n try:\n dal = ClientAccountDAL()\n accounts = dal.select_all_client_accounts()\n self.view.show_client_accounts(accounts)\n except Exception as e:\n self.view.show_message('Error', e.args[0], True)\n\n def create_transaction(self, account, tx_type):\n try:\n data = self.view.create_transaction(tx_type)\n\n transaction = None\n if tx_type == 'Deposit':\n transaction = account.deposit(\n date=data['date'],\n description=data['description'],\n amount=data['amount']\n )\n elif tx_type == 'Withdrawal':\n transaction = account.withdrawal(\n date=data['date'],\n description=data['description'],\n amount=data['amount']\n )\n else:\n msg = 'Invalid transaction type \"{0}\".'\n raise Exception(msg.format(tx_type))\n\n transaction_dal = TransactionDAL()\n transaction_dal.insert(transaction)\n\n message = 'Transaction recorded successfully.'\n self.view.show_message('Success', message, True)\n except Exception as e:\n main_message = 'Error inserting data into database'\n msg = '{0}\\n\\n{1}'.format(main_message, e.args[0])\n self.view.show_message('Error', msg, True)\n\n def list_statement(self, account):\n try:\n self.view.show_statement(account)\n except Exception as e:\n self.view.show_message('Error', e.args[0], True)\n\n def list_balance(self, account):\n try:\n self.view.show_balance(account)\n except Exception as e:\n self.view.show_message('Error', e.args[0], True)\n","sub_path":"w2/week2-weekend/bankapp/controller/account_controller.py","file_name":"account_controller.py","file_ext":"py","file_size_in_byte":4130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"268338813","text":"import argparse\n\n# import math\nimport numpy as np\n# import random\nimport os\nimport datetime\n# from concurrent import futures\n\nfrom Lidar import LidarDatasets\n\n\n# from StateBuffer import StateMem, StateBuffer\n# from EpisodeMemory import Episode, EpisodeMemory\n# from lidar_util import imshowLocalDistance\n\n# import pybullet as p\n# import gym\n# import cv2\n\nimport torch\nfrom torchvision.utils import save_image\n\nfrom model.VGGVAE_trainer import VGGVAE_trainer\nimport plot_graph\n\ndevice = 'cuda' if torch.cuda.is_available() else 'cpu'\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser(description='train')\n\n parser.add_argument('--batch-size', type=int, default=64)\n parser.add_argument('--epochs', type=int, default=100)\n\n parser.add_argument(\"--channels\", nargs=\"*\", type=int, default=[1, 64])\n parser.add_argument(\"--cnn-outsize\", type=int)\n parser.add_argument(\"--latent\", type=int, default=18)\n\n parser.add_argument('--models', type=str, default='', metavar='M', help='Load model checkpoint')\n parser.add_argument('--id', type=str, default='')\n\n args = parser.parse_args()\n\n s_time = datetime.datetime.now()\n\n print(\"start:\", s_time)\n\n ''' ---- Initialize ---- '''\n\n print(\"load dataset\")\n\n train_filenames = ['./data/vaernnEnv0/id-{}.npy'.format(id) for id in range(10)]\n test_filenames = ['./data/vaernnEnv0/id-{}.npy'.format(id) for id in range(10, 12)]\n\n lidarTrainDatasets = LidarDatasets(train_filenames)\n lidarTrainDatasets.limit(1080)\n\n lidarTestDatasets = LidarDatasets(test_filenames)\n lidarTestDatasets.limit(1080)\n\n train_loader = torch.utils.data.DataLoader(lidarTrainDatasets, batch_size = args.batch_size, shuffle = True, num_workers=2, pin_memory=True)\n test_loader = torch.utils.data.DataLoader(lidarTestDatasets, batch_size = args.batch_size, shuffle = False, num_workers=2, pin_memory=True)\n\n ''' ---- Train ---- '''\n\n print(\"Train\", datetime.datetime.now())\n\n out_dir = './result-VGGVAE' \n\n if args.id != '':\n out_dir += '/' + args.id\n\n out_dir += '/channels'\n\n for channel in args.channels:\n out_dir += '_{}'.format(channel)\n out_dir += '_latent_{}'.format(args.latent)\n\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n vae_train = VGGVAE_trainer(args.channels, args.latent, args.cnn_outsize, device=device)\n\n if args.models is not '' and os.path.exists(args.models):\n vae_train.load(args.models)\n\n train_plot_data = plot_graph.Plot_Graph_Data(out_dir, 'train_loss', {'train_loss': [], 'mse_loss': [], 'KLD_loss': []})\n test_plot_data = plot_graph.Plot_Graph_Data(out_dir, 'test_loss', {'test_loss': []})\n plotGraph = plot_graph.Plot_Graph([train_plot_data, test_plot_data])\n\n for epoch in range(1, args.epochs+1):\n\n mse_loss, KLD_loss = vae_train.train(train_loader)\n loss = mse_loss + KLD_loss\n\n test_loss = vae_train.test(test_loader)\n\n plotGraph.addDatas('train_loss', ['train_loss', 'mse_loss', 'KLD_loss'], [loss, mse_loss, KLD_loss])\n plotGraph.addDatas('test_loss', ['test_loss'], [test_loss])\n\n if epoch%10 == 0:\n vae_train.save(out_dir+'/vae.pth')\n\n plotGraph.plot('train_loss')\n plotGraph.plot('test_loss')\n\n print('epoch [{}/{}], loss: {:.4f} test_loss: {:.4f}'.format(\n epoch + 1,\n args.epochs,\n loss,\n test_loss)) \n\n if epoch % (args.epochs//10) == 0:\n vae_train.save(out_dir+'/vae{}.pth'.format(epoch))\n \n vae_train.vae.eval()\n data = lidarTrainDatasets.data[:100].to(device, non_blocking=True).view(-1, 1, 1080)\n\n recon_x, mu, logvar = vae_train.vae(data)\n save_image(torch.cat([data.view(-1,1080), recon_x.view(-1,1080)], dim=1), '{}/result{}.png'.format(out_dir, epoch))\n \n print(\"save:epoch\", epoch)\n\n e_time = datetime.datetime.now()\n\n print(\"start:\", s_time)\n print(\"end:\", e_time)\n print(\"end-start:\", e_time-s_time)\n","sub_path":"train_VGGVAE.py","file_name":"train_VGGVAE.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"414366380","text":"import pygame\nimport sys\n\ndimgreen = (46, 120, 50)\ngreen = (56, 142, 60)\n\ndimred = (200, 72, 72)\nred = (255, 82, 82)\n\nbuttonRadius = 55\n# funtion to render font\ndef textObj(text, font, color):\n textSurface = font.render(text, True, color)\n return textSurface, textSurface.get_rect()\n# function to render interactive button\ndef buttonCircle(screen, buttColor, buttonPos, text, textSize, textColor, textPos):\n pygame.draw.circle(screen, buttColor, buttonPos, buttonRadius)\n TextSurf, TextRect = textObj(text, textSize, textColor)\n TextRect.center = textPos\n screen.blit(TextSurf, TextRect)\ndef color_change(screen,Color,x,y,width,height,player):\n pygame.draw.rect(screen, Color, (x, y, width, height),0)\n pygame.draw.circle(screen,(255,255,255),(x-20,y+35),15)\n smallText = pygame.font.Font('freesansbold.ttf', 30)\n TextSurf,TextRect=textObj(\"<\",smallText,(0,0,0))\n TextRect.center=(x-20,y+33)\n player_color = smallText.render(\"Player \"+player, True, (0,0,0))\n screen.blit(player_color,[x+(width/2)-55,y+height+25])\n screen.blit(TextSurf,TextRect)\n pygame.draw.circle(screen,(255,255,255),(x+width+20,y+35),15)\n TextSurf2,TextRect2=textObj(\">\",smallText,(0,0,0))\n TextRect2.center=(x+21+width,y+33)\n screen.blit(TextSurf2,TextRect2)\ndef get_color(num,color,Type):\n if(num==1):\n color=(255,0,0)\n if Type==\"Dec\":\n num=6\n elif(num==2):\n color=(0,0,255)\n elif(num==3):\n color=(255,255,0)\n elif(num==4):\n color=(255,0,255)\n elif(num==5):\n if Type==\"Inc\":\n num=0\n color=(0,255,255)\n if(Type==\"Inc\"):\n return color,num\n else:\n return color,6-num\n# function for creating a start screen\ndef airHockeyStart(screen, clock, Scrwidth, Scrheight):\n num_p1=1\n num_p2=1\n color_p1=(255,0,0)\n color_p2=(255,255,0)\n while True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n screen.fill((60, 90, 100))\n largeText = pygame.font.Font('freesansbold.ttf', 50)\n smallText = pygame.font.Font('freesansbold.ttf', 30)\n TextSurf, TextRect = textObj(\"AirHockey\", largeText, (255, 255, 255))\n TextRect.center = (Scrwidth / 2, Scrheight / 2 - 130)\n screen.blit(TextSurf, TextRect)\n\n # mouse data\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n color_change(screen,color_p1,120,110,150,80,\"1\")\n color_change(screen,color_p2,920,110,150,80,\"2\")\n if((mouse[0]>85 and mouse[0]<115) and (mouse[1]>130 and mouse[1]<160)):\n # pygame.draw.circle(screen,(255,200,255),(100,145),15)\n if pygame.mouse.get_pressed()[0]==1:\n num_p1+=1\n color_p1,num_p1=get_color(num_p1,color_p1,\"Inc\")\n elif((mouse[0]>275 and mouse[0]<305) and (mouse[1]>130 and mouse[1]<160)):\n if pygame.mouse.get_pressed()[0]==1:\n num_p1+=1\n color_p1,num_p1=get_color(5-num_p1+1,color_p1,\"Dec\")\n # pygame.draw.circle(screen,(255,200,255),(100,145),15)\n if((mouse[0]>885 and mouse[0]<915) and (mouse[1]>130 and mouse[1]<160)):\n # pygame.draw.circle(screen,(255,200,255),(100,145),15)\n if pygame.mouse.get_pressed()[0]==1:\n num_p2+=1\n color_p2,num_p2=get_color(num_p2,color_p2,\"Inc\")\n elif((mouse[0]>1075 and mouse[0]<1105) and (mouse[1]>130 and mouse[1]<160)):\n # pygame.draw.circle(screen,(255,200,255),(100,145),15)\n if pygame.mouse.get_pressed()[0]==1:\n num_p2+=1\n color_p2,num_p2=get_color(5-num_p2+1,color_p2,\"Dec\")\n \n\n\n\n\n\n # difficulty button 'Hard'\n if abs(mouse[0] - 200) < buttonRadius and abs(mouse[1] - 470) < buttonRadius:\n buttonCircle(screen, green, (200, 470), \"Hard\", largeText, (255, 255, 255),\n (Scrwidth / 2 -400 , Scrheight / 2 + 170))\n if click[0] == 1:\n return 2,color_p1,color_p2\n\n else:\n buttonCircle(screen, dimgreen, (200, 470), \"Hard\", smallText, (255, 255, 255),\n (Scrwidth / 2 -400, Scrheight / 2 + 170))\n \n # difficulty button 'Easy'\n if abs(mouse[0] - 600) < buttonRadius and abs(mouse[1] - 470) < buttonRadius:\n buttonCircle(screen, green, (600, 470), \"Easy\", largeText, (255, 255, 255),\n (Scrwidth / 2 , Scrheight / 2 + 170))\n if click[0] == 1:\n return 1,color_p1,color_p2\n \n else:\n buttonCircle(screen, dimgreen, (600, 470), \"Easy\", smallText, (255, 255, 255),\n (Scrwidth / 2, Scrheight / 2 + 170))\n\n # quit button\n if abs(mouse[0] - 1000) < buttonRadius and abs(mouse[1] - 470) < buttonRadius:\n buttonCircle(screen, red, (1000, 470), \"Quit\", largeText, (255, 255, 255),\n (Scrwidth / 2 + 400, Scrheight / 2 + 170))\n if click[0] == 1:\n return 0\n else:\n buttonCircle(screen, dimred, (1000, 470), \"Quit\", smallText, (255, 255, 255),\n (Scrwidth / 2 + 400, Scrheight / 2 + 170))\n pygame.display.update()\n clock.tick(10)\n","sub_path":"startScreen.py","file_name":"startScreen.py","file_ext":"py","file_size_in_byte":5294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"375715255","text":"from django.shortcuts import render\nfrom django.shortcuts import render_to_response\nimport sys\nfrom django.core.context_processors import csrf\nfrom django.http import HttpResponse,JsonResponse\nfrom pymongo import MongoClient\nimport random\nimport datetime\nfrom django.views.decorators.cache import cache_control\nimport string\nfrom urllib.parse import quote\nfrom django.views.decorators.clickjacking import xframe_options_exempt\nimport os\nBASE_DIR = os.path.dirname(os.path.dirname(__file__))\n\n\n#Connect to MongoDB:\nclient = MongoClient()\n#Database collections:\ndb = client.mydb\n\n\n#GOOGLE MAPS API KEY\n\napi_key_file = os.path.join(BASE_DIR,'google_api_key.txt')\nwith open(api_key_file) as f:\n api_key = f.read().strip()\n\n\n#TURKPRIME SEC_CODE:\nSEC_CODE = '8DTBWY4J'\n\n#PATH to images used: (change if different dataset is introduced) \nIMG_SET = \"set2/\"\n\n#LIMIT MAX # OF IMAGES\nSET_LIM = False\nSET_SIZE = 250\n\n#Number of conditions:\nNUM_SITES = 6\n\n\n#LIMIT ASSIGNMENTS PER SET to MAX_ASS/NUM_SITES\nMAX_ASS = NUM_SITES*100\nLIMIT_P_SET = int(MAX_ASS/NUM_SITES)\n\n#Cookie size for hashing worker ids\nCOOKIE_SIZE = 16\n\n#Progress bar: Turn True for progress counts\nPROG_BAR = True\nN_PROG = [ False, False, False, True, True, True]\n\n#override question from mongo and put site 1 up: Same question throughout\nRANDQ = False\nRANDQT = 1\n\nrandom_questions = ['']\nrandom_questions[0] = 'Do you see any damage to manmade structures?'\nrandom_questions.append('Is there water in this picture?')\nrandom_questions.append('Is this picture visually interesting?')\nrandom_questions.append('Do you see any buildings?')\nrandom_questions.append('Is this a clear picture of terrain?')\nrandom_questions.append('Do you see any damage?')\n\n\n\n# Override question from mongo to put site 2 up: Question changes every RAND_X images\nRAND_CH = False\nRAND_CH_S = 2\nRAND_X = 7\n\n#Type of task for each condition\nTASK = [\"label\",\"label\",\"label\",\"label\",\"label\",\"label\"]\n#Show PATH for each condition: 0 -> Activate 1 -> Deactivate\nPATH = [ 0,0,0,0,0,0]\n\n\n\n\n#SHOW DONE BUTTON AFTER N IMAGES (Different for each condition)\nDON_SH = True\nN_DONE = [0,1,10,0,1,10]\n\n#Show extra context in instructions\nCONTEXT = False\ncont_msg = '

You will be shown a series of images taken from the Colorado area during the floods that took place in 2013. Nearly 19000 homes have been damaged and over 50 state highway bridges have been either seriously damaged or destroyed. Your work could provide assistance to disaster response efforts.

'\n\n#Use free text response survey page\nFREE_FORM = True\n#Tutorial button with no irrelevant button\nTUT3 = True\n\n\n#Override DB selection to put map every N images\nMAP_PER = False\nN_MAP = [0,1,5,10,20,30]\n\nmap_question = 'Can you locate the image on the map?'\nmap_buttons = ''\nmap_buttons += '\\n'\nmap_buttons += '\\n'\nmap_buttons += '\\n'\nmap_buttons += '\\n'\n\n#Function for weighted random sorting in conditions\ndef weighted_choice(choices):\n total = sum(w for c, w in choices)\n r = random.uniform(0, total)\n upto = 0\n for c, w in choices:\n if upto + w >= r:\n return c\n upto += w\n assert False, \"Shouldn't get here\"\n\n\n## CONSENT PAGE\n@xframe_options_exempt\ndef consent(request):\n\n\n #Get MTurk variables:\n worker_id = request.GET.get('workerId','')\n assignment_id = request.GET.get('assignmentId','')\n hit_id = request.GET.get('hitId','')\n subto = request.GET.get('turkSubmitTo','')\n \n #Create cookie for user\n #Approach 1: random string of lowercase, uppercase and digits, random seed is worker_id\n SEED = worker_id\n random.seed(SEED) \n cookie_id = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(COOKIE_SIZE))\n \n \n #Sort user to site, based on cookie id\n \n \n #Uncomment for uneven distributions\n \n# pik_me2 = [ (1,1/3),(2,1/3),(3,1/9),(4,1/9),(5,1/9), ]\n# limits = [0,13,0,0,1] \n# sort_num = 0;\n \n \n #Sort into condition: Save cookie_id and site_id (condition) in cookie_per_site database\n #Keep track of people in conditions and exclude conditions that are full\n sorted = False \n pik_me = [i+1 for i in range(NUM_SITES)]\n\n while sorted!= True:\n \n random.seed()\n sitenum = pik_me[random.randint(0,len(pik_me)-1)]\n\n #if user has done that before, keep him on same site, do not add to db\n obj2 = db.cookie_per_site.find({\"cookie_id\":cookie_id})\n objlist = list(obj2)\n\n if obj2.count() == 1:\n \n objj = objlist[0] \n sorted = True\n sitenum = int(objj['site_id'])\n break\n\n #IF Site full, try again, else save cookie_id,site_id pair and continue\n countme = int(db.cookie_per_site.find({\"site_id\": sitenum}).count())\n if countme < LIMIT_P_SET:\n db.cookie_per_site.save({\n \"site_id\": sitenum, \n \"cookie_id\":cookie_id,\n \"assignment_id\":assignment_id,\n \"hit_id\":hit_id\n })\n db.cookies_history.save({\n \"site_id\": sitenum, \n \"cookie_id\":cookie_id,\n \"assignment_id\":assignment_id,\n \"hit_id\":hit_id\n })\n sorted = True\n else:\n #Remove site num from selection\n pik_me.remove(sitenum)\n\n # If all conditions are full, empty the db, store and continue \n if len(pik_me) ==0:\n #Empty db, restart\n db.cookie_per_site.remove({})\n db.cookie_per_site.save({\n \"site_id\": sitenum, \n \"cookie_id\":cookie_id,\n \"assignment_id\":assignment_id,\n \"hit_id\":hit_id\n })\n db.cookies_history.save({\n \"site_id\": sitenum, \n \"cookie_id\":cookie_id,\n \"assignment_id\":assignment_id,\n \"hit_id\":hit_id\n })\n sorted = True\n\n #Uncomment for uneven distributions\n\n# sort_num = sort_num +1\n\n # #pick weighted:\n# sitenum = weighted_choice(pik_me2)\n# \n# #IF Site full, try again\n# countme = int(db.cookie_per_site.find({\"site_id\": sitenum}).count())\n# if countme < limits[sitenum - 1]:\n# if countme < LIMIT_P_SET\n# db.cookie_per_site.save({\"site_id\": sitenum, \"cookie_id\":cookie_id})\n# sorted = True\n# break\n# \n# if all sites full, reset\n# if sort_num==NUM_SITES:\n# Empty db, restart\n# db.cookie_per_site.remove({})\n# db.cookie_per_site.save({\"site_id\": sitenum, \"cookie_id\":cookie_id})\n# sorted = True\n# break\n# \n\n\n #Name of Database to be called for this user\n if sorted == True: \n siteId = 'trialimages'+ str(sitenum)\n else:\n\n #return 404, do not allow them to continue\n return render(request, 'votingapp/404.html',{})\n \n\n \n\n\n #Button not available during previewing HIT\n if assignment_id == 'ASSIGNMENT_ID_NOT_AVAILABLE':\n st_button = 'PLEASE ACCEPT THIS HIT TO CONTINUE'\n\n else:\n st_button = '' \n \n context = {\n 'assID': assignment_id,\n 'worker_id':worker_id,\n 'hit_id':hit_id,\n 'cookie_id': cookie_id,\n 'siteId': siteId,\n 'start_button' : st_button,\n 'subto' : subto\n }\n\n return render(request, 'votingapp/consent.html',context)\n\n\n\n##INSTRUCTIONS PAGE\n\n@xframe_options_exempt\ndef instructions(request):\n\n\n #Get Mturk info:\n worker_id = request.POST[\"workerId\"]\n assignment_id = request.POST[\"assignmentId\"]\n hit_id = request.POST[\"hitId\"]\n cookie_id = request.POST[\"cookie_id\"]\n siteId = request.POST[\"siteId\"]\n subto = request.GET[\"turkSubmitTo\"]\n \n if CONTEXT:\n show_context = cont_msg\n else:\n show_context = ''\n\n\n #Change text of instructions based on site id (for required work)\n \n #Get the number of condition\n stnm =int(siteId.split(\"trialimages\",1)[1]) \n qim = N_DONE[stnm-1] \n \n sel_task = TASK[stnm-1] \n \n #if MAP_PER activated, show \"random\" instructions (instr. for all types of tasks\"\n if MAP_PER:\n sel_task = \"random\"\n\n if sel_task ==\"map\": \n \n instr_page = 'votingapp/instructions_map.html';\n \n elif sel_task == \"label\":\n \n instr_page = 'votingapp/instructions_label.html';\n elif sel_task == \"random\":\n instr_page = 'votingapp/instructions_random.html';\n\n if qim ==0:\n ntq = '

This set contains '+str(SET_SIZE)+' subtasks. You may complete any number of subtasks before clicking the “Go to Survey” button to finish.

' \n elif qim == 1:\n ntq = '

This set contains '+str(SET_SIZE)+' subtasks. You must complete at least '+str(qim)+' subtask before clicking the “Go to Survey” button to finish.

' \n else:\n ntq = '

This set contains '+str(SET_SIZE)+' subtasks. You must complete at least '+str(qim)+' subtasks before clicking the “Go to Survey” button to finish.

' \n\n \n context = {\n 'assID': assignment_id,\n 'worker_id':worker_id,\n 'hit_id':hit_id,\n 'cookie_id' : cookie_id,\n 'siteId': siteId,\n 'subto': subto,\n 'num_to_quit': ntq,\n 'show_context':show_context\n }\n \n return render(request,instr_page,context)\n\n\n@xframe_options_exempt\ndef tutorial(request):\n\n\n #Get Mturk info:\n worker_id = request.POST[\"workerId\"]\n assignment_id = request.POST[\"assignmentId\"]\n hit_id = request.POST[\"hitId\"]\n cookie_id = request.POST[\"cookie_id\"]\n siteId = request.POST[\"siteId\"]\n subto = request.GET[\"turkSubmitTo\"]\n\n stnm =int(siteId.split(\"trialimages\",1)[1]) \n sel_task = TASK[stnm-1] \n\n #Examples for map type\n \n somename_map = 'AE00N39_953321W104_9425352013091600000000OL00_GU001002003.jpg'\n badname_map = 'AE00N38_950500W104_9631662013091700000000OL00_GU001002003.jpg'\n goodname_map = 'AE00N39_895380W104_9907402013091600000000OL00_GU001002003.jpg'\n irrname_map = 'AE00N39_821834W104_9253232013091500000000OL00_GU001002003.jpg'\n \n \n somebtn_map =''\n goodbtn_map =''\n badbtn_map =''\n irrbtn_map = ''\n\n #Examples for label type\n \n somename_label = 'AE00N39_953321W104_9425352013091600000000OL00_GU001002003.jpg'\n badname_label = 'AE00N39_895380W104_9907402013091600000000OL00_GU001002003.jpg'\n goodname_label = 'AE00N39_892000W105_3365002013091600000000OL00_GU001002003.jpg'\n irrname_label = 'AE00N39_869500W104_9206662013091400000000OL00_GU001002003.jpg'\n \n \n somebtn_label =''\n goodbtn_label =''\n if TUT3:\n badbtn_label =''\n else:\n badbtn_label =''\n irrbtn_label = ''\n\n\n \n #get goodname coords\n\n str_ch = '_'\n srname = str_ch.join(somename_map.split(str_ch)[:3])\n cursor = db.image_coords.find({\"image_name\":srname})\n cursor2 = list(cursor) \n if len(cursor2) > 0:\n \n obj2 = cursor2[0]\n sim_lat = obj2['lat']\n sim_lon = obj2['lon']\n #Check if object has zoom and head\n #if not,default is 16 and 0\n if 'zoom' in obj2:\n sim_zoom = obj2['zoom']\n else:\n sim_zoom = 16\n if 'heading' in obj2:\n sim_head = obj2['heading']\n else:\n sim_head = 0 \n \n #get badname coords\n\n str_ch = '_'\n srname = str_ch.join(badname_map.split(str_ch)[:3])\n #GET MEAN COORDS\n cursor = db.image_coords.find({\"image_name\":srname})\n cursor2 = list(cursor) \n if len(cursor2) > 0:\n\n obj2 = cursor2[0]\n bim_lat = obj2['lat']\n bim_lon = obj2['lon']\n #Check if object has zoom and head\n #if not,default is 16 and 0\n if 'zoom' in obj2:\n bim_zoom = obj2['zoom']\n else:\n bim_zoom = 16\n if 'heading' in obj2:\n bim_head = obj2['heading']\n else:\n bim_head = 0 \n \n #get irr coords\n\n str_ch = '_'\n srname = str_ch.join(irrname_map.split(str_ch)[:3])\n #GET MEAN COORDS\n cursor = db.image_coords.find({\"image_name\":srname})\n cursor2 = list(cursor) \n if len(cursor2) > 0:\n\n obj2 = cursor2[0]\n rim_lat = obj2['lat']\n rim_lon = obj2['lon']\n #Check if object has zoom and head\n #if not,default is 16 and 0\n if 'zoom' in obj2:\n rim_zoom = obj2['zoom']\n else:\n rim_zoom = 16\n if 'heading' in obj2:\n rim_head = obj2['heading']\n else:\n rim_head = 0 \n \n #If MAP_PER activated, override and show \"random\" tutorial (examples for all types of tasks)\" \n if MAP_PER:\n sel_task = \"random\"\n \n \n if sel_task == \"map\": \n context = {\n 'assID': assignment_id,\n 'worker_id':worker_id,\n 'hit_id':hit_id,\n 'good_image_id': IMG_SET + goodname_map,\n 'bad_image_id': IMG_SET + badname_map,\n 'some_image_id': IMG_SET + somename_map,\n 'irr_image_id': IMG_SET + irrname_map,\n 'cookie_id' : cookie_id,\n 'siteId': siteId,\n 'subto' : subto,\n 'api_key': api_key,\n 'some_im_lat': sim_lat,\n 'some_im_lon':sim_lon,\n 'some_im_zoom':sim_zoom,\n 'some_im_head':sim_head,\n 'bad_im_lat': bim_lat,\n 'bad_im_lon':bim_lon,\n 'bad_im_zoom':bim_zoom,\n 'bad_im_head':bim_head,\n 'goodbtn': goodbtn_map,\n 'badbtn': badbtn_map,\n 'somebtn': somebtn_map,\n 'irrbtn': irrbtn_map,\n 'irr_im_lat': rim_lat,\n 'irr_im_lon':rim_lon,\n 'irr_im_zoom':rim_zoom,\n 'irr_im_head':rim_head\n } \n return render(request,'votingapp/tutorial_page_map.html',context)\n elif sel_task == \"label\":\n context = {\n 'assID': assignment_id,\n 'worker_id':worker_id,\n 'hit_id':hit_id,\n 'good_image_id': IMG_SET + goodname_label,\n 'bad_image_id': IMG_SET + badname_label,\n 'some_image_id': IMG_SET + somename_label,\n 'irr_image_id': IMG_SET + irrname_label,\n 'cookie_id' : cookie_id,\n 'siteId': siteId,\n 'subto' : subto,\n 'api_key': api_key,\n 'some_im_lat': sim_lat,\n 'some_im_lon':sim_lon,\n 'some_im_zoom':sim_zoom,\n 'some_im_head':sim_head,\n 'bad_im_lat': bim_lat,\n 'bad_im_lon':bim_lon,\n 'bad_im_zoom':bim_zoom,\n 'bad_im_head':bim_head,\n 'goodbtn': goodbtn_label,\n 'badbtn': badbtn_label,\n 'somebtn': somebtn_label,\n 'irrbtn': irrbtn_label,\n 'irr_im_lat': rim_lat,\n 'irr_im_lon':rim_lon,\n 'irr_im_zoom':rim_zoom,\n 'irr_im_head':rim_head\n }\n if TUT3: \n return render(request,'votingapp/tutorial_page_label2.html',context)\n else:\n return render(request,'votingapp/tutorial_page_label.html',context) \n elif sel_task ==\"random\":\n context = {\n 'assID': assignment_id,\n 'worker_id':worker_id,\n 'hit_id':hit_id,\n 'good_image_id_label': IMG_SET + goodname_label,\n 'bad_image_id_label': IMG_SET + badname_label,\n 'some_image_id_label': IMG_SET + somename_label,\n 'irr_image_id_label': IMG_SET + irrname_label,\n 'good_image_id_map': IMG_SET + goodname_map,\n 'bad_image_id_map': IMG_SET + badname_map,\n 'some_image_id_map': IMG_SET + somename_map,\n 'irr_image_id_map': IMG_SET + irrname_map,\n 'cookie_id' : cookie_id,\n 'siteId': siteId,\n 'subto' : subto,\n 'api_key': api_key,\n 'some_im_lat': sim_lat,\n 'some_im_lon':sim_lon,\n 'some_im_zoom':sim_zoom,\n 'some_im_head':sim_head,\n 'bad_im_lat': bim_lat,\n 'bad_im_lon':bim_lon,\n 'bad_im_zoom':bim_zoom,\n 'bad_im_head':bim_head,\n 'goodbtn_label': goodbtn_label,\n 'badbtn_label': badbtn_label,\n 'somebtn_label': somebtn_label,\n 'irrbtn_label': irrbtn_label,\n 'goodbtn_map': goodbtn_map,\n 'badbtn_map': badbtn_map,\n 'somebtn_map': somebtn_map,\n 'irrbtn_map': irrbtn_map,\n 'irr_im_lat': rim_lat,\n 'irr_im_lon':rim_lon,\n 'irr_im_zoom':rim_zoom,\n 'irr_im_head':rim_head\n } \n return render(request,'votingapp/tutorial_page_random.html',context)\n \n\n\n##MAIN VOTING PAGE\n@xframe_options_exempt\ndef voting(request):\n \n\n if request.method == \"POST\":\n \n #POST: User voted an image\n \n \n worker_id = request.POST.get(\"workerId\",'')\n assignment_id = request.POST.get(\"assignmentId\",'')\n hit_id = request.POST.get(\"hitId\",'')\n cookie_id = request.POST.get(\"cookie_id\",'')\n siteId = request.POST.get(\"siteId\",'')\n \n testcnt = request.POST.get('countr', '') \n if testcnt is '':\n cnt = 0\n #User has started the process. Save dummy vote to calculate time started\n voting = {\n 'image_name': 'VOTING STARTED',\n 'vote': 10,\n 'time': str(datetime.datetime.now()),\n 'cookie_id' : str(cookie_id),\n 'site_id': int(siteId.split(\"trialimages\",1)[1]),\n 'voted_lat': -10,\n 'voted_lon': -10,\n 'voted_zoom':-10,\n 'voted_head':-10,\n 'im_lat': -10,\n 'im_lon': -10,\n 'im_zoom': -10,\n 'im_head': -10,\n 'im_rot':-10,\n 'map_moved': -10,\n 'road' : -10,\n 'im_question': -10,\n 'im_rot_bool': -10,\n 'maptype' : -10,\n 'road' : -10,\n 'map_moved' : -10,\n 'task_type' : -10 \n }\n vursor_ch = db.trialvotes.find({\"cookie_id\": str(cookie_id), \"image_name\": 'VOTING STARTED'})\n \n #only valid votes (0,1,2) and no duplicates:\n if vursor_ch.count() == 0: \n db.trialvotes.save(voting) \n \n else:\n cnt = testcnt \n \n \n #Save vote to database with datestamp, image name and cookie id and case\n if cnt !=0:\n voted_image = request.POST[\"img_name\"]\n vote = request.POST['answer']\n quest_answ = request.POST['questN']\n #strip the set name\n voted_image = voted_image.split(IMG_SET,1)[1].rstrip('\\n')\n \n #Get map coordinates from user\n voted_lat = request.POST.get(\"new_lat\",'')\n voted_lon = request.POST.get(\"new_lon\",'')\n voted_zoom = request.POST.get(\"new_zoom\",'')\n voted_head = request.POST.get(\"new_head\",'')\n im_rot = request.POST.get(\"im_rot\",'')\n im_rot_bool = request.POST.get(\"im_rot_bool\",'')\n \n \n #Get initial map coordinates \n im_lat = request.POST.get(\"im_lat\",'')\n im_lon = request.POST.get(\"im_lon\",'')\n im_zoom = request.POST.get(\"im_zoom\",'')\n im_head = request.POST.get(\"im_head\",'')\n \n #Maptype info\n maptype = request.POST.get(\"maptype\",'')\n road = request.POST.get(\"road\",'')\n \n #Task Type info\n vot_task_type = request.POST.get(\"task_type\",'')\n if vot_task_type == \"map\":\n \n \n\n #Boolean field for cases where map was not moved:\n df1 = abs(float(voted_lat) - float(im_lat))\n df2 = abs(float(voted_lon) - float(im_lon))\n df3 = abs(float(voted_zoom) - float(im_zoom))\n \n if df1 !=0 or df2 !=0 or df3 !=0:\n map_moved = 1\n else:\n map_moved = 0 \n\n mapbool = 0 if maptype =='satellite' else 1\n elif vot_task_type == \"label\":\n voted_lat = -10\n voted_lon = -10\n voted_zoom = -10\n voted_head = -10\n im_lat = -10\n im_lon = -10\n im_zoom = -10\n im_head = -10\n im_rot = -10\n mapbool = -10\n road = -10\n map_moved = -10\n im_rot_bool = -10\n \n\n voting = {\n 'image_name': str(voted_image),\n 'vote': int(vote),\n 'time': str(datetime.datetime.now()),\n 'cookie_id' : str(cookie_id),\n 'site_id': int(siteId.split(\"trialimages\",1)[1]),\n 'im_question': quest_answ,\n 'voted_lat': voted_lat,\n 'voted_lon': voted_lon,\n 'voted_zoom': voted_zoom,\n 'voted_head': voted_head,\n 'im_lat': im_lat,\n 'im_lon': im_lon,\n 'im_zoom': im_zoom,\n 'im_head': im_head,\n 'im_rot': im_rot,\n 'im_rot_bool': im_rot_bool,\n 'maptype' : mapbool,\n 'road' : road,\n 'map_moved' : map_moved,\n 'task_type' : vot_task_type\n }\n \n #Save to database votes, if no previous vote for image exists:\n \n vursor = db.trialvotes.find({\"cookie_id\": str(cookie_id), \"image_name\": str(voted_image)})\n \n #only valid votes (0,1,2) and no duplicates:\n if vursor.count() == 0 and int(vote) <10 :\n \n db.trialvotes.save(voting) \n# print('Vote saved') \n \n #Increase counter\n cnt = int(float(cnt)) + 1;\n \n \n else:\n #GET request:\n worker_id = request.POST.get(\"workerId\",'')\n assignment_id = request.POST.get(\"assignmentId\",'')\n hit_id = request.POST.get(\"hitId\",'')\n cookie_id = request.POST.get(\"cookie_id\",'')\n\n \n \n testcnt = request.GET.get('countr', '') \n if testcnt is '':\n cnt = 0\n else:\n cnt = testcnt \n \n \n #Get the SiteID\n siteId = request.POST.get(\"siteId\",'')\n subto = request.GET[\"turkSubmitTo\"]\n \n \n \n #call the db, get the collection for the condition, pick an image and show\n \n cursor = db[str(siteId)].find()\n cursorlist = list(cursor);\n\n\n #Shuffle randomly based on cookie id, pick image based on countr\n #Since seed is always cookie id, each user gets different order that\n #stays the same throughout the process\n \n SEED = cookie_id\n random.seed(SEED)\n random.shuffle(cursorlist)\n\n\n #Number of max labels:\n if SET_LIM:\n num_images = SET_SIZE\n else:\n num_images = cursor.count()\n \n #Pick image based on current counter:\n im_id = cnt; \n \n \n #If run out of images, go to survey:\n \n if cnt > num_images -1:\n context = {\n 'assID': assignment_id,\n 'worker_id':worker_id,\n 'hit_id':hit_id,\n 'cookie_id' : cookie_id,\n 'siteId': int(siteId.split(\"trialimages\",1)[1]),\n 'subto' : subto,\n 'countr': cnt,\n \n }\n if FREE_FORM:\n return render(request, 'votingapp/submit2.html',context)\n else:\n return render(request, 'votingapp/submit.html',context)\n\n\n #Get the object of the image\n obj = cursorlist[im_id];\n purename = obj['image_name']\n #Set the name of image to show next\n imname = IMG_SET + obj['image_name']\n #Get the task of the image\n im_task_type = obj['task_type']\n \n #for each possible answer, generate a button\n answer_buttons = '';\n \n \n if len(obj['answers']) == 2:\n \n button_colors = {\n 'answer1': 'green',\n 'answer2':'red'\n };\n elif len(obj['answers']) == 3:\n button_colors = {\n 'answer1': 'green',\n 'answer2':'yellow',\n 'answer3':'red'\n };\n elif len(obj['answers']) == 4:\n button_colors = {\n 'answer1': 'green',\n 'answer2':'yellow',\n 'answer3':'orange',\n 'answer4':'red'\n }; #SITE 1: Override Case: Ignore if False\n \n \n if RANDQ and int(siteId.split(\"trialimages\",1)[1])== RANDQT :\n SEED = cookie_id\n qnum = random.randint(0,len(random_questions)-1)\n show_quest = random_questions[qnum] \n else:\n show_quest = obj['question'] \n \n # Site 2: Override Case: Ignore if False\n \n if RAND_CH and int(siteId.split(\"trialimages\",1)[1]) == RAND_CH_S:\n #If reach 7th image, change random question, else keep showing the same\n if cnt % RAND_X == 0:\n nfresh_q = True\n while nfresh_q:\n random.seed()\n qnum = random.randint(0,len(random_questions)-1)\n show_quest = random_questions[qnum]\n # If the same do it again\n if cnt !=0:\n if show_quest is not quest_answ:\n nfresh_q = False\n else:\n nfresh_q = False \n \n\n else:\n show_quest = quest_answ \n else:\n show_quest = obj['question'] \n \n \n #If user gets an image they have voted before, change text and button \n app_warn = 'none'\n q_show_w = ''\n\n #Check for previous votes for this user and this image \n vursor = db.trialvotes.find({\"cookie_id\": str(cookie_id), \"image_name\": imname.split(IMG_SET,1)[1].rstrip('\\n')})\n\n if vursor.count() > 0:\n app_warn = ''\n q_show_w = 'none'\n value = 'Go to next image'\n st = '\\n'\n answer_buttons = answer_buttons + st;\n else:\n b_val = 0;\n for key, value in sorted(obj['answers'].items()):\n st = '\\n'\n answer_buttons = answer_buttons + st;\n b_val = b_val +1;\n \n \n stnm =int(siteId.split(\"trialimages\",1)[1])\n \n #Show prog bar for progress bar cases\n \n if PROG_BAR and N_PROG[stnm-1]:\n prog_show = ''\n else:\n prog_show = 'none' \n \n \n #For even number of conditions and progress bars, first half will not have progress bars, second half will\n if DON_SH and N_PROG[stnm-1] == False:\n if cnt < N_DONE[stnm-1]:\n #Show progress\n done_show ='hidden'\n shw_prg = 0\n prog_cnt = N_DONE[stnm-1]\n\n else:\n # Show button\n done_show = ''\n shw_prg = 0\n prog_cnt = N_DONE[stnm-1]\n \n \n #if stnm is over half show progress then show button\n \n if DON_SH and N_PROG[stnm-1]:\n if cnt < N_DONE[stnm-1]:\n #Show progress\n done_show =''\n shw_prg = 1\n prog_cnt = N_DONE[stnm-1]\n else:\n # Show button\n done_show = ''\n shw_prg = 0\n prog_cnt = N_DONE[stnm-1]\n \n qim = N_DONE[stnm-1] \n\n\n\n\n\n #GOOGLE MAPS:\n #Mean_image_coords collection contains average coordinates from previous users\n #If image has averages, then use these for Map\n #Else, get the default from image_coords collection\n\n #Find lat lon of image: GET MEAN COORDS\n str_ch = '_'\n srname = str_ch.join(purename.split(str_ch)[:3])\n #GET MEAN COORDS\n cursor = db.mean_image_coords.find({\"image_name\":srname})\n cursor2 = list(cursor)\n\n if len(cursor2) > 0:\n \n \n obj2 = cursor2[0]\n im_lat = obj2['lat']\n im_lon = obj2['lon']\n #Check if object has zoom and head\n #if not,default is 16 and 0\n if 'zoom' in obj2:\n im_zoom = obj2['zoom']\n else:\n im_zoom = 14\n if 'heading' in obj2:\n im_head = obj2['heading']\n else:\n im_head = 0\n \n \n \n else:\n\n cursor = db.image_coords.find({\"image_name\":srname})\n cursor2 = list(cursor) \n if len(cursor2) > 0:\n \n obj2 = cursor2[0]\n im_lat = obj2['lat']\n im_lon = obj2['lon']\n #Check if object has zoom and head\n #if not,default is 16 and 0\n if 'zoom' in obj2:\n im_zoom = obj2['zoom']\n else:\n im_zoom = 14\n if 'heading' in obj2:\n im_head = obj2['heading']\n else:\n im_head = 0 \n \n\n #Show path\n if PATH[stnm-1]:\n path_show = ''\n else:\n path_show = 'none' \n\n\n\n\n #TODO: If map every N images enabled, then change task type according to cnt\n #CHANGE Question and answers\n #Override DB selection to put map every N images\n\n if MAP_PER:\n if N_MAP[stnm-1] !=0 and cnt % N_MAP[stnm-1] == 0:\n im_task_type = \"map\"\n show_quest = map_question\n answer_buttons = map_buttons\n \n\n\n #Prepare template for view:\n \n \n \n #Check for task type\n if im_task_type == \"map\":\n im_voting_page = 'votingapp/image_voting_map.html'\n \n #Show instructions text on voting page \n if qim ==0:\n ntq = 'This set contains '+str(num_images)+' subtasks. You may complete any number of subtasks before clicking the “Go to Survey” button to finish.' \n elif qim == 1:\n ntq = 'This set contains '+str(num_images)+' subtasks. You must complete at least '+str(qim)+' subtask before clicking the “Go to Survey” button to finish.' \n else:\n ntq = 'This set contains '+str(num_images)+' subtasks. You must complete at least '+str(qim)+' subtasks before clicking the “Go to Survey” button to finish.' \n\n \n context = {\n 'assID': assignment_id,\n 'worker_id':worker_id,\n 'hit_id':hit_id,\n 'progress': cnt,\n 'question': show_quest,\n 'answerbttns': answer_buttons,\n 'image_id': imname,\n 'countr': cnt,\n 'cookie_id' : cookie_id,\n 'max_labels': num_images,\n 'siteId': siteId,\n 'prog_show': prog_show,\n 'subto' : subto,\n 'done_show': done_show,\n 'app_warn': app_warn,\n 'q_show_w':q_show_w,\n 'shw_prg':shw_prg,\n 'prog_cnt': prog_cnt,\n 'num_to_quit': ntq,\n 'api_key': api_key,\n 'im_lat': im_lat,\n 'im_lon':im_lon,\n 'im_zoom':im_zoom,\n 'im_head':im_head,\n 'task_type': im_task_type,\n 'path_show': path_show\n }\n elif im_task_type == \"label\":\n im_voting_page = 'votingapp/image_voting_label.html'\n\n #Show instructions text on voting page \n if qim ==0:\n ntq = 'This set contains '+str(num_images)+' subtasks. You may complete any number of subtasks before clicking the “Go to Survey” button to finish.' \n elif qim == 1:\n ntq = 'This set contains '+str(num_images)+' subtasks. You must complete at least '+str(qim)+' subtask before clicking the “Go to Survey” button to finish.' \n else:\n ntq = 'This set contains '+str(num_images)+' subtasks. You must complete at least '+str(qim)+' subtasks before clicking the “Go to Survey” button to finish.' \n\n\n \n context = {\n 'assID': assignment_id,\n 'worker_id':worker_id,\n 'hit_id':hit_id,\n 'progress': cnt,\n 'question': show_quest,\n 'answerbttns': answer_buttons,\n 'image_id': imname,\n 'countr': cnt,\n 'cookie_id' : cookie_id,\n 'max_labels': num_images,\n 'siteId': siteId,\n 'prog_show': prog_show,\n 'subto' : subto,\n 'done_show': done_show,\n 'app_warn': app_warn,\n 'q_show_w':q_show_w,\n 'shw_prg':shw_prg,\n 'prog_cnt': prog_cnt,\n 'num_to_quit': ntq,\n 'im_lat': im_lat,\n 'im_lon':im_lon,\n 'api_key': api_key,\n 'task_type': im_task_type,\n 'path_show': path_show\n }\n\n \n\n return render(request,im_voting_page,context)\n\n\n## SURVEY PAGE ###\n@xframe_options_exempt\ndef survey(request):\n \n \n #Render survey page with worker id, assid, hitid and cookie id\n\n worker_id = request.POST[\"workerId\"]\n assignment_id = request.POST[\"assignmentId\"]\n hit_id = request.POST[\"hitId\"]\n cookie_id = request.POST[\"cookie_id\"]\n cnt = request.POST[\"countr\"]\n siteId = request.POST[\"siteId\"]\n subto = request.GET[\"turkSubmitTo\"]\n\n #Get total number of votes from DB\n tot_cnt = int(db.trialvotes.find({'cookie_id':cookie_id}).count()) -1\n \n firstq_choices = []\n firstq_choices.append('I was engaged in the task
')\n firstq_choices.append('I wanted to see more images
')\n firstq_choices.append('I had no indication to stop
')\n firstq_choices.append('I did not understand the instructions
')\n firstq_choices.append('I wanted to help the project
')\n firstq_choices.append('I thought I would get paid more
')\n firstq_choices.append('I thought my submission would not get approved
')\n firstq_choices.append('I thought the payment was worth that much work
')\n\n\n SEED = cookie_id\n random.seed(SEED)\n random.shuffle(firstq_choices)\n first_ch = ''.join(firstq_choices)\n\n\n context = {\n 'assID': assignment_id,\n 'worker_id':worker_id,\n 'hit_id':hit_id,\n 'cookie_id': cookie_id,\n 'countr': tot_cnt,\n 'siteId': int(siteId.split(\"trialimages\",1)[1]),\n 'subto' :subto,\n 'first_ch': first_ch\n\n }\n\n if FREE_FORM:\n return render(request, 'votingapp/submit2.html',context)\n else:\n return render(request, 'votingapp/submit.html',context)\n\n\n\n\n### COMPLETION CODE PAGE\n@xframe_options_exempt\ndef done(request):\n \n # Bypass mTurk used for TurkPrime\n # Get all survey responses and save to survey_votes collection\n \n# worker_id = request.POST [\"workerId\"]\n subto = request.GET[\"turkSubmitTo\"]\n# techdiff = request.POST[\"techdiff\"]\n# techdifftext = request.POST[\"techdifftext\"]\n# confidence = request.POST[\"confidence\"]\n# enjoyment = request.POST[\"enjoyment\"]\n# worthwhile = request.POST[\"worthwhile\"]\n# additional_feedback = request.POST[\"additional_feedback\"]\n# voted_images = request.POST[\"voted_images\"]\n\n #First question:\n whymores = request.POST.getlist('whymore')\n why_fun = 1 if 'fun' in whymores else 0\n why_more = 1 if 'more' in whymores else 0\n why_stop = 1 if 'stop' in whymores else 0\n why_instructions = 1 if 'instructions' in whymores else 0\n why_paid = 1 if 'paid' in whymores else 0\n why_project = 1 if 'project' in whymores else 0\n why_other = 1 if 'other' in whymores else 0\n why_reject = 1 if 'reject' in whymores else 0\n why_worth = 1 if 'worth' in whymores else 0\n why_othert = request.POST.get('whymore_text','') if 'other' in whymores else ''\n\n #Second Question:\n why_primary = request.POST.get('whyprim','')\n why_primary_text = request.POST.get('whyprim_text','')\n \n\n\n #Object to save to DB:\n survey = {\n 'assignment_id' : request.POST[\"assignmentId\"],\n 'hit_id' : request.POST[\"hitId\"],\n 'cookie_id' : request.POST[\"cookie_id\"],\n 'siteId' : request.POST[\"siteId\"],\n 'techdiff' : request.POST.get('techdiff',''),\n 'techdifftext' : request.POST.get('techdifftext',''),\n 'confidence':request.POST.get('confidence',''),\n 'enjoyment' : request.POST.get('enjoyment',''),\n 'worthwhile' : request.POST.get('worthwhile',''),\n 'meaningful' : request.POST.get('meaningful',''),\n 'why_fun' : why_fun,\n 'why_more': why_more,\n 'why_stop' : why_stop,\n 'why_instructions' : why_instructions,\n 'why_paid' : why_paid,\n 'why_project' : why_project,\n 'why_reject' : why_reject,\n 'why_worth': why_worth,\n 'why_other' : why_other,\n 'why_primary': why_primary,\n 'why_primary_text' : why_primary_text,\n 'why_other_text' : why_othert,\n 'voted_images' : request.POST[\"voted_images\"],\n 'additional_feedback' : request.POST[\"additional_feedback\"]\n \n }\n \n vursor = db.survey_votes.find({\"cookie_id\": str(request.POST[\"cookie_id\"])})\n \n #don't allow dublicates:\n if vursor.count() == 0: \n db.survey_votes.save(survey) \n \n \n return render(request, 'votingapp/done_code.html',{'sec_code':SEC_CODE})\n\n### COMPLETION CODE PAGE\n@xframe_options_exempt\ndef path_points(request):\n \n #Get cookie id, site ID and counter\n# assignment_id = request.POST[\"assignmentId\"]\n# hit_id = request.POST[\"hitId\"]\n siteId = request.GET[\"siteId\"]\n countr = request.GET[\"countr\"]\n cookie_id = request.GET[\"cookie_id\"]\n coords_tosend = {}\n \n\n \n if int(countr) != 0:\n \n #Get the list of the site id with the order the user gets, up to countr\n cursor = db[str(siteId)].find()\n cursorlist = list(cursor) \n SEED = cookie_id\n random.seed(SEED)\n random.shuffle(cursorlist)\n get_cnt = 0\n list_images = []\n for elem in cursorlist:\n name = elem['image_name']\n str_ch = '_'\n trname = str_ch.join(name.split(str_ch)[:3])\n list_images.append(trname)\n get_cnt = get_cnt +1\n if get_cnt == int(countr):\n break\n \n #Get coordinates of images so far\n \n coords_res = list(db.image_coords.find( { \"image_name\": { \"$in\": list_images } } ))\n \n coord_array = []\n for name in list_images:\n \n for x in coords_res:\n if x['image_name'] == name:\n elem = x\n break\n lat = float(elem['lat'])\n lon = float(elem['lon'])\n obj = {}\n obj['lat'] = lat\n obj['lng'] = lon\n coord_array.append(obj)\n \n #Return JSON with coordinates\n coords_tosend[\"res\"] = coord_array \n else:\n coords_tosend[\"res\"] = [] \n return JsonResponse(coords_tosend)","sub_path":"mapdjango/votingapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":40537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"155500494","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nimport wave\nimport os\nimport struct\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy.fftpack import fft, fftshift\nfrom scipy.io import wavfile\n\n\n\ndef np_to_int16_bytes(x):\n x = np.int16(x * 2**(16-1))\n return struct.pack(str(len(x))+'h', *x)\n\n\ndef int16_bytes_to_np(x, num, sw):\n x = np.array(struct.unpack(str(num)+'h', x))\n x = x.astype(np.float) / 2**(16-1)\n return x\n\n\nclass Signal(object):\n\n def __init__(self, Fs=44100, duration=None, data=[]):\n self._duration = duration\n self._Fs, self._Ts = Fs, 1./Fs\n self._data = data\n if duration:\n self._n = np.arange(0, duration, self._Ts)\n\n def plot(self):\n if len(self._data):\n plt.plot(self._n, self._data)\n plt.show()\n\n def estimate_amplitude(self, base):\n amp = (np.dot(self._data, base._data) /\n np.dot(base._data, base._data) )\n return amp\n\n def dft(self):\n if len(self._data):\n return np.fft.fft(self._data)/len(self._data)\n\n def wav_write(self, outfile, Nch=1, Sw=2, normalize=True):\n if len(self._data):\n x = self._data\n x = x / max(x) if normalize else x\n dst = wave.open(outfile, 'wb')\n dst.setparams((Nch, Sw, self._Fs, len(x), 'NONE', 'not_compressed'))\n dst.writeframes(np_to_int16_bytes(x))\n dst.close()\n\n def wav_read(self, in_file):\n assert(os.path.exists(in_file))\n src = wave.open(in_file, 'rb')\n nch, sw, fs, nframes, _, _ = src.getparams()\n self.__init__(Fs=fs, duration=nframes/fs)\n assert(nch == 1), \"wav must be 1 ch\"\n self._data = int16_bytes_to_np(src.readframes(nframes), nframes, sw)\n src.close()\n\n @property\n def data(self):\n return self._data\n\n @property\n def duration(self):\n return self._duration\n\n @property\n def params(self):\n return self._duration, self._Fs, self._Ts\n\n\n\nclass Sinusoid(Signal):\n\n def __init__(self, duration=1, Fs=44100.0, amp=1.0, freq=440.0, phase=0):\n super(self.__class__, self).__init__(duration=duration, Fs=Fs)\n self.A, self.f, self.phi = amp, freq, phase\n self._w = 2 * np.pi * self.f\n self.__make()\n\n def __make(self):\n self._data = self.A * np.sin(self._w * self._n + self.phi)\n\n def power(self):\n return self.A**2/2.0\n\n def add_noise(self, snr):\n sigma2 = self.power()/(10**(snr/10.0))\n noise = np.random.normal(0, np.sqrt(sigma2), len(self._data))\n self._data += noise\n\n def remove_noise(self):\n self.__make()\n\n def shift(self, phi):\n self._phi = phi\n self.__make()\n\n\nclass Mixture(Signal):\n\n def __init__(self, *signals):\n duration, fs, _ = signals[0].params\n super(self.__class__, self).__init__(duration=duration, Fs=fs)\n self._data = np.zeros(len(signals[0].data))\n for sig in signals:\n self._data += sig.data\n\n\nclass Sequence(Signal):\n\n def __init__(self, *signals):\n _, fs, _ = signals[0].params\n duration = np.sum([sig.duration for sig in signals])\n super(self.__class__, self).__init__(duration=duration, Fs=fs)\n self._data = np.hstack([sig.data for sig in signals])\n\n\nclass MidiNotes():\n TUNING = 440\n NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F',\n 'F#', 'G', 'G#', 'A', 'A#', 'B']\n\n def __init__(self):\n self._notes = {}\n for i in range(24, 109):\n f = 2**((i-69)/12.0) * self.TUNING\n self._notes[self.NAMES[i % 12] + str(i/12-1)] = f\n\n def freq(self, name):\n return self._notes[name]\n\nfrom scipy import signal\n\ndef main():\n\n # QUESTION 2 ********************************************\n\n # PART 1\n\n N = 2048 #DFT Magnitude size, ie num of samplepoints\n\n sin1 = Sinusoid(1, N, 1.0, 525.0, 0) #Sinusoid 1 with Bin 525.0\n sin2 = Sinusoid(1, N, 1.0, 600.5, 0) #Sinusoid 2 with Bin 600.5\n window = np.hanning(N) #Hamming Window\n\n s1FFT = fft(sin1.data)\n s2FFT = fft(sin2.data)\n mag1 = np.abs(s1FFT)\n norm1 = len(mag1)\n for x in range(len(mag1)):\n mag1[x] = mag1[x] / norm1\n mag1[x] = 10*math.log10(mag1[x])\n mag2 = np.abs(s2FFT)\n norm2 = len(mag2)\n for x in range(len(mag2)):\n mag2[x] = mag2[x] / norm2\n mag2[x] = 10*math.log10(mag2[x])\n\n data = [0.0] * int(N)\n for x in range(int(N)):\n data[x] = window[x] * sin1.data[x]\n dataFFT = fft(data)\n magData = np.abs(dataFFT)\n normData = len(magData)\n for x in range(normData):\n magData[x] = magData[x] / normData\n magData[x] = 10*np.log10(magData[x])\n\n plt.plot(mag1, 'b', label='w/o H.W.')\n plt.plot(magData, 'r', label='w/ H.W.')\n plt.legend()\n plt.title('Bin 525 Sine Wave')\n plt.show()\n\n plt.plot(mag2, 'b')\n plt.title('Bin 600.5 Sine Wave')\n plt.show()\n\n # PART 2\n\n window2048 = np.hamming(2048)\n\n #fs, data2 = wavfile.read('flute.wav')\n\n fs, dataR = wavfile.read('CSC475.wav')\n data2 = dataR.T[0]\n\n data2048 = [0.0] * N\n data2048HW = [0.0] * N\n\n\n for x in range(N):\n data2048[x] = data2[x]\n data2048HW[x] = data2[x] * window2048[x]\n\n #test = abs(np.fft.rfft(data2048HW))\n data2048FFT = fft(data2048)\n data2048HWFFT = fft(data2048HW)\n magData2048 = np.abs(data2048FFT)\n magData2048HW = np.abs(data2048HWFFT)\n normData1 = len(magData2048)\n normData2 = len(magData2048HW)\n\n for x in range(normData1):\n magData2048[x] = magData2048[x] / normData1\n magData2048[x] = 10*np.log10(magData2048[x])\n for x in range(normData2):\n magData2048HW[x] = magData2048HW[x] / normData2\n magData2048HW[x] = 10*np.log10(magData2048HW[x])\n\n plt.plot(magData2048, 'b', label='w/o H.W.')\n plt.legend()\n plt.title('Flute E note')\n #plt.show()\n plt.plot(magData2048HW, 'r', label='w/ H.W.')\n plt.legend()\n plt.title('Flute E note')\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"Assignment1/mir2.py","file_name":"mir2.py","file_ext":"py","file_size_in_byte":6122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"73434000","text":"\"\"\"Script to gather forex currency details and perform statistical analysis.\"\"\"\nimport sys\nimport psycopg2\nimport datetime\nimport threading\nfrom forex_python.converter import CurrencyRates\nfrom config import config\n\ncurr_list = 'currencies.txt'\n\ndef main():\n \"\"\"Main entry point for the script.\"\"\"\n runLoop()\n # t = threading.Timer\n # t.daemon = True\n # t.start()\n # t(5.0, runLoop)\n # print('loop passed')\n\ndef runLoop():\n conn = connect()\n currencies = parseFile(curr_list)\n currency_rate = getCurrencyPairPrice(currencies)\n commitPricesToDb(currency_rate, conn, curr_list)\n\ndef parseFile(curr_list):\n \"\"\"Open text file of currencies and compile into list object\"\"\" \n with open(curr_list) as f:\n currencies = f.read().splitlines()\n return currencies\n\ndef connect():\n \"\"\"Connect to Postgresql database\"\"\"\n conn = None\n try:\n # read connection parameters\n params = config()\n \n # connect to the PostgreSQL server\n print('Connecting to the PostgreSQL database...')\n conn = psycopg2.connect(**params)\n \n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n return conn\n\ndef getCurrencyPairPrice(currencies):\n \"\"\"Get the current exchange rate of each currency pair\"\"\"\n currency_rate = []\n c = CurrencyRates()\n for item in currencies:\n stringboi = str(item)\n rate = c.get_rate('GBP', stringboi)\n currency_row = ['GBP', item, datetime.datetime.now(), rate]\n currency_rate.append(currency_row)\n\n return currency_rate\n\ndef commitPricesToDb(currency_rate, conn, curr_list):\n \"\"\"Take list of currency pair prices and commit to Db\"\"\"\n cur = conn.cursor()\n for currency in currency_rate:\n #try:\n statement = (\"\"\"INSERT INTO forex.{} (date_taken, rate) VALUES ('{}', '{}')\"\"\".format(currency[1], currency[2], currency[3]))\n print(statement)\n cur.execute(statement)\n #except:\n #print(\"I can't do that for some reason, would be great if i told you why wouldn't it?\")\n conn.commit()\n\nif __name__ == '__main__':\n sys.exit(main())\n","sub_path":"forex.py","file_name":"forex.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"528259413","text":"# -*- coding: utf-8 -*-\nimport os\n\nfrom cleo import Command\nfrom .configuration import rake\n\n\nclass CreateCommand(Command):\n \"\"\"\n Creates a new Group Class\n\n group:create\n {--path= : 配置路径}\n \"\"\"\n\n def handle(self):\n path = self.option('path')\n file = os.path.abspath(path)\n self.line(file)\n\n\nclass NewCommad(Command):\n \"\"\"\n new template\n\n group:new\n { name : yaml文件名称 }\n { --path=./config : 配置路径 }\n \"\"\"\n\n def handle(self):\n \"\"\"\n :return:\n \"\"\"\n name = self.argument('name')\n path = self.option('path')\n lang = self.choice(\n '请选择支持的语言 (defaults to java)',\n ['java', 'node', 'h5'],\n 0\n )\n\n self.line('You have just selected: %s' % lang)\n\n env = self.choice(\n '请选择Group的环境 (defaults to fat)',\n ['fat', 'uat', 'pro'],\n 0\n )\n\n self.line('You have just selected: %s' % env)\n\n input_app_id = self.ask('输入app id', '')\n\n self.confirm('Continue with this action?', False, '(?i)^(y|j)')\n\n\n full_path = rake.create(name,path,env, input_app_id,lang)\n\n self.line(full_path)\n","sub_path":"dig/group.py","file_name":"group.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"70314382","text":"'''\r\nCreated on 2019年5月1日\r\n# -*- coding:utf-8 -*-\r\n更新时间必须是下午5点以后或者是周末\r\n@author: Administrator\r\n'''\r\nimport pymysql\r\nimport jqdatasdk as jq\r\nimport time\r\nfrom _datetime import datetime\r\nfrom jqdatasdk import finance\r\n\r\n\r\n#超参\r\nksrq='2009-11-05'\r\n\r\n\r\n\r\n\r\n#认证\r\njq.auth('13401179853','king179853')\r\n\r\n#定义当前日期\r\nd=time.strftime('%Y-%m-%d',time.localtime(time.time())) \r\nprint('今天是'+d)\r\n\r\n#建立连接 获取游标\r\nconnect = pymysql.Connect(\r\n host='localhost',\r\n port=3306,\r\n user='root',\r\n passwd='123456',\r\n db='xg2',\r\n charset='utf8'\r\n)\r\ncursor = connect.cursor()\r\n\r\n#获取现有代码表\r\ndm_old_list=[]\r\nsql = \"SELECT dm ,name FROM dmb order by id \"\r\ncursor.execute(sql)\r\nfor a in cursor.fetchall():\r\n dm_old_list.append(list(a)) \r\n \r\n#获取现有日期表\r\ndate_old_list=[]\r\nsql = \"SELECT date FROM rqb order by id \"\r\ncursor.execute(sql)\r\nfor b in cursor.fetchall():\r\n date_old_list.append(b[0]) \r\n\r\n\r\n#获取最新代码表\r\ndm_new_list=[]\r\ndf_new=jq.get_all_securities(date=d );\r\ndf_new.drop(columns=['start_date', 'end_date','type','name'],axis=1,inplace=True);\r\ndf_new.rename(columns={'display_name':'name'},inplace=True)\r\ndf_new.reset_index(inplace=True,drop=False)\r\ndf_new.rename(columns={'index':'dm'},inplace=True)\r\nfor i in range(0, len(df_new)):\r\n df_new.iloc[i]['dm']=df_new.iloc[i]['dm'][:6] \r\ndm_new_list=df_new.values.tolist() \r\n\r\n\r\n\r\n#更新上证指数 \r\nszzs_df=jq.get_price('000001.XSHG', start_date=ksrq,end_date=d, frequency='daily', fields=['open', 'close', 'high', 'low', 'volume'], skip_paused=True, fq='pre')\r\nszzs_df.reset_index(inplace=True,drop=False)\r\nszzs_list=szzs_df.values.tolist()\r\ntotal=0;\r\nsql10=\"truncate table szzs\"\r\ncursor.execute(sql10)\r\nconnect.commit() \r\nfor j in range(len(szzs_list)):\r\n try:\r\n sql = \"INSERT INTO szzs (date,open,close,high,low,volume) VALUES ( '%s', %.2f ,%.2f ,%.2f ,%.2f,%.2f )\"\r\n date = datetime.date(datetime.fromtimestamp(szzs_list[j][0].timestamp())) \r\n data = (date,szzs_list[j][1],szzs_list[j][2],szzs_list[j][3],szzs_list[j][4],szzs_list[j][5])\r\n cursor.execute(sql % data)\r\n except Exception as e:\r\n connect.rollback() # 事务回滚\r\n continue\r\n else:\r\n connect.commit() # 事务提交\r\n total=total+cursor.rowcount\r\nprint('上证指数历史数据更新完成,共更新了',total,'条数据')\r\n\r\n\r\n#更新日期表\r\ntotal=0;\r\ndate_list=[]\r\nsql = \"SELECT date FROM szzs order by id \"\r\ncursor.execute(sql)\r\nfor row in cursor.fetchall():\r\n date_list.append(row)\r\n \r\nsql11=\"truncate table rqb\"\r\ncursor.execute(sql11)\r\nconnect.commit() \r\n \r\nfor k in range(0,len(date_list)):\r\n try:\r\n sql = \"INSERT INTO rqb (date) VALUES ( '%s')\"\r\n datek =date_list[k] \r\n datak = (datek)\r\n cursor.execute(sql % datak)\r\n except Exception as e:\r\n connect.rollback() # 事务回滚\r\n continue\r\n else:\r\n connect.commit() # 事务提交\r\n total=total+cursor.rowcount\r\nprint('日期表更新完成,共更新了',total,'条数据')\r\n\r\n#获取最新日期表\r\ndate_new_list=[]\r\nsql = \"SELECT date FROM rqb order by id \"\r\ncursor.execute(sql)\r\nfor c in cursor.fetchall():\r\n date_new_list.append(c[0]) \r\n\r\n\r\n\r\n \r\n#对比新老代码表和日期表\r\n\r\ndate_insert_list=[]\r\ndm_insert_list=[]\r\ndm_delete_list=[]\r\ndm_update_list=[]\r\ndm_old_int_list=[]\r\ndm_new_int_list=[]\r\n\r\nfor a0 in range(len(dm_old_list)):\r\n dm_old_int_list.append(dm_old_list[a0][0])\r\nfor b0 in range(len(dm_new_list)):\r\n dm_new_int_list.append(dm_new_list[b0][0])\r\n \r\nfor f in range(len(date_new_list)):\r\n if date_new_list[f] in date_old_list:\r\n pass\r\n else:\r\n date_insert_list.append(date_new_list[f])\r\n \r\nfor g in range(len(dm_new_list)):\r\n if dm_new_int_list[g] in dm_old_int_list:\r\n pass\r\n else:\r\n dm_insert_list.append(dm_new_list[g])\r\n \r\nfor h in range(len(dm_old_list)):\r\n if dm_old_int_list[h] in dm_new_int_list:\r\n pass\r\n else:\r\n dm_delete_list.append(dm_old_list[h])\r\n\r\nfor ee in range(len(dm_old_list)):\r\n if dm_old_list[ee] in dm_delete_list:\r\n pass\r\n else:\r\n dm_update_list.append(dm_old_list[ee])\r\nprint('需要更新的日期:',date_insert_list) \r\nprint('新上市:',dm_insert_list)\r\nprint('退市:',dm_delete_list)\r\n \r\n\r\n#更新代码表\r\ntotal=0\r\nfor m in range(len(dm_insert_list)):\r\n sql = \"INSERT INTO dmb (dm,name) VALUES ( '%s', '%s')\"\r\n data = (dm_insert_list[m][0],dm_insert_list[m][1])\r\n cursor.execute(sql % data)\r\n connect.commit()\r\n total=total+cursor.rowcount\r\nprint('成功插入代码表', total, '支股票')\r\n\r\ntotal=0\r\nfor n in range(len(dm_delete_list)):\r\n sql = \"delete from dmb where dm='%s'\"\r\n data = (dm_delete_list[n][0])\r\n cursor.execute(sql % data)\r\n connect.commit()\r\n total=total+cursor.rowcount\r\nprint('成功删除代码表', total, '支股票')\r\n\r\ntotal=0\r\nfor n in range(len(dm_delete_list)):\r\n sql = \"delete from kxfzb where dm='%s'\"\r\n data = (dm_delete_list[n][0])\r\n cursor.execute(sql % data)\r\n connect.commit()\r\n total=total+cursor.rowcount\r\nprint('成功删除可选分组表', total, '支股票')\r\n\r\n\r\n#更新股票表 \r\n#1.删除停止上市的表\r\n\r\nfor o in range(len(dm_delete_list)):\r\n sql = \" drop table %s \"\r\n data = ('TB'+dm_delete_list[o][0])\r\n cursor.execute(sql%data)\r\n connect.commit()\r\n print('成功删除', 'TB'+dm_delete_list[o][0])\r\n\r\n\r\n#2.插入新上市的表\r\n\r\nfor p in range(0, len(dm_insert_list)):\r\n sql = \"create table IF NOT EXISTS %s (\\\r\n id int primary key auto_increment,\\\r\n dm varchar(8) default '未知代码',\\\r\n date varchar(16) unique default '未知日期',\\\r\n open Float(7,2) default 0.00,\\\r\n close Float(7,2) default 0.00,\\\r\n high Float(7,2) default 0.00,\\\r\n low Float(7,2) default 0.00,\\\r\n zdf Float(5,2) default 0.00,\\\r\n cjl Float(14,2) default 0.00,\\\r\n ltsz Float(14,2) default 0.00,\\\r\n syl Float(10,2) default 0.00,\\\r\n ys Float(14,2) default 0.00,\\\r\n jlr Float(14,2) default 0.00,\\\r\n cdd Float(14,2) default 0.00,\\\r\n dd Float(14,2) default 0.00,\\\r\n zd Float(14,2) default 0.00,\\\r\n xd Float(14,2) default 0.00,\\\r\n lt_1 Float(5,2) default 0.00,\\\r\n lt_2 Float(5,2) default 0.00,\\\r\n lt_3 Float(5,2) default 0.00,\\\r\n lt_4 Float(5,2) default 0.00,\\\r\n lt_5 Float(5,2) default 0.00,\\\r\n lt_6 Float(5,2) default 0.00,\\\r\n lt_7 Float(5,2) default 0.00,\\\r\n lt_8 Float(5,2) default 0.00,\\\r\n lt_9 Float(5,2) default 0.00,\\\r\n lt_10 Float(5,2) default 0.00\\\r\n );\" \r\n data = ('TB'+dm_insert_list[p][0])\r\n cursor.execute(sql % data)\r\n connect.commit()\r\n print('成功创建','TB'+dm_insert_list[p][0])\r\n\r\n\r\n#3.向新增加的表中插入数据\r\nprint(\"开始向新上市的表中插入数据...................................................\")\r\ndm_insert_sh_list=[]\r\nfor s in range(len(dm_insert_list)):\r\n if dm_insert_list[s][0].startswith('6'):\r\n t=dm_insert_list[s][0]+'.XSHG'\r\n else:\r\n t=dm_insert_list[s][0]+'.XSHE' \r\n dm_insert_sh_list.append(t)\r\nfor q in range(0, len(dm_insert_list)):\r\n #获取收盘价\r\n insert_df=jq.get_price(dm_insert_sh_list[q], start_date=ksrq,end_date=d, frequency='daily', fields=['open', 'close', 'high', 'low', 'volume'], skip_paused=True, fq='pre')\r\n insert_df.reset_index(inplace=True,drop=False)\r\n insert_list=insert_df.values.tolist()\r\n for s in range(len(insert_list)):\r\n sql = \"INSERT INTO %s (date,open,close,high,low,cjl) VALUES ( '%s', %.2f ,%.2f ,%.2f ,%.2f,%.2f )\" \r\n date = datetime.date(datetime.fromtimestamp(insert_list[s][0].timestamp())) \r\n data = ('TB'+dm_insert_list[q][0],date,insert_list[s][1],insert_list[s][2],insert_list[s][3],insert_list[s][4],insert_list[s][5])\r\n cursor.execute(sql % data)\r\n connect.commit()\r\n print('TB'+dm_insert_sh_list[q][:6],'收盘价数据获取完成')\r\n \r\nprint('新表所有数据插入完毕....................................') \r\n\r\n\r\n#更新老表数据\r\nprint(\"开始向老表更新数据...................................\")\r\ndm_sh_list=[]\r\nfor at in range(len(dm_update_list)):\r\n if dm_update_list[at][0].startswith('6'):\r\n th=dm_update_list[at][0]+'.XSHG'\r\n else:\r\n th=dm_update_list[at][0]+'.XSHE' \r\n dm_sh_list.append(th)\r\nfor q in range(0, len(dm_update_list)):\r\n #更新收盘价\r\n total_df=jq.get_price(dm_sh_list[q],start_date=date_insert_list[0] , end_date=date_insert_list[-1], frequency='daily', fields=['open', 'close', 'high', 'low', 'volume'], skip_paused=True, fq='pre')\r\n total_df.reset_index(inplace=True,drop=False)\r\n total_list=total_df.values.tolist()\r\n for s in range(0,len(total_list)):\r\n sql = \" INSERT INTO %s (date,open,close,high,low,cjl) VALUES ( '%s', %.2f ,%.2f ,%.2f ,%.2f,%.2f )\" \r\n try:\r\n date = datetime.date(datetime.fromtimestamp(total_list[s][0].timestamp())) \r\n data = ('TB'+dm_update_list[q][0],date,total_list[s][1],total_list[s][2],total_list[s][3],total_list[s][4],total_list[s][5])\r\n cursor.execute(sql % data) \r\n except Exception as e:\r\n connect.rollback() # 事务回滚\r\n continue\r\n else:\r\n connect.commit() # 事务提交\r\n \r\n print('TB'+dm_sh_list[q][:6],'数据更新完成') \r\nprint('所有表所有数据更新完毕....................................') \r\n\r\n\r\nprint('**************************恭喜!所有数据为最新******************************') \r\n \r\n\r\n# 关闭连接\r\ncursor.close()\r\nconnect.close()","sub_path":"cjsj/采集10年数据/10数据更新.py","file_name":"10数据更新.py","file_ext":"py","file_size_in_byte":9820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"390577765","text":"import numpy as np\nnp.random.seed(0)\n\n\n# Queueing policies.\n\ndef first_come_first_served(queue):\n return queue.pop(0), queue\n\n\ndef last_come_first_served(queue):\n return queue.pop(), queue\n\n\ndef shortest_job_first(queue):\n next_job = min(queue)\n queue.remove(next_job)\n\n return next_job, queue\n\n\ndef longest_job_first(queue):\n next_job = max(queue)\n queue.remove(next_job)\n\n return next_job, queue\n\n\ndef random_first(queue):\n next_job = np.random.choice(queue)\n queue.remove(next_job)\n\n return next_job, queue\n\n\n# Arrival and service functions.\n\ndef exp_arrival_func():\n return np.random.exponential(2)\n\n\ndef exp_service_func():\n return np.random.exponential(1.5)\n\n\ndef uniform_service_func():\n return np.random.uniform(0, 3)\n\n\n# Simulation logic.\nclass Simulation:\n def __init__(self, arrival_func, service_func, policy):\n self.arrival_func = arrival_func\n self.service_func = service_func\n self.policy = policy\n\n self.clock = 0\n self.queue = []\n self.next_arrival = self.arrival_func()\n self.next_depart = float('inf')\n\n self.num_arrivals = 0\n self.num_departs = 0\n self.total_wait = 0\n\n def advance_time(self):\n next_event = min(self.next_arrival, self.next_depart)\n\n self.total_wait += len(self.queue) * (next_event - self.clock)\n self.clock = next_event\n\n if self.next_arrival <= self.next_depart:\n self.handle_arrival()\n else:\n self.handle_depart()\n\n def handle_arrival(self):\n self.queue.append(self.service_func())\n self.num_arrivals += 1\n\n if len(self.queue) <= 1:\n self.next_depart = self.clock + self.queue[0]\n self.next_arrival = self.clock + self.arrival_func()\n\n def handle_depart(self):\n self.num_departs += 1\n\n if len(self.queue) > 0:\n self.next_depart, self.queue = self.policy(self.queue)\n self.next_depart += self.clock\n else:\n self.next_depart = float('inf')\n\n\nif __name__ == '__main__':\n sim = Simulation(exp_arrival_func, exp_service_func,\n longest_job_first)\n\n for _ in range(1000):\n sim.advance_time()\n\n print(sim.num_arrivals)\n print(sim.num_departs)\n print(sim.total_wait)\n","sub_path":"simulations/simulation.py","file_name":"simulation.py","file_ext":"py","file_size_in_byte":2315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"120372949","text":"import os\nimport sys\nimport time\nimport traceback\nimport torch\nfrom queue import Queue\n\nimport requests\nfrom typing import List\nfrom functools import partial\n\nfrom ctools.utils import read_file, save_file, get_rank, get_world_size, get_data_decompressor, remove_file, broadcast\nfrom .base_comm_learner import BaseCommLearner\nfrom ..learner_hook import LearnerHook\n\n\nclass FlaskFileSystemLearner(BaseCommLearner):\n \"\"\"\n Overview:\n An implementation of CommLearner, using flask as the file system.\n Interfaces:\n __init__, register_learner, send_agent, get_data, send_train_info, start_heartbeats_thread\n init_service, close_service,\n Property:\n hooks4call\n \"\"\"\n\n def __init__(self, cfg: 'EasyDict') -> None: # noqa\n \"\"\"\n Overview:\n Initialize file path(url, path of traj & agent), comm frequency, dist learner info according to cfg.\n Arguments:\n - cfg (:obj:`EasyDict`): config dict\n \"\"\"\n super(FlaskFileSystemLearner, self).__init__(cfg)\n self._url_prefix = 'http://{}:{}/'.format(cfg.upstream_ip, cfg.upstream_port)\n\n self._path_traj = cfg.path_traj\n self._path_agent = cfg.path_agent\n # thread: _heartbeats_freq; hook: _send_agent_freq, _send_train_info_freq\n self._heartbeats_freq = cfg.heartbeats_freq\n self._send_agent_freq = cfg.send_agent_freq\n self._send_train_info_freq = cfg.send_train_info_freq\n self._rank = get_rank()\n self._world_size = get_world_size()\n if 'learner_ip' not in cfg.keys() or cfg.learner_ip == 'auto':\n self._learner_ip = os.environ.get('SLURMD_NODENAME', '')\n else:\n self._learner_ip = cfg.learner_ip\n self._learner_port = cfg.learner_port - self._rank\n self._restore = cfg.restore\n self._iter = 0\n\n # override\n def register_learner(self) -> None: # todo: 1 learner -> many agent?\n \"\"\"\n Overview:\n Register learner's info in coordinator, called by ``self.init_service``.\n Will set property ``_agent_name`` to returned response.info. Registration will repeat until succeeds.\n \"\"\"\n d = {\n 'learner_uid': self._learner_uid,\n 'learner_ip': self._learner_ip,\n 'learner_port': self._learner_port,\n 'world_size': self._world_size,\n 'restore': self._restore\n }\n while True: # only after registration succeeds, can ``_active_flag`` be set to True\n result = self._flask_send(d, 'coordinator/register_learner')\n if result is not None and result['code'] == 0:\n self._agent_name = result['info']['player_name']\n self._model_path = result['info']['model_path']\n return\n else:\n time.sleep(10)\n\n # override\n def send_agent(self, state_dict: dict) -> None:\n \"\"\"\n Overview:\n Save learner's agent in corresponding path, called by ``SendAgentHook``.\n Arguments:\n - state_dict (:obj:`dict`): state dict of the runtime agent\n \"\"\"\n new_path = self._agent_name + '_' + str(self._iter) + '_ckpt.pth'\n state_dict['model'] = {k: v for k, v in state_dict['model'].items() if 'value_networks' not in k}\n path = os.path.join(self._path_agent, new_path)\n save_file(path, state_dict)\n d = {'learner_uid': self._learner_uid, 'model_path': new_path}\n while self._active_flag:\n result = self._flask_send(d, 'coordinator/model_path_update')\n if result is not None and result['code'] == 0: # remove last model\n self._logger.info('save model at: {} for actor update'.format(new_path))\n if os.path.exists(os.path.join(self._path_agent, self._agent_name + '_' + str(self._iter - 5) +'_ckpt.pth')):\n os.remove(os.path.join(self._path_agent, self._agent_name + '_' + str(self._iter - 5) + '_ckpt.pth'))\n self._iter += 1\n return\n else:\n time.sleep(1)\n\n\n @staticmethod\n def load_data_fn(path_traj, traj_id, decompressor):\n file_path = os.path.join(path_traj, traj_id)\n s = read_file(file_path, fs_type='normal')\n remove_file(file_path)\n #s = decompressor(s)\n return s\n\n # override\n def get_data(self, batch_size: int) -> list: # todo: doc not finished\n \"\"\"\n Overview:\n Get batched data from coordinator.\n Arguments:\n - batch_size (:obj:`int`): size of one batch\n Returns:\n - stepdata (:obj:`list`): a list of train data, each element is one traj\n \"\"\"\n d = {'learner_uid': self._learner_uid, 'batch_size': batch_size}\n sleep_count = 1\n while self._active_flag:\n result = self._flask_send(d, 'coordinator/ask_for_metadata')\n if result is not None and result['code'] == 0:\n metadata = result['info']\n if metadata is not None:\n assert isinstance(metadata, list)\n decompressor = get_data_decompressor(metadata[0].get('compressor', 'none'))\n data = [\n partial(\n FlaskFileSystemLearner.load_data_fn,\n self._path_traj,\n m['traj_id'],\n decompressor=decompressor,\n ) for m in metadata\n ]\n return data\n time.sleep(sleep_count)\n sleep_count += 1\n\n # override\n def send_train_info(self, train_info: dict) -> None:\n \"\"\"\n Overview:\n Send train info to coordinator, called by ``SendTrainInfoHook``.\n Sending will repeat until succeeds or ``_active_flag`` is set to False.\n Arguments:\n - train info (:obj:`dict`): train info in `dict` type, \\\n including keys `train_info`(last iter), `learner_uid`\n \"\"\"\n d = {'train_info': train_info, 'learner_uid': self._learner_uid}\n while self._active_flag:\n result = self._flask_send(d, 'coordinator/send_train_info')\n if result is not None and result['code'] == 0:\n return result['info']\n else:\n time.sleep(1)\n\n # override\n def _send_learner_heartbeats(self) -> None:\n \"\"\"\n Overview:\n Send learner's heartbeats to coordinator, will start as a thread in ``self.start_heartbeats_thread``.\n Sending will take place every ``_heartbeats_freq`` seconds until ``_active_flag`` is set to False.\n \"\"\"\n d = {'learner_uid': self._learner_uid}\n while self._active_flag:\n self._flask_send(d, 'coordinator/get_heartbeats')\n for _ in range(self._heartbeats_freq):\n if not self._active_flag:\n break\n time.sleep(1)\n\n def _flask_send(self, data: dict, api: str) -> dict:\n \"\"\"\n Overview:\n Send info via flask and return the response.\n Log corresponding info/error when succeeds, fails or raises an exception.\n Arguments:\n - data (:obj:`dict`): the data to send via ``requests`` api\n - api (:obj:`str`): the specific api which the data will be sent to, \\\n should add prefix ([ip]:[port]) before when using.\n Returns:\n - response (:obj:`dict`): if no exception raises, return the json response\n \"\"\"\n response = None\n t = time.time()\n try:\n response = requests.post(self._url_prefix + api, json=data).json()\n if hasattr(self, '_agent_name'):\n name = self._agent_name.split('_')[0]\n else:\n name = 'none'\n if response['code'] == 0:\n self._logger.info(\"{} succeed sending result: {}, cost time: {:.4f}\".format(api, name, time.time() - t))\n else:\n self._logger.error(\"{} failed to send result: {}, cost time: {:.4f}\".format(api, name, time.time() - t))\n except Exception as e:\n self._logger.error(''.join(traceback.format_tb(e.__traceback__)))\n self._logger.error(\"[error] api({}): {}\".format(api, sys.exc_info()))\n return response\n\n @property\n def hooks4call(self) -> List[LearnerHook]:\n \"\"\"\n Overview:\n Initialize the hooks and return them.\n Returns:\n - hooks (:obj:`list`): the hooks which comm learner have, will be registered in learner as well.\n \"\"\"\n return [\n SendAgentHook('send_agent', 100, position='before_run', ext_args={}),\n SendAgentHook(\n 'send_agent', 100, position='after_iter', ext_args={'send_agent_freq': self._send_agent_freq}\n ),\n SendTrainInfoHook(\n 'send_train_info',\n 100,\n position='after_iter',\n ext_args={'send_train_info_freq': self._send_train_info_freq}\n ),\n ]\n\n def model_path(self):\n return os.path.join(self._path_agent, self._model_path)\n #return '/mnt/cache/zhouhang2/repo/distar/distar/entry/as_rl_baseline/experiments/final12/ckpt/iteration_86600.pth.tar'\n\nclass SendAgentHook(LearnerHook):\n \"\"\"\n Overview:\n Hook to send agent\n Interfaces:\n __init__, __call__\n Property:\n name, priority, position\n \"\"\"\n\n def __init__(self, *args, ext_args: dict = {}, **kwargs) -> None:\n \"\"\"\n Overview:\n init SendAgentHook\n Arguments:\n - ext_args (:obj:`dict`): extended_args, use ext_args.freq to set send_agent_freq\n \"\"\"\n super().__init__(*args, **kwargs)\n if 'send_agent_freq' in ext_args:\n self._freq = ext_args['send_agent_freq']\n else:\n self._freq = 1\n\n def __call__(self, engine: 'BaseLearner') -> None: # noqa\n \"\"\"\n Overview:\n Save learner's agent in corresponding path at interval iterations, including model_state_dict, last_iter\n Arguments:\n - engine (:obj:`BaseLearner`): the BaseLearner\n \"\"\"\n last_iter = engine.last_iter.val\n if engine.rank == 0 and last_iter % self._freq == 0:\n state_dict = {'model': engine.agent.model.state_dict(), 'iter': last_iter}\n engine.send_agent(state_dict)\n engine.info('{} save iter{} agent'.format(engine.name, last_iter))\n\n\nclass SendTrainInfoHook(LearnerHook):\n \"\"\"\n Overview:\n Hook to send train info\n Interfaces:\n __init__, __call__\n Property:\n name, priority, position\n \"\"\"\n\n def __init__(self, *args, ext_args: dict, **kwargs) -> None:\n \"\"\"\n Overview:\n init SendTrainInfoHook\n Arguments:\n - ext_args (:obj:`dict`): extended_args, use ext_args.freq to set send_train_info_freq\n \"\"\"\n super().__init__(*args, **kwargs)\n self._freq = ext_args['send_train_info_freq']\n\n def __call__(self, engine: 'BaseLearner') -> None: # noqa\n \"\"\"\n Overview:\n Send train info including last_iter at interval iterations, learner_uid (added in ``send_train_info``)\n Arguments:\n - engine (:obj:`BaseLearner`): the BaseLearner\n \"\"\"\n flag = torch.tensor([0])\n if engine.rank == 0:\n last_iter = engine.last_iter.val\n frames = int(self._freq * engine._world_size * engine._cfg.learner.data.batch_size * engine._cfg.learner.unroll_len)\n if last_iter % self._freq == 0 and hasattr(engine, 'last_ckpt_path'):\n state_dict = {'iter': frames, 'ckpt_path': os.path.abspath(engine.last_ckpt_path)}\n checkpoint_path = engine.send_train_info(state_dict)\n engine.info('{} save iter{} train_info'.format(engine.name, last_iter))\n if checkpoint_path != 'none':\n flag = torch.tensor([1])\n engine.checkpoint_manager.load(\n os.path.join(engine._path_agent, checkpoint_path),\n model=engine.agent.model,\n logger_prefix='({})'.format(engine.name),\n strict=True,\n info_print=engine.rank == 0,\n )\n engine.info('{} reset ckpt in {}!!!!!!!!!!!!!!!!!'.format(engine.name, checkpoint_path))\n state_dict = {'model': engine.agent.model.state_dict(), 'iter': last_iter}\n engine.send_agent(state_dict)\n engine.info('{} save iter{} agent'.format(engine.name, last_iter))\n broadcast(flag, 0)\n if flag: \n engine._setup_optimizer()\n engine._agent.model.broadcast_params()\n","sub_path":"ctools/worker/learner/comm/flask_fs_learner.py","file_name":"flask_fs_learner.py","file_ext":"py","file_size_in_byte":12979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"459047846","text":"# -*- coding: utf-8 -*-\nimport json\nimport os\nimport logging\nfrom copy import deepcopy\nfrom datetime import datetime, timedelta, date\n\nfrom PIL import Image\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.admin import helpers\nfrom django.core.cache import cache\nfrom django.core.files import File\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.core.urlresolvers import reverse\nfrom django.db import models\nfrom django.db.models import get_model\nfrom django.db.models.fields.files import ImageFieldFile as DjangoImageFieldFile, FieldFile\nfrom django.forms.models import modelform_factory\nfrom django.http.response import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render, get_object_or_404\nfrom django.template.defaultfilters import slugify\nfrom django.template.loader import get_template\nfrom django.utils.module_loading import import_by_path\nfrom django.utils.translation import ugettext as _\nfrom django.views.generic.base import TemplateView\nfrom django.views.generic.list import ListView\nfrom django.forms.fields import DateField, DateTimeField\nfrom import_export.formats.base_formats import XLS, CSV\n\nfrom ikwen.accesscontrol.backends import UMBRELLA\nfrom ikwen.accesscontrol.models import Member\nfrom ikwen.core.fields import MultiImageFieldFile, ImageFieldFile\nfrom ikwen.core.models import Service, AbstractConfig\nfrom ikwen.core.utils import get_service_instance, DefaultUploadBackend, generate_icons, get_model_admin_instance, \\\n get_preview_from_extension\nfrom ikwen.revival.models import ProfileTag, Revival\n\nlogger = logging.getLogger('ikwen')\n\n\nclass HybridListView(ListView):\n \"\"\"\n Extension of the django builtin :class:`django.views.generic.ListView`. This view is Hybrid because it can\n render HTML or JSON results for Ajax calls.\n\n :attr:search_field: Name of the default field it uses to filter Ajax requests. Defaults to *name*\n :attr:ordering: Tuple of model fields used to order object list when page is rendered in HTML\n :attr:ajax_ordering: Tuple of model fields used to order results of Ajax requests. It is similar to ordering of\n django admin\n \"\"\"\n page_size = int(getattr(settings, 'HYBRID_LIST_PAGE_SIZE', '50'))\n max_visible_page_count = 5\n search_field = 'name'\n ordering = ('-id', )\n list_filter = ()\n ajax_ordering = ('-id', )\n template_name = None\n html_results_template_name = 'core/snippets/object_list_results.html'\n embed_doc_template_name = None\n change_object_url_name = None\n show_add = True\n show_import = False\n export_resource = None\n\n def get_template_names(self):\n meta = self.get_queryset().model._meta\n if self.template_name:\n return [self.template_name]\n else:\n return [\"%s/%s_list.html\" % (meta.app_label, meta.model_name), 'core/object_list_base.html']\n\n def get_context_data(self, **kwargs):\n context = super(HybridListView, self).get_context_data(**kwargs)\n queryset = self.get_queryset()\n queryset = self.filter_queryset(queryset)\n start_date = self.request.GET.get('start_date')\n end_date = self.request.GET.get('end_date')\n max_chars = self.request.GET.get('max_chars', 4)\n if start_date and end_date:\n queryset = queryset.filter(created_on__range=(start_date, end_date))\n elif start_date:\n queryset = queryset.filter(created_on__gte=start_date)\n elif end_date:\n queryset = queryset.filter(created_on__lte=end_date)\n queryset = self.get_search_results(queryset, max_chars=max_chars)\n context_object_name = self.get_context_object_name(self.object_list)\n context[context_object_name] = queryset.order_by(*self.ordering)[:self.page_size]\n context['queryset'] = queryset\n context['page_size'] = self.get_page_size(self.request)\n context['max_visible_page_count'] = self.get_max_visible_page_count(queryset)\n context['total_objects'] = self.get_queryset().count()\n context['filter'] = self.get_filter()\n model = queryset.model\n meta = model._meta\n context['verbose_name'] = meta.verbose_name\n context['verbose_name_plural'] = meta.verbose_name_plural\n try:\n context['has_is_active_field'] = True if model().is_active is not None else False\n except AttributeError:\n pass\n try:\n context['is_sortable'] = True if model().order_of_appearance is not None else False\n except AttributeError:\n pass\n context['change_object_url_name'] = self.get_change_object_url_name(self.request, **kwargs)\n context['html_results_template_name'] = self.html_results_template_name\n context['show_add'] = self.show_add\n context['show_import'] = self.show_import\n context['show_export'] = self.export_resource is not None\n context['embed_doc_template_name'] = self.get_embed_doc_template_name()\n context['first_setup'] = self.request.GET.get('first_setup')\n return context\n\n def render_to_response(self, context, **response_kwargs):\n fmt = self.request.GET.get('format')\n queryset = context['queryset']\n if fmt == 'json':\n queryset = queryset.order_by(*self.ajax_ordering)\n start = int(self.request.GET.get('start', 0))\n length = int(self.request.GET.get('length', self.page_size))\n limit = start + length\n queryset = queryset[start:limit]\n response = []\n for item in queryset:\n try:\n response.append(item.to_dict())\n except:\n continue\n callback = self.request.GET.get('callback')\n if callback:\n response = {'object_list': response}\n jsonp = callback + '(' + json.dumps(response) + ')'\n return HttpResponse(jsonp, content_type='application/json', **response_kwargs)\n return HttpResponse(json.dumps(response), 'content-type: text/json', **response_kwargs)\n else:\n queryset = queryset.order_by(*self.ordering)\n if self.request.GET.get('action') == 'export':\n return self.export(queryset)\n paginator = Paginator(queryset, self.page_size)\n page = self.request.GET.get('page')\n try:\n objects_page = paginator.page(page)\n page = int(page)\n except PageNotAnInteger:\n page = 1\n objects_page = paginator.page(1)\n except EmptyPage:\n page = paginator.num_pages\n objects_page = paginator.page(paginator.num_pages)\n context['q'] = self.request.GET.get('q')\n context['objects_page'] = objects_page\n max_visible_page_count = context['max_visible_page_count']\n min_page = page - (page % max_visible_page_count)\n if min_page < max_visible_page_count:\n min_page += 1\n max_page = min(min_page + max_visible_page_count, paginator.num_pages)\n if page == paginator.num_pages:\n min_page = page - max_visible_page_count\n context['page_range'] = range(min_page, max_page + 1)\n context['max_page'] = max_page\n context['has_image'] = self.get_has_image(queryset)\n if fmt == 'html_results':\n return render(self.request, self.html_results_template_name, context)\n else:\n return super(HybridListView, self).render_to_response(context, **response_kwargs)\n\n def get(self, request, *args, **kwargs):\n action = request.GET.get('action')\n model_name = request.GET.get('model_name')\n if model_name:\n model = get_model(*model_name.split('.'))\n elif self.model:\n model = self.model\n else:\n model = self.get_queryset().model\n if action == 'delete':\n selection = request.GET['selection'].split(',')\n deleted = []\n for pk in selection:\n try:\n obj = model.objects.get(pk=pk)\n obj.delete()\n deleted.append(pk)\n except:\n continue\n response = {\n 'message': \"%d item(s) deleted.\" % len(selection),\n 'deleted': deleted\n }\n return HttpResponse(json.dumps(response))\n elif action == 'toggle_attribute':\n object_id = request.GET['object_id']\n attr = request.GET['attr']\n val = request.GET['val']\n obj = model._default_manager.get(pk=object_id)\n if val.lower() == 'true':\n obj.__dict__[attr] = True\n else:\n obj.__dict__[attr] = False\n obj.save()\n response = {'success': True}\n return HttpResponse(json.dumps(response), 'content-type: text/json')\n elif action:\n f = getattr(self, action)\n return f(request, *args, **kwargs)\n # Sorting stuffs\n sorted_keys = request.GET.get('sorted')\n if sorted_keys:\n for token in sorted_keys.split(','):\n object_id, order_of_appearance = token.split(':')\n try:\n model._default_manager.filter(pk=object_id).update(order_of_appearance=order_of_appearance)\n except:\n continue\n return super(HybridListView, self).get(request, *args, **kwargs)\n\n def get_change_object_url_name(self, request, **kwargs):\n if self.change_object_url_name:\n return self.change_object_url_name\n queryset = self.get_queryset()\n meta = queryset.model._meta\n return '%s:change_%s' % (meta.app_label, meta.model_name)\n\n def get_page_size(self, request):\n return self.page_size\n\n def get_max_visible_page_count(self, queryset):\n return self.max_visible_page_count\n\n def get_has_image(self, queryset):\n try:\n model_obj = queryset.order_by('-id')[0] # Take last created object as it tends to have most updated fields\n keys = model_obj.__dict__.keys()\n if not 'image' in keys:\n keys.append('image')\n if not 'photo' in keys:\n keys.append('photo')\n for key in keys:\n try:\n field = model_obj.__getattribute__(key)\n except:\n continue\n if isinstance(field, DjangoImageFieldFile) or isinstance(field, ImageFieldFile):\n return True\n except:\n return False\n\n def get_search_results(self, queryset, max_chars=None):\n \"\"\"\n Default search function that filters the queryset based on\n the value of GET parameter q and the search_field.\n Only the first max_chars of the search string will be used\n to search. Setting it to none causes to search with the\n input string exactly as such.\n \"\"\"\n # TODO: Implement MongoDB native indexed text search instead of Django ORM one for better performance\n search_term = self.request.GET.get('q')\n if search_term and len(search_term) >= 2:\n search_term = search_term.lower()\n word = slugify(search_term).replace('-', ' ')\n try:\n word = word[:int(max_chars)]\n except:\n pass\n if word:\n kwargs = {self.search_field + '__icontains': word}\n queryset = queryset.filter(**kwargs)\n return queryset\n\n def get_list_filter(self):\n return self.list_filter\n\n def get_filter(self):\n \"\"\"\n Generates the filter options based on self.get_list_filter()\n \"\"\"\n options = []\n for item in self.get_list_filter():\n if callable(item) or (type(item) is str and item.find('.') > 0):\n if type(item) is str:\n item = import_by_path(item)\n filter = item()\n choices = filter.lookups()\n try:\n is_date_filter = item.is_date_filter\n except:\n is_date_filter = False\n if choices:\n options.append({\n 'title': filter.title,\n 'parameter_name': filter.parameter_name,\n 'choices': filter.lookups(),\n 'is_date_filter': is_date_filter\n })\n else:\n if type(item) is tuple:\n item_title = item[1]\n item = item[0]\n else:\n item_title = item\n elt = None\n choices = []\n is_date_filter = False\n try:\n sample = self.get_queryset().order_by('-id')[0] # Take last created object as they tend to have most updated fields\n elt = sample.__getattribute__(item)\n except IndexError:\n pass\n if isinstance(elt, datetime) or isinstance(elt, date):\n now = datetime.now()\n criterion = {item + '__gt': now}\n has_future_dates = self.get_queryset().filter(**criterion).count() > 0\n choices = [\n ('__period__today', _(\"Today\")),\n ('__period__yesterday', _(\"Yesterday\")),\n ('__period__last_7_days', _(\"Last 7 days\")),\n ('__period__since_the_1st', _(\"Since the 1st\")),\n ]\n if has_future_dates:\n choices.extend([\n ('__period__next_7_days', _(\"Next 7 days\")),\n ('__period__next_30_days', _(\"Next 30 days\")),\n ])\n is_date_filter = True\n else:\n item_values = set([obj.__getattribute__(item) for obj in self.get_queryset()])\n item_values = list(sorted(item_values))\n item_values = [val for val in item_values if val is not None]\n if set(item_values) == {True, False}:\n choices = [\n (\"__true__\", _(\"Yes\")),\n (\"__false__\", _(\"No\"))\n ]\n elif len(item_values) > 0:\n obj = item_values[0]\n if isinstance(obj, models.Model):\n choices = [(obj.id, obj) for obj in item_values]\n else:\n choices = [(val, val) for val in item_values]\n options.append({\n 'title': item_title.capitalize(),\n 'parameter_name': item,\n 'choices': choices,\n 'is_date_filter': is_date_filter\n })\n return options\n\n def get_export_filename(self, file_format):\n date_str = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')\n if self.model:\n model = self.model\n else:\n model = self.get_queryset().model\n filename = \"%s_%s.%s\" % (model.__name__, date_str, file_format.get_extension())\n return filename\n\n def export(self, queryset):\n file_format = CSV()\n data = self.export_resource().export(queryset)\n export_data = file_format.export_data(data)\n content_type = file_format.get_content_type()\n try:\n response = HttpResponse(export_data, content_type=content_type)\n except TypeError:\n response = HttpResponse(export_data, mimetype=content_type)\n response['Content-Disposition'] = 'attachment; filename=%s' % self.get_export_filename(file_format)\n return response\n\n def filter_queryset(self, queryset):\n for item in self.get_list_filter():\n if callable(item) or (type(item) is str and item.find('.') > 0):\n if type(item) is str:\n item = import_by_path(item)\n filter = item()\n queryset = filter.queryset(self.request, queryset)\n else:\n if type(item) is tuple:\n item = item[0]\n kwargs = {}\n value = self.request.GET.get(item)\n if value:\n if value == '__true__':\n value = True\n elif value == '__false__':\n value = False\n elif value.startswith('__period__'):\n now = datetime.now()\n start_date, end_date = None, now\n value = value.replace('__period__', '')\n if value == 'today':\n start_date = datetime(now.year, now.month, now.day, 0, 0, 0)\n elif value == 'yesterday':\n yst = now - timedelta(days=1)\n start_date = datetime(yst.year, yst.month, yst.day, 0, 0, 0)\n end_date = datetime(yst.year, yst.month, yst.day, 23, 59, 59)\n elif value == 'last_7_days':\n b = now - timedelta(days=7)\n start_date = datetime(b.year, b.month, b.day, 0, 0, 0)\n elif value == 'since_the_1st':\n start_date = datetime(now.year, now.month, 1, 0, 0, 0)\n elif value == 'next_7_days':\n dl = now + timedelta(days=7)\n start_date = datetime(now.year, now.month, now.day, 0, 0, 0)\n end_date = datetime(dl.year, dl.month, dl.day, 23, 59, 59)\n elif value == 'next_30_days':\n dl = now + timedelta(days=30)\n start_date = datetime(now.year, now.month, now.day, 0, 0, 0)\n end_date = datetime(dl.year, dl.month, dl.day, 23, 59, 59)\n else:\n start_date, end_date = value.split(',')\n start_date += ' 00:00:00'\n end_date += ' 23:59:59'\n if start_date:\n item = item + '__range'\n value = (start_date, end_date)\n kwargs[item] = value\n queryset = queryset.filter(**kwargs)\n return queryset\n\n def get_embed_doc_template_name(self):\n meta = self.get_queryset().model._meta\n if self.embed_doc_template_name:\n embed_doc_template_name = self.embed_doc_template_name\n else:\n embed_doc_template_name = \"%s/embed_doc/change_%s.html\" % (meta.app_label, meta.model_name)\n try:\n get_template(embed_doc_template_name) # Just to test whether this template exists.\n return embed_doc_template_name\n except:\n pass\n\n\nclass ChangeObjectBase(TemplateView):\n model = None\n model_admin = None\n object_list_url = None # Django url name of the object list page\n change_object_url = None # Django url name of the change object page\n template_name = None\n embed_doc_template_name = None\n context_object_name = 'obj'\n profiles_aware = False # If set to true, object ProfileTag management utilities will be integrated to the object\n auto_profile = False # If true, this object generates a secret ProfileTag matching the actual object upon save\n revival_mail_renderer = None\n label_field = None\n slug_field = None\n\n def get_model(self):\n if isinstance(self.model, basestring):\n return get_model(*self.model.split('.'))\n else:\n return self.model\n\n def get_model_admin(self):\n if isinstance(self.model_admin, basestring):\n return import_by_path(self.model_admin)\n else:\n return self.model_admin\n\n def get_object(self, **kwargs):\n object_id = kwargs.get('object_id') # May be overridden with the one from GET data\n object_id = self.request.GET.get('object_id', object_id)\n if object_id:\n model = self.get_model()\n return get_object_or_404(model, pk=object_id)\n\n def get_model_form(self, obj):\n model = self.get_model()\n model_admin = self.get_model_admin()\n ModelForm = modelform_factory(model, fields=model_admin.fields)\n if obj:\n form = ModelForm(instance=obj)\n else:\n form = ModelForm(instance=model())\n return form\n\n def get_template_names(self):\n meta = self.get_model()._meta\n if self.template_name:\n return [self.template_name]\n else:\n return [\"%s/change_%s.html\" % (meta.app_label, meta.model_name), 'core/change_object_base.html']\n\n def get_embed_doc_template_name(self):\n meta = self.get_model()._meta\n if self.embed_doc_template_name:\n embed_doc_template_name = self.embed_doc_template_name\n else:\n embed_doc_template_name = \"%s/embed_doc/change_%s.html\" % (meta.app_label, meta.model_name)\n try:\n get_template(embed_doc_template_name) # Just to test whether this template exists.\n return embed_doc_template_name\n except:\n pass\n\n def get_context_data(self, **kwargs):\n context = super(ChangeObjectBase, self).get_context_data(**kwargs)\n model = self.get_model()\n model_admin = self.get_model_admin()\n model_admin = get_model_admin_instance(model, model_admin)\n obj = self.get_object(**kwargs)\n form = self.get_model_form(obj)\n obj_form = helpers.AdminForm(form, list(model_admin.get_fieldsets(self.request, obj)),\n model_admin.get_prepopulated_fields(self.request, obj),\n model_admin.get_readonly_fields(self.request, obj))\n model_obj = obj if obj else model()\n date_field_list = []\n datetime_field_list = []\n media_field_list = []\n i = 0\n for key in model_obj.__dict__.keys():\n field = model_obj.__getattribute__(key)\n if isinstance(field, FieldFile):\n if not field.field.editable:\n continue\n if isinstance(field, DjangoImageFieldFile) or isinstance(field, ImageFieldFile):\n preview = field.name\n elif isinstance(field, MultiImageFieldFile):\n preview = field.small_name\n else:\n preview = get_preview_from_extension(field.name) if field.name else ''\n media_obj = {\n 'image': field,\n 'media': field,\n 'preview': preview,\n 'field': key,\n 'help_text': field.field.help_text,\n 'counter': i\n }\n media_field_list.append(media_obj)\n i += 1\n field = form.base_fields.get(key)\n if isinstance(field, DateField):\n date_field_list.append(key)\n if isinstance(field, DateTimeField):\n datetime_field_list.append(key)\n\n context[self.context_object_name] = obj\n context['obj'] = obj # Base template recognize the context object only with the name 'obj'\n context['model'] = model_obj._meta.app_label + '.' + model_obj._meta.model_name\n context['verbose_name'] = model_obj._meta.verbose_name\n context['verbose_name_plural'] = model_obj._meta.verbose_name_plural\n context['object_list_url'] = self.get_object_list_url(self.request, obj, **kwargs)\n context['model_admin_form'] = obj_form\n context['label_field'] = self.label_field if self.label_field else 'name'\n context['slug_field'] = self.slug_field if self.slug_field else 'slug'\n context['date_field_list'] = date_field_list\n context['datetime_field_list'] = datetime_field_list\n context['media_field_list'] = media_field_list\n context['embed_doc_template_name'] = self.get_embed_doc_template_name()\n return context\n\n def get(self, request, *args, **kwargs):\n action = request.GET.get('action')\n if action == 'delete_image' or action == 'delete_media':\n model = self.get_model()\n object_id = kwargs.get('object_id')\n obj = get_object_or_404(model, pk=object_id)\n media_field = request.POST.get('media_field')\n if not media_field:\n media_field = request.POST.get('image_field', 'image')\n media = obj.__getattribute__(media_field)\n if media.name:\n os.unlink(media.path)\n try:\n os.unlink(media.small_path)\n os.unlink(media.thumb_path)\n except:\n pass\n obj.__setattr__(media_field, None)\n obj.save()\n return HttpResponse(\n json.dumps({'success': True}),\n content_type='application/json'\n )\n return super(ChangeObjectBase, self).get(request, *args, **kwargs)\n\n def post(self, request, *args, **kwargs):\n model = self.get_model()\n model_admin = self.get_model_admin()\n object_admin = get_model_admin_instance(model, model_admin)\n obj = self.get_object(**kwargs)\n before = None\n if obj:\n before = deepcopy(obj)\n else:\n obj = model()\n model_form = object_admin.get_form(request)\n form = model_form(request.POST, request.FILES, instance=obj)\n if form.is_valid():\n obj = form.save()\n slug_field = request.POST.get('slug_field', 'slug')\n slug = request.POST.get(slug_field)\n if slug:\n obj.__setattr__(slug_field, slug)\n else:\n try:\n obj.__getattribute__(slug_field)\n label_field = request.POST.get('label_field', 'name')\n try:\n label = obj.__getattribute__(label_field)\n obj.__setattr__(slug_field, slugify(label))\n obj.save()\n except:\n pass\n except:\n pass\n\n if self.auto_profile:\n label_field = request.POST.get('label_field', 'name')\n try:\n label = obj.__getattribute__(label_field)\n slug = '__' + slugify(label)\n if before:\n before_name = before.__getattribute__(label_field)\n before_slug = '__' + slugify(before_name)\n if before_name != label:\n ProfileTag.objects.filter(slug=before_slug).update(name=label, slug=slug)\n else:\n ProfileTag.objects.get_or_create(name=label, slug=slug, is_auto=True)\n except:\n pass\n\n s = get_service_instance()\n for key in obj.__dict__.keys():\n media = obj.__getattribute__(key)\n if not (isinstance(media, FieldFile) and media.field.editable):\n continue\n uploaded_media_url = request.POST.get(key)\n if uploaded_media_url and (not media.name or uploaded_media_url != media.url):\n filename = uploaded_media_url.split('/')[-1]\n media_root = getattr(settings, 'MEDIA_ROOT')\n path = uploaded_media_url.replace(getattr(settings, 'MEDIA_URL'), '')\n if isinstance(media, DjangoImageFieldFile) or isinstance(media, ImageFieldFile):\n seo_filename = s.project_name_slug + '_' + filename\n else:\n seo_filename = filename.capitalize()\n try:\n with open(media_root + path, 'r') as f:\n content = File(f)\n destination = media_root + media.field.upload_to + \"/\" + seo_filename\n media.save(destination, content)\n os.unlink(media_root + path)\n except:\n continue\n self.save_object_profile_tags(request, obj, *args, **kwargs)\n response = self.after_save(request, obj, *args, **kwargs)\n if response:\n return response\n if request.POST.get('keep_editing'):\n next_url = self.get_change_object_url(request, obj, *args, **kwargs)\n else:\n next_url = self.get_object_list_url(request, obj, *args, **kwargs)\n if before:\n messages.success(request, u'%s %s %s' % (obj._meta.verbose_name.capitalize(), unicode(obj), _('successfully updated')))\n else:\n messages.success(request, u'%s %s %s' % (obj._meta.verbose_name.capitalize(), unicode(obj), _('successfully changed')))\n return HttpResponseRedirect(next_url)\n else:\n context = self.get_context_data(**kwargs)\n context['errors'] = form.errors\n return render(request, self.get_template_names(), context)\n\n def get_object_list_url(self, request, obj, *args, **kwargs):\n model = self.get_model()\n if self.object_list_url:\n url = reverse(self.object_list_url)\n else:\n try:\n if obj is None:\n obj = model()\n url = reverse('%s:%s_list' % (obj._meta.app_label, obj._meta.model_name))\n except:\n url = request.META['HTTP_REFERER']\n return url\n\n def get_change_object_url(self, request, obj, *args, **kwargs):\n model = self.get_model()\n if self.change_object_url:\n url = reverse(self.change_object_url, args=(obj.id, ))\n else:\n try:\n if obj is None:\n obj = model()\n url = reverse('%s:change_%s' % (obj._meta.app_label, obj._meta.model_name), args=(obj.id, ))\n except:\n url = request.META['HTTP_REFERER']\n return url\n\n def save_object_profile_tags(self, request, obj, *args, **kwargs):\n auto_profiletag_id_list = kwargs.pop('auto_profiletag_id_list', [])\n profiletag_ids = request.GET.get('profiletag_ids', '').strip()\n revival_mail_renderer = kwargs.pop('revival_mail_renderer', self.revival_mail_renderer)\n if not (profiletag_ids or auto_profiletag_id_list):\n return\n do_revive = kwargs.pop('do_revive', None) # Set a revival if explicitly stated to do so\n if do_revive is None and not kwargs.get('object_id'):\n do_revive = True # Set a revival in any case for a newly added item\n profiletag_id_list = []\n if profiletag_ids:\n profiletag_id_list = profiletag_ids.split(',')\n profiletag_id_list.extend(auto_profiletag_id_list)\n model_name = obj._meta.app_label + '.' + obj._meta.model_name\n if do_revive and revival_mail_renderer: # This is a newly created object\n service = get_service_instance()\n srvce = Service.objects.using(UMBRELLA).get(pk=service.id)\n for tag_id in profiletag_id_list:\n revival, update = Revival.objects.get_or_create(service=service, model_name=model_name, object_id=obj.id,\n profile_tag_id=tag_id, mail_renderer=revival_mail_renderer)\n Revival.objects.using(UMBRELLA).get_or_create(id=revival.id, service=srvce, model_name=model_name, object_id=obj.id,\n profile_tag_id=tag_id, mail_renderer=revival_mail_renderer)\n\n def after_save(self, request, obj, *args, **kwargs):\n \"\"\"\n Run after the form is successfully saved\n in the post() function\n \"\"\"\n return None\n\n\nclass CustomizationImageUploadBackend(DefaultUploadBackend):\n \"\"\"\n Ajax upload handler for ikwen cover and profile images\n \"\"\"\n def upload_complete(self, request, filename, *args, **kwargs):\n import os\n from ikwen.conf import settings as ikwen_settings\n from ikwen.core.views import Configuration\n path = self.UPLOAD_DIR + \"/\" + filename\n self._dest.close()\n img_upload_context = request.GET['img_upload_context']\n media_root = getattr(settings, 'MEDIA_ROOT')\n usage = request.GET['usage']\n full_path = media_root + path\n try:\n with open(full_path, 'r') as f:\n content = File(f)\n if img_upload_context == Configuration.UPLOAD_CONTEXT:\n service_id = request.GET['service_id']\n service = Service.objects.get(pk=service_id)\n config = service.config\n if usage == 'profile':\n img = Image.open(full_path)\n if img.size != (512, 512):\n return {'error': _('Invalid dimensions. Please upload a 512 x 512px image.')}\n current_image_path = config.logo.path if config.logo.name else None\n destination = media_root + AbstractConfig.LOGO_UPLOAD_TO + \"/\" + filename\n config.logo.save(destination, content)\n url = ikwen_settings.MEDIA_URL + config.logo.name\n src = config.logo.path\n if getattr(settings, 'IS_UMBRELLA', False):\n icons_media_root = '%s%s/' % (ikwen_settings.CLUSTER_MEDIA_ROOT, service.project_name_slug)\n else:\n icons_media_root = None\n generate_icons(src, media_root=icons_media_root)\n destination2_folder = ikwen_settings.MEDIA_ROOT + AbstractConfig.LOGO_UPLOAD_TO\n if not os.path.exists(destination2_folder):\n os.makedirs(destination2_folder)\n destination2 = config.logo.path.replace(media_root, ikwen_settings.MEDIA_ROOT)\n os.rename(destination, destination2)\n else:\n img = Image.open(full_path)\n if img.size != (1000, 390):\n return {'error': _('Invalid dimensions. Please upload a 1000 x 590px image.')}\n current_image_path = config.cover_image.path if config.cover_image.name else None\n destination = media_root + AbstractConfig.COVER_UPLOAD_TO + \"/\" + filename\n config.cover_image.save(destination, content)\n url = ikwen_settings.MEDIA_URL + config.cover_image.name\n destination2_folder = ikwen_settings.MEDIA_ROOT + AbstractConfig.COVER_UPLOAD_TO\n if not os.path.exists(destination2_folder):\n os.makedirs(destination2_folder)\n destination2 = config.cover_image.path.replace(media_root, ikwen_settings.MEDIA_ROOT)\n os.rename(destination, destination2)\n cache.delete(service.id + ':config:')\n cache.delete(service.id + ':config:default')\n cache.delete(service.id + ':config:' + UMBRELLA)\n config.save(using=UMBRELLA)\n else:\n member_id = request.GET['member_id']\n member = Member.objects.get(pk=member_id)\n if usage == 'profile':\n current_image_path = member.photo.path if member.photo.name else None\n destination = media_root + Member.PROFILE_UPLOAD_TO + \"/\" + filename\n member.photo.save(destination, content)\n url = ikwen_settings.MEDIA_URL + member.photo.small_name\n else:\n current_image_path = member.cover_image.path if member.cover_image.name else None\n destination = media_root + Member.COVER_UPLOAD_TO + \"/\" + filename\n member.cover_image.save(destination, content)\n url = ikwen_settings.MEDIA_URL + member.cover_image.name\n member.propagate_changes()\n try:\n if os.path.exists(media_root + path):\n os.unlink(media_root + path)\n except Exception as e:\n if getattr(settings, 'DEBUG', False):\n raise e\n if current_image_path:\n try:\n if os.path.exists(current_image_path):\n os.unlink(current_image_path)\n except OSError as e:\n if getattr(settings, 'DEBUG', False):\n raise e\n return {\n 'url': url\n }\n except IOError as e:\n logger.error(\"File failed to upload. May be invalid or corrupted image file\", exc_info=True)\n if settings.DEBUG:\n raise e\n return {'error': 'File failed to upload. May be invalid or corrupted image file'}\n","sub_path":"core/generic.py","file_name":"generic.py","file_ext":"py","file_size_in_byte":37958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"175718456","text":"from flask import Flask, render_template, request, Response, jsonify\nimport sqlite3\nimport json, sys\nimport time, datetime\nimport webbrowser\nfrom initFunctions import *\n\n\n# Set the desired host and port\nhostName = '127.0.0.1'\nportNumber = 8000\n\n\n# Sets up/connects to DB\nconn = sqlite3.connect('coins.db')\nc = conn.cursor()\n\n\napp = Flask(__name__, static_folder='../static/dist', template_folder='../static')\n\n\n# Attempts to set up the necessary tables\ntry:\n # Coins Table\n c.execute('''\n\t CREATE TABLE Coins(\n coinID INTEGER PRIMARY KEY,\n coinTypeID INTEGER,\n year TEXT,\n mint TEXT,\n name TEXT,\n nickname TEXT,\n value INTEGER,\n quantity INTEGER,\n note TEXT\n )\n ''')\n\n # Coin Types\n c.execute('''\n CREATE TABLE CoinTypes(\n coinTypeID INTEGER PRIMARY KEY,\n name TEXT,\n nickname TEXT,\n value INTEGER,\n startYear TEXT,\n endYear TEXT,\n image TEXT\n )\n ''')\n\n\n # Transactions Table\n c.execute('''\n\t CREATE TABLE Transactions(\n\t transactionID INTEGER PRIMARY KEY,\n coinID INTEGER,\n buyDate TEXT,\n sellDate TEXT,\n buyPrice REAL,\n sellPrice REAL\n )\n ''')\n\n # Users Table\n c.execute('''\n \t CREATE TABLE Users(\n \t userID INTEGER PRIMARY KEY,\n email TEXT,\n password TEXT,\n firstName TEXT,\n lastName TEXT,\n birthday TEXT,\n joinDate TEXT\n )\n \t''')\n\nexcept sqlite3.Error as e:\n printErr(e)\n\n\ntry:\n # Clears the database tables\n print(\"Clearing tables...\")\n c.execute(\"DELETE FROM Coins WHERE 1\")\n c.execute(\"DELETE FROM CoinTypes WHERE 1\")\n print(\"Tables cleared...\")\n\n\n # Inserts the coin data\n print(\"Inserting data...\")\n query, query2 = initCoinDB()\n c.execute(query)\n c.execute(query2)\n conn.commit()\n print(\"Data inserted successfully.\")\n\n\n # Prints the count of rows in each table\n print(c.execute('''SELECT COUNT(*) FROM Coins''').fetchall())\n print(c.execute('''SELECT COUNT(*) FROM CoinTypes''').fetchall())\nexcept Exception as e:\n printErr(e)\n\n\n# Specify browser path to open URL\n# chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'\n\n# Opens URL\n# webbrowser.get(chrome_path).open(hostName + ':' + str(portNumber), new=2)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/collections', methods = ['POST', 'GET'])\ndef collections():\n # Sets up/connects to DB\n conn = sqlite3.connect('coins.db')\n c = conn.cursor()\n\n if request.method == 'GET':\n return render_template('index.html')\n else:\n\n # Gets the level\n # Level 0 - Value List\n # Level 1 - Type List\n # Level 2 - Coin List\n level = request.json[\"level\"]\n value = request.json[\"value\"]\n nickname = request.json[\"nickname\"]\n\n # print('', file=sys.stderr)\n # print(level, file=sys.stderr)\n # print(value, file=sys.stderr)\n # print(nickname, file=sys.stderr)\n # print('', file=sys.stderr)\n\n if level == 0:\n # Gets data\n c.execute('''\n SELECT value, MIN(startYear), MAX(endYear), image FROM CoinTypes\n GROUP BY value\n ORDER BY value ASC\n ''')\n info = c.fetchall()\n\n # Turns data into a json string\n jsonString = '{\"values\": ['\n for data in info:\n jsonString += '{\"name\": \"\", \"value\": \"' + valueLookupInt(data[0]) + '\", \"years\": \"' + str(data[1]) + ' - ' + str(data[2]) + '\", \"image\": \"' + str(data[3]) + '\"},'\n jsonString = jsonString[:-1] + ']'\n\n jsonString += ',\"header\": \"Value\"'\n jsonString += '}'\n\n return jsonify(jsonString), 202\n\n elif level == 1:\n # Gets data\n query = 'SELECT C.nickname, C.value, MIN(C.year) AS year, MAX(C.year), T.image FROM Coins AS C, CoinTypes AS T ' \\\n 'WHERE C.value=' + str(valueLookupStr(value)) + ' AND T.coinTypeID=C.coinTypeID ' \\\n 'GROUP BY C.name ' \\\n 'ORDER BY year DESC'\n c.execute(query)\n info = c.fetchall()\n\n # Turns data into a json string\n jsonString = '{\"values\": ['\n for data in info:\n jsonString += '{\"name\": \"' + data[0] + '\", \"value\": \"' + valueLookupInt(data[1]) + '\", \"years\": \"' + str(data[2]) + ' - ' + str(data[3]) + '\", \"image\": \"' + str(data[4]) + '\"},'\n jsonString = jsonString[:-1] + ']'\n\n jsonString += ',\"header\": \"' + valueLookupInt(info[0][1]) + '\"'\n jsonString += '}'\n\n return jsonify(jsonString), 202\n elif level == 2:\n # Gets data\n query = 'SELECT C.nickname, C.value, C.year, C.mint, C.note, T.image FROM Coins AS C, CoinTypes AS T ' \\\n 'WHERE C.value=' + str(valueLookupStr(value)) + ' AND T.coinTypeID=C.coinTypeID AND C.nickname=\"' + str(nickname) + '\" ' \\\n 'ORDER BY year DESC'\n c.execute(query)\n info = c.fetchall()\n\n # Turns data into a json string\n jsonString = '{\"values\": ['\n for data in info:\n jsonString += '{\"name\": \"' + data[0] + '\", \"value\": \"' + valueLookupInt(data[1]) + '\", \"years\": \"' + str(data[2]) + ' ' + str(data[3]) + '\", \"note\": \"Notes: ' + str(data[4]) + '\", \"image\": \"' + str(data[5]) + '\"},'\n jsonString = jsonString[:-1] + ']'\n\n jsonString += ',\"header\": \"' + info[0][0] + '\"'\n jsonString += '}'\n\n return jsonify(jsonString), 202\n else:\n return jsonify('{\"message\": \"Invalid level.\"}'), 404\n\n\n\nif __name__ == '__main__':\n # Runs the application\n app.run(host=hostName, port=portNumber)\n","sub_path":"server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":6094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"525408020","text":"#!/usr/bin/env python\n\"\"\"\nLFU.py: A cache which implements the\nleast frequently used algorithm.\n\"\"\"\n\n__author__ = \"Yves Weissig\"\n__email__ = \"weissig@uni-mainz.de\"\n__status__ = \"Development\"\n\nimport random\n\nfrom AbstractCache import AbstractCache\n\n\nclass LFUItem(object):\n \n def __init__(self, param_obj_id, param_atime, param_size):\n \"\"\"\n Inits the item with the passed parameters.\n \"\"\"\n self.obj_id = param_obj_id\n self.atime = param_atime\n self.size = param_size\n \n def __str__(self):\n return \"%s / %s\" % (self.atime, self.size)\n \n def __repr__(self):\n return \"[%s, %s]\" % (self.atime, self.size)\n\n\nclass LFUFrequency(object):\n \n def __init__(self, param_ref_counter):\n \"\"\"\n Inits the frequency with the passed parameters.\n \"\"\"\n self.items = {}\n self.ref_counter = param_ref_counter\n\n\nclass LFUCache(AbstractCache):\n \"\"\"\n Represents a cache which uses the least frequently used algorithm.\n \"\"\"\n \n # A dict which maps obj_id to its frequency\n lut = {}\n \n # A dict full of SimpleLFUFrequency's\n freq = {}\n \n # Size of this cache, in bytes\n cache_size = 10000000000000000000\n \n # The number of used bytes in this cache\n used_size = 0\n \n # A dict which contains all stats\n stats = {}\n \n def __init__(self, param_cache_size, min_obj_size, max_obj_size):\n \"\"\"\n Just some boring boilerplate code to init the cache.\n \"\"\"\n self.freq[0] = LFUFrequency(0)\n self.freq[1] = LFUFrequency(1)\n self.cache_size = param_cache_size\n self.stats[\"cache_size\"] = param_cache_size\n self.stats[\"cache_size_bytes\"] = param_cache_size\n self.stats[\"cache_size_kilobytes\"] = param_cache_size / 1024\n self.stats[\"cache_size_megabytes\"] = param_cache_size / 1024 / 1024\n self.stats[\"cache_size_gigabytes\"] = param_cache_size / 1024 / 1024 / 1024\n self.stats[\"cache_type\"] = \"SimpleLFU\"\n self.stats[\"evicted_objects\"] = 0\n self.stats[\"cached_objects\"] = 0\n self.stats[\"cached_bytes_written\"] = 0\n # Needed for \"backwards\" compability with SimpleBuckets\n self._max_size = param_cache_size\n \n def get_stats(self):\n \"\"\"\n Returns the statistical information.\n \"\"\"\n return self.stats\n \n def get_num_cached_objects(self):\n \"\"\"\n Returns the number of cached objects.\n \"\"\"\n return len(self.lut)\n \n def is_cached(self, obj_id):\n \"\"\"\n Returns if the object with the\n passed obj_id is cached or not.\n \"\"\"\n return obj_id in self.lut\n\n def is_remembered(self, obj_id):\n return self.is_cached(obj_id)\n\n def get_free_cache_bytes(self, size):\n \"\"\"\n Returns the number of free bytes in this cache.\n \"\"\"\n return self.cache_size - self.used_size\n \n def update_obj_size(self, obj_id, size, delta):\n \"\"\"\n Updates the size of an object in the cache.\n \"\"\"\n \n # Sanity checks\n # assert(obj_id in self.lut)\n # assert(obj_id in self.freq[self.lut[obj_id]].items)\n if obj_id not in self.lut:\n # Makes no sense here, but SimpleLRU behaves the same\n #raise Exception(\"Unable to update size of object ('%s') which \"\n #\"is not cached!\" % obj_id)\n return\n if obj_id not in self.freq[self.lut[obj_id]].items:\n raise Exception(\"Internal error during updating size of object \"\n \"('%s'), the lut points to a wrong frequency bucket!\" % obj_id)\n \n # Update size\n self.freq[self.lut[obj_id]].items[obj_id].size = size\n self.used_size += delta\n \n #self.sanity_check(\"update_obj_size\")\n \n def remove_cached(self, obj_id):\n \"\"\"\n Removes an object from the cache, returns the frequency it was\n used and the amount of freed bytes in the cache.\n \"\"\"\n \n # Sanity checks\n # assert(obj_id in self.lut)\n # assert(obj_id in self.freq[self.lut[obj_id]].items)\n if obj_id not in self.lut:\n # raise Exception(\"Unable to remove an object ('%s') which \"\n # \"is not cached!\" % obj_id)\n # This shouldn't raise an exception... because if we evict\n # the object and a second put is issued through the storage system\n # this would lead to an error here, although everything is fine.\n return 0\n if obj_id not in self.freq[self.lut[obj_id]].items:\n raise Exception(\"Internal error during removing the object ('%s'),\"\n \" the lut points to a wrong frequency bucket!\" % obj_id)\n \n # Free bytes and delete object in lut as well as in frequency bucket\n _freq = self.lut[obj_id]\n _size = self.freq[self.lut[obj_id]].items[obj_id].size\n self.used_size -= _size\n del self.freq[self.lut[obj_id]].items[obj_id]\n del self.lut[obj_id]\n \n #self.sanity_check(\"remove_cached\")\n \n return _freq, _size\n \n def cache_object(self, obj_id, size, xtime, force=True):\n \"\"\"\n Caches an object.\n \"\"\"\n \n # Don't cache objects which are too big\n if size > self.cache_size:\n raise Exception(\"Object '%s' is too big for this cache!\" % obj_id)\n \n # Evict objects if needed\n current_freq = 0\n i = 0\n #an_obj_id = None\n while self.used_size + size > self.cache_size:\n if (current_freq not in self.freq or \n self.freq[current_freq] is None or \n self.freq[current_freq].items is None or\n len(self.freq[current_freq].items) == 0):\n current_freq += 1\n else:\n an_obj_id = random.choice(list(self.freq[current_freq].items.keys()))\n if i % 1000 == 0:\n print (\"Warning, evicted %d objects (us: %d, s: %d, cs: %d, freq: %d, an_obj_id: %s, in lut: %s)\" %\n (i, self.used_size, size, self.cache_size, current_freq, an_obj_id, an_obj_id in self.lut))\n self.remove_cached(an_obj_id)\n self.stats[\"evicted_objects\"] += 1\n i += 1\n\n # Dirty, dirty fix... sometimes the object is already present\n if obj_id in self.lut:\n self.remove_cached(obj_id)\n \n # Put the object into the frequency bucket\n self.freq[1].items[obj_id] = LFUItem(obj_id, xtime, size)\n \n # Create a reference to the frequency bucket in the lut\n self.lut[obj_id] = 1\n \n # Set the used size of the cache\n self.used_size += size\n \n # Write statistics\n self.stats[\"cached_objects\"] += 1\n self.stats[\"cached_bytes_written\"] += size\n \n #self.sanity_check(\"cache_object\")\n \n def get_cached(self, obj_id, xtime):\n \"\"\"\n Retrieves an object from the cache.\n \"\"\"\n if obj_id not in self.lut:\n return False\n if obj_id not in self.freq[self.lut[obj_id]].items:\n raise Exception(\"Internal error during retrieving the cached object\"\n \" '%s', the lut points to a wrong frequency bucket!\" % obj_id)\n (_freq, _size) = self.remove_cached(obj_id)\n _freq += 1\n if _freq not in self.freq or self.freq[_freq] is None:\n self.freq[_freq] = LFUFrequency(_freq)\n self.freq[_freq].items[obj_id] = LFUItem(obj_id, xtime, _size)\n self.lut[obj_id] = _freq\n self.used_size += _size\n \n #self.sanity_check(\"get_cached\")\n \n return True\n \n def sanity_check(self, function):\n len_freq_items = 0\n for a_freq in self.freq.itervalues():\n len_freq_items += len(a_freq.items)\n if len(self.lut) != len_freq_items:\n print (\"after function %s: %d != %d\" % (function, len(self.lut), len_freq_items))\n exit(1)\n pass\n \n def debug_print(self):\n \"\"\"\n A debug function used to print the contents of the cache.\n \"\"\"\n print (\"---------\")\n print (\"num_cached_objects: %s\" % self.get_num_cached_objects())\n print (\"get_free_cache_bytes: %s\" % self.get_free_cache_bytes(None))\n for key, value in self.freq.items():\n print (\"Frequency: %s\" % key)\n print (value.items)\n\n def rename(self, from_obj_id, to_obj_id):\n\n if from_obj_id in self.lut:\n old = self.lut.pop(from_obj_id)\n self.lut[to_obj_id] = old\n\n for x, f in self.freq.items():\n if from_obj_id in f.items:\n old = f.items.pop(from_obj_id)\n old.obj_id = to_obj_id\n f.items[to_obj_id] = old\n\n def check_sanity(self):\n return True\n\n# AbstractCache.register(LFUCache)\n \nif __name__ == \"__main__\":\n \n # Replay of a small protocol\n tmp = LFUCache(2 * 1024)\n tmp.debug_print()\n tmp.cache_object(\"a\", 1024, 0)\n tmp.cache_object(\"b\", 512, 0)\n tmp.cache_object(\"c\", 256, 0)\n tmp.debug_print()\n tmp.get_cached(\"a\", 1)\n tmp.get_cached(\"a\", 2)\n tmp.get_cached(\"b\", 3)\n tmp.get_cached(\"a\", 4)\n tmp.get_cached(\"a\", 5)\n tmp.get_cached(\"a\", 6)\n tmp.get_cached(\"b\", 7)\n tmp.debug_print()\n tmp.cache_object(\"d\", 512, 0)\n tmp.debug_print()\n tmp.get_cached(\"d\", 7)\n tmp.get_cached(\"d\", 8)\n tmp.get_cached(\"d\", 9)\n tmp.get_cached(\"d\", 10)\n tmp.debug_print()\n tmp.cache_object(\"e\", 1024, 0)\n tmp.debug_print()","sub_path":"cache-simulator/cache_model_evaluation/LFU.py","file_name":"LFU.py","file_ext":"py","file_size_in_byte":9755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"51598385","text":"from typing import Callable, Union, List\n\nfrom ModelStructure import modelStructure as mS\n# from mip import *\nimport sys\nfrom itertools import combinations\nfrom Istop.AirlineAndFlight import istopAirline as air, istopFlight as modFl\nfrom ModelStructure.Solution import solution\n\nimport numpy as np\nimport pandas as pd\n\nimport time\nimport xpress as xp\n\nxp.controls.outputlog = 0\n\n\nclass Istop(mS.ModelStructure):\n\n @staticmethod\n def index(array, elem):\n for i in range(len(array)):\n if np.array_equiv(array[i], elem):\n return i\n\n def get_couple(self, couple):\n index = 0\n for c in self.couples:\n if couple[0].num == c[0].num and couple[1].num == c[1].num:\n return index\n index += 1\n\n @staticmethod\n def get_tuple(flight):\n j = 0\n indexes = []\n for pair in flight.airline.flight_pairs:\n if flight in pair:\n indexes.append(j)\n j += 1\n return indexes\n\n def get_match_for_flight(self, flight):\n j = 0\n indexes = []\n for match in self.matches:\n for couple in match:\n if flight.num == couple[0].num or flight.num == couple[1].num:\n indexes.append(j)\n j += 1\n return indexes\n\n def __init__(self, df_init, costFun: Union[Callable, List[Callable]], alpha=1, model_name=\"istop\"):\n\n self.preference_function = lambda x, y: x * (y ** alpha)\n self.offers = None\n super().__init__(df_init=df_init, costFun=costFun, airline_ctor=air.IstopAirline)\n airline: air.IstopAirline\n for airline in self.airlines:\n airline.set_preferences(self.preference_function)\n\n self.airlines_pairs = np.array(list(combinations(self.airlines, 2)))\n\n self.epsilon = sys.float_info.min\n self.m = xp.problem()\n\n self.x = None\n self.c = None\n # self.m.threads = -1\n # self.m.verbose = 0\n\n self.matches = []\n self.couples = []\n self.flights_in_matches = []\n\n # self.initial_objective_value = sum([self.score(flight, flight.slot) for flight in self.flights])\n\n def check_and_set_matches(self):\n for airl_pair in self.airlines_pairs:\n fl_pair_a = airl_pair[0].flight_pairs\n fl_pair_b = airl_pair[1].flight_pairs\n for pairA in fl_pair_a:\n for pairB in fl_pair_b:\n if self.condition(pairA, pairB):\n self.matches.append([pairA, pairB])\n\n for match in self.matches:\n for couple in match:\n if not self.is_in(couple, self.couples):\n self.couples.append(couple)\n if not self.f_in_matched(couple[0]):\n self.flights_in_matches.append(couple[0])\n if not self.f_in_matched(couple[1]):\n self.flights_in_matches.append(couple[1])\n\n print(\"preprocess concluded. number of couples: ******* \", len(self.matches))\n return len(self.matches) > 0\n\n def set_variables(self):\n self.x = np.array([[xp.var(vartype=xp.binary) for j in self.slots] for i in self.slots])\n\n self.c = np.array([xp.var(vartype=xp.binary) for i in self.matches])\n # print(self.x.shape)\n print(self.c.shape)\n self.m.addVariable(self.x, self.c)\n\n def set_constraints(self):\n for i in self.emptySlots:\n for j in self.slots:\n self.m.addConstraint(self.x[i, j] == 0)\n\n for flight in self.flights:\n if not self.f_in_matched(flight):\n self.m.addConstraint(self.x[flight.slot.index, flight.slot.index] == 1)\n else:\n self.m.addConstraint(xp.Sum(self.x[flight.slot.index, j.index] for j in flight.compatibleSlots) == 1)\n\n for j in self.slots:\n self.m.addConstraint(xp.Sum(self.x[i.index, j.index] for i in self.slots) <= 1)\n\n for flight in self.flights:\n for j in flight.notCompatibleSlots:\n self.m.addConstraint(self.x[flight.slot.index, j.index] == 0)\n\n for flight in self.flights_in_matches:\n self.m.addConstraint(xp.Sum(self.x[flight.slot.index, slot_to_swap.index] for slot_to_swap in\n [s for s in self.slots if s != flight.slot]) \\\n == xp.Sum([self.c[j] for j in self.get_match_for_flight(flight)]))\n\n for flight in self.flights:\n for other_flight in flight.airline.flights:\n if flight != other_flight:\n self.m.addConstraint(self.x[flight.slot.index, other_flight.slot.index] == 0)\n\n k = 0\n for match in self.matches:\n pairA = match[0]\n pairB = match[1]\n\n self.m.addConstraint(xp.Sum(self.x[i.slot.index, j.slot.index] for i in pairA for j in pairB) + \\\n xp.Sum(self.x[i.slot.index, j.slot.index] for i in pairB for j in pairA) >= \\\n (self.c[k]) * 4)\n\n self.m.addConstraint(\n xp.Sum(self.x[i.slot.index, j.slot.index] * i.costFun(i, j.slot) for i in pairA for j in pairB) - \\\n (1 - self.c[k]) * 100000 \\\n <= xp.Sum(self.x[i.slot.index, j.slot.index] * i.costFun(i, i.slot) for i in pairA for j in pairB) - \\\n self.epsilon)\n\n self.m.addConstraint(\n xp.Sum(self.x[i.slot.index, j.slot.index] * i.costFun(i, j.slot) for i in pairB for j in pairA) - \\\n (1 - self.c[k]) * 100000 \\\n <= xp.Sum(self.x[i.slot.index, j.slot.index] * i.costFun(i, i.slot) for i in pairB for j in pairA) - \\\n self.epsilon)\n\n k += 1\n\n def set_objective(self):\n\n self.m.setObjective(\n xp.Sum(self.x[flight.slot.index, j.index] * self.score(flight, j)\n for flight in self.flights for j in self.slots), sense=xp.minimize)\n\n def run(self, timing=False):\n print(\"start\")\n feasible = self.check_and_set_matches()\n print(\"end\", len(self.matches))\n if feasible:\n self.set_variables()\n\n start = time.time()\n self.set_constraints()\n end = time.time() - start\n if timing:\n print(\"Constraints setting time \", end)\n\n self.set_objective()\n\n start = time.time()\n self.m.solve()\n end = time.time() - start\n if timing:\n print(\"Simplex time \", end)\n\n # print(\"status: \", self.m.getProbStatus())\n print(\"problem status, explained: \", self.m.getProbStatusString())\n xpSolution = self.x\n # print(self.m.getSolution(self.x))\n self.assign_flights(xpSolution)\n\n else:\n self.assign_flights([flight.slot for flight in self.flights])\n\n solution.make_solution(self)\n\n self.offer_solution_maker()\n\n # for i in self.slots:\n # if self.x[i, i].x == 0:\n # for j in self.slots:\n # if self.x[i, j].x != 0:\n # print(i, j)\n\n for flight in self.flights:\n if flight.eta > flight.newSlot.time:\n print(\"********************** danno *********************************\",\n flight, flight.eta, flight.newSlot.time)\n\n offers = 0\n for i in range(len(self.matches)):\n if self.m.getSolution(self.c[i]) > 0.5:\n # print(self.matches[i])\n offers += 1\n print(\"offers: \", offers)\n\n def other_airlines_compatible_slots(self, flight):\n others_slots = []\n for airline in self.airlines:\n if airline != flight.airline:\n others_slots.extend(airline.AUslots)\n return np.intersect1d(others_slots, flight.compatibleSlots, assume_unique=True)\n\n def score(self, flight, slot):\n return (flight.preference * flight.delay(slot) ** 2) / 2\n\n def offer_solution_maker(self):\n\n flight: modFl.IstopFlight\n airline_names = [\"total\"] + [airline.name for airline in self.airlines]\n flights_numbers = [self.numFlights] + [len(airline.flights) for airline in self.airlines]\n offers = [sum([1 for flight in self.flights if flight.slot != flight.newSlot]) / 4]\n for airline in self.airlines:\n offers.append(sum([1 for flight in airline.flights if flight.slot != flight.newSlot]) / 2)\n\n offers = np.array(offers).astype(int)\n self.offers = pd.DataFrame({\"airline\": airline_names, \"flights\": flights_numbers, \"offers\": offers})\n self.offers.sort_values(by=\"flights\", inplace=True, ascending=False)\n\n def condition(self, pairA, pairB):\n\n A0 = pairA[0]\n A1 = pairA[1]\n B0 = pairB[0]\n B1 = pairB[1]\n\n initial_costA = A0.costFun(A0, A0.slot) + A1.costFun(A1, A1.slot)\n initial_costB = B0.costFun(B0, B0.slot) + B1.costFun(B1, B1.slot)\n\n offA1 = initial_costA - A0.costFun(A0, B0.slot) - A1.costFun(A1, B1.slot)\n offA2 = initial_costA - A0.costFun(A0, B1.slot) - A1.costFun(A1, B0.slot)\n offB1 = initial_costB - B0.costFun(B0, A0.slot) - B1.costFun(B1, A1.slot)\n offB2 = initial_costB - B0.costFun(B0, A1.slot) - B1.costFun(B1, A0.slot)\n\n if offA1 > 0 and offB1 > 0 and A0.etaSlot <= B0.slot and B0.etaSlot <= A0.slot and \\\n A1.etaSlot <= B1.slot and B1.etaSlot <= A1.slot:\n # print(A0, A0.slot, \"<->\", B0.slot, B0)\n # print(A1, A1.slot, \"<->\", B1.slot, B1)\n # print(A0, self.delays[A0.num, A0.slot], self.delays[A0.num, B0.slot])\n # print(B0, self.delays[B0.num, B0.slot], self.delays[B0.num, A0.slot])\n # print(A1, self.delays[A1.num, A1.slot], self.delays[A1.num, B1.slot])\n # print(B1, self.delays[B1.num, B1.slot], self.delays[B1.num, A1.slot])\n # print(offA1, offB1, \"\\n\")\n return True\n\n if offA2 > 0 and offB2 > 0 and A0.etaSlot <= B1.slot and B1.etaSlot <= A0.slot and \\\n A1.etaSlot <= B0.slot and B0.etaSlot <= A1.slot:\n # print(A0, A0.slot, \"<->\", B1.slot, B1)\n # print(A1, A1.slot, \"<->\", B0.slot, B0)\n # print(A0, self.delays[A0.num, A0.slot], self.delays[A0.num, B1.slot])\n # print(B0, self.delays[B0.num, B0.slot], self.delays[B0.num, A1.slot])\n # print(A1, self.delays[A1.num, A1.slot], self.delays[A1.num, B0.slot])\n # print(B1, self.delays[B1.num, B1.slot], self.delays[B1.num, A0.slot])\n # print(offA2, offB2, \"\\n\")\n return True\n\n if offA1 > 0 and offB2 > 0 and A0.etaSlot <= B0.slot and B0.etaSlot <= A1.slot and \\\n A1.etaSlot <= B1.slot and B1.etaSlot <= A0.slot:\n # print(A0, A0.slot, \"->\", B0.slot, B0, \"->\", A1, A1.slot, \"->\", B1.slot, B1)\n # print(A0, self.delays[A0.num, A0.slot], self.delays[A0.num, B0.slot])\n # print(B0, self.delays[B0.num, B0.slot], self.delays[B0.num, A1.slot])\n # print(A1, self.delays[A1.num, A1.slot], self.delays[A1.num, B1.slot])\n # print(B1, self.delays[B1.num, B1.slot], self.delays[B1.num, A0.slot])\n # print(offA1, offB2, \"\\n\")\n return True\n\n if offA2 > 0 and offB1 > 0 and A0.etaSlot <= B1.slot and B1.etaSlot <= A0.slot and \\\n A1.etaSlot <= B0.slot and B0.etaSlot <= A1.slot:\n # print(A0, A0.slot, \"<->\", B1.slot, B1, \"->\", A1, A1.slot, \"->\", B0.slot, B0)\n # print(A0, self.delays[A0.num, A0.slot], self.delays[A0.num, B1.slot])\n # print(B0, self.delays[B0.num, B0.slot], self.delays[B0.num, A0.slot])\n # print(A1, self.delays[A1.num, A1.slot], self.delays[A1.num, B0.slot])\n # print(B1, self.delays[B1.num, B1.slot], self.delays[B1.num, A1.slot])\n # print(offA2, offB1, \"\\n\")\n return True\n\n return False\n\n @staticmethod\n def is_in(couple, couples):\n for c in couples:\n if couple[0].num == c[0].num and couple[1].num == c[1].num:\n return True\n if couple[1].num == c[0].num and couple[0].num == c[1].num:\n return True\n return False\n\n def f_in_matched(self, flight):\n for f in self.flights_in_matches:\n if f.num == flight.num:\n return True\n return False\n\n def assign_flights(self, xpSolution):\n for flight in self.flights:\n for slot in self.slots:\n if self.m.getSolution(xpSolution[flight.slot.index, slot.index]) > .5:\n flight.newSlot = slot\n # print(flight, flight.slot, flight.newSlot)\n\n # def find_match(self, i):\n # for j in self.slotIndexes[self.slotIndexes != i]:\n # if self.xpSolution[i.slot, j] == 1:\n # return self.flights[j]\n","sub_path":"Istop/istop_old.py","file_name":"istop_old.py","file_ext":"py","file_size_in_byte":13043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"570286901","text":"# project/server/admin/views.py\n\n\n#################\n#### imports ####\n#################\n\nfrom flask import render_template, Blueprint, url_for, \\\n redirect, flash, request\nfrom project.server.models import Language\nfrom project.server import app, db\nfrom project.server.admin.forms import LanguageForm\n\n################\n#### config ####\n################\n\nadmin_blueprint = Blueprint('admin', __name__,)\n\n\n################\n#### routes ####\n################\n\n@admin_blueprint.route('/language', methods=['GET', 'POST'])\ndef language():\n form = LanguageForm(request.form)\n if form.validate_on_submit():\n lang = Language(\n language_code=form.language_code.data,\n description=form.description.data\n )\n db.session.add(lang)\n db.session.commit()\n\n flash('Thank you for adding language.', 'success')\n return redirect(url_for(\"admin.language\"))\n\n return render_template('admin/language.html', form=form)\n","sub_path":"project/server/admin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"379924710","text":"\"\"\"test_office.\"\"\"\nfrom os import path\nimport sys\n\nimport unittest\n\nsys.path.append(path.dirname(path.dirname(path.abspath(__file__))))\nfrom app.dojo import Dojo\nfrom io import StringIO\n\n\nclass officeTest(unittest.TestCase):\n \"\"\"\n This is test class for Office class.\n\n It contains tests for successful creation\n and allocation of `office` space\n \"\"\"\n\n def setUp(self):\n self.dojo_instance = Dojo()\n\n def test_create_office_successfully(self):\n \"\"\"Test to check successful creation of office.\"\"\"\n initial_length = len(self.dojo_instance.offices_list)\n new_office = self.dojo_instance.create_room('office', 'Green')\n new_length = len(self.dojo_instance.offices_list)\n difference = new_length - initial_length\n self.assertEqual(difference, 1)\n self.assertEqual('Office called Green has been successfully created!\\n',\n new_office)\n\n def test_add_person_and_allocate_office(self):\n \"\"\"Test allocation of office space to a person.\"\"\"\n self.dojo_instance.create_room('office', 'Green')\n new_person = self.dojo_instance.add_person('Lucy', 'Kimani',\n 'Staff', '')\n self.assertIn(\"Lucy has been allocated the office Green\", new_person)\n\n def tearDown(self):\n del self.dojo_instance\n","sub_path":"tests/test_office.py","file_name":"test_office.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"488242927","text":"# sweetscomplete.entity.common.Common test\n\n# tell python where to find module source code\nimport os,sys\nimport os,sys\nsys.path.append(os.path.realpath(\"/repo/chapters/07/src\"))\n\nfrom sweetscomplete.entity.common import Common\n\n# Testing Common\njsonDoc = '{\"key\":\"gender\",\"data\":{\"M\":\"male\",\"F\":\"female\",\"O\":\"Other\"}}'\ncommon = Common(jsonDoc)\n\n# Output\nprint(\"\\nObject\\n\")\nprint(vars(common))\n\nprint(\"\\nJSON\\n\")\nprint(common.toJson())\n","sub_path":"chapters/07/test_book_someplace_common_entity.py","file_name":"test_book_someplace_common_entity.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"286357629","text":"import random\nfrom usuario import Usuario\nfrom computer import Computer\n\ndef main():\n intento = 0\n menu = 0\n opcion = \"\"\n while menu == 0:\n opcion = \"\"\n opcion = input(\"\\nSi quiere adivinar el numero de la maquina ingrese 1, si quiere que la maquina adivine su numero ingrese 2: \")\n if opcion != \"1\" and opcion != \"2\":\n print(\"\\nDebe ingresar '1' o '2'!\")\n ########## Opcion 1 ########## \n elif opcion == \"1\":\n intento = \"\"\n juego = Usuario()\n #print(juego.respuesta)\n while juego.is_playing:\n intento = input(\"intento: \")\n juego.play(intento)\n print(f\"Ganaste en {juego.turno} intentos\")\n menu = 1\n ########## Opcion 2 ########## \n elif opcion == \"2\":\n num = input(\"\\nElija un numero: \")\n juego = Computer()\n while juego.is_playing:\n bien = regular = 0\n intento = intento + 1\n print(\"Recuerde que su numero es: \",num)\n juego.play()\n if juego.error:\n juego.is_playing = False\n while juego.loop_general:\n while juego.loop_bien:\n bien = input(\"Bien?:\\n\")\n juego.verificador(bien, 1)\n while juego.loop_regular: \n regular = input(\"Regular?:\\n\")\n juego.verificador(regular, 2)\n if juego.check_bienregular():\n juego.check()\n print(f\"Termino en {intento} intentos\")\n menu = 1\n\n\n # Error al elegir opción \n else:\n print(\"\\nSurgio un error en la eleccion de opciones\")\n\nmain()","sub_path":"Practicas/juego final/juego.py","file_name":"juego.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"570620693","text":"#!/usr/bin/python3\n#*************************************************************************\n#\n# Program: encoder\n# File: encoder.py\n#\n# Version: V1.0\n# Date: 18.05.21\n# Function: Encodes residues in a csv file\n# given encoding type \n#\n# Author: Ayub Hareed\n# \n# EMail: ayubm56@gmail.com\n#\n\n#\n#*************************************************************************\n#\n# Description:\n# ============\n#\n#*************************************************************************\n#\n# Usage:\n# ======\n#\n#*************************************************************************\n#\n# Revision History:\n# =================\n# V1.0 18.05.21 Original By: Ayub Hareed\n# V2.0 10.06.21 By: Ayub Hareed\n#*************************************************************************\n\n# import libraries \nimport sys\nimport utilities\nimport string\nimport os \n#*************************************************************************\n# function reads in the file\ndef read_csv_file(filename):\n with open(filename, 'r') as f:\n # read in the file and remove \\n\n file_raw = f.read().splitlines()\n csv_file = []\n # splits line by comma\n for line in file_raw:\n if ('#' not in line):\n lst = line.split(',')\n csv_file.append(lst)\n return (csv_file)\n#*************************************************************************\ndef csv_header(num, window, pro_lst, sec_title):\n \"\"\"\n input: num (intiger) - to show how many ### the encoder has\n window (intiger) - \n returns: string that contains the encoder header \n \"\"\"\n # imports the alphabet to use it on the \n # prefix of header\n letters = string.ascii_lowercase\n # since window equal sequnce size of either \n # N-terminal or C-terminal\n\n\n window = window * 2\n result = ''\n \n # if another encoder is used ontop of the general encoders\n if (len(pro_lst) > 0):\n lst = pro_lst[2] # get a line of the csv file\n \n encoded_sz = len(lst[3:])\n\n # the loop is used to make the header \n for prefix in range(0,window):\n for suffix in range(1,(num + 1)):\n result += ',' + letters[prefix] + str(suffix)\n \n # append the second encoder to the csv header\n if (encoded_sz > window):\n # result += ',sec1,sec2'\n # result += ',a_sec1,a_sec2,b_sec1,b_sec2,c_sec1,c_sec2,d_sec1,d_sec2,e_sec1,e_sec2,f_sec1,f_sec2,g_sec1,g_sec2,h_sec1,h_sec2,i_sec1,i_sec2' #,j_sec1,j_sec2,k_sec1,k_sec2'\n result += sec_title\n return (result)\n\n#*************************************************************************\ndef amino_acid_encoder(proline_csv, encoder):\n \"\"\"\n input: proline_csv (list of strings) - contains proline torsion csv output\n return: converts amino acid one letter code to encoder\n \"\"\"\n result = '' # used to concatinate the csv columns \n for line in proline_csv:\n \n # if statement ignores blank lines\n if len(line) > 1:\n\n \n # encode one letter amino acid \n if ('*' in line[-1]):\n sec_encode = utilities.Encode('../encoder_data/SecondaryStructure.txt', 'sec')\n sec_dict = sec_encode.get_encode_dict()\n line_test = line[-1].replace('*','')\n if line_test in sec_dict.keys():\n \n # add the pdb name, atom number and torsion angle type\n result += line[0] + ',' + line[1] + ',' + line[2] + ',' \n \n for i, item in enumerate(line):\n \n # to insure that the line doesn't end with a comma\n sec_encode = utilities.Encode('../encoder_data/SecondaryStructure.txt', 'sec')\n\n sec_dict = sec_encode.get_encode_dict()\n if (i > 2 and i < (len(line) - 1)):\n if (item in encoder.keys() and '*' not in item): # checks if the correct amino acid is entered\n\n encoded_amino_acid = encoder[item]\n result += str(encoded_amino_acid) + ','\n\n if ('*' in item):\n item = item.replace('*', '')\n if (item in sec_dict.keys()):\n encoded_amino_acid = sec_dict[item]\n result += str(encoded_amino_acid) + ','\n\n\n # last term\n elif (i > 2 and i == (len(line) - 1)):\n # checks if the correct amino acid is entered\n item = item.replace('*', '')\n sec_encode = utilities.Encode('../encoder_data/SecondaryStructure.txt', 'sec')\n sec_dict = sec_encode.get_encode_dict()\n if (item in sec_dict.keys()):\n encoded_amino_acid = sec_dict[item]\n result += str(encoded_amino_acid) + '\\n'\n else:\n no_sec = f'this secondary structure not found: {item}'\n with open('/home/ayub/Desktop/cis_proline/pisces/test/cathe_encode.out', 'a') as f:\n f.write(f'{no_sec}\\n')\n continue\n \n else:\n\n # add the pdb name, atom number and torsion angle type\n result += line[0] + ',' + line[1] + ',' + line[2] + ','\n \n for i, item in enumerate(line):\n\n # to insure that the line doesn't end with a comma\n if (i > 2 and i < (len(line) - 1)):\n if (item in encoder.keys()): # checks if the correct amino acid is entered\n\n encoded_amino_acid = encoder[item]\n result += str(encoded_amino_acid) + ','\n # last term\n elif (i > 2 and i == (len(line) - 1)):\n if (item in encoder.keys()): # checks if the correct amino acid is entered\n encoded_amino_acid = encoder[item]\n result += str(encoded_amino_acid) + '\\n'\n return (result)\n\n\n\n# ------------------------------------------------------------------------\n# Main program\n# ------------------------------------------------------------------------\nwindow = 3\nsec_title = sys.argv[3]\n\nif(len(sys.argv) > 4):\n window = int(sys.argv[4])\n# if ('-s' in sys.argv):\n# i = sys.argv.index('-s')\n# sec_encode = sys.argv[i]\n# else:\n# sec = None\n\n# using blosum45 as encoder\nif(sys.argv[1] == '-b45'):\n blosum45 = utilities.Encode('../encoder_data/BLOSUM45', 'blosum45')\n encoder = blosum45.get_encode_dict()\n proline_csv_file = sys.argv[2]\n proline_csv = read_csv_file(proline_csv_file)\n header = csv_header(20, window, proline_csv, sec_title)\n print('pdb,atom num,type{}'.format(header)) \n print(amino_acid_encoder(proline_csv, encoder))\n\n# using blosum62 as encoder\nif(sys.argv[1] == '-b62'):\n blosum62 = utilities.Encode('../encoder_data/BLOSUM62', 'blosum62')\n encoder = blosum62.get_encode_dict()\n proline_csv_file = sys.argv[2]\n proline_csv = read_csv_file(proline_csv_file)\n header = csv_header(20, window, proline_csv, sec_title)\n print('pdb,atom num,type{}'.format(header))\n print(amino_acid_encoder(proline_csv, encoder))\n\n# using blosum80 as encoder\nif(sys.argv[1] == '-b80'):\n blosum80 = utilities.Encode('../encoder_data/BLOSUM80', 'blosum80')\n encoder = blosum80.get_encode_dict()\n proline_csv_file = sys.argv[2]\n proline_csv = read_csv_file(proline_csv_file)\n header = csv_header(20, window, proline_csv, sec_title)\n print('pdb,atom num,type{}'.format(header))\n print(amino_acid_encoder(proline_csv, encoder))\n\n# using blosum90 as encoder\nif(sys.argv[1] == '-b90'):\n blosum90 = utilities.Encode('../encoder_data/BLOSUM90', 'blosum90')\n encoder = blosum90.get_encode_dict()\n proline_csv_file = sys.argv[2]\n proline_csv = read_csv_file(proline_csv_file)\n header = csv_header(20, window, proline_csv, sec_title)\n print('pdb,atom num,type{}'.format(header))\n print(amino_acid_encoder(proline_csv, encoder))\n\n\nif(sys.argv[1] == '-t5'):\n tscale5 = utilities.Encode('../encoder_data/TScale5.txt', 'tscale5')\n encoder = tscale5.get_encode_dict()\n proline_csv_file = sys.argv[2]\n proline_csv = read_csv_file(proline_csv_file)\n header = csv_header(5, window, proline_csv, sec_title)\n print('pdb,atom num,type{}'.format(header))\n print(amino_acid_encoder(proline_csv, encoder))\n\n\nif(sys.argv[1] == '-a4'):\n abhinandan4 = utilities.Encode('../encoder_data/Abhinandan4.txt', 'abhinandan4') \n encoder = abhinandan4.get_encode_dict()\n proline_csv_file = sys.argv[2]\n proline_csv = read_csv_file(proline_csv_file)\n header = csv_header(4, window, proline_csv, sec_title)\n print('pdb,atom num,type{}'.format(header))\n print(amino_acid_encoder(proline_csv, encoder))\n\nif (sys.argv[1] == '-pseudo'):\n tscale5 = utilities.Encode('../encoder_data/New_TScale5.txt', 'tscale5')\n encoder = tscale5.get_encode_dict()\n proline_csv_file = sys.argv[2]\n proline_csv = read_csv_file(proline_csv_file)\n header = csv_header(7, window, proline_csv, sec_title)\n print('pdb,atom num,type{}'.format(header))\n print(amino_acid_encoder(proline_csv, encoder))\n\nif (sys.argv[1] == '-ant'):\n tscale5 = utilities.Encode('../encoder_data/A4_with_TScale5.txt', 'tscale5')\n encoder = tscale5.get_encode_dict()\n proline_csv_file = sys.argv[2]\n proline_csv = read_csv_file(proline_csv_file)\n header = csv_header(9, window, proline_csv, sec_title)\n print('pdb,atom num,type{}'.format(header))\n print(amino_acid_encoder(proline_csv, encoder))\n\nif (sys.argv[1] == '-and'):\n blosum90 = utilities.Encode('../encoder_data/BLOSUM90_a4', 'a4nb90')\n encoder = blosum90.get_encode_dict()\n proline_csv_file = sys.argv[2]\n proline_csv = read_csv_file(proline_csv_file)\n header = csv_header(24, window, proline_csv, sec_title)\n print('pdb,atom num,type{}'.format(header))\n print(amino_acid_encoder(proline_csv, encoder))\n\n\n#*************************************************************************\n# first function handles argv arguments and error inputs from the \n# command line along with the help (-h) input\n# ../encoder_data/A4_with_TScale5.txt\n\n#*************************************************************************\n\n","sub_path":"scripts/encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":10720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"248076933","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nclass Solution:\n def reverseWords(self, s: str) -> str:\n s = s.strip(\" \")\n left = right = len(s) - 1\n res = []\n while left >= 0:\n while left >= 0 and s[left] != \" \": left -= 1\n res.append(s[left + 1:right + 1])\n while s[left] == \" \": left -= 1\n right = left\n return res\n\n\nif __name__ == '__main__':\n words = \" hello world \"\n s = Solution()\n res = s.reverseWords(words)\n print(res)\n","sub_path":"algorithm/sword/剑指 Offer 58 - I. 翻转单词顺序.py","file_name":"剑指 Offer 58 - I. 翻转单词顺序.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"497074441","text":"\nimport os, sys\nimport numpy as np\nimport torch\nimport six\nimport json\nimport random\nimport time\nfrom collections import defaultdict\nfrom torch.utils.data import Dataset, DataLoader\nfrom utils import *\nfrom itertools import combinations \n\n\nclass Trainer:\n \n def __iter__(self, *args, **kargs):\n return self.train.__iter__(*args, **kargs)\n \n @must_override\n def evaluate_model(self):\n pass\n \n \n @warn_not_override\n def _evaluate_during_train(self, model=None, trainer_target=None, args=None):\n pass\n \n def train_model(self, model=None, trainer_target=None, args=None):\n \n if model is None:\n model = self.model\n \n if args is None:\n raise Exception('require args')\n \n trainer_source = self\n if trainer_target is None:\n trainer_target = self\n \n losses = []\n times = []\n decay_rate = args.decay_rate\n learning_rate = args.lr\n for i_epoch in range(args.max_epoches):\n\n global_steps = int(model.global_steps.data)\n\n if global_steps > args.max_steps:\n print(f\"reach max_steps, stop training\")\n break\n\n tic = time.time()\n for i, batch in enumerate(trainer_source):\n loss = model.train_step(batch)['loss'].detach().cpu().numpy()\n losses.append(loss)\n toc = time.time()\n times.append(toc - tic)\n\n global_steps = int(model.global_steps.data)\n if global_steps % 100 == 0:\n print(f\"g_step {global_steps}, step {i+1}, \"\n f\"avg_time {sum(times)/len(times):.3f}, \"\n f\"loss:{sum(losses)/len(losses):.4f}\")\n losses = []\n times = []\n\n tic = time.time()\n\n if global_steps % 1000 == 0:\n _lr = learning_rate/(1+decay_rate*global_steps/1000)\n print(f\"learning rate was adjusted to {_lr}\")\n adjust_learning_rate(model.optimizer, lr=_lr)\n\n if global_steps % args.evaluate_interval == 0:\n self._evaluate_during_train(model=model, trainer_target=trainer_target, args=args)\n\n if global_steps == args.max_steps:\n break","sub_path":"data/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"412170129","text":"'''\r\nPLUS MINUS PROBLEM:\r\n\r\nGiven an array of integers, calculate the ratios of its elements that are positive, negative, and zero. Print the decimal value of each fraction on a new line with 6 places after the decimal.\r\n\r\nNote: This challenge introduces precision problems. The test cases are scaled to six decimal places, though answers with absolute error of up to 10^(-4) are acceptable.\r\n\r\nExample\r\n arr=[1,1,0,-1,-1]\r\n\r\nThere are n=5 elements, two positive, two negative and one zero. Their ratios are 2/5=0.400000,2/5=0.400000 and 1/5=0.200000.\r\nResults are printed as:\r\n\r\n0.400000\r\n0.400000\r\n0.200000\r\n\r\nFunction Description\r\n\r\nComplete the plusMinus function in the editor below.\r\n\r\nplusMinus has the following parameter(s):\r\n\r\nint arr[n]: an array of integers\r\nPrint\r\nPrint the ratios of positive, negative and zero values in the array. Each value should be printed on a separate line with 6 digits after the decimal. The function should not return a value.\r\n\r\nInput Format\r\n\r\nThe first line contains an integer,n, the size of the array.\r\nThe second line contains space-separated integers that describe arr[n].\r\n\r\nConstraints\r\n00):\r\n d+=1\r\n else:\r\n e+=1\r\n print (\"{0:.6f}\".format(d/n))\r\n print (\"{0:.6f}\".format(e/n))\r\n print (\"{0:.6f}\".format(c/n))\r\n \r\n\r\nif __name__ == '__main__':\r\n n = int(input().strip())\r\n\r\n arr = list(map(int, input().rstrip().split()))\r\n\r\n plusMinus(arr)\r\n","sub_path":"plus_minus.py","file_name":"plus_minus.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"76286046","text":"# load packages\nimport sys\nimport pandas as pd\nfrom sqlalchemy import create_engine\nimport re\nimport nltk\nnltk.download('punkt')\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nnltk.download('words')\nnltk.download('stopwords')\nnltk.download('wordnet')\nenglishwords=set(nltk.corpus.words.words())\nfrom nltk.stem.wordnet import WordNetLemmatizer\nfrom sklearn.pipeline import Pipeline, FeatureUnion\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.multioutput import MultiOutputClassifier\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.metrics import classification_report, accuracy_score\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.metrics import precision_recall_fscore_support as score\nimport pickle\n\n\ndef load_data(database_filepath):\n\t\"\"\"\n\tload the sql data and extract the input value and target values\n\t\n\tinput: database_filepath - the filepath that contains the cleaned sql datafile\n\toutput: X - the training data set, input values\n\t\t\tY - the training data set, target values\n\t\t\tcategory_names - the name of each target, this will be used to display the evluation result of each target\n\t\"\"\"\n\tengine = create_engine('sqlite:///' + database_filepath)\n\tdf=pd.read_sql_table('DisaterResponse', engine)\n\tX = df[\"message\"]\n\tY = df.iloc[:,4:]\n\tcategory_names = list(Y.columns)\n\treturn X,Y,category_names\n\n\ndef tokenize(text):\n\t\"\"\"\n\ttonkenize a text string, convert it to lower case, remove punctutation and root individual words\n\t\n\tinput: text - a text string\n\toutput: words - tokenized text string. a list that contains several individual words strings\n\t\"\"\"\n\ttext = text.lower()\n\ttext = re.sub(r\"[^a-zA-Z0-9]\", \" \", text)\n\twords = word_tokenize(text)\n\twords=[x for x in words if x in englishwords and x not in stopwords.words(\"english\")] #remove stop words and non-english words(just in case)\n\twordnet_lemmatizer=WordNetLemmatizer()\n\twords = [wordnet_lemmatizer.lemmatize(w, pos='v') for w in words] # root verb words\n\twords = [wordnet_lemmatizer.lemmatize(w, pos='n') for w in words] # root noun words\n\twords = [wordnet_lemmatizer.lemmatize(w, pos='a') for w in words] # root adj words\n\twords = [wordnet_lemmatizer.lemmatize(w, pos='v') for w in words] # root adv words\n\treturn words\n \n\n\ndef build_model():\n\t\"\"\"\n\tcreate a ML pipeine that contains countvectorizer, tfidftransformer and randomforestclassifier\n\tinput: None\n\tOutput: ML pipeline\n\t\"\"\"\n\tpipeline = Pipeline([\n\t\t\t\t\t\t('vect', CountVectorizer(tokenizer=tokenize)),\n\t\t\t\t\t\t('tfidf', TfidfTransformer()),\n\t\t\t\t\t\t('clf', MultiOutputClassifier(RandomForestClassifier(n_estimators=200,min_samples_split=6,criterion='gini'))), # create a randomforesetclassifier\n\t\t\t\t\t\t])\n \n\treturn pipeline\n\n\ndef evaluate_model(model, X_test, Y_test, category_names):\n\t\"\"\"\n\tevaluate the modeling results and display the accuracy score of each target category\n\tinput: model - the model for evaluation\n\t\t X_test - input values of testing data\n\t\t Y_test - target values of testing data\n\t\t category_names - a list that contains the names of each target category\n\toutput: none\n\t\"\"\"\n\ty_pred=model.predict(X_test)\n\tcol_names=Y_test.columns\n\tfor i in range(len(col_names)):\n\t\tprecision,recall,fscore,support=score(Y_test.iloc[:, i].values,y_pred[:, i],average='weighted')\n\t\tprint(\"Category:\", col_names[i],\"\\n\")\n\t\tprint('Precision of %s: %.2f \\n' %(col_names[i], precision))\n\t\tprint('Recall of %s: %.2f \\n' %(col_names[i], recall))\n\t\tprint('F1score of %s: %.2f \\n' %(col_names[i], fscore))\n\t\tprint('Accuracy of %s: %.2f \\n\\n' %(col_names[i], accuracy_score(Y_test.iloc[:, i].values, y_pred[:,i])))\n\tpass\n\n\ndef save_model(model, model_filepath):\n\t\"\"\"\n\tsave the trained model using pickle\n\tinput: model - the trained model\n\t\t model_filepath - the filepath to store the model\n\t\"\"\"\n\tpickle.dump(model, open(model_filepath, \"wb\"))\n\tpass\n\n\ndef main():\n\t\"\"\"\n\tpython models/train_classifier.py data/DisasterResponse.db models/classifier.pkl\n\t\"\"\"\n\tif len(sys.argv) == 3:\n\t\tdatabase_filepath, model_filepath = sys.argv[1:]\n\t\tprint('Loading data...\\n DATABASE: {}'.format(database_filepath))\n\t\tX, Y, category_names = load_data(database_filepath)\n\t\tX_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2) #splite the training and testing data\n \n\t\tprint('Building model...')\n\t\tmodel = build_model()\n \n\t\tprint('Training model...')\n\t\tmodel.fit(X_train, Y_train)\n \n\t\tprint('Evaluating model...')\n\t\tevaluate_model(model, X_test, Y_test, category_names)\n\n\t\tprint('Saving model...\\n MODEL: {}'.format(model_filepath))\n\t\tsave_model(model, model_filepath)\n\n\t\tprint('Trained model saved!')\n\n\telse:\n\t\tprint('Please provide the filepath of the disaster messages database '\\\n\t\t\t\t'as the first argument and the filepath of the pickle file to '\\\n\t\t\t\t'save the model to as the second argument. \\n\\nExample: python '\\\n\t\t\t\t'train_classifier.py ../data/DisasterResponse.db classifier.pkl')\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"P2/models/train_classifier.py","file_name":"train_classifier.py","file_ext":"py","file_size_in_byte":5078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"440364539","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 ('edition', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='edition',\n options={'ordering': ['name_edition'], 'managed': False, 'verbose_name_plural': 'editions'},\n ),\n ]\n","sub_path":"edition/migrations/0002_auto_20151030_1302.py","file_name":"0002_auto_20151030_1302.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"300937976","text":"'''\np.96 숫자 카드 게임\nn x m 행렬로 놓여있는 카드, 각 행마다 행에 놓여있는 카드 중 가장 작은 값들을 선택 -> 그 중 가장 큰 값을 출력\nn : 행, m : 열\n* time 모듈을 이용하여 코드 진행 시간을 측정하려 했으나 코드 입력하는 시간까지 측정되어 정확한 시간 측정 불가\n'''\n\n'''\n>> 1. 내 풀이(효율X) <<\nimport time\n\nn, m = map(int, input().split())\n\nnumbers = []\nminNum = []\n\nstart_time = time.time()\n\nfor i in range(n):\n mList = list(map(int, input().split()))\n numbers.append(mList)\n mList.sort()\n minNum.append(mList[0])\n\nminNum.sort()\nprint(minNum[-1])\n\nend_time = time.time()\nprint(end_time - start_time) # 0.30493593215942383\n'''\n\n# >> 내 풀이(효율 고려, 책의 풀이와 유사) <<\nimport time\n\nn, m = map(int, input().split())\n\nminNum = 0\n\nstart_time = time.time()\n\nfor i in range(n):\n mList = list(map(int, input().split()))\n num = min(mList)\n if minNum < num:\n minNum = num\n\nprint(minNum)\n\nend_time = time.time()\nprint(end_time - start_time) # 0.19670701026916504","sub_path":"greedy/cardGame.py","file_name":"cardGame.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"234866334","text":"'''\nCreated on Mar 14, 2017\n\n@author: Aaron\n'''\nimport bridge\nimport client\nimport time\n\ndef main():\n myBridge = bridge.Bridge()\n myBridge.start(myBridge.getArduinoPort())\n myClient = client.Client()\n myClient.connectToServer(myClient.askAddress())\n while (True):\n myBridge.send(myClient.recieveData())\n \n myClient.closeConnection()\n\nif __name__ == '__main__':\n main()\n","sub_path":"RPi_client/src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"211124207","text":"import sys\n\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom PyQt5.QtGui import QPainter, QPen\nfrom PyQt5.QtCore import Qt\nfrom random import randint\n\n\nclass MyWidget(QMainWindow):\n def __init__(self):\n super().__init__()\n self.do_paint = False\n uic.loadUi('UI.ui', self)\n self.pushButton.clicked.connect(self.paint)\n\n def paintEvent(self, event):\n if self.do_paint:\n qp = QPainter()\n qp.begin(self)\n self.draw_flag(qp)\n qp.end()\n\n def paint(self):\n self.do_paint = True\n self.repaint()\n\n def draw_flag(self, qp):\n qp.setPen(QPen(Qt.yellow, 5, Qt.SolidLine))\n r = randint(10, 300)\n qp.drawEllipse(250 - r // 2, 200 - r // 2, r, r)\n\n\ndef except_hook(cls, exception, traceback):\n sys.__excepthook__(cls, exception, traceback)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n form = MyWidget()\n form.show()\n sys.excepthook = except_hook\n sys.exit(app.exec())","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"85505751","text":"\nimport datetime\nimport random\n\nclass TokenManager(object):\n\n def __init__(self):\n self.tokens = self.fetch_tokens()\n self.tracker = {i: datetime.datetime.strptime(\"0\", \"%S\") for i in self.tokens}\n self.index = 0\n self.current = None\n self.dirty=True\n\n def fetch_tokens(self):\n with open(\".tokens.txt\",'r') as f:\n return [line.replace(\"\\r\",\"\") for line in f.read().split(\"\\n\") if line]\n\n def pick(self):\n now = datetime.datetime.now()\n available = [i for i in self.tokens if (self.tracker[i]-now).seconds > 60]\n if len(available) == 0:\n print(\"Out of tokens\")\n c = [(self.tracker[i]-now).seconds for i in self.tokens]\n import time\n time.sleep(min(c))\n return self.pick()\n \n i = random.randrange(0, len(available))\n return self.tokens[i]\n\n def on_timeout(self):\n if not self.current:\n raise Exception\n self.tracker[self.current] = datetime.datetime.now()\n self.dirty=True\n\n def next_token(self):\n if not self.current:\n self.current = self.tokens[random.randrange(0, len(self.tokens))]\n else:\n self.current = self.pick()\n self.dirty=False\n\n def get_current_token(self):\n if self.dirty:\n self.current = self.next_token()\n return self.current\n","sub_path":"fledger/tokens.py","file_name":"tokens.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"471739174","text":"# -*- coding:utf-8 -*-\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport time\nimport tensorflow as tf\nimport numpy as np\nimport sys,os\nimport argparse\nsys.path.append(\"..\")\nimport facenet\nimport h5py\n\n#model_dir = '/home/lichen/deepfashion/Additive-Margin-Softmax/trained_model/20190106-155428'\n#data_dir = '/home/lichen/deepfashion/dataset/categary/test/categary'\n#feat_out = '/home/lichen/deepfashion/Additive-Margin-Softmax/evaluation/result/1.h5'\nbatch_size = 100\n\ndef exporEmbed(model_dir,data_dir,feat_out):\n train_set = facenet.get_dataset(data_dir)\n image_list, label_list = facenet.get_image_paths_and_labels(train_set)\n # fetch the classes (labels as strings) exactly as it's done in get_dataset\n path_exp = os.path.expanduser(data_dir)\n classes = [path for path in os.listdir(path_exp) if os.path.isdir(os.path.join(path_exp, path))]\n classes.sort()\n # get the label strings\n label_strings = [name for name in classes if os.path.isdir(os.path.join(path_exp, name))]\n\n with tf.Graph().as_default():\n with tf.Session() as sess:\n # Load the model\n facenet.load_model(model_dir)\n # Get input and output tensors\n images_placeholder = tf.get_default_graph().get_tensor_by_name(\"input:0\")\n embeddings = tf.get_default_graph().get_tensor_by_name(\"embeddings:0\")\n phase_train_placeholder = tf.get_default_graph().get_tensor_by_name(\"phase_train:0\")\n\n # Run forward pass to calculate embeddings\n nrof_images = len(image_list)\n print('Number of images: ', nrof_images)\n if nrof_images % batch_size == 0:\n nrof_batches = nrof_images // batch_size\n else:\n nrof_batches = (nrof_images // batch_size) + 1\n print('Number of batches: ', nrof_batches)\n embedding_size = embeddings.get_shape()[1]\n emb_array = np.zeros((nrof_images, embedding_size))\n start_time = time.time()\n\n for i in range(nrof_batches):\n if i == nrof_batches -1:\n n = nrof_images\n else:\n n = i*batch_size + batch_size\n # Get images for the batch\n images = facenet.load_data(image_list[i*batch_size:n], False, False, 224)\n feed_dict = {images_placeholder: images, phase_train_placeholder:False}\n # Use the facenet model to calcualte embeddings\n embed = sess.run(embeddings, feed_dict=feed_dict)\n emb_array[i*batch_size:n, :] = embed\n print('Completed batch', i+1, 'of', nrof_batches)\n\n run_time = time.time() - start_time\n #h5f = h5py.File(feat_out, 'w')\n #export emedings and labels\n label_list = np.array(label_list) \n #h5f['feats'] = emb_array\n #h5f['lables'] = label_list\n np.save(\"result/embeddings.npy\", emb_array)\n np.save(\"result/labels.npy\", label_list)\n #h5f.close()\n \n print('Run time: ', run_time)\n\nif __name__ == '__main__':\n exporEmbed(model_dir,data_dir,feat_out)\n","sub_path":"evaluation/export_embedding.py","file_name":"export_embedding.py","file_ext":"py","file_size_in_byte":3252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"139298426","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2018-2019 CERN.\n#\n# invenio-app-ils is free software; you can redistribute it and/or modify it\n# under the terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Test record permissions.\"\"\"\n\nfrom __future__ import unicode_literals\n\nimport uuid\n\nimport pytest\nfrom flask_principal import RoleNeed, identity_loaded\nfrom flask_security import login_user\nfrom invenio_access.models import ActionRoles\nfrom invenio_accounts.models import Role, User\nfrom invenio_records.api import Record\n\nfrom invenio_app_ils.records.permissions import RecordPermission, \\\n create_records_action\n\n\n@pytest.mark.parametrize(\n \"access,action,is_allowed\",\n [\n ({\"foo\": \"bar\"}, \"read\", True),\n ({\"foo\": \"bar\"}, \"update\", False),\n ({\"_access\": {\"read\": [1]}}, \"read\", True),\n ({\"_access\": {\"read\": [2]}}, \"read\", False),\n ({\"_access\": {\"read\": [\"records-readers\"]}}, \"read\", True),\n # permission for specific user to create\n ({\"_access\": {\"update\": [1]}}, \"update\", True),\n # checks if the access works for different actions\n ({\"_access\": {\"update\": [1]}}, \"create\", False),\n ({\"_access\": {\"delete\": [1]}}, \"update\", False),\n # delete access for user and librarian\n ({\"_access\": {\"delete\": [1, \"librarian\"]}}, \"delete\", True),\n ],\n)\ndef test_record_generic_access(db, users, with_access, access, action,\n is_allowed):\n \"\"\"Test access control for records.\"\"\"\n\n @identity_loaded.connect\n def mock_identity_provides(sender, identity):\n \"\"\"Provide additional role to the user.\"\"\"\n roles = [RoleNeed(\"records-readers\")]\n # Gives the user additional roles, f.e. based on his groups\n identity.provides |= set(roles)\n\n def login_and_test(user_id):\n login_user(User.query.get(user_id))\n # Create record\n user = User.query.get(user_id)\n id = uuid.uuid4()\n record = Record.create(access, id_=id)\n factory = RecordPermission(record, action)\n if user.has_role(\"admin\"):\n # super user can do EVERYTHING\n assert factory.can()\n elif user.has_role(\"librarian\") and action != \"delete\":\n # librarian should be able to update, create, and read everything\n assert factory.can()\n else:\n assert factory.can() if is_allowed else not factory.can()\n\n # Test standard user\n login_and_test(users[\"patron1\"].id)\n # Test librarian access\n login_and_test(users[\"librarian\"].id)\n # Test superuser access\n login_and_test(users[\"admin\"].id)\n\n\n@pytest.mark.parametrize(\n \"access,action,is_allowed\",\n [\n ({\"foo\": \"bar\"}, \"create\", True),\n ({\"foo\": \"bar\"}, \"update\", False),\n ({\"foo\": \"bar\"}, \"delete\", False),\n ],\n)\ndef test_record_patron_create(db, users, access, action, is_allowed):\n \"\"\"Test patron create.\"\"\"\n # create role to be able to create records\n role = Role(name=\"records-creators\")\n db.session.add(role)\n db.session.commit()\n # assign role to the action \"create-records\"\n ar = ActionRoles.allow(create_records_action, role_id=role.id)\n db.session.add(ar)\n db.session.commit()\n\n @identity_loaded.connect\n def mock_identity_provides(sender, identity):\n \"\"\"Provide additional role to the user.\"\"\"\n roles = [RoleNeed(role.name)]\n # Gives the user additional roles, f.e. based on his groups\n identity.provides |= set(roles)\n\n login_user(users[\"patron1\"])\n\n id = uuid.uuid4()\n record = Record.create(access, id_=id)\n factory = RecordPermission(record, action)\n\n assert factory.can() if is_allowed else not factory.can()\n","sub_path":"tests/api/test_record_permissions.py","file_name":"test_record_permissions.py","file_ext":"py","file_size_in_byte":3725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"185742002","text":"from tkinter import *\r\nimport numpy as np\r\nimport time\r\nz=[]\r\nfrom boundry import y as z\r\nglobal center\r\ncenter=[]\r\ndef eqn(center):\r\n global res\r\n #print(\"\\n\",x[0],y[0],x[1],y[1])\r\n a=int(center[0][3][1])-int(center[0][3][0])\r\n b=int(center[0][2][0])-int(center[0][2][1])\r\n c=(int(center[0][2][0])*(int(center[0][3][0])-int(center[0][3][1]))-int(center[0][3][0])*(int(center[0][2][0])-int(center[0][2][1])))\r\n #print(x[0],y[0])\r\n res=a*int(center[0][0])+b*int(center[0][1])+c\r\n print(res)\r\n #print(\"\\n\",x1,y1)\r\n #print(\"\\n\",a,b,c)\r\n #print(\"\\n\",res) \r\nx1=20\r\ny1=30\r\nmy_window = Tk()\r\nmy_canvas = Canvas(my_window,width=400,height=400,background='black')\r\nmy_canvas.grid(row=0,column=0)\r\ni=0\r\nj=1\r\nk=0\r\ns=0\r\nu=0\r\nwhile (k<4):\r\n center.append([x1,y1,z[i],z[j]])\r\n print(center)\r\n print(type(center))\r\n t=eqn(center)\r\n my_canvas.create_line(z[i][0],z[i][1],z[j][0],z[j][1],fill='white')\r\n if res<0:\r\n print(\"in at\",i)\r\n u+=1\r\n my_canvas.create_line(x1,y1,x1+1,y1+1,fill='white')\r\n else:\r\n print(\"out at\",i)\r\n s+=1\r\n my_canvas.create_line(x1,y1,x1+1,y1+1,fill='red')\r\n i+=1\r\n j+=1\r\n k+=1\r\n if j==4:\r\n j=0\r\n if i==4:\r\n i=0\r\n if k==4:\r\n break\r\n # print(\"\\n\",s)\r\n time.sleep(0.5)\r\n center.clear()\r\nif s==4 or u==4:\r\n print(\"inside the boundry\")\r\nelse:\r\n print(\"outside the boundry\")\r\nmy_window.mainloop()\r\n","sub_path":"demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"151586794","text":"from __future__ import absolute_import, division, print_function\n#import six\n#import numpy as np\n#from ibeis.model.hots import hstypes\nimport utool as ut\n#profile = ut.profile\nprint, print_, printDBG, rrr, profile = ut.inject(__name__, '[_plh]', DEBUG=False)\n\n\nVERB_PIPELINE = ut.get_argflag(('--verb-pipeline', '--verb-pipe')) or ut.VERYVERBOSE\nVERB_TESTDATA = ut.get_argflag('--verb-testdata') or ut.VERYVERBOSE\n\n\ndef testdata_hs2(defaultdb='testdb1', qaids=None, daids=None, cfgdict=None, stop_node=None, argnames=[]):\n \"\"\"\n CommandLine:\n python -m ibeis.model.hots._pipeline_helpers --test-testdata_hs2\n\n Example0:\n >>> # DISABLE_DOCTEST\n >>> from ibeis.model.hots._pipeline_helpers import *\n >>> defaultdb = 'testdb1'\n >>> qaids = None\n >>> daids = None\n >>> stop_node = 'build_chipmatches'\n >>> cfgdict = None\n >>> argnames = []\n >>> # execute function\n >>> result = testdata_hs2(defaultdb, qaids, daids, cfgdict, stop_node, argnames)\n >>> # verify results\n >>> print(result)\n \"\"\"\n from ibeis.model.hots import pipeline\n func = getattr(pipeline, stop_node)\n ibs, qreq_ = get_pipeline_testdata(qaid_list=qaids, daid_list=daids, defaultdb=defaultdb, cfgdict=cfgdict)\n func_argnames = ut.get_func_argspec(func).args\n locals_ = testrun_pipeline_upto(qreq_, stop_node)\n args = ut.dict_take(locals_, func_argnames)\n return args\n\n\ndef testrun_pipeline_upto(qreq_, stop_node=None, verbose=True):\n r\"\"\"\n convinience: runs pipeline for tests\n this should mirror request_ibeis_query_L0\n\n Ignore:\n >>> import utool as ut\n >>> from ibeis.model.hots import pipeline\n >>> source = ut.get_func_sourcecode(pipeline.request_ibeis_query_L0)\n >>> stripsource = source[:]\n >>> stripsource = ut.strip_line_comments(stripsource)\n >>> triplequote1 = ut.TRIPLE_DOUBLE_QUOTE\n >>> triplequote2 = ut.TRIPLE_SINGLE_QUOTE\n >>> docstr_regex1 = 'r?' + triplequote1 + '.* + ' + triplequote1 + '\\n '\n >>> docstr_regex2 = 'r?' + triplequote2 + '.* + ' + triplequote2 + '\\n '\n >>> stripsource = ut.regex_replace(docstr_regex1, '', stripsource)\n >>> stripsource = ut.regex_replace(docstr_regex2, '', stripsource)\n >>> stripsource = ut.strip_line_comments(stripsource)\n >>> print(stripsource)\n \"\"\"\n from ibeis.model.hots.pipeline import (\n nearest_neighbors, baseline_neighbor_filter, weight_neighbors,\n build_chipmatches, spatial_verification,\n chipmatch_to_resdict, vsone_reranking, build_impossible_daids_list)\n\n qreq_.lazy_load(verbose=verbose)\n #---\n if stop_node == 'build_impossible_daids_list':\n return locals()\n impossible_daids_list, Kpad_list = build_impossible_daids_list(qreq_)\n #---\n if stop_node == 'nearest_neighbors':\n return locals()\n nns_list = nearest_neighbors(qreq_, Kpad_list, verbose=verbose)\n #---\n if stop_node == 'baseline_neighbor_filter':\n return locals()\n nnvalid0_list = baseline_neighbor_filter(qreq_, nns_list, impossible_daids_list, verbose=verbose)\n #---\n if stop_node == 'weight_neighbors':\n return locals()\n filtkey_list, filtweights_list, filtvalids_list = weight_neighbors(qreq_, nns_list, nnvalid0_list, verbose=verbose)\n #---\n if stop_node == 'filter_neighbors':\n raise AssertionError('no longer exists')\n #---\n if stop_node == 'build_chipmatches':\n return locals()\n cm_list_FILT = build_chipmatches(qreq_, nns_list, nnvalid0_list, filtkey_list, filtweights_list, filtvalids_list, verbose=verbose)\n #---\n if stop_node == 'spatial_verification':\n return locals()\n cm_list_SVER = spatial_verification(qreq_, cm_list_FILT, verbose=verbose)\n #---\n if stop_node == 'vsone_reranking':\n return locals()\n if qreq_.qparams.rrvsone_on:\n # VSONE RERANKING\n cm_list_VSONERR = vsone_reranking(qreq_, cm_list_SVER, verbose=verbose)\n cm_list = cm_list_VSONERR\n else:\n cm_list = cm_list_SVER\n #---\n if stop_node == 'chipmatch_to_resdict':\n return locals()\n qaid2_qres = chipmatch_to_resdict(qreq_, cm_list, verbose=verbose)\n\n assert False, 'unknown stop_node=%r' % (stop_node,)\n\n #qaid2_svtups = qreq_.metadata['qaid2_svtups']\n return locals()\n\n\ndef get_pipeline_testdata(dbname=None,\n cfgdict=None,\n qaid_list=None,\n daid_list=None,\n defaultdb='testdb1',\n cmdline_ok=True,\n preload=True):\n r\"\"\"\n Gets testdata for pipeline defined by tests / and or command line\n\n Args:\n cmdline_ok : if false does not check command line\n\n Returns:\n tuple: ibs, qreq_\n\n CommandLine:\n python -m ibeis.model.hots._pipeline_helpers --test-get_pipeline_testdata\n python -m ibeis.model.hots._pipeline_helpers --test-get_pipeline_testdata --daid_list 39 --qaid 41 --db PZ_MTEST\n python -m ibeis.model.hots._pipeline_helpers --test-get_pipeline_testdata --daids 39 --qaid 41 --db PZ_MTEST\n python -m ibeis.model.hots._pipeline_helpers --test-get_pipeline_testdata --qaid 41 --db PZ_MTEST\n python -m ibeis.model.hots._pipeline_helpers --test-get_pipeline_testdata --controlled_daids --qaids=41 --db PZ_MTEST --verb-testdata\n\n Example:\n >>> # ENABLE_DOCTEST\n >>> import ibeis # NOQA\n >>> from ibeis.model.hots import _pipeline_helpers as plh\n >>> cfgdict = dict(pipeline_root='vsone', codename='vsone')\n >>> ibs, qreq_ = plh.get_pipeline_testdata(cfgdict=cfgdict)\n >>> ibs, qreq_ = plh.get_pipeline_testdata(cfgdict=cfgdict)\n >>> result = ''\n >>> result += ('daids = %r\\n' % (qreq_.get_external_daids(),))\n >>> result += ('qaids = %r' % (qreq_.get_external_qaids(),))\n >>> print('cfgstr %s' % (qreq_.qparams.query_cfgstr,))\n >>> print(result)\n\n daids = array([1, 2, 3, 4, 5])\n qaids = array([1])\n \"\"\"\n import ibeis\n from ibeis.model.hots import query_request\n # Allow commandline specification if paramaters are not specified in tests\n if cfgdict is None:\n cfgdict = {}\n\n assert cmdline_ok is True, 'cmdline_ok should always be True'\n\n if cmdline_ok:\n from ibeis.model import Config\n # Allow specification of db and qaids/daids\n if dbname is not None:\n defaultdb = dbname\n dbname = ut.get_argval('--db', type_=str, default=defaultdb)\n\n ibs = ibeis.opendb(defaultdb=dbname)\n\n default_qaid_list = qaid_list\n default_daid_list = daid_list\n\n # setup special defautls\n\n if default_qaid_list is None:\n default_qaid_list = {\n 'testdb1' : [1],\n 'GZ_ALL' : [1032],\n 'PZ_ALL' : [1, 3, 5, 9],\n }.get(dbname, [1])\n\n default_daid_list = ut.get_argval(('--daids', '--daid-list'), type_=list, default=default_daid_list)\n\n if default_daid_list is None:\n if dbname == 'testdb1':\n default_daid_list = ibs.get_valid_aids()[0:5]\n else:\n default_daid_list = 'all'\n\n # Use commmand line parsing for custom values\n\n if cmdline_ok:\n from ibeis.init import main_helpers\n qaid_list_ = main_helpers.get_test_qaids(ibs, default_qaids=default_qaid_list)\n daid_list_ = main_helpers.get_test_daids(ibs, default_daids=default_daid_list, qaid_list=qaid_list_)\n #\n # Allow commond line specification of all query params\n default_cfgdict = dict(Config.parse_config_items(Config.QueryConfig()))\n default_cfgdict.update(cfgdict)\n _orig_cfgdict = cfgdict\n force_keys = set(list(_orig_cfgdict.keys()))\n cfgdict_ = ut.util_arg.argparse_dict(\n default_cfgdict, verbose=not ut.QUIET, only_specified=True,\n force_keys=force_keys)\n #ut.embed()\n if VERB_PIPELINE or VERB_TESTDATA:\n print('[plh] cfgdict_ = ' + ut.dict_str(cfgdict_))\n else:\n qaid_list_ = qaid_list\n daid_list_ = daid_list\n cfgdict_ = cfgdict\n\n #ibs = ibeis.test_main(db=dbname)\n\n if VERB_TESTDATA:\n #ibeis.other.dbinfo.print_qd_info(ibs, qaid_list_, daid_list_, verbose=True)\n ibeis.other.dbinfo.print_qd_info(ibs, qaid_list_, daid_list_, verbose=False)\n\n if 'with_metadata' not in cfgdict:\n cfgdict_['with_metadata'] = True\n qreq_ = query_request.new_ibeis_query_request(ibs, qaid_list_, daid_list_, cfgdict=cfgdict_)\n if preload:\n qreq_.lazy_load()\n return ibs, qreq_\n\n\n#+--- OTHER TESTDATA FUNCS ---\n\n\ndef testdata_pre_weight_neighbors(defaultdb='testdb1', qaid_list=[1, 2], daid_list=None, codename='vsmany', cfgdict=None):\n if cfgdict is None:\n cfgdict = dict(codename=codename)\n ibs, qreq_ = get_pipeline_testdata(\n qaid_list=qaid_list, daid_list=daid_list, defaultdb=defaultdb, cfgdict=cfgdict)\n locals_ = testrun_pipeline_upto(qreq_, 'weight_neighbors')\n nns_list, nnvalid0_list = ut.dict_take(locals_, ['nns_list', 'nnvalid0_list'])\n return ibs, qreq_, nns_list, nnvalid0_list\n\n\ndef testdata_sparse_matchinfo_nonagg(defaultdb='testdb1', codename='vsmany'):\n ibs, qreq_, args = testdata_pre_build_chipmatch(defaultdb=defaultdb, codename=codename)\n nns_list, nnvalid0_list, filtkey_list, filtweights_list, filtvalids_list = args\n if qreq_.qparams.vsone:\n interal_index = 1\n else:\n interal_index = 0\n qaid = qreq_.get_external_qaids()[0]\n daid = qreq_.get_external_daids()[1]\n qfx2_idx, _ = nns_list[interal_index]\n qfx2_valid0 = nnvalid0_list[interal_index]\n qfx2_score_list = filtweights_list[interal_index]\n qfx2_valid_list = filtvalids_list[interal_index]\n args = qfx2_idx, qfx2_valid0, qfx2_score_list, qfx2_valid_list\n return qreq_, qaid, daid, args\n\n\ndef testdata_pre_build_chipmatch(defaultdb='testdb1', codename='vsmany'):\n cfgdict = dict(codename=codename)\n ibs, qreq_ = get_pipeline_testdata(defaultdb=defaultdb, cfgdict=cfgdict)\n locals_ = testrun_pipeline_upto(qreq_, 'build_chipmatches')\n args = ut.dict_take(locals_, ['nns_list', 'nnvalid0_list', 'filtkey_list', 'filtweights_list', 'filtvalids_list'])\n return ibs, qreq_, args\n\n\ndef testdata_pre_baselinefilter(defaultdb='testdb1', qaid_list=None, daid_list=None, codename='vsmany'):\n cfgdict = dict(codename=codename)\n ibs, qreq_ = get_pipeline_testdata(\n qaid_list=qaid_list, daid_list=daid_list, defaultdb=defaultdb, cfgdict=cfgdict)\n locals_ = testrun_pipeline_upto(qreq_, 'baseline_neighbor_filter')\n nns_list, impossible_daids_list = ut.dict_take(locals_, ['nns_list', 'impossible_daids_list'])\n return qreq_, nns_list, impossible_daids_list\n\n\ndef testdata_pre_sver(defaultdb='PZ_MTEST', qaid_list=None, daid_list=None):\n \"\"\"\n >>> from ibeis.model.hots._pipeline_helpers import * # NOQA\n \"\"\"\n #from ibeis.model import Config\n cfgdict = dict()\n ibs, qreq_ = get_pipeline_testdata(\n qaid_list=qaid_list, daid_list=daid_list, defaultdb=defaultdb, cfgdict=cfgdict)\n locals_ = testrun_pipeline_upto(qreq_, 'spatial_verification')\n cm_list = locals_['cm_list_FILT']\n #nnfilts_list = locals_['nnfilts_list']\n return ibs, qreq_, cm_list\n\n\ndef get_pipeline_testdata2(defaultdb='testdb1', default_aidcfg_name_list=['default'], default_test_cfg_name_list=['default'], preload=False):\n r\"\"\"\n Gets testdata for pipeline defined by tests / and or command line\n\n Args:\n cmdline_ok : if false does not check command line\n\n Returns:\n tuple: ibs, qreq_\n\n CommandLine:\n python -m ibeis.model.hots._pipeline_helpers --test-get_pipeline_testdata\n python -m ibeis.model.hots._pipeline_helpers --test-get_pipeline_testdata --daid_list 39 --qaid 41 --db PZ_MTEST\n python -m ibeis.model.hots._pipeline_helpers --test-get_pipeline_testdata --daids 39 --qaid 41 --db PZ_MTEST\n python -m ibeis.model.hots._pipeline_helpers --test-get_pipeline_testdata --qaid 41 --db PZ_MTEST\n python -m ibeis.model.hots._pipeline_helpers --test-get_pipeline_testdata --controlled_daids --qaids=41 --db PZ_MTEST --verb-testdata\n\n Example:\n >>> # UNSTABLE_DOCTEST\n >>> import ibeis # NOQA\n >>> from ibeis.model.hots import _pipeline_helpers as plh\n >>> ibs, qreq_list = plh.get_pipeline_testdata2('PZ_MTEST', default_test_cfg_name_list=['candidacy_namescore'])\n\n daids = array([1, 2, 3, 4, 5])\n qaids = array([1])\n \"\"\"\n #from ibeis.init import main_helpers\n from ibeis.experiments import experiment_helpers\n from ibeis.model.hots import query_request\n #from ibeis.experiments import experiment_helpers\n import ibeis\n ibs = ibeis.opendb(defaultdb=defaultdb)\n acfg_name_list = ut.get_argval(('--aidcfg', '--acfg', '-a'), type_=list, default=default_aidcfg_name_list)\n test_cfg_name_list = ut.get_argval('-t', type_=list, default=default_test_cfg_name_list)\n\n # Generate list of query pipeline param configs\n acfg_list, expanded_aids_list = experiment_helpers.get_annotcfg_list(ibs, acfg_name_list)\n cfgdict_list, pipecfg_list = experiment_helpers.get_pipecfg_list(test_cfg_name_list, ibs=ibs)\n\n qreq_list = []\n\n for qaids, daids in expanded_aids_list:\n for query_cfg in pipecfg_list:\n qreq_ = query_request.new_ibeis_query_request(ibs, qaids, daids, query_cfg=query_cfg)\n qreq_list.append(qreq_)\n\n if preload:\n for qreq_ in qreq_list:\n qreq_.lazy_load()\n return ibs, qreq_list\n\n\ndef testdata_pre_sver2(*args, **kwargs):\n \"\"\"\n >>> from ibeis.model.hots._pipeline_helpers import * # NOQA\n >>> args = (,)\n >>> kwargs = {}\n \"\"\"\n #from ibeis.model import Config\n ibs, qreq_list = get_pipeline_testdata2(*args, **kwargs)\n locals_list = [testrun_pipeline_upto(qreq_, 'spatial_verification') for qreq_ in qreq_list]\n cms_list = [locals_['cm_list_FILT'] for locals_ in locals_list]\n #nnfilts_list = locals_['nnfilts_list']\n return ibs, qreq_list, cms_list\n\n\ndef testdata_post_sver(defaultdb='PZ_MTEST', qaid_list=None, daid_list=None, codename='vsmany', cfgdict=None):\n \"\"\"\n >>> from ibeis.model.hots._pipeline_helpers import * # NOQA\n \"\"\"\n #from ibeis.model import Config\n if cfgdict is None:\n cfgdict = dict(codename=codename)\n ibs, qreq_ = get_pipeline_testdata(\n qaid_list=qaid_list, daid_list=daid_list, defaultdb=defaultdb, cfgdict=cfgdict)\n locals_ = testrun_pipeline_upto(qreq_, 'vsone_reranking')\n cm_list = locals_['cm_list_SVER']\n #nnfilts_list = locals_['nnfilts_list']\n return ibs, qreq_, cm_list\n\n\ndef testdata_pre_vsonerr(defaultdb='PZ_MTEST', qaid_list=[1], daid_list='all'):\n \"\"\"\n >>> from ibeis.model.hots._pipeline_helpers import * # NOQA\n \"\"\"\n cfgdict = dict(sver_output_weighting=True, codename='vsmany', rrvsone_on=True)\n # Get pipeline testdata for this configuration\n ibs, qreq_ = get_pipeline_testdata(\n cfgdict=cfgdict, qaid_list=qaid_list, daid_list=daid_list, defaultdb=defaultdb, cmdline_ok=True)\n qaid_list = qreq_.get_external_qaids().tolist()\n qaid = qaid_list[0]\n #daid_list = qreq_.get_external_daids().tolist()\n if len(ibs.get_annot_groundtruth(qaid)) == 0:\n print('WARNING: qaid=%r has no groundtruth' % (qaid,))\n locals_ = testrun_pipeline_upto(qreq_, 'vsone_reranking')\n cm_list = locals_['cm_list_SVER']\n return ibs, qreq_, cm_list, qaid_list\n\n\ndef testdata_scoring(defaultdb='PZ_MTEST', qaid_list=[1], daid_list='all'):\n from ibeis.model.hots import vsone_pipeline\n ibs, qreq_, prior_cm = testdata_matching(defaultdb=defaultdb, qaid_list=qaid_list, daid_list=daid_list)\n config = qreq_.qparams\n cm = vsone_pipeline.refine_matches(qreq_, prior_cm, config)\n cm.evaluate_dnids(qreq_.ibs)\n return qreq_, cm\n\n\ndef testdata_matching(*args, **kwargs):\n \"\"\"\n >>> from ibeis.model.hots._pipeline_helpers import * # NOQA\n \"\"\"\n from ibeis.model.hots import vsone_pipeline\n from ibeis.model.hots import scoring\n ibs, qreq_, cm_list, qaid_list = testdata_pre_vsonerr(*args, **kwargs)\n vsone_pipeline.prepare_vsmany_chipmatch(qreq_, cm_list)\n nNameShortlist = qreq_.qparams.nNameShortlistVsone\n nAnnotPerName = qreq_.qparams.nAnnotPerNameVsOne\n scoring.score_chipmatch_list(qreq_, cm_list, 'nsum')\n vsone_pipeline.prepare_vsmany_chipmatch(qreq_, cm_list)\n cm_shortlist = scoring.make_chipmatch_shortlists(qreq_, cm_list, nNameShortlist, nAnnotPerName)\n prior_cm = cm_shortlist[0]\n return ibs, qreq_, prior_cm\n\n\n#L_______\n\n\ndef print_nearest_neighbor_assignments(qvecs_list, nns_list):\n nQAnnots = len(qvecs_list)\n nTotalDesc = sum(map(len, qvecs_list))\n nTotalNN = sum([qfx2_idx.size for (qfx2_idx, qfx2_dist) in nns_list])\n print('[hs] * assigned %d desc (from %d annots) to %r nearest neighbors'\n % (nTotalDesc, nQAnnots, nTotalNN))\n\n\ndef _self_verbose_check(qfx2_notsamechip, qfx2_valid0):\n nInvalidChips = ((True - qfx2_notsamechip)).sum()\n nNewInvalidChips = (qfx2_valid0 * (True - qfx2_notsamechip)).sum()\n total = qfx2_valid0.size\n print('[hs] * self invalidates %d/%d assignments' % (nInvalidChips, total))\n print('[hs] * %d are newly invalided by self' % (nNewInvalidChips))\n\n\ndef _samename_verbose_check(qfx2_notsamename, qfx2_valid0):\n nInvalidNames = ((True - qfx2_notsamename)).sum()\n nNewInvalidNames = (qfx2_valid0 * (True - qfx2_notsamename)).sum()\n total = qfx2_valid0.size\n print('[hs] * nid invalidates %d/%d assignments' % (nInvalidNames, total))\n print('[hs] * %d are newly invalided by nid' % nNewInvalidNames)\n\n\ndef _sameimg_verbose_check(qfx2_notsameimg, qfx2_valid0):\n nInvalidImgs = ((True - qfx2_notsameimg)).sum()\n nNewInvalidImgs = (qfx2_valid0 * (True - qfx2_notsameimg)).sum()\n total = qfx2_valid0.size\n print('[hs] * gid invalidates %d/%d assignments' % (nInvalidImgs, total))\n print('[hs] * %d are newly invalided by gid' % nNewInvalidImgs)\n\n\nif __name__ == '__main__':\n \"\"\"\n CommandLine:\n python -m ibeis.model.hots._pipeline_helpers\n python -m ibeis.model.hots._pipeline_helpers --allexamples\n python -m ibeis.model.hots._pipeline_helpers --allexamples --noface --nosrc\n \"\"\"\n import multiprocessing\n multiprocessing.freeze_support() # for win32\n import utool as ut # NOQA\n ut.doctest_funcs()\n","sub_path":"services/vision/hybrid-vision/ibeis/ibeis/model/hots/_pipeline_helpers.py","file_name":"_pipeline_helpers.py","file_ext":"py","file_size_in_byte":18596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"264511053","text":"import numpy as np\nimport tensorflow as tf\nimport sys\nimport os\nimport time\nimport csv\nimport argparse\nimport main\n\nfrom neural_network import NeuralNetwork\nfrom rl_log import LogQValues, LogReward\nfrom epsilon_greedy import EpsilonGreedy\nfrom epsilon_greedy import LinearControlSignal\nfrom neural_network_2 import NeuralNetwork\nfrom replay_memory import ReplayMemory\n\nfrom deuces import Card\nimport encode_state\nimport yaml\n\nimport pandas as pd\n\nclass Agent:\n \"\"\"\n Agent class interacts with the game evironment and creates\n instances of replay memory and the neural network\n \"\"\"\n def __init__(self, agent_name, action_names, training, epsilon_testing,\n state_shape, checkpoint_dir, render=False, use_logging=True):\n \"\"\"\n Create agent object instance. Will initialise the replay memory\n and neural network\n \n Args:\n agent_name (str): Name of agent\n training (bool): Whether the agent is training the neural network (True)\n or playing in test model (False)\n render (bool): Wjether to render the game (redundant)\n use_logging (bool): Whether to log to text files during training\n\n \"\"\"\n self.agent_name = agent_name\n self.checkpoint_dir = checkpoint_dir\n\n # The number of possible actions that the agent may take in every step.\n self.num_actions = len(action_names)\n\n # Whether we are training (True) or testing (False).\n self.training = training\n\n # Whether to render each image-frame of the game-environment to screen.\n self.render = render\n\n # Whether to use logging during training.\n self.use_logging = use_logging\n\n # Set shape of state that will be input\n self.state_shape = state_shape\n\n if self.use_logging and self.training:\n # Used for logging Q-values and rewards during training.\n self.log_q_values = LogQValues()\n self.log_reward = LogReward()\n else:\n self.log_q_values = None\n self.log_reward = None\n\n\n # List of string-names for the actions in the game-environment.\n self.action_names = action_names\n\n # Initialise epsilon greedy\n self.epsilon_greedy = EpsilonGreedy(start_value=1.0,\n end_value=epsilon_testing,\n num_iterations=5e6,\n num_actions=self.num_actions,\n epsilon_testing=epsilon_testing)\n\n if self.training:\n # The following control-signals are only used during training.\n\n # The learning-rate for the optimizer decreases linearly.\n self.learning_rate_control = LinearControlSignal(start_value=0.00001,\n end_value=0.00001,\n num_iterations=1e5)\n\n # The loss-limit is used to abort the optimization whenever the\n # mean batch-loss falls below this limit.\n self.loss_limit_control = LinearControlSignal(start_value=0.0,\n end_value=0.0,\n num_iterations=50000)\n\n # The maximum number of epochs to perform during optimization.\n self.max_epochs_control = LinearControlSignal(start_value=5.0,\n end_value=1.0,\n num_iterations=1e5)\n\n # The fraction of the replay-memory to be used.\n # Early in the training, we want to optimize more frequently\n # so the Neural Network is trained faster and the Q-values\n # are learned and updated more often. Later in the training,\n # we need more samples in the replay-memory to have sufficient\n # diversity, otherwise the Neural Network will over-fit.\n self.replay_fraction = LinearControlSignal(start_value=0.1,\n end_value=1.0,\n num_iterations=5e6)\n\n else:\n # We set these objects to None when they will not be used.\n self.learning_rate_control = None\n self.loss_limit_control = None\n self.max_epochs_control = None\n self.replay_fraction = None\n\n if self.training:\n # We only create the replay-memory when we are training the agent,\n # because it requires a lot of RAM.\n self.replay_memory = ReplayMemory(size=16000, state_shape=self.state_shape,\n num_actions=self.num_actions, checkpoint_dir=checkpoint_dir)\n else:\n self.replay_memory = None\n\n # Create the Neural Network used for estimating Q-values.\n self.model = NeuralNetwork(model_name=agent_name, input_shape=self.state_shape, num_actions=self.num_actions, \n checkpoint_dir=checkpoint_dir, replay_memory=self.replay_memory, training=self.training)\n\n # Record episode states. In the case of poker,\n # a hand constitutes an episode.\n self.episode_states = []\n self.episode_q_values = []\n self.episode_actions = []\n self.episode_epsilons = []\n self.hand_rewards = []\n\n # Log of the rewards obtained in each episode during calls to run()\n self.episode_rewards = []\n\n self.min_max_scaling = lambda a, b, min_x, max_x, x: a + ((x - min_x) * (b - a)) / (max_x - min_x)\n\n self.write_state_action = False\n self.output_path = \"./output/player_actions/player_\" + str(self.agent_name) + \"_actions.csv\"\n self.action_space = ['CALL', 'ALL_IN', 'CHECK', 'FOLD']\n\n with open(checkpoint_dir + \"action_config.yaml\", 'r') as yaml_file:\n self.action_config = yaml.load(yaml_file, Loader=yaml.FullLoader)\n\n raise_action_space = self.action_config['raise_actions']\n\n self.action_space.extend(raise_action_space)\n self.raise_idxs = list(range(4, len(raise_action_space) + 4))\n self.raise_multiples = self.action_config['raise_multiples']\n\n self.set_fold_q = self.action_config['set_fold_q']\n\n def get_replay_memory_size(self):\n return(self.replay_memory.num_used)\n\n def reset_episode_rewards(self):\n \"\"\"Reset the log of episode-rewards.\"\"\"\n self.episode_states = []\n self.episode_q_values = []\n self.episode_actions = []\n self.episode_rewards = []\n self.episode_epsilons = []\n\n def get_action_name(self, action):\n \"\"\"Return the name of an action.\"\"\"\n return self.action_names[action]\n\n def q_value_processing(self, q_values, hero_player, table):\n if table.current_bet == 0:\n valid_idxs = [1, 2, 4, 5, 6, 7]\n\n # Set fold Q-value to zero\n q_values[3] = 0.0\n\n # Set call Q-value to zero\n q_values[0] = 0.0\n\n # Change raise space\n if table.current_bet + table.big_blind > hero_player.stack:\n # Set all raise Q values to zero\n q_values[4:] = 0.0\n valid_idxs = [1, 2]\n\n\n elif table.current_bet + table.big_blind*2 > hero_player.stack:\n # Set 2x raise + Q values to zero\n q_values[5:] = 0.0\n valid_idxs = [1, 2, 4]\n\n elif table.current_bet + table.big_blind*4 > hero_player.stack:\n # Set 4x raise + raise Q values to zero\n q_values[6:] = 0.0\n valid_idxs = [1, 2, 4, 5]\n\n elif table.current_bet + table.big_blind*8 > hero_player.stack:\n # Set 8x raise + raise Q values to zero\n q_values[7:] = 0.0\n valid_idxs = [1, 2, 4, 5, 6]\n\n else:\n valid_idxs = [1, 2, 4, 5, 6, 7]\n\n\n\n ### Current bet above zero ###\n else:\n valid_idxs = [0, 1, 3, 4, 5, 6, 7]\n\n # Set check Q-value to zero\n q_values[2] = 0.0\n\n # Remove call if can only go all in or fold\n if table.current_bet > hero_player.stack:\n q_values[0] = 0.0\n q_values[4:] = 0.0\n valid_idxs = [1, 3]\n\n # Change raise space\n elif table.current_bet + table.big_blind > hero_player.stack:\n\n # Set all raise Q values to zero\n q_values[4:] = 0.0\n\n # Set call to 0\n q_values[0] = 0.0\n\n valid_idxs = [1, 3]\n\n\n elif table.current_bet + table.big_blind*2 > hero_player.stack:\n # Set 2x raise + Q values to zero\n q_values[5:] = 0.0\n valid_idxs = [0, 1, 3, 4]\n\n elif table.current_bet + table.big_blind*4 > hero_player.stack:\n # Set 4x raise + raise Q values to zero\n q_values[6:] = 0.0\n valid_idxs = [0, 1, 3, 4, 5]\n\n elif table.current_bet + table.big_blind*8 > hero_player.stack:\n # Set 8x raise + raise Q values to zero\n q_values[7:] = 0.0\n valid_idxs = [0, 1, 3, 4, 5, 6]\n\n else:\n valid_idxs = [0, 1, 3, 4, 5, 6, 7]\n\n\n return q_values, valid_idxs\n\n\n def q_value_processing_v2(self, q_values, hero_player, table):\n self.action_type_space = ['CALL', 'ALL_IN', 'CHECK', \n 'FOLD', 'RAISE_1']\n\n\n if table.current_bet == 0:\n valid_idxs = [1, 2, 4]\n\n # Set call Q-value to zero\n q_values[0] = 0.0\n\n # Set fold Q-value to zero\n q_values[3] = 0.0\n\n # Change raise space\n if table.current_bet + table.big_blind > hero_player.stack:\n # Set all raise Q values to zero\n q_values[4] = 0.0\n valid_idxs = [1, 2]\n\n else:\n valid_idxs = [0, 1, 3, 4]\n\n if table.current_bet > hero_player.stack:\n q_values[0] = 0.0\n q_values[4] = 0.0\n valid_idxs = [1, 3]\n\n if table.current_bet + table.big_blind > hero_player.stack:\n q_values[0] = 0.0\n q_values[4] = 0.0\n\n valid_idxs = [1, 3]\n\n return q_values, valid_idxs\n\n\n def q_value_processing_v3(self, q_values, hero_player, table):\n # self.action_type_space = ['CALL', 'ALL_IN', 'CHECK', \n # 'FOLD', 'RAISE_1', 'RAISE_1_5', 'RAISE_2', 'RAISE_2_5', \n # 'RAISE_3', 'RAISE_3_5', 'RAISE_4', 'RAISE_4_5']\n\n current_bet = table.current_bet\n hero_stack = hero_player.stack\n big_blind = table.big_blind\n\n\n # Call, all in, check, fold\n\n if table.current_bet == 0:\n valid_base_idxs = [1, 2]\n valid_raise_idxs = [idx for idx, raise_mul in zip(self.raise_idxs, self.raise_multiples) if hero_stack >= (current_bet + big_blind * raise_mul) ]\n valid_idxs = valid_base_idxs + valid_raise_idxs\n\n q_values = [q if idx in valid_idxs else -1 for idx, q in enumerate(q_values)]\n\n else:\n valid_base_idxs = [0, 1, 3]\n\n valid_raise_idxs = [idx for idx, raise_mul in zip(self.raise_idxs, self.raise_multiples) if hero_stack >= (current_bet + big_blind * raise_mul) ]\n valid_idxs = valid_base_idxs + valid_raise_idxs\n q_values = [q if idx in valid_idxs else -1 for idx, q in enumerate(q_values)]\n\n\n return q_values, valid_idxs\n\n\n def get_action(self, hero_player, table, state):\n \"\"\"\n Called by the game, requesting a response from the agent.\n \"\"\"\n\n q_values = self.model.get_q_values(states=state)[0]\n\n\n if self.set_fold_q:\n norm_fold_value = self.min_max_scaling(-1, 1, 0, 2, hero_player.stack / hero_player.prev_stack)\n q_values[3] = norm_fold_value\n\n # norm_reward_hill = lambda x, k: x**1 / (k**1 + x**1 + 1e-12)\n # q_values[0] = norm_reward_hill(q_values[0], 1.0)\n\n\n processed_q_values, valid_idxs = self.q_value_processing_v3(q_values, hero_player, table)\n # valid_idxs = [0, 1]\n # min_max_scaling = lambda a, b, min_x, max_x, x: a + ((x - min_x) * (b - a)) / (max_x - min_x)\n\n # q_values[3] = hero_player.stack / hero_player.prev_stack\n count_states = self.model.get_count_states()\n\n # Determine the action that the agent must take in the game-environment.\n # The epsilon is just used for printing further below.\n action, epsilon = self.epsilon_greedy.get_action(q_values=processed_q_values,\n iteration=count_states,\n training=self.training,\n valid_idxs=valid_idxs)\n \n\n # Card.print_pretty_cards(table.board)\n # print(self.agent_name, Card.print_pretty_cards(hero_player.hand))\n # print(\"Q-values: \", self.action_space[action])\n # print(\"\")\n # if self.agent_name == \"model_6\":\n # Card.print_pretty_cards(hero_player.hand)\n # Card.print_pretty_cards(table.board)\n # print(\"Q-values: \", q_values)\n # print(\"current stack: \", hero_player.stack)\n # print(\"current bet: \", table.current_bet)\n # print(\"Q-values: \", self.action_space[action])\n # print(\"\")\n\n # if self.write_state_action:\n # self.generate_state_action_data(state, q_values, table, hero_player)\n\n # else:\n self.episode_states.append(state)\n self.episode_q_values.append(q_values)\n self.episode_actions.append(action)\n self.episode_epsilons.append(epsilon)\n\n return action\n\n\n def update_end_hand_reward(self, end_hand_reward):\n total_investment = np.sum(self.hand_rewards) / len(self.hand_rewards)\n\n if total_investment == 0.0:\n proportional_rewards = [0.0 for x in self.hand_rewards]\n proportional_rewards[0] = end_hand_reward / len(self.hand_rewards)\n\n else:\n proportional_rewards = [(end_hand_reward * x) / total_investment for x in self.hand_rewards]\n\n # print(end_hand_reward)\n # print(self.hand_rewards)\n # print(proportional_rewards)\n # print(\"\")\n # updated_hand_rewards = [x + end_hand_reward for x in self.hand_rewards]\n \n for x in proportional_rewards:\n self.episode_rewards.append(x)\n\n self.hand_rewards = []\n\n def update_end_episode_reward(self, end_episode_reward):\n self.episode_rewards = [x + end_episode_reward for x in self.episode_rewards]\n\n def update_replay_memory(self):\n \"\"\"\n Needs to be called at the end of an episode, then we update\n \"\"\"\n win_rate = 0\n\n # Counter for the number of episodes we have processed.\n count_episodes = self.model.increase_count_episodes()\n \n is_full = False\n # episode_rewards = [0 for i in range(len(self.episode_states))]\n # episode_rewards[-1] = end_hand_reward\n\n # If we want to train the Neural Network to better estimate Q-values.\n if self.training:\n for x in range(len(self.episode_states)):\n end_episode = False\n\n # Add the state of the game-environment to the replay-memory.\n self.replay_memory.add(state=self.episode_states[x],\n q_values=self.episode_q_values[x],\n action=self.episode_actions[x],\n reward=self.episode_rewards[x],\n end_episode=end_episode)\n\n self.model.increase_count_states()\n\n\n # print(self.episode_rewards)\n\n\n # How much of the replay-memory should be used.\n count_states = self.model.get_count_states()\n use_fraction = self.replay_fraction.get_value(iteration=count_states)\n\n print(self.replay_memory.used_fraction())\n # print(self.replay_memory.used_fraction())\n # print(\"\")\n \n\n # When the replay-memory is sufficiently full.\n\n if self.replay_memory.is_full() \\\n or self.replay_memory.used_fraction() > use_fraction:\n \n is_full = True\n\n\n print(\"fraction full\")\n # Update all Q-values in the replay-memory through a backwards-sweep.\n self.replay_memory.update_all_q_values()\n print(np.around(self.replay_memory.estimation_errors,decimals=2))\n # print(self.replay_memory.estimation_errors)\n # exit()\n\n # Log statistics for the Q-values to file.\n\n # Get the control parameters for optimization of the Neural Network.\n # These are changed linearly depending on the state-counter.\n learning_rate = self.learning_rate_control.get_value(iteration=count_states)\n loss_limit = self.loss_limit_control.get_value(iteration=count_states)\n max_epochs = self.max_epochs_control.get_value(iteration=count_states)\n\n # Perform an optimization run on the Neural Network so as to\n # improve the estimates for the Q-values.\n # This will sample random batches from the replay-memory.\n loss_mean, acc = self.model.optimize(learning_rate=learning_rate, loss_limit=loss_limit, max_epochs=max_epochs)\n\n mean_epsilon = np.mean(self.episode_epsilons)\n\n print()\n msg = \"{0:.1f}, {1:.4f}, {2:.3f}, {3}, {4:.4f}\\n\".format(count_states, learning_rate, mean_epsilon, loss_mean, acc)\n with open(file=self.checkpoint_dir + \"train_data.txt\", mode='a', buffering=1) as file:\n file.write(msg)\n\n # Reset the replay-memory. This throws away all the data we have\n # just gathered, so we will have to fill the replay-memory again.\n self.replay_memory.reset()\n\n self.reset_episode_rewards()\n\n return is_full\n\n\n\n def train_from_history_csv(self, learning_rate):\n history_path = self.checkpoint_dir + \"state_reward.csv\"\n \n print(\"Reading csv...\")\n df = pd.read_csv(history_path)\n\n df_shape = np.shape(df)\n\n # make column names\n col_names = [\"state_\" + str(i) for i in range(df_shape[1] - 2)]\n col_names.append(\"action\")\n col_names.append(\"reward\")\n df.columns = col_names\n\n states = df.loc[:, df.columns != 'action']\n states = states.loc[:, states.columns != 'reward'].values\n\n actions = df['action'].values\n rewards = df['reward'].values\n\n self.replay_memory = ReplayMemory(size=len(actions), state_shape=self.state_shape,\n num_actions=self.num_actions, checkpoint_dir=self.checkpoint_dir)\n\n self.replay_memory.save_state_reward = False\n # Create the Neural Network used for estimating Q-values.\n self.model = NeuralNetwork(model_name=self.agent_name, input_shape=self.state_shape, num_actions=self.num_actions, \n checkpoint_dir=self.checkpoint_dir, replay_memory=self.replay_memory, training=self.training)\n\n states = np.array(states)\n\n print(\"Generating Q values...\")\n q_values = self.model.get_q_values(states=states)\n\n print(\"Adding states to replay memory\")\n # Get Q value predictions and add to replay memory\n for idx in range(len(actions)):\n\n # Add the state of the game-environment to the replay-memory.\n self.replay_memory.add(state=states[idx],\n q_values=q_values[idx],\n action=actions[idx],\n reward=rewards[idx],\n end_episode=False)\n\n print(\"Updating Q values\")\n self.replay_memory.update_all_q_values()\n\n # Get the control parameters for optimization of the Neural Network.\n # These are changed linearly depending on the state-counter.\n # learning_rate = self.learning_rate_control.get_value(iteration=count_states)\n # loss_limit = self.loss_limit_control.get_value(iteration=count_states)\n # max_epochs = self.max_epochs_control.get_value(iteration=count_states)\n\n # Perform an optimization run on the Neural Network so as to\n # improve the estimates for the Q-values.\n # This will sample random batches from the replay-memory.\n print(\"Running optimization\")\n loss_mean, acc = self.model.optimize(learning_rate=learning_rate, loss_limit=0, max_epochs=1)\n\n\n\n","sub_path":"agent.py","file_name":"agent.py","file_ext":"py","file_size_in_byte":21121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"652149577","text":"# -*- coding: utf-8 -*-\n\nimport sys\nimport os\n\n\nclass Tree:\n TAB = ' | '\n\n def __init__(self, HIDE, LIMIT, DEPTH):\n self.dir_id = 0\n self.dir_list = []\n\n self.HIDE = HIDE\n self.LIMIT = LIMIT\n self.DEPTH = DEPTH\n\n def __dir(self, path, depth):\n name = path[:]\n if name != '/': name = name.split('/')[-2]\n print(self.__class__.TAB * depth + '◊' + name + '/' + ' (' + str(self.dir_id) + ')')\n\n self.dir_id += 1\n self.dir_list.append(path)\n if self.LIMIT and depth > self.DEPTH: return\n\n for name_ in os.listdir(path):\n if self.HIDE and name_.startswith('.'): continue\n\n path_ = path + name_\n if os.path.isdir(path_):\n try:\n self.__dir(path_ + '/', depth + 1)\n except:\n # raise Exception('hoe')\n pass\n else:\n try:\n size = str(os.stat(path_).st_size)\n l = len(size)\n if l > 9:\n size = size[:l-9] + 'G'\n elif l > 6:\n size = size[:l-6] + 'M'\n elif l > 3:\n size = size[:l-3] + 'K'\n except:\n size = ''\n\n print(self.__class__.TAB * (depth + 1) + '' + name_ + ' ' + size)\n\n\n def start(self):\n path = os.getcwd()\n if path != '/':\n path += '/'\n self.__dir(path, 0)\n\n f = open(os.environ['HOME'] + '/.mycommand/.dir_list', 'w')\n sys.stdout = f\n for dir_path in self.dir_list:\n print(dir_path)\n sys.stdout = sys.__stdout__\n\n\n# class Tree end\n\n\ndef main():\n depth = 1\n try:\n mode = sys.argv[1]\n hide = True if mode.find('a') == -1 else False\n limit = True if mode.find('m') == -1 else False\n\n if not mode.find('l') == -1:\n try:\n level = sys.argv[2]\n if level.isdigit():\n depth = int(level)\n except: pass\n except:\n hide = True\n limit = True\n\n tree = Tree(hide, limit, depth)\n tree.start()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"223736526","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom config import config\nimport utils\nfrom datetime import datetime\nfrom one_ids import oneIds\nimport random\n\n\nclass MsgGetter:\n def get_ciba_msg(self):\n '''\n 从词霸中获取每日一句,带英文。\n :return:str ,返回每日一句(双语)\n '''\n print('获取格言信息(双语)...')\n resp = requests.get('http://open.iciba.com/dsapi')\n if resp.status_code == 200 and utils.isJson(resp):\n conentJson = resp.json()\n content = conentJson.get('content')\n note = conentJson.get('note')\n return f\"{content}\\n{note}\\n\"\n else:\n print(\"没有获取到数据\")\n return None\n\n def get_dictum_msg(self):\n '''\n 获取格言信息(从『一个。one』获取信息 http://wufazhuce.com/)\n :return: str, 一句格言或者短语\n '''\n print('获取格言信息...')\n user_url = 'http://wufazhuce.com/'\n resp = requests.get(user_url, headers=config.headers)\n if resp.status_code == 200:\n soup_texts = BeautifulSoup(resp.text, 'lxml')\n # 『one -个』 中的每日一句\n every_msg = soup_texts.find_all('div', class_='fp-one-cita')[0].find('a').text\n return every_msg + \"\\n\"\n print('每日一句获取失败')\n return ''\n\n def get_random_ONE_msg(self):\n url = \"http://wufazhuce.com/one/\"\n random_id = random.Random().randint(0, len(oneIds) - 1)\n resp = requests.get(url + str(random_id), headers=config.headers)\n if resp.status_code == 200:\n soup_texts = BeautifulSoup(resp.text, 'lxml')\n msg = soup_texts.find_all(\"div\", class_='one-cita')[0].text\n return msg + \"\\n\"\n return ''\n\n def get_lovelive_msg(self):\n '''\n 从土味情话中获取每日一句。\n :return: str,土味情话\n '''\n print('获取土味情话...')\n resp = requests.get(\"https://api.lovelive.tools/api/SweetNothings\")\n if resp.status_code == 200:\n return resp.text + \"\\n\"\n else:\n print('每日一句获取失败')\n return None\n\n def get_weather_msg(self, city_code):\n weather_url = f'http://t.weather.sojson.com/api/weather/city/{city_code}'\n resp = requests.get(url=weather_url)\n if resp.status_code == 200 and utils.isJson(resp) and resp.json().get('status') == 200:\n weatherJson = resp.json()\n # 今日天气\n today_weather = weatherJson.get('data').get('forecast')[1]\n # 今日日期\n today_time = datetime.now().strftime('%Y{y}%m{m}%d{d} %H:%M:%S').format(y='年', m='月', d='日')\n # 今日天气注意事项\n notice = today_weather.get('notice')\n # 温度\n high = today_weather.get('high')\n high_c = high[high.find(' ') + 1:]\n low = today_weather.get('low')\n low_c = low[low.find(' ') + 1:]\n temperature = f\"温度 : {low_c}/{high_c}\"\n\n # 风\n fx = today_weather.get('fx')\n fl = today_weather.get('fl')\n wind = f\"{fx} : {fl}\"\n\n # 空气指数\n aqi = today_weather.get('aqi')\n aqi = f\"空气 : {aqi}\"\n return f'{notice}\\n{temperature}\\n{wind}\\n{aqi}\\n'\n return \"\"\n\n def get_delta_msg(self, start):\n if start:\n try:\n start_datetime = datetime.strptime(start, \"%Y-%m-%d\")\n day_delta = (datetime.now() - start_datetime).days\n delta_msg = f'宝贝这是我们在一起的第 {day_delta} 天。\\n'\n except:\n delta_msg = ''\n else:\n delta_msg = ''\n return delta_msg\n\n def get_today_time(self):\n return datetime.now().strftime('%Y{y}%m{m}%d{d} %H:%M:%S').format(y='年', m='月', d='日') + \"\\n\"\n\n def get_drink_msg(self):\n strs = ['快喝水!!!', '起来走达走达喝点水', '起来溜达溜达喝点水', '久坐对身体不好,起来喝点水', '快起来喝水']\n r = random.Random()\n return strs[r.randint(0, len(strs) - 1)]\n\n def get_msg_by_channel(self, channel):\n channelToMsgFunc = {1: self.get_random_ONE_msg, 2: self.get_ciba_msg, 3: self.get_lovelive_msg}\n if channelToMsgFunc[channel]:\n return channelToMsgFunc[channel]()\n return ''\n\n\nmsgGetter = MsgGetter()\n","sub_path":"msg_getter.py","file_name":"msg_getter.py","file_ext":"py","file_size_in_byte":4559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"118285034","text":"import json\nimport os\nfrom typing import List\n\nfrom terminaltables import AsciiTable\n\nimport commands.config as cfg\nimport commands.data as data\nimport commands.format as fmt\n\n\ndef find_images() -> List[data.Image]:\n images = []\n for image_dir_name in os.listdir(cfg.IMAGE_DIR):\n image_dir = os.path.join(cfg.IMAGE_DIR, image_dir_name)\n with open(os.path.join(image_dir, 'manifest.json'), 'r') as manifest_file:\n manifest = json.loads(manifest_file.read())\n\n layers_path = os.path.join(image_dir, 'layers')\n\n size = sum(\n os.path.getsize(os.path.join(layers_path, layer))\n for layer in os.listdir(layers_path) if os.path.isfile(os.path.join(layers_path, layer))\n )\n\n # デフォルトのコマンドを取得する\n state = json.loads(manifest['history'][0]['v1Compatibility'])\n cmd = state['config']['Cmd']\n\n # working dirを取得する\n working_dir = state['config']['WorkingDir']\n working_dir = working_dir if working_dir else None\n\n\n image = data.Image(manifest['name'], manifest['tag'], size, cmd, image_dir, working_dir)\n images.append(image)\n\n return images\n\n\ndef run_images():\n print('fetching images')\n images = find_images()\n header = [['name', 'version', 'size', 'path']]\n data = header + [[img.name, img.version, fmt.sizeof_fmt(img.size), img.dir] for img in images]\n table = AsciiTable(data)\n print(table.table)\n","sub_path":"commands/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"428845944","text":"import re\r\ndef linear_search(lst,element):\r\n\telement=str(element)\r\n\tprint(lst)\r\n\tfor element in lst:\r\n\t\tprint(\"lst: \", len(lst))\r\n\t\tprint(\"Search.element: \" ,element)\r\n\t\t#if element==i:\r\n\t\tprint('found in position:', lst.index(element) )\r\n\t\tbreak \r\ndef main():\r\n\tliste=str(input('Enter the list here: '))\r\n\tliste=re.split(\"\\s\",liste)\r\n\tprint(\"type: \", type(liste) )\r\n\tsearch=int(input('Enter you search element: '))\r\n\tlinear_search(liste,search)\r\nif __name__=='__main__':\r\n\tmain()\t\r\n\r\n\r\n","sub_path":"linearsearch.py","file_name":"linearsearch.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"546622149","text":"from PIL import Image\nfrom django.db import models\nimport os\nfrom django.conf import settings\nfrom django import forms\nfrom solo.models import SingletonModel\nfrom resizeimage import resizeimage\nfrom io import BytesIO\nfrom django.core.files.base import ContentFile\n\nclass ThumbnailImage(SingletonModel):\n thumbnail_image = models.ImageField(\n upload_to=os.path.join(settings.MEDIA_ROOT, 'thumbs'),\n )\n\n def save(self, *args, **kwargs):\n pil_image_obj = Image.open(self.thumbnail_image)\n new_image = resizeimage.resize_cover(\n pil_image_obj,\n [250, 150],\n validate=False\n )\n\n new_image_io = BytesIO()\n new_image.save(new_image_io, format='PNG')\n\n temp_name = self.thumbnail_image.name\n self.thumbnail_image.delete(save=False)\n\n self.thumbnail_image.save(\n temp_name,\n content=ContentFile(new_image_io.getvalue()),\n save=False\n )\n\n super(ThumbnailImage, self).save(*args, **kwargs)\n\n\nclass ThumbnailImageForm(forms.Form):\n thumbnail_image = forms.FileField(\n label='Select a file',\n )\n","sub_path":"mapstory/apps/thumbnails/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"113724581","text":"import sys, getopt\nimport re\n\n# change suite name in output.xml to incorporate config parameters\ndef main(argv):\n \n try:\n opts, args = getopt.getopt(argv,\"h\",[\"modem=\",\"plan=\"])\n except getopt.GetoptError:\n print('python conv.py --modem --plan ')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print('python conv.py --modem --plan ')\n sys.exit()\n elif opt==\"--modem\":\n modem = arg\n elif opt==\"--plan\":\n plan = arg \n \n fpi = open(\"output.xml\",\"r\")\n \n # replace suite name with suite name followed by input parameters, separated by . \n xml_input = fpi.read()\n match = re.search('name=\"(.*?)\"',xml_input)\n result = match.groups()[0]\n modem_type = re.sub(r'^(.*?)-.*',r'\\1',modem)\n plan_string = re.sub(r'\\s',r'_',plan) \n xml_output = re.sub(result,result+\".\"+modem_type+\".\"+plan_string,xml_input)\n\n fpi.close()\n fpo = open(\"output.xml\",\"w\")\n fpo.write(xml_output)\n fpo.close()\n \nif __name__ == \"__main__\":\n main(sys.argv[1:])\n \n\n","sub_path":"tools/jenkins/convxml.py","file_name":"convxml.py","file_ext":"py","file_size_in_byte":1079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"71262271","text":"#!/usr/bin/env python\nfrom serial import Serial, EIGHTBITS, PARITY_NONE, STOPBITS_ONE\nfrom sys import argv\nimport time\nimport binascii\nassert len(argv) == 2\ns = Serial(\n port=argv[1],\n baudrate=115200,\n bytesize=EIGHTBITS,\n parity=PARITY_NONE,\n stopbits=STOPBITS_ONE,\n xonxoff=False,\n rtscts=False,\n timeout=0.0001,\n write_timeout=1\n)\n\ndef int2bytes(i):\n hex_string = \"%x\" %i\n n = len(hex_string)\n return binascii.unhexlify(hex_string.zfill(n+(n&1)))\n\ndef check(s, data):\n print(\"123\")\n w = s.read()\n print(\"fff\")\n while(w == b'0'):\n print(\"1111\")\n s.write(data)\n print(\"not ok\")\n w = s.read()\n \n'''\nwith open('fc', 'rb') as f:\n count = 0\n for b in f.read():\n b = int2bytes(b)\n print(\"1234\")\n s.write(b)\n check(s, b)\n count += 1\n \n'''\n\n\n\n\nfor i in range (1,100):\n a = int2bytes(i)\n print (a)\n s.write(a)\n\na = int2bytes(0)\nprint (a)\ns.write(a)\n\n","sub_path":"lab2/pc_python/rs232.py","file_name":"rs232.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"413424253","text":"import tensorflow as tf\n\n# number of inputs\ninput_len = 2\n# number of classes \nclasses_num = 2\n\nsess = tf.Session()\n\nx = tf.placeholder(\"float\", [None, input_len])\ny_ = tf.placeholder(\"float\", [None, classes_num])\n\nweights1 = tf.Variable(tf.truncated_normal([input_len, 50], stddev=0.0001))\nbiases1 = tf.Variable(tf.ones([50]))\n\nweights2 = tf.Variable(tf.truncated_normal([50, 25], stddev=0.0001))\nbiases2 = tf.Variable(tf.ones([25]))\n\nweights3 = tf.Variable(tf.truncated_normal([25, classes_num], stddev=0.0001))\nbiases3 = tf.Variable(tf.ones([classes_num]))\n\n# This time we introduce a single hidden layer into our model...\nhidden_layer_1 = tf.nn.relu(tf.matmul(x, weights1) + biases1)\nhidden_layer_2 = tf.nn.relu(tf.matmul(hidden_layer_1, weights2) + biases2)\nmodel = tf.nn.softmax(tf.matmul(hidden_layer_2, weights3) + biases3)\n\ncost = -tf.reduce_sum(y_*tf.log(model))\n\ntraining_step = tf.train.AdamOptimizer(learning_rate=0.0001).minimize(cost)\n \ninit = tf.initialize_all_variables()\nsess.run(init)\n\nfor ii in range(10000):\n # y_ -> element of correct class only must be 1\n if ii % 2 == 0: # even number [1,2] => 0\n sess.run(training_step, feed_dict={x: [[1, 2]], y_: [[1, 0]]})\n else: # odd number [2,1] => 1\n sess.run(training_step, feed_dict={x: [[2, 1]], y_: [[0, 1]]})\n\n# prediction\nprint(\"result of prediction --------\")\npred_rslt = sess.run(tf.argmax(model, 1), feed_dict={x: [[1, 2]]})\nprint(\" input: [1,2] =>\" + str(pred_rslt))\npred_rslt = sess.run(tf.argmax(model, 1), feed_dict={x: [[2, 1]]})\nprint(\" input: [2,1] =>\" + str(pred_rslt))\n\n","sub_path":"simple_tf_regression.py","file_name":"simple_tf_regression.py","file_ext":"py","file_size_in_byte":1656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"623509853","text":"import base64\nimport importlib\nimport inspect\nimport io\nimport os\nimport re\nimport sys\nimport textwrap\nfrom pathlib import Path\nimport warnings\nfrom redbaron import RedBaron\n\ntry:\n from numpydoc.docscrape import FunctionDoc, ClassDoc\nexcept ImportError as e:\n print('Please install the numpydoc package to build the documentation for Dymos')\n raise e\n\n\ndef define_env(env):\n\n @env.macro\n def inline_source(reference, include_def=True, include_docstring=True, indent_level=0, show_line_numbers=True, highlight_lines=None):\n \"\"\"\n Macro to embed the source code of the given reference into mkdocs.\n\n Parameters\n ----------\n reference : str\n The dotted path to the object whose source is to be displayed.\n include_def : bool\n If True, include the definition of the class, function, or method.\n include_docstring\n If True, include the docstring of the class, function, or method.\n indent_level : int\n The baseline indentation for the source.\n show_line_numbers : bool\n If True, display the line numbers of the source code.\n highlight_lines : sequence or None\n If provided, line numbers to be highlighted in the displayed source.\n\n Returns\n -------\n str\n Markdown-formatted source-code for the given reference.\n\n \"\"\"\n obj = get_object_from_reference(reference)\n\n obj = inspect.unwrap(obj)\n\n source = ''.join(inspect.getsourcelines(obj)[0])\n\n re_declaration = re.compile(r'^(.+?):', flags=(re.DOTALL | re.MULTILINE))\n re_docstring = re.compile(r'(\"\"\".+?\"\"\")', flags=(re.DOTALL | re.MULTILINE))\n\n if not include_def:\n source = re_declaration.sub('', source, count=1)\n if not include_docstring:\n source = re_docstring.sub('', source, count=1)\n\n source = textwrap.dedent(source)\n source = source.strip()\n\n indent = indent_level * ' '\n\n line_numbers = ' linenums=\"1\"' if show_line_numbers else ''\n\n if highlight_lines is not None:\n hl_lines = ' hl_lines=\"' + ' '.join([str(i) for i in highlight_lines]) + '\"'\n else:\n hl_lines = ''\n\n result = f'```python{line_numbers}{hl_lines}\\n{source}\\n```'\n\n return textwrap.indent(result, indent)\n\n @env.macro\n def embed_plot_from_script(script_path, alt_text='', width=640, height=480):\n \"\"\"\n Macro to embed a plot figure obtained by executing a script at the given path.\n\n Currently this only saves the last plot produced by the script.\n\n Parameters\n ----------\n script_path : str\n Path to the plot-generating script.\n alt_text : str\n Alternative text for the plots, for 508 compliance.\n width : int\n Width of the embedded plot, in pixels.\n height : int\n Height of the embedded plot, in pixels.\n\n Returns\n -------\n str\n An html image tag with the encoded plot data, used to directly include the given plot\n in mkdocs.\n\n \"\"\"\n import matplotlib.pyplot as plt\n\n plt.switch_backend('Agg')\n d = dict(locals(), **globals())\n\n dir_path = get_parent_dir(env)\n path_to_script = dir_path.joinpath(script_path)\n\n exec(open(path_to_script).read(), d, d)\n\n buf = io.BytesIO()\n plt.tight_layout()\n plt.savefig(buf, format='png')\n data = base64.b64encode(buf.getbuffer()).decode('ascii')\n return f'\"{alt_text}\"'\n\n @env.macro\n def embed_test_output(reference):\n \"\"\"\n Macro to embed a unittest.TestCase method in mkdocs.\n\n Return a markdown-formatted output from a test given by reference.\n\n The embedded test **must be decorated with the dymos.utils.doc_utils.save_for_docs** decorator!\n\n Parameters\n ----------\n reference : str\n The path to the embedded test method.\n\n Returns\n -------\n str\n Markdown-formatted output of the given test method.\n\n \"\"\"\n test_case, test_method = reference.split('.')[-2:]\n testcase_obj = get_object_from_reference('.'.join(reference.split('.')[:-1]))\n test_dir = Path(inspect.getfile(testcase_obj)).parent\n output_file = test_dir.joinpath('_output').joinpath(f'{test_case}.{test_method}.out')\n with open(output_file) as f:\n text = f.read()\n return f'```\\n{text}\\n```'\n\n @env.macro\n def embed_test_plot(reference, index=1, alt_text='', width=640, height=480):\n \"\"\"\n Macro to embed a unittest.TestCase method plot in mkdocs.\n\n The test method is embedded as a set of tabs.\n The embedded test **must be decorated with the dymos.utils.doc_utils.save_for_docs** decorator!\n\n The first tab contains the test source.\n The second tab contains the test standard output.\n The remaining tabs display any matplotlib plots generated in the test, which are selected using the plots argument.\n\n Parameters\n ----------\n reference : str\n The path to the embedded test method.\n index : int\n The index of the plot to be embedded.\n alt_text : str\n Alternative text for the plots, for 508 compliance.\n width : int\n Width of the embedded plot, in pixels.\n height : int\n Height of the embedded plot, in pixels.\n\n Returns\n -------\n str\n The markdown source that provides the embedded plot file, encoded directly as html\n \"\"\"\n test_case, test_method = reference.split('.')[-2:]\n testcase_obj = get_object_from_reference('.'.join(reference.split('.')[:-1]))\n test_dir = Path(inspect.getfile(testcase_obj)).parent\n plot_file = test_dir.joinpath('_output').joinpath(f'{test_case}.{test_method}_{index}.png')\n\n with open(plot_file, 'rb') as f:\n buf = io.BytesIO(f.read())\n\n data = base64.b64encode(buf.getbuffer()).decode(\"ascii\")\n return f'\"{alt_text}\"'\n\n @env.macro\n def embed_test(reference, script_name='script', plot_alt_text='', plots=None, plot_size=(640, 480),\n show_output=True, show_script=True, plot_names=None):\n \"\"\"\n Macro to embed a unittest.TestCase method source, output, and plots in mkdocs.\n\n The test method is embedded as a set of tabs.\n The embedded test **must be decorated with the dymos.utils.doc_utils.save_for_docs** decorator!\n\n The first tab contains the test source.\n The second tab contains the test standard output.\n The remaining tabs display any matplotlib plots generated in the test, which are selected using the plots argument.\n\n Parameters\n ----------\n reference : str\n The path to the embedded test method.\n script_name : str\n A heading for the test being run.\n plot_alt_text : str\n Alternative text for the plots, for 508 compliance.\n plots : tuple of ints or None\n The plots being requested (indexed at 1) or None for all plots.\n plot_size : tuple of width, height in pixels.\n The size of the plot figures being embedded in the markdown.\n show_output : bool\n Show output tab if True.\n show_script : bool\n Show script tab if True.\n plot_names : sequence of str or None\n If given, a sequence of tab titles to be assigned to the plots.\n\n Returns\n -------\n str\n The markdown source that provides a set of tabs for the test source, the test\n output, and the requested plots produced by the test.\n \"\"\"\n ss = io.StringIO()\n # First tab for the source\n if show_script:\n src = textwrap.indent(_get_test_source(reference), ' ')\n print(f'=== \"{script_name}\"', file=ss)\n print(' ```python3', file=ss)\n print(src, file=ss)\n print(' ```', file=ss)\n\n # Second tab for the output\n test_case, test_method = reference.split('.')[-2:]\n testcase_obj = get_object_from_reference('.'.join(reference.split('.')[:-1]))\n test_dir = Path(inspect.getfile(testcase_obj)).parent\n\n if show_output:\n output_file = test_dir.joinpath('_output').joinpath(f'{test_case}.{test_method}.out')\n with open(output_file) as f:\n text = f.read()\n\n print(f'=== \"output\"', file=ss)\n print(' ```', file=ss)\n print(textwrap.indent(text, ' '), file=ss)\n print(' ```', file=ss)\n\n # Remaining tabs are for plots\n\n for index in range(1, 100):\n if plots is None or index in plots:\n plot_file = test_dir.joinpath('_output').joinpath(f'{test_case}.{test_method}_{index}.png')\n if not os.path.exists(plot_file):\n break\n\n with open(plot_file, 'rb') as f:\n buf = io.BytesIO(f.read())\n\n data = base64.b64encode(buf.getbuffer()).decode(\"ascii\")\n width, height = plot_size\n try:\n plot_name = plot_names[index-1] if plot_names else f'{index}'\n except:\n plot_name = f'{index}'\n print(f'=== \"plot {plot_name}\"\\n', file=ss)\n print(f' \"{plot_alt_text}\"\\n', file=ss)\n\n return ss.getvalue()\n\n @env.macro\n def embed_options(reference, title=''):\n \"\"\"\n Macro to embed an OpenMDAO OptionsDictionary in mkdocs.\n\n Parameters\n ----------\n reference : str\n The dotted path to the options dictionary class or instance being documented.\n title : str\n The title provided above the options table.\n\n Returns\n -------\n str\n A markdown-formatted table for the entries in the options dictionary.\n\n \"\"\"\n from openmdao.api import OptionsDictionary\n options_dict = get_object_from_reference(reference)\n\n if isinstance(options_dict, OptionsDictionary):\n od = options_dict\n elif issubclass(options_dict, OptionsDictionary):\n od = options_dict()\n else:\n return f'Invalid OptionsDictionary: {reference}'\n\n return f'{title}\\n{_options_dict_to_markdown(od)}'\n\n @env.macro\n def doc_env():\n \"Document the environment\"\n return {name:getattr(env, name) for name in dir(env) if not name.startswith('_')}\n\n @env.macro\n def api_doc(reference, members=None):\n \"\"\"\n Embed API documentation of the given function, class, or method.\n\n Parameters\n ----------\n reference : str\n The path to the API function, class, or method being documented.\n members : sequence or None\n If reference is a class, the members of the class to be documented.\n Each will be displayed on a separate tab of the output.\n\n Returns\n -------\n str\n The markdown representation of the API documentation.\n\n \"\"\"\n\n module = '.'.join(reference.split('.')[:-1])\n item = reference.split('.')[-1]\n\n obj = getattr(get_object_from_reference(module), item)\n\n ss = io.StringIO()\n\n if inspect.isfunction(obj):\n _function_doc_markdown(obj, reference, outstream=ss)\n elif inspect.isclass(obj):\n _class_doc_markdown(obj, reference, members=members, outstream=ss)\n elif inspect.ismethod(obj):\n _function_doc_markdown(obj, reference, outstream=ss)\n\n return ss.getvalue()\n\n @env.macro\n def upgrade_doc(reference, feature, old_label='previous', new_label='updated'):\n \"\"\"\n This macro embeds an \"upgrade guide\" from the given reference string.\n\n In this case, the reference should point to a test method.\n The test method should document the new/preferred way of doing something.\n\n In the body of the test method, this macro searches for the\n strings '# upgrade_doc: begin {name}' and '# upgrade_doc: end {name}'\n where {name} is some feature to be demonstrated. The code between those comments will\n be documented in a tab-enclosed code-block with the label as given by 'new_label'.\n\n If old/deprecated behavior is to be shown for comparison, this should be placed in the\n test method's doc string between the '# upgrade_doc: begin {name}' and\n '# upgrade_doc: end {name}' strings. If present, this code will be shown in a separate\n tab-enclosed code-block with the label given by 'old_label'.\n\n Parameters\n ----------\n reference : str\n The path to the upgrade test for the given feature.\n feature : str\n The name of the feature whose use is to be documented.\n old_label : str\n The tab label for the tab showing the old/deprecated behavior (if present).\n new_label : str\n The tab label for the tab showing the new/preferred behavior.\n\n Returns\n -------\n str\n The markdown representation of the API documentation.\n\n \"\"\"\n ss = io.StringIO()\n _upgrade_doc_markdown(reference, feature, outstream=ss,\n old_label=old_label, new_label=new_label)\n return ss.getvalue()\n\n\ndef get_object_from_reference(reference):\n split = reference.split('.')\n right = []\n module = None\n while split:\n try:\n module = importlib.import_module('.'.join(split))\n break\n except ModuleNotFoundError:\n right.append(split.pop())\n if module:\n for entry in reversed(right):\n module = getattr(module, entry)\n return module\n\n\ndef get_parent_dir(env):\n page_path = Path(env.variables.page.url)\n full_path = Path(env.conf['docs_dir']).joinpath(page_path)\n dir_path = full_path.parents[0]\n return dir_path\n\n\ndef _get_test_source(reference):\n \"\"\"\n Return the source code from the test specified by the gien reference.\n\n Parameters\n ----------\n reference : str\n A dotted path to the test method whose source is desired.\n\n Returns\n -------\n str\n The returned source, dedented and having had assert method calls removed.\n\n \"\"\"\n obj = get_object_from_reference(reference)\n try:\n method = obj._method\n except AttributeError:\n raise RuntimeError(f'To embed test {reference} in documentation, it must be wrapped with the dymos.utils.doc_utils.save_for_docs decorator')\n\n func_name = reference.split('.')[-1]\n\n source = ''.join(inspect.getsourcelines(method)[0])\n\n re_declaration = re.compile(rf'(def {func_name}\\(.+?\\):)', flags=(re.DOTALL | re.MULTILINE))\n\n match_dec = re_declaration.search(source)\n\n start = match_dec.span()[1]\n\n # Strip off decorators and the test method declaration\n source = source[start:]\n\n source = textwrap.dedent(source)\n source = source.strip()\n\n # Remove the assert method calls from documentation.\n source = _strip_asserts(source)\n\n return source\n\ndef _strip_asserts(source):\n \"\"\"\n Remove assert method calls from source code.\n\n Using RedBaron, replace some assert calls with print statements that print the actual\n value given in the asserts. Depending on the calls, the actual value can be the first or second\n argument.\n\n Parameters\n ----------\n source : str\n String containing source lines.\n\n Returns\n -------\n str\n Source with asserts removed.\n \"\"\"\n rb = RedBaron(source) # convert to RedBaron internal structure\n\n # findAll is slow, so only check the ones that are present.\n asserts = ['assertAlmostEqual', 'assertLess', 'assertGreater', 'assertEqual',\n 'assert_equal_arrays', 'assertTrue', 'assertFalse', 'assert_near_equal',\n 'assert_rel_error', 'assert_almost_equal', 'assert_allclose']\n\n for assert_type in asserts:\n assert_nodes = rb.findAll(\"NameNode\", value=assert_type)\n for i in reversed(range(len(assert_nodes))):\n parent = assert_nodes[i].parent\n for j in reversed(range(len(parent.value))):\n assert_nodes[i].parent.remove(parent.value[j])\n\n return rb.dumps()\n\ndef _function_doc_markdown(func, reference, outstream=sys.stdout, indent='', method=False):\n \"\"\"\n Generate markdown documentation for the given function object.\n\n Parameters\n ----------\n func : function\n The function object to be documented.\n reference : str\n The dotted path to the function in the API.\n\n Returns\n -------\n str\n The markdown representation of the function documentation.\n \"\"\"\n doc = FunctionDoc(func)\n\n sig = func.__name__ + str(inspect.signature(func))\n\n if not method:\n print(f'{indent}!!! abstract \"{reference}\"\\n', file=outstream)\n else:\n print(f'{indent}!!! abstract \"\"\\n', file=outstream)\n indent = indent + ' '\n\n print(f\"{indent}**{sig}**\\n\", file=outstream)\n print('', file=outstream)\n\n if doc['Summary']:\n txt = textwrap.indent('\\n'.join(doc['Summary']), indent) + '\\n'\n print(txt, file=outstream)\n\n if doc['Extended Summary']:\n txt = textwrap.indent('\\n'.join(doc['Extended Summary']), indent) + '\\n'\n print(txt, file=outstream)\n\n print('', file=outstream)\n\n print(f'{indent}**Arguments:**\\n', file=outstream)\n\n for p in doc['Parameters']:\n print(f'{indent}**{p.name}**: {\" \".join(p.desc)}', file=outstream)\n print('', file=outstream)\n\n if doc['Raises']:\n print('{indent}**Raises:**\\n', file=outstream)\n\n for p in doc['Raises']:\n print(f'{indent}**{p.name}**: {\" \".join(p.desc)}', file=outstream)\n print('', file=outstream)\n\n\ndef _class_doc_markdown(cls, reference, members=None, outstream=sys.stdout, indent=''):\n \"\"\"\n\n Parameters\n ----------\n cls\n reference\n members\n outstream\n\n Returns\n -------\n\n \"\"\"\n doc = ClassDoc(cls)\n\n print(f'{indent}### class {reference}\\n', file=outstream)\n\n indent = indent + ''\n\n if doc['Summary']:\n print(indent + ' '.join(doc['Summary']), file=outstream)\n\n if doc['Extended Summary']:\n print(indent + ' '.join(doc['Extended Summary']) + '\\n', file=outstream)\n\n print('', file=outstream)\n print(f\"{indent}**{doc['Signature']}**\\n\", file=outstream)\n\n print(f'{indent}**Public API Methods:**\\n', file=outstream)\n\n for p in doc['Methods']:\n if members is not None and p.name in members:\n ref = '.'.join((reference, p.name))\n print(f'{indent}=== \"{p.name}\"\\n', file=outstream)\n _function_doc_markdown(getattr(cls, p.name), ref, outstream=outstream, indent=indent + \" \", method=True)\n\n\ndef _options_dict_to_markdown(od):\n \"\"\"\n Generate a markdown-formatted table to document the options dictionary.\n\n Returns\n -------\n str\n A markdown table representation of the options dictionay.\n \"\"\"\n return od.to_table(fmt='github')\n\n\ndef _split_docstring(obj):\n docstring = inspect.getdoc(obj)\n lines = inspect.getsourcelines(obj)[0]\n docstring_start = docstring_end = -1\n for i, line in enumerate(lines):\n # print(line)\n if line.strip().startswith('\"\"\"') or line.strip().startswith(\"'''\"):\n if docstring_start >= 0:\n docstring_end = i\n break\n else:\n docstring_start = i\n func_body = ''.join(lines[:docstring_start]) + ''.join(lines[docstring_end + 1:])\n return docstring, func_body\n\ndef _upgrade_doc_markdown(test_reference, feature, outstream=sys.stdout,\n old_label='previous', new_label='updated'):\n obj = get_object_from_reference(test_reference)\n docstring, func_body = _split_docstring(obj)\n\n re_feature = re.compile(rf'# upgrade_doc: begin {feature}(.+?)# upgrade_doc: end {feature}',\n flags=re.MULTILINE|re.DOTALL)\n\n doc_match = re_feature.search(docstring) if docstring else None\n body_match = re_feature.search(func_body)\n\n try:\n old_way = textwrap.dedent(doc_match.groups()[0])\n except AttributeError:\n warnings.warn(f'Unable to find feature label {feature} in the doc string of {test_reference}')\n old_way = None\n try:\n new_way = textwrap.dedent(body_match.groups()[0])\n except AttributeError:\n raise ValueError(f'Unable to find feature label {feature} in the body of {test_reference}')\n\n indent = ' '\n\n print(f'=== \"{new_label}\"', file=outstream)\n print(f'{indent}```', file=outstream)\n print(f'{textwrap.indent(new_way, indent)}', file=outstream)\n print(f'{indent}```', file=outstream)\n\n if old_way:\n print(f'=== \"{old_label}\"', file=outstream)\n print(f'{indent}```', file=outstream)\n print(f'{textwrap.indent(old_way, indent)}', file=outstream)\n print(f'{indent}```', file=outstream)\n\n\nif __name__ == '__main__':\n obj =_upgrade_doc_markdown('dymos.test.test_upgrade_guide.TestUpgrade_0_16_0.test_glob_timeseries_outputs',\n 'glob_timeseries_outputs')\n","sub_path":"mkdocs/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":21688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"342635007","text":"from __future__ import print_function\nimport argparse\nimport torch.nn as nn\nfrom models.resnet import ResNet20, ResNet50\nimport torch.optim as optim\nfrom torchvision import datasets, transforms, models\nimport torch.utils.data.distributed\nimport horovod.torch as hvd\nimport os\nimport wandb\nimport time\n\nhvd.init()\nglobal_step = 0\n\ndef metric_average(val, name):\n tensor = torch.tensor(val)\n avg_tensor = hvd.allreduce(tensor, name=name)\n return avg_tensor.item()\n\n\ncriterion = nn.CrossEntropyLoss()\n\n\ndef train(log_interval, model, device, train_loader, optimizer, epoch, train_sampler):\n global global_step\n model.train()\n # Horovod: set epoch to sampler for shuffling.\n train_sampler.set_epoch(epoch)\n for batch_idx, (data, target) in enumerate(train_loader):\n global_step += 1\n start = time.time()\n data, target = data.to(device), target.to(device)\n optimizer.zero_grad()\n output = model(data)\n loss = criterion(output, target)\n loss.backward()\n optimizer.step()\n end = time.time()\n if batch_idx % log_interval == 0:\n # Horovod: use train_sampler to determine the number of examples in\n # this worker's partition.\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(train_sampler),\n 100. * batch_idx / len(train_loader), loss.item()))\n wandb.log({\"epoch\": epoch, \"loss\": loss.item(), \"total_throughput\": hvd.size()*len(data)/(end-start)}, step=global_step)\n\n\ndef test(model, device, test_loader, test_sampler, epoch):\n global global_step\n model.eval()\n test_loss = 0.\n test_accuracy = 0.\n with torch.no_grad():\n for data, target in test_loader:\n data, target = data.to(device), target.to(device)\n output = model(data)\n # sum up batch loss\n test_loss += criterion(output, target).item()\n # get the index of the max log-probability\n pred = output.data.max(1, keepdim=True)[1]\n test_accuracy += pred.eq(target.data.view_as(pred)).float().sum().item()\n\n # Horovod: use test_sampler to determine the number of examples in\n # this worker's partition.\n test_loss /= len(test_sampler)\n test_accuracy /= len(test_sampler)\n\n # Horovod: average metric values across workers.\n test_loss = metric_average(test_loss, 'avg_loss')\n test_accuracy = metric_average(test_accuracy, 'avg_accuracy')\n\n # Horovod: print output only on first rank.\n if hvd.rank() == 0:\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {:.2f}%\\n'.format(\n test_loss, test_accuracy))\n\n wandb.log({\n \"Test Accuracy\": test_accuracy,\n \"Test Loss\": test_loss,\n \"epoch\": epoch}, step=global_step)\n\n\ndef main():\n parser = argparse.ArgumentParser(description='PyTorch CIFAR10 Example')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--seed', type=int, default=42, metavar='S',\n help='random seed (default: 42)')\n parser.add_argument('--log-interval', type=int, default=10, metavar='N',\n help='how many batches to wait before logging training status')\n\n parser.add_argument('--model', default='resnet20')\n parser.add_argument('--data_name', default='imagenet')\n parser.add_argument(\"--data-dir\", default=\"data\")\n parser.add_argument(\"--log-dir\", default=\"log\", help='not used, for compatibility')\n\n parser.add_argument('--optimizer', default='momentum')\n parser.add_argument('--epochs', type=int, default=400)\n parser.add_argument('--momentum', type=float, default=0.9)\n parser.add_argument('--weight_decay', type=float, default=0.0001)\n parser.add_argument('--test-batch-size', type=int, default=256)\n parser.add_argument('--batch-size', type=int, default=256)\n parser.add_argument('--lr', type=float, default=0.001)\n\n args = parser.parse_args()\n use_cuda = not args.no_cuda and torch.cuda.is_available()\n\n torch.manual_seed(args.seed)\n\n if use_cuda:\n # Horovod: pin GPU to local rank.\n torch.cuda.set_device(hvd.local_rank())\n torch.cuda.manual_seed(args.seed)\n\n device = torch.device(\"cuda\" if use_cuda else \"cpu\")\n\n kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {}\n\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n train_dataset = datasets.CIFAR10(args.data_dir, train=True, download=True, transform=transform_train)\n # Horovod: use DistributedSampler to partition the training data.\n train_sampler = torch.utils.data.distributed.DistributedSampler(\n train_dataset, num_replicas=hvd.size(), rank=hvd.rank())\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=args.batch_size, sampler=train_sampler, **kwargs)\n\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n test_dataset = datasets.CIFAR10(args.data_dir, train=False, transform=transform_test)\n\n # Horovod: use DistributedSampler to partition the test data.\n test_sampler = torch.utils.data.distributed.DistributedSampler(\n test_dataset, num_replicas=hvd.size(), rank=hvd.rank())\n test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=args.test_batch_size,\n sampler=test_sampler, **kwargs)\n\n if args.model == 'resnet20':\n model = ResNet20()\n elif args.model == 'resnet50':\n model = ResNet50()\n else:\n raise NotImplemented('model not implemented')\n\n # Move model to GPU.\n model.to(device)\n\n # Horovod: scale learning rate by the number of GPUs.\n if args.optimizer=='sgd':\n optimizer = optim.SGD(model.parameters(), lr=args.lr * hvd.size(), weight_decay=args.weight_decay)\n else:\n optimizer = optim.SGD(model.parameters(), lr=args.lr * hvd.size(), momentum=args.momentum, weight_decay=args.weight_decay)\n\n # Horovod: broadcast parameters & optimizer state.\n hvd.broadcast_parameters(model.state_dict(), root_rank=0)\n hvd.broadcast_optimizer_state(optimizer, root_rank=0)\n\n if hvd.rank()!=0:\n os.environ['WANDB_MODE'] = 'dryrun'\n wandb_id = os.environ.get('WANDB_ID', None)\n if wandb_id is None:\n wandb.init(config=args)\n else:\n wandb.init(config=args, id=f\"{wandb_id}{hvd.rank()}\")\n wandb.config.update({'SLURM_JOB_ID': os.environ.get('SLURM_JOB_ID', None)})\n # wandb.watch(model)\n\n # Horovod: wrap optimizer with DistributedOptimizer.\n optimizer = hvd.DistributedOptimizer(optimizer,\n named_parameters=model.named_parameters())\n\n\n for epoch in range(1, args.epochs + 1):\n train(args.log_interval, model, device, train_loader, optimizer, epoch, train_sampler)\n test(model, device, test_loader, test_sampler, epoch)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/pytorch_cifar10.py","file_name":"pytorch_cifar10.py","file_ext":"py","file_size_in_byte":7314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"528431605","text":"import time\nimport logging\n\nfrom urllib3.exceptions import HTTPError\n\nfrom .error import SolutionNotReady, OperationTimeout, NoSlotAvailable\nfrom .base_backend import BaseBackend\n\nlogger = logging.getLogger('captcha_solution.solver')\nDEFAULT_SUBMIT_TASK_TIMEOUT = 30\nDEFAULT_CHECK_RESULT_TIMEOUT = 120\nDEFAULT_NETWORK_TIMEOUT = 5\n\n\nclass CaptchaSolver(object):\n def __init__(\n self,\n backend,\n api_key=None,\n submit_task_timeout=DEFAULT_SUBMIT_TASK_TIMEOUT,\n check_result_timeout=DEFAULT_CHECK_RESULT_TIMEOUT,\n ):\n self.api_key = api_key\n if isinstance(backend, BaseBackend):\n self.backend = backend\n else:\n self.backend = BaseBackend.get_backend_class(backend)(\n api_key=self.api_key\n )\n self.submit_task_timeout = submit_task_timeout\n self.check_result_timeout = check_result_timeout\n\n def submit(self, data=None):\n start = time.time() \n while True:\n if time.time() - start > self.submit_task_timeout:\n raise OperationTimeout(\n 'Could not submit task in %d seconds'\n % self.submit_task_timeout\n )\n try:\n return self.backend.submit(data=data)\n except (NoSlotAvailable, HTTPError, OSError) as ex:\n logger.debug('Retrying to submit task. Error is %s' % ex)\n time.sleep(3)\n\n def check_result(self, task_id):\n start = time.time() \n while True:\n if time.time() - start > self.check_result_timeout:\n raise OperationTimeout(\n 'Could not get task result in %d seconds'\n % self.check_result_timeout\n )\n try:\n return self.backend.check_result(task_id)\n except (SolutionNotReady, HTTPError, OSError) as ex:\n logger.debug('Retrying to get task result. Error is %s' % ex)\n time.sleep(3)\n\n def solve(self, data=None):\n task_id = self.submit(data)['task_id']\n while True:\n try:\n res = self.check_result(task_id)\n except SolutionNotReady as ex:\n logger.debug('Solution is not ready for task %s' % task_id)\n else:\n return res\n time.sleep(2)\n\n def get_balance(self):\n return self.backend.get_balance()\n","sub_path":"captcha_solution/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"32376402","text":"#Write a python program which shows use of math and time module.\nimport time\nprint (\"Select the Module. \\n1.Math Module \\n2.Time Module \\n\")\n\nnum=int(input())\n\nif num==1:\n pi=22/7\n degree = float(input(\"Input degrees: \"))\n radian = degree*(pi/180)\n print(radian)\nelif num==2:\n localtime = time.asctime(time.localtime(time.time()))\n print (\"Local current time :\", localtime)\nelse:\n print(\"Invalid select..\")\n","sub_path":"Assignment 2/Question 1/Question 1.py","file_name":"Question 1.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"507629944","text":"import subprocess as sp\nimport requests\nimport cv2\nimport numpy\n\nx=sp.getoutput(\"cat /run/media/root/BA66-832E/pd.txt\")\ny=sp.getoutput(\"pwd\")\nurl=x\n\nwhile True:\n data=requests.get(url)\n myphoto=data.content\n myphoto_a=bytearray(myphoto)\n photo_1d=numpy.array(myphoto_a)\n photo_3d=cv2.imdecode(photo_1d, -1)\n cv2.imshow('stream',photo_3d)\n if cv2.waitKey(1)==13:\n break\ncv2.destroyAllWindows()\n\n\nprint(x)\nprint(y)\n","sub_path":"May 17/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"526057191","text":"import uuid\nfrom datetime import datetime\nfrom common_utilities import errors\nfrom ulapd_api.app import app\nfrom ulapd_api.exceptions import ApplicationError\nfrom ulapd_api.extensions import db\nfrom ulapd_api.models.user_details import UserDetails\nfrom ulapd_api.models.user_type import UserType\nfrom ulapd_api.models.licence import Licence\nfrom ulapd_api.models.user_terms_link import UserTermsLink\nfrom ulapd_api.models.dataset import Dataset\nfrom ulapd_api.models.activity import Activity\nfrom ulapd_api.models.contact import Contact\nfrom ulapd_api.utilities.decorators import handle_errors\nfrom ulapd_api.dependencies.account_api import AccountAPI, update_groups_for_ldap\nfrom ulapd_api.dependencies.verification_api import VerificationAPI\n\n\n@handle_errors(is_get=True)\ndef get_all_users():\n users = _extract_rows(UserDetails.get_user_details_all())\n user_list = []\n for user in users:\n user_type = get_user_type(user['user_type_id'])\n user_dict = {\n 'user_details': user,\n 'user_type': user_type\n }\n user_list.append(user_dict)\n\n return user_list\n\n\n@handle_errors(is_get=True)\ndef get_user_by_key(user_data):\n if user_data['key'] == 'user_details_id':\n user = UserDetails.get_user_details_by_id(user_data['value'])\n elif user_data['key'] == 'email':\n user = UserDetails.get_user_details_by_email(user_data['value'])\n elif user_data['key'] == 'api_key':\n user = UserDetails.get_user_details_by_api_key(user_data['value'])\n elif user_data['key'] == 'ldap_id':\n user = UserDetails.get_user_details_by_ldap_id(user_data['value'])\n else:\n raise ApplicationError('Incorrect key: {}'.format(user_data['key']), 'E101', http_code=404)\n\n if user:\n user_details = user.as_dict()\n user_type = get_user_type(user_details['user_type_id'])\n user_details['user_type'] = user_type\n contact_preferences = _build_contact_preferences(\n _extract_rows(Contact.get_contact_preferences_for_user(user_details['user_details_id'])))\n user_details['contact_preferences'] = contact_preferences\n user_dict = {\n 'user_details': user_details,\n 'datasets': _build_users_datasets(user_details['user_details_id'])\n }\n return user_dict\n else:\n raise ApplicationError(*errors.get('ulapd_api', 'USER_NOT_FOUND', filler=user_data['value']), http_code=404)\n\n\n@handle_errors(is_get=True)\ndef get_user_details(user_id):\n user_details = UserDetails.get_user_details_by_id(user_id)\n if user_details:\n result = user_details.as_dict()\n else:\n app.logger.error(\"User '{}' not found\".format(user_id))\n raise ApplicationError(*errors.get('ulapd_api', 'USER_NOT_FOUND', filler=user_id), http_code=404)\n\n return result\n\n\n@handle_errors(is_get=True)\ndef get_user_type(type_id):\n user_type = UserType.get_user_type_by_id(type_id)\n if user_type:\n result = user_type.as_dict()\n else:\n app.logger.error(\"User type '{}' not found\".format(type_id))\n raise ApplicationError(*errors.get('ulapd_api', 'USER_TYPE_NOT_FOUND', filler=type_id), http_code=404)\n\n return result\n\n\n@handle_errors(is_get=True)\ndef get_user_licences(user_id):\n return _extract_rows(UserTermsLink.get_user_terms_by_user_id(user_id))\n\n\n@handle_errors(is_get=True)\ndef get_licence_agreement(user_id, licence_name):\n result = {\n 'user_id': user_id,\n 'licence': licence_name,\n 'valid_licence': False,\n 'date_agreed': None\n }\n\n licence = UserTermsLink.get_user_terms_by_licence_name(user_id, licence_name)\n if licence:\n result['valid_licence'] = _check_agreement(licence_name, licence.date_agreed)\n result['date_agreed'] = licence.date_agreed\n return result\n\n\n@handle_errors(is_get=False)\ndef manage_licence_agreement(data):\n try:\n user = UserDetails.get_user_details_by_id(data['user_details_id'])\n if not user:\n app.logger.error(\"No user found for id {}\".format(data['user_details_id']))\n raise ApplicationError(*errors.get('ulapd_api', 'USER_NOT_FOUND',\n filler=data['user_details_id']), http_code=404)\n\n # check to see if user already has this type of licence\n ldap_update_needed = True\n licence_data = _extract_rows(Licence.get_licences_by_dataset_name(data['licence_id']))\n for rows in licence_data:\n user_licence = UserTermsLink.get_user_terms_by_licence_name(user.user_details_id, rows['licence_id'])\n if user_licence:\n app.logger.info('User {} already has the role {} so not updating ldap...'.format(user.user_details_id,\n data['licence_id']))\n ldap_update_needed = False\n\n stored_licence_id = data['licence_id']\n if _check_freemium(data['licence_id']):\n data['licence_id'] += '_direct'\n licence = UserTermsLink(data)\n db.session.add(licence)\n\n if ldap_update_needed:\n app.logger.info('User {} does not have the role {} so update ldap...'.format(user.user_details_id,\n stored_licence_id))\n _handle_ldap_group(stored_licence_id, user.ldap_id, True)\n\n db.session.commit()\n data['link_id'] = licence.user_terms_link_id\n return data\n except Exception as e:\n app.logger.error('Failed to manage licence for user {} with error - {}'.format(data['user_details_id'],\n str(e)))\n db.session.rollback()\n db.session.close()\n raise ApplicationError(*errors.get('ulapd_api', 'LICENCE_AGREE_ERROR', filler=e), http_code=400)\n\n\n@handle_errors(is_get=False)\ndef manage_multi_licence_agreement(data):\n try:\n user = UserDetails.get_user_details_by_id(data['user_details_id'])\n if not user:\n app.logger.error(\"No user found for id {}\".format(data['user_details_id']))\n raise ApplicationError(*errors.get('ulapd_api', 'USER_NOT_FOUND',\n filler=data['user_details_id']), http_code=404)\n\n current_licences = _extract_rows(UserTermsLink.get_user_terms_by_user_id(data['user_details_id']))\n current_list = [d['licence_id'] for d in current_licences]\n\n all_licences = Licence.get_all_licences()\n licence_dict = {}\n for rows in all_licences:\n licence_dict[rows.licence_name] = rows.dataset_name\n\n groups = {}\n for row in data['licences']:\n if row['licence_id'] not in current_list and row['agreed']:\n app.logger.info('Adding licence {} to db and ldap'.format(row['licence_id']))\n role = licence_dict[row['licence_id']]\n groups[role] = row['agreed']\n new_user_licence = UserTermsLink({'user_details_id': user.user_details_id,\n 'licence_id': row['licence_id']})\n db.session.add(new_user_licence)\n elif row['licence_id'] in current_list and not row['agreed']:\n app.logger.info('Removing licence {} from db and ldap'.format(row['licence_id']))\n role = licence_dict[row['licence_id']]\n groups[role] = row['agreed']\n UserTermsLink.delete_user_licence_agreement(user.user_details_id, row['licence_id'])\n else:\n app.logger.info('There is no change for licence {}'.format(row['licence_id']))\n\n # sort out freemium\n res_covs = [d for d in data['licences'] if 'res_cov' in d['licence_id']]\n groups = _handle_ldap_freemium_updates('res_cov', res_covs, groups, current_list)\n\n if bool(groups):\n app.logger.info('Sending these groups - {}, for ldap update for user {}'.format(groups,\n user.user_details_id))\n update_groups_for_ldap(user.ldap_id, groups)\n else:\n app.logger.info('No groups to update in ldap for user {}'.format(user.user_details_id))\n\n db.session.commit()\n return groups\n except Exception as e:\n app.logger.error('Failed to manage multi licences for user {} with error - {}'.format(data['user_details_id'],\n str(e)))\n db.session.rollback()\n db.session.close()\n raise ApplicationError(*errors.get('ulapd_api', 'LICENCE_AGREE_ERROR', filler=e), http_code=400)\n\n\n@handle_errors(is_get=True)\ndef get_dataset_activity(user_id):\n user = UserDetails.get_user_details_by_id(user_id)\n if user:\n return _build_user_dataset_activity(user_id)\n else:\n app.logger.error(\"No user found for id {}\".format(user_id))\n raise ApplicationError(*errors.get('ulapd_api', 'USER_NOT_FOUND', filler=user_id), http_code=404)\n\n\n@handle_errors(is_get=False)\ndef create_new_user(user_data):\n try:\n account = AccountAPI()\n verification = VerificationAPI()\n app.logger.info('Creating user in ldap for {}'.format(user_data['email']))\n response = account.create(user_data)\n user_data['ldap_id'] = response['user_id']\n\n user_data = _process_new_user_data(user_data)\n app.logger.info('Adding user {} to the ulapd database...'.format(user_data['email']))\n new_user_details = UserDetails(user_data)\n db.session.add(new_user_details)\n db.session.commit()\n user_data['user_details_id'] = new_user_details.user_details_id\n\n if user_data['contactable']:\n app.logger.info('Inserting the contact preferences for {}...'.format(user_data['email']))\n for preference in user_data['contact_preferences']:\n contact = {\n 'user_details_id': user_data['user_details_id'],\n 'contact_type': preference\n }\n contact_preference = Contact(contact)\n db.session.add(contact_preference)\n db.session.commit()\n app.logger.info('Finished adding user {} to the ulapd database...'.format(user_data['email']))\n\n # Add the user details to verification database for DST\n app.logger.info('Adding user {} to verification db...'.format(user_data['email']))\n verification.create(user_data)\n\n # Call to account-api to activate or acknowledge user\n is_uk_org = 'organisation-uk' in user_data['user_type']\n\n if is_uk_org:\n app.logger.info('Acknowledging user')\n account.acknowledge(user_data['ldap_id'])\n else:\n app.logger.info('Activating user')\n account.activate(user_data['ldap_id'])\n\n db.session.close()\n return user_data\n except Exception as e:\n app.logger.error('Failed to create user with error - {}'.format(str(e)))\n db.session.rollback()\n _delete_user_data(account, user_data)\n db.session.close()\n raise ApplicationError(*errors.get('ulapd_api', 'CREATE_USER_ERROR', filler=e), http_code=400)\n\n\n@handle_errors(is_get=False)\ndef delete_user(user_id):\n try:\n UserTermsLink.delete_user_by_user_id(user_id)\n Activity.delete_user_by_user_id(user_id)\n Contact.delete_contact_preferences_for_user(user_id)\n\n user = UserDetails.get_user_details_by_id(user_id)\n if user:\n db.session.delete(user)\n else:\n app.logger.error(\"No user: {} found for deletion\".format(user_id))\n db.session.rollback()\n db.session.close()\n raise ApplicationError(*errors.get('ulapd_api', 'USER_NOT_FOUND', filler=user_id), http_code=404)\n db.session.commit()\n return {'user_id': user_id, 'message': 'user deleted'}\n except Exception as e:\n db.session.rollback()\n db.session.close()\n raise ApplicationError(*errors.get('ulapd_api', 'DELETE_USER_ERROR', filler=e), http_code=400)\n\n\n@handle_errors(is_get=False)\ndef update_contact_preference(user_data):\n user = UserDetails.get_user_details_by_id(user_data['user_id'])\n if user:\n app.logger.info('Deleting contact preferences for user {}'.format(user_data['user_id']))\n\n Contact.delete_contact_preferences_for_user(user_data['user_id'])\n for contacts in user_data['contact_preferences']:\n contact = {\n 'user_details_id': user_data['user_id'],\n 'contact_type': contacts\n }\n contact_preference = Contact(contact)\n db.session.add(contact_preference)\n\n user.contactable = user_data['contactable']\n db.session.commit()\n user_details = user.as_dict()\n user_details['contact_preferences'] = user_data['contact_preferences']\n return user_details\n else:\n raise ApplicationError(*errors.get('ulapd_api', 'USER_NOT_FOUND', user_data['user_id']), http_code=404)\n\n\n@handle_errors(is_get=False)\ndef update_api_key(user_id):\n try:\n user = UserDetails.get_user_details_by_id(user_id)\n if user:\n user.api_key = _create_api_key()\n db.session.commit()\n return get_user_details(user_id)\n else:\n raise ApplicationError(*errors.get('ulapd_api', 'USER_NOT_FOUND', filler=user_id), http_code=404)\n\n except Exception as e:\n raise ApplicationError(*errors.get('ulapd_api', 'RESET_API_KEY_ERROR', filler=e), http_code=400)\n\n\n@handle_errors(is_get=True)\ndef get_users_dataset_access(user_id):\n user = UserDetails.get_user_details_by_id(user_id)\n if user:\n datasets = Dataset.get_all()\n dataset_access = []\n\n for row in datasets:\n if row.type != 'open':\n dataset_dict = {\n 'id': row.dataset_id,\n 'name': row.name,\n 'title': row.title,\n 'type': row.type\n }\n licence_names = _extract_rows(Licence.get_licences_by_dataset_name(row.name))\n\n licence_dict = {}\n for licence_rows in licence_names:\n licence = get_licence_agreement(user_id, licence_rows['licence_id'])\n licence_dict[licence_rows['licence_id']] = {\n 'title': licence_rows['title'],\n 'agreed': licence['valid_licence']\n }\n\n dataset_dict['licences'] = licence_dict\n dataset_access.append(dataset_dict)\n\n dataset_access = _sort_out_sample(dataset_access)\n\n licenced_datasets = [d for d in dataset_access if d['type'] == 'licenced']\n non_licenced_datasets = [d for d in dataset_access if d['type'] != 'licenced']\n\n full_access = non_licenced_datasets\n full_access.append(_sort_out_licenced_datasets(licenced_datasets))\n return full_access\n else:\n app.logger.error(\"No user found for id {}\".format(user_id))\n raise ApplicationError(*errors.get('ulapd_api', 'USER_NOT_FOUND', filler=user_id), http_code=404)\n\n\ndef _extract_rows(rows):\n return [row.as_dict() for row in rows]\n\n\ndef _check_agreement(licence_name, date_agreed):\n converted_date = date_agreed.date()\n agreed = False\n licence = Licence.get_licence_by_licence_name(licence_name)\n if licence and licence.last_updated <= converted_date:\n agreed = True\n return agreed\n\n\ndef _process_new_user_data(user_data):\n user_data['api_key'] = _create_api_key()\n user_data['user_type_id'] = _get_user_type_id(user_data['user_type'])\n for key, value in user_data.items():\n if value == '':\n user_data[key] = None\n\n if user_data['contact_preferences'] is not None and len(user_data['contact_preferences']) > 0:\n user_data['contactable'] = True\n else:\n user_data['contactable'] = False\n return user_data\n\n\ndef _get_user_type_id(user_type):\n user_type_data = UserType.get_user_id_by_type(user_type)\n user_type_dict = user_type_data.as_dict()\n return user_type_dict['user_type_id']\n\n\ndef _create_api_key():\n return str(uuid.uuid4())\n\n\ndef _build_users_datasets(user_id):\n user_licences = _extract_rows(UserTermsLink.get_user_terms_by_user_id(user_id))\n dataset_access = {}\n for rows in user_licences:\n licence = get_licence_agreement(user_id, rows['licence_id'])\n if licence['valid_licence']:\n licence_data = Licence.get_licence_by_licence_name(rows['licence_id'])\n dataset_data = Dataset.get_dataset_by_name(licence_data.dataset_name)\n if dataset_data.name in dataset_access:\n dataset_access[dataset_data.name]['licences'].append(licence_data.title)\n dataset_access[dataset_data.name]['date_agreed'] = None\n else:\n dataset_access[dataset_data.name] = {'date_agreed': str(licence['date_agreed']),\n 'private': dataset_data.private,\n 'valid_licence': licence['valid_licence'],\n 'licence_type': dataset_data.type,\n 'licences': [licence_data.title]}\n\n # Need to sort freemium licences into their correct order\n for key, value in dataset_access.items():\n if value['licence_type'] == 'freemium':\n value['licences'] = sorted(value['licences'], key=_order_freemium_licences)\n return dataset_access\n\n\ndef _delete_user_data(account, data):\n account.delete(data['ldap_id'])\n delete_user(data['user_details_id'])\n return\n\n\ndef _build_user_dataset_activity(user_id):\n dataset = Dataset.get_all()\n dataset_activity = []\n for row in dataset:\n dataset_dict = {\n 'id': row.dataset_id,\n 'name': row.name,\n 'private': row.private,\n 'title': row.title,\n 'licence_agreed': False,\n 'download_history': _get_dataset_downloads(user_id, row.name)\n }\n\n licence_names = _extract_rows(Licence.get_licences_by_dataset_name(row.name))\n\n if len(licence_names) > 1:\n for licence in licence_names:\n this_licence = get_licence_agreement(user_id, licence['licence_id'])\n if this_licence['valid_licence']:\n dataset_dict['licence_agreed'] = True\n break\n else:\n licence = get_licence_agreement(user_id, row.licence_name)\n if licence['valid_licence']:\n dataset_dict['licence_agreed'] = True\n converted_date = datetime.strftime(licence['date_agreed'], '%Y-%m-%dT%H:%M:%S.%f')\n dataset_dict['licence_agreed_date'] = str(converted_date)\n dataset_activity.append(dataset_dict)\n return dataset_activity\n\n\ndef _get_dataset_downloads(user_id, name):\n activities = Activity.get_user_activity_by_dataset(user_id, name)\n downloads = []\n for download in activities:\n if download.activity_type == 'download':\n converted_date = datetime.strftime(download.timestamp, '%Y-%m-%dT%H:%M:%S.%f')\n download_dict = {\n 'date': str(converted_date),\n 'file': download.file\n }\n downloads.append(download_dict)\n\n return downloads\n\n\ndef _build_contact_preferences(contact_preferences):\n return [row['contact_type'] for row in contact_preferences]\n\n\ndef _sort_out_sample(dataset_access):\n # for showing dataset access add sample licence info to parent and remove from the list\n for rows in dataset_access:\n if rows['name'][-7:] == '_sample':\n main_dataset = rows['name'][:-7]\n index = next((index for (index, d) in enumerate(dataset_access) if d[\"name\"] == main_dataset), None)\n sample_licence = rows['licences'][rows['name']]\n dataset_access[index]['licences'][main_dataset]['title'] = 'Full dataset'\n sample_licence['title'] = 'Sample'\n dataset_access[index]['licences'][rows['name']] = sample_licence\n\n return [d for d in dataset_access if d['name'][-7:] != '_sample']\n\n\ndef _sort_out_licenced_datasets(licenced_datasets):\n # for showing dataset access licenced datasets need to be lumped together under free datasets\n licenced_dict = {\n 'name': 'licenced',\n 'title': 'Free datasets',\n }\n\n free_dict = {}\n for items in licenced_datasets:\n item_licence = items['licences']\n item_licence[items['name']]['title'] = items['title']\n free_dict.update(item_licence)\n licenced_dict['licences'] = free_dict\n return licenced_dict\n\n\ndef _handle_ldap_group(licence, ldap_id, agreed):\n account = AccountAPI()\n payload = {\n 'ldap_id': ldap_id,\n 'groups': {\n licence: agreed\n }\n }\n return account.handle_role(payload)\n\n\ndef _check_freemium(dataset):\n details = Dataset.get_dataset_by_name(dataset)\n return True if details.type == 'freemium' else False\n\n\ndef _handle_ldap_freemium_updates(freemium_type, freemium_list, groups, current_list):\n agreed_freemium = [d for d in freemium_list if d['agreed']]\n if len(agreed_freemium) > 0 and freemium_type in groups:\n if freemium_type in str(current_list):\n app.logger.info('user already has role {} so not updating ldap'.format(freemium_type))\n del groups[freemium_type]\n else:\n groups[freemium_type] = True\n elif len(agreed_freemium) == 0 and freemium_type in str(current_list):\n direct_licence = freemium_type + '_direct'\n if direct_licence in str(current_list) and freemium_type in groups:\n app.logger.info('user has direct licence for role {} so not updating ldap'.format(freemium_type))\n del groups[freemium_type]\n else:\n groups[freemium_type] = False\n\n return groups\n\n\ndef _order_freemium_licences(item):\n func_list = ['Direct Use', 'Exploration', 'Commercial']\n return func_list.index(item)\n","sub_path":"ulapd_api/services/user_service.py","file_name":"user_service.py","file_ext":"py","file_size_in_byte":22387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"123367039","text":"#!/usr/bin/python3\ndef uppercase(str):\n for i in str:\n lower = ord(i)\n if lower > 96 and lower < 123:\n check = True\n else:\n check = False\n print(\"{:c}\".format((lower - 32) if check else lower), end='')\n print(\"\")\n","sub_path":"0x01-python-if_else_loops_functions/8-uppercase.py","file_name":"8-uppercase.py","file_ext":"py","file_size_in_byte":269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"399126581","text":"from django.shortcuts import render, redirect, HttpResponse \n# Using Django Messages: https://docs.djangoproject.com/en/1.11/ref/contrib/messages/#displaying-messages \nfrom django.contrib import messages \nfrom .models import * \nimport bcrypt\n \n \n \n# Create your views here. \ndef index(request): \n return render(request, 'login_reg/index.html')\n\ndef register(request):\n \n reg_errors = User.objects.registration_validator(request.POST)\n\n #validate registration\n if len(reg_errors):\n for k, v in reg_errors.items():\n messages.error(request,v)\n return redirect('/')\n\n else:\n # hashedPW = bcrypt.hashpw(request.POST['password'].encode(), bcrypt.gensalt()).decode()\n # newUser = User.objects.create(first_name=request.POST['first_name'], last_name=request.POST['last_name'], email=request.POST['email'], pw_hash = hashedPW, date_of_birth=request.POST['dob'])\n\n newUser = User.objects.new_user(request.POST)\n request.session['cur_user'] = newUser.id\n return redirect('/welcome/')\n\ndef login(request):\n login_errors = User.objects.login_validator(request.POST)\n thisUser = User.objects.filter(email = request.POST[\"login_email\"])\n #validate login\n if len(login_errors) or len(thisUser) <= 0:\n for k, v in login_errors.items():\n messages.info(request, v)\n return redirect('/')\n else:\n request.session['cur_user'] = thisUser.first().id\n return redirect('/welcome/')\n\n\ndef welcome(request):\n if not 'cur_user' in request.session:\n return redirect('/')\n else:\n thisUser = User.objects.get(id = request.session['cur_user'])\n context = {\n \"user\" : thisUser,\n }\n\n return render(request, 'login_reg/welcome.html', context)\n\n\n\ndef destroy(request):\n request.session.flush()\n return redirect('/')\n\n\ndef reg_ajax(request):\n # check email uniqueness\n\n emailExists = False\n allEmails = User.objects.filter(email=request.POST['email'])\n\n if len(allEmails) > 0:\n emailExists = True\n \n context = {\n \"emailExists\" : emailExists,\n }\n\n return render(request, 'login_reg/partials/unique_email.html', context)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"apps/login_reg/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"183611139","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Aug 13 10:12:51 2018\r\n\r\n@author: juan.zarco\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport seaborn as sns\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.model_selection import train_test_split, cross_val_predict, learning_curve, KFold, ShuffleSplit, cross_val_score,GridSearchCV\r\nfrom sklearn.decomposition import PCA\r\nfrom sklearn.metrics import mean_squared_error, r2_score, explained_variance_score\r\nfrom sklearn.ensemble import GradientBoostingRegressor, AdaBoostRegressor, RandomForestRegressor, BaggingRegressor\r\nfrom sklearn.linear_model import HuberRegressor, ElasticNet, ElasticNetCV, LinearRegression, Lasso, LassoCV, Ridge, RidgeCV\r\nimport sys\r\nimport Data_Exploration as de\r\nfrom Cross_Validation_Plotting import plot_learning_curve\r\nfrom operator import itemgetter\r\nimport time\r\nimport copy\r\nfrom sklearn.pipeline import make_pipeline\r\nfrom sklearn.preprocessing import RobustScaler\r\nimport xgboost as xgb\r\nimport lightgbm as lgb\r\nfrom scipy import stats\r\n\r\nld = 0\r\n\r\ndef aggeregate_models(models):\r\n models_ = tuple(models)\r\n names = []\r\n for model in models_:\r\n names.append(model.__name__)\r\n pass\r\n\r\ndef invboxcox(y,ld):\r\n if ld == 0:\r\n return(np.exp(y))\r\n else:\r\n return(np.exp(np.log(ld*y+1)/ld))\r\n\r\ndef avg_meta_model(X,y,n_folds,base_models,meta):\r\n kfold = KFold(n_splits=n_folds,shuffle=True,random_state=156)\r\n base_models_ = copy.copy(base_models)\r\n out_of_fold_predictions = np.zeros((X.shape[0], len(base_models)))\r\n #print('Matrix shape oof pred: ',out_of_fold_predictions.shape)\r\n for i,model in enumerate(base_models_):\r\n for train_index,holdout_index in kfold.split(X,y):\r\n instance = copy.copy(model)\r\n instance.fit(X[train_index],y[train_index])\r\n y_pred = instance.predict(X[holdout_index])\r\n #print('holdout_index: ',holdout_index)\r\n #print(holdout_index.shape)\r\n out_of_fold_predictions[holdout_index,i] = y_pred\r\n \r\n #out_of_fold_predictions = out_of_fold_predictions.mean(axis=1).reshape(X.shape[0],1) \r\n #X_new = np.append(X,out_of_fold_predictions)\r\n return meta.fit(out_of_fold_predictions,y)\r\n\r\ndef meta_predict(X,meta,base_models_fit):\r\n test_predictions = np.zeros((X.shape[0],len(base_models_fit)))\r\n for i,model in enumerate(base_models_fit):\r\n test_predictions[:,i] = model.predict(X)\r\n #test_predictions = test_predictions.mean(axis=1).reshape(X.shape[0],1)\r\n #X_new = np.append(X,test_predictions)\r\n return meta.predict(test_predictions)\r\n\r\n\r\ndef preprocessing():\r\n train_set = pd.read_csv('train.csv',compression = 'infer')\r\n test_set = pd.read_csv('test.csv', compression = 'infer')\r\n \r\n train_set.set_index(train_set.Id, inplace=True)\r\n test_set.set_index(test_set.Id, inplace=True)\r\n \r\n train_set.drop(['Id'],axis = 1,inplace=True)\r\n test_set.drop(['Id'],axis = 1, inplace=True)\r\n \r\n \r\n total_features_na = de.features_NA_Count(train_set, percentage = True)\r\n #Removing Outliers\r\n fig, ax = plt.subplots()\r\n ax.scatter(x = train_set['GrLivArea'], y = train_set['SalePrice'])\r\n plt.ylabel('SalePrice', fontsize=13)\r\n plt.xlabel('GrLivArea', fontsize=13)\r\n plt.show()\r\n \r\n train_set = train_set.drop(train_set[(train_set['GrLivArea']>4000) & (train_set['SalePrice']<300000)].index)\r\n #Modify the independent variable to transform it into a normal distribution via boxcox\r\n global ld\r\n train_set[\"SalePrice\"],ld = stats.boxcox(train_set[\"SalePrice\"])\r\n \r\n for key,val in sorted(total_features_na.items(), key = itemgetter(1), reverse = True):\r\n print('Total NA for: ', key, ' - ', '{:,.2%}'.format(val))\r\n \r\n #Recoding the values for PoolQC due to the nan associated with a PoolArea value of 0\r\n idx = train_set.PoolArea == 0\r\n \r\n train_set.loc[idx, 'PoolQC'] = 0\r\n \r\n datasets = (train_set,test_set)\r\n \r\n for set_ in datasets:\r\n pool_qc = set(set_.PoolQC)\r\n \r\n qc = {}\r\n iteration = 2\r\n for item in pool_qc:\r\n qc[item] = iteration\r\n iteration = iteration + 2\r\n \r\n set_.replace({'PoolQC': qc},inplace=True)\r\n \r\n train_set = de.DataEncode(train_set)\r\n test_set = de.DataEncode(test_set)\r\n #print('train set shape: ',train_set.shape)\r\n #print('test_set',test_set.shape)\r\n train_set.fillna(value = 0, inplace = True)\r\n test_set.fillna(value = 0, inplace = True)\r\n \r\n for set_ in datasets:\r\n set_.PoolQC = set_.PoolQC.astype('category')\r\n set_.OverallCond = set_.OverallCond.astype('category')\r\n set_.YrSold = set_.YrSold.astype('category')\r\n set_.MoSold = set_.MoSold.astype('category')\r\n \r\n total_features_na = de.features_NA_Count(train_set, percentage = True)\r\n \r\n print('Rechecking data for NA...\\n')\r\n \r\n for key,val in sorted(total_features_na.items(), key = itemgetter(1), reverse = True):\r\n print('Total NA for: ', key, ' - ', '{:,.2%}'.format(val))\r\n #print(train_set.columns)\r\n M = train_set.values\r\n #print('Matrix shape ',M.shape)\r\n X = M[:,0:M.shape[1]-1]\r\n y = M[:,-1]\r\n #print(X.shape)\r\n M_val = test_set.values\r\n \r\n return X,y,M_val\r\n \r\ndef setting_up_model_environment(X,y):\r\n import random\r\n random.seed(123)\r\n X_train, X_test, y_train, y_test = train_test_split(X,y, test_size = 0.3, random_state = 42)\r\n params = {'alpha':[0.00001,0.00005,0.0001,0.0005,0.001,0.005,0.01,0.05,0.1]}\r\n gboost = GradientBoostingRegressor(n_estimators=2000,learning_rate=0.1)\r\n gboost_meta = GradientBoostingRegressor(n_estimators=3000,learning_rate=0.1)\r\n #ada = AdaBoostRegressor(base_estimator=gboost,loss = 'square')\r\n bag = BaggingRegressor(base_estimator=gboost)\r\n bag_2 = BaggingRegressor()\r\n rfg = RandomForestRegressor()\r\n robust = HuberRegressor()\r\n enet = make_pipeline(RobustScaler(),GridSearchCV(ElasticNet(alpha=0.01,max_iter=5000),params))\r\n enet_cv = make_pipeline(RobustScaler(),ElasticNetCV(max_iter=5000))\r\n lm = LinearRegression()\r\n lasso = make_pipeline(RobustScaler(),GridSearchCV(Lasso(alpha = 0.01,max_iter=5000),params))\r\n lasso_cv = make_pipeline(RobustScaler(),LassoCV(max_iter=5000))\r\n ridge = Ridge(alpha=0.001,max_iter=2000)\r\n ridge_grid = GridSearchCV(ridge,params)\r\n ridge_cv = RidgeCV()\r\n model_xgb = xgb.XGBRegressor(colsample_bytree=0.4603, gamma=0.0468, \r\n learning_rate=0.05, max_depth=3, \r\n min_child_weight=1.7817, n_estimators=2200,\r\n reg_alpha=0.4640, reg_lambda=0.8571,\r\n subsample=0.5213, silent=1,\r\n random_state =7, nthread = -1)\r\n model_lgb = lgb.LGBMRegressor(objective='regression',num_leaves=5,\r\n learning_rate=0.05, n_estimators=720,\r\n max_bin = 55, bagging_fraction = 0.8,\r\n bagging_freq = 5, feature_fraction = 0.2319,\r\n feature_fraction_seed=9, bagging_seed=9,\r\n min_data_in_leaf =6, min_sum_hessian_in_leaf = 11)\r\n model_lgb_meta = lgb.LGBMRegressor(objective='regression',num_leaves=5,\r\n learning_rate=0.05, n_estimators=720,\r\n max_bin = 55, bagging_fraction = 0.8,\r\n bagging_freq = 5, feature_fraction = 0.2319,\r\n feature_fraction_seed=9, bagging_seed=9,\r\n min_data_in_leaf =6, min_sum_hessian_in_leaf = 11)\r\n \r\n model_set = (('gradient boost',gboost),('robust',robust),('elastic net', enet),\r\n ('elastic net cv', enet_cv),('ols', lm),('lasso',lasso),('lasso cv',lasso_cv),\r\n ('ridge',ridge_grid),('Random Forest Regressor',rfg),\r\n ('bagging tree',bag_2),('XGBoost',model_xgb),('LGBoost',model_lgb))\r\n \r\n model_environment = (model_set,(X_train,X_test,y_train,y_test))\r\n \r\n base_models = [gboost,rfg,bag_2,model_xgb,model_lgb]\r\n \r\n return model_environment,base_models,ridge_cv\r\n \r\n \r\ndef main():\r\n X,y,M_val = preprocessing()\r\n env,base_models,meta = setting_up_model_environment(X,y)\r\n models = env[0]\r\n data = env[1]\r\n X_train = data[0]\r\n y_train = data[2]\r\n reg_models = []\r\n X_test = data[1]\r\n y_test = data[3]\r\n cv = ShuffleSplit(n_splits=100, test_size=0.3, random_state=0)\r\n \r\n for name,model in models:\r\n print('Learning model: ',name)\r\n plot_learning_curve(model,name,cv=cv, X=X_train, y=y_train,ylim=(0,1.01))\r\n reg_models.append(model.fit(X_train,y_train))\r\n \r\n for model,temp in zip(reg_models,models):\r\n name = temp[0]\r\n print('RMSE Error for model - ', \r\n name,':',\r\n round(mean_squared_error(y_test,model.predict(X_test)) ** 0.5,2))\r\n print('R_2 Score for model - ',\r\n name,':',\r\n r2_score(y_test,model.predict(X_test)))\r\n print('\\n')\r\n \r\n fitted_base_models = [reg_models[i] for i in (0,8,9,10,11)]\r\n \r\n meta_model = avg_meta_model(X,y,5,base_models,meta)\r\n print('MSE Error for model - ', \r\n 'Meta',':',\r\n round(mean_squared_error(y_test,meta_predict(X_test,meta_model,fitted_base_models)) ** 0.5,2))\r\n print('R_2 Score for model - ', \r\n 'Meta',':',\r\n r2_score(y_test,meta_predict(X_test,meta_model,fitted_base_models)))\r\n #plot_learning_curve(meta_model,'Meta',cv=cv, X=X_train, y=y_train,ylim=(0,1.01))\r\n return reg_models,M_val,meta_model,fitted_base_models\r\n\r\nif __name__ == \"__main__\":\r\n model_results,test_set,meta_model,fitted_base_models = main()\r\n predictions = []\r\n test = pd.read_csv('test.csv', compression = 'infer')\r\n ids = test.Id\r\n for model in model_results:\r\n predictions.append(model.predict(test_set))\r\n predictions.append(meta_predict(test_set,meta_model,fitted_base_models))\r\n for i,pred in enumerate(predictions):\r\n predictions[i] = invboxcox(pred,ld)\r\n for i,model in enumerate(model_results):\r\n print(i,': ', model)\r\n print('\\n')\r\n print(i+1,': Meta Model')\r\n print('\\n')\r\n model_num = int(input('Which model predictions would you like to use?'))\r\n \r\n submission = pd.DataFrame(predictions[model_num],index=ids)\r\n submission.to_csv('house_prices_submission_fz.csv')","sub_path":"Housing Prices/housing_prices.py","file_name":"housing_prices.py","file_ext":"py","file_size_in_byte":10622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"55459881","text":"# -*- coding: utf-8 -*-\n###############################################################################\n#\n# Copyright (c) 2019 HERE Europe B.V.\n#\n# SPDX-License-Identifier: MIT\n# License-Filename: LICENSE\n#\n###############################################################################\n\nfrom qgis.PyQt.QtCore import pyqtSignal\nfrom qgis.PyQt.QtWidgets import QDialog\n\nfrom . import get_ui_class\nfrom ..modules import basemap\nfrom ..modules.controller import make_qt_args\n\nBaseMapDialogUI = get_ui_class('basemap_dialog.ui')\nclass BaseMapDialog(QDialog, BaseMapDialogUI):\n signal_add_basemap = pyqtSignal(object)\n\n def __init__(self, parent=None):\n \"\"\"init window\"\"\"\n QDialog.__init__(self, parent)\n BaseMapDialogUI.setupUi(self, self)\n\n def config(self, map_basemap_meta, auth):\n for k,v in map_basemap_meta.items():\n self.comboBox_basemap.addItem(k,v)\n self.lineEdit_app_id.setText( auth.get(\"app_id\",\"\"))\n self.lineEdit_app_code.setText( auth.get(\"app_code\",\"\"))\n \n ############# connect gui\n self.lineEdit_app_id.textChanged.connect(self.ui_valid_input)\n self.lineEdit_app_code.textChanged.connect(self.ui_valid_input)\n self.accepted.connect(self.add_basemap)\n \n self.ui_valid_input()\n def _get_basemap_meta(self):\n return self.comboBox_basemap.currentData()\n def add_basemap(self):\n meta=self._get_basemap_meta()\n app_id = self.lineEdit_app_id.text()\n app_code = self.lineEdit_app_code.text()\n self.signal_add_basemap.emit( make_qt_args(meta, app_id, app_code))\n ###### UI function\n def ui_valid_input(self, flag=None):\n ok = len(self.lineEdit_app_id.text()) > 0 and len(self.lineEdit_app_code.text()) > 0 \n self.ui_enable_ok_button(ok)\n return ok\n def ui_enable_ok_button(self, flag):\n self.buttonBox.button(self.buttonBox.Ok).setEnabled(flag)\n self.buttonBox.button(self.buttonBox.Ok).clearFocus()\n","sub_path":"XYZHubConnector/gui/basemap_dialog.py","file_name":"basemap_dialog.py","file_ext":"py","file_size_in_byte":2001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"308650471","text":"__author__ = 'ejunior'\n\nfrom console.commands import *\n\n\nctx = Context()\n\nwhile ctx.running:\n\n try:\n command = input('RPG> ').strip().lower()\n if command in commandList:\n (commandList[command]).execute(ctx)\n else:\n print('Invalid Command.')\n except Exception:\n raise\n\n","sub_path":"rpg.py","file_name":"rpg.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"381957233","text":"import numpy as np\nimport math\n\nclass Quaternion:\n def __init__(self, scalar=1, vec=[0,0,0]): \n self.q = np.array([scalar, 0., 0., 0.])\n self.q[1:4] = vec\n\n def normalize(self):\n self.q = self.q/np.linalg.norm(self.q)\n\n def scalar(self):\n return self.q[0]\n\n def vec(self):\n return self.q[1:4]\n\n def axis_angle(self):\n theta = 2*math.acos(self.scalar())\n vec = self.vec()\n if (np.linalg.norm(vec) == 0):\n return np.zeros(3)\n vec = vec/np.linalg.norm(vec)\n return vec*theta\n\n def euler_angles(self):\n phi = math.atan2(2*(self.q[0]*self.q[1]+self.q[2]*self.q[3]), \\\n 1 - 2*(self.q[1]**2 + self.q[2]**2)) \n theta = math.asin(2*(self.q[0]*self.q[2] - self.q[3]*self.q[1]))\n psi = math.atan2(2*(self.q[0]*self.q[3]+self.q[1]*self.q[2]), \\\n 1 - 2*(self.q[2]**2 + self.q[3]**2))\n return np.array([phi, theta, psi])\n\n def from_axis_angle(self, a):\n angle = np.linalg.norm(a)\n if angle != 0:\n axis = a/angle\n else:\n axis = np.array([1,0,0])\n self.q[0] = math.cos(angle/2)\n self.q[1:4] = axis*math.sin(angle/2)\n self.normalize()\n\n def from_rotm(self, R):\n theta = math.acos((np.trace(R)-1)/2)\n omega_hat = (R - np.transpose(R))/(2*math.sin(theta))\n omega = np.array([omega_hat[2,1], -omega_hat[2,0], omega_hat[1,0]])\n self.q[0] = math.cos(theta/2)\n self.q[1:4] = omega*math.sin(theta/2)\n self.normalize()\n\n def inv(self):\n q_inv = Quaternion(self.scalar(), -self.vec())\n q_inv.normalize()\n return q_inv\n\n #Implement quaternion multiplication\n def __mul__(self, other):\n t0 = self.q[0]*other.q[0] - \\\n self.q[1]*other.q[1] - \\\n self.q[2]*other.q[2] - \\\n self.q[3]*other.q[3]\n t1 = self.q[0]*other.q[1] + \\\n self.q[1]*other.q[0] + \\\n self.q[2]*other.q[3] - \\\n self.q[3]*other.q[2]\n t2 = self.q[0]*other.q[2] - \\\n self.q[1]*other.q[3] + \\\n self.q[2]*other.q[0] + \\\n self.q[3]*other.q[1]\n t3 = self.q[0]*other.q[3] + \\\n self.q[1]*other.q[2] - \\\n self.q[2]*other.q[1] + \\\n self.q[3]*other.q[0]\n retval = Quaternion(t0, [t1, t2, t3])\n return retval\n\n def __str__(self):\n return str(self.scalar()) + ', ' + str(self.vec())\n\n\n#q = Quaternion()\n#R = np.array([[1, 0, 0],[0, 0.707, -0.707],[0, 0.707, 0.707]])\n#q.from_rotm(R)\n#print q\n","sub_path":"HW2/hw2_p2_data/quaternion.py","file_name":"quaternion.py","file_ext":"py","file_size_in_byte":2609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"112839198","text":"from tkinter import Label, Button, Listbox, Toplevel, END, Entry, LabelFrame, messagebox, E, EW, W, NSEW, NS\n\nfrom src.database.entity.order import Order\nfrom src.gui.main.mainframe import MainFrame\n\n\nclass ClientMainFrame(MainFrame):\n def __init__(self, frame, database, user, screenName=None, baseName=None, className='Tk', useTk=1, sync=0,\n use=None):\n super().__init__(database, user, screenName, baseName, className, useTk, sync, use)\n self.frame = frame\n Button(self, text=\"Добавить\", command=self.add).grid(row=0, column=1, sticky=NS)\n label_frame = LabelFrame(self, text=\"Заказы\")\n Label(master=label_frame, text=\"id\", borderwidth=2, relief=\"solid\").grid(row=0, column=0, sticky=E)\n Label(master=label_frame, text=\"Статус\", borderwidth=2, relief=\"solid\").grid(row=0, column=1, sticky=EW)\n Label(master=label_frame, text=\"Опции\", borderwidth=2, relief=\"solid\").grid(row=0, column=2, columnspan=2,\n sticky=EW)\n\n for i in range(len(database.orders)):\n if database.orders[i].id in user.orders:\n Label(master=label_frame, text=database.orders[i].id).grid(row=i + 1, column=0, sticky=E)\n Label(master=label_frame, text=database.orders[i].status).grid(row=i + 1, column=1, sticky=EW)\n Button(master=label_frame, text=\"Открыть\", command=lambda ci=i: self.open(ci)).grid(row=i + 1, column=2,\n sticky=W)\n Button(master=label_frame, text=\"Отменить\", command=lambda ci=i: self.cancel(ci)).grid(row=i + 1,\n column=3,\n sticky=W)\n label_frame.grid(row=0, column=0, sticky=NSEW)\n self.columnconfigure(0, weight=1)\n self.rowconfigure(0, weight=1)\n label_frame.grid_columnconfigure(1, weight=1)\n self.protocol(\"WM_DELETE_WINDOW\", self.back)\n\n def back(self):\n self.frame.deiconify()\n self.destroy()\n\n def open(self, i):\n top = Toplevel(self)\n Label(top, text='Идентификатор:' + self.database.orders[i].id).pack()\n Label(top, text='Статус:' + self.database.orders[i].status).pack()\n label_frame = LabelFrame(top, text=\"Товары\")\n for item in self.database.products:\n if item.id in self.database.orders[i].products:\n Label(label_frame, text=item.name).pack()\n label_frame.pack()\n top.transient(self)\n top.grab_set()\n top.focus_set()\n top.wait_window()\n\n def add(self):\n top = Toplevel(self)\n\n Label(top, text=\"Идентификатор\").pack()\n id_entry = Entry(top)\n id_entry.pack()\n\n products_list = Listbox(top, selectmode=\"multiple\")\n for item in self.database.products:\n products_list.insert(END, item.name)\n products_list.pack()\n products = []\n for selected in products_list.curselection():\n products.append(products_list.get(selected))\n\n Button(top, text=\"Добавить заказ\",\n command=lambda: self.create(id_entry.get(), products_list.curselection())).pack()\n\n top.transient(self)\n top.grab_set()\n top.focus_set()\n top.wait_window()\n\n def create(self, i, indexes):\n product_ids = []\n for pi in indexes:\n product_ids.append(str(self.database.products[pi].id))\n\n self.database.orders.append(\n Order('product:' + str(i) + ':' + self.database.statuses['created'] + ':' + ','.join(product_ids)))\n for ci in range(len(self.database.clients)):\n if self.database.clients[ci].id == self.user.id:\n self.database.clients[ci].orders.append(str(i))\n error = self.database.validate()\n if error is not None:\n messagebox.showerror(\"Ошибка\", error)\n else:\n self.database.save()\n self.destroy()\n self.__init__(self.database, self.user)\n\n def cancel(self, i):\n self.database.orders[i].status = self.database.statuses[\"canceled\"]\n error = self.database.validate()\n if error is not None:\n messagebox.showerror(\"Ошибка\", error)\n else:\n self.database.save()\n self.destroy()\n self.__init__(self.database, self.user)\n\n def delete(self, i):\n self.database.orders.pop(i)\n error = self.database.validate()\n if error is not None:\n messagebox.showerror(\"Ошибка\", error)\n else:\n self.database.save()\n self.destroy()\n self.__init__(self.database, self.user)\n","sub_path":"src/gui/main/client_mainframe.py","file_name":"client_mainframe.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"94250469","text":"import os\nimport io\nimport atexit\nimport sched\nimport httplib2\nimport webbrowser\nimport configparser\n\nfrom apiclient import discovery\nfrom oauth2client import tools\nfrom oauth2client import client\nfrom oauth2client.file import Storage\n\ntry:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n\nclass Configuration:\n def __init__(self, configurationDirectory):\n self.sectionName = 'DEFAULT'\n self.configuration = configparser.ConfigParser()\n self.configurationFile = os.path.join(configurationDirectory, 'configuration.ini')\n # Writing default configuration file\n if not os.path.exists(self.configurationFile):\n self.configuration[self.sectionName] = {\n 'drive-directory': \"~/DriveSync\",\n 'sync-interval-seconds': 120\n }\n\n def __contains__(object, index):\n return index in object.configuration[object.sectionName]\n\n def __getitem__(object, index):\n return object.configuration[object.sectionName][index]\n\n def __setitem__(object, index, value):\n object.configuration[object.sectionName][index] = value\n\n def saveConfiguration(self):\n with open(str(self.configurationFile), 'w') as fileWriter:\n self.configuration.write(fileWriter)\n print('Wrote default configuration file on ' + self.configurationFile)\n\n def readConfiguration(self):\n self.configuration.read(self.configurationFile)\n\nclass DriveSync:\n def __init__(self):\n self.homeDirectory = os.path.expanduser('~')\n self.configurationDirectory = os.path.join(self.homeDirectory, '.drivesync')\n\n # Creating app directory if it doesn't exists\n if not os.path.exists(self.configurationDirectory):\n os.makedirs(self.configurationDirectory)\n print('Created DriveSync configuration folder on ' + self.configurationDirectory)\n\n self.configuration = Configuration(self.configurationDirectory)\n self.drivesyncDirectory = os.path.expanduser(self.configuration['drive-directory'])\n\n # Searching DriveSync directory\n if not os.path.exists(self.drivesyncDirectory):\n os.makedirs(self.drivesyncDirectory)\n print('Created DriveSync directory on ' + self.drivesyncDirectory)\n else:\n print('Using ' + self.drivesyncDirectory + ' as DriveSync folder')\n\n atexit.register(self.stopSynchronizationTask)\n self.synchronizationInterval = int( self.configuration['sync-interval-seconds'])\n # Force sync (this will register a task)\n self.scheduler = sched.scheduler()\n self.scheduler.enter(delay=0, priority=1, action=self.doSynchronizationTask)\n try:\n print('=== DriveSync initialized!')\n self.scheduler.run(blocking=True)\n except (KeyboardInterrupt, SystemExit):\n print('Application interrupted.')\n\n def getAuthenticatedService(self):\n self.credentialFilePath = os.path.join(self.configurationDirectory, 'drivesync-credentials.json')\n\n # Creating storage on credential file\n storage = Storage(self.credentialFilePath)\n credentials = storage.get()\n if not credentials or credentials.invalid:\n # Enable the API through developer id, asking for all privileges\n flow = client.flow_from_clientsecrets('client_secret.json', scope='https://www.googleapis.com/auth/drive')\n flow.user_agent = 'drive-sync-id'\n\n # Running permissions on Google\n if flags:\n credentials = tools.run_flow(flow, storage, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, storage)\n\n # Printing success\n print('Stored Google credentials on ' + self.credentialFilePath)\n\n # Create and return service\n http = credentials.authorize(httplib2.Http())\n return (discovery.build('drive', 'v3', http=http), http)\n\n def stopSynchronizationTask(self):\n # This will auto-trigger on exit\n print('Stopped synchronization thread')\n\n def doSynchronizationTask(self):\n print('-> Synchronizing...')\n somethingChanged = False\n\n idIndex = {}\n parentFileDict = {}\n pageToken = None\n while True:\n googleService, http = self.getAuthenticatedService()\n response = googleService.files().list(q=\"mimeType == 'application/vnd.google-apps.folder' and not trashed\",\n spaces='drive',\n fields='nextPageToken, files(id, name, mimeType, parents)',\n pageToken=pageToken).execute(http=http)\n for file in response.get('files', []):\n driveFile = DriveFile(file)\n\n idIndex[driveFile.id] = driveFile\n\n if driveFile.parent not in parentFileDict:\n parentFileDict[driveFile.parent] = [driveFile]\n else:\n parentFileDict[driveFile.parent] += [driveFile]\n pageToken = response.get('nextPageToken', None)\n if pageToken is None:\n break;\n\n for parent, fileList in parentFileDict.items():\n print(idIndex[parent].name + ': ' + str(fileList))\n\n if somethingChanged:\n print('-> Synchronized with Google Drive!')\n else:\n print('-> Nothing changed.')\n\n # Repeat task\n self.scheduler.enter(delay=self.synchronizationInterval, priority=1, action=self.doSynchronizationTask)\n\nclass DriveFile:\n def __init__(self, file):\n self.id = file.get('id')\n self.name = file.get('name')\n self.type = file.get('mimeType'),\n self.parent = file.get('parents', ['unknown'])[0]\n\n def __str__(self):\n return self.fileName\n\n def __iter__(self):\n return [self.id, self.name]\n\ndef main():\n print(\"=== DriveSync v0.1, by Rafael 'jabyftw' Santos ===\")\n driveSync = DriveSync()\n\nif __name__ == '__main__':\n main()\n","sub_path":"drivesync.py","file_name":"drivesync.py","file_ext":"py","file_size_in_byte":6201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"446431170","text":"# stdlib\nfrom typing import Optional\n\n# relative\nfrom .....common.message import ImmediateSyftMessageWithoutReply\nfrom .....common.serde.serializable import serializable\nfrom .....common.uid import UID\n\n\n@serializable(recursive_serde=True)\nclass HeritageUpdateMessage(ImmediateSyftMessageWithoutReply):\n __attr_allowlist__ = [\"new_ancestry_address\", \"address\", \"id\"]\n\n def __init__(\n self,\n new_ancestry_address: UID,\n address: UID,\n msg_id: Optional[UID] = None,\n ):\n super().__init__(address=address, msg_id=msg_id)\n self.new_ancestry_address = new_ancestry_address\n","sub_path":"packages/syft/src/syft/core/node/common/node_service/heritage_update/heritage_update_messages.py","file_name":"heritage_update_messages.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"137116615","text":"#!/usr/bin/env python3\n\nfrom . base_instruction import BaseInstruction\nfrom error_handler import ErrorHandler\n\nclass INS_Jumpifeq(BaseInstruction):\n\tdef __init__(self, instruction, programMemory):\n\t\tself.instruction = instruction\n\t\tself.programMemory = programMemory\n\t\t#self.callback = callback\n\n\tdef eval(self):\n\t\tif len(self.instruction['args']) != 3:\n\t\t\tErrorHandler.ERROR_XML_STRUCTURE()\n\n\t\tlabel = self.instruction['args']['1']\n\t\tself.validateLabel(label['value'])\n\n\t\tif label['value'] not in self.programMemory['PROG_LABELS']:\n\t\t\tErrorHandler.ERROR_SEMANTIC()\n\n\t\tsymb1 = None\n\t\tsymb2 = None\n\n\t\tif self.instruction['args']['2']['type'] == 'var':\n\t\t\tvarPath = self.parseVariable(self.programMemory, self.instruction['args']['2'])\n\t\t\tsymb1 = self.programMemory[varPath[0]][varPath[1]]\n\t\telse:\n\t\t\tsymb1 = self.parseConst(self.instruction['args']['2'])\n\n\t\tif self.instruction['args']['3']['type'] == 'var':\n\t\t\tvarPath = self.parseVariable(self.programMemory, self.instruction['args']['3'])\n\t\t\tsymb2 = self.programMemory[varPath[0]][varPath[1]]\n\t\telse:\n\t\t\tsymb2 = self.parseConst(self.instruction['args']['3'])\n\n\t\tif symb1['type'] != symb2['type']:\n\t\t\tErrorHandler.ERROR_RUNTIME_OPERAND()\n\n\t\tif symb1['value'] == symb2['value']:\n\t\t\treturn self.programMemory['PROG_LABELS'][label['value']]","sub_path":"ipp_proj_1/instructions/ins_jumpifeq.py","file_name":"ins_jumpifeq.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"514942996","text":"# -*- coding: utf-8 -*-\nimport requests\nimport redis\nimport html\nimport re\nimport multiprocessing\nfrom ua import get_ua\nfrom bs4 import BeautifulSoup\nimport time\nimport xlwt\nimport copy\nimport csv\nimport traceback\nimport pymysql\nimport os\nimport hashlib\nfrom config import *\n\ndef work():\n #entry_ids = r.lrange(\"entry_id\",0,4)\n #for entry_id in entry_ids:\n r = redis.Redis(host=\"127.0.0.1\",port=6379,db=0,password=\"\")\n conn = pymysql.connect(host='',db='cmro',port=3306,charset='utf8')\n cur = conn.cursor()\n while True:\n try:\n tup = None\n r_id = r.lpop(\"entry_id\")\n entry_id = str(r_id, encoding = \"utf-8\")\n sql_cmd = \"select * from cmro_t where id=%s\" % entry_id\n rv = cur.execute(sql_cmd)\n tup = cur.fetchone()\n if tup == None:\n print(\"pid:%s error0:%s id:%s\" % (os.getpid(),\"sql none\",entry_id))\n continue\n path = 'file/'+ entry_id + '/' + \"pic/\"\n if os.path.exists(path) == False:\n os.makedirs(path)\n #os.removedirs(path)\n #continue\n img_url = tup[8];\n img_name = ''\n if img_url == '' or img_url == None:\n continue\n try:\n img_name = path + img_url.split('/')[-1]\n if os.path.isfile(img_name) == True:\n continue\n rsp = requests.get(img_url,headers=get_ua(img_url),timeout=5)\n with open(img_name, \"wb\") as code:\n code.write(rsp.content)\n except Exception as e:\n print(\"pid:%s error1:%s id:%s\" % (os.getpid(),e,entry_id))\n r.rpush(\"entry_id\",entry_id)\n continue\n\n print(\"ok \",entry_id)\n except Exception as e:\n print(\"pid:%s error2:%s id:%s\" % (os.getpid(),e,r_id))\n break\n\nif __name__ == '__main__':\n #work()\n for i in range(1):\n p = multiprocessing.Process(target=work)\n p.start()\n","sub_path":"down_file.py","file_name":"down_file.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"321774878","text":"from typing import Union\n\nfrom django.db import models\n\n\ndef is_created_pk(pk):\n return isinstance(pk, str) and pk.startswith('c') and pk[1:].isnumeric()\n\n\ndef get_current_obj(model, pk, only_field=None):\n if is_created_pk(pk):\n return model()\n if only_field is not None:\n return model.objects.only(only_field).get(pk=pk)\n return model.objects.get(pk=pk)\n\n\ndef get_field_value(obj, field: Union[str, models.Field]):\n if isinstance(field, str):\n name = field\n model = type(obj)\n field = model._meta.get_field('titles' if name.startswith('title_') else name)\n else:\n name = field.name\n try:\n current_value = getattr(obj, field.attname)\n except AttributeError:\n current_value = field.to_prep_value(getattr(obj, field.name))\n if name.startswith('title_'):\n current_value = current_value.get(name[6:], '')\n return current_value\n","sub_path":"src/c3nav/editor/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"549691926","text":"# https://leetcode-cn.com/explore/interview/card/2020-top-interview-questions/278/classic-problems/1242/\n\n# LRU缓存机制\n# 运用你所掌握的数据结构,设计和实现一个 LRU (最近最少使用) 缓存机制。它应该支持以下操作: 获取数据 get 和 写入数据 put 。\n# 获取数据 get(key) - 如果关键字 (key) 存在于缓存中,则获取关键字的值(总是正数),否则返回 -1。\n# 写入数据 put(key, value) - 如果关键字已经存在,则变更其数据值;如果关键字不存在,则插入该组「关键字/值」。当缓存容量达到上限时,它应该在写入新数据之前删除最久未使用的数据值,从而为新的数据值留出空间。\n\n# 进阶:\n# 你是否可以在 O(1) 时间复杂度内完成这两种操作?\n\n# 示例:\n# LRUCache cache = new LRUCache( 2 /* 缓存容量 */ );\n# cache.put(1, 1);\n# cache.put(2, 2);\n# cache.get(1); // 返回 1\n# cache.put(3, 3); // 该操作会使得关键字 2 作废\n# cache.get(2); // 返回 -1 (未找到)\n# cache.put(4, 4); // 该操作会使得关键字 1 作废\n# cache.get(1); // 返回 -1 (未找到)\n# cache.get(3); // 返回 3\n# cache.get(4); // 返回 4\n\nfrom typing import *\n\nclass LRUCache:\n\n class Node:\n def __init__(self, val, nex=None, prev=None, key=None):\n self.key = key\n self.val = val\n self.nex = nex\n self.prev = prev\n def __str__(self):\n return \"{}:{} {} {}\".format(self.key, self.val, \"tail\" if not self.nex else self.nex.key, \"head\" if not self.prev else self.prev.key)\n\n def __init__(self, capacity: int):\n self.capacity = capacity\n self.hash = {}\n self.head = None\n self.tail = None\n\n def get(self, key: int) -> int:\n if key in self.hash.keys():\n self.put(key, self.hash[key].val)\n return self.hash[key].val\n else:\n return -1\n\n def put(self, key: int, value: int) -> None:\n if not self.hash: # empty cache\n n = self.Node(value, key=key)\n self.hash[key] = n\n self.head = n\n self.tail = n\n else:\n if key in self.hash.keys():\n curr = self.hash[key]\n curr.val = value\n if curr == self.head:\n return\n elif curr == self.tail:\n # process the penultimate node: update the tail\n curr.prev.nex = None\n self.tail = curr.prev\n else:\n # update the nodes in the front and at the back\n front = curr.prev\n back = curr.nex\n front.nex = back\n back.prev = front\n \n # squeeze the head node to 2nd place\n self.head.prev = curr\n curr.nex = self.head\n # update the head to curr\n self.head = curr\n # delete prev pointer of head\n curr.prev = None \n \n else:\n n = self.Node(value, nex=self.head, prev=None, key=key)\n self.hash[key] = n\n self.head.prev = n\n self.head = n\n while len(self.hash) > self.capacity:\n curr = self.tail\n curr.prev.nex = None\n self.tail = curr.prev\n del self.hash[curr.key]\n curr = None\n self.show()\n \n \n def show(self):\n l = self.head\n t = \"Head \\n\"\n while l:\n t += \"{}\\n\".format(l)\n l = l.nex\n t += \"Tail\\n\"\n print(t)\n\n\n# Your LRUCache object will be instantiated and called as such:\n# obj = LRUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)\n\n# [\"LRUCache\",\"put\",\"put\",\"get\",\"put\",\"get\",\"put\",\"get\",\"get\",\"get\"]\n# [[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]\n\n# [\"LRUCache\",\"put\",\"put\",\"get\",\"put\",\"get\",\"put\",\"get\",\"get\",\"get\"]\n# [[2],[1,1],[2,2],[1],[3,3],[2],[4,4],[1],[3],[4]]\n\nl = LRUCache(4)\nl.put(1, 10)\nl.put(2, 20)\nl.put(3, 30)\nl.put(4, 40)\nl.put(3, 300)\nl.put(1, 100)\nl.put(5, 12345)\n\n# Better method:\n\nfrom collections import OrderedDict\n\nclass LRUCache2(OrderedDict):\n\n def __init__(self, capacity: int):\n super().__init__()\n self.capacity = capacity\n\n def get(self, key: int) -> int:\n if key not in self:\n return -1\n self.move_to_end(key)\n return self[key]\n\n def put(self, key: int, value: int) -> None:\n if key in self:\n self[key] = value\n self[key] = value\n self.move_to_end(key)\n while len(self) > self.capacity:\n oldest = next(iter(self))\n del self[oldest]","sub_path":"企业面试题/Classics/LRUcache.py","file_name":"LRUcache.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"513787865","text":"import os\nos.environ['TF_CPP_MIN_LOG_LEVEL']='2'\n\n# Tuorial link\n# 1. https://www.tensorflow.org/get_started/mnist/beginners\n# 2. https://www.tensorflow.org/get_started/mnist/pros\n\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist = input_data.read_data_sets('MNIST_data',one_hot = True)\n\n# Here mnist is a lightweight class which stores the training, validation, and testing sets as NumPy arrays.\n# It also provides a function for iterating through data minibatches, which we will use below.\n\n# TensorFlow relies on a highly efficient C++ backend to do its computation. The connection to this backend is called a session.\n# The common usage for TensorFlow programs is to first create a graph and then launch it in a session.\n\n# Here we instead use the convenient InteractiveSession class, which makes TensorFlow more flexible about how you structure your code.\n# It allows you to interleave operations which build a computation graph with ones that run the graph.\n# This is particularly convenient when working in interactive contexts like IPython. If you are not using an InteractiveSession,\n# then you should build the entire computation graph before starting a session and launching the graph.\n\nimport tensorflow as tf\nsess = tf.InteractiveSession()\n\n# Build a Softmax Regression Model\n#=================================\n\n# We start building the computation graph by creating nodes for the input images and target output classes.\nx = tf.placeholder(tf.float32,shape = [None, 784])\ny_ = tf.placeholder(tf.float32, shape = [None, 10])\n\n# We now define the weights W and biases b for our model.\n\nW = tf.Variable(tf.zeros([784,10]))\nb = tf.Variable(tf.zeros([10]))\n\n# Before Variables can be used within a session, they must be initialized using that session.\n# This step takes the initial values (in this case tensors full of zeros) that have already been specified, and assigns them to each Variable.\n\nsess.run(tf.global_variables_initializer())\n\n\n# Predicted Class and Loss Function\n# ==================================\n# We can now implement our regression model. It only takes one line! We multiply the vectorized input images x by the weight matrix W, add the bias b.\n\ny = tf.matmul(x,W) + b\n\n# Here, our loss function is the cross-entropy between the target and the softmax activation function applied to the model's prediction\n\n# Note that tf.nn.softmax_cross_entropy_with_logits internally applies the softmax on the model's unnormalized model prediction\n# and sums across all classes, and tf.reduce_mean takes the average over these sums.\n\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_,logits = y))\n\n\n# Train the model\n# ==================\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\n\n# What TensorFlow actually did in that single line was to add new operations to the computation graph.\n# These operations included ones to compute gradients, compute parameter update steps, and apply update steps to the parameters.\n\n# The returned operation train_step, when run, will apply the gradient descent updates to the parameters.\n# Training the model can therefore be accomplished by repeatedly running train_step.\n\nfor _ in range(1000):\n batch = mnist.train.next_batch(100)\n train_step.run(feed_dict={x:batch[0], y_: batch[1]})\n# We load 100 training examples in each training iteration. We then run the train_step operation, using feed_dict to replace\n# the placeholder tensors x and y_ with the training examples. Note that you can replace any tensor in your computation graph\n# using feed_dict -- it's not restricted to just placeholders.\n\n\n# Evaluate the model\n#======================\n# tf.argmax is an extremely useful function which gives you the index of the highest entry in a tensor along some axis.\n# For example, tf.argmax(y,1) is the label our model thinks is most likely for each input, while tf.argmax(y_,1) is the true label.\n# We can use tf.equal to check if our prediction matches the truth.\n\ncorrect_prediction = tf.equal(tf.argmax(y,1),tf.argmax(y_,1))\n\n# That gives us a list of booleans. To determine what fraction are correct, we cast to floating point numbers and then take the mean.\n\naccuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n\n# Finally, we can evaluate our accuracy on the test data. This should be about 92% correct.\nprint(accuracy.eval(feed_dict = {x:mnist.test.images, y_:mnist.test.labels}))\n\n# If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).\n\n\n\n","sub_path":"TensorFlow Tutorial/mnist_practice.py","file_name":"mnist_practice.py","file_ext":"py","file_size_in_byte":4547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"173567103","text":"#!/usr/bin/python3\n\"\"\" Creates a view for State objects \"\"\"\n\nfrom api.v1.views import app_views\nfrom flask import jsonify, abort, request, make_response\nfrom models import storage\nfrom models.state import State\n\n\n@app_views.route(\"/states\", methods=[\"GET\", \"POST\"],\n strict_slashes=False)\ndef states():\n \"\"\" Route retrieves list of all State objects or creates State \"\"\"\n if request.method == \"GET\":\n states = storage.all(State)\n new_list = []\n for values in states.values():\n new_list.append(values.to_dict())\n return jsonify(new_list)\n else:\n data = request.get_json()\n if data is None:\n return \"Not a JSON\", 400\n if data.get(\"name\") is None:\n return \"Missing name\", 400\n obj = State()\n for key, value in data.items():\n setattr(obj, key, value)\n obj.save()\n return jsonify(obj.to_dict()), 201\n\n\n@app_views.route(\"/states/\", methods=[\"GET\", \"DELETE\", \"PUT\"],\n strict_slashes=False)\ndef states_id(state_id):\n \"\"\" Route retrieves a State object, deletes it or update it \"\"\"\n if request.method == \"GET\":\n state = storage.get(State, state_id)\n if state is None:\n abort(404)\n return jsonify(state.to_dict())\n elif request.method == \"DELETE\":\n state = storage.get(State, state_id)\n if state is None:\n abort(404)\n storage.delete(state)\n storage.save()\n return jsonify({}), 200\n else:\n data = request.get_json()\n if data is None:\n return \"Not a JSON\", 400\n obj = storage.get(State, state_id)\n if obj is None:\n abort(404)\n for key, value in data.items():\n if key != \"id\" and key != \"created_at\" and key != \"updated_at\":\n setattr(obj, key, value)\n obj.save()\n return jsonify(obj.to_dict()), 200\n","sub_path":"api/v1/views/states.py","file_name":"states.py","file_ext":"py","file_size_in_byte":1945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"42818285","text":"import time\nimport random\nimport RPi.GPIO as gpio\nimport numpy as np\n\ngpio.cleanup()\n\nadr_ports = [8, 7, 12, 10, 9, 11, 5] \nspike_port = 25\ngpio.setmode(gpio.BCM)\nfor i in adr_ports:\n gpio.setup(i, gpio.OUT)\ngpio.setup(spike_port, gpio.OUT)\n\ngpio.setup(22, gpio.OUT); gpio.setup(24, gpio.OUT) #To ground the reading signals\ngpio.output(22, False); gpio.output(24, False)\n\nadr = np.zeros((2, 7), dtype = int)\nadr[0] = [0,0,0,0,0,0,1]\nadr[1] = [0,0,0,0,0,1,0]\n\ndef fire(nr):\n for ii in np.arange(7):\n gpio.output(adr_ports[ii], adr[nr, ii])\n gpio.output(spike_port, True)\n\n time.sleep(1e-6)\n\n gpio.output(spike_port, False)\n\n #time.sleep(400e-6)\n\ngpio.setup(21, gpio.OUT)\ngpio.output(21, 1)\ncount = 0\nnr = 0\nwhile True:\n count = count + 1\n if count == 5:\n if nr == 0:\n nr = 1; gpio.output(21, True)\n else: nr = 0; gpio.output(21, False)\n count = 0\n fire(nr)\n","sub_path":"FPGA/Controlled_depression.py","file_name":"Controlled_depression.py","file_ext":"py","file_size_in_byte":923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"377939285","text":"\"\"\"\nCode Challenge\n Filename: \n height.py\n Problem Statement:\n\n people = [{'name': 'Mary', 'height': 160},\n {'name': 'Isla', 'height': 80},\n {'name': 'Sam'}]\n\n height_total = 0\n height_count = 0\n for person in people:\n if 'height' in person:\n height_total += person['height']\n height_count += 1\n\n if height_count > 0:\n average_height = height_total / height_count\n\n print (average_height)\n \nTry rewriting the code below using map, reduce and filter. \nFilter takes a function and a collection. \nIt returns a collection of every item for which the function returned True.\n \n\n\"\"\"\nfrom functools import reduce\npeople = [{'name': 'Mary', 'height': 160},\n {'name': 'Isla', 'height': 80},\n {'name': 'Sam'}]\n\n\nlist(filter(lambda x: 'height' in x, people))\n\n[item['height'] for item in list(filter(lambda x: 'height' in x, people))]\n\nreduce(lambda x,y: (x+y)/2, [item['height'] for item in list(filter(lambda x: 'height' in x, people))] )\n\n\n\n\n\n\n\n\n\nheight1 =list(map(lambda x:list(x.values())[1] if len(list(x.values()))==2 else 0, people))\nprint(height1)\nheight1.remove(0)\nprint(sum(height1)/len(height1))\nabz=reduce(lambda a,b:a+b,height1)/len(height1)\nprint(abz)\n\n\n\n\n\n\nlist(map( lambda x: x['height'] if len(x)==2 else 0 ,people))\ndict={'name': 'Mary', 'height': 160,'xy':6}\nlen(dict)\n","sub_path":"day 6/height.py","file_name":"height.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"580270164","text":"import sys\nfrom bisect import bisect_right\n\nread = sys.stdin.read\nreadline = sys.stdin.readline\nreadlines = sys.stdin.readlines\nsys.setrecursionlimit(10 ** 9)\nINF = 1 << 60\n\n\ndef main():\n N, *A = map(int, read().split())\n\n vec = [INF] * N\n for a in reversed(A):\n vec[bisect_right(vec, a)] = a\n\n try:\n print(vec.index(INF))\n except:\n print(N)\n\n return\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Python_codes/p02973/s744858550.py","file_name":"s744858550.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"185961310","text":"from selenium import webdriver\nimport re\nimport docx\nfrom docx import Document\nimport time\n\n\ndef writeWord(list):\n document = Document()\n for x in range(len(list)):\n document.add_paragraph(list[x][\"testLine\"])\n document.add_paragraph(list[x][\"A\"])\n document.add_paragraph(list[x][\"B\"])\n document.add_paragraph(list[x][\"C\"])\n document.add_paragraph(list[x][\"D\"])\n document.add_paragraph(list[x][\"answer\"])\n document.add_paragraph()\n\n document.save('double.docx')\n\n\n\ndef getData(brower):\n allInfos = []\n\n doublePage = brower.find_element_by_xpath('//*[@id=\"sectionRender\"]/div[2]/div[2]/a[1]')\n doublePage.click()\n for i in range(29):\n metaInfos = {}\n\n time.sleep(1)\n ChoiceAnswer = brower.find_element_by_xpath(\n '//*[@id=\"questionRender\"]/div[2]/div[2]/div[3]/div[2]/label[1]')\n ChoiceAnswer.click()\n time.sleep(0.5)\n outAnswer = brower.find_element_by_xpath(\n '//*[@id=\"questionRender\"]/div[2]/div[2]/div[4]/a[2]'\n )\n outAnswer.click()\n\n\n testLineTitle = brower.find_element_by_xpath(\n '//*[ @ id = \"questionRender\"] / div[2] / div[2] / div[3] / div[1]/div[1]'\n )\n testLineMes = brower.find_element_by_xpath(\n '//*[ @ id = \"questionRender\"] / div[2] / div[2] / div[3] / div[1]/div[2]'\n )\n testLine = str(testLineTitle.text) + str(testLineMes.text)\n metaInfos['testLine'] = testLine\n # print(testLine)\n\n for n in range(1, 5):\n choiceTitle = brower.find_element_by_xpath(\n '//*[@id=\"questionRender\"]/div[2]/div[2]/div[3]/div[2]/label[' + str(n) + ']/div[1]'\n )\n choiceMes = brower.find_element_by_xpath(\n '//*[@id=\"questionRender\"]/div[2]/div[2]/div[3]/div[2]/label[' + str(n) + ']/div[2]'\n )\n choice = str(choiceTitle.text) + str(choiceMes.text)\n if n==1:\n metaInfos['A'] = choice\n elif n==2:\n metaInfos['B'] = choice\n elif n==3:\n metaInfos['C'] = choice\n else:\n metaInfos['D'] = choice\n #print(metaInfos['D'])\n\n answerTitle = brower.find_element_by_xpath(\n '//*[@id=\"questionRender\"]/div[3]/div[2]/div[1]/div[2]/div/div[1]'\n )\n answerMes = brower.find_element_by_xpath(\n '//*[@id=\"questionRender\"]/div[3]/div[2]/div[1]/div[2]/div/div[2]'\n )\n answer = str(answerTitle.text) + str(answerMes.text)\n print(answer)\n metaInfos['answer'] = answer\n allInfos.append(metaInfos)\n\n\n\n # print()\n if i == 28:\n break\n nextPage = brower.find_element_by_xpath('//*[@id=\"sectionRender\"]/div[2]/div[2]/a[' + str(i+2) + ']')\n nextPage.click()\n\n #print(allInfos)\n\n return allInfos\n\nbrower = webdriver.Chrome()\nbrower.get(\"http://saishi.cnki.net/Exercise/Practice/ks0af38326-10ce-48a5-a2cb-84204baf254c/1\")\nwriteWord(getData(brower))\n","sub_path":"Crawl-Study-Materials/doubleTest.py","file_name":"doubleTest.py","file_ext":"py","file_size_in_byte":3065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"159879492","text":"\n\nclass Solution:\n def reverseBits(self, n: int) -> int:\n # >> << right shift, left shift\n res = 0\n for i in range(32):\n nn = n & 1\n res = res << 1\n res = res + nn\n n = n >> 1\n return res\n\nn = 7\nprint(Solution().reverseBits(n))","sub_path":"190. Reverse Bits.py","file_name":"190. Reverse Bits.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"158102740","text":"\nimport sys\n\nINFINITY = (None, sys.maxint)\n\ndef merge(arr, left, mid, right):\n a = arr[left:mid]\n b = arr[mid:right]\n a.append(INFINITY)\n b.append(INFINITY)\n for i in xrange(left, right):\n arr[i] = a.pop(0) if a[0][1] < b[0][1] else b.pop(0)\n \n \ndef merge_sort(arr, left=0, right=None):\n if right == None: right = len(arr)\n if left + 1 == right: return\n mid = left + (right - left) / 2\n merge_sort(arr, left, mid)\n merge_sort(arr, mid, right)\n merge(arr, left, mid, right)\n\nclass PriorityQueue:\n @classmethod\n def parent(cls, index): return (index - 1) / 2\n @classmethod\n def left(cls, index): return index * 2 + 1\n @classmethod\n def right(cls, index): return index * 2 + 2\n def __init__(self, compare, key, update):\n self.heap = []\n self.compare = compare\n self.key = key\n self.update = update\n\n def swap(self, a, b):\n temp = self.heap[a]\n self.heap[a] = self.heap[b]\n self.heap[b] = temp\n \n def insert(self, val):\n i = len(self.heap)\n self.heap.append(val)\n self.swim(i)\n\n def swim(self, i):\n parent = PriorityQueue.parent(i)\n if i != 0 and self.compare(self.heap[i], self.heap[parent]) < 0:\n self.swap(i, parent)\n self.swim(parent)\n\n def sink(self, i):\n left, right = PriorityQueue.left(i), PriorityQueue.right(i)\n if left >= len(self.heap):\n # Children are not in heap\n return\n if right >= len(self.heap):\n # Only left child is in the heap\n if self.compare(self.heap[i], self.heap[left]) > 0:\n self.swap(i, left)\n return\n # Both children are in the heap\n smaller = left if self.compare(self.heap[left], self.heap[right]) < 0 else right\n if self.compare(self.heap[i], self.heap[smaller]) > 0:\n self.swap(i, smaller)\n self.sink(smaller)\n\n def decrease_priority(self, key, val):\n for i, element in enumerate(self.heap):\n if self.key(element) == key:\n self.update(element, val)\n self.swim(i)\n return\n \n def pop(self):\n if len(self.heap) == 1: return self.heap.pop()\n bottom = self.heap.pop()\n top = self.heap.pop(0)\n self.heap.insert(0, bottom)\n return top\n\n def is_empty(self):\n return len(self.heap) == 0\n\n def get(self, key):\n for elem in self.heap:\n if self.key(elem) == key:\n return elem\n return None\n","sub_path":"proj4/sorts.py","file_name":"sorts.py","file_ext":"py","file_size_in_byte":2316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"41299689","text":"k=0\ni=0\nwhile i<5:\n a,b=input(\"Пиши через пробел: \").split(\" \")\n a = int(a)\n b = int(b)\n if a==0 and b==0:\n break\n elif a==0 or b==0:\n if a==0 and b!=0:\n k+=b\n elif a!=0 and b==0:\n k+=a\n continue\n print(a*b)\n k+=(a*b)\n i+=1\nprint(k)\n\n","sub_path":"Kurs1/scratch_4.py","file_name":"scratch_4.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"475641419","text":"import argparse\r\nimport serial\r\nimport serial.tools.list_ports\r\nimport script_lib.icron_file_parser as ifp\r\nimport script_lib.loaded_icron_file as lif\r\nimport threading as Threading\r\n\r\nimport time\r\n\r\ndef bw_lc_testSequence(ser, port, rate, time_delay):\r\n bw_lc = [[20,4], [20,2], [20,1], [10,4], [10,2], [10,1], [6,4], [6,2], [6,1]]\r\n for BW_LC in bw_lc:\r\n setIsolate(ser, rate)\r\n time.sleep(0.2)\r\n setBwLc(ser, BW_LC[0], BW_LC[1])\r\n time.sleep(0.1)\r\n restartLinkTraining(ser)\r\n time.sleep(time_delay)\r\n\r\ndef setIsolate(ser, rate):\r\n icmd_obj = loaded_icron_file.create_icmd(\"DP_COMPONENT\", \"DP_SetIsolateEnable\", False, [1])\r\n executeIcmd(icmd_obj, ser)\r\n\r\ndef setBwLc(ser, bandwidth, lanecount):\r\n print(('WROTE BW %d and LC %d') %(bandwidth, lanecount))\r\n icmd_obj = loaded_icron_file.create_icmd(\"DP_COMPONENT\", \"DP_SetBwLc\", False, [bandwidth, lanecount])\r\n executeIcmd(icmd_obj, ser)\r\n\r\n# def verifyBwLc(ser):\r\n\r\ndef restartLinkTraining(ser):\r\n print('RESTART LT \\n')\r\n icmd_obj = loaded_icron_file.create_icmd(\"DP_COMPONENT\", \"DP_RestartDPStateMachine\", False)\r\n executeIcmd(icmd_obj, ser)\r\n\r\ndef executeIcmd(icmd_obj, ser):\r\n icmd_thread = Threading.Thread(target = loaded_icron_file.send_icmd, args=(icmd_obj, ser,))\r\n icmd_thread.start()\r\n icmd_thread.join()\r\n\r\nif __name__ == \"__main__\":\r\n comPorts = list(serial.tools.list_ports.comports())\r\n\r\n print(\"Available COM Ports:\")\r\n for port in comPorts:\r\n if port.description == ('USB Serial Port '+ '(' + port.device + ')'):\r\n print(\" \" + port.device)\r\n userSelectedPort = input(\"\\nEnter the COM port you would like to use (default = COM1):\")\r\n if userSelectedPort == '':\r\n userSelectedPort = 'COM1'\r\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\r\n parser.add_argument(\"-d\", \"--device\", help=\"device to read from\", default=userSelectedPort)\r\n parser.add_argument(\"-b\", \"--baud\", help=\"baud rate in bps\", default=460800, type=int)\r\n parser.add_argument(\"-t\", \"--time_delay\", help=\"time delay for loop\", default=1, type=int)\r\n parser.add_argument(\"-i\", \"--icron_file\", help=\"icron file to be used\")\r\n parser.add_argument(\"-c\", \"--count\", help=\"repeat test this number of times\", default=1, type=int)\r\n args = parser.parse_args()\r\n\r\n ser = serial.Serial(args.device, args.baud, timeout=1)\r\n ser.flushInput()\r\n ser.flushOutput()\r\n\r\n iparsed_file = ifp.IcronParsedFile(args.icron_file)\r\n loaded_icron_file = lif.Loaded_icron_file(iparsed_file, \"blackbird\", args.device, args.baud)\r\n\r\n# icmd_obj = loaded_icron_file.create_icmd(\"DP_COMPONENT\", \"DP_PmLogState\", False)\r\n# executeIcmd(icmd_obj, ser)\r\n# num_args, response = loaded_icron_file.get_icmd_resp(ser)\r\n# print(num_args)\r\n# print(response)\r\n# print(icmd_thread.isAlive())\r\n\r\n# icmd_obj = loaded_icron_file.create_icmd(\"CORE_COMPONENT\", \"BBCORE_printHWModuleVersion\", False)\r\n# executeIcmd(icmd_obj, ser)\r\n# num_args, response = loaded_icron_file.get_icmd_resp(ser)\r\n# print(num_args)\r\n# print(response)\r\n\r\n # icmd_obj = loaded_icron_file.create_icmd(\"DP_COMPONENT\", \"DP_SetBwLc\", False, [0x14, 0x4])\r\n # executeIcmd(icmd_obj, ser)\r\n # num_args, response = loaded_icron_file.get_icmd_resp(ser)\r\n # print(\"number of args {}\". format(num_args))\r\n # print(\"response {}\". format(response))\r\n\r\n for count in range (0, args.count):\r\n bw_lc_testSequence(ser, port, args.baud, args.time_delay)\r\n\r\n ser.close()\r\n","sub_path":"cobs_lite/lib/bw_lc_test.py","file_name":"bw_lc_test.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"614286706","text":"from django.db.models.deletion import CASCADE\nfrom django.db import models\n\n\nclass Category(models.Model):\n cat_romance = \"Romance\"\n cat_fantacy = \"Fantacy\"\n cat_thriller= \"Thriller\"\n cat_horror = \"Horror\"\n cat_crime = \"Crime\"\n cat_true_story= \"True Story\"\n\n\n category = models.CharField(\n max_length=100,\n choices=(\n (cat_crime, cat_crime),\n (cat_fantacy, cat_fantacy),\n (cat_horror, cat_horror),\n (cat_romance, cat_romance),\n (cat_thriller, cat_thriller),\n (cat_true_story, cat_true_story)\n )\n )\n\n class Meta: # new\n verbose_name_plural = \"Categories\"\n\n def __str__(self):\n return self.category\n\nclass Publisher(models.Model):\n publisher_name = models.CharField(max_length=100)\n publish_date = models.DateField\n\n def __str__(self):\n return self.publisher_name\n\nclass Author(models.Model):\n gender_male = \"Male\"\n gender_female = \"Female\"\n gender_other = \"Other\"\n name = models.CharField(max_length=100)\n gender = models.CharField(max_length=100,\n choices=(\n (gender_female, gender_female),\n (gender_male, gender_male),\n (gender_other, gender_other)\n )\n )\n country = models.CharField(max_length=100)\n\n def __str__(self):\n return self.name\n\nclass Details(models.Model):\n book_name = models.CharField(max_length=100)\n category = models.ForeignKey(Category, on_delete=CASCADE)\n pages = models.IntegerField(default=1)\n publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)\n Author = models.ForeignKey(Author, on_delete=CASCADE)\n\n class Meta: # new\n verbose_name_plural = \"Details\"\n\n def __str__(self):\n return self.book_name","sub_path":"Custom/Bookstore/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"407411104","text":"import numpy as np\nimport copy\nimport logging\nimport torch\nimport os\nimport pandas as pd\nimport math\n\nfrom data import make_masks\nfrom utils import AccuracyCls, AccuracyRec, Loss, preds_embedding_cosine_similarity\n\n\ndef evaluate(epoch, data_iter, model_enc, model_dec,\n model_cls, cls_criteria, seq2seq_criteria,\n ent_criteria, params):\n ''' Evaluate performances over test/validation dataloader '''\n\n device = params.device\n\n model_cls.eval()\n model_enc.eval()\n model_dec.eval()\n\n cls_running_loss = Loss()\n rec_running_loss = Loss()\n ent_running_loss = Loss()\n\n rec_acc = AccuracyRec()\n cls_acc = AccuracyCls()\n\n with torch.no_grad():\n for i, batch in enumerate(data_iter):\n if params.TEST_MAX_BATCH_SIZE and i == params.TEST_MAX_BATCH_SIZE:\n break\n\n # Prepare batch\n src, labels = batch.text, batch.label\n src_mask, trg_mask = make_masks(src, src, device)\n\n src = src.to(device)\n src_mask = src_mask.to(device)\n trg_mask = trg_mask.to(device)\n labels = labels.to(device)\n\n # Classifier loss\n encode_out = model_enc(src, src_mask)\n cls_preds = model_cls(encode_out)\n cls_loss = cls_criteria(cls_preds, labels)\n cls_running_loss.update(cls_loss)\n\n # Rec loss\n preds = model_dec(encode_out, labels, src_mask, src, trg_mask)\n rec_loss = seq2seq_criteria(preds.contiguous().view(-1, preds.size(-1)),\n src.contiguous().view(-1))\n rec_running_loss.update(rec_loss)\n\n # Entropy loss\n ent_loss = ent_criteria(cls_preds)\n ent_running_loss.update(ent_loss)\n\n # Accuracy\n preds = preds[:, 1:, :]\n preds = preds.contiguous().view(-1, preds.size(-1))\n src = src[:, :-1]\n src = src.contiguous().view(-1)\n rec_acc.update(preds, src)\n cls_acc.update(cls_preds, labels)\n\n logging.info(\"Eval-e-{}: loss cls: {:.3f}, loss rec: {:.3f}, loss ent: {:.3f}\".format(epoch, cls_running_loss(),\n rec_running_loss(),\n ent_running_loss()))\n logging.info(\"Eval-e-{}: acc cls: {:.3f}, acc rec: {:.3f}\".format(epoch, cls_acc(), rec_acc()))\n # TODO - Roy - what metric to report ?\n return rec_acc\n\n\ndef greedy_decode_sent(preds, id2word, eos_id):\n ''' Nauve greedy decoding - just argmax over the vocabulary distribution '''\n preds = torch.argmax(preds, -1)\n decoded_sent = preds.squeeze(0).detach().cpu().numpy()\n # print(\" \".join([id2word[i] for i in decoded_sent]))\n decoded_sent = sent2str(decoded_sent, id2word, eos_id)\n return decoded_sent, preds\n\n\ndef sent2str(sent_as_np, id2word, eos_id=None):\n ''' Gets sentence as a list of ids and transfers to string\n Input is np array of ids '''\n if not (isinstance(sent_as_np, np.ndarray)):\n raise ValueError('Invalid input type, expected np array')\n if eos_id:\n end_id = np.where(sent_as_np == eos_id)[0]\n if len(end_id) > 1:\n sent_as_np = sent_as_np[:int(end_id[0])]\n elif len(end_id) == 1:\n sent_as_np = sent_as_np[:int(end_id)]\n\n return \" \".join([id2word[i] for i in sent_as_np])\n\n\ndef test_random_samples(data_iter, TEXT, model_gen, model_cls, device, src_embed=None, decode_func=None, num_samples=2,\n transfer_style=True, trans_cls=False, embed_preds=False):\n ''' Print some sample text to validate the model.\n transfer_style - bool, if True apply style transfer '''\n\n word2id = TEXT.vocab.stoi\n eos_id = int(word2id[''])\n id2word = {v: k for k, v in word2id.items()}\n model_gen.eval()\n\n with torch.no_grad():\n for step, batch in enumerate(data_iter):\n if num_samples == 0: break\n\n # Prepare batch\n src, labels = batch.text[0, ...], batch.label[0, ...]\n src = src.unsqueeze(0)\n labels = labels.unsqueeze(0)\n src_mask, _ = make_masks(src, src, device)\n\n src = src.to(device)\n src_mask = src_mask.to(device)\n labels = labels.to(device)\n true_labels = copy.deepcopy(labels)\n\n # Logical not on labels if transfer_style is set\n if transfer_style:\n labels = (~labels.bool()).long()\n # print(\"Original label \", true_labels, \" Transfer label \", labels)\n if src_embed:\n embeds = src_embed(src)\n preds = model_gen(embeds, src_mask, labels)\n else:\n preds = model_gen(src, src_mask, labels)\n\n sent_as_list = src.squeeze(0).detach().cpu().numpy()\n src_sent = sent2str(sent_as_list, id2word, eos_id)\n src_label = 'pos' if true_labels.detach().item() == 1 else 'neg'\n logging.info('Original: text: {}'.format(src_sent))\n logging.info('Original: class: {}'.format(src_label))\n\n if embed_preds:\n preds = preds_embedding_cosine_similarity(preds, model_gen.src_embed)\n if decode_func:\n dec_sent, decoded = decode_func(preds, id2word, eos_id)\n if src_embed:\n decoded = src_embed(decoded)\n if trans_cls:\n cls_preds = model_cls(decoded, src_mask)\n else:\n cls_preds = model_cls(decoded)\n pred_label = 'pos' if torch.argmax(cls_preds) == 1 else 'neg'\n if transfer_style:\n logging.info('Style transfer output:')\n logging.info('Predicted: text: {}'.format(dec_sent))\n logging.info('Predicted: class: {}'.format(pred_label))\n\n else:\n logging.info('Predicted: class: {}'.format(pred_label))\n logging.info('\\n')\n\n num_samples -= 1\n\n\ndef tensor2text(vocab, tensor):\n tensor = tensor.cpu().detach().numpy()\n text = []\n index2word = vocab.itos\n eos_idx = vocab.stoi['']\n\n # unk_idx = vocab.stoi['']\n # stop_idxs = [vocab.stoi['!'], vocab.stoi['.'], vocab.stoi['?']]\n\n for sample in tensor:\n end_id = np.where(sample == eos_idx)[0]\n if len(end_id) > 1:\n sample = sample[:int(end_id[0])]\n elif len(end_id) == 1:\n sample = sample[:int(end_id)]\n\n text.append(\" \".join([index2word[i] for i in sample]))\n return text\n\ndef generate_sentences(model_gen, data_iter, TEXT, params, limit=None):\n device = params.device\n vocab = TEXT.vocab\n\n model_gen = model_gen.to(device)\n model_gen.eval()\n\n test_generated_sentences = []\n test_original_sentences = []\n test_original_labels = []\n with torch.no_grad():\n for i, batch in enumerate(data_iter):\n\n # Prepare batch\n src, labels = batch.text, batch.label\n src_mask, _ = make_masks(src, src, device)\n src = src.to(device)\n src_mask = src_mask.to(device)\n labels = labels.to(device)\n\n # Negate labels\n neg_labels = (~labels.bool()).long()\n\n # Predict generated senteces\n preds = model_gen(src, src_mask, neg_labels)\n preds = torch.argmax(preds, dim=-1)\n\n # From preds to text - greedy decode\n test_generated_sentences += tensor2text(vocab, preds)\n test_original_sentences += tensor2text(vocab, src)\n test_original_labels += labels.detach().cpu().tolist()\n if limit and i == (limit - 1):\n break\n return test_generated_sentences, test_original_sentences, test_original_labels\n\ndef print_generated_test_samples(model_gen, data_iter, TEXT, params, num_senteces=10):\n num_batches = math.ceil(float(num_senteces) / data_iter.batch_size)\n test_generated_sentences, test_original_sentences, _ = generate_sentences(model_gen, data_iter, TEXT, params, num_batches)\n\n for gen, org in zip(test_generated_sentences[:num_senteces], test_original_sentences[:num_senteces]):\n print('Original: ' + org)\n print('Generated: ' + gen + '\\n')\n\ndef generate_senteces_to_csv(model_gen, data_iter, TEXT, params, out_dir, file_name, limit=None):\n test_generated_sentences, test_original_sentences, test_original_labels = generate_sentences(model_gen, data_iter, TEXT, params, limit)\n\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n\n data = np.array([test_generated_sentences, test_original_sentences, test_original_labels]).T\n df = pd.DataFrame(data, columns=[\"generated_sentences\", \"original_sentences\", \"original_labels\"])\n df.to_csv(os.path.join(out_dir, file_name))\n\n \"\"\"\nTODO: fix\ndef test_user_string(sent, label, TEXT, model_gen, model_cls, device, decode_func=None,\n transfer_style=True, trans_cls=False, embed_preds=False):\n ''' Print some sample text to validate the model.\n transfer_style - bool, if True apply style transfer '''\n\n word2id = TEXT.vocab.stoi\n eos_id = int(word2id[''])\n id2word = {v: k for k, v in word2id.items()}\n # define tokenizer\n en = English()\n\n def id_tokenize(sentence):\n return [word2id[tok.text] for tok in en.tokenizer(sentence)]\n\n model_gen.eval()\n\n with torch.no_grad():\n # Prepare batch\n\n token_ids = id_tokenize[sent]\n src = torch.LongTensor(token_ids)\n labels = torch.LongTensor(label).unsqueeze(0)\n src_mask, _ = make_masks(src, src, device)\n\n src = src.to(device)\n src_mask = src_mask.to(device)\n labels = labels.to(device)\n true_labels = copy.deepcopy(labels)\n\n # Logical not on labels if transfer_style is set\n if transfer_style:\n labels = (~labels.byte()).long()\n print(labels, true_labels)\n\n preds = model_gen(src, src_mask, labels)\n\n src_label = 'pos' if true_labels.detach().item() == 1 else 'neg'\n logging.info(f'Original: text: {src_sent}')\n logging.info('Original: class: {}'.format(src_label))\n\n if embed_preds:\n preds = preds_embedding_cosine_similarity(preds, model_gen.src_embed)\n if decode_func:\n dec_sent, decoded = decode_func(preds, id2word, eos_id)\n preds_for_cls = model_gen.src_embed(decoded)\n if trans_cls:\n cls_preds = model_cls(preds_for_cls, src_mask)\n else:\n cls_preds = model_cls(preds_for_cls)\n pred_label = 'pos' if torch.argmax(cls_preds) == 1 else 'neg'\n if transfer_style:\n logging.info('Style transfer output:')\n logging.info('Predicted: text: {}'.format(dec_sent))\n logging.info('Predicted: class: {}'.format(pred_label))\n\n else:\n logging.info('Predicted: class: {}'.format(pred_label))\n logging.info('\\n')\n\"\"\"\n","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":11039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"491785289","text":"# -*- coding: utf-8 -*-\n\"\"\"Unit tests for functions.py.\"\"\"\n\nimport json\nimport os\nimport unittest\n\nimport functions\n\n\nclass TestGetWikilovesCategoryName(unittest.TestCase):\n def test_get_wikiloves_category_name(self):\n result = functions.get_wikiloves_category_name(\"Earth\", \"2016\", \"France\")\n expected = \"Images_from_Wiki_Loves_Earth_2016_in_France\"\n self.assertEqual(result, expected)\n\n def test_get_wikiloves_category_name_using_exception(self):\n result = functions.get_wikiloves_category_name(\"Earth\", \"2016\", \"Netherlands\")\n expected = \"Images_from_Wiki_Loves_Earth_2016_in_the_Netherlands\"\n self.assertEqual(result, expected)\n\n def test_get_wikiloves_category_name_using_special_exception(self):\n result = functions.get_wikiloves_category_name(\"Monuments\", \"2017\", \"Austria\")\n expected = \"Media_from_WikiDaheim_2017_in_Austria/Cultural_heritage_monuments\"\n self.assertEqual(result, expected)\n\n def test_get_wikiloves_category_name_using_event_exception(self):\n result = functions.get_wikiloves_category_name(\"Science\", \"2017\", \"Estonia\")\n expected = \"Images_from_Wiki_Science_Competition_2017_in_Estonia\"\n self.assertEqual(result, expected)\n\n def test_get_wikiloves_category_name_using_edition_exception(self):\n result = functions.get_wikiloves_category_name(\"Science\", \"2015\", \"Estonia\")\n expected = \"Images_from_European_Science_Photo_Competition_2015_in_Estonia\"\n self.assertEqual(result, expected)\n\n\nclass TestGetEventName(unittest.TestCase):\n def test_get_event_name_wikiloves(self):\n data = {\n \"earth\": \"Wiki Loves Earth\",\n \"africa\": \"Wiki Loves Africa\",\n \"monuments\": \"Wiki Loves Monuments\",\n \"monuments\": \"Wiki Loves Monuments\",\n }\n for (event_slug, event_name) in list(data.items()):\n result = functions.get_event_name(event_slug)\n self.assertEqual(result, event_name)\n\n def test_get_event_name_wikiloves_several_words(self):\n result = functions.get_event_name(\"public_art\")\n expected = \"Wiki Loves Public Art\"\n self.assertEqual(result, expected)\n\n def test_get_event_name_wikiloves_exception(self):\n result = functions.get_event_name(\"science\")\n expected = \"Wiki Science Competition\"\n self.assertEqual(result, expected)\n\n\nclass TestGetEditionName(unittest.TestCase):\n def test_get_edition_name_classic(self):\n result = functions.get_edition_name(\"monuments\", 2016)\n expected = \"Wiki Loves Monuments 2016\"\n self.assertEqual(result, expected)\n\n def test_get_edition_name_several_words(self):\n result = functions.get_edition_name(\"public_art\", 2016)\n expected = \"Wiki Loves Public Art 2016\"\n self.assertEqual(result, expected)\n\n def test_get_edition_name_exception(self):\n result = functions.get_edition_name(\"science\", 2015)\n expected = \"European_Science_Photo_Competition_2015\"\n self.assertEqual(result, expected)\n\n\nclass TestNormalizeCountryName(unittest.TestCase):\n def test_normalize_country_name_one_word(self):\n result = functions.normalize_country_name(\"Albania\")\n expected = \"Albania\"\n self.assertEqual(result, expected)\n\n def test_normalize_country_name_two_words_with_underscores(self):\n result = functions.normalize_country_name(\"United_States\")\n expected = \"United States\"\n self.assertEqual(result, expected)\n\n def test_normalize_country_name_two_words_with_spaces(self):\n result = functions.normalize_country_name(\"United States\")\n expected = \"United States\"\n self.assertEqual(result, expected)\n\n def test_normalize_country_name_three_words_with_underscores(self):\n result = functions.normalize_country_name(\"United_Arab_Emirates\")\n expected = \"United Arab Emirates\"\n self.assertEqual(result, expected)\n\n def test_normalize_country_name_three_words_with_spaces(self):\n result = functions.normalize_country_name(\"United Arab Emirates\")\n expected = \"United Arab Emirates\"\n self.assertEqual(result, expected)\n\n\nclass TestGetCountrySummary(unittest.TestCase):\n def test_get_country_summary(self):\n country_data = {\n \"Turkey\": {\n \"earth\": {\n \"2015\": {\"count\": 5, \"usage\": 0, \"userreg\": 0, \"usercount\": 1}\n },\n \"monuments\": {\n \"2016\": {\"count\": 5, \"usage\": 0, \"userreg\": 0, \"usercount\": 1},\n \"2017\": {\"count\": 8, \"usage\": 0, \"userreg\": 0, \"usercount\": 1},\n },\n },\n \"Panama\": {\n \"earth\": {\n \"2016\": {\"count\": 26, \"usage\": 0, \"userreg\": 2, \"usercount\": 2}\n },\n \"monuments\": {\n \"2016\": {\"count\": 22, \"usage\": 0, \"userreg\": 2, \"usercount\": 2}\n },\n },\n \"Benin\": {\n \"africa\": {\n \"2014\": {\"count\": 5, \"usage\": 0, \"userreg\": 0, \"usercount\": 1}\n }\n },\n }\n result = functions.get_country_summary(country_data)\n expected = {\n \"Benin\": [None, None, [\"2014\"], None, None, None, None],\n \"Panama\": [[\"2016\"], [\"2016\"], None, None, None, None, None],\n \"Turkey\": [[\"2015\"], [\"2016\", \"2017\"], None, None, None, None, None],\n }\n self.assertEqual(result, expected)\n\n\nclass TestProcessDataMixin(unittest.TestCase):\n def setUp(self):\n current_path = os.path.abspath(os.path.curdir)\n data_file = os.path.join(current_path, \"conf/db.dump.json\")\n self.data = json.load(open(data_file, \"r\"))\n\n\nclass TestProcessData(TestProcessDataMixin):\n def test_get_country_data(self):\n result = functions.get_country_data(self.data)\n expected = {\n \"Austria\": {\n \"public_art\": {\n \"2013\": {\"count\": 5, \"usage\": 0, \"usercount\": 1, \"userreg\": 0}\n }\n },\n \"Benin\": {\n \"africa\": {\n \"2014\": {\"count\": 5, \"usage\": 0, \"usercount\": 1, \"userreg\": 0}\n }\n },\n \"Estonia\": {\n \"science\": {\n \"2017\": {\"count\": 9, \"usage\": 0, \"usercount\": 1, \"userreg\": 0}\n }\n },\n \"India\": {\n \"food\": {\n \"2017\": {\"count\": 9, \"usage\": 0, \"usercount\": 1, \"userreg\": 0}\n },\n \"folklore\": {\n \"2022\": {\"count\": 9, \"usage\": 0, \"usercount\": 1, \"userreg\": 0}\n },\n },\n \"Panama\": {\n \"earth\": {\n \"2015\": {\"count\": 26, \"usage\": 0, \"usercount\": 2, \"userreg\": 2}\n },\n \"monuments\": {\n \"2016\": {\"count\": 26, \"usage\": 0, \"usercount\": 2, \"userreg\": 2}\n },\n },\n \"Turkey\": {\n \"earth\": {\n \"2015\": {\"count\": 5, \"usage\": 0, \"usercount\": 1, \"userreg\": 0}\n },\n \"monuments\": {\n \"2016\": {\"count\": 5, \"usage\": 0, \"usercount\": 1, \"userreg\": 0}\n },\n },\n }\n self.assertEqual(result, expected)\n\n def test_get_events_data(self):\n result = functions.get_events_data(self.data)\n expected = {\n \"africa\": {\n \"2014\": {\n \"count\": 5,\n \"country_count\": 1,\n \"usage\": 0,\n \"usercount\": 1,\n \"userreg\": 0,\n }\n },\n \"earth\": {\n \"2015\": {\n \"count\": 31,\n \"country_count\": 2,\n \"usage\": 0,\n \"usercount\": 3,\n \"userreg\": 2,\n }\n },\n \"food\": {\n \"2017\": {\n \"count\": 9,\n \"country_count\": 1,\n \"usage\": 0,\n \"usercount\": 1,\n \"userreg\": 0,\n }\n },\n \"folklore\": {\n \"2022\": {\n \"count\": 9,\n \"country_count\": 1,\n \"usage\": 0,\n \"usercount\": 1,\n \"userreg\": 0,\n }\n },\n \"monuments\": {\n \"2016\": {\n \"count\": 31,\n \"country_count\": 2,\n \"usage\": 0,\n \"usercount\": 3,\n \"userreg\": 2,\n }\n },\n \"public_art\": {\n \"2013\": {\n \"count\": 5,\n \"country_count\": 1,\n \"usage\": 0,\n \"usercount\": 1,\n \"userreg\": 0,\n }\n },\n \"science\": {\n \"2017\": {\n \"count\": 9,\n \"country_count\": 1,\n \"usage\": 0,\n \"usercount\": 1,\n \"userreg\": 0,\n }\n },\n }\n self.assertEqual(result, expected)\n\n def test_get_menu(self):\n result = functions.get_menu(self.data)\n expected = {\n \"earth\": [\"2015\"],\n \"monuments\": [\"2016\"],\n \"africa\": [\"2014\"],\n \"public_art\": [\"2013\"],\n \"science\": [\"2017\"],\n \"food\": [\"2017\"],\n \"folklore\": [\"2022\"],\n }\n self.assertEqual(result, expected)\n\n def test_get_edition_data(self):\n result = functions.get_edition_data(self.data, \"monuments2016\")\n expected = {\n \"Turkey\": {\n \"count\": 5,\n \"category\": \"Images_from_Wiki_Loves_Monuments_2016_in_Turkey\",\n \"end\": 20160930205959,\n \"start\": 20160831210000,\n \"userreg\": 0,\n \"usage\": 0,\n \"data\": {\n \"20160903\": {\n \"images\": 5,\n \"joiners\": 1,\n \"newbie_joiners\": 0,\n }\n },\n \"usercount\": 1,\n },\n \"Panama\": {\n \"count\": 26,\n \"category\": \"Images_from_Wiki_Loves_Monuments_2016_in_Panama\",\n \"end\": 20161001045959,\n \"start\": 20160901050000,\n \"userreg\": 2,\n \"usage\": 0,\n \"data\": {\n \"20160902\": {\n \"images\": 4,\n \"joiners\": 1,\n \"newbie_joiners\": 1,\n },\n \"20160903\": {\n \"images\": 22,\n \"joiners\": 1,\n \"newbie_joiners\": 1,\n },\n },\n \"usercount\": 2,\n },\n }\n self.assertEqual(result, expected)\n\n def test_get_instance_users_data(self):\n result = functions.get_instance_users_data(self.data, \"monuments2016\", \"Panama\")\n expected = [\n (\"Edwin Bermudez\", {\"reg\": 20160903173639, \"usage\": 0, \"count\": 22}),\n (\"Jonas David\", {\"reg\": 20160902064618, \"usage\": 0, \"count\": 4}),\n ]\n self.assertEqual(result, expected)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/test_functions.py","file_name":"test_functions.py","file_ext":"py","file_size_in_byte":11605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"537316827","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nThis module contains classes that help create pointillized images.\n\"\"\"\n\nimport numpy as np\nfrom PIL import Image, ImageDraw, ExifTags, ImageEnhance\nfrom scipy import ndimage\nimport imageio\nfrom IPython.display import display\nfrom random import random\nimport os\nimport time\nimport inspect\nfrom matplotlib import pyplot as plt\n\n# Base class definitions, handles files and image manipulations\n\n\nclass pointillize:\n \"\"\"Base class for pointillzation project\"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"Initiialize with image or directory\"\"\"\n\n # Set debug state and initialize default params\n self.debug = kwargs.get('debug', False)\n self.params = {}\n self.params['reduce_factor'] = kwargs.get('reduce_factor', 2)\n self.params['increase_factor'] = kwargs.get('increase_factor', 2)\n self.point_queue = kwargs.get('queue', False)\n self.plot_coverage = kwargs.get('plot_coverage', True)\n self.use_coverage = kwargs.get('use_coverage', True)\n if self.point_queue:\n self._initQueue()\n\n # Get image if passed, or get from location\n image = kwargs.get('image', False)\n if image is False:\n location = kwargs.get('location', False)\n if location is False:\n raise ValueError('Must pass image or location')\n self.filename = location\n self.image = Image.open(self.filename)\n else:\n self.image = image\n self.filename = ['none']\n\n # Fix orientation if image is rotated\n if hasattr(self.image, '_getexif'): # only present in JPEGs\n for orientation in ExifTags.TAGS.keys():\n if ExifTags.TAGS[orientation] == 'Orientation':\n break\n e = self.image._getexif() # returns None if no EXIF data\n if e is not None:\n exif = dict(e.items())\n if orientation in exif:\n orientation = exif[orientation]\n if orientation == 3:\n self.image = self.image.transpose(Image.ROTATE_180)\n elif orientation == 6:\n self.image = self.image.transpose(Image.ROTATE_270)\n elif orientation == 8:\n self.image = self.image.transpose(Image.ROTATE_90)\n\n # Make array and blank canvas with borders\n self._build_array()\n self.border = kwargs.get('border', 100)\n self._newImage(self.border)\n\n def _build_array(self):\n \"\"\"Builds np arrays of self.images\"\"\"\n\n d = (self.image.size[0]**2 + self.image.size[1]**2)**0.5\n self.params['reduce_factor'] = max(min(self.params['reduce_factor'],\n d / 1000), 1)\n self.params['net_factor'] = (self.params['reduce_factor'] *\n self.params['increase_factor'])\n w = int(self.image.size[0]/self.params['reduce_factor'])\n h = int(self.image.size[1]/self.params['reduce_factor'])\n resized = self.image.resize([w, h])\n self.array = np.array(resized).astype('float')\n\n def _newImage(self, border):\n \"\"\"Creates new blank canvas with border\"\"\"\n\n h = self.image.size[1] * self.params['increase_factor']\n w = self.image.size[0] * self.params['increase_factor']\n self.out = Image.new(\n 'RGB',\n [w + (border * 2), h + (border * 2)],\n (255, 255, 255))\n if self.plot_coverage:\n self.out_coverage = Image.new(\n 'L', \n [w + (border * 2), h + (border * 2)],\n (0,))\n\n def print_attributes(self):\n \"\"\"Prints non-hidden object parameters\"\"\"\n\n variables = vars(self)\n for var in variables:\n if var[0] != '_':\n if var == 'array':\n print(var, ': ', '1 numpy array ')\n else:\n print(var, ': ', variables[var])\n\n def crop(self, aspect, resize=False, direction='height'):\n \"\"\"Crops and resizes in the height dimension to match aspect ratio\"\"\"\n\n w = self.image.size[0]\n h = self.image.size[1]\n if direction == 'height':\n h_new = w * aspect[1] // aspect[0]\n self.image = self.image.crop((0, h // 2 - h_new // 2,\n w, h // 2 + h_new // 2))\n elif direction == 'width':\n w_new = h * aspect[0] // aspect[1]\n self.image = self.image.crop((w // 2 - w_new // 2, 0,\n w // 2 + w_new // 2, h))\n else:\n raise ValueError('Invalid direction argument')\n\n if resize:\n self.image = self.image.resize([aspect[0], aspect[1]])\n\n self._build_array()\n self._newImage(self.border)\n\n def enhance(self, kind='contrast', amount=1):\n \"\"\"Multiplies kind ('contrast', 'sharpness', 'color') by amount\"\"\"\n\n if kind == 'contrast':\n self.image = ImageEnhance.Contrast(self.image).enhance(amount)\n elif kind == 'sharpness':\n self.image = ImageEnhance.Sharpness(self.image).enhance(amount)\n elif kind == 'color':\n self.image = ImageEnhance.Color(self.image).enhance(amount)\n else:\n raise Exception('Invalid Type')\n\n self._build_array()\n self._newImage(self.border)\n\n def resize(self, ratio, min_size):\n \"\"\"Resizes by ratio, or to min diagonal size in pixels, \n whichever is larger\"\"\"\n\n w = self.image.size[0]\n h = self.image.size[1]\n d = (h**2 + w**2)**0.5\n ratio = max(ratio, min_size / d)\n\n self.image = self.image.resize([int(w * ratio),\n int(h * ratio)])\n\n self._build_array()\n self._newImage(self.border)\n\n def display(self, **kwargs):\n \"\"\"Displays browser-size version of outputs, or original images\n if original=True\"\"\"\n\n original = kwargs.get('original', False)\n coverage = kwargs.get('coverage', False)\n gradient = kwargs.get('gradient', False)\n if original:\n image = self.image\n elif coverage:\n image = self.out_coverage\n elif gradient:\n image = Image.fromarray((self.array_complexity*255).astype('uint8'))\n else:\n image = self.out\n\n print(self.filename)\n ratio = 1000/(image.size[0]**2 + image.size[1]**2)**0.5\n display(image.resize(\n [int(image.size[0] * ratio), int(image.size[1] * ratio)]))\n\n def _getColorOfPixel(self, loc, r):\n \"\"\"Returns RGB tuple [0,255] of average color of the np array\n of an image within a square of width 2r at location loc=[x,y]\"\"\"\n\n # Redefine location to array based on reduce factor\n loc = [int(loc[0]/self.params['net_factor']),\n int(loc[1]/self.params['net_factor'])]\n r = max(int(r/self.params['net_factor']),1)\n\n left = int(max(loc[0] - r, 0))\n right = int(min(loc[0] + r, self.array.shape[1]))\n bottom = int(max(loc[1] - r, 0))\n top = int(min(loc[1] + r, self.array.shape[0]))\n x = range(left, right)\n y = range(bottom, top)\n if len(x) == 0 | len(y) == 0:\n return (255, 255, 255)\n # R = int(self.array[np.ix_(y, x, [0])].mean())\n # G = int(self.array[np.ix_(y, x, [1])].mean())\n # B = int(self.array[np.ix_(y, x, [2])].mean())\n R = int(self.array[bottom:top, left:right, [0]].mean())\n G = int(self.array[bottom:top, left:right, [1]].mean())\n B = int(self.array[bottom:top, left:right, [2]].mean())\n\n return (R, G, B)\n\n def _plotColorPoint(self, loc, r, mask=False, **kwargs):\n \"\"\"Plots point at loc with size r with average color from\n same in array\"\"\"\n\n use_transparency = kwargs.get('use_transparency', False) \n alpha_fcn = kwargs.get('alpha_fcn', lambda: 255)\n border = self.border\n color = self._getColorOfPixel(loc, r)\n\n # Hacking together transparency here for now\n # TODO handle more generally\n if use_transparency:\n alpha = int(alpha_fcn())\n self.alpha_list.append(alpha)\n else:\n alpha = 255\n\n if self.point_queue:\n self._queueColorPoint(loc, r, color)\n else:\n new_layer = Image.new('RGBA', (int(3*r), int(3*r)), (0, 0, 0, 0))\n draw = ImageDraw.Draw(new_layer)\n draw.ellipse((0, 0, 2*r, 2*r),\n color + (alpha,))\n self.out.paste(new_layer, (border + loc[0] - int(r),\n border + loc[1] - int(r)),\n new_layer)\n\n # TODO ALSO MOVE THIS TO SEPARATE FUNCTION INSTEAD OF COPYPASTA\n if self.plot_coverage & mask:\n color = (255,255,255)\n new_layer = Image.new('RGBA', (int(2*r), int(2*r)), (0, 0, 0, 0))\n draw = ImageDraw.Draw(new_layer)\n draw.ellipse((0, 0, 2*r, 2*r),\n color + (alpha,))\n self.out_coverage.paste(new_layer, (border + loc[0] - int(r),\n border + loc[1] - int(r)),\n new_layer)\n\n def plotRecPoints(self, n=40, multiplier=1, fill=False):\n \"\"\"Plots symmetrical array of points over an image array,\n where n is the number of points across the diagonal,\n and multiplier is the ratio of the radius to the step\n and if fill is True, fills frame, otherwise leaves border\"\"\"\n\n frame_is_top = (inspect.currentframe().\n f_back.f_code.co_name == '')\n to_print = True if self.debug & frame_is_top else False\n if to_print:\n print('plotRecPoints:', end=' ')\n start = time.time()\n count = 0\n h = self.array.shape[0]*self.params['net_factor']\n w = self.array.shape[1]*self.params['net_factor']\n step = (w**2 + h**2)**0.5/n\n r = step*multiplier\n if fill:\n for x in [int(x) for x in np.linspace(0, w, w // step)]:\n for y in [int(y) for y in np.linspace(0, h, h // step)]:\n self._plotColorPoint([x, y], r)\n count+=1\n else:\n\n for x in [int(x) for x in np.linspace(r, w - r, w // step)]:\n for y in [int(y) for y in np.linspace(r, h - r,\n h // step)]:\n self._plotColorPoint([x, y], r)\n count+=1\n\n end = time.time()\n frame_is_top = (inspect.currentframe()\n .f_back.f_code.co_name == '')\n if to_print:\n print('done...took %0.2f sec for %d points' % ((end - start), count))\n\n def _getComplexityOfPixel(self, array, loc, r, use_complexity=True):\n \"\"\"DEPRECATED: Returns value [0,1] of average complexity of the np array\n of an image within a square of width 2r at location loc=[x,y]\"\"\"\n\n if use_complexity:\n loc = [int(loc[0]/self.params['net_factor']),\n int(loc[1]/self.params['net_factor'])]\n r = int(r/self.params['net_factor'])\n\n left = max(loc[0] - r, 0)\n right = min(loc[0] + r, array.shape[1])\n bottom = max(loc[1] - r, 0)\n top = min(loc[1] + r, array.shape[0])\n x = range(left, right)\n y = range(bottom, top)\n if len(x) == 0 | len(y) == 0:\n return 0\n R = array[bottom:top, left:right, [0]].max() - array[bottom:top, left:right, [0]].min()\n G = array[bottom:top, left:right, [1]].max() - array[bottom:top, left:right, [1]].min()\n B = array[bottom:top, left:right, [2]].max() - array[bottom:top, left:right, [2]].min()\n if (np.isnan(R) | np.isnan(G) | np.isnan(B)):\n R, G, B = 0, 0, 0\n return 1 - (R + G + B) / (255 * 3.0)\n else:\n return np.random.random()\n\n def _generateRandomPoints(self, n):\n h = self.out.size[1]\n w = self.out.size[0]\n locations = []\n for i in range(0, int(n)):\n locations.append([int(random() * w), int(random() * h)])\n return locations\n \n \n def _getRadiusFromComplexity(self, d, power, constant, min_size, complexity):\n \"\"\"Returns radius based on complexity calculation\"\"\"\n return np.ceil((complexity / 2)**(power) *\n d * constant * 2**power + max(d*min_size,2))\n\n def plotRandomPointsComplexity(self, n=1e5, max_skips=2e3, constant=1e-2, power=1, min_size=1e-3, **kwargs):\n \"\"\"plots random points over image, where constant is\n the portion of the diagonal for the max size of the bubble,\n and power pushes the distribution towards smaller bubbles. \n Min is the portion of the diagonal for the min bubble size\"\"\"\n\n use_transparency = kwargs.get('use_transparency', False)\n alpha_fcn = kwargs.get('alpha_fcn', lambda: ((random() * 0.5)**3 * 255 * 2**3))\n use_complexity = kwargs.get('use_complexity', True)\n use_gradient = kwargs.get('use_gradient', True)\n grad_size = kwargs.get('grad_size', 20)\n grad_mult = kwargs.get('grad_mult', 1)\n\n if use_gradient:\n self._makeComplexityArray(1, grad_size, grad_mult)\n\n locations = kwargs.get('locations', False)\n if locations is not False:\n n = len(locations)\n frame_is_top = (inspect.currentframe().\n f_back.f_code.co_name == '')\n to_print = True if self.debug & frame_is_top else False\n if to_print:\n print('plotRandomPointsComplexity:', end=' ')\n start = time.time()\n\n h = self.array.shape[0]*self.params['net_factor']\n w = self.array.shape[1]*self.params['net_factor']\n d = (h**2 + w**2)**0.5\n j = 0 \n count = 0 \n points = 0\n if self.debug: \n self.count_list = [] \n self.point_list = []\n self.time_list = []\n self.radius_list = []\n self.complexity_list = []\n self.alpha_list = []\n while True:\n count +=1\n j+=1\n\n if points > int(n): \n if to_print: print('\\nWarning: max iterations reached\\n')\n break\n if count > max_skips: \n break\n\n if self.debug: \n self.count_list.append(count)\n self.point_list.append(points)\n self.time_list.append(time.time() - start)\n\n if locations is not False:\n loc = locations[points] #TODO, check if this is used and delete if not\n else:\n loc = [int(random() * w), int(random() * h)]\n # compare with probability matrix\n if random() < self._testProbability(loc):\n if use_gradient:\n complexity = self.array_complexity[(int(loc[1]/self.params['net_factor']),\n int(loc[0]/self.params['net_factor']))]\n else:\n complexity = self._getComplexityOfPixel(\n self.array, loc, int(d * constant / 2), use_complexity)\n r = self._getRadiusFromComplexity(d, power, constant, min_size, complexity)\n self._plotColorPoint(loc, r, use_transparency=use_transparency,\n alpha_fcn=alpha_fcn, mask=True)\n if self.debug: \n self.radius_list.append(r)\n self.complexity_list.append(complexity)\n points +=1\n count = 0\n\n end = time.time()\n if to_print:\n print('done...took %0.2f sec for %d points' % ((end - start), points))\n\n def _makeMetaSettings(self):\n\n self.settings = {\n 'uniform': {\n 'PlotRecPoints': {'n': 40, 'fill': (self.border == 0)},\n 'PlotPointsComplexity': {'constant': 0.004, 'power': 1, 'grad_size': .005, 'min_size': 0.004}\n }, \n 'coarse': {\n 'PlotRecPoints': {'n': 20, 'fill': (self.border == 0)},\n 'PlotPointsComplexity': {'constant': 0.016, 'power': 2, 'grad_size': .019, 'min_size': 0.004}\n },\n 'balanced': {\n 'PlotRecPoints': {'n': 100, 'fill': (self.border == 0)},\n 'PlotPointsComplexity': {'constant': 0.012, 'power': 3, 'grad_size': .015, 'min_size': 0.002}\n },\n 'fine': {\n 'PlotRecPoints': {'n': 100, 'fill': (self.border == 0)},\n 'PlotPointsComplexity': {'constant': 0.008, 'power': 3, 'grad_size': .01, 'min_size': 0.001}\n },\n 'ultrafine': {\n 'PlotRecPoints': {'n': 100, 'fill': (self.border == 0)},\n 'PlotPointsComplexity': {'constant': 0.005, 'power': 3, 'grad_size': .006, 'min_size': 0.0005}\n },\n }\n\n def plot(self, setting='balanced', n=1e5, max_skips=2e3,\n use_transparency=False, alpha_fcn=lambda: 255,):\n \"\"\"Makes plots with present settings and optional arguments\"\"\"\n\n self._makeMetaSettings() # TODO MOVE TO INIT\n\n if setting not in self.settings.keys():\n raise Exception(\"Invalid setting\")\n\n frame_is_top = (inspect.currentframe().\n f_back.f_code.co_name == '')\n to_print = True if self.debug & frame_is_top else False\n start = time.time()\n\n self.plotRecPoints(**self.settings[setting]['PlotRecPoints'])\n self.plotRandomPointsComplexity(**self.settings[setting]['PlotPointsComplexity'])\n\n if to_print: print('done in %0.2f seconds' % (time.time() - start))\n\n def _queueColorPoint(self, loc, r, color):\n \"\"\"Builds queue of color points\"\"\"\n self.pointQueue.append({'loc': loc, 'r': r, 'color': color})\n\n def _initQueue(self):\n \"\"\"Builds new point queue\"\"\"\n self.pointQueue = []\n\n def _plotQueue(self, multiplier):\n \"\"\"Plots point queue\"\"\"\n self._newImage(self.border)\n border = self.border\n for point in self.pointQueue:\n loc = point['loc']\n r = int(point['r'] * multiplier)\n color = point['color']\n draw = ImageDraw.Draw(self.out)\n draw.ellipse((border + loc[0] - r, (border + loc[1] - r),\n border + loc[0] + r, (border + loc[1] + r)),\n color + (255,))\n\n def _makeComplexityArray(self, sigma1, sigma2, multiplier=.8):\n\n h = self.array.shape[0]\n w = self.array.shape[1]\n d = (h**2 + w**2)**0.5\n gradient = ndimage.gaussian_gradient_magnitude(self.array.sum(axis=2), sigma=sigma1)\n gradient2 = ndimage.maximum_filter(gradient, size=d*sigma2)\n\n #gradient_sum = gradient + gradient2\n self.array_complexity = 1 - gradient2/gradient2.max()*multiplier-(1-multiplier)\n #self.array_complexity = 1 - gradient/gradient.max()\n\n def _testProbability(self, loc):\n if self.use_coverage:\n location = (loc[0] + self.border, loc[1] + self.border)\n probability = max(1 - self.out_coverage.getdata().getpixel(location)/255, 0)\n\n else:\n probability = 1\n\n return probability\n\n def _plotIterations(self):\n \n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n ax1.plot(self.count_list)\n ax2.plot(self.time_list, self.count_list)\n ax1.set_ylabel('Consecutive non-plots')\n ax1.set_xlabel('Iteration')\n ax2.set_xlabel('Seconds')\n ax1.ticklabel_format(style='sci', axis='x', scilimits=(0,0))\n ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0))\n f.set_figwidth(10)\n\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n ax1.plot(self.point_list)\n ax2.plot(self.time_list, self.point_list)\n ax1.set_ylabel('Plotted points')\n ax1.set_xlabel('Iterations')\n ax2.set_xlabel('Seconds')\n ax1.ticklabel_format(style='sci', axis='x', scilimits=(0,0))\n ax1.ticklabel_format(style='sci', axis='y', scilimits=(0,0))\n f.set_figwidth(10)\n plt.show() \n\n\n def _plotBubbleSize(self):\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n ax1.hist(self.radius_list, bins=100, orientation='horizontal')\n ax2.plot(self.radius_list, '.', alpha=min(0.5, 3e4/len(self.point_list)))\n ax1.set_ylabel('Radius')\n ax1.set_xlabel('Count')\n ax2.set_xlabel('Iteration')\n ax1.ticklabel_format(style='sci', axis='x', scilimits=(0,0))\n ax2.ticklabel_format(style='sci', axis='x', scilimits=(0,0))\n f.set_figwidth(10)\n plt.show()\n \n def _plotComplexity(self):\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n ax1.hist(self.complexity_list, bins=100, orientation='horizontal')\n ax2.scatter(x=self.radius_list, y=self.complexity_list, s=0.5)\n ax1.set_ylabel('Complexity')\n ax1.set_xlabel('Count')\n ax2.set_xlabel('Radius')\n ax1.ticklabel_format(style='sci', axis='x', scilimits=(0,0))\n f.set_figwidth(10)\n plt.show()\n\n def _plotAlpha(self):\n f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)\n ax1.hist(self.alpha_list, bins=100, orientation='horizontal')\n ax2.plot(self.alpha_list, '.', alpha=min(0.5, 3e4/len(self.point_list)))\n ax1.set_ylabel('Alpha')\n ax1.set_xlabel('Count')\n ax2.set_xlabel('Iteration')\n ax1.ticklabel_format(style='sci', axis='x', scilimits=(0,0))\n f.set_figwidth(10)\n plt.show()\n \n\n def save_out(self, location, **kwargs):\n \"\"\"Saves files to location\"\"\"\n\n suffix = kwargs.get('suffix', '')\n prefix = kwargs.get('prefix', '')\n\n if os.path.isdir(location) is not True:\n os.makedirs(location)\n\n self.out.save(\n location + '/' + prefix + self.filename.split('/')[1:][0] +\n ' - ' + suffix + '.png')\n\n\n# Subclass adding workflows and image stack (gif) handling\n\nclass pointillizeStack(pointillize):\n \"\"\"Subclass of pointillize for making stacks of images.\n Only supports single images currently\"\"\"\n\n def __init__(self, *args, **kwargs):\n\n pointillize.__init__(self, *args, **kwargs)\n\n def new_queue(self):\n \"\"\"Builds a new set of lists for the queue\"\"\"\n\n self.queue = {'methods': [], 'names': [], 'args': [], 'repeats': []}\n\n def add_to_queue(self, method, args, n):\n \"\"\"Adds a new method to the queue, to be run with args, n times\"\"\"\n\n self.queue['methods'].append(method)\n self.queue['names'].append(method.__name__)\n self.queue['args'].append(args)\n self.queue['repeats'].append(n)\n\n def print_queue(self):\n \"\"\"Prints current status of the queue\"\"\"\n for i, method in enumerate(self.queue['methods']):\n print(self.queue['names'][i], self.queue['args']\n [i], self.queue['repeats'][i])\n\n def run_queue(self, **kwargs):\n \"\"\"Runs queue, primarily for build_stacks()\"\"\"\n\n # Make new image\n self._newImage(self.border)\n\n # Set some parameters\n save_steps = kwargs.get('save_steps', False)\n frame_is_top = (inspect.currentframe().\n f_back.f_code.co_name == '')\n\n to_print = True if self.debug & (frame_is_top | save_steps) else False\n\n if save_steps:\n if not dir().__contains__('self.image_stack'):\n self.image_stack = []\n\n for i, method in enumerate(self.queue['methods']):\n in_kwargs = self.queue['args'][i]\n n = self.queue['repeats'][i]\n\n if to_print:\n print(method.__name__ + ':', end=' ')\n\n for i in range(0, n):\n method(**in_kwargs)\n if save_steps:\n self.image_stack.append(self.out.copy())\n if to_print:\n print(i + 1, end=' ')\n if to_print:\n print(\"done\")\n\n def build_stacks(self, n, save_steps):\n \"\"\"Makes an image stack by running the pipeline n times,\n saving intermediate steps if save_steps is true\"\"\"\n\n self.image_stack = []\n\n to_print = True if (self.debug & save_steps is not True) else False\n\n if to_print:\n print('Building image: ', end=' ')\n for j in range(0, n):\n if to_print:\n print(j + 1, end=' ')\n self._newImage(self.border)\n self.run_queue(save_steps=save_steps)\n self.image_stack.append(self.out)\n if to_print:\n print('done')\n\n def build_multipliers(self, plot_list, **kwargs):\n \"\"\"Plots the point queue repeatedly with multipliers from list set\"\"\"\n self.image_stack = []\n\n to_print = self.debug\n reverse = kwargs.get('reverse', True)\n reverse_list = kwargs.get('reverse_list', False)\n if reverse_list:\n self.pointQueue = sorted(self.pointQueue, key=lambda k: k['r'])\n n = len(plot_list)\n if to_print:\n print('Building image: ', end=' ')\n for j in range(0, n):\n if to_print:\n print(j + 1, end=' ')\n self._plotQueue(plot_list[j])\n self.image_stack.append(self.out)\n\n if reverse:\n self.image_stack += self.image_stack[::-1]\n\n if to_print:\n print('done')\n\n def save_gif(self, location, step_duration, **kwargs):\n \"\"\"Save a gif of the image stack with step_duration\"\"\"\n\n arrays = []\n for out in self.image_stack:\n arrays.append(np.array(out))\n\n imageio.mimsave(location, arrays, format='gif', duration=step_duration)\n\n\nclass pointillizePile(pointillizeStack):\n \"\"\"Subclass of pointillizeStack for operating serially on images\"\"\"\n\n def __init__(self, *args, **kwargs):\n\n location = kwargs.get('location', False)\n if location is False:\n raise ValueError('Must declare directory to initialize')\n else:\n self.pile_filenames = []\n if os.path.isdir(location):\n for file in os.listdir(location):\n if file.endswith(\".jpg\") | file.endswith(\".JPG\") | file.endswith(\".jpeg\") | file.endswith(\".JPEG\"):\n self.pile_filenames.append(location + file)\n else:\n raise ValueError('Must declare directory to initialize')\n\n self.outputs_store = []\n self.inputs_store = []\n self.filenames_store = []\n self._kwargs = kwargs\n self._args = args\n self._init_pointilize(index=0)\n\n def _init_pointilize(self, index):\n\n args = self._args\n kwargs = self._kwargs\n kwargs['location'] = self.pile_filenames[index]\n pointillize.__init__(self, *args, **kwargs)\n\n def display(self, **kwargs):\n \"\"\"Displays browser-size version of outputs, or original images\n if original=True\"\"\"\n\n original = kwargs.get('original', False)\n for i in range(len(self.inputs_store)):\n image = self.inputs_store[i] if original else self.outputs_store[i]\n print(self.filenames_store[i])\n ratio = 500/(image.size[0]**2 + image.size[1]**2)**0.5\n display(image.resize(\n [int(image.size[0] * ratio), int(image.size[1] * ratio)]))\n\n def run_pile_images(self, location, **kwargs):\n \"\"\"Process and save files to location\"\"\"\n\n print('Batch processing image:', end=' ')\n start=time.time()\n for i in range(0, len(self.pile_filenames)):\n print(i + 1, end=' ')\n self._init_pointilize(i)\n self.run_queue()\n self.save_out(location, **kwargs)\n self.filenames_store.append(self.filename)\n self.inputs_store.append(self.image)\n self.outputs_store.append(self.out)\n print('done....took %0.2f seconds' % (time.time()-start))\n\n\n def run_pile_gifs(self, location, n, save_steps, step_duration, **kwargs):\n\n suffix = kwargs.get('suffix', '')\n\n if os.path.isdir(location) is not True:\n os.makedirs(location)\n\n for i in range(0, len(self.pile_filenames)):\n print(i + 1, end=' ')\n self._init_pointilize(i)\n self.build_stacks(n, save_steps)\n self.save_gif(location + '/' + self.filename.split('/')[1] +\n ' ' + suffix + '.gif', step_duration, **kwargs)\n\n def run_pile_multipliers(self, location, multipliers,\n step_duration, **kwargs):\n\n suffix = kwargs.get('suffix', '')\n reverse = kwargs.get('reverse', False)\n\n if os.path.isdir(location) is not True:\n os.makedirs(location)\n\n for i in range(0, len(self.pile_filenames)):\n print(i + 1, end=' ')\n self._init_pointilize(i)\n self.run_queue()\n self.build_multipliers(multipliers, reverse=reverse)\n self.save_gif(location + '/' + self.filename.split('/')[1] +\n ' ' + suffix + '.gif', step_duration, **kwargs)\n","sub_path":"Archived/Pointilism/pointillism.py","file_name":"pointillism.py","file_ext":"py","file_size_in_byte":29584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"134477574","text":"import unittest\n\nimport pytest\nfrom kinto_remote_settings.signer import utils\nfrom pyramid.exceptions import ConfigurationError\n\n\nclass ParseResourcesTest(unittest.TestCase):\n def test_missing_arrow_raises_an_exception(self):\n raw_resources = \"\"\"\n foo bar\n \"\"\"\n with pytest.raises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n def test_non_local_first_argument_raises_an_exception(self):\n raw_resources = \"\"\"\n foo -> bar\n bar -> baz\n \"\"\"\n with pytest.raises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n def test_malformed_url_raises_an_exception(self):\n raw_resources = \"\"\"\n /buckets/sbid/scid -> /buckets/dbid/collections/dcid\n \"\"\"\n with pytest.raises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n def test_outnumbered_urls_raises_an_exception(self):\n raw_resources = (\n \"/buckets/sbid/scid -> \"\n \"/buckets/dbid/collections/dcid -> \"\n \"/buckets/dbid/collections/dcid -> \"\n \"/buckets/sbid/scid\"\n )\n with pytest.raises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n def test_returned_resources_match_the_expected_format(self):\n raw_resources = \"\"\"\n /buckets/sbid/collections/scid -> /buckets/dbid/collections/dcid\n \"\"\"\n resources = utils.parse_resources(raw_resources)\n assert resources == {\n \"/buckets/sbid/collections/scid\": {\n \"source\": {\"bucket\": \"sbid\", \"collection\": \"scid\"},\n \"destination\": {\"bucket\": \"dbid\", \"collection\": \"dcid\"},\n }\n }\n\n def test_returned_resources_match_the_legacy_format(self):\n raw_resources = \"\"\"\n sbid/scid -> dbid/dcid\n \"\"\"\n resources = utils.parse_resources(raw_resources)\n assert resources == {\n \"/buckets/sbid/collections/scid\": {\n \"source\": {\"bucket\": \"sbid\", \"collection\": \"scid\"},\n \"destination\": {\"bucket\": \"dbid\", \"collection\": \"dcid\"},\n }\n }\n\n raw_resources = \"\"\"\n sbid/scid ; dbid/dcid\n \"\"\"\n resources = utils.parse_resources(raw_resources)\n assert resources == {\n \"/buckets/sbid/collections/scid\": {\n \"source\": {\"bucket\": \"sbid\", \"collection\": \"scid\"},\n \"destination\": {\"bucket\": \"dbid\", \"collection\": \"dcid\"},\n }\n }\n\n def test_spaces_are_supported(self):\n raw_resources = \"\"\"\n /buckets/bid1/collections/scid1 -> /buckets/bid1/collections/dcid1\n /buckets/bid2/collections/scid2 -> /buckets/bid2/collections/dcid2\n \"\"\"\n resources = utils.parse_resources(raw_resources)\n assert len(resources) == 2\n assert (\n resources[\"/buckets/bid1/collections/scid1\"][\"source\"][\"bucket\"] == \"bid1\"\n )\n assert (\n resources[\"/buckets/bid2/collections/scid2\"][\"source\"][\"bucket\"] == \"bid2\"\n )\n\n def test_multiple_resources_are_supported(self):\n raw_resources = \"\"\"\n /buckets/sbid1/collections/scid1 -> /buckets/dbid1/collections/dcid1\n /buckets/sbid2/collections/scid2 -> /buckets/dbid2/collections/dcid2\n \"\"\"\n resources = utils.parse_resources(raw_resources)\n assert len(resources) == 2\n\n def test_a_preview_collection_is_supported(self):\n raw_resources = (\n \"/buckets/stage/collections/cid -> \"\n \"/buckets/preview/collections/cid -> \"\n \"/buckets/prod/collections/cid -> \"\n )\n resources = utils.parse_resources(raw_resources)\n assert resources == {\n \"/buckets/stage/collections/cid\": {\n \"source\": {\"bucket\": \"stage\", \"collection\": \"cid\"},\n \"preview\": {\"bucket\": \"preview\", \"collection\": \"cid\"},\n \"destination\": {\"bucket\": \"prod\", \"collection\": \"cid\"},\n }\n }\n\n def test_resources_should_be_space_separated(self):\n raw_resources = (\n \"/buckets/sbid1/collections/scid -> /buckets/dbid1/collections/dcid,\"\n \"/buckets/sbid2/collections/scid -> /buckets/dbid2/collections/dcid\"\n )\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n raw_resources = \"sbid1/scid -> dbid1/dcid,sbid2/scid -> dbid2/dcid\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n def test_resources_must_be_valid_names(self):\n raw_resources = (\n \"/buckets/sbi+d1/collections/scid -> /buckets/dbid1/collections/dci,d\"\n )\n with self.assertRaises(ConfigurationError) as e:\n utils.parse_resources(raw_resources)\n assert repr(e.exception).startswith(\n 'ConfigurationError(\"Malformed resource: '\n \"bucket or collection id is invalid\"\n )\n\n def test_resources_can_be_defined_per_bucket(self):\n raw_resources = \"/buckets/stage -> /buckets/preview -> /buckets/prod\"\n resources = utils.parse_resources(raw_resources)\n assert resources == {\n \"/buckets/stage\": {\n \"source\": {\"bucket\": \"stage\", \"collection\": None},\n \"preview\": {\"bucket\": \"preview\", \"collection\": None},\n \"destination\": {\"bucket\": \"prod\", \"collection\": None},\n }\n }\n\n def test_cannot_mix_per_bucket_and_per_collection(self):\n raw_resources = \"/buckets/stage -> /buckets/prod/collections/boom\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n raw_resources = (\n \"/buckets/stage/collections/boom -> \"\n \"/buckets/preview/collections/boom -> \"\n \"/buckets/prod\"\n )\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n raw_resources = (\n \"/buckets/stage -> /buckets/preview/collections/boom -> /buckets/prod\"\n )\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n raw_resources = \"/buckets/stage/collections/boom -> /buckets/prod\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n def test_cannot_repeat_source_preview_or_destination(self):\n raw_resources = \"/buckets/stage -> /buckets/stage -> /buckets/prod\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n raw_resources = \"/buckets/stage -> /buckets/preview -> /buckets/stage\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n raw_resources = \"/buckets/stage -> /buckets/preview -> /buckets/preview\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n def test_cannot_repeat_resources(self):\n # Repeated source.\n raw_resources = \"\"\"\n /buckets/stage -> /buckets/preview1 -> /buckets/prod1\n /buckets/stage -> /buckets/preview2 -> /buckets/prod2\n \"\"\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n # Repeated reviews.\n raw_resources = \"\"\"\n /buckets/stage1 -> /buckets/preview -> /buckets/prod1\n /buckets/stage2 -> /buckets/preview -> /buckets/prod2\n \"\"\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n # Repeated destination.\n raw_resources = \"\"\"\n /buckets/stage1 -> /buckets/prod\n /buckets/stage2 -> /buckets/preview -> /buckets/prod\n \"\"\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n # Source in other's preview.\n raw_resources = \"\"\"\n /buckets/stage -> /buckets/preview -> /buckets/prod\n /buckets/bid1 -> /buckets/stage -> /buckets/bid2\n \"\"\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n # Source in other's destination.\n raw_resources = \"\"\"\n /buckets/b/collections/c -> /buckets/b/collections/c2 -> /buckets/b/collections/c3\n /buckets/b/collections/ca -> /buckets/b/collections/cb -> /buckets/b/collections/c\n \"\"\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n\n # Preview in other's destination.\n raw_resources = \"\"\"\n /buckets/b/collections/c0 -> /buckets/b/collections/c1 -> /buckets/b/collections/c2\n /buckets/b/collections/ca -> /buckets/b/collections/cb -> /buckets/b/collections/c1\n \"\"\"\n with self.assertRaises(ConfigurationError):\n utils.parse_resources(raw_resources)\n","sub_path":"kinto-remote-settings/tests/signer/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":8911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"636085322","text":"#!/opt/softs/workshop/current/bin/python\n# -*- coding: utf-8 -*-\n'''\nCreated on Mar 16, 2010\n\n@author: vgazeill\n'''\n\nimport logging\nLOGGIN_FORMAT = '[TestCI_%(levelname)-8s] %(module)-15s.%(funcName)s: %(message)s'\nlogging.basicConfig(format=LOGGIN_FORMAT, level=logging.DEBUG)\n\n\nimport urllib2\n\n\n\ndef urlToFile(urlStr, outputFile):\n \n hLog = open(outputFile, 'w')\n if not hLog: \n return(False, \"Cant't write output file %s\" % (outputFile))\n \n try:\n fileHandle = urllib2.urlopen(urlStr)\n for line in fileHandle.readlines():\n hLog.write(line)\n fileHandle.close()\n \n except IOError:\n return (False, 'Cannot open URL %s for reading' % (urlStr))\n \n finally:\n if hLog: \n hLog.close()\n \n return (True, urlStr)\n\n\ndef isValidURL(url):\n \n req = urllib2.Request(url)\n try:\n urllib2.urlopen(req).readlines()\n return True\n \n except IOError:\n return False\n \n \n try:\n f = urllib2.urlopen(url)\n if f:\n f.close\n return True\n except:\n return False\n \n\n#if __name__ == '__main__':\n#\n# print str(urlToFile('http://nux08080:8085/job/CSATG5_functional/3164/console',\n# '/local/tmpAtt/log.txt'))\n# \n# \n# \n# \n ","sub_path":"main/Tools/HttpTools.py","file_name":"HttpTools.py","file_ext":"py","file_size_in_byte":1320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"473518476","text":"import doutil\nimport ec2\n\nleave = doutil.swarm_leave()\njoincmd = doutil.swarm_init()\nprint(joincmd)\n\n#ships = ['ship1']\n#ships = ['a1-ship1', 'a1-ship2']\nships = ['worker1', 'worker2']\n\nfor ship in ships:\n ip = ec2.returnIp(ship)\n pem = '-i /home/ubuntu/bucketlauncher2-keypair.pem '\n options = '-o \\\"StrictHostKeyChecking no\\\" '\n user = 'ubuntu@'+ip\n cmd = 'ssh ' + pem + options + user + ' ' + '\\'' + 'sudo' + joincmd +'\\''\n print(cmd)\n doutil.subprocess_cmd(cmd)\n\ncmd = 'sudo docker node ls'\nout = doutil.subprocess_cmd(cmd)\nprint(out)\n","sub_path":"djup/swarm/gaSwarm.py","file_name":"gaSwarm.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"23434718","text":"# -*- coding:utf-8 -*-\nimport os\n\nfrom selenium.webdriver import ChromeOptions\n\nfrom .webdriver import ChromeDriver, enable_headless_download\n\n\nclass DriverFactory:\n @classmethod\n def __format_driverpath(cls, path=None):\n default = 'chromedriver'\n\n if path is None or path == default:\n path = default\n\n elif path.startswith('~'):\n path = os.path.expanduser(path)\n\n else:\n path = os.path.abspath(path)\n\n return path\n\n @classmethod\n def __setup_options(cls, options, **kwargs):\n op = dict(\n headless='--headless' in options.arguments,\n downloadpath=kwargs.get('downloadpath', None)\n )\n\n return op\n\n def __init__(self, driverpath=None, options=None,\n setup_func=None, *args, **kwargs):\n\n if options is not None \\\n and not isinstance(options, ChromeOptions):\n raise TypeError(\"chrome_options must be 'webdriver.ChromeOptions'\")\n\n self.driverpath = self.__format_driverpath(driverpath)\n self.options = options or ChromeOptions()\n self.driver_setup = setup_func if setup_func else self.__setup_func\n self.setup_options = \\\n self.__setup_options(self.options, **kwargs)\n self.driver = None\n\n def __enter__(self):\n self.driver = ChromeDriver(\n executable_path=self.driverpath,\n options=self.options)\n self.driver_setup(**self.setup_options)\n\n self.driver.implicitly_wait(5)\n return self.driver\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.driver.close()\n self.driver.quit()\n\n def __setup_func(self, headless=False, downloadpath=None):\n if headless and downloadpath:\n enable_headless_download(self.driver, downloadpath)\n","sub_path":"seleniuk/chrome/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"497515023","text":"import pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\n\ndef change_male_female_to_bynary_value(data):\n sex_mapping = {'male': 1, 'female': 0}\n return data.applymap(lambda s: sex_mapping.get(s) if s in sex_mapping else s)\n\ndef fillnavalue(data):\n #return data.fillna(train_data.mean()) # заменяем средними значениями по колонке\n data['Age'] = data['Age'].fillna(data['Age'].mean())\n data[['SibSp', 'Parch', 'Fare']] = data[['SibSp', 'Parch', 'Fare']].fillna(value=0)\n data['Cabin'] = data[['Cabin']].fillna(value=0)\n cabin_mapping = {'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5, 'F': 6}\n data['top_cabin'] = data['Cabin'].astype(str).str[0]\n data['top_cabin'] = data.applymap(lambda s: cabin_mapping.get(s) if s in cabin_mapping else s)\n return data\n\nsns.set(color_codes=True)\ntrain_data = pd.read_csv(\"data/train.csv\")\ntest_data = pd.read_csv(\"data/test.csv\")\n\ntrain_data = change_male_female_to_bynary_value(train_data)\ntest_data = change_male_female_to_bynary_value(test_data)\n\ntrain_data = fillnavalue(train_data)\ntest_data = fillnavalue(test_data)\n\n\n\n# df.dropna() - удалить все наны\ntrain_data_x = train_data[['Pclass', 'Sex', 'Age', 'Parch', 'SibSp', 'top_cabin']].copy()\ntrain_data_y = train_data[['Survived']].copy()\ntest_data_x = test_data[['Pclass', 'Sex', 'Age', 'Parch', 'SibSp', 'top_cabin']].copy()\nfull_test_data = test_data\n\n\n\n\n#sns.barplot(x=train_data.Sex,y=train_data.Age)\n#plt.show(sns)\n\n\n\n\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"327904477","text":"import gc\nimport os\nimport sys\nfrom collections import Counter\n\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.python import set_random_seed, reset_default_graph, ops\nfrom tensorflow.python.keras.backend import clear_session\n\nfrom Glove.glovemodel import GloVe\nfrom rootfile import ROOTPATH\nfrom utility.Parameters import leaky_to_linear\nfrom utility.Random_Parameters import get_random_params\nfrom utility.argument_parser import parse_arguments\nfrom utility.minimal_loader import check_mini_load\nfrom utility.utility import setup_result_folder\n\nalgorithms_to_use, datasets_to_use, amount, dataset_mode = parse_arguments(sys.argv)\nfor dataset in datasets_to_use:\n dataset.mode = dataset_mode\n is_mini, mini_labels = check_mini_load(dataset, dataset_mode, 300)\n if is_mini:\n labels = mini_labels\n dataset.set_classes()\n emails = None\n else:\n emails, labels = dataset.load(dataset_mode=dataset_mode)\n\n glove = GloVe(300)\n\n features = glove.get_features(emails, dataset)\n\n for algorithm in algorithms_to_use:\n print(\"Running algorithm:\", algorithm.get_name())\n\n if not os.path.exists(ROOTPATH + \"Results/\" + dataset_mode + \"/\" + algorithm.get_name() + \"/\" + dataset.get_name() + \"/plots\"):\n os.makedirs(ROOTPATH + \"Results/\" + dataset_mode + \"/\" + algorithm.get_name() + \"/\" + dataset.get_name() + \"/plots\")\n\n setup_result_folder(algorithm.get_name(), dataset.get_name())\n best_fscore = 0\n best_fscore_list = []\n output_dim = len(set(labels))\n assert not np.any(np.isnan(features))\n # Create training data\n x_train, x_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=1, stratify=labels)\n\n print(Counter(y_train))\n for counter in range(1, (amount + 1)):\n np.random.seed(1)\n set_random_seed(1)\n print(\"#### STARTING RUN NUMBER {} #####\".format(counter))\n parameters = leaky_to_linear(get_random_params(algorithm.get_name(), output_dim))\n print(str(parameters))\n try:\n algorithm.run_train(dataset, x_train, y_train, x_test, y_test, parameters, should_plot=False)\n except Exception as e:\n print(\"Caught exception: \" + str(e))\n continue\n\n avg_fscore = np.average(algorithm.fscore)\n if avg_fscore > best_fscore:\n print('New champion! {}'.format(avg_fscore))\n best_fscore = avg_fscore\n algorithm.plot_data(dataset, y_test)\n\n clear_session()\n reset_default_graph()\n ops.reset_default_graph()\n gc.collect()\n","sub_path":"src/parameter_search.py","file_name":"parameter_search.py","file_ext":"py","file_size_in_byte":2744,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"136956615","text":"# Exercise 2.7\r\n\r\nprint (\"=========== Making Change ===========\")\r\nprint()\r\n\r\nchange = input (\"Enter an amount, integer, <100: \")\r\ntotal = int(change)\r\ncoin = 25 # To use 50 cent piece set this to 50\r\nwhile total>4:\r\n k = total//coin\r\n if k>0:\r\n print (k, \"coins of value\", coin)\r\n total = total - k*coin\r\n if coin==25:\r\n coin = 10\r\n else:\r\n coin = coin//2\r\nif total > 0:\r\n print (total, \" pennies\")\r\n\r\nprint (\"--------------------------------------------------------\")\r\n\r\n\r\n# Output:\r\n# Draw histogram for WidgetCorp Earnings in 2016.\r\n# Enter earning for the first quarter: 900000\r\n# Enter earning for the second quarter:874000\r\n# Enter earning for the third quarter:200000\r\n# Enter earning for the fourth quarter:439000\r\n# Earnings for WidgetCorp for 2016\r\n# Dollars for each quarter\r\n# ==============================\r\n# Q1: ############################################ 900000\r\n# Q2: ########################################## 874000\r\n# Q3: ######### 200000\r\n# Q4: #################### 439000","sub_path":"275-Langs/Python/python_anintroductiontoprogramming_supplement/Solutions/CH 2/exercise7.py","file_name":"exercise7.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"589070078","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\n\n# Create your views here.\nfrom django.http import JsonResponse\n\n\ndef update_info(request):\n attr = request.GET.get('attr', None)\n new_val = request.GET.get('new_val', None)\n try:\n setattr(request.user.profile, attr, new_val)\n request.user.profile.save()\n return JsonResponse({'status': 'Success', 'msg': 'save successfully'})\n except TypeError:\n return JsonResponse({'status':'Fail', 'msg': 'empty request'})","sub_path":"src/profiles/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"153284384","text":"#!/usr/bin/env python\n# coding: utf-8\n\n\nfrom mpi4py import MPI\n#import matplotlib.pyplot as plt\nimport numpy as np\nimport time\nimport scipy.stats as sts\n\n\ndef sim_lifetime():\n \n comm = MPI.COMM_WORLD\n rank = comm.Get_rank()\n size = comm.Get_size()\n t0 = time.time()\n\n rho = 0.5\n mu = 3.0\n sigma = 1.0\n z_0 = mu\n\n\n S = 1000 \n T = int(4160)\n np.random.seed(25)\n\n # scatter to processors\n #if rank == 0:\n # eps_mat = sts.norm.rvs(loc=0, scale=sigma, size=(S, T))\n #else:\n #eps_mat = None\n # eps_mat = comm.scatter(eps_mat, root=0)\n \n\n #N = eps_mat.shape[0]\n N = int(S/size)\n eps_mat = sts.norm.rvs(loc=0, scale=sigma, size=(N, T))\n z_mat = np.zeros((N, T))\n z_mat[0, :] = z_0\n\n for s_ind in range(N):\n z_tm1 = z_0\n for t_ind in range(T):\n e_t = eps_mat[s_ind, t_ind]\n z_t = rho * z_tm1 + (1 - rho) * mu + e_t\n z_mat[s_ind, t_ind] = z_t\n z_tm1 = z_t\n\n # gather all simulations\n z_all = None\n if rank == 0:\n z_all = np.empty([S, T], dtype='float')\n #comm.Gather(sendbuf = z_mat, recvbuf = z_all, root=0)\n comm.gather(z_mat, root = 0)\n \n if rank == 0:\n time_elapsed = time.time() - t0\n print(\"Simulated 1000 lifetimes in: %f seconds on %d MPI processes\"\n % (time_elapsed, size))\n #return time_elapsed\n\n return\n\ndef main():\n sim_lifetime()\n\nif __name__ == '__main__':\n main()\n","sub_path":"HW1Q1.py","file_name":"HW1Q1.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"571265832","text":"from speculator.utils import poloniex\n\"\"\"\nOn Balance Volume:\nOBV = OBV_prev + v\n such that,\n v = volume if close > close_prev\n v = 0 if close == close_prev\n v = -volume if close < close_prev\n\"\"\"\n\ndef eval_algorithm(curr, prev):\n \"\"\" Evaluates OBV\n\n Args:\n curr: Dict of current volume and close\n prev: Dict of previous OBV and close\n \n Returns:\n Float of OBV \n \"\"\"\n if curr['close'] > prev['close']:\n v = curr['volume']\n elif curr['close'] < prev['close']:\n v = curr['volume'] * -1\n else:\n v = 0\n return prev['obv'] + v\n\ndef get_poloniex(*args):\n \"\"\" Gets OBV of a currency pair from Poloniex.com exchange\n\n Returns:\n Float of OBV\n \"\"\"\n return from_poloniex(poloniex.get_json_shift(*args))\n\ndef from_poloniex(json):\n \"\"\" Gets OBV from a JSON of market data\n\n Args:\n json: List of dates where each entry is a dict of raw market data.\n\n Returns:\n Float of OBV\n \"\"\"\n closes = poloniex.get_attribute(json, 'close')\n volumes = poloniex.get_attribute(json, 'volume')\n for date, _ in enumerate(json):\n if date == 0:\n obv = 0\n continue\n curr = {'close': closes[date], 'volume': volumes[date]}\n prev = {'close': closes[date - 1], 'obv': obv}\n obv = eval_algorithm(curr, prev)\n return obv\n\n","sub_path":"speculator/features/obv.py","file_name":"obv.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"228280744","text":"from flask import Flask, request\nfrom flask_cors import CORS\nimport logging\nimport numpy as np\nimport pandas as pd\nimport sys\nimport pymongo\nimport re\nimport json\nimport time\nfrom datetime import datetime\nimport pandas as pd\n\napp = Flask(__name__)\nCORS(app)\nhandler = logging.FileHandler('app.log', encoding='UTF-8')\nlogging_format = logging.Formatter(\n '%(asctime)s - %(levelname)s - %(filename)s - %(funcName)s - %(lineno)s - %(message)s')\nhandler.setFormatter(logging_format)\napp.logger.addHandler(handler)\n# 连接\n\n\ndef content_mongo(host, port, db):\n client = pymongo.MongoClient(host, port)\n return client[db]\ndef getTime(dbs,keyword,start,end,query={}, host='localhost', port=27017):\n db = content_mongo(host, port, dbs)\n data = db.data3.find({'keyword': {'$in': keyword},'date':{\"$gte\":start,\"$lte\":end}}, {'_id': 0})\n datalist = []\n for item in data:\n if item not in datalist:\n datalist.append(item)\n df=pd.DataFrame(datalist).set_index('date')\n df=df.groupby(df['keyword'])\n df=list(df)\n df=dict(df)\n arr=[]\n for item in df:\n obj={}\n a=pd.DataFrame(df[item])\n temp=a['count'].to_json(orient='split')\n tempArr=json.loads(temp)\n obj['time']=tempArr['index']\n obj['data']=tempArr['data']\n obj['keyword']=item\n arr.append(obj)\n return json.dumps(arr, ensure_ascii=False)\n\ndef getData(dbs, keyword, query={}, host='localhost', port=27017):\n db = content_mongo(host, port, dbs)\n data = db.data.find({'keyword': {'$in': keyword}}, {'_id': 0})\n datalist = []\n for item in data:\n if item not in datalist:\n datalist.append(item)\n return json.dumps(datalist, ensure_ascii=False)\ndef string_toDatetime(string):\n return datetime.strptime(string, \"%Y-%m-%d\")\n# 路由\n\n\n@app.route('/getcount', methods=['GET'])\ndef main():\n keyword1 = request.args.get('key1')\n keyword2 = request.args.get('key2')\n startDate = request.args.get('startDate')\n endDate = request.args.get('endDate')\n keys = [keyword1, keyword2]\n data = getData('weibo', keys)\n if startDate!=\"NaN-NaN-NaN\":\n start=int(round(time.mktime(string_toDatetime(startDate).timetuple())*1000))\n end=int(round(time.mktime(string_toDatetime(endDate).timetuple())*1000))\n data2 = getTime('weibo',keys,start,end)\n temp=json.loads(data2)\n tempData=json.loads(data)\n for item in tempData:\n for item2 in temp:\n if item['keyword']==item2['keyword']:\n obj={}\n obj['time']=item2['time']\n obj['data']=item2['data']\n item['timeCount']=obj\n data=json.dumps(tempData, ensure_ascii=False)\n return data\n\n\nif __name__ == '__main__':\n app.debug = True\n app.run()\n","sub_path":"api/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"243137460","text":"\"\"\"\n API count exceeded - Increase Quota with Membership\n If you encounter an error (API count exceeded - Increase Quota with Membership) you need a VPN\n\n creat by Amir Hossein Tadas & TAHA\n\n instagram = Taha_t_80\n\"\"\"\nimport sys\nimport requests\nfrom colorama import Fore\nimport os\ndef __start__():\n try:\n print(Fore.LIGHTBLACK_EX+\"\\n [!] Simple Port Scanner ! ! !\")\n print(Fore.MAGENTA+\"\\n [!] Plase Enter IP/Domain\\n\")\n print(Fore.MAGENTA+\"\\n [!] for exampel : 158.58.188.67\\n\")\n inp = input(Fore.RED+\" ┌─[\"+Fore.LIGHTGREEN_EX+\"tahat80\"+Fore.BLUE+\"/\"+Fore.WHITE+\"Port-Scan\"+Fore.RED+\"\"\"]\n └──╼ \"\"\"+Fore.WHITE+\">> \")\n result = requests.get('https://api.hackertarget.com/nmap/?q=' + inp).text\n print(Fore.YELLOW+result)\n try:\n\n input(Fore.RED+\" [!] \"+Fore.GREEN+\"Back To again (Press Enter...) \")\n except:\n print(\"\")\n sys.exit() \n \n except:\n print(\"\\nExit :)\")\n\n\nif __name__ == '__main__':\n while True:\n try:\n os.system('cls')\n except:\n os.system('clear')\n\n __start__()\n","sub_path":"portscan.py","file_name":"portscan.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"46587640","text":"from behave import *\nfrom pages.create_organization import *\nfrom pages.login_page import *\nfrom pages.search_organization import *\nimport calendar\n\n@when(\"I open create organization modal\")\ndef step_impl(context):\n page = LoginPage(context)\n page.login()\n del page\n page1 = CreateOrganizationPage(context)\n page1.click_create_organization()\n del page1\n\n@then(\"Verify correct modal should be open\")\ndef first_modal_verify(context):\n page2 = CreateOrganizationPage(context)\n page2.verify_create_organization_first_modal()\n del page2\n\n\n@when(\"I enter correct data in all fields on first section and continue the process\")\ndef create_organization(context):\n page3 = CreateOrganizationPage(context)\n page3.create_organization(\"Org1\",\"Nainsi\",\"12345\",\"1234\",\"1234567890\",\"1234567890\",\"http://org.com\",\"7 rue de la \",\"rotisseriel\",\"Paris\",\"12345\", \"5 rue de la\",\"rotisseriel\",\"Paris\",\"12345\")\n time.sleep(3)\n del page3\n\n@then(\"Verify I redirected on second section\")\ndef first_modal_verify(context):\n page4 = CreateOrganizationPage(context)\n page4.verify_create_organization_second_modal()\n del page4\n\n@when(\"I enter Organization display name and continue process\")\ndef create_org_second_modal(context):\n global org1\n showtime = calendar.timegm(time.gmtime())\n org1 = str(showtime) + \"Capgemini\"\n page5 = CreateOrganizationPage(context)\n page5.enter_org_disp_name(org1)\n page5.image_upload()\n del page5\n\n@then(\"Verify I redirected on third section\")\ndef third_modal_verify(context):\n page6 = CreateOrganizationPage(context)\n page6.verify_create_organization_third_modal()\n del page6\n\n@when(\"I enter correct data in all fields on third section and finish the process\")\ndef create_org_third_modal(context):\n page7 = CreateOrganizationPage(context)\n page7.create_organization_third_section(\"n\",\"n\",\"n\",\"n\",\"n\",\"nainsi jain\"+str(calendar.timegm(time.gmtime())))\n del page7\n\n\n@then(\"Verify Organization should be created successfully\")\ndef verify_created_organization(context):\n page = SearchOrganization(context)\n page.search_with_pending_filter(org1)\n page8 = CreateOrganizationPage(context)\n page8.verify_organization_created(org1)\n del page8\n\n","sub_path":"steps/create_organization.py","file_name":"create_organization.py","file_ext":"py","file_size_in_byte":2266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"321224870","text":"import logging\n\nfrom flask import render_template, request, Flask\nfrom google.cloud import storage\n\n\napp = Flask(__name__)\nlogging.getLogger().setLevel(logging.DEBUG)\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef home():\n if request.method == 'GET':\n return render_template('index.html')\n else:\n uploaded_file = request.files['file']\n client = storage.Client()\n bucket = client.get_bucket('gae-2nd-study')\n blob = bucket.blob(uploaded_file.filename)\n blob.upload_from_file(uploaded_file)\n return 'アップロードしました。'\n\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=8080, debug=True)\n","sub_path":"example/10_gcs/example_gcs_01/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"590718776","text":"from pprint import pprint\n\n\ndef prepare_dict(file_name: str) -> dict:\n result: dict = dict()\n\n with open(file_name, 'r', encoding='utf-8') as file:\n for line in file:\n name_of_the_dish = line.strip()\n number_of_ingredients = int(file.readline())\n ingredients_list = []\n for ingredient in range(number_of_ingredients):\n ingredient_name, quantity, unit_of_measurement = file.readline().split('|')\n ingredients_list.append(\n {'ingredient_name': ingredient_name, 'quantity': quantity, 'measure': unit_of_measurement}\n )\n result[name_of_the_dish] = ingredients_list\n file.readline()\n return result\n\n\ncook_book = prepare_dict(\"resources/cook/recipes.txt\")\n\n\ndef get_shop_list_by_dishes(dishes, person_count):\n new_shop_dict = {}\n for dish in dishes:\n ingredients = cook_book.get(dish)\n for composition in ingredients:\n ingredient_name, quantity, measure = composition.values()\n quantity_with_person = int(quantity) * person_count\n if ingredient_name in new_shop_dict:\n quantity_with_person += new_shop_dict.get(ingredient_name).get('quantity')\n new_shop_dict[ingredient_name] = {\n 'measure': measure, 'quantity': quantity_with_person\n }\n return new_shop_dict\n\n\nshop_list_by_dishes = get_shop_list_by_dishes(['Омлет', 'Фахитос'], 2)\npprint(shop_list_by_dishes)\n","sub_path":"lesson_7-1_7-2.py","file_name":"lesson_7-1_7-2.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"647576993","text":"import logging\nimport inspect\nimport asyncio\n\nfrom lona.view import LonaView\n\nlogger = logging.getLogger('lona.view_loader')\n\n\nclass ViewLoader:\n def __init__(self, server):\n self.server = server\n\n self.setup()\n\n def _gen_cache_key(self, view):\n try:\n hash(view)\n\n return view\n\n except TypeError:\n return id(view)\n\n def _run_checks(self, route, view):\n # check if view is instance of lona.views.LonaView\n if(not route.http_pass_through and\n (not inspect.isclass(view) or not issubclass(view, LonaView))):\n\n logger.error('%s is no lona view', route.view)\n\n return\n\n # check if lona specific hooks are coroutine functions\n hook_names = [\n 'handle_user_enter',\n 'handle_request',\n 'handle_input_event_root',\n 'handle_input_event',\n ]\n\n for hook_name in hook_names:\n hook = getattr(view, hook_name, None)\n\n if(not route.http_pass_through and\n asyncio.iscoroutinefunction(hook)):\n\n logger.error(\n '%s.%s is a coroutine function',\n route.view,\n hook_name,\n )\n\n def _generate_acquiring_error_view(self, exception):\n class AcquiringErrorView(LonaView):\n def handle_request(self, request):\n raise exception\n\n return AcquiringErrorView\n\n def _acquire(self, view):\n logger.debug('loading %s', view)\n\n if isinstance(view, str):\n try:\n view = self.server.acquire(view)\n\n except Exception as exception:\n logger.exception(\"exception raised while importing '%s'\", view)\n\n view = self._generate_acquiring_error_view(exception)\n\n return view\n\n def setup(self):\n # views\n logger.debug('loading views from routes')\n\n self._cache = {}\n\n for route in self.server.router.routes:\n view = self._acquire(route.view)\n\n self._run_checks(route, view)\n\n cache_key = self._gen_cache_key(route.view)\n self._cache[cache_key] = view\n\n if route.frontend_view:\n view = self._acquire(route.frontend_view)\n cache_key = self._gen_cache_key(route.frontend_view)\n self._cache[cache_key] = view\n\n # special views\n import_strings = [\n # frontend\n self.server.settings.CORE_FRONTEND_VIEW,\n self.server.settings.FRONTEND_VIEW,\n\n # error 403\n self.server.settings.CORE_ERROR_403_VIEW,\n self.server.settings.ERROR_403_VIEW,\n\n # error 404\n self.server.settings.CORE_ERROR_404_VIEW,\n self.server.settings.ERROR_404_VIEW,\n\n # error 500\n self.server.settings.CORE_ERROR_500_VIEW,\n self.server.settings.ERROR_500_VIEW,\n ]\n\n for import_string in import_strings:\n if not import_string:\n continue\n\n # FIXME: run self._run_checks\n\n view = self._acquire(import_string)\n cache_key = self._gen_cache_key(import_string)\n self._cache[cache_key] = view\n\n def load(self, view):\n cache_key = self._gen_cache_key(view)\n\n return self._cache[cache_key]\n","sub_path":"lona/view_loader.py","file_name":"view_loader.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"616884456","text":"# English\ntext_en = {\n 'ready': \"Ready for the photo?\",\n 'processing': \"Processing the photo...\",\n}\n\n# German - Deutsche\ntext_de = {\n 'ready': \"Bereit fur das Foto?\",\n 'processing': \"Fotobearbeitung...\",\n}\n\n# French - Français\ntext_fr = {\n 'ready': \"Pret(s) pour la photo?\",\n 'processing': \"Traitement de la photo...\",\n}\n\n# Spanish - Español\ntext_es = {\n 'ready': \"Listo para la foto?\",\n 'processing': \"Procesamiento de fotos...\",\n}\n\nlanguage_dicts = {\n 'en': text_en,\n 'de': text_de,\n 'fr': text_fr,\n 'es': text_es,\n}\n\ndef get_text(language='en'):\n \"\"\"\n Retrieve a dictionary of text in the specified language, if available\n \"\"\"\n return language_dicts[language]\n\n# test for non-ascii characters not supported by the camera firmware\nfor language in language_dicts.values():\n for key, text in language.items():\n assert all(ord(c) in range(128) for c in text), text\n","sub_path":"text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"390810166","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport yaml\nimport subprocess\nimport argparse\nimport re\n\n__author__ = \"Jorge Niedbalski \"\n\n\ndef run(cmd):\n return subprocess.check_output(cmd.split(\" \"), stderr=subprocess.PIPE)\n\n\ndef load_yaml(cmd):\n return yaml.load(run(cmd))\n\n\nclass Service:\n\n def __init__(self, name, environment,\n skip_relations=[\"cluster\", ]):\n self.name = name\n self.skip_relations = skip_relations\n self.status = environment.get(\"services\")[self.name]\n\n def to_dict(self):\n r = {\n 'num_units': self.units,\n 'charm': self.charm,\n }\n\n if self.constraints:\n r.update({\n 'constraints': self.constraints,\n })\n\n if len(self.options):\n r.update({\n 'options': self.options,\n })\n\n return r\n\n @property\n def constraints(self):\n try:\n return run(\"juju get-constraints %s\" % self.name).strip(\"\\n\")\n except:\n return None\n\n @property\n def options(self):\n config = load_yaml(\"juju get %s\" % self.name)\n options = {}\n for k, v in config.get('settings').items():\n if 'value' in v:\n options[k] = v['value']\n return options\n\n @property\n def relations(self):\n if 'relations' in self.status:\n for name, items in self.status.get('relations').items():\n if name not in self.skip_relations:\n for item in items:\n if self.name != item:\n yield sorted([self.name, item])\n\n @property\n def units(self):\n if 'units' in self.status:\n return len(self.status.get(\"units\"))\n return 1\n\n @property\n def charm(self):\n def r(m):\n return m.groups()[0]\n\n return re.sub(\"(.*)(\\-[0-9]+)\", r,\n self.status.get('charm'))\n\n @property\n def placement(self):\n pass\n\n\nclass Environment:\n\n def __init__(self, options):\n self.options = options\n self.environment = load_yaml(\"juju status -e %s --format=yaml\" %\n self.options.environment)\n\n @property\n def services(self):\n services = []\n for service in self.environment.get('services').keys():\n services.append(Service(service, self.environment))\n return services\n\n def deployerize(self):\n output = {\n self.options.environment: {\n 'services': {},\n 'relations': [],\n }\n }\n relations = []\n\n for service in self.services:\n\n for relation in service.relations:\n if relation not in relations:\n relations.append(relation)\n\n output[self.options.environment]['services'][\n service.name] = service.to_dict()\n\n output[self.options.environment]['relations'] = relations\n\n with open(self.options.output, 'w+') as f:\n yaml.dump(output, f, default_flow_style=False)\n\n\ndef parse_options():\n parser = argparse.ArgumentParser(\n description='Convert your current juju environment status\\\n into a YAML suitable for being used on juju-deployer')\n\n parser.add_argument(\"--environment\",\n required=True,\n help='Juju environment to convert',\n type=str,\n metavar='environment')\n\n parser.add_argument(\"--output\",\n default=\"deployer.yaml\",\n help='File to store the deployer yaml',\n type=str,\n metavar='output')\n\n args = parser.parse_args()\n return args\n\n\ndef main():\n options = parse_options()\n d = Environment(options)\n d.deployerize()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"juju_deployerizer/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"292595781","text":"# Return the number of even ints in the given array. Note: the % \"mod\" operator \n# computes the remainder, e.g. 5 % 2 is 1.\n\n# count_evens([2, 1, 2, 3, 4]) → 3\n# count_evens([2, 2, 0]) → 3\n# count_evens([1, 3, 5]) → 0\n\ndef count_evens(nums):\n\tcount = 0\n\tfor num in nums:\n\t\tif num % 2 == 0:\n\t\t\tcount += 1\n\treturn count\n\n\n\n\n# Given an array length 1 or more of ints, return the difference between the \n# largest and smallest values in the array. Note: the built-in min(v1, v2) and \n# max(v1, v2) functions return the smaller or larger of two values.\n\n# big_diff([10, 3, 5, 6]) → 7\n# big_diff([7, 2, 10, 9]) → 8\n# big_diff([2, 10, 7, 2]) → 8\n\ndef big_diff(nums):\n\tlargest = nums[0]\n\tsmallest = nums[0]\n\tfor i in range(len(nums)):\n\t\tif largest < nums[i]:\n\t\t\tlargest = nums[i]\n\t\tif smallest > nums[i]:\n\t\t\tsmallest = nums[i]\n\treturn largest - smallest\n\n# candidate for r/shittyprogramming\ndef big_diff(nums):\n\tlargest = 0\n\tsmallest = 1000000000000000\n\tfor i in range(len(nums)):\n\t\tif largest < max(largest, nums[i]):\n\t\t\tlargest = max(largest, nums[i])\n\t\tif smallest > min(smallest, nums[i]):\n\t\t\tsmallest = min(smallest, nums[i])\n\treturn largest - smallest\n\n\n\n\n\n# Return the \"centered\" average of an array of ints, which we'll say is the mean \n# average of the values, except ignoring the largest and smallest values in the \n# array. If there are multiple copies of the smallest value, ignore just one copy, \n# and likewise for the largest value. Use int division to produce the final average. \n# You may assume that the array is length 3 or more.\n\n# centered_average([1, 2, 3, 4, 100]) → 3\n# centered_average([1, 1, 5, 5, 10, 8, 7]) → 5\n# centered_average([-10, -4, -2, -4, -2, 0]) → -3\n\ndef centered_average(nums):\n\ttotal = 0\n\tcenter = nums\n\n\t# remove largest and smallest numbers\n\tcenter.remove(max(nums))\n\tcenter.remove(min(nums))\n\t# sum the list\n\tfor i in center:\n\t\ttotal += i\n\n\t# return arithmetic mean\n\treturn total/len(center)\n\n\n\n\n# Return the sum of the numbers in the array, returning 0 for an empty array. \n# Except the number 13 is very unlucky, so it does not count and numbers that \n# come immediately after a 13 also do not count.\n\n# sum13([1, 2, 2, 1]) → 6\n# sum13([1, 1]) → 2\n# sum13([1, 2, 2, 1, 13]) → 6\n\ndef sum13(nums):\n\ttotal = 0\n\n\t# need the length of nums to be greater than 0\n\tif len(nums) == 0:\n\t\treturn 0\n\n\tfor i in range(length):\n\t\tif nums[i] != 13:\n\t\t\t# need to check if we are at the first index also\n\t\t\t# if we didn't check it, nums[i-1] would return the last\n\t\t\t# element in the list on the first (zeroeth) pass\n\t\t\tif i == 0 or nums[i-1] != 13:\n\t\t\t\ttotal += nums[i]\n\treturn total\n\n\n\n\n\n# Return the sum of the numbers in the array, except ignore sections of numbers \n# starting with a 6 and extending to the next 7 (every 6 will be followed by at \n# least one 7). Return 0 for no numbers.\n\n# sum67([1, 2, 2]) → 5\n# sum67([1, 2, 2, 6, 99, 99, 7]) → 5\n# sum67([1, 1, 6, 7, 2]) → 4\n\n\n# have to think of this problem like on/off\n\ndef sum67(nums):\n\tstate = 0\n\ttotal = 0\n\tfor num in nums:\n\t\t# if we are currently not between a 6 or 7\n\t\tif state == 0:\n\t\t\t# if the current number is 6, turn on the 'state'\n\t\t\tif num == 6:\n\t\t\t\tstate = 1\n\t\t\t# else, we must not be between 6 and 7 so increment the num to total\n\t\t\telse:\n\t\t\t\ttotal += num\n\t\t# if we are in between a 6 or 7, and the number is 7, turn the state off\n\t\telse:\n\t\t\tif num == 7:\n\t\t\t\tstate = 0\n\treturn total\n\n\n\n\n# Given an array of ints, return True if the array contains a 2 next to a 2 somewhere.\n\n# has22([1, 2, 2]) → True\n# has22([1, 2, 1, 2]) → False\n# has22([2, 1, 2]) → False\n\ndef has22(nums):\n\tfor i in range(len(nums)-1):\n\t\tif nums[i] == 2 and nums[i+1] == 2:\n\t\t\treturn True\n\treturn False","sub_path":"List_2.py","file_name":"List_2.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"636946065","text":"\"\"\"A library for the service of WebSockets (http://dev.w3.org/html5/websockets/) based connections\"\"\"\n\nimport socket\nimport threading\nimport sys\nimport time\nimport re\nimport traceback\nimport struct\nimport hashlib\nimport Queue\n\nfrom gevent import WebSocketFrame\n\nCRLF = '\\x0D\\x0A'\nDOUBLE_CRLF = CRLF+CRLF\nSTART_BYTE = '\\x00'\nEND_BYTE = '\\xff'\n\ndef parse_request_header(header):\n\t\"\"\"Breaks up the header lines of the WebSocket request into a dictionary\"\"\"\n\tlines = [token.strip() for token in header.split('\\r')[1:]]\n\tresult = {}\n\tfor line in lines:\n\t\tif len(line) == 0: break\n\t\tkey, value = line.split(' ', 1)\n\t\tresult[key[:len(key) - 1]] = value\n\treturn result\n\ndef receive_web_socket_message(socket):\n\t\tdata = socket.recv(2)\n\t\tframe = WebSocketFrame()\n\t\ttry:\n\t\t\tto_read = frame.handle_header(data[:2], enforce_mask=False)\n\t\texcept:\n\t\t\treraise()\n\t\tif to_read > 0:\n\t\t\tdata = socket.recv(to_read)\n\t\t\tframe.handle_length(data)\n\t\tpayload = socket.recv(frame.length)\n\t\twhile len(payload) < frame.length:\n\t\t\tbuf = socket.recv(frame.length - len(payload))\n\t\t\tif not buf: raise Exception('Could not read the websocket payload')\n\t\t\tpayload += buf\n\t\t\n\t\tif len(payload) == 0: return None\n\t\treturn payload\n\nMAX_HEADER_LENGTH = 8192\n\nclass WebSocketClient:\n\tdef __init__(self, host, port, origin, protocol='sample', version='0.1'):\n\t\tself.host = host\n\t\tself.port = port\n\t\tself.origin = origin\n\t\tself.protocol = protocol\n\t\tself.version = version\n\t\tself.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\t\tself.socket.connect((self.host, self.port))\n\t\tself.socket.send(self.generate_request_headers())\n\t\tself.response_headers = self.receive_request_header()\n\t\tself.closed = False\n\n\tdef receive_request_header(self):\n\t\tdata = ''\n\t\twhile len(data) <= MAX_HEADER_LENGTH and not data.endswith('\\r\\n\\r\\n'): data += self.socket.recv(1)\n\t\treturn parse_request_header(data)\n\t\t\n\tdef receive(self):\n\t\ttry:\n\t\t\treturn receive_web_socket_message(self.socket)\n\t\texcept:\n\t\t\tif not self.closed: raise\n\t\t\t\n\tdef send(self, message, opcode=WebSocketFrame.OPCODE_TEXT):\n\t\theader, message = WebSocketFrame.encode(message, opcode, '1234')\n\t\tself.socket.send(header)\n\t\tif message: self.socket.send(message)\n\n\tdef close(self):\n\t\tif self.closed: return\n\t\tself.closed = True\n\t\ttry:\n\t\t\tself.socket.shutdown(socket.SHUT_RDWR)\n\t\t\tself.socket.close()\n\t\texcept:\n\t\t\tpass # don't care\n\n\tdef generate_request_headers(self):\n\t\theaders = [\n\t\t\t\"GET / HTTP/1.1\",\n\t\t\t\"Host: %s:%s\" % (self.host, self.port),\n\t\t\t\"Upgrade: WebSocket\",\n\t\t\t\"Connection: Upgrade\",\n\t\t\t\"Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\",\n\t\t\t\"Origin: %s\" % self.origin,\n\t\t\t\"Sec-WebSocket-Protocol: %s\" % self.protocol,\n\t\t\t\"Sec-WebSocket-Version: %s\" % self.version,\n\t\t]\n\t\treturn '%s%s' % (CRLF.join(headers), DOUBLE_CRLF)\n","sub_path":"wind/websocket/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"526850078","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 ('core', '0010_auto_20160728_2347'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='numeracjafaktur',\n name='biezacy_numer',\n field=models.IntegerField(default=1),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='faktura',\n name='stawka_vat',\n field=models.CharField(max_length=2, choices=[('ZW', 'zw'), ('05', '5'), ('08', '8'), ('23', '23')]),\n ),\n ]\n","sub_path":"Phoenicia21/src/core/migrations/0011_auto_20160730_2114.py","file_name":"0011_auto_20160730_2114.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"216501871","text":"import numpy as np\nimport cv2 as cv\n\n\ndef dilate_map_xy(map_3d, l):\n map_3d_copy = map_3d.copy()\n kernel = np.ones((l+l+1, l+l+1))\n for i in range(map_3d_copy.shape[2]):\n im = map_3d_copy[:,:,i]\n im_fat = cv.dilate((im>0).astype(float), kernel=kernel)\n map_3d_copy[:,:,i] = im_fat\n return map_3d_copy\n\n\ndef embed_2d_path_in_2d_map(map_3d, robot_path, l):\n map_3d_0_path = map_3d.copy()\n for i in range(len(robot_path)-1):\n loc = robot_path[i]\n map_3d_0_path[loc[0]-l:loc[0]+l, loc[1]-l:loc[1]+l] = 4\n return map_3d_0_path\n\n\ndef embed_2d_path_in_3d_map(map_3d, robot_path, l, enum=4):\n map_3d_0_path = map_3d.copy()\n for i in range(len(robot_path)-1):\n loc = robot_path[i]\n map_3d_0_path[loc[0]-l+1:loc[0]+l+1, loc[1]-l+1:loc[1]+l+1, i] = enum\n for j in range(i, map_3d.shape[2]):\n loc = robot_path[i]\n map_3d_0_path[loc[0]-l+1:loc[0]+l+1, loc[1]-l+1:loc[1]+l+1, j] = enum\n return map_3d_0_path\n\n\ndef embed_path_in_3d_map(map_3d, robot_0_path, l=1, enum=4):\n map_3d_0_path = map_3d.copy()\n for i in range(len(robot_0_path)):\n loc = robot_0_path[i]\n map_3d_0_path[loc[0]-l:loc[0]+l+1, loc[1]-l:loc[1]+l+1, loc[2]] = enum\n return map_3d_0_path\n\n","sub_path":"Greedy/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"256263611","text":"# [백준 5086] 배수와 약수\n\nimport sys\n\n\ndef check(a, b):\n if a < b:\n if b % a == 0:\n return \"factor\"\n else:\n if a % b == 0:\n return \"multiple\"\n else:\n return \"neither\"\n\n\nwhile True:\n a, b = map(int, sys.stdin.readline().rstrip(\"\\n\").split())\n if a == 0 and b == 0:\n break\n print(check(a, b))\n","sub_path":"baekjoon_5086/baekjoon_5086.py","file_name":"baekjoon_5086.py","file_ext":"py","file_size_in_byte":375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"568043816","text":"import os\nimport matplotlib.pyplot as plt\nfrom re import split\n\n\ndef read_fasta_file(filename):\n \"\"\" Reads in file in fasta format and returns sequences of tuples containing\n header name and the corresponding sequence\"\"\"\n with open(filename, 'r') as file:\n return tuple((name, seq.replace('\\n', ''))\n for name, ignore, seq in [entry.partition('\\n')\n for entry in file.read().split('>')[1:]])\n\n\ndef blastp_parser(filename):\n \"\"\" Reads in blastp output file (-outfmt 6 & 7 ) and returns content of table as sequences of\n keys and values, where keys holds the attributes in the table\"\"\"\n with open(filename, 'r') as file:\n table = file.read().split('#')\n attribs = table[4].replace(' Fields: ', '').rstrip('\\n').split(', ')\n return tuple({attribs[n]: value for n, value in enumerate(hit.split('\\t'))}\n for hit in table[5].split('\\n')[1:-1])\n\n\ndef hmmscan_parser(filename):\n \"\"\" Reads in hmmscan output file (tblout format) and returns tables attributes as\n sequence of keys and values. Note that only the best domain for each query is kept.\"\"\"\n with open(filename, 'r') as file:\n domains = tuple()\n for line in file.read().split('\\n'):\n if line.startswith('#') or line == '':\n continue\n line = split('\\s+', line, 22)\n domain = dict()\n domain.setdefault('target name', line[0])\n domain.setdefault('accession', line[1])\n domain.setdefault('query name', line[2])\n domain.setdefault('domain evalue', line[7])\n domain.setdefault('description', ' '.join([line[n] for n in range(18, len(line))]))\n domains += (domain,)\n domains = collapse_duplicates(domains, 'query name')\n return domains\n\n\ndef alignment_file_parser(filename):\n \"\"\" Reads alignment file (in fasta format) and returns sequence of header name\n and the corresponding sequence. Here is alignment file format:\n >accession number|species name\n sequence\n \"\"\"\n aln_hits = tuple()\n for entry in read_fasta_file(filename):\n hit = dict()\n hit['subject acc.'] = entry[0].split('|')[0]\n hit['species name'] = entry[0].split('|')[1]\n hit['subject seq'] = entry[1]\n aln_hits += (hit,)\n return aln_hits\n\n\ndef get_species_taxon(hits):\n \"\"\" Takes in hits and returns hits which belong to bacterial species taxon.\"\"\"\n with open(dbdir + '2.species.taxids', 'r') as file:\n taxids = {line.rstrip('\\n') for line in file.readlines()}\n return tuple(hit for hit in hits if hit.get('subject tax ids') in taxids)\n\n\ndef extract_seqs(hits, start, end=None):\n \"\"\" Takes in hits and the desired range (start, end) and update sequence field\n for all hits\"\"\"\n for n in range(0, len(hits)):\n hits[n]['subject seq'] = hits[n]['subject seq'][start:end]\n\n\ndef collapse_duplicates(hits, key):\n \"\"\" Collapses hits with 100% similar sequences into one hit based on hits order\"\"\"\n duplicates = set()\n return tuple(hit for hit in hits\n if not (hit.get(key) in duplicates or duplicates.add(hit.get(key))))\n\n\ndef get_redundancy_level(seq1, seq2):\n \"\"\" Calculates similarity levels of two sequences\"\"\"\n return list(map(lambda x: x[0] == x[1], list(zip(seq1, seq2)))).count(True) / len(seq1)\n\n\ndef collapse_redundant_hits(hits, threshold=0.9):\n \"\"\" Collapses hits with similarity level set by threshold argument. Default\n threshold is 90%\"\"\"\n grouped_hits = []\n while len(hits) > 1:\n prev_hit = hits[0]\n subgroup = [prev_hit]\n ungroup = []\n for hit in hits[1:]:\n if get_redundancy_level(prev_hit.get('subject seq'), hit.get('subject seq')) > threshold:\n subgroup.append(hit)\n else:\n ungroup.append(hit)\n grouped_hits.append(subgroup)\n hits = ungroup\n return tuple(subgroup[0] for subgroup in grouped_hits)\n\n\ndef collect_loci(hits, upper_locus_range, lower_locus_range):\n \"\"\" Takes in hits and updates upper locus and lower locus sequence field using loci ranges\n provided as arguments \"\"\"\n for n in range(0, len(hits)):\n hits[n]['upper locus'] = hits[n]['subject seq'][upper_locus_range[0]:upper_locus_range[1]]\n hits[n]['lower locus'] = hits[n]['subject seq'][lower_locus_range[0]:lower_locus_range[1]]\n hits[n]['analyzed'] = False\n\n\ndef locus_type(hits, upper_locus_type, lower_locus_type):\n \"\"\" Takes in hits and returns hits whose upper and lowe loci match the provided loci types\n as arguements\"\"\"\n aa_set = {'charged': 'RHKDE', 'polar': 'STYNQ', 'nonpolar': 'GAVCPLIMWF', 'not_aligned': '-'}\n selected = tuple()\n for n in range(0, len(hits)):\n if (len(set(hits[n]['upper locus']) & set(aa_set[upper_locus_type])) > 0 and\n len(set(hits[n]['lower locus']) & set(aa_set[lower_locus_type])) > 0 and not hits[n]['analyzed']):\n selected += (hits[n],)\n hits[n]['analyzed'] = True\n return selected\n\n\ndef pie_plot(data, save_path, show_fig=False):\n \"\"\" generates pie plot\"\"\"\n\n def set_wedge_numbers(perc):\n return '{:.1f}%'.format(perc)\n\n plt.pie(data, explode=(0.02, 0.02, 0.02), labels=['charged-charged', 'charged-polar', 'other'],\n colors=['green', 'orange', 'gray'], autopct=lambda perc: set_wedge_numbers(perc), center=(0, 0),\n textprops=dict(color='black', fontsize=10))\n plt.savefig(save_path, dpi=None, facecolor='w', edgecolor='w', orientation='portrait', papertype=None,\n format='eps', transparent=False, bbox_inches=None, pad_inches=0.1, metadata=None)\n if show_fig:\n plt.show()\n\n\ndef process_domains():\n \"\"\" Runs hmmscan to obtain the best domain for each hit\"\"\"\n # run hmmcan to identify the best domain matches for each hit\n print('Running hmmscan to search each hit against Pfam 32.0 hmm profile database to determine the best domain '\n 'matched\\n(May take a few minutes ...)')\n os.system('hmmscan --cut_ga --cpu 4 --tblout {} {} {} > {}'\n .format(resultdir + 'domains.tab', pfamdb, resultdir + '_processed_hits.fa', logsdir + 'hmmscan.log'))\n\n domains = hmmscan_parser(resultdir + 'domains.tab')\n print('Total {} of unique domains were parsed for each hit.'.format(len(domains)))\n\n print('Processing domains ...')\n domain_types = {domain['target name'] for domain in domains}\n for domain_type in domain_types:\n evalues = tuple(float(domain['domain evalue']) for domain in domains if domain['target name'] == domain_type)\n print('{:.2f}% of the hits have \\'{}\\' domain with {} < E-values < {}.'\n .format(len(evalues) / len(domains) * 100, domain_type, min(evalues), max(evalues)))\n\n cutoff_evalue = 1e-10\n domains = tuple(domain['query name'] for domain in domains if float(domain['domain evalue']) < cutoff_evalue)\n print('Total {} of hits were remained after removing hits with E-value > {}'.format(len(domains), cutoff_evalue))\n return domains\n\n\ndef process_hits():\n \"\"\" Processes blastp output \"\"\"\n # parse hit table obtained form blastp search\n print('Parsing hits obtained from blastp search ...')\n hits = blastp_parser(datadir + '2.species.hits.tab')\n print('Total {} of hits were parsed from blastp search output.'.format(len(hits)))\n\n print('Processing the hits ...')\n # restrict the hits to species taxonomy level\n hits = get_species_taxon(hits)\n print('Total {} of hits remained after restricting hits to only species taxonomy level.'.format(len(hits)))\n\n # remove gaps from sequences\n for n in range(0, len(hits)):\n hits[n]['subject seq'] = hits[n]['subject seq'].replace('-', '')\n\n # remove hits, which did not align to membrane-proximal module of McpA (163-239)\n hits = tuple(hit for hit in hits\n if (int(hit['q. end']) > 239 and int(hit['q. start']) < 163))\n print('Total {} of hits remained after removing the hits that did not align to membrane-proximal module.'\n .format(len(hits)))\n\n # collect the hits that have 80% coverage of the query sequence (247 aa).\n hits = tuple(hit for hit in hits if len(hit['subject seq']) > 0.8*247)\n print('Total {} of hits remained after removing the hits that had less than 80% coverage [excluding gaps].'\n .format(len(hits)))\n\n # remove duplicate sequences\n hits = collapse_duplicates(hits, 'subject seq')\n print('Total {} of hits remained after removing duplicate sequences.'.format(len(hits)))\n\n # write processed hits in a fasta file used for domain identification\n with open(resultdir + '_processed_hits.fa', 'w') as file:\n file.writelines('>' + hit['subject acc.'] + '\\n' + hit['subject seq'] + '\\n' for hit in hits)\n print(100*'-')\n\n # identify domains for each hit\n domains = process_domains()\n\n # Collect hits that satisfied allowed threshold for domain\n hits = tuple(hit for hit in hits if hit['subject acc.'] in domains)\n\n # extract aa sequence of pH sensing region (membrane-proximal module) of collected hits\n extract_seqs(hits, start=-90)\n print('Sequences of TM2-proximal region ({} aa) were extracted.'.format(90))\n\n # remove hits that have same aa sequence to reduce bias\n hits = collapse_duplicates(hits, 'subject seq')\n print('Total {} of hits remained after removing duplicate sequences.'.format(len(hits)))\n\n # write processed hits in a fasta file\n with open(resultdir + '_seqs-for-align.fa', 'w') as file:\n file.writelines('>' + '|'.join([hit['subject acc.'],\n hit['subject title'].rstrip(']').partition('[')[2].strip('[').replace(' ', '_')])\n + '\\n' + hit['subject seq'] + '\\n' for hit in hits)\n print(100*'-')\n\n\ndef align_hits():\n \"\"\" Runs multiple-sequence alignments on processed hits\"\"\"\n print('Running clustal omega for fast initial MSA ...')\n os.system('clustalo -i {} -o {} --force > /dev/null'\n .format(resultdir + '_seqs-for-align.fa', resultdir + '_aligned_seqs.fa'))\n\n print('Running trimal to remove badly aligned sequences ...')\n os.system('trimal -in {} -out {} -resoverlap 0.80 -seqoverlap 90 > /dev/null'\n .format(resultdir + '_aligned_seqs.fa', resultdir + '_aligned_seqs_trimmed.fa'))\n\n aln_seqs = alignment_file_parser(resultdir + '_aligned_seqs_trimmed.fa')\n print('Total {} of hits remained after removing badly aligned hits.'.format(len(aln_seqs)))\n\n print('Trimming alignments and collapsing highly similar hits with 95% cutoff ...')\n left_cut_index = max([aln_seq['subject seq'].find('TKKVN') for aln_seq in aln_seqs])\n right_cut_index = max([aln_seq['subject seq'].find('AAQP') + 4 for aln_seq in aln_seqs])\n extract_seqs(aln_seqs, left_cut_index, right_cut_index)\n aln_seqs = collapse_redundant_hits(aln_seqs, 0.95)\n with open(resultdir + '_aligned_seqs_trimmed.fa', 'w') as file:\n file.writelines('>' + '|'.join([hit['subject acc.'], hit['species name'].replace(' ', '_')])\n + '\\n' + hit['subject seq'].replace('-', '') + '\\n' for hit in aln_seqs)\n print('Total {} of hits remained after collapsing highly similar sequences with {}% similarity.\\n'\n .format(len(aln_seqs), 0.95))\n\n print('Running Muscle for accurate MSA ...')\n os.system('muscle -in {} -out {} -log {} > /dev/null'\n .format(resultdir + '_aligned_seqs_trimmed.fa', resultdir + 'aligned_seqs.fa', logsdir + 'muscle.logs'))\n\n\ndef process_aln_seqs():\n \"\"\" Processes alignment sequences\"\"\"\n aln_seqs = alignment_file_parser(resultdir + 'aligned_seqs.fa')\n\n # collect pH residues from each alignment and sort alignments based on species names\n upper_ph_res = max([aln_seq['subject seq'].find('TQGYAFI') for aln_seq in aln_seqs])\n lower_ph_res = max([aln_seq['subject seq'].find('HEAAQP') for aln_seq in aln_seqs])\n collect_loci(aln_seqs, (upper_ph_res, upper_ph_res + 2), (lower_ph_res, lower_ph_res + 2))\n for n in range(0, len(aln_seqs)):\n aln_seqs[n].setdefault('analyzed', False)\n cc_aln_seqs = locus_type(aln_seqs, 'charged', 'charged')\n cp_aln_seqs = locus_type(aln_seqs, 'charged', 'polar')\n pc_aln_seqs = locus_type(aln_seqs, 'polar', 'charged')\n ph_aln_seqs = cc_aln_seqs + cp_aln_seqs + pc_aln_seqs\n ph_aln_seqs = sorted(ph_aln_seqs, key=lambda x: x.get('upper locus') + x.get('lower locus'), reverse=True)\n ph_aln_seqs = sorted(ph_aln_seqs, key=lambda x: x.get('species name'), reverse=False)\n with open(resultdir + 'ph_aligned_seqs.fa', 'w') as file:\n file.writelines('>' + '|'.join([hit['subject acc.'], hit['species name']]) +\n '\\n' + hit['subject seq'] + '\\n' for hit in ph_aln_seqs)\n print('Hits that are potentially capable of pH-sensing are written to <{}>.'\n .format(resultdir + 'ph_aligned_seqs.fa'))\n\n fractions = (len(cc_aln_seqs)/len(aln_seqs), (len(cp_aln_seqs) + len(pc_aln_seqs)) / len(aln_seqs),\n 1 - len(ph_aln_seqs) / len(aln_seqs))\n pie_plot(fractions, figuredir + 'pie.eps', True)\n print('Pie plot representing chemistry of pH amino acid residues is saved to <{}>.'.format(figuredir + 'pie.sps'))\n\n # collect hits which have highly conserved pH-sensing residues wrt to Bs 168 pH chemoreceptors\n with open(resultdir + 'Bs168_conserved_hits.fa', 'w') as file:\n file.writelines('>' + '|'.join([hit['subject acc.'], hit['species name']]) + '\\n' +\n hit['subject seq'].replace('-', '') + '\\n' for hit in aln_seqs\n if (hit['upper locus'] in {'KE', 'TQ'} and hit['lower locus'] in {'HE', 'HD', 'QD', 'KD'}))\n\n # collect upper and lower pH-sensing loci\n collect_loci(ph_aln_seqs, (upper_ph_res - 4, upper_ph_res + 6), (lower_ph_res - 4, lower_ph_res + 6))\n with open(resultdir + 'upper_loci_logo.fa', 'w') as file1, open(resultdir + 'lower_loci_logo.fa', 'w') as file2:\n file1.writelines('>' + hit['subject acc.'] + '\\n' + hit['upper locus'] + '\\n' for hit in ph_aln_seqs)\n file2.writelines('>' + hit['subject acc.'] + '\\n' + hit['lower locus'] + '\\n' for hit in ph_aln_seqs)\n print('pH loci sequences are written to <{}> and <{}>.'\n .format(resultdir + 'lower_loci_logo.fa', resultdir + 'upper_loci_logo.fa'))\n\n print(100*'-')\n return {hit['subject acc.'] for hit in ph_aln_seqs}\n\n\ndef process_tax_lineage(acc_set):\n \"\"\" Processes taxonomy lineage of identified bacterial species\"\"\"\n # extract taxonomy lineage of all identified species\n hits = blastp_parser(datadir + '2.species.hits.tab')\n acc_taxids = {(hit['subject acc.'], hit['subject tax ids']) for hit in hits}\n ph_taxids = {elt[1] for elt in acc_taxids if elt[0] in acc_set}\n\n print('Running taxonkit to extract taxonomy lineages for species potentially capable of pH-taxis...')\n with open(resultdir + 'ph_aligned_seqs.taxids', 'w') as file:\n file.writelines(taxid + '\\n' for taxid in ph_taxids)\n os.system('taxonkit lineage {} -o {}'.format(resultdir + 'ph_aligned_seqs.taxids', resultdir + '_lineage.txt'))\n reformat = '{p};{c};{o};{f};{g};{s}'\n os.system('taxonkit reformat {} -f \\'{}\\' | tee {} > /dev/null'\n .format(resultdir + '_lineage.txt', reformat, resultdir + '_ph_aligned_seqs.lineage'))\n\n tax_levels = ['phylum', 'class', 'order', 'family', 'genus', 'species']\n with open(resultdir + '_ph_aligned_seqs.lineage', 'r') as file:\n tax_entries = tuple({tax_levels[n]: value for n, value in enumerate(entry.split(';'))} for entry in\n tuple(line.rstrip('\\n').split('\\t')[-1] for line in file.readlines()))\n tax_entries = sorted(tax_entries, key=lambda x: x.get('species'))\n\n with open(resultdir + 'ph_aligned_seqs.lineage.tsv', 'w') as file:\n file.write('\\t'.join(tax_levels) + '\\n')\n file.writelines('\\t'.join(list(entry.values())) + '\\n' for entry in tax_entries)\n print('Taxonomy lineages are written to <{}>'.format(resultdir + 'ph_aligned_seqs.lineage.tsv'))\n\n for level in tax_levels:\n print('Total number of unique {}: {}'.format(level, len({entry.get(level) for entry in tax_entries})))\n print(100*'-')\n\n\ndef clear_intermediate_files():\n \"\"\" Remove all intermediate files generated during analysis for better organization\"\"\"\n os.system('rm -f {}_*'.format(resultdir))\n\n\ndef main():\n \"\"\" DO NOTHING \"\"\"\n pass\n\n\n# ---------------------------\nif __name__ == '__main__':\n main()\nelse:\n datadir = '../data/'\n resultdir = '../results/'\n figuredir = '../results/figures/'\n logsdir = '../logs/'\n dbdir = '../db/'\n pfamdb = '$HOME/hmmer-3.2.1/db/Pfam-A.hmm'\n","sub_path":"scripts/funcs.py","file_name":"funcs.py","file_ext":"py","file_size_in_byte":16824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"212245685","text":"import sys\nsys.stdin = open(\"input1208.txt\")\n\n# 최저 높이의 상자 인덱스 위치 반환 함수\ndef min_search():\n # 초기화\n min_value = 987654321\n min_idx = -1\n\n # 최저 높이를 찾자!\n for i in range(len(box)):\n if box[i] < min_value:\n min_value = box[i]\n min_idx = i\n return min_idx\n\n# 최고 높이의 상자 인덱스 위치 반환 함수\ndef max_search():\n max_value = 0\n max_idx = -1\n\n for i in range(len(box)):\n if box[i] > max_value:\n max_value = box[i]\n max_idx = i\n return max_idx\n\nfor tc in range(1, 10+1):\n # N=덤프 횟수\n N = int(input())\n \n # 박스들\n box = list(map(int, input().split()))\n\n # N번 덤프하기\n for i in range(N):\n # 최고 높이의 상자 한칸 내리기\n box[max_search()] -= 1\n # 최저 높이의 상자 한칸 올리기\n box[min_search()] += 1\n\n print(\"#{} {}\".format(tc, box[max_search()]-box[min_search()]))\n\n########################################################################################################################\nimport sys\nsys.stdin = open(\"input1208.txt\")\n\ndef bubble_sort(arr):\n for i in range(len(arr)-1, 0, -1):\n for j in range(0, i):\n if arr[j] > arr[j+1]:\n arr[j], arr[j+1] = arr[j+1], arr[j]\n\n\nfor tc in range(1, 11):\n N = int(input())\n box = list(map(int, input().split()))\n\n for i in range(N):\n bubble_sort(box)\n box[0] += 1\n box[-1] -= 1\n\n bubble_sort(box)\n print(\"#{} {}\".format(tc, box[-1]-box[0]))","sub_path":"SWEA/문제/1208.py","file_name":"1208.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"7231480","text":"\"\"\" \n@author: Frank\n@file: progress_queue.py \n@time: 18-4-24 下午4:51 \n\"\"\"\nimport time\nfrom multiprocessing import Process, Queue, Pool, Manager, Pipe\n\n# from queue import Queue # queue里面的Queue不能用于多进程编程\n\n\n# def producer(queue):\n# \tqueue.put(\"a\")\n# \ttime.sleep(2)\n#\n#\n# def consumer(queue):\n# \ttime.sleep(2)\n# \tprint(queue.get())\n#\n#\n# if __name__ == \"__main__\":\n# \tqueue = Queue(10)\n# \tmy_producer = Process(target=producer, args=(queue,))\n# \tmy_consumer = Process(target=consumer, args=(queue,))\n# \tmy_producer.start()\n# \tmy_consumer.start()\n# \tmy_producer.join()\n# \tmy_consumer.join()\n\n# nultiprocessing里面的Queue不能用于进场池, 所以要使用Manager中的Queue\n\n# def producer(queue):\n# \tqueue.put(\"a\")\n# \ttime.sleep(2)\n#\n#\n# def consumer(queue):\n# \ttime.sleep(2)\n# \tprint(queue.get())\n#\n#\n# if __name__ == \"__main__\":\n# \tqueue = Manager().Queue(10)\n# \tpool = Pool(2)\n# \tpool.apply_async(producer, args=(queue,))\n# \tpool.apply_async(consumer, args=(queue,))\n# \tpool.close()\n# \tpool.join()\n#\n# 通过Pipe实现进程间的通信\n# Pipe适用于两个指定的的进程\n#\n# def producer(send_pipe):\n# \tsend_pipe.send(\"frank\")\n#\n#\n# def consumer(recevie_pipe):\n# \tprint(recevie_pipe.recv())\n#\n#\n# if __name__ == \"__main__\":\n# \trecevie_pipe, send_pipe = Pipe()\n# \tmy_producer = Process(target=producer, args=(send_pipe,))\n# \tmy_consumer = Process(target=consumer, args=(recevie_pipe,))\n# \tmy_producer.start()\n# \tmy_consumer.start()\n# \tmy_producer.join()\n# \tmy_consumer.join()\n\n# 进程间的共享内存\ndef add_data(pd, k, v):\n\tpd[k] = v\n\nif __name__ == \"__main__\":\n\tprogress_dict = Manager().dict()\n\tp1 = Process(target=add_data, args=(progress_dict, \"a\", 1))\n\tp2 = Process(target=add_data, args=(progress_dict, \"b\", 2))\n\tp3 = Process(target=add_data, args=(progress_dict, \"c\", 3))\n\tp1.start()\n\tp2.start()\n\tp3.start()\n\tp1.join()\n\tp2.join()\n\tp3.join()\n\tprint(progress_dict)","sub_path":"progress_queue.py","file_name":"progress_queue.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"441941612","text":"#!/usr/bin/env python3\nimport sqlite3\nfrom flask import Flask, g, request, session, abort\nfrom contextlib import closing\nfrom flask_jsglue import JSGlue\n\n# config (which should be in another file for larger apps)\nDATABASE = '/tmp/pegasus.db'\nDEBUG = True\nSECRET_KEY = 'you shall not pass'\n\n\n# initialize app\napp = Flask(__name__)\njsglue = JSGlue(app)\napp.config.from_object(__name__) # or the other file if we had the config in another file (ref: app.config.from_envvar('FLASKR_SETTINGS', silent=True))\n\n# import other necessary modules\nimport pegasus.views\nimport pegasus.errorhandlers\n\ndef connect_db():\n return sqlite3.connect(app.config['DATABASE'])\n\ndef init_db():\n with closing(connect_db()) as db:\n with app.open_resource('schema.sql', mode='r') as f:\n db.cursor().executescript(f.read())\n db.commit()\n\n\n\n# database requests\n@app.before_request\ndef before_request():\n g.db = connect_db()\n g.db.execute('PRAGMA foreign_keys = ON')\n\n@app.before_request\ndef csrf_protect():\n if request.method == 'POST': # GET/ajax protection can be defined in their respective functions\n token = session.pop('_csrf_token', None)\n if not token or token != request.form.get('_csrf_token'):\n abort(400) \n\n@app.teardown_request\ndef teardown_request(exception):\n db = getattr(g, 'db', None)\n if db is not None:\n db.close()\n\n\n\n","sub_path":"pegasus/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"57597514","text":"import sys\nimport math\n\n\npalette_size = 256\nambient = [0, 0, 0.25]\ndiffuse = [0, 0.25, 1.0]\nspecular = [1.0, 1.0, 1.0]\nshininess = 2\n\n\ndef clamp(color, min=0, max=1.0):\n if color > max:\n return max\n elif color < min:\n return min\n else:\n return color\n\n\ndef add_colors(a, b):\n return [\n clamp(a[0] + b[0]),\n clamp(a[1] + b[1]),\n clamp(a[2] + b[2]),\n ]\n\n\ndef multiply_color(color, value):\n return [\n clamp(color[0] * value),\n clamp(color[1] * value),\n clamp(color[2] * value),\n ]\n\n\ndef fixed_point(value):\n return int(value * 31)\n\n\ndef gba_format(color):\n return ((fixed_point(color[0]) << 10) |\n (fixed_point(color[1]) << 5) |\n fixed_point(color[2]))\n\n\n# ambient + diffuse * angle + specular * angle^shininess\nvalues = []\nfor i in range(0, palette_size):\n angle = 1.0 / palette_size * i\n diff = multiply_color(diffuse, angle)\n spec = multiply_color(specular, math.pow(angle, shininess))\n values.append(add_colors(ambient, add_colors(diff, spec)))\n\noutput = ','.join([hex(gba_format(value)) for value in values])\n\nprint(output)\n","sub_path":"utils/palette-generator.py","file_name":"palette-generator.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"638011818","text":"n = int(input())\nlst = list(map(int,input().split()))\ndp = [0]*n\ndp[0] = 1\n\ni=1\nwhile i= 0:\n first = s[i]\n second = p1.next\n p1.next = second.next\n second.next = first.next\n first.next = second\n i -= 1\n\n","sub_path":"ReorderList/ReorderList.py","file_name":"ReorderList.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"437283964","text":"from typing import List\nfrom core.base_handler import BaseHandler\nfrom core.function_context import FunctionContext\n\n\nclass RaceConditionHandler(BaseHandler):\n vulnerability_name = 'Состояние гонки'\n\n def __init__(self):\n self.output = []\n\n def parse(self, contexts: List[FunctionContext]):\n total_errors = 0\n for context in contexts:\n if len(context.threads) != 0:\n declared_threads = context.threads\n # part for detecting same runnables\n func_in_threads = []\n # creating list of all runnables\n for thread in declared_threads:\n if thread.runnable_function not in func_in_threads:\n func_in_threads.append(thread.runnable_function)\n funcs_to_threads = [[] for i in range(len(func_in_threads))]\n # filling list of func - threads\n for index, func in enumerate(func_in_threads):\n for thread in declared_threads:\n if func == thread.runnable_function:\n funcs_to_threads[index].append(thread)\n # checking where function is used more than one time as runnable\n for func_usage in funcs_to_threads:\n if len(func_usage) > 1:\n total_errors += 1\n warning = f\"{total_errors}) Предупреждение в методе <{context.name}>!\\n\"\n warning += \"Потоки:\\n\"\n cur_func = func_usage[0].runnable_function\n for thread in func_usage:\n warning += f\"\\\"<{thread.thread_name}> (строка {thread.line_appeared})\\\"\\n\"\n warning += f\"используют одну и туже исполняемую функцию <{cur_func}>, \" \\\n f\"это может вызвать состояние гонки!\\n\"\n self.output.append(warning)\n self.output.append(self.vulnerability_name + \": \" + str(total_errors))\n return self.output\n","sub_path":"handlers/race_condition_handler.py","file_name":"race_condition_handler.py","file_ext":"py","file_size_in_byte":2185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"295738077","text":"# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport math\nimport os, sys\nimport numpy as np\nimport pdb\nfrom ogb.lsc import WikiKG90MDataset, WikiKG90MEvaluator\nimport pickle\nimport paddle\nfrom paddle.io import Dataset, DataLoader\n\n\nclass KGDataset:\n '''Load a knowledge graph\n\n The folder with a knowledge graph has five files:\n * entities stores the mapping between entity Id and entity name.\n * relations stores the mapping between relation Id and relation name.\n * train stores the triples in the training set.\n * valid stores the triples in the validation set.\n * test stores the triples in the test set.\n\n The mapping between entity (relation) Id and entity (relation) name is stored as 'id\\tname'.\n\n The triples are stored as 'head_name\\trelation_name\\ttail_name'.\n '''\n\n def __init__(self,\n entity_path,\n relation_path,\n train_path,\n valid_path=None,\n test_path=None,\n format=[0, 1, 2],\n delimiter='\\t',\n skip_first_line=False):\n self.delimiter = delimiter\n self.entity2id, self.n_entities = self.read_entity(entity_path)\n self.relation2id, self.n_relations = self.read_relation(relation_path)\n self.train = self.read_triple(train_path, \"train\", skip_first_line,\n format)\n if valid_path is not None:\n self.valid = self.read_triple(valid_path, \"valid\", skip_first_line,\n format)\n else:\n self.valid = None\n if test_path is not None:\n self.test = self.read_triple(test_path, \"test\", skip_first_line,\n format)\n else:\n self.test = None\n\n def read_entity(self, entity_path):\n with open(entity_path) as f:\n entity2id = {}\n for line in f:\n eid, entity = line.strip().split(self.delimiter)\n entity2id[entity] = int(eid)\n\n return entity2id, len(entity2id)\n\n def read_relation(self, relation_path):\n with open(relation_path) as f:\n relation2id = {}\n for line in f:\n rid, relation = line.strip().split(self.delimiter)\n relation2id[relation] = int(rid)\n\n return relation2id, len(relation2id)\n\n def read_triple(self, path, mode, skip_first_line=False, format=[0, 1, 2]):\n # mode: train/valid/test\n if path is None:\n return None\n\n print('Reading {} triples....'.format(mode))\n heads = []\n tails = []\n rels = []\n with open(path) as f:\n if skip_first_line:\n _ = f.readline()\n for line in f:\n triple = line.strip().split(self.delimiter)\n h, r, t = triple[format[0]], triple[format[1]], triple[format[\n 2]]\n heads.append(self.entity2id[h])\n rels.append(self.relation2id[r])\n tails.append(self.entity2id[t])\n\n heads = np.array(heads, dtype=np.int64)\n tails = np.array(tails, dtype=np.int64)\n rels = np.array(rels, dtype=np.int64)\n print('Finished. Read {} {} triples.'.format(len(heads), mode))\n return (heads, rels, tails)\n\n\nclass KGDatasetWiki(KGDataset):\n '''Load a knowledge graph wikikg\n '''\n\n def __init__(self, args, path, name='wikikg90m'):\n self.name = name\n self.dataset = WikiKG90MDataset(path)\n if args.eval_percent != 1.:\n num_valid = len(self.dataset.valid_dict['h,r->t']['hr'])\n num_valid = int(num_valid * args.eval_percent)\n self.dataset.valid_dict['h,r->t']['hr'] = self.dataset.valid_dict[\n 'h,r->t']['hr'][:num_valid]\n self.dataset.valid_dict['h,r->t'][\n 't_candidate'] = self.dataset.valid_dict['h,r->t'][\n 't_candidate'][:num_valid]\n self.dataset.valid_dict['h,r->t'][\n 't_correct_index'] = self.dataset.valid_dict['h,r->t'][\n 't_correct_index'][:num_valid]\n print(\"num_valid\", num_valid)\n if args.test_percent != 1.:\n num_test = len(self.dataset.test_dict['h,r->t']['hr'])\n num_test = int(num_test * args.test_percent)\n self.dataset.test_dict['h,r->t']['hr'] = self.dataset.test_dict[\n 'h,r->t']['hr'][:num_test]\n self.dataset.test_dict['h,r->t'][\n 't_candidate'] = self.dataset.test_dict['h,r->t'][\n 't_candidate'][:num_test]\n print(\"num_test\", num_test)\n if args.train_percent != 1.:\n num_train = self.dataset.train_hrt.shape[0]\n num_train = int(num_train * args.train_percent)\n print(\"num_train\", num_train)\n self.train = self.dataset.train_hrt.T[:, :num_train]\n else:\n self.train = self.dataset.train_hrt.T\n\n self.n_entities = self.dataset.num_entities\n self.n_relations = self.dataset.num_relations\n self.valid = None\n self.test = None\n self.valid_dict = self.dataset.valid_dict\n self.test_dict = self.dataset.test_dict\n self.entity_feat = self.dataset.entity_feat\n self.relation_feat = self.dataset.relation_feat\n if 't,r->h' in self.valid_dict:\n del self.valid_dict['t,r->h']\n if 't,r->h' in self.test_dict:\n del self.valid_dict['t,r->h']\n\n @property\n def emap_fname(self):\n return None\n\n @property\n def rmap_fname(self):\n return None\n\n\nclass KGDatasetCN31(KGDataset):\n def __init__(self, path, name='toy'):\n self.name = name\n # self.dataset = WikiKG90MDataset(path)\n self.train = np.fromfile(\n os.path.join(path, \"train_triple_id.txt\"),\n sep=\"\\t\").astype(\"int32\").reshape([-1, 3]).T\n self.valid = np.fromfile(\n os.path.join(path, \"valid_triple_id.txt\"),\n sep=\"\\t\").astype(\"int32\").reshape([-1, 3]).T\n self.test = np.fromfile(\n os.path.join(path, \"test_triple_id.txt\"),\n sep=\"\\t\").astype(\"int32\").reshape([-1, 3]).T\n\n self.n_entities = self.train.max() + 1\n self.n_relations = self.train[1, :].max() + 1\n self.feat_dim = 768\n self.entity_feat = np.random.randn(\n self.n_entities,\n self.feat_dim) #np.load(os.path.join(path, \"entity_feat.npy\"))\n self.relation_feat = np.random.randn(\n self.n_relations,\n self.feat_dim) #np.load(os.path.join(path, \"relation_feat.npy\"))\n self.entity_degree = np.ones((self.n_entities, 2))\n self.valid_dict = {\n 'h,r->t': {\n 'hr': np.random.randint(\n 15, size=(50, 2)),\n 't_candidate': np.random.randint(\n 15, size=(50, 10)),\n 't_correct_index': np.random.randint(\n 5, size=(50, ))\n }\n }\n self.test_dict = {\n 'h,r->t': {\n 'hr': np.random.randint(\n 15, size=(50, 2)),\n 't_candidate': np.random.randint(\n 15, size=(50, 10)),\n 't_correct_index': np.random.randint(\n 5, size=(50, ))\n }\n }\n\n @property\n def emap_fname(self):\n return None\n\n @property\n def rmap_fname(self):\n return None\n\n\nclass KGDatasetToy(KGDataset):\n def __init__(self, path, name='toy'):\n self.name = name\n # self.dataset = WikiKG90MDataset(path)\n self.n_entities = 10000\n self.n_relations = 15\n self.feat_dim = 768\n self.train = np.random.randint(\n 15,\n size=(3, 100000)) # np.load(os.path.join(path, \"train_hrt.npy\")).T\n self.valid = None\n self.test = None\n self.entity_feat = np.random.randn(\n self.n_entities,\n self.feat_dim) #np.load(os.path.join(path, \"entity_feat.npy\"))\n self.relation_feat = np.random.randn(\n self.n_relations,\n self.feat_dim) #np.load(os.path.join(path, \"relation_feat.npy\"))\n self.entity_degree = np.ones((self.n_entities, 2))\n self.valid_dict = {\n 'h,r->t': {\n 'hr': np.random.randint(\n 15, size=(50, 2)),\n 't_candidate': np.random.randint(\n 15, size=(50, 10)),\n 't_correct_index': np.random.randint(\n 5, size=(50, ))\n }\n }\n self.test_dict = {\n 'h,r->t': {\n 'hr': np.random.randint(\n 15, size=(50, 2)),\n 't_candidate': np.random.randint(\n 15, size=(50, 10)),\n 't_correct_index': np.random.randint(\n 5, size=(50, ))\n }\n }\n\n @property\n def emap_fname(self):\n return None\n\n @property\n def rmap_fname(self):\n return None\n\n\ndef get_dataset(args,\n data_path,\n data_name,\n format_str='built_in',\n delimiter='\\t',\n files=None,\n has_edge_importance=False):\n if format_str == 'built_in':\n if data_name == \"wikikg90m\":\n dataset = KGDatasetWiki(args=args, path=data_path)\n elif data_name == \"toy\":\n dataset = KGDatasetToy(data_path)\n elif data_name == \"cn31\":\n dataset = KGDatasetCN31(data_path)\n else:\n assert False, \"Unknown dataset {}\".format(data_name)\n else:\n dataset = KGDatasetToy(data_path, args=args)\n\n return dataset\n\n\nclass TrainSampler(Dataset):\n \"\"\"Use Dataset to pack train_sampler\n \"\"\"\n\n def __init__(self, edges, n_entities, neg_sample_size):\n super().__init__()\n self.edges = edges\n self.n_entities = n_entities\n self.neg_sample_size = neg_sample_size\n\n def __len__(self):\n return len(self.edges)\n\n def __getitem__(self, index):\n h, r, t = self.edges[index]\n return h, r, t\n\n def head_collate_fn(self, data):\n # Corrupt head\n neg_head = None\n h_new = np.random.randint(0, self.n_entities, self.neg_sample_size)\n unique_entity = np.unique(\n np.concatenate([[x[0] for x in data], [x[2]\n for x in data], h_new]))\n reindex_dict = {}\n for idx in range(len(unique_entity)):\n reindex_dict[unique_entity[idx]] = idx\n\n def mp(entry):\n return reindex_dict[entry]\n\n mp = np.vectorize(mp)\n h = mp([x[0] for x in data])\n t = mp([x[2] for x in data])\n h_new = mp(h_new)\n\n h = paddle.to_tensor(h, dtype='int32')\n r = paddle.to_tensor([x[1] for x in data], dtype='int32')\n t = paddle.to_tensor(t, dtype='int32')\n h_new = paddle.to_tensor(h_new, dtype='int32')\n unique_entity = paddle.to_tensor(unique_entity, dtype='int32')\n\n return (h, r, t), (h_new, r, t), unique_entity, 1\n\n def tail_collate_fn(self, data):\n # Corrupt tail\n neg_head = False\n t_new = np.random.randint(0, self.n_entities, self.neg_sample_size)\n unique_entity = np.unique(\n np.concatenate([[x[0] for x in data], [x[2]\n for x in data], t_new]))\n reindex_dict = {}\n for idx in range(len(unique_entity)):\n reindex_dict[unique_entity[idx]] = idx\n\n def mp(entry):\n return reindex_dict[entry]\n\n mp = np.vectorize(mp)\n h = mp([x[0] for x in data])\n t = mp([x[2] for x in data])\n t_new = mp(t_new)\n\n h = paddle.to_tensor(h, dtype='int32')\n r = paddle.to_tensor([x[1] for x in data], dtype='int32')\n t = paddle.to_tensor(t, dtype='int32')\n t_new = paddle.to_tensor(t_new, dtype='int32')\n unique_entity = paddle.to_tensor(unique_entity, dtype='int32')\n\n return (h, r, t), (h, r, t_new), unique_entity, 0\n\n\nclass TrainDataset(object):\n \"\"\"Sampler for training.\n \"\"\"\n\n def __init__(self, dataset, args, has_importance=False):\n self.edges = dataset.train.T # numpy.ndarray\n self.n_entities = dataset.n_entities\n num_train = len(self.edges)\n print('|Train|:', num_train)\n\n def create_sampler(self,\n batch_size,\n num_workers,\n neg_sample_size,\n neg_mode='head'):\n dataset = TrainSampler(self.edges, self.n_entities, neg_sample_size)\n if neg_mode == 'head':\n sampler = DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=True,\n drop_last=True,\n collate_fn=dataset.head_collate_fn)\n elif neg_mode == 'tail':\n sampler = DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=True,\n drop_last=True,\n collate_fn=dataset.tail_collate_fn)\n else:\n assert False, \"Not supported neg mode!\"\n return sampler\n\n\nclass NewBidirectionalOneShotIterator:\n def __init__(self, dataloader_head, dataloader_tail):\n self.iterator_head = self.one_shot_iterator(dataloader_head)\n self.iterator_tail = self.one_shot_iterator(dataloader_tail)\n self.step = 0\n\n def __next__(self):\n self.step += 1\n if self.step % 2 == 0:\n pos_triples, neg_triples, ids, neg_head = next(self.iterator_head)\n else:\n pos_triples, neg_triples, ids, neg_head = next(self.iterator_tail)\n return pos_triples, neg_triples, ids, neg_head\n\n @staticmethod\n def one_shot_iterator(dataloader):\n while True:\n for pos_triples, neg_triples, ids, neg_head in dataloader:\n yield pos_triples, neg_triples, ids, neg_head\n\n\nclass EvalSampler(object):\n \"\"\"Sampler for validation and testing.\n \"\"\"\n\n def __init__(self, edges, batch_size, mode):\n self.edges = edges\n self.batch_size = batch_size\n self.mode = mode\n self.neg_head = 'head' in mode\n self.cnt = 0\n if 'head' in self.mode:\n self.mode = 't,r->h'\n self.num_edges = len(self.edges['t,r->h']['tr'])\n elif 'tail' in self.mode:\n self.mode = 'h,r->t'\n self.num_edges = len(self.edges['h,r->t']['hr'])\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.cnt == self.num_edges:\n raise StopIteration\n beg = self.cnt\n if self.cnt + self.batch_size > self.num_edges:\n self.cnt = self.num_edges\n else:\n self.cnt += self.batch_size\n if self.mode == 't,r->h':\n return paddle.to_tensor(\n self.edges['t,r->h']['tr'][beg:self.cnt],\n \"int64\"), paddle.to_tensor(\n self.edges['t,r->h']['h_correct_index'][beg:self.cnt],\n \"int64\"), paddle.to_tensor(\n self.edges['t,r->h']['h_candidate'][beg:self.cnt],\n \"int64\")\n elif self.mode == 'h,r->t':\n return paddle.to_tensor(\n self.edges['h,r->t']['hr'][beg:self.cnt],\n \"int64\"), paddle.to_tensor(\n self.edges['h,r->t']['t_correct_index'][beg:self.cnt],\n \"int64\"), paddle.to_tensor(\n self.edges['h,r->t']['t_candidate'][beg:self.cnt],\n \"int64\")\n\n def reset(self):\n \"\"\"Reset the sampler\n \"\"\"\n self.cnt = 0\n return self\n\n\nclass EvalDataset(object):\n \"\"\"Dataset for validation or testing.\n \"\"\"\n\n def __init__(self, dataset, args):\n self.name = args.dataset\n src = [dataset.train[0]]\n etype_id = [dataset.train[1]]\n dst = [dataset.train[2]]\n self.num_train = len(dataset.train[0])\n if dataset.valid is not None:\n src.append(dataset.valid[0])\n etype_id.append(dataset.valid[1])\n dst.append(dataset.valid[2])\n self.num_valid = len(dataset.valid[0])\n elif self.name in ['wikikg90m', 'toy']:\n self.valid_dict = dataset.valid_dict\n self.num_valid = len(self.valid_dict['h,r->t']['hr'])\n else:\n self.num_valid = 0\n if dataset.test is not None:\n src.append(dataset.test[0])\n etype_id.append(dataset.test[1])\n dst.append(dataset.test[2])\n self.num_test = len(dataset.test[0])\n elif self.name in ['wikikg90m']:\n self.test_dict = dataset.test_dict\n self.num_test = len(self.test_dict['h,r->t']['hr'])\n else:\n self.num_test = 0\n src = np.concatenate(src)\n etype_id = np.concatenate(etype_id)\n dst = np.concatenate(dst)\n\n def get_edges(self, eval_type):\n if eval_type == 'valid':\n return self.valid\n elif eval_type == 'test':\n return self.test\n else:\n raise Exception('get invalid type: ' + eval_type)\n\n def get_dicts(self, eval_type):\n if eval_type == 'valid':\n return self.valid_dict\n elif eval_type == 'test':\n return self.test_dict\n else:\n raise Exception('get invalid type: ' + eval_type)\n\n def create_sampler(self,\n eval_type,\n batch_size,\n mode='tail',\n num_workers=32,\n rank=0,\n ranks=1):\n \"\"\"Create sampler for validation or testing\n \"\"\"\n edges = self.get_dicts(eval_type)\n new_edges = {}\n assert 'tail' in mode\n if 'tail' in mode:\n beg = edges['h,r->t']['hr'].shape[0] * rank // ranks\n end = min(edges['h,r->t']['hr'].shape[0] * (rank + 1) // ranks,\n edges['h,r->t']['hr'].shape[0])\n new_edges['h,r->t'] = {\n 'hr': edges['h,r->t']['hr'][beg:end],\n 't_candidate': edges['h,r->t']['t_candidate'][beg:end],\n }\n if 't_correct_index' in edges['h,r->t']:\n new_edges['h,r->t']['t_correct_index'] = edges['h,r->t'][\n 't_correct_index'][beg:end]\n else:\n new_edges['h,r->t']['t_correct_index'] = np.zeros(\n end - beg, dtype=np.short)\n else:\n assert False, mode\n print(beg, end)\n return EvalSampler(new_edges, batch_size, mode)\n","sub_path":"examples/kddcup2021/WikiKG90M/model/dataloader.py","file_name":"dataloader.py","file_ext":"py","file_size_in_byte":19411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"450632546","text":"from django.urls import include, path\nfrom django.contrib import admin\nfrom django.views.generic import TemplateView\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom idp.views import (\n SendThroughIdP, ProvideInfo,\n PostToSP, AlternateProvideInfo\n)\n\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('accounts/', include('django.contrib.auth.urls')),\n path('idp/', include('djangosaml2idp.urls')),\n path('', TemplateView.as_view(template_name=\"index.html\")),\n path('iframe/', TemplateView.as_view(template_name=\"iframe.html\")),\n\n # Transactional protocol: user POST to IDP which will perform data exchange\n path('endpoint/post/', SendThroughIdP.as_view(), name='endpoint_post'),\n path('endpoint/get/', ProvideInfo.as_view(), name='endpoint_get'),\n\n # Alternate transactional protocol: user POST to SP, which will retrieve\n # data from IdP\n path('endpoint/direct/',\n PostToSP.as_view(),\n name='endpoint_direct'),\n path('endpoint/alternate_get/',\n # csrf_exempt(AlternateProvideInfo.as_view()),\n AlternateProvideInfo.as_view(),\n name='endpoint_alternate_get'),\n]\n","sub_path":"idp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"247722414","text":"\"\"\"\nProblems:\n============================\nGiven an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and\nj != k, and nums[i] + nums[j] + nums[k] == 0.\n\nNotice that the solution set must not contain duplicate triplets.\n\nExample 1:\nInput: nums = [-1,0,1,2,-1,-4]\nOutput: [[-1,-1,2],[-1,0,1]]\n\nExample 2:\nInput: nums = []\nOutput: []\n\nExample 3:\nInput: nums = [0]\nOutput: []\n\nConstraints:\n0 <= nums.length <= 3000\n-105 <= nums[i] <= 105\n\n\n\"\"\"\nimport time\nfrom itertools import combinations\n\nstart_time = time.time_ns()\n\n\nclass Solution(object):\n def threeSum(self, nums):\n vals = []\n for (i, ival), (j, jval), (k, kval) in combinations(enumerate(nums), 3):\n if (ival + jval + kval == 0) and (i != k) and (j != k) and (i != k):\n val = [ival, jval, kval]\n val.sort()\n if val not in vals:\n vals.append(val)\n return vals\n\n\ninput = [-1, 0, 1, 2, -1, -4]\nthree_sum = Solution()\noutput = three_sum.threeSum(input)\nprint(output)\n\nprint(\"Script Execution Time: %s \" % (time.time_ns() - start_time))\n","sub_path":"leetcode/three_sum.py","file_name":"three_sum.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"459924407","text":"import zipfile\nimport shutil\nimport os\nimport sys\n\nprint(\"Delete and create directory with_macro\")\nshutil.rmtree(\"with_macro\",True)\nos.mkdir(\"with_macro\")\n\nfilename = \"with_macro/\"+sys.argv[1]\nprint(\"Open file \" + sys.argv[1])\nshutil.copyfile(sys.argv[1],filename)\n\ndoc = zipfile.ZipFile(filename,'a')\ndoc.write(\"myscript.py\", \"Scripts/python/myscript.py\")\nmanifest = []\nfor line in doc.open('META-INF/manifest.xml'):\n if '' in line.decode('utf-8'):\n for path in ['Scripts/','Scripts/python/','Scripts/python/myscript.py']:\n manifest.append(' ' % path)\n manifest.append(line.decode('utf-8'))\n\ndoc.writestr('META-INF/manifest.xml', ''.join(manifest))\ndoc.close()\nprint(\"File created: \"+filename)\n\n","sub_path":"sandbox/include_macro.py","file_name":"include_macro.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"313165622","text":"#### import the simple module from the paraview\nfrom paraview.simple import *\n#### disable automatic camera reset on 'Show'\nparaview.simple._DisableFirstRenderCameraReset()\n\n# get color transfer function/color map for 'PLWWinterMorning'\npLWWinterMorningLUT = GetColorTransferFunction('PLWWinterMorning')\n\n# get active view\nrenderView1 = GetActiveViewOrCreate('RenderView')\n# uncomment following to set a specific view size\n# renderView1.ViewSize = [1625, 1159]\n\n# get color legend/bar for pLWWinterMorningLUT in view renderView1\npLWWinterMorningLUTColorBar = GetScalarBar(pLWWinterMorningLUT, renderView1)\n\n# Properties modified on pLWWinterMorningLUTColorBar\npLWWinterMorningLUTColorBar.UseCustomLabels = 1\npLWWinterMorningLUTColorBar.CustomLabels = [1.0, 2.0, 3.0, 4.5, 5.0]\n\n# Properties modified on pLWWinterMorningLUTColorBar\npLWWinterMorningLUTColorBar.CustomLabels = [2.0, 3.0, 4.5, 5.0]\n\n# Properties modified on pLWWinterMorningLUTColorBar\npLWWinterMorningLUTColorBar.AddRangeLabels = 0\n\n# change scalar bar placement\npLWWinterMorningLUTColorBar.Orientation = 'Horizontal'\npLWWinterMorningLUTColorBar.Position = [0.3249230769230768, 0.039447799827437444]\npLWWinterMorningLUTColorBar.ScalarBarLength = 0.33000000000000024\n\n# Properties modified on pLWWinterMorningLUT\npLWWinterMorningLUT.Annotations = ['', '']\npLWWinterMorningLUT.IndexedColors = [0.0, 0.0, 0.0]\n\n# Properties modified on pLWWinterMorningLUT\npLWWinterMorningLUT.Annotations = ['2.5', '']\n\n# Properties modified on pLWWinterMorningLUT\npLWWinterMorningLUT.Annotations = ['2.5', 'test']","sub_path":"tests/paraviewScripts/colorLegendSettings_5p4.py","file_name":"colorLegendSettings_5p4.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"56254092","text":"\"\"\"Feature template projection vs time view plugin.\n\nThis plugin adds an interactive vispy figure showing the projection of selected \nspikes onto the templatre of the first cluster vs time\n\nTo activate the plugin, copy this file to `~/.phy/plugins/` and add this line\nto your `~/.phy/phy_config.py`:\n\n```python\nc.TemplateGUI.plugins = ['FeatureTemplateTimeView']\n```\n\nLuke Shaheen - Laboratory of Brain, Hearing and Behavior Jan 2017\n\"\"\"\n\nfrom phy import IPlugin\nfrom phy.utils import Bunch\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom phy.utils._color import _spike_colors, ColorSelector, _colormap\nfrom phy.cluster.views.scatter import ScatterView\nimport os.path as op\n\nclass FeatureTemplateTime(ScatterView):\n _callback_delay = 100\n def __init__(self,\n coords=None, # function clusters: Bunch(x, y)\n sample_rate=None,\n path=None,\n cont=None,\n gui=None,\n **kwargs):\n\n if coords is None:\n coords=self.get_template_projections\n assert coords\n self.coords = coords\n self.controller=cont\n self.gui=gui\n blocksizes_path=op.join(path,'blocksizes.npy')\n if op.exists(blocksizes_path):\n self.blocksizes=np.load(blocksizes_path)[0]\n self.blockstarts=np.load(op.join(path,'blockstarts.npy'))[0]\n self.blocksizes_time=self.blocksizes/sample_rate\n self.blockstarts_time=self.blockstarts/sample_rate\n self.gap_times=np.diff(self.blockstarts_time)-self.blocksizes_time[:-1]\n self.show_block_gap=False\n self.show_block_lines=True\n else:\n self.show_block_gap=False\n self.show_block_lines=False\n # Initialize the view.\n super(ScatterView, self).__init__(**kwargs)\n #self.canvas.events.mouse_press.connect(self.on_mouse_press)\n if self.show_block_lines:\n @self.controller.supervisor.actions.add(menu='FeatureTemplateTimeView',name='Toggle show block gaps') \n def toggle_show_block_gap(self=self,sup=self.controller.supervisor):\n self.show_block_gap = not self.show_block_gap \n self.on_select()\n\n def on_select(self, cluster_ids=None, **kwargs):\n super(ScatterView, self).on_select(cluster_ids, **kwargs)\n cluster_ids = self.cluster_ids\n n_clusters = len(cluster_ids)\n if n_clusters == 0:\n return\n\n # Retrieve the data.\n bunchs = self._get_data(cluster_ids)\n\n # Compute the data bounds.\n data_bounds = self._get_data_bounds(bunchs)\n if self.show_block_gap: \n line_times=self.blockstarts_time\n grey_line_times=self.blockstarts_time[1:]-self.gap_times\n data_bounds = (0, 0,self.controller.model.duration+self.gap_times.sum(), data_bounds[3])\n else:\n data_bounds = (0, 0, self.controller.model.duration, data_bounds[3])\n if self.show_block_lines: \n line_times=self.blockstarts_time\n\n # Plot the points.\n with self.building():\n self._plot_points(bunchs, data_bounds) \n if self.show_block_lines:\n for time in line_times:\n self.lines(pos=[time, data_bounds[1], time, data_bounds[3]],color=(1, 1, 1, 1),data_bounds=data_bounds)\n if self.show_block_gap:\n for time in grey_line_times:\n self.lines(pos=[time, data_bounds[1], time, data_bounds[3]],color=(.4, .4, .4, 1),data_bounds=data_bounds)\n liney = 0.\n self.lines(pos=[[data_bounds[0], liney, data_bounds[2], liney]],\n data_bounds=data_bounds,\n color=(1., 1., 1., .5),\n )\n \n def _get_data(self, cluster_ids):\n b = self.coords(cluster_ids)\n return b\n def get_template_projections(self,cluster_ids):\n if len(cluster_ids) < 1 :\n return None\n\n ni = self.controller.get_template_counts(cluster_ids[0])\n x_min=np.inf\n x_max=-np.inf\n y_min=np.inf\n y_max=-np.inf\n out=list()\n for cid in cluster_ids:\n si = self.controller._get_spike_ids(cid, self.controller.n_spikes_features)\n ti = self.controller.model.get_template_features(si)\n x = np.copy(self.controller.model.spike_times[si])\n y = np.average(ti, weights=ni, axis=1)\n if self.show_block_gap:\n for j in range(len(self.gap_times)): \n x[np.logical_and(self.controller.model.spike_times[si]>self.blocksizes_time[:j+1].sum(),self.controller.model.spike_times[si] today:\n df.loc[:, \"date_end\"] = df['date_end'].replace({df['date_end'].max(): today})\n \n questions = [q for q in MAPPING.label.tolist() if q in df.columns]\n\n # computes the mean for each country-date-question observation\n # (returned in long format)\n df_means = df.groupby([\"entity\", \"date_end\"])[questions] \\\n .mean() \\\n .round(1) \\\n .rename_axis('question', axis=1) \\\n .stack() \\\n .rename('mean') \\\n .to_frame()\n \n # counts the number of non-NaN responses for each country-date-question\n # observation (returned in long format)\n df_counts = df.groupby([\"entity\", \"date_end\"])[questions] \\\n .apply(lambda gp: gp.notnull().sum()) \\\n .rename_axis('question', axis=1) \\\n .stack() \\\n .rename('num_responses') \\\n .to_frame()\n \n df_agg = pd.merge(df_means, df_counts, left_index=True, right_index=True, how='outer', validate='1:1')\n \n if MIN_RESPONSES:\n df_agg = df_agg[df_agg['num_responses'] >= MIN_RESPONSES]\n \n # converts dataframe back to wide format.\n df_agg = df_agg.unstack().reset_index()\n df_agg.columns = [f'{lvl1}__{lvl0}' if lvl1 else lvl0 for lvl0, lvl1 in df_agg.columns]\n df_agg.rename(columns={'date_end': 'date'}, inplace=True)\n\n # constructs date variable for internal Grapher usage.\n df_agg.loc[:, \"date_internal_use\"] = (df_agg['date'] - datetime.datetime.strptime(ZERO_DAY, '%Y-%m-%d')).dt.days\n df_agg.drop('date', axis=1, inplace=True)\n\n return df_agg\n\n\ndef _rename_columns(df):\n suffixes = ['mean', 'num_responses']\n rename_dict = {}\n for row in MAPPING.itertuples():\n for sfx in suffixes:\n key = f'{row.label}__{sfx}'\n if key in df.columns:\n val = row.code_name if sfx == 'mean' else f'{row.code_name}__{sfx}'\n rename_dict[key] = val\n df = df.rename(columns=rename_dict)\n\n # renames index columns for use in `update_db`.\n df = df.rename(columns={'entity': 'Country', 'date_internal_use': 'Year'})\n return df\n\n\ndef _reorder_columns(df):\n index_cols = ['Country', 'Year']\n data_cols = sorted([col for col in df.columns if col not in index_cols])\n df = df[index_cols + data_cols]\n return df\n\n\nif __name__ == \"__main__\":\n update_csv()\n","sub_path":"scripts/scripts/yougov.py","file_name":"yougov.py","file_ext":"py","file_size_in_byte":7887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"67951926","text":"# -*- coding: utf-8 -*-\n'''\nAuthor: Marco A. Gallegos\nDate: 2020/02/03\nDescription:\nthis archive describes the package metadata for pypi\n'''\nimport setuptools\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"sqoopit\",\n version=\"0.0.12\",\n author=\"Marco A. Gallegos\",\n author_email=\"ma_galeza@hotmail.com\",\n description=\"A simple package to let you Sqoop into HDFS/Hive/HBase with python\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/marco-gallegos/sqoopit\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"389652450","text":"import sys\nimport csv\nimport pandas as pds\nimport sqlite3\n\ninputFile = sys.argv[1]\noutputFile = sys.argv[2]\n\n# load dataframe using basic read_csv; this requires a lot of memory\n# df = pds.read_csv('../target/harmonized-table.tsv.gz', sep='\\t', dtype=str, quoting=csv.QUOTE_NONE)\n# len(df) # -> 14300584\n\n# read harmonized-table by chunks\nprint('reading chunks')\nchunks = []\nchunkSize = 10**6\nfor chunk in pds.read_csv(inputFile, sep='\\t', dtype=str, quoting=csv.QUOTE_NONE, chunksize=chunkSize):\n chunks.append(chunk)\n\t\n# create sqlite db and write each chunk into db; trying save the all the data at once failed\nprint('saving as sqlite3')\ncon = sqlite3.connect(outputFile)\nfor chunk in chunks:\n\tchunk.to_sql(name='biosample', con=con, if_exists='append', index=False)\n\n# test loading from sqlite\n# con = sqlite3.connect('../target/harmonized_table.db')\n# sqlDf = pds.read_sql('select * from biosample limit 10', con) # test loading 10 records\n# sqlDf = pds.read_sql('select * from biosample', con) # test loading all records; NB: this is VERY expensive operation\n","sub_path":"util/save-harmonized-table-to-sqlite.py","file_name":"save-harmonized-table-to-sqlite.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"9909575","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport math\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dense, LSTM\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom keras.optimizers import SGD\r\ndf = pd.read_csv(\"DataFrame.csv\")\r\ndf.head()\r\n\r\nprint(df['Date'].dtype)\r\n\r\ndata = df.filter(['close'])\r\n\r\n# Convert dataframe to numpy\r\ndataset = data.values\r\n\r\ntraining_data_len = math.ceil(len(dataset) * 0.75)\r\nprint(training_data_len)\r\nscaler = MinMaxScaler(feature_range=(0, 1))\r\nscaled_data = scaler.fit_transform(dataset)\r\nscaled_data\r\n\r\ntime_step=1\r\n# create scaled training dataset\r\ntrain_data = scaled_data[0:training_data_len, :]\r\n\r\nx_train = []\r\ny_train = []\r\n\r\nfor i in range(time_step, len(train_data) ):\r\n x_train.append(train_data[i-time_step:i, 0])\r\n y_train.append(train_data[i, 0])\r\n\r\n# converting training data to numpy for using LSTM model\r\nx_train, y_train = np.array(x_train), np.array(y_train)\r\nx_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))\r\nprint(x_train.shape)\r\n\r\n# Creating the LSTM model\r\nmodel = Sequential()\r\nmodel.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))\r\nmodel.add(LSTM(50, return_sequences=True))\r\nmodel.add(LSTM(50, return_sequences=True, input_shape=(x_train.shape[1], 1)))\r\nmodel.add(LSTM(50, return_sequences=True))\r\nmodel.add(LSTM(50))\r\nmodel.add(Dense(25))\r\nmodel.add(Dense(1))\r\n\r\nmodel.compile(optimizer=SGD(momentum=0.9), loss='mean_squared_error')\r\n# Training the model\r\nmodel.fit(x_train, y_train, batch_size=10, epochs=100, validation_split=0.14)\r\ntest_data = scaled_data[training_data_len - time_step:, :]\r\n\r\nx_test = []\r\ny_test = dataset[training_data_len:, :]\r\n\r\n\r\nfor i in range(time_step, len(test_data)):\r\n x_test.append(test_data[i-time_step:i, 0])\r\n\r\n# convert to numpy and reshape\r\nx_test = np.array(x_test)\r\nx_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))\r\n\r\npredictions = model.predict(x_test)\r\npredictions = scaler.inverse_transform(predictions)\r\n\r\n# Error\r\nrmse = np.sqrt((np.mean(predictions - y_test)**2))\r\nprint(\"The error rate of the model is\", rmse)\r\n","sub_path":"Test.py","file_name":"Test.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"532477195","text":"import os\nos.environ['CUDA_VISIBLE_DEVICES'] = \"0\" # select the GPU\n\nimport argparse\nimport numpy as np\nfrom numpy.lib.format import open_memmap\nfrom numpy import linalg as LA\nimport torch.nn as nn\nimport torch\n\n\n# Hyperparameters\nbch_sz = 2000\nprint_freq = 3\n\n\ndef angle(v1, v2):\n v1_n = v1 / LA.norm(v1, axis=1, keepdims=True)\n v2_n = v2 / LA.norm(v2, axis=1, keepdims=True)\n dot_v1_v2 = v1_n * v2_n\n dot_v1_v2 = 1.0 - np.sum(dot_v1_v2, axis=1)\n dot_v1_v2 = np.nan_to_num(dot_v1_v2)\n return dot_v1_v2\n\n\nntu_skeleton_bone_pairs = (\n (1, 2), (2, 21), (3, 21), (4, 3), (5, 21), (6, 5),\n (7, 6), (8, 7), (9, 21), (10, 9), (11, 10), (12, 11),\n (13, 1), (14, 13), (15, 14), (16, 15), (17, 1), (18, 17),\n (19, 18), (20, 19), (22, 23), (21, 21), (23, 8), (24, 25), (25, 12)\n)\n\nntu_skeleton_orig_bone_pairs = {\n 25: 12, 24: 25, 23: 8, 21: 21, 22: 23, 20: 19, 19: 18, 18: 17,\n 17: 1, 16: 15, 15: 14, 14: 13, 13: 1, 12: 11, 11: 10, 10: 9,\n 9: 21, 8: 7, 7: 6, 6: 5, 5: 21, 4: 3, 3: 21, 2: 21, 1: 2\n}\n\nntu_bone_adj = {\n 25: 12,\n 24: 12,\n 12: 11,\n 11: 10,\n 10: 9,\n 9: 21,\n 21: 21,\n 5: 21,\n 6: 5,\n 7: 6,\n 8: 7,\n 22: 8,\n 23: 8,\n 3: 21,\n 4: 3,\n 2: 21,\n 1: 2,\n 17: 1,\n 18: 17,\n 19: 18,\n 20: 19,\n 13: 1,\n 14: 13,\n 15: 14,\n 16: 15\n}\n\nntu_bone_angle_pairs = {\n 25: (24, 12),\n 24: (25, 12),\n 12: (24, 25),\n 11: (12, 10),\n 10: (11, 9),\n 9: (10, 21),\n 21: (9, 5),\n 5: (21, 6),\n 6: (5, 7),\n 7: (6, 8),\n 8: (23, 22),\n 22: (8, 23),\n 23: (8, 22),\n 3: (4, 21),\n 4: (4, 4),\n 2: (21, 1),\n 1: (17, 13),\n 17: (18, 1),\n 18: (19, 17),\n 19: (20, 18),\n 20: (20, 20),\n 13: (1, 14),\n 14: (13, 15),\n 15: (14, 16),\n 16: (16, 16)\n}\n\nbone_pairs = {\n 'ntu/xview': ntu_skeleton_bone_pairs,\n 'ntu/xsub': ntu_skeleton_bone_pairs,\n\n # NTU 120 uses the same skeleton structure as NTU 60\n 'ntu120/xsub': ntu_skeleton_bone_pairs,\n 'ntu120/xset': ntu_skeleton_bone_pairs,\n\n 'kinetics': (\n (0, 0), (1, 0), (2, 1), (3, 2), (4, 3), (5, 1), (6, 5), (7, 6), (8, 2), (9, 8), (10, 9),\n (11, 5), (12, 11), (13, 12), (14, 0), (15, 0), (16, 14), (17, 15)\n )\n}\n\nbenchmarks = {\n 'ntu': ('ntu/xview', 'ntu/xsub'),\n 'ntu120': ('ntu120/xset', 'ntu120/xsub'),\n 'kinetics': ('kinetics',)\n}\n\nparts = {'train', 'val'}\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Bone data generation for NTU60/NTU120/Kinetics')\n parser.add_argument('--dataset', choices=['ntu', 'ntu120', 'kinetics'])\n parser.add_argument('--edge-type')\n args = parser.parse_args()\n args.dataset = 'ntu120'\n args.edge_type = 'jnt_bon'\n\n save_name = None\n\n if args.edge_type == 'joint_bone_angle_arms_legs':\n save_name = 'data/{}/{}_data_jnt_bon_ang_arms_legs_cuda.npy'\n else:\n raise NotImplementedError('Unsupported edge type. ')\n\n print('save name: ', save_name)\n\n if args.edge_type == 'joint_bone_angle_arms_legs':\n for benchmark in benchmarks[args.dataset]:\n for part in parts:\n print(benchmark, part)\n data = np.load('data/{}/{}_data_joint.npy'.format(benchmark, part), mmap_mode='r')\n N, C, T, V, M = data.shape\n print('data shape: ', data.shape)\n\n # Number of batches\n bch_len = N // bch_sz\n\n print('creating fp sp...')\n\n # fp_sp = None\n fp_sp = open_memmap(\n save_name.format(benchmark, part),\n dtype='float32',\n mode='w+',\n shape=(N, 15, T, V, M))\n\n for i in range(bch_len+1):\n if i % print_freq == 0:\n print(f'{i} out of {bch_len}')\n a_bch = torch.tensor(data[i * bch_sz:(i + 1) * bch_sz])\n\n # generating bones\n fp_sp_joint_list_bone = []\n fp_sp_joint_list_bone_angle = []\n fp_sp_joint_list_body_center_angle_1 = []\n fp_sp_joint_list_body_center_angle_2 = []\n fp_sp_left_hand_angle = []\n fp_sp_right_hand_angle = []\n fp_sp_two_hand_angle = []\n fp_sp_two_elbow_angle = []\n fp_sp_two_knee_angle = []\n fp_sp_two_feet_angle = []\n\n all_list = [\n fp_sp_joint_list_bone, fp_sp_joint_list_bone_angle, fp_sp_joint_list_body_center_angle_1,\n fp_sp_joint_list_body_center_angle_2, fp_sp_left_hand_angle, fp_sp_right_hand_angle,\n fp_sp_two_hand_angle, fp_sp_two_elbow_angle, fp_sp_two_knee_angle,\n fp_sp_two_feet_angle\n ]\n\n # cosine\n cos = nn.CosineSimilarity(dim=1, eps=0)\n\n for a_key in ntu_bone_angle_pairs:\n a_angle_value = ntu_bone_angle_pairs[a_key]\n a_bone_value = ntu_bone_adj[a_key]\n the_joint = a_key - 1\n a_adj = a_bone_value - 1\n a_bch = a_bch.to('cuda')\n bone_diff = (a_bch[:, :3, :, the_joint, :] -\n a_bch[:, :3, :, a_adj, :]).unsqueeze(3).cpu()\n fp_sp_joint_list_bone.append(bone_diff)\n\n # bone angles\n v1 = a_angle_value[0] - 1\n v2 = a_angle_value[1] - 1\n vec1 = a_bch[:, :3, :, v1, :] - a_bch[:, :3, :, the_joint, :]\n vec2 = a_bch[:, :3, :, v2, :] - a_bch[:, :3, :, the_joint, :]\n angular_feature = (1.0 - cos(vec1, vec2))\n angular_feature[angular_feature != angular_feature] = 0\n fp_sp_joint_list_bone_angle.append(angular_feature.unsqueeze(2).unsqueeze(1).cpu())\n\n # body angles 1\n vec1 = a_bch[:, :3, :, 2 - 1, :] - a_bch[:, :3, :, the_joint, :]\n vec2 = a_bch[:, :3, :, 21 - 1, :] - a_bch[:, :3, :, the_joint, :]\n angular_feature = (1.0 - cos(vec1, vec2))\n angular_feature[angular_feature != angular_feature] = 0\n fp_sp_joint_list_body_center_angle_1.append(angular_feature.unsqueeze(2).unsqueeze(1).cpu())\n\n # body angles 2\n vec1 = a_bch[:, :3, :, the_joint, :] - a_bch[:, :3, :, 21 - 1, :]\n vec2 = a_bch[:, :3, :, 2 - 1, :] - a_bch[:, :3, :, 21 - 1, :]\n angular_feature = (1.0 - cos(vec1, vec2))\n angular_feature[angular_feature != angular_feature] = 0\n fp_sp_joint_list_body_center_angle_2.append(angular_feature.unsqueeze(2).unsqueeze(1).cpu())\n\n # left hand angle\n vec1 = a_bch[:, :3, :, 24 - 1, :] - a_bch[:, :3, :, the_joint, :]\n vec2 = a_bch[:, :3, :, 25 - 1, :] - a_bch[:, :3, :, the_joint, :]\n angular_feature = (1.0 - cos(vec1, vec2))\n angular_feature[angular_feature != angular_feature] = 0\n fp_sp_left_hand_angle.append(angular_feature.unsqueeze(2).unsqueeze(1).cpu())\n\n # right hand angle\n vec1 = a_bch[:, :3, :, 22 - 1, :] - a_bch[:, :3, :, the_joint, :]\n vec2 = a_bch[:, :3, :, 23 - 1, :] - a_bch[:, :3, :, the_joint, :]\n angular_feature = (1.0 - cos(vec1, vec2))\n angular_feature[angular_feature != angular_feature] = 0\n fp_sp_right_hand_angle.append(angular_feature.unsqueeze(2).unsqueeze(1).cpu())\n\n # two hand angle\n vec1 = a_bch[:, :3, :, 24 - 1, :] - a_bch[:, :3, :, the_joint, :]\n vec2 = a_bch[:, :3, :, 22 - 1, :] - a_bch[:, :3, :, the_joint, :]\n angular_feature = (1.0 - cos(vec1, vec2))\n angular_feature[angular_feature != angular_feature] = 0\n fp_sp_two_hand_angle.append(angular_feature.unsqueeze(2).unsqueeze(1).cpu())\n\n # two elbow angle\n vec1 = a_bch[:, :3, :, 10 - 1, :] - a_bch[:, :3, :, the_joint, :]\n vec2 = a_bch[:, :3, :, 6 - 1, :] - a_bch[:, :3, :, the_joint, :]\n angular_feature = (1.0 - cos(vec1, vec2))\n angular_feature[angular_feature != angular_feature] = 0\n fp_sp_two_elbow_angle.append(angular_feature.unsqueeze(2).unsqueeze(1).cpu())\n\n # two knee angle\n vec1 = a_bch[:, :3, :, 18 - 1, :] - a_bch[:, :3, :, the_joint, :]\n vec2 = a_bch[:, :3, :, 14 - 1, :] - a_bch[:, :3, :, the_joint, :]\n angular_feature = (1.0 - cos(vec1, vec2))\n angular_feature[angular_feature != angular_feature] = 0\n fp_sp_two_knee_angle.append(angular_feature.unsqueeze(2).unsqueeze(1).cpu())\n\n # two feet angle\n vec1 = a_bch[:, :3, :, 20 - 1, :] - a_bch[:, :3, :, the_joint, :]\n vec2 = a_bch[:, :3, :, 16 - 1, :] - a_bch[:, :3, :, the_joint, :]\n angular_feature = (1.0 - cos(vec1, vec2))\n angular_feature[angular_feature != angular_feature] = 0\n fp_sp_two_feet_angle.append(angular_feature.unsqueeze(2).unsqueeze(1).cpu())\n\n for a_list_id in range(len(all_list)):\n all_list[a_list_id] = torch.cat(all_list[a_list_id], dim=3)\n\n all_list = torch.cat(all_list, dim=1)\n\n # Joint features.\n fp_sp[i * bch_sz:(i + 1) * bch_sz, :3, :, :, :] = a_bch.cpu().numpy()\n # Bone and angle features.\n fp_sp[i * bch_sz:(i + 1) * bch_sz, 3:, :, :, :] = all_list.numpy()\n\n print('fp sp: ', fp_sp.shape)\n save_f_name = save_name.format(benchmark, part)\n with open(save_f_name, 'wb') as f:\n np.save(f, fp_sp)\n\n","sub_path":"generate_ntu_angular_encoding.py","file_name":"generate_ntu_angular_encoding.py","file_ext":"py","file_size_in_byte":10521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"124788611","text":"import logging\nimport uuid\nfrom base64 import b32encode\nfrom decimal import Decimal, ROUND_DOWN\nfrom os import urandom\n\nimport requests\n\n\nlogger = logging.getLogger(__name__.split('.')[0])\n\n\ndef get_clean_phone_number(phone_number):\n clean_mobile = phone_number.strip()\n if clean_mobile.startswith('+84'):\n clean_mobile = clean_mobile.replace('+84', '0')\n if clean_mobile.startswith('84'):\n clean_mobile = clean_mobile.replace('84', '0')\n elif not clean_mobile.startswith('0'):\n clean_mobile = '0%s' % clean_mobile\n return clean_mobile\n\n\ndef generate_code(digits=6):\n return uuid.uuid4().hex[:digits].upper()\n\n\ndef random_token():\n \"\"\"\n Returns a new random string that can be used as a static token.\n\n :rtype: str\n \"\"\"\n return b32encode(urandom(5)).decode('utf-8').lower()\n\n\ndef round_amount(amount, prec=8):\n amount = amount if isinstance(amount, Decimal) else Decimal(amount)\n fmt = '.{}1'.format(\n '0' * (prec - 1)\n )\n return amount.quantize(Decimal(fmt), rounding=ROUND_DOWN)\n","sub_path":"utils/general.py","file_name":"general.py","file_ext":"py","file_size_in_byte":1054,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"323241157","text":"# file = open('C://Users/Tima/Documents/GitHub/goto/X1/train.fa', 'r')\n# a = file.readlines()\n# file.close()\n# genesdict = {}\n# for x in range(len(a)-1):\n# if x%2==0:\n# name = a[x].replace('>','').replace('\\n','')\n# data = a[x+1].replace('\\n','')\n# genesdict[name] = data\n\n# gistE = {}\n# for x in range(101):\n# gistE[x] = 0\n\n# gistC = {}\n# for x in range(101):\n# gistC[x] = 0\n\n\n\n# def count_gist(): \n# for x in genesdict:\n# if x[0] == 'E':\n# gistE[find_gc(genesdict[x])]+=1\n# if x[0] == 'C':\n# gistC[find_gc(genesdict[x])]+=1 \n\n\n# count_gist()\n\n# resfile = open('C://Users/Tima/Desktop/refile.txt', 'w')\n# print('Гистограмма для C', file=resfile)\n# print(gistC, file=resfile)\n# print('\\n\\n', file=resfile)\n# print('Гистограмма для E', file=resfile)\n# print(gistE, file=resfile)\n# resfile.close()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nfrom math import log\n\n\n# file = open('C://Users/Tima/Documents/GitHub/goto/X1/train.fa', 'r')\n# a = file.readlines()\n# file.close()\n\n\n\n# genesdict = {}\n# for x in range(len(a)-1):\n# if x%2==0:\n# name = a[x].replace('>','').replace('\\n','')\n# data = a[x+1].replace('\\n','')\n# genesdict[name] = data\n\ngencode = {'TAT': 'Y', 'TAG': 'X', 'CAA': 'Q', 'CTC': 'L', 'TCG': 'S', 'GGT': 'G', 'CAG': 'Q', 'GGC': 'G', 'TTA': 'L', 'CTA': 'L', 'TTC': 'F', 'CGC': 'R', 'TAA': 'X', 'GCT': 'A', 'GAG': 'E', 'GAA': 'E', 'AGT': 'S', 'AAA': 'K', 'TGT': 'C', 'CGG': 'R', 'GTG': 'V', 'ACA': 'T', 'TCT': 'S', 'AGG': 'R', 'CAT': 'H', 'CCT': 'P', 'ATC': 'I', 'ACT': 'T', 'AAT': 'N', 'ACG': 'T', 'GGA': 'G', 'GTT': 'V', 'TCA': 'S', 'GGG': 'G', 'CGA': 'R', 'TCC': 'S', 'GAT': 'D', 'CCA': 'P', 'AAG': 'K', 'AGA': 'R', 'GCA': 'A', 'GCC': 'A', 'CAC': 'H', 'CTG': 'L', 'CTT': 'L', 'TGA': 'X', 'TAC': 'Y', 'TGG': 'W', 'GCG': 'A', 'ATG': 'M', 'CCC': 'P', 'ATA': 'I', 'CCG': 'P', 'ATT': 'I', 'AGC': 'S', 'TTT': 'F', 'CGT': 'R', 'GAC': 'D', 'ACC': 'T', 'TTG': 'L', 'TGC': 'C', 'GTC': 'V', 'AAC': 'N', 'GTA': 'V'}\n\ndef find_gc(gene):\n gc_count = 0\n for x in gene:\n if x == 'G' or x == 'C':\n gc_count+=1\n return int((gc_count/len(gene))*100)\n\n\ndef complement(dna):\n result_dna = ''\n for x in dna:\n if x == 'T':\n result_dna+='A'\n elif x == 'A':\n result_dna+='T'\n elif x == 'G':\n result_dna+='C'\n elif x == 'C':\n result_dna+='G'\n #result_dna = ''.join(reversed(result_dna))\n return result_dna[::-1]\n\n# def find_aminos_in_gene(gene):\n# aminos = {'V': 0, 'Y': 0, 'C': 0, 'T': 0, 'L': 0, 'E': 0, 'D': 0, 'N': 0, 'I': 0, 'M': 0, 'P': 0, 'S': 0, 'H': 0, 'X': 0, 'Q': 0, 'G': 0, 'F': 0, 'A': 0, 'K': 0, 'W': 0, 'R': 0}\n# complement_dna = complement(gene)\n# for x in range(len(gene)-2):\n# triplet = gene[x]+gene[x+1]+gene[x+2]\n# aminos[gencode[triplet]]+=1\n# for x in range(len(complement_dna)-2):\n# triplet = gene[x]+gene[x+1]+gene[x+2]\n# aminos[gencode[triplet]]+=1\n# return aminos\n\n# def definer(aminos, percent):\n# percent = 0\n# if aminos['A'] > 67:\n# percent+=5\n# if aminos['C'] < 51:\n# percent+=5\n# if aminos['E'] < 69:\n# percent+=5\n# if aminos['D'] < 44:\n# percent+=5\n# if aminos['G'] > 76:\n# percent+=5\n# if aminos['F'] > 172:\n# percent+=5\n# if aminos['I'] < 132:\n# percent+=5\n# if aminos['H'] < 47:\n# percent+=5\n# if aminos['K'] < 150:\n# percent+=5\n# if aminos['M'] < 27:\n# percent+=5\n# if aminos['L'] < 178:\n# percent+=5\n# if aminos['N'] < 102:\n# percent+=5\n# if aminos['Q'] < 63:\n# percent+=5\n# if aminos['P'] > 68:\n# percent+=5\n# if aminos['S'] < 159:\n# percent+=5\n# if aminos['R'] > 114:\n# percent+=5\n# if aminos['T'] < 87:\n# percent+=5\n# if aminos['W'] < 23:\n# percent+=5\n# if aminos['V'] < 87:\n# percent+=5\n# if aminos['Y'] < 53:\n# percent+=5\n# if percent>90:\n# return 'E'\n# else:\n# return 'C'\n\n\n# def define_read(gene):\n# gc = find_gc(gene)\n# if 29','').replace('\\n','')\n data = filelines[line_number+1].replace('\\n','')\n genesdict[name] = data\n return genesdict\n\n\ndef form_reads_list(filepath):\n file = open(filepath, 'r')\n filelines = file.readlines()\n file.close()\n #genesdict = {}\n reads_list = []\n for line_number in range(len(filelines)-1):\n if line_number%2==0:\n #name = filelines[line_number].replace('>','').replace('\\n','')\n data = filelines[line_number+1].replace('\\n','')\n reads_list.append(data)\n return reads_list\n\n\n\ndef add_nuc_to_chain(chain):\n nuc = ['T', 'G', 'C', 'A']\n result_chain = {}\n for x in chain:\n for y in nuc:\n result_chain[x+y]=1\n return result_chain\n\ndef gen_base_markchain(k):\n nuc = ['T', 'G', 'C', 'A']\n if k <= 1:\n return {'T':1, 'G':1, 'C':1, 'A':1}\n else:\n return add_nuc_to_chain(gen_base_markchain(k-1))\n\n\ndef find_n_plets(k, gene, markchain):\n for x in range(len(gene)-k):\n n_plet = ''\n for i in range(k):\n n_plet+=gene[x+i]\n markchain[n_plet]+=1\n return markchain\n\ndef form_markchain(k, read_dict, type):\n markchain = gen_base_markchain(k)\n lower_markchain = gen_base_markchain(k-1)\n genes = []\n for x in read_dict:\n if x[0] == type:\n genes.append(read_dict[x])\n for gene in genes:\n markchain = find_n_plets(k, gene, markchain)\n lower_markchain = find_n_plets(k-1, gene, lower_markchain)\n for n_plet in markchain:\n markchain[n_plet] = markchain[n_plet]/lower_markchain[n_plet[:len(n_plet)-1]]\n return markchain\n\n\ndef find_probability(k, E_chain, C_chain, gene):\n e_probability = 1\n c_probability = 1\n for x in range(len(gene)-k):\n n_plet = ''\n for i in range(k):\n n_plet+=gene[x+i]\n e_probability += log(E_chain[n_plet])\n c_probability += log(C_chain[n_plet])\n #return('[' + str(e_probability) + ',' + str(c_probability) + ']\\n')\n if e_probability>c_probability:\n return 'E '\n else:\n return 'C '\n\ntrain_genesdict = form_genesdict('C://Users/Tima/Documents/GitHub/goto/data/X1/train.fa')\ntest_genesdict = form_genesdict('C://Users/Tima/Documents/GitHub/goto/data/X1/test.fa')\nE_chain = form_markchain(8, train_genesdict, 'E')\nC_chain = form_markchain(8, train_genesdict, 'C')\n\n\nresult = ''\nfor gene in form_reads_list('C://Users/Tima/Documents/GitHub/goto/data/X1/test.fa'):\n result+=find_probability(8, E_chain, C_chain, gene)\nresfile = open('C://Users/Tima/Desktop/resfile.txt', 'w')\nprint(result, file=resfile)\nresfile.close()\n ","sub_path":"summer2016/files/Shunin/Shunin X1 code.py","file_name":"Shunin X1 code.py","file_ext":"py","file_size_in_byte":7458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"650859900","text":"from xcp2k.inputsection import InputSection\n\n\nclass _xaa_cylindrical3(InputSection):\n def __init__(self):\n InputSection.__init__(self)\n self.V_d = None\n self.X_xtnt = None\n self.Base_center = None\n self.Base_radius = None\n self.N_sides = None\n self.Apx_type = None\n self.N_prtn = None\n self.Thickness = None\n self.Smoothing_width = None\n self.Delta_alpha = None\n self._name = \"XAA_CYLINDRICAL\"\n self._keywords = {'N_sides': 'N_SIDES', 'X_xtnt': 'X_XTNT', 'Smoothing_width': 'SMOOTHING_WIDTH', 'Base_radius': 'BASE_RADIUS', 'V_d': 'V_D', 'N_prtn': 'N_PRTN', 'Delta_alpha': 'DELTA_ALPHA', 'Base_center': 'BASE_CENTER', 'Thickness': 'THICKNESS', 'Apx_type': 'APX_TYPE'}\n self._aliases = {'Sigma': 'Smoothing_width'}\n\n\n @property\n def Sigma(self):\n \"\"\"\n See documentation for Smoothing_width\n \"\"\"\n return self.Smoothing_width\n\n @Sigma.setter\n def Sigma(self, value):\n self.Smoothing_width = value\n","sub_path":"xcp2k/classes/_xaa_cylindrical3.py","file_name":"_xaa_cylindrical3.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"109974751","text":"import os\nimport asyncio\nimport logging\nimport configparser\nfrom contextlib import suppress\n\nfrom .objects import Object\nimport ib_insync.util as util\n\n__all__ = ['IBController']\n\n\nclass IBController(Object):\n \"\"\"\n Programmatic control over starting and stopping TWS/Gateway\n using IBController (https://github.com/ib-controller/ib-controller).\n \n On Windows the the proactor event loop must have been set:\n \n .. code-block:: python\n \n import asyncio\n asyncio.set_event_loop(asyncio.ProactorEventLoop())\n\n \"\"\"\n defaults = dict(\n APP='TWS', # 'TWS' or 'GATEWAY'\n TWS_MAJOR_VRSN='969',\n TRADING_MODE='live', # 'live' or 'paper'\n IBC_INI='~/IBController/IBController.ini',\n IBC_PATH='~/IBController',\n TWS_PATH='~/Jts',\n LOG_PATH='~/IBController/Logs',\n TWSUSERID='',\n TWSPASSWORD='',\n JAVA_PATH='',\n TWS_CONFIG_PATH='')\n __slots__ = list(defaults) + ['_proc', '_logger', '_monitor']\n\n def __init__(self, *args, **kwargs):\n Object.__init__(self, *args, **kwargs)\n self._proc = None\n self._monitor = None\n self._logger = logging.getLogger('ib_insync.IBController')\n self.start()\n\n def __enter__(self):\n return self\n\n def __exit__(self, *_exc):\n self.stop()\n\n def start(self):\n \"\"\"\n Launch TWS/IBG.\n \"\"\"\n util.syncAwait(self.startAsync())\n\n def stop(self):\n \"\"\"\n Cleanly shutdown TWS/IBG.\n \"\"\"\n util.syncAwait(self.stopAsync())\n\n def terminate(self):\n \"\"\"\n Terminate TWS/IBG.\n \"\"\"\n util.syncAwait(self.terminateAsync())\n\n async def startAsync(self):\n if self._proc:\n return\n self._logger.info('Starting')\n\n # expand paths\n d = self.dict()\n for k, v in d.items():\n if k.endswith('_PATH') or k.endswith('_INI'):\n d[k] = os.path.expanduser(v)\n if not d['TWS_CONFIG_PATH']:\n d['TWS_CONFIG_PATH'] = d['TWS_PATH']\n self.update(**d)\n\n # run shell command\n ext = 'bat' if os.sys.platform == 'win32' else 'sh'\n cmd = f'{d[\"IBC_PATH\"]}/Scripts/DisplayBannerAndLaunch.{ext}'\n env = {**os.environ, **d}\n self._proc = await asyncio.create_subprocess_shell(cmd, env=env,\n stdout=asyncio.subprocess.PIPE)\n self._monitor = asyncio.ensure_future(self.monitorAsync())\n\n async def stopAsync(self):\n if not self._proc:\n return\n self._logger.info('Stopping')\n\n # read ibcontroller ini file to get controller port\n txt = '[section]' + open(self.IBC_INI).read()\n config = configparser.ConfigParser()\n config.read_string(txt)\n contrPort = config.getint('section', 'IbControllerPort')\n\n _reader, writer = await asyncio.open_connection('127.0.0.1', contrPort)\n writer.write(b'STOP')\n await writer.drain()\n writer.close()\n await self._proc.wait()\n self._proc = None\n self._monitor.cancel()\n self._monitor = None\n\n async def terminateAsync(self):\n if not self._proc:\n return\n self._logger.info('Terminating')\n with suppress(ProcessLookupError):\n self._proc.terminate()\n await self._proc.wait()\n self._proc = None\n self._monitor.cancel()\n self._monitor = None\n\n async def monitorAsync(self):\n while self._proc:\n line = await self._proc.stdout.readline()\n if not line:\n break\n self._logger.info(line.strip().decode())\n","sub_path":"ib_insync/ibcontroller.py","file_name":"ibcontroller.py","file_ext":"py","file_size_in_byte":3676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"245143606","text":"\n# COPYRIGHT 2007 BY BBN TECHNOLOGIES CORP.\n\n# BY USING THIS SOFTWARE THE USER EXPRESSLY AGREES: (1) TO BE BOUND BY\n# THE TERMS OF THIS AGREEMENT; (2) THAT YOU ARE AUTHORIZED TO AGREE TO\n# THESE TERMS ON BEHALF OF YOURSELF AND YOUR ORGANIZATION; (3) IF YOU OR\n# YOUR ORGANIZATION DO NOT AGREE WITH THE TERMS OF THIS AGREEMENT, DO\n# NOT CONTINUE. RETURN THE SOFTWARE AND ALL OTHER MATERIALS, INCLUDING\n# ANY DOCUMENTATION TO BBN TECHNOLOGIES CORP.\n\n# BBN GRANTS A NONEXCLUSIVE, ROYALTY-FREE RIGHT TO USE THIS SOFTWARE\n# KNOWN AS THE OntoNotes DB Tool v. 0.9 (HEREINAFTER THE \"SOFTWARE\")\n# SOLELY FOR RESEARCH PURPOSES. PROVIDED, YOU MUST AGREE TO ABIDE BY THE\n# LICENSE AND TERMS STATED HEREIN. TITLE TO THE SOFTWARE AND ITS\n# DOCUMENTATION AND ALL APPLICABLE COPYRIGHTS, TRADE SECRETS, PATENTS\n# AND OTHER INTELLECTUAL RIGHTS IN IT ARE AND REMAIN WITH BBN AND SHALL\n# NOT BE USED, REVEALED, DISCLOSED IN MARKETING OR ADVERTISEMENT OR ANY\n# OTHER ACTIVITY NOT EXPLICITLY PERMITTED IN WRITING.\n\n# NO WARRANTY. THE SOFTWARE IS PROVIDED \"AS IS\" WITHOUT WARRANTY OF ANY\n# KIND. THE SOFTWARE IS PROVIDED FOR RESEARCH PURPOSES ONLY. AS SUCH,\n# IT MAY CONTAIN ERRORS, WHICH COULD CAUSE FAILURES OR LOSS OF DATA. TO\n# THE MAXIMUM EXTENT PERMITTED BY LAW, BBN MAKES NO WARRANTIES, EXPRESS\n# OR IMPLIED AS TO THE SOFTWARE, ITS CAPABILITIES OR FUNCTIONALITY,\n# INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR\n# ANY USE OF THE SOFTWARE. THE USER ASSUMES THE ENTIRE COST OF ALL\n# NECESSARY REPAIR OR CORRECTION, EVEN IF BBN HAS BEEN ADVISED OF THE\n# POSSIBILITY OF SUCH A DEFECT OR DAMAGES. BBN MAKES NO WARRANTY THAT\n# THE SOFTWARE WILL MEET THE USER REQUIREMENTS, OR WILL BE\n# UNINTERRUPTED, TIMELY, SECURE, OR ERROR-FREE.\n\n# LIMITATION OF LIABILITY. THE ENTIRE RISK AS TO THE RESULTS AND\n# PERFORMANCE OF THE SOFTWARE IS ASSUMED BY THE USER. TO THE MAXIMUM\n# EXTENT PERMITTED BY APPLICABLE LAW, BBN SHALL NOT BE LIABLE WITH\n# RESPECT TO ANY SUBJECT MATTER OF THIS AGREEMENT UNDER ANY CONTRACT,\n# NEGLIGENCE, STRICT LIABILITY OR OTHER THEORY FOR ANY DIRECT,\n# CONSEQUENTIAL, RELIANCE, INCIDENTAL, SPECIAL, DIRECT OR INDIRECT\n# DAMAGES WHATSOEVER (INCLUDING WITHOUT LIMITATION, DAMAGES FOR LOSS OF\n# BUSINESS PROFITS, OR BUSINESS INFORMATION, OR FOR BUSINESS\n# INTERRUPTION, PERSONAL INJURY OR ANY OTHER LOSSES) RELATING TO (A)\n# LOSS OR INACCURACY OF DATA OR COST OF PROCUREMENT OF SUBSTITUTE\n# SYSTEM, SERVICES OR TECHNOLOGY, (B) THE USE OR INABILITY TO USE THE\n# SOFTWARE; (C) UNAUTHORIZED ACCESS TO OR ALTERATION OF YOUR\n# TRANSMISSIONS OR DATA; (D) ANY PERSONAL INJURY OR INJURY TO PROPERTY;\n# OR (E) ANY OTHER USE OF THE SOFTWARE EVEN IF BBN HAS BEEN FIRST\n# ADVISED OF THE POSSIBILITY OF ANY SUCH DAMAGES OR LOSSES.\n\n# WITHOUT LIMITATION OF THE FOREGOING, THE USER AGREES TO COMMIT NO ACT\n# WHICH, DIRECTLY OR INDIRECTLY, WOULD VIOLATE ANY U.S. LAW, REGULATION,\n# OR TREATY, OR ANY OTHER INTERNATIONAL TREATY OR AGREEMENT TO WHICH THE\n# UNITED STATES ADHERES OR WITH WHICH THE UNITED STATES COMPLIES,\n# RELATING TO THE EXPORT OR RE-EXPORT OF ANY COMMODITIES, SOFTWARE, OR\n# TECHNICAL DATA.\n\n\"\"\"\n----------------------------------------------------------------------\n:mod:`parallel` -- Alignment Metadata for Parallel Texts\n----------------------------------------------------------------------\n\nSee:\n\n - :class:`parallel_sentence`\n - :class:`parallel_document`\n - :class:`parallel_bank`\n\nCorrespondences:\n\n =========================== ====================================================== =====================================================================\n **Database Tables** **Python Objects** **File Elements**\n =========================== ====================================================== =====================================================================\n None :class:`parallel_bank` All ``.parallel`` files in an :class:`on.corpora.subcorpus`\n ``parallel_document`` :class:`parallel_document` The second line (original/translation line) in a ``.parallel`` file\n ``parallel_sentence`` :class:`parallel_sentence` All lines in a ``.parallel`` file after the first two (map lines)\n =========================== ====================================================== =====================================================================\n\n.. autoclass:: parallel_bank\n.. autoclass:: parallel_document\n.. autoclass:: parallel_sentence\n\n\"\"\"\n\n# author: sameer pradhan\n\nfrom __future__ import with_statement\nimport os\nimport os.path\nimport sys\nimport codecs\n\nimport on\nimport on.common.log\nimport on.common.util\nimport on.corpora\nimport on.corpora.tree\nimport on.corpora.proposition\nimport on.corpora.coreference\nimport on.corpora.name\nimport on.corpora.sense\n\nfrom on.corpora import abstract_bank\n\nclass parallel_sentence(object):\n\n def __init__(self, id_original, id_translation):\n self._trees = {\"translation\": None, \"original\" : None}\n\n self._ids = {}\n self.id_original = id_original\n self.id_translation = id_translation\n\n @property\n def id(self):\n return \"%s.%s\" % (self.id_translation, self.id_original)\n\n def __id_setter(trans_or_orig):\n def _set_id(self, val):\n if self._trees[trans_or_orig]:\n raise Exception(\"Cannot set id_%s after enrichment. Set tree_%s instead.\" % (trans_or_orig, trans_or_orig))\n self._ids[trans_or_orig] = val\n return _set_id\n\n def __id_getter(trans_or_orig):\n def _get_id(self):\n if self._trees[trans_or_orig]:\n return self._trees[trans_or_orig].id\n return self._ids[trans_or_orig]\n return _get_id\n\n id_original = property(__id_getter(\"original\"), __id_setter(\"original\"))\n id_translation = property(__id_getter(\"translation\"), __id_setter(\"translation\"))\n\n @property\n def tree_translation(self):\n return self._trees[\"translation\"]\n\n @property\n def tree_original(self):\n return self._trees[\"original\"]\n\n def set_trees(self, new_original, new_translation):\n if not ((new_original and new_translation) or (not new_original and not new_translation)):\n raise Exception(\"set_trees: new_original and new_translation should be both None or both non-None; instead got o=%s and t=%s\" % (\n None if not new_original else new_original.id,\n None if not new_translation else new_translation.id))\n\n assert (self.tree_original and self.tree_translation) or (not self.tree_original and not self.tree_translation)\n\n if self.tree_translation and self.tree_original:\n self.tree_translation.originals.remove(self.tree_original)\n self.tree_original.translations.remove(self.tree_translation)\n\n if new_original and new_translation:\n new_original.translations.append(new_translation)\n new_translation.originals.append(new_original)\n else:\n self._ids[\"original\"] = self.id_original\n self._ids[\"translation\"] = self.id_translation\n\n self._trees[\"original\"] = new_original\n self._trees[\"translation\"] = new_translation\n\n @staticmethod\n def from_string(map_line, original_document_id, translated_document_id):\n bits = map_line.split()\n\n if len(bits) != 3 or bits[0] != \"map\":\n on.common.log.error(\"Invalid line in parallel file: %s (%s)\"\n % (map_line, translated_document_id))\n\n return parallel_sentence(\"%s@%s\" % (bits[1], original_document_id),\n \"%s@%s\" % (bits[2], translated_document_id))\n\n def __repr__(self):\n return \"\"\\\n % (self.id, self.id_original, self.id_translation)\n\n sql_table_name = \"parallel_sentence\"\n sql_create_statement = \\\n\"\"\"\ncreate table parallel_sentence\n(\n id varchar(255) not null primary key,\n sentence_id_original varchar(255) not null,\n sentence_id_translation varchar(255) not null,\n foreign key (sentence_id_original) references sentence.id,\n foreign key (sentence_id_translation) references sentence.id\n)\ndefault character set utf8;\n\"\"\"\n\n sql_insert_statement = \\\n\"\"\"\ninsert into parallel_sentence\n(\n id,\n sentence_id_original,\n sentence_id_translation\n) values (%s, %s, %s)\n\"\"\"\n\n def write_to_db(self, cursor):\n cursor.execute(\"%s\" % (self.__class__.sql_insert_statement),\n (self.id, self.id_original, self.id_translation))\n\n\n def enrich_tree_document(self, original_tree_document,\n translation_tree_document):\n \"\"\" find the appropriate trees in the original and translated\n documents and let them know that they are related. Note that\n it's fine for a sentence to have multiple originals and for a\n sentence to have multiple translations. \"\"\"\n\n for a_id, a_td in [[self.id_original, original_tree_document],\n [self.id_translation, translation_tree_document]]:\n if a_id not in a_td.tree_ids:\n on.common.log.warning(\"id %s not found in tree document %s %r\\nThis is probably not the tree document this .parallel file was annotated against.\" % (\n a_id, a_td.document_id, [tid.split(\"@\")[0] for tid in a_td.tree_ids]))\n return\n\n self.set_trees(original_tree_document.tree_hash[self.id_original],\n translation_tree_document.tree_hash[self.id_translation])\n\n\nclass parallel_document(object):\n\n def __init__(self, id_original, id_translation, extension=\"parallel\"):\n self._tree_documents = {\"translation\" : None, \"original\" : None}\n self._ids = {}\n self.id_original = id_original\n self.id_translation = id_translation\n\n self.parallel_sentence_hash = {}\n self.parallel_sentence_id_list = []\n self.extension = extension\n\n\n @property\n def id(self):\n return \"%s.%s\" % (self.id_translation, self.id_original)\n\n @property\n def document_id(self):\n return self.id_translation\n\n def __id_setter(trans_or_orig):\n def _set_id(self, a_id):\n if self._tree_documents[trans_or_orig]:\n raise Exception(\"Cannot set id_%s after enrichment; set tree_%s instead.\" % (trans_or_orig, trans_or_orig))\n self._ids[trans_or_orig] = a_id\n return _set_id\n\n def __id_getter(trans_or_orig):\n def _get_id(self):\n if self._tree_documents[trans_or_orig]:\n return self._tree_documents[trans_or_orig].document_id\n return self._ids[trans_or_orig]\n return _get_id\n\n id_original = property(__id_getter(\"original\"), __id_setter(\"original\"))\n id_translation = property(__id_getter(\"translation\"), __id_setter(\"translation\"))\n\n @property\n def original_tree_document(self):\n return self._tree_documents[\"original\"]\n\n @property\n def translation_tree_document(self):\n return self._tree_documents[\"translation\"]\n\n\n def set_tree_documents(self, new_original, new_translation):\n if not ((new_original and new_translation) or (not new_original and not new_translation)):\n raise Exception(\"expected both None or both non-None\")\n\n assert (self.original_tree_document and self.translation_tree_document) or (not self.original_tree_document and not self.translation_tree_document)\n\n if new_original and new_translation:\n new_original.translations.append(new_translation)\n\n if new_translation.original:\n raise Exception(\"Got a document with more than one original: %s (%s ; %s)\"\n % (new_translation.id, new_translation.original.id, new_original.id))\n\n new_translation.original = new_original\n\n if self.original_tree_document and self.translation_tree_document:\n self.original_tree_document.translations.remove(self.translation_tree_document)\n self.translation_tree_document.original = None\n\n if not new_original and not new_translation and self.original_tree_document and self.translation_tree_document:\n self._ids[\"original\"] = self.id_original\n self._ids[\"translation\"] = self.id_translation\n\n self._tree_documents[\"original\"] = new_original\n self._tree_documents[\"translation\"] = new_translation\n\n def enrich_tree_documents(self, original_document, translation_document):\n\n self.set_tree_documents(original_document, translation_document)\n\n for a_parallel_sentence in self:\n a_parallel_sentence.enrich_tree_document(original_document, translation_document)\n\n @staticmethod\n def from_file(parallel_file_lines, translated_file_path, translated_subcorpus_id, extension=\"parallel\"):\n \"\"\" parallel file lines should look something like:\n\n translated document\n original chinese bc/cctv/00/cctv_0000\n map 0 0\n map 0 1\n ...\n\n \"\"\"\n\n if not parallel_file_lines[0].startswith(\"translated document\"):\n on.common.log.error(\"parallel_document: given bad file with initial line %s (in %s)\"\n % (parallel_file_lines[0], translated_subcorpus_id))\n\n original_file_path = parallel_file_lines[1].split()[2]\n original_lang_abbr = parallel_file_lines[1].split()[1]\n\n original_subcorpus_id = \"@\".join(translated_subcorpus_id.split(\"@\")[:-2] +\n [original_lang_abbr, translated_subcorpus_id.split(\"@\")[-1]])\n\n\n original_document_id = \"%s@%s\" % ( original_file_path, original_subcorpus_id )\n translated_document_id = \"%s@%s\" % ( translated_file_path, translated_subcorpus_id )\n\n translated_fid = translated_file_path.split(\"/\")[-1].split(\"_\")[-1]\n original_fid = original_file_path.split(\"/\")[-1].split(\"_\")[-1]\n\n if \"@%s@\" % translated_fid in original_document_id:\n original_document_id = original_document_id.replace(\"@%s@\" % translated_fid, \"@%s@\" % original_fid)\n elif \"@%s@\" % translated_fid[:2] in original_document_id:\n original_document_id = original_document_id.replace(\"@%s@\" % translated_fid[:2], \"@%s@\" % original_fid[:2])\n\n\n a_parallel_document = parallel_document(original_document_id, translated_document_id, extension)\n\n\n # now we go through the rest of the lines in the .parallel\n # file and build a large number of sentence to sentence\n # mappings. Note there may not be any at all if the\n # annotators didn't mark sentence to sentence mappings for\n # this document\n for line in [l.strip() for l in parallel_file_lines[2:] if l.strip()]:\n a_parallel_document.append( parallel_sentence.from_string(line, original_document_id, translated_document_id))\n\n return a_parallel_document\n\n @staticmethod\n def from_db(translation_document_id, a_cursor, extension=\"parallel\"):\n\n a_cursor.execute(\"select document_id_original from parallel_document where document_id_translation = '%s'\" % translation_document_id)\n rows = a_cursor.fetchall()\n\n if len(rows) != 1:\n on.common.log.error(\"Database coherency problem: multiple originals for translation %s\" % translation_document_id)\n\n original_document_id = rows[0][\"document_id_original\"]\n\n a_parallel_document = parallel_document(original_document_id, translation_document_id, extension)\n\n\n a_cursor.execute(\"\"\"select *\n from parallel_sentence\n join sentence\n on sentence.id = parallel_sentence.sentence_id_translation\n where sentence.document_id = '%s'\"\"\" % translation_document_id)\n\n for o, t in [(d_row[\"sentence_id_original\"], d_row[\"sentence_id_translation\"])\n for d_row in a_cursor.fetchall()]:\n a_parallel_document.append(parallel_sentence(o, t))\n\n return a_parallel_document\n\n def __getitem__(self, index):\n return self.parallel_sentence_hash[self.parallel_sentence_id_list[index]]\n\n def __len__(self):\n return len(self.parallel_sentence_id_list)\n\n def append(self, item):\n self.parallel_sentence_id_list.append(item.id)\n self.parallel_sentence_hash[item.id] = item\n\n def __repr__(self):\n return \"parallel_document instance: id=%s ; id_original=%s ; id_translation=%s ; %d parallel_sentences>\"\\\n % (self.id, self.id_original, self.id_translation, len(self))\n\n sql_table_name = \"parallel_document\"\n sql_create_statement = \\\n\"\"\"\ncreate table parallel_document\n(\n id varchar(255) not null,\n document_id_original varchar(255) not null,\n document_id_translation varchar(255) not null,\n foreign key (document_id_original) references document.id,\n foreign key (document_id_translation) references document.id\n)\ndefault character set utf8;\n\"\"\"\n\n sql_insert_statement = \\\n\"\"\"\ninsert into parallel_document\n(\n id,\n document_id_original,\n document_id_translation\n) values (%s, %s, %s)\n\"\"\"\n\n def write_to_db(self, cursor):\n cursor.execute(\"%s\" % (self.sql_insert_statement),\n (self.id, self.id_original, self.id_translation))\n\n for a_parallel_sentence in self:\n a_parallel_sentence.write_to_db(cursor)\n\n def dump_view(self, a_cursor=None, out_dir = \"\"):\n\n original_lang = self.id_original.split( \"@\")[-2]\n translation_lang = self.id_translation.split(\"@\")[-2]\n\n original_path = self.id_original.split( \"@\")[0]\n translation_path = self.id_translation.split(\"@\")[0]\n\n with codecs.open(on.common.util.output_file_name(self.id_translation, self.extension, out_dir), \"w\", \"utf-8\") as t_f:\n t_f.write(\"translated document\\n\")\n t_f.write(\"original %s %s\\n\" % (original_lang, original_path))\n for a_parallel_sentence in self:\n t_f.write(\"map %s %s\\n\" % (a_parallel_sentence.id_original.split( \"@\")[0],\n a_parallel_sentence.id_translation.split(\"@\")[0]))\n\n original_file_name = on.common.util.output_file_name(self.id_original, self.extension, out_dir)\n\n existing_lines = []\n existed = os.path.exists(original_file_name)\n if existed:\n with codecs.open(original_file_name, \"r\", \"utf-8\") as i_f:\n for line in i_f:\n if line.startswith(\"translation\"):\n existing_lines.append(line)\n with codecs.open(original_file_name, \"a\", \"utf-8\") as o_f:\n if not existed:\n o_f.write(\"original document\\n\")\n to_write = \"translation %s %s\\n\" % (translation_lang, translation_path)\n if to_write not in existing_lines:\n o_f.write(to_write)\n\nclass parallel_bank(abstract_bank):\n def __init__(self, a_subcorpus, tag, a_cursor=None, extension=\"parallel\"):\n abstract_bank.__init__(self, a_subcorpus, tag, extension)\n\n self.matching_parallel_banks = []\n self.matching_treebanks = []\n self.matching_subcorpora = []\n\n if(a_cursor == None):\n sys.stderr.write(\"reading the parallel bank [%s] ...\" % self.extension)\n for a_file in self.subcorpus.get_files(self.extension):\n sys.stderr.write(\".\")\n\n with codecs.open(a_file.physical_filename, \"r\", \"utf-8\") as f:\n parallel_file_lines = f.readlines()\n\n if parallel_file_lines[0].startswith(\"original document\"):\n \"\"\" we want to map translated documents back to their originals.\n There are two mapping files, which means there is redundant information,\n and we just need to do thing with the parallel files that represent\n translations. \"\"\"\n continue\n\n self.append(parallel_document.from_file(parallel_file_lines, a_file.document_id, a_subcorpus.id, self.extension))\n sys.stderr.write(\"\\n\")\n else:\n pass\n\n sql_table_name = \"parallel_document\"\n sql_exists_field = \"document_id_translation\"\n\n\n def enrich_treebank(self, a_translation_treebank):\n \"\"\" because we need both the original and the translation, we\n will ask the subcorpus for originals for this treebank, which\n may result in loading more treebanks.\n\n \"\"\"\n\n if not self:\n return # we don't contain any documents because we're the original's parallel bank\n\n sys.stderr.write(\"finding original trees to prepare for parallel bank enrichment....\")\n\n for a_parallel_document in self:\n try:\n a_original_subcorpus = self.subcorpus.find_subcorpus_for_document_id(a_parallel_document.id_original)\n except KeyError:\n continue\n\n a_original_treebank = a_original_subcorpus[a_translation_treebank.extension]\n\n if a_original_subcorpus not in self.matching_subcorpora:\n self.matching_subcorpora.append(a_original_subcorpus)\n\n if a_original_treebank not in self.matching_treebanks:\n self.matching_treebanks.append(a_original_treebank)\n\n sys.stderr.write(\" found %d original treebanks.\\n\" % len(self.matching_treebanks))\n\n if not self.matching_treebanks:\n on.common.log.status(\"warning: did not find *any* original treebanks\")\n return\n\n sys.stderr.write(\"enriching treebanks with tree-to-tree parallel data ....\")\n\n for a_parallel_document in self:\n sys.stderr.write(\".\")\n\n assert a_parallel_document.id_translation in a_translation_treebank\n\n original_treebank_candidates = [tb for tb in self.matching_treebanks if a_parallel_document.id_original in tb]\n if len(original_treebank_candidates) != 1:\n on.common.log.warning(\"the original document (%s) for document %s is %s; unable to enrich.\" % (\n a_parallel_document.id_original, a_parallel_document.id_translation,\n \"loaded more than once (%d times)\" % len(original_treebank_candidates) if original_treebank_candidates else \"not loaded\"))\n continue\n\n a_original_treebank = original_treebank_candidates[0]\n\n a_parallel_document.enrich_tree_documents(a_original_treebank.get_document(a_parallel_document.id_original),\n a_translation_treebank.get_document(a_parallel_document.id_translation))\n\n sys.stderr.write(\"\\n\")\n\n\n @classmethod\n def from_db(cls, a_subcorpus, tag, a_cursor, affixes=None):\n sys.stderr.write(\"reading the parallel bank ....\")\n a_parallel_bank = parallel_bank(a_subcorpus, tag, a_cursor)\n\n #---- now get all document ids for this subcorpus which are translations of other documents ----#\n a_cursor.execute(\"\"\"select document_id_translation\n from parallel_document\n join document\n on parallel_document.document_id_translation = document.id\n where document.subcorpus_id = '%s';\"\"\" % a_subcorpus.id)\n\n for a_document_id in [d_row[\"document_id_translation\"] for d_row in a_cursor.fetchall()]:\n\n if not on.common.util.matches_an_affix(a_document_id, affixes):\n continue\n\n sys.stderr.write(\".\")\n a_parallel_bank.append(parallel_document.from_db(a_document_id, a_cursor, a_parallel_bank.extension))\n\n sys.stderr.write(\"\\n\")\n return a_parallel_bank\n\n","sub_path":"camr_conversion/on/corpora/parallel.py","file_name":"parallel.py","file_ext":"py","file_size_in_byte":24009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"372902042","text":"import sys\nimport os\nsys.path.append(os.path.abspath('Resources'))\n\nfrom flask import Flask\nfrom flask.ext.restful import Api\n\napp = Flask(__name__)\napi = Api(app)\n\nfrom sectionResource import SectionsResource\nfrom sectionResource import SectionResource\nfrom subjectResource import SubjectsResource\n\nsectionRoutes = [\n '/section/',\n '/section'\n]\n\napi.add_resource(SectionsResource, '/sections')\napi.add_resource(SectionResource, *sectionRoutes)\napi.add_resource(SubjectsResource, '/subjects')\n\n@app.after_request\ndef after_request(response):\n response.headers.add('Access-Control-Allow-Origin', '*');\n response.headers.add('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With')\n response.headers.add('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE')\n return response\n\nif __name__ == '__main__':\n\tapp.run(debug=True)","sub_path":"src/RestApi/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"489049558","text":"import sys\nimport logging\nimport argparse\nfrom typing import Union\n\nfrom . import LOGGER_NAME\n# from .misc import can_use_interface\nfrom .channel_scanner import ChannelScanner, CHANNELS, FREQUENCIES\n\nlogger = logging.getLogger(LOGGER_NAME)\nSUBCMD_ARGS = {\n 'action': 'store_const',\n 'const': True,\n 'default': True,\n 'help': argparse.SUPPRESS\n}\n\n\ndef parse_args(args: list,\n exit: bool = True) -> Union[argparse.Namespace, None]:\n \"\"\"Arguments to control the ChannelScanner.\n\n usage: [-h] [--time TIME] [--graph-type {horizontal,vertical}]\n ... [--verbose | --debug | --console] interface\n ... {set,scan,hop,auto,search,hop_async_no_sniff} ...\n\n Channel scanner.\n\n positional arguments:\n interface Interface to sniff on.\n\n optional arguments:\n -h, --help show this help message and exit\n --time TIME, -t TIME Time in seconds between switching channels.\n --graph-type {horizontal,vertical}\n If console output is enabled, prints\n channel graph either horizontally or vertically.\n --verbose, -v Increase verbosity.\n --debug, -d Enable debugging output.\n --console, -c Program runs in console mode,\n utilising spinners and graphs.\n\n Modes:\n {set,scan,hop,auto,search,hop_async_no_sniff}\n set Set a certain channel.\n scan Scan channels.\n hop Hop between channels\n auto Scan channels and set current\n channel to most utilised channel.\n search Scan channel and search for an AccessPoint\n with a specific ssid.\n Set the current channel to that APs channel.\n hop_async_no_sniff Start a new thread that hops asynchronously\n and does not sniff data.\n \"\"\"\n parser = argparse.ArgumentParser(description='Channel scanner.')\n parser.add_argument('interface', help='Interface to sniff on.')\n\n # ---------- MODES ----------\n # 'set', 'scan', 'hop', 'auto' 'search', 'hop_async_no_sniff'\n modes = parser.add_subparsers(title=\"Modes\", dest='mode')\n setter = modes.add_parser('set', help=\"Set a certain channel.\")\n setter.add_argument(\n 'channel',\n type=int, help=\"Channel number of channel that is supposed to be set.\"\n )\n\n modes.add_parser('scan', help=\"Scan channels.\")\n\n modes.add_parser('hop', help=\"Hop between channels\")\n\n modes.add_parser(\n 'auto',\n help=\"Scan channels and set current channel to most utilised channel.\"\n )\n\n searcher = modes.add_parser('search', help=(\n \"Scan channel and search for an AccessPoint with a specific ssid. \"\n \"Set the current channel to that APs channel.\"\n ))\n searcher.add_argument('ssid', help=\"SSID in question.\")\n freqs = searcher.add_mutually_exclusive_group()\n freqs.add_argument(\n '--all',\n action=\"store_const\", const=FREQUENCIES._ALL, dest='freq',\n default=FREQUENCIES._ALL, help='Use all available frequencies (default).'\n )\n freqs.add_argument(\n '--2ghz', action=\"store_const\", const=FREQUENCIES._2GHz, dest='freq',\n help='Use only 2GHz frequency channels.'\n )\n freqs.add_argument(\n '--5ghz', action=\"store_const\", const=FREQUENCIES._5GHz, dest='freq',\n help='Use only 5GHz frequency channels.'\n )\n\n hop_async_no_sniff = modes.add_parser(\n 'hop_async_no_sniff',\n help=(\n \"Start a new thread that hops \"\n \"asynchronously and does not sniff data.\"\n )\n )\n channels = hop_async_no_sniff.add_mutually_exclusive_group()\n channels.add_argument(\n '--all-channels',\n action=\"store_const\", const=CHANNELS._ALL, dest='channels',\n default=CHANNELS._ALL, help='Use all available channels'\n )\n channels.add_argument(\n '--popular',\n action=\"store_const\", const=CHANNELS._POPULAR, dest='channels',\n help='Use most popular 2GHz channels 1, 6 and 12.'\n )\n channels.add_argument(\n '--populated',\n action=\"store_const\", const=CHANNELS._POPULATED, dest='channels',\n help=(\n 'Run scan available channels beforehand '\n 'and use only populated channels.'\n )\n )\n freqs = hop_async_no_sniff.add_mutually_exclusive_group()\n freqs.add_argument(\n '--all',\n action=\"store_const\", const=FREQUENCIES._ALL, dest='freq',\n default=FREQUENCIES._ALL, help='Use all available frequencies (default).'\n )\n freqs.add_argument(\n '--2ghz', action=\"store_const\", const=FREQUENCIES._2GHz, dest='freq',\n help='Use only 2GHz frequency channels.'\n )\n freqs.add_argument(\n '--5ghz', action=\"store_const\", const=FREQUENCIES._5GHz, dest='freq',\n help='Use only 5GHz frequency channels.'\n )\n hop_async_no_sniff.add_argument(\n '--random', action='store_true', help=\"Hop randomly between channels.\"\n )\n\n parser.add_argument(\n '--time', '-t', type=float, default=1,\n help=\"Time in seconds between switching channels.\"\n )\n parser.add_argument(\n '--graph-type', choices=['horizontal', 'vertical'],\n help=(\n \"If console output is enabled, \"\n \"prints channel graph either horizontally or vertically.\"\n )\n )\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\n '--verbose', '-v', action='store_true', help=\"Increase verbosity.\",\n )\n group.add_argument(\n '--debug', '-d', action='store_true', help='Enable debugging output.'\n )\n group.add_argument(\n '--console', '-c', action='store_true',\n help='Program runs in console mode. Utilising spinners and graphs.'\n )\n if exit:\n parsed_args = parser.parse_args(args)\n else:\n try:\n parsed_args = parser.parse_args(args)\n except SystemExit:\n parsed_args = None\n return parsed_args\n\n\ndef scan_channels(args=None): # noqa\n args = parse_args(args if args is not None else sys.argv[1:])\n if args.debug:\n if not logger.hasHandlers():\n logger.addHandler(logging.StreamHandler())\n logger.setLevel(logging.DEBUG)\n logger.debug(\"Debugging output enabled.\")\n elif args.verbose:\n if not logger.hasHandlers():\n logger.addHandler(logging.StreamHandler())\n logger.setLevel(logging.INFO)\n elif args.console:\n logger.setLevel(logging.ERROR)\n\n channel_scanner = ChannelScanner(\n args.interface, wait_time=args.time, console=args.console,\n )\n # 'set', 'scan', 'hop', 'auto' 'search', 'hop_async_no_sniff'\n if args.mode == 'set':\n channel_scanner.set_channel(args.channel)\n elif args.mode == 'scan':\n channel_scanner.channel_scanner()\n elif args.mode == 'hop':\n channel_scanner.channel_hopper()\n elif args.mode == 'auto':\n channel_scanner.set_auto_channel()\n elif args.mode == 'search':\n channel_scanner.ssid_searcher(args.ssid, args.freq)\n elif args.mode == 'hop_async_no_sniff':\n channel_scanner.channel_hopper_async_no_sniff(\n args.channels,\n args.freq,\n args.random\n )\n\n if args.console and args.graph_type == 'vertical':\n channel_scanner.print_channel_graph_vertical()\n elif args.console and args.graph_type == 'horizontal':\n channel_scanner.print_channel_graph_horizontal()\n\n\nif __name__ == '__main__': # pragma: no cover\n scan_channels()\n","sub_path":"probemon/wifi_channel/scan_channel.py","file_name":"scan_channel.py","file_ext":"py","file_size_in_byte":7699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"436810818","text":"from singleton import Singleton\nfrom secuenced_human_event import SecuencedHumanEvent\nfrom human_event import HumanEvent, \\\n MouseHumanEvent ,\\\n KeyboardHumanEvent ,\\\n SystemExternEvent\n\nfrom route_axis import RouteAxis\nfrom graph_parser import GraphParser\n\nimport re\n\nclass GraphInstance:\n \n def __init__(self):\n self.grap_name = 'Test graph'\n self.graph_parser = GraphParser.getInstance()\n self.navigator = self.graph_parser.navigator\n \n def load(self):\n j = Jaime.getInstance()\n url = 'http://samples.gaiaware.net/BasicControls/Timer/Overview/'\n self.graph_parser.entry_point = url\n \n ax = RouteAxis()\n ax.comment='Cargo pagina con ajax'\n ax.max_crosses = 1\n ax.to_url = re.compile(re.escape(url)+'.*') \n ax.axis_exit_method = RouteNode.CROSS_AXIS_METHOD_AJAX\n \n she = SecuencedHumanEvent() \n \n self.graph_parser.navigator.setAxis(ax,she)\n\n ax = RouteAxis()\n ax.comment='Cargo ajax de uso de cpu'\n ax.max_crosses = 10\n ax.to_url = re.compile(re.escape(url)+'.*') \n ax.axis_method = RouteNode.CROSS_AXIS_METHOD_AJAX\n ax.axis_exit_method = RouteNode.CROSS_AXIS_METHOD_AJAX\n \n she = SecuencedHumanEvent() \n self.graph_parser.navigator.setAxis(ax,she)\n \n \n# he = SystemExternEvent(\"whois\", [ '190.99.80.200'] ,'grep',['person:'])\n# he = SystemExternEvent(\"whois\", [ '190.99.80.200'] ,'sed',['-urn','/person:/p'])\n# she.pushHumanEvent(he) \n \n# he = SystemExternEvent(\"echo\", [ 'hola'],'grep',[ 'chau'])\n# she.pushHumanEvent(he) \n\n# he = MouseHumanEvent.moveMouseTo(\"input[name='q']\")\n# she.pushHumanEvent(he) \n# he = MouseHumanEvent.clickMouse()\n# she.pushHumanEvent(he) \n\n# he = KeyboardHumanEvent.writePushedText() \n# she.pushHumanEvent(he) \n \n# he = HumanEvent.saveImageUnderMouse('image.png')\n# she.pushHumanEvent(he) \n \n # he = SystemExternEvent(\"./dbc_client.py\", [ 'dguerchu', '30654815' ])\n # she.pushHumanEvent(he) \n \n# she.moveMouseTo(\"input[name='q']\")\n \n# he = SystemExternEvent(\"./dbc_client.py\", [ 'dguerchu', '30654815' ])\n# she.pushHumanEvent(he) \n \n# he = KeyboardHumanEvent.writePushedText() \n# she.pushHumanEvent(he) \n \n \n","sub_path":"src/application/graphs/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"413971507","text":"import os\nimport time\nimport argparse\nfrom stable_baselines import PPO2\nimport ray.rllib.agents.ppo as ppo\nfrom src.tfmodels.rlrec.movie_env import *\n\nconfig = ppo.DEFAULT_CONFIG.copy()\nconfig[\"num_gpus\"] = 0\nconfig[\"num_workers\"] = 8\nconfig[\"env\"]=MovieEnv\ntrainer = ppo.PPOTrainer(config=config)\n\ndef main(_):\n env = MovieEnv(config)\n episode_reward_p = 0\n import time\n begin = time.time()\n try:\n nepisode = 0\n step = 0\n while nepisode < 1:\n step = step + 1\n obs, reward, done, info = env.step([])\n if done:\n nepisode = nepisode + 1\n print(\"episode:{}\".format(nepisode), \"score:{}\".format(obs[\"score\"]))\n env.reset()\n end = time.time()\n print(\"total time: %.3f\" % ((end-begin)/60), \"min\")\n except KeyboardInterrupt:\n print('Game stopped, writing dump...')\n exit(1)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/tfmodels/rlrec/test_rllibppo.py","file_name":"test_rllibppo.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"143111187","text":"import pygame\n\nimport Type\nfrom Header import Header\nfrom Pallet import Pallet\nfrom ImageInfo import ImageInfo\nfrom Image import Image\n\nclass Art(object):\n\n def __init__(self, inputFile, header):\n\n self.header = header\n\n self.pallets = map(lambda i: Pallet(inputFile), range(self.header.numberOfPallets))\n\n infos = map(lambda i: ImageInfo(inputFile), range(self.header.numberOfAngles * self.header.numberOfFrames))\n\n self.images = map(lambda imageInfo:\n map(lambda pallet: Image(inputFile, imageInfo, pallet), self.pallets),\n infos)\n\n def Image(self, angleIndex, frameIndex = 0, palletIndex = 0):\n return self.images[angleIndex * self.header.numberOfFrames + frameIndex][palletIndex]\n\nclass RotatingAnimationArt(Art):\n\n def __init__(self, inputFile, header):\n super(RotatingAnimationArt, self).__init__(inputFile, header)\n\nclass StaticArt(Art):\n\n def __init__(self, inputFile, header):\n super(StaticArt, self).__init__(inputFile, header)\n\n def Image(self, frameIndex = 0, palletIndex = 0):\n return self.images[frameIndex][palletIndex]\n\nclass FontArt(StaticArt):\n\n ART_ASCII_OFFSET = 31\n\n def __init__(self, inputFile, header):\n super(FontArt, self).__init__(inputFile, header)\n\n def Sentence(self, sentence):\n\n characterImages = map(lambda character: self.Image(ord(character) - FontArt.ART_ASCII_OFFSET), sentence)\n\n totalWidth = sum(map(lambda x: x.info.drawOffset[0], characterImages))\n totalHeight = characterImages[1].info.drawOffset[1]\n\n sentenceTexture = pygame.Surface((totalWidth, totalHeight))\n sentenceTexture.set_colorkey((0, 0, 0))\n\n currentPosition = [0 , 0]\n for characterImage in characterImages:\n\n characterImage.Render(sentenceTexture, currentPosition)\n\n currentPosition[0] += characterImage.info.drawOffset[0]\n\n return sentenceTexture\n\ndef Read(inputFilePath):\n\n with open(inputFilePath, \"rb\") as inputFile:\n\n header = Header(inputFile)\n\n if header.type == Type.ROTATING_ART or header.type == Type.MOVING_ART:\n\n return RotatingAnimationArt(inputFile, header)\n\n elif header.type == Type.FONT_ART:\n\n return FontArt(inputFile, header)\n\n else:\n\n return StaticArt(inputFile, header)\n","sub_path":"EngineSrc/Data/DataTypes/Art/Art.py","file_name":"Art.py","file_ext":"py","file_size_in_byte":2378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"625436554","text":"#!/usr/bin/env python\n# | Copyright 2009-2016 Karlsruhe Institute of Technology\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# produces plots showing the Jobs performance\n#\n# run like this to plot all successful jobs:\n#\n# scripts/report.py --report PlotReport --job-selector state:SUCCESS\n#\n# add the option --use-task if you want the plotting script to load data like event count\n# per job from the configuration\n\ntry:\n\timport numpy\nexcept ImportError:\n\tnumpy = None\ntry:\n\timport matplotlib\n\timport matplotlib.pyplot\nexcept ImportError:\n\tmatplotlib = None\nimport os, re, logging\nfrom grid_control.output_processor import JobInfoProcessor, JobResult\nfrom grid_control.report import Report\nfrom grid_control.utils.data_structures import makeEnum\nfrom python_compat import irange, izip\n\nJobResultEnum = makeEnum([\n\t\"TIMESTAMP_WRAPPER_START\",\n\t\"TIMESTAMP_DEPLOYMENT_START\",\n\t\"TIMESTAMP_DEPLOYMENT_DONE\",\n\t\"TIMESTAMP_SE_IN_START\",\n\t\"TIMESTAMP_SE_IN_DONE\",\n\t\"TIMESTAMP_CMSSW_CMSRUN1_START\",\n\t\"TIMESTAMP_CMSSW_CMSRUN1_DONE\",\n\t\"TIMESTAMP_EXECUTION_START\",\n\t\"TIMESTAMP_EXECUTION_DONE\",\n\t\"TIMESTAMP_SE_OUT_START\",\n\t\"TIMESTAMP_SE_OUT_DONE\",\n\t\"TIMESTAMP_WRAPPER_DONE\",\n\t\"FILESIZE_IN_TOTAL\",\n\t\"FILESIZE_OUT_TOTAL\",\n\t\"EVENT_COUNT\"])\n\n\ndef extractJobTiming(jInfo, task):\n\tjobResult = dict()\n\tjobNum = jInfo[JobResult.JOBNUM]\n\n\t# intialize all with None\n\tfor key in JobResultEnum.enumNames:\n\t\tenumID = JobResultEnum.str2enum(key)\n\t\tjobResult[enumID] = None\n\n\ttotal_size_in = 0\n\ttotal_size_out = 0\n\tfor (key, val) in jInfo[JobResult.RAW].items():\n\t\tenumID = JobResultEnum.str2enum(key)\n\t\tif enumID is not None:\n\t\t\tjobResult[enumID] = val\n\n\t\t# look for file size information\n\t\tif re.match(\"OUTPUT_FILE_._SIZE\", key):\n\t\t\ttotal_size_out += int(val)\n\t\tif re.match(\"INPUT_FILE_._SIZE\", key):\n\t\t\ttotal_size_in += int(val)\n\n\tjobResult[JobResultEnum.FILESIZE_OUT_TOTAL] = total_size_out\n\tjobResult[JobResultEnum.FILESIZE_IN_TOTAL] = total_size_in\n\n\t# look for processed events, if available\n\tif task is not None:\n\t\tjobConfig = task.getJobConfig(jobNum)\n\t\tjobResult[JobResultEnum.EVENT_COUNT] = int(jobConfig[\"MAX_EVENTS\"])\n\t\t# make sure an undefined max event count (-1 in cmssw) is treated\n\t\t# as unkown event count\n\t\tif jobResult[JobResultEnum.EVENT_COUNT] < 0:\n\t\t\tjobResult[JobResultEnum.EVENT_COUNT] = None\n\telse:\n\t\tjobResult[JobResultEnum.EVENT_COUNT] = None\n\n\treturn jobResult\n\n\n# returns the job payload runtime in seconds\n# - if a CMSSW job was run, only the time spend in the actual\n# cmsRun call will be reported\n# - if a user job was run, the execution time of the user job\n# will be reported\ndef getPayloadRuntime(jobInfo):\n\tif (jobInfo[JobResultEnum.TIMESTAMP_CMSSW_CMSRUN1_START] is not None) and \\\n\t\t\t(jobInfo[JobResultEnum.TIMESTAMP_CMSSW_CMSRUN1_DONE] is not None):\n\t\treturn jobInfo[JobResultEnum.TIMESTAMP_CMSSW_CMSRUN1_DONE] - \\\n\t\t\tjobInfo[JobResultEnum.TIMESTAMP_CMSSW_CMSRUN1_START]\n\n\treturn jobInfo[JobResultEnum.TIMESTAMP_EXECUTION_DONE] - \\\n\t\tjobInfo[JobResultEnum.TIMESTAMP_EXECUTION_START]\n\n\ndef getSeOutRuntime(jobInfo):\n\treturn jobInfo[JobResultEnum.TIMESTAMP_SE_OUT_DONE] - \\\n\t\tjobInfo[JobResultEnum.TIMESTAMP_SE_OUT_START]\n\n\ndef getSeInRuntime(jobInfo):\n\treturn jobInfo[JobResultEnum.TIMESTAMP_SE_IN_DONE] - \\\n\t\tjobInfo[JobResultEnum.TIMESTAMP_SE_IN_START]\n\n\ndef getJobRuntime(jobInfo):\n\treturn jobInfo[JobResultEnum.TIMESTAMP_WRAPPER_DONE] - \\\n\t\tjobInfo[JobResultEnum.TIMESTAMP_WRAPPER_START]\n\n\n# note: can return None if no event count could be\n# determined for the job\ndef getEventCount(jobInfo):\n\treturn jobInfo[JobResultEnum.EVENT_COUNT]\n\n\ndef getEventRate(jobInfo):\n\tif (getPayloadRuntime(jobInfo) > 0) and (getEventCount(jobInfo) is not None):\n\t\treturn getEventCount(jobInfo) / (getPayloadRuntime(jobInfo) / 60.0)\n\telse:\n\t\treturn None\n\n\ndef getSeOutBandwidth(jobInfo):\n\tseOutTime = getSeOutRuntime(jobInfo)\n\tfileSize = jobInfo[JobResultEnum.FILESIZE_OUT_TOTAL]\n\n\tif seOutTime > 0:\n\t\treturn fileSize / seOutTime\n\telse:\n\t\treturn None\n\n\n# in MB\ndef getSeOutFilesize(jobInfo):\n\treturn jobInfo[JobResultEnum.FILESIZE_OUT_TOTAL] / 1000000.0\n\n\n# in MB\ndef getSeInFilesize(jobInfo):\n\treturn jobInfo[JobResultEnum.FILESIZE_IN_TOTAL] / 1000000.0\n\n\ndef getSeInBandwidth(jobInfo):\n\tseInTime = getSeInRuntime(jobInfo)\n\tfileSize = jobInfo[JobResultEnum.FILESIZE_IN_TOTAL]\n\tif seInTime > 0:\n\t\treturn fileSize / seInTime\n\n\ndef getJobCount(jobInfo):\n\treturn 1.0\n\n\ndef getSeOutAverageBandwithAtTimeSpan(jobInfo, timeStart, timeEnd):\n\tif getSeOutRuntime(jobInfo) > 0:\n\t\treturn getQuantityAtTimeSpan(jobInfo, timeStart, timeEnd,\n\t\t\tlambda jinf: (jinf[JobResultEnum.TIMESTAMP_SE_OUT_START], jinf[JobResultEnum.TIMESTAMP_SE_OUT_DONE]),\n\t\t\tgetSeOutBandwidth)\n\n\ndef getSeOutActiveAtTimeSpan(jobInfo, timeStart, timeEnd):\n\tif getSeOutRuntime(jobInfo) > 0:\n\t\treturn getQuantityAtTimeSpan(jobInfo, timeStart, timeEnd,\n\t\t\tlambda jinf: (jinf[JobResultEnum.TIMESTAMP_SE_OUT_START], jinf[JobResultEnum.TIMESTAMP_SE_OUT_DONE]),\n\t\t\tgetJobCount)\n\n\ndef getSeInAverageBandwithAtTimeSpan(jobInfo, timeStart, timeEnd):\n\tif getSeInRuntime(jobInfo) > 0:\n\t\treturn getQuantityAtTimeSpan(jobInfo, timeStart, timeEnd,\n\t\t\tlambda jinf: (jinf[JobResultEnum.TIMESTAMP_SE_IN_START], jinf[JobResultEnum.TIMESTAMP_SE_IN_DONE]),\n\t\t\tgetSeInBandwidth)\n\n\ndef getSeInActiveAtTimeSpan(jobInfo, timeStart, timeEnd):\n\tif getSeInRuntime(jobInfo) > 0:\n\t\treturn getQuantityAtTimeSpan(jobInfo, timeStart, timeEnd,\n\t\t\tlambda jinf: (jinf[JobResultEnum.TIMESTAMP_SE_IN_START], jinf[JobResultEnum.TIMESTAMP_SE_IN_DONE]),\n\t\t\tgetJobCount)\n\n\n# cumulated transfer sizes\n\ndef getSeOutSizeAtTimeSpan(jobInfo, timeStart, timeEnd):\n\tif getSeOutRuntime(jobInfo) > 0:\n\t\treturn getCumQuantityAtTimeSpan(jobInfo, timeStart, timeEnd,\n\t\t\tlambda jinf: (jinf[JobResultEnum.TIMESTAMP_SE_OUT_START], jinf[JobResultEnum.TIMESTAMP_SE_OUT_DONE]),\n\t\t\tgetSeOutFilesize)\n\n\ndef getSeInSizeAtTimeSpan(jobInfo, timeStart, timeEnd):\n\tif getSeInRuntime(jobInfo) > 0:\n\t\treturn getCumQuantityAtTimeSpan(jobInfo, timeStart, timeEnd,\n\t\t\tlambda jinf: (jinf[JobResultEnum.TIMESTAMP_SE_IN_START], jinf[JobResultEnum.TIMESTAMP_SE_IN_DONE]),\n\t\t\tgetSeInFilesize)\n\n\ndef getJobActiveAtTimeSpan(jobInfo, timeStart, timeEnd):\n\tif getJobRuntime(jobInfo) > 0:\n\t\treturn getQuantityAtTimeSpan(jobInfo, timeStart, timeEnd,\n\t\t\tlambda jinf: (jinf[JobResultEnum.TIMESTAMP_WRAPPER_START], jinf[JobResultEnum.TIMESTAMP_WRAPPER_DONE]),\n\t\t\tgetJobCount)\n\n\ndef getEventRateAtTimeSpan(jobInfo, timeStart, timeEnd):\n\tif getJobRuntime(jobInfo) > 0:\n\t\treturn getQuantityAtTimeSpan(jobInfo, timeStart, timeEnd,\n\t\t\tlambda jinf: (jinf[JobResultEnum.TIMESTAMP_CMSSW_CMSRUN1_START], jinf[JobResultEnum.TIMESTAMP_CMSSW_CMSRUN1_DONE]),\n\t\t\tgetEventRate)\n\n\ndef getCompleteRateAtTimeSpan(jobInfo, timeStart, timeEnd):\n\tif getJobRuntime(jobInfo) > 0:\n\t\treturn getCumQuantityAtTimeSpan(jobInfo, timeStart, timeEnd,\n\t\t\tlambda jinf: (jinf[JobResultEnum.TIMESTAMP_WRAPPER_START], jinf[JobResultEnum.TIMESTAMP_WRAPPER_DONE]),\n\t\t\tgetJobCount, useEndtime=True)\n\n\ndef getQuantityAtTimeSpan(jobInfo, timeStart, timeEnd, timingExtract, quantityExtract):\n\tassert (timeStart <= timeEnd)\n\n\t(theStart, theEnd) = timingExtract(jobInfo)\n\n\t# will be positive if there is overlap to the left\n\tleftOutside = max(0, theStart - timeStart)\n\t# will be positive if there is overlap to the right\n\trightOutside = max(0, timeEnd - theEnd)\n\ttotalOutside = leftOutside + rightOutside\n\tfractionOutside = float(totalOutside) / float(timeEnd - timeStart)\n\tfractionOutside = min(1.0, fractionOutside)\n\n\tq = quantityExtract(jobInfo)\n\tif q is not None:\n\t\treturn q * (1.0 - fractionOutside)\n\n\n# note: timeStart must be before all timestamps evaluated here\ndef getCumQuantityAtTimeSpan(jobInfo, timeStart, timeEnd, timingExtract, quantityExtract, useEndtime=False):\n\tassert (timeStart < timeEnd)\n\n\t(theStart, theEnd) = timingExtract(jobInfo)\n\n\t# simpler version, which does not interpolated between timeslices\n\tif useEndtime:\n\t\tif theEnd < timeStart:\n\t\t\treturn quantityExtract(jobInfo)\n\t\telse:\n\t\t\treturn 0\n\n\ttheSpan = theEnd - theStart\n\tdistFront = theStart - timeEnd\n\tdistBack = theEnd - timeEnd\n\n\t# current timeslice ends between theStart & theEnd\n\t# compute ratio of covered quantity\n\tif distFront < 0 and distBack >= 0:\n\t\tpartCovered = distBack / theSpan\n\t# current timeslice ends after theStart & theEnd\n\telif distFront < 0 and distBack < 0:\n\t\tpartCovered = 1.0\n\t# current timeslice ends before theStart & theEnd\n\telse:\n\t\tpartCovered = 0.0\n\n\treturn quantityExtract(jobInfo) * partCovered\n\n\nclass PlotReport(Report):\n\talias = ['plot']\n\n\tdef initHistogram(self, name, xlabel, ylabel):\n\t\tfig = matplotlib.pyplot.figure()\n\n\t\tax = fig.add_subplot(111)\n\t\tax.set_xlabel(xlabel) # ha=\"left\"\n\t\t# y = 0.8 will move the label more to the center\n\t\tax.set_ylabel(ylabel, va=\"top\", y=0.75, labelpad=20.0)\n\n\t\treturn (name, fig, ax)\n\n\tdef finalizeHistogram(self, plotSet, useLegend=False):\n\t\tif useLegend:\n\t\t\tmatplotlib.pyplot.legend(loc=\"upper right\", numpoints=1, frameon=False, ncol=2)\n\n\t\timageTypes = [\"png\", \"pdf\"]\n\t\tfor it in imageTypes:\n\t\t\tmatplotlib.pyplot.savefig(plotSet[0] + \".\" + it)\n\n\tdef plotHistogram(self, histo, jobResult, extractor):\n\t\tlog = logging.getLogger('report.plotreport')\n\t\tlog.info(\"Plotting \" + histo[0] + \" ...\")\n\t\truntime = []\n\t\tfor res in jobResult:\n\t\t\tval = extractor(res)\n\t\t\tif val is not None:\n\t\t\t\truntime.append(val)\n\n\t\tif not runtime:\n\t\t\tlog.info(\"Skipping \" + histo[0] + \", no input data\")\n\t\t\treturn None\n\n\t\t#thisHistType = \"bar\"\n\t\t# if transparent:\n\t\t#\tthisHistType = \"step\"\n\n\t\tpl = matplotlib.pyplot.hist(runtime, 40) # , color= plotColor, label = plotLabel, histtype=thisHistType)\n\t\t# histo[2].set_ymargin(0.4)\n\t\tlog.info(\"done\")\n\t\treturn pl\n\n\tdef plotOverall(self, histo, jInfos, timespan, extractor, fit=False, unit=\"MB/s\", cumulate=False):\n\t\tlog = logging.getLogger('report.plotreport')\n\t\tlog.info(\"Plotting \" + histo[0] + \" ...\")\n\n\t\ttrunctationFractionFront = 0.05\n\t\ttrunctationFractionBack = 0.3\n\n\t\trelTimeSpan = max(timespan) - min(timespan)\n\t\t# compute the amount of slices, for a small timespan, use every step\n\t\t# for large timespans, use 1000 slices at most\n\t\tstepSize = int(relTimeSpan / min(1000.0, relTimeSpan))\n\n\t\t(timeStep, overAllBandwidth) = \\\n\t\t\tself.collectData(min(timespan), max(timespan), stepSize, cumulate, extractor, jInfos)\n\n\t\tself.plotOverallAll(histo, timeStep, overAllBandwidth)\n\t\tif fit:\n\t\t\t# not the first and last 5 percent, used for fitting\n\t\t\t(timeStep, overAllBandwidth) = self.truncateData(timeStep, overAllBandwidth,\n\t\t\t\trelTimeSpan * trunctationFractionFront, relTimeSpan * (1.0 - trunctationFractionBack))\n\t\t\tif timeStep and overAllBandwidth:\n\t\t\t\tself.plotOverallTruncated(timeStep, overAllBandwidth, unit, trunctationFractionFront, trunctationFractionBack, relTimeSpan)\n\t\t\telse:\n\t\t\t\tlog.info(\"Skipping fit due to the lack of input data\")\n\t\tlog.info(\"done\")\n\n\tdef plotOverallAll(self, histo, timeStep, overAllBandwidth):\n\t\t# make sure the axis are not exactly the same\n\t\tminY = min(overAllBandwidth)\n\t\tmaxY = max(overAllBandwidth)\n\t\tif maxY <= minY:\n\t\t\tmaxY = minY + 1.0\n\n\t\thisto[2].set_ylim(bottom= minY * 0.99, top=maxY * 1.2)\n\t\thisto[2].set_xlim(left=min(timeStep) * 0.99, right=max(timeStep) * 1.01)\n\t\tmatplotlib.pyplot.plot(timeStep, overAllBandwidth, color=\"green\")\n\n\tdef collectData(self, minTime, maxTime, stepSize, cumulate, extractor, jInfos):\n\t\ttimeStep = []\n\t\toverAllBandwidth = []\n\t\tfor i in irange(minTime, maxTime + 1, stepSize):\n\t\t\tthisBw = 0\n\t\t\tcurrentTimeStep = i - minTime\n\t\t\ttimeStep.append(currentTimeStep)\n\n\t\t\tfor jinfo in jInfos:\n\t\t\t\tif cumulate:\n\t\t\t\t\tval = extractor(jinfo, minTime, i + 1)\n\t\t\t\telse:\n\t\t\t\t\tval = extractor(jinfo, i, i + stepSize)\n\n\t\t\t\tif val is not None:\n\t\t\t\t\tthisBw += val\n\n\t\t\toverAllBandwidth.append(thisBw)\n\t\treturn (timeStep, overAllBandwidth)\n\n\tdef truncateData(self, timeStep, overAllBandwidth, truncFront, truncBack):\n\t\ttruncatedTimeStep = []\n\t\ttruncatedOverAllBandwidth = []\n\t\tfor currentTimeStep, thisBw in izip(timeStep, overAllBandwidth):\n\t\t\tif (currentTimeStep > truncFront) and (currentTimeStep < truncBack):\n\t\t\t\ttruncatedOverAllBandwidth.append(thisBw)\n\t\t\t\ttruncatedTimeStep.append(currentTimeStep)\n\t\treturn (truncatedTimeStep, truncatedOverAllBandwidth)\n\n\tdef plotOverallTruncated(self, truncatedTimeStep, truncatedOverAllBandwidth, unit, trunctationFractionFront, trunctationFractionBack, relTimeSpan):\n\t\tfitRes = numpy.polyfit(truncatedTimeStep, truncatedOverAllBandwidth, 0)\n\n\t\tavgVal = fitRes[0]\n\t\tmatplotlib.pyplot.axhline(y=avgVal, xmin=trunctationFractionFront, xmax=1.0 - trunctationFractionBack,\n\t\t\tcolor=\"black\", lw=2)\n\n\t\tmatplotlib.pyplot.annotate(\"%.2f\" % avgVal + \" \" + unit, xy=(relTimeSpan * 0.7, avgVal),\n\t\t\txytext=(relTimeSpan * 0.75, avgVal * 0.85), backgroundcolor=\"gray\")\n\n\tdef handleMinMaxTiming(self, jResult, minTime, maxTime, stampStart, stampDone):\n\t\tif (minTime is None) or (maxTime is None):\n\t\t\tminTime = jResult[stampStart]\n\t\t\tmaxTime = jResult[stampDone]\n\t\telse:\n\t\t\tminTime = min(minTime, jResult[stampStart])\n\t\t\tmaxTime = max(maxTime, jResult[stampDone])\n\n\t\treturn(minTime, maxTime)\n\n\tdef produceHistogram(self, naming, lambdaExtractor):\n\t\thistogram = self.initHistogram(naming[0], naming[1], naming[2])\n\t\tself.plotHistogram(histogram, self.jobResult, lambdaExtractor)\n\t\tself.finalizeHistogram(histogram)\n\n\tdef produceOverallGraph(self, naming, timespan, lambdaExtractor, fit=False, unit=\"MB/s\", cumulate=False):\n\t\tlog = logging.getLogger('report.plotreport')\n\t\tif (timespan[0] == timespan[1]) or (timespan[0] is None) or (timespan[1] is None):\n\t\t\tlog.info(\"Skipping plot %s because no timespan is available\", naming)\n\t\t\treturn\n\t\thistogram = self.initHistogram(naming[0], naming[1], naming[2])\n\t\tself.plotOverall(histogram, self.jobResult, timespan, lambdaExtractor, fit, unit, cumulate)\n\t\tself.finalizeHistogram(histogram)\n\n\tdef display(self):\n\t\tif not numpy:\n\t\t\traise Exception('Unable to find numpy!')\n\t\tif not matplotlib:\n\t\t\traise Exception('Unable to find matplotlib!')\n\t\tself.jobResult = []\n\t\tlog = logging.getLogger('report.plotreport')\n\t\tlog.info(str(len(self._jobs)) + \" job(s) selected for plots\")\n\n\t\t# larger default fonts\n\t\tmatplotlib.rcParams.update({'font.size': 16})\n\n\t\tminSeOutTime = None\n\t\tmaxSeOutTime = None\n\n\t\tminSeInTime = None\n\t\tmaxSeInTime = None\n\n\t\tminWrapperTime = None\n\t\tmaxWrapperTime = None\n\n\t\tminCmsswTime = None\n\t\tmaxCmsswTime = None\n\n\t\tworkdir = self._jobDB.getWorkPath()\n\t\tfor j in self._jobs:\n\t\t\ttry:\n\t\t\t\tjInfo = JobInfoProcessor().process(os.path.join(workdir, 'output', 'job_%d' % j))\n\t\t\texcept Exception:\n\t\t\t\tlog.info(\"Ignoring job\")\n\t\t\t\tcontinue\n\n\t\t\tjResult = extractJobTiming(jInfo, self._task)\n\t\t\tself.jobResult.append(jResult)\n\n\t\t\t(minSeInTime, maxSeInTime) = self.handleMinMaxTiming(jResult, minSeInTime, maxSeInTime,\n\t\t\t\tJobResultEnum.TIMESTAMP_SE_IN_START, JobResultEnum.TIMESTAMP_SE_IN_DONE)\n\t\t\t(minSeOutTime, maxSeOutTime) = self.handleMinMaxTiming(jResult, minSeOutTime, maxSeOutTime,\n\t\t\t\tJobResultEnum.TIMESTAMP_SE_OUT_START, JobResultEnum.TIMESTAMP_SE_OUT_DONE)\n\t\t\t(minWrapperTime, maxWrapperTime) = self.handleMinMaxTiming(jResult, minWrapperTime, maxWrapperTime,\n\t\t\t\tJobResultEnum.TIMESTAMP_WRAPPER_START, JobResultEnum.TIMESTAMP_WRAPPER_DONE)\n\t\t\t(minCmsswTime, maxCmsswTime) = self.handleMinMaxTiming(jResult, minCmsswTime, maxCmsswTime,\n\t\t\t\tJobResultEnum.TIMESTAMP_CMSSW_CMSRUN1_START, JobResultEnum.TIMESTAMP_CMSSW_CMSRUN1_DONE)\n\n\t\tself.produceHistogram((\"payload_runtime\", \"Payload Runtime (min)\", \"Count\"),\n\t\t\tlambda x: getPayloadRuntime(x) / 60.0)\n\t\tself.produceHistogram((\"event_per_job\", \"Event per Job\", \"Count\"), getEventCount)\n\t\tself.produceHistogram((\"event_rate\", \"Event Rate (Events/min)\", \"Count\"), getEventRate)\n\t\tself.produceHistogram((\"se_in_runtime\", \"SE In Runtime (s)\", \"Count\"), getSeInRuntime)\n\t\tself.produceHistogram((\"se_in_size\", \"SE IN Size (MB)\", \"Count\"), getSeInFilesize)\n\t\tself.produceHistogram((\"se_out_runtime\", \"SE OUT Runtime (s)\", \"Count\"), getSeOutRuntime)\n\t\tself.produceHistogram((\"se_out_bandwidth\", \"SE OUT Bandwidth (MB/s)\", \"Count\"), getSeOutBandwidth)\n\t\tself.produceHistogram((\"se_out_size\", \"SE OUT Size (MB)\", \"Count\"), getSeOutFilesize)\n\t\tself.produceHistogram((\"se_out_runtime\", \"SE Out Runtime (s)\", \"Count\"), getSeOutRuntime)\n\n\t\t# job active & complete\n\t\tself.produceOverallGraph((\"job_active_total\", \"Time (s)\", \"Jobs Active\"),\n\t\t\t(minWrapperTime, maxWrapperTime), getJobActiveAtTimeSpan)\n\t\tself.produceOverallGraph((\"job_complete_total\", \"Time (s)\", \"Jobs Complete\"),\n\t\t\t(minWrapperTime, maxWrapperTime), getCompleteRateAtTimeSpan)\n\t\t# stage out active & bandwidth\n\t\tself.produceOverallGraph((\"se_out_bandwidth_total\", \"Time (s)\", \"Total SE OUT Bandwidth (MB/s)\"),\n\t\t\t(minSeOutTime, maxSeOutTime), getSeOutAverageBandwithAtTimeSpan, fit=True)\n\t\tself.produceOverallGraph((\"se_out_active_total\", \"Time (s)\", \"Active Stageouts\"),\n\t\t\t(minSeOutTime, maxSeOutTime), getSeOutActiveAtTimeSpan)\n\t\t# stage in active & bandwidth\n\t\tself.produceOverallGraph((\"se_in_bandwidth_total\", \"Time (s)\", \"Total SE IN Bandwidth (MB/s)\"),\n\t\t\t(minSeInTime, maxSeInTime), getSeInAverageBandwithAtTimeSpan, fit=True)\n\t\tself.produceOverallGraph((\"se_in_active_total\", \"Time (s)\", \"Active Stageins\"),\n\t\t\t(minSeInTime, maxSeInTime), getSeInActiveAtTimeSpan)\n\t\t# total stageout size\n\t\tself.produceOverallGraph((\"se_out_cum_size\", \"Time (s)\", \"Stageout Cumulated Size (MB)\"),\n\t\t\t(minSeOutTime, maxSeOutTime), getSeOutSizeAtTimeSpan, cumulate=True)\n\t\t# total stagein size\n\t\tself.produceOverallGraph((\"se_in_cum_size\", \"Time (s)\", \"Stagein Cumulated Size (MB)\"),\n\t\t\t(minSeInTime, maxSeInTime), getSeInSizeAtTimeSpan, cumulate=True)\n\t\t# event rate\n\t\tif (minCmsswTime is not None) and (maxCmsswTime is not None):\n\t\t\tself.produceOverallGraph((\"event_rate_total\", \"Time (s)\", \"Event Rate (Events/min)\"),\n\t\t\t\t(minCmsswTime, maxCmsswTime), getEventRateAtTimeSpan)\n\t\telse:\n\t\t\tlog.info(\"Skipping event_rate_total\")\n","sub_path":"packages/grid_control_gui/report_plot.py","file_name":"report_plot.py","file_ext":"py","file_size_in_byte":18310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"342007565","text":"#!/usr/bin/env python\n\n##############################################################################\n##\n## This file is part of Sardana\n##\n## http://www.sardana-controls.org/\n##\n## Copyright 2011 CELLS / ALBA Synchrotron, Bellaterra, Spain\n## \n## Sardana is free software: you can redistribute it and/or modify\n## it under the terms of the GNU Lesser 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## Sardana 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 Lesser General Public License for more details.\n## \n## You should have received a copy of the GNU Lesser General Public License\n## along with Sardana. If not, see .\n##\n##############################################################################\n\n\"\"\"This module contains the class definition for the MacroServer generic\nscan\"\"\"\n\n\n__all__ = [\"ls0d\", \"ls1d\", \"ls2d\", \"lsa\", \"lscom\", \"lsct\", \"lsctrl\",\n \"lsctrllib\", \"lsdef\", \"lsexp\", \"lsi\", \"lsior\", \"lsm\", \"lsmeas\",\n \"lspc\", \"lspm\", \"lsmac\", \"lsmaclib\"]\n\n__docformat__ = 'restructuredtext'\n\nfrom taurus.console import Alignment\nfrom taurus.console.list import List\nfrom sardana.macroserver.macro import *\n\nLeft, Right, HCenter = Alignment.Left, Alignment.Right, Alignment.HCenter\n\n#~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-\n# List of elements related macros\n#~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-\n\nclass _ls(Macro):\n param_def = [\n ['filter',\n ParamRepeat(['filter', Type.String, '.*', 'a regular expression filter'], min=1),\n '.*', 'a regular expression filter'],\n ]\n\n def get_column_names(self):\n cols = []\n for col in self.cols:\n if isinstance(col, tuple):\n col = col[0]\n cols.append(col)\n return cols\n \n def get_column_members(self):\n cols = []\n for col in self.cols:\n if isinstance(col, tuple):\n col = col[1]\n cols.append(col.lower())\n return cols\n \n def run(self, *filter):\n self.warning('This macro is not intended to be executed directly by ' \\\n 'the user')\n return\n\nclass lsdef(_ls):\n \"\"\"List all macro definitions\"\"\"\n\n cols = 'Name', 'Module', 'Brief Description'\n width = -1, -1, -1\n align = Right, Right, Left\n\n def run(self, filter):\n # TODO: passing a list causes TypeError: unhashable type: 'list'\n # uncomment it when bug-473 is fixed:\n # https://sourceforge.net/p/sardana/tickets/473/\n filter = filter[0]\n cols = self.get_column_names()\n out = List(cols, text_alignment=self.align,\n max_col_width=self.width)\n \n for m in self.getMacros(filter):\n if m.name.startswith(\"_\"):\n continue\n out.appendRow([m.name, m.module_name, m.get_brief_description()])\n \n for line in out.genOutput():\n self.output(line)\n\n\nclass _lsobj(_ls):\n \n subtype = Macro.All\n\n cols = 'Name', 'Type', 'Controller', 'Axis'#, 'State'\n width = -1, -1, -1, -1#, -1\n align = Right, Right, Right, Right#, Right\n\n def objs(self, filter):\n return self.findObjs(filter, type_class=self.type, subtype=self.subtype,\n reserve=False)\n\n def obj2Row(self, o, cols=None):\n cols = cols or self.get_column_members()\n ret = []\n for col in cols:\n if col == 'controller':\n value = self.getController(o.controller).name\n else:\n value = getattr(o, col)\n if value is None:\n value = '-----'\n ret.append(value)\n return ret\n \n def run(self, filter):\n objs = self.objs(filter)\n nb = len(objs)\n if nb is 0:\n if self.subtype is Macro.All:\n if isinstance(self.type, (str, unicode)):\n t = self.type.lower()\n else:\n t = \", \".join(self.type).lower()\n else:\n t = self.subtype.lower()\n self.output('No %ss defined' % t)\n return\n \n cols = self.get_column_names()\n out = List(cols, text_alignment=self.align,\n max_col_width=self.width)\n objs.sort()\n for obj in objs:\n try:\n out.appendRow( self.obj2Row(obj) )\n except:\n pass\n for line in out.genOutput():\n self.output(line)\n \n\nclass lsm(_lsobj):\n \"\"\"Lists all motors\"\"\"\n type = Type.Moveable\n\nclass lspm(lsm):\n \"\"\"Lists all existing motors\"\"\"\n subtype = 'PseudoMotor'\n\nclass lscom(_lsobj):\n \"\"\"Lists all communication channels\"\"\"\n type = Type.ComChannel\n \nclass lsior(_lsobj):\n \"\"\"Lists all IORegisters\"\"\"\n type = Type.IORegister\n\nclass lsexp(_lsobj):\n \"\"\"Lists all experiment channels\"\"\"\n type = Type.ExpChannel\n \nclass lsct(lsexp):\n \"\"\"Lists all Counter/Timers\"\"\"\n subtype = 'CTExpChannel'\n \nclass ls0d(lsexp):\n \"\"\"Lists all 0D experiment channels\"\"\"\n subtype = 'ZeroDExpChannel'\n \nclass ls1d(lsexp):\n \"\"\"Lists all 1D experiment channels\"\"\"\n subtype = 'OneDExpChannel'\n\nclass ls2d(lsexp):\n \"\"\"Lists all 2D experiment channels\"\"\"\n subtype = 'TwoDExpChannel'\n\nclass lspc(lsexp):\n \"\"\"Lists all pseudo counters\"\"\"\n subtype = 'PseudoCounter'\n\nclass lsctrllib(_lsobj):\n \"\"\"Lists all existing controller classes\"\"\"\n type = Type.ControllerClass\n cols = 'Name', ('Type', 'main_type'), ('Library', 'module'), ('Family','gender')\n\nclass lsctrl(_lsobj):\n \"\"\"Lists all existing controllers\"\"\"\n type = Type.Controller\n cols = 'Name', ('Type', 'main_type'), ('Class', 'klass'), 'Module'\n\nclass lsi(_lsobj):\n \"\"\"Lists all existing instruments\"\"\"\n type = Type.Instrument\n cols = 'Name', 'Type', ('Parent', 'parent_instrument')\n\nclass lsa(_lsobj):\n \"\"\"Lists all existing objects\"\"\"\n type = Type.Moveable, Type.ComChannel, Type.ExpChannel, Type.IORegister\n \nclass lsmeas(_lsobj):\n \"\"\"List existing measurement groups\"\"\"\n\n type = Type.MeasurementGroup\n\n cols = 'Active', 'Name', 'Timer', 'Experim. channels'\n width = -1, -1, -1, 60\n align = HCenter, Right, Right, Left\n \n def prepare(self, filter, **opts):\n try:\n self.mnt_grp = self.getEnv('ActiveMntGrp').lower() or None\n except:\n self.mnt_grp = None\n\n def obj2Row(self, o):\n if self.mnt_grp and (o.getName().lower() == self.mnt_grp):\n active = '*'\n else:\n active = ' '\n return active, o.name, o.getTimerName(), \", \".join(o.getChannelLabels())\n\nclass lsmac(_lsobj):\n \"\"\"Lists existing macros\"\"\"\n \n type = Type.MacroCode\n cols = 'Name', ('Location', 'file_path')\n\nclass lsmaclib(_lsobj):\n \"\"\"Lists existing macro libraries.\"\"\"\n \n type = Type.MacroLibrary\n cols = 'Name', ('Location', 'file_path')\n","sub_path":"src/sardana/macroserver/macros/lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":7388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"474489675","text":"import logging\nimport os\nimport yaml\n\n\nclass ConfigurationLoader:\n \n def load_config(self, config_file_path):\n \"\"\"\n The method will try to load the configuration\n to run the program.\n :param\n config_file_path: required configuration file path\n \"\"\"\n \n # Set up logger\n logger = logging.getLogger(__name__)\n \n if os.path.exists(config_file_path):\n logger.debug(\"Application configuration file found: {0}\"\n .format(config_file_path))\n with open(config_file_path, 'rt') as f:\n config = yaml.safe_load(f.read())\n return config\n else:\n message = \"Application configuration file NOT found, \" \\\n \"the application cannot start: {0}\" \\\n .format(config_file_path)\n logger.warning(message)\n raise OSError(message)\n","sub_path":"app/log/configuration_loader.py","file_name":"configuration_loader.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"97485267","text":"from django.test import TestCase\r\n\r\nfrom locallibrary.catalog.models import Author\r\nfrom django.urls import reverse\r\n\r\nclass AuthorListViewTest(TestCase):\r\n\r\n @classmethod\r\n def setUpTestData(cls):\r\n number_of_authors = 13\r\n for author_num in range(number_of_authors):\r\n Author.objects.create(first_name='Cristian %s' % author_num, last_name='Surname %s' % author_num)\r\n\r\n def test_view_url_exists_at_desired_location(self):\r\n resp = self.client.get('/catalog/authors/')\r\n self.assertEqual(resp.status_code, 200)\r\n\r\n def test_view_uses_correct_template(self):\r\n resp = self.client.get(reverse('authors'))\r\n self.assertEqual(resp.status_code, 200)\r\n\r\n self.assertTemplateUsed(resp, 'catalog/author_list.html')\r\n\r\n def test_pagination_is_ten(self):\r\n resp = self.client.get(reverse('authors'))\r\n self.assertEqual(resp.status_code, 200)\r\n self.assertTrue('is_paginated' in resp.context)\r\n self.assertTrue(resp.context['is_paginated'] == True)\r\n self.assertTrue(len(resp.context['author_list']) == 10)\r\n\r\n def test_list_all_authors(self):\r\n resp = self.client.get(reverse('authors')+'?page=2')\r\n self.assertEqual(resp.status_code, 200)\r\n self.assertTrue('is_paginated' in resp.context)\r\n self.assertTrue(resp.context['is_paginated'] == True)\r\n self.assertTrue( len(resp.context['author_list']) == 3)","sub_path":"locallibrary/catalog/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"354787519","text":"#!/usr/bin/env python\nimport os\nimport sys\n\nimport server\n\n\ndef customization():\n import threading\n t = threading.Thread(target=server.run)\n t.setDaemon(True)\n t.start()\n del t\n\n\ndef Is_child_processing():\n import re\n re_result = re.findall(\n \"{}\".format(os.getpid()),\n os.popen(\n \"ps -ejf | grep {} | grep -v \\\"grep\\\"\".format(os.getpid())).read()\n )\n ret = True if len(re_result) == 1 else False\n return ret\n\n\nif __name__ == '__main__':\n os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'serv.settings')\n try:\n from django.core.management import execute_from_command_line\n except ImportError as exc:\n raise ImportError(\n \"Couldn't import Django. Are you sure it's installed and \"\n \"available on your PYTHONPATH environment variable? Did you \"\n \"forget to activate a virtual environment?\"\n ) from exc\n\n if Is_child_processing():\n customization()\n\n execute_from_command_line(sys.argv)\n","sub_path":"src/archit_v1/serv/manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":1014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"47517071","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\nimport time\nimport webapp2_extras.appengine.auth.models\nfrom webapp2_extras import security\nfrom google.appengine.ext import ndb\n\nclass Counter(ndb.Model):\n nextPID = ndb.IntegerProperty()\n \nclass TPStore_v2(ndb.Model):\n PID = ndb.IntegerProperty()\n NID = ndb.IntegerProperty()\n \n status = ndb.IntegerProperty()\n label = ndb.StringProperty()\n \n ordering = ndb.IntegerProperty()\n \n # stepCounter = ndb.IntegerProperty()\n parentPath = ndb.IntegerProperty(repeated=True)\n\n##USER#######################\nclass User(webapp2_extras.appengine.auth.models.User):\n email_address = ndb.StringProperty()\n name = ndb.StringProperty()\n\n def set_password(self, raw_password):\n \"\"\"Sets the password for the current user\n \n :param raw_password:\n The raw password which will be hashed and stored\n \"\"\"\n self.password = security.generate_password_hash(raw_password, length=12)\n \n @classmethod\n def get_by_auth_token(cls, user_id, token, subject='auth'):\n \"\"\"Returns a user object based on a user ID and token.\n \n :param user_id:\n The user_id of the requesting user.\n :param token:\n The token string to be verified.\n :returns:\n A tuple ``(User, timestamp)``, with a user object and\n the token timestamp, or ``(None, None)`` if both were not found.\n \"\"\"\n token_key = cls.token_model.get_key(user_id, subject, token)\n user_key = ndb.Key(cls, user_id)\n # Use get_multi() to save a RPC call.\n valid_token, user = ndb.get_multi([token_key, user_key])\n if valid_token and user:\n timestamp = int(time.mktime(valid_token.created.timetuple()))\n return user, timestamp\n \n return None, None\n\nclass UserState(ndb.Model):\n # UID = ndb.IntegerProperty()\n userStateDict = ndb.JsonProperty()\n#############################\n \n# def hack():\n# userState = UserState(id=1)\n# userState.userStateDict = {}\n# userState.put()\n \n # gqlString = \"SELECT * FROM TPStore_v2\"\n # \n # resultList, cursor, hasMore = runQuery(gqlString, 1000)\n # \n # for item in resultList:\n # item.ordering = 1\n # \n # item.put()\n \ndef getUserStateDict(userID):\n userState = UserState.get_by_id(userID)\n \n if userState:\n return userState.userStateDict\n else:\n return {}\n \n## QUERY\ndef runQuery(gqlStringQuery, fetchAmount, idOnly=False, cursor=None, projection=None):\n\treturnQuery = ndb.gql(gqlStringQuery)\n\t\n\t#if fetchAmount > 1:\n\tif cursor:\n\t\tresultList, cursor, hasMore = returnQuery.fetch_page(fetchAmount, keys_only=idOnly, start_cursor=cursor, projection=projection)\n\telse:\n\t\tresultList, cursor, hasMore = returnQuery.fetch_page(fetchAmount, keys_only=idOnly, projection=projection)\n\t\n\treturn resultList, cursor, hasMore\n\n\ndef getTPList():\n gqlString = \"SELECT * FROM TPStore_v2 WHERE NID=1\"\n \n resultList, cursor, hasMore = runQuery(gqlString, 1000)\n return resultList\n\ndef insertTP(PID, dataDictText):\n putList = []\n TPItem = getTP(PID)\n \n if TPItem == None:\n TPItem = TPStore()\n TPItem.PID = PID\n \n TPItem.rawData = dataDictText\n \n putList.append(TPItem)\n ndb.put_multi(putList)\n\n###V2\ndef getNextPID_v2():\n counter = Counter.get_by_id(\"0\")\n nextPID = counter.nextPID\n counter.nextPID = nextPID + 1\n counter.put()\n \n return nextPID\n\ndef getNextNID(PID):\n gqlString = \"SELECT * FROM TPStore_v2 WHERE PID = %s ORDER BY NID desc\" % (PID)\n \n resultList, cursor, hasMore = runQuery(gqlString, 1) \n \n lastNID = 1\n for item in resultList:\n lastNID = item.NID\n \n return lastNID + 1\n\ndef parseToJson(item):\n responseItem = {\"id\": item.NID,\n \"status\": item.status,\n \"label\": item.label,\n \"parent_path\": item.parentPath,\n \"ordering\": item.ordering}\n \n return responseItem\n\ndef resolveTiles(PID, tileIDList):\n returnData = []\n \n for tileStoreID in map(lambda e: str(PID) + \"_\" + str(e), tileIDList):\n tileItem = TPStore_v2.get_by_id(tileStoreID)\n returnData.append(parseToJson(tileItem))\n \n return returnData\n\ndef getTP_v2(PID, tileID):\n gqlString = \"SELECT * FROM TPStore_v2 WHERE PID=%s AND parentPath=%s\" % (PID, tileID)\n \n resultList, cursor, hasMore = runQuery(gqlString, 1000) \n \n if len(resultList) > 0:\n return map(parseToJson, resultList)\n else:\n return None\n\ndef insertTP_v2(projectID, nodeID, parentID=None):\n uniqueS = \"%s_%s\" % (projectID, nodeID)\n TPItem = TPStore_v2(id=uniqueS)\n \n TPItem.PID = projectID\n TPItem.NID = nodeID\n TPItem.ordering = nodeID\n \n TPItem.status = 0\n TPItem.label = \"\"\n \n if parentID:\n uniqueS = \"%s_%s\" % (projectID, parentID)\n parentNode = TPStore_v2.get_by_id(uniqueS)\n \n # TPItem.stepCounter = parentNode.stepCounter + 1\n itemParentPath = []\n itemParentPath.extend(parentNode.parentPath)\n itemParentPath.append(nodeID)\n \n TPItem.parentPath = itemParentPath\n else:\n # TPItem.stepCounter = 1\n TPItem.parentPath = [nodeID]\n \n TPItem.put()\n \ndef modifyTP(projectID, nodeID, nodeData):\n uniqueS = \"%s_%s\" % (projectID, nodeID)\n TPItem = TPStore_v2.get_by_id(uniqueS)\n \n for key, value in nodeData.items():\n if key == \"parent_path\":\n key = \"parentPath\"\n \n if hasattr(TPItem, key):\n try:\n setattr(TPItem, key, value)\n except:\n raise ValueError(value)\n \n TPItem.put()\n \n return parseToJson(TPItem)\n\ndef removeTP(projectID, nodeID):\n uniqueS = \"%s_%s\" % (projectID, nodeID)\n TPItem = TPStore_v2.get_by_id(uniqueS)\n \n TPItem.key.delete()","sub_path":"kurohailo/DSStructure.py","file_name":"DSStructure.py","file_ext":"py","file_size_in_byte":5980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"623273606","text":"inp = [int(a) for a in input().rstrip().split()]\r\n\r\nsmallest = 0\r\n\r\ndef gcd(a, b): \r\n if a == 0 : \r\n return b \r\n \r\n return gcd(b%a, a)\r\n\r\na = inp[0]\r\nb = inp[1]\r\n\r\nwhile a != 0:\r\n a, b = b%a, a\r\n\r\nif inp[0]*inp[1]/b <= inp[2]:\r\n print(\"yes\")\r\nelse:\r\n print(\"no\")\r\n","sub_path":"DasBlinkenlights.py","file_name":"DasBlinkenlights.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"276635758","text":"'''\nUSAGE: stats.py
Сайт учреждения\"\n \"
Доп. информация: {}\".format(hospital.name,\n hospital.address,\n hospital.phone,\n hospital.doctor,\n hospital.site,\n hospital.info))\n h['name'] = hospital.name\n h['district'] = hospital.district_id\n h['types'] = hospital.type_of.split(',')\n markers.append(h)\n return markers\n\n\ndef _get_selected_markers():\n markers = []\n hospitals = _get_all_hospitals()\n for hospital in hospitals:\n h = dict()\n # Получаем долготу(lng) и широту(lat)\n h['lng'], h['lat'] = hospital.coordinates.split('; ')\n h['infobox'] = (\"{}
Адрес: {}\"\n \"
Телефон: {}\"\n \"
ФИО главного врача: {}\"\n \"
Сайт учреждения\"\n \"
Доп. информация: {}\".format(hospital.name,\n hospital.address,\n hospital.phone,\n hospital.doctor,\n hospital.site,\n hospital.info))\n h['name'] = hospital.name\n markers.append(h)\n return markers\n\nred_heat_map = \"\"\"FFE6E6\nFFD8D8\nFFC5C5\nFFB0B0\nFF9A9A\nFF9A9A\nFF6868\nFF4949\nFE2C2C\nFF1212\nCB3333\nA62929\n7B1818\"\"\"\n\n\ndef _get_polygons(criteria):\n polygons = []\n districts = _get_all_districts()\n map_colors = dict()\n legend = OrderedDict()\n h = red_heat_map.split('\\n')\n log.debug(criteria)\n _s = sorted(criteria, key=criteria.get)\n\n for i in range(0, len(_s), 3):\n legend[h[int(i/3)]] = \"{} {}\".format(int(round(criteria[_s[i]], 0)), int(round(criteria[_s[i+2]], 0)))\n map_colors[_s[i]], map_colors[_s[i+1]], map_colors[_s[i+2]] = h[int(i/3)], h[int(i/3)], h[int(i/3)]\n log.debug(legend)\n\n for district in districts:\n pol = {\n 'stroke_color': '#0AB0DE',\n 'stroke_opacity': 1.0,\n 'stroke_weight': 3,\n 'fill_color': map_colors[district.id],\n 'fill_opacity': .5,\n 'path': [],\n 'name': district.name\n }\n coord = ast.literal_eval(district.coordinates)\n for c in coord:\n pol['path'].append([c[1], c[0]])\n\n polygons.append(pol)\n\n return polygons, legend\n\n\nif __name__ == '__main__':\n from os import path\n import os\n\n extra_dirs = ['static', 'templates']\n extra_files = extra_dirs[:]\n for extra_dir in extra_dirs:\n for dirname, dirs, files in os.walk(extra_dir):\n for filename in files:\n filename = path.join(dirname, filename)\n if path.isfile(filename):\n extra_files.append(filename)\n app.run(host='0.0.0.0', extra_files=extra_files, debug=True,\n port=int(os.environ.get('PORT', 5000)))\n","sub_path":"web/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":31480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"236358579","text":"# -*- coding: utf-8 -*-\n###############################################################################\n# Copyright (c), Forschungszentrum Jülich GmbH, IAS-1/PGI-1, Germany. #\n# All rights reserved. #\n# This file is part of the Masci-tools package. #\n# (Material science tools) #\n# #\n# The code is hosted on GitHub at https://github.com/judftteam/masci-tools. #\n# For further information on the license, see the LICENSE.txt file. #\n# For further information please visit http://judft.de/. #\n# #\n###############################################################################\n\"\"\"\nThis module defines decorators for the ParseTasks class to make extending/modifying the parser\nmore convenient\n\nUp till now 3 decorators are defined:\n - ```register_migration``` marks a function of making backwards incompatible changes\n to the parsing tasks\n - ```register_parsing_function``` gives a mappimg between available parsing functions\n and the keywords in the parsing tasks\n - ```conversion_function``` makes the decorated function available to be called easily\n after a certain parsing task has occured\n\"\"\"\nfrom masci_tools.util.parse_tasks import ParseTasks\nfrom functools import wraps\n\n\ndef register_migration(base_version, target_version):\n \"\"\"\n Decorator to add migration for task definition dictionary to the ParseTasks class\n The function should only take the dict of task definitions as an argument\n\n :param base_version: str of the version, from which the migration starts\n :param target_version: str or list of str with the versions that work after\n the migration has been performed\n\n \"\"\"\n\n def migration_decorator(func):\n \"\"\"\n Return decorated ParseTasks object with _migrations dict attribute\n Here all registered migrations are inserted\n \"\"\"\n\n @wraps(func)\n def migration(*args):\n \"\"\"Decorator for migration function\"\"\"\n return func(*args)\n\n if not hasattr(ParseTasks, '_migrations'):\n ParseTasks._migrations = {} # pylint: disable=protected-access\n if not base_version in ParseTasks._migrations:\n ParseTasks._migrations[base_version] = {}\n\n target_version_list = target_version\n if not isinstance(target_version_list, list):\n target_version_list = [target_version_list]\n for valid_version in target_version_list:\n ParseTasks._migrations[base_version][valid_version] = migration # pylint: disable=protected-access\n\n for valid_version_2 in target_version_list:\n if valid_version == valid_version_2:\n continue\n if int(valid_version.split('.')[1]) > int(valid_version_2.split('.')[1]):\n if valid_version not in ParseTasks._migrations:\n ParseTasks._migrations[valid_version] = {}\n ParseTasks._migrations[valid_version][valid_version_2] = 'compatible'\n else:\n if valid_version_2 not in ParseTasks._migrations:\n ParseTasks._migrations[valid_version_2] = {}\n ParseTasks._migrations[valid_version_2][valid_version] = 'compatible'\n\n return migration\n\n return migration_decorator\n\n\ndef register_parsing_function(parse_type_name, all_attribs_keys=False):\n \"\"\"\n Decorator to add parse type for task definition dictionary.\n\n :param parse_type_name: str, the function can be selected in task defintions\n via this string\n :param all_attribs_keys: bool, if True the arguments for parsing multiple attributes\n are valid\n\n The decorated function has to have the following arguments:\n :param node: etree Element, on which to execute the xpath evaluations\n :param schema_dict: dict, containing all the path information and more\n :param name: str, name of the tag/attribute\n :param parser_info_out: dict, with warnings, info, errors, ...\n :param kwargs: here all other keyword arguments are collected\n\n \"\"\"\n\n def parse_type_decorator(func):\n \"\"\"\n Return decorated ParseTasks object with _parse_functions dict attribute\n Here all registered migrations are inserted\n \"\"\"\n\n @wraps(func)\n def parse_type(*args, **kwargs):\n \"\"\"Decorator for parse_type function\"\"\"\n return func(*args, **kwargs)\n\n if not hasattr(ParseTasks, '_parse_functions'):\n ParseTasks._parse_functions = {} # pylint: disable=protected-access\n ParseTasks._all_attribs_function = set()\n\n ParseTasks._parse_functions[parse_type_name] = parse_type # pylint: disable=protected-access\n if all_attribs_keys:\n ParseTasks._all_attribs_function.add(parse_type_name)\n\n return parse_type\n\n return parse_type_decorator\n\n\ndef conversion_function(func):\n \"\"\"\n Marks a function as a conversion function, which can be called after\n performing a parsing task. The function can be specified via the _conversions\n control key in the task definitions.\n\n A conversion function has to have the following arguments:\n :param out_dict: dict with the previously parsed information\n :param parser_info_out: dict, with warnings, info, errors, ...\n\n and return only the modified output dict\n \"\"\"\n\n @wraps(func)\n def convert_func(*args, **kwargs):\n \"\"\"Decorator for parse_type function\"\"\"\n return func(*args, **kwargs)\n\n if not hasattr(ParseTasks, '_conversion_functions'):\n ParseTasks._conversion_functions = {} # pylint: disable=protected-access\n\n ParseTasks._conversion_functions[func.__name__] = convert_func # pylint: disable=protected-access\n\n return convert_func\n","sub_path":"masci_tools/util/parse_tasks_decorators.py","file_name":"parse_tasks_decorators.py","file_ext":"py","file_size_in_byte":6153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"90442136","text":"#-*- coding: utf-8 -*-\n\"\"\"Signal handlers for shop_simplenotifications.\"\"\"\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.template import loader, RequestContext\n\nfrom shop.order_signals import confirmed, completed\nfrom shop.util.address import get_billing_address_from_request\n\ndef subject(template_name):\n \"\"\"Returns the email subject based on the subject template.\"\"\"\n subject = loader.render_to_string(template_name, self.get_context())\n return ''.join(subject.splitlines())\n\ndef confirmed_email_notification(sender, **kwargs):\n \"\"\"\n Sends an email notification to the shop owner when a new order is\n completed.\n \"\"\"\n subject_template_name = 'shop_simplenotifications/confirmed_subject.txt'\n body_template_name = 'shop_simplenotifications/confirmed_body.txt'\n request = kwargs.get('request')\n order = kwargs.get('order')\n subject = loader.render_to_string(\n subject_template_name,\n RequestContext(request, {'order': order})\n )\n subject = subject.join(subject.splitlines())\n body = loader.render_to_string(\n body_template_name,\n RequestContext(request, {'order': order})\n )\n from_email = getattr(settings, 'SN_FROM_EMAIL', settings.DEFAULT_FROM_EMAIL)\n owners = getattr(settings, 'SN_OWNERS', settings.ADMINS)\n send_mail(subject, body, from_email, [owner[1] for owner in owners], fail_silently=False)\n\nif 'confirmed' in getattr(settings, 'SN_BIND_NEW_ORDER_NOTIFICATION_TO', ['confirmed']): \n confirmed.connect(confirmed_email_notification)\nif 'completed' in getattr(settings, 'SN_BIND_NEW_ORDER_NOTIFICATION_TO', []): \n completed.connect(confirmed_email_notification)\n\n\ndef payment_instructions_email_notification(sender, **kwargs):\n \"\"\"\n Sends an email with payment instructions to the customer once and order is\n placed.\n \"\"\"\n subject_template_name = 'shop_simplenotifications/payment_instructions_subject.txt'\n body_template_name = 'shop_simplenotifications/payment_instructions_body.txt'\n \n request = kwargs.get('request')\n order = kwargs.get('order')\n \n emails = []\n if order.user and order.user.email: \n emails.append(order.user.email)\n if request and get_billing_address_from_request(request):\n address = get_billing_address_from_request(request)\n if hasattr(address, 'email'):\n emails.append(address.email)\n emails.append(address.email)\n \n emails = list(set(emails)) # removes duplicated entries\n if emails:\n subject = loader.render_to_string(\n subject_template_name,\n RequestContext(request, {'order': order})\n )\n subject = subject.join(subject.splitlines())\n body = loader.render_to_string(\n body_template_name,\n RequestContext(request, {'order': order})\n )\n from_email = getattr(settings, 'SN_FROM_EMAIL', settings.DEFAULT_FROM_EMAIL)\n send_mail(subject, body, from_email, emails, fail_silently=False)\n\nif 'confirmed' in getattr(settings, 'SN_BIND_PAYMENT_INSTRUCTION_TO', ['confirmed']):\n confirmed.connect(payment_instructions_email_notification)\nif 'completed' in getattr(settings, 'SN_BIND_PAYMENT_INSTRUCTION_TO', []):\n completed.connect(payment_instructions_email_notification)\n\n\n\n","sub_path":"shop_simplenotifications/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"190697085","text":"import collections, importlib, subprocess, time, random, threading, os\nfrom pathlib import Path\n\nwith open(\"Dockerfile\", \"w\") as dockerfile:\n dockerfile.write(\"FROM spysravan/codeserver \\nRUN apt update && apt install unzip -y\\n\")\n\ntechs = []\nfor i, f in enumerate(Path('catalog').glob('**/*.py')):\n techs.append(str(f)[:-3])\n print(str(i) + \": \" + f.name[:-3])\n\ntech_inps = input('Enter the technologies: ')\n\nprocess_output = ''\ndef get_output(process):\n global process_output\n term_wid = int(os.popen('stty size', 'r').read().split()[1]) - 20\n while process.poll() is None:\n process_output = process.stdout.readline().decode(\"utf-8\")[:term_wid].strip().replace('\\n','').replace('\\\\','')\n time.sleep(0.1) \n\ndef build_docker(n = 6):\n global process_output\n txt_colors = ['\\033[95m','\\033[94m','\\033[96m','\\033[92m','\\033[93m','\\033[91m','\\033[0m']\n process = subprocess.Popen(['bash', '-c', 'docker build -t custom .'],stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n threading.Thread(target=get_output, args=(process,)).start()\n while process.poll() is None:\n points = list(range(1,n)) + list(range(1,n-1)[::-1]) + list(range(2,n)) + list(range(1,n-1)[::-1])\n spaces = [0]*(n-1) + list(range(1,n-1)) + list(range(n-2)[::-1]) + [0] * (n-2)\n e_spaces = list(range(1,n-1)[::-1]) + [0] * (n+3) + list(range(1,n-1))\n for s,p,e in zip(spaces,points,e_spaces):\n print('Installing ' + random.choice(txt_colors) + ' '*s + '.'*p + ' '*e + '\\033[0m ' + process_output, end='\\r')\n time.sleep(0.1)\n return process.returncode, process.communicate()\n\nfor i in tech_inps.split(','):\n try:\n importlib.import_module(techs[int(i)].replace('/', '.'))\n res_code, stdouterr = build_docker()\n if res_code == 0:\n print('\\033[1m \\033[92m Successfully installed \\033[0m')\n else:\n print(stdouterr[0][-200:])\n print(stdouterr[0][-200:])\n except:\n pass\n\n\n\nqstns = []\nfor i, f in enumerate(Path('qstns').glob('**/*.zip')):\n qstns.append(str(f))\n print(str(i) + \": \" + f.name[:-4])\n\nqstn_no = int(input('Enter question number: ') or 0)\nwith open(\"Dockerfile\", \"a\") as dockerfile:\n dockerfile.write(\"ADD \" + qstns[qstn_no] + \" /root/challenge.zip \\n\")\n dockerfile.write(\"RUN cd /root && unzip challenge.zip && rm challenge.zip \\n\")\nbuild_docker()\n\ninp_run = input(\"\\nDo you want to run the docker image (y/n): \") or 'n'\nif inp_run == 'y':\n process = subprocess.Popen(['bash', '-c', 'docker run -d -p 80:80 custom'],stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n print(\"docker running at http://0.0.0.0:80\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"358160432","text":"from pydm import Display\nfrom PyQt5 import QtGui, QtCore, QtWidgets \nfrom PyQt5.QtGui import QPainter, QColor, QBrush, QPen \nfrom PyQt5.QtCore import Qt, QObject\nimport epics\nfrom epics import caget, caput\nfrom PyQt5.QtWidgets import (QWidgetItem, QCheckBox, QPushButton, QLineEdit,\n QGroupBox, QHBoxLayout, QMessageBox, QWidget,\n QLabel, QFrame, QComboBox)\nfrom pydm.widgets import PyDMDrawingRectangle, PyDMLabel\n\n\nclass CavityWithStatusBar(Display):\n\n\tdef ui_filename(self):\n\t\treturn 'CavityWithStatusBar.ui'\t\n\n\n\tdef __init__(self, parent=None, args=None):\n\t\tsuper(CavityWithStatusBar, self).__init__(parent=parent, args=args)\n\n\t\tself.ui.EmbeddedCavity.loadWhenShown = False\n\t\tself.ui.EmbeddedCavity.setStyleSheet(\"background-color:black\\n\")\n\t\t\n\t\trectangleList = self.ui.EmbeddedCavity.findChildren(PyDMDrawingRectangle)\n\t\tstatusbar = rectangleList[0]\t\n\t\t\n\t\tlabelList = self.ui.EmbeddedCavity.findChildren(PyDMLabel)\n\t\tTLC_label = labelList[0]\n#\t\tTLC_label.setText(\"Fault\")\n\t\t\n\n\n\t\t# PARAMETERS\n\t\tself.PV = ''\n\t\tself.Test_PV = 'SIOC:SYS0:ML07:AO010'\n\t\tself.value = caget(self.Test_PV)\n\t\t\n\t\t# BUTTON CONNECTIONS (send signal and then call a function)\n\t\t# Show status of cavity; green bar if on frequency (aka PV = 1.0)\n\t\tself.ui.cmOFF.PV = self.Test_PV\t\t\n\t\tself.ui.cmOFF.value = 0\n\t\tself.ui.cmOFF.embeddedStatusbar = statusbar\n\t\tself.ui.cmOFF.toggled.connect(self.change_PV)\n\n\t\tself.ui.cmON.PV = self.Test_PV\n\t\tself.ui.cmON.value = 1\n\t\tself.ui.cmON.embeddedStatusbar = statusbar\n\t\tself.ui.cmON.toggled.connect(self.change_PV)\n\n\n\t\n\t# change pv value with caput command\n\tdef change_PV(self):\n\t\tradioButton = self.sender() \n\t\tif radioButton.isChecked():\n\t\t\tcaput(radioButton.PV, radioButton.value)\t\n\t\tself.statusBarColor(radioButton.embeddedStatusbar)\n\t\t\n\n# Change the color of status bar via .setStyleSheet\n\tdef statusBarColor(self, statusbar):\n\t\tgreen = QColor(0,255,0)\n\t\tred = QColor(255,54,14)\n\t\tValue = caget(self.Test_PV)\n\t\tif Value == 1.0:\n\t\t\tstatusbar.brush.setColor(green)\n\t\t\tstatusbar.update()\n\t\telse:\n\t\t\tstatusbar.brush.setColor(red)\n\t\t\tstatusbar.update()\n\n\t\t\n\t\t\n","sub_path":"CodeTests/CavityWithStatusBar.py","file_name":"CavityWithStatusBar.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"25494991","text":"\n# coding: utf-8\n\n# In[43]:\n\n\nfrom pyaudio import PyAudio, paInt16 \nimport numpy as np \nfrom datetime import datetime \nimport wave\nimport os\nimport wave\nimport contextlib\nimport MySQLdb\nimport speech_recognition as sr\nimport time\nimport os\nimport pyaudio\nimport wave \nget_ipython().magic('load_ext autoreload')\nget_ipython().magic('autoreload 2')\nfrom keras.models import load_model\nfrom preprocess import *\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D\nfrom keras.utils import to_categorical\nfrom pydub import AudioSegment\nimport MySQLdb\nfeature_dim_2 = 11\nfeature_dim_1 = 20\nchannel = 1\nepochs = 50\nbatch_size = 100\nverbose = 1\nnum_classes = 2\nclass recoder:\n NUM_SAMPLES = 2000 #pyaudio内置缓冲大小\n SAMPLING_RATE = 8000 #取样频率\n LEVEL = 500 #声音保存的阈值\n COUNT_NUM = 20 #NUM_SAMPLES个取样之内出现COUNT_NUM个大于LEVEL的取样则记录声音\n SAVE_LENGTH = 8 #声音记录的最小长度:SAVE_LENGTH * NUM_SAMPLES 个取样\n TIME_COUNT = 10 #录音时间,单位s\n\n Voice_String = []\n \n def savewav(self,filename):\n wf = wave.open(filename, 'wb') \n wf.setnchannels(1) \n wf.setsampwidth(2) \n wf.setframerate(self.SAMPLING_RATE) \n wf.writeframes(np.array(self.Voice_String).tostring()) \n # wf.writeframes(self.Voice_String.decode())\n wf.close() \n\n def recoder(self):\n pa = PyAudio() \n stream = pa.open(format=paInt16, channels=1, rate=self.SAMPLING_RATE, input=True, \n frames_per_buffer=self.NUM_SAMPLES) \n save_count = 0 \n save_buffer = [] \n time_count = self.TIME_COUNT\n a = datetime.now()\n prevTime = a.second\n\n while True:\n #time_count -= 1\n \n # print time_count\n # 读入NUM_SAMPLES个取样\n string_audio_data = stream.read(self.NUM_SAMPLES) \n # 将读入的数据转换为数组\n audio_data = np.fromstring(string_audio_data, dtype=np.short)\n # 计算大于LEVEL的取样的个数\n large_sample_count = np.sum( audio_data > self.LEVEL )\n #print(np.max(audio_data))\n # 如果个数大于COUNT_NUM,则至少保存SAVE_LENGTH个块\n if large_sample_count > self.COUNT_NUM:\n save_count = self.SAVE_LENGTH \n else: \n save_count -= 1\n\n if save_count < 0:\n save_count = 0 \n\n if save_count > 0 : \n # 将要保存的数据存放到save_buffer中\n #print save_count > 0 and time_count >0\n save_buffer.append( string_audio_data ) \n else: \n #print save_buffer\n # 将save_buffer中的数据写入WAV文件,WAV文件的文件名是保存的时刻\n #print \"debug\"\n if len(save_buffer) > 0 : \n self.Voice_String = save_buffer\n save_buffer = [] \n print(\"Recode a piece of voice successfully!\")\n return True\n a = datetime.now()\n nowTime = a.second\n #if time_count==0: \n N = (nowTime%10)-(prevTime%10)\n if N>=2 or N==-8: \n if len(save_buffer)>1:\n self.Voice_String = save_buffer\n save_buffer = [] \n print(\"Recode a piece of voice successfully!\")\n prevTime = a.second\n return True\n else:\n return False\n\ndef get_wav_time(wav_path):\n '''\n 获取音频文件是时长\n :param wav_path: 音频路径\n :return: 音频时长 (单位秒)\n '''\n with contextlib.closing(wave.open('C:\\\\Users\\\\Kelly\\\\recordTest\\\\'+ wav_path, 'r')) as f:\n frames = f.getnframes()\n rate = f.getframerate()\n duration = frames / float(rate)\n return duration\n\ndef predict(filepath, model):\n sample = wav2mfcc(filepath)\n sample_reshaped = sample.reshape(1, feature_dim_1, feature_dim_2, channel)\n return get_labels()[0][\n np.argmax(model.predict(sample_reshaped))\n ]\ndef AudioToText(file_name):\n r = speech_recognition.Recognizer()\n with speech_recognition.AudioFile(file_name) as source: \n audio = r.record(source)\n try:\n Text = r.recognize_google(audio, language=\"zh-TW\") \n except sr.UnknownValueError:\n Text = \"無法翻譯\"\n except sr.RequestError as e:\n Text = \"無法翻譯{0}\".format(e)\n return Text\n \nif __name__ == \"__main__\":\n model = load_model('my_model.h5')\n list= []\n list2= []\n ret= []\n rm = []\n rm2=[]\n fi =[]\n LIMITCOUNT = 10\n filepath = 'C:\\\\Users\\\\Kelly\\\\recordTest'\n while (1):\n r = recoder()\n r.recoder()\n x = datetime.now()\n strx = str(x.year)+\"-\"+str(x.month)+\"-\"+str(x.day)+\"-\"+str(x.hour)+\"-\"+str(x.minute)+\"-\"+str(x.second)\n print(strx)\n r.savewav(\"C:\\\\Users\\\\Kelly\\\\recordTest\\\\\"+strx+\".wav\")\n LIMITCOUNT -= 1\n for root, dirs, files in os.walk(filepath):\n for f in files:\n list.append(f)\n for i in list:\n if not i in list2:\n ret.append(str(get_wav_time(i)))\n list2.append(i)\n for i in list2:\n for k,v in enumerate(ret):\n if (v==\"0.0\" or v==\"0.25\"):\n rm.append(k)\n for i in rm:\n if not i in rm2:\n rm2.append(i)\n os.remove(\"C:\\\\Users\\\\Kelly\\\\recordTest\\\\\"+list2[i]) \n if len([lists for lists in os.listdir(filepath) if os.path.isfile(os.path.join(filepath, lists))]) == 10:\n for root, dirs, files in os.walk(filepath):\n for f in files:\n Text = AudioToText(\"C:/Users/Kelly/recordtest/\"+f)\n if(Text !='無法翻譯'):\n os.remove(\"C:\\\\Users\\\\Kelly\\\\recordTest\\\\\"+f)\n for root, dirs, files in os.walk(filepath):\n for f in files:\n sound = AudioSegment.from_file(\"C:/Users/Kelly/recordtest/\"+f)\n loudness = sound.dBFS\n loudness1 = sound.rms\n if(loudness<-45 and loudness1<200):\n os.remove(\"C:\\\\Users\\\\Kelly\\\\recordTest\\\\\"+f)\n for root, dirs, files in os.walk(filepath):\n for f in files:\n predict2=predict((\"C:\\\\Users\\\\Kelly\\\\recordTest\\\\\"+f),model=model)\n if(predict2!='cough'):\n print(predict2)\n os.remove(\"C:\\\\Users\\\\Kelly\\\\recordTest\\\\\"+f)\n else:\n fi.append(f.split('.')[0])\n conn=MySQLdb.connect(host=\"localhost\",user=\"root\", passwd=\"abc0963470417\", db=\"cough\", charset=\"utf8\")\n cursor=conn.cursor() \n for i in range(len(fi)):\n SQL = \"INSERT INTO cough_time(time)VALUES('\"+fi[i]+\"')\"\n cursor.execute(SQL)\n conn.commit()\n conn.close()\n os.remove(\"C:\\\\Users\\\\Kelly\\\\recordTest\\\\\"+f)\n del fi[:]\n\n\n# In[42]:\n\n\nprint(fi)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"CoughDetect.py","file_name":"CoughDetect.py","file_ext":"py","file_size_in_byte":7533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"232303811","text":"#!/usr/bin/env python\n#coding:utf-8\n#Created by fsrm\n\nimport sys\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\nimport os\n\ndef main():\n import pika\n connection = pika.BlockingConnection(pika.ConnectionParameters('rabbit'))\n channel = connection.channel()\n channel.queue_declare(queue='task_queue', durable=True)\n\n\n message= ' '.join(sys.argv[1:]) or 'hello!'\n channel.basic_publish(exchange='',\n routing_key='task_queue',\n body=message,\n #properties=pika.BasicProperties(\n # delivery_mode = 2\n # )\n )\n print(\" [x] Sent %r\" % message)\n connection.close()\n\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"scripts/rabbitmq/test/queue_producer.py","file_name":"queue_producer.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"183798196","text":"class Solution(object):\n def letterCombinations(self, digits):\n \"\"\"\n :type digits: str\n :rtype: List[str]\n \"\"\"\n digitalMap = [\"\", \"\", \"abc\", \"def\", \"ghi\", \"jkl\", \"mno\", \"pqrs\", \"tuv\", \"wxyz\"]\n ans = []\n for c in digits:\n mappedChars = digitalMap[ord(c) - ord('0')]\n if (len(mappedChars) > 0):\n if len(ans) > 0:\n ans = [x + y for x in ans for y in mappedChars]\n else:\n ans = [y for y in mappedChars]\n\n return ans\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.letterCombinations(\"5103668950\"))","sub_path":"letterCombinations.py","file_name":"letterCombinations.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"358443615","text":"import pygame\n\npygame.init() # 초기화 (반드시 필요)\n\n# 화면 크기 설정\nscreen_width = 480 # width\nscreen_height = 640 # height\nscreen = pygame.display.set_mode((screen_width, screen_height))\n\n# 화면 타이틀 설정\npygame.display.set_caption(\"웅겹살의 오락실게임\") # 화면설정 screen변수로 선언\n\n# FPS\nclock = pygame.time.Clock()\n\n# 배경 이미지 불러오기\nbackground = pygame.image.load(\"C:/PythonWorkspace/pygame_basic/background.png\")\n\n# 캐릭터(sprite) 불러오기\ncharacter = pygame.image.load(\"C:/PythonWorkspace/pygame_basic/character.png\")\ncharacter_size = character.get_rect().size # 이미지 크기를 구해옴\ncharacter_width = character_size[0] # 캐릭터의 가로크기\ncharacter_height = character_size[1] # 캐릭터의 세로크기\ncharacter_x_pos = (screen_width / 2) - (character_width / 2) # 화면 가로의 중간위치\ncharacter_y_pos = screen_height - character_height # 화면 세로 가장 하단\n\n# 이동할 좌표\nto_x = 0\nto_y = 0\n\n# 이동 속도\ncharacter_speed = 0.6\n\n# 이벤트 루프\nrunning = True # 게임이 진행중인가?\nwhile running:\n dt = clock.tick(60) # 게임화면의 초당 프레임 수를 설정\n \n for event in pygame.event.get(): # 어떤 이벤트가 발생하였는가?\n if event.type == pygame.QUIT: # 창이 닫히는 이벤트가 발생하였는가?\n running = False # 게임이 진행중이 아님\n\n if event.type == pygame.KEYDOWN: # 키가 눌러졌는지 확인\n if event.key == pygame.K_LEFT: # 캐릭터를 왼쪽으로\n to_x -= character_speed # to_x = to_x - 5\n elif event.key == pygame.K_RIGHT: # 캐릭터를 오른쪽으로\n to_x += character_speed\n elif event.key == pygame.K_UP: # 캐릭터를 위로\n to_y -= character_speed\n elif event.key == pygame.K_DOWN: # 캐릭터를 아래로\n to_y += character_speed\n\n if event.type == pygame.KEYUP: # 방향키를 떼면 멈춤\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n to_x = 0\n elif event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n to_y = 0\n\n # 프레임별로 바뀌는 값 계산\n character_x_pos += to_x * dt\n character_y_pos += to_y * dt\n\n # 가로 경계값 처리\n if character_x_pos < 0:\n character_x_pos = 0\n elif character_x_pos > screen_width - character_width:\n character_x_pos = screen_width - character_width\n\n # 세로 경계값 처리\n if character_y_pos < 0:\n character_y_pos = 0\n elif character_y_pos > screen_height - character_height:\n character_y_pos = screen_height - character_height\n\n\n screen.blit(background, (0, 0)) # 배경 그리기\n\n screen.blit(character, (character_x_pos, character_y_pos))\n\n pygame.display.update() # 게임화면을 다시 그리기\n\n# pygame 종료\npygame.quit()","sub_path":"pygame_basic/5_frame_per_second.py","file_name":"5_frame_per_second.py","file_ext":"py","file_size_in_byte":3059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"194713148","text":"import tldextract\r\nfrom difflib import SequenceMatcher\r\nimport pyfiglet\r\nfrom time import sleep\r\nimport whois #pip install python-whois, windows: install whois in system32\r\n\r\ndomain = input(\"Enter your Domain: \")\r\ndomain = tldextract.extract(domain)\r\n#Output of extract: tupel with subdomain, domain and suffix, access via .Operator\r\ndomain_raw = domain.domain\r\ntld = domain.suffix\r\n\r\ncreated_domains = set() \r\nsimilar_tlds = set()\r\navailable_domains = set() \r\nregistered_domains = set()\r\nunregistered_domains = set()\r\n\r\ndef create_tlds():\r\n #change to Path of your Domain_Extensions File\r\n domain_list = open(\"C:/Users/chris/AppData/Local/Programs/Python/Python37-32/Scripts/Domain Phisher/Domain_Extensions.txt\", \"r\")\r\n #List of domain Extensions from: https://data.iana.org/TLD/tlds-alpha-by-domain.txt\r\n for domain in domain_list:\r\n new_domain = domain.lower()\r\n s = SequenceMatcher(None, tld, new_domain)\r\n similarity = s.ratio()\r\n #For Testing: 0.6 as Similarity Level, change according to your needs or make it editable by the User\r\n if similarity > 0.6:\r\n similar_tlds.add(new_domain)\r\n\r\ndef replace_char():\r\n if \"o\" in domain_raw:\r\n replaced_o = domain_raw.replace(\"o\", \"0\")\r\n created_domains.add(replaced_o) \r\n if \"l\" in domain_raw:\r\n replaced_l = domain_raw.replace(\"l\", \"1\")\r\n created_domains.add(replaced_l) \r\n if \"d\" in domain_raw:\r\n replaced_d = domain_raw.replace(\"d\", \"cl\")\r\n created_domains.add(replaced_d)\r\n return\r\n\r\ndef double_char():\r\n chars_to_double = [\"o\", \"l\", \"e\" ]\r\n for char in chars_to_double:\r\n doubled_char = char + char\r\n if char in domain_raw:\r\n domain_doubled = domain_raw.replace(char, doubled_char, 1)\r\n created_domains.add(domain_doubled)\r\n else:\r\n pass\r\n return\r\n\r\n#append Functions could be refactored to one function\r\n#less code, better to read\r\n#but with several functions the User has more controll over the Outpu\r\n \r\ndef append_it():\r\n it_list = [\"it\", \"servicedesk\", \"helpdesk\", \"support\", \"admin\"]\r\n for word in it_list:\r\n created_domains.add(word+domain_raw)\r\n created_domains.add(word+\"-\"+domain_raw)\r\n created_domains.add(domain_raw+word)\r\n created_domains.add(domain_raw+\"-\"+word)\r\n return\r\n\r\ndef append_customer():\r\n customer_list = [\"customer\", \"customerservice\", \"help\", \"info\", \"client\", \"consumer\"]\r\n for word in customer_list:\r\n created_domains.add(word+domain_raw)\r\n created_domains.add(word+\"-\"+domain_raw)\r\n created_domains.add(domain_raw+word)\r\n created_domains.add(domain_raw+\"-\"+word)\r\n return\r\n\r\ndef append_billing():\r\n billing_list = [\"bill\", \"billing\", \"invoice\", \"account\", \"check\", \"note\", \"report\"]\r\n for word in billing_list:\r\n created_domains.add(word+domain_raw)\r\n created_domains.add(word+\"-\"+domain_raw)\r\n created_domains.add(domain_raw+word)\r\n created_domains.add(domain_raw+\"-\"+word)\r\n return\r\n\r\ndef append_numbers():\r\n #1 and 11 are personal choices, 24 is often used as part of domains (e.g. scout24.de, immoscout24.de)\r\n #247 indicates that Website is reachable 24 hours, 7 days a week\r\n #365 indicates that Website is reachable 365 days a year\r\n number_list = [\"1\",\"11\",\"24\",\"247\",\"365\"]\r\n for word in number_list:\r\n created_domains.add(word+domain_raw)\r\n created_domains.add(word+\"-\"+domain_raw)\r\n created_domains.add(domain_raw+word)\r\n created_domains.add(domain_raw+\"-\"+word)\r\n return\r\n\r\ndef append_fake_tld():\r\n fake_tld_list = [\"com\", \"org\", \"net\", \"info\", \"gov\", \"io\", \"us\"]\r\n for word in fake_tld_list:\r\n created_domains.add(domain_raw+\"-\"+word)\r\n #append tld inside domain (www.google-com.net, serious domains only)\r\n #with - because . in domain not allowed\r\n return\r\n\r\ndef append_userinput():\r\n print(\"Enter the words you want to add to the domain\")\r\n print(\"Press enter after each word\")\r\n print(\"Press e to exit\")\r\n words = set()\r\n user_input = 0\r\n \r\n while 1:\r\n user_input = input().lower()\r\n if user_input == \"e\":\r\n break\r\n else:\r\n words.add(user_input)\r\n \r\n for word in words:\r\n created_domains.add(word+domain_raw)\r\n created_domains.add(word+\"-\"+domain_raw)\r\n created_domains.add(domain_raw+word)\r\n created_domains.add(domain_raw+\"-\"+word) \r\n return\r\n\r\ndef add_tld():\r\n for tld in similar_tlds:\r\n for domain in created_domains:\r\n domain = domain + \".\" +tld\r\n available_domains.add(domain)\r\n return\r\n \r\ndef print_info_screen():\r\n print(pyfiglet.figlet_format(\"Domain Phisher\"))\r\n print(\"Welcome to Domain Phisher \\n\")\r\n print(\"Run program with one or more of the following arguments: \\n\")\r\n print(\"==> c to generate customer Domains...\")\r\n print(\"E.g. customerservice-\"+domain_raw+\".tld \\n\")\r\n print(\"==> i to generate IT Domains...\")\r\n print(\"E.g. \"+domain_raw+\"-support.tld \\n\")\r\n print(\"==> b to generate Billing Domains...\")\r\n print(\"E.g. invoice\"+domain_raw+\".tld \\n\")\r\n print(\"==> n to generate Number Domains...\")\r\n print(\"E.g. \"+domain_raw+\"24.tld \\n\")\r\n print(\"==> f to genrate fake TLDs...\")\r\n print(\"E.g. \"+domain_raw+\"-com.tld \\n\")\r\n print(\"==> d to double chars of the Domain...\")\r\n print(\"E.g. doomain.tld \\n\")\r\n print(\"==> r to replace chars of the Domain...\")\r\n print(\"E.g. d0main.tld \\n\")\r\n print(\"==> u for your own userinput...\")\r\n print(\"E.g. append domains with custom words relevant to your industy \\n\")\r\n return input(\"Enter your choice here: \").lower()\r\n\r\ndef whois_lookup():\r\n for domain in available_domains:\r\n try:\r\n availability_check = whois.whois(domain)\r\n if availability_check.domain_name == None: #not \"null\" or NULL\r\n print(\"Domain: \", domain, \"is unregistered\")\r\n unregistered_domains.add(domain)\r\n else:\r\n print(\"Domain: \", domain, \"is registered, see Information below\")\r\n print(availability_check)\r\n registered_domains.add(domain)\r\n except (whois.parser.PywhoisError, socket.gaierror) as e:\r\n print(\"Unable to process Domain: \", domain) \r\n sleep(0.5)\r\n #wait half a second, so the server doesn´t get to many requests\r\n return\r\n\r\ndef print_result_screen():\r\n print(\"-----RESULT-----\")\r\n print(\"Generated\",len(created_domains),\"unique Domains\")\r\n print(\"Found\", len(similar_tlds), \"similar TLDs\")\r\n print(\"This means\", len(similar_tlds)*len(created_domains), \"possible Domains for Phishers\")\r\n print(len(unregistered_domains), \"of them are not registered\")\r\n print(len(registered_domains), \"of them are registered\")\r\n return\r\n\r\nselected_preferences = print_info_screen()\r\n\r\nif \"c\" in selected_preferences:\r\n append_customer()\r\nif \"i\" in selected_preferences:\r\n append_it()\r\nif \"b\" in selected_preferences:\r\n append_billing()\r\nif \"n\" in selected_preferences:\r\n append_numbers()\r\nif \"f\" in selected_preferences:\r\n append_fake_tld()\r\nif \"d\" in selected_preferences:\r\n double_char()\r\nif \"r\" in selected_preferences:\r\n replace_char()\r\nif \"u\" in selected_preferences:\r\n append_userinput()\r\n\r\ncreate_tlds()\r\nadd_tld()\r\n\r\nfor i in available_domains:\r\n print(i)\r\n\r\nwhois_lookup()\r\nprint_result_screen()\r\n","sub_path":"Domain Phisher/DomainPhisher_V4.py","file_name":"DomainPhisher_V4.py","file_ext":"py","file_size_in_byte":7506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"524705507","text":"import numpy as np\nimport cPickle\nimport os\n\n# Custom modules/functions\nimport writeInput\nimport SimulationTools\nimport springs\nfrom shutil import copyfile\n\nclass experiment(object):\n def __init__(self, pointsPerSide, pointsPerLength,\n sideLength, ligamentLength,\n stiffness, matrixStiffness, offset, damping, mass,\n twist=0.0, phi=0.0, rMl=0.0, rAp=0.0):\n\n self.pointsPerSide = pointsPerSide\n self.pointsPerLength = pointsPerLength\n self.sideLength = sideLength\n self.ligamentLength = ligamentLength\n self.stiffness = stiffness\n self.matrixStiffness = matrixStiffness\n self.offset = offset\n self.damping = damping\n self.mass = mass\n self.twist = twist\n self.phi = phi\n self.rMl = rMl\n self.rAp = rAp\n\n def runSpringSim(self, jobName, workingDirectory, genericInputFile):\n\n _checkIfDirExists(workingDirectory) #: Check if workingDirectory exists, if not, make one.\n springs.writeGeometry(workingDirectory, self.pointsPerSide, self.pointsPerLength, self.sideLength, self.sideLength,\n self.ligamentLength, self.stiffness, self.matrixStiffness, self.offset, self.damping, self.mass,\n twist=self.twist, phi=self.phi, rMl=self.rMl, rAp=self.rAp, embeded=False)\n\n copyfile(genericInputFile, workingDirectory+'/'+jobName+'.inp')\n SimulationTools.runSimulation(jobName, workingDirectory)\n return\n\n def runEmbedSim(self, jobName, workingDirectory, genericInputFile):\n\n _checkIfDirExists(workingDirectory) #: Check if workingDirectory exists, if not, make one.\n springs.writeGeometry(workingDirectory, self.pointsPerSide, self.pointsPerLength, self.sideLength, self.sideLength,\n self.ligamentLength, self.stiffness, self.matrixStiffness, self.offset, self.damping, self.mass,\n twist=self.twist, phi=self.phi, rMl=self.rMl, rAp=self.rAp, embeded=True)\n\n copyfile(genericInputFile, workingDirectory+'/'+jobName+'.inp')\n SimulationTools.runSimulation(jobName, workingDirectory)\n return\n\ndef _checkIfDirExists(directory):\n if not os.path.isdir(directory):\n os.mkdir(directory)\n return\n\ndef runBatch(experimentObject, batchDirectory, genericInputFile, baseJobName, rMl, springs=True):\n for param in rMl:\n jobName = '{}_{}'.format(baseJobName, int(param))\n workingDirectory = '{}/{}'.format(batchDirectory, jobName)\n experimentObject.rMl = param\n if springs is True:\n experimentObject.runSpringSim(jobName, workingDirectory, genericInputFile)\n else:\n experimentObject.runEmbedSim(jobName, workingDirectory, genericInputFile)\n odbFileName = '{}/{}.odb'.format(workingDirectory, jobName)\n SimulationTools.getResults(workingDirectory, odbFileName)\n\n return\n\nif __name__ == '__main__':\n springBatchDirectory = '/home/will/Projects/ClassWork/BiosolidMechanics/FinalProject/Simulations/springBatch'\n springInputFile = '/home/will/Projects/ClassWork/BiosolidMechanics/FinalProject/Simulations/InputFiles/GenericInputExplicit.inp'\n springJobName = 'spring'\n\n embedBatchDirectory = '/home/will/Projects/ClassWork/BiosolidMechanics/FinalProject/Simulations/embedBatch'\n embedInputFile = '/home/will/Projects/ClassWork/BiosolidMechanics/FinalProject/Simulations/InputFiles/GenericInputEmbeded.inp'\n embedJobName = 'embed'\n\n pointsPerSide = 5 # Nodes per edge of insertion area.\n sideLength = 5 # Width and height of femoral and tibial insertion areas.\n ligamentLength = 35 # Length of the ligament.\n twist=0 # Twist between the femoral insertion and the tibial insertion\n phi=0 # The angle between the planes that define the femoral insertion and the tibial insertion\n pointsPerLength = 20\n\n stiffness = 1000 # N/mm\n offset = 0.0 # mm\n matrixStiffness = 100 # N/mm\n damping = 0.1 # damping value\n mass = 0.05\n\n rMl = np.arange(5, 30, 5)\n\n exp = experiment(pointsPerSide, pointsPerLength, sideLength, ligamentLength,\n stiffness, matrixStiffness, offset, damping, mass,\n twist=twist, phi=phi, rMl=0.0, rAp=0.0)\n\n runBatch(exp, springBatchDirectory, springInputFile, springJobName, rMl)\n runBatch(exp, embedBatchDirectory, embedInputFile, embedJobName, rMl, springs=False)\n","sub_path":"BiosolidMechanics/FinalProject/src/batchSimulation.py","file_name":"batchSimulation.py","file_ext":"py","file_size_in_byte":4462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"186923477","text":"# def test(N):\n# if N == 0:\n# return -1\n# result = [_ for _ in xrange(10)]\n# for i in xrange(1, 10001):\n# k = N * i\n# m = str(k)\n# for s in m:\n# temp = int(s)\n# if temp in result:\n# result.remove(int(s))\n# if len(result) == 0:\n# return k\n# return -1\n\n# print test(1)\n# print test(5)\n# print test(15)\n# print test(19)\n\n# def test(str_):\n# l = len(str_)\n# d = [0] * l\n# e = [0] * l\n# for i in xrange(l):\n# if i == 0:\n# if str_[i] == '+':\n# d[i] = 0\n# e[i] = 1\n# else:\n# d[i] = 1\n# e[i] = 0\n# else:\n# if str_[i] == '+':\n# d[i] = min(d[i - 1], e[i - 1] + 1)\n# e[i] = min(e[i - 1] + 2, d[i - 1] + 1) \n# else:\n# d[i] = min(e[i - 1] + 1, d[i - 1] + 2)\n# e[i] = min(e[i - 1], d[i - 1] + 1)\n# return d[l - 1]\n\nimport math\n##def is_prime(n):\n## if n % 2 == 0 and n > 2: \n## return 2\n## for i in range(3, int(math.sqrt(n)) + 1, 2):\n## if n % i == 0:\n## return i\n## return 1\n##def convert_to_decmial(str_, base):\n## r = 0\n## for i in xrange(len(str_) - 1, -1, -1):\n## if str_[i] == '1':\n## r += math.pow(base, len(str_) - 1 - i)\n## return r\n\n##def test(K, C, S):\n## count = 0\n## for num in xrange(2 ** (N - 1) + 1, 2 ** N, 2):\n## if count >= J:\n## break\n## if num > 3:\n## result = \"\"\n## str_ = bin(num)[2:].zfill(N)\n## result += str_ + \" \"\n## # print str_\n## b = True\n## for base in xrange(2, 11):\n## k = convert_to_decmial(str_, base)\n## # print k\n## d = is_prime(k)\n## if d > 1:\n## result += str(d) + \" \"\n## else:\n## b = False\n## continue\n## if b:\n## print result\n## count += 1\n\n# test(6, 3)\n\n# print test(\"--+-\") # 3\n# print test(\"+++\") # 0 \n# print test(\"+-\") # 2\n# print test(\"+\") # 0\n# print test(\"-\") # 1\nimport itertools\ndef xor_string(a,b):\n c=\"0\"*len(a)\n for k in xrange(len(a)):\n if a[k] != b[k]:\n c[k]='1'\n return c\ndef test(K, C, S):\n if K == 1:\n if S < 1:\n return \"IMPOSSIBLE\"\n else:\n return \"1\"\n if C == 1:\n if S < K:\n return \"IMPOSSIBLE\"\n else:\n return \" \".join([str(_) for _ in xrange(1,K+1)])\n## res = []\n## p = \"\".join(['0' for _ in xrange(K-1)])\n## for seq in itertools.product(\"01\", repeat=K-1):\n## k = xor_string(p,\"\".join(seq))\n## for i in xrange(len(k)):\n## if k[i] == '1':\n## if (i+2) not in res:\n## res.append(i+2)\n## if S < len(res):\n if S < K-1:\n return \"IMPOSSIBLE\"\n else:\n #res.sort()\n return \" \".join([str(_) for _ in xrange(2,K+ 1)])\n\n##print \"(2,3,2) :\",test(2,3,2)\n##print \"(1,1,1) :\",test(1,1,1)\n##print \"(2,1,1) :\",test(2,1,1)\n##print \"(2,1,2) :\",test(2,1,2)\n##print \"(3,2,3) :\",test(3,2,3)\n\n\n\n \nif __name__ == \"__main__\":\n testcases = input()\n \n for caseNr in xrange(1, testcases + 1):\n K, C, S = raw_input().split()\n res = test(int(K), int(C), int(S))\n print(\"Case #%i: %s\" % (caseNr, res))\n #print(\"Case #1:\")\n \n \n","sub_path":"codes/CodeJamCrawler/16_0_4/peterpans01/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"195789994","text":"#!/usr/bin/env python3.7\nimport pandas as pd\n# Author: Roujia Li\n# email: Roujia.li@mail.utoronto.ca\n\n## process files for yeast and human to make the final input file for PPS analysis\n# the final input file can be found here:\n\n\ndef read_yeast_orf(HIP_target_ORFs, other_target_ORFs):\n \"\"\"\n Join HIP data and other data into one df, remove unwanted columns. Save the merged df to file\n :param HIP_target_ORFs: csv file contains which HIP ORF is in which sample\n :param other_target_ORFs: csv file contains which other ORF is in which sample\n :return: df with ORF name, db name and sample name\n \"\"\"\n HIP_df = pd.read_csv(HIP_target_ORFs)\n other_target_ORFs = pd.read_csv(other_target_ORFs)\n\n HIP_df = HIP_df[[\"ORF_id\", \"ORF_NAME_NODASH\", \"len(seq)\", \"SYMBOL\", \"plate\"]]\n HIP_df[\"db\"] = \"HIP\"\n HIP_df = HIP_df.rename(columns={\"ORF_id\": \"orf_name\"})\n other_ORFs = other_target_ORFs[[\"orf_name\", \"ORF_NAME_NODASH\", \"src_collection\", \"plate\"]]\n other_ORFs = other_ORFs.rename(columns={\"src_collection\": \"db\"})\n #other_ORFs['plate'] = 'scORFeome-' + other_ORFs['plate'].astype(str)\n combined = pd.concat([HIP_df, other_ORFs], axis=0, ignore_index=True)\n \n output_file = \"/home/rothlab/rli/02_dev/06_pps_pipeline/target_orfs/yeast_summary.csv\"\n combined.to_csv(output_file)\n return combined\n\n\ndef read_human_orf(human_ref_with_seq, human91_ref):\n \"\"\"\n human ref with enst/ensg ID\n \"\"\"\n ref_df_91 = pd.read_csv(human91_ref)\n ref_df_ensembl = pd.read_csv(human_ref_with_seq)\n ref_df_91 = ref_df_91.fillna(-1)\n\n # merge this two df together\n # check if there are NAs in entrez gene ID and entrez gene symbol\n merged_df = pd.merge(ref_df_91, ref_df_ensembl, left_on=[\"entrez_gene_id\", \"entrez_gene_symbol\"],\n right_on=[\"entrez_gene_id\", \"symbol\"], how=\"left\")\n merged_df[\"grch37_filled\"] = merged_df[\"cds_seq37\"].fillna(merged_df[\"cds_seq\"])\n merged_df[\"grch38_filled\"] = merged_df[\"cds_seq38\"].fillna(merged_df[\"cds_seq\"])\n\n merged_df[\"entrez_gene_id\"] = merged_df[\"entrez_gene_id\"].astype(int)\n merged_df['orf_name'] = merged_df['orf_id'].astype(str) + \"_\" + merged_df['entrez_gene_id'].astype(str) + \"_G0\" + merged_df['Pool group #'].astype(str) + \"_\" + merged_df['entrez_gene_symbol'].astype(str)\n\n # humanallORF = pd.read_csv(human_ref)\n # humanallORF = humanallORF[[\"ORFID\", \"ensembl_transcript_id\", \"ensembl_protein_id\", \"ensembl_gene_id\", \"uniprot_AC_iso\", \"symbol\", \"entrez_gene_id\", \"CDS\"]]\n #\n # humanallORF[\"entrez_gene_id\"] = humanallORF[\"entrez_gene_id\"].astype(int)\n # humanallORF['orf_name'] = humanallORF['entrez_gene_id'].astype(str) + \"_\" + humanallORF['entrez_gene_symbol'].astype(str)\n output_file = \"/home/rothlab/rli/02_dev/06_pps_pipeline/target_orfs/human_summary.csv\"\n merged_df.to_csv(output_file)\n return merged_df\n\nif __name__ == '__main__':\n # process yeast file\n HIP_target_ORFs = \"/home/rothlab/rli/02_dev/06_pps_pipeline/target_orfs/HIP_targeted_ORFs.csv\"\n other_target_ORFs = \"/home/rothlab/rli/02_dev/06_pps_pipeline/target_orfs/other_targeted_ORFs.csv\"\n read_yeast_orf(HIP_target_ORFs, other_target_ORFs)\n\n # process human file\n ref_91 = \"/home/rothlab/rli/02_dev/06_pps_pipeline/target_orfs/20161117_ORFeome91_seqs.csv\"\n ref_ensembl = \"/home/rothlab/rli/02_dev/06_pps_pipeline/publicdb/merged_ensembl_sequence.csv\"\n read_human_orf(ref_ensembl, ref_91)\n","sub_path":"build/lib/ppsAnalysis/process_input.py","file_name":"process_input.py","file_ext":"py","file_size_in_byte":3446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"108700452","text":"import typing\n\nfrom . import constants, exceptions\n\n\ndef convert_params_to_args_and_kwargs(params: typing.Any) -> typing.Tuple[list, dict]:\n if isinstance(params, (str, int, float, bool,)) or params is None:\n args = [params]\n kwargs = {}\n elif isinstance(params, list):\n args = params\n kwargs = {}\n elif isinstance(params, dict):\n args = []\n kwargs = params\n else:\n args = [params]\n kwargs = {}\n\n return args, kwargs\n\n\ndef parse_args_and_kwargs(args: typing.Any, kwargs: typing.Any) -> typing.Tuple:\n has_args = bool(args and args is not constants.NOTHING)\n has_kwargs = bool(kwargs and kwargs is not constants.NOTHING)\n\n if not has_args and not has_kwargs:\n params = constants.NOTHING\n args = []\n kwargs = {}\n return params, args, kwargs\n\n if not (has_args ^ has_kwargs):\n raise exceptions.InvalidParams('Need use args or kwargs.')\n\n if has_args:\n args = list(args)\n params = args\n kwargs = {}\n elif has_kwargs:\n kwargs = dict(kwargs)\n params = kwargs\n args = []\n\n return params, args, kwargs\n","sub_path":"aiohttp_rpc/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"187043154","text":"import sys\r\nfrom operator import itemgetter\r\nimport pandas as pd\r\n\r\n\r\ndef load_data(train_data, test_data, k, row):\r\n full_training_set = pd.read_csv(train_data, sep='\\t').values.tolist() #Taking Training_Data\r\n rd_train_data = pd.read_csv(train_data, sep='\\t').values.tolist()\r\n rd_test_data = pd.read_csv(test_data, sep='\\t').values.tolist() # Taking Testing Data\r\n for class_data in rd_train_data:\r\n del class_data[-1] # Divide the training set from class\r\n euc_distance = []\r\n for item in rd_test_data:\r\n distance = [euclidean_distance(item, element) for element in rd_train_data]\r\n euc_distance.append(distance) #Calculating the eclidean_distance and create a new list with the distance\r\n\r\n for column in range(204):\r\n full_training_set[column].append(euc_distance[row][column]) #Taking euclidean distance of each row from test set and merge into the training dataset\r\n sorted_full_set = sorted(full_training_set,key=itemgetter(10)) # Sort the euclidean distance based in ascending order\r\n\r\n new_list = []\r\n for value in range(k):\r\n a = sorted_full_set[value]\r\n select_class = a[-2]\r\n new_list.append(select_class) # based on the value of K, create a new list of class\r\n count_number = [new_list.count(1),new_list.count(2),new_list.count(3),new_list.count(5),new_list.count(6),new_list.count(7)] # Which class is maximum iterated\r\n accu_knn = round(((max(count_number)/len(new_list))*100),2) # Calculate the value of Estimated conditional probability of the predicted class\r\n print(int(max(new_list, key=new_list.count)), end=' ')\r\n print(accu_knn, \"%\")\r\n\r\n\r\ndef euclidean_distance(train_data, test_data): # function for euclidean distance\r\n\r\n return sum((p - q) ** 2 for p, q in zip(train_data, test_data)) ** .5\r\n\r\n\r\ndef main(R):\r\n trainingSet= sys.argv[1]\r\n testingSet = sys.argv[2]\r\n K = int(sys.argv[3]) if len(sys.argv) >= 4 else int(3) # The default value of K=3, if no input of K\r\n #R = int(input(\"Please Enter The Row Number of the Testing Dataset: \" + \" (0 to 9)\")) # seleting the row of testing dataset to find out the class of that row\r\n load_data(trainingSet, testingSet, K, R)\r\nfor item in range(9):\r\n main(item) #call the main function\r\n\r\n","sub_path":"KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":2281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"78958608","text":"# Thos class is probably obsolete\nclass Topology(object):\n instance = None\n\n def __new__(cls, *args, **kwargs):\n if cls.instance is not None:\n return cls.instance\n else:\n cls.instance = super(Topology, cls).__new__(args, kwargs)\n return cls.instance\n\n def __init__(self, in_node=None, out_node=None, sender_node=None, receiver_node=None):\n self.in_node = in_node\n self.out_node = out_node\n self.sender_node = sender_node\n self.receiver_node = receiver_node\n","sub_path":"src/components/topology.py","file_name":"topology.py","file_ext":"py","file_size_in_byte":541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"568926235","text":"# Solution for Bon Appetit\n\n\ndef refund(bill, k, b):\n total = sum(bill)\n total -= bill[k]\n ref = b - total // 2\n\n return ref\n\n\nif __name__ == '__main__':\n n, k = map(int, input().split()) # n = nr of items, k = item Anna did not eat\n bill = list(map(int, input().split()))\n b = int(input()) # Anna's charge\n\n ref = refund(bill, k, b)\n if ref:\n print(ref)\n else:\n print(\"Bon Appetit\")\n","sub_path":"Python/Algorithms/Implementation/Bon Appetit.py","file_name":"Bon Appetit.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"297656491","text":"# coding=utf-8\nimport json\n\nimport pika\n\nhostname = '10.90.60.10'\nport = 5672\n\nvirtual_host = '/'\n# parameters = pika.ConnectionParameters(host=hostname, port=port, virtual_host=virtual_host)\nparameters = pika.ConnectionParameters(host=hostname, virtual_host=virtual_host)\nconnection = pika.BlockingConnection(parameters)\nchannel = connection.channel()\nchannel.basic_qos(prefetch_count=1) # 使用basic_qos方法,并设置prefetch_count=1。这样是告诉RabbitMQ,在同一时刻,不要发送超过1条消息给一个工作者worker 公平调度\n\n# 声明消息队列,消息将在这个队列中进行传递。如果队列不存在,则创建\nchannel.queue_declare(queue='riskModel4PythonAddition', durable=True)\n\n\n# 定义一个回调函数来处理,这边的回调函数就是将信息打印出来。\ndef callback(ch, method, properties, body):\n\tprint('-->', ch, method, properties)\n\tprint(\"[x] Received %s\" % body)\n\tid = body\n\tresult = str(body, encoding='utf-8')\n\tresult = result.replace('\\'', '\\\"')\n\tid = json.loads(result)\n\tprint(id)\n\n\n# 告诉rabbitmq使用callback来接收信息\nchannel.basic_consume(callback,\n queue='riskModel4PythonAddition',\n no_ack=True # no_ack=True表示在回调函数中不需要发送确认标识\n )\n\nprint('[*]waitingfor messages.To exit press CTRL+C')\n\n# 开始接收信息,并进入阻塞状态,队列里有信息才会调用callback进行处理。按ctrl+c退出。\nchannel.start_consuming()\n","sub_path":"rabbitmq本地消费10服务器.py","file_name":"rabbitmq本地消费10服务器.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"413349261","text":"# pylint: skip-file\n# type: ignore\n# -*- coding: utf-8 -*-\n#\n# tests.models.programdb.test_ramstkrevision.py is part of The RAMSTK\n# Project\n#\n# All rights reserved.\n\"\"\"Test class for testing the RAMSTKRevision module algorithms and models.\"\"\"\n\n# Third Party Imports\nimport pytest\nfrom mocks import MockDAO\n\n# RAMSTK Package Imports\nfrom ramstk.models.programdb import RAMSTKRevision\n\n\n@pytest.fixture\ndef mock_program_dao(monkeypatch):\n _revision_1 = RAMSTKRevision()\n _revision_1.revision_id = 1\n _revision_1.availability_logistics = 0.9986\n _revision_1.availability_mission = 0.99934\n _revision_1.cost = 12532.15\n _revision_1.cost_failure = 0.0000352\n _revision_1.cost_hour = 1.2532\n _revision_1.hazard_rate_active = 0.0\n _revision_1.hazard_rate_dormant = 0.0\n _revision_1.hazard_rate_logistics = 0.0\n _revision_1.hazard_rate_mission = 0.0\n _revision_1.hazard_rate_software = 0.0\n _revision_1.mmt = 0.0\n _revision_1.mcmt = 0.0\n _revision_1.mpmt = 0.0\n _revision_1.mtbf_logistics = 0.0\n _revision_1.mtbf_mission = 0.0\n _revision_1.mttr = 0.0\n _revision_1.name = 'Original Revision'\n _revision_1.reliability_logistics = 0.99986\n _revision_1.reliability_mission = 0.99992\n _revision_1.remarks = 'This is the original revision.'\n _revision_1.revision_code = 'Rev. -'\n _revision_1.program_time = 2562\n _revision_1.program_time_sd = 26.83\n _revision_1.program_cost = 26492.83\n _revision_1.program_cost_sd = 15.62\n\n _revision_2 = RAMSTKRevision()\n _revision_2.revision_id = 2\n _revision_2.availability_logistics = 1.0\n _revision_2.availability_mission = 1.0\n _revision_2.cost = 0.0\n _revision_2.cost_failure = 0.0\n _revision_2.cost_hour = 0.0\n _revision_2.hazard_rate_active = 0.0\n _revision_2.hazard_rate_dormant = 0.0\n _revision_2.hazard_rate_logistics = 0.0\n _revision_2.hazard_rate_mission = 0.0\n _revision_2.hazard_rate_software = 0.0\n _revision_2.mmt = 0.0\n _revision_2.mcmt = 0.0\n _revision_2.mpmt = 0.0\n _revision_2.mtbf_logistics = 0.0\n _revision_2.mtbf_mission = 0.0\n _revision_2.mttr = 0.0\n _revision_2.name = 'Revision A'\n _revision_2.reliability_logistics = 1.0\n _revision_2.reliability_mission = 1.0\n _revision_2.remarks = 'This is the second revision.'\n _revision_2.revision_code = 'Rev. A'\n _revision_2.program_time = 0\n _revision_2.program_time_sd = 0.0\n _revision_2.program_cost = 0.0\n _revision_2.program_cost_sd = 0.0\n\n DAO = MockDAO()\n DAO.table = [\n _revision_1,\n _revision_2,\n ]\n\n yield DAO\n\n\nATTRIBUTES = {\n 'availability_logistics': 1.0,\n 'availability_mission': 1.0,\n 'cost': 0.0,\n 'cost_failure': 0.0,\n 'cost_hour': 0.0,\n 'hazard_rate_active': 0.0,\n 'hazard_rate_dormant': 0.0,\n 'hazard_rate_logistics': 0.0,\n 'hazard_rate_mission': 0.0,\n 'hazard_rate_software': 0.0,\n 'mmt': 0.0,\n 'mcmt': 0.0,\n 'mpmt': 0.0,\n 'mtbf_logistics': 0.0,\n 'mtbf_mission': 0.0,\n 'mttr': 0.0,\n 'name': 'Test Revision',\n 'reliability_logistics': 1.0,\n 'reliability_mission': 1.0,\n 'remarks': '',\n 'total_part_count': 1,\n 'revision_code': '',\n 'program_time': 0.0,\n 'program_time_sd': 0.0,\n 'program_cost': 0.0,\n 'program_cost_sd': 0.0\n}\n\n\n@pytest.mark.usefixtures('mock_program_dao')\nclass TestRAMSTKRevision():\n \"\"\"Class for testing the RAMSTKRevision model.\"\"\"\n @pytest.mark.unit\n def test_ramstkrevision_create(self, mock_program_dao):\n \"\"\"__init__() should create an RAMSTKRevision model.\"\"\"\n DUT = mock_program_dao.do_select_all(RAMSTKRevision)[0]\n\n assert isinstance(DUT, RAMSTKRevision)\n\n # Verify class attributes are properly initialized.\n assert DUT.__tablename__ == 'ramstk_revision'\n assert DUT.revision_id == 1\n assert DUT.availability_logistics == 0.9986\n assert DUT.availability_mission == 0.99934\n assert DUT.cost == 12532.15\n assert DUT.cost_failure == 0.0000352\n assert DUT.cost_hour == 1.2532\n assert DUT.hazard_rate_active == 0.0\n assert DUT.hazard_rate_dormant == 0.0\n assert DUT.hazard_rate_logistics == 0.0\n assert DUT.hazard_rate_mission == 0.0\n assert DUT.hazard_rate_software == 0.0\n assert DUT.mmt == 0.0\n assert DUT.mcmt == 0.0\n assert DUT.mpmt == 0.0\n assert DUT.mtbf_logistics == 0.0\n assert DUT.mtbf_mission == 0.0\n assert DUT.mttr == 0.0\n assert DUT.name == 'Original Revision'\n assert DUT.reliability_logistics == 0.99986\n assert DUT.reliability_mission == 0.99992\n assert DUT.remarks == 'This is the original revision.'\n assert DUT.revision_code == 'Rev. -'\n assert DUT.program_time == 2562\n assert DUT.program_time_sd == 26.83\n assert DUT.program_cost == 26492.83\n assert DUT.program_cost_sd == 15.62\n\n @pytest.mark.integration\n def test_get_attributes(self, mock_program_dao):\n \"\"\"get_attributes() should return a dict of {attr name:attr value}\n pairs.\"\"\"\n DUT = mock_program_dao.do_select_all(RAMSTKRevision)[0]\n\n _attributes = DUT.get_attributes()\n\n assert _attributes['availability_logistics'] == 0.9986\n assert _attributes['availability_mission'] == 0.99934\n assert _attributes['cost'] == 12532.15\n assert _attributes['cost_failure'] == 0.0000352\n assert _attributes['cost_hour'] == 1.2532\n assert _attributes['hazard_rate_active'] == 0.0\n assert _attributes['hazard_rate_dormant'] == 0.0\n assert _attributes['hazard_rate_logistics'] == 0.0\n assert _attributes['hazard_rate_mission'] == 0.0\n assert _attributes['hazard_rate_software'] == 0.0\n assert _attributes['mmt'] == 0.0\n assert _attributes['mcmt'] == 0.0\n assert _attributes['mpmt'] == 0.0\n assert _attributes['mtbf_logistics'] == 0.0\n assert _attributes['mtbf_mission'] == 0.0\n assert _attributes['mttr'] == 0.0\n assert _attributes['name'] == 'Original Revision'\n assert _attributes['reliability_logistics'] == 0.99986\n assert _attributes['reliability_mission'] == 0.99992\n assert _attributes['remarks'] == 'This is the original revision.'\n assert _attributes['revision_code'] == 'Rev. -'\n assert _attributes['program_time'] == 2562\n assert _attributes['program_time_sd'] == 26.83\n assert _attributes['program_cost'] == 26492.83\n assert _attributes['program_cost_sd'] == 15.62\n\n @pytest.mark.unit\n def test_set_attributes(self, mock_program_dao):\n \"\"\"set_attributes() should return a zero error code on success.\"\"\"\n DUT = mock_program_dao.do_select_all(RAMSTKRevision)[0]\n\n assert DUT.set_attributes(ATTRIBUTES) is None\n\n @pytest.mark.unit\n def test_set_attributes_none_value(self, mock_program_dao):\n \"\"\"set_attributes() should set an attribute to it's default value when\n the attribute is passed with a None value.\"\"\"\n DUT = mock_program_dao.do_select_all(RAMSTKRevision)[0]\n\n ATTRIBUTES['mttr'] = None\n\n assert DUT.set_attributes(ATTRIBUTES) is None\n assert DUT.get_attributes()['mttr'] == 0.0\n\n @pytest.mark.unit\n def test_set_attributes_unknown_attributes(self, mock_program_dao):\n \"\"\"set_attributes() should raise an AttributeError when passed an\n unknown attribute.\"\"\"\n DUT = mock_program_dao.do_select_all(RAMSTKRevision)[0]\n\n with pytest.raises(AttributeError):\n DUT.set_attributes({'shibboly-bibbly-boo': 0.9998})\n","sub_path":"tests/models/programdb/ramstkrevision_unit_test.py","file_name":"ramstkrevision_unit_test.py","file_ext":"py","file_size_in_byte":7652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"559007554","text":"# -*- coding: utf-8 -*-\n'''\n@Time : 20/04/25 15:49\n@Author : huguanghao\n@File : demo.py\n@Noice :\n@Modificattion :\n @Author :\n @Time :\n @Detail :\n'''\n\n# import sys\nimport time\nimport cv2\n# from PIL import Image, ImageDraw\n# from models.tiny_yolo import TinyYoloNet\nfrom tool.utils import *\nfrom tool.torch_utils import *\nfrom tool.darknet2pytorch import Darknet\nfrom tracker import *\nimport argparse\n\n\"\"\"hyper parameters\"\"\"\nuse_cuda = True\n\n\ndef detect_cv2_camera(cfgfile, weightfile, source, show):\n\n model_name = (cfgfile.split('.')[-2]).split('/')[-1]\n m = Darknet(cfgfile)\n\n #m.print_network()\n m.load_weights(weightfile)\n #print('Loading weights from %s... Done!' % (weightfile))\n\n if use_cuda:\n m.cuda()\n\n # Create tracker object\n tracker = EuclideanDistTracker()\n cap = cv2.VideoCapture(source)\n times_infer, times_pipe = [], []\n\n num_classes = m.num_classes\n if num_classes == 20:\n namesfile = 'data/voc.names'\n elif num_classes == 80:\n namesfile = 'data/coco.names'\n else:\n namesfile = 'data/x.names'\n class_names = load_class_names(namesfile)\n\n while True:\n ret, img = cap.read()\n\n if ret:\n img = cv2.resize(img, (1024,512))\n sized = cv2.resize(img, (m.width, m.height))\n sized = cv2.cvtColor(sized, cv2.COLOR_BGR2RGB)\n\n t0 = time.time()\n boxes = do_detect(m, sized, 0.4, 0.6, use_cuda)\n\n #result_img = plot_boxes_cv2(img, boxes[0], savename=None, class_names=class_names)\n\n t1 = time.time()\n t2 = time.time()\n\n times_infer.append(t1-t0)\n times_pipe.append(t2-t0)\n \n times_infer = times_infer[-20:]\n times_pipe = times_pipe[-20:]\n\n ms = sum(times_infer)/len(times_infer)*1000\n fps_infer = 1000 / (ms+0.00001)\n fps_pipe = 1000 / (sum(times_pipe)/len(times_pipe)*1000)\n\n boxes_ids = tracker.update(boxes[0])\n for box_id in boxes_ids:\n x, y, w, h, id = box_id\n cv2.putText(img, str(id), (x, y - 15), cv2.FONT_HERSHEY_PLAIN, 2, (255, 0, 0), 2)\n cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 3)\n \n # Stream results\n if show:\n cv2.imshow(model_name, img)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n cv2.destroyAllWindows()\n break # 1 millisecond\n\n print(\"Time: {:.2f}ms, Detection FPS: {:.1f}, total FPS: {:.1f}\".format(ms, fps_infer, fps_pipe))\n\n else:\n break \n\n cap.release()\n\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--cfgfile', type=str, default='./cfg/yolov4.cfg',\n help='path of cfg file', dest='cfgfile')\n parser.add_argument('--weightfile', type=str,\n default='./checkpoints/Yolov4_epoch1.pth',\n help='path of trained model.', dest='weightfile')\n parser.add_argument('--source', type=str, default='./output.mp4', help='path to video file.')\n parser.add_argument('--show', type=bool, default=True, help='display results')\n args = parser.parse_args()\n\n detect_cv2_camera(args.cfgfile, args.weightfile, args.source, args.show)\n","sub_path":"demo_detect_track.py","file_name":"demo_detect_track.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"393580496","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Sep 18 20:29:50 2012\n\n@author: zhengxin\n\"\"\"\nimport cudamat as cm\n\ndef softmax(eta):\n #temp = cm.empty((eta.shape[0],1))\n temp = cm.empty((1,eta.shape[1]))\n # this is considered to be potential numerical problem\n if True:\n eta.max(axis = 0, target = temp)\n #print eta.shape\n #print temp.shape\n temp.mult(-1)\n eta.add_row_vec(temp)\n cm.exp(eta)\n eta.sum(axis = 0, target = temp)\n temp.reciprocal()\n eta.mult_by_row(temp)\n# else:\n# cm.exp(eta)\n# eta.sum(axis = 0, target = temp)\n# temp.reciprocal()\n# eta.mult_by_col(temp)\n ","sub_path":"softmax.py","file_name":"softmax.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"19839855","text":"# coding: utf-8\n\nfrom datetime import datetime\nfrom core.dispatcher import dispatcher, Signals\n\n\nclass VirtualMachine(object):\n def __init__(self, name, platform):\n self.name = name\n self.ip = None\n self.mac = None\n self.platform = platform\n self.created = datetime.now()\n self.ready = False\n self.checking = False\n self.done = False\n\n @property\n def info(self):\n return {\n \"name\": str(self.name),\n \"ip\": str(self.ip),\n \"platform\": str(self.platform)\n }\n\n def create(self):\n pass\n\n def delete(self):\n dispatcher.send(signal=Signals.DELETE_VIRTUAL_MACHINE, sender=self)\n self.done = True\n\n def is_preloaded(self):\n return 'preloaded' in self.name\n","sub_path":"vmpool/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"647820033","text":"# Implementation of single branch model\n\nimport os\nimport time\nimport warnings\nimport numpy as np\nfrom numpy import newaxis\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Activation, Dropout, Flatten\nfrom keras.layers.recurrent import LSTM\nfrom keras.layers.convolutional import Conv1D\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.pooling import MaxPooling1D\nfrom keras.layers.recurrent import GRU\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' #Hide messy TensorFlow warnings\nwarnings.filterwarnings(\"ignore\") #Hide messy Numpy warnings\n\ndef build_model(layers, cnn_layers, lstm_units=200, kernel_size=5, stride_1=2, filter_num=128):\n # parameters obtained from stock_model.py in Convolutional Neural Stock Market Technical Analyser\n dropout = 0.5\n conv_stride = 2\n ksize = kernel_size\n pool_size = 2\n padding = \"same\"\n\n model = Sequential()\n\n model.add(Conv1D(\n input_shape = (layers[1], layers[0]), # (50, 1)\n filters=filter_num, \n kernel_size=ksize, \n strides=conv_stride, \n padding=padding, \n activation=None))\n BatchNormalization(axis=-1)\n model.add(Activation('relu'))\n\n model.add(MaxPooling1D(\n pool_size=pool_size))\n\n for x in range(1, cnn_layers):\n model.add(Conv1D(\n filters=filter_num*2*x, \n kernel_size=ksize, \n strides=conv_stride, \n padding=padding, \n activation=None))\n BatchNormalization(axis=-1)\n model.add(Activation('relu'))\n\n model.add(MaxPooling1D(\n pool_size=pool_size))\n\n\n model.add(GRU(lstm_units,input_shape = (layers[1], layers[0]), activation='tanh', return_sequences=True))\n model.add(Dropout(dropout/2))\n\n model.add(GRU(lstm_units,activation='tanh', return_sequences=False))\n model.add(Dropout(dropout))\n\n model.add(Dense(\n output_dim = 1)) # Linear output\n model.add(Activation(\"linear\"))\n\n\n print(model.summary())\n\n start = time.time()\n model.compile(loss=\"mse\", optimizer=\"adadelta\")\n print(\"> Compilation Time : \", time.time() - start)\n return model\n","sub_path":"single_cnn_gru.py","file_name":"single_cnn_gru.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"647175790","text":"# -*- coding: utf-8 -*\n#Installation du module xlutils\n#pip install xlutils\nimport numpy as np\nimport xlrd\nimport datetime\nimport os, glob\nMois=['Janvier','Fevrier','Mars','Avril','Mai','Juin','Juillet','Aout','Septembre','Octobre','Novembre','Décembre']\n\n#RAZ du fichier log\nf=open('log.txt','w')\n\nanswer=input('classe ? (1 : MPSI, 2: PSI)')\n\nif answer=='1':\n path=r\"/Users/emiliendurif/Documents/prepa/MPSI/organisation_programme/progression_2018_2019_MPSI.xlsx\"\n path_classe='/Users/emiliendurif/Documents/prepa/MPSI/2018-2019/'\n path_site='/Users/emiliendurif/Documents/prepa/MPSI/site'\n nligne=40#Derniere ligne où figure une donnée\n delta_td=1#position du jour des TD dans la semaine\n delta_cours=1#position du jour des cours dans la semaine\nelif answer=='2':\n path=r\"/Users/emiliendurif/Documents/prepa/PSI/organisation_psi/progression_2018_2019_PSI_emilien.xlsx\"\n path_classe='/Users/emiliendurif/Documents/prepa/PSI/2018-2019/'\n path_site='/Users/emiliendurif/Documents/prepa/PSI/organisation_psi/site'\n nligne=27#Derniere ligne où figure une donnée\n delta_td=4#position du jour des TD dans la semaine\n delta_cours=2#position du jour des cours dans la semaine\nelse:\n print('Mauvais choix')\n answer=input('classe ? (1 : MPSI, 2: PSI)')\n#Ouverture de la progression excel\nclasseur=xlrd.open_workbook(path)\nfeuilles=classeur.sheet_names()\n\n#Ouverture de la feuille du semanier\nfor f in feuilles:\n if \"Semanier\" in f:\n fs=classeur.sheet_by_name(f)\nliste_cours=[]\nliste_td=[]\nliste_cycle=[]\nliste_name_cycle=[]\nd0=datetime.date(1900,1,1)\nfor k in range(1,nligne):\n#for k in range(1,2):\n if 'Vacances' not in str(fs.cell_value(k,0)):\n delta = datetime.timedelta(days=(fs.cell_value(k,1)-2))\n d_s=d0+delta#Date du début de la semaine\n d_cours=d_s+datetime.timedelta(delta_cours)#Date du cours\n d_td=d_s+datetime.timedelta(delta_td)#Date du TD\n if fs.cell_value(k,2)!='':\n n_cycle=fs.cell_value(k,2)#numero du cycle\n name_cycle=fs.cell_value(k,3)#nom du cycle\n cycle_resume=fs.cell_value(k,14)#nom du cycle resume\n liste_cycle.append(n_cycle)\n liste_name_cycle.append(name_cycle)\n else:\n n_cycle=liste_cycle[-1]\n name_cycle=liste_name_cycle[-1]\n n_cours=fs.cell_value(k,4)#numero du cours\n #Gestion des cours\n if n_cours not in liste_cours:\n col_d=13#Colonne du nom des dossiers\n if fs.cell_value(k,col_d) !='':\n rep=fs.cell_value(k,col_d)\n rep0=os.listdir(path_classe+'/'+rep)\n for rep_cours in rep0:\n #Edition des entetes\n if n_cours in rep_cours:#Se positionner dans un repertoire de cours\n name_cours=fs.cell_value(k,5)#nom du cours\n d_cours_f=str(d_cours.day)+' '+Mois[d_cours.month-1]+' '+str(d_cours.year)#Date du cours écrite en français\n with open(path_classe+'/'+rep+'/'+rep_cours+'/entete.tex','w',encoding='iso-8859-1') as f:\n f.write('\\\\renewcommand{\\\\cycle}{'+n_cycle+' : '+name_cycle+'}\\n')\n f.write('\\\\renewcommand{\\\\cycleresume}{'+n_cycle+' : '+cycle_resume+'}\\n')\n f.write('\\\\renewcommand{\\\\titre}{'+name_cours+'}\\n')\n f.write('\\\\renewcommand{\\\\numero}{'+n_cours+'}\\n')\n f.write('\\\\renewcommand{\\\\auteur}{Emilien DURIF}\\n')\n f.write('\\\\renewcommand{\\\\etablissement}{Lycée La Martinière Monplaisir Lyon}\\n')\n f.write(\"\\\\renewcommand{\\\\discipline}{Sciences Industrielles pour l'Ingénieur}\\n\")\n if answer=='1':\n f.write('\\\\renewcommand{\\\\classe}{Classe préparatoire M.P.S.I.}\\n')\n elif answer=='2':\n f.write('\\\\renewcommand{\\\\classe}{Classe préparatoire P.S.I.}\\n')\n f.write('\\\\renewcommand{\\\\annee}{2018 - 2019}\\n')\n f.write('\\\\renewcommand{\\\\icone}{/Users/emiliendurif/Documents/prepa/latex/images/logo_martiniere.jpg}\\n')\n f.write('\\\\renewcommand{\\\\competences}{}\\n')\n f.write('\\\\renewcommand{\\\\date}\t{'+d_cours_f+'}\\n')\n \n liste_cours.append(n_cours)#Validation du nouveau cours\n\n \n\n","sub_path":"generer_entete0.py","file_name":"generer_entete0.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"503686002","text":"from __future__ import annotations\n\nfrom typing import TYPE_CHECKING\n\nfrom PySide6.QtCore import QObject\nfrom PySide6.QtGui import QUndoGroup\n\nfrom bsmu.vision.core.plugins.base import Plugin\nfrom bsmu.vision.plugins.windows.main import EditMenu\n\nif TYPE_CHECKING:\n from PySide6.QtGui import QAction\n\n from bsmu.vision.plugins.windows.main import MainWindowPlugin, MainWindow\n from bsmu.vision.plugins.doc_interfaces.mdi import MdiPlugin, Mdi\n\n\nclass UndoPlugin(Plugin):\n _DEFAULT_DEPENDENCY_PLUGIN_FULL_NAME_BY_KEY = {\n 'main_window_plugin': 'bsmu.vision.plugins.windows.main.MainWindowPlugin',\n 'mdi_plugin': 'bsmu.vision.plugins.doc_interfaces.mdi.MdiPlugin',\n }\n\n def __init__(self, main_window_plugin: MainWindowPlugin, mdi_plugin: MdiPlugin):\n super().__init__()\n\n self._main_window_plugin = main_window_plugin\n self._main_window: MainWindow | None = None\n\n self._mdi_plugin = mdi_plugin\n self._mdi: Mdi | None = None\n\n self._undo_manager: UndoManager | None = None\n\n def _enable(self):\n self._main_window = self._main_window_plugin.main_window\n self._mdi = self._mdi_plugin.mdi\n\n self._undo_manager = UndoManager()\n\n def _enable_gui(self):\n edit_menu = self._main_window.menu(EditMenu)\n edit_menu.addAction(self._undo_manager.create_undo_action(edit_menu))\n edit_menu.addAction(self._undo_manager.create_redo_action(edit_menu))\n\n def _disable(self):\n self._undo_manager = None\n\n self._mdi = None\n self._main_window = None\n\n raise NotImplementedError\n\n\nclass UndoManager(QObject):\n def __init__(self):\n super().__init__()\n\n self._undo_group = QUndoGroup()\n\n def create_undo_action(self, parent: QObject, prefix: str = '') -> QAction:\n return self._undo_group.createUndoAction(parent, prefix)\n\n def create_redo_action(self, parent: QObject, prefix: str = '') -> QAction:\n return self._undo_group.createRedoAction(parent, prefix)\n","sub_path":"vision-plugins/src/bsmu/vision/plugins/undo.py","file_name":"undo.py","file_ext":"py","file_size_in_byte":2024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"453015761","text":"import pandas\nimport numpy\n\n\nclass Graph(object):\n def __init__(self, size):\n self.size = size\n self.adjMatrix = [[0 for i in range(size)] for i in range(size)]\n\n def buildFromMatrix(self, matrix):\n self.adjMatrix = matrix\n if not self.isSimpleGraph:\n print(\"Podany graf nie jest grafem prostym\")\n return\n elif not self.isSymetric:\n print(\"Podany graf nie jest grafem nieskierowanym\")\n return\n return self\n\n def isSimpleGraph(self):\n for i in range(self.size):\n vertex_edges = 0\n vertex_row = self.adjMatrix[i]\n for j in range(self.size):\n if vertex_row[j] == 1:\n if i == j:\n return False\n vertex_edges = vertex_edges + 1\n if vertex_edges == 0:\n return False\n return True\n\n def isSymetric(self):\n for i in range(self.size):\n for j in range(self.size):\n if i == j:\n continue\n elif self.adjMatrix[i][j] != self.adjMatrix[j][i]:\n return False\n return True\n\n def addEdge(self, v1, v2):\n if self.isVertexInvalid(v1) or self.isVertexInvalid(v2):\n return\n if self.doesEdgeExist(v1, v2):\n print(\"Podana krawędź już istnieje\")\n return\n self.adjMatrix[v1][v2] = 1\n self.adjMatrix[v2][v1] = 1\n return self.getAdjacencyMatrix()\n\n def removeEdge(self, v1, v2):\n if self.isVertexInvalid(v1) or self.isVertexInvalid(v2):\n return\n if not self.doesEdgeExist(v1, v2):\n print(\"Podana krawędź nie istnieje\")\n return\n self.adjMatrix[v1][v2] = 0\n self.adjMatrix[v2][v1] = 0\n return self.getAdjacencyMatrix()\n\n def addVertex(self):\n self.size += 1\n for row in self.adjMatrix:\n row.append(0)\n self.adjMatrix.append([0 for i in range(self.size)])\n return self.getAdjacencyMatrix()\n\n def removeVertex(self, v):\n if self.isVertexInvalid(v):\n return\n self.removeEdgesAssociatedToVertex(v)\n self.removeRowFromMatrix(v)\n self.removeColumnFromMatrix(v)\n self.size -= 1\n return self.getAdjacencyMatrix()\n\n def removeEdgesAssociatedToVertex(self, v):\n for index in range(self.size):\n if self.adjMatrix[v][index] == 1:\n self.removeEdge(v, index)\n\n def removeRowFromMatrix(self, rowNum):\n del self.adjMatrix[rowNum]\n\n def removeColumnFromMatrix(self, colNum):\n for row in self.adjMatrix:\n del row[colNum]\n\n def findVertexDegree(self, v):\n degree = 0\n for index in range(self.size):\n if self.doesEdgeExist(v, index):\n if index == v:\n degree += 2\n else:\n degree += 1\n return degree\n\n def findMinGraphDegree(self):\n vertexDegree = self.findVertexDegree(0)\n if vertexDegree == 0:\n print(\"Minimalny stopień grafu: %d\" % vertexDegree)\n return vertexDegree\n else:\n for vertexNum in range(1, self.size):\n currentVertexDegree = self.findVertexDegree(vertexNum)\n if currentVertexDegree == 0:\n print(\"Minimalny stopień grafu: %d\" % vertexDegree)\n return vertexDegree\n elif currentVertexDegree < vertexDegree:\n vertexDegree = currentVertexDegree\n print(\"Minimalny stopień grafu: %d\" % vertexDegree)\n return vertexDegree\n \n def findMaxGraphDegree(self):\n vertexDegree = self.findVertexDegree(0)\n for vertexNum in range(1, self.size):\n currentVertexDegree = self.findVertexDegree(vertexNum)\n if currentVertexDegree > vertexDegree:\n vertexDegree = currentVertexDegree\n print(\"Maksymalny stopień grafu: %d\" % vertexDegree)\n return vertexDegree\n\n def findOddAndEvenVertexDegreesAmount(self):\n degrees = dict(\n even=0,\n odd=0\n )\n all_degrees = self.getAllDegrees()\n for degree in all_degrees:\n if degree % 2 == 0:\n degrees['even'] += 1\n else:\n degrees['odd'] += 1\n print(\"Wierzchołki parzystego stopnia: %d, nieparzystego: %d\" % (degrees['even'], degrees['odd']))\n return degrees\n\n def getAllDegrees(self):\n degrees = []\n for vertexNum in range(self.size):\n vertexDegree = self.findVertexDegree(vertexNum)\n degrees.append(vertexDegree)\n degrees.sort(reverse=True)\n return degrees\n\n def printAllDegrees(self):\n all_degrees = self.getAllDegrees()\n print(\"Stopnie: \", all_degrees)\n\n def getAllDegreesWithIndexes(self):\n degrees_indexes = {}\n for vertexNum in range(self.size):\n vertexDegree = self.findVertexDegree(vertexNum)\n degrees_indexes[vertexNum] = vertexDegree\n return degrees_indexes\n\n def getLastVertexIndex(self):\n return self.size - 1\n\n def getAdjacencyMatrix(self):\n return self.adjMatrix\n\n def isVertexInvalid(self, v):\n if not isinstance(v, int):\n print(\"Numery wierzchołków to liczby całkowite\")\n return True\n if v < 0 or v >= self.size:\n print(\"Podany wierzchołek %d nie istnieje. Numery wierzchołków są w zakresie 0 - %d\" % (v, self.size - 1))\n return True\n return False\n\n def doesEdgeExist(self, v1, v2):\n if self.adjMatrix[v1][v2] == 1:\n return True\n return False\n\n def toString(self):\n print(\"\\n\\nMacierz sąsiedztwa:\\n\")\n for row in self.adjMatrix:\n for value in row:\n print('{0:5}'.format(value), end=' ')\n print()\n print(\"Rozmiar macierzy: [ %d x %d ]\\n\" % (len(self.adjMatrix), len(self.adjMatrix[0])))\n return\n\n # saves adjacency matrix to csv file\n def writeToCsv(self):\n dfStringList = []\n for row in self.adjMatrix:\n dfStringList.append(', '.join(map(str, row)))\n dfString = '; '.join(map(str, dfStringList))\n numpyMatrix = numpy.matrix(dfString)\n dataframe = pandas.DataFrame(numpyMatrix)\n print(dataframe)\n dataframe.to_csv('./graph.csv')\n","sub_path":"zad2/classes/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":6510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"424329842","text":"# -*- coding: utf-8 -*-\n\nactionIndex_response = {\n u\"status\": 200,\n u\"items\": [\n {u\"id\": u\"movie\", u\"title\": u\"Фильмы\"},\n {u\"id\": u\"serial\", u\"title\": u\"Сериалы\"},\n {u\"id\": u\"tvshow\", u\"title\": u\"ТВ шоу\"},\n {u\"id\": u\"4k\", u\"title\": u\"4K\"},\n {u\"id\": u\"3d\", u\"title\": u\"3D\"},\n {u\"id\": u\"concert\", u\"title\": u\"Концерты\"},\n {u\"id\": u\"documovie\", u\"title\": u\"Документальные фильмы\"},\n {u\"id\": u\"docuserial\", u\"title\": u\"Документальные сериалы\"},\n ],\n}\n\nactionPlay_response = {\n u\"status\": 200,\n u\"item\": {\n u\"rating\": 3,\n u\"videos\": [\n {\n u\"files\": [\n {\n u\"url\": {\n u\"hls\": u\"https://example.com/hls/480\",\n u\"hls2\": u\"https://example.com/hls2/480\",\n u\"http\": u\"https://example.com/http/480\",\n u\"hls4\": u\"https://example.com/hls4/480\",\n },\n u\"h\": 304,\n u\"quality\": u\"480p\",\n u\"w\": 720,\n },\n {\n u\"url\": {\n u\"hls\": u\"https://example.com/hls/720\",\n u\"hls2\": u\"https://example.com/hls2/720\",\n u\"http\": u\"https://example.com/http/720\",\n u\"hls4\": u\"https://example.com/hls4/720\",\n },\n u\"h\": 540,\n u\"quality\": u\"720p\",\n u\"w\": 1280,\n },\n {\n u\"url\": {\n u\"hls\": u\"https://example.com/hls/1080\",\n u\"hls2\": u\"https://example.com/hls2/1080\",\n u\"http\": u\"https://example.com/http/1080\",\n u\"hls4\": u\"https://example.com/hls4/1080\",\n },\n u\"h\": 808,\n u\"quality\": u\"1080p\",\n u\"w\": 1912,\n },\n ],\n u\"title\": \"\",\n u\"watching\": {u\"status\": -1, u\"time\": 0},\n u\"number\": 1,\n u\"id\": 22000,\n u\"ac3\": 0,\n u\"tracks\": 3,\n u\"duration\": 5631,\n u\"watched\": -1,\n u\"thumbnail\": u\"https://example.com/480x270.jpg\",\n u\"subtitles\": [],\n }\n ],\n u\"imdb\": 306841,\n u\"year\": 2003,\n u\"duration\": {u\"average\": 5631, u\"total\": 5631},\n u\"bookmarks\": [],\n u\"ac3\": 0,\n u\"quality\": 1080,\n u\"id\": 8086,\n u\"kinopoisk\": 300,\n u\"plot\": u\"Тринадцатилетняя школьница Лиззи Магуайер и ее приятели Гордо, Кейт и Эсан собираются оттянуться по полной программе во время их поездки с классом в Италию.\\r\\nНо там случается весьма неожиданное происшествие: девочку ошибочно принимают за итальянскую поп-звезду Изабеллу, да к тому же девушка влюбляется в бывшего дружка Изабеллы Паоло. Когда родители Лизи обо всем узнают, они вместе с ее братом Мэттом срочно вылетают в Италию.\\r\\nНо Лиззи уже не та закомплексованная девочка-подросток, кем была раньше, она до такой степени вжилась в роль певицы, что и на самом деле стала самой настоящей звездой.\",\n u\"genres\": [\n {u\"id\": 1, u\"title\": u\"Комедия\"},\n {u\"id\": 6, u\"title\": u\"Семейный\"},\n {u\"id\": 8, u\"title\": u\"Приключения\"},\n {u\"id\": 10, u\"title\": u\"Мелодрама\"},\n {u\"id\": 19, u\"title\": u\"Музыкальный\"},\n ],\n u\"title\": u\"Лиззи Магуайр / The Lizzie McGuire Movie\",\n u\"comments\": 2,\n u\"advert\": False,\n u\"imdb_votes\": 30319,\n u\"subtype\": \"\",\n u\"type\": u\"movie\",\n u\"views\": 31,\n u\"director\": u\"Джим Фолл\",\n u\"finished\": False,\n u\"posters\": {\n u\"small\": u\"https://example.com/small/8086.jpg\",\n u\"big\": u\"https://example.com/big/8086.jpg\",\n u\"medium\": u\"https://example.com/medium/8086.jpg\",\n },\n u\"langs\": 3,\n u\"kinopoisk_votes\": 8307,\n u\"rating_votes\": u\"7\",\n u\"subtitles\": u\"0\",\n u\"kinopoisk_rating\": 6.322,\n u\"countries\": [{u\"id\": 1, u\"title\": u\"США\"}],\n u\"tracklist\": [],\n u\"rating_percentage\": u\"71.43\",\n u\"cast\": u\"Хилари Дафф, Адам Лэмберг, Халли Морган, Роберт Кэрредин, Джейк Томас, Эшли Брилло, Клэйтон Снайдер, Алекс Борштейн, Яни Гельман, Брендан Келли, Карли Шредер, Дэниэл Эскобар, Джоди Расикот, Питер Келамис, Терра С. Маклеод\",\n u\"poor_quality\": False,\n u\"imdb_rating\": 5.4,\n u\"voice\": \"\",\n u\"trailer\": {u\"url\": u\"http://www.youtube.com/watch?v=eIm8g4IA_1Y\", u\"id\": u\"eIm8g4IA_1Y\"},\n },\n}\n\n\nactionItems_response = {\n u\"status\": 200,\n u\"items\": [\n {\n u\"rating\": 0,\n u\"imdb\": 7544820,\n u\"year\": 2017,\n u\"duration\": {u\"average\": 5946, u\"total\": 5946},\n u\"quality\": 720,\n u\"id\": 35431,\n u\"kinopoisk\": 726439,\n u\"plot\": u\"Авторы, участники и продюсеры рассказывают о создании Шоу Дана Карви. Неприемлемые для аудитории праймтайма ЭйБиСи отрывки и образы, продержались в эфире всего 8 выпусков, но открыли миру команду талантливых актеров, сценаристов, писателей и продюсеров.\",\n u\"genres\": [{u\"id\": 82, u\"title\": u\"Кино\"}],\n u\"title\": u\"Слишком смешные, чтобы провалиться. Жизнь и смерть шоу Дана Карви / Too Funny to Fail: The Life & Death of The Dana Carvey Show\",\n u\"comments\": 0,\n u\"advert\": True,\n u\"imdb_votes\": 694,\n u\"subtype\": \"\",\n u\"type\": u\"documovie\",\n u\"views\": 0,\n u\"director\": u\"Джош Гринбаум\",\n u\"finished\": False,\n u\"posters\": {\n u\"small\": u\"https://example.com/small/35431.jpg\",\n u\"big\": u\"https://example.com/big/35431.jpg\",\n u\"medium\": u\"https://example.com/medium/35431.jpg\",\n },\n u\"langs\": 1,\n u\"kinopoisk_votes\": 25,\n u\"rating_votes\": u\"0\",\n u\"subtitles\": u\"0\",\n u\"kinopoisk_rating\": 0,\n u\"countries\": [{u\"id\": 1, u\"title\": u\"США\"}],\n u\"tracklist\": [],\n u\"rating_percentage\": u\"0\",\n u\"cast\": \"\",\n u\"poor_quality\": False,\n u\"imdb_rating\": 7.3,\n u\"voice\": None,\n u\"trailer\": None,\n },\n {\n u\"rating\": 0,\n u\"imdb\": None,\n u\"year\": 2018,\n u\"duration\": {u\"average\": 5606, u\"total\": 5606},\n u\"quality\": 1080,\n u\"id\": 35584,\n u\"kinopoisk\": 1181557,\n u\"plot\": u\"Детство вспоминается беспечным отрезком жизни лишь с\\xa0высоты прожитых лет.. Но\\xa0для детей это\\xa0время, когда они\\xa0впервые сталкиваются с\\xa0ответственностью, принимают решения, учатся признавать ошибки, прощать, любить. Киноальманах 11+ подходит для\\xa0просмотра всей семьёй. Порой бывает сложно рассказать своим детям о\\xa0чем-то важном для\\xa0себя и\\xa0для них. В\\xa0сборник короткометражек \\xab11+\\xbb вошли три\\xa0очень разных фильма, которые помогут пережить важный опыт взросления, почувствовать то, о\\xa0чем сложно сказать.\",\n u\"genres\": [\n {u\"id\": 1, u\"title\": u\"Комедия\"},\n {u\"id\": 6, u\"title\": u\"Семейный\"},\n {u\"id\": 10, u\"title\": u\"Мелодрама\"},\n ],\n u\"title\": u\"11+\",\n u\"comments\": 0,\n u\"advert\": True,\n u\"imdb_votes\": None,\n u\"subtype\": \"\",\n u\"type\": u\"movie\",\n u\"views\": 0,\n u\"director\": u\"Мария Сопова\",\n u\"finished\": False,\n u\"posters\": {\n u\"small\": u\"https://example.com/small/35584.jpg\",\n u\"big\": u\"https://example.com/big/35584.jpg\",\n u\"medium\": u\"https://example.com/medium/35584.jpg\",\n },\n u\"langs\": 1,\n u\"kinopoisk_votes\": 0,\n u\"rating_votes\": u\"0\",\n u\"subtitles\": u\"0\",\n u\"kinopoisk_rating\": 0,\n u\"countries\": [{u\"id\": 2, u\"title\": u\"Россия\"}],\n u\"tracklist\": [],\n u\"rating_percentage\": u\"0\",\n u\"cast\": u\"Александр Алёшкин, Елена Лямина, Михаил Новоженин, Дмитрий Белоцерковский, Татьяна Плетнева, Сергей Новоженин, Дарья Хитарова, Ксения Голубева, Никита Любимов, Полина Тарасова\",\n u\"poor_quality\": False,\n u\"imdb_rating\": 0,\n u\"voice\": None,\n u\"trailer\": None,\n },\n {\n u\"rating\": 9,\n u\"imdb\": None,\n u\"year\": 2011,\n u\"duration\": {u\"average\": 2838.287598944591, u\"total\": 1075711},\n u\"quality\": 480,\n u\"id\": 16015,\n u\"kinopoisk\": 762373,\n u\"plot\": u\"Каждые выходные двое ведущих отправляются в различные города мира. По правилам программы один ведущий должен прожить субботу и воскресенье на 100 долларов, а второй может тратить неограниченные средства, которые хранятся на золотой карте. Чтобы решить, кто из них будет жить как миллионер, а кто будет учиться выживанию, ведущие перед каждым путешествиям бросают монету, и каждый раз всё решает Орёл или решка.\",\n u\"genres\": [{u\"id\": 112, u\"title\": u\"Путешествия\"}],\n u\"subscribed\": False,\n u\"title\": u\"Орёл и решка\",\n u\"comments\": 1,\n u\"in_watchlist\": False,\n u\"advert\": False,\n u\"imdb_votes\": 59,\n u\"subtype\": \"\",\n u\"type\": u\"tvshow\",\n u\"views\": 63612,\n u\"director\": \"\",\n u\"finished\": False,\n u\"posters\": {\n u\"small\": u\"https://example.com/small/16015.jpg\",\n u\"big\": u\"https://example.com/big/16015.jpg\",\n u\"medium\": u\"https://example.com/medium/16015.jpg\",\n },\n u\"langs\": 381,\n u\"kinopoisk_votes\": 19205,\n u\"rating_votes\": u\"13\",\n u\"subtitles\": u\"0\",\n u\"kinopoisk_rating\": 8.323,\n u\"countries\": [{u\"id\": 23, u\"title\": u\"Украина\"}],\n u\"tracklist\": [],\n u\"rating_percentage\": u\"84.62\",\n u\"cast\": u\"Андрей Бедняков, Алан Бадоев, Жанна Бадоева, Анастасия Короткая, Леся Никитюк, Николай Серга, Регина Тодоренко, Евгений Синельников\",\n u\"poor_quality\": False,\n u\"imdb_rating\": 8.4,\n u\"voice\": None,\n u\"trailer\": None,\n },\n {\n u\"rating\": 13,\n u\"imdb\": 3314218,\n u\"year\": 2015,\n u\"duration\": {u\"average\": 2518.5, u\"total\": 95703},\n u\"quality\": 480,\n u\"id\": 10892,\n u\"kinopoisk\": 807444,\n u\"plot\": u\"Настоящий хаос окружает съемки любовных реалити-шоу. За кулисами может оказаться всё гораздо интереснее, чем в эфире. В погоне за рейтингами приходится всячески манипулировать конкурсантами, чтобы те выдали необходимый \\xabматериал\\xbb для шоу. А продюсер может уволить кого угодно за малейший недочёт.\",\n u\"genres\": [{u\"id\": 9, u\"title\": u\"Драма\"}],\n u\"subscribed\": False,\n u\"title\": u\"Нереально / UnREAL\",\n u\"comments\": 5,\n u\"in_watchlist\": False,\n u\"advert\": True,\n u\"imdb_votes\": 11148,\n u\"subtype\": \"\",\n u\"type\": u\"serial\",\n u\"views\": 6921,\n u\"director\": u\"Питер О’Фаллон, Ута Бризвитц, Лев Л. Спиро, Питер Уэрнер, Адам Кэйн, Дэвид Соломон, Шири Эпплби, Дженис Кук-Леонард, Сара Шапиро, Зинга Стюарт\",\n u\"finished\": False,\n u\"posters\": {\n u\"small\": u\"https://example.com/small/10892.jpg\",\n u\"big\": u\"https://example.com/big/10892.jpg\",\n u\"medium\": u\"https://example.com/medium/10892.jpg\",\n },\n u\"langs\": 84,\n u\"kinopoisk_votes\": 1634,\n u\"rating_votes\": u\"15\",\n u\"subtitles\": u\"0\",\n u\"kinopoisk_rating\": 7.292,\n u\"countries\": [{u\"id\": 1, u\"title\": u\"США\"}],\n u\"tracklist\": [],\n u\"rating_percentage\": u\"93.33\",\n u\"cast\": u\"Шири Эпплби, Констанс Зиммер, Крэйг Бирко, Джеффри Бауэр-Чепман, Джош Келли, Бреннан Эллиотт, Женевьев Бюкнер, Эми Хилл, Фредди Строма, Моника Барбаро, Джоанна Э. Брэдди, Б.Дж. Бритт, Натали Келли, Кимберли Матула, Майкл Рэди\",\n u\"poor_quality\": False,\n u\"imdb_rating\": 7.9,\n u\"voice\": u\"Gears Media, IdeaFilm (3,4 сезон)\",\n u\"trailer\": None,\n },\n {\n u\"rating\": 0,\n u\"imdb\": None,\n u\"year\": 2003,\n u\"duration\": {u\"average\": 1832, u\"total\": 9160},\n u\"quality\": 480,\n u\"id\": 35590,\n u\"kinopoisk\": None,\n u\"plot\": u\"Тысячи лет природа и сам человек создавали и разрушали целые культуры и цивилизации. Многое из того, что веками олицетворяло собой облик земной расы, ушло безвозвратно или породило множество тайн и загадок, обросших невероятным количеством легенд и преданий. Многие поколения археологов, историков и просто ловцов удачи пытаются на свой страх и риск найти и раскрыть некоторые из них.\",\n u\"genres\": [{u\"id\": 51, u\"title\": u\"История\"}],\n u\"subscribed\": False,\n u\"title\": u\"Античные секреты / The Travel Channel. Ancient Secrets\",\n u\"comments\": 0,\n u\"in_watchlist\": False,\n u\"advert\": False,\n u\"imdb_votes\": None,\n u\"subtype\": \"\",\n u\"type\": u\"docuserial\",\n u\"views\": 17,\n u\"director\": u\"Энн Кэролл, Джозеф Хиннеген, Марк Мастерс\",\n u\"finished\": True,\n u\"posters\": {\n u\"small\": u\"https://example.com/small/35590.jpg\",\n u\"big\": u\"https://example.com/big/35590.jpg\",\n u\"medium\": u\"https://example.com/medium/35590.jpg\",\n },\n u\"langs\": 3,\n u\"kinopoisk_votes\": None,\n u\"rating_votes\": u\"0\",\n u\"subtitles\": u\"0\",\n u\"kinopoisk_rating\": None,\n u\"countries\": [{u\"id\": 1, u\"title\": u\"США\"}],\n u\"tracklist\": [],\n u\"rating_percentage\": u\"0\",\n u\"cast\": \"\",\n u\"poor_quality\": False,\n u\"imdb_rating\": None,\n u\"voice\": None,\n u\"trailer\": None,\n },\n ],\n u\"pagination\": {\n # u\"current\": 1,\n # u\"total_items\": 27979,\n # u\"total\": 1399,\n # u\"perpage\": 20\n },\n}\n\n\nactionView_seasons_response = {\n u\"status\": 200,\n u\"item\": {\n u\"rating\": 11,\n u\"seasons\": [\n {\n u\"episodes\": [\n {\n u\"files\": [\n {\n u\"url\": {\n u\"hls\": u\"https://example.com/hls/480p\",\n u\"hls2\": u\"https://example.com/hls2/480p\",\n u\"http\": u\"https://example.com/http/480p\",\n u\"hls4\": u\"https://example.com/hls4/480p\",\n },\n u\"h\": 406,\n u\"quality\": u\"480p\",\n u\"w\": 720,\n },\n {\n u\"url\": {\n u\"hls\": u\"https://example.com/hls/720p\",\n u\"hls2\": u\"https://example.com/hls2/720p\",\n u\"http\": u\"https://example.com/http/720p\",\n u\"hls4\": u\"https://example.com/hls4/720p\",\n },\n u\"h\": 406,\n u\"quality\": u\"720p\",\n u\"w\": 960,\n },\n ],\n u\"title\": u\"Большой взрыв\",\n u\"watching\": {u\"status\": -1, u\"time\": 0},\n u\"number\": 1,\n u\"id\": 128671,\n u\"ac3\": 0,\n u\"tracks\": 1,\n u\"duration\": 2628,\n u\"watched\": -1,\n u\"thumbnail\": u\"https://example.com/480x270.jpg\",\n u\"subtitles\": [],\n }\n ],\n u\"watching\": {u\"status\": -1},\n u\"number\": 1,\n u\"title\": u\"1 сезон\",\n }\n ],\n u\"imdb\": 1832668,\n u\"year\": 2010,\n u\"duration\": {u\"average\": 2601.9166666666665, u\"total\": 124892},\n u\"bookmarks\": [],\n u\"ac3\": 0,\n u\"quality\": 480,\n u\"id\": 9475,\n u\"kinopoisk\": 615680,\n u\"plot\": u\"Это история о создании всего в этом мире. Программа исследует, как Вселенная возникла из ничего, и как она выросла с точки незначительно меньше, чем атомные частицы, до огромного космоса.\",\n u\"genres\": [{u\"id\": 60, u\"title\": u\"Космос\"}, {u\"id\": 81, u\"title\": u\"Вселенная\"}],\n u\"subscribed\": False,\n u\"title\": u\"Как устроена Вселенная / How the Universe Works\",\n u\"comments\": 0,\n u\"in_watchlist\": False,\n u\"advert\": False,\n u\"imdb_votes\": 4238,\n u\"subtype\": u\"\",\n u\"type\": u\"docuserial\",\n u\"views\": 3213,\n u\"director\": u\"Адам Уорнер, Питер Чинн, Луиз Сай, Лорни Тауненд, Шон Тревисик, Кейт Дарт, Джордж Харрис, Алекс Хирл\",\n u\"finished\": False,\n u\"posters\": {\n u\"small\": u\"https://example.com/small/9475.jpg\",\n u\"big\": u\"https://example.com/big/9475.jpg\",\n u\"medium\": u\"https://example.com/medium/9475.jpg\",\n },\n u\"langs\": 49,\n u\"kinopoisk_votes\": 2848,\n u\"rating_votes\": u\"13\",\n u\"subtitles\": u\"\",\n u\"kinopoisk_rating\": 8.739,\n u\"countries\": [{u\"id\": 1, u\"title\": u\"США\"}],\n u\"tracklist\": [],\n u\"rating_percentage\": u\"92.31\",\n u\"cast\": u\"Фил Плейт, Майк Роу, Мишель Таллер, Лоуренс Краусс, Мичио Каку, Ричард Линтерн, Дэн Дарда, Джофф Марси, Эрик Деллумс, Крис МакКэй, Дэвид Гринспун, Алекс Филиппенко, Дэвид Спергел, Питер Шульц, Шон Кэрролл\",\n u\"poor_quality\": False,\n u\"imdb_rating\": 9,\n u\"voice\": u\"\",\n u\"trailer\": None,\n },\n}\n\nactionView_without_seasons_response = {\n u\"status\": 200,\n u\"item\": {\n u\"rating\": 1,\n u\"videos\": [\n {\n u\"files\": [\n {\n u\"url\": {\n u\"hls\": u\"https://example.com/hls/480\",\n u\"hls2\": u\"https://example.com/hls2/480\",\n u\"http\": u\"https://example.com/http/480\",\n u\"hls4\": u\"https://example.com/hls4/480\",\n },\n u\"h\": 400,\n u\"quality\": u\"480p\",\n u\"w\": 720,\n }\n ],\n u\"title\": u\"От пещерных людей до королей\",\n u\"watching\": {u\"status\": -1, u\"time\": 0},\n u\"number\": 1,\n u\"id\": 520081,\n u\"ac3\": 0,\n u\"tracks\": 1,\n u\"duration\": 2635,\n u\"watched\": -1,\n u\"thumbnail\": u\"https://example.com/480x270.jpg\",\n u\"subtitles\": [],\n },\n {\n u\"files\": [\n {\n u\"url\": {\n u\"hls\": u\"https://example.com/hls/480\",\n u\"hls2\": u\"https://example.com/hls2/480\",\n u\"http\": u\"https://example.com/http/480\",\n u\"hls4\": u\"https://example.com/hls4/480\",\n },\n u\"h\": 400,\n u\"quality\": u\"480p\",\n u\"w\": 720,\n }\n ],\n u\"title\": u\"Яблоко раздора\",\n u\"watching\": {u\"status\": -1, u\"time\": 0},\n u\"number\": 2,\n u\"id\": 520078,\n u\"ac3\": 0,\n u\"tracks\": 1,\n u\"duration\": 2615,\n u\"watched\": -1,\n u\"thumbnail\": u\"https://example.com/480x270.jpg\",\n u\"subtitles\": [],\n },\n ],\n u\"imdb\": 5848928,\n u\"year\": 2016,\n u\"duration\": {u\"average\": 5250, u\"total\": 5250},\n u\"bookmarks\": [],\n u\"ac3\": 0,\n u\"quality\": 480,\n u\"id\": 35467,\n u\"kinopoisk\": None,\n u\"plot\": u\"Это были удивительные люди, рождённые белыми скалами и синем морем. Они изобрели демократию, отделили логику от разума, они передали глубочайшие душевные переживания в своих драмах, а совершенство человеческого тела - в спорте и искусствах. Греки - это люди, которые создали наш мир.\",\n u\"genres\": [{u\"id\": 51, u\"title\": u\"История\"}],\n u\"title\": u\"NG: Древние греки / The Greeks\",\n u\"comments\": 0,\n u\"advert\": False,\n u\"imdb_votes\": None,\n u\"subtype\": u\"multi\",\n u\"type\": u\"documovie\",\n u\"views\": 41,\n u\"director\": u\"Кэтрин Еллоз\",\n u\"finished\": False,\n u\"posters\": {\n u\"small\": u\"https://example.com/small/35467.jpg\",\n u\"big\": u\"https://example.com/big/35467.jpg\",\n u\"medium\": u\"https://example.com/medium/35467.jpg\",\n },\n u\"langs\": 2,\n u\"kinopoisk_votes\": None,\n u\"rating_votes\": u\"1\",\n u\"subtitles\": u\"0\",\n u\"kinopoisk_rating\": None,\n u\"countries\": [{u\"id\": 1, u\"title\": u\"США\"}],\n u\"tracklist\": [],\n u\"rating_percentage\": u\"100\",\n u\"cast\": u\"Беттани Хьюз\",\n u\"poor_quality\": False,\n u\"imdb_rating\": None,\n u\"voice\": None,\n u\"trailer\": None,\n },\n}\n\n\nwatching_info_response_with_seasons = {\n u\"status\": 200,\n u\"item\": {\n u\"watched\": 0,\n u\"seasons\": [\n {\n u\"status\": -1,\n u\"watched\": 0,\n u\"episodes\": [\n {\n u\"status\": -1,\n u\"updated\": None,\n u\"title\": \"\\u0411\\u043e\\u043b\\u044c\\u0448\\u043e\\u0439 \\u0432\\u0437\\u0440\\u044b\\u0432\",\n u\"number\": 1,\n u\"time\": 0,\n u\"duration\": 2628,\n u\"id\": 128671,\n }\n ],\n u\"id\": 1147,\n u\"number\": 1,\n }\n ],\n u\"type\": u\"docuserial\",\n u\"id\": 9475,\n u\"title\": \"\\u041a\\u0430\\u043a \\u0443\\u0441\\u0442\\u0440\\u043e\\u0435\\u043d\\u0430 \\u0412\\u0441\\u0435\\u043b\\u0435\\u043d\\u043d\\u0430\\u044f / How the Universe Works\",\n },\n}\n\nwatching_info_response_without_seasons = {\n u\"status\": 200,\n u\"item\": {\n u\"status\": -1,\n u\"type\": u\"documovie\",\n u\"id\": 35467,\n u\"videos\": [\n {\n u\"status\": -1,\n u\"updated\": u\"None\",\n u\"title\": \"\\u041e\\u0442 \\u043f\\u0435\\u0449\\u0435\\u0440\\u043d\\u044b\\u0445 \\u043b\\u044e\\u0434\\u0435\\u0439 \\u0434\\u043e \\u043a\\u043e\\u0440\\u043e\\u043b\\u0435\\u0439\",\n u\"number\": 1,\n u\"time\": 0,\n u\"duration\": 2635,\n u\"id\": 520081,\n },\n {\n u\"status\": -1,\n u\"updated\": u\"None\",\n u\"title\": \"\\u042f\\u0431\\u043b\\u043e\\u043a\\u043e \\u0440\\u0430\\u0437\\u0434\\u043e\\u0440\\u0430\",\n u\"number\": 2,\n u\"time\": 0,\n u\"duration\": 2615,\n u\"id\": 520078,\n },\n ],\n u\"title\": u\"NG: \\u0414\\u0440\\u0435\\u0432\\u043d\\u0438\\u0435 \\u0433\\u0440\\u0435\\u043a\\u0438 / The Greeks\",\n },\n}\n","sub_path":"tests/responses.py","file_name":"responses.py","file_ext":"py","file_size_in_byte":28121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"117715267","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport pickle\nimport numpy as np\n\nhome_path = '/home/franchesoni'\ndict_path = '/marino/data/MORPH/results/album1/extracted_dict.pickle'\n# Load dict / Cargo diccionario\ndict_path = home_path+dict_path\ndictionary = pickle.load(open(dict_path, 'rb'))\n# Convert to np array / Se pasa a np array\nlabels = np.asarray(list(dictionary.keys()))\nvectors = np.asarray(list(dictionary.values()))[:, 0, :].T\n\n# Take the norm of the difference between a vector and all other vectors\n# Calculo la norma de la resta de un vector contra todos los demas\nsubs = np.empty((len(labels), len(labels)))\nfor i in range(len(labels)):\n subs[i,:] = np.linalg.norm(np.expand_dims(vectors[:,i],axis=-1)-vectors,\n axis=0)\n\n# Thresholdsold definition / Definicion de threshes\nthresholds = np.linspace(0, 4, 50)\n# Get indices / Indices de etiquetas de jovenes y viejos\nlabels_young = [('_y/' in label) for label in labels]\nlabels_old = [('_y/' not in label) for label in labels]\n\n# Initialization / Inicializacion de acumuladores en 0\ntp, fp = np.zeros(len(thresholds)), np.zeros(len(thresholds))\ntn, fn = np.zeros(len(thresholds)), np.zeros(len(thresholds))\nfor i, thresh in enumerate(thresholds): # for each thresh / para cada umbral\n classification = subs < thresh # classify / clasifico\n counter = 0 # counter of total comparisons / total de comparaciones\n for young in labels[labels_young]: # for each young label\n _, a = np.unique(labels == young, return_index=True)\n index = a[1] # find its index / encuentro indice correspondiente\n\n # Find old version indices / Encuentro los indices de su version vieja\n old_version_indices = np.array([(label.split('/')[0] ==\n (young.split('/')[0][0:-2]))\n for label in labels])\n counter += np.sum(old_version_indices)\n # True positives / Sumo las veces que dio true en su version vieja\n tp[i] += np.sum(classification[:, index] * old_version_indices)\n # True negatives\n tn[i] += np.sum((~classification[:, index]) * labels_old\n * (~old_version_indices))\n # False positives / Sumo las veces que dio true fuera de su version vieja\n fp[i] += np.sum(classification[:, index] * labels_old * (~old_version_indices))\n # False negatives\n fn[i] += np.sum(~(classification[:, index]) * old_version_indices)\n\n#%% METRICS\ndef fscore(beta=1):\n fbeta = np.empty_like(precision)\n for i in range(len(precision)):\n if (precision[i]+recall[i]) != 0:\n fbeta[i] = (1+beta**2) * ((precision[i]*recall[i])\n / (beta**2*precision[i] + recall[i]))\n else:\n fbeta[i] = 0\n return fbeta\n\n# Probabilities\npd = tp / counter # probability of detection\npfa = fp / (np.sum(labels_young)*np.sum(labels_old) - counter) # false alarm\n\n# total, acc, precision, recall and fscore\ntotal = (np.sum(labels_young)*np.sum(labels_old))\naccuracy = (tp+tn)/(tp+tn+fp+fn)\nprecision, recall, = np.empty_like(accuracy), np.empty_like(accuracy)\nfor i in range(len(precision)):\n precision[i] = tp[i]/(tp[i]+fp[i]) if (tp[i]+fp[i]) != 0 else 0\n recall[i] = tp[i]/(tp[i]+fn[i]) if (tp[i]+fn[i]) != 0 else 0\nf1 = fscore()\n\n# matching - non_matching pairs\nmm = tp/(tp+fn) # match - match\nnn = tn/(tn+fp) # non_match - non_match\nmn = fp/(tn+fp) # match - non_match\nnm = fn/(tp+fn) # non_match - match\n\n# calculate accuracy as reported in reference paper\naccuracy_like_reference = (mm + nn) / 2\nbesti = np.argmax(accuracy_like_reference)\nres_matrix = np.array([[mm[besti], mn[besti]], [nm[besti], nn[besti]]])\n\n#%% Report results and plot\nprint('precision:', precision[besti])\nprint('recall:', recall[besti])\nprint('accuracy:', accuracy[besti])\nprint('f1:', f1[besti])\nprint(res_matrix)\nprint('accuracy as in the paper', accuracy_like_reference[besti])\n\nimport matplotlib.pyplot as plt\n# ROC CURVE\nplt.close('all'); plt.figure()\nplt.plot(pfa, pd, 'r')\nplt.title('ROC')\nplt.ylabel('PD')\nplt.xlabel('PFA')\nplt.grid()\n# Metrics vs threshold\nplt.figure()\nplt.plot(precision)\nplt.plot(recall)\nplt.plot(accuracy)\nplt.plot(f1)\nplt.legend(('precision', 'recall', 'accuracy', 'f1'))","sub_path":"evaluate_performance.py","file_name":"evaluate_performance.py","file_ext":"py","file_size_in_byte":4286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"296438120","text":"import numpy as np\r\nimport h5py\r\nimport matplotlib.pyplot as plt\r\nimport scipy\r\nfrom PIL import Image\r\nfrom scipy import ndimage\r\nfrom lr_utils import *\r\nimport skimage\r\n\r\n# Loading the data (cat/non-cat)\r\ntrain_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()\r\n\r\n\r\n# Example of a picture\r\n# index = 25\r\n# Each line of your train_set_x_orig and test_set_x_orig is an array representing an image.\r\n# example = train_set_x_orig[index]\r\n# plt.imshow(train_set_x_orig[index])\r\n# plt.show()\r\n# np.squeeze()函数可以删除数组形状中的单维度条目,即把shape中为1的维度去掉,但是对非单维的维度不起作用。\r\n# 利用squeeze()函数将表示向量的数组转换为秩为1的数组\r\n# print (\"y = \" + str(train_set_y[:, index]) + \", it's a '\" + \\\r\n# classes[np.squeeze(train_set_y[:, index])].decode(\"utf-8\") + \"' picture.\")\r\n\r\nm_train = train_set_x_orig.shape[0]\r\nm_test = test_set_x_orig.shape[0]\r\nnum_px = train_set_x_orig.shape[2]\r\n\r\nprint (\"Number of training examples: m_train = \" + str(m_train))\r\nprint (\"Number of testing examples: m_test = \" + str(m_test))\r\nprint (\"Height/Width of each image: num_px = \" + str(num_px))\r\nprint (\"Each image is of size: (\" + str(num_px) + \", \" + str(num_px) + \", 3)\")\r\nprint (\"train_set_x shape: \" + str(train_set_x_orig.shape))\r\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\r\nprint (\"test_set_x shape: \" + str(test_set_x_orig.shape))\r\nprint (\"test_set_y shape: \" + str(test_set_y.shape))\r\n\r\n# Reshape the training and test data sets so that images of size (num_px, num_px, 3) are \r\n# flattened into single vectors of shape (num_px * num_px * 3, 1).\r\n\r\n# Reshape the training and test examples\r\nprint(\"\\nReshape...\")\r\ntrain_set_x_flatten = train_set_x_orig.reshape(train_set_x_orig.shape[0], -1).T\r\ntest_set_x_flatten = test_set_x_orig.reshape(test_set_x_orig.shape[0], -1).T\r\n\r\nprint (\"train_set_x_flatten shape: \" + str(train_set_x_flatten.shape))\r\nprint (\"train_set_y shape: \" + str(train_set_y.shape))\r\nprint (\"test_set_x_flatten shape: \" + str(test_set_x_flatten.shape))\r\nprint (\"test_set_y shape: \" + str(test_set_y.shape))\r\nprint (\"sanity check after reshaping: \" + str(train_set_x_flatten[0:5,0]))\r\n\r\n# One common preprocessing step in machine learning is to center and standardize your dataset, \r\n# meaning that you substract the mean of the whole numpy array from each example, \r\n# and then divide each example by the standard deviation of the whole numpy array. \r\n# But for picture datasets, it is simpler and more convenient and works almost as well to \r\n# just divide every row of the dataset by 255 (the maximum value of a pixel channel).\r\n\r\nprint(\"\\nCenter and standardize dataset...\")\r\ntrain_set_x = train_set_x_flatten/255.\r\ntest_set_x = test_set_x_flatten/255.\r\n\r\n# 调用模型进行训练与预测\r\n# print(\"==============================================\")\r\n# d = model(train_set_x, train_set_y, test_set_x, test_set_y, \\\r\n# num_iterations = 2000, learning_rate = 0.005, print_cost = True)\r\n\r\n# Example of a picture that was wrongly classified.\r\n# index = 1\r\n# plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3)))\r\n# print (\"y = \" + str(test_set_y[0,index]) + \", you predicted that it is a \\\"\" + \\\r\n# classes[int(d[\"Y_prediction_test\"][0,index])].decode(\"utf-8\") + \"\\\" picture.\")\r\n#plt.show()\r\n\r\n# Plot learning curve (with costs)\r\n# costs = np.squeeze(d['costs'])\r\n# plt.plot(costs)\r\n# plt.ylabel('cost')\r\n# plt.xlabel('iterations (per hundreds)')\r\n# plt.title(\"Learning rate =\" + str(d[\"learning_rate\"]))\r\n# plt.show()\r\n\r\nlearning_rates = [0.01, 0.001, 0.0001]\r\nmodels = {}\r\nfor i in learning_rates:\r\n print (\"learning rate is: \" + str(i))\r\n models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)\r\n print ('\\n' + \"-------------------------------------------------------\" + '\\n')\r\n\r\nfor i in learning_rates:\r\n plt.plot(np.squeeze(models[str(i)][\"costs\"]), label= str(models[str(i)][\"learning_rate\"]))\r\n\r\nplt.ylabel('cost')\r\nplt.xlabel('iterations')\r\n\r\nlegend = plt.legend(loc='upper center', shadow=True)\r\nframe = legend.get_frame()\r\nframe.set_facecolor('0.90')\r\nplt.show()\r\n\r\n# # testing every func\r\n# print (\"sigmoid([0, 2]) = \" + str(sigmoid(np.array([0,2]))))\r\n\r\n# dim = 2\r\n# w, b = initialize_with_zeros(dim)\r\n# print (\"w = \" + str(w))\r\n# print (\"b = \" + str(b))\r\n\r\n# w, b, X, Y = np.array([[1],[2]]), 2, np.array([[1,2],[3,4]]), np.array([[1,0]])\r\n# grads, cost = propagate(w, b, X, Y)\r\n# print (\"dw = \" + str(grads[\"dw\"]))\r\n# print (\"db = \" + str(grads[\"db\"]))\r\n# print (\"cost = \" + str(cost))\r\n\r\n# params, grads, costs = optimize(w, b, X, Y, num_iterations= 100, learning_rate = 0.009, print_cost = False)\r\n\r\n# print (\"w = \" + str(params[\"w\"]))\r\n# print (\"b = \" + str(params[\"b\"]))\r\n# print (\"dw = \" + str(grads[\"dw\"]))\r\n# print (\"db = \" + str(grads[\"db\"]))\r\n\r\n# print (\"predictions = \" + str(predict(w, b, X)))\r\n# # end testing every func","sub_path":"01-Neural_Networks_and_Deep_Learning/week2/project/python/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":4976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"307850194","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n# *********************************************************************\n# Software : PyCharm\n#\n# dcntestlinkutils.py -\n#\n# Author :yanwh(yanwh@digitalchina.com)\n#\n# Version 1.0.0\n#\n# Copyright (c) 2004-9999 Digital China Networks Co. Ltd\n#\n#\n# *********************************************************************\n# Change log:\n# - 2018/3/19 19:20 add by yanwh\n#\n# *********************************************************************\n\n\ndef recover_args(path=None):\n \"\"\"\n 修改参数,避免单跑调试脚本的结果回传到testlink\n :return: None\n \"\"\"\n _temp = \"\"\"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\nargs = {\n 'productLine': '无线产品线',\n 'testSuite': '无线确认测试',\n 'testPlan': 'auto',\n 'testBuild': 'auto',\n 'testDevice': 'auto',\n 'notes': '',\n 'user': 'auto',\n 'aftersaleFlag': '0',\n 'aftersaleVersion': 'auto',\n 'scriptVersion': 'auto'\n }\n \"\"\"\n if path is None:\n import os\n path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'args.py')\n del os\n _args_filename = path\n with open(_args_filename, str('w+')) as _fp:\n _fp.write(str(_temp))\n","sub_path":"api_v1/dtestlink/dcntestlink/dcntestlinkutils.py","file_name":"dcntestlinkutils.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"286131965","text":"from tree import Leaf, build_tree\nfrom data import data\n\n\nprint(\"\\tThis is an awesome Luna City tourist detector:\")\nprint(\"\\tPossible answers to questions: 'yes' & 'no'\")\nprint(\"------------------------------------------------\")\n\n\ndef process_tree(node, spacing=\"\"):\n \"\"\"World's most elegant tree printing function.\"\"\"\n\n # Base case: we've reached a leaf\n if isinstance(node, Leaf):\n print(\"The most suitable tourist is -->\", node.predictions)\n return\n\n # Print the question at this node\n print(str(node.question))\n # get input\n val = input(\">\\t\")\n\n if val == \"yes\":\n process_tree(node.true_branch, spacing)\n elif val == \"no\":\n process_tree(node.false_branch, spacing)\n else:\n print(\"Not a valid command. Try again\")\n process_tree(node)\n\n\ntree = build_tree(data)\nprocess_tree(tree)\n","sub_path":"lab1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"421946314","text":"#coding=utf-8\nimport cv2\nimport os\nimport sys\nimport logging\nimport warnings\nimport time\nimport mxnet as mx\nfrom mxnet import gluon\nfrom mxnet.gluon.data import DataLoader\nfrom gluoncv import utils as gutils \n\nsys.path.append(os.path.expanduser('~/gluon-ocr'))\nfrom gluonocr.model_zoo import get_east\nfrom gluonocr.data import EASTDataset \nfrom gluonocr.data import PointAugmenter\nfrom gluonocr.loss import EASTLoss\nfrom config import args\n\ngutils.random.seed(args.seed)\n\nclass Trainer(object):\n def __init__(self):\n ctx = [mx.gpu(int(i)) for i in args.gpus.split(',')]\n self.ctx = ctx if ctx != 0 else [mx.cpu()]\n if args.syncbn and len(self.ctx) > 1:\n self.net = get_east(args.network, args.num_layers, pretrained_base=True,\n norm_layer=gluon.contrib.nn.SyncBatchNorm,\n norm_kwargs={'num_devices': len(self.ctx)})\n self.async_net = get_east(args.network, args.num_layers, pretrained_base=False) # used by cpu worker\n else:\n self.net = get_east(args.network, args.num_layers, pretrained_base=True) \n self.async_net = self.net\n\n model_name = '%s-%s%d-east'%(args.dataset_name, args.network, args.num_layers)\n self.train_dataloader, self.val_dataloader = self.get_dataloader()\n if not os.path.exists(args.save_prefix):\n os.mkdir(args.save_prefix)\n args.save_prefix += model_name\n if args.export_model:\n self.export_model()\n self.init_model()\n self.net.collect_params().reset_ctx(self.ctx)\n self.loss = EASTLoss(lambd=2.0)\n self.sum_loss = mx.metric.Loss('SumLoss')\n self.l1_loss = mx.metric.Loss('SmoothL1Loss')\n self.bce_loss = mx.metric.Loss('BalanceCELoss')\n\n def init_model(self):\n if args.resume.strip():\n self.net.load_parameters(args.resume.strip())\n self.async_net.load_parameters(args.resume.strip())\n else:\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\")\n self.net.initialize(init=mx.init.Xavier())\n self.async_net.initialize(init=mx.init.Xavier())\n\n def get_dataloader(self):\n augment = PointAugmenter()\n train_dataset = EASTDataset(args.train_img_dir, \n args.train_lab_dir,\n augment, mode='train',\n img_size=(args.data_shape, args.data_shape))\n val_dataset = EASTDataset(args.train_img_dir, \n args.train_lab_dir, mode='val',\n img_size=(args.data_shape, args.data_shape))\n args.num_samples = len(train_dataset)\n train_dataloader = DataLoader(train_dataset, batch_size=args.batch_size, \n last_batch='discard', shuffle=True, \n num_workers=args.num_workers, pin_memory=False)\n val_dataloader = DataLoader(val_dataset, batch_size=args.batch_size, \n num_workers=args.num_workers, last_batch='keep')\n return train_dataloader, val_dataloader\n\n def train(self):\n if args.lr_decay_period > 0:\n lr_decay_epoch = list(range(args.lr_decay_period, args.epochs, args.lr_decay_period))\n else:\n lr_decay_epoch = [int(i) for i in args.lr_decay_epoch.split(',')]\n lr_decay_epoch = [e - args.warmup_epochs for e in lr_decay_epoch]\n num_batches = args.num_samples // args.batch_size\n lr_scheduler = gutils.LRSequential([\n gutils.LRScheduler('linear', base_lr=0, target_lr=args.lr,\n nepochs=args.warmup_epochs, iters_per_epoch=num_batches),\n gutils.LRScheduler(args.lr_mode, base_lr=args.lr,\n nepochs=args.epochs - args.warmup_epochs,\n iters_per_epoch=num_batches,\n step_epoch=lr_decay_epoch,\n step_factor=args.lr_decay, power=2),\n ])\n\n trainer = gluon.Trainer(self.net.collect_params(), 'sgd',\n {'wd': args.wd, 'momentum': args.momentum, 'lr_scheduler': lr_scheduler}) #\n\n # set up logger\n logging.basicConfig()\n logger = logging.getLogger()\n logger.setLevel(logging.INFO)\n log_file_path = args.save_prefix + '_train.log'\n log_dir = os.path.dirname(log_file_path)\n if log_dir and not os.path.exists(log_dir):\n os.makedirs(log_dir)\n fh = logging.FileHandler(log_file_path)\n logger.addHandler(fh)\n logger.info(args)\n\n logger.info('Start training from [Epoch {}]'.format(args.start_epoch))\n best_loss = 1000\n\n for epoch in range(args.start_epoch, args.epochs):\n tic = time.time()\n btic = time.time()\n self.net.hybridize()\n for i, batch in enumerate(self.train_dataloader):\n data = gluon.utils.split_and_load(batch[0], ctx_list=self.ctx)\n score = gluon.utils.split_and_load(batch[1], ctx_list=self.ctx)\n mask = gluon.utils.split_and_load(batch[2], ctx_list=self.ctx)\n geo_map = gluon.utils.split_and_load(batch[3], ctx_list=self.ctx)\n sum_losses, bce_losses, l1_losses = [], [], []\n with mx.autograd.record():\n for d, s, m, gm in zip(data, score, mask, geo_map):\n pred_score, pred_geo = self.net(d)\n pred = {'score':pred_score, 'geo_map':pred_geo}\n lab = {'gt':s, 'mask':m, 'geo_map':gm}\n loss, metric = self.loss(pred, lab)\n sum_losses.append(loss)\n bce_losses.append(metric['bce_loss'])\n l1_losses.append(metric['l1_loss'])\n mx.autograd.backward(sum_losses)\n trainer.step(1)\n #mx.nd.waitall()\n self.sum_loss.update(0, sum_losses)\n self.l1_loss.update(0, l1_losses)\n self.bce_loss.update(0, bce_losses)\n if args.log_interval and not (i + 1) % args.log_interval:\n name0, loss0 = self.sum_loss.get()\n name1, loss1 = self.l1_loss.get()\n name2, loss2 = self.bce_loss.get()\n logger.info('[Epoch {}][Batch {}], LR: {:.2E}, Speed: {:.3f} samples/sec, {}={:.3f}, {}={:.3f}, {}={:.3f}'.format(\n epoch, i+1, trainer.learning_rate, args.batch_size/(time.time()-btic), name0, loss0, name1, loss1, name2, loss2))\n btic = time.time()\n name0, loss0 = self.sum_loss.get()\n name1, loss1 = self.l1_loss.get()\n name2, loss2 = self.bce_loss.get()\n logger.info('[Epoch {}] Training cost: {:.3f}, {}={:.3f}, {}={:.3f}, {}={:.3f}'.format(\n epoch, time.time()-tic, name0, loss0, name1, loss1, name2, loss2))\n\n if not (epoch + 1) % args.val_interval:\n # consider reduce the frequency of validation to save time\n mean_loss = self.validate(logger)\n if mean_loss < best_loss:\n best_loss = mean_loss\n self.net.save_parameters('{:s}_best.params'.format(args.save_prefix))\n if args.save_interval and (epoch+1) % args.save_interval == 0:\n self.net.save_parameters('{:s}_{:04d}_{:.3f}.params'.format(args.save_prefix, epoch+1, mean_loss))\n\n def validate(self, logger):\n if self.val_dataloader is None:\n return 0\n logger.info('Start validate.')\n self.sum_loss.reset()\n self.l1_loss.reset()\n self.bce_loss.reset()\n tic = time.time()\n for batch in self.val_dataloader:\n data = gluon.utils.split_and_load(batch[0], ctx_list=self.ctx, batch_axis=0)\n labs = [gluon.utils.split_and_load(batch[it], ctx_list=self.ctx, batch_axis=0) for it in range(1, 4)]\n for it, x in enumerate(data):\n score, geo_map = self.net(x)\n pred = {'score':score, 'geo_map':geo_map}\n lab = {'gt':labs[0][it], 'mask':labs[1][it], 'geo_map':labs[2][it]}\n loss, metric = self.loss(pred, lab)\n self.sum_loss.update(0, loss)\n self.l1_loss.update(0, metric['l1_loss'])\n self.bce_loss.update(0, metric['bce_loss'])\n \n name0, loss0 = self.sum_loss.get()\n name1, loss1 = self.l1_loss.get()\n name2, loss2 = self.bce_loss.get()\n \n logger.info('Evaling cost: {:.3f}, {}={:.3f}, {}={:.3f}, {}={:.3f}'.format(\n time.time()-tic, name0, loss0, name1, loss1, name2, loss2))\n self.sum_loss.reset()\n self.l1_loss.reset()\n self.bce_loss.reset()\n return loss0\n\n def export_model(self):\n self.net.export_block(args.save_prefix, args.resume.strip(), self.ctx)\n sys.exit()\n\nif __name__ == '__main__':\n trainer = Trainer()\n trainer.train()","sub_path":"scripts/detect/east/train_east.py","file_name":"train_east.py","file_ext":"py","file_size_in_byte":9220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"300813312","text":"class Solution(object):\n\t# DFS approach\n def canFinish(self, numCourses, prerequisites):\n \"\"\"\n :type numCourses: int\n :type prerequisites: List[List[int]]\n :rtype: bool\n \"\"\"\n '''\n For DFS, it will first visit a node, then one neighbor of it, then one neighbor of this neighbor... and so on. If it meets a node which was visited in the current process of DFS visit, a cycle is detected and we will return false. Otherwise it will start from another unvisited node and repeat this process till all the nodes have been visited. Note that you should make two records: one is to record all the visited nodes and the other is to record the visited nodes in the current DFS visit.\n '''\n def hasCycle(graph, visited, onPath, i):\n if visited[i]:\n return False\n if onPath[i]:\n return True\n \n onPath[i] = True\n for neighbor in graph[i]:\n if hasCycle(graph, visited, flag, neighbor):\n return True\n visited[i] = True\n onPath[i] = False\n return False\n \n graph = {}\n for i in range(numCourses):\n graph[i] = set()\n \n for p in prerequisites:\n graph[p[1]].add(p[0])\n \n visited = [False for i in range(numCourses)]\n flag = [False for i in range(numCourses)]\n \n for i in range(numCourses):\n if hasCycle(graph, visited, flag, i):\n return False\n \n return True\n\n\t# BFS approach\n def canFinish(self, numCourses, prerequisites):\n \"\"\"\n :type numCourses: int\n :type prerequisites: List[List[int]]\n :rtype: bool\n \"\"\"\n graph = {}\n for i in range(numCourses):\n graph[i] = set()\n\n for p in prerequisites:\t\n graph[p[1]].add(p[0])\n \n degree = [0 for i in range(numCourses)]\n for i in range(numCourses):\n for neighbor in graph[i]:\n degree[neighbor] += 1\n \n for i in range(numCourses):\n j = 0\n while j < numCourses and degree[j] != 0:\n j += 1\n \n if j == numCourses:\n return False\n \n degree[j] = -1\n for neighbor in graph[j]:\n degree[neighbor] -= 1\n \n return True\n","sub_path":"python_solutions/207-course-schedule.py","file_name":"207-course-schedule.py","file_ext":"py","file_size_in_byte":2464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"195367592","text":"from keras.layers.core import Dense, SpatialDropout1D\nfrom keras.layers.convolutional import Conv1D\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.pooling import GlobalMaxPooling1D\nfrom keras.models import Sequential\nfrom keras.preprocessing.sequence import pad_sequences\nfrom keras.utils import np_utils\nfrom sklearn.model_selection import train_test_split\nimport collections\nimport nltk\nimport numpy as np\nfrom make_tensorboard import make_tensorboard\nimport codecs\n\n\nnp.random.seed(42)\n\nINPUT_FILE = \"data/umich-sentiment-train.txt\"\nVOCAB_SIZE = 5000\nEMBED_SIZE = 100\nNUM_FILTERS = 256\nNUM_WORDS = 3\nBATCH_SIZE = 64\nNUM_EPOCHS = 20\n\ncounter = collections.Counter()\nfin = codecs.open(INPUT_FILE, \"r\", encoding='utf-8')\nmaxlen = 0\n# you have to download the nltk data\n# You will see the below command\n# import nltk\n# nltk.download()\n# NLTK Downloader\n# ---------------------------------------------------------------------------\n# d) Download l) List u) Update c) Config h) Help q) Quit\n# ---------------------------------------------------------------------------\n# Downloader> d\n#\n# Download which package (l=list; x=cancel)?\n# Identifier> all\n#\n\nfor line in fin:\n _, sent = line.strip().split(\"\\t\")\n words = [x.lower() for x in nltk.word_tokenize(sent)]\n if len(words) > maxlen:\n maxlen = len(words)\n for word in words:\n counter[word] += 1\nfin.close()\n\nword2index = collections.defaultdict(int)\nfor wid, word in enumerate(counter.most_common(VOCAB_SIZE)):\n word2index[word[0]] = wid + 1\n# Adding one because UNK.\n# It means representing words that are not seen in the vocubulary\nvocab_sz = len(word2index) + 1\nindex2word = {v: k for k, v in word2index.items()}\n\nxs, ys = [], []\nfin = codecs.open(INPUT_FILE, \"r\", encoding='utf-8')\nfor line in fin:\n label, sent = line.strip().split(\"\\t\")\n ys.append(int(label))\n words = [x.lower() for x in nltk.word_tokenize(sent)]\n wids = [word2index[word] for word in words]\n xs.append(wids)\nfin.close()\nX = pad_sequences(xs, maxlen=maxlen)\nY = np_utils.to_categorical(ys)\n\nXtrain, Xtest, Ytrain, Ytest = \\\n train_test_split(X, Y, test_size=0.3, random_state=42)\nprint(Xtrain.shape, Xtest.shape, Ytrain.shape, Ytest.shape)\n\nmodel = Sequential()\nmodel.add(Embedding(vocab_sz, EMBED_SIZE, input_length=maxlen))\nmodel.add(SpatialDropout1D(0.2))\nmodel.add(Conv1D(filters=NUM_FILTERS,\n kernel_size=NUM_WORDS,\n activation=\"relu\"))\nmodel.add(GlobalMaxPooling1D())\nmodel.add(Dense(2, activation=\"softmax\"))\n\nmodel.compile(optimizer=\"adam\", loss=\"categorical_crossentropy\",\n metrics=[\"accuracy\"])\n\ntensorboard, _ = make_tensorboard(\n set_dir_name='keras_learn_embedding_from_scratch')\n\nhistory = model.fit(Xtrain, Ytrain, batch_size=BATCH_SIZE,\n epochs=NUM_EPOCHS,\n callbacks=[tensorboard],\n validation_data=(Xtest, Ytest))\n\n# evaluate model\nscore = model.evaluate(Xtest, Ytest, verbose=1)\nprint(\"Test score: {:.3f}, accuracy: {:.3f}\".format(score[0], score[1]))\n","sub_path":"Chapter05/learn_embedding_from_scratch.py","file_name":"learn_embedding_from_scratch.py","file_ext":"py","file_size_in_byte":3080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"6468495","text":"# -*- coding: utf-8 -*-\nfrom module import pool_parallel as po\nfrom module import argorism as arg\nfrom module import Process as pro\nimport time\nimport os\n\nif __name__ == \"__main__\":\n\n pool_time = time.time()\n max_num = 1000000\n print(\"----------------------------\" + \"\\n\" + \"処理を並列化あり(pool)で実行\")\n result = po.pool_pal(arg.coin, 4, max_num)\n end_pool_time = time.time() - pool_time\n num0 = result.count(0)\n probability = num0 / max_num * 100\n\n process_time = time.time()\n print(\"----------------------------\" + \"\\n\" + \"処理を並列化あり(process)で実行\")\n process_result = pro.process(4, max_num)\n end_process_time = time.time() - process_time\n pro_num0 = process_result.count(0)\n pro_probability = pro_num0 / max_num * 100\n\n #po.pool_pal(arg.dice, 4, 10)\n\n time_no = time.time()\n print(\"\\n\" + \"----------------------------\" + \"\\n\" + \"処理を並列化なしで実行\")\n for i in range(max_num):\n arg.coin(i)\n end_time = time.time() - time_no\n print(\"\\n\" + \"--------------------------------------------\")\n print (\"並列化あり(pool):{0}\".format(end_pool_time) + \"[sec]\")\n print (\"並列化あり(process):{0}\".format(end_process_time) + \"[sec]\")\n print (\"並列化なし:{0}\".format(end_time) + \"[sec]\")\n print (\"コインの表が出た確率:{0}\".format(probability) + \"\\n\")\n\n # ファイルに書き込み\n current_path = os.getcwd()\n with open(current_path+\"/log_file\", mode='a') as f:\n f.write(\"並列化あり(pool):{0}\".format(end_pool_time) + \"[sec]\"+ \"\\n\")\n f.write(\"並列化あり(process):{0}\".format(end_process_time) + \"[sec]\")\n f.write(\"並列化なし:{0}\".format(end_time) + \"[sec]\"+ \"\\n\")\n f.write(\"コインの表が出た確率:{0}\".format(probability) + \"\\n\" + \"\\n\")","sub_path":"code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"653066031","text":"#1. Посмотреть документацию к API GitHub, разобраться как вывести список репозиториев для конкретного пользователя, сохранить JSON-вывод в файле *.json.\nimport requests\nimport json\n\ndef get_repositories(api_url, target_url):\n result_data=[]\n response = requests.get(api_url+target_url)\n j_data=json.loads(response.text)\n for item in j_data:\n result_data.append(item.get('name'))\n return response.status_code,result_data\n\ngithub_api_url=\"https://api.github.com/\"\nusername=\"AndreyU123\"\nrepositories_url=f\"users/{username}/repos\"\nstatus,data = get_repositories(github_api_url,repositories_url)\n\nprint(status)\nprint(data)\nwith open(\"ukladnikov_andrey_lesson1_data.json\",\"w\") as jsonfile:\n jsonfile.write(json.dumps(data))\n","sub_path":"Lesson1/UkladnikovAndrey_Lesson1_Task1.py","file_name":"UkladnikovAndrey_Lesson1_Task1.py","file_ext":"py","file_size_in_byte":851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"544084133","text":"import satimo\nfrom matplotlib.pyplot import *\nrcParams['font.family'] = \"Times New Roman\"\nrcParams['font.size'] = \"8\"\n\n# Calibration measurements\ncalfiles = [\n \"calib/calib2450.trx\",\n]\n\n# Reference files\nreffiles = [\n \"calib/SD740-70.ref\",\n \"calib/SD850-02.ref\",\n \"calib/SD900-51.ref\",\n \"calib/SD1800-45.ref\",\n \"calib/SD1900-49.ref\",\n \"calib/SD2050-36.ref\",\n \"calib/SD2450-43.ref\",\n \"calib/SD2600-28.ref\",\n]\n\nf,eff = satimo.efficiency(\"antenna_meas.trx\", calfiles, reffiles)\n\nfigure(figsize=(3.5, 3)) # Figure size.\nplot(f/1e9, eff)\ngrid()\nxlabel(\"Frequency [GHz]\")\nylabel(\"Efficiency [.]\")\ntight_layout() # Clean up figure.\nsavefig(\"ex5_efficiency.pdf\")\nshow()\n\n","sub_path":"rep/sec/post_processing/examples/example5.py","file_name":"example5.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"474148534","text":"from os import abort\nimport traceback\nfrom flask import render_template, redirect\nfrom flask.ext.login import login_required, current_user\nfrom app import app\nfrom app.DAO import get_port_for_app\nfrom app.core import Functions\n\nfrom app.model import application, get_alice_repo\n\n\n__author__ = 'Davor Obilinovic'\n\n@app.route('/')\n@login_required\ndef index():\n return redirect('/manager')\n\n@app.route('/manager')\n@login_required\ndef manager():\n tb=None\n try:\n app_list = application.get_all_apps()\n return render_template('index.html',\n apps = app_list,\n last_commit = Functions.format_time(get_alice_repo().heads[0].commit.committed_date),\n user=current_user)\n except Exception as e :\n tb = traceback.format_exc()\n else:\n tb = \"No error\"\n tb.replace(\", line\", \",
line\")\n return render_template(\"error.html\",message = tb)\n\n\n@app.route('/')\ndef apps(app_name):\n port = get_port_for_app(app_name)\n if not port:\n abort(404)\n return redirect('http://127.0.0.1:'+str(port))\n\n\n","sub_path":"app/views/pages.py","file_name":"pages.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"314741272","text":"import cv2\nimport datetime\n\ncap = cv2.VideoCapture(0)\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\nsmile_cascade = cv2.CascadeClassifier('haarcascade_smile.xml')\nwhile True:\n _, frame = cap.read()\n main_frame = frame.copy()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n face = face_cascade.detectMultiScale(gray, 1.3, 5)\n for x,y, w, h in face:\n cv2.rectangle(frame, (x, y), (x+w, y+h),(0,255,255),2)\n face_dect = frame[y:y+h, x:x+w, ]\n gray_dect = gray[y:y + h, x:x + w,]\n smile = smile_cascade.detectMultiScale(gray_dect, 1.3,25)\n\n for x1, y1, w1, h1 in smile:\n cv2.rectangle(face_dect, (x1, y1), (x1+w1, y1+h1), (0, 0, 114),2)\n time_stamp= datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n file_name = f'img{time_stamp}.png'\n cv2.imwrite(file_name,main_frame)\n cv2.imshow('Digital Camera', frame)\n if cv2.waitKey(10) == ord('q'):\n break\n\n","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"351501099","text":"from pynput import mouse\n\ngamePosition=[(0,0,0,0),(0,0,0,0),(0,0,0,0)]\ncount = 0 \npress = (0,0)\nreleased = (0,0)\ndef on_click(x, y, button, pressed):\n global count,press,released,gamePosition\n if count >2:\n return False\n if (button == mouse.Button.left) and (pressed == True):\n print(x,y,pressed)\n press=(x,y)\n elif (button == mouse.Button.left) and (pressed == False):\n print(x,y,pressed)\n released=(x,y)\n gamePosition[count]=press+released\n count+=1\n\nwith mouse.Listener(\n on_click=on_click) as listener:\n (listener.join())\nprint(mouse.Listener)\n \nfrom pynput import mouse\n\n\ndef on_click(x, y, button, pressed):\n global gamePosition\n print('{0} at {1}'.format(\n 'Pressed' if pressed else 'Released',\n (x, y)))\n if not pressed:\n # Stop listener\n return False\n# print(\"Please select the area (Click hold and release) of the game: \\\n# First insert question the answer1, answer2\")\n for i in range(2):\n with mouse.Listener(\n on_click=on_click) as listener:\n \n listener.join()\n \n \nfile = open('gamePos.txt','w')\nfor position in gamePosition:\n for number in position:\n file.write(str(number)+',')\nfile.close() ","sub_path":"mousePress.py","file_name":"mousePress.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"486515712","text":"import collections\nimport time\n\nfrom aspen.network_engines import CooperativeEngine\nfrom aspen.sockets import packet\nfrom aspen.sockets.loop import Die\nimport tornado.ioloop\nimport tornado.httpserver\nimport tornado.wsgi\n\n\nclass TornadoBuffer(collections.deque):\n \"\"\"Model a buffer of items.\n\n There are two of these for each Socket, one for incoming message payloads\n and one for outgoing message objects.\n\n Here's what the flow looks like:\n\n wire => [msg, msg, msg, msg, msg, msg, msg, msg] => resource\n wire <= [msg, msg, msg, msg, msg, msg, msg, msg] <= resource\n\n \"\"\"\n\n def __init__(self, name, socket=None):\n \"\"\"Takes a string and maybe a socket.\n\n If given a socket, we will try to play nice with its loop.\n\n \"\"\"\n\n # It feels like it's going to take deeper rewiring to get *.sock files\n # working with Tornado callbacks.\n raise NotImplementedError(\"Sorry, for now please use a different \"\n \"networking library in order to use *.sock \"\n \"files.\")\n\n collections.deque.__init__(self)\n self._socket = socket\n self._name = name\n\n put = collections.deque.appendleft\n get = collections.deque.pop\n empty = lambda d: not bool(d)\n\n\n # flush\n # =====\n # Used for outgoing buffer.\n\n def flush(self):\n \"\"\"Return an iterable of bytestrings or None.\n \"\"\"\n if not self.empty():\n return self.__flusher()\n return None\n\n def __flusher(self):\n \"\"\"Yield strings.\n\n We unload bytestrings as fast as we can until we run out of time or\n bytestrings. On my MacBook Pro I am seeing between 500 and 1000\n messages dumped in 2ms--without any WSGI/HTTP/TCP overhead. We always\n yield at least one bytestring to avoid deadlock.\n\n This generator is instantiated in self.flush.\n\n \"\"\"\n if not self.empty():\n yield packet.frame(self.get())\n timeout = time.time() + (0.007) # We have 7ms to dump bytestrings. Go!\n while not self.empty() and time.time() < timeout:\n yield packet.frame(self.get())\n\n\n # next\n # ====\n # Used for incoming buffer.\n\n def next(self):\n \"\"\"Return the next item from the queue.\n\n The first time this is called, we lazily instantiate the generator at\n self._blocked. Subsequent calls are directed directly to that\n generator's next method.\n\n \"\"\"\n self._blocked = self._blocked()\n self.next = self._next\n return self.next()\n\n def _next(self):\n try:\n return self._blocked.next()\n except StopIteration:\n # When the _blocked generator discovers Die and breaks, the\n # effect is a StopIteration here. It's a bug if this happens\n # other than when we are disconnecting the socket.\n assert self._socket is not None\n assert self._socket.loop.please_stop\n\n def _blocked(self):\n \"\"\"Yield items from self forever.\n\n This generator is lazily instantiated in self.next. It is designed to\n cooperate with ThreadedLoop. XXX Oh yeah?\n\n \"\"\"\n if self._socket is None: # We're on a Channel.\n while 1:\n yield self.get()\n else: # We're on a Socket.\n while not self._socket.loop.please_stop:\n out = self.get()\n if out is Die:\n break # will result in a StopIteration\n yield out\n\n\nclass TornadoLoop(object):\n\n def __init__(self, socket):\n self.socket = socket\n self.please_stop = False\n\n def __call__(self):\n while not self.please_stop:\n self.socket.tick()\n\n def start(self):\n pass\n\n def stop(self):\n self.please_stop = True\n self.socket.incoming.put(Die)\n\n\nclass Engine(CooperativeEngine):\n\n checker = None\n\n def bind(self):\n container = tornado.wsgi.WSGIContainer(self.website)\n http_server = tornado.httpserver.HTTPServer(container)\n http_server.listen(self.website.network_address[1])\n\n def sleep(self, seconds):\n time.sleep(seconds)\n\n def start(self):\n try:\n tornado.ioloop.IOLoop.instance().start()\n except SystemExit:\n pass\n\n def start_checking(self, check_all):\n self.checker = tornado.ioloop.PeriodicCallback(check_all, 500)\n self.checker.start()\n\n def stop_checking(self):\n self.checker.stop()\n\n Buffer = TornadoBuffer\n Loop = TornadoLoop\n\n","sub_path":"aspen/network_engines/tornado_.py","file_name":"tornado_.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"64989922","text":"import xml.etree.ElementTree as ET\r\nimport csv\r\n\r\narquivo_tokens = list(open('configuracao/tks.txt'))\r\ncodigo_programador = list(open('configuracao/codigo.txt'))\r\narvore = ET.parse('configuracao/parsing.xml')\r\nroot = arvore.getroot()\r\n\r\nblock, vivos, alcan, regras_finais, fita, escopo, simbolos, estados, tabela_simbolos, fita_saida = [], [], [], [], [], [], [], [], [], []\r\nepTransicao, gramatica, simbolo_redu, tabela = {}, {}, {}, {}\r\nrepeticao = 0\r\n\r\n\r\ndef eliminar_mortos():\r\n mortos = []\r\n for x in tabela:\r\n if x not in vivos and x != '€': #adiciona a regra aos mortos caso não esteja em vivos e não seja €\r\n mortos.append(x)\r\n\r\n for x in mortos:\r\n del tabela[x] #deleta da tabela os mortos\r\n\r\n\r\ndef buscar_vivos():\r\n mudou = False\r\n\r\n for regra in tabela:\r\n for simbolo in tabela[regra]:\r\n if tabela[regra][simbolo][0] in vivos and regra not in vivos:\r\n vivos.append(regra) # se o simbolo esta em vivos e a regra não está, add em vivos a regra\r\n mudou = True\r\n\r\n if mudou:\r\n buscar_vivos() #chama novamente, mudando a flag no inicio da funcao\r\n\r\n\r\ndef eliminar_inalcansaveis():\r\n loop = {}\r\n loop.update(tabela)\r\n for regra in loop:\r\n if regra not in alcan: #remove regra da tabela se não estiverem em alcan\r\n del tabela[regra]\r\n\r\n\r\ndef buscar_alcansaveis(estado):\r\n if estado not in alcan: #adiciona estado no alcan caso n esteja\r\n alcan.append(estado)\r\n for simbolo in tabela[estado]: #passa por cada simbolo de estado da tabela \r\n if tabela[estado][simbolo] and tabela[estado][simbolo][0] not in alcan: #continua adicionando os simbolos em alcan\r\n buscar_alcansaveis(tabela[estado][simbolo][0])\r\n\r\n\r\ndef encontrar_eps_set(e_transicoes): #encontra os estados que possuem o epsilon\r\n for x in e_transicoes:\r\n for y in tabela[x]['&']:\r\n if y not in e_transicoes:\r\n e_transicoes.append(y)\r\n return e_transicoes\r\n\r\n\r\ndef eliminar_et():\r\n for regra in tabela:\r\n et_set = encontrar_eps_set(tabela[regra]['&'])\r\n for estado in et_set:\r\n if estado in regras_finais: #verifica se o estado que possui & está nos regras_finais, se não está add\r\n regras_finais.append(regra)\r\n for simbolo in tabela[estado]:\r\n for transicao in tabela[estado][simbolo]: #verifica a transicao do estado e add na tabela caso ela não esteja\r\n if transicao not in tabela[regra][simbolo]:\r\n tabela[regra][simbolo].append(transicao)\r\n tabela[regra]['&'] = []\r\n\r\n\r\ndef criar_novos(nstates):\r\n for x in nstates:\r\n tabela[x] = {}\r\n estados.append(x) #salva o novo estado na tabela de estados\r\n for y in simbolos:\r\n tabela[x][y] = []\r\n tabela[x]['&'] = []\r\n\r\n for state in nstates:\r\n estadosjuntar = sorted(state.split(':'))\r\n for x in estadosjuntar:\r\n if x in regras_finais and state not in regras_finais: #faz uma nova verificação se está nos regras_finais, caso não esteja adiciona\r\n regras_finais.append(state)\r\n for simbolo in simbolos:\r\n for transition in tabela[x][simbolo]:\r\n if not tabela[state][simbolo].__contains__(transition): #verifica se existe na tabela e add caso não esteja\r\n tabela[state][simbolo].append(transition)\r\n determizinar() #verifica novamente\r\n\r\n\r\ndef determizinar():\r\n novosestados = []\r\n for regra in tabela:\r\n for producao in tabela[regra]:\r\n if len(tabela[regra][producao]) > 1: #busca pela regra com mais de 1 producao\r\n novo = []\r\n for estado in tabela[regra][producao]:\r\n if ':' in estado:\r\n for aux in estado.split(':'): #verifica e divide se tem mais regra\r\n if aux not in novo:\r\n novo.append(aux) #adiciona na variavel nova\r\n else:\r\n if estado not in novo:\r\n novo.append(estado) #adiciona na varivel nova\r\n\r\n if novo:\r\n novo = sorted(novo)\r\n novo = ':'.join(novo) #cria nova regra\r\n if novo and novo not in novosestados and novo not in list(tabela.keys()):\r\n novosestados.append(novo)\r\n tabela[regra][producao] = novo.split() #salva na tabela a nova regra\r\n if novosestados:\r\n criar_novos(novosestados)\r\n\r\n\r\ndef criar_automato_finitos(): #cria automato finito\r\n for x in gramatica:\r\n tabela[x] = {}\r\n estados.append(x) #pega todos estados da lista de gramatica\r\n for y in simbolos:\r\n tabela[x][y] = []\r\n tabela[x]['&'] = [] #limpado o estado do &\r\n \r\n\r\n for regra in gramatica:\r\n for producao in gramatica[regra]:\r\n if len(producao) == 1 and producao.islower() and regra not in regras_finais:\r\n regras_finais.append(regra) #adiciona a regra nas regras regras_finais caso seja = 1, minuscula e já n esteja nas regras_finais\r\n elif producao == '&' and regra not in regras_finais:\r\n regras_finais.append(regra) #adiciona $ nas regras_finais\r\n elif producao[0] == '<':\r\n tabela[regra]['&'].append(producao.split('<')[1][:-1]) #remove <> da regra e adiciona o que tem entre eles\r\n elif producao != '&':\r\n tabela[regra][producao[0]].append(producao.split('<')[1][:-1]) #remove <> da regra e inicial\r\n\r\n\r\ndef criar_sn(s):\r\n global repeticao\r\n if 'S' + str(repeticao) in gramatica:\r\n return\r\n gramatica['S' + str(repeticao)] = s.replace('\\n', '').split(' ::= ')[1].replace('>', str(repeticao) + '>').split(' | ')\r\n\r\n\r\ndef tratar_gramatica(gram, s):\r\n global repeticao #aux numero de repetições\r\n gram = gram.replace('\\n', '')\r\n for x in gram.split(' ::= ')[1].replace('<', '').replace('>', '').split(' | '): #separa letra da regra na posicao 0\r\n if x[0] not in simbolos and not x[0].isupper(): #verifica se não esta em simbolos e se não é maiuscula \r\n simbolos.append(x[0]) #salva em simbolos\r\n regra = gram.split(' ::= ')[0].replace('>', str(repeticao)).replace('<', '') #concatena letra da regra + número da repetição\r\n \r\n if regra[0] == 'S': #se a regra for S, repeticao+1\r\n repeticao += 1\r\n gramatica['S'] += gram.split(' ::= ')[1].replace('>', str(repeticao) + '>').split(' | ') #concatena na linha as próximas regras, ex: S0::=aS1\r\n else:\r\n gramatica[regra] = gram.split(' ::= ')[1].replace('>', str(repeticao)+'>').split(' | ') \r\n\r\n if '' in gram.split(' ::= ')[1]:\r\n criar_sn(s)\r\n\r\n\r\ndef tratar_token(token):\r\n token = token.replace('\\n', '') #replace a cada \\n pra pegar o token\r\n cp_token = token\r\n token = list(token) #quebra o token em caracteres\r\n for x in range(len(token)):\r\n if token[x] not in simbolos and not token[x].isupper(): #joga os caracteres dos tokens pra dentro de simbolos\r\n simbolos.append(token[x])\r\n\r\n if len(token) == 1:\r\n iniregra = '<' + cp_token.upper() + '>'\r\n gramatica['S'] += str(token[x] + iniregra).split() #salva na gramatica as regras de tamanho 1\r\n gramatica[cp_token.upper()] = []\r\n regras_finais.append(cp_token.upper()) #salva na lista os tokens de tamanho 1\r\n elif x == 0 and x != len(token)-1:\r\n iniregra = '<' + cp_token.upper() + '1>'\r\n gramatica['S'] += str(token[x] + iniregra).split() #salva na gramatica as regras de tamanho maior que 1 / o inicio deles\r\n elif x == len(token)-1:\r\n finregra = '<' + cp_token.upper() + '>'\r\n gramatica[cp_token.upper() + str(x)] = str(token[x] + finregra).split() #salva na gramatica as regras de tamanho maior que 1 / o fim deles\r\n gramatica[cp_token.upper()] = []\r\n regras_finais.append(cp_token.upper()) #salva na lista os tokens de tamanho maior que 1\r\n else:\r\n proxregra = '<' + cp_token.upper() + str(x+1) + '>'\r\n gramatica[cp_token.upper() + str(x)] = str(token[x] + proxregra).split() #salva na gramatica as regras de tamanho maior que 1 / o meio fim deles\r\n\r\n\r\ndef criar_csv():\r\n with open('afnd.csv', 'w', newline='') as f:\r\n w = csv.writer(f)\r\n copydict = {}\r\n copydict.update(tabela)\r\n w.writerow(list(copydict['S'].keys()) + ['regra'])\r\n for x in copydict:\r\n if x in regras_finais:\r\n copydict[x]['nomeregra'] = x + '&' #adiciona nome da regra concatenado com o epsilon\r\n else:\r\n copydict[x]['nomeregra'] = x #se não for final, não concatena com o epsilon\r\n w.writerow(copydict[x].values())\r\n\r\n\r\ndef estado_erro():\r\n tabela['€'] = {}\r\n for y in simbolos:\r\n tabela['€'][y] = [] #adiciona todos os simbolos no € como posição\r\n tabela['€']['&'] = [] #epsilon também\r\n for regra in tabela:\r\n for simbolo in tabela[regra]:\r\n if not tabela[regra][simbolo]:\r\n tabela[regra][simbolo] = ['€'] #adicona € nas posições do simbolo da regra com valor nulo\r\n\r\n\r\ndef analisador_lexico():\r\n separadores = [' ', '\\n', '\\t', '+', '-', '{', '}', '#', ';']\r\n espacadores = [' ', '\\n', '\\t']\r\n operadores = ['+', '-', '#', ';']\r\n id = 0\r\n for idx, linha in enumerate(codigo_programador): #pega numero da linha e código de cada linha\r\n E = 'S'\r\n string = ''\r\n for char in linha:\r\n if char in operadores and string: #caso lemos um operador e a string não está vazia\r\n if string[-1] not in operadores: #se o ultimo caracter não é um operador\r\n if E in regras_finais: #a regra do caracter lido é um dos regras_finais\r\n tabela_simbolos.append({'Line': idx, 'State': E, 'Label': string}) \r\n fita_saida.append(E) #adicionamos a regra na fita de saida\r\n else:\r\n tabela_simbolos.append({'Line': idx, 'State': 'Error', 'Label': string})\r\n fita_saida.append('Error')\r\n E = tabela['S'][char][0] #mapeamento para a próxima estrutura de operadores\r\n string = char\r\n id += 1\r\n else: #se o último caractere é um operador\r\n string += char #adiciona na string o caracter e continua normalmente\r\n if char not in simbolos:\r\n E = '€'\r\n else:\r\n E = tabela[E][char][0]\r\n elif char in separadores and string:\r\n if E in regras_finais:\r\n tabela_simbolos.append({'Line': idx, 'State': E, 'Label': string}) #adiciona em tabela_simbolos linha, estado e descricao\r\n fita_saida.append(E) #caso seja um final, adiciona na fita de saida\r\n else:\r\n tabela_simbolos.append({'Line': idx, 'State': 'Error', 'Label': string})\r\n fita_saida.append('Error')\r\n E = 'S'\r\n string = ''\r\n id += 1\r\n else:\r\n if char in espacadores: #se for um espaçador, continua\r\n continue\r\n if char not in separadores and char not in operadores and string: #caso n seja um separador, operador e já exista algo na string\r\n if string[-1] in operadores: #caso não seja um separador ele somente incrementa na string\r\n if E in regras_finais: #operado é um final\r\n tabela_simbolos.append({'Line': idx, 'State': E, 'Label': string})\r\n fita_saida.append(E)\r\n else:\r\n tabela_simbolos.append({'Line': idx, 'State': 'Error', 'Label': string})\r\n fita_saida.append('Error')\r\n E = 'S'\r\n string = ''\r\n id += 1\r\n string += char\r\n if char not in simbolos: #caso o caracter não esteja na tabela de simbolos\r\n E = '€'\r\n else:\r\n E = tabela[E][char][0] #o E recebe a regra do caracter \r\n tabela_simbolos.append({'Line': idx, 'State': 'EOF', 'Label': ''})\r\n fita_saida.append('EOF')\r\n erro = False\r\n for linha in tabela_simbolos:\r\n if linha['State'] == 'Error': #caso exita erro léxico, imprime\r\n erro = True\r\n print('Erro léxico: linha {}, sentença \"{}\" não reconhecida!'.format(linha['Line']+1, linha['Label']))\r\n if erro:\r\n exit() #finaliza caso exista erro\r\n\r\n\r\ndef mapeamento(symbols):\r\n symbols_indexes = {} #é feito um reverso com o index x name\r\n for index, symbol in enumerate(symbols):\r\n symbols_indexes[symbol['Name']] = str(index)\r\n simbolo_redu[str(index)] = symbol['Name']\r\n for fta in fita_saida: #nos estados que eram nomes, sao alterados pelo indice para ser reconhecido sintaticamente\r\n if fta == 'S1' or fta == 'ENQUANTO1:S1' or fta == 'IGUAL1:S1': \r\n fta = 'VAR' \r\n elif fta == 'S2':\r\n fta = 'NUM'\r\n elif fta == '$':\r\n fta = 'EOF'\r\n fita.append(symbols_indexes[fta])\r\n\r\n for line in tabela_simbolos: #troca S1 e S2 na fita_saida por VAR e NUM\r\n if line['State'] == 'S1' or line['State'] == 'ENQUANTO1:S1' or line['State'] == 'IGUAL1:S1':\r\n line['State'] = 'VAR'\r\n elif line['State'] == 'S2':\r\n line['State'] = 'NUM'\r\n elif line['State'] == '$':\r\n line['State'] = 'EOF'\r\n\r\n\r\ndef analisador_sintatico(): #aqui é lido o arquivo_tokens xml pelas suas tags, nome, type, etc\r\n redux_symbol, symbols, productions, lalr_table, pilha = [], [], [], [], ['0']\r\n\r\n def charge():\r\n xml_symbols = root.iter('Symbol')\r\n for symbol in xml_symbols:\r\n symbols.append({\r\n 'Index': symbol.attrib['Index'],\r\n 'Name': symbol.attrib['Name'],\r\n 'Type': symbol.attrib['Type']\r\n })\r\n\r\n xml_productions = root.iter('Production')\r\n for production in xml_productions:\r\n productions.append({\r\n 'NonTerminalIndex': production.attrib['NonTerminalIndex'],\r\n 'SymbolCount': int(production.attrib['SymbolCount']),\r\n })\r\n\r\n lalr_states = root.iter('LALRState')\r\n for state in lalr_states:\r\n lalr_table.append({})\r\n for action in state:\r\n lalr_table[int(state.attrib['Index'])][str(action.attrib['SymbolIndex'])] = {\r\n 'Action': action.attrib['Action'],\r\n 'Value': action.attrib['Value']\r\n }\r\n\r\n def parser():\r\n idx = 0\r\n while True:\r\n ultimo_fita = fita[0]\r\n try:\r\n action = lalr_table[int(pilha[0])][ultimo_fita] #busca pelas acoes e valores\r\n except:\r\n print('Erro sintático: linha {}, sentença \"{}\" não reconhecida!'.format(tabela_simbolos[idx]['Line']+1, tabela_simbolos[idx]['Label']))\r\n exit() #apresente o erro caso exista\r\n break\r\n\r\n if action['Action'] == '1':\r\n pilha.insert(0, fita.pop(0)) #remove da fita e add na pilha\r\n pilha.insert(0, action['Value'])\r\n idx += 1\r\n elif action['Action'] == '2':\r\n size = productions[int(action['Value'])]['SymbolCount'] * 2\r\n while size:\r\n pilha.pop(0)\r\n size -= 1\r\n redux_symbol.append(productions[int(action['Value'])]['NonTerminalIndex']) #adiciona não terminal na lista\r\n pilha.insert(0, productions[int(action['Value'])]['NonTerminalIndex']) #insere na pilha tbm\r\n pilha.insert(0, lalr_table[int(pilha[1])][pilha[0]]['Value']) \r\n elif action['Action'] == '3':\r\n print('salto')\r\n elif action['Action'] == '4':\r\n break\r\n\r\n def catch_statements(): #aqui é pego as declarações\r\n pilha_aux = [1]\r\n id = 1\r\n for symbol in redux_symbol:\r\n if simbolo_redu[symbol] == 'CONDS':\r\n id += 1\r\n pilha_aux.insert(0, id)\r\n block.append(pilha_aux[1])\r\n elif simbolo_redu[symbol] == 'REP' or simbolo_redu[symbol] == 'COND':\r\n pilha_aux.pop(0)\r\n elif simbolo_redu[symbol] == 'RVAR':\r\n escopo.append(pilha_aux[0])\r\n\r\n def complete_ts(): #completa a tabela de simbolos\r\n for token in tabela_simbolos:\r\n if token['State'] == 'VAR': #se o token for VAR\r\n token['Scope'] = escopo.pop(0) # adiciona o escopo em que ela está\r\n\r\n charge()\r\n mapeamento(symbols)\r\n parser()\r\n catch_statements()\r\n complete_ts()\r\n\r\n\r\ndef analisador_semantico():\r\n var_scope = {}\r\n error = False\r\n\r\n def check_scope(scope_use, scope_dec): #verifica se o escopo utilizado é o mesmo do escopo declarado\r\n if scope_use == scope_dec:\r\n return True\r\n elif scope_use == 1:\r\n return False\r\n else:\r\n return check_scope(block[scope_use-2], scope_dec)\r\n\r\n\r\n for index, token in enumerate(tabela_simbolos):\r\n if token['State'] == 'VAR' and tabela_simbolos[index-1]['State'] == 'DEF':\r\n if token['Label'] in var_scope: #caso a variável já esteja declarada\r\n error = True\r\n print('Erro semântico: linha {}, variável \"{}\" já declarada!'.format(token['Line']+1, token['Label']))\r\n else:\r\n var_scope[token['Label']] = token['Scope'] #adiciona o scopo da variavel\r\n\r\n if token['State'] == 'VAR' and tabela_simbolos[index-1]['State'] != 'DEF':\r\n if token['Label'] in var_scope:\r\n if not check_scope(token['Scope'], var_scope[token['Label']]): #se o escopo n for o mesmo do declarado, erro\r\n error = True\r\n print('Erro semântico: linha {}, variável \"{}\" escopo inválido!'.format(token['Line']+1, token['Label']))\r\n else:\r\n error = True\r\n print('Erro semântico: linha {}, variável \"{}\" não declarada!'.format(token['Line']+1, token['Label']))\r\n if error:\r\n exit()\r\n\r\ndef codigo_intermediario():\r\n ts_code = []\r\n int_code = []\r\n\r\n def encontra_operacoes():\r\n flag = False\r\n operacao = []\r\n for idx, token in enumerate(tabela_simbolos):\r\n if token['State'] == 'VAR' and tabela_simbolos[idx+1]['State'] == '#' and tabela_simbolos[idx+1]['State'] != ';': #se for atribuicao de variavel, VAR # 1 ;\r\n operacao.append(token['Label'])\r\n flag = True\r\n elif token['State'] == ';' and tabela_simbolos[idx-2]['State'] != 'DEF': #verifica se for definicao de variavel, def VAR;\r\n ts_code.append(operacao)\r\n operacao = []\r\n flag = False\r\n elif flag:\r\n operacao.append(token['Label'])\r\n\r\n\r\n def gera_temp(operacao, temp):\r\n flag = False\r\n cod, copy = [], []\r\n copy.extend(operacao)\r\n\r\n for idx in range(len(operacao)-1): #pega inicio e fim da linha\r\n if operacao[idx+1] == '~' or operacao[idx+1] == '/': #se for multiplicacao ou divisao\r\n for i in range(-1, 2):\r\n cod.insert(0, copy[idx]) #salva em cod as proximas contas, a # 0 \"~b/1\" por exemplo\r\n copy.pop(idx)\r\n copy.insert(idx, 'T' + str(temp))\r\n flag = True\r\n break\r\n\r\n if not flag:\r\n for idx in range(len(operacao)-1):\r\n if operacao[idx+1] == '+' or operacao[idx+1] == '-': #caso seja soma ou subtracao\r\n for i in range(-1, 2):\r\n cod.insert(0, copy[idx]) #salva em cod as proximas contas\r\n copy.pop(idx)\r\n copy.insert(idx, 'T' + str(temp))\r\n break\r\n\r\n cod.insert(0, '#')\r\n cod.insert(0, 'T'+str(temp)) #insere em T+numero qtd chamada da funcao as contas\r\n return copy, cod\r\n\r\n def gera_codigo():\r\n temp = 1\r\n for operacao in ts_code:\r\n while True:\r\n if len(operacao) == 3: #se for uma operacao simples, a # 0;\r\n cod = []\r\n for x in range(len(operacao)):\r\n cod.append(operacao[x]) #adiciona em cod a operacao \r\n\r\n int_code.append(cod)\r\n break\r\n\r\n operacao, cod = gera_temp(operacao, temp) #passa a operacao e o variavel aux parar se colocada em T1, T2, etc\r\n temp += 1\r\n int_code.append(cod) #salva no código intermediario\r\n\r\n def exporta_codigo():\r\n file = open('configuracao/codigo_intermediario.txt', 'w+')\r\n for x in int_code: #exporta codigo intermediario para cada linha do arquivo_tokens\r\n file.write(str(x).replace('[','').replace(']','').replace(\"'\",'').replace(',','') +'\\n')\r\n\r\n encontra_operacoes()\r\n gera_codigo()\r\n exporta_codigo()\r\n\r\n\r\ndef main():\r\n gramatica['S'] = []\r\n estadoinicial = ''\r\n for x in arquivo_tokens: #le o arquivo_tokens\r\n if ' ::=' in x:\r\n estadoinicial = x\r\n if '::=' in x:\r\n tratar_gramatica(x, estadoinicial) #funcao que trata a gramatica\r\n else:\r\n tratar_token(x) #trata os tokens e salva na regra da gramatica\r\n criar_automato_finitos() \r\n eliminar_et()\r\n determizinar()\r\n buscar_alcansaveis('S')\r\n eliminar_inalcansaveis()\r\n estado_erro()\r\n vivos.extend(regras_finais) #adiciona as regras regras_finais ao vivos\r\n buscar_vivos()\r\n eliminar_mortos()\r\n criar_csv()\r\n analisador_lexico()\r\n analisador_sintatico()\r\n analisador_semantico()\r\n codigo_intermediario()\r\n print('Compilado com sucesso!')\r\n\r\nprint('\\n')\r\nmain()","sub_path":"Compiladores/compilador.py","file_name":"compilador.py","file_ext":"py","file_size_in_byte":22601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"215137759","text":"#!/usr/bin/env python\nu\"\"\"\nhdf5_stokes.py\nWritten by Tyler Sutterley (07/2020)\n\nWrites spherical harmonic coefficients to HDF5 files\n\nCALLING SEQUENCE:\n hdf5_stokes(clm1,slm1,linp,minp,tinp,month,FILENAME=output_HDF5_file)\n\nINPUTS:\n clm1: cosine spherical harmonic coefficients\n slm1: sine spherical harmonic coefficients\n linp: spherical harmonic degree (l)\n minp: spherical harmonic order (m)\n tinp: date of measurement\n month: GRACE/GRACE-FO month\n\nOPTIONS:\n FILENAME: output filename HDF5\n UNITS: spherical harmonic units\n TIME_UNITS: time variable units\n TIME_LONGNAME: time variable description\n MONTHS_NAME: name of months variable within HDF5 file\n MONTHS_UNITS: months variable units\n MONTHS_LONGNAME: months variable description\n TITLE: title attribute of dataset\n CLOBBER: will overwrite an existing HDF5 file\n VERBOSE: will print to screen the HDF5 structure parameters\n DATE: harmonics have date information\n\nPYTHON DEPENDENCIES:\n numpy: Scientific Computing Tools For Python (https://numpy.org)\n h5py: Python interface for Hierarchal Data Format 5 (HDF5)\n (https://www.h5py.org)\n\nUPDATE HISTORY:\n Updated 07/2020: added function docstrings\n Updated 03/2020: only include title if not None\n Updated 10/2019: changing Y/N flags to True/False\n Updated 08/2019: don't include time (HH:MM:SS) in creation date\n Updated 07/2019: added creation date as a global attribute\n Updated 03/2019: print variables keys in list for Python3 compatibility\n Updated 12/2018: using python dictionaries to improve readability\n Updated 10/2018: using future division for python3 Compatibility\n Updated 02/2017: added MONTHS_UNITS, MONTHS_LONGNAME, MONTHS_NAME parameters\n aligned TIME_LONGNAME and TIME_UNITS with attributes\n can output a HDF5 file with multiple dates similar to the netcdf program\n Updated 06/2016: using __future__ print function\n Updated 03/2016: direct calculation of number of harmonics n_harm\n Updated 05/2015: minor change for MMAX != LMAX\n Updated 11/2014: got back to writing this\n in working condition with updated attributes as in netcdf equivalent\n Updated 12/2013: converted ncdf code to HDF5 code (alternative data type)\n Updated 07/2013: switched from Scientific Python to Scipy\n Updated 05/2013 made UNITS an option in case converting the units to\n mass harmonics or other harmonic variant\n Updated 03/2013: added units to clm and slm as 'Geodesy Normalization'\n switched I/O to column arrays for smaller file sizes and compatibility\n between languages\n made date an option for datasets that have no date\n Updated 01/2013 to add time and GRACE/GRACE-FO month number\n Written 07/2012\n\"\"\"\nfrom __future__ import print_function, division\n\nimport time\nimport h5py\nimport numpy as np\n\ndef hdf5_stokes(clm1, slm1, linp, minp, tinp, month, FILENAME=None,\n UNITS='Geodesy_Normalization', TIME_UNITS=None, TIME_LONGNAME=None,\n MONTHS_NAME='month', MONTHS_UNITS='number', MONTHS_LONGNAME='GRACE_month',\n TITLE=None, DATE=True, CLOBBER=True, VERBOSE=False):\n \"\"\"\n Writes spherical harmonic coefficients to HDF5 files\n\n Arguments\n ---------\n clm1: cosine spherical harmonic coefficients\n slm1: sine spherical harmonic coefficients\n linp: spherical harmonic degree (l)\n minp: spherical harmonic order (m)\n tinp: date of measurement\n month: GRACE/GRACE-FO month\n\n Keyword arguments\n -----------------\n FILENAME: HDF5 filename\n UNITS: spherical harmonic units\n TIME_UNITS: time variable units\n TIME_LONGNAME: time variable description\n MONTHS_NAME: name of months variable within HDF5 file\n MONTHS_UNITS: months variable units\n MONTHS_LONGNAME: months variable description\n TITLE: title attribute of dataset\n CLOBBER: will overwrite an existing HDF5 file\n VERBOSE: will print to screen the HDF5 structure parameters\n DATE: harmonics have date information\n \"\"\"\n\n #-- setting HDF5 clobber attribute\n clobber = 'w' if CLOBBER else 'w-'\n #-- opening HDF5 file for writing\n fileID = h5py.File(FILENAME, clobber)\n\n #-- Maximum spherical harmonic degree (LMAX) and order (MMAX)\n LMAX = np.max(linp)\n MMAX = np.max(minp)\n #-- Calculating the number of cos and sin harmonics up to LMAX\n #-- taking into account MMAX (if MMAX == LMAX then LMAX-MMAX=0)\n n_harm = (LMAX**2 + 3*LMAX - (LMAX-MMAX)**2 - (LMAX-MMAX))//2 + 1\n\n #-- Restructuring output matrix to array format\n #-- will reduce matrix size and insure compatibility between platforms\n if DATE:\n if (np.ndim(tinp) == 0):\n n_time = 1\n clm = np.zeros((n_harm))\n slm = np.zeros((n_harm))\n else:\n n_time = len(tinp)\n clm = np.zeros((n_harm,n_time))\n slm = np.zeros((n_harm,n_time))\n else:\n n_time = 0\n clm = np.zeros((n_harm))\n slm = np.zeros((n_harm))\n\n #-- restructured degree and order\n lout = np.zeros((n_harm,), dtype=np.int32)\n mout = np.zeros((n_harm,), dtype=np.int32)\n #-- create counter variable lm\n lm = 0\n for m in range(0,MMAX+1):#-- MMAX+1 to include MMAX\n for l in range(m,LMAX+1):#-- LMAX+1 to include LMAX\n lout[lm] = np.int(l)\n mout[lm] = np.int(m)\n if (DATE and (n_time > 1)):\n clm[lm,:] = clm1[l,m,:]\n slm[lm,:] = slm1[l,m,:]\n else:\n clm[lm] = clm1[l,m]\n slm[lm] = slm1[l,m]\n #-- add 1 to lm counter variable\n lm += 1\n\n #-- Defining the HDF5 dataset variables\n h5 = {}\n h5['l'] = fileID.create_dataset('l', (n_harm,),\n data=lout, dtype=np.int, compression='gzip')\n h5['m'] = fileID.create_dataset('m', (n_harm,),\n data=mout, dtype=np.int, compression='gzip')\n if DATE:\n h5['time'] = fileID.create_dataset('time', (n_time,),\n data=tinp, dtype=np.float, compression='gzip')\n h5['month'] = fileID.create_dataset(MONTHS_NAME, (n_time,),\n data=month, dtype=np.int, compression='gzip')\n #-- if more than 1 date in file\n if (n_time > 1):\n h5['clm'] = fileID.create_dataset('clm', (n_harm,n_time,),\n data=clm, dtype=np.float, compression='gzip')\n h5['slm'] = fileID.create_dataset('slm', (n_harm,n_time,),\n data=slm, dtype=np.float, compression='gzip')\n else:\n h5['clm'] = fileID.create_dataset('clm', (n_harm,),\n data=clm, dtype=np.float, compression='gzip')\n h5['slm'] = fileID.create_dataset('slm', (n_harm,),\n data=slm, dtype=np.float, compression='gzip')\n\n #-- filling HDF5 dataset attributes\n #-- Defining attributes for degree and order\n h5['l'].attrs['long_name'] = 'spherical_harmonic_degree'#-- degree long name\n h5['l'].attrs['units'] = 'Wavenumber'#-- SH degree units\n h5['m'].attrs['long_name'] = 'spherical_harmonic_order'#-- order long name\n h5['m'].attrs['units'] = 'Wavenumber'#-- SH order units\n #-- Defining attributes for dataset\n h5['clm'].attrs['long_name'] = 'cosine_spherical_harmonics'\n h5['clm'].attrs['units'] = UNITS\n h5['slm'].attrs['long_name'] = 'sine_spherical_harmonics'\n h5['slm'].attrs['units'] = UNITS\n if DATE:\n #-- Defining attributes for date and month (or integer date)\n h5['time'].attrs['long_name'] = TIME_LONGNAME\n h5['time'].attrs['units'] = TIME_UNITS\n h5['month'].attrs['long_name'] = MONTHS_LONGNAME\n h5['month'].attrs['units'] = MONTHS_UNITS\n #-- description of file\n if TITLE:\n fileID.attrs['description'] = TITLE\n #-- date created\n fileID.attrs['date_created'] = time.strftime('%Y-%m-%d',time.localtime())\n\n #-- Output HDF5 structure information\n if VERBOSE:\n print(FILENAME)\n print(list(fileID.keys()))\n\n #-- Closing the HDF5 file\n fileID.close()\n","sub_path":"gravity_toolkit/hdf5_stokes.py","file_name":"hdf5_stokes.py","file_ext":"py","file_size_in_byte":7976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"372072275","text":"# from . import *\n\n\nimport glob\nimport os\nimport librosa\n\nimport librosa.display\n#import librosa.logamplitude\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom matplotlib.pyplot import specgram\n\n\n\n\ndef extract_feature(file_name):\n X, sample_rate = librosa.load(file_name)\n stft = np.abs(librosa.stft(X))\n mfccs = np.mean(librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40).T,axis=0) # https://librosa.github.io/librosa/generated/librosa.feature.mfcc.html\n chroma = np.mean(librosa.feature.chroma_stft(S=stft, sr=sample_rate).T,axis=0) # https://librosa.github.io/librosa/generated/librosa.feature.chroma_stft.html\n mel = np.mean(librosa.feature.melspectrogram(X, sr=sample_rate).T,axis=0) # https://librosa.github.io/librosa/generated/librosa.feature.melspectrogram.html\n contrast = np.mean(librosa.feature.spectral_contrast(S=stft, sr=sample_rate).T,axis=0) # https://librosa.github.io/librosa/generated/librosa.feature.spectral_contrast.html\n tonnetz = np.mean(librosa.feature.tonnetz(y=librosa.effects.harmonic(X),\n sr=sample_rate).T,axis=0) # https://librosa.github.io/librosa/generated/librosa.feature.tonnetz.html\n return mfccs,chroma,mel,contrast,tonnetz\n\ndef parse_audio_files(parent_dir,sub_dirs,file_ext=\"*.wav\"):\n features, labels = np.empty((0,193)), np.empty(0)\n # print(\"\\nfound wav in\\n\")\n for label, sub_dir in enumerate(sub_dirs):\n for fn in glob.glob(os.path.join(parent_dir, sub_dir, file_ext)):\n # print(\"\\nfound wav ?\\n\" + fn)\n print(fn)\n try:\n # print(\"\\nfound wav found\\n\")\n mfccs, chroma, mel, contrast,tonnetz = extract_feature(fn)\n # print(\"\\nfound wav not found\\n\")\n except Exception as e:\n # print (\"Error encountered while parsing file: \", fn)\n continue\n ext_features = np.hstack([mfccs,chroma,mel,contrast,tonnetz])\n features = np.vstack([features,ext_features])\n # example of file name : 108041-9-0-4\n labels = np.append(labels, fn.split('/')[2].split('-')[1])\n # labels = np.append(labels, fn.split('/')[2].split('_')[1])\n return np.array(features), np.array(labels, dtype = np.int)\n\ndef one_hot_encode(labels):\n n_labels = len(labels)\n n_unique_labels = len(np.unique(labels))\n one_hot_encode = np.zeros((n_labels,n_unique_labels))\n one_hot_encode[np.arange(n_labels), labels] = 1\n return one_hot_encode\n\nparent_dir = 'Sound-Data'\n# parent_dir = ''\ntr_sub_dirs = [\"fold1\",\"fold2\"]\nts_sub_dirs = [\"fold3\"]\ntr_features, tr_labels = parse_audio_files(parent_dir,tr_sub_dirs)\nts_features, ts_labels = parse_audio_files(parent_dir,ts_sub_dirs)\n\ntr_labels = one_hot_encode(tr_labels)\nts_labels = one_hot_encode(ts_labels)\n\n# ===========================================================\n# Classification using Multilayer Neural Network\n\ntraining_epochs = 50\nn_dim = tr_features.shape[1]\nn_classes = 10\nn_hidden_units_one = 280\nn_hidden_units_two = 300\nsd = 1 / np.sqrt(n_dim)\nlearning_rate = 0.01\n\n# ---------------------\n# X = tf.placeholder(tf.float32,[None,n_dim])\n# Y = tf.placeholder(tf.float32,[None,n_classes])\nX = tf.placeholder(tf.float32,(None,n_dim))\nY = tf.placeholder(tf.float32,(None,n_classes))\n\nW_1 = tf.Variable(tf.random_normal([n_dim,n_hidden_units_one], mean = 0, stddev=sd))\nb_1 = tf.Variable(tf.random_normal([n_hidden_units_one], mean = 0, stddev=sd))\nh_1 = tf.nn.tanh(tf.matmul(X,W_1) + b_1)\n\nW_2 = tf.Variable(tf.random_normal([n_hidden_units_one,n_hidden_units_two],mean = 0, stddev=sd))\nb_2 = tf.Variable(tf.random_normal([n_hidden_units_two], mean = 0, stddev=sd))\nh_2 = tf.nn.sigmoid(tf.matmul(h_1,W_2) + b_2)\n\nW = tf.Variable(tf.random_normal([n_hidden_units_two,n_classes], mean = 0, stddev=sd))\nb = tf.Variable(tf.random_normal([n_classes], mean = 0, stddev=sd))\ny_ = tf.nn.softmax(tf.matmul(h_2,W) + b)\n\n# init = tf.initialize_all_variables()\ninit = tf.global_variables_initializer()\n\n\n# --------------------\ncost_function = -tf.reduce_sum(Y * tf.log(y_))\noptimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost_function)\n\ncorrect_prediction = tf.equal(tf.argmax(y_,1), tf.argmax(Y,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\n\n# ---------------------\ncost_history = np.empty(shape=[1], dtype=float)\ny_true, y_pred = None, None\n\nwith tf.Session() as sess:\n sess.run(init)\n for epoch in range(training_epochs):\n _, cost = sess.run([optimizer, cost_function], feed_dict={X: tr_features, Y: tr_labels}) # 여기서 shape 에러가 뜸.\n cost_history = np.append(cost_history, cost)\n\n y_pred = sess.run(tf.argmax(y_, 1), feed_dict={X: ts_features})\n y_true = sess.run(tf.argmax(ts_labels, 1))\n print(\"Test accuracy: \", round(sess.run(accuracy,feed_dict={X: ts_features, Y: ts_labels}), 3))\n\nfig = plt.figure(figsize=(10, 8))\nplt.plot(cost_history)\nplt.axis([0, training_epochs, 0, np.max(cost_history)])\nplt.show()\n\np, r, f, s = tf.precision_recall_fscore_support(y_true, y_pred, average=\"micro\")\nprint (\"F-Score:\", round(f, 3))","sub_path":"Urban Sound Classification/part1_Feature Extraction/Classification using Multilayer Neural Network main.py","file_name":"Classification using Multilayer Neural Network main.py","file_ext":"py","file_size_in_byte":5114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"248463045","text":"\n\nimport calendar\nimport numpy as np\n#\nfrom .... import global_var\n#\n\n\ndef distribution(ax, \n df,\n figsize,\n nature = None,\n physical_quantity = None,\n ):\n \"\"\"\n Draws in a subplot the boxplots of the weather data.\n \n :param ax: The ax to fill\n :param df: The production data\n :param figsize: Desired size of the figure\n :param nature: The nature of the weather data to plot\n :param weather_quantity: The weather quantity to plot\n :type ax: matplotlib.axes._subplots.AxesSubplot\n :type df: pd.DataFrame\n :type fig_size: (int,int)\n :type nature: string\n :type weather_quantity: string\n :return: None\n :rtype: None\n \"\"\" \n\n data = df.loc[ (df[global_var.weather_nature] == nature)\n & (df[global_var.weather_physical_quantity] == physical_quantity)\n ][global_var.weather_physical_quantity_value]\n \n MONTHS = np.unique(data.index.month)\n YEARS = np.unique(data.index.year)\n\n df_grouped = data.groupby(by = [data.index.year, data.index.month])\n \n interspace_years = 8 \n slice_order = slice(None, None, ( 1\n if figsize[0] > figsize[1]\n else\n -1\n ))\n \n positions = [\n (month - data.index.month.min())*interspace_years + (year - data.index.year.min())\n for year, month in df_grouped.groups.keys()\n ] [slice_order]\n \n labels = [\n calendar.month_abbr[month]\n if year == YEARS.min()\n else \n ''\n for year, month in df_grouped.groups.keys()\n ]\n \n \n widths = [0.9\n for key in df_grouped.groups.keys()\n ]\n \n flierprops = dict(marker = '.', \n markerfacecolor = 'k', \n markersize = 2,\n linestyle = 'none', \n markeredgecolor = 'k',\n )\n \n b_plot = ax.boxplot([df_grouped.get_group(e) for e in df_grouped.groups.keys()], \n vert = figsize[0] > figsize[1], \n positions = positions, \n labels = labels, \n notch = True,\n patch_artist = True,\n widths = widths,\n flierprops = flierprops,\n whis = [1,99],\n )\n \n \n colors = ['pink',\n 'lightblue',\n 'lightgreen',\n 'yellow',\n 'orange',\n ]\n for ii, patch in enumerate(b_plot['boxes']):\n patch.set_facecolor(colors[ii//len(MONTHS)])\n patch.set(linewidth=0.25)\n \n if figsize[0] > figsize[1]: \n ax.yaxis.grid(True)\n ax.set_xlim(-1, interspace_years*(len(MONTHS)-1) + len(YEARS) + 1)\n ax.set_ylabel(physical_quantity)\n else:\n ax.xaxis.grid(True)\n ax.set_ylim(-1, interspace_years*(len(MONTHS)-1) + len(YEARS) + 1)\n ax.set_xlabel(physical_quantity)\n \n \n _ = ax.legend(\n [pp for pp in b_plot['boxes'][::len(MONTHS)]],\n YEARS, \n ncol = 1,\n )","sub_path":"pub_data_visualization/weather/plot/subplot/distribution.py","file_name":"distribution.py","file_ext":"py","file_size_in_byte":3557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"419443410","text":"from flask import Flask, Response, send_file, request\nimport io\nimport random\nimport operator\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nfrom scipy.stats import norm\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom flask_cors import CORS, cross_origin\n\napp = Flask(__name__)\ncors = CORS(app)\napp.config['CORS_HEADERS'] = 'Content-Type'\nplt.style.use('bmh')\n\n\n@app.route('/plot/', methods=['GET', 'POST'])\n@cross_origin()\ndef plot(index):\n index = int(index)\n config = request.json\n fig = Figure()\n if 'finder' in config:\n fig = find(config['finder'])\n elif config:\n fig = create_figure(config, index)\n output = io.BytesIO()\n FigureCanvas(fig).print_png(output)\n return Response(output.getvalue(), mimetype='image/png')\n\n\ndef create_figure(config, index):\n state = State(config)\n state.plot()\n\n fig = Figure(figsize=(6, 6), dpi=240)\n axis = fig.add_subplot(1, 1, 1)\n axis.set_xlim([state.ranges['emin'] *\n state.ranges['chans'] /\n state.ranges['emax'], state.ranges['chans']])\n if index == 0:\n axis.plot(state.plot1[0], state.plot1[1], ',-')\n if index == 1:\n axis.plot(state.plot2[0], state.plot2[1], ',-')\n if index == 2:\n axis.scatter(state.plot3[0], state.plot3[1], s=2)\n if index == 3:\n axis.scatter(state.plot4[0], state.plot4[1], s=2)\n # fig.tight_layout()\n axis.set(xlabel='Channels', ylabel='Intensity', title='')\n return fig\n\n\ndef find(config):\n fig = Figure(figsize=(6, 6), dpi=240)\n axis = fig.add_subplot(1, 1, 1)\n print('peak finder')\n finder = Finder()\n\n plotX = []\n plotY = []\n count = 1\n\n smooth = config['smoothing']\n pmax = int(config['max'])\n pmin = int(config['min'])\n h1 = config['h1']\n h2 = config['h2']\n h3 = config['h3']\n\n for x in range(len(finder.plotX) // smooth):\n sum = 0\n for y in range(smooth):\n sum = sum + int(finder.plotY[smooth*x+y])\n plotX.append(count)\n plotY.append(sum // smooth)\n count = count + 1\n\n secder = []\n par_ar = [i for i in range(pmin, pmax+1)]\n\n for p in par_ar:\n for x in range(p, len(plotX) - p):\n secder.append(plotY[x + 1] - 2 * plotY[x] + plotY[x - 1])\n peak_pos = []\n\n for i in range(p, len(secder) - p):\n if secder[i-p] > h1:\n if secder[i] < -h2:\n if secder[i+p] > h3:\n peak_pos.append(int(i + p))\n\n def gaussian(x, a, mean, sigma):\n return a * np.exp(-((x - mean)**2 / (2 * sigma**2)))\n\n for i in peak_pos[:2]:\n try:\n ys = []\n xs = []\n lin = []\n if i+2*p < len(plotX):\n for j in range(i-2*p, i+2*p+1):\n ys.append(plotY[j])\n xs.append(plotX[j])\n lin = np.linspace(\n ys[0], ys[len(ys)-1], num=len(ys))\n fit_mat = []\n for j in range(len(ys)):\n fit_mat.append(ys[j]-lin[j])\n mu, std = norm.fit(fit_mat)\n graph, _ = curve_fit(\n gaussian, xs, fit_mat, p0=[1, mu, std])\n if graph[0]/p > 2 and graph[1] > 0:\n fit_show = []\n for j in range(len(ys)):\n fit_show.append(\n gaussian(xs[j], *graph)+lin[j])\n axis.plot(xs, fit_show, ',-')\n except e:\n print(e)\n\n axis.scatter(plotX, plotY, s=2)\n\n return fig\n\n\nclass Finder():\n def __init__(self):\n self.plotY = []\n with open('spectrum.dat') as fl:\n for line in fl.readlines():\n self.plotY.append(int(line.split(' ')[1]))\n self.plotX = np.linspace(1, len(self.plotY), num=len(self.plotY))\n\n\nclass State():\n passed = True\n\n def __init__(self, config):\n self.lines = []\n self.background = {}\n self.ranges = {}\n self.config = {'background': True, 'expand': 'FWHM', 'flag': 'first'}\n\n for line in config['lines']:\n self.lines.append({\n 'I': float(line['intensity']),\n 'E': float(line['energy']), # * 1e3,\n 'FWHM': float(line['fwhm']) # * 1e3\n })\n\n self.lines.sort(key=operator.itemgetter('E'))\n\n self.background['a'] = float(config['background']['a'])\n self.background['b'] = float(config['background']['b'])\n self.background['e1'] = float(config['background']['e1'])\n self.background['e2'] = float(config['background']['e2'])\n\n self.ranges['emax'] = float(config['range']['emax']) # * 1e3\n self.ranges['emin'] = float(config['range']['emin']) # * 1e3\n self.ranges['chans'] = float(config['range']['chan_number'])\n\n self.xs = np.linspace(1,\n int(self.ranges['chans']),\n int(self.ranges['chans']))\n self.ys = np.zeros(int(self.ranges['chans']))\n self.plot1 = np.vstack((self.xs, self.ys))\n\n def search(self, my_array, target):\n diff = my_array - target\n mask = np.ma.less_equal(diff, 0)\n if np.all(mask):\n return None\n mask_diff = np.ma.masked_array(diff, mask)\n return mask_diff.argmin()\n\n def plot(self):\n for line in self.lines:\n it = self.search(\n self.plot1[0],\n (line['E'] * (self.ranges['chans']) / (self.ranges['emax']))\n )\n self.plot1[1][it] += line['I']\n self.plot2 = np.array(self.plot1)\n if(self.config['background']):\n self.plot2[1] += (self.background['e1'] *\n np.exp(-1 * self.background['e2'] * self.plot2[0]))\n self.plot2[1] += (self.background['a'] *\n self.plot2[0] + self.background['b'])\n elif(self.config['background'] == False):\n None\n else:\n passed = False\n print(\"Error: background value in config file is undefined\")\n\n self.plot3 = np.array(self.plot2)\n\n if(self.config['expand'] == 'FWHM'):\n for line in self.lines:\n sig = line['FWHM'] / 2.355 * \\\n self.ranges['chans'] / self.ranges['emax']\n gaus = (np.exp(-1 * np.power(self.plot3[0] - (\n line['E'] * self.ranges['chans'] / self.ranges['emax']), 2) / (2 * np.power(sig, 2))))\n self.plot3[1] += line['I'] * gaus\n\n elif(self.config['expand'] == 'None'):\n for line in self.lines:\n it = self.search(\n self.plot3[0],\n (line['E'] *\n self.ranges['chans'] /\n self.ranges['emax']))\n self.plot3[1][it] += line['I']\n else:\n passed = False\n print(\"Error: expand value in config file is undefined\")\n\n self.plot4 = np.array(self.plot3)\n passed_inner = True\n if(self.config['flag'] == 'second'):\n A, B = np.shape(plot4)\n i = 0\n for i in range(B):\n lam = self.plot4[1][i]\n if(lam >= 0):\n self.plot4[1][i] = np.random.poisson(lam=lam, size=None)\n else:\n passed_inner = False\n elif(self.config['flag'] == 'first'):\n A, B = np.shape(self.plot4)\n i = 0\n for i in range(B):\n if(self.plot4[1][i] > 10):\n mu = self.plot4[1][i]\n sigma = np.sqrt(self.plot4[1][i])\n self.plot4[1][i] = random.gauss(mu, sigma)\n else:\n lam = self.plot4[1][i]\n if(lam >= 0):\n self.plot4[1][i] = np.random.poisson(lam=lam,\n size=None)\n else:\n passed_inner = False\n elif(self.config['flag'] == 'None'):\n None\n else:\n passed = False\n print(\"Error: flag value in config file is undefined\")\n","sub_path":"plt/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"81393204","text":"import cv2\nimport pytesseract\nimport numpy as np\nfrom PIL import Image, ImageOps\n\ndef add_border(input_image, output_image, border):\n img = Image.open(input_image)\n \n if isinstance(border, int) or isinstance(border, tuple):\n bimg = ImageOps.expand(img, border=border)\n else:\n raise RuntimeError('border is not an integer or tuple!')\n \n bimg.save(output_image)\n \n\n\n\npytesseract.pytesseract.tesseract_cmd = r'C:\\\\Program Files\\\\Tesseract-OCR\\\\tesseract.exe'\n\ncascade=cv2.CascadeClassifier(\"src\\data\\haarcascade_russian_plate_number.xml\")\n\n\n\ndef extract_num(img_name):\n global text\n img=cv2.imread(img_name)\n gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n nplate=cascade.detectMultiScale(gray,1.1,4) #number-plate detection\n\n #cropping the plate\n for (x,y,w,h) in nplate :\n a,b=(int(0.02*img.shape[0]) ,int(0.025*img.shape[1]))\n cropped_img=img[y+a:y+h-a , x+b:x+w-b, :]\n\n #image processing (on the cropped image)\n kernel=np.ones((1,1) , np.uint8)\n cropped_img=cv2.dilate(cropped_img ,kernel,iterations=1)\n cropped_img=cv2.erode(cropped_img,kernel,iterations=1)\n\n \n\n # convertion the plate image to the gray scale\n plate_gray=cv2.cvtColor(cropped_img, cv2.COLOR_BGR2GRAY)\n #convertion the plate image to black&white only 1\n (thresh , cropped_img)=cv2.threshold(plate_gray,127,255,cv2.THRESH_BINARY)\n\n cropped_img_loc= \"plate.png\"\n cv2.imwrite(cropped_img_loc,cropped_img)\n cv2.imshow(\"cropped image\", cv2.imread(cropped_img_loc))\n #cv2.imshow(\"threshold-image\" , plate)\n #cv2.imwrite(\"temp.png\",plate)\n #adding a border \n add_border(cropped_img_loc, output_image='cropped_img_bord.jpg',border=150)\n\n #convertion the plate image to a text \n text=pytesseract.image_to_string('cropped_img_bord.jpg')\n #deleting spaces\n text=''.join(e for e in text if e.isalnum())\n print(\"number is : \" , text)\n \n #drawing a rectangle around the plate\n cv2.rectangle(img , (x,y) , (x+w,y+h) ,(51,51,255), 2)\n cv2.rectangle(img , (x, y-40) ,(x+w,y) ,(51,51,255),-1)\n\n #put the text on the rectangle\n cv2.putText(img,text,(x,y-10),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,255),2,cv2.LINE_AA)\n #cv2.imshow(\"Plate\",cropped_img)\n\n\n\n cv2.imshow(\"Result\",img)\n cv2.imwrite(\"Result.jpg\",img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\nextract_num('src\\images\\car_1.jpg')\n\n\n\n\n \n\n \n\n\n ","sub_path":"src/yt_testing.py","file_name":"yt_testing.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"355094055","text":"__author__ = [('Naufan Rusyda Faikar', 'idmuslimdev@gmail.com')]\n__version__ = '0.1'\n\n\nfrom PyQt5.QtCore import QRect, Qt, QPoint, QPointF\nfrom PyQt5.QtWidgets import QWidget, QVBoxLayout\nfrom PyQt5.QtGui import QPaintEvent, QPainter, QBrush, QColor, QPen\n\nfrom enum import Enum, auto\nfrom typing import List\n\n\nclass WidgetType(Enum):\n LINE = auto()\n PLOT = auto()\n RECT = auto()\n TEXTBOX = auto()\n\n\nclass Drawing():\n\n def __init__(self, points: List[QPoint],\n fill_color: str = '#00000000',\n fill_pattern: Qt.BrushStyle = Qt.SolidPattern,\n stroke_color: str = '#00000000',\n stroke_size: int = 0,\n stroke_style: Qt.PenStyle = Qt.SolidLine):\n self.points = points\n self.fill_color = fill_color\n self.fill_pattern = fill_pattern\n self.stroke_color = stroke_color\n self.stroke_size = stroke_size\n self.stroke_style = stroke_style\n\n @property\n def points(self) -> List[QPointF]:\n return self._points\n\n @points.setter\n def points(self, points: List[QPointF]) -> None:\n self._points = points\n\n @property\n def fill_color(self) -> str:\n return self._fill_color\n\n @fill_color.setter\n def fill_color(self, color: str) -> None:\n self._fill_color = color # dalam HEX\n\n @property\n def fill_pattern(self) -> Qt.BrushStyle:\n return self._fill_pattern\n\n @fill_pattern.setter\n def fill_pattern(self, style: Qt.BrushStyle) -> None:\n self._fill_pattern = style\n\n @property\n def stroke_color(self) -> str:\n return self._stroke_color\n\n @stroke_color.setter\n def stroke_color(self, color: str) -> None:\n self._stroke_color = color # dalam HEX\n\n @property\n def stroke_size(self) -> int:\n return self._stroke_size\n\n @stroke_size.setter\n def stroke_size(self, size: int) -> None:\n self._stroke_size = size # dalam piksel\n\n @property\n def stroke_style(self) -> Qt.PenStyle:\n return self._stroke_style\n\n @stroke_style.setter\n def stroke_style(self, style: Qt.PenStyle) -> None:\n self._stroke_style = style\n\n\nclass Widget(QWidget):\n\n def __init__(self, parent: QWidget, rect: QRect,\n type_: WidgetType = WidgetType.PLOT,\n child: QWidget = None) -> None:\n super().__init__(parent=parent)\n\n self.setAttribute(Qt.WA_DeleteOnClose, True)\n self.setVisible(True)\n self.setMouseTracking(False)\n rect = rect.toRect()\n rect.adjust(1, 1, 0, 0)\n self.setGeometry(rect)\n\n self.layout = QVBoxLayout(self)\n self.layout.setContentsMargins(0, 0, 0, 0)\n\n self.type_ = type_\n self.child = child\n # rect.adjust(0, 0, 1, 1)\n self.drawing = Drawing([\n QPointF(0, 0),\n QPointF(rect.topRight() - rect.topLeft()),\n QPointF(rect.bottomRight() - rect.topLeft()),\n QPointF(rect.bottomLeft() - self.geometry().topLeft())\n ])\n self.rotation = 0 # dalam derajat\n self.moveable = True\n self.rotatable = True\n self.resizable = True\n\n def paintEvent(self, painter: QPaintEvent) -> None:\n painter = QPainter(self)\n painter.setRenderHint(QPainter.RenderHint(\n # QPainter.Antialiasing |\n QPainter.SmoothPixmapTransform |\n QPainter.HighQualityAntialiasing)\n )\n self.paint(painter)\n painter.end()\n\n def paint(self, painter: QPainter) -> None:\n # Mengeset drawing style\n if self.drawing.stroke_color.lower() not in ['#00000000',\n 'transparent'] \\\n and self.drawing.stroke_size > 0 \\\n and self.drawing.stroke_style is not Qt.NoPen:\n pen = QPen(QColor(self.drawing.stroke_color),\n self.drawing.stroke_size, self.drawing.stroke_style)\n pen.setCosmetic(True)\n pen.setJoinStyle(Qt.MiterJoin)\n painter.setPen(pen)\n else:\n painter.setPen(Qt.NoPen)\n if self.drawing.fill_color.lower() not in ['#00000000', 'transparent'] \\\n and self.drawing.fill_pattern is not Qt.NoBrush:\n painter.setBrush(QBrush(QColor(self.drawing.fill_color),\n self.drawing.fill_pattern))\n\n # Tweaks untuk menggambar border\n if self.drawing.stroke_size > 1: # \\\n # and self.drawing.stroke_style is not Qt.NoPen:\n painter.translate(self.drawing.stroke_size / 2,\n self.drawing.stroke_size / 2)\n size = self.geometry().bottomRight() - self.geometry().topLeft()\n offset = QPoint(self.drawing.stroke_size - 1,\n self.drawing.stroke_size - 1)\n painter.scale(size.x() / (size.x() + offset.x()),\n size.y() / (size.y() + offset.y()))\n else:\n # FIXME: ada gap 1px di sisi kanan dan bawah drawing\n # untuk sementara, dipaksa supaya stroke_size >= 1\n # painter.translate(1, 1)\n pass\n\n # Menggambar objek drawing\n str_points = ''\n for i in range(len(self.drawing.points)):\n str_points += 'self.drawing.points[{}]'.format(i)\n if i + 1 < len(self.drawing.points):\n str_points += ', '\n if str_points:\n exec('painter.drawPolygon({})'.format(str_points))\n\n @property\n def child(self) -> QWidget:\n return self._child\n\n @child.setter\n def child(self, cwidget: QWidget):\n self._child = cwidget\n if cwidget is not None:\n self._child.setParent(self)\n self._child.releaseMouse()\n self.layout.addWidget(cwidget)\n self.child.setAttribute(\n Qt.WA_TransparentForMouseEvents, True)\n self.update()\n\n @property\n def type_(self) -> WidgetType:\n return self._type\n\n @type_.setter\n def type_(self, type_: WidgetType) -> None:\n self._type = type_\n\n @property\n def drawing(self) -> List[QPoint]:\n return self._drawing\n\n @drawing.setter\n def drawing(self, geometry: List[QPoint]) -> None:\n self._drawing = geometry\n\n @property\n def rotation(self) -> int:\n return self._rotation\n\n @rotation.setter\n def rotation(self, rotatation: int) -> None:\n self._rotation = rotatation\n\n @property\n def moveable(self) -> bool:\n return self._moveable\n\n @moveable.setter\n def moveable(self, state: bool) -> None:\n self._moveable = state\n\n @property\n def resizable(self) -> bool:\n return self._resizable\n\n @resizable.setter\n def resizable(self, state: bool):\n self._resizable = state\n\n @property\n def rotatable(self) -> bool:\n return self._rotatable\n\n @rotatable.setter\n def rotatable(self, state: bool) -> None:\n self._rotatable = state\n","sub_path":"src/component/widget.py","file_name":"widget.py","file_ext":"py","file_size_in_byte":7033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"306544258","text":"from Generic.filedialogs import BatchProcess\nfrom Generic.video import ReadVideo\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\ndef intensity_img(filename):\n readvid = ReadVideo(filename=file)\n frame_init = readvid.read_next_frame() # .astype(np.int32)\n\n\n intensity=[]\n for i in range(int(readvid.num_frames/10) - 1):\n frame = readvid.find_frame(i*10).astype(np.int32)\n intensity.append(np.mean(frame))\n intensity=np.array(intensity)\n\n print(np.mean(intensity))\n\n readvid.close()\n\n\nif __name__ == '__main__':\n for file in BatchProcess(pathfilter='/media/ppzmis/data/ActiveMatter/Microscopy/191126_500nm_particles/StreamDIC002.avi'):\n intensity_img(file)","sub_path":"preprocessing/intensity.py","file_name":"intensity.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"146599499","text":"\"\"\"Directory operations\n\"\"\"\n\nimport os\nfrom typing import Optional\nfrom lib.commands.core.custom_types import Config\n\n\ndef get_dir_name(dir_type: str) -> str:\n \"\"\"Get a specific directory name\n\n Args:\n dir_type (str): A type of directory\n\n Returns:\n str: A name of directory\n \"\"\"\n if dir_type == \"DOCUMENT\":\n return \".docs\"\n elif dir_type == \"HISTORY\":\n return \".histories\"\n elif dir_type == \"TODO\":\n return \".todo\"\n elif dir_type == \"MEMO\":\n return \".memo\"\n elif dir_type == \"TAG\":\n return \".tags\"\n elif dir_type == \"DOMAIN\":\n return \".domains\"\n elif dir_type == \"METADATA\":\n return \".metadata\"\n else:\n raise Exception(f\"No such dir_type: {dir_type}\")\n\n\ndef get_dir_path(dir_type: str, config: Config) -> Optional[str]:\n \"\"\"Get an absolute path of directory\n\n Args:\n dir_type (str): A directory type\n config (Config): Config data\n\n Returns:\n Optional[str]: A path\n \"\"\"\n dir_name = get_dir_name(dir_type)\n root_path: str = config[\"root_path\"]\n uuid: str = config[\"uuid\"]\n if root_path and uuid:\n doc_dir = f\"{root_path}/{dir_name}/{uuid}\"\n return doc_dir\n else:\n return None\n\n\ndef make_directory(dir_type: str, config: Config) -> None:\n \"\"\"Make a specific directory if it doesn't exist\n\n Args:\n dir_type (str): A directory type\n config (Config): Config data\n \"\"\"\n dir_path = get_dir_path(dir_type, config),\n if not os.path.isdir(dir_path):\n os.makedirs(dir_path)","sub_path":"lib/commands/core/dir_ops.py","file_name":"dir_ops.py","file_ext":"py","file_size_in_byte":1573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"364770496","text":"#!/usr/bin/env python\r\n# coding=utf-8\r\n\r\nimport os.path\r\n\r\nimport tornado.httpserver\r\nimport tornado.ioloop\r\nimport tornado.options\r\nimport tornado.web\r\n\r\nfrom tornado.options import define, options\r\ndefine(\"port\", default=8000, help=\"run on the given port\", type=int)\r\n\r\nclass IndexHandler(tornado.web.RequestHandler):\r\n def get(self):\r\n self.render(\"index.html\")\r\n \r\n\r\nclass UserHandler(tornado.web.RequestHandler):\r\n def post(self):\r\n html_user = self.get_argument(\"username\") \r\n\r\n self.render(\"user.html\",username=\"李刚\",email=\"vagabond1132@gmail.com\",website=\"123\",language=\"chinese\")\r\n\r\nhandlers = [\r\n (\"/\", IndexHandler),\r\n (\"/user\", UserHandler)\r\n]\r\n\r\ntemplate_path = os.path.join(os.path.dirname(__file__),\"template\")\r\n\r\nif __name__ == \"__main__\":\r\n tornado.options.parse_command_line() \r\n app = tornado.web.Application(handlers, template_path) \r\n http_server = tornado.httpserver.HTTPServer(app) \r\n http_server.listen(options.port) # 8000端口\r\n tornado.ioloop.IOLoop.instance().start()\r\n # 监听到 服务端的url 进行 链接的处理 -- 转到 类中,输出;\r\n","sub_path":"python/template/sendhtml.py","file_name":"sendhtml.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"631135996","text":"# -*- coding: UTF-8 -*-\n\nimport ssl\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\n\nfrom lol.model.hero import HeroInfo\n\n\n# 获取html数据\ndef get_html(url):\n ssl._create_default_https_context = ssl._create_unverified_context\n return requests.get(url).content\n\n\ndef parse_json(json_str):\n json_data = json.loads(json_str)\n json_list = json_data['data']\n hero_list = []\n for key in json_list:\n content = json_list[key]\n hero = HeroInfo(int(content['key']), content['title'], content['name'])\n hero.icon = content['image']['full']\n hero.tags = content['tags']\n hero.desc = content['id']\n hero_list.append(hero)\n print(content)\n return hero_list\n\n\ndef parse_hero(html_str):\n soup = BeautifulSoup(html_str, 'html.parser')\n li_list = soup.find('ul', id=\"champion_list\").find_all(\"li\")\n return li_list\n\n\ndef parse_hero_info(hero_tag, index):\n content_tag = hero_tag.find(\"a\")\n desc_tag = hero_tag.find_all(\"div\")[1]\n\n if content_tag and desc_tag:\n content_url = content_tag.get(\"href\")\n icon_url = content_tag.find(\"img\").get(\"src\")\n name = desc_tag.h2.string\n nick_name = desc_tag.h3.string\n desc = desc_tag.p.string\n tags = desc_tag.div.span.string\n\n hero_info = HeroInfo(index, name, nick_name)\n hero_info.icon_url = icon_url\n hero_info.content_url = content_url\n hero_info.desc = desc\n hero_info.tags = tags\n return hero_info\n\n\ndef save_lines_file(lines_data, save_path):\n # wb 写入二进制\n # w 写入文本\n # 1.打开文件\n file_point = open(save_path, 'w')\n # 2.写入数据\n file_point.writelines(lines_data)\n # 3.关闭文件\n file_point.close()\n","sub_path":"lol/parser/lol_hero.py","file_name":"lol_hero.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"510737570","text":"import logging\n\nimport pygame\n\nfrom ghettogames.events import ResourceManager\n\n\nlog = logging.getLogger('game.sounds')\nlog.addHandler(logging.NullHandler())\n\n\nclass SoundManager(ResourceManager):\n def __init__(self, game=None):\n \"\"\"\n Manage sounds.\n\n SoundManager manages sounds.\n\n Args:\n ----\n game -\n\n \"\"\"\n super().__init__(game=game)\n\n # Set the mixer pre-init settings\n pygame.mixer.pre_init(22050, -16, 2, 1024)\n pygame.mixer.init()\n\n # Sound Stuff\n # pygame.mixer.get_init() -> (frequency, format, channels)\n (sound_frequency, sound_format, sound_channels) = pygame.mixer.get_init()\n log.info('Mixer Settings:')\n log.info(\n f'Frequency: {sound_frequency}, '\n f'Format: {sound_format}, '\n f'Channels: {sound_channels}'\n )\n\n @classmethod\n def args(cls, parser):\n group = parser.add_argument_group('Sound Mixer Options') # noqa: W0612\n\n return parser","sub_path":"ghettogames/sounds.py","file_name":"sounds.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"108083264","text":"import random\n\n#Forca\nboard = ['''\n------------->>Hangman<<--------------\n\n +----+\n | |\n |\n |\n |\n |\n==============''','''\n +----+\n | |\n O |\n |\n |\n |\n==============''','''\n +----+\n | |\n O |\n | |\n |\n |\n==============''','''\n +----+\n | |\n O |\n/| |\n |\n |\n==============''','''\n +----+\n | |\n O |\n/|\\ |\n |\n |\n==============''','''\n +----+\n | |\n O |\n/|\\ |\n/ |\n |\n==============''','''\n +----+\n | |\n O |\n/|\\ |\n/ \\ |\n |\n==============''']\n\n#Classe da forca\nclass Hangman:\n # Método construtor\n def __init__(self, string):\n self.string = string\n self.status = 0\n self.dont_see = ['-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-','-']\n # Advinha a letra\n def guess(self, letter):\n letter = input('Qual letra voce escolhe?')\n if letter in self.string:\n self.dont_see[self.string.c]\n return self.status\n else :\n return self.status + 1\n \n # Verifica se o jogo terminou\n def game_end(self):\n if self.status == 6:\n return 1\n\n # Verifica se o jogador ganhou\n def winner(self):\n print(\"alo\")\n # Não mostra letra no board\n def hide_word(self):\n print(dont_see[:len(self.string)])\n # Status do game\n def print_game_status(self):\n print(board[self.status])\n# Função para leitura do banco\ndef rand_word():\n with open('palavras.txt', 'rt') as f:\n bank = f.readlines()\n return bank[random.randint(0, len(bank))].strip()\n\ndef main():\n game = Hangman(rand_word()) \n\n game.print_game_status()\n\n # De acordo com o resultado, imprime a mensagem na tela\n if game.winner():\n print('\\nParabéns você completou a palavra')\n else:\n print('\\nGame over!')\n print('\\nA palavra era '+ game.string)\n print('Foi bom jogar com você!')\n\n# Executa o programa\nif __name__ == '__main__':\n main()","sub_path":"Laboratorio3/forca.py","file_name":"forca.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"83835650","text":"\nfrom flask import Flask, render_template, request, redirect, url_for\nimport pandas\nfrom pandas import DataFrame, to_datetime\nimport numpy as np\nimport json\nimport os\nfrom datetime import datetime, timedelta\nimport requests\nfrom bokeh.plotting import figure, output_file, show\nfrom bokeh.embed import components\nfrom bokeh.resources import INLINE\n\n# from bokeh.util.string import encode_utf8\n\napp = Flask(__name__)\n\n@app.route('/')\ndef main():\n return redirect('/index')\n\n@app.route('/index',methods=['GET','POST'])\ndef index():\n return render_template('index.html')\n\ndef make_plot():\n now = datetime.now()\n date_end = now.strftime('%Y-%m-%d')\n date_start = (now-timedelta(days=31)).strftime('%Y-%m-%d')\n\n ticker = request.form['ticker']\n features = request.form.getlist('features')\n\n URL = 'https://www.quandl.com/api/v3/datasets/WIKI/'+ticker+'.json?start_date='+date_start+'&end_date='+date_end\n r = requests.get(URL)\n request_df = DataFrame(r.json())\n df = DataFrame(request_df.ix['data','dataset'],columns=request_df.ix['column_names','dataset'])\n df.columns = [x.lower() for x in df.columns]\n df = df.set_index(['date'])\n df.index = to_datetime(df.index)\n\n p = figure(x_axis_type=\"datetime\",width=800,height=800)\n p.xaxis.axis_label = \"Date\"\n p.ygrid.band_fill_color = \"olive\"\n p.ygrid.band_fill_alpha = 0.1\n if 'Open' in features:\n p.line(df.index,df['open'], legend='opening price')\n if 'Adj. Open' in features:\n p.line(df.index,df['adj. open'], legend='adjusted opening price')\n if 'Close' in features:\n p.line(df.index,df['close'], legend='closing price')\n if 'Adj. Close' in features:\n p.line(df.index,df['adj. close'], legend='adjusted closing price')\n return p\n\n\n@app.route('/plot',methods=['POST'])\ndef plot():\n plot = make_plot()\n js_resources = INLINE.render_js()\n css_resources = INLINE.render_css()\n script, div = components(plot, INLINE)\n return render_template('plot.html',plot_script=script,plot_div=div,\n js_resources=js_resources,css_resources=css_resources)\n\n# @app.route('/error',methods=['GET','POST'])\n# def error():\n# return render_template('error.html')\n\nif __name__ == '__main__':\n port = int(os.environ.get(\"PORT\", 5000))\n app.run(host='0.0.0.0', port=port)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"229923459","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun May 21 12:28:27 2017\n\n@author: albert\n\"\"\"\nfrom nltk.tokenize import RegexpTokenizer\nimport re\nfrom textmt.tokenise.regex import MTRegex\n\nclass MTTokenizer(RegexpTokenizer):\n\n\tdef __init__(self, *args):\n\t\t'''Initialise an MTTokenizer with a sequence of regexps that match different tokens. \n\t\tThese are internally compiled in a disjunction (a|b|..|z)'''\n\n\t\tif len(args) == 0:\n\t\t\targs = [MTRegex.NUMERIC_DATE, MTRegex.DECIMAL, MTRegex.NUMBER,\n\t\t\t\t\tMTRegex.DEF_ARTICLE, MTRegex.DEF_NUMERAL, \n\t\t\t\t\tMTRegex.PROCLITIC_PREP,MTRegex.WORD,\t\t\t\t\t\n\t\t\t\t\tMTRegex.END_PUNCTUATION]\n\n\t\tsuper().__init__(\"|\".join(args), gaps=False, discard_empty=True,\n flags=re.UNICODE | re.MULTILINE | re.DOTALL | re.IGNORECASE)\n","sub_path":"textmt/tokenise/tokenise.py","file_name":"tokenise.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"462209340","text":"import importlib\nimport pkgutil\nimport inspect\n\nfrom fastapi import FastAPI\nfrom pydantic import BaseSettings\n\nimport odpapi_adapters\n\n\nclass ODPAPIAdapterConfig(BaseSettings):\n pass\n\n\nclass ODPAPIAdapter:\n def __init__(self, app: FastAPI, config: ODPAPIAdapterConfig):\n self.app = app\n self.config = config\n self.app_config = self.app.extra['config']\n\n\ndef load_adapters(app: FastAPI):\n adapter_classes = {}\n config_classes = {}\n for module_info in pkgutil.iter_modules(odpapi_adapters.__path__, odpapi_adapters.__name__ + '.'):\n module = importlib.import_module(module_info.name)\n adapter_classes.update({\n name: cls for (name, cls) in inspect.getmembers(module, lambda x: inspect.isclass(x) and\n x is not ODPAPIAdapter and\n issubclass(x, ODPAPIAdapter))\n })\n config_classes.update({\n name: cls for (name, cls) in inspect.getmembers(module, lambda x: inspect.isclass(x) and\n x is not ODPAPIAdapterConfig and\n issubclass(x, ODPAPIAdapterConfig))\n })\n\n adapters = {}\n for adapter_name, adapter_cls in adapter_classes.items():\n config_name = adapter_name + 'Config'\n config_cls = config_classes[config_name]\n adapters[adapter_name] = adapter_cls(app, config_cls())\n\n app.extra['adapters'] = adapters\n","sub_path":"odpapi/adapters.py","file_name":"adapters.py","file_ext":"py","file_size_in_byte":1630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"635814613","text":"import numpy as np\nfrom numpy.linalg import inv\nfrom util import Util\nfrom sklearn.preprocessing import PolynomialFeatures\nimport matplotlib.pyplot as plt\ntest=Util()\nrad = 10\nthk = 5\nsep = -5\nN = 2000\n\nX, y = test.generatedata(rad, thk, sep, N)\n\nplt.scatter(X[y>0][:, 0], X[y>0][:, 1], s=1)\nplt.scatter(X[y<0][:, 0], X[y<0][:, 1], s=1)\nplt.show()\n\nmax_step = 10000\n\nt = np.arange(max_step)\nr = 2 * (rad + thk)\npoly = PolynomialFeatures(3)\nX_poly = poly.fit_transform(X)\n\nn = 2000\n\na = np.linspace(-r, r, n)\nb = np.linspace(-r, r, n)\n\n\nA, B = np.meshgrid(a, b)\nmax_step = 10000\n\nW_poly, W_poly_hat, w_poly, error_poly = test.Pocket_PLA(X_poly, y, max_step=max_step)\nEin_poly = np.mean(np.sign(W_poly_hat.dot(X_poly.T)) != y, axis=1)\n\nplt.plot(t, Ein_poly)\nplt.title('Ein VS t')\nplt.show()\nX1 = np.c_[A.reshape(-1, 1), B.reshape(-1, 1)]\npoly = PolynomialFeatures(3)\nX_poly1 = poly.fit_transform(X1)\n\n\nresult = X_poly1.dot(w_poly)\n\nresult = np.reshape(result, np.shape(A))\n# print(result)\nplt.contour(A, B, result, 1, colors = 'red')\nplt.scatter(X[y>0][:, 0], X[y>0][:, 1], s=1)\nplt.scatter(X[y<0][:, 0], X[y<0][:, 1], s=1)\nplt.title('Pocket PLA')\nplt.show()\nprint('Pocket PLA error rate' + str(error_poly / N))\n\n\n\n\nw_poly_lr = inv(X_poly.T.dot(X_poly)).dot(X_poly.T).dot(y)\nX1 = np.c_[A.reshape(-1, 1), B.reshape(-1, 1)]\npoly = PolynomialFeatures(3)\nX_poly1 = poly.fit_transform(X1)\n\n\nresult = X_poly1.dot(w_poly_lr)\n\nresult = np.reshape(result, np.shape(A))\nplt.contour(A, B, result, 1, colors = 'red')\nplt.scatter(X[y>0][:, 0], X[y>0][:, 1], s=1)\nplt.scatter(X[y<0][:, 0], X[y<0][:, 1], s=1)\nplt.title('Linear regression')\nplt.show()\nerror = np.mean(np.sign(X_poly.dot(w_poly_lr)) != y)\nprint('linear regression error rate' + str(error))\n","sub_path":"homework/hw2_ml/code/5-d.py","file_name":"5-d.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"52544515","text":"# -*- coding: utf-8 -*-\n\n\"\"\"This script compares what's in each resource.\"\"\"\n\nimport datetime\nimport itertools as itt\nimport math\nimport os\nimport random\nimport sys\nfrom collections import Counter\nfrom typing import Collection, Set\n\nimport click\n\nfrom bioregistry import (\n get_description, get_email, get_example, get_format, get_homepage, get_name, get_obo_download, get_owl_download,\n get_pattern, get_version, read_registry,\n)\nfrom bioregistry.constants import DOCS_IMG\nfrom bioregistry.external import (\n get_biolink, get_bioportal, get_go, get_miriam, get_n2t, get_ncbi, get_obofoundry, get_ols, get_prefix_commons,\n get_wikidata_registry,\n)\n\nbioregistry = read_registry()\n\nLICENSES = {\n 'None': None,\n 'license': None,\n 'unspecified': None,\n # CC-BY (4.0)\n 'CC-BY 4.0': 'CC-BY',\n 'CC BY 4.0': 'CC-BY',\n 'https://creativecommons.org/licenses/by/4.0/': 'CC-BY',\n 'http://creativecommons.org/licenses/by/4.0/': 'CC-BY',\n 'http://creativecommons.org/licenses/by/4.0': 'CC-BY',\n 'https://creativecommons.org/licenses/by/3.0/': 'CC-BY',\n 'url: http://creativecommons.org/licenses/by/4.0/': 'CC-BY',\n 'SWO is provided under a Creative Commons Attribution 4.0 International'\n ' (CC BY 4.0) license (https://creativecommons.org/licenses/by/4.0/).': 'CC-BY',\n # CC-BY (3.0)\n 'CC-BY 3.0 https://creativecommons.org/licenses/by/3.0/': 'CC-BY',\n 'http://creativecommons.org/licenses/by/3.0/': 'CC-BY',\n 'CC-BY 3.0': 'CC-BY',\n 'CC BY 3.0': 'CC-BY',\n 'CC-BY version 3.0': 'CC-BY',\n # CC-BY (2.0)\n 'CC-BY 2.0': 'CC-BY',\n # CC-BY (unversioned)\n 'CC-BY': 'CC-BY',\n 'creative-commons-attribution-license': 'CC-BY',\n # CC-BY-SA\n 'CC-BY-SA': 'CC-BY-SA',\n 'https://creativecommons.org/licenses/by-sa/4.0/': 'CC-BY-SA',\n # CC-BY-NC-SA\n 'http://creativecommons.org/licenses/by-nc-sa/2.0/': 'CC-BY-NC-SA',\n # CC 0\n 'CC-0': 'CC-0',\n 'CC0 1.0 Universal': 'CC-0',\n 'CC0': 'CC-0',\n 'http://creativecommons.org/publicdomain/zero/1.0/': 'CC-0',\n 'https://creativecommons.org/publicdomain/zero/1.0/': 'CC-0',\n # Apache 2.0\n 'Apache 2.0 License': 'Other',\n 'LICENSE-2.0': 'Other',\n 'www.apache.org/licenses/LICENSE-2.0': 'Other',\n # Other\n 'GNU GPL 3.0': 'Other',\n 'hpo': 'Other',\n 'Artistic License 2.0': 'Other',\n 'New BSD license': 'Other',\n}\n\n\ndef _remap_license(k):\n return k and LICENSES.get(k, k)\n\n\nSINGLE_FIG = (8, 3.5)\nTODAY = datetime.datetime.today().strftime('%Y-%m-%d')\nWATERMARK_TEXT = f'https://github.com/bioregistry/bioregistry ({TODAY})'\n\n\n@click.command()\ndef compare(): # noqa:C901\n \"\"\"Compare the registries.\"\"\"\n random.seed(0)\n try:\n import matplotlib.pyplot as plt\n import seaborn as sns\n from matplotlib_venn import venn2\n except ImportError:\n click.secho(\n 'Could not import matplotlib dependencies.'\n ' Install bioregistry again with `pip install bioregistry[charts]`.',\n fg='red',\n )\n return sys.exit(1)\n\n watermark = True\n sns.set_style('whitegrid')\n\n ###############################################\n # What kinds of licenses are resources using? #\n ###############################################\n licenses, conflicts, obo_has_license, ols_has_license = _get_license_and_conflicts()\n\n # How many times does the license appear in OLS / OBO Foundry\n fig, ax = plt.subplots(figsize=SINGLE_FIG)\n venn2(\n subsets=(obo_has_license, ols_has_license),\n set_labels=('OBO', 'OLS'),\n set_colors=('red', 'green'),\n ax=ax,\n )\n if watermark:\n ax.text(\n 0.5, -0.1, WATERMARK_TEXT, transform=plt.gca().transAxes,\n fontsize=10, color='gray', alpha=0.5,\n ha='center', va='bottom',\n )\n\n path = os.path.join(DOCS_IMG, 'license_coverage.svg')\n click.echo(f'output to {path}')\n fig.tight_layout()\n fig.savefig(path, dpi=300)\n plt.close(fig)\n\n fig, ax = plt.subplots(figsize=SINGLE_FIG)\n sns.countplot(x=licenses, ax=ax)\n ax.set_xlabel('License')\n ax.set_ylabel('Count')\n ax.set_yscale('log')\n if watermark:\n fig.text(\n 1.0, 0.5, WATERMARK_TEXT,\n fontsize=8, color='gray', alpha=0.5,\n ha='right', va='center', rotation=90,\n )\n\n path = os.path.join(DOCS_IMG, 'licenses.svg')\n click.echo(f'output to {path}')\n fig.tight_layout()\n fig.savefig(path, dpi=300)\n plt.close(fig)\n\n ##############################################\n # How many entries have version information? #\n ##############################################\n def _get_has(f):\n return {key for key in bioregistry if f(key)}\n\n has_wikidata_database = {\n key\n for key, entry in bioregistry.items()\n if 'database' in entry.get('wikidata', {})\n }\n measurements = [\n ('Name', _get_has(get_name)),\n ('Description', _get_has(get_description)),\n ('Version', _get_has(get_version)),\n ('Homepage', _get_has(get_homepage)),\n ('Contact Email', _get_has(get_email)),\n ('Pattern', _get_has(get_pattern)),\n ('Format URL', _get_has(get_format)),\n ('Example', _get_has(get_example)),\n ('Wikidata Database', has_wikidata_database),\n ('OBO', _get_has(get_obo_download)),\n ('OWL', _get_has(get_owl_download)),\n ]\n\n ncols = 3\n nrows = int(math.ceil(len(measurements) / ncols))\n fig, axes = plt.subplots(ncols=ncols, nrows=nrows)\n for measurement, ax in itt.zip_longest(measurements, axes.ravel()):\n if measurement is None:\n ax.axis('off')\n continue\n label, prefixes = measurement\n ax.pie(\n (len(prefixes), len(bioregistry) - len(prefixes)),\n labels=('Yes', 'No'),\n autopct='%1.f%%',\n startangle=30,\n explode=[0.1, 0],\n )\n ax.set_title(label)\n if watermark:\n fig.text(\n 0.5, 0, WATERMARK_TEXT,\n fontsize=8, color='gray', alpha=0.5,\n ha='center', va='bottom',\n )\n\n path = os.path.join(DOCS_IMG, 'has_attribute.svg')\n click.echo(f'output to {path}')\n fig.tight_layout()\n fig.savefig(path, dpi=300)\n plt.close(fig)\n\n # -------------------------------------------------------------------- #\n\n miriam_prefixes = set(get_miriam(skip_deprecated=True, mappify=True))\n ols_prefixes = set(get_ols(mappify=True))\n obofoundry_prefixes = set(get_obofoundry(skip_deprecated=True, mappify=True))\n wikidata_prefixes = set(get_wikidata_registry())\n n2t_prefixes = set(get_n2t())\n go_prefixes = set(get_go(mappify=True))\n bioportal_prefixes = set(get_bioportal(mappify=True))\n prefixcommons_prefixes = set(get_prefix_commons())\n biolink_prefixes = set(get_biolink())\n ncbi_prefixes = set(get_ncbi())\n\n keys = [\n ('obofoundry', 'OBO Foundry', 'red', obofoundry_prefixes),\n ('ols', 'OLS', 'green', ols_prefixes),\n ('miriam', 'MIRIAM', 'blue', miriam_prefixes),\n ('wikidata', 'Wikidata', 'purple', wikidata_prefixes),\n ('n2t', 'Name-to-Thing', 'orange', n2t_prefixes),\n ('go', 'GO', 'yellow', go_prefixes),\n ('bioportal', 'BioPortal', 'cyan', bioportal_prefixes),\n ('prefixcommons', 'Prefix Commons', 'magenta', prefixcommons_prefixes),\n ('biolink', 'Biolink Model', 'pink', biolink_prefixes),\n ('ncbi', 'NCBI', 'green', ncbi_prefixes),\n ]\n\n ############################################################\n # How well does the Bioregistry cover the other resources? #\n ############################################################\n\n ncols = 3\n nrows = int(math.ceil(len(keys) / ncols))\n figsize = (3.25 * ncols, 2.0 * nrows)\n fig, axes = plt.subplots(ncols=ncols, nrows=nrows, figsize=figsize)\n for key, ax in itt.zip_longest(keys, axes.ravel()):\n if key is None:\n ax.axis('off')\n continue\n key, label, color, prefixes = key\n # Remap bioregistry prefixes to match the external\n # vocabulary, when possible\n bioregistry_remapped = {\n br_entry.get(key, {}).get('prefix', br_key)\n for br_key, br_entry in bioregistry.items()\n }\n venn2(\n subsets=(bioregistry_remapped, prefixes),\n set_labels=('Bioregistry', label),\n set_colors=('grey', color),\n ax=ax,\n )\n if watermark:\n fig.text(\n 0.5, 0, WATERMARK_TEXT,\n fontsize=8, color='gray', alpha=0.5,\n ha='center', va='bottom',\n )\n\n path = os.path.join(DOCS_IMG, 'bioregistry_coverage.svg')\n click.echo(f'output to {path}')\n fig.tight_layout()\n fig.savefig(path, dpi=300)\n plt.close(fig)\n\n ######################################################\n # What's the overlap between each pair of resources? #\n ######################################################\n\n pairs = list(itt.combinations(keys, r=2))\n ncols = 4\n nrows = int(math.ceil(len(pairs) / ncols))\n figsize = (3 * ncols, 2.5 * nrows)\n fig, axes = plt.subplots(ncols=ncols, nrows=nrows, figsize=figsize)\n for pair, ax in itt.zip_longest(pairs, axes.ravel()):\n if pair is None:\n ax.axis('off')\n continue\n (l_key, l_label, l_color, l_prefixes), (r_key, r_label, r_color, r_prefixes) = pair\n # Remap external vocabularies to bioregistry\n # prefixes, when possible\n l_prefixes = _remap(key=l_key, prefixes=l_prefixes)\n r_prefixes = _remap(key=r_key, prefixes=r_prefixes)\n venn2(\n subsets=(l_prefixes, r_prefixes),\n set_labels=(l_label, r_label),\n set_colors=(l_color, r_color),\n ax=ax,\n )\n if watermark:\n fig.text(\n 0.5, 0, WATERMARK_TEXT, # transform=plt.gca().transAxes,\n fontsize=14, color='gray', alpha=0.5,\n ha='center', va='bottom',\n )\n\n path = os.path.join(DOCS_IMG, 'external_overlap.svg')\n click.echo(f'output to {path}')\n fig.tight_layout()\n fig.savefig(path, dpi=300)\n plt.close(fig)\n\n ##############################################\n # Histogram of how many xrefs each entry has #\n ##############################################\n xref_counts = [\n sum(\n key in entry\n for key, *_ in keys\n )\n for entry in bioregistry.values()\n ]\n fig, ax = plt.subplots(figsize=SINGLE_FIG)\n sns.barplot(data=sorted(Counter(xref_counts).items()), ci=None, color='blue', alpha=0.4, ax=ax)\n ax.set_xlabel('Number External References')\n ax.set_ylabel('Count')\n ax.set_yscale('log')\n if watermark:\n fig.text(\n 1.0, 0.5, WATERMARK_TEXT,\n fontsize=8, color='gray', alpha=0.5,\n ha='right', va='center', rotation=90,\n )\n\n path = os.path.join(DOCS_IMG, 'xrefs.svg')\n click.echo(f'output to {path}')\n fig.tight_layout()\n fig.savefig(path, dpi=300)\n plt.close(fig)\n\n\ndef _get_license_and_conflicts():\n licenses = []\n conflicts = set()\n obo_has_license, ols_has_license = set(), set()\n for key, entry in bioregistry.items():\n obo_license = _remap_license(entry.get('obofoundry', {}).get('license'))\n if obo_license:\n obo_has_license.add(key)\n\n ols_license = _remap_license(entry.get('ols', {}).get('license'))\n if ols_license:\n ols_has_license.add(key)\n\n if not obo_license and not ols_license:\n licenses.append('None')\n if obo_license and not ols_license:\n licenses.append(obo_license)\n elif not obo_license and ols_license:\n licenses.append(ols_license)\n elif obo_license == ols_license:\n licenses.append(obo_license)\n else: # different licenses!\n licenses.append(ols_license)\n licenses.append(obo_license)\n conflicts.add(key)\n print(f'[{key}] Conflicting licenses- {obo_license} and {ols_license}')\n continue\n return licenses, conflicts, obo_has_license, ols_has_license\n\n\ndef _remap(*, key: str, prefixes: Collection[str]) -> Set[str]:\n br_external_to = {\n br_entry[key]['prefix']: br_id\n for br_id, br_entry in bioregistry.items()\n if key in br_entry and 'prefix' in br_entry[key]\n }\n return {\n br_external_to.get(prefix, prefix)\n for prefix in prefixes\n }\n\n\nif __name__ == '__main__':\n compare()\n","sub_path":"src/bioregistry/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":12568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"171792886","text":"\"\"\"\nProgram: Final_Calculator(Master).py\nDeveloper: Michael Royer\nLanguage: Python-3.x.x\nPrimum Diem: 12/2017\nModified: 03/28/2018\n\nDescription: This program is a calculator that is designed to help students know what finals they should focus on and which ones they can just glance over.\n\nInput: The user will be asked four questions about their class. They are as follows: the total points possible, the amount of points earned, their desired percentage score, and the amount of points the are left in the class.\n\nOutput: This program in output the minimum score they have to make on their final to get their desired score.\n\"\"\"\n\n\n# The Input function asks the user for four different questions, and returns their answers as a float.\ndef Input():\n total_points = float(input(\"Enter the total points possible in your class.\"\"\\n\"))\n your_points = float(input(\"Enter the amount of points that you have earned in your class up until this point.\"\"\\n\"))\n desired_score = float(input(\"Enter the percentage score that you want to earn in the class (ex. 90, 80 or 84.5).\"\"\\n\"))\n points_LOTB= float(input(\"Enter the amount of points possible that are left in your class.\"\"\\n\"))\n\n return total_points, your_points, desired_score, points_LOTB\n\n\n# The Calculation function the controls the processing part of the program.\ndef Calculation(total_points, your_points, desired_score, points_LOTB):\n\n\n # This if-statement fixes the 'divide by zero' bug.\n if points_LOTB <= 0:\n print (\"Sorry mate your class is over.\")\n Input()\n\n points_need = total_points * (desired_score / 100)\n D_score_needed = (points_need - your_points) / points_LOTB\n score_needed = D_score_needed * 100\n\n return score_needed, desired_score\n\n\n# The Output function that controls the output part of the program.\ndef Output(score_needed, desired_score):\n\n if score_needed <= 0:\n print (\"If you skip your final and still pass your class with a\", desired_score, \"percent.\")\n\n if score_needed > 100:\n print (\"You can't make a\", desired_score, \"percent in your class even if you make a perfect score on your test.\")\n\n if (score_needed <= 100 and score_needed >= 0):\n print (\"You need to make at least\", score_needed, \"percent on your test to make a\", desired_score, \"percent in your class.\")\n\n\n# The Main function excuites the program in order.\ndef Main():\n [total_points, your_points, desired_score, points_LOTB] = Input()\n [score_needed, desired_score] = Calculation(total_points, your_points, desired_score, points_LOTB)\n Output(score_needed, desired_score)\n\n\n# This block excuites the program\nMain()\n","sub_path":"runme.py","file_name":"runme.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"197897334","text":"from unittest import TestCase\nimport classroom_manager\n\n\nclass Test_Student(TestCase):\n def test_prop_construct(self):\n id = 1234\n first_name = \"Hannah\"\n last_name = \"Pittman\"\n assignments = []\n\n # Constructor call\n student = classroom_manager.Student(id, first_name, last_name)\n\n self.assertEqual(id, student.id)\n self.assertEqual(first_name, student.first_name)\n self.assertEqual(last_name, student.last_name)\n self.assertEqual(assignments, student.assignments)\n\n def test_full_name(self):\n student = classroom_manager.Student(1234, \"Hannah\", \"Pittman\")\n self.assertEqual(student.get_full_name(), \"Hannah Pittman\")\n\n def test_get_assignments(self):\n assignment1 = classroom_manager.Assignment(\"Assignment 1\", 100)\n assignment2 = classroom_manager.Assignment(\"Quiz 1\", 50)\n student = classroom_manager.Student(1234, \"Hannah\", \"Pittman\")\n student.assignments = [assignment1, assignment2]\n self.assertEqual(student.get_assignments(), student.assignments)\n\n def test_get_assignment(self):\n assignment1 = classroom_manager.Assignment(\"Assignment 1\", 100)\n assignment2 = classroom_manager.Assignment(\"Quiz 1\", 50)\n student = classroom_manager.Student(1234, \"Hannah\", \"Pittman\")\n\n self.assertEqual(student.get_assignment(\"Quiz 1\"), None) # no assignments to look at\n student.assignments = [assignment1, assignment2]\n self.assertEqual(student.get_assignment(\"Quiz 1\"), student.assignments[1]) # assignment at index 1\n\n def test_get_average(self):\n student = classroom_manager.Student(1234, \"Hannah\", \"Pittman\")\n assignment1 = classroom_manager.Assignment(\"Assignment 1\", 100)\n assignment1.grade = None\n assignment2 = classroom_manager.Assignment(\"Quiz 1\", 50)\n assignment2.grade = 50\n student.assignments = [assignment1, assignment2]\n\n self.assertEqual(student.get_average(), 50)\n assignment1.grade = 95\n self.assertEqual(student.get_average(), 72.5)\n\n def test_submit_assignnment(self):\n assignment1 = classroom_manager.Assignment(\"Assignment 1\", 100)\n assignment2 = classroom_manager.Assignment(\"Quiz 1\", 50)\n student = classroom_manager.Student(1234, \"Hannah\", \"Pittman\")\n student.assignments = [assignment1, assignment2]\n\n assignment3 = \"Homework 1\"\n student.submit_assignment(assignment3)\n\n self.assertEqual(len(student.assignments), 3)\n\n def test_remove_assignment(self):\n assignment1 = classroom_manager.Assignment(\"Assignment 1\", 100)\n assignment2 = classroom_manager.Assignment(\"Quiz 1\", 50)\n student = classroom_manager.Student(1234, \"Hannah\", \"Pittman\")\n student.assignments = [assignment1, assignment2]\n\n student.remove_assignment(\"Quiz 1\")\n self.assertEqual(len(student.assignments), 1)\n\nclass Test_Assignment(TestCase):\n def test_prop_construct(self):\n name = \"Quiz 1\"\n max_score = 100\n grade = None\n\n # Constructor call\n assignment = classroom_manager.Assignment(name, max_score)\n\n self.assertEqual(name, assignment.name)\n self.assertEqual(max_score, assignment.max_score)\n self.assertEqual(grade, assignment.grade)\n\n def test_assign_grade(self):\n assignment = classroom_manager.Assignment('Quiz 1', 100)\n self.assertEqual(assignment.max_score, 100)\n\n assignment.assign_grade(100)\n self.assertEqual(assignment.grade, 100)\n assignment.assign_grade(101)\n self.assertEqual(assignment.grade, None)\n","sub_path":"projects/pittmaha/dominion/test_classroom_manager.py","file_name":"test_classroom_manager.py","file_ext":"py","file_size_in_byte":3645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"84423481","text":"lines = open(\"day13sample2.txt\",\"r\").readlines()\nfrom functools import reduce\n\ndef chinese_remainder(n, a):\n sum = 0\n prod = reduce(lambda a, b: a*b, n)\n for n_i, a_i in zip(n, a):\n p = prod // n_i\n sum += a_i * mul_inv(p, n_i) * p\n return sum % prod\n \n \n \ndef mul_inv(a, b):\n b0 = b\n x0, x1 = 0, 1\n if b == 1: return 1\n while a > 1:\n q = a // b\n a, b = b, a%b\n x0, x1 = x1 - q * x0, x0\n if x1 < 0: x1 += b0\n return x1\n \ndef part_a():\n timor = int(lines[0])\n splitted = [int(char) for char in lines[1].split(\",\") if char != \"x\"]\n ans = list()\n for l in splitted:\n inj = timor // l\n if inj * l > timor:\n ans.append((l,inj*l))\n else:\n ans.append((l,(inj+1)*l))\n smol = 99999999999999\n answer = (0,0)\n mi = min([val[1] for val in ans])\n for val in ans:\n if val[1] == mi:\n answer = val\n print(answer[0] * (answer[1] - timor))\n\ndef part_b():\n splitted = [int(char) for char in lines[0].split(\",\") if char != \"x\"]\n print(splitted)\n\n\npart_b()\n\n","sub_path":"day13/day13.py","file_name":"day13.py","file_ext":"py","file_size_in_byte":1041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"109643548","text":"\"\"\"Devices that represent lights\"\"\"\nimport asyncio\nimport logging\n\nfrom .fah_device import FahDevice\nfrom ..const import (\n FUNCTION_IDS_SWITCHING_ACTUATOR,\n FUNCTION_IDS_DIMMING_ACTUATOR,\n PID_SWITCH_ON_OFF,\n PID_ABSOLUTE_SET_VALUE,\n PID_INFO_ON_OFF,\n PID_INFO_ACTUAL_DIMMING_VALUE,\n )\n\nLOG = logging.getLogger(__name__)\n\nclass FahLight(FahDevice):\n \"\"\" Free@Home light object \"\"\"\n state = None\n brightness = None\n\n def pairing_ids(function_id=None):\n if function_id in FUNCTION_IDS_SWITCHING_ACTUATOR:\n return {\n \"inputs\": [\n PID_SWITCH_ON_OFF,\n ],\n \"outputs\": [\n PID_INFO_ON_OFF,\n ]\n }\n elif function_id in FUNCTION_IDS_DIMMING_ACTUATOR:\n return {\n \"inputs\": [\n PID_SWITCH_ON_OFF,\n PID_ABSOLUTE_SET_VALUE,\n ],\n \"outputs\": [\n PID_INFO_ON_OFF,\n PID_INFO_ACTUAL_DIMMING_VALUE,\n ]\n }\n\n async def turn_on(self):\n \"\"\" Turn the light on \"\"\"\n oldstate = self.state\n await self.client.set_datapoint(self.serialnumber, self.channel_id, self._datapoints[PID_SWITCH_ON_OFF], '1')\n self.state = True\n\n if self.is_dimmer() \\\n and ((oldstate != self.state and int(self.brightness) > 0) or (oldstate == self.state)):\n await self.client.set_datapoint(self.serialnumber, self.channel_id, self._datapoints[PID_ABSOLUTE_SET_VALUE], str(self.brightness))\n\n async def turn_off(self):\n \"\"\" Turn the light off \"\"\"\n await self.client.set_datapoint(self.serialnumber, self.channel_id, self._datapoints[PID_SWITCH_ON_OFF], '0')\n self.state = False\n\n def set_brightness(self, brightness):\n \"\"\" Set the brightness of the light \"\"\"\n if self.is_dimmer():\n self.brightness = brightness\n\n def get_brightness(self):\n \"\"\" Return the brightness of the light \"\"\"\n return self.brightness\n\n def is_on(self):\n \"\"\" Return the state of the light \"\"\"\n return self.state\n\n def is_dimmer(self):\n \"\"\"Return true if device is a dimmer\"\"\"\n return PID_ABSOLUTE_SET_VALUE in self._datapoints\n\n def update_datapoint(self, dp, value):\n \"\"\"Receive updated datapoint.\"\"\"\n if PID_INFO_ON_OFF in self._datapoints and self._datapoints[PID_INFO_ON_OFF] == dp:\n self.state = (value == '1')\n LOG.info(\"light device %s (%s) dp %s state %s\", self.name, self.lookup_key, dp, value)\n\n elif PID_INFO_ACTUAL_DIMMING_VALUE in self._datapoints and self._datapoints[PID_INFO_ACTUAL_DIMMING_VALUE] == dp:\n self.brightness = value\n LOG.info(\"light device %s (%s) dp %s brightness %s\", self.name, self.lookup_key, dp, value)\n\n else:\n LOG.info(\"light device %s (%s) unknown dp %s value %s\", self.name, self.lookup_key, dp, value)\n \n def update_parameter(self, param, value):\n LOG.debug(\"Not yet implemented\")\n","sub_path":"custom_components/freeathome/fah/devices/fah_light.py","file_name":"fah_light.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"632613022","text":"for i, name in enumerate(['body','asd']):\n print(i, name)\n\nstudent_list =['김혜경','한상우','배원제']\nfor i, name in enumerate(student_list):\n print(i, name)\n\nstudent_list =['김혜경','한상우','배원제']\nfor i, name in enumerate(student_list):\n if(i<2):\n print(i,name,\"다음 손님 : \",student_list[i+1])\n else:\n print(i, student_list[i], \"고객님 잠시 부탁드립니다.\")\n","sub_path":"python_workspace/01_jump_to_python/5_APP/5_native_function/235_enumerate.py","file_name":"235_enumerate.py","file_ext":"py","file_size_in_byte":422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"193481490","text":"import os, sys\nsys.path.append('../')\n\nfrom src.main import Game\nfrom src.utils import format_move_log\n\ndef convert_pgn_to_a1(s_pgn):\n ''' convert s_pgn to a1-tuple '''\n\n game = Game(s_pgn_instructions=s_pgn\n ,b_log_move=True\n )\n ret = game.play()\n gameLog = game.get_gamelog()\n s_instruct = format_move_log(gameLog.get_log_move())\n\n s_instruct = s_instruct.rstrip()\n s_instruct = s_instruct.lstrip()\n\n return s_instruct\n\n#duplicate from src/utils\ndef find_app_path_root(input_file, find_dir = \"chess\"):\n ''' input: input_file - pass in __file__\n return: a relative-path to folder or None '''\n \n _path = os.path.abspath(os.path.dirname(input_file))\n \n while(True):\n \n _head, _tail = os.path.split(_path)\n \n if _head == _path:\n return None\n \n if str.lower(_tail) == str.lower(find_dir):\n return os.path.relpath(_path, start = os.getcwd())\n \n _path = _head\n\n\nif __name__ == \"__main__\":\n \n s_input = \"1. c4\"\n print(convert_pgn_to_a1(s_input))\n\n\ndef test_convert_pgn_to_a1_1():\n ''' testing some string conversions'''\n \n #note turn8 has white castling\n s_input = \"1. c4 Nf6 2. Nc3 g6 3. g3 c5 4. Bg2 Nc6 5. Nf3 d6 6. d4 cxd4 7. Nxd4 Bd7 8. O-O Bg7 9. Nxc6 Bxc6 10. e4 O-O 11. Be3 a6 12. Rc1 Nd7 13. Qe2 b5 14. b4 Ne5 15. cxb5 axb5 16. Nxb5 Bxb5 17. Qxb5 Qb8 18. a4 Qxb5 19. axb5 Rfb8 20. b6 Ng4 21. b7\"\n \n s_output = convert_pgn_to_a1(s_input)\n \n ANSWER = \"1. c2 c4 2. g8 f6 3. b1 c3 4. g7 g6 5. g2 g3 6. c7 c5 7. f1 g2 8. b8 c6 9. g1 f3 10. d7 d6 11. d2 d4 12. c5 d4 13. f3 d4 14. c8 d7 15. e1 g1 16. f8 g7 17. d4 c6 18. d7 c6 19. e2 e4 20. e8 g8 21. c1 e3 22. a7 a6 23. a1 c1 24. f6 d7 25. d1 e2 26. b7 b5 27. b2 b4 28. d7 e5 29. c4 b5 30. a6 b5 31. c3 b5 32. c6 b5 33. e2 b5 34. d8 b8 35. a2 a4 36. b8 b5 37. a4 b5 38. f8 b8 39. b5 b6 40. e5 g4 41. b6 b7\"\n\n assert s_output == ANSWER\n \n\n\n \n\n ","sub_path":"basic_engine/tools/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"292638710","text":"import os\nimport sys\nimport math\nimport re\nimport enchant\nimport string\n\nf_name=\"train_doc.txt\"\npath=os.path.normpath(\"/Users/Desktop/train_doc\")\nunique_words=dict()\nexclude=set(string.punctuation)\n\n#--tot number of words,sentences and paragraphs\ntot_eng_words=0\t\t\t#number of dictonary english words\ntot_words=0\t\t\t\t#total number of words\ntot_sent=0\t\t\t\t#total number of sentences\t\ntot_par=0\t\t\t\t#total number of paragraphs\t\n\ntest_str=\"\"\ntest_str_orig=\"\"\n\nwith open(f_name,\"r\") as f:\n\tlinelist=f.readlines()\n\ttry:\n\t\tfor i in range(0,len(linelist)):\n\t\t\tstr_data=linelist[i]\n\t\t\ttest_str+=str_data.lower()\n\t\t\ttest_str_orig+=linelist[i]\n\t\t\tstr_data_split=str_data.split(\" \")\n\t\t\t#print(len(str_data_split))\n\t\t\tenglish_dict=enchant.Dict(\"en_US\")\t\t#creating an english dict\n\t\t\t#print(str_data_split)\n\t\t\tcount=0\n\t\t\tfor item in str_data_split:\n\t\t\t\t#print(item)\n\t\t\t\tif(item!=\"\" and english_dict.check(item)==True):\n\t\t\t\t\tcount+=1\n\t\t\t\tif(item=='\\n'):\n\t\t\t\t\ttot_par+=1\t\n\t\t\t#print(count)\t\t\n\t\t\ttot_eng_words+=count\n\t\t\ttot_words+=len(str_data_split)\n\t\t\t\t\n\texcept Exception as e:\n\t\tprint(type(e))\n\n\nprint(tot_words)\nprint(tot_eng_words)\nprint(tot_par)\n\n#print(test_str)\n\nregex_words=r\"\\w+[-|.|-|']?\\w+\"\t\t#regex exp for finding number of words \nmatches=re.finditer(regex_words,test_str,re.MULTILINE)\n#print(type(matches))\nprint(\"Total number of words in the text:\")\nprint(len(list(matches)))\n\nregex_para=r\"\\n\\n\"\nmatches=re.finditer(regex_para,test_str,re.MULTILINE)\t\t#regex expression for finding number of paragraphs\nprint(\"Total number of paragraphs\")\nprint(len(list(matches)))\n#print(test_str)\n\n\nprint(\"Total number of sentences: \")\t\t\t\t\t\t#regex exp for fiding number of sentences\nregex_sent=r\"[\\n\\.!?]?[A-Z][^.]{6,}[?\\.!] ?\"\n#print(regex_sent)\nmatches=re.finditer(regex_sent,test_str_orig,re.MULTILINE)\nprint(len(list(matches)))\n\nprint(\"Another way to find total number of sentences: \")\t#regex exp for finding number of sentences\nregex_sent_2=r\"\\w{3,}[.]\"\nmatches=re.finditer(regex_sent_2,test_str_orig,re.MULTILINE)\nprint(len(list(matches)))\n\nstr1=raw_input(\"Enter word to find number of sentences beggining with this word: \")\nstr1=str1.lower()\n#regex1=r\"^for\\b |[.] ?for\\b\\Gfor\\b\"\nregex_beg=r\"[.|?|!|\\n] ?\"+re.escape(str1)+\"\\\\b\"+\"|\\G\"+str1+\"\\\\b\"\t\t#regex exp for finding number of sentences beggining with a word\nmatches=re.finditer(regex_beg,test_str,re.MULTILINE)\nprint(\"Number of sentences starting with word: \"+str1)\t\nprint(len(list(matches)))\t\n\nstr2=raw_input(\"Enter word to find number of sentences ending with this word:\")\nstr2=str2.lower()\n#regex2=\" ?\"+str1+\"\\\\b\"+\" ?[.]|[?]\"\nregex_end=r\" ?\"+re.escape(str2)+\"\\\\b\"+\" ?[.|?|!]\"\t\t\t\t#regex exp for finding number of sentences ending with a word\nmatches=re.finditer(regex_end,test_str,re.MULTILINE)\nprint(\"Number of sentences ending with word: \"+str2)\t\nprint(len(list(matches)))\t\n\nstr3=raw_input(\"Enter word to find it's frequency: \")\nstr3=str3.lower()\nregex_freq=r\"(? (list, list):\n with open(fp, 'r') as f:\n algorithm = f.readline().strip()\n f.readline()\n image = []\n for line in f.read().splitlines():\n image.append(line)\n return algorithm, image\n\ndef sequential_enhances(image: list, algorithm: list, n_times: int) -> list:\n output_image = image\n out_of_bounds = '.'\n for __ in range(n_times):\n output_image, out_of_bounds = enhance(output_image, algorithm, out_of_bounds)\n return output_image\n\ndef enhance(image: list, algorithm: list, out_of_bounds: str) -> list:\n output_image = []\n height = len(image)\n width = len(image[0])\n for y in range(-1,height + 1):\n row = []\n for x in range(-1,width + 1):\n pixel_value = calc_pixel_value((x,y), image, out_of_bounds)\n row.append(algorithm[pixel_value])\n output_image.append(row)\n out_of_bounds = algorithm[int(''.join(['1' if bit == '#' else '0' for bit in out_of_bounds*9]), 2)]\n return output_image, out_of_bounds\n\ndef calc_pixel_value(pixel: tuple, image: list, out_of_bounds: str) -> int:\n x, y = pixel\n pixel_value = ''\n for yi in range(y-1,y+2):\n for xi in range(x-1, x+2):\n pixel_value += image[yi][xi] if 0 <= yi < len(image) and 0 <= xi < len(image[yi]) else out_of_bounds\n return int(''.join(['1' if bit == '#' else '0' for bit in pixel_value]), 2)\n\ndef print_image(image: list) -> None:\n for line in image:\n print(''.join(line))\n\ndef count_lit_pixels(image: list) -> int:\n lit_pixels = 0\n for pixel in chain.from_iterable(image):\n lit_pixels += 1 if pixel == '#' else 0\n return lit_pixels\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(prog='Advent of code 2021 - day 20, part 1')\n parser.add_argument('input', help='path to input file', default='input.txt', nargs='?')\n args = parser.parse_args()\n algorithm, image = read_from_file(args.input)\n enhanced_image = sequential_enhances(image, algorithm, 2)\n lit_pixels = count_lit_pixels(enhanced_image)\n print(lit_pixels)","sub_path":"2021/20/part1.py","file_name":"part1.py","file_ext":"py","file_size_in_byte":2157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"38261459","text":"USER_AGENTS = [\n 'Mozilla/5.0 (CrKey armv7l 1.5.16041) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.0 Safari/537.36',\n 'Mozilla/5.0 (Linux; U; Android 4.2.2; he-il; NEO-X5-116A Build/JDQ39) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30',\n 'Mozilla/5.0 (Linux; Android 4.2.2; AFTB Build/JDQ39) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.173 Mobile Safari/537.22',\n 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.246',\n 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9',\n]\n\ndef get_random_user_agent():\n return random.choice(USER_AGENTS)\n\ndef obfuscator_request(contact_hash, cookie):\n \"\"\" Sends request to http://ogloszenia.trojmiasto.pl/_ajax/obfuscator/?decode\n\n :param contact_hash: Data hash needed to decode information\n :type contact_hash: str\n :return: Response returned by request\n \"\"\"\n user_agent = get_random_user_agent()\n log.info('user-agent: {0}'.format(user_agent))\n response = requests.post(\n OBFUSCATOR_URL,\n data={\n \"hash\": contact_hash,\n \"type\": \"ogloszenia\"\n },\n headers={\n \"cookie\": \"{0}\".format(cookie),\n 'User-Agent': user_agent\n }\n )\n try:\n response.raise_for_status()\n except requests.HTTPError as e:\n log.warning('Request for {0} failed. Error: {1}'.format(OBFUSCATOR_URL, e))\n return None\n return response\n\n\ndef get_cookie_from(response):\n \"\"\" Provides cookie for given response\n\n :param response: Requests.response object\n :return: Cookie information as string\n :rtype: string\n \"\"\"\n cookie = response.headers['Set-Cookie'].split(';')[0]\n return cookie\n\n# offer.py:\n# It can read a few phone numbers and mails due to captcha, number of allowed requests\n# contact_details = {\"phone\": [], \"mail\": None}\n# contact_hashes = html_parser.find_all(\"a\")\n# for contact_hash in contact_hashes:\n# if contact_hash.has_attr(\"data-hash\"):\n# print(contact_hash.attrs[\"data-hash\"], cookie)\n# response = obfuscator_request(contact_hash.attrs[\"data-hash\"], cookie).json()\n# else:\n# continue\n# try:\n# if \"@\" in response[\"phrase\"]:\n# contact_details[\"mail\"] = response[\"phrase\"]\n# else:\n# contact_details[\"phone\"].append(response[\"phrase\"])\n# except KeyError:\n# log.warning(response)\n# break\n# return contact_details\n","sub_path":"usefull/old_trojmiasto.py","file_name":"old_trojmiasto.py","file_ext":"py","file_size_in_byte":2651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"562831772","text":"from pyramid.view import view_config, forbidden_view_config\nfrom pyramid.security import remember, forget, authenticated_userid\nfrom pyramid.httpexceptions import HTTPFound, HTTPForbidden\nimport json, requests\n\n@view_config(route_name='home', renderer='templates/home.pt')\ndef vw_home(request):\n return {'project': 'eos_portal', \"logged_in\": request.authenticated_userid}\n\ndef forbidden_view(request):\n # do not allow a user to login if they are already logged in\n if authenticated_userid(request):\n return HTTPForbidden()\n loc = request.route_url('login', _query=(('next', request.path),))\n return HTTPFound(location=loc)\n\n@view_config(route_name='login', renderer='templates/login.pt')\ndef vw_login(request):\n session = request.session\n error_flag=False\n if 'submit' in request.POST:\n r = requests.get('http://localhost:6543/users/asdf/password?actor_id=' + request.POST['username'] + '&password=' + request.POST['password'])\n login = request.params['username']\n if r.status_code == 200:\n headers = remember(request, login)\n request.session['token'] = r.text\n \n q = requests.get('http://localhost:6543/users/asdf?actor_id=' + request.POST['username'])\n if q.status_code == 200:\n credit = json.loads(json.loads(q.text))['credits']\n if credit is None:\n credit = 0\n session['credit'] = credit\n \n return HTTPFound(location='http://localhost:6542/servers', headers=headers)\n else:\n error_flag = True\n return {\"project\": 'eos_portal', \"values\": error_flag, \"logged_in\": request.authenticated_userid}\n\n@view_config(route_name='servers', renderer='templates/servers.pt')\ndef vw_servers(request):\n owner = authenticated_userid(request)\n session = request.session\n if ('credit' in session) == False:\n return HTTPFound(location='http://localhost:6542/logout') #Turn this into a decorator\n server_list = \"gah\"\n r = requests.get('http://localhost:6543/servers?actor_id='+ request.authenticated_userid )\n if r.status_code == 200:\n server_list = json.loads(r.text)\n else:\n server_list = \"Request Failed\"\n return dict(logged_in = request.authenticated_userid, values=server_list, credit=session['credit'])\n\n@view_config(route_name='stop', renderer='templates/main.pt')\ndef vw_stop(request):\n session = request.session\n r = requests.put('http://localhost:6543/servers/aasdf/stop')\n return HTTPFound(location='/main', headers=headers)\n\n@view_config(route_name='account', renderer='templates/account.pt')\ndef vw_account(request):\n session = request.session\n headers = request.headers\n account_details = {}\n r = requests.get('http://localhost:6543/users/asdf?actor_id=' + request.authenticated_userid)\n if r.status_code == 200:\n account_details = json.loads(json.loads(r.text))\n if account_details['credits'] is None:\n account_details['credits'] = 0\n return dict(logged_in = request.authenticated_userid, values=account_details, credit=session['credit'])\n\n@view_config(route_name='logout')\ndef logout(request):\n headers = forget(request)\n return HTTPFound(location = request.resource_url(request.context), headers=headers)\n","sub_path":"eos_portal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"364436481","text":"#!/usr/bin/python\nimport RPi.GPIO as GPIO\nimport time\n \nsoil = 4\nlight = 18\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(soil, GPIO.IN)\nGPIO.setup(light,GPIO.IN)\n \nwhile True: \n\n if GPIO.input(soil):\n soilStatus = 0\n\n else:\n soilStatus = 1\n\n if GPIO.input(light):\n lightStatus = 0\n\n else:\n lightStatus = 1\n\n if (soilStatus == 1 and lightStatus == 1):\n print(\"Your plants are ok.\")\n\n if (soilStatus == 0 and lightStatus == 1):\n print(\"Your plants need more sunlight.\")\n\n if (soilStatus == 1 and lightStatus == 0):\n print(\"Your plants need some water.\")\n\n if (soilStatus == 0 and lightStatus == 0):\n print(\"Your plants need some water and more sunlight.\") \n\n time.sleep(1)","sub_path":"Sensors.py","file_name":"Sensors.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"538220441","text":"from __future__ import print_function, division\n\nimport luigi\nimport json\nimport time\nimport re\nimport datetime\nimport subprocess\nimport base64\nfrom urllib import urlopen\n\nimport os\nimport sys\nfrom collections import defaultdict\n\n\nfrom elasticsearch import Elasticsearch\n\n#for hack to get around non self signed certificates\nimport ssl\n\n#Amazon S3 support for writing touch files to S3\nfrom luigi.s3 import S3Target\n#luigi S3 uses boto for AWS credentials\nimport boto\n\nclass ConsonanceTask(luigi.Task):\n\n # TODO : update to reflect pipeline parameters.\n\n json_dict = {}\n\n redwood_host = luigi.Parameter(\"storage system name such as storage.ucsc-cgp.org must be input\")\n redwood_token = luigi.Parameter(\"must_be_defined\")\n dockstore_tool_running_dockstore_tool = luigi.Parameter(default=\"must enter quay.io path to dockstore tool runner and version\")\n workflow_version = luigi.Parameter(default=\"must be defined\")\n vm_instance_type = luigi.Parameter(default='c4.8xlarge')\n vm_region = luigi.Parameter(default='us-west-2')\n tmp_dir = luigi.Parameter(default='/datastore') #equivalent of work mount\n\n cgp_pipeline_job_metadata_str = luigi.Parameter(default=\"must input metadata\")\n# cgp_pipeline_job_metadata = json.loads(self.cgp_pipeline_job_metadata_str)\n\n touch_file_path = luigi.Parameter(default='must input touch file path')\n metadata_json_file_name = luigi.Parameter(default='must input metadata json file name')\n file_prefix = luigi.Parameter(default='must input file prefix')\n\n #Consonance will not be called in test mode\n test_mode = luigi.BoolParameter(default = False)\n\n def run(self):\n print(\"\\n\\n\\n** TASK RUN **\")\n\n cgp_pipeline_job_metadata = json.loads(self.cgp_pipeline_job_metadata_str)\n\n self.s3_metadata_json_file_path = cgp_pipeline_job_metadata[\"s3_metadata_json_file_path\"]\n self.local_dockstore_tool_runner_json_file_path = cgp_pipeline_job_metadata[\"local_dockstore_tool_runner_json_file_path\"]\n self.s3_dockstore_tool_runner_json_file_path = cgp_pipeline_job_metadata[\"s3_dockstore_tool_runner_json_file_path\"]\n# self.s3_finished_json_file_path = cgp_pipeline_job_metadata[\"s3_finished_json_file_path\"]\n\n\n\n# print \"** MAKE TEMP DIR **\"\n # create a unique temp dir\n local_json_dir = \"/tmp/\" + self.touch_file_path\n cmd = [\"mkdir\", \"-p\", local_json_dir ]\n cmd_str = ''.join(cmd)\n print(cmd_str)\n try:\n subprocess.check_call(cmd)\n except subprocess.CalledProcessError as e:\n #If we get here then the called command return code was non zero\n print(\"\\nERROR!!! MAKING LOCAL JSON DIR : \" + cmd_str + \" FAILED !!!\", file=sys.stderr)\n print(\"\\nReturn code:\" + str(e.returncode), file=sys.stderr)\n return_code = e.returncode\n sys.exit(return_code)\n except Exception as e:\n print(\"\\nERROR!!! MAKING LOCAL JSON DIR : \" + cmd_str + \" THREW AN EXCEPTION !!!\", file=sys.stderr)\n print(\"\\nException information:\" + str(e), file=sys.stderr)\n #if we get here the called command threw an exception other than just\n #returning a non zero return code, so just set the return code to 1\n return_code = 1\n sys.exit(return_code)\n\n\n\n print(\"** MAKE JSON FOR WORKER **\")\n # create a json for for the pipeline which will be executed by the \n #dockstore-tool-running-dockstore-tool and passed as base64encoded\n # will need to encode the JSON above in this: https://docs.python.org/2/library/base64.html\n # see http://luigi.readthedocs.io/en/stable/api/luigi.parameter.html?highlight=luigi.parameter\n # TODO: this is tied to the requirements of the tool being targeted\n \n json_str = json.dumps(cgp_pipeline_job_metadata[\"pipeline_job_json\"], sort_keys=True, indent=4, separators=(',', ': '))\n print(\"THE JSON: \"+json_str)\n # now make base64 encoded version\n base64_json_str = base64.urlsafe_b64encode(json_str)\n print(\"** MAKE JSON FOR DOCKSTORE TOOL WRAPPER **\")\n\n # create a json for dockstoreRunningDockstoreTool, embed the JSON as a param\n p = self.save_dockstore_tool_runner_json().open('w')\n p_local = self.save_dockstore_tool_runner_json_local().open('w')\n\n target_tool= cgp_pipeline_job_metadata['target_tool_prefix'] + \":\" + self.workflow_version\n\n dockstore_tool_runner_json = {}\n dockstore_tool_runner_json[\"program_name\"] = cgp_pipeline_job_metadata[\"program\"].replace(' ','_')\n dockstore_tool_runner_json[\"json_encoded\"] = base64_json_str\n dockstore_tool_runner_json[\"docker_uri\"] = target_tool\n dockstore_tool_runner_json[\"dockstore_url\" ] = cgp_pipeline_job_metadata['target_tool_url']\n dockstore_tool_runner_json[\"redwood_token\" ] = self.redwood_token\n dockstore_tool_runner_json[\"redwood_host\"] = self.redwood_host\n\n #use only one parent uuid even though inputs are from more than one bundle?\n #Do this now until file browser code fixed so that it won't \n #display duplicate workflow outputs\n #parent_uuids = ','.join(map(\"{0}\".format, cgp_job['parent_uuids']))\n #print(\"parent uuids:%s\" % parent_uuids)\n #dockstore_tool_runner_json[\"parent_uuids\"] = parent_uuids\n dockstore_tool_runner_json[\"parent_uuids\"] = cgp_pipeline_job_metadata['parent_uuids'][0]\n\n dockstore_tool_runner_json[\"workflow_type\"] = cgp_pipeline_job_metadata[\"analysis_type\"]\n dockstore_tool_runner_json[\"launch_type\"] = cgp_pipeline_job_metadata[\"launch_type\"]\n dockstore_tool_runner_json[\"tmpdir\"] = self.tmp_dir\n dockstore_tool_runner_json[\"vm_instance_type\"] = self.vm_instance_type\n dockstore_tool_runner_json[\"vm_region\"] = self.vm_region\n dockstore_tool_runner_json[\"vm_location\"] = \"aws\"\n dockstore_tool_runner_json[\"vm_instance_cores\"] = 36\n dockstore_tool_runner_json[\"vm_instance_mem_gb\"] = 60\n dockstore_tool_runner_json[\"output_metadata_json\"] = \"/tmp/final_metadata.json\"\n\n dockstore_tool_runner_json_str = json.dumps(dockstore_tool_runner_json , sort_keys=True, indent=4, separators=(',', ': '))\n print(dockstore_tool_runner_json_str, file=p)\n p.close()\n \n # write the parameterized JSON for input to Consonance\n # to a local file since Consonance cannot read files on s3\n print(dockstore_tool_runner_json_str, file=p_local)\n p_local.close()\n\n # execute consonance run, parse the job UUID\n\n cmd = [\"consonance\", \"run\", \"--tool-dockstore-id\", self.dockstore_tool_running_dockstore_tool, \\\n \"--flavour\", self.vm_instance_type, \"--run-descriptor\", self.save_dockstore_tool_runner_json_local().path]\n cmd_str = ' '.join(cmd)\n if self.test_mode == False:\n print(\"** SUBMITTING TO CONSONANCE **\")\n print(\"executing:\"+ cmd_str)\n print(\"** WAITING FOR CONSONANCE **\")\n\n try:\n consonance_output_json = subprocess.check_output(cmd)\n except subprocess.CalledProcessError as e:\n #If we get here then the called command return code was non zero\n print(\"\\nERROR!!! CONSONANCE CALL: \" + cmd_str + \" FAILED !!!\", file=sys.stderr)\n print(\"\\nReturn code:\" + str(e.returncode), file=sys.stderr)\n\n return_code = e.returncode\n sys.exit(return_code)\n except Exception as e:\n print(\"\\nERROR!!! CONSONANCE CALL: \" + cmd_str + \" THREW AN EXCEPTION !!!\", file=sys.stderr)\n print(\"\\nException information:\" + str(e), file=sys.stderr)\n #if we get here the called command threw an exception other than just\n #returning a non zero return code, so just set the return code to 1\n return_code = 1\n sys.exit(return_code)\n\n print(\"Consonance output is:\\n\\n{}\\n--end consonance output---\\n\\n\".format(consonance_output_json))\n\n #get consonance job uuid from output of consonance command\n consonance_output = json.loads(consonance_output_json)\n if \"job_uuid\" in consonance_output:\n cgp_pipeline_job_metadata[\"consonance_job_uuid\"] = consonance_output[\"job_uuid\"]\n else:\n print(\"ERROR: COULD NOT FIND CONSONANCE JOB UUID IN CONSONANCE OUTPUT!\", file=sys.stderr)\n else:\n print(\"TEST MODE: Consonance command would be:\"+ cmd_str)\n cgp_pipeline_job_metadata[\"consonance_job_uuid\"] = 'no consonance id in test mode'\n\n #remove the local parameterized JSON file that\n #was created for the Consonance call\n #since the Consonance call is finished\n self.save_dockstore_tool_runner_json_local().remove()\n\n #convert the meta data to a string and\n #save the donor metadata for the sample being processed to the touch\n # file directory\n cgp_job_json = json.dumps(cgp_pipeline_job_metadata, sort_keys=True, indent=4, separators=(',', ': '))\n m = self.save_metadata_json().open('w')\n print(cgp_job_json, file=m)\n m.close()\n\n\n # NOW MAke a final report\n f = self.output().open('w')\n # TODO: could print report on what was successful and what failed? Also, provide enough details like donor ID etc\n print(\"Consonance task is complete\", file=f)\n f.close()\n print(\"\\n\\n\\n\\n** TASK RUN DONE **\")\n\n def save_metadata_json(self):\n return S3Target(self.s3_metadata_json_file_path)\n\n def save_dockstore_tool_runner_json_local(self):\n return luigi.LocalTarget(self.local_dockstore_tool_runner_json_file_path)\n\n def save_dockstore_tool_runner_json(self):\n return S3Target(self.s3_dockstore_tool_runner_json_file_path)\n\n def output(self):\n# return S3Target(self.s3_finished_json_file_path)\n# print(\"output target:{}\".format(\"s3://\" + self.touch_file_path + \"/\" + self.file_prefix + \"_finished.json\"))\n return S3Target(\"s3://\" + self.touch_file_path + \"/\" + self.file_prefix + \"_finished.json\")\n\n\nclass base_Coordinator(luigi.Task):\n \n es_index_host = luigi.Parameter(default='localhost')\n es_index_port = luigi.Parameter(default='9200')\n redwood_token = luigi.Parameter(\"must_be_defined\")\n redwood_host = luigi.Parameter(default='storage.ucsc-cgp.org')\n dockstore_tool_running_dockstore_tool = luigi.Parameter(default=\"must input quay.io path to dockstore tool runner and version\")\n tmp_dir = luigi.Parameter(default='/datastore')\n max_jobs = luigi.Parameter(default='-1')\n bundle_uuid_filename_to_file_uuid = {}\n process_sample_uuids = luigi.Parameter(default = \"\")\n\n workflow_version = luigi.Parameter(default=\"\")\n touch_file_bucket = luigi.Parameter(default=\"must be input\")\n\n vm_instance_type = luigi.Parameter(default='c4.8xlarge')\n vm_region = luigi.Parameter(default='us-west-2')\n\n #Consonance will not be called in test mode\n test_mode = luigi.BoolParameter(default = False)\n\n center = luigi.Parameter(default = \"\")\n program = luigi.Parameter(default = \"\")\n project = luigi.Parameter(default = \"\")\n\n #Classes derived from this class must implement these methods\n '''\n Return a string that is the name that will be used to name the touchfile path\n\n E.g.:\n return 'Fusion'\n '''\n def get_pipeline_name(self):\n raise NotImplementedError('You need to define a get_pipeline_name method!')\n\n '''\n Return a dictionary of CWL option to reference file name so this information\n can be added to the parameterized JSON input to the pipeline\n\n E.g.:\n cwl_option_to_reference_file_name = defaultdict()\n\n ######################CUSTOMIZE REFERENCE FILES FOR PIPELINE START####################### \n cwl_option_to_reference_file_name['index'] = \"STARFusion-GRCh38gencode23.tar.gz\"\n ######################CUSTOMIZE REFERENCE FILES FOR PIPELINE END####################### \n\n return cwl_option_to_reference_file_name\n '''\n def get_cgp_job_reference_files(self):\n raise NotImplementedError('You need to define a get_cgp_job_reference_files method!') \n\n '''\n Returns a dictionary of keyword used in the dockstore tool runner parameterized JSON\n and used in Elastic search to find needed samples. The JSON data does not depend\n on samples found in the Elastic search so can be added here\n '''\n def get_pipeline_job_fixed_metadata(self):\n raise NotImplementedError('You need to define a get_pipeline_job_fixed_metadata method!')\n\n '''\n Returns a dictionary of keywords to metadata that is used to setup the touch file path\n and metadata and dockstore JSON file names. These sometimes depend on the sample name\n or other information found through the Elastic search so is separated from the method\n that gets the fixed metadata. This routine adds to the metadata dictionary for the pipeline.\n \n E.g\n\n ###########################CUSTOMIZE METADATA FOR PIPELINE START#########################\n #The items below are usually customized for a particular workflow or tool\n\n #launch type is either 'workflow' or 'tool'\n cgp_pipeline_job_metadata[\"launch_type\"] = \"tool\"\n cgp_pipeline_job_metadata[\"analysis_type\"] = \"fusion_variant_calling\"\n cgp_pipeline_job_metadata['metadata_json_file_name'] = cgp_pipeline_job_metadata['file_prefix'] + '_meta_data.json'\n cgp_pipeline_job_metadata[\"target_tool_prefix\"] = 'registry.hub.docker.com/ucsctreehouse/fusion'\n cgp_pipeline_job_metadata[\"target_tool_url\"] = \\\n \"https://dockstore.org/containers/registry.hub.docker.com/ucsctreehouse/fusion/\"\n cgp_pipeline_job_metadata['file_prefix'] = sample[\"submitter_sample_id\"]\n cgp_pipeline_job_metadata[\"last_touch_file_folder_suffix\"] = cgp_pipeline_job_metadata[\"submitter_sample_id\"]\n\n ######################CUSTOMIZE METADATA FOR PIPELINE END################################## \n '''\n def get_pipeline_job_customized_metadata(self, cgp_pipeline_job_metadata):\n raise NotImplementedError('You need to define a get_pipeline_customized_metadata method!')\n\n '''\n Returns a dictionary of CWL keywords and values that make up the CWL input parameterized\n JSON for the pipeline. This is the input to the pipeline to be run from Dockstore. \n\n E.g:\n #Edit the following lines to set up the pipeline tool/workflow CWL options \n ######################CUSTOMIZE JSON INPUT FOR PIPELINE START################################### \n\n cgp_pipeline_job_json = defaultdict()\n \n for file in analysis[\"workflow_outputs\"]:\n print(\"\\nfile type:\"+file[\"file_type\"])\n print(\"\\nfile name:\"+file[\"file_path\"])\n \n #if (file[\"file_type\"] != \"bam\"): output an error message?\n \n file_path = 'redwood' + '://' + self.redwood_host + '/' + analysis['bundle_uuid'] + '/' + \\\n self.fileToUUID(file[\"file_path\"], analysis[\"bundle_uuid\"]) + \\\n \"/\" + file[\"file_path\"]\n \n if 'fastq1' not in cgp_pipeline_job_json.keys():\n cgp_pipeline_job_json['fastq1'] = defaultdict(dict)\n cgp_pipeline_job_json['fastq1'] = {\"class\" : \"File\", \"path\" : file_path}\n elif 'fastq2' not in cgp_pipeline_job_json.keys():\n cgp_pipeline_job_json['fastq2'] = defaultdict(dict)\n cgp_pipeline_job_json['fastq2'] = {\"class\" : \"File\", \"path\" : file_path}\n else:\n print(\"ERROR: too many input files!!!\", file=sys.stderr)\n \n if 'parent_uuids' not in cgp_pipeline_job_metadata.keys():\n cgp_pipeline_job_metadata[\"parent_uuids\"] = []\n \n if sample[\"sample_uuid\"] not in cgp_pipeline_job_metadata[\"parent_uuids\"]: \n cgp_pipeline_job_metadata[\"parent_uuids\"].append(sample[\"sample_uuid\"])\n \n cgp_pipeline_job_json[\"outputdir\"] = '.'\n cgp_pipeline_job_json[\"root-ownership\"] = True\n \n # Specify the output files here, using the options in the CWL file as keys\n file_path = \"/tmp/star-fusion-gene-list-filtered.final\"\n cgp_pipeline_job_json[\"output1\"] = {\"class\" : \"File\", \"path\" : file_path}\n file_path = \"/tmp/star-fusion-gene-list-filtered.final.bedpe\"\n cgp_pipeline_job_json[\"output2\"] = {\"class\" : \"File\", \"path\" : file_path}\n file_path = \"/tmp/star-fusion-non-filtered.final\"\n cgp_pipeline_job_json[\"output3\"] = {\"class\" : \"File\", \"path\" : file_path}\n file_path = \"/tmp/star-fusion-non-filtered.final.bedpe\"\n cgp_pipeline_job_json[\"output4\"] = {\"class\" : \"File\", \"path\" : file_path}\n\n ####################CUSTOMIZE JSON INPUT FOR PIPELINE END#######################################\n\n ''' \n def get_pipeline_parameterized_json(self, cgp_pipeline_job_metadata, analysis):\n raise NotImplementedError('You need to define a get_pipeline_parameterized_json method!')\n\n\n def get_cgp_pipeline_jobs_metadata(self, hits, cgp_jobs_fixed_metadata, cgp_jobs_reference_files):\n cgp_all_pipeline_jobs_metadata = []\n\n for hit in hits:\n print(\"\\n\\n\\nDonor uuid:%(donor_uuid)s Center Name:%(center_name)s Program:%(program)s Project:%(project)s\" % hit[\"_source\"])\n print(\"Got %d specimens:\" % len(hit[\"_source\"][\"specimen\"]))\n\n #if a particular center, program or project is requested for processing and\n #the current one does not match go on to the next sample\n if self.center and (self.center != hit[\"_source\"][\"center_name\"]):\n continue\n if self.program and (self.program != hit[\"_source\"][\"program\"]):\n continue\n if self.project and (self.project != hit[\"_source\"][\"project\"]):\n continue\n\n\n for specimen in hit[\"_source\"][\"specimen\"]:\n print(\"Next sample of %d samples:\" % len(specimen[\"samples\"]))\n for sample in specimen[\"samples\"]:\n print(\"Next analysis of %d analysis:\" % len(sample[\"analysis\"]))\n\n #if a particular sample uuid is requested for processing and\n #the current sample uuid does not match go on to the next sample\n if self.process_sample_uuids and sample[\"sample_uuid\"] not in self.process_sample_uuids.split():\n continue\n\n for analysis in sample[\"analysis\"]:\n #print analysis\n print(\"HIT!!!!\")\n print(\"analysis type:{}\".format(analysis[\"analysis_type\"]))\n print(\"normal flag:{}\".format(str(hit[\"_source\"][\"flags\"][\"normal_sequence\"])))\n print(\"tumor flag:{}\".format(str(hit[\"_source\"][\"flags\"][\"tumor_sequence\"])))\n\n for output in analysis[\"workflow_outputs\"]:\n json_str = json.dumps(output, sort_keys=True, indent=4, separators=(',', ': '))\n print(json_str)\n\n #put together the metadata and then decide whether the job is to be included in the list of jobs\n #This metadata will be passed to the Consonance Task and some\n #some of the meta data will be used in the Luigi status page for the job\n cgp_pipeline_job_metadata = defaultdict()\n print(\"constructing pipeline job metadata\") \n\n #attach fixed metadata to pipeline job json\n cgp_pipeline_job_metadata.update(cgp_jobs_fixed_metadata)\n\n cgp_pipeline_job_metadata[\"sample_name\"] = sample[\"submitter_sample_id\"]\n cgp_pipeline_job_metadata[\"program\"] = hit[\"_source\"][\"program\"]\n cgp_pipeline_job_metadata[\"project\"] = hit[\"_source\"][\"project\"]\n cgp_pipeline_job_metadata[\"center_name\"] = hit[\"_source\"][\"center_name\"]\n cgp_pipeline_job_metadata[\"submitter_donor_id\"] = hit[\"_source\"][\"submitter_donor_id\"]\n cgp_pipeline_job_metadata[\"donor_uuid\"] = hit[\"_source\"][\"donor_uuid\"]\n if \"submitter_donor_primary_site\" in hit[\"_source\"]:\n cgp_pipeline_job_metadata[\"submitter_donor_primary_site\"] = hit[\"_source\"][\"submitter_donor_primary_site\"]\n else:\n cgp_pipeline_job_metadata[\"submitter_donor_primary_site\"] = \"not provided\"\n cgp_pipeline_job_metadata[\"submitter_specimen_id\"] = specimen[\"submitter_specimen_id\"]\n cgp_pipeline_job_metadata[\"specimen_uuid\"] = specimen[\"specimen_uuid\"]\n cgp_pipeline_job_metadata[\"submitter_specimen_type\"] = specimen[\"submitter_specimen_type\"]\n cgp_pipeline_job_metadata[\"submitter_experimental_design\"] = specimen[\"submitter_experimental_design\"]\n cgp_pipeline_job_metadata[\"submitter_sample_id\"] = sample[\"submitter_sample_id\"]\n cgp_pipeline_job_metadata[\"sample_uuid\"] = sample[\"sample_uuid\"]\n cgp_pipeline_job_metadata[\"workflow_version\"] = self.workflow_version\n\n\n #get metadata for the pipeline that depends on the particular sample \n cgp_pipeline_job_metadata = self.get_pipeline_job_customized_metadata(cgp_pipeline_job_metadata)\n\n #The action service monitor looks for 'workflow_name' when it inserts the job data into its DB\n cgp_pipeline_job_metadata[\"workflow_name\"] = cgp_pipeline_job_metadata[\"target_tool_prefix\"]\n\n workflow_version_dir = self.workflow_version.replace('.', '_')\n touch_file_path_prefix = self.touch_file_bucket + \\\n \"/consonance-jobs/\" + \\\n self.get_pipeline_name() + \"_Coordinator/\" + workflow_version_dir\n\n touch_file_path = touch_file_path_prefix + \"/\" \\\n + cgp_pipeline_job_metadata[\"center_name\"] + \"_\" \\\n + cgp_pipeline_job_metadata[\"program\"] + \"_\" \\\n + cgp_pipeline_job_metadata[\"project\"] + \"_\" \\\n + cgp_pipeline_job_metadata[\"submitter_donor_primary_site\"] + \"_\" \\\n + cgp_pipeline_job_metadata[\"submitter_specimen_id\"] + \"_\" \\\n + cgp_pipeline_job_metadata[\"submitter_sample_id\"] + \"_\" \\\n + cgp_pipeline_job_metadata[\"last_touch_file_folder_suffix\"] + \"_\" \\\n + cgp_pipeline_job_metadata[\"sample_uuid\"]\n\n cgp_pipeline_job_metadata[\"s3_metadata_json_file_path\"] = \"s3://\" + \\\n touch_file_path + \"/\" + \\\n cgp_pipeline_job_metadata['metadata_json_file_name']\n cgp_pipeline_job_metadata[\"s3_dockstore_tool_runner_json_file_path\"] = \"s3://\" + \\\n touch_file_path + \"/\" + \\\n cgp_pipeline_job_metadata['file_prefix'] + \\\n \"_dockstore_tool.json\"\n cgp_pipeline_job_metadata[\"local_dockstore_tool_runner_json_file_path\"] = \"/tmp/\" + \\\n touch_file_path + \"/\" + \\\n cgp_pipeline_job_metadata['file_prefix'] + \\\n \"_dockstore_tool.json\"\n cgp_pipeline_job_metadata[\"s3_finished_json_file_path\"] = \"s3://\" + \\\n touch_file_path + \"/\" + \\\n cgp_pipeline_job_metadata['file_prefix'] + \\\n \"_finished.json\"\n cgp_pipeline_job_metadata[\"touch_file_path\"] = touch_file_path\n #should we remove all white space from the path in the case where \n #i.e. the program name is two words separated by blanks?\n # remove all whitespace from touch file path\n #touch_file_path = ''.join(touch_file_path.split())\n \n json_str = json.dumps(cgp_pipeline_job_metadata, sort_keys=True, indent=4, separators=(',', ': ')) \n print(\"HIT metadata:\\n{}\".format(json_str))\n\n #If this sample has not already been run through the pipeline add it to the list of jobs\n if ( (\n #Most pipelines work only on a certain data format \n #For instance Fusion and RNA-Seq pipelines work only on uploaded sequences\n #and the CNV pipeline works only with uploaded BAMs\n analysis[\"analysis_type\"] == cgp_pipeline_job_metadata[\"input_data_analysis_type\"] and \\\n #Most pipelines work only on specially prepared data\n #For example the Fusion pipeline works only on RNA-Seq prepared data\n (re.match(\"^\" + cgp_pipeline_job_metadata[\"input_data_experimental_design\"] + \"$\", specimen[\"submitter_experimental_design\"]))\n ) \n and \\\n (\n (hit[\"_source\"][\"flags\"][ cgp_pipeline_job_metadata[\"normal_metadata_flag\"] ] == False and \\\n sample[\"sample_uuid\"] in hit[\"_source\"][\"missing_items\"][ cgp_pipeline_job_metadata[\"normal_missing_item\"] ] and \\\n re.match(\"^Normal - \", specimen[\"submitter_specimen_type\"])) \n or \\\n (\n hit[\"_source\"][\"flags\"][ cgp_pipeline_job_metadata[\"tumor_metadata_flag\"] ] == False and \\\n sample[\"sample_uuid\"] in hit[\"_source\"][\"missing_items\"][ cgp_pipeline_job_metadata[\"tumor_missing_item\"] ] and \\\n re.match(\"^Primary tumour - |^Recurrent tumour - |^Metastatic tumour - |^Cell line -\", specimen[\"submitter_specimen_type\"]))\n )\n ):\n\n #get the parameterized JSON that is the input to the pipeline registered in Dockstore\n cgp_pipeline_job_json = self.get_pipeline_parameterized_json(cgp_pipeline_job_metadata, analysis)\n \n #If the derived pipeline code was unable to construct valid parameterized\n #pipeline JSON input file the list will be empty \n if cgp_pipeline_job_json:\n #attach reference file json to pipeline job json\n cgp_pipeline_job_json.update(cgp_jobs_reference_files)\n print('keys for cgp pipeline job json:' + ','.join(cgp_pipeline_job_json.keys()))\n\n json_str = json.dumps(cgp_pipeline_job_json, sort_keys=True, indent=4, separators=(',', ': '))\n #print(\"\\nCGP pipeline job json:\\n{}\".format(json_str))\n \n #attach the workflow or tool parameterized json to the job metadata\n cgp_pipeline_job_metadata[\"pipeline_job_json\"] = cgp_pipeline_job_json\n json_str = json.dumps(cgp_pipeline_job_metadata, sort_keys=True, indent=4, separators=(',', ': '))\n #print(\"\\nCGP pipeline job metadata:\\n{}\".format(json_str))\n \n #attach this jobs metadata to a list of all the jobs metadata\n cgp_all_pipeline_jobs_metadata.append(cgp_pipeline_job_metadata)\n json_str = json.dumps(cgp_all_pipeline_jobs_metadata, sort_keys=True, indent=4, separators=(',', ': '))\n #print(\"\\nCGP all pipeline jobs meta data:\\n{}\".format(json_str))\n else:\n json_str = json.dumps(cgp_pipeline_job_metadata, sort_keys=True, indent=4, separators=(',', ': '))\n print(\"\\nWARNING: UNABLE TO GET PARAMETERIZED JSON FOR PIPELINE WITH METADATA:{}\".format(json_str) , file=sys.stderr)\n\n return cgp_all_pipeline_jobs_metadata\n\n def requires(self):\n print(\"\\n\\n\\n\\n** COORDINATOR REQUIRES **\")\n\n # now query the metadata service so I have the mapping of bundle_uuid & file names -> file_uuid\n print(str(\"metadata.\"+self.redwood_host+\"/entities?page=0\"))\n\n #hack to get around none self signed certificates\n ctx = ssl.create_default_context()\n ctx.check_hostname = False\n ctx.verify_mode = ssl.CERT_NONE\n\n #Go through the metadata and setup the mapping of bundle uuid to file name\n json_str = urlopen(str(\"https://metadata.\"+self.redwood_host+\"/entities?page=0\"), context=ctx).read()\n metadata_struct = json.loads(json_str)\n print(\"** METADATA TOTAL PAGES: \"+str(metadata_struct[\"totalPages\"]))\n for i in range(0, metadata_struct[\"totalPages\"]):\n print(\"** CURRENT METADATA TOTAL PAGES: \"+str(i))\n json_str = urlopen(str(\"https://metadata.\"+self.redwood_host+\"/entities?page=\"+str(i)), context=ctx).read()\n metadata_struct = json.loads(json_str)\n for file_hash in metadata_struct[\"content\"]:\n self.bundle_uuid_filename_to_file_uuid[file_hash[\"gnosId\"]+\"_\"+file_hash[\"fileName\"]] = file_hash[\"id\"]\n\n\n #Get the reference file metadata from the storage system\n #and create a file path that the Dockstore tool runner can\n #used to download the reference file from the storage system\n cgp_jobs_reference_files = defaultdict()\n cwl_option_to_reference_file_name = self.get_cgp_job_reference_files()\n\n #Go through the reference files for this pipeline and find the bundle uuid\n #file uuid and file name in the metadata and set up the path to the file \n #in the storage system so it can be downloaded when the pipeline is run\n for switch, file_name in cwl_option_to_reference_file_name.iteritems():\n print(\"switch:{} file name {}\".format(switch, file_name))\n file_name_metadata_json = urlopen(str(\"https://metadata.\"+self.redwood_host+\"/entities?fileName=\"+file_name), context=ctx).read()\n file_name_metadata = json.loads(file_name_metadata_json)\n if file_name_metadata['totalElements'] == 0:\n print('ERROR: could not find reference file in storage system!')\n print(\"reference file metadata:\\n{}\".format(str(file_name_metadata)))\n bundle_uuid = file_name_metadata[\"content\"][0][\"gnosId\"]\n file_uuid = file_name_metadata[\"content\"][0][\"id\"]\n file_name = file_name_metadata[\"content\"][0][\"fileName\"]\n\n ref_file_path = 'redwood' + '://' + self.redwood_host + '/' + bundle_uuid + '/' + \\\n file_uuid + \"/\" + file_name\n cgp_jobs_reference_files[switch] = {\"class\" : \"File\", \"path\" : ref_file_path}\n\n json_str = json.dumps(cgp_jobs_reference_files[switch], sort_keys=True, indent=4, separators=(',', ': '))\n print(\"Reference files json:\\n{}\".format(json_str))\n\n\n cgp_jobs_fixed_metadata = self.get_pipeline_job_fixed_metadata()\n\n # now query elasticsearch to find the samples that been run through the pipeline\n print(\"setting up elastic search Elasticsearch([\\\"http:\\/\\/\"+self.es_index_host+\":\"+self.es_index_port+\"]\")\n es = Elasticsearch([{'host': self.es_index_host, 'port': self.es_index_port}])\n res = es.search(index=\"analysis_index\", body={\"query\" : {\"bool\" : {\"should\" : [{\"term\" : { \"flags.\" + cgp_jobs_fixed_metadata[\"normal_metadata_flag\"] : \"false\"}}, \\\n {\"term\" : {\"flags.\" + cgp_jobs_fixed_metadata[\"tumor_metadata_flag\"] : \"false\" }}],\"minimum_should_match\" : 1 }}}, size=5000)\n\n print(\"Got %d Hits:\" % res['hits']['total'])\n cgp_pipeline_jobs_metadata = self.get_cgp_pipeline_jobs_metadata(res['hits']['hits'], cgp_jobs_fixed_metadata, cgp_jobs_reference_files)\n\n listOfJobs = []\n #Go through the list of jobs and if the max number of jobs to run has\n #not been reached add it to the list of jobs to run\n for job_num, job in enumerate(cgp_pipeline_jobs_metadata):\n print('job num:{}'.format(job_num))\n if (job_num < int(self.max_jobs) or int(self.max_jobs) < 0):\n cgp_pipeline_job_metadata_str = json.dumps(job, sort_keys=True, indent=4, separators=(',', ': '))\n print(\"\\npipeline job metadata:\")\n print(cgp_pipeline_job_metadata_str)\n\n listOfJobs.append(ConsonanceTask(redwood_host=self.redwood_host,\n vm_instance_type=self.vm_instance_type,\n vm_region = self.vm_region,\n redwood_token=self.redwood_token,\n dockstore_tool_running_dockstore_tool=self.dockstore_tool_running_dockstore_tool,\n tmp_dir=self.tmp_dir,\n workflow_version = self.workflow_version,\n cgp_pipeline_job_metadata_str = cgp_pipeline_job_metadata_str,\n metadata_json_file_name = job['metadata_json_file_name'],\n touch_file_path = job['touch_file_path'],\n file_prefix = job['file_prefix'],\n test_mode=self.test_mode))\n\n \n print(\"total of {} jobs; max jobs allowed is {}\\n\\n\".format(str(len(listOfJobs)), self.max_jobs))\n\n # these jobs are yielded to\n print(\"\\n\\n** COORDINATOR REQUIRES DONE!!! **\")\n return listOfJobs\n\n def run(self):\n print(\"\\n\\n\\n\\n** COORDINATOR RUN **\")\n # now make a final report\n f = self.output().open('w')\n # TODO: could print report on what was successful and what failed? Also, provide enough details like donor ID etc\n print(\"batch is complete\", file=f)\n f.close()\n print(\"\\n\\n\\n\\n** COORDINATOR RUN DONE **\")\n\n def output(self):\n print(\"\\n\\n\\n\\n** COORDINATOR OUTPUT **\")\n # the final report\n ts = time.time()\n ts_str = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H:%M:%S')\n workflow_version_dir = self.workflow_version.replace('.', '_')\n return S3Target('s3://'+ self.touch_file_bucket + '/consonance-jobs/{}_Coordinator/{}/{}-{}.txt'.format( \\\n self.get_pipeline_name(), workflow_version_dir, self.get_pipeline_name(), ts_str))\n\n def fileToUUID(self, input, bundle_uuid):\n return self.bundle_uuid_filename_to_file_uuid[bundle_uuid+\"_\"+input]\n #\"afb54dff-41ad-50e5-9c66-8671c53a278b\"\n\nif __name__ == '__main__':\n luigi.run()\n\n","sub_path":"luigi_task_executor/base_decider.py","file_name":"base_decider.py","file_ext":"py","file_size_in_byte":35724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"502380125","text":"winStates = [[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]]\r\nallBoards = set()\r\ngamesCount = 0\r\n\r\ndef run():\r\n recurse(\"_________\")\r\n\r\ndef win(layout):\r\n for winState in winStates:\r\n if layout[winState[0]] != '_' and layout[winState[0]] == layout[winState[1]] and layout[winState[1]] == layout[winState[2]]:\r\n return True\r\n return False\r\n\r\ndef recurse(layout):\r\n global gamesCount\r\n\r\n allBoards.add(layout)\r\n\r\n if win(layout) or layout.count(\"_\") == 0:\r\n gamesCount += 1\r\n return\r\n\r\n next = \"\"\r\n if layout.count(\"x\") == layout.count(\"o\"):\r\n next = \"x\"\r\n else:\r\n next = \"o\"\r\n\r\n for position in range(0,9):\r\n if layout[position] == \"_\":\r\n newLayout = layout[:position] + next + layout[position + 1:]\r\n recurse(newLayout)\r\n\r\nrun()\r\nprint(gamesCount, len(allBoards))\r\n","sub_path":"tictactoe/games-boards-count.py","file_name":"games-boards-count.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"460139144","text":"import argparse\r\nimport os\r\n\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nimport torch.optim as optim\r\nfrom torchvision import datasets, transforms\r\nfrom tqdm import tqdm\r\n\r\nfrom net.models import Net\r\nfrom net.quantization import apply_weight_sharing\r\nimport util\r\n\r\n# 아래는 depth map prediction을 위해서 필용한 것.\r\nimport model_utils\r\nfrom dataset import NYUDataset\r\nfrom custom_transforms import *\r\n\r\nos.makedirs('saves', exist_ok=True)\r\n\r\n# Training settings\r\nparser = argparse.ArgumentParser(description='PyTorch MNIST pruning from deep compression paper')\r\nparser.add_argument('--batch-size', type=int, default=8, metavar='N',\r\n help='input batch size for training (default: 8)')\r\nparser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',\r\n help='input batch size for testing (default: 1000)')\r\nparser.add_argument('--epochs', type=int, default=1, metavar='N',\r\n help='number of epochs to train (default: 1)') # 경록\r\nparser.add_argument('--lr', type=float, default=0.0000005, metavar='LR',\r\n help='learning rate (default: 0.01)')\r\nparser.add_argument('--no-cuda', action='store_true', default=False,\r\n help='disables CUDA training')\r\nparser.add_argument('--seed', type=int, default=42, metavar='S',\r\n help='random seed (default: 42)')\r\nparser.add_argument('--log-interval', type=int, default=10, metavar='N',\r\n help='how many batches to wait before logging training status')\r\nparser.add_argument('--log', type=str, default='log.txt',\r\n help='log file name')\r\nparser.add_argument('--sensitivity', type=float, default=2,\r\n help=\"sensitivity value that is multiplied to layer's std in order to get threshold value\")\r\nparser.add_argument('--percentile', type=float, default=5,\r\n help=\"percentile value that is under % value to get threshold value\")\r\nargs = parser.parse_args()\r\n\r\n# Control Seed\r\ntorch.manual_seed(args.seed)\r\n\r\n# Select Device\r\nuse_cuda = not args.no_cuda and torch.cuda.is_available()\r\ndevice = torch.device(\"cuda\" if use_cuda else 'cpu')\r\nif use_cuda:\r\n print(\"Using CUDA!\")\r\n torch.cuda.manual_seed(args.seed)\r\nelse:\r\n print('Not using CUDA!!!')\r\n\r\n# Loader\r\nkwargs = {'num_workers': 5, 'pin_memory': True} if use_cuda else {}\r\n# train_loader = torch.utils.data.DataLoader(\r\n# datasets.MNIST('data', train=True, download=True,\r\n# transform=transforms.Compose([\r\n# transforms.ToTensor(),\r\n# transforms.Normalize((0.1307,), (0.3081,))\r\n# ])),\r\n# batch_size=args.batch_size, shuffle=True, **kwargs)\r\n# test_loader = torch.utils.data.DataLoader(\r\n# datasets.MNIST('data', train=False, transform=transforms.Compose([\r\n# transforms.ToTensor(),\r\n# transforms.Normalize((0.1307,), (0.3081,))\r\n# ])),\r\n# batch_size=args.test_batch_size, shuffle=False, **kwargs)\r\n\r\n# 아래는 depth Map Prediction을 위한\r\nbs = 8\r\nsz = (320,240)\r\nmean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]\r\nmean, std = torch.tensor(mean), torch.tensor(std)\r\nunnormalize = UnNormalizeImgBatch(mean, std)\r\n\r\ntfms = transforms.Compose([\r\n ResizeImgAndDepth(sz),\r\n RandomHorizontalFlip(),\r\n ImgAndDepthToTensor(),\r\n NormalizeImg(mean, std)\r\n])\r\n\r\nds = NYUDataset('/content/gdrive/My Drive/data/train.mat', tfms) # 경록\r\ndl = torch.utils.data.DataLoader(ds, bs, shuffle=True)\r\n\r\n# test loader 준비\r\nts = NYUDataset('/content/gdrive/My Drive/data/test.mat', tfms) # 경록\r\ntl = torch.utils.data.DataLoader(ts, bs, shuffle=True)\r\n\r\n\r\n# Define which model to use\r\nmodel = Net(mask=True).to(device) # 경록\r\n\r\nfor name, param in model.named_parameters():\r\n if \"VGG\" in name:\r\n param.requires_grad = False\r\n\r\n\r\nprint(model)\r\nutil.print_model_parameters(model)\r\n\r\n# NOTE : `weight_decay` term denotes L2 regularization loss term\r\noptimizer = optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=args.lr)\r\n# optimizer = optim.Adam(model.parameters(), lr=args.lr, weight_decay=0.0001)\r\ninitial_optimizer_state_dict = optimizer.state_dict()\r\n\r\ndef train(epochs):\r\n model.train()\r\n for epoch in range(epochs):\r\n pbar = tqdm(enumerate(dl), total=len(dl))\r\n for batch_idx, (data, target) in pbar:\r\n data, target = data.to(device), target.to(device)\r\n optimizer.zero_grad()\r\n output = model(data)\r\n loss = model_utils.depth_loss(output, target)\r\n loss.backward()\r\n\r\n # zero-out all the gradients corresponding to the pruned connections\r\n for name, p in model.named_parameters():\r\n if 'VGG' in name:\r\n continue\r\n if 'mask' in name:\r\n continue\r\n tensor = p.data.cpu().numpy()\r\n grad_tensor = p.grad.data.cpu().numpy()\r\n grad_tensor = np.where(tensor==0, 0, grad_tensor)\r\n p.grad.data = torch.from_numpy(grad_tensor).to(device)\r\n\r\n optimizer.step()\r\n if batch_idx % args.log_interval == 0:\r\n done = batch_idx * len(data)\r\n percentage = 100. * batch_idx / len(dl)\r\n pbar.set_description(f'Train Epoch: {epoch} [{done:5}/{len(dl.dataset)} ({percentage:3.0f}%)] Loss: {loss.item():.6f}')\r\n\r\n\r\ndef test():\r\n model.eval()\r\n test_loss = 0\r\n test_count = 0\r\n with torch.no_grad():\r\n print(f'tl length:{len(tl.dataset):.4f}')\r\n for data, target in tl:\r\n data, target = data.to(device), target.to(device)\r\n output = model(data)\r\n test_count += 1\r\n print(f'test count: {test_count:.4f}')\r\n test_loss += model_utils.depth_loss(output, target).item()\r\n\r\n test_loss /= len(tl.dataset)\r\n print(f'Test set: Average loss: {test_loss:.4f}')\r\n return test_loss\r\n\r\n\r\n# Initial training\r\nprint(\"--- Initial training ---\")\r\ntrain(args.epochs)\r\naccuracy = test()\r\nutil.log(args.log, f\"initial_accuracy {accuracy}\")\r\n# torch.save(model, f\"/content/gdrive/My Drive/data/model_freeze_L1_40e.ptmodel\") # 경록\r\n# torch.save(model.state_dict(), '/content/gdrive/My Drive/data/model_freeze_L1_40e.ckpt') # 경록\r\n# print(\"--- Before pruning ---\")\r\n# util.print_nonzeros(model)\r\n\r\nfor name, param in model.named_parameters():\r\n print(name, ':', param.requires_grad)\r\n\r\n# Pruning\r\n########################################################################################################################\r\n############################################################\r\n############################################################여기서 perentile할 건지, std할건지 정해야 한다.\r\n########################################################################################################################\r\n# model.prune_by_percentile(args.percentile)\r\n# accuracy = test()\r\n# util.log(args.log, f\"accuracy_after_pruning {accuracy}\")\r\n# print(\"--- After pruning ---\")\r\n# util.print_nonzeros(model)\r\n\r\n# Retrain\r\n# print(\"--- Retraining ---\")\r\n# optimizer.load_state_dict(initial_optimizer_state_dict) # Reset the optimizer\r\n# train(args.epochs)\r\n# torch.save(model, f\"saves/model_after_retraining.ptmodel\")\r\n# accuracy = test()\r\n# util.log(args.log, f\"accuracy_after_retraining {accuracy}\")\r\n#\r\n# print(\"--- After Retraining ---\")\r\n# util.print_nonzeros(model)\r\n","sub_path":"freeze_prune.py","file_name":"freeze_prune.py","file_ext":"py","file_size_in_byte":7600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"262035424","text":"from fuzzywuzzy import process\nimport numpy as np\n\n\nfrom tool import Singleton\nimport sudoku_solving\nfrom Block import Block\n\n@Singleton\nclass Sudoku:\n def __init__(self):\n size = (9, 9)\n self.already_solved = {}\n self.already_solved_numbers = {}\n self.already_solved_false = []\n self.puzzle = np.empty(size, dtype=np.object)\n for i in range(size[0]):\n for j in range(size[1]):\n self.puzzle[i, j] = Block()\n\n def update_block(self, img, block_pos, physical_pos):\n self.puzzle[block_pos].update(img, block_pos, physical_pos)\n\n def guess_sudoku(self, confidence_threshold=0):\n for i in range(9):\n for j in range(9):\n block = self.puzzle[i, j]\n block.guess_number(confidence_threshold=confidence_threshold)\n\n def write_solution(self, sudoku_image, solution, ignore=None):\n if solution is not False:\n cols = '123456789'\n rows = 'ABCDEFGHI'\n for i in range(9):\n for j in range(9):\n number = solution[rows[i] + cols[j]]\n block = self.puzzle[i, j]\n if ignore is None:\n if block.number == 0:\n block.write(sudoku_image, number)\n else:\n if (i, j) not in ignore:\n block.write(sudoku_image, number)\n\n def get_existing_numbers(self):\n existing_numbers = []\n for i in range(9):\n for j in range(9):\n block = self.puzzle[i, j]\n if block.number != 0:\n existing_numbers.append((i, j))\n\n return existing_numbers\n\n def as_string(self):\n string = ''\n array = np.ravel(self.puzzle)\n for guy in array:\n string += str(guy.number)\n\n return string\n\n def solve_basic(self):\n string = self.as_string()\n if string in self.already_solved.keys():\n return self.already_solved[string]\n else:\n solved = sudoku_solving.solve(string)\n return solved\n\n def solve_approximate(self, approximate=False):\n 'If it finds a sudoku similar to one it has already done, uses its solution'\n string = self.as_string()\n if string in self.already_solved.keys():\n\n return self.already_solved[string], self.already_solved_numbers[string]\n else:\n # We save the attempts that we already did but were unsuccesful\n if string in self.already_solved_false:\n solved = False\n else:\n solved = sudoku_solving.solve(string)\n # Print answer\n sudoku_solving.result(string)\n\n # If the sudoku is unsolvable but very similar to one we already did\n # we assume it's the same one but we couldn't quite catch some numbers\n # Approximate is percent-based, 90 = 90%\n if solved is False:\n # Saves this sudoku as false so we don't have to try to solve it every frame\n self.already_solved_false.append(string)\n\n if self.already_solved.keys():\n\n guesses = process.extract(string, self.already_solved.keys())\n\n if guesses:\n\n # Prioritizes length, then similarity to the guess\n if approximate is False:\n best = max(guesses, key=lambda x: (x[1], len(self.already_solved_numbers[x[0]])))[0]\n return self.already_solved[best], self.already_solved_numbers[best]\n else:\n sorty = sorted(guesses, key=lambda x: (len(self.already_solved_numbers[x[0]]), x[1]),\n reverse=True)\n for item in sorty:\n if item[1] > approximate:\n # Sort them by length and then get the one with biggest length that has addecuate ratio?\n return self.already_solved[item[0]], self.already_solved_numbers[item[0]]\n else:\n best = max(guesses, key=lambda x: (x[1], len(self.already_solved_numbers[x[0]])))[0]\n return self.already_solved[best], self.already_solved_numbers[best]\n\n # Only saves correct solutions\n if solved is not False:\n # also save the numbers that already exist in the array\n # (so we don't write over them if we can't see them)\n self.already_solved_numbers[string] = self.get_existing_numbers()\n self.already_solved[string] = solved\n\n return solved, self.already_solved_numbers[string]\n\n return False, False\n\n def solve(self, img_cropped_sudoku, approximate=False):\n solution, existing_numbers = self.solve_approximate(approximate)\n self.write_solution(img_cropped_sudoku, solution, ignore=existing_numbers)\n","sub_path":"src/Sudoku.py","file_name":"Sudoku.py","file_ext":"py","file_size_in_byte":5150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"593256401","text":"import cv2\nimport numpy as np\nfrom keras import models\nimport tensorflow as tf\nfrom tensorflow import keras\nimport sys\nfrom PIL import Image\nimport face_recognition\n\n# Initialize some variables\nface_locations = []\nface_ages = []\n\nvideo = cv2.VideoCapture(0)\nprocess_this_frame = True\nmodel_path = \"/Users/christianbv/PycharmProjects/ML/venv/models_model_adam_v2_14_11\"\n\n# Loading the model for inference\nmodel = models.load_model(model_path)\nclass_labels = ['0-2', '3-6', '7-12', '13-17', '18-22', '23-26', '27-33', '34-44', '45-59', '60-199']\nprint(\"Model loaded...\", '\\n','\\n')\n\n\n\"\"\"\n Converts the multi-class predictions into one single value\n Using the average value of each bucket here - naturally not very precise, however it gives an indication\n\"\"\"\ndef predict_acc_age(predictions):\n score = 0\n avg_age = [1, 4.5, 9.5, 15, 20, 24.5, 30, 39, 52, 75]\n for i in range(len(predictions)):\n score += avg_age[i] * predictions[i]\n return int(score)\n\n\"\"\"\n Predicts the age for a given picture\n Returns:\n predicted age (regression), predicted age class (class with highest softmax value), and prob (highest softmax value).\n\"\"\"\ndef predict_age(im):\n im_array = keras.preprocessing.image.img_to_array(im)\n im_array = tf.expand_dims(im_array, 0) # Create a batch\n\n predictions = model.predict(im_array)\n score = tf.nn.softmax(predictions[0])\n prob = max(score.numpy())\n predicted_age_class = class_labels[np.argmax(score.numpy())]\n predicted_age = predict_acc_age(score.numpy())\n return predicted_age, predicted_age_class, prob\n\"\"\"\n The logic which runs everything\n Press q for exit\n\"\"\"\nwhile True:\n _, frame = video.read()\n # Gjør bildet mindre\n smaller_img = cv2.resize(frame, (0,0), fx=0.5, fy = 0.5)\n # Endrer fra BGR til RGB (face recognition)\n rgb_smaller = smaller_img[:,:,::-1]\n\n # Prossesserer bare annenhvert bilde:\n if process_this_frame:\n # Henter ut lokasjoner og encodings for hvert fjes i denne video framen:\n face_locations = face_recognition.face_locations(rgb_smaller)\n im = Image.fromarray(rgb_smaller)\n images = []\n # Predikerer alder:\n for (top,right,bottom,left) in face_locations:\n padding = abs(left-right)*0.4\n im_cropped = im.crop((left - padding, top - padding, right + padding, bottom + padding))\n im_resized = im_cropped.resize((256,256), Image.ANTIALIAS)\n images.append(im_resized)\n\n face_ages = []\n for image in images:\n age_acc, age_pred, prob = predict_age(image)\n text = f'Age: {age_acc}. {np.round(prob*100,3)}%'\n #text2 = f'Age: {age_acc}, interval: {age_pred}. {np.round(prob*100,3)}%' # Uncomment for both regressor and class with highest score\n face_ages.append(text)\n\n process_this_frame = not process_this_frame\n\n # Display the results\n for (top, right, bottom, left), age in zip(face_locations, face_ages):\n # Scale back up face locations since the frame we detected in was scaled to 1/4 size\n top *= 2\n right *= 2\n bottom *= 2\n left *= 2\n\n # Draw a box around the face\n cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)\n\n # Draw a label with a name below the face\n cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)\n font = cv2.FONT_HERSHEY_DUPLEX\n cv2.putText(frame, age, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)\n\n # Display the resulting image\n cv2.imshow('Video', frame)\n\n key = cv2.waitKey(1)\n if key == ord('q'):\n break\nvideo.release()\ncv2.destroyAllWindows()\n","sub_path":"inference_CNN.py","file_name":"inference_CNN.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"97513536","text":"import pyglet\nfrom os.path import join\nfrom engine.core.utils.mipy.py_extensions import *\nfrom engine.core.utils.mipy.caching import mod_cache\nfrom engine.core import GLOBAL\nimport weakref\n\npath_img =convertSlashPath(\"resources/images/\")\npath_audio =convertSlashPath(\"resources/audio/\")\npath_fonts =convertSlashPath(\"resources/fonts/\")\npath_shaders =convertSlashPath(\"resources/shaders\")\n\n@mod_cache\ndef loadAnimationFromSheet(name,dim,timing,looping):\n\tpath = join(path_img,name)\n\traw = pyglet.resource.image(path)\n\traw_seq = pyglet.image.ImageGrid(raw, dim[1], dim[0])\n\tanim = pyglet.image.Animation.from_image_sequence(raw_seq, timing, looping)\n\treturn anim\n\ndef loadStaticImage(name):\n\tpath = join(path_img,name)\n\treturn pyglet.resource.image(path)\n\n\ndef checkCachedImage(name):\n\tname = join(path_img,name)\n\tif name in pyglet.resource._default_loader._cached_images:\n\t\tdel pyglet.resource._default_loader._cached_images[name]\n\n\ndef clearCache():\n\tpyglet.resource._default_loader._cached_textures = weakref.WeakValueDictionary()\n\tpyglet.resource._default_loader._cached_images = weakref.WeakValueDictionary()","sub_path":"engine/core/resource_manager.py","file_name":"resource_manager.py","file_ext":"py","file_size_in_byte":1111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"552623019","text":"import datetime\nfrom django.core.cache import cache\nfrom django.conf import settings\nfrom django.utils.deprecation import MiddlewareMixin\n\nclass AUserMiddleware(MiddlewareMixin):\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 current_user = request.user\n print(request.user)\n if request.user.is_authenticated:\n now = datetime.datetime.now()\n print(now)\n cache.set('seen_%s' %(current_user.username), now, \n settings.USER_LASTSEEN_TIMEOUT)\n return response\n\n","sub_path":"Login/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"562403459","text":"from ..common import *\n\n\ndef gabor_cos(x, y, frq, ang, sig):\n gamma = 1./(sig*frq)\n return np.cos(2.*np.pi*gamma*sig*( x*np.sin(ang) - y*np.cos(ang) ))\n\n\ndef gabor_sin(x, y, frq, ang, sig):\n gamma = 1./(sig*frq)\n return np.sin(2.*np.pi*gamma*sig*( x*np.sin(ang) - y*np.cos(ang) ))\n\n \ndef gabor_exp(x, y, sig):\n return np.exp(-(x**2 + y**2)/(2*sig**2))\n\n\ndef gabor_xy(kernel_width):\n half_width = kernel_width//2\n xmax = half_width; ymax = half_width\n x, y = np.meshgrid(np.arange(-xmax, xmax + 1),\n np.arange(-ymax, ymax + 1))\n y = -y\n return x, y\n\n\ndef gabor(kernel_width, angle, sigma, freq):\n x, y = gabor_xy(kernel_width)\n gc = gabor_cos(x, y, freq, angle, sigma)\n gs = gabor_sin(x, y, freq, angle, sigma)\n ge = gabor_exp(x, y, sigma)\n gbr = gc*gs*ge\n gbr = sum2zero(gbr)\n gbr,w = conv2one(gbr)\n\n return gbr\n\n\ndef multi_gabor(kernel_width, angles, sigma, freq):\n tmp_k = [gabor(kernel_width, a, sigma, freq) for a in angles]\n \n similar = []\n for i in range(len(angles)):\n for j in range(i+1, len(angles)):\n error = np.mean((tmp_k[i] - tmp_k[j])**2)\n if error <= 0.01:\n similar.append(j)\n \n kernels = {rad2deg(angles[i]): tmp_k[i] \\\n for i in range(len(angles)) if i not in similar}\n\n return kernels\n \n","sub_path":"vision/sim_tools/kernels/gabor.py","file_name":"gabor.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"377520277","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 22 17:10:35 2019\n\n@author: LocalAdmin\n\nCurve fitting script\n\n\"\"\"\nimport os\nimport math as m\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.optimize import curve_fit\nimport instrument_module as instr\n\ndef negative_exponent(x, a, b, c):\n return a * np.exp(- x / b)\n\ndef reverse_exponent(x, a, b, c):\n return a * (1 - np.exp(-b * x)) + c\n\ndef logarithm(x, a, b, c, d):\n loga = a * np.log(b * x + d) + c\n return loga\n\ndef linear(x, a, b):\n return a * x + b\n\ndef power_law(x, a, b, c):\n return a * x**b + c\n\n# Inputs\n \nfolder = r'D:\\Rijk\\MEP_control_software'\nfile_name = '0117_1703_WO3196_full_IV_curve'\n\nfile_current = os.path.join(folder, file_name, 'data', file_name + '_current')\nfile_voltage = os.path.join(folder, file_name, 'data', file_name + '_voltage')\n\nfunc = linear\n\nstart = 17\nstop = 101 - 17\n\n#p0 = [1E12, -3/2, 1E5]\n#p0 = [2E7, 1E4, 2E7]\n#bounds = (0, np.inf)\n\n# Import data\ncurrent_plus = instr.load_data(file_current)[1][:101]\nvoltage_plus = instr.load_data(file_voltage)[1][:101]\n\n\ncurrent_min = instr.load_data(file_current)[1][101:]\nvoltage_min = instr.load_data(file_voltage)[1][101:]\n\nxdata0 = current_plus\nydata0 = voltage_plus\n\nif start > 0:\n if stop < len(xdata0):\n xdata0 = xdata0[start:stop]\n ydata0 = ydata0[start:stop]\n else:\n print('Stop index too large for current array')\n xdata0 = xdata0[start:]\n ydata0 = ydata0[start:]\n xdata0 = xdata0 - min(xdata0)\n \nelse:\n print('Start index zero or lower, so not used')\n if stop < len(xdata0):\n xdata0 = xdata0[:stop]\n ydata0 = ydata0[:stop]\n else:\n print('Stop index too large for current array')\n#\n## Correction for logarithmic fitting purposes\n## gets rid of the negative values in y\n#for i in range(len(ydata)):\n# if ydata[i] < 0.01:\n# ydata[i] = 1E9\n# else:\n# ydata[i] = ydata[i]\n\n# Perform regular fit and constrained fit\npopt, pcov = curve_fit(func, xdata0, ydata0, maxfev=int(1E9))\n#popt, pcov = curve_fit(func, xdata0, ydata0, p0, maxfev=int(1E9))\n#popt, pcov = curve_fit(func, xdata, ydata, p0, maxfev=int(1E7), bounds=bounds)\n\n# Plot fit\n\n#plt.close('all')\n\nxdata_fit = np.linspace(min(xdata0), max(xdata0), int(1E3))\n\nplt.figure()\nplt.plot(xdata0, ydata0)\nplt.plot(xdata_fit, func(xdata_fit, *popt))\n#plt.plot(current_plus, voltage_plus)\n#plt.plot(current_min, voltage_min)\n\n\nplt.title('IV curve of WO3916')\nplt.xlabel('Current (A)')\nplt.ylabel('Voltage (V)')\n\n#plt.ylim(min(xdata0), 120)\n#plt.xlim(min(ydata0), 1.2E5)\n\n#plt.yscale('log')\n#plt.yscale('linear')\n#\n#plt.xscale('log')\n#plt.yscale('log')\n\nplt.legend(['Data', 'Fit'])\n#plt.legend(['Plus', 'Minus'])\n\n#instr.save_plot(file_name + '_fit')","sub_path":"data_fit_ivcurve.py","file_name":"data_fit_ivcurve.py","file_ext":"py","file_size_in_byte":2779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"182017534","text":"import re\n\nVariables = dict() # Key -> Variable ; Value -> [valor, tipo] \nFunciones = dict() # Key -> Nombre de la funcion ; Value -> [(operando,tipo entrada,tipo salida),sentencias] \nIn_Fun = None\nIn_While = None\nCond_Done = False\nLET = \"let mut\"\nWHILE = \"while\"\nIF = \"if\"\nELSE = \"else\"\nELSE_IF = \"else if\"\nRETURN = \"return\"\nFN = \"fn\"\nSENT = \";\"\nEND = \"}\"\nPRINT = \"println!\"\n\n\nvar_val = re.compile(\"let mut\\s*(\\w+)\\s*:\\s*(i16|i32|f64)\\s*=\\s*(\\d*|\\d*\\.\\d*)\\s*;\")\nvar_var = re.compile(\"let mut\\s*(\\w+)\\s*:\\s*(i16|i32|f64)\\s*=\\s*(\\w+)\\s*;\")\nvar_func = re.compile(\"let mut\\s*(\\w*)\\s*:\\s*(i16|i32|f64)\\s*=\\s*(\\w*)\\((\\w*)\\)\\s*;\")\nvar_op = re.compile(\"let mut\\s*(\\w+)\\s*:\\s*(i16|i32|f64)\\s*=\\s*(\\w+)\\s*(\\+|\\-)\\s*(\\w+)\\s*;\")\nvar_op_cast = re.compile(\"let mut\\s*(\\w*)\\s*:\\s*(i16|i32|f64)\\s*=\\s*(\\w*)\\s*(\\+|\\-)\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*;\")\nvar_op_valcasti = re.compile(\"let mut\\s*(\\w*)\\s*:\\s*(i16|i32|f64)\\s*=\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*(\\+|\\-)\\s*(\\w*)\\s*;\")\nvar_op_valcastd = re.compile(\"let mut\\s*(\\w*)\\s*:\\s*(i16|i32|f64)\\s*=\\s*(\\w*)\\s*(\\+|\\-)\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*;\")\nvar_op_cast_cast = re.compile(\"let mut\\s*(\\w*)\\s*:\\s*(i16|i32|f64)\\s*=\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*(\\+|\\-)\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*;\")\nsent_val = re.compile(\"(\\w*)\\s*=\\s*(\\w*)\\s*;\")\nobj_bool = re.compile(\"(\\w*)\\s*(<|>|=|>=|<=)\\s*(\\w*)\")\nsent_var = re.compile(\"(\\w*)\\s*=\\s*(\\w*)\\s*;\")\nsent_func = re.compile(\"(\\w*)\\s*=\\s*(\\w*)\\((\\w*)\\)\\s*;\")\nsent_op = re.compile(\"(\\w*)\\s*=\\s*(\\w*)\\s*(\\+|\\-)+\\s*(\\w*)\\s*;\")\nsent_op_cast = re.compile(\"(\\w*)\\s*=\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*;\")\nsent_op_valcasti = re.compile(\"(\\w*)\\s*=\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*(\\+|\\-)\\s*(\\w*)\\s*;\")\nsent_op_valcastd = re.compile(\"(\\w*)\\s*=\\s*(\\w*)\\s*(\\+|\\-)\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*;\")\nsent_op_doublecast = re.compile(\"(\\w+)\\s*=\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*(\\+|\\-)+\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*;\")\nop_sc = re.compile(\"(\\w*|\\d*)\\s*(\\+|\\-)\\s*(\\w*|\\d*)\\s*\")\nop_cd = re.compile(\"\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*(\\+|\\-)\\s*(\\w*)\\s*\")\nop_ci = re.compile(\"(\\w*)\\s*(\\+|\\-)\\s*\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*\")\nop_func_de = re.compile(\"(\\w*)\\s*=\\s*(\\w*)\\s*(\\+|\\-)\\s*(\\w*)\\((\\w*)\\)\\s*;\")\nop_func_iz = re.compile(\"(\\w*)\\s*=\\s*(\\w*)\\((\\w*)\\)\\s*(\\+|\\-)\\s*(\\w*)\\s*;\")\nop_func_do = re.compile(\"(\\w*)\\s*=\\s*(\\w*)\\((\\w*)\\)\\s*(\\+|\\-)\\s*(\\w*)\\((\\w*)\\)\\s*;\")\ncast = re.compile(\"\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*\")\nwhile_sent = re.compile(\"while\\s*(\\w*)\\s*(<|>|=|>=|<=)\\s*(\\w*|\\d*\\.\\d*)\\s*{\")\nif_sent = re.compile(\"if\\s*(\\w*)\\s*(<|>|=|>=|<=)\\s*(\\w*|\\d*\\.\\d*)\\s*{\")\nelseif_sent = re.compile(\"}\\s*else if\\s*([A-z])\\s*(<=|>=|>|<|=)\\s*([A-z]+|[0-9]+)\\s*{\")\nelse_sent= re.compile(\"}\\s*else\\s*{\")\nend_while = end_func = end_if = re.compile(\"}\")\nretorno_var_val = re.compile(\"return\\s(\\w*)\\s*;\")\nretorno_opsc = re.compile(\"return\\s(\\w*|\\d*)\\s*(\\+|\\-)\\s(\\w*|\\d*)\\s*;\")\nretorno_ci = re.compile(\"return\\s(\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*(\\+|\\-)\\s*(\\w*))\\s*;\")\nretorno_cd = re.compile(\"return\\s(\\w*)\\s*(\\+|\\-)\\s\\((\\w*)\\s*as\\s*(i16|i32|f64)\\)\\s*;\")\nretorno_dc = re.compile(\"return\\s\\((\\w+)\\s*as\\s*(i16|i32|f64)\\)\\s*(\\+|\\-)\\s*\\((\\w*)+\\sas\\s*(i16|i32|f64)\\)\\s*;\")\nfunc = re.compile(\"fn\\s*(\\w*)\\((\\w*)\\s*:\\s*(i16|i32|f64)+\\)\\s*->\\s*(i16|i32|f64)\\s*{\")\nfunc_main = re.compile(\"fn main\\(\\)\\s*{\")\nprint_ln = re.compile(\"println!\\s*\\((\\w+)\\);\")\n\n\"\"\"\nif_exec_static(line,lista,VARS): Ejecuta los ifs dentro de las funciones.\nInputs:\n(string): Linea que lee del archivo.\n(lista): Lista con todas las sentencias del if.\n(diccionario): Diccionario con las variables del ambito.\n..\nOutputs:\n(diccionario): Diccionario varibles actualizado.\n(lista): Lista con sentencias hasta donde se ejecuto.\n\"\"\"\n\n\ndef if_exec_static(line,lista,VARS):\n\tif tuple == type(VARS):\n\t\tVARS = VARS[0]\n\tllaves_abiertas = 1\n\tCOND = False\n\tobj = if_sent.match(line)\n\tif obj and not COND:\n\t\tboolean = bool(obj.group(1),obj.group(2),obj.group(3),VARS)\n\t\tif boolean:\n\t\t\tCOND == True\n\t\t\twhile len(lista) > 0:\n\t\t\t\tlista.pop(0)\n\t\t\t\tprint(lista)\n\t\t\t\tline = lista[0]\n\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\tline = line.strip(\"\\t\")\n\t\t\t\ta = identifier(line)\n\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\tbreak\n\t\t\t\tif a == SENT:\n\t\t\t\t\tlista.pop(0)\n\t\t\t\t\tVARS = sentence(line,VARS)\n\t\t\t\tif a == IF:\n\t\t\t\t\tVARS,lista = if_exec_static(line,lista,VARS)\n\t\t\t\tif a == WHILE:\n\t\t\t\t\tlista_while = while_list_static(line,lista)\n\t\t\t\t\tVARS,lista = exe_while_static(lista_while,lista,VARS)\n\t\t\t\tif a == END:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\t\tlista.pop(0)\n\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\tbreak\n\t\telse:\n\t\t\tlista.pop(0)\n\t\t\twhile len(lista) > 0:\n\t\t\t\tline = lista[0]\n\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\tline = line.strip(\"\\t\")\n\t\t\t\ta = identifier(line)\n\t\t\t\tprint(llaves_abiertas)\n\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\tbreak\n\t\t\t\tif \"{\" in line and a == END:\n\t\t\t\t\tlista.pop(0)\n\t\t\t\telif \"{\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas + 1\n\t\t\t\t\tlista.pop(0)\n\t\t\t\telif a == END:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\t\tlista.pop(0)\n\t\t\t\telse:\n\t\t\t\t\tlista.pop(0)\n\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\tbreak\n\t\n\tobj = elseif_sent.match(line)\n\tif obj and not COND:\n\t\tboolean = bool(obj.group(1),obj.group(2),obj.group(3),VARS)\n\t\tif boolean:\n\t\t\tCOND == True\n\t\t\twhile len(lista) > 0:\n\t\t\t\tline = lista[0]\n\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\tline = line.strip(\"\\t\")\n\t\t\t\ta = identifier(line)\n\t\t\t\tif a == SENT:\n\t\t\t\t\tVARS = sentence(line,VARS)\n\t\t\t\t\tlista.pop(0)\n\t\t\t\tif a == IF:\n\t\t\t\t\tVARS,lista = if_exec_static(line,lista,VARS)\n\t\t\t\tif a == WHILE:\n\t\t\t\t\tlista_while = while_list_static(line,lista)\n\t\t\t\t\tVARS,lista = exe_while_static(lista_while,lista,VARS)\n\t\t\t\tif a == END:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\t\tlista.pop(0)\n\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\tbreak\n\t\telse:\n\t\t\twhile len(lista) > 0:\n\t\t\t\tline = lista[0]\n\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\tline = line.strip(\"\\t\")\n\t\t\t\ta = identifier(line)\n\t\t\t\tif \"{\" in line and a == END:\n\t\t\t\t\tlista.pop(0)\n\t\t\t\telif \"{\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas + 1\n\t\t\t\t\tlista.pop(0)\n\t\t\t\telif a == END:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\t\tlista.pop(0)\n\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\tbreak\n\t\t\n\tobj = else_sent.match(line)\n\tif obj and not COND:\n\t\twhile len(lista) > 0:\n\t\t\tline = lista[0]\n\t\t\tline = line.strip(\"\\n\")\n\t\t\tline = line.strip(\"\\t\")\n\t\t\ta = identifier(line)\n\t\t\tif a == SENT:\n\t\t\t\tVARS = sentence(line,VARS)\n\t\t\t\tlista.pop(0)\n\t\t\tif a == IF:\n\t\t\t\tVARS,lista = if_exec_static(line,lista,VARS)\n\t\t\tif a == WHILE:\n\t\t\t\tlista_while = while_list_static(line,lista)\n\t\t\t\tVARS,lista = exe_while(lista_while,lista,VARS)\n\t\t\tif a == END:\n\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\tlista.pop(0)\n\t\t\tif llaves_abiertas == 0:\n\t\t\t\tbreak\n\treturn VARS,lista\n\"\"\"\nwhile_list_static(line,lista) : Crea una lista con las sentencias del while.\nInputs:\n(string): Linea del archivo.\n(list): Lista sentencias de la funcion.\n..\nOutputs:\n(list): Lista con las sentencias del while.\n\"\"\"\ndef while_list_static(line,lista):\n\tobj = while_sent.match(line)\n\tvar1 = obj.group(1)\n\tcond = obj.group(2)\n\tvar2 = obj.group(3)\n\tlista_while = list()\n\tlista_while.append((var1,cond,var2))\n\tllaves_abiertas = 1\n\tprint(\"______________________________\")\n\tprint(\"Creando Lista\",lista_while)\n\tprint(\"______________________________\")\n\tlista.pop(0)\n\twhile llaves_abiertas > 0:\n\t\tprint(\"Creando Lista\",lista_while)\n\t\tline = lista[0]\n\t\tline = line.strip(\"\\n\")\n\t\tline = line.strip(\"\\t\")\n\t\ta = identifier(line)\n\t\tif line == \"\":\n\t\t\tlista.pop(0)\n\t\t\tcontinue\n\t\tif \"}\" in line and \"{\" in line:\n\t\t\tlista.pop(0)\n\t\t\tlista_while.append(line)\n\t\telif \"}\" in line:\n\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\tlista.pop(0)\n\t\t\tlista_while.append(line)\n\t\telif \"{\" in line:\n\t\t\tllaves_abiertas = llaves_abiertas + 1\n\t\t\tlista_while.append(line)\n\t\telse:\n\t\t\tlista.pop(0)\n\t\t\tlista_while.append(line)\n\t\tif llaves_abiertas == 0:\n\t\t\tbreak\n\tprint(\"______________________________\")\n\tprint(\"Lista Creada\",lista_while)\n\tprint(\"______________________________\")\n\treturn lista_while\n\n\"\"\"\nexe_while_static(lista_while,lista,VARS) : Ejecuta el ciclo while dentro de la funcion.\nInputs:\n(list): Lista con las sentencias del while.\n(list): Lista de sentencias por leer de la funcion.\n(dict): Diccionaro con las variables del ambito.\n..\nOutputs:\n(list): Lista con las sentencias que faltan por leer de la funcion.\n(var): Diccionario con las variables actualizadas.\n\"\"\"\ndef exe_while_static(lista_while,lista,VARS):\n\tif tuple == type(VARS):\n\t\tVARS = VARS[0]\n\tFlag = bool(lista_while[0][0],lista_while[0][1],lista_while[0][2],VARS)\n\tprint(\"While a ejecutar --> \",lista)\n\twhile Flag:\n\t\tlista2 = lista\n\t\tprint(\"Inicio ciclo while\")\n\t\tprint(VARS, \"-->\")\n\t\tfor line in lista_while[1:]:\n\t\t\tline = line.strip(\"\\n\")\n\t\t\tline = line.strip(\"\\t\")\n\t\t\tprint(lista_while)\n\t\t\ta = identifier(line)\n\t\t\tif a == SENT:\n\t\t\t\tprint(\"While - Sentencia\")\n\t\t\t\tVARS = sentence(line,VARS)\n\t\t\telif a == IF:\n\t\t\t\tprint(\"While - If\")\n\t\t\t\tVARS,lista2 = if_exec_static(line,lista2,VARS)\n\t\t\telif a == WHILE:\n\t\t\t\tlista_while = while_list_static(line,lista)\n\t\t\t\tVARS,lista = exe_while_static(lista_while,lista,VARS)\n\t\tprint(\"-->\",VARS)\n\t\tprint(\"Final ciclo while\")\n\t\tFlag = bool(lista_while[0][0],lista_while[0][1],lista_while[0][2],VARS)\n\t\tif Flag == False:\n\t\t\tbreak\n\treturn VARS,lista\n\n\"\"\"\ndef exe_while(lista_while,fp,VARS): Ejecuta el ciclo while dentro del main.\nInputs:\n(list): Lista con la sentencias del while.\n(file obj): Archivo que se esta leyendo.\n(dict): Diccionario con las variables del ambito.\n..\nOutputs:\n(dict): Diccionario varibles actualizadas.\n\"\"\"\n\ndef exe_while(lista_while,fp,VARS):\n\tif tuple == type(VARS):\n\t\tVARS = VARS[0]\n\tprint(\"-------------- Entrando While --------------------\")\n\tprint(\"Lista While -> \",lista_while)\n\tFlag = bool(lista_while[0][0],lista_while[0][1],lista_while[0][2],VARS)\n\ti = 1\n\twhile Flag:\n\t\tprint(\"----------------------\")\n\t\tlista_aux = lista_while[1:]\n\t\tprint(\"Ciclo n: \",i)\n\t\tllaves = 1\n\t\twhile len(lista_aux) > 0:\n\t\t\tline = lista_aux[0]\n\t\t\tline = line.strip(\"\\n\")\n\t\t\tline = line.strip(\"\\t\")\n\t\t\tprint(line)\n\t\t\ta = identifier(line)\n\t\t\tif a == SENT:\n\t\t\t\tVARS = sentence(line,VARS)\n\t\t\t\tlista_aux.pop(0)\n\t\t\t\tprint(VARS)\n\t\t\telif a == IF:\n\t\t\t\tVARS = if_exec(line,fp,VARS)\n\t\t\t\tprint(VARS)\n\t\t\telif a == WHILE:\n\t\t\t\tprint(line)\n\t\t\t\tlista_while2 = while_list_static(line,lista_aux)\n\t\t\t\tVARS = exe_while_static(lista_while2,lista_aux,VARS)\n\t\t\telif \"}\" in line:\n\t\t\t\tllaves = llaves - 1\n\t\t\t\tif llaves == 0:\n\t\t\t\t\tbreak\n\t\tprint(lista_while)\n\t\tFlag = bool(lista_while[0][0],lista_while[0][1],lista_while[0][2],VARS)\n\t\tif Flag == False:\n\t\t\tbreak\n\t\ti = i + 1\n\t\tprint(\"----------------------\")\n\tprint(\"-------------- Saliendo While --------------------\")\n\treturn VARS\n\n\"\"\"\nbool(var,cond,var2,VARS): Evalua si es verdadero o falso la expresion.\nInputs:\n(string): Variable.\n(string): Variable o valor.\n(dict): Diccinario de las variables del ambito.\n..\nOutputs:\n(boolean): False si no se cumple.\n(boolean): True si se cumple.\n\"\"\"\ndef bool(var,cond,var2,VARS):\n\tif var2.isdigit():\n\t\tvar = get_val_value(var,VARS)\n\t\tvar2 = int(var2)\n\telif isfloat(var2):\n\t\tvar = get_val_value(var,VARS)\n\t\tvar2 = float(var2)\n\telif compar_types(var,var2,VARS) == True:\n\t\tvar = get_val_value(var,VARS)\n\t\tvar2 = get_val_value(var2,VARS)\n\telse:\n\t\tprint(\"Error Tipo\")\n\t\texit(1)\n\tif cond == \"<\":\n\t\treturn var < var2\n\telif cond == \">\":\n\t\treturn var > var2\n\telif cond == \"=\":\n\t\treturn var == var2\n\telif cond == \">=\":\n\t\treturn var >= var2\n\telif cond == \"<=\":\n\t\treturn var <= var2\n\telse:\n\t\tprint(\"Error de Sintaxis\")\n\t\texit(1)\n\"\"\"\nprintln(line,VARS): Imprime el valor y el tipo de la varible.\nInputs:\n(string) Linea donde este el print.\n(dict) Diccionario con las variables del ambito.\n..\nOutputs:\n(string): Mensaje con el valor y tipo.\n\n\"\"\"\ndef println(line,VARS):\n\tobj = print_ln.match(line)\n\tvar = obj.group(1)\n\tvalor = get_val_value(var,VARS)\n\ttype_var = VARS[var][1]\n\tprint(\"El valor es: \"+str(valor)+\". Su tipo es: \"+type_var)\n\n\"\"\"\nstore_fun(line,fp): Guarda las funciones en un diccionario.\nInputs:\n(str): Linea que se esta leyendo.\n(file obj): Archivo que se esta leyendo.\n..\nOutputs:\n(None): Si es la funcion main.\n(True): Si hace la operacion con exito.\n\n\"\"\"\ndef store_fun(line,fp):\n\tobj = func_main.match(line)\n\tif obj:\n\t\treturn None\n\tobj = func.match(line)\n\tname_func = obj.group(1)\n\tvar_func = obj.group(2)\n\ttype_in = obj.group(3)\n\ttype_out = obj.group(4)\n\tllaves_abiertas = 1\n\tFunciones[name_func] = [(var_func,type_in,type_out)]\n\tfor line in fp:\n\t\tline = line.strip(\"\\n\")\n\t\tline = line.strip(\"\\t\")\n\t\ta = identifier(line)\n\t\tif llaves_abiertas <= 0:\n\t\t\tbreak\n\t\tif \"}\" in line:\n\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\tif \"{\" in line:\n\t\t\tllaves_abiertas = llaves_abiertas + 1\n\t\tFunciones[name_func].append(line)\n\treturn True\n\"\"\"\nwhile_list(line,fp) : Guarda el ciclo while en una lista.\nInputs:\n(str): Linea que se esta leyendo.\n(file obj): Archivo que se esta leyendo.\n..\nOutputs:\n(list): Lista con las sentencias del while.\n\n\"\"\"\ndef while_list(line,fp):\n\tobj = while_sent.match(line)\n\tvar1 = obj.group(1)\n\tcond = obj.group(2)\n\tvar2 = obj.group(3)\n\tlista = list()\n\tlista.append((var1,cond,var2))\n\tllaves_abiertas = 1\n\tfor line in fp:\n\t\tline = line.strip(\"\\n\")\n\t\tline = line.strip(\"\\t\")\n\t\tprint(\"Linea lista: \",line)\n\t\ta = identifier(line)\n\t\tlista.append(line)\n\t\tif llaves_abiertas == 0:\n\t\t\tbreak\n\t\tif line == \"\":\n\t\t\tcontinue\n\t\tif \"}\" in line:\n\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\tif \"{\" in line:\n\t\t\tllaves_abiertas = llaves_abiertas + 1\n\t\tif llaves_abiertas == 0:\n\t\t\tbreak\n\treturn lista\n\"\"\"\nif_exec(line,fp,VARS) : Ejecuta el if dentro del main.\nInputs:\n(str): Linea que se esta leyendo.\n(file obj): Archivo que se esta leyendo.\n(dict): Diccionario con las variables del ambito.\n..\nOutputs:\n(dict): Diccionario con las variables actualizadas.\n\n\"\"\"\ndef if_exec(line,fp,VARS):\n\tprint(\"-------------- Entrando If --------------\")\n\tprint(line)\n\tllaves_abiertas = 1\n\tCOND = True\n\tobj = if_sent.match(line)\n\tif obj and COND:\n\t\tprint(\"Match con IF\")\n\t\tboolean = bool(obj.group(1),obj.group(2),obj.group(3),VARS)\n\t\tif boolean:\n\t\t\tprint(\"If condicion cumplida\")\n\t\t\tCOND = False\n\t\t\tfor line in fp:\n\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\tline = line.strip(\"\\t\")\n\t\t\t\tprint (line)\n\t\t\t\ta = identifier(line)\n\t\t\t\tif a == IF:\n\t\t\t\t\tVARS = if_exec(line,fp,VARS)\n\t\t\t\tif a == WHILE:\n\t\t\t\t\tlista_while = while_list(line,fp)\n\t\t\t\t\tVARS = exe_while(lista_while,fp,VARS)\n\t\t\t\tif a == SENT:\n\t\t\t\t\tVARS = sentence(line,VARS)\n\t\t\t\tif \"}\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\tif \"{\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas + 1\n\t\telse:\n\t\t\tprint(\"If condicion NO cumplida\")\n\t\t\tfor line in fp:\n\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\tline = line.strip(\"\\t\")\n\t\t\t\tprint (line)\n\t\t\t\ta = identifier(line)\n\t\t\t\tif \"}\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\tif \"{\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas + 1\n\tobj = elseif_sent.match(line)\n\tif obj:\n\t\tprint(\"Match con ELSE IF\")\n\t\tboolean = bool(obj.group(1),obj.group(2),obj.group(3),VARS)\n\t\tif boolean and COND:\n\t\t\tprint(\"ELSE If condicion cumplida\")\n\t\t\tCOND = False\n\t\t\tllaves_abiertas = 1\n\t\t\tfor line in fp:\n\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\tline = line.strip(\"\\t\")\n\t\t\t\tprint (line)\n\t\t\t\ta = identifier(line)\n\t\t\t\tif a == IF:\n\t\t\t\t\tVARS = if_exec(line,fp,VARS)\n\t\t\t\tif a == WHILE:\n\t\t\t\t\tlista_while = while_list(line,fp)\n\t\t\t\t\tVARS = exe_while(lista_while,fp,VARS)\n\t\t\t\tif a == SENT:\n\t\t\t\t\tVARS = sentence(line,VARS)\n\t\t\t\tif \"}\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\tif \"{\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas + 1\n\t\telse:\n\t\t\tprint(\"ELSE IF condicion NO cumplida\")\n\t\t\tfor line in fp:\n\t\t\t\tllaves_abiertas = 1\n\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\tline = line.strip(\"\\t\")\n\t\t\t\tprint (line)\n\t\t\t\ta = identifier(line)\n\t\t\t\tif \"}\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\tif \"{\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas + 1\n\tobj = else_sent.match(line)\n\tif obj:\n\t\tif COND:\n\t\t\tllaves_abiertas = 1\n\t\t\tprint(\"Condicion ELSE Entra\")\n\t\t\tfor line in fp:\n\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\tline = line.strip(\"\\t\")\n\t\t\t\tprint (line)\n\t\t\t\ta = identifier(line)\n\t\t\t\tif a == IF:\n\t\t\t\t\tVARS = if_exec(line,fp,VARS)\n\t\t\t\tif a == WHILE:\n\t\t\t\t\tlista_while = while_list(line,fp)\n\t\t\t\t\tVARS = exe_while(lista_while,fp,VARS)\n\t\t\t\tif a == SENT:\n\t\t\t\t\tVARS = sentence(line,VARS)\n\t\t\t\tif \"}\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\tif \"{\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas + 1\n\t\telse:\n\t\t\tprint(\"ELSE Saltado\")\n\t\t\tfor line in fp:\n\t\t\t\tllaves_abiertas = 1\n\t\t\t\tline = line.strip(\"\\n\")\n\t\t\t\tline = line.strip(\"\\t\")\n\t\t\t\tprint (line)\n\t\t\t\ta = identifier(line)\n\t\t\t\tif \"}\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas - 1\n\t\t\t\t\tif llaves_abiertas == 0:\n\t\t\t\t\t\tbreak\n\t\t\t\tif \"{\" in line:\n\t\t\t\t\tllaves_abiertas = llaves_abiertas + 1\n\tprint(\"-------------- Saliendo If --------------\")\n\treturn VARS\n\"\"\"\nsentence(line,VARS) : Evalua la sintaxis y ejecuta las linas que recibe.\nInputs:\n(str): Linea que se esta leyendo.\n(file obj): Archivo que se esta leyendo.\n\nOutputs:\n(dict): Diccionario con las variables actualizadas.\n(systemExit): Salida en el caso de haber error.\n\n\"\"\"\ndef sentence(line,VARS):\n\tline = line.strip(\"\\t\")\n\tline = line.strip(\"\\n\")\n\tobj = sent_op.match(line)\n\tif (obj):\n\t\tprint(VARS)\n\t\tif tuple == type(VARS):\n\t\t\tVARS = VARS[0]\n\t\tif obj.group(1) in VARS.keys():\n\t\t\tvar = obj.group(2)\n\t\t\top = obj.group(3)\n\t\t\tvar2 = obj.group(4)\n\t\t\tif var.isdigit() and var2.isdigit():\n\t\t\t\tif op == \"+\":\n\t\t\t\t\tVARS[obj.group(1)][0] = str(int(var) + int(var2))\n\t\t\t\t\treturn VARS\n\t\t\t\telif op == \"-\":\n\t\t\t\t\tVARS[obj.group(1)][0] = str(int(var) - int(var2))\n\t\t\t\t\treturn VARS\n\t\t\telif var.isdigit():\n\t\t\t\tif not compar_types(obj.group(1),var2,VARS):\n\t\t\t\t\tprint(\"Error de tipos\")\n\t\t\t\t\treturn exit(1)\n\t\t\t\tvar2 = get_val_value(var2,VARS)\n\t\t\t\tif op == \"+\":\n\t\t\t\t\tVARS[obj.group(1)][0] = str(int(var) + var2)\n\t\t\t\t\treturn VARS\n\t\t\t\telse:\n\t\t\t\t\tVARS[obj.group(1)][0] = str(int(var) - var2)\n\t\t\t\t\treturn VARS\n\t\t\telif var2.isdigit():\n\t\t\t\tif compar_types(obj.group(1),var,VARS):\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Error de tipos\")\n\t\t\t\t\treturn exit(1)\n\t\t\t\tvar = get_val_value(var,VARS)\n\t\t\t\tif op == \"+\":\n\t\t\t\t\tVARS[obj.group(1)][0] = str(var + int(var2))\n\t\t\t\t\treturn VARS\n\t\t\t\telse:\n\t\t\t\t\tVARS[obj.group(1)][0] = str(var - int(var2))\n\t\t\t\t\treturn VARS\n\t\t\telse:\n\t\t\t\tif not compar_types(var,var2,VARS):\n\t\t\t\t\tprint(\"Error de tipos\")\n\t\t\t\t\treturn exit(1)\n\t\t\t\tif not compar_types(obj.group(1),var,VARS):\n\t\t\t\t\tprint(\"Error de tipos\")\n\t\t\t\t\treturn exit(1)\n\t\t\t\tvar = get_val_value(var,VARS)\n\t\t\t\tvar2 = get_val_value(var2,VARS)\n\t\t\t\tif op == \"+\":\n\t\t\t\t\tVARS[obj.group(1)][0] = str(var + var2)\n\t\t\t\t\treturn VARS\n\t\t\t\telse:\n\t\t\t\t\tVARS[obj.group(1)][0] = str(var - var2)\n\t\t\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Variable \"+obj.group(1)+\" no declarada\")\n\t\t\treturn exit(1)\n\n\tobj = sent_val.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tval = obj.group(2)\n\t\tif var not in VARS.keys():\n\t\t\tprint(\"Variable \"+var+\" no definida\")\n\t\t\treturn exit(1)\n\t\tVARS[var][0] = val\n\t\treturn VARS\n\n\tobj = sent_var.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tvar2 = obj.group(2)\n\t\tif var in VARS.keys() and var2 in VARS.keys():\n\t\t\tif compar_types(var,var2):\n\t\t\t\tVARS[var][0] = get_val_value(var2)\n\t\t\telse:\n\t\t\t\tprint(\"Error de Tipo\")\n\t\t\t\treturn exit(1)\n\t\telse:\n\t\t\tprint(\"Variable o variables no definidas\")\n\t\n\tobj = sent_op_cast.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tvar2 = obj.group(2)\n\t\tcast = obj.group(3)\n\t\tif var not in VARS.keys():\n\t\t\tprint(\"Variable \"+var+\" no definida\")\n\t\t\treturn exit(1)\n\t\tif cast == VARS[var][1]:\n\t\t\tVARS[var][0] = var2\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\treturn exit(1)\n\n\tobj = sent_op_valcastd.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tvar2 = obj.group(2)\n\t\top = obj.group(3)\n\t\tvar3 = obj.group(4)\n\t\tcast = obj.group(5)\n\t\tif var2.isdigit():\n\t\t\tif cast == VARS[var][1]:\n\t\t\t\tif op == \"+\":\n\t\t\t\t\tVARS[var][0] = str(int(VARS[var3][0]) + int(var2))\n\t\t\t\t\treturn VARS\n\t\t\t\telse:\n\t\t\t\t\tVARS[var][0] = str(int(var2) - int(var3))\n\t\t\t\t\treturn VARS\n\t\tif cast == VARS[var2][1] and cast == VARS[var][1]:\n\t\t\tif op == \"+\":\n\t\t\t\tVARS[var][0] = str(int(VARS[var3][0]) + int(VARS[var2][0]))\n\t\t\t\treturn VARS\n\t\t\telse:\n\t\t\t\tVARS[var][0] = str(int(VARS[var2][0]) - int(var3))\n\t\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\treturn exit(1)\n\n\tobj = sent_op_valcasti.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tvar2 = obj.group(2)\n\t\tcast = obj.group(3)\n\t\top = obj.group(4)\n\t\tvar3 = obj.group(5)\n\t\tif var3.isdigit():\n\t\t\tif cast == VARS[var][1]:\n\t\t\t\tif op == \"+\":\n\t\t\t\t\tVARS[var][0] = str(int(VARS[var2][0]) + int(var3))\n\t\t\t\t\treturn VARS\n\t\t\t\telse:\n\t\t\t\t\tVARS[var][0] = str(int(VARS[var2][0]) - int(var3))\n\t\t\t\t\treturn VARS\n\t\t\telse:\n\t\t\t\tprint(\"Error de Tipo\")\n\t\t\t\texit(1)\n\t\tif cast == VARS[var][1] and cast == VARS[var3][1]:\n\t\t\tif op == \"+\":\n\t\t\t\tVARS[var][0] = str(int(VARS[var3][0]) + int(VARS[var2][0]))\n\t\t\t\treturn VARS\n\t\t\telse:\n\t\t\t\tVARS[var][0] = str(int(VARS[var2][0]) - int(VARS[var3][0]))\n\t\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\treturn exit(1)\n\tobj = sent_op_doublecast.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tvar1 = obj.group(2)\n\t\tcast1 = obj.group(3)\n\t\top = obj.group(4)\n\t\tvar2 = obj.group(5)\n\t\tcast2 = obj.group(6)\n\t\tif(cast1 == cast2):\n\t\t\tif cast1 in [\"i16\",\"i32\"] and \"f64\" in VARS[var1]:\n\t\t\t\tvar1 = float_to_int(var1,VARS)\n\t\t\tif cast2 in [\"i16\",\"i32\"] and VARS[var2][1] == \"f64\":\n\t\t\t\tvar2 = float_to_int(var2,VARS)\n\t\t\tif cast1 == \"f64\" and VARS[var1][1] in [\"i16\",\"i32\"]:\n\t\t\t\tvar1 = int_to_float(var1,VARS)\n\t\t\tif cast2 == \"f64\" and VARS[var2][1] in [\"i16\",\"i32\"]:\n\t\t\t\tvar2 = int_to_float(var2,VARS)\n\t\t\tif VARS[var][1] == cast1:\n\t\t\t\tif cast1 == \"f64\" and op == \"+\":\n\t\t\t\t\tVARS[var][0] = str(float(var1) + float(var2))\n\t\t\t\tif cast1 == \"f64\" and op == \"-\":\n\t\t\t\t\tVARS[var][0] = str(float(var1) - float(var2))\n\t\t\t\tif cast1 in [\"i16\",\"i32\"] and op == \"+\":\n\t\t\t\t\tVARS[var][0] = str(int(VARS[var1][0]) + int(VARS[var2][0]))\n\t\t\t\tif cast1 in [\"i16\",\"i32\"] and op == \"-\":\n\t\t\t\t\tVARS[var][0] = str(int(VARS[var1][0]) - int(VARS[var2][0]))\n\t\t\telse:\n\t\t\t\tprint(\"Error de Tipo\")\n\t\t\t\treturn exit(1)\n\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\treturn exit(1)\n\tobj = sent_func.match(line)\n\tif obj:\n\t\tvar = obj.group(1)\n\t\tfunc = obj.group(2)\n\t\tvar2 = obj.group(3)\n\t\tprint(VARS[var][1],Funciones[func][0][2])\n\t\tif VARS[var][1] == Funciones[func][0][2]:\n\t\t\tVARS[var][0] = exe_func(func,var2,VARS)\n\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\texit(1)\n\tobj = op_func_de.match(line)\n\tif obj:\n\t\tprint(\"MATCH\")\n\t\tvar = obj.group(1)\n\t\tvar2 = obj.group(2)\n\t\top = obj.group(3)\n\t\tfunc = obj.group(4)\n\t\tvar3 = obj.group(5)\n\t\tprint(var,var2,op,func,var3)\n\t\tprint(VARS[var][1],Funciones[func][0][2])\n\t\tif VARS[var][1] == Funciones[func][0][2]:\n\t\t\tprint(var2,func,var3)\n\t\t\taux = exe_func(func,var3,VARS)\n\t\t\tprint(aux)\n\t\t\tprint(var,var2,func,var3,aux)\n\t\t\tVARS[var][0] = operation(var2+\" \"+op+\" \"+aux[0]+\";\",VARS)\n\t\t\tprint(VARS)\n\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\texit(1)\n\tobj = op_func_iz.match(line)\n\tif obj:\n\t\tvar = obj.group(1)\n\t\tfun = obj.group(2)\n\t\tvar2 = obj.group(3)\n\t\top = obj.group(4)\n\t\tvar3 = obj.group(5)\n\t\tif VARS[var][1] == Funciones[func][2]:\n\t\t\taux = exe_func(func,var2,VARS)\n\t\t\tVARS[var][0] = operation(aux+op+var3,VARS)\n\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\texit(1)\n\tobj = op_func_do.match(line)\n\tif obj:\n\t\tvar = obj.group(1)\n\t\tfun1 = obj.group(2)\n\t\tvar1 = obj.group(3)\n\t\top = obj.group(4)\n\t\tvar2 = obj.group(5)\n\t\tfunc2 = obj.group(6)\n\t\tif VARS[var][1] == Funciones[func1][2]:\n\t\t\taux1 = exe_func(func1,var1,VARS)\n\t\t\taux2 = exe_func(func2,var2,VARS)\n\t\t\tVARS[var][0] = operation(aux1+op+aux2,VARS)\n\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\texit(1)\n\tif line == \"\":\n\t\tprint(\"Linea en Blanco, pasando ...\")\n\t\treturn VARS\n\tprint(\"no se encontro nada\")\n\texit(1)\n\"\"\"\nfloat_to_int(var,VARS) : Cambia el string de float a entero.\nInputs:\n(str): Variable que se va a modificar.\n(dict): Diccinario con las variables del ambito.\n\n..\nOutputs:\n(string): Valor modificado.\n\n\"\"\"\ndef float_to_int(var,VARS):\n\tvar = VARS[var][0].split(\".\")[0]\n\treturn var\n\"\"\"\nint_to_float(var,VARS) : Cambia el string de entero a float.\nInputs:\n(str): Variable que se va a modificar.\n(dict): Diccinario con las variables del ambito.\n\n..\nOutputs:\n(string): Valor modificado.\n\n\"\"\"\ndef int_to_float(var,VARS):\n\tvar = VARS[var][0]+\".0\"\n\treturn var\n\"\"\"\ndeclaration(line,VARS) : Declara las variables que se van a utilizar.\nInputs:\n(str: Linea que esta leyendo del archivo.\n(dict): Diccionario con las variables del ambito.\n..\nOutputs:\n(systemExit): Salida en caso de error.\n(dict): Diccionario con las variables actualizadas.\n\n\"\"\"\ndef declaration(line,VARS):\n\tobj = var_val.search(line)\n\tif(obj):\n\t\tvar = obj.group(1)\n\t\ttipo = obj.group(2) \n\t\tvar2 = obj.group(3)\n\t\tif isfloat(var2) and tipo in [\"i16\",\"i32\"]:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\texit(1)\n\t\telse:\n\t\t\tVARS[var] = [var2,tipo]\n\t\t\t\n\t\treturn VARS\n\tobj = var_var.search(line)\n\tif(obj):\n\t\tvar = obj.group(1)\n\t\ttipo = obj.group(2) \n\t\tvar2 = obj.group(3)\n\t\tif VARS[var2][1] == tipo:\n\t\t\tVARS[var] = [VARS[var2][0],tipo]\n\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\texit(1)\n\tobj = var_op.search(line)\n\tif obj:\n\t\tvar = obj.group(1)\n\t\ttipo = obj.group(2)\n\t\tvar2 = obj.group(3)\n\t\top = obj.group(4)\n\t\tvar3 = obj.group(5)\n\t\tsent = var2+op+var3+\";\"\n\t\tif (var2.isdigit() or isfloat(var2)) and (obj.group(5).isdigit() or isfloat(obj.group(5))):\n\t\t\tVARS[var] = [operation(sent,VARS),tipo]\n\t\t\treturn VARS\n\t\telif (var2.isdigit() or isfloat(var2)):\n\t\t\tif VARS[var3][1] == tipo:\n\t\t\t\tVARS[var] = [operation(sent,VARS),tipo]\n\t\t\t\treturn VARS\n\t\t\telse:\n\t\t\t\tprint(\"Error Tipo\")\n\t\t\t\texit(1)\n\t\telif (var3.isdigit() or isfloat(var3)):\n\t\t\tif VARS[var2][1] == tipo:\n\t\t\t\tVARS[var] = [operation(sent,VARS),tipo]\n\t\t\t\treturn VARS\n\t\t\telse:\n\t\t\t\tprint(\"Error Tipo\")\n\t\t\t\texit(1)\n\t\telif compar_types(obj.group(3),obj.group(5),VARS):\n\t\t\tif get_val_type(obj.group(3),VARS) in [\"i32\",\"i16\"]:\n\t\t\t\tif tipo == VARS[var2][1]:\n\t\t\t\t\tvalor = operation(var2+op+var3+\";\",VARS)\n\t\t\t\t\tVARS = up_val(obj.group(1),valor,obj.group(2),VARS)\n\t\t\t\t\treturn VARS\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Error Tipo\")\n\t\t\t\t\texit(1)\n\t\t\telif VARS[obj.group(3)][1]==\"f64\" and VARS[obj.group(3)][1]==\"f64\":\n\t\t\t\tvalor = operation(var2+op+var3+\";\",VARS)\n\t\t\t\tVARS = up_val(obj.group(1),valor,obj.group(2),VARS)\n\t\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Error de tipo\")\n\t\t\texit(1)\n\tobj = var_op_cast.match(line)\n\tprint(line)\n\tif obj:\n\t\tvar = obj.group(1)\n\t\ttipo = obj.group(2)\n\t\tvar2 = obj.group(3)\n\t\tcast = obj.group(4)\n\t\tif cast == tipo:\n\t\t\tVARS[var] = [VARS[var2][0],tipo]\n\t\t\treturn VARS\n\tobj = var_op_cast_cast.search(line)\n\tif obj:\n\t\tif compar_types(obj.group(3),obj.group(6)):\n\t\t\tif get_val_type(obj.group(3)) == (\"i32\" or \"i16\"):\n\t\t\t\tvalor = ops[obj.group(5)](int(float(get_val_value(obj.group(3)))),int(float(get_val_value(obj.group(6)))))\n\t\t\t\tVARS = up_val(obj.group(1),valor,obj.group(2),VARS)\n\t\t\t\treturn VARS\n\t\t\telse:\n\t\t\t\tvalor = ops[obj.group(5)](float(get_val_value(obj.group(3))),float(get_val_value(obj.group(6))))\n\t\t\t\tVARS = up_val(obj.group(1),valor,obj.group(2),VARS)\n\t\t\t\treturn VARS\n\t\telse:\n\t\t\tprint(\"Error de tipo\")\t\n\tobj = var_op_valcasti.search(line)\n\tif obj:\n\t\tobj = sent_op_valcastd.search(line)\n\tobj = var_func.match(line)\n\tif obj:\n\t\tvar = obj.group(1)\n\t\ttipo = obj.group(2)\n\t\tfunc = obj.group(3)\n\t\tvar2 = obj.group(4)\n\t\tVARS[var] = [exe_func(func,var2,VARS),tipo]\n\t\treturn VARS\n\n\tprint(\"No Definido\")\n\texit(1)\n\"\"\"\nup_val(var,valor,tipo,VARS): Agrega una variable al diccionario.\nInputs:\n(string): Variable que se va a agregar.\n(string): Valor de la variable.\n(string): Tipo de la variable.\n..\nOutputs:\n(dict): Diccionaro con las variables actualizadas.\n\n\"\"\"\ndef up_val(var,valor,tipo,VARS):\n\tif tuple == type(VARS):\n\t\tVARS = VARS[0]\n\tVARS[var] = [valor,tipo]\n\treturn VARS\n\"\"\"\ncompar_types(var1,var2,VARS) : Compara el tipo de dos variables.\nInputs:\n(string): Primera variable.\n(string): Segunda variable.\n(dict): Diccionario con las variables del ambito.\n..\nOutputs:\n(systemExit): Salida en el caso de error.\n(boolean): En el caso que se sean iguales.\n\n\"\"\"\ndef compar_types(var1,var2,VARS): \n\tif VARS[var1][1] == VARS[var2][1]:\n\t\treturn True\n\telse:\n\t\tprint(\"Error de tipo\")\n\t\treturn exit(1)\n\"\"\"\ncast(var,tipo,VARS) : Cambia el tipo de la variable en el caso de ser necesario.\n\nInputs:\n(string): Variable que se va a castear.\n(string): Tipo al que se va a cambiar.\n(dict): Diccionario con las variables del ambito.\n..\nOutputs:\n(systemExit): Salida en caso de error.\n(dict): Diccionario con las variables actualizadas.\n\"\"\"\ndef cast(var,tipo,VARS): \n\tif var not in VARS.keys():\n\t\treturn exit(1)\n\tVARS[var][1] = tipo\n\"\"\"\nget_val_type(var,VARS) : Obtiene el tipo de la variable.\nInputs:\n(string): Variable que se desea saber el tipo.\n(dict): Diccionario con las variables del ambito.\n..\nOutputs:\n(dict): Diccionario con las variables actualizadas.\n\n\"\"\"\ndef get_val_type(var,VARS):\n\tif tuple == type(VARS):\n\t\tVARS = VARS[0]\n\treturn VARS[var][1]\n\"\"\"\nget_val_value(var,VARS) : Obtiene el valor de la variable.\nInputs:\n(string): Variable que se desea saber el valor.\n(dict): Diccionario con las variables del ambito.\n..\nOutputs:\n(dict): Diccionario con las variables actualizadas.\n\n\"\"\"\ndef get_val_value(var,VARS):\n\tif tuple == type(VARS):\n\t\tVARS = VARS[0]\n\tif var.isdigit():\n\t\treturn int(VARS[var][0])\n\telse:\n\t\treturn float(VARS[var][0])\n\"\"\"\noperation(line,VARS): Ejecuta la operacion de la linea que lee.\nInputs:\n(string): Linea que se lee del archivo.\n(dict): Diccionario con las variables del ambito.\n..\nOutputs:\n(str): Resultado despues de la operacion.\n\n\"\"\"\ndef operation(line,VARS):\n\tif tuple == type(VARS):\n\t\tVARS = VARS[0]\n\tobj = op_sc.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\top = obj.group(2)\n\t\tvar2 = obj.group(3)\n\t\tif (var.isdigit() or isfloat(var)) and (var2.isdigit() or isfloat(var2)):\n\t\t\tif op == \"+\":\n\t\t\t\treturn str(float(var) + float(var2))\n\t\t\telse:\n\t\t\t\treturn str(float(var) - float(var2))\n\t\telif var.isdigit() or isfloat(var):\n\t\t\tif VARS[var2][1] in [\"i16\",\"i32\"]:\n\t\t\t\tif op == \"+\":\n\t\t\t\t\treturn str(int(var) + int(VARS[var2][0]))\n\t\t\t\telse:\n\t\t\t\t\treturn str(int(var) - int(VARS[var2][0]))\n\t\t\telse:\n\t\t\t\tif op == \"+\":\n\t\t\t\t\treturn str(float(var) + float(VARS[var2][0]))\n\t\t\t\telse:\n\t\t\t\t\treturn str(float(var) - float(VARS[var2][0]))\n\t\telif var2.isdigit() or isfloat(var):\n\t\t\tif VARS[var][1] in [\"i16\",\"i32\"]:\n\t\t\t\tif op == \"+\":\n\t\t\t\t\treturn str(int(var2) + int(VARS[var][0]))\n\t\t\t\tif op == \"-\":\n\t\t\t\t\treturn str(int(VARS[var][0]) - int(var2))\n\t\t\telse:\n\t\t\t\tif op == \"+\":\n\t\t\t\t\treturn str(float(var2) + float(VARS[var][0]))\n\t\t\t\tif op == \"-\":\n\t\t\t\t\treturn str(float(VARS[var][0]) - float(var2))\n\t\telif var in VARS.keys() and var2 in VARS.keys():\n\t\t\tif compar_types(var,var2,VARS):\n\t\t\t\tif VARS[var][1] in [\"i16\",\"i32\"] and VARS[var2][1] in [\"i16\",\"i32\"]:\n\t\t\t\t\tif op == \"+\":\n\t\t\t\t\t\treturn str(int(VARS[var][0]) + int(VARS[var2][0]))\n\t\t\t\t\tif op == \"-\":\n\t\t\t\t\t\treturn str(int(VARS[var][0]) - int(VARS[var2][0]))\n\t\t\t\telif VARS[var][1] == \"f64\" and VARS[var2][1] == \"f64\":\n\t\t\t\t\tif op == \"+\":\n\t\t\t\t\t\treturn str(float(VARS[var][0]) + float(VARS[var2][0]))\n\t\t\t\t\tif op == \"-\":\n\t\t\t\t\t\treturn str(float(VARS[var][0]) - float(VARS[var2][0]))\n\t\t\telse:\n\t\t\t\tprint(\"Error de Tipos\")\n\t\t\t\texit(1)\n\n\t\telse:\n\t\t\tprint(\"Variable \"+var+\" o \"+var2+\" no declarada\")\n\t\t\treturn exit(1)\n\n\tobj = sent_func.match(line)\n\tif (obj): # Falta La funcion que ejecuta las funciones para llamarla aca\n\t\tvar = obj.group(1)\n\t\tfunc = obj.group(2)\n\t\tvar2 = obj.group(3)\n\t\tval = exe_func(func,var2,VARS)\n\t\tif VARS[var][1] == Funciones[func][0][2]:\n\t\t\tVARS[val][0] = val\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\texit(1)\n\tobj = sent_var.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tvar2 = obj.group(2)\n\t\tif var in VARS.keys() and var2 in VARS.keys():\n\t\t\tif compar_types(var,var2):\n\t\t\t\treturn var2\n\t\t\telse:\n\t\t\t\tprint(\"Error de Tipo\")\n\t\t\t\treturn exit(1)\n\t\telse:\n\t\t\tprint(\"Variable o variables no definidas\")\n\t\n\tobj = sent_val.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tval = obj.group(2)\n\t\tif var not in VARS.keys():\n\t\t\tprint(\"Variable \"+var+\" no definida\")\n\t\t\treturn exit(1)\n\t\treturn val\n\t\n\tobj = sent_op_cast.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tvar2 = obj.group(2)\n\t\tcast = obj.group(3)\n\t\tif var not in VARS.keys():\n\t\t\tprint(\"Variable \"+var+\" no definida\")\n\t\t\treturn exit(1)\n\t\tif cast == VARS[var][1]:\n\t\t\treturn var2\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\treturn exit(1)\n\n\tobj = sent_op_valcastd.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tvar2 = obj.group(2)\n\t\top = obj.group(3)\n\t\tvar3 = obj.group(4)\n\t\tcast = obj.group(5)\n\t\tif var2.isdigit():\n\t\t\tif cast == VARS[var][1]:\n\t\t\t\tif op == \"+\":\n\t\t\t\t\treturn str(int(VARS[var3][0]) + int(var2))\n\t\t\t\telse:\n\t\t\t\t\treturn str(int(var2) - int(var3))\n\t\tif cast == VARS[var2][1] and cast == VARS[var][1]:\n\t\t\tif op == \"+\":\n\t\t\t\treturn str(int(VARS[var3][0]) + int(VARS[var2][0]))\n\t\t\telse:\n\t\t\t\treturn str(int(VARS[var2][0]) - int(var3))\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\treturn exit(1)\n\n\tobj = sent_op_valcasti.match(line)\n\tif (obj):\n\t\tvar = obj.group(1)\n\t\tvar2 = obj.group(2)\n\t\tcast = obj.group(3)\n\t\top = obj.group(4)\n\t\tvar3 = obj.group(5)\n\t\tif var3.isdigit():\n\t\t\tif cast == VARS[var][1]:\n\t\t\t\tif op == \"+\":\n\t\t\t\t\treturn str(int(VARS[var2][0]) + int(var3))\n\t\t\t\telse:\n\t\t\t\t\treturn str(int(VARS[var2][0]) - int(var3))\n\t\tif cast == VARS[var][1]:\n\t\t\tif op == \"+\":\n\t\t\t\treturn str(int(VARS[var3][0]) + int(VARS[var2][0]))\n\t\t\telse:\n\t\t\t\treturn str(int(VARS[var2][0]) - int(VARS[var3][0]))\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\treturn exit(1)\n\t\n\tobj = retorno_opsc.match(line)\n\tif (obj):\n\t\tif obj.group(1) in VARS.keys():\n\t\t\tvar = obj.group(1)\n\t\t\top = obj.group(2)\n\t\t\tvar2 = obj.group(3)\n\t\t\tif var.isdigit() and var2.isdigit():\n\t\t\t\tif op == \"+\":\n\t\t\t\t\treturn str(int(var) + int(var2))\n\t\t\t\telif op == \"-\":\n\t\t\t\t\treturn str(int(var) - int(var2))\n\t\t\telif var.isdigit():\n\t\t\t\tif not compar_types(obj.group(1),var2):\n\t\t\t\t\tprint(\"Error de tipos\")\n\t\t\t\t\treturn exit(1)\n\t\t\t\tvar2 = get_val_value(var2,VARS)\n\t\t\t\tif op == \"+\":\n\t\t\t\t\treturn str(int(var) + var2)\n\t\t\t\telse:\n\t\t\t\t\treturn str(int(var) - var2)\n\t\t\telif var2.isdigit():\n\t\t\t\tif compar_types(obj.group(1),var,VARS) == False:\n\t\t\t\t\tprint(\"Error de tipos\")\n\t\t\t\t\treturn exit(1)\n\t\t\t\tvar = get_val_value(var,VARS)\n\t\t\t\tif op == \"+\":\n\t\t\t\t\treturn str(var + int(var2))\n\t\t\t\telse:\n\t\t\t\t\treturn str(var - int(var2))\n\t\t\telse:\n\t\t\t\tif compar_types(var,var2,VARS) == False:\n\t\t\t\t\tprint(\"Error de tipos\")\n\t\t\t\t\treturn exit(1)\n\t\t\t\tif compar_types(obj.group(1),var,VARS) == False:\n\t\t\t\t\tprint(\"Error de tipos\")\n\t\t\t\t\treturn exit(1)\n\t\t\t\tvar = get_val_value(var,VARS)\n\t\t\t\tvar2 = get_val_value(var2,VARS)\n\t\t\t\tif op == \"+\":\n\t\t\t\t\treturn str(var + var2)\n\t\t\t\telse:\n\t\t\t\t\treturn str(var - var2)\n\t\telse:\n\t\t\tprint(\"Variable \"+obj.group(1)+\" no declarada\")\n\t\t\treturn exit(1)\n\n\n\tobj = retorno_dc.match(line)\n\tif (obj):\n\t\tvar1 = obj.group(1)\n\t\tcast1 = obj.group(2)\n\t\top = obj.group(3)\n\t\tvar2 = obj.group(4)\n\t\tcast2 = obj.group(5)\n\t\tif(cast1 == cast2):\n\t\t\tif cast1 in [\"i16\",\"i32\"] and VARS[var1][1] == \"f64\":\n\t\t\t\tvar1 = float_to_int(var1,VARS)\n\t\t\tif cast2 in [\"i16\",\"i32\"] and VARS[var2][1] == \"f64\":\n\t\t\t\tvar2 = float_to_int(var2,VARS)\n\t\t\tif cast1 == \"f64\" and VARS[var1][1] in [\"i16\",\"i32\"]:\n\t\t\t\tvar1 = int_to_float(var1,VARS)\n\t\t\tif cast2 == \"f64\" and VARS[var2][1] in [\"i16\",\"i32\"]:\n\t\t\t\tvar2 = int_to_float(var2,VARS)\n\t\t\tif VARS[var][1] == cast1:\n\t\t\t\tif cast1 == \"f64\" and op == \"+\":\n\t\t\t\t\treturn str(float(var1) + float(var2))\n\t\t\t\tif cast1 == \"f64\" and op == \"-\":\n\t\t\t\t\treturn str(float(var1) - float(var2))\n\t\t\t\tif cast1 [\"i16\",\"i32\"] and op == \"+\":\n\t\t\t\t\treturn str(int(var1) + int(var2))\n\t\t\t\tif cast1 [\"i16\",\"i32\"] and op == \"-\":\n\t\t\t\t\treturn str(int(var1) - int(var2))\n\t\t\telse:\n\t\t\t\tprint(\"Error de Tipo\")\n\t\t\t\texit(1)\n\t\telse:\n\t\t\tprint(\"Error de Tipo\")\n\t\t\texit(1)\n\tprint(\"Error de Sintaxis --> \",line)\n\texit(1)\n\n\"\"\"\nidentifier(line) : Identifica que es lo que se esta intentando hacer.\nInputs:\n(string): Linea que se esta leyendo.\n..\nOutputs:\n(string): Token de la operacion.\n\n\"\"\"\ndef identifier(line):\n\tif LET in line:\n\t\treturn LET\n\telif WHILE in line:\n\t\treturn WHILE\n\telif ELSE_IF in line:\n\t\treturn ELSE_IF\n\telif IF in line:\n\t\treturn IF\n\telif ELSE in line:\n\t\treturn ELSE\n\telif RETURN in line:\n\t\treturn RETURN\n\telif FN in line:\n\t\treturn FN\n\telif END in line:\n\t\treturn END\n\telif PRINT in line:\n\t\treturn PRINT\n\telse:\n\t\treturn SENT\n\"\"\"\nisfloat(a) : Verifica si el valor es flotante o no.\nInputs:\n(str): Valor que se desea verificar.\n..\nOutputs:\n(boolean): Si es flotante es verdadedo.\n(boolean): Si no es flotante es falso.\n\n\"\"\"\ndef isfloat(a):\n\tif \".\" in a:\n\t\treturn True\n\telse:\n\t\treturn False\n\"\"\"\nexe_func(nombre,val,VARS) : Ejecuta la funcion y hace el retorno.\nInputs:\n(string): Nombre de la funcion.\n(string): Parametro de la funcion.\n(dict): Diccionario con las variables del ambito.\n..\nOutputs:\n(string): Valor de retorno.\n\n\"\"\"\ndef exe_func(nombre,val,VARS):\n\tif tuple == type(VARS):\n\t\tVARS = VARS[0]\n\tlista = Funciones[nombre][1:]\n\tif val.isdigit():\n\t\tVARS_Local = dict()\n\t\tVARS_Local[Funciones[nombre][0][0]] = [val,Funciones[nombre][0][1]]\n\telif isfloat(val):\n\t\tVARS_Local = dict()\n\t\tVARS_Local[Funciones[nombre][0][0]] = [val,Funciones[nombre][0][1]]\n\telif val in VARS.keys():\n\t\tVARS_Local = dict()\n\t\tVARS_Local[Funciones[nombre][0][0]] = [VARS[val][0],Funciones[nombre][0][1]]\n\twhile len(lista) > 0:\n\t\tline = lista[0]\n\t\tprint(lista)\n\t\tprint(VARS_Local)\n\t\tline = line.strip(\"\\n\")\n\t\tline = line.strip(\"\\t\")\n\t\ta = identifier(line)\n\t\tif a == WHILE:\n\t\t\tlista_while = while_list_static(line,lista)\n\t\t\tVARS_Local,lista = exe_while_static(lista_while,lista,VARS_Local)\n\t\telif a == IF:\n\t\t\tVARS_Local,lista = if_exec_static(line,lista,VARS_Local)\n\t\telif a == SENT:\n\t\t\tVARS_Local = sentence(line,VARS_Local)\n\t\t\tlista.pop(0)\n\t\telif a == RETURN:\n\t\t\treturn ret_fun(line,Funciones[nombre][0][1],VARS_Local)\n\n\"\"\"\nret_fun(line,tipo,VARS) : Evalua la sentencia en el retorno de la funcion.\nInputs:\n(string): Linea que se evalua el retorno.\n(string): Tipo que debe retornar.\n(dict): Diccionario con las variables del ambito.\n..\nOutputs:\n(string): Valor de retorno.\n\n\"\"\"\ndef ret_fun(line,tipo,VARS):\n\tobj = retorno_var_val.match(line)\n\tif obj:\n\t\tvar = obj.group(1)\n\t\tif var.isdigit():\n\t\t\treturn var\n\t\telse:\n\t\t\tvar = VARS[var]\n\t\t\treturn var\n\tobj = retorno_opsc.match(line)\n\tif obj:\n\t\treturn operation(line,VARS)\n\tobj = retorno_cd\n\tif obj:\n\t\treturn operation(line,VARS)\n\tobj = retorno_ci\n\tif obj:\n\t\treturn operation(line,VARS)\n\tobj = retorno_dc\n\tif obj:\n\t\treturn operation(line,VARS)\n\n\"\"\"\nmain() : Ejecuta las demas funciones dependiendo que lee en el archivo.\nInputs:\n(None): No recibe parametro.\n..\nOutputs:\n(None): No retorna parametro.\n\n\"\"\"\ndef main():\n\tfp = open(\"codigo_rust2.txt\",\"r\")\n\t\n\tDIC = dict()\n\tfor line in fp:\n\t\tline = line.strip(\"\\n\")\n\t\tline = line.strip(\"\\t\")\n\t\tprint(line)\n\t\ta = identifier(line)\n\t\tif a == FN:\n\t\t\tstore_fun(line,fp)\n\t\t\tprint(\"Evaluando funcion\")\n\t\telif a == WHILE:\n\t\t\tprint(\"Evaluando while\")\n\t\t\tlista = while_list(line,fp)\n\t\t\texe_while(lista,fp,DIC)\n\t\telif a == IF:\n\t\t\tprint(\"Evaluando if\")\n\t\t\tDIC= if_exec(line,fp,DIC)\n\t\telif a == LET:\n\t\t\tprint(\"Declarando: \",line)\n\t\t\tDIC = declaration(line,DIC)\n\t\t\tprint(DIC)\n\t\telif a == SENT:\n\t\t\tprint(\"Sentenciando: \",line)\n\t\t\tDIC = sentence(line,DIC)\n\t\telif a == PRINT:\n\t\t\tprintln(line,DIC)\n\t\telse:\n\t\t\tcontinue\n\tprint(\"Termino del Archivo\\n\\n\")\n\tprint(\"Funciones -> \",Funciones,\"\\n\")\n\tprint(\"Variables en Main -> \",DIC)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"inter3.py","file_name":"inter3.py","file_ext":"py","file_size_in_byte":39169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"631367125","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 24 14:19:00 2018\n\n@author: fangyucheng\n\"\"\"\n\nimport os\nimport re\nimport asyncio\nimport time\nimport copy\nimport requests\nimport datetime\nimport aiohttp\nimport urllib\n\ntry:\n from crawler_sys.framework.func_get_releaser_id import *\nexcept:\n from func_get_releaser_id import *\nfrom bs4 import BeautifulSoup\nfrom multiprocessing import Pool\nfrom multiprocessing import Process\nfrom crawler.crawler_sys.framework.video_fields_std import Std_fields_video\nfrom crawler.crawler_sys.utils.output_results import retry_get_url\nfrom crawler.crawler_sys.utils.output_results import output_result\nfrom crawler.crawler_sys.utils.trans_str_play_count_to_int import trans_play_count\nfrom crawler.crawler_sys.utils.trans_strtime_to_timestamp import trans_strtime_to_timestamp\nfrom crawler.crawler_sys.utils.trans_duration_str_to_second import trans_duration\nfrom crawler.crawler_sys.utils import connect_with_redis\nfrom crawler.crawler_sys.utils.util_logging import logged\nfrom crawler.crawler_sys.proxy_pool.func_get_proxy_form_kuaidaili import get_proxy\n\n\n#\n# logging = output_log(page_category='crawler',\n# program_info='tudou',)\n\nclass Crawler_tudou():\n\n def __init__(self, timeout=None, platform='new_tudou'):\n if timeout == None:\n self.timeout = 10\n else:\n self.timeout = timeout\n self.platform = platform\n self.TotalVideo_num = None\n self.midstepurl = None\n std_fields = Std_fields_video()\n self.video_data = std_fields.video_data\n self.video_data['platform'] = self.platform\n unused_key_list = ['channel', 'describe', 'repost_count', 'isOriginal']\n for key in unused_key_list:\n self.video_data.pop(key)\n self.list_page_url_lst = [\n \"http://www.tudou.com/api/getfeeds?secCateId=10016&utdid=T8v9EQPOimUCAXL%2FAz0YrDOB&page_size=24\",\n \"http://www.tudou.com/api/getfeeds?secCateId=10195&utdid=XA2EFIGslWoCAWp4y3KXcZh7&page_size=24\",\n \"http://www.tudou.com/api/getfeeds?secCateId=622736331&utdid=XA2EFIGslWoCAWp4y3KXcZh7&page_size=24\",\n \"http://www.tudou.com/api/getfeeds?secCateId=622769673&utdid=XA2EFIGslWoCAWp4y3KXcZh7&page_size=24\",\n \"http://www.tudou.com/api/getfeeds?secCateId=10116&utdid=XA2EFIGslWoCAWp4y3KXcZh7&page_size=24\",\n \"http://www.tudou.com/api/getfeeds?secCateId=622621940&utdid=XA2EFIGslWoCAWp4y3KXcZh7&page_size=24\",\n \"http://www.tudou.com/api/getfeeds?secCateId=10198&utdid=XA2EFIGslWoCAWp4y3KXcZh7&page_size=24\",\n \"http://www.tudou.com/api/getfeeds?secCateId=622336449&utdid=XA2EFIGslWoCAWp4y3KXcZh7&page_size=24\",\n \"http://www.tudou.com/api/getfeeds?secCateId=10051&utdid=XA2EFIGslWoCAWp4y3KXcZh7&page_size=24\"]\n\n def video_page(self, url):\n video_info = copy.deepcopy(self.video_data)\n get_page = requests.get(url, timeout=3)\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n try:\n video_info['title'] = soup.find('h1', {'class': 'td-playbase__title'}).span.text\n except:\n video_info['title'] = None\n try:\n video_info['releaser'] = soup.find('a', {'class': 'td-play__userinfo__name'}).text\n except:\n video_info['releaser'] = None\n try:\n midsteptime = soup.find('div', {'class':\n 'td-play__videoinfo__details-box__time'}).text[:-2]\n video_info['release_time'] = int(datetime.datetime.strptime(midsteptime,\n '%Y-%m-%d %H:%M:%S').timestamp() * 1e3)\n except:\n video_info['release_time'] = None\n try:\n video_info['releaserUrl'] = soup.find(\"a\", {\"class\": \"td-play__userinfo__name\"})['href']\n video_info['releaser_id_str'] = \"new_tudou_%s\" % (self.get_releaser_id(video_info['releaserUrl']))\n except:\n video_info['releaserUrl'] = None\n try:\n find_play_count = ' '.join(re.findall('total_vv.*stripe_bottom', page))\n replace_comma_pcnt = find_play_count.replace(',', '')\n play_count_str = ' '.join(re.findall('total_vv\":\"\\d+', replace_comma_pcnt))\n video_info['play_count'] = int(' '.join(re.findall('\\d+', play_count_str)))\n except:\n video_info['play_count'] = 0\n try:\n find_comment_count = ' '.join(re.findall('total_comment.*recommend', page))\n replace_comma_ccnt = find_comment_count.replace(',', '')\n comment_count_str = ' '.join(re.findall('total_comment\":\"\\d+', replace_comma_ccnt))\n video_info['comment_count'] = int(' '.join(re.findall('\\d+', comment_count_str)))\n except:\n video_info['comment_count'] = 0\n try:\n find_dura = re.findall('stripe_bottom\":\"\\d+:\\d+', page)\n dura_str = ' '.join(find_dura).split('\":\"')[-1]\n video_info['duration'] = trans_duration(dura_str)\n except:\n video_info['duration'] = 0\n video_info['fetch_time'] = int(datetime.datetime.now().timestamp() * 1e3)\n video_info['url'] = url\n print(\"get video data at %s\" % url)\n return video_info\n\n def search_page(self, keyword, search_pages_max=30,\n output_to_es_raw=False,\n output_to_es_register=False,\n es_index=None,\n doc_type=None):\n search_data_Lst = []\n headers = {\n \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"accept-language\": \"zh,zh-CN;q=0.9\",\n \"cookie\": \"SOKUSESSID=1553755022290AhL; cna=2U8aFb1yaVcCAdr3nSX3f47K; _uab_collina=155799409092003127272852; __ayft=1579161875253; __aysid=1579161875253Zl2; __ayscnt=1; P_ck_ctl=5A18564922916D48652E056B1E408EDE; SK_QUERY=%5B%7B%22q%22%3A%22%25E6%2587%2582%25E8%25BD%25A6%25E8%2580%2581%25E5%25BC%25A0%22%7D%2C%7B%22q%22%3A%22%25E5%25B0%258F%25E9%25B9%258F%22%7D%5D; JSESSIONID=57F80DCADD926955C8B91971B5334C42; __arpvid=1579162484198LNMIn3-1579162484216; __aypstp=8; __ayspstp=8; isg=BBQUwi2xNucxPqDWRI5_X4Eo5VKGbThX3kr36q707x8ombXj13kz5f1fnZkBYXCv\",\n \"referer\": \"https://www.soku.com/nt/search/q_%E6%87%82%E8%BD%A6%E8%80%81%E5%BC%A0_orderby_2_limitdate_0?spm=a2h0k.8191414.0.0&site=14&_lg=10&page=2\",\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 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.87 Safari/537.36\",\n }\n url = ('https://www.soku.com/nt/search/q_'\n + keyword\n + '_orderby_2_limitdate_0?&spm=a2h0k.8191414.0.0&site=14&_lg=10&page={}'\n .format(str(i)) for i in range(1, search_pages_max + 1))\n for urls in url:\n print(urls)\n get_page = requests.get(urls, headers=headers)\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n potato = soup.find_all(\"div\", {\"class\": \"v\"})\n for data_line in potato:\n dura = data_line.find(\"span\", {\"class\": \"v-time\"}).text\n duration_str = dura\n dl = duration_str.split(':')\n dl_int = []\n for v in dl:\n v = int(v)\n dl_int.append(v)\n if len(dl_int) == 2:\n duration = dl_int[0] * 60 + dl_int[1]\n else:\n duration = dl_int[0] * 3660 + dl_int[1] * 60 + dl_int[2]\n url = data_line.find('div', {'class': 'v-meta-title'}).a['href']\n url = 'http:' + url\n one_video_dic = self.video_page(url)\n one_video_dic['url'] = url\n one_video_dic['duration'] = duration\n one_video_dic['search_word'] = keyword\n search_data_Lst.append(one_video_dic)\n print('get page done')\n\n if len(search_data_Lst) >= 100:\n output_result(result_Lst=search_data_Lst,\n platform=self.platform,\n output_to_es_raw=output_to_es_raw,\n output_to_es_register=output_to_es_register,\n es_index=es_index,\n doc_type=doc_type)\n search_data_Lst.clear()\n\n if search_data_Lst != []:\n output_result(result_Lst=search_data_Lst,\n platform=self.platform,\n output_to_es_raw=output_to_es_raw,\n output_to_es_register=output_to_es_register,\n es_index=es_index,\n doc_type=doc_type)\n\n return search_data_Lst\n\n def process_one_video(self, line):\n video_info = copy.deepcopy(self.video_data)\n try:\n video_info['title'] = line.find('a', {'target': 'video'})['title']\n except:\n video_info['title'] = None\n try:\n url = line.find('a', {'target': 'video'})['href']\n video_info['url'] = 'https:' + url\n except:\n video_info['url'] = None\n try:\n play_count_str = line.find('span', {'class': 'v-num'}).text\n video_info['play_count'] = trans_play_count(play_count_str)\n except:\n video_info['play_count'] = 0\n # logging.warning(\"can't get play_count at page %s\" % video_info['url'])\n try:\n release_time_str = line.find('span', {'class': 'v-publishtime'}).text\n video_info['release_time'] = trans_strtime_to_timestamp(input_time=release_time_str,\n missing_year=True)\n except:\n release_time_str = 0\n # logging.warning(\"can't get release_time at page %s\" % video_info['url'])\n try:\n dura_str = line.find('span', {'class': 'v-time'}).text\n video_info['duration'] = trans_duration(dura_str)\n except:\n video_info['duration'] = 0\n # logging.warning(\"can't get duration at page %s\" % video_info['url'])\n fetch_time = int(time.time() * 1e3)\n video_info['fetch_time'] = fetch_time\n return video_info\n\n def get_releaser_id(self, releaserUrl):\n return get_releaser_id(platform=self.platform, releaserUrl=releaserUrl)\n\n def releaser_page_via_pc(self, releaserUrl,\n output_to_file=False,\n filepath=None,\n releaser_page_num_max=1000,\n output_to_es_raw=False,\n output_to_es_register=False,\n push_to_redis=False,\n es_index=None,\n doc_type=None):\n \"\"\"\n input releaserUrl must be strict as https://id.tudou.com/i/UMjc5MzI5NDA==/videos?\n end with /videos otherwise when scrolling it will make mistakes\n \"\"\"\n releaser_id = self.get_releaser_id(releaserUrl)\n print(\"working on releaser: %s\" % releaser_id)\n releaserUrl = 'https://id.tudou.com/i/%s/videos' % releaser_id\n result_lst = []\n get_page = retry_get_url(releaserUrl)\n get_page.encoding = 'utf-8'\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n try:\n releaser = soup.find('div', {'class': 'user-name'}).a.text\n except:\n releaser = None\n try:\n total_video_num_str = soup.find('div', {'class': 'title'}).span.text\n total_video_num = total_video_num_str.replace('(', '').replace(')', '').replace(',', '')\n total_video_num = trans_play_count(total_video_num)\n except:\n print(releaserUrl)\n if total_video_num % 50 == 0:\n total_page_num = int(total_video_num / 50)\n else:\n total_page_num = int(total_video_num / 50) + 1\n if releaser_page_num_max > total_page_num:\n releaser_page_num_max = total_page_num\n print(\"releaser page num max is %s\" % releaser_page_num_max)\n video_lst = soup.find_all('div', {'class': 'v'})\n for line in video_lst:\n video_info = self.process_one_video(line)\n video_info['releaserUrl'] = releaserUrl\n video_info['releaser'] = releaser\n result_lst.append(video_info)\n if releaser_page_num_max >= 2:\n page_num = 2\n try:\n partial_releaserUrl = soup.find('li', {'class': 'next'}).a['href']\n new_releaserUrl = 'https://id.tudou.com%s' % partial_releaserUrl\n except:\n print(new_releaserUrl)\n while page_num <= releaser_page_num_max:\n get_page = retry_get_url(new_releaserUrl)\n get_page.encoding = 'utf-8'\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n if page_num != releaser_page_num_max:\n try:\n new_releaserUrl = 'https://id.tudou.com' + soup.find('li', {'class': 'next'}).a['href']\n except:\n new_releaserUrl = ('https://id.tudou.com/i/%s/videos?order=1&page=%s' % (releaser_id, page_num))\n video_lst = soup.find_all('div', {'class': 'v'})\n for line in video_lst:\n video_info = self.process_one_video(line)\n video_info['releaserUrl'] = releaserUrl\n video_info['releaser'] = releaser\n result_lst.append(video_info)\n print('get page %s list length is %s' % (page_num, len(result_lst)))\n page_num += 1\n output_result(result_Lst=result_lst,\n platform=self.platform,\n output_to_file=output_to_file,\n filepath=filepath,\n output_to_es_raw=output_to_es_raw,\n es_index=es_index,\n doc_type=doc_type,\n output_to_es_register=output_to_es_register,\n push_to_redis=push_to_redis)\n result_lst.clear()\n if result_lst != []:\n output_result(result_Lst=result_lst,\n platform=self.platform,\n output_to_file=output_to_file,\n filepath=filepath,\n output_to_es_raw=output_to_es_raw,\n output_to_es_register=output_to_es_register,\n push_to_redis=push_to_redis,\n es_index=es_index,\n doc_type=doc_type)\n\n def get_releaser_follower_num(self, releaserUrl):\n get_page = requests.get(releaserUrl, timeout=3)\n get_page.encoding = 'utf-8'\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n try:\n follower_str = soup.find('li', {'class': 'snum'}).em.text\n follower_num = trans_play_count(follower_str)\n print('%s follower number is %s' % (releaserUrl, follower_num))\n releaser_img = self.get_releaser_image(data=soup)\n return follower_num, releaser_img\n except:\n print(\"can't can followers\")\n\n def get_releaser_page(self,releaserUrl):\n get_page = requests.get(releaserUrl, timeout=3)\n get_page.encoding = 'utf-8'\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n try:\n follower_str = soup.find('li', {'class': 'snum'}).em.text\n follower_num = trans_play_count(follower_str)\n print('%s follower number is %s' % (releaserUrl, follower_num))\n signature = soup.find('div', {'class': 'user-desc'}).div.span.text\n try:\n signature_type = soup.find('div', {'class': 'user-name'}).a.next_sibling[\"title\"]\n except:\n signature_type = \"\"\n dic = {\n \"signature\":signature,\n \"follower_num\":follower_num,\n \"signature_type\":signature_type,\n }\n print(dic)\n return dic\n except:\n print(\"can't find followers\")\n return None\n\n\n def releaser_video_sum(self, releaserUrl):\n get_page = retry_get_url(releaserUrl)\n get_page.encoding = 'utf-8'\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n total_video_num_str = soup.find('div', {'class': 'title'}).span.text\n total_video_num = total_video_num_str.replace('(', '').replace(')', '').replace(',', '')\n total_video_num = trans_play_count(total_video_num)\n return total_video_num\n\n def start_list_page(self, task_list,\n retry_times=20):\n url_lst = []\n count = 0\n while count < retry_times:\n count += 1\n for list_url in task_list:\n get_page = requests.get(list_url)\n try:\n video_lst = get_page.json()\n except:\n continue\n else:\n for video_dic in video_lst:\n video_id = video_dic['codeId']\n url = 'http://video.tudou.com/v/%s.html' % video_id\n url_lst.append(url)\n print('push %s video url into redis set' % len(url_lst))\n connect_with_redis.push_video_url_to_redis_set(platform=self.platform, url_lst=url_lst)\n\n async def download_html(self, session, url):\n get_page = await session.get(url)\n page = await get_page.text(\"utf-8\", errors=\"ignore\")\n return url + \"fangyuchenggoalkeeper\" + page\n\n async def get_video_page(self, loop, task_lst):\n async with aiohttp.ClientSession() as session:\n video_page = [loop.create_task(self.download_html(session, url))\n for url in task_lst]\n done, pending = await asyncio.wait(video_page)\n download_video_page_lst = [d.result() for d in done]\n connect_with_redis.push_video_page_html_to_redis(platform=self.platform,\n result_lst=download_video_page_lst)\n\n def download_video_page_async(self):\n task_lst = connect_with_redis.retrieve_video_url_from_redis_set(platform=self.platform)\n loop = asyncio.get_event_loop()\n loop.run_until_complete(self.get_video_page(loop, task_lst))\n\n def download_video_page_async_single_process(self):\n key = 'new_tudou_video_url'\n pid = os.getpid()\n while connect_with_redis.length_of_set(key) > 0:\n self.download_video_page_async()\n print(\"platform: %s, action: download video page, pid: %s\"\n % (self.platform, pid))\n\n def download_video_page_async_multi_process(self, process_num=10):\n pool = Pool(processes=process_num)\n for line in range(process_num):\n pool.apply_async(self.download_video_page_async_single_process)\n pool.close()\n pool.join()\n\n def parse_video_page_html(self, html):\n page_lst = html.split('fangyuchenggoalkeeper')\n url = page_lst[0]\n page = page_lst[1]\n soup = BeautifulSoup(page, 'html.parser')\n try:\n title = soup.find('h1', {'class': 'td-playbase__title'}).span.text\n except:\n title = None\n try:\n releaser = soup.find('a', {'class': 'td-play__userinfo__name'}).text\n except:\n releaser = None\n try:\n midsteptime = soup.find('div', {'class':\n 'td-play__videoinfo__details-box__time'}).text[:-2]\n release_time = int(datetime.datetime.strptime(midsteptime,\n '%Y-%m-%d %H:%M:%S').timestamp() * 1e3)\n except:\n release_time = None\n try:\n releaserUrl = soup.find(\"a\", {\"class\": \"td-play__userinfo__name\"})['href']\n except:\n releaserUrl = None\n try:\n find_play_count = ' '.join(re.findall('total_vv.*stripe_bottom', page))\n replace_comma = find_play_count.replace(',', '')\n play_count_str = ' '.join(re.findall('total_vv\":\"\\d+', replace_comma))\n play_count = int(' '.join(re.findall('\\d+', play_count_str)))\n except:\n play_count = 0\n try:\n find_dura = re.findall('stripe_bottom\":\"\\d+:\\d+', page)\n dura_str = ' '.join(find_dura).split('\":\"')[-1]\n duration = trans_duration(dura_str)\n except:\n duration = 0\n fetch_time = int(time.time() * 1e3)\n info_dic = {'platform': self.platform,\n \"title\": title,\n 'url': url,\n 'duration': duration,\n \"releaser\": releaser,\n \"release_time\": release_time,\n \"releaserUrl\": releaserUrl,\n 'play_count': play_count,\n 'fetch_time': fetch_time}\n return info_dic\n\n def parse_video_page_single_process(self,\n output_to_file=False,\n filepath=None,\n push_to_redis=False,\n output_to_es_raw=False,\n es_index=None,\n doc_type=None,\n output_to_es_register=False):\n error_url_list = []\n pid = os.getpid()\n key = 'new_tudou_video_page_html'\n result_lst = []\n while connect_with_redis.length_of_lst(key) > 0:\n video_page_html = connect_with_redis.retrieve_video_page_html_from_redis(platform=self.platform)\n video_info = self.parse_video_page_html(video_page_html)\n try:\n video_info['title']\n except:\n continue\n if video_info['title'] is not None:\n result_lst.append(video_info)\n print(\"platform: %s, action: parse video page, process_id: %s,\"\n \"count number: %s\" % (self.platform, pid, len(result_lst)))\n if len(result_lst) >= 1000:\n output_result(result_Lst=result_lst,\n platform=self.platform,\n output_to_file=output_to_file,\n filepath=filepath,\n push_to_redis=push_to_redis,\n output_to_es_raw=output_to_es_raw,\n es_index=es_index,\n doc_type=doc_type,\n output_to_es_register=output_to_es_register)\n result_lst.clear()\n else:\n try:\n error_url_list.append(video_info['url'])\n except:\n pass\n if result_lst != []:\n output_result(result_Lst=result_lst,\n platform=self.platform,\n output_to_file=output_to_file,\n filepath=filepath,\n push_to_redis=push_to_redis,\n output_to_es_raw=output_to_es_raw,\n es_index=es_index,\n doc_type=doc_type,\n output_to_es_register=output_to_es_register)\n if error_url_list != []:\n connect_with_redis.push_video_url_to_redis_set(platform=self.platform,\n url_lst=error_url_list)\n\n def parse_video_page_multi_process(self,\n para_dict,\n process_num=30):\n pool = Pool(processes=process_num)\n for line in range(process_num):\n pool.apply_async(self.parse_video_page_single_process, kwds=para_dict)\n pool.close()\n pool.join()\n\n def key_customer(self, releaserUrl,\n releaser_page_num_max=1000,\n output_to_es_raw=False,\n es_index='crawler-data-raw',\n doc_type='doc'):\n \"\"\"\n input releaserUrl must be strict as https://id.tudou.com/i/UMjc5MzI5NDA==/videos?\n end with /videos otherwise when scrolling it will make mistakes\n \"\"\"\n releaser_id = self.get_releaser_id(releaserUrl)\n print(\"working on releaser: %s\" % releaser_id)\n releaserUrl = 'https://id.tudou.com/i/%s/videos' % releaser_id\n result_lst = []\n get_page = retry_get_url(releaserUrl)\n get_page.encoding = 'utf-8'\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n try:\n releaser = soup.find('div', {'class': 'user-name'}).a.text\n except:\n releaser = None\n try:\n total_video_num_str = soup.find('div', {'class': 'title'}).span.text\n total_video_num = total_video_num_str.replace('(', '').replace(')', '').replace(',', '')\n total_video_num = trans_play_count(total_video_num)\n except:\n print(releaserUrl)\n if total_video_num % 50 == 0:\n total_page_num = int(total_video_num / 50)\n else:\n total_page_num = int(total_video_num / 50) + 1\n if releaser_page_num_max > total_page_num:\n releaser_page_num_max = total_page_num\n print(\"releaser page num max is %s\" % releaser_page_num_max)\n video_lst = soup.find_all('div', {'class': 'v'})\n for line in video_lst:\n video_info = self.process_one_video(line)\n video_info['releaserUrl'] = releaserUrl\n video_info['releaser'] = releaser\n result_lst.append(video_info)\n if releaser_page_num_max >= 2:\n page_num = 2\n try:\n partial_releaserUrl = soup.find('li', {'class': 'next'}).a['href']\n new_releaserUrl = 'https://id.tudou.com%s' % partial_releaserUrl\n except:\n print(new_releaserUrl)\n while page_num <= releaser_page_num_max:\n get_page = retry_get_url(new_releaserUrl)\n get_page.encoding = 'utf-8'\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n if page_num != releaser_page_num_max:\n try:\n new_releaserUrl = 'https://id.tudou.com' + soup.find('li', {'class': 'next'}).a['href']\n except:\n new_releaserUrl = ('https://id.tudou.com/i/%s/videos?order=1&page=%s' % (releaser_id, page_num))\n video_lst = soup.find_all('div', {'class': 'v'})\n for line in video_lst:\n video_info = self.process_one_video(line)\n video_info['releaserUrl'] = releaserUrl\n video_info['releaser'] = releaser\n result_lst.append(video_info)\n print('get page %s list length is %s' % (page_num, len(result_lst)))\n page_num += 1\n output_result(result_Lst=result_lst,\n platform=self.platform,\n output_to_es_raw=output_to_es_raw,\n es_index=es_index,\n doc_type=doc_type)\n result_lst.clear()\n if result_lst != []:\n output_result(result_Lst=result_lst,\n platform=self.platform,\n output_to_es_raw=output_to_es_raw,\n es_index=es_index,\n doc_type=doc_type)\n result_lst.clear()\n\n def get_releaser_name(self, releaserUrl):\n\n \"\"\"\n Due to the function releaser_page can't get releaser name from api,\n I add a function to get it from web page\n posted by yucheng fang\n \"\"\"\n\n get_page = requests.get(releaserUrl)\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n try:\n releaser = soup.find('div', {'class': 'user-name'}).a.text\n except:\n print(\"can't get releaser name at soup.find('div', {'class': 'user-name'}).a.text\")\n if releaser is not None:\n print(\"get releaser name at soup.find('div', {'class': 'user-name'}).a.text\")\n return releaser\n else:\n print(\"get releaser name at soup.find('div', {'class': 'user-name'}).a.text\")\n try:\n releaser = soup.find('div', {'class': 'head-avatar'}).a['title']\n except:\n print(\"can't get releaser name at soup.find('div', {'class': 'head-avatar'}).a['title']\")\n if releaser is not None:\n return releaser\n else:\n print(\"can't get releaser name at soup.find('div', {'class': 'head-avatar'}).a['title']\")\n return None\n\n def rebuild_releaserUrl(self, releaserUrl):\n get_page = requests.get(releaserUrl)\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n releaser_id = soup.find('div', {'class': 'user-name'}).a['href']\n url = 'https://id.tudou.com' + releaser_id + '/videos'\n return url\n\n # @logged\n def releaser_page_web(self, releaserUrl,\n output_to_file=False,\n filepath=None,\n releaser_page_num_max=30,\n output_to_es_raw=False,\n es_index=None,\n doc_type=None,\n output_to_es_register=False,\n push_to_redis=False, proxies_num=None):\n releaser_id = self.get_releaser_id(releaserUrl)\n # releaser = self.get_releaser_name(releaserUrl)\n releaserUrl = 'https://id.tudou.com/i/%s/videos' % releaser_id\n json_headers = {\n \"accept\": \"application/json, text/javascript, */*; q=0.01\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"accept-language\": \"zh,zh-CN;q=0.9\",\n # \"cookie\": \"cna=W99aFOvX+QACAXL4fBJI3rAw; __ysuid=1541219939103JPW; ykss=e93bad5ef9c26af71c8e7ee5; P_ck_ctl=47F163FE35A5B1B2E479B158A12376A7; __ayvstp=16; __aysvstp=16; _zpdtk=ecd18a6d5d86a28b786b653356133cfb606dd1dc; isg=BOzsOnpUnhIGhYq8YxHgZ36EvcoepZBPH_JJJ0Yt-Rc6UY5bbrVJ3rr3dxdpWcin\",\n \"referer\": releaserUrl,\n \"sec-fetch-dest\": \"empty\",\n \"sec-fetch-mode\": \"cors\",\n \"sec-fetch-site\": \"same-origin\",\n \"user-agent\": \"Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1\",\n \"x-csrf-token\": \"ecd18a6d5d86a28b786b653356133cfb606dd1dc\",\n \"x-requested-with\": \"XMLHttpRequest\",\n }\n json_cookies = {\n \"cna\": \"W99aFOvX+QACAXL4fBJI3rAw\",\n \"__ysuid\": \"1541219939103JPW\",\n \"ykss\": \"e93bad5ef9c26af71c8e7ee5\",\n \"P_ck_ctl\": \"47F163FE35A5B1B2E479B158A12376A7\",\n \"__ayvstp\": \"16\",\n \"__aysvstp\": \"16\",\n \"_zpdtk\": \"ecd18a6d5d86a28b786b653356133cfb606dd1dc\",\n \"isg\": \"BOzsOnpUnhIGhYq8YxHgZ36EvcoepZBPH_JJJ0Yt-Rc6UY5bbrVJ3rr3dxdpWcin\",\n }\n firsh_page_headers = {\n\n \"accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9\",\n \"accept-encoding\": \"gzip, deflate, br\",\n \"accept-language\": \"zh,zh-CN;q=0.9\",\n #\"cookie\": \"cna=W99aFOvX+QACAXL4fBJI3rAw; __ysuid=1541219939103JPW; ykss=e93bad5ef9c26af71c8e7ee5; P_ck_ctl=47F163FE35A5B1B2E479B158A12376A7; __ayvstp=16; __aysvstp=16; _zpdtk=9053e5d58ee0c51b1f3da8008dd4bda164ecd846; isg=BHl5FRo0A8WDkd_DnlItMBsXiOVThm042sF8-Juu9KAfIpu049ZUCb80oCjUmgVw\",\n \"referer\": releaserUrl,\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 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1\",\n\n }\n first_page_res = retry_get_url(releaserUrl, headers=firsh_page_headers, proxies=proxies_num)\n json_cookies.update(dict(first_page_res.cookies))\n user_id = re.findall('uid=\"(\\d+)\"', first_page_res.text)[0]\n zptk_url = \"https://id.tudou.com/i/h5/id_%s/playlisttab?uid=%s\" % (user_id, user_id)\n playlisttab_res = retry_get_url(zptk_url, headers=json_headers, proxies=proxies_num,cookies=json_cookies)\n # print(dict(playlisttab_res.cookies))\n json_cookies.update(dict(playlisttab_res.cookies))\n json_headers[\"x-csrf-token\"] = dict(playlisttab_res.cookies)[\"_zpdtk\"]\n count = 1\n retry_time = 0\n result_list = []\n\n self.video_data['releaserUrl'] = releaserUrl\n\n print(\"working on releaser_id: %s\" % (releaser_id))\n while count <= releaser_page_num_max and retry_time < 5:\n proxies = get_proxy(proxies_num)\n api_url = 'https://id.tudou.com/i/h5/id_%s/videos?ajax=1&pn=%s&pl=20' % (user_id,count)\n print(api_url)\n if proxies:\n get_page = requests.get(api_url, headers=json_headers, proxies=proxies, timeout=3,cookies=json_cookies)\n else:\n get_page = requests.get(api_url, headers=json_headers, timeout=3,cookies=json_cookies)\n _zpdtk = dict(get_page.cookies)\n json_cookies.update(_zpdtk)\n # print(dict(get_page.cookies))\n json_headers[\"x-csrf-token\"] = _zpdtk[\"_zpdtk\"]\n page_dic = get_page.json()\n # releaser_page_num_max = page_dic[\"page\"][\"pz\"]\n releaser = page_dic['channelOwnerInfo'][\"data\"][\"nickname\"]\n # has_more = page_dic.get('has_more')\n try:\n data_list = page_dic['data'][\"data\"]\n time.sleep(0.25)\n except:\n retry_time += 1\n time.sleep(0.25)\n print(\"no more data at page: %s try_time: %s\" % (count, retry_time))\n continue\n if data_list == []:\n retry_time += 1\n time.sleep(0.25)\n print(\"no more data at page: %s try_time: %s\" % (count, retry_time))\n continue\n else:\n retry_time = 0\n print(\"get data at page: %s\" % (count))\n count += 1\n for info_dic in data_list:\n video_info = copy.deepcopy(self.video_data)\n if type(info_dic) == str:\n info_dic = data_list[info_dic]\n video_info['video_id'] = info_dic[\"videoid\"]\n video_info['title'] = info_dic[\"title\"]\n video_info['releaser'] = releaser\n video_info['url'] = 'https://video.tudou.com/v/%s.html' % info_dic[\"videoid\"]\n video_info['duration'] = int(info_dic.get('seconds')/1e3)\n video_info['releaser_id_str'] = \"new_tudou_%s\" % (releaser_id)\n video_info['comment_count'] = int(info_dic.get('total_comment'))\n video_info['favorite_count'] = int(info_dic.get('total_up'))\n # favorite_count in database means 点赞数, while in web page the factor\n # named praiseNumber\n # in web page facorite_count means 收藏数\n video_info['video_img'] = info_dic.get('thumburl')\n video_info['play_count'] = info_dic.get('total_vv')\n video_info['release_time'] = int(info_dic.get('publishtime')*1e3)\n # print(video_info['release_time'])\n # if '天前' in release_time_str:\n # video_info['release_time'] = self.video_page(video_info['url'])['release_time']\n # else:\n # video_info['release_time'] = trans_strtime_to_timestamp(input_time=release_time_str,\n # missing_year=True)\n video_info['fetch_time'] = int(time.time() * 1e3)\n result_list.append(video_info)\n if len(result_list) >= 100:\n output_result(result_Lst=result_list,\n platform=self.platform,\n output_to_file=output_to_file,\n filepath=filepath,\n output_to_es_raw=output_to_es_raw,\n es_index=es_index,\n doc_type=doc_type,\n output_to_es_register=output_to_es_register)\n result_list.clear()\n if result_list != []:\n output_result(result_Lst=result_list,\n platform=self.platform,\n output_to_file=output_to_file,\n filepath=filepath,\n output_to_es_raw=output_to_es_raw,\n es_index=es_index,\n doc_type=doc_type,\n output_to_es_register=output_to_es_register)\n return result_list\n\n def releaser_page(self, releaserUrl,\n **kwargs):\n self.releaser_page_web(releaserUrl, **kwargs)\n\n # @logged\n\n def releaser_page_app(self, releaserUrl,\n output_to_file=False,\n filepath=None,\n releaser_page_num_max=30,\n output_to_es_raw=False,\n es_index=None,\n doc_type=None,\n output_to_es_register=False,\n push_to_redis=False, proxies_num=None):\n\n \"\"\"\n get video info from api instead of web page html\n the most scroll page is 1000\n \"\"\"\n\n headers = {'Host': 'apis.tudou.com',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Accept-Encoding': 'gzip, deflate',\n 'Connection': 'keep-alive',\n 'Cookie': ('isg=BIeH6gcJlwZw_xQESm9jlG-vFTuRJGXxikf0g1l0mJY9yKeKYVuAvzKJbkgzOzPm;'\n 'cna=XA2EFIGslWoCAWp4y3KXcZh7; ykss=cdbd115c102a68710215ad93;'\n '__ysuid=1543316262167mjE; P_ck_ctl=62DE1D55DFE1C0F4F27A8662E6575F08;'\n '__ayvstp=32'),\n 'Upgrade-Insecure-Requests': '1',\n 'Cache-Control': 'max-age=0'}\n\n count = 1\n # has_more = True\n retry_time = 0\n result_list = []\n releaser_id = self.get_releaser_id(releaserUrl)\n releaser = self.get_releaser_name(releaserUrl)\n releaserUrl = 'https://id.tudou.com/i/%s/videos' % releaser_id\n self.video_data['releaser'] = releaser\n self.video_data['releaserUrl'] = releaserUrl\n url_dic = {\"uid\": releaser_id,\n \"pL\": \"20\"}\n print(\"working on releaser: %s releaser_id: %s\" % (releaser, releaser_id))\n while count <= releaser_page_num_max and retry_time < 5:\n proxies = get_proxy(proxies_num)\n url_dic['pg'] = str(count)\n url_dic['pn'] = str(count)\n api_url = 'http://apis.tudou.com/subscribe/v1/video?%s' % urllib.parse.urlencode(url_dic)\n print(api_url)\n if proxies:\n get_page = requests.get(api_url, headers=headers, proxies=proxies, timeout=3)\n else:\n get_page = requests.get(api_url, headers=headers, timeout=3)\n page_dic = get_page.json()\n # has_more = page_dic.get('has_more')\n try:\n data_list = page_dic['entity']\n except:\n retry_time += 1\n time.sleep(0.25)\n print(\"no more data at releaser: %s page: %s try_time: %s\" % (releaser, count, retry_time))\n continue\n if data_list == []:\n retry_time += 1\n time.sleep(0.25)\n print(\"no more data at releaser: %s page: %s try_time: %s\" % (releaser, count, retry_time))\n continue\n else:\n retry_time = 0\n print(\"get data at releaser: %s page: %s\" % (releaser, count))\n count += 1\n for info_dic in data_list:\n video_info = copy.deepcopy(self.video_data)\n one_video = info_dic.get('detail')\n if one_video is not None:\n get_title = one_video.get('base_detail')\n if get_title is not None:\n video_info['title'] = get_title.get('title')\n detail_info = one_video.get('video_detail')\n if detail_info is not None:\n video_id = detail_info.get('video_id')\n if video_id is not None:\n video_info['video_id'] = video_id\n video_info['url'] = 'https://video.tudou.com/v/%s.html' % video_id\n video_info['duration'] = detail_info.get('duration')\n video_info['releaser_id_str'] = \"new_tudou_%s\" % (releaser_id)\n video_info['comment_count'] = int(detail_info.get('comment_count'))\n video_info['favorite_count'] = int(detail_info.get('praiseNumber'))\n # favorite_count in database means 点赞数, while in web page the factor\n # named praiseNumber\n # in web page facorite_count means 收藏数\n video_info['shoucang_count'] = (detail_info.get('favorite_count'))\n video_info['video_img'] = self.get_video_image(detail_info)\n print('play_count', detail_info.get('vv_count'))\n video_info['play_count'] = detail_info.get('vv_count')\n release_time_str = detail_info.get('publish_time')\n # print(video_info['release_time'])\n if '天前' in release_time_str:\n video_info['release_time'] = self.video_page(video_info['url'])['release_time']\n else:\n video_info['release_time'] = trans_strtime_to_timestamp(input_time=release_time_str,\n missing_year=True)\n video_info['fetch_time'] = int(time.time() * 1e3)\n result_list.append(video_info)\n if len(result_list) >= 100:\n output_result(result_Lst=result_list,\n platform=self.platform,\n output_to_file=output_to_file,\n filepath=filepath,\n output_to_es_raw=output_to_es_raw,\n es_index=es_index,\n doc_type=doc_type,\n output_to_es_register=output_to_es_register)\n result_list.clear()\n if result_list != []:\n output_result(result_Lst=result_list,\n platform=self.platform,\n output_to_file=output_to_file,\n filepath=filepath,\n output_to_es_raw=output_to_es_raw,\n es_index=es_index,\n doc_type=doc_type,\n output_to_es_register=output_to_es_register)\n return result_list\n\n def get_releaser_image(self, releaserUrl=None, data=None):\n if releaserUrl:\n get_page = requests.get(releaserUrl)\n get_page.encoding = 'utf-8'\n page = get_page.text\n soup = BeautifulSoup(page, 'html.parser')\n try:\n image_url = soup.find('a', {'class': 'user-avatar'}).next_element[\"src\"]\n print(image_url)\n return image_url\n except:\n print(\"can't get image\")\n else:\n image_url = data.find('a', {'class': 'user-avatar'}).next_element[\"src\"]\n print(image_url)\n return image_url\n\n @staticmethod\n def get_video_image(data):\n video_photo_url = data[\"cover\"][\"big\"][\"url\"]\n return video_photo_url\n\n\n# test\nif __name__ == '__main__':\n test = Crawler_tudou()\n url = 'https://video.tudou.com/v/XNDExNjcyNTI0MA==.html'\n releaser_url = \"https://id.tudou.com/i/UNDM0NTUyNjYxNg==\"\n # releaserUrl = 'https://id.tudou.com/i/UMzcyNTE2OTE2/'\n # test.get_data_mediaid(releaserUrl)\n # test.App_releaser_page_video(releaserUrl,\n # output_to_es_raw=True,\n # es_index='crawler-data-raw',\n # doc_type='doc',\n # releaser_page_num_max=300)\n # test.releaser_page(releaserUrl=releaser_url, output_to_es_raw=True,\n # es_index='crawler-data-raw',\n # doc_type='doc',\n # releaser_page_num_max=2)\n # break\n #sr_tud = test.search_page(keyword='任正非', search_pages_max=2)\n # pass\n test.get_releaser_page(releaser_url)\n","sub_path":"crawler_sys/site_crawler/crawler_tudou.py","file_name":"crawler_tudou.py","file_ext":"py","file_size_in_byte":47472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"621360775","text":"import random\n\nimport scrapy\nfrom scrapy.http import Request\n\nfrom shanghai_top_spider.items import ShanghaiTopSpiderItem\nfrom user_agent import agents\n\n\nclass ShanghaiTopCrawler(scrapy.Spider):\n name = \"shanghai_top_spider\"\n allowed_domains = [\"dianping.com\"]\n start_urls = [\n \"http://www.dianping.com/search/keyword/1/0_%E6%99%AF%E7%82%B9/o2\",\n \"http://www.dianping.com/search/keyword/1/0_%E5%95%86%E5%9C%88/o2\",\n \"http://www.dianping.com/search/keyword/1/0_%E5%B0%8F%E5%90%83%E8%A1%97/o2\",\n \"http://www.dianping.com/search/keyword/1/0_%E9%85%92%E5%BA%97/o2\",\n \"http://www.dianping.com/search/keyword/1/0_%E9%85%92%E5%90%A7/o2\"\n ]\n\n def start_requests(self):\n for url in self.start_urls:\n header = {\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Encoding': 'gzip,deflate,sdch',\n 'Accept-Language': 'zdeprecatedh-CN,zh;q=0.8,en;q=0.6',\n 'Host': 'www.dianping.com',\n 'User-Agent': random.choice(agents),\n 'Referer': url,\n }\n yield Request(url, callback=self.parse, headers=header)\n\n def parse(self, response):\n self.logger.info('the url is :%s', response.url)\n if response.status == 200:\n hxs = scrapy.Selector(response)\n xs = hxs.xpath('//*[@id=\"shop-all-list\"]/ul/li')\n index = 1\n for x in xs:\n storage_item = ShanghaiTopSpiderItem()\n site_name = x.xpath('div[2]/div[1]/a[1]/h4/text()').extract()\n url = x.xpath('div[2]/div[1]/a[1]/@href').extract()\n site_id = x.xpath('div[2]/div[1]/a[1]/@data-shopid').extract()\n star = x.xpath('div[2]/div[2]/span/@title').extract()\n region_name = x.xpath('div[2]/div[3]/a[2]/span/text()').extract()\n category_name = x.xpath('div[2]/div[3]/a[1]/span/text()').extract()\n address = x.xpath('div[2]/div[3]/span/text()').extract()\n img_url = x.xpath('div[1]/a/img/@src').extract()\n category_type = self.start_urls.index(response.url) + 1\n\n storage_item['site_name'] = site_name\n storage_item['url'] = url\n storage_item['site_id'] = site_id\n storage_item['star'] = star\n storage_item['region_name'] = region_name if region_name else \"\"\n storage_item['category_name'] = category_name if category_name else \"\"\n storage_item['address'] = address\n storage_item['img_url'] = img_url\n storage_item['sort'] = index\n storage_item['category_type'] = category_type\n index += 1\n yield storage_item\n else:\n return ''\n","sub_path":"shanghai_top_spider/spiders/shanghai_top_crawler.py","file_name":"shanghai_top_crawler.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"180155829","text":"class Solution:\n def dailyTemperatures(self, T: List[int]) -> List[int]:\n stack = list()\n t_length = len(T)\n res_list = [0 for _ in range(t_length)]\n \n for key, value in enumerate(T): \n if stack:\n while stack and T[stack[-1]] < value:\n res_list[stack[-1]] = key - stack[-1]\n stack.pop()\n stack.append(key)\n return res_list\n \n \n ","sub_path":"leetcode/739-daily-temperatures/daily-temperatures.python3.py","file_name":"daily-temperatures.python3.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"205626996","text":"def A(m,n):\n if n == 0:\n return 1\n else:\n return A(m,n-1)*(m-n+1)\n \n\nN = int(input())\nL = list(map(int,str(N+1)))\nres = 0\nn = len(L)\n\nfor i in range(1,n):\n res += 9*A(9,i-1)\n\nseen = set()\nfor i, x in enumerate(L):\n temp = sum( y not in seen for y in range(0 if i else 1,x))\n res += temp*A(9-i,n-i-1)\n if x in seen:\n break\n seen.add(x)\nprint(N-res)","sub_path":"Code/CodeRecords/2364/60791/258973.py","file_name":"258973.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"317378495","text":"# -*- coding: utf-8 -*-\n\"\"\"Operation to search through contacts.\"\"\"\n\nfrom intercom import utils\n\n\nclass Search(object):\n \"\"\"A mixin that provides `search` functionality.\"\"\"\n\n def search(self, query, **params):\n \"\"\"Find all instances of the resource based on the supplied parameters.\"\"\"\n collection_name = utils.resource_class_to_collection_name(\n self.collection_class)\n finder_url = \"/{}/scroll\".format(collection_name)\n\n response = self.client.post(\"/{}/search\".format(collection_name), query)\n \n collection_data = response['data']\n \n return map(lambda item: self.collection_class(**item), collection_data)","sub_path":"intercom/api_operations/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"576178346","text":"from csv import DictWriter\nfrom csv import DictReader\nfrom datetime import datetime\nclass Copy():\n\n def __init__(self):\n path = \"/home/tychien/Downloads/shipinformation_202109.csv\"\n with open(path,'r') as read_obj: \n csv_dict_reader = DictReader(read_obj)\n counter = 0\n for row in csv_dict_reader:\n counter += 1\n if counter <=20:\n with open('out_file.csv','a') as csv_file:\n fieldnames = row.keys()\n writer = DictWriter(csv_file, fieldnames, delimiter=',')\n if counter == 1:\n writer.writeheader()\n writer.writerow(row)\n \n \n print(row['MMSI'],row['Record_Time'])\n row_t = str(row['Record_Time'])\n print(row_t)\n row_d = datetime.strptime(row_t, '%Y-%m-%d %H:%M:%S')\n print(row_d.day)\n print('2021-08-31 23:54:22')\n else:\n break\nif __name__ == '__main__':\n copy = Copy()\n","sub_path":"ais/AIS_gui/testdir/cplines.py","file_name":"cplines.py","file_ext":"py","file_size_in_byte":1182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"5101636","text":"import requests\nimport json\nimport pandas as pd\nimport config_LinkedIn as lc\nimport datetime\nimport exasol as e\nimport config_Exasol as ec\n\nexaconnect = e.connect(\n dsn=ec.dsn,\n DRIVER=ec.DRIVER,\n EXAHOST=ec.EXAHOST,\n EXAUID=ec.EXAUID,\n EXAPWD=ec.EXAPWD,\n autocommit=True\n )\n\nexasol_lookup_campaigns_db = 'CU_ONLINE_MARKETING_STG.LINKEDIN_CAMPAIGNS_UPDATED'\nexasol_import_db = 'CU_ONLINE_MARKETING_STG.LINKEDIN_ADS'\n\napikey = lc.apitoken\ncu_online_id = lc.cu_online_id\n\n\ndef get_linkedin_dataframe(passed_url):\n get_active_url = requests.get(passed_url)\n json_details = json.loads(get_active_url.text)['elements']\n df = pd.io.json.json_normalize(json_details)\n return df\n\n\ndef linkedin_converttime(dataframe, field):\n dataframe[field] = pd.to_numeric(dataframe[field])\n dataframe[field] = pd.to_datetime(dataframe[field], unit='ms')\n\n\nif __name__ == '__main__':\n\n # campaign_ids = ['136487424', '137350024']\n exaconnect.execute('truncate table ' + exasol_import_db)\n\n exacontact = exaconnect.readData(\"select distinct id from \" + exasol_lookup_campaigns_db)\n campaigns = pd.DataFrame(exacontact)\n print(campaigns)\n campaign_ids = campaigns['ID'].values.tolist()\n\n active_campaign_ids = []\n print(campaign_ids)\n for campaign in campaign_ids:\n active_campaign_ids.append('urn:li:sponsoredCampaign:' + str(campaign))\n\n print(active_campaign_ids)\n\n for campaign in active_campaign_ids:\n creatives_df = get_linkedin_dataframe(\n 'https://api.linkedin.com/v2/adCreativesV2?q=search&search.campaign.values[0]=' + campaign + '&oauth2_access_token=' + apikey)\n\n linkedin_converttime(creatives_df, 'changeAuditStamps.created.time')\n linkedin_converttime(creatives_df, 'changeAuditStamps.lastModified.time')\n creatives_df = creatives_df.loc[(creatives_df['status'] == 'ACTIVE')].reset_index()\n\n creative_ids = creatives_df[[\n 'id',\n 'campaign',\n 'status',\n 'changeAuditStamps.created.time',\n 'changeAuditStamps.lastModified.time'\n ]]\n\n print(creative_ids)\n print('')\n\n # TODO: Find Creatives update if id and modified is greater than saved data\n # exaconnect.writePandas(creative_ids, 'UNIVERSITY_WAREHOUSE_STAGING.LINKEDIN_CREATIVES')\n\n print('')\n # TODO: If not in List then end the campaign\n\n active_ads = creative_ids['id'].values.tolist()\n\n for creative_ad in active_ads:\n creative_id = str(creative_ad)\n ads_pivot = '&pivot=CREATIVE'\n ads_time_granularity = '&timeGranularity=DAILY'\n ads_creativeid = '&creatives=urn:li:sponsoredCreative:' + creative_id\n start_date = datetime.datetime.now() + datetime.timedelta(-150)\n ads_start_month = '&dateRange.start.month=' + str(start_date.month)\n ads_start_day = '&dateRange.start.day=' + str(start_date.day)\n ads_start_year = '&dateRange.start.year=' + str(start_date.year)\n ads_url = 'https://api.linkedin.com/v2/adAnalyticsV2?q=analytics&oauth2_access_token=' + apikey + ads_start_month + ads_start_day + ads_start_year + ads_time_granularity + ads_pivot + ads_creativeid\n print(ads_url)\n #\n ads_df = get_linkedin_dataframe(ads_url)\n if ads_df.empty:\n print('No Data')\n continue\n else:\n ads_df_w_creativeid = ads_df.loc[:, 'creative_id'] = creative_id\n # Add creative id to the dataset - not returned get endpoint\n ads_df.reindex().fillna(0)\n active_ads = ads_df[[\n 'creative_id',\n 'clicks',\n 'comments',\n 'companyPageClicks',\n 'costInUsd',\n 'dateRange.start.day',\n 'dateRange.start.month',\n 'dateRange.start.year',\n 'impressions',\n 'follows',\n 'shares',\n 'viralClicks',\n 'viralFollows',\n 'viralImpressions',\n 'viralComments',\n 'viralShares'\n ]]\n\n active_ads['ad_date'] = active_ads['dateRange.start.year'].map(str) + '-' + active_ads['dateRange.start.month'].map(str) + '-' + active_ads['dateRange.start.day'].map(str)\n active_ads = active_ads.drop(columns=['dateRange.start.day', 'dateRange.start.month', 'dateRange.start.year'])\n print(active_ads)\n exaconnect.writePandas(active_ads, exasol_import_db)\n","sub_path":"LinkedIn_AdsByCampaign.py","file_name":"LinkedIn_AdsByCampaign.py","file_ext":"py","file_size_in_byte":4764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"183092194","text":"import math\nimport sys\n\nif (len(sys.argv) < 3):\n\tprint(\"Usage: ConvertRawToPCD.py inputFile outputFile.pcd\")\n\tsys.exit(1)\n\n# Open the input file\nf = open(sys.argv[1], 'r')\n\npoint_cloud = []\n\nfor line in f:\n\tif (not (line == \"\\n\" or line == \"\")):\n\t\t# Convert the raw values (DxxRxxIxx) into cartesian coordinates\n\t\tr_raw = line.split('R')[0][1:]\n\t\ttheta_raw = str(line.split('R')[1]).split('I')[0]\n\t\tphi_raw = str(line.split('I')[1])\n\t\t\n\t\tr = float(r_raw)/100\n\t\ttheta = math.radians(float(theta_raw)/3570*360)\n\t\tphi = math.pi/2 - math.radians(float(phi_raw)/440*360/260*60)\n\n\t\tx = r * math.sin(phi) * math.cos(theta)\n\t\ty = r * math.sin(phi) * math.sin(theta)\n\t\tz = r * math.cos(phi)\n\t\t# Append the coordinates into the point cloud \n\t\tpoint_cloud.append([x, y, z])\nf.close()\n\n# Open the output file\nf = open(sys.argv[2], 'w')\n\n# Write the PCD headers\nf.write('# .PCD v.7 - Point Cloud Data file format')\nf.write('VERSION .7\\n')\nf.write('FIELDS x y z\\n')\nf.write('SIZE 4 4 4\\n')\nf.write('TYPE F F F\\n')\nf.write('COUNT 1 1 1\\n')\nf.write('WIDTH '+ str(len(point_cloud)) + '\\n')\nf.write('HEIGHT 1\\n')\nf.write('VIEWPOINT 0 0 0 1 0 0 0\\n')\nf.write('POINTS '+ str(len(point_cloud)) + '\\n')\nf.write('DATA ascii\\n')\n\n# Add each point to the file\nfor point in point_cloud:\n\tf.write(str(round(point[0], 5)) + ' ' + str(round(point[1], 5)) + ' ' + str(round(point[2],5)) + '\\n')\nf.close()\n","sub_path":"PCL/build/ConvertRawToPCD.py","file_name":"ConvertRawToPCD.py","file_ext":"py","file_size_in_byte":1375,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"643423977","text":"# define el algoritmo de im\r\n# - conjunto de vistas\r\n# - esquema global\r\n\r\nimport copy\r\nimport pprint\r\nfrom MCD import *\r\nfrom MCDAux import *\r\n\r\n#Recibe una lista de vistas\r\n#Un query CQ\r\ndef createMCDs(vistas, query):\r\n C = Set([])\r\n subsQ = query.cuerpo\r\n conQ = query.comparacion\r\n n = len(subsQ)\r\n for i in xrange(n):\r\n g = subsQ[i]\r\n for V in vistas:\r\n subsV = V.cuerpo\r\n maps = obtPosiblesMaps(query, V)\r\n for v in subsV:\r\n if v.esIgual(g):\r\n phitodo = mappingH(g, v, V)\r\n if phitodo:\r\n gi = Set([i])\r\n mcdaux = crearMCDAux(query, V, phitodo, gi)\r\n if mcdaux != None:\r\n extenderMapping(C, mcdaux, query, V, maps, gi)\r\n i = i + 1\r\n eliminarMCDsNoMinimales(C);\r\n return C\r\n\r\n\r\ndef crearMCDAux(query, vista, phictodo, gi):\r\n if not property1_c1(query, vista, phictodo):\r\n return None\r\n else:\r\n phic, hc = calcularPhiH(vista, phictodo)\r\n gc = calcularGcPosibles(query, phic, hc, vista, gi)\r\n return MCDAux(query, vista, phictodo, gi, phic, hc, gc)\r\n\r\n\r\ndef extenderMapping(C, mcdaux, query, vista, maps, gi):\r\n if not mcdaux.cumpleProperty1_c1:\r\n return \r\n\r\n mapsFaltan = obtMapsFaltantes(maps, mcdaux.phictodo)\r\n return extenderMapping1(C, mcdaux, query, vista, mapsFaltan, gi)\r\n\r\n\r\ndef extenderMapping1(mcds, mcdaux, query, vista, maps, gi):\r\n if mcdaux is None:\r\n return \r\n\r\n if len(mcdaux.phic) == 0:\r\n return \r\n\r\n if mcdaux.esValido:\r\n mcds |= mcdaux.mcds\r\n return\r\n\r\n if len(maps) == 0:\r\n return\r\n \r\n n = len(maps)\r\n for x in xrange(n):\r\n (varq, varv) = maps[x]\r\n maps2 = maps[x+1:]\r\n mcdauxN = agregarMapping(mcds, mcdaux, varq, varv, query, vista, gi)\r\n extenderMapping1(mcds, mcdauxN, query, vista, maps2, gi)\r\n\r\n\r\ndef obtPosiblesMaps(query, V):\r\n maps = Set([])\r\n for subobq in query.cuerpo:\r\n for subobv in V.cuerpo:\r\n if subobq.predicado == subobv.predicado:\r\n variablesq = subobq.orden\r\n variablesv = subobv.orden\r\n n = len(variablesq)\r\n for x in xrange(n):\r\n maps.add((variablesq[x], variablesv[x]))\r\n return maps\r\n\r\n\r\ndef agregarMapping(mcds, mcdaux, varq, varv, query, vista, gi):\r\n return mcdaux.extender(varq, varv, gi)\r\n\r\ndef mappingH(g, v, V):\r\n phitodo = {}\r\n varsY = v.orden\r\n j = 0\r\n for x in g.orden:\r\n phitodo.setdefault(x,Set([])).add(varsY[j])\r\n j = j + 1\r\n\r\n for i in phitodo:\r\n phitodo[i]=list(phitodo[i])\r\n return phitodo\r\n\r\ndef obtMapsFaltantes(maps, phictodo):\r\n maps2 = maps.copy()\r\n for varq in phictodo:\r\n for varv in phictodo[varq]:\r\n maps2.remove((varq, varv)) \r\n return list(maps2)\r\n\r\ndef eliminarMCDsNoMinimales(mcds):\r\n listaMcds = list(mcds)\r\n n = len(listaMcds)\r\n for x in xrange(n):\r\n mcdx = listaMcds[x]\r\n gcmcdx = mcdx.gc\r\n mapsmcdx = mcdx.conjuntoMaps\r\n for y in xrange(x+1,n): \r\n mcdy = listaMcds[y]\r\n if x != y and mcdx.vista.cabeza.predicado == mcdy.vista.cabeza.predicado:\r\n gcmcdy = mcdy.gc\r\n mapsmcdy = mcdy.conjuntoMaps\r\n if mapsmcdy <= mapsmcdx and gcmcdy <= gcmcdx:\r\n mcds.discard(mcdx)\r\n break\r\n elif mapsmcdy >= mapsmcdx and gcmcdy >= gcmcdx:\r\n mcds.discard(mcdy)\r\n\r\n\r\n\r\n","sub_path":"minicon/MCAlgorithm/createMCDs.py","file_name":"createMCDs.py","file_ext":"py","file_size_in_byte":3653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"496325547","text":"\"\"\"\nQuestion: https://leetcode.com/problems/reverse-integer/\n\nGiven a 32-bit signed integer, reverse digits of an integer.\n\nExample 1:\n\nInput: 123\nOutput: 321\nExample 2:\n\nInput: -123\nOutput: -321\nExample 3:\n\nInput: 120\nOutput: 21\nNote:\nAssume we are dealing with an environment which could only store integers\n within the 32-bit signed integer range: [−2^31, 2^31 − 1].\n For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.\n\"\"\"\n\n\nclass Solution:\n def reverse(self, x: int) -> int:\n return self.first_implementation(x)\n\n @staticmethod\n def first_implementation(inp: int) -> int:\n \"\"\"\n Implementation running in O(n) time for the implied complexity of the reverse operation\n Space Complexity: O(n)\n -- Given that there needs to be a new string allocated of at least n size.\n \"\"\"\n is_neg = False\n if inp < 0:\n is_neg = True\n inp *= -1\n outp = int(str(inp)[::-1])\n if outp > (2 ** 31 - 1) or outp < -2 ** 31:\n outp = 0\n return outp * -1 if is_neg else outp\n","sub_path":"python/coding_challenges/leet_code/reverse_integer.py","file_name":"reverse_integer.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"363451698","text":"#wap take list as a input and print all the elements of the that are less than 10\r\n#ex.[4,5,6,10,23,21,99]\r\n\r\n'''a=[4,5,6,10,23,21,99]\r\n#for i in a:\r\nif a < 10:\r\n print(a)'''\r\n#supose we have 2 list\r\n#a=[\r\n'''a=[3,4,5,6,10,234,10]\r\nb=[4,1,5,7,8,10,10,4]\r\nd=[]\r\nfor i in a:\r\n for k in b:\r\n if i==k and i not in d:\r\n d.append(i)\r\nprint(d)'''\r\n\r\n'''a=[3,4,5,6,10,23,4,10]\r\nd=[]\r\nfor i in a:'''\r\n\r\na='madam'\r\n'''for i in a:\r\n a.append(i)\r\n print(a is palindrom)\r\nelse:\r\n print(not palindron)'''\r\n\r\n'''a='hello'\r\na.lower():\r\nprint(a)'''\r\n\r\n\r\n\r\n\r\n\r\n \r\n","sub_path":"Downloads/python/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"622203084","text":"# Hack to be able to import across /app/waldren\nimport sys\nsys.path.append('/app/waldren/base')\n\nimport TDClient\nfrom tda import client\nimport os, pandas\nimport talib\nimport psycopg2\n\ndef is_consolidating(df, percentage=2):\n recent_candlesticks = df[-15:]\n \n max_close = recent_candlesticks['close'].max()\n min_close = recent_candlesticks['close'].min()\n\n threshold = 1 - (percentage / 100)\n if min_close > (max_close * threshold):\n return True \n\n return False\n\ndef is_breaking_out(df, percentage=2.5):\n last_close = df[-1:]['close'].values[0]\n\n if is_consolidating(df[:-1], percentage=percentage):\n recent_closes = df[-16:-1]\n\n if last_close > recent_closes['close'].max():\n return True\n\n return False\n\ndef get_watchlist(cursor):\n cursor.execute(\"SELECT stock_id, symbol FROM watchlist w, stock s WHERE s.id = w.stock_id AND w.list='screener' AND w.active=TRUE\")\n rows = cursor.fetchall()\n return rows\n\ndef main():\n connection = psycopg2.connect(\n host=\"timescale\",\n database=\"tradekit\",\n user=\"tradekit\",\n password=\"yourpassword\",\n )\n\n cursor = connection.cursor()\n cursor.execute (\"SELECT symbol, name FROM indicators\")\n rows = cursor.fetchall()\n cdl_patterns = []\n for row in rows:\n cdl_patterns.append( (row[0], row[1]) )\n \n tc = TDClient.TDClient()\n\n watchlist = get_watchlist(cursor)\n\n for stock in watchlist:\n df = tc.get_price_daily_history(stock[1], period=client.Client.PriceHistory.Period.ONE_YEAR)\n print()\n print(\"****************************** Results for {} ********************************\".format(stock[1]))\n print(df.tail())\n\n for pat in cdl_patterns:\n pattern_function = getattr(talib, pat[0])\n\n results = pattern_function(df['open'], df['high'], df['low'], df['close'])\n last = results.tail(1).values[0]\n\n if last > 0:\n print(\"{} is bullish\".format(pat[1]))\n elif last < 0:\n print(\"{} is bullish\".format(pat[1]))\n \n print()\n if is_consolidating(df):\n print (\"IS CONSOLIDATING\")\n if is_breaking_out(df):\n print(\"IS BREAKINGOUT\")\n print(\"********************************************************************************\")\n\n cursor.close()\n connection.close()\n\nif __name__ == \"__main__\":\n main()\n \n\n","sub_path":"waldren/screener/candle_screener.py","file_name":"candle_screener.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"483129213","text":"#!/usr/bin/env python\n# -*- encode: utf-8 -*-\n\n#Copyright 2015 RAPP\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: Athanassios Kintsakis\n# contact: akintsakis@issel.ee.auth.gr\n\n\nimport rospkg\nimport rospy\nimport sys\nimport xml.etree.ElementTree as ET\nimport calendar\nimport time\nimport random\nfrom datetime import datetime\nfrom os.path import expanduser\nfrom collections import OrderedDict\nfrom random import randint\nfrom codecs import open\n\n\nfrom rapp_platform_ros_communications.srv import (\n ontologySubSuperClassesOfSrv,\n ontologySubSuperClassesOfSrvRequest,\n ontologySubSuperClassesOfSrvResponse,\n testSelectorSrv,\n testSelectorSrvResponse,\n createOntologyAliasSrv,\n createOntologyAliasSrvRequest,\n createOntologyAliasSrvResponse,\n userPerformanceCognitveTestsSrv,\n userPerformanceCognitveTestsSrvRequest,\n userPerformanceCognitveTestsSrvResponse,\n cognitiveTestsOfTypeSrv,\n cognitiveTestsOfTypeSrvRequest,\n cognitiveTestsOfTypeSrvResponse,\n fetchDataSrv,\n fetchDataSrvRequest,\n fetchDataSrvResponse\n )\n\nfrom rapp_platform_ros_communications.msg import (\n StringArrayMsg\n )\n\nclass TestSelector:\n\n def chooserFunction(self,req):\n currentTimestamp = int(time.time()) #15552000000 for last 3 months\n\n try:\n res = testSelectorSrvResponse()\n #obtain user's ontology alias. It will be created if it does not exist in case of invalid username it will be caught\n serv_topic = rospy.get_param('rapp_knowrob_wrapper_create_ontology_alias')\n if(not serv_topic):\n rospy.logerror(\"rapp_knowrob_wrapper_create_ontology_alias param not found\")\n res.trace.append(\"rapp_knowrob_wrapper_create_ontology_alias param not found\")\n res.error=\"rapp_knowrob_wrapper_create_ontology_alias param not found\"\n res.success=False\n return res\n rospy.wait_for_service(serv_topic)\n knowrob_service = rospy.ServiceProxy(serv_topic, createOntologyAliasSrv)\n createOntologyAliasReq = createOntologyAliasSrvRequest()\n createOntologyAliasReq.username=req.username\n createOntologyAliasResponse = knowrob_service(createOntologyAliasReq)\n if(createOntologyAliasResponse.success!=True):\n res.trace.extend(createOntologyAliasResponse.trace)\n res.error=createOntologyAliasResponse.error\n res.success=False\n return res\n\n\n #get user language\n serv_topic = rospy.get_param('rapp_mysql_wrapper_user_fetch_data_topic')\n if(not serv_topic):\n rospy.logerror(\"rapp_mysql_wrapper_user_fetch_data_topic param not found\")\n res.trace.append(\"rapp_mysql_wrapper_user_fetch_data_topic param not found\")\n res.error=\"mysql_wrapper_rapp_read_data topic param not found\"\n res.success=False\n return res\n rospy.wait_for_service(serv_topic)\n knowrob_service = rospy.ServiceProxy(serv_topic, fetchDataSrv)\n fetchDataSrvReq = fetchDataSrvRequest()\n fetchDataSrvReq.req_cols=[\"language\"]\n fetchDataSrvReq.where_data=[StringArrayMsg(s=[\"username\",req.username])]\n #print fetchDataSrvReq.where_data\n fetchDataSrvResponse = knowrob_service(fetchDataSrvReq)\n if(fetchDataSrvResponse.success.data!=True):\n #print fetchDataSrvResponse.res_data[0].s[0];\n res.trace.extend(fetchDataSrvResponse.trace)\n res.error=fetchDataSrvResponse.trace[0]\n res.success=False\n return res\n userLanguage=fetchDataSrvResponse.res_data[0].s[0];\n #print userLanguage\n #\n\n\n #Check if test type exists (if a test type is provided)\n serv_topic = rospy.get_param('rapp_knowrob_wrapper_subclasses_of_topic')\n if(not serv_topic):\n rospy.logerror(\"rapp_knowrob_wrapper_subclasses_of_topic topic param not found\")\n res.trace.append(\"rapp_knowrob_wrapper_subclasses_of_topic topic param not found\")\n res.error=\"rapp_knowrob_wrapper_subclasses_of_topic topic param not found\"\n res.success=False\n return res\n rospy.wait_for_service(serv_topic)\n knowrob_service = rospy.ServiceProxy(serv_topic, ontologySubSuperClassesOfSrv)\n testTypesReq = ontologySubSuperClassesOfSrvRequest()\n testTypesReq.ontology_class=\"CognitiveTests\"\n testTypesResponse = knowrob_service(testTypesReq)\n if(testTypesResponse.success!=True):\n res.trace.extend(testTypesResponse.trace)\n res.trace.append(\"cannot load test categories from ontology\")\n res.error=testTypesResponse.error+\"cannot load test categories from ontology\"\n res.success=False\n return res\n testTypesList=[]\n for s in testTypesResponse.results:\n #res.trace.append(s)\n tmpList=s.split('#')\n testTypesList.append(tmpList[1])\n\n serv_topic = rospy.get_param('rapp_knowrob_wrapper_user_performance_cognitve_tests')\n if(not serv_topic):\n rospy.logerror(\"rapp_knowrob_wrapper_user_performance_cognitve_tests topic not foud\")\n res.trace.append(\"mysql_wrapper_rapp_read_data topic param not found\")\n res.error=\"mysql_wrapper_rapp_read_data topic param not found\"\n res.success=False\n return res\n\n if(req.testType==\"\"):\n res.trace.append(\"no test type provided, will use least recently used\")\n noRecordsList=[]\n d1=OrderedDict()\n for s in testTypesList:\n userPerformanceReq=userPerformanceCognitveTestsSrvRequest()\n userPerformanceReq.test_type=s\n userPerformanceReq.ontology_alias=createOntologyAliasResponse.ontology_alias\n knowrob_service = rospy.ServiceProxy(serv_topic, userPerformanceCognitveTestsSrv)\n userPerformanceResponse = knowrob_service(userPerformanceReq)\n if(userPerformanceResponse.success!=True):\n noRecordsList.append(s)\n else:\n tmpUserPerfOrganizedByTimestamp=self.organizeUserPerformance(userPerformanceResponse)\n t1=tmpUserPerfOrganizedByTimestamp.items()[0][0]\n d1[t1]=[s]\n\n if(len(noRecordsList)>0):\n req.testType=random.choice(noRecordsList)\n res.trace.append(\"made random choice from the test types which were never used by the user, choice was: \"+ req.testType)\n else:\n d1=OrderedDict(sorted(d1.items(), key=lambda t: t[0]))\n req.testType=d1.values()[0][0]\n res.trace.append(\"all test types had performance records.. least recently used one was :\"+ req.testType)\n else:\n if (req.testType not in testTypesList):\n res.trace.append(\"testType provided does not exist\")\n res.error=\"testType provided does not exist\"\n res.success=False\n return res\n\n # check if performance records exist for the selected test in order to determine the difficulty setting\n noUserPerformanceRecordsExist=False;\n chosenDif=\"1\"\n userPerformanceReq=userPerformanceCognitveTestsSrvRequest()\n userPerformanceReq.test_type=req.testType\n userPerformanceReq.ontology_alias=createOntologyAliasResponse.ontology_alias\n knowrob_service = rospy.ServiceProxy(serv_topic, userPerformanceCognitveTestsSrv)\n userPerformanceResponse = knowrob_service(userPerformanceReq)\n if(userPerformanceResponse.success!=True):\n res.trace.extend(userPerformanceResponse.trace)\n res.trace.append(\"KnowRob wrapper returned no performance records for this user.. will start with a a difficulty setting of 1\")\n noUserPerformanceRecordsExist=True\n else:\n userPerfOrganizedByTimestamp=self.organizeUserPerformance(userPerformanceResponse)\n for k, v in userPerfOrganizedByTimestamp.items():\n if(currentTimestamp-k>15552000000):\n del userPerfOrganizedByTimestamp[k]\n else:\n break\n\n userScore=self.calculateUserScore(userPerfOrganizedByTimestamp)\n res.trace.append(\"user score :\"+str(userScore))\n if(userScore==0):\n chosenDif=\"1\"\n elif(userScore<0.75*100):\n chosenDif=\"1\"\n elif(userScore<0.75*2*100):\n chosenDif=\"2\"\n else: #(userScore>0.75*3*100)\n chosenDif=\"3\"\n res.trace.append(\"Chosen Diff :\"+chosenDif)\n\n #Get cognitive tests of the selected type.\n serv_topic = rospy.get_param('rapp_knowrob_wrapper_cognitive_tests_of_type')\n if(not serv_topic):\n rospy.logerror(\"rapp_knowrob_wrapper_cognitive_tests_of_type not found\")\n res.trace.append(\"rapp_knowrob_wrapper_cognitive_tests_of_type not found\")\n res.error=\"rapp_knowrob_wrapper_cognitive_tests_of_type not found\"\n res.success=False\n return res\n cognitiveTestsOfTypeSrvReq=cognitiveTestsOfTypeSrvRequest()\n cognitiveTestsOfTypeSrvReq.test_type=req.testType\n cognitiveTestsOfTypeSrvReq.test_language=userLanguage\n knowrob_service = rospy.ServiceProxy(serv_topic, cognitiveTestsOfTypeSrv)\n cognitiveTestsOfTypeResponse = knowrob_service(cognitiveTestsOfTypeSrvReq)\n\n if(cognitiveTestsOfTypeResponse.success!=True):\n res.trace.extend(cognitiveTestsOfTypeResponse.trace)\n res.error=cognitiveTestsOfTypeResponse.error\n res.success=False\n return res\n\n #print \"after tests.........\"\n #Filter the tests according to the determined difficulty\n success,testsOfTypeOrdered=self.filterTestsbyDifficulty(cognitiveTestsOfTypeResponse,chosenDif,res)\n\n #If no test exists\n if(not success): #not len(testsOfTypeOrdered)>0):\n res.trace.append(\"Error, no tests of type contained in the ontology... cannot proceed\")\n res.error=\"Error, no tests of type contained in the ontology... cannot proceed\"\n res.success=False\n return res\n\n #Choose the least recently used test of the given test type and difficulty and obtain the path to the xml file\n finalTestname=\"\"\n finalTestFilePath=\"\"\n if(noUserPerformanceRecordsExist):\n #print \"inside no records\"\n finalTestname=random.choice(testsOfTypeOrdered.keys())\n finalTest=testsOfTypeOrdered[finalTestname]\n finalTestFilePath=finalTest[0][0]\n else:\n testsOfTypeOrderedCopy=testsOfTypeOrdered.copy()\n for k, v in userPerfOrganizedByTimestamp.items():\n if(v[0][0] in testsOfTypeOrderedCopy):\n del testsOfTypeOrderedCopy[v[0][0]]\n\n if(len(testsOfTypeOrderedCopy)>0):\n finalTestname=random.choice(testsOfTypeOrderedCopy.keys())\n finalTest=testsOfTypeOrderedCopy[finalTestname]\n finalTestFilePath=finalTest[0][0]\n else:\n finalTestname=userPerfOrganizedByTimestamp.values()[len(userPerfOrganizedByTimestamp)-1]\n finalTestname=finalTestname[0][0]\n finalTest=testsOfTypeOrdered[finalTestname]\n finalTestFilePath=finalTest[0][0]\n\n #Retrieve the name of the selected test\n tmpList=finalTestname.split('#')\n res.test=tmpList[1]\n\n #Parse the test xml file and retrieve the desired information\n rospack = rospkg.RosPack()\n localPackagePath=rospack.get_path('rapp_cognitive_exercise')\n finalTestFilePath=localPackagePath+finalTestFilePath\n res.trace.append(finalTestFilePath)\n self.retrieveDataFromTestXml(finalTestFilePath,res,userLanguage)\n res.language=userLanguage\n res.success=True\n\n except IndexError:\n res.trace.append(\"Null pointer exception.. some argument was empty\")\n res.error=\"Null pointer exception.. some argument was empty\"\n res.success=False\n #print \"Wrong Query Input Format, check for empty required columns list or wrong/incomplete Query data format\"\n except IOError:\n res.success=False\n res.trace.append(\"IO Error, cant open file or read data\")\n res.error=\"IO Error, cant open file or read data\"\n return res\n\n def retrieveDataFromTestXml(self,finalTestFilePath,res,userLanguage):\n #print \"inside xml\"\n tree = ET.parse(finalTestFilePath)\n root = tree.getroot()\n res.testType=root.find(\"testType\").text.encode('UTF-8')\n res.testSubType=root.find(\"testSubType\").text.encode('UTF-8')\n language=root.find('Languages')\n #print userLanguage\n #language=language.find(userLanguage)\n\n for question in language.find(userLanguage):\n res.questions.append(question.find(\"body\").text.encode('UTF-8'))\n res.correctAnswers.append(question.find(\"correctAnswer\").text.encode('UTF-8'))\n line=StringArrayMsg()\n for answers in question.findall('answer'):\n line.s.append(answers.find(\"body\").text.encode('UTF-8'))\n res.answers.append(line)\n\n def organizeUserPerformance(self,userPerf):\n d=OrderedDict()\n for i in range(len(userPerf.tests)):\n tlist=[userPerf.tests[i],userPerf.scores[i],userPerf.difficulty[i]]\n d[int(userPerf.timestamps[i])]=[tlist]\n #testTypesDict[s]=['1']\n d=OrderedDict(sorted(d.items(), key=lambda t: t[0], reverse=True))\n return d\n\n def calculateUserScore(self,d):\n score=0\n if (len(d)>0):\n for k, v in d.items():\n score=score+int(v[0][1])*int(v[0][2])\n score=score/len(d)\n return score\n else:\n return 0\n\n def filterTestsbyDifficulty(self,testsOfType,chosenDif,res):\n success=False\n d=dict()\n intDif=int(chosenDif)\n if(intDif==0):\n return success,d\n else:\n for i in range(len(testsOfType.tests)):\n if(testsOfType.difficulty[i]==chosenDif):\n tlist=[testsOfType.file_paths[i],testsOfType.difficulty[i],testsOfType.subtype[i]]\n d[testsOfType.tests[i]]=[tlist]\n\n if(not len(d)>0):\n res.trace.append(\"downscaling difficulty by 1 as no test exists for diff = \" +chosenDif);\n #print \"downscaling difficulty by 1 as no test exists for diff = \" +chosenDif\n chosenDif=str(int(chosenDif)-1)\n success,d=self.filterTestsbyDifficulty(testsOfType,chosenDif,res)\n else:\n success=True\n return success,d\n\n\n\n\n","sub_path":"rapp_cognitive_exercise/src/test_selector.py","file_name":"test_selector.py","file_ext":"py","file_size_in_byte":14335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"528087896","text":"from flask import request, jsonify, escape, Blueprint\nfrom common.token import token_required\nfrom db.db import session, answears, questions\nfrom flask_cors import CORS\n\nanswers_api = Blueprint('answers_api', __name__)\nCORS(answers_api)\n@answers_api.route('/api/proper_answer_to/')\n@token_required\ndef get_correct_answer(current_user, question_id):\n #add checking user\n answer = answears.get_right_answer(question_id)\n if answer is None:\n return jsonify({'message' : 'No such element'}), 200\n return jsonify({\"name\" : answer.name, \"answer_id\" : answer.id}), 200\n\n@answers_api.route('/api/answers/')\n@token_required\ndef get_answers_for_question(current_user, question_id):\n result = answears.get_answers(question_id)\n if not result:\n return jsonify({'message' : 'No such element'}), 200\n print (result)\n result_info = []\n for n in result:\n r = { \"answer_id\" : n.id, \"name\" : n.name, \"isProper\" : n.isProper}\n result_info.append(r)\n return jsonify({\"answers\" : result_info}), 200\n\n@answers_api.route('/api/answer', methods=['POST'])\n@token_required\ndef add_answer(current_user):\n name = escape(request.form.get('name'))\n question_id = escape(request.form.get('question_id'))\n isProper = escape(request.form.get('isProper'))\n answer = answears(name=name, question_id=question_id, isProper=isProper)\n question = questions.get_one_question(question_id)\n if not question:\n return jsonify({'message' : 'No such element'}), 200\n elif current_user.id != question.user_id and current_user.level !=3:\n return jsonify({'message' : 'Forbidden'}), 403\n session.add(answer)\n session.commit()\n return jsonify({\"message\" : \"Answer has been added\", \"answer_id\" : answer.id}), 200\n\n@answers_api.route('/api/answers/', methods=['DELETE'])\n@token_required\ndef delete_answers_for_question(current_user, question_id):\n question = questions.get_one_question(question_id)\n if not question:\n return jsonify({'message' : 'No such element'}), 200\n elif current_user.id != question.user_id and current_user.level !=3:\n return jsonify({'message' : 'Forbidden'}), 403\n answers = answears.get_answers(question_id)\n for n in answers:\n session.delete(n)\n session.commit()\n return jsonify({\"message\" : \"Answers for this question has been deleted\"}), 200\n\n\n@answers_api.route('/api/answer/', methods=['DELETE'])\n@token_required\ndef delete_one_answer(current_user, answer_id):\n answer = session.query(answears).filter_by(id = answer_id).first()\n if not answer:\n return jsonify({'message' : 'No such element'}), 200\n question = questions.get_one_question(answer.question_id)\n if current_user.id != question.user_id and current_user.level !=3:\n return jsonify({'message' : 'Forbidden'}), 403\n session.delete(answer)\n session.commit()\n return jsonify({\"message\" : \"Answer has been deleted\"}), 200\n","sub_path":"routes/answers_api_file.py","file_name":"answers_api_file.py","file_ext":"py","file_size_in_byte":3006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"403767759","text":"\"\"\"\n450. 删除二叉搜索树中的节点\n给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。\n返回二叉搜索树(有可能被更新)的根节点的引用。\n一般来说,删除节点可分为两个步骤:\n首先找到需要删除的节点;\n如果找到了,删除它。\n说明: 要求算法时间复杂度为 O(h),h 为树的高度。\n示例:\nroot = [5,3,6,2,4,null,7]\nkey = 3\n 5\n / \\\n 3 6\n / \\ \\\n2 4 7\n给定需要删除的节点值是 3,所以我们首先找到 3 这个节点,然后删除它。\n一个正确的答案是 [5,4,6,2,null,null,7], 如下图所示。\n 5\n / \\\n 4 6\n / \\\n2 7\n另一个正确答案是 [5,2,6,null,4,null,7]。\n 5\n / \\\n 2 6\n \\ \\\n 4 7\n\"\"\"\n\n# Definition for a binary tree node.\nfrom typing import List\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n def __str__(self):\n return f'node: val={self.val}'\n\n\nclass Solution:\n def predecessor(self, root: TreeNode) -> TreeNode:\n \"\"\"\n 返回左子节点中的最大节点(前驱节点)\n \"\"\"\n node = root.left\n while node and node.right:\n node = node.right\n return node\n\n def successor(self, root: TreeNode) -> TreeNode:\n \"\"\"\n 返回右子节点中的最小节点(后驱节点)\n \"\"\"\n node = root.right\n while node and node.left:\n node = node.left\n return node\n\n def deleteNode(self, root: TreeNode, key: int) -> TreeNode:\n if root is None:\n return\n if key < root.val:\n root.left = self.deleteNode(root.left, key)\n elif key > root.val:\n root.right = self.deleteNode(root.right, key)\n else:\n if not (root.left or root.right): # 没有子节点\n root = None\n elif root.right: # 有右子节点\n root.val = self.successor(root).val\n root.right = self.deleteNode(root.right, root.val)\n else:\n root.val = self.predecessor(root).val\n root.left = self.deleteNode(root.left, root.val)\n return root\n \n def inOrder(self, root: TreeNode) -> List:\n # 中序遍历\n return self.inOrder(root.left) + [root.val] + self.inOrder(root.right) if root else []\n\n\nnode5 = TreeNode(5)\nnode3 = TreeNode(3)\nnode6 = TreeNode(6)\nnode2 = TreeNode(2)\nnode4 = TreeNode(4)\nnode7 = TreeNode(7)\n\nnode5.left = node3\nnode5.right = node6\nnode3.left = node2\nnode3.right = node4\nnode6.right = node7\n\ns = Solution()\nn = s.deleteNode(node5, 3)\nprint(n)\n","sub_path":"delete_node_450.py","file_name":"delete_node_450.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"232792862","text":" \nimport matplotlib.pyplot as plt\nimport numpy as np\n#import uncertainties.unumpy as unp\n#import os, platform,sys\nfrom numpy import linalg as LA\n\n\ndef eigenvalues(a):\n\tEW,EV=LA.eig(a)\n\treturn EW\n\ndef eigenvectors(a):\n\tEW,EV=LA.eig(a)\n\treturn EV\n\ndef paracalc(R3):\n\tif R3 == 3:\n\t\tp,q=1,0\n\t\tS2h=1/2\n\telif R3 == 6:\n\t\tp,q=2,0\n\t\tS2h=5/2\n\telif R3 == 8:\n\t\tp,q=1,1\n\t\tS2h=3\n\telif R3 == 10:\n\t\tp,q=3,0\n\t\tS2h=15/2\n\telif R3 == 15:\n\t\tp,q=2,1\n\t\tS2h=10\n\telse:\n\t\tprint('Trottel, falsches R3')\n\tdR3h=(1/2)*(p+1)*(q+1)*(p+q+2)\n\tC2R3h=p+q+(1/3)*((p**2)+(q**2)+p*q)\n\treturn dR3h,C2R3h,S2h\n\n\n#Parameter\n#NF=100 #Materieinhalt\n#R3=3 # halo, i bims Darsdelung lol\n\ndef prob(R3,NFmax):\n\tNF=0\n\twhile (NF 0:\n file_word.write(\" \".join(wlist) + \"\\n\")\n file_tag.write(\" \".join(taglist) + \"\\n\")\n\n\ndef trans_zero_one_label(tags_path, tags01_path):\n with open(tags01_path, \"w\", encoding=\"utf8\") as file_write:\n with open(tags_path, \"r\", encoding=\"utf8\") as file_read:\n for line in file_read:\n tags = line.strip().split(\" \")\n new_tags = []\n i = 0\n while i < len(tags):\n if tags[i].startswith(\"B-\"):\n label = tags[i].split(\"-\")[-1]\n j = i + 1\n while j < len(tags) and tags[j] == \"I-\" + label:\n j += 1\n new_tags.append(\"0\")\n new_tags.append(\"1\")\n i = j\n else:\n new_tags.append(\"1\")\n i += 1\n file_write.write(\" \".join(new_tags) + \"\\n\")\n\n\ndef merge_entity(data_path, tags_path, data_new_path, tags_new_path):\n with open(tags_path, \"r\", encoding=\"utf8\") as file_tags_read, \\\n open(data_path, \"r\", encoding=\"utf8\") as file_words_read:\n tags = [line.strip().split() for line in file_tags_read]\n words = [line.strip().split() for line in file_words_read]\n\n with open(tags_new_path, \"w\", encoding=\"utf8\") as file_tags_write, \\\n open(data_new_path, \"w\", encoding=\"utf8\") as file_words_write:\n entity = \"\"\n label = \"\"\n\n for ws, ts in zip(words, tags):\n new_ws, new_ts = [], []\n for w, t in zip(ws, ts):\n if t.startswith(\"B-\") and len(entity) == 0:\n entity = w\n label = t.split(\"-\")[-1]\n elif t.startswith(\"B-\"):\n new_ts.append(entity)\n new_ts.append(label)\n entity = w\n label = t.split(\"-\")[-1]\n elif t.startswith(\"I-\"):\n entity += w\n elif t == \"O\":\n if len(entity) > 0:\n new_ts.append(entity)\n new_ts.append(label)\n entity, label = \"\", \"\"\n new_ts.append(\"O\")\n new_ws.append(w)\n file_words_write.write(\" \".join(new_ws) + \"\\n\")\n file_tags_write.write(\" \".join(new_ts) + \"\\n\")\n\n\ndef trans_pred(data_path, ptags_path, words_path):\n with open(ptags_path, \"w\", encoding=\"utf8\") as file_ptag, \\\n open(data_path, \"r\", encoding=\"utf8\") as file_read, \\\n open(words_path, \"r\", encoding=\"utf8\") as file_word:\n words_list = [line.strip() for line in file_word]\n taglist = []\n wlist = []\n words_with_entity_dict = {}\n for line in file_read:\n if len(line.strip()) == 0:\n words_with_entity_dict[\" \".join(wlist)] = \" \".join(taglist)\n wlist = []\n taglist = []\n else:\n items = line.rstrip(\"\\n\").split(\" \")\n if len(items) != 3:\n print(line)\n traceback.print_exc()\n wlist.append(items[0])\n if items[-1] != \"O\":\n taglist.append(\"1\")\n else:\n taglist.append(\"0\")\n\n if len(wlist) > 0:\n words_with_entity_dict[\" \".join(wlist)] = \" \".join(taglist)\n\n for sent in words_list:\n if sent not in words_with_entity_dict:\n taglist = \" \".join([\"0\"] * len(sent.split(\" \")))\n else:\n taglist = words_with_entity_dict[sent]\n file_ptag.write(taglist + \"\\n\")\n\n\ndef trans2entity_label(data_path, words_path, tags_path):\n with open(words_path, \"w\", encoding=\"utf8\") as file_word, \\\n open(tags_path, \"w\", encoding=\"utf8\") as file_tag, \\\n open(data_path, \"r\", encoding=\"utf8\") as file_read:\n wlist = []\n taglist = []\n for line in file_read:\n if len(line.strip()) == 0:\n if len([tag for tag in taglist if tag != \"O\"]) > 0:\n file_word.write(\" \".join(wlist) + \"\\n\")\n file_tag.write(\" \".join(taglist) + \"\\n\")\n wlist = []\n taglist = []\n else:\n items = line.rstrip(\"\\n\").split(\" \")\n if len(items) == 2:\n wlist.append(items[0])\n else:\n taglist.append(\"\")\n if items[-1] in [\"B-MODEL\", \"B-BRAND\", \"B-PRODUCTNAME\"]:\n new_label = \"B-ENTITY\"\n elif items[-1] in [\"I-MODEL\", \"I-BRAND\", \"I-PRODUCTNAME\"]:\n new_label = \"I-ENTITY\"\n else:\n new_label = \"O\"\n taglist.append(new_label)\n\n if len(wlist) > 0:\n file_word.write(\" \".join(wlist) + \"\\n\")\n file_tag.write(\" \".join(taglist) + \"\\n\")\n\n\nif __name__ == \"__main__\":\n stdopinion = 10000\n # data_dir = \"E:/nlp_experiment/typical_opinion_extract/sequence_label/\"\n data_dir = \"E:/nlp_experiment/auto-ner/gpu/\"\n\n # trans_zero_one_label(\"D:/workspace/tensorflow/tf_ner/data/example/train.tags.txt\",\n # \"D:/workspace/tensorflow/tf_ner/data/example/train.tags01.txt\")\n\n trans_zero_one_label(\"/data/kongyy/nlp/tf_ner_guillaumegenthial/example/10002/train.tags.txt\",\n \"/data/kongyy/nlp/tf_ner_guillaumegenthial/example/10002/train.tags01.txt\")\n\n trans_zero_one_label(\"/data/kongyy/nlp/tf_ner_guillaumegenthial/example/10002/test.tags.txt\",\n \"/data/kongyy/nlp/tf_ner_guillaumegenthial/example/10002/test.tags01.txt\")\n\n # for data_type in [\"test\", \"train\"]:\n # if len(str(stdopinion)) == 0:\n # trans2entity_label(data_dir + \"{}.txt\".format(data_type),\n # data_dir + \"{}.words.txt\".format(data_type),\n # data_dir + \"{}.tags.txt\".format(data_type),\n # )\n # else:\n # trans2entity_label(data_dir + \"{}/{}.txt\".format(stdopinion, data_type),\n # data_dir + \"{}/{}.words.txt\".format(stdopinion, data_type),\n # data_dir + \"{}/{}.tags.txt\".format(stdopinion, data_type),\n # )\n\n # trans_pred(data_dir + \"{}/{}.preds.txt\".format(stdopinion, data_type),\n # data_dir + \"{}/{}.ptags.txt\".format(stdopinion, data_type),\n # data_dir + \"{}/{}.words.txt\".format(stdopinion, data_type)\n # )\n","sub_path":"data/example/trans_conll_to_this.py","file_name":"trans_conll_to_this.py","file_ext":"py","file_size_in_byte":7727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"115180677","text":"# -*- coding: utf-8 -*-\nfrom __future__ import annotations\n\nfrom math import cos, degrees, radians, sin, tau\n\nfrom pygerber.mathclasses import Vector2D, angle_from_zero\nfrom pygerber.renderer.spec import ArcSpec\n\n\nclass ArcUtilMixin:\n @property\n def isCCW(self):\n return self.renderer.isCCW()\n\n def get_begin_end_angles(self, spec: ArcSpec):\n begin_relative = spec.begin - spec.center\n end_relative = spec.end - spec.center\n begin_angle = degrees(angle_from_zero(begin_relative))\n end_angle = degrees(angle_from_zero(end_relative))\n if begin_angle >= end_angle:\n end_angle += 360\n return begin_angle, end_angle\n\n def get_arc_points(self, spec: ArcSpec, is_ccw: bool) -> Vector2D:\n begin_angle, end_angle = self.get_begin_end_angles(spec)\n radius = spec.get_radius()\n x, y = self.get_arc_co_functions(radius)\n delta = self.get_arc_traverse_step_angle(begin_angle, end_angle, radius)\n if is_ccw:\n return self.__get_arc_points_ccw(end_angle, begin_angle, x, spec, y, delta)\n else:\n return self.__get_arc_points_cw(end_angle, begin_angle, x, spec, y, delta)\n\n def get_arc_traverse_step_angle(self, begin_angle, end_angle, radius):\n raise NotImplementedError(\n \"get_arc_traverse_step_angle() have to be implemented in subclass.\"\n )\n\n def __get_arc_points_ccw(self, end_angle, begin_angle, x, spec, y, delta):\n end_relative_angle = end_angle - begin_angle\n angle_offset = begin_angle\n current_angle = 0\n while current_angle <= end_relative_angle:\n yield Vector2D(\n x(current_angle + angle_offset) + spec.center.x,\n y(current_angle + angle_offset) + spec.center.y,\n )\n current_angle += delta\n\n def __get_arc_points_cw(self, end_angle, begin_angle, x, spec, y, delta):\n end_relative_angle = end_angle - begin_angle\n angle_offset = begin_angle\n current_angle = 360\n while current_angle >= end_relative_angle:\n yield Vector2D(\n x(current_angle + angle_offset) + spec.center.x,\n y(current_angle + angle_offset) + spec.center.y,\n )\n current_angle -= delta\n\n @staticmethod\n def get_arc_co_functions(radius):\n def x(alpha):\n return radius * cos(radians(alpha))\n\n def y(alpha):\n return radius * sin(radians(alpha))\n\n return x, y\n\n @staticmethod\n def get_arc_length(radius) -> float:\n return tau * radius\n\n @staticmethod\n def get_arc_ratio(relative_angle):\n return relative_angle / 360\n\n @staticmethod\n def get_relative_angle(begin_angle, end_angle):\n return end_angle - begin_angle\n","sub_path":"src/pygerber/renderer/arc_util_mixin.py","file_name":"arc_util_mixin.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"34940587","text":"\n\nfrom xai.brain.wordbase.nouns._dogma import _DOGMA\n\n#calss header\nclass _DOGMAS(_DOGMA, ):\n\tdef __init__(self,): \n\t\t_DOGMA.__init__(self)\n\t\tself.name = \"DOGMAS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"dogma\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_dogmas.py","file_name":"_dogmas.py","file_ext":"py","file_size_in_byte":231,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"190175717","text":"from tkinter import *\nimport os\nfrom time import gmtime, strftime\nimport cv2\nimport csv\n\ncsv_data = []\n\nclass Window(Frame):\n\n def __init__(self, master=None):\n \n Frame.__init__(self, master) \n \n self.master = master\n\n self.init_window()\n\n #Creation of init_window\n def init_window(self):\n\n self.master.title(\"Parking Spot Predictor\")\n self.pack(fill=BOTH, expand=1)\n\n listOfCsvFiles = os.listdir(\"Choose_Parking_Spots/csv\")\n\n self.variable = StringVar(self)\n self.variable.set(listOfCsvFiles[0])\n\n self.MenuCSV = OptionMenu(self, self.variable, * listOfCsvFiles)\n self.MenuCSV.pack()\n\n ButtonSubmit = Button(self, text=\"Use This Setting\", command=self.Submit)\n ButtonSubmit.pack()\n\n def Submit(self):\n global csv_data\n csv_data = self.variable.get()\n print(csv_data)\n saveCSVData()\n exit()\n \n#Save CSV Data\ndef saveCSVData():\n global csv_data\n with open('Choose_Parking_Spots/currentUsed.csv','w') as fp:\n writer = csv.writer(fp, delimiter=',')\n writer.writerows(csv_data)\n\n#Display Menu\nroot = Tk()\nroot.geometry(\"200x120\")\napp = Window(root)\nroot.mainloop() \n\n\n","sub_path":"Choose_CSV/choose_csv.py","file_name":"choose_csv.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"292608894","text":"from collections import OrderedDict\nfrom itertools import groupby\nimport calendar\nimport hashlib\nfrom datetime import time as std_time\nfrom cacheops import cached\nfrom django.core import signing\nfrom django.db.models import Count\nimport monthdelta\nimport json\nimport time\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse, reverse_lazy\nfrom django.db import connection\nfrom django.http import HttpResponseRedirect\nfrom django.utils import timezone\nfrom django.utils.text import slugify\nfrom django.utils.timezone import datetime, timedelta\nfrom django.contrib.admin.views.decorators import staff_member_required\nfrom django.views.generic import DeleteView, TemplateView\nfrom django.views.generic.list import ListView\nfrom django.views.generic.detail import DetailView, BaseDetailView\n\nfrom django_ajax.mixin import AJAXMixin\nfrom braces.views import LoginRequiredMixin, SuperuserRequiredMixin, StaffuserRequiredMixin\nfrom extra_views import CreateWithInlinesView, NamedFormsetsMixin, UpdateWithInlinesView\nfrom haystack.query import SearchQuerySet, RelatedSearchQuerySet\nfrom haystack.views import SearchView\nfrom rest_framework.authtoken.models import Token\n\nfrom artists.models import Artist, Instrument\nfrom metrics.models import UserVideoMetric\nfrom oscar_apps.catalogue.models import Product\nfrom search.utils import facets_by_model_name\nfrom .forms import EventAddForm, GigPlayedAddInlineFormSet, GigPlayedInlineFormSetHelper, GigPlayedEditInlineFormset, \\\n EventSearchForm, EventEditForm\nfrom .models import Event, Recording\n\n\nclass HomepageView(ListView):\n template_name = 'home.html'\n context_object_name = 'events_today'\n\n def get_queryset(self):\n date_range_start = timezone.localtime(timezone.now()).replace(hour=5, minute=0)\n date_range_end = date_range_start + timedelta(days=1)\n return Event.objects.filter(start__gte=date_range_start, start__lte=date_range_end).order_by('start')\n\n def get_context_data(self, **kwargs):\n context = super(HomepageView, self).get_context_data(**kwargs)\n date_range_start = timezone.localtime(timezone.now())\n # if it's not night when events are still hapenning, show next day\n if date_range_start.hour > 6:\n date_range_start += timedelta(days=1)\n # don't show last nights events that are technically today\n date_range_start = date_range_start.replace(hour=10)\n events = Event.objects.filter(start__gte=date_range_start).order_by('start')\n if not self.request.user.is_staff:\n events = events.exclude(state=Event.STATUS.Draft)\n # 30 events should be enough to show next 7 days with events\n events = events[:30]\n dates = {}\n for k, g in groupby(events, lambda e: e.listing_date()):\n dates[k] = list(g)\n # next 7 days\n sorted_dates = OrderedDict(sorted(dates.items(), key=lambda d: d[0])).items()[:7]\n context['new_in_archive'] = Event.objects.most_recent()[:8]\n context['next_7_days'] = sorted_dates\n\n @cached(timeout=6*60*60)\n def _get_most_popular():\n context = {}\n most_popular_ids = UserVideoMetric.objects.most_popular(count=4, weekly=True)\n most_popular = []\n for event_data in most_popular_ids:\n try:\n event = Event.objects.get(id=event_data['event_id'])\n most_popular.append(event)\n except Event.DoesNotExist:\n pass\n context['popular_in_archive'] = most_popular\n return context\n\n context.update(_get_most_popular())\n context['popular_in_store'] = Product.objects.filter(featured=True, product_class__slug='album')[:6]\n return context\n\nhomepage = HomepageView.as_view()\n\n\nclass EventAddView(StaffuserRequiredMixin, NamedFormsetsMixin, CreateWithInlinesView):\n template_name = 'events/event_add.html'\n model = Event\n form_class = EventAddForm\n inlines = [GigPlayedAddInlineFormSet]\n inlines_names = ['artists']\n\n def get_context_data(self, **kwargs):\n context = super(EventAddView, self).get_context_data(**kwargs)\n context['artists'].helper = GigPlayedInlineFormSetHelper()\n context['show_times'] = json.dumps(settings.SHOW_TIMES)\n return context\n\nevent_add = EventAddView.as_view()\n\n\nclass EventDetailView(DetailView):\n queryset = Event.objects.all().select_related('recording', 'recording__media_file')\n context_object_name = 'event'\n template_name = 'events/event_details_new.html'\n\n def get_context_data(self, **kwargs):\n context = super(EventDetailView, self).get_context_data(**kwargs)\n context['performers'] = self.object.get_performers()\n context['facebook_app_id'] = settings.FACEBOOK_APP_ID\n context['metrics_ping_interval'] = settings.PING_INTERVAL\n context['metrics_server_url'] = settings.METRICS_SERVER_URL\n context['metrics_signed_data'] = self._generate_metrics_data()\n if self.request.user.is_authenticated():\n context['user_token'] = Token.objects.get(user=self.request.user)\n user_is_artist = self.request.user.is_artist and self.request.user.artist in self.object.performers.all()\n user_is_staff = self.request.user.is_staff\n if user_is_artist or user_is_staff:\n context['count_metrics'] = False\n else:\n context['count_metrics'] = True\n return context\n\n def _generate_metrics_data(self):\n data = {}\n for rec in self.object.recordings.all():\n rec_data = {\n 'recording_id': rec.id,\n 'recording_type': rec.media_file.media_type.upper()[0],\n 'event_id': self.object.id,\n 'user_id': self.request.user.id,\n }\n signed_value = signing.dumps(rec_data)\n data[rec.id] = signed_value\n return data\n\nevent_detail = EventDetailView.as_view()\n\n\nclass EventEditView(NamedFormsetsMixin, UpdateWithInlinesView):\n model = Event\n form_class = EventEditForm\n template_name = 'events/event_edit.html'\n inlines = [GigPlayedEditInlineFormset]\n inlines_names = ['artists']\n\n def get_context_data(self, **kwargs):\n context = super(EventEditView, self).get_context_data(**kwargs)\n context['artists'].helper = GigPlayedInlineFormSetHelper()\n context['show_times'] = json.dumps(settings.SHOW_TIMES)\n return context\n\n\n # def test_func(self, user):\n # \"\"\"\n # Show 403 forbidden page only when the logged in user doesn't have required\n # permissions, redirect anonymous users to the login screen.\n # \"\"\"\n # self.raise_exception = True\n # try:\n # artist_id_match = self.kwargs.get('pk') == str(user.artist.id)\n # except Artist.DoesNotExist:\n # artist_id_match = False\n # return (artist_id_match or user.is_superuser)\n\nevent_edit = staff_member_required(EventEditView.as_view())\n\n\nclass EventDeleteView(StaffuserRequiredMixin, DeleteView):\n model = Event\n success_url = reverse_lazy('home')\n\nevent_delete = EventDeleteView.as_view()\n\n\nclass EventCloneView(StaffuserRequiredMixin, BaseDetailView):\n model = Event\n\n def post(self, request, *args, **kwargs):\n self.object = self.get_object()\n old_event_id = self.object.id\n gig_info = self.object.get_performers()\n new_object = self.object\n new_object.pk = None\n new_object.state = Event.STATUS.Draft\n new_object.save()\n for info in gig_info:\n info.pk = None\n info.event = new_object\n info.save()\n self.extra_event_processing(new_object, old_event_id)\n self.new_object = new_object\n return HttpResponseRedirect(self.get_success_url())\n\n def get_success_url(self):\n return reverse('event_edit', kwargs={'pk': self.new_object.id, 'slug': slugify(self.new_object.title)})\n\n def extra_event_processing(self, event, old_event_id):\n \"\"\"\n Overridable method meant for extra event processing such as cloning the tickets or doing\n some other manipulation on the newly cloned event object.\n \"\"\"\n pass\n\nevent_clone = EventCloneView.as_view()\n\n\nclass EventSearchView(SearchView):\n template = 'search/event_search.html'\n\n def extra_context(self):\n context = {}\n paginator, page = self.build_page()\n adjacent_pages = 2\n startPage = max(page.number - adjacent_pages, 1)\n if startPage <= 3:\n startPage = 1\n endPage = page.number + adjacent_pages + 1\n if endPage >= paginator.num_pages - 1:\n endPage = paginator.num_pages + 1\n page_numbers = [n for n in xrange(startPage, endPage) if n > 0 and n <= paginator.num_pages]\n context.update({\n 'page_numbers': page_numbers,\n 'show_first': 1 not in page_numbers,\n 'show_last': paginator.num_pages not in page_numbers,\n })\n\n context['counts'] = facets_by_model_name(self.sqs)\n\n artist_id = self.request.GET.get('artist')\n if artist_id:\n search_term = Artist.objects.get(id=artist_id).full_name()\n else:\n search_term = self.request.GET.get('q')\n context['search_term'] = search_term\n\n return context\n\n def get_results(self):\n self.sqs = super(EventSearchView, self).get_results().facet('model', order='term').order_by('-start')\n sqs = self.sqs.models(Event).load_all_queryset(Event, Event.objects.all().annotate(product_count=Count('products')).extra(select={\n 'video_count': \"SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE \"\n \"events_recording.event_id = events_event. ID AND \"\n \"events_recording.media_file_id = multimedia_mediafile. ID AND \"\n \" events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='video'\"\n \" GROUP BY events_event.id\",\n 'audio_count': \"SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE \"\n \"events_recording.event_id = events_event. ID AND \"\n \"events_recording.media_file_id = multimedia_mediafile. ID AND \"\n \" events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='audio'\"\n \" GROUP BY events_event.id\",\n }))\n return sqs\n\n\nevent_search = EventSearchView(\n form_class=EventSearchForm,\n searchqueryset=RelatedSearchQuerySet()\n)\n\n\nclass ScheduleView(ListView):\n context_object_name = 'dates'\n template_name = 'events/schedule.html'\n\n def get_queryset(self):\n \"\"\"\n The view returns a list of events in two week intervals, for both the home page\n and the \"next\" links. The correct two week interval is set through the URL or by\n default it's a two week interval from the current date. The admin user sees all future\n events immediately, regardless of date intervals and event status.\n \"\"\"\n dates = {}\n two_week_interval = int(self.request.GET.get('week', 0))\n start_days = two_week_interval * 14\n date_range_start = timezone.localtime(timezone.now()) + timezone.timedelta(days=start_days)\n # don't show last nights events that are technically today\n date_range_start = date_range_start.replace(hour=10)\n self.date_start = date_range_start\n date_range_end = date_range_start + timezone.timedelta(days=14)\n events = Event.objects.filter(start__gte=date_range_start, start__lte=date_range_end).order_by('start')\n if not self.request.user.is_staff:\n events = events.exclude(state=Event.STATUS.Draft)\n\n events = events.annotate(product_count=Count('products')).extra(select={\n 'video_count': \"SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE \"\n \"events_recording.event_id = events_event. ID AND \"\n \"events_recording.media_file_id = multimedia_mediafile. ID AND \"\n \" events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='video'\"\n \" GROUP BY events_event.id\",\n 'audio_count': \"SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE \"\n \"events_recording.event_id = events_event. ID AND \"\n \"events_recording.media_file_id = multimedia_mediafile. ID AND \"\n \" events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='audio'\"\n \" GROUP BY events_event.id\",\n })\n for k, g in groupby(events, lambda e: e.listing_date()):\n dates[k] = list(g)\n for date in [(date_range_start + timedelta(days=d)).date() for d in range(14)]:\n if date not in dates:\n dates[date] = []\n sorted_dates = OrderedDict(sorted(dates.items(), key=lambda d: d[0]))\n return sorted_dates\n\n def get_context_data(self, **kwargs):\n context = super(ScheduleView, self).get_context_data(**kwargs)\n # js months are zero indexed\n context['month'] = self.date_start.month - 1\n context['year'] = self.date_start.year\n week = int(self.request.GET.get('week', 0))\n if week != 1:\n context['prev_url'] = \"{0}?week={1}\".format(reverse('schedule'), week-1)\n else:\n context['prev_url'] = reverse('schedule')\n if week == -1:\n context['next_url'] = reverse('schedule')\n else:\n context['next_url'] = \"{0}?week={1}\".format(reverse('schedule'), week+1)\n return context\n\nschedule = ScheduleView.as_view()\n\n\nclass MonthlyScheduleView(ListView):\n context_object_name = 'dates'\n template_name = 'events/schedule.html'\n\n def get_queryset(self):\n dates = {}\n month = int(self.kwargs.get('month', timezone.now().month))\n year = int(self.kwargs.get('year', timezone.now().year))\n # don't show last nights events that are technically today\n date_range_start = timezone.make_aware(timezone.datetime(year, month, 1, hour=10),\n timezone.get_default_timezone())\n date_range_end = date_range_start + monthdelta.MonthDelta(1)\n last_day_of_month = calendar.monthrange(year, month)[1]\n events = Event.objects.filter(start__range=(date_range_start, date_range_end)).order_by('start')\n if not self.request.user.is_staff:\n events = events.exclude(state=Event.STATUS.Draft)\n events = events.annotate(product_count=Count('products')).extra(select={\n 'video_count': \"SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE \"\n \"events_recording.event_id = events_event. ID AND \"\n \"events_recording.media_file_id = multimedia_mediafile. ID AND \"\n \" events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='video'\"\n \" GROUP BY events_event.id\",\n 'audio_count': \"SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE \"\n \"events_recording.event_id = events_event. ID AND \"\n \"events_recording.media_file_id = multimedia_mediafile. ID AND \"\n \" events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='audio'\"\n \" GROUP BY events_event.id\",\n })\n for k, g in groupby(events, lambda e: e.listing_date()):\n dates[k] = list(g)\n for date in [(date_range_start + timedelta(days=d)).date() for d in range(last_day_of_month)]:\n if date not in dates:\n dates[date] = []\n sorted_dates = OrderedDict(sorted(dates.items(), key=lambda d: d[0]))\n return sorted_dates\n\n def get_context_data(self, **kwargs):\n \"\"\"\n Timedelta doesn't support months so to get the next and previous months, we do a max delta (31 days) for the\n next month, and a min one (1 day) for the previous month.\n \"\"\"\n context = super(MonthlyScheduleView, self).get_context_data(**kwargs)\n # js months are zero indexed\n month = int(self.kwargs.get('month', timezone.now().month))\n year = int(self.kwargs.get('year', timezone.now().year))\n context['month'] = month - 1\n context['year'] = year\n context['month_view'] = True\n # position of the \"NEXT\" box, after all the dates and the \"PREV\" box\n context['next_month_position'] = len(context['dates']) + 2\n current_month = timezone.datetime(year=year, month=month, day=1)\n next_month = current_month + timezone.timedelta(days=31)\n prev_month = current_month - timezone.timedelta(days=1)\n context['prev_url'] = reverse('monthly_schedule', kwargs={'year': prev_month.year, 'month': prev_month.month})\n context['next_url'] = reverse('monthly_schedule', kwargs={'year': next_month.year, 'month': next_month.month})\n return context\n\nmonthly_schedule = MonthlyScheduleView.as_view()\n\n\nclass ScheduleCarouselAjaxView(AJAXMixin, DetailView):\n context_object_name = 'event'\n model = Event\n template_name = \"blocks/schedule-event-details-carousel.html\"\n\nschedule_carousel_ajax = ScheduleCarouselAjaxView.as_view()\n\n\nclass HomepageEventCarouselAjaxView(AJAXMixin, ListView):\n context_object_name = 'events'\n template_name = \"blocks/homepage-upcoming-events-carousel.html\"\n\n def get_queryset(self):\n date = self.request.GET.get('date')\n if date and date != \"undefined\":\n date = timezone.make_aware(datetime.strptime(date, \"%m/%d/%Y\").replace(hour=6, minute=0),\n timezone.get_current_timezone())\n end_range_date = date + timedelta(days=1)\n events = Event.objects.filter(start__range=(date, end_range_date)).order_by('start')\n if not self.request.user.is_staff:\n events = events.exclude(state=Event.STATUS.Draft)\n return events\n return Event.objects.none()\n\n def get_context_data(self, **kwargs):\n context = super(HomepageEventCarouselAjaxView, self).get_context_data(**kwargs)\n if self.request.GET.get(\"template\") == \"home\":\n start = timezone.localtime(timezone.now()) - timedelta(hours=4)\n context['dates'] = [start + timedelta(days=d) for d in range(5)]\n return context\n\nevent_carousel_ajax = HomepageEventCarouselAjaxView.as_view()\n\n\nclass LiveStreamView(ListView):\n context_object_name = \"events\"\n template_name = \"events/live-stream.html\"\n\n def get_queryset(self):\n now = timezone.localtime(timezone.now())\n tomorrow = now\n if not now.hour < 6:\n tomorrow = now + timedelta(days=1)\n tomorrow = tomorrow.replace(hour=6)\n events = list(Event.objects.public().filter(end__gte=now,\n start__lte=tomorrow).order_by('start'))\n return events\n\n def get_context_data(self, **kwargs):\n now = timezone.localtime(timezone.now())\n context = super(LiveStreamView, self).get_context_data(**kwargs)\n TRESHOLD = 30\n # also include todays events that have finished\n if now.hour < 6:\n start_range = (now - timedelta(days=1)).replace(hour=6)\n end_range = now.replace(hour=6)\n\n else:\n start_range = now.replace(hour=6)\n end_range = (now + timedelta(days=1)).replace(hour=6)\n todays_events = Event.objects.public().filter(start__gte=start_range,\n start__lte=end_range).order_by('start')\n # currently playing or future events, showed for displaying \"coming up\"\n if context['events'] and context['events'][0].has_started():\n context['currently_playing'] = context['events'].pop(0)\n\n context['first_future_show'] = Event.objects.filter(start__gte=timezone.now()).order_by('start').first()\n\n return context\n\nlive_stream = LiveStreamView.as_view()\n\n\nclass MezzrowLiveStreamView(TemplateView):\n template_name = 'events/live-stream-mezzrow.html'\n\n def get_context_data(self, **kwargs):\n context = super(MezzrowLiveStreamView, self).get_context_data(**kwargs)\n now = timezone.localtime(timezone.now())\n stream_turn_off_hour = 2\n stream_turn_on_hour = 17\n context['hide_stream'] = stream_turn_off_hour <= now.hour <= stream_turn_on_hour\n return context\n\nlive_stream_mezzrow = MezzrowLiveStreamView.as_view()\n\n\nclass ArchiveView(ListView):\n template_name = \"events/archive.html\"\n context_object_name = 'date_events'\n\n def get_queryset(self):\n two_week_interval = int(self.request.GET.get('week', 0)) * 14\n\n cursor = connection.cursor()\n cursor.execute('SELECT DISTINCT(e.start::date) FROM \"events_event\" AS e INNER JOIN \"events_recording\" AS rec'\n ' ON e.id=rec.event_id WHERE date_part(\\'hour\\', e.start) > 12 ORDER BY start DESC LIMIT 14 OFFSET %s', [two_week_interval])\n dates = [d[0] for d in cursor.fetchall()]\n date_range_start = datetime.combine(dates[-1], std_time(10, 0))\n self.date_start = date_range_start\n date_range_end = dates[0] + timedelta(days=1)\n date_range_end = datetime.combine(date_range_end, std_time(4, 0))\n events = Event.objects.exclude(recordings=None).filter(start__gte=date_range_start, start__lte=date_range_end).order_by('start')\n if not self.request.user.is_staff:\n events = events.exclude(state=Event.STATUS.Draft)\n\n events = events.annotate(product_count=Count('products')).extra(select={\n 'video_count': \"SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE \"\n \"events_recording.event_id = events_event. ID AND \"\n \"events_recording.media_file_id = multimedia_mediafile. ID AND \"\n \" events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='video'\"\n \" GROUP BY events_event.id\",\n 'audio_count': \"SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE \"\n \"events_recording.event_id = events_event. ID AND \"\n \"events_recording.media_file_id = multimedia_mediafile. ID AND \"\n \" events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='audio'\"\n \" GROUP BY events_event.id\",\n })\n dates = {}\n for k, g in groupby(events, lambda e: e.listing_date()):\n dates[k] = list(g)\n sorted_dates = OrderedDict(sorted(dates.items(), key=lambda d: d[0])).items()\n return sorted_dates\n\n def get_context_data(self, **kwargs):\n context = super(ArchiveView, self).get_context_data(**kwargs)\n\n @cached(timeout=6*60*60)\n def _get_most_popular():\n context = {}\n context['most_recent'] = Event.objects.most_recent()[:12]\n\n weekly_most_popular_ids = UserVideoMetric.objects.most_popular(count=12, weekly=False)\n weekly_most_popular = []\n for event_data in weekly_most_popular_ids:\n try:\n event = Event.objects.get(id=event_data['event_id'])\n weekly_most_popular.append(event)\n except Event.DoesNotExist:\n pass\n context['most_popular'] = weekly_most_popular\n\n return context\n\n context['month'] = self.date_start.month - 1\n context['year'] = self.date_start.year\n context.update(_get_most_popular())\n context.update(self.get_pagination())\n return context\n\n def get_pagination(self):\n context = {}\n week = int(self.request.GET.get('week', 0))\n context['prev_url'] = \"{0}?week={1}\".format(reverse('archive'), week + 1)\n if week > 1:\n context['next_url'] = \"{0}?week={1}\".format(reverse('archive'), week - 1)\n else:\n context['next_url'] = reverse('archive')\n return context\n\n\narchive = ArchiveView.as_view()\n\n\nclass MonthlyArchiveView(ArchiveView):\n def get_queryset(self):\n dates = {}\n month = int(self.kwargs.get('month', timezone.now().month))\n year = int(self.kwargs.get('year', timezone.now().year))\n # don't show last nights events that are technically today\n date_range_start = timezone.make_aware(timezone.datetime(year, month, 1, hour=10),\n timezone.get_default_timezone())\n self.date_start = date_range_start\n date_range_end = date_range_start + monthdelta.MonthDelta(1)\n events = Event.objects.exclude(recordings=None).filter(start__range=(date_range_start, date_range_end)).order_by('start')\n if not self.request.user.is_staff:\n events = events.exclude(state=Event.STATUS.Draft)\n events = events.annotate(product_count=Count('products')).extra(select={\n 'video_count': \"SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE \"\n \"events_recording.event_id = events_event. ID AND \"\n \"events_recording.media_file_id = multimedia_mediafile. ID AND \"\n \" events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='video'\"\n \" GROUP BY events_event.id\",\n 'audio_count': \"SELECT COUNT(*) FROM events_recording, multimedia_mediafile WHERE \"\n \"events_recording.event_id = events_event. ID AND \"\n \"events_recording.media_file_id = multimedia_mediafile. ID AND \"\n \" events_recording. STATE = 'Published' AND multimedia_mediafile.media_type='audio'\"\n \" GROUP BY events_event.id\",\n })\n for k, g in groupby(events, lambda e: e.listing_date()):\n dates[k] = list(g)\n sorted_dates = OrderedDict(sorted(dates.items(), key=lambda d: d[0])).items()\n return sorted_dates\n\n def get_pagination(self):\n context = {}\n # js months are zero indexed\n month = int(self.kwargs.get('month', timezone.now().month))\n year = int(self.kwargs.get('year', timezone.now().year))\n context['month'] = month - 1\n context['year'] = year\n context['month_view'] = True\n # position of the \"NEXT\" box, after all the dates and the \"PREV\" box\n current_month = timezone.datetime(year=year, month=month, day=1)\n next_month = current_month + timezone.timedelta(days=31)\n prev_month = current_month - timezone.timedelta(days=1)\n context['prev_url'] = reverse('monthly_archive', kwargs={'year': prev_month.year, 'month': prev_month.month})\n context['next_url'] = reverse('monthly_archive', kwargs={'year': next_month.year, 'month': next_month.month})\n return context\n\nmonthly_archive = MonthlyArchiveView.as_view()\n","sub_path":"smallslive/events/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":27482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"13746281","text":"\"\"\"Dataset utils for preparing data for the network.\"\"\"\nimport sys\n#print(sys.path)\n\n#sys.path.remove('/opt/ros/kinetic/lib/python2.7/dist-packages')\nimport itertools\nimport fnmatch\nimport os\n\nimport numpy as np\nimport cv2\n\nfrom wavedata.tools.core import moose_load_calibration\nfrom wavedata.tools.obj_detection import obj_utils\n\nfrom avod.core import box_3d_encoder\nfrom avod.core import constants\nfrom avod.datasets.kitti import kitti_aug\nfrom avod.datasets.kitti.kitti_utils import KittiUtils\n\n\n\nclass Sample:\n def __init__(self, name, augs):\n self.name = name\n self.augs = augs\n\n\nclass MooseDataset:\n def __init__(self, dataset_config):\n\n\n \"\"\"\n Initializes directories, and loads the sample list\n\n Args:\n dataset_config: KittiDatasetConfig\n name: unique name for the dataset\n data_split: \"train\", \"val\", \"test\", \"trainval\"\n data_split_dir: must be specified for custom \"training\"\n dataset_dir: Kitti dataset dir if not in default location\n classes: relevant classes\n num_clusters: number of k-means clusters to separate for\n each class\n \"\"\"\n # Parse config\n self.config = dataset_config\n\n self.name = self.config.name\n self.data_split = self.config.data_split\n #self.dataset_dir = os.path.expanduser(self.config.dataset_dir)\n self.dataset_dir = '/media/wavelab/d3cd89ab-7705-4996-94f3-01da25ba8f50/moosey'\n\n data_split_dir = self.config.data_split_dir\n\n self.has_labels = self.config.has_labels\n self.cluster_split = self.config.cluster_split\n\n self.classes = list(self.config.classes)\n self.num_classes = len(self.classes)\n self.num_clusters = np.asarray(self.config.num_clusters)\n\n self.bev_source = self.config.bev_source\n self.aug_list = self.config.aug_list\n\n # Determines the network mode. This is initialized to 'train' but\n # is overwritten inside the model based on the mode.\n self.train_val_test = 'train'\n # Determines if training includes all samples, including the ones\n # without anchor_info. This is initialized to False, but is overwritten\n # via the config inside the model.\n self.train_on_all_samples = False\n\n self._set_up_classes_name()\n\n # Check that paths and split are valid\n self._check_dataset_dir()\n\n # Get all files and folders in dataset directory\n all_files = os.listdir(self.dataset_dir)\n\n # Get possible data splits from txt files in dataset folder\n possible_splits = []\n for file_name in all_files:\n if fnmatch.fnmatch(file_name, '*.txt'):\n possible_splits.append(os.path.splitext(file_name)[0])\n # This directory contains a readme.txt file, remove it from the list\n if 'readme' in possible_splits:\n possible_splits.remove('readme')\n\n\n if self.data_split not in possible_splits:\n print(\"This is the data_split\")\n print(self.data_split)\n print(\"This is the possible splits\")\n print(possible_splits)\n raise ValueError(\"Invalid data split: {}, possible_splits: {}\"\n .format(self.data_split, possible_splits))\n\n # Check data_split_dir\n # Get possible data split dirs from folder names in dataset folder\n possible_split_dirs = []\n for folder_name in all_files:\n if os.path.isdir(self.dataset_dir + '/' + folder_name):\n possible_split_dirs.append(folder_name)\n if data_split_dir in possible_split_dirs:\n split_dir = self.dataset_dir + '/' + data_split_dir\n self._data_split_dir = split_dir\n else:\n raise ValueError(\n \"Invalid data split dir: {}, possible dirs\".format(\n data_split_dir, possible_split_dirs))\n\n # Batch pointers\n self._index_in_epoch = 0\n self.epochs_completed = 0\n\n #self._cam_idx =00 #moose's front camera\n\n # Initialize the sample list\n loaded_sample_names = self.load_sample_names(self.data_split)\n\n # Augment the sample list\n aug_sample_list = []\n\n # Loop through augmentation lengths e.g.\n # 0: []\n # 1: ['flip'], ['pca_jitter']\n # 2: ['flip', 'pca_jitter']\n for aug_idx in range(len(self.aug_list) + 1):\n # Get all combinations\n augmentations = list(itertools.combinations(self.aug_list,\n aug_idx))\n for augmentation in augmentations:\n for sample_name in loaded_sample_names:\n aug_sample_list.append(Sample(sample_name, augmentation))\n\n self.sample_list = np.asarray(aug_sample_list)\n self.num_samples = len(self.sample_list)\n\n self._set_up_directories()\n\n\n # Setup utils object\n self.kitti_utils = KittiUtils(self)\n\n # Paths\n @property\n def rgb_image_dir(self):\n return self.image_dir\n\n @property\n def sample_names(self):\n # This is a property since the sample list gets shuffled for training\n return np.asarray(\n [sample.name for sample in self.sample_list])\n\n @property\n def bev_image_dir(self):\n raise NotImplementedError(\"BEV images not saved to disk yet!\")\n\n def _check_dataset_dir(self):\n \"\"\"Checks that dataset directory exists in the file system\n\n Raises:\n FileNotFoundError: if the dataset folder is missing\n \"\"\"\n # Check that dataset path is valid\n if not os.path.exists(self.dataset_dir):\n raise FileNotFoundError('Dataset path does not exist: {}'\n .format(self.dataset_dir))\n\n def _set_up_directories(self):\n \"\"\"Sets up data directories.\"\"\"\n # Setup Directories\n self.image_dir = self._data_split_dir + '/image' #+ str(self._cam_idx)\n self.calib_dir = self._data_split_dir + '/calibmoose' #think about this\n #self.disp_dir = self._data_split_dir + '/disparity'\n self.planes_dir = self._data_split_dir + '/filtered_planes'\n self.velo_dir = self._data_split_dir + '/filtered_lidar_points/data/filtered_'\n self.depth_dir = '/media/wavelab/d3cd89ab-7705-4996-94f3-01da25ba8f50/avod-master/outputs/obj/filtered_3_snow_depth_moose_multiscale' #+ str(self._cam_idx)\n\n\n # Labels are always in the training folder\n self.label_dir = self._data_split_dir+ \\\n '/annotation'\n #+ str(self._cam_idx)\n\n def _set_up_classes_name(self):\n # Unique identifier for multiple classes\n if self.num_classes > 1:\n if self.classes == ['Pedestrian', 'Cyclist']:\n self.classes_name = 'People'\n elif self.classes == ['Car', 'Pedestrian', 'Cyclist']:\n self.classes_name = 'All'\n else:\n raise NotImplementedError('Need new unique identifier for '\n 'multiple classes')\n else:\n self.classes_name = self.classes[0]\n\n # Get sample paths\n def get_rgb_image_path(self, sample_name):\n return self.rgb_image_dir + '/' + sample_name + '.png'\n\n def get_depth_map_path(self, sample_name):\n return self.depth_dir + '/' + sample_name + '_left_depth.png' #what's this\n\n def get_velodyne_path(self, sample_name):\n return self.velo_dir + '/' + sample_name + '.bin'\n\n def get_bev_sample_path(self, sample_name):\n return self.bev_image_dir + '/' + sample_name + '.png' #what's this\n\n # Cluster info\n def get_cluster_info(self):\n return self.kitti_utils.clusters, self.kitti_utils.std_devs\n\n def get_anchors_info(self, sample_name):\n return self.kitti_utils.get_anchors_info(\n self.classes_name,\n self.kitti_utils.anchor_strides,\n sample_name)\n\n # Data loading methods\n def load_sample_names(self, data_split):\n \"\"\"Load the sample names listed in this dataset's set file\n (e.g. train.txt, validation.txt)\n\n Args:\n data_split: override the sample list to load (e.g. for clustering)\n\n Returns:\n A list of sample names (file names) read from\n the .txt file corresponding to the data split\n \"\"\"\n set_file = self.dataset_dir + '/' + data_split + '.txt'\n with open(set_file, 'r') as f:\n sample_names = f.read().splitlines() #eg 00000000001\n print(sample_names)\n print(set_file)\n\n return np.array(sample_names)\n\n def load_samples(self, indices):\n \"\"\" Loads input-output data for a set of samples. Should only be\n called when a particular sample dict is required. Otherwise,\n samples should be provided by the next_batch function\n\n Args:\n indices: A list of sample indices from the dataset.sample_list\n to be loaded\n\n Return:\n samples: a list of data sample dicts\n \"\"\"\n sample_dicts = []\n for sample_idx in indices:\n sample = self.sample_list[sample_idx]\n sample_name = sample.name\n\n # Only read labels if they exist\n if self.has_labels:\n # Read mini batch first to see if it is empty\n anchors_info = self.get_anchors_info(sample_name)\n\n if (not anchors_info) and self.train_val_test == 'train' \\\n and (not self.train_on_all_samples):\n empty_sample_dict = {\n constants.KEY_SAMPLE_NAME: sample_name,\n constants.KEY_ANCHORS_INFO: anchors_info\n }\n return [empty_sample_dict]\n\n obj_labels = obj_utils.read_labels(self.label_dir,\n int(sample_name))\n\n # Only use objects that match dataset classes\n obj_labels = self.kitti_utils.filter_labels(obj_labels)\n\n else:\n obj_labels = None\n\n anchors_info = []\n\n label_anchors = np.zeros((1, 6))\n label_boxes_3d = np.zeros((1, 7))\n label_classes = np.zeros(1)\n\n img_idx = int(sample_name)\n\n # Load image (BGR -> RGB)\n cv_bgr_image = cv2.imread(self.get_rgb_image_path(\n sample_name))\n rgb_image = cv_bgr_image[..., :: -1]\n image_shape = rgb_image.shape[0:2]\n image_input = rgb_image\n\n # Get ground plane\n ground_plane = obj_utils.get_road_plane(int(sample_name),\n self.planes_dir)\n\n\n\n # Get calibration\n calib = moose_load_calibration.load_calibration(self.calib_dir)\n\n if img_idx < 100:\n\n\n\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM00']['camera_matrix']['data']).reshape(-1,3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3, 0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n stereo_calib_p2 = T_IMG_CAM\n\n elif (img_idx >= 100 and img_idx <200):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM01']['camera_matrix']['data']).reshape(-1,\n 3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n stereo_calib_p2 = T_IMG_CAM\n\n elif (img_idx >= 200 and img_idx <300):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM02']['camera_matrix']['data']).reshape(-1,\n 3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n stereo_calib_p2 = T_IMG_CAM\n\n elif (img_idx >= 300 and img_idx <400):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM03']['camera_matrix']['data']).reshape(-1,\n 3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n stereo_calib_p2 = T_IMG_CAM\n\n elif (img_idx >= 400 and img_idx <500):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM04']['camera_matrix']['data']).reshape(-1,\n 3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n stereo_calib_p2 = T_IMG_CAM\n\n elif (img_idx >= 500 and img_idx <600):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM05']['camera_matrix']['data']).reshape(-1,\n 3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n stereo_calib_p2 = T_IMG_CAM\n\n elif (img_idx >= 600 and img_idx <700):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM06']['camera_matrix']['data']).reshape(-1,\n 3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n stereo_calib_p2 = T_IMG_CAM\n\n elif (img_idx >= 700 and img_idx <800):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM07']['camera_matrix']['data']).reshape(-1,\n 3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n stereo_calib_p2 = T_IMG_CAM\n\n else:\n print(\"YOLO\")\n\n\n\n point_cloud = self.get_point_cloud('lidar', img_idx, image_shape) #possibly change this\n\n # Augmentation (Flipping)\n if kitti_aug.AUG_FLIPPING in sample.augs:\n image_input = kitti_aug.flip_image(image_input)\n point_cloud = kitti_aug.flip_point_cloud(point_cloud)\n obj_labels = [kitti_aug.flip_label_in_3d_only(obj)\n for obj in obj_labels]\n ground_plane = kitti_aug.flip_ground_plane(ground_plane)\n stereo_calib_p2 = kitti_aug.flip_stereo_calib_p2(\n stereo_calib_p2, image_shape)\n\n # Augmentation (Image Jitter)\n if kitti_aug.AUG_PCA_JITTER in sample.augs:\n image_input[:, :, 0:3] = kitti_aug.apply_pca_jitter(\n image_input[:, :, 0:3])\n\n if obj_labels is not None:\n label_boxes_3d = np.asarray(\n [box_3d_encoder.object_label_to_box_3d(obj_label)\n for obj_label in obj_labels])\n\n label_classes = [\n self.kitti_utils.class_str_to_index(obj_label.type)\n for obj_label in obj_labels]\n label_classes = np.asarray(label_classes, dtype=np.int32)\n\n # Return empty anchors_info if no ground truth after filtering\n if len(label_boxes_3d) == 0:\n anchors_info = []\n if self.train_on_all_samples:\n # If training without any positive labels, we cannot\n # set these to zeros, because later on the offset calc\n # uses log on these anchors. So setting any arbitrary\n # number here that does not break the offset calculation\n # should work, since the negative samples won't be\n # regressed in any case.\n dummy_anchors = [[-1000, -1000, -1000, 1, 1, 1]]\n label_anchors = np.asarray(dummy_anchors)\n dummy_boxes = [[-1000, -1000, -1000, 1, 1, 1, 0]]\n label_boxes_3d = np.asarray(dummy_boxes)\n else:\n label_anchors = np.zeros((1, 6))\n label_boxes_3d = np.zeros((1, 7))\n label_classes = np.zeros(1)\n else:\n label_anchors = box_3d_encoder.box_3d_to_anchor(\n label_boxes_3d, ortho_rotate=True)\n\n # Create BEV maps\n bev_images = self.kitti_utils.create_bev_maps(\n point_cloud, ground_plane)\n\n height_maps = bev_images.get('height_maps')\n density_map = bev_images.get('density_map')\n bev_input = np.dstack((*height_maps, density_map))\n\n sample_dict = {\n constants.KEY_LABEL_BOXES_3D: label_boxes_3d,\n constants.KEY_LABEL_ANCHORS: label_anchors,\n constants.KEY_LABEL_CLASSES: label_classes,\n\n constants.KEY_IMAGE_INPUT: image_input,\n constants.KEY_BEV_INPUT: bev_input,\n\n constants.KEY_ANCHORS_INFO: anchors_info,\n\n constants.KEY_POINT_CLOUD: point_cloud,\n constants.KEY_GROUND_PLANE: ground_plane,\n constants.KEY_STEREO_CALIB_P2: stereo_calib_p2,\n\n constants.KEY_SAMPLE_NAME: sample_name,\n constants.KEY_SAMPLE_AUGS: sample.augs\n }\n sample_dicts.append(sample_dict)\n\n return sample_dicts\n\n def _shuffle_samples(self):\n perm = np.arange(self.num_samples)\n np.random.shuffle(perm)\n self.sample_list = self.sample_list[perm]\n\n def next_batch(self, batch_size, shuffle=True):\n \"\"\"\n Retrieve the next `batch_size` samples from this data set.\n\n Args:\n batch_size: number of samples in the batch\n shuffle: whether to shuffle the indices after an epoch is completed\n\n Returns:\n list of dictionaries containing sample information\n \"\"\"\n\n # Create empty set of samples\n samples_in_batch = []\n\n start = self._index_in_epoch\n # Shuffle only for the first epoch\n if self.epochs_completed == 0 and start == 0 and shuffle:\n self._shuffle_samples()\n\n # Go to the next epoch\n if start + batch_size >= self.num_samples:\n\n # Finished epoch\n self.epochs_completed += 1\n\n # Get the rest examples in this epoch\n rest_num_examples = self.num_samples - start\n\n # Append those samples to the current batch\n samples_in_batch.extend(\n self.load_samples(np.arange(start, self.num_samples)))\n\n # Shuffle the data\n if shuffle:\n self._shuffle_samples()\n\n # Start next epoch\n start = 0\n self._index_in_epoch = batch_size - rest_num_examples\n end = self._index_in_epoch\n\n # Append the rest of the batch\n samples_in_batch.extend(self.load_samples(np.arange(start, end)))\n\n else:\n self._index_in_epoch += batch_size\n end = self._index_in_epoch\n\n # Append the samples in the range to the batch\n samples_in_batch.extend(self.load_samples(np.arange(start, end)))\n\n return samples_in_batch\n\n\n\n\n\n\n def get_point_cloud(self, source, img_idx, image_shape=None):\n\n calib = moose_load_calibration.load_calibration(self.calib_dir)\n\n def lidar_to_camera(lidar_path, img_idx): # lidar to front camera\n scan_data = np.fromfile(lidar_path, dtype=np.float32) # numpy from file reads binary file\n lidar = scan_data.reshape((-1, 4))\n\n [rows,cols] = lidar.shape; # rows and cols of the lidar points, rows = number of lidar points, columns (4 = x , y, z , intensity)\n\n # 0: front , 1: front right, 2: right front, 3: back right, 4: back, 5: left back, 6: left front, 7: front left\n\n point_cloud_cam = np.zeros([lidar.shape[0], lidar.shape[1]])\n\n if img_idx < 100:\n T_CAM_LIDAR = np.linalg.inv(np.array(calib['extrinsics']['T_LIDAR_CAM00']));\n\n\n elif (img_idx >= 100 and img_idx < 200):\n T_CAM_LIDAR = np.linalg.inv(np.array(calib['extrinsics']['T_LIDAR_CAM01']));\n\n\n elif (img_idx >= 200 and img_idx < 300):\n T_CAM_LIDAR = np.linalg.inv(np.array(calib['extrinsics']['T_LIDAR_CAM02']));\n\n elif (img_idx >= 300 and img_idx < 400):\n T_CAM_LIDAR = np.linalg.inv(np.array(calib['extrinsics']['T_LIDAR_CAM03']));\n\n elif (img_idx >= 400 and img_idx < 500):\n T_CAM_LIDAR = np.linalg.inv(np.array(calib['extrinsics']['T_LIDAR_CAM04']));\n\n elif (img_idx >= 500 and img_idx < 600):\n T_CAM_LIDAR = np.linalg.inv(np.array(calib['extrinsics']['T_LIDAR_CAM05']));\n\n elif (img_idx >= 600 and img_idx < 700):\n T_CAM_LIDAR = np.linalg.inv(np.array(calib['extrinsics']['T_LIDAR_CAM06']));\n\n elif (img_idx >= 700 and img_idx < 800):\n T_CAM_LIDAR = np.linalg.inv(np.array(calib['extrinsics']['T_LIDAR_CAM07']));\n\n else:\n T_CAM_LIDAR = \"YOLO\"\n\n\n for i in range(rows):\n point_cloud_cam[i] = np.matmul(T_CAM_LIDAR, lidar[i])\n\n return point_cloud_cam\n\n\n if source == \"lidar\":\n # wavedata wants im_size in (w, h) order\n min_intensity = None\n\n im_size = [image_shape[1], image_shape[0]]\n\n if img_idx < 100:\n lidar_idx = img_idx\n lidar_path = self.velo_dir + format(lidar_idx, '010') + \".bin\"\n\n\n elif (img_idx >= 100 and img_idx < 200):\n lidar_idx = img_idx - 100\n lidar_path = self.velo_dir + format(lidar_idx, '010') + \".bin\"\n\n\n elif (img_idx >= 200 and img_idx < 300):\n lidar_idx = img_idx - 200\n lidar_path = self.velo_dir + format(lidar_idx, '010') + \".bin\"\n\n elif (img_idx >= 300 and img_idx < 400):\n lidar_idx = img_idx - 300\n lidar_path = self.velo_dir + format(lidar_idx, '010') + \".bin\"\n\n elif (img_idx >= 400 and img_idx < 500):\n lidar_idx = img_idx - 400\n lidar_path = self.velo_dir + format(lidar_idx, '010') + \".bin\"\n\n elif (img_idx >= 500 and img_idx < 600):\n lidar_idx = img_idx - 500\n lidar_path = self.velo_dir + format(lidar_idx, '010') + \".bin\"\n\n elif (img_idx >= 600 and img_idx < 700):\n lidar_idx = img_idx - 600\n lidar_path = self.velo_dir + format(lidar_idx, '010') + \".bin\"\n\n elif (img_idx >= 700 and img_idx < 800):\n lidar_idx = img_idx - 700\n lidar_path = self.velo_dir + format(lidar_idx, '010') + \".bin\"\n else:\n lidar_path = \"YOLO\"\n\n\n\n\n pts = lidar_to_camera(lidar_path,img_idx)\n\n # The given image is assumed to be a 2D image\n if not im_size:\n\n return pts[:, 0:3].T\n\n\n\n\n\n else:\n\n\n # Only keep points in front of camera (positive z)\n pts = pts[pts[:, 2] > 0]\n\n if img_idx < 100:\n\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM00']['camera_matrix']['data']).reshape(-1,3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n\n\n elif (img_idx >= 100 and img_idx < 200):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM01']['camera_matrix']['data']).reshape(-1,3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n\n\n elif (img_idx >= 200 and img_idx < 300):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM02']['camera_matrix']['data']).reshape(-1,3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n\n\n elif (img_idx >= 300 and img_idx < 400):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM03']['camera_matrix']['data']).reshape(-1,3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n\n\n elif (img_idx >= 400 and img_idx < 500):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM04']['camera_matrix']['data']).reshape(-1,3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n\n\n elif (img_idx >= 500 and img_idx < 600):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM05']['camera_matrix']['data']).reshape(-1,3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n elif (img_idx >= 600 and img_idx < 700):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM06']['camera_matrix']['data']).reshape(-1,3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n\n elif (img_idx >= 700 and img_idx < 800):\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM07']['camera_matrix']['data']).reshape(-1,\n 3) # camera to image #intrinsic matrix\n\n # T_IMG_CAM : 4 x 4 matrix\n T_IMG_CAM = T_IMG_CAM[0:3,0:4]; # remove last row, #choose the first 3 rows and get rid of the last column\n\n\n else:\n T_IMG_CAM = \"yolo\"\n\n\n\n # read image\n\n\n point_in_im = np.zeros([pts.shape[0], 2])\n for i in range(len(pts)):\n\n\n a = np.matmul(T_IMG_CAM, pts[i])\n\n point_in_im[i] = [a[0] / a[2], a[1] / a[2]]\n\n # Project points onto image\n\n # Project to image frame\n\n # Filter based on the given image size\n image_filter = (point_in_im[:, 0] > 0) & \\\n (point_in_im[:, 0] < im_size[0]) & \\\n (point_in_im[:, 1] > 0) & \\\n (point_in_im[:, 1] < im_size[1])\n\n if not min_intensity:\n\n return pts[image_filter][:, 0:3].T\n\n else:\n intensity_filter = i > min_intensity\n point_filter = np.logical_and(image_filter, intensity_filter)\n return pts[point_filter][:, 0:3].T\n\n\n\n\n else:\n raise ValueError(\"Invalid source {}\".format(source))\n\n #img = cv2.imread(self.img_path)\n\n #cv2.imshow('image', img)\n #image_shape = img.shape[:2]\n\n\n '''\n\n def lidar_to_camera_zero(img_idx): # lidar to front camera\n lidar_path = self.velo_dir + \"/\" + format(img_idx, '010') + \".bin\"\n scan_data = np.fromfile(lidar_path, dtype=np.float32) # numpy from file reads binary file\n lidar = scan_data.reshape((-1, 4))\n\n [rows,\n cols] = lidar.shape; # rows and cols of the lidar points, rows = number of lidar points, columns (4 = x , y, z , intensity)\n\n # 0: front , 1: front right, 2: right front, 3: back right, 4: back, 5: left back, 6: left front, 7: front left\n\n point_cloud_cam = np.zeros([lidar.shape[0], lidar.shape[1]])\n\n T_CAM_LIDAR = np.linalg.inv(np.array(calib['extrinsics']['T_LIDAR_CAM00'])); # going from lidar to camera\n\n for i in range(rows):\n point_cloud_cam[i] = np.matmul(T_CAM_LIDAR, lidar[i])\n\n return point_cloud_cam\n\n\n\n def get_lidar_point_cloud(point_cloud_cam,\n image_shape=None, min_intensity=None):\n\n im_size = [image_shape[1], image_shape[0]]\n \"\"\" Calculates the lidar point cloud, and optionally returns only the\n points that are projected to the image.\n\n :param img_idx: image index\n :param calib_dir: directory with calibration files\n :param velo_dir: directory with velodyne files\n :param im_size: (optional) 2 x 1 list containing the size of the image\n to filter the point cloud [w, h]\n :param min_intensity: (optional) minimum intensity required to keep a point\n\n :return: (3, N) point_cloud in the form [[x,...][y,...][z,...]]\n \"\"\"\n\n pts = point_cloud_cam[:, 0:3]\n\n # The given image is assumed to be a 2D image\n if not im_size:\n\n return pts.T\n\n else:\n # Only keep points in front of camera (positive z)\n pts = pts[pts[:, 2] > 0]\n calib = moose_load_calibration.load_calibration(self.calib_dir)\n T_IMG_CAM = np.eye(4); # identity matrix\n T_IMG_CAM[0:3, 0:3] = np.array(calib['CAM0' + cam]['camera_matrix']['data']).reshape(-1,\n 3) # matrix of the camera\n T_IMG_CAM = T_IMG_CAM[0:3, 0:4]; # remove last row\n\n T_CAM_LIDAR = np.linalg.inv(np.array(\n calib['extrinsics']['T_LIDAR_CAM0' + cam])) # lidar to camera is the inverse of camera to lidar\n\n dist_coeffs = np.array(calib['CAM0' + cam]['distortion_coefficients']['data']) # get the distortion coeff\n\n moose_lidar_utils_obj = lidar_utils(T_CAM_LIDAR) # T_CAM_LIDAR (lidar to camera)\n\n # read image\n img = cv2.imread(img_path)\n\n DISTORTED = False\n\n # Project points onto image\n img, img_points = moose_lidar_utils_obj.project_points(img, lidar_path, T_IMG_CAM, T_CAM_LIDAR, dist_coeffs,\n DISTORTED,\n 'bin') # projects lidar points into image frame\n # Project to image frame\n point_in_im = img_points\n\n # Filter based on the given image size\n image_filter = (point_in_im[:, 0] > 0) & \\\n (point_in_im[:, 0] < im_size[0]) & \\\n (point_in_im[:, 1] > 0) & \\\n (point_in_im[:, 1] < im_size[1])\n\n if not min_intensity:\n return pts[image_filter].T\n\n else:\n intensity_filter = i > min_intensity\n point_filter = np.logical_and(image_filter, intensity_filter)\n return pts[point_filter].T\n \n '''","sub_path":"avod/datasets/kitti/moose_dataset.py","file_name":"moose_dataset.py","file_ext":"py","file_size_in_byte":33466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"581124561","text":"import numpy as np\nimport string\nimport os\nimport re\nimport random\nimport cv2\nimport pickle\n\nDATADIR =\"English\\Img\\Bmp\"\nCLASSES = string.ascii_uppercase\nIMG_SIZE = 64\n\n\ndef load_filenames():\n filenames = []\n for path, dirs,files in os.walk(DATADIR):\n \"\"\"Fájlrendszer bejárása és kép elérési utak betöltése\"\"\"\n filenames += list(map(lambda f: path+'\\\\'+f, files))\n return filenames\n\n\ndef create_datasets(dataset):\n test_img = []\n train_img = []\n\n \"\"\"fájlok megkeverse és szétosztása két állományba\"\"\"\n random.shuffle(dataset)\n j=0;\n for i in dataset:\n if j 0:\n cmd_opts.append(\"-f\"+opt_list[ii])\n file_output += \"1\"\n t1.append(1)\n else:\n # cmd_opts.append(\"-fno-\"+opt_list[ii])\n file_output += \"0\"\n t1.append(0)\n \n #construct results table\n t1.append(-1)\n t1.append(-1)\n for jj in range(3):\n full_table.append(t1)\n\n # file_output += \".out\"\n\n #Put compile command together\n for item in cmd_base:\n full_command.append(item)\n full_command.append(file_output)\n for item in cmd_opts:\n full_command.append(item)\n\n #store compile commands\n commands.append(full_command)\n\n #store output filenames\n filenames.append(file_output)\n\n \n\n\nall_data['copy'] = list(full_table)\nall_data['scale'] = list(full_table)\nall_data['add'] = list(full_table)\nall_data['triad'] = list(full_table)\n\nprint(len(full_table))\n\nif comp == True:\n ### Compile Experiment\n for cmd in commands:\n print(cmd)\n subprocess.call(cmd)\n process = subprocess.Popen(cmd, \\\n stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).communicate()[0]\n\nif run == True:\n ### Run Experiment\n for trial in filenames:\n for replication in range(3):\n #overwrite file on first repl\n if replication == 0:\n print(\"./\"+trial + \" > \" + trial+\".out\")\n process = subprocess.Popen(\"./\"+trial + \" >> \" + trial+\".out\", shell=True)\n process.wait()\n else:\n print(\"./\"+trial + \" >> \" + trial+\".out\")\n process = subprocess.Popen(\"./\"+trial + \" >> \" + trial+\".out\", shell=True)\n process.wait()\n\n\ndef str_to_float(stream_list):\n stream_list.pop(0)\n for ii, col in enumerate(stream_list):\n stream_list[ii] = float(stream_list[ii])\n\n return stream_list\n\ndef get_index(filename, replications, cur_repl):\n index = 0\n exponent = 0\n\n for ii, factor in enumerate(filename):\n index += int(float(factor))*replications*(2**exponent)\n exponent += 1\n\n #replication number\n index += cur_repl\n # print(filename, factor, ii, index, 'cur_repl = ', cur_repl)\n\n return index\n\ndef stream_data_to_csv(all_data, filename, csv_prefix, replications):\n ''' filename is stream data file\n csv_prefix is the directory the csvs are in\n replications is the number of times each setup was run'''\n content = []\n with open(csv_prefix+filename+\".out\") as f:\n content = f.readlines()\n f.close()\n\n repl = 0\n results = {}\n results['copy'] = []\n results['scale'] = []\n results['add'] = []\n results['triad'] = []\n\n for line in content:\n if repl >= replications:\n break\n\n index = get_index(filename, replications, repl)\n\n if \"Copy:\" in line:\n tt = 'copy'\n # print(\"Repl = \", repl)\n data = str_to_float(line.split())\n all_data[tt][index][0] = repl\n all_data[tt][index][10] = data[0]\n all_data[tt][index][11] = data[1]\n\n # print(all_data['copy'][index], repl, index)\n with open(csv_prefix + tt + '.csv', 'ta') as outcsv:\n writer = csv.writer(outcsv)\n writer.writerow(all_data[tt][index])\n\n elif \"Scale:\" in line:\n tt = 'scale'\n data = str_to_float(line.split())\n all_data[tt][index][0] = repl\n all_data[tt][index][10] = data[0]\n all_data[tt][index][11] = data[1]\n\n # print(all_data['copy'][index], repl, index)\n with open(csv_prefix + tt + '.csv', 'ta') as outcsv:\n writer = csv.writer(outcsv)\n writer.writerow(all_data[tt][index])\n\n elif \"Add:\" in line:\n tt = 'add'\n data = str_to_float(line.split())\n all_data[tt][index][0] = repl\n all_data[tt][index][10] = data[0]\n all_data[tt][index][11] = data[1]\n\n # print(all_data['copy'][index], repl, index)\n with open(csv_prefix + tt + '.csv', 'ta') as outcsv:\n writer = csv.writer(outcsv)\n writer.writerow(all_data[tt][index])\n\n elif \"Triad:\" in line:\n tt = 'triad'\n data = str_to_float(line.split())\n all_data[tt][index][0] = repl\n all_data[tt][index][10] = data[0]\n all_data[tt][index][11] = data[1]\n\n # print(all_data['copy'][index], repl, index)\n with open(csv_prefix + tt + '.csv', 'ta') as outcsv:\n writer = csv.writer(outcsv)\n writer.writerow(all_data[tt][index])\n\n ##next replication after triad\n repl += 1\n\n\n\n### Process Data\ncsv_prefix = \"Exp2/\"\n\nfiles = ['copy', 'scale', 'add', 'triad']\n\n# print(len(filenames))\n\nfor ii in files:\n #clear contents of old files\n open(csv_prefix + ii + '.csv', 'w').close()\n\n#Write csv header\nfor ii in files:\n with open(csv_prefix + ii + '.csv', 'wt') as outcsv:\n writer = csv.writer(outcsv)\n writer.writerow(['Repl', 'inline-functions', 'unswitch-loops', 'predictive-commoning', 'gcse-after-reload', \n 'tree-loop-distribute-patterns', 'tree-slp-vectorize', 'vect-cost-model', 'tree-partial-pre', \n 'ipa-cp-clone', 'Best Rate', 'Avg Time'])\n\nfor exp in sorted(filenames):\n # print(exp)\n\n outfile = exp[5:]\n # print(outfile)\n stream_data_to_csv(all_data, outfile, csv_prefix, 3)\n\n\n# print(all_data['copy'][0:2])\n\n\n# print(all_data['copy'])\n\n\n\n\n\n\n# opt_list = [['auto-inc-dec', 'branch-count-reg', 'combine-stack-adjustments'],\n# ['compare-elim', 'cprop-registers' ,'dce'], ['defer-pop' ,'delayed-branch', 'dse'], \n# ['forward-propagate', 'guess-branch-probability', 'if-conversion2'], \n# ['if-conversion', 'inline-functions-called-once', 'ipa-pure-const'], \n# ['ipa-profile', 'ipa-reference', 'merge-constants'], \n# ['move-loop-invariants', 'reorder-blocks', 'shrink-wrap'], ['split-wide-types', 'ssa-backprop', 'ssa-phiopt'], \n# ['tree-bit-ccp', 'tree-ccp', 'tree-ch'], ['tree-coalesce-vars', 'tree-copy-prop', 'tree-dce'],\n# ['tree-dominator-opts', 'tree-dse', 'tree-forwprop'], ['tree-fre', 'tree-phiprop', 'tree-sink'], \n# ['tree-slsr', 'tree-sra', 'tree-pta'], ['tree-ter', 'unit-at-a-time']]\n\n## 01 ops\n# opt_list = ['auto-inc-dec', 'branch-count-reg', 'combine-stack-adjustments',\n# 'compare-elim', 'cprop-registers' ,'dce', 'defer-pop' ,'delayed-branch', 'dse', \n# 'forward-propagate', 'guess-branch-probability', 'if-conversion2', \n# 'if-conversion', 'inline-functions-called-once', 'ipa-pure-const', \n# 'ipa-profile', 'ipa-reference', 'merge-constants', \n# 'move-loop-invariants', 'reorder-blocks', 'shrink-wrap', 'split-wide-types', 'ssa-backprop', 'ssa-phiopt', \n# 'tree-bit-ccp', 'tree-ccp', 'tree-ch', 'tree-coalesce-vars', 'tree-copy-prop', 'tree-dce',\n# 'tree-dominator-opts', 'tree-dse', 'tree-forwprop', 'tree-fre', 'tree-phiprop', 'tree-sink', \n# 'tree-slsr', 'tree-sra', 'tree-pta', 'tree-ter', 'unit-at-a-time']\n","sub_path":"Project/Experiment2.py","file_name":"Experiment2.py","file_ext":"py","file_size_in_byte":7992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"447550063","text":"\"\"\"\nModule to provide processing for the container blocks.\n\"\"\"\nimport logging\n\nfrom pymarkdown.block_quote_processor import BlockQuoteProcessor\nfrom pymarkdown.extensions.pragma_token import PragmaExtension\nfrom pymarkdown.html_helper import HtmlHelper\nfrom pymarkdown.inline_markdown_token import TextMarkdownToken\nfrom pymarkdown.leaf_block_processor import LeafBlockProcessor\nfrom pymarkdown.link_reference_definition_helper import LinkReferenceDefinitionHelper\nfrom pymarkdown.list_block_processor import ListBlockProcessor\nfrom pymarkdown.parser_helper import ParserHelper, PositionMarker\nfrom pymarkdown.parser_logger import ParserLogger\n\nPOGGER = ParserLogger(logging.getLogger(__name__))\n\n\nclass ContainerBlockProcessor:\n \"\"\"\n Class to provide processing for the container blocks.\n \"\"\"\n\n # pylint: disable=too-many-locals\n # pylint: disable=too-many-arguments\n # pylint: disable=too-many-statements\n # pylint: disable=too-many-branches\n # pylint: disable=too-many-return-statements\n @staticmethod\n def parse_line_for_container_blocks(\n parser_state,\n position_marker,\n ignore_link_definition_start,\n parser_properties,\n container_start_bq_count,\n container_depth=0,\n foobar=None,\n init_bq=None,\n ):\n \"\"\"\n Parse the line, taking care to handle any container blocks before deciding\n whether or not to pass the (remaining parts of the) line to the leaf block\n processor.\n\n Note: This is one of the more heavily traffic functions in the\n parser. Debugging should be uncommented only if needed.\n \"\"\"\n\n line_to_parse = position_marker.text_to_parse\n if container_depth == 0:\n parser_state.mark_start_information(position_marker)\n\n # POGGER.debug(\"Line:$:\", line_to_parse)\n # POGGER.debug(\"Stack Depth:$:\", parser_state.original_stack_depth)\n # POGGER.debug(\"Document Depth:$:\", parser_state.original_document_depth)\n\n # Debug to be used for block quotes if needed.\n # POGGER.debug(\n # \"Last Block Quote:$:\",\n # parser_state.last_block_quote_stack_token,\n # )\n # POGGER.debug(\n # \"Last Block Quote:$:\",\n # parser_state.last_block_quote_markdown_token_index,\n # )\n # POGGER.debug(\n # \"Last Block Quote:$:\", parser_state.copy_of_last_block_quote_markdown_token\n # )\n\n start_index, extracted_whitespace = ParserHelper.extract_whitespace(\n line_to_parse, 0\n )\n\n if ContainerBlockProcessor.__look_for_pragmas(\n position_marker,\n line_to_parse,\n container_depth,\n extracted_whitespace,\n parser_properties,\n ):\n return None, None, None, None, False\n\n if container_depth == 0:\n parser_state.copy_of_token_stack = []\n for next_item in parser_state.token_stack:\n parser_state.copy_of_token_stack.append(next_item)\n\n (\n current_container_blocks,\n adj_ws,\n stack_bq_count,\n this_bq_count,\n ) = ContainerBlockProcessor.__calculate_for_container_blocks(\n parser_state,\n line_to_parse,\n extracted_whitespace,\n foobar,\n init_bq,\n )\n # POGGER.debug(\"this_bq_count>>$\", this_bq_count)\n\n end_container_indices = ContainerIndices(-1, -1, -1)\n parser_state.nested_list_start = None\n (\n did_process,\n was_container_start,\n end_container_indices.block_index,\n this_bq_count,\n stack_bq_count,\n line_to_parse,\n start_index,\n leaf_tokens,\n container_level_tokens,\n removed_chars_at_start,\n did_blank,\n last_block_quote_index,\n text_removed_by_container,\n avoid_block_starts,\n requeue_line_info,\n ) = ContainerBlockProcessor.__get_block_start_index(\n position_marker,\n parser_state,\n extracted_whitespace,\n adj_ws,\n this_bq_count,\n stack_bq_count,\n start_index,\n container_start_bq_count,\n container_depth,\n )\n if requeue_line_info:\n POGGER.debug(\">>requeuing lines after looking for block start. returning.\")\n return None, None, None, requeue_line_info, False\n\n if did_blank:\n POGGER.debug(\">>already handled blank line. returning.\")\n container_level_tokens.extend(leaf_tokens)\n return container_level_tokens, line_to_parse, this_bq_count, None, True\n\n # POGGER.debug(\"this_bq_count>>$\", this_bq_count)\n # POGGER.debug(\"stack_bq_count>>$\", stack_bq_count)\n # POGGER.debug(\">>avoid_block_starts>>$\", avoid_block_starts)\n # POGGER.debug(\">>did_process>>$\", did_process)\n\n (\n did_process,\n was_container_start,\n end_container_indices.ulist_index,\n line_to_parse,\n removed_chars_at_start,\n requeue_line_info,\n ) = ContainerBlockProcessor.__get_list_start_index(\n position_marker,\n line_to_parse,\n start_index,\n True,\n parser_state,\n did_process,\n was_container_start,\n extracted_whitespace,\n adj_ws,\n stack_bq_count,\n this_bq_count,\n removed_chars_at_start,\n current_container_blocks,\n container_level_tokens,\n )\n if requeue_line_info:\n POGGER.debug(\n \">>requeuing lines after looking for ordered list start. returning.\"\n )\n return None, None, None, requeue_line_info, False\n # POGGER.debug(\"this_bq_count>>$\", this_bq_count)\n # POGGER.debug(\"stack_bq_count>>$\", stack_bq_count)\n # POGGER.debug(\"was_container_start>>$\", was_container_start)\n (\n did_process,\n was_container_start,\n end_container_indices.olist_index,\n line_to_parse,\n removed_chars_at_start,\n requeue_line_info,\n ) = ContainerBlockProcessor.__get_list_start_index(\n position_marker,\n line_to_parse,\n start_index,\n False,\n parser_state,\n did_process,\n was_container_start,\n extracted_whitespace,\n adj_ws,\n stack_bq_count,\n this_bq_count,\n removed_chars_at_start,\n current_container_blocks,\n container_level_tokens,\n )\n if requeue_line_info:\n POGGER.debug(\n \">>requeuing lines after looking for unordered list start. returning.\"\n )\n return None, None, None, requeue_line_info, False\n # POGGER.debug(\"this_bq_count>>$\", this_bq_count)\n # POGGER.debug(\"stack_bq_count>>$\", stack_bq_count)\n\n # POGGER.debug(\"last_block_quote_index>>$\", last_block_quote_index)\n # POGGER.debug(\"indices>>$\", end_container_indices)\n # POGGER.debug(\"line_to_parse(after containers)>>$\", line_to_parse)\n # POGGER.debug(\"was_container_start>>$\", was_container_start)\n\n last_list_start_index = 0\n if end_container_indices.block_index != -1:\n assert last_block_quote_index in (\n end_container_indices.block_index - 1,\n end_container_indices.block_index,\n )\n elif end_container_indices.olist_index != -1:\n last_list_start_index = end_container_indices.olist_index\n elif end_container_indices.ulist_index != -1:\n last_list_start_index = end_container_indices.ulist_index\n\n did_process_blank_line = False\n if not parser_state.token_stack[-1].is_fenced_code_block:\n new_position_marker = PositionMarker(\n position_marker.line_number, start_index, line_to_parse\n )\n # POGGER.debug(\"this_bq_count>>$\", this_bq_count)\n # POGGER.debug(\"stack_bq_count>>$\", stack_bq_count)\n # POGGER.debug(\"was_container_start>>$\", was_container_start)\n (\n line_to_parse,\n leaf_tokens,\n container_level_tokens,\n this_bq_count,\n did_process_blank_line,\n ) = ContainerBlockProcessor.__handle_nested_container_blocks(\n parser_state,\n container_depth,\n this_bq_count,\n stack_bq_count,\n new_position_marker,\n parser_properties,\n end_container_indices,\n leaf_tokens,\n container_level_tokens,\n was_container_start,\n avoid_block_starts,\n start_index,\n removed_chars_at_start,\n text_removed_by_container,\n )\n # POGGER.debug_with_visible_whitespace(\"text>>$>>\", line_to_parse)\n # POGGER.debug(\"this_bq_count>>$\", this_bq_count)\n # POGGER.debug(\"stack_bq_count>>$\", stack_bq_count)\n\n # POGGER.debug(\"olist->container_level_tokens->$\", container_level_tokens)\n # POGGER.debug(\"removed_chars_at_start>>>$\", removed_chars_at_start)\n\n if container_depth or did_process_blank_line:\n assert not leaf_tokens\n POGGER.debug(\">>>>>>>>$<<<<<<<<<<\", line_to_parse)\n return container_level_tokens, line_to_parse, this_bq_count, None, False\n\n # POGGER.debug_with_visible_whitespace(\n # \">>__process_list_in_progress>>$>>\",\n # line_to_parse,\n # )\n (\n did_process,\n line_to_parse,\n container_level_tokens,\n used_indent,\n requeue_line_info,\n ) = ContainerBlockProcessor.__process_list_in_progress(\n parser_state,\n did_process,\n line_to_parse,\n start_index,\n container_level_tokens,\n extracted_whitespace,\n )\n if requeue_line_info:\n return None, None, None, requeue_line_info, False\n\n # POGGER.debug_with_visible_whitespace(\n # \">>__process_list_in_progress>>$>>\", line_to_parse\n # )\n # POGGER.debug(\"container_start_bq_count>>$\", container_start_bq_count)\n # POGGER.debug(\"this_bq_count>>$\", this_bq_count)\n # POGGER.debug(\"stack_bq_count>>$\", stack_bq_count)\n ContainerBlockProcessor.__process_lazy_lines(\n parser_state,\n leaf_tokens,\n this_bq_count,\n stack_bq_count,\n line_to_parse,\n container_level_tokens,\n container_start_bq_count,\n )\n # POGGER.debug_with_visible_whitespace(\"text>>$>>\", line_to_parse)\n # POGGER.debug(\"container_level_tokens>>$>>\", container_level_tokens)\n\n # TODO refactor to make indent unnecessary?\n calculated_indent = len(parser_state.original_line_to_parse) - len(\n line_to_parse\n )\n # POGGER.debug(\">>indent>>$\", calculated_indent)\n\n force_it = False\n if (\n used_indent\n and parser_state.token_stack[-1].is_paragraph\n and parser_state.token_stack[-2].is_block_quote\n ):\n assert text_removed_by_container is None\n text_removed_by_container, force_it = used_indent, True\n\n newer_position_marker = PositionMarker(\n position_marker.line_number,\n start_index,\n line_to_parse,\n index_indent=calculated_indent,\n )\n parser_state.mark_for_leaf_processing(container_level_tokens)\n leaf_tokens, requeue_line_info = ContainerBlockProcessor.__process_leaf_tokens(\n parser_state,\n leaf_tokens,\n newer_position_marker,\n this_bq_count,\n removed_chars_at_start,\n ignore_link_definition_start,\n last_block_quote_index,\n last_list_start_index,\n text_removed_by_container,\n force_it,\n )\n parser_state.clear_after_leaf_processing()\n\n container_level_tokens.extend(leaf_tokens)\n return (\n container_level_tokens,\n line_to_parse,\n this_bq_count,\n requeue_line_info,\n False,\n )\n # pylint: enable=too-many-locals\n # pylint: enable=too-many-arguments\n # pylint: enable=too-many-statements\n # pylint: enable=too-many-branches\n # pylint: enable=too-many-return-statements\n\n @staticmethod\n # pylint: disable=too-many-locals, too-many-arguments\n def __get_block_start_index(\n position_marker,\n parser_state,\n extracted_whitespace,\n adj_ws,\n this_bq_count,\n stack_bq_count,\n start_index,\n container_start_bq_count,\n container_depth,\n ):\n new_position_marker = PositionMarker(\n position_marker.line_number, start_index, position_marker.text_to_parse\n )\n (\n did_process,\n was_container_start,\n block_index,\n this_bq_count,\n stack_bq_count,\n line_to_parse,\n start_index,\n leaf_tokens,\n container_level_tokens,\n removed_chars_at_start,\n did_blank,\n last_block_quote_index,\n text_removed_by_container,\n avoid_block_starts,\n requeue_line_info,\n ) = BlockQuoteProcessor.handle_block_quote_block(\n parser_state,\n new_position_marker,\n extracted_whitespace,\n adj_ws,\n this_bq_count,\n stack_bq_count,\n container_start_bq_count,\n container_depth,\n )\n # POGGER.debug(\"container_start_bq_count>>:$\", container_start_bq_count)\n # POGGER.debug(\"this_bq_count>>:$\", this_bq_count)\n # POGGER.debug(\"stack_bq_count>>$\", stack_bq_count)\n # POGGER.debug(\"did_process>>$\", did_process)\n POGGER.debug(\"text>>:$:>>\", line_to_parse)\n # POGGER.debug(\">>container_level_tokens>>$\", container_level_tokens)\n # POGGER.debug(\">>leaf_tokens>>$\", leaf_tokens)\n return (\n did_process,\n was_container_start,\n block_index,\n this_bq_count,\n stack_bq_count,\n line_to_parse,\n start_index,\n leaf_tokens,\n container_level_tokens,\n removed_chars_at_start,\n did_blank,\n last_block_quote_index,\n text_removed_by_container,\n avoid_block_starts,\n requeue_line_info,\n )\n\n # pylint: enable=too-many-locals, too-many-arguments\n\n # pylint: disable=too-many-locals, too-many-arguments\n @staticmethod\n def __get_list_start_index(\n position_marker,\n line_to_parse,\n start_index,\n is_ulist,\n parser_state,\n did_process,\n was_container_start,\n extracted_whitespace,\n adj_ws,\n stack_bq_count,\n this_bq_count,\n removed_chars_at_start,\n current_container_blocks,\n container_level_tokens,\n ):\n \"\"\"\n Note: This is one of the more heavily traffic functions in the\n parser. Debugging should be uncommented only if needed.\n \"\"\"\n # TODO refactor so it doesn't need this!\n new_position_marker = PositionMarker(\n position_marker.line_number, start_index, line_to_parse\n )\n\n POGGER.debug(\n \"pre-list>>#$#$#$#\",\n position_marker.index_number,\n position_marker.index_indent,\n position_marker.text_to_parse,\n )\n POGGER.debug(\n \"pre-list>>#$#$#$#\",\n new_position_marker.index_number,\n new_position_marker.index_indent,\n new_position_marker.text_to_parse,\n )\n (\n did_process,\n was_container_start,\n new_list_index,\n line_to_parse,\n resultant_tokens,\n removed_chars_at_start,\n requeue_line_info,\n ) = ListBlockProcessor.handle_list_block(\n is_ulist,\n parser_state,\n did_process,\n was_container_start,\n new_position_marker,\n extracted_whitespace,\n adj_ws,\n stack_bq_count,\n this_bq_count,\n removed_chars_at_start,\n current_container_blocks,\n )\n if requeue_line_info:\n return (\n None,\n None,\n None,\n None,\n None,\n requeue_line_info,\n )\n container_level_tokens.extend(resultant_tokens)\n POGGER.debug(\n \"post-ulist>>#$#$#$#\",\n position_marker.index_number,\n position_marker.index_indent,\n position_marker.text_to_parse,\n )\n POGGER.debug(\n \"post-ulist>>#$#$#$#\",\n new_position_marker.index_number,\n new_position_marker.index_indent,\n new_position_marker.text_to_parse,\n )\n POGGER.debug(\"text>>$>>\", line_to_parse)\n\n return (\n did_process,\n was_container_start,\n new_list_index,\n line_to_parse,\n removed_chars_at_start,\n None,\n )\n\n # pylint: enable=too-many-locals, too-many-arguments\n\n @staticmethod\n def __calculate_for_container_blocks(\n parser_state,\n line_to_parse,\n extracted_whitespace,\n foobar,\n init_bq,\n ):\n \"\"\"\n Perform some calculations that will be needed for parsing the container blocks.\n \"\"\"\n this_bq_count = 0 if init_bq is None else init_bq\n\n current_container_blocks = [\n ind for ind in parser_state.token_stack if ind.is_list\n ]\n\n adj_ws = ContainerBlockProcessor.__calculate_adjusted_whitespace(\n parser_state,\n current_container_blocks,\n line_to_parse,\n extracted_whitespace,\n foobar=foobar,\n )\n\n return (\n current_container_blocks,\n adj_ws,\n parser_state.count_of_block_quotes_on_stack(),\n this_bq_count,\n )\n\n # pylint: disable=too-many-arguments\n @staticmethod\n def __calculate_adjusted_whitespace(\n parser_state,\n current_container_blocks,\n line_to_parse,\n extracted_whitespace,\n foobar=None,\n previous_ws_len=0,\n ):\n \"\"\"\n Based on the last container on the stack, determine what the adjusted whitespace is.\n \"\"\"\n\n adj_ws, stack_index = (\n extracted_whitespace,\n parser_state.find_last_list_block_on_stack(),\n )\n if stack_index <= 0:\n POGGER.debug(\"PLFCB>>No Started lists\")\n assert not current_container_blocks\n if foobar is None:\n POGGER.debug(\"PLFCB>>No Started Block Quote\")\n else:\n POGGER.debug(\"PLFCB>>Started Block Quote\")\n adj_ws = extracted_whitespace[foobar:]\n else:\n assert current_container_blocks\n POGGER.debug(\n \"PLFCB>>Started list-last stack>>$\",\n parser_state.token_stack,\n )\n POGGER.debug(\n \"PLFCB>>Started list-last stack>>$\",\n parser_state.token_stack[stack_index],\n )\n token_index = len(parser_state.token_document) - 1\n\n while token_index >= 0 and not (\n parser_state.token_document[token_index].is_any_list_token\n ):\n token_index -= 1\n POGGER.debug(\n \"PLFCB>>Started list-last token>>$\",\n parser_state.token_document[token_index],\n )\n assert token_index >= 0\n\n old_start_index = parser_state.token_document[token_index].indent_level\n\n ws_len = (\n ParserHelper.calculate_length(extracted_whitespace) + previous_ws_len\n )\n POGGER.debug(\"old_start_index>>$>>ws_len>>$\", old_start_index, ws_len)\n if ws_len >= old_start_index:\n POGGER.debug(\"RELINE:$:\", line_to_parse)\n adj_ws = extracted_whitespace[old_start_index:]\n return adj_ws\n\n # pylint: enable=too-many-arguments\n\n # pylint: disable=too-many-arguments, too-many-locals, too-many-statements, too-many-branches\n @staticmethod\n def __handle_nested_container_blocks(\n parser_state,\n container_depth,\n this_bq_count,\n stack_bq_count,\n position_marker,\n parser_properties,\n end_container_indices,\n leaf_tokens,\n container_level_tokens,\n was_container_start,\n avoid_block_starts,\n start_index,\n removed_chars_at_start,\n text_removed_by_container,\n ):\n \"\"\"\n Handle the processing of nested container blocks, as they can contain\n themselves and get somewhat messy.\n \"\"\"\n did_process_blank_line = False\n adjusted_text_to_parse = position_marker.text_to_parse\n\n POGGER.debug(\"adjusted_text_to_parse>$<\", adjusted_text_to_parse)\n POGGER.debug(\"index_number>$<\", position_marker.index_number)\n POGGER.debug(\"index_indent>$<\", position_marker.index_indent)\n POGGER.debug(\"start_index>$<\", start_index)\n POGGER.debug(\"parser_state.nested_list_start>$\", parser_state.nested_list_start)\n POGGER.debug(\"was_container_start>$\", was_container_start)\n\n if was_container_start and position_marker.text_to_parse:\n assert container_depth < 10\n POGGER.debug(\n \"__handle_nested_container_blocks>stack>>:$:<<\",\n position_marker.text_to_parse,\n )\n POGGER.debug(\n \"__handle_nested_container_blocks>end_container_indices>>:$:<<\",\n end_container_indices,\n )\n nested_container_starts = (\n ContainerBlockProcessor.__get_nested_container_starts(\n parser_state,\n position_marker.text_to_parse,\n end_container_indices,\n avoid_block_starts,\n start_index,\n removed_chars_at_start,\n text_removed_by_container,\n )\n )\n POGGER.debug(\n \"__handle_nested_container_blocks>nested_container_starts>>:$:<<\",\n nested_container_starts,\n )\n POGGER.debug(\n \"__handle_nested_container_blocks>end_container_indices>>:$:<<\",\n end_container_indices,\n )\n\n POGGER.debug(\n \"check next container_start>stack>>$\", parser_state.token_stack\n )\n POGGER.debug(\"check next container_start>leaf_tokens>>$\", leaf_tokens)\n POGGER.debug(\n \"check next container_start>container_level_tokens>>$\",\n container_level_tokens,\n )\n\n adj_line_to_parse = position_marker.text_to_parse\n\n POGGER.debug(\"check next container_start>pre>>$<<\", adj_line_to_parse)\n active_container_index = max(\n end_container_indices.ulist_index,\n end_container_indices.olist_index,\n end_container_indices.block_index,\n )\n POGGER.debug(\n \"check next container_start>max>>$>>bq>>$\",\n active_container_index,\n end_container_indices.block_index,\n )\n delta = 0\n already_adjusted = False\n if (\n end_container_indices.block_index != -1\n and not nested_container_starts.ulist_index\n and not nested_container_starts.olist_index\n ):\n assert active_container_index == end_container_indices.block_index\n POGGER.debug(\n \"parser_state.nested_list_start>>$<<\",\n parser_state.nested_list_start,\n )\n POGGER.debug(\"adj_line_to_parse>>$<<\", adj_line_to_parse)\n POGGER.debug(\n \"parser_state.token_document>>$<<\", parser_state.token_document\n )\n if parser_state.nested_list_start and adj_line_to_parse.strip():\n start_index, _ = ParserHelper.extract_whitespace(\n adj_line_to_parse, 0\n )\n POGGER.debug(\n \"end_container_indices.block_index>>$<<\",\n end_container_indices.block_index,\n )\n POGGER.debug(\"start_index>>$<<\", start_index)\n\n indent_level = parser_state.nested_list_start.indent_level\n POGGER.debug(\n \"indent_level>>$<<\",\n indent_level,\n )\n\n POGGER.debug(\n \"parser_state.nested_list_start.matching_markdown_token>>$<<\",\n parser_state.nested_list_start.matching_markdown_token,\n )\n list_start_token_index = parser_state.token_document.index(\n parser_state.nested_list_start.matching_markdown_token\n )\n POGGER.debug(\n \"list_start_token_index>>$<<\",\n list_start_token_index,\n )\n token_after_list_start = parser_state.token_document[\n list_start_token_index + 1\n ]\n POGGER.debug(\n \"token_after_list_start>>$<<\",\n token_after_list_start,\n )\n assert (\n parser_state.nested_list_start.matching_markdown_token.line_number\n == token_after_list_start.line_number\n )\n column_number_delta = (\n token_after_list_start.column_number\n - parser_state.nested_list_start.matching_markdown_token.column_number\n )\n POGGER.debug(\n \"column_number_delta>>$<<\",\n column_number_delta,\n )\n adjusted_indent_level = (\n column_number_delta + end_container_indices.block_index\n )\n POGGER.debug(\n \"adjusted_indent_level>>$<< indent_level>$\",\n adjusted_indent_level,\n indent_level,\n )\n indent_was_adjusted = indent_level != adjusted_indent_level\n if indent_level > adjusted_indent_level:\n delta = indent_level - adjusted_indent_level\n indent_level = (\n column_number_delta + end_container_indices.block_index\n )\n\n if (\n parser_state.token_document[-1].is_blank_line\n and (end_container_indices.block_index + start_index)\n < indent_level\n ):\n POGGER.debug(\"\\n\\nBOOM\\n\\n\")\n\n y_tokens = []\n while parser_state.token_document[-1].is_blank_line:\n y_tokens.append(parser_state.token_document[-1])\n del parser_state.token_document[-1]\n\n x_tokens, _ = parser_state.close_open_blocks_fn(\n parser_state,\n include_lists=True,\n )\n # assert False\n parser_state.token_document.extend(x_tokens)\n parser_state.token_document.extend(y_tokens)\n elif (\n not nested_container_starts.block_index\n and adj_line_to_parse\n and adj_line_to_parse[0] == \" \"\n and indent_was_adjusted\n and parser_state.nested_list_start\n ):\n\n POGGER.debug(\"adj_line_to_parse>:$:<\", adj_line_to_parse)\n POGGER.debug(\n \"parser_state.nested_list_start>:$:<\",\n parser_state.nested_list_start.matching_markdown_token.extracted_whitespace,\n )\n\n POGGER.debug(\n \"this_bq_count:$, stack_bq_count:$\",\n this_bq_count,\n stack_bq_count,\n )\n POGGER.debug(\n \"original_line_to_parse:>:$:<\",\n parser_state.original_line_to_parse,\n )\n\n POGGER.debug(\"BOOM\")\n if adj_line_to_parse.startswith(\n parser_state.nested_list_start.matching_markdown_token.extracted_whitespace\n ):\n adj_line_to_parse = adj_line_to_parse[\n len(\n parser_state.nested_list_start.matching_markdown_token.extracted_whitespace\n ) :\n ]\n else:\n assert parser_state.original_line_to_parse.endswith(\n adj_line_to_parse\n )\n orig_parse = len(parser_state.original_line_to_parse)\n curr_parse = len(adj_line_to_parse)\n delta_parse = orig_parse - curr_parse\n POGGER.debug(\n \"delta_parse($) = curr_parse($) - orig_parse($)\",\n delta_parse,\n curr_parse,\n orig_parse,\n )\n whitespace_to_remove = parser_state.nested_list_start.matching_markdown_token.extracted_whitespace[\n delta_parse:\n ]\n POGGER.debug(\n \"whitespace_to_remove>:$:<\", whitespace_to_remove\n )\n assert adj_line_to_parse.startswith(whitespace_to_remove)\n adj_line_to_parse = adj_line_to_parse[\n len(whitespace_to_remove) :\n ]\n\n already_adjusted = True\n\n POGGER.debug(\n \"check next container_start>mid>>stack_bq_count>>$<already adjusted<<$<<\",\n adj_line_to_parse,\n )\n adjusted_text_to_parse = adj_line_to_parse\n else:\n POGGER.debug(\"check next container_start>post<<$<<\", adj_line_to_parse)\n adj_line_to_parse = f\"{ParserHelper.repeat_string(ParserHelper.space_character, active_container_index)}{adj_line_to_parse}\"\n POGGER.debug(\"check next container_start>post<<$<<\", adj_line_to_parse)\n\n POGGER.debug(\"leaf_tokens>>$\", leaf_tokens)\n assert not leaf_tokens\n if container_level_tokens:\n parser_state.token_document.extend(container_level_tokens)\n container_level_tokens = []\n\n POGGER.debug(\n \"check next container_start>stack>>$\", parser_state.token_stack\n )\n POGGER.debug(\n \"check next container_start>tokenized_document>>$\",\n parser_state.token_document,\n )\n\n if (\n nested_container_starts.ulist_index\n or nested_container_starts.olist_index\n or nested_container_starts.block_index\n ):\n POGGER.debug(\n \"check next container_start>nested_container\",\n )\n (\n adjusted_text_to_parse,\n this_bq_count,\n did_process_blank_line,\n ) = ContainerBlockProcessor.__look_for_container_blocks(\n parser_state,\n adj_line_to_parse,\n end_container_indices.block_index,\n container_depth,\n this_bq_count,\n position_marker,\n parser_properties,\n )\n parser_state.set_no_para_start_if_empty()\n return (\n adjusted_text_to_parse,\n leaf_tokens,\n container_level_tokens,\n this_bq_count,\n did_process_blank_line,\n )\n\n # pylint: enable=too-many-arguments, too-many-locals, too-many-statements, too-many-branches\n\n # pylint: disable=too-many-arguments, too-many-locals, too-many-statements\n @staticmethod\n def __get_nested_container_starts(\n parser_state,\n line_to_parse,\n end_container_indices,\n avoid_block_starts,\n start_index,\n removed_chars_at_start,\n text_removed_by_container,\n ):\n\n POGGER.debug(\"check next container_start>\")\n POGGER.debug(\"check next container_start>start_index>$\", start_index)\n POGGER.debug(\n \"check next container_start>removed_chars_at_start:$:\",\n removed_chars_at_start,\n )\n POGGER.debug(\n \"check next container_start>text_removed_by_container:$:\",\n text_removed_by_container,\n )\n POGGER.debug(\"check next container_start>stack>>$\", parser_state.token_stack)\n\n _, ex_ws_test = ParserHelper.extract_whitespace(line_to_parse, 0)\n\n whitespace_scan_start_index = 0\n for token_stack_index in parser_state.token_stack:\n if token_stack_index.is_block_quote:\n # if text_removed_by_container:\n # if text_removed_by_container.startswith(\"> \"):\n # text_removed_by_container = text_removed_by_container[2:]\n # elif text_removed_by_container.startswith(\">\"):\n # text_removed_by_container = text_removed_by_container[1:]\n # else:\n # POGGER.info(\"check next container_start> out of block quote data\")\n pass\n elif token_stack_index.is_list:\n if token_stack_index.ws_before_marker <= len(ex_ws_test):\n whitespace_scan_start_index = token_stack_index.ws_before_marker\n\n after_ws_index, ex_whitespace = ParserHelper.extract_whitespace(\n line_to_parse, whitespace_scan_start_index\n )\n if not ex_whitespace:\n ex_whitespace = \"\"\n after_ws_index = whitespace_scan_start_index\n\n nested_ulist_start, _, _, _ = ListBlockProcessor.is_ulist_start(\n parser_state, line_to_parse, after_ws_index, ex_whitespace, False\n )\n nested_olist_start, _, _, _ = ListBlockProcessor.is_olist_start(\n parser_state, line_to_parse, after_ws_index, ex_whitespace, False\n )\n nested_block_start = (\n False\n if avoid_block_starts\n else BlockQuoteProcessor.is_block_quote_start(\n line_to_parse, after_ws_index, ex_whitespace\n )\n )\n POGGER.debug(\n \"check next container_start>ulist>$>index>$\",\n nested_ulist_start,\n end_container_indices.ulist_index,\n )\n POGGER.debug(\n \"check next container_start>olist>$>index>$\",\n nested_olist_start,\n end_container_indices.olist_index,\n )\n POGGER.debug(\n \"check next container_start>bquote>$>index>$\",\n nested_block_start,\n end_container_indices.block_index,\n )\n return ContainerIndices(\n nested_ulist_start, nested_olist_start, nested_block_start\n )\n\n # pylint: enable=too-many-arguments, too-many-locals, too-many-statements\n\n # pylint: disable=too-many-arguments\n @staticmethod\n def __look_for_container_blocks(\n parser_state,\n adj_line_to_parse,\n end_of_bquote_start_index,\n container_depth,\n this_bq_count,\n position_marker,\n parser_properties,\n ):\n \"\"\"\n Look for container blocks that we can use.\n \"\"\"\n POGGER.debug(\"check next container_start>recursing\")\n POGGER.debug(\"check next container_start>>$\\n\", adj_line_to_parse)\n POGGER.debug(\"this_bq_count>$\", this_bq_count)\n container_start_bq_count = this_bq_count\n\n adj_block = (\n None if end_of_bquote_start_index == -1 else end_of_bquote_start_index\n )\n\n position_marker = PositionMarker(\n position_marker.line_number, -1, adj_line_to_parse\n )\n (\n produced_inner_tokens,\n line_to_parse,\n proposed_this_bq_count,\n requeue_line_info,\n did_process_blank_line,\n ) = ContainerBlockProcessor.parse_line_for_container_blocks(\n parser_state,\n position_marker,\n False,\n parser_properties,\n container_start_bq_count,\n container_depth=container_depth + 1,\n foobar=adj_block,\n init_bq=this_bq_count,\n )\n assert not requeue_line_info or not requeue_line_info.lines_to_requeue\n # TODO will need to deal with force_ignore_first_as_lrd\n\n POGGER.debug(\"\\ncheck next container_start>recursed\")\n POGGER.debug(\"check next container_start>stack>>$\", parser_state.token_stack)\n POGGER.debug(\n \"check next container_start>tokenized_document>>$\",\n parser_state.token_document,\n )\n POGGER.debug(\"check next container_start>line_parse>>$\", line_to_parse)\n POGGER.debug(\"this_bq_count>$\", this_bq_count)\n if proposed_this_bq_count:\n this_bq_count += proposed_this_bq_count\n POGGER.debug(\"this_bq_count>$\", this_bq_count)\n\n POGGER.debug(\"parser_state.token_document>$\", parser_state.token_document)\n parser_state.token_document.extend(produced_inner_tokens)\n POGGER.debug(\"parser_state.token_document>$\", parser_state.token_document)\n POGGER.debug(\"did_process_blank_line>$\", did_process_blank_line)\n return line_to_parse, this_bq_count, did_process_blank_line\n\n # pylint: enable=too-many-arguments\n\n # pylint: disable=too-many-arguments\n @staticmethod\n def __process_list_in_progress(\n parser_state,\n did_process,\n line_to_parse,\n start_index,\n container_level_tokens,\n extracted_whitespace,\n ):\n used_indent = None\n requeue_line_info = None\n if not did_process:\n is_list_in_process, ind = LeafBlockProcessor.check_for_list_in_process(\n parser_state\n )\n if is_list_in_process:\n assert not container_level_tokens\n POGGER.debug(\"clt>>list-in-progress\")\n POGGER.debug(\"clt>>line_to_parse>>:$:>>\", line_to_parse)\n (\n container_level_tokens,\n line_to_parse,\n used_indent,\n requeue_line_info,\n ) = ListBlockProcessor.list_in_process(\n parser_state,\n line_to_parse,\n start_index,\n extracted_whitespace,\n ind,\n )\n POGGER.debug(\"clt>>line_to_parse>>:$:>>\", line_to_parse)\n POGGER.debug(\"clt>>used_indent>>:$:>>\", used_indent)\n POGGER.debug(\"clt>>requeue_line_info>>:$:>>\", requeue_line_info)\n did_process = True\n\n return (\n did_process,\n line_to_parse,\n container_level_tokens,\n used_indent,\n requeue_line_info,\n )\n\n # pylint: enable=too-many-arguments\n\n # pylint: disable=too-many-arguments\n @staticmethod\n def __process_lazy_lines(\n parser_state,\n leaf_tokens,\n this_bq_count,\n stack_bq_count,\n line_to_parse,\n container_level_tokens,\n container_start_bq_count,\n ):\n\n POGGER.debug(\"LINE-lazy>$\", line_to_parse)\n assert not leaf_tokens\n POGGER.debug(\"clt>>lazy-check\")\n\n POGGER.debug(\"__process_lazy_lines>>ltp>$\", line_to_parse)\n after_ws_index, ex_whitespace = ParserHelper.extract_whitespace(\n line_to_parse, 0\n )\n remaining_line = line_to_parse[after_ws_index:]\n POGGER.debug(\"container_start_bq_count>>:$\", container_start_bq_count)\n POGGER.debug(\"__process_lazy_lines>>this_bq_count>$<\", this_bq_count)\n POGGER.debug(\"__process_lazy_lines>>stack_bq_count>$<\", stack_bq_count)\n POGGER.debug(\"__process_lazy_lines>>mod->ltp>$<\", remaining_line)\n POGGER.debug(\"__process_lazy_lines>>mod->ews>$<\", ex_whitespace)\n\n lazy_tokens = BlockQuoteProcessor.check_for_lazy_handling(\n parser_state,\n this_bq_count,\n stack_bq_count,\n remaining_line,\n ex_whitespace,\n )\n if lazy_tokens:\n POGGER.debug(\"clt>>lazy-found\")\n container_level_tokens.extend(lazy_tokens)\n\n # pylint: enable=too-many-arguments\n\n # pylint: disable=too-many-arguments, too-many-locals\n @staticmethod\n def __process_leaf_tokens(\n parser_state,\n leaf_tokens,\n xposition_marker,\n this_bq_count,\n removed_chars_at_start,\n ignore_link_definition_start,\n last_block_quote_index,\n last_list_start_index,\n text_removed_by_container,\n force_it,\n ):\n assert not leaf_tokens\n POGGER.debug(\"parsing leaf>>\")\n position_marker = PositionMarker(\n xposition_marker.line_number,\n 0,\n xposition_marker.text_to_parse,\n index_indent=xposition_marker.index_indent,\n )\n (\n leaf_tokens,\n requeue_line_info,\n ) = ContainerBlockProcessor.__parse_line_for_leaf_blocks(\n parser_state,\n position_marker,\n this_bq_count,\n removed_chars_at_start,\n ignore_link_definition_start,\n last_block_quote_index,\n last_list_start_index,\n text_removed_by_container,\n force_it,\n )\n POGGER.debug(\"parsed leaf>>$\", leaf_tokens)\n return leaf_tokens, requeue_line_info\n\n # pylint: enable=too-many-arguments, too-many-locals\n\n @staticmethod\n def __close_indented_block_if_indent_not_there(parser_state, extracted_whitespace):\n\n POGGER.debug(\n \"__close_indented_block_if_indent_not_there>>$>\",\n parser_state.token_stack[-1],\n )\n POGGER.debug(\n \"__close_indented_block_if_indent_not_there>>$>\", extracted_whitespace\n )\n pre_tokens = []\n if parser_state.token_stack[\n -1\n ].is_indented_code_block and ParserHelper.is_length_less_than_or_equal_to(\n extracted_whitespace, 3\n ):\n pre_tokens.append(\n parser_state.token_stack[\n -1\n ].generate_close_markdown_token_from_stack_token()\n )\n del parser_state.token_stack[-1]\n\n extracted_blank_line_tokens = (\n ContainerBlockProcessor.extract_markdown_tokens_back_to_blank_line(\n parser_state, False\n )\n )\n extracted_blank_line_tokens.reverse()\n pre_tokens.extend(extracted_blank_line_tokens)\n POGGER.debug(\n \"__close_indented_block_if_indent_not_there>>pre_tokens>$>\", pre_tokens\n )\n return pre_tokens\n\n @staticmethod\n def __handle_fenced_code_block(\n parser_state,\n outer_processed,\n position_marker,\n extracted_whitespace,\n new_tokens,\n ):\n \"\"\"\n Take care of the processing for fenced code blocks.\n \"\"\"\n if not parser_state.token_stack[-1].was_link_definition_started:\n (\n fenced_tokens,\n extracted_whitespace,\n ) = LeafBlockProcessor.parse_fenced_code_block(\n parser_state,\n position_marker,\n extracted_whitespace,\n )\n outer_processed = False\n if fenced_tokens:\n new_tokens.extend(fenced_tokens)\n outer_processed = True\n elif parser_state.token_stack[-1].is_fenced_code_block:\n new_tokens.append(\n TextMarkdownToken(\n position_marker.text_to_parse[position_marker.index_number :],\n extracted_whitespace,\n position_marker=position_marker,\n )\n )\n outer_processed = True\n return outer_processed\n\n # pylint: disable=too-many-arguments\n @staticmethod\n def __handle_html_block(\n parser_state,\n outer_processed,\n position_marker,\n extracted_whitespace,\n new_tokens,\n ):\n \"\"\"\n Take care of the processing for html blocks.\n \"\"\"\n\n POGGER.debug(\">>position_marker>>ttp>>$>>\", position_marker.text_to_parse)\n POGGER.debug(\">>position_marker>>in>>$>>\", position_marker.index_number)\n POGGER.debug(\">>position_marker>>ln>>$>>\", position_marker.line_number)\n if not outer_processed and not parser_state.token_stack[-1].is_html_block:\n POGGER.debug(\">>html started?>>\")\n old_top_of_stack = parser_state.token_stack[-1]\n html_tokens = HtmlHelper.parse_html_block(\n parser_state,\n position_marker,\n extracted_whitespace,\n )\n if html_tokens:\n POGGER.debug(\">>html started>>\")\n LeafBlockProcessor.correct_for_leaf_block_start_in_list(\n parser_state,\n position_marker.index_indent,\n old_top_of_stack,\n html_tokens,\n )\n else:\n POGGER.debug(\">>html not started>>\")\n new_tokens.extend(html_tokens)\n if parser_state.token_stack[-1].is_html_block:\n POGGER.debug(\">>html continued>>\")\n html_tokens = HtmlHelper.check_normal_html_block_end(\n parser_state,\n position_marker.text_to_parse,\n position_marker.index_number,\n extracted_whitespace,\n position_marker,\n )\n assert html_tokens\n new_tokens.extend(html_tokens)\n outer_processed = True\n\n return outer_processed\n\n # pylint: enable=too-many-arguments\n\n # pylint: disable=too-many-arguments\n @staticmethod\n def __handle_link_reference_definition(\n parser_state,\n outer_processed,\n position_marker,\n extracted_whitespace,\n remaining_line_to_parse,\n ignore_link_definition_start,\n pre_tokens,\n ):\n \"\"\"\n Take care of the processing for link reference definitions.\n \"\"\"\n requeue_line_info, new_tokens = None, []\n\n POGGER.debug(\n \"handle_link_reference_definition>>pre_tokens>>$<<\",\n pre_tokens,\n )\n\n if not outer_processed and not ignore_link_definition_start:\n POGGER.debug(\n \"plflb-process_link_reference_definition>>outer_processed>>$\",\n position_marker.text_to_parse[position_marker.index_number :],\n )\n (\n outer_processed,\n _, # did_complete_lrd,\n _, # did_pause_lrd,\n requeue_line_info,\n new_tokens,\n ) = LinkReferenceDefinitionHelper.process_link_reference_definition(\n parser_state,\n position_marker,\n remaining_line_to_parse,\n extracted_whitespace,\n parser_state.original_line_to_parse,\n parser_state.original_stack_depth,\n parser_state.original_document_depth,\n )\n if requeue_line_info and requeue_line_info.lines_to_requeue:\n outer_processed = True\n POGGER.debug(\n \"plflb-process_link_reference_definition>>outer_processed>>$>outer_processed>>$>pre_tokens>>$<<\", pre_tokens)\n pre_tokens.extend(new_tokens)\n POGGER.debug(\"handle_link_reference_definition>>pre_tokens>>$<<\", pre_tokens)\n return outer_processed, requeue_line_info\n\n # pylint: enable=too-many-arguments\n\n # pylint: disable=too-many-arguments,too-many-locals\n @staticmethod\n def __parse_line_for_leaf_blocks(\n parser_state,\n xposition_marker,\n this_bq_count,\n removed_chars_at_start,\n ignore_link_definition_start,\n last_block_quote_index,\n last_list_start_index,\n text_removed_by_container,\n force_it,\n ):\n \"\"\"\n Parse the contents of a line for a leaf block.\n\n Note: This is one of the more heavily traffic functions in the\n parser. Debugging should be uncommented only if needed.\n \"\"\"\n POGGER.debug(\"Leaf Line:$:\", xposition_marker.text_to_parse)\n # POGGER.debug(\"this_bq_count:$:\", this_bq_count)\n new_tokens = []\n\n # TODO rename to avoid collision with parameter\n remaining_line_to_parse = xposition_marker.text_to_parse[\n xposition_marker.index_number :\n ]\n (new_index_number, extracted_whitespace,) = ParserHelper.extract_whitespace(\n xposition_marker.text_to_parse, xposition_marker.index_number\n )\n position_marker = PositionMarker(\n xposition_marker.line_number,\n new_index_number,\n xposition_marker.text_to_parse,\n index_indent=xposition_marker.index_indent,\n )\n\n pre_tokens = ContainerBlockProcessor.__close_indented_block_if_indent_not_there(\n parser_state, extracted_whitespace\n )\n\n outer_processed = ContainerBlockProcessor.__handle_fenced_code_block(\n parser_state,\n False,\n position_marker,\n extracted_whitespace,\n new_tokens,\n )\n\n ignore_lrd_start = (\n ignore_link_definition_start or parser_state.token_stack[-1].is_html_block\n )\n\n (\n outer_processed,\n requeue_line_info,\n ) = ContainerBlockProcessor.__handle_link_reference_definition(\n parser_state,\n outer_processed,\n position_marker,\n extracted_whitespace,\n remaining_line_to_parse,\n ignore_lrd_start,\n pre_tokens,\n )\n\n outer_processed = ContainerBlockProcessor.__handle_html_block(\n parser_state,\n outer_processed,\n position_marker,\n extracted_whitespace,\n new_tokens,\n )\n\n if not outer_processed:\n assert not new_tokens\n new_tokens = LeafBlockProcessor.parse_atx_headings(\n parser_state, position_marker, extracted_whitespace\n )\n if not new_tokens:\n new_tokens = LeafBlockProcessor.parse_indented_code_block(\n parser_state,\n position_marker,\n extracted_whitespace,\n removed_chars_at_start,\n last_block_quote_index,\n last_list_start_index,\n )\n if not new_tokens:\n stack_bq_count = parser_state.count_of_block_quotes_on_stack()\n new_tokens = LeafBlockProcessor.parse_setext_headings(\n parser_state,\n position_marker,\n extracted_whitespace,\n this_bq_count,\n stack_bq_count,\n )\n if not new_tokens:\n stack_bq_count = parser_state.count_of_block_quotes_on_stack()\n new_tokens = LeafBlockProcessor.parse_thematic_break(\n parser_state,\n position_marker,\n extracted_whitespace,\n this_bq_count,\n stack_bq_count,\n )\n if not new_tokens:\n stack_bq_count = parser_state.count_of_block_quotes_on_stack()\n new_tokens = LeafBlockProcessor.parse_paragraph(\n parser_state,\n position_marker,\n extracted_whitespace,\n this_bq_count,\n stack_bq_count,\n text_removed_by_container,\n force_it,\n )\n\n POGGER.debug(\">>leaf--adding>>$\", new_tokens)\n pre_tokens.extend(new_tokens)\n POGGER.debug(\">>leaf--added>>$\", pre_tokens)\n return pre_tokens, requeue_line_info\n\n @staticmethod\n def extract_markdown_tokens_back_to_blank_line(parser_state, was_forced):\n \"\"\"\n Extract tokens going back to the last blank line token.\n \"\"\"\n\n pre_tokens = []\n while parser_state.token_document[-1].is_blank_line:\n last_element = parser_state.token_document[-1]\n if was_forced:\n pre_tokens.insert(0, last_element)\n else:\n pre_tokens.append(last_element)\n del parser_state.token_document[-1]\n return pre_tokens\n\n # pylint: enable=too-many-arguments, too-many-locals\n\n # pylint: disable=too-many-arguments\n @staticmethod\n def __look_for_pragmas(\n position_marker,\n line_to_parse,\n container_depth,\n extracted_whitespace,\n parser_properties,\n ):\n\n found_pragmas = False\n if parser_properties.is_pragmas_enabled:\n found_pragmas = PragmaExtension.look_for_pragmas(\n position_marker,\n line_to_parse,\n container_depth,\n extracted_whitespace,\n parser_properties,\n )\n return found_pragmas\n\n # pylint: enable=too-many-arguments\n\n\n# pylint: disable=too-few-public-methods\n# pylint: disable=too-many-lines\nclass ContainerIndices:\n \"\"\"\n Class to provide for encapsulation on a group of container indices.\n \"\"\"\n\n def __init__(self, ulist_index, olist_index, block_index):\n self.ulist_index = ulist_index\n self.olist_index = olist_index\n self.block_index = block_index\n\n def __str__(self):\n return f\"{{ContainerIndices:ulist_index:{self.ulist_index};olist_index:{self.olist_index};block_index:{self.block_index}}}\"\n\n\n# pylint: enable=too-few-public-methods\n","sub_path":"pymarkdown/container_block_processor.py","file_name":"container_block_processor.py","file_ext":"py","file_size_in_byte":56732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"377883926","text":"\"\"\"\r\nHeap homework\r\n@author: login\r\n\"\"\"\r\n\r\ndef newHeap():\r\n return [None]\r\n \r\ndef isEmpty(H):\r\n return len(H) == 1\r\n\r\nH = [None,(2,'A'),(12,'B'),(10,'C'),(24,'D'),(16,'E'),(14,'F'),(18,'G'),(30,'H'),(26,'I'),(20,'J'),(32,'K'),(28,'L'),(22,'M')]\r\nHe= [None, (1, 'P'), (2, 'A'), (5, 'N'), (12, 'B'), (16, 'E'), (14, 'F'), (10, 'C'), (24, 'D'), (26, 'I'), (20, 'J'), (32, 'K'), (28, 'L'), (22, 'M'), (18, 'G'), (15, 'O'), (30, 'H')]\r\n\r\ndef heapPush(H,x): \r\n i=len(H) \r\n H.append(x)\r\n while i > 1 and x < H[i//2]: \r\n (H[i],H[i//2]) = (H[i//2] , H[i]) \r\n i//=2 \r\n return H\r\n \r\n\r\ndef heapPop(H):\r\n if isEmpty(H):\r\n return None\r\n (B,length)= (True,len(H)) \r\n i=1 \r\n (H[1],H[length-1]) = (H[length-1],H[1])\r\n Mini = H.pop()\r\n length-=1 \r\n while B and 2*i < length : \r\n if 2*i+1 == length :\r\n if H[2*i] < H[i]:\r\n i*=2\r\n swap=H[i]\r\n else :\r\n B=False\r\n else:\r\n if H[2*i] swap :\r\n (H[i],H[i//2]) = (H[i//2],H[i])\r\n elif B and H[i//2] <= swap:\r\n B=False\r\n return Mini\r\n \r\ndef heapUpdate(H, x, pos):\r\n length = len(H)\r\n if pos <= 0 or pos >= length :\r\n raise Exception('mauvaise valeur pos') \r\n H[pos] = x\r\n while pos > 1 and x < H[pos//2]: \r\n (H[pos],H[pos//2]) = (H[pos//2] , H[pos]) \r\n pos//=2 \r\n return H\r\n \r\n \r\n \r\n \r\n\r\n#------------------------------------------------------------------------------\r\n\r\n\r\ndef heapSort(L):\r\n length = len(L)\r\n H = newHeap()\r\n for i in range(length):\r\n heapPush(H,L[i])\r\n for i in range(length):\r\n L[i]=heapPop(H)\r\n return L\r\n\r\n \r\n \r\ndef heapify(H):\r\n for i in range (1,len(H)):\r\n heapUpdate(H,H[i],i)\r\n return H \r\n","sub_path":"fang_c-heap.py","file_name":"fang_c-heap.py","file_ext":"py","file_size_in_byte":2068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"419591040","text":"import turtle # 1. import the modules\nimport random\n\n\nwn = turtle.Screen() # 2. Create a screen\nwn.setup(750, 250, 0, 0)\nwn.bgcolor('lightblue')\n\nlance = turtle.Turtle() # 3. Create two turtles\nandy = turtle.Turtle()\nlance.color('red')\nandy.color('blue')\nlance.shape('turtle')\nandy.shape('turtle')\n\nandy.up() # 4. Move the turtles to their starting point\nlance.up()\nandy.goto(-300, 20)\nlance.goto(-300, -20)\n\nandy_max_step = 75\nlance_max_step = 85\n\nnum_steps = random.randrange(5, 16)\nprint(\"Today's race will be\", num_steps, \"lengths\")\nfor n in range(num_steps):\n andy.forward(random.randrange(0, andy_max_step))\n andy.write(str(n + 1))\n print('after', n + 1, 'steps andy is at ', andy.xcor())\n # andy.dot()\n lance.forward(random.randrange(0, lance_max_step))\n lance.write(str(n + 1))\n print('after', n + 1, 'steps lance is at ', lance.xcor())\n # lance.dot()\nandy.hideturtle()\nlance.hideturtle()\n\n\nwn.exitonclick()\n","sub_path":"unit1/Chapter 04 - Modules (and Turtles)/Studio 3 - Turtle Racing.py","file_name":"Studio 3 - Turtle Racing.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"642832375","text":"from matplotlib import pyplot as plt\nfrom datetime import datetime\nfrom matplotlib.gridspec import GridSpec\nimport matplotlib.dates as mdates\nimport matplotlib.ticker as mticker\nimport pandas as pd\nimport numpy as np\nimport math\n\nclass AeroTool():\n def __init__(self):\n pass\n\n # this func plot the industry nav and the ideal nav using given pressures.\n # @bench indicate the industry itself, @ideal indicate the prescribed strategy.\n # in the bottom figure, the solid line indicate buy pressure, the dotted line\n # indicate sell pressure, and both are large when value are postive.\n @staticmethod\n def Xray_standalone(ticker,conf,startDay=None, endDay=None):\n q = 252\n perf = pd.DataFrame(columns=['bench', 'ideal'], index=['ret', 'risk', 'sr'])\n\n ass = pd.read_csv(\"{}.csv\".format(ticker), header=0,dtype={'tradingDay': str})\n\n holding = ass['ideal'].shift(periods=1).fillna(value=0)\n\n ass['nav-bench'] = ass['logR'].cumsum().apply(lambda x: np.exp(x))\n #@lr is a pd.Series of log returns.\n def _performance(lrets,q,rf=0.00):\n lrets = lrets.fillna(value=0)\n excess = np.exp(lrets.mean()*q)-rf-1\n daily_gain = lrets.apply(lambda x: np.exp(x)-1)\n risk = daily_gain.std()*np.sqrt(q)\n sr = excess/risk\n return excess,risk,sr\n\n perf.loc[:, 'bench'] = _performance(ass['logR'], q)\n\n daily_gain = ass['logR'].apply(lambda x: np.exp(x) - 1) * holding\n ass['nav-ideal'] = (daily_gain + 1).cumprod()\n perf.loc[:, 'ideal'] = _performance(daily_gain.apply(lambda x: np.log(1 + x)), q)\n\n if startDay!=None:\n ass = ass[ass['tradingDay'] > startDay]\n if endDay!=None:\n ass = ass[ass['tradingDay'] < endDay]\n\n # ass = ass.set_index('tradingDay')\n ass['tradingDay_index'] = ass['tradingDay'].apply(lambda x: datetime.strptime(x, \"%Y%m%d\").date())\n ass = ass.set_index('tradingDay_index')\n\n fig = plt.figure()\n gs = GridSpec(3, 3)\n ax1 = plt.subplot(gs[:2, :])\n ax2 = plt.subplot(gs[2:3, :], sharex=ax1)\n\n lns1 = ax1.plot(ass['nav-bench'], color='black',\n label='bench(left):ret={:.2f},risk={:.2f},sr={:.2f}'.format(perf.iloc[0, 0], perf.iloc[1, 0],\n perf.iloc[2, 0]))\n ax1_ = ax1.twinx()\n lns2 = ax1_.plot(ass['nav-ideal'], color='red',\n label='ideal(right):ret={:.2f},risk={:.2f},sr={:.2f}'.format(perf.iloc[0, 1], perf.iloc[1, 1],\n perf.iloc[2, 1]))\n ax1.grid()\n\n ax2.plot(ass['buyP'], linestyle='-', color='black')\n ax2.plot(ass['sellP'], linestyle=':', color='black')\n ax2_ = ax2.twinx()\n ax2_.plot(ass['ideal'], color='red')\n ax2.grid()\n\n # added these three lines\n lns = lns1 + lns2\n labs = [l.get_label() for l in lns]\n ax1.legend(lns, labs, loc=2)\n\n ax1.set_title('Xray[{}]: conf=[ratio={},thres={},granu={}], avgH={:.2f}'.\n format(ticker, conf['gradient_ratio'],conf['port_thres'], conf['granularity'], ass['ideal'].mean()))\n\n # ax2.legend()\n plt.rcParams['font.sans-serif'] = ['SimHei']\n plt.setp(ax1.get_xticklabels(), visible=False)\n ax2.xaxis.set_major_locator(mticker.MultipleLocator(150))\n ax2.set_xticklabels(labels=ass.index, rotation=90)\n plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%y/%m'))\n\n plt.savefig(\"Xray-{}.png\".format(ticker))\n plt.show()\n ass.iloc[:,:-2].to_csv(\"{}.csv\".format(ticker), index=False)\n\n # @long_weight is a pd.Series about buy pressure\n # @short_weight is a pd.Series about sell pressure\n # this func return the combined holding.\n @staticmethod\n def combineWeight(long_weight, short_weight, conf=None):\n if conf==None:\n conf = {\"gradient_ratio\": 1.2, \"port_thres\": 10,\"granularity\":0.05}\n\n gradient_long = float(conf['granularity'])\n gradient_short = float(conf['gradient_ratio']) * gradient_long\n port_thres = float(conf['port_thres'])\n\n combined_weight = pd.DataFrame(np.zeros([len(long_weight),2]), index=long_weight.index, columns=['Weight',\"Delta\"])\n last_port = 0.0\n for t in range(len(long_weight)):\n target_date = long_weight.index[t]\n delta = -gradient_long * long_weight.loc[target_date] + gradient_short * short_weight.loc[target_date]\n current_port = last_port + delta\n if current_port > port_thres:\n current_port = port_thres\n if current_port < 0:\n current_port = 0\n combined_weight.loc[target_date, \"Weight\"] = current_port\n combined_weight.loc[target_date, \"Delta\"] = delta\n\n if math.isnan(current_port):\n last_port = 0\n else:\n last_port = current_port\n\n combined_weight = combined_weight / port_thres\n\n return combined_weight\n\n\n","sub_path":"industry-rotation-main/AeroTool/AeroTool.py","file_name":"AeroTool.py","file_ext":"py","file_size_in_byte":5173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"59877617","text":"import tensorflow as tf\n\ndef parse_fn(filename):\n print('Parse filename %s' % filename)\n img = tf.io.read_file(filename)\n img = tf.io.decode_png(img, channels=3)\n img = tf.image.resize(img, [224, 224])\n img /= 255.0\n\n label = tf.strings.split(filename, '/')\n out = table.lookup(label[-2])\n return img, out\n\n\ntable = tf.lookup.StaticHashTable(\n tf.lookup.KeyValueTensorInitializer([\"normal\", \"dead\", \"rotten\", \"clear\"], [0, 1, 2, 3], key_dtype=tf.string, value_dtype=tf.int64), 4)\ndataset = tf.data.Dataset.list_files('/mnt/projects/Data/Training/*/*.png')\ndataset = dataset.shuffle(True)\ndataset = dataset.repeat()\ndataset = dataset.map(map_func=parse_fn)\ndataset = dataset.batch(2)\n\nfor x in dataset:\n print(x)\n","sub_path":"models/official/efficientnet/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"245175494","text":"import cv2\nimport numpy as np\nfrom PIL import Image\nfrom PIL import ImageFont\nfrom PIL import ImageDraw\n\n\n\ndef prikaziSliku(img):\n cv2.imshow('image', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\ndef ucitajSliku(putanja):\n img = cv2.imread(putanja) #ucita sliku sa prosledjene putanje\n # bluruje sliku - bude onako smooth mutna\n img = cv2.GaussianBlur(img, (5, 5), 0)\n # menja RGB u BGR i postaje crno-bela slika\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # kreira masku - niz koji je dimenzija crno bele slike\n mask = np.zeros((gray.shape), np.uint8)\n # pretstavlja elipse na osnovu kojih se detektuju oblasti\n kernel1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))\n # detektuje one \"izrazenije\" oblasti koje su se odredile na osnovu kernela\n # i uklanja sumove\n close = cv2.morphologyEx(gray, cv2.MORPH_CLOSE, kernel1)\n # slika postaje crno bela bez nijansi sive\n div = np.float32(gray) / (close)\n res = np.uint8(cv2.normalize(div, div, 0, 255, cv2.NORM_MINMAX))\n # treba jos obraditi sliku pa vracamo i res i res2, zato vracamo res2 a res jos obradjujemo\n res2 = cv2.cvtColor(res, cv2.COLOR_GRAY2BGR)\n resNovi = izolujMatricu(res, mask)\n\n return resNovi,res2\n\ndef izolujMatricu(res, mask):\n # konvertuje sve u crno belo za lakse izolovanje\n # brojevi 0,1,201 i 2 su eksperimentalno dobijeni\n thresh = cv2.adaptiveThreshold(res, 255, 0, 1, 201, 2)\n # pronalazi sve konture u obliku cetvorougla\n # smesta u pomenljivu contours, a ove prazne promenljive\n # su tu zato sto funkcija fintContours mora da ima 3 izlaza\n # i smesta u srednju promenljivu\n _, contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n # pretpostavka : najveci kvadrat na slici pretstavlja sudoku matricu\n max_area = 0\n best_cnt = None\n for cnt in contours:\n # pretrazuje i gleda svaku konturu posebno\n area = cv2.contourArea(cnt)\n # pretpostavka da ce matrica da zauzima veci deo slike\n if area > 1000:\n if area > max_area:\n max_area = area\n best_cnt = cnt\n\n # crta konture : na masku(crnu pozadinu) stavlja najveci kvadrat koji je preuzet\n # prvi parametar je izvorna slika, drugi parametar pretstavlja konture koje se iscrtavaju\n # treci je index konture (posto imamo samo jednu, prosledjuje se 0 (da zelimo iscrtati sve konture\n # stavi se -1)\n # ovo ostalo treba da su za boje i to, ne radi kad se unese nesto drugo od 255 i -1\n cv2.drawContours(mask, [best_cnt], 0, 255, -1)\n\n # u masci se nalazi beli cetvorougao koji je dimenzija sudoku matrice\n # potrebno je samo jos sa AND operacijom da se puste res i mask i kao rezultat\n # se izbacuje izdvojena sudoku matrica sa slike na crnoj pozadini\n res = cv2.bitwise_and(res, mask)\n return res\n\n\ndef detekcijaHorizontalnihLinija(res):\n kernelx = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 5))\n\n dx = cv2.Sobel(res, cv2.CV_16S, 1, 0)\n dx = cv2.convertScaleAbs(dx)\n cv2.normalize(dx, dx, 0, 255, cv2.NORM_MINMAX)\n ret, close = cv2.threshold(dx, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n close = cv2.morphologyEx(close, cv2.MORPH_DILATE, kernelx, iterations=1)\n\n _, contour, hierarch = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n for cnt in contour:\n x, y, w, h = cv2.boundingRect(cnt)\n if h / w > 5:\n cv2.drawContours(close, [cnt], 0, 255, -1)\n else:\n cv2.drawContours(close, [cnt], 0, 0, -1)\n close = cv2.morphologyEx(close, cv2.MORPH_CLOSE, None, iterations=2)\n closex = close.copy()\n return closex\n\ndef detekcijaVertikalnihLinija(res):\n kernely = cv2.getStructuringElement(cv2.MORPH_RECT, (7, 1))\n dy = cv2.Sobel(res, cv2.CV_16S, 0, 2)\n dy = cv2.convertScaleAbs(dy)\n cv2.normalize(dy, dy, 0, 255, cv2.NORM_MINMAX)\n ret, close = cv2.threshold(dy, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)\n close = cv2.morphologyEx(close, cv2.MORPH_DILATE, kernely)\n\n _, contour, hierarch = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n for cnt in contour:\n x, y, w, h = cv2.boundingRect(cnt)\n if w / h > 5:\n cv2.drawContours(close, [cnt], 0, 255, -1)\n else:\n cv2.drawContours(close, [cnt], 0, 0, -1)\n\n close = cv2.morphologyEx(close, cv2.MORPH_DILATE, None, iterations=2)\n closey = close.copy()\n return closey\n\ndef dodajKoordinatePreseka(res,img):\n i = 0\n _, contour, hierarch = cv2.findContours(res, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n centroids = []\n for cnt in contour:\n mom = cv2.moments(cnt)\n (x, y) = int(mom['m10'] / mom['m00']), int(mom['m01'] / mom['m00'])\n cv2.circle(img, (x, y), 5, (0, 255, 0), -1)\n centroids.append((x, y))\n return centroids\n\n\ndef setuj_i_sortiraj(centroids):\n centroids = np.array(centroids, dtype=np.float32)\n centri = centroids.reshape((100, 2))\n sortirani_centri = centri[np.argsort(centri[:, 1])]\n\n stekovani = np.vstack([sortirani_centri[i * 10:(i + 1) * 10][np.argsort(sortirani_centri[i * 10:(i + 1) * 10, 0])] for i in range(10)])\n stekovani_r = stekovani.reshape((10, 10, 2))\n return stekovani_r,stekovani\n\ndef kreirajMatricu(b,bm,res2):\n niz = []\n output = np.zeros((450, 450, 3), np.uint8)\n for i, j in enumerate(b):\n # pred_int(\"j = \",j)\n red_i = i // 10\n kolona_i = i % 10\n #pred_int('int(red_i) = ',int(red_i))\n #pred_int(kolona_i)\n if kolona_i != 9 and red_i != 9:\n src = bm[red_i:red_i + 2, kolona_i:kolona_i + 2].reshape((4, 2))\n #pred_int(i, '\\n', src)\n dst = np.array([[kolona_i * 50, red_i * 50], [(kolona_i + 1) * 50 - 1, red_i * 50], [kolona_i * 50, (red_i + 1) * 50 - 1],\n [(kolona_i + 1) * 50 - 1, (red_i + 1) * 50 - 1]], np.float32)\n retval = cv2.getPerspectiveTransform(src, dst)\n warp = cv2.warpPerspective(res2, retval, (450, 450))\n output[int(red_i) * 50:(int(red_i) + 1) * 50 - 1, int(kolona_i) * 50:(int(kolona_i) + 1) * 50 - 1] = warp[int(red_i) * 50:(int(red_i) + 1) * 50 - 1,\n int(kolona_i) * 50:(int(kolona_i) + 1) * 50 - 1].copy()\n niz.append(warp[int(red_i) * 50:(int(red_i) + 1) * 50 - 1,int(kolona_i) * 50:(int(kolona_i) + 1) * 50 - 1].copy())\n #pred_ikaziSliku(output)\n return output,niz\n\n\ndef razbiSlikuNaKvadrate(img):\n # Creates a list containing 9 lists, each of 9 items, all set to 0\n w, h = 9, 9;\n Matrix = [[0 for x in range(w)] for y in range(h)]\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n for i in range(0, 9):\n for j in range(0, 9):\n img_crop = img[i*50:(i+1)*50, j*50:(j+1)*50]\n #img_crop = resize_region(img_crop)\n Matrix[i][j] = img_crop\n\n return Matrix\n\ndef iscrtajBrojeveNaSliku(ulazna_matrica, resena_matrica, slika):\n image = Image.fromarray(slika, 'RGB')\n draw = ImageDraw.Draw(image)\n font = ImageFont.truetype('arial.ttf', 40)\n for i in range(0, 9):\n for j in range(0, 9):\n # draw.text((i*50 + 10, j*50), \"1\", (i*30, i*j, j*20),font = font)\n if ulazna_matrica[j][i] == 0:\n #print(ulazna_matrica[i][j])\n draw.text((i * 50 + 10, j * 50), str(resena_matrica[j][i]), (0, 255, 0), font=font)\n\n konacna_slika = np.array(image)\n # kovertovanje RGB i BGR\n konacna_slika = konacna_slika[:, :, ::-1].copy()\n prikaziSliku(konacna_slika)\n","sub_path":"fun_slike.py","file_name":"fun_slike.py","file_ext":"py","file_size_in_byte":7649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"320087625","text":"\nimport time\nimport requests\nfrom bs4 import BeautifulSoup\nuser_agent = \"\"\n'''\nimport requests\nfrom bs4 import BeautifulSoup\nimport time\nurl = \"https://www.tripadvisor.cn/Hotel_Review-g294212-d1414087-Reviews-Beijing_Qianmen_Guanqi_Hotel-Beijing.html#apg=029157d74b54476d9f763e7821ad1423&ss=472FE5670259B7973E544AC1E6DB6BEF\"\nwb_data = requests.get(url)\nsoup = BeautifulSoup(wb_data.text,'lxml')\n\n'''\nurl = ['https://www.tripadvisor.cn/Hotels-g294212-oa{}-Beijing-Hotels.html'.format(str(i)) for i in range(30, 900, 30)]\n\n\ndef main():\n for i in url:\n a(i)\n\n\ndef a(a):\n time.sleep(2)\n wb_data = requests.get(a)\n print(wb_data)\n soup = BeautifulSoup(wb_data.text, 'html-paser')\n titles = soup.select('div.listing_title > a')\n prices = soup.select('div.price-wrap > div')\n imgs = soup.select('div.inner')\n for title, price, img in zip(titles, prices, imgs):\n data = {\n 'title': title.get_text(),\n 'price': list(price.stripped_strings),\n 'img': img.get('data-lazyurl')\n }\n print(data)\n with open('a.txt','a') as f:\n for key in data:\n f.write(str(data[key])+\"\\n\")\n f.close()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"the first 独立.py","file_name":"the first 独立.py","file_ext":"py","file_size_in_byte":1246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"137690352","text":"import os,sys,logging, zlib\nimport numpy as np\nfrom larcv import larcv\nfrom ctypes import c_int\nfrom ublarcvserver import MDPyWorkerBase, Broker, Client\nlarcv.json.load_jsonutils()\n\n\"\"\"\nImplements worker for ubssnet\n\"\"\"\n\nclass UBSSNetWorker(MDPyWorkerBase):\n\n def __init__(self,broker_address,plane,\n weight_file,device,batch_size,\n use_half=False,use_compression=False,\n **kwargs):\n \"\"\"\n Constructor\n\n inputs\n ------\n broker_address str IP address of broker\n plane int Plane ID number. Currently [0,1,2] only\n weight_file str path to files with weights\n batch_size int number of batches to process in one pass\n use_half bool if true, run inference in half-precision\n use_compression bool if true, compress serialized image data \n \"\"\"\n if type(plane) is not int:\n raise ValueError(\"'plane' argument must be integer for plane ID\")\n elif plane not in [0,1,2]:\n raise ValueError(\"unrecognized plane argument. \\\n should be either one of [0,1,2]\")\n else:\n pass\n\n if type(batch_size) is not int or batch_size<0:\n raise ValueError(\"'batch_size' must be a positive integer\")\n\n self.plane = plane\n self.batch_size = batch_size\n self._still_processing_msg = False\n self._use_half = use_half\n self._use_compression = use_compression\n service_name = \"ubssnet_plane%d\"%(self.plane)\n\n super(UBSSNetWorker,self).__init__( service_name,\n broker_address, **kwargs)\n\n self.load_model(weight_file,device,self._use_half)\n if self.is_model_loaded():\n self._log.info(\"Loaded ubSSNet model. Service={}\"\\\n .format(service_name))\n\n def load_model(self,weight_file,device,use_half):\n # import pytorch\n try:\n import torch\n except:\n raise RuntimeError(\"could not load pytorch!\")\n\n # import model\n try:\n from ubssnet import ubSSNet\n except:\n raise RuntimeError(\"could not load ubSSNet model. did you remember\"\n +\" to setup pytorch-uresnet?\")\n\n if \"cuda\" not in device and \"cpu\" not in device:\n raise ValueError(\"invalid device name [{}]. Must str with name \\\n \\\"cpu\\\" or \\\"cuda:X\\\" where X=device number\")\n\n self._log = logging.getLogger(self.idname())\n\n self.device = torch.device(device)\n if not self._use_half:\n self.model = ubSSNet(weight_file).to(self.device)\n else:\n self.model = ubSSNet(weight_file).half().to(self.device)\n self.model.eval()\n\n\n def make_reply(self,request,nreplies):\n \"\"\"we load each image and pass it through the net.\n we run one batch before sending off partial reply.\n the attribute self._still_processing_msg is used to tell us if we\n are still in the middle of a reply.\n \"\"\"\n #print(\"DummyPyWorker. Sending client message back\")\n self._log.debug(\"received message with {} parts\".format(len(request)))\n\n if not self.is_model_loaded():\n self._log.debug(\"model not loaded for some reason. loading.\")\n\n try:\n import torch\n except:\n raise RuntimeError(\"could not load pytorch!\")\n\n # message pattern: [image_bson,image_bson,...]\n\n nmsgs = len(request)\n nbatches = nmsgs/self.batch_size\n\n if not self._still_processing_msg:\n self._next_msg_id = 0\n\n # turn message pieces into numpy arrays\n img2d_v = []\n sizes = []\n frames_used = []\n rseid_v = []\n for imsg in xrange(self._next_msg_id,nmsgs):\n\n c_run = c_int()\n c_subrun = c_int()\n c_event = c_int()\n c_id = c_int()\n \n if self._use_compression:\n try:\n compressed_data = str(request[imsg])\n data = zlib.decompress(compressed_data)\n img2d = larcv.json.image2d_from_pybytes(data,\n c_run, c_subrun, c_event, c_id )\n except:\n self._log.error(\"Image Data (compressed) in message part {}\\\n could not be converted\".format(imsg))\n continue\n else:\n try:\n img2d = larcv.json.image2d_from_pybytes(str(request[imsg]),\n c_run, c_subrun, c_event, c_id )\n except:\n self._log.error(\"Image Data (uncompressed) in message part {}\\\n could not be converted\".format(imsg))\n continue \n \n self._log.debug(\"Image[{}] converted: {}\"\\\n .format(imsg,img2d.meta().dump()))\n\n\n # check if correct plane!\n if img2d.meta().plane()!=self.plane:\n self._log.debug(\"Image[{}] is the wrong plane!\".format(imsg))\n continue\n\n # check that same size as previous images\n imgsize = (int(img2d.meta().cols()),int(img2d.meta().rows()))\n if len(sizes)==0:\n sizes.append(imgsize)\n elif len(sizes)>0 and imgsize not in sizes:\n self._log.debug(\"Next image a different size. \\\n we do not continue batch.\")\n self._next_msg_id = imsg\n break\n img2d_v.append(img2d)\n frames_used.append(imsg)\n rseid_v.append((c_run.value,c_subrun.value,c_event.value,c_id.value))\n if len(img2d_v)>=self.batch_size:\n self._next_msg_id = imsg+1\n break\n\n\n # convert the images into numpy arrays\n nimgs = len(img2d_v)\n self._log.debug(\"converted msgs into batch of {} images. frames={}\"\n .format(nimgs,frames_used))\n np_dtype = np.float32\n if self._use_half:\n np_dtype = np.float16\n img_batch_np = np.zeros( (nimgs,1,sizes[0][0],sizes[0][1]),\n dtype=np_dtype )\n\n for iimg,img2d in enumerate(img2d_v):\n meta = img2d.meta()\n img2d_np = larcv.as_ndarray( img2d )\\\n .reshape( (1,1,meta.cols(),meta.rows()))\n if not self._use_half:\n img_batch_np[iimg,:] = img2d_np\n else:\n img_batch_np[iimg,:] = img2d_np.as_type(np.float16)\n\n # now make into torch tensor\n img2d_batch_t = torch.from_numpy( img_batch_np ).to(self.device)\n with torch.set_grad_enabled(False):\n out_batch_np = self.model(img2d_batch_t).detach().cpu().numpy()\n\n # remove background values\n out_batch_np = out_batch_np[:,1:,:,:]\n\n # compression techniques\n ## 1) threshold values to zero\n ## 2) suppress output for non-adc values\n ## 3) use half\n\n # suppress small values\n out_batch_np[ out_batch_np<1.0e-3 ] = 0.0\n\n # threshold\n for ich in xrange(out_batch_np.shape[1]):\n out_batch_np[:,ich,:,:][ img_batch_np[:,0,:,:]<10.0 ] = 0.0\n\n # convert back to full precision, if we used half-precision in the net\n if self._use_half:\n out_batch_np = out_batch_np.as_type(np.float32)\n\n\n self._log.debug(\"passed images through net. output batch shape={}\"\n .format(out_batch_np.shape))\n # convert from numpy array batch back to image2d and messages\n reply = []\n for iimg in xrange(out_batch_np.shape[0]):\n img2d = img2d_v[iimg]\n rseid = rseid_v[iimg]\n meta = img2d.meta()\n for ich in xrange(out_batch_np.shape[1]):\n out_np = out_batch_np[iimg,ich,:,:]\n out_img2d = larcv.as_image2d_meta( out_np, meta )\n bson = larcv.json.as_pybytes( out_img2d,\n rseid[0], rseid[1], rseid[2], rseid[3] )\n if self._use_compression:\n compressed = zlib.compress(bson)\n else:\n compressed = bson\n reply.append(compressed)\n\n if self._next_msg_id>=nmsgs:\n isfinal = True\n self._still_processing_msg = False\n else:\n isfinal = False\n self._still_processing_msg = True\n\n self._log.debug(\"formed reply with {} frames. isfinal={}\"\n .format(len(reply),isfinal))\n return reply,isfinal\n\n def is_model_loaded(self):\n return self.model is not None\n","sub_path":"app/ubssnet/UBSSNetWorker.py","file_name":"UBSSNetWorker.py","file_ext":"py","file_size_in_byte":8920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"144711593","text":"from tools.preps.oof_features import mk_rank_oof_features\nfrom tools.utils.args import parse_mk_oof_feature_args\n\n\ndef main():\n args = parse_mk_oof_feature_args()\n oof_features = mk_rank_oof_features(\n args.oof_filename,\n args.sub_filename,\n args.col_name)\n feature_name = f'./mnt/inputs/features/{args.col_name}.pkl.gz'\n print(f'now saving to {feature_name}')\n oof_features[args.col_name].reset_index(drop=True).to_pickle(feature_name)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"runs/p007_mk_rank_oof_features.py","file_name":"p007_mk_rank_oof_features.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"634242198","text":"\n#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n \n# Version de decembre 2016 incluant la fonction taille de lot jusque 49\n\n\n\ntry:\n from tkinter import *\nexcept:\n from Tkinter import *\nimport socket\nimport argparse\n\ndef marquerNiveau(x,y):\n#procedure pour dessiner le marqueur rond a l'emplacement x,y\n canvas.coords(marqueur,taille*x,hauteur/2-taille*(1-y),taille*(x+1),hauteur/2-taille*(2-y))\n \nparser = argparse.ArgumentParser(description='wipbox client')\nparser.add_argument('--ip', nargs=1, help='adresse ip')\nparser.add_argument('--port', type=int, help='numero de port')\nparser.add_argument('--stock', type=int, help='stock')\n#ATTENTION : nous allons coder les noms de machine sur 6 caracteres obligatoirement\nparser.add_argument('--nom', type=str, help='nom de la machine')\nargs = parser.parse_args()\n\nif(args.ip is not None):\n serveur_ip = args.ip[0]\nserveur_port = 1111\nif(args.port is not None):\n serveur_port = args.port\n#ATTENTION ne pas depasser 49\nstock=29\nif(args.stock is not None):\n stock = args.stock\n\nprint(\"adress \" + serveur_ip + \"[\" + str(serveur_port) + \"]\" )\n\n\n#Definition de la taille de l ecran et du stock\nfenetre = Tk()\nthreshold=input (\"quelle est le seuil d'alerte pour cette machine ? \")\n#protection sur le nombre de cellules du tableau\nif stock>49:\n stock = 49\nlTab = stock//10+1\nprint(\"le tableau aura \",lTab,\" lignes\")\nlargeur =fenetre.winfo_screenwidth()\nhauteur=fenetre.winfo_screenheight()\ntaille=largeur/10\nlevel =0\n\n#initialisation de la fenetre\nfenetre.title(args.nom)\nfenetre.resizable(0,0)\ncanvas = Canvas(fenetre, width=largeur, height=hauteur, background='black')\ntry:\n photo = PhotoImage(file=\"ntn.jpeg\")\n canvas.create_image(0, 0, anchor=NW, image=photo)\nexcept:\n print (\"load img fail\")\ncoordx=level\n\n\n#dessin du tableau\ni=0\nfor i in range(stock+1):\n if iint(threshold):\n couleur='indianred3'\n j= i//10\n canvas.create_rectangle(taille*(i-10*j),hauteur/2-(2-j)*taille,taille*(i-10*j+1),hauteur/2-(1-j)*taille, fill=couleur,outline='white')\n canvas.create_text(taille*(0.5+i-10*j),hauteur/2-(1.5-j)*taille,justify=CENTER,text=i,font=\"arial 18 bold\")\n#position initiale du curseur \nmarqueur=canvas.create_oval(0,0,0,0,outline='cornflower blue',width=16)\nmarquerNiveau(0,0)\ncanvas.pack()\n\n\ndef send_level(level):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((serveur_ip, serveur_port))\n print (level)\n if level<10:\n codebyte=(\"0\"+str(level)).encode('ascii')\n elif level>=10:\n codebyte=str(level).encode('ascii')\n nombyte=str(args.nom).encode('ascii')\n thresholdbyte = str(threshold).encode('ascii')\n print (codebyte)\n print (nombyte)\n s.send((nombyte) + (codebyte) + (thresholdbyte))\n \n\n#Detection du clic, de la position et positionnement d'un symbole\ndef touche(event):\n if hauteur/2-2*taille\", touche)\n\n\nfenetre.mainloop()\n","sub_path":"ghostclient.py","file_name":"ghostclient.py","file_ext":"py","file_size_in_byte":3468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"644652139","text":"class Solution(object):\n def containsNearbyAlmostDuplicate(self, nums, k, t):\n \"\"\"\n :type nums: List[int]\n :type k: int\n :type t: int\n :rtype: bool\n \"\"\"\n newNums = [[x, i] for i, x in enumerate(nums)]\n newNums.sort()\n while len(newNums) > 1:\n a = newNums.pop()\n b = 1\n while b <= len(newNums) and newNums[-b][0] + t >= a[0]:\n if abs(newNums[-b][1] - a[1]) <= k:\n return True\n b += 1\n return False","sub_path":"containsNearbyAlmostDuplicate.py","file_name":"containsNearbyAlmostDuplicate.py","file_ext":"py","file_size_in_byte":551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"136349330","text":"from __future__ import print_function\nfrom __future__ import absolute_import\n\nimport os\nimport cv2\nimport random\nimport PIL.Image as Image\nimport numpy as np\nfrom config import settings\nfrom utils import Aug\nfrom torchvision import transforms\n\n#random.seed(1385)\n\nclass voc_train():\n\n \"\"\"Face Landmarks dataset.\"\"\"\n\n def __init__(self, args, mode=None, transform=None):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file with annotations.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.mode = mode\n self.num_classes = 8\n self.group = args.group\n self.num_folds = args.num_folds\n #self.binary_map_dir = os.path.join(settings.DATA_DIR, 'VOCdevkit2012/VOC2012/', 'Binary_map_aug/train') #val\n self.data_list_dir = os.path.join('data_list/train')\n self.img_dir = os.path.join(settings.DATA_DIR, 'IMAGES/')\n self.mask_dir = os.path.join(settings.DATA_DIR, 'MASKS/')\n #self.binary_mask_dir = os.path.join(settings.DATA_DIR, 'VOCdevkit2012/VOC2012/', 'Binary_map_aug/train/')\n\n self.abnormalities = settings.abnormalities\n self.history_mask_list = [None] * self.__len__()\n \n self.train_id_list, self.val_id_list = self.get_train_id_list()\n print('Train set: ', self.train_id_list)\n print('Val set: ', self.val_id_list)\n\n self.list_splite = self.get_total_list()\n \n self.list_splite_len = len(self.list_splite)\n \n self.list_class = self.get_class_list()\n # print('list class: ', self.list_class)\n\n self.transform = transform\n self.aug = Aug.Augmentation()\n\n self._img = transforms.Compose([\n transforms.ToPILImage(),\n transforms.ToTensor(),\n transforms.Normalize(mean=settings.mean_vals, std=settings.std_vals)\n ])\n self._mask = transforms.Compose([\n transforms.ToPILImage(),\n transforms.ToTensor()\n ])\n\n self.count = 0\n self.random_generator = random.Random()\n if self.mode == 'train':\n self.len = args.max_steps * args.batch_size *2\n else:\n self.len = len(self.list_splite)\n #self.random_generator.shuffle(self.list_splite)\n #self.random_generator.seed(1385)\n\n def get_train_id_list(self):\n num = int(self.num_classes/ self.num_folds)\n val_set = [self.group * num + v for v in range(num)]\n train_set = [x for x in range(self.num_classes) if x not in val_set]\n\n return train_set, val_set\n\n def get_total_list(self):\n new_exist_class_list = []\n\n fold_list = [0, 1, 2, 3]\n print('Mode: ', self.mode)\n if self.mode == 'train':\n fold_list.remove(self.group)\n print('FOLD: ', fold_list)\n for fold in fold_list:\n f = open(os.path.join(self.data_list_dir, 'split%1d_train.txt' % (fold)))\n while True:\n item = f.readline()\n if item == '':\n break\n img_name = item[:len(item)] #item[:11]\n # print('img name:', img_name)\n\n if 'angioectasia' in img_name:\n cat = self.abnormalities[img_name[:len(img_name)-6]]\n else:\n cat = self.abnormalities[img_name[:len(img_name)-2]]\n new_exist_class_list.append([img_name, cat])\n print(\"Total images are : \", len(new_exist_class_list))\n else:\n fold = self.group\n print('FOLD: ', fold)\n f = open(os.path.join(self.data_list_dir, 'split%1d_train.txt' % (fold)))\n while True:\n item = f.readline()\n if item == '':\n break\n img_name = item[:len(item)] #item[:11]\n # print('img name:', img_name)\n\n if 'angioectasia' in img_name:\n cat = self.abnormalities[img_name[:len(img_name)-6]]\n else:\n cat = self.abnormalities[img_name[:len(img_name)-2]]\n new_exist_class_list.append([img_name, cat])\n\n print(\"Total images are : \", len(new_exist_class_list))\n # if need filter\n new_exist_class_list = self.filte_multi_class(new_exist_class_list)\n return new_exist_class_list\n\n def filte_multi_class(self, exist_class_list):\n\n new_exist_class_list = []\n for name, class_ in exist_class_list:\n\n mask_path = self.mask_dir + name[:-1] + 'm.png'\n # print(name, len(name))\n mask = cv2.imread(str(mask_path))\n # print(mask.shape)\n labels = np.unique(mask[:,:,0])\n\n labels = [label - 1 for label in labels if label != 255 and label != 0]\n if set(labels).issubset(self.train_id_list):\n new_exist_class_list.append([name, class_])\n print(\"Total images after filted are : \", len(new_exist_class_list))\n return new_exist_class_list\n\n\n def get_class_list(self):\n list_class = {}\n for i in range(self.num_classes):\n list_class[i] = []\n for name, class_ in self.list_splite:\n # print(name, class_)\n list_class[class_].append(name)\n\n return list_class\n\n def read_img(self, name):\n path = self.img_dir + name[:-1] + '.png'\n img = cv2.imread(path)\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n return img\n\n def read_mask(self, name, category):\n path = self.mask_dir + name[:-1] + 'm.png'\n mask = cv2.imread(path, 0) \n _, mask = cv2.threshold(mask, 200, 255, cv2.THRESH_BINARY)\n # mask = mask / 255\n # mask[mask!=category+1] = 0\n # mask[mask==category+1] = 1\n\n return mask #.astype(np.float32)\n '''\n def read_binary_mask(self, name, category):\n path = self.binary_mask_dir +str(category+1)+'/'+ name + '.png'\n mask = cv2.imread(path)/255\n\n return mask[:,:,0].astype(np.float32)\n '''\n def load_frame(self, support_name, query_name, class_):\n support_img = self.read_img(support_name)\n query_img = self.read_img(query_name)\n support_mask = self.read_mask(support_name, class_)\n query_mask = self.read_mask(query_name, class_)\n\n #support_mask = self.read_binary_mask(support_name, class_)\n #query_mask = self.read_binary_mask(query_name, class_)\n\n return query_img, query_mask, support_img, support_mask, class_\n\n def random_choose(self):\n\n if self.mode == 'train':\n class_ = np.random.choice(self.train_id_list, 1, replace=False)[0]\n # print('class: ', class_)\n else:\n class_ = np.random.choice(self.val_id_list, 1, replace=False)[0]\n # print('class: ', class_)\n\n cat_list = self.list_class[class_]\n # print(cat_list, len(cat_list))\n\n sample_img_ids_1 = np.random.choice(len(cat_list), 2, replace=False)\n\n query_name = cat_list[sample_img_ids_1[0]]\n print('query image name: ', query_name)\n support_name = cat_list[sample_img_ids_1[1]]\n print('support image name: ', support_name)\n\n return support_name, query_name, class_\n\n def show(self, img):\n cv2.imshow('img', img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n def __len__(self):\n return 2 #self.len #len(self.train_id_list) \n\n def __getitem__(self, idx):\n support_name, query_name, class_ = self.random_choose()\n\n query_img, query_mask, support_img, support_mask, class_ = self.load_frame(support_name, query_name, class_)\n\n _aug = self.aug._aug()\n query_augmented = _aug(image=query_img, mask=query_mask)\n query_img = query_augmented['image']\n query_mask = query_augmented['mask']\n\n # _, query_mask = cv2.threshold(query_mask, 200, 255, cv2.THRESH_BINARY)\n # self.show(query_img)\n # self.show(query_mask)\n\n query_img = self._img(query_img)\n query_mask = self._mask(query_mask)\n\n support_augmented = _aug(image=support_img, mask=support_mask)\n support_img = support_augmented['image']\n support_mask = support_augmented['mask']\n\n # _, support_mask = cv2.threshold(support_mask, 200, 255, cv2.THRESH_BINARY)\n # self.show(support_img)\n # self.show(support_mask)\n\n support_img = self._img(support_img)\n support_mask = self._mask(support_mask)\n\n # if self.transform is not None:\n # query_img, query_mask = self.transform(query_img, query_mask)\n # support_img, support_mask = self.transform(support_img, support_mask)\n\n if self.history_mask_list[index] is None:\n\n history_mask=torch.zeros(2,41,41).fill_(0.0)\n\n else:\n if random.random()>self.prob:\n history_mask=self.history_mask_list[index]\n else:\n history_mask = torch.zeros(2, 41, 41).fill_(0.0)\n\n self.count = self.count + 1\n\n return query_img, query_mask, support_img, support_mask, history_mask, class_, idx\n","sub_path":"data/coco_train.py","file_name":"coco_train.py","file_ext":"py","file_size_in_byte":9312,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"45817391","text":"from datetime import datetime\nfrom django.shortcuts import redirect\nfrom django.contrib.auth.mixins import AccessMixin\nfrom django.views.generic import CreateView, DeleteView, UpdateView\nfrom django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin\nfrom django.contrib.auth.tokens import PasswordResetTokenGenerator\nfrom six import text_type\nfrom threading import Thread\nfrom users.models import Profile, Account\nfrom django.http import Http404\nfrom django.urls import reverse\nfrom .utils import (\n assembly, percentages_of_incomes, days_of_month,\n daily_avg, max_amount, check_recurrent_or_new,\n delete_recurrent_object\n)\n\n\nclass ObjectCreateListViewMixin(CreateView):\n model = None\n form_class = None\n model_name = None\n color = None\n template_name = 'users/create-update-list-objects.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n date = datetime.now()\n account = Account.objects.get(id=self.kwargs['pk'])\n obj = self.model.objects.filter(\n user=self.request.user,\n account=account,\n created_date__year=date.year,\n created_date__month=date.month\n )\n recurrent_obj = self.model.objects.filter(\n user=self.request.user, recurrent=True,\n account=account,\n created_date__year=date.year,\n created_date__month=date.month\n )\n currency = account.currency\n\n if date.month == 1:\n obj_last_month = self.model.objects.filter(\n user=self.request.user,\n account=account,\n created_date__year=date.year - 1,\n created_date__month=date.month + 11\n )\n else:\n obj_last_month = self.model.objects.filter(\n user=self.request.user,\n account=account,\n created_date__year=date.year,\n created_date__month=date.month - 1\n )\n\n total_obj = assembly(obj)\n total_obj_last_month = assembly(obj_last_month)\n check_recurrent_or_new(self.request.user, recurrent_obj, self.model, account)\n\n context['title'] = self.model_name\n context['color'] = self.color\n context['account'] = account\n context['objects'] = obj\n context['total_sum'] = total_obj\n context['currency'] = currency\n context['total_sum_last_month'] = total_obj_last_month\n context['date'] = date\n return context\n\n def form_valid(self, form):\n account = Account.objects.get(id=self.kwargs['pk'])\n form.instance.user = self.request.user\n form.instance.account = account\n return super().form_valid(form)\n\n\nclass ObjectUpdateViewMixin(LoginRequiredMixin, UpdateView):\n model = None\n template_name = 'users/create-update-list-objects.html'\n fields = ['name', 'amount', 'category', 'recurrent']\n model_name = None\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n account = Account.objects.get(id=self.kwargs['id'])\n date = datetime.now()\n obj = self.model.objects.filter(\n user=self.request.user,\n account=account,\n created_date__year=date.year,\n created_date__month=date.month\n )\n recurrent_objs = self.model.objects.filter(\n user=self.request.user,\n account=account,\n recurrent=True,\n created_date__year=date.year,\n created_date__month=date.month\n )\n currency = account.currency\n\n if date.month == 1:\n obj_last_month = self.model.objects.filter(\n user=self.request.user,\n account=account,\n created_date__year=date.year - 1,\n created_date__month=date.month + 11\n )\n else:\n obj_last_month = self.model.objects.filter(\n user=self.request.user,\n account=account,\n created_date__year=date.year,\n created_date__month=date.month - 1\n )\n\n total_obj = assembly(obj)\n total_obj_last_month = assembly(obj_last_month)\n check_recurrent_or_new(self.request.user, recurrent_objs, self.model, account)\n\n context['title'] = self.model_name\n context['color'] = 'success'\n context['account'] = account\n context['objects'] = obj\n context['total_sum'] = total_obj\n context['currency'] = currency\n context['total_sum_last_month'] = total_obj_last_month\n context['date'] = date\n return context\n\n\n def form_valid(self, form):\n account = Account.objects.get(id=self.kwargs['id'])\n current_object_instance = form.save(commit=False)\n old_object = self.model.objects.get(id=current_object_instance.id)\n\n if old_object.recurrent:\n if not current_object_instance.recurrent:\n delete_recurrent_object(self.request.user, old_object, self.model, account)\n\n form.instance.user = self.request.user\n form.instance.account = account\n return super().form_valid(form)\n\n def get_queryset(self, *args, **kwargs):\n return super().get_queryset(*args, **kwargs).filter(user=self.request.user)\n\n\nclass ObjectDeleteViewMixin(LoginRequiredMixin, DeleteView):\n model = None\n template_name = 'users/create-update-list-objects.html'\n object_url = None\n success_url = None\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n return context\n\n def post(self, request, *args, **kwargs):\n account_id = kwargs['id']\n account = Account.objects.get(id=account_id)\n self.success_url = reverse(self.object_url, kwargs={'pk' : account_id})\n\n if request.POST.get('deleteNextRecurrentObject', False):\n delete_recurrent_object(request.user, self.get_object(), self.model, account)\n return super().post(request, *args, **kwargs)\n\n def get_queryset(self, *args, **kwargs):\n return super().get_queryset(*args, **kwargs).filter(user=self.request.user)\n\n\nclass EmailTokenGenerator(PasswordResetTokenGenerator):\n\n def _make_hash_value(self, user, timestamp):\n return(text_type(user.email_verified) + text_type(user.id) + text_type(timestamp))\n\n\nclass SendEmailThreadMixin(Thread):\n\n def __init__(self, email):\n self.email = email\n Thread.__init__(self)\n\n def run(self):\n self.email.send(fail_silently=False)\n\n\nclass IsAuthenticatedMixin(AccessMixin):\n\n def dispatch(self, request, *args, **kwargs):\n if request.user.is_authenticated:\n return redirect('accounts')\n return super().dispatch(request, *args, **kwargs)\n\n\nclass IsSuperuserOrStaffMixin(AccessMixin):\n\n def dispatch(self, request, *args, **kwargs):\n if not request.user.is_superuser or not request.user.is_staff:\n raise Http404()\n return super().dispatch(request, *args, **kwargs)\n\n\nclass IsEmailVerifiedMixin(AccessMixin):\n\n def dispatch(self, request, *args, **kwargs):\n if request.user.email_verified:\n raise Http404()\n return super().dispatch(request, *args, **kwargs)\n\n\nclass TotalAccountDashboardMixin(AccessMixin):\n\n def dispatch(self, request, *args, **kwargs):\n if not request.user.pro_membership:\n raise Http404()\n return super().dispatch(request, *args, **kwargs)\n","sub_path":"common/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":7546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"344810667","text":"import sqlite3\nimport sys\n\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem, QLabel\nfrom addEditCoffeeForm import addWindow\nfrom main_window import MainWindow\nclass MyWidget(QMainWindow, MainWindow):\n def __init__(self):\n super().__init__()\n self.setupUi(self)\n self.resize(1000, 600)\n self.tableWidget.setRowCount(0)\n self.tableWidget.resize(980, 490)\n self.tableWidget.move(10, 50)\n self.pushButton.clicked.connect(self.add_coffe)\n self.pushButton_2.clicked.connect(self.change_coffe)\n self.showResults()\n\n def showResults(self):\n con = sqlite3.connect('.\\\\Data\\\\coffee.sqlite')\n cur = con.cursor()\n result = cur.execute(f\"\"\"select * from coffee order by id\"\"\").fetchall()\n numRows = 0\n columns1 = ['ID', 'Name', 'Sort', 'Stage', 'Beans', 'Taste', 'Price', 'Volume']\n self.tableWidget.setRowCount(0)\n self.tableWidget.setColumnCount(8)\n self.tableWidget.setHorizontalHeaderLabels(columns1)\n for el in result:\n self.tableWidget.insertRow(numRows)\n self.tableWidget.setItem(numRows, 0, QTableWidgetItem(str(el[0])))\n self.tableWidget.setItem(numRows, 1, QTableWidgetItem(str(el[1])))\n self.tableWidget.setItem(numRows, 2, QTableWidgetItem(str(el[2])))\n self.tableWidget.setItem(numRows, 3, QTableWidgetItem(str(el[3])))\n self.tableWidget.setItem(numRows, 4, QTableWidgetItem(str(el[4])))\n self.tableWidget.setItem(numRows, 5, QTableWidgetItem(str(el[5])))\n self.tableWidget.setItem(numRows, 6, QTableWidgetItem(str(el[6])))\n self.tableWidget.setItem(numRows, 7, QTableWidgetItem(str(el[7])))\n\n numRows += 1\n\n self.tableWidget.resizeColumnsToContents()\n\n def add_coffe(self):\n self.add_window = addWindow(1, self.tableWidget)\n self.add_window.show()\n\n def change_coffe(self):\n self.add_window = addWindow(2, self.tableWidget)\n self.add_window.show()\n\n\nclass addWindow(QMainWindow, addWindow):\n def __init__(self, code, table):\n super().__init__()\n self.setupUi(self)\n self.table = table\n self.label8 = QLabel(self)\n self.label8.move(100, 220)\n if code == 2:\n id = self.table.item(self.table.currentRow(), 0).text()\n con = sqlite3.connect('.\\\\Data\\\\coffee.sqlite')\n cur = con.cursor()\n result = cur.execute(f\"\"\"select * from coffee where id = {id}\"\"\").fetchall()\n self.coffee = result[0]\n print(result)\n self.lineEdit.setText(self.coffee[1])\n self.lineEdit_2.setText(self.coffee[2])\n self.lineEdit_3.setText(self.coffee[3])\n self.lineEdit_4.setText(self.coffee[4])\n self.lineEdit_5.setText(self.coffee[5])\n self.lineEdit_6.setText(str(self.coffee[6]))\n self.lineEdit_7.setText(str(self.coffee[7]))\n self.pushButton.setText('Изменить')\n self.pushButton.clicked.connect(self.confirm)\n\n def confirm(self):\n if self.pushButton.text() == 'Добавить':\n self.addToDB()\n elif self.pushButton.text() == 'Изменить':\n self.editDB()\n\n def addToDB(self):\n name = self.lineEdit.text()\n sort = self.lineEdit_2.text()\n stage = self.lineEdit_3.text()\n beans = self.lineEdit_4.text()\n taste = self.lineEdit_5.text()\n price = self.lineEdit_6.text()\n vol = self.lineEdit_7.text()\n if name and sort and stage and beans and taste and price and vol:\n self.label8.setText('')\n con = sqlite3.connect('.\\\\Data\\\\coffee.sqlite')\n cur = con.cursor()\n result = cur.execute(f\"\"\"select * from coffee\"\"\").fetchall()\n id = result[-1][0]\n cur.execute(f\"\"\"insert into coffee('id', 'name', 'sort', 'stage', 'beans', 'taste', 'price', 'volume')\nvalues ({id+1}, '{name}', '{sort}', '{stage}', '{beans}', '{taste}', {price}, {vol})\"\"\")\n con.commit()\n con.close()\n self.close()\n ex.showResults()\n\n else:\n self.label8.setText('Неверный ввод')\n\n def editDB(self):\n name = self.lineEdit.text()\n sort = self.lineEdit_2.text()\n stage = self.lineEdit_3.text()\n beans = self.lineEdit_4.text()\n taste = self.lineEdit_5.text()\n price = self.lineEdit_6.text()\n vol = self.lineEdit_7.text()\n if name and sort and stage and beans and taste and price and vol:\n self.label8.setText('')\n con = sqlite3.connect('.\\\\Data\\\\coffee.sqlite')\n cur = con.cursor()\n cur.execute(f'''delete from coffee where id = {self.coffee[0]}''')\n cur.execute(f\"\"\"insert into coffee('id', 'name', 'sort', 'stage', 'beans', 'taste', 'price', 'volume')\n values ({self.coffee[0]}, '{name}', '{sort}', '{stage}', '{beans}', '{taste}', {price}, {vol})\"\"\")\n con.commit()\n con.close()\n self.close()\n ex.showResults()\n else:\n self.label8.setText('Неверный ввод')\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = MyWidget()\n ex.show()\n sys.exit(app.exec_())\n","sub_path":"Release/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"408498435","text":"import sys, os\nimport math\n\nfrom ROOT import *\ngROOT.ProcessLine(\".x \" + os.environ['MYSW_DIR'] + \"/Utils/rootlogon.C\")\n\n\n\n\n\nfile_1 = TFile(\"xsec_tune1.root\");\nxsec_mumom_1 = file_1.Get(\"xsec_mumom_cv\")\ncov_mumom_tune_1 = file_1.Get(\"covariance_matrix_mumom_cv\")\nxsec_muangle_1 = file_1.Get(\"xsec_muangle_cv\")\ncov_muangle_tune_1 = file_1.Get(\"covariance_matrix_muangle_cv\")\n\nfile_3 = TFile(\"xsec_tune3.root\");\nxsec_mumom_3 = file_3.Get(\"xsec_mumom_cv\")\n# cov_tune_3 = file_3.Get(\"covariance_matrix_mumom_cv\")\nxsec_muangle_3 = file_3.Get(\"xsec_muangle_cv\")\n\nh_cov_mumom_tune1 = xsec_mumom_1.Clone(\"h_cov_mumom_tune1\")\nfor i in xrange(cov_mumom_tune_1.GetNbinsX()):\n\tunc_syst = math.sqrt(cov_mumom_tune_1.GetBinContent(i+1, i+1));\n\th_cov_mumom_tune1.SetBinError(i+1, unc_syst);\n\nh_cov_muangle_tune1 = xsec_muangle_1.Clone(\"h_cov_mumom_tune1\")\nfor i in xrange(cov_muangle_tune_1.GetNbinsX()):\n\tunc_syst = math.sqrt(cov_muangle_tune_1.GetBinContent(i+1, i+1));\n\th_cov_muangle_tune1.SetBinError(i+1, unc_syst);\n\n\nc = TCanvas(\"c1\", \"c1\")\n\nxsec_mumom_1.SetLineColor(kBlack)\nxsec_mumom_3.SetLineColor(50)\n\nxsec_mumom_1.GetXaxis().SetTitle(\"p_{#mu} [GeV]\")\nxsec_mumom_1.GetYaxis().SetTitle(\"d#sigma/dp_{#mu} [10^{-38} cm^{2}/GeV]\")\n\nxsec_mumom_1.SetMaximum(1.5)\n\nxsec_mumom_1.Draw(\"histo\")\nh_cov_mumom_tune1.Draw(\"E1 same\")\nxsec_mumom_3.Draw(\"histo same\")\n\nl = TLegend(0.42,0.71, 0.87,0.85);\nl.AddEntry(xsec_muangle_1, \"Tune 1 (GENIE Syst Uncertainty)\", \"le\");\nl.AddEntry(xsec_muangle_3, \"Tune 3\", \"l\");\nl.Draw()\n\nc1 = TCanvas(\"c\", \"c\")\n\nxsec_muangle_1.SetLineColor(kBlack)\nxsec_muangle_3.SetLineColor(50)\n\nxsec_muangle_1.GetXaxis().SetTitle(\"cos(#theta_{#mu})\")\nxsec_muangle_1.GetYaxis().SetTitle(\"d#sigma/dcos(#theta_{#mu}) [10^{-38} cm^{2}]\")\n\nxsec_muangle_1.SetMaximum(2.8)\n\nxsec_muangle_1.Draw(\"histo\")\nh_cov_muangle_tune1.Draw(\"E1 same\")\nxsec_muangle_3.Draw(\"histo same\")\n\nl.Draw()\n\n\n# print \"CV cross section\", xsec_onebin_cv.GetBinContent(1)\n\n# print \"Systematic parameter & Cross section & Total xsec perc difference \\\\\\\\\"\n\n# print \"cv & \", xsec_onebin_cv.GetBinContent(1), \" & 0.0 \\\\\\\\\"\n\n\n\n# for i in xrange(0, xsec_mumom_cv.GetNbinsX()):\n# \tfor j in xrange(0, xsec_mumom_cv.GetNbinsX()):\n# \t\tcov_matrix.SetBinContent(i+1, j+1, 0) \n# \t\tcov_matrix_frac.SetBinContent(i+1, j+1, 0)\n\n\n# det_syst_list = [\"nospacecharge\", \"dicharge\", \"lightyeild\", \"nodeltaray\", \"stretchRes\", \"altDeadChannels\", \"deadSaturatedChannels\", \"noPEnoise\", \"noShortedResp\", \"whitenoise\", \"enhancedexttpcvis\", \"lifetime10ms\", \"dl0\", \"dt0\", \"birksrecomb\", \"nohadronic\"]\n\n# stat_err_perbin_mumom = [0.0041, 0.013, 0.010, 0.0048, 0.0028, 0.00067]\n# stat_err_perbin_muangle = [0.0034, 0.0026, 0.0060, 0.0038, 0.0055, 0.0087, 0.0080, 0.011, 0.018]\n# stat_err_perbin_onebin = 0.0091\n\n# syst_total_xsec = 0\n\n# for syst_name in det_syst_list:\n\n# \tif syst_name == \"nodeltaray\": # or syst_name == \"dicharge\" or syst_name == \"stretchRes\" or syst_name == \"noShortedResp\":\n# \t\tcontinue\n\n# \tfile_name = \"xsec_file_\" + syst_name + \".root\"\n# \tfile = TFile(file_name);\n# \t# if (file.IsOpen()):\n# \t# \tprint \"File with name\", file_name, \"is opened\"\n# \t# else:\n# \t# \tprint \"Cannot find file\", file_name\n# \t# \texit(0)\n\n# \txsec_onebin = file.Get(\"xsec_onebin_\" + syst_name)\n# \txsec_mumom = file.Get(\"xsec_mumom_\" + syst_name)\n\n\n\n# \tperc_diff = (xsec_onebin_cv.GetBinContent(1) - xsec_onebin.GetBinContent(1)) / xsec_onebin_cv.GetBinContent(1)\n# \tprint syst_name, \" & \", xsec_onebin.GetBinContent(1), \" & \", perc_diff*100, \" \\\\\\\\\"\n# \tsyst_total_xsec = syst_total_xsec + abs(xsec_onebin_cv.GetBinContent(1) - xsec_onebin.GetBinContent(1))\n# \t#print \"diff is \", abs(xsec_onebin_cv.GetBinContent(1) - xsec_onebin.GetBinContent(1))\n\n\t\n\n\t\n\n# \t# Loop over bins to calculate D0\n\n# \tfor i in xrange(0, xsec_mumom.GetNbinsX()):\n# \t\td0 = (xsec_mumom.GetBinContent(i+1) - xsec_mumom_cv.GetBinContent(i+1) + stat_err_perbin_mumom[i])**2\n# \t\td0_frac = (xsec_mumom.GetBinContent(i+1) - xsec_mumom_cv.GetBinContent(i+1) + stat_err_perbin_mumom[i])**2 / (xsec_mumom_cv.GetBinContent(i+1))**2\n# \t\tcov_matrix.SetBinContent(i+1, i+1, cov_matrix.GetBinContent(i+1, i+1) + d0_frac)\n# \t\tcov_matrix_frac.SetBinContent(i+1, i+1, cov_matrix.GetBinContent(i+1, i+1) + d0)\n# \t\t# print \"systematic\", syst_name, \"d0\", d0, \"---\", cov_matrix.GetBinContent(i+1, i+1)\n# \t\t# print \"systematic\", syst_name, \"nominal\", xsec_mumom_cv.GetBinContent(i+1), \"variation\", xsec_mumom.GetBinContent(i+1) \n\n\n\n# print \"Total onebin syst err:\", syst_total_xsec\n# print \"Total onebin syst err (relative):\", syst_total_xsec / xsec_onebin.GetBinContent(1)\n\n# gStyle.SetPaintTextFormat(\"4.2f\");\n# gStyle.SetPalette(kDeepSea);\n\n# # cov_matrix.SetMarkerColor(kWhite);\n# # cov_matrix.SetMarkerSize(1.6);\n# # cov_matrix.GetXaxis().SetTitle(\"Bin i\");\n# # cov_matrix.GetXaxis().SetTitle(\"Bin j\");\n# # cov_matrix.GetXaxis().CenterTitle();\n# # cov_matrix.GetYaxis().CenterTitle();\n# # cov_matrix\n# # cov_matrix\n# # cov_matrix.Draw(\"colz TEXT\")\n\n# cov_matrix_frac.SetMarkerColor(kWhite);\n# cov_matrix_frac.SetMarkerSize(1.6);\n# cov_matrix_frac.GetXaxis().SetTitle(\"Bin i\");\n# cov_matrix_frac.GetXaxis().SetTitle(\"Bin j\");\n# cov_matrix_frac.GetXaxis().CenterTitle();\n# cov_matrix_frac.GetYaxis().CenterTitle();\n# cov_matrix_frac\n# cov_matrix_frac\n# cov_matrix_frac.Draw(\"colz TEXT\")\n\nraw_input(\"Please press enter to exit.\")\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Sandbox/tune1_tune3_xsec_comp/compare.py","file_name":"compare.py","file_ext":"py","file_size_in_byte":5327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"83425624","text":"\"\"\"\nFor CommonsCloud copyright information please see the LICENSE document\n(the \"License\") included with this software package. This file may not\nbe used in any manner except in compliance with the License\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\n\"\"\"\nImport System Dependencies\n\"\"\"\nfrom datetime import datetime, timedelta\n\n\n\"\"\"\nImport Flask Dependencies\n\"\"\"\nfrom flask import jsonify\nfrom flask import url_for\nfrom flask import redirect\nfrom flask import render_template\nfrom flask import request\n\nfrom werkzeug.security import gen_salt\n\nfrom flask.ext.security import current_user\nfrom flask.ext.security import login_required\n\nfrom flask.ext.oauthlib.provider import OAuth2RequestValidator\n\n\n\"\"\"\nImport Application Dependencies\n\"\"\"\nfrom CommonsCloudAPI.extensions import db\nfrom CommonsCloudAPI.extensions import logger\nfrom CommonsCloudAPI.extensions import oauth\n\nfrom CommonsCloudAPI.models.oauth import Client\nfrom CommonsCloudAPI.models.oauth import Grant\nfrom CommonsCloudAPI.models.oauth import Token\n\n\n\"\"\"\nImport Module Dependencies\n\"\"\"\nfrom . import module\n\n\n\"\"\"\nThis endpoint creates the necessary client id and client_secret\nnecessary for secure OAuth2 authentication\n\nTo access this endpoint the user must be logged in to the system\n\n\"\"\"\n@module.route('/oauth/client')\n@login_required\ndef oauth_client():\n\n next_url = url_for('oauth.oauth_client', **request.args)\n\n \"\"\"\n If the user is not authenticated we should redirect them\n to the login page\n \"\"\"\n if not hasattr(current_user, 'id'):\n return redirect(url_for('security.login', next=next_url))\n\n \"\"\"\n Assign the current_user object to a variable so that we don't\n accidently alter the object during this process.\n \"\"\"\n this_user = current_user\n\n \"\"\"\n Generate a client_id and client_secret for our OAuth2 authentication\n \"\"\"\n client_id = gen_salt(40)\n client_secret = gen_salt(50)\n _redirect_uris = ''\n _default_scopes = ''\n user_id = this_user.id\n\n # @todo\n #\n # We need to turn this call to Client into a web form so that\n # our application is doing the call to this url .... which should\n # actually just be a utility function\n #\n # item = Client(\n # client_id=client_id,\n # client_secret=client_secret,\n # _redirect_uris='http://localhost:9000/authorized',\n # _default_scopes='user,applications',\n # user_id=this_user.id,\n # )\n #\n # @end\n #\n item = Client(\n client_id = client_id,\n client_secret = client_secret,\n _redirect_uris = _redirect_uris,\n _default_scopes = _default_scopes,\n user_id = user_id,\n )\n \n \"\"\"\n Save the OAuth2 authentication information to the database\n \"\"\"\n db.session.add(item)\n db.session.commit()\n\n \"\"\"\n Return the client id and secret as a JSON object ... Why? Do we need to?\n \"\"\"\n return jsonify(\n client_key=client_id,\n client_secret=client_secret,\n ), 200\n\n\n@module.route('/oauth/token')\n@oauth.token_handler\ndef access_token():\n return None\n\n@module.route('/oauth/authorize', methods=['GET', 'POST'])\n@oauth.authorize_handler\ndef authorize(*args, **kwargs):\n\n next_url = url_for('oauth.authorize', **request.args)\n\n if not hasattr(current_user, 'id'):\n return redirect(url_for('security.login', next=next_url))\n\n \"\"\"\n Assign the current_user object to a variable so that we don't\n accidently alter the object during this process.\n \"\"\"\n this_user = current_user\n\n if request.method == 'GET':\n\n client_id = kwargs.get('client_id')\n client = Client.query.filter_by(client_id=client_id).first()\n kwargs['client'] = client\n kwargs['user'] = this_user\n return render_template('oauth/authorize.html', **kwargs)\n\n confirm = request.form.get('confirm', 'no')\n return confirm == 'Allow Access'\n\n@oauth.clientgetter\ndef load_client(client_id):\n return Client.query.filter_by(client_id=client_id).first()\n\n\n@oauth.grantgetter\ndef load_grant(client_id, code):\n return Grant.query.filter_by(client_id=client_id, code=code).first()\n\n\n@oauth.grantsetter\ndef save_grant(client_id, code, request, *args, **kwargs):\n # decide the expires time yourself\n expires = datetime.utcnow() + timedelta(days=1)\n grant = Grant(\n client_id=client_id,\n code=code['code'],\n redirect_uri=request.redirect_uri,\n _scopes=' '.join(request.scopes),\n user=current_user,\n expires=expires\n )\n db.session.add(grant)\n db.session.commit()\n return grant\n\n\n@oauth.tokengetter\ndef load_token(access_token=None, refresh_token=None):\n if access_token:\n return Token.query.filter_by(access_token=access_token).first()\n elif refresh_token:\n return Token.query.filter_by(refresh_token=refresh_token).first()\n\n\n@oauth.tokensetter\ndef save_token(token, oauth_request, *args, **kwargs):\n\n toks = Token.query.filter_by(\n client_id=oauth_request.client.client_id,\n user_id=current_user.id\n )\n\n # make sure that every client has only one token connected to a user\n for t in toks:\n db.session.delete(t)\n\n expires = datetime.utcnow() + timedelta(days=1)\n\n tok = Token(\n access_token=token['access_token'],\n # refresh_token=token['refresh_token'],\n token_type=token['token_type'],\n _scopes=token['scope'],\n expires=expires,\n client_id=oauth_request.client.client_id,\n user_id=current_user.id,\n )\n db.session.add(tok)\n db.session.commit()\n return tok\n","sub_path":"CommonsCloudAPI/modules/oauth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"110704657","text":"from __future__ import annotations\nimport zipfile\nimport shutil\nimport os\nimport re\nfrom enum import IntEnum\nfrom jinja2 import Template\nfrom typing import Optional, List, Dict\n\nimport xml.etree.ElementTree as ET\nfrom xml.etree.ElementTree import Element\n\nimport xml.dom.minidom as minidom # minidom used for prettyprint\n\nnamespace = \"{http://schemas.microsoft.com/office/visio/2012/main}\" # visio file name space\next_prop_namespace = '{http://schemas.openxmlformats.org/officeDocument/2006/extended-properties}'\nvt_namespace = '{http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes}'\nr_namespace = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'\ndocument_rels_namespace = \"{http://schemas.openxmlformats.org/package/2006/relationships}\"\ncont_types_namespace = '{http://schemas.openxmlformats.org/package/2006/content-types}'\n\n# utility functions\ndef to_float(val: str):\n try:\n if val is None:\n return\n return float(val)\n except ValueError:\n return 0.0\n\n\nclass PagePosition(IntEnum):\n FIRST = 0\n LAST = -1\n END = -1\n AFTER = -2\n BEFORE= -3\n\n\nclass VisioFile:\n \"\"\"Represents a vsdx file\n\n :param filename: filename the :class:`VisioFile` was created from\n :type filename: str\n :param pages: a list of pages in the VisioFile\n :type pages: list of :class:`Page`\n :param master_pages: a list of master pages in the VisioFile\n :type master_pages: list of :class:`Page`\n\n Contains :class:`Page`, :class:`Shape`, :class:`Connect` and :class:`Cell` sub-classes\n \"\"\"\n def __init__(self, filename, debug: bool = False):\n \"\"\"VisioFile constructor\n\n :param filename: the vsdx file to load and create the VisioFile object from\n :type filename: str\n :param debug: enable/disable debugging\n :type debug: bool, default to False\n \"\"\"\n self.debug = debug\n self.filename = filename\n if debug:\n print(f\"VisioFile(filename={filename})\")\n file_type = self.filename.split('.')[-1] # last text after dot\n if not file_type.lower() == 'vsdx':\n raise TypeError(f'Invalid File Type:{file_type}')\n\n self.directory = os.path.abspath(filename)[:-5]\n self.pages_xml = None # type: ET.ElementTree\n self.pages_xml_rels = None # type: ET.ElementTree\n self.content_types_xml = None # type: ET.ElementTree\n self.app_xml = None # type: ET.ElementTree\n self.document_xml = None # type: ET.ElementTree\n self.document_xml_rels = None # type: ET.ElementTree\n self.pages = list() # type: List[VisioFile.Page] # list of Page objects, populated by open_vsdx_file()\n self.master_pages = list() # type: List[VisioFile.Page] # list of Page objects, populated by open_vsdx_file()\n self.open_vsdx_file()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.close_vsdx()\n\n @staticmethod\n def pretty_print_element(xml: Element) -> str:\n if type(xml) is Element:\n return minidom.parseString(ET.tostring(xml)).toprettyxml()\n elif type(xml) is ET.ElementTree:\n return minidom.parseString(ET.tostring(xml.getroot())).toprettyxml()\n else:\n return f\"Not an Element. type={type(xml)}\"\n\n def open_vsdx_file(self):\n with zipfile.ZipFile(self.filename, \"r\") as zip_ref:\n zip_ref.extractall(self.directory)\n\n # load each page file into an ElementTree object\n self.load_pages()\n self.load_master_pages()\n\n def _pages_filename(self):\n page_dir = f'{self.directory}/visio/pages/'\n pages_filename = page_dir + 'pages.xml' # pages.xml contains Page name, width, height, mapped to Id\n return pages_filename\n\n @property\n def _masters_folder(self):\n path = f\"{self.directory}/visio/masters\"\n return path\n\n def load_pages(self):\n rel_dir = f'{self.directory}/visio/pages/_rels/'\n page_dir = f'{self.directory}/visio/pages/'\n\n rel_filename = rel_dir + 'pages.xml.rels'\n rels = file_to_xml(rel_filename).getroot() # rels contains page filenames\n self.pages_xml_rels = file_to_xml(rel_filename) # store pages.xml.rels so pages can be added or removed\n if self.debug:\n print(f\"Relationships({rel_filename})\", VisioFile.pretty_print_element(rels))\n relid_page_dict = {}\n\n for rel in rels:\n rel_id = rel.attrib['Id']\n page_file = rel.attrib['Target']\n relid_page_dict[rel_id] = page_file\n\n pages_filename = self._pages_filename() # pages contains Page name, width, height, mapped to Id\n pages = file_to_xml(pages_filename).getroot() # this contains a list of pages with rel_id and filename\n self.pages_xml = file_to_xml(pages_filename) # store xml so pages can be removed\n if self.debug:\n print(f\"Pages({pages_filename})\", VisioFile.pretty_print_element(pages))\n\n for page in pages: # type: Element\n rel_id = page[1].attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id']\n page_name = page.attrib['Name']\n\n page_path = page_dir + relid_page_dict.get(rel_id, None)\n\n new_page = VisioFile.Page(file_to_xml(page_path), page_path, page_name, self)\n self.pages.append(new_page)\n\n if self.debug:\n print(f\"Page({new_page.filename})\", VisioFile.pretty_print_element(new_page.xml.getroot()))\n\n self.content_types_xml = file_to_xml(f'{self.directory}/[Content_Types].xml')\n # TODO: add correctness cross-check. Or maybe the other way round, start from [Content_Types].xml\n # to get page_dir and other paths...\n\n self.app_xml = file_to_xml(f'{self.directory}/docProps/app.xml') # note: files in docProps may be missing\n self.document_xml = file_to_xml(f'{self.directory}/visio/document.xml')\n self.document_xml_rels = file_to_xml(f'{self.directory}/visio/_rels/document.xml.rels')\n\n def load_master_pages(self):\n # get data from /visio/masters folder\n master_rel_path = f'{self.directory}/visio/masters/_rels/masters.xml.rels'\n\n master_rels_data = file_to_xml(master_rel_path)\n master_rels = master_rels_data.getroot() if master_rels_data else []\n if self.debug:\n print(f\"Master Relationships({master_rel_path})\", VisioFile.pretty_print_element(master_rels))\n\n # populate relid to master path\n relid_to_path = {}\n for rel in master_rels:\n master_id = rel.attrib.get('Id')\n master_path = f\"{self.directory}/visio/masters/{rel.attrib.get('Target')}\" # get path from rel\n relid_to_path[master_id] = master_path\n\n # load masters.xml file\n masters_path = f'{self.directory}/visio/masters/masters.xml'\n masters_data = file_to_xml(masters_path) # contains more info about master page (i.e. Name, Icon)\n masters = masters_data.getroot() if masters_data else []\n\n # for each master page, create the VisioFile.Page object\n for master in masters:\n rel_id = master.find(f\"{namespace}Rel\").attrib[f\"{r_namespace}id\"]\n master_id = master.attrib['ID']\n\n master_path = relid_to_path[rel_id]\n\n master_page = VisioFile.Page(file_to_xml(master_path), master_path, master_id, self)\n self.master_pages.append(master_page)\n\n if self.debug:\n print(f\"Master({master_path}, id={master_id})\", VisioFile.pretty_print_element(master_page.xml.getroot()))\n\n return\n\n def get_page(self, n: int) -> VisioFile.Page:\n try:\n return self.pages[n]\n except IndexError:\n return None\n\n def get_page_names(self):\n return [p.name for p in self.pages]\n\n def get_page_by_name(self, name: str):\n \"\"\"Get page from VisioFile with matching name\n\n :param name: The name of the required page\n :type name: str\n\n :return: :class:`Page` object representing the page (or None if not found)\n \"\"\"\n for p in self.pages:\n if p.name == name:\n return p\n\n def get_master_page_by_id(self, id: str):\n \"\"\"Get master page from VisioFile with matching ID.\n\n Referred by :attr:`Shape.master_ID`.\n\n :param id: The ID of the required master\n :type id: str\n\n :return: :class:`Page` object representing the master page (or None if not found)\n \"\"\"\n for m in self.master_pages:\n if m.name == id:\n return m\n\n def remove_page_by_index(self, index: int):\n \"\"\"Remove zero-based nth page from VisioFile object\n\n :param index: Zero-based index of the page\n :type index: int\n\n :return: None\n \"\"\"\n\n # remove Page element from pages.xml file - zero based index\n # todo: similar function by page id, and by page title\n page = self.pages_xml.find(f\"{namespace}Page[{index+1}]\")\n if page:\n self.pages_xml.getroot().remove(page)\n page = self.pages[index] # type: VisioFile.Page\n self._remove_page_from_app_xml(page.name)\n del self.pages[index]\n\n def _update_pages_xml_rels(self, new_page_filename: str) -> str:\n '''Updates the pages.xml.rels file with a reference to the new page and returns the new relid\n '''\n\n max_relid = max(self.pages_xml_rels.getroot(), key=lambda rel: int(rel.attrib['Id'][3:]), default=None) # 'rIdXX' -> XX\n max_relid = int(max_relid.attrib['Id'][3:]) if max_relid is not None else 0\n new_page_relid = f'rId{max_relid + 1}' # Most likely will be equal to len(self.pages)+1\n\n new_page_rel = {\n 'Target': new_page_filename,\n 'Type' : 'http://schemas.microsoft.com/visio/2010/relationships/page',\n 'Id' : new_page_relid\n }\n self.pages_xml_rels.getroot().append(Element('{http://schemas.openxmlformats.org/package/2006/relationships}Relationship', new_page_rel))\n\n return new_page_relid\n\n def _get_new_page_name(self, new_page_name: str) -> str:\n i = 1\n while new_page_name in self.get_page_names():\n new_page_name = f'{new_page_name}-{i}' # Page-X-i\n i += 1\n\n return new_page_name\n\n def _get_max_page_id(self) -> int:\n page_with_max_id = max(self.pages_xml.getroot(), key=lambda page: int(page.attrib['ID']))\n max_page_id = int(page_with_max_id.attrib['ID'])\n\n return max_page_id\n\n def _get_index(self, *, index: int, page: VisioFile.Page or None):\n if type(index) is PagePosition: # only update index if it is relative to source page\n if index == PagePosition.LAST:\n index = len(self.pages)\n elif index == PagePosition.FIRST:\n index = 0\n elif page: # need page for BEFORE or AFTER\n orig_page_idx = self.pages.index(page)\n if index == PagePosition.BEFORE:\n # insert new page at the original page's index\n index = orig_page_idx\n elif index == PagePosition.AFTER:\n # insert new page after the original page\n index = orig_page_idx + 1\n else:\n index = len(self.pages) # default to LAST if invalid Position/page combination\n\n return index\n\n def _add_content_types_override(self, part_name_path: str, content_type: str):\n content_types = self.content_types_xml.getroot()\n\n content_types_attribs = {\n 'PartName': part_name_path,\n 'ContentType': content_type,\n }\n override_element = Element(f'{cont_types_namespace}Override', content_types_attribs)\n # find existing elements with same content_type\n matching_overrides = content_types.findall(\n f'{cont_types_namespace}Override[@ContentType=\"{content_type}\"]'\n )\n if len(matching_overrides): # insert after similar elements\n idx = list(content_types).index(matching_overrides[-1])\n content_types.insert(idx+1, override_element)\n else: # add at end of list\n content_types.append(override_element)\n\n def _update_content_types_xml(self, new_page_filename: str):\n # todo: use generic function above\n content_types = self.content_types_xml.getroot()\n\n content_types_attribs = {\n 'PartName' : f'/visio/pages/{new_page_filename}',\n 'ContentType': 'application/vnd.ms-visio.page+xml'\n }\n content_types_element = Element(f'{cont_types_namespace}Override', content_types_attribs)\n\n # add the new element after the last such element\n # first find the index:\n all_page_overrides = content_types.findall(\n f'{cont_types_namespace}Override[@ContentType=\"application/vnd.ms-visio.page+xml\"]'\n )\n idx = list(content_types).index(all_page_overrides[-1])\n\n # then add it:\n content_types.insert(idx+1, content_types_element)\n\n def document_rels(self) -> List[Element]:\n rels = self.document_xml_rels.findall(f'{document_rels_namespace}Relationship')\n return rels\n\n def _add_document_rel(self, rel_type: str, target: str):\n rel_ids = [int(str(r.attrib.get('Id')).replace('rId', '')) for r in self.document_rels()]\n new_rel = Element(f\"{document_rels_namespace}Relationship\",\n {\n \"Id\": f\"rId{max(rel_ids)+1}\",\n \"Type\": rel_type,\n \"Target\": target,\n })\n self.document_xml_rels.getroot().append(new_rel)\n\n def _style_sheets(self) -> Element:\n # return StyleSheets element from document.xml\n return self.document_xml.getroot().find(f'{namespace}StyleSheets')\n\n def _get_styles_name_list(self) -> List[str]:\n return [s.attrib.get('Name','') for s in self._style_sheets().findall(f'{namespace}StyleSheet')]\n\n def _get_style_by_name(self, name: str) -> Element:\n stylesheet = self._style_sheets().find(f\"{namespace}StyleSheet[@Name = '{name}']\")\n return stylesheet\n\n def _get_style_by_id(self, ID: str) -> Element:\n stylesheet = self._style_sheets().find(f\"{namespace}StyleSheet[@ID = '{ID}']\")\n return stylesheet\n\n def _heading_pairs(self) -> Element:\n # return HeadingPairs element from app.xml\n return self.app_xml.getroot().find(f'{ext_prop_namespace}HeadingPairs')\n\n def _titles_of_parts(self) -> Element:\n # return TitlesOfParts element from app.xml\n return self.app_xml.getroot().find(f'{ext_prop_namespace}TitlesOfParts')\n\n def _titles_of_parts_list(self) -> List[str]:\n # return list of strings\n return [t.text for t in self._titles_of_parts().find(f\".//{vt_namespace}vector\")]\n\n def _add_titles_of_parts_item(self, title: str):\n titles = self._titles_of_parts()\n vector = titles.find(f\".//{vt_namespace}vector\") # new variant appended to vector Element\n new_title = Element(f'{vt_namespace}lpstr', {})\n new_title.text = title\n vector.append(new_title)\n # add one to vector size, as we have added two new variant elements\n vector.attrib['size'] = str(int(vector.attrib.get('size', 0)) + 1)\n\n def _get_app_xml_value(self, name: str) -> str:\n variants = self._heading_pairs().findall(f\".//{vt_namespace}variant\")\n # find Pages in headings\n for index in range(len(variants)):\n v = variants[index]\n lpstr = v.find(f\".//{vt_namespace}lpstr\")\n if type(lpstr) is Element and lpstr.text == name:\n next_v = variants[index+1] if index < (len(variants)-1) else None # next variant if there is one\n i4 = next_v.find(f\".//{vt_namespace}i4\") if type(next_v) is Element else None\n if type(i4) is Element:\n return i4.text\n\n def _set_app_xml_value(self, name: str, value: str):\n variants = self._heading_pairs().findall(f\".//{vt_namespace}variant\")\n # find Pages in headings\n for index in range(len(variants)):\n v = variants[index]\n lpstr = v.find(f\".//{vt_namespace}lpstr\")\n if type(lpstr) is Element and lpstr.text == name:\n next_v = variants[index+1] if index < (len(variants)-1) else None # next variant if there is one\n i4 = next_v.find(f\".//{vt_namespace}i4\") if type(next_v) is Element else None\n if type(i4) is Element:\n i4.text = value\n return\n # no matching variant found - so create new item and populate it\n vector = self._heading_pairs().find(f\".//{vt_namespace}vector\") # new variant appended to vector Element\n name_variant = Element(f'{vt_namespace}variant', {})\n lpstr = Element(f'{vt_namespace}lpstr', {})\n lpstr.text = name\n name_variant.append(lpstr)\n vector.append(name_variant)\n i4_variant = Element(f'{vt_namespace}variant', {})\n i4 = Element(f'{vt_namespace}i4', {})\n i4.text = value\n i4_variant.append(i4)\n vector.append(i4_variant)\n # add two to vector size, as we have added two new variant elements\n vector.attrib['size'] = str(int(vector.attrib.get('size', 0)) + 2)\n\n def _add_page_to_app_xml(self, new_page_name: str):\n # todo: use _add_titles_of_parts_item()\n HeadingPairs = self._heading_pairs()\n i4 = HeadingPairs.find(f'.//{vt_namespace}i4')\n num_pages = int(i4.text)\n i4.text = str(num_pages+1) # increment as page added\n\n TitlesOfParts = self.app_xml.getroot().find(f'{ext_prop_namespace}TitlesOfParts')\n vector = TitlesOfParts.find(f'{vt_namespace}vector')\n\n lpstr = Element(f'{vt_namespace}lpstr')\n lpstr.text = new_page_name\n vector.append(lpstr) # add new lpstr element with new page name\n vector_size = int(vector.attrib['size'])\n vector.set('size', str(vector_size+1)) # increment as page added\n\n def _remove_page_from_app_xml(self, page_name: str):\n HeadingPairs = self.app_xml.getroot().find(f'{ext_prop_namespace}HeadingPairs')\n i4 = HeadingPairs.find(f'.//{vt_namespace}i4')\n num_pages = int(i4.text)\n i4.text = str(num_pages-1) # decrement as page removed\n\n TitlesOfParts = self.app_xml.getroot().find(f'{ext_prop_namespace}TitlesOfParts')\n vector = TitlesOfParts.find(f'{vt_namespace}vector')\n\n for lpstr in vector.findall(f'{vt_namespace}lpstr'):\n if lpstr.text == page_name:\n vector.remove(lpstr) # remove page from list of names\n break\n\n vector_size = int(vector.attrib['size'])\n vector.set('size', str(vector_size-1)) # decrement as page removed\n\n def _create_page(\n self,\n *,\n new_page_xml_str: str,\n page_name: str,\n new_page_element: Element,\n index: int or PagePosition,\n source_page: Optional[VisioFile.Page] = None,\n ) -> VisioFile.Page:\n # Create visio\\pages\\pageX.xml file\n # Add to visio\\pages\\_rels\\pages.xml.rels\n # Add to visio\\pages\\pages.xml\n # Add to [Content_Types].xml\n # Add to docProps\\app.xml\n\n page_dir = f'{self.directory}/visio/pages/' # TODO: better concatenation\n\n # create pageX.xml\n new_page_xml = ET.ElementTree(ET.fromstring(new_page_xml_str))\n new_page_filename = f'page{len(self.pages) + 1}.xml'\n new_page_path = page_dir+new_page_filename # TODO: better concatenation\n\n # update pages.xml.rels - add rel for the new page\n # done by the caller\n\n # update pages.xml - insert the PageElement Element in it's correct location\n index = self._get_index(index=index, page=source_page)\n self.pages_xml.getroot().insert(index, new_page_element)\n\n # update [Content_Types].xml - insert reference to the new page\n self._update_content_types_xml(new_page_filename)\n\n # update app.xml, if it exists\n if self.app_xml:\n self._add_page_to_app_xml(page_name)\n\n # Update VisioFile object\n new_page = VisioFile.Page(new_page_xml, new_page_path, page_name, self)\n\n self.pages.insert(index, new_page) # insert new page at defined index\n\n return new_page\n\n def add_page_at(self, index: int, name: Optional[str] = None) -> VisioFile.Page:\n \"\"\"Add a new page at the specified index of the VisioFile\n\n :param index: zero-based index where the new page will be placed\n :type index: int\n\n :param name: The name of the new page\n :type name: str, optional\n\n :return: :class:`Page` object representing the new page\n \"\"\"\n\n # Determine the new page's name\n new_page_name = self._get_new_page_name(name or f'Page-{len(self.pages) + 1}')\n\n # Determine the new page's filename\n new_page_filename = f'page{len(self.pages) + 1}.xml'\n\n # Add reference to the new page in pages.xml.rels and get new relid\n new_page_relid = self._update_pages_xml_rels(new_page_filename)\n\n # Create default empty page xml\n # TODO: figure out the best way to define this default pagesheet XML\n # For example, python-docx has a 'template.docx' file which is copied.\n new_pagesheet_attribs = {\n 'FillStyle': '0',\n 'LineStyle': '0',\n 'TextStyle': '0'\n }\n new_pagesheet_element = Element(f'{namespace}PageSheet', new_pagesheet_attribs)\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'PageWidth', 'V':'8.26771653543307'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'PageHeight', 'V':'11.69291338582677'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'ShdwOffsetX', 'V':'0.1181102362204724'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'ShdwOffsetY', 'V':'-0.1181102362204724'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'PageScale', 'U':'MM', 'V':'0.03937007874015748'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'DrawingScale', 'U':'MM', 'V':'0.03937007874015748'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'DrawingSizeType', 'V':'0'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'DrawingScaleType', 'V':'0'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'InhibitSnap', 'V':'0'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'PageLockReplace', 'U':'BOOL', 'V':'0'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'PageLockDuplicate', 'U':'BOOL', 'V':'0'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'UIVisibility', 'V':'0'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'ShdwType', 'V':'0'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'ShdwObliqueAngle', 'V':'0'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'ShdwScaleFactor', 'V':'1'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'DrawingResizeType', 'V':'1'}))\n new_pagesheet_element.append(Element(f'{namespace}Cell', {'N':'PageShapeSplit', 'V':'1'}))\n\n new_page_attribs = {\n 'ID' : str(self._get_max_page_id() + 1),\n 'NameU': new_page_name,\n 'Name' : new_page_name,\n }\n new_page_element = Element(f'{namespace}Page', new_page_attribs)\n new_page_element.append(new_pagesheet_element)\n\n new_page_rel = {\n '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id' : new_page_relid\n }\n new_page_element.append(Element(f'{namespace}Rel', new_page_rel))\n\n # create the new page\n new_page = self._create_page(\n new_page_xml_str = f\"\",\n page_name = new_page_name,\n new_page_element = new_page_element,\n index = index\n )\n\n return new_page\n\n def add_page(self, name: Optional[str] = None) -> VisioFile.Page:\n \"\"\"Add a new page at the end of the VisioFile\n\n :param name: The name of the new page\n :type name: str, optional\n\n :return: Page object representing the new page\n \"\"\"\n\n return self.add_page_at(PagePosition.LAST, name)\n\n def copy_page(self, page: VisioFile.Page, *, index: Optional[int] = PagePosition.AFTER, name: Optional[str] = None) -> VisioFile.Page:\n \"\"\"Copy an existing page and insert in VisioFile\n\n :param page: the page to copy\n :type page: VisioFile.Page\n :param index: the specific int or relation PagePosition location for new page\n :type index: int or PagePosition\n :param name: name of new page (note this may be altered if name already exists)\n :type name: str\n\n :return: the newly created page\n \"\"\"\n # Determine the new page's name\n new_page_name = self._get_new_page_name(name or page.name)\n\n # Determine the new page's filename\n new_page_filename = f'page{len(self.pages) + 1}.xml'\n\n # Add reference to the new page in pages.xml.rels and get new relid\n new_page_relid = self._update_pages_xml_rels(new_page_filename)\n\n # Copy the source page and update relevant attributes\n page_element = self.pages_xml.find(f\"{namespace}Page[@Name='{page.name}']\")\n new_page_element = ET.fromstring(ET.tostring(page_element))\n\n new_page_element.attrib['ID'] = str(self._get_max_page_id() + 1)\n new_page_element.attrib['NameU'] = new_page_name\n new_page_element.attrib['Name'] = new_page_name\n new_page_element.find(f'{namespace}Rel').attrib['{http://schemas.openxmlformats.org/officeDocument/2006/relationships}id'] = new_page_relid\n\n # create the new page\n new_page = self._create_page(\n new_page_xml_str = ET.tostring(page.xml.getroot()),\n page_name = new_page_name,\n new_page_element = new_page_element,\n index = index,\n source_page = page,\n )\n\n # copy pageX.xml.rels if it exists\n # from testing, this does not actually seem to make a difference\n _, original_filename = os.path.split(page.filename)\n page_xml_rels_file = f'{self.directory}/visio/pages/_rels/{original_filename}.rels' # TODO: better concatenation\n new_page_xml_rels_file = f'{self.directory}/visio/pages/_rels/{new_page_filename}.rels' # TODO: better concatenation\n try:\n shutil.copy(page_xml_rels_file, new_page_xml_rels_file)\n except FileNotFoundError:\n pass\n\n return new_page\n\n # TODO: dead code - never used\n def get_sub_shapes(self, shape: Element, nth=1):\n for e in shape:\n if 'Shapes' in e.tag:\n nth -= 1\n if not nth:\n return e\n\n @staticmethod\n def get_shape_location(shape: Element) -> (float, float):\n x, y = 0.0, 0.0\n cell_PinX = shape.find(f'{namespace}Cell[@N=\"PinX\"]') # type: Element\n cell_PinY = shape.find(f'{namespace}Cell[@N=\"PinY\"]')\n x = float(cell_PinX.attrib['V'])\n y = float(cell_PinY.attrib['V'])\n\n return x, y\n\n @staticmethod\n def set_shape_location(shape: Element, x: float, y: float):\n cell_PinX = shape.find(f'{namespace}Cell[@N=\"PinX\"]') # type: Element\n cell_PinY = shape.find(f'{namespace}Cell[@N=\"PinY\"]')\n cell_PinX.attrib['V'] = str(x)\n cell_PinY.attrib['V'] = str(y)\n\n @staticmethod\n # TODO: is this never used?\n def get_shape_text(shape: ET) -> str:\n # technically the below is not an exact replacement of the above...\n text = \"\"\n text_elem = shape.find(f\"{namespace}Text\")\n if text_elem is not None:\n text = \"\".join(text_elem.itertext())\n return text\n\n @staticmethod\n # TODO: is this never used?\n def set_shape_text(shape: ET, text: str):\n t = shape.find(f\"{namespace}Text\") # type: Element\n if t is not None:\n if t.text:\n t.text = text\n else:\n t[0].tail = text\n\n # context = {'customer_name':'codypy.com', 'year':2020 }\n # example shape text \"For {{customer_name}} (c){{year}}\" -> \"For codypy.com (c)2020\"\n @staticmethod\n def apply_text_context(shapes: Element, context: dict):\n\n def _replace_shape_text(shape: Element, context: dict):\n text = VisioFile.get_shape_text(shape)\n\n for key in context.keys():\n r_key = \"{{\" + key + \"}}\"\n text = text.replace(r_key, str(context[key]))\n VisioFile.set_shape_text(shape, text)\n\n for shape in shapes.findall(f\"{namespace}Shapes\"):\n VisioFile.apply_text_context(shape, context) # recursive call\n _replace_shape_text(shape, context)\n\n for shape in shapes.findall(f\"{namespace}Shape\"):\n _replace_shape_text(shape, context)\n\n def jinja_render_vsdx(self, context: dict):\n \"\"\"Transform a template VisioFile object using the Jinja language\n The method updates the VisioFile object loaded from the template file, so does not return any value\n Note: vsdx specific extensions are available such as `{% for item in list %}` statements with no `{% endfor %}`\n\n :param context: A dictionary containing values that can be accessed by the Jinja processor\n :type context: dict\n\n :return: None\n \"\"\"\n # parse each shape in each page as Jinja2 template with context\n pages_to_remove = [] # list of pages to be removed after loop\n for page in self.pages: # type: VisioFile.Page\n # check if page should be removed\n if VisioFile.jinja_page_showif(page, context):\n loop_shape_ids = list()\n for shapes_by_id in page.shapes: # type: VisioFile.Shape\n VisioFile.jinja_render_shape(shape=shapes_by_id, context=context, loop_shape_ids=loop_shape_ids)\n\n source = ET.tostring(page.xml.getroot(), encoding='unicode')\n source = VisioFile.unescape_jinja_statements(source) # unescape chars like < and > inside {%...%}\n template = Template(source)\n output = template.render(context)\n page.xml = ET.ElementTree(ET.fromstring(output)) # create ElementTree from Element created from output\n\n # update loop shape IDs which have been duplicated by Jinja template\n page.set_max_ids()\n for shape_id in loop_shape_ids:\n shapes_by_id = page._find_shapes_by_id(shape_id) # type: List[VisioFile.Shape]\n if shapes_by_id and len(shapes_by_id) > 1:\n delta = 0\n for shape in shapes_by_id[1:]: # from the 2nd onwards - leaving original unchanged\n # increment each new shape duplicated by the jinja loop\n self.increment_sub_shape_ids(shape, page)\n delta += shape.height # automatically move each duplicate down\n shape.move(0, -delta) # move duplicated shapes so they are visible\n else:\n # note page to remove after this loop has completed\n pages_to_remove.append(page)\n # remove pages after processing\n for p in pages_to_remove:\n self.remove_page_by_index(p.index_num)\n\n @staticmethod\n def jinja_render_shape(shape: VisioFile.Shape, context: dict, loop_shape_ids: list):\n prev_shape = None\n for s in shape.sub_shapes(): # type: VisioFile.Shape\n # manage for loops in template\n loop_shape_id = VisioFile.jinja_create_for_loop_if(s, prev_shape)\n if loop_shape_id:\n loop_shape_ids.append(loop_shape_id)\n prev_shape = s\n # manage 'set self' statements\n VisioFile.jinja_set_selfs(s, context)\n VisioFile.jinja_render_shape(shape=s, context=context, loop_shape_ids=loop_shape_ids)\n\n @staticmethod\n def jinja_set_selfs(shape: VisioFile.Shape, context: dict):\n # apply any {% self self.xxx = yyy %} statements in shape properties\n jinja_source = shape.text\n matches = re.findall(r'{% set self.(.*?)\\s?=\\s?(.*?) %}', jinja_source) # non-greedy search for all {%...%} strings\n for m in matches: # type: tuple # expect ('property', 'value') such as ('x', '10') or ('y', 'n*2')\n property_name = m[0]\n value = \"{{ \"+m[1]+\" }}\" # Jinja to be processed\n # todo: replace any self references in value with actual value - i.e. {% set self.x = self.x+1 %}\n self_refs = re.findall(r'self.(.*)[\\s+-/*//]?', m[1]) # greedy search for all self.? between +, -, *, or /\n for self_ref in self_refs: # type: tuple # expect ('property', 'value') such as ('x', '10') or ('y', 'n*2')\n ref_val = str(shape.__getattribute__(self_ref[0]))\n value = value.replace('self.'+self_ref[0], ref_val)\n # use Jinja template to calculate any self refs found\n template = Template(value) # value might be '{{ 1.0+2.4*3 }}'\n value = template.render(context)\n if property_name in ['x', 'y']:\n shape.__setattr__(property_name, value)\n\n # remove any {% set self %} statements, leaving any remaining text\n matches = re.findall('{% set self.*?%}', jinja_source)\n for m in matches:\n jinja_source = jinja_source.replace(m, '') # remove Jinja 'set self' statement\n shape.text = jinja_source\n\n @staticmethod\n def unescape_jinja_statements(jinja_source):\n # unescape any text between {% ... %}\n jinja_source_out = jinja_source\n matches = re.findall('{%(.*?)%}', jinja_source) # non-greedy search for all {%...%} strings\n for m in matches:\n unescaped = m.replace('>', '>').replace('<', '<')\n jinja_source_out = jinja_source_out.replace(m, unescaped)\n return jinja_source_out\n\n @staticmethod\n def jinja_create_for_loop_if(shape: VisioFile.Shape, previous_shape:VisioFile.Shape or None):\n # update a Shapes tag where text looks like a jinja {% for xxxx %} loop\n # move text to start of Shapes tag and add {% endfor %} at end of tag\n text = shape.text\n\n # use regex to find all loops\n jinja_loops = re.findall(r\"{% for\\s(.*?)\\s%}\", text)\n\n for loop in jinja_loops:\n jinja_loop_text = f\"{{% for {loop} %}}\"\n # move the for loop to start of shapes element (just before first Shape element)\n if previous_shape:\n if previous_shape.xml.tail:\n previous_shape.xml.tail += jinja_loop_text\n else:\n previous_shape.xml.tail = jinja_loop_text # add jinja loop text after previous shape, before this element\n else:\n if shape.parent.xml.text:\n shape.parent.xml.text += jinja_loop_text\n else:\n shape.parent.xml.text = jinja_loop_text # add jinja loop at start of parent, just before this element\n shape.text = shape.text.replace(jinja_loop_text, '') # remove jinja loop from tag in element\n\n # add closing 'endfor' to just inside the shapes element, after last shape\n if shape.xml.tail: # extend or set text at end of Shape element\n shape.xml.tail += \"{% endfor %}\"\n else:\n shape.xml.tail = '{% endfor %}'\n\n jinja_show_ifs = re.findall(r\"{% showif\\s(.*?)\\s%}\", text) # find all showif statements\n # jinja_show_if - translate non-standard {% showif statement %} to valid jinja if statement\n for show_if in jinja_show_ifs:\n jinja_show_if = f\"{{% if {show_if} %}}\" # translate to actual jinja if statement\n # move the for loop to start of shapes element (just before first Shape element)\n if previous_shape:\n previous_shape.xml.tail = str(previous_shape.xml.tail or '')+jinja_show_if # add jinja loop text after previous shape, before this element\n else:\n shape.parent.xml.text = str(shape.parent.xml.text or '')+jinja_show_if # add jinja loop at start of parent, just before this element\n\n # remove original jinja showif from tag in element\n shape.text = shape.text.replace(f\"{{% showif {show_if} %}}\", '')\n\n # add closing 'endfor' to just inside the shapes element, after last shape\n if shape.xml.tail: # extend or set text at end of Shape element\n shape.xml.tail += \"{% endif %}\"\n else:\n shape.xml.tail = '{% endif %}'\n\n if jinja_loops:\n return shape.ID # return shape ID if it is a loop, so that duplicate shape IDs can be updated\n\n @staticmethod\n def jinja_page_showif(page: VisioFile.Page, context: dict):\n text = page.name\n jinja_source = re.findall(r\"{% showif\\s(.*?)\\s%}\", text)\n if len(jinja_source):\n # process last matching value\n template_source = \"{{ \"+jinja_source[-1]+\" }}\"\n template = Template(template_source) # value might be '{{ 1.0+2.4*3 }}'\n value = template.render(context)\n # is the value truthy - i.e. not 0, False, or empty string, tuple, list or dict\n print(f\"jinja_page_showif(context={context}) statement: {template_source} returns: {type(value)} {value}\")\n if value in ['False', '0', '', '()', '[]', '{}']:\n print(\"value in ['False', '0', '', '()', '[]', '{}']\")\n return False # page should be hidden\n # remove jinja statement from page name\n jinja_statement = re.match(\"{%.*?%}\", page.name)[0]\n page.set_name(page.name.replace(jinja_statement, ''))\n print(f\"jinja_statement={jinja_statement} page.name={page.name}\")\n return True # page should be left in\n\n @staticmethod\n def get_shape_id(shape: ET) -> str:\n return shape.attrib['ID']\n\n def increment_sub_shape_ids(self, shape: VisioFile.Shape, page, id_map: dict = None):\n id_map = self.increment_shape_ids(shape.xml, page, id_map)\n self.update_ids(shape.xml, id_map)\n for s in shape.sub_shapes():\n id_map = self.increment_shape_ids(s.xml, page, id_map)\n self.update_ids(s.xml, id_map)\n if s.sub_shapes():\n id_map = self.increment_sub_shape_ids(s, page, id_map)\n return id_map\n\n def copy_shape(self, shape: Element, page: VisioFile.Page) -> ET:\n \"\"\"Insert shape into first Shapes tag in destination page, and return the copy.\n\n If destination page does not have a Shapes tag yet, create it.\n\n Parameters:\n shape (Element): The source shape to be copied. Use Shape.xml\n page (ElementTree): The page where the new Shape will be placed. Use Page.xml\n page_path (str): The filename of the page where the new Shape will be placed. Use Page.filename\n\n Returns:\n ElementTree: The new shape ElementTree\n\n \"\"\"\n\n new_shape = ET.fromstring(ET.tostring(shape))\n\n page.set_max_ids()\n # find or create Shapes tag\n shapes_tag = page.xml.find(f\"{namespace}Shapes\")\n if shapes_tag is None:\n shapes_tag = Element(f\"{namespace}Shapes\")\n page.xml.getroot().append(shapes_tag)\n\n id_map = self.increment_shape_ids(new_shape, page) # page_obj)\n self.update_ids(new_shape, id_map)\n shapes_tag.append(new_shape)\n\n return new_shape\n\n def insert_shape(self, shape: Element, shapes: Element, page: ET, page_path: str) -> ET:\n # insert shape into shapes tag, and return updated shapes tag\n for page_obj in self.pages:\n if page_obj.filename == page_path:\n break\n\n id_map = self.increment_shape_ids(shape, page_obj)\n self.update_ids(shape, id_map)\n shapes.append(shape)\n return shapes\n\n def increment_shape_ids(self, shape: Element, page: VisioFile.Page, id_map: dict=None):\n if id_map is None:\n id_map = dict()\n self.set_new_id(shape, page, id_map)\n for e in shape.findall(f\"{namespace}Shapes\"):\n self.increment_shape_ids(e, page, id_map)\n for e in shape.findall(f\"{namespace}Shape\"):\n self.set_new_id(e, page, id_map)\n\n return id_map\n\n def set_new_id(self, element: Element, page: VisioFile.Page, id_map: dict):\n page.max_id += 1\n max_id = page.max_id\n if element.attrib.get('ID'):\n current_id = element.attrib['ID']\n id_map[current_id] = max_id # record mappings\n element.attrib['ID'] = str(max_id)\n return max_id # return new id for info\n\n def update_ids(self, shape: Element, id_map: dict):\n # update: 0:\n directory = new_filename[0:new_filename.rfind(os.sep)]\n if directory:\n if not os.path.exists(directory):\n os.mkdir(directory)\n shutil.make_archive(base_filename, 'zip', self.directory)\n if not new_filename:\n shutil.move(base_filename + '.zip', base_filename + '_new.vsdx')\n else:\n if new_filename[-5:] != '.vsdx':\n new_filename += '.vsdx'\n shutil.move(base_filename + '.zip', new_filename)\n self.close_vsdx()\n\n class Cell:\n def __init__(self, xml: Element, shape: VisioFile.Shape):\n self.xml = xml\n self.shape = shape\n\n @property\n def value(self):\n return self.xml.attrib.get('V')\n\n @value.setter\n def value(self, value: str):\n self.xml.attrib['V'] = str(value)\n\n @property\n def formula(self):\n return self.xml.attrib.get('F')\n\n @formula.setter\n def formula(self, value: str):\n self.xml.attrib['F'] = str(value)\n\n @property\n def name(self):\n return self.xml.attrib.get('N')\n\n @property\n def func(self): # assume F stands for function, i.e. F=\"Width*0.5\"\n return self.xml.attrib.get('F')\n\n def __repr__(self):\n return f\"Cell: name={self.name} val={self.value} func={self.func}\"\n\n class DataProperty:\n def __init__(self, *, xml: Element, shape: VisioFile.Shape):\n \"\"\"Represents a single Data Property item associated with a Shape object\"\"\"\n name = xml.attrib.get('N')\n # get Cell element for each property of DataProperty\n label_cell = xml.find(f'{namespace}Cell[@N=\"Label\"]')\n value_cell = xml.find(f'{namespace}Cell[@N=\"Value\"]')\n value = value_cell.attrib.get('V') if type(value_cell) is Element else None\n\n if type(label_cell) is Element:\n value_type_cell = xml.find(f'{namespace}Cell[@N=\"Type\"]')\n prompt_cell = xml.find(f'{namespace}Cell[@N=\"Prompt\"]')\n sort_key_cell = xml.find(f'{namespace}Cell[@N=\"SortKey\"]')\n\n # get values from each Cell Element\n value_type = value_type_cell.attrib.get('V') if type(value_type_cell) is Element else None\n label = label_cell.attrib.get('V') if type(label_cell) is Element else None\n prompt = prompt_cell.attrib.get('V') if type(prompt_cell) is Element else None\n sort_key = sort_key_cell.attrib.get('V') if type(sort_key_cell) is Element else None\n else:\n # over-ridden master shape properties have no label - only a name and value\n master_prop = [p for p in shape.master_shape.data_properties.values() if p.name == name][0] # type: VisioFile.DataProperty\n label = master_prop.label\n value_type = master_prop.value_type\n prompt = master_prop.prompt\n sort_key = master_prop.sort_key\n\n # set DataProperty properties from xml\n self.name = name\n self.value = value\n self.value_type = value_type\n self.label = label\n self.prompt = prompt\n self.sort_key = sort_key\n\n self.shape = shape # reference back to Shape object\n self.xml = xml # reference to xml used to create DataProperty\n\n class Shape:\n \"\"\"Represents a single shape, or a group shape containing other shapes\n \"\"\"\n def __init__(self, xml: Element, parent: VisioFile.Page or VisioFile.Shape, page: VisioFile.Page):\n self.xml = xml\n self.parent = parent\n self.tag = xml.tag\n self.ID = xml.attrib.get('ID', None)\n self.master_shape_ID = xml.attrib.get('MasterShape', None)\n self.master_page_ID = xml.attrib.get('Master', None) # i.e. '2', note: the master_page.name not list index\n if self.master_page_ID is None and isinstance(parent, VisioFile.Shape): # in case of a sub_shape\n self.master_page_ID = parent.master_page_ID\n self.shape_type = xml.attrib.get('Type', None)\n self.page = page\n\n # get Cells in Shape\n self.cells = dict()\n for e in self.xml.findall(f\"{namespace}Cell\"):\n cell = VisioFile.Cell(xml=e, shape=self)\n self.cells[cell.name] = cell\n geometry = self.xml.find(f'{namespace}Section[@N=\"Geometry\"]')\n if geometry is not None:\n for r in geometry.findall(f\"{namespace}Row\"):\n row_type = r.attrib['T']\n if row_type:\n for e in r.findall(f\"{namespace}Cell\"):\n cell = VisioFile.Cell(xml=e, shape=self)\n key = f\"Geometry/{row_type}/{cell.name}\"\n self.cells[key] = cell\n #print(f\"added name:['{key}']={cell} {cell.xml}\")\n\n self._data_properties = None # internal field to hold Shape.data_propertes, set by property\n\n def __repr__(self):\n return f\"\"\n\n def copy(self, page: Optional[VisioFile.Page] = None) -> VisioFile.Shape:\n \"\"\"Copy this Shape to the specified destination Page, and return the copy.\n\n If the destination page is not specified, the Shape is copied to its containing Page.\n\n :param page: The page where the new Shape will be placed.\n If not specified, the copy will be placed in the original shape's page.\n :type page: :class:`Page` (Optional)\n\n :return: :class:`Shape` the new copy of shape\n \"\"\"\n dst_page = page or self.page\n new_shape_xml = self.page.vis.copy_shape(self.xml, dst_page)\n\n # set parent: location for new shape tag to be added\n if page:\n # set parent to first page Shapes tag if destination page passed\n parent = page.shapes\n else:\n # or set parent to source shapes own parent\n parent = self.parent\n\n return VisioFile.Shape(xml=new_shape_xml, parent=parent, page=dst_page)\n\n @property\n def master_shape(self) -> VisioFile.Shape:\n \"\"\"Get this shapes master\n\n Returns this Shape's master as a Shape object (or None)\n\n \"\"\"\n master_page = self.page.vis.get_master_page_by_id(self.master_page_ID)\n if not master_page:\n return # None if no master page set for this Shape\n master_shape = master_page.shapes[0].sub_shapes()[0] # there's always a single master shape in a master page\n\n if self.master_shape_ID is not None:\n master_sub_shape = master_shape.find_shape_by_id(self.master_shape_ID)\n return master_sub_shape\n\n return master_shape\n\n @property\n def data_properties(self) -> Dict[str, VisioFile.DataProperty]:\n \"\"\"\n Get data properties of the shape - which labels, names, and values\n returns a dictionary of DataProperty objects indexed by property label\n\n :return: Dict[str, VisioFile.DataProperty]\n \"\"\"\n if self._data_properties:\n # return cached dict if present\n return self._data_properties\n\n properties = dict()\n if self.master_shape: # start with master data properties or empty dict\n properties = self.master_shape.data_properties\n properties_xml = self.xml.find(f'{namespace}Section[@N=\"Property\"]')\n if type(properties_xml) is Element:\n property_rows = properties_xml.findall(f'{namespace}Row')\n for prop in property_rows:\n data_prop = VisioFile.DataProperty(xml=prop, shape=self)\n # add properties to dict to allow fast lookup by property.label\n properties[data_prop.label] = data_prop\n self._data_properties = properties # cache for next call\n return properties\n\n def cell_value(self, name: str):\n cell = self.cells.get(name)\n if cell:\n return cell.value\n\n if self.master_page_ID is not None:\n return self.master_shape.cell_value(name)\n\n def cell_formula(self, name: str):\n cell = self.cells.get(name)\n if cell:\n return cell.formula\n\n if self.master_page_ID is not None:\n return self.master_shape.cell_formula(name)\n\n def set_cell_value(self, name: str, value: str):\n cell = self.cells.get(name)\n if cell: # only set value of existing item\n cell.value = value\n\n elif self.master_page_ID is not None:\n master_cell_xml = self.master_shape.xml.find(f'{namespace}Cell[@N=\"{name}\"]')\n new_cell = ET.fromstring(ET.tostring(master_cell_xml))\n\n self.cells[name] = VisioFile.Cell(xml=new_cell, shape=self)\n self.cells[name].value = value\n\n self.xml.append(self.cells[name].xml)\n\n # LineStyle=\"7\" FillStyle=\"7\" TextStyle=\"7\"\n @property\n def line_style_id(self):\n return self.xml.attrib.get('LineStyle')\n\n @line_style_id.setter\n def line_style_id(self, value):\n self.xml.attrib['LineStyle'] = str(value)\n\n @property\n def fill_style_id(self):\n return self.xml.attrib.get('FillStyle')\n\n @fill_style_id.setter\n def fill_style_id(self, value):\n self.xml.attrib['FillStyle'] = str(value)\n\n @property\n def text_style_id(self):\n return self.xml.attrib.get('TextStyle')\n\n @text_style_id.setter\n def text_style_id(self, value):\n self.xml.attrib['TextStyle'] = str(value)\n\n @property\n def line_weight(self) -> float:\n val = self.cell_value('LineWeight')\n return to_float(val)\n\n @line_weight.setter\n def line_weight(self, value: float or str):\n self.set_cell_value('LineWeight', str(value))\n\n @property\n def line_color(self) -> str:\n return self.cell_value('LineColor')\n\n @line_color.setter\n def line_color(self, value: str):\n self.set_cell_value('LineColor', str(value))\n\n @property\n def x(self):\n return to_float(self.cell_value('PinX'))\n\n @x.setter\n def x(self, value: float or str):\n self.set_cell_value('PinX', str(value))\n\n @property\n def y(self):\n return to_float(self.cell_value('PinY'))\n\n @y.setter\n def y(self, value: float or str):\n self.set_cell_value('PinY', str(value))\n\n @property\n def line_to_x(self):\n return to_float(self.cell_value('Geometry/LineTo/X'))\n\n @line_to_x.setter\n def line_to_x(self, value):\n self.set_cell_value('Geometry/LineTo/X', str(value))\n\n @property\n def line_to_y(self):\n return to_float(self.cell_value('Geometry/LineTo/Y'))\n\n @line_to_y.setter\n def line_to_y(self, value):\n self.set_cell_value('Geometry/LineTo/Y', str(value))\n\n @property\n def begin_x(self):\n return to_float(self.cell_value('BeginX'))\n\n @begin_x.setter\n def begin_x(self, value: float or str):\n self.set_cell_value('BeginX', str(value))\n\n @property\n def begin_y(self):\n return to_float(self.cell_value('BeginY'))\n\n @begin_y.setter\n def begin_y(self, value: float or str):\n self.set_cell_value('BeginY', str(value))\n\n @property\n def end_x(self):\n return to_float(self.cell_value('EndX'))\n\n @end_x.setter\n def end_x(self, value: float or str):\n self.set_cell_value('EndX', str(value))\n\n @property\n def end_y(self):\n return to_float(self.cell_value('EndY'))\n\n @end_y.setter\n def end_y(self, value: float or str):\n self.set_cell_value('EndY', str(value))\n\n def move(self, x_delta: float, y_delta: float):\n self.x = self.x + x_delta\n self.y = self.y + y_delta\n\n @property\n def height(self):\n return to_float(self.cell_value('Height'))\n\n @height.setter\n def height(self, value: float or str):\n self.set_cell_value('Height', str(value))\n\n @property\n def width(self):\n return to_float(self.cell_value('Width'))\n\n @width.setter\n def width(self, value: float or str):\n self.set_cell_value('Width', str(value))\n\n @property\n def center_x_y(self):\n x = self.x - (self.width/2)\n y = self.y + (self.height/2)\n return x, y\n\n @staticmethod\n def clear_all_text_from_xml(x: Element):\n x.text = ''\n x.tail = ''\n for i in x:\n VisioFile.Shape.clear_all_text_from_xml(i)\n\n @property\n def text(self):\n # return contents of Text element, or Master shape (if referenced), or empty string\n text_element = self.xml.find(f\"{namespace}Text\")\n\n if isinstance(text_element, Element):\n return \"\".join(text_element.itertext()) # get all text from sub elements\n elif self.master_page_ID:\n return self.master_shape.text # get text from master shape\n return \"\"\n\n @text.setter\n def text(self, value):\n text_element = self.xml.find(f\"{namespace}Text\")\n if isinstance(text_element, Element): # if there is a Text element then clear out and set contents\n VisioFile.Shape.clear_all_text_from_xml(text_element)\n text_element.text = value\n # todo: create new Text element if not found\n\n def sub_shapes(self) -> List[VisioFile.Shape]:\n \"\"\"Get child/sub shapes contained by a VisioFile.Shape\n\n :returns: list of VisioFile.Shape objects\n :rtype: List[VisioFile.Shape]\n \"\"\"\n shapes = list()\n # for each shapes tag, look for Shape objects\n # self can be either a Shapes or a Shape\n # a Shapes has a list of Shape\n # a Shape can have 0 or 1 Shapes (1 if type is Group)\n\n if self.shape_type == 'Group':\n parent_element = self.xml.find(f\"{namespace}Shapes\")\n else: # a Shapes\n parent_element = self.xml\n if parent_element:\n shapes = [VisioFile.Shape(xml=shape, parent=self, page=self.page) for shape in parent_element]\n else:\n shapes = []\n return shapes\n\n def get_max_id(self):\n max_id = int(self.ID)\n if self.shape_type == 'Group':\n for shape in self.sub_shapes():\n new_max = shape.get_max_id()\n if new_max > max_id:\n max_id = new_max\n return max_id\n\n def find_shape_by_id(self, shape_id: str) -> VisioFile.Shape: # returns Shape\n \"\"\"\n Recursively search for a shape, based on a known shape_id, and return a single VisioFile.Shape\n\n :param shape_id:\n :return: VisooFile.Shape\n \"\"\"\n # recursively search for shapes by text and return first match\n for shape in self.sub_shapes(): # type: VisioFile.Shape\n if shape.ID == shape_id:\n return shape\n if shape.shape_type == 'Group':\n found = shape.find_shape_by_id(shape_id)\n if found:\n return found\n\n def find_shapes_by_id(self, shape_id: str) -> List[VisioFile.Shape]:\n # recursively search for shapes by ID and return all matches\n found = list()\n for shape in self.sub_shapes(): # type: VisioFile.Shape\n if shape.ID == shape_id:\n found.append(shape)\n if shape.shape_type == 'Group':\n sub_found = shape.find_shapes_by_id(shape_id)\n if sub_found:\n found.extend(sub_found)\n return found # return list of matching shapes\n\n def find_shapes_by_master(self, master_page_ID: str, master_shape_ID: str) -> List[VisioFile.Shape]:\n # recursively search for shapes by master ID and return all matches\n found = list()\n for shape in self.sub_shapes(): # type: VisioFile.Shape\n if shape.master_shape_ID == master_shape_ID and shape.master_page_ID == master_page_ID:\n found.append(shape)\n if shape.shape_type == 'Group':\n sub_found = shape.find_shapes_by_master(master_shape_ID, master_shape_ID)\n if sub_found:\n found.extend(sub_found)\n return found # return list of matching shapes\n\n def find_shape_by_text(self, text: str) -> VisioFile.Shape: # returns Shape\n # recursively search for shapes by text and return first match\n for shape in self.sub_shapes(): # type: VisioFile.Shape\n if text in shape.text:\n return shape\n if shape.shape_type == 'Group':\n found = shape.find_shape_by_text(text)\n if found:\n return found\n\n def find_shapes_by_text(self, text: str, shapes: List[VisioFile.Shape] = None) -> List[VisioFile.Shape]:\n # recursively search for shapes by text and return all matches\n if not shapes:\n shapes = list()\n for shape in self.sub_shapes(): # type: VisioFile.Shape\n if text in shape.text:\n shapes.append(shape)\n if shape.shape_type == 'Group':\n found = shape.find_shapes_by_text(text)\n if found:\n shapes.extend(found)\n return shapes\n\n def find_shape_by_property_label(self, property_label: str) -> VisioFile.Shape: # returns Shape\n # recursively search for shapes by property name and return first match\n for shape in self.sub_shapes(): # type: VisioFile.Shape\n if property_label in shape.data_properties.keys():\n return shape\n if shape.shape_type == 'Group':\n found = shape.find_shape_by_property_label(property_label)\n if found:\n return found\n\n def find_shapes_by_property_label(self, property_label: str, shapes: List[VisioFile.Shape] = None) -> List[VisioFile.Shape]:\n # recursively search for shapes by property name and return all matches\n if not shapes:\n shapes = list()\n for shape in self.sub_shapes(): # type: VisioFile.Shape\n if property_label in shape.data_properties.keys():\n shapes.append(shape)\n if shape.shape_type == 'Group':\n found = shape.find_shapes_by_property_label(property_label)\n if found:\n shapes.extend(found)\n return shapes\n\n def apply_text_filter(self, context: dict):\n # check text against all context keys\n text = self.text\n for key in context.keys():\n r_key = \"{{\" + key + \"}}\"\n text = text.replace(r_key, str(context[key]))\n self.text = text\n\n for s in self.sub_shapes():\n s.apply_text_filter(context)\n\n def find_replace(self, old: str, new: str):\n # find and replace text in this shape and sub shapes\n text = self.text\n self.text = text.replace(old, new)\n\n for s in self.sub_shapes():\n s.find_replace(old, new)\n\n def remove(self):\n self.parent.xml.remove(self.xml)\n\n def append_shape(self, append_shape: VisioFile.Shape):\n # insert shape into shapes tag, and return updated shapes tag\n id_map = self.page.vis.increment_shape_ids(append_shape.xml, self.page)\n self.page.vis.update_ids(append_shape.xml, id_map)\n self.xml.append(append_shape.xml)\n\n @property\n def connects(self):\n # get list of connect items linking shapes\n connects = list()\n for c in self.page.connects:\n if self.ID in [c.shape_id, c.connector_shape_id]:\n connects.append(c)\n return connects\n\n @property\n def connected_shapes(self):\n # return a list of connected shapes\n shapes = list()\n for c in self.connects:\n if c.connector_shape_id != self.ID:\n shapes.append(self.page.find_shape_by_id(c.connector_shape_id))\n if c.shape_id != self.ID:\n shapes.append(self.page.find_shape_by_id(c.shape_id))\n return shapes\n\n class Connect:\n \"\"\"Connect class to represent a connection between two `VisioFile.Shape` objects\"\"\"\n def __init__(self, xml: Element=None, page: VisioFile.Page=None):\n if page is None:\n return\n if type(xml) is Element: # create from xml\n self.xml = xml\n self.page = page # type: VisioFile.Page\n self.from_id = xml.attrib.get('FromSheet') # ref to the connector shape\n self.to_id = xml.attrib.get('ToSheet') # ref to the shape where the connector terminates\n self.from_rel = xml.attrib.get('FromCell') # i.e. EndX / BeginX\n self.to_rel = xml.attrib.get('ToCell') # i.e. PinX\n\n @staticmethod\n def create(page: VisioFile.Page=None, from_shape: VisioFile.Shape = None, to_shape: VisioFile.Shape = None) -> VisioFile.Shape:\n \"\"\"Create a new Connect object between from_shape and to_shape\n\n :returns: a new Connect object\n :rtype: VisioFile.Shape\n \"\"\"\n if from_shape and to_shape: # create new connector shape and connect items between this and the two shapes\n # create new connect shape and get id\n media = Media()\n connector_shape = media.straight_connector.copy(page) # default to straight connector\n connector_shape.text = '' # clear text used to find shape\n if not os.path.exists(page.vis._masters_folder):\n # Add masters folder to directory if not already present\n shutil.copytree(media._media_vsdx._masters_folder, page.vis._masters_folder)\n page.vis.load_master_pages() # load copied master page files into VisioFile object\n # add new master to document relationship\n page.vis._add_document_rel(rel_type=\"http://schemas.microsoft.com/visio/2010/relationships/masters\",\n target=\"masters/masters.xml\")\n # create masters/master1 elements in [Content_Types].xml\n page.vis._add_content_types_override(content_type=\"application/vnd.ms-visio.masters+xml\",\n part_name_path=\"/visio/masters/masters.xml\")\n page.vis._add_content_types_override(content_type=\"application/vnd.ms-visio.master+xml\",\n part_name_path=\"/visio/masters/master1.xml\")\n\n # update HeadingPairs and TitlesOfParts in app.xml\n if page.vis._get_app_xml_value('Masters') is None:\n page.vis._set_app_xml_value('Masters', '1')\n if 'Dynamic connector' not in page.vis._titles_of_parts_list(): # todo: replace static string with name from shape\n page.vis._add_titles_of_parts_item('Dynamic connector')\n\n # copy style used by new connector shape\n if not page.vis._get_style_by_id(connector_shape.master_shape.line_style_id):\n # assume same if is ok, todo: use names for match and increment IDs\n media_style = media._media_vsdx._get_style_by_id(connector_shape.master_shape.line_style_id)\n page.vis._style_sheets().append(media_style)\n media._media_vsdx.close_vsdx()\n\n # set Begin and End Trigger formulae for the new shape - linking to shapes in destination page\n beg_trigger = connector_shape.cells.get('BegTrigger')\n beg_trigger.formula = beg_trigger.formula.replace('Sheet.1!', f'Sheet{from_shape.ID}!')\n end_trigger = connector_shape.cells.get('EndTrigger')\n end_trigger.formula = end_trigger.formula.replace('Sheet.2!', f'Sheet{to_shape.ID}!')\n # create connect relationships\n # todo: FromPart=\"12\" and ToPart=\"3\" represent the part of a shape to connection is from/to\n end_connect_xml = f''\n beg_connect_xml = f''\n\n # Add these new connection relationships to the page\n page.add_connect(VisioFile.Connect(xml=ET.fromstring(end_connect_xml), page=page))\n page.add_connect(VisioFile.Connect(xml=ET.fromstring(beg_connect_xml), page=page))\n return connector_shape\n\n @property\n def shape_id(self):\n # ref to the shape where the connector terminates - convenience property\n return self.to_id\n\n @property\n def shape(self) -> VisioFile.Shape:\n return self.page.find_shape_by_id(self.shape_id)\n\n @property\n def connector_shape_id(self):\n # ref to the connector shape - convenience property\n return self.from_id\n\n @property\n def connector_shape(self) -> VisioFile.Shape:\n return self.page.find_shape_by_id(self.connector_shape_id)\n\n def __repr__(self):\n return f\"Connect: from={self.from_id} to={self.to_id} connector_id={self.connector_shape_id} shape_id={self.shape_id}\"\n\n class Page:\n \"\"\"Represents a page in a vsdx file\n\n :param vis: the VisioFile object the page belongs to\n :type vis: :class:`VisioFile`\n :param name: the name of the page\n :type name: str\n :param connects: a list of Connect objects in the page\n :type connects: List of :class:`Connect`\n\n \"\"\"\n def __init__(self, xml: ET.ElementTree, filename: str, page_name: str, vis: VisioFile):\n self._xml = xml\n self.filename = filename\n self.name = page_name\n self.vis = vis\n self.max_id = 0\n\n def __repr__(self):\n return f\"\"\n\n @property\n def connects(self):\n return self.get_connects()\n\n def set_name(self, value: str):\n # todo: change to name property\n pages_filename = self.vis._pages_filename() # pages contains Page name, width, height, mapped to Id\n pages = file_to_xml(pages_filename) # this contains a list of pages with rel_id and filename\n page = pages.getroot().find(f\"{namespace}Page[{self.index_num + 1}]\")\n #print(f\"set_name() page={VisioFile.pretty_print_element(page)}\")\n if page:\n page.attrib['Name'] = value\n self.name = value\n self.vis.pages_xml = pages\n\n @property\n def xml(self):\n return self._xml\n\n @xml.setter\n def xml(self, value):\n self._xml = value\n\n @property\n def shapes(self):\n \"\"\"Return a list of :class:`Shape` objects\n\n Note: typically returns one :class:`Shape` object which itself contains :class:`Shape` objects\n\n \"\"\"\n return [VisioFile.Shape(xml=shapes, parent=self, page=self) for shapes in self.xml.findall(f\"{namespace}Shapes\")]\n\n def sub_shapes(self) -> List[VisioFile.Shape]:\n \"\"\"Return list of Shape objects at top level of VisioFile.Page\n\n :returns: list of `VisioFile.Shape` objects\n :rtype: List[VisioFile.Shape]\n \"\"\"\n # note that self.shapes should always return a single shape\n return self.shapes[0].sub_shapes()\n\n def set_max_ids(self):\n # get maximum shape id from xml in page\n for shapes in self.shapes:\n for shape in shapes.sub_shapes():\n id = shape.get_max_id()\n if id > self.max_id:\n self.max_id = id\n\n return self.max_id\n\n @property\n def index_num(self):\n # return zero-based index of this page in parent VisioFile.pages list\n return self.vis.pages.index(self)\n\n def add_connect(self, connect: VisioFile.Connect):\n connects = self.xml.find(f\".//{namespace}Connects\")\n if connects is None:\n connects = ET.fromstring(f\"\")\n self.xml.getroot().append(connects)\n connects = self.xml.find(f\".//{namespace}Connects\")\n\n connects.append(connect.xml)\n\n def get_connects(self):\n elements = self.xml.findall(f\".//{namespace}Connect\") # search recursively\n connects = [VisioFile.Connect(xml=e, page=self) for e in elements]\n return connects\n\n def get_connectors_between(self, shape_a_id: str='', shape_a_text: str='',\n shape_b_id: str='', shape_b_text: str=''):\n shape_a = self.find_shape_by_id(shape_a_id) if shape_a_id else self.find_shape_by_text(shape_a_text)\n shape_b = self.find_shape_by_id(shape_b_id) if shape_b_id else self.find_shape_by_text(shape_b_text)\n connector_ids = set(a.ID for a in shape_a.connected_shapes).intersection(\n set(b.ID for b in shape_b.connected_shapes))\n\n connectors = set()\n for id in connector_ids:\n connectors.add(self.find_shape_by_id(id))\n return connectors\n\n def apply_text_context(self, context: dict):\n for s in self.shapes:\n s.apply_text_filter(context)\n\n def find_replace(self, old: str, new: str):\n for s in self.shapes:\n s.find_replace(old, new)\n\n def find_shape_by_id(self, shape_id) -> VisioFile.Shape:\n for s in self.shapes:\n found = s.find_shape_by_id(shape_id)\n if found:\n return found\n\n def _find_shapes_by_id(self, shape_id) -> List[VisioFile.Shape]:\n # return all shapes by ID - should only be used internally\n found = list()\n for s in self.shapes:\n found = s.find_shapes_by_id(shape_id)\n if found:\n return found\n return found\n\n def find_shapes_with_same_master(self, shape: VisioFile.Shape) -> List[VisioFile.Shape]:\n # return all shapes with master\n found = list()\n for s in self.shapes:\n found = s.find_shapes_by_master(master_page_ID=shape.master_page_ID,\n master_shape_ID=shape.master_shape_ID)\n if found:\n return found\n return found\n\n def find_shape_by_text(self, text: str) -> VisioFile.Shape:\n for s in self.shapes:\n found = s.find_shape_by_text(text)\n if found:\n return found\n\n def find_shapes_by_text(self, text: str) -> List[VisioFile.Shape]:\n shapes = list()\n for s in self.shapes:\n found = s.find_shapes_by_text(text)\n if found:\n shapes.extend(found)\n return shapes\n\n def find_shape_by_property_label(self, property_label: str) -> VisioFile.Shape:\n # return first matching shape with label\n # note: use label rather than name as label is more easily visible in diagram\n for s in self.shapes:\n found = s.find_shape_by_property_label(property_label)\n if found:\n return found\n\n def find_shapes_by_property_label(self, property_label: str) -> List[VisioFile.Shape]:\n # return all matching shapes with property label\n shapes = list()\n for s in self.shapes:\n found = s.find_shapes_by_property_label(property_label)\n if found:\n shapes.extend(found)\n return shapes\n\n\ndef file_to_xml(filename: str) -> ET.ElementTree:\n \"\"\"Import a file as an ElementTree\"\"\"\n try:\n tree = ET.parse(filename)\n return tree\n except FileNotFoundError:\n pass # return None\n\n\ndef xml_to_file(xml: ET.ElementTree, filename: str):\n \"\"\"Save an ElementTree to a file\"\"\"\n xml.write(filename, xml_declaration=True, method='xml', encoding='UTF-8')\n\n\nclass Media:\n straight_connector_text = 'STRAIGHT_CONNECTOR'\n curved_connector_text = 'CURVED_CONNECTOR'\n\n def __init__(self):\n basedir = str(os.path.relpath(__file__))\n file_path = os.sep.join(basedir.split(os.sep)[:-1])\n file_path = os.path.join(file_path, 'media', 'media.vsdx')\n self._media_vsdx = VisioFile(file_path)\n\n @property\n def straight_connector(self):\n return self._media_vsdx.pages[0].find_shape_by_text(Media.straight_connector_text)\n\n @property\n def curved_connector(self):\n return self._media_vsdx.pages[0].find_shape_by_text(Media.straight_connector_text)\n","sub_path":"vsdx/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":79078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"186810319","text":"from sklearn import datasets \nfrom sklearn import svm\nimport numpy as np\n\n# read in some data\ndigits = datasets.load_digits()\nX = digits.data\ny = digits.target\n\n# shuffle the data\nperm = np.random.permutation(len(X))\nX = X[perm]\ny = y[perm]\n\n# pick a training size\nt = int(0.8 * len(X))\n\n# train a support vector machine\nclf = svm.SVC(gamma=0.001, C=100.)\nclf.fit(X[:t], y[:t])\n\n# how does it perform on test data?\nz = clf.predict(X[t:])\ntt = len(z)\ncomp = [z[i] == y[i+t] for i in range(tt)]\nagree = sum(comp)\nprint(agree, tt, float(agree)/tt)\n","sub_path":"examples/sklearn3.py","file_name":"sklearn3.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"109481391","text":"import numpy as np\nimport pandas as pd\nimport os\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nimport statistics\n\nimport time\nimport warnings\n\n# From https://machinelearningmastery.com/sequence-classification-lstm-recurrent-neural-networks-python-keras/\n# and https://towardsdatascience.com/multi-class-text-classification-with-lstm-1590bee1bd17\nfrom sklearn.model_selection import train_test_split\nfrom keras.layers import Dense, BatchNormalization\nfrom keras.callbacks import EarlyStopping\nfrom sklearn.preprocessing import label_binarize\nfrom keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.optimizers import SGD\n\nfrom sklearn.metrics import confusion_matrix, roc_curve, auc, roc_auc_score, recall_score\nfrom keras import backend as K\nimport tensorflow as tf\n\nwarnings.filterwarnings('ignore')\n\n\ndef get_auc(actual, preds, classes):\n return roc_auc_score(label_binarize(actual, classes), label_binarize(preds, classes))\n\n\ndef get_fpr(actual, preds):\n tn, fp, fn, tp = confusion_matrix(actual, preds, labels=[0,1]).ravel()\n fpr = fp * 1.0 / (tn + fp) if (tn + fp) != 0 else 0\n \n return fpr\n\n\ndef subtotal(x):\n xx = [0]\n for i, t in enumerate(x):\n xx += [xx[-1] + t]\n return xx[1:]\n\n\ndef get_recall(true):\n total_true = float(len([i for i in true if i == 1]))\n hit = 0.0\n recall = []\n for i in range(len(true)):\n if true[i] == 1:\n hit += 1\n recall += [hit / total_true if total_true else 0.0]\n return recall\n\n\ndef get_popt20(data):\n data.sort_values(by=[\"bug\", \"loc\"], ascending=[0, 1], inplace=True)\n x_sum = float(sum(data['loc']))\n x = data['loc'].apply(lambda t: t / x_sum)\n xx = subtotal(x)\n\n # get AUC_optimal\n yy = get_recall(data['bug'].values)\n xxx = [i for i in xx if i <= 0.2]\n yyy = yy[:len(xxx)]\n s_opt = round(auc(xxx, yyy), 3)\n\n # get AUC_worst\n xx = subtotal(x[::-1])\n yy = get_recall(data['bug'][::-1].values)\n xxx = [i for i in xx if i <= 0.2]\n yyy = yy[:len(xxx)]\n try:\n s_wst = round(auc(xxx, yyy), 3)\n except:\n # print \"s_wst forced = 0\"\n s_wst = 0\n \n # get AUC_prediction\n data.sort_values(by=[\"prediction\", \"loc\"], ascending=[0, 1], inplace=True)\n x = data['loc'].apply(lambda t: t / x_sum)\n xx = subtotal(x)\n yy = get_recall(data['bug'].values)\n xxx = [k for k in xx if k <= 0.2]\n yyy = yy[:len(xxx)]\n try:\n s_m = round(auc(xxx, yyy), 3)\n except:\n return 0\n \n Popt = (s_m - s_wst) / (s_opt - s_wst)\n return round(Popt,3)\n\n\nbase_path = '../data/defect/'\n\n\nfile_dic = {\"ivy\": [\"ivy-1.1.csv\", \"ivy-1.4.csv\", \"ivy-2.0.csv\"],\n \"lucene\": [\"lucene-2.0.csv\", \"lucene-2.2.csv\", \"lucene-2.4.csv\"],\n \"poi\": [\"poi-1.5.csv\", \"poi-2.0.csv\", \"poi-2.5.csv\", \"poi-3.0.csv\"],\n \"synapse\": [\"synapse-1.0.csv\", \"synapse-1.1.csv\", \"synapse-1.2.csv\"],\n \"velocity\": [\"velocity-1.4.csv\", \"velocity-1.5.csv\", \"velocity-1.6.csv\"],\n \"camel\": [\"camel-1.0.csv\", \"camel-1.2.csv\", \"camel-1.4.csv\", \"camel-1.6.csv\"],\n \"jedit\": [\"jedit-3.2.csv\", \"jedit-4.0.csv\", \"jedit-4.1.csv\", \"jedit-4.2.csv\", \"jedit-4.3.csv\"],\n \"log4j\": [\"log4j-1.0.csv\", \"log4j-1.1.csv\", \"log4j-1.2.csv\"],\n \"xalan\": [\"xalan-2.4.csv\", \"xalan-2.5.csv\", \"xalan-2.6.csv\", \"xalan-2.7.csv\"],\n \"xerces\": [\"xerces-1.2.csv\", \"xerces-1.3.csv\", \"xerces-1.4.csv\"]\n }\n\n\ndef run_on_dataset(filename, metric='d2h', epochs=10, layers=4, draw_roc=False, weighted=False):\n paths = [os.path.join(base_path, file_name) for file_name in file_dic[filename]]\n train_df = pd.concat([pd.read_csv(path) for path in paths[:-1]], ignore_index=True)\n test_df = pd.read_csv(paths[-1])\n \n train_df, test_df = train_df.iloc[:, 3:], test_df.iloc[:, 3:]\n train_size = train_df[\"bug\"].count()\n df = pd.concat([train_df, test_df], ignore_index=True)\n df['bug'] = df['bug'].apply(lambda x: 0 if x == 0 else 1)\n \n train_data = df.iloc[:train_size, :]\n test_data = df.iloc[train_size:, :]\n \n X_train = train_data[train_data.columns[:-2]]\n y_train = train_data['bug']\n X_test = test_data[test_data.columns[:-2]]\n y_test = test_data['bug']\n \n frac = sum(y_train) * 1.0 / len(y_train)\n if weighted:\n weights = np.array([1., 0.1 / frac])\n else:\n weights = np.array([1., 1.])\n \n model = Sequential()\n model.add(Dense(20, input_shape=(X_train.shape[1],), activation='relu', name='layer1'))\n \n for i in range(layers - 2):\n model.add(Dense(20, activation='relu', name='layer'+str(i+2)))\n \n model.add(Dense(1, activation='sigmoid', name='layer'+str(layers)))\n model.compile(loss=weighted_categorical_crossentropy(weights), optimizer='adam', metrics=['accuracy'])\n\n batch_size = 64\n\n history = model.fit(X_train, y_train, epochs=epochs, batch_size=batch_size,validation_split=0.1, verbose=0, callbacks=[EarlyStopping(monitor='val_loss', patience=20, min_delta=0.0001)])\n \n y_pred = model.predict_classes(X_test)\n \n if metric == 'fpr':\n metric_ = get_fpr(y_test, y_pred)\n elif metric == 'recall':\n metric_ = recall_score(y_test, y_pred)\n elif metric == 'auc':\n metric_ = get_auc(y_test, y_pred, classes=[0,1])\n elif metric == 'popt20':\n test_data.loc[:,\"prediction\"]=y_pred\n metric_ = get_popt20(test_data)\n \n if draw_roc:\n fpr, tpr, _ = roc_curve(y_test, y_pred)\n print('AUC =', auc(fpr, tpr))\n print(metric, '=', metric_)\n plt.plot(fpr, tpr, color='darkorange')\n plt.plot([0, 1], [0, 1], color='navy', linestyle='--')\n \n return history, metric_\n\n\nfor dataset in file_dic.keys():\n print(dataset)\n print('=' * len(dataset))\n for metric in ['fpr']:\n values = []\n for i in range(20):\n _, metric_ = run_on_dataset(filename=dataset, metric=metric, epochs=10, layers=4)\n values.append(metric_)\n \n print(metric, '-', statistics.median(values))\n \n print()\n","sub_path":"doc/RQ1.py","file_name":"RQ1.py","file_ext":"py","file_size_in_byte":6111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"493666061","text":"import pygame as pg\r\nimport os\r\nimport pandas as pd\r\nimport collections as co\r\nimport numpy as np\r\nimport pickle\r\nfrom Visualization import DrawBackground, DrawNewState, DrawImage,GiveExperimentFeedback\r\nfrom Controller import HumanController,ModelController\r\nimport UpdateWorld\r\nfrom Writer import WriteDataFrameToCSV\r\nfrom Trial import Trial\r\n\r\n\r\nclass Experiment():\r\n def __init__(self, trial, writer, experimentValues, initialWorld, updateWorld, drawImage, resultsPath, \\\r\n minDistanceBetweenGrids):\r\n self.trial = trial\r\n self.writer = writer\r\n self.experimentValues = experimentValues\r\n self.initialWorld = initialWorld\r\n self.updateWorld = updateWorld\r\n self.drawImage = drawImage\r\n self.resultsPath = resultsPath\r\n self.minDistanceBetweenGrids = minDistanceBetweenGrids\r\n\r\n def __call__(self, finishTime):\r\n bean1Grid, bean2Grid, playerGrid = self.initialWorld(self.minDistanceBetweenGrids)\r\n trialIndex = 0\r\n score=0\r\n currentStopwatch=0\r\n while True:\r\n results, bean1Grid, playerGrid,score,currentStopwatch = self.trial(bean1Grid, bean2Grid, playerGrid,score,currentStopwatch)\r\n response = self.experimentValues.copy()\r\n response.update(results)\r\n responseDF = pd.DataFrame(response, index=[trialIndex])\r\n self.writer(responseDF)\r\n if currentStopwatch >= finishTime:\r\n break\r\n bean2Grid, self.experimentValues[\"condition\"] = self.updateWorld(bean1Grid, playerGrid)\r\n trialIndex += 1\r\n return score\r\n\r\n\r\ndef main():\r\n gridSize = 16\r\n bounds = [0, 0, gridSize - 1,gridSize - 1]\r\n minDistanceBetweenGrids = 5\r\n condition = [-5, -3, -1, 0, 1, 3, 5]\r\n counter = [0] * len(condition)\r\n initialWorld = UpdateWorld.InitialWorld(bounds)\r\n updateWorld = UpdateWorld.UpdateWorld(bounds, condition, counter)\r\n pg.init()\r\n screenWidth = 680\r\n screenHeight = 680\r\n screen = pg.display.set_mode((screenWidth, screenHeight))\r\n leaveEdgeSpace = 2\r\n lineWidth = 1\r\n backgroundColor = [205, 255, 204]\r\n lineColor = [0, 0, 0]\r\n targetColor = [255, 50, 50]\r\n playerColor = [50, 50, 255]\r\n targetRadius = 10\r\n playerRadius = 10\r\n stopwatchUnit = 100\r\n finishTime=1000*90\r\n block=1\r\n softmaxBeita=-1\r\n textColorTuple = (255, 50, 50)\r\n stopwatchEvent = pg.USEREVENT + 1\r\n pg.time.set_timer(stopwatchEvent, stopwatchUnit)\r\n pg.event.set_allowed([pg.KEYDOWN, pg.QUIT, stopwatchEvent])\r\n pg.key.set_repeat(120,120)\r\n picturePath = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) + '/Pictures/'\r\n resultsPath = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) + '/Results/'\r\n experimentValues = co.OrderedDict()\r\n experimentValues[\"name\"] = input(\"Please enter your name:\").capitalize()\r\n experimentValues[\"condition\"] = 'None'\r\n writerPath = resultsPath + experimentValues[\"name\"] + '.csv'\r\n writer = WriteDataFrameToCSV(writerPath)\r\n introductionImage = pg.image.load(picturePath + 'introduction.png')\r\n restImage = pg.image.load(picturePath + 'rest.png')\r\n finishImage = pg.image.load(picturePath + 'finish.png')\r\n introductionImage=pg.transform.scale(introductionImage, (screenWidth,screenHeight))\r\n finishImage=pg.transform.scale(finishImage, (int(screenWidth*2/3),int(screenHeight/4)))\r\n drawBackground = DrawBackground(screen, gridSize, leaveEdgeSpace, backgroundColor, lineColor, lineWidth,\r\n textColorTuple)\r\n drawNewState = DrawNewState(screen, drawBackground, targetColor, playerColor, targetRadius, playerRadius)\r\n drawImage = DrawImage(screen)\r\n humanController = HumanController(gridSize, stopwatchEvent, stopwatchUnit, drawNewState,finishTime)\r\n policy = pickle.load(open(\"SingleWolfTwoSheepsGrid15.pkl\",\"rb\"))\r\n modelController = ModelController(policy, gridSize, stopwatchEvent, stopwatchUnit, drawNewState, finishTime, softmaxBeita)\r\n trial = Trial(modelController, drawNewState, stopwatchEvent,finishTime)\r\n experiment = Experiment(trial, writer, experimentValues, initialWorld, updateWorld, drawImage, resultsPath,\r\n minDistanceBetweenGrids)\r\n giveExperimentFeedback=GiveExperimentFeedback(screen,textColorTuple,screenWidth,screenHeight)\r\n drawImage(introductionImage)\r\n score=[0]*block\r\n for i in range(block):\r\n score[i] = experiment(finishTime)\r\n giveExperimentFeedback(i,score)\r\n if i == block-1:\r\n drawImage(finishImage)\r\n # else:\r\n # drawImage(restImage)\r\n\r\n participantsScore=np.sum(np.array(score))\r\n print(participantsScore)\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"SourceCode/Experiment.py","file_name":"Experiment.py","file_ext":"py","file_size_in_byte":4788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"621119845","text":"# Copyright 2019 NEC Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\"\"\"\n[概要]\n 監視アダプタ 監視実行処理(子プロセス)\n\"\"\"\n\nimport os\nimport sys\nimport json\nimport re\nimport pytz\nimport datetime\nimport django\nimport traceback\n\nfrom socket import gethostname\n\n# OASE モジュール importパス追加\nmy_path = os.path.dirname(os.path.abspath(__file__))\ntmp_path = my_path.split('oase-root')\nroot_dir_path = tmp_path[0] + 'oase-root'\nsys.path.append(root_dir_path)\n\n# OASE モジュール import\n# #LOCAL_PATCH#\nos.environ['DJANGO_SETTINGS_MODULE'] = 'confs.frameworkconfs.settings'\ndjango.setup()\n\nfrom django.conf import settings\nfrom django.db import transaction\nfrom django.db.models import Q\n\n#################################################\n# デバック用\nif settings.DEBUG and getattr(settings, 'ENABLE_NOSERVICE_BACKYARDS', False):\n oase_root_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../..')\n os.environ['OASE_ROOT_DIR'] = oase_root_dir \n os.environ['RUN_INTERVAL'] = '3'\n os.environ['PYTHON_MODULE'] = '/usr/bin/python3'\n os.environ['LOG_LEVEL'] = \"TRACE\"\n os.environ['LOG_DIR'] = oase_root_dir + \"/logs/backyardlogs/oase_action\"\n#################################################\n# 環境変数取得\ntry:\n root_dir_path = os.environ['OASE_ROOT_DIR']\n run_interval = os.environ['RUN_INTERVAL']\n python_module = os.environ['PYTHON_MODULE']\n log_dir = os.environ['LOG_DIR']\n log_level = os.environ['LOG_LEVEL']\nexcept Exception as ex:\n print(str(ex))\n sys.exit(2)\n\n# ロガー初期化\nfrom libs.commonlibs.oase_logger import OaseLogger\nlogger = OaseLogger.get_instance()\n\n#################################################\n# 負荷テスト設定\nENABLE_LOAD_TEST = getattr(settings, 'ENABLE_LOAD_TEST', False)\nif ENABLE_LOAD_TEST:\n import time\n import logging\n loadtest_logger = logging.getLogger('load_zabbix_monitor')\n\n\nfrom web_app.models.models import User\nfrom web_app.models.models import System\nfrom web_app.models.models import RuleType\nfrom web_app.models.models import MonitoringType\nfrom web_app.models.models import AdapterType\nfrom web_app.models.ZABBIX_monitoring_models import ZabbixAdapter\nfrom web_app.models.ZABBIX_monitoring_models import ZabbixMonitoringHistory\nfrom web_app.templatetags.common import get_message\n\nfrom libs.backyardlibs.monitoring_adapter.ZABBIX.manage_trigger import ManageTrigger\nfrom libs.backyardlibs.monitoring_adapter.ZABBIX.ZABBIX_api import ZabbixApi\nfrom libs.backyardlibs.monitoring_adapter.ZABBIX.ZABBIX_formatting import message_formatting\nfrom libs.backyardlibs.monitoring_adapter.ZABBIX.ZABBIX_request import send_request\nfrom libs.commonlibs.common import Common\nfrom libs.commonlibs.define import *\n\n\n#-------------------\n# STATUS\n#-------------------\nPROCESSING = 1\nPROCESSED = 2\nSERVER_ERROR = 3\n\nDB_OASE_USER = -2140000005\n\nclass ZabbixAdapterSubModules:\n \"\"\"\n [クラス概要]\n アクションドライバメイン処理クラス\n \"\"\"\n\n def __init__(self, zabbix_adapter_id=0):\n \"\"\"\n [概要]\n コンストラクタ\n \"\"\"\n\n # クラス生成\n self.monitoring_history = None\n self.zabbix_adapter_id = zabbix_adapter_id\n self.zabbix_adapter = None\n self.monitoring_history = None\n self.user_objects = User.objects.get(user_id=DB_OASE_USER)\n self.user = self.user_objects.user_name\n\n\n def insert_monitoring_history(self, zabbix_lastchange, status):\n \"\"\"\n [概要]\n ZABBIX監視履歴登録メゾット\n \"\"\"\n logger.logic_log('LOSI00001', 'zabbix_adapter_id: %s, zabbix_lastchange: %s, status: %s' % (self.zabbix_adapter_id, zabbix_lastchange, status))\n\n monitoring_history = None\n monitoring_history_id = -1\n try:\n monitoring_history = ZabbixMonitoringHistory(\n zabbix_adapter_id = self.zabbix_adapter_id,\n zabbix_lastchange = zabbix_lastchange,\n status = status,\n status_update_id = gethostname(),\n last_update_timestamp = datetime.datetime.now(pytz.timezone('UTC')),\n last_update_user = self.user,\n )\n monitoring_history.save(force_insert=True)\n\n monitoring_history_id = monitoring_history.pk\n\n except Exception as e:\n logger.system_log('LOSM25013', self.zabbix_adapter_id)\n logger.logic_log('LOSM00001', 'zabbix_adapter_id: %s, Traceback: %s' % (self.zabbix_adapter_id, traceback.format_exc()))\n monitoring_history = None\n\n logger.logic_log('LOSI00002', 'zabbix_adapter_id: %s, monitoring_history_id: %s' % (self.zabbix_adapter_id, str(monitoring_history_id)))\n\n return monitoring_history\n\n\n def update_monitoring_history(self, status, last_monitoring_time):\n \"\"\"\n [概要]\n ZABBIX監視履歴更新メゾット\n \"\"\"\n\n logger.logic_log('LOSI00001', 'zabbix_adapter_id: %s, status: %s' % (self.zabbix_adapter_id, status))\n try:\n self.monitoring_history.status = status\n self.monitoring_history.zabbix_lastchange = last_monitoring_time\n self.monitoring_history.status_update_id = gethostname()\n self.monitoring_history.last_update_timestamp = datetime.datetime.now(pytz.timezone('UTC'))\n self.monitoring_history.last_update_user = self.user\n self.monitoring_history.save(force_update=True)\n\n except Exception as e:\n raise\n\n logger.logic_log('LOSI00002', 'zabbix_adapter_id: %s' % (self.zabbix_adapter_id))\n return True\n\n\n def execute(self, zabbix_adapter, zabbix_lastchange):\n \"\"\"\n [概要]\n 監視実行\n \"\"\"\n\n logger.logic_log('LOSI00001', 'zabbix_adapter_id: %s' % (self.zabbix_adapter_id))\n\n result = True\n api_response = []\n last_monitoring_time = 0\n try:\n zabbix_api = ZabbixApi(zabbix_adapter)\n # TODO last_monitoring_timeを返却してもらう予定 現状(2020/01/10) 0で実施する\n api_response = zabbix_api.get_active_triggers(zabbix_lastchange)\n zabbix_api.logout()\n\n except TypeError as e:\n result = False\n logger.system_log('LOSM25014', self.zabbix_adapter_id)\n logger.logic_log('LOSM00001', 'zabbix_adapter_id: %s, e: %s' % (self.zabbix_adapter_id, e))\n\n except Exception as e:\n result = False\n logger.system_log('LOSM25014', self.zabbix_adapter_id)\n logger.logic_log('LOSM00001', 'zabbix_adapter_id: %s, e: %s, Traceback: %s' % (self.zabbix_adapter_id, e, traceback.format_exc()))\n\n logger.logic_log('LOSI00002', 'zabbix_adapter_id: %s' % (self.zabbix_adapter_id))\n\n return result, api_response, last_monitoring_time\n\n\n def do_workflow(self):\n \"\"\"\n [概要]\n \n \"\"\"\n logger.logic_log('LOSI00001', 'zabbix_adapter_id: %s' % (self.zabbix_adapter_id))\n\n zabbix_adapter = None\n latest_monitoring_history = None\n zabbix_lastchange = 0\n\n # 事前情報取得\n try:\n zabbix_adapter = ZabbixAdapter.objects.get(pk=self.zabbix_adapter_id)\n\n latest_monitoring_history = ZabbixMonitoringHistory.objects.filter(zabbix_adapter_id=self.zabbix_adapter_id, status=PROCESSED).order_by('zabbix_lastchange').reverse().first()\n\n except Exception as e:\n logger.logic_log('LOSM00001', 'zabbix_adapter_id: %s, Traceback: %s' % (self.zabbix_adapter_id, traceback.format_exc()))\n\n if latest_monitoring_history != None:\n zabbix_lastchange = latest_monitoring_history.zabbix_lastchange\n\n # 監視履歴作成 メンバ変数にセット\n try:\n self.monitoring_history = self.insert_monitoring_history(zabbix_lastchange, PROCESSING)\n if self.monitoring_history is None:\n return False\n\n except Exception as e:\n logger.system_log('LOSM25013', self.zabbix_adapter_id)\n logger.logic_log('LOSM00001', 'Traceback: %s' % (traceback.format_exc()))\n return False\n\n runnable = True\n error_occurred = False\n try:\n # 監視実行\n result_flag, result_data, last_monitoring_time = self.execute(zabbix_adapter, zabbix_lastchange)\n\n if not result_flag:\n error_occurred = True\n runnable = False\n\n # トリガー比較\n difference = []\n if runnable:\n triggerManager = ManageTrigger(self.zabbix_adapter_id, self.user)\n confirm_list = [(int(record['triggerid']), int(record['lastchange'])) for record in result_data]\n flag_array = triggerManager.main(confirm_list)\n\n index = 0\n for flag in flag_array:\n if flag:\n difference.append(result_data[index])\n\n index = index + 1\n\n if len(difference) <= 0:\n runnable = False\n\n # メッセージ整形\n if runnable:\n formatting_result, form_data = message_formatting(difference, zabbix_adapter.rule_type_id, self.zabbix_adapter_id)\n\n if not formatting_result:\n error_occurred = True\n runnable = False\n\n if len(form_data) <= 0:\n runnable = False\n\n # OASEへ本番リクエスト\n if runnable:\n send_result = send_request(form_data)\n\n if not send_result:\n error_occurred = True\n runnable = False\n\n # トリガー情報を保存\n if runnable:\n triggerManager.save_trigger_info(confirm_list)\n\n except Exception as e:\n error_occurred = True\n logger.system_log('LOSM25014', self.zabbix_adapter_id)\n logger.logic_log('LOSM00001', 'Traceback: %s' % (traceback.format_exc()))\n\n # 結果により監視履歴更新\n status = 'success'\n try:\n # 正常終了\n if not error_occurred:\n self.update_monitoring_history(PROCESSED, last_monitoring_time)\n\n # 異常終了\n else:\n status = 'error'\n self.update_monitoring_history(SERVER_ERROR, last_monitoring_time)\n\n except Exception as e:\n status = 'error'\n logger.system_log('LOSM25011')\n logger.logic_log('LOSM00001', 'Traceback: %s' % (traceback.format_exc()))\n\n logger.logic_log('LOSI00002', 'Monitoring status: %s.' % status)\n\n return True\n\n\nif __name__ == '__main__':\n\n zabbix_adapter_id = 0\n\n # 起動パラメータ\n args = sys.argv\n\n # 引数の共通部分設定\n if len(args) == 2:\n zabbix_adapter_id = int(args[1])\n else:\n logger.system_log('LOSE25000')\n logger.logic_log('LOSE00002', 'args: %s' % (args))\n sys.exit(2)\n\n if ENABLE_LOAD_TEST:\n start_time = time.time()\n loadtest_logger.warn('処理開始 ZabbixAdapterID[%s]' % (zabbix_adapter_id))\n\n logger.logic_log('LOSI25002', str(zabbix_adapter_id))\n try:\n zabbix_sub_module = ZabbixAdapterSubModules(zabbix_adapter_id)\n\n zabbix_sub_module.do_workflow()\n\n except Exception as e:\n logger.system_log('LOSM25014', self.zabbix_adapter_id)\n logger.logic_log('LOSM00001', 'zabbix_adapter_id: %s, Traceback: %s' % (str(zabbix_adapter_id), traceback.format_exc()))\n\n if ENABLE_LOAD_TEST:\n elapsed_time = time.time() - start_time\n loadtest_logger.warn('処理終了 所要時間[%s] ZabbixAdapterID[%s]' % (elapsed_time, zabbix_adapter_id))\n\n logger.logic_log('LOSI25003', str(zabbix_adapter_id))\n\n sys.exit(0)\n\n","sub_path":"oase-root/backyards/monitoring_adapter/ZABBIX_monitoring_sub.py","file_name":"ZABBIX_monitoring_sub.py","file_ext":"py","file_size_in_byte":12539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"637289654","text":"import json\nimport requests\nfrom cklib.args import ArgumentParser\nfrom cklib.logging import log\nfrom cklib.jwt import encode_jwt_to_headers\nfrom cklib.graph import Graph, GraphExportIterator\n\n\ndef send_to_ckcore(graph: Graph):\n if not ArgumentParser.args.ckcore_uri:\n return\n\n log.info(\"ckcore Event Handler called\")\n\n base_uri = ArgumentParser.args.ckcore_uri.strip(\"/\")\n ckcore_graph = ArgumentParser.args.ckcore_graph\n dump_json = ArgumentParser.args.debug_dump_json\n\n create_graph(base_uri, ckcore_graph)\n update_model(graph, base_uri, dump_json=dump_json)\n send_graph(graph, base_uri, ckcore_graph, dump_json=dump_json)\n\n\ndef create_graph(ckcore_base_uri: str, ckcore_graph: str):\n graph_uri = f\"{ckcore_base_uri}/graph/{ckcore_graph}\"\n\n log.debug(f\"Creating graph {ckcore_graph} via {graph_uri}\")\n\n headers = {\"accept\": \"application/json\"}\n if getattr(ArgumentParser.args, \"psk\", None):\n encode_jwt_to_headers(headers, {}, ArgumentParser.args.psk)\n\n r = requests.post(graph_uri, data=\"\", headers=headers)\n if r.status_code != 200:\n log.error(r.content)\n raise RuntimeError(f\"Failed to create graph: {r.content}\")\n\n\ndef update_model(graph: Graph, ckcore_base_uri: str, dump_json: bool = False):\n model_uri = f\"{ckcore_base_uri}/model\"\n\n log.debug(f\"Updating model via {model_uri}\")\n\n model_json = json.dumps(graph.export_model(), indent=4)\n if dump_json:\n with open(\"model.dump.json\", \"w\") as model_outfile:\n model_outfile.write(model_json)\n\n headers = {}\n if getattr(ArgumentParser.args, \"psk\", None):\n encode_jwt_to_headers(headers, {}, ArgumentParser.args.psk)\n\n r = requests.patch(model_uri, data=model_json, headers=headers)\n if r.status_code != 200:\n log.error(r.content)\n raise RuntimeError(f\"Failed to create model: {r.content}\")\n\n\ndef send_graph(\n graph: Graph, ckcore_base_uri: str, ckcore_graph: str, dump_json: bool = False\n):\n merge_uri = f\"{ckcore_base_uri}/graph/{ckcore_graph}/merge\"\n\n log.debug(f\"Sending graph via {merge_uri}\")\n\n graph_outfile = None\n if dump_json:\n graph_outfile = open(\"graph.dump.json\", \"w\")\n\n try:\n graph_export_iterator = GraphExportIterator(graph, graph_outfile)\n\n headers = {\n \"Content-Type\": \"application/x-ndjson\",\n \"Cloudkeeper-Ckworker-Nodes\": str(graph.number_of_nodes()),\n \"Cloudkeeper-Ckworker-Edges\": str(graph.number_of_edges()),\n }\n if getattr(ArgumentParser.args, \"psk\", None):\n encode_jwt_to_headers(headers, {}, ArgumentParser.args.psk)\n\n r = requests.post(\n merge_uri,\n data=graph_export_iterator,\n headers=headers,\n )\n if r.status_code != 200:\n log.error(r.content)\n raise RuntimeError(f\"Failed to send graph: {r.content}\")\n log.debug(f\"ckcore reply: {r.content.decode()}\")\n log.debug(\n f\"Sent {graph_export_iterator.nodes_sent} nodes and\"\n f\" {graph_export_iterator.edges_sent} edges to ckcore\"\n )\n finally:\n if graph_outfile is not None:\n graph_outfile.close()\n\n\ndef add_args(arg_parser: ArgumentParser) -> None:\n arg_parser.add_argument(\n \"--ckcore-uri\",\n help=\"ckcore URI (default: http://localhost:8900)\",\n default=\"http://localhost:8900\",\n dest=\"ckcore_uri\",\n )\n arg_parser.add_argument(\n \"--ckcore-ws-uri\",\n help=\"ckcore Websocket URI (default: ws://localhost:8900)\",\n default=\"ws://localhost:8900\",\n dest=\"ckcore_ws_uri\",\n )\n arg_parser.add_argument(\n \"--ckcore-graph\",\n help=\"ckcore graph name (default: ck)\",\n default=\"ck\",\n dest=\"ckcore_graph\",\n )\n arg_parser.add_argument(\n \"--debug-dump-json\",\n help=\"Dump the generated json data (default: False)\",\n dest=\"debug_dump_json\",\n action=\"store_true\",\n )\n","sub_path":"ckworker/ckworker/ckcore.py","file_name":"ckcore.py","file_ext":"py","file_size_in_byte":3980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"254833656","text":"# Pyspark LDA Version Example\n\ndf_for_lda = df_ratings\n\nLDA_NUM_TOPICS = 5\nLDA_MAX_ITERATIONS = 100\nLDA_OPTIMIZER = 'em'\nLDA_FEATURES_COL = 'TFOut'\n\nlda = LDA().setK(LDA_NUM_TOPICS).setMaxIter(LDA_MAX_ITERATIONS).setOptimizer(LDA_OPTIMIZER).setFeaturesCol(LDA_FEATURES_COL)\n\n# Setup Text Analytics Preprocessing and LDA\npipe_text_prep = Pipeline().setStages([get_relevant_data,documentAssembler,tknNlp,lemm,finishNlp,removePunct,tkn,stops,tf,lda])\nLDA_MODEL_INDEX = -1\nLDA_TF_MODEL_INDEX = -2\n\ntrainedPipe_lda = pipe_text_prep.fit(df_for_lda)\ntrainedDF_lda = trainedPipe_lda.transform(df_for_lda)\n\nSHOW_NUM_WORDS_PER_TOPIC = 3\ndf_lda_topics = trained_lda_model.describeTopics(maxTermsPerTopic = SHOW_NUM_WORDS_PER_TOPIC)\ntrained_tf_model = trainedPipe_lda.stages[LDA_TF_MODEL_INDEX]\nvocab_array = trained_tf_model.vocabulary\ndisplay(df_lda_topics)\n\n# NOTE: Annoying way to look up Vocabulary via UDF on the items\ndef get_vocab(term_array):\n result = []\n for i in range(len(term_array)):\n term = vocab_array[term_array[i]]\n result.append(term)\n return result\n\nfn_get_vocab = F.udf(lambda x: get_vocab(x))\ndf_lda_topics_final = df_lda_topics.withColumn('vocabTerms', fn_get_vocab(df_lda_topics.termIndices))\ndisplay(df_lda_topics_final)","sub_path":"pyspark-helpers/pyspark_lda.py","file_name":"pyspark_lda.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"618422758","text":"groupmates = [\n {\n \"name\": \"sasha\",\n \"group\": \"19\",\n \"age\": 20,\n \"marks\": [4, 3, 5, 5, 4]\n },\n {\n \"name\": \"pasha\",\n \"group\": \"19\",\n \"age\": 19,\n \"marks\": [3, 2, 3, 3, 3]\n },\n {\n \"name\": \"danila\",\n \"group\": \"19\",\n \"age\": 18,\n \"marks\": [3, 2, 4, 3, 5]\n },\n {\n \"name\": \"dima\",\n \"group\": \"19\",\n \"age\": 19,\n \"marks\": [5, 5, 5, 4, 5]\n },\n {\n \"name\": \"ivan\",\n \"group\": \"19\",\n \"age\": 20,\n \"marks\": [5, 5, 4, 5, 5]\n }\n]\n\ndef count_mark(students,mark):\n print (\"name\".ljust(15), \"group\".ljust(8), \"age\".ljust(8), \"marks\".ljust(20))\n for student in students:\n marks_list = student['marks']\n result = (sum(marks_list)/len(marks_list))\n if result >= need:\n print(student[\"name\"].ljust(15), student[\"group\"].ljust(8), str(student[\"age\"]).ljust(8), str(student[\"marks\"]).ljust(20))\n\nneed = int(input('Input :'))\n\ncount_mark(groupmates,need)\n","sub_path":"123.py","file_name":"123.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"174275163","text":"import time\nfrom enum import Enum\nfrom concurrent.futures import TimeoutError\n\nfrom descarteslabs.common.property_filtering import GenericProperties\nfrom .catalog_base import CatalogObject, CatalogClient, check_deleted\nfrom .attributes import Attribute, Resolution, Timestamp, BooleanAttribute\n\nproperties = GenericProperties()\n\n\nclass Product(CatalogObject):\n \"\"\"A raster product that connects band information to imagery.\n\n Parameters\n ----------\n kwargs : dict\n With the exception of readonly attributes\n (:py:attr:`~descarteslabs.catalog.CatalogObject.created`,\n :py:attr:`~descarteslabs.catalog.CatalogObject.modified`), any\n (inherited) attribute listed below can also be used as a keyword argument.\n\n Inheritance\n -----------\n For inherited parameters, methods, attributes, and properties, please refer to the\n base class:\n\n * :py:class:`descarteslabs.catalog.CatalogObject`\n\n |\n\n Attributes\n ----------\n name : str\n Required: The name of this product.\n *Sortable*.\n description : str\n A description with further details on this product.\n start_datetime : str, datetime-like\n The beginning of the mission for this product.\n *Filterable, sortable*.\n end_datetime : str, datetime-like\n The end of the mission for this product.\n *Filterable, sortable*.\n is_core : bool\n Whether this is a Descartes Labs catalog core product, which means that\n the product is fully supported by Descartes Labs.\n *Filterable, sortable*.\n revisit_period_minutes_min : float\n Minimum length of the time interval between observations of any given area in\n minutes.\n *Filterable, sortable*.\n revisit_period_minutes_max : float\n Maxiumum length of the time interval between observations of any given area in\n minutes.\n *Filterable, sortable*.\n resolution_min : Resolution\n Minimum resolution of the bands for this product. If applying a filter with a\n plain unitless number the value is assumed to be in meters.\n *Filterable, sortable*.\n resolution_max : Resolution\n Maximum resolution of the bands for this product. If applying a filter with a\n plain unitless number the value is assumed to be in meters.\n *Filterable, sortable*.\n \"\"\"\n\n _doc_type = \"product\"\n _url = \"/products\"\n\n # Product Attributes\n name = Attribute()\n description = Attribute()\n is_core = BooleanAttribute()\n revisit_period_minutes_min = Attribute()\n revisit_period_minutes_max = Attribute()\n start_datetime = Timestamp()\n end_datetime = Timestamp()\n resolution_min = Resolution()\n resolution_max = Resolution()\n\n @check_deleted\n def delete_related_objects(self):\n \"\"\"Delete all related bands and images for this product.\n\n Starts an asynchronous operation that deletes all bands and images associated\n with this product. If the product has a large number of associated images, this\n operation could take several minutes, or even hours.\n\n Returns\n -------\n DeletionTaskStatus\n Returns :py:class`DeletionTaskStatus` if deletion task was successfully started and ``None``\n if there were no related objects to delete.\n\n Raises\n ------\n ConflictError\n If a deletion process is already in progress.\n\n \"\"\"\n r = self._client.session.post(\n \"/products/{}/delete_related_objects\".format(self.id),\n json={\"data\": {\"type\": \"product_delete_task\"}},\n )\n if r.status_code == 201:\n response = r.json()\n return DeletionTaskStatus(\n id=self.id, _client=self._client, **response[\"data\"][\"attributes\"]\n )\n\n @check_deleted\n def get_delete_status(self):\n \"\"\"Fetches the status of a deletion task.\n\n Fetches the status of a deletion task started using\n :py:meth:`delete_related_objects`.\n\n Returns\n -------\n DeletionTaskStatus\n\n \"\"\"\n r = self._client.session.get(\n \"/products/{}/delete_related_objects\".format(self.id)\n )\n response = r.json()\n return DeletionTaskStatus(id=self.id, **response[\"data\"][\"attributes\"])\n\n @check_deleted\n def update_related_objects_permissions(\n self, owners=None, readers=None, writers=None, inherit=False\n ):\n \"\"\"Update the owners, readers, and/or writers for all related bands and images.\n\n Starts an asynchronous operation that updates the owners, readers, and/or\n writers of all bands and images associated with this product. If the product\n has a large number of associated images, this operation could take several\n minutes, or even hours.\n\n Parameters\n ----------\n owners : list(str)\n readers : list(str)\n writers : list(str)\n inherit: Whether to inherit the values from the product for owners, readers,\n and/or writers that have not been set in this request. By default, this\n value is ``False`` and if an ACL is not set, it is not changed.\n When set to ``True``, and the ACL is not set, it is inherited from the\n product.\n\n Returns\n -------\n UpdatePermissionsTaskStatus\n Returns :py:class`UpdatePermissionsTaskStatus` if update task was\n successfully started and ``None`` if there were no related objects\n to update.\n\n Raises\n ------\n ConflictError\n If an update task is already in progress.\n\n \"\"\"\n\n r = self._client.session.post(\n \"/products/{}/update_related_objects_acls\".format(self.id),\n json={\n \"data\": {\n \"type\": \"product_update_acls\",\n \"attributes\": {\n \"owners\": owners,\n \"readers\": readers,\n \"writers\": writers,\n \"inherit\": inherit,\n },\n }\n },\n )\n if r.status_code == 201:\n response = r.json()\n return UpdatePermissionsTaskStatus(\n id=self.id, _client=self._client, **response[\"data\"][\"attributes\"]\n )\n\n @check_deleted\n def get_update_permissions_status(self):\n \"\"\"Fetches the status of an update task.\n\n Fetches the status of an update task started using\n :py:meth:`update_related_objects_permissions`.\n\n Returns\n -------\n UpdatePermissionsTaskStatus\n\n Example\n -------\n >>> product = Product.get('product-id')\n >>> product.update_related_objects_permissions()\n >>> product.get_update_permissions_status()\n\n \"\"\"\n r = self._client.session.get(\n \"/products/{}/update_related_objects_acls\".format(self.id)\n )\n response = r.json()\n return UpdatePermissionsTaskStatus(\n id=self.id, _client=self._client, **response[\"data\"][\"attributes\"]\n )\n\n @check_deleted\n def bands(self):\n \"\"\"A search query for all bands for this product, sorted by default band\n ``sort_order``.\n\n Returns\n -------\n :py:class:`~descarteslabs.catalog.search.Search`\n A :py:class:`~descarteslabs.catalog.search.Search` instance configured to\n find all bands for this product.\n \"\"\"\n from .band import Band\n\n return (\n Band.search(client=self._client)\n .filter(properties.product_id == self.id)\n .sort(\"sort_order\")\n )\n\n @check_deleted\n def derived_bands(self):\n \"\"\"A search query for all derived bands associated with this product.\n\n Returns\n -------\n :py:class:`~descarteslabs.catalog.search.Search`\n A :py:class:`~descarteslabs.catalog.search.Search` instance configured to\n find all derived bands for this product.\n \"\"\"\n from .search import Search\n from .band import DerivedBand\n\n return Search(\n DerivedBand,\n url=\"{}/{}/relationships/{}\".format(self._url, self.id, \"derived_bands\"),\n client=self._client,\n includes=False,\n )\n\n @check_deleted\n def images(self):\n \"\"\"A search query for all images in this product.\n\n Returns\n -------\n :py:class:`~descarteslabs.catalog.search.Search`\n A :py:class:`~descarteslabs.catalog.search.Search` instance configured to\n find all images in this product.\n \"\"\"\n from .image import Image\n\n return Image.search(client=self._client).filter(\n properties.product_id == self.id\n )\n\n @check_deleted\n def image_uploads(self):\n \"\"\"A search query for all uploads in this product created by this user.\n\n Returns\n -------\n :py:class:`~descarteslabs.catalog.search.Search`\n A :py:class:`~descarteslabs.catalog.search.Search` instance configured to\n find all uploads in this product.\n \"\"\"\n from .image_upload import ImageUpload\n\n return ImageUpload.search(client=self._client).filter(\n properties.product_id == self.id\n )\n\n @classmethod\n def namespace_id(cls, id_, client=None):\n \"\"\"Generate a fully namespaced id.\n\n Parameters\n ----------\n id_ : str\n The unprefixed part of the id that you want prefixed.\n client : CatalogClient, optional\n A `CatalogClient` instance to use for requests to the Descartes Labs\n catalog. The\n :py:meth:`~descarteslabs.catalog.CatalogClient.get_default_client` will\n be used if not set.\n\n Returns\n -------\n str\n The fully namespaced id.\n\n Example\n -------\n >>> product_id = Product.namespace_id(\"my-product\")\n \"\"\"\n if client is None:\n client = CatalogClient.get_default_client()\n org = client.auth.payload.get(\"org\")\n if org is None:\n org = client.auth.namespace # defaults to the user namespace\n\n prefix = \"{}:\".format(org)\n if id_.startswith(prefix):\n return id_\n\n return \"{}{}\".format(prefix, id_)\n\n\nclass TaskState(Enum):\n \"\"\"\n Attributes\n ----------\n NEVERRAN : enum\n The operation was never invoked.\n RUNNING : enum\n The operation is in progress.\n SUCCEEDED : enum\n The operation was successfully completed.\n FAILED : enum\n The operation resulted in a failure and may not have been completed.\n \"\"\"\n\n NEVERRAN = \"NONE\" # The operation was never started\n RUNNING = \"RUNNING\"\n SUCCEEDED = \"SUCCESS\"\n FAILED = \"FAILURE\"\n\n\nclass TaskStatus(object):\n \"\"\"\n A base class for the status of asynchronous jobs.\n \"\"\"\n\n task_name = \"task\"\n _TERMINAL_STATES = [TaskState.SUCCEEDED, TaskState.FAILED]\n _POLLING_INTERVAL = 60\n\n def __init__(\n self,\n id=None,\n status=None,\n start_datetime=None,\n duration_in_seconds=None,\n errors=None,\n _client=None,\n **kwargs\n ):\n self.product_id = id\n self.start_datetime = start_datetime\n self.duration_in_seconds = duration_in_seconds\n self.errors = errors\n self._client = _client or CatalogClient.get_default_client()\n\n try:\n self.status = TaskState(status)\n except ValueError:\n pass\n\n def __repr__(self):\n status = self.status.value if self.status else \"UNKNOWN\"\n text = [\"{} {} status: {}\".format(self.product_id, self.task_name, status)]\n if self.start_datetime:\n text.append(\" - started: {}\".format(self.start_datetime))\n\n if self.duration_in_seconds:\n text.append(\" - took {:,.4f} seconds\".format(self.duration_in_seconds))\n\n if self.errors:\n text.append(\" - {} errors reported:\".format(len(self.errors)))\n for e in self.errors:\n text.append(\" - {}\".format(e))\n return \"\\n\".join(text)\n\n def reload(self):\n r = self._client.session.get(\n \"/products/{}/update_related_objects_acls\".format(self.product_id)\n )\n response = r.json()\n new_values = response[\"data\"][\"attributes\"]\n\n self.status = TaskState(new_values.pop(\"status\"))\n for (key, value) in new_values.items():\n setattr(self, key, value)\n\n def wait_for_completion(self, timeout=None):\n \"\"\"Wait for the task to complete.\n\n Parameters\n ----------\n timeout : int, optional\n If specified, will wait up to specified number of seconds and will raise\n a :py:exc:`concurrent.futures.TimeoutError` if the task has not completed.\n\n Raises\n ------\n :py:exc:`concurrent.futures.TimeoutError`\n If the specified timeout elapses and the task has not completed\n \"\"\"\n if self.status in self._TERMINAL_STATES:\n return\n\n if timeout:\n timeout = time.time() + timeout\n while True:\n self.reload()\n if self.status in self._TERMINAL_STATES:\n return\n if timeout:\n t = timeout - time.time()\n if t <= 0:\n raise TimeoutError()\n t = min(t, self._POLLING_INTERVAL)\n else:\n t = self._POLLING_INTERVAL\n time.sleep(t)\n\n\nclass DeletionTaskStatus(TaskStatus):\n \"\"\"The asynchronous deletion task's status\n\n Inheritance\n -----------\n For inherited parameters, methods, attributes, and properties, please refer to the\n base class:\n\n * :py:class:`TaskStatus`\n\n |\n\n Attributes\n ----------\n product_id : str\n The id of the product for which this task is running.\n status : TaskState\n The state of the task as explained in `TaskState`.\n start_datetime : datetime\n The date and time at which the task started running.\n duration_in_seconds : float\n The duration of the task.\n objects_deleted : int\n The number of object (a combination of bands or images) that were deleted.\n errors: list\n In case the status is ``FAILED`` this will contain a list of errors\n that were encountered. In all other states this will not be set.\n \"\"\"\n\n task_name = \"deletion task\"\n\n def __init__(self, objects_deleted=None, **kwargs):\n super(DeletionTaskStatus, self).__init__(**kwargs)\n self.objects_deleted = objects_deleted\n\n def __repr__(self):\n text = super(DeletionTaskStatus, self).__repr__()\n\n if self.objects_deleted:\n text += \"\\n - {:,} objects deleted\".format(self.objects_deleted)\n\n return text\n\n\nclass UpdatePermissionsTaskStatus(TaskStatus):\n \"\"\"The asynchronous task status for updating related objects' access control permissions\n\n Inheritance\n -----------\n For inherited parameters, methods, attributes, and properties, please refer to the\n base class:\n\n * :py:class:`TaskStatus`\n\n |\n\n Attributes\n ----------\n product_id : str\n The id of the product for which this task is running.\n status : TaskState\n The state of the task as explained in `TaskState`.\n start_datetime : datetime\n The date and time at which the task started running.\n duration_in_seconds : float\n The duration of the task.\n objects_updated : int\n The number of object (a combination of bands or images) that were updated.\n errors: list\n In case the status is ``FAILED`` this will contain a list of errors\n that were encountered. In all other states this will not be set.\n \"\"\"\n\n task_name = \"update permissions task\"\n\n def __init__(self, objects_updated=None, **kwargs):\n super(UpdatePermissionsTaskStatus, self).__init__(**kwargs)\n self.objects_updated = objects_updated\n\n def __repr__(self):\n text = super(UpdatePermissionsTaskStatus, self).__repr__()\n if self.objects_updated:\n text += \"\\n - {:,} objects updated\".format(self.objects_updated)\n return text\n","sub_path":"descarteslabs/catalog/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":16373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"238585491","text":"\"\"\"Produce batches of SVHN digits AND SVHN region test datasets.\n\nWrapping the SVHN digits and SVHN region dataset loaders, produce\nconsistent batches of data from both of the aforementioned loaders\nand bunch them up into a single returned batch. That is the batch\nproduced pertains to same images from both loaders.\n\nNOTE: This only wraps generating of combined dataset for test\ndata exclusively. It is also important to limit the number of\nthreads and buffer for the individual dataset loaders to 1 so\nthat batches do not get mixed up because of multi-threaded\nprocessing. \n\"\"\"\nimport sys\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\n\nfrom load_svhn_digits import SVHNDigits\nfrom load_svhn_region import SVHNRegion\n\nclass SVHNEval(object):\n \"\"\"Encapsulates SVHN combined eval dataset loader.\"\"\"\n def __init__(self, batch_size=32):\n \"\"\"Constructor for SVHNEval.\n \n Instantiate object with \n Batch size indicating number of images, labels and bounding boxes to be delivered per batch.\n \"\"\"\n self._region_obj = SVHNRegion('test', batch_size=batch_size, buffer_size=1, num_threads=1)\n self._digits_obj = SVHNDigits('test', batch_size=batch_size, buffer_size=1, num_threads=1)\n\n def next_batch(self):\n \"\"\"Get the combined next batch of data for eval.\"\"\"\n region_images, region_bboxes = self._region_obj.next_batch()\n digits_images, digits_labels = self._digits_obj.next_batch()\n\n return region_images, region_bboxes, digits_labels\n \n def get_dataset_size(self):\n \"\"\"Getter for dataset size.\"\"\"\n return self._region_obj.get_dataset_size()\n\ndef main():\n # Test if SVHNEval works properly.\n # Invoking script from command-line triggers the test.\n svhn_eval = SVHNEval(batch_size=2)\n\n for i in range(0, 32, 2):\n images, bboxes, labels = svhn_eval.next_batch()\n ax = plt.subplot(4,8,i+1)\n plt.imshow(images[0] + 0.5)\n plt.axis('off')\n plt.title(labels['string'][0])\n bbox_left, bbox_top, bbox_width, bbox_height = bboxes[0, 1], bboxes[0, 0], bboxes[0, 3], bboxes[0, 2]\n ax.add_patch(patches.Rectangle((bbox_left, bbox_top), bbox_width, bbox_height, fill=False))\n ax = plt.subplot(4,8,i+2)\n plt.imshow(images[1] + 0.5)\n plt.axis('off')\n plt.title(labels['string'][1])\n bbox_left, bbox_top, bbox_width, bbox_height = bboxes[1, 1], bboxes[1, 0], bboxes[1, 3], bboxes[1, 2]\n ax.add_patch(patches.Rectangle((bbox_left, bbox_top), bbox_width, bbox_height, fill=False))\n\n plt.show()\n\nif __name__ == '__main__':\n import sys\n sys.exit(int(main() or 0))","sub_path":"dataset/load_svhn_eval.py","file_name":"load_svhn_eval.py","file_ext":"py","file_size_in_byte":2681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"258688956","text":"import cx_Oracle\n\nconnection_string = 'eldar/eldar@192.168.1.12/orcl'\nuser = 'eldar'\npas = 'eldar'\ntns = cx_Oracle.makedsn('192.168.1.12','1521','orcl')\n#print(tns)\n\nsql_str = '''select t1.data , t2.data\nfrom t1,t2\nwhere t1.id = t2.id'''\n\nv_from = sql_str.find('from')\nv_where = sql_str.find('where')\n\nstr_select = sql_str[7:v_from]\nstr_from = sql_str[v_from+5:v_where]\nstr_where = sql_str[v_where+6:]\n\n\nmapping_dict = {}\n\nfor tables in str_from.strip().split(','):\n mapping_dict.setdefault(tables,[])\n\nfor columns in str_select.split(','):\n k,v = columns.strip().split('.')\n #d.setdefault(k,[v\n mapping_dict[k].append(v)\n\nfor wheres in str_where.split('='):\n k,v = wheres.strip().split('.')\n mapping_dict[k].append(v)\n\nprint(mapping_dict)\n#mapping_dict = dict(zip( [str_from],[] ) )\n\n## need to be done:\n## modify sql_string by concatinating additional columns to select clause\n#new_sql =\n#then pass it ot oracle cursor\nprint(\"select %s form %s where %s \" % (str_select,str_from,str_where) )\n##\n\nconnection = cx_Oracle.connect(connection_string)\n#connection = cx_Oracle.connect(user,pas,tns)\ncursor = connection.cursor()\n#print(connection.version)\ncursor.execute(sql_str)\nfor a in cursor:\n print(a[0],a[1])\n\nheader = [i[0] for i in cursor.description]\nprint(header)\n\ncursor.close()\nconnection.close()\n","sub_path":"draft.py","file_name":"draft.py","file_ext":"py","file_size_in_byte":1329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"455111733","text":"\"\"\"The Fast Gradient Method attack.\"\"\"\nimport numpy as np\nimport torch\n\n\ndef optimize_linear(grad, eps, norm=np.inf):\n \"\"\"\n Solves for the optimal input to a linear function under a norm constraint.\n Optimal_perturbation = argmax_{eta, ||eta||_{norm} < eps} dot(eta, grad)\n :param grad: Tensor, shape (N, d_1, ...). Batch of gradients\n :param eps: float. Scalar specifying size of constraint region\n :param norm: np.inf, 1, or 2. Order of norm constraint.\n :returns: Tensor, shape (N, d_1, ...). Optimal perturbation\n \"\"\"\n\n red_ind = list(range(1, len(grad.size())))\n avoid_zero_div = torch.tensor(1e-12, dtype=grad.dtype, device=grad.device)\n if norm == np.inf:\n # Take sign of gradient\n optimal_perturbation = torch.sign(grad)\n elif norm == 1:\n abs_grad = torch.abs(grad)\n sign = torch.sign(grad)\n red_ind = list(range(1, len(grad.size())))\n abs_grad = torch.abs(grad)\n ori_shape = [1]*len(grad.size())\n ori_shape[0] = grad.size(0)\n\n max_abs_grad, _ = torch.max(abs_grad.view(grad.size(0), -1), 1)\n max_mask = abs_grad.eq(max_abs_grad.view(ori_shape)).to(torch.float)\n num_ties = max_mask\n for red_scalar in red_ind:\n num_ties = torch.sum(num_ties, red_scalar, keepdim=True)\n optimal_perturbation = sign * max_mask / num_ties\n # TODO integrate below to a test file\n # check that the optimal perturbations have been correctly computed\n opt_pert_norm = optimal_perturbation.abs().sum(dim=red_ind)\n assert torch.all(opt_pert_norm == torch.ones_like(opt_pert_norm))\n elif norm == 2:\n square = torch.max(\n avoid_zero_div,\n torch.sum(grad ** 2, red_ind, keepdim=True)\n )\n optimal_perturbation = grad / torch.sqrt(square)\n # TODO integrate below to a test file\n # check that the optimal perturbations have been correctly computed\n opt_pert_norm = optimal_perturbation.pow(\n 2).sum(dim=red_ind, keepdim=True).sqrt()\n one_mask = (\n (square <= avoid_zero_div).to(torch.float) * opt_pert_norm +\n (square > avoid_zero_div).to(torch.float))\n assert torch.allclose(opt_pert_norm, one_mask, rtol=1e-05, atol=1e-08)\n else:\n raise NotImplementedError(\"Only L-inf, L1 and L2 norms are \"\n \"currently implemented.\")\n\n # Scale perturbation to be the solution for the norm=eps rather than\n # norm=1 problem\n scaled_perturbation = eps * optimal_perturbation\n return scaled_perturbation\n\n\ndef clip_eta(eta, norm, eps):\n \"\"\"\n PyTorch implementation of the clip_eta in utils_tf.\n :param eta: Tensor\n :param norm: np.inf, 1, or 2\n :param eps: float\n \"\"\"\n if norm not in [np.inf, 1, 2]:\n raise ValueError('norm must be np.inf, 1, or 2.')\n\n avoid_zero_div = torch.tensor(1e-12, dtype=eta.dtype, device=eta.device)\n reduc_ind = list(range(1, len(eta.size())))\n if norm == np.inf:\n eta = torch.clamp(eta, -eps, eps)\n else:\n if norm == 1:\n raise NotImplementedError(\"L1 clip is not implemented.\")\n norm = torch.max(\n avoid_zero_div,\n torch.sum(torch.abs(eta), dim=reduc_ind, keepdim=True)\n )\n elif norm == 2:\n norm = torch.sqrt(torch.max(\n avoid_zero_div,\n torch.sum(eta ** 2, dim=reduc_ind, keepdim=True)\n ))\n factor = torch.min(\n torch.tensor(1., dtype=eta.dtype, device=eta.device),\n eps / norm\n )\n eta *= factor\n return eta\n\n\ndef fast_gradient_method(model_fn, x, eps, norm,\n clip_min=None, clip_max=None, y=None,\n targeted=False, sanity_checks=False,\n model_loss=False):\n \"\"\"\n PyTorch implementation of the Fast Gradient Method.\n :param model_fn: a callable that takes an input tensor and returns the model logits.\n :param x: input tensor.\n :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572.\n :param norm: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2.\n :param clip_min: (optional) float. Minimum float value for adversarial example components.\n :param clip_max: (optional) float. Maximum float value for adversarial example components.\n :param y: (optional) Tensor with true labels. If targeted is true, then provide the\n target label. Otherwise, only provide this parameter if you'd like to use true\n labels when crafting adversarial samples. Otherwise, model predictions are used\n as labels to avoid the \"label leaking\" effect (explained in this paper:\n https://arxiv.org/abs/1611.01236). Default is None.\n :param targeted: (optional) bool. Is the attack targeted or untargeted?\n Untargeted, the default, will try to make the label incorrect.\n Targeted will instead try to move in the direction of being more like y.\n :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime /\n memory or for unit tests that intentionally pass strange input)\n :return: a tensor for the adversarial example\n \"\"\"\n if norm not in [np.inf, 1, 2]:\n raise ValueError(\n \"Norm order must be either np.inf, 1, or 2, got {} instead.\".format(norm))\n if eps < 0:\n raise ValueError(\n \"eps must be greater than or equal to 0, got {} instead\".format(eps))\n if eps == 0:\n return x\n if clip_min is not None and clip_max is not None:\n if clip_min > clip_max:\n raise ValueError(\n \"clip_min must be less than or equal to clip_max, got clip_min={} and clip_max={}\".format(\n clip_min, clip_max))\n\n asserts = []\n\n # If a data range was specified, check that the input was in that range\n if clip_min is not None:\n assert_ge = torch.all(torch.ge(x, torch.tensor(\n clip_min, device=x.device, dtype=x.dtype)))\n asserts.append(assert_ge)\n\n if clip_max is not None:\n assert_le = torch.all(torch.le(x, torch.tensor(\n clip_max, device=x.device, dtype=x.dtype)))\n asserts.append(assert_le)\n\n # x needs to be a leaf variable, of floating point type and have requires_grad being True for\n # its grad to be computed and stored properly in a backward call\n x = x.clone().detach().to(torch.float).requires_grad_(True)\n if y is None:\n # Using model predictions as ground truth to avoid label leaking\n _, y = torch.max(model_fn(x), 1)\n\n # Compute loss\n loss_fn = model_fn.loss if model_loss else torch.nn.CrossEntropyLoss()\n loss = loss_fn(model_fn(x), y)\n\n # If attack is targeted, minimize loss of target label rather than maximize loss of correct label\n if targeted:\n loss = -loss\n\n # Define gradient of loss wrt input\n loss.backward()\n optimal_perturbation = optimize_linear(x.grad, eps, norm)\n\n # Add perturbation to original example to obtain adversarial example\n adv_x = x + optimal_perturbation\n\n # If clipping is needed, reset all values outside of [clip_min, clip_max]\n if (clip_min is not None) or (clip_max is not None):\n if clip_min is None or clip_max is None:\n raise ValueError(\n \"One of clip_min and clip_max is None but we don't currently support one-sided clipping\")\n adv_x = torch.clamp(adv_x, clip_min, clip_max)\n\n if sanity_checks:\n assert np.all(asserts)\n return adv_x\n\n\ndef projected_gradient_descent(model_fn, x, eps, eps_iter, nb_iter, norm,\n clip_min=None, clip_max=None, y=None, targeted=False,\n rand_init=True, rand_minmax=None,\n sanity_checks=True,\n model_loss=False):\n \"\"\"\n This class implements either the Basic Iterative Method\n (Kurakin et al. 2016) when rand_init is set to False. or the\n Madry et al. (2017) method if rand_init is set to True.\n Paper link (Kurakin et al. 2016): https://arxiv.org/pdf/1607.02533.pdf\n Paper link (Madry et al. 2017): https://arxiv.org/pdf/1706.06083.pdf\n :param model_fn: a callable that takes an input tensor and returns the model logits.\n :param x: input tensor.\n :param eps: epsilon (input variation parameter); see https://arxiv.org/abs/1412.6572.\n :param eps_iter: step size for each attack iteration\n :param nb_iter: Number of attack iterations.\n :param norm: Order of the norm (mimics NumPy). Possible values: np.inf, 1 or 2.\n :param clip_min: (optional) float. Minimum float value for adversarial example components.\n :param clip_max: (optional) float. Maximum float value for adversarial example components.\n :param y: (optional) Tensor with true labels. If targeted is true, then provide the\n target label. Otherwise, only provide this parameter if you'd like to use true\n labels when crafting adversarial samples. Otherwise, model predictions are used\n as labels to avoid the \"label leaking\" effect (explained in this paper:\n https://arxiv.org/abs/1611.01236). Default is None.\n :param targeted: (optional) bool. Is the attack targeted or untargeted?\n Untargeted, the default, will try to make the label incorrect.\n Targeted will instead try to move in the direction of being more like y.\n :param rand_init: (optional) bool. Whether to start the attack from a randomly perturbed x.\n :param rand_minmax: (optional) bool. Support of the continuous uniform distribution from\n which the random perturbation on x was drawn. Effective only when rand_init is\n True. Default equals to eps.\n :param sanity_checks: bool, if True, include asserts (Turn them off to use less runtime /\n memory or for unit tests that intentionally pass strange input)\n :return: a tensor for the adversarial example\n \"\"\"\n if norm == 1:\n raise NotImplementedError(\"It's not clear that FGM is a good inner loop\"\n \" step for PGD when norm=1, because norm=1 FGM \"\n \" changes only one pixel at a time. We need \"\n \" to rigorously test a strong norm=1 PGD \"\n \"before enabling this feature.\")\n if norm not in [np.inf, 2]:\n raise ValueError(\"Norm order must be either np.inf or 2.\")\n if eps < 0:\n raise ValueError(\n \"eps must be greater than or equal to 0, got {} instead\".format(eps))\n if eps == 0:\n return x\n if eps_iter < 0:\n raise ValueError(\n \"eps_iter must be greater than or equal to 0, got {} instead\".format(eps_iter))\n if eps_iter == 0:\n return x\n\n assert eps_iter <= eps, (eps_iter, eps)\n if clip_min is not None and clip_max is not None:\n if clip_min > clip_max:\n raise ValueError(\n \"clip_min must be less than or equal to clip_max, got clip_min={} and clip_max={}\".format(\n clip_min, clip_max))\n\n asserts = []\n\n # If a data range was specified, check that the input was in that range\n if clip_min is not None:\n assert_ge = torch.all(torch.ge(x, torch.tensor(\n clip_min, device=x.device, dtype=x.dtype)))\n asserts.append(assert_ge)\n\n if clip_max is not None:\n assert_le = torch.all(torch.le(x, torch.tensor(\n clip_max, device=x.device, dtype=x.dtype)))\n asserts.append(assert_le)\n\n # Initialize loop variables\n if rand_init:\n if rand_minmax is None:\n rand_minmax = eps\n eta = torch.zeros_like(x).uniform_(-rand_minmax, rand_minmax)\n else:\n eta = torch.zeros_like(x)\n\n # Clip eta\n eta = clip_eta(eta, norm, eps)\n adv_x = x + eta\n if clip_min is not None or clip_max is not None:\n adv_x = torch.clamp(adv_x, clip_min, clip_max)\n\n if y is None:\n # Using model predictions as ground truth to avoid label leaking\n _, y = torch.max(model_fn(x), 1)\n\n i = 0\n while i < nb_iter:\n adv_x = fast_gradient_method(model_fn, adv_x, eps_iter, norm,\n clip_min=clip_min, clip_max=clip_max, y=y,\n targeted=targeted, model_loss=model_loss)\n\n # Clipping perturbation eta to norm norm ball\n eta = adv_x - x\n eta = clip_eta(eta, norm, eps)\n adv_x = x + eta\n\n # Redo the clipping.\n # FGM already did it, but subtracting and re-adding eta can add some\n # small numerical error.\n if clip_min is not None or clip_max is not None:\n adv_x = torch.clamp(adv_x, clip_min, clip_max)\n i += 1\n\n asserts.append(eps_iter <= eps)\n if norm == np.inf and clip_min is not None:\n # TODO necessary to cast clip_min and clip_max to x.dtype?\n asserts.append(eps + clip_min <= clip_max)\n\n if sanity_checks:\n assert np.all(asserts)\n return adv_x\n","sub_path":"adv/pgd_clever.py","file_name":"pgd_clever.py","file_ext":"py","file_size_in_byte":13211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"312194823","text":"#!/usr/bin/env python\n\nimport sys\nimport math\nfrom gsp import GSP\nfrom util import argmax_index\n\nfrom mewtbb import MewtBB\n\nclass MewtBudget(MewtBB):\n \"\"\"Balanced bidding agent\"\"\"\n\n def __init__(self, id, value, budget):\n self.id = id\n self.value = value\n self.budget = budget\n self.past_clicks = 0\n self.exp_ct1 = []\n\n n_periods = 48\n for i in range(n_periods):\n self.exp_ct1.append(round(30 * math.cos(math.pi * i / 24) + 50))\n \n def initial_bid(self, reserve):\n return self.value\n\n def expected_utils(self, t, history, reserve):\n \"\"\"\n Figure out the expected utility of bidding such that we win each\n slot, assuming that everyone else keeps their bids constant from\n the previous round.\n\n returns a list of utilities per slot.\n \"\"\"\n prev_round = history.round(t - 1)\n m = len(prev_round.clicks)\n utilities = []\n\n for i in range(m):\n t_j = self.paymentGivenOtherBids(t, prev_round, i)\n if (t_j < reserve):\n t_j = reserve\n #if (t_j >= target_budget):\n # utilities.append(float(\"-inf\"))\n utilities.append(prev_round.clicks[i] * (self.value - t_j))\n\n return utilities\n\n def target_slot(self, t, target_budget, history, reserve):\n \"\"\"Figure out the best slot to target, assuming that everyone else\n keeps their bids constant from the previous rounds.\n\n Returns (slot_id, min_bid, max_bid), where min_bid is the bid needed to tie\n the other-agent bid for that slot in the last round. If slot_id = 0,\n max_bid is min_bid * 2\n \"\"\"\n utilities = self.expected_utils(t, history, reserve)\n prev_round = history.round(t-1)\n sorted_index = sorted(range(len(utilities)),\n key=lambda k: self.paymentGivenOtherBids(t, prev_round, k) * prev_round.clicks[k], reverse=True)\n index_list = [k for k, idx in enumerate(sorted_index) if self.paymentGivenOtherBids(t, prev_round, idx) * prev_round.clicks[k] < target_budget]\n if (len(index_list) > 0):\n i = index_list[0]\n else:\n i = sorted_index[len(sorted_index)-1]\n info = self.slot_info(t, history, reserve)\n return info[i]\n\n def calc_relative_budget_factor(self, history):\n average_others_spent = float(sum(history.agents_spent) - history.agents_spent[self.id]) / (\n len(history.agents_spent) - 1)\n if (average_others_spent < 1 or history.agents_spent[self.id] < 1):\n return 1.0\n return float(average_others_spent / history.agents_spent[self.id])\n\n def calc_relative_ct_factor(self, t, prev_round):\n average_clicks_past = float(self.past_clicks) / t\n if (average_clicks_past < 1):\n return 1.0\n return sum(prev_round.clicks) / average_clicks_past\n\n def calc_baseline_budget(self, t, remaining_budget):\n t0 = t % len(self.exp_ct1)\n exp_total_ct1 = sum(self.exp_ct1[t0:len(self.exp_ct1)-1])\n if (exp_total_ct1 < 1):\n return remaining_budget\n return round(float(remaining_budget * self.exp_ct1[t0] / exp_total_ct1))\n\n def calc_target_budget(self, baseline_budget, relative_budget_factor, relative_ct_factor):\n target_budget = baseline_budget * relative_budget_factor * relative_ct_factor * 0.2\n return target_budget\n\n def bid(self, t, history, reserve):\n # The Balanced bidding strategy (BB) is the strategy for a player j that, given\n # bids b_{-j},\n # - targets the slot s*_j which maximizes his utility, that is,\n # s*_j = argmax_s {clicks_s (v_j - t_s(j))}.\n # - chooses his bid b' for the next round so as to\n # satisfy the following equation:\n # clicks_{s*_j} (v_j - t_{s*_j}(j)) = clicks_{s*_j-1}(v_j - b')\n # (p_x is the price/click in slot x)\n # If s*_j is the top slot, bid the value v_j\n\n if (t == 0):\n return self.initial_bid()\n\n prev_round = history.round(t - 1)\n m = len(prev_round.clicks)\n\n self.past_clicks += sum(prev_round.clicks)\n remaining_budget = self.budget - history.agents_spent[self.id]\n base_budget = self.calc_baseline_budget(t, remaining_budget)\n b_factor = self.calc_relative_budget_factor(history)\n ct_factor = self.calc_relative_ct_factor(t, prev_round)\n target_budget = self.calc_target_budget(base_budget, b_factor, ct_factor)\n\n (slot, min_bid, max_bid) = self.target_slot(t, target_budget, history, reserve)\n\n target_payment = self.paymentGivenOtherBids(t, prev_round, slot)\n if target_payment < reserve:\n target_payment = reserve\n\n if target_payment > self.value:\n bid = self.value\n elif slot == 0:\n bid = self.value\n else:\n target_ctr = prev_round.clicks[slot]\n previous_ctr = prev_round.clicks[slot - 1]\n bid = - float(target_ctr * (self.value - target_payment)) / (previous_ctr) + self.value\n\n if bid > target_budget:\n return target_budget\n else:\n return bid\n\n def __repr__(self):\n return \"%s(id=%d, value=%d)\" % (\n self.__class__.__name__, self.id, self.value)\n","sub_path":"Internet Auction Agents/bs/pset7/mewtbudget.py","file_name":"mewtbudget.py","file_ext":"py","file_size_in_byte":5354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"277517253","text":"in_file = '/home/tharun/Desktop/input.txt'\nout_file = '/home/tharun/Desktop/output.txt'\ntarget = open(out_file, 'w')\nwith open(in_file, \"r\") as f:\n content = f.read().splitlines()\n tc = int(content[0])\n sleep = '1111111111'\n for i in xrange(1,tc+1):\n valst = content[i]\n val = int(valst)\n current = bytearray('0000000000')\n k = 1\n if valst == '0':\n line = 'Case #%d: INSOMNIA' % i\n target.write(line)\n target.write(\"\\n\")\n continue\n while k > 0:\n num = k * val\n # print k,val,num\n numst = str(num)\n length = len(numst)\n for j in xrange(0,length):\n index = int(numst[j])\n current[index] = '1'\n if current == sleep:\n line = 'Case #%d: %d' % (i,num)\n target.write(line)\n target.write(\"\\n\")\n break\n k = k + 1\n\n","sub_path":"codes/CodeJamCrawler/16_0_1/tharun/gcj1x.py","file_name":"gcj1x.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"516667145","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom collections import defaultdict\nimport re\nfrom itertools import zip_longest\n\nurl2 = 'https://multiplex.ua/cinema/kyiv/lavina'\n\n\ndef get_html(url2):\n # we get html using the URL address\n r = requests.get(url2)\n response = r.text\n return response\n\n\ndef parse_name(html):\n # display a list of movies using the library BeautifulSoup\n soup = BeautifulSoup(html, 'lxml')\n table = soup.find('div', class_='cinema_inside sch_date')\n projects = []\n rows = table.find_all('a')\n\n for i, j in enumerate(rows):\n if i%2 != 0:\n projects.append(j)\n\n #create a list in which we will use the iteration to add the names of the films\n info = []\n for row in projects:\n info.append([row.text])\n\n for i in range(len(info)):\n info[i] = info[i][0]\n return \"\\n\".join(info)\n\n\n\ndef parse_time(html):\n # create two lists in which there will be sessions and movie titles to them using the library BeautifulSoup\n soup = BeautifulSoup(html, 'lxml')\n table = soup.find('div', class_= 'cinema_inside sch_date')\n table1 = table.find_all(class_= 'ns')\n\n # with the help of iteration we add the time of sessions to the list\n list_time = []\n for i in table1:\n time = i.text\n t = time.replace('\\n', '')\n list_time.append(t)\n\n #by iteration create a list with the name of the movie\n proj_list_name = []\n for i in table1:\n proj_list_name.append(i)\n\n name_time = []\n for i in table1:\n st = str(i)\n name_time.append(st)\n\n list_name = []\n for i in name_time:\n s = i.split('data-name=\"')\n r = s[1].split('\"')\n m = r[0]\n list_name.append(m)\n return list_name, list_time\n\n\na, b = parse_time(get_html('https://multiplex.ua/cinema/kyiv/lavina'))\n\ndef get_dict(a, b):\n items = []\n for item in zip_longest(a, b):\n items.append(item)\n #create a dictionary in which the name of the movie will be the key, and the value will be a list of sessions\n sessions_film = defaultdict(list)\n for key, value in items:\n sessions_film[key].append(value)\n sessions_film1 = []\n for key in sessions_film:\n film = key + ': ' + \" \".join(sessions_film[key])\n\n sessions_film1.append(film)\n lst = '\\n'.join(sessions_film1)\n return lst\n\n\n\n\n\n","sub_path":"v.oksiutenko/BOT/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"537112138","text":"# if example\n\n# name = 'Alice'\n# if name == 'Alice':\n# print(\"Hello Alice\")\n# print('Done')\n\n# it will check for cond and if its true it will exe all blocks\n# remember blocks\n\n# age = 22\n# if age == 21:\n# print(\"21\")\n# print(\"done\")\n\n\n# if else\n\n# password = 'swordfish'\n# if password == 'swordfish':\n# print(\"Access granted\")\n# else:\n# print('wrong Password')\n\n\n# password = 'bob'\n# if password == 'swordfish':\n# print(\"Access granted\")\n# else:\n# print('wrong Password')\n\n\n# if else example\n\nname = 'bob'\nage = 3000\nif name == 'Alice': # this is falso so its skipped\n print('hii alice')\nelif age < 12:\n print('you are not alice kiddo')\nelif age > 2000:\n print(\"vampire\")\nelif age > 100:\n print('grannie')\n\n# order of block doesnot matter, it only checks first true block\n","sub_path":"control-statements.py","file_name":"control-statements.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"589666188","text":"import pymongo\nfrom pymongo import MongoClient\nfrom bson.objectid import ObjectId\nfrom flask import render_template, Flask, request, redirect, send_from_directory\n\napp = Flask(__name__, static_url_path='') # 최하단에 __name__ == '__main__': // URL어떤것이 들어갈지 /static/\nclient = MongoClient()\n\ndb = client.blog #블로그라는 데이터베이스를 갖고옴\ncollection = db.sanghyeon #상현이라는 시트하나 가져온거임(컬렉션) #db아무거나 해도됨\n\n@app.route('/') # 순전히 플라스크 문법 -> 파이썬의 플라스크 모듈이 웹서버로부터 / 를 달라고 요청함 #('/') -> 데코레이터\ndef home():\n posts = collection.find().skip(0).limit(20)\n return render_template('main.html', posts=posts) #render_template함수에 들어가면 돌아가면서 rendering됨 #html을 읽어서 템플릿엔진을 돌림 #main.html의 post를 돌림\n\n@app.route('/add', methods=['POST', 'GET']) #POST: 데이터를 쓰는것, GET: 데이터를 가져오는것\ndef add():\n if request.method == 'POST':\n collection.save({\n \"title\": request.form[\"title\"],\n \"content\": request.form[\"content\"]\n })\n return redirect('/') # 브라우저 --post/add(if부분 실행)--> 서버 | 브라우저 <--redirect/-- 서버 | 브라우저 --GET/--> 서버 | 브라우저 <---- 서버\n else: # GET 파트임\n return render_template('add.html') #아니면 add.html을 실행해라\n\n@app.route('/update', methods=['POST', 'GET'])\ndef update():\n if request.method == 'POST':\n collection.save({\n \"_id\": ObjectId(request.form[\"_id\"]),\n \"title\": request.form[\"title\"],\n \"content\": request.form[\"content\"]\n })\n return redirect('/')\n else: # GET 파트임\n _id = request.args.get('_id', '')\n # if(_id is ''): --> 우리는 뺄거임\n # return render_template('error.html')\n p = collection.find_one({\"_id\": ObjectId(_id)})\n return render_template('detail.html', post=p) # jinja2에 넘겨줄때 render_template으로 알려준거임\n\n@app.route('/delete/<_id>', methods=['POST', 'GET']) # 삭제버튼은 GET으로 하지 않음\ndef delete(_id):\n if request.method == 'POST':\n collection.remove({\"_id\": ObjectId(_id)})\n return redirect('/')\n else: # GET\n p = collection.find_one({\"_id\": ObjectId(_id)}) #_id = request.args.get('_id', '') 이거 위에서 해서 필요없음\n return render_template('delete-check.html', post=p)\n\n@app.route('/static/')\ndef static_file(filename):\n return send_from_directory('static', filename)\n\nif __name__ == '__main__':\n app.run(debug=True) #app.run(debug=True)하면 오류나면 어떤 오류인지 알려줌\n","sub_path":"blog/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"444255231","text":"import gevent # 协程库\nimport time\n\n# 只要协程第一步就要请猴子\nfrom gevent import monkey\n\n# 打补丁\nmonkey.patch_all() # 会把当前程序中所有的耗时全转换成我们gevent中的耗时\n\n\n# 一边唱歌,一边跳舞\n\ndef read():\n\twhile True:\n\t\tprint(\"读取\")\n\t\ttime.sleep(1) # 系统的自动转换成我们gevent.sleep(1)\n\n\ndef copy():\n\twhile True:\n\t\tprint(\"复制\")\n\t\t# gevent.sleep(1)\n\t\ttime.sleep(1)\n\n\ndef main():\n\t\"\"\"使用协程去运行我们跳舞与唱歌\"\"\"\n\t# gevent.spawn # 我们循环一次用一个协程\n\n\t# 定义一个列表\n\tspawn_list = list()\n\n\tspawn = gevent.spawn(copy)\n\tspawn_list.append(spawn)\n\n\tread_spawn = gevent.spawn(read)\n\tspawn_list.append(read_spawn)\n\n\t# 等一下\n\tgevent.joinall(spawn_list)\n\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"系统编程/协程/05_使用monkey.py","file_name":"05_使用monkey.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"623938081","text":"import struct\n\n# noinspection SpellCheckingInspection\nclass SerializationOne:\n\n def description(self):\n return \"\"\"\n Este es el primer ejercicio, es bastante fácil.\n El objetivo es entender como mandar un string de longitud variable desde C.\n Para eso, mandame el valor de ejecutar uname -rm en una terminal de linux.\n Primero, tenes que enviar el protocolo que mandaste para conseguir la informacion\n pero cambiando el campo preguntaORequesta y despues seteando bytesSolucion\n a la longitud del string a enviar + 1 (por el \\0).\n Despues, envias otro send con el string.\n \"\"\"\n\n def validate(self, data):\n uname_value = str(data, encoding='utf-8')\n correct = \"4.4.5-1-ARCH x86_64\"\n if uname_value.strip() == correct:\n return 1, \"Excelente!! Tu respuesta es correcta.\"\n return 0, \"Mmmm, no, lo siento, tu respuesta esta mal =(, tu respuseta fue: \" + uname_value\n\n\nclass SerializationTwo:\n\n def description(self):\n return \"\"\"\n En este ejercicio es parecido, pero ahora tenes que envíar un struct en vez de un string.\n Envia la siguiente estructura con los valores 4, 8 y 10.\n\n typedef struct {\n \tint32_t valor1;\n \tint32_t valor2;\n \tint32_t valor3;\n } StructEjercicio2;\n\n \"\"\"\n\n def validate(self, data):\n ex_format = \"3i\"\n expected_size = struct.calcsize(ex_format)\n if len(data) != expected_size:\n return 0, \"Mandaste una cantidad incorrecta de bytes,\\\n deberian ser {expected} pero llegaron {real}\".format(expected=expected_size, real=len(data))\n\n (valor1, valor2, valor3) = valores = struct.unpack(ex_format, data)\n if valor1 == 4 and valor2 == 8 and valor3 == 10:\n return 1, \"Excelente, los valores llegaron bien!\"\n\n return 0, \"Mmm algun valor llego mal, me mandaste valor1={valor1},\\\n valor2={valor2} y valor3={valor3}\".format(valor1=valor1, valor2=valor2, valor3=valor3)\n\n\nclass SerializationThree:\n\n def description(self):\n return \"\"\"\n El objetivo de este ejercicio es enviar un archivo copmleto. En este caso es el que esta en el directorio\n\n \"archivos/loremipsum.txt\"\n\n Para que sea más facil, el archivo es de texto plano.\n \"\"\"\n\n def validate(self, data):\n received_data = str(data, encoding='utf-8')\n with open(\"../resuelto/archivos/loremipsum.txt\", \"r\") as file:\n content = file.read()\n if content.strip() == received_data.strip():\n return 1, \"Excelente, el archivo llego bien\"\n return 0, \"El contenido del archivo llego diferente\"\n","sub_path":"server/exercises/serialization.py","file_name":"serialization.py","file_ext":"py","file_size_in_byte":2711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"269570942","text":"from sqlalchemy.orm import joinedload, joinedload_all\n\nfrom clld.db.models.common import (\n ValueSet, Parameter, Language, Contribution, ValueSetReference,\n)\nfrom clld.web.datatables.base import (\n DataTable, Col, LinkCol, DetailsRowLinkCol, LinkToMapCol, LanguageCol,\n)\nfrom clld.web.util.helpers import linked_references\n\n\nclass ParameterCol(LinkCol):\n def get_obj(self, item):\n return item.parameter\n\n\nclass _LinkToMapCol(LinkToMapCol):\n def get_obj(self, item):\n return item.language\n\n\nclass RefsCol(Col):\n def format(self, item):\n return linked_references(self.dt.req, item)\n\n\nclass Valuesets(DataTable):\n\n def __init__(self,\n req,\n model,\n parameter=None,\n contribution=None,\n language=None,\n search='col',\n **kw):\n self.search = search\n\n for attr, _model in [\n ('parameter', Parameter),\n ('contribution', Contribution),\n ('language', Language),\n ]:\n if locals()[attr]:\n setattr(self, attr, locals()[attr])\n elif attr in req.params:\n setattr(self, attr, _model.get(req.params[attr]))\n else:\n setattr(self, attr, None)\n\n DataTable.__init__(self, req, model, **kw)\n\n def base_query(self, query):\n query = query.join(Language)\\\n .options(\n joinedload(ValueSet.language),\n joinedload_all(ValueSet.references, ValueSetReference.source))\n\n if self.language:\n query = query.join(Parameter).options(joinedload(ValueSet.parameter))\n return query.filter(ValueSet.language_pk == self.language.pk)\n\n if self.parameter:\n return query.filter(ValueSet.parameter_pk == self.parameter.pk)\n\n if self.contribution:\n query = query.join(Parameter)\n return query.filter(ValueSet.contribution_pk == self.contribution.pk)\n\n return query\n\n def col_defs(self):\n #\n # TODO: move the first col def to apics-specific table!\n #\n #name_col = ValueNameCol(self, 'value')\n #if self.parameter and self.parameter.domain:\n # name_col.choices = [de.name for de in self.parameter.domain]\n\n refs_col = RefsCol(self, 'references', bSearchable=False, bSortable=False)\n\n res = [DetailsRowLinkCol(self)]\n\n if self.parameter:\n return res + [\n LanguageCol(self, 'language', model_col=Language.name),\n #name_col,\n refs_col,\n _LinkToMapCol(self),\n ]\n\n if self.language:\n return res + [\n #name_col,\n ParameterCol(self, 'parameter', model_col=Parameter.name),\n refs_col,\n #\n # TODO: refs?\n #\n ]\n\n return res + [\n LanguageCol(self, 'language', model_col=Language.name),\n #name_col,\n ParameterCol(self, 'parameter', model_col=Parameter.name),\n refs_col,\n #\n # TODO: contribution col?\n #\n ]\n\n def toolbar(self):\n return ''\n\n def get_options(self):\n opts = DataTable.get_options(self)\n #opts[\"aaSorting\"] = [[1, \"asc\"]]\n\n #opts['bLengthChange'] = False\n #opts['bPaginate'] = False\n #opts['bInfo'] = False\n\n for attr in ['parameter', 'contribution', 'language']:\n if getattr(self, attr):\n opts['sAjaxSource'] = self.req.route_url(\n 'values', _query={attr: getattr(self, attr).id})\n\n return opts\n","sub_path":"clld/web/datatables/valueset.py","file_name":"valueset.py","file_ext":"py","file_size_in_byte":3739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"650090013","text":"import logging\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\nfrom typing import TYPE_CHECKING, Any, Optional\n\nfrom rotkehlchen.accounting.mixins.event import AccountingEventMixin, AccountingEventType\nfrom rotkehlchen.accounting.structures.base import ActionType\nfrom rotkehlchen.assets.asset import Asset\nfrom rotkehlchen.history.deserialization import deserialize_price\nfrom rotkehlchen.logging import RotkehlchenLogsAdapter\nfrom rotkehlchen.serialization.deserialize import (\n deserialize_asset_amount,\n deserialize_optional,\n deserialize_timestamp,\n)\nfrom rotkehlchen.types import AssetAmount, Location, Price, Timestamp\nfrom rotkehlchen.utils.mixins.enums import DBCharEnumMixIn\n\nif TYPE_CHECKING:\n from rotkehlchen.accounting.pot import AccountingPot\n\nlogger = logging.getLogger(__name__)\nlog = RotkehlchenLogsAdapter(logger)\n\n\nclass LedgerActionType(DBCharEnumMixIn):\n INCOME = 1\n EXPENSE = 2\n LOSS = 3\n DIVIDENDS_INCOME = 4\n DONATION_RECEIVED = 5\n AIRDROP = 6\n GIFT = 7\n GRANT = 8\n\n def is_profitable(self) -> bool:\n return self in (\n LedgerActionType.INCOME,\n LedgerActionType.DIVIDENDS_INCOME,\n LedgerActionType.DONATION_RECEIVED,\n LedgerActionType.AIRDROP,\n LedgerActionType.GIFT,\n LedgerActionType.GRANT,\n )\n\n\nLedgerActionDBTuple = tuple[\n int, # timestamp\n str, # action_type\n str, # location\n str, # amount\n str, # asset\n Optional[str], # rate\n Optional[str], # rate_asset\n Optional[str], # link\n Optional[str], # notes\n]\n\n\nLedgerActionDBTupleWithIdentifier = tuple[\n int, # identifier\n int, # timestamp\n str, # action_type\n str, # location\n str, # amount\n str, # asset\n Optional[str], # rate\n Optional[str], # rate_asset\n Optional[str], # link\n Optional[str], # notes\n]\n\n\n@dataclass(init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)\nclass LedgerAction(AccountingEventMixin):\n \"\"\"Represents an income/loss/expense for accounting purposes\"\"\"\n identifier: int # the unique id of the action and DB primary key\n timestamp: Timestamp\n action_type: LedgerActionType\n location: Location\n amount: AssetAmount\n asset: Asset\n rate: Optional[Price] = None\n rate_asset: Optional[Asset] = None\n link: Optional[str] = None\n notes: Optional[str] = None\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __str__(self) -> str:\n return (\n f''\n )\n\n def serialize(self) -> dict[str, Any]:\n return {\n 'identifier': self.identifier,\n 'timestamp': self.timestamp,\n 'action_type': str(self.action_type),\n 'location': str(self.location),\n 'amount': str(self.amount),\n 'asset': self.asset.identifier,\n 'rate': str(self.rate) if self.rate else None,\n 'rate_asset': self.rate_asset.identifier if self.rate_asset else None,\n 'link': self.link,\n 'notes': self.notes,\n }\n\n @classmethod\n def deserialize(cls, data: dict[str, Any]) -> 'LedgerAction':\n \"\"\"Deserializes a ledger action dict to a LedgerAction object.\n May raise:\n - DeserializationError\n - KeyError\n - UnknownAsset\n \"\"\"\n rate_asset = deserialize_optional(data['rate_asset'], Asset)\n return cls(\n identifier=int(data['identifier']),\n timestamp=deserialize_timestamp(data['timestamp']),\n action_type=LedgerActionType.deserialize(data['action_type']),\n location=Location.deserialize(data['location']),\n asset=Asset(data['asset']).check_existence(),\n amount=deserialize_asset_amount(data['amount']),\n rate=deserialize_optional(data['rate'], deserialize_price),\n link=deserialize_optional(data['link'], str),\n notes=deserialize_optional(data['notes'], str),\n rate_asset=rate_asset.check_existence() if rate_asset is not None else None,\n )\n\n def serialize_for_db(self) -> LedgerActionDBTuple:\n \"\"\"Serializes an action for writing in the DB.\n Identifier and extra_data are ignored\"\"\"\n return (\n self.timestamp,\n self.action_type.serialize_for_db(),\n self.location.serialize_for_db(),\n str(self.amount),\n self.asset.identifier,\n str(self.rate) if self.rate else None,\n self.rate_asset.identifier if self.rate_asset else None,\n self.link,\n self.notes,\n )\n\n @classmethod\n def deserialize_from_db(\n cls,\n data: LedgerActionDBTupleWithIdentifier,\n ) -> 'LedgerAction':\n \"\"\"May raise:\n - DeserializationError\n - UnknownAsset\n \"\"\"\n rate_asset = deserialize_optional(data[7], Asset)\n return cls(\n identifier=data[0],\n timestamp=deserialize_timestamp(data[1]),\n action_type=LedgerActionType.deserialize_from_db(data[2]),\n location=Location.deserialize_from_db(data[3]),\n amount=deserialize_asset_amount(data[4]),\n asset=Asset(data[5]).check_existence(),\n rate=deserialize_optional(data[6], deserialize_price),\n rate_asset=rate_asset.check_existence() if rate_asset is not None else None,\n link=data[8],\n notes=data[9],\n )\n\n def is_profitable(self) -> bool:\n return self.action_type.is_profitable()\n\n # -- Methods of AccountingEventMixin\n\n def get_timestamp(self) -> Timestamp:\n return self.timestamp\n\n @staticmethod\n def get_accounting_event_type() -> AccountingEventType:\n return AccountingEventType.LEDGER_ACTION\n\n def get_identifier(self) -> str:\n return str(self.identifier)\n\n def should_ignore(self, ignored_ids_mapping: dict[ActionType, set[str]]) -> bool:\n return self.get_identifier() in ignored_ids_mapping.get(ActionType.LEDGER_ACTION, set())\n\n def get_assets(self) -> list[Asset]:\n return [self.asset]\n\n def process(\n self,\n accounting: 'AccountingPot',\n events_iterator: Iterator['AccountingEventMixin'], # pylint: disable=unused-argument\n ) -> int:\n given_price = None # Determine if non-standard price should be used\n if self.rate is not None and self.rate_asset is not None:\n if self.rate_asset == accounting.profit_currency:\n given_price = self.rate\n else:\n quote_rate = accounting.get_rate_in_profit_currency(self.rate_asset, self.timestamp) # noqa: E501\n given_price = Price(self.rate * quote_rate)\n\n taxed = self.action_type in accounting.settings.taxable_ledger_actions\n notes = self.notes if self.notes else f'{self.action_type} ledger action'\n if self.is_profitable():\n accounting.add_acquisition(\n event_type=AccountingEventType.LEDGER_ACTION,\n notes=notes,\n location=self.location,\n timestamp=self.timestamp,\n asset=self.asset,\n amount=self.amount,\n taxable=taxed,\n given_price=given_price,\n )\n else:\n accounting.add_spend(\n event_type=AccountingEventType.LEDGER_ACTION,\n notes=notes,\n location=self.location,\n timestamp=self.timestamp,\n asset=self.asset,\n amount=self.amount,\n taxable=taxed,\n given_price=given_price,\n )\n\n return 1\n","sub_path":"rotkehlchen/accounting/ledger_actions.py","file_name":"ledger_actions.py","file_ext":"py","file_size_in_byte":8163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"444056003","text":"#!/usr/bin/env python\n# license removed for brevity\nimport rospy\nfrom std_msgs.msg import String\nfrom beginner_tutorials.msg import data\n\ndef talker():\n pub = rospy.Publisher('data', data, queue_size=10)\n rospy.init_node('talker', anonymous=True)\n rate = rospy.Rate(10) # 10hz\n\n msg = data()\n\n count = 1\n\n while not rospy.is_shutdown():\n #hello_str = \"hello world %s\" % rospy.get_time()\n msg.ID = count\n msg.height = 180.0\n msg.weight = 50.0\n rospy.loginfo(msg.ID)\n pub.publish(msg)\n rate.sleep()\n count = count +1\n\nif __name__ == '__main__':\n try:\n talker()\n except rospy.ROSInterruptException:\n pass","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"425769220","text":"sample_dict = {\n 'class_a': {\n 'student1': {\n 'name': 'Misha',\n 'marks': {\n 'math': 90,\n 'history': 85\n }\n }\n }\n}\n\n# 1. Вывести значение ключа \"name\";\nprint(sample_dict['class_a']['student1']['name'])\n\n# 2. Вывести значение ключа \"history\";\nprint(sample_dict['class_a']['student1']['marks']['history'])\n\n# 3. Добавить нового студента в \"class_a\", соответственно его \"name\" и \"marks\";\nsample_dict['class_a']['student2'] = {\n 'name': 'Vasya',\n 'marks': {\n 'math': 75,\n 'history': 95\n }\n }\nprint(sample_dict)\n\n# 4. Добавить новый класс со студентами (в sample_dict нужно добавить class_b, в котором будет 2 студента);\nsample_dict['class_b'] = {\n 'student3': {\n 'name': 'Sveta',\n 'marks': {\n 'math': 80,\n 'history': 90\n }\n },\n 'student4': {\n 'name': 'Vika',\n 'marks': {\n 'math': 95,\n 'history': 95\n }\n }\n }\nprint(sample_dict)\n\n# 5. Добавить каждому студенту в \"marks\" предмет \"physics\" с оценкой;\nsample_dict['class_a']['student1']['marks']['physics'] = 90\nsample_dict['class_a']['student2']['marks']['physics'] = 80\nsample_dict['class_b']['student3']['marks']['physics'] = 85\nsample_dict['class_b']['student4']['marks']['physics'] = 90\n\nprint(sample_dict)\n\n# 6. Подсчитать средний бал по каждому студенту (результат округлить до 2 знаков после запятой);\nl = len(sample_dict['class_a']['student1']['marks']) # number of subjects\nsr_bal_stud1 = round(sum(list(sample_dict['class_a']['student1'] \\\n ['marks'].values())) / l, 2)\nsr_bal_stud2 = round(sum(list(sample_dict['class_a']['student2'] \\\n ['marks'].values())) / l, 2)\nsr_bal_stud3 = round(sum(list(sample_dict['class_b']['student3'] \\\n ['marks'].values())) / l, 2)\nsr_bal_stud4 = round(sum(list(sample_dict['class_b']['student4'] \\\n ['marks'].values())) / l, 2)\n\nprint(sr_bal_stud1)\nprint(sr_bal_stud2)\nprint(sr_bal_stud3)\nprint(sr_bal_stud4)\n\n# 7. Создать словарь со средним баллом за каждого студента;\nsr_bal_stud_dict = {'Misha': sr_bal_stud1, 'Vasya': sr_bal_stud2, \\\n 'Sveta': sr_bal_stud3, 'Vika': sr_bal_stud4}\n\nprint(sr_bal_stud_dict)\n\n# 8. Определить лучшего студента по успеваемости;\nx = max(sr_bal_stud_dict['Misha'], sr_bal_stud_dict['Vasya'], \\\n sr_bal_stud_dict['Sveta'], sr_bal_stud_dict['Vika']) # max point among students\nbest_stud = list(sr_bal_stud_dict.keys()) \\\n [list(sr_bal_stud_dict.values()).index(x)] # splits dictionary values in a list\n\nprint('best student - ' + best_stud)\n\n# 9. Подсчитать средний бал по каждому классу (результат округлить до 2 знаков после запятой);\nl_a = len(sample_dict['class_a']) # number of students in the class a\nl_b = len(sample_dict['class_b']) # number of students in the class b\nsr_bal_class_a = round((sr_bal_stud1 + sr_bal_stud2) / l_a, 2)\nsr_bal_class_b = round((sr_bal_stud3 + sr_bal_stud4) / l_b, 2)\n\nprint(sr_bal_class_a)\nprint(sr_bal_class_b)\n\n# 8. Создать словарь со средним баллом за классы;\nsr_bal_slas_dict = {'sr_bal_class_a': sr_bal_class_a, \\\n 'sr_bal_class_b': sr_bal_class_b}\n\nprint(sr_bal_slas_dict)\n\n# 9. Определить лучший класс по успеваемости.\ny = max(sr_bal_slas_dict['sr_bal_class_a'], \\\n sr_bal_slas_dict['sr_bal_class_b']) # max point among classes\nbest_class = list(sr_bal_slas_dict.keys()) \\\n [list(sr_bal_slas_dict.values()).index(y)][-1] # splits dictionary values in a list\n\nprint('best class - slass ' + str(best_class))\n","sub_path":"Baliuk/homework2/file2.py","file_name":"file2.py","file_ext":"py","file_size_in_byte":4711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"193029598","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n\n @ Author : Administrator\n @ date : 2019/6/27 21:39\n @ IDE : PyCharm\n @ GitHub : https://github.com/JackyPJB\n @ Contact : pengjianbiao@hotmail.com\n-------------------------------------------------\n Description : \n-------------------------------------------------\n\"\"\"\nimport hashlib\nimport random\nimport time\nimport urllib.request\nfrom xml.etree import ElementTree as eTree\nfrom wechatpy.pay import WeChatPay\n\nfrom flask import Blueprint, jsonify\n\nfrom app import app\nfrom app.utils.wechat_base import Map\nfrom wechatpy import WeChatPay\n\ntry:\n from flask import request\nexcept Exception:\n request = None\n\nconfig = app.config\nbp = Blueprint('xcc_pay_shop', __name__, url_prefix=\"/wx/pay_shop\")\n\nmp_id = config.get('MP_APPID_SHOP')\nmp_secret = config.get('MP_SECRET_SHOP')\nmp_mch_id = config.get('MP_MCH_ID')\nmp_mch_key = config.get('MP_MCH_KEY')\n# 这里吃的大亏,回调地址不能用 https , fuck\nhttp_root = config.get('HTTP_ROOT')\nnotify_url = http_root + '/wx/pay/notifyurl'\n\nmch_key = config.get('WECHAT_MCH_KEY')\n\"\"\"\nappid – 微信公众号/或者小程序号\napi_key – 商户 key, 不要在这里使用小程序的密钥\nmch_id – 商户号\n(sub_mch_id – 可选,子商户号,受理模式下必填,这里不填)\n(mch_cert – 商户证书路径,这里不填)\nmch_key – 必填,商户证书私钥路径(小程序,这里也填商户号key)\ntimeout – 可选,请求超时时间,单位秒,默认无超时设置\nsandbox – 可选,是否使用测试环境,默认为 False\n\"\"\"\nwx_pay = WeChatPay(appid=mp_id, mch_id=mp_mch_id, mch_key=mp_mch_key, api_key=mp_mch_key)\n\n\n# 微信的签名逻辑需要注意:\n#\n# 商户密钥不参与字典序排序\n# md5后需要转大写\n# 参与排序的字典名要与微信的文档严格保持一致\n@bp.route(\"/reqPay\", methods=[\"POST\", \"GET\"])\ndef get_json1():\n print(request.args)\n # 这里还有一个 请求 sign 的构造过程, wechatpy 都已经封装好了\n rs = wx_pay.order.create(trade_type=\"JSAPI\",\n total_fee=1, # 订单总金额,单位为分\n notify_url=notify_url, # 异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的 http 地址,不能是 https ,不能携带参数。\n user_id=request.args.get(\"openid\"), # 微信分配的小程序ID,擦嘞\n body=\"测试\", # 商品详细描述,对于使用单品优惠的商户,该字段必须按照规范上传\n client_ip=request.remote_addr, # 这就是 spbill_create_ip,换两个名字\n out_trade_no=str(int(time.time())), # 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*且在同一个商户号下唯一\n )\n # 获取 paySign\n # paySign wx_pay.jsapi.get_jsapi_signature(rs[\"prepay_id\"])\n jsapi_params = wx_pay.jsapi.get_jsapi_params(rs[\"prepay_id\"])\n return jsonify(jsapi_params)\n\n\n# 微信推送消息是XML格式,使用wechatpy的parse_payment_result方法可以将结果转化成OrderedDict类型,且帮你做好了验签。\n@bp.route(\"/notifyurl\", methods=[\"GET\", \"POST\"])\ndef get_notify_url():\n notify_data = request.data\n print(notify_data)\n data = wx_pay.parse_payment_result(notify_data)\n print(data)\n # 然后就可以根据返回的结果,处理之前的订单了。\n # TODO 写上处理结果的逻辑。存储数据库之类的\n # 唯一需要注意的一点,微信推送消息后,需要给微信服务器返回一个消息:\n return \"\"\n\n\n\"\"\" 之前没用 wechatpy , 自己手动写的方法, 能用,但是有现成的封装好的不是更好吗\n 感谢 wechatpy 的作者 https://wechatpy.readthedocs.io/zh_CN/master/pay.html#module-wechatpy.pay\n# 生成随机字符串,长度要求在32位以内\ndef creat_nonce_str():\n ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'\n ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n ascii_letters = ascii_lowercase + ascii_uppercase\n digits = '0123456789'\n char = ascii_letters + digits\n return \"\".join(random.choice(char) for _ in range(16))\n\n\nto_uft8 = lambda x: x.encode(\"utf-8\") if isinstance(x, str) else x\n\n\n# 签名所有发送或者接收到的数据为集合M,将集合M内非空参数值的参数按照参数名ASCII码从小到大排序\n# URL键值对的格式(即key1 = value1 & key2 = value2…)拼接成字符串stringA\n# tringA最后拼接上key得到stringSignTemp字符串,并对stringSignTemp进行MD5运算,\n# 再将得到的字符串所有字符转换为大写\ndef sign(pay_data):\n stringA = '&'.join([\"{0}={1}\".format(k, pay_data.get(k)) for k in sorted(pay_data)])\n stringSignTemp = '{0}&key={1}'.format(stringA, mp_mch_key)\n return hashlib.md5(to_uft8(stringSignTemp)).hexdigest().upper()\n\n\n# 生成xml格式发送\ndef to_xml(arr):\n xml = [\"\"]\n for k, v in arr.items():\n if v.isdigit():\n xml.append(\"<{0}>{1}\".format(k, v))\n else:\n xml.append(\"<{0}>\".format(k, v))\n xml.append(\"\")\n return \"\".join(xml)\n\n\n# 每个element对象都具有以下属性:\n# 1.tag:string对象,表示数据代表的种类。\n# 2.attrib:dictionary对象,表示附有的属性。\n# 3.text:string对象,表示element的内容。\n# 4.tail:string对象,表示element闭合之后的尾迹。\n# 例如:< tag attrib1 = 1 > text < / tag > tail\ndef to_dict(content):\n raw = {}\n root = eTree.fromstring(content)\n for child in root:\n raw[child.tag] = child.text\n return raw\n\n\n# 实行发送请求,并且得到返回结果\ndef pay_send_get(url, xml_data):\n req = urllib.request.Request(url, bytes(xml_data, encoding=\"utf8\"))\n opener = urllib.request.build_opener(urllib.request.HTTPSHandler())\n # try:\n # resp = urllib.request.urlopen(url,bytes(data, encoding=\"utf8\"), timeout=20)\n resp = opener.open(req, timeout=20).read()\n print(\"统一下单返回:\")\n print(resp)\n # # except urllib.request.HTTPSHandler as e:\n # # resp = e\n res_data = Map(to_dict(resp))\n\n # 微信服务器返回的xml里有:\n # 返回状态码:return_code\n # 此字段是通信标识,非交易标识,交易是否成功需要查看result_code来判断\n # 返回信息:return_msg 如果无错为空\n if res_data.return_code == \"FAIL\":\n # raise PayError(data.return_msg)\n raise res_data.return_msg\n\n # 得到了返回的xml,并且转成dict类型\n return res_data\n# python小程序付款参考: https://www.jianshu.com/p/07ed48e4a50b\n@bp.route(\"/reqPay1\", methods=[\"POST\", \"GET\"])\ndef get_json():\n spbill_create_ip = request.remote_addr\n openid = request.args.get(\"openid\")\n print(openid)\n data = {\n 'appid': mp_id, # 微信分配的小程序ID,擦嘞,这里的appid 的 i 是小写\n 'mch_id': mp_mch_id, # 微信支付分配的商户号\n 'nonce_str': creat_nonce_str(), # 随机字符串,长度要求在32位以内\n 'body': '测试', # 商品详细描述,对于使用单品优惠的商户,该字段必须按照规范上传\n 'out_trade_no': str(int(time.time())), # 商户系统内部订单号,要求32个字符内,只能是数字、大小写字母_-|*且在同一个商户号下唯一\n 'total_fee': '1', # 订单总金额,单位为分\n 'spbill_create_ip': spbill_create_ip, # 支持IPV4和IPV6两种格式的IP地址。调用微信支付API的机器IP 支付提交用户端ip,得到终端ip\n 'notify_url': notify_url, # 异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。\n 'attach': '{\"msg\": \"自定义数据\"}', # 附加数据,在查询API和支付通知中原样返回,可作为自定义参数使用。\n 'trade_type': \"JSAPI\", # 小程序取值如下:JSAPI\n 'openid': openid # 用户标识 当 trade_type=JSAPI,此参数必传,用户在商户appid下的唯一标识。\n }\n get_sign = sign(data)\n print(\"第一次搞到sign:\")\n print(get_sign)\n data[\"sign\"] = get_sign\n print(data)\n get_xml = to_xml(data)\n print(get_xml)\n res_data = pay_send_get(\"https://api.mch.weixin.qq.com/pay/unifiedorder\", get_xml)\n print(res_data)\n # 得到prepay_id 微信生成的预支付会话标识,用于后续接口调用中使用,该值有效期为2小时\n prepay_id = res_data[\"prepay_id\"]\n # 生成wx.requestPayment小程序中的paySign签名: https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=7_7\n paySign_data = {\n 'appId': mp_id, # 微信分配的小程序ID 擦嘞,这里的appId 的 I 是大写\n 'timeStamp': str(int(time.time())), # 时间戳从1970年1月1日00:00:00至今的秒数,即当前的时间\n 'nonceStr': creat_nonce_str(), # 随机字符串,不长于32位\n 'package': 'prepay_id={0}'.format(prepay_id),\n # 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=wx2017033010242291fcfe0db70013231072\n 'signType': 'MD5' # 签名类型,默认为MD5\n }\n # 生成 sign 签名\n get_paySign = sign(paySign_data)\n print(\"这次搞到的sign\" + get_paySign)\n paySign_data[\"paySign\"] = get_paySign\n print(paySign_data)\n return jsonify(paySign_data)\n \n@bp.route(\"/notifyurl\", methods=[\"GET\", \"POST\"])\ndef get_notify_url():\n print(\"yes,here\")\n allthings = request.stream.read()\n print(allthings)\n respData = {'return_code': \"SUCCESS\"}\n # respData = arrayToXml(respData)\n return to_xml(respData)\n\"\"\"\n","sub_path":"app/routes/xcc_pay_shop.py","file_name":"xcc_pay_shop.py","file_ext":"py","file_size_in_byte":9997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"409284196","text":"from btfxwss import BtfxWss\nimport time\nimport sys\nfrom .indicators import macd, rsi\nfrom .positions import LongPosition\nimport datetime\nimport json\nimport os\n\nTICKER_FILE_LOCATION = \"/Users/caesar/Desktop/bitfinex/bitfinex/websockets/ticker_files/{symbol}/\"\nTRADE_FILE_LOCATION = \"/Users/caesar/Desktop/bitfinex/bitfinex/websockets/trade_files/{symbol}/\"\n\n\ndef parse_ticker(ticker):\n # ticker = ([[2.1524, 102891.82706453, 2.1578, 169533.05006635, 0.341, 0.1884, 2.151, 85626133.66420326, 2.196, 1.8201]], 1514903073.135506)\n return ','.join(list(map(lambda x: str(x), ticker[0][-1])) + [str(ticker[1])]) + '\\n'\n\ndef main():\n wss = BtfxWss()\n wss.start()\n macd_obj = macd.MACD()\n rsi_obj = rsi.RSI()\n long_position = LongPosition()\n\n while not wss.conn.connected.is_set():\n time.sleep(1)\n\n # wss.subscribe_to_ticker('XRPUSD')\n wss.subscribe_to_trades('XRPUSD')\n\n time.sleep(15)\n \n # ticker_q = wss.tickers('XRPUSD') # returns a Queue object for the pair.\n ticker_q = wss.trades('XRPUSD')\n while 1:\n if ticker_q.empty():\n time.sleep(1)\n else:\n ticker = ticker_q.get()\n print(ticker)\n # price = ticker[0][-1][6]\n # timestamp = ticker[1]\n timestamp = ticker[1]\n price = ticker[0][-1][-1]\n if isinstance(price, list):\n continue\n macd_obj.update_macd(timestamp, price)\n # print(macd_obj.macds)\n rsi_obj.update_rsi(timestamp, price)\n # print(rsi_obj.rsi)\n long_position.update_position(macd_obj.macds['present_macd'], macd_obj.macds['present_signal'], rsi_obj.rsi['rsi'], price, timestamp)\n # print('\\n\\n')\n\n\ndef store_data(symbol):\n file_dir = TRADE_FILE_LOCATION.format(symbol=symbol)\n if not os.path.exists(file_dir):\n os.makedirs(file_dir)\n wss = BtfxWss()\n wss.start()\n while not wss.conn.connected.is_set():\n time.sleep(1)\n wss.subscribe_to_trades(symbol)\n time.sleep(15)\n trade_q = wss.trades(symbol)\n while 1:\n if trade_q.empty():\n time.sleep(1)\n else:\n trade = trade_q.get()\n with open(file_dir + datetime.datetime.now().strftime(\"%Y%m%d\") + '.txt', 'a') as outfile:\n outfile.write(str(trade))\n outfile.write('\\n')\n print(trade)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"websockets/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"245911532","text":"from conftest import CRATE_HOST, CRATE_PORT\nfrom translators.crate import CrateTranslator\nfrom translators.influx import InfluxTranslator\nfrom translators.rethink import RethinkTranslator\nimport os\nimport pytest\n\n\nINFLUX_HOST = os.environ.get('INFLUX_HOST', 'influx')\nRETHINK_HOST = os.environ.get('RETHINK_HOST', 'rethink')\n\n\n@pytest.fixture\ndef influx_translator():\n with InfluxTranslator(INFLUX_HOST) as trans:\n yield trans\n\n\n@pytest.fixture()\ndef crate_translator(clean_crate):\n with CrateTranslator(host=CRATE_HOST, port=CRATE_PORT) as trans:\n yield trans\n\n\n@pytest.fixture()\ndef rethink_translator():\n with RethinkTranslator(RETHINK_HOST) as trans:\n yield trans\n","sub_path":"translators/fixtures.py","file_name":"fixtures.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"107429945","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Tintri, Inc.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport json\nimport sys\nimport tintri_1_1 as tintri\n\n\"\"\"\n This Python script sets the QoS of the VMs in the first TGC service group with\n more than 2 VMs. \n\n Command usage:\n qos_on_service_group.py server_name user_name password min_value max_value\n Where:\"\n server_name - name of a TGC server\n user_name - user name used to login into the TGC server\n password - password for the user\n min_value - the QoS minimum value for the VM\n max_value - the QoS maximum value for the VM\n\n\"\"\"\n\n# For exhaustive messages on console, make it to True; otherwise keep it False\ndebug_mode = False\n\n\ndef print_with_prefix(prefix, out):\n print(prefix + out)\n return\n\n\ndef print_debug(out):\n if debug_mode:\n print_with_prefix(\"[DEBUG] : \", out)\n return\n\n\ndef print_info(out):\n print_with_prefix(\"[INFO] : \", out)\n return\n\n\ndef print_error(out):\n print_with_prefix(\"[ERROR] : \", out)\n return\n\n\n# Sets the Minimum and maximum QoS values on a TGC service group.\ndef set_qos(server_name, session_id, sg_uuid, new_min_value, new_max_value):\n # Create new QoS object with the fields to be changed\n modify_qos_info = {'minNormalizedIops': int(new_min_value),\n 'maxNormalizedIops': int(new_max_value),\n 'typeId': 'com.tintri.api.rest.v310.dto.domain.beans.vm.VirtualMachineQoSConfig'\n }\n \n # Configure the QoS for the service group\n modify_qos_url = \"/v310/servicegroup/\" + sg_uuid + \"/qosConfig\"\n r = tintri.api_put(server_name, modify_qos_url, modify_qos_info, session_id)\n print_debug(\"The JSON response of the get invoke to the server \" +\n server_name + \" is: \" + r.text)\n \n # if HTTP Response is not 204 then raise an exception\n if r.status_code != 204:\n print_error(\"The HTTP response for the put invoke to the server \" +\n server_name + \" is not 204, but is: \" + str(r.status_code))\n print_error(\"url = \" + modify_qos_url)\n print_error(\"payload = \" + str(modify_qos_info))\n print_error(\"response: \" + r.text)\n tintri.api_logout(server_name, session_id)\n print_info(\"Error log off \" + server_name)\n sys.exit(-20)\n \n # Apply the QoS values that were for the service group that\n # were configured above.\n apply_qos_url = \"/v310/servicegroup/\" + sg_uuid + \"/qos\"\n r = tintri.api_post(server_name, apply_qos_url, None, session_id)\n print_debug(\"The JSON response of the get invoke to the server \" +\n server_name + \" is: \" + r.text)\n \n # if HTTP Response is not 204 then raise an exception\n if r.status_code != 204:\n print_error(\"The HTTP response for the post invoke to the server \" +\n server_name + \" is not 204, but is: \" + str(r.status_code))\n print_error(\"url = \" + modify_qos_url)\n print_error(\"payload = None\")\n print_error(\"response: \" + r.text)\n tintri.api_logout(server_name, session_id)\n print_info(\"Error log off \" + server_name)\n sys.exit(-21)\n\n\n# main\nif len(sys.argv) < 6:\n print(\"\\nsets the QoS of the VMs in a TGC service group with more than 2 VMs.\\n\")\n print(\"Usage: \" + sys.argv[0] + \" server_name user_name password min_value max_value\\n\")\n print(\"Where:\")\n print(\" server_name - name of a TGC server\")\n print(\" user_name - user name used to login into the TGC and VMstore servers\")\n print(\" password - password for the TGC and VMstore users\")\n print(\" min_value - the QoS minimum value for the VM\")\n print(\" max_value - the QoS maximum value for the VM\")\n sys.exit(-1)\n\nserver_name = sys.argv[1]\nuser_name = sys.argv[2]\npassword = sys.argv[3]\nnew_min_value = sys.argv[4]\nnew_max_value = sys.argv[5]\n\n# Get the preferred version\nr = tintri.api_version(server_name)\njson_info = r.json()\npreferred_version = json_info['preferredVersion']\nproduct_name = json_info['productName']\n\n# Check for correct product\nif product_name != \"Tintri Global Center\":\n print_error(\"Tintri server needs to be Tintri Global Center, not a \" + product_name)\n sys.exit(-8)\n\n# Check for the correct version\nversions = preferred_version.split(\".\")\nmajor_version = versions[0]\nminor_version = int(versions[1])\nif major_version != \"v310\":\n print_error(\"Incorrect major version: \" + major_version + \". Should be v310.\")\n sys.exit(-8)\nif minor_version < 31:\n print_error(\"Incorrect minor Version: \" + minor_version + \". Should be 31 or greater\")\n sys.exit(-8)\n\n# Login to TGC\nsession_id = tintri.api_login(server_name, user_name, password)\nif session_id is None:\n sys.exit(-7)\n\n# Get a list of service groups\nurl = \"/v310/servicegroup\"\nr = tintri.api_get(server_name, url, session_id)\nprint_debug(\"The JSON response of the get invoke to the server \" +\n server_name + \" is: \" + r.text)\n\n# if HTTP Response is not 200 then raise an error\nif r.status_code != 200:\n print_error(\"The HTTP response for the get invoke to the server \" +\n server_name + \" is not 200, but is: \" + str(r.status_code))\n print_error(\"url = \" + url)\n print_error(\"response: \" + r.text)\n tintri.api_logout(server_name, session_id)\n sys.exit(-10)\n\nsg_paginated_result = r.json()\nnum_sgs = int(sg_paginated_result[\"absoluteTotal\"])\nif num_sgs == 0:\n print_error(\"No Service Groups present\")\n tintri.api_logout(server_name, session_id)\n exit(88)\n\nprint_info(str(num_sgs) + \" Service Groups present\")\n\n# Initialze the member list\nsg_uuid = \"\"\nfound = False\n\n# Look for a qualifying service group\nitems = sg_paginated_result[\"items\"]\ncount = 1\nfor sg in items:\n sg_name = sg[\"name\"]\n sg_uuid = sg[\"uuid\"][\"uuid\"]\n sg_member_count = sg[\"memberCount\"]\n print_info(str(count) + \": \" + sg_name + \"(\" + str(sg_member_count) + \"): \" + sg_uuid)\n if sg_member_count >= 2: \n found = True\n break\n count += 1\n\nif not found:\n print_error(\"No service groups matching the criertia.\")\n tintri.api_logout(server_name, session_id)\n sys.exit(-15)\n\nset_qos(server_name, session_id, sg_uuid, new_min_value, new_max_value)\n\n# All pau, log out\ntintri.api_logout(server_name, session_id)\n\n","sub_path":"examples/python/set_qos_tgc_service_groups.py","file_name":"set_qos_tgc_service_groups.py","file_ext":"py","file_size_in_byte":7371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"305985450","text":"# -*- coding:utf-8 -*-\nimport urllib2\nimport urllib\nimport re\nclass BLOG:\n def __init__(self):\n print (u\"开始爬取博客……\")\n \n def getArticalNum(self):\n baseUrl = 'http://yaoxv.cc'\n request = urllib2.Request(baseUrl)\n response = urllib2.urlopen(request)\n response = response.read().decode('utf-8')\n pattern = re.compile('',re.S)\n urlStr = re.findall(pattern,response)\n length = len(urlStr)\n print (u\"共发现%d篇博客\"%(length))\n return length\n \n def getUrl(self,i):\n baseUrl = 'http://yaoxv.cc'\n request = urllib2.Request(baseUrl)\n response = urllib2.urlopen(request)\n response = response.read().decode('utf-8')\n pattern = re.compile('',re.S)\n urlStr = re.findall(pattern,response)\n url = baseUrl + urlStr[i]\n return url.encode('utf-8')\n\n def getPage(self,url):\n #url = getUrl(self,i)\n request = urllib2.Request(url)\n response = urllib2.urlopen(request)\n return response.read().decode('utf-8')\n\n def getTitle(self,page):\n #page = getPage(self)\n pattern = re.compile('

(.*?)

',re.S)\n title = re.search(pattern,page)\n if title:\n # print (\"第%d篇博客:\"%(i+1))\n # print title.group(1)\n return title.group(1).strip()\n else:\n return None\n \n def getContents(self,page):\n #page = getPage(self)\n pattern = re.compile('
(.*?)
',re.S)\n items = re.findall(pattern,page)\n contents = []\n for item in items:\n content = self.replace(item)\n contents.append(content.encode('utf-8'))\n #for content in contents:\n # print content\n return contents \n \n def replace(self,x):\n #removeImg = re.compile('| {7}|')\n removeAddr = re.compile('|
')\n replaceHx = re.compile('|')\n replaceCodingNum = re.compile('.*?')\n replaceLine = re.compile('|
|
|

')\n replaceTD = re.compile('')\n replacePara = re.compile('')\n replaceBR = re.compile('

|
')\n removeExtraTag = re.compile('<.*?>')\n \n #x = re.sub(removeImg,\"\",x)\n x = re.sub(removeAddr,\"\",x)\n x = re.sub(replaceHx,\"\\n\",x)\n x = re.sub(replaceCodingNum,\"\\n\",x)\n x = re.sub(replaceLine,\"\\n\",x)\n x = re.sub(replaceTD,\"\\t\",x)\n x = re.sub(replacePara,\"\\n \",x)\n x = re.sub(replaceBR,\"\\n\",x)\n x = re.sub(removeExtraTag,\"\",x)\n return x.strip()\n \n def setFileTitle(self,title,i):\n #title = getTitle().encode('utf-8')\n print (u\"开始写入第%d篇博客\"%(i+1))\n if i==0:\n file = open('blog.txt',\"w+\")\n else:\n file = open('blog.txt',\"a\")\n #file.write()\n file.write(\"第%d篇博客:\"%(i+1)+title.encode('utf-8')+'\\n') \n file.close()\n \n def setFileContents(self,contents,i):\n #contents = getContents(self)\n file = open('blog.txt',\"a\")\n for content in contents:\n file.write(content)\n file.close()\n #print contents\n print (u\"第%d篇博客完成写入\"%(i+1))\n\n def start(self):\n i = 0 \n length = self.getArticalNum()\n for i in range(length):\n url = self.getUrl(i)\n page = self.getPage(url)\n title = self.getTitle(page)\n contents = self.getContents(page)\n self.setFileTitle(title,i)\n self.setFileContents(contents,i)\n\n\nif __name__ == '__main__':\n \n blog = BLOG()\n blog.start()\n\n\n","sub_path":"blog.py","file_name":"blog.py","file_ext":"py","file_size_in_byte":4704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"348453980","text":"# Faça um programa que leia um ângulo qualquer e mostre na tela o valor do seno, cosseno e tangente desse ângulo.\n\nimport math\nan = int(input('Informe o ângulo desejado: '))\nseno = math.sin(math.radians(an))\ncosseno = math.cos(math.radians(an))\ntangente = math.tan(math.radians(an))\nprint('O ângulo de {}º tem o SENO de {:.2f}'.format(an, seno))\nprint('O ângulo de {}º tem o COSSENO de {:.2f}'.format(an, cosseno))\nprint('O ângulo de {}º tem a TANGENTE de {:.2f}'.format(an, tangente))\n","sub_path":"olamundo.py/exercicios/ex018.py","file_name":"ex018.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"124238971","text":"#Lab Exercise 07\n#List and Tuple Sorting\n\nfile = open(\"scores.txt\", \"r\")\nname=\"\"\npeople=[]\nfirst=True\nfor line in file:\n line=line.strip()\n name=(line[:21])\n nums=line[21:]\n nums=nums.split(\" \")\n first=True \n for x in nums:\n if x and first:\n exam1=int(x)\n first=False\n elif x:\n exam2=int(x)\n avg=(exam1+exam2)/2\n tup=name,exam1,exam2,avg\n people.append(tup)\npeople.sort()\ntotal1,total2=0,0\nprint('{:<20s}{:>0s}{:>10s}{:>16s}'\\\n .format(\"Name\",\"Exam 1\",\"Exam 2\",\"Exam Average\"))\nfor x in people:\n total1+=x[1]\n total2+=x[2]\n print('{:<20s}{:<11d}{:<10d}{:<16.1f}'\\\n .format(x[0],x[1],x[2],x[3])) \navg1=total1/5\navg2=total2/5\nprint()\nprint('{:<20s}{:<.1f}'\\\n .format(\"Exam 1 Average: \",avg1))\nprint('{:<20s}{:<.1f}'\\\n .format(\"Exam 2 Average: \",avg2)) ","sub_path":"Labs/lab07.py","file_name":"lab07.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"555731121","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport win32serviceutil\nimport win32service\nimport win32event\nimport monitor\nclass SmallestPythonService(win32serviceutil.ServiceFramework):\n _svc_name_ = \"WriteCache\"\n _svc_display_name_ = \"WriteCache Monitor Service\"\n def __init__(self, args):\n self.threads = []\n win32serviceutil.ServiceFramework.__init__(self, args)\n self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)\n def SvcStop(self):\n self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)\n win32event.SetEvent(self.hWaitStop)\n def SvcDoRun(self):\n #This is my program !\n monitor.wrong()\n self.threads = []\n self.ReportServiceStatus(win32service.SERVICE_RUNNING)\n win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)\nif __name__=='__main__':\n win32serviceutil.HandleCommandLine(SmallestPythonService)","sub_path":"win_deamon.py","file_name":"win_deamon.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"442431839","text":"import random\n\nimport torch\nfrom torch import nn as nn\nfrom torch.nn import functional as F\n\nfrom src.Config import NeatProperties as Props, Config\nfrom src.NEAT.Gene import NodeGene, NodeType\nfrom src.NEAT.Mutagen import Mutagen, ValueType\n\nuse_convs = True\nuse_linears = True\n\n\nclass ModuleNEATNode(NodeGene):\n def __init__(self, id, node_type=NodeType.HIDDEN, activation=F.relu, layer_type=nn.Conv2d,\n conv_window_size=3, conv_stride=1, max_pool_size=2):\n \"\"\"initialises all of the nodes mutagens, and assigns initial values\"\"\"\n\n super(ModuleNEATNode, self).__init__(id, node_type)\n\n batch_norm_chance = 0.65 # chance that a new node will start with batch norm\n use_batch_norm = random.random() < batch_norm_chance\n\n dropout_chance = 0.2 # chance that a new node will start with drop out\n use_dropout = random.random() < dropout_chance\n\n max_pool_chance = 0.3 # chance that a new node will start with drop out\n use_max_pool = random.random() < max_pool_chance\n\n self.activation = Mutagen(F.relu, F.leaky_relu, torch.sigmoid, F.relu6,\n discreet_value=activation, name=\"activation function\",\n mutation_chance=0.15) # TODO try add in Selu, Elu\n\n conv_out_features = 25 + random.randint(0, 25)\n linear_out_features = 100 + random.randint(0, 100)\n\n linear_submutagens = \\\n {\n \"regularisation\": Mutagen(None, nn.BatchNorm1d,\n discreet_value=nn.BatchNorm1d if use_batch_norm else None,\n mutation_chance=0.15),\n\n \"dropout\": Mutagen(None, nn.Dropout, discreet_value=nn.Dropout if use_dropout else None, sub_mutagens=\n {\n nn.Dropout: {\n \"dropout_factor\": Mutagen(value_type=ValueType.CONTINUOUS, current_value=0.15, start_range=0,\n end_range=0.75)}\n }, mutation_chance=0.08),\n\n \"out_features\": Mutagen(value_type=ValueType.WHOLE_NUMBERS, current_value=linear_out_features,\n start_range=10,\n end_range=1024, name=\"num out features\", mutation_chance=0.22,\n distance_weighting=Props.LAYER_SIZE_COEFFICIENT if Config.allow_attribute_distance else 0)\n }\n\n conv_submutagens = {\n \"conv_window_size\": Mutagen(3, 5, 7, discreet_value=conv_window_size, mutation_chance=0.13),\n\n \"conv_stride\": Mutagen(value_type=ValueType.WHOLE_NUMBERS, current_value=conv_stride, start_range=1,\n end_range=5),\n\n \"reduction\": Mutagen(None, nn.MaxPool2d, discreet_value=nn.MaxPool2d if use_max_pool else None,\n sub_mutagens=\n {\n nn.MaxPool2d: {\"pool_size\": Mutagen(\n value_type=ValueType.WHOLE_NUMBERS, current_value=max_pool_size, start_range=2,\n end_range=5)}\n }, mutation_chance=0.15),\n\n \"regularisation\": Mutagen(None, nn.BatchNorm2d, discreet_value=nn.BatchNorm2d if use_batch_norm else None,\n mutation_chance=0.15),\n\n \"dropout\": Mutagen(None, nn.Dropout2d, discreet_value=nn.Dropout2d if use_dropout else None, sub_mutagens=\n {\n nn.Dropout2d: {\n \"dropout_factor\": Mutagen(value_type=ValueType.CONTINUOUS, current_value=0.1,\n start_range=0, end_range=0.75)}\n }, mutation_chance=0.08),\n\n \"out_features\": Mutagen(value_type=ValueType.WHOLE_NUMBERS, current_value=conv_out_features, start_range=1,\n end_range=100, name=\"num out features\", mutation_chance=0.22,\n distance_weighting=Props.LAYER_SIZE_COEFFICIENT if Config.allow_attribute_distance else 0)\n }\n\n if use_linears and not use_convs:\n self.layer_type = Mutagen(nn.Linear, discreet_value=nn.Linear,\n distance_weighting=Props.LAYER_TYPE_COEFFICIENT if Config.allow_attribute_distance else 0,\n sub_mutagens={nn.Linear: linear_submutagens}\n )\n if use_convs and not use_linears:\n self.layer_type = Mutagen(nn.Conv2d, discreet_value=nn.Conv2d,\n distance_weighting=Props.LAYER_TYPE_COEFFICIENT if Config.allow_attribute_distance else 0,\n sub_mutagens={nn.Conv2d: conv_submutagens})\n if use_convs and use_linears:\n self.layer_type = Mutagen(nn.Conv2d, nn.Linear, discreet_value=layer_type,\n distance_weighting=Props.LAYER_TYPE_COEFFICIENT if Config.allow_attribute_distance else 0,\n sub_mutagens={\n nn.Conv2d: conv_submutagens,\n nn.Linear: linear_submutagens\n }, name=\"deep layer type\", mutation_chance=0.08)\n\n def get_all_mutagens(self):\n return [self.activation, self.layer_type]\n\n def __repr__(self):\n return str(self.node_type)\n\n def get_node_name(self):\n return repr(self.layer_type()) + \"\\n\" + \"features: \" + repr(self.layer_type.get_sub_value(\"out_features\"))\n\n def get_complexity(self):\n \"\"\"approximates the size of this layer in terms of trainable parameters\"\"\"\n if self.layer_type() == nn.Conv2d:\n return pow(self.layer_type.get_sub_value(\"conv_window_size\"), 2) * self.layer_type.get_sub_value(\n \"out_features\")\n elif self.layer_type() == nn.Linear:\n return self.layer_type.get_sub_value(\"out_features\")\n else:\n raise Exception()\n","sub_path":"src/CoDeepNEAT/CDNNodes/ModuleNode.py","file_name":"ModuleNode.py","file_ext":"py","file_size_in_byte":6193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"539474189","text":"import os\nos.environ['CUDA_VISIBLE_DEVICES'] = \"1\"\n\nimport torch\nimport torch.nn.functional as F\nfrom torch.optim import Adam\nfrom sklearn.metrics import roc_auc_score, average_precision_score\nimport scipy.sparse as sp\nimport numpy as np\nimport time\nfrom collections import defaultdict\n\nfrom input_data import load_data\nfrom preprocessing import *\nimport args\nimport model\n\n\n# Train on CPU (hide GPU) due to memory constraints\n# os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(args.device)\n\nauc_list = []\nap_list = []\n\nepoch_test_performance = defaultdict(list)\nepoch_valid_performance = defaultdict(list)\n\ndef get_train_edges_parts(edges, epoch):\n number_of_slices = int(np.floor(len(edges)/args.subsample_number))\n index = epoch % number_of_slices\n return edges[index*args.subsample_number:(index+1)*args.subsample_number]\n\nfor exp in range(10):\n args.model = 'NLGF'\n\n print('model= '+ str(args.model)) \n print('dataset=' + str(args.dataset))\n print('learning rate= '+ str(args.learning_rate))\n print('epoch= '+ str(args.num_epoch))\n print('subsample_number='+ str(args.subsample_number))\n print('hidden1_dim='+str(args.hidden1_dim))\n\n adj, features = load_data(args.dataset)\n\n # Store original adjacency matrix (without diagonal entries) for later\n adj_orig = adj\n adj_orig = adj_orig - sp.dia_matrix((adj_orig.diagonal()[np.newaxis, :], [0]), shape=adj_orig.shape)\n adj_orig.eliminate_zeros()\n\n adj_train, train_edges, train_false_edges, val_edges, val_edges_false, test_edges, test_edges_false = mask_test_edges(adj)\n \n adj = adj_train\n\n # Some preprocessing\n adj_norm = preprocess_graph(adj)\n\n num_nodes = adj.shape[0]\n\n features = sparse_to_tuple(features.tocoo())\n num_features = features[2][1]\n features_nonzero = features[1].shape[0]\n\n # Create Model\n pos_weight = float(adj.shape[0] * adj.shape[0] - adj.sum()) / adj.sum()\n norm = adj.shape[0] * adj.shape[0] / float((adj.shape[0] * adj.shape[0] - adj.sum()) * 2)\n\n adj_norm = torch.sparse.FloatTensor(torch.LongTensor(adj_norm[0].T), \n torch.FloatTensor(adj_norm[1]), \n torch.Size(adj_norm[2]))\n features = torch.sparse.FloatTensor(torch.LongTensor(features[0].T), \n torch.FloatTensor(features[1]), \n torch.Size(features[2]))\n adj_label = torch.cat((torch.ones(args.subsample_number,1), torch.zeros(args.subsample_number,1)),0)\n\n weight_mask = adj_label.view(-1) == 1\n # weight_mask = adj_label.to_dense().view(-1) == 1\n weight_tensor = torch.ones(weight_mask.size(0)) \n weight_tensor[weight_mask] = pos_weight\n\n\n if torch.cuda.is_available():\n adj_norm = adj_norm.cuda()\n # init model and optimizer\n model_adj_norm = getattr(model,args.model)(adj_norm)\n optimizer = Adam(model_adj_norm.parameters(), lr=args.learning_rate)\n\n if torch.cuda.is_available():\n features = features.cuda()\n adj_label = adj_label.cuda()\n model_adj_norm.cuda()\n weight_tensor = weight_tensor.cuda()\n\n def get_scores(edges_pos, edges_neg, adj_rec):\n\n def sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n # Predict on test set of edges\n preds = []\n pos = []\n for index, e in enumerate(edges_pos):\n preds.append(adj_rec[index,:].item())\n # preds.append(adj_rec[e[0], e[1]].item())\n\n pos.append(adj_orig[e[0], e[1]])\n\n preds_neg = []\n neg = []\n for index, e in enumerate(edges_neg):\n index += len(edges_pos)\n preds_neg.append(adj_rec[index,:].item())\n # preds_neg.append(adj_rec[e[0], e[1]].item())\n\n neg.append(adj_orig[e[0], e[1]])\n\n preds_all = np.hstack([preds, preds_neg])\n labels_all = np.hstack([np.ones(len(preds)), np.zeros(len(preds_neg))])\n roc_score = roc_auc_score(labels_all, preds_all)\n ap_score = average_precision_score(labels_all, preds_all)\n\n return roc_score, ap_score\n\n def get_acc(adj_rec, adj_label):\n labels_all = adj_label.view(-1).long()\n preds_all = (adj_rec > 0.5).view(-1).long()\n accuracy = (preds_all == labels_all).sum().float() / labels_all.size(0)\n return accuracy\n\n def reverse_edge(edges):\n reversed_edges = []\n for x,y in edges:\n reversed_edges.append((y,x))\n return reversed_edges\n print('='*88)\n print(str(exp)+' iteration....' + str(args.learning_rate))\n print('='*88)\n \n all_time =0\n # train model\n for epoch in range(args.num_epoch):\n\n t = time.time()\n\n np.random.seed(args.edge_idx_seed)\n np.random.shuffle(train_edges)\n np.random.seed(args.edge_idx_seed)\n np.random.shuffle(train_false_edges)\n\n train_edges_part = train_edges[:args.subsample_number]\n train_false_edges_part = train_false_edges[:args.subsample_number]\n\n # train_edges_part = get_train_edges_parts(train_edges, epoch)\n # train_false_edges_part = get_train_edges_parts(train_false_edges, epoch)\n\n # train_edges_part = np.concatenate((get_train_edges_parts(train_edges, epoch), reverse_edge(get_train_edges_parts(train_edges, epoch))))\n # train_false_edges_part = np.concatenate((get_train_edges_parts(train_false_edges, epoch), reverse_edge(get_train_edges_parts(train_false_edges, epoch))))\n\n model_adj_norm.train()\n\n\n A_pred = model_adj_norm(features, train_edges_part, train_false_edges_part)\n optimizer.zero_grad()\n\n loss = log_lik = norm*F.binary_cross_entropy(A_pred.view(-1), adj_label.view(-1))\n\n if args.model == 'VGAE' or args.model == 'VGAE2' or args.model =='NVGF':\n kl_divergence = 0.5/ A_pred.size(0) * (1 + 2*model_adj_norm.layer.logstd - model_adj_norm.layer.mean**2 - torch.exp(model_adj_norm.layer.logstd)).sum(1).mean()\n loss -= kl_divergence\n\n loss.backward()\n optimizer.step()\n\n train_acc = get_acc(A_pred,adj_label)\n time_elapsed = time.time() - t\n all_time += time_elapsed\n with torch.no_grad():\n A_pred = model_adj_norm(features, val_edges, val_edges_false)\n val_roc, val_ap = get_scores(val_edges, val_edges_false, A_pred.cpu())\n print(\"Epoch:\", '%04d' % (epoch + 1), \"train_loss=\", \"{:.5f}\".format(loss.item()),\n \"train_acc=\", \"{:.5f}\".format(train_acc), \"val_roc=\", \"{:.5f}\".format(val_roc),\n \"val_ap=\", \"{:.5f}\".format(val_ap),\n \"time=\", \"{:.5f}\".format(time_elapsed))\n if (epoch + 1) % 20 == 0:\n with torch.no_grad():\n A_pred = model_adj_norm(features, test_edges, test_edges_false)\n test_roc, test_ap = get_scores(test_edges, test_edges_false, A_pred.cpu())\n epoch_test_performance[(epoch+1)].append(test_roc)\n epoch_valid_performance[(epoch+1)].append(val_roc)\n\n print(args.model + \" End of training!\", \"test_roc=\", \"{:.5f}\".format(test_roc),\n \"test_ap=\", \"{:.5f}\".format(test_ap)) \n\n with torch.no_grad():\n A_pred = model_adj_norm(features, test_edges, test_edges_false)\n test_roc, test_ap = get_scores(test_edges, test_edges_false, A_pred.cpu())\n print(\"End of training!\", \"test_roc=\", \"{:.5f}\".format(test_roc),\n \"test_ap=\", \"{:.5f}\".format(test_ap))\n\n auc_list.append(test_roc)\n ap_list.append(test_ap)\n\n\n\nmean_roc, ste_roc = np.mean(auc_list), np.std(auc_list)/(10**(1/2))\nmean_ap, ste_ap = np.mean(ap_list), np.std(ap_list)/(10**(1/2))\n\nroc = '{:.1f}'.format(mean_roc*100.0)+'+'+'{:.2f}'.format(ste_roc*100.0).strip(' ')\nap = '{:.1f}'.format(mean_ap*100.0)+'+'+'{:.2f}'.format(ste_ap*100.0).strip(' ')\n\nprint('model= '+ str(args.model)) \nprint('dataset=' + str(args.dataset))\nprint('learning rate= '+ str(args.learning_rate))\nprint('epoch= '+ str(args.num_epoch))\nprint('subsample_number='+ str(args.subsample_number))\nprint('hidden1_dim='+str(args.hidden1_dim))\n\nprint('\\nGAE')\nprint(roc)\nprint(ap)\nprint()\n\nepoch_test_performance_list = []\nfor key,val in epoch_test_performance.items():\n # print(key + ':' + np.mean(val))\n epoch_test_performance_list.append((key, np.mean(val)))\n\nsorted_by_second = sorted(epoch_test_performance_list, key=lambda tup: tup[1],reverse=True)\nprint('test=',sorted_by_second)\n\nepoch_valid_performance_list = []\nfor key,val in epoch_valid_performance.items():\n # print(key + ':' + np.mean(val))\n epoch_valid_performance_list.append((key, np.mean(val)))\n\nsorted_by_second = sorted(epoch_valid_performance_list, key=lambda tup: tup[1],reverse=True)\nprint('valid=',sorted_by_second)\n","sub_path":"unipartite_link_prediction/neural_decoder.py","file_name":"neural_decoder.py","file_ext":"py","file_size_in_byte":8711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"536405312","text":"from schema import exceptions\n\n\nclass Status():\n ERROR = 500\n INVALID_FIELDS = 501\n FIELD_VALUE_ALREADY_USED = 502\n KEY_VALUE_ALREADY_USED = 503\n NOT_FOUND = 400\n OK = 200\n\n\nclass Response():\n \"\"\"Response\n\n The Response class provides an envelop for the messages that are going from\n the Schema and the Table. They ensure the data is in good standing (and if\n not, they provide context around the errors.)\n\n \"\"\"\n\n def __init__(self, status, message, errors=None):\n \"\"\"Response constructor.\n\n See:\n `create_error_response` and `create_success_response` for\n shortcuts.\n\n Args:\n status (int): The status of the Response.\n message: The message of the response. The message can contain any\n datastructures (dictionary, set, list)\n errors (list): The errors (if some have occured.)\n \"\"\"\n\n self.status = status\n self.errors = errors or {}\n self.message = message or {}\n self.formatted_message = None\n\n def __getattr__(self, key):\n \"\"\"Shortcut to access properties on the response message.\n\n If the response message (and only if the response message is a\n dictionary), this method provides a shortcut to access its properties.\n\n Raises:\n FieldException: If the response format is not a dictionary.\n\n Args:\n key (string): The key to get.\n\n Return:\n The value for this specific key (and if it does not exist the\n default value.)\n \"\"\"\n\n if not self.formatted_message and isinstance(self.message, dict):\n self.formatted_message = self.message\n elif not self.formatted_message:\n try:\n self.formatted_message = dict(self.message)\n except:\n pass\n\n if self.formatted_message:\n return self.formatted_message.get(key)\n\n raise exceptions.RESPONSE_FORMAT_ATTRIBUTES_UNAVAILABLE\n\n @property\n def success(self):\n return self.status == Status.OK\n\n\ndef create_error_response(errors=None, message=None):\n \"\"\"Create an error response.\n\n Args:\n errors (dict): List of errors (if any.)\n message: Message that will be provided as part of the response\n (optional.)\n Return:\n `Response`: The error response.\n \"\"\"\n\n return Response(\n status=Status.ERROR,\n errors=errors,\n message=message)\n\n\ndef create_success_response(message=None):\n \"\"\"Create a success response.\n\n Args:\n message: The response from the schema (optional.)\n Return:\n `Response`: a successful response.\n \"\"\"\n\n return Response(\n status=Status.OK,\n message=message)\n","sub_path":"schema/response.py","file_name":"response.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"175610253","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nclass Radar(object):\n\n def __init__(self, fig, titles, label, rect=None):\n if rect is None:\n rect = [0.05, 0.15, 0.95, 0.75]\n\n self.n = len(titles)\n self.angles = [a if a <=360. else a - 360. for a in np.arange(90, 90+360, 360.0/self.n)]\n self.axes = [fig.add_axes(rect, projection=\"polar\", label=\"axes%d\" % i) \n for i in range(self.n)]\n\n self.ax = self.axes[0]\n \n # Show the labels\n self.ax.set_thetagrids(self.angles, labels=titles, fontsize=14, weight=\"bold\", color=\"black\")\n\n for ax in self.axes[1:]:\n ax.patch.set_visible(False)\n ax.grid(False)\n ax.xaxis.set_visible(False)\n self.ax.yaxis.grid(False)\n\n for ax, angle in zip(self.axes, self.angles):\n ax.set_rgrids(range(1, 6), labels=label, angle=angle, fontsize=12)\n # hide outer spine (circle)\n ax.spines[\"polar\"].set_visible(False)\n ax.set_ylim(0, 6)\n ax.xaxis.grid(True, color='black', linestyle='-', zorder=1)\n\n # draw a line on the y axis at each label\n ax.tick_params(axis='y', pad=0, left=True, length=6, width=1, direction='inout')\n\n def decorate_ticks(self, axes):\n for idx, tick in enumerate(axes.xaxis.get_major_ticks()):\n # get the gridline\n gl = tick.gridline\n \n gl.set_marker('o')\n gl.set_markersize(15)\n if idx == 0:\n # print('tick properties:')\n # plt.getp(tick) \n # get the gridline\n gl = tick.gridline\n # print('grid properties:')\n # plt.getp(gl)\n\n gl.set_markerfacecolor('#003399')\n elif idx == 1:\n gl.set_markerfacecolor('#336666')\n elif idx == 2:\n gl.set_markerfacecolor('#336699')\n elif idx == 3:\n gl.set_markerfacecolor('#CC3333')\n elif idx == 4:\n gl.set_markerfacecolor('#CC9933')\n # this doesn't get used. The center doesn't seem to be different than 5\n else:\n gl.set_markerfacecolor('#CC0033')\n\n if idx == 0 or idx == 3:\n tick.set_pad(10)\n else:\n tick.set_pad(30)\n \n # set the center marker to white\n axes.plot(0, 0, 'h', markersize=15, color='#ffffff')\n\n def plot(self, values, *args, **kw):\n angle = np.deg2rad(np.r_[self.angles, self.angles[0]])\n values = np.r_[values, values[0]]\n self.ax.plot(angle, values, *args, **kw)\n\nfig = plt.figure(1)\n\ntitles = ['TG01', 'TG02', 'TG03', 'TG04', 'TG05', 'TG06']\nlabel = list(\"ABCDE\")\n\nradar = Radar(fig, titles, label)\nradar.plot([3.75, 3.25, 3.0, 2.75, 4.25, 3.5], \"-\", linewidth=2, color=\"b\", alpha=.7, label=\"Data01\")\nradar.plot([3.25, 2.25, 2.25, 2.25, 1.5, 1.75],\"-\", linewidth=2, color=\"r\", alpha=.7, label=\"Data02\")\n\nradar.decorate_ticks(radar.ax)\n\n# this avoids clipping the markers below the thetagrid labels\nradar.ax.xaxis.grid(clip_on = False)\n\nradar.ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.10),\n fancybox=True, shadow=True, ncol=4)\n\nplt.show()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"44555772","text":"import socket\nimport wikipedia\nimport time\nimport pickle\nimport random\nimport os\nfrom espeak import espeak\n\nimport install\nimport more\n\ndef line():\n print('----------') \ndef say(text):\n os.system(\"espeak -s 150 -w out.wav '\"+(text)+\"' && aplay out.wav\")\n\ntry:\n username = pickle.load( open(\"username.jab\", \"rb\") )\nexcept:\n say(\"Who are you?\")\n install.us()\n line()\n username = pickle.load( open(\"username.jab\", \"rb\") )\n \ntry:\n dic = pickle.load( open(\"diction.jab\", \"rb\") )\nexcept:\n install.diction()\n dic = pickle.load( open(\"diction.jab\", \"rb\") )\n\n\nnone = [\"WhAt?\", \"Error, I am too boring\", \"I am tired, this is a lie\", \"LOL\", \"Whats Up? The sky\", \"I am bored...\", \"I have not expressions\", \"The cake is a lie!\"]\n\n\nwhile True:\n found = []\n ask = input(\"==> \")\n ask = ask.lower()\n ask = ask.split()\n final = more.extra(ask)\n if final == \"NULL\":\n for i in ask:\n if i in dic:\n found.append(i)\n if len(found) > 0:\n final = random.choice(dic[random.choice(found)])\n print(final)\n say(final)\n line()\n\n else:\n final = random.choice(none)\n print(final)\n say(final)\n else:\n print(final)\n say(final)\n \n \n\n\n","sub_path":"Main/JAB.py","file_name":"JAB.py","file_ext":"py","file_size_in_byte":1307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"371561245","text":"import sys\nimport io\nfrom selenium import webdriver\n\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')\n\ndriver = webdriver.PhantomJS('./phantomjs/bin/phantomjs')\n\ndriver.implicitly_wait(5)\n\ndriver.get('https://google.com')\n\ndriver.save_screenshot(\"F:/Website1.png\")\n\n\ndriver.implicitly_wait(5)\n\ndriver.get('https://www.daum.net')\n\ndriver.save_screenshot(\"F:/Website2.png\")\ndriver.quit()\n","sub_path":"section3/3-6(all)/3-6-1.py","file_name":"3-6-1.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"453529662","text":"#!/usr/bin/env python3\n\n# Problem: https://dsa.cs.tsinghua.edu.cn/oj/problem.shtml?id=5094\n\nN = 100005\n\n# Stack:栈\n# top:栈顶位置\nStack = ['' for i in range(N)]\ntop = 0\n\n\ndef push(name):\n global top\n if top >= N:\n # stack full\n return None\n\n Stack[top] = name\n top += 1\n\n\ndef pop():\n global top\n if top == 0:\n # stack empty\n return None\n\n top -= 1\n return Stack[top]\n\n\ndef query(pos):\n if pos > top or pos <= 0:\n return None\n\n return Stack[pos-1]\n\n\nn = int(input())\nfor _ in range(n):\n tmp = input().split(' ')\n op = int(tmp[0])\n if op == 1:\n name = tmp[1].strip('\\n')\n push(name)\n elif op == 2:\n print(pop())\n else:\n pos = int(tmp[1])\n print(query(pos))","sub_path":"TsinghuaOnlineJudge/oj_stack.py","file_name":"oj_stack.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"398797796","text":"from sklearn.cluster import KMeans\nimport tensorflow as tf\nimport numpy as np\nfrom generative_models.vae import VAE\nfrom analysis.encode_decode import decode\nimport math\nfrom matplotlib import pyplot as plt\nfrom analysis import Cluster\nfrom analysis import ClusterGroup\nfrom analysis import ManualAnnotation\n\n\ndef decode_latent_vectors(cluster_centers, exp_config):\n tf.reset_default_graph()\n with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:\n model = VAE(sess,\n epoch=1,\n batch_size=exp_config.BATCH_SIZE,\n z_dim=exp_config.Z_DIM,\n dataset_name=exp_config.dataset_name,\n beta=exp_config.beta,\n num_units_in_layer=exp_config.num_units,\n log_dir=exp_config.LOG_PATH,\n checkpoint_dir=exp_config.TRAINED_MODELS_PATH,\n result_dir=exp_config.PREDICTION_RESULTS_PATH\n )\n z = np.zeros([cluster_centers.shape[0], exp_config.Z_DIM])\n\n for i in range(cluster_centers.shape[0]):\n z[i, :] = cluster_centers[i]\n decoded_images = decode(model, z, exp_config.BATCH_SIZE)\n return decoded_images\n\n\ndef cluster_and_decode_latent_vectors(num_clusters, latent_vectors, exp_config):\n kmeans = KMeans(n_clusters=num_clusters)\n cluster_labels = kmeans.fit_predict(latent_vectors)\n cluster_centers = kmeans.cluster_centers_\n decoded_images = decode_latent_vectors(cluster_centers, exp_config)\n\n return decoded_images, cluster_centers, cluster_labels\n\n\ndef display_cluster_center_images(decoded_images,\n image_filename,\n cluster_centers\n ):\n colormap = \"Greys\"\n fig = plt.figure()\n fig.tight_layout()\n num_cols = 4\n num_clusters = cluster_centers.shape[0]\n num_rows = math.ceil(num_clusters / num_cols)\n # fig.suptitle(\n # f\"Decoded Cluster Centers. \\nClustered the latent vectors of training set N_3={exp_config.num_units[2]}\"\n # f\" z_dim={exp_config.Z_DIM} run_id={run_id + 1}\")\n for i in range(cluster_centers.shape[0]):\n ax = fig.add_subplot(num_rows, num_cols, i + 1)\n ax.imshow(np.squeeze(decoded_images[i]), cmap=colormap)\n plt.savefig(image_filename,\n bbox=\"tight\",\n pad_inches=0)\n\n\n# Given a cluster_num, return the cluster object and ClusterGroup which it belongs to\ndef get_cluster(cluster_num,\n cluster_group_dict):\n for cluster_group_name, cluster_group in cluster_group_dict.items():\n cluster = cluster_group.get_cluster(cluster_num)\n if cluster is not None:\n return cluster_group, cluster\n\n\ndef assign_manual_label_and_confidence(df,\n manual_annotation_dict,\n dist_to_conf,\n cluster_group_dict,\n cluster_column_name_2\n ):\n df[\"manual_annotation\"] = np.ones(df.shape[0]) * -1\n df[\"manual_annotation_confidence\"] = np.zeros(df.shape[0])\n df[\"distance_to_confidence\"] = np.zeros(df.shape[0])\n manual_labels = manual_annotation_dict[\"manual_labels\"]\n cluster_labels = np.asarray(manual_annotation_dict[\"cluster_labels\"])\n\n num_clusters = len(manual_labels)\n for annotate_cluster in range(num_clusters):\n distance_df = df[\"distance_{}\".format(annotate_cluster)]\n manual_label = manual_labels[annotate_cluster]\n _manual_confidence = manual_annotation_dict[\"manual_confidence\"][annotate_cluster]\n if isinstance(manual_label, tuple) or isinstance(manual_label, list):\n _, cluster = get_cluster(annotate_cluster, cluster_group_dict)\n for _cluster in cluster.next_level_clusters[\"good_clusters\"]:\n _distance_df = df[f\"distance_level_2_{cluster.id}_{_cluster.id}\"]\n _manual_label = _cluster.manual_annotation.label\n if isinstance(_manual_label, tuple) or isinstance(_manual_label, list):\n # TODO add this code\n pass\n elif _manual_label != -1:\n indices = np.where((np.asarray(cluster_labels) == cluster.id)\n & (df[cluster_column_name_2].values == _cluster.id))[0]\n df[\"manual_annotation\"].iloc[indices] = _manual_label\n _dist = _distance_df.iloc[indices]\n df[\"manual_annotation_confidence\"].iloc[indices] = _cluster.manual_annotation.confidence * dist_to_conf(_dist)\n df[\"distance_to_confidence\"].iloc[indices] = dist_to_conf(_dist)\n elif manual_label != -1:\n print(\"Manual Label\", manual_label)\n indices = np.where(cluster_labels == annotate_cluster)\n df[\"manual_annotation\"].iloc[indices] = manual_label\n _, cluster = get_cluster(annotate_cluster, cluster_group_dict)\n print(df[df[\"manual_annotation\"] == manual_label].shape, cluster.details[\"cluster_data_frame\"].shape)\n num_correct = df[(manual_label == df[\"manual_annotation\"]) & (df[\"label\"] == manual_label)].shape[0]\n print(\"Num correct={}\".format(num_correct))\n\n percentage_correct = 100 * num_correct / df[df[\"manual_annotation\"] == manual_label].shape[0]\n print(f\"Cluster {annotate_cluster} Manual Label {manual_label} Percentage correct {percentage_correct}\")\n dist = distance_df.iloc[indices]\n df[\"manual_annotation_confidence\"].iloc[indices] = _manual_confidence * dist_to_conf(dist)\n df[\"distance_to_confidence\"].iloc[indices] = dist_to_conf(dist)\n else:\n print(\"unknown\")\n # unknown, check if second level clustering is done or not\n _, cluster = get_cluster(annotate_cluster, cluster_group_dict)\n print(type(cluster.next_level_clusters))\n print(list(cluster.next_level_clusters.keys()))\n\n for cluster_group_name, cluster_group in cluster.next_level_clusters.items():\n for _cluster in cluster_group:\n _distance_df = df[f\"distance_level_2_{cluster.id}_{_cluster.id}\"]\n _manual_label = _cluster.manual_annotation.label\n if isinstance(_manual_label, tuple) or isinstance(_manual_label, list):\n # TODO add this code\n pass\n elif _manual_label != -1:\n print(\"Manual_label\", manual_label)\n indices = np.where((np.asarray(cluster_labels) == cluster.id)\n & (df[cluster_column_name_2].values == _cluster.id))[0]\n df[\"manual_annotation\"].iloc[indices] = _manual_label\n _dist = _distance_df.iloc[indices]\n df[\"manual_annotation_confidence\"].iloc[\n indices] = _cluster.manual_annotation.confidence * dist_to_conf(_dist)\n df[\"distance_to_confidence\"].iloc[indices] = dist_to_conf(_dist)\n print(\"********************************\")\n\n\ndef get_samples_for_cluster(df, cluster_num, cluster_column_name):\n _df = df[df[cluster_column_name] == cluster_num]\n return _df\n\n\n\"\"\"\nCreate groups of clusters based on manual label given to each cluster. Different categories of cluster group are\n1. impure\nContains impure clusters. impure cluster is a cluster where the cluster center have similarity with multiple labels,\neach with different confidence\n2. unknown\nThe user who annotated the label doesn't know the label, or it is an invalid data for the domain under consideration\n3. similar_labels\nThere are multiple clusters in the cluster group all of which has similar label\n4. good_clusters\nThere are multiple clusters all with different labels each with a different confidence level greater than a threshold\n4. average_clusters\nThere are multiple clusters all with different labels each with a different confidence level around 0.5\n5. low_confidence_clusters\nThere are multiple clusters all with different labels each with a different confidence level close to zero\n\"\"\"\n# TODO check how to do this with parameters to constructer\n# annotation_string = \"pure_cluster:Cluster number: {}\\nCluster center label:{}\\n Confidence: {}\"\n\n\ndef get_cluster_groups(manual_labels,\n manual_confidence,\n cluster_column_name,\n cluster_centers,\n cluster_labels,\n df,\n parent_indices=None):\n\n cluster_groups_dict = dict()\n for cluster_num, cluster_center_label in enumerate(manual_labels):\n if parent_indices is None:\n _df = get_samples_for_cluster(df, cluster_num, cluster_column_name)\n indices = np.where(df[cluster_column_name].values == cluster_num)\n else:\n _df = get_samples_for_cluster(df.iloc[parent_indices], cluster_num, cluster_column_name)\n indices = np.where(df[cluster_column_name].iloc[parent_indices].values == cluster_num)\n\n cluster_details = {\n \"cluster_centers\": cluster_centers[cluster_num],\n \"cluster_labels\": cluster_labels,\n \"indices\": indices, # Indices of this cluster elements in parent DataFrame\n \"cluster_data_frame\": _df,\n \"whole_data_frame\": df\n }\n if isinstance(cluster_center_label, tuple) or isinstance(cluster_center_label, list):\n # impure cluster\n # create an impure clusterGroup\n manual_annotation = ManualAnnotation(cluster_center_label,\n manual_confidence[cluster_num])\n cluster = Cluster(cluster_id=cluster_num,\n name=f\"cluster_{cluster_num}\",\n cluster_details=cluster_details,\n level=1,\n manual_annotation=manual_annotation)\n if \"impure_cluster\" in cluster_groups_dict.keys():\n cluster_groups_dict[\"impure_cluster\"].add_cluster(cluster)\n else:\n cluster_groups_dict[\"impure_cluster\"] = ClusterGroup(\"impure_cluster\", [cluster])\n elif cluster_center_label == -1:\n # unknown cluster\n manual_annotation = ManualAnnotation(cluster_center_label, manual_confidence[cluster_num])\n cluster = Cluster(cluster_id=cluster_num,\n name=f\"cluster_{cluster_num}\",\n cluster_details=cluster_details,\n level=1,\n manual_annotation=manual_annotation\n )\n if \"unknown_cluster\" in cluster_groups_dict.keys():\n cluster_groups_dict[\"unknown_cluster\"].add_cluster(cluster)\n else:\n cluster_groups_dict[\"unknown_cluster\"] = ClusterGroup(\"unknown_cluster\", [cluster])\n # unknown cluster\n else:\n # good/average/low confidence\n manual_annotation = ManualAnnotation(cluster_center_label, manual_confidence[cluster_num])\n cluster = Cluster(cluster_id=cluster_num,\n name=\"cluster_\".format(cluster_num),\n cluster_details=cluster_details,\n level=1,\n manual_annotation=manual_annotation)\n cluster_group_label = manual_annotation.get_label()\n if cluster_group_label in cluster_groups_dict.keys():\n cluster_groups_dict[cluster_group_label].add_cluster(cluster)\n else:\n cluster_groups_dict[cluster_group_label] = ClusterGroup(cluster_group_label,\n [cluster])\n return cluster_groups_dict\n","sub_path":"analysis/cluster_utils.py","file_name":"cluster_utils.py","file_ext":"py","file_size_in_byte":12133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"238570429","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render\n\n# Create your views here.\nfrom .models import Docs\n\ndef index(request):\n num_docs = Docs.objects.all().count()\n return render(\n\trequest,\n\t'index.html',\n\tcontext={'num_docs':num_docs},\n )\n","sub_path":"elearning/xblock_development/sandbox/dbdocs/myauth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"101353191","text":"from frames.VelocityFrame import VelocityFrame\nimport requests\nimport resources as rs\nimport json\n\n\nclass SprintData(VelocityFrame):\n \"\"\"\n Encapsulates Data from all sprints within given object as a DataFrame\n \"\"\"\n def __init__(self, board_id):\n super().__init__()\n sprint_obj = self.get_data(board_id)\n for i, sprint in enumerate(sprint_obj['sprints']):\n sprint_id = str(sprint[\"id\"])\n name = sprint[\"name\"]\n committed = sprint_obj[\"velocityStatEntries\"][sprint_id][\"estimated\"][\"value\"]\n completed = sprint_obj[\"velocityStatEntries\"][sprint_id][\"completed\"][\"value\"]\n self.add(name, committed, completed)\n\n self.df = self.df.set_index(\"name\")\n\n def get_data(self, board_id):\n return json.loads(requests.get(rs.server + rs.chart_endpoint + str(board_id),\n auth=(rs.user_name, rs.api_token)).text)\n","sub_path":"python/frames/SprintData.py","file_name":"SprintData.py","file_ext":"py","file_size_in_byte":930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"144885315","text":"# 62 ms >87.42%\n# 17.3 mb <52.58%\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def addOneRow(self, root: Optional[TreeNode], val: int, depth: int) -> Optional[TreeNode]:\n if depth == 1:\n newRoot = TreeNode(val, root, None)\n return newRoot\n else:\n self.helper(root, val, depth)\n return root\n def helper(self, root, val, depth):\n if depth < 2:\n return\n if root == None:\n return\n if depth == 2:\n tempLeft = root.left\n tempRight = root.right\n root.left = TreeNode(val, tempLeft, None)\n root.right = TreeNode(val, None, tempRight)\n else:\n self.helper(root.left, val, depth-1)\n self.helper(root.right, val, depth-1)\n \n","sub_path":"leetcodl/add_row_tree.py","file_name":"add_row_tree.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"268183265","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.4 (3310)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/examples/python/generate_full_multiperiod_set.py\n# Compiled at: 2018-10-21 08:00:46\n# Size of source mod 2**32: 3526 bytes\n\"\"\" Example of using the transitionMatrix generator methods to generate a full multi-period matrix set\nThe input data are processed Standard and Poor's matrices for a selection of cumulative observation points\nNB: This example requires a substantial amount of custom code!\n\n\"\"\"\nfrom scipy.linalg import expm\nimport transitionMatrix as tm\nfrom transitionMatrix import source_path\ndataset_path = source_path + 'datasets/'\nprint('> Loading multi-period transitional matrices (cumulative mode) from json file')\nSnP_Set0 = tm.TransitionMatrixSet(json_file=dataset_path + 'sp_NR_adjusted.json', temporal_type='Cumulative')\nprint('> Validate')\nprint(SnP_Set0.validate())\nprint('> Set the timesteps at which we have matrix observations')\nSnP_Set0.timesteps = [\n 1, 2, 3, 5, 7, 10]\nprint(SnP_Set0.timesteps)\ntimesteps = SnP_Set0.timesteps[(len(SnP_Set0.timesteps) - 1)]\nSnP = tm.TransitionMatrixSet(dimension=8, periods=timesteps)\nprint('> Fill in the gaps between periods')\nt_list = SnP_Set0.timesteps\nts = 1\nSnP.entries[ts - 1] = SnP_Set0.entries[0]\nfor k in t_list:\n i = t_list.index(k)\n if i < len(t_list) - 1:\n gap = t_list[(i + 1)] - t_list[i]\n if gap > 1:\n lm = SnP_Set0.entries[i]\n lm.fix_rowsums()\n rm = SnP_Set0.entries[(i + 1)]\n rm.fix_rowsums()\n q = rm * lm.I\n q.fix_rowsums()\n q.fix_negativerates()\n G = q.generator(t=gap)\n for gap_period in range(1, gap + 1):\n gm = expm(gap_period * G)\n cm = gm * lm\n cm.fix_negativerates()\n ts += 1\n SnP.entries[ts - 1] = cm\n\n else:\n ts += 1\n SnP.entries[ts - 1] = SnP_Set0.entries[(i + 1)]\n else:\n ts = timesteps\n SnP.entries[ts - 1] = SnP_Set0.entries[i]\n\nSnP.timesteps = t_list\nSnP.temporal_type = 'Cumulative'\nSnP.print(accuracy=4)\nSnP.to_json(dataset_path + 'sp_multiperiod.json', accuracy=8)","sub_path":"pycfiles/transitionMatrix-0.4.0-py3.4/generate_full_multiperiod_set.cpython-34.py","file_name":"generate_full_multiperiod_set.cpython-34.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"468387226","text":"import socket\nimport time\nfrom unittest import TestCase\n\n\nclass TestCache(TestCase):\n\n def test_pool(self):\n from memcachepool.cache import UMemcacheCache\n\n # creating the cache class\n cache = UMemcacheCache('127.0.0.1:11211', {})\n\n # simple calls\n cache.set('a', '1')\n self.assertEqual(cache.get('a'), '1')\n\n # should support any type and deal with serialization\n # like python-memcached does\n cache.set('a', 1)\n self.assertEqual(cache.get('a'), 1)\n cache.delete('a')\n self.assertEqual(cache.get('a'), None)\n\n def test_many(self):\n # make sure all the 'many' APIs work\n from memcachepool.cache import UMemcacheCache\n\n # creating the cache class\n cache = UMemcacheCache('127.0.0.1:11211', {})\n\n cache.set_many({'a': 1, 'b': 2})\n\n res = cache.get_many(['a', 'b']).values()\n self.assertTrue(1 in res)\n self.assertTrue(2 in res)\n\n cache.delete_many(['a', 'b'])\n self.assertEqual(cache.get_many(['a', 'b']), {})\n\n def test_incr_decr(self):\n # Testing incr and decr operations\n from memcachepool.cache import UMemcacheCache\n\n # creating the cache class\n cache = UMemcacheCache('127.0.0.1:11211', {})\n cache.set('a', 1)\n cache.incr('a', 1)\n self.assertEquals(cache.get('a'), 2)\n cache.decr('a', 1)\n self.assertEquals(cache.get('a'), 1)\n\n def test_types(self):\n # Testing if correct types are returned\n from memcachepool.cache import UMemcacheCache\n\n # creating the cache class\n cache = UMemcacheCache('127.0.0.1:11211', {})\n cache.set('a', int(1))\n self.assertEquals(cache.get('a'), 1)\n self.assertTrue(isinstance(cache.get('a'), int))\n\n cache.set('a', long(1))\n self.assertEquals(cache.get('a'), 1)\n self.assertTrue(isinstance(cache.get('a'), long))\n\n def test_loadbalance(self):\n from memcachepool.cache import UMemcacheCache\n\n # creating the cache class with two backends (one is off)\n params = {'SOCKET_TIMEOUT': 1, 'BLACKLIST_TIME': 1}\n cache = UMemcacheCache('127.0.0.1:11214;127.0.0.2:11213', params)\n\n # the load balancer should blacklist both IPs.\n # and return an error\n self.assertRaises(socket.error, cache.set, 'a', '1')\n self.assertTrue(len(cache._blacklist), 2)\n\n # wait for two seconds.\n time.sleep(1.1)\n\n # calling _pick_server should purge the blacklist\n cache._pick_server()\n self.assertEqual(len(cache._blacklist), 0)\n","sub_path":"memcachepool/tests/test_cache.py","file_name":"test_cache.py","file_ext":"py","file_size_in_byte":2625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"544167284","text":"def ordenarShell(arreglo): \n\n\tarreglo_size = len(arreglo) \n\tbrecha = int(arreglo_size/2) #división entera\n\t\n\twhile brecha > 0: \t\t\n\t\tfor recorrido in range(brecha,arreglo_size): \t\t\t\n\t\t\tbuffer = arreglo[recorrido] \n\t\t\tindice = recorrido \n\t\t\twhile indice >= brecha and arreglo[indice-brecha] > buffer: \n\t\t\t\tarreglo[indice] = arreglo[indice-brecha] \n\t\t\t\tindice -= brecha \n\t\t\tarreglo[indice] = buffer \n\t\t\t\n\t\tbrecha = int(brecha/2) #división entera\n\n# Función principal \nif __name__ == \"__main__\":\n\tdatos = [8, 5, 3, 9, 1, 4, 7]\n\tarreglo_size = len(datos) \n\tprint (\"Arreglo original: \" + str(datos)) \n\tordenarShell(datos) \n\tprint (\"Arreglo original: \" + str(datos)) \n\n\n\n","sub_path":"python/2.2 Algoritmos de Ordenamiento/shellsort/ShellSortTest.py","file_name":"ShellSortTest.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"503210363","text":"import os, sys\nfrom sys import argv\nimport subprocess\n# ffmpeg -i input.avi -vcodec copy -acodec copy -ss 00:00:00 -t 00:30:00 output1.avi \\\n# -vcodec copy -acodec copy -ss 00:30:00 -t 00:30:00 output2.avi\n\nffmpeg = r\"E:/ydl/ffmpeg.exe\"\n\ninp = argv[1]\n\nfolder = os.path.dirname(inp)\nfilename = os.path.basename(inp)\nprint('folder', folder)\nprint('filename', filename)\n\n\n\ndef split_video():\n args = [ffmpeg]\n\n args_things1 = \"-vcodec copy -acodec copy -ss 00:00:00 -t 03:30:00\".split()\n args_things2 = \"-vcodec copy -acodec copy -ss 03:30:00 -t 07:10:00\".split()\n args += ['-i', inp]\n args += args_things1 + [inp+'-split1.mp4']\n\n args += ['-i', inp]\n args += args_things2 + [inp+'-split2.mp4']\n\n subprocess.run(args)\n\ndef split_video_short():\n args = [ffmpeg]\n\n args_things1 = \"-vcodec copy -acodec copy -ss 03:00:00 -t 03:10:00\".split()\n args += ['-i', inp]\n args += args_things1 + [inp+'-split_short.mp4']\n\n subprocess.run(args)\n\n\ndef split_video_args():\n time_ranges = [tuple(a.split(',')) for a in argv[2:]]\n print(time_ranges)\n # exit()\n args = [ffmpeg]\n args += ['-i', inp]\n\n # args_things1 = (\"-vcodec copy -acodec copy -ss %s:00 -t %s:00\"%()).split()\n for t_range in time_ranges:\n args_things1 = (\"-vcodec copy -acodec copy -ss %s:00 -t %s:00\"%t_range).split()\n print(args_things1)\n s = (\"%s_%s\" % t_range).replace(':','-')\n args += args_things1 + [inp+'-%s.mp4'%s]\n print(args)\n # exit()\n subprocess.run(args)\n\n\n\n\n# split_video_short()\nsplit_video_args()","sub_path":"_projlab/ffmpeg/ffmpeg-split.py","file_name":"ffmpeg-split.py","file_ext":"py","file_size_in_byte":1566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"200257727","text":"from airflow.exceptions import AirflowException\nfrom airflow.contrib.hooks.gcs_hook import GoogleCloudStorageHook\nfrom googleapiclient.errors import HttpError\nfrom googleads import adwords\nfrom googleads import oauth2\nfrom googleads.errors import AdWordsReportBadRequestError, AdWordsReportError, GoogleAdsServerFault\n\nimport pandas as pd\nfrom datetime import date, timedelta\nimport os\n\n\nclass GoogleAdsBaseHook():\n\n\t'''\n\tInterations with the Google Ads API \n\n\t'''\n\n\tdef __init__(self, path_to_keyfile, service_account_user,developer_token,client_customer_id):\n\n\t\t\n\t\tself.path_to_keyfile = path_to_keyfile\n\n\t\tself.service_account_user = service_account_user\n\t\tself.developer_token = developer_token\n\t\tself.client_customer_id = client_customer_id\n\n\n\n\tdef authenticate(self):\n\n\t\toauth2_client = oauth2.GoogleServiceAccountClient(self.path_to_keyfile,\n\t\t oauth2.GetAPIScope('adwords'), sub=self.service_account_user)\n\n\t\tclient = adwords.AdWordsClient(self.developer_token, oauth2_client, client_customer_id=self.client_customer_id)\n\t\t\n\t\tcustomer_service = client.GetService('CustomerService',\n\t\t version='v201809')\n\t\tcustomers = customer_service.getCustomers()\n\n\t\tprint('You are logged in as a user with access to the following customers:')\n\n\t\tfor customer in customers:\n\t\t\tprint('\\t%s' % customer['customerId'])\n\n\t\treturn client\n\n\n\n\tdef get_customers(self):\n\n\t\tclient = self.authenticate()\n\t\ttry:\n\t\t\tcustomers = client.GetService('CustomerService', version='v201809').getCustomers()\n\n\t\t\tfor customer in customers:\n\t\t\t\tprint(customer)\n\t\texcept GoogleAdsServerFault as e:\n\t\t\traise AirflowException('Customer not found please check the client_customer_id is valid. Error was %s', e.content)\n\n\n\tdef get_account_performance_report(self, fields, report_type, startDate, endDate):\n\n\t\tclient = self.authenticate()\n\n\t\tpass\n\n\n\tdef get_performance_report(self, fields, report_type, startDate, endDate, filename, bucket):\n\n\t\tclient = self.authenticate()\n\n\t\treport_downloader = client.GetReportDownloader(version=\"v201809\")\n\t\tif report_type == \"SEARCH_QUERY_PERFORMANCE_REPORT\":\n\t\t\ttry:\n\t\t\t report_query = (adwords.ReportQueryBuilder()\n\t\t\t .Select(*fields)\n\t\t\t .From(report_type)\n\t\t\t .Where('Impressions').GreaterThan('0')\n\t\t\t .During(start_date=startDate, end_date=endDate)\n\t\t\t .Build())\n\t\t\t zero_impr = False\n\t\t\texcept AdWordsReportBadRequestError as e:\n\t\t\t\traise AirflowException('There was an error in the report request. You may be trying to access a report for a manager account. Error was %s', e)\n\n\n\t\telif report_type == \"KEYWORDS_PERFORMANCE_REPORT\":\n\t\t\ttry:\n\t\t\t report_query = (adwords.ReportQueryBuilder()\n\t\t\t .Select(*fields)\n\t\t\t .From(report_type)\n\t\t\t .Where('KeywordMatchType').EqualTo('EXACT')\n\t\t\t .During(start_date=startDate, end_date=endDate)\n\t\t\t .Build())\n\t\t\t zero_impr = True\n\t\t\texcept (AdWordsReportBadRequestError, AdWordsReportError) as e:\n\t\t\t\traise AirflowException('There was an error in the report request. You may be trying to access a report for a manager account. Error was %s', e)\n\t\telse:\n\t\t raise AirflowException('report_type not supported. Please see documentation')\n\n\t\ttry:\n\t\t\treport = report_downloader.DownloadReportAsStringWithAwql(report_query, 'CSV', skip_report_header=True,\n\t skip_column_header=False, skip_report_summary=True,\n\t include_zero_impressions=zero_impr)\n\t\texcept (AdWordsReportBadRequestError, AdWordsReportError) as e:\n\t\t\traise AirflowException('There was an error in the report request. You may be trying to access a report for a manager account. Error was %s', e)\n\t\n\t\tlocal_path = str(os.getcwd())\n\t\tlocal_file = filename.split('/')[-1]\n\t\twith open(local_path+'/'+local_file, 'w') as file:\n\t\t\tfor line in report:\n\t\t\t\tfile.write(line)\n\t\t\tfile.close()\n\n\t\tdf = pd.read_csv(local_path+'/'+local_file)\n\n\t\tdf.replace(\" --\", '', inplace=True)\n\n\t\tif \"Cost\" in df.columns.tolist():\n\t\t\tdf['Cost'] = df['Cost'] / 1000000.0\n\n\t\tdf.to_csv(local_path+'/'+local_file, index=False)\n\n\t\tgcs_hook = GoogleCloudStorageHook()\n\t\tresult = gcs_hook.upload(bucket=bucket, object=filename, filename=local_path+'/'+local_file)\n\n\n\t\tif result:\n\t\t\tprint('Report %s file uploaded to bucket %s', report_type, bucket)\n\t\t\n\t\t\tos.remove(local_path+'/'+local_file)\n\t\t\treturn 'gs://'+bucket+'/'+filename\n\t\t\tprint('DONE')\n\t\t\n\t\t\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"jelly-airflow/hooks/googleads_base_hook.py","file_name":"googleads_base_hook.py","file_ext":"py","file_size_in_byte":4501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"139229242","text":"import binascii\nimport hashlib\nimport sys\n\nimport requests\n\nif len(sys.argv) < 3:\n print(\"usage:\")\n print(\"python3 ./api_test.py \")\n sys.exit()\n\nuuid = sys.argv[1]\nauth = sys.argv[2]\n\nurl_base = 'http://localhost:8080'\nurl_sign = url_base + '/{}'.format(uuid)\nurl_sign_hash = url_base + '/{}/hash'.format(uuid)\nurl_vrfy = url_base + '/verify'.format(uuid)\nurl_vrfy_hash = url_base + '/verify/hash'.format(uuid)\n\nheader_auth = {'X-Auth-Token': auth}\nheader_bin = {'Content-Type': 'application/octet-stream'}\nheader_json = {'Content-Type': 'application/json'}\n\nmsg_json = '{\"data\":{\"H\":\"55\",\"T\":\"25.5\"}}'.encode()\nmsg_bin = \"test binary\".encode()\nmsg_hash = binascii.a2b_base64(\"dl/c6FzLMDdqtG/nKKxAlbx0mP+8IlLuiU9IhzF1838=\")\n\n# sign json\nprint(\"sign json: {}\".format(msg_json.decode()))\nr = requests.post(url=url_sign,\n headers={**header_auth, **header_json},\n data=msg_json)\nprint(\"response: ({}) {}\\n\".format(r.status_code, r.text))\n\n# verify json\nprint(\"verify json: {}\".format(msg_json.decode()))\nr = requests.post(url=url_vrfy,\n headers=header_json,\n data=msg_json)\nprint(\"response: ({}) {}\\n\".format(r.status_code, r.text))\n\n# sign binary\nprint(\"sign binary: {}\".format(msg_bin))\nprint(\"hash: {}\".format(binascii.b2a_base64(hashlib.sha256(msg_bin).digest()).decode().rstrip('\\n')))\nr = requests.post(url=url_sign,\n headers={**header_auth, **header_bin},\n data=msg_bin)\nprint(\"response: ({}) {}\\n\".format(r.status_code, r.text))\n\n# verify binary\nprint(\"verify binary: {}\".format(msg_bin))\nr = requests.post(url=url_vrfy,\n headers=header_bin,\n data=msg_bin)\nprint(\"response: ({}) {}\\n\".format(r.status_code, r.text))\n\n# sign hash\nprint(\"sign hash: {}\".format(binascii.b2a_base64(msg_hash).decode().rstrip('\\n')))\nr = requests.post(url=url_sign_hash,\n headers={**header_auth, **header_bin},\n data=msg_hash)\nprint(\"response: ({}) {}\\n\".format(r.status_code, r.text))\n\n# verify hash\nprint(\"verify hash: {}\".format(binascii.b2a_base64(msg_hash).decode().rstrip('\\n')))\nr = requests.post(url=url_vrfy_hash,\n headers=header_bin,\n data=msg_hash)\nprint(\"response: ({}) {}\\n\".format(r.status_code, r.text))\n","sub_path":"simulation/api_test.py","file_name":"api_test.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"32905945","text":"import time\n\nimport cv2.cv2 as cv2\nimport numpy as np\nfrom PyQt5.QtWidgets import QWidget, QPushButton, QFileDialog, QLabel\n\nimport matplotlib\nfrom matplotlib.figure import Figure\n\nmatplotlib.use('Qt5Agg')\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\n\n\nclass MatplotCanvasWidget(QWidget):\n\n def __init__(self):\n super(MatplotCanvasWidget, self).__init__()\n\n self.btn = QPushButton(\"Load Image\", self)\n\n self.btn.clicked.connect(self.load_image)\n self.btn.resize(100, 30)\n self.btn.move(10, 10)\n\n self.static_canvas = FigureCanvas(Figure(figsize=(5, 3)))\n self.static_canvas.setParent(self)\n self.static_canvas.resize(384, 256)\n self.static_canvas.move(10, 70)\n\n self._static_ax = self.static_canvas.figure.subplots()\n t = np.linspace(0, 10, 501)\n self._static_ax.plot(t, np.tan(t), \".\")\n self.static_canvas.draw()\n\n self.dynamic_canvas = FigureCanvas(Figure(figsize=(5, 3)))\n self.dynamic_canvas.setParent(self)\n self.dynamic_canvas.resize(384, 256)\n self.dynamic_canvas.move(500, 70)\n\n self._dynamic_ax = self.dynamic_canvas.figure.subplots()\n self._timer = self.dynamic_canvas.new_timer(\n 100, [(self._update_canvas, (), {})])\n self._timer.start()\n\n def _update_canvas(self):\n self._dynamic_ax.clear()\n t = np.linspace(0, 10, 101)\n # Shift the sinusoid as a function of time.\n self._dynamic_ax.plot(t, np.sin(t + time.time()))\n self._dynamic_ax.figure.canvas.draw()\n # self.addToolBar(QtCore.Qt.BottomToolBarArea,\n # NavigationToolbar(self.static_canvas, self))\n\n # self.creation_figure()\n # self.canvas.setParent(self)\n\n\n def load_image(self):\n fname, _ = QFileDialog.getOpenFileName(self, 'Open file', './images', \"Image files (*.jpg *.png)\")\n\n if len(fname) > 0:\n self.image = cv2.imread(fname)\n\n im_rgb = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)\n self._static_ax.clear()\n self._static_ax.imshow(im_rgb)\n\n self.static_canvas.draw()\n\n\n\n\n","sub_path":"python/OpenCVDemo/MatplotCanvasWidget.py","file_name":"MatplotCanvasWidget.py","file_ext":"py","file_size_in_byte":2276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"573132602","text":"from flask import Flask, render_template, request, send_file, redirect\nfrom mailmerge import MailMerge\nimport mammoth\nimport os\n\n\napp = Flask(__name__)\n\n@app.route(\"/\", methods=['GET', 'POST'])\ndef home():\n return render_template('index.html')\n\n@app.route(\"/tempo\", methods=['GET', 'POST'])\ndef tempo():\n return render_template('template.html')\n\n\n\n\n@app.route('/download', methods=['GET', 'POST'])\ndef downloadFile ():\n input_nr = request.form.get('nrInput')\n input_year = request.form.get('yearInput')\n input_month = request.form.get('monthInput')\n input_day = request.form.get('dayInput')\n input_name = request.form.get('nameInput')\n input_name1 = request.form.get('name1Input')\n input_personalno = request.form.get('personalnoInput')\n input_passportno = request.form.get('passportnoInput')\n input_area = request.form.get('areaInput')\n input_address = request.form.get('addressInput')\n input_price = request.form.get('priceInput')\n input_year1 = request.form.get('year1Input')\n input_month1 = request.form.get('month1Input')\n input_day1 = request.form.get('day1Input')\n input_day2 = request.form.get('day2Input')\n input_depositprice = request.form.get('depositpriceInput')\n\n template = \"input.docx\"\n document = MailMerge(template)\n\n document.merge(\n Nr=input_nr,\n Year=input_year,\n Month=input_month,\n Day=input_day,\n Name=input_name,\n Name1=input_name1,\n PersonalNO=input_personalno,\n PassportNO=input_passportno,\n Area=input_area,\n Address=input_address,\n Price=input_price,\n Year1=input_year1,\n Month1=input_month1,\n Day1=input_day1,\n Day2=input_day2,\n DepositPrice=input_depositprice\n )\n\n document.write('output.docx')\n path = \"output.docx\"\n\n if \"Template\" in request.form:\n return render_template('template.html')\n else:\n return send_file('output.docx', attachment_filename='output.docx')\n\n\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"89787348","text":"\nimport numpy as np\nimport scipy.io\nimport math\nimport matplotlib.pyplot as plt\nimport random as rd\nrd.seed(2018)\nnp.random.seed(2018)\n\nimport pandas as pd\nimport datetime as DT\nimport time\n\nfrom joblib import Parallel, delayed\nimport multiprocessing\nimport parmap\nfrom multiprocessing import Pool, freeze_support\nimport itertools\n\nfrom trainGD_EXP_Renorm import trainGD_EXP\nfrom trainGD_PWL_Renorm import trainGD_PWL\nfrom trainGD_QEXP_Renorm_New import trainGD_QEXP\nfrom trainGD_RAY_Renorm import trainGD_RAY\n\ninput_data = scipy.io.loadmat('4Kern_Renorm_10seq_T5000.mat')\n\neps = 0.1\n\nn_of_seq = 10\n\nresolution = 40\n\nllh_GD_EXP = np.array([])\nllh_GD_PWL = np.array([])\nllh_GD_QEXP = np.array([])\nllh_GD_RAY = np.array([])\n\nllh_GD_EXP_Renorm_alpha = np.array([])\nllh_GD_PWL_Renorm_K = np.array([])\nllh_GD_QEXP_Renorm_a = np.array([])\nllh_GD_RAY_Renorm_gamma = np.array([])\n\nllh_GD_EXP_Renorm_beta = np.array([])\nllh_GD_PWL_Renorm_c = np.array([])\nllh_GD_PWL_Renorm_p = np.array([])\nllh_GD_QEXP_Renorm_q = np.array([])\nllh_GD_RAY_Renorm_eta = np.array([])\n\nllh_GD_EXP_Renorm_alphabeta = np.array([])\nllh_GD_PWL_Renorm_Kc = np.array([])\nllh_GD_QEXP_Renorm_aq = np.array([])\nllh_GD_RAY_Renorm_gammaeta = np.array([])\n\nllh_GD_PWL_Renorm_Kp = np.array([])\n\nfor i in range(1,5):\n\n\tind_seq = 'Seq' + repr(i)\n\n\tprint(ind_seq)\n\n\tfor j in range(0,n_of_seq):\n\n\t\tprint(j)\n\n\t\tseq = input_data[ind_seq][j][0][0]\n\n\t\tEXP_Param = trainGD_EXP(seq,eps)\n\n\t\tPWL_Param = trainGD_PWL(seq,eps)\n\n\t\tQEXP_Param = trainGD_QEXP(seq,eps)\n\n\t\tRAY_Param = trainGD_RAY(seq,eps)\n\n\t\tllh_GD_EXP = np.append(llh_GD_EXP,EXP_Param['final_llh'])\n\t\tllh_GD_PWL = np.append(llh_GD_PWL,PWL_Param['final_llh'])\n\t\tllh_GD_QEXP = np.append(llh_GD_QEXP,QEXP_Param['final_llh'])\n\t\tllh_GD_RAY = np.append(llh_GD_RAY,RAY_Param['final_llh'])\n\n\t\tllh_GD_EXP_Renorm_alpha = np.append(llh_GD_EXP_Renorm_alpha,EXP_Param['llh_renorm_alpha'])\n\t\tllh_GD_PWL_Renorm_K = np.append(llh_GD_PWL_Renorm_K,PWL_Param['llh_renorm_K'])\n\t\tllh_GD_QEXP_Renorm_a = np.append(llh_GD_QEXP_Renorm_a,QEXP_Param['llh_renorm_alpha'])\n\t\tllh_GD_RAY_Renorm_gamma = np.append(llh_GD_RAY_Renorm_gamma,RAY_Param['llh_renorm_gamma'])\n\n\t\tllh_GD_EXP_Renorm_beta = np.append(llh_GD_EXP_Renorm_beta,EXP_Param['llh_renorm_beta'])\n\t\tllh_GD_PWL_Renorm_c = np.append(llh_GD_PWL_Renorm_c,PWL_Param['llh_renorm_c'])\n\t\tllh_GD_PWL_Renorm_p = np.append(llh_GD_PWL_Renorm_p,PWL_Param['llh_renorm_p'])\n\t\tllh_GD_QEXP_Renorm_q = np.append(llh_GD_QEXP_Renorm_q,QEXP_Param['llh_renorm_q'])\n\t\tllh_GD_RAY_Renorm_eta = np.append(llh_GD_RAY_Renorm_eta,RAY_Param['llh_renorm_eta'])\n\n\t\tllh_GD_EXP_Renorm_alphabeta = np.append(llh_GD_EXP_Renorm_alphabeta,EXP_Param['llh_renorm_sqrt'])\n\t\tllh_GD_PWL_Renorm_Kc = np.append(llh_GD_PWL_Renorm_Kc,PWL_Param['llh_renorm_Kc'])\n\t\tllh_GD_QEXP_Renorm_aq = np.append(llh_GD_QEXP_Renorm_aq,QEXP_Param['llh_renorm_sqrt'])\n\t\tllh_GD_RAY_Renorm_gammaeta = np.append(llh_GD_RAY_Renorm_gammaeta,RAY_Param['llh_renorm_sqrt'])\n\n\t\tllh_GD_PWL_Renorm_Kp = np.append(llh_GD_PWL_Renorm_Kp,PWL_Param['llh_renorm_Kp'])\n\n\n\t\t\nprint('llh_GD_EXP: ' + repr(llh_GD_EXP) + '\\n')\nprint('llh_GD_EXP_Renorm_alpha: ' + repr(llh_GD_EXP_Renorm_alpha) + '\\n')\nprint('llh_GD_EXP_Renorm_beta: ' + repr(llh_GD_EXP_Renorm_beta) + '\\n')\nprint('llh_GD_EXP_Renorm_alphabeta: ' + repr(llh_GD_EXP_Renorm_alphabeta) + '\\n')\n\nprint('llh_GD_PWL: ' + repr(llh_GD_PWL) + '\\n')\nprint('llh_GD_PWL_Renorm_K: ' + repr(llh_GD_PWL_Renorm_K) + '\\n')\nprint('llh_GD_PWL_Renorm_c: ' + repr(llh_GD_PWL_Renorm_c) + '\\n')\nprint('lllh_GD_PWL_Renorm_p: ' + repr(llh_GD_PWL_Renorm_p) + '\\n')\nprint('llh_GD_PWL_Renorm_Kc: ' + repr(llh_GD_PWL_Renorm_Kc) + '\\n')\nprint('llh_GD_PWL_Renorm_Kp: ' + repr(llh_GD_PWL_Renorm_Kp) + '\\n')\n\nprint('llh_GD_QEXP: ' + repr(llh_GD_QEXP) + '\\n')\nprint('llh_GD_QEXP_Renorm_a: ' + repr(llh_GD_QEXP_Renorm_a) + '\\n')\nprint('lllh_GD_QEXP_Renorm_q: ' + repr(llh_GD_QEXP_Renorm_q) + '\\n')\nprint('llh_GD_QEXP_Renorm_aq: ' + repr(llh_GD_QEXP_Renorm_aq) + '\\n')\n\nprint('llh_GD_RAY: ' + repr(llh_GD_RAY) + '\\n')\nprint('llh_GD_RAY_Renorm_gamma: ' + repr(llh_GD_RAY_Renorm_gamma) + '\\n')\nprint('llh_GD_RAY_Renorm_eta: ' + repr(llh_GD_RAY_Renorm_eta) + '\\n')\nprint('llh_GD_RAY_Renorm_gammaeta: ' + repr(llh_GD_RAY_Renorm_gammaeta) + '\\n')\n\nf = open('Exp_Synthetic_Renorm_T5000_eps_0.1.txt','w')\nf.write('llh_GD_EXP: ' + repr(llh_GD_EXP) + '\\n')\nf.write('llh_GD_EXP_Renorm_alpha: ' + repr(llh_GD_EXP_Renorm_alpha) + '\\n')\nf.write('llh_GD_EXP_Renorm_beta: ' + repr(llh_GD_EXP_Renorm_beta) + '\\n')\nf.write('llh_GD_EXP_Renorm_alphabeta: ' + repr(llh_GD_EXP_Renorm_alphabeta) + '\\n')\n\nf.write('llh_GD_PWL: ' + repr(llh_GD_PWL) + '\\n')\nf.write('llh_GD_PWL_Renorm_K: ' + repr(llh_GD_PWL_Renorm_K) + '\\n')\nf.write('llh_GD_PWL_Renorm_c: ' + repr(llh_GD_PWL_Renorm_c) + '\\n')\nf.write('lllh_GD_PWL_Renorm_p: ' + repr(llh_GD_PWL_Renorm_p) + '\\n')\nf.write('llh_GD_PWL_Renorm_Kc: ' + repr(llh_GD_PWL_Renorm_Kc) + '\\n')\nf.write('llh_GD_PWL_Renorm_Kp: ' + repr(llh_GD_PWL_Renorm_Kp) + '\\n')\n\nf.write('llh_GD_QEXP: ' + repr(llh_GD_QEXP) + '\\n')\nf.write('llh_GD_QEXP_Renorm_a: ' + repr(llh_GD_QEXP_Renorm_a) + '\\n')\nf.write('lllh_GD_QEXP_Renorm_q: ' + repr(llh_GD_QEXP_Renorm_q) + '\\n')\nf.write('llh_GD_QEXP_Renorm_aq: ' + repr(llh_GD_QEXP_Renorm_aq) + '\\n')\n\nf.write('llh_GD_RAY: ' + repr(llh_GD_RAY) + '\\n')\nf.write('llh_GD_RAY_Renorm_gamma: ' + repr(llh_GD_RAY_Renorm_gamma) + '\\n')\nf.write('llh_GD_RAY_Renorm_eta: ' + repr(llh_GD_RAY_Renorm_eta) + '\\n')\nf.write('llh_GD_RAY_Renorm_gammaeta: ' + repr(llh_GD_RAY_Renorm_gammaeta) + '\\n')\n\nf.close()\n\nnp.savez('llh_arrays_eps_0.1_T5000.npz', llh_GD_EXP=llh_GD_EXP,llh_GD_EXP_Renorm_alpha=llh_GD_EXP_Renorm_alpha,llh_GD_EXP_Renorm_beta=llh_GD_EXP_Renorm_beta,llh_GD_EXP_Renorm_alphabeta=llh_GD_EXP_Renorm_alphabeta,llh_GD_PWL=llh_GD_PWL,llh_GD_PWL_Renorm_K=llh_GD_PWL_Renorm_K,llh_GD_PWL_Renorm_c=llh_GD_PWL_Renorm_c,llh_GD_PWL_Renorm_p=llh_GD_PWL_Renorm_p,llh_GD_PWL_Renorm_Kc=llh_GD_PWL_Renorm_Kc,llh_GD_PWL_Renorm_Kp=llh_GD_PWL_Renorm_Kp,llh_GD_QEXP=llh_GD_QEXP,llh_GD_QEXP_Renorm_a=llh_GD_QEXP_Renorm_a,llh_GD_QEXP_Renorm_q=llh_GD_QEXP_Renorm_q,llh_GD_QEXP_Renorm_aq=llh_GD_QEXP_Renorm_aq,llh_GD_RAY=llh_GD_RAY,llh_GD_RAY_Renorm_gamma=llh_GD_RAY_Renorm_gamma,llh_GD_RAY_Renorm_eta=llh_GD_RAY_Renorm_eta,llh_GD_RAY_Renorm_gammaeta=llh_GD_RAY_Renorm_gammaeta)\n\n","sub_path":"Exp_synthetic_Renorm_eps_0.1_T5000.py","file_name":"Exp_synthetic_Renorm_eps_0.1_T5000.py","file_ext":"py","file_size_in_byte":6276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"488024692","text":"import random, time\nfrom collections import deque\nfrom game.gamesrc.objects.baseobjects import Object\n\nclass CombatManager(Object):\n \"\"\"\n This represents a combat management object, and it largely handles all\n combat related actions/results. Currently, we only support a single target\n and no grouping on either side. This will likely change down the road.\n \"\"\"\n\n def at_object_creation(self):\n self.attacker = None\n self.attacker_queue = []\n self.defender = None\n self.defender_queue = []\n self.max_actions = 4\n \n def generate_texts(self):\n \"\"\"\n TODO: Add more texts.\n \"\"\"\n self.missed_attacks_text = [\"You try to hit %s but miss.\" % self.defender.key, \n \"As you bring your weapon down, it bounces off of %s's armor harmlessly\" % self.defender.key,\n \"You swing your weapon but miss mightily.\", \n \"You try to clobber %s, but miss wildly.\" % self.defender.key]\n self.opponent_missed_attacks_text = [\"%s misses you with their wild attack.\" % self.defender.key]\n \n def score_hit(self, who):\n if 'attacker' in who:\n damage_amount = self.attacker.get_damage()\n self.defender.take_damage(damage=damage_amount)\n self.attacker.msg(\"You deal {r%s{n damage to %s.\" % (damage_amount, self.defender.key ))\n \"\"\"\n if self.defender.db.attributes['temp_health'] <= 0:\n self.attacker.msg(\"{bYou have defeated your foe!{n DEBUG: inside combat manager\")\n self.attacker.msg_contents(\"%s has defeated %s\" % (self.attacker.name, self.defender.name))\n self.attacker.award_exp(self.defender.db.attributes['exp_award'])\n self.check_quest_flags()\n self.defender.death()\n self.attacker.db.in_combat = False\n self.attacker.scripts.validate()\n \"\"\"\n return\n else:\n damage_amount = self.defender.get_damage()\n self.attacker.take_damage(damage=damage_amount)\n self.attacker.msg(\"You take {r%s{n points of damage.\" % damage_amount)\n self.attacker.msg(\"{rHP: (%s/%s){n {bMP: (%s/%s){n\" % (self.attacker.db.attributes['temp_health'], self.attacker.db.attributes['health'], \n self.attacker.db.attributes['temp_mana'], self.attacker.db.attributes['mana']))\n if self.attacker.db.attributes['temp_health'] <= 0:\n self.attacker.msg(\"{rYou have been killed!\")\n self.attacker.location.msg_contents(\"{r%s has be slain by %s!{n\" % (self.attacker.name, self.defender.name), exclude=self)\n self.defender.db.target = None\n self.defender.db.in_combat = False\n self.attacker.death() \n return\n\n def check_quest_flags(self):\n quest_log = self.attacker.db.quest_log\n quest_log.check_quest_flags(self.db.defender)\n \n def score_miss(self, who):\n if 'attacker' in who:\n miss_text = random.choice(self.missed_attacks_text)\n self.attacker.msg(miss_text)\n return\n else:\n miss_text = random.choice(self.opponent_missed_attacks_text)\n self.attacker.msg(miss_text)\n return\n \n def process_action(self):\n atk_queue = self.attacker_queue\n def_queue = self.defender_queue\n \n atk_queue = deque(atk_queue)\n def_queue = deque(def_queue)\n try: \n atk_action = atk_queue.popleft()\n except IndexError:\n atk_action = 'attack'\n \n try:\n def_action = def_queue.popleft()\n except IndexError:\n def_action = 'attack'\n \n if len(atk_queue) >= 2:\n self.db.current_action = atk_action\n self.db.next_action = atk_queue[0]\n self.db.second_action = atk_queue[1]\n\n self.attacker_queue = atk_queue\n self.defender_queue = def_queue\n self.defender.db.combat_queue = def_queue\n self.attacker.db.combat_queue = atk_queue\n \n #self.attacker.msg(\"{yYour Attack Queue: {g%s{n\" % self.attacker_queue)\n self.attacker_initiative = self.attacker.initiative_roll()\n self.defender_initiative = self.defender.initiative_roll()\n if self.attacker_initiative > self.defender_initiative:\n if 'attack' in atk_action: \n attack_roll = self.attacker.attack_roll()\n if attack_roll >= self.defender.db.attributes['armor_rating']:\n if 'defend' in def_action:\n self.attacker.msg(\"%s is in a defensive position, negating your attack.\" % self.defender.name)\n return\n elif 'attack' in def_action:\n defender_attack_roll = self.defender.attack_roll()\n if defender_attack_roll >= self.attacker.db.attributes['temp_armor_rating']:\n self.score_hit(who='defender')\n else:\n self.score_miss(who='defender') \n else:\n pass\n #do nothing \n self.score_hit(who=\"attacker\")\n else:\n self.score_miss(who=\"attacker\")\n elif 'defend' in atk_action:\n self.attacker.msg(\"{bYou are in a defensive stance, negating any damage done.{n\")\n return\n if 'attack' in def_action:\n def_atk_roll = self.defender.attack_roll()\n if def_atk_roll >= self.attacker.db.attributes['temp_armor_rating']:\n self.score_hit(who=\"defender\")\n else:\n self.score_miss(who=\"defender\")\n elif 'defend' in def_action:\n self.attacker.msg(\"{b%s and yourself seem to have defended at the same time, so you stare at each other viciously.{n\" % self.defender.name)\n elif 'skill' in atk_action:\n split = atk_action.split(':')\n #self.attacker.msg(\"You prepare to use the skill: {g%s{n!\" % split[1].title())\n #self.check_for_combo( )\n manager = self.attacker.db.skill_log\n character_skills = manager.db.skills\n if split[1] in character_skills.keys():\n skill_obj = character_skills[split[1]]\n skill_obj.on_use(caller=self.attacker)\n \n else:\n pass\n else:\n if 'attack' in def_action:\n attack_roll = self.defender.attack_roll()\n if attack_roll >= self.attacker.db.attributes['temp_armor_rating']:\n if 'defend' in atk_action:\n self.attacker.msg(\"{bYou easily defend against %s's attack, negating any damage.{n\" % self.defender.name)\n return\n elif 'attack' in atk_action:\n attack_roll = self.attacker.attack_roll()\n if attack_roll >= self.defender.db.attributes['armor_rating']:\n self.score_hit(who=\"attacker\")\n else:\n self.score_miss(who=\"attacker\")\n elif 'skill' in atk_action:\n split = atk_action.split(':')\n #self.attacker.msg(\"You prepare to use the skill: {g%s{n!\" % split[1].title())\n #self.check_for_combo()\n manager = self.attacker.db.skill_log\n character_skills = manager.db.skills\n if split[1] in character_skills.keys():\n skill_obj = character_skills[split[1]]\n skill_obj.on_use(caller=self.attacker)\n else:\n pass\n self.score_hit(who='defender')\n else:\n self.score_miss(who='defender')\n if 'defend' in atk_action:\n self.attacker.msg(\"{bYou easily defend against %s's attack, negating any damage.{n\" % self.defender.name)\n return\n elif 'attack' in atk_action:\n attack_roll = self.attacker.attack_roll()\n if attack_roll >= self.defender.db.attributes['armor_rating']:\n self.score_hit(who=\"attacker\")\n else:\n self.score_miss(who=\"attacker\")\n elif 'skill' in atk_action:\n split = atk_action.split(':')\n self.attacker.msg(\"You prepare to use the skill: {g%s{n!\" % split[1].title())\n #self.check_for_combo()\n manager = self.attacker.db.skill_log\n character_skills = manager.db.skills\n if split[1] in character_skills.keys():\n skill_obj = character_skills[split[1]]\n skill_obj.on_use(caller=self.attacker)\n\n else:\n self.attacker.msg(\"No action selected, probably because I couldnt pop shiz off the deque.\")\n\n def check_for_combo(self):\n prev_action = self.db.prev_atk_action\n adj_action = self.db.adj_action\n \n \n\n def combat_round(self): \n \"\"\"\n This is what controls the combat rounds that get fired off.\n two things that are important:\n --defender = the target of the character/what the character\n chose to attack with the attack command\n --attacker = player character.\n \"\"\"\n self.attacker_initiative = self.attacker.initiative_roll()\n self.defender_initiative = self.defender.initiative_roll()\n if len(self.attacker_queue) >= len(self.defender_queue):\n self.process_action()\n elif len(self.attacker_queue) < 1:\n self.process_action()\n else:\n self.process_action() \n #self.attacker.msg(\"Combat round complete. Queue up to four of your next actions.\")\n\n \"\"\"\n if self.attacker_initiative > self.defender_initiative: \n self.attacker.msg(\"{rYou begin your assult against: %s (You rolled a %s and they rolled a %s){n\" \\\n % (self.defender.key, self.attacker_initiative, self.defender_initiative))\n attacker_roll = self.attacker.attack_roll()\n# self.attacker.msg(\"DEBUG: Your attack roll: %s vs %s armor\" % (attacker_roll, self.defender.db.attributes['armor_rating']))\n if attacker_roll >= self.defender.db.attributes['armor_rating']: \n self.score_hit(who=\"attacker\")\n else:\n self.score_miss(who=\"attacker\")\n \n #check if the opponent is dead before they take their turn\n if self.defender.db.corpse is True:\n return\n \n defender_roll = self.defender.attack_roll()\n #self.attacker.msg(\"DEBUG: Defender attack roll: %s vs %s armor\"% (defender_roll, self.attacker.db.attributes['armor_rating']))\n if defender_roll >= int(self.attacker.db.attributes['temp_armor_rating']):\n self.score_hit(who=\"defender\")\n else:\n self.score_miss(who=\"defender\")\n else:\n self.attacker.msg(\"{r%s gets the jump on you and begins it's assault! (They rolled a %s and you rolled a %s){n\" \\\n % (self.defender.key, self.defender_initiative, self.attacker_initiative))\n defender_roll = self.defender.attack_roll()\n #self.attacker.msg(\"DEBUG: Defender attack roll: %s vs %s armor\" % (defender_roll, self.attacker.db.armor_rating))\n if defender_roll >= int(self.attacker.db.attributes['temp_armor_rating']):\n self.score_hit(who=\"defender\")\n else:\n self.score_miss(who=\"defender\")\n \n if self.attacker.db.in_combat is False: \n #assume death has occured\n return \n\n attacker_roll = self.attacker.attack_roll()\n self.attacker.msg(\"DEBUG: Your attack roll: %s vs %s armor\" % (attacker_roll, self.defender.db.attributes['armor_rating']))\n if attacker_roll >= self.defender.db.attributes['armor_rating']:\n self.score_hit(who=\"attacker\")\n else:\n self.score_miss(who=\"attacker\")\n \"\"\"\n","sub_path":"game/gamesrc/objects/world/combat.py","file_name":"combat.py","file_ext":"py","file_size_in_byte":12847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"124949971","text":"from django.http import JsonResponse, HttpResponseNotAllowed, HttpResponseBadRequest, HttpResponseNotFound\nfrom .models import Chat, Message\nfrom users.models import Member\nimport json\nfrom django.shortcuts import render, get_object_or_404\nfrom .models import User\nfrom django.contrib.auth.decorators import login_required\n\n\n# Create your views here.\n\nfrom django import forms\n\nclass create_chat_chat(forms.ModelForm):\n class Meta:\n model = Chat\n fields = ('topic', 'is_group_chat')\n\n# class create_chat_member(forms.Form):\n# uid = forms.IntegerField(label='UserId')\n# def clean_uid(self):\n# data = self.cleaned_data['uid']\n# if not User.objects.filter(id=data):\n# raise forms.ValidationError(\"You have forgotten about Fred!\")\n# return data\n\n@login_required\ndef chat_list(request): \n if request.method == 'GET':\n chat = Chat.objects.all()\n resp = [{c.id: c.topic} for c in chat]\n response = JsonResponse({\"resp\": resp})\n return response\n return HttpResponseNotAllowed({'err' : 'response not allowed'})\n\n#@login_required\ndef messages_list (request, cid):\n if request.method == 'GET' or request.method == 'POST':\n # if Member.objects.filter(chat_id=cid, user_id=request.user.id):\n # print(request.user.id, \"user\")\n # messages = Message.objects.filter(chat_id=cid) \n # read_messages(request, cid)\n # container = [{message.user_id: message.content} for message in messages]\n # return JsonResponse({\"resp\": container})\n # return JsonResponse({\"not a member\": \"user is not a member\"})\n messages = Message.objects.filter(chat_id=cid)\n chat = get_object_or_404(Chat, id=cid)\n resp = [{message.content: message.added_at} for message in messages]\n return JsonResponse({\"name\": chat.topic, \"data\": resp})\n return HttpResponseNotAllowed({'err': 'resp not allowed'})\n\n@login_required\ndef create_chat (request):\n if request.method == 'POST':\n form = create_chat_chat(request.POST)\n if form.is_valid():\n created_chat = form.save()\n Member.objects.create(chat_id=created_chat.id, user_id=request.user.id)\n return JsonResponse({created_chat.id: created_chat.topic})\n return HttpResponseBadRequest({\"error_not_valid_form\": \"not valid form\"})\n else:\n form = create_chat_chat()\n return render(request, 'create_chat.html', {'form': form})\n\nclass send_message_form(forms.ModelForm):\n class Meta:\n model = Message\n exclude = ['user']\n\n@login_required\ndef send_message(request):\n if request.method == 'POST':\n form = send_message_form(request.POST)\n if form.is_valid():\n message = form.save(commit=False)\n if not Member.objects.filter(chat_id=message.chat_id, user_id=request.user.id):\n return HttpResponseBadRequest({\"not a member\": \"user is not a member\"})\n message.user_id = request.user.id\n message = form.save()\n chat = Chat.objects.get(id=message.chat_id)\n chat.last_message = message.id\n chat.save()\n return JsonResponse({message.id: message.content})\n return HttpResponseBadRequest({\"errors\": form.errors}) #form errords\n else:\n form = send_message_form()\n return render(request, 'send_message.html', {'form': form})\n\n\n@login_required\ndef read_messages(request, cid):\n chat = get_object_or_404(Chat, id=cid)\n message = Message.objects.filter(id=chat.last_message).first()\n if message:\n member = Member.objects.get(chat_id=cid, user_id=request.user.id)\n member.last_read_message = message\n member.save()\n","sub_path":"application/chats/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"79097865","text":"import numpy as np\n\n\nclass Agent(object):\n def __init__(self, env_setting):\n n_state, n_action, n_step = (\n env_setting[\"n_state\"],\n env_setting[\"n_action\"],\n env_setting[\"n_step\"],\n )\n self.env_setting = env_setting\n self.Q = np.ones((n_step + 1, n_state, n_action)) * n_step\n self.N = np.zeros((n_step + 1, n_state, n_action)) + 1e-10\n self.V = np.zeros((n_step + 1, n_state))\n self.R_hat = np.zeros((n_step + 1, n_state, n_action))\n self.P_hat = np.zeros((n_step + 1, n_state, n_action, n_state))\n self.transition_count = np.zeros(\n (n_step + 1, n_state, n_action, n_state), dtype=np.int\n )\n self.Q[n_step, ...] = 0\n self.pi = np.zeros((n_step + 1, n_state), dtype=np.int)\n\n def greedy(self, step, state):\n return np.argmax(self.Q[step, state, :])\n\n def policy_greedy(self):\n setting = self.env_setting\n n_state, n_action, n_step, p = (\n setting[\"n_state\"],\n setting[\"n_action\"],\n setting[\"n_step\"],\n setting[\"p\"],\n )\n self.pi[...] = 0\n for step in range(n_step):\n for state in range(n_state):\n self.pi[step, state] = self.greedy(step, state)\n return self.pi\n\n def estimate_reward(self, step, state, action, reward):\n N = self.N[step, state, action]\n self.R_hat[step, state, action] = (self.R_hat[step, state, action] * N + reward) / (N + 1)\n\n def estimate_transition(self, step, state, action, next_state):\n self.transition_count[step, state, action, next_state] += 1\n state_action_count = self.transition_count[step, state, action, :]\n self.P_hat[step, state, action, :] = state_action_count / np.sum(state_action_count)\n\n def estimate_dynamic(self, step, state, action, reward, next_state):\n self.estimate_reward(step, state, action, reward)\n self.estimate_transition(step, state, action, next_state)\n","sub_path":"tabular/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"217628175","text":"from scripts.mapmaker_start import Point\nimport pytest\n\n# in order to prevent minor bug add blank line\ndef test_make_one_point():\n p1 = Point(\"Dakar\", 14.7167, 17.4677)\n assert p1.get_lat_long() == (14.7167, 17.4677)\n# in order to prevent minor bug add blank line \n\ndef test_invalid_point_generation():\n with pytest.raises(ValueError) as exp:\n Point(\"Buenos Aires\", 12.11386, -555.08269)\n #breakpoint()\n assert str(exp.value) == 'Invalid latitude, longitude combination'\n \n with pytest.raises(ValueError) as exp:\n Point(5, 12.11386, -55.08269)\n assert str(exp.value) == 'City name provided must be a string'\n#exception testing is a good way to define unwanted behaviors\n","sub_path":"tests/test_mapmaker_start.py","file_name":"test_mapmaker_start.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"237671840","text":"# pylint: disable = invalid-name, superfluous-parens, bad-whitespace, using-constant-test\n\"\"\"\nTake the raw Reddit sign data and output it to a spreadsheet for manual codifying\nUsage: python step1_prepcodify_minecraft.py\n\"\"\"\n\nimport sys\nimport pprint\nimport csv\nimport json\nimport argparse\nimport nltk\n#nltk.download('punkt')\n\nparser = argparse.ArgumentParser()\n# from http://www.knight-of-pi.org/python-argparse-massively-simplifies-parsing-complex-command-line-parameters/\n# parser.add_argument('-d', '--debug', nargs='?', metavar='1..5', type=int,\n# choices=range(1, 5), default=2,\n# help='Debug level is a value between 1 and 5')\nparser.add_argument('-i', '--input', nargs='?',\n type=argparse.FileType('r'), default=sys.stdin,\n help='Take program input in the file passed after -i')\nparser.add_argument('-c', '--columnheader', nargs='?', metavar='path',\n type=str, default='data/header.csv',\n help='Take program header in the file passed after -h')\nparser.add_argument('-r', '--repeats', nargs='?', metavar='path',\n type=str, default='data/coded_blacklist.csv',\n help='Take program header in the file passed after -h')\nparser.add_argument('-n', '--nlines', nargs='?', type=int,\n default=200,\n help='How many lines should be written to output?')\nparser.add_argument('-t', '--tag', nargs='?', type=str,\n default='',\n help='how are we labeling the produced dataset?')\nargs = parser.parse_args()\n#print( args )\n\n### build header\nheader = []\nwith open( args.columnheader, 'r') as header_file:\n reader = csv.reader(header_file, delimiter=',')\n # pull single row from this single row file\n header = next( reader )\n # convert to dictionary of empty strings\n # this will be the rtemplate of each row\n header = { heading : '' for heading in header }\n#print(header)\n\n#### build blacklist\n#communities_coded = []\n#with open( args.repeats, 'r') as blacklist_file:\n# reader = csv.DictReader(blacklist_file, delimiter=',')\n# for row in reader:\n# domain = row['domain']\n# community = row['communityID']\n# communities_coded.append( domain+'_'+community )\n#print( communities_coded )\n\nwith args.input as jsonl_infile:\n writer = csv.DictWriter(sys.stdout, delimiter=',', fieldnames=header)\n for row in jsonl_infile: ### for each subreddit\n line_counter = 0 # can't use enumerate because I increment this in funny ways in the loop\n jrow = json.loads( row )\n for rule in jrow['rules']: ### for each rule in the sub\n rule_text = rule['description']\n ### string handling\n rule_text = rule_text.replace(r'\"', \"'\") # for reddit: lots of quotes to deal with\n #rule_text = rule_text.replace(r'\\r', r'\\n') # wierd newlines\n if rule_text.startswith('='): # excellhandling\n rule_text = '\\\\' + rule_text\n #assert '|' not in rule_text, rule_text + '\\n' + \"No |'s. if this triggers, comment out and add the replace line below\" \n #rule_text = rule_text.replace(r'|', '/') # my coders use pipes so they can't appear in the data.\n #assert '\\t' not in rule_text, rule_text.replace('\\t', 'XXX') + '\\n' + \"if this triggers, comment out and add the replace line below\" \n rule_text = rule_text.replace('\\t', ' ') # clean out tabs, which throw off csv cell ordering\n ### aiding tokenizer\n rule_text = rule_text.replace(r'.**', '. ') # for reddit: sentences followed by markdown\n rule_text = rule_text.replace(r'.*', '. ') # for reddit\n rule_text = rule_text.replace(r'\\n\\n**', '. ') # for reddit: double \\n+bullets instead of .'s\n rule_text = rule_text.replace(r'\\n\\n*', '. ') # for reddit\n rule_text = rule_text.replace(r'\\n\\n-', '. ') # for reddit\n rule_text = rule_text.replace(r'.\\n\\n', '. ') # for reddit\n rule_text = rule_text.replace(r'\\n\\n', '. ') # for reddit\n rule_text = rule_text.replace('\\n\\n', '. ') # for reddit ### not sure why this catches things the above don't\n rule_text = rule_text.replace(r'\\n**', '. ') # for reddit\n rule_text = rule_text.replace(r'\\n*', '. ') # for reddit\n rule_text = rule_text.replace(r'\\n', '. ') # for reddit\n rule_text = rule_text.replace('\\n', '. ') # for reddit\n rule_texts = nltk.sent_tokenize( rule_text )\n ### write the rule as an IS, and it's descript as several IS's\n ### this is necesary because it simplifies the context tab and because rules are sometimes written with the description referring to content in the short name of the rule\n trow = header.copy()\n trow['domain'] = 'reddit'\n trow['communityID'] = 'r/' + jrow['sub']\n trow['timestamp'] = rule['createdUtc']\n trow['ref'] = 'https://www.reddit.com/' + trow['communityID']\n trow['text'] = rule['shortName']\n trow['lineID'] = line_counter\n line_counter += 1\n writer.writerow( trow )\n for rule_text in rule_texts: ### for each institutional statement in the rule\n trow = header.copy()\n trow['domain'] = 'reddit'\n trow['communityID'] = 'r/' + jrow['sub']\n trow['timestamp'] = rule['createdUtc']\n trow['ref'] = 'https://www.reddit.com/' + trow['communityID']\n trow['text'] = rule_text\n trow['lineID'] = line_counter\n line_counter += 1\n writer.writerow( trow )\n if False and line_counter == 85:\n print(trow)\n print(rule)\n print(rule['description'])\n print(rule_texts)\n print(rule_text)\n print(\"REALLY\", r'\\n\\n' in rule_text)\n print(\"REALLY\", r'\\n' in rule_text)\n print(\"REALLY\", '\\\\n' in rule_text)\n print(\"REALLY\", '\\n\\n' in rule_text)\n print(\"REALLY\", '\\n' in rule_text)\n print(\"REALLY\", r'\\r' in rule_text)\n if ( args.nlines != -1 ) and ( line_counter >= args.nlines ): ### break after a whole sub\n break\n","sub_path":"step1_prepcodify_reddit.py","file_name":"step1_prepcodify_reddit.py","file_ext":"py","file_size_in_byte":6616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"579734198","text":"\n\nfrom xai.brain.wordbase.nouns._heed import _HEED\n\n#calss header\nclass _HEEDING(_HEED, ):\n\tdef __init__(self,): \n\t\t_HEED.__init__(self)\n\t\tself.name = \"HEEDING\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"heed\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_heeding.py","file_name":"_heeding.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"255514221","text":"from .server.parsers import HTTPParser\nfrom .server.handler import HTTPHandler\nfrom .server.worker import SocketListener\nfrom .server.middleware.AuthGuardian import AuthGuardian\nfrom .server.middleware.DatabaseMiddleware import DatabaseMiddleware\nfrom .server.middleware.HTTPHeaders import HTTPHeaders\nfrom .guardian import ResourceGuardianMidddleware\nfrom .router import router\nfrom .auth.Auth import Authorization\nfrom . import domain\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, scoped_session\nfrom logging.handlers import RotatingFileHandler\nimport logging\nimport ssl\nimport argparse\nimport time\nimport sys\nimport json\n\n\nLOG_FORMAT = \"%(asctime)s.%(msecs)03d %(process)s.%(thread)s %(levelname)7s: %(name)s %(message)s\"\n\n\ndef setup_database(dbssn):\n domain.metadata.create_all(bind=dbssn.get_bind())\n\n\ndef get_dbssn(config, echo=False):\n db_uri = config[\"db_uri\"]\n\n engine = create_engine(db_uri, echo=echo, pool_size=20, max_overflow=10)\n Session = scoped_session(\n sessionmaker(autoflush=True, autocommit=False, bind=engine)\n )\n dbssn = Session\n try:\n engine.connect()\n return dbssn\n except:\n logging.error(\"Could not connect to database\")\n time.sleep(1)\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-s\", \"--ssl\", help=\"SSL\", action=\"store_true\")\n parser.add_argument(\"-c\", \"--config\", help=\"Config file\", action=\"store\")\n parser.add_argument(\n \"-i\", \"--init-database\", help=\"Initialize database tables\", action=\"store_true\"\n )\n parser.add_argument(\"--add-superuser\", help=\"Add superuser\", action=\"store_true\")\n parser.add_argument(\"--start\", help=\"Start server\", action=\"store_true\")\n args = parser.parse_args()\n\n logging.basicConfig(format=LOG_FORMAT, level=logging.DEBUG)\n\n with open(args.config) as f:\n config = json.load(f)\n\n dbssn_factory = get_dbssn(config, echo=True)\n dbssn = dbssn_factory()\n\n if args.init_database:\n setup_database(dbssn)\n\n if args.add_superuser:\n superuser = domain.User()\n superuser.username = \"superuser\"\n superuser.first_name = \"Super\"\n superuser.last_name = \"User\"\n superuser.password_set(\"AdMiNiStRaToR1@3\")\n superuser.role = domain.User.Role.admin.value\n dbssn.add(superuser)\n dbssn.commit()\n\n if not args.start:\n sys.exit(0)\n\n if args.ssl:\n context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)\n\n server_cert = config[\"server_cert\"]\n server_key = config[\"server_key\"]\n\n context.load_cert_chain(certfile=server_cert, keyfile=server_key)\n else:\n context = None\n\n auth_module = Authorization(user_model=domain.User, secret=config[\"secret\"])\n middleware = [\n HTTPHeaders(cdtime=60, keep_alive=True),\n DatabaseMiddleware(dbssn_factory=dbssn_factory),\n AuthGuardian(auth_module),\n ResourceGuardianMidddleware(),\n ]\n h = HTTPHandler(HTTPParser(), router=router, middleware=middleware)\n server = SocketListener(h, address=\"0.0.0.0\", port=12345, ssl_context=context)\n dbssn.close()\n server.serve()\n","sub_path":"tin/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"616467854","text":"import logging\n\nfrom sen.docker_backend import DockerContainer, RootImage\nfrom sen.exceptions import NotifyError\nfrom sen.tui.constants import HELP_TEXT\nfrom sen.tui.widgets.info import ImageInfoWidget, ContainerInfoWidget, ProcessTree\nfrom sen.tui.widgets.list.main import MainListBox\nfrom sen.tui.widgets.list.util import get_operation_notify_widget\nfrom sen.tui.widgets.list.common import AsyncScrollableListBox, ScrollableListBox\nfrom sen.tui.widgets.tree import ImageTree\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Buffer:\n \"\"\"\n base buffer class\n \"\"\"\n display_name = None # display in status bar\n widget = None # display this in main frame\n tag = None # single char, for status\n\n def __init__(self):\n logger.debug(\"creating buffer %r\", self)\n\n def __repr__(self):\n return \"{}(name={!r}, widget={!r})\".format(\n self.__class__.__name__, self.display_name, self.widget)\n\n def destroy(self):\n destroy_method = getattr(self.widget, \"destroy\", None)\n if destroy_method:\n destroy_method()\n\n def find_previous(self, s=None):\n logger.debug(\"searching next %r in %r\", s, self.__class__.__name__)\n try:\n self.widget.find_previous(s)\n except AttributeError as ex:\n logger.debug(repr(ex))\n raise NotifyError(\"Can't search in this buffer.\")\n\n def find_next(self, s=None):\n logger.debug(\"searching next %r in %r\", s, self.__class__.__name__)\n try:\n self.widget.find_next(s)\n except AttributeError as ex:\n logger.debug(repr(ex))\n raise NotifyError(\"Can't search in this buffer.\")\n\n def build_status_bar(self):\n status_bar = getattr(self.widget, \"status_bar\", None)\n if status_bar:\n return status_bar()\n\n def filter(self, s):\n logger.debug(\"filter widget %r with query %r\", self.widget, s)\n widgets = self.widget.filter(s)\n if widgets is not None:\n self.widget.set_body(widgets)\n\n\nclass ImageInfoBuffer(Buffer):\n tag = \"I\"\n\n def __init__(self, docker_image, ui):\n \"\"\"\n :param docker_image:\n :param ui: ui object so we refresh\n \"\"\"\n if isinstance(docker_image, RootImage):\n raise NotifyError(\"Image \\\"scratch\\\" doesn't provide any more information.\")\n self.display_name = docker_image.short_name\n self.widget = ImageInfoWidget(ui, docker_image)\n super().__init__()\n\n\nclass ContainerInfoBuffer(Buffer):\n tag = \"I\"\n\n def __init__(self, docker_container, ui):\n \"\"\"\n :param docker_container:\n :param ui: ui object so we refresh\n \"\"\"\n self.display_name = docker_container.short_name\n self.widget = ContainerInfoWidget(ui, docker_container)\n super().__init__()\n\n\nclass TreeBuffer(Buffer):\n display_name = \"Tree\"\n tag = \"T\"\n\n def __init__(self, docker_backend, ui):\n \"\"\"\n \"\"\"\n self.widget = ImageTree(docker_backend, ui)\n super().__init__()\n\n\nclass MainListBuffer(Buffer):\n display_name = \"Listing\"\n tag = \"M\"\n\n def __init__(self, docker_backend, ui):\n self.ui = ui\n self.widget = MainListBox(docker_backend, ui)\n super().__init__()\n\n def refresh(self, focus_on_top=False):\n self.widget.populate(focus_on_top=focus_on_top)\n self.ui.refresh()\n\n\nclass LogsBuffer(Buffer):\n\n def __init__(self, docker_object, ui, follow=False):\n \"\"\"\n\n :param docker_object: container to display logs\n :param ui: ui object so we refresh\n \"\"\"\n self.tag = \"F\" if follow else \"L\"\n self.display_name = docker_object.short_name\n if isinstance(docker_object, DockerContainer):\n try:\n pre_message = \"Getting logs for container {}...\".format(docker_object.short_name)\n ui.notify_message(pre_message)\n if follow:\n # FIXME: this is a bit race-y -- we might lose some logs with this approach\n operation = docker_object.logs(follow=follow, lines=0)\n static_data = docker_object.logs(follow=False).response\n self.widget = AsyncScrollableListBox(operation.response, ui, static_data=static_data)\n else:\n operation = docker_object.logs(follow=follow)\n self.widget = ScrollableListBox(operation.response)\n ui.remove_notification_message(pre_message)\n ui.notify_widget(get_operation_notify_widget(operation, display_always=False))\n except Exception as ex:\n # FIXME: let's catch 404 and print that container doesn't exist\n # instead of printing ugly HTTP error\n raise NotifyError(\"Error getting logs for container %s: %r\" % (docker_object, ex))\n else:\n raise NotifyError(\"Only containers have logs.\")\n super().__init__()\n\n\nclass InspectBuffer(Buffer):\n tag = \"I\"\n\n def __init__(self, docker_object):\n \"\"\"\n\n :param docker_object: object to inspect\n \"\"\"\n self.display_name = docker_object.short_name\n inspect_data = docker_object.display_inspect()\n self.widget = ScrollableListBox(inspect_data)\n self.display_name = docker_object.short_name\n super().__init__()\n\n\nclass HelpBuffer(Buffer):\n tag = \"H\"\n display_name = \"\"\n\n def __init__(self):\n \"\"\"\n \"\"\"\n self.widget = ScrollableListBox(HELP_TEXT)\n super().__init__()\n","sub_path":"sen/tui/buffer.py","file_name":"buffer.py","file_ext":"py","file_size_in_byte":5581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"522341388","text":"pkgname = \"harfbuzz\"\npkgver = \"8.1.1\"\npkgrel = 0\nbuild_style = \"meson\"\nconfigure_args = [\n \"-Dglib=enabled\",\n \"-Dfreetype=enabled\",\n \"-Dcairo=enabled\",\n \"-Dicu=enabled\",\n \"-Dgraphite2=enabled\",\n \"-Dintrospection=enabled\",\n \"-Ddocs=enabled\",\n]\nhostmakedepends = [\n \"meson\",\n \"pkgconf\",\n \"glib-devel\",\n \"gtk-doc-tools\",\n \"gobject-introspection\",\n # prevent installing self through freetype\n \"freetype-bootstrap\",\n]\nmakedepends = [\n \"freetype-bootstrap\",\n \"cairo-devel\",\n \"graphite2-devel\",\n \"icu-devel\",\n]\npkgdesc = \"Text shaping engine\"\nmaintainer = \"q66 \"\nlicense = \"MIT\"\nurl = \"http://www.freedesktop.org/wiki/Software/HarfBuzz\"\nsource = f\"https://github.com/{pkgname}/{pkgname}/releases/download/{pkgver}/{pkgname}-{pkgver}.tar.xz\"\nsha256 = \"0305ad702e11906a5fc0c1ba11c270b7f64a8f5390d676aacfd71db129d6565f\"\n# test failures since icu 71\noptions = [\"!cross\", \"!check\"]\n\n\ndef post_install(self):\n self.install_license(\"COPYING\")\n\n\n@subpackage(\"harfbuzz-devel\")\ndef _devel(self):\n return self.default_devel()\n\n\n@subpackage(\"harfbuzz-progs\")\ndef _progs(self):\n return self.default_progs()\n","sub_path":"main/harfbuzz/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"514462280","text":"# Produces a list like this:\n# ==========================\n# \n# \n# \n# \n# \n\nimport glob\nimport os\nimport nltk\n\n\n\nnltk_handles = []\nproper_nouns = []\n\n# dowload nltk packages\n# nltk.download()\n\n# read in the files into a list\nos.chdir(\"texts\")\nfor filename in glob.glob(\"*.txt\"):\n tokens = nltk.wordpunct_tokenize(open(filename, 'r').read())\n nltk_handles.append(tokens)\n\n words_pos = nltk.pos_tag(tokens)\n nouns = [t for t in words_pos if t[1].startswith('NNP')]\n\n print(nltk.FreqDist([noun[0] for noun in nouns]))","sub_path":"hack-night/count_proper_nouns.py","file_name":"count_proper_nouns.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"625436995","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 25 16:58:51 2020\n\n@author: LENOVO A9\n\"\"\"\n\nprint (\"============================\")\nprint (\"===== [ program data ] =====\")\nprint (\"============================\")\ndata = {}\nwhile True :\n print(\"\")\n m = input (\"= [L]ihat, [T]ambah, [U]bah, [H]apus, [C]ari, [K]eluar =\")\n print (\"================================================\")\n print (\" | NO | NAMA | NIM | TUGAS | UTS | UAS | AKHIR |\")\n print (\"============ > NO DATA < =======================\")\n if m.lower() == 'k' :\n break\n elif m.lower() == 'l' :\n print (\"===================DAFTAR NILAI================= \")\n print (\"=================================================\")\n print (\" | NO | NAMA | NIM | TUGAS | UTS | UAS | AKIHIR |\")\n print (\"=================================================\")\n i = 0\n for x in data.items():\n i += 1\n print (\" 1 | {0:9} | {1:9} | {2:9} | {3:9} | {4:9} | {5:9} |\" .format(x[0] , x[1][0] , x[1][1] , x[1][2] , x[1][3] , x[1][4]))\n \n else :\n print (\" === NO DATA ===\")\n \n elif m.lower() == 't' :\n print ( \"=== MENAMBAH DATA MAHASISWA ===\")\n nama = input (\"masukan NAMA : \")\n nim = input (\"masukan NIM : \")\n tugas = float(input (\"masukan nilai TUGAS : \"))\n uts = float(input(\"masukan nilai UTS : \"))\n uas = float(input(\"masukan nilai UAS : \"))\n akhir = (0.30 * tugas ) + (0.35 * uts ) + (0.35 * uas)\n data [nama] = nim , tugas , uts , uas , akhir\n \n elif m.lower() == 'u' :\n print (\"=== MENGUBAH DATA MAHASISWA ===\")\n nama = input (\"masukan NAMA : \")\n if nama in data.keys() :\n nim = input (\"masukan NIM : \")\n tugas = float (input(\"masukan nilai TUGAS : \"))\n uts = float(input(\"masukan nilai UTS : \"))\n uas = float(input(\"masukan nilai UAS : \"))\n akhir = (0.30 * tugas) + (0.35 * uts) + (0.35 * uas)\n data [nama] = nim , tugas , uts , uas , akhir\n \n else :\n print(\" === NO DATA ===\")\n \n elif m.lower() == 'v' :\n print (\"=== HAPUS DATA MAHASISWA ===\")\n nama = input (\"masukan NAMA : \")\n if nama in data.keys() :\n print (\"DATA\" , nama , \"ADALAH {0} \" .format (data [nama] ))\n else :\n print(\"=== NO DATA ===\")\n \n else :\n print (\"=== SELANJUTNYA ===\")\n \n \n \n \n ","sub_path":"PRAKTIKUM 5.py","file_name":"PRAKTIKUM 5.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"297866666","text":"# encoding: UTF-8\n\nfrom builtins import str\n\nimport psutil\n#import sys\nimport qdarkstyle\n\nfrom uiBasicWidget import *\n\n########################################################################\nclass MainWindow(QtGui.QMainWindow):\n \"\"\"主窗口\"\"\"\n signalStatusBar = QtCore.pyqtSignal(type(Event()))\n\n #----------------------------------------------------------------------\n def __init__(self, mainEngine, eventEngine, app, sheets):\n \"\"\"Constructor\"\"\"\n super(MainWindow, self).__init__()\n \n self.mainEngine = mainEngine\n self.eventEngine = eventEngine\n self.app = app\n self.sheets = sheets\n \n self.widgetDict = {} # 用来保存子窗口的字典\n \n self.initUi()\n self.eventEngine.register(EVENT_TITLE, self.updateTitle)\n \n self.sid = None\n \n def updateTitle(self, event):\n (user, stratid) = event.dict_['data']\n self.setWindowTitle('VnTrader: ' + str(user) + \"/\" + str(stratid))\n self.sid = stratid\n \n #----------------------------------------------------------------------\n def initUi(self):\n \"\"\"初始化界面\"\"\"\n self.setWindowTitle('VnTrader')\n self.initCentral()\n self.initMenu()\n #self.initStatusBar()\n \n def showLogin(self):\n self.connectQuantOS()\n \n #----------------------------------------------------------------------\n def initCentral(self):\n \n \"\"\"初始化中心区域\"\"\"\n widgetTradingW, dockTradingW = self.createDock(TradingWidget, u'交易', QtCore.Qt.LeftDockWidgetArea)\n\n widgetMarketM, dockMarketM = self.createDock(MarketMonitor, u'行情', QtCore.Qt.RightDockWidgetArea)\n widgetPositionM, dockPositionM = self.createDock(PositionMonitor, u'持仓', QtCore.Qt.RightDockWidgetArea)\n \n widgetAccountM, dockAccountM = self.createDock(AccountMonitor, u'资金', QtCore.Qt.BottomDockWidgetArea)\n widgetContractM, dockContractM = self.createDock(ContractMonitor, u'合约', QtCore.Qt.BottomDockWidgetArea)\n widgetLogM, dockLogM = self.createDock(LogMonitor, u'日志', QtCore.Qt.BottomDockWidgetArea)\n\n widgetTradeM, dockTradeM = self.createDock(TradeMonitor, u'成交', QtCore.Qt.BottomDockWidgetArea)\n widgetOrderM, dockOrderM = self.createDock(OrderMonitor, u'委托', QtCore.Qt.BottomDockWidgetArea)\n\n \n self.tabifyDockWidget(dockContractM, dockTradeM)\n self.tabifyDockWidget(dockTradeM, dockOrderM)\n self.tabifyDockWidget(dockAccountM, dockLogM)\n \n dockOrderM.raise_()\n dockLogM.raise_()\n \n # 连接组件之间的信号\n widgetPositionM.itemDoubleClicked.connect(widgetTradingW.closePosition)\n widgetMarketM.itemDoubleClicked.connect(widgetTradingW.fillSymbol)\n \n #----------------------------------------------------------------------\n def initMenu(self):\n \"\"\"初始化菜单\"\"\"\n # 创建操作\n connectQuantOSAction = QtGui.QAction(u'连接和切换策略', self)\n connectQuantOSAction.triggered.connect(self.connectQuantOS) \n \n exitAction = QtGui.QAction(u'退出', self)\n exitAction.triggered.connect(self.close)\n \n aboutAction = QtGui.QAction(u'关于', self)\n aboutAction.triggered.connect(self.openAbout)\n \n colorAction = QtGui.QAction(u'变色', self)\n colorAction.triggered.connect(self.changeColor)\n \n # 创建菜单\n menubar = self.menuBar()\n \n # 设计为只显示存在的接口\n sysMenu = menubar.addMenu(u'系统')\n if 'quantos' in self.mainEngine.gatewayDict:\n sysMenu.addAction(connectQuantOSAction)\n sysMenu.addSeparator()\n sysMenu.addAction(exitAction)\n \n # 帮助\n helpMenu = menubar.addMenu(u'帮助')\n helpMenu.addAction(aboutAction)\n helpMenu.addAction(colorAction)\n \n #----------------------------------------------------------------------\n def initStatusBar(self):\n \"\"\"初始化状态栏\"\"\"\n self.statusLabel = QtGui.QLabel()\n self.statusLabel.setAlignment(QtCore.Qt.AlignLeft)\n \n self.statusBar().addPermanentWidget(self.statusLabel)\n self.statusLabel.setText(self.getCpuMemory())\n \n self.sbCount = 0\n self.sbTrigger = 10 # 10秒刷新一次\n self.signalStatusBar.connect(self.updateStatusBar)\n self.eventEngine.register(EVENT_TIMER, self.signalStatusBar.emit)\n \n #----------------------------------------------------------------------\n def updateStatusBar(self, event):\n \"\"\"在状态栏更新CPU和内存信息\"\"\"\n self.sbCount += 1\n \n if self.sbCount == self.sbTrigger:\n self.sbCount = 0\n self.statusLabel.setText(self.getCpuMemory())\n \n #----------------------------------------------------------------------\n def getCpuMemory(self):\n \"\"\"获取CPU和内存状态信息\"\"\"\n cpuPercent = psutil.cpu_percent()\n memoryPercent = psutil.virtual_memory().percent\n return u'CPU使用率:%d%% 内存使用率:%d%%' % (cpuPercent, memoryPercent) \n \n #----------------------------------------------------------------------\n def connectQuantOS(self):\n self.mainEngine.connect('quantos') \n \n #----------------------------------------------------------------------\n def openAbout(self):\n \"\"\"打开关于\"\"\"\n try:\n self.widgetDict['aboutW'].show()\n except KeyError:\n self.widgetDict['aboutW'] = AboutWidget(self)\n self.widgetDict['aboutW'].show()\n \n #----------------------------------------------------------------------\n def closeEvent(self, event):\n \"\"\"关闭事件\"\"\"\n reply = QtGui.QMessageBox.question(self, u'退出',\n u'确认退出?', QtGui.QMessageBox.Yes | \n QtGui.QMessageBox.No, QtGui.QMessageBox.No)\n\n if reply == QtGui.QMessageBox.Yes: \n for widget in list(self.widgetDict.values()):\n widget.close()\n \n self.mainEngine.exit()\n event.accept()\n else:\n event.ignore()\n \n #----------------------------------------------------------------------\n def createDock(self, widgetClass, widgetName, widgetArea):\n \"\"\"创建停靠组件\"\"\"\n widget = widgetClass(self.mainEngine, self.eventEngine)\n dock = QtGui.QDockWidget(widgetName)\n dock.setWidget(widget)\n dock.setObjectName(widgetName)\n dock.setFeatures(dock.DockWidgetFloatable|dock.DockWidgetMovable)\n self.addDockWidget(widgetArea, dock)\n return widget, dock\n \n def changeColor(self):\n self.app.setStyleSheet(self.sheets[1])\n self.sheets = [self.sheets[1], self.sheets[0]]\n\n########################################################################\nclass AboutWidget(QtGui.QDialog):\n \"\"\"显示关于信息\"\"\"\n\n #----------------------------------------------------------------------\n def __init__(self, parent=None):\n \"\"\"Constructor\"\"\"\n super(AboutWidget, self).__init__(parent)\n\n self.initUi()\n\n #----------------------------------------------------------------------\n def initUi(self):\n \"\"\"\"\"\"\n self.setWindowTitle(u'关于VnTrader')\n\n text = u\"\"\"\n quantos trade client\n \"\"\"\n\n label = QtGui.QLabel()\n label.setText(text)\n label.setMinimumWidth(500)\n\n vbox = QtGui.QVBoxLayout()\n vbox.addWidget(label)\n\n self.setLayout(vbox)\n ","sub_path":"vnTrader/uiMainWindow.py","file_name":"uiMainWindow.py","file_ext":"py","file_size_in_byte":7835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"584370836","text":"from .base import Trainer\nfrom ..utils import logger\nimport tensorflow as tf\n\n\nclass GPUMixin(Trainer):\n def _setup(self):\n ctx = None\n try:\n import pycuda.driver as pd\n import pycuda.tools as pt\n pd.init()\n ctx = pt.make_default_context()\n except:\n pass\n\n try:\n super()._setup()\n finally:\n if ctx is not None:\n ctx.detach()\n\n\nclass NoGraphSummaryMixin(Trainer):\n def _setup(self):\n super()._setup()\n\n def _create_summary_writer(self):\n if not hasattr(logger, 'LOG_DIR'):\n raise RuntimeError(\n \"Please use logger.set_logger_dir at the beginning of your script.\")\n return tf.train.SummaryWriter(logger.LOG_DIR, graph=None)\n\n","sub_path":"tensorpack/train/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"313816369","text":"from django.urls import path\nfrom . import views\n\n\"\"\" Url Pattern for root URL Pattern \"\"\"\nurlpatterns = [\n path('', views.homePage, name=\"homePage\"),\n path('category/', views.categoryQuestion, name='categoryQuestion'),\n path('question/', views.QuestionDetails, name='QuestionDetails'),\n path('save-comment', views.SaveComment, name=\"SaveComment\"),\n path('user-registration', views.userRegistration, name=\"userRegistration\"),\n path('user-login', views.userLogin, name=\"userLogin\"),\n path('user-profile', views.userProfile, name=\"userProfile\"),\n path('post-question', views.postQuestion, name=\"postQuestion\")\n]","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"256767976","text":"import datetime\nimport uuid\n\nfrom app import app\nimport os\nimport math\n\nfrom shopyoapi.init import db\nfrom modules.box__ecommerce.category.upload import add_uncategorised_category\nfrom modules.box__ecommerce.category.upload import add_some_category\nfrom modules.box__ecommerce.product.models import Product\nfrom modules.box__ecommerce.category.models import SubCategory\nfrom modules.box__ecommerce.store.models import Store\nfrom modules.box__default.admin.models import User\nfrom shopyoapi.uploads import add_non_admin\nfrom shopyoapi.file import trycopy\nfrom shopyoapi.path import static_path\nfrom .factories import StoreFactory\nfrom .factories import ProductFactory\nfrom .factories import CategoryFactory\nfrom .factories import SubCategoryFactory\n\n\ndef upload_dummy_store_with_products2():\n with app.app_context():\n\n subcategories = SubCategory.query.all()\n stores = StoreFactory.create_batch(10)\n\n for subcategory in subcategories:\n products = ProductFactory.create_batch(33)\n subcategory.products = products\n prod_per_store = int((len(products) / len(stores)))\n subcategory.save(commit=False)\n\n for i in range(len(stores)):\n\n if stores[i].products is None:\n stores[i].products = []\n\n k = i * prod_per_store\n\n if i == (len(stores) - 1):\n stores[i].products.extend(products[k:])\n else:\n stores[i].products.extend(products[k: k + prod_per_store])\n stores[i].save(commit=False)\n\n db.session.commit()\n\n\ndef upload_dummy_store_with_products():\n with app.app_context():\n p1 = Product(\n barcode=str(uuid.uuid1()),\n price=10.0,\n name=\"Apple\",\n in_stock=50,\n selling_price=15.0,\n discontinued=False,\n description=\"\",\n is_featured=True\n )\n p2 = Product(\n barcode=str(uuid.uuid1()),\n price=10.0,\n name=\"Pear\",\n in_stock=50,\n selling_price=15.0,\n discontinued=False,\n description=\"\",\n )\n p3 = Product(\n barcode=str(uuid.uuid1()),\n price=10.0,\n name=\"Peach\",\n in_stock=50,\n selling_price=15.0,\n discontinued=False,\n description=\"\",\n )\n\n sub_uncateg = SubCategory.query.filter(SubCategory.name == 'uncategorised').first()\n p1.subcategory = sub_uncateg\n p1.set_status_approved()\n p2.subcategory = sub_uncateg\n p2.set_status_approved()\n p3.subcategory = sub_uncateg\n p3.set_status_approved()\n\n store1_logo = 's1_marketflow_logo.png'\n store1_banner = 's1_marketflow_banner.png'\n store = Store(\n name='TM Shop',\n slug='tm-shop',\n brn='1234',\n location='Impasse La Roue, Bonne Mer',\n is_verified=True,\n owner_id_card='J1234',\n owner_address='Rue des fleurs, Moka',\n owner_phone='1234567',\n logo_filename=store1_logo,\n banner_filename=store1_banner,\n is_featured=True\n )\n trycopy(\n os.path.join(static_path, 'default', 'store', 'marketflow_logo.png'),\n os.path.join(static_path, 'uploads', 'store_logo_photos', store1_logo),\n )\n trycopy(\n os.path.join(static_path, 'default', 'store', 'marketflow_banner.png'),\n os.path.join(static_path, 'uploads', 'store_banner_photos', store1_banner),\n )\n add_non_admin('store@store.com', 'pass')\n dummy_owner = User.query.filter(User.email == 'store@store.com').first()\n dummy_owner.is_store_owner = True\n store.store_owner = dummy_owner\n store.products.extend([p1, p2, p3])\n store.save()\n\n store2_logo = 's2_marketflow_logo.png'\n store2_banner = 's2_marketflow_banner.png'\n store2 = Store(\n name='Talent Moris',\n slug='talent-moris',\n brn='123e4',\n location='Pamplemousses',\n is_verified=True,\n owner_id_card='J1234eee',\n owner_address='Rue des fleurs, Port Louis',\n owner_phone='1237777',\n logo_filename=store2_logo,\n banner_filename=store2_banner,\n is_featured=True\n )\n trycopy(\n os.path.join(static_path, 'default', 'store', 'marketflow_logo.png'),\n os.path.join(static_path, 'uploads', 'store_logo_photos', store2_logo),\n )\n trycopy(\n os.path.join(static_path, 'default', 'store', 'marketflow_banner.png'),\n os.path.join(static_path, 'uploads', 'store_banner_photos', store2_banner),\n )\n descrip = '''\nKick Start Package at : Rs 1500 monthly\nCollaborative working space located at Pamplemousses (close to Botanical garden)\nFree WIFI\nFree meeting spaces\nFree parking\nTalentmoris.com:\nOnline store as from MUR 4500 annually\nFree delivery\n\nShared Services at very affordable prices\nAdministrative & secretarial support: As from MUR 1200 per month\nTraining – Starting at MUR 1000 monthly\nCoaching\nBusiness mentoring\nProject management\nBusiness plan\nBusiness development\nLegal advice\nPrinting services\nRegular events\n '''.replace('\\n', '
')\n px = Product(\n barcode=str(uuid.uuid1()),\n price=4500,\n name=\"Startup Package\",\n in_stock=50,\n selling_price=4500,\n discontinued=False,\n description=descrip,\n is_featured=True\n )\n px.set_status_approved()\n px.subcategory = sub_uncateg\n add_non_admin('store@marketflow.com', 'pass')\n dummy_owner2 = User.query.filter(User.email == 'store@marketflow.com').first()\n dummy_owner2.is_store_owner = True\n store2.store_owner = dummy_owner2\n store2.products.extend([px])\n store2.save()\n\n\ndef upload():\n if app.config['DEBUG']:\n print('Uploading dummy store data ...')\n\n print(\"Adding category and subcategory uncategorised ...\")\n add_uncategorised_category()\n # print('Adding some more category ...')\n # add_some_category()\n print('Adding dummy store with products ...')\n upload_dummy_store_with_products2()\n","sub_path":"modules/box__ecommerce/store/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":6490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"465467607","text":"from DES.module import *\n\ndef main():\n key = \"\"\n user = \" \"\n while len(key) != 8:\n key = input(\"Enter a 8 character key: \")\n if len(key) != 8:\n print(\"Key needs to be 8 Characters, try again\")\n\n # Intializes Cipher with DES_ECB\n cipher = createDES_ECB(key)\n\n\t# Determining which IP address and Port to connect to\n ip = input(\"Enter Server IP Address: \")\n port = int(input(\"Enter Server Port: \"))\n server_address = declareAddress(ip, port)\n sock = declareSocket()\n\n # Choose if user is client or server\n while user != \"CLIENT\" and user != \"SERVER\":\n user = input(\"Are you the server or client?\")\n user = user.upper()\n print(user)\n\n # Divides tasks of the Server and Client and executes based on previous choice\n if user == \"SERVER\":\n bindSocket(server_address, sock)\n serverSide(sock, cipher)\n if user == \"CLIENT\":\n connectSocket(server_address, sock)\n clientSide(sock, cipher)\nmain()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"52486795","text":"from sqlalchemy import (MetaData, Table, Column, Integer, Numeric, String,\n DateTime, ForeignKey, create_engine, insert)\nfrom A5CompleteCode import cookies, users, orders, line_items\n\nmetadata = MetaData()\nengine = create_engine('postgresql+psycopg2://@localhost:' '5432/mydb')\nconnection = engine.connect()\nprint(engine.table_names())\nmetadata =MetaData()\n#inserting order1\nins1 = insert(orders).values(user_id=1, order_id=1)\nresult = connection.execute(ins1)\nins2 = insert(line_items)\norder_items1 = [\n {\n 'order_id': 1,\n 'cookie_id': 1,\n 'quantity': 2,\n 'extended_cost': 1.00\n },\n {\n 'order_id': 1,\n 'cookie_id': 3,\n 'quantity': 12,\n 'extended_cost': 3.00\n }\n]\nresult = connection.execute(ins2, order_items1)\n\n\n#inserting Order2\nins3 = insert(orders).values(user_id=2, order_id=2)\nresult = connection.execute(ins3)\nins4 = insert(line_items)\norder_items2 = [\n {\n 'order_id': 2,\n 'cookie_id': 1,\n 'quantity': 24,\n 'extended_cost': 12.00\n },\n {\n 'order_id': 2,\n 'cookie_id': 4,\n 'quantity': 6,\n 'extended_cost': 6.00\n }\n]\nresult = connection.execute(ins4, order_items2)\n","sub_path":"SqlAlchemy/B1InsertingData3.py","file_name":"B1InsertingData3.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"511103257","text":"#!/usr/bin/python\n\n# import flask\nfrom flask import Flask, jsonify, request, redirect, url_for, send_from_directory\n\nimport keras\nfrom keras.models import load_model\nimport numpy as np\n\n# Setup Flask app.\napp = Flask(__name__)\napp.debug = True\n\ndef sample(preds, temperature=1.0):\n # helper function to sample an index from a probability array\n preds = np.asarray(preds).astype('float64')\n preds = np.log(preds) / temperature\n exp_preds = np.exp(preds)\n preds = exp_preds / np.sum(exp_preds)\n probas = np.random.multinomial(1, preds, 1)\n return np.argmax(probas)\n\nmodel = load_model('model.h5')\n\nmaxlen = 40\ntext = open('hamlet.txt').read().lower() # read the file and convert to lowercase\nchars = sorted(list(set(text)))\n# what position does each character exist at in the prev list\nchar_indices = dict((c,i) for i, c in enumerate(chars))\nindices_char = dict((i,c) for i,c in enumerate(chars))\n\n\n# Routes\n@app.route('/')\ndef root():\n return app.send_static_file('index.html')\n\n# All static files\n@app.route('/')\ndef static_proxy(path):\n # send_static_file will guess the correct MIME type\n return app.send_static_file(path)\n\n## Also now a post request to receive a file\n@app.route('/upload', methods=['POST'])\ndef upload():\n sentence = request.form['seed']\n print(sentence)\n # sentence = 'ince of denmark hamlet prince of denmark'\n diversity = float(request.form['temperature'])\n length = int(request.form['length'])\n generated = ''\n # generated += sentence\n for i in range(length):\n x = np.zeros((1, maxlen, len(chars)))\n for t, char in enumerate(sentence):\n x[0, t, char_indices[char]] = 1.\n preds = model.predict(x, verbose=0)[0]\n next_index = sample(preds, diversity)\n next_char = indices_char[next_index]\n generated += next_char\n sentence = sentence[1:] + next_char\n return jsonify(status='success',sentence=generated);\n\n# Run app:\nif __name__ == '__main__':\n# app.run( host='0.0.0.0', port=8080, debug=True )\n app.run( host='0.0.0.0', port=8080, debug=False )\n","sub_path":"week5-cnn-rnn-tensorflow/04b_rnn_flask_js/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"402813651","text":"from _Framework.ControlSurfaceComponent import ControlSurfaceComponent\nfrom _Framework.SubjectSlot import subject_slot\n\nclass MetronomeComponent(ControlSurfaceComponent):\n \"\"\"\n Show metronome beat readout\n \"\"\"\n\n def __init__(self, *a, **k):\n super(MetronomeComponent, self).__init__(*a, **k)\n self._lights = None\n self._beat = None\n self._on_time.subject = self.song()\n\n def set_lights(self, controls):\n self._lights = controls\n self.update()\n\n @subject_slot('current_song_time')\n def _on_time(self):\n if not self.is_enabled() or not self._lights:\n self._beat = None\n return\n beats = self.song().get_current_beats_song_time()\n if beats.beats != self._beat:\n self._beat = (beats.beats - 1) % len(self._lights)\n self.update()\n\n def update(self):\n if not self._lights or not self.is_enabled():\n return\n for idx, c in enumerate(self._lights):\n if self._beat is not idx:\n c.set_light('Metronome.Background')\n else:\n c.set_light('Metronome.Beat')\n\n","sub_path":"bvalosek_common/MetronomeComponent.py","file_name":"MetronomeComponent.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"199815062","text":"# Summation of primes\n# Problem 10\n\n# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.\n\n# Find the sum of all the primes below two million.\n\n# import genprimes\n\nimport math\n\n# def p010():\n# primes = genprimes.genPrimes()\n# next_prime = next(primes)\n# s = 0\n# while next_prime < 2 * 10 ** 6:\n# s += next_prime\n# next_prime = next(primes)\n# return s\n\ntwo_mil = 2 * 10 ** 6\n\nupper_limit = int(math.sqrt(two_mil))\n\narray = [True] * two_mil\narray[0] = False\narray[1] = False\n\ni = 2\nwhile i < two_mil:\n if array[i] == False:\n continue\n j = i ** 2\n while j < two_mil:\n array[j] = False\n j += i\n i += 1\n\nprint('almost done')\n\nprint(sum(array))\n\n\n\n# import Math.NumberTheory.Primes\n\n# problem10 :: Integer\n# problem10 = sum $ takeWhile (< 2 * 10^6) primes\n\n# main = print problem10\n","sub_path":"python/p010.py","file_name":"p010.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"} +{"seq_id":"566702872","text":"# Copyright (c) 2016 Baidu, Inc. All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom paddle.trainer.PyDataProvider2 import *\n\n\ndef meta_to_header(meta, name):\n metas = meta[name]['__meta__']['raw_meta']\n for each_meta in metas:\n if each_meta['type'] == 'id':\n yield integer_value(each_meta['max'])\n elif each_meta['type'] == 'embedding':\n is_seq = each_meta['seq'] == 'sequence'\n yield integer_value(len(each_meta['dict']),\n seq_type=SequenceType.SEQUENCE if is_seq\n else SequenceType.NO_SEQUENCE)\n elif each_meta['type'] == 'one_hot_dense':\n yield dense_vector(len(each_meta['dict']))\n","sub_path":"baidu/Paddle/demo/recommendation/common_utils.py","file_name":"common_utils.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"32"}